Page MenuHomeFreeBSD

No OneTemporary

This file is larger than 256 KB, so syntax highlighting was skipped.
diff --git a/crypto/openssl/CHANGES.md b/crypto/openssl/CHANGES.md
index bd876eb89dd4..19e0fd6e25a5 100644
--- a/crypto/openssl/CHANGES.md
+++ b/crypto/openssl/CHANGES.md
@@ -1,20014 +1,20083 @@
OpenSSL CHANGES
===============
This is a high-level summary of the most important changes.
For a full list of changes, see the [git commit log][log] and
pick the appropriate release branch.
[log]: https://github.com/openssl/openssl/commits/
OpenSSL Releases
----------------
- [OpenSSL 3.0](#openssl-30)
- [OpenSSL 1.1.1](#openssl-111)
- [OpenSSL 1.1.0](#openssl-110)
- [OpenSSL 1.0.2](#openssl-102)
- [OpenSSL 1.0.1](#openssl-101)
- [OpenSSL 1.0.0](#openssl-100)
- [OpenSSL 0.9.x](#openssl-09x)
OpenSSL 3.0
-----------
For OpenSSL 3.0 a [Migration guide][] has been added, so the CHANGES entries
listed here are only a brief description.
The migration guide contains more detailed information related to new features,
breaking changes, and mappings for the large list of deprecated functions.
[Migration guide]: https://github.com/openssl/openssl/tree/master/doc/man7/migration_guide.pod
+### Changes between 3.0.13 and 3.0.14 [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*
+
+ * 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*
+
+ * New atexit configuration switch, which controls whether the OPENSSL_cleanup
+ is registered when libcrypto is unloaded. This can be used on platforms
+ where using atexit() from shared libraries causes crashes on exit.
+
+ *Randall S. Becker*
+
### Changes between 3.0.12 and 3.0.13 [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*
* 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*
### Changes between 3.0.11 and 3.0.12 [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.0.10 and 3.0.11 [19 Sep 2023]
* Fix POLY1305 MAC implementation corrupting XMM registers on Windows.
The POLY1305 MAC (message authentication code) implementation in OpenSSL
does not save the contents of non-volatile XMM registers on Windows 64
platform when calculating the MAC of data larger than 64 bytes. Before
returning to the caller all the XMM registers are set to zero rather than
restoring their previous content. The vulnerable code is used only on newer
x86_64 processors supporting the AVX512-IFMA instructions.
The consequences of this kind of internal application state corruption can
be various - from no consequences, if the calling application does not
depend on the contents of non-volatile XMM registers at all, to the worst
consequences, where the attacker could get complete control of the
application process. However given the contents of the registers are just
zeroized so the attacker cannot put arbitrary values inside, the most likely
consequence, if any, would be an incorrect result of some application
dependent calculations or a crash leading to a denial of service.
([CVE-2023-4807])
*Bernd Edlinger*
### Changes between 3.0.9 and 3.0.10 [1 Aug 2023]
* Fix excessive time spent checking DH q parameter value.
The function DH_check() performs various checks on DH parameters. After
fixing CVE-2023-3446 it was discovered that a large q parameter value can
also trigger an overly long computation during some of these checks.
A correct q value, if present, cannot be larger than the modulus p
parameter, thus it is unnecessary to perform these checks if q is larger
than p.
If DH_check() is called with such q parameter value,
DH_CHECK_INVALID_Q_VALUE return flag is set and the computationally
intensive checks are skipped.
([CVE-2023-3817])
*Tomáš Mráz*
* Fix DH_check() excessive time with over sized modulus.
The function DH_check() performs various checks on DH parameters. One of
those checks confirms that the modulus ("p" parameter) is not too large.
Trying to use a very large modulus is slow and OpenSSL will not normally use
a modulus which is over 10,000 bits in length.
However the DH_check() function checks numerous aspects of the key or
parameters that have been supplied. Some of those checks use the supplied
modulus value even if it has already been found to be too large.
A new limit has been added to DH_check of 32,768 bits. Supplying a
key/parameters with a modulus over this size will simply cause DH_check() to
fail.
([CVE-2023-3446])
*Matt Caswell*
* Do not ignore empty associated data entries with AES-SIV.
The AES-SIV algorithm allows for authentication of multiple associated
data entries along with the encryption. To authenticate empty data the
application has to call `EVP_EncryptUpdate()` (or `EVP_CipherUpdate()`)
with NULL pointer as the output buffer and 0 as the input buffer length.
The AES-SIV implementation in OpenSSL just returns success for such call
instead of performing the associated data authentication operation.
The empty data thus will not be authenticated. ([CVE-2023-2975])
Thanks to Juerg Wullschleger (Google) for discovering the issue.
The fix changes the authentication tag value and the ciphertext for
applications that use empty associated data entries with AES-SIV.
To decrypt data encrypted with previous versions of OpenSSL the application
has to skip calls to `EVP_DecryptUpdate()` for empty associated data
entries.
*Tomáš Mráz*
### Changes between 3.0.8 and 3.0.9 [30 May 2023]
* Mitigate for the time it takes for `OBJ_obj2txt` to translate gigantic
OBJECT IDENTIFIER sub-identifiers to canonical numeric text form.
OBJ_obj2txt() would translate any size OBJECT IDENTIFIER to canonical
numeric text form. For gigantic sub-identifiers, this would take a very
long time, the time complexity being O(n^2) where n is the size of that
sub-identifier. ([CVE-2023-2650])
To mitigitate this, `OBJ_obj2txt()` will only translate an OBJECT
IDENTIFIER to canonical numeric text form if the size of that OBJECT
IDENTIFIER is 586 bytes or less, and fail otherwise.
The basis for this restriction is [RFC 2578 (STD 58), section 3.5]. OBJECT
IDENTIFIER values, which stipulates that OBJECT IDENTIFIERS may have at
most 128 sub-identifiers, and that the maximum value that each sub-
identifier may have is 2^32-1 (4294967295 decimal).
For each byte of every sub-identifier, only the 7 lower bits are part of
the value, so the maximum amount of bytes that an OBJECT IDENTIFIER with
these restrictions may occupy is 32 * 128 / 7, which is approximately 586
bytes.
*Richard Levitte*
* Fixed buffer overread in AES-XTS decryption on ARM 64 bit platforms which
happens if the buffer size is 4 mod 5 in 16 byte AES blocks. This can
trigger a crash of an application using AES-XTS decryption if the memory
just after the buffer being decrypted is not mapped.
Thanks to Anton Romanov (Amazon) for discovering the issue.
([CVE-2023-1255])
*Nevine Ebeid*
* Reworked the Fix for the Timing Oracle in RSA Decryption ([CVE-2022-4304]).
The previous fix for this timing side channel turned out to cause
a severe 2-3x performance regression in the typical use case
compared to 3.0.7. The new fix uses existing constant time
code paths, and restores the previous performance level while
fully eliminating all existing timing side channels.
The fix was developed by Bernd Edlinger with testing support
by Hubert Kario.
*Bernd Edlinger*
* Corrected documentation of X509_VERIFY_PARAM_add0_policy() to mention
that it does not enable policy checking. Thanks to David Benjamin for
discovering this issue.
([CVE-2023-0466])
*Tomáš Mráz*
* Fixed an issue where invalid certificate policies in leaf certificates are
silently ignored by OpenSSL and other certificate policy checks are skipped
for that certificate. A malicious CA could use this to deliberately assert
invalid certificate policies in order to circumvent policy checking on the
certificate altogether.
([CVE-2023-0465])
*Matt Caswell*
* Limited the number of nodes created in a policy tree to mitigate
against CVE-2023-0464. The default limit is set to 1000 nodes, which
should be sufficient for most installations. If required, the limit
can be adjusted by setting the OPENSSL_POLICY_TREE_NODES_MAX build
time define to a desired maximum number of nodes or zero to allow
unlimited growth.
([CVE-2023-0464])
*Paul Dale*
### Changes between 3.0.7 and 3.0.8 [7 Feb 2023]
* Fixed NULL dereference during PKCS7 data verification.
A NULL pointer can be dereferenced when signatures are being
verified on PKCS7 signed or signedAndEnveloped data. In case the hash
algorithm used for the signature is known to the OpenSSL library but
the implementation of the hash algorithm is not available the digest
initialization will fail. There is a missing check for the return
value from the initialization function which later leads to invalid
usage of the digest API most likely leading to a crash.
([CVE-2023-0401])
PKCS7 data is processed by the SMIME library calls and also by the
time stamp (TS) library calls. The TLS implementation in OpenSSL does
not call these functions however third party applications would be
affected if they call these functions to verify signatures on untrusted
data.
*Tomáš Mráz*
* Fixed X.400 address type confusion in X.509 GeneralName.
There is a type confusion vulnerability relating to X.400 address processing
inside an X.509 GeneralName. X.400 addresses were parsed as an ASN1_STRING
but the public structure definition for GENERAL_NAME incorrectly specified
the type of the x400Address field as ASN1_TYPE. This field is subsequently
interpreted by the OpenSSL function GENERAL_NAME_cmp as an ASN1_TYPE rather
than an ASN1_STRING.
When CRL checking is enabled (i.e. the application sets the
X509_V_FLAG_CRL_CHECK flag), this vulnerability may allow an attacker to
pass arbitrary pointers to a memcmp call, enabling them to read memory
contents or enact a denial of service.
([CVE-2023-0286])
*Hugo Landau*
* Fixed NULL dereference validating DSA public key.
An invalid pointer dereference on read can be triggered when an
application tries to check a malformed DSA public key by the
EVP_PKEY_public_check() function. This will most likely lead
to an application crash. This function can be called on public
keys supplied from untrusted sources which could allow an attacker
to cause a denial of service attack.
The TLS implementation in OpenSSL does not call this function
but applications might call the function if there are additional
security requirements imposed by standards such as FIPS 140-3.
([CVE-2023-0217])
*Shane Lontis, Tomáš Mráz*
* Fixed Invalid pointer dereference in d2i_PKCS7 functions.
An invalid pointer dereference on read can be triggered when an
application tries to load malformed PKCS7 data with the
d2i_PKCS7(), d2i_PKCS7_bio() or d2i_PKCS7_fp() functions.
The result of the dereference is an application crash which could
lead to a denial of service attack. The TLS implementation in OpenSSL
does not call this function however third party applications might
call these functions on untrusted data.
([CVE-2023-0216])
*Tomáš Mráz*
* Fixed Use-after-free following BIO_new_NDEF.
The public API function BIO_new_NDEF is a helper function used for
streaming ASN.1 data via a BIO. It is primarily used internally to OpenSSL
to support the SMIME, CMS and PKCS7 streaming capabilities, but may also
be called directly by end user applications.
The function receives a BIO from the caller, prepends a new BIO_f_asn1
filter BIO onto the front of it to form a BIO chain, and then returns
the new head of the BIO chain to the caller. Under certain conditions,
for example if a CMS recipient public key is invalid, the new filter BIO
is freed and the function returns a NULL result indicating a failure.
However, in this case, the BIO chain is not properly cleaned up and the
BIO passed by the caller still retains internal pointers to the previously
freed filter BIO. If the caller then goes on to call BIO_pop() on the BIO
then a use-after-free will occur. This will most likely result in a crash.
([CVE-2023-0215])
*Viktor Dukhovni, Matt Caswell*
* Fixed Double free after calling PEM_read_bio_ex.
The function PEM_read_bio_ex() reads a PEM file from a BIO and parses and
decodes the "name" (e.g. "CERTIFICATE"), any header data and the payload
data. If the function succeeds then the "name_out", "header" and "data"
arguments are populated with pointers to buffers containing the relevant
decoded data. The caller is responsible for freeing those buffers. It is
possible to construct a PEM file that results in 0 bytes of payload data.
In this case PEM_read_bio_ex() will return a failure code but will populate
the header argument with a pointer to a buffer that has already been freed.
If the caller also frees this buffer then a double free will occur. This
will most likely lead to a crash.
The functions PEM_read_bio() and PEM_read() are simple wrappers around
PEM_read_bio_ex() and therefore these functions are also directly affected.
These functions are also called indirectly by a number of other OpenSSL
functions including PEM_X509_INFO_read_bio_ex() and
SSL_CTX_use_serverinfo_file() which are also vulnerable. Some OpenSSL
internal uses of these functions are not vulnerable because the caller does
not free the header argument if PEM_read_bio_ex() returns a failure code.
([CVE-2022-4450])
*Kurt Roeckx, Matt Caswell*
* Fixed Timing Oracle in RSA Decryption.
A timing based side channel exists in the OpenSSL RSA Decryption
implementation which could be sufficient to recover a plaintext across
a network in a Bleichenbacher style attack. To achieve a successful
decryption an attacker would have to be able to send a very large number
of trial messages for decryption. The vulnerability affects all RSA padding
modes: PKCS#1 v1.5, RSA-OEAP and RSASVE.
([CVE-2022-4304])
*Dmitry Belyavsky, Hubert Kario*
* Fixed X.509 Name Constraints Read Buffer Overflow.
A read buffer overrun can be triggered in X.509 certificate verification,
specifically in name constraint checking. The read buffer overrun might
result in a crash which could lead to a denial of service attack.
In a TLS client, this can be triggered by connecting to a malicious
server. In a TLS server, this can be triggered if the server requests
client authentication and a malicious client connects.
([CVE-2022-4203])
*Viktor Dukhovni*
* Fixed X.509 Policy Constraints Double Locking security issue.
If an X.509 certificate contains a malformed policy constraint and
policy processing is enabled, then a write lock will be taken twice
recursively. On some operating systems (most widely: Windows) this
results in a denial of service when the affected process hangs. Policy
processing being enabled on a publicly facing server is not considered
to be a common setup.
([CVE-2022-3996])
*Paul Dale*
* Our provider implementations of `OSSL_FUNC_KEYMGMT_EXPORT` and
`OSSL_FUNC_KEYMGMT_GET_PARAMS` for EC and SM2 keys now honor
`OSSL_PKEY_PARAM_EC_POINT_CONVERSION_FORMAT` as set (and
default to `POINT_CONVERSION_UNCOMPRESSED`) when exporting
`OSSL_PKEY_PARAM_PUB_KEY`, instead of unconditionally using
`POINT_CONVERSION_COMPRESSED` as in previous 3.x releases.
For symmetry, our implementation of `EVP_PKEY_ASN1_METHOD->export_to`
for legacy EC and SM2 keys is also changed similarly to honor the
equivalent conversion format flag as specified in the underlying
`EC_KEY` object being exported to a provider, when this function is
called through `EVP_PKEY_export()`.
*Nicola Tuveri*
### Changes between 3.0.6 and 3.0.7 [1 Nov 2022]
* Fixed two buffer overflows in punycode decoding functions.
A buffer overrun can be triggered in X.509 certificate verification,
specifically in name constraint checking. Note that this occurs after
certificate chain signature verification and requires either a CA to
have signed the malicious certificate or for the application to continue
certificate verification despite failure to construct a path to a trusted
issuer.
In a TLS client, this can be triggered by connecting to a malicious
server. In a TLS server, this can be triggered if the server requests
client authentication and a malicious client connects.
An attacker can craft a malicious email address to overflow
an arbitrary number of bytes containing the `.` character (decimal 46)
on the stack. This buffer overflow could result in a crash (causing a
denial of service).
([CVE-2022-3786])
An attacker can craft a malicious email address to overflow four
attacker-controlled bytes on the stack. This buffer overflow could
result in a crash (causing a denial of service) or potentially remote code
execution depending on stack layout for any given platform/compiler.
([CVE-2022-3602])
*Paul Dale*
* Removed all references to invalid OSSL_PKEY_PARAM_RSA names for CRT
parameters in OpenSSL code.
Applications should not use the names OSSL_PKEY_PARAM_RSA_FACTOR,
OSSL_PKEY_PARAM_RSA_EXPONENT and OSSL_PKEY_PARAM_RSA_COEFFICIENT.
Use the numbered names such as OSSL_PKEY_PARAM_RSA_FACTOR1 instead.
Using these invalid names may cause algorithms to use slower methods
that ignore the CRT parameters.
*Shane Lontis*
* Fixed a regression introduced in 3.0.6 version raising errors on some stack
operations.
*Tomáš Mráz*
* Fixed a regression introduced in 3.0.6 version not refreshing the certificate
data to be signed before signing the certificate.
*Gibeom Gwon*
* Added RIPEMD160 to the default provider.
*Paul Dale*
* Ensured that the key share group sent or accepted for the key exchange
is allowed for the protocol version.
*Matt Caswell*
### Changes between 3.0.5 and 3.0.6 [11 Oct 2022]
* OpenSSL supports creating a custom cipher via the legacy
EVP_CIPHER_meth_new() function and associated function calls. This function
was deprecated in OpenSSL 3.0 and application authors are instead encouraged
to use the new provider mechanism in order to implement custom ciphers.
OpenSSL versions 3.0.0 to 3.0.5 incorrectly handle legacy custom ciphers
passed to the EVP_EncryptInit_ex2(), EVP_DecryptInit_ex2() and
EVP_CipherInit_ex2() functions (as well as other similarly named encryption
and decryption initialisation functions). Instead of using the custom cipher
directly it incorrectly tries to fetch an equivalent cipher from the
available providers. An equivalent cipher is found based on the NID passed to
EVP_CIPHER_meth_new(). This NID is supposed to represent the unique NID for a
given cipher. However it is possible for an application to incorrectly pass
NID_undef as this value in the call to EVP_CIPHER_meth_new(). When NID_undef
is used in this way the OpenSSL encryption/decryption initialisation function
will match the NULL cipher as being equivalent and will fetch this from the
available providers. This will succeed if the default provider has been
loaded (or if a third party provider has been loaded that offers this
cipher). Using the NULL cipher means that the plaintext is emitted as the
ciphertext.
Applications are only affected by this issue if they call
EVP_CIPHER_meth_new() using NID_undef and subsequently use it in a call to an
encryption/decryption initialisation function. Applications that only use
SSL/TLS are not impacted by this issue.
([CVE-2022-3358])
*Matt Caswell*
* Fix LLVM vs Apple LLVM version numbering confusion that caused build failures
on MacOS 10.11
*Richard Levitte*
* Fixed the linux-mips64 Configure target which was missing the
SIXTY_FOUR_BIT bn_ops flag. This was causing heap corruption on that
platform.
*Adam Joseph*
* Fix handling of a ticket key callback that returns 0 in TLSv1.3 to not send a
ticket
*Matt Caswell*
* Correctly handle a retransmitted ClientHello in DTLS
*Matt Caswell*
* Fixed detection of ktls support in cross-compile environment on Linux
*Tomas Mraz*
* Fixed some regressions and test failures when running the 3.0.0 FIPS provider
against 3.0.x
*Paul Dale*
* Fixed SSL_pending() and SSL_has_pending() with DTLS which were failing to
report correct results in some cases
*Matt Caswell*
* Fix UWP builds by defining VirtualLock
*Charles Milette*
* For known safe primes use the minimum key length according to RFC 7919.
Longer private key sizes unnecessarily raise the cycles needed to compute the
shared secret without any increase of the real security. This fixes a
regression from 1.1.1 where these shorter keys were generated for the known
safe primes.
*Tomas Mraz*
* Added the loongarch64 target
*Shi Pujin*
* Fixed EC ASM flag passing. Flags for ASM implementations of EC curves were
only passed to the FIPS provider and not to the default or legacy provider.
*Juergen Christ*
* Fixed reported performance degradation on aarch64. Restored the
implementation prior to commit 2621751 ("aes/asm/aesv8-armx.pl: avoid
32-bit lane assignment in CTR mode") for 64bit targets only, since it is
reportedly 2-17% slower and the silicon errata only affects 32bit targets.
The new algorithm is still used for 32 bit targets.
*Bernd Edlinger*
* Added a missing header for memcmp that caused compilation failure on some
platforms
*Gregor Jasny*
### Changes between 3.0.4 and 3.0.5 [5 Jul 2022]
* The OpenSSL 3.0.4 release introduced a serious bug in the RSA
implementation for X86_64 CPUs supporting the AVX512IFMA instructions.
This issue makes the RSA implementation with 2048 bit private keys
incorrect on such machines and memory corruption will happen during
the computation. As a consequence of the memory corruption an attacker
may be able to trigger a remote code execution on the machine performing
the computation.
SSL/TLS servers or other servers using 2048 bit RSA private keys running
on machines supporting AVX512IFMA instructions of the X86_64 architecture
are affected by this issue.
([CVE-2022-2274])
*Xi Ruoyao*
* AES OCB mode for 32-bit x86 platforms using the AES-NI assembly optimised
implementation would not encrypt the entirety of the data under some
circumstances. This could reveal sixteen bytes of data that was
preexisting in the memory that wasn't written. In the special case of
"in place" encryption, sixteen bytes of the plaintext would be revealed.
Since OpenSSL does not support OCB based cipher suites for TLS and DTLS,
they are both unaffected.
([CVE-2022-2097])
*Alex Chernyakhovsky, David Benjamin, Alejandro Sedeño*
### Changes between 3.0.3 and 3.0.4 [21 Jun 2022]
* In addition to the c_rehash shell command injection identified in
CVE-2022-1292, further bugs where the c_rehash script does not
properly sanitise shell metacharacters to prevent command injection have been
fixed.
When the CVE-2022-1292 was fixed it was not discovered that there
are other places in the script where the file names of certificates
being hashed were possibly passed to a command executed through the shell.
This script is distributed by some operating systems in a manner where
it is automatically executed. On such operating systems, an attacker
could execute arbitrary commands with the privileges of the script.
Use of the c_rehash script is considered obsolete and should be replaced
by the OpenSSL rehash command line tool.
(CVE-2022-2068)
*Daniel Fiala, Tomáš Mráz*
* Case insensitive string comparison no longer uses locales. It has instead
been directly implemented.
*Paul Dale*
### Changes between 3.0.2 and 3.0.3 [3 May 2022]
* Case insensitive string comparison is reimplemented via new locale-agnostic
comparison functions OPENSSL_str[n]casecmp always using the POSIX locale for
comparison. The previous implementation had problems when the Turkish locale
was used.
*Dmitry Belyavskiy*
* Fixed a bug in the c_rehash script which was not properly sanitising shell
metacharacters to prevent command injection. This script is distributed by
some operating systems in a manner where it is automatically executed. On
such operating systems, an attacker could execute arbitrary commands with the
privileges of the script.
Use of the c_rehash script is considered obsolete and should be replaced
by the OpenSSL rehash command line tool.
(CVE-2022-1292)
*Tomáš Mráz*
* Fixed a bug in the function `OCSP_basic_verify` that verifies the signer
certificate on an OCSP response. The bug caused the function in the case
where the (non-default) flag OCSP_NOCHECKS is used to return a postivie
response (meaning a successful verification) even in the case where the
response signing certificate fails to verify.
It is anticipated that most users of `OCSP_basic_verify` will not use the
OCSP_NOCHECKS flag. In this case the `OCSP_basic_verify` function will return
a negative value (indicating a fatal error) in the case of a certificate
verification failure. The normal expected return value in this case would be
0.
This issue also impacts the command line OpenSSL "ocsp" application. When
verifying an ocsp response with the "-no_cert_checks" option the command line
application will report that the verification is successful even though it
has in fact failed. In this case the incorrect successful response will also
be accompanied by error messages showing the failure and contradicting the
apparently successful result.
([CVE-2022-1343])
*Matt Caswell*
* Fixed a bug where the RC4-MD5 ciphersuite incorrectly used the
AAD data as the MAC key. This made the MAC key trivially predictable.
An attacker could exploit this issue by performing a man-in-the-middle attack
to modify data being sent from one endpoint to an OpenSSL 3.0 recipient such
that the modified data would still pass the MAC integrity check.
Note that data sent from an OpenSSL 3.0 endpoint to a non-OpenSSL 3.0
endpoint will always be rejected by the recipient and the connection will
fail at that point. Many application protocols require data to be sent from
the client to the server first. Therefore, in such a case, only an OpenSSL
3.0 server would be impacted when talking to a non-OpenSSL 3.0 client.
If both endpoints are OpenSSL 3.0 then the attacker could modify data being
sent in both directions. In this case both clients and servers could be
affected, regardless of the application protocol.
Note that in the absence of an attacker this bug means that an OpenSSL 3.0
endpoint communicating with a non-OpenSSL 3.0 endpoint will fail to complete
the handshake when using this ciphersuite.
The confidentiality of data is not impacted by this issue, i.e. an attacker
cannot decrypt data that has been encrypted using this ciphersuite - they can
only modify it.
In order for this attack to work both endpoints must legitimately negotiate
the RC4-MD5 ciphersuite. This ciphersuite is not compiled by default in
OpenSSL 3.0, and is not available within the default provider or the default
ciphersuite list. This ciphersuite will never be used if TLSv1.3 has been
negotiated. In order for an OpenSSL 3.0 endpoint to use this ciphersuite the
following must have occurred:
1) OpenSSL must have been compiled with the (non-default) compile time option
enable-weak-ssl-ciphers
2) OpenSSL must have had the legacy provider explicitly loaded (either
through application code or via configuration)
3) The ciphersuite must have been explicitly added to the ciphersuite list
4) The libssl security level must have been set to 0 (default is 1)
5) A version of SSL/TLS below TLSv1.3 must have been negotiated
6) Both endpoints must negotiate the RC4-MD5 ciphersuite in preference to any
others that both endpoints have in common
(CVE-2022-1434)
*Matt Caswell*
* Fix a bug in the OPENSSL_LH_flush() function that breaks reuse of the memory
occuppied by the removed hash table entries.
This function is used when decoding certificates or keys. If a long lived
process periodically decodes certificates or keys its memory usage will
expand without bounds and the process might be terminated by the operating
system causing a denial of service. Also traversing the empty hash table
entries will take increasingly more time.
Typically such long lived processes might be TLS clients or TLS servers
configured to accept client certificate authentication.
(CVE-2022-1473)
*Hugo Landau, Aliaksei Levin*
* The functions `OPENSSL_LH_stats` and `OPENSSL_LH_stats_bio` now only report
the `num_items`, `num_nodes` and `num_alloc_nodes` statistics. All other
statistics are no longer supported. For compatibility, these statistics are
still listed in the output but are now always reported as zero.
*Hugo Landau*
### Changes between 3.0.1 and 3.0.2 [15 Mar 2022]
* Fixed a bug in the BN_mod_sqrt() function that can cause it to loop forever
for non-prime moduli.
Internally this function is used when parsing certificates that contain
elliptic curve public keys in compressed form or explicit elliptic curve
parameters with a base point encoded in compressed form.
It is possible to trigger the infinite loop by crafting a certificate that
has invalid explicit curve parameters.
Since certificate parsing happens prior to verification of the certificate
signature, any process that parses an externally supplied certificate may thus
be subject to a denial of service attack. The infinite loop can also be
reached when parsing crafted private keys as they can contain explicit
elliptic curve parameters.
Thus vulnerable situations include:
- TLS clients consuming server certificates
- TLS servers consuming client certificates
- Hosting providers taking certificates or private keys from customers
- Certificate authorities parsing certification requests from subscribers
- Anything else which parses ASN.1 elliptic curve parameters
Also any other applications that use the BN_mod_sqrt() where the attacker
can control the parameter values are vulnerable to this DoS issue.
([CVE-2022-0778])
*Tomáš Mráz*
* Add ciphersuites based on DHE_PSK (RFC 4279) and ECDHE_PSK (RFC 5489)
to the list of ciphersuites providing Perfect Forward Secrecy as
required by SECLEVEL >= 3.
*Dmitry Belyavskiy, Nicola Tuveri*
* Made the AES constant time code for no-asm configurations
optional due to the resulting 95% performance degradation.
The AES constant time code can be enabled, for no assembly
builds, with: ./config no-asm -DOPENSSL_AES_CONST_TIME
*Paul Dale*
* Fixed PEM_write_bio_PKCS8PrivateKey() to make it possible to use empty
passphrase strings.
*Darshan Sen*
* The negative return value handling of the certificate verification callback
was reverted. The replacement is to set the verification retry state with
the SSL_set_retry_verify() function.
*Tomáš Mráz*
### Changes between 3.0.0 and 3.0.1 [14 Dec 2021]
* Fixed invalid handling of X509_verify_cert() internal errors in libssl
Internally libssl in OpenSSL calls X509_verify_cert() on the client side to
verify a certificate supplied by a server. That function may return a
negative return value to indicate an internal error (for example out of
memory). Such a negative return value is mishandled by OpenSSL and will cause
an IO function (such as SSL_connect() or SSL_do_handshake()) to not indicate
success and a subsequent call to SSL_get_error() to return the value
SSL_ERROR_WANT_RETRY_VERIFY. This return value is only supposed to be
returned by OpenSSL if the application has previously called
SSL_CTX_set_cert_verify_callback(). Since most applications do not do this
the SSL_ERROR_WANT_RETRY_VERIFY return value from SSL_get_error() will be
totally unexpected and applications may not behave correctly as a result. The
exact behaviour will depend on the application but it could result in
crashes, infinite loops or other similar incorrect responses.
This issue is made more serious in combination with a separate bug in OpenSSL
3.0 that will cause X509_verify_cert() to indicate an internal error when
processing a certificate chain. This will occur where a certificate does not
include the Subject Alternative Name extension but where a Certificate
Authority has enforced name constraints. This issue can occur even with valid
chains.
([CVE-2021-4044])
*Matt Caswell*
* Corrected a few file name and file reference bugs in the build,
installation and setup scripts, which lead to installation verification
failures. Slightly enhanced the installation verification script.
*Richard Levitte*
* Fixed EVP_PKEY_eq() to make it possible to use it with strictly private
keys.
*Richard Levitte*
* Fixed PVK encoder to properly query for the passphrase.
*Tomáš Mráz*
* Multiple fixes in the OSSL_HTTP API functions.
*David von Oheimb*
* Allow sign extension in OSSL_PARAM_allocate_from_text() for the
OSSL_PARAM_INTEGER data type and return error on negative numbers
used with the OSSL_PARAM_UNSIGNED_INTEGER data type. Make
OSSL_PARAM_BLD_push_BN{,_pad}() return an error on negative numbers.
*Richard Levitte*
* Allow copying uninitialized digest contexts with EVP_MD_CTX_copy_ex.
*Tomáš Mráz*
* Fixed detection of ARMv7 and ARM64 CPU features on FreeBSD.
*Allan Jude*
* Multiple threading fixes.
*Matt Caswell*
* Added NULL digest implementation to keep compatibility with 1.1.1 version.
*Tomáš Mráz*
* Allow fetching an operation from the provider that owns an unexportable key
as a fallback if that is still allowed by the property query.
*Richard Levitte*
### Changes between 1.1.1 and 3.0.0 [7 sep 2021]
* TLS_MAX_VERSION, DTLS_MAX_VERSION and DTLS_MIN_VERSION constants are now
deprecated.
*Matt Caswell*
* The `OPENSSL_s390xcap` environment variable can be used to set bits in the
S390X capability vector to zero. This simplifies testing of different code
paths on S390X architecture.
*Patrick Steuer*
* Encrypting more than 2^64 TLS records with AES-GCM is disallowed
as per FIPS 140-2 IG A.5 "Key/IV Pair Uniqueness Requirements from
SP 800-38D". The communication will fail at this point.
*Paul Dale*
* The EC_GROUP_clear_free() function is deprecated as there is nothing
confidential in EC_GROUP data.
*Nicola Tuveri*
* The byte order mark (BOM) character is ignored if encountered at the
beginning of a PEM-formatted file.
*Dmitry Belyavskiy*
* Added CMS support for the Russian GOST algorithms.
*Dmitry Belyavskiy*
* Due to move of the implementation of cryptographic operations
to the providers, validation of various operation parameters can
be postponed until the actual operation is executed where previously
it happened immediately when an operation parameter was set.
For example when setting an unsupported curve with
EVP_PKEY_CTX_set_ec_paramgen_curve_nid() this function call will not
fail but later keygen operations with the EVP_PKEY_CTX will fail.
*OpenSSL team members and many third party contributors*
* The EVP_get_cipherbyname() function will return NULL for algorithms such as
"AES-128-SIV", "AES-128-CBC-CTS" and "CAMELLIA-128-CBC-CTS" which were
previously only accessible via low level interfaces. Use EVP_CIPHER_fetch()
instead to retrieve these algorithms from a provider.
*Shane Lontis*
* On build targets where the multilib postfix is set in the build
configuration the libdir directory was changing based on whether
the lib directory with the multilib postfix exists on the system
or not. This unpredictable behavior was removed and eventual
multilib postfix is now always added to the default libdir. Use
`--libdir=lib` to override the libdir if adding the postfix is
undesirable.
*Jan Lána*
* The triple DES key wrap functionality now conforms to RFC 3217 but is
no longer interoperable with OpenSSL 1.1.1.
*Paul Dale*
* The ERR_GET_FUNC() function was removed. With the loss of meaningful
function codes, this function can only cause problems for calling
applications.
*Paul Dale*
* Add a configurable flag to output date formats as ISO 8601. Does not
change the default date format.
*William Edmisten*
* Version of MSVC earlier than 1300 could get link warnings, which could
be suppressed if the undocumented -DI_CAN_LIVE_WITH_LNK4049 was set.
Support for this flag has been removed.
*Rich Salz*
* Rework and make DEBUG macros consistent. Remove unused -DCONF_DEBUG,
-DBN_CTX_DEBUG, and REF_PRINT. Add a new tracing category and use it for
printing reference counts. Rename -DDEBUG_UNUSED to -DUNUSED_RESULT_DEBUG
Fix BN_DEBUG_RAND so it compiles and, when set, force DEBUG_RAND to be set
also. Rename engine_debug_ref to be ENGINE_REF_PRINT also for consistency.
*Rich Salz*
* The signatures of the functions to get and set options on SSL and
SSL_CTX objects changed from "unsigned long" to "uint64_t" type.
Some source code changes may be required.
*Rich Salz*
* The public definitions of conf_method_st and conf_st have been
deprecated. They will be made opaque in a future release.
*Rich Salz and Tomáš Mráz*
* Client-initiated renegotiation is disabled by default. To allow it, use
the -client_renegotiation option, the SSL_OP_ALLOW_CLIENT_RENEGOTIATION
flag, or the "ClientRenegotiation" config parameter as appropriate.
*Rich Salz*
* Add "abspath" and "includedir" pragma's to config files, to prevent,
or modify relative pathname inclusion.
*Rich Salz*
* OpenSSL includes a cryptographic module that is intended to be FIPS 140-2
validated. Please consult the README-FIPS and
README-PROVIDERS files, as well as the migration guide.
*OpenSSL team members and many third party contributors*
* For the key types DH and DHX the allowed settable parameters are now different.
*Shane Lontis*
* The openssl commands that read keys, certificates, and CRLs now
automatically detect the PEM or DER format of the input files.
*David von Oheimb, Richard Levitte, and Tomáš Mráz*
* Added enhanced PKCS#12 APIs which accept a library context.
*Jon Spillett*
* The default manual page suffix ($MANSUFFIX) has been changed to "ossl"
*Matt Caswell*
* Added support for Kernel TLS (KTLS).
*Boris Pismenny, John Baldwin and Andrew Gallatin*
* Support for RFC 5746 secure renegotiation is now required by default for
SSL or TLS connections to succeed.
*Benjamin Kaduk*
* The signature of the `copy` functional parameter of the
EVP_PKEY_meth_set_copy() function has changed so its `src` argument is
now `const EVP_PKEY_CTX *` instead of `EVP_PKEY_CTX *`. Similarly
the signature of the `pub_decode` functional parameter of the
EVP_PKEY_asn1_set_public() function has changed so its `pub` argument is
now `const X509_PUBKEY *` instead of `X509_PUBKEY *`.
*David von Oheimb*
* The error return values from some control calls (ctrl) have changed.
*Paul Dale*
* A public key check is now performed during EVP_PKEY_derive_set_peer().
*Shane Lontis*
* Many functions in the EVP_ namespace that are getters of values from
implementations or contexts were renamed to include get or get0 in their
names. Old names are provided as macro aliases for compatibility and
are not deprecated.
*Tomáš Mráz*
* The EVP_PKEY_CTRL_PKCS7_ENCRYPT, EVP_PKEY_CTRL_PKCS7_DECRYPT,
EVP_PKEY_CTRL_PKCS7_SIGN, EVP_PKEY_CTRL_CMS_ENCRYPT,
EVP_PKEY_CTRL_CMS_DECRYPT, and EVP_PKEY_CTRL_CMS_SIGN control operations
are deprecated.
*Tomáš Mráz*
* The EVP_PKEY_public_check() and EVP_PKEY_param_check() functions now work for
more key types.
* The output from the command line applications may have minor
changes.
*Paul Dale*
* The output from numerous "printing" may have minor changes.
*David von Oheimb*
* Windows thread synchronization uses read/write primitives (SRWLock) when
supported by the OS, otherwise CriticalSection continues to be used.
*Vincent Drake*
* Add filter BIO BIO_f_readbuffer() that allows BIO_tell() and BIO_seek() to
work on read only BIO source/sinks that do not support these functions.
This allows piping or redirection of a file BIO using stdin to be buffered
into memory. This is used internally in OSSL_DECODER_from_bio().
*Shane Lontis*
* OSSL_STORE_INFO_get_type() may now return an additional value. In 1.1.1
this function would return one of the values OSSL_STORE_INFO_NAME,
OSSL_STORE_INFO_PKEY, OSSL_STORE_INFO_PARAMS, OSSL_STORE_INFO_CERT or
OSSL_STORE_INFO_CRL. Decoded public keys would previously have been reported
as type OSSL_STORE_INFO_PKEY in 1.1.1. In 3.0 decoded public keys are now
reported as having the new type OSSL_STORE_INFO_PUBKEY. Applications
using this function should be amended to handle the changed return value.
*Richard Levitte*
* Improved adherence to Enhanced Security Services (ESS, RFC 2634 and RFC 5035)
for the TSP and CMS Advanced Electronic Signatures (CAdES) implementations.
As required by RFC 5035 check both ESSCertID and ESSCertIDv2 if both present.
Correct the semantics of checking the validation chain in case ESSCertID{,v2}
contains more than one certificate identifier: This means that all
certificates referenced there MUST be part of the validation chain.
*David von Oheimb*
* The implementation of older EVP ciphers related to CAST, IDEA, SEED, RC2, RC4,
RC5, DESX and DES have been moved to the legacy provider.
*Matt Caswell*
* The implementation of the EVP digests MD2, MD4, MDC2, WHIRLPOOL and
RIPEMD-160 have been moved to the legacy provider.
*Matt Caswell*
* The deprecated function EVP_PKEY_get0() now returns NULL being called for a
provided key.
*Dmitry Belyavskiy*
* The deprecated functions EVP_PKEY_get0_RSA(),
EVP_PKEY_get0_DSA(), EVP_PKEY_get0_EC_KEY(), EVP_PKEY_get0_DH(),
EVP_PKEY_get0_hmac(), EVP_PKEY_get0_poly1305() and EVP_PKEY_get0_siphash() as
well as the similarly named "get1" functions behave differently in
OpenSSL 3.0.
*Matt Caswell*
* A number of functions handling low-level keys or engines were deprecated
including EVP_PKEY_set1_engine(), EVP_PKEY_get0_engine(), EVP_PKEY_assign(),
EVP_PKEY_get0(), EVP_PKEY_get0_hmac(), EVP_PKEY_get0_poly1305() and
EVP_PKEY_get0_siphash().
*Matt Caswell*
* PKCS#5 PBKDF1 key derivation has been moved from PKCS5_PBE_keyivgen() into
the legacy crypto provider as an EVP_KDF. Applications requiring this KDF
will need to load the legacy crypto provider. This includes these PBE
algorithms which use this KDF:
- NID_pbeWithMD2AndDES_CBC
- NID_pbeWithMD5AndDES_CBC
- NID_pbeWithSHA1AndRC2_CBC
- NID_pbeWithMD2AndRC2_CBC
- NID_pbeWithMD5AndRC2_CBC
- NID_pbeWithSHA1AndDES_CBC
*Jon Spillett*
* Deprecated obsolete BIO_set_callback(), BIO_get_callback(), and
BIO_debug_callback() functions.
*Tomáš Mráz*
* Deprecated obsolete EVP_PKEY_CTX_get0_dh_kdf_ukm() and
EVP_PKEY_CTX_get0_ecdh_kdf_ukm() functions.
*Tomáš Mráz*
* The RAND_METHOD APIs have been deprecated.
*Paul Dale*
* The SRP APIs have been deprecated.
*Matt Caswell*
* Add a compile time option to prevent the caching of provider fetched
algorithms. This is enabled by including the no-cached-fetch option
at configuration time.
*Paul Dale*
* pkcs12 now uses defaults of PBKDF2, AES and SHA-256, with a MAC iteration
count of PKCS12_DEFAULT_ITER.
*Tomáš Mráz and Sahana Prasad*
* The openssl speed command does not use low-level API calls anymore.
*Tomáš Mráz*
* Parallel dual-prime 1024-bit modular exponentiation for AVX512_IFMA
capable processors.
*Ilya Albrekht, Sergey Kirillov, Andrey Matyukov (Intel Corp)*
* Combining the Configure options no-ec and no-dh no longer disables TLSv1.3.
*Matt Caswell*
* Implemented support for fully "pluggable" TLSv1.3 groups. This means that
providers may supply their own group implementations (using either the "key
exchange" or the "key encapsulation" methods) which will automatically be
detected and used by libssl.
*Matt Caswell, Nicola Tuveri*
* The undocumented function X509_certificate_type() has been deprecated;
*Rich Salz*
* Deprecated the obsolete BN_pseudo_rand() and BN_pseudo_rand_range().
*Tomáš Mráz*
* Removed RSA padding mode for SSLv23 (which was only used for
SSLv2). This includes the functions RSA_padding_check_SSLv23() and
RSA_padding_add_SSLv23() and the `-ssl` option in the deprecated
`rsautl` command.
*Rich Salz*
* Deprecated the obsolete X9.31 RSA key generation related functions.
* While a callback function set via `SSL_CTX_set_cert_verify_callback()`
is not allowed to return a value > 1, this is no more taken as failure.
*Viktor Dukhovni and David von Oheimb*
* Deprecated the obsolete X9.31 RSA key generation related functions
BN_X931_generate_Xpq(), BN_X931_derive_prime_ex(), and
BN_X931_generate_prime_ex().
*Tomáš Mráz*
* The default key generation method for the regular 2-prime RSA keys was
changed to the FIPS 186-4 B.3.6 method.
*Shane Lontis*
* Deprecated the BN_is_prime_ex() and BN_is_prime_fasttest_ex() functions.
*Kurt Roeckx*
* Deprecated EVP_MD_CTX_set_update_fn() and EVP_MD_CTX_update_fn().
*Rich Salz*
* Deprecated the type OCSP_REQ_CTX and the functions OCSP_REQ_CTX_*() and
replaced with OSSL_HTTP_REQ_CTX and the functions OSSL_HTTP_REQ_CTX_*().
*Rich Salz, Richard Levitte, and David von Oheimb*
* Deprecated `X509_http_nbio()` and `X509_CRL_http_nbio()`.
*David von Oheimb*
* Deprecated `OCSP_parse_url()`.
*David von Oheimb*
* Validation of SM2 keys has been separated from the validation of regular EC
keys.
*Nicola Tuveri*
* Behavior of the `pkey` app is changed, when using the `-check` or `-pubcheck`
switches: a validation failure triggers an early exit, returning a failure
exit status to the parent process.
*Nicola Tuveri*
* Changed behavior of SSL_CTX_set_ciphersuites() and SSL_set_ciphersuites()
to ignore unknown ciphers.
*Otto Hollmann*
* The `-cipher-commands` and `-digest-commands` options
of the command line utility `list` have been deprecated.
Instead use the `-cipher-algorithms` and `-digest-algorithms` options.
*Dmitry Belyavskiy*
* Added convenience functions for generating asymmetric key pairs:
The 'quick' one-shot (yet somewhat limited) function L<EVP_PKEY_Q_keygen(3)>
and macros for the most common cases: <EVP_RSA_gen(3)> and L<EVP_EC_gen(3)>.
*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 `<h1>` and `<h2>` 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<openssl-cmp(1)> and L<OSSL_CMP_exec_IR_ses(3)> 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<OSSL_HTTP_transfer(3)> 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 <https://www.openssl.org/policies/codingstyle.html>.
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
<openssl/macros.h>. 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 <openssl/configuration.h>
#undef OPENSSL_NO_DEPRECATED
#define OPENSSL_SUPPRESS_DEPRECATED
#include <openssl/macros.h>
This should not be used by applications that use the exported
symbols, as that will lead to linking errors.
*Richard Levitte*
* Fixed an overflow bug in the x64_64 Montgomery squaring procedure
used in exponentiation with 512-bit moduli. No EC algorithms are
affected. Analysis suggests that attacks against 2-prime RSA1024,
3-prime RSA1536, and DSA1024 as a result of this defect would be very
difficult to perform and are not believed likely. Attacks against DH512
are considered just feasible. However, for an attack the target would
have to re-use the DH512 private key, which is not recommended anyway.
Also applications directly using the low-level API BN_mod_exp may be
affected if they use BN_FLG_CONSTTIME.
([CVE-2019-1551])
*Andy Polyakov*
* Most memory-debug features have been deprecated, and the functionality
replaced with no-ops.
*Rich Salz*
* Added documentation for the STACK API.
*Rich Salz*
* Introduced a new method type and API, OSSL_ENCODER, to represent
generic encoders. These do the same sort of job that PEM writers
and d2i functions do, but with support for methods supplied by
providers, and the possibility for providers to support other
formats as well.
*Richard Levitte*
* Introduced a new method type and API, OSSL_DECODER, to represent
generic decoders. These do the same sort of job that PEM readers
and i2d functions do, but with support for methods supplied by
providers, and the possibility for providers to support other
formats as well.
*Richard Levitte*
* Added a .pragma directive to the syntax of configuration files, to
allow varying behavior in a supported and predictable manner.
Currently added pragma:
.pragma dollarid:on
This allows dollar signs to be a keyword character unless it's
followed by a opening brace or parenthesis. This is useful for
platforms where dollar signs are commonly used in names, such as
volume names and system directory names on VMS.
*Richard Levitte*
* Added functionality to create an EVP_PKEY from user data.
*Richard Levitte*
* Change the interpretation of the '--api' configuration option to
mean that this is a desired API compatibility level with no
further meaning. The previous interpretation, that this would
also mean to remove all deprecated symbols up to and including
the given version, no requires that 'no-deprecated' is also used
in the configuration.
When building applications, the desired API compatibility level
can be set with the OPENSSL_API_COMPAT macro like before. For
API compatibility version below 3.0, the old style numerical
value is valid as before, such as -DOPENSSL_API_COMPAT=0x10100000L.
For version 3.0 and on, the value is expected to be the decimal
value calculated from the major and minor version like this:
MAJOR * 10000 + MINOR * 100
Examples:
-DOPENSSL_API_COMPAT=30000 For 3.0
-DOPENSSL_API_COMPAT=30200 For 3.2
To hide declarations that are deprecated up to and including the
given API compatibility level, -DOPENSSL_NO_DEPRECATED must be
given when building the application as well.
*Richard Levitte*
* Added the X509_LOOKUP_METHOD called X509_LOOKUP_store, to allow
access to certificate and CRL stores via URIs and OSSL_STORE
loaders.
This adds the following functions:
- X509_LOOKUP_store()
- X509_STORE_load_file()
- X509_STORE_load_path()
- X509_STORE_load_store()
- SSL_add_store_cert_subjects_to_stack()
- SSL_CTX_set_default_verify_store()
- SSL_CTX_load_verify_file()
- SSL_CTX_load_verify_dir()
- SSL_CTX_load_verify_store()
*Richard Levitte*
* Added a new method to gather entropy on VMS, based on SYS$GET_ENTROPY.
The presence of this system service is determined at run-time.
*Richard Levitte*
* Added functionality to create an EVP_PKEY context based on data
for methods from providers. This takes an algorithm name and a
property query string and simply stores them, with the intent
that any operation that uses this context will use those strings
to fetch the needed methods implicitly, thereby making the port
of application written for pre-3.0 OpenSSL easier.
*Richard Levitte*
* The undocumented function NCONF_WIN32() has been deprecated; for
conversion details see the HISTORY section of doc/man5/config.pod
*Rich Salz*
* Introduced the new functions EVP_DigestSignInit_ex() and
EVP_DigestVerifyInit_ex(). The macros EVP_DigestSignUpdate() and
EVP_DigestVerifyUpdate() have been converted to functions. See the man
pages for further details.
*Matt Caswell*
* Over two thousand fixes were made to the documentation, including:
adding missing command flags, better style conformance, documentation
of internals, etc.
*Rich Salz, Richard Levitte*
* s390x assembly pack: add hardware-support for P-256, P-384, P-521,
X25519, X448, Ed25519 and Ed448.
*Patrick Steuer*
* Print all values for a PKCS#12 attribute with 'openssl pkcs12', not just
the first value.
*Jon Spillett*
* Deprecated the public definition of `ERR_STATE` as well as the function
`ERR_get_state()`. This is done in preparation of making `ERR_STATE` an
opaque type.
*Richard Levitte*
* Added ERR functionality to give callers access to the stored function
names that have replaced the older function code based functions.
New functions are ERR_peek_error_func(), ERR_peek_last_error_func(),
ERR_peek_error_data(), ERR_peek_last_error_data(), ERR_get_error_all(),
ERR_peek_error_all() and ERR_peek_last_error_all().
Deprecate ERR functions ERR_get_error_line(), ERR_get_error_line_data(),
ERR_peek_error_line_data(), ERR_peek_last_error_line_data() and
ERR_func_error_string().
*Richard Levitte*
* Extended testing to be verbose for failing tests only. The make variables
VERBOSE_FAILURE or VF can be used to enable this:
$ make VF=1 test # Unix
$ mms /macro=(VF=1) test ! OpenVMS
$ nmake VF=1 test # Windows
*Richard Levitte*
* Added the `-copy_extensions` option to the `x509` command for use with
`-req` and `-x509toreq`. When given with the `copy` or `copyall` argument,
all extensions in the request are copied to the certificate or vice versa.
*David von Oheimb*, *Kirill Stefanenkov <kirill_stefanenkov@rambler.ru>*
* Added the `-copy_extensions` option to the `req` command for use with
`-x509`. When given with the `copy` or `copyall` argument,
all extensions in the certification request are copied to the certificate.
*David von Oheimb*
* The `x509`, `req`, and `ca` commands now make sure that X.509v3 certificates
they generate are by default RFC 5280 compliant in the following sense:
There is a subjectKeyIdentifier extension with a hash value of the public key
and for not self-signed certs there is an authorityKeyIdentifier extension
with a keyIdentifier field or issuer information identifying the signing key.
This is done unless some configuration overrides the new default behavior,
such as `subjectKeyIdentifier = none` and `authorityKeyIdentifier = none`.
*David von Oheimb*
* Added several checks to `X509_verify_cert()` according to requirements in
RFC 5280 in case `X509_V_FLAG_X509_STRICT` is set
(which may be done by using the CLI option `-x509_strict`):
* The basicConstraints of CA certificates must be marked critical.
* CA certificates must explicitly include the keyUsage extension.
* If a pathlenConstraint is given the key usage keyCertSign must be allowed.
* The issuer name of any certificate must not be empty.
* The subject name of CA certs, certs with keyUsage crlSign,
and certs without subjectAlternativeName must not be empty.
* If a subjectAlternativeName extension is given it must not be empty.
* The signatureAlgorithm field and the cert signature must be consistent.
* Any given authorityKeyIdentifier and any given subjectKeyIdentifier
must not be marked critical.
* The authorityKeyIdentifier must be given for X.509v3 certs
unless they are self-signed.
* The subjectKeyIdentifier must be given for all X.509v3 CA certs.
*David von Oheimb*
* Certificate verification using `X509_verify_cert()` meanwhile rejects EC keys
with explicit curve parameters (specifiedCurve) as required by RFC 5480.
*Tomáš Mráz*
* For built-in EC curves, ensure an EC_GROUP built from the curve name is
used even when parsing explicit parameters, when loading a encoded key
or calling `EC_GROUP_new_from_ecpkparameters()`/
`EC_GROUP_new_from_ecparameters()`.
This prevents bypass of security hardening and performance gains,
especially for curves with specialized EC_METHODs.
By default, if a key encoded with explicit parameters is loaded and later
encoded, the output is still encoded with explicit parameters, even if
internally a "named" EC_GROUP is used for computation.
*Nicola Tuveri*
* Compute ECC cofactors if not provided during EC_GROUP construction. Before
this change, EC_GROUP_set_generator would accept order and/or cofactor as
NULL. After this change, only the cofactor parameter can be NULL. It also
does some minimal sanity checks on the passed order.
([CVE-2019-1547])
*Billy Bob Brumley*
* Fixed a padding oracle in PKCS7_dataDecode and CMS_decrypt_set1_pkey.
An attack is simple, if the first CMS_recipientInfo is valid but the
second CMS_recipientInfo is chosen ciphertext. If the second
recipientInfo decodes to PKCS #1 v1.5 form plaintext, the correct
encryption key will be replaced by garbage, and the message cannot be
decoded, but if the RSA decryption fails, the correct encryption key is
used and the recipient will not notice the attack.
As a work around for this potential attack the length of the decrypted
key must be equal to the cipher default key length, in case the
certifiate is not given and all recipientInfo are tried out.
The old behaviour can be re-enabled in the CMS code by setting the
CMS_DEBUG_DECRYPT flag.
*Bernd Edlinger*
* Early start up entropy quality from the DEVRANDOM seed source has been
improved for older Linux systems. The RAND subsystem will wait for
/dev/random to be producing output before seeding from /dev/urandom.
The seeded state is stored for future library initialisations using
a system global shared memory segment. The shared memory identifier
can be configured by defining OPENSSL_RAND_SEED_DEVRANDOM_SHM_ID to
the desired value. The default identifier is 114.
*Paul Dale*
* Revised BN_generate_prime_ex to not avoid factors 2..17863 in p-1
when primes for RSA keys are computed.
Since we previously always generated primes == 2 (mod 3) for RSA keys,
the 2-prime and 3-prime RSA modules were easy to distinguish, since
`N = p*q = 1 (mod 3)`, but `N = p*q*r = 2 (mod 3)`. Therefore fingerprinting
2-prime vs. 3-prime RSA keys was possible by computing N mod 3.
This avoids possible fingerprinting of newly generated RSA modules.
*Bernd Edlinger*
* Correct the extended master secret constant on EBCDIC systems. Without this
fix TLS connections between an EBCDIC system and a non-EBCDIC system that
negotiate EMS will fail. Unfortunately this also means that TLS connections
between EBCDIC systems with this fix, and EBCDIC systems without this
fix will fail if they negotiate EMS.
*Matt Caswell*
* Changed the library initialisation so that the config file is now loaded
by default. This was already the case for libssl. It now occurs for both
libcrypto and libssl. Use the OPENSSL_INIT_NO_LOAD_CONFIG option to
`OPENSSL_init_crypto()` to suppress automatic loading of a config file.
*Matt Caswell*
* Introduced new error raising macros, `ERR_raise()` and `ERR_raise_data()`,
where the former acts as a replacement for `ERR_put_error()`, and the
latter replaces the combination `ERR_put_error()` + `ERR_add_error_data()`.
`ERR_raise_data()` adds more flexibility by taking a format string and
an arbitrary number of arguments following it, to be processed with
`BIO_snprintf()`.
*Richard Levitte*
* Introduced a new function, `OSSL_PROVIDER_available()`, which can be used
to check if a named provider is loaded and available. When called, it
will also activate all fallback providers if such are still present.
*Richard Levitte*
* Enforce a minimum DH modulus size of 512 bits.
*Bernd Edlinger*
* Changed DH parameters to generate the order q subgroup instead of 2q.
Previously generated DH parameters are still accepted by DH_check
but DH_generate_key works around that by clearing bit 0 of the
private key for those. This avoids leaking bit 0 of the private key.
*Bernd Edlinger*
* Significantly reduce secure memory usage by the randomness pools.
*Paul Dale*
* `{CRYPTO,OPENSSL}_mem_debug_{push,pop}` are now no-ops and have been
deprecated.
*Rich Salz*
* A new type, EVP_KEYEXCH, has been introduced to represent key exchange
algorithms. An implementation of a key exchange algorithm can be obtained
by using the function EVP_KEYEXCH_fetch(). An EVP_KEYEXCH algorithm can be
used in a call to EVP_PKEY_derive_init_ex() which works in a similar way to
the older EVP_PKEY_derive_init() function. See the man pages for the new
functions for further details.
*Matt Caswell*
* The EVP_PKEY_CTX_set_dh_pad() macro has now been converted to a function.
*Matt Caswell*
* Removed the function names from error messages and deprecated the
xxx_F_xxx define's.
*Richard Levitte*
* Removed NextStep support and the macro OPENSSL_UNISTD
*Rich Salz*
* Removed DES_check_key. Also removed OPENSSL_IMPLEMENT_GLOBAL,
OPENSSL_GLOBAL_REF, OPENSSL_DECLARE_GLOBAL.
Also removed "export var as function" capability; we do not export
variables, only functions.
*Rich Salz*
* RC5_32_set_key has been changed to return an int type, with 0 indicating
an error and 1 indicating success. In previous versions of OpenSSL this
was a void type. If a key was set longer than the maximum possible this
would crash.
*Matt Caswell*
* Support SM2 signing and verification schemes with X509 certificate.
*Paul Yang*
* Use SHA256 as the default digest for TS query in the `ts` app.
*Tomáš Mráz*
* Change PBKDF2 to conform to SP800-132 instead of the older PKCS5 RFC2898.
*Shane Lontis*
* Default cipher lists/suites are now available via a function, the
#defines are deprecated.
*Todd Short*
* Add target VC-WIN32-UWP, VC-WIN64A-UWP, VC-WIN32-ARM-UWP and
VC-WIN64-ARM-UWP in Windows OneCore target for making building libraries
for Windows Store apps easier. Also, the "no-uplink" option has been added.
*Kenji Mouri*
* Join the directories crypto/x509 and crypto/x509v3
*Richard Levitte*
* Added command 'openssl kdf' that uses the EVP_KDF API.
*Shane Lontis*
* Added command 'openssl mac' that uses the EVP_MAC API.
*Shane Lontis*
* Added OPENSSL_info() to get diverse built-in OpenSSL data, such
as default directories. Also added the command 'openssl info'
for scripting purposes.
*Richard Levitte*
* The functions AES_ige_encrypt() and AES_bi_ige_encrypt() have been
deprecated.
*Matt Caswell*
* Add prediction resistance to the DRBG reseeding process.
*Paul Dale*
* Limit the number of blocks in a data unit for AES-XTS to 2^20 as
mandated by IEEE Std 1619-2018.
*Paul Dale*
* Added newline escaping functionality to a filename when using openssl dgst.
This output format is to replicate the output format found in the `*sum`
checksum programs. This aims to preserve backward compatibility.
*Matt Eaton, Richard Levitte, and Paul Dale*
* Removed the heartbeat message in DTLS feature, as it has very
little usage and doesn't seem to fulfill a valuable purpose.
The configuration option is now deprecated.
*Richard Levitte*
* Changed the output of 'openssl {digestname} < file' to display the
digest name in its output.
*Richard Levitte*
* Added a new generic trace API which provides support for enabling
instrumentation through trace output.
*Richard Levitte & Matthias St. Pierre*
* Added build tests for C++. These are generated files that only do one
thing, to include one public OpenSSL head file each. This tests that
the public header files can be usefully included in a C++ application.
This test isn't enabled by default. It can be enabled with the option
'enable-buildtest-c++'.
*Richard Levitte*
* Added KB KDF (EVP_KDF_KB) to EVP_KDF.
*Robbie Harwood*
* Added SSH KDF (EVP_KDF_SSHKDF) and KRB5 KDF (EVP_KDF_KRB5KDF) to EVP_KDF.
*Simo Sorce*
* Added Single Step KDF (EVP_KDF_SS), X963 KDF, and X942 KDF to EVP_KDF.
*Shane Lontis*
* Added KMAC to EVP_MAC.
*Shane Lontis*
* Added property based algorithm implementation selection framework to
the core.
*Paul Dale*
* Added SCA hardening for modular field inversion in EC_GROUP through
a new dedicated field_inv() pointer in EC_METHOD.
This also addresses a leakage affecting conversions from projective
to affine coordinates.
*Billy Bob Brumley, Nicola Tuveri*
* Added EVP_KDF, an EVP layer KDF API, to simplify adding KDF and PRF
implementations. This includes an EVP_PKEY to EVP_KDF bridge for
those algorithms that were already supported through the EVP_PKEY API
(scrypt, TLS1 PRF and HKDF). The low-level KDF functions for PBKDF2
and scrypt are now wrappers that call EVP_KDF.
*David Makepeace*
* Build devcrypto engine as a dynamic engine.
*Eneas U de Queiroz*
* Add keyed BLAKE2 to EVP_MAC.
*Antoine Salon*
* Fix a bug in the computation of the endpoint-pair shared secret used
by DTLS over SCTP. This breaks interoperability with older versions
of OpenSSL like OpenSSL 1.1.0 and OpenSSL 1.0.2. There is a runtime
switch SSL_MODE_DTLS_SCTP_LABEL_LENGTH_BUG (off by default) enabling
interoperability with such broken implementations. However, enabling
this switch breaks interoperability with correct implementations.
* Fix a use after free bug in d2i_X509_PUBKEY when overwriting a
re-used X509_PUBKEY object if the second PUBKEY is malformed.
*Bernd Edlinger*
* Move strictness check from EVP_PKEY_asn1_new() to EVP_PKEY_asn1_add0().
*Richard Levitte*
* Changed the license to the Apache License v2.0.
*Richard Levitte*
* Switch to a new version scheme using three numbers MAJOR.MINOR.PATCH.
- Major releases (indicated by incrementing the MAJOR release number)
may introduce incompatible API/ABI changes.
- Minor releases (indicated by incrementing the MINOR release number)
may introduce new features but retain API/ABI compatibility.
- Patch releases (indicated by incrementing the PATCH number)
are intended for bug fixes and other improvements of existing
features only (like improving performance or adding documentation)
and retain API/ABI compatibility.
*Richard Levitte*
* Add support for RFC5297 SIV mode (siv128), including AES-SIV.
*Todd Short*
* Remove the 'dist' target and add a tarball building script. The
'dist' target has fallen out of use, and it shouldn't be
necessary to configure just to create a source distribution.
*Richard Levitte*
* Recreate the OS390-Unix config target. It no longer relies on a
special script like it did for OpenSSL pre-1.1.0.
*Richard Levitte*
* Instead of having the source directories listed in Configure, add
a 'build.info' keyword SUBDIRS to indicate what sub-directories to
look into.
*Richard Levitte*
* Add GMAC to EVP_MAC.
*Paul Dale*
* Ported the HMAC, CMAC and SipHash EVP_PKEY_METHODs to EVP_MAC.
*Richard Levitte*
* Added EVP_MAC, an EVP layer MAC API, to simplify adding MAC
implementations. This includes a generic EVP_PKEY to EVP_MAC bridge,
to facilitate the continued use of MACs through raw private keys in
functionality such as `EVP_DigestSign*` and `EVP_DigestVerify*`.
*Richard Levitte*
* Deprecate ECDH_KDF_X9_62().
*Antoine Salon*
* Added EVP_PKEY_ECDH_KDF_X9_63 and ecdh_KDF_X9_63() as replacements for
the EVP_PKEY_ECDH_KDF_X9_62 KDF type and ECDH_KDF_X9_62(). The old names
are retained for backwards compatibility.
*Antoine Salon*
* AES-XTS mode now enforces that its two keys are different to mitigate
the attacked described in "Efficient Instantiations of Tweakable
Blockciphers and Refinements to Modes OCB and PMAC" by Phillip Rogaway.
Details of this attack can be obtained from:
<http://web.cs.ucdavis.edu/%7Erogaway/papers/offsets.pdf>
*Paul Dale*
* Rename the object files, i.e. give them other names than in previous
versions. Their names now include the name of the final product, as
well as its type mnemonic (bin, lib, shlib).
*Richard Levitte*
* Added new option for 'openssl list', '-objects', which will display the
list of built in objects, i.e. OIDs with names.
*Richard Levitte*
* Added the options `-crl_lastupdate` and `-crl_nextupdate` to `openssl ca`,
allowing the `lastUpdate` and `nextUpdate` fields in the generated CRL to
be set explicitly.
*Chris Novakovic*
* Added support for Linux Kernel TLS data-path. The Linux Kernel data-path
improves application performance by removing data copies and providing
applications with zero-copy system calls such as sendfile and splice.
*Boris Pismenny*
* The SSL option SSL_OP_CLEANSE_PLAINTEXT is introduced.
*Martin Elshuber*
* `PKCS12_parse` now maintains the order of the parsed certificates
when outputting them via `*ca` (rather than reversing it).
*David von Oheimb*
* Deprecated pthread fork support methods.
*Randall S. Becker*
* Added support for FFDHE key exchange in TLS 1.3.
*Raja Ashok*
* Added a new concept for OpenSSL plugability: providers. This
functionality is designed to replace the ENGINE API and ENGINE
implementations, and to be much more dynamic, allowing provider
authors to introduce new algorithms among other things, as long as
there's an API that supports the algorithm type.
With this concept comes a new core API for interaction between
libcrypto and provider implementations. Public libcrypto functions
that want to use providers do so through this core API.
The main documentation for this core API is found in
doc/man7/provider.pod, doc/man7/provider-base.pod, and they in turn
refer to other manuals describing the API specific for supported
algorithm types (also called operations).
*The OpenSSL team*
OpenSSL 1.1.1
-------------
### Changes between 1.1.1l and 1.1.1m [xx XXX xxxx]
* Avoid loading of a dynamic engine twice.
*Bernd Edlinger*
* Prioritise DANE TLSA issuer certs over peer certs
*Viktor Dukhovni*
* Fixed random API for MacOS prior to 10.12
These MacOS versions don't support the CommonCrypto APIs
*Lenny Primak*
### Changes between 1.1.1k and 1.1.1l [24 Aug 2021]
* Fixed an SM2 Decryption Buffer Overflow.
In order to decrypt SM2 encrypted data an application is expected to
call the API function EVP_PKEY_decrypt(). Typically an application will
call this function twice. The first time, on entry, the "out" parameter
can be NULL and, on exit, the "outlen" parameter is populated with the
buffer size required to hold the decrypted plaintext. The application
can then allocate a sufficiently sized buffer and call EVP_PKEY_decrypt()
again, but this time passing a non-NULL value for the "out" parameter.
A bug in the implementation of the SM2 decryption code means that the
calculation of the buffer size required to hold the plaintext returned
by the first call to EVP_PKEY_decrypt() can be smaller than the actual
size required by the second call. This can lead to a buffer overflow
when EVP_PKEY_decrypt() is called by the application a second time with
a buffer that is too small.
A malicious attacker who is able present SM2 content for decryption to
an application could cause attacker chosen data to overflow the buffer
by up to a maximum of 62 bytes altering the contents of other data held
after the buffer, possibly changing application behaviour or causing
the application to crash. The location of the buffer is application
dependent but is typically heap allocated.
([CVE-2021-3711])
*Matt Caswell*
* Fixed various read buffer overruns processing ASN.1 strings
ASN.1 strings are represented internally within OpenSSL as an ASN1_STRING
structure which contains a buffer holding the string data and a field
holding the buffer length. This contrasts with normal C strings which
are repesented as a buffer for the string data which is terminated
with a NUL (0) byte.
Although not a strict requirement, ASN.1 strings that are parsed using
OpenSSL's own "d2i" functions (and other similar parsing functions) as
well as any string whose value has been set with the ASN1_STRING_set()
function will additionally NUL terminate the byte array in the
ASN1_STRING structure.
However, it is possible for applications to directly construct valid
ASN1_STRING structures which do not NUL terminate the byte array by
directly setting the "data" and "length" fields in the ASN1_STRING
array. This can also happen by using the ASN1_STRING_set0() function.
Numerous OpenSSL functions that print ASN.1 data have been found to
assume that the ASN1_STRING byte array will be NUL terminated, even
though this is not guaranteed for strings that have been directly
constructed. Where an application requests an ASN.1 structure to be
printed, and where that ASN.1 structure contains ASN1_STRINGs that have
been directly constructed by the application without NUL terminating
the "data" field, then a read buffer overrun can occur.
The same thing can also occur during name constraints processing
of certificates (for example if a certificate has been directly
constructed by the application instead of loading it via the OpenSSL
parsing functions, and the certificate contains non NUL terminated
ASN1_STRING structures). It can also occur in the X509_get1_email(),
X509_REQ_get1_email() and X509_get1_ocsp() functions.
If a malicious actor can cause an application to directly construct an
ASN1_STRING and then process it through one of the affected OpenSSL
functions then this issue could be hit. This might result in a crash
(causing a Denial of Service attack). It could also result in the
disclosure of private memory contents (such as private keys, or
sensitive plaintext).
([CVE-2021-3712])
*Matt Caswell*
### Changes between 1.1.1j and 1.1.1k [25 Mar 2021]
* Fixed a problem with verifying a certificate chain when using the
X509_V_FLAG_X509_STRICT flag. This flag enables additional security checks of
the certificates present in a certificate chain. It is not set by default.
Starting from OpenSSL version 1.1.1h a check to disallow certificates in
the chain that have explicitly encoded elliptic curve parameters was added
as an additional strict check.
An error in the implementation of this check meant that the result of a
previous check to confirm that certificates in the chain are valid CA
certificates was overwritten. This effectively bypasses the check
that non-CA certificates must not be able to issue other certificates.
If a "purpose" has been configured then there is a subsequent opportunity
for checks that the certificate is a valid CA. All of the named "purpose"
values implemented in libcrypto perform this check. Therefore, where
a purpose is set the certificate chain will still be rejected even when the
strict flag has been used. A purpose is set by default in libssl client and
server certificate verification routines, but it can be overridden or
removed by an application.
In order to be affected, an application must explicitly set the
X509_V_FLAG_X509_STRICT verification flag and either not set a purpose
for the certificate verification or, in the case of TLS client or server
applications, override the default purpose.
([CVE-2021-3450])
*Tomáš Mráz*
* Fixed an issue where an OpenSSL TLS server may crash if sent a maliciously
crafted renegotiation ClientHello message from a client. If a TLSv1.2
renegotiation ClientHello omits the signature_algorithms extension (where it
was present in the initial ClientHello), but includes a
signature_algorithms_cert extension then a NULL pointer dereference will
result, leading to a crash and a denial of service attack.
A server is only vulnerable if it has TLSv1.2 and renegotiation enabled
(which is the default configuration). OpenSSL TLS clients are not impacted by
this issue.
([CVE-2021-3449])
*Peter Kästle and Samuel Sapalski*
### Changes between 1.1.1i and 1.1.1j [16 Feb 2021]
* Fixed the X509_issuer_and_serial_hash() function. It attempts to
create a unique hash value based on the issuer and serial number data
contained within an X509 certificate. However it was failing to correctly
handle any errors that may occur while parsing the issuer field (which might
occur if the issuer field is maliciously constructed). This may subsequently
result in a NULL pointer deref and a crash leading to a potential denial of
service attack.
([CVE-2021-23841])
*Matt Caswell*
* Fixed the RSA_padding_check_SSLv23() function and the RSA_SSLV23_PADDING
padding mode to correctly check for rollback attacks. This is considered a
bug in OpenSSL 1.1.1 because it does not support SSLv2. In 1.0.2 this is
CVE-2021-23839.
*Matt Caswell*
Fixed the EVP_CipherUpdate, EVP_EncryptUpdate and EVP_DecryptUpdate
functions. Previously they could overflow the output length argument in some
cases where the input length is close to the maximum permissable length for
an integer on the platform. In such cases the return value from the function
call would be 1 (indicating success), but the output length value would be
negative. This could cause applications to behave incorrectly or crash.
([CVE-2021-23840])
*Matt Caswell*
* Fixed SRP_Calc_client_key so that it runs in constant time. The previous
implementation called BN_mod_exp without setting BN_FLG_CONSTTIME. This
could be exploited in a side channel attack to recover the password. Since
the attack is local host only this is outside of the current OpenSSL
threat model and therefore no CVE is assigned.
Thanks to Mohammed Sabt and Daniel De Almeida Braga for reporting this
issue.
*Matt Caswell*
### Changes between 1.1.1h and 1.1.1i [8 Dec 2020]
* Fixed NULL pointer deref in the GENERAL_NAME_cmp function
This function could crash if both GENERAL_NAMEs contain an EDIPARTYNAME.
If an attacker can control both items being compared then this could lead
to a possible denial of service attack. OpenSSL itself uses the
GENERAL_NAME_cmp function for two purposes:
1) Comparing CRL distribution point names between an available CRL and a
CRL distribution point embedded in an X509 certificate
2) When verifying that a timestamp response token signer matches the
timestamp authority name (exposed via the API functions
TS_RESP_verify_response and TS_RESP_verify_token)
([CVE-2020-1971])
*Matt Caswell*
### Changes between 1.1.1g and 1.1.1h [22 Sep 2020]
* Certificates with explicit curve parameters are now disallowed in
verification chains if the X509_V_FLAG_X509_STRICT flag is used.
*Tomáš Mráz*
* The 'MinProtocol' and 'MaxProtocol' configuration commands now silently
ignore TLS protocol version bounds when configuring DTLS-based contexts, and
conversely, silently ignore DTLS protocol version bounds when configuring
TLS-based contexts. The commands can be repeated to set bounds of both
types. The same applies with the corresponding "min_protocol" and
"max_protocol" command-line switches, in case some application uses both TLS
and DTLS.
SSL_CTX instances that are created for a fixed protocol version (e.g.
TLSv1_server_method()) also silently ignore version bounds. Previously
attempts to apply bounds to these protocol versions would result in an
error. Now only the "version-flexible" SSL_CTX instances are subject to
limits in configuration files in command-line options.
*Viktor Dukhovni*
* Handshake now fails if Extended Master Secret extension is dropped
on renegotiation.
*Tomáš Mráz*
* The Oracle Developer Studio compiler will start reporting deprecated APIs
### Changes between 1.1.1f and 1.1.1g [21 Apr 2020]
* Fixed segmentation fault in SSL_check_chain()
Server or client applications that call the SSL_check_chain() function
during or after a TLS 1.3 handshake may crash due to a NULL pointer
dereference as a result of incorrect handling of the
"signature_algorithms_cert" TLS extension. The crash occurs if an invalid
or unrecognised signature algorithm is received from the peer. This could
be exploited by a malicious peer in a Denial of Service attack.
([CVE-2020-1967])
*Benjamin Kaduk*
* Added AES consttime code for no-asm configurations
an optional constant time support for AES was added
when building openssl for no-asm.
Enable with: ./config no-asm -DOPENSSL_AES_CONST_TIME
Disable with: ./config no-asm -DOPENSSL_NO_AES_CONST_TIME
At this time this feature is by default disabled.
It will be enabled by default in 3.0.
*Bernd Edlinger*
### Changes between 1.1.1e and 1.1.1f [31 Mar 2020]
* Revert the change of EOF detection while reading in libssl to avoid
regressions in applications depending on the current way of reporting
the EOF. As the existing method is not fully accurate the change to
reporting the EOF via SSL_ERROR_SSL is kept on the current development
branch and will be present in the 3.0 release.
*Tomáš Mráz*
* Revised BN_generate_prime_ex to not avoid factors 3..17863 in p-1
when primes for RSA keys are computed.
Since we previously always generated primes == 2 (mod 3) for RSA keys,
the 2-prime and 3-prime RSA modules were easy to distinguish, since
N = p*q = 1 (mod 3), but N = p*q*r = 2 (mod 3). Therefore fingerprinting
2-prime vs. 3-prime RSA keys was possible by computing N mod 3.
This avoids possible fingerprinting of newly generated RSA modules.
*Bernd Edlinger*
### Changes between 1.1.1d and 1.1.1e [17 Mar 2020]
* Properly detect EOF while reading in libssl. Previously if we hit an EOF
while reading in libssl then we would report an error back to the
application (SSL_ERROR_SYSCALL) but errno would be 0. We now add
an error to the stack (which means we instead return SSL_ERROR_SSL) and
therefore give a hint as to what went wrong.
*Matt Caswell*
* Check that ed25519 and ed448 are allowed by the security level. Previously
signature algorithms not using an MD were not being checked that they were
allowed by the security level.
*Kurt Roeckx*
* Fixed SSL_get_servername() behaviour. The behaviour of SSL_get_servername()
was not quite right. The behaviour was not consistent between resumption
and normal handshakes, and also not quite consistent with historical
behaviour. The behaviour in various scenarios has been clarified and
it has been updated to make it match historical behaviour as closely as
possible.
*Matt Caswell*
* *[VMS only]* The header files that the VMS compilers include automatically,
`__DECC_INCLUDE_PROLOGUE.H` and `__DECC_INCLUDE_EPILOGUE.H`, use pragmas
that the C++ compiler doesn't understand. This is a shortcoming in the
compiler, but can be worked around with `__cplusplus` guards.
C++ applications that use OpenSSL libraries must be compiled using the
qualifier `/NAMES=(AS_IS,SHORTENED)` to be able to use all the OpenSSL
functions. Otherwise, only functions with symbols of less than 31
characters can be used, as the linker will not be able to successfully
resolve symbols with longer names.
*Richard Levitte*
* Added a new method to gather entropy on VMS, based on SYS$GET_ENTROPY.
The presence of this system service is determined at run-time.
*Richard Levitte*
* Print all values for a PKCS#12 attribute with 'openssl pkcs12', not just
the first value.
*Jon Spillett*
### Changes between 1.1.1c and 1.1.1d [10 Sep 2019]
* Fixed a fork protection issue. OpenSSL 1.1.1 introduced a rewritten random
number generator (RNG). This was intended to include protection in the
event of a fork() system call in order to ensure that the parent and child
processes did not share the same RNG state. However this protection was not
being used in the default case.
A partial mitigation for this issue is that the output from a high
precision timer is mixed into the RNG state so the likelihood of a parent
and child process sharing state is significantly reduced.
If an application already calls OPENSSL_init_crypto() explicitly using
OPENSSL_INIT_ATFORK then this problem does not occur at all.
([CVE-2019-1549])
*Matthias St. Pierre*
* For built-in EC curves, ensure an EC_GROUP built from the curve name is
used even when parsing explicit parameters, when loading a encoded key
or calling `EC_GROUP_new_from_ecpkparameters()`/
`EC_GROUP_new_from_ecparameters()`.
This prevents bypass of security hardening and performance gains,
especially for curves with specialized EC_METHODs.
By default, if a key encoded with explicit parameters is loaded and later
encoded, the output is still encoded with explicit parameters, even if
internally a "named" EC_GROUP is used for computation.
*Nicola Tuveri*
* Compute ECC cofactors if not provided during EC_GROUP construction. Before
this change, EC_GROUP_set_generator would accept order and/or cofactor as
NULL. After this change, only the cofactor parameter can be NULL. It also
does some minimal sanity checks on the passed order.
([CVE-2019-1547])
*Billy Bob Brumley*
* Fixed a padding oracle in PKCS7_dataDecode and CMS_decrypt_set1_pkey.
An attack is simple, if the first CMS_recipientInfo is valid but the
second CMS_recipientInfo is chosen ciphertext. If the second
recipientInfo decodes to PKCS #1 v1.5 form plaintext, the correct
encryption key will be replaced by garbage, and the message cannot be
decoded, but if the RSA decryption fails, the correct encryption key is
used and the recipient will not notice the attack.
As a work around for this potential attack the length of the decrypted
key must be equal to the cipher default key length, in case the
certifiate is not given and all recipientInfo are tried out.
The old behaviour can be re-enabled in the CMS code by setting the
CMS_DEBUG_DECRYPT flag.
([CVE-2019-1563])
*Bernd Edlinger*
* Early start up entropy quality from the DEVRANDOM seed source has been
improved for older Linux systems. The RAND subsystem will wait for
/dev/random to be producing output before seeding from /dev/urandom.
The seeded state is stored for future library initialisations using
a system global shared memory segment. The shared memory identifier
can be configured by defining OPENSSL_RAND_SEED_DEVRANDOM_SHM_ID to
the desired value. The default identifier is 114.
*Paul Dale*
* Correct the extended master secret constant on EBCDIC systems. Without this
fix TLS connections between an EBCDIC system and a non-EBCDIC system that
negotiate EMS will fail. Unfortunately this also means that TLS connections
between EBCDIC systems with this fix, and EBCDIC systems without this
fix will fail if they negotiate EMS.
*Matt Caswell*
* Use Windows installation paths in the mingw builds
Mingw isn't a POSIX environment per se, which means that Windows
paths should be used for installation.
([CVE-2019-1552])
*Richard Levitte*
* Changed DH_check to accept parameters with order q and 2q subgroups.
With order 2q subgroups the bit 0 of the private key is not secret
but DH_generate_key works around that by clearing bit 0 of the
private key for those. This avoids leaking bit 0 of the private key.
*Bernd Edlinger*
* Significantly reduce secure memory usage by the randomness pools.
*Paul Dale*
* Revert the DEVRANDOM_WAIT feature for Linux systems
The DEVRANDOM_WAIT feature added a select() call to wait for the
/dev/random device to become readable before reading from the
/dev/urandom device.
It turned out that this change had negative side effects on
performance which were not acceptable. After some discussion it
was decided to revert this feature and leave it up to the OS
resp. the platform maintainer to ensure a proper initialization
during early boot time.
*Matthias St. Pierre*
### Changes between 1.1.1b and 1.1.1c [28 May 2019]
* Add build tests for C++. These are generated files that only do one
thing, to include one public OpenSSL head file each. This tests that
the public header files can be usefully included in a C++ application.
This test isn't enabled by default. It can be enabled with the option
'enable-buildtest-c++'.
*Richard Levitte*
* Enable SHA3 pre-hashing for ECDSA and DSA.
*Patrick Steuer*
* Change the default RSA, DSA and DH size to 2048 bit instead of 1024.
This changes the size when using the `genpkey` command when no size is given.
It fixes an omission in earlier changes that changed all RSA, DSA and DH
generation commands to use 2048 bits by default.
*Kurt Roeckx*
* Reorganize the manual pages to consistently have RETURN VALUES,
EXAMPLES, SEE ALSO and HISTORY come in that order, and adjust
util/fix-doc-nits accordingly.
*Paul Yang, Joshua Lock*
* Add the missing accessor EVP_PKEY_get0_engine()
*Matt Caswell*
* Have commands like `s_client` and `s_server` output the signature scheme
along with other cipher suite parameters when debugging.
*Lorinczy Zsigmond*
* Make OPENSSL_config() error agnostic again.
*Richard Levitte*
* Do the error handling in RSA decryption constant time.
*Bernd Edlinger*
* Prevent over long nonces in ChaCha20-Poly1305.
ChaCha20-Poly1305 is an AEAD cipher, and requires a unique nonce input
for every encryption operation. RFC 7539 specifies that the nonce value
(IV) should be 96 bits (12 bytes). OpenSSL allows a variable nonce length
and front pads the nonce with 0 bytes if it is less than 12
bytes. However it also incorrectly allows a nonce to be set of up to 16
bytes. In this case only the last 12 bytes are significant and any
additional leading bytes are ignored.
It is a requirement of using this cipher that nonce values are
unique. Messages encrypted using a reused nonce value are susceptible to
serious confidentiality and integrity attacks. If an application changes
the default nonce length to be longer than 12 bytes and then makes a
change to the leading bytes of the nonce expecting the new value to be a
new unique nonce then such an application could inadvertently encrypt
messages with a reused nonce.
Additionally the ignored bytes in a long nonce are not covered by the
integrity guarantee of this cipher. Any application that relies on the
integrity of these ignored leading bytes of a long nonce may be further
affected. Any OpenSSL internal use of this cipher, including in SSL/TLS,
is safe because no such use sets such a long nonce value. However user
applications that use this cipher directly and set a non-default nonce
length to be longer than 12 bytes may be vulnerable.
This issue was reported to OpenSSL on 16th of March 2019 by Joran Dirk
Greef of Ronomon.
([CVE-2019-1543])
*Matt Caswell*
* Add DEVRANDOM_WAIT feature for Linux systems
On older Linux systems where the getrandom() system call is not available,
OpenSSL normally uses the /dev/urandom device for seeding its CSPRNG.
Contrary to getrandom(), the /dev/urandom device will not block during
early boot when the kernel CSPRNG has not been seeded yet.
To mitigate this known weakness, use select() to wait for /dev/random to
become readable before reading from /dev/urandom.
* Ensure that SM2 only uses SM3 as digest algorithm
*Paul Yang*
### Changes between 1.1.1a and 1.1.1b [26 Feb 2019]
* Change the info callback signals for the start and end of a post-handshake
message exchange in TLSv1.3. In 1.1.1/1.1.1a we used SSL_CB_HANDSHAKE_START
and SSL_CB_HANDSHAKE_DONE. Experience has shown that many applications get
confused by this and assume that a TLSv1.2 renegotiation has started. This
can break KeyUpdate handling. Instead we no longer signal the start and end
of a post handshake message exchange (although the messages themselves are
still signalled). This could break some applications that were expecting
the old signals. However without this KeyUpdate is not usable for many
applications.
*Matt Caswell*
### Changes between 1.1.1 and 1.1.1a [20 Nov 2018]
* Timing vulnerability in DSA signature generation
The OpenSSL DSA signature algorithm has been shown to be vulnerable to a
timing side channel attack. An attacker could use variations in the signing
algorithm to recover the private key.
This issue was reported to OpenSSL on 16th October 2018 by Samuel Weiser.
([CVE-2018-0734])
*Paul Dale*
* Timing vulnerability in ECDSA signature generation
The OpenSSL ECDSA signature algorithm has been shown to be vulnerable to a
timing side channel attack. An attacker could use variations in the signing
algorithm to recover the private key.
This issue was reported to OpenSSL on 25th October 2018 by Samuel Weiser.
([CVE-2018-0735])
*Paul Dale*
* Fixed the issue that RAND_add()/RAND_seed() silently discards random input
if its length exceeds 4096 bytes. The limit has been raised to a buffer size
of two gigabytes and the error handling improved.
This issue was reported to OpenSSL by Dr. Falko Strenzke. It has been
categorized as a normal bug, not a security issue, because the DRBG reseeds
automatically and is fully functional even without additional randomness
provided by the application.
### Changes between 1.1.0i and 1.1.1 [11 Sep 2018]
* Add a new ClientHello callback. Provides a callback interface that gives
the application the ability to adjust the nascent SSL object at the
earliest stage of ClientHello processing, immediately after extensions have
been collected but before they have been processed. In particular, this
callback can adjust the supported TLS versions in response to the contents
of the ClientHello
*Benjamin Kaduk*
* Add SM2 base algorithm support.
*Jack Lloyd*
* s390x assembly pack: add (improved) hardware-support for the following
cryptographic primitives: sha3, shake, aes-gcm, aes-ccm, aes-ctr, aes-ofb,
aes-cfb/cfb8, aes-ecb.
*Patrick Steuer*
* Make EVP_PKEY_asn1_new() a bit stricter about its input. A NULL pem_str
parameter is no longer accepted, as it leads to a corrupt table. NULL
pem_str is reserved for alias entries only.
*Richard Levitte*
* Use the new ec_scalar_mul_ladder scaffold to implement a specialized ladder
step for prime curves. The new implementation is based on formulae from
differential addition-and-doubling in homogeneous projective coordinates
from Izu-Takagi "A fast parallel elliptic curve multiplication resistant
against side channel attacks" and Brier-Joye "Weierstrass Elliptic Curves
and Side-Channel Attacks" Eq. (8) for y-coordinate recovery, modified
to work in projective coordinates.
*Billy Bob Brumley, Nicola Tuveri*
* Change generating and checking of primes so that the error rate of not
being prime depends on the intended use based on the size of the input.
For larger primes this will result in more rounds of Miller-Rabin.
The maximal error rate for primes with more than 1080 bits is lowered
to 2^-128.
*Kurt Roeckx, Annie Yousar*
* Increase the number of Miller-Rabin rounds for DSA key generating to 64.
*Kurt Roeckx*
* The 'tsget' script is renamed to 'tsget.pl', to avoid confusion when
moving between systems, and to avoid confusion when a Windows build is
done with mingw vs with MSVC. For POSIX installs, there's still a
symlink or copy named 'tsget' to avoid that confusion as well.
*Richard Levitte*
* Revert blinding in ECDSA sign and instead make problematic addition
length-invariant. Switch even to fixed-length Montgomery multiplication.
*Andy Polyakov*
* Use the new ec_scalar_mul_ladder scaffold to implement a specialized ladder
step for binary curves. The new implementation is based on formulae from
differential addition-and-doubling in mixed Lopez-Dahab projective
coordinates, modified to independently blind the operands.
*Billy Bob Brumley, Sohaib ul Hassan, Nicola Tuveri*
* Add a scaffold to optionally enhance the Montgomery ladder implementation
for `ec_scalar_mul_ladder` (formerly `ec_mul_consttime`) allowing
EC_METHODs to implement their own specialized "ladder step", to take
advantage of more favorable coordinate systems or more efficient
differential addition-and-doubling algorithms.
*Billy Bob Brumley, Sohaib ul Hassan, Nicola Tuveri*
* Modified the random device based seed sources to keep the relevant
file descriptors open rather than reopening them on each access.
This allows such sources to operate in a chroot() jail without
the associated device nodes being available. This behaviour can be
controlled using RAND_keep_random_devices_open().
*Paul Dale*
* Numerous side-channel attack mitigations have been applied. This may have
performance impacts for some algorithms for the benefit of improved
security. Specific changes are noted in this change log by their respective
authors.
*Matt Caswell*
* AIX shared library support overhaul. Switch to AIX "natural" way of
handling shared libraries, which means collecting shared objects of
different versions and bitnesses in one common archive. This allows to
mitigate conflict between 1.0 and 1.1 side-by-side installations. It
doesn't affect the way 3rd party applications are linked, only how
multi-version installation is managed.
*Andy Polyakov*
* Make ec_group_do_inverse_ord() more robust and available to other
EC cryptosystems, so that irrespective of BN_FLG_CONSTTIME, SCA
mitigations are applied to the fallback BN_mod_inverse().
When using this function rather than BN_mod_inverse() directly, new
EC cryptosystem implementations are then safer-by-default.
*Billy Bob Brumley*
* Add coordinate blinding for EC_POINT and implement projective
coordinate blinding for generic prime curves as a countermeasure to
chosen point SCA attacks.
*Sohaib ul Hassan, Nicola Tuveri, Billy Bob Brumley*
* Add blinding to ECDSA and DSA signatures to protect against side channel
attacks discovered by Keegan Ryan (NCC Group).
*Matt Caswell*
* Enforce checking in the `pkeyutl` command to ensure that the input
length does not exceed the maximum supported digest length when performing
a sign, verify or verifyrecover operation.
*Matt Caswell*
* SSL_MODE_AUTO_RETRY is enabled by default. Applications that use blocking
I/O in combination with something like select() or poll() will hang. This
can be turned off again using SSL_CTX_clear_mode().
Many applications do not properly handle non-application data records, and
TLS 1.3 sends more of such records. Setting SSL_MODE_AUTO_RETRY works
around the problems in those applications, but can also break some.
It's recommended to read the manpages about SSL_read(), SSL_write(),
SSL_get_error(), SSL_shutdown(), SSL_CTX_set_mode() and
SSL_CTX_set_read_ahead() again.
*Kurt Roeckx*
* When unlocking a pass phrase protected PEM file or PKCS#8 container, we
now allow empty (zero character) pass phrases.
*Richard Levitte*
* Apply blinding to binary field modular inversion and remove patent
pending (OPENSSL_SUN_GF2M_DIV) BN_GF2m_mod_div implementation.
*Billy Bob Brumley*
* Deprecate ec2_mult.c and unify scalar multiplication code paths for
binary and prime elliptic curves.
*Billy Bob Brumley*
* Remove ECDSA nonce padding: EC_POINT_mul is now responsible for
constant time fixed point multiplication.
*Billy Bob Brumley*
* Revise elliptic curve scalar multiplication with timing attack
defenses: ec_wNAF_mul redirects to a constant time implementation
when computing fixed point and variable point multiplication (which
in OpenSSL are mostly used with secret scalars in keygen, sign,
ECDH derive operations).
*Billy Bob Brumley, Nicola Tuveri, Cesar Pereida García,
Sohaib ul Hassan*
* Updated CONTRIBUTING
*Rich Salz*
* Updated DRBG / RAND to request nonce and additional low entropy
randomness from the system.
*Matthias St. Pierre*
* Updated 'openssl rehash' to use OpenSSL consistent default.
*Richard Levitte*
* Moved the load of the ssl_conf module to libcrypto, which helps
loading engines that libssl uses before libssl is initialised.
*Matt Caswell*
* Added EVP_PKEY_sign() and EVP_PKEY_verify() for EdDSA
*Matt Caswell*
* Fixed X509_NAME_ENTRY_set to get multi-valued RDNs right in all cases.
*Ingo Schwarze, Rich Salz*
* Added output of accepting IP address and port for 'openssl s_server'
*Richard Levitte*
* Added a new API for TLSv1.3 ciphersuites:
SSL_CTX_set_ciphersuites()
SSL_set_ciphersuites()
*Matt Caswell*
* Memory allocation failures consistently add an error to the error
stack.
*Rich Salz*
* Don't use OPENSSL_ENGINES and OPENSSL_CONF environment values
in libcrypto when run as setuid/setgid.
*Bernd Edlinger*
* Load any config file by default when libssl is used.
*Matt Caswell*
* Added new public header file <openssl/rand_drbg.h> 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:
<https://wiki.openssl.org/index.php/TLS1.3>
*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 <jack.lloyd@ribose.com>,*
*Ronald Tse <ronald.tse@ribose.com>,*
*Erick Borsboom <erick.borsboom@ribose.com>*
* 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 <jack.lloyd@ribose.com>,*
*Ronald Tse <ronald.tse@ribose.com>,*
*Erick Borsboom <erick.borsboom@ribose.com>*
* 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 <tmraz@fedoraproject.org>*
* 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
<https://www.akkadia.org/drepper/SHA-crypt.txt>
*Richard Levitte*
* Heartbeat support has been removed; the ABI is changed for now.
*Richard Levitte, Rich Salz*
* Support for SSL_OP_NO_ENCRYPT_THEN_MAC in SSL_CONF_cmd.
*Emilia Käsper*
* The RSA "null" method, which was partially supported to avoid patent
issues, has been replaced to always returns NULL.
*Rich Salz*
OpenSSL 1.1.0
-------------
### Changes between 1.1.0k and 1.1.0l [10 Sep 2019]
* For built-in EC curves, ensure an EC_GROUP built from the curve name is
used even when parsing explicit parameters, when loading a encoded key
or calling `EC_GROUP_new_from_ecpkparameters()`/
`EC_GROUP_new_from_ecparameters()`.
This prevents bypass of security hardening and performance gains,
especially for curves with specialized EC_METHODs.
By default, if a key encoded with explicit parameters is loaded and later
encoded, the output is still encoded with explicit parameters, even if
internally a "named" EC_GROUP is used for computation.
*Nicola Tuveri*
* Compute ECC cofactors if not provided during EC_GROUP construction. Before
this change, EC_GROUP_set_generator would accept order and/or cofactor as
NULL. After this change, only the cofactor parameter can be NULL. It also
does some minimal sanity checks on the passed order.
([CVE-2019-1547])
*Billy Bob Brumley*
* Fixed a padding oracle in PKCS7_dataDecode and CMS_decrypt_set1_pkey.
An attack is simple, if the first CMS_recipientInfo is valid but the
second CMS_recipientInfo is chosen ciphertext. If the second
recipientInfo decodes to PKCS #1 v1.5 form plaintext, the correct
encryption key will be replaced by garbage, and the message cannot be
decoded, but if the RSA decryption fails, the correct encryption key is
used and the recipient will not notice the attack.
As a work around for this potential attack the length of the decrypted
key must be equal to the cipher default key length, in case the
certifiate is not given and all recipientInfo are tried out.
The old behaviour can be re-enabled in the CMS code by setting the
CMS_DEBUG_DECRYPT flag.
([CVE-2019-1563])
*Bernd Edlinger*
* Use Windows installation paths in the mingw builds
Mingw isn't a POSIX environment per se, which means that Windows
paths should be used for installation.
([CVE-2019-1552])
*Richard Levitte*
### Changes between 1.1.0j and 1.1.0k [28 May 2019]
* Change the default RSA, DSA and DH size to 2048 bit instead of 1024.
This changes the size when using the `genpkey` command when no size is given.
It fixes an omission in earlier changes that changed all RSA, DSA and DH
generation commands to use 2048 bits by default.
*Kurt Roeckx*
* Prevent over long nonces in ChaCha20-Poly1305.
ChaCha20-Poly1305 is an AEAD cipher, and requires a unique nonce input
for every encryption operation. RFC 7539 specifies that the nonce value
(IV) should be 96 bits (12 bytes). OpenSSL allows a variable nonce length
and front pads the nonce with 0 bytes if it is less than 12
bytes. However it also incorrectly allows a nonce to be set of up to 16
bytes. In this case only the last 12 bytes are significant and any
additional leading bytes are ignored.
It is a requirement of using this cipher that nonce values are
unique. Messages encrypted using a reused nonce value are susceptible to
serious confidentiality and integrity attacks. If an application changes
the default nonce length to be longer than 12 bytes and then makes a
change to the leading bytes of the nonce expecting the new value to be a
new unique nonce then such an application could inadvertently encrypt
messages with a reused nonce.
Additionally the ignored bytes in a long nonce are not covered by the
integrity guarantee of this cipher. Any application that relies on the
integrity of these ignored leading bytes of a long nonce may be further
affected. Any OpenSSL internal use of this cipher, including in SSL/TLS,
is safe because no such use sets such a long nonce value. However user
applications that use this cipher directly and set a non-default nonce
length to be longer than 12 bytes may be vulnerable.
This issue was reported to OpenSSL on 16th of March 2019 by Joran Dirk
Greef of Ronomon.
([CVE-2019-1543])
*Matt Caswell*
* Added SCA hardening for modular field inversion in EC_GROUP through
a new dedicated field_inv() pointer in EC_METHOD.
This also addresses a leakage affecting conversions from projective
to affine coordinates.
*Billy Bob Brumley, Nicola Tuveri*
* Fix a use after free bug in d2i_X509_PUBKEY when overwriting a
re-used X509_PUBKEY object if the second PUBKEY is malformed.
*Bernd Edlinger*
* Move strictness check from EVP_PKEY_asn1_new() to EVP_PKEY_asn1_add0().
*Richard Levitte*
* Remove the 'dist' target and add a tarball building script. The
'dist' target has fallen out of use, and it shouldn't be
necessary to configure just to create a source distribution.
*Richard Levitte*
### Changes between 1.1.0i and 1.1.0j [20 Nov 2018]
* Timing vulnerability in DSA signature generation
The OpenSSL DSA signature algorithm has been shown to be vulnerable to a
timing side channel attack. An attacker could use variations in the signing
algorithm to recover the private key.
This issue was reported to OpenSSL on 16th October 2018 by Samuel Weiser.
([CVE-2018-0734])
*Paul Dale*
* Timing vulnerability in ECDSA signature generation
The OpenSSL ECDSA signature algorithm has been shown to be vulnerable to a
timing side channel attack. An attacker could use variations in the signing
algorithm to recover the private key.
This issue was reported to OpenSSL on 25th October 2018 by Samuel Weiser.
([CVE-2018-0735])
*Paul Dale*
* Add coordinate blinding for EC_POINT and implement projective
coordinate blinding for generic prime curves as a countermeasure to
chosen point SCA attacks.
*Sohaib ul Hassan, Nicola Tuveri, Billy Bob Brumley*
### Changes between 1.1.0h and 1.1.0i [14 Aug 2018]
* Client DoS due to large DH parameter
During key agreement in a TLS handshake using a DH(E) based ciphersuite a
malicious server can send a very large prime value to the client. This will
cause the client to spend an unreasonably long period of time generating a
key for this prime resulting in a hang until the client has finished. This
could be exploited in a Denial Of Service attack.
This issue was reported to OpenSSL on 5th June 2018 by Guido Vranken
([CVE-2018-0732])
*Guido Vranken*
* Cache timing vulnerability in RSA Key Generation
The OpenSSL RSA Key generation algorithm has been shown to be vulnerable to
a cache timing side channel attack. An attacker with sufficient access to
mount cache timing attacks during the RSA key generation process could
recover the private key.
This issue was reported to OpenSSL on 4th April 2018 by Alejandro Cabrera
Aldaya, Billy Brumley, Cesar Pereida Garcia and Luis Manuel Alvarez Tapia.
([CVE-2018-0737])
*Billy Brumley*
* Make EVP_PKEY_asn1_new() a bit stricter about its input. A NULL pem_str
parameter is no longer accepted, as it leads to a corrupt table. NULL
pem_str is reserved for alias entries only.
*Richard Levitte*
* Revert blinding in ECDSA sign and instead make problematic addition
length-invariant. Switch even to fixed-length Montgomery multiplication.
*Andy Polyakov*
* Change generating and checking of primes so that the error rate of not
being prime depends on the intended use based on the size of the input.
For larger primes this will result in more rounds of Miller-Rabin.
The maximal error rate for primes with more than 1080 bits is lowered
to 2^-128.
*Kurt Roeckx, Annie Yousar*
* Increase the number of Miller-Rabin rounds for DSA key generating to 64.
*Kurt Roeckx*
* Add blinding to ECDSA and DSA signatures to protect against side channel
attacks discovered by Keegan Ryan (NCC Group).
*Matt Caswell*
* When unlocking a pass phrase protected PEM file or PKCS#8 container, we
now allow empty (zero character) pass phrases.
*Richard Levitte*
* Certificate time validation (X509_cmp_time) enforces stricter
compliance with RFC 5280. Fractional seconds and timezone offsets
are no longer allowed.
*Emilia Käsper*
* Fixed a text canonicalisation bug in CMS
Where a CMS detached signature is used with text content the text goes
through a canonicalisation process first prior to signing or verifying a
signature. This process strips trailing space at the end of lines, converts
line terminators to CRLF and removes additional trailing line terminators
at the end of a file. A bug in the canonicalisation process meant that
some characters, such as form-feed, were incorrectly treated as whitespace
and removed. This is contrary to the specification (RFC5485). This fix
could mean that detached text data signed with an earlier version of
OpenSSL 1.1.0 may fail to verify using the fixed version, or text data
signed with a fixed OpenSSL may fail to verify with an earlier version of
OpenSSL 1.1.0. A workaround is to only verify the canonicalised text data
and use the "-binary" flag (for the "cms" command line application) or set
the SMIME_BINARY/PKCS7_BINARY/CMS_BINARY flags (if using CMS_verify()).
*Matt Caswell*
### Changes between 1.1.0g and 1.1.0h [27 Mar 2018]
* Constructed ASN.1 types with a recursive definition could exceed the stack
Constructed ASN.1 types with a recursive definition (such as can be found
in PKCS7) could eventually exceed the stack given malicious input with
excessive recursion. This could result in a Denial Of Service attack. There
are no such structures used within SSL/TLS that come from untrusted sources
so this is considered safe.
This issue was reported to OpenSSL on 4th January 2018 by the OSS-fuzz
project.
([CVE-2018-0739])
*Matt Caswell*
* Incorrect CRYPTO_memcmp on HP-UX PA-RISC
Because of an implementation bug the PA-RISC CRYPTO_memcmp function is
effectively reduced to only comparing the least significant bit of each
byte. This allows an attacker to forge messages that would be considered as
authenticated in an amount of tries lower than that guaranteed by the
security claims of the scheme. The module can only be compiled by the
HP-UX assembler, so that only HP-UX PA-RISC targets are affected.
This issue was reported to OpenSSL on 2nd March 2018 by Peter Waltenberg
(IBM).
([CVE-2018-0733])
*Andy Polyakov*
* Add a build target 'build_all_generated', to build all generated files
and only that. This can be used to prepare everything that requires
things like perl for a system that lacks perl and then move everything
to that system and do the rest of the build there.
*Richard Levitte*
* Backport SSL_OP_NO_RENGOTIATION
OpenSSL 1.0.2 and below had the ability to disable renegotiation using the
(undocumented) SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS flag. Due to the opacity
changes this is no longer possible in 1.1.0. Therefore the new
SSL_OP_NO_RENEGOTIATION option from 1.1.1-dev has been backported to
1.1.0 to provide equivalent functionality.
Note that if an application built against 1.1.0h headers (or above) is run
using an older version of 1.1.0 (prior to 1.1.0h) then the option will be
accepted but nothing will happen, i.e. renegotiation will not be prevented.
*Matt Caswell*
* Removed the OS390-Unix config target. It relied on a script that doesn't
exist.
*Rich Salz*
* rsaz_1024_mul_avx2 overflow bug on x86_64
There is an overflow bug in the AVX2 Montgomery multiplication procedure
used in exponentiation with 1024-bit moduli. No EC algorithms are affected.
Analysis suggests that attacks against RSA and DSA as a result of this
defect would be very difficult to perform and are not believed likely.
Attacks against DH1024 are considered just feasible, because most of the
work necessary to deduce information about a private key may be performed
offline. The amount of resources required for such an attack would be
significant. However, for an attack on TLS to be meaningful, the server
would have to share the DH1024 private key among multiple clients, which is
no longer an option since CVE-2016-0701.
This only affects processors that support the AVX2 but not ADX extensions
like Intel Haswell (4th generation).
This issue was reported to OpenSSL by David Benjamin (Google). The issue
was originally found via the OSS-Fuzz project.
([CVE-2017-3738])
*Andy Polyakov*
### Changes between 1.1.0f and 1.1.0g [2 Nov 2017]
* bn_sqrx8x_internal carry bug on x86_64
There is a carry propagating bug in the x86_64 Montgomery squaring
procedure. No EC algorithms are affected. Analysis suggests that attacks
against RSA and DSA as a result of this defect would be very difficult to
perform and are not believed likely. Attacks against DH are considered just
feasible (although very difficult) because most of the work necessary to
deduce information about a private key may be performed offline. The amount
of resources required for such an attack would be very significant and
likely only accessible to a limited number of attackers. An attacker would
additionally need online access to an unpatched system using the target
private key in a scenario with persistent DH parameters and a private
key that is shared between multiple clients.
This only affects processors that support the BMI1, BMI2 and ADX extensions
like Intel Broadwell (5th generation) and later or AMD Ryzen.
This issue was reported to OpenSSL by the OSS-Fuzz project.
([CVE-2017-3736])
*Andy Polyakov*
* Malformed X.509 IPAddressFamily could cause OOB read
If an X.509 certificate has a malformed IPAddressFamily extension,
OpenSSL could do a one-byte buffer overread. The most likely result
would be an erroneous display of the certificate in text format.
This issue was reported to OpenSSL by the OSS-Fuzz project.
([CVE-2017-3735])
*Rich Salz*
### Changes between 1.1.0e and 1.1.0f [25 May 2017]
* Have 'config' recognise 64-bit mingw and choose 'mingw64' as the target
platform rather than 'mingw'.
*Richard Levitte*
* Remove the VMS-specific reimplementation of gmtime from crypto/o_times.c.
VMS C's RTL has a fully up to date gmtime() and gmtime_r() since V7.1,
which is the minimum version we support.
*Richard Levitte*
### Changes between 1.1.0d and 1.1.0e [16 Feb 2017]
* Encrypt-Then-Mac renegotiation crash
During a renegotiation handshake if the Encrypt-Then-Mac extension is
negotiated where it was not in the original handshake (or vice-versa) then
this can cause OpenSSL to crash (dependant on ciphersuite). Both clients
and servers are affected.
This issue was reported to OpenSSL by Joe Orton (Red Hat).
([CVE-2017-3733])
*Matt Caswell*
### Changes between 1.1.0c and 1.1.0d [26 Jan 2017]
* Truncated packet could crash via OOB read
If one side of an SSL/TLS path is running on a 32-bit host and a specific
cipher is being used, then a truncated packet can cause that host to
perform an out-of-bounds read, usually resulting in a crash.
This issue was reported to OpenSSL by Robert Święcki of Google.
([CVE-2017-3731])
*Andy Polyakov*
* Bad (EC)DHE parameters cause a client crash
If a malicious server supplies bad parameters for a DHE or ECDHE key
exchange then this can result in the client attempting to dereference a
NULL pointer leading to a client crash. This could be exploited in a Denial
of Service attack.
This issue was reported to OpenSSL by Guido Vranken.
([CVE-2017-3730])
*Matt Caswell*
* BN_mod_exp may produce incorrect results on x86_64
There is a carry propagating bug in the x86_64 Montgomery squaring
procedure. No EC algorithms are affected. Analysis suggests that attacks
against RSA and DSA as a result of this defect would be very difficult to
perform and are not believed likely. Attacks against DH are considered just
feasible (although very difficult) because most of the work necessary to
deduce information about a private key may be performed offline. The amount
of resources required for such an attack would be very significant and
likely only accessible to a limited number of attackers. An attacker would
additionally need online access to an unpatched system using the target
private key in a scenario with persistent DH parameters and a private
key that is shared between multiple clients. For example this can occur by
default in OpenSSL DHE based SSL/TLS ciphersuites. Note: This issue is very
similar to CVE-2015-3193 but must be treated as a separate problem.
This issue was reported to OpenSSL by the OSS-Fuzz project.
([CVE-2017-3732])
*Andy Polyakov*
### Changes between 1.1.0b and 1.1.0c [10 Nov 2016]
* ChaCha20/Poly1305 heap-buffer-overflow
TLS connections using `*-CHACHA20-POLY1305` ciphersuites are susceptible to
a DoS attack by corrupting larger payloads. This can result in an OpenSSL
crash. This issue is not considered to be exploitable beyond a DoS.
This issue was reported to OpenSSL by Robert Święcki (Google Security Team)
([CVE-2016-7054])
*Richard Levitte*
* CMS Null dereference
Applications parsing invalid CMS structures can crash with a NULL pointer
dereference. This is caused by a bug in the handling of the ASN.1 CHOICE
type in OpenSSL 1.1.0 which can result in a NULL value being passed to the
structure callback if an attempt is made to free certain invalid encodings.
Only CHOICE structures using a callback which do not handle NULL value are
affected.
This issue was reported to OpenSSL by Tyler Nighswander of ForAllSecure.
([CVE-2016-7053])
*Stephen Henson*
* Montgomery multiplication may produce incorrect results
There is a carry propagating bug in the Broadwell-specific Montgomery
multiplication procedure that handles input lengths divisible by, but
longer than 256 bits. Analysis suggests that attacks against RSA, DSA
and DH private keys are impossible. This is because the subroutine in
question is not used in operations with the private key itself and an input
of the attacker's direct choice. Otherwise the bug can manifest itself as
transient authentication and key negotiation failures or reproducible
erroneous outcome of public-key operations with specially crafted input.
Among EC algorithms only Brainpool P-512 curves are affected and one
presumably can attack ECDH key negotiation. Impact was not analyzed in
detail, because pre-requisites for attack are considered unlikely. Namely
multiple clients have to choose the curve in question and the server has to
share the private key among them, neither of which is default behaviour.
Even then only clients that chose the curve will be affected.
This issue was publicly reported as transient failures and was not
initially recognized as a security issue. Thanks to Richard Morgan for
providing reproducible case.
([CVE-2016-7055])
*Andy Polyakov*
* Removed automatic addition of RPATH in shared libraries and executables,
as this was a remainder from OpenSSL 1.0.x and isn't needed any more.
*Richard Levitte*
### Changes between 1.1.0a and 1.1.0b [26 Sep 2016]
* Fix Use After Free for large message sizes
The patch applied to address CVE-2016-6307 resulted in an issue where if a
message larger than approx 16k is received then the underlying buffer to
store the incoming message is reallocated and moved. Unfortunately a
dangling pointer to the old location is left which results in an attempt to
write to the previously freed location. This is likely to result in a
crash, however it could potentially lead to execution of arbitrary code.
This issue only affects OpenSSL 1.1.0a.
This issue was reported to OpenSSL by Robert Święcki.
([CVE-2016-6309])
*Matt Caswell*
### Changes between 1.1.0 and 1.1.0a [22 Sep 2016]
* OCSP Status Request extension unbounded memory growth
A malicious client can send an excessively large OCSP Status Request
extension. If that client continually requests renegotiation, sending a
large OCSP Status Request extension each time, then there will be unbounded
memory growth on the server. This will eventually lead to a Denial Of
Service attack through memory exhaustion. Servers with a default
configuration are vulnerable even if they do not support OCSP. Builds using
the "no-ocsp" build time option are not affected.
This issue was reported to OpenSSL by Shi Lei (Gear Team, Qihoo 360 Inc.)
([CVE-2016-6304])
*Matt Caswell*
* SSL_peek() hang on empty record
OpenSSL 1.1.0 SSL/TLS will hang during a call to SSL_peek() if the peer
sends an empty record. This could be exploited by a malicious peer in a
Denial Of Service attack.
This issue was reported to OpenSSL by Alex Gaynor.
([CVE-2016-6305])
*Matt Caswell*
* Excessive allocation of memory in tls_get_message_header() and
dtls1_preprocess_fragment()
A (D)TLS message includes 3 bytes for its length in the header for the
message. This would allow for messages up to 16Mb in length. Messages of
this length are excessive and OpenSSL includes a check to ensure that a
peer is sending reasonably sized messages in order to avoid too much memory
being consumed to service a connection. A flaw in the logic of version
1.1.0 means that memory for the message is allocated too early, prior to
the excessive message length check. Due to way memory is allocated in
OpenSSL this could mean an attacker could force up to 21Mb to be allocated
to service a connection. This could lead to a Denial of Service through
memory exhaustion. However, the excessive message length check still takes
place, and this would cause the connection to immediately fail. Assuming
that the application calls SSL_free() on the failed connection in a timely
manner then the 21Mb of allocated memory will then be immediately freed
again. Therefore the excessive memory allocation will be transitory in
nature. This then means that there is only a security impact if:
1) The application does not call SSL_free() in a timely manner in the event
that the connection fails
or
2) The application is working in a constrained environment where there is
very little free memory
or
3) The attacker initiates multiple connection attempts such that there are
multiple connections in a state where memory has been allocated for the
connection; SSL_free() has not yet been called; and there is insufficient
memory to service the multiple requests.
Except in the instance of (1) above any Denial Of Service is likely to be
transitory because as soon as the connection fails the memory is
subsequently freed again in the SSL_free() call. However there is an
increased risk during this period of application crashes due to the lack of
memory - which would then mean a more serious Denial of Service.
This issue was reported to OpenSSL by Shi Lei (Gear Team, Qihoo 360 Inc.)
(CVE-2016-6307 and CVE-2016-6308)
*Matt Caswell*
* solaris-x86-cc, i.e. 32-bit configuration with vendor compiler,
had to be removed. Primary reason is that vendor assembler can't
assemble our modules with -KPIC flag. As result it, assembly
support, was not even available as option. But its lack means
lack of side-channel resistant code, which is incompatible with
security by todays standards. Fortunately gcc is readily available
prepackaged option, which we firmly point at...
*Andy Polyakov*
### Changes between 1.0.2h and 1.1.0 [25 Aug 2016]
* Windows command-line tool supports UTF-8 opt-in option for arguments
and console input. Setting OPENSSL_WIN32_UTF8 environment variable
(to any value) allows Windows user to access PKCS#12 file generated
with Windows CryptoAPI and protected with non-ASCII password, as well
as files generated under UTF-8 locale on Linux also protected with
non-ASCII password.
*Andy Polyakov*
* To mitigate the SWEET32 attack ([CVE-2016-2183]), 3DES cipher suites
have been disabled by default and removed from DEFAULT, just like RC4.
See the RC4 item below to re-enable both.
*Rich Salz*
* The method for finding the storage location for the Windows RAND seed file
has changed. First we check %RANDFILE%. If that is not set then we check
the directories %HOME%, %USERPROFILE% and %SYSTEMROOT% in that order. If
all else fails we fall back to C:\.
*Matt Caswell*
* The EVP_EncryptUpdate() function has had its return type changed from void
to int. A return of 0 indicates and error while a return of 1 indicates
success.
*Matt Caswell*
* The flags RSA_FLAG_NO_CONSTTIME, DSA_FLAG_NO_EXP_CONSTTIME and
DH_FLAG_NO_EXP_CONSTTIME which previously provided the ability to switch
off the constant time implementation for RSA, DSA and DH have been made
no-ops and deprecated.
*Matt Caswell*
* Windows RAND implementation was simplified to only get entropy by
calling CryptGenRandom(). Various other RAND-related tickets
were also closed.
*Joseph Wylie Yandle, Rich Salz*
* The stack and lhash API's were renamed to start with `OPENSSL_SK_`
and `OPENSSL_LH_`, respectively. The old names are available
with API compatibility. They new names are now completely documented.
*Rich Salz*
* Unify TYPE_up_ref(obj) methods signature.
SSL_CTX_up_ref(), SSL_up_ref(), X509_up_ref(), EVP_PKEY_up_ref(),
X509_CRL_up_ref(), X509_OBJECT_up_ref_count() methods are now returning an
int (instead of void) like all others TYPE_up_ref() methods.
So now these methods also check the return value of CRYPTO_atomic_add(),
and the validity of object reference counter.
*fdasilvayy@gmail.com*
* With Windows Visual Studio builds, the .pdb files are installed
alongside the installed libraries and executables. For a static
library installation, ossl_static.pdb is the associate compiler
generated .pdb file to be used when linking programs.
*Richard Levitte*
* Remove openssl.spec. Packaging files belong with the packagers.
*Richard Levitte*
* Automatic Darwin/OSX configuration has had a refresh, it will now
recognise x86_64 architectures automatically. You can still decide
to build for a different bitness with the environment variable
KERNEL_BITS (can be 32 or 64), for example:
KERNEL_BITS=32 ./config
*Richard Levitte*
* Change default algorithms in pkcs8 utility to use PKCS#5 v2.0,
256 bit AES and HMAC with SHA256.
*Steve Henson*
* Remove support for MIPS o32 ABI on IRIX (and IRIX only).
*Andy Polyakov*
* Triple-DES ciphers have been moved from HIGH to MEDIUM.
*Rich Salz*
* To enable users to have their own config files and build file templates,
Configure looks in the directory indicated by the environment variable
OPENSSL_LOCAL_CONFIG_DIR as well as the in-source Configurations/
directory. On VMS, OPENSSL_LOCAL_CONFIG_DIR is expected to be a logical
name and is used as is.
*Richard Levitte*
* The following datatypes were made opaque: X509_OBJECT, X509_STORE_CTX,
X509_STORE, X509_LOOKUP, and X509_LOOKUP_METHOD. The unused type
X509_CERT_FILE_CTX was removed.
*Rich Salz*
* "shared" builds are now the default. To create only static libraries use
the "no-shared" Configure option.
*Matt Caswell*
* Remove the no-aes, no-hmac, no-rsa, no-sha and no-md5 Configure options.
All of these option have not worked for some while and are fundamental
algorithms.
*Matt Caswell*
* Make various cleanup routines no-ops and mark them as deprecated. Most
global cleanup functions are no longer required because they are handled
via auto-deinit (see OPENSSL_init_crypto and OPENSSL_init_ssl man pages).
Explicitly de-initing can cause problems (e.g. where a library that uses
OpenSSL de-inits, but an application is still using it). The affected
functions are CONF_modules_free(), ENGINE_cleanup(), OBJ_cleanup(),
EVP_cleanup(), BIO_sock_cleanup(), CRYPTO_cleanup_all_ex_data(),
RAND_cleanup(), SSL_COMP_free_compression_methods(), ERR_free_strings() and
COMP_zlib_cleanup().
*Matt Caswell*
* --strict-warnings no longer enables runtime debugging options
such as REF_DEBUG. Instead, debug options are automatically
enabled with '--debug' builds.
*Andy Polyakov, Emilia Käsper*
* Made DH and DH_METHOD opaque. The structures for managing DH objects
have been moved out of the public header files. New functions for managing
these have been added.
*Matt Caswell*
* Made RSA and RSA_METHOD opaque. The structures for managing RSA
objects have been moved out of the public header files. New
functions for managing these have been added.
*Richard Levitte*
* Made DSA and DSA_METHOD opaque. The structures for managing DSA objects
have been moved out of the public header files. New functions for managing
these have been added.
*Matt Caswell*
* Made BIO and BIO_METHOD opaque. The structures for managing BIOs have been
moved out of the public header files. New functions for managing these
have been added.
*Matt Caswell*
* Removed no-rijndael as a config option. Rijndael is an old name for AES.
*Matt Caswell*
* Removed the mk1mf build scripts.
*Richard Levitte*
* Headers are now wrapped, if necessary, with OPENSSL_NO_xxx, so
it is always safe to #include a header now.
*Rich Salz*
* Removed the aged BC-32 config and all its supporting scripts
*Richard Levitte*
* Removed support for Ultrix, Netware, and OS/2.
*Rich Salz*
* Add support for HKDF.
*Alessandro Ghedini*
* Add support for blake2b and blake2s
*Bill Cox*
* Added support for "pipelining". Ciphers that have the
EVP_CIPH_FLAG_PIPELINE flag set have a capability to process multiple
encryptions/decryptions simultaneously. There are currently no built-in
ciphers with this property but the expectation is that engines will be able
to offer it to significantly improve throughput. Support has been extended
into libssl so that multiple records for a single connection can be
processed in one go (for >=TLS 1.1).
*Matt Caswell*
* Added the AFALG engine. This is an async capable engine which is able to
offload work to the Linux kernel. In this initial version it only supports
AES128-CBC. The kernel must be version 4.1.0 or greater.
*Catriona Lucey*
* OpenSSL now uses a new threading API. It is no longer necessary to
set locking callbacks to use OpenSSL in a multi-threaded environment. There
are two supported threading models: pthreads and windows threads. It is
also possible to configure OpenSSL at compile time for "no-threads". The
old threading API should no longer be used. The functions have been
replaced with "no-op" compatibility macros.
*Alessandro Ghedini, Matt Caswell*
* Modify behavior of ALPN to invoke callback after SNI/servername
callback, such that updates to the SSL_CTX affect ALPN.
*Todd Short*
* Add SSL_CIPHER queries for authentication and key-exchange.
*Todd Short*
* Changes to the DEFAULT cipherlist:
- Prefer (EC)DHE handshakes over plain RSA.
- Prefer AEAD ciphers over legacy ciphers.
- Prefer ECDSA over RSA when both certificates are available.
- Prefer TLSv1.2 ciphers/PRF.
- Remove DSS, SEED, IDEA, CAMELLIA, and AES-CCM from the
default cipherlist.
*Emilia Käsper*
* Change the ECC default curve list to be this, in order: x25519,
secp256r1, secp521r1, secp384r1.
*Rich Salz*
* RC4 based libssl ciphersuites are now classed as "weak" ciphers and are
disabled by default. They can be re-enabled using the
enable-weak-ssl-ciphers option to Configure.
*Matt Caswell*
* If the server has ALPN configured, but supports no protocols that the
client advertises, send a fatal "no_application_protocol" alert.
This behaviour is SHALL in RFC 7301, though it isn't universally
implemented by other servers.
*Emilia Käsper*
* Add X25519 support.
Add ASN.1 and EVP_PKEY methods for X25519. This includes support
for public and private key encoding using the format documented in
draft-ietf-curdle-pkix-02. The corresponding EVP_PKEY method supports
key generation and key derivation.
TLS support complies with draft-ietf-tls-rfc4492bis-08 and uses
X25519(29).
*Steve Henson*
* Deprecate SRP_VBASE_get_by_user.
SRP_VBASE_get_by_user had inconsistent memory management behaviour.
In order to fix an unavoidable memory leak ([CVE-2016-0798]),
SRP_VBASE_get_by_user was changed to ignore the "fake user" SRP
seed, even if the seed is configured.
Users should use SRP_VBASE_get1_by_user instead. Note that in
SRP_VBASE_get1_by_user, caller must free the returned value. Note
also that even though configuring the SRP seed attempts to hide
invalid usernames by continuing the handshake with fake
credentials, this behaviour is not constant time and no strong
guarantees are made that the handshake is indistinguishable from
that of a valid user.
*Emilia Käsper*
* Configuration change; it's now possible to build dynamic engines
without having to build shared libraries and vice versa. This
only applies to the engines in `engines/`, those in `crypto/engine/`
will always be built into libcrypto (i.e. "static").
Building dynamic engines is enabled by default; to disable, use
the configuration option "disable-dynamic-engine".
The only requirements for building dynamic engines are the
presence of the DSO module and building with position independent
code, so they will also automatically be disabled if configuring
with "disable-dso" or "disable-pic".
The macros OPENSSL_NO_STATIC_ENGINE and OPENSSL_NO_DYNAMIC_ENGINE
are also taken away from openssl/opensslconf.h, as they are
irrelevant.
*Richard Levitte*
* Configuration change; if there is a known flag to compile
position independent code, it will always be applied on the
libcrypto and libssl object files, and never on the application
object files. This means other libraries that use routines from
libcrypto / libssl can be made into shared libraries regardless
of how OpenSSL was configured.
If this isn't desirable, the configuration options "disable-pic"
or "no-pic" can be used to disable the use of PIC. This will
also disable building shared libraries and dynamic engines.
*Richard Levitte*
* Removed JPAKE code. It was experimental and has no wide use.
*Rich Salz*
* The INSTALL_PREFIX Makefile variable has been renamed to
DESTDIR. That makes for less confusion on what this variable
is for. Also, the configuration option --install_prefix is
removed.
*Richard Levitte*
* Heartbeat for TLS has been removed and is disabled by default
for DTLS; configure with enable-heartbeats. Code that uses the
old #define's might need to be updated.
*Emilia Käsper, Rich Salz*
* Rename REF_CHECK to REF_DEBUG.
*Rich Salz*
* New "unified" build system
The "unified" build system is aimed to be a common system for all
platforms we support. With it comes new support for VMS.
This system builds supports building in a different directory tree
than the source tree. It produces one Makefile (for unix family
or lookalikes), or one descrip.mms (for VMS).
The source of information to make the Makefile / descrip.mms is
small files called 'build.info', holding the necessary
information for each directory with source to compile, and a
template in Configurations, like unix-Makefile.tmpl or
descrip.mms.tmpl.
With this change, the library names were also renamed on Windows
and on VMS. They now have names that are closer to the standard
on Unix, and include the major version number, and in certain
cases, the architecture they are built for. See "Notes on shared
libraries" in INSTALL.
We rely heavily on the perl module Text::Template.
*Richard Levitte*
* Added support for auto-initialisation and de-initialisation of the library.
OpenSSL no longer requires explicit init or deinit routines to be called,
except in certain circumstances. See the OPENSSL_init_crypto() and
OPENSSL_init_ssl() man pages for further information.
*Matt Caswell*
* The arguments to the DTLSv1_listen function have changed. Specifically the
"peer" argument is now expected to be a BIO_ADDR object.
* Rewrite of BIO networking library. The BIO library lacked consistent
support of IPv6, and adding it required some more extensive
modifications. This introduces the BIO_ADDR and BIO_ADDRINFO types,
which hold all types of addresses and chains of address information.
It also introduces a new API, with functions like BIO_socket,
BIO_connect, BIO_listen, BIO_lookup and a rewrite of BIO_accept.
The source/sink BIOs BIO_s_connect, BIO_s_accept and BIO_s_datagram
have been adapted accordingly.
*Richard Levitte*
* RSA_padding_check_PKCS1_type_1 now accepts inputs with and without
the leading 0-byte.
*Emilia Käsper*
* CRIME protection: disable compression by default, even if OpenSSL is
compiled with zlib enabled. Applications can still enable compression
by calling SSL_CTX_clear_options(ctx, SSL_OP_NO_COMPRESSION), or by
using the SSL_CONF library to configure compression.
*Emilia Käsper*
* The signature of the session callback configured with
SSL_CTX_sess_set_get_cb was changed. The read-only input buffer
was explicitly marked as `const unsigned char*` instead of
`unsigned char*`.
*Emilia Käsper*
* Always DPURIFY. Remove the use of uninitialized memory in the
RNG, and other conditional uses of DPURIFY. This makes -DPURIFY a no-op.
*Emilia Käsper*
* Removed many obsolete configuration items, including
DES_PTR, DES_RISC1, DES_RISC2, DES_INT
MD2_CHAR, MD2_INT, MD2_LONG
BF_PTR, BF_PTR2
IDEA_SHORT, IDEA_LONG
RC2_SHORT, RC2_LONG, RC4_LONG, RC4_CHUNK, RC4_INDEX
*Rich Salz, with advice from Andy Polyakov*
* Many BN internals have been moved to an internal header file.
*Rich Salz with help from Andy Polyakov*
* Configuration and writing out the results from it has changed.
Files such as Makefile include/openssl/opensslconf.h and are now
produced through general templates, such as Makefile.in and
crypto/opensslconf.h.in and some help from the perl module
Text::Template.
Also, the center of configuration information is no longer
Makefile. Instead, Configure produces a perl module in
configdata.pm which holds most of the config data (in the hash
table %config), the target data that comes from the target
configuration in one of the `Configurations/*.conf` files (in
%target).
*Richard Levitte*
* To clarify their intended purposes, the Configure options
--prefix and --openssldir change their semantics, and become more
straightforward and less interdependent.
--prefix shall be used exclusively to give the location INSTALLTOP
where programs, scripts, libraries, include files and manuals are
going to be installed. The default is now /usr/local.
--openssldir shall be used exclusively to give the default
location OPENSSLDIR where certificates, private keys, CRLs are
managed. This is also where the default openssl.cnf gets
installed.
If the directory given with this option is a relative path, the
values of both the --prefix value and the --openssldir value will
be combined to become OPENSSLDIR.
The default for --openssldir is INSTALLTOP/ssl.
Anyone who uses --openssldir to specify where OpenSSL is to be
installed MUST change to use --prefix instead.
*Richard Levitte*
* The GOST engine was out of date and therefore it has been removed. An up
to date GOST engine is now being maintained in an external repository.
See: <https://wiki.openssl.org/index.php/Binaries>. 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 <David.Woodhouse@intel.com> and also*
*Ivan Nestlerode <ivan.nestlerode@sonos.com>*
* 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 <ismo.puustinen@intel.com>*
* 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 <https://www.openssl.org/source/OCB-patent-grant-OpenSSL.pdf>. Support
for OCB can be removed by calling config with no-ocb.
*Matt Caswell*
* SSLv2 support has been removed. It still supports receiving a SSLv2
compatible client hello.
*Kurt Roeckx*
* Increased the minimal RSA keysize from 256 to 512 bits [Rich Salz],
done while fixing the error code for the key-too-small case.
*Annie Yousar <a.yousar@informatik.hu-berlin.de>*
* 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 <felix@erbridge.co.uk>*
* 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 <martin@kaiser.cx>*
* Harmonize version and its documentation. -f flag is used to display
compilation flags.
*mancha <mancha1@zoho.com>*
* 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 <mancha1@zoho.com>*
* Fix some double frees. These are not thought to be exploitable.
*mancha <mancha1@zoho.com>*
* 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 <agl@chromium.org> and Bodo Moeller <bmoeller@acm.org> for
preparing the fix ([CVE-2014-0160])
*Adam Langley, Bodo Moeller*
* Fix for the attack described in the paper "Recovering OpenSSL
ECDSA Nonces Using the FLUSH+RELOAD Cache Side-channel Attack"
by Yuval Yarom and Naomi Benger. Details can be obtained from:
<http://eprint.iacr.org/2014/140>
Thanks to Yuval Yarom and Naomi Benger for discovering this
flaw and to Yuval Yarom for supplying a fix ([CVE-2014-0076])
*Yuval Yarom and Naomi Benger*
* 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 <palmer@google.com> 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 <emilia.kasper@esat.kuleuven.be> (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 <robpercival@google.com>*
OpenSSL 1.0.2
-------------
### Changes between 1.0.2s and 1.0.2t [10 Sep 2019]
* For built-in EC curves, ensure an EC_GROUP built from the curve name is
used even when parsing explicit parameters, when loading a encoded key
or calling `EC_GROUP_new_from_ecpkparameters()`/
`EC_GROUP_new_from_ecparameters()`.
This prevents bypass of security hardening and performance gains,
especially for curves with specialized EC_METHODs.
By default, if a key encoded with explicit parameters is loaded and later
encoded, the output is still encoded with explicit parameters, even if
internally a "named" EC_GROUP is used for computation.
*Nicola Tuveri*
* Compute ECC cofactors if not provided during EC_GROUP construction. Before
this change, EC_GROUP_set_generator would accept order and/or cofactor as
NULL. After this change, only the cofactor parameter can be NULL. It also
does some minimal sanity checks on the passed order.
([CVE-2019-1547])
*Billy Bob Brumley*
* Fixed a padding oracle in PKCS7_dataDecode and CMS_decrypt_set1_pkey.
An attack is simple, if the first CMS_recipientInfo is valid but the
second CMS_recipientInfo is chosen ciphertext. If the second
recipientInfo decodes to PKCS #1 v1.5 form plaintext, the correct
encryption key will be replaced by garbage, and the message cannot be
decoded, but if the RSA decryption fails, the correct encryption key is
used and the recipient will not notice the attack.
As a work around for this potential attack the length of the decrypted
key must be equal to the cipher default key length, in case the
certifiate is not given and all recipientInfo are tried out.
The old behaviour can be re-enabled in the CMS code by setting the
CMS_DEBUG_DECRYPT flag.
([CVE-2019-1563])
*Bernd Edlinger*
* Document issue with installation paths in diverse Windows builds
'/usr/local/ssl' is an unsafe prefix for location to install OpenSSL
binaries and run-time config file.
([CVE-2019-1552])
*Richard Levitte*
### Changes between 1.0.2r and 1.0.2s [28 May 2019]
* Change the default RSA, DSA and DH size to 2048 bit instead of 1024.
This changes the size when using the `genpkey` command when no size is given.
It fixes an omission in earlier changes that changed all RSA, DSA and DH
generation commands to use 2048 bits by default.
*Kurt Roeckx*
* Add FIPS support for Android Arm 64-bit
Support for Android Arm 64-bit was added to the OpenSSL FIPS Object
Module in Version 2.0.10. For some reason, the corresponding target
'android64-aarch64' was missing OpenSSL 1.0.2, whence it could not be
built with FIPS support on Android Arm 64-bit. This omission has been
fixed.
*Matthias St. Pierre*
### Changes between 1.0.2q and 1.0.2r [26 Feb 2019]
* 0-byte record padding oracle
If an application encounters a fatal protocol error and then calls
SSL_shutdown() twice (once to send a close_notify, and once to receive one)
then OpenSSL can respond differently to the calling application if a 0 byte
record is received with invalid padding compared to if a 0 byte record is
received with an invalid MAC. If the application then behaves differently
based on that in a way that is detectable to the remote peer, then this
amounts to a padding oracle that could be used to decrypt data.
In order for this to be exploitable "non-stitched" ciphersuites must be in
use. Stitched ciphersuites are optimised implementations of certain
commonly used ciphersuites. Also the application must call SSL_shutdown()
twice even if a protocol error has occurred (applications should not do
this but some do anyway).
This issue was discovered by Juraj Somorovsky, Robert Merget and Nimrod
Aviram, with additional investigation by Steven Collison and Andrew
Hourselt. It was reported to OpenSSL on 10th December 2018.
([CVE-2019-1559])
*Matt Caswell*
* Move strictness check from EVP_PKEY_asn1_new() to EVP_PKEY_asn1_add0().
*Richard Levitte*
### Changes between 1.0.2p and 1.0.2q [20 Nov 2018]
* Microarchitecture timing vulnerability in ECC scalar multiplication
OpenSSL ECC scalar multiplication, used in e.g. ECDSA and ECDH, has been
shown to be vulnerable to a microarchitecture timing side channel attack.
An attacker with sufficient access to mount local timing attacks during
ECDSA signature generation could recover the private key.
This issue was reported to OpenSSL on 26th October 2018 by Alejandro
Cabrera Aldaya, Billy Brumley, Sohaib ul Hassan, Cesar Pereida Garcia and
Nicola Tuveri.
([CVE-2018-5407])
*Billy Brumley*
* Timing vulnerability in DSA signature generation
The OpenSSL DSA signature algorithm has been shown to be vulnerable to a
timing side channel attack. An attacker could use variations in the signing
algorithm to recover the private key.
This issue was reported to OpenSSL on 16th October 2018 by Samuel Weiser.
([CVE-2018-0734])
*Paul Dale*
* Resolve a compatibility issue in EC_GROUP handling with the FIPS Object
Module, accidentally introduced while backporting security fixes from the
development branch and hindering the use of ECC in FIPS mode.
*Nicola Tuveri*
### Changes between 1.0.2o and 1.0.2p [14 Aug 2018]
* Client DoS due to large DH parameter
During key agreement in a TLS handshake using a DH(E) based ciphersuite a
malicious server can send a very large prime value to the client. This will
cause the client to spend an unreasonably long period of time generating a
key for this prime resulting in a hang until the client has finished. This
could be exploited in a Denial Of Service attack.
This issue was reported to OpenSSL on 5th June 2018 by Guido Vranken
([CVE-2018-0732])
*Guido Vranken*
* Cache timing vulnerability in RSA Key Generation
The OpenSSL RSA Key generation algorithm has been shown to be vulnerable to
a cache timing side channel attack. An attacker with sufficient access to
mount cache timing attacks during the RSA key generation process could
recover the private key.
This issue was reported to OpenSSL on 4th April 2018 by Alejandro Cabrera
Aldaya, Billy Brumley, Cesar Pereida Garcia and Luis Manuel Alvarez Tapia.
([CVE-2018-0737])
*Billy Brumley*
* Make EVP_PKEY_asn1_new() a bit stricter about its input. A NULL pem_str
parameter is no longer accepted, as it leads to a corrupt table. NULL
pem_str is reserved for alias entries only.
*Richard Levitte*
* Revert blinding in ECDSA sign and instead make problematic addition
length-invariant. Switch even to fixed-length Montgomery multiplication.
*Andy Polyakov*
* Change generating and checking of primes so that the error rate of not
being prime depends on the intended use based on the size of the input.
For larger primes this will result in more rounds of Miller-Rabin.
The maximal error rate for primes with more than 1080 bits is lowered
to 2^-128.
*Kurt Roeckx, Annie Yousar*
* Increase the number of Miller-Rabin rounds for DSA key generating to 64.
*Kurt Roeckx*
* Add blinding to ECDSA and DSA signatures to protect against side channel
attacks discovered by Keegan Ryan (NCC Group).
*Matt Caswell*
* When unlocking a pass phrase protected PEM file or PKCS#8 container, we
now allow empty (zero character) pass phrases.
*Richard Levitte*
* Certificate time validation (X509_cmp_time) enforces stricter
compliance with RFC 5280. Fractional seconds and timezone offsets
are no longer allowed.
*Emilia Käsper*
### Changes between 1.0.2n and 1.0.2o [27 Mar 2018]
* Constructed ASN.1 types with a recursive definition could exceed the stack
Constructed ASN.1 types with a recursive definition (such as can be found
in PKCS7) could eventually exceed the stack given malicious input with
excessive recursion. This could result in a Denial Of Service attack. There
are no such structures used within SSL/TLS that come from untrusted sources
so this is considered safe.
This issue was reported to OpenSSL on 4th January 2018 by the OSS-fuzz
project.
([CVE-2018-0739])
*Matt Caswell*
### Changes between 1.0.2m and 1.0.2n [7 Dec 2017]
* Read/write after SSL object in error state
OpenSSL 1.0.2 (starting from version 1.0.2b) introduced an "error state"
mechanism. The intent was that if a fatal error occurred during a handshake
then OpenSSL would move into the error state and would immediately fail if
you attempted to continue the handshake. This works as designed for the
explicit handshake functions (SSL_do_handshake(), SSL_accept() and
SSL_connect()), however due to a bug it does not work correctly if
SSL_read() or SSL_write() is called directly. In that scenario, if the
handshake fails then a fatal error will be returned in the initial function
call. If SSL_read()/SSL_write() is subsequently called by the application
for the same SSL object then it will succeed and the data is passed without
being decrypted/encrypted directly from the SSL/TLS record layer.
In order to exploit this issue an application bug would have to be present
that resulted in a call to SSL_read()/SSL_write() being issued after having
already received a fatal error.
This issue was reported to OpenSSL by David Benjamin (Google).
([CVE-2017-3737])
*Matt Caswell*
* rsaz_1024_mul_avx2 overflow bug on x86_64
There is an overflow bug in the AVX2 Montgomery multiplication procedure
used in exponentiation with 1024-bit moduli. No EC algorithms are affected.
Analysis suggests that attacks against RSA and DSA as a result of this
defect would be very difficult to perform and are not believed likely.
Attacks against DH1024 are considered just feasible, because most of the
work necessary to deduce information about a private key may be performed
offline. The amount of resources required for such an attack would be
significant. However, for an attack on TLS to be meaningful, the server
would have to share the DH1024 private key among multiple clients, which is
no longer an option since CVE-2016-0701.
This only affects processors that support the AVX2 but not ADX extensions
like Intel Haswell (4th generation).
This issue was reported to OpenSSL by David Benjamin (Google). The issue
was originally found via the OSS-Fuzz project.
([CVE-2017-3738])
*Andy Polyakov*
### Changes between 1.0.2l and 1.0.2m [2 Nov 2017]
* bn_sqrx8x_internal carry bug on x86_64
There is a carry propagating bug in the x86_64 Montgomery squaring
procedure. No EC algorithms are affected. Analysis suggests that attacks
against RSA and DSA as a result of this defect would be very difficult to
perform and are not believed likely. Attacks against DH are considered just
feasible (although very difficult) because most of the work necessary to
deduce information about a private key may be performed offline. The amount
of resources required for such an attack would be very significant and
likely only accessible to a limited number of attackers. An attacker would
additionally need online access to an unpatched system using the target
private key in a scenario with persistent DH parameters and a private
key that is shared between multiple clients.
This only affects processors that support the BMI1, BMI2 and ADX extensions
like Intel Broadwell (5th generation) and later or AMD Ryzen.
This issue was reported to OpenSSL by the OSS-Fuzz project.
([CVE-2017-3736])
*Andy Polyakov*
* Malformed X.509 IPAddressFamily could cause OOB read
If an X.509 certificate has a malformed IPAddressFamily extension,
OpenSSL could do a one-byte buffer overread. The most likely result
would be an erroneous display of the certificate in text format.
This issue was reported to OpenSSL by the OSS-Fuzz project.
*Rich Salz*
### Changes between 1.0.2k and 1.0.2l [25 May 2017]
* Have 'config' recognise 64-bit mingw and choose 'mingw64' as the target
platform rather than 'mingw'.
*Richard Levitte*
### Changes between 1.0.2j and 1.0.2k [26 Jan 2017]
* Truncated packet could crash via OOB read
If one side of an SSL/TLS path is running on a 32-bit host and a specific
cipher is being used, then a truncated packet can cause that host to
perform an out-of-bounds read, usually resulting in a crash.
This issue was reported to OpenSSL by Robert Święcki of Google.
([CVE-2017-3731])
*Andy Polyakov*
* BN_mod_exp may produce incorrect results on x86_64
There is a carry propagating bug in the x86_64 Montgomery squaring
procedure. No EC algorithms are affected. Analysis suggests that attacks
against RSA and DSA as a result of this defect would be very difficult to
perform and are not believed likely. Attacks against DH are considered just
feasible (although very difficult) because most of the work necessary to
deduce information about a private key may be performed offline. The amount
of resources required for such an attack would be very significant and
likely only accessible to a limited number of attackers. An attacker would
additionally need online access to an unpatched system using the target
private key in a scenario with persistent DH parameters and a private
key that is shared between multiple clients. For example this can occur by
default in OpenSSL DHE based SSL/TLS ciphersuites. Note: This issue is very
similar to CVE-2015-3193 but must be treated as a separate problem.
This issue was reported to OpenSSL by the OSS-Fuzz project.
([CVE-2017-3732])
*Andy Polyakov*
* Montgomery multiplication may produce incorrect results
There is a carry propagating bug in the Broadwell-specific Montgomery
multiplication procedure that handles input lengths divisible by, but
longer than 256 bits. Analysis suggests that attacks against RSA, DSA
and DH private keys are impossible. This is because the subroutine in
question is not used in operations with the private key itself and an input
of the attacker's direct choice. Otherwise the bug can manifest itself as
transient authentication and key negotiation failures or reproducible
erroneous outcome of public-key operations with specially crafted input.
Among EC algorithms only Brainpool P-512 curves are affected and one
presumably can attack ECDH key negotiation. Impact was not analyzed in
detail, because pre-requisites for attack are considered unlikely. Namely
multiple clients have to choose the curve in question and the server has to
share the private key among them, neither of which is default behaviour.
Even then only clients that chose the curve will be affected.
This issue was publicly reported as transient failures and was not
initially recognized as a security issue. Thanks to Richard Morgan for
providing reproducible case.
([CVE-2016-7055])
*Andy Polyakov*
* OpenSSL now fails if it receives an unrecognised record type in TLS1.0
or TLS1.1. Previously this only happened in SSLv3 and TLS1.2. This is to
prevent issues where no progress is being made and the peer continually
sends unrecognised record types, using up resources processing them.
*Matt Caswell*
### Changes between 1.0.2i and 1.0.2j [26 Sep 2016]
* Missing CRL sanity check
A bug fix which included a CRL sanity check was added to OpenSSL 1.1.0
but was omitted from OpenSSL 1.0.2i. As a result any attempt to use
CRLs in OpenSSL 1.0.2i will crash with a null pointer exception.
This issue only affects the OpenSSL 1.0.2i
([CVE-2016-7052])
*Matt Caswell*
### Changes between 1.0.2h and 1.0.2i [22 Sep 2016]
* OCSP Status Request extension unbounded memory growth
A malicious client can send an excessively large OCSP Status Request
extension. If that client continually requests renegotiation, sending a
large OCSP Status Request extension each time, then there will be unbounded
memory growth on the server. This will eventually lead to a Denial Of
Service attack through memory exhaustion. Servers with a default
configuration are vulnerable even if they do not support OCSP. Builds using
the "no-ocsp" build time option are not affected.
This issue was reported to OpenSSL by Shi Lei (Gear Team, Qihoo 360 Inc.)
([CVE-2016-6304])
*Matt Caswell*
* In order to mitigate the SWEET32 attack, the DES ciphers were moved from
HIGH to MEDIUM.
This issue was reported to OpenSSL Karthikeyan Bhargavan and Gaetan
Leurent (INRIA)
([CVE-2016-2183])
*Rich Salz*
* OOB write in MDC2_Update()
An overflow can occur in MDC2_Update() either if called directly or
through the EVP_DigestUpdate() function using MDC2. If an attacker
is able to supply very large amounts of input data after a previous
call to EVP_EncryptUpdate() with a partial block then a length check
can overflow resulting in a heap corruption.
The amount of data needed is comparable to SIZE_MAX which is impractical
on most platforms.
This issue was reported to OpenSSL by Shi Lei (Gear Team, Qihoo 360 Inc.)
([CVE-2016-6303])
*Stephen Henson*
* Malformed SHA512 ticket DoS
If a server uses SHA512 for TLS session ticket HMAC it is vulnerable to a
DoS attack where a malformed ticket will result in an OOB read which will
ultimately crash.
The use of SHA512 in TLS session tickets is comparatively rare as it requires
a custom server callback and ticket lookup mechanism.
This issue was reported to OpenSSL by Shi Lei (Gear Team, Qihoo 360 Inc.)
([CVE-2016-6302])
*Stephen Henson*
* OOB write in BN_bn2dec()
The function BN_bn2dec() does not check the return value of BN_div_word().
This can cause an OOB write if an application uses this function with an
overly large BIGNUM. This could be a problem if an overly large certificate
or CRL is printed out from an untrusted source. TLS is not affected because
record limits will reject an oversized certificate before it is parsed.
This issue was reported to OpenSSL by Shi Lei (Gear Team, Qihoo 360 Inc.)
([CVE-2016-2182])
*Stephen Henson*
* OOB read in TS_OBJ_print_bio()
The function TS_OBJ_print_bio() misuses OBJ_obj2txt(): the return value is
the total length the OID text representation would use and not the amount
of data written. This will result in OOB reads when large OIDs are
presented.
This issue was reported to OpenSSL by Shi Lei (Gear Team, Qihoo 360 Inc.)
([CVE-2016-2180])
*Stephen Henson*
* Pointer arithmetic undefined behaviour
Avoid some undefined pointer arithmetic
A common idiom in the codebase is to check limits in the following manner:
"p + len > limit"
Where "p" points to some malloc'd data of SIZE bytes and
limit == p + SIZE
"len" here could be from some externally supplied data (e.g. from a TLS
message).
The rules of C pointer arithmetic are such that "p + len" is only well
defined where len <= SIZE. Therefore the above idiom is actually
undefined behaviour.
For example this could cause problems if some malloc implementation
provides an address for "p" such that "p + len" actually overflows for
values of len that are too big and therefore p + len < limit.
This issue was reported to OpenSSL by Guido Vranken
([CVE-2016-2177])
*Matt Caswell*
* Constant time flag not preserved in DSA signing
Operations in the DSA signing algorithm should run in constant time in
order to avoid side channel attacks. A flaw in the OpenSSL DSA
implementation means that a non-constant time codepath is followed for
certain operations. This has been demonstrated through a cache-timing
attack to be sufficient for an attacker to recover the private DSA key.
This issue was reported by César Pereida (Aalto University), Billy Brumley
(Tampere University of Technology), and Yuval Yarom (The University of
Adelaide and NICTA).
([CVE-2016-2178])
*César Pereida*
* DTLS buffered message DoS
In a DTLS connection where handshake messages are delivered out-of-order
those messages that OpenSSL is not yet ready to process will be buffered
for later use. Under certain circumstances, a flaw in the logic means that
those messages do not get removed from the buffer even though the handshake
has been completed. An attacker could force up to approx. 15 messages to
remain in the buffer when they are no longer required. These messages will
be cleared when the DTLS connection is closed. The default maximum size for
a message is 100k. Therefore the attacker could force an additional 1500k
to be consumed per connection. By opening many simulataneous connections an
attacker could cause a DoS attack through memory exhaustion.
This issue was reported to OpenSSL by Quan Luo.
([CVE-2016-2179])
*Matt Caswell*
* DTLS replay protection DoS
A flaw in the DTLS replay attack protection mechanism means that records
that arrive for future epochs update the replay protection "window" before
the MAC for the record has been validated. This could be exploited by an
attacker by sending a record for the next epoch (which does not have to
decrypt or have a valid MAC), with a very large sequence number. This means
that all subsequent legitimate packets are dropped causing a denial of
service for a specific DTLS connection.
This issue was reported to OpenSSL by the OCAP audit team.
([CVE-2016-2181])
*Matt Caswell*
* Certificate message OOB reads
In OpenSSL 1.0.2 and earlier some missing message length checks can result
in OOB reads of up to 2 bytes beyond an allocated buffer. There is a
theoretical DoS risk but this has not been observed in practice on common
platforms.
The messages affected are client certificate, client certificate request
and server certificate. As a result the attack can only be performed
against a client or a server which enables client authentication.
This issue was reported to OpenSSL by Shi Lei (Gear Team, Qihoo 360 Inc.)
([CVE-2016-6306])
*Stephen Henson*
### Changes between 1.0.2g and 1.0.2h [3 May 2016]
* Prevent padding oracle in AES-NI CBC MAC check
A MITM attacker can use a padding oracle attack to decrypt traffic
when the connection uses an AES CBC cipher and the server support
AES-NI.
This issue was introduced as part of the fix for Lucky 13 padding
attack ([CVE-2013-0169]). The padding check was rewritten to be in
constant time by making sure that always the same bytes are read and
compared against either the MAC or padding bytes. But it no longer
checked that there was enough data to have both the MAC and padding
bytes.
This issue was reported by Juraj Somorovsky using TLS-Attacker.
*Kurt Roeckx*
* Fix EVP_EncodeUpdate overflow
An overflow can occur in the EVP_EncodeUpdate() function which is used for
Base64 encoding of binary data. If an attacker is able to supply very large
amounts of input data then a length check can overflow resulting in a heap
corruption.
Internally to OpenSSL the EVP_EncodeUpdate() function is primarily used by
the `PEM_write_bio*` family of functions. These are mainly used within the
OpenSSL command line applications, so any application which processes data
from an untrusted source and outputs it as a PEM file should be considered
vulnerable to this issue. User applications that call these APIs directly
with large amounts of untrusted data may also be vulnerable.
This issue was reported by Guido Vranken.
([CVE-2016-2105])
*Matt Caswell*
* Fix EVP_EncryptUpdate overflow
An overflow can occur in the EVP_EncryptUpdate() function. If an attacker
is able to supply very large amounts of input data after a previous call to
EVP_EncryptUpdate() with a partial block then a length check can overflow
resulting in a heap corruption. Following an analysis of all OpenSSL
internal usage of the EVP_EncryptUpdate() function all usage is one of two
forms. The first form is where the EVP_EncryptUpdate() call is known to be
the first called function after an EVP_EncryptInit(), and therefore that
specific call must be safe. The second form is where the length passed to
EVP_EncryptUpdate() can be seen from the code to be some small value and
therefore there is no possibility of an overflow. Since all instances are
one of these two forms, it is believed that there can be no overflows in
internal code due to this problem. It should be noted that
EVP_DecryptUpdate() can call EVP_EncryptUpdate() in certain code paths.
Also EVP_CipherUpdate() is a synonym for EVP_EncryptUpdate(). All instances
of these calls have also been analysed too and it is believed there are no
instances in internal usage where an overflow could occur.
This issue was reported by Guido Vranken.
([CVE-2016-2106])
*Matt Caswell*
* Prevent ASN.1 BIO excessive memory allocation
When ASN.1 data is read from a BIO using functions such as d2i_CMS_bio()
a short invalid encoding can cause allocation of large amounts of memory
potentially consuming excessive resources or exhausting memory.
Any application parsing untrusted data through d2i BIO functions is
affected. The memory based functions such as d2i_X509() are *not* affected.
Since the memory based functions are used by the TLS library, TLS
applications are not affected.
This issue was reported by Brian Carpenter.
([CVE-2016-2109])
*Stephen Henson*
* EBCDIC overread
ASN1 Strings that are over 1024 bytes can cause an overread in applications
using the X509_NAME_oneline() function on EBCDIC systems. This could result
in arbitrary stack data being returned in the buffer.
This issue was reported by Guido Vranken.
([CVE-2016-2176])
*Matt Caswell*
* Modify behavior of ALPN to invoke callback after SNI/servername
callback, such that updates to the SSL_CTX affect ALPN.
*Todd Short*
* Remove LOW from the DEFAULT cipher list. This removes singles DES from the
default.
*Kurt Roeckx*
* Only remove the SSLv2 methods with the no-ssl2-method option. When the
methods are enabled and ssl2 is disabled the methods return NULL.
*Kurt Roeckx*
### Changes between 1.0.2f and 1.0.2g [1 Mar 2016]
* Disable weak ciphers in SSLv3 and up in default builds of OpenSSL.
Builds that are not configured with "enable-weak-ssl-ciphers" will not
provide any "EXPORT" or "LOW" strength ciphers.
*Viktor Dukhovni*
* Disable SSLv2 default build, default negotiation and weak ciphers. SSLv2
is by default disabled at build-time. Builds that are not configured with
"enable-ssl2" will not support SSLv2. Even if "enable-ssl2" is used,
users who want to negotiate SSLv2 via the version-flexible SSLv23_method()
will need to explicitly call either of:
SSL_CTX_clear_options(ctx, SSL_OP_NO_SSLv2);
or
SSL_clear_options(ssl, SSL_OP_NO_SSLv2);
as appropriate. Even if either of those is used, or the application
explicitly uses the version-specific SSLv2_method() or its client and
server variants, SSLv2 ciphers vulnerable to exhaustive search key
recovery have been removed. Specifically, the SSLv2 40-bit EXPORT
ciphers, and SSLv2 56-bit DES are no longer available.
([CVE-2016-0800])
*Viktor Dukhovni*
* Fix a double-free in DSA code
A double free bug was discovered when OpenSSL parses malformed DSA private
keys and could lead to a DoS attack or memory corruption for applications
that receive DSA private keys from untrusted sources. This scenario is
considered rare.
This issue was reported to OpenSSL by Adam Langley(Google/BoringSSL) using
libFuzzer.
([CVE-2016-0705])
*Stephen Henson*
* Disable SRP fake user seed to address a server memory leak.
Add a new method SRP_VBASE_get1_by_user that handles the seed properly.
SRP_VBASE_get_by_user had inconsistent memory management behaviour.
In order to fix an unavoidable memory leak, SRP_VBASE_get_by_user
was changed to ignore the "fake user" SRP seed, even if the seed
is configured.
Users should use SRP_VBASE_get1_by_user instead. Note that in
SRP_VBASE_get1_by_user, caller must free the returned value. Note
also that even though configuring the SRP seed attempts to hide
invalid usernames by continuing the handshake with fake
credentials, this behaviour is not constant time and no strong
guarantees are made that the handshake is indistinguishable from
that of a valid user.
([CVE-2016-0798])
*Emilia Käsper*
* Fix BN_hex2bn/BN_dec2bn NULL pointer deref/heap corruption
In the BN_hex2bn function the number of hex digits is calculated using an
int value `i`. Later `bn_expand` is called with a value of `i * 4`. For
large values of `i` this can result in `bn_expand` not allocating any
memory because `i * 4` is negative. This can leave the internal BIGNUM data
field as NULL leading to a subsequent NULL ptr deref. For very large values
of `i`, the calculation `i * 4` could be a positive value smaller than `i`.
In this case memory is allocated to the internal BIGNUM data field, but it
is insufficiently sized leading to heap corruption. A similar issue exists
in BN_dec2bn. This could have security consequences if BN_hex2bn/BN_dec2bn
is ever called by user applications with very large untrusted hex/dec data.
This is anticipated to be a rare occurrence.
All OpenSSL internal usage of these functions use data that is not expected
to be untrusted, e.g. config file data or application command line
arguments. If user developed applications generate config file data based
on untrusted data then it is possible that this could also lead to security
consequences. This is also anticipated to be rare.
This issue was reported to OpenSSL by Guido Vranken.
([CVE-2016-0797])
*Matt Caswell*
* Fix memory issues in `BIO_*printf` functions
The internal `fmtstr` function used in processing a "%s" format string in
the `BIO_*printf` functions could overflow while calculating the length of a
string and cause an OOB read when printing very long strings.
Additionally the internal `doapr_outch` function can attempt to write to an
OOB memory location (at an offset from the NULL pointer) in the event of a
memory allocation failure. In 1.0.2 and below this could be caused where
the size of a buffer to be allocated is greater than INT_MAX. E.g. this
could be in processing a very long "%s" format string. Memory leaks can
also occur.
The first issue may mask the second issue dependent on compiler behaviour.
These problems could enable attacks where large amounts of untrusted data
is passed to the `BIO_*printf` functions. If applications use these functions
in this way then they could be vulnerable. OpenSSL itself uses these
functions when printing out human-readable dumps of ASN.1 data. Therefore
applications that print this data could be vulnerable if the data is from
untrusted sources. OpenSSL command line applications could also be
vulnerable where they print out ASN.1 data, or if untrusted data is passed
as command line arguments.
Libssl is not considered directly vulnerable. Additionally certificates etc
received via remote connections via libssl are also unlikely to be able to
trigger these issues because of message size limits enforced within libssl.
This issue was reported to OpenSSL Guido Vranken.
([CVE-2016-0799])
*Matt Caswell*
* Side channel attack on modular exponentiation
A side-channel attack was found which makes use of cache-bank conflicts on
the Intel Sandy-Bridge microarchitecture which could lead to the recovery
of RSA keys. The ability to exploit this issue is limited as it relies on
an attacker who has control of code in a thread running on the same
hyper-threaded core as the victim thread which is performing decryptions.
This issue was reported to OpenSSL by Yuval Yarom, The University of
Adelaide and NICTA, Daniel Genkin, Technion and Tel Aviv University, and
Nadia Heninger, University of Pennsylvania with more information at
<http://cachebleed.info>.
([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 <ismo.puustinen@intel.com>*
### 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 <trevp@trevp.net> 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 <rob.stradling@comodo.com> and Ben Laurie*
* Initial experimental support for explicitly trusted non-root CAs.
OpenSSL still tries to build a complete chain to a root but if an
intermediate CA has a trust setting included that is used. The first
setting is used: whether to trust (e.g., -addtrust option to the x509
utility) or reject.
*Steve Henson*
* Add -trusted_first option which attempts to find certificates in the
trusted store even if an untrusted chain is also supplied.
*Steve Henson*
* MIPS assembly pack updates: support for MIPS32r2 and SmartMIPS ASE,
platform support for Linux and Android.
*Andy Polyakov*
* Support for linux-x32, ILP32 environment in x86_64 framework.
*Andy Polyakov*
* Experimental multi-implementation support for FIPS capable OpenSSL.
When in FIPS mode the approved implementations are used as normal,
when not in FIPS mode the internal unapproved versions are used instead.
This means that the FIPS capable OpenSSL isn't forced to use the
(often lower performance) FIPS implementations outside FIPS mode.
*Steve Henson*
* Transparently support X9.42 DH parameters when calling
PEM_read_bio_DHparameters. This means existing applications can handle
the new parameter format automatically.
*Steve Henson*
* Initial experimental support for X9.42 DH parameter format: mainly
to support use of 'q' parameter for RFC5114 parameters.
*Steve Henson*
* Add DH parameters from RFC5114 including test data to dhtest.
*Steve Henson*
* Support for automatic EC temporary key parameter selection. If enabled
the most preferred EC parameters are automatically used instead of
hardcoded fixed parameters. Now a server just has to call:
SSL_CTX_set_ecdh_auto(ctx, 1) and the server will automatically
support ECDH and use the most appropriate parameters.
*Steve Henson*
* Enhance and tidy EC curve and point format TLS extension code. Use
static structures instead of allocation if default values are used.
New ctrls to set curves we wish to support and to retrieve shared curves.
Print out shared curves in s_server. New options to s_server and s_client
to set list of supported curves.
*Steve Henson*
* New ctrls to retrieve supported signature algorithms and
supported curve values as an array of NIDs. Extend openssl utility
to print out received values.
*Steve Henson*
* Add new APIs EC_curve_nist2nid and EC_curve_nid2nist which convert
between NIDs and the more common NIST names such as "P-256". Enhance
ecparam utility and ECC method to recognise the NIST names for curves.
*Steve Henson*
* Enhance SSL/TLS certificate chain handling to support different
chains for each certificate instead of one chain in the parent SSL_CTX.
*Steve Henson*
* Support for fixed DH ciphersuite client authentication: where both
server and client use DH certificates with common parameters.
*Steve Henson*
* Support for fixed DH ciphersuites: those requiring DH server
certificates.
*Steve Henson*
* New function i2d_re_X509_tbs for re-encoding the TBS portion of
the certificate.
Note: Related 1.0.2-beta specific macros X509_get_cert_info,
X509_CINF_set_modified, X509_CINF_get_issuer, X509_CINF_get_extensions and
X509_CINF_get_signature were reverted post internal team review.
OpenSSL 1.0.1
-------------
### Changes between 1.0.1t and 1.0.1u [22 Sep 2016]
* OCSP Status Request extension unbounded memory growth
A malicious client can send an excessively large OCSP Status Request
extension. If that client continually requests renegotiation, sending a
large OCSP Status Request extension each time, then there will be unbounded
memory growth on the server. This will eventually lead to a Denial Of
Service attack through memory exhaustion. Servers with a default
configuration are vulnerable even if they do not support OCSP. Builds using
the "no-ocsp" build time option are not affected.
This issue was reported to OpenSSL by Shi Lei (Gear Team, Qihoo 360 Inc.)
([CVE-2016-6304])
*Matt Caswell*
* In order to mitigate the SWEET32 attack, the DES ciphers were moved from
HIGH to MEDIUM.
This issue was reported to OpenSSL Karthikeyan Bhargavan and Gaetan
Leurent (INRIA)
([CVE-2016-2183])
*Rich Salz*
* OOB write in MDC2_Update()
An overflow can occur in MDC2_Update() either if called directly or
through the EVP_DigestUpdate() function using MDC2. If an attacker
is able to supply very large amounts of input data after a previous
call to EVP_EncryptUpdate() with a partial block then a length check
can overflow resulting in a heap corruption.
The amount of data needed is comparable to SIZE_MAX which is impractical
on most platforms.
This issue was reported to OpenSSL by Shi Lei (Gear Team, Qihoo 360 Inc.)
([CVE-2016-6303])
*Stephen Henson*
* Malformed SHA512 ticket DoS
If a server uses SHA512 for TLS session ticket HMAC it is vulnerable to a
DoS attack where a malformed ticket will result in an OOB read which will
ultimately crash.
The use of SHA512 in TLS session tickets is comparatively rare as it requires
a custom server callback and ticket lookup mechanism.
This issue was reported to OpenSSL by Shi Lei (Gear Team, Qihoo 360 Inc.)
([CVE-2016-6302])
*Stephen Henson*
* OOB write in BN_bn2dec()
The function BN_bn2dec() does not check the return value of BN_div_word().
This can cause an OOB write if an application uses this function with an
overly large BIGNUM. This could be a problem if an overly large certificate
or CRL is printed out from an untrusted source. TLS is not affected because
record limits will reject an oversized certificate before it is parsed.
This issue was reported to OpenSSL by Shi Lei (Gear Team, Qihoo 360 Inc.)
([CVE-2016-2182])
*Stephen Henson*
* OOB read in TS_OBJ_print_bio()
The function TS_OBJ_print_bio() misuses OBJ_obj2txt(): the return value is
the total length the OID text representation would use and not the amount
of data written. This will result in OOB reads when large OIDs are
presented.
This issue was reported to OpenSSL by Shi Lei (Gear Team, Qihoo 360 Inc.)
([CVE-2016-2180])
*Stephen Henson*
* Pointer arithmetic undefined behaviour
Avoid some undefined pointer arithmetic
A common idiom in the codebase is to check limits in the following manner:
"p + len > limit"
Where "p" points to some malloc'd data of SIZE bytes and
limit == p + SIZE
"len" here could be from some externally supplied data (e.g. from a TLS
message).
The rules of C pointer arithmetic are such that "p + len" is only well
defined where len <= SIZE. Therefore the above idiom is actually
undefined behaviour.
For example this could cause problems if some malloc implementation
provides an address for "p" such that "p + len" actually overflows for
values of len that are too big and therefore p + len < limit.
This issue was reported to OpenSSL by Guido Vranken
([CVE-2016-2177])
*Matt Caswell*
* Constant time flag not preserved in DSA signing
Operations in the DSA signing algorithm should run in constant time in
order to avoid side channel attacks. A flaw in the OpenSSL DSA
implementation means that a non-constant time codepath is followed for
certain operations. This has been demonstrated through a cache-timing
attack to be sufficient for an attacker to recover the private DSA key.
This issue was reported by César Pereida (Aalto University), Billy Brumley
(Tampere University of Technology), and Yuval Yarom (The University of
Adelaide and NICTA).
([CVE-2016-2178])
*César Pereida*
* DTLS buffered message DoS
In a DTLS connection where handshake messages are delivered out-of-order
those messages that OpenSSL is not yet ready to process will be buffered
for later use. Under certain circumstances, a flaw in the logic means that
those messages do not get removed from the buffer even though the handshake
has been completed. An attacker could force up to approx. 15 messages to
remain in the buffer when they are no longer required. These messages will
be cleared when the DTLS connection is closed. The default maximum size for
a message is 100k. Therefore the attacker could force an additional 1500k
to be consumed per connection. By opening many simulataneous connections an
attacker could cause a DoS attack through memory exhaustion.
This issue was reported to OpenSSL by Quan Luo.
([CVE-2016-2179])
*Matt Caswell*
* DTLS replay protection DoS
A flaw in the DTLS replay attack protection mechanism means that records
that arrive for future epochs update the replay protection "window" before
the MAC for the record has been validated. This could be exploited by an
attacker by sending a record for the next epoch (which does not have to
decrypt or have a valid MAC), with a very large sequence number. This means
that all subsequent legitimate packets are dropped causing a denial of
service for a specific DTLS connection.
This issue was reported to OpenSSL by the OCAP audit team.
([CVE-2016-2181])
*Matt Caswell*
* Certificate message OOB reads
In OpenSSL 1.0.2 and earlier some missing message length checks can result
in OOB reads of up to 2 bytes beyond an allocated buffer. There is a
theoretical DoS risk but this has not been observed in practice on common
platforms.
The messages affected are client certificate, client certificate request
and server certificate. As a result the attack can only be performed
against a client or a server which enables client authentication.
This issue was reported to OpenSSL by Shi Lei (Gear Team, Qihoo 360 Inc.)
([CVE-2016-6306])
*Stephen Henson*
### Changes between 1.0.1s and 1.0.1t [3 May 2016]
* Prevent padding oracle in AES-NI CBC MAC check
A MITM attacker can use a padding oracle attack to decrypt traffic
when the connection uses an AES CBC cipher and the server support
AES-NI.
This issue was introduced as part of the fix for Lucky 13 padding
attack ([CVE-2013-0169]). The padding check was rewritten to be in
constant time by making sure that always the same bytes are read and
compared against either the MAC or padding bytes. But it no longer
checked that there was enough data to have both the MAC and padding
bytes.
This issue was reported by Juraj Somorovsky using TLS-Attacker.
([CVE-2016-2107])
*Kurt Roeckx*
* Fix EVP_EncodeUpdate overflow
An overflow can occur in the EVP_EncodeUpdate() function which is used for
Base64 encoding of binary data. If an attacker is able to supply very large
amounts of input data then a length check can overflow resulting in a heap
corruption.
Internally to OpenSSL the EVP_EncodeUpdate() function is primarly used by
the `PEM_write_bio*` family of functions. These are mainly used within the
OpenSSL command line applications, so any application which processes data
from an untrusted source and outputs it as a PEM file should be considered
vulnerable to this issue. User applications that call these APIs directly
with large amounts of untrusted data may also be vulnerable.
This issue was reported by Guido Vranken.
([CVE-2016-2105])
*Matt Caswell*
* Fix EVP_EncryptUpdate overflow
An overflow can occur in the EVP_EncryptUpdate() function. If an attacker
is able to supply very large amounts of input data after a previous call to
EVP_EncryptUpdate() with a partial block then a length check can overflow
resulting in a heap corruption. Following an analysis of all OpenSSL
internal usage of the EVP_EncryptUpdate() function all usage is one of two
forms. The first form is where the EVP_EncryptUpdate() call is known to be
the first called function after an EVP_EncryptInit(), and therefore that
specific call must be safe. The second form is where the length passed to
EVP_EncryptUpdate() can be seen from the code to be some small value and
therefore there is no possibility of an overflow. Since all instances are
one of these two forms, it is believed that there can be no overflows in
internal code due to this problem. It should be noted that
EVP_DecryptUpdate() can call EVP_EncryptUpdate() in certain code paths.
Also EVP_CipherUpdate() is a synonym for EVP_EncryptUpdate(). All instances
of these calls have also been analysed too and it is believed there are no
instances in internal usage where an overflow could occur.
This issue was reported by Guido Vranken.
([CVE-2016-2106])
*Matt Caswell*
* Prevent ASN.1 BIO excessive memory allocation
When ASN.1 data is read from a BIO using functions such as d2i_CMS_bio()
a short invalid encoding can casuse allocation of large amounts of memory
potentially consuming excessive resources or exhausting memory.
Any application parsing untrusted data through d2i BIO functions is
affected. The memory based functions such as d2i_X509() are *not* affected.
Since the memory based functions are used by the TLS library, TLS
applications are not affected.
This issue was reported by Brian Carpenter.
([CVE-2016-2109])
*Stephen Henson*
* EBCDIC overread
ASN1 Strings that are over 1024 bytes can cause an overread in applications
using the X509_NAME_oneline() function on EBCDIC systems. This could result
in arbitrary stack data being returned in the buffer.
This issue was reported by Guido Vranken.
([CVE-2016-2176])
*Matt Caswell*
* Modify behavior of ALPN to invoke callback after SNI/servername
callback, such that updates to the SSL_CTX affect ALPN.
*Todd Short*
* Remove LOW from the DEFAULT cipher list. This removes singles DES from the
default.
*Kurt Roeckx*
* Only remove the SSLv2 methods with the no-ssl2-method option. When the
methods are enabled and ssl2 is disabled the methods return NULL.
*Kurt Roeckx*
### Changes between 1.0.1r and 1.0.1s [1 Mar 2016]
* Disable weak ciphers in SSLv3 and up in default builds of OpenSSL.
Builds that are not configured with "enable-weak-ssl-ciphers" will not
provide any "EXPORT" or "LOW" strength ciphers.
*Viktor Dukhovni*
* Disable SSLv2 default build, default negotiation and weak ciphers. SSLv2
is by default disabled at build-time. Builds that are not configured with
"enable-ssl2" will not support SSLv2. Even if "enable-ssl2" is used,
users who want to negotiate SSLv2 via the version-flexible SSLv23_method()
will need to explicitly call either of:
SSL_CTX_clear_options(ctx, SSL_OP_NO_SSLv2);
or
SSL_clear_options(ssl, SSL_OP_NO_SSLv2);
as appropriate. Even if either of those is used, or the application
explicitly uses the version-specific SSLv2_method() or its client and
server variants, SSLv2 ciphers vulnerable to exhaustive search key
recovery have been removed. Specifically, the SSLv2 40-bit EXPORT
ciphers, and SSLv2 56-bit DES are no longer available.
([CVE-2016-0800])
*Viktor Dukhovni*
* Fix a double-free in DSA code
A double free bug was discovered when OpenSSL parses malformed DSA private
keys and could lead to a DoS attack or memory corruption for applications
that receive DSA private keys from untrusted sources. This scenario is
considered rare.
This issue was reported to OpenSSL by Adam Langley(Google/BoringSSL) using
libFuzzer.
([CVE-2016-0705])
*Stephen Henson*
* Disable SRP fake user seed to address a server memory leak.
Add a new method SRP_VBASE_get1_by_user that handles the seed properly.
SRP_VBASE_get_by_user had inconsistent memory management behaviour.
In order to fix an unavoidable memory leak, SRP_VBASE_get_by_user
was changed to ignore the "fake user" SRP seed, even if the seed
is configured.
Users should use SRP_VBASE_get1_by_user instead. Note that in
SRP_VBASE_get1_by_user, caller must free the returned value. Note
also that even though configuring the SRP seed attempts to hide
invalid usernames by continuing the handshake with fake
credentials, this behaviour is not constant time and no strong
guarantees are made that the handshake is indistinguishable from
that of a valid user.
([CVE-2016-0798])
*Emilia Käsper*
* Fix BN_hex2bn/BN_dec2bn NULL pointer deref/heap corruption
In the BN_hex2bn function the number of hex digits is calculated using an
int value `i`. Later `bn_expand` is called with a value of `i * 4`. For
large values of `i` this can result in `bn_expand` not allocating any
memory because `i * 4` is negative. This can leave the internal BIGNUM data
field as NULL leading to a subsequent NULL ptr deref. For very large values
of `i`, the calculation `i * 4` could be a positive value smaller than `i`.
In this case memory is allocated to the internal BIGNUM data field, but it
is insufficiently sized leading to heap corruption. A similar issue exists
in BN_dec2bn. This could have security consequences if BN_hex2bn/BN_dec2bn
is ever called by user applications with very large untrusted hex/dec data.
This is anticipated to be a rare occurrence.
All OpenSSL internal usage of these functions use data that is not expected
to be untrusted, e.g. config file data or application command line
arguments. If user developed applications generate config file data based
on untrusted data then it is possible that this could also lead to security
consequences. This is also anticipated to be rare.
This issue was reported to OpenSSL by Guido Vranken.
([CVE-2016-0797])
*Matt Caswell*
* Fix memory issues in `BIO_*printf` functions
The internal `fmtstr` function used in processing a "%s" format string in
the `BIO_*printf` functions could overflow while calculating the length of a
string and cause an OOB read when printing very long strings.
Additionally the internal `doapr_outch` function can attempt to write to an
OOB memory location (at an offset from the NULL pointer) in the event of a
memory allocation failure. In 1.0.2 and below this could be caused where
the size of a buffer to be allocated is greater than INT_MAX. E.g. this
could be in processing a very long "%s" format string. Memory leaks can
also occur.
The first issue may mask the second issue dependent on compiler behaviour.
These problems could enable attacks where large amounts of untrusted data
is passed to the `BIO_*printf` functions. If applications use these functions
in this way then they could be vulnerable. OpenSSL itself uses these
functions when printing out human-readable dumps of ASN.1 data. Therefore
applications that print this data could be vulnerable if the data is from
untrusted sources. OpenSSL command line applications could also be
vulnerable where they print out ASN.1 data, or if untrusted data is passed
as command line arguments.
Libssl is not considered directly vulnerable. Additionally certificates etc
received via remote connections via libssl are also unlikely to be able to
trigger these issues because of message size limits enforced within libssl.
This issue was reported to OpenSSL Guido Vranken.
([CVE-2016-0799])
*Matt Caswell*
* Side channel attack on modular exponentiation
A side-channel attack was found which makes use of cache-bank conflicts on
the Intel Sandy-Bridge microarchitecture which could lead to the recovery
of RSA keys. The ability to exploit this issue is limited as it relies on
an attacker who has control of code in a thread running on the same
hyper-threaded core as the victim thread which is performing decryptions.
This issue was reported to OpenSSL by Yuval Yarom, The University of
Adelaide and NICTA, Daniel Genkin, Technion and Tel Aviv University, and
Nadia Heninger, University of Pennsylvania with more information at
<http://cachebleed.info>.
([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 <ismo.puustinen@intel.com>*
### Changes between 1.0.1o and 1.0.1p [9 Jul 2015]
* Alternate chains certificate forgery
During certificate verfification, OpenSSL will attempt to find an
alternative certificate chain if the first attempt to build such a chain
fails. An error in the implementation of this logic can mean that an
attacker could cause certain checks on untrusted certificates to be
bypassed, such as the CA flag, enabling them to use a valid leaf
certificate to act as a CA and "issue" an invalid certificate.
This issue was reported to OpenSSL by Adam Langley/David Benjamin
(Google/BoringSSL).
([CVE-2015-1793])
*Matt Caswell*
* Race condition handling PSK identify hint
If PSK identity hints are received by a multi-threaded client then
the values are wrongly updated in the parent SSL_CTX structure. This can
result in a race condition potentially leading to a double free of the
identify hint data.
([CVE-2015-3196])
*Stephen Henson*
### Changes between 1.0.1n and 1.0.1o [12 Jun 2015]
* Fix HMAC ABI incompatibility. The previous version introduced an ABI
incompatibility in the handling of HMAC. The previous ABI has now been
restored.
### Changes between 1.0.1m and 1.0.1n [11 Jun 2015]
* Malformed ECParameters causes infinite loop
When processing an ECParameters structure OpenSSL enters an infinite loop
if the curve specified is over a specially malformed binary polynomial
field.
This can be used to perform denial of service against any
system which processes public keys, certificate requests or
certificates. This includes TLS clients and TLS servers with
client authentication enabled.
This issue was reported to OpenSSL by Joseph Barr-Pixton.
([CVE-2015-1788])
*Andy Polyakov*
* Exploitable out-of-bounds read in X509_cmp_time
X509_cmp_time does not properly check the length of the ASN1_TIME
string and can read a few bytes out of bounds. In addition,
X509_cmp_time accepts an arbitrary number of fractional seconds in the
time string.
An attacker can use this to craft malformed certificates and CRLs of
various sizes and potentially cause a segmentation fault, resulting in
a DoS on applications that verify certificates or CRLs. TLS clients
that verify CRLs are affected. TLS clients and servers with client
authentication enabled may be affected if they use custom verification
callbacks.
This issue was reported to OpenSSL by Robert Swiecki (Google), and
independently by Hanno Böck.
([CVE-2015-1789])
*Emilia Käsper*
* PKCS7 crash with missing EnvelopedContent
The PKCS#7 parsing code does not handle missing inner EncryptedContent
correctly. An attacker can craft malformed ASN.1-encoded PKCS#7 blobs
with missing content and trigger a NULL pointer dereference on parsing.
Applications that decrypt PKCS#7 data or otherwise parse PKCS#7
structures from untrusted sources are affected. OpenSSL clients and
servers are not affected.
This issue was reported to OpenSSL by Michal Zalewski (Google).
([CVE-2015-1790])
*Emilia Käsper*
* CMS verify infinite loop with unknown hash function
When verifying a signedData message the CMS code can enter an infinite loop
if presented with an unknown hash function OID. This can be used to perform
denial of service against any system which verifies signedData messages using
the CMS code.
This issue was reported to OpenSSL by Johannes Bauer.
([CVE-2015-1792])
*Stephen Henson*
* Race condition handling NewSessionTicket
If a NewSessionTicket is received by a multi-threaded client when attempting to
reuse a previous ticket then a race condition can occur potentially leading to
a double free of the ticket data.
([CVE-2015-1791])
*Matt Caswell*
* Reject DH handshakes with parameters shorter than 768 bits.
*Kurt Roeckx and Emilia Kasper*
* dhparam: generate 2048-bit parameters by default.
*Kurt Roeckx and Emilia Kasper*
### Changes between 1.0.1l and 1.0.1m [19 Mar 2015]
* Segmentation fault in ASN1_TYPE_cmp fix
The function ASN1_TYPE_cmp will crash with an invalid read if an attempt is
made to compare ASN.1 boolean types. Since ASN1_TYPE_cmp is used to check
certificate signature algorithm consistency this can be used to crash any
certificate verification operation and exploited in a DoS attack. Any
application which performs certificate verification is vulnerable including
OpenSSL clients and servers which enable client authentication.
([CVE-2015-0286])
*Stephen Henson*
* ASN.1 structure reuse memory corruption fix
Reusing a structure in ASN.1 parsing may allow an attacker to cause
memory corruption via an invalid write. Such reuse is and has been
strongly discouraged and is believed to be rare.
Applications that parse structures containing CHOICE or ANY DEFINED BY
components may be affected. Certificate parsing (d2i_X509 and related
functions) are however not affected. OpenSSL clients and servers are
not affected.
([CVE-2015-0287])
*Stephen Henson*
* PKCS7 NULL pointer dereferences fix
The PKCS#7 parsing code does not handle missing outer ContentInfo
correctly. An attacker can craft malformed ASN.1-encoded PKCS#7 blobs with
missing content and trigger a NULL pointer dereference on parsing.
Applications that verify PKCS#7 signatures, decrypt PKCS#7 data or
otherwise parse PKCS#7 structures from untrusted sources are
affected. OpenSSL clients and servers are not affected.
This issue was reported to OpenSSL by Michal Zalewski (Google).
([CVE-2015-0289])
*Emilia Käsper*
* DoS via reachable assert in SSLv2 servers fix
A malicious client can trigger an OPENSSL_assert (i.e., an abort) in
servers that both support SSLv2 and enable export cipher suites by sending
a specially crafted SSLv2 CLIENT-MASTER-KEY message.
This issue was discovered by Sean Burford (Google) and Emilia Käsper
(OpenSSL development team).
([CVE-2015-0293])
*Emilia Käsper*
* Use After Free following d2i_ECPrivatekey error fix
A malformed EC private key file consumed via the d2i_ECPrivateKey function
could cause a use after free condition. This, in turn, could cause a double
free in several private key parsing functions (such as d2i_PrivateKey
or EVP_PKCS82PKEY) and could lead to a DoS attack or memory corruption
for applications that receive EC private keys from untrusted
sources. This scenario is considered rare.
This issue was discovered by the BoringSSL project and fixed in their
commit 517073cd4b.
([CVE-2015-0209])
*Matt Caswell*
* X509_to_X509_REQ NULL pointer deref fix
The function X509_to_X509_REQ will crash with a NULL pointer dereference if
the certificate key is invalid. This function is rarely used in practice.
This issue was discovered by Brian Carpenter.
([CVE-2015-0288])
*Stephen Henson*
* Removed the export ciphers from the DEFAULT ciphers
*Kurt Roeckx*
### Changes between 1.0.1k and 1.0.1l [15 Jan 2015]
* Build fixes for the Windows and OpenVMS platforms
*Matt Caswell and Richard Levitte*
### Changes between 1.0.1j and 1.0.1k [8 Jan 2015]
* Fix DTLS segmentation fault in dtls1_get_record. A carefully crafted DTLS
message can cause a segmentation fault in OpenSSL due to a NULL pointer
dereference. This could lead to a Denial Of Service attack. Thanks to
Markus Stenberg of Cisco Systems, Inc. for reporting this issue.
([CVE-2014-3571])
*Steve Henson*
* Fix DTLS memory leak in dtls1_buffer_record. A memory leak can occur in the
dtls1_buffer_record function under certain conditions. In particular this
could occur if an attacker sent repeated DTLS records with the same
sequence number but for the next epoch. The memory leak could be exploited
by an attacker in a Denial of Service attack through memory exhaustion.
Thanks to Chris Mueller for reporting this issue.
([CVE-2015-0206])
*Matt Caswell*
* Fix issue where no-ssl3 configuration sets method to NULL. When openssl is
built with the no-ssl3 option and a SSL v3 ClientHello is received the ssl
method would be set to NULL which could later result in a NULL pointer
dereference. Thanks to Frank Schmirler for reporting this issue.
([CVE-2014-3569])
*Kurt Roeckx*
* Abort handshake if server key exchange message is omitted for ephemeral
ECDH ciphersuites.
Thanks to Karthikeyan Bhargavan of the PROSECCO team at INRIA for
reporting this issue.
([CVE-2014-3572])
*Steve Henson*
* Remove non-export ephemeral RSA code on client and server. This code
violated the TLS standard by allowing the use of temporary RSA keys in
non-export ciphersuites and could be used by a server to effectively
downgrade the RSA key length used to a value smaller than the server
certificate. Thanks for Karthikeyan Bhargavan of the PROSECCO team at
INRIA or reporting this issue.
([CVE-2015-0204])
*Steve Henson*
* Fixed issue where DH client certificates are accepted without verification.
An OpenSSL server will accept a DH certificate for client authentication
without the certificate verify message. This effectively allows a client to
authenticate without the use of a private key. This only affects servers
which trust a client certificate authority which issues certificates
containing DH keys: these are extremely rare and hardly ever encountered.
Thanks for Karthikeyan Bhargavan of the PROSECCO team at INRIA or reporting
this issue.
([CVE-2015-0205])
*Steve Henson*
* Ensure that the session ID context of an SSL is updated when its
SSL_CTX is updated via SSL_set_SSL_CTX.
The session ID context is typically set from the parent SSL_CTX,
and can vary with the CTX.
*Adam Langley*
* Fix various certificate fingerprint issues.
By using non-DER or invalid encodings outside the signed portion of a
certificate the fingerprint can be changed without breaking the signature.
Although no details of the signed portion of the certificate can be changed
this can cause problems with some applications: e.g. those using the
certificate fingerprint for blacklists.
1. Reject signatures with non zero unused bits.
If the BIT STRING containing the signature has non zero unused bits reject
the signature. All current signature algorithms require zero unused bits.
2. Check certificate algorithm consistency.
Check the AlgorithmIdentifier inside TBS matches the one in the
certificate signature. NB: this will result in signature failure
errors for some broken certificates.
Thanks to Konrad Kraszewski from Google for reporting this issue.
3. Check DSA/ECDSA signatures use DER.
Re-encode DSA/ECDSA signatures and compare with the original received
signature. Return an error if there is a mismatch.
This will reject various cases including garbage after signature
(thanks to Antti Karjalainen and Tuomo Untinen from the Codenomicon CROSS
program for discovering this case) and use of BER or invalid ASN.1 INTEGERs
(negative or with leading zeroes).
Further analysis was conducted and fixes were developed by Stephen Henson
of the OpenSSL core team.
([CVE-2014-8275])
*Steve Henson*
* Correct Bignum squaring. Bignum squaring (BN_sqr) may produce incorrect
results on some platforms, including x86_64. This bug occurs at random
with a very low probability, and is not known to be exploitable in any
way, though its exact impact is difficult to determine. Thanks to Pieter
Wuille (Blockstream) who reported this issue and also suggested an initial
fix. Further analysis was conducted by the OpenSSL development team and
Adam Langley of Google. The final fix was developed by Andy Polyakov of
the OpenSSL core team.
([CVE-2014-3570])
*Andy Polyakov*
* Do not resume sessions on the server if the negotiated protocol
version does not match the session's version. Resuming with a different
version, while not strictly forbidden by the RFC, is of questionable
sanity and breaks all known clients.
*David Benjamin, Emilia Käsper*
* Tighten handling of the ChangeCipherSpec (CCS) message: reject
early CCS messages during renegotiation. (Note that because
renegotiation is encrypted, this early CCS was not exploitable.)
*Emilia Käsper*
* Tighten client-side session ticket handling during renegotiation:
ensure that the client only accepts a session ticket if the server sends
the extension anew in the ServerHello. Previously, a TLS client would
reuse the old extension state and thus accept a session ticket if one was
announced in the initial ServerHello.
Similarly, ensure that the client requires a session ticket if one
was advertised in the ServerHello. Previously, a TLS client would
ignore a missing NewSessionTicket message.
*Emilia Käsper*
### Changes between 1.0.1i and 1.0.1j [15 Oct 2014]
* SRTP Memory Leak.
A flaw in the DTLS SRTP extension parsing code allows an attacker, who
sends a carefully crafted handshake message, to cause OpenSSL to fail
to free up to 64k of memory causing a memory leak. This could be
exploited in a Denial Of Service attack. This issue affects OpenSSL
1.0.1 server implementations for both SSL/TLS and DTLS regardless of
whether SRTP is used or configured. Implementations of OpenSSL that
have been compiled with OPENSSL_NO_SRTP defined are not affected.
The fix was developed by the OpenSSL team.
([CVE-2014-3513])
*OpenSSL team*
* Session Ticket Memory Leak.
When an OpenSSL SSL/TLS/DTLS server receives a session ticket the
integrity of that ticket is first verified. In the event of a session
ticket integrity check failing, OpenSSL will fail to free memory
causing a memory leak. By sending a large number of invalid session
tickets an attacker could exploit this issue in a Denial Of Service
attack.
([CVE-2014-3567])
*Steve Henson*
* Build option no-ssl3 is incomplete.
When OpenSSL is configured with "no-ssl3" as a build option, servers
could accept and complete a SSL 3.0 handshake, and clients could be
configured to send them.
([CVE-2014-3568])
*Akamai and the OpenSSL team*
* Add support for TLS_FALLBACK_SCSV.
Client applications doing fallback retries should call
SSL_set_mode(s, SSL_MODE_SEND_FALLBACK_SCSV).
([CVE-2014-3566])
*Adam Langley, Bodo Moeller*
* Add additional DigestInfo checks.
Re-encode DigestInto in DER and check against the original when
verifying RSA signature: this will reject any improperly encoded
DigestInfo structures.
Note: this is a precautionary measure and no attacks are currently known.
*Steve Henson*
### Changes between 1.0.1h and 1.0.1i [6 Aug 2014]
* Fix SRP buffer overrun vulnerability. Invalid parameters passed to the
SRP code can be overrun an internal buffer. Add sanity check that
g, A, B < N to SRP code.
Thanks to Sean Devlin and Watson Ladd of Cryptography Services, NCC
Group for discovering this issue.
([CVE-2014-3512])
*Steve Henson*
* A flaw in the OpenSSL SSL/TLS server code causes the server to negotiate
TLS 1.0 instead of higher protocol versions when the ClientHello message
is badly fragmented. This allows a man-in-the-middle attacker to force a
downgrade to TLS 1.0 even if both the server and the client support a
higher protocol version, by modifying the client's TLS records.
Thanks to David Benjamin and Adam Langley (Google) for discovering and
researching this issue.
([CVE-2014-3511])
*David Benjamin*
* OpenSSL DTLS clients enabling anonymous (EC)DH ciphersuites are subject
to a denial of service attack. A malicious server can crash the client
with a null pointer dereference (read) by specifying an anonymous (EC)DH
ciphersuite and sending carefully crafted handshake messages.
Thanks to Felix Gröbert (Google) for discovering and researching this
issue.
([CVE-2014-3510])
*Emilia Käsper*
* By sending carefully crafted DTLS packets an attacker could cause openssl
to leak memory. This can be exploited through a Denial of Service attack.
Thanks to Adam Langley for discovering and researching this issue.
([CVE-2014-3507])
*Adam Langley*
* An attacker can force openssl to consume large amounts of memory whilst
processing DTLS handshake messages. This can be exploited through a
Denial of Service attack.
Thanks to Adam Langley for discovering and researching this issue.
([CVE-2014-3506])
*Adam Langley*
* An attacker can force an error condition which causes openssl to crash
whilst processing DTLS packets due to memory being freed twice. This
can be exploited through a Denial of Service attack.
Thanks to Adam Langley and Wan-Teh Chang for discovering and researching
this issue.
([CVE-2014-3505])
*Adam Langley*
* If a multithreaded client connects to a malicious server using a resumed
session and the server sends an ec point format extension it could write
up to 255 bytes to freed memory.
Thanks to Gabor Tyukasz (LogMeIn Inc) for discovering and researching this
issue.
([CVE-2014-3509])
*Gabor Tyukasz*
* A malicious server can crash an OpenSSL client with a null pointer
dereference (read) by specifying an SRP ciphersuite even though it was not
properly negotiated with the client. This can be exploited through a
Denial of Service attack.
Thanks to Joonas Kuorilehto and Riku Hietamäki (Codenomicon) for
discovering and researching this issue.
([CVE-2014-5139])
*Steve Henson*
* A flaw in OBJ_obj2txt may cause pretty printing functions such as
X509_name_oneline, X509_name_print_ex et al. to leak some information
from the stack. Applications may be affected if they echo pretty printing
output to the attacker.
Thanks to Ivan Fratric (Google) for discovering this issue.
([CVE-2014-3508])
*Emilia Käsper, and Steve Henson*
* Fix ec_GFp_simple_points_make_affine (thus, EC_POINTs_mul etc.)
for corner cases. (Certain input points at infinity could lead to
bogus results, with non-infinity inputs mapped to infinity too.)
*Bodo Moeller*
### Changes between 1.0.1g and 1.0.1h [5 Jun 2014]
* Fix for SSL/TLS MITM flaw. An attacker using a carefully crafted
handshake can force the use of weak keying material in OpenSSL
SSL/TLS clients and servers.
Thanks to KIKUCHI Masashi (Lepidum Co. Ltd.) for discovering and
researching this issue. ([CVE-2014-0224])
*KIKUCHI Masashi, Steve Henson*
* Fix DTLS recursion flaw. By sending an invalid DTLS handshake to an
OpenSSL DTLS client the code can be made to recurse eventually crashing
in a DoS attack.
Thanks to Imre Rad (Search-Lab Ltd.) for discovering this issue.
([CVE-2014-0221])
*Imre Rad, Steve Henson*
* Fix DTLS invalid fragment vulnerability. A buffer overrun attack can
be triggered by sending invalid DTLS fragments to an OpenSSL DTLS
client or server. This is potentially exploitable to run arbitrary
code on a vulnerable client or server.
Thanks to Jüri Aedla for reporting this issue. ([CVE-2014-0195])
*Jüri Aedla, Steve Henson*
* Fix bug in TLS code where clients enable anonymous ECDH ciphersuites
are subject to a denial of service attack.
Thanks to Felix Gröbert and Ivan Fratric at Google for discovering
this issue. ([CVE-2014-3470])
*Felix Gröbert, Ivan Fratric, Steve Henson*
* Harmonize version and its documentation. -f flag is used to display
compilation flags.
*mancha <mancha1@zoho.com>*
* Fix eckey_priv_encode so it immediately returns an error upon a failure
in i2d_ECPrivateKey.
*mancha <mancha1@zoho.com>*
* Fix some double frees. These are not thought to be exploitable.
*mancha <mancha1@zoho.com>*
### 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 <agl@chromium.org> and Bodo Moeller <bmoeller@acm.org> for
preparing the fix ([CVE-2014-0160])
*Adam Langley, Bodo Moeller*
* Fix for the attack described in the paper "Recovering OpenSSL
ECDSA Nonces Using the FLUSH+RELOAD Cache Side-channel Attack"
by Yuval Yarom and Naomi Benger. Details can be obtained from:
<http://eprint.iacr.org/2014/140>
Thanks to Yuval Yarom and Naomi Benger for discovering this
flaw and to Yuval Yarom for supplying a fix ([CVE-2014-0076])
*Yuval Yarom and Naomi Benger*
* TLS pad extension: draft-agl-tls-padding-03
Workaround for the "TLS hang bug" (see FAQ and PR#2771): if the
TLS client Hello record length value would otherwise be > 255 and
less that 512 pad with a dummy extension containing zeroes so it
is at least 512 bytes long.
*Adam Langley, Steve Henson*
### Changes between 1.0.1e and 1.0.1f [6 Jan 2014]
* Fix for TLS record tampering bug. A carefully crafted invalid
handshake could crash OpenSSL with a NULL pointer exception.
Thanks to Anton Johansson for reporting this issues.
([CVE-2013-4353])
* Keep original DTLS digest and encryption contexts in retransmission
structures so we can use the previous session parameters if they need
to be resent. ([CVE-2013-6450])
*Steve Henson*
* Add option SSL_OP_SAFARI_ECDHE_ECDSA_BUG (part of SSL_OP_ALL) which
avoids preferring ECDHE-ECDSA ciphers when the client appears to be
Safari on OS X. Safari on OS X 10.8..10.8.3 advertises support for
several ECDHE-ECDSA ciphers, but fails to negotiate them. The bug
is fixed in OS X 10.8.4, but Apple have ruled out both hot fixing
10.8..10.8.3 and forcing users to upgrade to 10.8.4 or newer.
*Rob Stradling, Adam Langley*
### Changes between 1.0.1d and 1.0.1e [11 Feb 2013]
* Correct fix for CVE-2013-0169. The original didn't work on AES-NI
supporting platforms or when small records were transferred.
*Andy Polyakov, Steve Henson*
### Changes between 1.0.1c and 1.0.1d [5 Feb 2013]
* Make the decoding of SSLv3, TLS and DTLS CBC records constant time.
This addresses the flaw in CBC record processing discovered by
Nadhem Alfardan and Kenny Paterson. Details of this attack can be found
at: <http://www.isg.rhul.ac.uk/tls/>
Thanks go to Nadhem Alfardan and Kenny Paterson of the Information
Security Group at Royal Holloway, University of London
(www.isg.rhul.ac.uk) for discovering this flaw and Adam Langley and
Emilia Käsper for the initial patch.
([CVE-2013-0169])
*Emilia Käsper, Adam Langley, Ben Laurie, Andy Polyakov, Steve Henson*
* Fix flaw in AESNI handling of TLS 1.2 and 1.1 records for CBC mode
ciphersuites which can be exploited in a denial of service attack.
Thanks go to and to Adam Langley <agl@chromium.org> for discovering
and detecting this bug and to Wolfgang Ettlinger
<wolfgang.ettlinger@gmail.com> 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 <palmer@google.com> and Ben Laurie*
* Call OCSP Stapling callback after ciphersuite has been chosen, so
the right response is stapled. Also change SSL_get_certificate()
so it returns the certificate actually sent.
See <http://rt.openssl.org/Ticket/Display.html?id=2836>.
*Rob Stradling <rob.stradling@comodo.com>*
* 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 <agl@chromium.org> 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 <seggelmann@fh-muenster.de>*
* Add support for SCTP.
*Robin Seggelmann <seggelmann@fh-muenster.de>*
* Improved PRNG seeding for VOS.
*Paul Green <Paul.Green@stratus.com>*
* 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 <peter.sylvester@edelweb.fr>*
* Add TLS key material exporter from RFC 5705.
*Eric Rescorla*
* Add DTLS-SRTP negotiation from RFC 5764.
*Eric Rescorla*
* Add Next Protocol Negotiation,
<http://tools.ietf.org/html/draft-agl-tls-nextprotoneg-00>. Can be
disabled with a no-npn flag to config or Configure. Code donated
by Google.
*Adam Langley <agl@google.com> 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 <lists@kaiser.cx>*
* 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 <pde@eff.org>, 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 <christophe.renou@edelweb.fr>, Peter Sylvester
<peter.sylvester@edelweb.fr>, Tom Wu <tjw@cs.stanford.edu>, 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 <seggelmann@fh-muenster.de>*
* 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 <seggelmann@fh-muenster.de>, Steve Henson*
* Initial TLSv1.1 support. Since TLSv1.1 is very similar to TLS v1.0 only
a few changes are required:
Add SSL_OP_NO_TLSv1_1 flag.
Add TLSv1_1 methods.
Update version checking logic to handle version 1.1.
Add explicit IV handling (ported from DTLS code).
Add command line options to s_client/s_server.
*Steve Henson*
OpenSSL 1.0.0
-------------
### Changes between 1.0.0s and 1.0.0t [3 Dec 2015]
* X509_ATTRIBUTE memory leak
When presented with a malformed X509_ATTRIBUTE structure OpenSSL will leak
memory. This structure is used by the PKCS#7 and CMS routines so any
application which reads PKCS#7 or CMS data from untrusted sources is
affected. SSL/TLS is not affected.
This issue was reported to OpenSSL by Adam Langley (Google/BoringSSL) using
libFuzzer.
([CVE-2015-3195])
*Stephen Henson*
* Race condition handling PSK identify hint
If PSK identity hints are received by a multi-threaded client then
the values are wrongly updated in the parent SSL_CTX structure. This can
result in a race condition potentially leading to a double free of the
identify hint data.
([CVE-2015-3196])
*Stephen Henson*
### Changes between 1.0.0r and 1.0.0s [11 Jun 2015]
* Malformed ECParameters causes infinite loop
When processing an ECParameters structure OpenSSL enters an infinite loop
if the curve specified is over a specially malformed binary polynomial
field.
This can be used to perform denial of service against any
system which processes public keys, certificate requests or
certificates. This includes TLS clients and TLS servers with
client authentication enabled.
This issue was reported to OpenSSL by Joseph Barr-Pixton.
([CVE-2015-1788])
*Andy Polyakov*
* Exploitable out-of-bounds read in X509_cmp_time
X509_cmp_time does not properly check the length of the ASN1_TIME
string and can read a few bytes out of bounds. In addition,
X509_cmp_time accepts an arbitrary number of fractional seconds in the
time string.
An attacker can use this to craft malformed certificates and CRLs of
various sizes and potentially cause a segmentation fault, resulting in
a DoS on applications that verify certificates or CRLs. TLS clients
that verify CRLs are affected. TLS clients and servers with client
authentication enabled may be affected if they use custom verification
callbacks.
This issue was reported to OpenSSL by Robert Swiecki (Google), and
independently by Hanno Böck.
([CVE-2015-1789])
*Emilia Käsper*
* PKCS7 crash with missing EnvelopedContent
The PKCS#7 parsing code does not handle missing inner EncryptedContent
correctly. An attacker can craft malformed ASN.1-encoded PKCS#7 blobs
with missing content and trigger a NULL pointer dereference on parsing.
Applications that decrypt PKCS#7 data or otherwise parse PKCS#7
structures from untrusted sources are affected. OpenSSL clients and
servers are not affected.
This issue was reported to OpenSSL by Michal Zalewski (Google).
([CVE-2015-1790])
*Emilia Käsper*
* CMS verify infinite loop with unknown hash function
When verifying a signedData message the CMS code can enter an infinite loop
if presented with an unknown hash function OID. This can be used to perform
denial of service against any system which verifies signedData messages using
the CMS code.
This issue was reported to OpenSSL by Johannes Bauer.
([CVE-2015-1792])
*Stephen Henson*
* Race condition handling NewSessionTicket
If a NewSessionTicket is received by a multi-threaded client when attempting to
reuse a previous ticket then a race condition can occur potentially leading to
a double free of the ticket data.
([CVE-2015-1791])
*Matt Caswell*
### Changes between 1.0.0q and 1.0.0r [19 Mar 2015]
* Segmentation fault in ASN1_TYPE_cmp fix
The function ASN1_TYPE_cmp will crash with an invalid read if an attempt is
made to compare ASN.1 boolean types. Since ASN1_TYPE_cmp is used to check
certificate signature algorithm consistency this can be used to crash any
certificate verification operation and exploited in a DoS attack. Any
application which performs certificate verification is vulnerable including
OpenSSL clients and servers which enable client authentication.
([CVE-2015-0286])
*Stephen Henson*
* ASN.1 structure reuse memory corruption fix
Reusing a structure in ASN.1 parsing may allow an attacker to cause
memory corruption via an invalid write. Such reuse is and has been
strongly discouraged and is believed to be rare.
Applications that parse structures containing CHOICE or ANY DEFINED BY
components may be affected. Certificate parsing (d2i_X509 and related
functions) are however not affected. OpenSSL clients and servers are
not affected.
([CVE-2015-0287])
*Stephen Henson*
* PKCS7 NULL pointer dereferences fix
The PKCS#7 parsing code does not handle missing outer ContentInfo
correctly. An attacker can craft malformed ASN.1-encoded PKCS#7 blobs with
missing content and trigger a NULL pointer dereference on parsing.
Applications that verify PKCS#7 signatures, decrypt PKCS#7 data or
otherwise parse PKCS#7 structures from untrusted sources are
affected. OpenSSL clients and servers are not affected.
This issue was reported to OpenSSL by Michal Zalewski (Google).
([CVE-2015-0289])
*Emilia Käsper*
* DoS via reachable assert in SSLv2 servers fix
A malicious client can trigger an OPENSSL_assert (i.e., an abort) in
servers that both support SSLv2 and enable export cipher suites by sending
a specially crafted SSLv2 CLIENT-MASTER-KEY message.
This issue was discovered by Sean Burford (Google) and Emilia Käsper
(OpenSSL development team).
([CVE-2015-0293])
*Emilia Käsper*
* Use After Free following d2i_ECPrivatekey error fix
A malformed EC private key file consumed via the d2i_ECPrivateKey function
could cause a use after free condition. This, in turn, could cause a double
free in several private key parsing functions (such as d2i_PrivateKey
or EVP_PKCS82PKEY) and could lead to a DoS attack or memory corruption
for applications that receive EC private keys from untrusted
sources. This scenario is considered rare.
This issue was discovered by the BoringSSL project and fixed in their
commit 517073cd4b.
([CVE-2015-0209])
*Matt Caswell*
* X509_to_X509_REQ NULL pointer deref fix
The function X509_to_X509_REQ will crash with a NULL pointer dereference if
the certificate key is invalid. This function is rarely used in practice.
This issue was discovered by Brian Carpenter.
([CVE-2015-0288])
*Stephen Henson*
* Removed the export ciphers from the DEFAULT ciphers
*Kurt Roeckx*
### Changes between 1.0.0p and 1.0.0q [15 Jan 2015]
* Build fixes for the Windows and OpenVMS platforms
*Matt Caswell and Richard Levitte*
### Changes between 1.0.0o and 1.0.0p [8 Jan 2015]
* Fix DTLS segmentation fault in dtls1_get_record. A carefully crafted DTLS
message can cause a segmentation fault in OpenSSL due to a NULL pointer
dereference. This could lead to a Denial Of Service attack. Thanks to
Markus Stenberg of Cisco Systems, Inc. for reporting this issue.
([CVE-2014-3571])
*Steve Henson*
* Fix DTLS memory leak in dtls1_buffer_record. A memory leak can occur in the
dtls1_buffer_record function under certain conditions. In particular this
could occur if an attacker sent repeated DTLS records with the same
sequence number but for the next epoch. The memory leak could be exploited
by an attacker in a Denial of Service attack through memory exhaustion.
Thanks to Chris Mueller for reporting this issue.
([CVE-2015-0206])
*Matt Caswell*
* Fix issue where no-ssl3 configuration sets method to NULL. When openssl is
built with the no-ssl3 option and a SSL v3 ClientHello is received the ssl
method would be set to NULL which could later result in a NULL pointer
dereference. Thanks to Frank Schmirler for reporting this issue.
([CVE-2014-3569])
*Kurt Roeckx*
* Abort handshake if server key exchange message is omitted for ephemeral
ECDH ciphersuites.
Thanks to Karthikeyan Bhargavan of the PROSECCO team at INRIA for
reporting this issue.
([CVE-2014-3572])
*Steve Henson*
* Remove non-export ephemeral RSA code on client and server. This code
violated the TLS standard by allowing the use of temporary RSA keys in
non-export ciphersuites and could be used by a server to effectively
downgrade the RSA key length used to a value smaller than the server
certificate. Thanks for Karthikeyan Bhargavan of the PROSECCO team at
INRIA or reporting this issue.
([CVE-2015-0204])
*Steve Henson*
* Fixed issue where DH client certificates are accepted without verification.
An OpenSSL server will accept a DH certificate for client authentication
without the certificate verify message. This effectively allows a client to
authenticate without the use of a private key. This only affects servers
which trust a client certificate authority which issues certificates
containing DH keys: these are extremely rare and hardly ever encountered.
Thanks for Karthikeyan Bhargavan of the PROSECCO team at INRIA or reporting
this issue.
([CVE-2015-0205])
*Steve Henson*
* Correct Bignum squaring. Bignum squaring (BN_sqr) may produce incorrect
results on some platforms, including x86_64. This bug occurs at random
with a very low probability, and is not known to be exploitable in any
way, though its exact impact is difficult to determine. Thanks to Pieter
Wuille (Blockstream) who reported this issue and also suggested an initial
fix. Further analysis was conducted by the OpenSSL development team and
Adam Langley of Google. The final fix was developed by Andy Polyakov of
the OpenSSL core team.
([CVE-2014-3570])
*Andy Polyakov*
* Fix various certificate fingerprint issues.
By using non-DER or invalid encodings outside the signed portion of a
certificate the fingerprint can be changed without breaking the signature.
Although no details of the signed portion of the certificate can be changed
this can cause problems with some applications: e.g. those using the
certificate fingerprint for blacklists.
1. Reject signatures with non zero unused bits.
If the BIT STRING containing the signature has non zero unused bits reject
the signature. All current signature algorithms require zero unused bits.
2. Check certificate algorithm consistency.
Check the AlgorithmIdentifier inside TBS matches the one in the
certificate signature. NB: this will result in signature failure
errors for some broken certificates.
Thanks to Konrad Kraszewski from Google for reporting this issue.
3. Check DSA/ECDSA signatures use DER.
Reencode DSA/ECDSA signatures and compare with the original received
signature. Return an error if there is a mismatch.
This will reject various cases including garbage after signature
(thanks to Antti Karjalainen and Tuomo Untinen from the Codenomicon CROSS
program for discovering this case) and use of BER or invalid ASN.1 INTEGERs
(negative or with leading zeroes).
Further analysis was conducted and fixes were developed by Stephen Henson
of the OpenSSL core team.
([CVE-2014-8275])
*Steve Henson*
### Changes between 1.0.0n and 1.0.0o [15 Oct 2014]
* Session Ticket Memory Leak.
When an OpenSSL SSL/TLS/DTLS server receives a session ticket the
integrity of that ticket is first verified. In the event of a session
ticket integrity check failing, OpenSSL will fail to free memory
causing a memory leak. By sending a large number of invalid session
tickets an attacker could exploit this issue in a Denial Of Service
attack.
([CVE-2014-3567])
*Steve Henson*
* Build option no-ssl3 is incomplete.
When OpenSSL is configured with "no-ssl3" as a build option, servers
could accept and complete a SSL 3.0 handshake, and clients could be
configured to send them.
([CVE-2014-3568])
*Akamai and the OpenSSL team*
* Add support for TLS_FALLBACK_SCSV.
Client applications doing fallback retries should call
SSL_set_mode(s, SSL_MODE_SEND_FALLBACK_SCSV).
([CVE-2014-3566])
*Adam Langley, Bodo Moeller*
* Add additional DigestInfo checks.
Reencode DigestInto in DER and check against the original when
verifying RSA signature: this will reject any improperly encoded
DigestInfo structures.
Note: this is a precautionary measure and no attacks are currently known.
*Steve Henson*
### Changes between 1.0.0m and 1.0.0n [6 Aug 2014]
* OpenSSL DTLS clients enabling anonymous (EC)DH ciphersuites are subject
to a denial of service attack. A malicious server can crash the client
with a null pointer dereference (read) by specifying an anonymous (EC)DH
ciphersuite and sending carefully crafted handshake messages.
Thanks to Felix Gröbert (Google) for discovering and researching this
issue.
([CVE-2014-3510])
*Emilia Käsper*
* By sending carefully crafted DTLS packets an attacker could cause openssl
to leak memory. This can be exploited through a Denial of Service attack.
Thanks to Adam Langley for discovering and researching this issue.
([CVE-2014-3507])
*Adam Langley*
* An attacker can force openssl to consume large amounts of memory whilst
processing DTLS handshake messages. This can be exploited through a
Denial of Service attack.
Thanks to Adam Langley for discovering and researching this issue.
([CVE-2014-3506])
*Adam Langley*
* An attacker can force an error condition which causes openssl to crash
whilst processing DTLS packets due to memory being freed twice. This
can be exploited through a Denial of Service attack.
Thanks to Adam Langley and Wan-Teh Chang for discovering and researching
this issue.
([CVE-2014-3505])
*Adam Langley*
* If a multithreaded client connects to a malicious server using a resumed
session and the server sends an ec point format extension it could write
up to 255 bytes to freed memory.
Thanks to Gabor Tyukasz (LogMeIn Inc) for discovering and researching this
issue.
([CVE-2014-3509])
*Gabor Tyukasz*
* A flaw in OBJ_obj2txt may cause pretty printing functions such as
X509_name_oneline, X509_name_print_ex et al. to leak some information
from the stack. Applications may be affected if they echo pretty printing
output to the attacker.
Thanks to Ivan Fratric (Google) for discovering this issue.
([CVE-2014-3508])
*Emilia Käsper, and Steve Henson*
* Fix ec_GFp_simple_points_make_affine (thus, EC_POINTs_mul etc.)
for corner cases. (Certain input points at infinity could lead to
bogus results, with non-infinity inputs mapped to infinity too.)
*Bodo Moeller*
### Changes between 1.0.0l and 1.0.0m [5 Jun 2014]
* Fix for SSL/TLS MITM flaw. An attacker using a carefully crafted
handshake can force the use of weak keying material in OpenSSL
SSL/TLS clients and servers.
Thanks to KIKUCHI Masashi (Lepidum Co. Ltd.) for discovering and
researching this issue. ([CVE-2014-0224])
*KIKUCHI Masashi, Steve Henson*
* Fix DTLS recursion flaw. By sending an invalid DTLS handshake to an
OpenSSL DTLS client the code can be made to recurse eventually crashing
in a DoS attack.
Thanks to Imre Rad (Search-Lab Ltd.) for discovering this issue.
([CVE-2014-0221])
*Imre Rad, Steve Henson*
* Fix DTLS invalid fragment vulnerability. A buffer overrun attack can
be triggered by sending invalid DTLS fragments to an OpenSSL DTLS
client or server. This is potentially exploitable to run arbitrary
code on a vulnerable client or server.
Thanks to Jüri Aedla for reporting this issue. ([CVE-2014-0195])
*Jüri Aedla, Steve Henson*
* Fix bug in TLS code where clients enable anonymous ECDH ciphersuites
are subject to a denial of service attack.
Thanks to Felix Gröbert and Ivan Fratric at Google for discovering
this issue. ([CVE-2014-3470])
*Felix Gröbert, Ivan Fratric, Steve Henson*
* Harmonize version and its documentation. -f flag is used to display
compilation flags.
*mancha <mancha1@zoho.com>*
* Fix eckey_priv_encode so it immediately returns an error upon a failure
in i2d_ECPrivateKey.
*mancha <mancha1@zoho.com>*
* Fix some double frees. These are not thought to be exploitable.
*mancha <mancha1@zoho.com>*
* Fix for the attack described in the paper "Recovering OpenSSL
ECDSA Nonces Using the FLUSH+RELOAD Cache Side-channel Attack"
by Yuval Yarom and Naomi Benger. Details can be obtained from:
<http://eprint.iacr.org/2014/140>
Thanks to Yuval Yarom and Naomi Benger for discovering this
flaw and to Yuval Yarom for supplying a fix ([CVE-2014-0076])
*Yuval Yarom and Naomi Benger*
### 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: <http://www.isg.rhul.ac.uk/tls/>
Thanks go to Nadhem Alfardan and Kenny Paterson of the Information
Security Group at Royal Holloway, University of London
(www.isg.rhul.ac.uk) for discovering this flaw and Adam Langley and
Emilia Käsper for the initial patch.
([CVE-2013-0169])
*Emilia Käsper, Adam Langley, Ben Laurie, Andy Polyakov, Steve Henson*
* 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 <http://rt.openssl.org/Ticket/Display.html?id=2836>.
(This is a backport)
*Rob Stradling <rob.stradling@comodo.com>*
* 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 <agl@chromium.org> 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 <inestlerode@us.ibm.com> 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 <inestlerode@us.ibm.com> for discovering this bug.
*Steve Henson*
### Changes between 1.0.0f and 1.0.0g [18 Jan 2012]
* Fix for DTLS DoS issue introduced by fix for CVE-2011-4109.
Thanks to Antonio Martin, Enterprise Secure Access Research and
Development, Cisco Systems, Inc. for discovering this bug and
preparing a fix. ([CVE-2012-0050])
*Antonio Martin*
### Changes between 1.0.0e and 1.0.0f [4 Jan 2012]
* Nadhem Alfardan and Kenny Paterson have discovered an extension
of the Vaudenay padding oracle attack on CBC mode encryption
which enables an efficient plaintext recovery attack against
the OpenSSL implementation of DTLS. Their attack exploits timing
differences arising during decryption processing. A research
paper describing this attack can be found at:
<http://www.isg.rhul.ac.uk/~kp/dtls.pdf>
Thanks go to Nadhem Alfardan and Kenny Paterson of the Information
Security Group at Royal Holloway, University of London
(www.isg.rhul.ac.uk) for discovering this flaw and to Robin Seggelmann
<seggelmann@fh-muenster.de> and Michael Tuexen <tuexen@fh-muenster.de>
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 <desnacked@gmail.com> 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 <amdeich@gmail.com>*
* Prevent malformed RFC3779 data triggering an assertion failure.
Thanks to Andrew Chi, BBN Technologies, for discovering the flaw
and Rob Austein <sra@hactrn.net> for fixing it. ([CVE-2011-4577])
*Rob Austein <sra@hactrn.net>*
* Improved PRNG seeding for VOS.
*Paul Green <Paul.Green@stratus.com>*
* 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 <ossl@velox.ch>*
* Fix SSL memory handling for (EC)DH ciphersuites, in particular
for multi-threaded use of ECDH. ([CVE-2011-3210])
*Adam Langley (Google)*
* Fix x509_name_ex_d2i memory leak on bad inputs.
*Bodo Moeller*
* Remove hard coded ecdsaWithSHA1 signature tests in ssl code and check
signature public key algorithm by using OID xref utilities instead.
Before this you could only use some ECC ciphersuites with SHA1 only.
*Steve Henson*
* Add protection against ECDSA timing attacks as mentioned in the paper
by Billy Bob Brumley and Nicola Tuveri, see:
<http://eprint.iacr.org/2011/232.pdf>
*Billy Bob Brumley and Nicola Tuveri*
### Changes between 1.0.0c and 1.0.0d [8 Feb 2011]
* Fix parsing of OCSP stapling ClientHello extension. CVE-2011-0014
*Neel Mehta, Adam Langley, Bodo Moeller (Google)*
* Fix bug in string printing code: if *any* escaping is enabled we must
escape the escape character (backslash) or the resulting string is
ambiguous.
*Steve Henson*
### Changes between 1.0.0b and 1.0.0c [2 Dec 2010]
* Disable code workaround for ancient and obsolete Netscape browsers
and servers: an attacker can use it in a ciphersuite downgrade attack.
Thanks to Martin Rex for discovering this bug. CVE-2010-4180
*Steve Henson*
* Fixed J-PAKE implementation error, originally discovered by
Sebastien Martini, further info and confirmation from Stefan
Arentz and Feng Hao. Note that this fix is a security fix. CVE-2010-4252
*Ben Laurie*
### Changes between 1.0.0a and 1.0.0b [16 Nov 2010]
* Fix extension code to avoid race conditions which can result in a buffer
overrun vulnerability: resumed sessions must not be modified as they can
be shared by multiple threads. CVE-2010-3864
*Steve Henson*
* Fix WIN32 build system to correctly link an ENGINE directory into
a DLL.
*Steve Henson*
### Changes between 1.0.0 and 1.0.0a [01 Jun 2010]
* Check return value of int_rsa_verify in pkey_rsa_verifyrecover
([CVE-2010-1633])
*Steve Henson, Peter-Michael Hager <hager@dortmund.net>*
### 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 <weisz@vcpc.univie.ac.at>*
* 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 <julia@diku.dk>*
* 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 <lists@gknw.net>*
* Add ECDHE and PSK support to DTLS.
*Michael Tuexen <tuexen@fh-muenster.de>*
* 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 <vitus@cryptocom.ru>*
* Support GeneralizedTime in ca utility.
*Oliver Martin <oliver@volatilevoid.net>, 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 <j@w1.fi>*
* 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 <vitus@cryptocom.ru>*
* 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 <vitus@cryptocom.ru>*
* 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 <pdh@utter.chaos.org.uk>, 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 <vitus@cryptocom.ru>, 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 <zooey@hirschkaefer.de>*
* New make target "install_html_docs" installs HTML renditions of the
manual pages.
*Oliver Tappe <zooey@hirschkaefer.de>*
* 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 <zglozik@opentsa.org>, The OpenTSA Project*
* Add initial support for TLS extensions, specifically for the server_name
extension so far. The SSL_SESSION, SSL_CTX, and SSL data structures now
have new members for a host name. The SSL data structure has an
additional member `SSL_CTX *initial_ctx` so that new sessions can be
stored in that context to allow for session resumption, even after the
SSL has been switched to a new SSL_CTX in reaction to a client's
server_name extension.
New functions (subject to change):
SSL_get_servername()
SSL_get_servername_type()
SSL_set_SSL_CTX()
New CTRL codes and macros (subject to change):
SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
- SSL_CTX_set_tlsext_servername_callback()
SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG
- SSL_CTX_set_tlsext_servername_arg()
SSL_CTRL_SET_TLSEXT_HOSTNAME - SSL_set_tlsext_host_name()
openssl s_client has a new '-servername ...' option.
openssl s_server has new options '-servername_host ...', '-cert2 ...',
'-key2 ...', '-servername_fatal' (subject to change). This allows
testing the HostName extension for a specific single host name ('-cert'
and '-key' remain fallbacks for handshakes without HostName
negotiation). If the unrecognized_name alert has to be sent, this by
default is a warning; it becomes fatal with the '-servername_fatal'
option.
*Peter Sylvester, Remy Allais, Christophe Renou*
* Whirlpool hash implementation is added.
*Andy Polyakov*
* BIGNUM code on 64-bit SPARCv9 targets is switched from bn(64,64) to
bn(64,32). Because of instruction set limitations it doesn't have
any negative impact on performance. This was done mostly in order
to make it possible to share assembler modules, such as bn_mul_mont
implementations, between 32- and 64-bit builds without hassle.
*Andy Polyakov*
* Move code previously exiled into file crypto/ec/ec2_smpt.c
to ec2_smpl.c, and no longer require the OPENSSL_EC_BIN_PT_COMP
macro.
*Bodo Moeller*
* New candidate for BIGNUM assembler implementation, bn_mul_mont,
dedicated Montgomery multiplication procedure, is introduced.
BN_MONT_CTX is modified to allow bn_mul_mont to reach for higher
"64-bit" performance on certain 32-bit targets.
*Andy Polyakov*
* New option SSL_OP_NO_COMP to disable use of compression selectively
in SSL structures. New SSL ctrl to set maximum send fragment size.
Save memory by setting the I/O buffer sizes dynamically instead of
using the maximum available value.
*Steve Henson*
* New option -V for 'openssl ciphers'. This prints the ciphersuite code
in addition to the text details.
*Bodo Moeller*
* Very, very preliminary EXPERIMENTAL support for printing of general
ASN1 structures. This currently produces rather ugly output and doesn't
handle several customised structures at all.
*Steve Henson*
* Integrated support for PVK file format and some related formats such
as MS PUBLICKEYBLOB and PRIVATEKEYBLOB. Command line switches to support
these in the 'rsa' and 'dsa' utilities.
*Steve Henson*
* Support for PKCS#1 RSAPublicKey format on rsa utility command line.
*Steve Henson*
* Remove the ancient ASN1_METHOD code. This was only ever used in one
place for the (very old) "NETSCAPE" format certificates which are now
handled using new ASN1 code equivalents.
*Steve Henson*
* Let the TLSv1_method() etc. functions return a 'const' SSL_METHOD
pointer and make the SSL_METHOD parameter in SSL_CTX_new,
SSL_CTX_set_ssl_version and SSL_set_ssl_method 'const'.
*Nils Larsch*
* Modify CRL distribution points extension code to print out previously
unsupported fields. Enhance extension setting code to allow setting of
all fields.
*Steve Henson*
* Add print and set support for Issuing Distribution Point CRL extension.
*Steve Henson*
* Change 'Configure' script to enable Camellia by default.
*NTT*
OpenSSL 0.9.x
-------------
### Changes between 0.9.8m and 0.9.8n [24 Mar 2010]
* When rejecting SSL/TLS records due to an incorrect version number, never
update s->server with a new major version number. As of
- OpenSSL 0.9.8m if 'short' is a 16-bit type,
- OpenSSL 0.9.8f if 'short' is longer than 16 bits,
the previous behavior could result in a read attempt at NULL when
receiving specific incorrect SSL/TLS records once record payload
protection is active. ([CVE-2010-0740])
*Bodo Moeller, Adam Langley <agl@chromium.org>*
* 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 <thoger@redhat.com>*
### 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., <openssl/cast.h>): 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 <ekr@networkresonance.com>, 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 <julia@diku.dk>*
* 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 <lists@gknw.net>*
* 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 <dwmw2@infradead.org>, 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 <darryl-mailinglists@netbauds.net>*
* Add `2.5.4.*` OIDs
*Ilya O. <vrghost@gmail.com>*
### 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 <Paolo.Ganci@AdNovum.CH>*
* 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 <inestlerode@us.ibm.com>*
* 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 <jnshapir@us.ibm.com>*
* 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 <sander@temme.net>*
* 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 <sra@hactrn.net>*
* Add support for XMPP STARTTLS in s_client.
*Philip Paeps <philip@freebsd.org>*
* 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 <inestlerode@us.ibm.com>*
* 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 <paulsheer@gmail.com>*
* 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 <eflash@gmx.net>*
* 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 <kurt@roeckx.be>, Peter Hartley <pdh@utter.chaos.org.uk>,
Steve Henson*
* Add RFC4507 support to OpenSSL. This includes the corrections in
RFC4507bis. The encrypted ticket format is an encrypted encoded
SSL_SESSION structure, that way new session features are automatically
supported.
If a client application caches session in an SSL_SESSION structure
support is transparent because tickets are now stored in the encoded
SSL_SESSION.
The SSL_CTX structure automatically generates keys for ticket
protection in servers so again support should be possible
with no application modification.
If a client or server wishes to disable RFC4507 support then the option
SSL_OP_NO_TICKET can be set.
Add a TLS extension debugging callback to allow the contents of any client
or server extensions to be examined.
This work was sponsored by Google.
*Steve Henson*
* Add initial support for TLS extensions, specifically for the server_name
extension so far. The SSL_SESSION, SSL_CTX, and SSL data structures now
have new members for a host name. The SSL data structure has an
additional member `SSL_CTX *initial_ctx` so that new sessions can be
stored in that context to allow for session resumption, even after the
SSL has been switched to a new SSL_CTX in reaction to a client's
server_name extension.
New functions (subject to change):
SSL_get_servername()
SSL_get_servername_type()
SSL_set_SSL_CTX()
New CTRL codes and macros (subject to change):
SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
- SSL_CTX_set_tlsext_servername_callback()
SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG
- SSL_CTX_set_tlsext_servername_arg()
SSL_CTRL_SET_TLSEXT_HOSTNAME - SSL_set_tlsext_host_name()
openssl s_client has a new '-servername ...' option.
openssl s_server has new options '-servername_host ...', '-cert2 ...',
'-key2 ...', '-servername_fatal' (subject to change). This allows
testing the HostName extension for a specific single host name ('-cert'
and '-key' remain fallbacks for handshakes without HostName
negotiation). If the unrecognized_name alert has to be sent, this by
default is a warning; it becomes fatal with the '-servername_fatal'
option.
*Peter Sylvester, Remy Allais, Christophe Renou, Steve Henson*
* Add AES and SSE2 assembly language support to VC++ build.
*Steve Henson*
* Mitigate attack on final subtraction in Montgomery reduction.
*Andy Polyakov*
* Fix crypto/ec/ec_mult.c to work properly with scalars of value 0
(which previously caused an internal error).
*Bodo Moeller*
* Squeeze another 10% out of IGE mode when in != out.
*Ben Laurie*
* AES IGE mode speedup.
*Dean Gaudet (Google)*
* Add the Korean symmetric 128-bit cipher SEED (see
<http://www.kisa.or.kr/kisa/seed/jsp/seed_eng.jsp>) and
add SEED ciphersuites from RFC 4162:
TLS_RSA_WITH_SEED_CBC_SHA = "SEED-SHA"
TLS_DHE_DSS_WITH_SEED_CBC_SHA = "DHE-DSS-SEED-SHA"
TLS_DHE_RSA_WITH_SEED_CBC_SHA = "DHE-RSA-SEED-SHA"
TLS_DH_anon_WITH_SEED_CBC_SHA = "ADH-SEED-SHA"
To minimize changes between patchlevels in the OpenSSL 0.9.8
series, SEED remains excluded from compilation unless OpenSSL
is configured with 'enable-seed'.
*KISA, Bodo Moeller*
* Mitigate branch prediction attacks, which can be practical if a
single processor is shared, allowing a spy process to extract
information. For detailed background information, see
<http://eprint.iacr.org/2007/039> (O. Aciicmez, S. Gueron,
J.-P. Seifert, "New Branch Prediction Vulnerabilities in OpenSSL
and Necessary Software Countermeasures"). The core of the change
are new versions BN_div_no_branch() and
BN_mod_inverse_no_branch() of BN_div() and BN_mod_inverse(),
respectively, which are slower, but avoid the security-relevant
conditional branches. These are automatically called by BN_div()
and BN_mod_inverse() if the flag BN_FLG_CONSTTIME is set for one
of the input BIGNUMs. Also, BN_is_bit_set() has been changed to
remove a conditional branch.
BN_FLG_CONSTTIME is the new name for the previous
BN_FLG_EXP_CONSTTIME flag, since it now affects more than just
modular exponentiation. (Since OpenSSL 0.9.7h, setting this flag
in the exponent causes BN_mod_exp_mont() to use the alternative
implementation in BN_mod_exp_mont_consttime().) The old name
remains as a deprecated alias.
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 <http://info.isl.ntt.co.jp/crypt/eng/info/chiteki.html>).
Also, add Camellia TLS ciphersuites from RFC 4132.
To minimize changes between patchlevels in the OpenSSL 0.9.8
series, Camellia remains excluded from compilation unless OpenSSL
is configured with 'enable-camellia'.
*NTT*
* Disable the padding bug check when compression is in use. The padding
bug check assumes the first packet is of even length, this is not
necessarily true if 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 <halostatue@gmail.com>*
* Update support for ECC-based TLS ciphersuites according to
draft-ietf-tls-ecc-12.txt with proposed changes (but without
TLS extensions, which are supported starting with the 0.9.9
branch, not in the OpenSSL 0.9.8 branch).
*Douglas Stebila*
* New functions EVP_CIPHER_CTX_new() and EVP_CIPHER_CTX_free() to support
opaque EVP_CIPHER_CTX handling.
*Steve Henson*
* Fixes and enhancements to zlib compression code. We now only use
"zlib1.dll" and use the default `__cdecl` calling convention on Win32
to conform with the standards mentioned here:
<http://www.zlib.net/DLL_FAQ.txt>
Static zlib linking now works on Windows and the new --with-zlib-include
--with-zlib-lib options to Configure can be used to supply the location
of the headers and library. Gracefully handle case where zlib library
can't be loaded.
*Steve Henson*
* Several fixes and enhancements to the OID generation code. The old code
sometimes allowed invalid OIDs (1.X for X >= 40 for example), couldn't
handle numbers larger than ULONG_MAX, truncated printing and had a
non standard OBJ_obj2txt() behaviour.
*Steve Henson*
* Add support for building of engines under engine/ as shared libraries
under VC++ build system.
*Steve Henson*
* Corrected the numerous bugs in the Win32 path splitter in DSO.
Hopefully, we will not see any false combination of paths any more.
*Richard Levitte*
### Changes between 0.9.8 and 0.9.8a [11 Oct 2005]
* Remove the functionality of SSL_OP_MSIE_SSLV2_RSA_PADDING
(part of SSL_OP_ALL). This option used to disable the
countermeasure against man-in-the-middle protocol-version
rollback in the SSL 2.0 server implementation, which is a bad
idea. ([CVE-2005-2969])
*Bodo Moeller; problem pointed out by Yutaka Oiwa (Research Center
for Information Security, National Institute of Advanced Industrial
Science and Technology [AIST], Japan)*
* Add two function to clear and return the verify parameter flags.
*Steve Henson*
* Keep cipherlists sorted in the source instead of sorting them at
runtime, thus removing the need for a lock.
*Nils Larsch*
* Avoid some small subgroup attacks in Diffie-Hellman.
*Nick Mathewson and Ben Laurie*
* Add functions for well-known primes.
*Nick Mathewson*
* Extended Windows CE support.
*Satoshi Nakamura and Andy Polyakov*
* Initialize SSL_METHOD structures at compile time instead of during
runtime, thus removing the need for a lock.
*Steve Henson*
* Make PKCS7_decrypt() work even if no certificate is supplied by
attempting to decrypt each encrypted key in turn. Add support to
smime utility.
*Steve Henson*
### Changes between 0.9.7h and 0.9.8 [05 Jul 2005]
[NB: OpenSSL 0.9.7i and later 0.9.7 patch levels were released after
OpenSSL 0.9.8.]
* Add libcrypto.pc and libssl.pc for those who feel they need them.
*Richard Levitte*
* Change CA.sh and CA.pl so they don't bundle the CSR and the private
key into the same file any more.
*Richard Levitte*
* Add initial support for Win64, both IA64 and AMD64/x64 flavors.
*Andy Polyakov*
* Add -utf8 command line and config file option to 'ca'.
*Stefan <stf@udoma.org*
* Removed the macro des_crypt(), as it seems to conflict with some
libraries. Use DES_crypt().
*Richard Levitte*
* Correct naming of the 'chil' and '4758cca' ENGINEs. This
involves renaming the source and generated shared-libs for
both. The engines will accept the corrected or legacy ids
('ncipher' and '4758_cca' respectively) when binding. NB,
this only applies when building 'shared'.
*Corinna Vinschen <vinschen@redhat.com> 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 <nagendra@cs.stanford.edu> 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 <michal@logix.cz>, 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 <babin-ebell@trustcenter.de> 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 <nla@trustcenter.de>
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 <nla@trustcenter.de>*
* 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" <peter@runestig.com>*
* 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 <douglas.stebila@sun.com>*
* 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 <nla@trustcenter.de>*
* 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 <nla@trustcenter.de>*
* 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 <nla@trustcenter.de>*
* 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 <nla@trustcenter.de>*
* 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 <nla@trustcenter.de> 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 <nla@trustcenter.de>*
* 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 <nla@trustcenter.de>*
* 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 <larsch@trustcenter.de, Bodo Moeller*
* Remove a few calls to bn_wexpand() in BN_sqr() (the one in there
was actually never needed) and in BN_mul(). The removal in BN_mul()
required a small change in bn_mul_part_recursive() and the addition
of the functions bn_cmp_part_words(), bn_sub_part_words() and
bn_add_part_words(), which do the same thing as bn_cmp_words(),
bn_sub_words() and bn_add_words() except they take arrays with
differing sizes.
*Richard Levitte*
### Changes between 0.9.7l and 0.9.7m [23 Feb 2007]
* Cleanse PEM buffers before freeing them since they may contain
sensitive data.
*Benjamin Bennett <ben@psc.edu>*
* 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 <dtucker@zip.com.au> 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 <openssl@nauticusnet.com>, 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 <d.holmes@f5.com>*
* 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 <Peter.Sylvester@EdelWeb.fr>*
* 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 <Kevin.Greaney@hp.com> 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 <smr@essemer.com.au> 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 <nestler@MIT.EDU>,
Nils Larsch <nla@trustcenter.de> 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 <crispin@flowerday.cx> 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 <kris@obsecurity.org>*
### 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 <crispin@flowerday.cx> 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 <smr@essemer.com.au> 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 <vinschen@redhat.com> 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 <michael.bell@rz.hu-berlin.de>, Steve Henson*
* The "block size" for block ciphers in CFB and OFB mode should be 1.
*Steve Henson, reported by Yngve Nysaeter Pettersen <yngve@opera.com>*
* 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 <dkaufman@rahul.net>*
* 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 <babinebell@trustcenter.de>*
* Improve diagnostics in file reading and command-line digests.
*Ben Laurie aided and abetted by Solar Designer <solar@openwall.com>*
* 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 <joop@fokus.gmd.de>)
*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 <michael.bell@rz.hu-berlin.de>)
*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 <smetters@parc.xerox.com>*
* Added the '4758cca' ENGINE to support IBM 4758 cards.
*Maurice Gittens <maurice@gittens.nl>, 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 <stephen@sprunk.org> 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 <vix@cyber.ee> and Richard Levitte*
* Make it possible to produce shared libraries on ReliantUNIX.
*Robert Dahlem <Robert.Dahlem@ffm2.siemens.de> 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 <vix@cyber.ee> via Richard Levitte*
* Fix a crashbug and a logic bug in hwcrhk_load_pubkey().
*Toomas Kiisk <vix@cyber.ee> via Richard Levitte*
* Add -keyform to rsautl, and document -engine.
*Richard Levitte, inspired by Toomas Kiisk <vix@cyber.ee>*
* 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 <stephen@sprunk.org> 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" <macro@ds2.pg.gda.pl> and Richard Levitte*
* Add support for Subject Information Access extension.
*Peter Sylvester <Peter.Sylvester@EdelWeb.fr>*
* 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" <deengert@anl.gov>.
*Lutz Jaenicke*
* Add support for shared libraries for Unixware-7
(Boyd Lynn Gerber <gerberb@zenez.com>).
*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 <sxw@sxw.org.uk>]
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 <staatsvr@asc.hpc.mil>, Jeffrey Altman <jaltman@columbia.edu>
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" <brianh@kheldar.apana.org.au> 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 <VWalker@novell.com>, 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 <dtartara@novamens.com>*
* 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 <fibikova@exp-math.uni-essen.de>*
* 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 <openssl/bn.h>. 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 <madwolf@hackmasters.net>*
* 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) <certs`.
*Bodo Moeller*
* Make ASN1_UTCTIME_set_string() and ASN1_GENERALIZEDTIME_set_string()
set string type: to handle setting ASN1_TIME structures. Fix ca
utility to correctly initialize revocation date of CRLs.
*Steve Henson*
* New option SSL_OP_CIPHER_SERVER_PREFERENCE allows the server to override
the clients preferred ciphersuites and rather use its own preferences.
Should help to work around M$ SGC (Server Gated Cryptography) bug in
Internet Explorer by ensuring unchanged hash method during stepup.
(Also replaces the broken/deactivated SSL_OP_NON_EXPORT_FIRST option.)
*Lutz Jaenicke*
* Make mkdef.pl recognise all DECLARE_ASN1 macros, change rijndael
to aes and add a new 'exist' option to print out symbols that don't
appear to exist.
*Steve Henson*
* Additional options to ocsp utility to allow flags to be set and
additional certificates supplied.
*Steve Henson*
* Add the option -VAfile to 'openssl ocsp', so the user can give the
OCSP client a number of certificate to only verify the response
signature against.
*Richard Levitte*
* Update Rijndael code to version 3.0 and change EVP AES ciphers to
handle the new API. Currently only ECB, CBC modes supported. Add new
AES OIDs.
Add TLS AES ciphersuites as described in RFC3268, "Advanced
Encryption Standard (AES) Ciphersuites for Transport Layer
Security (TLS)". (In beta versions of OpenSSL 0.9.7, these were
not enabled by default and were not part of the "ALL" ciphersuite
alias because they were not yet official; they could be
explicitly requested by specifying the "AESdraft" ciphersuite
group alias. In the final release of OpenSSL 0.9.7, the group
alias is called "AES" and is part of "ALL".)
*Ben Laurie, Steve Henson, Bodo Moeller*
* New function OCSP_copy_nonce() to copy nonce value (if present) from
request to response.
*Steve Henson*
* Functions for OCSP responders. OCSP_request_onereq_count(),
OCSP_request_onereq_get0(), OCSP_onereq_get0_id() and OCSP_id_get0_info()
extract information from a certificate request. OCSP_response_create()
creates a response and optionally adds a basic response structure.
OCSP_basic_add1_status() adds a complete single response to a basic
response and returns the OCSP_SINGLERESP structure just added (to allow
extensions to be included for example). OCSP_basic_add1_cert() adds a
certificate to a basic response and OCSP_basic_sign() signs a basic
response with various flags. New helper functions ASN1_TIME_check()
(checks validity of ASN1_TIME structure) and ASN1_TIME_to_generalizedtime()
(converts ASN1_TIME to GeneralizedTime).
*Steve Henson*
* Various new functions. EVP_Digest() combines EVP_Digest{Init,Update,Final}()
in a single operation. X509_get0_pubkey_bitstr() extracts the public_key
structure from a certificate. X509_pubkey_digest() digests the public_key
contents: this is used in various key identifiers.
*Steve Henson*
* Make sk_sort() tolerate a NULL argument.
*Steve Henson reported by Massimiliano Pala <madwolf@comune.modena.it>*
* 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
<support@securenetterm.com>*
* 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
<support@securenetterm.com>*
* 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 <madwolf@comune.modena.it>*
* 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 <serial>` 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 <madwolf@comune.modena.it>*
* 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 <djm@mindrot.org>*
* New configuration for the GNU Hurd.
*Jonathan Bartlett <johnnyb@wolfram.com> 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 <staatsvr@asc.hpc.mil>,
Jeffrey Altman <jaltman@columbia.edu>, 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 <fibikova@exp-math.uni-essen.de>, 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 <fibikova@exp-math.uni-essen.de>, Bodo Moeller*
<!--
The following entry accidentally appeared in the CHANGES file
distributed with OpenSSL 0.9.7. The modifications described in
it do *not* apply to OpenSSL 0.9.7.
* Remove a few calls to bn_wexpand() in BN_sqr() (the one in there
was actually never needed) and in BN_mul(). The removal in BN_mul()
required a small change in bn_mul_part_recursive() and the addition
of the functions bn_cmp_part_words(), bn_sub_part_words() and
bn_add_part_words(), which do the same thing as bn_cmp_words(),
bn_sub_words() and bn_add_words() except they take arrays with
differing sizes.
*Richard Levitte*
-->
* 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 <djm@mindrot.org>*
* 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 <mainbug@celocom.de>, 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 <steve@araqnid.ddts.net>.)
*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 <zeev-l@yahoo.com>*
* Undo an undocumented change introduced in 0.9.6e which caused
repeated calls to OpenSSL_add_all_ciphers() and
OpenSSL_add_all_digests() to be ignored, even after calling
EVP_cleanup().
*Richard Levitte*
* Change the default configuration reader to deal with last line not
being properly terminated.
*Richard Levitte*
* Change X509_NAME_cmp() so it applies the special rules on handling
DN values that are of type PrintableString, as well as RDNs of type
emailAddress where the value has the type ia5String.
*stefank@valicert.com via Richard Levitte*
* Add a SSL_SESS_CACHE_NO_INTERNAL_STORE flag to take over half
the job SSL_SESS_CACHE_NO_INTERNAL_LOOKUP was inconsistently
doing, define a new flag (SSL_SESS_CACHE_NO_INTERNAL) to be
the bitwise-OR of the two for use by the majority of applications
wanting this behaviour, and update the docs. The documented
behaviour and actual behaviour were inconsistent and had been
changing anyway, so this is more a bug-fix than a behavioural
change.
*Geoff Thorpe, diagnosed by Nadav Har'El*
* Don't impose a 16-byte length minimum on session IDs in ssl/s3_clnt.c
(the SSL 3.0 and TLS 1.0 specifications allow any length up to 32 bytes).
*Bodo Moeller*
* Fix initialization code race conditions in
SSLv23_method(), SSLv23_client_method(), SSLv23_server_method(),
SSLv2_method(), SSLv2_client_method(), SSLv2_server_method(),
SSLv3_method(), SSLv3_client_method(), SSLv3_server_method(),
TLSv1_method(), TLSv1_client_method(), TLSv1_server_method(),
ssl2_get_cipher_by_char(),
ssl3_get_cipher_by_char().
*Patrick McCormick <patrick@tellme.com>, 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 <mrsam@courier-mta.com>
(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 <lgazis@rainbow.com>*
### 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 <Weimer@CERT.Uni-Stuttgart.DE>,
Alon Kantor <alonk@checkpoint.com> (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 <arne@ats.cyber.ee>, 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 <stav@mercury.co.il>, James Yonan <jim@ntlp.com>*
* 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 <stav@mercury.co.il>, James Yonan <jim@ntlp.com>*
* 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 <mbm@aldigital.co.uk> 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 <nla@trustcenter.de>; problem pointed out by Bodo Moeller*
* Check various `X509_...()` return values in `apps/req.c`.
*Nils Larsch <nla@trustcenter.de>*
* 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
<ptsekov@syntrex.com> 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 <arne@ats.cyber.ee>*
* 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
<sss@sss.dnsalias.net>).
*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 <tom@arcot.com>.
*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 <YoramZ@gilian.com>).
*Lutz Jaenicke*
* Add information about CygWin 1.3 and on, and preserve proper
configuration for the versions before that.
*Corinna Vinschen <vinschen@redhat.com> 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"
<izhar@checkpoint.com>.
*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 <aslam@funk.com>.
*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 <vix@cyber.ee> via Richard Levitte*
* Add the configuration target linux-s390x.
*Neale Ferguson <Neale.Ferguson@SoftwareAG-USA.com> 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" <dan@bti.net>*
* 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 <dpc@qualys.com>*
### Changes between 0.9.6b and 0.9.6c [21 dec 2001]
* Fix BN_rand_range bug pointed out by Dominikus Scherkl
<Dominikus.Scherkl@biodata.com>. (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 <andy.schneider@bjss.co.uk>*
* [In 0.9.6c-engine release:]
Fix mutex callback return values in crypto/engine/hw_ncipher.c.
*Andy Schneider <andy.schneider@bjss.co.uk>*
* [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 <rshapiro@abinitio.com>*
* [In 0.9.6c-engine release:]
Add support for Broadcom crypto accelerator cards, backported
from 0.9.7.
*Broadcom, Nalin Dahyabhai <nalin@redhat.com>, 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 <gbenson@redhat.com>*
* 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 <rsalz@zolera.com>*
* 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 <andy.schneider@bjss.co.uk>*
* 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 <ekr@rtfm.com>*
* 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 <gerberb@zenez.com>).
*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 <jim.ellis@cavium.com>*
* 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 <AYoung1@NCSUS.JNJ.COM>*
* 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" <deengert@anl.gov>.)
*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" <shinton@netopia.com>).
*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 <mooney@dogbert.cc.ndsu.NoDak.edu> 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 <lampa@fee.vutbr.cz>*
* 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 <vitek@roguewave.com>*
* Add support for shared libraries under Irix.
*Albert Chin-A-Young <china@thewrittenword.com>*
* Add configuration option to build on Linux on both big-endian and
little-endian MIPS.
*Ralf Baechle <ralf@uni-koblenz.de>*
* Add the possibility to create shared libraries on HP-UX.
*Richard Levitte*
### Changes between 0.9.6a and 0.9.6b [9 Jul 2001]
* Change ssleay_rand_bytes (crypto/rand/md_rand.c)
to avoid a SSLeay/OpenSSL PRNG weakness pointed out by
Markku-Juhani O. Saarinen <markku-juhani.saarinen@nokia.com>:
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 <Paul.Rose@bridge.com>*
* 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 <hzheng@atdsprint.com>*
* Change Configure and Makefiles to provide EXE_EXT, which will contain
the default extension for executables, if any. Also, make the perl
scripts that use symlink() to test if it really exists and use "cp"
if it doesn't. All this made OpenSSL compilable and installable in
CygWin.
*Richard Levitte*
* Fix for asn1_GetSequence() for indefinite length constructed data.
If SEQUENCE is length is indefinite just set c->slen to the total
amount of data available.
*Steve Henson, reported by shige@FreeBSD.org*
*This change does not apply to 0.9.7.*
* Change bctest to avoid here-documents inside command substitution
(workaround for FreeBSD /bin/sh bug).
For compatibility with Ultrix, avoid shell functions (introduced
in the bctest version that searches along $PATH).
*Bodo Moeller*
* Rename 'des_encrypt' to 'des_encrypt1'. This avoids the clashes
with des_encrypt() defined on some operating systems, like Solaris
and UnixWare.
*Richard Levitte*
* Check the result of RSA-CRT (see D. Boneh, R. DeMillo, R. Lipton:
On the Importance of Eliminating Errors in Cryptographic
Computations, J. Cryptology 14 (2001) 2, 101-119,
<http://theory.stanford.edu/~dabo/papers/faults.ps.gz>).
*Ulf Moeller*
* MIPS assembler BIGNUM division bug fix.
*Andy Polyakov*
* Disabled incorrect Alpha assembler code.
*Richard Levitte*
* Fix PKCS#7 decode routines so they correctly update the length
after reading an EOC for the EXPLICIT tag.
*Steve Henson*
*This change does not apply to 0.9.7.*
* Fix bug in PKCS#12 key generation routines. This was triggered
if a 3DES key was generated with a 0 initial byte. Include
PKCS12_BROKEN_KEYGEN compilation option to retain the old
(but broken) behaviour.
*Steve Henson*
* Enhance bctest to search for a working bc along $PATH and print
it when found.
*Tim Rice <tim@multitalents.net> 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 <jeremy@baymoo.org>*
* 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 <madwolf@opensca.org>*
* 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 <khockenb@stevens-tech.edu> and
"Bruce W. Forsberg" <bruce.forsberg@baesystems.com>*
* 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" <bruce.forsberg@baesystems.com>*
* ./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 <oddissey@samsung.co.kr>*
* 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 <eday@concentric.net>*
* 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" <Steven.Reddie@ca.com>*
* Fix a deadlock in CRYPTO_mem_leaks().
*Bodo Moeller*
* Use better test patterns in bntest.
*Ulf Möller*
* rand_win.c fix for Borland C.
*Ulf Möller*
* BN_rshift bugfix for n == 0.
*Bodo Moeller*
* Add a 'bctest' script that checks for some known 'bc' bugs
so that 'make test' does not abort just because 'bc' is broken.
*Bodo Moeller*
* Store verify_result within SSL_SESSION also for client side to
avoid potential security hole. (Re-used sessions on the client side
always resulted in verify_result==X509_V_OK, not using the original
result of the server certificate verification.)
*Lutz Jaenicke*
* Fix ssl3_pending: If the record in s->s3->rrec is not of type
SSL3_RT_APPLICATION_DATA, return 0.
Similarly, change ssl2_pending to return 0 if SSL_in_init(s) is true.
*Bodo Moeller*
* Fix SSL_peek:
Both ssl2_peek and ssl3_peek, which were totally broken in earlier
releases, have been re-implemented by renaming the previous
implementations of ssl2_read and ssl3_read to ssl2_read_internal
and ssl3_read_internal, respectively, and adding 'peek' parameters
to them. The new ssl[23]_{read,peek} functions are calls to
ssl[23]_read_internal with the 'peek' flag set appropriately.
A 'peek' parameter has also been added to ssl3_read_bytes, which
does the actual work for ssl3_read_internal.
*Bodo Moeller*
* Initialise "ex_data" member of RSA/DSA/DH structures prior to calling
the method-specific "init()" handler. Also clean up ex_data after
calling the method-specific "finish()" handler. Previously, this was
happening the other way round.
*Geoff Thorpe*
* Increase BN_CTX_NUM (the number of BIGNUMs in a BN_CTX) to 16.
The previous value, 12, was not always sufficient for BN_mod_exp().
*Bodo Moeller*
* Make sure that shared libraries get the internal name engine with
the full version number and not just 0. This should mark the
shared libraries as not backward compatible. Of course, this should
be changed again when we can guarantee backward binary compatibility.
*Richard Levitte*
* Fix typo in get_cert_by_subject() in by_dir.c
*Jean-Marc Desperrier <jean-marc.desperrier@certplus.com>*
* 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 <gertz@epact.se>*
* 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 <jaltman@columbia.edu>*
* 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 <djm@mindrot.org>.
*Richard Levitte*
* Add a large number of documentation files for many SSL routines.
*Lutz Jaenicke <Lutz.Jaenicke@aet.TU-Cottbus.DE>*
* Add a configuration entry for Sony News 4.
*NAKAJI Hiroyuki <nakaji@tutrp.tut.ac.jp>*
* 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 <Martin.Kraemer@MchP.Siemens.De>*
* 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 <su@celocom.de>*
* 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 <andreas@ds3.etech.fh-hamburg.de>*
* A demo state-machine implementation was sponsored by
Nuron (<http://www.nuron.com/>) and is now available in
demos/state_machine.
*Ben Laurie*
* New options added to the 'dgst' utility for signature
generation and verification.
*Steve Henson*
* Unrecognized PKCS#7 content types are now handled via a
catch all ASN1_TYPE structure. This allows unsupported
types to be stored as a "blob" and an application can
encode and decode it manually.
*Steve Henson*
* Fix various signed/unsigned issues to make a_strex.c
compile under VC++.
*Oscar Jacobsson <oscar.jacobsson@celocom.com>*
* 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 <sven@tartu.cyber.ee>*
* 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 <assar@sics.se>, 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 <scott@xypro.com>*
* 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_<name>(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 <bertie@ncipher.com> 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 <root@theporch.com>*
* 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 <jjarvie@newsguy.com>*
* 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 <grosser@hisolutions.com>*
* 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 <djm@mindrot.org>, 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
<attili@amaxo.com>*
* 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 <YostW@tce.com>*
* 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 <shadow@DEMENTIA.ORG>*
* Fix so V_ASN1_APP_CHOOSE works again: however its use is strongly
discouraged.
*Steve Henson, pointed out by Brian Korver <briank@cs.stanford.edu>*
* 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 <rolf@suse.de>*
* Assembler module support for Mingw32.
*Ulf Möller*
* Shared library support for HPUX (in shlib/).
*Lutz Jaenicke <Lutz.Jaenicke@aet.TU-Cottbus.DE> and Anonymous*
* Shared library support for Solaris gcc.
*Lutz Behnke <behnke@trustcenter.de>*
### 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 <agray@iconsinc.com>*
* 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 <peter@runestig.com>*
* 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 <das33@cornell.edu>*
* Support EGD <http://www.lothar.com/tech/crypto/>. 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*
* `<openssl/opensslconf.h>` (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 <openssl/opensslconf.h>
defines all pertinent `NO_<algo>` 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 <Martin.Kraemer@Mch.SNI.De>*
* 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 <Lutz.Jaenicke@aet.TU-Cottbus.DE>*
* 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 <kris@hub.freebsd.org>, 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 <roy@centicsystems.ca>*
* 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 <fheymans@isaserver.be>, 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 <pocheng@nst.com.tw>, 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 <geoff@eu.c2.net>*
* 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 <levitte@stacken.kth.se>*
* 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 <sampo@mail.neuronio.pt>*
* 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 <arne@ats.cyber.ee>*
* 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 <madwolf@comune.modena.it> 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
<madwolf@comune.modena.it>. The new option is called -extensions
and can be applied to ca, req and x509. Also -reqexts to override
the request extensions in req and -crlexts to override the crl extensions
in ca.
*Steve Henson*
* Add new feature to the SPKAC handling in ca. Now you can include
the same field multiple times by preceding it by "XXXX." for example:
1.OU="Unit name 1"
2.OU="Unit name 2"
this is the same syntax as used in the req config file.
*Steve Henson*
* Allow certificate extensions to be added to certificate requests. These
are specified in a 'req_extensions' option of the req section of the
config file. They can be printed out with the -text option to req but
are otherwise ignored at present.
*Steve Henson*
* Fix a horrible bug in enc_read() in crypto/evp/bio_enc.c: if the first
data read consists of only the final block it would not decrypted because
EVP_CipherUpdate() would correctly report zero bytes had been decrypted.
A misplaced 'break' also meant the decrypted final block might not be
copied until the next read.
*Steve Henson*
* Initial support for DH_METHOD. Again based on RSA_METHOD. Also added
a few extra parameters to the DH structure: these will be useful if
for example we want the value of 'q' or implement X9.42 DH.
*Steve Henson*
* Initial support for DSA_METHOD. This is based on the RSA_METHOD and
provides hooks that allow the default DSA functions or functions on a
"per key" basis to be replaced. This allows hardware acceleration and
hardware key storage to be handled without major modification to the
library. Also added low-level modexp hooks and CRYPTO_EX structure and
associated functions.
*Steve Henson*
* Add a new flag to memory BIOs, BIO_FLAG_MEM_RDONLY. This marks the BIO
as "read only": it can't be written to and the buffer it points to will
not be freed. Reading from a read only BIO is much more efficient than
a normal memory BIO. This was added because there are several times when
an area of memory needs to be read from a BIO. The previous method was
to create a memory BIO and write the data to it, this results in two
copies of the data and an O(n^2) reading algorithm. There is a new
function BIO_new_mem_buf() which creates a read only memory BIO from
an area of memory. Also modified the PKCS#7 routines to use read only
memory BIOs.
*Steve Henson*
* Bugfix: ssl23_get_client_hello did not work properly when called in
state SSL23_ST_SR_CLNT_HELLO_B, i.e. when the first 7 bytes of
a SSLv2-compatible client hello for SSLv3 or TLSv1 could be read,
but a retry condition occurred while trying to read the rest.
*Bodo Moeller*
* The PKCS7_ENC_CONTENT_new() function was setting the content type as
NID_pkcs7_encrypted by default: this was wrong since this should almost
always be NID_pkcs7_data. Also modified the PKCS7_set_type() to handle
the encrypted data type: this is a more sensible place to put it and it
allows the PKCS#12 code to be tidied up that duplicated this
functionality.
*Steve Henson*
* Changed obj_dat.pl script so it takes its input and output files on
the command line. This should avoid shell escape redirection problems
under Win32.
*Steve Henson*
* Initial support for certificate extension requests, these are included
in things like Xenroll certificate requests. Included functions to allow
extensions to be obtained and added.
*Steve Henson*
* -crlf option to s_client and s_server for sending newlines as
CRLF (as required by many protocols).
*Bodo Moeller*
### Changes between 0.9.3a and 0.9.4 [09 Aug 1999]
* Install libRSAglue.a when OpenSSL is built with RSAref.
*Ralf S. Engelschall*
* A few more `#ifndef NO_FP_API / #endif` pairs for consistency.
*Andrija Antonijevic <TheAntony2@bigfoot.com>*
* 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 <dmiller@ilogic.com.au>; 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_<TYPE>_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 <pre@mo.msk.ru>*
* 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 <Doug.Erickson@Part.NET>*
* 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 <bwelling@tislabs.com>*
* 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 <bwheeler@authentica-security.com>*
* 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 <khjeon@sds.samsung.co.kr>*
* 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 <MRC@Panda.COM>.
*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 <ray.miller@oucs.ox.ac.uk>*
"linux-sparc" configuration.
*Christian Forster <fo@hawo.stw.uni-erlangen.de>*
* 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 <Martin.Kraemer@MchP.Siemens.De>*
* Support BS2000/OSD-POSIX.
*Martin Kraemer <Martin.Kraemer@MchP.Siemens.De>*
* 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 <appro@fy.chalmers.se>*
* 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 <appro@fy.chalmers.se>*
* VMS support.
*Richard Levitte <richard@levitte.org>*
* 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 <sak@parallelconsulting.com>, 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 <jj@void.si>, modified by Ulf Möller*
* Support Mingw32.
*Ulf Möller*
* SHA-1 cleanups and performance enhancements.
*Andy Polyakov <appro@fy.chalmers.se>*
* Sparc v8plus assembler for the bignum library.
*Andy Polyakov <appro@fy.chalmers.se>*
* Accept any -xxx and +xxx compiler options in Configure.
*Ulf Möller*
* Update HPUX configuration.
*Anonymous*
* Add missing `sk_<type>_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 <niels@netbox.org>*
* New Configure option `no-<cipher>` (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 `<foo.h>` to `<openssl/foo.h>`.
*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 <merlin@baltimore.ie>*
* Fix lots of warnings.
*Richard Levitte <levitte@stacken.kth.se>*
* 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 <levitte@stacken.kth.se>*
* Fix problems with sizeof(long) == 8.
*Andy Polyakov <appro@fy.chalmers.se>*
* Change functions to ANSI C.
*Ulf Möller*
* Fix typos in error codes.
*Martin Kraemer <Martin.Kraemer@MchP.Siemens.De>, Ulf Möller*
* Remove defunct assembler files from Configure.
*Ulf Möller*
* SPARC v8 assembler BIGNUM implementation.
*Andy Polyakov <appro@fy.chalmers.se>*
* 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 <nils@medcom.se>*
* 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 <certfile>` facility which revokes a certificate
specified in `<certfile>` 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 <madwolf@openca.org>, 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 <cipher>` 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 <niels@netbox.org>*
* 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 <igor@pobox.org>*
* Get rid of redundant BN file bn_mulw.c, and rename bn_div64 to
bn_div_words in alpha.s.
*Hannes Reinecke <H.Reinecke@hw.ac.uk> 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 <ulf@fitug.de>*
* Move definitions of IS_SET/IS_SEQUENCE inside crypto/asn1/asn1.h
so they no longer are missing under -DNOPROTO.
*Soren S. Jorvang <soren@t.dk>*
### 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 <ulf@fitug.de>*
* Remove some legacy and erroneous uses of malloc, free instead of
Malloc, Free.
*Lennart Bang <lob@netstream.se>, with minor changes by Steve*
* Make rsa_oaep_test return non-zero on error.
*Ulf Moeller <ulf@fitug.de>*
* 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 <Matthias.Loepfe@AdNovum.CH>*
* 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 <Matthias.Loepfe@adnovum.ch>*
* Let util/clean-depend.pl work also with older Perl 5.00x versions.
*Matthias Loepfe <Matthias.Loepfe@adnovum.ch>*
* 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 <kroneru@yahoo.com> 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 <kenji@miyake.org>, integrated by Ben Laurie*
* Add config entry for Linux on MIPS.
*John Tobey <jtobey@channel1.com>*
* 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 <id>:<details>`,
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 `<id>` with value
`<details>` and `perl Configure <id>` 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 <lob@kulthea.stacken.kth.se>*
* Don't install bss_file.c under PREFIX/include/
*Lennart Bong <lob@kulthea.stacken.kth.se>*
* Get the Win32 compile working again. Modify mkdef.pl so it can handle
functions that return function pointers and has support for NT specific
stuff. Fix mk1mf.pl and VC-32.pl to support NT differences also. Various
#ifdef WIN32 and WINNTs sprinkled about the place and some changes from
unsigned to signed types: this was killing the Win32 compile.
*Steve Henson*
* Add new certificate file to stack functions,
SSL_add_dir_cert_subjects_to_stack() and
SSL_add_file_cert_subjects_to_stack(). These largely supplant
SSL_load_client_CA_file(), and can be used to add multiple certs easily
to a stack (usually this is then handed to SSL_CTX_set_client_CA_list()).
This means that Apache-SSL and similar packages don't have to mess around
to add as many CAs as they want to the preferred list.
*Ben Laurie*
* Experiment with doxygen documentation. Currently only partially applied to
ssl/ssl_lib.c.
See <http://www.stack.nl/~dimitri/doxygen/index.html>, and run doxygen with
openssl.doxy as the configuration file.
*Ben Laurie*
* Get rid of remaining C++-style comments which strict C compilers hate.
*Ralf S. Engelschall, pointed out by Carlos Amengual*
* Changed BN_RECURSION in bn_mont.c to BN_RECURSION_MONT so it is not
compiled in by default: it has problems with large keys.
*Steve Henson*
* Add a bunch of SSL_xxx() functions for configuring the temporary RSA and
DH private keys and/or callback functions which directly correspond to
their SSL_CTX_xxx() counterparts but work on a per-connection basis. This
is needed for applications which have to configure certificates on a
per-connection basis (e.g. Apache+mod_ssl) instead of a per-context basis
(e.g. s_server).
For the RSA certificate situation is makes no difference, but
for the DSA certificate situation this fixes the "no shared cipher"
problem where the OpenSSL cipher selection procedure failed because the
temporary keys were not overtaken from the context and the API provided
no way to reconfigure them.
The new functions now let applications reconfigure the stuff and they
are in detail: SSL_need_tmp_RSA, SSL_set_tmp_rsa, SSL_set_tmp_dh,
SSL_set_tmp_rsa_callback and SSL_set_tmp_dh_callback. Additionally a new
non-public-API function ssl_cert_instantiate() is used as a helper
function and also to reduce code redundancy inside ssl_rsa.c.
*Ralf S. Engelschall*
* Move s_server -dcert and -dkey options out of the undocumented feature
area because they are useful for the DSA situation and should be
recognized by the users.
*Ralf S. Engelschall*
* Fix the cipher decision scheme for export ciphers: the export bits are
*not* within SSL_MKEY_MASK or SSL_AUTH_MASK, they are within
SSL_EXP_MASK. So, the original variable has to be used instead of the
already masked variable.
*Richard Levitte <levitte@stacken.kth.se>*
* Fix `port` variable from `int` to `unsigned int` in crypto/bio/b_sock.c
*Richard Levitte <levitte@stacken.kth.se>*
* 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 <levitte@stacken.kth.se>*
* 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 <arne@ats.cyber.ee>*
* 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 <arne@ats.cyber.ee>, 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 <ulf@fitug.de>*
* 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 <ulf@fitug.de>, 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 <eabalea@certplus.com>*
* 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 <Matthias.Loepfe@adnovum.ch>*
* 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 <batie@aahz.jf.intel.com>*
* Fixed ms/32all.bat script: `no_asm` -> `no-asm`
*Rainer W. Gerling <gerling@mpg-gv.mpg.de>*
* 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 <jeremy@cnri.reston.va.us>*
* 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 <itojun@kame.net>*
* File was opened incorrectly in randfile.c.
*Ulf Möller <ulf@fitug.de>*
* 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 <ulf@fitug.de>*
* Remove pointless MD5 hash when using DSA keys in ca.
*Anonymous <nobody@replay.com>*
* 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 <nobody@replay.com>*
* 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 <neil.costigan@celocom.com>*
* 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 <fheymans@isaserver.be>*
* If a DH key is generated in s3_srvr.c, don't blow it by trying to use
NULL pointers.
*Anonymous <nobody@replay.com>*
* 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 <nobody@replay.com>*
* 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 <arne@ats.cyber.ee>*
* rsa_eay.c would attempt to free a NULL context.
*Arne Ansper <arne@ats.cyber.ee>*
* BIO_s_socket() had a broken should_retry() on Windoze.
*Arne Ansper <arne@ats.cyber.ee>*
* BIO_f_buffer() didn't pass on BIO_CTRL_FLUSH.
*Arne Ansper <arne@ats.cyber.ee>*
* 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 <command>`
are no longer created. This way we have a single and consistent command
line interface `openssl <command>`, similar to `cvs <command>`.
*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 <gp@nsj.co.jp>*
* 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 <ulf@fitug.de>*
* 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 <beckman@acl.lanl.gov>*
* 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 <shenson@bigfoot.com>*
* 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 <ebishop@spyglass.com>*
<!-- Links -->
+[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
diff --git a/crypto/openssl/CONTRIBUTING.md b/crypto/openssl/CONTRIBUTING.md
index 15490fd9f620..fec6616e21fe 100644
--- a/crypto/openssl/CONTRIBUTING.md
+++ b/crypto/openssl/CONTRIBUTING.md
@@ -1,110 +1,112 @@
HOW TO CONTRIBUTE TO OpenSSL
============================
Please visit our [Getting Started] page for other ideas about how to contribute.
[Getting Started]: <https://www.openssl.org/community/getting-started.html>
Development is done on GitHub in the [openssl/openssl] repository.
[openssl/openssl]: <https://github.com/openssl/openssl>
-To request new a feature, ask a question, or report a bug,
+To request a new feature, ask a question, or report a bug,
please open an [issue on GitHub](https://github.com/openssl/openssl/issues).
To submit a patch or implement a new feature, please open a
[pull request on GitHub](https://github.com/openssl/openssl/pulls).
If you are thinking of making a large contribution,
open an issue for it before starting work, to get comments from the community.
Someone may be already working on the same thing,
or there may be special reasons why a feature is not implemented.
To make it easier to review and accept your pull request, please follow these
guidelines:
1. Anything other than a trivial contribution requires a [Contributor
License Agreement] (CLA), giving us permission to use your code.
If your contribution is too small to require a CLA (e.g., fixing a spelling
mistake), then place the text "`CLA: trivial`" on a line by itself below
the rest of your commit message separated by an empty line, like this:
```
One-line summary of trivial change
Optional main body of commit message. It might contain a sentence
or two explaining the trivial change.
CLA: trivial
```
It is not sufficient to only place the text "`CLA: trivial`" in the GitHub
pull request description.
[Contributor License Agreement]: <https://www.openssl.org/policies/cla.html>
To amend a missing "`CLA: trivial`" line after submission, do the following:
```
git commit --amend
# add the line, save and quit the editor
git push -f [<repository> [<branch>]]
```
2. All source files should start with the following text (with
appropriate comment characters at the start of each line and the
year(s) updated):
```
Copyright 20xx-20yy 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
```
3. Patches should be as current as possible; expect to have to rebase
often. We do not accept merge commits, you will have to remove them
(usually by rebasing) before it will be acceptable.
- 4. Code provided should follow our [coding style] and compile without warnings.
+ 4. Code provided should follow our [coding style] and [documentation policy]
+ and compile without warnings.
There is a [Perl tool](util/check-format.pl) that helps
finding code formatting mistakes and other coding style nits.
Where `gcc` or `clang` is available, you should use the
`--strict-warnings` `Configure` option. OpenSSL compiles on many varied
platforms: try to ensure you only use portable features.
Clean builds via GitHub Actions are required. They are started automatically
whenever a PR is created or updated by committers.
[coding style]: https://www.openssl.org/policies/technical/coding-style.html
+ [documentation policy]: https://openssl.org/policies/technical/documentation-policy.html
5. When at all possible, code contributions should include tests. These can
either be added to an existing test, or completely new. Please see
[test/README.md](test/README.md) for information on the test framework.
6. New features or changed functionality must include
documentation. Please look at the `.pod` files in `doc/man[1357]` for
examples of our style. Run `make doc-nits` to make sure that your
documentation changes are clean.
7. For user visible changes (API changes, behaviour changes, ...),
consider adding a note in [CHANGES.md](CHANGES.md).
This could be a summarising description of the change, and could
explain the grander details.
Have a look through existing entries for inspiration.
Please note that this is NOT simply a copy of git-log one-liners.
Also note that security fixes get an entry in [CHANGES.md](CHANGES.md).
This file helps users get more in-depth information of what comes
with a specific release without having to sift through the higher
noise ratio in git-log.
8. For larger or more important user visible changes, as well as
security fixes, please add a line in [NEWS.md](NEWS.md).
On exception, it might be worth adding a multi-line entry (such as
the entry that announces all the types that became opaque with
OpenSSL 1.1.0).
This file helps users get a very quick summary of what comes with a
specific release, to see if an upgrade is worth the effort.
9. Guidelines how to integrate error output of new crypto library modules
can be found in [crypto/err/README.md](crypto/err/README.md).
diff --git a/crypto/openssl/Configurations/10-main.conf b/crypto/openssl/Configurations/10-main.conf
index ff8af7146318..1155d9859c56 100644
--- a/crypto/openssl/Configurations/10-main.conf
+++ b/crypto/openssl/Configurations/10-main.conf
@@ -1,1955 +1,1962 @@
## -*- mode: perl; -*-
## Standard openssl configuration targets.
# Helper functions for the Windows configs
my $vc_win64a_info = {};
sub vc_win64a_info {
unless (%$vc_win64a_info) {
if (`nasm -v 2>NUL` =~ /NASM version ([0-9]+\.[0-9]+)/ && $1 >= 2.0) {
$vc_win64a_info = { AS => "nasm",
ASFLAGS => "-g",
asflags => "-Ox -f win64 -DNEAR",
asoutflag => "-o ",
perlasm_scheme => "nasm" };
} elsif ($disabled{asm}) {
# assembler is still used to compile uplink shim
$vc_win64a_info = { AS => "ml64",
ASFLAGS => "/nologo /Zi",
asflags => "/c /Cp /Cx",
asoutflag => "/Fo",
perlasm_scheme => "masm" };
} else {
$die->("NASM not found - make sure it's installed and available on %PATH%\n");
$vc_win64a_info = { AS => "{unknown}",
ASFLAGS => "",
asflags => "",
asoutflag => "",
perlasm_scheme => "auto" };
}
}
return $vc_win64a_info;
}
my $vc_win32_info = {};
sub vc_win32_info {
unless (%$vc_win32_info) {
my $ver=`nasm -v 2>NUL`;
my $vew=`nasmw -v 2>NUL`;
if ($ver ne "" || $vew ne "") {
$vc_win32_info = { AS => $ver ge $vew ? "nasm" : "nasmw",
ASFLAGS => "",
asflags => "-f win32",
asoutflag => "-o ",
perlasm_scheme => "win32n" };
} elsif ($disabled{asm}) {
# not actually used, uplink shim is inlined into C code
$vc_win32_info = { AS => "ml",
ASFLAGS => "/nologo /Zi",
asflags => "/Cp /coff /c /Cx",
asoutflag => "/Fo",
perlasm_scheme => "win32" };
} else {
$die->("NASM not found - make sure it's installed and available on %PATH%\n");
$vc_win32_info = { AS => "{unknown}",
ASFLAGS => "",
asflags => "",
asoutflag => "",
perlasm_scheme => "win32" };
}
}
return $vc_win32_info;
}
my $vc_wince_info = {};
sub vc_wince_info {
unless (%$vc_wince_info) {
# sanity check
$die->('%OSVERSION% is not defined') if (!defined(env('OSVERSION')));
$die->('%PLATFORM% is not defined') if (!defined(env('PLATFORM')));
$die->('%TARGETCPU% is not defined') if (!defined(env('TARGETCPU')));
#
# Idea behind this is to mimic flags set by eVC++ IDE...
#
my $wcevers = env('OSVERSION'); # WCENNN
my $wcevernum;
my $wceverdotnum;
if ($wcevers =~ /^WCE([1-9])([0-9]{2})$/) {
$wcevernum = "$1$2";
$wceverdotnum = "$1.$2";
} else {
$die->('%OSVERSION% value is insane');
$wcevernum = "{unknown}";
$wceverdotnum = "{unknown}";
}
my $wcecdefs = "-D_WIN32_WCE=$wcevernum -DUNDER_CE=$wcevernum"; # -D_WIN32_WCE=NNN
my $wcelflag = "/subsystem:windowsce,$wceverdotnum"; # ...,N.NN
my $wceplatf = env('PLATFORM');
$wceplatf =~ tr/a-z0-9 /A-Z0-9_/;
$wcecdefs .= " -DWCE_PLATFORM_$wceplatf";
my $wcetgt = env('TARGETCPU'); # just shorter name...
SWITCH: for($wcetgt) {
/^X86/ && do { $wcecdefs.=" -Dx86 -D_X86_ -D_i386_ -Di_386_";
$wcelflag.=" /machine:X86"; last; };
/^ARMV4[IT]/ && do { $wcecdefs.=" -DARM -D_ARM_ -D$wcetgt";
$wcecdefs.=" -DTHUMB -D_THUMB_" if($wcetgt=~/T$/);
$wcecdefs.=" -QRarch4T -QRinterwork-return";
$wcelflag.=" /machine:THUMB"; last; };
/^ARM/ && do { $wcecdefs.=" -DARM -D_ARM_ -D$wcetgt";
$wcelflag.=" /machine:ARM"; last; };
/^MIPSIV/ && do { $wcecdefs.=" -DMIPS -D_MIPS_ -DR4000 -D$wcetgt";
$wcecdefs.=" -D_MIPS64 -QMmips4 -QMn32";
$wcelflag.=" /machine:MIPSFPU"; last; };
/^MIPS16/ && do { $wcecdefs.=" -DMIPS -D_MIPS_ -DR4000 -D$wcetgt";
$wcecdefs.=" -DMIPSII -QMmips16";
$wcelflag.=" /machine:MIPS16"; last; };
/^MIPSII/ && do { $wcecdefs.=" -DMIPS -D_MIPS_ -DR4000 -D$wcetgt";
$wcecdefs.=" -QMmips2";
$wcelflag.=" /machine:MIPS"; last; };
/^R4[0-9]{3}/ && do { $wcecdefs.=" -DMIPS -D_MIPS_ -DR4000";
$wcelflag.=" /machine:MIPS"; last; };
/^SH[0-9]/ && do { $wcecdefs.=" -D$wcetgt -D_${wcetgt}_ -DSHx";
$wcecdefs.=" -Qsh4" if ($wcetgt =~ /^SH4/);
$wcelflag.=" /machine:$wcetgt"; last; };
{ $wcecdefs.=" -D$wcetgt -D_${wcetgt}_";
$wcelflag.=" /machine:$wcetgt"; last; };
}
$vc_wince_info = { cppflags => $wcecdefs,
lflags => $wcelflag };
}
return $vc_wince_info;
}
# Helper functions for the VMS configs
my $vms_info = {};
sub vms_info {
my $pointer_size_str = $config{target} =~ m|-p(\d+)$| ? $1 : "";
# For the case where Configure iterate through all config targets, such
# as when listing them and their details, we reset info if the pointer
# size changes.
if (%$vms_info && $vms_info->{pointer_size} ne $pointer_size_str) {
$vms_info = {};
}
unless (%$vms_info) {
$vms_info->{disable_warns} = [
"CXXPRAGMANA", # Shut up about unknown / unsupported pragmas
];
$vms_info->{pointer_size} = $pointer_size_str;
if ($pointer_size_str eq "64") {
`PIPE CC /NOCROSS_REFERENCE /NOLIST /NOOBJECT /WARNINGS = DISABLE = ( MAYLOSEDATA3, EMPTYFILE ) NL: 2> NL:`;
if ($? == 0) {
push @{$vms_info->{disable_warns}}, "MAYLOSEDATA3";
}
}
unless ($disabled{zlib}) {
my $default_zlib = 'GNV$LIBZSHR' . $pointer_size_str;
if (defined($disabled{"zlib-dynamic"})) {
$vms_info->{zlib} = $withargs{zlib_lib} || "$default_zlib/SHARE";
} else {
$vms_info->{def_zlib} = $withargs{zlib_lib} || $default_zlib;
# In case the --with-zlib-lib value contains something like
# /SHARE or /LIB or so at the end, remove it.
$vms_info->{def_zlib} =~ s|/.*$||g;
}
}
if ($config{target} =~ /-ia64/) {
`PIPE ias -H 2> NL:`;
if ($? == 0) {
$vms_info->{AS} = "ias";
$vms_info->{ASFLAGS} = '-d debug';
$vms_info->{asflags} = '"-N" vms_upcase';
$vms_info->{asoutflag} = "-o ";
$vms_info->{perlasm_scheme} = "ias";
}
}
}
return $vms_info;
}
my %targets = (
#### Basic configs that should work on any 32-bit box
"gcc" => {
inherit_from => [ "BASE_unix" ],
CC => "gcc",
CFLAGS => picker(debug => "-O0 -g",
release => "-O3"),
thread_scheme => "(unknown)",
bn_ops => "BN_LLONG",
},
"cc" => {
inherit_from => [ "BASE_unix" ],
CC => "cc",
CFLAGS => "-O",
thread_scheme => "(unknown)",
},
#### VOS Configurations
"vos-gcc" => {
inherit_from => [ "BASE_unix" ],
CC => "gcc",
CFLAGS => picker(default => "-Wall",
debug => "-O0 -g",
release => "-O3"),
cppflags => "-D_POSIX_C_SOURCE=200112L -D_BSD -D_VOS_EXTENDED_NAMES",
lib_cppflags => "-DB_ENDIAN",
thread_scheme => "(unknown)",
sys_id => "VOS",
lflags => add("-Wl,-map"),
bn_ops => "BN_LLONG",
shared_extension => ".so",
},
#### Solaris configurations
"solaris-common" => {
inherit_from => [ "BASE_unix" ],
template => 1,
lib_cppflags => "-DFILIO_H",
ex_libs => add("-lsocket -lnsl -ldl"),
dso_scheme => "dlfcn",
thread_scheme => "pthreads",
},
#### Solaris common with Sun C setups
"solaris-common-cc" => {
inherit_from => [ "solaris-common" ],
template => 1,
shared_target => "solaris",
shared_ldflag => "-Wl,-Bsymbolic",
shared_defflag => "-Wl,-M,",
shared_sonameflag=> "-Wl,-h,",
},
#### Solaris common with GNU C setups
"solaris-common-gcc" => {
inherit_from => [ "solaris-common" ],
template => 1,
shared_target => "solaris-gcc-shared", # The rest is on shared_info.pl
},
#### Solaris x86 with GNU C setups
"solaris-x86-gcc" => {
# NB. GNU C has to be configured to use GNU assembler, and not
# /usr/ccs/bin/as. Failure to comply will result in compile
# failures [at least] in 32-bit build.
inherit_from => [ "solaris-common-gcc" ],
CC => "gcc",
CFLAGS => add_before(picker(default => "-Wall",
debug => "-O0 -g",
release => "-O3 -fomit-frame-pointer")),
cflags => add(threads("-pthread")),
lib_cppflags => add("-DL_ENDIAN"),
ex_libs => add(threads("-pthread")),
bn_ops => "BN_LLONG",
shared_cflag => "-fPIC",
shared_ldflag => add_before("-shared -static-libgcc"),
asm_arch => 'x86',
perlasm_scheme => 'elf',
},
"solaris64-x86_64-gcc" => {
# -shared -static-libgcc might appear controversial, but modules
# taken from static libgcc do not have relocations and linking
# them into our shared objects doesn't have any negative side
# effects. On the contrary, doing so makes it possible to use
# gcc shared build with Sun C. Given that gcc generates faster
# code [thanks to inline assembler], I would actually recommend
# to consider using gcc shared build even with vendor compiler:-)
# -- <appro@openssl.org>
inherit_from => [ "solaris-common-gcc" ],
CC => "gcc",
CFLAGS => add_before(picker(default => "-Wall",
debug => "-O0 -g",
release => "-O3")),
cflags => add_before("-m64", threads("-pthread")),
lib_cppflags => add("-DL_ENDIAN"),
ex_libs => add(threads("-pthread")),
bn_ops => "SIXTY_FOUR_BIT_LONG",
asm_arch => 'x86_64',
perlasm_scheme => "elf",
shared_cflag => "-fPIC",
shared_ldflag => add_before("-shared -static-libgcc"),
multilib => "/64",
},
#### Solaris x86 with Sun C setups
# There used to be solaris-x86-cc target, but it was removed,
# primarily because 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 today's
# standards. Fortunately gcc is readily available prepackaged
# option, which we can firmly point at...
#
# On related note, solaris64-x86_64-cc target won't compile code
# paths utilizing AVX and post-Haswell instruction extensions.
# Consider switching to solaris64-x86_64-gcc even here...
#
"solaris64-x86_64-cc" => {
inherit_from => [ "solaris-common-cc" ],
CC => "cc",
CFLAGS => add_before(picker(debug => "-g",
release => "-xO5 -xdepend -xbuiltin")),
cflags => add_before("-xarch=generic64 -xstrconst -Xa"),
cppflags => add(threads("-D_REENTRANT")),
lib_cppflags => add("-DL_ENDIAN"),
thread_scheme => "pthreads",
lflags => add(threads("-mt")),
ex_libs => add(threads("-lpthread")),
bn_ops => "SIXTY_FOUR_BIT_LONG",
asm_arch => 'x86_64',
perlasm_scheme => "elf",
shared_cflag => "-KPIC",
shared_ldflag => add_before("-G -dy -z text"),
multilib => "/64",
},
#### SPARC Solaris with GNU C setups
"solaris-sparcv7-gcc" => {
inherit_from => [ "solaris-common-gcc" ],
CC => "gcc",
CFLAGS => add_before(picker(default => "-Wall",
debug => "-O0 -g",
release => "-O3")),
cflags => add(threads("-pthread")),
lib_cppflags => add("-DB_ENDIAN -DBN_DIV2W"),
ex_libs => add(threads("-pthread")),
bn_ops => "BN_LLONG RC4_CHAR",
shared_cflag => "-fPIC",
shared_ldflag => add_before("-shared"),
},
"solaris-sparcv8-gcc" => {
inherit_from => [ "solaris-sparcv7-gcc" ],
cflags => add_before("-mcpu=v8"),
asm_arch => 'sparcv8',
perlasm_scheme => 'void',
},
"solaris-sparcv9-gcc" => {
# -m32 should be safe to add as long as driver recognizes
# -mcpu=ultrasparc
inherit_from => [ "solaris-sparcv7-gcc" ],
cflags => add_before("-m32 -mcpu=ultrasparc"),
asm_arch => 'sparcv9',
perlasm_scheme => 'void',
},
"solaris64-sparcv9-gcc" => {
inherit_from => [ "solaris-sparcv9-gcc" ],
cflags => sub { my $f=join(" ",@_); $f =~ s/\-m32/-m64/; $f; },
bn_ops => "BN_LLONG RC4_CHAR",
multilib => "/64",
},
#### SPARC Solaris with Sun C setups
# SC4.0 doesn't pass 'make test', upgrade to SC5.0 or SC4.2.
# SC4.2 is ok, better than gcc even on bn as long as you tell it -xarch=v8
# SC5.0 note: Compiler common patch 107357-01 or later is required!
"solaris-sparcv7-cc" => {
inherit_from => [ "solaris-common-cc" ],
CC => "cc",
CFLAGS => add_before(picker(debug => "-g",
release => "-xO5 -xdepend")),
cflags => add_before("-xstrconst -Xa"),
cppflags => add(threads("-D_REENTRANT")),
lib_cppflags => add("-DB_ENDIAN -DBN_DIV2W"),
lflags => add(threads("-mt")),
ex_libs => add(threads("-lpthread")),
bn_ops => "BN_LLONG RC4_CHAR",
shared_cflag => "-KPIC",
shared_ldflag => add_before("-G -dy -z text"),
},
####
"solaris-sparcv8-cc" => {
inherit_from => [ "solaris-sparcv7-cc" ],
cflags => add_before("-xarch=v8"),
asm_arch => 'sparcv8',
perlasm_scheme => 'void',
},
"solaris-sparcv9-cc" => {
inherit_from => [ "solaris-sparcv7-cc" ],
cflags => add_before("-xarch=v8plus"),
asm_arch => 'sparcv9',
perlasm_scheme => 'void',
},
"solaris64-sparcv9-cc" => {
inherit_from => [ "solaris-sparcv7-cc" ],
cflags => add_before("-m64 -xarch=sparc"),
bn_ops => "BN_LLONG RC4_CHAR",
asm_arch => 'sparcv9',
perlasm_scheme => 'void',
multilib => "/64",
},
#### IRIX 6.x configs
# Only N32 and N64 ABIs are supported.
"irix-common" => {
inherit_from => [ "BASE_unix" ],
template => 1,
cppflags => threads("-D_SGI_MP_SOURCE"),
lib_cppflags => "-DB_ENDIAN",
ex_libs => add(threads("-lpthread")),
thread_scheme => "pthreads",
dso_scheme => "dlfcn",
shared_target => "self",
shared_ldflag => "-shared -Wl,-Bsymbolic",
shared_sonameflag=> "-Wl,-soname,",
},
"irix-mips3-gcc" => {
inherit_from => [ "irix-common" ],
CC => "gcc",
CFLAGS => picker(debug => "-g -O0",
release => "-O3"),
LDFLAGS => "-static-libgcc",
cflags => "-mabi=n32",
bn_ops => "RC4_CHAR SIXTY_FOUR_BIT",
asm_arch => 'mips64',
perlasm_scheme => "n32",
multilib => "32",
},
"irix-mips3-cc" => {
inherit_from => [ "irix-common" ],
CC => "cc",
CFLAGS => picker(debug => "-g -O0",
release => "-O2"),
cflags => "-n32 -mips3 -use_readonly_const -G0 -rdata_shared",
bn_ops => "RC4_CHAR SIXTY_FOUR_BIT",
asm_arch => 'mips64',
perlasm_scheme => "n32",
multilib => "32",
},
# N64 ABI builds.
"irix64-mips4-gcc" => {
inherit_from => [ "irix-common" ],
CC => "gcc",
CFLAGS => picker(debug => "-g -O0",
release => "-O3"),
LDFLAGS => "-static-libgcc",
cflags => "-mabi=64 -mips4",
bn_ops => "RC4_CHAR SIXTY_FOUR_BIT_LONG",
asm_arch => 'mips64',
perlasm_scheme => "64",
multilib => "64",
},
"irix64-mips4-cc" => {
inherit_from => [ "irix-common" ],
CC => "cc",
CFLAGS => picker(debug => "-g -O0",
release => "-O2"),
cflags => "-64 -mips4 -use_readonly_const -G0 -rdata_shared",
bn_ops => "RC4_CHAR SIXTY_FOUR_BIT_LONG",
asm_arch => 'mips64',
perlasm_scheme => "64",
multilib => "64",
},
#### Unified HP-UX ANSI C configs.
# Special notes:
# - Originally we were optimizing at +O4 level. It should be noted
# that the only difference between +O3 and +O4 is global inter-
# procedural analysis. As it has to be performed during the link
# stage the compiler leaves behind certain pseudo-code in lib*.a
# which might be release or even patch level specific. Generating
# the machine code for and analyzing the *whole* program appears
# to be *extremely* memory demanding while the performance gain is
# actually questionable. The situation is intensified by the default
# HP-UX data set size limit (infamous 'maxdsiz' tunable) of 64MB
# which is way too low for +O4. In other words, doesn't +O3 make
# more sense?
# - Keep in mind that the HP compiler by default generates code
# suitable for execution on the host you're currently compiling at.
# If the toolkit is meant to be used on various PA-RISC processors
# consider './Configure hpux-parisc-[g]cc +DAportable'.
# - -DMD32_XARRAY triggers workaround for compiler bug we ran into in
# 32-bit message digests. (For the moment of this writing) HP C
# doesn't seem to "digest" too many local variables (they make "him"
# chew forever:-). For more details look-up MD32_XARRAY comment in
# crypto/sha/sha_local.h.
# - originally there were 32-bit hpux-parisc2-* targets. They were
# scrapped, because a) they were not interchangeable with other 32-bit
# targets; b) performance-critical 32-bit assembly modules implement
# even PA-RISC 2.0-specific code paths, which are chosen at run-time,
# thus adequate performance is provided even with PA-RISC 1.1 build.
"hpux-common" => {
inherit_from => [ "BASE_unix" ],
template => 1,
defines => add("_XOPEN_SOURCE", "_XOPEN_SOURCE_EXTENDED",
"_HPUX_ALT_XOPEN_SOCKET_API"),
lib_cppflags => "-DB_ENDIAN",
thread_scheme => "pthreads",
dso_scheme => "dlfcn", # overridden in 32-bit PA-RISC builds
shared_target => "self",
bin_lflags => "-Wl,+s,+cdp,../:,+cdp,./:",
shared_ldflag => "-Wl,-B,symbolic,+vnocompatwarnings,-z,+s,+cdp,../:,+cdp,./:",
shared_sonameflag=> "-Wl,+h,",
},
"hpux-parisc-gcc" => {
inherit_from => [ "hpux-common" ],
CC => "gcc",
CFLAGS => picker(debug => "-O0 -g",
release => "-O3"),
cflags => add(threads("-pthread")),
lib_cppflags => add("-DBN_DIV2W"),
ex_libs => add("-ldld", threads("-pthread")),
bn_ops => "BN_LLONG RC4_CHAR",
dso_scheme => "dl",
shared_cflag => "-fPIC",
shared_ldflag => add_before("-shared"),
shared_extension => ".sl.\$(SHLIB_VERSION_NUMBER)",
},
"hpux-parisc1_1-gcc" => {
inherit_from => [ "hpux-parisc-gcc" ],
asm_arch => 'parisc11',
perlasm_scheme => "32",
multilib => "/pa1.1",
},
"hpux64-parisc2-gcc" => {
inherit_from => [ "hpux-common" ],
CC => "gcc",
CFLAGS => combine(picker(debug => "-O0 -g",
release => "-O3")),
cflags => add(threads("-pthread")),
ex_libs => add("-ldl", threads("-pthread")),
bn_ops => "SIXTY_FOUR_BIT_LONG RC4_CHAR",
asm_arch => 'parisc20_64',
perlasm_scheme => "64",
shared_cflag => "-fpic",
shared_ldflag => add_before("-shared"),
shared_extension => ".sl.\$(SHLIB_VERSION_NUMBER)",
multilib => "/pa20_64",
},
# More attempts at unified 10.X and 11.X targets for HP C compiler.
"hpux-parisc-cc" => {
inherit_from => [ "hpux-common" ],
CC => "cc",
CFLAGS => picker(debug => "+O0 +d -g",
release => "+O3"),
cflags => "+Optrs_strongly_typed -Ae +ESlit",
cppflags => threads("-D_REENTRANT"),
lib_cppflags => add("-DBN_DIV2W -DMD32_XARRAY"),
ex_libs => add("-ldld", threads("-lpthread")),
bn_ops => "RC4_CHAR",
dso_scheme => "dl",
shared_cflag => "+Z",
shared_ldflag => add_before("-b"),
shared_extension => ".sl.\$(SHLIB_VERSION_NUMBER)",
},
"hpux-parisc1_1-cc" => {
inherit_from => [ "hpux-parisc-cc" ],
cflags => add_before("+DA1.1"),
asm_arch => 'parisc11',
perlasm_scheme => "32",
multilib => "/pa1.1",
},
"hpux64-parisc2-cc" => {
inherit_from => [ "hpux-common" ],
CC => "cc",
CFLAGS => picker(debug => "+O0 +d -g",
release => "+O3") ,
cflags => "+DD64 +Optrs_strongly_typed -Ae +ESlit",
cppflags => threads("-D_REENTRANT") ,
lib_cppflags => add("-DMD32_XARRAY"),
ex_libs => add("-ldl", threads("-lpthread")),
bn_ops => "SIXTY_FOUR_BIT_LONG RC4_CHAR",
asm_arch => 'parisc20_64',
perlasm_scheme => "64",
shared_cflag => "+Z",
shared_ldflag => add_before("-b"),
shared_extension => ".sl.\$(SHLIB_VERSION_NUMBER)",
multilib => "/pa20_64",
},
# HP/UX IA-64 targets
"hpux-ia64-cc" => {
inherit_from => [ "hpux-common" ],
CC => "cc",
CFLAGS => picker(debug => "+O0 +d -g",
release => "+O2"),
cflags => "-Ae +DD32 +Olit=all -z",
cppflags => add(threads("-D_REENTRANT")),
ex_libs => add("-ldl", threads("-lpthread")),
bn_ops => "SIXTY_FOUR_BIT",
asm_arch => 'ia64',
perlasm_scheme => 'void',
shared_cflag => "+Z",
shared_ldflag => add_before("-b"),
multilib => "/hpux32",
},
"hpux64-ia64-cc" => {
inherit_from => [ "hpux-common" ],
CC => "cc",
CFLAGS => picker(debug => "+O0 +d -g",
release => "+O3"),
cflags => "-Ae +DD64 +Olit=all -z",
cppflags => threads("-D_REENTRANT"),
ex_libs => add("-ldl", threads("-lpthread")),
bn_ops => "SIXTY_FOUR_BIT_LONG",
asm_arch => 'ia64',
perlasm_scheme => 'void',
shared_cflag => "+Z",
shared_ldflag => add_before("-b"),
multilib => "/hpux64",
},
# GCC builds...
"hpux-ia64-gcc" => {
inherit_from => [ "hpux-common" ],
CC => "gcc",
CFLAGS => picker(debug => "-O0 -g",
release => "-O3"),
cflags => add(threads("-pthread")),
ex_libs => add("-ldl", threads("-pthread")),
bn_ops => "SIXTY_FOUR_BIT",
asm_arch => 'ia64',
perlasm_scheme => 'void',
shared_cflag => "-fpic",
shared_ldflag => add_before("-shared"),
multilib => "/hpux32",
},
"hpux64-ia64-gcc" => {
inherit_from => [ "hpux-common" ],
CC => "gcc",
CFLAGS => picker(debug => "-O0 -g",
release => "-O3"),
cflags => combine("-mlp64", threads("-pthread")),
ex_libs => add("-ldl", threads("-pthread")),
bn_ops => "SIXTY_FOUR_BIT_LONG",
asm_arch => 'ia64',
perlasm_scheme => 'void',
shared_cflag => "-fpic",
shared_ldflag => add_before("-shared"),
multilib => "/hpux64",
},
#### HP MPE/iX http://jazz.external.hp.com/src/openssl/
"MPE/iX-gcc" => {
inherit_from => [ "BASE_unix" ],
CC => "gcc",
CFLAGS => "-O3",
cppflags => "-D_POSIX_SOURCE -D_SOCKET_SOURCE",
includes => [ "/SYSLOG/PUB" ],
lib_cppflags => "-DBN_DIV2W",
sys_id => "MPE",
lflags => add("-L/SYSLOG/PUB"),
ex_libs => add("-lsyslog -lsocket -lcurses"),
thread_scheme => "(unknown)",
bn_ops => "BN_LLONG",
},
#### DEC Alpha Tru64 targets. Tru64 is marketing name for OSF/1 version 4
#### and forward. In reality 'uname -s' still returns "OSF1". Originally
#### there were even osf1-* configs targeting prior versions provided,
#### but not anymore...
"tru64-alpha-gcc" => {
inherit_from => [ "BASE_unix" ],
CC => "gcc",
CFLAGS => "-O3",
cflags => add("-std=c9x", threads("-pthread")),
cppflags => "-D_XOPEN_SOURCE=500 -D_OSF_SOURCE",
ex_libs => add("-lrt", threads("-pthread")), # for mlock(2)
bn_ops => "SIXTY_FOUR_BIT_LONG",
asm_arch => 'alpha',
perlasm_scheme => "void",
thread_scheme => "pthreads",
dso_scheme => "dlfcn",
shared_target => "alpha-osf1-shared",
shared_extension => ".so",
},
"tru64-alpha-cc" => {
inherit_from => [ "BASE_unix" ],
CC => "cc",
CFLAGS => "-tune host -fast",
cflags => add("-std1 -readonly_strings",
threads("-pthread")),
cppflags => "-D_XOPEN_SOURCE=500 -D_OSF_SOURCE",
ex_libs => add("-lrt", threads("-pthread")), # for mlock(2)
bn_ops => "SIXTY_FOUR_BIT_LONG",
asm_arch => 'alpha',
perlasm_scheme => "void",
thread_scheme => "pthreads",
dso_scheme => "dlfcn",
shared_target => "alpha-osf1-shared",
shared_ldflag => "-msym",
shared_extension => ".so",
},
####
#### Variety of LINUX:-)
####
# *-generic* is endian-neutral target, but ./config is free to
# throw in -D[BL]_ENDIAN, whichever appropriate...
"linux-generic32" => {
inherit_from => [ "BASE_unix" ],
CC => "gcc",
CXX => "g++",
CFLAGS => picker(default => "-Wall",
debug => "-O0 -g",
release => "-O3"),
CXXFLAGS => picker(default => "-Wall",
debug => "-O0 -g",
release => "-O3"),
cflags => threads("-pthread"),
cxxflags => combine("-std=c++11", threads("-pthread")),
lib_cppflags => "-DOPENSSL_USE_NODELETE",
ex_libs => add("-ldl", threads("-pthread")),
bn_ops => "BN_LLONG RC4_CHAR",
thread_scheme => "pthreads",
dso_scheme => "dlfcn",
shared_target => "linux-shared",
shared_cflag => "-fPIC",
shared_ldflag => sub { $disabled{pinshared} ? () : "-Wl,-znodelete" },
enable => [ "afalgeng" ],
},
"linux-latomic" => {
inherit_from => [ "linux-generic32" ],
ex_libs => add(threads("-latomic")),
},
"linux-generic64" => {
inherit_from => [ "linux-generic32" ],
bn_ops => "SIXTY_FOUR_BIT_LONG RC4_CHAR",
},
"linux-ppc" => {
inherit_from => [ "linux-latomic" ],
asm_arch => 'ppc32',
perlasm_scheme => "linux32",
lib_cppflags => add("-DB_ENDIAN"),
},
"linux-ppc64" => {
inherit_from => [ "linux-generic64" ],
cflags => add("-m64"),
cxxflags => add("-m64"),
lib_cppflags => add("-DB_ENDIAN"),
asm_arch => 'ppc64',
perlasm_scheme => "linux64",
multilib => "64",
},
"linux-ppc64le" => {
inherit_from => [ "linux-generic64" ],
cflags => add("-m64"),
cxxflags => add("-m64"),
lib_cppflags => add("-DL_ENDIAN"),
asm_arch => 'ppc64',
perlasm_scheme => "linux64le",
},
"linux-armv4" => {
################################################################
# Note that -march is not among compiler options in linux-armv4
# target description. Not specifying one is intentional to give
# you choice to:
#
# a) rely on your compiler default by not specifying one;
# b) specify your target platform explicitly for optimal
# performance, e.g. -march=armv6 or -march=armv7-a;
# c) build "universal" binary that targets *range* of platforms
# by specifying minimum and maximum supported architecture;
#
# As for c) option. It actually makes no sense to specify
# maximum to be less than ARMv7, because it's the least
# requirement for run-time switch between platform-specific
# code paths. And without run-time switch performance would be
# equivalent to one for minimum. Secondly, there are some
# natural limitations that you'd have to accept and respect.
# Most notably you can *not* build "universal" binary for
# big-endian platform. This is because ARMv7 processor always
# picks instructions in little-endian order. Another similar
# limitation is that -mthumb can't "cross" -march=armv6t2
# boundary, because that's where it became Thumb-2. Well, this
# limitation is a bit artificial, because it's not really
# impossible, but it's deemed too tricky to support. And of
# course you have to be sure that your binutils are actually
# up to the task of handling maximum target platform. With all
# this in mind here is an example of how to configure
# "universal" build:
#
# ./Configure linux-armv4 -march=armv6 -D__ARM_MAX_ARCH__=8
#
inherit_from => [ "linux-latomic" ],
asm_arch => 'armv4',
perlasm_scheme => "linux32",
},
"linux-aarch64" => {
inherit_from => [ "linux-generic64" ],
asm_arch => 'aarch64',
perlasm_scheme => "linux64",
},
"linux-arm64ilp32" => { # https://wiki.linaro.org/Platform/arm64-ilp32
inherit_from => [ "linux-generic32" ],
cflags => add("-mabi=ilp32"),
cxxflags => add("-mabi=ilp32"),
bn_ops => "SIXTY_FOUR_BIT RC4_CHAR",
asm_arch => 'aarch64',
perlasm_scheme => "linux64",
},
-
+ "linux-arm64ilp32-clang" => { # clang config abi by --target
+ inherit_from => [ "linux-generic32" ],
+ CC => "clang",
+ CXX => "clang++",
+ bn_ops => "SIXTY_FOUR_BIT RC4_CHAR",
+ asm_arch => 'aarch64',
+ perlasm_scheme => "linux64",
+ },
"linux-mips32" => {
# Configure script adds minimally required -march for assembly
# support, if no -march was specified at command line.
inherit_from => [ "linux-latomic" ],
cflags => add("-mabi=32"),
cxxflags => add("-mabi=32"),
asm_arch => 'mips32',
perlasm_scheme => "o32",
},
# mips32 and mips64 below refer to contemporary MIPS Architecture
# specifications, MIPS32 and MIPS64, rather than to kernel bitness.
"linux-mips64" => {
inherit_from => [ "linux-latomic" ],
cflags => add("-mabi=n32"),
cxxflags => add("-mabi=n32"),
bn_ops => "RC4_CHAR SIXTY_FOUR_BIT",
asm_arch => 'mips64',
perlasm_scheme => "n32",
multilib => "32",
},
"linux64-mips64" => {
inherit_from => [ "linux-generic64" ],
cflags => add("-mabi=64"),
cxxflags => add("-mabi=64"),
asm_arch => 'mips64',
perlasm_scheme => "64",
multilib => "64",
},
# riscv64 below refers to contemporary RISCV Architecture
# specifications,
"linux64-riscv64" => {
inherit_from => [ "linux-generic64"],
perlasm_scheme => "linux64",
},
# loongarch64 below refers to contemporary LoongArch Architecture
# specifications,
"linux64-loongarch64" => {
inherit_from => [ "linux-generic64"],
perlasm_scheme => "linux64",
},
#### IA-32 targets...
#### These two targets are a bit aged and are to be used on older Linux
#### machines where gcc doesn't understand -m32 and -m64
"linux-elf" => {
inherit_from => [ "linux-generic32" ],
CFLAGS => add(picker(release => "-fomit-frame-pointer")),
lib_cppflags => add("-DL_ENDIAN"),
bn_ops => "BN_LLONG",
asm_arch => 'x86',
perlasm_scheme => "elf",
},
"linux-aout" => {
inherit_from => [ "BASE_unix" ],
CC => "gcc",
CFLAGS => add(picker(default => "-Wall",
debug => "-O0 -g",
release => "-O3 -fomit-frame-pointer")),
lib_cppflags => add("-DL_ENDIAN"),
bn_ops => "BN_LLONG",
thread_scheme => "(unknown)",
asm_arch => 'x86',
perlasm_scheme => "a.out",
},
#### X86 / X86_64 targets
"linux-x86" => {
inherit_from => [ "linux-generic32" ],
CFLAGS => add(picker(release => "-fomit-frame-pointer")),
cflags => add("-m32"),
cxxflags => add("-m32"),
lib_cppflags => add("-DL_ENDIAN"),
bn_ops => "BN_LLONG",
asm_arch => 'x86',
perlasm_scheme => "elf",
},
"linux-x86-clang" => {
inherit_from => [ "linux-x86" ],
CC => "clang",
CXX => "clang++",
ex_libs => add(threads("-latomic")),
},
"linux-x86_64" => {
inherit_from => [ "linux-generic64" ],
cflags => add("-m64"),
cxxflags => add("-m64"),
lib_cppflags => add("-DL_ENDIAN"),
bn_ops => "SIXTY_FOUR_BIT_LONG",
asm_arch => 'x86_64',
perlasm_scheme => "elf",
multilib => "64",
},
"linux-x86_64-clang" => {
inherit_from => [ "linux-x86_64" ],
CC => "clang",
CXX => "clang++",
},
"linux-x32" => {
inherit_from => [ "linux-generic32" ],
cflags => add("-mx32"),
cxxflags => add("-mx32"),
lib_cppflags => add("-DL_ENDIAN"),
bn_ops => "SIXTY_FOUR_BIT",
asm_arch => 'x86_64',
perlasm_scheme => "elf32",
multilib => "x32",
},
"linux-ia64" => {
inherit_from => [ "linux-generic64" ],
bn_ops => "SIXTY_FOUR_BIT_LONG",
asm_arch => 'ia64',
perlasm_scheme => 'void',
},
"linux64-s390x" => {
inherit_from => [ "linux-generic64" ],
cflags => add("-m64"),
cxxflags => add("-m64"),
lib_cppflags => add("-DB_ENDIAN"),
asm_arch => 's390x',
perlasm_scheme => "64",
multilib => "64",
},
"linux32-s390x" => {
#### So called "highgprs" target for z/Architecture CPUs
# "Highgprs" is kernel feature first implemented in Linux
# 2.6.32, see /proc/cpuinfo. The idea is to preserve most
# significant bits of general purpose registers not only
# upon 32-bit process context switch, but even on
# asynchronous signal delivery to such process. This makes
# it possible to deploy 64-bit instructions even in legacy
# application context and achieve better [or should we say
# adequate] performance. The build is binary compatible with
# linux-generic32, and the idea is to be able to install the
# resulting libcrypto.so alongside generic one, e.g. as
# /lib/highgprs/libcrypto.so.x.y, for ldconfig and run-time
# linker to autodiscover. Unfortunately it doesn't work just
# yet, because of couple of bugs in glibc
# sysdeps/s390/dl-procinfo.c affecting ldconfig and ld.so.1...
#
inherit_from => [ "linux-generic32" ],
cflags => add("-m31 -Wa,-mzarch"),
cxxflags => add("-m31 -Wa,-mzarch"),
lib_cppflags => add("-DB_ENDIAN"),
asm_arch => 's390x',
perlasm_scheme => "31",
multilib => "/highgprs",
},
#### SPARC Linux setups
"linux-sparcv8" => {
inherit_from => [ "linux-latomic" ],
cflags => add("-mcpu=v8"),
cxxflags => add("-mcpu=v8"),
lib_cppflags => add("-DB_ENDIAN -DBN_DIV2W"),
asm_arch => 'sparcv8',
perlasm_scheme => 'void',
},
"linux-sparcv9" => {
# it's a real mess with -mcpu=ultrasparc option under Linux,
# but -Wa,-Av8plus should do the trick no matter what.
inherit_from => [ "linux-latomic" ],
cflags => add("-m32 -mcpu=ultrasparc -Wa,-Av8plus"),
cxxflags => add("-m32 -mcpu=ultrasparc -Wa,-Av8plus"),
lib_cppflags => add("-DB_ENDIAN -DBN_DIV2W"),
asm_arch => 'sparcv9',
perlasm_scheme => 'void',
},
"linux64-sparcv9" => {
# GCC 3.1 is a requirement
inherit_from => [ "linux-generic64" ],
cflags => add("-m64 -mcpu=ultrasparc"),
cxxflags => add("-m64 -mcpu=ultrasparc"),
lib_cppflags => add("-DB_ENDIAN"),
ex_libs => add(threads("-latomic")),
bn_ops => "BN_LLONG RC4_CHAR",
asm_arch => 'sparcv9',
perlasm_scheme => 'void',
multilib => "64",
},
"linux-alpha-gcc" => {
inherit_from => [ "linux-generic64" ],
lib_cppflags => add("-DL_ENDIAN"),
bn_ops => "SIXTY_FOUR_BIT_LONG",
asm_arch => 'alpha',
perlasm_scheme => "void",
},
"linux-c64xplus" => {
inherit_from => [ "BASE_unix" ],
# TI_CGT_C6000_7.3.x is a requirement
CC => "cl6x",
CFLAGS => "-o2 -ox -ms",
cflags => "--linux -ea=.s -eo=.o -mv6400+ -pden",
cxxflags => "--linux -ea=.s -eo=.o -mv6400+ -pden",
cppflags => combine("-DOPENSSL_SMALL_FOOTPRINT",
threads("-D_REENTRANT")),
bn_ops => "BN_LLONG",
thread_scheme => "pthreads",
asm_arch => 'c64xplus',
perlasm_scheme => "void",
dso_scheme => "dlfcn",
shared_target => "linux-shared",
shared_cflag => "--pic",
shared_ldflag => add("-z --sysv --shared"),
ranlib => "true",
},
#### *BSD
"BSD-generic32" => {
# As for thread cflag. Idea is to maintain "collective" set of
# flags, which would cover all BSD flavors. -pthread applies
# to them all, but is treated differently. OpenBSD expands is
# as -D_POSIX_THREAD -lc_r, which is sufficient. FreeBSD 4.x
# expands it as -lc_r, which has to be accompanied by explicit
# -D_THREAD_SAFE and sometimes -D_REENTRANT. FreeBSD 5.x
# expands it as -lc_r, which seems to be sufficient?
inherit_from => [ "BASE_unix" ],
CC => "cc",
CFLAGS => picker(default => "-Wall",
debug => "-O0 -g",
release => "-O3"),
cflags => threads("-pthread"),
cppflags => threads("-D_THREAD_SAFE -D_REENTRANT"),
ex_libs => add(threads("-pthread")),
enable => add("devcryptoeng"),
bn_ops => "BN_LLONG",
thread_scheme => "pthreads",
dso_scheme => "dlfcn",
shared_target => "bsd-gcc-shared",
shared_cflag => "-fPIC",
},
"BSD-generic64" => {
inherit_from => [ "BSD-generic32" ],
bn_ops => "SIXTY_FOUR_BIT_LONG",
},
"BSD-x86" => {
inherit_from => [ "BSD-generic32" ],
CFLAGS => add(picker(release => "-fomit-frame-pointer")),
lib_cppflags => add("-DL_ENDIAN"),
bn_ops => "BN_LLONG",
asm_arch => 'x86',
perlasm_scheme => "a.out",
},
"BSD-x86-elf" => {
inherit_from => [ "BSD-x86" ],
perlasm_scheme => "elf",
},
"BSD-sparcv8" => {
inherit_from => [ "BSD-generic32" ],
cflags => add("-mcpu=v8"),
lib_cppflags => add("-DB_ENDIAN"),
asm_arch => 'sparcv8',
perlasm_scheme => 'void',
},
"BSD-sparc64" => {
# -DMD32_REG_T=int doesn't actually belong in sparc64 target, it
# simply *happens* to work around a compiler bug in gcc 3.3.3,
# triggered by RIPEMD160 code.
inherit_from => [ "BSD-generic64" ],
lib_cppflags => add("-DB_ENDIAN -DMD32_REG_T=int"),
bn_ops => "BN_LLONG",
asm_arch => 'sparcv9',
perlasm_scheme => 'void',
},
"BSD-ia64" => {
inherit_from => [ "BSD-generic64" ],
lib_cppflags => add("-DL_ENDIAN"),
bn_ops => "SIXTY_FOUR_BIT_LONG",
asm_arch => 'ia64',
perlasm_scheme => 'void',
},
"BSD-x86_64" => {
inherit_from => [ "BSD-generic64" ],
lib_cppflags => add("-DL_ENDIAN"),
bn_ops => "SIXTY_FOUR_BIT_LONG",
asm_arch => 'x86_64',
perlasm_scheme => "elf",
},
"BSD-aarch64" => {
inherit_from => [ "BSD-generic64" ],
lib_cppflags => add("-DL_ENDIAN"),
bn_ops => "SIXTY_FOUR_BIT_LONG",
asm_arch => 'aarch64',
perlasm_scheme => "linux64",
},
# riscv64 below refers to contemporary RISCV Architecture
# specifications,
"BSD-riscv64" => {
inherit_from => [ "BSD-generic64"],
perlasm_scheme => "linux64",
},
"bsdi-elf-gcc" => {
inherit_from => [ "BASE_unix" ],
CC => "gcc",
CFLAGS => "-fomit-frame-pointer -O3 -Wall",
lib_cppflags => "-DPERL5 -DL_ENDIAN",
ex_libs => add("-ldl"),
bn_ops => "BN_LLONG",
asm_arch => 'x86',
perlasm_scheme => "elf",
thread_scheme => "(unknown)",
dso_scheme => "dlfcn",
shared_target => "bsd-gcc-shared",
shared_cflag => "-fPIC",
},
#### SCO/Caldera targets.
#
# Originally we had like unixware-*, unixware-*-pentium, unixware-*-p6, etc.
# Now we only have blended unixware-* as it's the only one used by ./config.
# If you want to optimize for particular microarchitecture, bypass ./config
# and './Configure unixware-7 -Kpentium_pro' or whatever appropriate.
# Note that not all targets include assembler support. Mostly because of
# lack of motivation to support out-of-date platforms with out-of-date
# compiler drivers and assemblers.
#
# UnixWare 2.0x fails destest with -O.
"unixware-2.0" => {
inherit_from => [ "BASE_unix" ],
CC => "cc",
cflags => threads("-Kthread"),
lib_cppflags => "-DFILIO_H -DNO_STRINGS_H",
ex_libs => add("-lsocket -lnsl -lresolv -lx"),
thread_scheme => "uithreads",
},
"unixware-2.1" => {
inherit_from => [ "BASE_unix" ],
CC => "cc",
CFLAGS => "-O",
cflags => threads("-Kthread"),
lib_cppflags => "-DFILIO_H",
ex_libs => add("-lsocket -lnsl -lresolv -lx"),
thread_scheme => "uithreads",
},
"unixware-7" => {
inherit_from => [ "BASE_unix" ],
CC => "cc",
CFLAGS => "-O",
cflags => combine("-Kalloca", threads("-Kthread")),
lib_cppflags => "-DFILIO_H",
ex_libs => add("-lsocket -lnsl"),
thread_scheme => "uithreads",
bn_ops => "BN_LLONG",
asm_arch => 'x86',
perlasm_scheme => "elf-1",
dso_scheme => "dlfcn",
shared_target => "svr5-shared",
shared_cflag => "-Kpic",
},
"unixware-7-gcc" => {
inherit_from => [ "BASE_unix" ],
CC => "gcc",
CFLAGS => "-O3 -fomit-frame-pointer -Wall",
cppflags => add(threads("-D_REENTRANT")),
lib_cppflags => add("-DL_ENDIAN -DFILIO_H"),
ex_libs => add("-lsocket -lnsl"),
bn_ops => "BN_LLONG",
thread_scheme => "pthreads",
asm_arch => 'x86',
perlasm_scheme => "elf-1",
dso_scheme => "dlfcn",
shared_target => "gnu-shared",
shared_cflag => "-fPIC",
},
# SCO 5 - Ben Laurie says the -O breaks the SCO cc.
"sco5-cc" => {
inherit_from => [ "BASE_unix" ],
cc => "cc",
cflags => "-belf",
ex_libs => add("-lsocket -lnsl"),
thread_scheme => "(unknown)",
asm_arch => 'x86',
perlasm_scheme => "elf-1",
dso_scheme => "dlfcn",
shared_target => "svr3-shared",
shared_cflag => "-Kpic",
},
"sco5-gcc" => {
inherit_from => [ "BASE_unix" ],
cc => "gcc",
cflags => "-O3 -fomit-frame-pointer",
ex_libs => add("-lsocket -lnsl"),
bn_ops => "BN_LLONG",
thread_scheme => "(unknown)",
asm_arch => 'x86',
perlasm_scheme => "elf-1",
dso_scheme => "dlfcn",
shared_target => "svr3-shared",
shared_cflag => "-fPIC",
},
#### IBM's AIX.
# Below targets assume AIX >=5. Caveat lector. If you are accustomed
# to control compilation "bitness" by setting $OBJECT_MODE environment
# variable, then you should know that in OpenSSL case it's considered
# only in ./config. Once configured, build procedure remains "deaf" to
# current value of $OBJECT_MODE.
"aix-common" => {
inherit_from => [ "BASE_unix" ],
template => 1,
sys_id => "AIX",
lib_cppflags => "-DB_ENDIAN",
lflags => "-Wl,-bsvr4",
thread_scheme => "pthreads",
dso_scheme => "dlfcn",
shared_target => "aix",
module_ldflags => "-Wl,-G,-bsymbolic,-bnoentry",
shared_ldflag => "-Wl,-G,-bsymbolic,-bnoentry",
shared_defflag => "-Wl,-bE:",
shared_fipsflag => "-Wl,-binitfini:_init:_cleanup",
perl_platform => 'AIX',
},
"aix-gcc" => {
inherit_from => [ "aix-common" ],
CC => "gcc",
CFLAGS => picker(debug => "-O0 -g",
release => "-O"),
cflags => add(threads("-pthread")),
ex_libs => add(threads("-pthread")),
bn_ops => "BN_LLONG RC4_CHAR",
asm_arch => 'ppc32',
perlasm_scheme => "aix32",
shared_ldflag => add_before("-shared -static-libgcc"),
AR => add("-X32"),
RANLIB => add("-X32"),
},
"aix64-gcc" => {
inherit_from => [ "aix-common" ],
CC => "gcc",
CFLAGS => picker(debug => "-O0 -g",
release => "-O"),
cflags => combine("-maix64", threads("-pthread")),
ex_libs => add(threads("-pthread")),
bn_ops => "SIXTY_FOUR_BIT_LONG RC4_CHAR",
asm_arch => 'ppc64',
perlasm_scheme => "aix64",
shared_ldflag => add_before("-shared -static-libgcc"),
shared_extension => "64.so.\$(SHLIB_VERSION_NUMBER)",
AR => add("-X64"),
RANLIB => add("-X64"),
},
"aix64-gcc-as" => {
inherit_from => [ "aix64-gcc" ],
perlasm_scheme => "aix64-as",
},
"aix-cc" => {
inherit_from => [ "aix-common" ],
CC => "cc",
CFLAGS => picker(debug => "-O0 -g",
release => "-O"),
cflags => combine("-q32 -qmaxmem=16384 -qro -qroconst",
threads("-qthreaded")),
cppflags => threads("-D_THREAD_SAFE"),
ex_libs => add(threads("-lpthreads")),
bn_ops => "BN_LLONG RC4_CHAR",
asm_arch => 'ppc32',
perlasm_scheme => "aix32",
shared_cflag => "-qpic",
AR => add("-X32"),
RANLIB => add("-X32"),
},
"aix64-cc" => {
inherit_from => [ "aix-common" ],
CC => "cc",
CFLAGS => picker(debug => "-O0 -g",
release => "-O"),
cflags => combine("-q64 -qmaxmem=16384 -qro -qroconst",
threads("-qthreaded")),
cppflags => threads("-D_THREAD_SAFE"),
ex_libs => add(threads("-lpthreads")),
bn_ops => "SIXTY_FOUR_BIT_LONG RC4_CHAR",
asm_arch => 'ppc64',
perlasm_scheme => "aix64",
dso_scheme => "dlfcn",
shared_cflag => "-qpic",
shared_extension => "64.so.\$(SHLIB_VERSION_NUMBER)",
AR => add("-X64"),
RANLIB => add("-X64"),
},
# SIEMENS BS2000/OSD: an EBCDIC-based mainframe
"BS2000-OSD" => {
inherit_from => [ "BASE_unix" ],
CC => "c89",
CFLAGS => "-O",
cflags => "-XLLML -XLLMK -XL",
cppflags => "-DCHARSET_EBCDIC",
lib_cppflags => "-DB_ENDIAN",
ex_libs => add("-lsocket -lnsl"),
bn_ops => "THIRTY_TWO_BIT RC4_CHAR",
thread_scheme => "(unknown)",
},
#### Visual C targets
#
# Win64 targets, WIN64I denotes IA-64/Itanium and WIN64A - AMD64
#
# Note about /wd4090, disable warning C4090. This warning returns false
# positives in some situations. Disabling it altogether masks both
# legitimate and false cases, but as we compile on multiple platforms,
# we rely on other compilers to catch legitimate cases.
#
# Also note that we force threads no matter what. Configuring "no-threads"
# is ignored.
#
# UNICODE is defined in VC-common and applies to all targets. It used to
# be an opt-in option for VC-WIN32, but not anymore. The original reason
# was because ANSI API was *native* system interface for no longer
# supported Windows 9x. Keep in mind that UNICODE only affects how
# OpenSSL libraries interact with underlying OS, it doesn't affect API
# that OpenSSL presents to application.
"VC-common" => {
inherit_from => [ "BASE_Windows" ],
template => 1,
CC => "cl",
CPP => '$(CC) /EP /C',
CFLAGS => "/W3 /wd4090 /nologo",
coutflag => "/Fo",
LD => "link",
LDFLAGS => "/nologo /debug",
ldoutflag => "/out:",
ldpostoutflag => "",
ld_resp_delim => "\n",
bin_lflags => "setargv.obj",
makedepcmd => '$(CC) /Zs /showIncludes',
makedep_scheme => 'VC',
AR => "lib",
ARFLAGS => "/nologo",
aroutflag => "/out:",
ar_resp_delim => "\n",
RC => "rc",
rcoutflag => "/fo",
defines => add("OPENSSL_SYS_WIN32", "WIN32_LEAN_AND_MEAN",
"UNICODE", "_UNICODE",
"_CRT_SECURE_NO_DEPRECATE",
"_WINSOCK_DEPRECATED_NO_WARNINGS"),
lib_cflags => add("/Zi /Fdossl_static.pdb"),
lib_defines => add("L_ENDIAN"),
dso_cflags => "/Zi /Fddso.pdb",
bin_cflags => "/Zi /Fdapp.pdb",
# def_flag made to empty string so a .def file gets generated
shared_defflag => '',
shared_ldflag => "/dll",
shared_target => "win-shared", # meaningless except it gives Configure a hint
lddefflag => "/def:",
ldresflag => " ",
ld_implib_flag => "/implib:",
thread_scheme => "winthreads",
dso_scheme => "win32",
perl_platform => 'Windows::MSVC',
# additional parameter to build_scheme denotes install-path "flavour"
build_scheme => add("VC-common", { separator => undef }),
},
"VC-noCE-common" => {
inherit_from => [ "VC-common" ],
template => 1,
CFLAGS => add(picker(debug => '/Od',
release => '/O2')),
cflags => add(picker(default => '/Gs0 /GF /Gy',
debug =>
sub {
($disabled{shared} ? "" : "/MDd");
},
release =>
sub {
($disabled{shared} ? "" : "/MD");
})),
defines => add(picker(default => [], # works as type cast
debug => [ "DEBUG", "_DEBUG" ])),
lib_cflags => add(sub { $disabled{shared} ? "/MT /Zl" : () }),
# Following might/should appears controversial, i.e. defining
# /MDd without evaluating $disabled{shared}. It works in
# non-shared build because static library is compiled with /Zl
# and bares no reference to specific RTL. And it works in
# shared build because multiple /MDd options are not prohibited.
# But why /MDd in static build? Well, basically this is just a
# reference point, which allows to catch eventual errors that
# would prevent those who want to wrap OpenSSL into own .DLL.
# Why not /MD in release build then? Well, some are likely to
# prefer [non-debug] openssl.exe to be free from Micorosoft RTL
# redistributable.
bin_cflags => add(picker(debug => "/MDd",
release => sub { $disabled{shared} ? "/MT" : () },
)),
bin_lflags => add("/subsystem:console /opt:ref"),
ex_libs => add(sub {
my @ex_libs = ();
push @ex_libs, 'ws2_32.lib' unless $disabled{sock};
push @ex_libs, 'gdi32.lib advapi32.lib crypt32.lib user32.lib';
return join(" ", @ex_libs);
}),
},
"VC-WIN64-common" => {
inherit_from => [ "VC-noCE-common" ],
template => 1,
ex_libs => add(sub {
my @ex_libs = ();
push @ex_libs, 'bufferoverflowu.lib' if (`cl 2>&1` =~ /14\.00\.4[0-9]{4}\./);
return join(" ", @_, @ex_libs);
}),
bn_ops => add("SIXTY_FOUR_BIT"),
},
"VC-WIN64I" => {
inherit_from => [ "VC-WIN64-common" ],
AS => "ias",
ASFLAGS => "-d debug",
asoutflag => "-o ",
sys_id => "WIN64I",
uplink_arch => 'ia64',
asm_arch => 'ia64',
perlasm_scheme => "ias",
multilib => "-ia64",
},
"VC-WIN64A" => {
inherit_from => [ "VC-WIN64-common" ],
AS => sub { vc_win64a_info()->{AS} },
ASFLAGS => sub { vc_win64a_info()->{ASFLAGS} },
asoutflag => sub { vc_win64a_info()->{asoutflag} },
asflags => sub { vc_win64a_info()->{asflags} },
sys_id => "WIN64A",
uplink_arch => 'x86_64',
asm_arch => 'x86_64',
perlasm_scheme => sub { vc_win64a_info()->{perlasm_scheme} },
multilib => "-x64",
},
"VC-WIN32" => {
inherit_from => [ "VC-noCE-common" ],
AS => sub { vc_win32_info()->{AS} },
ASFLAGS => sub { vc_win32_info()->{ASFLAGS} },
asoutflag => sub { vc_win32_info()->{asoutflag} },
asflags => sub { vc_win32_info()->{asflags} },
sys_id => "WIN32",
bn_ops => add("BN_LLONG"),
uplink_arch => 'common',
asm_arch => 'x86',
perlasm_scheme => sub { vc_win32_info()->{perlasm_scheme} },
# "WOW" stands for "Windows on Windows", and "VC-WOW" engages
# some installation path heuristics in windows-makefile.tmpl...
build_scheme => add("VC-WOW", { separator => undef }),
},
"VC-CE" => {
inherit_from => [ "VC-common" ],
CFLAGS => add(picker(debug => "/Od",
release => "/O1i")),
CPPDEFINES => picker(debug => [ "DEBUG", "_DEBUG" ]),
LDFLAGS => add("/nologo /opt:ref"),
cflags =>
combine('/GF /Gy',
sub { vc_wince_info()->{cflags}; },
sub { `cl 2>&1` =~ /Version ([0-9]+)\./ && $1>=14
? ($disabled{shared} ? " /MT" : " /MD")
: " /MC"; }),
cppflags => sub { vc_wince_info()->{cppflags}; },
lib_defines => add("NO_CHMOD", "OPENSSL_SMALL_FOOTPRINT"),
lib_cppflags => sub { vc_wince_info()->{cppflags}; },
includes =>
add(combine(sub { defined(env('WCECOMPAT'))
? '$(WCECOMPAT)/include' : (); },
sub { defined(env('PORTSDK_LIBPATH'))
? '$(PORTSDK_LIBPATH)/../../include'
: (); })),
lflags => add(combine(sub { vc_wince_info()->{lflags}; },
sub { defined(env('PORTSDK_LIBPATH'))
? "/entry:mainCRTstartup" : (); })),
sys_id => "WINCE",
bn_ops => add("BN_LLONG"),
ex_libs => add(sub {
my @ex_libs = ();
push @ex_libs, 'ws2.lib' unless $disabled{sock};
push @ex_libs, 'crypt32.lib';
if (defined(env('WCECOMPAT'))) {
my $x = '$(WCECOMPAT)/lib';
if (-f "$x/env('TARGETCPU')/wcecompatex.lib") {
$x .= '/$(TARGETCPU)/wcecompatex.lib';
} else {
$x .= '/wcecompatex.lib';
}
push @ex_libs, $x;
}
push @ex_libs, '$(PORTSDK_LIBPATH)/portlib.lib'
if (defined(env('PORTSDK_LIBPATH')));
push @ex_libs, '/nodefaultlib coredll.lib corelibc.lib'
if (env('TARGETCPU') =~ /^X86|^ARMV4[IT]/);
return join(" ", @ex_libs);
}),
},
#### MinGW
"mingw-common" => {
inherit_from => [ 'BASE_unix' ],
template => 1,
CC => "gcc",
CFLAGS => picker(default => "-Wall",
debug => "-g -O0",
release => "-O3"),
cppflags => combine("-DUNICODE -D_UNICODE -DWIN32_LEAN_AND_MEAN",
threads("-D_MT")),
lib_cppflags => "-DL_ENDIAN",
ex_libs => add("-lws2_32 -lgdi32 -lcrypt32"),
thread_scheme => "winthreads",
dso_scheme => "win32",
shared_target => "mingw-shared",
shared_cppflags => add("_WINDLL"),
shared_ldflag => "-static-libgcc",
perl_platform => 'mingw',
},
"mingw" => {
inherit_from => [ "mingw-common" ],
CFLAGS => add(picker(release => "-fomit-frame-pointer")),
cflags => "-m32",
sys_id => "MINGW32",
bn_ops => add("BN_LLONG"),
asm_arch => 'x86',
uplink_arch => 'x86',
perlasm_scheme => "coff",
shared_rcflag => "--target=pe-i386",
multilib => "",
},
"mingw64" => {
# As for uplink_arch. Applink makes it possible to use
# .dll compiled with one compiler with application compiled with
# another compiler. It's possible to engage Applink support in
# mingw64 build, but it's not done, because until mingw64
# supports structured exception handling, one can't seriously
# consider its binaries for using with non-mingw64 run-time
# environment. And as mingw64 is always consistent with itself,
# Applink is never engaged and can as well be omitted.
inherit_from => [ "mingw-common" ],
cflags => "-m64",
sys_id => "MINGW64",
bn_ops => add("SIXTY_FOUR_BIT"),
asm_arch => 'x86_64',
uplink_arch => undef,
perlasm_scheme => "mingw64",
shared_rcflag => "--target=pe-x86-64",
multilib => "64",
},
#### UEFI
"UEFI" => {
inherit_from => [ "BASE_unix" ],
CC => "cc",
CFLAGS => "-O",
lib_cppflags => "-DL_ENDIAN",
sys_id => "UEFI",
},
"UEFI-x86" => {
inherit_from => [ "UEFI" ],
asm_arch => 'x86',
perlasm_scheme => "win32n",
},
"UEFI-x86_64" => {
inherit_from => [ "UEFI" ],
asm_arch => 'x86_64',
perlasm_scheme => "nasm",
},
#### UWIN
"UWIN" => {
inherit_from => [ "BASE_unix" ],
CC => "cc",
CFLAGS => "-O -Wall",
lib_cppflags => "-DTERMIOS -DL_ENDIAN",
sys_id => "UWIN",
bn_ops => "BN_LLONG",
dso_scheme => "win32",
},
#### Cygwin
"Cygwin-common" => {
inherit_from => [ "BASE_unix" ],
template => 1,
CC => "gcc",
CFLAGS => picker(default => "-Wall",
debug => "-g -O0",
release => "-O3"),
lib_cppflags => "-DTERMIOS -DL_ENDIAN",
sys_id => "CYGWIN",
thread_scheme => "pthread",
dso_scheme => "dlfcn",
shared_target => "cygwin-shared",
shared_cppflags => "-D_WINDLL",
perl_platform => 'Cygwin',
},
"Cygwin-x86" => {
inherit_from => [ "Cygwin-common" ],
CFLAGS => add(picker(release => "-O3 -fomit-frame-pointer")),
bn_ops => "BN_LLONG",
asm_arch => 'x86',
perlasm_scheme => "coff",
},
"Cygwin-x86_64" => {
inherit_from => [ "Cygwin-common" ],
CC => "gcc",
bn_ops => "SIXTY_FOUR_BIT_LONG",
asm_arch => 'x86_64',
perlasm_scheme => "mingw64",
},
# Backward compatibility for those using this target
"Cygwin" => {
inherit_from => [ "Cygwin-x86" ]
},
# In case someone constructs the Cygwin target name themself
"Cygwin-i386" => {
inherit_from => [ "Cygwin-x86" ]
},
"Cygwin-i486" => {
inherit_from => [ "Cygwin-x86" ]
},
"Cygwin-i586" => {
inherit_from => [ "Cygwin-x86" ]
},
"Cygwin-i686" => {
inherit_from => [ "Cygwin-x86" ]
},
##### MacOS X (a.k.a. Darwin) setup
"darwin-common" => {
inherit_from => [ "BASE_unix" ],
template => 1,
CC => "cc",
CFLAGS => picker(debug => "-g -O0",
release => "-O3"),
cppflags => threads("-D_REENTRANT"),
lflags => add("-Wl,-search_paths_first"),
sys_id => "MACOSX",
bn_ops => "BN_LLONG RC4_CHAR",
thread_scheme => "pthreads",
perlasm_scheme => "osx32",
dso_scheme => "dlfcn",
ranlib => "ranlib -c",
shared_target => "darwin-shared",
shared_cflag => "-fPIC",
shared_extension => ".\$(SHLIB_VERSION_NUMBER).dylib",
},
# Option "freeze" such as -std=gnu9x can't negatively interfere
# with future defaults for below two targets, because MacOS X
# for PPC has no future, it was discontinued by vendor in 2009.
"darwin-ppc-cc" => { inherit_from => [ "darwin-ppc" ] }, # Historic alias
"darwin-ppc" => {
inherit_from => [ "darwin-common" ],
cflags => add("-arch ppc -std=gnu9x -Wa,-force_cpusubtype_ALL"),
lib_cppflags => add("-DB_ENDIAN"),
shared_cflag => add("-fno-common"),
asm_arch => 'ppc32',
perlasm_scheme => "osx32",
},
"darwin64-ppc-cc" => { inherit_from => [ "darwin64-ppc" ] }, # Historic alias
"darwin64-ppc" => {
inherit_from => [ "darwin-common" ],
cflags => add("-arch ppc64 -std=gnu9x"),
lib_cppflags => add("-DB_ENDIAN"),
bn_ops => "SIXTY_FOUR_BIT_LONG RC4_CHAR",
asm_arch => 'ppc64',
perlasm_scheme => "osx64",
},
"darwin-i386-cc" => { inherit_from => [ "darwin-i386" ] }, # Historic alias
"darwin-i386" => {
inherit_from => [ "darwin-common" ],
CFLAGS => add(picker(release => "-fomit-frame-pointer")),
cflags => add("-arch i386"),
lib_cppflags => add("-DL_ENDIAN"),
bn_ops => "BN_LLONG RC4_INT",
asm_arch => 'x86',
perlasm_scheme => "macosx",
},
"darwin64-x86_64-cc" => { inherit_from => [ "darwin64-x86_64" ] }, # Historic alias
"darwin64-x86_64" => {
inherit_from => [ "darwin-common" ],
CFLAGS => add("-Wall"),
cflags => add("-arch x86_64"),
lib_cppflags => add("-DL_ENDIAN"),
bn_ops => "SIXTY_FOUR_BIT_LONG",
asm_arch => 'x86_64',
perlasm_scheme => "macosx",
},
"darwin64-arm64-cc" => { inherit_from => [ "darwin64-arm64" ] }, # "Historic" alias
"darwin64-arm64" => {
inherit_from => [ "darwin-common" ],
CFLAGS => add("-Wall"),
cflags => add("-arch arm64"),
lib_cppflags => add("-DL_ENDIAN"),
bn_ops => "SIXTY_FOUR_BIT_LONG",
asm_arch => 'aarch64',
perlasm_scheme => "ios64",
},
##### GNU Hurd
"hurd-x86" => {
inherit_from => [ "BASE_unix" ],
CC => "gcc",
CFLAGS => "-O3 -fomit-frame-pointer -Wall",
cflags => threads("-pthread"),
lib_cppflags => "-DL_ENDIAN",
ex_libs => add("-ldl", threads("-pthread")),
bn_ops => "BN_LLONG",
asm_arch => 'x86',
perlasm_scheme => 'elf',
thread_scheme => "pthreads",
dso_scheme => "dlfcn",
shared_target => "linux-shared",
shared_cflag => "-fPIC",
},
##### VxWorks for various targets
"vxworks-ppc60x" => {
inherit_from => [ "BASE_unix" ],
CC => "ccppc",
CFLAGS => "-O2 -Wall -fstrength-reduce",
cflags => "-mrtp -mhard-float -mstrict-align -fno-implicit-fp -fno-builtin -fno-strict-aliasing",
cppflags => combine("-D_REENTRANT -DPPC32_fp60x -DCPU=PPC32",
"_DTOOL_FAMILY=gnu -DTOOL=gnu",
"-I\$(WIND_BASE)/target/usr/h",
"-I\$(WIND_BASE)/target/usr/h/wrn/coreip"),
sys_id => "VXWORKS",
lflags => add("-L \$(WIND_BASE)/target/usr/lib/ppc/PPC32/common"),
ex_libs => add("-Wl,--defsym,__wrs_rtp_base=0xe0000000"),
},
"vxworks-ppcgen" => {
inherit_from => [ "BASE_unix" ],
CC => "ccppc",
CFLAGS => "-O1 -Wall",
cflags => "-mrtp -msoft-float -mstrict-align -fno-builtin -fno-strict-aliasing",
cppflags => combine("-D_REENTRANT -DPPC32 -DCPU=PPC32",
"-DTOOL_FAMILY=gnu -DTOOL=gnu",
"-I\$(WIND_BASE)/target/usr/h",
"-I\$(WIND_BASE)/target/usr/h/wrn/coreip"),
sys_id => "VXWORKS",
lflags => add("-L \$(WIND_BASE)/target/usr/lib/ppc/PPC32/sfcommon"),
ex_libs => add("-Wl,--defsym,__wrs_rtp_base=0xe0000000"),
},
"vxworks-ppc405" => {
inherit_from => [ "BASE_unix" ],
CC => "ccppc",
CFLAGS => "-g",
cflags => "-msoft-float -mlongcall",
cppflags => combine("-D_REENTRANT -DPPC32 -DCPU=PPC405",
"-DTOOL_FAMILY=gnu -DTOOL=gnu",
"-I\$(WIND_BASE)/target/h"),
sys_id => "VXWORKS",
lflags => add("-r"),
},
"vxworks-ppc750" => {
inherit_from => [ "BASE_unix" ],
CC => "ccppc",
CFLAGS => "-ansi -fvolatile -Wall \$(DEBUG_FLAG)",
cflags => "-nostdinc -fno-builtin -fno-for-scope -fsigned-char -msoft-float -mlongcall",
cppflags => combine("-DPPC750 -D_REENTRANT -DCPU=PPC604",
"-I\$(WIND_BASE)/target/h"),
sys_id => "VXWORKS",
lflags => add("-r"),
},
"vxworks-ppc750-debug" => {
inherit_from => [ "BASE_unix" ],
CC => "ccppc",
CFLAGS => "-ansi -fvolatile -Wall -g",
cflags => "-nostdinc -fno-builtin -fno-for-scope -fsigned-char -msoft-float -mlongcall",
cppflags => combine("-DPPC750 -D_REENTRANT -DCPU=PPC604",
"-DPEDANTIC -DDEBUG",
"-I\$(WIND_BASE)/target/h"),
sys_id => "VXWORKS",
lflags => add("-r"),
},
"vxworks-ppc860" => {
inherit_from => [ "BASE_unix" ],
CC => "ccppc",
cflags => "-nostdinc -msoft-float",
cppflags => combine("-DCPU=PPC860 -DNO_STRINGS_H",
"-I\$(WIND_BASE)/target/h"),
sys_id => "VXWORKS",
lflags => add("-r"),
},
"vxworks-simlinux" => {
inherit_from => [ "BASE_unix" ],
CC => "ccpentium",
cflags => "-B\$(WIND_BASE)/host/\$(WIND_HOST_TYPE)/lib/gcc-lib/ -fno-builtin -fno-defer-pop",
cppflags => combine("-D_VSB_CONFIG_FILE=\"\$(WIND_BASE)/target/lib/h/config/vsbConfig.h\"",
"-DL_ENDIAN -DCPU=SIMLINUX -DNO_STRINGS_H",
"-DTOOL_FAMILY=gnu -DTOOL=gnu",
"-DOPENSSL_NO_HW_PADLOCK",
"-I\$(WIND_BASE)/target/h",
"-I\$(WIND_BASE)/target/h/wrn/coreip"),
sys_id => "VXWORKS",
lflags => add("-r"),
ranlib => "ranlibpentium",
},
"vxworks-mips" => {
inherit_from => [ "BASE_unix" ],
CC => "ccmips",
CFLAGS => "-O -G 0",
cflags => "-mrtp -mips2 -B\$(WIND_BASE)/host/\$(WIND_HOST_TYPE)/lib/gcc-lib/ -msoft-float -mno-branch-likely -fno-builtin -fno-defer-pop",
cppflags => combine("-D_VSB_CONFIG_FILE=\"\$(WIND_BASE)/target/lib/h/config/vsbConfig.h\"",
"-DCPU=MIPS32 -DNO_STRINGS_H",
"-DTOOL_FAMILY=gnu -DTOOL=gnu",
"-DOPENSSL_NO_HW_PADLOCK",
threads("-D_REENTRANT"),
"-I\$(WIND_BASE)/target/h",
"-I\$(WIND_BASE)/target/h/wrn/coreip"),
sys_id => "VXWORKS",
lflags => add("-L \$(WIND_BASE)/target/usr/lib/mips/MIPSI32/sfcommon"),
ex_libs => add("-Wl,--defsym,__wrs_rtp_base=0xe0000000"),
thread_scheme => "pthreads",
asm_arch => 'mips32',
perlasm_scheme => "o32",
ranlib => "ranlibmips",
},
#### uClinux
"uClinux-dist" => {
inherit_from => [ "BASE_unix" ],
CC => sub { env('CC') },
cppflags => threads("-D_REENTRANT"),
ex_libs => add("\$(LDLIBS)"),
bn_ops => "BN_LLONG",
thread_scheme => "pthreads",
dso_scheme => sub { env('LIBSSL_dlfcn') },
shared_target => "linux-shared",
shared_cflag => "-fPIC",
ranlib => sub { env('RANLIB') },
},
"uClinux-dist64" => {
inherit_from => [ "BASE_unix" ],
CC => sub { env('CC') },
cppflags => threads("-D_REENTRANT"),
ex_libs => add("\$(LDLIBS)"),
bn_ops => "SIXTY_FOUR_BIT_LONG",
thread_scheme => "pthreads",
dso_scheme => sub { env('LIBSSL_dlfcn') },
shared_target => "linux-shared",
shared_cflag => "-fPIC",
ranlib => sub { env('RANLIB') },
},
##### VMS
# Most things happen in vms-generic.
# Note that vms_info extracts the pointer size from the end of
# the target name, and will assume that anything matching /-p\d+$/
# indicates the pointer size setting for the desired target.
"vms-generic" => {
inherit_from => [ "BASE_VMS" ],
template => 1,
CC => "CC/DECC",
CPP => '$(CC)/PREPROCESS_ONLY=SYS$OUTPUT:',
CFLAGS =>
combine(picker(default => "/STANDARD=(ISOC94,RELAXED)/NOLIST/PREFIX=ALL",
debug => "/NOOPTIMIZE/DEBUG",
release => "/OPTIMIZE/NODEBUG"),
sub { my @warnings =
@{vms_info()->{disable_warns}};
@warnings
? "/WARNINGS=DISABLE=(".join(",",@warnings).")" : (); }),
cflag_incfirst => '/FIRST_INCLUDE=',
lib_defines =>
add("OPENSSL_USE_NODELETE",
sub {
return vms_info()->{def_zlib}
? "LIBZ=\"\"\"".vms_info()->{def_zlib}."\"\"\"" : ();
}),
lflags => picker(default => "/MAP='F\$PARSE(\".MAP\",\"\$\@\")'",
debug => "/DEBUG/TRACEBACK",
release => "/NODEBUG/NOTRACEBACK"),
# Because of dso_cflags below, we can't set the generic |cflags| here,
# as it can't be overridden, so we set separate C flags for libraries
# and binaries instead.
bin_cflags => add("/NAMES=(AS_IS,SHORTENED)/EXTERN_MODEL=STRICT_REFDEF"),
lib_cflags => add("/NAMES=(AS_IS,SHORTENED)/EXTERN_MODEL=STRICT_REFDEF"),
# Strictly speaking, DSOs should not need to have name shortening,
# as all their exported symbols should be short enough to fit the
# linker's 31 character per symbol name limit. However, providers
# may be composed of more than one object file, and internal symbols
# may and do surpass the 31 character limit.
dso_cflags => add("/NAMES=(SHORTENED)"),
ex_libs => add(sub { return vms_info()->{zlib} || (); }),
shared_target => "vms-shared",
# def_flag made to empty string so a .opt file gets generated
shared_defflag => '',
dso_scheme => "vms",
thread_scheme => "pthreads",
makedep_scheme => 'VMS C',
AS => sub { vms_info()->{AS} },
ASFLAGS => sub { vms_info()->{ASFLAGS} },
asoutflag => sub { vms_info()->{asoutflag} },
asflags => sub { vms_info()->{asflags} },
perlasm_scheme => sub { vms_info()->{perlasm_scheme} },
disable => add('pinshared', 'loadereng'),
},
# From HELP CC/POINTER_SIZE:
#
# ----------
# LONG[=ARGV] The compiler assumes 64-bit pointers. If the ARGV option to
# LONG or 64 is present, the main argument argv will be an
# array of long pointers instead of an array of short pointers.
#
# 64[=ARGV] Same as LONG.
# ----------
#
# We don't want the hassle of dealing with 32-bit pointers with argv, so
# we force it to have 64-bit pointers, see the added cflags in the -p64
# config targets below.
"vms-alpha" => {
inherit_from => [ "vms-generic" ],
bn_ops => "SIXTY_FOUR_BIT RC4_INT",
pointer_size => "",
},
"vms-alpha-p32" => {
inherit_from => [ "vms-alpha" ],
cflags => add("/POINTER_SIZE=32"),
pointer_size => "32",
},
"vms-alpha-p64" => {
inherit_from => [ "vms-alpha" ],
cflags => add("/POINTER_SIZE=64=ARGV"),
pointer_size => "64",
},
"vms-ia64" => {
inherit_from => [ "vms-generic" ],
bn_ops => "SIXTY_FOUR_BIT RC4_INT",
asm_arch => sub { vms_info()->{AS} ? 'ia64' : undef },
perlasm_scheme => 'ias',
pointer_size => "",
},
"vms-ia64-p32" => {
inherit_from => [ "vms-ia64" ],
cflags => add("/POINTER_SIZE=32"),
pointer_size => "32",
},
"vms-ia64-p64" => {
inherit_from => [ "vms-ia64" ],
cflags => add("/POINTER_SIZE=64=ARGV"),
pointer_size => "64",
},
"vms-x86_64" => {
inherit_from => [ "vms-generic" ],
bn_ops => "SIXTY_FOUR_BIT",
pointer_size => "",
},
"vms-x86_64-p32" => {
inherit_from => [ "vms-x86_64" ],
cflags => add("/POINTER_SIZE=32"),
pointer_size => "32",
},
"vms-x86_64-p64" => {
inherit_from => [ "vms-x86_64" ],
cflags => add("/POINTER_SIZE=64=ARGV"),
pointer_size => "64",
}
);
diff --git a/crypto/openssl/Configurations/15-ios.conf b/crypto/openssl/Configurations/15-ios.conf
index 54d37f63f445..81e3d68bc7f0 100644
--- a/crypto/openssl/Configurations/15-ios.conf
+++ b/crypto/openssl/Configurations/15-ios.conf
@@ -1,64 +1,64 @@
#### iPhoneOS/iOS
#
# It takes recent enough Xcode to use following two targets. It shouldn't
# be a problem by now, but if they don't work, original targets below
# that depend on manual definition of environment variables should still
# work...
#
my %targets = (
"ios-common" => {
template => 1,
inherit_from => [ "darwin-common" ],
sys_id => "iOS",
disable => [ "shared", "async" ],
},
"ios-xcrun" => {
inherit_from => [ "ios-common" ],
# It should be possible to go below iOS 6 and even add -arch armv6,
# thus targeting iPhone pre-3GS, but it's assumed to be irrelevant
# at this point.
CC => "xcrun -sdk iphoneos cc",
cflags => add("-arch armv7 -mios-version-min=6.0.0 -fno-common"),
asm_arch => 'armv4',
perlasm_scheme => "ios32",
},
"ios64-xcrun" => {
inherit_from => [ "ios-common" ],
CC => "xcrun -sdk iphoneos cc",
cflags => add("-arch arm64 -mios-version-min=7.0.0 -fno-common"),
bn_ops => "SIXTY_FOUR_BIT_LONG RC4_CHAR",
asm_arch => 'aarch64',
perlasm_scheme => "ios64",
},
"iossimulator-xcrun" => {
inherit_from => [ "ios-common" ],
CC => "xcrun -sdk iphonesimulator cc",
},
# It takes three prior-set environment variables to make it work:
#
# CROSS_COMPILE=/where/toolchain/is/usr/bin/ [note ending slash]
# CROSS_TOP=/where/SDKs/are
# CROSS_SDK=iPhoneOSx.y.sdk
#
# Exact paths vary with Xcode releases, but for couple of last ones
# they would look like this:
#
# CROSS_COMPILE=`xcode-select --print-path`/Toolchains/XcodeDefault.xctoolchain/usr/bin/
# CROSS_TOP=`xcode-select --print-path`/Platforms/iPhoneOS.platform/Developer
# CROSS_SDK=iPhoneOS.sdk
#
"iphoneos-cross" => {
inherit_from => [ "ios-common" ],
- cflags => add("-isysroot \$(CROSS_TOP)/SDKs/\$(CROSS_SDK) -fno-common"),
+ cflags => add("-isysroot \"\$(CROSS_TOP)/SDKs/\$(CROSS_SDK)\" -fno-common"),
},
"ios-cross" => {
inherit_from => [ "ios-xcrun" ],
CC => "cc",
- cflags => add("-isysroot \$(CROSS_TOP)/SDKs/\$(CROSS_SDK)"),
+ cflags => add("-isysroot \"\$(CROSS_TOP)/SDKs/\$(CROSS_SDK)\""),
},
"ios64-cross" => {
inherit_from => [ "ios64-xcrun" ],
CC => "cc",
- cflags => add("-isysroot \$(CROSS_TOP)/SDKs/\$(CROSS_SDK)"),
+ cflags => add("-isysroot \"\$(CROSS_TOP)/SDKs/\$(CROSS_SDK)\""),
},
);
diff --git a/crypto/openssl/Configurations/unix-Makefile.tmpl b/crypto/openssl/Configurations/unix-Makefile.tmpl
index 3754595d38b5..644540397de5 100644
--- a/crypto/openssl/Configurations/unix-Makefile.tmpl
+++ b/crypto/openssl/Configurations/unix-Makefile.tmpl
@@ -1,1996 +1,1996 @@
##
## Makefile for OpenSSL
##
## {- join("\n## ", @autowarntext) -}
{-
use OpenSSL::Util;
our $makedep_scheme = $config{makedep_scheme};
our $makedepcmd = platform->makedepcmd();
sub windowsdll { $config{target} =~ /^(?:Cygwin|mingw)/ }
# Shared AIX support is special. We put libcrypto[64].so.ver into
# libcrypto.a and use libcrypto_a.a as static one.
sub sharedaix { !$disabled{shared} && $config{target} =~ /^aix/ }
our $sover_dirname = platform->shlib_version_as_filename();
# This makes sure things get built in the order they need
# to. You're welcome.
sub dependmagic {
my $target = shift;
- return "$target: build_generated\n\t\$(MAKE) depend && \$(MAKE) _$target\n_$target";
+ return "$target: build_generated\n\t\"\$(MAKE)\" depend && \"\$(MAKE)\" _$target\n_$target";
}
our $COLUMNS = $ENV{COLUMNS};
if ($COLUMNS =~ /^\d+$/) {
$COLUMNS = int($COLUMNS) - 2; # 2 to leave space for ending ' \'
} else {
$COLUMNS = 76;
}
sub fill_lines {
my $item_sep = shift; # string
my $line_length = shift; # number of chars
my @result = ();
my $resultpos = 0;
foreach (@_) {
my $fill_line = $result[$resultpos] // '';
my $newline =
($fill_line eq '' ? '' : $fill_line . $item_sep) . $_;
if (length($newline) > $line_length) {
# If this is a single item and the intended result line
# is empty, we put it there anyway
if ($fill_line eq '') {
$result[$resultpos++] = $newline;
} else {
$result[++$resultpos] = $_;
}
} else {
$result[$resultpos] = $newline;
}
}
return @result;
}
'';
-}
PLATFORM={- $config{target} -}
OPTIONS={- $config{options} -}
CONFIGURE_ARGS=({- join(", ",quotify_l(@{$config{perlargv}})) -})
SRCDIR={- $config{sourcedir} -}
BLDDIR={- $config{builddir} -}
FIPSKEY={- $config{FIPSKEY} -}
VERSION={- "$config{full_version}" -}
VERSION_NUMBER={- "$config{version}" -}
MAJOR={- $config{major} -}
MINOR={- $config{minor} -}
SHLIB_VERSION_NUMBER={- $config{shlib_version} -}
SHLIB_TARGET={- $target{shared_target} -}
LIBS={- join(" \\\n" . ' ' x 5,
fill_lines(" ", $COLUMNS - 5,
map { platform->staticlib($_) // () }
@{$unified_info{libraries}})) -}
SHLIBS={- join(" \\\n" . ' ' x 7,
fill_lines(" ", $COLUMNS - 7,
map { platform->sharedlib($_) // () }
@{$unified_info{libraries}})) -}
SHLIB_INFO={- join(" \\\n" . ' ' x 11,
fill_lines(" ", $COLUMNS - 11,
map { my $x = platform->sharedlib($_);
my $y = platform->sharedlib_simple($_) // '';
my $z = platform->sharedlib_import($_) // '';
$x ? "\"$x;$y;$z\"" : () }
@{$unified_info{libraries}})) -}
MODULES={- join(" \\\n" . ' ' x 8,
fill_lines(" ", $COLUMNS - 8,
map { platform->dso($_) }
# Drop all modules that are dependencies, they will
# be processed through their dependents
grep { my $x = $_;
!grep { grep { $_ eq $x } @$_ }
values %{$unified_info{depends}} }
@{$unified_info{modules}})) -}
FIPSMODULE={- # We do some extra checking here, as there should be only one
use File::Basename;
our @fipsmodules =
grep { !$unified_info{attributes}->{modules}->{$_}->{noinst}
&& $unified_info{attributes}->{modules}->{$_}->{fips} }
@{$unified_info{modules}};
die "More that one FIPS module" if scalar @fipsmodules > 1;
join(" ", map { platform->dso($_) } @fipsmodules) -}
FIPSMODULENAME={- die "More that one FIPS module" if scalar @fipsmodules > 1;
join(" ", map { basename(platform->dso($_)) } @fipsmodules) -}
PROGRAMS={- join(" \\\n" . ' ' x 9,
fill_lines(" ", $COLUMNS - 9,
map { platform->bin($_) }
@{$unified_info{programs}})) -}
SCRIPTS={- join(" \\\n" . ' ' x 8,
fill_lines(" ", $COLUMNS - 8, @{$unified_info{scripts}})) -}
{- output_off() if $disabled{makedepend}; "" -}
DEPS={- join(" \\\n" . ' ' x 5,
fill_lines(" ", $COLUMNS - 5,
map { platform->isobj($_) ? platform->dep($_) : () }
grep { $unified_info{sources}->{$_}->[0] =~ /\.c$/ }
keys %{$unified_info{sources}})); -}
{- output_on() if $disabled{makedepend}; "" -}
GENERATED_MANDATORY={- join(" \\\n" . ' ' x 20,
fill_lines(" ", $COLUMNS - 20,
@{$unified_info{depends}->{""}})) -}
GENERATED_PODS={- # common0.tmpl provides @generated
join(" \\\n" . ' ' x 15,
fill_lines(" ", $COLUMNS - 15,
map { my $x = $_;
(
grep {
$unified_info{attributes}->{depends}
->{$x}->{$_}->{pod} // 0
}
keys %{$unified_info{attributes}->{depends}->{$x}}
) ? $x : ();
}
@generated)) -}
GENERATED={- # common0.tmpl provides @generated
join(" \\\n" . ' ' x 5,
fill_lines(" ", $COLUMNS - 5,
map { platform->convertext($_) } @generated )) -}
INSTALL_LIBS={-
join(" \\\n" . ' ' x 13,
fill_lines(" ", $COLUMNS - 13,
map { platform->staticlib($_) // () }
grep { !$unified_info{attributes}->{libraries}->{$_}->{noinst} }
@{$unified_info{libraries}}))
-}
INSTALL_SHLIBS={-
join(" \\\n" . ' ' x 15,
fill_lines(" ", $COLUMNS - 15,
map { platform->sharedlib($_) // () }
grep { !$unified_info{attributes}->{libraries}->{$_}->{noinst} }
@{$unified_info{libraries}}))
-}
INSTALL_SHLIB_INFO={-
join(" \\\n" . ' ' x 19,
fill_lines(" ", $COLUMNS - 19,
map { my $x = platform->sharedlib($_);
my $y = platform->sharedlib_simple($_) // '';
my $z = platform->sharedlib_import($_) // '';
$x ? "\"$x;$y;$z\"" : () }
grep { !$unified_info{attributes}->{libraries}->{$_}->{noinst} }
@{$unified_info{libraries}}))
-}
INSTALL_ENGINES={-
join(" \\\n" . ' ' x 16,
fill_lines(" ", $COLUMNS - 16,
map { platform->dso($_) }
grep { !$unified_info{attributes}->{modules}->{$_}->{noinst}
&& $unified_info{attributes}->{modules}->{$_}->{engine} }
@{$unified_info{modules}}))
-}
INSTALL_MODULES={-
join(" \\\n" . ' ' x 16,
fill_lines(" ", $COLUMNS - 16,
map { platform->dso($_) }
grep { !$unified_info{attributes}->{modules}->{$_}->{noinst}
&& !$unified_info{attributes}->{modules}->{$_}->{engine}
&& !$unified_info{attributes}->{modules}->{$_}->{fips} }
@{$unified_info{modules}}))
-}
INSTALL_FIPSMODULE={-
join(" \\\n" . ' ' x 16,
fill_lines(" ", $COLUMNS - 16,
map { platform->dso($_) }
grep { !$unified_info{attributes}->{modules}->{$_}->{noinst}
&& $unified_info{attributes}->{modules}->{$_}->{fips} }
@{$unified_info{modules}}))
-}
INSTALL_FIPSMODULECONF=providers/fipsmodule.cnf
INSTALL_PROGRAMS={-
join(" \\\n" . ' ' x 16,
fill_lines(" ", $COLUMNS - 16, map { platform->bin($_) }
grep { !$unified_info{attributes}->{programs}->{$_}->{noinst} }
@{$unified_info{programs}}))
-}
BIN_SCRIPTS={-
join(" \\\n" . ' ' x 12,
fill_lines(" ", $COLUMNS - 12,
map { my $x = $unified_info{attributes}->{scripts}->{$_}->{linkname};
$x ? "$_:$x" : $_ }
grep { !$unified_info{attributes}->{scripts}->{$_}->{noinst}
&& !$unified_info{attributes}->{scripts}->{$_}->{misc} }
@{$unified_info{scripts}}))
-}
MISC_SCRIPTS={-
join(" \\\n" . ' ' x 13,
fill_lines(" ", $COLUMNS - 13,
map { my $x = $unified_info{attributes}->{scripts}->{$_}->{linkname};
$x ? "$_:$x" : $_ }
grep { !$unified_info{attributes}->{scripts}->{$_}->{noinst}
&& $unified_info{attributes}->{scripts}->{$_}->{misc} }
@{$unified_info{scripts}}))
-}
IMAGEDOCS1={-
join(" \\\n" . ' ' x 10,
fill_lines(" ", $COLUMNS - 10,
@{$unified_info{imagedocs}->{man1}})) -}
IMAGEDOCS3={-
join(" \\\n" . ' ' x 10,
fill_lines(" ", $COLUMNS - 10,
@{$unified_info{imagedocs}->{man3}})) -}
IMAGEDOCS5={-
join(" \\\n" . ' ' x 10,
fill_lines(" ", $COLUMNS - 10,
@{$unified_info{imagedocs}->{man5}})) -}
IMAGEDOCS7={-
join(" \\\n" . ' ' x 10,
fill_lines(" ", $COLUMNS - 10,
@{$unified_info{imagedocs}->{man7}})) -}
HTMLDOCS1={-
join(" \\\n" . ' ' x 10,
fill_lines(" ", $COLUMNS - 10,
@{$unified_info{htmldocs}->{man1}})) -}
HTMLDOCS3={-
join(" \\\n" . ' ' x 10,
fill_lines(" ", $COLUMNS - 10,
@{$unified_info{htmldocs}->{man3}})) -}
HTMLDOCS5={-
join(" \\\n" . ' ' x 10,
fill_lines(" ", $COLUMNS - 10,
@{$unified_info{htmldocs}->{man5}})) -}
HTMLDOCS7={-
join(" \\\n" . ' ' x 10,
fill_lines(" ", $COLUMNS - 10,
@{$unified_info{htmldocs}->{man7}})) -}
MANDOCS1={-
join(" \\\n" . ' ' x 9,
fill_lines(" ", $COLUMNS - 9,
@{$unified_info{mandocs}->{man1}})) -}
MANDOCS3={-
join(" \\\n" . ' ' x 9,
fill_lines(" ", $COLUMNS - 9,
@{$unified_info{mandocs}->{man3}})) -}
MANDOCS5={-
join(" \\\n" . ' ' x 9,
fill_lines(" ", $COLUMNS - 9,
@{$unified_info{mandocs}->{man5}})) -}
MANDOCS7={-
join(" \\\n" . ' ' x 9,
fill_lines(" ", $COLUMNS - 9,
@{$unified_info{mandocs}->{man7}})) -}
APPS_OPENSSL="{- use File::Spec::Functions;
catfile("apps","openssl") -}"
# DESTDIR is for package builders so that they can configure for, say,
# /usr/ and yet have everything installed to /tmp/somedir/usr/.
# Normally it is left empty.
DESTDIR=
# Do not edit these manually. Use Configure with --prefix or --openssldir
# to change this! Short explanation in the top comment in Configure
INSTALLTOP={- # $prefix is used in the OPENSSLDIR perl snippet
#
our $prefix = $config{prefix} || "/usr/local";
$prefix -}
OPENSSLDIR={- #
# The logic here is that if no --openssldir was given,
# OPENSSLDIR will get the value from $prefix plus "/ssl".
# If --openssldir was given and the value is an absolute
# path, OPENSSLDIR will get its value without change.
# If the value from --openssldir is a relative path,
# OPENSSLDIR will get $prefix with the --openssldir
# value appended as a subdirectory.
#
use File::Spec::Functions;
our $openssldir =
$config{openssldir} ?
(file_name_is_absolute($config{openssldir}) ?
$config{openssldir}
: catdir($prefix, $config{openssldir}))
: catdir($prefix, "ssl");
$openssldir -}
LIBDIR={- our $libdir = $config{libdir};
unless ($libdir) {
$libdir = "lib$target{multilib}";
}
file_name_is_absolute($libdir) ? "" : $libdir -}
# $(libdir) is chosen to be compatible with the GNU coding standards
libdir={- file_name_is_absolute($libdir)
? $libdir : '$(INSTALLTOP)/$(LIBDIR)' -}
ENGINESDIR=$(libdir)/engines-{- $sover_dirname -}
MODULESDIR=$(libdir)/ossl-modules
# Convenience variable for those who want to set the rpath in shared
# libraries and applications
LIBRPATH=$(libdir)
MANDIR=$(INSTALLTOP)/share/man
DOCDIR=$(INSTALLTOP)/share/doc/$(BASENAME)
HTMLDIR=$(DOCDIR)/html
# MANSUFFIX is for the benefit of anyone who may want to have a suffix
# appended after the manpage file section number. "ssl" is popular,
# resulting in files such as config.5ssl rather than config.5.
MANSUFFIX=ossl
HTMLSUFFIX=html
# For "optional" echo messages, to get "real" silence
ECHO = echo
##### User defined commands and flags ################################
# We let the C compiler driver to take care of .s files. This is done in
# order to be excused from maintaining a separate set of architecture
# dependent assembler flags. E.g. if you throw -mcpu=ultrasparc at SPARC
# gcc, then the driver will automatically translate it to -xarch=v8plus
# and pass it down to assembler. In any case, we do not define AS or
# ASFLAGS for this reason.
CROSS_COMPILE={- $config{CROSS_COMPILE} -}
CC=$(CROSS_COMPILE){- $config{CC} -}
CXX={- $config{CXX} ? "\$(CROSS_COMPILE)$config{CXX}" : '' -}
CPPFLAGS={- our $cppflags1 = join(" ",
(map { "-D".$_} @{$config{CPPDEFINES}}),
(map { "-I".$_} @{$config{CPPINCLUDES}}),
@{$config{CPPFLAGS}}) -}
CFLAGS={- join(' ', @{$config{CFLAGS}}) -}
CXXFLAGS={- join(' ', @{$config{CXXFLAGS}}) -}
LDFLAGS= {- join(' ', @{$config{LDFLAGS}}) -}
EX_LIBS= {- join(' ', @{$config{LDLIBS}}) -}
MAKEDEPEND={- $config{makedepcmd} -}
PERL={- $config{PERL} -}
AR=$(CROSS_COMPILE){- $config{AR} -}
ARFLAGS= {- join(' ', @{$config{ARFLAGS}}) -}
RANLIB={- $config{RANLIB} ? "\$(CROSS_COMPILE)$config{RANLIB}" : "true"; -}
RC= $(CROSS_COMPILE){- $config{RC} -}
RCFLAGS={- join(' ', @{$config{RCFLAGS}}) -} {- $target{shared_rcflag} -}
RM= rm -f
RMDIR= rmdir
TAR= {- $target{TAR} || "tar" -}
TARFLAGS= {- $target{TARFLAGS} -}
BASENAME= openssl
NAME= $(BASENAME)-$(VERSION)
# Relative to $(SRCDIR)
TARFILE= ../$(NAME).tar
##### Project flags ##################################################
# Variables starting with CNF_ are common variables for all product types
CNF_CPPFLAGS={- our $cppflags2 =
join(' ', $target{cppflags} || (),
(map { "-D".$_} @{$target{defines}},
@{$config{defines}}),
(map { "-I".$_} @{$target{includes}},
@{$config{includes}}),
@{$config{cppflags}}) -}
CNF_CFLAGS={- join(' ', $target{cflags} || (),
@{$config{cflags}}) -}
CNF_CXXFLAGS={- join(' ', $target{cxxflags} || (),
@{$config{cxxflags}}) -}
CNF_LDFLAGS={- join(' ', $target{lflags} || (),
@{$config{lflags}}) -}
CNF_EX_LIBS={- join(' ', $target{ex_libs} || (),
@{$config{ex_libs}}) -}
# Variables starting with LIB_ are used to build library object files
# and shared libraries.
# Variables starting with DSO_ are used to build DSOs and their object files.
# Variables starting with BIN_ are used to build programs and their object
# files.
LIB_CPPFLAGS={- our $lib_cppflags =
join(' ', $target{lib_cppflags} || (),
$target{shared_cppflag} || (),
(map { '-D'.$_ }
@{$target{lib_defines} || ()},
@{$target{shared_defines} || ()},
@{$config{lib_defines} || ()},
@{$config{shared_defines} || ()}),
(map { '-I'.quotify1($_) }
@{$target{lib_includes}},
@{$target{shared_includes}},
@{$config{lib_includes}},
@{$config{shared_includes}}),
@{$config{lib_cppflags}},
@{$config{shared_cppflag}});
join(' ', $lib_cppflags,
(map { '-D'.$_ }
'OPENSSLDIR="\"$(OPENSSLDIR)\""',
'ENGINESDIR="\"$(ENGINESDIR)\""',
'MODULESDIR="\"$(MODULESDIR)\""'),
'$(CNF_CPPFLAGS)', '$(CPPFLAGS)') -}
LIB_CFLAGS={- join(' ', $target{lib_cflags} || (),
$target{shared_cflag} || (),
@{$config{lib_cflags}},
@{$config{shared_cflag}},
'$(CNF_CFLAGS)', '$(CFLAGS)') -}
LIB_CXXFLAGS={- join(' ', $target{lib_cxxflags} || (),
$target{shared_cxxflag} || (),
@{$config{lib_cxxflags}},
@{$config{shared_cxxflag}},
'$(CNF_CXXFLAGS)', '$(CXXFLAGS)') -}
LIB_LDFLAGS={- join(' ', $target{shared_ldflag} || (),
$config{shared_ldflag} || (),
'$(CNF_LDFLAGS)', '$(LDFLAGS)') -}
LIB_EX_LIBS=$(CNF_EX_LIBS) $(EX_LIBS)
DSO_CPPFLAGS={- join(' ', $target{dso_cppflags} || (),
$target{module_cppflags} || (),
(map { '-D'.$_ }
@{$target{dso_defines}},
@{$target{module_defines}},
@{$config{dso_defines} || ()},
@{$config{module_defines} || ()}),
(map { '-I'.quotify1($_) }
@{$target{dso_includes}},
@{$target{module_includes}},
@{$config{dso_includes}},
@{$config{module_includes}}),
@{$config{dso_cppflags}},
@{$config{module_cppflags}},
'$(CNF_CPPFLAGS)', '$(CPPFLAGS)') -}
DSO_CFLAGS={- join(' ', $target{dso_cflags} || (),
$target{module_cflags} || (),
@{$config{dso_cflags}},
@{$config{module_cflags}},
'$(CNF_CFLAGS)', '$(CFLAGS)') -}
DSO_CXXFLAGS={- join(' ', $target{dso_cxxflags} || (),
$target{module_cxxflags} || (),
@{$config{dso_cxxflags}},
@{$config{module_cxxflag}},
'$(CNF_CXXFLAGS)', '$(CXXFLAGS)') -}
DSO_LDFLAGS={- join(' ', $target{dso_ldflags} || (),
$target{module_ldflags} || (),
@{$config{dso_ldflags}},
@{$config{module_ldflags}},
'$(CNF_LDFLAGS)', '$(LDFLAGS)') -}
DSO_EX_LIBS=$(CNF_EX_LIBS) $(EX_LIBS)
BIN_CPPFLAGS={- join(' ', $target{bin_cppflags} || (),
(map { '-D'.$_ } @{$config{bin_defines} || ()}),
@{$config{bin_cppflags}},
'$(CNF_CPPFLAGS)', '$(CPPFLAGS)') -}
BIN_CFLAGS={- join(' ', $target{bin_cflags} || (),
@{$config{bin_cflags}},
'$(CNF_CFLAGS)', '$(CFLAGS)') -}
BIN_CXXFLAGS={- join(' ', $target{bin_cxxflags} || (),
@{$config{bin_cxxflags}},
'$(CNF_CXXFLAGS)', '$(CXXFLAGS)') -}
BIN_LDFLAGS={- join(' ', $target{bin_lflags} || (),
@{$config{bin_lflags}},
'$(CNF_LDFLAGS)', '$(LDFLAGS)') -}
BIN_EX_LIBS=$(CNF_EX_LIBS) $(EX_LIBS)
# CPPFLAGS_Q is used for one thing only: to build up buildinf.h
CPPFLAGS_Q={- $cppflags1 =~ s|([\\"])|\\$1|g;
$cppflags2 =~ s|([\\"])|\\$1|g;
$lib_cppflags =~ s|([\\"])|\\$1|g;
join(' ', $lib_cppflags || (), $cppflags2 || (),
$cppflags1 || ()) -}
PERLASM_SCHEME= {- $target{perlasm_scheme} -}
# For x86 assembler: Set PROCESSOR to 386 if you want to support
# the 80386.
PROCESSOR= {- $config{processor} -}
# We want error [and other] messages in English. Trouble is that make(1)
# doesn't pass macros down as environment variables unless there already
# was corresponding variable originally set. In other words we can only
# reassign environment variables, but not set new ones, not in portable
# manner that is. That's why we reassign several, just to be sure...
LC_ALL=C
LC_MESSAGES=C
LANG=C
# The main targets ###################################################
{- dependmagic('build_sw'); -}: build_libs_nodep build_modules_nodep build_programs_nodep link-utils
{- dependmagic('build_libs'); -}: build_libs_nodep
{- dependmagic('build_modules'); -}: build_modules_nodep
{- dependmagic('build_programs'); -}: build_programs_nodep
build_generated_pods: $(GENERATED_PODS)
build_docs: build_man_docs build_html_docs
build_man_docs: $(MANDOCS1) $(MANDOCS3) $(MANDOCS5) $(MANDOCS7)
build_html_docs: $(HTMLDOCS1) $(HTMLDOCS3) $(HTMLDOCS5) $(HTMLDOCS7)
build_generated: $(GENERATED_MANDATORY)
build_libs_nodep: libcrypto.pc libssl.pc openssl.pc
build_modules_nodep: $(MODULES)
build_programs_nodep: $(PROGRAMS) $(SCRIPTS)
# Kept around for backward compatibility
build_apps build_tests: build_programs
# Convenience target to prebuild all generated files, not just the mandatory
# ones
build_all_generated: $(GENERATED_MANDATORY) $(GENERATED) build_docs
@ : {- output_off() if $disabled{makedepend}; "" -}
@echo "Warning: consider configuring with no-makedepend, because if"
@echo " target system doesn't have $(PERL),"
@echo " then make will fail..."
@ : {- output_on() if $disabled{makedepend}; "" -}
all: build_sw build_docs
test: tests
{- dependmagic('tests'); -}: build_programs_nodep build_modules_nodep link-utils
- $(MAKE) run_tests
+ "$(MAKE)" run_tests
run_tests: FORCE
@ : {- output_off() if $disabled{tests}; "" -}
( SRCTOP=$(SRCDIR) \
BLDTOP=$(BLDDIR) \
PERL="$(PERL)" \
FIPSKEY="$(FIPSKEY)" \
EXE_EXT={- platform->binext() -} \
$(PERL) $(SRCDIR)/test/run_tests.pl $(TESTS) )
@ : {- if ($disabled{tests}) { output_on(); } else { output_off(); } "" -}
@echo "Tests are not supported with your chosen Configure options"
@ : {- output_on() if !$disabled{tests}; "" -}
list-tests:
@ : {- output_off() if $disabled{tests}; "" -}
- $(MAKE) run_tests TESTS=list
+ "$(MAKE)" run_tests TESTS=list
@ : {- if ($disabled{tests}) { output_on(); } else { output_off(); } "" -}
@echo "Tests are not supported with your chosen Configure options"
@ : {- output_on() if !$disabled{tests}; "" -}
install: install_sw install_ssldirs install_docs {- $disabled{fips} ? "" : "install_fips" -}
uninstall: uninstall_docs uninstall_sw {- $disabled{fips} ? "" : "uninstall_fips" -}
libclean:
@set -e; for s in $(SHLIB_INFO); do \
if [ "$$s" = ";" ]; then continue; fi; \
s1=`echo "$$s" | cut -f1 -d";"`; \
s2=`echo "$$s" | cut -f2 -d";"`; \
s3=`echo "$$s" | cut -f3 -d";"`; \
$(ECHO) $(RM) $$s1; {- output_off() unless windowsdll(); "" -}\
$(RM) apps/$$s1; \
$(RM) test/$$s1; \
$(RM) fuzz/$$s1; {- output_on() unless windowsdll(); "" -}\
$(RM) $$s1; \
if [ "$$s2" != "" ]; then \
$(ECHO) $(RM) $$s2; \
$(RM) $$s2; \
fi; \
if [ "$$s3" != "" ]; then \
$(ECHO) $(RM) $$s3; \
$(RM) $$s3; \
fi; \
done
$(RM) $(LIBS)
$(RM) *{- platform->defext() -}
clean: libclean
$(RM) $(HTMLDOCS1)
$(RM) $(HTMLDOCS3)
$(RM) $(HTMLDOCS5)
$(RM) $(HTMLDOCS7)
$(RM) $(MANDOCS1)
$(RM) $(MANDOCS3)
$(RM) $(MANDOCS5)
$(RM) $(MANDOCS7)
$(RM) $(PROGRAMS) $(TESTPROGS) $(MODULES) $(FIPSMODULE) $(SCRIPTS)
$(RM) $(GENERATED_MANDATORY) $(GENERATED)
-find . -name '*{- platform->depext() -}' \! -name '.*' \! -type d -exec $(RM) {} \;
-find . -name '*{- platform->objext() -}' \! -name '.*' \! -type d -exec $(RM) {} \;
$(RM) core
$(RM) tags TAGS doc-nits md-nits
$(RM) -r test/test-runs
$(RM) providers/fips*.new
$(RM) openssl.pc libcrypto.pc libssl.pc
-find . -type l \! -name '.*' -exec $(RM) {} \;
distclean: clean
$(RM) include/openssl/configuration.h
$(RM) configdata.pm
$(RM) Makefile
# We check if any depfile is newer than Makefile and decide to
# concatenate only if that is true.
depend: Makefile
@: {- output_off() if $disabled{makedepend}; "" -}
@$(PERL) $(SRCDIR)/util/add-depends.pl "{- $makedep_scheme -}"
@: {- output_on() if $disabled{makedepend}; "" -}
# Install helper targets #############################################
install_sw: install_dev install_engines install_modules install_runtime
uninstall_sw: uninstall_runtime uninstall_modules uninstall_engines uninstall_dev
install_docs: install_man_docs install_html_docs
uninstall_docs: uninstall_man_docs uninstall_html_docs
$(RM) -r "$(DESTDIR)$(DOCDIR)"
{- output_off() if $disabled{fips}; "" -}
install_fips: build_sw $(INSTALL_FIPSMODULECONF)
@[ -n "$(INSTALLTOP)" ] || (echo INSTALLTOP should not be empty; exit 1)
@$(PERL) $(SRCDIR)/util/mkdir-p.pl "$(DESTDIR)$(MODULESDIR)"
@$(PERL) $(SRCDIR)/util/mkdir-p.pl "$(DESTDIR)$(OPENSSLDIR)"
@$(ECHO) "*** Installing FIPS module"
@$(ECHO) "install $(INSTALL_FIPSMODULE) -> $(DESTDIR)$(MODULESDIR)/$(FIPSMODULENAME)"
@cp "$(INSTALL_FIPSMODULE)" "$(DESTDIR)$(MODULESDIR)/$(FIPSMODULENAME).new"
@chmod 755 "$(DESTDIR)$(MODULESDIR)/$(FIPSMODULENAME).new"
@mv -f "$(DESTDIR)$(MODULESDIR)/$(FIPSMODULENAME).new" \
"$(DESTDIR)$(MODULESDIR)/$(FIPSMODULENAME)"
@$(ECHO) "*** Installing FIPS module configuration"
@$(ECHO) "install $(INSTALL_FIPSMODULECONF) -> $(DESTDIR)$(OPENSSLDIR)/fipsmodule.cnf"
@cp $(INSTALL_FIPSMODULECONF) "$(DESTDIR)$(OPENSSLDIR)/fipsmodule.cnf"
uninstall_fips:
@$(ECHO) "*** Uninstalling FIPS module configuration"
$(RM) "$(DESTDIR)$(OPENSSLDIR)/fipsmodule.cnf"
@$(ECHO) "*** Uninstalling FIPS module"
$(RM) "$(DESTDIR)$(MODULESDIR)/$(FIPSMODULENAME)"
{- if ($disabled{fips}) { output_on(); } else { output_off(); } "" -}
install_fips:
@$(ECHO) "The 'install_fips' target requires the 'enable-fips' option"
uninstall_fips:
@$(ECHO) "The 'uninstall_fips' target requires the 'enable-fips' option"
{- output_on() if !$disabled{fips}; "" -}
install_ssldirs:
@$(PERL) $(SRCDIR)/util/mkdir-p.pl "$(DESTDIR)$(OPENSSLDIR)/certs"
@$(PERL) $(SRCDIR)/util/mkdir-p.pl "$(DESTDIR)$(OPENSSLDIR)/private"
@$(PERL) $(SRCDIR)/util/mkdir-p.pl "$(DESTDIR)$(OPENSSLDIR)/misc"
@set -e; for x in dummy $(MISC_SCRIPTS); do \
if [ "$$x" = "dummy" ]; then continue; fi; \
x1=`echo "$$x" | cut -f1 -d:`; \
x2=`echo "$$x" | cut -f2 -d:`; \
fn=`basename $$x1`; \
$(ECHO) "install $$x1 -> $(DESTDIR)$(OPENSSLDIR)/misc/$$fn"; \
cp $$x1 "$(DESTDIR)$(OPENSSLDIR)/misc/$$fn.new"; \
chmod 755 "$(DESTDIR)$(OPENSSLDIR)/misc/$$fn.new"; \
mv -f "$(DESTDIR)$(OPENSSLDIR)/misc/$$fn.new" \
"$(DESTDIR)$(OPENSSLDIR)/misc/$$fn"; \
if [ "$$x1" != "$$x2" ]; then \
ln=`basename "$$x2"`; \
: {- output_off() unless windowsdll(); "" -}; \
$(ECHO) "copy $(DESTDIR)$(OPENSSLDIR)/misc/$$ln -> $(DESTDIR)$(OPENSSLDIR)/misc/$$fn"; \
cp "$(DESTDIR)$(OPENSSLDIR)/misc/$$fn" "$(DESTDIR)$(OPENSSLDIR)/misc/$$ln"; \
: {- output_on() unless windowsdll();
output_off() if windowsdll(); "" -}; \
$(ECHO) "link $(DESTDIR)$(OPENSSLDIR)/misc/$$ln -> $(DESTDIR)$(OPENSSLDIR)/misc/$$fn"; \
ln -sf $$fn "$(DESTDIR)$(OPENSSLDIR)/misc/$$ln"; \
: {- output_on() if windowsdll(); "" -}; \
fi; \
done
@$(ECHO) "install $(SRCDIR)/apps/openssl.cnf -> $(DESTDIR)$(OPENSSLDIR)/openssl.cnf.dist"
@cp $(SRCDIR)/apps/openssl.cnf "$(DESTDIR)$(OPENSSLDIR)/openssl.cnf.new"
@chmod 644 "$(DESTDIR)$(OPENSSLDIR)/openssl.cnf.new"
@mv -f "$(DESTDIR)$(OPENSSLDIR)/openssl.cnf.new" "$(DESTDIR)$(OPENSSLDIR)/openssl.cnf.dist"
@if [ ! -f "$(DESTDIR)$(OPENSSLDIR)/openssl.cnf" ]; then \
$(ECHO) "install $(SRCDIR)/apps/openssl.cnf -> $(DESTDIR)$(OPENSSLDIR)/openssl.cnf"; \
cp $(SRCDIR)/apps/openssl.cnf "$(DESTDIR)$(OPENSSLDIR)/openssl.cnf"; \
chmod 644 "$(DESTDIR)$(OPENSSLDIR)/openssl.cnf"; \
fi
@$(ECHO) "install $(SRCDIR)/apps/ct_log_list.cnf -> $(DESTDIR)$(OPENSSLDIR)/ct_log_list.cnf.dist"
@cp $(SRCDIR)/apps/ct_log_list.cnf "$(DESTDIR)$(OPENSSLDIR)/ct_log_list.cnf.new"
@chmod 644 "$(DESTDIR)$(OPENSSLDIR)/ct_log_list.cnf.new"
@mv -f "$(DESTDIR)$(OPENSSLDIR)/ct_log_list.cnf.new" "$(DESTDIR)$(OPENSSLDIR)/ct_log_list.cnf.dist"
@if [ ! -f "$(DESTDIR)$(OPENSSLDIR)/ct_log_list.cnf" ]; then \
$(ECHO) "install $(SRCDIR)/apps/ct_log_list.cnf -> $(DESTDIR)$(OPENSSLDIR)/ct_log_list.cnf"; \
cp $(SRCDIR)/apps/ct_log_list.cnf "$(DESTDIR)$(OPENSSLDIR)/ct_log_list.cnf"; \
chmod 644 "$(DESTDIR)$(OPENSSLDIR)/ct_log_list.cnf"; \
fi
install_dev: install_runtime_libs
@[ -n "$(INSTALLTOP)" ] || (echo INSTALLTOP should not be empty; exit 1)
@$(ECHO) "*** Installing development files"
@$(PERL) $(SRCDIR)/util/mkdir-p.pl "$(DESTDIR)$(INSTALLTOP)/include/openssl"
@ : {- output_off() if $disabled{uplink}; "" -}
@$(ECHO) "install $(SRCDIR)/ms/applink.c -> $(DESTDIR)$(INSTALLTOP)/include/openssl/applink.c"
@cp $(SRCDIR)/ms/applink.c "$(DESTDIR)$(INSTALLTOP)/include/openssl/applink.c"
@chmod 644 "$(DESTDIR)$(INSTALLTOP)/include/openssl/applink.c"
@ : {- output_on() if $disabled{uplink}; "" -}
@set -e; for i in $(SRCDIR)/include/openssl/*.h \
$(BLDDIR)/include/openssl/*.h; do \
fn=`basename $$i`; \
$(ECHO) "install $$i -> $(DESTDIR)$(INSTALLTOP)/include/openssl/$$fn"; \
cp $$i "$(DESTDIR)$(INSTALLTOP)/include/openssl/$$fn"; \
chmod 644 "$(DESTDIR)$(INSTALLTOP)/include/openssl/$$fn"; \
done
@$(PERL) $(SRCDIR)/util/mkdir-p.pl "$(DESTDIR)$(libdir)"
@set -e; for l in $(INSTALL_LIBS); do \
fn=`basename $$l`; \
$(ECHO) "install $$l -> $(DESTDIR)$(libdir)/$$fn"; \
cp $$l "$(DESTDIR)$(libdir)/$$fn.new"; \
$(RANLIB) "$(DESTDIR)$(libdir)/$$fn.new"; \
chmod 644 "$(DESTDIR)$(libdir)/$$fn.new"; \
mv -f "$(DESTDIR)$(libdir)/$$fn.new" \
"$(DESTDIR)$(libdir)/$$fn"; \
done
@ : {- output_off() if $disabled{shared}; "" -}
@set -e; for s in $(INSTALL_SHLIB_INFO); do \
s1=`echo "$$s" | cut -f1 -d";"`; \
s2=`echo "$$s" | cut -f2 -d";"`; \
s3=`echo "$$s" | cut -f3 -d";"`; \
fn1=`basename "$$s1"`; \
fn2=`basename "$$s2"`; \
fn3=`basename "$$s3"`; \
: {- output_off(); output_on() unless windowsdll() or sharedaix(); "" -}; \
if [ "$$fn2" != "" ]; then \
$(ECHO) "link $(DESTDIR)$(libdir)/$$fn2 -> $(DESTDIR)$(libdir)/$$fn1"; \
ln -sf $$fn1 "$(DESTDIR)$(libdir)/$$fn2"; \
fi; \
: {- output_off() unless windowsdll() or sharedaix(); output_on() if windowsdll(); "" -}; \
if [ "$$fn3" != "" ]; then \
$(ECHO) "install $$s3 -> $(DESTDIR)$(libdir)/$$fn3"; \
cp $$s3 "$(DESTDIR)$(libdir)/$$fn3.new"; \
chmod 755 "$(DESTDIR)$(libdir)/$$fn3.new"; \
mv -f "$(DESTDIR)$(libdir)/$$fn3.new" \
"$(DESTDIR)$(libdir)/$$fn3"; \
fi; \
: {- output_off() if windowsdll(); output_on() if sharedaix(); "" -}; \
a="$(DESTDIR)$(libdir)/$$fn2"; \
$(ECHO) "install $$s1 -> $$a"; \
if [ -f $$a ]; then ( trap "rm -rf /tmp/ar.$$$$" INT 0; \
mkdir /tmp/ar.$$$$; ( cd /tmp/ar.$$$$; \
cp -f $$a $$a.new; \
for so in `$(AR) t $$a`; do \
$(AR) x $$a $$so; \
chmod u+w $$so; \
strip -X32_64 -e $$so; \
$(AR) r $$a.new $$so; \
done; \
)); fi; \
$(AR) r $$a.new $$s1; \
mv -f $$a.new $$a; \
: {- output_off() if sharedaix(); output_on(); "" -}; \
done
@ : {- output_on() if $disabled{shared}; "" -}
@$(PERL) $(SRCDIR)/util/mkdir-p.pl "$(DESTDIR)$(libdir)/pkgconfig"
@$(ECHO) "install libcrypto.pc -> $(DESTDIR)$(libdir)/pkgconfig/libcrypto.pc"
@cp libcrypto.pc "$(DESTDIR)$(libdir)/pkgconfig"
@chmod 644 "$(DESTDIR)$(libdir)/pkgconfig/libcrypto.pc"
@$(ECHO) "install libssl.pc -> $(DESTDIR)$(libdir)/pkgconfig/libssl.pc"
@cp libssl.pc "$(DESTDIR)$(libdir)/pkgconfig"
@chmod 644 "$(DESTDIR)$(libdir)/pkgconfig/libssl.pc"
@$(ECHO) "install openssl.pc -> $(DESTDIR)$(libdir)/pkgconfig/openssl.pc"
@cp openssl.pc "$(DESTDIR)$(libdir)/pkgconfig"
@chmod 644 "$(DESTDIR)$(libdir)/pkgconfig/openssl.pc"
uninstall_dev: uninstall_runtime_libs
@$(ECHO) "*** Uninstalling development files"
@ : {- output_off() if $disabled{uplink}; "" -}
@$(ECHO) "$(RM) $(DESTDIR)$(INSTALLTOP)/include/openssl/applink.c"
@$(RM) "$(DESTDIR)$(INSTALLTOP)/include/openssl/applink.c"
@ : {- output_on() if $disabled{uplink}; "" -}
@set -e; for i in $(SRCDIR)/include/openssl/*.h \
$(BLDDIR)/include/openssl/*.h; do \
fn=`basename $$i`; \
$(ECHO) "$(RM) $(DESTDIR)$(INSTALLTOP)/include/openssl/$$fn"; \
$(RM) "$(DESTDIR)$(INSTALLTOP)/include/openssl/$$fn"; \
done
-$(RMDIR) "$(DESTDIR)$(INSTALLTOP)/include/openssl"
-$(RMDIR) "$(DESTDIR)$(INSTALLTOP)/include"
@set -e; for l in $(INSTALL_LIBS); do \
fn=`basename $$l`; \
$(ECHO) "$(RM) $(DESTDIR)$(libdir)/$$fn"; \
$(RM) "$(DESTDIR)$(libdir)/$$fn"; \
done
@ : {- output_off() if $disabled{shared}; "" -}
@set -e; for s in $(INSTALL_SHLIB_INFO); do \
s1=`echo "$$s" | cut -f1 -d";"`; \
s2=`echo "$$s" | cut -f2 -d";"`; \
s3=`echo "$$s" | cut -f3 -d";"`; \
fn1=`basename "$$s1"`; \
fn2=`basename "$$s2"`; \
fn3=`basename "$$s3"`; \
: {- output_off() if windowsdll(); "" -}; \
$(ECHO) "$(RM) $(DESTDIR)$(libdir)/$$fn1"; \
$(RM) "$(DESTDIR)$(libdir)/$$fn1"; \
if [ -n "$$fn2" ]; then \
$(ECHO) "$(RM) $(DESTDIR)$(libdir)/$$fn2"; \
$(RM) "$(DESTDIR)$(libdir)/$$fn2"; \
fi; \
: {- output_on() if windowsdll(); "" -}{- output_off() unless windowsdll(); "" -}; \
if [ -n "$$fn3" ]; then \
$(ECHO) "$(RM) $(DESTDIR)$(libdir)/$$fn3"; \
$(RM) "$(DESTDIR)$(libdir)/$$fn3"; \
fi; \
: {- output_on() unless windowsdll(); "" -}; \
done
@ : {- output_on() if $disabled{shared}; "" -}
$(RM) "$(DESTDIR)$(libdir)/pkgconfig/libcrypto.pc"
$(RM) "$(DESTDIR)$(libdir)/pkgconfig/libssl.pc"
$(RM) "$(DESTDIR)$(libdir)/pkgconfig/openssl.pc"
-$(RMDIR) "$(DESTDIR)$(libdir)/pkgconfig"
-$(RMDIR) "$(DESTDIR)$(libdir)"
_install_modules_deps: install_runtime_libs build_modules
install_engines: _install_modules_deps
@[ -n "$(INSTALLTOP)" ] || (echo INSTALLTOP should not be empty; exit 1)
@$(PERL) $(SRCDIR)/util/mkdir-p.pl "$(DESTDIR)$(ENGINESDIR)/"
@$(ECHO) "*** Installing engines"
@set -e; for e in dummy $(INSTALL_ENGINES); do \
if [ "$$e" = "dummy" ]; then continue; fi; \
fn=`basename $$e`; \
$(ECHO) "install $$e -> $(DESTDIR)$(ENGINESDIR)/$$fn"; \
cp $$e "$(DESTDIR)$(ENGINESDIR)/$$fn.new"; \
chmod 755 "$(DESTDIR)$(ENGINESDIR)/$$fn.new"; \
mv -f "$(DESTDIR)$(ENGINESDIR)/$$fn.new" \
"$(DESTDIR)$(ENGINESDIR)/$$fn"; \
done
uninstall_engines:
@$(ECHO) "*** Uninstalling engines"
@set -e; for e in dummy $(INSTALL_ENGINES); do \
if [ "$$e" = "dummy" ]; then continue; fi; \
fn=`basename $$e`; \
$(ECHO) "$(RM) $(DESTDIR)$(ENGINESDIR)/$$fn"; \
$(RM) "$(DESTDIR)$(ENGINESDIR)/$$fn"; \
done
-$(RMDIR) "$(DESTDIR)$(ENGINESDIR)"
install_modules: _install_modules_deps
@[ -n "$(INSTALLTOP)" ] || (echo INSTALLTOP should not be empty; exit 1)
@$(PERL) $(SRCDIR)/util/mkdir-p.pl "$(DESTDIR)$(MODULESDIR)/"
@$(ECHO) "*** Installing modules"
@set -e; for e in dummy $(INSTALL_MODULES); do \
if [ "$$e" = "dummy" ]; then continue; fi; \
fn=`basename $$e`; \
$(ECHO) "install $$e -> $(DESTDIR)$(MODULESDIR)/$$fn"; \
cp $$e "$(DESTDIR)$(MODULESDIR)/$$fn.new"; \
chmod 755 "$(DESTDIR)$(MODULESDIR)/$$fn.new"; \
mv -f "$(DESTDIR)$(MODULESDIR)/$$fn.new" \
"$(DESTDIR)$(MODULESDIR)/$$fn"; \
done
uninstall_modules:
@$(ECHO) "*** Uninstalling modules"
@set -e; for e in dummy $(INSTALL_MODULES); do \
if [ "$$e" = "dummy" ]; then continue; fi; \
fn=`basename $$e`; \
$(ECHO) "$(RM) $(DESTDIR)$(MODULESDIR)/$$fn"; \
$(RM) "$(DESTDIR)$(MODULESDIR)/$$fn"; \
done
-$(RMDIR) "$(DESTDIR)$(MODULESDIR)"
install_runtime: install_programs
install_runtime_libs: build_libs
@[ -n "$(INSTALLTOP)" ] || (echo INSTALLTOP should not be empty; exit 1)
@ : {- output_off() if windowsdll(); "" -}
@$(PERL) $(SRCDIR)/util/mkdir-p.pl "$(DESTDIR)$(libdir)"
@ : {- output_on() if windowsdll(); output_off() unless windowsdll(); "" -}
@$(PERL) $(SRCDIR)/util/mkdir-p.pl "$(DESTDIR)$(INSTALLTOP)/bin"
@ : {- output_on() unless windowsdll(); "" -}
@$(ECHO) "*** Installing runtime libraries"
@set -e; for s in dummy $(INSTALL_SHLIBS); do \
if [ "$$s" = "dummy" ]; then continue; fi; \
fn=`basename $$s`; \
: {- output_off() unless windowsdll(); "" -}; \
$(ECHO) "install $$s -> $(DESTDIR)$(INSTALLTOP)/bin/$$fn"; \
cp $$s "$(DESTDIR)$(INSTALLTOP)/bin/$$fn.new"; \
chmod 755 "$(DESTDIR)$(INSTALLTOP)/bin/$$fn.new"; \
mv -f "$(DESTDIR)$(INSTALLTOP)/bin/$$fn.new" \
"$(DESTDIR)$(INSTALLTOP)/bin/$$fn"; \
: {- output_on() unless windowsdll(); "" -}{- output_off() if windowsdll(); "" -}; \
$(ECHO) "install $$s -> $(DESTDIR)$(libdir)/$$fn"; \
cp $$s "$(DESTDIR)$(libdir)/$$fn.new"; \
chmod 755 "$(DESTDIR)$(libdir)/$$fn.new"; \
mv -f "$(DESTDIR)$(libdir)/$$fn.new" \
"$(DESTDIR)$(libdir)/$$fn"; \
: {- output_on() if windowsdll(); "" -}; \
done
install_programs: install_runtime_libs build_programs
@[ -n "$(INSTALLTOP)" ] || (echo INSTALLTOP should not be empty; exit 1)
@$(PERL) $(SRCDIR)/util/mkdir-p.pl "$(DESTDIR)$(INSTALLTOP)/bin"
@$(ECHO) "*** Installing runtime programs"
@set -e; for x in dummy $(INSTALL_PROGRAMS); do \
if [ "$$x" = "dummy" ]; then continue; fi; \
fn=`basename $$x`; \
$(ECHO) "install $$x -> $(DESTDIR)$(INSTALLTOP)/bin/$$fn"; \
cp $$x "$(DESTDIR)$(INSTALLTOP)/bin/$$fn.new"; \
chmod 755 "$(DESTDIR)$(INSTALLTOP)/bin/$$fn.new"; \
mv -f "$(DESTDIR)$(INSTALLTOP)/bin/$$fn.new" \
"$(DESTDIR)$(INSTALLTOP)/bin/$$fn"; \
done
@set -e; for x in dummy $(BIN_SCRIPTS); do \
if [ "$$x" = "dummy" ]; then continue; fi; \
fn=`basename $$x`; \
$(ECHO) "install $$x -> $(DESTDIR)$(INSTALLTOP)/bin/$$fn"; \
cp $$x "$(DESTDIR)$(INSTALLTOP)/bin/$$fn.new"; \
chmod 755 "$(DESTDIR)$(INSTALLTOP)/bin/$$fn.new"; \
mv -f "$(DESTDIR)$(INSTALLTOP)/bin/$$fn.new" \
"$(DESTDIR)$(INSTALLTOP)/bin/$$fn"; \
done
uninstall_runtime: uninstall_programs uninstall_runtime_libs
uninstall_programs:
@$(ECHO) "*** Uninstalling runtime programs"
@set -e; for x in dummy $(INSTALL_PROGRAMS); \
do \
if [ "$$x" = "dummy" ]; then continue; fi; \
fn=`basename $$x`; \
$(ECHO) "$(RM) $(DESTDIR)$(INSTALLTOP)/bin/$$fn"; \
$(RM) "$(DESTDIR)$(INSTALLTOP)/bin/$$fn"; \
done;
@set -e; for x in dummy $(BIN_SCRIPTS); \
do \
if [ "$$x" = "dummy" ]; then continue; fi; \
fn=`basename $$x`; \
$(ECHO) "$(RM) $(DESTDIR)$(INSTALLTOP)/bin/$$fn"; \
$(RM) "$(DESTDIR)$(INSTALLTOP)/bin/$$fn"; \
done
-$(RMDIR) "$(DESTDIR)$(INSTALLTOP)/bin"
uninstall_runtime_libs:
@$(ECHO) "*** Uninstalling runtime libraries"
@ : {- output_off() unless windowsdll(); "" -}
@set -e; for s in dummy $(INSTALL_SHLIBS); do \
if [ "$$s" = "dummy" ]; then continue; fi; \
fn=`basename $$s`; \
$(ECHO) "$(RM) $(DESTDIR)$(INSTALLTOP)/bin/$$fn"; \
$(RM) "$(DESTDIR)$(INSTALLTOP)/bin/$$fn"; \
done
@ : {- output_on() unless windowsdll(); "" -}
install_man_docs: build_man_docs
@[ -n "$(INSTALLTOP)" ] || (echo INSTALLTOP should not be empty; exit 1)
@$(PERL) $(SRCDIR)/util/mkdir-p.pl "$(DESTDIR)$(MANDIR)/man1"
@$(PERL) $(SRCDIR)/util/mkdir-p.pl "$(DESTDIR)$(MANDIR)/man3"
@$(PERL) $(SRCDIR)/util/mkdir-p.pl "$(DESTDIR)$(MANDIR)/man5"
@$(PERL) $(SRCDIR)/util/mkdir-p.pl "$(DESTDIR)$(MANDIR)/man7"
@$(ECHO) "*** Installing manpages"
@set -e; for x in dummy $(MANDOCS1); do \
if [ "$$x" = "dummy" ]; then continue; fi; \
fn=`basename $$x`; \
$(ECHO) "install $$x -> $(DESTDIR)$(MANDIR)/man1/$${fn}$(MANSUFFIX)"; \
cp $$x "$(DESTDIR)$(MANDIR)/man1/$${fn}$(MANSUFFIX)"; \
chmod 644 "$(DESTDIR)$(MANDIR)/man1/$${fn}$(MANSUFFIX)"; \
$(PERL) $(SRCDIR)/util/write-man-symlinks install $(SRCDIR)/doc/man1 $(BLDDIR)/doc/man1 $${fn}$(MANSUFFIX) "$(DESTDIR)$(MANDIR)/man1"; \
done
@set -e; for x in dummy $(MANDOCS3); do \
if [ "$$x" = "dummy" ]; then continue; fi; \
fn=`basename $$x`; \
$(ECHO) "install $$x -> $(DESTDIR)$(MANDIR)/man3/$${fn}$(MANSUFFIX)"; \
cp $$x "$(DESTDIR)$(MANDIR)/man3/$${fn}$(MANSUFFIX)"; \
chmod 644 "$(DESTDIR)$(MANDIR)/man3/$${fn}$(MANSUFFIX)"; \
$(PERL) $(SRCDIR)/util/write-man-symlinks install $(SRCDIR)/doc/man3 $(BLDDIR)/doc/man3 $${fn}$(MANSUFFIX) "$(DESTDIR)$(MANDIR)/man3"; \
done
@set -e; for x in dummy $(MANDOCS5); do \
if [ "$$x" = "dummy" ]; then continue; fi; \
fn=`basename $$x`; \
$(ECHO) "install $$x -> $(DESTDIR)$(MANDIR)/man5/$${fn}$(MANSUFFIX)"; \
cp $$x "$(DESTDIR)$(MANDIR)/man5/$${fn}$(MANSUFFIX)"; \
chmod 644 "$(DESTDIR)$(MANDIR)/man5/$${fn}$(MANSUFFIX)"; \
$(PERL) $(SRCDIR)/util/write-man-symlinks install $(SRCDIR)/doc/man5 $(BLDDIR)/doc/man5 $${fn}$(MANSUFFIX) "$(DESTDIR)$(MANDIR)/man5"; \
done
@set -e; for x in dummy $(MANDOCS7); do \
if [ "$$x" = "dummy" ]; then continue; fi; \
fn=`basename $$x`; \
$(ECHO) "install $$x -> $(DESTDIR)$(MANDIR)/man7/$${fn}$(MANSUFFIX)"; \
cp $$x "$(DESTDIR)$(MANDIR)/man7/$${fn}$(MANSUFFIX)"; \
chmod 644 "$(DESTDIR)$(MANDIR)/man7/$${fn}$(MANSUFFIX)"; \
$(PERL) $(SRCDIR)/util/write-man-symlinks install $(SRCDIR)/doc/man7 $(BLDDIR)/doc/man7 $${fn}$(MANSUFFIX) "$(DESTDIR)$(MANDIR)/man7"; \
done
uninstall_man_docs: build_man_docs
@$(ECHO) "*** Uninstalling manpages"
@set -e; for x in dummy $(MANDOCS1); do \
if [ "$$x" = "dummy" ]; then continue; fi; \
fn=`basename $$x`; \
$(ECHO) "$(RM) $(DESTDIR)$(MANDIR)/man1/$${fn}$(MANSUFFIX)"; \
$(RM) "$(DESTDIR)$(MANDIR)/man1/$${fn}$(MANSUFFIX)"; \
$(PERL) $(SRCDIR)/util/write-man-symlinks uninstall $(SRCDIR)/doc/man1 $(BLDDIR)/doc/man1 $${fn}$(MANSUFFIX) "$(DESTDIR)$(MANDIR)/man1"; \
done
@set -e; for x in dummy $(MANDOCS3); do \
if [ "$$x" = "dummy" ]; then continue; fi; \
fn=`basename $$x`; \
$(ECHO) "$(RM) $(DESTDIR)$(MANDIR)/man3/$${fn}$(MANSUFFIX)"; \
$(RM) "$(DESTDIR)$(MANDIR)/man3/$${fn}$(MANSUFFIX)"; \
$(PERL) $(SRCDIR)/util/write-man-symlinks uninstall $(SRCDIR)/doc/man3 $(BLDDIR)/doc/man3 $${fn}$(MANSUFFIX) "$(DESTDIR)$(MANDIR)/man3"; \
done
@set -e; for x in dummy $(MANDOCS5); do \
if [ "$$x" = "dummy" ]; then continue; fi; \
fn=`basename $$x`; \
$(ECHO) "$(RM) $(DESTDIR)$(MANDIR)/man5/$${fn}$(MANSUFFIX)"; \
$(RM) "$(DESTDIR)$(MANDIR)/man5/$${fn}$(MANSUFFIX)"; \
$(PERL) $(SRCDIR)/util/write-man-symlinks uninstall $(SRCDIR)/doc/man5 $(BLDDIR)/doc/man5 $${fn}$(MANSUFFIX) "$(DESTDIR)$(MANDIR)/man5"; \
done
@set -e; for x in dummy $(MANDOCS7); do \
if [ "$$x" = "dummy" ]; then continue; fi; \
fn=`basename $$x`; \
$(ECHO) "$(RM) $(DESTDIR)$(MANDIR)/man7/$${fn}$(MANSUFFIX)"; \
$(RM) "$(DESTDIR)$(MANDIR)/man7/$${fn}$(MANSUFFIX)"; \
$(PERL) $(SRCDIR)/util/write-man-symlinks uninstall $(SRCDIR)/doc/man7 $(BLDDIR)/doc/man7 $${fn}$(MANSUFFIX) "$(DESTDIR)$(MANDIR)/man7"; \
done
install_html_docs: install_image_docs build_html_docs
@[ -n "$(INSTALLTOP)" ] || (echo INSTALLTOP should not be empty; exit 1)
@$(PERL) $(SRCDIR)/util/mkdir-p.pl "$(DESTDIR)$(HTMLDIR)/man1"
@$(PERL) $(SRCDIR)/util/mkdir-p.pl "$(DESTDIR)$(HTMLDIR)/man3"
@$(PERL) $(SRCDIR)/util/mkdir-p.pl "$(DESTDIR)$(HTMLDIR)/man5"
@$(PERL) $(SRCDIR)/util/mkdir-p.pl "$(DESTDIR)$(HTMLDIR)/man7"
@$(ECHO) "*** Installing HTML manpages"
@set -e; for x in dummy $(HTMLDOCS1); do \
if [ "$$x" = "dummy" ]; then continue; fi; \
fn=`basename $$x`; \
$(ECHO) "install $$x -> $(DESTDIR)$(HTMLDIR)/man1/$$fn"; \
cp $$x "$(DESTDIR)$(HTMLDIR)/man1/$$fn"; \
chmod 644 "$(DESTDIR)$(HTMLDIR)/man1/$$fn"; \
done
@set -e; for x in dummy $(HTMLDOCS3); do \
if [ "$$x" = "dummy" ]; then continue; fi; \
fn=`basename $$x`; \
$(ECHO) "install $$x -> $(DESTDIR)$(HTMLDIR)/man3/$$fn"; \
cp $$x "$(DESTDIR)$(HTMLDIR)/man3/$$fn"; \
chmod 644 "$(DESTDIR)$(HTMLDIR)/man3/$$fn"; \
done
@set -e; for x in dummy $(HTMLDOCS5); do \
if [ "$$x" = "dummy" ]; then continue; fi; \
fn=`basename $$x`; \
$(ECHO) "install $$x -> $(DESTDIR)$(HTMLDIR)/man5/$$fn"; \
cp $$x "$(DESTDIR)$(HTMLDIR)/man5/$$fn"; \
chmod 644 "$(DESTDIR)$(HTMLDIR)/man5/$$fn"; \
done
@set -e; for x in dummy $(HTMLDOCS7); do \
if [ "$$x" = "dummy" ]; then continue; fi; \
fn=`basename $$x`; \
$(ECHO) "install $$x -> $(DESTDIR)$(HTMLDIR)/man7/$$fn"; \
cp $$x "$(DESTDIR)$(HTMLDIR)/man7/$$fn"; \
chmod 644 "$(DESTDIR)$(HTMLDIR)/man7/$$fn"; \
done
uninstall_html_docs: uninstall_image_docs
@$(ECHO) "*** Uninstalling HTML manpages"
@set -e; for x in dummy $(HTMLDOCS1); do \
if [ "$$x" = "dummy" ]; then continue; fi; \
fn=`basename $$x`; \
$(ECHO) "$(RM) $(DESTDIR)$(HTMLDIR)/man1/$$fn"; \
$(RM) "$(DESTDIR)$(HTMLDIR)/man1/$$fn"; \
done
@set -e; for x in dummy $(HTMLDOCS3); do \
if [ "$$x" = "dummy" ]; then continue; fi; \
fn=`basename $$x`; \
$(ECHO) "$(RM) $(DESTDIR)$(HTMLDIR)/man3/$$fn"; \
$(RM) "$(DESTDIR)$(HTMLDIR)/man3/$$fn"; \
done
@set -e; for x in dummy $(HTMLDOCS5); do \
if [ "$$x" = "dummy" ]; then continue; fi; \
fn=`basename $$x`; \
$(ECHO) "$(RM) $(DESTDIR)$(HTMLDIR)/man5/$$fn"; \
$(RM) "$(DESTDIR)$(HTMLDIR)/man5/$$fn"; \
done
@set -e; for x in dummy $(HTMLDOCS7); do \
if [ "$$x" = "dummy" ]; then continue; fi; \
fn=`basename $$x`; \
$(ECHO) "$(RM) $(DESTDIR)$(HTMLDIR)/man7/$$fn"; \
$(RM) "$(DESTDIR)$(HTMLDIR)/man7/$$fn"; \
done
install_image_docs:
@$(PERL) $(SRCDIR)/util/mkdir-p.pl "$(DESTDIR)$(HTMLDIR)/man7/img"
@set -e; for x in dummy $(IMAGEDOCS7); do \
if [ "$$x" = "dummy" ]; then continue; fi; \
fn=`basename $$x`; \
$(ECHO) "install $$x -> $(DESTDIR)$(HTMLDIR)/man7/img/$$fn"; \
cp $(SRCDIR)/$$x "$(DESTDIR)$(HTMLDIR)/man7/img/$$fn"; \
chmod 644 "$(DESTDIR)$(HTMLDIR)/man7/img/$$fn"; \
done
uninstall_image_docs:
@set -e; for x in dummy $(IMAGEDOCS7); do \
if [ "$$x" = "dummy" ]; then continue; fi; \
fn=`basename $$x`; \
$(ECHO) "$(RM) $(DESTDIR)$(HTMLDIR)/man7/img/$$fn"; \
$(RM) "$(DESTDIR)$(HTMLDIR)/man7/img/$$fn"; \
done
# Developer targets (note: these are only available on Unix) #########
# It's important that generate_buildinfo comes after ordinals, as ordinals
# is sensitive to build.info changes.
update: generate errors ordinals generate_buildinfo
generate: generate_apps generate_crypto_bn generate_crypto_objects \
generate_crypto_conf generate_crypto_asn1 generate_fuzz_oids
generate_buildinfo: generate_doc_buildinfo
.PHONY: doc-nits md-nits
doc-nits: build_generated_pods
$(PERL) $(SRCDIR)/util/find-doc-nits -c -n -l -e
# This uses "mdl", the markdownlint application, which is written in ruby.
# The source is at https://github.com/markdownlint/markdownlint
# If you have ruby installed, "gem install mdl" should work.
# Another option is at https://snapcraft.io/install/mdl/debian
# Finally, there's a Node.js version, which we haven't tried, that
# can be found at https://github.com/DavidAnson/markdownlint
md-nits:
mdl -s util/markdownlint.rb .
# Test coverage is a good idea for the future
#coverage: $(PROGRAMS) $(TESTPROGRAMS)
# ...
lint:
lint -DLINT $(INCLUDES) $(SRCS)
generate_apps:
( cd $(SRCDIR); $(PERL) VMS/VMSify-conf.pl \
< apps/openssl.cnf > apps/openssl-vms.cnf )
generate_crypto_bn:
( cd $(SRCDIR); $(PERL) crypto/bn/bn_prime.pl > crypto/bn/bn_prime.h )
generate_crypto_objects:
( cd $(SRCDIR); $(PERL) crypto/objects/objects.pl -n \
crypto/objects/objects.txt \
crypto/objects/obj_mac.num \
> crypto/objects/obj_mac.new && \
mv crypto/objects/obj_mac.new crypto/objects/obj_mac.num )
( cd $(SRCDIR); $(PERL) crypto/objects/objects.pl \
crypto/objects/objects.txt \
crypto/objects/obj_mac.num \
> include/openssl/obj_mac.h )
( cd $(SRCDIR); $(PERL) crypto/objects/obj_dat.pl \
include/openssl/obj_mac.h \
> crypto/objects/obj_dat.h )
( cd $(SRCDIR); $(PERL) crypto/objects/objxref.pl \
crypto/objects/obj_mac.num \
crypto/objects/obj_xref.txt \
> crypto/objects/obj_xref.h )
( cd $(SRCDIR); sed -e '1,8d' crypto/objects/obj_compat.h >> include/openssl/obj_mac.h )
generate_crypto_conf:
( cd $(SRCDIR); $(PERL) crypto/conf/keysets.pl \
> crypto/conf/conf_def.h )
generate_crypto_asn1:
( cd $(SRCDIR); $(PERL) crypto/asn1/charmap.pl \
> crypto/asn1/charmap.h )
generate_fuzz_oids:
( cd $(SRCDIR); $(PERL) fuzz/mkfuzzoids.pl \
crypto/objects/obj_dat.h \
> fuzz/oids.txt )
generate_doc_buildinfo:
( $(PERL) -I$(BLDDIR) -Mconfigdata \
$(SRCDIR)/util/dofile.pl -o Makefile \
$(SRCDIR)/doc/build.info.in \
> $(SRCDIR)/doc/build.info.new; \
if ( test -e $(SRCDIR)/doc/build.info \
&& cmp $(SRCDIR)/doc/build.info.new $(SRCDIR)/doc/build.info \
> /dev/null ); \
then \
rm $(SRCDIR)/doc/build.info.new; \
else \
mv $(SRCDIR)/doc/build.info.new $(SRCDIR)/doc/build.info; \
fi )
generate_fips_sources: providers/fips.module.sources.new
providers/fips.module.sources.new: configdata.pm
rm -rf sources-tmp
mkdir sources-tmp
( \
srcdir=`cd $(SRCDIR); pwd`; \
cd sources-tmp \
&& $$srcdir/Configure --banner=Configured enable-fips -O0 \
&& ./configdata.pm --query 'get_sources("providers/fips")' > sources1 \
- && $(MAKE) -sj 4 build_generated providers/fips.so \
+ && "$(MAKE)" -sj 4 build_generated providers/fips.so \
&& find . -name '*.d' | xargs cat > dep1 \
- && $(MAKE) distclean \
+ && "$(MAKE)" distclean \
&& $$srcdir/Configure --banner=Configured enable-fips no-asm -O0 \
&& ./configdata.pm --query 'get_sources("providers/fips")' > sources2 \
- && $(MAKE) -sj 4 build_generated providers/fips.so \
+ && "$(MAKE)" -sj 4 build_generated providers/fips.so \
&& find . -name '*.d' | xargs cat > dep2 \
&& cat sources1 sources2 \
| grep -v ' : \\$$' | grep -v util/providers.num \
| sed -e 's/^ *//' -e 's/ *\\$$//' \
| sort | uniq > sources \
&& cat dep1 dep2 \
| $(PERL) -p -e 's/\\\n//' \
| sed -e 's/^.*: *//' -e 's/ */ /g' \
| fgrep -f sources \
| tr ' ' '\n' \
| sort | uniq > deps.raw \
&& cat deps.raw \
| xargs ./configdata.pm --query 'get_sources(@ARGV)' \
| $(PERL) -p -e 's/\\\n//' \
| sed -e 's/\./\\\./g' -e 's/ : */:/' -e 's/^/s:/' -e 's/$$/:/' \
> deps.sed \
&& cat deps.raw | sed -f deps.sed > deps \
)
( \
cat sources-tmp/sources sources-tmp/deps \
| $(PERL) -p -e 's:^ *\Q../\E:: ;' \
-e 's:^\Q$(SRCDIR)/\E:: if "$(SRCDIR)" ne "." ;' \
-e 'my $$x; do { $$x = $$_; s:(^|/)((?!\Q../\E)[^/]*/)\Q..\E($$|/):$$1: } while ($$x ne $$_) ;' ; \
cd $(SRCDIR); \
for x in crypto/bn/asm/*.pl crypto/bn/asm/*.S \
crypto/aes/asm/*.pl crypto/aes/asm/*.S \
crypto/ec/asm/*.pl \
crypto/modes/asm/*.pl \
crypto/sha/asm/*.pl \
crypto/*cpuid.pl crypto/*cpuid.S \
crypto/*cap.c; do \
echo "$$x"; \
done \
) | sort | uniq > providers/fips.module.sources.new
rm -rf sources-tmp
# Set to -force to force a rebuild
ERROR_REBUILD=
errors:
( b=`pwd`; set -e; cd $(SRCDIR); \
$(PERL) util/ck_errf.pl -strict -internal; \
$(PERL) -I$$b util/mkerr.pl $(ERROR_REBUILD) -internal )
( b=`pwd`; set -e; cd $(SRCDIR)/engines; \
for E in *.ec ; do \
$(PERL) ../util/ck_errf.pl -strict \
-conf $$E `basename $$E .ec`.c; \
$(PERL) -I$$b ../util/mkerr.pl $(ERROR_REBUILD) -static \
-conf $$E `basename $$E .ec`.c ; \
done )
{- use File::Basename;
my @sslheaders_tmpl =
qw( include/openssl/ssl.h
include/openssl/ssl2.h
include/openssl/ssl3.h
include/openssl/sslerr.h
include/openssl/tls1.h
include/openssl/dtls1.h
include/openssl/srtp.h
include/openssl/sslerr_legacy.h );
my @cryptoheaders_tmpl =
qw( include/internal/dso.h
include/internal/o_dir.h
include/internal/err.h
include/internal/evp.h
include/internal/pem.h
include/internal/asn1.h
include/internal/sslconf.h );
my @cryptoskipheaders = ( @sslheaders_tmpl,
qw( include/openssl/conf_api.h
include/openssl/ebcdic.h
include/openssl/opensslconf.h
include/openssl/symhacks.h ) );
our %cryptoheaders = ();
our %sslheaders = ();
foreach my $d ( qw( include/openssl include/internal ) ) {
my @header_patterns =
map { catfile($config{sourcedir}, $d, $_) } ( '*.h', '*.h.in' );
foreach my $f ( map { glob($_) } @header_patterns ) {
my $base = basename($f);
my $base_in = basename($f, '.in');
my $dir = catfile($config{sourcedir}, $d);
if ($base ne $base_in) {
# We have a .h.in file, which means the header file is in the
# build tree.
$base = $base_in;
$dir = catfile($config{builddir}, $d);
}
my $new_f = catfile($dir, $base);
my $fn = "$d/$base";
# The logic to add files to @cryptoheaders is a bit complex. The
# file to be added must be either in the public header directory
# or one of the pre-declared internal headers, and must under no
# circumstances be one of those that must be skipped.
$cryptoheaders{$new_f} = 1
if (($d eq 'include/openssl'
|| ( grep { $_ eq $fn } @cryptoheaders_tmpl ))
&& !( grep { $_ eq $fn } @cryptoskipheaders ));
# The logic to add files to @sslheaders is much simpler...
$sslheaders{$new_f} = 1 if grep { $_ eq $fn } @sslheaders_tmpl;
}
}
"";
-}
CRYPTOHEADERS={- join(" \\\n" . ' ' x 14,
fill_lines(" ", $COLUMNS - 14, sort keys %cryptoheaders)) -}
SSLHEADERS={- join(" \\\n" . ' ' x 11,
fill_lines(" ", $COLUMNS - 11, sort keys %sslheaders)) -}
renumber: build_generated
$(PERL) $(SRCDIR)/util/mknum.pl --version $(VERSION_NUMBER) --no-warnings \
--ordinals $(SRCDIR)/util/libcrypto.num \
--symhacks $(SRCDIR)/include/openssl/symhacks.h \
--renumber \
$(CRYPTOHEADERS)
$(PERL) $(SRCDIR)/util/mknum.pl --version $(VERSION_NUMBER) --no-warnings \
--ordinals $(SRCDIR)/util/libssl.num \
--symhacks $(SRCDIR)/include/openssl/symhacks.h \
--renumber \
$(SSLHEADERS)
ordinals: build_generated
$(PERL) $(SRCDIR)/util/mknum.pl --version $(VERSION_NUMBER) --no-warnings \
--ordinals $(SRCDIR)/util/libcrypto.num \
--symhacks $(SRCDIR)/include/openssl/symhacks.h \
$(CRYPTOHEADERS)
$(PERL) $(SRCDIR)/util/mknum.pl --version $(VERSION_NUMBER) --no-warnings \
--ordinals $(SRCDIR)/util/libssl.num \
--symhacks $(SRCDIR)/include/openssl/symhacks.h \
$(SSLHEADERS)
test_ordinals:
- $(MAKE) run_tests TESTS=test_ordinals
+ "$(MAKE)" run_tests TESTS=test_ordinals
tags TAGS: FORCE
rm -f TAGS tags
-ctags -R .
-etags `find . -name '*.[ch]' -o -name '*.pm'`
providers/fips.checksum.new: providers/fips.module.sources.new
@which unifdef > /dev/null || \
( echo >&2 "ERROR: unifdef not in your \$$PATH, FIPS checksums not calculated"; \
false )
( sources=`pwd`/providers/fips.module.sources.new; \
cd $(SRCDIR) \
&& cat $$sources \
| xargs ./util/fips-checksums.sh ) \
> providers/fips-sources.checksums.new \
&& sha256sum providers/fips-sources.checksums.new \
| sed -e 's|\.new||' > providers/fips.checksum.new
fips-checksums: providers/fips.checksum.new
$(SRCDIR)/providers/fips.checksum: providers/fips.checksum.new
cp -p providers/fips.module.sources.new $(SRCDIR)/providers/fips.module.sources
cp -p providers/fips-sources.checksums.new $(SRCDIR)/providers/fips-sources.checksums
cp -p providers/fips.checksum.new $(SRCDIR)/providers/fips.checksum
update-fips-checksums: $(SRCDIR)/providers/fips.checksum
diff-fips-checksums: fips-checksums
diff -u $(SRCDIR)/providers/fips.module.sources providers/fips.module.sources.new
diff -u $(SRCDIR)/providers/fips-sources.checksums providers/fips-sources.checksums.new
diff -u $(SRCDIR)/providers/fips.checksum providers/fips.checksum.new
# Release targets (note: only available on Unix) #####################
tar:
(cd $(SRCDIR); ./util/mktar.sh --name='$(NAME)' --tarfile='$(TARFILE)')
# Helper targets #####################################################
link-utils: $(BLDDIR)/util/opensslwrap.sh $(BLDDIR)/apps/openssl.cnf
$(BLDDIR)/util/opensslwrap.sh: Makefile
@if [ "$(SRCDIR)" != "$(BLDDIR)" ]; then \
mkdir -p "$(BLDDIR)/util"; \
ln -sf "../$(SRCDIR)/util/`basename "$@"`" "$(BLDDIR)/util"; \
fi
$(BLDDIR)/apps/openssl.cnf: Makefile
@if [ "$(SRCDIR)" != "$(BLDDIR)" ]; then \
mkdir -p "$(BLDDIR)/apps"; \
ln -sf "../$(SRCDIR)/apps/`basename "$@"`" "$(BLDDIR)/apps"; \
fi
FORCE:
# Building targets ###################################################
libcrypto.pc libssl.pc openssl.pc: Makefile $(LIBS) {- join(" ",map { platform->sharedlib_simple($_) // platform->sharedlib_import($_) // platform->sharedlib($_) // () } @{$unified_info{libraries}}) -}
libcrypto.pc:
@ ( echo 'prefix=$(INSTALLTOP)'; \
echo 'exec_prefix=$${prefix}'; \
if [ -n "$(LIBDIR)" ]; then \
echo 'libdir=$${exec_prefix}/$(LIBDIR)'; \
else \
echo 'libdir=$(libdir)'; \
fi; \
echo 'includedir=$${prefix}/include'; \
echo 'enginesdir=$${libdir}/engines-{- $sover_dirname -}'; \
echo 'modulesdir=$${libdir}/ossl-modules'; \
echo ''; \
echo 'Name: OpenSSL-libcrypto'; \
echo 'Description: OpenSSL cryptography library'; \
echo 'Version: '$(VERSION); \
echo 'Libs: -L$${libdir} -lcrypto'; \
echo 'Libs.private: $(LIB_EX_LIBS)'; \
echo 'Cflags: -I$${includedir}' ) > libcrypto.pc
libssl.pc:
@ ( echo 'prefix=$(INSTALLTOP)'; \
echo 'exec_prefix=$${prefix}'; \
if [ -n "$(LIBDIR)" ]; then \
echo 'libdir=$${exec_prefix}/$(LIBDIR)'; \
else \
echo 'libdir=$(libdir)'; \
fi; \
echo 'includedir=$${prefix}/include'; \
echo ''; \
echo 'Name: OpenSSL-libssl'; \
echo 'Description: Secure Sockets Layer and cryptography libraries'; \
echo 'Version: '$(VERSION); \
echo 'Requires.private: libcrypto'; \
echo 'Libs: -L$${libdir} -lssl'; \
echo 'Cflags: -I$${includedir}' ) > libssl.pc
openssl.pc:
@ ( echo 'prefix=$(INSTALLTOP)'; \
echo 'exec_prefix=$${prefix}'; \
if [ -n "$(LIBDIR)" ]; then \
echo 'libdir=$${exec_prefix}/$(LIBDIR)'; \
else \
echo 'libdir=$(libdir)'; \
fi; \
echo 'includedir=$${prefix}/include'; \
echo ''; \
echo 'Name: OpenSSL'; \
echo 'Description: Secure Sockets Layer and cryptography libraries and tools'; \
echo 'Version: '$(VERSION); \
echo 'Requires: libssl libcrypto' ) > openssl.pc
Makefile: configdata.pm \
{- join(" \\\n" . ' ' x 10,
fill_lines(" ", $COLUMNS - 10,
@{$config{build_file_templates}})) -}
@echo "Detected changed: $?"
$(PERL) configdata.pm
@echo "**************************************************"
@echo "*** ***"
@echo "*** Please run the same make command again ***"
@echo "*** ***"
@echo "**************************************************"
@false
configdata.pm: $(SRCDIR)/Configure $(SRCDIR)/config \
{- join(" \\\n" . ' ' x 15,
fill_lines(" ", $COLUMNS - 15,
@{$config{build_infos}},
@{$config{conf_files}})) -}
@echo "Detected changed: $?"
$(PERL) configdata.pm -r
@echo "**************************************************"
@echo "*** ***"
@echo "*** Please run the same make command again ***"
@echo "*** ***"
@echo "**************************************************"
@false
reconfigure reconf:
$(PERL) configdata.pm -r
{-
use File::Basename;
use File::Spec::Functions qw/:DEFAULT abs2rel rel2abs/;
# Helper function to convert dependencies in platform agnostic form to
# dependencies in platform form.
sub compute_platform_depends {
map { my $x = $_;
grep { $x eq $_ } @{$unified_info{programs}} and platform->bin($x)
or grep { $x eq $_ } @{$unified_info{modules}} and platform->dso($x)
or grep { $x eq $_ } @{$unified_info{libraries}} and platform->lib($x)
or platform->convertext($x); } @_;
}
# Helper function to figure out dependencies on libraries
# It takes a list of library names and outputs a list of dependencies
sub compute_lib_depends {
# Depending on shared libraries:
# On Windows POSIX layers, we depend on {libname}.dll.a
# On Unix platforms, we depend on {shlibname}.so
return map { platform->sharedlib_simple($_)
// platform->sharedlib_import($_)
// platform->sharedlib($_)
// platform->staticlib($_)
} @_;
}
sub generatetarget {
my %args = @_;
my $deps = join(" ", compute_platform_depends(@{$args{deps}}));
return <<"EOF";
$args{target}: $deps
EOF
}
sub generatesrc {
my %args = @_;
my $gen0 = $args{generator}->[0];
my $gen_args = join('', map { " $_" }
@{$args{generator}}[1..$#{$args{generator}}]);
my $gen_incs = join("", map { " -I".$_ } @{$args{generator_incs}});
my $incs = join("", map { " -I".$_ } @{$args{incs}});
my $defs = join("", map { " -D".$_ } @{$args{defs}});
my $deps = join(" ", compute_platform_depends(@{$args{generator_deps}},
@{$args{deps}}));
if ($args{src} =~ /\.html$/) {
#
# HTML generator
#
my $title = basename($args{src}, ".html");
my $pod = $gen0;
return <<"EOF";
$args{src}: $pod
\$(PERL) \$(SRCDIR)/util/mkpod2html.pl -i "$pod" -o \$\@ -t "$title" -r "\$(SRCDIR)/doc"
EOF
} elsif ($args{src} =~ /\.(\d)$/) {
#
# Man-page generator
#
my $section = $1;
my $name = uc basename($args{src}, ".$section");
my $pod = $gen0;
return <<"EOF";
$args{src}: $pod
pod2man --name=$name --section=$section\$(MANSUFFIX) --center=OpenSSL \\
--release=\$(VERSION) $pod >\$\@
EOF
} elsif (platform->isdef($args{src})) {
#
# Linker script-ish generator
#
my $target = platform->def($args{src});
(my $mkdef_os = $target{shared_target}) =~ s|-shared$||;
my $ord_ver = $args{intent} eq 'lib' ? ' --version $(VERSION_NUMBER)' : '';
my $ord_name = $args{generator}->[1] || $args{product};
return <<"EOF";
$target: $gen0 $deps \$(SRCDIR)/util/mkdef.pl
\$(PERL) \$(SRCDIR)/util/mkdef.pl$ord_ver --type $args{intent} --ordinals $gen0 --name $ord_name --OS $mkdef_os > $target
EOF
} elsif (platform->isasm($args{src})
|| platform->iscppasm($args{src})) {
#
# Assembler generator
#
my $cppflags = {
shlib => '$(LIB_CFLAGS) $(LIB_CPPFLAGS)',
lib => '$(LIB_CFLAGS) $(LIB_CPPFLAGS)',
dso => '$(DSO_CFLAGS) $(DSO_CPPFLAGS)',
bin => '$(BIN_CFLAGS) $(BIN_CPPFLAGS)'
} -> {$args{intent}};
my $generator;
if ($gen0 =~ /\.pl$/) {
$generator = 'CC="$(CC)" $(PERL)'.$gen_incs.' '.$gen0.$gen_args
.' "$(PERLASM_SCHEME)"'.$incs.' '.$cppflags.$defs.' $(PROCESSOR)';
} elsif ($gen0 =~ /\.m4$/) {
$generator = 'm4 -B 8192'.$gen_incs.' '.$gen0.$gen_args.' >'
} elsif ($gen0 =~ /\.S$/) {
$generator = undef;
} else {
die "Generator type for $args{src} unknown: $gen0\n";
}
if (defined($generator)) {
return <<"EOF";
$args{src}: $gen0 $deps
$generator \$@
EOF
}
return <<"EOF";
$args{src}: $gen0 $deps
\$(CC) $incs $cppflags $defs -E $gen0 | \\
\$(PERL) -ne '/^#(line)?\\s*[0-9]+/ or print' > \$@
EOF
} elsif ($gen0 =~ m|^.*\.in$|) {
#
# "dofile" generator (file.in -> file)
#
my $dofile = abs2rel(rel2abs(catfile($config{sourcedir},
"util", "dofile.pl")),
rel2abs($config{builddir}));
my @perlmodules = ( 'configdata.pm',
grep { $_ =~ m|\.pm$| } @{$args{deps}} );
my %perlmoduleincs = map { '"-I'.dirname($_).'"' => 1 } @perlmodules;
$deps = join(' ', $deps, compute_platform_depends(@perlmodules));
@perlmodules = map { "-M".basename($_, '.pm') } @perlmodules;
my $perlmodules = join(' ', '', sort keys %perlmoduleincs, @perlmodules);
return <<"EOF";
$args{src}: $gen0 $deps
\$(PERL)$perlmodules "$dofile" "-o$target{build_file}" $gen0$gen_args > \$@
EOF
} elsif (grep { $_ eq $gen0 } @{$unified_info{programs}}) {
#
# Generic generator using OpenSSL programs
#
# Redo $gen0, to ensure that we have the proper extension where
# necessary.
$gen0 = platform->bin($gen0);
# Use $(PERL) to execute wrap.pl directly to avoid calling env
return <<"EOF";
$args{src}: $gen0 $deps \$(BLDDIR)/util/wrap.pl
\$(PERL) \$(BLDDIR)/util/wrap.pl $gen0$gen_args > \$@
EOF
} else {
#
# Generic generator using Perl
#
return <<"EOF";
$args{src}: $gen0 $deps
\$(PERL)$gen_incs $gen0$gen_args > \$@
EOF
}
}
# Should one wonder about the end of the Perl snippet, it's because this
# second regexp eats up line endings as well, if the removed path is the
# last in the line. We may therefore need to put back a line ending.
sub src2obj {
my %args = @_;
my $obj = platform->convertext($args{obj});
my $dep = platform->dep($args{obj});
my @srcs = @{$args{srcs}};
my $srcs = join(" ", @srcs);
my $deps = join(" ", @srcs, @{$args{deps}});
my $incs = join("", map { " -I".$_ } @{$args{incs}});
my $defs = join("", map { " -D".$_ } @{$args{defs}});
my $cmd;
my $cmdflags;
my $cmdcompile;
if (grep /\.rc$/, @srcs) {
$cmd = '$(RC)';
$cmdflags = '$(RCFLAGS)';
$cmdcompile = '';
} elsif (grep /\.(cc|cpp)$/, @srcs) {
$cmd = '$(CXX)';
$cmdcompile = ' -c';
$cmdflags = {
shlib => '$(LIB_CXXFLAGS) $(LIB_CPPFLAGS)',
lib => '$(LIB_CXXFLAGS) $(LIB_CPPFLAGS)',
dso => '$(DSO_CXXFLAGS) $(DSO_CPPFLAGS)',
bin => '$(BIN_CXXFLAGS) $(BIN_CPPFLAGS)'
} -> {$args{intent}};
} else {
$cmd = '$(CC)';
$cmdcompile = ' -c';
$cmdflags = {
shlib => '$(LIB_CFLAGS) $(LIB_CPPFLAGS)',
lib => '$(LIB_CFLAGS) $(LIB_CPPFLAGS)',
dso => '$(DSO_CFLAGS) $(DSO_CPPFLAGS)',
bin => '$(BIN_CFLAGS) $(BIN_CPPFLAGS)'
} -> {$args{intent}};
}
my $recipe;
# extension-specific rules
if (grep /\.s$/, @srcs) {
$recipe .= <<"EOF";
$obj: $deps
$cmd $cmdflags -c -o \$\@ $srcs
EOF
} elsif (grep /\.S$/, @srcs) {
# Originally there was multi-step rule with $(CC) -E file.S
# followed by $(CC) -c file.s. It compensated for one of
# legacy platform compiler's inability to handle .S files.
# The platform is long discontinued by vendor so there is
# hardly a point to drag it along...
$recipe .= <<"EOF";
$obj: $deps
$cmd $incs $defs $cmdflags -c -o \$\@ $srcs
EOF
} elsif ($makedep_scheme eq 'gcc' && !grep /\.rc$/, @srcs) {
$recipe .= <<"EOF";
$obj: $deps
$cmd $incs $defs $cmdflags -MMD -MF $dep.tmp -MT \$\@ -c -o \$\@ $srcs
\@touch $dep.tmp
\@if cmp $dep.tmp $dep > /dev/null 2> /dev/null; then \\
rm -f $dep.tmp; \\
else \\
mv $dep.tmp $dep; \\
fi
EOF
} else {
$recipe .= <<"EOF";
$obj: $deps
$cmd $incs $defs $cmdflags $cmdcompile -o \$\@ $srcs
EOF
if ($makedep_scheme eq 'makedepend') {
$recipe .= <<"EOF";
\$(MAKEDEPEND) -f- -Y -- $incs $cmdflags -- $srcs 2>/dev/null \\
> $dep
EOF
}
}
return $recipe;
}
# We *know* this routine is only called when we've configure 'shared'.
sub obj2shlib {
my %args = @_;
my @linkdirs = ();
my @linklibs = ();
foreach (@{$args{deps}}) {
if (platform->isstaticlib($_)) {
push @linklibs, platform->convertext($_);
} else {
my $d = "-L" . dirname($_);
my $l = basename($_);
$l =~ s/^lib//;
$l = "-l" . $l;
push @linklibs, $l;
push @linkdirs, $d unless grep { $d eq $_ } @linkdirs;
}
}
my $linkflags = join("", map { $_." " } @linkdirs);
my $linklibs = join("", map { $_." " } @linklibs);
my @objs = map { platform->convertext($_) }
grep { !platform->isdef($_) }
@{$args{objs}};
my @defs = map { platform->def($_) }
grep { platform->isdef($_) }
@{$args{objs}};
my @deps = compute_lib_depends(@{$args{deps}});
die "More than one exported symbol map" if scalar @defs > 1;
my $full = platform->sharedlib($args{lib});
# $import is for Windows and subsystems thereof, where static import
# libraries for DLLs are a thing. On platforms that have this mechanism,
# $import has the name of this import library. On platforms that don't
# have this mechanism, $import will be |undef|.
my $import = platform->sharedlib_import($args{lib});
# $simple is for platforms where full shared library names include the
# shared library version, and there's a simpler name that doesn't include
# that version. On such platforms, $simple has the simpler name. On
# other platforms, it will be |undef|.
my $simple = platform->sharedlib_simple($args{lib});
my $argfile = defined $target{shared_argfileflag} ? $full.".args" : undef;
my $shared_soname = "";
$shared_soname .= ' '.$target{shared_sonameflag}.basename($full)
if defined $target{shared_sonameflag};
my $shared_imp = "";
$shared_imp .= ' '.$target{shared_impflag}.basename($import)
if defined $target{shared_impflag} && defined $import;
my $shared_def = join("", map { ' '.$target{shared_defflag}.$_ } @defs);
# There is at least one platform where the compiler-as-linker needs to
# have one object file directly on the command line. That won't hurt
# any other platform, so we do that for everyone when there's an argfile
# to be had. This depends heavily on splice, which removes elements from
# the given array, and returns them so they can be captured.
my @argfileobjs = $argfile
? splice(@objs, 1)
: ();
my $argfilecmds = $argfile
? join("\n\t", map { "echo $_ >> $argfile" } @argfileobjs)
: undef;
my $argfiledeps = $argfile
? join(" \\\n" . ' ' x (length($argfile) + 2),
fill_lines(' ', $COLUMNS - length($full) - 2, @argfileobjs))
: undef;
my @fulldeps = (@objs, ($argfile ? $argfile : ()), @defs, @deps);
my @fullobjs = (
@objs,
($argfile ? $target{shared_argfileflag}.$argfile : ())
);
my $fulldeps =
join(" \\\n" . ' ' x (length($full) + 2),
fill_lines(' ', $COLUMNS - length($full) - 2, @fulldeps));
my $fullobjs =
join(" \\\n\t\t", fill_lines(' ', $COLUMNS - 16, @fullobjs));
my $recipe = '';
if (defined $simple && $simple ne $full) {
if (sharedaix()) {
$recipe .= <<"EOF";
$simple: $full
rm -f $simple && \\
\$(AR) r $simple $full
EOF
} else {
$recipe .= <<"EOF";
$simple: $full
rm -f $simple && \\
ln -s $full $simple
EOF
}
}
if (defined $import) {
$recipe .= <<"EOF";
$import: $full
EOF
}
$recipe .= <<"EOF";
$full: $fulldeps
\$(CC) \$(LIB_CFLAGS) $linkflags\$(LIB_LDFLAGS)$shared_soname$shared_imp \\
-o $full$shared_def \\
$fullobjs \\
$linklibs \$(LIB_EX_LIBS)
EOF
if (windowsdll()) {
$recipe .= <<"EOF";
rm -f apps/$full
rm -f fuzz/$full
cp -p $full apps/
cp -p $full fuzz/
EOF
if (!$disabled{tests}) {
$recipe .= <<"EOF";
rm -f test/$full
cp -p $full test/
EOF
}
}
$recipe .= <<"EOF" if defined $argfile;
$argfile: $argfiledeps
\$(RM) $argfile
$argfilecmds
EOF
return $recipe;
}
sub obj2dso {
my %args = @_;
my $dso = platform->dso($args{module});
my @linkdirs = ();
my @linklibs = ();
foreach (@{$args{deps}}) {
next unless defined $_;
if (platform->isstaticlib($_)) {
push @linklibs, platform->convertext($_);
} else {
my $d = "-L" . dirname($_);
my $l = basename($_);
$l =~ s/^lib//;
$l = "-l" . $l;
push @linklibs, $l;
push @linkdirs, $d unless grep { $d eq $_ } @linkdirs;
}
}
my $linkflags = join("", map { $_." " } @linkdirs);
my $linklibs = join("", map { $_." " } @linklibs);
my @objs = map { platform->convertext($_) }
grep { !platform->isdef($_) }
@{$args{objs}};
my @defs = map { platform->def($_) }
grep { platform->isdef($_) }
@{$args{objs}};
my @deps = compute_lib_depends(@{$args{deps}});
my $shared_def = join("", map { ' '.$target{shared_defflag}.$_ } @defs);
# Next line needs to become "less magic" (see PR #11950)
$shared_def .= ' '.$target{shared_fipsflag} if (defined $target{shared_fipsflag} && $shared_def =~ m/providers\/fips/);
my $objs = join(" \\\n\t\t", fill_lines(' ', $COLUMNS - 16, @objs));
my $deps = join(" \\\n" . ' ' x (length($dso) + 2),
fill_lines(' ', $COLUMNS - length($dso) - 2,
@objs, @defs, @deps));
return <<"EOF";
$dso: $deps
\$(CC) \$(DSO_CFLAGS) $linkflags\$(DSO_LDFLAGS) \\
-o $dso$shared_def \\
$objs \\
$linklibs\$(DSO_EX_LIBS)
EOF
}
sub obj2lib {
my %args = @_;
my $lib = platform->staticlib($args{lib});
my @objs = map { platform->obj($_) } @{$args{objs}};
my $deps = join(" \\\n" . ' ' x (length($lib) + 2),
fill_lines(' ', $COLUMNS - length($lib) - 2, @objs));
my $max_per_call = 500;
my @objs_grouped;
push @objs_grouped, join(" ", splice @objs, 0, $max_per_call) while @objs;
my $fill_lib =
join("\n\t", (map { "\$(AR) \$(ARFLAGS) $lib $_" } @objs_grouped));
return <<"EOF";
$lib: $deps
\$(RM) $lib
$fill_lib
\$(RANLIB) \$\@ || echo Never mind.
EOF
}
sub obj2bin {
my %args = @_;
my $bin = platform->bin($args{bin});
my @objs = map { platform->obj($_) } @{$args{objs}};
my @deps = compute_lib_depends(@{$args{deps}});
my $objs = join(" \\\n" . ' ' x (length($bin) + 2),
fill_lines(' ', $COLUMNS - length($bin) - 2, @objs));
my @linkdirs = ();
my @linklibs = ();
foreach (@{$args{deps}}) {
next unless defined $_;
if (platform->isstaticlib($_)) {
push @linklibs, platform->convertext($_);
} else {
my $d = "-L" . dirname($_);
my $l = basename($_);
$l =~ s/^lib//;
$l = "-l" . $l;
push @linklibs, $l;
push @linkdirs, $d unless grep { $d eq $_ } @linkdirs;
}
}
my $linkflags = join("", map { $_." " } @linkdirs);
my $linklibs = join("", map { $_." " } @linklibs);
my $cmd = '$(CC)';
my $cmdflags = '$(BIN_CFLAGS)';
if (grep /_cc\.o$/, @{$args{objs}}) {
$cmd = '$(CXX)';
$cmdflags = '$(BIN_CXXFLAGS)';
}
my $objs = join(" \\\n\t\t", fill_lines(' ', $COLUMNS - 16, @objs));
my $deps = join(" \\\n" . ' ' x (length($bin) + 2),
fill_lines(' ', $COLUMNS - length($bin) - 2,
@objs, @deps));
return <<"EOF";
$bin: $deps
rm -f $bin
\$\${LDCMD:-$cmd} $cmdflags $linkflags\$(BIN_LDFLAGS) \\
-o $bin \\
$objs \\
$linklibs\$(BIN_EX_LIBS)
EOF
}
sub in2script {
my %args = @_;
my $script = $args{script};
my $sources = join(" ", @{$args{sources}});
my $dofile = abs2rel(rel2abs(catfile($config{sourcedir},
"util", "dofile.pl")),
rel2abs($config{builddir}));
return <<"EOF";
$script: $sources configdata.pm
\$(RM) "$script"
\$(PERL) "-I\$(BLDDIR)" -Mconfigdata "$dofile" \\
"-o$target{build_file}" $sources > "$script"
chmod a+x $script
EOF
}
sub generatedir {
my %args = @_;
my $dir = $args{dir};
my @deps = compute_platform_depends(@{$args{deps}});
my @comments = ();
# We already have a 'test' target, and the top directory is just plain
# silly
return if $dir eq "test" || $dir eq ".";
foreach my $type (("dso", "lib", "bin", "script")) {
next unless defined($unified_info{dirinfo}->{$dir}->{products}->{$type});
# For lib object files, we could update the library. However, it
# was decided that it's enough to build the directory local object
# files, so we don't need to add any actions, and the dependencies
# are already taken care of.
if ($type ne "lib") {
foreach my $prod (@{$unified_info{dirinfo}->{$dir}->{products}->{$type}}) {
if (dirname($prod) eq $dir) {
push @deps, compute_platform_depends($prod);
} else {
push @comments, "# No support to produce $type ".join(", ", @{$unified_info{dirinfo}->{$dir}->{products}->{$type}});
}
}
}
}
my $target = "$dir $dir/";
my $deps = join(" \\\n\t",
fill_lines(' ', $COLUMNS - 8, @deps));
my $comments = join("\n", "", @comments);
return <<"EOF";
$target: \\
$deps$comments
EOF
}
"" # Important! This becomes part of the template result.
-}
diff --git a/crypto/openssl/Configure b/crypto/openssl/Configure
index 84cc4094644a..40c03ad0af32 100755
--- a/crypto/openssl/Configure
+++ b/crypto/openssl/Configure
@@ -1,3596 +1,3597 @@
#! /usr/bin/env perl
# -*- mode: perl; -*-
-# Copyright 2016-2023 The OpenSSL Project Authors. All Rights Reserved.
+# Copyright 2016-2024 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
## Configure -- OpenSSL source tree configuration script
use 5.10.0;
use strict;
use Config;
use FindBin;
use lib "$FindBin::Bin/util/perl";
use File::Basename;
use File::Spec::Functions qw/:DEFAULT abs2rel rel2abs splitdir/;
use File::Path qw/mkpath/;
use OpenSSL::fallback "$FindBin::Bin/external/perl/MODULES.txt";
use OpenSSL::Glob;
use OpenSSL::Template;
use OpenSSL::config;
# see INSTALL.md for instructions.
my $orig_death_handler = $SIG{__DIE__};
$SIG{__DIE__} = \&death_handler;
my $usage="Usage: Configure [no-<cipher> ...] [enable-<cipher> ...] [-Dxxx] [-lxxx] [-Lxxx] [-fxxx] [-Kxxx] [no-hw-xxx|no-hw] [[no-]threads] [[no-]shared] [[no-]zlib|zlib-dynamic] [no-asm] [no-egd] [sctp] [386] [--prefix=DIR] [--openssldir=OPENSSLDIR] [--with-xxx[=vvv]] [--config=FILE] os/compiler[:flags]\n";
my $banner = <<"EOF";
**********************************************************************
*** ***
*** OpenSSL has been successfully configured ***
*** ***
*** If you encounter a problem while building, please open an ***
*** issue on GitHub <https://github.com/openssl/openssl/issues> ***
*** and include the output from the following command: ***
*** ***
*** perl configdata.pm --dump ***
*** ***
*** (If you are new to OpenSSL, you might want to consult the ***
*** 'Troubleshooting' section in the INSTALL.md file first) ***
*** ***
**********************************************************************
EOF
# Options:
#
# --config add the given configuration file, which will be read after
# any "Configurations*" files that are found in the same
# directory as this script.
# --prefix prefix for the OpenSSL installation, which includes the
# directories bin, lib, include, share/man, share/doc/openssl
# This becomes the value of INSTALLTOP in Makefile
# (Default: /usr/local)
# --openssldir OpenSSL data area, such as openssl.cnf, certificates and keys.
# If it's a relative directory, it will be added on the directory
# given with --prefix.
# This becomes the value of OPENSSLDIR in Makefile and in C.
# (Default: PREFIX/ssl)
# --banner=".." Output specified text instead of default completion banner
#
# -w Don't wait after showing a Configure warning
#
# --cross-compile-prefix Add specified prefix to binutils components.
#
# --api One of 0.9.8, 1.0.0, 1.0.1, 1.0.2, 1.1.0, 1.1.1, or 3.0
# Define the public APIs as they were for that version
# including patch releases. If 'no-deprecated' is also
# given, do not compile support for interfaces deprecated
# up to and including the specified OpenSSL version.
#
# no-hw-xxx do not compile support for specific crypto hardware.
# Generic OpenSSL-style methods relating to this support
# are always compiled but return NULL if the hardware
# support isn't compiled.
# no-hw do not compile support for any crypto hardware.
# [no-]threads [don't] try to create a library that is suitable for
# multithreaded applications (default is "threads" if we
# know how to do it)
# [no-]shared [don't] try to create shared libraries when supported.
# [no-]pic [don't] try to build position independent code when supported.
# If disabled, it also disables shared and dynamic-engine.
# no-asm do not use assembler
# no-egd do not compile support for the entropy-gathering daemon APIs
# [no-]zlib [don't] compile support for zlib compression.
# zlib-dynamic Like "zlib", but the zlib library is expected to be a shared
# library and will be loaded in run-time by the OpenSSL library.
# sctp include SCTP support
# no-uplink Don't build support for UPLINK interface.
# enable-weak-ssl-ciphers
# Enable weak ciphers that are disabled by default.
# 386 generate 80386 code in assembly modules
# no-sse2 disables IA-32 SSE2 code in assembly modules, the above
# mentioned '386' option implies this one
# no-<cipher> build without specified algorithm (dsa, idea, rc5, ...)
# -<xxx> +<xxx> All options which are unknown to the 'Configure' script are
# /<xxx> passed through to the compiler. Unix-style options beginning
# with a '-' or '+' are recognized, as well as Windows-style
# options beginning with a '/'. If the option contains arguments
# separated by spaces, then the URL-style notation %20 can be
# used for the space character in order to avoid having to quote
# the option. For example, -opt%20arg gets expanded to -opt arg.
# In fact, any ASCII character can be encoded as %xx using its
# hexadecimal encoding.
# -static while -static is also a pass-through compiler option (and
# as such is limited to environments where it's actually
# meaningful), it triggers a number configuration options,
# namely no-pic, no-shared and no-threads. It is
# argued that the only reason to produce statically linked
# binaries (and in context it means executables linked with
# -static flag, and not just executables linked with static
# libcrypto.a) is to eliminate dependency on specific run-time,
# a.k.a. libc version. The mentioned config options are meant
# to achieve just that. Unfortunately on Linux it's impossible
# to eliminate the dependency completely for openssl executable
# because of getaddrinfo and gethostbyname calls, which can
# invoke dynamically loadable library facility anyway to meet
# the lookup requests. For this reason on Linux statically
# linked openssl executable has rather debugging value than
# production quality.
#
# BN_LLONG use the type 'long long' in crypto/bn/bn.h
# RC4_CHAR use 'char' instead of 'int' for RC4_INT in crypto/rc4/rc4.h
# Following are set automatically by this script
#
# MD5_ASM use some extra md5 assembler,
# SHA1_ASM use some extra sha1 assembler, must define L_ENDIAN for x86
# RMD160_ASM use some extra ripemd160 assembler,
# SHA256_ASM sha256_block is implemented in assembler
# SHA512_ASM sha512_block is implemented in assembler
# AES_ASM AES_[en|de]crypt is implemented in assembler
# Minimum warning options... any contributions to OpenSSL should at least
# get past these. Note that we only use these with C compilers, not with
# C++ compilers.
# -DPEDANTIC complements -pedantic and is meant to mask code that
# is not strictly standard-compliant and/or implementation-specific,
# e.g. inline assembly, disregards to alignment requirements, such
# that -pedantic would complain about. Incidentally -DPEDANTIC has
# to be used even in sanitized builds, because sanitizer too is
# supposed to and does take notice of non-standard behaviour. Then
# -pedantic with pre-C9x compiler would also complain about 'long
# long' not being supported. As 64-bit algorithms are common now,
# it grew impossible to resolve this without sizeable additional
# code, so we just tell compiler to be pedantic about everything
# but 'long long' type.
my @gcc_devteam_warn = qw(
-DPEDANTIC -pedantic -Wno-long-long -DUNUSEDRESULT_DEBUG
-Wall
-Wmissing-declarations
-Wextra
-Wno-unused-parameter
-Wno-missing-field-initializers
-Wswitch
-Wsign-compare
-Wshadow
-Wformat
-Wtype-limits
-Wundef
-Werror
-Wmissing-prototypes
-Wstrict-prototypes
);
# These are used in addition to $gcc_devteam_warn when the compiler is clang.
# TODO(openssl-team): fix problems and investigate if (at least) the
# following warnings can also be enabled:
# -Wcast-align
# -Wunreachable-code -- no, too ugly/compiler-specific
# -Wlanguage-extension-token -- no, we use asm()
# -Wunused-macros -- no, too tricky for BN and _XOPEN_SOURCE etc
# -Wextended-offsetof -- no, needed in CMS ASN1 code
my @clang_devteam_warn = qw(
-Wno-unknown-warning-option
-Wswitch-default
-Wno-parentheses-equality
-Wno-language-extension-token
-Wno-extended-offsetof
-Wconditional-uninitialized
-Wincompatible-pointer-types-discards-qualifiers
-Wmissing-variable-declarations
);
my @cl_devteam_warn = qw(
/WX
);
my $strict_warnings = 0;
# As for $BSDthreads. Idea is to maintain "collective" set of flags,
# which would cover all BSD flavors. -pthread applies to them all,
# but is treated differently. OpenBSD expands is as -D_POSIX_THREAD
# -lc_r, which is sufficient. FreeBSD 4.x expands it as -lc_r,
# which has to be accompanied by explicit -D_THREAD_SAFE and
# sometimes -D_REENTRANT. FreeBSD 5.x expands it as -lc_r, which
# seems to be sufficient?
our $BSDthreads="-pthread -D_THREAD_SAFE -D_REENTRANT";
#
# API compatibility name to version number mapping.
#
my $apitable = {
# This table expresses when API additions or changes can occur.
# The numbering used changes from 3.0 and on because we updated
# (solidified) our version numbering scheme at that point.
# From 3.0 and on, we internalise the given version number in decimal
# as MAJOR * 10000 + MINOR * 100 + 0
"3.0.0" => 30000,
"3.0" => 30000,
# Note that before 3.0, we didn't have the same version number scheme.
# Still, the numbering we use here covers what we need.
"1.1.1" => 10101,
"1.1.0" => 10100,
"1.0.2" => 10002,
"1.0.1" => 10001,
"1.0.0" => 10000,
"0.9.8" => 908,
};
# For OpenSSL::config::get_platform
my %guess_opts = ();
my $dryrun = 0;
our %table = ();
our %config = ();
our %withargs = ();
our $now_printing; # set to current entry's name in print_table_entry
# (todo: right thing would be to encapsulate name
# into %target [class] and make print_table_entry
# a method)
# Forward declarations ###############################################
# read_config(filename)
#
# Reads a configuration file and populates %table with the contents
# (which the configuration file places in %targets).
sub read_config;
# resolve_config(target)
#
# Resolves all the late evaluations, inheritances and so on for the
# chosen target and any target it inherits from.
sub resolve_config;
# Information collection #############################################
# Unified build supports separate build dir
my $srcdir = catdir(absolutedir(dirname($0))); # catdir ensures local syntax
my $blddir = catdir(absolutedir(".")); # catdir ensures local syntax
# File::Spec::Unix doesn't detect case insensitivity, so we make sure to
# check if the source and build directory are really the same, and make
# them so. This avoids all kinds of confusion later on.
# We must check @File::Spec::ISA rather than using File::Spec->isa() to
# know if File::Spec ended up loading File::Spec::Unix.
$srcdir = $blddir
if (grep(/::Unix$/, @File::Spec::ISA)
&& samedir($srcdir, $blddir));
my $dofile = abs2rel(catfile($srcdir, "util/dofile.pl"));
my $local_config_envname = 'OPENSSL_LOCAL_CONFIG_DIR';
$config{sourcedir} = abs2rel($srcdir, $blddir);
$config{builddir} = abs2rel($blddir, $blddir);
# echo -n 'holy hand grenade of antioch' | openssl sha256
$config{FIPSKEY} =
'f4556650ac31d35461610bac4ed81b1a181b2d8a43ea2854cbae22ca74560813';
# Collect reconfiguration information if needed
my @argvcopy=@ARGV;
if (grep /^reconf(igure)?$/, @argvcopy) {
die "reconfiguring with other arguments present isn't supported"
if scalar @argvcopy > 1;
if (-f "./configdata.pm") {
my $file = "./configdata.pm";
unless (my $return = do $file) {
die "couldn't parse $file: $@" if $@;
die "couldn't do $file: $!" unless defined $return;
die "couldn't run $file" unless $return;
}
@argvcopy = defined($configdata::config{perlargv}) ?
@{$configdata::config{perlargv}} : ();
die "Incorrect data to reconfigure, please do a normal configuration\n"
if (grep(/^reconf/,@argvcopy));
$config{perlenv} = $configdata::config{perlenv} // {};
} else {
die "Insufficient data to reconfigure, please do a normal configuration\n";
}
}
$config{perlargv} = [ @argvcopy ];
# Historical: if known directories in crypto/ have been removed, it means
# that those sub-systems are disabled.
# (the other option would be to removed them from the SUBDIRS statement in
# crypto/build.info)
# We reverse the input list for cosmetic purely reasons, to compensate that
# 'unshift' adds at the front of the list (i.e. in reverse input order).
foreach ( reverse sort( 'aes', 'aria', 'bf', 'camellia', 'cast', 'des', 'dh',
'dsa', 'ec', 'hmac', 'idea', 'md2', 'md5', 'mdc2',
'rc2', 'rc4', 'rc5', 'ripemd', 'seed', 'sha',
'sm2', 'sm3', 'sm4') ) {
unshift @argvcopy, "no-$_" if ! -d catdir($srcdir, 'crypto', $_);
}
# Collect version numbers
my %version = ();
collect_information(
collect_from_file(catfile($srcdir,'VERSION.dat')),
qr/\s*(\w+)\s*=\s*(.*?)\s*$/ =>
sub {
# Only define it if there is a value at all
if ($2 ne '') {
my $k = $1;
my $v = $2;
# Some values are quoted. Trim the quotes
$v = $1 if $v =~ /^"(.*)"$/;
$version{uc $k} = $v;
}
},
"OTHERWISE" =>
sub { die "Something wrong with this line:\n$_\nin $srcdir/VERSION.dat" },
);
$config{major} = $version{MAJOR} // 'unknown';
$config{minor} = $version{MINOR} // 'unknown';
$config{patch} = $version{PATCH} // 'unknown';
$config{prerelease} =
defined $version{PRE_RELEASE_TAG} ? "-$version{PRE_RELEASE_TAG}" : '';
$config{build_metadata} =
defined $version{BUILD_METADATA} ? "+$version{BUILD_METADATA}" : '';
$config{shlib_version} = $version{SHLIB_VERSION} // 'unknown';
$config{release_date} = $version{RELEASE_DATE} // 'xx XXX xxxx';
$config{version} = "$config{major}.$config{minor}.$config{patch}";
$config{full_version} = "$config{version}$config{prerelease}$config{build_metadata}";
die "erroneous version information in VERSION.dat: ",
"$config{version}, $config{shlib_version}\n"
unless (defined $version{MAJOR}
&& defined $version{MINOR}
&& defined $version{PATCH}
&& defined $version{SHLIB_VERSION});
# Collect target configurations
my $pattern = catfile(dirname($0), "Configurations", "*.conf");
foreach (sort glob($pattern)) {
&read_config($_);
}
if (defined env($local_config_envname)) {
if ($^O eq 'VMS') {
# VMS environment variables are logical names,
# which can be used as is
$pattern = $local_config_envname . ':' . '*.conf';
} else {
$pattern = catfile(env($local_config_envname), '*.conf');
}
foreach (sort glob($pattern)) {
&read_config($_);
}
}
# Save away perl command information
$config{perl_cmd} = $^X;
$config{perl_version} = $Config{version};
$config{perl_archname} = $Config{archname};
$config{prefix}="";
$config{openssldir}="";
$config{processor}="";
$config{libdir}="";
my $auto_threads=1; # enable threads automatically? true by default
my $default_ranlib;
# Known TLS and DTLS protocols
my @tls = qw(ssl3 tls1 tls1_1 tls1_2 tls1_3);
my @dtls = qw(dtls1 dtls1_2);
# Explicitly known options that are possible to disable. They can
# be regexps, and will be used like this: /^no-${option}$/
# For developers: keep it sorted alphabetically
my @disablables = (
"acvp-tests",
"afalgeng",
"aria",
"asan",
"asm",
"async",
+ "atexit",
"autoalginit",
"autoerrinit",
"autoload-config",
"bf",
"blake2",
"buildtest-c++",
"bulk",
"cached-fetch",
"camellia",
"capieng",
"cast",
"chacha",
"cmac",
"cmp",
"cms",
"comp",
"crypto-mdebug",
"ct",
"deprecated",
"des",
"devcryptoeng",
"dgram",
"dh",
"dsa",
"dso",
"dtls",
"dynamic-engine",
"ec",
"ec2m",
"ec_nistp_64_gcc_128",
"ecdh",
"ecdsa",
"egd",
"engine",
"err",
"external-tests",
"filenames",
"fips",
"fips-securitychecks",
"fuzz-afl",
"fuzz-libfuzzer",
"gost",
"idea",
"ktls",
"legacy",
"loadereng",
"makedepend",
"md2",
"md4",
"mdc2",
"module",
"msan",
"multiblock",
"nextprotoneg",
"ocb",
"ocsp",
"padlockeng",
"pic",
"pinshared",
"poly1305",
"posix-io",
"psk",
"rc2",
"rc4",
"rc5",
"rdrand",
"rfc3779",
"rmd160",
"scrypt",
"sctp",
"secure-memory",
"seed",
"shared",
"siphash",
"siv",
"sm2",
"sm3",
"sm4",
"sock",
"srp",
"srtp",
"sse2",
"ssl",
"ssl-trace",
"static-engine",
"stdio",
"tests",
"threads",
"tls",
"trace",
"ts",
"ubsan",
"ui-console",
"unit-test",
"uplink",
"weak-ssl-ciphers",
"whirlpool",
"zlib",
"zlib-dynamic",
);
foreach my $proto ((@tls, @dtls))
{
push(@disablables, $proto);
push(@disablables, "$proto-method") unless $proto eq "tls1_3";
}
# Internal disablables, for aliasing purposes. They serve no special
# purpose here, but allow scripts to get to know them through configdata.pm,
# where these are merged with @disablables.
# The actual aliasing mechanism is done via %disable_cascades
my @disablables_int = qw(
crmf
);
my %deprecated_disablables = (
"ssl2" => undef,
"buf-freelists" => undef,
"crypto-mdebug-backtrace" => undef,
"hw" => "hw", # causes cascade, but no macro
"hw-padlock" => "padlockeng",
"ripemd" => "rmd160",
"ui" => "ui-console",
"heartbeats" => undef,
);
# All of the following are disabled by default:
our %disabled = ( # "what" => "comment"
"fips" => "default",
"asan" => "default",
"buildtest-c++" => "default",
"crypto-mdebug" => "default",
"crypto-mdebug-backtrace" => "default",
"devcryptoeng" => "default",
"ec_nistp_64_gcc_128" => "default",
"egd" => "default",
"external-tests" => "default",
"fuzz-afl" => "default",
"fuzz-libfuzzer" => "default",
"ktls" => "default",
"md2" => "default",
"msan" => "default",
"rc5" => "default",
"sctp" => "default",
"ssl3" => "default",
"ssl3-method" => "default",
"trace" => "default",
"ubsan" => "default",
"unit-test" => "default",
"weak-ssl-ciphers" => "default",
"zlib" => "default",
"zlib-dynamic" => "default",
);
# Note: => pair form used for aesthetics, not to truly make a hash table
my @disable_cascades = (
# "what" => [ "cascade", ... ]
"bulk" => [ "shared", "dso",
"aria", "async", "autoload-config",
"blake2", "bf", "camellia", "cast", "chacha",
"cmac", "cms", "cmp", "comp", "ct",
"des", "dgram", "dh", "dsa",
"ec", "engine",
"filenames",
"idea", "ktls",
"md4", "multiblock", "nextprotoneg",
"ocsp", "ocb", "poly1305", "psk",
"rc2", "rc4", "rmd160",
"seed", "siphash", "siv",
"sm3", "sm4", "srp",
"srtp", "ssl3-method", "ssl-trace",
"ts", "ui-console", "whirlpool",
"fips-securitychecks" ],
sub { $config{processor} eq "386" }
=> [ "sse2" ],
"ssl" => [ "ssl3" ],
"ssl3-method" => [ "ssl3" ],
"zlib" => [ "zlib-dynamic" ],
"des" => [ "mdc2" ],
"ec" => [ "ec2m", "ecdsa", "ecdh", "sm2", "gost" ],
"dgram" => [ "dtls", "sctp" ],
"sock" => [ "dgram" ],
"dtls" => [ @dtls ],
sub { 0 == scalar grep { !$disabled{$_} } @dtls }
=> [ "dtls" ],
"tls" => [ @tls ],
sub { 0 == scalar grep { !$disabled{$_} } @tls }
=> [ "tls" ],
"crypto-mdebug" => [ "crypto-mdebug-backtrace" ],
"module" => [ "dynamic-engine", "fips" ],
# Without shared libraries, dynamic engines aren't possible.
# This is due to them having to link with libcrypto and register features
# using the ENGINE functionality, and since that relies on global tables,
# those *have* to be exacty the same as the ones accessed from the app,
# which cannot be guaranteed if shared libraries aren't present.
# (note that even with shared libraries, both the app and dynamic engines
# must be linked with the same library)
"shared" => [ "dynamic-engine", "uplink" ],
"dso" => [ "dynamic-engine", "module" ],
# Other modules don't necessarily have to link with libcrypto, so shared
# libraries do not have to be a condition to produce those.
# Without position independent code, there can be no shared libraries
# or modules.
"pic" => [ "shared", "module" ],
"engine" => [ "dynamic-engine", grep(/eng$/, @disablables) ],
"dynamic-engine" => [ "loadereng" ],
"hw" => [ "padlockeng" ],
# no-autoalginit is only useful when building non-shared
"autoalginit" => [ "shared", "apps", "fips" ],
"stdio" => [ "apps", "capieng", "egd" ],
"apps" => [ "tests" ],
"tests" => [ "external-tests" ],
"comp" => [ "zlib" ],
"sm3" => [ "sm2" ],
sub { !$disabled{"unit-test"} } => [ "heartbeats" ],
sub { !$disabled{"msan"} } => [ "asm" ],
"cmac" => [ "siv" ],
"legacy" => [ "md2" ],
"cmp" => [ "crmf" ],
"fips" => [ "fips-securitychecks", "acvp-tests" ],
"deprecated-3.0" => [ "engine", "srp" ]
);
# Avoid protocol support holes. Also disable all versions below N, if version
# N is disabled while N+1 is enabled.
#
my @list = (reverse @tls);
while ((my $first, my $second) = (shift @list, shift @list)) {
last unless @list;
push @disable_cascades, ( sub { !$disabled{$first} && $disabled{$second} }
=> [ @list ] );
unshift @list, $second;
}
my @list = (reverse @dtls);
while ((my $first, my $second) = (shift @list, shift @list)) {
last unless @list;
push @disable_cascades, ( sub { !$disabled{$first} && $disabled{$second} }
=> [ @list ] );
unshift @list, $second;
}
# Explicit "no-..." options will be collected in %disabled along with the defaults.
# To remove something from %disabled, use "enable-foo".
# For symmetry, "disable-foo" is a synonym for "no-foo".
# For the "make variables" CPPINCLUDES and CPPDEFINES, we support lists with
# platform specific list separators. Users from those platforms should
# recognise those separators from how you set up the PATH to find executables.
# The default is the Unix like separator, :, but as an exception, we also
# support the space as separator.
my $list_separator_re =
{ VMS => qr/(?<!\^),/,
MSWin32 => qr/(?<!\\);/ } -> {$^O} // qr/(?<!\\)[:\s]/;
# All the "make variables" we support
# Some get pre-populated for the sake of backward compatibility
# (we supported those before the change to "make variable" support.
my %user = (
AR => env('AR'),
ARFLAGS => [],
AS => undef,
ASFLAGS => [],
CC => env('CC'),
CFLAGS => [ env('CFLAGS') || () ],
CXX => env('CXX'),
CXXFLAGS => [ env('CXXFLAGS') || () ],
CPP => undef,
CPPFLAGS => [ env('CPPFLAGS') || () ], # -D, -I, -Wp,
CPPDEFINES => [], # Alternative for -D
CPPINCLUDES => [], # Alternative for -I
CROSS_COMPILE => env('CROSS_COMPILE'),
HASHBANGPERL=> env('HASHBANGPERL') || env('PERL'),
LD => undef,
LDFLAGS => [ env('LDFLAGS') || () ], # -L, -Wl,
LDLIBS => [ env('LDLIBS') || () ], # -l
MT => undef,
MTFLAGS => [],
PERL => env('PERL') || ($^O ne "VMS" ? $^X : "perl"),
RANLIB => env('RANLIB'),
RC => env('RC') || env('WINDRES'),
RCFLAGS => [ env('RCFLAGS') || () ],
RM => undef,
);
# Info about what "make variables" may be prefixed with the cross compiler
# prefix. This should NEVER mention any such variable with a list for value.
my @user_crossable = qw ( AR AS CC CXX CPP LD MT RANLIB RC );
# The same but for flags given as Configure options. These are *additional*
# input, as opposed to the VAR=string option that override the corresponding
# config target attributes
my %useradd = (
CPPDEFINES => [],
CPPINCLUDES => [],
CPPFLAGS => [],
CFLAGS => [],
CXXFLAGS => [],
LDFLAGS => [],
LDLIBS => [],
RCFLAGS => [],
);
my %user_synonyms = (
HASHBANGPERL=> 'PERL',
RC => 'WINDRES',
);
# Some target attributes have been renamed, this is the translation table
my %target_attr_translate =(
ar => 'AR',
as => 'AS',
cc => 'CC',
cxx => 'CXX',
cpp => 'CPP',
hashbangperl => 'HASHBANGPERL',
ld => 'LD',
mt => 'MT',
ranlib => 'RANLIB',
rc => 'RC',
rm => 'RM',
);
# Initialisers coming from 'config' scripts
$config{defines} = [ split(/$list_separator_re/, env('__CNF_CPPDEFINES')) ];
$config{includes} = [ split(/$list_separator_re/, env('__CNF_CPPINCLUDES')) ];
$config{cppflags} = [ env('__CNF_CPPFLAGS') || () ];
$config{cflags} = [ env('__CNF_CFLAGS') || () ];
$config{cxxflags} = [ env('__CNF_CXXFLAGS') || () ];
$config{lflags} = [ env('__CNF_LDFLAGS') || () ];
$config{ex_libs} = [ env('__CNF_LDLIBS') || () ];
$config{openssl_api_defines}=[];
$config{openssl_sys_defines}=[];
$config{openssl_feature_defines}=[];
$config{options}="";
$config{build_type} = "release";
my $target="";
my %cmdvars = (); # Stores FOO='blah' type arguments
my %unsupported_options = ();
my %deprecated_options = ();
# If you change this, update apps/version.c
my @known_seed_sources = qw(getrandom devrandom os egd none rdcpu librandom);
my @seed_sources = ();
while (@argvcopy)
{
$_ = shift @argvcopy;
# Support env variable assignments among the options
if (m|^(\w+)=(.+)?$|)
{
$cmdvars{$1} = $2;
# Every time a variable is given as a configuration argument,
# it acts as a reset if the variable.
if (exists $user{$1})
{
$user{$1} = ref $user{$1} eq "ARRAY" ? [] : undef;
}
#if (exists $useradd{$1})
# {
# $useradd{$1} = [];
# }
next;
}
# VMS is a case insensitive environment, and depending on settings
# out of our control, we may receive options uppercased. Let's
# downcase at least the part before any equal sign.
if ($^O eq "VMS")
{
s/^([^=]*)/lc($1)/e;
}
# some people just can't read the instructions, clang people have to...
s/^-no-(?!integrated-as)/no-/;
# rewrite some options in "enable-..." form
s /^-?-?shared$/enable-shared/;
s /^sctp$/enable-sctp/;
s /^threads$/enable-threads/;
s /^zlib$/enable-zlib/;
s /^zlib-dynamic$/enable-zlib-dynamic/;
s /^fips$/enable-fips/;
if (/^(no|disable|enable)-(.+)$/)
{
my $word = $2;
if ($word !~ m|hw(?:-.+)| # special treatment for hw regexp opt
&& !exists $deprecated_disablables{$word}
&& !grep { $word eq $_ } @disablables)
{
$unsupported_options{$_} = 1;
next;
}
}
if (/^no-(.+)$/ || /^disable-(.+)$/)
{
foreach my $proto ((@tls, @dtls))
{
if ($1 eq "$proto-method")
{
$disabled{"$proto"} = "option($proto-method)";
last;
}
}
if ($1 eq "dtls")
{
foreach my $proto (@dtls)
{
$disabled{$proto} = "option(dtls)";
}
$disabled{"dtls"} = "option(dtls)";
}
elsif ($1 eq "ssl")
{
# Last one of its kind
$disabled{"ssl3"} = "option(ssl)";
}
elsif ($1 eq "tls")
{
# XXX: Tests will fail if all SSL/TLS
# protocols are disabled.
foreach my $proto (@tls)
{
$disabled{$proto} = "option(tls)";
}
}
elsif ($1 eq "static-engine")
{
delete $disabled{"dynamic-engine"};
}
elsif ($1 eq "dynamic-engine")
{
$disabled{"dynamic-engine"} = "option";
}
elsif (exists $deprecated_disablables{$1})
{
$deprecated_options{$_} = 1;
if (defined $deprecated_disablables{$1})
{
$disabled{$deprecated_disablables{$1}} = "option";
}
}
elsif ($1 =~ m|hw(?:-.+)|) # deprecate hw options in regexp form
{
$deprecated_options{$_} = 1;
}
else
{
$disabled{$1} = "option";
}
# No longer an automatic choice
$auto_threads = 0 if ($1 eq "threads");
}
elsif (/^enable-(.+)$/)
{
if ($1 eq "static-engine")
{
$disabled{"dynamic-engine"} = "option";
}
elsif ($1 eq "dynamic-engine")
{
delete $disabled{"dynamic-engine"};
}
elsif ($1 eq "zlib-dynamic")
{
delete $disabled{"zlib"};
}
my $algo = $1;
delete $disabled{$algo};
# No longer an automatic choice
$auto_threads = 0 if ($1 eq "threads");
}
elsif (/^-d$/) # From older 'config'
{
$config{build_type} = "debug";
}
elsif (/^-v$/) # From older 'config'
{
$guess_opts{verbose} = 1;
}
elsif (/^-w$/)
{
$guess_opts{nowait} = 1;
}
elsif (/^-t$/) # From older 'config'
{
$dryrun = 1;
}
elsif (/^--strict-warnings$/)
{
# Pretend that our strict flags is a C flag, and replace it
# with the proper flags later on
push @{$useradd{CFLAGS}}, '--ossl-strict-warnings';
$strict_warnings=1;
}
elsif (/^--debug$/)
{
$config{build_type} = "debug";
}
elsif (/^--release$/)
{
$config{build_type} = "release";
}
elsif (/^386$/)
{ $config{processor}=386; }
elsif (/^rsaref$/)
{
# No RSAref support any more since it's not needed.
# The check for the option is there so scripts aren't
# broken
}
elsif (m|^[-+/]|)
{
if (/^--prefix=(.*)$/)
{
$config{prefix}=$1;
}
elsif (/^--api=(.*)$/)
{
my $api = $1;
die "Unknown API compatibility level $api"
unless defined $apitable->{$api};
$config{api}=$apitable->{$api};
}
elsif (/^--libdir=(.*)$/)
{
$config{libdir}=$1;
}
elsif (/^--openssldir=(.*)$/)
{
$config{openssldir}=$1;
}
elsif (/^--with-zlib-lib=(.*)$/)
{
$withargs{zlib_lib}=$1;
}
elsif (/^--with-zlib-include=(.*)$/)
{
$withargs{zlib_include}=$1;
}
elsif (/^--with-fuzzer-lib=(.*)$/)
{
$withargs{fuzzer_lib}=$1;
}
elsif (/^--with-fuzzer-include=(.*)$/)
{
$withargs{fuzzer_include}=$1;
}
elsif (/^--with-rand-seed=(.*)$/)
{
foreach my $x (split(m|,|, $1))
{
die "Unknown --with-rand-seed choice $x\n"
if ! grep { $x eq $_ } @known_seed_sources;
push @seed_sources, $x;
}
}
elsif (/^--fips-key=(.*)$/)
{
$user{FIPSKEY}=lc($1);
die "Non-hex character in FIPS key\n"
if $user{FIPSKEY} =~ /[^a-f0-9]/;
die "FIPS key must have even number of characters\n"
if length $1 & 1;
die "FIPS key too long (64 bytes max)\n"
if length $1 > 64;
}
elsif (/^--banner=(.*)$/)
{
$banner = $1 . "\n";
}
elsif (/^--cross-compile-prefix=(.*)$/)
{
$user{CROSS_COMPILE}=$1;
}
elsif (/^--config=(.*)$/)
{
read_config $1;
}
elsif (/^-l(.*)$/)
{
push @{$useradd{LDLIBS}}, $_;
}
elsif (/^-framework$/)
{
push @{$useradd{LDLIBS}}, $_, shift(@argvcopy);
}
elsif (/^-L(.*)$/ or /^-Wl,/)
{
push @{$useradd{LDFLAGS}}, $_;
}
elsif (/^-rpath$/ or /^-R$/)
# -rpath is the OSF1 rpath flag
# -R is the old Solaris rpath flag
{
my $rpath = shift(@argvcopy) || "";
$rpath .= " " if $rpath ne "";
push @{$useradd{LDFLAGS}}, $_, $rpath;
}
elsif (/^-static$/)
{
push @{$useradd{LDFLAGS}}, $_;
}
elsif (m|^[-/]D(.*)$|)
{
push @{$useradd{CPPDEFINES}}, $1;
}
elsif (m|^[-/]I(.*)$|)
{
push @{$useradd{CPPINCLUDES}}, $1;
}
elsif (/^-Wp,$/)
{
push @{$useradd{CPPFLAGS}}, $1;
}
else # common if (/^[-+]/), just pass down...
{
# Treat %xx as an ASCII code (e.g. replace %20 by a space character).
# This provides a simple way to pass options with arguments separated
# by spaces without quoting (e.g. -opt%20arg translates to -opt arg).
$_ =~ s/%([0-9a-f]{1,2})/chr(hex($1))/gei;
push @{$useradd{CFLAGS}}, $_;
push @{$useradd{CXXFLAGS}}, $_;
}
}
elsif (m|^/|)
{
# Treat %xx as an ASCII code (e.g. replace %20 by a space character).
# This provides a simple way to pass options with arguments separated
# by spaces without quoting (e.g. /opt%20arg translates to /opt arg).
$_ =~ s/%([0-9a-f]{1,2})/chr(hex($1))/gei;
push @{$useradd{CFLAGS}}, $_;
push @{$useradd{CXXFLAGS}}, $_;
}
else
{
die "target already defined - $target (offending arg: $_)\n" if ($target ne "");
$target=$_;
}
unless ($_ eq $target || /^no-/ || /^disable-/)
{
# "no-..." follows later after implied deactivations
# have been derived. (Don't take this too seriously,
# we really only write OPTIONS to the Makefile out of
# nostalgia.)
if ($config{options} eq "")
{ $config{options} = $_; }
else
{ $config{options} .= " ".$_; }
}
}
if (keys %deprecated_options)
{
warn "***** Deprecated options: ",
join(", ", keys %deprecated_options), "\n";
}
if (keys %unsupported_options)
{
die "***** Unsupported options: ",
join(", ", keys %unsupported_options), "\n";
}
# If any %useradd entry has been set, we must check that the "make
# variables" haven't been set. We start by checking of any %useradd entry
# is set.
if (grep { scalar @$_ > 0 } values %useradd) {
# Hash of env / make variables names. The possible values are:
# 1 - "make vars"
# 2 - %useradd entry set
# 3 - both set
my %detected_vars =
map { my $v = 0;
$v += 1 if $cmdvars{$_};
$v += 2 if @{$useradd{$_}};
$_ => $v }
keys %useradd;
# If any of the corresponding "make variables" is set, we error
if (grep { $_ & 1 } values %detected_vars) {
my $names = join(', ', grep { $detected_vars{$_} > 0 }
sort keys %detected_vars);
die <<"_____";
***** Mixing make variables and additional compiler/linker flags as
***** configure command line option is not permitted.
***** Affected make variables: $names
_____
}
}
# Check through all supported command line variables to see if any of them
# were set, and canonicalise the values we got. If no compiler or linker
# flag or anything else that affects %useradd was set, we also check the
# environment for values.
my $anyuseradd =
grep { defined $_ && (ref $_ ne 'ARRAY' || @$_) } values %useradd;
foreach (keys %user) {
my $value = $cmdvars{$_};
$value //= env($_) unless $anyuseradd;
$value //=
defined $user_synonyms{$_} ? $cmdvars{$user_synonyms{$_}} : undef;
$value //= defined $user_synonyms{$_} ? env($user_synonyms{$_}) : undef
unless $anyuseradd;
if (defined $value) {
if (ref $user{$_} eq 'ARRAY') {
if ($_ eq 'CPPDEFINES' || $_ eq 'CPPINCLUDES') {
$user{$_} = [ split /$list_separator_re/, $value ];
} else {
$user{$_} = [ $value ];
}
} elsif (!defined $user{$_}) {
$user{$_} = $value;
}
}
}
if (grep { /-rpath\b/ } ($user{LDFLAGS} ? @{$user{LDFLAGS}} : ())
&& !$disabled{shared}
&& !($disabled{asan} && $disabled{msan} && $disabled{ubsan})) {
die "***** Cannot simultaneously use -rpath, shared libraries, and\n",
"***** any of asan, msan or ubsan\n";
}
# If no target was given, try guessing.
unless ($target) {
my %system_config = OpenSSL::config::get_platform(%guess_opts, %user);
# The $system_config{disable} is used to populate %disabled with
# entries that aren't already there.
foreach ( @{$system_config{disable} // []} ) {
$disabled{$_} = 'system' unless defined $disabled{$_};
}
delete $system_config{disable};
# Override config entries with stuff from the guesser.
# It's assumed that this really is nothing new.
%config = ( %config, %system_config );
$target = $system_config{target};
}
sub disable {
my $disable_type = shift;
for (@_) {
$disabled{$_} = $disable_type;
}
my @tocheckfor = (@_ ? @_ : keys %disabled);
while (@tocheckfor) {
my %new_tocheckfor = ();
my @cascade_copy = (@disable_cascades);
while (@cascade_copy) {
my ($test, $descendents) =
(shift @cascade_copy, shift @cascade_copy);
if (ref($test) eq "CODE" ? $test->() : defined($disabled{$test})) {
foreach (grep { !defined($disabled{$_}) } @$descendents) {
$new_tocheckfor{$_} = 1; $disabled{$_} = "cascade";
}
}
}
@tocheckfor = (keys %new_tocheckfor);
}
}
disable(); # First cascade run
our $die = sub { die @_; };
if ($target eq "TABLE") {
local $die = sub { warn @_; };
foreach (sort keys %table) {
print_table_entry($_, "TABLE");
}
exit 0;
}
if ($target eq "LIST") {
foreach (sort keys %table) {
print $_,"\n" unless $table{$_}->{template};
}
exit 0;
}
if ($target eq "HASH") {
local $die = sub { warn @_; };
print "%table = (\n";
foreach (sort keys %table) {
print_table_entry($_, "HASH");
}
exit 0;
}
print "Configuring OpenSSL version $config{full_version} ";
print "for target $target\n";
if (scalar(@seed_sources) == 0) {
print "Using os-specific seed configuration\n";
push @seed_sources, 'os';
}
if (scalar(grep { $_ eq 'egd' } @seed_sources) > 0) {
delete $disabled{'egd'};
}
if (scalar(grep { $_ eq 'none' } @seed_sources) > 0) {
die "Cannot seed with none and anything else" if scalar(@seed_sources) > 1;
warn <<_____ if scalar(@seed_sources) == 1;
============================== WARNING ===============================
You have selected the --with-rand-seed=none option, which effectively
disables automatic reseeding of the OpenSSL random generator.
All operations depending on the random generator such as creating keys
will not work unless the random generator is seeded manually by the
application.
Please read the 'Note on random number generation' section in the
INSTALL.md instructions and the RAND_DRBG(7) manual page for more
details.
============================== WARNING ===============================
_____
}
push @{$config{openssl_feature_defines}},
map { (my $x = $_) =~ tr|[\-a-z]|[_A-Z]|; "OPENSSL_RAND_SEED_$x" }
@seed_sources;
# Backward compatibility?
if ($target =~ m/^CygWin32(-.*)$/) {
$target = "Cygwin".$1;
}
# Support for legacy targets having a name starting with 'debug-'
my ($d, $t) = $target =~ m/^(debug-)?(.*)$/;
if ($d) {
$config{build_type} = "debug";
# If we do not find debug-foo in the table, the target is set to foo.
if (!$table{$target}) {
$target = $t;
}
}
if ($target) {
# It's possible that we have different config targets for specific
# toolchains, so we try to detect them, and go for the plain config
# target if not.
my $found;
foreach ( ( "$target-$user{CC}", "$target", undef ) ) {
$found=$_ if $table{$_} && !$table{$_}->{template};
last if $found;
}
$target = $found;
} else {
# If we don't have a config target now, we try the C compiler as we
# fallback
my $cc = $user{CC} // 'cc';
$target = $cc if $table{$cc} && !$table{$cc}->{template};
}
&usage unless $target;
exit 0 if $dryrun; # From older 'config'
$config{target} = $target;
my %target = resolve_config($target);
foreach (keys %target_attr_translate) {
$target{$target_attr_translate{$_}} = $target{$_}
if $target{$_};
delete $target{$_};
}
%target = ( %{$table{DEFAULTS}}, %target );
my %conf_files = map { $_ => 1 } (@{$target{_conf_fname_int}});
$config{conf_files} = [ sort keys %conf_files ];
# Using sub disable within these loops may prove fragile, so we run
# a cascade afterwards
foreach my $feature (@{$target{disable}}) {
if (exists $deprecated_disablables{$feature}) {
warn "***** config $target disables deprecated feature $feature\n";
} elsif (!grep { $feature eq $_ } @disablables) {
die "***** config $target disables unknown feature $feature\n";
}
$disabled{$feature} = 'config';
}
foreach my $feature (@{$target{enable}}) {
if ("default" eq ($disabled{$feature} // "")) {
if (exists $deprecated_disablables{$feature}) {
warn "***** config $target enables deprecated feature $feature\n";
} elsif (!grep { $feature eq $_ } @disablables) {
die "***** config $target enables unknown feature $feature\n";
}
delete $disabled{$feature};
}
}
# If uplink_arch isn't defined, disable uplink
$disabled{uplink} = 'no uplink_arch' unless (defined $target{uplink_arch});
# If asm_arch isn't defined, disable asm
$disabled{asm} = 'no asm_arch' unless (defined $target{asm_arch});
disable(); # Run a cascade now
$target{CXXFLAGS}//=$target{CFLAGS} if $target{CXX};
$target{cxxflags}//=$target{cflags} if $target{CXX};
$target{exe_extension}=".exe" if ($config{target} eq "DJGPP");
$target{exe_extension}=".pm" if ($config{target} =~ /vos/);
# Fill %config with values from %user, and in case those are undefined or
# empty, use values from %target (acting as a default).
foreach (keys %user) {
my $ref_type = ref $user{$_};
# Temporary function. Takes an intended ref type (empty string or "ARRAY")
# and a value that's to be coerced into that type.
my $mkvalue = sub {
my $type = shift;
my $value = shift;
my $undef_p = shift;
die "Too many arguments for \$mkvalue" if @_;
while (ref $value eq 'CODE') {
$value = $value->();
}
if ($type eq 'ARRAY') {
return undef unless defined $value;
return undef if ref $value ne 'ARRAY' && !$value;
return undef if ref $value eq 'ARRAY' && !@$value;
return [ $value ] unless ref $value eq 'ARRAY';
}
return undef unless $value;
return $value;
};
$config{$_} =
$mkvalue->($ref_type, $user{$_})
|| $mkvalue->($ref_type, $target{$_});
delete $config{$_} unless defined $config{$_};
}
# Finish up %config by appending things the user gave us on the command line
# apart from "make variables"
foreach (keys %useradd) {
# The must all be lists, so we assert that here
die "internal error: \$useradd{$_} isn't an ARRAY\n"
unless ref $useradd{$_} eq 'ARRAY';
if (defined $config{$_}) {
push @{$config{$_}}, @{$useradd{$_}};
} else {
$config{$_} = [ @{$useradd{$_}} ];
}
}
# At this point, we can forget everything about %user and %useradd,
# because it's now all been merged into the corresponding $config entry
if ($config{prefix} && !$config{CROSS_COMPILE}) {
die "Directory given with --prefix MUST be absolute\n"
unless file_name_is_absolute($config{prefix});
}
if (grep { $_ =~ /(?:^|\s)-static(?:\s|$)/ } @{$config{LDFLAGS}}) {
disable('static', 'pic', 'threads');
}
# Allow overriding the build file name
$config{build_file} = env('BUILDFILE') || $target{build_file} || "Makefile";
# Make sure build_scheme is consistent.
$target{build_scheme} = [ $target{build_scheme} ]
if ref($target{build_scheme}) ne "ARRAY";
my ($builder, $builder_platform, @builder_opts) =
@{$target{build_scheme}};
foreach my $checker (($builder_platform."-".$config{build_file}."-checker.pm",
$builder_platform."-checker.pm")) {
my $checker_path = catfile($srcdir, "Configurations", $checker);
if (-f $checker_path) {
my $fn = $ENV{CONFIGURE_CHECKER_WARN}
? sub { warn $@; } : sub { die $@; };
if (! do $checker_path) {
if ($@) {
$fn->($@);
} elsif ($!) {
$fn->($!);
} else {
$fn->("The detected tools didn't match the platform\n");
}
}
last;
}
}
push @{$config{defines}}, "NDEBUG" if $config{build_type} eq "release";
if ($target =~ /^mingw/ && `$config{CC} --target-help 2>&1` =~ m/-mno-cygwin/m)
{
push @{$config{cflags}}, "-mno-cygwin";
push @{$config{cxxflags}}, "-mno-cygwin" if $config{CXX};
push @{$config{shared_ldflag}}, "-mno-cygwin";
}
if ($target =~ /linux.*-mips/ && !$disabled{asm}
&& !grep { $_ =~ /-m(ips|arch=)/ } (@{$config{CFLAGS}})) {
# minimally required architecture flags for assembly modules
my $value;
$value = '-mips2' if ($target =~ /mips32/);
$value = '-mips3' if ($target =~ /mips64/);
unshift @{$config{cflags}}, $value;
unshift @{$config{cxxflags}}, $value if $config{CXX};
}
# If threads aren't disabled, check how possible they are
unless ($disabled{threads}) {
if ($auto_threads) {
# Enabled by default, disable it forcibly if unavailable
if ($target{thread_scheme} eq "(unknown)") {
disable("unavailable", 'threads');
}
} else {
# The user chose to enable threads explicitly, let's see
# if there's a chance that's possible
if ($target{thread_scheme} eq "(unknown)") {
# If the user asked for "threads" and we don't have internal
# knowledge how to do it, [s]he is expected to provide any
# system-dependent compiler options that are necessary. We
# can't truly check that the given options are correct, but
# we expect the user to know what [s]He is doing.
if (!@{$config{CFLAGS}} && !@{$config{CPPDEFINES}}) {
die "You asked for multi-threading support, but didn't\n"
,"provide any system-specific compiler options\n";
}
}
}
}
# Find out if clang's sanitizers have been enabled with -fsanitize
# flags and ensure that the corresponding %disabled elements area
# removed to reflect that the sanitizers are indeed enabled.
my %detected_sanitizers = ();
foreach (grep /^-fsanitize=/, @{$config{CFLAGS} || []}) {
(my $checks = $_) =~ s/^-fsanitize=//;
foreach (split /,/, $checks) {
my $d = { address => 'asan',
undefined => 'ubsan',
memory => 'msan' } -> {$_};
next unless defined $d;
$detected_sanitizers{$d} = 1;
if (defined $disabled{$d}) {
die "***** Conflict between disabling $d and enabling $_ sanitizer"
if $disabled{$d} ne "default";
delete $disabled{$d};
}
}
}
# If threads still aren't disabled, add a C macro to ensure the source
# code knows about it. Any other flag is taken care of by the configs.
unless($disabled{threads}) {
push @{$config{openssl_feature_defines}}, "OPENSSL_THREADS";
}
my $no_shared_warn=0;
if (($target{shared_target} // '') eq "")
{
$no_shared_warn = 1
if (!$disabled{shared} || !$disabled{"dynamic-engine"});
disable('no-shared-target', 'pic');
}
if ($disabled{"dynamic-engine"}) {
$config{dynamic_engines} = 0;
} else {
$config{dynamic_engines} = 1;
}
unless ($disabled{asan} || defined $detected_sanitizers{asan}) {
push @{$config{cflags}}, "-fsanitize=address";
}
unless ($disabled{ubsan} || defined $detected_sanitizers{ubsan}) {
push @{$config{cflags}}, "-fsanitize=undefined", "-fno-sanitize-recover=all", "-DPEDANTIC";
}
unless ($disabled{msan} || defined $detected_sanitizers{msan}) {
push @{$config{cflags}}, "-fsanitize=memory";
}
unless ($disabled{"fuzz-libfuzzer"} && $disabled{"fuzz-afl"}
&& $disabled{asan} && $disabled{ubsan} && $disabled{msan}) {
push @{$config{cflags}}, "-fno-omit-frame-pointer", "-g";
push @{$config{cxxflags}}, "-fno-omit-frame-pointer", "-g" if $config{CXX};
}
#
# Platform fix-ups
#
# This saves the build files from having to check
if ($disabled{pic})
{
foreach (qw(shared_cflag shared_cxxflag shared_cppflag
shared_defines shared_includes shared_ldflag
module_cflags module_cxxflags module_cppflags
module_defines module_includes module_lflags))
{
delete $config{$_};
$target{$_} = "";
}
}
else
{
push @{$config{lib_defines}}, "OPENSSL_PIC";
}
if ($target{sys_id} ne "")
{
push @{$config{openssl_sys_defines}}, "OPENSSL_SYS_$target{sys_id}";
}
my %predefined_C = compiler_predefined($config{CROSS_COMPILE}.$config{CC});
my %predefined_CXX = $config{CXX}
? compiler_predefined($config{CROSS_COMPILE}.$config{CXX})
: ();
unless ($disabled{asm}) {
# big endian systems can use ELFv2 ABI
if ($target eq "linux-ppc64") {
$target{perlasm_scheme} = "linux64v2" if ($predefined_C{_CALL_ELF} == 2);
}
}
# Check for makedepend capabilities.
if (!$disabled{makedepend}) {
# If the attribute makedep_scheme is defined, then we assume that the
# config target and its associated build file are programmed to deal
# with it.
# If makedep_scheme is undefined, we go looking for GCC compatible
# dependency making, and if that's not available, we try to fall back
# on 'makedepend'.
if ($target{makedep_scheme}) {
$config{makedep_scheme} = $target{makedep_scheme};
# If the makedepcmd attribute is defined, copy it. If not, the
# build files will have to fend for themselves.
$config{makedepcmd} = $target{makedepcmd} if $target{makedepcmd};
} elsif (($predefined_C{__GNUC__} // -1) >= 3
&& !($predefined_C{__APPLE_CC__} && !$predefined_C{__clang__})) {
# We know that GNU C version 3 and up as well as all clang
# versions support dependency generation, but Xcode did not
# handle $cc -M before clang support (but claims __GNUC__ = 3)
$config{makedep_scheme} = 'gcc';
} else {
# In all other cases, we look for 'makedepend', and set the
# makedep_scheme value if we found it.
$config{makedepcmd} = which('makedepend');
$config{makedep_scheme} = 'makedepend' if $config{makedepcmd};
}
# If no depend scheme is set, we disable makedepend
disable('unavailable', 'makedepend') unless $config{makedep_scheme};
}
if (!$disabled{asm} && !$predefined_C{__MACH__} && $^O ne 'VMS') {
# probe for -Wa,--noexecstack option...
if ($predefined_C{__clang__}) {
# clang has builtin assembler, which doesn't recognize --help,
# but it apparently recognizes the option in question on all
# supported platforms even when it's meaningless. In other words
# probe would fail, but probed option always accepted...
push @{$config{cflags}}, "-Wa,--noexecstack", "-Qunused-arguments";
} else {
my $cc = $config{CROSS_COMPILE}.$config{CC};
open(PIPE, "$cc -Wa,--help -c -o null.$$.o -x assembler /dev/null 2>&1 |");
while(<PIPE>) {
if (m/--noexecstack/) {
push @{$config{cflags}}, "-Wa,--noexecstack";
last;
}
}
close(PIPE);
unlink("null.$$.o");
}
}
# Deal with bn_ops ###################################################
$config{bn_ll} =0;
my $def_int="unsigned int";
$config{rc4_int} =$def_int;
($config{b64l},$config{b64},$config{b32})=(0,0,1);
my $count = 0;
foreach (sort split(/\s+/,$target{bn_ops})) {
$count++ if /SIXTY_FOUR_BIT|SIXTY_FOUR_BIT_LONG|THIRTY_TWO_BIT/;
$config{bn_ll}=1 if $_ eq 'BN_LLONG';
$config{rc4_int}="unsigned char" if $_ eq 'RC4_CHAR';
($config{b64l},$config{b64},$config{b32})
=(0,1,0) if $_ eq 'SIXTY_FOUR_BIT';
($config{b64l},$config{b64},$config{b32})
=(1,0,0) if $_ eq 'SIXTY_FOUR_BIT_LONG';
($config{b64l},$config{b64},$config{b32})
=(0,0,1) if $_ eq 'THIRTY_TWO_BIT';
}
die "Exactly one of SIXTY_FOUR_BIT|SIXTY_FOUR_BIT_LONG|THIRTY_TWO_BIT can be set in bn_ops\n"
if $count > 1;
$config{api} = $config{major} * 10000 + $config{minor} * 100
unless $config{api};
foreach (keys %$apitable) {
$disabled{"deprecated-$_"} = "deprecation"
if $disabled{deprecated} && $config{api} >= $apitable->{$_};
}
disable(); # Run a cascade now
# Hack cflags for better warnings (dev option) #######################
# "Stringify" the C and C++ flags string. This permits it to be made part of
# a string and works as well on command lines.
$config{cflags} = [ map { (my $x = $_) =~ s/([\\\"])/\\$1/g; $x }
@{$config{cflags}} ];
$config{cxxflags} = [ map { (my $x = $_) =~ s/([\\\"])/\\$1/g; $x }
@{$config{cxxflags}} ] if $config{CXX};
$config{openssl_api_defines} = [
"OPENSSL_CONFIGURED_API=".$config{api},
];
my @strict_warnings_collection=();
if ($strict_warnings)
{
my $wopt;
my $gccver = $predefined_C{__GNUC__} // -1;
if ($gccver >= 4)
{
push @strict_warnings_collection, @gcc_devteam_warn;
push @strict_warnings_collection, @clang_devteam_warn
if (defined($predefined_C{__clang__}));
}
elsif ($config{target} =~ /^VC-/)
{
push @strict_warnings_collection, @cl_devteam_warn;
}
else
{
warn "WARNING --strict-warnings requires gcc[>=4] or gcc-alike, or MSVC"
}
}
$config{CFLAGS} = [ map { $_ eq '--ossl-strict-warnings'
? @strict_warnings_collection
: ( $_ ) }
@{$config{CFLAGS}} ];
unless ($disabled{afalgeng}) {
$config{afalgeng}="";
if (grep { $_ eq 'afalgeng' } @{$target{enable}}) {
my $minver = 4*10000 + 1*100 + 0;
if ($config{CROSS_COMPILE} eq "") {
my $verstr = `uname -r`;
my ($ma, $mi1, $mi2) = split("\\.", $verstr);
($mi2) = $mi2 =~ /(\d+)/;
my $ver = $ma*10000 + $mi1*100 + $mi2;
if ($ver < $minver) {
disable('too-old-kernel', 'afalgeng');
} else {
push @{$config{engdirs}}, "afalg";
}
} else {
disable('cross-compiling', 'afalgeng');
}
} else {
disable('not-linux', 'afalgeng');
}
}
unless ($disabled{devcryptoeng}) {
if ($target =~ m/^BSD/) {
my $maxver = 5*100 + 7;
my $sysstr = `uname -s`;
my $verstr = `uname -r`;
$sysstr =~ s|\R$||;
$verstr =~ s|\R$||;
my ($ma, $mi, @rest) = split m|\.|, $verstr;
my $ver = $ma*100 + $mi;
if ($sysstr eq 'OpenBSD' && $ver >= $maxver) {
disable('too-new-kernel', 'devcryptoeng');
}
}
}
unless ($disabled{ktls}) {
$config{ktls}="";
my $cc = $config{CROSS_COMPILE}.$config{CC};
if ($target =~ m/^linux/) {
system("printf '#include <sys/types.h>\n#include <linux/tls.h>' | $cc -E - >/dev/null 2>&1");
if ($? != 0) {
disable('too-old-kernel', 'ktls');
}
} elsif ($target =~ m/^BSD/) {
system("printf '#include <sys/types.h>\n#include <sys/ktls.h>' | $cc -E - >/dev/null 2>&1");
if ($? != 0) {
disable('too-old-freebsd', 'ktls');
}
} else {
disable('not-linux-or-freebsd', 'ktls');
}
}
push @{$config{openssl_other_defines}}, "OPENSSL_NO_KTLS" if ($disabled{ktls});
# Get the extra flags used when building shared libraries and modules. We
# do this late because some of them depend on %disabled.
# Make the flags to build DSOs the same as for shared libraries unless they
# are already defined
$target{module_cflags} = $target{shared_cflag} unless defined $target{module_cflags};
$target{module_cxxflags} = $target{shared_cxxflag} unless defined $target{module_cxxflags};
$target{module_ldflags} = $target{shared_ldflag} unless defined $target{module_ldflags};
{
my $shared_info_pl =
catfile(dirname($0), "Configurations", "shared-info.pl");
my %shared_info = read_eval_file($shared_info_pl);
push @{$target{_conf_fname_int}}, $shared_info_pl;
my $si = $target{shared_target};
while (ref $si ne "HASH") {
last if ! defined $si;
if (ref $si eq "CODE") {
$si = $si->();
} else {
$si = $shared_info{$si};
}
}
# Some of the 'shared_target' values don't have any entries in
# %shared_info. That's perfectly fine, AS LONG AS the build file
# template knows how to handle this. That is currently the case for
# Windows and VMS.
if (defined $si) {
# Just as above, copy certain shared_* attributes to the corresponding
# module_ attribute unless the latter is already defined
$si->{module_cflags} = $si->{shared_cflag} unless defined $si->{module_cflags};
$si->{module_cxxflags} = $si->{shared_cxxflag} unless defined $si->{module_cxxflags};
$si->{module_ldflags} = $si->{shared_ldflag} unless defined $si->{module_ldflags};
foreach (sort keys %$si) {
$target{$_} = defined $target{$_}
? add($si->{$_})->($target{$_})
: $si->{$_};
}
}
}
# ALL MODIFICATIONS TO %disabled, %config and %target MUST BE DONE FROM HERE ON
######################################################################
# Build up information for skipping certain directories depending on disabled
# features, as well as setting up macros for disabled features.
# This is a tentative database of directories to skip. Some entries may not
# correspond to anything real, but that's ok, they will simply be ignored.
# The actual processing of these entries is done in the build.info lookup
# loop further down.
#
# The key is a Unix formatted path in the source tree, the value is an index
# into %disabled_info, so any existing path gets added to a corresponding
# 'skipped' entry in there with the list of skipped directories.
my %skipdir = ();
my %disabled_info = (); # For configdata.pm
foreach my $what (sort keys %disabled) {
# There are deprecated disablables that translate to themselves.
# They cause disabling cascades, but should otherwise not regiter.
next if $deprecated_disablables{$what};
# The generated $disabled{"deprecated-x.y"} entries are special
# and treated properly elsewhere
next if $what =~ m|^deprecated-|;
$config{options} .= " no-$what";
if (!grep { $what eq $_ } ( 'buildtest-c++', 'fips', 'threads', 'shared',
'module', 'pic', 'dynamic-engine', 'makedepend',
'zlib-dynamic', 'zlib', 'sse2', 'legacy' )) {
(my $WHAT = uc $what) =~ s|-|_|g;
my $skipdir = $what;
# fix-up crypto/directory name(s)
$skipdir = "ripemd" if $what eq "rmd160";
$skipdir = "whrlpool" if $what eq "whirlpool";
my $macro = $disabled_info{$what}->{macro} = "OPENSSL_NO_$WHAT";
push @{$config{openssl_feature_defines}}, $macro;
$skipdir{engines} = $what if $what eq 'engine';
$skipdir{"crypto/$skipdir"} = $what
unless $what eq 'async' || $what eq 'err' || $what eq 'dso';
}
}
if ($disabled{"dynamic-engine"}) {
push @{$config{openssl_feature_defines}}, "OPENSSL_NO_DYNAMIC_ENGINE";
} else {
push @{$config{openssl_feature_defines}}, "OPENSSL_NO_STATIC_ENGINE";
}
# If we use the unified build, collect information from build.info files
my %unified_info = ();
my $buildinfo_debug = defined($ENV{CONFIGURE_DEBUG_BUILDINFO});
if ($builder eq "unified") {
use Text::Template 1.46;
sub cleandir {
my $base = shift;
my $dir = shift;
my $relativeto = shift || ".";
my $no_mkpath = shift // 0;
$dir = catdir($base,$dir) unless isabsolute($dir);
# Make sure the directories we're building in exists
mkpath($dir) unless $no_mkpath;
my $res = abs2rel(absolutedir($dir), rel2abs($relativeto));
#print STDERR "DEBUG[cleandir]: $dir , $base => $res\n";
return $res;
}
sub cleanfile {
my $base = shift;
my $file = shift;
my $relativeto = shift || ".";
my $no_mkpath = shift // 0;
$file = catfile($base,$file) unless isabsolute($file);
my $d = dirname($file);
my $f = basename($file);
# Make sure the directories we're building in exists
mkpath($d) unless $no_mkpath;
my $res = abs2rel(catfile(absolutedir($d), $f), rel2abs($relativeto));
#print STDERR "DEBUG[cleanfile]: $d , $f => $res\n";
return $res;
}
# Store the name of the template file we will build the build file from
# in %config. This may be useful for the build file itself.
my @build_file_template_names =
( $builder_platform."-".$config{build_file}.".tmpl",
$config{build_file}.".tmpl" );
my @build_file_templates = ();
# First, look in the user provided directory, if given
if (defined env($local_config_envname)) {
@build_file_templates =
map {
if ($^O eq 'VMS') {
# VMS environment variables are logical names,
# which can be used as is
$local_config_envname . ':' . $_;
} else {
catfile(env($local_config_envname), $_);
}
}
@build_file_template_names;
}
# Then, look in our standard directory
push @build_file_templates,
( map { cleanfile($srcdir, catfile("Configurations", $_), $blddir, 1) }
@build_file_template_names );
my $build_file_template;
for $_ (@build_file_templates) {
$build_file_template = $_;
last if -f $build_file_template;
$build_file_template = undef;
}
if (!defined $build_file_template) {
die "*** Couldn't find any of:\n", join("\n", @build_file_templates), "\n";
}
$config{build_file_templates}
= [ cleanfile($srcdir, catfile("Configurations", "common0.tmpl"),
$blddir, 1),
$build_file_template ];
my @build_dirs = ( [ ] ); # current directory
$config{build_infos} = [ ];
# We want to detect configdata.pm in the source tree, so we
# don't use it if the build tree is different.
my $src_configdata = cleanfile($srcdir, "configdata.pm", $blddir, 1);
# Any source file that we recognise is placed in this hash table, with
# the list of its intended destinations as value. When everything has
# been collected, there's a routine that checks that these source files
# exist, or if they are generated, that the generator exists.
my %check_exist = ();
my %check_generate = ();
my %ordinals = ();
while (@build_dirs) {
my @curd = @{shift @build_dirs};
my $sourced = catdir($srcdir, @curd);
my $buildd = catdir($blddir, @curd);
my $unixdir = join('/', @curd);
if (exists $skipdir{$unixdir}) {
my $what = $skipdir{$unixdir};
push @{$disabled_info{$what}->{skipped}}, catdir(@curd);
next;
}
mkpath($buildd);
my $f = 'build.info';
# The basic things we're trying to build
my @programs = ();
my @libraries = ();
my @modules = ();
my @scripts = ();
my %sources = ();
my %shared_sources = ();
my %includes = ();
my %defines = ();
my %depends = ();
my %generate = ();
my %imagedocs = ();
my %htmldocs = ();
my %mandocs = ();
# Support for $variablename in build.info files.
# Embedded perl code is the ultimate master, still. If its output
# contains a dollar sign, it had better be escaped, or it will be
# taken for a variable name prefix.
my %variables = ();
# Variable name syntax
my $variable_name_re = qr/(?P<VARIABLE>[[:alpha:]][[:alnum:]_]*)/;
# Value modifier syntaxes
my $variable_subst_re = qr/\/(?P<RE>(?:\\\/|.)*?)\/(?P<SUBST>.*?)/;
# Variable reference
my $variable_simple_re = qr/(?<!\\)\$${variable_name_re}/;
my $variable_w_mod_re =
qr/(?<!\\)\$\{${variable_name_re}(?P<MOD>(?:\\\/|.)*?)\}/;
# Tie it all together
my $variable_re = qr/${variable_simple_re}|${variable_w_mod_re}/;
my $expand_variables = sub {
my $value = '';
my $value_rest = shift;
if ($ENV{CONFIGURE_DEBUG_VARIABLE_EXPAND}) {
print STDERR
"DEBUG[\$expand_variables] Parsed '$value_rest' ...\n"
}
while ($value_rest =~ /${variable_re}/) {
# We must save important regexp values, because the next
# regexp clears them
my $mod = $+{MOD};
my $variable_value = $variables{$+{VARIABLE}};
$value_rest = $';
$value .= $`;
# Process modifier expressions, if present
if (defined $mod) {
if ($mod =~ /^${variable_subst_re}$/) {
my $re = $+{RE};
my $subst = $+{SUBST};
$variable_value =~ s/\Q$re\E/$subst/g;
if ($ENV{CONFIGURE_DEBUG_VARIABLE_EXPAND}) {
print STDERR
"DEBUG[\$expand_variables] ... and substituted ",
"'$re' with '$subst'\n";
}
}
}
$value .= $variable_value;
}
if ($ENV{CONFIGURE_DEBUG_VARIABLE_EXPAND}) {
print STDERR
"DEBUG[\$expand_variables] ... into: '$value$value_rest'\n";
}
return $value . $value_rest;
};
# Support for attributes in build.info files
my %attributes = ();
my $handle_attributes = sub {
my $attr_str = shift;
my $ref = shift;
my @goals = @_;
return unless defined $attr_str;
my @a = tokenize($attr_str, qr|\s*,\s*|);
foreach my $a (@a) {
my $ac = 1;
my $ak = $a;
my $av = 1;
if ($a =~ m|^(!)?(.*?)\s* = \s*(.*?)$|x) {
$ac = ! $1;
$ak = $2;
$av = $3;
}
foreach my $g (@goals) {
if ($ac) {
$$ref->{$g}->{$ak} = $av;
} else {
delete $$ref->{$g}->{$ak};
}
}
}
};
# Support for pushing values on multiple indexes of a given hash
# array.
my $push_to = sub {
my $valueref = shift;
my $index_str = shift; # May be undef or empty
my $attrref = shift; # May be undef
my $attr_str = shift;
my @values = @_;
if (defined $index_str) {
my @indexes = ( '' );
if ($index_str !~ m|^\s*$|) {
@indexes = tokenize($index_str);
}
foreach (@indexes) {
push @{$valueref->{$_}}, @values;
if (defined $attrref) {
$handle_attributes->($attr_str, \$$attrref->{$_},
@values);
}
}
} else {
push @$valueref, @values;
$handle_attributes->($attr_str, $attrref, @values)
if defined $attrref;
}
};
if ($buildinfo_debug) {
print STDERR "DEBUG: Reading ",catfile($sourced, $f),"\n";
}
push @{$config{build_infos}}, catfile(abs2rel($sourced, $blddir), $f);
my $template =
Text::Template->new(TYPE => 'FILE',
SOURCE => catfile($sourced, $f),
PREPEND => qq{use lib "$FindBin::Bin/util/perl";});
die "Something went wrong with $sourced/$f: $!\n" unless $template;
my @text =
split /^/m,
$template->fill_in(HASH => { config => \%config,
target => \%target,
disabled => \%disabled,
withargs => \%withargs,
builddir => abs2rel($buildd, $blddir),
sourcedir => abs2rel($sourced, $blddir),
buildtop => abs2rel($blddir, $blddir),
sourcetop => abs2rel($srcdir, $blddir) },
DELIMITERS => [ "{-", "-}" ]);
# The top item of this stack has the following values
# -2 positive already run and we found ELSE (following ELSIF should fail)
# -1 positive already run (skip until ENDIF)
# 0 negatives so far (if we're at a condition, check it)
# 1 last was positive (don't skip lines until next ELSE, ELSIF or ENDIF)
# 2 positive ELSE (following ELSIF should fail)
my @skip = ();
# A few useful generic regexps
my $index_re = qr/\[\s*(?P<INDEX>(?:\\.|.)*?)\s*\]/;
my $cond_re = qr/\[\s*(?P<COND>(?:\\.|.)*?)\s*\]/;
my $attribs_re = qr/(?:\{\s*(?P<ATTRIBS>(?:\\.|.)*?)\s*\})?/;
my $value_re = qr/(?P<VALUE>.*?)/;
collect_information(
collect_from_array([ @text ],
qr/\\$/ => sub { my $l1 = shift; my $l2 = shift;
$l1 =~ s/\\$//; $l1.$l2 }),
# Info we're looking for
qr/^\s* IF ${cond_re} \s*$/x
=> sub {
if (! @skip || $skip[$#skip] > 0) {
push @skip, !! $expand_variables->($+{COND});
} else {
push @skip, -1;
}
},
qr/^\s* ELSIF ${cond_re} \s*$/x
=> sub { die "ELSIF out of scope" if ! @skip;
die "ELSIF following ELSE" if abs($skip[$#skip]) == 2;
$skip[$#skip] = -1 if $skip[$#skip] != 0;
$skip[$#skip] = !! $expand_variables->($+{COND})
if $skip[$#skip] == 0; },
qr/^\s* ELSE \s*$/x
=> sub { die "ELSE out of scope" if ! @skip;
$skip[$#skip] = -2 if $skip[$#skip] != 0;
$skip[$#skip] = 2 if $skip[$#skip] == 0; },
qr/^\s* ENDIF \s*$/x
=> sub { die "ENDIF out of scope" if ! @skip;
pop @skip; },
qr/^\s* ${variable_re} \s* = \s* ${value_re} \s* $/x
=> sub {
if (!@skip || $skip[$#skip] > 0) {
$variables{$+{VARIABLE}} = $expand_variables->($+{VALUE});
}
},
qr/^\s* SUBDIRS \s* = \s* ${value_re} \s* $/x
=> sub {
if (!@skip || $skip[$#skip] > 0) {
foreach (tokenize($expand_variables->($+{VALUE}))) {
push @build_dirs, [ @curd, splitdir($_, 1) ];
}
}
},
qr/^\s* PROGRAMS ${attribs_re} \s* = \s* ${value_re} \s* $/x
=> sub { $push_to->(\@programs, undef,
\$attributes{programs}, $+{ATTRIBS},
tokenize($expand_variables->($+{VALUE})))
if !@skip || $skip[$#skip] > 0; },
qr/^\s* LIBS ${attribs_re} \s* = \s* ${value_re} \s* $/x
=> sub { $push_to->(\@libraries, undef,
\$attributes{libraries}, $+{ATTRIBS},
tokenize($expand_variables->($+{VALUE})))
if !@skip || $skip[$#skip] > 0; },
qr/^\s* MODULES ${attribs_re} \s* = \s* ${value_re} \s* $/x
=> sub { $push_to->(\@modules, undef,
\$attributes{modules}, $+{ATTRIBS},
tokenize($expand_variables->($+{VALUE})))
if !@skip || $skip[$#skip] > 0; },
qr/^\s* SCRIPTS ${attribs_re} \s* = \s* ${value_re} \s* $/x
=> sub { $push_to->(\@scripts, undef,
\$attributes{scripts}, $+{ATTRIBS},
tokenize($expand_variables->($+{VALUE})))
if !@skip || $skip[$#skip] > 0; },
qr/^\s* IMAGEDOCS ${index_re} \s* = \s* ${value_re} \s* $/x
=> sub { $push_to->(\%imagedocs, $expand_variables->($+{INDEX}),
undef, undef,
tokenize($expand_variables->($+{VALUE})))
if !@skip || $skip[$#skip] > 0; },
qr/^\s* HTMLDOCS ${index_re} \s* = \s* ${value_re} \s* $/x
=> sub { $push_to->(\%htmldocs, $expand_variables->($+{INDEX}),
undef, undef,
tokenize($expand_variables->($+{VALUE})))
if !@skip || $skip[$#skip] > 0; },
qr/^\s* MANDOCS ${index_re} \s* = \s* ${value_re} \s* $/x
=> sub { $push_to->(\%mandocs, $expand_variables->($+{INDEX}),
undef, undef,
tokenize($expand_variables->($+{VALUE})))
if !@skip || $skip[$#skip] > 0; },
qr/^\s* SOURCE ${index_re} ${attribs_re} \s* = \s* ${value_re} \s* $/x
=> sub { $push_to->(\%sources, $expand_variables->($+{INDEX}),
\$attributes{sources}, $+{ATTRIBS},
tokenize($expand_variables->($+{VALUE})))
if !@skip || $skip[$#skip] > 0; },
qr/^\s* SHARED_SOURCE ${index_re} ${attribs_re} \s* = \s* ${value_re} \s* $/x
=> sub { $push_to->(\%shared_sources, $expand_variables->($+{INDEX}),
\$attributes{sources}, $+{ATTRIBS},
tokenize($expand_variables->($+{VALUE})))
if !@skip || $skip[$#skip] > 0; },
qr/^\s* INCLUDE ${index_re} \s* = \s* ${value_re} \s* $/x
=> sub { $push_to->(\%includes, $expand_variables->($+{INDEX}),
undef, undef,
tokenize($expand_variables->($+{VALUE})))
if !@skip || $skip[$#skip] > 0; },
qr/^\s* DEFINE ${index_re} \s* = \s* ${value_re} \s* $/x
=> sub { $push_to->(\%defines, $expand_variables->($+{INDEX}),
undef, undef,
tokenize($expand_variables->($+{VALUE})))
if !@skip || $skip[$#skip] > 0; },
qr/^\s* DEPEND ${index_re} ${attribs_re} \s* = \s* ${value_re} \s* $/x
=> sub { $push_to->(\%depends, $expand_variables->($+{INDEX}),
\$attributes{depends}, $+{ATTRIBS},
tokenize($expand_variables->($+{VALUE})))
if !@skip || $skip[$#skip] > 0; },
qr/^\s* GENERATE ${index_re} ${attribs_re} \s* = \s* ${value_re} \s* $/x
=> sub { $push_to->(\%generate, $expand_variables->($+{INDEX}),
\$attributes{generate}, $+{ATTRIBS},
$expand_variables->($+{VALUE}))
if !@skip || $skip[$#skip] > 0; },
qr/^\s* (?:\#.*)? $/x => sub { },
"OTHERWISE" => sub { die "Something wrong with this line:\n$_\nat $sourced/$f" },
"BEFORE" => sub {
if ($buildinfo_debug) {
print STDERR "DEBUG: Parsing ",join(" ", @_),"\n";
print STDERR "DEBUG: ... before parsing, skip stack is ",join(" ", map { int($_) } @skip),"\n";
}
},
"AFTER" => sub {
if ($buildinfo_debug) {
print STDERR "DEBUG: .... after parsing, skip stack is ",join(" ", map { int($_) } @skip),"\n";
}
},
);
die "runaway IF?" if (@skip);
if (grep { defined $attributes{modules}->{$_}->{engine} } keys %attributes
and !$config{dynamic_engines}) {
die <<"EOF"
ENGINES can only be used if configured with 'dynamic-engine'.
This is usually a fault in a build.info file.
EOF
}
{
my %infos = ( programs => [ @programs ],
libraries => [ @libraries ],
modules => [ @modules ],
scripts => [ @scripts ] );
foreach my $k (keys %infos) {
foreach (@{$infos{$k}}) {
my $item = cleanfile($buildd, $_, $blddir);
$unified_info{$k}->{$item} = 1;
# Fix up associated attributes
$unified_info{attributes}->{$k}->{$item} =
$attributes{$k}->{$_}
if defined $attributes{$k}->{$_};
}
}
}
# Check that we haven't defined any library as both shared and
# explicitly static. That is forbidden.
my @doubles = ();
foreach (grep /\.a$/, keys %{$unified_info{libraries}}) {
(my $l = $_) =~ s/\.a$//;
push @doubles, $l if defined $unified_info{libraries}->{$l};
}
die "these libraries are both explicitly static and shared:\n ",
join(" ", @doubles), "\n"
if @doubles;
foreach (keys %sources) {
my $dest = $_;
my $ddest = cleanfile($buildd, $_, $blddir);
foreach (@{$sources{$dest}}) {
my $s = cleanfile($sourced, $_, $blddir, 1);
# If it's generated or we simply don't find it in the source
# tree, we assume it's in the build tree.
if ($s eq $src_configdata || $generate{$_} || ! -f $s) {
$s = cleanfile($buildd, $_, $blddir);
}
my $o = $_;
# We recognise C++, C and asm files
if ($s =~ /\.(cc|cpp|c|s|S)$/) {
push @{$check_exist{$s}}, $ddest;
$o =~ s/\.[csS]$/.o/; # C and assembler
$o =~ s/\.(cc|cpp)$/_cc.o/; # C++
$o = cleanfile($buildd, $o, $blddir);
$unified_info{sources}->{$ddest}->{$o} = -1;
$unified_info{sources}->{$o}->{$s} = -1;
} elsif ($s =~ /\.rc$/) {
# We also recognise resource files
push @{$check_exist{$s}}, $ddest;
$o =~ s/\.rc$/.res/; # Resource configuration
$o = cleanfile($buildd, $o, $blddir);
$unified_info{sources}->{$ddest}->{$o} = -1;
$unified_info{sources}->{$o}->{$s} = -1;
} else {
push @{$check_exist{$s}}, $ddest;
$unified_info{sources}->{$ddest}->{$s} = 1;
}
# Fix up associated attributes
if ($o ne $_) {
$unified_info{attributes}->{sources}->{$ddest}->{$o} =
$unified_info{attributes}->{sources}->{$o}->{$s} =
$attributes{sources}->{$dest}->{$_}
if defined $attributes{sources}->{$dest}->{$_};
} else {
$unified_info{attributes}->{sources}->{$ddest}->{$s} =
$attributes{sources}->{$dest}->{$_}
if defined $attributes{sources}->{$dest}->{$_};
}
}
}
foreach (keys %shared_sources) {
my $dest = $_;
my $ddest = cleanfile($buildd, $_, $blddir);
foreach (@{$shared_sources{$dest}}) {
my $s = cleanfile($sourced, $_, $blddir, 1);
# If it's generated or we simply don't find it in the source
# tree, we assume it's in the build tree.
if ($s eq $src_configdata || $generate{$_} || ! -f $s) {
$s = cleanfile($buildd, $_, $blddir);
}
my $o = $_;
if ($s =~ /\.(cc|cpp|c|s|S)$/) {
# We recognise C++, C and asm files
push @{$check_exist{$s}}, $ddest;
$o =~ s/\.[csS]$/.o/; # C and assembler
$o =~ s/\.(cc|cpp)$/_cc.o/; # C++
$o = cleanfile($buildd, $o, $blddir);
$unified_info{shared_sources}->{$ddest}->{$o} = -1;
$unified_info{sources}->{$o}->{$s} = -1;
} elsif ($s =~ /\.rc$/) {
# We also recognise resource files
push @{$check_exist{$s}}, $ddest;
$o =~ s/\.rc$/.res/; # Resource configuration
$o = cleanfile($buildd, $o, $blddir);
$unified_info{shared_sources}->{$ddest}->{$o} = -1;
$unified_info{sources}->{$o}->{$s} = -1;
} elsif ($s =~ /\.ld$/) {
# We also recognise linker scripts (or corresponding)
# We know they are generated files
push @{$check_exist{$s}}, $ddest;
$o = cleanfile($buildd, $_, $blddir);
$unified_info{shared_sources}->{$ddest}->{$o} = 1;
} else {
die "unrecognised source file type for shared library: $s\n";
}
# Fix up associated attributes
if ($o ne $_) {
$unified_info{attributes}->{shared_sources}->{$ddest}->{$o} =
$unified_info{attributes}->{sources}->{$o}->{$s} =
$attributes{sources}->{$dest}->{$_}
if defined $attributes{sources}->{$dest}->{$_};
} else {
$unified_info{attributes}->{shared_sources}->{$ddest}->{$o} =
$attributes{sources}->{$dest}->{$_}
if defined $attributes{sources}->{$dest}->{$_};
}
}
}
foreach (keys %generate) {
my $dest = $_;
my $ddest = cleanfile($buildd, $_, $blddir);
die "more than one generator for $dest: "
,join(" ", @{$generate{$_}}),"\n"
if scalar @{$generate{$_}} > 1;
my @generator = split /\s+/, $generate{$dest}->[0];
my $gen = $generator[0];
$generator[0] = cleanfile($sourced, $gen, $blddir, 1);
# If the generator is itself generated, it's in the build tree
if ($generate{$gen} || ! -f $generator[0]) {
$generator[0] = cleanfile($buildd, $gen, $blddir);
}
$check_generate{$ddest}->{$generator[0]}++;
$unified_info{generate}->{$ddest} = [ @generator ];
# Fix up associated attributes
$unified_info{attributes}->{generate}->{$ddest} =
$attributes{generate}->{$dest}->{$gen}
if defined $attributes{generate}->{$dest}->{$gen};
}
foreach (keys %depends) {
my $dest = $_;
my $ddest = $dest;
if ($dest =~ /^\|(.*)\|$/) {
# Collect the raw target
$unified_info{targets}->{$1} = 1;
$ddest = $1;
} elsif ($dest eq '') {
$ddest = '';
} else {
$ddest = cleanfile($sourced, $_, $blddir, 1);
# If the destination doesn't exist in source, it can only be
# a generated file in the build tree.
if ($ddest eq $src_configdata || ! -f $ddest) {
$ddest = cleanfile($buildd, $_, $blddir);
}
}
foreach (@{$depends{$dest}}) {
my $d = cleanfile($sourced, $_, $blddir, 1);
my $d2 = cleanfile($buildd, $_, $blddir);
# If we know it's generated, or assume it is because we can't
# find it in the source tree, we set file we depend on to be
# in the build tree rather than the source tree.
if ($d eq $src_configdata
|| (grep { $d2 eq $_ }
keys %{$unified_info{generate}})
|| ! -f $d) {
$d = $d2;
}
$unified_info{depends}->{$ddest}->{$d} = 1;
# Fix up associated attributes
$unified_info{attributes}->{depends}->{$ddest}->{$d} =
$attributes{depends}->{$dest}->{$_}
if defined $attributes{depends}->{$dest}->{$_};
}
}
foreach (keys %includes) {
my $dest = $_;
my $ddest = cleanfile($sourced, $_, $blddir, 1);
# If the destination doesn't exist in source, it can only be
# a generated file in the build tree.
if ($ddest eq $src_configdata || ! -f $ddest) {
$ddest = cleanfile($buildd, $_, $blddir);
}
foreach (@{$includes{$dest}}) {
my $is = cleandir($sourced, $_, $blddir, 1);
my $ib = cleandir($buildd, $_, $blddir);
push @{$unified_info{includes}->{$ddest}->{source}}, $is
unless grep { $_ eq $is } @{$unified_info{includes}->{$ddest}->{source}};
push @{$unified_info{includes}->{$ddest}->{build}}, $ib
unless grep { $_ eq $ib } @{$unified_info{includes}->{$ddest}->{build}};
}
}
foreach my $dest (keys %defines) {
my $ddest;
if ($dest ne "") {
$ddest = cleanfile($sourced, $dest, $blddir, 1);
# If the destination doesn't exist in source, it can only
# be a generated file in the build tree.
if (! -f $ddest) {
$ddest = cleanfile($buildd, $dest, $blddir);
}
}
foreach my $v (@{$defines{$dest}}) {
$v =~ m|^([^=]*)(=.*)?$|;
die "0 length macro name not permitted\n" if $1 eq "";
if ($dest ne "") {
die "$1 defined more than once\n"
if defined $unified_info{defines}->{$ddest}->{$1};
$unified_info{defines}->{$ddest}->{$1} = $2;
} else {
die "$1 defined more than once\n"
if grep { $v eq $_ } @{$config{defines}};
push @{$config{defines}}, $v;
}
}
}
foreach my $section (keys %imagedocs) {
foreach (@{$imagedocs{$section}}) {
my $imagedocs = cleanfile($buildd, $_, $blddir);
$unified_info{imagedocs}->{$section}->{$imagedocs} = 1;
}
}
foreach my $section (keys %htmldocs) {
foreach (@{$htmldocs{$section}}) {
my $htmldocs = cleanfile($buildd, $_, $blddir);
$unified_info{htmldocs}->{$section}->{$htmldocs} = 1;
}
}
foreach my $section (keys %mandocs) {
foreach (@{$mandocs{$section}}) {
my $mandocs = cleanfile($buildd, $_, $blddir);
$unified_info{mandocs}->{$section}->{$mandocs} = 1;
}
}
}
my $ordinals_text = join(', ', sort keys %ordinals);
warn <<"EOF" if $ordinals_text;
WARNING: ORDINALS were specified for $ordinals_text
They are ignored and should be replaced with a combination of GENERATE,
DEPEND and SHARED_SOURCE.
EOF
# Check that each generated file is only generated once
my $ambiguous_generation = 0;
foreach (sort keys %check_generate) {
my @generators = sort keys %{$check_generate{$_}};
my $generators_txt = join(', ', @generators);
if (scalar @generators > 1) {
warn "$_ is GENERATEd by more than one generator ($generators_txt)\n";
$ambiguous_generation++;
}
if ($check_generate{$_}->{$generators[0]} > 1) {
warn "INFO: $_ has more than one GENERATE declaration (same generator)\n"
}
}
die "There are ambiguous source file generations\n"
if $ambiguous_generation > 0;
# All given source files should exist, or if generated, their
# generator should exist. This loop ensures this is true.
my $missing = 0;
foreach my $orig (sort keys %check_exist) {
foreach my $dest (@{$check_exist{$orig}}) {
if ($orig ne $src_configdata) {
if ($orig =~ /\.a$/) {
# Static library names may be used as sources, so we
# need to detect those and give them special treatment.
unless (grep { $_ eq $orig }
keys %{$unified_info{libraries}}) {
warn "$orig is given as source for $dest, but no such library is built\n";
$missing++;
}
} else {
# A source may be generated, and its generator may be
# generated as well. We therefore loop to dig out the
# first generator.
my $gen = $orig;
while (my @next = keys %{$check_generate{$gen}}) {
$gen = $next[0];
}
if (! -f $gen) {
if ($gen ne $orig) {
$missing++;
warn "$orig is given as source for $dest, but its generator (leading to $gen) is missing\n";
} else {
$missing++;
warn "$orig is given as source for $dest, but is missing\n";
}
}
}
}
}
}
die "There are files missing\n" if $missing > 0;
# Go through the sources of all libraries and check that the same basename
# doesn't appear more than once. Some static library archivers depend on
# them being unique.
{
my $err = 0;
foreach my $prod (keys %{$unified_info{libraries}}) {
my @prod_sources =
map { keys %{$unified_info{sources}->{$_}} }
keys %{$unified_info{sources}->{$prod}};
my %srccnt = ();
# Count how many times a given each source basename
# appears for each product.
foreach my $src (@prod_sources) {
$srccnt{basename $src}++;
}
foreach my $src (keys %srccnt) {
if ((my $cnt = $srccnt{$src}) > 1) {
print STDERR "$src appears $cnt times for the product $prod\n";
$err++
}
}
}
die if $err > 0;
}
# Massage the result
# If we depend on a header file or a perl module, add an inclusion of
# its directory to allow smoothe inclusion
foreach my $dest (keys %{$unified_info{depends}}) {
next if $dest eq "";
foreach my $d (keys %{$unified_info{depends}->{$dest}}) {
next unless $d =~ /\.(h|pm)$/;
my $i = dirname($d);
my $spot =
$d eq "configdata.pm" || defined($unified_info{generate}->{$d})
? 'build' : 'source';
push @{$unified_info{includes}->{$dest}->{$spot}}, $i
unless grep { $_ eq $i } @{$unified_info{includes}->{$dest}->{$spot}};
}
}
# Go through all intermediary files and change their names to something that
# reflects what they will be built for. Note that for some source files,
# this leads to duplicate object files because they are used multiple times.
# the goal is to rename all object files according to this scheme:
# {productname}-{midfix}-{origobjname}.[o|res]
# the {midfix} is a keyword indicating the type of product, which is mostly
# valuable for libraries since they come in two forms.
#
# This also reorganises the {sources} and {shared_sources} so that the
# former only contains ALL object files that are supposed to end up in
# static libraries and programs, while the latter contains ALL object files
# that are supposed to end up in shared libraries and DSOs.
# The main reason for having two different source structures is to allow
# the same name to be used for the static and the shared variants of a
# library.
{
# Take copies so we don't get interference from added stuff
my %unified_copy = ();
foreach (('sources', 'shared_sources')) {
$unified_copy{$_} = { %{$unified_info{$_}} }
if defined($unified_info{$_});
delete $unified_info{$_};
}
foreach my $prodtype (('programs', 'libraries', 'modules', 'scripts')) {
# $intent serves multi purposes:
# - give a prefix for the new object files names
# - in the case of libraries, rearrange the object files so static
# libraries use the 'sources' structure exclusively, while shared
# libraries use the 'shared_sources' structure exclusively.
my $intent = {
programs => { bin => { src => [ 'sources' ],
dst => 'sources' } },
libraries => { lib => { src => [ 'sources' ],
dst => 'sources' },
shlib => { prodselect =>
sub { grep !/\.a$/, @_ },
src => [ 'sources',
'shared_sources' ],
dst => 'shared_sources' } },
modules => { dso => { src => [ 'sources' ],
dst => 'sources' } },
scripts => { script => { src => [ 'sources' ],
dst => 'sources' } }
} -> {$prodtype};
foreach my $kind (keys %$intent) {
next if ($intent->{$kind}->{dst} eq 'shared_sources'
&& $disabled{shared});
my @src = @{$intent->{$kind}->{src}};
my $dst = $intent->{$kind}->{dst};
my $prodselect = $intent->{$kind}->{prodselect} // sub { @_ };
foreach my $prod ($prodselect->(keys %{$unified_info{$prodtype}})) {
# %prod_sources has all applicable objects as keys, and
# their corresponding sources as values
my %prod_sources =
map { $_ => [ keys %{$unified_copy{sources}->{$_}} ] }
map { keys %{$unified_copy{$_}->{$prod}} }
@src;
foreach (keys %prod_sources) {
# Only affect object files and resource files,
# the others simply get a new value
# (+1 instead of -1)
if ($_ =~ /\.(o|res)$/) {
(my $prodname = $prod) =~ s|\.a$||;
my $newobj =
catfile(dirname($_),
basename($prodname)
. '-' . $kind
. '-' . basename($_));
$unified_info{$dst}->{$prod}->{$newobj} = 1;
foreach my $src (@{$prod_sources{$_}}) {
$unified_info{sources}->{$newobj}->{$src} = 1;
# Adjust source attributes
my $attrs = $unified_info{attributes}->{sources};
if (defined $attrs->{$prod}
&& defined $attrs->{$prod}->{$_}) {
$attrs->{$prod}->{$newobj} =
$attrs->{$prod}->{$_};
delete $attrs->{$prod}->{$_};
}
foreach my $objsrc (keys %{$attrs->{$_} // {}}) {
$attrs->{$newobj}->{$objsrc} =
$attrs->{$_}->{$objsrc};
delete $attrs->{$_}->{$objsrc};
}
}
# Adjust dependencies
foreach my $deps (keys %{$unified_info{depends}->{$_}}) {
$unified_info{depends}->{$_}->{$deps} = -1;
$unified_info{depends}->{$newobj}->{$deps} = 1;
}
# Adjust includes
foreach my $k (('source', 'build')) {
next unless
defined($unified_info{includes}->{$_}->{$k});
my @incs = @{$unified_info{includes}->{$_}->{$k}};
$unified_info{includes}->{$newobj}->{$k} = [ @incs ];
}
} else {
$unified_info{$dst}->{$prod}->{$_} = 1;
}
}
}
}
}
}
# At this point, we have a number of sources with the value -1. They
# aren't part of the local build and are probably meant for a different
# platform, and can therefore be cleaned away. That happens when making
# %unified_info more efficient below.
### Make unified_info a bit more efficient
# One level structures
foreach (("programs", "libraries", "modules", "scripts", "targets")) {
$unified_info{$_} = [ sort keys %{$unified_info{$_}} ];
}
# Two level structures
foreach my $l1 (("sources", "shared_sources", "ldadd", "depends",
"imagedocs", "htmldocs", "mandocs")) {
foreach my $l2 (sort keys %{$unified_info{$l1}}) {
my @items =
sort
grep { $unified_info{$l1}->{$l2}->{$_} > 0 }
keys %{$unified_info{$l1}->{$l2}};
if (@items) {
$unified_info{$l1}->{$l2} = [ @items ];
} else {
delete $unified_info{$l1}->{$l2};
}
}
}
# Defines
foreach my $dest (sort keys %{$unified_info{defines}}) {
$unified_info{defines}->{$dest}
= [ map { $_.$unified_info{defines}->{$dest}->{$_} }
sort keys %{$unified_info{defines}->{$dest}} ];
}
# Includes
foreach my $dest (sort keys %{$unified_info{includes}}) {
if (defined($unified_info{includes}->{$dest}->{build})) {
my @source_includes = ();
@source_includes = ( @{$unified_info{includes}->{$dest}->{source}} )
if defined($unified_info{includes}->{$dest}->{source});
$unified_info{includes}->{$dest} =
[ @{$unified_info{includes}->{$dest}->{build}} ];
foreach my $inc (@source_includes) {
push @{$unified_info{includes}->{$dest}}, $inc
unless grep { $_ eq $inc } @{$unified_info{includes}->{$dest}};
}
} elsif (defined($unified_info{includes}->{$dest}->{source})) {
$unified_info{includes}->{$dest} =
[ @{$unified_info{includes}->{$dest}->{source}} ];
} else {
delete $unified_info{includes}->{$dest};
}
}
# For convenience collect information regarding directories where
# files are generated, those generated files and the end product
# they end up in where applicable. Then, add build rules for those
# directories
my %loopinfo = ( "lib" => [ @{$unified_info{libraries}} ],
"dso" => [ @{$unified_info{modules}} ],
"bin" => [ @{$unified_info{programs}} ],
"script" => [ @{$unified_info{scripts}} ],
"docs" => [ (map { @{$unified_info{imagedocs}->{$_} // []} }
keys %{$unified_info{imagedocs} // {}}),
(map { @{$unified_info{htmldocs}->{$_} // []} }
keys %{$unified_info{htmldocs} // {}}),
(map { @{$unified_info{mandocs}->{$_} // []} }
keys %{$unified_info{mandocs} // {}}) ] );
foreach my $type (sort keys %loopinfo) {
foreach my $product (@{$loopinfo{$type}}) {
my %dirs = ();
my $pd = dirname($product);
foreach (@{$unified_info{sources}->{$product} // []},
@{$unified_info{shared_sources}->{$product} // []}) {
my $d = dirname($_);
# We don't want to create targets for source directories
# when building out of source
next if ($config{sourcedir} ne $config{builddir}
&& $d =~ m|^\Q$config{sourcedir}\E|);
# We already have a "test" target, and the current directory
# is just silly to make a target for
next if $d eq "test" || $d eq ".";
$dirs{$d} = 1;
push @{$unified_info{dirinfo}->{$d}->{deps}}, $_
if $d ne $pd;
}
foreach (sort keys %dirs) {
push @{$unified_info{dirinfo}->{$_}->{products}->{$type}},
$product;
}
}
}
}
# For the schemes that need it, we provide the old *_obj configs
# from the *_asm_obj ones
foreach (grep /_(asm|aux)_src$/, keys %target) {
my $src = $_;
(my $obj = $_) =~ s/_(asm|aux)_src$/_obj/;
$target{$obj} = $target{$src};
$target{$obj} =~ s/\.[csS]\b/.o/g; # C and assembler
$target{$obj} =~ s/\.(cc|cpp)\b/_cc.o/g; # C++
}
# Write down our configuration where it fits #########################
my %template_vars = (
config => \%config,
target => \%target,
disablables => \@disablables,
disablables_int => \@disablables_int,
disabled => \%disabled,
withargs => \%withargs,
unified_info => \%unified_info,
tls => \@tls,
dtls => \@dtls,
makevars => [ sort keys %user ],
disabled_info => \%disabled_info,
user_crossable => \@user_crossable,
);
my $configdata_outname = 'configdata.pm';
open CONFIGDATA, ">$configdata_outname.new"
or die "Trying to create $configdata_outname.new: $!";
my $configdata_tmplname = cleanfile($srcdir, "configdata.pm.in", $blddir, 1);
my $configdata_tmpl =
OpenSSL::Template->new(TYPE => 'FILE', SOURCE => $configdata_tmplname);
$configdata_tmpl->fill_in(
FILENAME => $configdata_tmplname,
OUTPUT => \*CONFIGDATA,
HASH => { %template_vars,
autowarntext => [
'WARNING: do not edit!',
"Generated by Configure from $configdata_tmplname",
] }
) or die $Text::Template::ERROR;
close CONFIGDATA;
rename "$configdata_outname.new", $configdata_outname;
if ($builder_platform eq 'unix') {
my $mode = (0755 & ~umask);
chmod $mode, 'configdata.pm'
or warn sprintf("WARNING: Couldn't change mode for 'configdata.pm' to 0%03o: %s\n",$mode,$!);
}
print "Created $configdata_outname\n";
print "Running $configdata_outname\n";
my $perlcmd = (quotify("maybeshell", $config{PERL}))[0];
my $cmd = "$perlcmd $configdata_outname";
#print STDERR "DEBUG[run_dofile]: \$cmd = $cmd\n";
system($cmd);
exit 1 if $? != 0;
$SIG{__DIE__} = $orig_death_handler;
print <<"EOF" if ($disabled{threads} eq "unavailable");
The library could not be configured for supporting multi-threaded
applications as the compiler options required on this system are not known.
See file INSTALL.md for details if you need multi-threading.
EOF
print <<"EOF" if ($no_shared_warn);
The options 'shared', 'pic' and 'dynamic-engine' aren't supported on this
platform, so we will pretend you gave the option 'no-pic', which also disables
'shared' and 'dynamic-engine'. If you know how to implement shared libraries
or position independent code, please let us know (but please first make sure
you have tried with a current version of OpenSSL).
EOF
print $banner;
exit(0);
######################################################################
#
# Helpers and utility functions
#
# Death handler, to print a helpful message in case of failure #######
#
sub death_handler {
die @_ if $^S; # To prevent the added message in eval blocks
my $build_file = $config{build_file} // "build file";
my @message = ( <<"_____", @_ );
Failure! $build_file wasn't produced.
Please read INSTALL.md and associated NOTES-* files. You may also have to
look over your available compiler tool chain or change your configuration.
_____
# Dying is terminal, so it's ok to reset the signal handler here.
$SIG{__DIE__} = $orig_death_handler;
die @message;
}
# Configuration file reading #########################################
# Note: All of the helper functions are for lazy evaluation. They all
# return a CODE ref, which will return the intended value when evaluated.
# Thus, whenever there's mention of a returned value, it's about that
# intended value.
# Helper function to implement conditional value variants, with a default
# plus additional values based on the value of $config{build_type}.
# Arguments are given in hash table form:
#
# picker(default => "Basic string: ",
# debug => "debug",
# release => "release")
#
# When configuring with --debug, the resulting string will be
# "Basic string: debug", and when not, it will be "Basic string: release"
#
# This can be used to create variants of sets of flags according to the
# build type:
#
# cflags => picker(default => "-Wall",
# debug => "-g -O0",
# release => "-O3")
#
sub picker {
my %opts = @_;
return sub { add($opts{default} || (),
$opts{$config{build_type}} || ())->(); }
}
# Helper function to combine several values of different types into one.
# This is useful if you want to combine a string with the result of a
# lazy function, such as:
#
# cflags => combine("-Wall", sub { $disabled{zlib} ? () : "-DZLIB" })
#
sub combine {
my @stuff = @_;
return sub { add(@stuff)->(); }
}
# Helper function to implement conditional values depending on the value
# of $disabled{threads}. Can be used as follows:
#
# cflags => combine("-Wall", threads("-pthread"))
#
sub threads {
my @flags = @_;
return sub { add($disabled{threads} ? () : @flags)->(); }
}
sub shared {
my @flags = @_;
return sub { add($disabled{shared} ? () : @flags)->(); }
}
our $add_called = 0;
# Helper function to implement adding values to already existing configuration
# values. It handles elements that are ARRAYs, CODEs and scalars
sub _add {
my $separator = shift;
# If there's any ARRAY in the collection of values OR the separator
# is undef, we will return an ARRAY of combined values, otherwise a
# string of joined values with $separator as the separator.
my $found_array = !defined($separator);
my @values =
map {
my $res = $_;
while (ref($res) eq "CODE") {
$res = $res->();
}
if (defined($res)) {
if (ref($res) eq "ARRAY") {
$found_array = 1;
@$res;
} else {
$res;
}
} else {
();
}
} (@_);
$add_called = 1;
if ($found_array) {
[ @values ];
} else {
join($separator, grep { defined($_) && $_ ne "" } @values);
}
}
sub add_before {
my $separator = " ";
if (ref($_[$#_]) eq "HASH") {
my $opts = pop;
$separator = $opts->{separator};
}
my @x = @_;
sub { _add($separator, @x, @_) };
}
sub add {
my $separator = " ";
if (ref($_[$#_]) eq "HASH") {
my $opts = pop;
$separator = $opts->{separator};
}
my @x = @_;
sub { _add($separator, @_, @x) };
}
sub read_eval_file {
my $fname = shift;
my $content;
my @result;
open F, "< $fname" or die "Can't open '$fname': $!\n";
{
undef local $/;
$content = <F>;
}
close F;
{
local $@;
@result = ( eval $content );
warn $@ if $@;
}
return wantarray ? @result : $result[0];
}
# configuration reader, evaluates the input file as a perl script and expects
# it to fill %targets with target configurations. Those are then added to
# %table.
sub read_config {
my $fname = shift;
my %targets;
{
# Protect certain tables from tampering
local %table = ();
%targets = read_eval_file($fname);
}
my %preexisting = ();
foreach (sort keys %targets) {
$preexisting{$_} = 1 if $table{$_};
}
die <<"EOF",
The following config targets from $fname
shadow pre-existing config targets with the same name:
EOF
map { " $_\n" } sort keys %preexisting
if %preexisting;
# For each target, check that it's configured with a hash table.
foreach (keys %targets) {
if (ref($targets{$_}) ne "HASH") {
if (ref($targets{$_}) eq "") {
warn "Deprecated target configuration for $_, ignoring...\n";
} else {
warn "Misconfigured target configuration for $_ (should be a hash table), ignoring...\n";
}
delete $targets{$_};
} else {
$targets{$_}->{_conf_fname_int} = add([ $fname ]);
}
}
%table = (%table, %targets);
}
# configuration resolver. Will only resolve all the lazy evaluation
# codeblocks for the chosen target and all those it inherits from,
# recursively
sub resolve_config {
my $target = shift;
my @breadcrumbs = @_;
# my $extra_checks = defined($ENV{CONFIGURE_EXTRA_CHECKS});
if (grep { $_ eq $target } @breadcrumbs) {
die "inherit_from loop! target backtrace:\n "
,$target,"\n ",join("\n ", @breadcrumbs),"\n";
}
if (!defined($table{$target})) {
warn "Warning! target $target doesn't exist!\n";
return ();
}
# Recurse through all inheritances. They will be resolved on the
# fly, so when this operation is done, they will all just be a
# bunch of attributes with string values.
# What we get here, though, are keys with references to lists of
# the combined values of them all. We will deal with lists after
# this stage is done.
my %combined_inheritance = ();
if ($table{$target}->{inherit_from}) {
my @inherit_from =
map { ref($_) eq "CODE" ? $_->() : $_ } @{$table{$target}->{inherit_from}};
foreach (@inherit_from) {
my %inherited_config = resolve_config($_, $target, @breadcrumbs);
# 'template' is a marker that's considered private to
# the config that had it.
delete $inherited_config{template};
foreach (keys %inherited_config) {
if (!$combined_inheritance{$_}) {
$combined_inheritance{$_} = [];
}
push @{$combined_inheritance{$_}}, $inherited_config{$_};
}
}
}
# We won't need inherit_from in this target any more, since we've
# resolved all the inheritances that lead to this
delete $table{$target}->{inherit_from};
# Now is the time to deal with those lists. Here's the place to
# decide what shall be done with those lists, all based on the
# values of the target we're currently dealing with.
# - If a value is a coderef, it will be executed with the list of
# inherited values as arguments.
# - If the corresponding key doesn't have a value at all or is the
# empty string, the inherited value list will be run through the
# default combiner (below), and the result becomes this target's
# value.
# - Otherwise, this target's value is assumed to be a string that
# will simply override the inherited list of values.
my $default_combiner = add();
my %all_keys =
map { $_ => 1 } (keys %combined_inheritance,
keys %{$table{$target}});
sub process_values {
my $object = shift;
my $inherited = shift; # Always a [ list ]
my $target = shift;
my $entry = shift;
$add_called = 0;
while(ref($object) eq "CODE") {
$object = $object->(@$inherited);
}
if (!defined($object)) {
return ();
}
elsif (ref($object) eq "ARRAY") {
local $add_called; # To make sure recursive calls don't affect it
return [ map { process_values($_, $inherited, $target, $entry) }
@$object ];
} elsif (ref($object) eq "") {
return $object;
} else {
die "cannot handle reference type ",ref($object)
," found in target ",$target," -> ",$entry,"\n";
}
}
foreach my $key (sort keys %all_keys) {
my $previous = $combined_inheritance{$key};
# Current target doesn't have a value for the current key?
# Assign it the default combiner, the rest of this loop body
# will handle it just like any other coderef.
if (!exists $table{$target}->{$key}) {
$table{$target}->{$key} = $default_combiner;
}
$table{$target}->{$key} = process_values($table{$target}->{$key},
$combined_inheritance{$key},
$target, $key);
unless(defined($table{$target}->{$key})) {
delete $table{$target}->{$key};
}
# if ($extra_checks &&
# $previous && !($add_called || $previous ~~ $table{$target}->{$key})) {
# warn "$key got replaced in $target\n";
# }
}
# Finally done, return the result.
return %{$table{$target}};
}
sub usage
{
print STDERR $usage;
print STDERR "\npick os/compiler from:\n";
my $j=0;
my $i;
my $k=0;
foreach $i (sort keys %table)
{
next if $table{$i}->{template};
next if $i =~ /^debug/;
$k += length($i) + 1;
if ($k > 78)
{
print STDERR "\n";
$k=length($i);
}
print STDERR $i . " ";
}
foreach $i (sort keys %table)
{
next if $table{$i}->{template};
next if $i !~ /^debug/;
$k += length($i) + 1;
if ($k > 78)
{
print STDERR "\n";
$k=length($i);
}
print STDERR $i . " ";
}
exit(1);
}
sub compiler_predefined {
state %predefined;
my $cc = shift;
return () if $^O eq 'VMS';
die 'compiler_predefined called without a compiler command'
unless $cc;
if (! $predefined{$cc}) {
$predefined{$cc} = {};
# collect compiler pre-defines from gcc or gcc-alike...
open(PIPE, "$cc -dM -E -x c /dev/null 2>&1 |");
while (my $l = <PIPE>) {
$l =~ m/^#define\s+(\w+(?:\(\w+\))?)(?:\s+(.+))?/ or last;
$predefined{$cc}->{$1} = $2 // '';
}
close(PIPE);
}
return %{$predefined{$cc}};
}
sub which
{
my ($name)=@_;
if (eval { require IPC::Cmd; 1; }) {
IPC::Cmd->import();
return scalar IPC::Cmd::can_run($name);
} else {
# if there is $directories component in splitpath,
# then it's not something to test with $PATH...
return $name if (File::Spec->splitpath($name))[1];
foreach (File::Spec->path()) {
my $fullpath = catfile($_, "$name$target{exe_extension}");
if (-f $fullpath and -x $fullpath) {
return $fullpath;
}
}
}
}
sub env
{
my $name = shift;
my %opts = @_;
unless ($opts{cacheonly}) {
# Note that if $ENV{$name} doesn't exist or is undefined,
# $config{perlenv}->{$name} will be created with the value
# undef. This is intentional.
$config{perlenv}->{$name} = $ENV{$name}
if ! exists $config{perlenv}->{$name};
}
return $config{perlenv}->{$name};
}
# Configuration printer ##############################################
sub print_table_entry
{
local $now_printing = shift;
my %target = resolve_config($now_printing);
my $type = shift;
# Don't print the templates
return if $target{template};
my @sequence = (
"sys_id",
"cpp",
"cppflags",
"defines",
"includes",
"cc",
"cflags",
"ld",
"lflags",
"loutflag",
"ex_libs",
"bn_ops",
"enable",
"disable",
"poly1035_asm_src",
"thread_scheme",
"perlasm_scheme",
"dso_scheme",
"shared_target",
"shared_cflag",
"shared_defines",
"shared_ldflag",
"shared_rcflag",
"shared_extension",
"dso_extension",
"obj_extension",
"exe_extension",
"ranlib",
"ar",
"arflags",
"aroutflag",
"rc",
"rcflags",
"rcoutflag",
"mt",
"mtflags",
"mtinflag",
"mtoutflag",
"multilib",
"build_scheme",
);
if ($type eq "TABLE") {
print "\n";
print "*** $now_printing\n";
foreach (@sequence) {
if (ref($target{$_}) eq "ARRAY") {
printf "\$%-12s = %s\n", $_, join(" ", @{$target{$_}});
} else {
printf "\$%-12s = %s\n", $_, $target{$_};
}
}
} elsif ($type eq "HASH") {
my $largest =
length((sort { length($a) <=> length($b) } @sequence)[-1]);
print " '$now_printing' => {\n";
foreach (@sequence) {
if ($target{$_}) {
if (ref($target{$_}) eq "ARRAY") {
print " '",$_,"'"," " x ($largest - length($_))," => [ ",join(", ", map { "'$_'" } @{$target{$_}})," ],\n";
} else {
print " '",$_,"'"," " x ($largest - length($_))," => '",$target{$_},"',\n";
}
}
}
print " },\n";
}
}
# Utility routines ###################################################
# On VMS, if the given file is a logical name, File::Spec::Functions
# will consider it an absolute path. There are cases when we want a
# purely syntactic check without checking the environment.
sub isabsolute {
my $file = shift;
# On non-platforms, we just use file_name_is_absolute().
return file_name_is_absolute($file) unless $^O eq "VMS";
# If the file spec includes a device or a directory spec,
# file_name_is_absolute() is perfectly safe.
return file_name_is_absolute($file) if $file =~ m|[:\[]|;
# Here, we know the given file spec isn't absolute
return 0;
}
# Makes a directory absolute and cleans out /../ in paths like foo/../bar
# On some platforms, this uses rel2abs(), while on others, realpath() is used.
# realpath() requires that at least all path components except the last is an
# existing directory. On VMS, the last component of the directory spec must
# exist.
sub absolutedir {
my $dir = shift;
# realpath() is quite buggy on VMS. It uses LIB$FID_TO_NAME, which
# will return the volume name for the device, no matter what. Also,
# it will return an incorrect directory spec if the argument is a
# directory that doesn't exist.
if ($^O eq "VMS") {
return rel2abs($dir);
}
# We use realpath() on Unix, since no other will properly clean out
# a directory spec.
use Cwd qw/realpath/;
return realpath($dir);
}
# Check if all paths are one and the same, using stat. They must both exist
# We need this for the cases when File::Spec doesn't detect case insensitivity
# (File::Spec::Unix assumes case sensitivity)
sub samedir {
die "samedir expects two arguments\n" unless scalar @_ == 2;
my @stat0 = stat($_[0]); # First argument
my @stat1 = stat($_[1]); # Second argument
die "Couldn't stat $_[0]" unless @stat0;
die "Couldn't stat $_[1]" unless @stat1;
# Compare device number
return 0 unless ($stat0[0] == $stat1[0]);
# Compare "inode". The perl manual recommends comparing as
# string rather than as number.
return 0 unless ($stat0[1] eq $stat1[1]);
return 1; # All the same
}
sub quotify {
my %processors = (
perl => sub { my $x = shift;
$x =~ s/([\\\$\@"])/\\$1/g;
return '"'.$x.'"'; },
maybeshell => sub { my $x = shift;
(my $y = $x) =~ s/([\\\"])/\\$1/g;
if ($x ne $y || $x =~ m|\s|) {
return '"'.$y.'"';
} else {
return $x;
}
},
);
my $for = shift;
my $processor =
defined($processors{$for}) ? $processors{$for} : sub { shift; };
return map { $processor->($_); } @_;
}
# collect_from_file($filename, $line_concat_cond_re, $line_concat)
# $filename is a file name to read from
# $line_concat_cond_re is a regexp detecting a line continuation ending
# $line_concat is a CODEref that takes care of concatenating two lines
sub collect_from_file {
my $filename = shift;
my $line_concat_cond_re = shift;
my $line_concat = shift;
open my $fh, $filename || die "unable to read $filename: $!\n";
return sub {
my $saved_line = "";
$_ = "";
while (<$fh>) {
s|\R$||;
if (defined $line_concat) {
$_ = $line_concat->($saved_line, $_);
$saved_line = "";
}
if (defined $line_concat_cond_re && /$line_concat_cond_re/) {
$saved_line = $_;
next;
}
return $_;
}
die "$filename ending with continuation line\n" if $_;
close $fh;
return undef;
}
}
# collect_from_array($array, $line_concat_cond_re, $line_concat)
# $array is an ARRAYref of lines
# $line_concat_cond_re is a regexp detecting a line continuation ending
# $line_concat is a CODEref that takes care of concatenating two lines
sub collect_from_array {
my $array = shift;
my $line_concat_cond_re = shift;
my $line_concat = shift;
my @array = (@$array);
return sub {
my $saved_line = "";
$_ = "";
while (defined($_ = shift @array)) {
s|\R$||;
if (defined $line_concat) {
$_ = $line_concat->($saved_line, $_);
$saved_line = "";
}
if (defined $line_concat_cond_re && /$line_concat_cond_re/) {
$saved_line = $_;
next;
}
return $_;
}
die "input text ending with continuation line\n" if $_;
return undef;
}
}
# collect_information($lineiterator, $line_continue, $regexp => $CODEref, ...)
# $lineiterator is a CODEref that delivers one line at a time.
# All following arguments are regex/CODEref pairs, where the regexp detects a
# line and the CODEref does something with the result of the regexp.
sub collect_information {
my $lineiterator = shift;
my %collectors = @_;
while(defined($_ = $lineiterator->())) {
s|\R$||;
my $found = 0;
if ($collectors{"BEFORE"}) {
$collectors{"BEFORE"}->($_);
}
foreach my $re (keys %collectors) {
if ($re !~ /^OTHERWISE|BEFORE|AFTER$/ && /$re/) {
$collectors{$re}->($lineiterator);
$found = 1;
};
}
if ($collectors{"OTHERWISE"}) {
$collectors{"OTHERWISE"}->($lineiterator, $_)
unless $found || !defined $collectors{"OTHERWISE"};
}
if ($collectors{"AFTER"}) {
$collectors{"AFTER"}->($_);
}
}
}
# tokenize($line)
# tokenize($line,$separator)
# $line is a line of text to split up into tokens
# $separator [optional] is a regular expression that separates the tokens,
# the default being spaces. Do not use quotes of any kind as separators,
# that will give undefined results.
# Returns a list of tokens.
#
# Tokens are divided by separator (spaces by default). If the tokens include
# the separators, they have to be quoted with single or double quotes.
# Double quotes inside a double quoted token must be escaped. Escaping is done
# with backslash.
# Basically, the same quoting rules apply for " and ' as in any
# Unix shell.
sub tokenize {
my $line = my $debug_line = shift;
my $separator = shift // qr|\s+|;
my @result = ();
if ($ENV{CONFIGURE_DEBUG_TOKENIZE}) {
print STDERR "DEBUG[tokenize]: \$separator = $separator\n";
}
while ($line =~ s|^${separator}||, $line ne "") {
my $token = "";
again:
$line =~ m/^(.*?)(${separator}|"|'|$)/;
$token .= $1;
$line = $2.$';
if ($line =~ m/^"((?:[^"\\]+|\\.)*)"/) {
$token .= $1;
$line = $';
goto again;
} elsif ($line =~ m/^'([^']*)'/) {
$token .= $1;
$line = $';
goto again;
}
push @result, $token;
}
if ($ENV{CONFIGURE_DEBUG_TOKENIZE}) {
print STDERR "DEBUG[tokenize]: Parsed '$debug_line' into:\n";
print STDERR "DEBUG[tokenize]: ('", join("', '", @result), "')\n";
}
return @result;
}
diff --git a/crypto/openssl/INSTALL.md b/crypto/openssl/INSTALL.md
index fef408e9d1e3..c0dae491c94d 100644
--- a/crypto/openssl/INSTALL.md
+++ b/crypto/openssl/INSTALL.md
@@ -1,1825 +1,1832 @@
Build and Install
=================
This document describes installation on all supported operating
systems: the Unix/Linux family (including macOS), OpenVMS,
and Windows.
Table of Contents
=================
- [Prerequisites](#prerequisites)
- [Notational Conventions](#notational-conventions)
- [Quick Installation Guide](#quick-installation-guide)
- [Building OpenSSL](#building-openssl)
- [Installing OpenSSL](#installing-openssl)
- [Configuration Options](#configuration-options)
- [API Level](#api-level)
- [Cross Compile Prefix](#cross-compile-prefix)
- [Build Type](#build-type)
- [Directories](#directories)
- [Compiler Warnings](#compiler-warnings)
- [ZLib Flags](#zlib-flags)
- [Seeding the Random Generator](#seeding-the-random-generator)
- [Setting the FIPS HMAC key](#setting-the-FIPS-HMAC-key)
- [Enable and Disable Features](#enable-and-disable-features)
- [Displaying configuration data](#displaying-configuration-data)
- [Installation Steps in Detail](#installation-steps-in-detail)
- [Configure](#configure-openssl)
- [Build](#build-openssl)
- [Test](#test-openssl)
- [Install](#install-openssl)
- [Advanced Build Options](#advanced-build-options)
- [Environment Variables](#environment-variables)
- [Makefile Targets](#makefile-targets)
- [Running Selected Tests](#running-selected-tests)
- [Troubleshooting](#troubleshooting)
- [Configuration Problems](#configuration-problems)
- [Build Failures](#build-failures)
- [Test Failures](#test-failures)
- [Notes](#notes)
- [Notes on multi-threading](#notes-on-multi-threading)
- [Notes on shared libraries](#notes-on-shared-libraries)
- [Notes on random number generation](#notes-on-random-number-generation)
- [Notes on assembler modules compilation](#notes-on-assembler-modules-compilation)
Prerequisites
=============
To install OpenSSL, you will need:
* A "make" implementation
* Perl 5 with core modules (please read [NOTES-PERL.md](NOTES-PERL.md))
* The Perl module `Text::Template` (please read [NOTES-PERL.md](NOTES-PERL.md))
* an ANSI C compiler
* a development environment in the form of development libraries and C
header files
* a supported operating system
For additional platform specific requirements, solutions to specific
issues and other details, please read one of these:
* [Notes for UNIX-like platforms](NOTES-UNIX.md)
* [Notes for Android platforms](NOTES-ANDROID.md)
* [Notes for Windows platforms](NOTES-WINDOWS.md)
* [Notes for the DOS platform with DJGPP](NOTES-DJGPP.md)
* [Notes for the OpenVMS platform](NOTES-VMS.md)
* [Notes on Perl](NOTES-PERL.md)
* [Notes on Valgrind](NOTES-VALGRIND.md)
Notational conventions
======================
Throughout this document, we use the following conventions.
Commands
--------
Any line starting with a dollar sign is a command line.
$ command
The dollar sign indicates the shell prompt and is not to be entered as
part of the command.
Choices
-------
Several words in curly braces separated by pipe characters indicate a
**mandatory choice**, to be replaced with one of the given words.
For example, the line
$ echo { WORD1 | WORD2 | WORD3 }
represents one of the following three commands
$ echo WORD1
- or -
$ echo WORD2
- or -
$ echo WORD3
One or several words in square brackets separated by pipe characters
denote an **optional choice**. It is similar to the mandatory choice,
but it can also be omitted entirely.
So the line
$ echo [ WORD1 | WORD2 | WORD3 ]
represents one of the four commands
$ echo WORD1
- or -
$ echo WORD2
- or -
$ echo WORD3
- or -
$ echo
Arguments
---------
**Mandatory arguments** are enclosed in double curly braces.
A simple example would be
$ type {{ filename }}
which is to be understood to use the command `type` on some file name
determined by the user.
**Optional Arguments** are enclosed in double square brackets.
[[ options ]]
Note that the notation assumes spaces around `{`, `}`, `[`, `]`, `{{`, `}}` and
`[[`, `]]`. This is to differentiate from OpenVMS directory
specifications, which also use [ and ], but without spaces.
Quick Installation Guide
========================
If you just want to get OpenSSL installed without bothering too much
about the details, here is the short version of how to build and install
OpenSSL. If any of the following steps fails, please consult the
[Installation in Detail](#installation-steps-in-detail) section below.
Building OpenSSL
----------------
Use the following commands to configure, build and test OpenSSL.
The testing is optional, but recommended if you intend to install
OpenSSL for production use.
### Unix / Linux / macOS
$ ./Configure
$ make
$ make test
### OpenVMS
Use the following commands to build OpenSSL:
$ perl Configure
$ mms
$ mms test
### Windows
If you are using Visual Studio, open a Developer Command Prompt and
issue the following commands to build OpenSSL.
$ perl Configure
$ nmake
$ nmake test
As mentioned in the [Choices](#choices) section, you need to pick one
of the four Configure targets in the first command.
Most likely you will be using the `VC-WIN64A` target for 64bit Windows
binaries (AMD64) or `VC-WIN32` for 32bit Windows binaries (X86).
The other two options are `VC-WIN64I` (Intel IA64, Itanium) and
`VC-CE` (Windows CE) are rather uncommon nowadays.
Installing OpenSSL
------------------
The following commands will install OpenSSL to a default system location.
**Danger Zone:** even if you are impatient, please read the following two
paragraphs carefully before you install OpenSSL.
For security reasons the default system location is by default not writable
for unprivileged users. So for the final installation step administrative
privileges are required. The default system location and the procedure to
obtain administrative privileges depends on the operating system.
It is recommended to compile and test OpenSSL with normal user privileges
and use administrative privileges only for the final installation step.
On some platforms OpenSSL is preinstalled as part of the Operating System.
In this case it is highly recommended not to overwrite the system versions,
because other applications or libraries might depend on it.
To avoid breaking other applications, install your copy of OpenSSL to a
[different location](#installing-to-a-different-location) which is not in
the global search path for system libraries.
Finally, if you plan on using the FIPS module, you need to read the
[Post-installation Notes](#post-installation-notes) further down.
### Unix / Linux / macOS
Depending on your distribution, you need to run the following command as
root user or prepend `sudo` to the command:
$ make install
By default, OpenSSL will be installed to
/usr/local
More precisely, the files will be installed into the subdirectories
/usr/local/bin
/usr/local/lib
/usr/local/include
...
depending on the file type, as it is custom on Unix-like operating systems.
### OpenVMS
Use the following command to install OpenSSL.
$ mms install
By default, OpenSSL will be installed to
SYS$COMMON:[OPENSSL]
### Windows
If you are using Visual Studio, open the Developer Command Prompt _elevated_
and issue the following command.
$ nmake install
The easiest way to elevate the Command Prompt is to press and hold down both
the `<CTRL>` and `<SHIFT>` keys while clicking the menu item in the task menu.
The default installation location is
C:\Program Files\OpenSSL
for native binaries, or
C:\Program Files (x86)\OpenSSL
for 32bit binaries on 64bit Windows (WOW64).
#### Installing to a different location
To install OpenSSL to a different location (for example into your home
directory for testing purposes) run `Configure` as shown in the following
examples.
The options `--prefix` and `--openssldir` are explained in further detail in
[Directories](#directories) below, and the values used here are mere examples.
On Unix:
$ ./Configure --prefix=/opt/openssl --openssldir=/usr/local/ssl
On OpenVMS:
$ perl Configure --prefix=PROGRAM:[INSTALLS] --openssldir=SYS$MANAGER:[OPENSSL]
Note: if you do add options to the configuration command, please make sure
you've read more than just this Quick Start, such as relevant `NOTES-*` files,
the options outline below, as configuration options may change the outcome
in otherwise unexpected ways.
Configuration Options
=====================
There are several options to `./Configure` to customize the build (note that
for Windows, the defaults for `--prefix` and `--openssldir` depend on what
configuration is used and what Windows implementation OpenSSL is built on.
For more information, see the [Notes for Windows platforms](NOTES-WINDOWS.md).
API Level
---------
--api=x.y[.z]
Build the OpenSSL libraries to support the API for the specified version.
If [no-deprecated](#no-deprecated) is also given, don't build with support
for deprecated APIs in or below the specified version number. For example,
adding
--api=1.1.0 no-deprecated
will remove support for all APIs that were deprecated in OpenSSL version
1.1.0 or below. This is a rather specialized option for developers.
If you just intend to remove all deprecated APIs up to the current version
entirely, just specify [no-deprecated](#no-deprecated).
If `--api` isn't given, it defaults to the current (minor) OpenSSL version.
Cross Compile Prefix
--------------------
--cross-compile-prefix=<PREFIX>
The `<PREFIX>` to include in front of commands for your toolchain.
It is likely to have to end with dash, e.g. `a-b-c-` would invoke GNU compiler
as `a-b-c-gcc`, etc. Unfortunately cross-compiling is too case-specific to put
together one-size-fits-all instructions. You might have to pass more flags or
set up environment variables to actually make it work. Android and iOS cases
are discussed in corresponding `Configurations/15-*.conf` files. But there are
cases when this option alone is sufficient. For example to build the mingw64
target on Linux `--cross-compile-prefix=x86_64-w64-mingw32-` works. Naturally
provided that mingw packages are installed. Today Debian and Ubuntu users
have option to install a number of prepackaged cross-compilers along with
corresponding run-time and development packages for "alien" hardware. To give
another example `--cross-compile-prefix=mipsel-linux-gnu-` suffices in such
case.
For cross compilation, you must [configure manually](#manual-configuration).
Also, note that `--openssldir` refers to target's file system, not one you are
building on.
Build Type
----------
--debug
Build OpenSSL with debugging symbols and zero optimization level.
--release
Build OpenSSL without debugging symbols. This is the default.
Directories
-----------
### libdir
--libdir=DIR
The name of the directory under the top of the installation directory tree
(see the `--prefix` option) where libraries will be installed. By default
this is `lib`. Note that on Windows only static libraries (`*.lib`) will
be stored in this location. Shared libraries (`*.dll`) will always be
installed to the `bin` directory.
Some build targets have a multilib postfix set in the build configuration.
For these targets the default libdir is `lib<multilib-postfix>`. Please use
`--libdir=lib` to override the libdir if adding the postfix is undesirable.
### openssldir
--openssldir=DIR
Directory for OpenSSL configuration files, and also the default certificate
and key store. Defaults are:
Unix: /usr/local/ssl
Windows: C:\Program Files\Common Files\SSL
OpenVMS: SYS$COMMON:[OPENSSL-COMMON]
For 32bit Windows applications on Windows 64bit (WOW64), always replace
`C:\Program Files` by `C:\Program Files (x86)`.
### prefix
--prefix=DIR
The top of the installation directory tree. Defaults are:
Unix: /usr/local
Windows: C:\Program Files\OpenSSL
OpenVMS: SYS$COMMON:[OPENSSL]
Compiler Warnings
-----------------
--strict-warnings
This is a developer flag that switches on various compiler options recommended
for OpenSSL development. It only works when using gcc or clang as the compiler.
If you are developing a patch for OpenSSL then it is recommended that you use
this option where possible.
ZLib Flags
----------
### with-zlib-include
--with-zlib-include=DIR
The directory for the location of the zlib include file. This option is only
necessary if [zlib](#zlib) is used and the include file is not
already on the system include path.
### with-zlib-lib
--with-zlib-lib=LIB
**On Unix**: this is the directory containing the zlib library.
If not provided the system library path will be used.
**On Windows:** this is the filename of the zlib library (with or
without a path). This flag must be provided if the
[zlib-dynamic](#zlib-dynamic) option is not also used. If `zlib-dynamic` is used
then this flag is optional and defaults to `ZLIB1` if not provided.
**On VMS:** this is the filename of the zlib library (with or without a path).
This flag is optional and if not provided then `GNV$LIBZSHR`, `GNV$LIBZSHR32`
or `GNV$LIBZSHR64` is used by default depending on the pointer size chosen.
Seeding the Random Generator
----------------------------
--with-rand-seed=seed1[,seed2,...]
A comma separated list of seeding methods which will be tried by OpenSSL
in order to obtain random input (a.k.a "entropy") for seeding its
cryptographically secure random number generator (CSPRNG).
The current seeding methods are:
### os
Use a trusted operating system entropy source.
This is the default method if such an entropy source exists.
### getrandom
Use the [getrandom(2)][man-getrandom] or equivalent system call.
[man-getrandom]: http://man7.org/linux/man-pages/man2/getrandom.2.html
### devrandom
Use the first device from the `DEVRANDOM` list which can be opened to read
random bytes. The `DEVRANDOM` preprocessor constant expands to
"/dev/urandom","/dev/random","/dev/srandom"
on most unix-ish operating systems.
### egd
Check for an entropy generating daemon.
This source is ignored by the FIPS provider.
### rdcpu
Use the `RDSEED` or `RDRAND` command if provided by the CPU.
### librandom
Use librandom (not implemented yet).
This source is ignored by the FIPS provider.
### none
Disable automatic seeding. This is the default on some operating systems where
no suitable entropy source exists, or no support for it is implemented yet.
This option is ignored by the FIPS provider.
For more information, see the section [Notes on random number generation][rng]
at the end of this document.
[rng]: #notes-on-random-number-generation
Setting the FIPS HMAC key
-------------------------
--fips-key=value
As part of its self-test validation, the FIPS module must verify itself
by performing a SHA-256 HMAC computation on itself. The default key is
-the SHA256 value of "the holy handgrenade of antioch" and is sufficient
+the SHA256 value of "holy hand grenade of antioch" and is sufficient
for meeting the FIPS requirements.
To change the key to a different value, use this flag. The value should
be a hex string no more than 64 characters.
Enable and Disable Features
---------------------------
Feature options always come in pairs, an option to enable feature
`xxxx`, and an option to disable it:
[ enable-xxxx | no-xxxx ]
Whether a feature is enabled or disabled by default, depends on the feature.
In the following list, always the non-default variant is documented: if
feature `xxxx` is disabled by default then `enable-xxxx` is documented and
if feature `xxxx` is enabled by default then `no-xxxx` is documented.
### no-afalgeng
Don't build the AFALG engine.
This option will be forced on a platform that does not support AFALG.
### enable-ktls
Build with Kernel TLS support.
This option will enable the use of the Kernel TLS data-path, which can improve
performance and allow for the use of sendfile and splice system calls on
TLS sockets. The Kernel may use TLS accelerators if any are available on the
system. This option will be forced off on systems that do not support the
Kernel TLS data-path.
### enable-asan
Build with the Address sanitiser.
This is a developer option only. It may not work on all platforms and should
never be used in production environments. It will only work when used with
gcc or clang and should be used in conjunction with the [no-shared](#no-shared)
option.
### enable-acvp-tests
Build support for Automated Cryptographic Validation Protocol (ACVP)
tests.
This is required for FIPS validation purposes. Certain ACVP tests require
access to algorithm internals that are not normally accessible.
Additional information related to ACVP can be found at
<https://github.com/usnistgov/ACVP>.
### no-asm
Do not use assembler code.
This should be viewed as debugging/troubleshooting option rather than for
production use. On some platforms a small amount of assembler code may still
be used even with this option.
### no-async
Do not build support for async operations.
+### no-atexit
+
+Do not use `atexit()` in libcrypto builds.
+
+`atexit()` has varied semantics between platforms and can cause SIGSEGV in some
+circumstances. This option disables the atexit registration of OPENSSL_cleanup.
+
### no-autoalginit
Don't automatically load all supported ciphers and digests.
Typically OpenSSL will make available all of its supported ciphers and digests.
For a statically linked application this may be undesirable if small executable
size is an objective. This only affects libcrypto. Ciphers and digests will
have to be loaded manually using `EVP_add_cipher()` and `EVP_add_digest()`
if this option is used. This option will force a non-shared build.
### no-autoerrinit
Don't automatically load all libcrypto/libssl error strings.
Typically OpenSSL will automatically load human readable error strings. For a
statically linked application this may be undesirable if small executable size
is an objective.
### no-autoload-config
Don't automatically load the default `openssl.cnf` file.
Typically OpenSSL will automatically load a system config file which configures
default SSL options.
### enable-buildtest-c++
While testing, generate C++ buildtest files that simply check that the public
OpenSSL header files are usable standalone with C++.
Enabling this option demands extra care. For any compiler flag given directly
as configuration option, you must ensure that it's valid for both the C and
the C++ compiler. If not, the C++ build test will most likely break. As an
alternative, you can use the language specific variables, `CFLAGS` and `CXXFLAGS`.
### --banner=text
Use the specified text instead of the default banner at the end of
configuration.
### --w
On platforms where the choice of 32-bit or 64-bit architecture
is not explicitly specified, `Configure` will print a warning
message and wait for a few seconds to let you interrupt the
configuration. Using this flag skips the wait.
### no-bulk
Build only some minimal set of features.
This is a developer option used internally for CI build tests of the project.
### no-cached-fetch
Never cache algorithms when they are fetched from a provider. Normally, a
provider indicates if the algorithms it supplies can be cached or not. Using
this option will reduce run-time memory usage but it also introduces a
significant performance penalty. This option is primarily designed to help
with detecting incorrect reference counting.
### no-capieng
Don't build the CAPI engine.
This option will be forced if on a platform that does not support CAPI.
### no-cmp
Don't build support for Certificate Management Protocol (CMP)
and Certificate Request Message Format (CRMF).
### no-cms
Don't build support for Cryptographic Message Syntax (CMS).
### no-comp
Don't build support for SSL/TLS compression.
If this option is enabled (the default), then compression will only work if
the zlib or `zlib-dynamic` options are also chosen.
### enable-crypto-mdebug
This now only enables the `failed-malloc` feature.
### enable-crypto-mdebug-backtrace
This is a no-op; the project uses the compiler's address/leak sanitizer instead.
### no-ct
Don't build support for Certificate Transparency (CT).
### no-deprecated
Don't build with support for deprecated APIs up until and including the version
given with `--api` (or the current version, if `--api` wasn't specified).
### no-dgram
Don't build support for datagram based BIOs.
Selecting this option will also force the disabling of DTLS.
### no-dso
Don't build support for loading Dynamic Shared Objects (DSO)
### enable-devcryptoeng
Build the `/dev/crypto` engine.
This option is automatically selected on the BSD platform, in which case it can
be disabled with `no-devcryptoeng`.
### no-dynamic-engine
Don't build the dynamically loaded engines.
This only has an effect in a shared build.
### no-ec
Don't build support for Elliptic Curves.
### no-ec2m
Don't build support for binary Elliptic Curves
### enable-ec_nistp_64_gcc_128
Enable support for optimised implementations of some commonly used NIST
elliptic curves.
This option is only supported on platforms:
- with little-endian storage of non-byte types
- that tolerate misaligned memory references
- where the compiler:
- supports the non-standard type `__uint128_t`
- defines the built-in macro `__SIZEOF_INT128__`
### enable-egd
Build support for gathering entropy from the Entropy Gathering Daemon (EGD).
### no-engine
Don't build support for loading engines.
### no-err
Don't compile in any error strings.
### enable-external-tests
Enable building of integration with external test suites.
This is a developer option and may not work on all platforms. The following
external test suites are currently supported:
- GOST engine test suite
- Python PYCA/Cryptography test suite
- krb5 test suite
See the file [test/README-external.md](test/README-external.md)
for further details.
### no-filenames
Don't compile in filename and line number information (e.g. for errors and
memory allocation).
### enable-fips
Build (and install) the FIPS provider
### no-fips-securitychecks
Don't perform FIPS module run-time checks related to enforcement of security
parameters such as minimum security strength of keys.
### enable-fuzz-libfuzzer, enable-fuzz-afl
Build with support for fuzzing using either libfuzzer or AFL.
These are developer options only. They may not work on all platforms and
should never be used in production environments.
See the file [fuzz/README.md](fuzz/README.md) for further details.
### no-gost
Don't build support for GOST based ciphersuites.
Note that if this feature is enabled then GOST ciphersuites are only available
if the GOST algorithms are also available through loading an externally supplied
engine.
### no-legacy
Don't build the legacy provider.
Disabling this also disables the legacy algorithms: MD2 (already disabled by default).
### no-makedepend
Don't generate dependencies.
### no-module
Don't build any dynamically loadable engines.
This also implies `no-dynamic-engine`.
### no-multiblock
Don't build support for writing multiple records in one go in libssl
Note: this is a different capability to the pipelining functionality.
### no-nextprotoneg
Don't build support for the Next Protocol Negotiation (NPN) TLS extension.
### no-ocsp
Don't build support for Online Certificate Status Protocol (OCSP).
### no-padlockeng
Don't build the padlock engine.
### no-hw-padlock
As synonym for `no-padlockeng`. Deprecated and should not be used.
### no-pic
Don't build with support for Position Independent Code.
### no-pinshared
Don't pin the shared libraries.
By default OpenSSL will attempt to stay in memory until the process exits.
This is so that libcrypto and libssl can be properly cleaned up automatically
via an `atexit()` handler. The handler is registered by libcrypto and cleans
up both libraries. On some platforms the `atexit()` handler will run on unload of
libcrypto (if it has been dynamically loaded) rather than at process exit.
This option can be used to stop OpenSSL from attempting to stay in memory until the
process exits. This could lead to crashes if either libcrypto or libssl have
already been unloaded at the point that the atexit handler is invoked, e.g. on a
platform which calls `atexit()` on unload of the library, and libssl is unloaded
before libcrypto then a crash is likely to happen.
Note that shared library pinning is not automatically disabled for static builds,
i.e., `no-shared` does not imply `no-pinshared`. This may come as a surprise when
linking libcrypto statically into a shared third-party library, because in this
case the shared library will be pinned. To prevent this behaviour, you need to
configure the static build using `no-shared` and `no-pinshared` together.
Applications can suppress running of the `atexit()` handler at run time by
using the `OPENSSL_INIT_NO_ATEXIT` option to `OPENSSL_init_crypto()`.
See the man page for it for further details.
### no-posix-io
Don't use POSIX IO capabilities.
### no-psk
Don't build support for Pre-Shared Key based ciphersuites.
### no-rdrand
Don't use hardware RDRAND capabilities.
### no-rfc3779
Don't build support for RFC3779, "X.509 Extensions for IP Addresses and
AS Identifiers".
### sctp
Build support for Stream Control Transmission Protocol (SCTP).
### no-shared
Do not create shared libraries, only static ones.
See [Notes on shared libraries](#notes-on-shared-libraries) below.
### no-sock
Don't build support for socket BIOs.
### no-srp
Don't build support for Secure Remote Password (SRP) protocol or
SRP based ciphersuites.
### no-srtp
Don't build Secure Real-Time Transport Protocol (SRTP) support.
### no-sse2
Exclude SSE2 code paths from 32-bit x86 assembly modules.
Normally SSE2 extension is detected at run-time, but the decision whether or not
the machine code will be executed is taken solely on CPU capability vector. This
means that if you happen to run OS kernel which does not support SSE2 extension
on Intel P4 processor, then your application might be exposed to "illegal
instruction" exception. There might be a way to enable support in kernel, e.g.
FreeBSD kernel can be compiled with `CPU_ENABLE_SSE`, and there is a way to
disengage SSE2 code paths upon application start-up, but if you aim for wider
"audience" running such kernel, consider `no-sse2`. Both the `386` and `no-asm`
options imply `no-sse2`.
### no-ssl-trace
Don't build with SSL Trace capabilities.
This removes the `-trace` option from `s_client` and `s_server`, and omits the
`SSL_trace()` function from libssl.
Disabling `ssl-trace` may provide a small reduction in libssl binary size.
### no-static-engine
Don't build the statically linked engines.
This only has an impact when not built "shared".
### no-stdio
Don't use anything from the C header file `stdio.h` that makes use of the `FILE`
type. Only libcrypto and libssl can be built in this way. Using this option will
suppress building the command line applications. Additionally, since the OpenSSL
tests also use the command line applications, the tests will also be skipped.
### no-tests
Don't build test programs or run any tests.
### no-threads
Don't build with support for multi-threaded applications.
### threads
Build with support for multi-threaded applications. Most platforms will enable
this by default. However, if on a platform where this is not the case then this
will usually require additional system-dependent options!
See [Notes on multi-threading](#notes-on-multi-threading) below.
### enable-trace
Build with support for the integrated tracing api.
See manual pages OSSL_trace_set_channel(3) and OSSL_trace_enabled(3) for details.
### no-ts
Don't build Time Stamping (TS) Authority support.
### enable-ubsan
Build with the Undefined Behaviour sanitiser (UBSAN).
This is a developer option only. It may not work on all platforms and should
never be used in production environments. It will only work when used with
gcc or clang and should be used in conjunction with the `-DPEDANTIC` option
(or the `--strict-warnings` option).
### no-ui-console
Don't build with the User Interface (UI) console method
The User Interface console method enables text based console prompts.
### enable-unit-test
Enable additional unit test APIs.
This should not typically be used in production deployments.
### no-uplink
Don't build support for UPLINK interface.
### enable-weak-ssl-ciphers
Build support for SSL/TLS ciphers that are considered "weak"
Enabling this includes for example the RC4 based ciphersuites.
### zlib
Build with support for zlib compression/decompression.
### zlib-dynamic
Like the zlib option, but has OpenSSL load the zlib library dynamically
when needed.
This is only supported on systems where loading of shared libraries is supported.
### 386
In 32-bit x86 builds, use the 80386 instruction set only in assembly modules
The default x86 code is more efficient, but requires at least an 486 processor.
Note: This doesn't affect compiler generated code, so this option needs to be
accompanied by a corresponding compiler-specific option.
### no-{protocol}
no-{ssl|ssl3|tls|tls1|tls1_1|tls1_2|tls1_3|dtls|dtls1|dtls1_2}
Don't build support for negotiating the specified SSL/TLS protocol.
If `no-tls` is selected then all of `tls1`, `tls1_1`, `tls1_2` and `tls1_3`
are disabled.
Similarly `no-dtls` will disable `dtls1` and `dtls1_2`. The `no-ssl` option is
synonymous with `no-ssl3`. Note this only affects version negotiation.
OpenSSL will still provide the methods for applications to explicitly select
the individual protocol versions.
### no-{protocol}-method
no-{ssl3|tls1|tls1_1|tls1_2|dtls1|dtls1_2}-method
Analogous to `no-{protocol}` but in addition do not build the methods for
applications to explicitly select individual protocol versions. Note that there
is no `no-tls1_3-method` option because there is no application method for
TLSv1.3.
Using individual protocol methods directly is deprecated. Applications should
use `TLS_method()` instead.
### enable-{algorithm}
enable-{md2|rc5}
Build with support for the specified algorithm.
### no-{algorithm}
no-{aria|bf|blake2|camellia|cast|chacha|cmac|
des|dh|dsa|ecdh|ecdsa|idea|md4|mdc2|ocb|
poly1305|rc2|rc4|rmd160|scrypt|seed|
siphash|siv|sm2|sm3|sm4|whirlpool}
Build without support for the specified algorithm.
The `ripemd` algorithm is deprecated and if used is synonymous with `rmd160`.
### Compiler-specific options
-Dxxx, -Ixxx, -Wp, -lxxx, -Lxxx, -Wl, -rpath, -R, -framework, -static
These system specific options will be recognised and passed through to the
compiler to allow you to define preprocessor symbols, specify additional
libraries, library directories or other compiler options. It might be worth
noting that some compilers generate code specifically for processor the
compiler currently executes on. This is not necessarily what you might have
in mind, since it might be unsuitable for execution on other, typically older,
processor. Consult your compiler documentation.
Take note of the [Environment Variables](#environment-variables) documentation
below and how these flags interact with those variables.
-xxx, +xxx, /xxx
Additional options that are not otherwise recognised are passed through as
they are to the compiler as well. Unix-style options beginning with a
`-` or `+` and Windows-style options beginning with a `/` are recognized.
Again, consult your compiler documentation.
If the option contains arguments separated by spaces, then the URL-style
notation `%20` can be used for the space character in order to avoid having
to quote the option. For example, `-opt%20arg` gets expanded to `-opt arg`.
In fact, any ASCII character can be encoded as %xx using its hexadecimal
encoding.
Take note of the [Environment Variables](#environment-variables) documentation
below and how these flags interact with those variables.
### Environment Variables
VAR=value
Assign the given value to the environment variable `VAR` for `Configure`.
These work just like normal environment variable assignments, but are supported
on all platforms and are confined to the configuration scripts only.
These assignments override the corresponding value in the inherited environment,
if there is one.
The following variables are used as "`make` variables" and can be used as an
alternative to giving preprocessor, compiler and linker options directly as
configuration. The following variables are supported:
AR The static library archiver.
ARFLAGS Flags for the static library archiver.
AS The assembler compiler.
ASFLAGS Flags for the assembler compiler.
CC The C compiler.
CFLAGS Flags for the C compiler.
CXX The C++ compiler.
CXXFLAGS Flags for the C++ compiler.
CPP The C/C++ preprocessor.
CPPFLAGS Flags for the C/C++ preprocessor.
CPPDEFINES List of CPP macro definitions, separated
by a platform specific character (':' or
space for Unix, ';' for Windows, ',' for
VMS). This can be used instead of using
-D (or what corresponds to that on your
compiler) in CPPFLAGS.
CPPINCLUDES List of CPP inclusion directories, separated
the same way as for CPPDEFINES. This can
be used instead of -I (or what corresponds
to that on your compiler) in CPPFLAGS.
HASHBANGPERL Perl invocation to be inserted after '#!'
in public perl scripts (only relevant on
Unix).
LD The program linker (not used on Unix, $(CC)
is used there).
LDFLAGS Flags for the shared library, DSO and
program linker.
LDLIBS Extra libraries to use when linking.
Takes the form of a space separated list
of library specifications on Unix and
Windows, and as a comma separated list of
libraries on VMS.
RANLIB The library archive indexer.
RC The Windows resource compiler.
RCFLAGS Flags for the Windows resource compiler.
RM The command to remove files and directories.
These cannot be mixed with compiling/linking flags given on the command line.
In other words, something like this isn't permitted.
$ ./Configure -DFOO CPPFLAGS=-DBAR -DCOOKIE
Backward compatibility note:
To be compatible with older configuration scripts, the environment variables
are ignored if compiling/linking flags are given on the command line, except
for the following:
AR, CC, CXX, CROSS_COMPILE, HASHBANGPERL, PERL, RANLIB, RC, and WINDRES
For example, the following command will not see `-DBAR`:
$ CPPFLAGS=-DBAR ./Configure -DCOOKIE
However, the following will see both set variables:
$ CC=gcc CROSS_COMPILE=x86_64-w64-mingw32- ./Configure -DCOOKIE
If `CC` is set, it is advisable to also set `CXX` to ensure both the C and C++
compiler are in the same "family". This becomes relevant with
`enable-external-tests` and `enable-buildtest-c++`.
### Reconfigure
reconf
reconfigure
Reconfigure from earlier data.
This fetches the previous command line options and environment from data
saved in `configdata.pm` and runs the configuration process again, using
these options and environment. Note: NO other option is permitted together
with `reconf`. Note: The original configuration saves away values for ALL
environment variables that were used, and if they weren't defined, they are
still saved away with information that they weren't originally defined.
This information takes precedence over environment variables that are
defined when reconfiguring.
Displaying configuration data
-----------------------------
The configuration script itself will say very little, and finishes by
creating `configdata.pm`. This perl module can be loaded by other scripts
to find all the configuration data, and it can also be used as a script to
display all sorts of configuration data in a human readable form.
For more information, please do:
$ ./configdata.pm --help # Unix
or
$ perl configdata.pm --help # Windows and VMS
Installation Steps in Detail
============================
Configure OpenSSL
-----------------
### Automatic Configuration
In previous version, the `config` script determined the platform type and
compiler and then called `Configure`. Starting with this release, they are
the same.
#### Unix / Linux / macOS
$ ./Configure [[ options ]]
#### OpenVMS
$ perl Configure [[ options ]]
#### Windows
$ perl Configure [[ options ]]
### Manual Configuration
OpenSSL knows about a range of different operating system, hardware and
compiler combinations. To see the ones it knows about, run
$ ./Configure LIST # Unix
or
$ perl Configure LIST # All other platforms
For the remainder of this text, the Unix form will be used in all examples.
Please use the appropriate form for your platform.
Pick a suitable name from the list that matches your system. For most
operating systems there is a choice between using cc or gcc.
When you have identified your system (and if necessary compiler) use this
name as the argument to `Configure`. For example, a `linux-elf` user would
run:
$ ./Configure linux-elf [[ options ]]
### Creating your own Configuration
If your system isn't listed, you will have to create a configuration
file named `Configurations/{{ something }}.conf` and add the correct
configuration for your system. See the available configs as examples
and read [Configurations/README.md](Configurations/README.md) and
[Configurations/README-design.md](Configurations/README-design.md)
for more information.
The generic configurations `cc` or `gcc` should usually work on 32 bit
Unix-like systems.
`Configure` creates a build file (`Makefile` on Unix, `makefile` on Windows
and `descrip.mms` on OpenVMS) from a suitable template in `Configurations/`,
and defines various macros in `include/openssl/configuration.h` (generated
from `include/openssl/configuration.h.in`.
If none of the generated build files suit your purpose, it's possible to
write your own build file template and give its name through the environment
variable `BUILDFILE`. For example, Ninja build files could be supported by
writing `Configurations/build.ninja.tmpl` and then configure with `BUILDFILE`
set like this (Unix syntax shown, you'll have to adapt for other platforms):
$ BUILDFILE=build.ninja perl Configure [options...]
### Out of Tree Builds
OpenSSL can be configured to build in a build directory separate from the
source code directory. It's done by placing yourself in some other
directory and invoking the configuration commands from there.
#### Unix example
$ mkdir /var/tmp/openssl-build
$ cd /var/tmp/openssl-build
$ /PATH/TO/OPENSSL/SOURCE/Configure [[ options ]]
#### OpenVMS example
$ set default sys$login:
$ create/dir [.tmp.openssl-build]
$ set default [.tmp.openssl-build]
$ perl D:[PATH.TO.OPENSSL.SOURCE]Configure [[ options ]]
#### Windows example
$ C:
$ mkdir \temp-openssl
$ cd \temp-openssl
$ perl d:\PATH\TO\OPENSSL\SOURCE\Configure [[ options ]]
Paths can be relative just as well as absolute. `Configure` will do its best
to translate them to relative paths whenever possible.
Build OpenSSL
-------------
Build OpenSSL by running:
$ make # Unix
$ mms ! (or mmk) OpenVMS
$ nmake # Windows
This will build the OpenSSL libraries (`libcrypto.a` and `libssl.a` on
Unix, corresponding on other platforms) and the OpenSSL binary
(`openssl`). The libraries will be built in the top-level directory,
and the binary will be in the `apps/` subdirectory.
If the build fails, take a look at the [Build Failures](#build-failures)
subsection of the [Troubleshooting](#troubleshooting) section.
Test OpenSSL
------------
After a successful build, and before installing, the libraries should
be tested. Run:
$ make test # Unix
$ mms test ! OpenVMS
$ nmake test # Windows
**Warning:** you MUST run the tests from an unprivileged account (or disable
your privileges temporarily if your platform allows it).
See [test/README.md](test/README.md) for further details how run tests.
See [test/README-dev.md](test/README-dev.md) for guidelines on adding tests.
Install OpenSSL
---------------
If everything tests ok, install OpenSSL with
$ make install # Unix
$ mms install ! OpenVMS
$ nmake install # Windows
Note that in order to perform the install step above you need to have
appropriate permissions to write to the installation directory.
The above commands will install all the software components in this
directory tree under `<PREFIX>` (the directory given with `--prefix` or
its default):
### Unix / Linux / macOS
bin/ Contains the openssl binary and a few other
utility scripts.
include/openssl
Contains the header files needed if you want
to build your own programs that use libcrypto
or libssl.
lib Contains the OpenSSL library files.
lib/engines Contains the OpenSSL dynamically loadable engines.
share/man/man1 Contains the OpenSSL command line man-pages.
share/man/man3 Contains the OpenSSL library calls man-pages.
share/man/man5 Contains the OpenSSL configuration format man-pages.
share/man/man7 Contains the OpenSSL other misc man-pages.
share/doc/openssl/html/man1
share/doc/openssl/html/man3
share/doc/openssl/html/man5
share/doc/openssl/html/man7
Contains the HTML rendition of the man-pages.
### OpenVMS
'arch' is replaced with the architecture name, `ALPHA` or `IA64`,
'sover' is replaced with the shared library version (`0101` for 1.1), and
'pz' is replaced with the pointer size OpenSSL was built with:
[.EXE.'arch'] Contains the openssl binary.
[.EXE] Contains a few utility scripts.
[.include.openssl]
Contains the header files needed if you want
to build your own programs that use libcrypto
or libssl.
[.LIB.'arch'] Contains the OpenSSL library files.
[.ENGINES'sover''pz'.'arch']
Contains the OpenSSL dynamically loadable engines.
[.SYS$STARTUP] Contains startup, login and shutdown scripts.
These define appropriate logical names and
command symbols.
[.SYSTEST] Contains the installation verification procedure.
[.HTML] Contains the HTML rendition of the manual pages.
### Additional Directories
Additionally, install will add the following directories under
OPENSSLDIR (the directory given with `--openssldir` or its default)
for you convenience:
certs Initially empty, this is the default location
for certificate files.
private Initially empty, this is the default location
for private key files.
misc Various scripts.
The installation directory should be appropriately protected to ensure
unprivileged users cannot make changes to OpenSSL binaries or files, or
install engines. If you already have a pre-installed version of OpenSSL as
part of your Operating System it is recommended that you do not overwrite
the system version and instead install to somewhere else.
Package builders who want to configure the library for standard locations,
but have the package installed somewhere else so that it can easily be
packaged, can use
$ make DESTDIR=/tmp/package-root install # Unix
$ mms/macro="DESTDIR=TMP:[PACKAGE-ROOT]" install ! OpenVMS
The specified destination directory will be prepended to all installation
target paths.
Compatibility issues with previous OpenSSL versions
---------------------------------------------------
### COMPILING existing applications
Starting with version 1.1.0, OpenSSL hides a number of structures that were
previously open. This includes all internal libssl structures and a number
of EVP types. Accessor functions have been added to allow controlled access
to the structures' data.
This means that some software needs to be rewritten to adapt to the new ways
of doing things. This often amounts to allocating an instance of a structure
explicitly where you could previously allocate them on the stack as automatic
variables, and using the provided accessor functions where you would previously
access a structure's field directly.
Some APIs have changed as well. However, older APIs have been preserved when
possible.
Post-installation Notes
-----------------------
With the default OpenSSL installation comes a FIPS provider module, which
needs some post-installation attention, without which it will not be usable.
This involves using the following command:
$ openssl fipsinstall
See the openssl-fipsinstall(1) manual for details and examples.
Advanced Build Options
======================
Environment Variables
---------------------
A number of environment variables can be used to provide additional control
over the build process. Typically these should be defined prior to running
`Configure`. Not all environment variables are relevant to all platforms.
AR
The name of the ar executable to use.
BUILDFILE
Use a different build file name than the platform default
("Makefile" on Unix-like platforms, "makefile" on native Windows,
"descrip.mms" on OpenVMS). This requires that there is a
corresponding build file template.
See [Configurations/README.md](Configurations/README.md)
for further information.
CC
The compiler to use. Configure will attempt to pick a default
compiler for your platform but this choice can be overridden
using this variable. Set it to the compiler executable you wish
to use, e.g. gcc or clang.
CROSS_COMPILE
This environment variable has the same meaning as for the
"--cross-compile-prefix" Configure flag described above. If both
are set then the Configure flag takes precedence.
HASHBANGPERL
The command string for the Perl executable to insert in the
#! line of perl scripts that will be publicly installed.
Default: /usr/bin/env perl
Note: the value of this variable is added to the same scripts
on all platforms, but it's only relevant on Unix-like platforms.
KERNEL_BITS
This can be the value `32` or `64` to specify the architecture
when it is not "obvious" to the configuration. It should generally
not be necessary to specify this environment variable.
NM
The name of the nm executable to use.
OPENSSL_LOCAL_CONFIG_DIR
OpenSSL comes with a database of information about how it
should be built on different platforms as well as build file
templates for those platforms. The database is comprised of
".conf" files in the Configurations directory. The build
file templates reside there as well as ".tmpl" files. See the
file [Configurations/README.md](Configurations/README.md)
for further information about the format of ".conf" files
as well as information on the ".tmpl" files.
In addition to the standard ".conf" and ".tmpl" files, it is
possible to create your own ".conf" and ".tmpl" files and
store them locally, outside the OpenSSL source tree.
This environment variable can be set to the directory where
these files are held and will be considered by Configure
before it looks in the standard directories.
PERL
The name of the Perl executable to use when building OpenSSL.
Only needed if builing should use a different Perl executable
than what is used to run the Configure script.
RANLIB
The name of the ranlib executable to use.
RC
The name of the rc executable to use. The default will be as
defined for the target platform in the ".conf" file. If not
defined then "windres" will be used. The WINDRES environment
variable is synonymous to this. If both are defined then RC
takes precedence.
WINDRES
See RC.
Makefile Targets
----------------
The `Configure` script generates a Makefile in a format relevant to the specific
platform. The Makefiles provide a number of targets that can be used. Not all
targets may be available on all platforms. Only the most common targets are
described here. Examine the Makefiles themselves for the full list.
all
The target to build all the software components and
documentation.
build_sw
Build all the software components.
THIS IS THE DEFAULT TARGET.
build_docs
Build all documentation components.
clean
Remove all build artefacts and return the directory to a "clean"
state.
depend
Rebuild the dependencies in the Makefiles. This is a legacy
option that no longer needs to be used since OpenSSL 1.1.0.
install
Install all OpenSSL components.
install_sw
Only install the OpenSSL software components.
install_docs
Only install the OpenSSL documentation components.
install_man_docs
Only install the OpenSSL man pages (Unix only).
install_html_docs
Only install the OpenSSL HTML documentation.
install_fips
Install the FIPS provider module configuration file.
list-tests
Prints a list of all the self test names.
test
Build and run the OpenSSL self tests.
uninstall
Uninstall all OpenSSL components.
reconfigure
reconf
Re-run the configuration process, as exactly as the last time
as possible.
update
This is a developer option. If you are developing a patch for
OpenSSL you may need to use this if you want to update
automatically generated files; add new error codes or add new
(or change the visibility of) public API functions. (Unix only).
Running Selected Tests
----------------------
You can specify a set of tests to be performed
using the `make` variable `TESTS`.
See the section [Running Selected Tests of
test/README.md](test/README.md#running-selected-tests).
Troubleshooting
===============
Configuration Problems
----------------------
### Selecting the correct target
The `./Configure` script tries hard to guess your operating system, but in some
cases it does not succeed. You will see a message like the following:
$ ./Configure
Operating system: x86-whatever-minix
This system (minix) is not supported. See file INSTALL.md for details.
Even if the automatic target selection by the `./Configure` script fails,
chances are that you still might find a suitable target in the `Configurations`
directory, which you can supply to the `./Configure` command,
possibly after some adjustment.
The `Configurations/` directory contains a lot of examples of such targets.
The main configuration file is [10-main.conf], which contains all targets that
are officially supported by the OpenSSL team. Other configuration files contain
targets contributed by other OpenSSL users. The list of targets can be found in
a Perl list `my %targets = ( ... )`.
my %targets = (
...
"target-name" => {
inherit_from => [ "base-target" ],
CC => "...",
cflags => add("..."),
asm_arch => '...',
perlasm_scheme => "...",
},
...
)
If you call `./Configure` without arguments, it will give you a list of all
known targets. Using `grep`, you can lookup the target definition in the
`Configurations/` directory. For example the `android-x86_64` can be found in
[Configurations/15-android.conf](Configurations/15-android.conf).
The directory contains two README files, which explain the general syntax and
design of the configuration files.
- [Configurations/README.md](Configurations/README.md)
- [Configurations/README-design.md](Configurations/README-design.md)
If you need further help, try to search the [openssl-users] mailing list
or the [GitHub Issues] for existing solutions. If you don't find anything,
you can [raise an issue] to ask a question yourself.
More about our support resources can be found in the [SUPPORT] file.
### Configuration Errors
If the `./Configure` or `./Configure` command fails with an error message,
read the error message carefully and try to figure out whether you made
a mistake (e.g., by providing a wrong option), or whether the script is
working incorrectly. If you think you encountered a bug, please
[raise an issue] on GitHub to file a bug report.
Along with a short description of the bug, please provide the complete
configure command line and the relevant output including the error message.
Note: To make the output readable, pleace add a 'code fence' (three backquotes
` ``` ` on a separate line) before and after your output:
```
./Configure [your arguments...]
[output...]
```
Build Failures
--------------
If the build fails, look carefully at the output. Try to locate and understand
the error message. It might be that the compiler is already telling you
exactly what you need to do to fix your problem.
There may be reasons for the failure that aren't problems in OpenSSL itself,
for example if the compiler reports missing standard or third party headers.
If the build succeeded previously, but fails after a source or configuration
change, it might be helpful to clean the build tree before attempting another
build. Use this command:
$ make clean # Unix
$ mms clean ! (or mmk) OpenVMS
$ nmake clean # Windows
Assembler error messages can sometimes be sidestepped by using the `no-asm`
configuration option. See also [notes](#notes-on-assembler-modules-compilation).
Compiling parts of OpenSSL with gcc and others with the system compiler will
result in unresolved symbols on some systems.
If you are still having problems, try to search the [openssl-users] mailing
list or the [GitHub Issues] for existing solutions. If you think you
encountered an OpenSSL bug, please [raise an issue] to file a bug report.
Please take the time to review the existing issues first; maybe the bug was
already reported or has already been fixed.
Test Failures
-------------
If some tests fail, look at the output. There may be reasons for the failure
that isn't a problem in OpenSSL itself (like an OS malfunction or a Perl issue).
You may want increased verbosity, that can be accomplished as described in
section [Test Failures of test/README.md](test/README.md#test-failures).
You may also want to selectively specify which test(s) to perform. This can be
done using the `make` variable `TESTS` as described in section [Running
Selected Tests of test/README.md](test/README.md#running-selected-tests).
If you find a problem with OpenSSL itself, try removing any
compiler optimization flags from the `CFLAGS` line in the Makefile and
run `make clean; make` or corresponding.
To report a bug please open an issue on GitHub, at
<https://github.com/openssl/openssl/issues>.
Notes
=====
Notes on multi-threading
------------------------
For some systems, the OpenSSL `Configure` script knows what compiler options
are needed to generate a library that is suitable for multi-threaded
applications. On these systems, support for multi-threading is enabled
by default; use the `no-threads` option to disable (this should never be
necessary).
On other systems, to enable support for multi-threading, you will have
to specify at least two options: `threads`, and a system-dependent option.
(The latter is `-D_REENTRANT` on various systems.) The default in this
case, obviously, is not to include support for multi-threading (but
you can still use `no-threads` to suppress an annoying warning message
from the `Configure` script.)
OpenSSL provides built-in support for two threading models: pthreads (found on
most UNIX/Linux systems), and Windows threads. No other threading models are
supported. If your platform does not provide pthreads or Windows threads then
you should use `Configure` with the `no-threads` option.
For pthreads, all locks are non-recursive. In addition, in a debug build,
the mutex attribute `PTHREAD_MUTEX_ERRORCHECK` is used. If this is not
available on your platform, you might have to add
`-DOPENSSL_NO_MUTEX_ERRORCHECK` to your `Configure` invocation.
(On Linux `PTHREAD_MUTEX_ERRORCHECK` is an enum value, so a built-in
ifdef test cannot be used.)
Notes on shared libraries
-------------------------
For most systems the OpenSSL `Configure` script knows what is needed to
build shared libraries for libcrypto and libssl. On these systems
the shared libraries will be created by default. This can be suppressed and
only static libraries created by using the `no-shared` option. On systems
where OpenSSL does not know how to build shared libraries the `no-shared`
option will be forced and only static libraries will be created.
Shared libraries are named a little differently on different platforms.
One way or another, they all have the major OpenSSL version number as
part of the file name, i.e. for OpenSSL 1.1.x, `1.1` is somehow part of
the name.
On most POSIX platforms, shared libraries are named `libcrypto.so.1.1`
and `libssl.so.1.1`.
on Cygwin, shared libraries are named `cygcrypto-1.1.dll` and `cygssl-1.1.dll`
with import libraries `libcrypto.dll.a` and `libssl.dll.a`.
On Windows build with MSVC or using MingW, shared libraries are named
`libcrypto-1_1.dll` and `libssl-1_1.dll` for 32-bit Windows,
`libcrypto-1_1-x64.dll` and `libssl-1_1-x64.dll` for 64-bit x86_64 Windows,
and `libcrypto-1_1-ia64.dll` and `libssl-1_1-ia64.dll` for IA64 Windows.
With MSVC, the import libraries are named `libcrypto.lib` and `libssl.lib`,
while with MingW, they are named `libcrypto.dll.a` and `libssl.dll.a`.
On VMS, shareable images (VMS speak for shared libraries) are named
`ossl$libcrypto0101_shr.exe` and `ossl$libssl0101_shr.exe`. However, when
OpenSSL is specifically built for 32-bit pointers, the shareable images
are named `ossl$libcrypto0101_shr32.exe` and `ossl$libssl0101_shr32.exe`
instead, and when built for 64-bit pointers, they are named
`ossl$libcrypto0101_shr64.exe` and `ossl$libssl0101_shr64.exe`.
Notes on random number generation
---------------------------------
Availability of cryptographically secure random numbers is required for
secret key generation. OpenSSL provides several options to seed the
internal CSPRNG. If not properly seeded, the internal CSPRNG will refuse
to deliver random bytes and a "PRNG not seeded error" will occur.
The seeding method can be configured using the `--with-rand-seed` option,
which can be used to specify a comma separated list of seed methods.
However, in most cases OpenSSL will choose a suitable default method,
so it is not necessary to explicitly provide this option. Note also
that not all methods are available on all platforms. The FIPS provider will
silently ignore seed sources that were not validated.
I) On operating systems which provide a suitable randomness source (in
form of a system call or system device), OpenSSL will use the optimal
available method to seed the CSPRNG from the operating system's
randomness sources. This corresponds to the option `--with-rand-seed=os`.
II) On systems without such a suitable randomness source, automatic seeding
and reseeding is disabled (`--with-rand-seed=none`) and it may be necessary
to install additional support software to obtain a random seed and reseed
the CSPRNG manually. Please check out the manual pages for `RAND_add()`,
`RAND_bytes()`, `RAND_egd()`, and the FAQ for more information.
Notes on assembler modules compilation
--------------------------------------
Compilation of some code paths in assembler modules might depend on whether the
current assembler version supports certain ISA extensions or not. Code paths
that use the AES-NI, PCLMULQDQ, SSSE3, and SHA extensions are always assembled.
Apart from that, the minimum requirements for the assembler versions are shown
in the table below:
| ISA extension | GNU as | nasm | llvm |
|---------------|--------|--------|---------|
| AVX | 2.19 | 2.09 | 3.0 |
| AVX2 | 2.22 | 2.10 | 3.1 |
| ADCX/ADOX | 2.23 | 2.10 | 3.3 |
| AVX512 | 2.25 | 2.11.8 | 3.6 (*) |
| AVX512IFMA | 2.26 | 2.11.8 | 6.0 (*) |
| VAES | 2.30 | 2.13.3 | 6.0 (*) |
---
(*) Even though AVX512 support was implemented in llvm 3.6, prior to version 7.0
an explicit -march flag was apparently required to compile assembly modules. But
then the compiler generates processor-specific code, which in turn contradicts
the idea of performing dispatch at run-time, which is facilitated by the special
variable `OPENSSL_ia32cap`. For versions older than 7.0, it is possible to work
around the problem by forcing the build procedure to use the following script:
#!/bin/sh
exec clang -no-integrated-as "$@"
instead of the real clang. In which case it doesn't matter what clang version
is used, as it is the version of the GNU assembler that will be checked.
---
<!-- Links -->
[openssl-users]:
<https://mta.openssl.org/mailman/listinfo/openssl-users>
[SUPPORT]:
./SUPPORT.md
[GitHub Issues]:
<https://github.com/openssl/openssl/issues>
[raise an issue]:
<https://github.com/openssl/openssl/issues/new/choose>
[10-main.conf]:
Configurations/10-main.conf
diff --git a/crypto/openssl/NEWS.md b/crypto/openssl/NEWS.md
index d9a48b157eb1..fb231bcd8459 100644
--- a/crypto/openssl/NEWS.md
+++ b/crypto/openssl/NEWS.md
@@ -1,1640 +1,1655 @@
NEWS
====
This file gives a brief overview of the major changes between each OpenSSL
release. For more details please read the CHANGES file.
OpenSSL Releases
----------------
- [OpenSSL 3.0](#openssl-30)
- [OpenSSL 1.1.1](#openssl-111)
- [OpenSSL 1.1.0](#openssl-110)
- [OpenSSL 1.0.2](#openssl-102)
- [OpenSSL 1.0.1](#openssl-101)
- [OpenSSL 1.0.0](#openssl-100)
- [OpenSSL 0.9.x](#openssl-09x)
OpenSSL 3.0
-----------
+### Major changes between OpenSSL 3.0.13 and OpenSSL 3.0.14 [4 Jun 2024]
+
+ * 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])
+
+ * Fixed unbounded memory growth with session handling in TLSv1.3
+ ([CVE-2024-2511])
+
### Major changes between OpenSSL 3.0.12 and OpenSSL 3.0.13 [30 Jan 2024]
* 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])
* Fix excessive time spent in DH check / generation with large Q parameter
value ([CVE-2023-5678])
### Major changes between OpenSSL 3.0.11 and OpenSSL 3.0.12 [24 Oct 2023]
* Mitigate incorrect resize handling for symmetric cipher keys and IVs.
([CVE-2023-5363])
### Major changes between OpenSSL 3.0.10 and OpenSSL 3.0.11 [19 Sep 2023]
* Fix POLY1305 MAC implementation corrupting XMM registers on Windows
([CVE-2023-4807])
### Major changes between OpenSSL 3.0.9 and OpenSSL 3.0.10 [1 Aug 2023]
* Fix excessive time spent checking DH q parameter value ([CVE-2023-3817])
* Fix DH_check() excessive time with over sized modulus ([CVE-2023-3446])
* Do not ignore empty associated data entries with AES-SIV ([CVE-2023-2975])
### Major changes between OpenSSL 3.0.8 and OpenSSL 3.0.9 [30 May 2023]
* Mitigate for very slow `OBJ_obj2txt()` performance with gigantic OBJECT
IDENTIFIER sub-identities. ([CVE-2023-2650])
* Fixed buffer overread in AES-XTS decryption on ARM 64 bit platforms
([CVE-2023-1255])
* Fixed documentation of X509_VERIFY_PARAM_add0_policy() ([CVE-2023-0466])
* Fixed handling of invalid certificate policies in leaf certificates
([CVE-2023-0465])
* Limited the number of nodes created in a policy tree ([CVE-2023-0464])
### Major changes between OpenSSL 3.0.7 and OpenSSL 3.0.8 [7 Feb 2023]
* Fixed NULL dereference during PKCS7 data verification ([CVE-2023-0401])
* Fixed X.400 address type confusion in X.509 GeneralName ([CVE-2023-0286])
* Fixed NULL dereference validating DSA public key ([CVE-2023-0217])
* Fixed Invalid pointer dereference in d2i_PKCS7 functions ([CVE-2023-0216])
* Fixed Use-after-free following BIO_new_NDEF ([CVE-2023-0215])
* Fixed Double free after calling PEM_read_bio_ex ([CVE-2022-4450])
* Fixed Timing Oracle in RSA Decryption ([CVE-2022-4304])
* Fixed X.509 Name Constraints Read Buffer Overflow ([CVE-2022-4203])
* Fixed X.509 Policy Constraints Double Locking ([CVE-2022-3996])
### Major changes between OpenSSL 3.0.6 and OpenSSL 3.0.7 [1 Nov 2022]
* Added RIPEMD160 to the default provider.
* Fixed regressions introduced in 3.0.6 version.
* Fixed two buffer overflows in punycode decoding functions.
([CVE-2022-3786]) and ([CVE-2022-3602])
### Major changes between OpenSSL 3.0.5 and OpenSSL 3.0.6 [11 Oct 2022]
* Fix for custom ciphers to prevent accidental use of NULL encryption
([CVE-2022-3358])
### Major changes between OpenSSL 3.0.4 and OpenSSL 3.0.5 [5 Jul 2022]
* Fixed heap memory corruption with RSA private key operation
([CVE-2022-2274])
* Fixed AES OCB failure to encrypt some bytes on 32-bit x86 platforms
([CVE-2022-2097])
### Major changes between OpenSSL 3.0.3 and OpenSSL 3.0.4 [21 Jun 2022]
* Fixed additional bugs in the c_rehash script which was not properly
sanitising shell metacharacters to prevent command injection
([CVE-2022-2068])
### Major changes between OpenSSL 3.0.2 and OpenSSL 3.0.3 [3 May 2022]
* Fixed a bug in the c_rehash script which was not properly sanitising shell
metacharacters to prevent command injection ([CVE-2022-1292])
* Fixed a bug in the function `OCSP_basic_verify` that verifies the signer
certificate on an OCSP response ([CVE-2022-1343])
* Fixed a bug where the RC4-MD5 ciphersuite incorrectly used the
AAD data as the MAC key ([CVE-2022-1434])
* Fix a bug in the OPENSSL_LH_flush() function that breaks reuse of the memory
occuppied by the removed hash table entries ([CVE-2022-1473])
### Major changes between OpenSSL 3.0.1 and OpenSSL 3.0.2 [15 Mar 2022]
* Fixed a bug in the BN_mod_sqrt() function that can cause it to loop forever
for non-prime moduli ([CVE-2022-0778])
### Major changes between OpenSSL 3.0.0 and OpenSSL 3.0.1 [14 Dec 2021]
* Fixed invalid handling of X509_verify_cert() internal errors in libssl
([CVE-2021-4044])
* Allow fetching an operation from the provider that owns an unexportable key
as a fallback if that is still allowed by the property query.
### Major changes between OpenSSL 1.1.1 and OpenSSL 3.0.0 [7 sep 2021]
* Enhanced 'openssl list' with many new options.
* Added migration guide to man7.
* Implemented support for fully "pluggable" TLSv1.3 groups.
* Added suport for Kernel TLS (KTLS).
* Changed the license to the Apache License v2.0.
* Moved all variations of the EVP ciphers CAST5, BF, IDEA, SEED, RC2,
RC4, RC5, and DES to the legacy provider.
* Moved the EVP digests MD2, MD4, MDC2, WHIRLPOOL and RIPEMD-160 to the legacy
provider.
* Added convenience functions for generating asymmetric key pairs.
* Deprecated the `OCSP_REQ_CTX` type and functions.
* Deprecated the `EC_KEY` and `EC_KEY_METHOD` types and functions.
* Deprecated the `RSA` and `RSA_METHOD` types and functions.
* Deprecated the `DSA` and `DSA_METHOD` types and functions.
* Deprecated the `DH` and `DH_METHOD` types and functions.
* Deprecated the `ERR_load_` functions.
* Remove the `RAND_DRBG` API.
* Deprecated the `ENGINE` API.
* Added `OSSL_LIB_CTX`, a libcrypto library context.
* Added various `_ex` functions to the OpenSSL API that support using
a non-default `OSSL_LIB_CTX`.
* Interactive mode is removed from the 'openssl' program.
* The X25519, X448, Ed25519, Ed448, SHAKE128 and SHAKE256 algorithms are
included in the FIPS provider.
* X509 certificates signed using SHA1 are no longer allowed at security
level 1 or higher. The default security level for TLS is 1, so
certificates signed using SHA1 are by default no longer trusted to
authenticate servers or clients.
* enable-crypto-mdebug and enable-crypto-mdebug-backtrace were mostly
disabled; the project uses address sanitize/leak-detect instead.
* Added a Certificate Management Protocol (CMP, RFC 4210) implementation
also covering CRMF (RFC 4211) and HTTP transfer (RFC 6712).
It is part of the crypto lib and adds a 'cmp' app with a demo configuration.
All widely used CMP features are supported for both clients and servers.
* Added a proper HTTP client supporting GET with optional redirection, POST,
arbitrary request and response content types, TLS, persistent connections,
connections via HTTP(s) proxies, connections and exchange via user-defined
BIOs (allowing implicit connections), and timeout checks.
* Added util/check-format.pl for checking adherence to the coding guidelines.
* Added OSSL_ENCODER, a generic encoder API.
* Added OSSL_DECODER, a generic decoder API.
* Added OSSL_PARAM_BLD, an easier to use API to OSSL_PARAM.
* Added error raising macros, ERR_raise() and ERR_raise_data().
* Deprecated ERR_put_error(), ERR_get_error_line(), ERR_get_error_line_data(),
ERR_peek_error_line_data(), ERR_peek_last_error_line_data() and
ERR_func_error_string().
* Added OSSL_PROVIDER_available(), to check provider availibility.
* Added 'openssl mac' that uses the EVP_MAC API.
* Added 'openssl kdf' that uses the EVP_KDF API.
* Add OPENSSL_info() and 'openssl info' to get built-in data.
* Add support for enabling instrumentation through trace and debug
output.
* Changed our version number scheme and set the next major release to
3.0.0
* Added EVP_MAC, an EVP layer MAC API, and a generic EVP_PKEY to EVP_MAC
bridge. Supported MACs are: BLAKE2, CMAC, GMAC, HMAC, KMAC, POLY1305
and SIPHASH.
* Removed the heartbeat message in DTLS feature.
* Added EVP_KDF, an EVP layer KDF and PRF API, and a generic EVP_PKEY to
EVP_KDF bridge. Supported KDFs are: HKDF, KBKDF, KRB5 KDF, PBKDF2,
PKCS12 KDF, SCRYPT, SSH KDF, SSKDF, TLS1 PRF, X9.42 KDF and X9.63 KDF.
* All of the low-level MD2, MD4, MD5, MDC2, RIPEMD160, SHA1, SHA224,
SHA256, SHA384, SHA512 and Whirlpool digest functions have been
deprecated.
* All of the low-level AES, Blowfish, Camellia, CAST, DES, IDEA, RC2,
RC4, RC5 and SEED cipher functions have been deprecated.
* All of the low-level DH, DSA, ECDH, ECDSA and RSA public key functions
have been deprecated.
* SSL 3, TLS 1.0, TLS 1.1, and DTLS 1.0 only work at security level 0,
except when RSA key exchange without SHA1 is used.
* Added providers, a new pluggability concept that will replace the
ENGINE API and ENGINE implementations.
OpenSSL 1.1.1
-------------
### Major changes between OpenSSL 1.1.1k and OpenSSL 1.1.1l [24 Aug 2021]
* Fixed an SM2 Decryption Buffer Overflow ([CVE-2021-3711])
* Fixed various read buffer overruns processing ASN.1 strings ([CVE-2021-3712])
### Major changes between OpenSSL 1.1.1j and OpenSSL 1.1.1k [25 Mar 2021]
* Fixed a problem with verifying a certificate chain when using the
X509_V_FLAG_X509_STRICT flag ([CVE-2021-3450])
* Fixed an issue where an OpenSSL TLS server may crash if sent a maliciously
crafted renegotiation ClientHello message from a client ([CVE-2021-3449])
### Major changes between OpenSSL 1.1.1i and OpenSSL 1.1.1j [16 Feb 2021]
* Fixed a NULL pointer deref in the X509_issuer_and_serial_hash()
function ([CVE-2021-23841])
* Fixed the RSA_padding_check_SSLv23() function and the RSA_SSLV23_PADDING
padding mode to correctly check for rollback attacks
* Fixed an overflow in the EVP_CipherUpdate, EVP_EncryptUpdate and
EVP_DecryptUpdate functions ([CVE-2021-23840])
* Fixed SRP_Calc_client_key so that it runs in constant time
### Major changes between OpenSSL 1.1.1h and OpenSSL 1.1.1i [8 Dec 2020]
* Fixed NULL pointer deref in GENERAL_NAME_cmp ([CVE-2020-1971])
### Major changes between OpenSSL 1.1.1g and OpenSSL 1.1.1h [22 Sep 2020]
* Disallow explicit curve parameters in verifications chains when
X509_V_FLAG_X509_STRICT is used
* Enable 'MinProtocol' and 'MaxProtocol' to configure both TLS and DTLS
contexts
* Oracle Developer Studio will start reporting deprecation warnings
### Major changes between OpenSSL 1.1.1f and OpenSSL 1.1.1g [21 Apr 2020]
* Fixed segmentation fault in SSL_check_chain() ([CVE-2020-1967])
### Major changes between OpenSSL 1.1.1e and OpenSSL 1.1.1f [31 Mar 2020]
* Revert the unexpected EOF reporting via SSL_ERROR_SSL
### Major changes between OpenSSL 1.1.1d and OpenSSL 1.1.1e [17 Mar 2020]
* Fixed an overflow bug in the x64_64 Montgomery squaring procedure
used in exponentiation with 512-bit moduli ([CVE-2019-1551])
### Major changes between OpenSSL 1.1.1c and OpenSSL 1.1.1d [10 Sep 2019]
* Fixed a fork protection issue ([CVE-2019-1549])
* Fixed a padding oracle in PKCS7_dataDecode and CMS_decrypt_set1_pkey
([CVE-2019-1563])
* For built-in EC curves, ensure an EC_GROUP built from the curve name is
used even when parsing explicit parameters
* Compute ECC cofactors if not provided during EC_GROUP construction
([CVE-2019-1547])
* Early start up entropy quality from the DEVRANDOM seed source has been
improved for older Linux systems
* Correct the extended master secret constant on EBCDIC systems
* Use Windows installation paths in the mingw builds ([CVE-2019-1552])
* Changed DH_check to accept parameters with order q and 2q subgroups
* Significantly reduce secure memory usage by the randomness pools
* Revert the DEVRANDOM_WAIT feature for Linux systems
### Major changes between OpenSSL 1.1.1b and OpenSSL 1.1.1c [28 May 2019]
* Prevent over long nonces in ChaCha20-Poly1305 ([CVE-2019-1543])
### Major changes between OpenSSL 1.1.1a and OpenSSL 1.1.1b [26 Feb 2019]
* Change the info callback signals for the start and end of a post-handshake
message exchange in TLSv1.3.
* Fix a bug in DTLS over SCTP. This breaks interoperability with older
versions of OpenSSL like OpenSSL 1.1.0 and OpenSSL 1.0.2.
### Major changes between OpenSSL 1.1.1 and OpenSSL 1.1.1a [20 Nov 2018]
* Timing vulnerability in DSA signature generation ([CVE-2018-0734])
* Timing vulnerability in ECDSA signature generation ([CVE-2018-0735])
### Major changes between OpenSSL 1.1.0i and OpenSSL 1.1.1 [11 Sep 2018]
* Support for TLSv1.3 added. The TLSv1.3 implementation includes:
* Fully compliant implementation of RFC8446 (TLSv1.3) on by default
* Early data (0-RTT)
* Post-handshake authentication and key update
* Middlebox Compatibility Mode
* TLSv1.3 PSKs
* Support for all five RFC8446 ciphersuites
* RSA-PSS signature algorithms (backported to TLSv1.2)
* Configurable session ticket support
* Stateless server support
* Rewrite of the packet construction code for "safer" packet handling
* Rewrite of the extension handling code
For further important information, see the [TLS1.3 page](
https://wiki.openssl.org/index.php/TLS1.3) in the OpenSSL Wiki.
* Complete rewrite of the OpenSSL random number generator to introduce the
following capabilities
* The default RAND method now utilizes an AES-CTR DRBG according to
NIST standard SP 800-90Ar1.
* Support for multiple DRBG instances with seed chaining.
* There is a public and private DRBG instance.
* The DRBG instances are fork-safe.
* Keep all global DRBG instances on the secure heap if it is enabled.
* The public and private DRBG instance are per thread for lock free
operation
* Support for various new cryptographic algorithms including:
* SHA3
* SHA512/224 and SHA512/256
* EdDSA (both Ed25519 and Ed448) including X509 and TLS support
* X448 (adding to the existing X25519 support in 1.1.0)
* Multi-prime RSA
* SM2
* SM3
* SM4
* SipHash
* ARIA (including TLS support)
* Significant Side-Channel attack security improvements
* Add a new ClientHello callback to provide the ability to adjust the SSL
object at an early stage.
* Add 'Maximum Fragment Length' TLS extension negotiation and support
* A new STORE module, which implements a uniform and URI based reader of
stores that can contain keys, certificates, CRLs and numerous other
objects.
* Move the display of configuration data to configdata.pm.
* Allow GNU style "make variables" to be used with Configure.
* Claim the namespaces OSSL and OPENSSL, represented as symbol prefixes
* Rewrite of devcrypto engine
OpenSSL 1.1.0
-------------
### Major changes between OpenSSL 1.1.0k and OpenSSL 1.1.0l [10 Sep 2019]
* Fixed a padding oracle in PKCS7_dataDecode and CMS_decrypt_set1_pkey
([CVE-2019-1563])
* For built-in EC curves, ensure an EC_GROUP built from the curve name is
used even when parsing explicit parameters
* Compute ECC cofactors if not provided during EC_GROUP construction
([CVE-2019-1547])
* Use Windows installation paths in the mingw builds ([CVE-2019-1552])
### Major changes between OpenSSL 1.1.0j and OpenSSL 1.1.0k [28 May 2019]
* Prevent over long nonces in ChaCha20-Poly1305 ([CVE-2019-1543])
### Major changes between OpenSSL 1.1.0i and OpenSSL 1.1.0j [20 Nov 2018]
* Timing vulnerability in DSA signature generation ([CVE-2018-0734])
* Timing vulnerability in ECDSA signature generation ([CVE-2018-0735])
### Major changes between OpenSSL 1.1.0h and OpenSSL 1.1.0i [14 Aug 2018]
* Client DoS due to large DH parameter ([CVE-2018-0732])
* Cache timing vulnerability in RSA Key Generation ([CVE-2018-0737])
### Major changes between OpenSSL 1.1.0g and OpenSSL 1.1.0h [27 Mar 2018]
* Constructed ASN.1 types with a recursive definition could exceed the
stack ([CVE-2018-0739])
* Incorrect CRYPTO_memcmp on HP-UX PA-RISC ([CVE-2018-0733])
* rsaz_1024_mul_avx2 overflow bug on x86_64 ([CVE-2017-3738])
### Major changes between OpenSSL 1.1.0f and OpenSSL 1.1.0g [2 Nov 2017]
* bn_sqrx8x_internal carry bug on x86_64 ([CVE-2017-3736])
* Malformed X.509 IPAddressFamily could cause OOB read ([CVE-2017-3735])
### Major changes between OpenSSL 1.1.0e and OpenSSL 1.1.0f [25 May 2017]
* config now recognises 64-bit mingw and chooses mingw64 instead of mingw
### Major changes between OpenSSL 1.1.0d and OpenSSL 1.1.0e [16 Feb 2017]
* Encrypt-Then-Mac renegotiation crash ([CVE-2017-3733])
### Major changes between OpenSSL 1.1.0c and OpenSSL 1.1.0d [26 Jan 2017]
* Truncated packet could crash via OOB read ([CVE-2017-3731])
* Bad (EC)DHE parameters cause a client crash ([CVE-2017-3730])
* BN_mod_exp may produce incorrect results on x86_64 ([CVE-2017-3732])
### Major changes between OpenSSL 1.1.0b and OpenSSL 1.1.0c [10 Nov 2016]
* ChaCha20/Poly1305 heap-buffer-overflow ([CVE-2016-7054])
* CMS Null dereference ([CVE-2016-7053])
* Montgomery multiplication may produce incorrect results ([CVE-2016-7055])
### Major changes between OpenSSL 1.1.0a and OpenSSL 1.1.0b [26 Sep 2016]
* Fix Use After Free for large message sizes ([CVE-2016-6309])
### Major changes between OpenSSL 1.1.0 and OpenSSL 1.1.0a [22 Sep 2016]
* OCSP Status Request extension unbounded memory growth ([CVE-2016-6304])
* SSL_peek() hang on empty record ([CVE-2016-6305])
* Excessive allocation of memory in tls_get_message_header()
([CVE-2016-6307])
* Excessive allocation of memory in dtls1_preprocess_fragment()
([CVE-2016-6308])
### Major changes between OpenSSL 1.0.2h and OpenSSL 1.1.0 [25 Aug 2016]
* Copyright text was shrunk to a boilerplate that points to the license
* "shared" builds are now the default when possible
* Added support for "pipelining"
* Added the AFALG engine
* New threading API implemented
* Support for ChaCha20 and Poly1305 added to libcrypto and libssl
* Support for extended master secret
* CCM ciphersuites
* Reworked test suite, now based on perl, Test::Harness and Test::More
* *Most* libcrypto and libssl public structures were made opaque,
including:
BIGNUM and associated types, EC_KEY and EC_KEY_METHOD,
DH and DH_METHOD, DSA and DSA_METHOD, RSA and RSA_METHOD,
BIO and BIO_METHOD, EVP_MD_CTX, EVP_MD, EVP_CIPHER_CTX,
EVP_CIPHER, EVP_PKEY and associated types, HMAC_CTX,
X509, X509_CRL, X509_OBJECT, X509_STORE_CTX, X509_STORE,
X509_LOOKUP, X509_LOOKUP_METHOD
* libssl internal structures made opaque
* SSLv2 support removed
* Kerberos ciphersuite support removed
* RC4 removed from DEFAULT ciphersuites in libssl
* 40 and 56 bit cipher support removed from libssl
* All public header files moved to include/openssl, no more symlinking
* SSL/TLS state machine, version negotiation and record layer rewritten
* EC revision: now operations use new EC_KEY_METHOD.
* Support for OCB mode added to libcrypto
* Support for asynchronous crypto operations added to libcrypto and libssl
* Deprecated interfaces can now be disabled at build time either
relative to the latest release via the "no-deprecated" Configure
argument, or via the "--api=1.1.0|1.0.0|0.9.8" option.
* Application software can be compiled with -DOPENSSL_API_COMPAT=version
to ensure that features deprecated in that version are not exposed.
* Support for RFC6698/RFC7671 DANE TLSA peer authentication
* Change of Configure to use --prefix as the main installation
directory location rather than --openssldir. The latter becomes
the directory for certs, private key and openssl.cnf exclusively.
* Reworked BIO networking library, with full support for IPv6.
* New "unified" build system
* New security levels
* Support for scrypt algorithm
* Support for X25519
* Extended SSL_CONF support using configuration files
* KDF algorithm support. Implement TLS PRF as a KDF.
* Support for Certificate Transparency
* HKDF support.
OpenSSL 1.0.2
-------------
### Major changes between OpenSSL 1.0.2s and OpenSSL 1.0.2t [10 Sep 2019]
* Fixed a padding oracle in PKCS7_dataDecode and CMS_decrypt_set1_pkey
([CVE-2019-1563])
* For built-in EC curves, ensure an EC_GROUP built from the curve name is
used even when parsing explicit parameters
* Compute ECC cofactors if not provided during EC_GROUP construction
([CVE-2019-1547])
* Document issue with installation paths in diverse Windows builds
([CVE-2019-1552])
### Major changes between OpenSSL 1.0.2r and OpenSSL 1.0.2s [28 May 2019]
* None
### Major changes between OpenSSL 1.0.2q and OpenSSL 1.0.2r [26 Feb 2019]
* 0-byte record padding oracle ([CVE-2019-1559])
### Major changes between OpenSSL 1.0.2p and OpenSSL 1.0.2q [20 Nov 2018]
* Microarchitecture timing vulnerability in ECC scalar multiplication ([CVE-2018-5407])
* Timing vulnerability in DSA signature generation ([CVE-2018-0734])
### Major changes between OpenSSL 1.0.2o and OpenSSL 1.0.2p [14 Aug 2018]
* Client DoS due to large DH parameter ([CVE-2018-0732])
* Cache timing vulnerability in RSA Key Generation ([CVE-2018-0737])
### Major changes between OpenSSL 1.0.2n and OpenSSL 1.0.2o [27 Mar 2018]
* Constructed ASN.1 types with a recursive definition could exceed the
stack ([CVE-2018-0739])
### Major changes between OpenSSL 1.0.2m and OpenSSL 1.0.2n [7 Dec 2017]
* Read/write after SSL object in error state ([CVE-2017-3737])
* rsaz_1024_mul_avx2 overflow bug on x86_64 ([CVE-2017-3738])
### Major changes between OpenSSL 1.0.2l and OpenSSL 1.0.2m [2 Nov 2017]
* bn_sqrx8x_internal carry bug on x86_64 ([CVE-2017-3736])
* Malformed X.509 IPAddressFamily could cause OOB read ([CVE-2017-3735])
### Major changes between OpenSSL 1.0.2k and OpenSSL 1.0.2l [25 May 2017]
* config now recognises 64-bit mingw and chooses mingw64 instead of mingw
### Major changes between OpenSSL 1.0.2j and OpenSSL 1.0.2k [26 Jan 2017]
* Truncated packet could crash via OOB read ([CVE-2017-3731])
* BN_mod_exp may produce incorrect results on x86_64 ([CVE-2017-3732])
* Montgomery multiplication may produce incorrect results ([CVE-2016-7055])
### Major changes between OpenSSL 1.0.2i and OpenSSL 1.0.2j [26 Sep 2016]
* Missing CRL sanity check ([CVE-2016-7052])
### Major changes between OpenSSL 1.0.2h and OpenSSL 1.0.2i [22 Sep 2016]
* OCSP Status Request extension unbounded memory growth ([CVE-2016-6304])
* SWEET32 Mitigation ([CVE-2016-2183])
* OOB write in MDC2_Update() ([CVE-2016-6303])
* Malformed SHA512 ticket DoS ([CVE-2016-6302])
* OOB write in BN_bn2dec() ([CVE-2016-2182])
* OOB read in TS_OBJ_print_bio() ([CVE-2016-2180])
* Pointer arithmetic undefined behaviour ([CVE-2016-2177])
* Constant time flag not preserved in DSA signing ([CVE-2016-2178])
* DTLS buffered message DoS ([CVE-2016-2179])
* DTLS replay protection DoS ([CVE-2016-2181])
* Certificate message OOB reads ([CVE-2016-6306])
### Major changes between OpenSSL 1.0.2g and OpenSSL 1.0.2h [3 May 2016]
* Prevent padding oracle in AES-NI CBC MAC check ([CVE-2016-2107])
* Fix EVP_EncodeUpdate overflow ([CVE-2016-2105])
* Fix EVP_EncryptUpdate overflow ([CVE-2016-2106])
* Prevent ASN.1 BIO excessive memory allocation ([CVE-2016-2109])
* EBCDIC overread ([CVE-2016-2176])
* Modify behavior of ALPN to invoke callback after SNI/servername
callback, such that updates to the SSL_CTX affect ALPN.
* Remove LOW from the DEFAULT cipher list. This removes singles DES from
the default.
* Only remove the SSLv2 methods with the no-ssl2-method option.
### Major changes between OpenSSL 1.0.2f and OpenSSL 1.0.2g [1 Mar 2016]
* Disable weak ciphers in SSLv3 and up in default builds of OpenSSL.
* Disable SSLv2 default build, default negotiation and weak ciphers
([CVE-2016-0800])
* Fix a double-free in DSA code ([CVE-2016-0705])
* Disable SRP fake user seed to address a server memory leak
([CVE-2016-0798])
* Fix BN_hex2bn/BN_dec2bn NULL pointer deref/heap corruption
([CVE-2016-0797])
* Fix memory issues in BIO_*printf functions ([CVE-2016-0799])
* Fix side channel attack on modular exponentiation ([CVE-2016-0702])
### Major changes between OpenSSL 1.0.2e and OpenSSL 1.0.2f [28 Jan 2016]
* DH small subgroups ([CVE-2016-0701])
* SSLv2 doesn't block disabled ciphers ([CVE-2015-3197])
### Major changes between OpenSSL 1.0.2d and OpenSSL 1.0.2e [3 Dec 2015]
* BN_mod_exp may produce incorrect results on x86_64 ([CVE-2015-3193])
* Certificate verify crash with missing PSS parameter ([CVE-2015-3194])
* X509_ATTRIBUTE memory leak ([CVE-2015-3195])
* Rewrite EVP_DecodeUpdate (base64 decoding) to fix several bugs
* In DSA_generate_parameters_ex, if the provided seed is too short,
return an error
### Major changes between OpenSSL 1.0.2c and OpenSSL 1.0.2d [9 Jul 2015]
* Alternate chains certificate forgery ([CVE-2015-1793])
* Race condition handling PSK identify hint ([CVE-2015-3196])
### Major changes between OpenSSL 1.0.2b and OpenSSL 1.0.2c [12 Jun 2015]
* Fix HMAC ABI incompatibility
### Major changes between OpenSSL 1.0.2a and OpenSSL 1.0.2b [11 Jun 2015]
* Malformed ECParameters causes infinite loop ([CVE-2015-1788])
* Exploitable out-of-bounds read in X509_cmp_time ([CVE-2015-1789])
* PKCS7 crash with missing EnvelopedContent ([CVE-2015-1790])
* CMS verify infinite loop with unknown hash function ([CVE-2015-1792])
* Race condition handling NewSessionTicket ([CVE-2015-1791])
### Major changes between OpenSSL 1.0.2 and OpenSSL 1.0.2a [19 Mar 2015]
* OpenSSL 1.0.2 ClientHello sigalgs DoS fix ([CVE-2015-0291])
* Multiblock corrupted pointer fix ([CVE-2015-0290])
* Segmentation fault in DTLSv1_listen fix ([CVE-2015-0207])
* Segmentation fault in ASN1_TYPE_cmp fix ([CVE-2015-0286])
* Segmentation fault for invalid PSS parameters fix ([CVE-2015-0208])
* ASN.1 structure reuse memory corruption fix ([CVE-2015-0287])
* PKCS7 NULL pointer dereferences fix ([CVE-2015-0289])
* DoS via reachable assert in SSLv2 servers fix ([CVE-2015-0293])
* Empty CKE with client auth and DHE fix ([CVE-2015-1787])
* Handshake with unseeded PRNG fix ([CVE-2015-0285])
* Use After Free following d2i_ECPrivatekey error fix ([CVE-2015-0209])
* X509_to_X509_REQ NULL pointer deref fix ([CVE-2015-0288])
* Removed the export ciphers from the DEFAULT ciphers
### Major changes between OpenSSL 1.0.1l and OpenSSL 1.0.2 [22 Jan 2015]
* Suite B support for TLS 1.2 and DTLS 1.2
* Support for DTLS 1.2
* TLS automatic EC curve selection.
* API to set TLS supported signature algorithms and curves
* SSL_CONF configuration API.
* TLS Brainpool support.
* ALPN support.
* CMS support for RSA-PSS, RSA-OAEP, ECDH and X9.42 DH.
OpenSSL 1.0.1
-------------
### Major changes between OpenSSL 1.0.1t and OpenSSL 1.0.1u [22 Sep 2016]
* OCSP Status Request extension unbounded memory growth ([CVE-2016-6304])
* SWEET32 Mitigation ([CVE-2016-2183])
* OOB write in MDC2_Update() ([CVE-2016-6303])
* Malformed SHA512 ticket DoS ([CVE-2016-6302])
* OOB write in BN_bn2dec() ([CVE-2016-2182])
* OOB read in TS_OBJ_print_bio() ([CVE-2016-2180])
* Pointer arithmetic undefined behaviour ([CVE-2016-2177])
* Constant time flag not preserved in DSA signing ([CVE-2016-2178])
* DTLS buffered message DoS ([CVE-2016-2179])
* DTLS replay protection DoS ([CVE-2016-2181])
* Certificate message OOB reads ([CVE-2016-6306])
### Major changes between OpenSSL 1.0.1s and OpenSSL 1.0.1t [3 May 2016]
* Prevent padding oracle in AES-NI CBC MAC check ([CVE-2016-2107])
* Fix EVP_EncodeUpdate overflow ([CVE-2016-2105])
* Fix EVP_EncryptUpdate overflow ([CVE-2016-2106])
* Prevent ASN.1 BIO excessive memory allocation ([CVE-2016-2109])
* EBCDIC overread ([CVE-2016-2176])
* Modify behavior of ALPN to invoke callback after SNI/servername
callback, such that updates to the SSL_CTX affect ALPN.
* Remove LOW from the DEFAULT cipher list. This removes singles DES from
the default.
* Only remove the SSLv2 methods with the no-ssl2-method option.
### Major changes between OpenSSL 1.0.1r and OpenSSL 1.0.1s [1 Mar 2016]
* Disable weak ciphers in SSLv3 and up in default builds of OpenSSL.
* Disable SSLv2 default build, default negotiation and weak ciphers
([CVE-2016-0800])
* Fix a double-free in DSA code ([CVE-2016-0705])
* Disable SRP fake user seed to address a server memory leak
([CVE-2016-0798])
* Fix BN_hex2bn/BN_dec2bn NULL pointer deref/heap corruption
([CVE-2016-0797])
* Fix memory issues in BIO_*printf functions ([CVE-2016-0799])
* Fix side channel attack on modular exponentiation ([CVE-2016-0702])
### Major changes between OpenSSL 1.0.1q and OpenSSL 1.0.1r [28 Jan 2016]
* Protection for DH small subgroup attacks
* SSLv2 doesn't block disabled ciphers ([CVE-2015-3197])
### Major changes between OpenSSL 1.0.1p and OpenSSL 1.0.1q [3 Dec 2015]
* Certificate verify crash with missing PSS parameter ([CVE-2015-3194])
* X509_ATTRIBUTE memory leak ([CVE-2015-3195])
* Rewrite EVP_DecodeUpdate (base64 decoding) to fix several bugs
* In DSA_generate_parameters_ex, if the provided seed is too short,
return an error
### Major changes between OpenSSL 1.0.1o and OpenSSL 1.0.1p [9 Jul 2015]
* Alternate chains certificate forgery ([CVE-2015-1793])
* Race condition handling PSK identify hint ([CVE-2015-3196])
### Major changes between OpenSSL 1.0.1n and OpenSSL 1.0.1o [12 Jun 2015]
* Fix HMAC ABI incompatibility
### Major changes between OpenSSL 1.0.1m and OpenSSL 1.0.1n [11 Jun 2015]
* Malformed ECParameters causes infinite loop ([CVE-2015-1788])
* Exploitable out-of-bounds read in X509_cmp_time ([CVE-2015-1789])
* PKCS7 crash with missing EnvelopedContent ([CVE-2015-1790])
* CMS verify infinite loop with unknown hash function ([CVE-2015-1792])
* Race condition handling NewSessionTicket ([CVE-2015-1791])
### Major changes between OpenSSL 1.0.1l and OpenSSL 1.0.1m [19 Mar 2015]
* Segmentation fault in ASN1_TYPE_cmp fix ([CVE-2015-0286])
* ASN.1 structure reuse memory corruption fix ([CVE-2015-0287])
* PKCS7 NULL pointer dereferences fix ([CVE-2015-0289])
* DoS via reachable assert in SSLv2 servers fix ([CVE-2015-0293])
* Use After Free following d2i_ECPrivatekey error fix ([CVE-2015-0209])
* X509_to_X509_REQ NULL pointer deref fix ([CVE-2015-0288])
* Removed the export ciphers from the DEFAULT ciphers
### Major changes between OpenSSL 1.0.1k and OpenSSL 1.0.1l [15 Jan 2015]
* Build fixes for the Windows and OpenVMS platforms
### Major changes between OpenSSL 1.0.1j and OpenSSL 1.0.1k [8 Jan 2015]
* Fix for [CVE-2014-3571]
* Fix for [CVE-2015-0206]
* Fix for [CVE-2014-3569]
* Fix for [CVE-2014-3572]
* Fix for [CVE-2015-0204]
* Fix for [CVE-2015-0205]
* Fix for [CVE-2014-8275]
* Fix for [CVE-2014-3570]
### Major changes between OpenSSL 1.0.1i and OpenSSL 1.0.1j [15 Oct 2014]
* Fix for [CVE-2014-3513]
* Fix for [CVE-2014-3567]
* Mitigation for [CVE-2014-3566] (SSL protocol vulnerability)
* Fix for [CVE-2014-3568]
### Major changes between OpenSSL 1.0.1h and OpenSSL 1.0.1i [6 Aug 2014]
* Fix for [CVE-2014-3512]
* Fix for [CVE-2014-3511]
* Fix for [CVE-2014-3510]
* Fix for [CVE-2014-3507]
* Fix for [CVE-2014-3506]
* Fix for [CVE-2014-3505]
* Fix for [CVE-2014-3509]
* Fix for [CVE-2014-5139]
* Fix for [CVE-2014-3508]
### Major changes between OpenSSL 1.0.1g and OpenSSL 1.0.1h [5 Jun 2014]
* Fix for [CVE-2014-0224]
* Fix for [CVE-2014-0221]
* Fix for [CVE-2014-0198]
* Fix for [CVE-2014-0195]
* Fix for [CVE-2014-3470]
* Fix for [CVE-2010-5298]
### Major changes between OpenSSL 1.0.1f and OpenSSL 1.0.1g [7 Apr 2014]
* Fix for [CVE-2014-0160]
* Add TLS padding extension workaround for broken servers.
* Fix for [CVE-2014-0076]
### Major changes between OpenSSL 1.0.1e and OpenSSL 1.0.1f [6 Jan 2014]
* Don't include gmt_unix_time in TLS server and client random values
* Fix for TLS record tampering bug ([CVE-2013-4353])
* Fix for TLS version checking bug ([CVE-2013-6449])
* Fix for DTLS retransmission bug ([CVE-2013-6450])
### Major changes between OpenSSL 1.0.1d and OpenSSL 1.0.1e [11 Feb 2013]
* Corrected fix for ([CVE-2013-0169])
### Major changes between OpenSSL 1.0.1c and OpenSSL 1.0.1d [4 Feb 2013]
* Fix renegotiation in TLS 1.1, 1.2 by using the correct TLS version.
* Include the fips configuration module.
* Fix OCSP bad key DoS attack ([CVE-2013-0166])
* Fix for SSL/TLS/DTLS CBC plaintext recovery attack ([CVE-2013-0169])
* Fix for TLS AESNI record handling flaw ([CVE-2012-2686])
### Major changes between OpenSSL 1.0.1b and OpenSSL 1.0.1c [10 May 2012]
* Fix TLS/DTLS record length checking bug ([CVE-2012-2333])
* Don't attempt to use non-FIPS composite ciphers in FIPS mode.
### Major changes between OpenSSL 1.0.1a and OpenSSL 1.0.1b [26 Apr 2012]
* Fix compilation error on non-x86 platforms.
* Make FIPS capable OpenSSL ciphers work in non-FIPS mode.
* Fix SSL_OP_NO_TLSv1_1 clash with SSL_OP_ALL in OpenSSL 1.0.0
### Major changes between OpenSSL 1.0.1 and OpenSSL 1.0.1a [19 Apr 2012]
* Fix for ASN1 overflow bug ([CVE-2012-2110])
* Workarounds for some servers that hang on long client hellos.
* Fix SEGV in AES code.
### Major changes between OpenSSL 1.0.0h and OpenSSL 1.0.1 [14 Mar 2012]
* TLS/DTLS heartbeat support.
* SCTP support.
* RFC 5705 TLS key material exporter.
* RFC 5764 DTLS-SRTP negotiation.
* Next Protocol Negotiation.
* PSS signatures in certificates, requests and CRLs.
* Support for password based recipient info for CMS.
* Support TLS v1.2 and TLS v1.1.
* Preliminary FIPS capability for unvalidated 2.0 FIPS module.
* SRP support.
OpenSSL 1.0.0
-------------
### Major changes between OpenSSL 1.0.0s and OpenSSL 1.0.0t [3 Dec 2015]
* X509_ATTRIBUTE memory leak (([CVE-2015-3195]))
* Race condition handling PSK identify hint ([CVE-2015-3196])
### Major changes between OpenSSL 1.0.0r and OpenSSL 1.0.0s [11 Jun 2015]
* Malformed ECParameters causes infinite loop ([CVE-2015-1788])
* Exploitable out-of-bounds read in X509_cmp_time ([CVE-2015-1789])
* PKCS7 crash with missing EnvelopedContent ([CVE-2015-1790])
* CMS verify infinite loop with unknown hash function ([CVE-2015-1792])
* Race condition handling NewSessionTicket ([CVE-2015-1791])
### Major changes between OpenSSL 1.0.0q and OpenSSL 1.0.0r [19 Mar 2015]
* Segmentation fault in ASN1_TYPE_cmp fix ([CVE-2015-0286])
* ASN.1 structure reuse memory corruption fix ([CVE-2015-0287])
* PKCS7 NULL pointer dereferences fix ([CVE-2015-0289])
* DoS via reachable assert in SSLv2 servers fix ([CVE-2015-0293])
* Use After Free following d2i_ECPrivatekey error fix ([CVE-2015-0209])
* X509_to_X509_REQ NULL pointer deref fix ([CVE-2015-0288])
* Removed the export ciphers from the DEFAULT ciphers
### Major changes between OpenSSL 1.0.0p and OpenSSL 1.0.0q [15 Jan 2015]
* Build fixes for the Windows and OpenVMS platforms
### Major changes between OpenSSL 1.0.0o and OpenSSL 1.0.0p [8 Jan 2015]
* Fix for [CVE-2014-3571]
* Fix for [CVE-2015-0206]
* Fix for [CVE-2014-3569]
* Fix for [CVE-2014-3572]
* Fix for [CVE-2015-0204]
* Fix for [CVE-2015-0205]
* Fix for [CVE-2014-8275]
* Fix for [CVE-2014-3570]
### Major changes between OpenSSL 1.0.0n and OpenSSL 1.0.0o [15 Oct 2014]
* Fix for [CVE-2014-3513]
* Fix for [CVE-2014-3567]
* Mitigation for [CVE-2014-3566] (SSL protocol vulnerability)
* Fix for [CVE-2014-3568]
### Major changes between OpenSSL 1.0.0m and OpenSSL 1.0.0n [6 Aug 2014]
* Fix for [CVE-2014-3510]
* Fix for [CVE-2014-3507]
* Fix for [CVE-2014-3506]
* Fix for [CVE-2014-3505]
* Fix for [CVE-2014-3509]
* Fix for [CVE-2014-3508]
Known issues in OpenSSL 1.0.0m:
* EAP-FAST and other applications using tls_session_secret_cb
won't resume sessions. Fixed in 1.0.0n-dev
* Compilation failure of s3_pkt.c on some platforms due to missing
`<limits.h>` include. Fixed in 1.0.0n-dev
### Major changes between OpenSSL 1.0.0l and OpenSSL 1.0.0m [5 Jun 2014]
* Fix for [CVE-2014-0224]
* Fix for [CVE-2014-0221]
* Fix for [CVE-2014-0198]
* Fix for [CVE-2014-0195]
* Fix for [CVE-2014-3470]
* Fix for [CVE-2014-0076]
* Fix for [CVE-2010-5298]
### Major changes between OpenSSL 1.0.0k and OpenSSL 1.0.0l [6 Jan 2014]
* Fix for DTLS retransmission bug ([CVE-2013-6450])
### Major changes between OpenSSL 1.0.0j and OpenSSL 1.0.0k [5 Feb 2013]
* Fix for SSL/TLS/DTLS CBC plaintext recovery attack ([CVE-2013-0169])
* Fix OCSP bad key DoS attack ([CVE-2013-0166])
### Major changes between OpenSSL 1.0.0i and OpenSSL 1.0.0j [10 May 2012]
* Fix DTLS record length checking bug ([CVE-2012-2333])
### Major changes between OpenSSL 1.0.0h and OpenSSL 1.0.0i [19 Apr 2012]
* Fix for ASN1 overflow bug ([CVE-2012-2110])
### Major changes between OpenSSL 1.0.0g and OpenSSL 1.0.0h [12 Mar 2012]
* Fix for CMS/PKCS#7 MMA ([CVE-2012-0884])
* Corrected fix for ([CVE-2011-4619])
* Various DTLS fixes.
### Major changes between OpenSSL 1.0.0f and OpenSSL 1.0.0g [18 Jan 2012]
* Fix for DTLS DoS issue ([CVE-2012-0050])
### Major changes between OpenSSL 1.0.0e and OpenSSL 1.0.0f [4 Jan 2012]
* Fix for DTLS plaintext recovery attack ([CVE-2011-4108])
* Clear block padding bytes of SSL 3.0 records ([CVE-2011-4576])
* Only allow one SGC handshake restart for SSL/TLS ([CVE-2011-4619])
* Check parameters are not NULL in GOST ENGINE ([CVE-2012-0027])
* Check for malformed RFC3779 data ([CVE-2011-4577])
### Major changes between OpenSSL 1.0.0d and OpenSSL 1.0.0e [6 Sep 2011]
* Fix for CRL vulnerability issue ([CVE-2011-3207])
* Fix for ECDH crashes ([CVE-2011-3210])
* Protection against EC timing attacks.
* Support ECDH ciphersuites for certificates using SHA2 algorithms.
* Various DTLS fixes.
### Major changes between OpenSSL 1.0.0c and OpenSSL 1.0.0d [8 Feb 2011]
* Fix for security issue ([CVE-2011-0014])
### Major changes between OpenSSL 1.0.0b and OpenSSL 1.0.0c [2 Dec 2010]
* Fix for security issue ([CVE-2010-4180])
* Fix for ([CVE-2010-4252])
* Fix mishandling of absent EC point format extension.
* Fix various platform compilation issues.
* Corrected fix for security issue ([CVE-2010-3864]).
### Major changes between OpenSSL 1.0.0a and OpenSSL 1.0.0b [16 Nov 2010]
* Fix for security issue ([CVE-2010-3864]).
* Fix for ([CVE-2010-2939])
* Fix WIN32 build system for GOST ENGINE.
### Major changes between OpenSSL 1.0.0 and OpenSSL 1.0.0a [1 Jun 2010]
* Fix for security issue ([CVE-2010-1633]).
* GOST MAC and CFB fixes.
### Major changes between OpenSSL 0.9.8n and OpenSSL 1.0.0 [29 Mar 2010]
* RFC3280 path validation: sufficient to process PKITS tests.
* Integrated support for PVK files and keyblobs.
* Change default private key format to PKCS#8.
* CMS support: able to process all examples in RFC4134
* Streaming ASN1 encode support for PKCS#7 and CMS.
* Multiple signer and signer add support for PKCS#7 and CMS.
* ASN1 printing support.
* Whirlpool hash algorithm added.
* RFC3161 time stamp support.
* New generalised public key API supporting ENGINE based algorithms.
* New generalised public key API utilities.
* New ENGINE supporting GOST algorithms.
* SSL/TLS GOST ciphersuite support.
* PKCS#7 and CMS GOST support.
* RFC4279 PSK ciphersuite support.
* Supported points format extension for ECC ciphersuites.
* ecdsa-with-SHA224/256/384/512 signature types.
* dsa-with-SHA224 and dsa-with-SHA256 signature types.
* Opaque PRF Input TLS extension support.
* Updated time routines to avoid OS limitations.
OpenSSL 0.9.x
-------------
### Major changes between OpenSSL 0.9.8m and OpenSSL 0.9.8n [24 Mar 2010]
* CFB cipher definition fixes.
* Fix security issues [CVE-2010-0740] and [CVE-2010-0433].
### Major changes between OpenSSL 0.9.8l and OpenSSL 0.9.8m [25 Feb 2010]
* Cipher definition fixes.
* Workaround for slow RAND_poll() on some WIN32 versions.
* Remove MD2 from algorithm tables.
* SPKAC handling fixes.
* Support for RFC5746 TLS renegotiation extension.
* Compression memory leak fixed.
* Compression session resumption fixed.
* Ticket and SNI coexistence fixes.
* Many fixes to DTLS handling.
### Major changes between OpenSSL 0.9.8k and OpenSSL 0.9.8l [5 Nov 2009]
* Temporary work around for [CVE-2009-3555]: disable renegotiation.
### Major changes between OpenSSL 0.9.8j and OpenSSL 0.9.8k [25 Mar 2009]
* Fix various build issues.
* Fix security issues [CVE-2009-0590], [CVE-2009-0591], [CVE-2009-0789]
### Major changes between OpenSSL 0.9.8i and OpenSSL 0.9.8j [7 Jan 2009]
* Fix security issue ([CVE-2008-5077])
* Merge FIPS 140-2 branch code.
### Major changes between OpenSSL 0.9.8g and OpenSSL 0.9.8h [28 May 2008]
* CryptoAPI ENGINE support.
* Various precautionary measures.
* Fix for bugs affecting certificate request creation.
* Support for local machine keyset attribute in PKCS#12 files.
### Major changes between OpenSSL 0.9.8f and OpenSSL 0.9.8g [19 Oct 2007]
* Backport of CMS functionality to 0.9.8.
* Fixes for bugs introduced with 0.9.8f.
### Major changes between OpenSSL 0.9.8e and OpenSSL 0.9.8f [11 Oct 2007]
* Add gcc 4.2 support.
* Add support for AES and SSE2 assembly language optimization
for VC++ build.
* Support for RFC4507bis and server name extensions if explicitly
selected at compile time.
* DTLS improvements.
* RFC4507bis support.
* TLS Extensions support.
### Major changes between OpenSSL 0.9.8d and OpenSSL 0.9.8e [23 Feb 2007]
* Various ciphersuite selection fixes.
* RFC3779 support.
### Major changes between OpenSSL 0.9.8c and OpenSSL 0.9.8d [28 Sep 2006]
* Introduce limits to prevent malicious key DoS ([CVE-2006-2940])
* Fix security issues [CVE-2006-2937], [CVE-2006-3737], [CVE-2006-4343]
* Changes to ciphersuite selection algorithm
### Major changes between OpenSSL 0.9.8b and OpenSSL 0.9.8c [5 Sep 2006]
* Fix Daniel Bleichenbacher forged signature attack, [CVE-2006-4339]
* New cipher Camellia
### Major changes between OpenSSL 0.9.8a and OpenSSL 0.9.8b [4 May 2006]
* Cipher string fixes.
* Fixes for VC++ 2005.
* Updated ECC cipher suite support.
* New functions EVP_CIPHER_CTX_new() and EVP_CIPHER_CTX_free().
* Zlib compression usage fixes.
* Built in dynamic engine compilation support on Win32.
* Fixes auto dynamic engine loading in Win32.
### Major changes between OpenSSL 0.9.8 and OpenSSL 0.9.8a [11 Oct 2005]
* Fix potential SSL 2.0 rollback ([CVE-2005-2969])
* Extended Windows CE support
### Major changes between OpenSSL 0.9.7g and OpenSSL 0.9.8 [5 Jul 2005]
* Major work on the BIGNUM library for higher efficiency and to
make operations more streamlined and less contradictory. This
is the result of a major audit of the BIGNUM library.
* Addition of BIGNUM functions for fields GF(2^m) and NIST
curves, to support the Elliptic Crypto functions.
* Major work on Elliptic Crypto; ECDH and ECDSA added, including
the use through EVP, X509 and ENGINE.
* New ASN.1 mini-compiler that's usable through the OpenSSL
configuration file.
* Added support for ASN.1 indefinite length constructed encoding.
* New PKCS#12 'medium level' API to manipulate PKCS#12 files.
* Complete rework of shared library construction and linking
programs with shared or static libraries, through a separate
Makefile.shared.
* Rework of the passing of parameters from one Makefile to another.
* Changed ENGINE framework to load dynamic engine modules
automatically from specifically given directories.
* New structure and ASN.1 functions for CertificatePair.
* Changed the ZLIB compression method to be stateful.
* Changed the key-generation and primality testing "progress"
mechanism to take a structure that contains the ticker
function and an argument.
* New engine module: GMP (performs private key exponentiation).
* New engine module: VIA PadLOck ACE extension in VIA C3
Nehemiah processors.
* Added support for IPv6 addresses in certificate extensions.
See RFC 1884, section 2.2.
* Added support for certificate policy mappings, policy
constraints and name constraints.
* Added support for multi-valued AVAs in the OpenSSL
configuration file.
* Added support for multiple certificates with the same subject
in the 'openssl ca' index file.
* Make it possible to create self-signed certificates using
'openssl ca -selfsign'.
* Make it possible to generate a serial number file with
'openssl ca -create_serial'.
* New binary search functions with extended functionality.
* New BUF functions.
* New STORE structure and library to provide an interface to all
sorts of data repositories. Supports storage of public and
private keys, certificates, CRLs, numbers and arbitrary blobs.
This library is unfortunately unfinished and unused within
OpenSSL.
* New control functions for the error stack.
* Changed the PKCS#7 library to support one-pass S/MIME
processing.
* Added the possibility to compile without old deprecated
functionality with the OPENSSL_NO_DEPRECATED macro or the
'no-deprecated' argument to the config and Configure scripts.
* Constification of all ASN.1 conversion functions, and other
affected functions.
* Improved platform support for PowerPC.
* New FIPS 180-2 algorithms (SHA-224, -256, -384 and -512).
* New X509_VERIFY_PARAM structure to support parameterisation
of X.509 path validation.
* Major overhaul of RC4 performance on Intel P4, IA-64 and
AMD64.
* Changed the Configure script to have some algorithms disabled
by default. Those can be explicitly enabled with the new
argument form 'enable-xxx'.
* Change the default digest in 'openssl' commands from MD5 to
SHA-1.
* Added support for DTLS.
* New BIGNUM blinding.
* Added support for the RSA-PSS encryption scheme
* Added support for the RSA X.931 padding.
* Added support for BSD sockets on NetWare.
* Added support for files larger than 2GB.
* Added initial support for Win64.
* Added alternate pkg-config files.
### Major changes between OpenSSL 0.9.7l and OpenSSL 0.9.7m [23 Feb 2007]
* FIPS 1.1.1 module linking.
* Various ciphersuite selection fixes.
### Major changes between OpenSSL 0.9.7k and OpenSSL 0.9.7l [28 Sep 2006]
* Introduce limits to prevent malicious key DoS ([CVE-2006-2940])
* Fix security issues [CVE-2006-2937], [CVE-2006-3737], [CVE-2006-4343]
### Major changes between OpenSSL 0.9.7j and OpenSSL 0.9.7k [5 Sep 2006]
* Fix Daniel Bleichenbacher forged signature attack, [CVE-2006-4339]
### Major changes between OpenSSL 0.9.7i and OpenSSL 0.9.7j [4 May 2006]
* Visual C++ 2005 fixes.
* Update Windows build system for FIPS.
### Major changes between OpenSSL 0.9.7h and OpenSSL 0.9.7i [14 Oct 2005]
* Give EVP_MAX_MD_SIZE its old value, except for a FIPS build.
### Major changes between OpenSSL 0.9.7g and OpenSSL 0.9.7h [11 Oct 2005]
* Fix SSL 2.0 Rollback ([CVE-2005-2969])
* Allow use of fixed-length exponent on DSA signing
* Default fixed-window RSA, DSA, DH private-key operations
### Major changes between OpenSSL 0.9.7f and OpenSSL 0.9.7g [11 Apr 2005]
* More compilation issues fixed.
* Adaptation to more modern Kerberos API.
* Enhanced or corrected configuration for Solaris64, Mingw and Cygwin.
* Enhanced x86_64 assembler BIGNUM module.
* More constification.
* Added processing of proxy certificates (RFC 3820).
### Major changes between OpenSSL 0.9.7e and OpenSSL 0.9.7f [22 Mar 2005]
* Several compilation issues fixed.
* Many memory allocation failure checks added.
* Improved comparison of X509 Name type.
* Mandatory basic checks on certificates.
* Performance improvements.
### Major changes between OpenSSL 0.9.7d and OpenSSL 0.9.7e [25 Oct 2004]
* Fix race condition in CRL checking code.
* Fixes to PKCS#7 (S/MIME) code.
### Major changes between OpenSSL 0.9.7c and OpenSSL 0.9.7d [17 Mar 2004]
* Security: Fix Kerberos ciphersuite SSL/TLS handshaking bug
* Security: Fix null-pointer assignment in do_change_cipher_spec()
* Allow multiple active certificates with same subject in CA index
* Multiple X509 verification fixes
* Speed up HMAC and other operations
### Major changes between OpenSSL 0.9.7b and OpenSSL 0.9.7c [30 Sep 2003]
* Security: fix various ASN1 parsing bugs.
* New -ignore_err option to OCSP utility.
* Various interop and bug fixes in S/MIME code.
* SSL/TLS protocol fix for unrequested client certificates.
### Major changes between OpenSSL 0.9.7a and OpenSSL 0.9.7b [10 Apr 2003]
* Security: counter the Klima-Pokorny-Rosa extension of
Bleichbacher's attack
* Security: make RSA blinding default.
* Configuration: Irix fixes, AIX fixes, better mingw support.
* Support for new platforms: linux-ia64-ecc.
* Build: shared library support fixes.
* ASN.1: treat domainComponent correctly.
* Documentation: fixes and additions.
### Major changes between OpenSSL 0.9.7 and OpenSSL 0.9.7a [19 Feb 2003]
* Security: Important security related bugfixes.
* Enhanced compatibility with MIT Kerberos.
* Can be built without the ENGINE framework.
* IA32 assembler enhancements.
* Support for new platforms: FreeBSD/IA64 and FreeBSD/Sparc64.
* Configuration: the no-err option now works properly.
* SSL/TLS: now handles manual certificate chain building.
* SSL/TLS: certain session ID malfunctions corrected.
### Major changes between OpenSSL 0.9.6 and OpenSSL 0.9.7 [30 Dec 2002]
* New library section OCSP.
* Complete rewrite of ASN1 code.
* CRL checking in verify code and openssl utility.
* Extension copying in 'ca' utility.
* Flexible display options in 'ca' utility.
* Provisional support for international characters with UTF8.
* Support for external crypto devices ('engine') is no longer
a separate distribution.
* New elliptic curve library section.
* New AES (Rijndael) library section.
* Support for new platforms: Windows CE, Tandem OSS, A/UX, AIX 64-bit,
Linux x86_64, Linux 64-bit on Sparc v9
* Extended support for some platforms: VxWorks
* Enhanced support for shared libraries.
* Now only builds PIC code when shared library support is requested.
* Support for pkg-config.
* Lots of new manuals.
* Makes symbolic links to or copies of manuals to cover all described
functions.
* Change DES API to clean up the namespace (some applications link also
against libdes providing similar functions having the same name).
Provide macros for backward compatibility (will be removed in the
future).
* Unify handling of cryptographic algorithms (software and engine)
to be available via EVP routines for asymmetric and symmetric ciphers.
* NCONF: new configuration handling routines.
* Change API to use more 'const' modifiers to improve error checking
and help optimizers.
* Finally remove references to RSAref.
* Reworked parts of the BIGNUM code.
* Support for new engines: Broadcom ubsec, Accelerated Encryption
Processing, IBM 4758.
* A few new engines added in the demos area.
* Extended and corrected OID (object identifier) table.
* PRNG: query at more locations for a random device, automatic query for
EGD style random sources at several locations.
* SSL/TLS: allow optional cipher choice according to server's preference.
* SSL/TLS: allow server to explicitly set new session ids.
* SSL/TLS: support Kerberos cipher suites (RFC2712).
Only supports MIT Kerberos for now.
* SSL/TLS: allow more precise control of renegotiations and sessions.
* SSL/TLS: add callback to retrieve SSL/TLS messages.
* SSL/TLS: support AES cipher suites (RFC3268).
### Major changes between OpenSSL 0.9.6j and OpenSSL 0.9.6k [30 Sep 2003]
* Security: fix various ASN1 parsing bugs.
* SSL/TLS protocol fix for unrequested client certificates.
### Major changes between OpenSSL 0.9.6i and OpenSSL 0.9.6j [10 Apr 2003]
* Security: counter the Klima-Pokorny-Rosa extension of
Bleichbacher's attack
* Security: make RSA blinding default.
* Build: shared library support fixes.
### Major changes between OpenSSL 0.9.6h and OpenSSL 0.9.6i [19 Feb 2003]
* Important security related bugfixes.
### Major changes between OpenSSL 0.9.6g and OpenSSL 0.9.6h [5 Dec 2002]
* New configuration targets for Tandem OSS and A/UX.
* New OIDs for Microsoft attributes.
* Better handling of SSL session caching.
* Better comparison of distinguished names.
* Better handling of shared libraries in a mixed GNU/non-GNU environment.
* Support assembler code with Borland C.
* Fixes for length problems.
* Fixes for uninitialised variables.
* Fixes for memory leaks, some unusual crashes and some race conditions.
* Fixes for smaller building problems.
* Updates of manuals, FAQ and other instructive documents.
### Major changes between OpenSSL 0.9.6f and OpenSSL 0.9.6g [9 Aug 2002]
* Important building fixes on Unix.
### Major changes between OpenSSL 0.9.6e and OpenSSL 0.9.6f [8 Aug 2002]
* Various important bugfixes.
### Major changes between OpenSSL 0.9.6d and OpenSSL 0.9.6e [30 Jul 2002]
* Important security related bugfixes.
* Various SSL/TLS library bugfixes.
### Major changes between OpenSSL 0.9.6c and OpenSSL 0.9.6d [9 May 2002]
* Various SSL/TLS library bugfixes.
* Fix DH parameter generation for 'non-standard' generators.
### Major changes between OpenSSL 0.9.6b and OpenSSL 0.9.6c [21 Dec 2001]
* Various SSL/TLS library bugfixes.
* BIGNUM library fixes.
* RSA OAEP and random number generation fixes.
* Object identifiers corrected and added.
* Add assembler BN routines for IA64.
* Add support for OS/390 Unix, UnixWare with gcc, OpenUNIX 8,
MIPS Linux; shared library support for Irix, HP-UX.
* Add crypto accelerator support for AEP, Baltimore SureWare,
Broadcom and Cryptographic Appliance's keyserver
[in 0.9.6c-engine release].
### Major changes between OpenSSL 0.9.6a and OpenSSL 0.9.6b [9 Jul 2001]
* Security fix: PRNG improvements.
* Security fix: RSA OAEP check.
* Security fix: Reinsert and fix countermeasure to Bleichbacher's
attack.
* MIPS bug fix in BIGNUM.
* Bug fix in "openssl enc".
* Bug fix in X.509 printing routine.
* Bug fix in DSA verification routine and DSA S/MIME verification.
* Bug fix to make PRNG thread-safe.
* Bug fix in RAND_file_name().
* Bug fix in compatibility mode trust settings.
* Bug fix in blowfish EVP.
* Increase default size for BIO buffering filter.
* Compatibility fixes in some scripts.
### Major changes between OpenSSL 0.9.6 and OpenSSL 0.9.6a [5 Apr 2001]
* Security fix: change behavior of OpenSSL to avoid using
environment variables when running as root.
* Security fix: check the result of RSA-CRT to reduce the
possibility of deducing the private key from an incorrectly
calculated signature.
* Security fix: prevent Bleichenbacher's DSA attack.
* Security fix: Zero the premaster secret after deriving the
master secret in DH ciphersuites.
* Reimplement SSL_peek(), which had various problems.
* Compatibility fix: the function des_encrypt() renamed to
des_encrypt1() to avoid clashes with some Unixen libc.
* Bug fixes for Win32, HP/UX and Irix.
* Bug fixes in BIGNUM, SSL, PKCS#7, PKCS#12, X.509, CONF and
memory checking routines.
* Bug fixes for RSA operations in threaded environments.
* Bug fixes in misc. openssl applications.
* Remove a few potential memory leaks.
* Add tighter checks of BIGNUM routines.
* Shared library support has been reworked for generality.
* More documentation.
* New function BN_rand_range().
* Add "-rand" option to openssl s_client and s_server.
### Major changes between OpenSSL 0.9.5a and OpenSSL 0.9.6 [10 Oct 2000]
* Some documentation for BIO and SSL libraries.
* Enhanced chain verification using key identifiers.
* New sign and verify options to 'dgst' application.
* Support for DER and PEM encoded messages in 'smime' application.
* New 'rsautl' application, low-level RSA utility.
* MD4 now included.
* Bugfix for SSL rollback padding check.
* Support for external crypto devices [1].
* Enhanced EVP interface.
[1] The support for external crypto devices is currently a separate
distribution. See the file README-Engine.md.
### Major changes between OpenSSL 0.9.5 and OpenSSL 0.9.5a [1 Apr 2000]
* Bug fixes for Win32, SuSE Linux, NeXTSTEP and FreeBSD 2.2.8
* Shared library support for HPUX and Solaris-gcc
* Support of Linux/IA64
* Assembler support for Mingw32
* New 'rand' application
* New way to check for existence of algorithms from scripts
### Major changes between OpenSSL 0.9.4 and OpenSSL 0.9.5 [25 May 2000]
* S/MIME support in new 'smime' command
* Documentation for the OpenSSL command line application
* Automation of 'req' application
* Fixes to make s_client, s_server work under Windows
* Support for multiple fieldnames in SPKACs
* New SPKAC command line utility and associated library functions
* Options to allow passwords to be obtained from various sources
* New public key PEM format and options to handle it
* Many other fixes and enhancements to command line utilities
* Usable certificate chain verification
* Certificate purpose checking
* Certificate trust settings
* Support of authority information access extension
* Extensions in certificate requests
* Simplified X509 name and attribute routines
* Initial (incomplete) support for international character sets
* New DH_METHOD, DSA_METHOD and enhanced RSA_METHOD
* Read only memory BIOs and simplified creation function
* TLS/SSL protocol bugfixes: Accept TLS 'client hello' in SSL 3.0
record; allow fragmentation and interleaving of handshake and other
data
* TLS/SSL code now "tolerates" MS SGC
* Work around for Netscape client certificate hang bug
* RSA_NULL option that removes RSA patent code but keeps other
RSA functionality
* Memory leak detection now allows applications to add extra information
via a per-thread stack
* PRNG robustness improved
* EGD support
* BIGNUM library bug fixes
* Faster DSA parameter generation
* Enhanced support for Alpha Linux
* Experimental macOS support
### Major changes between OpenSSL 0.9.3 and OpenSSL 0.9.4 [9 Aug 1999]
* Transparent support for PKCS#8 format private keys: these are used
by several software packages and are more secure than the standard
form
* PKCS#5 v2.0 implementation
* Password callbacks have a new void * argument for application data
* Avoid various memory leaks
* New pipe-like BIO that allows using the SSL library when actual I/O
must be handled by the application (BIO pair)
### Major changes between OpenSSL 0.9.2b and OpenSSL 0.9.3 [24 May 1999]
* Lots of enhancements and cleanups to the Configuration mechanism
* RSA OEAP related fixes
* Added "openssl ca -revoke" option for revoking a certificate
* Source cleanups: const correctness, type-safe stacks and ASN.1 SETs
* Source tree cleanups: removed lots of obsolete files
* Thawte SXNet, certificate policies and CRL distribution points
extension support
* Preliminary (experimental) S/MIME support
* Support for ASN.1 UTF8String and VisibleString
* Full integration of PKCS#12 code
* Sparc assembler bignum implementation, optimized hash functions
* Option to disable selected ciphers
### Major changes between OpenSSL 0.9.1c and OpenSSL 0.9.2b [22 Mar 1999]
* Fixed a security hole related to session resumption
* Fixed RSA encryption routines for the p < q case
* "ALL" in cipher lists now means "everything except NULL ciphers"
* Support for Triple-DES CBCM cipher
* Support of Optimal Asymmetric Encryption Padding (OAEP) for RSA
* First support for new TLSv1 ciphers
* Added a few new BIOs (syslog BIO, reliable BIO)
* Extended support for DSA certificate/keys.
* Extended support for Certificate Signing Requests (CSR)
* Initial support for X.509v3 extensions
* Extended support for compression inside the SSL record layer
* Overhauled Win32 builds
* Cleanups and fixes to the Big Number (BN) library
* Support for ASN.1 GeneralizedTime
* Splitted ASN.1 SETs from SEQUENCEs
* ASN1 and PEM support for Netscape Certificate Sequences
* Overhauled Perl interface
* Lots of source tree cleanups.
* Lots of memory leak fixes.
* Lots of bug fixes.
### Major changes between SSLeay 0.9.0b and OpenSSL 0.9.1c [23 Dec 1998]
* Integration of the popular NO_RSA/NO_DSA patches
* Initial support for compression inside the SSL record layer
* Added BIO proxy and filtering functionality
* Extended Big Number (BN) library
* Added RIPE MD160 message digest
* Added support for RC2/64bit cipher
* Extended ASN.1 parser routines
* Adjustments of the source tree for CVS
* Support for various new platforms
<!-- Links -->
+[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
diff --git a/crypto/openssl/NOTES-NONSTOP.md b/crypto/openssl/NOTES-NONSTOP.md
index 68438b998884..ab13de7d3a76 100644
--- a/crypto/openssl/NOTES-NONSTOP.md
+++ b/crypto/openssl/NOTES-NONSTOP.md
@@ -1,259 +1,262 @@
NOTES FOR THE HPE NONSTOP PLATFORM
==============================
Requirement details
-------------------
In addition to the requirements and instructions listed
in [INSTALL.md](INSTALL.md), the following are required as well:
* The TNS/X platform supports hardware randomization.
Specify the `--with-rand-seed=rdcpu` option to the `./Configure` script.
This is recommended but not required. `egd` is supported at 3.0 but cannot
be used if FIPS is selected.
* The TNS/E platform does not support hardware randomization, so
specify the `--with-rand-seed=egd` option to the `./Configure` script.
About c99 compiler
------------------
The c99 compiler is required for building OpenSSL from source. While c11
may work, it has not been broadly tested. c99 is the only compiler
prerequisite needed to build OpenSSL 3.0 on this platform. You should also
have the FLOSS package installed on your system. The ITUGLIB FLOSS package
is the only FLOSS variant that has been broadly tested.
Threading Models
----------------
OpenSSL can be built using unthreaded, POSIX User Threads (PUT), or Standard
POSIX Threads (SPT). Select the following build configuration for each on
the TNS/X (L-Series) platform:
* `nonstop-nsx` or default will select an unthreaded build.
* `nonstop-nsx_put` selects the PUT build.
* `nonstop-nsx_64_put` selects the 64 bit file length PUT build.
* `nonstop-nsx_spt_floss` selects the SPT build with FLOSS. FLOSS is
required for SPT builds because of a known hang when using SPT on its own.
### TNS/E Considerations
The TNS/E platform is build using the same set of builds specifying `nse`
instead of `nsx` in the set above.
You cannot build for TNS/E for FIPS, so you must specify the `no-fips`
option to `./Configure`.
Linking and Loading Considerations
----------------------------------
Because of how the NonStop Common Runtime Environment (CRE) works, there are
restrictions on how programs can link and load with OpenSSL libraries.
On current NonStop platforms, programs cannot both statically link OpenSSL
libraries and dynamically load OpenSSL shared libraries concurrently. If this
is done, there is a high probability of encountering a SIGSEGV condition
relating to `atexit()` processing when a shared library is unloaded and when
the program terminates. This limitation applies to all OpenSSL shared library
components.
-A resolution to this situation is under investigation.
+It is possible to configure the build with `no-atexit` to avoid the SIGSEGV.
+Preferably, you can explicitly call `OPENSSL_cleanup()` from your application.
+It is not mandatory as it just deallocates various global data structures
+OpenSSL allocated.
About Prefix and OpenSSLDir
---------------------------
Because there are many potential builds that must co-exist on any given
NonStop node, managing the location of your build distribution is crucial.
Keep each destination separate and distinct. Mixing any mode described in
this document can cause application instability. The recommended approach
is to specify the OpenSSL version and threading model in your configuration
options, and keeping your memory and float options consistent, for example:
* For 1.1 `--prefix=/usr/local-ssl1.1 --openssldir=/usr/local-ssl1.1/ssl`
* For 1.1 PUT `--prefix=/usr/local-ssl1.1_put --openssldir=/usr/local-ssl1.1_put/ssl`
As of 3.0, the NonStop configurations use the multilib attribute to distinguish
between different models:
* For 3.0 `--prefix=/usr/local-ssl3.0 --openssldir=/usr/local-ssl3.0/ssl`
The PUT model is placed in `${prefix}/lib-put` for 32-bit models and
`${prefix}/lib64-put` for 64-bit models.
Use the `_RLD_LIB_PATH` environment variable in OSS to select the appropriate
directory containing `libcrypto.so` and `libssl.so`. In GUARDIAN, use the
`=_RLD_LIB_PATH` search define to locate the GUARDIAN subvolume where OpenSSL
is installed.
Float Considerations
--------------------
OpenSSL is built using IEEE Float mode by default. If you need a different
IEEE mode, create a new configuration specifying `tfloat-x86-64` (for Tandem
Float) or `nfloat-x86-64` (for Neutral Float).
Memory Models
-------------
The current OpenSSL default memory model uses the default platform address
model. If you need a different address model, you must specify the appropriate
c99 options for compile (`CFLAGS`) and linkers (`LDFLAGS`).
Cross Compiling on Windows
--------------------------
To configure and compile OpenSSL, you will need to set up a Cygwin environment.
The Cygwin tools should include bash, make, and any other normal tools required
for building programs.
Your `PATH` must include the bin directory for the c99 cross-compiler, as in:
export PATH=/cygdrive/c/Program\ Files\ \(x86\)/HPE\ NonStop/L16.05/usr/bin:$PATH
This should be set before Configure is run. For the c99 cross-compiler to work
correctly, you also need the `COMP_ROOT` set, as in:
export COMP_ROOT="C:\Program Files (x86)\HPE NonStop\L16.05"
`COMP_ROOT` needs to be in Windows form.
`Configure` must specify the `no-makedepend` option otherwise errors will
result when running the build because the c99 cross-compiler does not support
the `gcc -MT` option. An example of a `Configure` command to be run from the
OpenSSL directory is:
./Configure nonstop-nsx_64 no-makedepend --with-rand-seed=rdcpu
Do not forget to include any OpenSSL cross-compiling prefix and certificate
options when creating your libraries.
The OpenSSL test suite will not run on your workstation. In order to verify the
build, you will need to perform the build and test steps in OSS in your NonStop
server. You can also build under gcc and run the test suite for Windows but that
is not equivalent.
**Note:** In the event that you are attempting a FIPS-compliant cross-compile,
be aware that signatures may not match between builds done under OSS and under
cross-compiles as the compilers do not necessarily generate identical objects.
Anything and everything to do with FIPS is outside the scope of this document.
Refer to the FIPS security policy for more information.
The following build configurations have been successfully attempted at one
point or another. If you are successful in your cross-compile efforts, please
update this list:
- nonstop-nsx_64
- nonstop-nsx_64_put
**Note:** Cross-compile builds for TNS/E have not been attempted, but should
follow the same considerations as for TNS/X above. SPT builds generally require
FLOSS, which is not available for workstation builds. As a result, SPT builds
of OpenSSL cannot be cross-compiled.
Also see the NSDEE discussion below for more historical information.
Cross Compiling with NSDEE
--------------------------
**Note:** None of these builds have been tested by the platform maintainer and
are supplied for historical value. Please submit a Pull Request to OpenSSL
should these need to be adjusted.
If you are attempting to build OpenSSL with NSDEE, you will need to specify
the following variables. The following set of compiler defines are required:
# COMP_ROOT must be a full path for the build system (e.g. windows)
COMP_ROOT=$(cygpath -w /path/to/comp_root)
# CC must be executable by your shell
CC=/path/to/c99
### Optional Build Variables
DBGFLAG="--debug"
CIPHENABLES="enable-ssl3 enable-ssl3-method enable-weak-ssl-ciphers enable-rc4"
### Internal Known TNS/X to TNS/E Cross Compile Variables
The following definition is required if you are building on TNS/X for TNS/E
and have access to a TNS/E machine on your EXPAND network - with an example
node named `\CS3`:
SYSTEMLIBS="-L/E/cs3/usr/local/lib"
Version Procedure (VPROC) Considerations
----------------------------------------
If you require a VPROC entry for platform version identification, use the
following variables:
### For Itanium
OPENSSL_VPROC_PREFIX=T0085H06
### For x86
OPENSSL_VPROC_PREFIX=T0085L01
### Common Definition
export OPENSSL_VPROC=${OPENSSL_VPROC_PREFIX}_$(
. VERSION.dat
if [ -n "$PRE_RELEASE_TAG" ]; then
PRE_RELEASE_TAG="-$PRE_RELEASE_TAG"
fi
if [ -n "$BUILD_METADATA" ]; then
BUILD_METADATA="+$BUILD_METADATA"
fi
echo "$MAJOR.$MINOR.$PATCH$PRE_RELEASE_TAG$BUILD_METADATA" |\
sed -e 's/[-.+]/_/g'
)
Example Configure Targets
-------------------------
For OSS targets, the main DLL names will be `libssl.so` and `libcrypto.so`.
For GUARDIAN targets, DLL names will be `ssl` and `crypto`. The following
assumes that your PWD is set according to your installation standards.
./Configure nonstop-nsx --prefix=${PWD} \
--openssldir=${PWD}/ssl no-threads \
--with-rand-seed=rdcpu ${CIPHENABLES} ${DBGFLAG} ${SYSTEMLIBS}
./Configure nonstop-nsx_g --prefix=${PWD} \
--openssldir=${PWD}/ssl no-threads \
--with-rand-seed=rdcpu ${CIPHENABLES} ${DBGFLAG} ${SYSTEMLIBS}
./Configure nonstop-nsx_put --prefix=${PWD} \
--openssldir=${PWD}/ssl threads "-D_REENTRANT" \
--with-rand-seed=rdcpu ${CIPHENABLES} ${DBGFLAG} ${SYSTEMLIBS}
./Configure nonstop-nsx_spt_floss --prefix=${PWD} \
--openssldir=${PWD}/ssl threads "-D_REENTRANT" \
--with-rand-seed=rdcpu ${CIPHENABLES} ${DBGFLAG} ${SYSTEMLIBS}
./Configure nonstop-nsx_64 --prefix=${PWD} \
--openssldir=${PWD}/ssl no-threads \
--with-rand-seed=rdcpu ${CIPHENABLES} ${DBGFLAG} ${SYSTEMLIBS}
./Configure nonstop-nsx_64_put --prefix=${PWD} \
--openssldir=${PWD}/ssl threads "-D_REENTRANT" \
--with-rand-seed=rdcpu ${CIPHENABLES} ${DBGFLAG} ${SYSTEMLIBS}
./Configure nonstop-nsx_g_tandem --prefix=${PWD} \
--openssldir=${PWD}/ssl no-threads \
--with-rand-seed=rdcpu ${CIPHENABLES} ${DBGFLAG} ${SYSTEMLIBS}
./Configure nonstop-nse --prefix=${PWD} \
--openssldir=${PWD}/ssl no-threads \
--with-rand-seed=egd ${CIPHENABLES} ${DBGFLAG} ${SYSTEMLIBS}
./Configure nonstop-nse_g --prefix=${PWD} \
--openssldir=${PWD}/ssl no-threads \
--with-rand-seed=egd ${CIPHENABLES} ${DBGFLAG} ${SYSTEMLIBS}
./Configure nonstop-nse_put --prefix=${PWD} \
--openssldir=${PWD}/ssl threads "-D_REENTRANT" \
--with-rand-seed=egd ${CIPHENABLES} ${DBGFLAG} ${SYSTEMLIBS}
./Configure nonstop-nse_spt_floss --prefix=${PWD} \
--openssldir=${PWD}/ssl threads "-D_REENTRANT" \
--with-rand-seed=egd ${CIPHENABLES} ${DBGFLAG} ${SYSTEMLIBS}
./Configure nonstop-nse_64 --prefix=${PWD} \
--openssldir=${PWD}/ssl no-threads \
--with-rand-seed=egd ${CIPHENABLES} ${DBGFLAG} ${SYSTEMLIBS}
./Configure nonstop-nse_64_put --prefix=${PWD} \
--openssldir=${PWD}/ssl threads "-D_REENTRANT"
--with-rand-seed=egd ${CIPHENABLES} ${DBGFLAG} ${SYSTEMLIBS}
./Configure nonstop-nse_g_tandem --prefix=${PWD} \
--openssldir=${PWD}/ssl no-threads \
--with-rand-seed=egd ${CIPHENABLES} ${DBGFLAG} ${SYSTEMLIBS}
diff --git a/crypto/openssl/VERSION.dat b/crypto/openssl/VERSION.dat
index 3ee1a6f829f4..5de9bf3d01ba 100644
--- a/crypto/openssl/VERSION.dat
+++ b/crypto/openssl/VERSION.dat
@@ -1,7 +1,7 @@
MAJOR=3
MINOR=0
-PATCH=13
+PATCH=14
PRE_RELEASE_TAG=
BUILD_METADATA=
-RELEASE_DATE="30 Jan 2024"
+RELEASE_DATE="4 Jun 2024"
SHLIB_VERSION=3
diff --git a/crypto/openssl/apps/lib/s_cb.c b/crypto/openssl/apps/lib/s_cb.c
index f2ddd94c3de4..7881c1667626 100644
--- a/crypto/openssl/apps/lib/s_cb.c
+++ b/crypto/openssl/apps/lib/s_cb.c
@@ -1,1569 +1,1571 @@
/*
- * Copyright 1995-2022 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 1995-2024 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
*/
/* callback functions used by s_client, s_server, and s_time */
#include <stdio.h>
#include <stdlib.h>
#include <string.h> /* for memcpy() and strcmp() */
#include "apps.h"
#include <openssl/core_names.h>
#include <openssl/params.h>
#include <openssl/err.h>
#include <openssl/rand.h>
#include <openssl/x509.h>
#include <openssl/ssl.h>
#include <openssl/bn.h>
#ifndef OPENSSL_NO_DH
# include <openssl/dh.h>
#endif
#include "s_apps.h"
#define COOKIE_SECRET_LENGTH 16
VERIFY_CB_ARGS verify_args = { -1, 0, X509_V_OK, 0 };
#ifndef OPENSSL_NO_SOCK
static unsigned char cookie_secret[COOKIE_SECRET_LENGTH];
static int cookie_initialized = 0;
#endif
static BIO *bio_keylog = NULL;
static const char *lookup(int val, const STRINT_PAIR* list, const char* def)
{
for ( ; list->name; ++list)
if (list->retval == val)
return list->name;
return def;
}
int verify_callback(int ok, X509_STORE_CTX *ctx)
{
X509 *err_cert;
int err, depth;
err_cert = X509_STORE_CTX_get_current_cert(ctx);
err = X509_STORE_CTX_get_error(ctx);
depth = X509_STORE_CTX_get_error_depth(ctx);
if (!verify_args.quiet || !ok) {
BIO_printf(bio_err, "depth=%d ", depth);
if (err_cert != NULL) {
X509_NAME_print_ex(bio_err,
X509_get_subject_name(err_cert),
0, get_nameopt());
BIO_puts(bio_err, "\n");
} else {
BIO_puts(bio_err, "<no cert>\n");
}
}
if (!ok) {
BIO_printf(bio_err, "verify error:num=%d:%s\n", err,
X509_verify_cert_error_string(err));
if (verify_args.depth < 0 || verify_args.depth >= depth) {
if (!verify_args.return_error)
ok = 1;
verify_args.error = err;
} else {
ok = 0;
verify_args.error = X509_V_ERR_CERT_CHAIN_TOO_LONG;
}
}
switch (err) {
case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
if (err_cert != NULL) {
BIO_puts(bio_err, "issuer= ");
X509_NAME_print_ex(bio_err, X509_get_issuer_name(err_cert),
0, get_nameopt());
BIO_puts(bio_err, "\n");
}
break;
case X509_V_ERR_CERT_NOT_YET_VALID:
case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
if (err_cert != NULL) {
BIO_printf(bio_err, "notBefore=");
ASN1_TIME_print(bio_err, X509_get0_notBefore(err_cert));
BIO_printf(bio_err, "\n");
}
break;
case X509_V_ERR_CERT_HAS_EXPIRED:
case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
if (err_cert != NULL) {
BIO_printf(bio_err, "notAfter=");
ASN1_TIME_print(bio_err, X509_get0_notAfter(err_cert));
BIO_printf(bio_err, "\n");
}
break;
case X509_V_ERR_NO_EXPLICIT_POLICY:
if (!verify_args.quiet)
policies_print(ctx);
break;
}
if (err == X509_V_OK && ok == 2 && !verify_args.quiet)
policies_print(ctx);
if (ok && !verify_args.quiet)
BIO_printf(bio_err, "verify return:%d\n", ok);
return ok;
}
int set_cert_stuff(SSL_CTX *ctx, char *cert_file, char *key_file)
{
if (cert_file != NULL) {
if (SSL_CTX_use_certificate_file(ctx, cert_file,
SSL_FILETYPE_PEM) <= 0) {
BIO_printf(bio_err, "unable to get certificate from '%s'\n",
cert_file);
ERR_print_errors(bio_err);
return 0;
}
if (key_file == NULL)
key_file = cert_file;
if (SSL_CTX_use_PrivateKey_file(ctx, key_file, SSL_FILETYPE_PEM) <= 0) {
BIO_printf(bio_err, "unable to get private key from '%s'\n",
key_file);
ERR_print_errors(bio_err);
return 0;
}
/*
* If we are using DSA, we can copy the parameters from the private
* key
*/
/*
* Now we know that a key and cert have been set against the SSL
* context
*/
if (!SSL_CTX_check_private_key(ctx)) {
BIO_printf(bio_err,
"Private key does not match the certificate public key\n");
return 0;
}
}
return 1;
}
int set_cert_key_stuff(SSL_CTX *ctx, X509 *cert, EVP_PKEY *key,
STACK_OF(X509) *chain, int build_chain)
{
int chflags = chain ? SSL_BUILD_CHAIN_FLAG_CHECK : 0;
if (cert == NULL)
return 1;
if (SSL_CTX_use_certificate(ctx, cert) <= 0) {
BIO_printf(bio_err, "error setting certificate\n");
ERR_print_errors(bio_err);
return 0;
}
if (SSL_CTX_use_PrivateKey(ctx, key) <= 0) {
BIO_printf(bio_err, "error setting private key\n");
ERR_print_errors(bio_err);
return 0;
}
/*
* Now we know that a key and cert have been set against the SSL context
*/
if (!SSL_CTX_check_private_key(ctx)) {
BIO_printf(bio_err,
"Private key does not match the certificate public key\n");
return 0;
}
if (chain && !SSL_CTX_set1_chain(ctx, chain)) {
BIO_printf(bio_err, "error setting certificate chain\n");
ERR_print_errors(bio_err);
return 0;
}
if (build_chain && !SSL_CTX_build_cert_chain(ctx, chflags)) {
BIO_printf(bio_err, "error building certificate chain\n");
ERR_print_errors(bio_err);
return 0;
}
return 1;
}
static STRINT_PAIR cert_type_list[] = {
{"RSA sign", TLS_CT_RSA_SIGN},
{"DSA sign", TLS_CT_DSS_SIGN},
{"RSA fixed DH", TLS_CT_RSA_FIXED_DH},
{"DSS fixed DH", TLS_CT_DSS_FIXED_DH},
{"ECDSA sign", TLS_CT_ECDSA_SIGN},
{"RSA fixed ECDH", TLS_CT_RSA_FIXED_ECDH},
{"ECDSA fixed ECDH", TLS_CT_ECDSA_FIXED_ECDH},
{"GOST01 Sign", TLS_CT_GOST01_SIGN},
{"GOST12 Sign", TLS_CT_GOST12_IANA_SIGN},
{NULL}
};
static void ssl_print_client_cert_types(BIO *bio, SSL *s)
{
const unsigned char *p;
int i;
int cert_type_num = SSL_get0_certificate_types(s, &p);
if (!cert_type_num)
return;
BIO_puts(bio, "Client Certificate Types: ");
for (i = 0; i < cert_type_num; i++) {
unsigned char cert_type = p[i];
const char *cname = lookup((int)cert_type, cert_type_list, NULL);
if (i)
BIO_puts(bio, ", ");
if (cname != NULL)
BIO_puts(bio, cname);
else
BIO_printf(bio, "UNKNOWN (%d),", cert_type);
}
BIO_puts(bio, "\n");
}
static const char *get_sigtype(int nid)
{
switch (nid) {
case EVP_PKEY_RSA:
return "RSA";
case EVP_PKEY_RSA_PSS:
return "RSA-PSS";
case EVP_PKEY_DSA:
return "DSA";
case EVP_PKEY_EC:
return "ECDSA";
case NID_ED25519:
return "Ed25519";
case NID_ED448:
return "Ed448";
case NID_id_GostR3410_2001:
return "gost2001";
case NID_id_GostR3410_2012_256:
return "gost2012_256";
case NID_id_GostR3410_2012_512:
return "gost2012_512";
default:
return NULL;
}
}
static int do_print_sigalgs(BIO *out, SSL *s, int shared)
{
int i, nsig, client;
client = SSL_is_server(s) ? 0 : 1;
if (shared)
nsig = SSL_get_shared_sigalgs(s, 0, NULL, NULL, NULL, NULL, NULL);
else
nsig = SSL_get_sigalgs(s, -1, NULL, NULL, NULL, NULL, NULL);
if (nsig == 0)
return 1;
if (shared)
BIO_puts(out, "Shared ");
if (client)
BIO_puts(out, "Requested ");
BIO_puts(out, "Signature Algorithms: ");
for (i = 0; i < nsig; i++) {
int hash_nid, sign_nid;
unsigned char rhash, rsign;
const char *sstr = NULL;
if (shared)
SSL_get_shared_sigalgs(s, i, &sign_nid, &hash_nid, NULL,
&rsign, &rhash);
else
SSL_get_sigalgs(s, i, &sign_nid, &hash_nid, NULL, &rsign, &rhash);
if (i)
BIO_puts(out, ":");
sstr = get_sigtype(sign_nid);
if (sstr)
BIO_printf(out, "%s", sstr);
else
BIO_printf(out, "0x%02X", (int)rsign);
if (hash_nid != NID_undef)
BIO_printf(out, "+%s", OBJ_nid2sn(hash_nid));
else if (sstr == NULL)
BIO_printf(out, "+0x%02X", (int)rhash);
}
BIO_puts(out, "\n");
return 1;
}
int ssl_print_sigalgs(BIO *out, SSL *s)
{
int nid;
if (!SSL_is_server(s))
ssl_print_client_cert_types(out, s);
do_print_sigalgs(out, s, 0);
do_print_sigalgs(out, s, 1);
if (SSL_get_peer_signature_nid(s, &nid) && nid != NID_undef)
BIO_printf(out, "Peer signing digest: %s\n", OBJ_nid2sn(nid));
if (SSL_get_peer_signature_type_nid(s, &nid))
BIO_printf(out, "Peer signature type: %s\n", get_sigtype(nid));
return 1;
}
#ifndef OPENSSL_NO_EC
int ssl_print_point_formats(BIO *out, SSL *s)
{
int i, nformats;
const char *pformats;
nformats = SSL_get0_ec_point_formats(s, &pformats);
if (nformats <= 0)
return 1;
BIO_puts(out, "Supported Elliptic Curve Point Formats: ");
for (i = 0; i < nformats; i++, pformats++) {
if (i)
BIO_puts(out, ":");
switch (*pformats) {
case TLSEXT_ECPOINTFORMAT_uncompressed:
BIO_puts(out, "uncompressed");
break;
case TLSEXT_ECPOINTFORMAT_ansiX962_compressed_prime:
BIO_puts(out, "ansiX962_compressed_prime");
break;
case TLSEXT_ECPOINTFORMAT_ansiX962_compressed_char2:
BIO_puts(out, "ansiX962_compressed_char2");
break;
default:
BIO_printf(out, "unknown(%d)", (int)*pformats);
break;
}
}
BIO_puts(out, "\n");
return 1;
}
int ssl_print_groups(BIO *out, SSL *s, int noshared)
{
int i, ngroups, *groups, nid;
ngroups = SSL_get1_groups(s, NULL);
if (ngroups <= 0)
return 1;
groups = app_malloc(ngroups * sizeof(int), "groups to print");
SSL_get1_groups(s, groups);
BIO_puts(out, "Supported groups: ");
for (i = 0; i < ngroups; i++) {
if (i)
BIO_puts(out, ":");
nid = groups[i];
BIO_printf(out, "%s", SSL_group_to_name(s, nid));
}
OPENSSL_free(groups);
if (noshared) {
BIO_puts(out, "\n");
return 1;
}
BIO_puts(out, "\nShared groups: ");
ngroups = SSL_get_shared_group(s, -1);
for (i = 0; i < ngroups; i++) {
if (i)
BIO_puts(out, ":");
nid = SSL_get_shared_group(s, i);
BIO_printf(out, "%s", SSL_group_to_name(s, nid));
}
if (ngroups == 0)
BIO_puts(out, "NONE");
BIO_puts(out, "\n");
return 1;
}
#endif
int ssl_print_tmp_key(BIO *out, SSL *s)
{
EVP_PKEY *key;
if (!SSL_get_peer_tmp_key(s, &key))
return 1;
BIO_puts(out, "Server Temp Key: ");
switch (EVP_PKEY_get_id(key)) {
case EVP_PKEY_RSA:
BIO_printf(out, "RSA, %d bits\n", EVP_PKEY_get_bits(key));
break;
case EVP_PKEY_DH:
BIO_printf(out, "DH, %d bits\n", EVP_PKEY_get_bits(key));
break;
#ifndef OPENSSL_NO_EC
case EVP_PKEY_EC:
{
char name[80];
size_t name_len;
if (!EVP_PKEY_get_utf8_string_param(key, OSSL_PKEY_PARAM_GROUP_NAME,
name, sizeof(name), &name_len))
strcpy(name, "?");
BIO_printf(out, "ECDH, %s, %d bits\n", name, EVP_PKEY_get_bits(key));
}
break;
#endif
default:
BIO_printf(out, "%s, %d bits\n", OBJ_nid2sn(EVP_PKEY_get_id(key)),
EVP_PKEY_get_bits(key));
}
EVP_PKEY_free(key);
return 1;
}
long bio_dump_callback(BIO *bio, int cmd, const char *argp, size_t len,
int argi, long argl, int ret, size_t *processed)
{
BIO *out;
out = (BIO *)BIO_get_callback_arg(bio);
if (out == NULL)
return ret;
if (cmd == (BIO_CB_READ | BIO_CB_RETURN)) {
if (ret > 0 && processed != NULL) {
BIO_printf(out, "read from %p [%p] (%zu bytes => %zu (0x%zX))\n",
(void *)bio, (void *)argp, len, *processed, *processed);
BIO_dump(out, argp, (int)*processed);
} else {
BIO_printf(out, "read from %p [%p] (%zu bytes => %d)\n",
(void *)bio, (void *)argp, len, ret);
}
} else if (cmd == (BIO_CB_WRITE | BIO_CB_RETURN)) {
if (ret > 0 && processed != NULL) {
BIO_printf(out, "write to %p [%p] (%zu bytes => %zu (0x%zX))\n",
(void *)bio, (void *)argp, len, *processed, *processed);
BIO_dump(out, argp, (int)*processed);
} else {
BIO_printf(out, "write to %p [%p] (%zu bytes => %d)\n",
(void *)bio, (void *)argp, len, ret);
}
}
return ret;
}
void apps_ssl_info_callback(const SSL *s, int where, int ret)
{
const char *str;
int w;
w = where & ~SSL_ST_MASK;
if (w & SSL_ST_CONNECT)
str = "SSL_connect";
else if (w & SSL_ST_ACCEPT)
str = "SSL_accept";
else
str = "undefined";
if (where & SSL_CB_LOOP) {
BIO_printf(bio_err, "%s:%s\n", str, SSL_state_string_long(s));
} else if (where & SSL_CB_ALERT) {
str = (where & SSL_CB_READ) ? "read" : "write";
BIO_printf(bio_err, "SSL3 alert %s:%s:%s\n",
str,
SSL_alert_type_string_long(ret),
SSL_alert_desc_string_long(ret));
} else if (where & SSL_CB_EXIT) {
if (ret == 0)
BIO_printf(bio_err, "%s:failed in %s\n",
str, SSL_state_string_long(s));
else if (ret < 0)
BIO_printf(bio_err, "%s:error in %s\n",
str, SSL_state_string_long(s));
}
}
static STRINT_PAIR ssl_versions[] = {
{"SSL 3.0", SSL3_VERSION},
{"TLS 1.0", TLS1_VERSION},
{"TLS 1.1", TLS1_1_VERSION},
{"TLS 1.2", TLS1_2_VERSION},
{"TLS 1.3", TLS1_3_VERSION},
{"DTLS 1.0", DTLS1_VERSION},
{"DTLS 1.0 (bad)", DTLS1_BAD_VER},
{NULL}
};
static STRINT_PAIR alert_types[] = {
{" close_notify", 0},
{" end_of_early_data", 1},
{" unexpected_message", 10},
{" bad_record_mac", 20},
{" decryption_failed", 21},
{" record_overflow", 22},
{" decompression_failure", 30},
{" handshake_failure", 40},
{" bad_certificate", 42},
{" unsupported_certificate", 43},
{" certificate_revoked", 44},
{" certificate_expired", 45},
{" certificate_unknown", 46},
{" illegal_parameter", 47},
{" unknown_ca", 48},
{" access_denied", 49},
{" decode_error", 50},
{" decrypt_error", 51},
{" export_restriction", 60},
{" protocol_version", 70},
{" insufficient_security", 71},
{" internal_error", 80},
{" inappropriate_fallback", 86},
{" user_canceled", 90},
{" no_renegotiation", 100},
{" missing_extension", 109},
{" unsupported_extension", 110},
{" certificate_unobtainable", 111},
{" unrecognized_name", 112},
{" bad_certificate_status_response", 113},
{" bad_certificate_hash_value", 114},
{" unknown_psk_identity", 115},
{" certificate_required", 116},
{NULL}
};
static STRINT_PAIR handshakes[] = {
{", HelloRequest", SSL3_MT_HELLO_REQUEST},
{", ClientHello", SSL3_MT_CLIENT_HELLO},
{", ServerHello", SSL3_MT_SERVER_HELLO},
{", HelloVerifyRequest", DTLS1_MT_HELLO_VERIFY_REQUEST},
{", NewSessionTicket", SSL3_MT_NEWSESSION_TICKET},
{", EndOfEarlyData", SSL3_MT_END_OF_EARLY_DATA},
{", EncryptedExtensions", SSL3_MT_ENCRYPTED_EXTENSIONS},
{", Certificate", SSL3_MT_CERTIFICATE},
{", ServerKeyExchange", SSL3_MT_SERVER_KEY_EXCHANGE},
{", CertificateRequest", SSL3_MT_CERTIFICATE_REQUEST},
{", ServerHelloDone", SSL3_MT_SERVER_DONE},
{", CertificateVerify", SSL3_MT_CERTIFICATE_VERIFY},
{", ClientKeyExchange", SSL3_MT_CLIENT_KEY_EXCHANGE},
{", Finished", SSL3_MT_FINISHED},
{", CertificateUrl", SSL3_MT_CERTIFICATE_URL},
{", CertificateStatus", SSL3_MT_CERTIFICATE_STATUS},
{", SupplementalData", SSL3_MT_SUPPLEMENTAL_DATA},
{", KeyUpdate", SSL3_MT_KEY_UPDATE},
#ifndef OPENSSL_NO_NEXTPROTONEG
{", NextProto", SSL3_MT_NEXT_PROTO},
#endif
{", MessageHash", SSL3_MT_MESSAGE_HASH},
{NULL}
};
void msg_cb(int write_p, int version, int content_type, const void *buf,
size_t len, SSL *ssl, void *arg)
{
BIO *bio = arg;
const char *str_write_p = write_p ? ">>>" : "<<<";
char tmpbuf[128];
const char *str_version, *str_content_type = "", *str_details1 = "", *str_details2 = "";
const unsigned char* bp = buf;
if (version == SSL3_VERSION ||
version == TLS1_VERSION ||
version == TLS1_1_VERSION ||
version == TLS1_2_VERSION ||
version == TLS1_3_VERSION ||
version == DTLS1_VERSION || version == DTLS1_BAD_VER) {
str_version = lookup(version, ssl_versions, "???");
switch (content_type) {
case SSL3_RT_CHANGE_CIPHER_SPEC:
/* type 20 */
str_content_type = ", ChangeCipherSpec";
break;
case SSL3_RT_ALERT:
/* type 21 */
str_content_type = ", Alert";
str_details1 = ", ???";
if (len == 2) {
switch (bp[0]) {
case 1:
str_details1 = ", warning";
break;
case 2:
str_details1 = ", fatal";
break;
}
str_details2 = lookup((int)bp[1], alert_types, " ???");
}
break;
case SSL3_RT_HANDSHAKE:
/* type 22 */
str_content_type = ", Handshake";
str_details1 = "???";
if (len > 0)
str_details1 = lookup((int)bp[0], handshakes, "???");
break;
case SSL3_RT_APPLICATION_DATA:
/* type 23 */
str_content_type = ", ApplicationData";
break;
case SSL3_RT_HEADER:
/* type 256 */
str_content_type = ", RecordHeader";
break;
case SSL3_RT_INNER_CONTENT_TYPE:
/* type 257 */
str_content_type = ", InnerContent";
break;
default:
BIO_snprintf(tmpbuf, sizeof(tmpbuf)-1, ", Unknown (content_type=%d)", content_type);
str_content_type = tmpbuf;
}
} else {
BIO_snprintf(tmpbuf, sizeof(tmpbuf)-1, "Not TLS data or unknown version (version=%d, content_type=%d)", version, content_type);
str_version = tmpbuf;
}
BIO_printf(bio, "%s %s%s [length %04lx]%s%s\n", str_write_p, str_version,
str_content_type, (unsigned long)len, str_details1,
str_details2);
if (len > 0) {
size_t num, i;
BIO_printf(bio, " ");
num = len;
for (i = 0; i < num; i++) {
if (i % 16 == 0 && i > 0)
BIO_printf(bio, "\n ");
BIO_printf(bio, " %02x", ((const unsigned char *)buf)[i]);
}
if (i < len)
BIO_printf(bio, " ...");
BIO_printf(bio, "\n");
}
(void)BIO_flush(bio);
}
static STRINT_PAIR tlsext_types[] = {
{"server name", TLSEXT_TYPE_server_name},
{"max fragment length", TLSEXT_TYPE_max_fragment_length},
{"client certificate URL", TLSEXT_TYPE_client_certificate_url},
{"trusted CA keys", TLSEXT_TYPE_trusted_ca_keys},
{"truncated HMAC", TLSEXT_TYPE_truncated_hmac},
{"status request", TLSEXT_TYPE_status_request},
{"user mapping", TLSEXT_TYPE_user_mapping},
{"client authz", TLSEXT_TYPE_client_authz},
{"server authz", TLSEXT_TYPE_server_authz},
{"cert type", TLSEXT_TYPE_cert_type},
{"supported_groups", TLSEXT_TYPE_supported_groups},
{"EC point formats", TLSEXT_TYPE_ec_point_formats},
{"SRP", TLSEXT_TYPE_srp},
{"signature algorithms", TLSEXT_TYPE_signature_algorithms},
{"use SRTP", TLSEXT_TYPE_use_srtp},
{"session ticket", TLSEXT_TYPE_session_ticket},
{"renegotiation info", TLSEXT_TYPE_renegotiate},
{"signed certificate timestamps", TLSEXT_TYPE_signed_certificate_timestamp},
{"TLS padding", TLSEXT_TYPE_padding},
#ifdef TLSEXT_TYPE_next_proto_neg
{"next protocol", TLSEXT_TYPE_next_proto_neg},
#endif
#ifdef TLSEXT_TYPE_encrypt_then_mac
{"encrypt-then-mac", TLSEXT_TYPE_encrypt_then_mac},
#endif
#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
{"application layer protocol negotiation",
TLSEXT_TYPE_application_layer_protocol_negotiation},
#endif
#ifdef TLSEXT_TYPE_extended_master_secret
{"extended master secret", TLSEXT_TYPE_extended_master_secret},
#endif
{"key share", TLSEXT_TYPE_key_share},
{"supported versions", TLSEXT_TYPE_supported_versions},
{"psk", TLSEXT_TYPE_psk},
{"psk kex modes", TLSEXT_TYPE_psk_kex_modes},
{"certificate authorities", TLSEXT_TYPE_certificate_authorities},
{"post handshake auth", TLSEXT_TYPE_post_handshake_auth},
{NULL}
};
/* from rfc8446 4.2.3. + gost (https://tools.ietf.org/id/draft-smyshlyaev-tls12-gost-suites-04.html) */
static STRINT_PAIR signature_tls13_scheme_list[] = {
{"rsa_pkcs1_sha1", 0x0201 /* TLSEXT_SIGALG_rsa_pkcs1_sha1 */},
{"ecdsa_sha1", 0x0203 /* TLSEXT_SIGALG_ecdsa_sha1 */},
/* {"rsa_pkcs1_sha224", 0x0301 TLSEXT_SIGALG_rsa_pkcs1_sha224}, not in rfc8446 */
/* {"ecdsa_sha224", 0x0303 TLSEXT_SIGALG_ecdsa_sha224} not in rfc8446 */
{"rsa_pkcs1_sha256", 0x0401 /* TLSEXT_SIGALG_rsa_pkcs1_sha256 */},
{"ecdsa_secp256r1_sha256", 0x0403 /* TLSEXT_SIGALG_ecdsa_secp256r1_sha256 */},
{"rsa_pkcs1_sha384", 0x0501 /* TLSEXT_SIGALG_rsa_pkcs1_sha384 */},
{"ecdsa_secp384r1_sha384", 0x0503 /* TLSEXT_SIGALG_ecdsa_secp384r1_sha384 */},
{"rsa_pkcs1_sha512", 0x0601 /* TLSEXT_SIGALG_rsa_pkcs1_sha512 */},
{"ecdsa_secp521r1_sha512", 0x0603 /* TLSEXT_SIGALG_ecdsa_secp521r1_sha512 */},
{"rsa_pss_rsae_sha256", 0x0804 /* TLSEXT_SIGALG_rsa_pss_rsae_sha256 */},
{"rsa_pss_rsae_sha384", 0x0805 /* TLSEXT_SIGALG_rsa_pss_rsae_sha384 */},
{"rsa_pss_rsae_sha512", 0x0806 /* TLSEXT_SIGALG_rsa_pss_rsae_sha512 */},
{"ed25519", 0x0807 /* TLSEXT_SIGALG_ed25519 */},
{"ed448", 0x0808 /* TLSEXT_SIGALG_ed448 */},
{"rsa_pss_pss_sha256", 0x0809 /* TLSEXT_SIGALG_rsa_pss_pss_sha256 */},
{"rsa_pss_pss_sha384", 0x080a /* TLSEXT_SIGALG_rsa_pss_pss_sha384 */},
{"rsa_pss_pss_sha512", 0x080b /* TLSEXT_SIGALG_rsa_pss_pss_sha512 */},
{"gostr34102001", 0xeded /* TLSEXT_SIGALG_gostr34102001_gostr3411 */},
{"gostr34102012_256", 0xeeee /* TLSEXT_SIGALG_gostr34102012_256_gostr34112012_256 */},
{"gostr34102012_512", 0xefef /* TLSEXT_SIGALG_gostr34102012_512_gostr34112012_512 */},
{NULL}
};
/* from rfc5246 7.4.1.4.1. */
static STRINT_PAIR signature_tls12_alg_list[] = {
{"anonymous", TLSEXT_signature_anonymous /* 0 */},
{"RSA", TLSEXT_signature_rsa /* 1 */},
{"DSA", TLSEXT_signature_dsa /* 2 */},
{"ECDSA", TLSEXT_signature_ecdsa /* 3 */},
{NULL}
};
/* from rfc5246 7.4.1.4.1. */
static STRINT_PAIR signature_tls12_hash_list[] = {
{"none", TLSEXT_hash_none /* 0 */},
{"MD5", TLSEXT_hash_md5 /* 1 */},
{"SHA1", TLSEXT_hash_sha1 /* 2 */},
{"SHA224", TLSEXT_hash_sha224 /* 3 */},
{"SHA256", TLSEXT_hash_sha256 /* 4 */},
{"SHA384", TLSEXT_hash_sha384 /* 5 */},
{"SHA512", TLSEXT_hash_sha512 /* 6 */},
{NULL}
};
void tlsext_cb(SSL *s, int client_server, int type,
const unsigned char *data, int len, void *arg)
{
BIO *bio = arg;
const char *extname = lookup(type, tlsext_types, "unknown");
BIO_printf(bio, "TLS %s extension \"%s\" (id=%d), len=%d\n",
client_server ? "server" : "client", extname, type, len);
BIO_dump(bio, (const char *)data, len);
(void)BIO_flush(bio);
}
#ifndef OPENSSL_NO_SOCK
int generate_stateless_cookie_callback(SSL *ssl, unsigned char *cookie,
size_t *cookie_len)
{
unsigned char *buffer = NULL;
size_t length = 0;
unsigned short port;
BIO_ADDR *lpeer = NULL, *peer = NULL;
int res = 0;
/* Initialize a random secret */
if (!cookie_initialized) {
if (RAND_bytes(cookie_secret, COOKIE_SECRET_LENGTH) <= 0) {
BIO_printf(bio_err, "error setting random cookie secret\n");
return 0;
}
cookie_initialized = 1;
}
if (SSL_is_dtls(ssl)) {
lpeer = peer = BIO_ADDR_new();
if (peer == NULL) {
BIO_printf(bio_err, "memory full\n");
return 0;
}
/* Read peer information */
(void)BIO_dgram_get_peer(SSL_get_rbio(ssl), peer);
} else {
peer = ourpeer;
}
/* Create buffer with peer's address and port */
if (!BIO_ADDR_rawaddress(peer, NULL, &length)) {
BIO_printf(bio_err, "Failed getting peer address\n");
BIO_ADDR_free(lpeer);
return 0;
}
OPENSSL_assert(length != 0);
port = BIO_ADDR_rawport(peer);
length += sizeof(port);
buffer = app_malloc(length, "cookie generate buffer");
memcpy(buffer, &port, sizeof(port));
BIO_ADDR_rawaddress(peer, buffer + sizeof(port), NULL);
if (EVP_Q_mac(NULL, "HMAC", NULL, "SHA1", NULL,
cookie_secret, COOKIE_SECRET_LENGTH, buffer, length,
cookie, DTLS1_COOKIE_LENGTH, cookie_len) == NULL) {
BIO_printf(bio_err,
"Error calculating HMAC-SHA1 of buffer with secret\n");
goto end;
}
res = 1;
end:
OPENSSL_free(buffer);
BIO_ADDR_free(lpeer);
return res;
}
int verify_stateless_cookie_callback(SSL *ssl, const unsigned char *cookie,
size_t cookie_len)
{
unsigned char result[EVP_MAX_MD_SIZE];
size_t resultlength;
/* Note: we check cookie_initialized because if it's not,
* it cannot be valid */
if (cookie_initialized
&& generate_stateless_cookie_callback(ssl, result, &resultlength)
&& cookie_len == resultlength
&& memcmp(result, cookie, resultlength) == 0)
return 1;
return 0;
}
int generate_cookie_callback(SSL *ssl, unsigned char *cookie,
unsigned int *cookie_len)
{
size_t temp = 0;
int res = generate_stateless_cookie_callback(ssl, cookie, &temp);
if (res != 0)
*cookie_len = (unsigned int)temp;
return res;
}
int verify_cookie_callback(SSL *ssl, const unsigned char *cookie,
unsigned int cookie_len)
{
return verify_stateless_cookie_callback(ssl, cookie, cookie_len);
}
#endif
/*
* Example of extended certificate handling. Where the standard support of
* one certificate per algorithm is not sufficient an application can decide
* which certificate(s) to use at runtime based on whatever criteria it deems
* appropriate.
*/
/* Linked list of certificates, keys and chains */
struct ssl_excert_st {
int certform;
const char *certfile;
int keyform;
const char *keyfile;
const char *chainfile;
X509 *cert;
EVP_PKEY *key;
STACK_OF(X509) *chain;
int build_chain;
struct ssl_excert_st *next, *prev;
};
static STRINT_PAIR chain_flags[] = {
{"Overall Validity", CERT_PKEY_VALID},
{"Sign with EE key", CERT_PKEY_SIGN},
{"EE signature", CERT_PKEY_EE_SIGNATURE},
{"CA signature", CERT_PKEY_CA_SIGNATURE},
{"EE key parameters", CERT_PKEY_EE_PARAM},
{"CA key parameters", CERT_PKEY_CA_PARAM},
{"Explicitly sign with EE key", CERT_PKEY_EXPLICIT_SIGN},
{"Issuer Name", CERT_PKEY_ISSUER_NAME},
{"Certificate Type", CERT_PKEY_CERT_TYPE},
{NULL}
};
static void print_chain_flags(SSL *s, int flags)
{
STRINT_PAIR *pp;
for (pp = chain_flags; pp->name; ++pp)
BIO_printf(bio_err, "\t%s: %s\n",
pp->name,
(flags & pp->retval) ? "OK" : "NOT OK");
BIO_printf(bio_err, "\tSuite B: ");
if (SSL_set_cert_flags(s, 0) & SSL_CERT_FLAG_SUITEB_128_LOS)
BIO_puts(bio_err, flags & CERT_PKEY_SUITEB ? "OK\n" : "NOT OK\n");
else
BIO_printf(bio_err, "not tested\n");
}
/*
* Very basic selection callback: just use any certificate chain reported as
* valid. More sophisticated could prioritise according to local policy.
*/
static int set_cert_cb(SSL *ssl, void *arg)
{
int i, rv;
SSL_EXCERT *exc = arg;
#ifdef CERT_CB_TEST_RETRY
static int retry_cnt;
if (retry_cnt < 5) {
retry_cnt++;
BIO_printf(bio_err,
"Certificate callback retry test: count %d\n",
retry_cnt);
return -1;
}
#endif
SSL_certs_clear(ssl);
if (exc == NULL)
return 1;
/*
* Go to end of list and traverse backwards since we prepend newer
* entries this retains the original order.
*/
while (exc->next != NULL)
exc = exc->next;
i = 0;
while (exc != NULL) {
i++;
rv = SSL_check_chain(ssl, exc->cert, exc->key, exc->chain);
BIO_printf(bio_err, "Checking cert chain %d:\nSubject: ", i);
X509_NAME_print_ex(bio_err, X509_get_subject_name(exc->cert), 0,
get_nameopt());
BIO_puts(bio_err, "\n");
print_chain_flags(ssl, rv);
if (rv & CERT_PKEY_VALID) {
if (!SSL_use_certificate(ssl, exc->cert)
|| !SSL_use_PrivateKey(ssl, exc->key)) {
return 0;
}
/*
* NB: we wouldn't normally do this as it is not efficient
* building chains on each connection better to cache the chain
* in advance.
*/
if (exc->build_chain) {
if (!SSL_build_cert_chain(ssl, 0))
return 0;
} else if (exc->chain != NULL) {
if (!SSL_set1_chain(ssl, exc->chain))
return 0;
}
}
exc = exc->prev;
}
return 1;
}
void ssl_ctx_set_excert(SSL_CTX *ctx, SSL_EXCERT *exc)
{
SSL_CTX_set_cert_cb(ctx, set_cert_cb, exc);
}
static int ssl_excert_prepend(SSL_EXCERT **pexc)
{
SSL_EXCERT *exc = app_malloc(sizeof(*exc), "prepend cert");
memset(exc, 0, sizeof(*exc));
exc->next = *pexc;
*pexc = exc;
if (exc->next) {
exc->certform = exc->next->certform;
exc->keyform = exc->next->keyform;
exc->next->prev = exc;
} else {
exc->certform = FORMAT_PEM;
exc->keyform = FORMAT_PEM;
}
return 1;
}
void ssl_excert_free(SSL_EXCERT *exc)
{
SSL_EXCERT *curr;
if (exc == NULL)
return;
while (exc) {
X509_free(exc->cert);
EVP_PKEY_free(exc->key);
sk_X509_pop_free(exc->chain, X509_free);
curr = exc;
exc = exc->next;
OPENSSL_free(curr);
}
}
int load_excert(SSL_EXCERT **pexc)
{
SSL_EXCERT *exc = *pexc;
if (exc == NULL)
return 1;
/* If nothing in list, free and set to NULL */
if (exc->certfile == NULL && exc->next == NULL) {
ssl_excert_free(exc);
*pexc = NULL;
return 1;
}
for (; exc; exc = exc->next) {
if (exc->certfile == NULL) {
BIO_printf(bio_err, "Missing filename\n");
return 0;
}
exc->cert = load_cert(exc->certfile, exc->certform,
"Server Certificate");
if (exc->cert == NULL)
return 0;
if (exc->keyfile != NULL) {
exc->key = load_key(exc->keyfile, exc->keyform,
0, NULL, NULL, "server key");
} else {
exc->key = load_key(exc->certfile, exc->certform,
0, NULL, NULL, "server key");
}
if (exc->key == NULL)
return 0;
if (exc->chainfile != NULL) {
if (!load_certs(exc->chainfile, 0, &exc->chain, NULL, "server chain"))
return 0;
}
}
return 1;
}
enum range { OPT_X_ENUM };
int args_excert(int opt, SSL_EXCERT **pexc)
{
SSL_EXCERT *exc = *pexc;
assert(opt > OPT_X__FIRST);
assert(opt < OPT_X__LAST);
if (exc == NULL) {
if (!ssl_excert_prepend(&exc)) {
BIO_printf(bio_err, " %s: Error initialising xcert\n",
opt_getprog());
goto err;
}
*pexc = exc;
}
switch ((enum range)opt) {
case OPT_X__FIRST:
case OPT_X__LAST:
return 0;
case OPT_X_CERT:
if (exc->certfile != NULL && !ssl_excert_prepend(&exc)) {
BIO_printf(bio_err, "%s: Error adding xcert\n", opt_getprog());
goto err;
}
*pexc = exc;
exc->certfile = opt_arg();
break;
case OPT_X_KEY:
if (exc->keyfile != NULL) {
BIO_printf(bio_err, "%s: Key already specified\n", opt_getprog());
goto err;
}
exc->keyfile = opt_arg();
break;
case OPT_X_CHAIN:
if (exc->chainfile != NULL) {
BIO_printf(bio_err, "%s: Chain already specified\n",
opt_getprog());
goto err;
}
exc->chainfile = opt_arg();
break;
case OPT_X_CHAIN_BUILD:
exc->build_chain = 1;
break;
case OPT_X_CERTFORM:
if (!opt_format(opt_arg(), OPT_FMT_ANY, &exc->certform))
return 0;
break;
case OPT_X_KEYFORM:
if (!opt_format(opt_arg(), OPT_FMT_ANY, &exc->keyform))
return 0;
break;
}
return 1;
err:
ERR_print_errors(bio_err);
ssl_excert_free(exc);
*pexc = NULL;
return 0;
}
static void print_raw_cipherlist(SSL *s)
{
const unsigned char *rlist;
static const unsigned char scsv_id[] = { 0, 0xFF };
size_t i, rlistlen, num;
if (!SSL_is_server(s))
return;
num = SSL_get0_raw_cipherlist(s, NULL);
OPENSSL_assert(num == 2);
rlistlen = SSL_get0_raw_cipherlist(s, &rlist);
BIO_puts(bio_err, "Client cipher list: ");
for (i = 0; i < rlistlen; i += num, rlist += num) {
const SSL_CIPHER *c = SSL_CIPHER_find(s, rlist);
if (i)
BIO_puts(bio_err, ":");
if (c != NULL) {
BIO_puts(bio_err, SSL_CIPHER_get_name(c));
} else if (memcmp(rlist, scsv_id, num) == 0) {
BIO_puts(bio_err, "SCSV");
} else {
size_t j;
BIO_puts(bio_err, "0x");
for (j = 0; j < num; j++)
BIO_printf(bio_err, "%02X", rlist[j]);
}
}
BIO_puts(bio_err, "\n");
}
/*
* Hex encoder for TLSA RRdata, not ':' delimited.
*/
static char *hexencode(const unsigned char *data, size_t len)
{
static const char *hex = "0123456789abcdef";
char *out;
char *cp;
size_t outlen = 2 * len + 1;
int ilen = (int) outlen;
if (outlen < len || ilen < 0 || outlen != (size_t)ilen) {
BIO_printf(bio_err, "%s: %zu-byte buffer too large to hexencode\n",
opt_getprog(), len);
exit(1);
}
cp = out = app_malloc(ilen, "TLSA hex data buffer");
while (len-- > 0) {
*cp++ = hex[(*data >> 4) & 0x0f];
*cp++ = hex[*data++ & 0x0f];
}
*cp = '\0';
return out;
}
void print_verify_detail(SSL *s, BIO *bio)
{
int mdpth;
EVP_PKEY *mspki;
long verify_err = SSL_get_verify_result(s);
if (verify_err == X509_V_OK) {
const char *peername = SSL_get0_peername(s);
BIO_printf(bio, "Verification: OK\n");
if (peername != NULL)
BIO_printf(bio, "Verified peername: %s\n", peername);
} else {
const char *reason = X509_verify_cert_error_string(verify_err);
BIO_printf(bio, "Verification error: %s\n", reason);
}
if ((mdpth = SSL_get0_dane_authority(s, NULL, &mspki)) >= 0) {
uint8_t usage, selector, mtype;
const unsigned char *data = NULL;
size_t dlen = 0;
char *hexdata;
mdpth = SSL_get0_dane_tlsa(s, &usage, &selector, &mtype, &data, &dlen);
/*
* The TLSA data field can be quite long when it is a certificate,
* public key or even a SHA2-512 digest. Because the initial octets of
* ASN.1 certificates and public keys contain mostly boilerplate OIDs
* and lengths, we show the last 12 bytes of the data instead, as these
* are more likely to distinguish distinct TLSA records.
*/
#define TLSA_TAIL_SIZE 12
if (dlen > TLSA_TAIL_SIZE)
hexdata = hexencode(data + dlen - TLSA_TAIL_SIZE, TLSA_TAIL_SIZE);
else
hexdata = hexencode(data, dlen);
BIO_printf(bio, "DANE TLSA %d %d %d %s%s %s at depth %d\n",
usage, selector, mtype,
(dlen > TLSA_TAIL_SIZE) ? "..." : "", hexdata,
(mspki != NULL) ? "signed the certificate" :
mdpth ? "matched TA certificate" : "matched EE certificate",
mdpth);
OPENSSL_free(hexdata);
}
}
void print_ssl_summary(SSL *s)
{
const SSL_CIPHER *c;
X509 *peer;
BIO_printf(bio_err, "Protocol version: %s\n", SSL_get_version(s));
print_raw_cipherlist(s);
c = SSL_get_current_cipher(s);
BIO_printf(bio_err, "Ciphersuite: %s\n", SSL_CIPHER_get_name(c));
do_print_sigalgs(bio_err, s, 0);
peer = SSL_get0_peer_certificate(s);
if (peer != NULL) {
int nid;
BIO_puts(bio_err, "Peer certificate: ");
X509_NAME_print_ex(bio_err, X509_get_subject_name(peer),
0, get_nameopt());
BIO_puts(bio_err, "\n");
if (SSL_get_peer_signature_nid(s, &nid))
BIO_printf(bio_err, "Hash used: %s\n", OBJ_nid2sn(nid));
if (SSL_get_peer_signature_type_nid(s, &nid))
BIO_printf(bio_err, "Signature type: %s\n", get_sigtype(nid));
print_verify_detail(s, bio_err);
} else {
BIO_puts(bio_err, "No peer certificate\n");
}
#ifndef OPENSSL_NO_EC
ssl_print_point_formats(bio_err, s);
if (SSL_is_server(s))
ssl_print_groups(bio_err, s, 1);
else
ssl_print_tmp_key(bio_err, s);
#else
if (!SSL_is_server(s))
ssl_print_tmp_key(bio_err, s);
#endif
}
int config_ctx(SSL_CONF_CTX *cctx, STACK_OF(OPENSSL_STRING) *str,
SSL_CTX *ctx)
{
int i;
SSL_CONF_CTX_set_ssl_ctx(cctx, ctx);
for (i = 0; i < sk_OPENSSL_STRING_num(str); i += 2) {
const char *flag = sk_OPENSSL_STRING_value(str, i);
const char *arg = sk_OPENSSL_STRING_value(str, i + 1);
if (SSL_CONF_cmd(cctx, flag, arg) <= 0) {
BIO_printf(bio_err, "Call to SSL_CONF_cmd(%s, %s) failed\n",
flag, arg == NULL ? "<NULL>" : arg);
ERR_print_errors(bio_err);
return 0;
}
}
if (!SSL_CONF_CTX_finish(cctx)) {
BIO_puts(bio_err, "Error finishing context\n");
ERR_print_errors(bio_err);
return 0;
}
return 1;
}
static int add_crls_store(X509_STORE *st, STACK_OF(X509_CRL) *crls)
{
X509_CRL *crl;
int i, ret = 1;
for (i = 0; i < sk_X509_CRL_num(crls); i++) {
crl = sk_X509_CRL_value(crls, i);
if (!X509_STORE_add_crl(st, crl))
ret = 0;
}
return ret;
}
int ssl_ctx_add_crls(SSL_CTX *ctx, STACK_OF(X509_CRL) *crls, int crl_download)
{
X509_STORE *st;
st = SSL_CTX_get_cert_store(ctx);
add_crls_store(st, crls);
if (crl_download)
store_setup_crl_download(st);
return 1;
}
int ssl_load_stores(SSL_CTX *ctx,
const char *vfyCApath, const char *vfyCAfile,
const char *vfyCAstore,
const char *chCApath, const char *chCAfile,
const char *chCAstore,
STACK_OF(X509_CRL) *crls, int crl_download)
{
X509_STORE *vfy = NULL, *ch = NULL;
int rv = 0;
if (vfyCApath != NULL || vfyCAfile != NULL || vfyCAstore != NULL) {
vfy = X509_STORE_new();
if (vfy == NULL)
goto err;
if (vfyCAfile != NULL && !X509_STORE_load_file(vfy, vfyCAfile))
goto err;
if (vfyCApath != NULL && !X509_STORE_load_path(vfy, vfyCApath))
goto err;
if (vfyCAstore != NULL && !X509_STORE_load_store(vfy, vfyCAstore))
goto err;
add_crls_store(vfy, crls);
- SSL_CTX_set1_verify_cert_store(ctx, vfy);
+ if (SSL_CTX_set1_verify_cert_store(ctx, vfy) == 0)
+ goto err;
if (crl_download)
store_setup_crl_download(vfy);
}
if (chCApath != NULL || chCAfile != NULL || chCAstore != NULL) {
ch = X509_STORE_new();
if (ch == NULL)
goto err;
if (chCAfile != NULL && !X509_STORE_load_file(ch, chCAfile))
goto err;
if (chCApath != NULL && !X509_STORE_load_path(ch, chCApath))
goto err;
if (chCAstore != NULL && !X509_STORE_load_store(ch, chCAstore))
goto err;
- SSL_CTX_set1_chain_cert_store(ctx, ch);
+ if (SSL_CTX_set1_chain_cert_store(ctx, ch) == 0)
+ goto err;
}
rv = 1;
err:
X509_STORE_free(vfy);
X509_STORE_free(ch);
return rv;
}
/* Verbose print out of security callback */
typedef struct {
BIO *out;
int verbose;
int (*old_cb) (const SSL *s, const SSL_CTX *ctx, int op, int bits, int nid,
void *other, void *ex);
} security_debug_ex;
static STRINT_PAIR callback_types[] = {
{"Supported Ciphersuite", SSL_SECOP_CIPHER_SUPPORTED},
{"Shared Ciphersuite", SSL_SECOP_CIPHER_SHARED},
{"Check Ciphersuite", SSL_SECOP_CIPHER_CHECK},
#ifndef OPENSSL_NO_DH
{"Temp DH key bits", SSL_SECOP_TMP_DH},
#endif
{"Supported Curve", SSL_SECOP_CURVE_SUPPORTED},
{"Shared Curve", SSL_SECOP_CURVE_SHARED},
{"Check Curve", SSL_SECOP_CURVE_CHECK},
{"Supported Signature Algorithm", SSL_SECOP_SIGALG_SUPPORTED},
{"Shared Signature Algorithm", SSL_SECOP_SIGALG_SHARED},
{"Check Signature Algorithm", SSL_SECOP_SIGALG_CHECK},
{"Signature Algorithm mask", SSL_SECOP_SIGALG_MASK},
{"Certificate chain EE key", SSL_SECOP_EE_KEY},
{"Certificate chain CA key", SSL_SECOP_CA_KEY},
{"Peer Chain EE key", SSL_SECOP_PEER_EE_KEY},
{"Peer Chain CA key", SSL_SECOP_PEER_CA_KEY},
{"Certificate chain CA digest", SSL_SECOP_CA_MD},
{"Peer chain CA digest", SSL_SECOP_PEER_CA_MD},
{"SSL compression", SSL_SECOP_COMPRESSION},
{"Session ticket", SSL_SECOP_TICKET},
{NULL}
};
static int security_callback_debug(const SSL *s, const SSL_CTX *ctx,
int op, int bits, int nid,
void *other, void *ex)
{
security_debug_ex *sdb = ex;
int rv, show_bits = 1, cert_md = 0;
const char *nm;
int show_nm;
rv = sdb->old_cb(s, ctx, op, bits, nid, other, ex);
if (rv == 1 && sdb->verbose < 2)
return 1;
BIO_puts(sdb->out, "Security callback: ");
nm = lookup(op, callback_types, NULL);
show_nm = nm != NULL;
switch (op) {
case SSL_SECOP_TICKET:
case SSL_SECOP_COMPRESSION:
show_bits = 0;
show_nm = 0;
break;
case SSL_SECOP_VERSION:
BIO_printf(sdb->out, "Version=%s", lookup(nid, ssl_versions, "???"));
show_bits = 0;
show_nm = 0;
break;
case SSL_SECOP_CA_MD:
case SSL_SECOP_PEER_CA_MD:
cert_md = 1;
break;
case SSL_SECOP_SIGALG_SUPPORTED:
case SSL_SECOP_SIGALG_SHARED:
case SSL_SECOP_SIGALG_CHECK:
case SSL_SECOP_SIGALG_MASK:
show_nm = 0;
break;
}
if (show_nm)
BIO_printf(sdb->out, "%s=", nm);
switch (op & SSL_SECOP_OTHER_TYPE) {
case SSL_SECOP_OTHER_CIPHER:
BIO_puts(sdb->out, SSL_CIPHER_get_name(other));
break;
#ifndef OPENSSL_NO_EC
case SSL_SECOP_OTHER_CURVE:
{
const char *cname;
cname = EC_curve_nid2nist(nid);
if (cname == NULL)
cname = OBJ_nid2sn(nid);
BIO_puts(sdb->out, cname);
}
break;
#endif
case SSL_SECOP_OTHER_CERT:
{
if (cert_md) {
int sig_nid = X509_get_signature_nid(other);
BIO_puts(sdb->out, OBJ_nid2sn(sig_nid));
} else {
EVP_PKEY *pkey = X509_get0_pubkey(other);
if (pkey == NULL) {
BIO_printf(sdb->out, "Public key missing");
} else {
const char *algname = "";
EVP_PKEY_asn1_get0_info(NULL, NULL, NULL, NULL,
&algname, EVP_PKEY_get0_asn1(pkey));
BIO_printf(sdb->out, "%s, bits=%d",
algname, EVP_PKEY_get_bits(pkey));
}
}
break;
}
case SSL_SECOP_OTHER_SIGALG:
{
const unsigned char *salg = other;
const char *sname = NULL;
int raw_sig_code = (salg[0] << 8) + salg[1]; /* always big endian (msb, lsb) */
/* raw_sig_code: signature_scheme from tls1.3, or signature_and_hash from tls1.2 */
if (nm != NULL)
BIO_printf(sdb->out, "%s", nm);
else
BIO_printf(sdb->out, "s_cb.c:security_callback_debug op=0x%x", op);
sname = lookup(raw_sig_code, signature_tls13_scheme_list, NULL);
if (sname != NULL) {
BIO_printf(sdb->out, " scheme=%s", sname);
} else {
int alg_code = salg[1];
int hash_code = salg[0];
const char *alg_str = lookup(alg_code, signature_tls12_alg_list, NULL);
const char *hash_str = lookup(hash_code, signature_tls12_hash_list, NULL);
if (alg_str != NULL && hash_str != NULL)
BIO_printf(sdb->out, " digest=%s, algorithm=%s", hash_str, alg_str);
else
BIO_printf(sdb->out, " scheme=unknown(0x%04x)", raw_sig_code);
}
}
}
if (show_bits)
BIO_printf(sdb->out, ", security bits=%d", bits);
BIO_printf(sdb->out, ": %s\n", rv ? "yes" : "no");
return rv;
}
void ssl_ctx_security_debug(SSL_CTX *ctx, int verbose)
{
static security_debug_ex sdb;
sdb.out = bio_err;
sdb.verbose = verbose;
sdb.old_cb = SSL_CTX_get_security_callback(ctx);
SSL_CTX_set_security_callback(ctx, security_callback_debug);
SSL_CTX_set0_security_ex_data(ctx, &sdb);
}
static void keylog_callback(const SSL *ssl, const char *line)
{
if (bio_keylog == NULL) {
BIO_printf(bio_err, "Keylog callback is invoked without valid file!\n");
return;
}
/*
* There might be concurrent writers to the keylog file, so we must ensure
* that the given line is written at once.
*/
BIO_printf(bio_keylog, "%s\n", line);
(void)BIO_flush(bio_keylog);
}
int set_keylog_file(SSL_CTX *ctx, const char *keylog_file)
{
/* Close any open files */
BIO_free_all(bio_keylog);
bio_keylog = NULL;
if (ctx == NULL || keylog_file == NULL) {
/* Keylogging is disabled, OK. */
return 0;
}
/*
* Append rather than write in order to allow concurrent modification.
* Furthermore, this preserves existing keylog files which is useful when
* the tool is run multiple times.
*/
bio_keylog = BIO_new_file(keylog_file, "a");
if (bio_keylog == NULL) {
BIO_printf(bio_err, "Error writing keylog file %s\n", keylog_file);
return 1;
}
/* Write a header for seekable, empty files (this excludes pipes). */
if (BIO_tell(bio_keylog) == 0) {
BIO_puts(bio_keylog,
"# SSL/TLS secrets log file, generated by OpenSSL\n");
(void)BIO_flush(bio_keylog);
}
SSL_CTX_set_keylog_callback(ctx, keylog_callback);
return 0;
}
void print_ca_names(BIO *bio, SSL *s)
{
const char *cs = SSL_is_server(s) ? "server" : "client";
const STACK_OF(X509_NAME) *sk = SSL_get0_peer_CA_list(s);
int i;
if (sk == NULL || sk_X509_NAME_num(sk) == 0) {
if (!SSL_is_server(s))
BIO_printf(bio, "---\nNo %s certificate CA names sent\n", cs);
return;
}
BIO_printf(bio, "---\nAcceptable %s certificate CA names\n",cs);
for (i = 0; i < sk_X509_NAME_num(sk); i++) {
X509_NAME_print_ex(bio, sk_X509_NAME_value(sk, i), 0, get_nameopt());
BIO_write(bio, "\n", 1);
}
}
diff --git a/crypto/openssl/apps/list.c b/crypto/openssl/apps/list.c
index 0fcbcbb083cb..7d3136a8a161 100644
--- a/crypto/openssl/apps/list.c
+++ b/crypto/openssl/apps/list.c
@@ -1,1716 +1,1717 @@
/*
- * Copyright 1995-2022 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 1995-2024 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
/* We need to use some deprecated APIs */
#define OPENSSL_SUPPRESS_DEPRECATED
#include <string.h>
#include <openssl/evp.h>
#include <openssl/err.h>
#include <openssl/provider.h>
#include <openssl/safestack.h>
#include <openssl/kdf.h>
#include <openssl/encoder.h>
#include <openssl/decoder.h>
#include <openssl/store.h>
#include <openssl/core_names.h>
#include <openssl/rand.h>
#include "apps.h"
#include "app_params.h"
#include "progs.h"
#include "opt.h"
#include "names.h"
static int verbose = 0;
static const char *select_name = NULL;
/* Checks to see if algorithms are fetchable */
#define IS_FETCHABLE(type, TYPE) \
static int is_ ## type ## _fetchable(const TYPE *alg) \
{ \
TYPE *impl; \
const char *propq = app_get0_propq(); \
OSSL_LIB_CTX *libctx = app_get0_libctx(); \
const char *name = TYPE ## _get0_name(alg); \
\
ERR_set_mark(); \
impl = TYPE ## _fetch(libctx, name, propq); \
ERR_pop_to_mark(); \
if (impl == NULL) \
return 0; \
TYPE ## _free(impl); \
return 1; \
}
IS_FETCHABLE(cipher, EVP_CIPHER)
IS_FETCHABLE(digest, EVP_MD)
IS_FETCHABLE(mac, EVP_MAC)
IS_FETCHABLE(kdf, EVP_KDF)
IS_FETCHABLE(rand, EVP_RAND)
IS_FETCHABLE(keymgmt, EVP_KEYMGMT)
IS_FETCHABLE(signature, EVP_SIGNATURE)
IS_FETCHABLE(kem, EVP_KEM)
IS_FETCHABLE(asym_cipher, EVP_ASYM_CIPHER)
IS_FETCHABLE(keyexch, EVP_KEYEXCH)
IS_FETCHABLE(decoder, OSSL_DECODER)
IS_FETCHABLE(encoder, OSSL_ENCODER)
#ifndef OPENSSL_NO_DEPRECATED_3_0
static int include_legacy(void)
{
return app_get0_propq() == NULL;
}
static void legacy_cipher_fn(const EVP_CIPHER *c,
const char *from, const char *to, void *arg)
{
if (select_name != NULL
&& (c == NULL
|| OPENSSL_strcasecmp(select_name, EVP_CIPHER_get0_name(c)) != 0))
return;
if (c != NULL) {
BIO_printf(arg, " %s\n", EVP_CIPHER_get0_name(c));
} else {
if (from == NULL)
from = "<undefined>";
if (to == NULL)
to = "<undefined>";
BIO_printf(arg, " %s => %s\n", from, to);
}
}
#endif
DEFINE_STACK_OF(EVP_CIPHER)
static int cipher_cmp(const EVP_CIPHER * const *a,
const EVP_CIPHER * const *b)
{
return strcmp(OSSL_PROVIDER_get0_name(EVP_CIPHER_get0_provider(*a)),
OSSL_PROVIDER_get0_name(EVP_CIPHER_get0_provider(*b)));
}
static void collect_ciphers(EVP_CIPHER *cipher, void *stack)
{
STACK_OF(EVP_CIPHER) *cipher_stack = stack;
if (is_cipher_fetchable(cipher)
&& sk_EVP_CIPHER_push(cipher_stack, cipher) > 0)
EVP_CIPHER_up_ref(cipher);
}
static void list_ciphers(void)
{
STACK_OF(EVP_CIPHER) *ciphers = sk_EVP_CIPHER_new(cipher_cmp);
int i;
if (ciphers == NULL) {
BIO_printf(bio_err, "ERROR: Memory allocation\n");
return;
}
#ifndef OPENSSL_NO_DEPRECATED_3_0
if (include_legacy()) {
BIO_printf(bio_out, "Legacy:\n");
EVP_CIPHER_do_all_sorted(legacy_cipher_fn, bio_out);
}
#endif
BIO_printf(bio_out, "Provided:\n");
EVP_CIPHER_do_all_provided(app_get0_libctx(), collect_ciphers, ciphers);
sk_EVP_CIPHER_sort(ciphers);
for (i = 0; i < sk_EVP_CIPHER_num(ciphers); i++) {
const EVP_CIPHER *c = sk_EVP_CIPHER_value(ciphers, i);
STACK_OF(OPENSSL_CSTRING) *names = NULL;
if (select_name != NULL && !EVP_CIPHER_is_a(c, select_name))
continue;
names = sk_OPENSSL_CSTRING_new(name_cmp);
if (names != NULL && EVP_CIPHER_names_do_all(c, collect_names, names)) {
BIO_printf(bio_out, " ");
print_names(bio_out, names);
BIO_printf(bio_out, " @ %s\n",
OSSL_PROVIDER_get0_name(EVP_CIPHER_get0_provider(c)));
if (verbose) {
const char *desc = EVP_CIPHER_get0_description(c);
if (desc != NULL)
BIO_printf(bio_out, " description: %s\n", desc);
print_param_types("retrievable algorithm parameters",
EVP_CIPHER_gettable_params(c), 4);
print_param_types("retrievable operation parameters",
EVP_CIPHER_gettable_ctx_params(c), 4);
print_param_types("settable operation parameters",
EVP_CIPHER_settable_ctx_params(c), 4);
}
}
sk_OPENSSL_CSTRING_free(names);
}
sk_EVP_CIPHER_pop_free(ciphers, EVP_CIPHER_free);
}
#ifndef OPENSSL_NO_DEPRECATED_3_0
static void legacy_md_fn(const EVP_MD *m,
const char *from, const char *to, void *arg)
{
if (m != NULL) {
BIO_printf(arg, " %s\n", EVP_MD_get0_name(m));
} else {
if (from == NULL)
from = "<undefined>";
if (to == NULL)
to = "<undefined>";
BIO_printf((BIO *)arg, " %s => %s\n", from, to);
}
}
#endif
DEFINE_STACK_OF(EVP_MD)
static int md_cmp(const EVP_MD * const *a, const EVP_MD * const *b)
{
return strcmp(OSSL_PROVIDER_get0_name(EVP_MD_get0_provider(*a)),
OSSL_PROVIDER_get0_name(EVP_MD_get0_provider(*b)));
}
static void collect_digests(EVP_MD *digest, void *stack)
{
STACK_OF(EVP_MD) *digest_stack = stack;
if (is_digest_fetchable(digest)
&& sk_EVP_MD_push(digest_stack, digest) > 0)
EVP_MD_up_ref(digest);
}
static void list_digests(void)
{
STACK_OF(EVP_MD) *digests = sk_EVP_MD_new(md_cmp);
int i;
if (digests == NULL) {
BIO_printf(bio_err, "ERROR: Memory allocation\n");
return;
}
#ifndef OPENSSL_NO_DEPRECATED_3_0
if (include_legacy()) {
BIO_printf(bio_out, "Legacy:\n");
EVP_MD_do_all_sorted(legacy_md_fn, bio_out);
}
#endif
BIO_printf(bio_out, "Provided:\n");
EVP_MD_do_all_provided(app_get0_libctx(), collect_digests, digests);
sk_EVP_MD_sort(digests);
for (i = 0; i < sk_EVP_MD_num(digests); i++) {
const EVP_MD *m = sk_EVP_MD_value(digests, i);
STACK_OF(OPENSSL_CSTRING) *names = NULL;
if (select_name != NULL && !EVP_MD_is_a(m, select_name))
continue;
names = sk_OPENSSL_CSTRING_new(name_cmp);
if (names != NULL && EVP_MD_names_do_all(m, collect_names, names)) {
BIO_printf(bio_out, " ");
print_names(bio_out, names);
BIO_printf(bio_out, " @ %s\n",
OSSL_PROVIDER_get0_name(EVP_MD_get0_provider(m)));
if (verbose) {
const char *desc = EVP_MD_get0_description(m);
if (desc != NULL)
BIO_printf(bio_out, " description: %s\n", desc);
print_param_types("retrievable algorithm parameters",
EVP_MD_gettable_params(m), 4);
print_param_types("retrievable operation parameters",
EVP_MD_gettable_ctx_params(m), 4);
print_param_types("settable operation parameters",
EVP_MD_settable_ctx_params(m), 4);
}
}
sk_OPENSSL_CSTRING_free(names);
}
sk_EVP_MD_pop_free(digests, EVP_MD_free);
}
DEFINE_STACK_OF(EVP_MAC)
static int mac_cmp(const EVP_MAC * const *a, const EVP_MAC * const *b)
{
return strcmp(OSSL_PROVIDER_get0_name(EVP_MAC_get0_provider(*a)),
OSSL_PROVIDER_get0_name(EVP_MAC_get0_provider(*b)));
}
static void collect_macs(EVP_MAC *mac, void *stack)
{
STACK_OF(EVP_MAC) *mac_stack = stack;
if (is_mac_fetchable(mac)
&& sk_EVP_MAC_push(mac_stack, mac) > 0)
EVP_MAC_up_ref(mac);
}
static void list_macs(void)
{
STACK_OF(EVP_MAC) *macs = sk_EVP_MAC_new(mac_cmp);
int i;
if (macs == NULL) {
BIO_printf(bio_err, "ERROR: Memory allocation\n");
return;
}
BIO_printf(bio_out, "Provided MACs:\n");
EVP_MAC_do_all_provided(app_get0_libctx(), collect_macs, macs);
sk_EVP_MAC_sort(macs);
for (i = 0; i < sk_EVP_MAC_num(macs); i++) {
const EVP_MAC *m = sk_EVP_MAC_value(macs, i);
STACK_OF(OPENSSL_CSTRING) *names = NULL;
if (select_name != NULL && !EVP_MAC_is_a(m, select_name))
continue;
names = sk_OPENSSL_CSTRING_new(name_cmp);
if (names != NULL && EVP_MAC_names_do_all(m, collect_names, names)) {
BIO_printf(bio_out, " ");
print_names(bio_out, names);
BIO_printf(bio_out, " @ %s\n",
OSSL_PROVIDER_get0_name(EVP_MAC_get0_provider(m)));
if (verbose) {
const char *desc = EVP_MAC_get0_description(m);
if (desc != NULL)
BIO_printf(bio_out, " description: %s\n", desc);
print_param_types("retrievable algorithm parameters",
EVP_MAC_gettable_params(m), 4);
print_param_types("retrievable operation parameters",
EVP_MAC_gettable_ctx_params(m), 4);
print_param_types("settable operation parameters",
EVP_MAC_settable_ctx_params(m), 4);
}
}
sk_OPENSSL_CSTRING_free(names);
}
sk_EVP_MAC_pop_free(macs, EVP_MAC_free);
}
/*
* KDFs and PRFs
*/
DEFINE_STACK_OF(EVP_KDF)
static int kdf_cmp(const EVP_KDF * const *a, const EVP_KDF * const *b)
{
return strcmp(OSSL_PROVIDER_get0_name(EVP_KDF_get0_provider(*a)),
OSSL_PROVIDER_get0_name(EVP_KDF_get0_provider(*b)));
}
static void collect_kdfs(EVP_KDF *kdf, void *stack)
{
STACK_OF(EVP_KDF) *kdf_stack = stack;
if (is_kdf_fetchable(kdf)
&& sk_EVP_KDF_push(kdf_stack, kdf) > 0)
EVP_KDF_up_ref(kdf);
}
static void list_kdfs(void)
{
STACK_OF(EVP_KDF) *kdfs = sk_EVP_KDF_new(kdf_cmp);
int i;
if (kdfs == NULL) {
BIO_printf(bio_err, "ERROR: Memory allocation\n");
return;
}
BIO_printf(bio_out, "Provided KDFs and PDFs:\n");
EVP_KDF_do_all_provided(app_get0_libctx(), collect_kdfs, kdfs);
sk_EVP_KDF_sort(kdfs);
for (i = 0; i < sk_EVP_KDF_num(kdfs); i++) {
const EVP_KDF *k = sk_EVP_KDF_value(kdfs, i);
STACK_OF(OPENSSL_CSTRING) *names = NULL;
if (select_name != NULL && !EVP_KDF_is_a(k, select_name))
continue;
names = sk_OPENSSL_CSTRING_new(name_cmp);
if (names != NULL && EVP_KDF_names_do_all(k, collect_names, names)) {
BIO_printf(bio_out, " ");
print_names(bio_out, names);
BIO_printf(bio_out, " @ %s\n",
OSSL_PROVIDER_get0_name(EVP_KDF_get0_provider(k)));
if (verbose) {
const char *desc = EVP_KDF_get0_description(k);
if (desc != NULL)
BIO_printf(bio_out, " description: %s\n", desc);
print_param_types("retrievable algorithm parameters",
EVP_KDF_gettable_params(k), 4);
print_param_types("retrievable operation parameters",
EVP_KDF_gettable_ctx_params(k), 4);
print_param_types("settable operation parameters",
EVP_KDF_settable_ctx_params(k), 4);
}
}
sk_OPENSSL_CSTRING_free(names);
}
sk_EVP_KDF_pop_free(kdfs, EVP_KDF_free);
}
/*
* RANDs
*/
DEFINE_STACK_OF(EVP_RAND)
static int rand_cmp(const EVP_RAND * const *a, const EVP_RAND * const *b)
{
int ret = OPENSSL_strcasecmp(EVP_RAND_get0_name(*a), EVP_RAND_get0_name(*b));
if (ret == 0)
ret = strcmp(OSSL_PROVIDER_get0_name(EVP_RAND_get0_provider(*a)),
OSSL_PROVIDER_get0_name(EVP_RAND_get0_provider(*b)));
return ret;
}
static void collect_rands(EVP_RAND *rand, void *stack)
{
STACK_OF(EVP_RAND) *rand_stack = stack;
if (is_rand_fetchable(rand)
&& sk_EVP_RAND_push(rand_stack, rand) > 0)
EVP_RAND_up_ref(rand);
}
static void list_random_generators(void)
{
STACK_OF(EVP_RAND) *rands = sk_EVP_RAND_new(rand_cmp);
int i;
if (rands == NULL) {
BIO_printf(bio_err, "ERROR: Memory allocation\n");
return;
}
BIO_printf(bio_out, "Provided RNGs and seed sources:\n");
EVP_RAND_do_all_provided(app_get0_libctx(), collect_rands, rands);
sk_EVP_RAND_sort(rands);
for (i = 0; i < sk_EVP_RAND_num(rands); i++) {
const EVP_RAND *m = sk_EVP_RAND_value(rands, i);
if (select_name != NULL
&& OPENSSL_strcasecmp(EVP_RAND_get0_name(m), select_name) != 0)
continue;
BIO_printf(bio_out, " %s", EVP_RAND_get0_name(m));
BIO_printf(bio_out, " @ %s\n",
OSSL_PROVIDER_get0_name(EVP_RAND_get0_provider(m)));
if (verbose) {
const char *desc = EVP_RAND_get0_description(m);
if (desc != NULL)
BIO_printf(bio_out, " description: %s\n", desc);
print_param_types("retrievable algorithm parameters",
EVP_RAND_gettable_params(m), 4);
print_param_types("retrievable operation parameters",
EVP_RAND_gettable_ctx_params(m), 4);
print_param_types("settable operation parameters",
EVP_RAND_settable_ctx_params(m), 4);
}
}
sk_EVP_RAND_pop_free(rands, EVP_RAND_free);
}
static void display_random(const char *name, EVP_RAND_CTX *drbg)
{
EVP_RAND *rand;
uint64_t u;
const char *p;
const OSSL_PARAM *gettables;
OSSL_PARAM params[2] = { OSSL_PARAM_END, OSSL_PARAM_END };
unsigned char buf[1000];
BIO_printf(bio_out, "%s:\n", name);
if (drbg != NULL) {
rand = EVP_RAND_CTX_get0_rand(drbg);
BIO_printf(bio_out, " %s", EVP_RAND_get0_name(rand));
BIO_printf(bio_out, " @ %s\n",
OSSL_PROVIDER_get0_name(EVP_RAND_get0_provider(rand)));
switch (EVP_RAND_get_state(drbg)) {
case EVP_RAND_STATE_UNINITIALISED:
p = "uninitialised";
break;
case EVP_RAND_STATE_READY:
p = "ready";
break;
case EVP_RAND_STATE_ERROR:
p = "error";
break;
default:
p = "unknown";
break;
}
BIO_printf(bio_out, " state = %s\n", p);
gettables = EVP_RAND_gettable_ctx_params(rand);
if (gettables != NULL)
for (; gettables->key != NULL; gettables++) {
/* State has been dealt with already, so ignore */
if (OPENSSL_strcasecmp(gettables->key, OSSL_RAND_PARAM_STATE) == 0)
continue;
/* Outside of verbose mode, we skip non-string values */
if (gettables->data_type != OSSL_PARAM_UTF8_STRING
&& gettables->data_type != OSSL_PARAM_UTF8_PTR
&& !verbose)
continue;
params->key = gettables->key;
params->data_type = gettables->data_type;
if (gettables->data_type == OSSL_PARAM_UNSIGNED_INTEGER
|| gettables->data_type == OSSL_PARAM_INTEGER) {
params->data = &u;
params->data_size = sizeof(u);
} else {
params->data = buf;
params->data_size = sizeof(buf);
}
params->return_size = 0;
if (EVP_RAND_CTX_get_params(drbg, params))
print_param_value(params, 2);
}
}
}
static void list_random_instances(void)
{
display_random("primary", RAND_get0_primary(NULL));
display_random("public", RAND_get0_public(NULL));
display_random("private", RAND_get0_private(NULL));
}
/*
* Encoders
*/
DEFINE_STACK_OF(OSSL_ENCODER)
static int encoder_cmp(const OSSL_ENCODER * const *a,
const OSSL_ENCODER * const *b)
{
return strcmp(OSSL_PROVIDER_get0_name(OSSL_ENCODER_get0_provider(*a)),
OSSL_PROVIDER_get0_name(OSSL_ENCODER_get0_provider(*b)));
}
static void collect_encoders(OSSL_ENCODER *encoder, void *stack)
{
STACK_OF(OSSL_ENCODER) *encoder_stack = stack;
if (is_encoder_fetchable(encoder)
&& sk_OSSL_ENCODER_push(encoder_stack, encoder) > 0)
OSSL_ENCODER_up_ref(encoder);
}
static void list_encoders(void)
{
STACK_OF(OSSL_ENCODER) *encoders;
int i;
encoders = sk_OSSL_ENCODER_new(encoder_cmp);
if (encoders == NULL) {
BIO_printf(bio_err, "ERROR: Memory allocation\n");
return;
}
BIO_printf(bio_out, "Provided ENCODERs:\n");
OSSL_ENCODER_do_all_provided(app_get0_libctx(), collect_encoders,
encoders);
sk_OSSL_ENCODER_sort(encoders);
for (i = 0; i < sk_OSSL_ENCODER_num(encoders); i++) {
OSSL_ENCODER *k = sk_OSSL_ENCODER_value(encoders, i);
STACK_OF(OPENSSL_CSTRING) *names = NULL;
if (select_name != NULL && !OSSL_ENCODER_is_a(k, select_name))
continue;
names = sk_OPENSSL_CSTRING_new(name_cmp);
if (names != NULL && OSSL_ENCODER_names_do_all(k, collect_names, names)) {
BIO_printf(bio_out, " ");
print_names(bio_out, names);
BIO_printf(bio_out, " @ %s (%s)\n",
OSSL_PROVIDER_get0_name(OSSL_ENCODER_get0_provider(k)),
OSSL_ENCODER_get0_properties(k));
if (verbose) {
const char *desc = OSSL_ENCODER_get0_description(k);
if (desc != NULL)
BIO_printf(bio_out, " description: %s\n", desc);
print_param_types("settable operation parameters",
OSSL_ENCODER_settable_ctx_params(k), 4);
}
}
sk_OPENSSL_CSTRING_free(names);
}
sk_OSSL_ENCODER_pop_free(encoders, OSSL_ENCODER_free);
}
/*
* Decoders
*/
DEFINE_STACK_OF(OSSL_DECODER)
static int decoder_cmp(const OSSL_DECODER * const *a,
const OSSL_DECODER * const *b)
{
return strcmp(OSSL_PROVIDER_get0_name(OSSL_DECODER_get0_provider(*a)),
OSSL_PROVIDER_get0_name(OSSL_DECODER_get0_provider(*b)));
}
static void collect_decoders(OSSL_DECODER *decoder, void *stack)
{
STACK_OF(OSSL_DECODER) *decoder_stack = stack;
if (is_decoder_fetchable(decoder)
&& sk_OSSL_DECODER_push(decoder_stack, decoder) > 0)
OSSL_DECODER_up_ref(decoder);
}
static void list_decoders(void)
{
STACK_OF(OSSL_DECODER) *decoders;
int i;
decoders = sk_OSSL_DECODER_new(decoder_cmp);
if (decoders == NULL) {
BIO_printf(bio_err, "ERROR: Memory allocation\n");
return;
}
BIO_printf(bio_out, "Provided DECODERs:\n");
OSSL_DECODER_do_all_provided(app_get0_libctx(), collect_decoders,
decoders);
sk_OSSL_DECODER_sort(decoders);
for (i = 0; i < sk_OSSL_DECODER_num(decoders); i++) {
OSSL_DECODER *k = sk_OSSL_DECODER_value(decoders, i);
STACK_OF(OPENSSL_CSTRING) *names = NULL;
if (select_name != NULL && !OSSL_DECODER_is_a(k, select_name))
continue;
names = sk_OPENSSL_CSTRING_new(name_cmp);
if (names != NULL && OSSL_DECODER_names_do_all(k, collect_names, names)) {
BIO_printf(bio_out, " ");
print_names(bio_out, names);
BIO_printf(bio_out, " @ %s (%s)\n",
OSSL_PROVIDER_get0_name(OSSL_DECODER_get0_provider(k)),
OSSL_DECODER_get0_properties(k));
if (verbose) {
const char *desc = OSSL_DECODER_get0_description(k);
if (desc != NULL)
BIO_printf(bio_out, " description: %s\n", desc);
print_param_types("settable operation parameters",
OSSL_DECODER_settable_ctx_params(k), 4);
}
}
sk_OPENSSL_CSTRING_free(names);
}
sk_OSSL_DECODER_pop_free(decoders, OSSL_DECODER_free);
}
DEFINE_STACK_OF(EVP_KEYMGMT)
static int keymanager_cmp(const EVP_KEYMGMT * const *a,
const EVP_KEYMGMT * const *b)
{
return strcmp(OSSL_PROVIDER_get0_name(EVP_KEYMGMT_get0_provider(*a)),
OSSL_PROVIDER_get0_name(EVP_KEYMGMT_get0_provider(*b)));
}
static void collect_keymanagers(EVP_KEYMGMT *km, void *stack)
{
STACK_OF(EVP_KEYMGMT) *km_stack = stack;
if (is_keymgmt_fetchable(km)
&& sk_EVP_KEYMGMT_push(km_stack, km) > 0)
EVP_KEYMGMT_up_ref(km);
}
static void list_keymanagers(void)
{
int i;
STACK_OF(EVP_KEYMGMT) *km_stack = sk_EVP_KEYMGMT_new(keymanager_cmp);
EVP_KEYMGMT_do_all_provided(app_get0_libctx(), collect_keymanagers,
km_stack);
sk_EVP_KEYMGMT_sort(km_stack);
for (i = 0; i < sk_EVP_KEYMGMT_num(km_stack); i++) {
EVP_KEYMGMT *k = sk_EVP_KEYMGMT_value(km_stack, i);
STACK_OF(OPENSSL_CSTRING) *names = NULL;
if (select_name != NULL && !EVP_KEYMGMT_is_a(k, select_name))
continue;
names = sk_OPENSSL_CSTRING_new(name_cmp);
if (names != NULL && EVP_KEYMGMT_names_do_all(k, collect_names, names)) {
const char *desc = EVP_KEYMGMT_get0_description(k);
BIO_printf(bio_out, " Name: ");
if (desc != NULL)
BIO_printf(bio_out, "%s", desc);
else
BIO_printf(bio_out, "%s", sk_OPENSSL_CSTRING_value(names, 0));
BIO_printf(bio_out, "\n");
BIO_printf(bio_out, " Type: Provider Algorithm\n");
BIO_printf(bio_out, " IDs: ");
print_names(bio_out, names);
BIO_printf(bio_out, " @ %s\n",
OSSL_PROVIDER_get0_name(EVP_KEYMGMT_get0_provider(k)));
if (verbose) {
print_param_types("settable key generation parameters",
EVP_KEYMGMT_gen_settable_params(k), 4);
print_param_types("settable operation parameters",
EVP_KEYMGMT_settable_params(k), 4);
print_param_types("retrievable operation parameters",
EVP_KEYMGMT_gettable_params(k), 4);
}
}
sk_OPENSSL_CSTRING_free(names);
}
sk_EVP_KEYMGMT_pop_free(km_stack, EVP_KEYMGMT_free);
}
DEFINE_STACK_OF(EVP_SIGNATURE)
static int signature_cmp(const EVP_SIGNATURE * const *a,
const EVP_SIGNATURE * const *b)
{
return strcmp(OSSL_PROVIDER_get0_name(EVP_SIGNATURE_get0_provider(*a)),
OSSL_PROVIDER_get0_name(EVP_SIGNATURE_get0_provider(*b)));
}
static void collect_signatures(EVP_SIGNATURE *sig, void *stack)
{
STACK_OF(EVP_SIGNATURE) *sig_stack = stack;
if (is_signature_fetchable(sig)
&& sk_EVP_SIGNATURE_push(sig_stack, sig) > 0)
EVP_SIGNATURE_up_ref(sig);
}
static void list_signatures(void)
{
int i, count = 0;
STACK_OF(EVP_SIGNATURE) *sig_stack = sk_EVP_SIGNATURE_new(signature_cmp);
EVP_SIGNATURE_do_all_provided(app_get0_libctx(), collect_signatures,
sig_stack);
sk_EVP_SIGNATURE_sort(sig_stack);
for (i = 0; i < sk_EVP_SIGNATURE_num(sig_stack); i++) {
EVP_SIGNATURE *k = sk_EVP_SIGNATURE_value(sig_stack, i);
STACK_OF(OPENSSL_CSTRING) *names = NULL;
if (select_name != NULL && !EVP_SIGNATURE_is_a(k, select_name))
continue;
names = sk_OPENSSL_CSTRING_new(name_cmp);
if (names != NULL && EVP_SIGNATURE_names_do_all(k, collect_names, names)) {
count++;
BIO_printf(bio_out, " ");
print_names(bio_out, names);
BIO_printf(bio_out, " @ %s\n",
OSSL_PROVIDER_get0_name(EVP_SIGNATURE_get0_provider(k)));
if (verbose) {
const char *desc = EVP_SIGNATURE_get0_description(k);
if (desc != NULL)
BIO_printf(bio_out, " description: %s\n", desc);
print_param_types("settable operation parameters",
EVP_SIGNATURE_settable_ctx_params(k), 4);
print_param_types("retrievable operation parameters",
EVP_SIGNATURE_gettable_ctx_params(k), 4);
}
}
sk_OPENSSL_CSTRING_free(names);
}
sk_EVP_SIGNATURE_pop_free(sig_stack, EVP_SIGNATURE_free);
if (count == 0)
BIO_printf(bio_out, " -\n");
}
DEFINE_STACK_OF(EVP_KEM)
static int kem_cmp(const EVP_KEM * const *a,
const EVP_KEM * const *b)
{
return strcmp(OSSL_PROVIDER_get0_name(EVP_KEM_get0_provider(*a)),
OSSL_PROVIDER_get0_name(EVP_KEM_get0_provider(*b)));
}
static void collect_kem(EVP_KEM *kem, void *stack)
{
STACK_OF(EVP_KEM) *kem_stack = stack;
if (is_kem_fetchable(kem)
&& sk_EVP_KEM_push(kem_stack, kem) > 0)
EVP_KEM_up_ref(kem);
}
static void list_kems(void)
{
int i, count = 0;
STACK_OF(EVP_KEM) *kem_stack = sk_EVP_KEM_new(kem_cmp);
EVP_KEM_do_all_provided(app_get0_libctx(), collect_kem, kem_stack);
sk_EVP_KEM_sort(kem_stack);
for (i = 0; i < sk_EVP_KEM_num(kem_stack); i++) {
EVP_KEM *k = sk_EVP_KEM_value(kem_stack, i);
STACK_OF(OPENSSL_CSTRING) *names = NULL;
if (select_name != NULL && !EVP_KEM_is_a(k, select_name))
continue;
names = sk_OPENSSL_CSTRING_new(name_cmp);
if (names != NULL && EVP_KEM_names_do_all(k, collect_names, names)) {
count++;
BIO_printf(bio_out, " ");
print_names(bio_out, names);
BIO_printf(bio_out, " @ %s\n",
OSSL_PROVIDER_get0_name(EVP_KEM_get0_provider(k)));
if (verbose) {
const char *desc = EVP_KEM_get0_description(k);
if (desc != NULL)
BIO_printf(bio_out, " description: %s\n", desc);
print_param_types("settable operation parameters",
EVP_KEM_settable_ctx_params(k), 4);
print_param_types("retrievable operation parameters",
EVP_KEM_gettable_ctx_params(k), 4);
}
}
sk_OPENSSL_CSTRING_free(names);
}
sk_EVP_KEM_pop_free(kem_stack, EVP_KEM_free);
if (count == 0)
BIO_printf(bio_out, " -\n");
}
DEFINE_STACK_OF(EVP_ASYM_CIPHER)
static int asymcipher_cmp(const EVP_ASYM_CIPHER * const *a,
const EVP_ASYM_CIPHER * const *b)
{
return strcmp(OSSL_PROVIDER_get0_name(EVP_ASYM_CIPHER_get0_provider(*a)),
OSSL_PROVIDER_get0_name(EVP_ASYM_CIPHER_get0_provider(*b)));
}
static void collect_asymciph(EVP_ASYM_CIPHER *asym_cipher, void *stack)
{
STACK_OF(EVP_ASYM_CIPHER) *asym_cipher_stack = stack;
if (is_asym_cipher_fetchable(asym_cipher)
&& sk_EVP_ASYM_CIPHER_push(asym_cipher_stack, asym_cipher) > 0)
EVP_ASYM_CIPHER_up_ref(asym_cipher);
}
static void list_asymciphers(void)
{
int i, count = 0;
STACK_OF(EVP_ASYM_CIPHER) *asymciph_stack =
sk_EVP_ASYM_CIPHER_new(asymcipher_cmp);
EVP_ASYM_CIPHER_do_all_provided(app_get0_libctx(), collect_asymciph,
asymciph_stack);
sk_EVP_ASYM_CIPHER_sort(asymciph_stack);
for (i = 0; i < sk_EVP_ASYM_CIPHER_num(asymciph_stack); i++) {
EVP_ASYM_CIPHER *k = sk_EVP_ASYM_CIPHER_value(asymciph_stack, i);
STACK_OF(OPENSSL_CSTRING) *names = NULL;
if (select_name != NULL && !EVP_ASYM_CIPHER_is_a(k, select_name))
continue;
names = sk_OPENSSL_CSTRING_new(name_cmp);
if (names != NULL
&& EVP_ASYM_CIPHER_names_do_all(k, collect_names, names)) {
count++;
BIO_printf(bio_out, " ");
print_names(bio_out, names);
BIO_printf(bio_out, " @ %s\n",
OSSL_PROVIDER_get0_name(EVP_ASYM_CIPHER_get0_provider(k)));
if (verbose) {
const char *desc = EVP_ASYM_CIPHER_get0_description(k);
if (desc != NULL)
BIO_printf(bio_out, " description: %s\n", desc);
print_param_types("settable operation parameters",
EVP_ASYM_CIPHER_settable_ctx_params(k), 4);
print_param_types("retrievable operation parameters",
EVP_ASYM_CIPHER_gettable_ctx_params(k), 4);
}
}
sk_OPENSSL_CSTRING_free(names);
}
sk_EVP_ASYM_CIPHER_pop_free(asymciph_stack, EVP_ASYM_CIPHER_free);
if (count == 0)
BIO_printf(bio_out, " -\n");
}
DEFINE_STACK_OF(EVP_KEYEXCH)
static int kex_cmp(const EVP_KEYEXCH * const *a,
const EVP_KEYEXCH * const *b)
{
return strcmp(OSSL_PROVIDER_get0_name(EVP_KEYEXCH_get0_provider(*a)),
OSSL_PROVIDER_get0_name(EVP_KEYEXCH_get0_provider(*b)));
}
static void collect_kex(EVP_KEYEXCH *kex, void *stack)
{
STACK_OF(EVP_KEYEXCH) *kex_stack = stack;
if (is_keyexch_fetchable(kex)
&& sk_EVP_KEYEXCH_push(kex_stack, kex) > 0)
EVP_KEYEXCH_up_ref(kex);
}
static void list_keyexchanges(void)
{
int i, count = 0;
STACK_OF(EVP_KEYEXCH) *kex_stack = sk_EVP_KEYEXCH_new(kex_cmp);
EVP_KEYEXCH_do_all_provided(app_get0_libctx(), collect_kex, kex_stack);
sk_EVP_KEYEXCH_sort(kex_stack);
for (i = 0; i < sk_EVP_KEYEXCH_num(kex_stack); i++) {
EVP_KEYEXCH *k = sk_EVP_KEYEXCH_value(kex_stack, i);
STACK_OF(OPENSSL_CSTRING) *names = NULL;
if (select_name != NULL && !EVP_KEYEXCH_is_a(k, select_name))
continue;
names = sk_OPENSSL_CSTRING_new(name_cmp);
if (names != NULL && EVP_KEYEXCH_names_do_all(k, collect_names, names)) {
count++;
BIO_printf(bio_out, " ");
print_names(bio_out, names);
BIO_printf(bio_out, " @ %s\n",
OSSL_PROVIDER_get0_name(EVP_KEYEXCH_get0_provider(k)));
if (verbose) {
const char *desc = EVP_KEYEXCH_get0_description(k);
if (desc != NULL)
BIO_printf(bio_out, " description: %s\n", desc);
print_param_types("settable operation parameters",
EVP_KEYEXCH_settable_ctx_params(k), 4);
print_param_types("retrievable operation parameters",
EVP_KEYEXCH_gettable_ctx_params(k), 4);
}
}
sk_OPENSSL_CSTRING_free(names);
}
sk_EVP_KEYEXCH_pop_free(kex_stack, EVP_KEYEXCH_free);
if (count == 0)
BIO_printf(bio_out, " -\n");
}
static void list_objects(void)
{
int max_nid = OBJ_new_nid(0);
int i;
char *oid_buf = NULL;
int oid_size = 0;
/* Skip 0, since that's NID_undef */
for (i = 1; i < max_nid; i++) {
const ASN1_OBJECT *obj = OBJ_nid2obj(i);
const char *sn = OBJ_nid2sn(i);
const char *ln = OBJ_nid2ln(i);
int n = 0;
/*
* If one of the retrieved objects somehow generated an error,
* we ignore it. The check for NID_undef below will detect the
* error and simply skip to the next NID.
*/
ERR_clear_error();
if (OBJ_obj2nid(obj) == NID_undef)
continue;
if ((n = OBJ_obj2txt(NULL, 0, obj, 1)) == 0) {
BIO_printf(bio_out, "# None-OID object: %s, %s\n", sn, ln);
continue;
}
if (n < 0)
break; /* Error */
if (n > oid_size) {
oid_buf = OPENSSL_realloc(oid_buf, n + 1);
if (oid_buf == NULL) {
BIO_printf(bio_err, "ERROR: Memory allocation\n");
break; /* Error */
}
oid_size = n + 1;
}
if (OBJ_obj2txt(oid_buf, oid_size, obj, 1) < 0)
break; /* Error */
if (ln == NULL || strcmp(sn, ln) == 0)
BIO_printf(bio_out, "%s = %s\n", sn, oid_buf);
else
BIO_printf(bio_out, "%s = %s, %s\n", sn, ln, oid_buf);
}
OPENSSL_free(oid_buf);
}
static void list_options_for_command(const char *command)
{
const FUNCTION *fp;
const OPTIONS *o;
for (fp = functions; fp->name != NULL; fp++)
if (strcmp(fp->name, command) == 0)
break;
if (fp->name == NULL) {
BIO_printf(bio_err, "Invalid command '%s'; type \"help\" for a list.\n",
command);
return;
}
if ((o = fp->help) == NULL)
return;
for ( ; o->name != NULL; o++) {
char c = o->valtype;
if (o->name == OPT_PARAM_STR)
break;
if (o->name == OPT_HELP_STR
|| o->name == OPT_MORE_STR
|| o->name == OPT_SECTION_STR
|| o->name[0] == '\0')
continue;
BIO_printf(bio_out, "%s %c\n", o->name, c == '\0' ? '-' : c);
}
/* Always output the -- marker since it is sometimes documented. */
BIO_printf(bio_out, "- -\n");
}
static int is_md_available(const char *name)
{
EVP_MD *md;
const char *propq = app_get0_propq();
/* Look through providers' digests */
ERR_set_mark();
md = EVP_MD_fetch(app_get0_libctx(), name, propq);
ERR_pop_to_mark();
if (md != NULL) {
EVP_MD_free(md);
return 1;
}
return propq != NULL || get_digest_from_engine(name) == NULL ? 0 : 1;
}
static int is_cipher_available(const char *name)
{
EVP_CIPHER *cipher;
const char *propq = app_get0_propq();
/* Look through providers' ciphers */
ERR_set_mark();
cipher = EVP_CIPHER_fetch(app_get0_libctx(), name, propq);
ERR_pop_to_mark();
if (cipher != NULL) {
EVP_CIPHER_free(cipher);
return 1;
}
return propq != NULL || get_cipher_from_engine(name) == NULL ? 0 : 1;
}
static void list_type(FUNC_TYPE ft, int one)
{
FUNCTION *fp;
int i = 0;
DISPLAY_COLUMNS dc;
memset(&dc, 0, sizeof(dc));
if (!one)
calculate_columns(functions, &dc);
for (fp = functions; fp->name != NULL; fp++) {
if (fp->type != ft)
continue;
switch (ft) {
case FT_cipher:
if (!is_cipher_available(fp->name))
continue;
break;
case FT_md:
if (!is_md_available(fp->name))
continue;
break;
default:
break;
}
if (one) {
BIO_printf(bio_out, "%s\n", fp->name);
} else {
if (i % dc.columns == 0 && i > 0)
BIO_printf(bio_out, "\n");
BIO_printf(bio_out, "%-*s", dc.width, fp->name);
i++;
}
}
if (!one)
BIO_printf(bio_out, "\n\n");
}
static void list_pkey(void)
{
#ifndef OPENSSL_NO_DEPRECATED_3_0
int i;
if (select_name == NULL && include_legacy()) {
BIO_printf(bio_out, "Legacy:\n");
for (i = 0; i < EVP_PKEY_asn1_get_count(); i++) {
const EVP_PKEY_ASN1_METHOD *ameth;
int pkey_id, pkey_base_id, pkey_flags;
const char *pinfo, *pem_str;
ameth = EVP_PKEY_asn1_get0(i);
EVP_PKEY_asn1_get0_info(&pkey_id, &pkey_base_id, &pkey_flags,
&pinfo, &pem_str, ameth);
if (pkey_flags & ASN1_PKEY_ALIAS) {
BIO_printf(bio_out, " Name: %s\n", OBJ_nid2ln(pkey_id));
BIO_printf(bio_out, "\tAlias for: %s\n",
OBJ_nid2ln(pkey_base_id));
} else {
BIO_printf(bio_out, " Name: %s\n", pinfo);
BIO_printf(bio_out, "\tType: %s Algorithm\n",
pkey_flags & ASN1_PKEY_DYNAMIC ?
"External" : "Builtin");
BIO_printf(bio_out, "\tOID: %s\n", OBJ_nid2ln(pkey_id));
if (pem_str == NULL)
pem_str = "(none)";
BIO_printf(bio_out, "\tPEM string: %s\n", pem_str);
}
}
}
#endif
BIO_printf(bio_out, "Provided:\n");
BIO_printf(bio_out, " Key Managers:\n");
list_keymanagers();
}
static void list_pkey_meth(void)
{
#ifndef OPENSSL_NO_DEPRECATED_3_0
size_t i;
size_t meth_count = EVP_PKEY_meth_get_count();
if (select_name == NULL && include_legacy()) {
BIO_printf(bio_out, "Legacy:\n");
for (i = 0; i < meth_count; i++) {
const EVP_PKEY_METHOD *pmeth = EVP_PKEY_meth_get0(i);
int pkey_id, pkey_flags;
EVP_PKEY_meth_get0_info(&pkey_id, &pkey_flags, pmeth);
BIO_printf(bio_out, " %s\n", OBJ_nid2ln(pkey_id));
BIO_printf(bio_out, "\tType: %s Algorithm\n",
pkey_flags & ASN1_PKEY_DYNAMIC ? "External" : "Builtin");
}
}
#endif
BIO_printf(bio_out, "Provided:\n");
BIO_printf(bio_out, " Encryption:\n");
list_asymciphers();
BIO_printf(bio_out, " Key Exchange:\n");
list_keyexchanges();
BIO_printf(bio_out, " Signatures:\n");
list_signatures();
BIO_printf(bio_out, " Key encapsulation:\n");
list_kems();
}
DEFINE_STACK_OF(OSSL_STORE_LOADER)
static int store_cmp(const OSSL_STORE_LOADER * const *a,
const OSSL_STORE_LOADER * const *b)
{
return strcmp(OSSL_PROVIDER_get0_name(OSSL_STORE_LOADER_get0_provider(*a)),
OSSL_PROVIDER_get0_name(OSSL_STORE_LOADER_get0_provider(*b)));
}
static void collect_store_loaders(OSSL_STORE_LOADER *store, void *stack)
{
STACK_OF(OSSL_STORE_LOADER) *store_stack = stack;
if (sk_OSSL_STORE_LOADER_push(store_stack, store) > 0)
OSSL_STORE_LOADER_up_ref(store);
}
static void list_store_loaders(void)
{
STACK_OF(OSSL_STORE_LOADER) *stores = sk_OSSL_STORE_LOADER_new(store_cmp);
int i;
if (stores == NULL) {
BIO_printf(bio_err, "ERROR: Memory allocation\n");
return;
}
BIO_printf(bio_out, "Provided STORE LOADERs:\n");
OSSL_STORE_LOADER_do_all_provided(app_get0_libctx(), collect_store_loaders,
stores);
sk_OSSL_STORE_LOADER_sort(stores);
for (i = 0; i < sk_OSSL_STORE_LOADER_num(stores); i++) {
const OSSL_STORE_LOADER *m = sk_OSSL_STORE_LOADER_value(stores, i);
STACK_OF(OPENSSL_CSTRING) *names = NULL;
if (select_name != NULL && !OSSL_STORE_LOADER_is_a(m, select_name))
continue;
names = sk_OPENSSL_CSTRING_new(name_cmp);
if (names != NULL && OSSL_STORE_LOADER_names_do_all(m, collect_names,
names)) {
BIO_printf(bio_out, " ");
print_names(bio_out, names);
BIO_printf(bio_out, " @ %s\n",
OSSL_PROVIDER_get0_name(OSSL_STORE_LOADER_get0_provider(m)));
}
sk_OPENSSL_CSTRING_free(names);
}
sk_OSSL_STORE_LOADER_pop_free(stores, OSSL_STORE_LOADER_free);
}
DEFINE_STACK_OF(OSSL_PROVIDER)
static int provider_cmp(const OSSL_PROVIDER * const *a,
const OSSL_PROVIDER * const *b)
{
return strcmp(OSSL_PROVIDER_get0_name(*a), OSSL_PROVIDER_get0_name(*b));
}
static int collect_providers(OSSL_PROVIDER *provider, void *stack)
{
STACK_OF(OSSL_PROVIDER) *provider_stack = stack;
/*
* If OK - result is the index of inserted data
* Error - result is -1 or 0
*/
return sk_OSSL_PROVIDER_push(provider_stack, provider) > 0 ? 1 : 0;
}
static void list_provider_info(void)
{
STACK_OF(OSSL_PROVIDER) *providers = sk_OSSL_PROVIDER_new(provider_cmp);
OSSL_PARAM params[5];
char *name, *version, *buildinfo;
int status;
int i;
if (providers == NULL) {
BIO_printf(bio_err, "ERROR: Memory allocation\n");
return;
}
if (OSSL_PROVIDER_do_all(NULL, &collect_providers, providers) != 1) {
+ sk_OSSL_PROVIDER_free(providers);
BIO_printf(bio_err, "ERROR: Memory allocation\n");
return;
}
BIO_printf(bio_out, "Providers:\n");
sk_OSSL_PROVIDER_sort(providers);
for (i = 0; i < sk_OSSL_PROVIDER_num(providers); i++) {
const OSSL_PROVIDER *prov = sk_OSSL_PROVIDER_value(providers, i);
const char *provname = OSSL_PROVIDER_get0_name(prov);
BIO_printf(bio_out, " %s\n", provname);
/* Query the "known" information parameters, the order matches below */
params[0] = OSSL_PARAM_construct_utf8_ptr(OSSL_PROV_PARAM_NAME,
&name, 0);
params[1] = OSSL_PARAM_construct_utf8_ptr(OSSL_PROV_PARAM_VERSION,
&version, 0);
params[2] = OSSL_PARAM_construct_int(OSSL_PROV_PARAM_STATUS, &status);
params[3] = OSSL_PARAM_construct_utf8_ptr(OSSL_PROV_PARAM_BUILDINFO,
&buildinfo, 0);
params[4] = OSSL_PARAM_construct_end();
OSSL_PARAM_set_all_unmodified(params);
if (!OSSL_PROVIDER_get_params(prov, params)) {
BIO_printf(bio_err,
"WARNING: Unable to query provider parameters for %s\n",
provname);
} else {
/* Print out the provider information, the params order matches above */
if (OSSL_PARAM_modified(params))
BIO_printf(bio_out, " name: %s\n", name);
if (OSSL_PARAM_modified(params + 1))
BIO_printf(bio_out, " version: %s\n", version);
if (OSSL_PARAM_modified(params + 2))
BIO_printf(bio_out, " status: %sactive\n", status ? "" : "in");
if (verbose) {
if (OSSL_PARAM_modified(params + 3))
BIO_printf(bio_out, " build info: %s\n", buildinfo);
print_param_types("gettable provider parameters",
OSSL_PROVIDER_gettable_params(prov), 4);
}
}
}
sk_OSSL_PROVIDER_free(providers);
}
#ifndef OPENSSL_NO_DEPRECATED_3_0
static void list_engines(void)
{
# ifndef OPENSSL_NO_ENGINE
ENGINE *e;
BIO_puts(bio_out, "Engines:\n");
e = ENGINE_get_first();
while (e) {
BIO_printf(bio_out, "%s\n", ENGINE_get_id(e));
e = ENGINE_get_next(e);
}
# else
BIO_puts(bio_out, "Engine support is disabled.\n");
# endif
}
#endif
static void list_disabled(void)
{
BIO_puts(bio_out, "Disabled algorithms:\n");
#ifdef OPENSSL_NO_ARIA
BIO_puts(bio_out, "ARIA\n");
#endif
#ifdef OPENSSL_NO_BF
BIO_puts(bio_out, "BF\n");
#endif
#ifdef OPENSSL_NO_BLAKE2
BIO_puts(bio_out, "BLAKE2\n");
#endif
#ifdef OPENSSL_NO_CAMELLIA
BIO_puts(bio_out, "CAMELLIA\n");
#endif
#ifdef OPENSSL_NO_CAST
BIO_puts(bio_out, "CAST\n");
#endif
#ifdef OPENSSL_NO_CMAC
BIO_puts(bio_out, "CMAC\n");
#endif
#ifdef OPENSSL_NO_CMS
BIO_puts(bio_out, "CMS\n");
#endif
#ifdef OPENSSL_NO_COMP
BIO_puts(bio_out, "COMP\n");
#endif
#ifdef OPENSSL_NO_DES
BIO_puts(bio_out, "DES\n");
#endif
#ifdef OPENSSL_NO_DGRAM
BIO_puts(bio_out, "DGRAM\n");
#endif
#ifdef OPENSSL_NO_DH
BIO_puts(bio_out, "DH\n");
#endif
#ifdef OPENSSL_NO_DSA
BIO_puts(bio_out, "DSA\n");
#endif
#if defined(OPENSSL_NO_DTLS)
BIO_puts(bio_out, "DTLS\n");
#endif
#if defined(OPENSSL_NO_DTLS1)
BIO_puts(bio_out, "DTLS1\n");
#endif
#if defined(OPENSSL_NO_DTLS1_2)
BIO_puts(bio_out, "DTLS1_2\n");
#endif
#ifdef OPENSSL_NO_EC
BIO_puts(bio_out, "EC\n");
#endif
#ifdef OPENSSL_NO_EC2M
BIO_puts(bio_out, "EC2M\n");
#endif
#if defined(OPENSSL_NO_ENGINE) && !defined(OPENSSL_NO_DEPRECATED_3_0)
BIO_puts(bio_out, "ENGINE\n");
#endif
#ifdef OPENSSL_NO_GOST
BIO_puts(bio_out, "GOST\n");
#endif
#ifdef OPENSSL_NO_IDEA
BIO_puts(bio_out, "IDEA\n");
#endif
#ifdef OPENSSL_NO_MD2
BIO_puts(bio_out, "MD2\n");
#endif
#ifdef OPENSSL_NO_MD4
BIO_puts(bio_out, "MD4\n");
#endif
#ifdef OPENSSL_NO_MD5
BIO_puts(bio_out, "MD5\n");
#endif
#ifdef OPENSSL_NO_MDC2
BIO_puts(bio_out, "MDC2\n");
#endif
#ifdef OPENSSL_NO_OCB
BIO_puts(bio_out, "OCB\n");
#endif
#ifdef OPENSSL_NO_OCSP
BIO_puts(bio_out, "OCSP\n");
#endif
#ifdef OPENSSL_NO_PSK
BIO_puts(bio_out, "PSK\n");
#endif
#ifdef OPENSSL_NO_RC2
BIO_puts(bio_out, "RC2\n");
#endif
#ifdef OPENSSL_NO_RC4
BIO_puts(bio_out, "RC4\n");
#endif
#ifdef OPENSSL_NO_RC5
BIO_puts(bio_out, "RC5\n");
#endif
#ifdef OPENSSL_NO_RMD160
BIO_puts(bio_out, "RMD160\n");
#endif
#ifdef OPENSSL_NO_SCRYPT
BIO_puts(bio_out, "SCRYPT\n");
#endif
#ifdef OPENSSL_NO_SCTP
BIO_puts(bio_out, "SCTP\n");
#endif
#ifdef OPENSSL_NO_SEED
BIO_puts(bio_out, "SEED\n");
#endif
#ifdef OPENSSL_NO_SM2
BIO_puts(bio_out, "SM2\n");
#endif
#ifdef OPENSSL_NO_SM3
BIO_puts(bio_out, "SM3\n");
#endif
#ifdef OPENSSL_NO_SM4
BIO_puts(bio_out, "SM4\n");
#endif
#ifdef OPENSSL_NO_SOCK
BIO_puts(bio_out, "SOCK\n");
#endif
#ifdef OPENSSL_NO_SRP
BIO_puts(bio_out, "SRP\n");
#endif
#ifdef OPENSSL_NO_SRTP
BIO_puts(bio_out, "SRTP\n");
#endif
#ifdef OPENSSL_NO_SSL3
BIO_puts(bio_out, "SSL3\n");
#endif
#ifdef OPENSSL_NO_TLS1
BIO_puts(bio_out, "TLS1\n");
#endif
#ifdef OPENSSL_NO_TLS1_1
BIO_puts(bio_out, "TLS1_1\n");
#endif
#ifdef OPENSSL_NO_TLS1_2
BIO_puts(bio_out, "TLS1_2\n");
#endif
#ifdef OPENSSL_NO_WHIRLPOOL
BIO_puts(bio_out, "WHIRLPOOL\n");
#endif
#ifndef ZLIB
BIO_puts(bio_out, "ZLIB\n");
#endif
}
/* Unified enum for help and list commands. */
typedef enum HELPLIST_CHOICE {
OPT_COMMON,
OPT_ONE, OPT_VERBOSE,
OPT_COMMANDS, OPT_DIGEST_COMMANDS, OPT_MAC_ALGORITHMS, OPT_OPTIONS,
OPT_DIGEST_ALGORITHMS, OPT_CIPHER_COMMANDS, OPT_CIPHER_ALGORITHMS,
OPT_PK_ALGORITHMS, OPT_PK_METHOD, OPT_DISABLED,
OPT_KDF_ALGORITHMS, OPT_RANDOM_INSTANCES, OPT_RANDOM_GENERATORS,
OPT_ENCODERS, OPT_DECODERS, OPT_KEYMANAGERS, OPT_KEYEXCHANGE_ALGORITHMS,
OPT_KEM_ALGORITHMS, OPT_SIGNATURE_ALGORITHMS, OPT_ASYM_CIPHER_ALGORITHMS,
OPT_STORE_LOADERS, OPT_PROVIDER_INFO,
OPT_OBJECTS, OPT_SELECT_NAME,
#ifndef OPENSSL_NO_DEPRECATED_3_0
OPT_ENGINES,
#endif
OPT_PROV_ENUM
} HELPLIST_CHOICE;
const OPTIONS list_options[] = {
OPT_SECTION("General"),
{"help", OPT_HELP, '-', "Display this summary"},
OPT_SECTION("Output"),
{"1", OPT_ONE, '-', "List in one column"},
{"verbose", OPT_VERBOSE, '-', "Verbose listing"},
{"select", OPT_SELECT_NAME, 's', "Select a single algorithm"},
{"commands", OPT_COMMANDS, '-', "List of standard commands"},
{"standard-commands", OPT_COMMANDS, '-', "List of standard commands"},
#ifndef OPENSSL_NO_DEPRECATED_3_0
{"digest-commands", OPT_DIGEST_COMMANDS, '-',
"List of message digest commands (deprecated)"},
#endif
{"digest-algorithms", OPT_DIGEST_ALGORITHMS, '-',
"List of message digest algorithms"},
{"kdf-algorithms", OPT_KDF_ALGORITHMS, '-',
"List of key derivation and pseudo random function algorithms"},
{"random-instances", OPT_RANDOM_INSTANCES, '-',
"List the primary, public and private random number generator details"},
{"random-generators", OPT_RANDOM_GENERATORS, '-',
"List of random number generators"},
{"mac-algorithms", OPT_MAC_ALGORITHMS, '-',
"List of message authentication code algorithms"},
#ifndef OPENSSL_NO_DEPRECATED_3_0
{"cipher-commands", OPT_CIPHER_COMMANDS, '-',
"List of cipher commands (deprecated)"},
#endif
{"cipher-algorithms", OPT_CIPHER_ALGORITHMS, '-',
"List of symmetric cipher algorithms"},
{"encoders", OPT_ENCODERS, '-', "List of encoding methods" },
{"decoders", OPT_DECODERS, '-', "List of decoding methods" },
{"key-managers", OPT_KEYMANAGERS, '-', "List of key managers" },
{"key-exchange-algorithms", OPT_KEYEXCHANGE_ALGORITHMS, '-',
"List of key exchange algorithms" },
{"kem-algorithms", OPT_KEM_ALGORITHMS, '-',
"List of key encapsulation mechanism algorithms" },
{"signature-algorithms", OPT_SIGNATURE_ALGORITHMS, '-',
"List of signature algorithms" },
{"asymcipher-algorithms", OPT_ASYM_CIPHER_ALGORITHMS, '-',
"List of asymmetric cipher algorithms" },
{"public-key-algorithms", OPT_PK_ALGORITHMS, '-',
"List of public key algorithms"},
{"public-key-methods", OPT_PK_METHOD, '-',
"List of public key methods"},
{"store-loaders", OPT_STORE_LOADERS, '-',
"List of store loaders"},
{"providers", OPT_PROVIDER_INFO, '-',
"List of provider information"},
#ifndef OPENSSL_NO_DEPRECATED_3_0
{"engines", OPT_ENGINES, '-',
"List of loaded engines"},
#endif
{"disabled", OPT_DISABLED, '-', "List of disabled features"},
{"options", OPT_OPTIONS, 's',
"List options for specified command"},
{"objects", OPT_OBJECTS, '-',
"List built in objects (OID<->name mappings)"},
OPT_PROV_OPTIONS,
{NULL}
};
int list_main(int argc, char **argv)
{
char *prog;
HELPLIST_CHOICE o;
int one = 0, done = 0;
struct {
unsigned int commands:1;
unsigned int random_instances:1;
unsigned int random_generators:1;
unsigned int digest_commands:1;
unsigned int digest_algorithms:1;
unsigned int kdf_algorithms:1;
unsigned int mac_algorithms:1;
unsigned int cipher_commands:1;
unsigned int cipher_algorithms:1;
unsigned int encoder_algorithms:1;
unsigned int decoder_algorithms:1;
unsigned int keymanager_algorithms:1;
unsigned int signature_algorithms:1;
unsigned int keyexchange_algorithms:1;
unsigned int kem_algorithms:1;
unsigned int asym_cipher_algorithms:1;
unsigned int pk_algorithms:1;
unsigned int pk_method:1;
unsigned int store_loaders:1;
unsigned int provider_info:1;
#ifndef OPENSSL_NO_DEPRECATED_3_0
unsigned int engines:1;
#endif
unsigned int disabled:1;
unsigned int objects:1;
unsigned int options:1;
} todo = { 0, };
verbose = 0; /* Clear a possible previous call */
prog = opt_init(argc, argv, list_options);
while ((o = opt_next()) != OPT_EOF) {
switch (o) {
case OPT_EOF: /* Never hit, but suppresses warning */
case OPT_ERR:
opthelp:
BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
return 1;
case OPT_HELP:
opt_help(list_options);
return 0;
case OPT_ONE:
one = 1;
break;
case OPT_COMMANDS:
todo.commands = 1;
break;
case OPT_DIGEST_COMMANDS:
todo.digest_commands = 1;
break;
case OPT_DIGEST_ALGORITHMS:
todo.digest_algorithms = 1;
break;
case OPT_KDF_ALGORITHMS:
todo.kdf_algorithms = 1;
break;
case OPT_RANDOM_INSTANCES:
todo.random_instances = 1;
break;
case OPT_RANDOM_GENERATORS:
todo.random_generators = 1;
break;
case OPT_MAC_ALGORITHMS:
todo.mac_algorithms = 1;
break;
case OPT_CIPHER_COMMANDS:
todo.cipher_commands = 1;
break;
case OPT_CIPHER_ALGORITHMS:
todo.cipher_algorithms = 1;
break;
case OPT_ENCODERS:
todo.encoder_algorithms = 1;
break;
case OPT_DECODERS:
todo.decoder_algorithms = 1;
break;
case OPT_KEYMANAGERS:
todo.keymanager_algorithms = 1;
break;
case OPT_SIGNATURE_ALGORITHMS:
todo.signature_algorithms = 1;
break;
case OPT_KEYEXCHANGE_ALGORITHMS:
todo.keyexchange_algorithms = 1;
break;
case OPT_KEM_ALGORITHMS:
todo.kem_algorithms = 1;
break;
case OPT_ASYM_CIPHER_ALGORITHMS:
todo.asym_cipher_algorithms = 1;
break;
case OPT_PK_ALGORITHMS:
todo.pk_algorithms = 1;
break;
case OPT_PK_METHOD:
todo.pk_method = 1;
break;
case OPT_STORE_LOADERS:
todo.store_loaders = 1;
break;
case OPT_PROVIDER_INFO:
todo.provider_info = 1;
break;
#ifndef OPENSSL_NO_DEPRECATED_3_0
case OPT_ENGINES:
todo.engines = 1;
break;
#endif
case OPT_DISABLED:
todo.disabled = 1;
break;
case OPT_OBJECTS:
todo.objects = 1;
break;
case OPT_OPTIONS:
list_options_for_command(opt_arg());
break;
case OPT_VERBOSE:
verbose = 1;
break;
case OPT_SELECT_NAME:
select_name = opt_arg();
break;
case OPT_PROV_CASES:
if (!opt_provider(o))
return 1;
break;
}
done = 1;
}
/* No extra arguments. */
if (opt_num_rest() != 0)
goto opthelp;
if (todo.commands)
list_type(FT_general, one);
if (todo.random_instances)
list_random_instances();
if (todo.random_generators)
list_random_generators();
if (todo.digest_commands)
list_type(FT_md, one);
if (todo.digest_algorithms)
list_digests();
if (todo.kdf_algorithms)
list_kdfs();
if (todo.mac_algorithms)
list_macs();
if (todo.cipher_commands)
list_type(FT_cipher, one);
if (todo.cipher_algorithms)
list_ciphers();
if (todo.encoder_algorithms)
list_encoders();
if (todo.decoder_algorithms)
list_decoders();
if (todo.keymanager_algorithms)
list_keymanagers();
if (todo.signature_algorithms)
list_signatures();
if (todo.asym_cipher_algorithms)
list_asymciphers();
if (todo.keyexchange_algorithms)
list_keyexchanges();
if (todo.kem_algorithms)
list_kems();
if (todo.pk_algorithms)
list_pkey();
if (todo.pk_method)
list_pkey_meth();
if (todo.store_loaders)
list_store_loaders();
if (todo.provider_info)
list_provider_info();
#ifndef OPENSSL_NO_DEPRECATED_3_0
if (todo.engines)
list_engines();
#endif
if (todo.disabled)
list_disabled();
if (todo.objects)
list_objects();
if (!done)
goto opthelp;
return 0;
}
diff --git a/crypto/openssl/apps/ocsp.c b/crypto/openssl/apps/ocsp.c
index 821e224c6ce4..fb3105da5526 100644
--- a/crypto/openssl/apps/ocsp.c
+++ b/crypto/openssl/apps/ocsp.c
@@ -1,1262 +1,1262 @@
/*
- * Copyright 2001-2022 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2001-2024 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 <openssl/opensslconf.h>
#ifdef OPENSSL_SYS_VMS
/* So fd_set and friends get properly defined on OpenVMS */
-# define _XOPEN_SOURCE_EXTENDED
+# define _XOPEN_SOURCE_EXTENDED 1
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <ctype.h>
/* Needs to be included before the openssl headers */
#include "apps.h"
#include "http_server.h"
#include "progs.h"
#include "internal/sockets.h"
#include <openssl/e_os2.h>
#include <openssl/crypto.h>
#include <openssl/err.h>
#include <openssl/ssl.h>
#include <openssl/evp.h>
#include <openssl/bn.h>
#include <openssl/x509v3.h>
#if defined(__TANDEM)
# if defined(OPENSSL_TANDEM_FLOSS)
# include <floss.h(floss_fork)>
# endif
#endif
#if defined(OPENSSL_SYS_VXWORKS)
/* not supported */
int setpgid(pid_t pid, pid_t pgid)
{
errno = ENOSYS;
return 0;
}
/* not supported */
pid_t fork(void)
{
errno = ENOSYS;
return (pid_t) -1;
}
#endif
/* Maximum leeway in validity period: default 5 minutes */
#define MAX_VALIDITY_PERIOD (5 * 60)
static int add_ocsp_cert(OCSP_REQUEST **req, X509 *cert,
const EVP_MD *cert_id_md, X509 *issuer,
STACK_OF(OCSP_CERTID) *ids);
static int add_ocsp_serial(OCSP_REQUEST **req, char *serial,
const EVP_MD *cert_id_md, X509 *issuer,
STACK_OF(OCSP_CERTID) *ids);
static int print_ocsp_summary(BIO *out, OCSP_BASICRESP *bs, OCSP_REQUEST *req,
STACK_OF(OPENSSL_STRING) *names,
STACK_OF(OCSP_CERTID) *ids, long nsec,
long maxage);
static void make_ocsp_response(BIO *err, OCSP_RESPONSE **resp, OCSP_REQUEST *req,
CA_DB *db, STACK_OF(X509) *ca, X509 *rcert,
EVP_PKEY *rkey, const EVP_MD *md,
STACK_OF(OPENSSL_STRING) *sigopts,
STACK_OF(X509) *rother, unsigned long flags,
int nmin, int ndays, int badsig,
const EVP_MD *resp_md);
static char **lookup_serial(CA_DB *db, ASN1_INTEGER *ser);
static int do_responder(OCSP_REQUEST **preq, BIO **pcbio, BIO *acbio,
const char *port, int timeout);
static int send_ocsp_response(BIO *cbio, const OCSP_RESPONSE *resp);
static char *prog;
#ifdef HTTP_DAEMON
static int index_changed(CA_DB *);
#endif
typedef enum OPTION_choice {
OPT_COMMON,
OPT_OUTFILE, OPT_TIMEOUT, OPT_URL, OPT_HOST, OPT_PORT,
#ifndef OPENSSL_NO_SOCK
OPT_PROXY, OPT_NO_PROXY,
#endif
OPT_IGNORE_ERR, OPT_NOVERIFY, OPT_NONCE, OPT_NO_NONCE,
OPT_RESP_NO_CERTS, OPT_RESP_KEY_ID, OPT_NO_CERTS,
OPT_NO_SIGNATURE_VERIFY, OPT_NO_CERT_VERIFY, OPT_NO_CHAIN,
OPT_NO_CERT_CHECKS, OPT_NO_EXPLICIT, OPT_TRUST_OTHER,
OPT_NO_INTERN, OPT_BADSIG, OPT_TEXT, OPT_REQ_TEXT, OPT_RESP_TEXT,
OPT_REQIN, OPT_RESPIN, OPT_SIGNER, OPT_VAFILE, OPT_SIGN_OTHER,
OPT_VERIFY_OTHER, OPT_CAFILE, OPT_CAPATH, OPT_CASTORE, OPT_NOCAFILE,
OPT_NOCAPATH, OPT_NOCASTORE,
OPT_VALIDITY_PERIOD, OPT_STATUS_AGE, OPT_SIGNKEY, OPT_REQOUT,
OPT_RESPOUT, OPT_PATH, OPT_ISSUER, OPT_CERT, OPT_SERIAL,
OPT_INDEX, OPT_CA, OPT_NMIN, OPT_REQUEST, OPT_NDAYS, OPT_RSIGNER,
OPT_RKEY, OPT_ROTHER, OPT_RMD, OPT_RSIGOPT, OPT_HEADER,
OPT_PASSIN,
OPT_RCID,
OPT_V_ENUM,
OPT_MD,
OPT_MULTI, OPT_PROV_ENUM
} OPTION_CHOICE;
const OPTIONS ocsp_options[] = {
OPT_SECTION("General"),
{"help", OPT_HELP, '-', "Display this summary"},
{"ignore_err", OPT_IGNORE_ERR, '-',
"Ignore error on OCSP request or response and continue running"},
{"CAfile", OPT_CAFILE, '<', "Trusted certificates file"},
{"CApath", OPT_CAPATH, '<', "Trusted certificates directory"},
{"CAstore", OPT_CASTORE, ':', "Trusted certificates store URI"},
{"no-CAfile", OPT_NOCAFILE, '-',
"Do not load the default certificates file"},
{"no-CApath", OPT_NOCAPATH, '-',
"Do not load certificates from the default certificates directory"},
{"no-CAstore", OPT_NOCASTORE, '-',
"Do not load certificates from the default certificates store"},
OPT_SECTION("Responder"),
{"timeout", OPT_TIMEOUT, 'p',
"Connection timeout (in seconds) to the OCSP responder"},
{"resp_no_certs", OPT_RESP_NO_CERTS, '-',
"Don't include any certificates in response"},
#ifdef HTTP_DAEMON
{"multi", OPT_MULTI, 'p', "run multiple responder processes"},
#endif
{"no_certs", OPT_NO_CERTS, '-',
"Don't include any certificates in signed request"},
{"badsig", OPT_BADSIG, '-',
"Corrupt last byte of loaded OCSP response signature (for test)"},
{"CA", OPT_CA, '<', "CA certificate"},
{"nmin", OPT_NMIN, 'p', "Number of minutes before next update"},
{"nrequest", OPT_REQUEST, 'p',
"Number of requests to accept (default unlimited)"},
{"reqin", OPT_REQIN, 's', "File with the DER-encoded request"},
{"signer", OPT_SIGNER, '<', "Certificate to sign OCSP request with"},
{"sign_other", OPT_SIGN_OTHER, '<',
"Additional certificates to include in signed request"},
{"index", OPT_INDEX, '<', "Certificate status index file"},
{"ndays", OPT_NDAYS, 'p', "Number of days before next update"},
{"rsigner", OPT_RSIGNER, '<',
"Responder certificate to sign responses with"},
{"rkey", OPT_RKEY, '<', "Responder key to sign responses with"},
{"passin", OPT_PASSIN, 's', "Responder key pass phrase source"},
{"rother", OPT_ROTHER, '<', "Other certificates to include in response"},
{"rmd", OPT_RMD, 's', "Digest Algorithm to use in signature of OCSP response"},
{"rsigopt", OPT_RSIGOPT, 's', "OCSP response signature parameter in n:v form"},
{"header", OPT_HEADER, 's', "key=value header to add"},
{"rcid", OPT_RCID, 's', "Use specified algorithm for cert id in response"},
{"", OPT_MD, '-', "Any supported digest algorithm (sha1,sha256, ... )"},
OPT_SECTION("Client"),
{"url", OPT_URL, 's', "Responder URL"},
{"host", OPT_HOST, 's', "TCP/IP hostname:port to connect to"},
{"port", OPT_PORT, 'N', "Port to run responder on"},
{"path", OPT_PATH, 's', "Path to use in OCSP request"},
#ifndef OPENSSL_NO_SOCK
{"proxy", OPT_PROXY, 's',
"[http[s]://]host[:port][/path] of HTTP(S) proxy to use; path is ignored"},
{"no_proxy", OPT_NO_PROXY, 's',
"List of addresses of servers not to use HTTP(S) proxy for"},
{OPT_MORE_STR, 0, 0,
"Default from environment variable 'no_proxy', else 'NO_PROXY', else none"},
#endif
{"out", OPT_OUTFILE, '>', "Output filename"},
{"noverify", OPT_NOVERIFY, '-', "Don't verify response at all"},
{"nonce", OPT_NONCE, '-', "Add OCSP nonce to request"},
{"no_nonce", OPT_NO_NONCE, '-', "Don't add OCSP nonce to request"},
{"no_signature_verify", OPT_NO_SIGNATURE_VERIFY, '-',
"Don't check signature on response"},
{"resp_key_id", OPT_RESP_KEY_ID, '-',
"Identify response by signing certificate key ID"},
{"no_cert_verify", OPT_NO_CERT_VERIFY, '-',
"Don't check signing certificate"},
{"text", OPT_TEXT, '-', "Print text form of request and response"},
{"req_text", OPT_REQ_TEXT, '-', "Print text form of request"},
{"resp_text", OPT_RESP_TEXT, '-', "Print text form of response"},
{"no_chain", OPT_NO_CHAIN, '-', "Don't chain verify response"},
{"no_cert_checks", OPT_NO_CERT_CHECKS, '-',
"Don't do additional checks on signing certificate"},
{"no_explicit", OPT_NO_EXPLICIT, '-',
"Do not explicitly check the chain, just verify the root"},
{"trust_other", OPT_TRUST_OTHER, '-',
"Don't verify additional certificates"},
{"no_intern", OPT_NO_INTERN, '-',
"Don't search certificates contained in response for signer"},
{"respin", OPT_RESPIN, 's', "File with the DER-encoded response"},
{"VAfile", OPT_VAFILE, '<', "Validator certificates file"},
{"verify_other", OPT_VERIFY_OTHER, '<',
"Additional certificates to search for signer"},
{"cert", OPT_CERT, '<', "Certificate to check"},
{"serial", OPT_SERIAL, 's', "Serial number to check"},
{"validity_period", OPT_VALIDITY_PERIOD, 'u',
"Maximum validity discrepancy in seconds"},
{"signkey", OPT_SIGNKEY, 's', "Private key to sign OCSP request with"},
{"reqout", OPT_REQOUT, 's', "Output file for the DER-encoded request"},
{"respout", OPT_RESPOUT, 's', "Output file for the DER-encoded response"},
{"issuer", OPT_ISSUER, '<', "Issuer certificate"},
{"status_age", OPT_STATUS_AGE, 'p', "Maximum status age in seconds"},
OPT_V_OPTIONS,
OPT_PROV_OPTIONS,
{NULL}
};
int ocsp_main(int argc, char **argv)
{
BIO *acbio = NULL, *cbio = NULL, *derbio = NULL, *out = NULL;
EVP_MD *cert_id_md = NULL, *rsign_md = NULL;
STACK_OF(OPENSSL_STRING) *rsign_sigopts = NULL;
int trailing_md = 0;
CA_DB *rdb = NULL;
EVP_PKEY *key = NULL, *rkey = NULL;
OCSP_BASICRESP *bs = NULL;
OCSP_REQUEST *req = NULL;
OCSP_RESPONSE *resp = NULL;
STACK_OF(CONF_VALUE) *headers = NULL;
STACK_OF(OCSP_CERTID) *ids = NULL;
STACK_OF(OPENSSL_STRING) *reqnames = NULL;
STACK_OF(X509) *sign_other = NULL, *verify_other = NULL, *rother = NULL;
STACK_OF(X509) *issuers = NULL;
X509 *issuer = NULL, *cert = NULL;
STACK_OF(X509) *rca_cert = NULL;
EVP_MD *resp_certid_md = NULL;
X509 *signer = NULL, *rsigner = NULL;
X509_STORE *store = NULL;
X509_VERIFY_PARAM *vpm = NULL;
const char *CAfile = NULL, *CApath = NULL, *CAstore = NULL;
char *header, *value, *respdigname = NULL;
char *host = NULL, *port = NULL, *path = "/", *outfile = NULL;
#ifndef OPENSSL_NO_SOCK
char *opt_proxy = NULL;
char *opt_no_proxy = NULL;
#endif
char *rca_filename = NULL, *reqin = NULL, *respin = NULL;
char *reqout = NULL, *respout = NULL, *ridx_filename = NULL;
char *rsignfile = NULL, *rkeyfile = NULL;
char *passinarg = NULL, *passin = NULL;
char *sign_certfile = NULL, *verify_certfile = NULL, *rcertfile = NULL;
char *signfile = NULL, *keyfile = NULL;
char *thost = NULL, *tport = NULL, *tpath = NULL;
int noCAfile = 0, noCApath = 0, noCAstore = 0;
int accept_count = -1, add_nonce = 1, noverify = 0, use_ssl = -1;
int vpmtouched = 0, badsig = 0, i, ignore_err = 0, nmin = 0, ndays = -1;
int req_text = 0, resp_text = 0, res, ret = 1;
int req_timeout = -1;
long nsec = MAX_VALIDITY_PERIOD, maxage = -1;
unsigned long sign_flags = 0, verify_flags = 0, rflags = 0;
OPTION_CHOICE o;
if ((reqnames = sk_OPENSSL_STRING_new_null()) == NULL
|| (ids = sk_OCSP_CERTID_new_null()) == NULL
|| (vpm = X509_VERIFY_PARAM_new()) == NULL)
goto end;
prog = opt_init(argc, argv, ocsp_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:
ret = 0;
opt_help(ocsp_options);
goto end;
case OPT_OUTFILE:
outfile = opt_arg();
break;
case OPT_TIMEOUT:
#ifndef OPENSSL_NO_SOCK
req_timeout = atoi(opt_arg());
#endif
break;
case OPT_URL:
OPENSSL_free(thost);
OPENSSL_free(tport);
OPENSSL_free(tpath);
thost = tport = tpath = NULL;
if (!OSSL_HTTP_parse_url(opt_arg(), &use_ssl, NULL /* userinfo */,
&host, &port, NULL /* port_num */,
&path, NULL /* qry */, NULL /* frag */)) {
BIO_printf(bio_err, "%s Error parsing -url argument\n", prog);
goto end;
}
thost = host;
tport = port;
tpath = path;
break;
case OPT_HOST:
host = opt_arg();
break;
case OPT_PORT:
port = opt_arg();
break;
case OPT_PATH:
path = opt_arg();
break;
#ifndef OPENSSL_NO_SOCK
case OPT_PROXY:
opt_proxy = opt_arg();
break;
case OPT_NO_PROXY:
opt_no_proxy = opt_arg();
break;
#endif
case OPT_IGNORE_ERR:
ignore_err = 1;
break;
case OPT_NOVERIFY:
noverify = 1;
break;
case OPT_NONCE:
add_nonce = 2;
break;
case OPT_NO_NONCE:
add_nonce = 0;
break;
case OPT_RESP_NO_CERTS:
rflags |= OCSP_NOCERTS;
break;
case OPT_RESP_KEY_ID:
rflags |= OCSP_RESPID_KEY;
break;
case OPT_NO_CERTS:
sign_flags |= OCSP_NOCERTS;
break;
case OPT_NO_SIGNATURE_VERIFY:
verify_flags |= OCSP_NOSIGS;
break;
case OPT_NO_CERT_VERIFY:
verify_flags |= OCSP_NOVERIFY;
break;
case OPT_NO_CHAIN:
verify_flags |= OCSP_NOCHAIN;
break;
case OPT_NO_CERT_CHECKS:
verify_flags |= OCSP_NOCHECKS;
break;
case OPT_NO_EXPLICIT:
verify_flags |= OCSP_NOEXPLICIT;
break;
case OPT_TRUST_OTHER:
verify_flags |= OCSP_TRUSTOTHER;
break;
case OPT_NO_INTERN:
verify_flags |= OCSP_NOINTERN;
break;
case OPT_BADSIG:
badsig = 1;
break;
case OPT_TEXT:
req_text = resp_text = 1;
break;
case OPT_REQ_TEXT:
req_text = 1;
break;
case OPT_RESP_TEXT:
resp_text = 1;
break;
case OPT_REQIN:
reqin = opt_arg();
break;
case OPT_RESPIN:
respin = opt_arg();
break;
case OPT_SIGNER:
signfile = opt_arg();
break;
case OPT_VAFILE:
verify_certfile = opt_arg();
verify_flags |= OCSP_TRUSTOTHER;
break;
case OPT_SIGN_OTHER:
sign_certfile = opt_arg();
break;
case OPT_VERIFY_OTHER:
verify_certfile = opt_arg();
break;
case OPT_CAFILE:
CAfile = opt_arg();
break;
case OPT_CAPATH:
CApath = opt_arg();
break;
case OPT_CASTORE:
CAstore = opt_arg();
break;
case OPT_NOCAFILE:
noCAfile = 1;
break;
case OPT_NOCAPATH:
noCApath = 1;
break;
case OPT_NOCASTORE:
noCAstore = 1;
break;
case OPT_V_CASES:
if (!opt_verify(o, vpm))
goto end;
vpmtouched++;
break;
case OPT_VALIDITY_PERIOD:
opt_long(opt_arg(), &nsec);
break;
case OPT_STATUS_AGE:
opt_long(opt_arg(), &maxage);
break;
case OPT_SIGNKEY:
keyfile = opt_arg();
break;
case OPT_REQOUT:
reqout = opt_arg();
break;
case OPT_RESPOUT:
respout = opt_arg();
break;
case OPT_ISSUER:
issuer = load_cert(opt_arg(), FORMAT_UNDEF, "issuer certificate");
if (issuer == NULL)
goto end;
if (issuers == NULL) {
if ((issuers = sk_X509_new_null()) == NULL)
goto end;
}
if (!sk_X509_push(issuers, issuer))
goto end;
break;
case OPT_CERT:
X509_free(cert);
cert = load_cert(opt_arg(), FORMAT_UNDEF, "certificate");
if (cert == NULL)
goto end;
if (cert_id_md == NULL)
cert_id_md = (EVP_MD *)EVP_sha1();
if (!add_ocsp_cert(&req, cert, cert_id_md, issuer, ids))
goto end;
if (!sk_OPENSSL_STRING_push(reqnames, opt_arg()))
goto end;
trailing_md = 0;
break;
case OPT_SERIAL:
if (cert_id_md == NULL)
cert_id_md = (EVP_MD *)EVP_sha1();
if (!add_ocsp_serial(&req, opt_arg(), cert_id_md, issuer, ids))
goto end;
if (!sk_OPENSSL_STRING_push(reqnames, opt_arg()))
goto end;
trailing_md = 0;
break;
case OPT_INDEX:
ridx_filename = opt_arg();
break;
case OPT_CA:
rca_filename = opt_arg();
break;
case OPT_NMIN:
nmin = opt_int_arg();
if (ndays == -1)
ndays = 0;
break;
case OPT_REQUEST:
accept_count = opt_int_arg();
break;
case OPT_NDAYS:
ndays = atoi(opt_arg());
break;
case OPT_RSIGNER:
rsignfile = opt_arg();
break;
case OPT_RKEY:
rkeyfile = opt_arg();
break;
case OPT_PASSIN:
passinarg = opt_arg();
break;
case OPT_ROTHER:
rcertfile = opt_arg();
break;
case OPT_RMD: /* Response MessageDigest */
respdigname = opt_arg();
break;
case OPT_RSIGOPT:
if (rsign_sigopts == NULL)
rsign_sigopts = sk_OPENSSL_STRING_new_null();
if (rsign_sigopts == NULL
|| !sk_OPENSSL_STRING_push(rsign_sigopts, opt_arg()))
goto end;
break;
case OPT_HEADER:
header = opt_arg();
value = strchr(header, '=');
if (value == NULL) {
BIO_printf(bio_err, "Missing = in header key=value\n");
goto opthelp;
}
*value++ = '\0';
if (!X509V3_add_value(header, value, &headers))
goto end;
break;
case OPT_RCID:
if (!opt_md(opt_arg(), &resp_certid_md))
goto opthelp;
break;
case OPT_MD:
if (trailing_md) {
BIO_printf(bio_err,
"%s: Digest must be before -cert or -serial\n",
prog);
goto opthelp;
}
if (!opt_md(opt_unknown(), &cert_id_md))
goto opthelp;
trailing_md = 1;
break;
case OPT_MULTI:
#ifdef HTTP_DAEMON
multi = atoi(opt_arg());
#endif
break;
case OPT_PROV_CASES:
if (!opt_provider(o))
goto end;
break;
}
}
/* No extra arguments. */
argc = opt_num_rest();
if (argc != 0)
goto opthelp;
if (trailing_md) {
BIO_printf(bio_err, "%s: Digest must be before -cert or -serial\n",
prog);
goto opthelp;
}
if (respdigname != NULL) {
if (!opt_md(respdigname, &rsign_md))
goto end;
}
/* Have we anything to do? */
if (req == NULL && reqin == NULL
&& respin == NULL && !(port != NULL && ridx_filename != NULL))
goto opthelp;
out = bio_open_default(outfile, 'w', FORMAT_TEXT);
if (out == NULL)
goto end;
if (req == NULL && (add_nonce != 2))
add_nonce = 0;
if (req == NULL && reqin != NULL) {
derbio = bio_open_default(reqin, 'r', FORMAT_ASN1);
if (derbio == NULL)
goto end;
req = d2i_OCSP_REQUEST_bio(derbio, NULL);
BIO_free(derbio);
if (req == NULL) {
BIO_printf(bio_err, "Error reading OCSP request\n");
goto end;
}
}
if (req == NULL && port != NULL) {
#ifndef OPENSSL_NO_SOCK
acbio = http_server_init_bio(prog, port);
if (acbio == NULL)
goto end;
#else
BIO_printf(bio_err, "Cannot act as server - sockets not supported\n");
goto end;
#endif
}
if (rsignfile != NULL) {
if (rkeyfile == NULL)
rkeyfile = rsignfile;
rsigner = load_cert(rsignfile, FORMAT_UNDEF, "responder certificate");
if (rsigner == NULL) {
BIO_printf(bio_err, "Error loading responder certificate\n");
goto end;
}
if (!load_certs(rca_filename, 0, &rca_cert, NULL, "CA certificates"))
goto end;
if (rcertfile != NULL) {
if (!load_certs(rcertfile, 0, &rother, NULL,
"responder other certificates"))
goto end;
}
if (!app_passwd(passinarg, NULL, &passin, NULL)) {
BIO_printf(bio_err, "Error getting password\n");
goto end;
}
rkey = load_key(rkeyfile, FORMAT_UNDEF, 0, passin, NULL,
"responder private key");
if (rkey == NULL)
goto end;
}
if (ridx_filename != NULL
&& (rkey == NULL || rsigner == NULL || rca_cert == NULL)) {
BIO_printf(bio_err,
"Responder mode requires certificate, key, and CA.\n");
goto end;
}
if (ridx_filename != NULL) {
rdb = load_index(ridx_filename, NULL);
if (rdb == NULL || index_index(rdb) <= 0) {
BIO_printf(bio_err,
"Problem with index file: %s (could not load/parse file)\n",
ridx_filename);
ret = 1;
goto end;
}
}
#ifdef HTTP_DAEMON
if (multi && acbio != NULL)
spawn_loop(prog);
if (acbio != NULL && req_timeout > 0)
signal(SIGALRM, socket_timeout);
#endif
if (acbio != NULL)
log_message(prog, LOG_INFO, "waiting for OCSP client connections...");
redo_accept:
if (acbio != NULL) {
#ifdef HTTP_DAEMON
if (index_changed(rdb)) {
CA_DB *newrdb = load_index(ridx_filename, NULL);
if (newrdb != NULL && index_index(newrdb) > 0) {
free_index(rdb);
rdb = newrdb;
} else {
free_index(newrdb);
log_message(prog, LOG_ERR, "error reloading updated index: %s",
ridx_filename);
}
}
#endif
req = NULL;
res = do_responder(&req, &cbio, acbio, port, req_timeout);
if (res == 0)
goto redo_accept;
if (req == NULL) {
if (res == 1) {
resp =
OCSP_response_create(OCSP_RESPONSE_STATUS_MALFORMEDREQUEST,
NULL);
send_ocsp_response(cbio, resp);
}
goto done_resp;
}
}
if (req == NULL
&& (signfile != NULL || reqout != NULL
|| host != NULL || add_nonce || ridx_filename != NULL)) {
BIO_printf(bio_err, "Need an OCSP request for this operation!\n");
goto end;
}
if (req != NULL && add_nonce) {
if (!OCSP_request_add1_nonce(req, NULL, -1))
goto end;
}
if (signfile != NULL) {
if (keyfile == NULL)
keyfile = signfile;
signer = load_cert(signfile, FORMAT_UNDEF, "signer certificate");
if (signer == NULL) {
BIO_printf(bio_err, "Error loading signer certificate\n");
goto end;
}
if (sign_certfile != NULL) {
if (!load_certs(sign_certfile, 0, &sign_other, NULL,
"signer certificates"))
goto end;
}
key = load_key(keyfile, FORMAT_UNDEF, 0, NULL, NULL,
"signer private key");
if (key == NULL)
goto end;
if (!OCSP_request_sign(req, signer, key, NULL,
sign_other, sign_flags)) {
BIO_printf(bio_err, "Error signing OCSP request\n");
goto end;
}
}
if (req_text && req != NULL)
OCSP_REQUEST_print(out, req, 0);
if (reqout != NULL) {
derbio = bio_open_default(reqout, 'w', FORMAT_ASN1);
if (derbio == NULL)
goto end;
i2d_OCSP_REQUEST_bio(derbio, req);
BIO_free(derbio);
}
if (rdb != NULL) {
make_ocsp_response(bio_err, &resp, req, rdb, rca_cert, rsigner, rkey,
rsign_md, rsign_sigopts, rother, rflags, nmin, ndays,
badsig, resp_certid_md);
if (resp == NULL)
goto end;
if (cbio != NULL)
send_ocsp_response(cbio, resp);
} else if (host != NULL) {
#ifndef OPENSSL_NO_SOCK
resp = process_responder(req, host, port, path, opt_proxy, opt_no_proxy,
use_ssl, headers, req_timeout);
if (resp == NULL)
goto end;
#else
BIO_printf(bio_err,
"Error creating connect BIO - sockets not supported\n");
goto end;
#endif
} else if (respin != NULL) {
derbio = bio_open_default(respin, 'r', FORMAT_ASN1);
if (derbio == NULL)
goto end;
resp = d2i_OCSP_RESPONSE_bio(derbio, NULL);
BIO_free(derbio);
if (resp == NULL) {
BIO_printf(bio_err, "Error reading OCSP response\n");
goto end;
}
} else {
ret = 0;
goto end;
}
done_resp:
if (respout != NULL) {
derbio = bio_open_default(respout, 'w', FORMAT_ASN1);
if (derbio == NULL)
goto end;
i2d_OCSP_RESPONSE_bio(derbio, resp);
BIO_free(derbio);
}
i = OCSP_response_status(resp);
if (i != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
BIO_printf(out, "Responder Error: %s (%d)\n",
OCSP_response_status_str(i), i);
if (!ignore_err)
goto end;
}
if (resp_text)
OCSP_RESPONSE_print(out, resp, 0);
/* If running as responder don't verify our own response */
if (cbio != NULL) {
/* If not unlimited, see if we took all we should. */
if (accept_count != -1 && --accept_count <= 0) {
ret = 0;
goto end;
}
BIO_free_all(cbio);
cbio = NULL;
OCSP_REQUEST_free(req);
req = NULL;
OCSP_RESPONSE_free(resp);
resp = NULL;
goto redo_accept;
}
if (ridx_filename != NULL) {
ret = 0;
goto end;
}
if (store == NULL) {
store = setup_verify(CAfile, noCAfile, CApath, noCApath,
CAstore, noCAstore);
if (!store)
goto end;
}
if (vpmtouched)
X509_STORE_set1_param(store, vpm);
if (verify_certfile != NULL) {
if (!load_certs(verify_certfile, 0, &verify_other, NULL,
"validator certificates"))
goto end;
}
bs = OCSP_response_get1_basic(resp);
if (bs == NULL) {
BIO_printf(bio_err, "Error parsing response\n");
goto end;
}
ret = 0;
if (!noverify) {
if (req != NULL && ((i = OCSP_check_nonce(req, bs)) <= 0)) {
if (i == -1)
BIO_printf(bio_err, "WARNING: no nonce in response\n");
else {
BIO_printf(bio_err, "Nonce Verify error\n");
ret = 1;
goto end;
}
}
i = OCSP_basic_verify(bs, verify_other, store, verify_flags);
if (i <= 0 && issuers) {
i = OCSP_basic_verify(bs, issuers, store, OCSP_TRUSTOTHER);
if (i > 0)
ERR_clear_error();
}
if (i <= 0) {
BIO_printf(bio_err, "Response Verify Failure\n");
ERR_print_errors(bio_err);
ret = 1;
} else {
BIO_printf(bio_err, "Response verify OK\n");
}
}
if (!print_ocsp_summary(out, bs, req, reqnames, ids, nsec, maxage))
ret = 1;
end:
ERR_print_errors(bio_err);
X509_free(signer);
X509_STORE_free(store);
X509_VERIFY_PARAM_free(vpm);
sk_OPENSSL_STRING_free(rsign_sigopts);
EVP_PKEY_free(key);
EVP_PKEY_free(rkey);
EVP_MD_free(cert_id_md);
EVP_MD_free(rsign_md);
EVP_MD_free(resp_certid_md);
X509_free(cert);
sk_X509_pop_free(issuers, X509_free);
X509_free(rsigner);
sk_X509_pop_free(rca_cert, X509_free);
free_index(rdb);
BIO_free_all(cbio);
BIO_free_all(acbio);
BIO_free_all(out);
OCSP_REQUEST_free(req);
OCSP_RESPONSE_free(resp);
OCSP_BASICRESP_free(bs);
sk_OPENSSL_STRING_free(reqnames);
sk_OCSP_CERTID_free(ids);
sk_X509_pop_free(sign_other, X509_free);
sk_X509_pop_free(verify_other, X509_free);
sk_CONF_VALUE_pop_free(headers, X509V3_conf_free);
OPENSSL_free(thost);
OPENSSL_free(tport);
OPENSSL_free(tpath);
return ret;
}
#ifdef HTTP_DAEMON
static int index_changed(CA_DB *rdb)
{
struct stat sb;
if (rdb != NULL && stat(rdb->dbfname, &sb) != -1) {
if (rdb->dbst.st_mtime != sb.st_mtime
|| rdb->dbst.st_ctime != sb.st_ctime
|| rdb->dbst.st_ino != sb.st_ino
|| rdb->dbst.st_dev != sb.st_dev) {
syslog(LOG_INFO, "index file changed, reloading");
return 1;
}
}
return 0;
}
#endif
static int add_ocsp_cert(OCSP_REQUEST **req, X509 *cert,
const EVP_MD *cert_id_md, X509 *issuer,
STACK_OF(OCSP_CERTID) *ids)
{
OCSP_CERTID *id;
if (issuer == NULL) {
BIO_printf(bio_err, "No issuer certificate specified\n");
return 0;
}
if (*req == NULL)
*req = OCSP_REQUEST_new();
if (*req == NULL)
goto err;
id = OCSP_cert_to_id(cert_id_md, cert, issuer);
if (id == NULL || !sk_OCSP_CERTID_push(ids, id))
goto err;
if (!OCSP_request_add0_id(*req, id))
goto err;
return 1;
err:
BIO_printf(bio_err, "Error Creating OCSP request\n");
return 0;
}
static int add_ocsp_serial(OCSP_REQUEST **req, char *serial,
const EVP_MD *cert_id_md, X509 *issuer,
STACK_OF(OCSP_CERTID) *ids)
{
OCSP_CERTID *id;
const X509_NAME *iname;
ASN1_BIT_STRING *ikey;
ASN1_INTEGER *sno;
if (issuer == NULL) {
BIO_printf(bio_err, "No issuer certificate specified\n");
return 0;
}
if (*req == NULL)
*req = OCSP_REQUEST_new();
if (*req == NULL)
goto err;
iname = X509_get_subject_name(issuer);
ikey = X509_get0_pubkey_bitstr(issuer);
sno = s2i_ASN1_INTEGER(NULL, serial);
if (sno == NULL) {
BIO_printf(bio_err, "Error converting serial number %s\n", serial);
return 0;
}
id = OCSP_cert_id_new(cert_id_md, iname, ikey, sno);
ASN1_INTEGER_free(sno);
if (id == NULL || !sk_OCSP_CERTID_push(ids, id))
goto err;
if (!OCSP_request_add0_id(*req, id))
goto err;
return 1;
err:
BIO_printf(bio_err, "Error Creating OCSP request\n");
return 0;
}
static int print_ocsp_summary(BIO *out, OCSP_BASICRESP *bs, OCSP_REQUEST *req,
STACK_OF(OPENSSL_STRING) *names,
STACK_OF(OCSP_CERTID) *ids, long nsec,
long maxage)
{
OCSP_CERTID *id;
const char *name;
int i, status, reason;
ASN1_GENERALIZEDTIME *rev, *thisupd, *nextupd;
int ret = 1;
if (req == NULL || !sk_OPENSSL_STRING_num(names))
return 1;
if (bs == NULL || !sk_OCSP_CERTID_num(ids))
return 0;
for (i = 0; i < sk_OCSP_CERTID_num(ids); i++) {
id = sk_OCSP_CERTID_value(ids, i);
name = sk_OPENSSL_STRING_value(names, i);
BIO_printf(out, "%s: ", name);
if (!OCSP_resp_find_status(bs, id, &status, &reason,
&rev, &thisupd, &nextupd)) {
BIO_puts(out, "ERROR: No Status found.\n");
ret = 0;
continue;
}
/*
* Check validity: if invalid write to output BIO so we know which
* response this refers to.
*/
if (!OCSP_check_validity(thisupd, nextupd, nsec, maxage)) {
BIO_puts(out, "WARNING: Status times invalid.\n");
ERR_print_errors(out);
}
BIO_printf(out, "%s\n", OCSP_cert_status_str(status));
BIO_puts(out, "\tThis Update: ");
ASN1_GENERALIZEDTIME_print(out, thisupd);
BIO_puts(out, "\n");
if (nextupd) {
BIO_puts(out, "\tNext Update: ");
ASN1_GENERALIZEDTIME_print(out, nextupd);
BIO_puts(out, "\n");
}
if (status != V_OCSP_CERTSTATUS_REVOKED)
continue;
if (reason != -1)
BIO_printf(out, "\tReason: %s\n", OCSP_crl_reason_str(reason));
BIO_puts(out, "\tRevocation Time: ");
ASN1_GENERALIZEDTIME_print(out, rev);
BIO_puts(out, "\n");
}
return ret;
}
static void make_ocsp_response(BIO *err, OCSP_RESPONSE **resp, OCSP_REQUEST *req,
CA_DB *db, STACK_OF(X509) *ca, X509 *rcert,
EVP_PKEY *rkey, const EVP_MD *rmd,
STACK_OF(OPENSSL_STRING) *sigopts,
STACK_OF(X509) *rother, unsigned long flags,
int nmin, int ndays, int badsig,
const EVP_MD *resp_md)
{
ASN1_TIME *thisupd = NULL, *nextupd = NULL;
OCSP_CERTID *cid;
OCSP_BASICRESP *bs = NULL;
int i, id_count;
EVP_MD_CTX *mctx = NULL;
EVP_PKEY_CTX *pkctx = NULL;
id_count = OCSP_request_onereq_count(req);
if (id_count <= 0) {
*resp =
OCSP_response_create(OCSP_RESPONSE_STATUS_MALFORMEDREQUEST, NULL);
goto end;
}
bs = OCSP_BASICRESP_new();
thisupd = X509_gmtime_adj(NULL, 0);
if (ndays != -1)
nextupd = X509_time_adj_ex(NULL, ndays, nmin * 60, NULL);
/* Examine each certificate id in the request */
for (i = 0; i < id_count; i++) {
OCSP_ONEREQ *one;
ASN1_INTEGER *serial;
char **inf;
int jj;
int found = 0;
ASN1_OBJECT *cert_id_md_oid;
const EVP_MD *cert_id_md;
OCSP_CERTID *cid_resp_md = NULL;
one = OCSP_request_onereq_get0(req, i);
cid = OCSP_onereq_get0_id(one);
OCSP_id_get0_info(NULL, &cert_id_md_oid, NULL, NULL, cid);
cert_id_md = EVP_get_digestbyobj(cert_id_md_oid);
if (cert_id_md == NULL) {
*resp = OCSP_response_create(OCSP_RESPONSE_STATUS_INTERNALERROR,
NULL);
goto end;
}
for (jj = 0; jj < sk_X509_num(ca) && !found; jj++) {
X509 *ca_cert = sk_X509_value(ca, jj);
OCSP_CERTID *ca_id = OCSP_cert_to_id(cert_id_md, NULL, ca_cert);
if (OCSP_id_issuer_cmp(ca_id, cid) == 0) {
found = 1;
if (resp_md != NULL)
cid_resp_md = OCSP_cert_to_id(resp_md, NULL, ca_cert);
}
OCSP_CERTID_free(ca_id);
}
OCSP_id_get0_info(NULL, NULL, NULL, &serial, cid);
inf = lookup_serial(db, serial);
/* at this point, we can have cid be an alias of cid_resp_md */
cid = (cid_resp_md != NULL) ? cid_resp_md : cid;
if (!found) {
OCSP_basic_add1_status(bs, cid,
V_OCSP_CERTSTATUS_UNKNOWN,
0, NULL, thisupd, nextupd);
continue;
}
if (inf == NULL) {
OCSP_basic_add1_status(bs, cid,
V_OCSP_CERTSTATUS_UNKNOWN,
0, NULL, thisupd, nextupd);
} else if (inf[DB_type][0] == DB_TYPE_VAL) {
OCSP_basic_add1_status(bs, cid,
V_OCSP_CERTSTATUS_GOOD,
0, NULL, thisupd, nextupd);
} else if (inf[DB_type][0] == DB_TYPE_REV) {
ASN1_OBJECT *inst = NULL;
ASN1_TIME *revtm = NULL;
ASN1_GENERALIZEDTIME *invtm = NULL;
OCSP_SINGLERESP *single;
int reason = -1;
unpack_revinfo(&revtm, &reason, &inst, &invtm, inf[DB_rev_date]);
single = OCSP_basic_add1_status(bs, cid,
V_OCSP_CERTSTATUS_REVOKED,
reason, revtm, thisupd, nextupd);
if (single == NULL) {
*resp = OCSP_response_create(OCSP_RESPONSE_STATUS_INTERNALERROR,
NULL);
goto end;
}
if (invtm != NULL)
OCSP_SINGLERESP_add1_ext_i2d(single, NID_invalidity_date,
invtm, 0, 0);
else if (inst != NULL)
OCSP_SINGLERESP_add1_ext_i2d(single,
NID_hold_instruction_code, inst,
0, 0);
ASN1_OBJECT_free(inst);
ASN1_TIME_free(revtm);
ASN1_GENERALIZEDTIME_free(invtm);
}
OCSP_CERTID_free(cid_resp_md);
}
OCSP_copy_nonce(bs, req);
mctx = EVP_MD_CTX_new();
if ( mctx == NULL || !EVP_DigestSignInit(mctx, &pkctx, rmd, NULL, rkey)) {
*resp = OCSP_response_create(OCSP_RESPONSE_STATUS_INTERNALERROR, NULL);
goto end;
}
for (i = 0; i < sk_OPENSSL_STRING_num(sigopts); i++) {
char *sigopt = sk_OPENSSL_STRING_value(sigopts, i);
if (pkey_ctrl_string(pkctx, sigopt) <= 0) {
BIO_printf(err, "parameter error \"%s\"\n", sigopt);
ERR_print_errors(bio_err);
*resp = OCSP_response_create(OCSP_RESPONSE_STATUS_INTERNALERROR,
NULL);
goto end;
}
}
if (!OCSP_basic_sign_ctx(bs, rcert, mctx, rother, flags)) {
*resp = OCSP_response_create(OCSP_RESPONSE_STATUS_INTERNALERROR, bs);
goto end;
}
if (badsig) {
const ASN1_OCTET_STRING *sig = OCSP_resp_get0_signature(bs);
corrupt_signature(sig);
}
*resp = OCSP_response_create(OCSP_RESPONSE_STATUS_SUCCESSFUL, bs);
end:
EVP_MD_CTX_free(mctx);
ASN1_TIME_free(thisupd);
ASN1_TIME_free(nextupd);
OCSP_BASICRESP_free(bs);
}
static char **lookup_serial(CA_DB *db, ASN1_INTEGER *ser)
{
int i;
BIGNUM *bn = NULL;
char *itmp, *row[DB_NUMBER], **rrow;
for (i = 0; i < DB_NUMBER; i++)
row[i] = NULL;
bn = ASN1_INTEGER_to_BN(ser, NULL);
OPENSSL_assert(bn); /* FIXME: should report an error at this
* point and abort */
if (BN_is_zero(bn)) {
itmp = OPENSSL_strdup("00");
OPENSSL_assert(itmp);
} else {
itmp = BN_bn2hex(bn);
}
row[DB_serial] = itmp;
BN_free(bn);
rrow = TXT_DB_get_by_index(db->db, DB_serial, row);
OPENSSL_free(itmp);
return rrow;
}
static int do_responder(OCSP_REQUEST **preq, BIO **pcbio, BIO *acbio,
const char *port, int timeout)
{
#ifndef OPENSSL_NO_SOCK
return http_server_get_asn1_req(ASN1_ITEM_rptr(OCSP_REQUEST),
(ASN1_VALUE **)preq, NULL, pcbio, acbio,
NULL /* found_keep_alive */,
prog, port, 1 /* accept_get */, timeout);
#else
BIO_printf(bio_err,
"Error getting OCSP request - sockets not supported\n");
*preq = NULL;
return 0;
#endif
}
static int send_ocsp_response(BIO *cbio, const OCSP_RESPONSE *resp)
{
#ifndef OPENSSL_NO_SOCK
return http_server_send_asn1_resp(cbio,
0 /* no keep-alive */,
"application/ocsp-response",
ASN1_ITEM_rptr(OCSP_RESPONSE),
(const ASN1_VALUE *)resp);
#else
BIO_printf(bio_err,
"Error sending OCSP response - sockets not supported\n");
return 0;
#endif
}
#ifndef OPENSSL_NO_SOCK
OCSP_RESPONSE *process_responder(OCSP_REQUEST *req, const char *host,
const char *port, const char *path,
const char *proxy, const char *no_proxy,
int use_ssl, STACK_OF(CONF_VALUE) *headers,
int req_timeout)
{
SSL_CTX *ctx = NULL;
OCSP_RESPONSE *resp = NULL;
if (use_ssl == 1) {
ctx = SSL_CTX_new(TLS_client_method());
if (ctx == NULL) {
BIO_printf(bio_err, "Error creating SSL context.\n");
goto end;
}
}
resp = (OCSP_RESPONSE *)
app_http_post_asn1(host, port, path, proxy, no_proxy,
ctx, headers, "application/ocsp-request",
(ASN1_VALUE *)req, ASN1_ITEM_rptr(OCSP_REQUEST),
"application/ocsp-response",
req_timeout, ASN1_ITEM_rptr(OCSP_RESPONSE));
if (resp == NULL)
BIO_printf(bio_err, "Error querying OCSP responder\n");
end:
SSL_CTX_free(ctx);
return resp;
}
#endif
diff --git a/crypto/openssl/apps/pkcs12.c b/crypto/openssl/apps/pkcs12.c
index b442d358f8b7..ab78903ee9cd 100644
--- a/crypto/openssl/apps/pkcs12.c
+++ b/crypto/openssl/apps/pkcs12.c
@@ -1,1231 +1,1237 @@
/*
- * Copyright 1999-2022 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 1999-2024 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 <openssl/opensslconf.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "apps.h"
#include "progs.h"
#include <openssl/crypto.h>
#include <openssl/err.h>
#include <openssl/pem.h>
#include <openssl/pkcs12.h>
#include <openssl/provider.h>
#include <openssl/kdf.h>
#define NOKEYS 0x1
#define NOCERTS 0x2
#define INFO 0x4
#define CLCERTS 0x8
#define CACERTS 0x10
#define PASSWD_BUF_SIZE 2048
#define WARN_EXPORT(opt) \
BIO_printf(bio_err, "Warning: -%s option ignored with -export\n", opt);
#define WARN_NO_EXPORT(opt) \
BIO_printf(bio_err, "Warning: -%s option ignored without -export\n", opt);
static int get_cert_chain(X509 *cert, X509_STORE *store,
STACK_OF(X509) *untrusted_certs,
STACK_OF(X509) **chain);
int dump_certs_keys_p12(BIO *out, const PKCS12 *p12,
const char *pass, int passlen, int options,
char *pempass, const EVP_CIPHER *enc);
int dump_certs_pkeys_bags(BIO *out, const STACK_OF(PKCS12_SAFEBAG) *bags,
const char *pass, int passlen, int options,
char *pempass, const EVP_CIPHER *enc);
int dump_certs_pkeys_bag(BIO *out, const PKCS12_SAFEBAG *bags,
const char *pass, int passlen,
int options, char *pempass, const EVP_CIPHER *enc);
void print_attribute(BIO *out, const ASN1_TYPE *av);
int print_attribs(BIO *out, const STACK_OF(X509_ATTRIBUTE) *attrlst,
const char *name);
void hex_prin(BIO *out, unsigned char *buf, int len);
static int alg_print(const X509_ALGOR *alg);
int cert_load(BIO *in, STACK_OF(X509) *sk);
static int set_pbe(int *ppbe, const char *str);
typedef enum OPTION_choice {
OPT_COMMON,
OPT_CIPHER, OPT_NOKEYS, OPT_KEYEX, OPT_KEYSIG, OPT_NOCERTS, OPT_CLCERTS,
OPT_CACERTS, OPT_NOOUT, OPT_INFO, OPT_CHAIN, OPT_TWOPASS, OPT_NOMACVER,
#ifndef OPENSSL_NO_DES
OPT_DESCERT,
#endif
OPT_EXPORT, OPT_ITER, OPT_NOITER, OPT_MACITER, OPT_NOMACITER,
OPT_NOMAC, OPT_LMK, OPT_NODES, OPT_NOENC, OPT_MACALG, OPT_CERTPBE, OPT_KEYPBE,
OPT_INKEY, OPT_CERTFILE, OPT_UNTRUSTED, OPT_PASSCERTS,
OPT_NAME, OPT_CSP, OPT_CANAME,
OPT_IN, OPT_OUT, OPT_PASSIN, OPT_PASSOUT, OPT_PASSWORD, OPT_CAPATH,
OPT_CAFILE, OPT_CASTORE, OPT_NOCAPATH, OPT_NOCAFILE, OPT_NOCASTORE, OPT_ENGINE,
OPT_R_ENUM, OPT_PROV_ENUM,
#ifndef OPENSSL_NO_DES
OPT_LEGACY_ALG
#endif
} OPTION_CHOICE;
const OPTIONS pkcs12_options[] = {
OPT_SECTION("General"),
{"help", OPT_HELP, '-', "Display this summary"},
{"in", OPT_IN, '<', "Input file"},
{"out", OPT_OUT, '>', "Output file"},
{"passin", OPT_PASSIN, 's', "Input file pass phrase source"},
{"passout", OPT_PASSOUT, 's', "Output file pass phrase source"},
{"password", OPT_PASSWORD, 's', "Set PKCS#12 import/export password source"},
{"twopass", OPT_TWOPASS, '-', "Separate MAC, encryption passwords"},
{"nokeys", OPT_NOKEYS, '-', "Don't output private keys"},
{"nocerts", OPT_NOCERTS, '-', "Don't output certificates"},
{"noout", OPT_NOOUT, '-', "Don't output anything, just verify PKCS#12 input"},
#ifndef OPENSSL_NO_DES
{"legacy", OPT_LEGACY_ALG, '-',
# ifdef OPENSSL_NO_RC2
"Use legacy encryption algorithm 3DES_CBC for keys and certs"
# else
"Use legacy encryption: 3DES_CBC for keys, RC2_CBC for certs"
# endif
},
#endif
#ifndef OPENSSL_NO_ENGINE
{"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"},
#endif
OPT_PROV_OPTIONS,
OPT_R_OPTIONS,
OPT_SECTION("PKCS#12 import (parsing PKCS#12)"),
{"info", OPT_INFO, '-', "Print info about PKCS#12 structure"},
{"nomacver", OPT_NOMACVER, '-', "Don't verify integrity MAC"},
{"clcerts", OPT_CLCERTS, '-', "Only output client certificates"},
{"cacerts", OPT_CACERTS, '-', "Only output CA certificates"},
{"", OPT_CIPHER, '-', "Any supported cipher for output encryption"},
{"noenc", OPT_NOENC, '-', "Don't encrypt private keys"},
{"nodes", OPT_NODES, '-', "Don't encrypt private keys; deprecated"},
OPT_SECTION("PKCS#12 output (export)"),
{"export", OPT_EXPORT, '-', "Create PKCS12 file"},
{"inkey", OPT_INKEY, 's', "Private key, else read from -in input file"},
{"certfile", OPT_CERTFILE, '<', "Extra certificates for PKCS12 output"},
{"passcerts", OPT_PASSCERTS, 's', "Certificate file pass phrase source"},
{"chain", OPT_CHAIN, '-', "Build and add certificate chain for EE cert,"},
{OPT_MORE_STR, 0, 0,
"which is the 1st cert from -in matching the private key (if given)"},
{"untrusted", OPT_UNTRUSTED, '<', "Untrusted certificates for chain building"},
{"CAfile", OPT_CAFILE, '<', "PEM-format file of CA's"},
{"CApath", OPT_CAPATH, '/', "PEM-format directory of CA's"},
{"CAstore", OPT_CASTORE, ':', "URI to store of CA's"},
{"no-CAfile", OPT_NOCAFILE, '-',
"Do not load the default certificates file"},
{"no-CApath", OPT_NOCAPATH, '-',
"Do not load certificates from the default certificates directory"},
{"no-CAstore", OPT_NOCASTORE, '-',
"Do not load certificates from the default certificates store"},
{"name", OPT_NAME, 's', "Use name as friendly name"},
{"caname", OPT_CANAME, 's',
"Use name as CA friendly name (can be repeated)"},
{"CSP", OPT_CSP, 's', "Microsoft CSP name"},
{"LMK", OPT_LMK, '-',
"Add local machine keyset attribute to private key"},
{"keyex", OPT_KEYEX, '-', "Set key type to MS key exchange"},
{"keysig", OPT_KEYSIG, '-', "Set key type to MS key signature"},
{"keypbe", OPT_KEYPBE, 's', "Private key PBE algorithm (default AES-256 CBC)"},
{"certpbe", OPT_CERTPBE, 's',
"Certificate PBE algorithm (default PBES2 with PBKDF2 and AES-256 CBC)"},
#ifndef OPENSSL_NO_DES
{"descert", OPT_DESCERT, '-',
"Encrypt output with 3DES (default PBES2 with PBKDF2 and AES-256 CBC)"},
#endif
{"macalg", OPT_MACALG, 's',
"Digest algorithm to use in MAC (default SHA256)"},
{"iter", OPT_ITER, 'p', "Specify the iteration count for encryption and MAC"},
{"noiter", OPT_NOITER, '-', "Don't use encryption iteration"},
{"nomaciter", OPT_NOMACITER, '-', "Don't use MAC iteration)"},
{"maciter", OPT_MACITER, '-', "Unused, kept for backwards compatibility"},
{"nomac", OPT_NOMAC, '-', "Don't generate MAC"},
{NULL}
};
int pkcs12_main(int argc, char **argv)
{
char *infile = NULL, *outfile = NULL, *keyname = NULL, *certfile = NULL;
char *untrusted = NULL, *ciphername = NULL, *enc_flag = NULL;
char *passcertsarg = NULL, *passcerts = NULL;
char *name = NULL, *csp_name = NULL;
char pass[PASSWD_BUF_SIZE] = "", macpass[PASSWD_BUF_SIZE] = "";
int export_pkcs12 = 0, options = 0, chain = 0, twopass = 0, keytype = 0;
#ifndef OPENSSL_NO_DES
int use_legacy = 0;
#endif
/* use library defaults for the iter, maciter, cert, and key PBE */
int iter = 0, maciter = 0;
int cert_pbe = NID_undef;
int key_pbe = NID_undef;
int ret = 1, macver = 1, add_lmk = 0, private = 0;
int noprompt = 0;
char *passinarg = NULL, *passoutarg = NULL, *passarg = NULL;
char *passin = NULL, *passout = NULL, *macalg = NULL;
char *cpass = NULL, *mpass = NULL, *badpass = NULL;
const char *CApath = NULL, *CAfile = NULL, *CAstore = NULL, *prog;
int noCApath = 0, noCAfile = 0, noCAstore = 0;
ENGINE *e = NULL;
BIO *in = NULL, *out = NULL;
PKCS12 *p12 = NULL;
STACK_OF(OPENSSL_STRING) *canames = NULL;
EVP_CIPHER *default_enc = (EVP_CIPHER *)EVP_aes_256_cbc();
EVP_CIPHER *enc = (EVP_CIPHER *)default_enc;
OPTION_CHOICE o;
prog = opt_init(argc, argv, pkcs12_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(pkcs12_options);
ret = 0;
goto end;
case OPT_NOKEYS:
options |= NOKEYS;
break;
case OPT_KEYEX:
keytype = KEY_EX;
break;
case OPT_KEYSIG:
keytype = KEY_SIG;
break;
case OPT_NOCERTS:
options |= NOCERTS;
break;
case OPT_CLCERTS:
options |= CLCERTS;
break;
case OPT_CACERTS:
options |= CACERTS;
break;
case OPT_NOOUT:
options |= (NOKEYS | NOCERTS);
break;
case OPT_INFO:
options |= INFO;
break;
case OPT_CHAIN:
chain = 1;
break;
case OPT_TWOPASS:
twopass = 1;
break;
case OPT_NOMACVER:
macver = 0;
break;
#ifndef OPENSSL_NO_DES
case OPT_DESCERT:
cert_pbe = NID_pbe_WithSHA1And3_Key_TripleDES_CBC;
break;
#endif
case OPT_EXPORT:
export_pkcs12 = 1;
break;
case OPT_NODES:
case OPT_NOENC:
/*
* |enc_flag| stores the name of the option used so it
* can be printed if an error message is output.
*/
enc_flag = opt_flag() + 1;
enc = NULL;
ciphername = NULL;
break;
case OPT_CIPHER:
ciphername = opt_unknown();
enc_flag = opt_unknown();
break;
case OPT_ITER:
maciter = iter = opt_int_arg();
break;
case OPT_NOITER:
iter = 1;
break;
case OPT_MACITER:
/* no-op */
break;
case OPT_NOMACITER:
maciter = 1;
break;
case OPT_NOMAC:
cert_pbe = -1;
maciter = -1;
break;
case OPT_MACALG:
macalg = opt_arg();
break;
case OPT_CERTPBE:
if (!set_pbe(&cert_pbe, opt_arg()))
goto opthelp;
break;
case OPT_KEYPBE:
if (!set_pbe(&key_pbe, opt_arg()))
goto opthelp;
break;
case OPT_R_CASES:
if (!opt_rand(o))
goto end;
break;
case OPT_INKEY:
keyname = opt_arg();
break;
case OPT_CERTFILE:
certfile = opt_arg();
break;
case OPT_UNTRUSTED:
untrusted = opt_arg();
break;
case OPT_PASSCERTS:
passcertsarg = opt_arg();
break;
case OPT_NAME:
name = opt_arg();
break;
case OPT_LMK:
add_lmk = 1;
break;
case OPT_CSP:
csp_name = opt_arg();
break;
case OPT_CANAME:
if (canames == NULL
&& (canames = sk_OPENSSL_STRING_new_null()) == NULL)
goto end;
sk_OPENSSL_STRING_push(canames, opt_arg());
break;
case OPT_IN:
infile = opt_arg();
break;
case OPT_OUT:
outfile = opt_arg();
break;
case OPT_PASSIN:
passinarg = opt_arg();
break;
case OPT_PASSOUT:
passoutarg = opt_arg();
break;
case OPT_PASSWORD:
passarg = opt_arg();
break;
case OPT_CAPATH:
CApath = opt_arg();
break;
case OPT_CASTORE:
CAstore = opt_arg();
break;
case OPT_CAFILE:
CAfile = opt_arg();
break;
case OPT_NOCAPATH:
noCApath = 1;
break;
case OPT_NOCASTORE:
noCAstore = 1;
break;
case OPT_NOCAFILE:
noCAfile = 1;
break;
case OPT_ENGINE:
e = setup_engine(opt_arg(), 0);
break;
#ifndef OPENSSL_NO_DES
case OPT_LEGACY_ALG:
use_legacy = 1;
break;
#endif
case OPT_PROV_CASES:
if (!opt_provider(o))
goto end;
break;
}
}
/* No extra arguments. */
argc = opt_num_rest();
if (argc != 0)
goto opthelp;
if (!app_RAND_load())
goto end;
if (ciphername != NULL) {
if (!opt_cipher_any(ciphername, &enc))
goto opthelp;
}
if (export_pkcs12) {
if ((options & INFO) != 0)
WARN_EXPORT("info");
if (macver == 0)
WARN_EXPORT("nomacver");
if ((options & CLCERTS) != 0)
WARN_EXPORT("clcerts");
if ((options & CACERTS) != 0)
WARN_EXPORT("cacerts");
if (enc != default_enc)
BIO_printf(bio_err,
"Warning: output encryption option -%s ignored with -export\n", enc_flag);
} else {
if (keyname != NULL)
WARN_NO_EXPORT("inkey");
if (certfile != NULL)
WARN_NO_EXPORT("certfile");
if (passcertsarg != NULL)
WARN_NO_EXPORT("passcerts");
if (chain)
WARN_NO_EXPORT("chain");
if (untrusted != NULL)
WARN_NO_EXPORT("untrusted");
if (CAfile != NULL)
WARN_NO_EXPORT("CAfile");
if (CApath != NULL)
WARN_NO_EXPORT("CApath");
if (CAstore != NULL)
WARN_NO_EXPORT("CAstore");
if (noCAfile)
WARN_NO_EXPORT("no-CAfile");
if (noCApath)
WARN_NO_EXPORT("no-CApath");
if (noCAstore)
WARN_NO_EXPORT("no-CAstore");
if (name != NULL)
WARN_NO_EXPORT("name");
if (canames != NULL)
WARN_NO_EXPORT("caname");
if (csp_name != NULL)
WARN_NO_EXPORT("CSP");
if (add_lmk)
WARN_NO_EXPORT("LMK");
if (keytype == KEY_EX)
WARN_NO_EXPORT("keyex");
if (keytype == KEY_SIG)
WARN_NO_EXPORT("keysig");
if (key_pbe != NID_undef)
WARN_NO_EXPORT("keypbe");
if (cert_pbe != NID_undef && cert_pbe != -1)
WARN_NO_EXPORT("certpbe and -descert");
if (macalg != NULL)
WARN_NO_EXPORT("macalg");
if (iter != 0)
WARN_NO_EXPORT("iter and -noiter");
if (maciter == 1)
WARN_NO_EXPORT("nomaciter");
if (cert_pbe == -1 && maciter == -1)
WARN_NO_EXPORT("nomac");
}
#ifndef OPENSSL_NO_DES
if (use_legacy) {
/* load the legacy provider if not loaded already*/
if (!OSSL_PROVIDER_available(app_get0_libctx(), "legacy")) {
if (!app_provider_load(app_get0_libctx(), "legacy"))
goto end;
/* load the default provider explicitly */
if (!app_provider_load(app_get0_libctx(), "default"))
goto end;
}
if (cert_pbe == NID_undef) {
/* Adapt default algorithm */
# ifndef OPENSSL_NO_RC2
cert_pbe = NID_pbe_WithSHA1And40BitRC2_CBC;
# else
cert_pbe = NID_pbe_WithSHA1And3_Key_TripleDES_CBC;
# endif
}
if (key_pbe == NID_undef)
key_pbe = NID_pbe_WithSHA1And3_Key_TripleDES_CBC;
if (enc == default_enc)
enc = (EVP_CIPHER *)EVP_des_ede3_cbc();
if (macalg == NULL)
macalg = "sha1";
}
#endif
private = 1;
if (!app_passwd(passcertsarg, NULL, &passcerts, NULL)) {
BIO_printf(bio_err, "Error getting certificate file password\n");
goto end;
}
if (passarg != NULL) {
if (export_pkcs12)
passoutarg = passarg;
else
passinarg = passarg;
}
if (!app_passwd(passinarg, passoutarg, &passin, &passout)) {
BIO_printf(bio_err, "Error getting passwords\n");
goto end;
}
if (cpass == NULL) {
if (export_pkcs12)
cpass = passout;
else
cpass = passin;
}
if (cpass != NULL) {
mpass = cpass;
noprompt = 1;
if (twopass) {
if (export_pkcs12)
BIO_printf(bio_err, "Option -twopass cannot be used with -passout or -password\n");
else
BIO_printf(bio_err, "Option -twopass cannot be used with -passin or -password\n");
goto end;
}
} else {
cpass = pass;
mpass = macpass;
}
if (twopass) {
/* To avoid bit rot */
if (1) {
#ifndef OPENSSL_NO_UI_CONSOLE
if (EVP_read_pw_string(
macpass, sizeof(macpass), "Enter MAC Password:", export_pkcs12)) {
BIO_printf(bio_err, "Can't read Password\n");
goto end;
}
} else {
#endif
BIO_printf(bio_err, "Unsupported option -twopass\n");
goto end;
}
}
if (export_pkcs12) {
EVP_PKEY *key = NULL;
X509 *ee_cert = NULL, *x = NULL;
STACK_OF(X509) *certs = NULL;
STACK_OF(X509) *untrusted_certs = NULL;
EVP_MD *macmd = NULL;
unsigned char *catmp = NULL;
int i;
if ((options & (NOCERTS | NOKEYS)) == (NOCERTS | NOKEYS)) {
BIO_printf(bio_err, "Nothing to export due to -noout or -nocerts and -nokeys\n");
goto export_end;
}
if ((options & NOCERTS) != 0) {
chain = 0;
BIO_printf(bio_err, "Warning: -chain option ignored with -nocerts\n");
}
if (!(options & NOKEYS)) {
key = load_key(keyname ? keyname : infile,
FORMAT_PEM, 1, passin, e,
keyname ?
"private key from -inkey file" :
"private key from -in file");
if (key == NULL)
goto export_end;
}
/* Load all certs in input file */
if (!(options & NOCERTS)) {
if (!load_certs(infile, 1, &certs, passin,
"certificates from -in file"))
goto export_end;
if (sk_X509_num(certs) < 1) {
BIO_printf(bio_err, "No certificate in -in file %s\n", infile);
goto export_end;
}
if (key != NULL) {
/* Look for matching private key */
for (i = 0; i < sk_X509_num(certs); i++) {
x = sk_X509_value(certs, i);
if (X509_check_private_key(x, key)) {
ee_cert = x;
/* Zero keyid and alias */
X509_keyid_set1(ee_cert, NULL, 0);
X509_alias_set1(ee_cert, NULL, 0);
/* Remove from list */
(void)sk_X509_delete(certs, i);
break;
}
}
if (ee_cert == NULL) {
BIO_printf(bio_err,
"No cert in -in file '%s' matches private key\n",
infile);
goto export_end;
}
}
}
/* Load any untrusted certificates for chain building */
if (untrusted != NULL) {
if (!load_certs(untrusted, 0, &untrusted_certs, passcerts,
"untrusted certificates"))
goto export_end;
}
/* If chaining get chain from end entity cert */
if (chain) {
int vret;
STACK_OF(X509) *chain2;
X509_STORE *store;
X509 *ee_cert_tmp = ee_cert;
/* Assume the first cert if we haven't got anything else */
if (ee_cert_tmp == NULL && certs != NULL)
ee_cert_tmp = sk_X509_value(certs, 0);
if (ee_cert_tmp == NULL) {
BIO_printf(bio_err,
"No end entity certificate to check with -chain\n");
goto export_end;
}
if ((store = setup_verify(CAfile, noCAfile, CApath, noCApath,
CAstore, noCAstore))
== NULL)
goto export_end;
vret = get_cert_chain(ee_cert_tmp, store, untrusted_certs, &chain2);
X509_STORE_free(store);
if (vret == X509_V_OK) {
int add_certs;
/* Remove from chain2 the first (end entity) certificate */
X509_free(sk_X509_shift(chain2));
/* Add the remaining certs (except for duplicates) */
add_certs = X509_add_certs(certs, chain2, X509_ADD_FLAG_UP_REF
| X509_ADD_FLAG_NO_DUP);
sk_X509_pop_free(chain2, X509_free);
if (!add_certs)
goto export_end;
} else {
if (vret != X509_V_ERR_UNSPECIFIED)
BIO_printf(bio_err, "Error getting chain: %s\n",
X509_verify_cert_error_string(vret));
goto export_end;
}
}
/* Add any extra certificates asked for */
if (certfile != NULL) {
if (!load_certs(certfile, 0, &certs, passcerts,
"extra certificates from -certfile"))
goto export_end;
}
/* Add any CA names */
for (i = 0; i < sk_OPENSSL_STRING_num(canames); i++) {
catmp = (unsigned char *)sk_OPENSSL_STRING_value(canames, i);
X509_alias_set1(sk_X509_value(certs, i), catmp, -1);
}
if (csp_name != NULL && key != NULL)
EVP_PKEY_add1_attr_by_NID(key, NID_ms_csp_name,
MBSTRING_ASC, (unsigned char *)csp_name,
-1);
if (add_lmk && key != NULL)
EVP_PKEY_add1_attr_by_NID(key, NID_LocalKeySet, 0, NULL, -1);
if (!noprompt && !(enc == NULL && maciter == -1)) {
/* To avoid bit rot */
if (1) {
#ifndef OPENSSL_NO_UI_CONSOLE
if (EVP_read_pw_string(pass, sizeof(pass),
"Enter Export Password:", 1)) {
BIO_printf(bio_err, "Can't read Password\n");
goto export_end;
}
} else {
#endif
BIO_printf(bio_err, "Password required\n");
goto export_end;
}
}
if (!twopass)
OPENSSL_strlcpy(macpass, pass, sizeof(macpass));
p12 = PKCS12_create_ex(cpass, name, key, ee_cert, certs,
key_pbe, cert_pbe, iter, -1, keytype,
app_get0_libctx(), app_get0_propq());
if (p12 == NULL) {
BIO_printf(bio_err, "Error creating PKCS12 structure for %s\n",
outfile);
goto export_end;
}
if (macalg != NULL) {
if (!opt_md(macalg, &macmd))
goto opthelp;
}
if (maciter != -1)
if (!PKCS12_set_mac(p12, mpass, -1, NULL, 0, maciter, macmd)) {
BIO_printf(bio_err, "Error creating PKCS12 MAC; no PKCS12KDF support?\n");
BIO_printf(bio_err, "Use -nomac if MAC not required and PKCS12KDF support not available.\n");
goto export_end;
}
assert(private);
out = bio_open_owner(outfile, FORMAT_PKCS12, private);
if (out == NULL)
goto end;
i2d_PKCS12_bio(out, p12);
ret = 0;
export_end:
EVP_PKEY_free(key);
EVP_MD_free(macmd);
sk_X509_pop_free(certs, X509_free);
sk_X509_pop_free(untrusted_certs, X509_free);
X509_free(ee_cert);
ERR_print_errors(bio_err);
goto end;
}
in = bio_open_default(infile, 'r', FORMAT_PKCS12);
if (in == NULL)
goto end;
- out = bio_open_owner(outfile, FORMAT_PEM, private);
- if (out == NULL)
- goto end;
p12 = PKCS12_init_ex(NID_pkcs7_data, app_get0_libctx(), app_get0_propq());
if (p12 == NULL) {
ERR_print_errors(bio_err);
goto end;
}
if ((p12 = d2i_PKCS12_bio(in, &p12)) == NULL) {
ERR_print_errors(bio_err);
goto end;
}
if (!noprompt) {
if (1) {
#ifndef OPENSSL_NO_UI_CONSOLE
if (EVP_read_pw_string(pass, sizeof(pass), "Enter Import Password:",
0)) {
BIO_printf(bio_err, "Can't read Password\n");
goto end;
}
} else {
#endif
BIO_printf(bio_err, "Password required\n");
goto end;
}
}
if (!twopass)
OPENSSL_strlcpy(macpass, pass, sizeof(macpass));
if ((options & INFO) && PKCS12_mac_present(p12)) {
const ASN1_INTEGER *tmaciter;
const X509_ALGOR *macalgid;
const ASN1_OBJECT *macobj;
const ASN1_OCTET_STRING *tmac;
const ASN1_OCTET_STRING *tsalt;
PKCS12_get0_mac(&tmac, &macalgid, &tsalt, &tmaciter, p12);
/* current hash algorithms do not use parameters so extract just name,
in future alg_print() may be needed */
X509_ALGOR_get0(&macobj, NULL, NULL, macalgid);
BIO_puts(bio_err, "MAC: ");
i2a_ASN1_OBJECT(bio_err, macobj);
BIO_printf(bio_err, ", Iteration %ld\n",
tmaciter != NULL ? ASN1_INTEGER_get(tmaciter) : 1L);
BIO_printf(bio_err, "MAC length: %ld, salt length: %ld\n",
tmac != NULL ? ASN1_STRING_length(tmac) : 0L,
tsalt != NULL ? ASN1_STRING_length(tsalt) : 0L);
}
if (macver) {
EVP_KDF *pkcs12kdf;
pkcs12kdf = EVP_KDF_fetch(app_get0_libctx(), "PKCS12KDF",
app_get0_propq());
if (pkcs12kdf == NULL) {
BIO_printf(bio_err, "Error verifying PKCS12 MAC; no PKCS12KDF support.\n");
BIO_printf(bio_err, "Use -nomacver if MAC verification is not required.\n");
goto end;
}
EVP_KDF_free(pkcs12kdf);
/* If we enter empty password try no password first */
if (!mpass[0] && PKCS12_verify_mac(p12, NULL, 0)) {
/* If mac and crypto pass the same set it to NULL too */
if (!twopass)
cpass = NULL;
} else if (!PKCS12_verify_mac(p12, mpass, -1)) {
/*
* May be UTF8 from previous version of OpenSSL:
* convert to a UTF8 form which will translate
* to the same Unicode password.
*/
unsigned char *utmp;
int utmplen;
unsigned long err = ERR_peek_error();
if (ERR_GET_LIB(err) == ERR_LIB_PKCS12
&& ERR_GET_REASON(err) == PKCS12_R_MAC_ABSENT) {
BIO_printf(bio_err, "Warning: MAC is absent!\n");
goto dump;
}
utmp = OPENSSL_asc2uni(mpass, -1, NULL, &utmplen);
if (utmp == NULL)
goto end;
badpass = OPENSSL_uni2utf8(utmp, utmplen);
OPENSSL_free(utmp);
if (!PKCS12_verify_mac(p12, badpass, -1)) {
BIO_printf(bio_err, "Mac verify error: invalid password?\n");
ERR_print_errors(bio_err);
goto end;
} else {
BIO_printf(bio_err, "Warning: using broken algorithm\n");
if (!twopass)
cpass = badpass;
}
}
}
dump:
assert(private);
+
+ out = bio_open_owner(outfile, FORMAT_PEM, private);
+ if (out == NULL)
+ goto end;
+
if (!dump_certs_keys_p12(out, p12, cpass, -1, options, passout, enc)) {
BIO_printf(bio_err, "Error outputting keys and certificates\n");
ERR_print_errors(bio_err);
goto end;
}
ret = 0;
end:
PKCS12_free(p12);
release_engine(e);
BIO_free(in);
BIO_free_all(out);
sk_OPENSSL_STRING_free(canames);
OPENSSL_free(badpass);
OPENSSL_free(passcerts);
OPENSSL_free(passin);
OPENSSL_free(passout);
return ret;
}
int dump_certs_keys_p12(BIO *out, const PKCS12 *p12, const char *pass,
int passlen, int options, char *pempass,
const EVP_CIPHER *enc)
{
STACK_OF(PKCS7) *asafes = NULL;
STACK_OF(PKCS12_SAFEBAG) *bags;
int i, bagnid;
int ret = 0;
PKCS7 *p7;
if ((asafes = PKCS12_unpack_authsafes(p12)) == NULL)
return 0;
for (i = 0; i < sk_PKCS7_num(asafes); i++) {
p7 = sk_PKCS7_value(asafes, i);
bagnid = OBJ_obj2nid(p7->type);
if (bagnid == NID_pkcs7_data) {
bags = PKCS12_unpack_p7data(p7);
if (options & INFO)
BIO_printf(bio_err, "PKCS7 Data\n");
} else if (bagnid == NID_pkcs7_encrypted) {
if (options & INFO) {
BIO_printf(bio_err, "PKCS7 Encrypted data: ");
- alg_print(p7->d.encrypted->enc_data->algorithm);
+ if (p7->d.encrypted == NULL) {
+ BIO_printf(bio_err, "<no data>\n");
+ } else {
+ alg_print(p7->d.encrypted->enc_data->algorithm);
+ }
}
bags = PKCS12_unpack_p7encdata(p7, pass, passlen);
} else {
continue;
}
if (!bags)
goto err;
if (!dump_certs_pkeys_bags(out, bags, pass, passlen,
options, pempass, enc)) {
sk_PKCS12_SAFEBAG_pop_free(bags, PKCS12_SAFEBAG_free);
goto err;
}
sk_PKCS12_SAFEBAG_pop_free(bags, PKCS12_SAFEBAG_free);
bags = NULL;
}
ret = 1;
err:
sk_PKCS7_pop_free(asafes, PKCS7_free);
return ret;
}
int dump_certs_pkeys_bags(BIO *out, const STACK_OF(PKCS12_SAFEBAG) *bags,
const char *pass, int passlen, int options,
char *pempass, const EVP_CIPHER *enc)
{
int i;
for (i = 0; i < sk_PKCS12_SAFEBAG_num(bags); i++) {
if (!dump_certs_pkeys_bag(out,
sk_PKCS12_SAFEBAG_value(bags, i),
pass, passlen, options, pempass, enc))
return 0;
}
return 1;
}
int dump_certs_pkeys_bag(BIO *out, const PKCS12_SAFEBAG *bag,
const char *pass, int passlen, int options,
char *pempass, const EVP_CIPHER *enc)
{
EVP_PKEY *pkey;
PKCS8_PRIV_KEY_INFO *p8;
const PKCS8_PRIV_KEY_INFO *p8c;
X509 *x509;
const STACK_OF(X509_ATTRIBUTE) *attrs;
int ret = 0;
attrs = PKCS12_SAFEBAG_get0_attrs(bag);
switch (PKCS12_SAFEBAG_get_nid(bag)) {
case NID_keyBag:
if (options & INFO)
BIO_printf(bio_err, "Key bag\n");
if (options & NOKEYS)
return 1;
print_attribs(out, attrs, "Bag Attributes");
p8c = PKCS12_SAFEBAG_get0_p8inf(bag);
if ((pkey = EVP_PKCS82PKEY(p8c)) == NULL)
return 0;
print_attribs(out, PKCS8_pkey_get0_attrs(p8c), "Key Attributes");
ret = PEM_write_bio_PrivateKey(out, pkey, enc, NULL, 0, NULL, pempass);
EVP_PKEY_free(pkey);
break;
case NID_pkcs8ShroudedKeyBag:
if (options & INFO) {
const X509_SIG *tp8;
const X509_ALGOR *tp8alg;
BIO_printf(bio_err, "Shrouded Keybag: ");
tp8 = PKCS12_SAFEBAG_get0_pkcs8(bag);
X509_SIG_get0(tp8, &tp8alg, NULL);
alg_print(tp8alg);
}
if (options & NOKEYS)
return 1;
print_attribs(out, attrs, "Bag Attributes");
if ((p8 = PKCS12_decrypt_skey(bag, pass, passlen)) == NULL)
return 0;
if ((pkey = EVP_PKCS82PKEY(p8)) == NULL) {
PKCS8_PRIV_KEY_INFO_free(p8);
return 0;
}
print_attribs(out, PKCS8_pkey_get0_attrs(p8), "Key Attributes");
PKCS8_PRIV_KEY_INFO_free(p8);
ret = PEM_write_bio_PrivateKey(out, pkey, enc, NULL, 0, NULL, pempass);
EVP_PKEY_free(pkey);
break;
case NID_certBag:
if (options & INFO)
BIO_printf(bio_err, "Certificate bag\n");
if (options & NOCERTS)
return 1;
if (PKCS12_SAFEBAG_get0_attr(bag, NID_localKeyID)) {
if (options & CACERTS)
return 1;
} else if (options & CLCERTS)
return 1;
print_attribs(out, attrs, "Bag Attributes");
if (PKCS12_SAFEBAG_get_bag_nid(bag) != NID_x509Certificate)
return 1;
if ((x509 = PKCS12_SAFEBAG_get1_cert(bag)) == NULL)
return 0;
dump_cert_text(out, x509);
ret = PEM_write_bio_X509(out, x509);
X509_free(x509);
break;
case NID_secretBag:
if (options & INFO)
BIO_printf(bio_err, "Secret bag\n");
print_attribs(out, attrs, "Bag Attributes");
BIO_printf(bio_err, "Bag Type: ");
i2a_ASN1_OBJECT(bio_err, PKCS12_SAFEBAG_get0_bag_type(bag));
BIO_printf(bio_err, "\nBag Value: ");
print_attribute(out, PKCS12_SAFEBAG_get0_bag_obj(bag));
return 1;
case NID_safeContentsBag:
if (options & INFO)
BIO_printf(bio_err, "Safe Contents bag\n");
print_attribs(out, attrs, "Bag Attributes");
return dump_certs_pkeys_bags(out, PKCS12_SAFEBAG_get0_safes(bag),
pass, passlen, options, pempass, enc);
default:
BIO_printf(bio_err, "Warning unsupported bag type: ");
i2a_ASN1_OBJECT(bio_err, PKCS12_SAFEBAG_get0_type(bag));
BIO_printf(bio_err, "\n");
return 1;
}
return ret;
}
/* Given a single certificate return a verified chain or NULL if error */
static int get_cert_chain(X509 *cert, X509_STORE *store,
STACK_OF(X509) *untrusted_certs,
STACK_OF(X509) **chain)
{
X509_STORE_CTX *store_ctx = NULL;
STACK_OF(X509) *chn = NULL;
int i = 0;
store_ctx = X509_STORE_CTX_new_ex(app_get0_libctx(), app_get0_propq());
if (store_ctx == NULL) {
i = X509_V_ERR_UNSPECIFIED;
goto end;
}
if (!X509_STORE_CTX_init(store_ctx, store, cert, untrusted_certs)) {
i = X509_V_ERR_UNSPECIFIED;
goto end;
}
if (X509_verify_cert(store_ctx) > 0)
chn = X509_STORE_CTX_get1_chain(store_ctx);
else if ((i = X509_STORE_CTX_get_error(store_ctx)) == 0)
i = X509_V_ERR_UNSPECIFIED;
end:
X509_STORE_CTX_free(store_ctx);
*chain = chn;
return i;
}
static int alg_print(const X509_ALGOR *alg)
{
int pbenid, aparamtype;
const ASN1_OBJECT *aoid;
const void *aparam;
PBEPARAM *pbe = NULL;
X509_ALGOR_get0(&aoid, &aparamtype, &aparam, alg);
pbenid = OBJ_obj2nid(aoid);
BIO_printf(bio_err, "%s", OBJ_nid2ln(pbenid));
/*
* If PBE algorithm is PBES2 decode algorithm parameters
* for additional details.
*/
if (pbenid == NID_pbes2) {
PBE2PARAM *pbe2 = NULL;
int encnid;
if (aparamtype == V_ASN1_SEQUENCE)
pbe2 = ASN1_item_unpack(aparam, ASN1_ITEM_rptr(PBE2PARAM));
if (pbe2 == NULL) {
BIO_puts(bio_err, ", <unsupported parameters>");
goto done;
}
X509_ALGOR_get0(&aoid, &aparamtype, &aparam, pbe2->keyfunc);
pbenid = OBJ_obj2nid(aoid);
X509_ALGOR_get0(&aoid, NULL, NULL, pbe2->encryption);
encnid = OBJ_obj2nid(aoid);
BIO_printf(bio_err, ", %s, %s", OBJ_nid2ln(pbenid),
OBJ_nid2sn(encnid));
/* If KDF is PBKDF2 decode parameters */
if (pbenid == NID_id_pbkdf2) {
PBKDF2PARAM *kdf = NULL;
int prfnid;
if (aparamtype == V_ASN1_SEQUENCE)
kdf = ASN1_item_unpack(aparam, ASN1_ITEM_rptr(PBKDF2PARAM));
if (kdf == NULL) {
BIO_puts(bio_err, ", <unsupported parameters>");
goto done;
}
if (kdf->prf == NULL) {
prfnid = NID_hmacWithSHA1;
} else {
X509_ALGOR_get0(&aoid, NULL, NULL, kdf->prf);
prfnid = OBJ_obj2nid(aoid);
}
BIO_printf(bio_err, ", Iteration %ld, PRF %s",
ASN1_INTEGER_get(kdf->iter), OBJ_nid2sn(prfnid));
PBKDF2PARAM_free(kdf);
#ifndef OPENSSL_NO_SCRYPT
} else if (pbenid == NID_id_scrypt) {
SCRYPT_PARAMS *kdf = NULL;
if (aparamtype == V_ASN1_SEQUENCE)
kdf = ASN1_item_unpack(aparam, ASN1_ITEM_rptr(SCRYPT_PARAMS));
if (kdf == NULL) {
BIO_puts(bio_err, ", <unsupported parameters>");
goto done;
}
BIO_printf(bio_err, ", Salt length: %d, Cost(N): %ld, "
"Block size(r): %ld, Parallelism(p): %ld",
ASN1_STRING_length(kdf->salt),
ASN1_INTEGER_get(kdf->costParameter),
ASN1_INTEGER_get(kdf->blockSize),
ASN1_INTEGER_get(kdf->parallelizationParameter));
SCRYPT_PARAMS_free(kdf);
#endif
}
PBE2PARAM_free(pbe2);
} else {
if (aparamtype == V_ASN1_SEQUENCE)
pbe = ASN1_item_unpack(aparam, ASN1_ITEM_rptr(PBEPARAM));
if (pbe == NULL) {
BIO_puts(bio_err, ", <unsupported parameters>");
goto done;
}
BIO_printf(bio_err, ", Iteration %ld", ASN1_INTEGER_get(pbe->iter));
PBEPARAM_free(pbe);
}
done:
BIO_puts(bio_err, "\n");
return 1;
}
/* Load all certificates from a given file */
int cert_load(BIO *in, STACK_OF(X509) *sk)
{
int ret = 0;
X509 *cert;
while ((cert = PEM_read_bio_X509(in, NULL, NULL, NULL))) {
ret = 1;
if (!sk_X509_push(sk, cert))
return 0;
}
if (ret)
ERR_clear_error();
return ret;
}
/* Generalised x509 attribute value print */
void print_attribute(BIO *out, const ASN1_TYPE *av)
{
char *value;
switch (av->type) {
case V_ASN1_BMPSTRING:
value = OPENSSL_uni2asc(av->value.bmpstring->data,
av->value.bmpstring->length);
BIO_printf(out, "%s\n", value);
OPENSSL_free(value);
break;
case V_ASN1_UTF8STRING:
BIO_printf(out, "%.*s\n", av->value.utf8string->length,
av->value.utf8string->data);
break;
case V_ASN1_OCTET_STRING:
hex_prin(out, av->value.octet_string->data,
av->value.octet_string->length);
BIO_printf(out, "\n");
break;
case V_ASN1_BIT_STRING:
hex_prin(out, av->value.bit_string->data,
av->value.bit_string->length);
BIO_printf(out, "\n");
break;
default:
BIO_printf(out, "<Unsupported tag %d>\n", av->type);
break;
}
}
/* Generalised attribute print: handle PKCS#8 and bag attributes */
int print_attribs(BIO *out, const STACK_OF(X509_ATTRIBUTE) *attrlst,
const char *name)
{
X509_ATTRIBUTE *attr;
ASN1_TYPE *av;
int i, j, attr_nid;
if (!attrlst) {
BIO_printf(out, "%s: <No Attributes>\n", name);
return 1;
}
if (!sk_X509_ATTRIBUTE_num(attrlst)) {
BIO_printf(out, "%s: <Empty Attributes>\n", name);
return 1;
}
BIO_printf(out, "%s\n", name);
for (i = 0; i < sk_X509_ATTRIBUTE_num(attrlst); i++) {
ASN1_OBJECT *attr_obj;
attr = sk_X509_ATTRIBUTE_value(attrlst, i);
attr_obj = X509_ATTRIBUTE_get0_object(attr);
attr_nid = OBJ_obj2nid(attr_obj);
BIO_printf(out, " ");
if (attr_nid == NID_undef) {
i2a_ASN1_OBJECT(out, attr_obj);
BIO_printf(out, ": ");
} else {
BIO_printf(out, "%s: ", OBJ_nid2ln(attr_nid));
}
if (X509_ATTRIBUTE_count(attr)) {
for (j = 0; j < X509_ATTRIBUTE_count(attr); j++)
{
av = X509_ATTRIBUTE_get0_type(attr, j);
print_attribute(out, av);
}
} else {
BIO_printf(out, "<No Values>\n");
}
}
return 1;
}
void hex_prin(BIO *out, unsigned char *buf, int len)
{
int i;
for (i = 0; i < len; i++)
BIO_printf(out, "%02X ", buf[i]);
}
static int set_pbe(int *ppbe, const char *str)
{
if (!str)
return 0;
if (strcmp(str, "NONE") == 0) {
*ppbe = -1;
return 1;
}
*ppbe = OBJ_txt2nid(str);
if (*ppbe == NID_undef) {
BIO_printf(bio_err, "Unknown PBE algorithm %s\n", str);
return 0;
}
return 1;
}
diff --git a/crypto/openssl/apps/req.c b/crypto/openssl/apps/req.c
index c7d4c7822cda..2fc53d4bfcfa 100644
--- a/crypto/openssl/apps/req.c
+++ b/crypto/openssl/apps/req.c
@@ -1,1686 +1,1686 @@
/*
* Copyright 1995-2024 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 <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#include <ctype.h>
#include "apps.h"
#include "progs.h"
#include <openssl/core_names.h>
#include <openssl/bio.h>
#include <openssl/evp.h>
#include <openssl/conf.h>
#include <openssl/err.h>
#include <openssl/asn1.h>
#include <openssl/x509.h>
#include <openssl/x509v3.h>
#include <openssl/objects.h>
#include <openssl/pem.h>
#include <openssl/bn.h>
#include <openssl/lhash.h>
#include <openssl/rsa.h>
#ifndef OPENSSL_NO_DSA
# include <openssl/dsa.h>
#endif
#define BITS "default_bits"
#define KEYFILE "default_keyfile"
#define PROMPT "prompt"
#define DISTINGUISHED_NAME "distinguished_name"
#define ATTRIBUTES "attributes"
#define V3_EXTENSIONS "x509_extensions"
#define REQ_EXTENSIONS "req_extensions"
#define STRING_MASK "string_mask"
#define UTF8_IN "utf8"
#define DEFAULT_KEY_LENGTH 2048
#define MIN_KEY_LENGTH 512
#define DEFAULT_DAYS 30 /* default cert validity period in days */
#define UNSET_DAYS -2 /* -1 may be used for testing expiration checks */
#define EXT_COPY_UNSET -1
static int make_REQ(X509_REQ *req, EVP_PKEY *pkey, X509_NAME *fsubj,
int mutlirdn, int attribs, unsigned long chtype);
static int prompt_info(X509_REQ *req,
STACK_OF(CONF_VALUE) *dn_sk, const char *dn_sect,
STACK_OF(CONF_VALUE) *attr_sk, const char *attr_sect,
int attribs, unsigned long chtype);
static int auto_info(X509_REQ *req, STACK_OF(CONF_VALUE) *sk,
STACK_OF(CONF_VALUE) *attr, int attribs,
unsigned long chtype);
static int add_attribute_object(X509_REQ *req, char *text, const char *def,
char *value, int nid, int n_min, int n_max,
unsigned long chtype);
static int add_DN_object(X509_NAME *n, char *text, const char *def,
char *value, int nid, int n_min, int n_max,
unsigned long chtype, int mval);
static int genpkey_cb(EVP_PKEY_CTX *ctx);
static int build_data(char *text, const char *def, char *value,
int n_min, int n_max, char *buf, const int buf_size,
const char *desc1, const char *desc2);
static int req_check_len(int len, int n_min, int n_max);
static int check_end(const char *str, const char *end);
static int join(char buf[], size_t buf_size, const char *name,
const char *tail, const char *desc);
static EVP_PKEY_CTX *set_keygen_ctx(const char *gstr,
char **pkeytype, long *pkeylen,
ENGINE *keygen_engine);
static const char *section = "req";
static CONF *req_conf = NULL;
static CONF *addext_conf = NULL;
static int batch = 0;
typedef enum OPTION_choice {
OPT_COMMON,
OPT_INFORM, OPT_OUTFORM, OPT_ENGINE, OPT_KEYGEN_ENGINE, OPT_KEY,
OPT_PUBKEY, OPT_NEW, OPT_CONFIG, OPT_KEYFORM, OPT_IN, OPT_OUT,
OPT_KEYOUT, OPT_PASSIN, OPT_PASSOUT, OPT_NEWKEY,
OPT_PKEYOPT, OPT_SIGOPT, OPT_VFYOPT, OPT_BATCH, OPT_NEWHDR, OPT_MODULUS,
OPT_VERIFY, OPT_NOENC, OPT_NODES, OPT_NOOUT, OPT_VERBOSE, OPT_UTF8,
OPT_NAMEOPT, OPT_REQOPT, OPT_SUBJ, OPT_SUBJECT, OPT_TEXT, OPT_X509,
OPT_CA, OPT_CAKEY,
OPT_MULTIVALUE_RDN, OPT_DAYS, OPT_SET_SERIAL,
OPT_COPY_EXTENSIONS, OPT_ADDEXT, OPT_EXTENSIONS,
OPT_REQEXTS, OPT_PRECERT, OPT_MD,
OPT_SECTION,
OPT_R_ENUM, OPT_PROV_ENUM
} OPTION_CHOICE;
const OPTIONS req_options[] = {
OPT_SECTION("General"),
{"help", OPT_HELP, '-', "Display this summary"},
#ifndef OPENSSL_NO_ENGINE
{"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"},
{"keygen_engine", OPT_KEYGEN_ENGINE, 's',
"Specify engine to be used for key generation operations"},
#endif
{"in", OPT_IN, '<', "X.509 request input file (default stdin)"},
{"inform", OPT_INFORM, 'F', "Input format - DER or PEM"},
{"verify", OPT_VERIFY, '-', "Verify self-signature on the request"},
OPT_SECTION("Certificate"),
{"new", OPT_NEW, '-', "New request"},
{"config", OPT_CONFIG, '<', "Request template file"},
{"section", OPT_SECTION, 's', "Config section to use (default \"req\")"},
{"utf8", OPT_UTF8, '-', "Input characters are UTF8 (default ASCII)"},
{"nameopt", OPT_NAMEOPT, 's', "Certificate subject/issuer name printing options"},
{"reqopt", OPT_REQOPT, 's', "Various request text options"},
{"text", OPT_TEXT, '-', "Text form of request"},
{"x509", OPT_X509, '-',
"Output an X.509 certificate structure instead of a cert request"},
{"CA", OPT_CA, '<', "Issuer cert to use for signing a cert, implies -x509"},
{"CAkey", OPT_CAKEY, 's',
"Issuer private key to use with -CA; default is -CA arg"},
{OPT_MORE_STR, 1, 1, "(Required by some CA's)"},
{"subj", OPT_SUBJ, 's', "Set or modify subject of request or cert"},
{"subject", OPT_SUBJECT, '-',
"Print the subject of the output request or cert"},
{"multivalue-rdn", OPT_MULTIVALUE_RDN, '-',
"Deprecated; multi-valued RDNs support is always on."},
{"days", OPT_DAYS, 'p', "Number of days cert is valid for"},
{"set_serial", OPT_SET_SERIAL, 's', "Serial number to use"},
{"copy_extensions", OPT_COPY_EXTENSIONS, 's',
"copy extensions from request when using -x509"},
{"addext", OPT_ADDEXT, 's',
"Additional cert extension key=value pair (may be given more than once)"},
{"extensions", OPT_EXTENSIONS, 's',
"Cert extension section (override value in config file)"},
{"reqexts", OPT_REQEXTS, 's',
"Request extension section (override value in config file)"},
{"precert", OPT_PRECERT, '-',
"Add a poison extension to the generated cert (implies -new)"},
OPT_SECTION("Keys and Signing"),
{"key", OPT_KEY, 's', "Key for signing, and to include unless -in given"},
{"keyform", OPT_KEYFORM, 'f', "Key file format (ENGINE, other values ignored)"},
{"pubkey", OPT_PUBKEY, '-', "Output public key"},
{"keyout", OPT_KEYOUT, '>', "File to write private key to"},
{"passin", OPT_PASSIN, 's', "Private key and certificate password source"},
{"passout", OPT_PASSOUT, 's', "Output file pass phrase source"},
{"newkey", OPT_NEWKEY, 's',
"Generate new key with [<alg>:]<nbits> or <alg>[:<file>] or param:<file>"},
{"pkeyopt", OPT_PKEYOPT, 's', "Public key options as opt:value"},
{"sigopt", OPT_SIGOPT, 's', "Signature parameter in n:v form"},
{"vfyopt", OPT_VFYOPT, 's', "Verification parameter in n:v form"},
{"", OPT_MD, '-', "Any supported digest"},
OPT_SECTION("Output"),
{"out", OPT_OUT, '>', "Output file"},
{"outform", OPT_OUTFORM, 'F', "Output format - DER or PEM"},
{"batch", OPT_BATCH, '-',
"Do not ask anything during request generation"},
{"verbose", OPT_VERBOSE, '-', "Verbose output"},
{"noenc", OPT_NOENC, '-', "Don't encrypt private keys"},
{"nodes", OPT_NODES, '-', "Don't encrypt private keys; deprecated"},
{"noout", OPT_NOOUT, '-', "Do not output REQ"},
{"newhdr", OPT_NEWHDR, '-', "Output \"NEW\" in the header lines"},
{"modulus", OPT_MODULUS, '-', "RSA modulus"},
OPT_R_OPTIONS,
OPT_PROV_OPTIONS,
{NULL}
};
/*
* An LHASH of strings, where each string is an extension name.
*/
static unsigned long ext_name_hash(const OPENSSL_STRING *a)
{
return OPENSSL_LH_strhash((const char *)a);
}
static int ext_name_cmp(const OPENSSL_STRING *a, const OPENSSL_STRING *b)
{
return strcmp((const char *)a, (const char *)b);
}
static void exts_cleanup(OPENSSL_STRING *x)
{
OPENSSL_free((char *)x);
}
/*
* Is the |kv| key already duplicated? This is remarkably tricky to get right.
* Return 0 if unique, -1 on runtime error; 1 if found or a syntax error.
*/
static int duplicated(LHASH_OF(OPENSSL_STRING) *addexts, char *kv)
{
char *p;
size_t off;
/* Check syntax. */
/* Skip leading whitespace, make a copy. */
while (*kv && isspace(_UC(*kv)))
if (*++kv == '\0')
return 1;
if ((p = strchr(kv, '=')) == NULL)
return 1;
off = p - kv;
if ((kv = OPENSSL_strdup(kv)) == NULL)
return -1;
/* Skip trailing space before the equal sign. */
for (p = kv + off; p > kv; --p)
if (!isspace(_UC(p[-1])))
break;
if (p == kv) {
OPENSSL_free(kv);
return 1;
}
*p = '\0';
/* Finally have a clean "key"; see if it's there [by attempt to add it]. */
p = (char *)lh_OPENSSL_STRING_insert(addexts, (OPENSSL_STRING *)kv);
if (p != NULL) {
OPENSSL_free(p);
return 1;
} else if (lh_OPENSSL_STRING_error(addexts)) {
OPENSSL_free(kv);
return -1;
}
return 0;
}
int req_main(int argc, char **argv)
{
ASN1_INTEGER *serial = NULL;
BIO *out = NULL;
ENGINE *e = NULL, *gen_eng = NULL;
EVP_PKEY *pkey = NULL, *CAkey = NULL;
EVP_PKEY_CTX *genctx = NULL;
STACK_OF(OPENSSL_STRING) *pkeyopts = NULL, *sigopts = NULL, *vfyopts = NULL;
LHASH_OF(OPENSSL_STRING) *addexts = NULL;
X509 *new_x509 = NULL, *CAcert = NULL;
X509_REQ *req = NULL;
EVP_CIPHER *cipher = NULL;
EVP_MD *md = NULL;
int ext_copy = EXT_COPY_UNSET;
BIO *addext_bio = NULL;
char *extensions = NULL;
const char *infile = NULL, *CAfile = NULL, *CAkeyfile = NULL;
char *outfile = NULL, *keyfile = NULL, *digest = NULL;
char *keyalgstr = NULL, *p, *prog, *passargin = NULL, *passargout = NULL;
char *passin = NULL, *passout = NULL;
char *nofree_passin = NULL, *nofree_passout = NULL;
char *req_exts = NULL, *subj = NULL;
X509_NAME *fsubj = NULL;
char *template = default_config_file, *keyout = NULL;
const char *keyalg = NULL;
OPTION_CHOICE o;
int days = UNSET_DAYS;
int ret = 1, gen_x509 = 0, i = 0, newreq = 0, verbose = 0;
int informat = FORMAT_UNDEF, outformat = FORMAT_PEM, keyform = FORMAT_UNDEF;
int modulus = 0, multirdn = 1, verify = 0, noout = 0, text = 0;
int noenc = 0, newhdr = 0, subject = 0, pubkey = 0, precert = 0;
long newkey_len = -1;
unsigned long chtype = MBSTRING_ASC, reqflag = 0;
#ifndef OPENSSL_NO_DES
cipher = (EVP_CIPHER *)EVP_des_ede3_cbc();
#endif
prog = opt_init(argc, argv, req_options);
while ((o = opt_next()) != OPT_EOF) {
switch (o) {
case OPT_EOF:
case OPT_ERR:
opthelp:
BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
goto end;
case OPT_HELP:
opt_help(req_options);
ret = 0;
goto end;
case OPT_INFORM:
if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &informat))
goto opthelp;
break;
case OPT_OUTFORM:
if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &outformat))
goto opthelp;
break;
case OPT_ENGINE:
e = setup_engine(opt_arg(), 0);
break;
case OPT_KEYGEN_ENGINE:
#ifndef OPENSSL_NO_ENGINE
gen_eng = setup_engine(opt_arg(), 0);
if (gen_eng == NULL) {
BIO_printf(bio_err, "Can't find keygen engine %s\n", *argv);
goto opthelp;
}
#endif
break;
case OPT_KEY:
keyfile = opt_arg();
break;
case OPT_PUBKEY:
pubkey = 1;
break;
case OPT_NEW:
newreq = 1;
break;
case OPT_CONFIG:
template = opt_arg();
break;
case OPT_SECTION:
section = opt_arg();
break;
case OPT_KEYFORM:
if (!opt_format(opt_arg(), OPT_FMT_ANY, &keyform))
goto opthelp;
break;
case OPT_IN:
infile = opt_arg();
break;
case OPT_OUT:
outfile = opt_arg();
break;
case OPT_KEYOUT:
keyout = opt_arg();
break;
case OPT_PASSIN:
passargin = opt_arg();
break;
case OPT_PASSOUT:
passargout = opt_arg();
break;
case OPT_R_CASES:
if (!opt_rand(o))
goto end;
break;
case OPT_PROV_CASES:
if (!opt_provider(o))
goto end;
break;
case OPT_NEWKEY:
keyalg = opt_arg();
newreq = 1;
break;
case OPT_PKEYOPT:
if (pkeyopts == NULL)
pkeyopts = sk_OPENSSL_STRING_new_null();
if (pkeyopts == NULL
|| !sk_OPENSSL_STRING_push(pkeyopts, opt_arg()))
goto opthelp;
break;
case OPT_SIGOPT:
if (!sigopts)
sigopts = sk_OPENSSL_STRING_new_null();
if (!sigopts || !sk_OPENSSL_STRING_push(sigopts, opt_arg()))
goto opthelp;
break;
case OPT_VFYOPT:
if (!vfyopts)
vfyopts = sk_OPENSSL_STRING_new_null();
if (!vfyopts || !sk_OPENSSL_STRING_push(vfyopts, opt_arg()))
goto opthelp;
break;
case OPT_BATCH:
batch = 1;
break;
case OPT_NEWHDR:
newhdr = 1;
break;
case OPT_MODULUS:
modulus = 1;
break;
case OPT_VERIFY:
verify = 1;
break;
case OPT_NODES:
case OPT_NOENC:
noenc = 1;
break;
case OPT_NOOUT:
noout = 1;
break;
case OPT_VERBOSE:
verbose = 1;
break;
case OPT_UTF8:
chtype = MBSTRING_UTF8;
break;
case OPT_NAMEOPT:
if (!set_nameopt(opt_arg()))
goto opthelp;
break;
case OPT_REQOPT:
if (!set_cert_ex(&reqflag, opt_arg()))
goto opthelp;
break;
case OPT_TEXT:
text = 1;
break;
case OPT_X509:
gen_x509 = 1;
break;
case OPT_CA:
CAfile = opt_arg();
gen_x509 = 1;
break;
case OPT_CAKEY:
CAkeyfile = opt_arg();
break;
case OPT_DAYS:
days = atoi(opt_arg());
if (days < -1) {
BIO_printf(bio_err, "%s: -days parameter arg must be >= -1\n",
prog);
goto end;
}
break;
case OPT_SET_SERIAL:
if (serial != NULL) {
BIO_printf(bio_err, "Serial number supplied twice\n");
goto opthelp;
}
serial = s2i_ASN1_INTEGER(NULL, opt_arg());
if (serial == NULL)
goto opthelp;
break;
case OPT_SUBJECT:
subject = 1;
break;
case OPT_SUBJ:
subj = opt_arg();
break;
case OPT_MULTIVALUE_RDN:
/* obsolete */
break;
case OPT_COPY_EXTENSIONS:
if (!set_ext_copy(&ext_copy, opt_arg())) {
BIO_printf(bio_err, "Invalid extension copy option: \"%s\"\n",
opt_arg());
goto end;
}
break;
case OPT_ADDEXT:
p = opt_arg();
if (addexts == NULL) {
addexts = lh_OPENSSL_STRING_new(ext_name_hash, ext_name_cmp);
addext_bio = BIO_new(BIO_s_mem());
if (addexts == NULL || addext_bio == NULL)
goto end;
}
i = duplicated(addexts, p);
if (i == 1) {
BIO_printf(bio_err, "Duplicate extension: %s\n", p);
goto opthelp;
}
if (i < 0 || BIO_printf(addext_bio, "%s\n", p) < 0)
goto end;
break;
case OPT_EXTENSIONS:
extensions = opt_arg();
break;
case OPT_REQEXTS:
req_exts = opt_arg();
break;
case OPT_PRECERT:
newreq = precert = 1;
break;
case OPT_MD:
digest = opt_unknown();
break;
}
}
/* No extra arguments. */
argc = opt_num_rest();
if (argc != 0)
goto opthelp;
if (!app_RAND_load())
goto end;
if (!gen_x509) {
if (days != UNSET_DAYS)
BIO_printf(bio_err, "Ignoring -days without -x509; not generating a certificate\n");
if (ext_copy == EXT_COPY_NONE)
BIO_printf(bio_err, "Ignoring -copy_extensions 'none' when -x509 is not given\n");
}
if (gen_x509 && infile == NULL)
newreq = 1;
if (!app_passwd(passargin, passargout, &passin, &passout)) {
BIO_printf(bio_err, "Error getting passwords\n");
goto end;
}
if ((req_conf = app_load_config_verbose(template, verbose)) == NULL)
goto end;
if (addext_bio != NULL) {
if (verbose)
BIO_printf(bio_err,
"Using additional configuration from -addext options\n");
if ((addext_conf = app_load_config_bio(addext_bio, NULL)) == NULL)
goto end;
}
if (template != default_config_file && !app_load_modules(req_conf))
goto end;
if (req_conf != NULL) {
p = NCONF_get_string(req_conf, NULL, "oid_file");
if (p == NULL)
ERR_clear_error();
if (p != NULL) {
BIO *oid_bio = BIO_new_file(p, "r");
if (oid_bio == NULL) {
if (verbose)
BIO_printf(bio_err,
"Problems opening '%s' for extra OIDs\n", p);
} else {
OBJ_create_objects(oid_bio);
BIO_free(oid_bio);
}
}
}
if (!add_oid_section(req_conf))
goto end;
/* Check that any specified digest is fetchable */
if (digest != NULL) {
if (!opt_md(digest, &md)) {
ERR_clear_error();
goto opthelp;
}
EVP_MD_free(md);
} else {
/* No digest specified, default to configuration */
p = NCONF_get_string(req_conf, section, "default_md");
if (p == NULL)
ERR_clear_error();
else
digest = p;
}
if (extensions == NULL) {
extensions = NCONF_get_string(req_conf, section, V3_EXTENSIONS);
if (extensions == NULL)
ERR_clear_error();
}
if (extensions != NULL) {
/* Check syntax of file */
X509V3_CTX ctx;
X509V3_set_ctx_test(&ctx);
X509V3_set_nconf(&ctx, req_conf);
if (!X509V3_EXT_add_nconf(req_conf, &ctx, extensions, NULL)) {
BIO_printf(bio_err,
"Error checking x509 extension section %s\n",
extensions);
goto end;
}
}
if (addext_conf != NULL) {
/* Check syntax of command line extensions */
X509V3_CTX ctx;
X509V3_set_ctx_test(&ctx);
- X509V3_set_nconf(&ctx, addext_conf);
+ X509V3_set_nconf(&ctx, req_conf);
if (!X509V3_EXT_add_nconf(addext_conf, &ctx, "default", NULL)) {
BIO_printf(bio_err, "Error checking extensions defined using -addext\n");
goto end;
}
}
if (passin == NULL) {
passin = nofree_passin =
NCONF_get_string(req_conf, section, "input_password");
if (passin == NULL)
ERR_clear_error();
}
if (passout == NULL) {
passout = nofree_passout =
NCONF_get_string(req_conf, section, "output_password");
if (passout == NULL)
ERR_clear_error();
}
p = NCONF_get_string(req_conf, section, STRING_MASK);
if (p == NULL)
ERR_clear_error();
if (p != NULL && !ASN1_STRING_set_default_mask_asc(p)) {
BIO_printf(bio_err, "Invalid global string mask setting %s\n", p);
goto end;
}
if (chtype != MBSTRING_UTF8) {
p = NCONF_get_string(req_conf, section, UTF8_IN);
if (p == NULL)
ERR_clear_error();
else if (strcmp(p, "yes") == 0)
chtype = MBSTRING_UTF8;
}
if (req_exts == NULL) {
req_exts = NCONF_get_string(req_conf, section, REQ_EXTENSIONS);
if (req_exts == NULL)
ERR_clear_error();
}
if (req_exts != NULL) {
/* Check syntax of file */
X509V3_CTX ctx;
X509V3_set_ctx_test(&ctx);
X509V3_set_nconf(&ctx, req_conf);
if (!X509V3_EXT_add_nconf(req_conf, &ctx, req_exts, NULL)) {
BIO_printf(bio_err,
"Error checking request extension section %s\n",
req_exts);
goto end;
}
}
if (keyfile != NULL) {
pkey = load_key(keyfile, keyform, 0, passin, e, "private key");
if (pkey == NULL)
goto end;
app_RAND_load_conf(req_conf, section);
}
if (newreq && pkey == NULL) {
app_RAND_load_conf(req_conf, section);
if (!NCONF_get_number(req_conf, section, BITS, &newkey_len)) {
ERR_clear_error();
newkey_len = DEFAULT_KEY_LENGTH;
}
genctx = set_keygen_ctx(keyalg, &keyalgstr, &newkey_len, gen_eng);
if (genctx == NULL)
goto end;
if (newkey_len < MIN_KEY_LENGTH
&& (EVP_PKEY_CTX_is_a(genctx, "RSA")
|| EVP_PKEY_CTX_is_a(genctx, "RSA-PSS")
|| EVP_PKEY_CTX_is_a(genctx, "DSA"))) {
BIO_printf(bio_err, "Private key length too short, needs to be at least %d bits, not %ld.\n",
MIN_KEY_LENGTH, newkey_len);
goto end;
}
if (newkey_len > OPENSSL_RSA_MAX_MODULUS_BITS
&& (EVP_PKEY_CTX_is_a(genctx, "RSA")
|| EVP_PKEY_CTX_is_a(genctx, "RSA-PSS")))
BIO_printf(bio_err,
"Warning: It is not recommended to use more than %d bit for RSA keys.\n"
" Your key size is %ld! Larger key size may behave not as expected.\n",
OPENSSL_RSA_MAX_MODULUS_BITS, newkey_len);
#ifndef OPENSSL_NO_DSA
if (EVP_PKEY_CTX_is_a(genctx, "DSA")
&& newkey_len > OPENSSL_DSA_MAX_MODULUS_BITS)
BIO_printf(bio_err,
"Warning: It is not recommended to use more than %d bit for DSA keys.\n"
" Your key size is %ld! Larger key size may behave not as expected.\n",
OPENSSL_DSA_MAX_MODULUS_BITS, newkey_len);
#endif
if (pkeyopts != NULL) {
char *genopt;
for (i = 0; i < sk_OPENSSL_STRING_num(pkeyopts); i++) {
genopt = sk_OPENSSL_STRING_value(pkeyopts, i);
if (pkey_ctrl_string(genctx, genopt) <= 0) {
BIO_printf(bio_err, "Key parameter error \"%s\"\n", genopt);
goto end;
}
}
}
EVP_PKEY_CTX_set_cb(genctx, genpkey_cb);
EVP_PKEY_CTX_set_app_data(genctx, bio_err);
pkey = app_keygen(genctx, keyalgstr, newkey_len, verbose);
if (pkey == NULL)
goto end;
EVP_PKEY_CTX_free(genctx);
genctx = NULL;
}
if (keyout == NULL && keyfile == NULL) {
keyout = NCONF_get_string(req_conf, section, KEYFILE);
if (keyout == NULL)
ERR_clear_error();
}
if (pkey != NULL && (keyfile == NULL || keyout != NULL)) {
if (verbose) {
BIO_printf(bio_err, "Writing private key to ");
if (keyout == NULL)
BIO_printf(bio_err, "stdout\n");
else
BIO_printf(bio_err, "'%s'\n", keyout);
}
out = bio_open_owner(keyout, outformat, newreq);
if (out == NULL)
goto end;
p = NCONF_get_string(req_conf, section, "encrypt_rsa_key");
if (p == NULL) {
ERR_clear_error();
p = NCONF_get_string(req_conf, section, "encrypt_key");
if (p == NULL)
ERR_clear_error();
}
if ((p != NULL) && (strcmp(p, "no") == 0))
cipher = NULL;
if (noenc)
cipher = NULL;
i = 0;
loop:
if (!PEM_write_bio_PrivateKey(out, pkey, cipher,
NULL, 0, NULL, passout)) {
if ((ERR_GET_REASON(ERR_peek_error()) ==
PEM_R_PROBLEMS_GETTING_PASSWORD) && (i < 3)) {
ERR_clear_error();
i++;
goto loop;
}
goto end;
}
BIO_free_all(out);
out = NULL;
BIO_printf(bio_err, "-----\n");
}
/*
* subj is expected to be in the format /type0=value0/type1=value1/type2=...
* where characters may be escaped by \
*/
if (subj != NULL
&& (fsubj = parse_name(subj, chtype, multirdn, "subject")) == NULL)
goto end;
if (!newreq) {
req = load_csr(infile /* if NULL, reads from stdin */,
informat, "X509 request");
if (req == NULL)
goto end;
}
if (CAkeyfile == NULL)
CAkeyfile = CAfile;
if (CAkeyfile != NULL) {
if (CAfile == NULL) {
BIO_printf(bio_err,
"Warning: Ignoring -CAkey option since no -CA option is given\n");
} else {
if ((CAkey = load_key(CAkeyfile, FORMAT_UNDEF,
0, passin, e,
CAkeyfile != CAfile
? "issuer private key from -CAkey arg"
: "issuer private key from -CA arg")) == NULL)
goto end;
}
}
if (CAfile != NULL) {
if ((CAcert = load_cert_pass(CAfile, FORMAT_UNDEF, 1, passin,
"issuer cert from -CA arg")) == NULL)
goto end;
if (!X509_check_private_key(CAcert, CAkey)) {
BIO_printf(bio_err,
"Issuer CA certificate and key do not match\n");
goto end;
}
}
if (newreq || gen_x509) {
if (CAcert == NULL && pkey == NULL) {
BIO_printf(bio_err, "Must provide a signature key using -key or"
" provide -CA / -CAkey\n");
goto end;
}
if (req == NULL) {
req = X509_REQ_new_ex(app_get0_libctx(), app_get0_propq());
if (req == NULL) {
goto end;
}
if (!make_REQ(req, pkey, fsubj, multirdn, !gen_x509, chtype)){
BIO_printf(bio_err, "Error making certificate request\n");
goto end;
}
/* Note that -x509 can take over -key and -subj option values. */
}
if (gen_x509) {
EVP_PKEY *pub_key = X509_REQ_get0_pubkey(req);
EVP_PKEY *issuer_key = CAcert != NULL ? CAkey : pkey;
X509V3_CTX ext_ctx;
X509_NAME *issuer = CAcert != NULL ? X509_get_subject_name(CAcert) :
X509_REQ_get_subject_name(req);
X509_NAME *n_subj = fsubj != NULL ? fsubj :
X509_REQ_get_subject_name(req);
if ((new_x509 = X509_new_ex(app_get0_libctx(),
app_get0_propq())) == NULL)
goto end;
if (serial != NULL) {
if (!X509_set_serialNumber(new_x509, serial))
goto end;
} else {
if (!rand_serial(NULL, X509_get_serialNumber(new_x509)))
goto end;
}
if (!X509_set_issuer_name(new_x509, issuer))
goto end;
if (days == UNSET_DAYS) {
days = DEFAULT_DAYS;
}
if (!set_cert_times(new_x509, NULL, NULL, days))
goto end;
if (!X509_set_subject_name(new_x509, n_subj))
goto end;
if (!pub_key || !X509_set_pubkey(new_x509, pub_key))
goto end;
if (ext_copy == EXT_COPY_UNSET) {
if (infile != NULL)
BIO_printf(bio_err, "Warning: No -copy_extensions given; ignoring any extensions in the request\n");
} else if (!copy_extensions(new_x509, req, ext_copy)) {
BIO_printf(bio_err, "Error copying extensions from request\n");
goto end;
}
/* Set up V3 context struct */
X509V3_set_ctx(&ext_ctx, CAcert != NULL ? CAcert : new_x509,
new_x509, NULL, NULL, X509V3_CTX_REPLACE);
/* prepare fallback for AKID, but only if issuer cert == new_x509 */
if (CAcert == NULL) {
if (!X509V3_set_issuer_pkey(&ext_ctx, issuer_key))
goto end;
ERR_set_mark();
if (!X509_check_private_key(new_x509, issuer_key))
BIO_printf(bio_err,
"Warning: Signature key and public key of cert do not match\n");
ERR_pop_to_mark();
}
X509V3_set_nconf(&ext_ctx, req_conf);
/* Add extensions */
if (extensions != NULL
&& !X509V3_EXT_add_nconf(req_conf, &ext_ctx, extensions,
new_x509)) {
BIO_printf(bio_err, "Error adding x509 extensions from section %s\n",
extensions);
goto end;
}
if (addext_conf != NULL
&& !X509V3_EXT_add_nconf(addext_conf, &ext_ctx, "default",
new_x509)) {
BIO_printf(bio_err, "Error adding extensions defined via -addext\n");
goto end;
}
/* If a pre-cert was requested, we need to add a poison extension */
if (precert) {
if (X509_add1_ext_i2d(new_x509, NID_ct_precert_poison,
NULL, 1, 0) != 1) {
BIO_printf(bio_err, "Error adding poison extension\n");
goto end;
}
}
i = do_X509_sign(new_x509, issuer_key, digest, sigopts, &ext_ctx);
if (!i)
goto end;
} else {
X509V3_CTX ext_ctx;
/* Set up V3 context struct */
X509V3_set_ctx(&ext_ctx, NULL, NULL, req, NULL, 0);
X509V3_set_nconf(&ext_ctx, req_conf);
/* Add extensions */
if (req_exts != NULL
&& !X509V3_EXT_REQ_add_nconf(req_conf, &ext_ctx,
req_exts, req)) {
BIO_printf(bio_err, "Error adding request extensions from section %s\n",
req_exts);
goto end;
}
if (addext_conf != NULL
&& !X509V3_EXT_REQ_add_nconf(addext_conf, &ext_ctx, "default",
req)) {
BIO_printf(bio_err, "Error adding extensions defined via -addext\n");
goto end;
}
i = do_X509_REQ_sign(req, pkey, digest, sigopts);
if (!i)
goto end;
}
}
if (subj != NULL && !newreq && !gen_x509) {
if (verbose) {
BIO_printf(out, "Modifying subject of certificate request\n");
print_name(out, "Old subject=", X509_REQ_get_subject_name(req));
}
if (!X509_REQ_set_subject_name(req, fsubj)) {
BIO_printf(bio_err, "Error modifying subject of certificate request\n");
goto end;
}
if (verbose) {
print_name(out, "New subject=", X509_REQ_get_subject_name(req));
}
}
if (verify) {
EVP_PKEY *tpubkey = pkey;
if (tpubkey == NULL) {
tpubkey = X509_REQ_get0_pubkey(req);
if (tpubkey == NULL)
goto end;
}
i = do_X509_REQ_verify(req, tpubkey, vfyopts);
if (i < 0)
goto end;
if (i == 0)
BIO_printf(bio_err, "Certificate request self-signature verify failure\n");
else /* i > 0 */
BIO_printf(bio_err, "Certificate request self-signature verify OK\n");
}
if (noout && !text && !modulus && !subject && !pubkey) {
ret = 0;
goto end;
}
out = bio_open_default(outfile,
keyout != NULL && outfile != NULL &&
strcmp(keyout, outfile) == 0 ? 'a' : 'w',
outformat);
if (out == NULL)
goto end;
if (pubkey) {
EVP_PKEY *tpubkey = X509_REQ_get0_pubkey(req);
if (tpubkey == NULL) {
BIO_printf(bio_err, "Error getting public key\n");
goto end;
}
PEM_write_bio_PUBKEY(out, tpubkey);
}
if (text) {
if (gen_x509)
ret = X509_print_ex(out, new_x509, get_nameopt(), reqflag);
else
ret = X509_REQ_print_ex(out, req, get_nameopt(), reqflag);
if (ret == 0) {
if (gen_x509)
BIO_printf(bio_err, "Error printing certificate\n");
else
BIO_printf(bio_err, "Error printing certificate request\n");
goto end;
}
}
if (subject) {
print_name(out, "subject=", gen_x509
? X509_get_subject_name(new_x509)
: X509_REQ_get_subject_name(req));
}
if (modulus) {
EVP_PKEY *tpubkey;
if (gen_x509)
tpubkey = X509_get0_pubkey(new_x509);
else
tpubkey = X509_REQ_get0_pubkey(req);
if (tpubkey == NULL) {
BIO_puts(bio_err, "Modulus is unavailable\n");
goto end;
}
BIO_puts(out, "Modulus=");
if (EVP_PKEY_is_a(tpubkey, "RSA") || EVP_PKEY_is_a(tpubkey, "RSA-PSS")) {
BIGNUM *n = NULL;
if (!EVP_PKEY_get_bn_param(tpubkey, "n", &n))
goto end;
BN_print(out, n);
BN_free(n);
} else {
BIO_puts(out, "Wrong Algorithm type");
}
BIO_puts(out, "\n");
}
if (!noout && !gen_x509) {
if (outformat == FORMAT_ASN1)
i = i2d_X509_REQ_bio(out, req);
else if (newhdr)
i = PEM_write_bio_X509_REQ_NEW(out, req);
else
i = PEM_write_bio_X509_REQ(out, req);
if (!i) {
BIO_printf(bio_err, "Unable to write certificate request\n");
goto end;
}
}
if (!noout && gen_x509 && new_x509 != NULL) {
if (outformat == FORMAT_ASN1)
i = i2d_X509_bio(out, new_x509);
else
i = PEM_write_bio_X509(out, new_x509);
if (!i) {
BIO_printf(bio_err, "Unable to write X509 certificate\n");
goto end;
}
}
ret = 0;
end:
if (ret) {
ERR_print_errors(bio_err);
}
NCONF_free(req_conf);
NCONF_free(addext_conf);
BIO_free(addext_bio);
BIO_free_all(out);
EVP_PKEY_free(pkey);
EVP_PKEY_CTX_free(genctx);
sk_OPENSSL_STRING_free(pkeyopts);
sk_OPENSSL_STRING_free(sigopts);
sk_OPENSSL_STRING_free(vfyopts);
lh_OPENSSL_STRING_doall(addexts, exts_cleanup);
lh_OPENSSL_STRING_free(addexts);
#ifndef OPENSSL_NO_ENGINE
release_engine(gen_eng);
#endif
OPENSSL_free(keyalgstr);
X509_REQ_free(req);
X509_NAME_free(fsubj);
X509_free(new_x509);
X509_free(CAcert);
EVP_PKEY_free(CAkey);
ASN1_INTEGER_free(serial);
release_engine(e);
if (passin != nofree_passin)
OPENSSL_free(passin);
if (passout != nofree_passout)
OPENSSL_free(passout);
return ret;
}
static int make_REQ(X509_REQ *req, EVP_PKEY *pkey, X509_NAME *fsubj,
int multirdn, int attribs, unsigned long chtype)
{
int ret = 0, i;
char no_prompt = 0;
STACK_OF(CONF_VALUE) *dn_sk = NULL, *attr_sk = NULL;
char *tmp, *dn_sect, *attr_sect;
tmp = NCONF_get_string(req_conf, section, PROMPT);
if (tmp == NULL)
ERR_clear_error();
if ((tmp != NULL) && strcmp(tmp, "no") == 0)
no_prompt = 1;
dn_sect = NCONF_get_string(req_conf, section, DISTINGUISHED_NAME);
if (dn_sect == NULL) {
ERR_clear_error();
} else {
dn_sk = NCONF_get_section(req_conf, dn_sect);
if (dn_sk == NULL) {
BIO_printf(bio_err, "Unable to get '%s' section\n", dn_sect);
goto err;
}
}
attr_sect = NCONF_get_string(req_conf, section, ATTRIBUTES);
if (attr_sect == NULL) {
ERR_clear_error();
} else {
attr_sk = NCONF_get_section(req_conf, attr_sect);
if (attr_sk == NULL) {
BIO_printf(bio_err, "Unable to get '%s' section\n", attr_sect);
goto err;
}
}
/* so far there is only version 1 */
if (!X509_REQ_set_version(req, X509_REQ_VERSION_1))
goto err;
if (fsubj != NULL)
i = X509_REQ_set_subject_name(req, fsubj);
else if (no_prompt)
i = auto_info(req, dn_sk, attr_sk, attribs, chtype);
else
i = prompt_info(req, dn_sk, dn_sect, attr_sk, attr_sect, attribs,
chtype);
if (!i)
goto err;
if (!X509_REQ_set_pubkey(req, pkey))
goto err;
ret = 1;
err:
return ret;
}
static int prompt_info(X509_REQ *req,
STACK_OF(CONF_VALUE) *dn_sk, const char *dn_sect,
STACK_OF(CONF_VALUE) *attr_sk, const char *attr_sect,
int attribs, unsigned long chtype)
{
int i;
char *p, *q;
char buf[100];
int nid, mval;
long n_min, n_max;
char *type, *value;
const char *def;
CONF_VALUE *v;
X509_NAME *subj = X509_REQ_get_subject_name(req);
if (!batch) {
BIO_printf(bio_err,
"You are about to be asked to enter information that will be incorporated\n");
BIO_printf(bio_err, "into your certificate request.\n");
BIO_printf(bio_err,
"What you are about to enter is what is called a Distinguished Name or a DN.\n");
BIO_printf(bio_err,
"There are quite a few fields but you can leave some blank\n");
BIO_printf(bio_err,
"For some fields there will be a default value,\n");
BIO_printf(bio_err,
"If you enter '.', the field will be left blank.\n");
BIO_printf(bio_err, "-----\n");
}
if (sk_CONF_VALUE_num(dn_sk)) {
i = -1;
start:
for (;;) {
i++;
if (sk_CONF_VALUE_num(dn_sk) <= i)
break;
v = sk_CONF_VALUE_value(dn_sk, i);
p = q = NULL;
type = v->name;
if (!check_end(type, "_min") || !check_end(type, "_max") ||
!check_end(type, "_default") || !check_end(type, "_value"))
continue;
/*
* Skip past any leading X. X: X, etc to allow for multiple
* instances
*/
for (p = v->name; *p; p++)
if ((*p == ':') || (*p == ',') || (*p == '.')) {
p++;
if (*p)
type = p;
break;
}
if (*type == '+') {
mval = -1;
type++;
} else {
mval = 0;
}
/* If OBJ not recognised ignore it */
if ((nid = OBJ_txt2nid(type)) == NID_undef)
goto start;
if (!join(buf, sizeof(buf), v->name, "_default", "Name"))
return 0;
if ((def = NCONF_get_string(req_conf, dn_sect, buf)) == NULL) {
ERR_clear_error();
def = "";
}
if (!join(buf, sizeof(buf), v->name, "_value", "Name"))
return 0;
if ((value = NCONF_get_string(req_conf, dn_sect, buf)) == NULL) {
ERR_clear_error();
value = NULL;
}
if (!join(buf, sizeof(buf), v->name, "_min", "Name"))
return 0;
if (!NCONF_get_number(req_conf, dn_sect, buf, &n_min)) {
ERR_clear_error();
n_min = -1;
}
if (!join(buf, sizeof(buf), v->name, "_max", "Name"))
return 0;
if (!NCONF_get_number(req_conf, dn_sect, buf, &n_max)) {
ERR_clear_error();
n_max = -1;
}
if (!add_DN_object(subj, v->value, def, value, nid,
n_min, n_max, chtype, mval))
return 0;
}
if (X509_NAME_entry_count(subj) == 0) {
BIO_printf(bio_err, "Error: No objects specified in config file\n");
return 0;
}
if (attribs) {
if ((attr_sk != NULL) && (sk_CONF_VALUE_num(attr_sk) > 0)
&& (!batch)) {
BIO_printf(bio_err,
"\nPlease enter the following 'extra' attributes\n");
BIO_printf(bio_err,
"to be sent with your certificate request\n");
}
i = -1;
start2:
for (;;) {
i++;
if ((attr_sk == NULL) || (sk_CONF_VALUE_num(attr_sk) <= i))
break;
v = sk_CONF_VALUE_value(attr_sk, i);
type = v->name;
if ((nid = OBJ_txt2nid(type)) == NID_undef)
goto start2;
if (!join(buf, sizeof(buf), type, "_default", "Name"))
return 0;
if ((def = NCONF_get_string(req_conf, attr_sect, buf))
== NULL) {
ERR_clear_error();
def = "";
}
if (!join(buf, sizeof(buf), type, "_value", "Name"))
return 0;
if ((value = NCONF_get_string(req_conf, attr_sect, buf))
== NULL) {
ERR_clear_error();
value = NULL;
}
if (!join(buf, sizeof(buf), type, "_min", "Name"))
return 0;
if (!NCONF_get_number(req_conf, attr_sect, buf, &n_min)) {
ERR_clear_error();
n_min = -1;
}
if (!join(buf, sizeof(buf), type, "_max", "Name"))
return 0;
if (!NCONF_get_number(req_conf, attr_sect, buf, &n_max)) {
ERR_clear_error();
n_max = -1;
}
if (!add_attribute_object(req,
v->value, def, value, nid, n_min,
n_max, chtype))
return 0;
}
}
} else {
BIO_printf(bio_err, "No template, please set one up.\n");
return 0;
}
return 1;
}
static int auto_info(X509_REQ *req, STACK_OF(CONF_VALUE) *dn_sk,
STACK_OF(CONF_VALUE) *attr_sk, int attribs,
unsigned long chtype)
{
int i, spec_char, plus_char;
char *p, *q;
char *type;
CONF_VALUE *v;
X509_NAME *subj;
subj = X509_REQ_get_subject_name(req);
for (i = 0; i < sk_CONF_VALUE_num(dn_sk); i++) {
int mval;
v = sk_CONF_VALUE_value(dn_sk, i);
p = q = NULL;
type = v->name;
/*
* Skip past any leading X. X: X, etc to allow for multiple instances
*/
for (p = v->name; *p; p++) {
#ifndef CHARSET_EBCDIC
spec_char = (*p == ':' || *p == ',' || *p == '.');
#else
spec_char = (*p == os_toascii[':'] || *p == os_toascii[',']
|| *p == os_toascii['.']);
#endif
if (spec_char) {
p++;
if (*p)
type = p;
break;
}
}
#ifndef CHARSET_EBCDIC
plus_char = (*type == '+');
#else
plus_char = (*type == os_toascii['+']);
#endif
if (plus_char) {
type++;
mval = -1;
} else {
mval = 0;
}
if (!X509_NAME_add_entry_by_txt(subj, type, chtype,
(unsigned char *)v->value, -1, -1,
mval))
return 0;
}
if (!X509_NAME_entry_count(subj)) {
BIO_printf(bio_err, "Error: No objects specified in config file\n");
return 0;
}
if (attribs) {
for (i = 0; i < sk_CONF_VALUE_num(attr_sk); i++) {
v = sk_CONF_VALUE_value(attr_sk, i);
if (!X509_REQ_add1_attr_by_txt(req, v->name, chtype,
(unsigned char *)v->value, -1))
return 0;
}
}
return 1;
}
static int add_DN_object(X509_NAME *n, char *text, const char *def,
char *value, int nid, int n_min, int n_max,
unsigned long chtype, int mval)
{
int ret = 0;
char buf[1024];
ret = build_data(text, def, value, n_min, n_max, buf, sizeof(buf),
"DN value", "DN default");
if ((ret == 0) || (ret == 1))
return ret;
ret = 1;
if (!X509_NAME_add_entry_by_NID(n, nid, chtype,
(unsigned char *)buf, -1, -1, mval))
ret = 0;
return ret;
}
static int add_attribute_object(X509_REQ *req, char *text, const char *def,
char *value, int nid, int n_min,
int n_max, unsigned long chtype)
{
int ret = 0;
char buf[1024];
ret = build_data(text, def, value, n_min, n_max, buf, sizeof(buf),
"Attribute value", "Attribute default");
if ((ret == 0) || (ret == 1))
return ret;
ret = 1;
if (!X509_REQ_add1_attr_by_NID(req, nid, chtype,
(unsigned char *)buf, -1)) {
BIO_printf(bio_err, "Error adding attribute\n");
ret = 0;
}
return ret;
}
static int build_data(char *text, const char *def, char *value,
int n_min, int n_max, char *buf, const int buf_size,
const char *desc1, const char *desc2)
{
int i;
start:
if (!batch)
BIO_printf(bio_err, "%s [%s]:", text, def);
(void)BIO_flush(bio_err);
if (value != NULL) {
if (!join(buf, buf_size, value, "\n", desc1))
return 0;
BIO_printf(bio_err, "%s\n", value);
} else {
buf[0] = '\0';
if (!batch) {
if (!fgets(buf, buf_size, stdin))
return 0;
} else {
buf[0] = '\n';
buf[1] = '\0';
}
}
if (buf[0] == '\0')
return 0;
if (buf[0] == '\n') {
if ((def == NULL) || (def[0] == '\0'))
return 1;
if (!join(buf, buf_size, def, "\n", desc2))
return 0;
} else if ((buf[0] == '.') && (buf[1] == '\n')) {
return 1;
}
i = strlen(buf);
if (buf[i - 1] != '\n') {
BIO_printf(bio_err, "Missing newline at end of input\n");
return 0;
}
buf[--i] = '\0';
#ifdef CHARSET_EBCDIC
ebcdic2ascii(buf, buf, i);
#endif
if (!req_check_len(i, n_min, n_max)) {
if (batch || value)
return 0;
goto start;
}
return 2;
}
static int req_check_len(int len, int n_min, int n_max)
{
if (n_min > 0 && len < n_min) {
BIO_printf(bio_err,
"String too short, must be at least %d bytes long\n", n_min);
return 0;
}
if (n_max >= 0 && len > n_max) {
BIO_printf(bio_err,
"String too long, must be at most %d bytes long\n", n_max);
return 0;
}
return 1;
}
/* Check if the end of a string matches 'end' */
static int check_end(const char *str, const char *end)
{
size_t elen, slen;
const char *tmp;
elen = strlen(end);
slen = strlen(str);
if (elen > slen)
return 1;
tmp = str + slen - elen;
return strcmp(tmp, end);
}
/*
* Merge the two strings together into the result buffer checking for
* overflow and producing an error message if there is.
*/
static int join(char buf[], size_t buf_size, const char *name,
const char *tail, const char *desc)
{
const size_t name_len = strlen(name), tail_len = strlen(tail);
if (name_len + tail_len + 1 > buf_size) {
BIO_printf(bio_err, "%s '%s' too long\n", desc, name);
return 0;
}
memcpy(buf, name, name_len);
memcpy(buf + name_len, tail, tail_len + 1);
return 1;
}
static EVP_PKEY_CTX *set_keygen_ctx(const char *gstr,
char **pkeytype, long *pkeylen,
ENGINE *keygen_engine)
{
EVP_PKEY_CTX *gctx = NULL;
EVP_PKEY *param = NULL;
long keylen = -1;
BIO *pbio = NULL;
const char *keytype = NULL;
size_t keytypelen = 0;
int expect_paramfile = 0;
const char *paramfile = NULL;
/* Treat the first part of gstr, and only that */
if (gstr == NULL) {
/*
* Special case: when no string given, default to RSA and the
* key length given by |*pkeylen|.
*/
keytype = "RSA";
keylen = *pkeylen;
} else if (gstr[0] >= '0' && gstr[0] <= '9') {
/* Special case: only keylength given from string, so default to RSA */
keytype = "RSA";
/* The second part treatment will do the rest */
} else {
const char *p = strchr(gstr, ':');
int len;
if (p != NULL)
len = p - gstr;
else
len = strlen(gstr);
if (strncmp(gstr, "param", len) == 0) {
expect_paramfile = 1;
if (p == NULL) {
BIO_printf(bio_err,
"Parameter file requested but no path given: %s\n",
gstr);
return NULL;
}
} else {
keytype = gstr;
keytypelen = len;
}
if (p != NULL)
gstr = gstr + len + 1;
else
gstr = NULL;
}
/* Treat the second part of gstr, if there is one */
if (gstr != NULL) {
/* If the second part starts with a digit, we assume it's a size */
if (!expect_paramfile && gstr[0] >= '0' && gstr[0] <= '9')
keylen = atol(gstr);
else
paramfile = gstr;
}
if (paramfile != NULL) {
pbio = BIO_new_file(paramfile, "r");
if (pbio == NULL) {
BIO_printf(bio_err, "Cannot open parameter file %s\n", paramfile);
return NULL;
}
param = PEM_read_bio_Parameters(pbio, NULL);
if (param == NULL) {
X509 *x;
(void)BIO_reset(pbio);
x = PEM_read_bio_X509(pbio, NULL, NULL, NULL);
if (x != NULL) {
param = X509_get_pubkey(x);
X509_free(x);
}
}
BIO_free(pbio);
if (param == NULL) {
BIO_printf(bio_err, "Error reading parameter file %s\n", paramfile);
return NULL;
}
if (keytype == NULL) {
keytype = EVP_PKEY_get0_type_name(param);
if (keytype == NULL) {
EVP_PKEY_free(param);
BIO_puts(bio_err, "Unable to determine key type\n");
return NULL;
}
}
}
if (keytypelen > 0)
*pkeytype = OPENSSL_strndup(keytype, keytypelen);
else
*pkeytype = OPENSSL_strdup(keytype);
if (*pkeytype == NULL) {
BIO_printf(bio_err, "Out of memory\n");
EVP_PKEY_free(param);
return NULL;
}
if (keylen >= 0)
*pkeylen = keylen;
if (param != NULL) {
if (!EVP_PKEY_is_a(param, *pkeytype)) {
BIO_printf(bio_err, "Key type does not match parameters\n");
EVP_PKEY_free(param);
return NULL;
}
if (keygen_engine != NULL)
gctx = EVP_PKEY_CTX_new(param, keygen_engine);
else
gctx = EVP_PKEY_CTX_new_from_pkey(app_get0_libctx(),
param, app_get0_propq());
*pkeylen = EVP_PKEY_get_bits(param);
EVP_PKEY_free(param);
} else {
if (keygen_engine != NULL) {
int pkey_id = get_legacy_pkey_id(app_get0_libctx(), *pkeytype,
keygen_engine);
if (pkey_id != NID_undef)
gctx = EVP_PKEY_CTX_new_id(pkey_id, keygen_engine);
} else {
gctx = EVP_PKEY_CTX_new_from_name(app_get0_libctx(),
*pkeytype, app_get0_propq());
}
}
if (gctx == NULL) {
BIO_puts(bio_err, "Error allocating keygen context\n");
return NULL;
}
if (EVP_PKEY_keygen_init(gctx) <= 0) {
BIO_puts(bio_err, "Error initializing keygen context\n");
EVP_PKEY_CTX_free(gctx);
return NULL;
}
if (keylen == -1 && (EVP_PKEY_CTX_is_a(gctx, "RSA")
|| EVP_PKEY_CTX_is_a(gctx, "RSA-PSS")))
keylen = *pkeylen;
if (keylen != -1) {
OSSL_PARAM params[] = { OSSL_PARAM_END, OSSL_PARAM_END };
size_t bits = keylen;
params[0] =
OSSL_PARAM_construct_size_t(OSSL_PKEY_PARAM_BITS, &bits);
if (EVP_PKEY_CTX_set_params(gctx, params) <= 0) {
BIO_puts(bio_err, "Error setting keysize\n");
EVP_PKEY_CTX_free(gctx);
return NULL;
}
}
return gctx;
}
static int genpkey_cb(EVP_PKEY_CTX *ctx)
{
char c = '*';
BIO *b = EVP_PKEY_CTX_get_app_data(ctx);
int p;
p = EVP_PKEY_CTX_get_keygen_info(ctx, 0);
if (p == 0)
c = '.';
if (p == 1)
c = '+';
if (p == 2)
c = '*';
if (p == 3)
c = '\n';
BIO_write(b, &c, 1);
(void)BIO_flush(b);
return 1;
}
diff --git a/crypto/openssl/apps/speed.c b/crypto/openssl/apps/speed.c
index 1113d775b8ab..d8e2c70e6128 100644
--- a/crypto/openssl/apps/speed.c
+++ b/crypto/openssl/apps/speed.c
@@ -1,3750 +1,3754 @@
/*
- * Copyright 1995-2023 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 1995-2024 The OpenSSL Project Authors. All Rights Reserved.
* Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#undef SECONDS
#define SECONDS 3
#define PKEY_SECONDS 10
#define RSA_SECONDS PKEY_SECONDS
#define DSA_SECONDS PKEY_SECONDS
#define ECDSA_SECONDS PKEY_SECONDS
#define ECDH_SECONDS PKEY_SECONDS
#define EdDSA_SECONDS PKEY_SECONDS
#define SM2_SECONDS PKEY_SECONDS
#define FFDH_SECONDS PKEY_SECONDS
/* We need to use some deprecated APIs */
#define OPENSSL_SUPPRESS_DEPRECATED
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include "apps.h"
#include "progs.h"
#include "internal/numbers.h"
#include <openssl/crypto.h>
#include <openssl/rand.h>
#include <openssl/err.h>
#include <openssl/evp.h>
#include <openssl/objects.h>
#include <openssl/core_names.h>
#include <openssl/async.h>
#if !defined(OPENSSL_SYS_MSDOS)
# include <unistd.h>
#endif
#if defined(__TANDEM)
# if defined(OPENSSL_TANDEM_FLOSS)
# include <floss.h(floss_fork)>
# endif
#endif
#if defined(_WIN32)
# include <windows.h>
#endif
#include <openssl/bn.h>
#include <openssl/rsa.h>
#include "./testrsa.h"
#ifndef OPENSSL_NO_DH
# include <openssl/dh.h>
#endif
#include <openssl/x509.h>
#include <openssl/dsa.h>
#include "./testdsa.h"
#include <openssl/modes.h>
#ifndef HAVE_FORK
# if defined(OPENSSL_SYS_VMS) || defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_VXWORKS)
# define HAVE_FORK 0
# else
# define HAVE_FORK 1
# include <sys/wait.h>
# endif
#endif
#if HAVE_FORK
# undef NO_FORK
#else
# define NO_FORK
#endif
#define MAX_MISALIGNMENT 63
#define MAX_ECDH_SIZE 256
#define MISALIGN 64
#define MAX_FFDH_SIZE 1024
#ifndef RSA_DEFAULT_PRIME_NUM
# define RSA_DEFAULT_PRIME_NUM 2
#endif
typedef struct openssl_speed_sec_st {
int sym;
int rsa;
int dsa;
int ecdsa;
int ecdh;
int eddsa;
int sm2;
int ffdh;
} openssl_speed_sec_t;
static volatile int run = 0;
static int mr = 0; /* machine-readeable output format to merge fork results */
static int usertime = 1;
static double Time_F(int s);
static void print_message(const char *s, long num, int length, int tm);
static void pkey_print_message(const char *str, const char *str2,
long num, unsigned int bits, int sec);
static void print_result(int alg, int run_no, int count, double time_used);
#ifndef NO_FORK
static int do_multi(int multi, int size_num);
#endif
static const int lengths_list[] = {
16, 64, 256, 1024, 8 * 1024, 16 * 1024
};
#define SIZE_NUM OSSL_NELEM(lengths_list)
static const int *lengths = lengths_list;
static const int aead_lengths_list[] = {
2, 31, 136, 1024, 8 * 1024, 16 * 1024
};
#define START 0
#define STOP 1
#ifdef SIGALRM
static void alarmed(int sig)
{
signal(SIGALRM, alarmed);
run = 0;
}
static double Time_F(int s)
{
double ret = app_tminterval(s, usertime);
if (s == STOP)
alarm(0);
return ret;
}
#elif defined(_WIN32)
# define SIGALRM -1
static unsigned int lapse;
static volatile unsigned int schlock;
static void alarm_win32(unsigned int secs)
{
lapse = secs * 1000;
}
# define alarm alarm_win32
static DWORD WINAPI sleepy(VOID * arg)
{
schlock = 1;
Sleep(lapse);
run = 0;
return 0;
}
static double Time_F(int s)
{
double ret;
static HANDLE thr;
if (s == START) {
schlock = 0;
thr = CreateThread(NULL, 4096, sleepy, NULL, 0, NULL);
if (thr == NULL) {
DWORD err = GetLastError();
BIO_printf(bio_err, "unable to CreateThread (%lu)", err);
ExitProcess(err);
}
while (!schlock)
Sleep(0); /* scheduler spinlock */
ret = app_tminterval(s, usertime);
} else {
ret = app_tminterval(s, usertime);
if (run)
TerminateThread(thr, 0);
CloseHandle(thr);
}
return ret;
}
#else
# error "SIGALRM not defined and the platform is not Windows"
#endif
static void multiblock_speed(const EVP_CIPHER *evp_cipher, int lengths_single,
const openssl_speed_sec_t *seconds);
static int opt_found(const char *name, unsigned int *result,
const OPT_PAIR pairs[], unsigned int nbelem)
{
unsigned int idx;
for (idx = 0; idx < nbelem; ++idx, pairs++)
if (strcmp(name, pairs->name) == 0) {
*result = pairs->retval;
return 1;
}
return 0;
}
#define opt_found(value, pairs, result)\
opt_found(value, result, pairs, OSSL_NELEM(pairs))
typedef enum OPTION_choice {
OPT_COMMON,
OPT_ELAPSED, OPT_EVP, OPT_HMAC, OPT_DECRYPT, OPT_ENGINE, OPT_MULTI,
OPT_MR, OPT_MB, OPT_MISALIGN, OPT_ASYNCJOBS, OPT_R_ENUM, OPT_PROV_ENUM,
OPT_PRIMES, OPT_SECONDS, OPT_BYTES, OPT_AEAD, OPT_CMAC
} OPTION_CHOICE;
const OPTIONS speed_options[] = {
{OPT_HELP_STR, 1, '-', "Usage: %s [options] [algorithm...]\n"},
OPT_SECTION("General"),
{"help", OPT_HELP, '-', "Display this summary"},
{"mb", OPT_MB, '-',
"Enable (tls1>=1) multi-block mode on EVP-named cipher"},
{"mr", OPT_MR, '-', "Produce machine readable output"},
#ifndef NO_FORK
{"multi", OPT_MULTI, 'p', "Run benchmarks in parallel"},
#endif
#ifndef OPENSSL_NO_ASYNC
{"async_jobs", OPT_ASYNCJOBS, 'p',
"Enable async mode and start specified number of jobs"},
#endif
#ifndef OPENSSL_NO_ENGINE
{"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"},
#endif
{"primes", OPT_PRIMES, 'p', "Specify number of primes (for RSA only)"},
OPT_SECTION("Selection"),
{"evp", OPT_EVP, 's', "Use EVP-named cipher or digest"},
{"hmac", OPT_HMAC, 's', "HMAC using EVP-named digest"},
{"cmac", OPT_CMAC, 's', "CMAC using EVP-named cipher"},
{"decrypt", OPT_DECRYPT, '-',
"Time decryption instead of encryption (only EVP)"},
{"aead", OPT_AEAD, '-',
"Benchmark EVP-named AEAD cipher in TLS-like sequence"},
OPT_SECTION("Timing"),
{"elapsed", OPT_ELAPSED, '-',
"Use wall-clock time instead of CPU user time as divisor"},
{"seconds", OPT_SECONDS, 'p',
"Run benchmarks for specified amount of seconds"},
{"bytes", OPT_BYTES, 'p',
"Run [non-PKI] benchmarks on custom-sized buffer"},
{"misalign", OPT_MISALIGN, 'p',
"Use specified offset to mis-align buffers"},
OPT_R_OPTIONS,
OPT_PROV_OPTIONS,
OPT_PARAMETERS(),
{"algorithm", 0, 0, "Algorithm(s) to test (optional; otherwise tests all)"},
{NULL}
};
enum {
D_MD2, D_MDC2, D_MD4, D_MD5, D_SHA1, D_RMD160,
D_SHA256, D_SHA512, D_WHIRLPOOL, D_HMAC,
D_CBC_DES, D_EDE3_DES, D_RC4, D_CBC_IDEA, D_CBC_SEED,
D_CBC_RC2, D_CBC_RC5, D_CBC_BF, D_CBC_CAST,
D_CBC_128_AES, D_CBC_192_AES, D_CBC_256_AES,
D_CBC_128_CML, D_CBC_192_CML, D_CBC_256_CML,
D_EVP, D_GHASH, D_RAND, D_EVP_CMAC, ALGOR_NUM
};
/* name of algorithms to test. MUST BE KEEP IN SYNC with above enum ! */
static const char *names[ALGOR_NUM] = {
"md2", "mdc2", "md4", "md5", "sha1", "rmd160",
"sha256", "sha512", "whirlpool", "hmac(md5)",
"des-cbc", "des-ede3", "rc4", "idea-cbc", "seed-cbc",
"rc2-cbc", "rc5-cbc", "blowfish", "cast-cbc",
"aes-128-cbc", "aes-192-cbc", "aes-256-cbc",
"camellia-128-cbc", "camellia-192-cbc", "camellia-256-cbc",
"evp", "ghash", "rand", "cmac"
};
/* list of configured algorithm (remaining), with some few alias */
static const OPT_PAIR doit_choices[] = {
{"md2", D_MD2},
{"mdc2", D_MDC2},
{"md4", D_MD4},
{"md5", D_MD5},
{"hmac", D_HMAC},
{"sha1", D_SHA1},
{"sha256", D_SHA256},
{"sha512", D_SHA512},
{"whirlpool", D_WHIRLPOOL},
{"ripemd", D_RMD160},
{"rmd160", D_RMD160},
{"ripemd160", D_RMD160},
{"rc4", D_RC4},
{"des-cbc", D_CBC_DES},
{"des-ede3", D_EDE3_DES},
{"aes-128-cbc", D_CBC_128_AES},
{"aes-192-cbc", D_CBC_192_AES},
{"aes-256-cbc", D_CBC_256_AES},
{"camellia-128-cbc", D_CBC_128_CML},
{"camellia-192-cbc", D_CBC_192_CML},
{"camellia-256-cbc", D_CBC_256_CML},
{"rc2-cbc", D_CBC_RC2},
{"rc2", D_CBC_RC2},
{"rc5-cbc", D_CBC_RC5},
{"rc5", D_CBC_RC5},
{"idea-cbc", D_CBC_IDEA},
{"idea", D_CBC_IDEA},
{"seed-cbc", D_CBC_SEED},
{"seed", D_CBC_SEED},
{"bf-cbc", D_CBC_BF},
{"blowfish", D_CBC_BF},
{"bf", D_CBC_BF},
{"cast-cbc", D_CBC_CAST},
{"cast", D_CBC_CAST},
{"cast5", D_CBC_CAST},
{"ghash", D_GHASH},
{"rand", D_RAND}
};
static double results[ALGOR_NUM][SIZE_NUM];
enum { R_DSA_512, R_DSA_1024, R_DSA_2048, DSA_NUM };
static const OPT_PAIR dsa_choices[DSA_NUM] = {
{"dsa512", R_DSA_512},
{"dsa1024", R_DSA_1024},
{"dsa2048", R_DSA_2048}
};
static double dsa_results[DSA_NUM][2]; /* 2 ops: sign then verify */
enum {
R_RSA_512, R_RSA_1024, R_RSA_2048, R_RSA_3072, R_RSA_4096, R_RSA_7680,
R_RSA_15360, RSA_NUM
};
static const OPT_PAIR rsa_choices[RSA_NUM] = {
{"rsa512", R_RSA_512},
{"rsa1024", R_RSA_1024},
{"rsa2048", R_RSA_2048},
{"rsa3072", R_RSA_3072},
{"rsa4096", R_RSA_4096},
{"rsa7680", R_RSA_7680},
{"rsa15360", R_RSA_15360}
};
static double rsa_results[RSA_NUM][2]; /* 2 ops: sign then verify */
#ifndef OPENSSL_NO_DH
enum ff_params_t {
R_FFDH_2048, R_FFDH_3072, R_FFDH_4096, R_FFDH_6144, R_FFDH_8192, FFDH_NUM
};
static const OPT_PAIR ffdh_choices[FFDH_NUM] = {
{"ffdh2048", R_FFDH_2048},
{"ffdh3072", R_FFDH_3072},
{"ffdh4096", R_FFDH_4096},
{"ffdh6144", R_FFDH_6144},
{"ffdh8192", R_FFDH_8192},
};
static double ffdh_results[FFDH_NUM][1]; /* 1 op: derivation */
#endif /* OPENSSL_NO_DH */
enum ec_curves_t {
R_EC_P160, R_EC_P192, R_EC_P224, R_EC_P256, R_EC_P384, R_EC_P521,
#ifndef OPENSSL_NO_EC2M
R_EC_K163, R_EC_K233, R_EC_K283, R_EC_K409, R_EC_K571,
R_EC_B163, R_EC_B233, R_EC_B283, R_EC_B409, R_EC_B571,
#endif
R_EC_BRP256R1, R_EC_BRP256T1, R_EC_BRP384R1, R_EC_BRP384T1,
R_EC_BRP512R1, R_EC_BRP512T1, ECDSA_NUM
};
/* list of ecdsa curves */
static const OPT_PAIR ecdsa_choices[ECDSA_NUM] = {
{"ecdsap160", R_EC_P160},
{"ecdsap192", R_EC_P192},
{"ecdsap224", R_EC_P224},
{"ecdsap256", R_EC_P256},
{"ecdsap384", R_EC_P384},
{"ecdsap521", R_EC_P521},
#ifndef OPENSSL_NO_EC2M
{"ecdsak163", R_EC_K163},
{"ecdsak233", R_EC_K233},
{"ecdsak283", R_EC_K283},
{"ecdsak409", R_EC_K409},
{"ecdsak571", R_EC_K571},
{"ecdsab163", R_EC_B163},
{"ecdsab233", R_EC_B233},
{"ecdsab283", R_EC_B283},
{"ecdsab409", R_EC_B409},
{"ecdsab571", R_EC_B571},
#endif
{"ecdsabrp256r1", R_EC_BRP256R1},
{"ecdsabrp256t1", R_EC_BRP256T1},
{"ecdsabrp384r1", R_EC_BRP384R1},
{"ecdsabrp384t1", R_EC_BRP384T1},
{"ecdsabrp512r1", R_EC_BRP512R1},
{"ecdsabrp512t1", R_EC_BRP512T1}
};
enum { R_EC_X25519 = ECDSA_NUM, R_EC_X448, EC_NUM };
/* list of ecdh curves, extension of |ecdsa_choices| list above */
static const OPT_PAIR ecdh_choices[EC_NUM] = {
{"ecdhp160", R_EC_P160},
{"ecdhp192", R_EC_P192},
{"ecdhp224", R_EC_P224},
{"ecdhp256", R_EC_P256},
{"ecdhp384", R_EC_P384},
{"ecdhp521", R_EC_P521},
#ifndef OPENSSL_NO_EC2M
{"ecdhk163", R_EC_K163},
{"ecdhk233", R_EC_K233},
{"ecdhk283", R_EC_K283},
{"ecdhk409", R_EC_K409},
{"ecdhk571", R_EC_K571},
{"ecdhb163", R_EC_B163},
{"ecdhb233", R_EC_B233},
{"ecdhb283", R_EC_B283},
{"ecdhb409", R_EC_B409},
{"ecdhb571", R_EC_B571},
#endif
{"ecdhbrp256r1", R_EC_BRP256R1},
{"ecdhbrp256t1", R_EC_BRP256T1},
{"ecdhbrp384r1", R_EC_BRP384R1},
{"ecdhbrp384t1", R_EC_BRP384T1},
{"ecdhbrp512r1", R_EC_BRP512R1},
{"ecdhbrp512t1", R_EC_BRP512T1},
{"ecdhx25519", R_EC_X25519},
{"ecdhx448", R_EC_X448}
};
static double ecdh_results[EC_NUM][1]; /* 1 op: derivation */
static double ecdsa_results[ECDSA_NUM][2]; /* 2 ops: sign then verify */
enum { R_EC_Ed25519, R_EC_Ed448, EdDSA_NUM };
static const OPT_PAIR eddsa_choices[EdDSA_NUM] = {
{"ed25519", R_EC_Ed25519},
{"ed448", R_EC_Ed448}
};
static double eddsa_results[EdDSA_NUM][2]; /* 2 ops: sign then verify */
#ifndef OPENSSL_NO_SM2
enum { R_EC_CURVESM2, SM2_NUM };
static const OPT_PAIR sm2_choices[SM2_NUM] = {
{"curveSM2", R_EC_CURVESM2}
};
# define SM2_ID "TLSv1.3+GM+Cipher+Suite"
# define SM2_ID_LEN sizeof("TLSv1.3+GM+Cipher+Suite") - 1
static double sm2_results[SM2_NUM][2]; /* 2 ops: sign then verify */
#endif /* OPENSSL_NO_SM2 */
#define COND(unused_cond) (run && count < INT_MAX)
#define COUNT(d) (count)
typedef struct loopargs_st {
ASYNC_JOB *inprogress_job;
ASYNC_WAIT_CTX *wait_ctx;
unsigned char *buf;
unsigned char *buf2;
unsigned char *buf_malloc;
unsigned char *buf2_malloc;
unsigned char *key;
size_t buflen;
size_t sigsize;
EVP_PKEY_CTX *rsa_sign_ctx[RSA_NUM];
EVP_PKEY_CTX *rsa_verify_ctx[RSA_NUM];
EVP_PKEY_CTX *dsa_sign_ctx[DSA_NUM];
EVP_PKEY_CTX *dsa_verify_ctx[DSA_NUM];
EVP_PKEY_CTX *ecdsa_sign_ctx[ECDSA_NUM];
EVP_PKEY_CTX *ecdsa_verify_ctx[ECDSA_NUM];
EVP_PKEY_CTX *ecdh_ctx[EC_NUM];
EVP_MD_CTX *eddsa_ctx[EdDSA_NUM];
EVP_MD_CTX *eddsa_ctx2[EdDSA_NUM];
#ifndef OPENSSL_NO_SM2
EVP_MD_CTX *sm2_ctx[SM2_NUM];
EVP_MD_CTX *sm2_vfy_ctx[SM2_NUM];
EVP_PKEY *sm2_pkey[SM2_NUM];
#endif
unsigned char *secret_a;
unsigned char *secret_b;
size_t outlen[EC_NUM];
#ifndef OPENSSL_NO_DH
EVP_PKEY_CTX *ffdh_ctx[FFDH_NUM];
unsigned char *secret_ff_a;
unsigned char *secret_ff_b;
#endif
EVP_CIPHER_CTX *ctx;
EVP_MAC_CTX *mctx;
} loopargs_t;
static int run_benchmark(int async_jobs, int (*loop_function) (void *),
loopargs_t * loopargs);
static unsigned int testnum;
/* Nb of iterations to do per algorithm and key-size */
static long c[ALGOR_NUM][SIZE_NUM];
static char *evp_mac_mdname = "md5";
static char *evp_hmac_name = NULL;
static const char *evp_md_name = NULL;
static char *evp_mac_ciphername = "aes-128-cbc";
static char *evp_cmac_name = NULL;
static int have_md(const char *name)
{
int ret = 0;
EVP_MD *md = NULL;
if (opt_md_silent(name, &md)) {
EVP_MD_CTX *ctx = EVP_MD_CTX_new();
if (ctx != NULL && EVP_DigestInit(ctx, md) > 0)
ret = 1;
EVP_MD_CTX_free(ctx);
EVP_MD_free(md);
}
return ret;
}
static int have_cipher(const char *name)
{
int ret = 0;
EVP_CIPHER *cipher = NULL;
if (opt_cipher_silent(name, &cipher)) {
EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
if (ctx != NULL
&& EVP_CipherInit_ex(ctx, cipher, NULL, NULL, NULL, 1) > 0)
ret = 1;
EVP_CIPHER_CTX_free(ctx);
EVP_CIPHER_free(cipher);
}
return ret;
}
static int EVP_Digest_loop(const char *mdname, int algindex, void *args)
{
loopargs_t *tempargs = *(loopargs_t **) args;
unsigned char *buf = tempargs->buf;
unsigned char digest[EVP_MAX_MD_SIZE];
int count;
EVP_MD *md = NULL;
if (!opt_md_silent(mdname, &md))
return -1;
for (count = 0; COND(c[algindex][testnum]); count++) {
if (!EVP_Digest(buf, (size_t)lengths[testnum], digest, NULL, md,
NULL)) {
count = -1;
break;
}
}
EVP_MD_free(md);
return count;
}
static int EVP_Digest_md_loop(void *args)
{
return EVP_Digest_loop(evp_md_name, D_EVP, args);
}
static int EVP_Digest_MD2_loop(void *args)
{
return EVP_Digest_loop("md2", D_MD2, args);
}
static int EVP_Digest_MDC2_loop(void *args)
{
return EVP_Digest_loop("mdc2", D_MDC2, args);
}
static int EVP_Digest_MD4_loop(void *args)
{
return EVP_Digest_loop("md4", D_MD4, args);
}
static int MD5_loop(void *args)
{
return EVP_Digest_loop("md5", D_MD5, args);
}
static int EVP_MAC_loop(int algindex, void *args)
{
loopargs_t *tempargs = *(loopargs_t **) args;
unsigned char *buf = tempargs->buf;
EVP_MAC_CTX *mctx = tempargs->mctx;
unsigned char mac[EVP_MAX_MD_SIZE];
int count;
for (count = 0; COND(c[algindex][testnum]); count++) {
size_t outl;
if (!EVP_MAC_init(mctx, NULL, 0, NULL)
|| !EVP_MAC_update(mctx, buf, lengths[testnum])
|| !EVP_MAC_final(mctx, mac, &outl, sizeof(mac)))
return -1;
}
return count;
}
static int HMAC_loop(void *args)
{
return EVP_MAC_loop(D_HMAC, args);
}
static int CMAC_loop(void *args)
{
return EVP_MAC_loop(D_EVP_CMAC, args);
}
static int SHA1_loop(void *args)
{
return EVP_Digest_loop("sha1", D_SHA1, args);
}
static int SHA256_loop(void *args)
{
return EVP_Digest_loop("sha256", D_SHA256, args);
}
static int SHA512_loop(void *args)
{
return EVP_Digest_loop("sha512", D_SHA512, args);
}
static int WHIRLPOOL_loop(void *args)
{
return EVP_Digest_loop("whirlpool", D_WHIRLPOOL, args);
}
static int EVP_Digest_RMD160_loop(void *args)
{
return EVP_Digest_loop("ripemd160", D_RMD160, args);
}
static int algindex;
static int EVP_Cipher_loop(void *args)
{
loopargs_t *tempargs = *(loopargs_t **) args;
unsigned char *buf = tempargs->buf;
int count;
if (tempargs->ctx == NULL)
return -1;
for (count = 0; COND(c[algindex][testnum]); count++)
if (EVP_Cipher(tempargs->ctx, buf, buf, (size_t)lengths[testnum]) <= 0)
return -1;
return count;
}
static int GHASH_loop(void *args)
{
loopargs_t *tempargs = *(loopargs_t **) args;
unsigned char *buf = tempargs->buf;
EVP_MAC_CTX *mctx = tempargs->mctx;
int count;
/* just do the update in the loop to be comparable with 1.1.1 */
for (count = 0; COND(c[D_GHASH][testnum]); count++) {
if (!EVP_MAC_update(mctx, buf, lengths[testnum]))
return -1;
}
return count;
}
#define MAX_BLOCK_SIZE 128
static unsigned char iv[2 * MAX_BLOCK_SIZE / 8];
static EVP_CIPHER_CTX *init_evp_cipher_ctx(const char *ciphername,
const unsigned char *key,
int keylen)
{
EVP_CIPHER_CTX *ctx = NULL;
EVP_CIPHER *cipher = NULL;
if (!opt_cipher_silent(ciphername, &cipher))
return NULL;
if ((ctx = EVP_CIPHER_CTX_new()) == NULL)
goto end;
if (!EVP_CipherInit_ex(ctx, cipher, NULL, NULL, NULL, 1)) {
EVP_CIPHER_CTX_free(ctx);
ctx = NULL;
goto end;
}
if (EVP_CIPHER_CTX_set_key_length(ctx, keylen) <= 0) {
EVP_CIPHER_CTX_free(ctx);
ctx = NULL;
goto end;
}
if (!EVP_CipherInit_ex(ctx, NULL, NULL, key, iv, 1)) {
EVP_CIPHER_CTX_free(ctx);
ctx = NULL;
goto end;
}
end:
EVP_CIPHER_free(cipher);
return ctx;
}
static int RAND_bytes_loop(void *args)
{
loopargs_t *tempargs = *(loopargs_t **) args;
unsigned char *buf = tempargs->buf;
int count;
for (count = 0; COND(c[D_RAND][testnum]); count++)
RAND_bytes(buf, lengths[testnum]);
return count;
}
static int decrypt = 0;
static int EVP_Update_loop(void *args)
{
loopargs_t *tempargs = *(loopargs_t **) args;
unsigned char *buf = tempargs->buf;
EVP_CIPHER_CTX *ctx = tempargs->ctx;
int outl, count, rc;
+ unsigned char faketag[16] = { 0xcc };
if (decrypt) {
+ if (EVP_CIPHER_get_flags(EVP_CIPHER_CTX_get0_cipher(ctx)) & EVP_CIPH_FLAG_AEAD_CIPHER) {
+ (void)EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_TAG, sizeof(faketag), faketag);
+ }
for (count = 0; COND(c[D_EVP][testnum]); count++) {
rc = EVP_DecryptUpdate(ctx, buf, &outl, buf, lengths[testnum]);
if (rc != 1) {
/* reset iv in case of counter overflow */
EVP_CipherInit_ex(ctx, NULL, NULL, NULL, iv, -1);
}
}
} else {
for (count = 0; COND(c[D_EVP][testnum]); count++) {
rc = EVP_EncryptUpdate(ctx, buf, &outl, buf, lengths[testnum]);
if (rc != 1) {
/* reset iv in case of counter overflow */
EVP_CipherInit_ex(ctx, NULL, NULL, NULL, iv, -1);
}
}
}
if (decrypt)
EVP_DecryptFinal_ex(ctx, buf, &outl);
else
EVP_EncryptFinal_ex(ctx, buf, &outl);
return count;
}
/*
* CCM does not support streaming. For the purpose of performance measurement,
* each message is encrypted using the same (key,iv)-pair. Do not use this
* code in your application.
*/
static int EVP_Update_loop_ccm(void *args)
{
loopargs_t *tempargs = *(loopargs_t **) args;
unsigned char *buf = tempargs->buf;
EVP_CIPHER_CTX *ctx = tempargs->ctx;
int outl, count;
unsigned char tag[12];
if (decrypt) {
for (count = 0; COND(c[D_EVP][testnum]); count++) {
(void)EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_TAG, sizeof(tag),
tag);
/* reset iv */
(void)EVP_DecryptInit_ex(ctx, NULL, NULL, NULL, iv);
/* counter is reset on every update */
(void)EVP_DecryptUpdate(ctx, buf, &outl, buf, lengths[testnum]);
}
} else {
for (count = 0; COND(c[D_EVP][testnum]); count++) {
/* restore iv length field */
(void)EVP_EncryptUpdate(ctx, NULL, &outl, NULL, lengths[testnum]);
/* counter is reset on every update */
(void)EVP_EncryptUpdate(ctx, buf, &outl, buf, lengths[testnum]);
}
}
if (decrypt)
(void)EVP_DecryptFinal_ex(ctx, buf, &outl);
else
(void)EVP_EncryptFinal_ex(ctx, buf, &outl);
return count;
}
/*
* To make AEAD benchmarking more relevant perform TLS-like operations,
* 13-byte AAD followed by payload. But don't use TLS-formatted AAD, as
* payload length is not actually limited by 16KB...
*/
static int EVP_Update_loop_aead(void *args)
{
loopargs_t *tempargs = *(loopargs_t **) args;
unsigned char *buf = tempargs->buf;
EVP_CIPHER_CTX *ctx = tempargs->ctx;
int outl, count;
unsigned char aad[13] = { 0xcc };
unsigned char faketag[16] = { 0xcc };
if (decrypt) {
for (count = 0; COND(c[D_EVP][testnum]); count++) {
(void)EVP_DecryptInit_ex(ctx, NULL, NULL, NULL, iv);
(void)EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_TAG,
sizeof(faketag), faketag);
(void)EVP_DecryptUpdate(ctx, NULL, &outl, aad, sizeof(aad));
(void)EVP_DecryptUpdate(ctx, buf, &outl, buf, lengths[testnum]);
(void)EVP_DecryptFinal_ex(ctx, buf + outl, &outl);
}
} else {
for (count = 0; COND(c[D_EVP][testnum]); count++) {
(void)EVP_EncryptInit_ex(ctx, NULL, NULL, NULL, iv);
(void)EVP_EncryptUpdate(ctx, NULL, &outl, aad, sizeof(aad));
(void)EVP_EncryptUpdate(ctx, buf, &outl, buf, lengths[testnum]);
(void)EVP_EncryptFinal_ex(ctx, buf + outl, &outl);
}
}
return count;
}
static long rsa_c[RSA_NUM][2]; /* # RSA iteration test */
static int RSA_sign_loop(void *args)
{
loopargs_t *tempargs = *(loopargs_t **) args;
unsigned char *buf = tempargs->buf;
unsigned char *buf2 = tempargs->buf2;
size_t *rsa_num = &tempargs->sigsize;
EVP_PKEY_CTX **rsa_sign_ctx = tempargs->rsa_sign_ctx;
int ret, count;
for (count = 0; COND(rsa_c[testnum][0]); count++) {
*rsa_num = tempargs->buflen;
ret = EVP_PKEY_sign(rsa_sign_ctx[testnum], buf2, rsa_num, buf, 36);
if (ret <= 0) {
BIO_printf(bio_err, "RSA sign failure\n");
ERR_print_errors(bio_err);
count = -1;
break;
}
}
return count;
}
static int RSA_verify_loop(void *args)
{
loopargs_t *tempargs = *(loopargs_t **) args;
unsigned char *buf = tempargs->buf;
unsigned char *buf2 = tempargs->buf2;
size_t rsa_num = tempargs->sigsize;
EVP_PKEY_CTX **rsa_verify_ctx = tempargs->rsa_verify_ctx;
int ret, count;
for (count = 0; COND(rsa_c[testnum][1]); count++) {
ret = EVP_PKEY_verify(rsa_verify_ctx[testnum], buf2, rsa_num, buf, 36);
if (ret <= 0) {
BIO_printf(bio_err, "RSA verify failure\n");
ERR_print_errors(bio_err);
count = -1;
break;
}
}
return count;
}
#ifndef OPENSSL_NO_DH
static long ffdh_c[FFDH_NUM][1];
static int FFDH_derive_key_loop(void *args)
{
loopargs_t *tempargs = *(loopargs_t **) args;
EVP_PKEY_CTX *ffdh_ctx = tempargs->ffdh_ctx[testnum];
unsigned char *derived_secret = tempargs->secret_ff_a;
int count;
for (count = 0; COND(ffdh_c[testnum][0]); count++) {
/* outlen can be overwritten with a too small value (no padding used) */
size_t outlen = MAX_FFDH_SIZE;
EVP_PKEY_derive(ffdh_ctx, derived_secret, &outlen);
}
return count;
}
#endif /* OPENSSL_NO_DH */
static long dsa_c[DSA_NUM][2];
static int DSA_sign_loop(void *args)
{
loopargs_t *tempargs = *(loopargs_t **) args;
unsigned char *buf = tempargs->buf;
unsigned char *buf2 = tempargs->buf2;
size_t *dsa_num = &tempargs->sigsize;
EVP_PKEY_CTX **dsa_sign_ctx = tempargs->dsa_sign_ctx;
int ret, count;
for (count = 0; COND(dsa_c[testnum][0]); count++) {
*dsa_num = tempargs->buflen;
ret = EVP_PKEY_sign(dsa_sign_ctx[testnum], buf2, dsa_num, buf, 20);
if (ret <= 0) {
BIO_printf(bio_err, "DSA sign failure\n");
ERR_print_errors(bio_err);
count = -1;
break;
}
}
return count;
}
static int DSA_verify_loop(void *args)
{
loopargs_t *tempargs = *(loopargs_t **) args;
unsigned char *buf = tempargs->buf;
unsigned char *buf2 = tempargs->buf2;
size_t dsa_num = tempargs->sigsize;
EVP_PKEY_CTX **dsa_verify_ctx = tempargs->dsa_verify_ctx;
int ret, count;
for (count = 0; COND(dsa_c[testnum][1]); count++) {
ret = EVP_PKEY_verify(dsa_verify_ctx[testnum], buf2, dsa_num, buf, 20);
if (ret <= 0) {
BIO_printf(bio_err, "DSA verify failure\n");
ERR_print_errors(bio_err);
count = -1;
break;
}
}
return count;
}
static long ecdsa_c[ECDSA_NUM][2];
static int ECDSA_sign_loop(void *args)
{
loopargs_t *tempargs = *(loopargs_t **) args;
unsigned char *buf = tempargs->buf;
unsigned char *buf2 = tempargs->buf2;
size_t *ecdsa_num = &tempargs->sigsize;
EVP_PKEY_CTX **ecdsa_sign_ctx = tempargs->ecdsa_sign_ctx;
int ret, count;
for (count = 0; COND(ecdsa_c[testnum][0]); count++) {
*ecdsa_num = tempargs->buflen;
ret = EVP_PKEY_sign(ecdsa_sign_ctx[testnum], buf2, ecdsa_num, buf, 20);
if (ret <= 0) {
BIO_printf(bio_err, "ECDSA sign failure\n");
ERR_print_errors(bio_err);
count = -1;
break;
}
}
return count;
}
static int ECDSA_verify_loop(void *args)
{
loopargs_t *tempargs = *(loopargs_t **) args;
unsigned char *buf = tempargs->buf;
unsigned char *buf2 = tempargs->buf2;
size_t ecdsa_num = tempargs->sigsize;
EVP_PKEY_CTX **ecdsa_verify_ctx = tempargs->ecdsa_verify_ctx;
int ret, count;
for (count = 0; COND(ecdsa_c[testnum][1]); count++) {
ret = EVP_PKEY_verify(ecdsa_verify_ctx[testnum], buf2, ecdsa_num,
buf, 20);
if (ret <= 0) {
BIO_printf(bio_err, "ECDSA verify failure\n");
ERR_print_errors(bio_err);
count = -1;
break;
}
}
return count;
}
/* ******************************************************************** */
static long ecdh_c[EC_NUM][1];
static int ECDH_EVP_derive_key_loop(void *args)
{
loopargs_t *tempargs = *(loopargs_t **) args;
EVP_PKEY_CTX *ctx = tempargs->ecdh_ctx[testnum];
unsigned char *derived_secret = tempargs->secret_a;
int count;
size_t *outlen = &(tempargs->outlen[testnum]);
for (count = 0; COND(ecdh_c[testnum][0]); count++)
EVP_PKEY_derive(ctx, derived_secret, outlen);
return count;
}
static long eddsa_c[EdDSA_NUM][2];
static int EdDSA_sign_loop(void *args)
{
loopargs_t *tempargs = *(loopargs_t **) args;
unsigned char *buf = tempargs->buf;
EVP_MD_CTX **edctx = tempargs->eddsa_ctx;
unsigned char *eddsasig = tempargs->buf2;
size_t *eddsasigsize = &tempargs->sigsize;
int ret, count;
for (count = 0; COND(eddsa_c[testnum][0]); count++) {
ret = EVP_DigestSignInit(edctx[testnum], NULL, NULL, NULL, NULL);
if (ret == 0) {
BIO_printf(bio_err, "EdDSA sign init failure\n");
ERR_print_errors(bio_err);
count = -1;
break;
}
ret = EVP_DigestSign(edctx[testnum], eddsasig, eddsasigsize, buf, 20);
if (ret == 0) {
BIO_printf(bio_err, "EdDSA sign failure\n");
ERR_print_errors(bio_err);
count = -1;
break;
}
}
return count;
}
static int EdDSA_verify_loop(void *args)
{
loopargs_t *tempargs = *(loopargs_t **) args;
unsigned char *buf = tempargs->buf;
EVP_MD_CTX **edctx = tempargs->eddsa_ctx2;
unsigned char *eddsasig = tempargs->buf2;
size_t eddsasigsize = tempargs->sigsize;
int ret, count;
for (count = 0; COND(eddsa_c[testnum][1]); count++) {
ret = EVP_DigestVerifyInit(edctx[testnum], NULL, NULL, NULL, NULL);
if (ret == 0) {
BIO_printf(bio_err, "EdDSA verify init failure\n");
ERR_print_errors(bio_err);
count = -1;
break;
}
ret = EVP_DigestVerify(edctx[testnum], eddsasig, eddsasigsize, buf, 20);
if (ret != 1) {
BIO_printf(bio_err, "EdDSA verify failure\n");
ERR_print_errors(bio_err);
count = -1;
break;
}
}
return count;
}
#ifndef OPENSSL_NO_SM2
static long sm2_c[SM2_NUM][2];
static int SM2_sign_loop(void *args)
{
loopargs_t *tempargs = *(loopargs_t **) args;
unsigned char *buf = tempargs->buf;
EVP_MD_CTX **sm2ctx = tempargs->sm2_ctx;
unsigned char *sm2sig = tempargs->buf2;
size_t sm2sigsize;
int ret, count;
EVP_PKEY **sm2_pkey = tempargs->sm2_pkey;
const size_t max_size = EVP_PKEY_get_size(sm2_pkey[testnum]);
for (count = 0; COND(sm2_c[testnum][0]); count++) {
sm2sigsize = max_size;
if (!EVP_DigestSignInit(sm2ctx[testnum], NULL, EVP_sm3(),
NULL, sm2_pkey[testnum])) {
BIO_printf(bio_err, "SM2 init sign failure\n");
ERR_print_errors(bio_err);
count = -1;
break;
}
ret = EVP_DigestSign(sm2ctx[testnum], sm2sig, &sm2sigsize,
buf, 20);
if (ret == 0) {
BIO_printf(bio_err, "SM2 sign failure\n");
ERR_print_errors(bio_err);
count = -1;
break;
}
/* update the latest returned size and always use the fixed buffer size */
tempargs->sigsize = sm2sigsize;
}
return count;
}
static int SM2_verify_loop(void *args)
{
loopargs_t *tempargs = *(loopargs_t **) args;
unsigned char *buf = tempargs->buf;
EVP_MD_CTX **sm2ctx = tempargs->sm2_vfy_ctx;
unsigned char *sm2sig = tempargs->buf2;
size_t sm2sigsize = tempargs->sigsize;
int ret, count;
EVP_PKEY **sm2_pkey = tempargs->sm2_pkey;
for (count = 0; COND(sm2_c[testnum][1]); count++) {
if (!EVP_DigestVerifyInit(sm2ctx[testnum], NULL, EVP_sm3(),
NULL, sm2_pkey[testnum])) {
BIO_printf(bio_err, "SM2 verify init failure\n");
ERR_print_errors(bio_err);
count = -1;
break;
}
ret = EVP_DigestVerify(sm2ctx[testnum], sm2sig, sm2sigsize,
buf, 20);
if (ret != 1) {
BIO_printf(bio_err, "SM2 verify failure\n");
ERR_print_errors(bio_err);
count = -1;
break;
}
}
return count;
}
#endif /* OPENSSL_NO_SM2 */
static int run_benchmark(int async_jobs,
int (*loop_function) (void *), loopargs_t * loopargs)
{
int job_op_count = 0;
int total_op_count = 0;
int num_inprogress = 0;
int error = 0, i = 0, ret = 0;
OSSL_ASYNC_FD job_fd = 0;
size_t num_job_fds = 0;
if (async_jobs == 0) {
return loop_function((void *)&loopargs);
}
for (i = 0; i < async_jobs && !error; i++) {
loopargs_t *looparg_item = loopargs + i;
/* Copy pointer content (looparg_t item address) into async context */
ret = ASYNC_start_job(&loopargs[i].inprogress_job, loopargs[i].wait_ctx,
&job_op_count, loop_function,
(void *)&looparg_item, sizeof(looparg_item));
switch (ret) {
case ASYNC_PAUSE:
++num_inprogress;
break;
case ASYNC_FINISH:
if (job_op_count == -1) {
error = 1;
} else {
total_op_count += job_op_count;
}
break;
case ASYNC_NO_JOBS:
case ASYNC_ERR:
BIO_printf(bio_err, "Failure in the job\n");
ERR_print_errors(bio_err);
error = 1;
break;
}
}
while (num_inprogress > 0) {
#if defined(OPENSSL_SYS_WINDOWS)
DWORD avail = 0;
#elif defined(OPENSSL_SYS_UNIX)
int select_result = 0;
OSSL_ASYNC_FD max_fd = 0;
fd_set waitfdset;
FD_ZERO(&waitfdset);
for (i = 0; i < async_jobs && num_inprogress > 0; i++) {
if (loopargs[i].inprogress_job == NULL)
continue;
if (!ASYNC_WAIT_CTX_get_all_fds
(loopargs[i].wait_ctx, NULL, &num_job_fds)
|| num_job_fds > 1) {
BIO_printf(bio_err, "Too many fds in ASYNC_WAIT_CTX\n");
ERR_print_errors(bio_err);
error = 1;
break;
}
ASYNC_WAIT_CTX_get_all_fds(loopargs[i].wait_ctx, &job_fd,
&num_job_fds);
FD_SET(job_fd, &waitfdset);
if (job_fd > max_fd)
max_fd = job_fd;
}
if (max_fd >= (OSSL_ASYNC_FD)FD_SETSIZE) {
BIO_printf(bio_err,
"Error: max_fd (%d) must be smaller than FD_SETSIZE (%d). "
"Decrease the value of async_jobs\n",
max_fd, FD_SETSIZE);
ERR_print_errors(bio_err);
error = 1;
break;
}
select_result = select(max_fd + 1, &waitfdset, NULL, NULL, NULL);
if (select_result == -1 && errno == EINTR)
continue;
if (select_result == -1) {
BIO_printf(bio_err, "Failure in the select\n");
ERR_print_errors(bio_err);
error = 1;
break;
}
if (select_result == 0)
continue;
#endif
for (i = 0; i < async_jobs; i++) {
if (loopargs[i].inprogress_job == NULL)
continue;
if (!ASYNC_WAIT_CTX_get_all_fds
(loopargs[i].wait_ctx, NULL, &num_job_fds)
|| num_job_fds > 1) {
BIO_printf(bio_err, "Too many fds in ASYNC_WAIT_CTX\n");
ERR_print_errors(bio_err);
error = 1;
break;
}
ASYNC_WAIT_CTX_get_all_fds(loopargs[i].wait_ctx, &job_fd,
&num_job_fds);
#if defined(OPENSSL_SYS_UNIX)
if (num_job_fds == 1 && !FD_ISSET(job_fd, &waitfdset))
continue;
#elif defined(OPENSSL_SYS_WINDOWS)
if (num_job_fds == 1
&& !PeekNamedPipe(job_fd, NULL, 0, NULL, &avail, NULL)
&& avail > 0)
continue;
#endif
ret = ASYNC_start_job(&loopargs[i].inprogress_job,
loopargs[i].wait_ctx, &job_op_count,
loop_function, (void *)(loopargs + i),
sizeof(loopargs_t));
switch (ret) {
case ASYNC_PAUSE:
break;
case ASYNC_FINISH:
if (job_op_count == -1) {
error = 1;
} else {
total_op_count += job_op_count;
}
--num_inprogress;
loopargs[i].inprogress_job = NULL;
break;
case ASYNC_NO_JOBS:
case ASYNC_ERR:
--num_inprogress;
loopargs[i].inprogress_job = NULL;
BIO_printf(bio_err, "Failure in the job\n");
ERR_print_errors(bio_err);
error = 1;
break;
}
}
}
return error ? -1 : total_op_count;
}
typedef struct ec_curve_st {
const char *name;
unsigned int nid;
unsigned int bits;
size_t sigsize; /* only used for EdDSA curves */
} EC_CURVE;
static EVP_PKEY *get_ecdsa(const EC_CURVE *curve)
{
EVP_PKEY_CTX *kctx = NULL;
EVP_PKEY *key = NULL;
/* Ensure that the error queue is empty */
if (ERR_peek_error()) {
BIO_printf(bio_err,
"WARNING: the error queue contains previous unhandled errors.\n");
ERR_print_errors(bio_err);
}
/*
* Let's try to create a ctx directly from the NID: this works for
* curves like Curve25519 that are not implemented through the low
* level EC interface.
* If this fails we try creating a EVP_PKEY_EC generic param ctx,
* then we set the curve by NID before deriving the actual keygen
* ctx for that specific curve.
*/
kctx = EVP_PKEY_CTX_new_id(curve->nid, NULL);
if (kctx == NULL) {
EVP_PKEY_CTX *pctx = NULL;
EVP_PKEY *params = NULL;
/*
* If we reach this code EVP_PKEY_CTX_new_id() failed and a
* "int_ctx_new:unsupported algorithm" error was added to the
* error queue.
* We remove it from the error queue as we are handling it.
*/
unsigned long error = ERR_peek_error();
if (error == ERR_peek_last_error() /* oldest and latest errors match */
/* check that the error origin matches */
&& ERR_GET_LIB(error) == ERR_LIB_EVP
&& (ERR_GET_REASON(error) == EVP_R_UNSUPPORTED_ALGORITHM
|| ERR_GET_REASON(error) == ERR_R_UNSUPPORTED))
ERR_get_error(); /* pop error from queue */
if (ERR_peek_error()) {
BIO_printf(bio_err,
"Unhandled error in the error queue during EC key setup.\n");
ERR_print_errors(bio_err);
return NULL;
}
/* Create the context for parameter generation */
if ((pctx = EVP_PKEY_CTX_new_from_name(NULL, "EC", NULL)) == NULL
|| EVP_PKEY_paramgen_init(pctx) <= 0
|| EVP_PKEY_CTX_set_ec_paramgen_curve_nid(pctx,
curve->nid) <= 0
|| EVP_PKEY_paramgen(pctx, &params) <= 0) {
BIO_printf(bio_err, "EC params init failure.\n");
ERR_print_errors(bio_err);
EVP_PKEY_CTX_free(pctx);
return NULL;
}
EVP_PKEY_CTX_free(pctx);
/* Create the context for the key generation */
kctx = EVP_PKEY_CTX_new(params, NULL);
EVP_PKEY_free(params);
}
if (kctx == NULL
|| EVP_PKEY_keygen_init(kctx) <= 0
|| EVP_PKEY_keygen(kctx, &key) <= 0) {
BIO_printf(bio_err, "EC key generation failure.\n");
ERR_print_errors(bio_err);
key = NULL;
}
EVP_PKEY_CTX_free(kctx);
return key;
}
#define stop_it(do_it, test_num)\
memset(do_it + test_num, 0, OSSL_NELEM(do_it) - test_num);
int speed_main(int argc, char **argv)
{
ENGINE *e = NULL;
loopargs_t *loopargs = NULL;
const char *prog;
const char *engine_id = NULL;
EVP_CIPHER *evp_cipher = NULL;
EVP_MAC *mac = NULL;
double d = 0.0;
OPTION_CHOICE o;
int async_init = 0, multiblock = 0, pr_header = 0;
uint8_t doit[ALGOR_NUM] = { 0 };
int ret = 1, misalign = 0, lengths_single = 0, aead = 0;
long count = 0;
unsigned int size_num = SIZE_NUM;
unsigned int i, k, loopargs_len = 0, async_jobs = 0;
int keylen;
int buflen;
BIGNUM *bn = NULL;
EVP_PKEY_CTX *genctx = NULL;
#ifndef NO_FORK
int multi = 0;
#endif
long op_count = 1;
openssl_speed_sec_t seconds = { SECONDS, RSA_SECONDS, DSA_SECONDS,
ECDSA_SECONDS, ECDH_SECONDS,
EdDSA_SECONDS, SM2_SECONDS,
FFDH_SECONDS };
static const unsigned char key32[32] = {
0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0,
0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12,
0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34,
0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56
};
static const unsigned char deskey[] = {
0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, /* key1 */
0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, /* key2 */
0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34 /* key3 */
};
static const struct {
const unsigned char *data;
unsigned int length;
unsigned int bits;
} rsa_keys[] = {
{ test512, sizeof(test512), 512 },
{ test1024, sizeof(test1024), 1024 },
{ test2048, sizeof(test2048), 2048 },
{ test3072, sizeof(test3072), 3072 },
{ test4096, sizeof(test4096), 4096 },
{ test7680, sizeof(test7680), 7680 },
{ test15360, sizeof(test15360), 15360 }
};
uint8_t rsa_doit[RSA_NUM] = { 0 };
int primes = RSA_DEFAULT_PRIME_NUM;
#ifndef OPENSSL_NO_DH
typedef struct ffdh_params_st {
const char *name;
unsigned int nid;
unsigned int bits;
} FFDH_PARAMS;
static const FFDH_PARAMS ffdh_params[FFDH_NUM] = {
{"ffdh2048", NID_ffdhe2048, 2048},
{"ffdh3072", NID_ffdhe3072, 3072},
{"ffdh4096", NID_ffdhe4096, 4096},
{"ffdh6144", NID_ffdhe6144, 6144},
{"ffdh8192", NID_ffdhe8192, 8192}
};
uint8_t ffdh_doit[FFDH_NUM] = { 0 };
#endif /* OPENSSL_NO_DH */
static const unsigned int dsa_bits[DSA_NUM] = { 512, 1024, 2048 };
uint8_t dsa_doit[DSA_NUM] = { 0 };
/*
* We only test over the following curves as they are representative, To
* add tests over more curves, simply add the curve NID and curve name to
* the following arrays and increase the |ecdh_choices| and |ecdsa_choices|
* lists accordingly.
*/
static const EC_CURVE ec_curves[EC_NUM] = {
/* Prime Curves */
{"secp160r1", NID_secp160r1, 160},
{"nistp192", NID_X9_62_prime192v1, 192},
{"nistp224", NID_secp224r1, 224},
{"nistp256", NID_X9_62_prime256v1, 256},
{"nistp384", NID_secp384r1, 384},
{"nistp521", NID_secp521r1, 521},
#ifndef OPENSSL_NO_EC2M
/* Binary Curves */
{"nistk163", NID_sect163k1, 163},
{"nistk233", NID_sect233k1, 233},
{"nistk283", NID_sect283k1, 283},
{"nistk409", NID_sect409k1, 409},
{"nistk571", NID_sect571k1, 571},
{"nistb163", NID_sect163r2, 163},
{"nistb233", NID_sect233r1, 233},
{"nistb283", NID_sect283r1, 283},
{"nistb409", NID_sect409r1, 409},
{"nistb571", NID_sect571r1, 571},
#endif
{"brainpoolP256r1", NID_brainpoolP256r1, 256},
{"brainpoolP256t1", NID_brainpoolP256t1, 256},
{"brainpoolP384r1", NID_brainpoolP384r1, 384},
{"brainpoolP384t1", NID_brainpoolP384t1, 384},
{"brainpoolP512r1", NID_brainpoolP512r1, 512},
{"brainpoolP512t1", NID_brainpoolP512t1, 512},
/* Other and ECDH only ones */
{"X25519", NID_X25519, 253},
{"X448", NID_X448, 448}
};
static const EC_CURVE ed_curves[EdDSA_NUM] = {
/* EdDSA */
{"Ed25519", NID_ED25519, 253, 64},
{"Ed448", NID_ED448, 456, 114}
};
#ifndef OPENSSL_NO_SM2
static const EC_CURVE sm2_curves[SM2_NUM] = {
/* SM2 */
{"CurveSM2", NID_sm2, 256}
};
uint8_t sm2_doit[SM2_NUM] = { 0 };
#endif
uint8_t ecdsa_doit[ECDSA_NUM] = { 0 };
uint8_t ecdh_doit[EC_NUM] = { 0 };
uint8_t eddsa_doit[EdDSA_NUM] = { 0 };
/* checks declarated curves against choices list. */
OPENSSL_assert(ed_curves[EdDSA_NUM - 1].nid == NID_ED448);
OPENSSL_assert(strcmp(eddsa_choices[EdDSA_NUM - 1].name, "ed448") == 0);
OPENSSL_assert(ec_curves[EC_NUM - 1].nid == NID_X448);
OPENSSL_assert(strcmp(ecdh_choices[EC_NUM - 1].name, "ecdhx448") == 0);
OPENSSL_assert(ec_curves[ECDSA_NUM - 1].nid == NID_brainpoolP512t1);
OPENSSL_assert(strcmp(ecdsa_choices[ECDSA_NUM - 1].name, "ecdsabrp512t1") == 0);
#ifndef OPENSSL_NO_SM2
OPENSSL_assert(sm2_curves[SM2_NUM - 1].nid == NID_sm2);
OPENSSL_assert(strcmp(sm2_choices[SM2_NUM - 1].name, "curveSM2") == 0);
#endif
prog = opt_init(argc, argv, speed_options);
while ((o = opt_next()) != OPT_EOF) {
switch (o) {
case OPT_EOF:
case OPT_ERR:
opterr:
BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
goto end;
case OPT_HELP:
opt_help(speed_options);
ret = 0;
goto end;
case OPT_ELAPSED:
usertime = 0;
break;
case OPT_EVP:
if (doit[D_EVP]) {
BIO_printf(bio_err, "%s: -evp option cannot be used more than once\n", prog);
goto opterr;
}
ERR_set_mark();
if (!opt_cipher_silent(opt_arg(), &evp_cipher)) {
if (have_md(opt_arg()))
evp_md_name = opt_arg();
}
if (evp_cipher == NULL && evp_md_name == NULL) {
ERR_clear_last_mark();
BIO_printf(bio_err,
"%s: %s is an unknown cipher or digest\n",
prog, opt_arg());
goto end;
}
ERR_pop_to_mark();
doit[D_EVP] = 1;
break;
case OPT_HMAC:
if (!have_md(opt_arg())) {
BIO_printf(bio_err, "%s: %s is an unknown digest\n",
prog, opt_arg());
goto end;
}
evp_mac_mdname = opt_arg();
doit[D_HMAC] = 1;
break;
case OPT_CMAC:
if (!have_cipher(opt_arg())) {
BIO_printf(bio_err, "%s: %s is an unknown cipher\n",
prog, opt_arg());
goto end;
}
evp_mac_ciphername = opt_arg();
doit[D_EVP_CMAC] = 1;
break;
case OPT_DECRYPT:
decrypt = 1;
break;
case OPT_ENGINE:
/*
* In a forked execution, an engine might need to be
* initialised by each child process, not by the parent.
* So store the name here and run setup_engine() later on.
*/
engine_id = opt_arg();
break;
case OPT_MULTI:
#ifndef NO_FORK
multi = atoi(opt_arg());
if ((size_t)multi >= SIZE_MAX / sizeof(int)) {
BIO_printf(bio_err, "%s: multi argument too large\n", prog);
return 0;
}
#endif
break;
case OPT_ASYNCJOBS:
#ifndef OPENSSL_NO_ASYNC
async_jobs = atoi(opt_arg());
if (!ASYNC_is_capable()) {
BIO_printf(bio_err,
"%s: async_jobs specified but async not supported\n",
prog);
goto opterr;
}
if (async_jobs > 99999) {
BIO_printf(bio_err, "%s: too many async_jobs\n", prog);
goto opterr;
}
#endif
break;
case OPT_MISALIGN:
misalign = opt_int_arg();
if (misalign > MISALIGN) {
BIO_printf(bio_err,
"%s: Maximum offset is %d\n", prog, MISALIGN);
goto opterr;
}
break;
case OPT_MR:
mr = 1;
break;
case OPT_MB:
multiblock = 1;
#ifdef OPENSSL_NO_MULTIBLOCK
BIO_printf(bio_err,
"%s: -mb specified but multi-block support is disabled\n",
prog);
goto end;
#endif
break;
case OPT_R_CASES:
if (!opt_rand(o))
goto end;
break;
case OPT_PROV_CASES:
if (!opt_provider(o))
goto end;
break;
case OPT_PRIMES:
primes = opt_int_arg();
break;
case OPT_SECONDS:
seconds.sym = seconds.rsa = seconds.dsa = seconds.ecdsa
= seconds.ecdh = seconds.eddsa
= seconds.sm2 = seconds.ffdh = atoi(opt_arg());
break;
case OPT_BYTES:
lengths_single = atoi(opt_arg());
lengths = &lengths_single;
size_num = 1;
break;
case OPT_AEAD:
aead = 1;
break;
}
}
/* Remaining arguments are algorithms. */
argc = opt_num_rest();
argv = opt_rest();
if (!app_RAND_load())
goto end;
for (; *argv; argv++) {
const char *algo = *argv;
if (opt_found(algo, doit_choices, &i)) {
doit[i] = 1;
continue;
}
if (strcmp(algo, "des") == 0) {
doit[D_CBC_DES] = doit[D_EDE3_DES] = 1;
continue;
}
if (strcmp(algo, "sha") == 0) {
doit[D_SHA1] = doit[D_SHA256] = doit[D_SHA512] = 1;
continue;
}
#ifndef OPENSSL_NO_DEPRECATED_3_0
if (strcmp(algo, "openssl") == 0) /* just for compatibility */
continue;
#endif
if (strncmp(algo, "rsa", 3) == 0) {
if (algo[3] == '\0') {
memset(rsa_doit, 1, sizeof(rsa_doit));
continue;
}
if (opt_found(algo, rsa_choices, &i)) {
rsa_doit[i] = 1;
continue;
}
}
#ifndef OPENSSL_NO_DH
if (strncmp(algo, "ffdh", 4) == 0) {
if (algo[4] == '\0') {
memset(ffdh_doit, 1, sizeof(ffdh_doit));
continue;
}
if (opt_found(algo, ffdh_choices, &i)) {
ffdh_doit[i] = 2;
continue;
}
}
#endif
if (strncmp(algo, "dsa", 3) == 0) {
if (algo[3] == '\0') {
memset(dsa_doit, 1, sizeof(dsa_doit));
continue;
}
if (opt_found(algo, dsa_choices, &i)) {
dsa_doit[i] = 2;
continue;
}
}
if (strcmp(algo, "aes") == 0) {
doit[D_CBC_128_AES] = doit[D_CBC_192_AES] = doit[D_CBC_256_AES] = 1;
continue;
}
if (strcmp(algo, "camellia") == 0) {
doit[D_CBC_128_CML] = doit[D_CBC_192_CML] = doit[D_CBC_256_CML] = 1;
continue;
}
if (strncmp(algo, "ecdsa", 5) == 0) {
if (algo[5] == '\0') {
memset(ecdsa_doit, 1, sizeof(ecdsa_doit));
continue;
}
if (opt_found(algo, ecdsa_choices, &i)) {
ecdsa_doit[i] = 2;
continue;
}
}
if (strncmp(algo, "ecdh", 4) == 0) {
if (algo[4] == '\0') {
memset(ecdh_doit, 1, sizeof(ecdh_doit));
continue;
}
if (opt_found(algo, ecdh_choices, &i)) {
ecdh_doit[i] = 2;
continue;
}
}
if (strcmp(algo, "eddsa") == 0) {
memset(eddsa_doit, 1, sizeof(eddsa_doit));
continue;
}
if (opt_found(algo, eddsa_choices, &i)) {
eddsa_doit[i] = 2;
continue;
}
#ifndef OPENSSL_NO_SM2
if (strcmp(algo, "sm2") == 0) {
memset(sm2_doit, 1, sizeof(sm2_doit));
continue;
}
if (opt_found(algo, sm2_choices, &i)) {
sm2_doit[i] = 2;
continue;
}
#endif
BIO_printf(bio_err, "%s: Unknown algorithm %s\n", prog, algo);
goto end;
}
/* Sanity checks */
if (aead) {
if (evp_cipher == NULL) {
BIO_printf(bio_err, "-aead can be used only with an AEAD cipher\n");
goto end;
} else if (!(EVP_CIPHER_get_flags(evp_cipher) &
EVP_CIPH_FLAG_AEAD_CIPHER)) {
BIO_printf(bio_err, "%s is not an AEAD cipher\n",
EVP_CIPHER_get0_name(evp_cipher));
goto end;
}
}
if (multiblock) {
if (evp_cipher == NULL) {
BIO_printf(bio_err, "-mb can be used only with a multi-block"
" capable cipher\n");
goto end;
} else if (!(EVP_CIPHER_get_flags(evp_cipher) &
EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK)) {
BIO_printf(bio_err, "%s is not a multi-block capable\n",
EVP_CIPHER_get0_name(evp_cipher));
goto end;
} else if (async_jobs > 0) {
BIO_printf(bio_err, "Async mode is not supported with -mb");
goto end;
}
}
/* Initialize the job pool if async mode is enabled */
if (async_jobs > 0) {
async_init = ASYNC_init_thread(async_jobs, async_jobs);
if (!async_init) {
BIO_printf(bio_err, "Error creating the ASYNC job pool\n");
goto end;
}
}
loopargs_len = (async_jobs == 0 ? 1 : async_jobs);
loopargs =
app_malloc(loopargs_len * sizeof(loopargs_t), "array of loopargs");
memset(loopargs, 0, loopargs_len * sizeof(loopargs_t));
for (i = 0; i < loopargs_len; i++) {
if (async_jobs > 0) {
loopargs[i].wait_ctx = ASYNC_WAIT_CTX_new();
if (loopargs[i].wait_ctx == NULL) {
BIO_printf(bio_err, "Error creating the ASYNC_WAIT_CTX\n");
goto end;
}
}
buflen = lengths[size_num - 1];
if (buflen < 36) /* size of random vector in RSA benchmark */
buflen = 36;
if (INT_MAX - (MAX_MISALIGNMENT + 1) < buflen) {
BIO_printf(bio_err, "Error: buffer size too large\n");
goto end;
}
buflen += MAX_MISALIGNMENT + 1;
loopargs[i].buf_malloc = app_malloc(buflen, "input buffer");
loopargs[i].buf2_malloc = app_malloc(buflen, "input buffer");
memset(loopargs[i].buf_malloc, 0, buflen);
memset(loopargs[i].buf2_malloc, 0, buflen);
/* Align the start of buffers on a 64 byte boundary */
loopargs[i].buf = loopargs[i].buf_malloc + misalign;
loopargs[i].buf2 = loopargs[i].buf2_malloc + misalign;
loopargs[i].buflen = buflen - misalign;
loopargs[i].sigsize = buflen - misalign;
loopargs[i].secret_a = app_malloc(MAX_ECDH_SIZE, "ECDH secret a");
loopargs[i].secret_b = app_malloc(MAX_ECDH_SIZE, "ECDH secret b");
#ifndef OPENSSL_NO_DH
loopargs[i].secret_ff_a = app_malloc(MAX_FFDH_SIZE, "FFDH secret a");
loopargs[i].secret_ff_b = app_malloc(MAX_FFDH_SIZE, "FFDH secret b");
#endif
}
#ifndef NO_FORK
if (multi && do_multi(multi, size_num))
goto show_res;
#endif
/* Initialize the engine after the fork */
e = setup_engine(engine_id, 0);
/* No parameters; turn on everything. */
if (argc == 0 && !doit[D_EVP] && !doit[D_HMAC] && !doit[D_EVP_CMAC]) {
memset(doit, 1, sizeof(doit));
doit[D_EVP] = doit[D_EVP_CMAC] = 0;
ERR_set_mark();
for (i = D_MD2; i <= D_WHIRLPOOL; i++) {
if (!have_md(names[i]))
doit[i] = 0;
}
for (i = D_CBC_DES; i <= D_CBC_256_CML; i++) {
if (!have_cipher(names[i]))
doit[i] = 0;
}
if ((mac = EVP_MAC_fetch(app_get0_libctx(), "GMAC",
app_get0_propq())) != NULL) {
EVP_MAC_free(mac);
mac = NULL;
} else {
doit[D_GHASH] = 0;
}
if ((mac = EVP_MAC_fetch(app_get0_libctx(), "HMAC",
app_get0_propq())) != NULL) {
EVP_MAC_free(mac);
mac = NULL;
} else {
doit[D_HMAC] = 0;
}
ERR_pop_to_mark();
memset(rsa_doit, 1, sizeof(rsa_doit));
#ifndef OPENSSL_NO_DH
memset(ffdh_doit, 1, sizeof(ffdh_doit));
#endif
memset(dsa_doit, 1, sizeof(dsa_doit));
memset(ecdsa_doit, 1, sizeof(ecdsa_doit));
memset(ecdh_doit, 1, sizeof(ecdh_doit));
memset(eddsa_doit, 1, sizeof(eddsa_doit));
#ifndef OPENSSL_NO_SM2
memset(sm2_doit, 1, sizeof(sm2_doit));
#endif
}
for (i = 0; i < ALGOR_NUM; i++)
if (doit[i])
pr_header++;
if (usertime == 0 && !mr)
BIO_printf(bio_err,
"You have chosen to measure elapsed time "
"instead of user CPU time.\n");
#if SIGALRM > 0
signal(SIGALRM, alarmed);
#endif
if (doit[D_MD2]) {
for (testnum = 0; testnum < size_num; testnum++) {
print_message(names[D_MD2], c[D_MD2][testnum], lengths[testnum],
seconds.sym);
Time_F(START);
count = run_benchmark(async_jobs, EVP_Digest_MD2_loop, loopargs);
d = Time_F(STOP);
print_result(D_MD2, testnum, count, d);
if (count < 0)
break;
}
}
if (doit[D_MDC2]) {
for (testnum = 0; testnum < size_num; testnum++) {
print_message(names[D_MDC2], c[D_MDC2][testnum], lengths[testnum],
seconds.sym);
Time_F(START);
count = run_benchmark(async_jobs, EVP_Digest_MDC2_loop, loopargs);
d = Time_F(STOP);
print_result(D_MDC2, testnum, count, d);
if (count < 0)
break;
}
}
if (doit[D_MD4]) {
for (testnum = 0; testnum < size_num; testnum++) {
print_message(names[D_MD4], c[D_MD4][testnum], lengths[testnum],
seconds.sym);
Time_F(START);
count = run_benchmark(async_jobs, EVP_Digest_MD4_loop, loopargs);
d = Time_F(STOP);
print_result(D_MD4, testnum, count, d);
if (count < 0)
break;
}
}
if (doit[D_MD5]) {
for (testnum = 0; testnum < size_num; testnum++) {
print_message(names[D_MD5], c[D_MD5][testnum], lengths[testnum],
seconds.sym);
Time_F(START);
count = run_benchmark(async_jobs, MD5_loop, loopargs);
d = Time_F(STOP);
print_result(D_MD5, testnum, count, d);
if (count < 0)
break;
}
}
if (doit[D_SHA1]) {
for (testnum = 0; testnum < size_num; testnum++) {
print_message(names[D_SHA1], c[D_SHA1][testnum], lengths[testnum],
seconds.sym);
Time_F(START);
count = run_benchmark(async_jobs, SHA1_loop, loopargs);
d = Time_F(STOP);
print_result(D_SHA1, testnum, count, d);
if (count < 0)
break;
}
}
if (doit[D_SHA256]) {
for (testnum = 0; testnum < size_num; testnum++) {
print_message(names[D_SHA256], c[D_SHA256][testnum],
lengths[testnum], seconds.sym);
Time_F(START);
count = run_benchmark(async_jobs, SHA256_loop, loopargs);
d = Time_F(STOP);
print_result(D_SHA256, testnum, count, d);
if (count < 0)
break;
}
}
if (doit[D_SHA512]) {
for (testnum = 0; testnum < size_num; testnum++) {
print_message(names[D_SHA512], c[D_SHA512][testnum],
lengths[testnum], seconds.sym);
Time_F(START);
count = run_benchmark(async_jobs, SHA512_loop, loopargs);
d = Time_F(STOP);
print_result(D_SHA512, testnum, count, d);
if (count < 0)
break;
}
}
if (doit[D_WHIRLPOOL]) {
for (testnum = 0; testnum < size_num; testnum++) {
print_message(names[D_WHIRLPOOL], c[D_WHIRLPOOL][testnum],
lengths[testnum], seconds.sym);
Time_F(START);
count = run_benchmark(async_jobs, WHIRLPOOL_loop, loopargs);
d = Time_F(STOP);
print_result(D_WHIRLPOOL, testnum, count, d);
if (count < 0)
break;
}
}
if (doit[D_RMD160]) {
for (testnum = 0; testnum < size_num; testnum++) {
print_message(names[D_RMD160], c[D_RMD160][testnum],
lengths[testnum], seconds.sym);
Time_F(START);
count = run_benchmark(async_jobs, EVP_Digest_RMD160_loop, loopargs);
d = Time_F(STOP);
print_result(D_RMD160, testnum, count, d);
if (count < 0)
break;
}
}
if (doit[D_HMAC]) {
static const char hmac_key[] = "This is a key...";
int len = strlen(hmac_key);
OSSL_PARAM params[3];
mac = EVP_MAC_fetch(app_get0_libctx(), "HMAC", app_get0_propq());
if (mac == NULL || evp_mac_mdname == NULL)
goto end;
evp_hmac_name = app_malloc(sizeof("hmac()") + strlen(evp_mac_mdname),
"HMAC name");
sprintf(evp_hmac_name, "hmac(%s)", evp_mac_mdname);
names[D_HMAC] = evp_hmac_name;
params[0] =
OSSL_PARAM_construct_utf8_string(OSSL_MAC_PARAM_DIGEST,
evp_mac_mdname, 0);
params[1] =
OSSL_PARAM_construct_octet_string(OSSL_MAC_PARAM_KEY,
(char *)hmac_key, len);
params[2] = OSSL_PARAM_construct_end();
for (i = 0; i < loopargs_len; i++) {
loopargs[i].mctx = EVP_MAC_CTX_new(mac);
if (loopargs[i].mctx == NULL)
goto end;
if (!EVP_MAC_CTX_set_params(loopargs[i].mctx, params))
goto skip_hmac; /* Digest not found */
}
for (testnum = 0; testnum < size_num; testnum++) {
print_message(names[D_HMAC], c[D_HMAC][testnum], lengths[testnum],
seconds.sym);
Time_F(START);
count = run_benchmark(async_jobs, HMAC_loop, loopargs);
d = Time_F(STOP);
print_result(D_HMAC, testnum, count, d);
if (count < 0)
break;
}
for (i = 0; i < loopargs_len; i++)
EVP_MAC_CTX_free(loopargs[i].mctx);
EVP_MAC_free(mac);
mac = NULL;
}
skip_hmac:
if (doit[D_CBC_DES]) {
int st = 1;
for (i = 0; st && i < loopargs_len; i++) {
loopargs[i].ctx = init_evp_cipher_ctx("des-cbc", deskey,
sizeof(deskey) / 3);
st = loopargs[i].ctx != NULL;
}
algindex = D_CBC_DES;
for (testnum = 0; st && testnum < size_num; testnum++) {
print_message(names[D_CBC_DES], c[D_CBC_DES][testnum],
lengths[testnum], seconds.sym);
Time_F(START);
count = run_benchmark(async_jobs, EVP_Cipher_loop, loopargs);
d = Time_F(STOP);
print_result(D_CBC_DES, testnum, count, d);
}
for (i = 0; i < loopargs_len; i++)
EVP_CIPHER_CTX_free(loopargs[i].ctx);
}
if (doit[D_EDE3_DES]) {
int st = 1;
for (i = 0; st && i < loopargs_len; i++) {
loopargs[i].ctx = init_evp_cipher_ctx("des-ede3-cbc", deskey,
sizeof(deskey));
st = loopargs[i].ctx != NULL;
}
algindex = D_EDE3_DES;
for (testnum = 0; st && testnum < size_num; testnum++) {
print_message(names[D_EDE3_DES], c[D_EDE3_DES][testnum],
lengths[testnum], seconds.sym);
Time_F(START);
count =
run_benchmark(async_jobs, EVP_Cipher_loop, loopargs);
d = Time_F(STOP);
print_result(D_EDE3_DES, testnum, count, d);
}
for (i = 0; i < loopargs_len; i++)
EVP_CIPHER_CTX_free(loopargs[i].ctx);
}
for (k = 0; k < 3; k++) {
algindex = D_CBC_128_AES + k;
if (doit[algindex]) {
int st = 1;
keylen = 16 + k * 8;
for (i = 0; st && i < loopargs_len; i++) {
loopargs[i].ctx = init_evp_cipher_ctx(names[algindex],
key32, keylen);
st = loopargs[i].ctx != NULL;
}
for (testnum = 0; st && testnum < size_num; testnum++) {
print_message(names[algindex], c[algindex][testnum],
lengths[testnum], seconds.sym);
Time_F(START);
count =
run_benchmark(async_jobs, EVP_Cipher_loop, loopargs);
d = Time_F(STOP);
print_result(algindex, testnum, count, d);
}
for (i = 0; i < loopargs_len; i++)
EVP_CIPHER_CTX_free(loopargs[i].ctx);
}
}
for (k = 0; k < 3; k++) {
algindex = D_CBC_128_CML + k;
if (doit[algindex]) {
int st = 1;
keylen = 16 + k * 8;
for (i = 0; st && i < loopargs_len; i++) {
loopargs[i].ctx = init_evp_cipher_ctx(names[algindex],
key32, keylen);
st = loopargs[i].ctx != NULL;
}
for (testnum = 0; st && testnum < size_num; testnum++) {
print_message(names[algindex], c[algindex][testnum],
lengths[testnum], seconds.sym);
Time_F(START);
count =
run_benchmark(async_jobs, EVP_Cipher_loop, loopargs);
d = Time_F(STOP);
print_result(algindex, testnum, count, d);
}
for (i = 0; i < loopargs_len; i++)
EVP_CIPHER_CTX_free(loopargs[i].ctx);
}
}
for (algindex = D_RC4; algindex <= D_CBC_CAST; algindex++) {
if (doit[algindex]) {
int st = 1;
keylen = 16;
for (i = 0; st && i < loopargs_len; i++) {
loopargs[i].ctx = init_evp_cipher_ctx(names[algindex],
key32, keylen);
st = loopargs[i].ctx != NULL;
}
for (testnum = 0; st && testnum < size_num; testnum++) {
print_message(names[algindex], c[algindex][testnum],
lengths[testnum], seconds.sym);
Time_F(START);
count =
run_benchmark(async_jobs, EVP_Cipher_loop, loopargs);
d = Time_F(STOP);
print_result(algindex, testnum, count, d);
}
for (i = 0; i < loopargs_len; i++)
EVP_CIPHER_CTX_free(loopargs[i].ctx);
}
}
if (doit[D_GHASH]) {
static const char gmac_iv[] = "0123456789ab";
OSSL_PARAM params[3];
mac = EVP_MAC_fetch(app_get0_libctx(), "GMAC", app_get0_propq());
if (mac == NULL)
goto end;
params[0] = OSSL_PARAM_construct_utf8_string(OSSL_ALG_PARAM_CIPHER,
"aes-128-gcm", 0);
params[1] = OSSL_PARAM_construct_octet_string(OSSL_MAC_PARAM_IV,
(char *)gmac_iv,
sizeof(gmac_iv) - 1);
params[2] = OSSL_PARAM_construct_end();
for (i = 0; i < loopargs_len; i++) {
loopargs[i].mctx = EVP_MAC_CTX_new(mac);
if (loopargs[i].mctx == NULL)
goto end;
if (!EVP_MAC_init(loopargs[i].mctx, key32, 16, params))
goto end;
}
for (testnum = 0; testnum < size_num; testnum++) {
print_message(names[D_GHASH], c[D_GHASH][testnum], lengths[testnum],
seconds.sym);
Time_F(START);
count = run_benchmark(async_jobs, GHASH_loop, loopargs);
d = Time_F(STOP);
print_result(D_GHASH, testnum, count, d);
if (count < 0)
break;
}
for (i = 0; i < loopargs_len; i++)
EVP_MAC_CTX_free(loopargs[i].mctx);
EVP_MAC_free(mac);
mac = NULL;
}
if (doit[D_RAND]) {
for (testnum = 0; testnum < size_num; testnum++) {
print_message(names[D_RAND], c[D_RAND][testnum], lengths[testnum],
seconds.sym);
Time_F(START);
count = run_benchmark(async_jobs, RAND_bytes_loop, loopargs);
d = Time_F(STOP);
print_result(D_RAND, testnum, count, d);
}
}
if (doit[D_EVP]) {
if (evp_cipher != NULL) {
int (*loopfunc) (void *) = EVP_Update_loop;
if (multiblock && (EVP_CIPHER_get_flags(evp_cipher) &
EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK)) {
multiblock_speed(evp_cipher, lengths_single, &seconds);
ret = 0;
goto end;
}
names[D_EVP] = EVP_CIPHER_get0_name(evp_cipher);
if (EVP_CIPHER_get_mode(evp_cipher) == EVP_CIPH_CCM_MODE) {
loopfunc = EVP_Update_loop_ccm;
} else if (aead && (EVP_CIPHER_get_flags(evp_cipher) &
EVP_CIPH_FLAG_AEAD_CIPHER)) {
loopfunc = EVP_Update_loop_aead;
if (lengths == lengths_list) {
lengths = aead_lengths_list;
size_num = OSSL_NELEM(aead_lengths_list);
}
}
for (testnum = 0; testnum < size_num; testnum++) {
print_message(names[D_EVP], c[D_EVP][testnum], lengths[testnum],
seconds.sym);
for (k = 0; k < loopargs_len; k++) {
loopargs[k].ctx = EVP_CIPHER_CTX_new();
if (loopargs[k].ctx == NULL) {
BIO_printf(bio_err, "\nEVP_CIPHER_CTX_new failure\n");
exit(1);
}
if (!EVP_CipherInit_ex(loopargs[k].ctx, evp_cipher, NULL,
NULL, iv, decrypt ? 0 : 1)) {
BIO_printf(bio_err, "\nEVP_CipherInit_ex failure\n");
ERR_print_errors(bio_err);
exit(1);
}
EVP_CIPHER_CTX_set_padding(loopargs[k].ctx, 0);
keylen = EVP_CIPHER_CTX_get_key_length(loopargs[k].ctx);
loopargs[k].key = app_malloc(keylen, "evp_cipher key");
EVP_CIPHER_CTX_rand_key(loopargs[k].ctx, loopargs[k].key);
if (!EVP_CipherInit_ex(loopargs[k].ctx, NULL, NULL,
loopargs[k].key, NULL, -1)) {
BIO_printf(bio_err, "\nEVP_CipherInit_ex failure\n");
ERR_print_errors(bio_err);
exit(1);
}
OPENSSL_clear_free(loopargs[k].key, keylen);
/* SIV mode only allows for a single Update operation */
if (EVP_CIPHER_get_mode(evp_cipher) == EVP_CIPH_SIV_MODE)
(void)EVP_CIPHER_CTX_ctrl(loopargs[k].ctx,
EVP_CTRL_SET_SPEED, 1, NULL);
}
Time_F(START);
count = run_benchmark(async_jobs, loopfunc, loopargs);
d = Time_F(STOP);
for (k = 0; k < loopargs_len; k++)
EVP_CIPHER_CTX_free(loopargs[k].ctx);
print_result(D_EVP, testnum, count, d);
}
} else if (evp_md_name != NULL) {
names[D_EVP] = evp_md_name;
for (testnum = 0; testnum < size_num; testnum++) {
print_message(names[D_EVP], c[D_EVP][testnum], lengths[testnum],
seconds.sym);
Time_F(START);
count = run_benchmark(async_jobs, EVP_Digest_md_loop, loopargs);
d = Time_F(STOP);
print_result(D_EVP, testnum, count, d);
if (count < 0)
break;
}
}
}
if (doit[D_EVP_CMAC]) {
OSSL_PARAM params[3];
EVP_CIPHER *cipher = NULL;
mac = EVP_MAC_fetch(app_get0_libctx(), "CMAC", app_get0_propq());
if (mac == NULL || evp_mac_ciphername == NULL)
goto end;
if (!opt_cipher(evp_mac_ciphername, &cipher))
goto end;
keylen = EVP_CIPHER_get_key_length(cipher);
EVP_CIPHER_free(cipher);
if (keylen <= 0 || keylen > (int)sizeof(key32)) {
BIO_printf(bio_err, "\nRequested CMAC cipher with unsupported key length.\n");
goto end;
}
evp_cmac_name = app_malloc(sizeof("cmac()")
+ strlen(evp_mac_ciphername), "CMAC name");
sprintf(evp_cmac_name, "cmac(%s)", evp_mac_ciphername);
names[D_EVP_CMAC] = evp_cmac_name;
params[0] = OSSL_PARAM_construct_utf8_string(OSSL_ALG_PARAM_CIPHER,
evp_mac_ciphername, 0);
params[1] = OSSL_PARAM_construct_octet_string(OSSL_MAC_PARAM_KEY,
(char *)key32, keylen);
params[2] = OSSL_PARAM_construct_end();
for (i = 0; i < loopargs_len; i++) {
loopargs[i].mctx = EVP_MAC_CTX_new(mac);
if (loopargs[i].mctx == NULL)
goto end;
if (!EVP_MAC_CTX_set_params(loopargs[i].mctx, params))
goto end;
}
for (testnum = 0; testnum < size_num; testnum++) {
print_message(names[D_EVP_CMAC], c[D_EVP_CMAC][testnum],
lengths[testnum], seconds.sym);
Time_F(START);
count = run_benchmark(async_jobs, CMAC_loop, loopargs);
d = Time_F(STOP);
print_result(D_EVP_CMAC, testnum, count, d);
if (count < 0)
break;
}
for (i = 0; i < loopargs_len; i++)
EVP_MAC_CTX_free(loopargs[i].mctx);
EVP_MAC_free(mac);
mac = NULL;
}
for (i = 0; i < loopargs_len; i++)
if (RAND_bytes(loopargs[i].buf, 36) <= 0)
goto end;
for (testnum = 0; testnum < RSA_NUM; testnum++) {
EVP_PKEY *rsa_key = NULL;
int st = 0;
if (!rsa_doit[testnum])
continue;
if (primes > RSA_DEFAULT_PRIME_NUM) {
/* we haven't set keys yet, generate multi-prime RSA keys */
bn = BN_new();
st = bn != NULL
&& BN_set_word(bn, RSA_F4)
&& init_gen_str(&genctx, "RSA", NULL, 0, NULL, NULL)
&& EVP_PKEY_CTX_set_rsa_keygen_bits(genctx, rsa_keys[testnum].bits) > 0
&& EVP_PKEY_CTX_set1_rsa_keygen_pubexp(genctx, bn) > 0
&& EVP_PKEY_CTX_set_rsa_keygen_primes(genctx, primes) > 0
&& EVP_PKEY_keygen(genctx, &rsa_key);
BN_free(bn);
bn = NULL;
EVP_PKEY_CTX_free(genctx);
genctx = NULL;
} else {
const unsigned char *p = rsa_keys[testnum].data;
st = (rsa_key = d2i_PrivateKey(EVP_PKEY_RSA, NULL, &p,
rsa_keys[testnum].length)) != NULL;
}
for (i = 0; st && i < loopargs_len; i++) {
loopargs[i].rsa_sign_ctx[testnum] = EVP_PKEY_CTX_new(rsa_key, NULL);
loopargs[i].sigsize = loopargs[i].buflen;
if (loopargs[i].rsa_sign_ctx[testnum] == NULL
|| EVP_PKEY_sign_init(loopargs[i].rsa_sign_ctx[testnum]) <= 0
|| EVP_PKEY_sign(loopargs[i].rsa_sign_ctx[testnum],
loopargs[i].buf2,
&loopargs[i].sigsize,
loopargs[i].buf, 36) <= 0)
st = 0;
}
if (!st) {
BIO_printf(bio_err,
"RSA sign setup failure. No RSA sign will be done.\n");
ERR_print_errors(bio_err);
op_count = 1;
} else {
pkey_print_message("private", "rsa",
rsa_c[testnum][0], rsa_keys[testnum].bits,
seconds.rsa);
/* RSA_blinding_on(rsa_key[testnum],NULL); */
Time_F(START);
count = run_benchmark(async_jobs, RSA_sign_loop, loopargs);
d = Time_F(STOP);
BIO_printf(bio_err,
mr ? "+R1:%ld:%d:%.2f\n"
: "%ld %u bits private RSA's in %.2fs\n",
count, rsa_keys[testnum].bits, d);
rsa_results[testnum][0] = (double)count / d;
op_count = count;
}
for (i = 0; st && i < loopargs_len; i++) {
loopargs[i].rsa_verify_ctx[testnum] = EVP_PKEY_CTX_new(rsa_key,
NULL);
if (loopargs[i].rsa_verify_ctx[testnum] == NULL
|| EVP_PKEY_verify_init(loopargs[i].rsa_verify_ctx[testnum]) <= 0
|| EVP_PKEY_verify(loopargs[i].rsa_verify_ctx[testnum],
loopargs[i].buf2,
loopargs[i].sigsize,
loopargs[i].buf, 36) <= 0)
st = 0;
}
if (!st) {
BIO_printf(bio_err,
"RSA verify setup failure. No RSA verify will be done.\n");
ERR_print_errors(bio_err);
rsa_doit[testnum] = 0;
} else {
pkey_print_message("public", "rsa",
rsa_c[testnum][1], rsa_keys[testnum].bits,
seconds.rsa);
Time_F(START);
count = run_benchmark(async_jobs, RSA_verify_loop, loopargs);
d = Time_F(STOP);
BIO_printf(bio_err,
mr ? "+R2:%ld:%d:%.2f\n"
: "%ld %u bits public RSA's in %.2fs\n",
count, rsa_keys[testnum].bits, d);
rsa_results[testnum][1] = (double)count / d;
}
if (op_count <= 1) {
/* if longer than 10s, don't do any more */
stop_it(rsa_doit, testnum);
}
EVP_PKEY_free(rsa_key);
}
for (testnum = 0; testnum < DSA_NUM; testnum++) {
EVP_PKEY *dsa_key = NULL;
int st;
if (!dsa_doit[testnum])
continue;
st = (dsa_key = get_dsa(dsa_bits[testnum])) != NULL;
for (i = 0; st && i < loopargs_len; i++) {
loopargs[i].dsa_sign_ctx[testnum] = EVP_PKEY_CTX_new(dsa_key,
NULL);
loopargs[i].sigsize = loopargs[i].buflen;
if (loopargs[i].dsa_sign_ctx[testnum] == NULL
|| EVP_PKEY_sign_init(loopargs[i].dsa_sign_ctx[testnum]) <= 0
|| EVP_PKEY_sign(loopargs[i].dsa_sign_ctx[testnum],
loopargs[i].buf2,
&loopargs[i].sigsize,
loopargs[i].buf, 20) <= 0)
st = 0;
}
if (!st) {
BIO_printf(bio_err,
"DSA sign setup failure. No DSA sign will be done.\n");
ERR_print_errors(bio_err);
op_count = 1;
} else {
pkey_print_message("sign", "dsa",
dsa_c[testnum][0], dsa_bits[testnum],
seconds.dsa);
Time_F(START);
count = run_benchmark(async_jobs, DSA_sign_loop, loopargs);
d = Time_F(STOP);
BIO_printf(bio_err,
mr ? "+R3:%ld:%u:%.2f\n"
: "%ld %u bits DSA signs in %.2fs\n",
count, dsa_bits[testnum], d);
dsa_results[testnum][0] = (double)count / d;
op_count = count;
}
for (i = 0; st && i < loopargs_len; i++) {
loopargs[i].dsa_verify_ctx[testnum] = EVP_PKEY_CTX_new(dsa_key,
NULL);
if (loopargs[i].dsa_verify_ctx[testnum] == NULL
|| EVP_PKEY_verify_init(loopargs[i].dsa_verify_ctx[testnum]) <= 0
|| EVP_PKEY_verify(loopargs[i].dsa_verify_ctx[testnum],
loopargs[i].buf2,
loopargs[i].sigsize,
loopargs[i].buf, 36) <= 0)
st = 0;
}
if (!st) {
BIO_printf(bio_err,
"DSA verify setup failure. No DSA verify will be done.\n");
ERR_print_errors(bio_err);
dsa_doit[testnum] = 0;
} else {
pkey_print_message("verify", "dsa",
dsa_c[testnum][1], dsa_bits[testnum],
seconds.dsa);
Time_F(START);
count = run_benchmark(async_jobs, DSA_verify_loop, loopargs);
d = Time_F(STOP);
BIO_printf(bio_err,
mr ? "+R4:%ld:%u:%.2f\n"
: "%ld %u bits DSA verify in %.2fs\n",
count, dsa_bits[testnum], d);
dsa_results[testnum][1] = (double)count / d;
}
if (op_count <= 1) {
/* if longer than 10s, don't do any more */
stop_it(dsa_doit, testnum);
}
EVP_PKEY_free(dsa_key);
}
for (testnum = 0; testnum < ECDSA_NUM; testnum++) {
EVP_PKEY *ecdsa_key = NULL;
int st;
if (!ecdsa_doit[testnum])
continue;
st = (ecdsa_key = get_ecdsa(&ec_curves[testnum])) != NULL;
for (i = 0; st && i < loopargs_len; i++) {
loopargs[i].ecdsa_sign_ctx[testnum] = EVP_PKEY_CTX_new(ecdsa_key,
NULL);
loopargs[i].sigsize = loopargs[i].buflen;
if (loopargs[i].ecdsa_sign_ctx[testnum] == NULL
|| EVP_PKEY_sign_init(loopargs[i].ecdsa_sign_ctx[testnum]) <= 0
|| EVP_PKEY_sign(loopargs[i].ecdsa_sign_ctx[testnum],
loopargs[i].buf2,
&loopargs[i].sigsize,
loopargs[i].buf, 20) <= 0)
st = 0;
}
if (!st) {
BIO_printf(bio_err,
"ECDSA sign setup failure. No ECDSA sign will be done.\n");
ERR_print_errors(bio_err);
op_count = 1;
} else {
pkey_print_message("sign", "ecdsa",
ecdsa_c[testnum][0], ec_curves[testnum].bits,
seconds.ecdsa);
Time_F(START);
count = run_benchmark(async_jobs, ECDSA_sign_loop, loopargs);
d = Time_F(STOP);
BIO_printf(bio_err,
mr ? "+R5:%ld:%u:%.2f\n"
: "%ld %u bits ECDSA signs in %.2fs\n",
count, ec_curves[testnum].bits, d);
ecdsa_results[testnum][0] = (double)count / d;
op_count = count;
}
for (i = 0; st && i < loopargs_len; i++) {
loopargs[i].ecdsa_verify_ctx[testnum] = EVP_PKEY_CTX_new(ecdsa_key,
NULL);
if (loopargs[i].ecdsa_verify_ctx[testnum] == NULL
|| EVP_PKEY_verify_init(loopargs[i].ecdsa_verify_ctx[testnum]) <= 0
|| EVP_PKEY_verify(loopargs[i].ecdsa_verify_ctx[testnum],
loopargs[i].buf2,
loopargs[i].sigsize,
loopargs[i].buf, 20) <= 0)
st = 0;
}
if (!st) {
BIO_printf(bio_err,
"ECDSA verify setup failure. No ECDSA verify will be done.\n");
ERR_print_errors(bio_err);
ecdsa_doit[testnum] = 0;
} else {
pkey_print_message("verify", "ecdsa",
ecdsa_c[testnum][1], ec_curves[testnum].bits,
seconds.ecdsa);
Time_F(START);
count = run_benchmark(async_jobs, ECDSA_verify_loop, loopargs);
d = Time_F(STOP);
BIO_printf(bio_err,
mr ? "+R6:%ld:%u:%.2f\n"
: "%ld %u bits ECDSA verify in %.2fs\n",
count, ec_curves[testnum].bits, d);
ecdsa_results[testnum][1] = (double)count / d;
}
if (op_count <= 1) {
/* if longer than 10s, don't do any more */
stop_it(ecdsa_doit, testnum);
}
}
for (testnum = 0; testnum < EC_NUM; testnum++) {
int ecdh_checks = 1;
if (!ecdh_doit[testnum])
continue;
for (i = 0; i < loopargs_len; i++) {
EVP_PKEY_CTX *test_ctx = NULL;
EVP_PKEY_CTX *ctx = NULL;
EVP_PKEY *key_A = NULL;
EVP_PKEY *key_B = NULL;
size_t outlen;
size_t test_outlen;
if ((key_A = get_ecdsa(&ec_curves[testnum])) == NULL /* generate secret key A */
|| (key_B = get_ecdsa(&ec_curves[testnum])) == NULL /* generate secret key B */
|| (ctx = EVP_PKEY_CTX_new(key_A, NULL)) == NULL /* derivation ctx from skeyA */
|| EVP_PKEY_derive_init(ctx) <= 0 /* init derivation ctx */
|| EVP_PKEY_derive_set_peer(ctx, key_B) <= 0 /* set peer pubkey in ctx */
|| EVP_PKEY_derive(ctx, NULL, &outlen) <= 0 /* determine max length */
|| outlen == 0 /* ensure outlen is a valid size */
|| outlen > MAX_ECDH_SIZE /* avoid buffer overflow */) {
ecdh_checks = 0;
BIO_printf(bio_err, "ECDH key generation failure.\n");
ERR_print_errors(bio_err);
op_count = 1;
break;
}
/*
* Here we perform a test run, comparing the output of a*B and b*A;
* we try this here and assume that further EVP_PKEY_derive calls
* never fail, so we can skip checks in the actually benchmarked
* code, for maximum performance.
*/
if ((test_ctx = EVP_PKEY_CTX_new(key_B, NULL)) == NULL /* test ctx from skeyB */
|| EVP_PKEY_derive_init(test_ctx) <= 0 /* init derivation test_ctx */
|| EVP_PKEY_derive_set_peer(test_ctx, key_A) <= 0 /* set peer pubkey in test_ctx */
|| EVP_PKEY_derive(test_ctx, NULL, &test_outlen) <= 0 /* determine max length */
|| EVP_PKEY_derive(ctx, loopargs[i].secret_a, &outlen) <= 0 /* compute a*B */
|| EVP_PKEY_derive(test_ctx, loopargs[i].secret_b, &test_outlen) <= 0 /* compute b*A */
|| test_outlen != outlen /* compare output length */) {
ecdh_checks = 0;
BIO_printf(bio_err, "ECDH computation failure.\n");
ERR_print_errors(bio_err);
op_count = 1;
break;
}
/* Compare the computation results: CRYPTO_memcmp() returns 0 if equal */
if (CRYPTO_memcmp(loopargs[i].secret_a,
loopargs[i].secret_b, outlen)) {
ecdh_checks = 0;
BIO_printf(bio_err, "ECDH computations don't match.\n");
ERR_print_errors(bio_err);
op_count = 1;
break;
}
loopargs[i].ecdh_ctx[testnum] = ctx;
loopargs[i].outlen[testnum] = outlen;
EVP_PKEY_free(key_A);
EVP_PKEY_free(key_B);
EVP_PKEY_CTX_free(test_ctx);
test_ctx = NULL;
}
if (ecdh_checks != 0) {
pkey_print_message("", "ecdh",
ecdh_c[testnum][0],
ec_curves[testnum].bits, seconds.ecdh);
Time_F(START);
count =
run_benchmark(async_jobs, ECDH_EVP_derive_key_loop, loopargs);
d = Time_F(STOP);
BIO_printf(bio_err,
mr ? "+R7:%ld:%d:%.2f\n" :
"%ld %u-bits ECDH ops in %.2fs\n", count,
ec_curves[testnum].bits, d);
ecdh_results[testnum][0] = (double)count / d;
op_count = count;
}
if (op_count <= 1) {
/* if longer than 10s, don't do any more */
stop_it(ecdh_doit, testnum);
}
}
for (testnum = 0; testnum < EdDSA_NUM; testnum++) {
int st = 1;
EVP_PKEY *ed_pkey = NULL;
EVP_PKEY_CTX *ed_pctx = NULL;
if (!eddsa_doit[testnum])
continue; /* Ignore Curve */
for (i = 0; i < loopargs_len; i++) {
loopargs[i].eddsa_ctx[testnum] = EVP_MD_CTX_new();
if (loopargs[i].eddsa_ctx[testnum] == NULL) {
st = 0;
break;
}
loopargs[i].eddsa_ctx2[testnum] = EVP_MD_CTX_new();
if (loopargs[i].eddsa_ctx2[testnum] == NULL) {
st = 0;
break;
}
if ((ed_pctx = EVP_PKEY_CTX_new_id(ed_curves[testnum].nid,
NULL)) == NULL
|| EVP_PKEY_keygen_init(ed_pctx) <= 0
|| EVP_PKEY_keygen(ed_pctx, &ed_pkey) <= 0) {
st = 0;
EVP_PKEY_CTX_free(ed_pctx);
break;
}
EVP_PKEY_CTX_free(ed_pctx);
if (!EVP_DigestSignInit(loopargs[i].eddsa_ctx[testnum], NULL, NULL,
NULL, ed_pkey)) {
st = 0;
EVP_PKEY_free(ed_pkey);
break;
}
if (!EVP_DigestVerifyInit(loopargs[i].eddsa_ctx2[testnum], NULL,
NULL, NULL, ed_pkey)) {
st = 0;
EVP_PKEY_free(ed_pkey);
break;
}
EVP_PKEY_free(ed_pkey);
ed_pkey = NULL;
}
if (st == 0) {
BIO_printf(bio_err, "EdDSA failure.\n");
ERR_print_errors(bio_err);
op_count = 1;
} else {
for (i = 0; i < loopargs_len; i++) {
/* Perform EdDSA signature test */
loopargs[i].sigsize = ed_curves[testnum].sigsize;
st = EVP_DigestSign(loopargs[i].eddsa_ctx[testnum],
loopargs[i].buf2, &loopargs[i].sigsize,
loopargs[i].buf, 20);
if (st == 0)
break;
}
if (st == 0) {
BIO_printf(bio_err,
"EdDSA sign failure. No EdDSA sign will be done.\n");
ERR_print_errors(bio_err);
op_count = 1;
} else {
pkey_print_message("sign", ed_curves[testnum].name,
eddsa_c[testnum][0],
ed_curves[testnum].bits, seconds.eddsa);
Time_F(START);
count = run_benchmark(async_jobs, EdDSA_sign_loop, loopargs);
d = Time_F(STOP);
BIO_printf(bio_err,
mr ? "+R8:%ld:%u:%s:%.2f\n" :
"%ld %u bits %s signs in %.2fs \n",
count, ed_curves[testnum].bits,
ed_curves[testnum].name, d);
eddsa_results[testnum][0] = (double)count / d;
op_count = count;
}
/* Perform EdDSA verification test */
for (i = 0; i < loopargs_len; i++) {
st = EVP_DigestVerify(loopargs[i].eddsa_ctx2[testnum],
loopargs[i].buf2, loopargs[i].sigsize,
loopargs[i].buf, 20);
if (st != 1)
break;
}
if (st != 1) {
BIO_printf(bio_err,
"EdDSA verify failure. No EdDSA verify will be done.\n");
ERR_print_errors(bio_err);
eddsa_doit[testnum] = 0;
} else {
pkey_print_message("verify", ed_curves[testnum].name,
eddsa_c[testnum][1],
ed_curves[testnum].bits, seconds.eddsa);
Time_F(START);
count = run_benchmark(async_jobs, EdDSA_verify_loop, loopargs);
d = Time_F(STOP);
BIO_printf(bio_err,
mr ? "+R9:%ld:%u:%s:%.2f\n"
: "%ld %u bits %s verify in %.2fs\n",
count, ed_curves[testnum].bits,
ed_curves[testnum].name, d);
eddsa_results[testnum][1] = (double)count / d;
}
if (op_count <= 1) {
/* if longer than 10s, don't do any more */
stop_it(eddsa_doit, testnum);
}
}
}
#ifndef OPENSSL_NO_SM2
for (testnum = 0; testnum < SM2_NUM; testnum++) {
int st = 1;
EVP_PKEY *sm2_pkey = NULL;
if (!sm2_doit[testnum])
continue; /* Ignore Curve */
/* Init signing and verification */
for (i = 0; i < loopargs_len; i++) {
EVP_PKEY_CTX *sm2_pctx = NULL;
EVP_PKEY_CTX *sm2_vfy_pctx = NULL;
EVP_PKEY_CTX *pctx = NULL;
st = 0;
loopargs[i].sm2_ctx[testnum] = EVP_MD_CTX_new();
loopargs[i].sm2_vfy_ctx[testnum] = EVP_MD_CTX_new();
if (loopargs[i].sm2_ctx[testnum] == NULL
|| loopargs[i].sm2_vfy_ctx[testnum] == NULL)
break;
sm2_pkey = NULL;
st = !((pctx = EVP_PKEY_CTX_new_id(EVP_PKEY_SM2, NULL)) == NULL
|| EVP_PKEY_keygen_init(pctx) <= 0
|| EVP_PKEY_CTX_set_ec_paramgen_curve_nid(pctx,
sm2_curves[testnum].nid) <= 0
|| EVP_PKEY_keygen(pctx, &sm2_pkey) <= 0);
EVP_PKEY_CTX_free(pctx);
if (st == 0)
break;
st = 0; /* set back to zero */
/* attach it sooner to rely on main final cleanup */
loopargs[i].sm2_pkey[testnum] = sm2_pkey;
loopargs[i].sigsize = EVP_PKEY_get_size(sm2_pkey);
sm2_pctx = EVP_PKEY_CTX_new(sm2_pkey, NULL);
sm2_vfy_pctx = EVP_PKEY_CTX_new(sm2_pkey, NULL);
if (sm2_pctx == NULL || sm2_vfy_pctx == NULL) {
EVP_PKEY_CTX_free(sm2_vfy_pctx);
break;
}
/* attach them directly to respective ctx */
EVP_MD_CTX_set_pkey_ctx(loopargs[i].sm2_ctx[testnum], sm2_pctx);
EVP_MD_CTX_set_pkey_ctx(loopargs[i].sm2_vfy_ctx[testnum], sm2_vfy_pctx);
/*
* No need to allow user to set an explicit ID here, just use
* the one defined in the 'draft-yang-tls-tl13-sm-suites' I-D.
*/
if (EVP_PKEY_CTX_set1_id(sm2_pctx, SM2_ID, SM2_ID_LEN) != 1
|| EVP_PKEY_CTX_set1_id(sm2_vfy_pctx, SM2_ID, SM2_ID_LEN) != 1)
break;
if (!EVP_DigestSignInit(loopargs[i].sm2_ctx[testnum], NULL,
EVP_sm3(), NULL, sm2_pkey))
break;
if (!EVP_DigestVerifyInit(loopargs[i].sm2_vfy_ctx[testnum], NULL,
EVP_sm3(), NULL, sm2_pkey))
break;
st = 1; /* mark loop as succeeded */
}
if (st == 0) {
BIO_printf(bio_err, "SM2 init failure.\n");
ERR_print_errors(bio_err);
op_count = 1;
} else {
for (i = 0; i < loopargs_len; i++) {
/* Perform SM2 signature test */
st = EVP_DigestSign(loopargs[i].sm2_ctx[testnum],
loopargs[i].buf2, &loopargs[i].sigsize,
loopargs[i].buf, 20);
if (st == 0)
break;
}
if (st == 0) {
BIO_printf(bio_err,
"SM2 sign failure. No SM2 sign will be done.\n");
ERR_print_errors(bio_err);
op_count = 1;
} else {
pkey_print_message("sign", sm2_curves[testnum].name,
sm2_c[testnum][0],
sm2_curves[testnum].bits, seconds.sm2);
Time_F(START);
count = run_benchmark(async_jobs, SM2_sign_loop, loopargs);
d = Time_F(STOP);
BIO_printf(bio_err,
mr ? "+R10:%ld:%u:%s:%.2f\n" :
"%ld %u bits %s signs in %.2fs \n",
count, sm2_curves[testnum].bits,
sm2_curves[testnum].name, d);
sm2_results[testnum][0] = (double)count / d;
op_count = count;
}
/* Perform SM2 verification test */
for (i = 0; i < loopargs_len; i++) {
st = EVP_DigestVerify(loopargs[i].sm2_vfy_ctx[testnum],
loopargs[i].buf2, loopargs[i].sigsize,
loopargs[i].buf, 20);
if (st != 1)
break;
}
if (st != 1) {
BIO_printf(bio_err,
"SM2 verify failure. No SM2 verify will be done.\n");
ERR_print_errors(bio_err);
sm2_doit[testnum] = 0;
} else {
pkey_print_message("verify", sm2_curves[testnum].name,
sm2_c[testnum][1],
sm2_curves[testnum].bits, seconds.sm2);
Time_F(START);
count = run_benchmark(async_jobs, SM2_verify_loop, loopargs);
d = Time_F(STOP);
BIO_printf(bio_err,
mr ? "+R11:%ld:%u:%s:%.2f\n"
: "%ld %u bits %s verify in %.2fs\n",
count, sm2_curves[testnum].bits,
sm2_curves[testnum].name, d);
sm2_results[testnum][1] = (double)count / d;
}
if (op_count <= 1) {
/* if longer than 10s, don't do any more */
for (testnum++; testnum < SM2_NUM; testnum++)
sm2_doit[testnum] = 0;
}
}
}
#endif /* OPENSSL_NO_SM2 */
#ifndef OPENSSL_NO_DH
for (testnum = 0; testnum < FFDH_NUM; testnum++) {
int ffdh_checks = 1;
if (!ffdh_doit[testnum])
continue;
for (i = 0; i < loopargs_len; i++) {
EVP_PKEY *pkey_A = NULL;
EVP_PKEY *pkey_B = NULL;
EVP_PKEY_CTX *ffdh_ctx = NULL;
EVP_PKEY_CTX *test_ctx = NULL;
size_t secret_size;
size_t test_out;
/* Ensure that the error queue is empty */
if (ERR_peek_error()) {
BIO_printf(bio_err,
"WARNING: the error queue contains previous unhandled errors.\n");
ERR_print_errors(bio_err);
}
pkey_A = EVP_PKEY_new();
if (!pkey_A) {
BIO_printf(bio_err, "Error while initialising EVP_PKEY (out of memory?).\n");
ERR_print_errors(bio_err);
op_count = 1;
ffdh_checks = 0;
break;
}
pkey_B = EVP_PKEY_new();
if (!pkey_B) {
BIO_printf(bio_err, "Error while initialising EVP_PKEY (out of memory?).\n");
ERR_print_errors(bio_err);
op_count = 1;
ffdh_checks = 0;
break;
}
ffdh_ctx = EVP_PKEY_CTX_new_id(EVP_PKEY_DH, NULL);
if (!ffdh_ctx) {
BIO_printf(bio_err, "Error while allocating EVP_PKEY_CTX.\n");
ERR_print_errors(bio_err);
op_count = 1;
ffdh_checks = 0;
break;
}
if (EVP_PKEY_keygen_init(ffdh_ctx) <= 0) {
BIO_printf(bio_err, "Error while initialising EVP_PKEY_CTX.\n");
ERR_print_errors(bio_err);
op_count = 1;
ffdh_checks = 0;
break;
}
if (EVP_PKEY_CTX_set_dh_nid(ffdh_ctx, ffdh_params[testnum].nid) <= 0) {
BIO_printf(bio_err, "Error setting DH key size for keygen.\n");
ERR_print_errors(bio_err);
op_count = 1;
ffdh_checks = 0;
break;
}
if (EVP_PKEY_keygen(ffdh_ctx, &pkey_A) <= 0 ||
EVP_PKEY_keygen(ffdh_ctx, &pkey_B) <= 0) {
BIO_printf(bio_err, "FFDH key generation failure.\n");
ERR_print_errors(bio_err);
op_count = 1;
ffdh_checks = 0;
break;
}
EVP_PKEY_CTX_free(ffdh_ctx);
/*
* check if the derivation works correctly both ways so that
* we know if future derive calls will fail, and we can skip
* error checking in benchmarked code
*/
ffdh_ctx = EVP_PKEY_CTX_new(pkey_A, NULL);
if (ffdh_ctx == NULL) {
BIO_printf(bio_err, "Error while allocating EVP_PKEY_CTX.\n");
ERR_print_errors(bio_err);
op_count = 1;
ffdh_checks = 0;
break;
}
if (EVP_PKEY_derive_init(ffdh_ctx) <= 0) {
BIO_printf(bio_err, "FFDH derivation context init failure.\n");
ERR_print_errors(bio_err);
op_count = 1;
ffdh_checks = 0;
break;
}
if (EVP_PKEY_derive_set_peer(ffdh_ctx, pkey_B) <= 0) {
BIO_printf(bio_err, "Assigning peer key for derivation failed.\n");
ERR_print_errors(bio_err);
op_count = 1;
ffdh_checks = 0;
break;
}
if (EVP_PKEY_derive(ffdh_ctx, NULL, &secret_size) <= 0) {
BIO_printf(bio_err, "Checking size of shared secret failed.\n");
ERR_print_errors(bio_err);
op_count = 1;
ffdh_checks = 0;
break;
}
if (secret_size > MAX_FFDH_SIZE) {
BIO_printf(bio_err, "Assertion failure: shared secret too large.\n");
op_count = 1;
ffdh_checks = 0;
break;
}
if (EVP_PKEY_derive(ffdh_ctx,
loopargs[i].secret_ff_a,
&secret_size) <= 0) {
BIO_printf(bio_err, "Shared secret derive failure.\n");
ERR_print_errors(bio_err);
op_count = 1;
ffdh_checks = 0;
break;
}
/* Now check from side B */
test_ctx = EVP_PKEY_CTX_new(pkey_B, NULL);
if (!test_ctx) {
BIO_printf(bio_err, "Error while allocating EVP_PKEY_CTX.\n");
ERR_print_errors(bio_err);
op_count = 1;
ffdh_checks = 0;
break;
}
if (EVP_PKEY_derive_init(test_ctx) <= 0 ||
EVP_PKEY_derive_set_peer(test_ctx, pkey_A) <= 0 ||
EVP_PKEY_derive(test_ctx, NULL, &test_out) <= 0 ||
EVP_PKEY_derive(test_ctx, loopargs[i].secret_ff_b, &test_out) <= 0 ||
test_out != secret_size) {
BIO_printf(bio_err, "FFDH computation failure.\n");
op_count = 1;
ffdh_checks = 0;
break;
}
/* compare the computed secrets */
if (CRYPTO_memcmp(loopargs[i].secret_ff_a,
loopargs[i].secret_ff_b, secret_size)) {
BIO_printf(bio_err, "FFDH computations don't match.\n");
ERR_print_errors(bio_err);
op_count = 1;
ffdh_checks = 0;
break;
}
loopargs[i].ffdh_ctx[testnum] = ffdh_ctx;
EVP_PKEY_free(pkey_A);
pkey_A = NULL;
EVP_PKEY_free(pkey_B);
pkey_B = NULL;
EVP_PKEY_CTX_free(test_ctx);
test_ctx = NULL;
}
if (ffdh_checks != 0) {
pkey_print_message("", "ffdh", ffdh_c[testnum][0],
ffdh_params[testnum].bits, seconds.ffdh);
Time_F(START);
count =
run_benchmark(async_jobs, FFDH_derive_key_loop, loopargs);
d = Time_F(STOP);
BIO_printf(bio_err,
mr ? "+R12:%ld:%d:%.2f\n" :
"%ld %u-bits FFDH ops in %.2fs\n", count,
ffdh_params[testnum].bits, d);
ffdh_results[testnum][0] = (double)count / d;
op_count = count;
}
if (op_count <= 1) {
/* if longer than 10s, don't do any more */
stop_it(ffdh_doit, testnum);
}
}
#endif /* OPENSSL_NO_DH */
#ifndef NO_FORK
show_res:
#endif
if (!mr) {
printf("version: %s\n", OpenSSL_version(OPENSSL_FULL_VERSION_STRING));
printf("%s\n", OpenSSL_version(OPENSSL_BUILT_ON));
printf("options: %s\n", BN_options());
printf("%s\n", OpenSSL_version(OPENSSL_CFLAGS));
printf("%s\n", OpenSSL_version(OPENSSL_CPU_INFO));
}
if (pr_header) {
if (mr) {
printf("+H");
} else {
printf("The 'numbers' are in 1000s of bytes per second processed.\n");
printf("type ");
}
for (testnum = 0; testnum < size_num; testnum++)
printf(mr ? ":%d" : "%7d bytes", lengths[testnum]);
printf("\n");
}
for (k = 0; k < ALGOR_NUM; k++) {
const char *alg_name = names[k];
if (!doit[k])
continue;
if (k == D_EVP) {
if (evp_cipher == NULL)
alg_name = evp_md_name;
else if ((alg_name = EVP_CIPHER_get0_name(evp_cipher)) == NULL)
app_bail_out("failed to get name of cipher '%s'\n", evp_cipher);
}
if (mr)
printf("+F:%u:%s", k, alg_name);
else
printf("%-13s", alg_name);
for (testnum = 0; testnum < size_num; testnum++) {
if (results[k][testnum] > 10000 && !mr)
printf(" %11.2fk", results[k][testnum] / 1e3);
else
printf(mr ? ":%.2f" : " %11.2f ", results[k][testnum]);
}
printf("\n");
}
testnum = 1;
for (k = 0; k < RSA_NUM; k++) {
if (!rsa_doit[k])
continue;
if (testnum && !mr) {
printf("%18ssign verify sign/s verify/s\n", " ");
testnum = 0;
}
if (mr)
printf("+F2:%u:%u:%f:%f\n",
k, rsa_keys[k].bits, rsa_results[k][0], rsa_results[k][1]);
else
printf("rsa %4u bits %8.6fs %8.6fs %8.1f %8.1f\n",
rsa_keys[k].bits, 1.0 / rsa_results[k][0], 1.0 / rsa_results[k][1],
rsa_results[k][0], rsa_results[k][1]);
}
testnum = 1;
for (k = 0; k < DSA_NUM; k++) {
if (!dsa_doit[k])
continue;
if (testnum && !mr) {
printf("%18ssign verify sign/s verify/s\n", " ");
testnum = 0;
}
if (mr)
printf("+F3:%u:%u:%f:%f\n",
k, dsa_bits[k], dsa_results[k][0], dsa_results[k][1]);
else
printf("dsa %4u bits %8.6fs %8.6fs %8.1f %8.1f\n",
dsa_bits[k], 1.0 / dsa_results[k][0], 1.0 / dsa_results[k][1],
dsa_results[k][0], dsa_results[k][1]);
}
testnum = 1;
for (k = 0; k < OSSL_NELEM(ecdsa_doit); k++) {
if (!ecdsa_doit[k])
continue;
if (testnum && !mr) {
printf("%30ssign verify sign/s verify/s\n", " ");
testnum = 0;
}
if (mr)
printf("+F4:%u:%u:%f:%f\n",
k, ec_curves[k].bits,
ecdsa_results[k][0], ecdsa_results[k][1]);
else
printf("%4u bits ecdsa (%s) %8.4fs %8.4fs %8.1f %8.1f\n",
ec_curves[k].bits, ec_curves[k].name,
1.0 / ecdsa_results[k][0], 1.0 / ecdsa_results[k][1],
ecdsa_results[k][0], ecdsa_results[k][1]);
}
testnum = 1;
for (k = 0; k < EC_NUM; k++) {
if (!ecdh_doit[k])
continue;
if (testnum && !mr) {
printf("%30sop op/s\n", " ");
testnum = 0;
}
if (mr)
printf("+F5:%u:%u:%f:%f\n",
k, ec_curves[k].bits,
ecdh_results[k][0], 1.0 / ecdh_results[k][0]);
else
printf("%4u bits ecdh (%s) %8.4fs %8.1f\n",
ec_curves[k].bits, ec_curves[k].name,
1.0 / ecdh_results[k][0], ecdh_results[k][0]);
}
testnum = 1;
for (k = 0; k < OSSL_NELEM(eddsa_doit); k++) {
if (!eddsa_doit[k])
continue;
if (testnum && !mr) {
printf("%30ssign verify sign/s verify/s\n", " ");
testnum = 0;
}
if (mr)
printf("+F6:%u:%u:%s:%f:%f\n",
k, ed_curves[k].bits, ed_curves[k].name,
eddsa_results[k][0], eddsa_results[k][1]);
else
printf("%4u bits EdDSA (%s) %8.4fs %8.4fs %8.1f %8.1f\n",
ed_curves[k].bits, ed_curves[k].name,
1.0 / eddsa_results[k][0], 1.0 / eddsa_results[k][1],
eddsa_results[k][0], eddsa_results[k][1]);
}
#ifndef OPENSSL_NO_SM2
testnum = 1;
for (k = 0; k < OSSL_NELEM(sm2_doit); k++) {
if (!sm2_doit[k])
continue;
if (testnum && !mr) {
printf("%30ssign verify sign/s verify/s\n", " ");
testnum = 0;
}
if (mr)
printf("+F7:%u:%u:%s:%f:%f\n",
k, sm2_curves[k].bits, sm2_curves[k].name,
sm2_results[k][0], sm2_results[k][1]);
else
printf("%4u bits SM2 (%s) %8.4fs %8.4fs %8.1f %8.1f\n",
sm2_curves[k].bits, sm2_curves[k].name,
1.0 / sm2_results[k][0], 1.0 / sm2_results[k][1],
sm2_results[k][0], sm2_results[k][1]);
}
#endif
#ifndef OPENSSL_NO_DH
testnum = 1;
for (k = 0; k < FFDH_NUM; k++) {
if (!ffdh_doit[k])
continue;
if (testnum && !mr) {
printf("%23sop op/s\n", " ");
testnum = 0;
}
if (mr)
printf("+F8:%u:%u:%f:%f\n",
k, ffdh_params[k].bits,
ffdh_results[k][0], 1.0 / ffdh_results[k][0]);
else
printf("%4u bits ffdh %8.4fs %8.1f\n",
ffdh_params[k].bits,
1.0 / ffdh_results[k][0], ffdh_results[k][0]);
}
#endif /* OPENSSL_NO_DH */
ret = 0;
end:
ERR_print_errors(bio_err);
for (i = 0; i < loopargs_len; i++) {
OPENSSL_free(loopargs[i].buf_malloc);
OPENSSL_free(loopargs[i].buf2_malloc);
BN_free(bn);
EVP_PKEY_CTX_free(genctx);
for (k = 0; k < RSA_NUM; k++) {
EVP_PKEY_CTX_free(loopargs[i].rsa_sign_ctx[k]);
EVP_PKEY_CTX_free(loopargs[i].rsa_verify_ctx[k]);
}
#ifndef OPENSSL_NO_DH
OPENSSL_free(loopargs[i].secret_ff_a);
OPENSSL_free(loopargs[i].secret_ff_b);
for (k = 0; k < FFDH_NUM; k++)
EVP_PKEY_CTX_free(loopargs[i].ffdh_ctx[k]);
#endif
for (k = 0; k < DSA_NUM; k++) {
EVP_PKEY_CTX_free(loopargs[i].dsa_sign_ctx[k]);
EVP_PKEY_CTX_free(loopargs[i].dsa_verify_ctx[k]);
}
for (k = 0; k < ECDSA_NUM; k++) {
EVP_PKEY_CTX_free(loopargs[i].ecdsa_sign_ctx[k]);
EVP_PKEY_CTX_free(loopargs[i].ecdsa_verify_ctx[k]);
}
for (k = 0; k < EC_NUM; k++)
EVP_PKEY_CTX_free(loopargs[i].ecdh_ctx[k]);
for (k = 0; k < EdDSA_NUM; k++) {
EVP_MD_CTX_free(loopargs[i].eddsa_ctx[k]);
EVP_MD_CTX_free(loopargs[i].eddsa_ctx2[k]);
}
#ifndef OPENSSL_NO_SM2
for (k = 0; k < SM2_NUM; k++) {
EVP_PKEY_CTX *pctx = NULL;
/* free signing ctx */
if (loopargs[i].sm2_ctx[k] != NULL
&& (pctx = EVP_MD_CTX_get_pkey_ctx(loopargs[i].sm2_ctx[k])) != NULL)
EVP_PKEY_CTX_free(pctx);
EVP_MD_CTX_free(loopargs[i].sm2_ctx[k]);
/* free verification ctx */
if (loopargs[i].sm2_vfy_ctx[k] != NULL
&& (pctx = EVP_MD_CTX_get_pkey_ctx(loopargs[i].sm2_vfy_ctx[k])) != NULL)
EVP_PKEY_CTX_free(pctx);
EVP_MD_CTX_free(loopargs[i].sm2_vfy_ctx[k]);
/* free pkey */
EVP_PKEY_free(loopargs[i].sm2_pkey[k]);
}
#endif
OPENSSL_free(loopargs[i].secret_a);
OPENSSL_free(loopargs[i].secret_b);
}
OPENSSL_free(evp_hmac_name);
OPENSSL_free(evp_cmac_name);
if (async_jobs > 0) {
for (i = 0; i < loopargs_len; i++)
ASYNC_WAIT_CTX_free(loopargs[i].wait_ctx);
}
if (async_init) {
ASYNC_cleanup_thread();
}
OPENSSL_free(loopargs);
release_engine(e);
EVP_CIPHER_free(evp_cipher);
EVP_MAC_free(mac);
return ret;
}
static void print_message(const char *s, long num, int length, int tm)
{
BIO_printf(bio_err,
mr ? "+DT:%s:%d:%d\n"
: "Doing %s for %ds on %d size blocks: ", s, tm, length);
(void)BIO_flush(bio_err);
run = 1;
alarm(tm);
}
static void pkey_print_message(const char *str, const char *str2, long num,
unsigned int bits, int tm)
{
BIO_printf(bio_err,
mr ? "+DTP:%d:%s:%s:%d\n"
: "Doing %u bits %s %s's for %ds: ", bits, str, str2, tm);
(void)BIO_flush(bio_err);
run = 1;
alarm(tm);
}
static void print_result(int alg, int run_no, int count, double time_used)
{
if (count == -1) {
BIO_printf(bio_err, "%s error!\n", names[alg]);
ERR_print_errors(bio_err);
return;
}
BIO_printf(bio_err,
mr ? "+R:%d:%s:%f\n"
: "%d %s's in %.2fs\n", count, names[alg], time_used);
results[alg][run_no] = ((double)count) / time_used * lengths[run_no];
}
#ifndef NO_FORK
static char *sstrsep(char **string, const char *delim)
{
char isdelim[256];
char *token = *string;
if (**string == 0)
return NULL;
memset(isdelim, 0, sizeof(isdelim));
isdelim[0] = 1;
while (*delim) {
isdelim[(unsigned char)(*delim)] = 1;
delim++;
}
while (!isdelim[(unsigned char)(**string)])
(*string)++;
if (**string) {
**string = 0;
(*string)++;
}
return token;
}
static int do_multi(int multi, int size_num)
{
int n;
int fd[2];
int *fds;
int status;
static char sep[] = ":";
fds = app_malloc(sizeof(*fds) * multi, "fd buffer for do_multi");
for (n = 0; n < multi; ++n) {
if (pipe(fd) == -1) {
BIO_printf(bio_err, "pipe failure\n");
exit(1);
}
fflush(stdout);
(void)BIO_flush(bio_err);
if (fork()) {
close(fd[1]);
fds[n] = fd[0];
} else {
close(fd[0]);
close(1);
if (dup(fd[1]) == -1) {
BIO_printf(bio_err, "dup failed\n");
exit(1);
}
close(fd[1]);
mr = 1;
usertime = 0;
OPENSSL_free(fds);
return 0;
}
printf("Forked child %d\n", n);
}
/* for now, assume the pipe is long enough to take all the output */
for (n = 0; n < multi; ++n) {
FILE *f;
char buf[1024];
char *p;
if ((f = fdopen(fds[n], "r")) == NULL) {
BIO_printf(bio_err, "fdopen failure with 0x%x\n",
errno);
OPENSSL_free(fds);
return 1;
}
while (fgets(buf, sizeof(buf), f)) {
p = strchr(buf, '\n');
if (p)
*p = '\0';
if (buf[0] != '+') {
BIO_printf(bio_err,
"Don't understand line '%s' from child %d\n", buf,
n);
continue;
}
printf("Got: %s from %d\n", buf, n);
if (strncmp(buf, "+F:", 3) == 0) {
int alg;
int j;
p = buf + 3;
alg = atoi(sstrsep(&p, sep));
sstrsep(&p, sep);
for (j = 0; j < size_num; ++j)
results[alg][j] += atof(sstrsep(&p, sep));
} else if (strncmp(buf, "+F2:", 4) == 0) {
int k;
double d;
p = buf + 4;
k = atoi(sstrsep(&p, sep));
sstrsep(&p, sep);
d = atof(sstrsep(&p, sep));
rsa_results[k][0] += d;
d = atof(sstrsep(&p, sep));
rsa_results[k][1] += d;
} else if (strncmp(buf, "+F3:", 4) == 0) {
int k;
double d;
p = buf + 4;
k = atoi(sstrsep(&p, sep));
sstrsep(&p, sep);
d = atof(sstrsep(&p, sep));
dsa_results[k][0] += d;
d = atof(sstrsep(&p, sep));
dsa_results[k][1] += d;
} else if (strncmp(buf, "+F4:", 4) == 0) {
int k;
double d;
p = buf + 4;
k = atoi(sstrsep(&p, sep));
sstrsep(&p, sep);
d = atof(sstrsep(&p, sep));
ecdsa_results[k][0] += d;
d = atof(sstrsep(&p, sep));
ecdsa_results[k][1] += d;
} else if (strncmp(buf, "+F5:", 4) == 0) {
int k;
double d;
p = buf + 4;
k = atoi(sstrsep(&p, sep));
sstrsep(&p, sep);
d = atof(sstrsep(&p, sep));
ecdh_results[k][0] += d;
} else if (strncmp(buf, "+F6:", 4) == 0) {
int k;
double d;
p = buf + 4;
k = atoi(sstrsep(&p, sep));
sstrsep(&p, sep);
sstrsep(&p, sep);
d = atof(sstrsep(&p, sep));
eddsa_results[k][0] += d;
d = atof(sstrsep(&p, sep));
eddsa_results[k][1] += d;
# ifndef OPENSSL_NO_SM2
} else if (strncmp(buf, "+F7:", 4) == 0) {
int k;
double d;
p = buf + 4;
k = atoi(sstrsep(&p, sep));
sstrsep(&p, sep);
sstrsep(&p, sep);
d = atof(sstrsep(&p, sep));
sm2_results[k][0] += d;
d = atof(sstrsep(&p, sep));
sm2_results[k][1] += d;
# endif /* OPENSSL_NO_SM2 */
# ifndef OPENSSL_NO_DH
} else if (strncmp(buf, "+F8:", 4) == 0) {
int k;
double d;
p = buf + 4;
k = atoi(sstrsep(&p, sep));
sstrsep(&p, sep);
d = atof(sstrsep(&p, sep));
ffdh_results[k][0] += d;
# endif /* OPENSSL_NO_DH */
} else if (strncmp(buf, "+H:", 3) == 0) {
;
} else {
BIO_printf(bio_err, "Unknown type '%s' from child %d\n", buf,
n);
}
}
fclose(f);
}
OPENSSL_free(fds);
for (n = 0; n < multi; ++n) {
while (wait(&status) == -1)
if (errno != EINTR) {
BIO_printf(bio_err, "Waitng for child failed with 0x%x\n",
errno);
return 1;
}
if (WIFEXITED(status) && WEXITSTATUS(status)) {
BIO_printf(bio_err, "Child exited with %d\n", WEXITSTATUS(status));
} else if (WIFSIGNALED(status)) {
BIO_printf(bio_err, "Child terminated by signal %d\n",
WTERMSIG(status));
}
}
return 1;
}
#endif
static void multiblock_speed(const EVP_CIPHER *evp_cipher, int lengths_single,
const openssl_speed_sec_t *seconds)
{
static const int mblengths_list[] =
{ 8 * 1024, 2 * 8 * 1024, 4 * 8 * 1024, 8 * 8 * 1024, 8 * 16 * 1024 };
const int *mblengths = mblengths_list;
int j, count, keylen, num = OSSL_NELEM(mblengths_list);
const char *alg_name;
unsigned char *inp = NULL, *out = NULL, *key, no_key[32], no_iv[16];
EVP_CIPHER_CTX *ctx = NULL;
double d = 0.0;
if (lengths_single) {
mblengths = &lengths_single;
num = 1;
}
inp = app_malloc(mblengths[num - 1], "multiblock input buffer");
out = app_malloc(mblengths[num - 1] + 1024, "multiblock output buffer");
if ((ctx = EVP_CIPHER_CTX_new()) == NULL)
app_bail_out("failed to allocate cipher context\n");
if (!EVP_EncryptInit_ex(ctx, evp_cipher, NULL, NULL, no_iv))
app_bail_out("failed to initialise cipher context\n");
if ((keylen = EVP_CIPHER_CTX_get_key_length(ctx)) < 0) {
BIO_printf(bio_err, "Impossible negative key length: %d\n", keylen);
goto err;
}
key = app_malloc(keylen, "evp_cipher key");
if (EVP_CIPHER_CTX_rand_key(ctx, key) <= 0)
app_bail_out("failed to generate random cipher key\n");
if (!EVP_EncryptInit_ex(ctx, NULL, NULL, key, NULL))
app_bail_out("failed to set cipher key\n");
OPENSSL_clear_free(key, keylen);
if (EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_MAC_KEY,
sizeof(no_key), no_key) <= 0)
app_bail_out("failed to set AEAD key\n");
if ((alg_name = EVP_CIPHER_get0_name(evp_cipher)) == NULL)
app_bail_out("failed to get cipher name\n");
for (j = 0; j < num; j++) {
print_message(alg_name, 0, mblengths[j], seconds->sym);
Time_F(START);
for (count = 0; run && count < INT_MAX; count++) {
unsigned char aad[EVP_AEAD_TLS1_AAD_LEN];
EVP_CTRL_TLS1_1_MULTIBLOCK_PARAM mb_param;
size_t len = mblengths[j];
int packlen;
memset(aad, 0, 8); /* avoid uninitialized values */
aad[8] = 23; /* SSL3_RT_APPLICATION_DATA */
aad[9] = 3; /* version */
aad[10] = 2;
aad[11] = 0; /* length */
aad[12] = 0;
mb_param.out = NULL;
mb_param.inp = aad;
mb_param.len = len;
mb_param.interleave = 8;
packlen = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_TLS1_1_MULTIBLOCK_AAD,
sizeof(mb_param), &mb_param);
if (packlen > 0) {
mb_param.out = out;
mb_param.inp = inp;
mb_param.len = len;
(void)EVP_CIPHER_CTX_ctrl(ctx,
EVP_CTRL_TLS1_1_MULTIBLOCK_ENCRYPT,
sizeof(mb_param), &mb_param);
} else {
int pad;
if (RAND_bytes(inp, 16) <= 0)
app_bail_out("error setting random bytes\n");
len += 16;
aad[11] = (unsigned char)(len >> 8);
aad[12] = (unsigned char)(len);
pad = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_TLS1_AAD,
EVP_AEAD_TLS1_AAD_LEN, aad);
EVP_Cipher(ctx, out, inp, len + pad);
}
}
d = Time_F(STOP);
BIO_printf(bio_err, mr ? "+R:%d:%s:%f\n"
: "%d %s's in %.2fs\n", count, "evp", d);
results[D_EVP][j] = ((double)count) / d * mblengths[j];
}
if (mr) {
fprintf(stdout, "+H");
for (j = 0; j < num; j++)
fprintf(stdout, ":%d", mblengths[j]);
fprintf(stdout, "\n");
fprintf(stdout, "+F:%d:%s", D_EVP, alg_name);
for (j = 0; j < num; j++)
fprintf(stdout, ":%.2f", results[D_EVP][j]);
fprintf(stdout, "\n");
} else {
fprintf(stdout,
"The 'numbers' are in 1000s of bytes per second processed.\n");
fprintf(stdout, "type ");
for (j = 0; j < num; j++)
fprintf(stdout, "%7d bytes", mblengths[j]);
fprintf(stdout, "\n");
fprintf(stdout, "%-24s", alg_name);
for (j = 0; j < num; j++) {
if (results[D_EVP][j] > 10000)
fprintf(stdout, " %11.2fk", results[D_EVP][j] / 1e3);
else
fprintf(stdout, " %11.2f ", results[D_EVP][j]);
}
fprintf(stdout, "\n");
}
err:
OPENSSL_free(inp);
OPENSSL_free(out);
EVP_CIPHER_CTX_free(ctx);
}
diff --git a/crypto/openssl/apps/ts.c b/crypto/openssl/apps/ts.c
index 57292e187cd2..01b73f380428 100644
--- a/crypto/openssl/apps/ts.c
+++ b/crypto/openssl/apps/ts.c
@@ -1,1034 +1,1037 @@
/*
- * Copyright 2006-2022 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2006-2024 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 <openssl/opensslconf.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "apps.h"
#include "progs.h"
#include <openssl/bio.h>
#include <openssl/err.h>
#include <openssl/pem.h>
#include <openssl/rand.h>
#include <openssl/ts.h>
#include <openssl/bn.h>
/* Request nonce length, in bits (must be a multiple of 8). */
#define NONCE_LENGTH 64
/* Name of config entry that defines the OID file. */
#define ENV_OID_FILE "oid_file"
/* Is |EXACTLY_ONE| of three pointers set? */
#define EXACTLY_ONE(a, b, c) \
(( a && !b && !c) || \
( b && !a && !c) || \
( c && !a && !b))
static ASN1_OBJECT *txt2obj(const char *oid);
static CONF *load_config_file(const char *configfile);
/* Query related functions. */
static int query_command(const char *data, const char *digest,
const EVP_MD *md, const char *policy, int no_nonce,
int cert, const char *in, const char *out, int text);
static TS_REQ *create_query(BIO *data_bio, const char *digest, const EVP_MD *md,
const char *policy, int no_nonce, int cert);
static int create_digest(BIO *input, const char *digest,
const EVP_MD *md, unsigned char **md_value);
static ASN1_INTEGER *create_nonce(int bits);
/* Reply related functions. */
static int reply_command(CONF *conf, const char *section, const char *engine,
const char *queryfile, const char *passin, const char *inkey,
const EVP_MD *md, const char *signer, const char *chain,
const char *policy, const char *in, int token_in,
const char *out, int token_out, int text);
static TS_RESP *read_PKCS7(BIO *in_bio);
static TS_RESP *create_response(CONF *conf, const char *section, const char *engine,
const char *queryfile, const char *passin,
const char *inkey, const EVP_MD *md, const char *signer,
const char *chain, const char *policy);
static ASN1_INTEGER *serial_cb(TS_RESP_CTX *ctx, void *data);
static ASN1_INTEGER *next_serial(const char *serialfile);
static int save_ts_serial(const char *serialfile, ASN1_INTEGER *serial);
/* Verify related functions. */
static int verify_command(const char *data, const char *digest, const char *queryfile,
const char *in, int token_in,
const char *CApath, const char *CAfile,
const char *CAstore,
char *untrusted, X509_VERIFY_PARAM *vpm);
static TS_VERIFY_CTX *create_verify_ctx(const char *data, const char *digest,
const char *queryfile,
const char *CApath, const char *CAfile,
const char *CAstore,
char *untrusted,
X509_VERIFY_PARAM *vpm);
static X509_STORE *create_cert_store(const char *CApath, const char *CAfile,
const char *CAstore, X509_VERIFY_PARAM *vpm);
static int verify_cb(int ok, X509_STORE_CTX *ctx);
typedef enum OPTION_choice {
OPT_COMMON,
OPT_ENGINE, OPT_CONFIG, OPT_SECTION, OPT_QUERY, OPT_DATA,
OPT_DIGEST, OPT_TSPOLICY, OPT_NO_NONCE, OPT_CERT,
OPT_IN, OPT_TOKEN_IN, OPT_OUT, OPT_TOKEN_OUT, OPT_TEXT,
OPT_REPLY, OPT_QUERYFILE, OPT_PASSIN, OPT_INKEY, OPT_SIGNER,
OPT_CHAIN, OPT_VERIFY, OPT_CAPATH, OPT_CAFILE, OPT_CASTORE, OPT_UNTRUSTED,
OPT_MD, OPT_V_ENUM, OPT_R_ENUM, OPT_PROV_ENUM
} OPTION_CHOICE;
const OPTIONS ts_options[] = {
OPT_SECTION("General"),
{"help", OPT_HELP, '-', "Display this summary"},
{"config", OPT_CONFIG, '<', "Configuration file"},
{"section", OPT_SECTION, 's', "Section to use within config file"},
#ifndef OPENSSL_NO_ENGINE
{"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"},
#endif
{"inkey", OPT_INKEY, 's', "File with private key for reply"},
{"signer", OPT_SIGNER, 's', "Signer certificate file"},
{"chain", OPT_CHAIN, '<', "File with signer CA chain"},
{"CAfile", OPT_CAFILE, '<', "File with trusted CA certs"},
{"CApath", OPT_CAPATH, '/', "Path to trusted CA files"},
{"CAstore", OPT_CASTORE, ':', "URI to trusted CA store"},
{"untrusted", OPT_UNTRUSTED, '<', "Extra untrusted certs"},
{"token_in", OPT_TOKEN_IN, '-', "Input is a PKCS#7 file"},
{"token_out", OPT_TOKEN_OUT, '-', "Output is a PKCS#7 file"},
{"passin", OPT_PASSIN, 's', "Input file pass phrase source"},
{"", OPT_MD, '-', "Any supported digest"},
OPT_SECTION("Query"),
{"query", OPT_QUERY, '-', "Generate a TS query"},
{"data", OPT_DATA, '<', "File to hash"},
{"digest", OPT_DIGEST, 's', "Digest (as a hex string)"},
{"queryfile", OPT_QUERYFILE, '<', "File containing a TS query"},
{"cert", OPT_CERT, '-', "Put cert request into query"},
{"in", OPT_IN, '<', "Input file"},
OPT_SECTION("Verify"),
{"verify", OPT_VERIFY, '-', "Verify a TS response"},
{"reply", OPT_REPLY, '-', "Generate a TS reply"},
{"tspolicy", OPT_TSPOLICY, 's', "Policy OID to use"},
{"no_nonce", OPT_NO_NONCE, '-', "Do not include a nonce"},
{"out", OPT_OUT, '>', "Output file"},
{"text", OPT_TEXT, '-', "Output text (not DER)"},
OPT_R_OPTIONS,
OPT_V_OPTIONS,
OPT_PROV_OPTIONS,
{NULL}
};
/*
* This command is so complex, special help is needed.
*/
static char* opt_helplist[] = {
"",
"Typical uses:",
" openssl ts -query [-rand file...] [-config file] [-data file]",
" [-digest hexstring] [-tspolicy oid] [-no_nonce] [-cert]",
" [-in file] [-out file] [-text]",
"",
" openssl ts -reply [-config file] [-section tsa_section]",
" [-queryfile file] [-passin password]",
" [-signer tsa_cert.pem] [-inkey private_key.pem]",
" [-chain certs_file.pem] [-tspolicy oid]",
" [-in file] [-token_in] [-out file] [-token_out]",
#ifndef OPENSSL_NO_ENGINE
" [-text] [-engine id]",
#else
" [-text]",
#endif
"",
" openssl ts -verify -CApath dir -CAfile root-cert.pem -CAstore uri",
" -untrusted extra-certs.pem [-data file] [-digest hexstring]",
" [-queryfile request.tsq] -in response.tsr [-token_in] ...",
NULL,
};
int ts_main(int argc, char **argv)
{
CONF *conf = NULL;
const char *CAfile = NULL, *prog;
char *untrusted = NULL;
const char *configfile = default_config_file, *engine = NULL;
const char *section = NULL, *digestname = NULL;
char **helpp;
char *password = NULL;
char *data = NULL, *digest = NULL, *policy = NULL;
char *in = NULL, *out = NULL, *queryfile = NULL, *passin = NULL;
char *inkey = NULL, *signer = NULL, *chain = NULL, *CApath = NULL;
char *CAstore = NULL;
EVP_MD *md = NULL;
OPTION_CHOICE o, mode = OPT_ERR;
int ret = 1, no_nonce = 0, cert = 0, text = 0;
int vpmtouched = 0;
X509_VERIFY_PARAM *vpm = NULL;
/* Input is ContentInfo instead of TimeStampResp. */
int token_in = 0;
/* Output is ContentInfo instead of TimeStampResp. */
int token_out = 0;
if ((vpm = X509_VERIFY_PARAM_new()) == NULL)
goto end;
prog = opt_init(argc, argv, ts_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(ts_options);
for (helpp = opt_helplist; *helpp; ++helpp)
BIO_printf(bio_err, "%s\n", *helpp);
ret = 0;
goto end;
case OPT_CONFIG:
configfile = opt_arg();
break;
case OPT_SECTION:
section = opt_arg();
break;
case OPT_QUERY:
case OPT_REPLY:
case OPT_VERIFY:
if (mode != OPT_ERR)
goto opthelp;
mode = o;
break;
case OPT_DATA:
data = opt_arg();
break;
case OPT_DIGEST:
digest = opt_arg();
break;
case OPT_R_CASES:
if (!opt_rand(o))
goto end;
break;
case OPT_PROV_CASES:
if (!opt_provider(o))
goto end;
break;
case OPT_TSPOLICY:
policy = opt_arg();
break;
case OPT_NO_NONCE:
no_nonce = 1;
break;
case OPT_CERT:
cert = 1;
break;
case OPT_IN:
in = opt_arg();
break;
case OPT_TOKEN_IN:
token_in = 1;
break;
case OPT_OUT:
out = opt_arg();
break;
case OPT_TOKEN_OUT:
token_out = 1;
break;
case OPT_TEXT:
text = 1;
break;
case OPT_QUERYFILE:
queryfile = opt_arg();
break;
case OPT_PASSIN:
passin = opt_arg();
break;
case OPT_INKEY:
inkey = opt_arg();
break;
case OPT_SIGNER:
signer = opt_arg();
break;
case OPT_CHAIN:
chain = opt_arg();
break;
case OPT_CAPATH:
CApath = opt_arg();
break;
case OPT_CAFILE:
CAfile = opt_arg();
break;
case OPT_CASTORE:
CAstore = opt_arg();
break;
case OPT_UNTRUSTED:
untrusted = opt_arg();
break;
case OPT_ENGINE:
engine = opt_arg();
break;
case OPT_MD:
digestname = opt_unknown();
break;
case OPT_V_CASES:
if (!opt_verify(o, vpm))
goto end;
vpmtouched++;
break;
}
}
/* No extra arguments. */
argc = opt_num_rest();
if (argc != 0 || mode == OPT_ERR)
goto opthelp;
if (!app_RAND_load())
goto end;
if (digestname != NULL) {
if (!opt_md(digestname, &md))
goto opthelp;
}
if (mode == OPT_REPLY && passin &&
!app_passwd(passin, NULL, &password, NULL)) {
BIO_printf(bio_err, "Error getting password.\n");
goto end;
}
if ((conf = load_config_file(configfile)) == NULL)
goto end;
if (configfile != default_config_file && !app_load_modules(conf))
goto end;
/* Check parameter consistency and execute the appropriate function. */
if (mode == OPT_QUERY) {
if (vpmtouched)
goto opthelp;
if ((data != NULL) && (digest != NULL))
goto opthelp;
ret = !query_command(data, digest, md, policy, no_nonce, cert,
in, out, text);
} else if (mode == OPT_REPLY) {
if (vpmtouched)
goto opthelp;
if ((in != NULL) && (queryfile != NULL))
goto opthelp;
if (in == NULL) {
if ((conf == NULL) || (token_in != 0))
goto opthelp;
}
ret = !reply_command(conf, section, engine, queryfile,
password, inkey, md, signer, chain, policy,
in, token_in, out, token_out, text);
} else if (mode == OPT_VERIFY) {
if ((in == NULL) || !EXACTLY_ONE(queryfile, data, digest))
goto opthelp;
ret = !verify_command(data, digest, queryfile, in, token_in,
CApath, CAfile, CAstore, untrusted,
vpmtouched ? vpm : NULL);
} else {
goto opthelp;
}
end:
X509_VERIFY_PARAM_free(vpm);
EVP_MD_free(md);
NCONF_free(conf);
OPENSSL_free(password);
return ret;
}
/*
* Configuration file-related function definitions.
*/
static ASN1_OBJECT *txt2obj(const char *oid)
{
ASN1_OBJECT *oid_obj = NULL;
if ((oid_obj = OBJ_txt2obj(oid, 0)) == NULL)
BIO_printf(bio_err, "cannot convert %s to OID\n", oid);
return oid_obj;
}
static CONF *load_config_file(const char *configfile)
{
CONF *conf = app_load_config(configfile);
if (conf != NULL) {
const char *p;
BIO_printf(bio_err, "Using configuration from %s\n", configfile);
p = NCONF_get_string(conf, NULL, ENV_OID_FILE);
if (p != NULL) {
BIO *oid_bio = BIO_new_file(p, "r");
if (!oid_bio)
ERR_print_errors(bio_err);
else {
OBJ_create_objects(oid_bio);
BIO_free_all(oid_bio);
}
} else
ERR_clear_error();
if (!add_oid_section(conf))
ERR_print_errors(bio_err);
}
return conf;
}
/*
* Query-related method definitions.
*/
static int query_command(const char *data, const char *digest, const EVP_MD *md,
const char *policy, int no_nonce,
int cert, const char *in, const char *out, int text)
{
int ret = 0;
TS_REQ *query = NULL;
BIO *in_bio = NULL;
BIO *data_bio = NULL;
BIO *out_bio = NULL;
/* Build query object. */
if (in != NULL) {
if ((in_bio = bio_open_default(in, 'r', FORMAT_ASN1)) == NULL)
goto end;
query = d2i_TS_REQ_bio(in_bio, NULL);
} else {
if (digest == NULL
&& (data_bio = bio_open_default(data, 'r', FORMAT_ASN1)) == NULL)
goto end;
query = create_query(data_bio, digest, md, policy, no_nonce, cert);
}
if (query == NULL)
goto end;
if (text) {
if ((out_bio = bio_open_default(out, 'w', FORMAT_TEXT)) == NULL)
goto end;
if (!TS_REQ_print_bio(out_bio, query))
goto end;
} else {
if ((out_bio = bio_open_default(out, 'w', FORMAT_ASN1)) == NULL)
goto end;
if (!i2d_TS_REQ_bio(out_bio, query))
goto end;
}
ret = 1;
end:
ERR_print_errors(bio_err);
BIO_free_all(in_bio);
BIO_free_all(data_bio);
BIO_free_all(out_bio);
TS_REQ_free(query);
return ret;
}
static TS_REQ *create_query(BIO *data_bio, const char *digest, const EVP_MD *md,
const char *policy, int no_nonce, int cert)
{
int ret = 0;
TS_REQ *ts_req = NULL;
int len;
TS_MSG_IMPRINT *msg_imprint = NULL;
X509_ALGOR *algo = NULL;
unsigned char *data = NULL;
ASN1_OBJECT *policy_obj = NULL;
ASN1_INTEGER *nonce_asn1 = NULL;
if (md == NULL && (md = EVP_get_digestbyname("sha256")) == NULL)
goto err;
if ((ts_req = TS_REQ_new()) == NULL)
goto err;
if (!TS_REQ_set_version(ts_req, 1))
goto err;
if ((msg_imprint = TS_MSG_IMPRINT_new()) == NULL)
goto err;
if ((algo = X509_ALGOR_new()) == NULL)
goto err;
if ((algo->algorithm = OBJ_nid2obj(EVP_MD_get_type(md))) == NULL)
goto err;
if ((algo->parameter = ASN1_TYPE_new()) == NULL)
goto err;
algo->parameter->type = V_ASN1_NULL;
if (!TS_MSG_IMPRINT_set_algo(msg_imprint, algo))
goto err;
if ((len = create_digest(data_bio, digest, md, &data)) == 0)
goto err;
if (!TS_MSG_IMPRINT_set_msg(msg_imprint, data, len))
goto err;
if (!TS_REQ_set_msg_imprint(ts_req, msg_imprint))
goto err;
if (policy && (policy_obj = txt2obj(policy)) == NULL)
goto err;
if (policy_obj && !TS_REQ_set_policy_id(ts_req, policy_obj))
goto err;
/* Setting nonce if requested. */
if (!no_nonce && (nonce_asn1 = create_nonce(NONCE_LENGTH)) == NULL)
goto err;
if (nonce_asn1 && !TS_REQ_set_nonce(ts_req, nonce_asn1))
goto err;
if (!TS_REQ_set_cert_req(ts_req, cert))
goto err;
ret = 1;
err:
if (!ret) {
TS_REQ_free(ts_req);
ts_req = NULL;
BIO_printf(bio_err, "could not create query\n");
ERR_print_errors(bio_err);
}
TS_MSG_IMPRINT_free(msg_imprint);
X509_ALGOR_free(algo);
OPENSSL_free(data);
ASN1_OBJECT_free(policy_obj);
ASN1_INTEGER_free(nonce_asn1);
return ts_req;
}
static int create_digest(BIO *input, const char *digest, const EVP_MD *md,
unsigned char **md_value)
{
int md_value_len;
int rv = 0;
EVP_MD_CTX *md_ctx = NULL;
md_value_len = EVP_MD_get_size(md);
if (md_value_len < 0)
return 0;
if (input != NULL) {
unsigned char buffer[4096];
int length;
md_ctx = EVP_MD_CTX_new();
if (md_ctx == NULL)
return 0;
*md_value = app_malloc(md_value_len, "digest buffer");
if (!EVP_DigestInit(md_ctx, md))
goto err;
while ((length = BIO_read(input, buffer, sizeof(buffer))) > 0) {
if (!EVP_DigestUpdate(md_ctx, buffer, length))
goto err;
}
if (!EVP_DigestFinal(md_ctx, *md_value, NULL))
goto err;
md_value_len = EVP_MD_get_size(md);
} else {
long digest_len;
*md_value = OPENSSL_hexstr2buf(digest, &digest_len);
if (*md_value == NULL || md_value_len != digest_len) {
- OPENSSL_free(*md_value);
- *md_value = NULL;
BIO_printf(bio_err, "bad digest, %d bytes "
"must be specified\n", md_value_len);
- return 0;
+ goto err;
}
}
rv = md_value_len;
err:
+ if (rv <= 0) {
+ OPENSSL_free(*md_value);
+ *md_value = NULL;
+ rv = 0;
+ }
EVP_MD_CTX_free(md_ctx);
return rv;
}
static ASN1_INTEGER *create_nonce(int bits)
{
unsigned char buf[20];
ASN1_INTEGER *nonce = NULL;
int len = (bits - 1) / 8 + 1;
int i;
if (len > (int)sizeof(buf))
goto err;
if (RAND_bytes(buf, len) <= 0)
goto err;
/* Find the first non-zero byte and creating ASN1_INTEGER object. */
for (i = 0; i < len && !buf[i]; ++i)
continue;
if ((nonce = ASN1_INTEGER_new()) == NULL)
goto err;
OPENSSL_free(nonce->data);
nonce->length = len - i;
nonce->data = app_malloc(nonce->length + 1, "nonce buffer");
memcpy(nonce->data, buf + i, nonce->length);
return nonce;
err:
BIO_printf(bio_err, "could not create nonce\n");
ASN1_INTEGER_free(nonce);
return NULL;
}
/*
* Reply-related method definitions.
*/
static int reply_command(CONF *conf, const char *section, const char *engine,
const char *queryfile, const char *passin, const char *inkey,
const EVP_MD *md, const char *signer, const char *chain,
const char *policy, const char *in, int token_in,
const char *out, int token_out, int text)
{
int ret = 0;
TS_RESP *response = NULL;
BIO *in_bio = NULL;
BIO *query_bio = NULL;
BIO *inkey_bio = NULL;
BIO *signer_bio = NULL;
BIO *out_bio = NULL;
if (in != NULL) {
if ((in_bio = BIO_new_file(in, "rb")) == NULL)
goto end;
if (token_in) {
response = read_PKCS7(in_bio);
} else {
response = d2i_TS_RESP_bio(in_bio, NULL);
}
} else {
response = create_response(conf, section, engine, queryfile,
passin, inkey, md, signer, chain, policy);
if (response != NULL)
BIO_printf(bio_err, "Response has been generated.\n");
else
BIO_printf(bio_err, "Response is not generated.\n");
}
if (response == NULL)
goto end;
/* Write response. */
if (text) {
if ((out_bio = bio_open_default(out, 'w', FORMAT_TEXT)) == NULL)
goto end;
if (token_out) {
TS_TST_INFO *tst_info = TS_RESP_get_tst_info(response);
if (!TS_TST_INFO_print_bio(out_bio, tst_info))
goto end;
} else {
if (!TS_RESP_print_bio(out_bio, response))
goto end;
}
} else {
if ((out_bio = bio_open_default(out, 'w', FORMAT_ASN1)) == NULL)
goto end;
if (token_out) {
PKCS7 *token = TS_RESP_get_token(response);
if (!i2d_PKCS7_bio(out_bio, token))
goto end;
} else {
if (!i2d_TS_RESP_bio(out_bio, response))
goto end;
}
}
ret = 1;
end:
ERR_print_errors(bio_err);
BIO_free_all(in_bio);
BIO_free_all(query_bio);
BIO_free_all(inkey_bio);
BIO_free_all(signer_bio);
BIO_free_all(out_bio);
TS_RESP_free(response);
return ret;
}
/* Reads a PKCS7 token and adds default 'granted' status info to it. */
static TS_RESP *read_PKCS7(BIO *in_bio)
{
int ret = 0;
PKCS7 *token = NULL;
TS_TST_INFO *tst_info = NULL;
TS_RESP *resp = NULL;
TS_STATUS_INFO *si = NULL;
if ((token = d2i_PKCS7_bio(in_bio, NULL)) == NULL)
goto end;
if ((tst_info = PKCS7_to_TS_TST_INFO(token)) == NULL)
goto end;
if ((resp = TS_RESP_new()) == NULL)
goto end;
if ((si = TS_STATUS_INFO_new()) == NULL)
goto end;
if (!TS_STATUS_INFO_set_status(si, TS_STATUS_GRANTED))
goto end;
if (!TS_RESP_set_status_info(resp, si))
goto end;
TS_RESP_set_tst_info(resp, token, tst_info);
token = NULL; /* Ownership is lost. */
tst_info = NULL; /* Ownership is lost. */
ret = 1;
end:
PKCS7_free(token);
TS_TST_INFO_free(tst_info);
if (!ret) {
TS_RESP_free(resp);
resp = NULL;
}
TS_STATUS_INFO_free(si);
return resp;
}
static TS_RESP *create_response(CONF *conf, const char *section, const char *engine,
const char *queryfile, const char *passin,
const char *inkey, const EVP_MD *md, const char *signer,
const char *chain, const char *policy)
{
int ret = 0;
TS_RESP *response = NULL;
BIO *query_bio = NULL;
TS_RESP_CTX *resp_ctx = NULL;
if ((query_bio = BIO_new_file(queryfile, "rb")) == NULL)
goto end;
if ((section = TS_CONF_get_tsa_section(conf, section)) == NULL)
goto end;
if ((resp_ctx = TS_RESP_CTX_new()) == NULL)
goto end;
if (!TS_CONF_set_serial(conf, section, serial_cb, resp_ctx))
goto end;
#ifndef OPENSSL_NO_ENGINE
if (!TS_CONF_set_crypto_device(conf, section, engine))
goto end;
#endif
if (!TS_CONF_set_signer_cert(conf, section, signer, resp_ctx))
goto end;
if (!TS_CONF_set_certs(conf, section, chain, resp_ctx))
goto end;
if (!TS_CONF_set_signer_key(conf, section, inkey, passin, resp_ctx))
goto end;
if (md) {
if (!TS_RESP_CTX_set_signer_digest(resp_ctx, md))
goto end;
} else if (!TS_CONF_set_signer_digest(conf, section, NULL, resp_ctx)) {
goto end;
}
if (!TS_CONF_set_ess_cert_id_digest(conf, section, resp_ctx))
goto end;
if (!TS_CONF_set_def_policy(conf, section, policy, resp_ctx))
goto end;
if (!TS_CONF_set_policies(conf, section, resp_ctx))
goto end;
if (!TS_CONF_set_digests(conf, section, resp_ctx))
goto end;
if (!TS_CONF_set_accuracy(conf, section, resp_ctx))
goto end;
if (!TS_CONF_set_clock_precision_digits(conf, section, resp_ctx))
goto end;
if (!TS_CONF_set_ordering(conf, section, resp_ctx))
goto end;
if (!TS_CONF_set_tsa_name(conf, section, resp_ctx))
goto end;
if (!TS_CONF_set_ess_cert_id_chain(conf, section, resp_ctx))
goto end;
if ((response = TS_RESP_create_response(resp_ctx, query_bio)) == NULL)
goto end;
ret = 1;
end:
if (!ret) {
TS_RESP_free(response);
response = NULL;
}
TS_RESP_CTX_free(resp_ctx);
BIO_free_all(query_bio);
return response;
}
static ASN1_INTEGER *serial_cb(TS_RESP_CTX *ctx, void *data)
{
const char *serial_file = (const char *)data;
ASN1_INTEGER *serial = next_serial(serial_file);
if (serial == NULL) {
TS_RESP_CTX_set_status_info(ctx, TS_STATUS_REJECTION,
"Error during serial number "
"generation.");
TS_RESP_CTX_add_failure_info(ctx, TS_INFO_ADD_INFO_NOT_AVAILABLE);
} else {
save_ts_serial(serial_file, serial);
}
return serial;
}
static ASN1_INTEGER *next_serial(const char *serialfile)
{
int ret = 0;
BIO *in = NULL;
ASN1_INTEGER *serial = NULL;
BIGNUM *bn = NULL;
if ((serial = ASN1_INTEGER_new()) == NULL)
goto err;
if ((in = BIO_new_file(serialfile, "r")) == NULL) {
ERR_clear_error();
BIO_printf(bio_err, "Warning: could not open file %s for "
"reading, using serial number: 1\n", serialfile);
if (!ASN1_INTEGER_set(serial, 1))
goto err;
} else {
char buf[1024];
if (!a2i_ASN1_INTEGER(in, serial, buf, sizeof(buf))) {
BIO_printf(bio_err, "unable to load number from %s\n",
serialfile);
goto err;
}
if ((bn = ASN1_INTEGER_to_BN(serial, NULL)) == NULL)
goto err;
ASN1_INTEGER_free(serial);
serial = NULL;
if (!BN_add_word(bn, 1))
goto err;
if ((serial = BN_to_ASN1_INTEGER(bn, NULL)) == NULL)
goto err;
}
ret = 1;
err:
if (!ret) {
ASN1_INTEGER_free(serial);
serial = NULL;
}
BIO_free_all(in);
BN_free(bn);
return serial;
}
static int save_ts_serial(const char *serialfile, ASN1_INTEGER *serial)
{
int ret = 0;
BIO *out = NULL;
if ((out = BIO_new_file(serialfile, "w")) == NULL)
goto err;
if (i2a_ASN1_INTEGER(out, serial) <= 0)
goto err;
if (BIO_puts(out, "\n") <= 0)
goto err;
ret = 1;
err:
if (!ret)
BIO_printf(bio_err, "could not save serial number to %s\n",
serialfile);
BIO_free_all(out);
return ret;
}
/*
* Verify-related method definitions.
*/
static int verify_command(const char *data, const char *digest, const char *queryfile,
const char *in, int token_in,
const char *CApath, const char *CAfile,
const char *CAstore, char *untrusted,
X509_VERIFY_PARAM *vpm)
{
BIO *in_bio = NULL;
PKCS7 *token = NULL;
TS_RESP *response = NULL;
TS_VERIFY_CTX *verify_ctx = NULL;
int ret = 0;
if ((in_bio = BIO_new_file(in, "rb")) == NULL)
goto end;
if (token_in) {
if ((token = d2i_PKCS7_bio(in_bio, NULL)) == NULL)
goto end;
} else {
if ((response = d2i_TS_RESP_bio(in_bio, NULL)) == NULL)
goto end;
}
if ((verify_ctx = create_verify_ctx(data, digest, queryfile,
CApath, CAfile, CAstore, untrusted,
vpm)) == NULL)
goto end;
ret = token_in
? TS_RESP_verify_token(verify_ctx, token)
: TS_RESP_verify_response(verify_ctx, response);
end:
printf("Verification: ");
if (ret)
printf("OK\n");
else {
printf("FAILED\n");
ERR_print_errors(bio_err);
}
BIO_free_all(in_bio);
PKCS7_free(token);
TS_RESP_free(response);
TS_VERIFY_CTX_free(verify_ctx);
return ret;
}
static TS_VERIFY_CTX *create_verify_ctx(const char *data, const char *digest,
const char *queryfile,
const char *CApath, const char *CAfile,
const char *CAstore,
char *untrusted,
X509_VERIFY_PARAM *vpm)
{
TS_VERIFY_CTX *ctx = NULL;
STACK_OF(X509) *certs;
BIO *input = NULL;
TS_REQ *request = NULL;
int ret = 0;
int f = 0;
if (data != NULL || digest != NULL) {
if ((ctx = TS_VERIFY_CTX_new()) == NULL)
goto err;
f = TS_VFY_VERSION | TS_VFY_SIGNER;
if (data != NULL) {
BIO *out = NULL;
f |= TS_VFY_DATA;
if ((out = BIO_new_file(data, "rb")) == NULL)
goto err;
if (TS_VERIFY_CTX_set_data(ctx, out) == NULL) {
BIO_free_all(out);
goto err;
}
} else if (digest != NULL) {
long imprint_len;
unsigned char *hexstr = OPENSSL_hexstr2buf(digest, &imprint_len);
f |= TS_VFY_IMPRINT;
if (TS_VERIFY_CTX_set_imprint(ctx, hexstr, imprint_len) == NULL) {
BIO_printf(bio_err, "invalid digest string\n");
goto err;
}
}
} else if (queryfile != NULL) {
if ((input = BIO_new_file(queryfile, "rb")) == NULL)
goto err;
if ((request = d2i_TS_REQ_bio(input, NULL)) == NULL)
goto err;
if ((ctx = TS_REQ_to_TS_VERIFY_CTX(request, NULL)) == NULL)
goto err;
} else {
return NULL;
}
/* Add the signature verification flag and arguments. */
TS_VERIFY_CTX_add_flags(ctx, f | TS_VFY_SIGNATURE);
/* Initialising the X509_STORE object. */
if (TS_VERIFY_CTX_set_store(ctx,
create_cert_store(CApath, CAfile, CAstore, vpm))
== NULL)
goto err;
/* Loading any extra untrusted certificates. */
if (untrusted != NULL) {
certs = load_certs_multifile(untrusted, NULL, "extra untrusted certs",
vpm);
if (certs == NULL || TS_VERIFY_CTX_set_certs(ctx, certs) == NULL)
goto err;
}
ret = 1;
err:
if (!ret) {
TS_VERIFY_CTX_free(ctx);
ctx = NULL;
}
BIO_free_all(input);
TS_REQ_free(request);
return ctx;
}
static X509_STORE *create_cert_store(const char *CApath, const char *CAfile,
const char *CAstore, X509_VERIFY_PARAM *vpm)
{
X509_STORE *cert_ctx = NULL;
X509_LOOKUP *lookup = NULL;
OSSL_LIB_CTX *libctx = app_get0_libctx();
const char *propq = app_get0_propq();
cert_ctx = X509_STORE_new();
if (cert_ctx == NULL) {
BIO_printf(bio_err, "memory allocation failure\n");
return NULL;
}
X509_STORE_set_verify_cb(cert_ctx, verify_cb);
if (CApath != NULL) {
lookup = X509_STORE_add_lookup(cert_ctx, X509_LOOKUP_hash_dir());
if (lookup == NULL) {
BIO_printf(bio_err, "memory allocation failure\n");
goto err;
}
if (X509_LOOKUP_add_dir(lookup, CApath, X509_FILETYPE_PEM) <= 0) {
BIO_printf(bio_err, "Error loading directory %s\n", CApath);
goto err;
}
}
if (CAfile != NULL) {
lookup = X509_STORE_add_lookup(cert_ctx, X509_LOOKUP_file());
if (lookup == NULL) {
BIO_printf(bio_err, "memory allocation failure\n");
goto err;
}
if (X509_LOOKUP_load_file_ex(lookup, CAfile, X509_FILETYPE_PEM, libctx,
propq) <= 0) {
BIO_printf(bio_err, "Error loading file %s\n", CAfile);
goto err;
}
}
if (CAstore != NULL) {
lookup = X509_STORE_add_lookup(cert_ctx, X509_LOOKUP_store());
if (lookup == NULL) {
BIO_printf(bio_err, "memory allocation failure\n");
goto err;
}
if (X509_LOOKUP_load_store_ex(lookup, CAstore, libctx, propq) <= 0) {
BIO_printf(bio_err, "Error loading store URI %s\n", CAstore);
goto err;
}
}
if (vpm != NULL)
X509_STORE_set1_param(cert_ctx, vpm);
return cert_ctx;
err:
X509_STORE_free(cert_ctx);
return NULL;
}
static int verify_cb(int ok, X509_STORE_CTX *ctx)
{
return ok;
}
diff --git a/crypto/openssl/crypto/aes/build.info b/crypto/openssl/crypto/aes/build.info
index 47f99fdf3366..dec340779281 100644
--- a/crypto/openssl/crypto/aes/build.info
+++ b/crypto/openssl/crypto/aes/build.info
@@ -1,129 +1,129 @@
LIBS=../../libcrypto
$AESASM=aes_core.c aes_cbc.c
IF[{- !$disabled{asm} -}]
$AESASM_x86=aes-586.S
$AESDEF_x86=AES_ASM
$AESASM_x86_sse2=vpaes-x86.S aesni-x86.S
$AESDEF_x86_sse2=VPAES_ASM OPENSSL_IA32_SSE2
$AESASM_x86_64=\
aes-x86_64.s vpaes-x86_64.s bsaes-x86_64.s aesni-x86_64.s \
aesni-sha1-x86_64.s aesni-sha256-x86_64.s aesni-mb-x86_64.s
$AESDEF_x86_64=AES_ASM VPAES_ASM BSAES_ASM
$AESASM_ia64=aes_core.c aes_cbc.c aes-ia64.s
$AESDEF_ia64=AES_ASM
$AESASM_sparcv9=\
aes_core.c aes_cbc.c aes-sparcv9.S aest4-sparcv9.S aesfx-sparcv9.S
$AESDEF_sparcv9=AES_ASM
$AESASM_mips32=aes_cbc.c aes-mips.S
$AESDEF_mips32=AES_ASM
$AESASM_mips64=$AESASM_mips32
$AESDEF_mips64=$AESDEF_mips32
$AESASM_s390x=aes-s390x.S
# aes-390x.S implements AES_ctr32_encrypt and AES_xts_[en|de]crypt
$AESDEF_s390x=AES_ASM AES_CTR_ASM AES_XTS_ASM
$AESASM_armv4=aes_cbc.c aes-armv4.S bsaes-armv7.S aesv8-armx.S
$AESDEF_armv4=AES_ASM BSAES_ASM
$AESASM_aarch64=aes_core.c aes_cbc.c aesv8-armx.S vpaes-armv8.S
$AESDEF_aarch64=VPAES_ASM
$AESASM_parisc11=aes_core.c aes_cbc.c aes-parisc.s
$AESDEF_parisc11=AES_ASM
$AESASM_parisc20_64=$AESASM_parisc11
$AESDEF_parisc20_64=$AESDEF_parisc11
$AESASM_ppc32=aes_core.c aes_cbc.c aes-ppc.s vpaes-ppc.s aesp8-ppc.s
$AESDEF_ppc32=AES_ASM VPAES_ASM
$AESASM_ppc64=$AESASM_ppc32
$AESDEF_ppc64=$AESDEF_ppc32
$AESASM_c64xplus=aes-c64xplus.s aes_cbc.c
# aes-c64xplus.s implements AES_ctr32_encrypt
$AESDEF_c64xplus=AES_ASM AES_CTR_ASM
# Now that we have defined all the arch specific variables, use the
# appropriate one, and define the appropriate macros
IF[$AESASM_{- $target{asm_arch} -}]
$AESASM=$AESASM_{- $target{asm_arch} -}
$AESDEF=$AESDEF_{- $target{asm_arch} -}
IF[{- !$disabled{sse2} -}]
$AESASM=$AESASM $AESASM_{- $target{asm_arch} -}_sse2
$AESDEF=$AESDEF $AESDEF_{- $target{asm_arch} -}_sse2
ENDIF
ENDIF
ENDIF
$COMMON=aes_misc.c aes_ecb.c $AESASM
SOURCE[../../libcrypto]=$COMMON aes_cfb.c aes_ofb.c aes_wrap.c
IF[{- !$disabled{'deprecated-3.0'} -}]
SOURCE[../../libcrypto]=aes_ige.c
ENDIF
SOURCE[../../providers/libfips.a]=$COMMON
# Implementations are now spread across several libraries, so the defines
# need to be applied to all affected libraries and modules.
DEFINE[../../libcrypto]=$AESDEF
DEFINE[../../providers/libfips.a]=$AESDEF
DEFINE[../../providers/libdefault.a]=$AESDEF
# We only need to include the AESDEF stuff in the legacy provider when it's a
# separate module and it's dynamically linked with libcrypto. Otherwise, it
# already gets everything that the static libcrypto.a has, and doesn't need it
# added again.
IF[{- !$disabled{module} && !$disabled{shared} -}]
- DEFINE[../providers/liblegacy.a]=$AESDEF
+ DEFINE[../../providers/liblegacy.a]=$AESDEF
ENDIF
GENERATE[aes-ia64.s]=asm/aes-ia64.S
GENERATE[aes-586.S]=asm/aes-586.pl
DEPEND[aes-586.S]=../perlasm/x86asm.pl
GENERATE[vpaes-x86.S]=asm/vpaes-x86.pl
DEPEND[vpaes-586.S]=../perlasm/x86asm.pl
GENERATE[aesni-x86.S]=asm/aesni-x86.pl
DEPEND[aesni-586.S]=../perlasm/x86asm.pl
GENERATE[aes-x86_64.s]=asm/aes-x86_64.pl
GENERATE[vpaes-x86_64.s]=asm/vpaes-x86_64.pl
GENERATE[bsaes-x86_64.s]=asm/bsaes-x86_64.pl
GENERATE[aesni-x86_64.s]=asm/aesni-x86_64.pl
GENERATE[aesni-sha1-x86_64.s]=asm/aesni-sha1-x86_64.pl
GENERATE[aesni-sha256-x86_64.s]=asm/aesni-sha256-x86_64.pl
GENERATE[aesni-mb-x86_64.s]=asm/aesni-mb-x86_64.pl
GENERATE[aes-sparcv9.S]=asm/aes-sparcv9.pl
INCLUDE[aes-sparcv9.o]=..
GENERATE[aest4-sparcv9.S]=asm/aest4-sparcv9.pl
INCLUDE[aest4-sparcv9.o]=..
DEPEND[aest4-sparcv9.S]=../perlasm/sparcv9_modes.pl
GENERATE[aesfx-sparcv9.S]=asm/aesfx-sparcv9.pl
INCLUDE[aesfx-sparcv9.o]=..
GENERATE[aes-ppc.s]=asm/aes-ppc.pl
GENERATE[vpaes-ppc.s]=asm/vpaes-ppc.pl
GENERATE[aesp8-ppc.s]=asm/aesp8-ppc.pl
GENERATE[aes-parisc.s]=asm/aes-parisc.pl
GENERATE[aes-mips.S]=asm/aes-mips.pl
INCLUDE[aes-mips.o]=..
GENERATE[aesv8-armx.S]=asm/aesv8-armx.pl
INCLUDE[aesv8-armx.o]=..
GENERATE[vpaes-armv8.S]=asm/vpaes-armv8.pl
INCLUDE[vpaes-armv8.o]=..
GENERATE[aes-armv4.S]=asm/aes-armv4.pl
INCLUDE[aes-armv4.o]=..
GENERATE[bsaes-armv7.S]=asm/bsaes-armv7.pl
INCLUDE[bsaes-armv7.o]=..
GENERATE[aes-s390x.S]=asm/aes-s390x.pl
INCLUDE[aes-s390x.o]=..
GENERATE[aes-c64xplus.S]=asm/aes-c64xplus.pl
diff --git a/crypto/openssl/crypto/bio/bio_lib.c b/crypto/openssl/crypto/bio/bio_lib.c
index c86b9ac198ca..245a75afa1b8 100644
--- a/crypto/openssl/crypto/bio/bio_lib.c
+++ b/crypto/openssl/crypto/bio/bio_lib.c
@@ -1,982 +1,986 @@
/*
- * Copyright 1995-2023 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 1995-2024 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
*/
#define OPENSSL_SUPPRESS_DEPRECATED
#include <stdio.h>
#include <errno.h>
#include <openssl/crypto.h>
#include "internal/numbers.h"
#include "bio_local.h"
/*
* Helper macro for the callback to determine whether an operator expects a
* len parameter or not
*/
#define HAS_LEN_OPER(o) ((o) == BIO_CB_READ || (o) == BIO_CB_WRITE \
|| (o) == BIO_CB_GETS)
#ifndef OPENSSL_NO_DEPRECATED_3_0
# define HAS_CALLBACK(b) ((b)->callback != NULL || (b)->callback_ex != NULL)
#else
# define HAS_CALLBACK(b) ((b)->callback_ex != NULL)
#endif
/*
* Helper function to work out whether to call the new style callback or the old
* one, and translate between the two.
*
* This has a long return type for consistency with the old callback. Similarly
* for the "long" used for "inret"
*/
static long bio_call_callback(BIO *b, int oper, const char *argp, size_t len,
int argi, long argl, long inret,
size_t *processed)
{
long ret = inret;
#ifndef OPENSSL_NO_DEPRECATED_3_0
int bareoper;
if (b->callback_ex != NULL)
#endif
return b->callback_ex(b, oper, argp, len, argi, argl, inret, processed);
#ifndef OPENSSL_NO_DEPRECATED_3_0
/* Strip off any BIO_CB_RETURN flag */
bareoper = oper & ~BIO_CB_RETURN;
/*
* We have an old style callback, so we will have to do nasty casts and
* check for overflows.
*/
if (HAS_LEN_OPER(bareoper)) {
/* In this case |len| is set, and should be used instead of |argi| */
if (len > INT_MAX)
return -1;
argi = (int)len;
}
if (inret > 0 && (oper & BIO_CB_RETURN) && bareoper != BIO_CB_CTRL) {
if (*processed > INT_MAX)
return -1;
inret = *processed;
}
ret = b->callback(b, oper, argp, argi, argl, inret);
if (ret > 0 && (oper & BIO_CB_RETURN) && bareoper != BIO_CB_CTRL) {
*processed = (size_t)ret;
ret = 1;
}
#endif
return ret;
}
BIO *BIO_new_ex(OSSL_LIB_CTX *libctx, const BIO_METHOD *method)
{
BIO *bio = OPENSSL_zalloc(sizeof(*bio));
if (bio == NULL) {
ERR_raise(ERR_LIB_BIO, ERR_R_MALLOC_FAILURE);
return NULL;
}
bio->libctx = libctx;
bio->method = method;
bio->shutdown = 1;
bio->references = 1;
if (!CRYPTO_new_ex_data(CRYPTO_EX_INDEX_BIO, bio, &bio->ex_data))
goto err;
bio->lock = CRYPTO_THREAD_lock_new();
if (bio->lock == NULL) {
ERR_raise(ERR_LIB_BIO, ERR_R_MALLOC_FAILURE);
CRYPTO_free_ex_data(CRYPTO_EX_INDEX_BIO, bio, &bio->ex_data);
goto err;
}
if (method->create != NULL && !method->create(bio)) {
ERR_raise(ERR_LIB_BIO, ERR_R_INIT_FAIL);
CRYPTO_free_ex_data(CRYPTO_EX_INDEX_BIO, bio, &bio->ex_data);
CRYPTO_THREAD_lock_free(bio->lock);
goto err;
}
if (method->create == NULL)
bio->init = 1;
return bio;
err:
OPENSSL_free(bio);
return NULL;
}
BIO *BIO_new(const BIO_METHOD *method)
{
return BIO_new_ex(NULL, method);
}
int BIO_free(BIO *a)
{
int ret;
if (a == NULL)
return 0;
if (CRYPTO_DOWN_REF(&a->references, &ret, a->lock) <= 0)
return 0;
REF_PRINT_COUNT("BIO", a);
if (ret > 0)
return 1;
REF_ASSERT_ISNT(ret < 0);
if (HAS_CALLBACK(a)) {
ret = (int)bio_call_callback(a, BIO_CB_FREE, NULL, 0, 0, 0L, 1L, NULL);
if (ret <= 0)
return 0;
}
if ((a->method != NULL) && (a->method->destroy != NULL))
a->method->destroy(a);
CRYPTO_free_ex_data(CRYPTO_EX_INDEX_BIO, a, &a->ex_data);
CRYPTO_THREAD_lock_free(a->lock);
OPENSSL_free(a);
return 1;
}
void BIO_set_data(BIO *a, void *ptr)
{
a->ptr = ptr;
}
void *BIO_get_data(BIO *a)
{
return a->ptr;
}
void BIO_set_init(BIO *a, int init)
{
a->init = init;
}
int BIO_get_init(BIO *a)
{
return a->init;
}
void BIO_set_shutdown(BIO *a, int shut)
{
a->shutdown = shut;
}
int BIO_get_shutdown(BIO *a)
{
return a->shutdown;
}
void BIO_vfree(BIO *a)
{
BIO_free(a);
}
int BIO_up_ref(BIO *a)
{
int i;
if (CRYPTO_UP_REF(&a->references, &i, a->lock) <= 0)
return 0;
REF_PRINT_COUNT("BIO", a);
REF_ASSERT_ISNT(i < 2);
return i > 1;
}
void BIO_clear_flags(BIO *b, int flags)
{
b->flags &= ~flags;
}
int BIO_test_flags(const BIO *b, int flags)
{
return (b->flags & flags);
}
void BIO_set_flags(BIO *b, int flags)
{
b->flags |= flags;
}
#ifndef OPENSSL_NO_DEPRECATED_3_0
BIO_callback_fn BIO_get_callback(const BIO *b)
{
return b->callback;
}
void BIO_set_callback(BIO *b, BIO_callback_fn cb)
{
b->callback = cb;
}
#endif
BIO_callback_fn_ex BIO_get_callback_ex(const BIO *b)
{
return b->callback_ex;
}
void BIO_set_callback_ex(BIO *b, BIO_callback_fn_ex cb)
{
b->callback_ex = cb;
}
void BIO_set_callback_arg(BIO *b, char *arg)
{
b->cb_arg = arg;
}
char *BIO_get_callback_arg(const BIO *b)
{
return b->cb_arg;
}
const char *BIO_method_name(const BIO *b)
{
return b->method->name;
}
int BIO_method_type(const BIO *b)
{
return b->method->type;
}
/*
* This is essentially the same as BIO_read_ex() except that it allows
* 0 or a negative value to indicate failure (retryable or not) in the return.
* This is for compatibility with the old style BIO_read(), where existing code
* may make assumptions about the return value that it might get.
*/
static int bio_read_intern(BIO *b, void *data, size_t dlen, size_t *readbytes)
{
int ret;
if (b == NULL) {
ERR_raise(ERR_LIB_BIO, ERR_R_PASSED_NULL_PARAMETER);
return -1;
}
if (b->method == NULL || b->method->bread == NULL) {
ERR_raise(ERR_LIB_BIO, BIO_R_UNSUPPORTED_METHOD);
return -2;
}
if (HAS_CALLBACK(b) &&
((ret = (int)bio_call_callback(b, BIO_CB_READ, data, dlen, 0, 0L, 1L,
NULL)) <= 0))
return ret;
if (!b->init) {
ERR_raise(ERR_LIB_BIO, BIO_R_UNINITIALIZED);
return -1;
}
ret = b->method->bread(b, data, dlen, readbytes);
if (ret > 0)
b->num_read += (uint64_t)*readbytes;
if (HAS_CALLBACK(b))
ret = (int)bio_call_callback(b, BIO_CB_READ | BIO_CB_RETURN, data,
dlen, 0, 0L, ret, readbytes);
/* Shouldn't happen */
if (ret > 0 && *readbytes > dlen) {
ERR_raise(ERR_LIB_BIO, ERR_R_INTERNAL_ERROR);
return -1;
}
return ret;
}
int BIO_read(BIO *b, void *data, int dlen)
{
size_t readbytes;
int ret;
if (dlen < 0)
return 0;
ret = bio_read_intern(b, data, (size_t)dlen, &readbytes);
if (ret > 0) {
/* *readbytes should always be <= dlen */
ret = (int)readbytes;
}
return ret;
}
int BIO_read_ex(BIO *b, void *data, size_t dlen, size_t *readbytes)
{
return bio_read_intern(b, data, dlen, readbytes) > 0;
}
static int bio_write_intern(BIO *b, const void *data, size_t dlen,
size_t *written)
{
size_t local_written;
int ret;
if (written != NULL)
*written = 0;
/*
* b == NULL is not an error but just means that zero bytes are written.
* Do not raise an error here.
*/
if (b == NULL)
return 0;
if (b->method == NULL || b->method->bwrite == NULL) {
ERR_raise(ERR_LIB_BIO, BIO_R_UNSUPPORTED_METHOD);
return -2;
}
if (HAS_CALLBACK(b) &&
((ret = (int)bio_call_callback(b, BIO_CB_WRITE, data, dlen, 0, 0L, 1L,
NULL)) <= 0))
return ret;
if (!b->init) {
ERR_raise(ERR_LIB_BIO, BIO_R_UNINITIALIZED);
return -1;
}
ret = b->method->bwrite(b, data, dlen, &local_written);
if (ret > 0)
b->num_write += (uint64_t)local_written;
if (HAS_CALLBACK(b))
ret = (int)bio_call_callback(b, BIO_CB_WRITE | BIO_CB_RETURN, data,
dlen, 0, 0L, ret, &local_written);
if (written != NULL)
*written = local_written;
return ret;
}
int BIO_write(BIO *b, const void *data, int dlen)
{
size_t written;
int ret;
if (dlen <= 0)
return 0;
ret = bio_write_intern(b, data, (size_t)dlen, &written);
if (ret > 0) {
/* written should always be <= dlen */
ret = (int)written;
}
return ret;
}
int BIO_write_ex(BIO *b, const void *data, size_t dlen, size_t *written)
{
return bio_write_intern(b, data, dlen, written) > 0
|| (b != NULL && dlen == 0); /* order is important for *written */
}
int BIO_puts(BIO *b, const char *buf)
{
int ret;
size_t written = 0;
if (b == NULL) {
ERR_raise(ERR_LIB_BIO, ERR_R_PASSED_NULL_PARAMETER);
return -1;
}
if (b->method == NULL || b->method->bputs == NULL) {
ERR_raise(ERR_LIB_BIO, BIO_R_UNSUPPORTED_METHOD);
return -2;
}
if (HAS_CALLBACK(b)) {
ret = (int)bio_call_callback(b, BIO_CB_PUTS, buf, 0, 0, 0L, 1L, NULL);
if (ret <= 0)
return ret;
}
if (!b->init) {
ERR_raise(ERR_LIB_BIO, BIO_R_UNINITIALIZED);
return -1;
}
ret = b->method->bputs(b, buf);
if (ret > 0) {
b->num_write += (uint64_t)ret;
written = ret;
ret = 1;
}
if (HAS_CALLBACK(b))
ret = (int)bio_call_callback(b, BIO_CB_PUTS | BIO_CB_RETURN, buf, 0, 0,
0L, ret, &written);
if (ret > 0) {
if (written > INT_MAX) {
ERR_raise(ERR_LIB_BIO, BIO_R_LENGTH_TOO_LONG);
ret = -1;
} else {
ret = (int)written;
}
}
return ret;
}
int BIO_gets(BIO *b, char *buf, int size)
{
int ret;
size_t readbytes = 0;
if (b == NULL) {
ERR_raise(ERR_LIB_BIO, ERR_R_PASSED_NULL_PARAMETER);
return -1;
}
if (b->method == NULL || b->method->bgets == NULL) {
ERR_raise(ERR_LIB_BIO, BIO_R_UNSUPPORTED_METHOD);
return -2;
}
if (size < 0) {
ERR_raise(ERR_LIB_BIO, BIO_R_INVALID_ARGUMENT);
return -1;
}
if (HAS_CALLBACK(b)) {
ret = (int)bio_call_callback(b, BIO_CB_GETS, buf, size, 0, 0L, 1, NULL);
if (ret <= 0)
return ret;
}
if (!b->init) {
ERR_raise(ERR_LIB_BIO, BIO_R_UNINITIALIZED);
return -1;
}
ret = b->method->bgets(b, buf, size);
if (ret > 0) {
readbytes = ret;
ret = 1;
}
if (HAS_CALLBACK(b))
ret = (int)bio_call_callback(b, BIO_CB_GETS | BIO_CB_RETURN, buf, size,
0, 0L, ret, &readbytes);
if (ret > 0) {
/* Shouldn't happen */
if (readbytes > (size_t)size)
ret = -1;
else
ret = (int)readbytes;
}
return ret;
}
int BIO_get_line(BIO *bio, char *buf, int size)
{
int ret = 0;
char *ptr = buf;
if (buf == NULL) {
ERR_raise(ERR_LIB_BIO, ERR_R_PASSED_NULL_PARAMETER);
return -1;
}
if (size <= 0) {
ERR_raise(ERR_LIB_BIO, BIO_R_INVALID_ARGUMENT);
return -1;
}
*buf = '\0';
if (bio == NULL) {
ERR_raise(ERR_LIB_BIO, ERR_R_PASSED_NULL_PARAMETER);
return -1;
}
if (!bio->init) {
ERR_raise(ERR_LIB_BIO, BIO_R_UNINITIALIZED);
return -1;
}
while (size-- > 1 && (ret = BIO_read(bio, ptr, 1)) > 0)
if (*ptr++ == '\n')
break;
*ptr = '\0';
return ret > 0 || BIO_eof(bio) ? ptr - buf : ret;
}
int BIO_indent(BIO *b, int indent, int max)
{
if (indent < 0)
indent = 0;
if (indent > max)
indent = max;
while (indent--)
if (BIO_puts(b, " ") != 1)
return 0;
return 1;
}
long BIO_int_ctrl(BIO *b, int cmd, long larg, int iarg)
{
int i;
i = iarg;
return BIO_ctrl(b, cmd, larg, (char *)&i);
}
void *BIO_ptr_ctrl(BIO *b, int cmd, long larg)
{
void *p = NULL;
if (BIO_ctrl(b, cmd, larg, (char *)&p) <= 0)
return NULL;
else
return p;
}
long BIO_ctrl(BIO *b, int cmd, long larg, void *parg)
{
long ret;
if (b == NULL)
return -1;
if (b->method == NULL || b->method->ctrl == NULL) {
ERR_raise(ERR_LIB_BIO, BIO_R_UNSUPPORTED_METHOD);
return -2;
}
if (HAS_CALLBACK(b)) {
ret = bio_call_callback(b, BIO_CB_CTRL, parg, 0, cmd, larg, 1L, NULL);
if (ret <= 0)
return ret;
}
ret = b->method->ctrl(b, cmd, larg, parg);
if (HAS_CALLBACK(b))
ret = bio_call_callback(b, BIO_CB_CTRL | BIO_CB_RETURN, parg, 0, cmd,
larg, ret, NULL);
return ret;
}
long BIO_callback_ctrl(BIO *b, int cmd, BIO_info_cb *fp)
{
long ret;
if (b == NULL)
return -2;
if (b->method == NULL || b->method->callback_ctrl == NULL
|| cmd != BIO_CTRL_SET_CALLBACK) {
ERR_raise(ERR_LIB_BIO, BIO_R_UNSUPPORTED_METHOD);
return -2;
}
if (HAS_CALLBACK(b)) {
ret = bio_call_callback(b, BIO_CB_CTRL, (void *)&fp, 0, cmd, 0, 1L,
NULL);
if (ret <= 0)
return ret;
}
ret = b->method->callback_ctrl(b, cmd, fp);
if (HAS_CALLBACK(b))
ret = bio_call_callback(b, BIO_CB_CTRL | BIO_CB_RETURN, (void *)&fp, 0,
cmd, 0, ret, NULL);
return ret;
}
/*
* It is unfortunate to duplicate in functions what the BIO_(w)pending macros
* do; but those macros have inappropriate return type, and for interfacing
* from other programming languages, C macros aren't much of a help anyway.
*/
size_t BIO_ctrl_pending(BIO *bio)
{
long ret = BIO_ctrl(bio, BIO_CTRL_PENDING, 0, NULL);
if (ret < 0)
ret = 0;
#if LONG_MAX > SIZE_MAX
if (ret > SIZE_MAX)
ret = SIZE_MAX;
#endif
return (size_t)ret;
}
size_t BIO_ctrl_wpending(BIO *bio)
{
long ret = BIO_ctrl(bio, BIO_CTRL_WPENDING, 0, NULL);
if (ret < 0)
ret = 0;
#if LONG_MAX > SIZE_MAX
if (ret > SIZE_MAX)
ret = SIZE_MAX;
#endif
return (size_t)ret;
}
/* put the 'bio' on the end of b's list of operators */
BIO *BIO_push(BIO *b, BIO *bio)
{
BIO *lb;
if (b == NULL)
return bio;
lb = b;
while (lb->next_bio != NULL)
lb = lb->next_bio;
lb->next_bio = bio;
if (bio != NULL)
bio->prev_bio = lb;
/* called to do internal processing */
BIO_ctrl(b, BIO_CTRL_PUSH, 0, lb);
return b;
}
/* Remove the first and return the rest */
BIO *BIO_pop(BIO *b)
{
BIO *ret;
if (b == NULL)
return NULL;
ret = b->next_bio;
BIO_ctrl(b, BIO_CTRL_POP, 0, b);
if (b->prev_bio != NULL)
b->prev_bio->next_bio = b->next_bio;
if (b->next_bio != NULL)
b->next_bio->prev_bio = b->prev_bio;
b->next_bio = NULL;
b->prev_bio = NULL;
return ret;
}
BIO *BIO_get_retry_BIO(BIO *bio, int *reason)
{
BIO *b, *last;
b = last = bio;
for (;;) {
if (!BIO_should_retry(b))
break;
last = b;
b = b->next_bio;
if (b == NULL)
break;
}
if (reason != NULL)
*reason = last->retry_reason;
return last;
}
int BIO_get_retry_reason(BIO *bio)
{
return bio->retry_reason;
}
void BIO_set_retry_reason(BIO *bio, int reason)
{
bio->retry_reason = reason;
}
BIO *BIO_find_type(BIO *bio, int type)
{
int mt, mask;
if (bio == NULL) {
ERR_raise(ERR_LIB_BIO, ERR_R_PASSED_NULL_PARAMETER);
return NULL;
}
mask = type & 0xff;
do {
if (bio->method != NULL) {
mt = bio->method->type;
if (!mask) {
if (mt & type)
return bio;
} else if (mt == type) {
return bio;
}
}
bio = bio->next_bio;
} while (bio != NULL);
return NULL;
}
BIO *BIO_next(BIO *b)
{
if (b == NULL)
return NULL;
return b->next_bio;
}
void BIO_set_next(BIO *b, BIO *next)
{
b->next_bio = next;
}
void BIO_free_all(BIO *bio)
{
BIO *b;
int ref;
while (bio != NULL) {
b = bio;
ref = b->references;
bio = bio->next_bio;
BIO_free(b);
/* Since ref count > 1, don't free anyone else. */
if (ref > 1)
break;
}
}
BIO *BIO_dup_chain(BIO *in)
{
BIO *ret = NULL, *eoc = NULL, *bio, *new_bio;
for (bio = in; bio != NULL; bio = bio->next_bio) {
if ((new_bio = BIO_new(bio->method)) == NULL)
goto err;
#ifndef OPENSSL_NO_DEPRECATED_3_0
new_bio->callback = bio->callback;
#endif
new_bio->callback_ex = bio->callback_ex;
new_bio->cb_arg = bio->cb_arg;
new_bio->init = bio->init;
new_bio->shutdown = bio->shutdown;
new_bio->flags = bio->flags;
/* This will let SSL_s_sock() work with stdin/stdout */
new_bio->num = bio->num;
if (BIO_dup_state(bio, (char *)new_bio) <= 0) {
BIO_free(new_bio);
goto err;
}
/* copy app data */
if (!CRYPTO_dup_ex_data(CRYPTO_EX_INDEX_BIO, &new_bio->ex_data,
&bio->ex_data)) {
BIO_free(new_bio);
goto err;
}
if (ret == NULL) {
eoc = new_bio;
ret = eoc;
} else {
BIO_push(eoc, new_bio);
eoc = new_bio;
}
}
return ret;
err:
BIO_free_all(ret);
return NULL;
}
void BIO_copy_next_retry(BIO *b)
{
BIO_set_flags(b, BIO_get_retry_flags(b->next_bio));
b->retry_reason = b->next_bio->retry_reason;
}
int BIO_set_ex_data(BIO *bio, int idx, void *data)
{
return CRYPTO_set_ex_data(&(bio->ex_data), idx, data);
}
void *BIO_get_ex_data(const BIO *bio, int idx)
{
return CRYPTO_get_ex_data(&(bio->ex_data), idx);
}
uint64_t BIO_number_read(BIO *bio)
{
if (bio)
return bio->num_read;
return 0;
}
uint64_t BIO_number_written(BIO *bio)
{
if (bio)
return bio->num_write;
return 0;
}
void bio_free_ex_data(BIO *bio)
{
CRYPTO_free_ex_data(CRYPTO_EX_INDEX_BIO, bio, &bio->ex_data);
}
void bio_cleanup(void)
{
#ifndef OPENSSL_NO_SOCK
bio_sock_cleanup_int();
CRYPTO_THREAD_lock_free(bio_lookup_lock);
bio_lookup_lock = NULL;
#endif
CRYPTO_THREAD_lock_free(bio_type_lock);
bio_type_lock = NULL;
}
/* Internal variant of the below BIO_wait() not calling BIOerr() */
static int bio_wait(BIO *bio, time_t max_time, unsigned int nap_milliseconds)
{
#ifndef OPENSSL_NO_SOCK
int fd;
#endif
long sec_diff;
if (max_time == 0) /* no timeout */
return 1;
#ifndef OPENSSL_NO_SOCK
- if (BIO_get_fd(bio, &fd) > 0 && fd < FD_SETSIZE)
- return BIO_socket_wait(fd, BIO_should_read(bio), max_time);
+ if (BIO_get_fd(bio, &fd) > 0) {
+ int ret = BIO_socket_wait(fd, BIO_should_read(bio), max_time);
+
+ if (ret != -1)
+ return ret;
+ }
#endif
/* fall back to polling since no sockets are available */
sec_diff = (long)(max_time - time(NULL)); /* might overflow */
if (sec_diff < 0)
return 0; /* clearly timeout */
/* now take a nap at most the given number of milliseconds */
if (sec_diff == 0) { /* we are below the 1 seconds resolution of max_time */
if (nap_milliseconds > 1000)
nap_milliseconds = 1000;
} else { /* for sec_diff > 0, take min(sec_diff * 1000, nap_milliseconds) */
if ((unsigned long)sec_diff * 1000 < nap_milliseconds)
nap_milliseconds = (unsigned int)sec_diff * 1000;
}
ossl_sleep(nap_milliseconds);
return 1;
}
/*-
* Wait on (typically socket-based) BIO at most until max_time.
* Succeed immediately if max_time == 0.
* If sockets are not available support polling: succeed after waiting at most
* the number of nap_milliseconds in order to avoid a tight busy loop.
* Call BIOerr(...) on timeout or error.
* Returns -1 on error, 0 on timeout, and 1 on success.
*/
int BIO_wait(BIO *bio, time_t max_time, unsigned int nap_milliseconds)
{
int rv = bio_wait(bio, max_time, nap_milliseconds);
if (rv <= 0)
ERR_raise(ERR_LIB_BIO,
rv == 0 ? BIO_R_TRANSFER_TIMEOUT : BIO_R_TRANSFER_ERROR);
return rv;
}
/*
* Connect via given BIO using BIO_do_connect() until success/timeout/error.
* Parameter timeout == 0 means no timeout, < 0 means exactly one try.
* For non-blocking and potentially even non-socket BIOs perform polling with
* the given density: between polls sleep nap_milliseconds using BIO_wait()
* in order to avoid a tight busy loop.
* Returns -1 on error, 0 on timeout, and 1 on success.
*/
int BIO_do_connect_retry(BIO *bio, int timeout, int nap_milliseconds)
{
int blocking = timeout <= 0;
time_t max_time = timeout > 0 ? time(NULL) + timeout : 0;
int rv;
if (bio == NULL) {
ERR_raise(ERR_LIB_BIO, ERR_R_PASSED_NULL_PARAMETER);
return -1;
}
if (nap_milliseconds < 0)
nap_milliseconds = 100;
BIO_set_nbio(bio, !blocking);
retry:
ERR_set_mark();
rv = BIO_do_connect(bio);
if (rv <= 0) { /* could be timeout or retryable error or fatal error */
int err = ERR_peek_last_error();
int reason = ERR_GET_REASON(err);
int do_retry = BIO_should_retry(bio); /* may be 1 only if !blocking */
if (ERR_GET_LIB(err) == ERR_LIB_BIO) {
switch (reason) {
case ERR_R_SYS_LIB:
/*
* likely retryable system error occurred, which may be
* EAGAIN (resource temporarily unavailable) some 40 secs after
* calling getaddrinfo(): Temporary failure in name resolution
* or a premature ETIMEDOUT, some 30 seconds after connect()
*/
case BIO_R_CONNECT_ERROR:
case BIO_R_NBIO_CONNECT_ERROR:
/* some likely retryable connection error occurred */
(void)BIO_reset(bio); /* often needed to avoid retry failure */
do_retry = 1;
break;
default:
break;
}
}
if (timeout >= 0 && do_retry) {
ERR_pop_to_mark();
/* will not actually wait if timeout == 0 (i.e., blocking BIO): */
rv = bio_wait(bio, max_time, nap_milliseconds);
if (rv > 0)
goto retry;
ERR_raise(ERR_LIB_BIO,
rv == 0 ? BIO_R_CONNECT_TIMEOUT : BIO_R_CONNECT_ERROR);
} else {
ERR_clear_last_mark();
rv = -1;
if (err == 0) /* missing error queue entry */
/* workaround: general error */
ERR_raise(ERR_LIB_BIO, BIO_R_CONNECT_ERROR);
}
} else {
ERR_clear_last_mark();
}
return rv;
}
diff --git a/crypto/openssl/crypto/bio/bio_sock.c b/crypto/openssl/crypto/bio/bio_sock.c
index 476cbcc5cef1..12e6a68e3a25 100644
--- a/crypto/openssl/crypto/bio/bio_sock.c
+++ b/crypto/openssl/crypto/bio/bio_sock.c
@@ -1,415 +1,419 @@
/*
- * Copyright 1995-2022 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 1995-2024 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 <stdio.h>
#include <stdlib.h>
#include "bio_local.h"
#ifndef OPENSSL_NO_SOCK
# define SOCKET_PROTOCOL IPPROTO_TCP
# ifdef SO_MAXCONN
# define MAX_LISTEN SO_MAXCONN
# elif defined(SOMAXCONN)
# define MAX_LISTEN SOMAXCONN
# else
# define MAX_LISTEN 32
# endif
# if defined(OPENSSL_SYS_WINDOWS)
static int wsa_init_done = 0;
# endif
# if defined __TANDEM
# include <unistd.h>
# include <sys/time.h> /* select */
# if defined(OPENSSL_TANDEM_FLOSS)
# include <floss.h(floss_select)>
# endif
# elif defined _WIN32
# include <winsock.h> /* for type fd_set */
# else
# include <unistd.h>
# if defined __VMS
# include <sys/socket.h>
# elif defined _HPUX_SOURCE
# include <sys/time.h>
# else
# include <sys/select.h>
# endif
# endif
# ifndef OPENSSL_NO_DEPRECATED_1_1_0
int BIO_get_host_ip(const char *str, unsigned char *ip)
{
BIO_ADDRINFO *res = NULL;
int ret = 0;
if (BIO_sock_init() != 1)
return 0; /* don't generate another error code here */
if (BIO_lookup(str, NULL, BIO_LOOKUP_CLIENT, AF_INET, SOCK_STREAM, &res)) {
size_t l;
if (BIO_ADDRINFO_family(res) != AF_INET) {
ERR_raise(ERR_LIB_BIO, BIO_R_GETHOSTBYNAME_ADDR_IS_NOT_AF_INET);
} else if (BIO_ADDR_rawaddress(BIO_ADDRINFO_address(res), NULL, &l)) {
/*
* Because only AF_INET addresses will reach this far, we can assert
* that l should be 4
*/
if (ossl_assert(l == 4))
ret = BIO_ADDR_rawaddress(BIO_ADDRINFO_address(res), ip, &l);
}
BIO_ADDRINFO_free(res);
} else {
ERR_add_error_data(2, "host=", str);
}
return ret;
}
int BIO_get_port(const char *str, unsigned short *port_ptr)
{
BIO_ADDRINFO *res = NULL;
int ret = 0;
if (str == NULL) {
ERR_raise(ERR_LIB_BIO, BIO_R_NO_PORT_DEFINED);
return 0;
}
if (BIO_sock_init() != 1)
return 0; /* don't generate another error code here */
if (BIO_lookup(NULL, str, BIO_LOOKUP_CLIENT, AF_INET, SOCK_STREAM, &res)) {
if (BIO_ADDRINFO_family(res) != AF_INET) {
ERR_raise(ERR_LIB_BIO, BIO_R_ADDRINFO_ADDR_IS_NOT_AF_INET);
} else {
*port_ptr = ntohs(BIO_ADDR_rawport(BIO_ADDRINFO_address(res)));
ret = 1;
}
BIO_ADDRINFO_free(res);
} else {
ERR_add_error_data(2, "host=", str);
}
return ret;
}
# endif
int BIO_sock_error(int sock)
{
int j = 0, i;
socklen_t size = sizeof(j);
/*
* Note: under Windows the third parameter is of type (char *) whereas
* under other systems it is (void *) if you don't have a cast it will
* choke the compiler: if you do have a cast then you can either go for
* (char *) or (void *).
*/
i = getsockopt(sock, SOL_SOCKET, SO_ERROR, (void *)&j, &size);
if (i < 0)
return get_last_socket_error();
else
return j;
}
# ifndef OPENSSL_NO_DEPRECATED_1_1_0
struct hostent *BIO_gethostbyname(const char *name)
{
/*
* Caching gethostbyname() results forever is wrong, so we have to let
* the true gethostbyname() worry about this
*/
return gethostbyname(name);
}
# endif
int BIO_sock_init(void)
{
# ifdef OPENSSL_SYS_WINDOWS
static struct WSAData wsa_state;
if (!wsa_init_done) {
wsa_init_done = 1;
memset(&wsa_state, 0, sizeof(wsa_state));
/*
* Not making wsa_state available to the rest of the code is formally
* wrong. But the structures we use are [believed to be] invariable
* among Winsock DLLs, while API availability is [expected to be]
* probed at run-time with DSO_global_lookup.
*/
if (WSAStartup(0x0202, &wsa_state) != 0) {
ERR_raise_data(ERR_LIB_SYS, get_last_socket_error(),
"calling wsastartup()");
ERR_raise(ERR_LIB_BIO, BIO_R_WSASTARTUP);
return -1;
}
}
# endif /* OPENSSL_SYS_WINDOWS */
# ifdef WATT32
extern int _watt_do_exit;
_watt_do_exit = 0; /* don't make sock_init() call exit() */
if (sock_init())
return -1;
# endif
return 1;
}
void bio_sock_cleanup_int(void)
{
# ifdef OPENSSL_SYS_WINDOWS
if (wsa_init_done) {
wsa_init_done = 0;
WSACleanup();
}
# endif
}
int BIO_socket_ioctl(int fd, long type, void *arg)
{
int i;
# ifdef __DJGPP__
i = ioctlsocket(fd, type, (char *)arg);
# else
# if defined(OPENSSL_SYS_VMS)
/*-
* 2011-02-18 SMS.
* VMS ioctl() can't tolerate a 64-bit "void *arg", but we
* observe that all the consumers pass in an "unsigned long *",
* so we arrange a local copy with a short pointer, and use
* that, instead.
*/
# if __INITIAL_POINTER_SIZE == 64
# define ARG arg_32p
# pragma pointer_size save
# pragma pointer_size 32
unsigned long arg_32;
unsigned long *arg_32p;
# pragma pointer_size restore
arg_32p = &arg_32;
arg_32 = *((unsigned long *)arg);
# else /* __INITIAL_POINTER_SIZE == 64 */
# define ARG arg
# endif /* __INITIAL_POINTER_SIZE == 64 [else] */
# else /* defined(OPENSSL_SYS_VMS) */
# define ARG arg
# endif /* defined(OPENSSL_SYS_VMS) [else] */
i = ioctlsocket(fd, type, ARG);
# endif /* __DJGPP__ */
if (i < 0)
ERR_raise_data(ERR_LIB_SYS, get_last_socket_error(),
"calling ioctlsocket()");
return i;
}
# ifndef OPENSSL_NO_DEPRECATED_1_1_0
int BIO_get_accept_socket(char *host, int bind_mode)
{
int s = INVALID_SOCKET;
char *h = NULL, *p = NULL;
BIO_ADDRINFO *res = NULL;
if (!BIO_parse_hostserv(host, &h, &p, BIO_PARSE_PRIO_SERV))
return INVALID_SOCKET;
if (BIO_sock_init() != 1)
return INVALID_SOCKET;
if (BIO_lookup(h, p, BIO_LOOKUP_SERVER, AF_UNSPEC, SOCK_STREAM, &res) != 0)
goto err;
if ((s = BIO_socket(BIO_ADDRINFO_family(res), BIO_ADDRINFO_socktype(res),
BIO_ADDRINFO_protocol(res), 0)) == INVALID_SOCKET) {
s = INVALID_SOCKET;
goto err;
}
if (!BIO_listen(s, BIO_ADDRINFO_address(res),
bind_mode ? BIO_SOCK_REUSEADDR : 0)) {
BIO_closesocket(s);
s = INVALID_SOCKET;
}
err:
BIO_ADDRINFO_free(res);
OPENSSL_free(h);
OPENSSL_free(p);
return s;
}
int BIO_accept(int sock, char **ip_port)
{
BIO_ADDR res;
int ret = -1;
ret = BIO_accept_ex(sock, &res, 0);
if (ret == (int)INVALID_SOCKET) {
if (BIO_sock_should_retry(ret)) {
ret = -2;
goto end;
}
ERR_raise_data(ERR_LIB_SYS, get_last_socket_error(),
"calling accept()");
ERR_raise(ERR_LIB_BIO, BIO_R_ACCEPT_ERROR);
goto end;
}
if (ip_port != NULL) {
char *host = BIO_ADDR_hostname_string(&res, 1);
char *port = BIO_ADDR_service_string(&res, 1);
if (host != NULL && port != NULL)
*ip_port = OPENSSL_zalloc(strlen(host) + strlen(port) + 2);
else
*ip_port = NULL;
if (*ip_port == NULL) {
ERR_raise(ERR_LIB_BIO, ERR_R_MALLOC_FAILURE);
BIO_closesocket(ret);
ret = (int)INVALID_SOCKET;
} else {
strcpy(*ip_port, host);
strcat(*ip_port, ":");
strcat(*ip_port, port);
}
OPENSSL_free(host);
OPENSSL_free(port);
}
end:
return ret;
}
# endif
int BIO_set_tcp_ndelay(int s, int on)
{
int ret = 0;
# if defined(TCP_NODELAY) && (defined(IPPROTO_TCP) || defined(SOL_TCP))
int opt;
# ifdef SOL_TCP
opt = SOL_TCP;
# else
# ifdef IPPROTO_TCP
opt = IPPROTO_TCP;
# endif
# endif
ret = setsockopt(s, opt, TCP_NODELAY, (char *)&on, sizeof(on));
# endif
return (ret == 0);
}
int BIO_socket_nbio(int s, int mode)
{
int ret = -1;
int l;
l = mode;
# ifdef FIONBIO
l = mode;
ret = BIO_socket_ioctl(s, FIONBIO, &l);
# elif defined(F_GETFL) && defined(F_SETFL) && (defined(O_NONBLOCK) || defined(FNDELAY))
/* make sure this call always pushes an error level; BIO_socket_ioctl() does so, so we do too. */
l = fcntl(s, F_GETFL, 0);
if (l == -1) {
ERR_raise_data(ERR_LIB_SYS, get_last_sys_error(),
"calling fcntl()");
ret = -1;
} else {
# if defined(O_NONBLOCK)
l &= ~O_NONBLOCK;
# else
l &= ~FNDELAY; /* BSD4.x */
# endif
if (mode) {
# if defined(O_NONBLOCK)
l |= O_NONBLOCK;
# else
l |= FNDELAY; /* BSD4.x */
# endif
}
ret = fcntl(s, F_SETFL, l);
if (ret < 0) {
ERR_raise_data(ERR_LIB_SYS, get_last_sys_error(),
"calling fcntl()");
}
}
# else
/* make sure this call always pushes an error level; BIO_socket_ioctl() does so, so we do too. */
ERR_raise(ERR_LIB_BIO, ERR_R_PASSED_INVALID_ARGUMENT);
# endif
return (ret == 0);
}
int BIO_sock_info(int sock,
enum BIO_sock_info_type type, union BIO_sock_info_u *info)
{
switch (type) {
case BIO_SOCK_INFO_ADDRESS:
{
socklen_t addr_len;
int ret = 0;
addr_len = sizeof(*info->addr);
ret = getsockname(sock, BIO_ADDR_sockaddr_noconst(info->addr),
&addr_len);
if (ret == -1) {
ERR_raise_data(ERR_LIB_SYS, get_last_socket_error(),
"calling getsockname()");
ERR_raise(ERR_LIB_BIO, BIO_R_GETSOCKNAME_ERROR);
return 0;
}
if ((size_t)addr_len > sizeof(*info->addr)) {
ERR_raise(ERR_LIB_BIO, BIO_R_GETSOCKNAME_TRUNCATED_ADDRESS);
return 0;
}
}
break;
default:
ERR_raise(ERR_LIB_BIO, BIO_R_UNKNOWN_INFO_TYPE);
return 0;
}
return 1;
}
/*
* Wait on fd at most until max_time; succeed immediately if max_time == 0.
* If for_read == 0 then assume to wait for writing, else wait for reading.
* Returns -1 on error, 0 on timeout, and 1 on success.
*/
int BIO_socket_wait(int fd, int for_read, time_t max_time)
{
fd_set confds;
struct timeval tv;
time_t now;
+#ifdef _WIN32
+ if ((SOCKET)fd == INVALID_SOCKET)
+#else
if (fd < 0 || fd >= FD_SETSIZE)
+#endif
return -1;
if (max_time == 0)
return 1;
now = time(NULL);
if (max_time < now)
return 0;
FD_ZERO(&confds);
openssl_fdset(fd, &confds);
tv.tv_usec = 0;
tv.tv_sec = (long)(max_time - now); /* might overflow */
return select(fd + 1, for_read ? &confds : NULL,
for_read ? NULL : &confds, NULL, &tv);
}
#endif /* !defined(OPENSSL_NO_SOCK) */
diff --git a/crypto/openssl/crypto/bn/bn_lib.c b/crypto/openssl/crypto/bn/bn_lib.c
index cf1bfe8ab085..9677a603cb2d 100644
--- a/crypto/openssl/crypto/bn/bn_lib.c
+++ b/crypto/openssl/crypto/bn/bn_lib.c
@@ -1,1063 +1,1104 @@
/*
- * Copyright 1995-2023 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 1995-2024 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 <assert.h>
#include <limits.h>
#include "internal/cryptlib.h"
#include "internal/endian.h"
#include "bn_local.h"
#include <openssl/opensslconf.h>
#include "internal/constant_time.h"
/* This stuff appears to be completely unused, so is deprecated */
#ifndef OPENSSL_NO_DEPRECATED_0_9_8
/*-
* For a 32 bit machine
* 2 - 4 == 128
* 3 - 8 == 256
* 4 - 16 == 512
* 5 - 32 == 1024
* 6 - 64 == 2048
* 7 - 128 == 4096
* 8 - 256 == 8192
*/
static int bn_limit_bits = 0;
static int bn_limit_num = 8; /* (1<<bn_limit_bits) */
static int bn_limit_bits_low = 0;
static int bn_limit_num_low = 8; /* (1<<bn_limit_bits_low) */
static int bn_limit_bits_high = 0;
static int bn_limit_num_high = 8; /* (1<<bn_limit_bits_high) */
static int bn_limit_bits_mont = 0;
static int bn_limit_num_mont = 8; /* (1<<bn_limit_bits_mont) */
void BN_set_params(int mult, int high, int low, int mont)
{
if (mult >= 0) {
if (mult > (int)(sizeof(int) * 8) - 1)
mult = sizeof(int) * 8 - 1;
bn_limit_bits = mult;
bn_limit_num = 1 << mult;
}
if (high >= 0) {
if (high > (int)(sizeof(int) * 8) - 1)
high = sizeof(int) * 8 - 1;
bn_limit_bits_high = high;
bn_limit_num_high = 1 << high;
}
if (low >= 0) {
if (low > (int)(sizeof(int) * 8) - 1)
low = sizeof(int) * 8 - 1;
bn_limit_bits_low = low;
bn_limit_num_low = 1 << low;
}
if (mont >= 0) {
if (mont > (int)(sizeof(int) * 8) - 1)
mont = sizeof(int) * 8 - 1;
bn_limit_bits_mont = mont;
bn_limit_num_mont = 1 << mont;
}
}
int BN_get_params(int which)
{
if (which == 0)
return bn_limit_bits;
else if (which == 1)
return bn_limit_bits_high;
else if (which == 2)
return bn_limit_bits_low;
else if (which == 3)
return bn_limit_bits_mont;
else
return 0;
}
#endif
const BIGNUM *BN_value_one(void)
{
static const BN_ULONG data_one = 1L;
static const BIGNUM const_one =
{ (BN_ULONG *)&data_one, 1, 1, 0, BN_FLG_STATIC_DATA };
return &const_one;
}
/*
* Old Visual Studio ARM compiler miscompiles BN_num_bits_word()
* https://mta.openssl.org/pipermail/openssl-users/2018-August/008465.html
*/
#if defined(_MSC_VER) && defined(_ARM_) && defined(_WIN32_WCE) \
&& _MSC_VER>=1400 && _MSC_VER<1501
# define MS_BROKEN_BN_num_bits_word
# pragma optimize("", off)
#endif
int BN_num_bits_word(BN_ULONG l)
{
BN_ULONG x, mask;
int bits = (l != 0);
#if BN_BITS2 > 32
x = l >> 32;
mask = (0 - x) & BN_MASK2;
mask = (0 - (mask >> (BN_BITS2 - 1)));
bits += 32 & mask;
l ^= (x ^ l) & mask;
#endif
x = l >> 16;
mask = (0 - x) & BN_MASK2;
mask = (0 - (mask >> (BN_BITS2 - 1)));
bits += 16 & mask;
l ^= (x ^ l) & mask;
x = l >> 8;
mask = (0 - x) & BN_MASK2;
mask = (0 - (mask >> (BN_BITS2 - 1)));
bits += 8 & mask;
l ^= (x ^ l) & mask;
x = l >> 4;
mask = (0 - x) & BN_MASK2;
mask = (0 - (mask >> (BN_BITS2 - 1)));
bits += 4 & mask;
l ^= (x ^ l) & mask;
x = l >> 2;
mask = (0 - x) & BN_MASK2;
mask = (0 - (mask >> (BN_BITS2 - 1)));
bits += 2 & mask;
l ^= (x ^ l) & mask;
x = l >> 1;
mask = (0 - x) & BN_MASK2;
mask = (0 - (mask >> (BN_BITS2 - 1)));
bits += 1 & mask;
return bits;
}
#ifdef MS_BROKEN_BN_num_bits_word
# pragma optimize("", on)
#endif
/*
* This function still leaks `a->dmax`: it's caller's responsibility to
* expand the input `a` in advance to a public length.
*/
static ossl_inline
int bn_num_bits_consttime(const BIGNUM *a)
{
int j, ret;
unsigned int mask, past_i;
int i = a->top - 1;
bn_check_top(a);
for (j = 0, past_i = 0, ret = 0; j < a->dmax; j++) {
mask = constant_time_eq_int(i, j); /* 0xff..ff if i==j, 0x0 otherwise */
ret += BN_BITS2 & (~mask & ~past_i);
ret += BN_num_bits_word(a->d[j]) & mask;
past_i |= mask; /* past_i will become 0xff..ff after i==j */
}
/*
* if BN_is_zero(a) => i is -1 and ret contains garbage, so we mask the
* final result.
*/
mask = ~(constant_time_eq_int(i, ((int)-1)));
return ret & mask;
}
int BN_num_bits(const BIGNUM *a)
{
int i = a->top - 1;
bn_check_top(a);
if (a->flags & BN_FLG_CONSTTIME) {
/*
* We assume that BIGNUMs flagged as CONSTTIME have also been expanded
* so that a->dmax is not leaking secret information.
*
* In other words, it's the caller's responsibility to ensure `a` has
* been preallocated in advance to a public length if we hit this
* branch.
*
*/
return bn_num_bits_consttime(a);
}
if (BN_is_zero(a))
return 0;
return ((i * BN_BITS2) + BN_num_bits_word(a->d[i]));
}
static void bn_free_d(BIGNUM *a, int clear)
{
if (BN_get_flags(a, BN_FLG_SECURE))
OPENSSL_secure_clear_free(a->d, a->dmax * sizeof(a->d[0]));
else if (clear != 0)
OPENSSL_clear_free(a->d, a->dmax * sizeof(a->d[0]));
else
OPENSSL_free(a->d);
}
void BN_clear_free(BIGNUM *a)
{
if (a == NULL)
return;
if (a->d != NULL && !BN_get_flags(a, BN_FLG_STATIC_DATA))
bn_free_d(a, 1);
if (BN_get_flags(a, BN_FLG_MALLOCED)) {
OPENSSL_cleanse(a, sizeof(*a));
OPENSSL_free(a);
}
}
void BN_free(BIGNUM *a)
{
if (a == NULL)
return;
if (!BN_get_flags(a, BN_FLG_STATIC_DATA))
bn_free_d(a, 0);
if (a->flags & BN_FLG_MALLOCED)
OPENSSL_free(a);
}
void bn_init(BIGNUM *a)
{
static BIGNUM nilbn;
*a = nilbn;
bn_check_top(a);
}
BIGNUM *BN_new(void)
{
BIGNUM *ret;
if ((ret = OPENSSL_zalloc(sizeof(*ret))) == NULL) {
ERR_raise(ERR_LIB_BN, ERR_R_MALLOC_FAILURE);
return NULL;
}
ret->flags = BN_FLG_MALLOCED;
bn_check_top(ret);
return ret;
}
BIGNUM *BN_secure_new(void)
{
BIGNUM *ret = BN_new();
if (ret != NULL)
ret->flags |= BN_FLG_SECURE;
return ret;
}
/* This is used by bn_expand2() */
/* The caller MUST check that words > b->dmax before calling this */
static BN_ULONG *bn_expand_internal(const BIGNUM *b, int words)
{
BN_ULONG *a = NULL;
if (words > (INT_MAX / (4 * BN_BITS2))) {
ERR_raise(ERR_LIB_BN, BN_R_BIGNUM_TOO_LONG);
return NULL;
}
if (BN_get_flags(b, BN_FLG_STATIC_DATA)) {
ERR_raise(ERR_LIB_BN, BN_R_EXPAND_ON_STATIC_BIGNUM_DATA);
return NULL;
}
if (BN_get_flags(b, BN_FLG_SECURE))
a = OPENSSL_secure_zalloc(words * sizeof(*a));
else
a = OPENSSL_zalloc(words * sizeof(*a));
if (a == NULL) {
ERR_raise(ERR_LIB_BN, ERR_R_MALLOC_FAILURE);
return NULL;
}
assert(b->top <= words);
if (b->top > 0)
memcpy(a, b->d, sizeof(*a) * b->top);
return a;
}
/*
* This is an internal function that should not be used in applications. It
* ensures that 'b' has enough room for a 'words' word number and initialises
* any unused part of b->d with leading zeros. It is mostly used by the
* various BIGNUM routines. If there is an error, NULL is returned. If not,
* 'b' is returned.
*/
BIGNUM *bn_expand2(BIGNUM *b, int words)
{
if (words > b->dmax) {
BN_ULONG *a = bn_expand_internal(b, words);
if (!a)
return NULL;
if (b->d != NULL)
bn_free_d(b, 1);
b->d = a;
b->dmax = words;
}
return b;
}
BIGNUM *BN_dup(const BIGNUM *a)
{
BIGNUM *t;
if (a == NULL)
return NULL;
bn_check_top(a);
t = BN_get_flags(a, BN_FLG_SECURE) ? BN_secure_new() : BN_new();
if (t == NULL)
return NULL;
if (!BN_copy(t, a)) {
BN_free(t);
return NULL;
}
bn_check_top(t);
return t;
}
BIGNUM *BN_copy(BIGNUM *a, const BIGNUM *b)
{
int bn_words;
bn_check_top(b);
bn_words = BN_get_flags(b, BN_FLG_CONSTTIME) ? b->dmax : b->top;
if (a == b)
return a;
if (bn_wexpand(a, bn_words) == NULL)
return NULL;
if (b->top > 0)
memcpy(a->d, b->d, sizeof(b->d[0]) * bn_words);
a->neg = b->neg;
a->top = b->top;
a->flags |= b->flags & BN_FLG_FIXED_TOP;
bn_check_top(a);
return a;
}
#define FLAGS_DATA(flags) ((flags) & (BN_FLG_STATIC_DATA \
| BN_FLG_CONSTTIME \
| BN_FLG_SECURE \
| BN_FLG_FIXED_TOP))
#define FLAGS_STRUCT(flags) ((flags) & (BN_FLG_MALLOCED))
void BN_swap(BIGNUM *a, BIGNUM *b)
{
int flags_old_a, flags_old_b;
BN_ULONG *tmp_d;
int tmp_top, tmp_dmax, tmp_neg;
bn_check_top(a);
bn_check_top(b);
flags_old_a = a->flags;
flags_old_b = b->flags;
tmp_d = a->d;
tmp_top = a->top;
tmp_dmax = a->dmax;
tmp_neg = a->neg;
a->d = b->d;
a->top = b->top;
a->dmax = b->dmax;
a->neg = b->neg;
b->d = tmp_d;
b->top = tmp_top;
b->dmax = tmp_dmax;
b->neg = tmp_neg;
a->flags = FLAGS_STRUCT(flags_old_a) | FLAGS_DATA(flags_old_b);
b->flags = FLAGS_STRUCT(flags_old_b) | FLAGS_DATA(flags_old_a);
bn_check_top(a);
bn_check_top(b);
}
void BN_clear(BIGNUM *a)
{
if (a == NULL)
return;
bn_check_top(a);
if (a->d != NULL)
OPENSSL_cleanse(a->d, sizeof(*a->d) * a->dmax);
a->neg = 0;
a->top = 0;
a->flags &= ~BN_FLG_FIXED_TOP;
}
BN_ULONG BN_get_word(const BIGNUM *a)
{
if (a->top > 1)
return BN_MASK2;
else if (a->top == 1)
return a->d[0];
/* a->top == 0 */
return 0;
}
int BN_set_word(BIGNUM *a, BN_ULONG w)
{
bn_check_top(a);
if (bn_expand(a, (int)sizeof(BN_ULONG) * 8) == NULL)
return 0;
a->neg = 0;
a->d[0] = w;
a->top = (w ? 1 : 0);
a->flags &= ~BN_FLG_FIXED_TOP;
bn_check_top(a);
return 1;
}
BIGNUM *BN_bin2bn(const unsigned char *s, int len, BIGNUM *ret)
{
unsigned int i, m;
unsigned int n;
BN_ULONG l;
BIGNUM *bn = NULL;
if (ret == NULL)
ret = bn = BN_new();
if (ret == NULL)
return NULL;
bn_check_top(ret);
/* Skip leading zero's. */
for ( ; len > 0 && *s == 0; s++, len--)
continue;
n = len;
if (n == 0) {
ret->top = 0;
return ret;
}
i = ((n - 1) / BN_BYTES) + 1;
m = ((n - 1) % (BN_BYTES));
if (bn_wexpand(ret, (int)i) == NULL) {
BN_free(bn);
return NULL;
}
ret->top = i;
ret->neg = 0;
l = 0;
while (n--) {
l = (l << 8L) | *(s++);
if (m-- == 0) {
ret->d[--i] = l;
l = 0;
m = BN_BYTES - 1;
}
}
/*
* need to call this due to clear byte at top if avoiding having the top
* bit set (-ve number)
*/
bn_correct_top(ret);
return ret;
}
typedef enum {big, little} endianess_t;
/* ignore negative */
static
int bn2binpad(const BIGNUM *a, unsigned char *to, int tolen, endianess_t endianess)
{
int n;
size_t i, lasti, j, atop, mask;
BN_ULONG l;
/*
* In case |a| is fixed-top, BN_num_bytes can return bogus length,
* but it's assumed that fixed-top inputs ought to be "nominated"
* even for padded output, so it works out...
*/
n = BN_num_bytes(a);
if (tolen == -1) {
tolen = n;
} else if (tolen < n) { /* uncommon/unlike case */
BIGNUM temp = *a;
bn_correct_top(&temp);
n = BN_num_bytes(&temp);
if (tolen < n)
return -1;
}
/* Swipe through whole available data and don't give away padded zero. */
atop = a->dmax * BN_BYTES;
if (atop == 0) {
if (tolen != 0)
memset(to, '\0', tolen);
return tolen;
}
lasti = atop - 1;
atop = a->top * BN_BYTES;
if (endianess == big)
to += tolen; /* start from the end of the buffer */
for (i = 0, j = 0; j < (size_t)tolen; j++) {
unsigned char val;
l = a->d[i / BN_BYTES];
mask = 0 - ((j - atop) >> (8 * sizeof(i) - 1));
val = (unsigned char)(l >> (8 * (i % BN_BYTES)) & mask);
if (endianess == big)
*--to = val;
else
*to++ = val;
i += (i - lasti) >> (8 * sizeof(i) - 1); /* stay on last limb */
}
return tolen;
}
int BN_bn2binpad(const BIGNUM *a, unsigned char *to, int tolen)
{
if (tolen < 0)
return -1;
return bn2binpad(a, to, tolen, big);
}
int BN_bn2bin(const BIGNUM *a, unsigned char *to)
{
return bn2binpad(a, to, -1, big);
}
BIGNUM *BN_lebin2bn(const unsigned char *s, int len, BIGNUM *ret)
{
unsigned int i, m;
unsigned int n;
BN_ULONG l;
BIGNUM *bn = NULL;
if (ret == NULL)
ret = bn = BN_new();
if (ret == NULL)
return NULL;
bn_check_top(ret);
s += len;
/* Skip trailing zeroes. */
for ( ; len > 0 && s[-1] == 0; s--, len--)
continue;
n = len;
if (n == 0) {
ret->top = 0;
return ret;
}
i = ((n - 1) / BN_BYTES) + 1;
m = ((n - 1) % (BN_BYTES));
if (bn_wexpand(ret, (int)i) == NULL) {
BN_free(bn);
return NULL;
}
ret->top = i;
ret->neg = 0;
l = 0;
while (n--) {
s--;
l = (l << 8L) | *s;
if (m-- == 0) {
ret->d[--i] = l;
l = 0;
m = BN_BYTES - 1;
}
}
/*
* need to call this due to clear byte at top if avoiding having the top
* bit set (-ve number)
*/
bn_correct_top(ret);
return ret;
}
int BN_bn2lebinpad(const BIGNUM *a, unsigned char *to, int tolen)
{
if (tolen < 0)
return -1;
return bn2binpad(a, to, tolen, little);
}
BIGNUM *BN_native2bn(const unsigned char *s, int len, BIGNUM *ret)
{
DECLARE_IS_ENDIAN;
if (IS_LITTLE_ENDIAN)
return BN_lebin2bn(s, len, ret);
return BN_bin2bn(s, len, ret);
}
int BN_bn2nativepad(const BIGNUM *a, unsigned char *to, int tolen)
{
DECLARE_IS_ENDIAN;
if (IS_LITTLE_ENDIAN)
return BN_bn2lebinpad(a, to, tolen);
return BN_bn2binpad(a, to, tolen);
}
int BN_ucmp(const BIGNUM *a, const BIGNUM *b)
{
int i;
BN_ULONG t1, t2, *ap, *bp;
+ ap = a->d;
+ bp = b->d;
+
+ if (BN_get_flags(a, BN_FLG_CONSTTIME)
+ && a->top == b->top) {
+ int res = 0;
+
+ for (i = 0; i < b->top; i++) {
+ res = constant_time_select_int(constant_time_lt_bn(ap[i], bp[i]),
+ -1, res);
+ res = constant_time_select_int(constant_time_lt_bn(bp[i], ap[i]),
+ 1, res);
+ }
+ return res;
+ }
+
bn_check_top(a);
bn_check_top(b);
i = a->top - b->top;
if (i != 0)
return i;
- ap = a->d;
- bp = b->d;
+
for (i = a->top - 1; i >= 0; i--) {
t1 = ap[i];
t2 = bp[i];
if (t1 != t2)
return ((t1 > t2) ? 1 : -1);
}
return 0;
}
int BN_cmp(const BIGNUM *a, const BIGNUM *b)
{
int i;
int gt, lt;
BN_ULONG t1, t2;
if ((a == NULL) || (b == NULL)) {
if (a != NULL)
return -1;
else if (b != NULL)
return 1;
else
return 0;
}
bn_check_top(a);
bn_check_top(b);
if (a->neg != b->neg) {
if (a->neg)
return -1;
else
return 1;
}
if (a->neg == 0) {
gt = 1;
lt = -1;
} else {
gt = -1;
lt = 1;
}
if (a->top > b->top)
return gt;
if (a->top < b->top)
return lt;
for (i = a->top - 1; i >= 0; i--) {
t1 = a->d[i];
t2 = b->d[i];
if (t1 > t2)
return gt;
if (t1 < t2)
return lt;
}
return 0;
}
int BN_set_bit(BIGNUM *a, int n)
{
int i, j, k;
if (n < 0)
return 0;
i = n / BN_BITS2;
j = n % BN_BITS2;
if (a->top <= i) {
if (bn_wexpand(a, i + 1) == NULL)
return 0;
for (k = a->top; k < i + 1; k++)
a->d[k] = 0;
a->top = i + 1;
a->flags &= ~BN_FLG_FIXED_TOP;
}
a->d[i] |= (((BN_ULONG)1) << j);
bn_check_top(a);
return 1;
}
int BN_clear_bit(BIGNUM *a, int n)
{
int i, j;
bn_check_top(a);
if (n < 0)
return 0;
i = n / BN_BITS2;
j = n % BN_BITS2;
if (a->top <= i)
return 0;
a->d[i] &= (~(((BN_ULONG)1) << j));
bn_correct_top(a);
return 1;
}
int BN_is_bit_set(const BIGNUM *a, int n)
{
int i, j;
bn_check_top(a);
if (n < 0)
return 0;
i = n / BN_BITS2;
j = n % BN_BITS2;
if (a->top <= i)
return 0;
return (int)(((a->d[i]) >> j) & ((BN_ULONG)1));
}
-int BN_mask_bits(BIGNUM *a, int n)
+int ossl_bn_mask_bits_fixed_top(BIGNUM *a, int n)
{
int b, w;
- bn_check_top(a);
if (n < 0)
return 0;
w = n / BN_BITS2;
b = n % BN_BITS2;
if (w >= a->top)
return 0;
if (b == 0)
a->top = w;
else {
a->top = w + 1;
a->d[w] &= ~(BN_MASK2 << b);
}
- bn_correct_top(a);
+ a->flags |= BN_FLG_FIXED_TOP;
return 1;
}
+int BN_mask_bits(BIGNUM *a, int n)
+{
+ int ret;
+
+ bn_check_top(a);
+ ret = ossl_bn_mask_bits_fixed_top(a, n);
+ if (ret)
+ bn_correct_top(a);
+ return ret;
+}
+
void BN_set_negative(BIGNUM *a, int b)
{
if (b && !BN_is_zero(a))
a->neg = 1;
else
a->neg = 0;
}
int bn_cmp_words(const BN_ULONG *a, const BN_ULONG *b, int n)
{
int i;
BN_ULONG aa, bb;
if (n == 0)
return 0;
aa = a[n - 1];
bb = b[n - 1];
if (aa != bb)
return ((aa > bb) ? 1 : -1);
for (i = n - 2; i >= 0; i--) {
aa = a[i];
bb = b[i];
if (aa != bb)
return ((aa > bb) ? 1 : -1);
}
return 0;
}
/*
* Here follows a specialised variants of bn_cmp_words(). It has the
* capability of performing the operation on arrays of different sizes. The
* sizes of those arrays is expressed through cl, which is the common length
* ( basically, min(len(a),len(b)) ), and dl, which is the delta between the
* two lengths, calculated as len(a)-len(b). All lengths are the number of
* BN_ULONGs...
*/
int bn_cmp_part_words(const BN_ULONG *a, const BN_ULONG *b, int cl, int dl)
{
int n, i;
n = cl - 1;
if (dl < 0) {
for (i = dl; i < 0; i++) {
if (b[n - i] != 0)
return -1; /* a < b */
}
}
if (dl > 0) {
for (i = dl; i > 0; i--) {
if (a[n + i] != 0)
return 1; /* a > b */
}
}
return bn_cmp_words(a, b, cl);
}
/*-
* Constant-time conditional swap of a and b.
* a and b are swapped if condition is not 0.
* nwords is the number of words to swap.
* Assumes that at least nwords are allocated in both a and b.
* Assumes that no more than nwords are used by either a or b.
*/
void BN_consttime_swap(BN_ULONG condition, BIGNUM *a, BIGNUM *b, int nwords)
{
BN_ULONG t;
int i;
if (a == b)
return;
bn_wcheck_size(a, nwords);
bn_wcheck_size(b, nwords);
condition = ((~condition & ((condition - 1))) >> (BN_BITS2 - 1)) - 1;
t = (a->top ^ b->top) & condition;
a->top ^= t;
b->top ^= t;
t = (a->neg ^ b->neg) & condition;
a->neg ^= t;
b->neg ^= t;
/*-
* BN_FLG_STATIC_DATA: indicates that data may not be written to. Intention
* is actually to treat it as it's read-only data, and some (if not most)
* of it does reside in read-only segment. In other words observation of
* BN_FLG_STATIC_DATA in BN_consttime_swap should be treated as fatal
* condition. It would either cause SEGV or effectively cause data
* corruption.
*
* BN_FLG_MALLOCED: refers to BN structure itself, and hence must be
* preserved.
*
* BN_FLG_SECURE: must be preserved, because it determines how x->d was
* allocated and hence how to free it.
*
* BN_FLG_CONSTTIME: sufficient to mask and swap
*
* BN_FLG_FIXED_TOP: indicates that we haven't called bn_correct_top() on
* the data, so the d array may be padded with additional 0 values (i.e.
* top could be greater than the minimal value that it could be). We should
* be swapping it
*/
#define BN_CONSTTIME_SWAP_FLAGS (BN_FLG_CONSTTIME | BN_FLG_FIXED_TOP)
t = ((a->flags ^ b->flags) & BN_CONSTTIME_SWAP_FLAGS) & condition;
a->flags ^= t;
b->flags ^= t;
/* conditionally swap the data */
for (i = 0; i < nwords; i++) {
t = (a->d[i] ^ b->d[i]) & condition;
a->d[i] ^= t;
b->d[i] ^= t;
}
}
#undef BN_CONSTTIME_SWAP_FLAGS
/* Bits of security, see SP800-57 */
int BN_security_bits(int L, int N)
{
int secbits, bits;
if (L >= 15360)
secbits = 256;
else if (L >= 7680)
secbits = 192;
else if (L >= 3072)
secbits = 128;
else if (L >= 2048)
secbits = 112;
else if (L >= 1024)
secbits = 80;
else
return 0;
if (N == -1)
return secbits;
bits = N / 2;
if (bits < 80)
return 0;
return bits >= secbits ? secbits : bits;
}
void BN_zero_ex(BIGNUM *a)
{
a->neg = 0;
a->top = 0;
a->flags &= ~BN_FLG_FIXED_TOP;
}
int BN_abs_is_word(const BIGNUM *a, const BN_ULONG w)
{
return ((a->top == 1) && (a->d[0] == w)) || ((w == 0) && (a->top == 0));
}
int BN_is_zero(const BIGNUM *a)
{
return a->top == 0;
}
int BN_is_one(const BIGNUM *a)
{
return BN_abs_is_word(a, 1) && !a->neg;
}
int BN_is_word(const BIGNUM *a, const BN_ULONG w)
{
return BN_abs_is_word(a, w) && (!w || !a->neg);
}
+int ossl_bn_is_word_fixed_top(const BIGNUM *a, BN_ULONG w)
+{
+ int res, i;
+ const BN_ULONG *ap = a->d;
+
+ if (a->neg || a->top == 0)
+ return 0;
+
+ res = constant_time_select_int(constant_time_eq_bn(ap[0], w), 1, 0);
+
+ for (i = 1; i < a->top; i++)
+ res = constant_time_select_int(constant_time_is_zero_bn(ap[i]),
+ res, 0);
+ return res;
+}
+
int BN_is_odd(const BIGNUM *a)
{
return (a->top > 0) && (a->d[0] & 1);
}
int BN_is_negative(const BIGNUM *a)
{
return (a->neg != 0);
}
int BN_to_montgomery(BIGNUM *r, const BIGNUM *a, BN_MONT_CTX *mont,
BN_CTX *ctx)
{
return BN_mod_mul_montgomery(r, a, &(mont->RR), mont, ctx);
}
void BN_with_flags(BIGNUM *dest, const BIGNUM *b, int flags)
{
dest->d = b->d;
dest->top = b->top;
dest->dmax = b->dmax;
dest->neg = b->neg;
dest->flags = ((dest->flags & BN_FLG_MALLOCED)
| (b->flags & ~BN_FLG_MALLOCED)
| BN_FLG_STATIC_DATA | flags);
}
BN_GENCB *BN_GENCB_new(void)
{
BN_GENCB *ret;
if ((ret = OPENSSL_malloc(sizeof(*ret))) == NULL) {
ERR_raise(ERR_LIB_BN, ERR_R_MALLOC_FAILURE);
return NULL;
}
return ret;
}
void BN_GENCB_free(BN_GENCB *cb)
{
if (cb == NULL)
return;
OPENSSL_free(cb);
}
void BN_set_flags(BIGNUM *b, int n)
{
b->flags |= n;
}
int BN_get_flags(const BIGNUM *b, int n)
{
return b->flags & n;
}
/* Populate a BN_GENCB structure with an "old"-style callback */
void BN_GENCB_set_old(BN_GENCB *gencb, void (*callback) (int, int, void *),
void *cb_arg)
{
BN_GENCB *tmp_gencb = gencb;
tmp_gencb->ver = 1;
tmp_gencb->arg = cb_arg;
tmp_gencb->cb.cb_1 = callback;
}
/* Populate a BN_GENCB structure with a "new"-style callback */
void BN_GENCB_set(BN_GENCB *gencb, int (*callback) (int, int, BN_GENCB *),
void *cb_arg)
{
BN_GENCB *tmp_gencb = gencb;
tmp_gencb->ver = 2;
tmp_gencb->arg = cb_arg;
tmp_gencb->cb.cb_2 = callback;
}
void *BN_GENCB_get_arg(BN_GENCB *cb)
{
return cb->arg;
}
BIGNUM *bn_wexpand(BIGNUM *a, int words)
{
return (words <= a->dmax) ? a : bn_expand2(a, words);
}
void bn_correct_top_consttime(BIGNUM *a)
{
int j, atop;
BN_ULONG limb;
unsigned int mask;
for (j = 0, atop = 0; j < a->dmax; j++) {
limb = a->d[j];
limb |= 0 - limb;
limb >>= BN_BITS2 - 1;
limb = 0 - limb;
mask = (unsigned int)limb;
mask &= constant_time_msb(j - a->top);
atop = constant_time_select_int(mask, j + 1, atop);
}
mask = constant_time_eq_int(atop, 0);
a->top = atop;
a->neg = constant_time_select_int(mask, 0, a->neg);
a->flags &= ~BN_FLG_FIXED_TOP;
}
void bn_correct_top(BIGNUM *a)
{
BN_ULONG *ftl;
int tmp_top = a->top;
if (tmp_top > 0) {
for (ftl = &(a->d[tmp_top]); tmp_top > 0; tmp_top--) {
ftl--;
if (*ftl != 0)
break;
}
a->top = tmp_top;
}
if (a->top == 0)
a->neg = 0;
a->flags &= ~BN_FLG_FIXED_TOP;
bn_pollute(a);
}
diff --git a/crypto/openssl/crypto/bn/bn_rand.c b/crypto/openssl/crypto/bn/bn_rand.c
index 2ca426ff76ed..ba0970b1f87d 100644
--- a/crypto/openssl/crypto/bn/bn_rand.c
+++ b/crypto/openssl/crypto/bn/bn_rand.c
@@ -1,328 +1,414 @@
/*
- * Copyright 1995-2023 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 1995-2024 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 <stdio.h>
#include <time.h>
#include "internal/cryptlib.h"
#include "crypto/rand.h"
#include "bn_local.h"
#include <openssl/rand.h>
#include <openssl/sha.h>
#include <openssl/evp.h>
typedef enum bnrand_flag_e {
NORMAL, TESTING, PRIVATE
} BNRAND_FLAG;
static int bnrand(BNRAND_FLAG flag, BIGNUM *rnd, int bits, int top, int bottom,
unsigned int strength, BN_CTX *ctx)
{
unsigned char *buf = NULL;
int b, ret = 0, bit, bytes, mask;
OSSL_LIB_CTX *libctx = ossl_bn_get_libctx(ctx);
if (bits == 0) {
if (top != BN_RAND_TOP_ANY || bottom != BN_RAND_BOTTOM_ANY)
goto toosmall;
BN_zero(rnd);
return 1;
}
if (bits < 0 || (bits == 1 && top > 0))
goto toosmall;
bytes = (bits + 7) / 8;
bit = (bits - 1) % 8;
mask = 0xff << (bit + 1);
buf = OPENSSL_malloc(bytes);
if (buf == NULL) {
ERR_raise(ERR_LIB_BN, ERR_R_MALLOC_FAILURE);
goto err;
}
/* make a random number and set the top and bottom bits */
b = flag == NORMAL ? RAND_bytes_ex(libctx, buf, bytes, strength)
: RAND_priv_bytes_ex(libctx, buf, bytes, strength);
if (b <= 0)
goto err;
if (flag == TESTING) {
/*
* generate patterns that are more likely to trigger BN library bugs
*/
int i;
unsigned char c;
for (i = 0; i < bytes; i++) {
if (RAND_bytes_ex(libctx, &c, 1, strength) <= 0)
goto err;
if (c >= 128 && i > 0)
buf[i] = buf[i - 1];
else if (c < 42)
buf[i] = 0;
else if (c < 84)
buf[i] = 255;
}
}
if (top >= 0) {
if (top) {
if (bit == 0) {
buf[0] = 1;
buf[1] |= 0x80;
} else {
buf[0] |= (3 << (bit - 1));
}
} else {
buf[0] |= (1 << bit);
}
}
buf[0] &= ~mask;
if (bottom) /* set bottom bit if requested */
buf[bytes - 1] |= 1;
if (!BN_bin2bn(buf, bytes, rnd))
goto err;
ret = 1;
err:
OPENSSL_clear_free(buf, bytes);
bn_check_top(rnd);
return ret;
toosmall:
ERR_raise(ERR_LIB_BN, BN_R_BITS_TOO_SMALL);
return 0;
}
int BN_rand_ex(BIGNUM *rnd, int bits, int top, int bottom,
unsigned int strength, BN_CTX *ctx)
{
return bnrand(NORMAL, rnd, bits, top, bottom, strength, ctx);
}
#ifndef FIPS_MODULE
int BN_rand(BIGNUM *rnd, int bits, int top, int bottom)
{
return bnrand(NORMAL, rnd, bits, top, bottom, 0, NULL);
}
int BN_bntest_rand(BIGNUM *rnd, int bits, int top, int bottom)
{
return bnrand(TESTING, rnd, bits, top, bottom, 0, NULL);
}
#endif
int BN_priv_rand_ex(BIGNUM *rnd, int bits, int top, int bottom,
unsigned int strength, BN_CTX *ctx)
{
return bnrand(PRIVATE, rnd, bits, top, bottom, strength, ctx);
}
#ifndef FIPS_MODULE
int BN_priv_rand(BIGNUM *rnd, int bits, int top, int bottom)
{
return bnrand(PRIVATE, rnd, bits, top, bottom, 0, NULL);
}
#endif
/* random number r: 0 <= r < range */
static int bnrand_range(BNRAND_FLAG flag, BIGNUM *r, const BIGNUM *range,
unsigned int strength, BN_CTX *ctx)
{
int n;
int count = 100;
if (r == NULL) {
ERR_raise(ERR_LIB_BN, ERR_R_PASSED_NULL_PARAMETER);
return 0;
}
if (range->neg || BN_is_zero(range)) {
ERR_raise(ERR_LIB_BN, BN_R_INVALID_RANGE);
return 0;
}
n = BN_num_bits(range); /* n > 0 */
/* BN_is_bit_set(range, n - 1) always holds */
if (n == 1)
BN_zero(r);
else if (!BN_is_bit_set(range, n - 2) && !BN_is_bit_set(range, n - 3)) {
/*
* range = 100..._2, so 3*range (= 11..._2) is exactly one bit longer
* than range
*/
do {
if (!bnrand(flag, r, n + 1, BN_RAND_TOP_ANY, BN_RAND_BOTTOM_ANY,
strength, ctx))
return 0;
/*
* If r < 3*range, use r := r MOD range (which is either r, r -
* range, or r - 2*range). Otherwise, iterate once more. Since
* 3*range = 11..._2, each iteration succeeds with probability >=
* .75.
*/
if (BN_cmp(r, range) >= 0) {
if (!BN_sub(r, r, range))
return 0;
if (BN_cmp(r, range) >= 0)
if (!BN_sub(r, r, range))
return 0;
}
if (!--count) {
ERR_raise(ERR_LIB_BN, BN_R_TOO_MANY_ITERATIONS);
return 0;
}
}
while (BN_cmp(r, range) >= 0);
} else {
do {
/* range = 11..._2 or range = 101..._2 */
- if (!bnrand(flag, r, n, BN_RAND_TOP_ANY, BN_RAND_BOTTOM_ANY, 0,
- ctx))
+ if (!bnrand(flag, r, n, BN_RAND_TOP_ANY, BN_RAND_BOTTOM_ANY,
+ strength, ctx))
return 0;
if (!--count) {
ERR_raise(ERR_LIB_BN, BN_R_TOO_MANY_ITERATIONS);
return 0;
}
}
while (BN_cmp(r, range) >= 0);
}
bn_check_top(r);
return 1;
}
int BN_rand_range_ex(BIGNUM *r, const BIGNUM *range, unsigned int strength,
BN_CTX *ctx)
{
return bnrand_range(NORMAL, r, range, strength, ctx);
}
#ifndef FIPS_MODULE
int BN_rand_range(BIGNUM *r, const BIGNUM *range)
{
return bnrand_range(NORMAL, r, range, 0, NULL);
}
#endif
int BN_priv_rand_range_ex(BIGNUM *r, const BIGNUM *range, unsigned int strength,
BN_CTX *ctx)
{
return bnrand_range(PRIVATE, r, range, strength, ctx);
}
#ifndef FIPS_MODULE
int BN_priv_rand_range(BIGNUM *r, const BIGNUM *range)
{
return bnrand_range(PRIVATE, r, range, 0, NULL);
}
# ifndef OPENSSL_NO_DEPRECATED_3_0
int BN_pseudo_rand(BIGNUM *rnd, int bits, int top, int bottom)
{
return BN_rand(rnd, bits, top, bottom);
}
int BN_pseudo_rand_range(BIGNUM *r, const BIGNUM *range)
{
return BN_rand_range(r, range);
}
# endif
#endif
+int ossl_bn_priv_rand_range_fixed_top(BIGNUM *r, const BIGNUM *range,
+ unsigned int strength, BN_CTX *ctx)
+{
+ int n;
+ int count = 100;
+
+ if (r == NULL) {
+ ERR_raise(ERR_LIB_BN, ERR_R_PASSED_NULL_PARAMETER);
+ return 0;
+ }
+
+ if (range->neg || BN_is_zero(range)) {
+ ERR_raise(ERR_LIB_BN, BN_R_INVALID_RANGE);
+ return 0;
+ }
+
+ n = BN_num_bits(range); /* n > 0 */
+
+ /* BN_is_bit_set(range, n - 1) always holds */
+
+ if (n == 1) {
+ BN_zero(r);
+ } else {
+ BN_set_flags(r, BN_FLG_CONSTTIME);
+ do {
+ if (!bnrand(PRIVATE, r, n + 1, BN_RAND_TOP_ONE, BN_RAND_BOTTOM_ANY,
+ strength, ctx))
+ return 0;
+
+ if (!--count) {
+ ERR_raise(ERR_LIB_BN, BN_R_TOO_MANY_ITERATIONS);
+ return 0;
+ }
+ ossl_bn_mask_bits_fixed_top(r, n);
+ }
+ while (BN_ucmp(r, range) >= 0);
+#ifdef BN_DEBUG
+ /* With BN_DEBUG on a fixed top number cannot be returned */
+ bn_correct_top(r);
+#endif
+ }
+
+ return 1;
+}
+
/*
- * BN_generate_dsa_nonce generates a random number 0 <= out < range. Unlike
- * BN_rand_range, it also includes the contents of |priv| and |message| in
- * the generation so that an RNG failure isn't fatal as long as |priv|
+ * ossl_bn_gen_dsa_nonce_fixed_top generates a random number 0 <= out < range.
+ * Unlike BN_rand_range, it also includes the contents of |priv| and |message|
+ * in the generation so that an RNG failure isn't fatal as long as |priv|
* remains secret. This is intended for use in DSA and ECDSA where an RNG
* weakness leads directly to private key exposure unless this function is
* used.
*/
-int BN_generate_dsa_nonce(BIGNUM *out, const BIGNUM *range,
- const BIGNUM *priv, const unsigned char *message,
- size_t message_len, BN_CTX *ctx)
+int ossl_bn_gen_dsa_nonce_fixed_top(BIGNUM *out, const BIGNUM *range,
+ const BIGNUM *priv,
+ const unsigned char *message,
+ size_t message_len, BN_CTX *ctx)
{
EVP_MD_CTX *mdctx = EVP_MD_CTX_new();
/*
* We use 512 bits of random data per iteration to ensure that we have at
* least |range| bits of randomness.
*/
unsigned char random_bytes[64];
unsigned char digest[SHA512_DIGEST_LENGTH];
unsigned done, todo;
- /* We generate |range|+8 bytes of random output. */
- const unsigned num_k_bytes = BN_num_bytes(range) + 8;
+ /* We generate |range|+1 bytes of random output. */
+ const unsigned num_k_bytes = BN_num_bytes(range) + 1;
unsigned char private_bytes[96];
unsigned char *k_bytes = NULL;
+ const int max_n = 64; /* Pr(failure to generate) < 2^max_n */
+ int n;
int ret = 0;
EVP_MD *md = NULL;
OSSL_LIB_CTX *libctx = ossl_bn_get_libctx(ctx);
if (mdctx == NULL)
- goto err;
+ goto end;
k_bytes = OPENSSL_malloc(num_k_bytes);
if (k_bytes == NULL)
- goto err;
+ goto end;
+ /* Ensure top byte is set to avoid non-constant time in bin2bn */
+ k_bytes[0] = 0xff;
/* We copy |priv| into a local buffer to avoid exposing its length. */
if (BN_bn2binpad(priv, private_bytes, sizeof(private_bytes)) < 0) {
/*
* No reasonable DSA or ECDSA key should have a private key this
* large and we don't handle this case in order to avoid leaking the
* length of the private key.
*/
ERR_raise(ERR_LIB_BN, BN_R_PRIVATE_KEY_TOO_LARGE);
- goto err;
+ goto end;
}
md = EVP_MD_fetch(libctx, "SHA512", NULL);
if (md == NULL) {
ERR_raise(ERR_LIB_BN, BN_R_NO_SUITABLE_DIGEST);
- goto err;
- }
- for (done = 0; done < num_k_bytes;) {
- if (RAND_priv_bytes_ex(libctx, random_bytes, sizeof(random_bytes), 0) <= 0)
- goto err;
-
- if (!EVP_DigestInit_ex(mdctx, md, NULL)
- || !EVP_DigestUpdate(mdctx, &done, sizeof(done))
- || !EVP_DigestUpdate(mdctx, private_bytes,
- sizeof(private_bytes))
- || !EVP_DigestUpdate(mdctx, message, message_len)
- || !EVP_DigestUpdate(mdctx, random_bytes, sizeof(random_bytes))
- || !EVP_DigestFinal_ex(mdctx, digest, NULL))
- goto err;
-
- todo = num_k_bytes - done;
- if (todo > SHA512_DIGEST_LENGTH)
- todo = SHA512_DIGEST_LENGTH;
- memcpy(k_bytes + done, digest, todo);
- done += todo;
+ goto end;
}
+ for (n = 0; n < max_n; n++) {
+ unsigned char i = 0;
+
+ for (done = 1; done < num_k_bytes;) {
+ if (RAND_priv_bytes_ex(libctx, random_bytes, sizeof(random_bytes),
+ 0) <= 0)
+ goto end;
+
+ if (!EVP_DigestInit_ex(mdctx, md, NULL)
+ || !EVP_DigestUpdate(mdctx, &i, sizeof(i))
+ || !EVP_DigestUpdate(mdctx, private_bytes,
+ sizeof(private_bytes))
+ || !EVP_DigestUpdate(mdctx, message, message_len)
+ || !EVP_DigestUpdate(mdctx, random_bytes,
+ sizeof(random_bytes))
+ || !EVP_DigestFinal_ex(mdctx, digest, NULL))
+ goto end;
+
+ todo = num_k_bytes - done;
+ if (todo > SHA512_DIGEST_LENGTH)
+ todo = SHA512_DIGEST_LENGTH;
+ memcpy(k_bytes + done, digest, todo);
+ done += todo;
+ ++i;
+ }
- if (!BN_bin2bn(k_bytes, num_k_bytes, out))
- goto err;
- if (BN_mod(out, out, range, ctx) != 1)
- goto err;
- ret = 1;
+ if (!BN_bin2bn(k_bytes, num_k_bytes, out))
+ goto end;
- err:
+ /* Clear out the top bits and rejection filter into range */
+ BN_set_flags(out, BN_FLG_CONSTTIME);
+ ossl_bn_mask_bits_fixed_top(out, BN_num_bits(range));
+
+ if (BN_ucmp(out, range) < 0) {
+ ret = 1;
+#ifdef BN_DEBUG
+ /* With BN_DEBUG on a fixed top number cannot be returned */
+ bn_correct_top(out);
+#endif
+ goto end;
+ }
+ }
+ /* Failed to generate anything */
+ ERR_raise(ERR_LIB_BN, ERR_R_INTERNAL_ERROR);
+
+ end:
EVP_MD_CTX_free(mdctx);
EVP_MD_free(md);
OPENSSL_clear_free(k_bytes, num_k_bytes);
OPENSSL_cleanse(digest, sizeof(digest));
OPENSSL_cleanse(random_bytes, sizeof(random_bytes));
OPENSSL_cleanse(private_bytes, sizeof(private_bytes));
return ret;
}
+
+int BN_generate_dsa_nonce(BIGNUM *out, const BIGNUM *range,
+ const BIGNUM *priv, const unsigned char *message,
+ size_t message_len, BN_CTX *ctx)
+{
+ int ret;
+
+ ret = ossl_bn_gen_dsa_nonce_fixed_top(out, range, priv, message,
+ message_len, ctx);
+ /*
+ * This call makes the BN_generate_dsa_nonce non-const-time, thus we
+ * do not use it internally. But fixed_top BNs currently cannot be returned
+ * from public API calls.
+ */
+ bn_correct_top(out);
+ return ret;
+}
diff --git a/crypto/openssl/crypto/bn/bn_shift.c b/crypto/openssl/crypto/bn/bn_shift.c
index 8fcb04324e6d..d67331f1f634 100644
--- a/crypto/openssl/crypto/bn/bn_shift.c
+++ b/crypto/openssl/crypto/bn/bn_shift.c
@@ -1,216 +1,216 @@
/*
- * Copyright 1995-2020 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 1995-2024 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 <assert.h>
#include "internal/cryptlib.h"
#include "bn_local.h"
int BN_lshift1(BIGNUM *r, const BIGNUM *a)
{
register BN_ULONG *ap, *rp, t, c;
int i;
bn_check_top(r);
bn_check_top(a);
if (r != a) {
r->neg = a->neg;
if (bn_wexpand(r, a->top + 1) == NULL)
return 0;
r->top = a->top;
} else {
if (bn_wexpand(r, a->top + 1) == NULL)
return 0;
}
ap = a->d;
rp = r->d;
c = 0;
for (i = 0; i < a->top; i++) {
t = *(ap++);
*(rp++) = ((t << 1) | c) & BN_MASK2;
c = t >> (BN_BITS2 - 1);
}
*rp = c;
r->top += c;
bn_check_top(r);
return 1;
}
int BN_rshift1(BIGNUM *r, const BIGNUM *a)
{
BN_ULONG *ap, *rp, t, c;
int i;
bn_check_top(r);
bn_check_top(a);
if (BN_is_zero(a)) {
BN_zero(r);
return 1;
}
i = a->top;
ap = a->d;
if (a != r) {
if (bn_wexpand(r, i) == NULL)
return 0;
r->neg = a->neg;
}
rp = r->d;
r->top = i;
t = ap[--i];
rp[i] = t >> 1;
c = t << (BN_BITS2 - 1);
r->top -= (t == 1);
while (i > 0) {
t = ap[--i];
rp[i] = ((t >> 1) & BN_MASK2) | c;
c = t << (BN_BITS2 - 1);
}
if (!r->top)
r->neg = 0; /* don't allow negative zero */
bn_check_top(r);
return 1;
}
int BN_lshift(BIGNUM *r, const BIGNUM *a, int n)
{
int ret;
if (n < 0) {
ERR_raise(ERR_LIB_BN, BN_R_INVALID_SHIFT);
return 0;
}
ret = bn_lshift_fixed_top(r, a, n);
bn_correct_top(r);
bn_check_top(r);
return ret;
}
/*
* In respect to shift factor the execution time is invariant of
* |n % BN_BITS2|, but not |n / BN_BITS2|. Or in other words pre-condition
* for constant-time-ness is |n < BN_BITS2| or |n / BN_BITS2| being
* non-secret.
*/
int bn_lshift_fixed_top(BIGNUM *r, const BIGNUM *a, int n)
{
int i, nw;
unsigned int lb, rb;
BN_ULONG *t, *f;
BN_ULONG l, m, rmask = 0;
assert(n >= 0);
bn_check_top(r);
bn_check_top(a);
nw = n / BN_BITS2;
if (bn_wexpand(r, a->top + nw + 1) == NULL)
return 0;
if (a->top != 0) {
lb = (unsigned int)n % BN_BITS2;
rb = BN_BITS2 - lb;
rb %= BN_BITS2; /* say no to undefined behaviour */
rmask = (BN_ULONG)0 - rb; /* rmask = 0 - (rb != 0) */
rmask |= rmask >> 8;
f = &(a->d[0]);
t = &(r->d[nw]);
l = f[a->top - 1];
t[a->top] = (l >> rb) & rmask;
for (i = a->top - 1; i > 0; i--) {
m = l << lb;
l = f[i - 1];
t[i] = (m | ((l >> rb) & rmask)) & BN_MASK2;
}
t[0] = (l << lb) & BN_MASK2;
} else {
/* shouldn't happen, but formally required */
r->d[nw] = 0;
}
if (nw != 0)
memset(r->d, 0, sizeof(*t) * nw);
r->neg = a->neg;
r->top = a->top + nw + 1;
r->flags |= BN_FLG_FIXED_TOP;
return 1;
}
int BN_rshift(BIGNUM *r, const BIGNUM *a, int n)
{
int ret = 0;
if (n < 0) {
ERR_raise(ERR_LIB_BN, BN_R_INVALID_SHIFT);
return 0;
}
+ bn_check_top(r);
+ bn_check_top(a);
+
ret = bn_rshift_fixed_top(r, a, n);
bn_correct_top(r);
bn_check_top(r);
return ret;
}
/*
* In respect to shift factor the execution time is invariant of
* |n % BN_BITS2|, but not |n / BN_BITS2|. Or in other words pre-condition
* for constant-time-ness for sufficiently[!] zero-padded inputs is
* |n < BN_BITS2| or |n / BN_BITS2| being non-secret.
*/
int bn_rshift_fixed_top(BIGNUM *r, const BIGNUM *a, int n)
{
int i, top, nw;
unsigned int lb, rb;
BN_ULONG *t, *f;
BN_ULONG l, m, mask;
- bn_check_top(r);
- bn_check_top(a);
-
assert(n >= 0);
nw = n / BN_BITS2;
if (nw >= a->top) {
/* shouldn't happen, but formally required */
BN_zero(r);
return 1;
}
rb = (unsigned int)n % BN_BITS2;
lb = BN_BITS2 - rb;
lb %= BN_BITS2; /* say no to undefined behaviour */
mask = (BN_ULONG)0 - lb; /* mask = 0 - (lb != 0) */
mask |= mask >> 8;
top = a->top - nw;
if (r != a && bn_wexpand(r, top) == NULL)
return 0;
t = &(r->d[0]);
f = &(a->d[nw]);
l = f[0];
for (i = 0; i < top - 1; i++) {
m = f[i + 1];
t[i] = (l >> rb) | ((m << lb) & mask);
l = m;
}
t[i] = l >> rb;
r->neg = a->neg;
r->top = top;
r->flags |= BN_FLG_FIXED_TOP;
return 1;
}
diff --git a/crypto/openssl/crypto/dsa/dsa_check.c b/crypto/openssl/crypto/dsa/dsa_check.c
index fb0e9129a295..801b932d8724 100644
--- a/crypto/openssl/crypto/dsa/dsa_check.c
+++ b/crypto/openssl/crypto/dsa/dsa_check.c
@@ -1,97 +1,133 @@
/*
- * Copyright 1995-2023 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 1995-2024 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 <stdio.h>
#include "internal/cryptlib.h"
#include <openssl/bn.h>
#include "dsa_local.h"
#include "crypto/dsa.h"
+static int dsa_precheck_params(const DSA *dsa, int *ret)
+{
+ if (dsa->params.p == NULL || dsa->params.q == NULL) {
+ ERR_raise(ERR_LIB_DSA, DSA_R_BAD_FFC_PARAMETERS);
+ *ret = FFC_CHECK_INVALID_PQ;
+ return 0;
+ }
+
+ if (BN_num_bits(dsa->params.p) > OPENSSL_DSA_MAX_MODULUS_BITS) {
+ ERR_raise(ERR_LIB_DSA, DSA_R_MODULUS_TOO_LARGE);
+ *ret = FFC_CHECK_INVALID_PQ;
+ return 0;
+ }
+
+ if (BN_num_bits(dsa->params.q) >= BN_num_bits(dsa->params.p)) {
+ ERR_raise(ERR_LIB_DSA, DSA_R_BAD_Q_VALUE);
+ *ret = FFC_CHECK_INVALID_PQ;
+ return 0;
+ }
+
+ return 1;
+}
+
int ossl_dsa_check_params(const DSA *dsa, int checktype, int *ret)
{
+ if (!dsa_precheck_params(dsa, ret))
+ return 0;
+
if (checktype == OSSL_KEYMGMT_VALIDATE_QUICK_CHECK)
return ossl_ffc_params_simple_validate(dsa->libctx, &dsa->params,
FFC_PARAM_TYPE_DSA, ret);
else
/*
* Do full FFC domain params validation according to FIPS-186-4
* - always in FIPS_MODULE
* - only if possible (i.e., seed is set) in default provider
*/
return ossl_ffc_params_full_validate(dsa->libctx, &dsa->params,
FFC_PARAM_TYPE_DSA, ret);
}
/*
* See SP800-56Ar3 Section 5.6.2.3.1 : FFC Full public key validation.
*/
int ossl_dsa_check_pub_key(const DSA *dsa, const BIGNUM *pub_key, int *ret)
{
+ if (!dsa_precheck_params(dsa, ret))
+ return 0;
+
return ossl_ffc_validate_public_key(&dsa->params, pub_key, ret)
&& *ret == 0;
}
/*
* See SP800-56Ar3 Section 5.6.2.3.1 : FFC Partial public key validation.
* To only be used with ephemeral FFC public keys generated using the approved
* safe-prime groups.
*/
int ossl_dsa_check_pub_key_partial(const DSA *dsa, const BIGNUM *pub_key, int *ret)
{
+ if (!dsa_precheck_params(dsa, ret))
+ return 0;
+
return ossl_ffc_validate_public_key_partial(&dsa->params, pub_key, ret)
&& *ret == 0;
}
int ossl_dsa_check_priv_key(const DSA *dsa, const BIGNUM *priv_key, int *ret)
{
*ret = 0;
- return (dsa->params.q != NULL
- && ossl_ffc_validate_private_key(dsa->params.q, priv_key, ret));
+ if (!dsa_precheck_params(dsa, ret))
+ return 0;
+
+ return ossl_ffc_validate_private_key(dsa->params.q, priv_key, ret);
}
/*
* FFC pairwise check from SP800-56A R3.
* Section 5.6.2.1.4 Owner Assurance of Pair-wise Consistency
*/
int ossl_dsa_check_pairwise(const DSA *dsa)
{
int ret = 0;
BN_CTX *ctx = NULL;
BIGNUM *pub_key = NULL;
- if (dsa->params.p == NULL
- || dsa->params.g == NULL
+ if (!dsa_precheck_params(dsa, &ret))
+ return 0;
+
+ if (dsa->params.g == NULL
|| dsa->priv_key == NULL
|| dsa->pub_key == NULL)
return 0;
ctx = BN_CTX_new_ex(dsa->libctx);
if (ctx == NULL)
goto err;
pub_key = BN_new();
if (pub_key == NULL)
goto err;
/* recalculate the public key = (g ^ priv) mod p */
if (!ossl_dsa_generate_public_key(ctx, dsa, dsa->priv_key, pub_key))
goto err;
/* check it matches the existing pubic_key */
ret = BN_cmp(pub_key, dsa->pub_key) == 0;
err:
BN_free(pub_key);
BN_CTX_free(ctx);
return ret;
}
diff --git a/crypto/openssl/crypto/dsa/dsa_ossl.c b/crypto/openssl/crypto/dsa/dsa_ossl.c
index 8fd66a950e37..0c18b78f7633 100644
--- a/crypto/openssl/crypto/dsa/dsa_ossl.c
+++ b/crypto/openssl/crypto/dsa/dsa_ossl.c
@@ -1,480 +1,481 @@
/*
- * Copyright 1995-2023 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 1995-2024 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 <stdio.h>
#include "internal/cryptlib.h"
#include "crypto/bn.h"
#include <openssl/bn.h>
#include <openssl/sha.h>
#include "dsa_local.h"
#include <openssl/asn1.h>
#define MIN_DSA_SIGN_QBITS 128
#define MAX_DSA_SIGN_RETRIES 8
static DSA_SIG *dsa_do_sign(const unsigned char *dgst, int dlen, DSA *dsa);
static int dsa_sign_setup_no_digest(DSA *dsa, BN_CTX *ctx_in, BIGNUM **kinvp,
BIGNUM **rp);
static int dsa_sign_setup(DSA *dsa, BN_CTX *ctx_in, BIGNUM **kinvp,
BIGNUM **rp, const unsigned char *dgst, int dlen);
static int dsa_do_verify(const unsigned char *dgst, int dgst_len,
DSA_SIG *sig, DSA *dsa);
static int dsa_init(DSA *dsa);
static int dsa_finish(DSA *dsa);
static BIGNUM *dsa_mod_inverse_fermat(const BIGNUM *k, const BIGNUM *q,
BN_CTX *ctx);
static DSA_METHOD openssl_dsa_meth = {
"OpenSSL DSA method",
dsa_do_sign,
dsa_sign_setup_no_digest,
dsa_do_verify,
NULL, /* dsa_mod_exp, */
NULL, /* dsa_bn_mod_exp, */
dsa_init,
dsa_finish,
DSA_FLAG_FIPS_METHOD,
NULL,
NULL,
NULL
};
static const DSA_METHOD *default_DSA_method = &openssl_dsa_meth;
#ifndef FIPS_MODULE
void DSA_set_default_method(const DSA_METHOD *meth)
{
default_DSA_method = meth;
}
#endif /* FIPS_MODULE */
const DSA_METHOD *DSA_get_default_method(void)
{
return default_DSA_method;
}
const DSA_METHOD *DSA_OpenSSL(void)
{
return &openssl_dsa_meth;
}
DSA_SIG *ossl_dsa_do_sign_int(const unsigned char *dgst, int dlen, DSA *dsa)
{
BIGNUM *kinv = NULL;
BIGNUM *m, *blind, *blindm, *tmp;
BN_CTX *ctx = NULL;
int reason = ERR_R_BN_LIB;
DSA_SIG *ret = NULL;
int rv = 0;
int retries = 0;
if (dsa->params.p == NULL
|| dsa->params.q == NULL
|| dsa->params.g == NULL) {
reason = DSA_R_MISSING_PARAMETERS;
goto err;
}
if (dsa->priv_key == NULL) {
reason = DSA_R_MISSING_PRIVATE_KEY;
goto err;
}
ret = DSA_SIG_new();
if (ret == NULL)
goto err;
ret->r = BN_new();
ret->s = BN_new();
if (ret->r == NULL || ret->s == NULL)
goto err;
ctx = BN_CTX_new_ex(dsa->libctx);
if (ctx == NULL)
goto err;
m = BN_CTX_get(ctx);
blind = BN_CTX_get(ctx);
blindm = BN_CTX_get(ctx);
tmp = BN_CTX_get(ctx);
if (tmp == NULL)
goto err;
redo:
if (!dsa_sign_setup(dsa, ctx, &kinv, &ret->r, dgst, dlen))
goto err;
if (dlen > BN_num_bytes(dsa->params.q))
/*
* if the digest length is greater than the size of q use the
* BN_num_bits(dsa->q) leftmost bits of the digest, see fips 186-3,
* 4.2
*/
dlen = BN_num_bytes(dsa->params.q);
if (BN_bin2bn(dgst, dlen, m) == NULL)
goto err;
/*
* The normal signature calculation is:
*
* s := k^-1 * (m + r * priv_key) mod q
*
* We will blind this to protect against side channel attacks
*
* s := blind^-1 * k^-1 * (blind * m + blind * r * priv_key) mod q
*/
/*
* Generate a blinding value
* The size of q is tested in dsa_sign_setup() so there should not be an infinite loop here.
*/
do {
if (!BN_priv_rand_ex(blind, BN_num_bits(dsa->params.q) - 1,
BN_RAND_TOP_ANY, BN_RAND_BOTTOM_ANY, 0, ctx))
goto err;
} while (BN_is_zero(blind));
BN_set_flags(blind, BN_FLG_CONSTTIME);
BN_set_flags(blindm, BN_FLG_CONSTTIME);
BN_set_flags(tmp, BN_FLG_CONSTTIME);
/* tmp := blind * priv_key * r mod q */
if (!BN_mod_mul(tmp, blind, dsa->priv_key, dsa->params.q, ctx))
goto err;
if (!BN_mod_mul(tmp, tmp, ret->r, dsa->params.q, ctx))
goto err;
/* blindm := blind * m mod q */
if (!BN_mod_mul(blindm, blind, m, dsa->params.q, ctx))
goto err;
/* s : = (blind * priv_key * r) + (blind * m) mod q */
if (!BN_mod_add_quick(ret->s, tmp, blindm, dsa->params.q))
goto err;
/* s := s * k^-1 mod q */
if (!BN_mod_mul(ret->s, ret->s, kinv, dsa->params.q, ctx))
goto err;
/* s:= s * blind^-1 mod q */
if (BN_mod_inverse(blind, blind, dsa->params.q, ctx) == NULL)
goto err;
if (!BN_mod_mul(ret->s, ret->s, blind, dsa->params.q, ctx))
goto err;
/*
* Redo if r or s is zero as required by FIPS 186-4: Section 4.6
* This is very unlikely.
* Limit the retries so there is no possibility of an infinite
* loop for bad domain parameter values.
*/
if (BN_is_zero(ret->r) || BN_is_zero(ret->s)) {
if (retries++ > MAX_DSA_SIGN_RETRIES) {
reason = DSA_R_TOO_MANY_RETRIES;
goto err;
}
goto redo;
}
rv = 1;
err:
if (rv == 0) {
ERR_raise(ERR_LIB_DSA, reason);
DSA_SIG_free(ret);
ret = NULL;
}
BN_CTX_free(ctx);
BN_clear_free(kinv);
return ret;
}
static DSA_SIG *dsa_do_sign(const unsigned char *dgst, int dlen, DSA *dsa)
{
return ossl_dsa_do_sign_int(dgst, dlen, dsa);
}
static int dsa_sign_setup_no_digest(DSA *dsa, BN_CTX *ctx_in,
BIGNUM **kinvp, BIGNUM **rp)
{
return dsa_sign_setup(dsa, ctx_in, kinvp, rp, NULL, 0);
}
static int dsa_sign_setup(DSA *dsa, BN_CTX *ctx_in,
BIGNUM **kinvp, BIGNUM **rp,
const unsigned char *dgst, int dlen)
{
BN_CTX *ctx = NULL;
BIGNUM *k, *kinv = NULL, *r = *rp;
BIGNUM *l;
int ret = 0;
int q_bits, q_words;
if (!dsa->params.p || !dsa->params.q || !dsa->params.g) {
ERR_raise(ERR_LIB_DSA, DSA_R_MISSING_PARAMETERS);
return 0;
}
/* Reject obviously invalid parameters */
if (BN_is_zero(dsa->params.p)
|| BN_is_zero(dsa->params.q)
|| BN_is_zero(dsa->params.g)
|| BN_is_negative(dsa->params.p)
|| BN_is_negative(dsa->params.q)
|| BN_is_negative(dsa->params.g)) {
ERR_raise(ERR_LIB_DSA, DSA_R_INVALID_PARAMETERS);
return 0;
}
if (dsa->priv_key == NULL) {
ERR_raise(ERR_LIB_DSA, DSA_R_MISSING_PRIVATE_KEY);
return 0;
}
k = BN_new();
l = BN_new();
if (k == NULL || l == NULL)
goto err;
if (ctx_in == NULL) {
/* if you don't pass in ctx_in you get a default libctx */
if ((ctx = BN_CTX_new_ex(NULL)) == NULL)
goto err;
} else
ctx = ctx_in;
/* Preallocate space */
q_bits = BN_num_bits(dsa->params.q);
q_words = bn_get_top(dsa->params.q);
if (q_bits < MIN_DSA_SIGN_QBITS
|| !bn_wexpand(k, q_words + 2)
|| !bn_wexpand(l, q_words + 2))
goto err;
/* Get random k */
do {
if (dgst != NULL) {
/*
* We calculate k from SHA512(private_key + H(message) + random).
* This protects the private key from a weak PRNG.
*/
- if (!BN_generate_dsa_nonce(k, dsa->params.q, dsa->priv_key, dgst,
- dlen, ctx))
+ if (!ossl_bn_gen_dsa_nonce_fixed_top(k, dsa->params.q,
+ dsa->priv_key, dgst,
+ dlen, ctx))
goto err;
- } else if (!BN_priv_rand_range_ex(k, dsa->params.q, 0, ctx))
+ } else if (!ossl_bn_priv_rand_range_fixed_top(k, dsa->params.q, 0, ctx))
goto err;
- } while (BN_is_zero(k));
+ } while (ossl_bn_is_word_fixed_top(k, 0));
BN_set_flags(k, BN_FLG_CONSTTIME);
BN_set_flags(l, BN_FLG_CONSTTIME);
if (dsa->flags & DSA_FLAG_CACHE_MONT_P) {
if (!BN_MONT_CTX_set_locked(&dsa->method_mont_p,
dsa->lock, dsa->params.p, ctx))
goto err;
}
/* Compute r = (g^k mod p) mod q */
/*
* We do not want timing information to leak the length of k, so we
* compute G^k using an equivalent scalar of fixed bit-length.
*
* We unconditionally perform both of these additions to prevent a
* small timing information leakage. We then choose the sum that is
* one bit longer than the modulus.
*
* There are some concerns about the efficacy of doing this. More
* specifically refer to the discussion starting with:
* https://github.com/openssl/openssl/pull/7486#discussion_r228323705
* The fix is to rework BN so these gymnastics aren't required.
*/
if (!BN_add(l, k, dsa->params.q)
|| !BN_add(k, l, dsa->params.q))
goto err;
BN_consttime_swap(BN_is_bit_set(l, q_bits), k, l, q_words + 2);
if ((dsa)->meth->bn_mod_exp != NULL) {
if (!dsa->meth->bn_mod_exp(dsa, r, dsa->params.g, k, dsa->params.p,
ctx, dsa->method_mont_p))
goto err;
} else {
if (!BN_mod_exp_mont(r, dsa->params.g, k, dsa->params.p, ctx,
dsa->method_mont_p))
goto err;
}
if (!BN_mod(r, r, dsa->params.q, ctx))
goto err;
/* Compute part of 's = inv(k) (m + xr) mod q' */
if ((kinv = dsa_mod_inverse_fermat(k, dsa->params.q, ctx)) == NULL)
goto err;
BN_clear_free(*kinvp);
*kinvp = kinv;
kinv = NULL;
ret = 1;
err:
if (!ret)
ERR_raise(ERR_LIB_DSA, ERR_R_BN_LIB);
if (ctx != ctx_in)
BN_CTX_free(ctx);
BN_clear_free(k);
BN_clear_free(l);
return ret;
}
static int dsa_do_verify(const unsigned char *dgst, int dgst_len,
DSA_SIG *sig, DSA *dsa)
{
BN_CTX *ctx;
BIGNUM *u1, *u2, *t1;
BN_MONT_CTX *mont = NULL;
const BIGNUM *r, *s;
int ret = -1, i;
if (dsa->params.p == NULL
|| dsa->params.q == NULL
|| dsa->params.g == NULL) {
ERR_raise(ERR_LIB_DSA, DSA_R_MISSING_PARAMETERS);
return -1;
}
i = BN_num_bits(dsa->params.q);
/* fips 186-3 allows only different sizes for q */
if (i != 160 && i != 224 && i != 256) {
ERR_raise(ERR_LIB_DSA, DSA_R_BAD_Q_VALUE);
return -1;
}
if (BN_num_bits(dsa->params.p) > OPENSSL_DSA_MAX_MODULUS_BITS) {
ERR_raise(ERR_LIB_DSA, DSA_R_MODULUS_TOO_LARGE);
return -1;
}
u1 = BN_new();
u2 = BN_new();
t1 = BN_new();
ctx = BN_CTX_new_ex(NULL); /* verify does not need a libctx */
if (u1 == NULL || u2 == NULL || t1 == NULL || ctx == NULL)
goto err;
DSA_SIG_get0(sig, &r, &s);
if (BN_is_zero(r) || BN_is_negative(r) ||
BN_ucmp(r, dsa->params.q) >= 0) {
ret = 0;
goto err;
}
if (BN_is_zero(s) || BN_is_negative(s) ||
BN_ucmp(s, dsa->params.q) >= 0) {
ret = 0;
goto err;
}
/*
* Calculate W = inv(S) mod Q save W in u2
*/
if ((BN_mod_inverse(u2, s, dsa->params.q, ctx)) == NULL)
goto err;
/* save M in u1 */
if (dgst_len > (i >> 3))
/*
* if the digest length is greater than the size of q use the
* BN_num_bits(dsa->q) leftmost bits of the digest, see fips 186-3,
* 4.2
*/
dgst_len = (i >> 3);
if (BN_bin2bn(dgst, dgst_len, u1) == NULL)
goto err;
/* u1 = M * w mod q */
if (!BN_mod_mul(u1, u1, u2, dsa->params.q, ctx))
goto err;
/* u2 = r * w mod q */
if (!BN_mod_mul(u2, r, u2, dsa->params.q, ctx))
goto err;
if (dsa->flags & DSA_FLAG_CACHE_MONT_P) {
mont = BN_MONT_CTX_set_locked(&dsa->method_mont_p,
dsa->lock, dsa->params.p, ctx);
if (!mont)
goto err;
}
if (dsa->meth->dsa_mod_exp != NULL) {
if (!dsa->meth->dsa_mod_exp(dsa, t1, dsa->params.g, u1, dsa->pub_key, u2,
dsa->params.p, ctx, mont))
goto err;
} else {
if (!BN_mod_exp2_mont(t1, dsa->params.g, u1, dsa->pub_key, u2,
dsa->params.p, ctx, mont))
goto err;
}
/* let u1 = u1 mod q */
if (!BN_mod(u1, t1, dsa->params.q, ctx))
goto err;
/*
* V is now in u1. If the signature is correct, it will be equal to R.
*/
ret = (BN_ucmp(u1, r) == 0);
err:
if (ret < 0)
ERR_raise(ERR_LIB_DSA, ERR_R_BN_LIB);
BN_CTX_free(ctx);
BN_free(u1);
BN_free(u2);
BN_free(t1);
return ret;
}
static int dsa_init(DSA *dsa)
{
dsa->flags |= DSA_FLAG_CACHE_MONT_P;
dsa->dirty_cnt++;
return 1;
}
static int dsa_finish(DSA *dsa)
{
BN_MONT_CTX_free(dsa->method_mont_p);
return 1;
}
/*
* Compute the inverse of k modulo q.
* Since q is prime, Fermat's Little Theorem applies, which reduces this to
* mod-exp operation. Both the exponent and modulus are public information
* so a mod-exp that doesn't leak the base is sufficient. A newly allocated
* BIGNUM is returned which the caller must free.
*/
static BIGNUM *dsa_mod_inverse_fermat(const BIGNUM *k, const BIGNUM *q,
BN_CTX *ctx)
{
BIGNUM *res = NULL;
BIGNUM *r, *e;
if ((r = BN_new()) == NULL)
return NULL;
BN_CTX_start(ctx);
if ((e = BN_CTX_get(ctx)) != NULL
&& BN_set_word(r, 2)
&& BN_sub(e, q, r)
&& BN_mod_exp_mont(r, k, e, q, ctx, NULL))
res = r;
else
BN_free(r);
BN_CTX_end(ctx);
return res;
}
diff --git a/crypto/openssl/crypto/dsa/dsa_sign.c b/crypto/openssl/crypto/dsa/dsa_sign.c
index ddfbfa18af15..91d334ea533a 100644
--- a/crypto/openssl/crypto/dsa/dsa_sign.c
+++ b/crypto/openssl/crypto/dsa/dsa_sign.c
@@ -1,209 +1,214 @@
/*
- * Copyright 1995-2023 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 1995-2024 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 <openssl/bn.h>
#include "internal/cryptlib.h"
#include "dsa_local.h"
#include "crypto/asn1_dsa.h"
#include "crypto/dsa.h"
DSA_SIG *DSA_do_sign(const unsigned char *dgst, int dlen, DSA *dsa)
{
return dsa->meth->dsa_do_sign(dgst, dlen, dsa);
}
#ifndef OPENSSL_NO_DEPRECATED_3_0
int DSA_sign_setup(DSA *dsa, BN_CTX *ctx_in, BIGNUM **kinvp, BIGNUM **rp)
{
return dsa->meth->dsa_sign_setup(dsa, ctx_in, kinvp, rp);
}
#endif
DSA_SIG *DSA_SIG_new(void)
{
DSA_SIG *sig = OPENSSL_zalloc(sizeof(*sig));
if (sig == NULL)
ERR_raise(ERR_LIB_DSA, ERR_R_MALLOC_FAILURE);
return sig;
}
void DSA_SIG_free(DSA_SIG *sig)
{
if (sig == NULL)
return;
BN_clear_free(sig->r);
BN_clear_free(sig->s);
OPENSSL_free(sig);
}
DSA_SIG *d2i_DSA_SIG(DSA_SIG **psig, const unsigned char **ppin, long len)
{
DSA_SIG *sig;
if (len < 0)
return NULL;
if (psig != NULL && *psig != NULL) {
sig = *psig;
} else {
sig = DSA_SIG_new();
if (sig == NULL)
return NULL;
}
if (sig->r == NULL)
sig->r = BN_new();
if (sig->s == NULL)
sig->s = BN_new();
if (sig->r == NULL || sig->s == NULL
|| ossl_decode_der_dsa_sig(sig->r, sig->s, ppin, (size_t)len) == 0) {
if (psig == NULL || *psig == NULL)
DSA_SIG_free(sig);
return NULL;
}
if (psig != NULL && *psig == NULL)
*psig = sig;
return sig;
}
int i2d_DSA_SIG(const DSA_SIG *sig, unsigned char **ppout)
{
BUF_MEM *buf = NULL;
size_t encoded_len;
WPACKET pkt;
if (ppout == NULL) {
if (!WPACKET_init_null(&pkt, 0))
return -1;
} else if (*ppout == NULL) {
if ((buf = BUF_MEM_new()) == NULL
|| !WPACKET_init_len(&pkt, buf, 0)) {
BUF_MEM_free(buf);
return -1;
}
} else {
if (!WPACKET_init_static_len(&pkt, *ppout, SIZE_MAX, 0))
return -1;
}
if (!ossl_encode_der_dsa_sig(&pkt, sig->r, sig->s)
|| !WPACKET_get_total_written(&pkt, &encoded_len)
|| !WPACKET_finish(&pkt)) {
BUF_MEM_free(buf);
WPACKET_cleanup(&pkt);
return -1;
}
if (ppout != NULL) {
if (*ppout == NULL) {
*ppout = (unsigned char *)buf->data;
buf->data = NULL;
BUF_MEM_free(buf);
} else {
*ppout += encoded_len;
}
}
return (int)encoded_len;
}
int DSA_size(const DSA *dsa)
{
int ret = -1;
DSA_SIG sig;
if (dsa->params.q != NULL) {
sig.r = sig.s = dsa->params.q;
ret = i2d_DSA_SIG(&sig, NULL);
if (ret < 0)
ret = 0;
}
return ret;
}
void DSA_SIG_get0(const DSA_SIG *sig, const BIGNUM **pr, const BIGNUM **ps)
{
if (pr != NULL)
*pr = sig->r;
if (ps != NULL)
*ps = sig->s;
}
int DSA_SIG_set0(DSA_SIG *sig, BIGNUM *r, BIGNUM *s)
{
if (r == NULL || s == NULL)
return 0;
BN_clear_free(sig->r);
BN_clear_free(sig->s);
sig->r = r;
sig->s = s;
return 1;
}
int ossl_dsa_sign_int(int type, const unsigned char *dgst, int dlen,
unsigned char *sig, unsigned int *siglen, DSA *dsa)
{
DSA_SIG *s;
+ if (sig == NULL) {
+ *siglen = DSA_size(dsa);
+ return 1;
+ }
+
/* legacy case uses the method table */
if (dsa->libctx == NULL || dsa->meth != DSA_get_default_method())
s = DSA_do_sign(dgst, dlen, dsa);
else
s = ossl_dsa_do_sign_int(dgst, dlen, dsa);
if (s == NULL) {
*siglen = 0;
return 0;
}
- *siglen = i2d_DSA_SIG(s, sig != NULL ? &sig : NULL);
+ *siglen = i2d_DSA_SIG(s, &sig);
DSA_SIG_free(s);
return 1;
}
int DSA_sign(int type, const unsigned char *dgst, int dlen,
unsigned char *sig, unsigned int *siglen, DSA *dsa)
{
return ossl_dsa_sign_int(type, dgst, dlen, sig, siglen, dsa);
}
/* data has already been hashed (probably with SHA or SHA-1). */
/*-
* returns
* 1: correct signature
* 0: incorrect signature
* -1: error
*/
int DSA_verify(int type, const unsigned char *dgst, int dgst_len,
const unsigned char *sigbuf, int siglen, DSA *dsa)
{
DSA_SIG *s;
const unsigned char *p = sigbuf;
unsigned char *der = NULL;
int derlen = -1;
int ret = -1;
s = DSA_SIG_new();
if (s == NULL)
return ret;
if (d2i_DSA_SIG(&s, &p, siglen) == NULL)
goto err;
/* Ensure signature uses DER and doesn't have trailing garbage */
derlen = i2d_DSA_SIG(s, &der);
if (derlen != siglen || memcmp(sigbuf, der, derlen))
goto err;
ret = DSA_do_verify(dgst, dgst_len, s, dsa);
err:
OPENSSL_clear_free(der, derlen);
DSA_SIG_free(s);
return ret;
}
diff --git a/crypto/openssl/crypto/ec/build.info b/crypto/openssl/crypto/ec/build.info
index a511e887a9ba..6dd98e9f4f17 100644
--- a/crypto/openssl/crypto/ec/build.info
+++ b/crypto/openssl/crypto/ec/build.info
@@ -1,105 +1,105 @@
$ECASM=
IF[{- !$disabled{asm} -}]
$ECASM_x86=ecp_nistz256.c ecp_nistz256-x86.S
$ECDEF_x86=ECP_NISTZ256_ASM
$ECASM_x86_64=ecp_nistz256.c ecp_nistz256-x86_64.s x25519-x86_64.s
$ECDEF_x86_64=ECP_NISTZ256_ASM X25519_ASM
$ECASM_ia64=
$ECASM_sparcv9=ecp_nistz256.c ecp_nistz256-sparcv9.S
$ECDEF_sparcv9=ECP_NISTZ256_ASM
$ECASM_sparcv8=
$ECASM_alpha=
$ECASM_mips32=
$ECASM_mips64=
$ECASM_s390x=ecp_s390x_nistp.c ecx_s390x.c
$ECDEF_s390x=S390X_EC_ASM
$ECASM_armv4=ecp_nistz256.c ecp_nistz256-armv4.S
$ECDEF_armv4=ECP_NISTZ256_ASM
$ECASM_aarch64=ecp_nistz256.c ecp_nistz256-armv8.S
$ECDEF_aarch64=ECP_NISTZ256_ASM
$ECASM_parisc11=
$ECASM_parisc20_64=
$ECASM_ppc32=
$ECASM_ppc64=ecp_nistz256.c ecp_ppc.c ecp_nistz256-ppc64.s x25519-ppc64.s
$ECDEF_ppc64=ECP_NISTZ256_ASM X25519_ASM
IF[{- !$disabled{'ec_nistp_64_gcc_128'} -}]
$ECASM_ppc64=$ECASM_ppc64 ecp_nistp521-ppc64.s
$ECDEF_ppc64=$ECDEF_ppc64 ECP_NISTP521_ASM
INCLUDE[ecp_nistp521.o]=..
ENDIF
$ECASM_c64xplus=
# Now that we have defined all the arch specific variables, use the
# appropriate one, and define the appropriate macros
IF[$ECASM_{- $target{asm_arch} -}]
$ECASM=$ECASM_{- $target{asm_arch} -}
$ECDEF=$ECDEF_{- $target{asm_arch} -}
ENDIF
ENDIF
$COMMON=ec_lib.c ecp_smpl.c ecp_mont.c ecp_nist.c ec_cvt.c ec_mult.c \
ec_curve.c ec_check.c ec_key.c ec_kmeth.c ecx_key.c ec_asn1.c \
ec2_smpl.c \
ecp_oct.c ec2_oct.c ec_oct.c ecdh_ossl.c \
ecdsa_ossl.c ecdsa_sign.c ecdsa_vrf.c curve25519.c \
curve448/f_generic.c curve448/scalar.c \
curve448/curve448_tables.c curve448/eddsa.c curve448/curve448.c \
$ECASM ec_backend.c ecx_backend.c ecdh_kdf.c curve448/arch_64/f_impl64.c \
curve448/arch_32/f_impl32.c
IF[{- !$disabled{'ec_nistp_64_gcc_128'} -}]
$COMMON=$COMMON ecp_nistp224.c ecp_nistp256.c ecp_nistp521.c ecp_nistputil.c
ENDIF
SOURCE[../../libcrypto]=$COMMON ec_ameth.c ec_pmeth.c ecx_meth.c \
ec_err.c eck_prn.c \
ec_deprecated.c ec_print.c
SOURCE[../../providers/libfips.a]=$COMMON
# Implementations are now spread across several libraries, so the defines
# need to be applied to all affected libraries and modules.
DEFINE[../../libcrypto]=$ECDEF
DEFINE[../../providers/libfips.a]=$ECDEF
DEFINE[../../providers/libdefault.a]=$ECDEF
# We only need to include the ECDEF stuff in the legacy provider when
# it's a separate module and it's dynamically linked with libcrypto.
# Otherwise, it already gets everything that the static libcrypto.a
# has, and doesn't need it added again.
IF[{- !$disabled{module} && !$disabled{shared} -}]
- DEFINE[../providers/liblegacy.a]=$ECDEF
+ DEFINE[../../providers/liblegacy.a]=$ECDEF
ENDIF
GENERATE[ecp_nistz256-x86.S]=asm/ecp_nistz256-x86.pl
GENERATE[ecp_nistz256-x86_64.s]=asm/ecp_nistz256-x86_64.pl
GENERATE[ecp_nistz256-avx2.s]=asm/ecp_nistz256-avx2.pl
GENERATE[ecp_nistz256-sparcv9.S]=asm/ecp_nistz256-sparcv9.pl
INCLUDE[ecp_nistz256-sparcv9.o]=..
INCLUDE[ecp_s390x_nistp.o]=..
INCLUDE[ecx_s390x.o]=..
INCLUDE[ecx_meth.o]=..
GENERATE[ecp_nistz256-armv4.S]=asm/ecp_nistz256-armv4.pl
INCLUDE[ecp_nistz256-armv4.o]=..
GENERATE[ecp_nistz256-armv8.S]=asm/ecp_nistz256-armv8.pl
INCLUDE[ecp_nistz256-armv8.o]=..
GENERATE[ecp_nistz256-ppc64.s]=asm/ecp_nistz256-ppc64.pl
GENERATE[ecp_nistp521-ppc64.s]=asm/ecp_nistp521-ppc64.pl
GENERATE[x25519-x86_64.s]=asm/x25519-x86_64.pl
GENERATE[x25519-ppc64.s]=asm/x25519-ppc64.pl
diff --git a/crypto/openssl/crypto/ec/curve448/arch_64/f_impl64.c b/crypto/openssl/crypto/ec/curve448/arch_64/f_impl64.c
index 8f7a7dd391bd..dfe75b8fc5ca 100644
--- a/crypto/openssl/crypto/ec/curve448/arch_64/f_impl64.c
+++ b/crypto/openssl/crypto/ec/curve448/arch_64/f_impl64.c
@@ -1,210 +1,210 @@
/*
- * Copyright 2017-2022 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2017-2024 The OpenSSL Project Authors. All Rights Reserved.
* Copyright 2014 Cryptography Research, Inc.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*
* Originally written by Mike Hamburg
*/
#include "e_os.h"
#include <openssl/macros.h>
#include "internal/numbers.h"
#ifndef UINT128_MAX
/* No support for 128 bit ints, so do nothing here */
NON_EMPTY_TRANSLATION_UNIT
#else
# include "../field.h"
void gf_mul(gf_s * RESTRICT cs, const gf as, const gf bs)
{
const uint64_t *a = as->limb, *b = bs->limb;
uint64_t *c = cs->limb;
uint128_t accum0 = 0, accum1 = 0, accum2;
uint64_t mask = (1ULL << 56) - 1;
uint64_t aa[4], bb[4], bbb[4];
unsigned int i, j;
for (i = 0; i < 4; i++) {
aa[i] = a[i] + a[i + 4];
bb[i] = b[i] + b[i + 4];
bbb[i] = bb[i] + b[i + 4];
}
for (i = 0; i < 4; i++) {
accum2 = 0;
for (j = 0; j <= i; j++) {
accum2 += widemul(a[j], b[i - j]);
accum1 += widemul(aa[j], bb[i - j]);
accum0 += widemul(a[j + 4], b[i - j + 4]);
}
for (; j < 4; j++) {
- accum2 += widemul(a[j], b[i - j + 8]);
- accum1 += widemul(aa[j], bbb[i - j + 4]);
- accum0 += widemul(a[j + 4], bb[i - j + 4]);
+ accum2 += widemul(a[j], b[i + 8 - j]);
+ accum1 += widemul(aa[j], bbb[i + 4 - j]);
+ accum0 += widemul(a[j + 4], bb[i + 4 - j]);
}
accum1 -= accum2;
accum0 += accum2;
c[i] = ((uint64_t)(accum0)) & mask;
c[i + 4] = ((uint64_t)(accum1)) & mask;
accum0 >>= 56;
accum1 >>= 56;
}
accum0 += accum1;
accum0 += c[4];
accum1 += c[0];
c[4] = ((uint64_t)(accum0)) & mask;
c[0] = ((uint64_t)(accum1)) & mask;
accum0 >>= 56;
accum1 >>= 56;
c[5] += ((uint64_t)(accum0));
c[1] += ((uint64_t)(accum1));
}
void gf_mulw_unsigned(gf_s * RESTRICT cs, const gf as, uint32_t b)
{
const uint64_t *a = as->limb;
uint64_t *c = cs->limb;
uint128_t accum0 = 0, accum4 = 0;
uint64_t mask = (1ULL << 56) - 1;
int i;
for (i = 0; i < 4; i++) {
accum0 += widemul(b, a[i]);
accum4 += widemul(b, a[i + 4]);
c[i] = accum0 & mask;
accum0 >>= 56;
c[i + 4] = accum4 & mask;
accum4 >>= 56;
}
accum0 += accum4 + c[4];
c[4] = accum0 & mask;
c[5] += accum0 >> 56;
accum4 += c[0];
c[0] = accum4 & mask;
c[1] += accum4 >> 56;
}
void gf_sqr(gf_s * RESTRICT cs, const gf as)
{
const uint64_t *a = as->limb;
uint64_t *c = cs->limb;
uint128_t accum0 = 0, accum1 = 0, accum2;
uint64_t mask = (1ULL << 56) - 1;
uint64_t aa[4];
unsigned int i;
/* For some reason clang doesn't vectorize this without prompting? */
for (i = 0; i < 4; i++)
aa[i] = a[i] + a[i + 4];
accum2 = widemul(a[0], a[3]);
accum0 = widemul(aa[0], aa[3]);
accum1 = widemul(a[4], a[7]);
accum2 += widemul(a[1], a[2]);
accum0 += widemul(aa[1], aa[2]);
accum1 += widemul(a[5], a[6]);
accum0 -= accum2;
accum1 += accum2;
c[3] = ((uint64_t)(accum1)) << 1 & mask;
c[7] = ((uint64_t)(accum0)) << 1 & mask;
accum0 >>= 55;
accum1 >>= 55;
accum0 += widemul(2 * aa[1], aa[3]);
accum1 += widemul(2 * a[5], a[7]);
accum0 += widemul(aa[2], aa[2]);
accum1 += accum0;
accum0 -= widemul(2 * a[1], a[3]);
accum1 += widemul(a[6], a[6]);
accum2 = widemul(a[0], a[0]);
accum1 -= accum2;
accum0 += accum2;
accum0 -= widemul(a[2], a[2]);
accum1 += widemul(aa[0], aa[0]);
accum0 += widemul(a[4], a[4]);
c[0] = ((uint64_t)(accum0)) & mask;
c[4] = ((uint64_t)(accum1)) & mask;
accum0 >>= 56;
accum1 >>= 56;
accum2 = widemul(2 * aa[2], aa[3]);
accum0 -= widemul(2 * a[2], a[3]);
accum1 += widemul(2 * a[6], a[7]);
accum1 += accum2;
accum0 += accum2;
accum2 = widemul(2 * a[0], a[1]);
accum1 += widemul(2 * aa[0], aa[1]);
accum0 += widemul(2 * a[4], a[5]);
accum1 -= accum2;
accum0 += accum2;
c[1] = ((uint64_t)(accum0)) & mask;
c[5] = ((uint64_t)(accum1)) & mask;
accum0 >>= 56;
accum1 >>= 56;
accum2 = widemul(aa[3], aa[3]);
accum0 -= widemul(a[3], a[3]);
accum1 += widemul(a[7], a[7]);
accum1 += accum2;
accum0 += accum2;
accum2 = widemul(2 * a[0], a[2]);
accum1 += widemul(2 * aa[0], aa[2]);
accum0 += widemul(2 * a[4], a[6]);
accum2 += widemul(a[1], a[1]);
accum1 += widemul(aa[1], aa[1]);
accum0 += widemul(a[5], a[5]);
accum1 -= accum2;
accum0 += accum2;
c[2] = ((uint64_t)(accum0)) & mask;
c[6] = ((uint64_t)(accum1)) & mask;
accum0 >>= 56;
accum1 >>= 56;
accum0 += c[3];
accum1 += c[7];
c[3] = ((uint64_t)(accum0)) & mask;
c[7] = ((uint64_t)(accum1)) & mask;
/* we could almost stop here, but it wouldn't be stable, so... */
accum0 >>= 56;
accum1 >>= 56;
c[4] += ((uint64_t)(accum0)) + ((uint64_t)(accum1));
c[0] += ((uint64_t)(accum1));
}
#endif
diff --git a/crypto/openssl/crypto/ec/ecdsa_ossl.c b/crypto/openssl/crypto/ec/ecdsa_ossl.c
index 0bf4635e2f97..4b54a30cf9bc 100644
--- a/crypto/openssl/crypto/ec/ecdsa_ossl.c
+++ b/crypto/openssl/crypto/ec/ecdsa_ossl.c
@@ -1,481 +1,486 @@
/*
- * Copyright 2002-2023 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2002-2024 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
*/
/*
* ECDSA low level APIs are deprecated for public use, but still ok for
* internal use.
*/
#include "internal/deprecated.h"
#include <string.h>
#include <openssl/err.h>
#include <openssl/obj_mac.h>
#include <openssl/rand.h>
#include "crypto/bn.h"
#include "ec_local.h"
#define MIN_ECDSA_SIGN_ORDERBITS 64
/*
* It is highly unlikely that a retry will happen,
* Multiple retries would indicate that something is wrong
* with the group parameters (which would normally only happen
* with a bad custom group).
*/
#define MAX_ECDSA_SIGN_RETRIES 8
int ossl_ecdsa_sign_setup(EC_KEY *eckey, BN_CTX *ctx_in, BIGNUM **kinvp,
BIGNUM **rp)
{
if (eckey->group->meth->ecdsa_sign_setup == NULL) {
ERR_raise(ERR_LIB_EC, EC_R_CURVE_DOES_NOT_SUPPORT_ECDSA);
return 0;
}
return eckey->group->meth->ecdsa_sign_setup(eckey, ctx_in, kinvp, rp);
}
ECDSA_SIG *ossl_ecdsa_sign_sig(const unsigned char *dgst, int dgst_len,
const BIGNUM *in_kinv, const BIGNUM *in_r,
EC_KEY *eckey)
{
if (eckey->group->meth->ecdsa_sign_sig == NULL) {
ERR_raise(ERR_LIB_EC, EC_R_CURVE_DOES_NOT_SUPPORT_ECDSA);
return NULL;
}
return eckey->group->meth->ecdsa_sign_sig(dgst, dgst_len,
in_kinv, in_r, eckey);
}
int ossl_ecdsa_verify_sig(const unsigned char *dgst, int dgst_len,
const ECDSA_SIG *sig, EC_KEY *eckey)
{
if (eckey->group->meth->ecdsa_verify_sig == NULL) {
ERR_raise(ERR_LIB_EC, EC_R_CURVE_DOES_NOT_SUPPORT_ECDSA);
return 0;
}
return eckey->group->meth->ecdsa_verify_sig(dgst, dgst_len, sig, eckey);
}
int ossl_ecdsa_sign(int type, const unsigned char *dgst, int dlen,
unsigned char *sig, unsigned int *siglen,
const BIGNUM *kinv, const BIGNUM *r, EC_KEY *eckey)
{
ECDSA_SIG *s;
+ if (sig == NULL && (kinv == NULL || r == NULL)) {
+ *siglen = ECDSA_size(eckey);
+ return 1;
+ }
+
s = ECDSA_do_sign_ex(dgst, dlen, kinv, r, eckey);
if (s == NULL) {
*siglen = 0;
return 0;
}
*siglen = i2d_ECDSA_SIG(s, sig != NULL ? &sig : NULL);
ECDSA_SIG_free(s);
return 1;
}
static int ecdsa_sign_setup(EC_KEY *eckey, BN_CTX *ctx_in,
BIGNUM **kinvp, BIGNUM **rp,
const unsigned char *dgst, int dlen)
{
BN_CTX *ctx = NULL;
BIGNUM *k = NULL, *r = NULL, *X = NULL;
const BIGNUM *order;
EC_POINT *tmp_point = NULL;
const EC_GROUP *group;
int ret = 0;
int order_bits;
const BIGNUM *priv_key;
if (eckey == NULL || (group = EC_KEY_get0_group(eckey)) == NULL) {
ERR_raise(ERR_LIB_EC, ERR_R_PASSED_NULL_PARAMETER);
return 0;
}
if ((priv_key = EC_KEY_get0_private_key(eckey)) == NULL) {
ERR_raise(ERR_LIB_EC, EC_R_MISSING_PRIVATE_KEY);
return 0;
}
if (!EC_KEY_can_sign(eckey)) {
ERR_raise(ERR_LIB_EC, EC_R_CURVE_DOES_NOT_SUPPORT_SIGNING);
return 0;
}
if ((ctx = ctx_in) == NULL) {
if ((ctx = BN_CTX_new_ex(eckey->libctx)) == NULL) {
ERR_raise(ERR_LIB_EC, ERR_R_MALLOC_FAILURE);
return 0;
}
}
k = BN_secure_new(); /* this value is later returned in *kinvp */
r = BN_new(); /* this value is later returned in *rp */
X = BN_new();
if (k == NULL || r == NULL || X == NULL) {
ERR_raise(ERR_LIB_EC, ERR_R_MALLOC_FAILURE);
goto err;
}
if ((tmp_point = EC_POINT_new(group)) == NULL) {
ERR_raise(ERR_LIB_EC, ERR_R_EC_LIB);
goto err;
}
order = EC_GROUP_get0_order(group);
/* Preallocate space */
order_bits = BN_num_bits(order);
/* Check the number of bits here so that an infinite loop is not possible */
if (order_bits < MIN_ECDSA_SIGN_ORDERBITS
|| !BN_set_bit(k, order_bits)
|| !BN_set_bit(r, order_bits)
|| !BN_set_bit(X, order_bits))
goto err;
do {
/* get random k */
do {
if (dgst != NULL) {
- if (!BN_generate_dsa_nonce(k, order, priv_key,
- dgst, dlen, ctx)) {
+ if (!ossl_bn_gen_dsa_nonce_fixed_top(k, order, priv_key,
+ dgst, dlen, ctx)) {
ERR_raise(ERR_LIB_EC, EC_R_RANDOM_NUMBER_GENERATION_FAILED);
goto err;
}
} else {
- if (!BN_priv_rand_range_ex(k, order, 0, ctx)) {
+ if (!ossl_bn_priv_rand_range_fixed_top(k, order, 0, ctx)) {
ERR_raise(ERR_LIB_EC, EC_R_RANDOM_NUMBER_GENERATION_FAILED);
goto err;
}
}
- } while (BN_is_zero(k));
+ } while (ossl_bn_is_word_fixed_top(k, 0));
/* compute r the x-coordinate of generator * k */
if (!EC_POINT_mul(group, tmp_point, k, NULL, NULL, ctx)) {
ERR_raise(ERR_LIB_EC, ERR_R_EC_LIB);
goto err;
}
if (!EC_POINT_get_affine_coordinates(group, tmp_point, X, NULL, ctx)) {
ERR_raise(ERR_LIB_EC, ERR_R_EC_LIB);
goto err;
}
if (!BN_nnmod(r, X, order, ctx)) {
ERR_raise(ERR_LIB_EC, ERR_R_BN_LIB);
goto err;
}
} while (BN_is_zero(r));
/* compute the inverse of k */
if (!ossl_ec_group_do_inverse_ord(group, k, k, ctx)) {
ERR_raise(ERR_LIB_EC, ERR_R_BN_LIB);
goto err;
}
/* clear old values if necessary */
BN_clear_free(*rp);
BN_clear_free(*kinvp);
/* save the pre-computed values */
*rp = r;
*kinvp = k;
ret = 1;
err:
if (!ret) {
BN_clear_free(k);
BN_clear_free(r);
}
if (ctx != ctx_in)
BN_CTX_free(ctx);
EC_POINT_free(tmp_point);
BN_clear_free(X);
return ret;
}
int ossl_ecdsa_simple_sign_setup(EC_KEY *eckey, BN_CTX *ctx_in, BIGNUM **kinvp,
BIGNUM **rp)
{
return ecdsa_sign_setup(eckey, ctx_in, kinvp, rp, NULL, 0);
}
ECDSA_SIG *ossl_ecdsa_simple_sign_sig(const unsigned char *dgst, int dgst_len,
const BIGNUM *in_kinv, const BIGNUM *in_r,
EC_KEY *eckey)
{
int ok = 0, i;
int retries = 0;
BIGNUM *kinv = NULL, *s, *m = NULL;
const BIGNUM *order, *ckinv;
BN_CTX *ctx = NULL;
const EC_GROUP *group;
ECDSA_SIG *ret;
const BIGNUM *priv_key;
group = EC_KEY_get0_group(eckey);
priv_key = EC_KEY_get0_private_key(eckey);
if (group == NULL) {
ERR_raise(ERR_LIB_EC, ERR_R_PASSED_NULL_PARAMETER);
return NULL;
}
if (priv_key == NULL) {
ERR_raise(ERR_LIB_EC, EC_R_MISSING_PRIVATE_KEY);
return NULL;
}
if (!EC_KEY_can_sign(eckey)) {
ERR_raise(ERR_LIB_EC, EC_R_CURVE_DOES_NOT_SUPPORT_SIGNING);
return NULL;
}
ret = ECDSA_SIG_new();
if (ret == NULL) {
ERR_raise(ERR_LIB_EC, ERR_R_MALLOC_FAILURE);
return NULL;
}
ret->r = BN_new();
ret->s = BN_new();
if (ret->r == NULL || ret->s == NULL) {
ERR_raise(ERR_LIB_EC, ERR_R_MALLOC_FAILURE);
goto err;
}
s = ret->s;
if ((ctx = BN_CTX_new_ex(eckey->libctx)) == NULL
|| (m = BN_new()) == NULL) {
ERR_raise(ERR_LIB_EC, ERR_R_MALLOC_FAILURE);
goto err;
}
order = EC_GROUP_get0_order(group);
i = BN_num_bits(order);
/*
* Need to truncate digest if it is too long: first truncate whole bytes.
*/
if (8 * dgst_len > i)
dgst_len = (i + 7) / 8;
if (!BN_bin2bn(dgst, dgst_len, m)) {
ERR_raise(ERR_LIB_EC, ERR_R_BN_LIB);
goto err;
}
/* If still too long, truncate remaining bits with a shift */
if ((8 * dgst_len > i) && !BN_rshift(m, m, 8 - (i & 0x7))) {
ERR_raise(ERR_LIB_EC, ERR_R_BN_LIB);
goto err;
}
do {
if (in_kinv == NULL || in_r == NULL) {
if (!ecdsa_sign_setup(eckey, ctx, &kinv, &ret->r, dgst, dgst_len)) {
ERR_raise(ERR_LIB_EC, ERR_R_ECDSA_LIB);
goto err;
}
ckinv = kinv;
} else {
ckinv = in_kinv;
if (BN_copy(ret->r, in_r) == NULL) {
ERR_raise(ERR_LIB_EC, ERR_R_MALLOC_FAILURE);
goto err;
}
}
/*
* With only one multiplicant being in Montgomery domain
* multiplication yields real result without post-conversion.
* Also note that all operations but last are performed with
* zero-padded vectors. Last operation, BN_mod_mul_montgomery
* below, returns user-visible value with removed zero padding.
*/
if (!bn_to_mont_fixed_top(s, ret->r, group->mont_data, ctx)
|| !bn_mul_mont_fixed_top(s, s, priv_key, group->mont_data, ctx)) {
ERR_raise(ERR_LIB_EC, ERR_R_BN_LIB);
goto err;
}
if (!bn_mod_add_fixed_top(s, s, m, order)) {
ERR_raise(ERR_LIB_EC, ERR_R_BN_LIB);
goto err;
}
/*
* |s| can still be larger than modulus, because |m| can be. In
* such case we count on Montgomery reduction to tie it up.
*/
if (!bn_to_mont_fixed_top(s, s, group->mont_data, ctx)
|| !BN_mod_mul_montgomery(s, s, ckinv, group->mont_data, ctx)) {
ERR_raise(ERR_LIB_EC, ERR_R_BN_LIB);
goto err;
}
if (BN_is_zero(s)) {
/*
* if kinv and r have been supplied by the caller, don't
* generate new kinv and r values
*/
if (in_kinv != NULL && in_r != NULL) {
ERR_raise(ERR_LIB_EC, EC_R_NEED_NEW_SETUP_VALUES);
goto err;
}
/* Avoid infinite loops cause by invalid group parameters */
if (retries++ > MAX_ECDSA_SIGN_RETRIES) {
ERR_raise(ERR_LIB_EC, EC_R_TOO_MANY_RETRIES);
goto err;
}
} else {
/* s != 0 => we have a valid signature */
break;
}
} while (1);
ok = 1;
err:
if (!ok) {
ECDSA_SIG_free(ret);
ret = NULL;
}
BN_CTX_free(ctx);
BN_clear_free(m);
BN_clear_free(kinv);
return ret;
}
/*-
* returns
* 1: correct signature
* 0: incorrect signature
* -1: error
*/
int ossl_ecdsa_verify(int type, const unsigned char *dgst, int dgst_len,
const unsigned char *sigbuf, int sig_len, EC_KEY *eckey)
{
ECDSA_SIG *s;
const unsigned char *p = sigbuf;
unsigned char *der = NULL;
int derlen = -1;
int ret = -1;
s = ECDSA_SIG_new();
if (s == NULL)
return ret;
if (d2i_ECDSA_SIG(&s, &p, sig_len) == NULL)
goto err;
/* Ensure signature uses DER and doesn't have trailing garbage */
derlen = i2d_ECDSA_SIG(s, &der);
if (derlen != sig_len || memcmp(sigbuf, der, derlen) != 0)
goto err;
ret = ECDSA_do_verify(dgst, dgst_len, s, eckey);
err:
OPENSSL_free(der);
ECDSA_SIG_free(s);
return ret;
}
int ossl_ecdsa_simple_verify_sig(const unsigned char *dgst, int dgst_len,
const ECDSA_SIG *sig, EC_KEY *eckey)
{
int ret = -1, i;
BN_CTX *ctx;
const BIGNUM *order;
BIGNUM *u1, *u2, *m, *X;
EC_POINT *point = NULL;
const EC_GROUP *group;
const EC_POINT *pub_key;
/* check input values */
if (eckey == NULL || (group = EC_KEY_get0_group(eckey)) == NULL ||
(pub_key = EC_KEY_get0_public_key(eckey)) == NULL || sig == NULL) {
ERR_raise(ERR_LIB_EC, EC_R_MISSING_PARAMETERS);
return -1;
}
if (!EC_KEY_can_sign(eckey)) {
ERR_raise(ERR_LIB_EC, EC_R_CURVE_DOES_NOT_SUPPORT_SIGNING);
return -1;
}
ctx = BN_CTX_new_ex(eckey->libctx);
if (ctx == NULL) {
ERR_raise(ERR_LIB_EC, ERR_R_MALLOC_FAILURE);
return -1;
}
BN_CTX_start(ctx);
u1 = BN_CTX_get(ctx);
u2 = BN_CTX_get(ctx);
m = BN_CTX_get(ctx);
X = BN_CTX_get(ctx);
if (X == NULL) {
ERR_raise(ERR_LIB_EC, ERR_R_BN_LIB);
goto err;
}
order = EC_GROUP_get0_order(group);
if (order == NULL) {
ERR_raise(ERR_LIB_EC, ERR_R_EC_LIB);
goto err;
}
if (BN_is_zero(sig->r) || BN_is_negative(sig->r) ||
BN_ucmp(sig->r, order) >= 0 || BN_is_zero(sig->s) ||
BN_is_negative(sig->s) || BN_ucmp(sig->s, order) >= 0) {
ERR_raise(ERR_LIB_EC, EC_R_BAD_SIGNATURE);
ret = 0; /* signature is invalid */
goto err;
}
/* calculate tmp1 = inv(S) mod order */
if (!ossl_ec_group_do_inverse_ord(group, u2, sig->s, ctx)) {
ERR_raise(ERR_LIB_EC, ERR_R_BN_LIB);
goto err;
}
/* digest -> m */
i = BN_num_bits(order);
/*
* Need to truncate digest if it is too long: first truncate whole bytes.
*/
if (8 * dgst_len > i)
dgst_len = (i + 7) / 8;
if (!BN_bin2bn(dgst, dgst_len, m)) {
ERR_raise(ERR_LIB_EC, ERR_R_BN_LIB);
goto err;
}
/* If still too long truncate remaining bits with a shift */
if ((8 * dgst_len > i) && !BN_rshift(m, m, 8 - (i & 0x7))) {
ERR_raise(ERR_LIB_EC, ERR_R_BN_LIB);
goto err;
}
/* u1 = m * tmp mod order */
if (!BN_mod_mul(u1, m, u2, order, ctx)) {
ERR_raise(ERR_LIB_EC, ERR_R_BN_LIB);
goto err;
}
/* u2 = r * w mod q */
if (!BN_mod_mul(u2, sig->r, u2, order, ctx)) {
ERR_raise(ERR_LIB_EC, ERR_R_BN_LIB);
goto err;
}
if ((point = EC_POINT_new(group)) == NULL) {
ERR_raise(ERR_LIB_EC, ERR_R_MALLOC_FAILURE);
goto err;
}
if (!EC_POINT_mul(group, point, u1, pub_key, u2, ctx)) {
ERR_raise(ERR_LIB_EC, ERR_R_EC_LIB);
goto err;
}
if (!EC_POINT_get_affine_coordinates(group, point, X, NULL, ctx)) {
ERR_raise(ERR_LIB_EC, ERR_R_EC_LIB);
goto err;
}
if (!BN_nnmod(u1, X, order, ctx)) {
ERR_raise(ERR_LIB_EC, ERR_R_BN_LIB);
goto err;
}
/* if the signature is correct u1 is equal to sig->r */
ret = (BN_ucmp(u1, sig->r) == 0);
err:
BN_CTX_end(ctx);
BN_CTX_free(ctx);
EC_POINT_free(point);
return ret;
}
diff --git a/crypto/openssl/crypto/encode_decode/encoder_lib.c b/crypto/openssl/crypto/encode_decode/encoder_lib.c
index 7a55c7ab9a27..a88332b79d52 100644
--- a/crypto/openssl/crypto/encode_decode/encoder_lib.c
+++ b/crypto/openssl/crypto/encode_decode/encoder_lib.c
@@ -1,674 +1,679 @@
/*
- * Copyright 2019-2022 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2019-2024 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 <openssl/core_names.h>
#include <openssl/bio.h>
#include <openssl/encoder.h>
#include <openssl/buffer.h>
#include <openssl/params.h>
#include <openssl/provider.h>
#include <openssl/trace.h>
#include "internal/bio.h"
#include "internal/provider.h"
#include "encoder_local.h"
struct encoder_process_data_st {
OSSL_ENCODER_CTX *ctx;
/* Current BIO */
BIO *bio;
/* Index of the current encoder instance to be processed */
int current_encoder_inst_index;
/* Processing data passed down through recursion */
int level; /* Recursion level */
OSSL_ENCODER_INSTANCE *next_encoder_inst;
int count_output_structure;
/* Processing data passed up through recursion */
OSSL_ENCODER_INSTANCE *prev_encoder_inst;
unsigned char *running_output;
size_t running_output_length;
/* Data type = the name of the first succeeding encoder implementation */
const char *data_type;
};
static int encoder_process(struct encoder_process_data_st *data);
int OSSL_ENCODER_to_bio(OSSL_ENCODER_CTX *ctx, BIO *out)
{
struct encoder_process_data_st data;
memset(&data, 0, sizeof(data));
data.ctx = ctx;
data.bio = out;
data.current_encoder_inst_index = OSSL_ENCODER_CTX_get_num_encoders(ctx);
if (data.current_encoder_inst_index == 0) {
ERR_raise_data(ERR_LIB_OSSL_ENCODER, OSSL_ENCODER_R_ENCODER_NOT_FOUND,
"No encoders were found. For standard encoders you need "
"at least one of the default or base providers "
"available. Did you forget to load them?");
return 0;
}
+ if (ctx->cleanup == NULL || ctx->construct == NULL) {
+ ERR_raise(ERR_LIB_OSSL_ENCODER, ERR_R_INIT_FAIL);
+ return 0;
+ }
+
return encoder_process(&data) > 0;
}
#ifndef OPENSSL_NO_STDIO
static BIO *bio_from_file(FILE *fp)
{
BIO *b;
if ((b = BIO_new(BIO_s_file())) == NULL) {
ERR_raise(ERR_LIB_OSSL_ENCODER, ERR_R_BUF_LIB);
return NULL;
}
BIO_set_fp(b, fp, BIO_NOCLOSE);
return b;
}
int OSSL_ENCODER_to_fp(OSSL_ENCODER_CTX *ctx, FILE *fp)
{
BIO *b = bio_from_file(fp);
int ret = 0;
if (b != NULL)
ret = OSSL_ENCODER_to_bio(ctx, b);
BIO_free(b);
return ret;
}
#endif
int OSSL_ENCODER_to_data(OSSL_ENCODER_CTX *ctx, unsigned char **pdata,
size_t *pdata_len)
{
BIO *out;
BUF_MEM *buf = NULL;
int ret = 0;
if (pdata_len == NULL) {
ERR_raise(ERR_LIB_OSSL_ENCODER, ERR_R_PASSED_NULL_PARAMETER);
return 0;
}
out = BIO_new(BIO_s_mem());
if (out != NULL
&& OSSL_ENCODER_to_bio(ctx, out)
&& BIO_get_mem_ptr(out, &buf) > 0) {
ret = 1; /* Hope for the best. A too small buffer will clear this */
if (pdata != NULL && *pdata != NULL) {
if (*pdata_len < buf->length)
/*
* It's tempting to do |*pdata_len = (size_t)buf->length|
* However, it's believed to be confusing more than helpful,
* so we don't.
*/
ret = 0;
else
*pdata_len -= buf->length;
} else {
/* The buffer with the right size is already allocated for us */
*pdata_len = (size_t)buf->length;
}
if (ret) {
if (pdata != NULL) {
if (*pdata != NULL) {
memcpy(*pdata, buf->data, buf->length);
*pdata += buf->length;
} else {
/* In this case, we steal the data from BIO_s_mem() */
*pdata = (unsigned char *)buf->data;
buf->data = NULL;
}
}
}
}
BIO_free(out);
return ret;
}
int OSSL_ENCODER_CTX_set_selection(OSSL_ENCODER_CTX *ctx, int selection)
{
if (!ossl_assert(ctx != NULL)) {
ERR_raise(ERR_LIB_OSSL_ENCODER, ERR_R_PASSED_NULL_PARAMETER);
return 0;
}
if (!ossl_assert(selection != 0)) {
ERR_raise(ERR_LIB_OSSL_ENCODER, ERR_R_PASSED_INVALID_ARGUMENT);
return 0;
}
ctx->selection = selection;
return 1;
}
int OSSL_ENCODER_CTX_set_output_type(OSSL_ENCODER_CTX *ctx,
const char *output_type)
{
if (!ossl_assert(ctx != NULL) || !ossl_assert(output_type != NULL)) {
ERR_raise(ERR_LIB_OSSL_ENCODER, ERR_R_PASSED_NULL_PARAMETER);
return 0;
}
ctx->output_type = output_type;
return 1;
}
int OSSL_ENCODER_CTX_set_output_structure(OSSL_ENCODER_CTX *ctx,
const char *output_structure)
{
if (!ossl_assert(ctx != NULL) || !ossl_assert(output_structure != NULL)) {
ERR_raise(ERR_LIB_OSSL_ENCODER, ERR_R_PASSED_NULL_PARAMETER);
return 0;
}
ctx->output_structure = output_structure;
return 1;
}
static OSSL_ENCODER_INSTANCE *ossl_encoder_instance_new(OSSL_ENCODER *encoder,
void *encoderctx)
{
OSSL_ENCODER_INSTANCE *encoder_inst = NULL;
const OSSL_PROVIDER *prov;
OSSL_LIB_CTX *libctx;
const OSSL_PROPERTY_LIST *props;
const OSSL_PROPERTY_DEFINITION *prop;
if (!ossl_assert(encoder != NULL)) {
ERR_raise(ERR_LIB_OSSL_ENCODER, ERR_R_PASSED_NULL_PARAMETER);
return 0;
}
if ((encoder_inst = OPENSSL_zalloc(sizeof(*encoder_inst))) == NULL) {
ERR_raise(ERR_LIB_OSSL_ENCODER, ERR_R_MALLOC_FAILURE);
return 0;
}
if (!OSSL_ENCODER_up_ref(encoder)) {
ERR_raise(ERR_LIB_OSSL_ENCODER, ERR_R_INTERNAL_ERROR);
goto err;
}
prov = OSSL_ENCODER_get0_provider(encoder);
libctx = ossl_provider_libctx(prov);
props = ossl_encoder_parsed_properties(encoder);
if (props == NULL) {
ERR_raise_data(ERR_LIB_OSSL_DECODER, ERR_R_INVALID_PROPERTY_DEFINITION,
"there are no property definitions with encoder %s",
OSSL_ENCODER_get0_name(encoder));
goto err;
}
/* The "output" property is mandatory */
prop = ossl_property_find_property(props, libctx, "output");
encoder_inst->output_type = ossl_property_get_string_value(libctx, prop);
if (encoder_inst->output_type == NULL) {
ERR_raise_data(ERR_LIB_OSSL_DECODER, ERR_R_INVALID_PROPERTY_DEFINITION,
"the mandatory 'output' property is missing "
"for encoder %s (properties: %s)",
OSSL_ENCODER_get0_name(encoder),
OSSL_ENCODER_get0_properties(encoder));
goto err;
}
/* The "structure" property is optional */
prop = ossl_property_find_property(props, libctx, "structure");
if (prop != NULL)
encoder_inst->output_structure
= ossl_property_get_string_value(libctx, prop);
encoder_inst->encoder = encoder;
encoder_inst->encoderctx = encoderctx;
return encoder_inst;
err:
ossl_encoder_instance_free(encoder_inst);
return NULL;
}
void ossl_encoder_instance_free(OSSL_ENCODER_INSTANCE *encoder_inst)
{
if (encoder_inst != NULL) {
if (encoder_inst->encoder != NULL)
encoder_inst->encoder->freectx(encoder_inst->encoderctx);
encoder_inst->encoderctx = NULL;
OSSL_ENCODER_free(encoder_inst->encoder);
encoder_inst->encoder = NULL;
OPENSSL_free(encoder_inst);
}
}
static int ossl_encoder_ctx_add_encoder_inst(OSSL_ENCODER_CTX *ctx,
OSSL_ENCODER_INSTANCE *ei)
{
int ok;
if (ctx->encoder_insts == NULL
&& (ctx->encoder_insts =
sk_OSSL_ENCODER_INSTANCE_new_null()) == NULL) {
ERR_raise(ERR_LIB_OSSL_ENCODER, ERR_R_MALLOC_FAILURE);
return 0;
}
ok = (sk_OSSL_ENCODER_INSTANCE_push(ctx->encoder_insts, ei) > 0);
if (ok) {
OSSL_TRACE_BEGIN(ENCODER) {
BIO_printf(trc_out,
"(ctx %p) Added encoder instance %p (encoder %p):\n"
" %s with %s\n",
(void *)ctx, (void *)ei, (void *)ei->encoder,
OSSL_ENCODER_get0_name(ei->encoder),
OSSL_ENCODER_get0_properties(ei->encoder));
} OSSL_TRACE_END(ENCODER);
}
return ok;
}
int OSSL_ENCODER_CTX_add_encoder(OSSL_ENCODER_CTX *ctx, OSSL_ENCODER *encoder)
{
OSSL_ENCODER_INSTANCE *encoder_inst = NULL;
const OSSL_PROVIDER *prov = NULL;
void *encoderctx = NULL;
void *provctx = NULL;
if (!ossl_assert(ctx != NULL) || !ossl_assert(encoder != NULL)) {
ERR_raise(ERR_LIB_OSSL_ENCODER, ERR_R_PASSED_NULL_PARAMETER);
return 0;
}
prov = OSSL_ENCODER_get0_provider(encoder);
provctx = OSSL_PROVIDER_get0_provider_ctx(prov);
if ((encoderctx = encoder->newctx(provctx)) == NULL
|| (encoder_inst =
ossl_encoder_instance_new(encoder, encoderctx)) == NULL)
goto err;
/* Avoid double free of encoderctx on further errors */
encoderctx = NULL;
if (!ossl_encoder_ctx_add_encoder_inst(ctx, encoder_inst))
goto err;
return 1;
err:
ossl_encoder_instance_free(encoder_inst);
if (encoderctx != NULL)
encoder->freectx(encoderctx);
return 0;
}
int OSSL_ENCODER_CTX_add_extra(OSSL_ENCODER_CTX *ctx,
OSSL_LIB_CTX *libctx, const char *propq)
{
return 1;
}
int OSSL_ENCODER_CTX_get_num_encoders(OSSL_ENCODER_CTX *ctx)
{
if (ctx == NULL || ctx->encoder_insts == NULL)
return 0;
return sk_OSSL_ENCODER_INSTANCE_num(ctx->encoder_insts);
}
int OSSL_ENCODER_CTX_set_construct(OSSL_ENCODER_CTX *ctx,
OSSL_ENCODER_CONSTRUCT *construct)
{
if (!ossl_assert(ctx != NULL)) {
ERR_raise(ERR_LIB_OSSL_ENCODER, ERR_R_PASSED_NULL_PARAMETER);
return 0;
}
ctx->construct = construct;
return 1;
}
int OSSL_ENCODER_CTX_set_construct_data(OSSL_ENCODER_CTX *ctx,
void *construct_data)
{
if (!ossl_assert(ctx != NULL)) {
ERR_raise(ERR_LIB_OSSL_ENCODER, ERR_R_PASSED_NULL_PARAMETER);
return 0;
}
ctx->construct_data = construct_data;
return 1;
}
int OSSL_ENCODER_CTX_set_cleanup(OSSL_ENCODER_CTX *ctx,
OSSL_ENCODER_CLEANUP *cleanup)
{
if (!ossl_assert(ctx != NULL)) {
ERR_raise(ERR_LIB_OSSL_ENCODER, ERR_R_PASSED_NULL_PARAMETER);
return 0;
}
ctx->cleanup = cleanup;
return 1;
}
OSSL_ENCODER *
OSSL_ENCODER_INSTANCE_get_encoder(OSSL_ENCODER_INSTANCE *encoder_inst)
{
if (encoder_inst == NULL)
return NULL;
return encoder_inst->encoder;
}
void *
OSSL_ENCODER_INSTANCE_get_encoder_ctx(OSSL_ENCODER_INSTANCE *encoder_inst)
{
if (encoder_inst == NULL)
return NULL;
return encoder_inst->encoderctx;
}
const char *
OSSL_ENCODER_INSTANCE_get_output_type(OSSL_ENCODER_INSTANCE *encoder_inst)
{
if (encoder_inst == NULL)
return NULL;
return encoder_inst->output_type;
}
const char *
OSSL_ENCODER_INSTANCE_get_output_structure(OSSL_ENCODER_INSTANCE *encoder_inst)
{
if (encoder_inst == NULL)
return NULL;
return encoder_inst->output_structure;
}
static int encoder_process(struct encoder_process_data_st *data)
{
OSSL_ENCODER_INSTANCE *current_encoder_inst = NULL;
OSSL_ENCODER *current_encoder = NULL;
OSSL_ENCODER_CTX *current_encoder_ctx = NULL;
BIO *allocated_out = NULL;
const void *original_data = NULL;
OSSL_PARAM abstract[10];
const OSSL_PARAM *current_abstract = NULL;
int i;
int ok = -1; /* -1 signifies that the lookup loop gave nothing */
int top = 0;
if (data->next_encoder_inst == NULL) {
/* First iteration, where we prepare for what is to come */
data->count_output_structure =
data->ctx->output_structure == NULL ? -1 : 0;
top = 1;
}
for (i = data->current_encoder_inst_index; i-- > 0;) {
OSSL_ENCODER *next_encoder = NULL;
const char *current_output_type;
const char *current_output_structure;
struct encoder_process_data_st new_data;
if (!top)
next_encoder =
OSSL_ENCODER_INSTANCE_get_encoder(data->next_encoder_inst);
current_encoder_inst =
sk_OSSL_ENCODER_INSTANCE_value(data->ctx->encoder_insts, i);
current_encoder =
OSSL_ENCODER_INSTANCE_get_encoder(current_encoder_inst);
current_encoder_ctx =
OSSL_ENCODER_INSTANCE_get_encoder_ctx(current_encoder_inst);
current_output_type =
OSSL_ENCODER_INSTANCE_get_output_type(current_encoder_inst);
current_output_structure =
OSSL_ENCODER_INSTANCE_get_output_structure(current_encoder_inst);
memset(&new_data, 0, sizeof(new_data));
new_data.ctx = data->ctx;
new_data.current_encoder_inst_index = i;
new_data.next_encoder_inst = current_encoder_inst;
new_data.count_output_structure = data->count_output_structure;
new_data.level = data->level + 1;
OSSL_TRACE_BEGIN(ENCODER) {
BIO_printf(trc_out,
"[%d] (ctx %p) Considering encoder instance %p (encoder %p)\n",
data->level, (void *)data->ctx,
(void *)current_encoder_inst, (void *)current_encoder);
} OSSL_TRACE_END(ENCODER);
/*
* If this is the top call, we check if the output type of the current
* encoder matches the desired output type.
* If this isn't the top call, i.e. this is deeper in the recursion,
* we instead check if the output type of the current encoder matches
* the name of the next encoder (the one found by the parent call).
*/
if (top) {
if (data->ctx->output_type != NULL
&& OPENSSL_strcasecmp(current_output_type,
data->ctx->output_type) != 0) {
OSSL_TRACE_BEGIN(ENCODER) {
BIO_printf(trc_out,
"[%d] Skipping because current encoder output type (%s) != desired output type (%s)\n",
data->level,
current_output_type, data->ctx->output_type);
} OSSL_TRACE_END(ENCODER);
continue;
}
} else {
if (!OSSL_ENCODER_is_a(next_encoder, current_output_type)) {
OSSL_TRACE_BEGIN(ENCODER) {
BIO_printf(trc_out,
"[%d] Skipping because current encoder output type (%s) != name of encoder %p\n",
data->level,
current_output_type, (void *)next_encoder);
} OSSL_TRACE_END(ENCODER);
continue;
}
}
/*
* If the caller and the current encoder specify an output structure,
* Check if they match. If they do, count the match, otherwise skip
* the current encoder.
*/
if (data->ctx->output_structure != NULL
&& current_output_structure != NULL) {
if (OPENSSL_strcasecmp(data->ctx->output_structure,
current_output_structure) != 0) {
OSSL_TRACE_BEGIN(ENCODER) {
BIO_printf(trc_out,
"[%d] Skipping because current encoder output structure (%s) != ctx output structure (%s)\n",
data->level,
current_output_structure,
data->ctx->output_structure);
} OSSL_TRACE_END(ENCODER);
continue;
}
data->count_output_structure++;
}
/*
* Recurse to process the encoder implementations before the current
* one.
*/
ok = encoder_process(&new_data);
data->prev_encoder_inst = new_data.prev_encoder_inst;
data->running_output = new_data.running_output;
data->running_output_length = new_data.running_output_length;
/*
* ok == -1 means that the recursion call above gave no further
* encoders, and that the one we're currently at should
* be tried.
* ok == 0 means that something failed in the recursion call
* above, making the result unsuitable for a chain.
* In this case, we simply continue to try finding a
* suitable encoder at this recursion level.
* ok == 1 means that the recursion call was successful, and we
* try to use the result at this recursion level.
*/
if (ok != 0)
break;
OSSL_TRACE_BEGIN(ENCODER) {
BIO_printf(trc_out,
"[%d] Skipping because recusion level %d failed\n",
data->level, new_data.level);
} OSSL_TRACE_END(ENCODER);
}
/*
* If |i < 0|, we didn't find any useful encoder in this recursion, so
* we do the rest of the process only if |i >= 0|.
*/
if (i < 0) {
ok = -1;
OSSL_TRACE_BEGIN(ENCODER) {
BIO_printf(trc_out,
"[%d] (ctx %p) No suitable encoder found\n",
data->level, (void *)data->ctx);
} OSSL_TRACE_END(ENCODER);
} else {
/* Preparations */
switch (ok) {
case 0:
break;
case -1:
/*
* We have reached the beginning of the encoder instance sequence,
* so we prepare the object to be encoded.
*/
/*
* |data->count_output_structure| is one of these values:
*
* -1 There is no desired output structure
* 0 There is a desired output structure, and it wasn't
* matched by any of the encoder instances that were
* considered
* >0 There is a desired output structure, and at least one
* of the encoder instances matched it
*/
if (data->count_output_structure == 0)
return 0;
original_data =
data->ctx->construct(current_encoder_inst,
data->ctx->construct_data);
/* Also set the data type, using the encoder implementation name */
data->data_type = OSSL_ENCODER_get0_name(current_encoder);
/* Assume that the constructor recorded an error */
if (original_data != NULL)
ok = 1;
else
ok = 0;
break;
case 1:
if (!ossl_assert(data->running_output != NULL)) {
ERR_raise(ERR_LIB_OSSL_ENCODER, ERR_R_INTERNAL_ERROR);
ok = 0;
break;
}
{
/*
* Create an object abstraction from the latest output, which
* was stolen from the previous round.
*/
OSSL_PARAM *abstract_p = abstract;
const char *prev_output_structure =
OSSL_ENCODER_INSTANCE_get_output_structure(data->prev_encoder_inst);
*abstract_p++ =
OSSL_PARAM_construct_utf8_string(OSSL_OBJECT_PARAM_DATA_TYPE,
(char *)data->data_type, 0);
if (prev_output_structure != NULL)
*abstract_p++ =
OSSL_PARAM_construct_utf8_string(OSSL_OBJECT_PARAM_DATA_STRUCTURE,
(char *)prev_output_structure,
0);
*abstract_p++ =
OSSL_PARAM_construct_octet_string(OSSL_OBJECT_PARAM_DATA,
data->running_output,
data->running_output_length);
*abstract_p = OSSL_PARAM_construct_end();
current_abstract = abstract;
}
break;
}
/* Calling the encoder implementation */
if (ok) {
OSSL_CORE_BIO *cbio = NULL;
BIO *current_out = NULL;
/*
* If we're at the last encoder instance to use, we're setting up
* final output. Otherwise, set up an intermediary memory output.
*/
if (top)
current_out = data->bio;
else if ((current_out = allocated_out = BIO_new(BIO_s_mem()))
== NULL)
ok = 0; /* Assume BIO_new() recorded an error */
if (ok)
ok = (cbio = ossl_core_bio_new_from_bio(current_out)) != NULL;
if (ok) {
ok = current_encoder->encode(current_encoder_ctx, cbio,
original_data, current_abstract,
data->ctx->selection,
ossl_pw_passphrase_callback_enc,
&data->ctx->pwdata);
OSSL_TRACE_BEGIN(ENCODER) {
BIO_printf(trc_out,
"[%d] (ctx %p) Running encoder instance %p => %d\n",
data->level, (void *)data->ctx,
(void *)current_encoder_inst, ok);
} OSSL_TRACE_END(ENCODER);
}
ossl_core_bio_free(cbio);
data->prev_encoder_inst = current_encoder_inst;
}
}
/* Cleanup and collecting the result */
OPENSSL_free(data->running_output);
data->running_output = NULL;
/*
* Steal the output from the BIO_s_mem, if we did allocate one.
* That'll be the data for an object abstraction in the next round.
*/
if (allocated_out != NULL) {
BUF_MEM *buf;
BIO_get_mem_ptr(allocated_out, &buf);
data->running_output = (unsigned char *)buf->data;
data->running_output_length = buf->length;
memset(buf, 0, sizeof(*buf));
}
BIO_free(allocated_out);
if (original_data != NULL)
data->ctx->cleanup(data->ctx->construct_data);
return ok;
}
diff --git a/crypto/openssl/crypto/engine/eng_pkey.c b/crypto/openssl/crypto/engine/eng_pkey.c
index f84fcde46016..d18d837e625c 100644
--- a/crypto/openssl/crypto/engine/eng_pkey.c
+++ b/crypto/openssl/crypto/engine/eng_pkey.c
@@ -1,180 +1,138 @@
/*
- * Copyright 2001-2023 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2001-2024 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
/* We need to use some engine deprecated APIs */
#define OPENSSL_SUPPRESS_DEPRECATED
#include "eng_local.h"
/* Basic get/set stuff */
int ENGINE_set_load_privkey_function(ENGINE *e,
ENGINE_LOAD_KEY_PTR loadpriv_f)
{
e->load_privkey = loadpriv_f;
return 1;
}
int ENGINE_set_load_pubkey_function(ENGINE *e, ENGINE_LOAD_KEY_PTR loadpub_f)
{
e->load_pubkey = loadpub_f;
return 1;
}
int ENGINE_set_load_ssl_client_cert_function(ENGINE *e,
ENGINE_SSL_CLIENT_CERT_PTR
loadssl_f)
{
e->load_ssl_client_cert = loadssl_f;
return 1;
}
ENGINE_LOAD_KEY_PTR ENGINE_get_load_privkey_function(const ENGINE *e)
{
return e->load_privkey;
}
ENGINE_LOAD_KEY_PTR ENGINE_get_load_pubkey_function(const ENGINE *e)
{
return e->load_pubkey;
}
ENGINE_SSL_CLIENT_CERT_PTR ENGINE_get_ssl_client_cert_function(const ENGINE
*e)
{
return e->load_ssl_client_cert;
}
/* API functions to load public/private keys */
EVP_PKEY *ENGINE_load_private_key(ENGINE *e, const char *key_id,
UI_METHOD *ui_method, void *callback_data)
{
EVP_PKEY *pkey;
if (e == NULL) {
ERR_raise(ERR_LIB_ENGINE, ERR_R_PASSED_NULL_PARAMETER);
return NULL;
}
if (!CRYPTO_THREAD_write_lock(global_engine_lock))
return NULL;
if (e->funct_ref == 0) {
CRYPTO_THREAD_unlock(global_engine_lock);
ERR_raise(ERR_LIB_ENGINE, ENGINE_R_NOT_INITIALISED);
return NULL;
}
CRYPTO_THREAD_unlock(global_engine_lock);
if (!e->load_privkey) {
ERR_raise(ERR_LIB_ENGINE, ENGINE_R_NO_LOAD_FUNCTION);
return NULL;
}
pkey = e->load_privkey(e, key_id, ui_method, callback_data);
if (pkey == NULL) {
ERR_raise(ERR_LIB_ENGINE, ENGINE_R_FAILED_LOADING_PRIVATE_KEY);
return NULL;
}
- /* We enforce check for legacy key */
- switch (EVP_PKEY_get_id(pkey)) {
- case EVP_PKEY_RSA:
- {
- RSA *rsa = EVP_PKEY_get1_RSA(pkey);
- EVP_PKEY_set1_RSA(pkey, rsa);
- RSA_free(rsa);
- }
- break;
-# ifndef OPENSSL_NO_EC
- case EVP_PKEY_SM2:
- case EVP_PKEY_EC:
- {
- EC_KEY *ec = EVP_PKEY_get1_EC_KEY(pkey);
- EVP_PKEY_set1_EC_KEY(pkey, ec);
- EC_KEY_free(ec);
- }
- break;
-# endif
-# ifndef OPENSSL_NO_DSA
- case EVP_PKEY_DSA:
- {
- DSA *dsa = EVP_PKEY_get1_DSA(pkey);
- EVP_PKEY_set1_DSA(pkey, dsa);
- DSA_free(dsa);
- }
- break;
-#endif
-# ifndef OPENSSL_NO_DH
- case EVP_PKEY_DH:
- {
- DH *dh = EVP_PKEY_get1_DH(pkey);
- EVP_PKEY_set1_DH(pkey, dh);
- DH_free(dh);
- }
- break;
-#endif
- default:
- /*Do nothing */
- break;
- }
-
return pkey;
}
EVP_PKEY *ENGINE_load_public_key(ENGINE *e, const char *key_id,
UI_METHOD *ui_method, void *callback_data)
{
EVP_PKEY *pkey;
if (e == NULL) {
ERR_raise(ERR_LIB_ENGINE, ERR_R_PASSED_NULL_PARAMETER);
return NULL;
}
if (!CRYPTO_THREAD_write_lock(global_engine_lock))
return NULL;
if (e->funct_ref == 0) {
CRYPTO_THREAD_unlock(global_engine_lock);
ERR_raise(ERR_LIB_ENGINE, ENGINE_R_NOT_INITIALISED);
return NULL;
}
CRYPTO_THREAD_unlock(global_engine_lock);
if (!e->load_pubkey) {
ERR_raise(ERR_LIB_ENGINE, ENGINE_R_NO_LOAD_FUNCTION);
return NULL;
}
pkey = e->load_pubkey(e, key_id, ui_method, callback_data);
if (pkey == NULL) {
ERR_raise(ERR_LIB_ENGINE, ENGINE_R_FAILED_LOADING_PUBLIC_KEY);
return NULL;
}
return pkey;
}
int ENGINE_load_ssl_client_cert(ENGINE *e, SSL *s,
STACK_OF(X509_NAME) *ca_dn, X509 **pcert,
EVP_PKEY **ppkey, STACK_OF(X509) **pother,
UI_METHOD *ui_method, void *callback_data)
{
if (e == NULL) {
ERR_raise(ERR_LIB_ENGINE, ERR_R_PASSED_NULL_PARAMETER);
return 0;
}
if (!CRYPTO_THREAD_write_lock(global_engine_lock))
return 0;
if (e->funct_ref == 0) {
CRYPTO_THREAD_unlock(global_engine_lock);
ERR_raise(ERR_LIB_ENGINE, ENGINE_R_NOT_INITIALISED);
return 0;
}
CRYPTO_THREAD_unlock(global_engine_lock);
if (!e->load_ssl_client_cert) {
ERR_raise(ERR_LIB_ENGINE, ENGINE_R_NO_LOAD_FUNCTION);
return 0;
}
return e->load_ssl_client_cert(e, s, ca_dn, pcert, ppkey, pother,
ui_method, callback_data);
}
diff --git a/crypto/openssl/crypto/err/openssl.ec b/crypto/openssl/crypto/err/openssl.ec
index 3612c195f09f..f3802a05b5c3 100644
--- a/crypto/openssl/crypto/err/openssl.ec
+++ b/crypto/openssl/crypto/err/openssl.ec
@@ -1,81 +1,81 @@
# configuration file for util/mkerr.pl
# The INPUT HEADER is scanned for declarations
# LIBNAME PUBLIC HEADER ERROR-TABLE FILE INTERNAL HEADER (if relevant)
L ERR NONE NONE
L FUNC NONE NONE
L BN include/openssl/bnerr.h crypto/bn/bn_err.c include/crypto/bnerr.h
L RSA include/openssl/rsaerr.h crypto/rsa/rsa_err.c include/crypto/rsaerr.h
L DH include/openssl/dherr.h crypto/dh/dh_err.c include/crypto/dherr.h
L EVP include/openssl/evperr.h crypto/evp/evp_err.c include/crypto/evperr.h
L BUF include/openssl/buffererr.h crypto/buffer/buf_err.c include/crypto/buffererr.h
L OBJ include/openssl/objectserr.h crypto/objects/obj_err.c include/crypto/objectserr.h
L PEM include/openssl/pemerr.h crypto/pem/pem_err.c include/crypto/pemerr.h
L DSA include/openssl/dsaerr.h crypto/dsa/dsa_err.c include/crypto/dsaerr.h
L X509 include/openssl/x509err.h crypto/x509/x509_err.c include/crypto/x509err.h
L ASN1 include/openssl/asn1err.h crypto/asn1/asn1_err.c include/crypto/asn1err.h
L CONF include/openssl/conferr.h crypto/conf/conf_err.c include/crypto/conferr.h
L CRYPTO include/openssl/cryptoerr.h crypto/cpt_err.c include/crypto/cryptoerr.h
L EC include/openssl/ecerr.h crypto/ec/ec_err.c include/crypto/ecerr.h
L SSL include/openssl/sslerr.h ssl/ssl_err.c ssl/sslerr.h
L BIO include/openssl/bioerr.h crypto/bio/bio_err.c include/crypto/bioerr.h
L PKCS7 include/openssl/pkcs7err.h crypto/pkcs7/pkcs7err.c include/crypto/pkcs7err.h
L X509V3 include/openssl/x509v3err.h crypto/x509/v3err.c include/crypto/x509v3err.h
L PKCS12 include/openssl/pkcs12err.h crypto/pkcs12/pk12err.c include/crypto/pkcs12err.h
L RAND include/openssl/randerr.h crypto/rand/rand_err.c include/crypto/randerr.h
L DSO NONE crypto/dso/dso_err.c include/internal/dsoerr.h
L ENGINE include/openssl/engineerr.h crypto/engine/eng_err.c include/crypto/engineerr.h
L OCSP include/openssl/ocsperr.h crypto/ocsp/ocsp_err.c include/crypto/ocsperr.h
L UI include/openssl/uierr.h crypto/ui/ui_err.c include/crypto/uierr.h
L COMP include/openssl/comperr.h crypto/comp/comp_err.c include/crypto/comperr.h
L TS include/openssl/tserr.h crypto/ts/ts_err.c include/crypto/tserr.h
L CMS include/openssl/cmserr.h crypto/cms/cms_err.c include/crypto/cmserr.h
L CRMF include/openssl/crmferr.h crypto/crmf/crmf_err.c include/crypto/crmferr.h
L CMP include/openssl/cmperr.h crypto/cmp/cmp_err.c include/crypto/cmperr.h
L CT include/openssl/cterr.h crypto/ct/ct_err.c include/crypto/cterr.h
L ASYNC include/openssl/asyncerr.h crypto/async/async_err.c include/crypto/asyncerr.h
# KDF is only here for conservation purposes
L KDF NONE NONE NONE
L SM2 NONE crypto/sm2/sm2_err.c include/crypto/sm2err.h
L OSSL_STORE include/openssl/storeerr.h crypto/store/store_err.c include/crypto/storeerr.h
L ESS include/openssl/esserr.h crypto/ess/ess_err.c include/crypto/esserr.h
L PROP NONE crypto/property/property_err.c include/internal/propertyerr.h
L PROV include/openssl/proverr.h providers/common/provider_err.c providers/common/include/prov/proverr.h
L OSSL_ENCODER include/openssl/encodererr.h crypto/encode_decode/encoder_err.c include/crypto/encodererr.h
L OSSL_DECODER include/openssl/decodererr.h crypto/encode_decode/decoder_err.c include/crypto/decodererr.h
L HTTP include/openssl/httperr.h crypto/http/http_err.c include/crypto/httperr.h
# SSL/TLS alerts
R SSL_R_SSLV3_ALERT_UNEXPECTED_MESSAGE 1010
R SSL_R_SSLV3_ALERT_BAD_RECORD_MAC 1020
R SSL_R_TLSV1_ALERT_DECRYPTION_FAILED 1021
R SSL_R_TLSV1_ALERT_RECORD_OVERFLOW 1022
R SSL_R_SSLV3_ALERT_DECOMPRESSION_FAILURE 1030
R SSL_R_SSLV3_ALERT_HANDSHAKE_FAILURE 1040
R SSL_R_SSLV3_ALERT_NO_CERTIFICATE 1041
R SSL_R_SSLV3_ALERT_BAD_CERTIFICATE 1042
R SSL_R_SSLV3_ALERT_UNSUPPORTED_CERTIFICATE 1043
R SSL_R_SSLV3_ALERT_CERTIFICATE_REVOKED 1044
R SSL_R_SSLV3_ALERT_CERTIFICATE_EXPIRED 1045
R SSL_R_SSLV3_ALERT_CERTIFICATE_UNKNOWN 1046
R SSL_R_SSLV3_ALERT_ILLEGAL_PARAMETER 1047
R SSL_R_TLSV1_ALERT_UNKNOWN_CA 1048
R SSL_R_TLSV1_ALERT_ACCESS_DENIED 1049
R SSL_R_TLSV1_ALERT_DECODE_ERROR 1050
R SSL_R_TLSV1_ALERT_DECRYPT_ERROR 1051
R SSL_R_TLSV1_ALERT_EXPORT_RESTRICTION 1060
R SSL_R_TLSV1_ALERT_PROTOCOL_VERSION 1070
R SSL_R_TLSV1_ALERT_INSUFFICIENT_SECURITY 1071
R SSL_R_TLSV1_ALERT_INTERNAL_ERROR 1080
R SSL_R_TLSV1_ALERT_INAPPROPRIATE_FALLBACK 1086
R SSL_R_TLSV1_ALERT_USER_CANCELLED 1090
R SSL_R_TLSV1_ALERT_NO_RENEGOTIATION 1100
R SSL_R_TLSV13_ALERT_MISSING_EXTENSION 1109
R SSL_R_TLSV1_UNSUPPORTED_EXTENSION 1110
R SSL_R_TLSV1_CERTIFICATE_UNOBTAINABLE 1111
R SSL_R_TLSV1_UNRECOGNIZED_NAME 1112
R SSL_R_TLSV1_BAD_CERTIFICATE_STATUS_RESPONSE 1113
R SSL_R_TLSV1_BAD_CERTIFICATE_HASH_VALUE 1114
-R TLS1_AD_UNKNOWN_PSK_IDENTITY 1115
+R SSL_R_TLSV1_ALERT_UNKNOWN_PSK_IDENTITY 1115
R SSL_R_TLSV13_ALERT_CERTIFICATE_REQUIRED 1116
-R TLS1_AD_NO_APPLICATION_PROTOCOL 1120
+R SSL_R_TLSV1_ALERT_NO_APPLICATION_PROTOCOL 1120
diff --git a/crypto/openssl/crypto/ess/ess_lib.c b/crypto/openssl/crypto/ess/ess_lib.c
index 65444d383ff4..cd42f951f7b8 100644
--- a/crypto/openssl/crypto/ess/ess_lib.c
+++ b/crypto/openssl/crypto/ess/ess_lib.c
@@ -1,315 +1,315 @@
/*
- * Copyright 2019-2021 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2019-2024 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 <string.h>
#include <openssl/x509v3.h>
#include <openssl/err.h>
#include <openssl/ess.h>
#include "internal/sizes.h"
#include "crypto/ess.h"
#include "crypto/x509.h"
static ESS_CERT_ID *ESS_CERT_ID_new_init(const X509 *cert,
int set_issuer_serial);
static ESS_CERT_ID_V2 *ESS_CERT_ID_V2_new_init(const EVP_MD *hash_alg,
const X509 *cert,
int set_issuer_serial);
ESS_SIGNING_CERT *OSSL_ESS_signing_cert_new_init(const X509 *signcert,
const STACK_OF(X509) *certs,
int set_issuer_serial)
{
ESS_CERT_ID *cid = NULL;
ESS_SIGNING_CERT *sc;
int i;
if ((sc = ESS_SIGNING_CERT_new()) == NULL)
goto err;
if (sc->cert_ids == NULL
&& (sc->cert_ids = sk_ESS_CERT_ID_new_null()) == NULL)
goto err;
if ((cid = ESS_CERT_ID_new_init(signcert, set_issuer_serial)) == NULL
|| !sk_ESS_CERT_ID_push(sc->cert_ids, cid))
goto err;
for (i = 0; i < sk_X509_num(certs); ++i) {
X509 *cert = sk_X509_value(certs, i);
if ((cid = ESS_CERT_ID_new_init(cert, 1)) == NULL
|| !sk_ESS_CERT_ID_push(sc->cert_ids, cid))
goto err;
}
return sc;
err:
ESS_SIGNING_CERT_free(sc);
ESS_CERT_ID_free(cid);
ERR_raise(ERR_LIB_ESS, ERR_R_MALLOC_FAILURE);
return NULL;
}
static ESS_CERT_ID *ESS_CERT_ID_new_init(const X509 *cert,
int set_issuer_serial)
{
ESS_CERT_ID *cid = NULL;
GENERAL_NAME *name = NULL;
unsigned char cert_sha1[SHA_DIGEST_LENGTH];
if ((cid = ESS_CERT_ID_new()) == NULL)
goto err;
if (!X509_digest(cert, EVP_sha1(), cert_sha1, NULL))
goto err;
if (!ASN1_OCTET_STRING_set(cid->hash, cert_sha1, SHA_DIGEST_LENGTH))
goto err;
/* Setting the issuer/serial if requested. */
if (!set_issuer_serial)
return cid;
if (cid->issuer_serial == NULL
&& (cid->issuer_serial = ESS_ISSUER_SERIAL_new()) == NULL)
goto err;
if ((name = GENERAL_NAME_new()) == NULL)
goto err;
name->type = GEN_DIRNAME;
if ((name->d.dirn = X509_NAME_dup(X509_get_issuer_name(cert))) == NULL)
goto err;
if (!sk_GENERAL_NAME_push(cid->issuer_serial->issuer, name))
goto err;
name = NULL; /* Ownership is lost. */
ASN1_INTEGER_free(cid->issuer_serial->serial);
if ((cid->issuer_serial->serial =
ASN1_INTEGER_dup(X509_get0_serialNumber(cert))) == NULL)
goto err;
return cid;
err:
GENERAL_NAME_free(name);
ESS_CERT_ID_free(cid);
ERR_raise(ERR_LIB_ESS, ERR_R_MALLOC_FAILURE);
return NULL;
}
ESS_SIGNING_CERT_V2 *OSSL_ESS_signing_cert_v2_new_init(const EVP_MD *hash_alg,
const X509 *signcert,
const
STACK_OF(X509) *certs,
int set_issuer_serial)
{
ESS_CERT_ID_V2 *cid = NULL;
ESS_SIGNING_CERT_V2 *sc;
int i;
if ((sc = ESS_SIGNING_CERT_V2_new()) == NULL)
goto err;
cid = ESS_CERT_ID_V2_new_init(hash_alg, signcert, set_issuer_serial);
if (cid == NULL)
goto err;
if (!sk_ESS_CERT_ID_V2_push(sc->cert_ids, cid))
goto err;
cid = NULL;
for (i = 0; i < sk_X509_num(certs); ++i) {
X509 *cert = sk_X509_value(certs, i);
if ((cid = ESS_CERT_ID_V2_new_init(hash_alg, cert, 1)) == NULL)
goto err;
if (!sk_ESS_CERT_ID_V2_push(sc->cert_ids, cid))
goto err;
cid = NULL;
}
return sc;
err:
ESS_SIGNING_CERT_V2_free(sc);
ESS_CERT_ID_V2_free(cid);
ERR_raise(ERR_LIB_ESS, ERR_R_MALLOC_FAILURE);
return NULL;
}
static ESS_CERT_ID_V2 *ESS_CERT_ID_V2_new_init(const EVP_MD *hash_alg,
const X509 *cert,
int set_issuer_serial)
{
ESS_CERT_ID_V2 *cid;
GENERAL_NAME *name = NULL;
unsigned char hash[EVP_MAX_MD_SIZE];
unsigned int hash_len = sizeof(hash);
X509_ALGOR *alg = NULL;
memset(hash, 0, sizeof(hash));
if ((cid = ESS_CERT_ID_V2_new()) == NULL)
goto err;
if (!EVP_MD_is_a(hash_alg, SN_sha256)) {
alg = X509_ALGOR_new();
if (alg == NULL)
goto err;
X509_ALGOR_set_md(alg, hash_alg);
if (alg->algorithm == NULL)
goto err;
cid->hash_alg = alg;
alg = NULL;
} else {
cid->hash_alg = NULL;
}
if (!X509_digest(cert, hash_alg, hash, &hash_len))
goto err;
if (!ASN1_OCTET_STRING_set(cid->hash, hash, hash_len))
goto err;
if (!set_issuer_serial)
return cid;
if ((cid->issuer_serial = ESS_ISSUER_SERIAL_new()) == NULL)
goto err;
if ((name = GENERAL_NAME_new()) == NULL)
goto err;
name->type = GEN_DIRNAME;
if ((name->d.dirn = X509_NAME_dup(X509_get_issuer_name(cert))) == NULL)
goto err;
if (!sk_GENERAL_NAME_push(cid->issuer_serial->issuer, name))
goto err;
name = NULL; /* Ownership is lost. */
ASN1_INTEGER_free(cid->issuer_serial->serial);
cid->issuer_serial->serial = ASN1_INTEGER_dup(X509_get0_serialNumber(cert));
if (cid->issuer_serial->serial == NULL)
goto err;
return cid;
err:
X509_ALGOR_free(alg);
GENERAL_NAME_free(name);
ESS_CERT_ID_V2_free(cid);
ERR_raise(ERR_LIB_ESS, ERR_R_MALLOC_FAILURE);
return NULL;
}
static int ess_issuer_serial_cmp(const ESS_ISSUER_SERIAL *is, const X509 *cert)
{
GENERAL_NAME *issuer;
if (is == NULL || cert == NULL || sk_GENERAL_NAME_num(is->issuer) != 1)
return -1;
issuer = sk_GENERAL_NAME_value(is->issuer, 0);
if (issuer->type != GEN_DIRNAME
|| X509_NAME_cmp(issuer->d.dirn, X509_get_issuer_name(cert)) != 0)
return -1;
return ASN1_INTEGER_cmp(is->serial, X509_get0_serialNumber(cert));
}
/*
* Find the cert in |certs| referenced by |cid| if not NULL, else by |cid_v2|.
* The cert must be the first one in |certs| if and only if |index| is 0.
* Return 0 on not found, -1 on error, else 1 + the position in |certs|.
*/
static int find(const ESS_CERT_ID *cid, const ESS_CERT_ID_V2 *cid_v2,
int index, const STACK_OF(X509) *certs)
{
const X509 *cert;
EVP_MD *md = NULL;
char name[OSSL_MAX_NAME_SIZE];
unsigned char cert_digest[EVP_MAX_MD_SIZE];
unsigned int len, cid_hash_len;
const ESS_ISSUER_SERIAL *is;
int i;
int ret = -1;
if (cid == NULL && cid_v2 == NULL) {
ERR_raise(ERR_LIB_ESS, ERR_R_PASSED_INVALID_ARGUMENT);
return -1;
}
if (cid != NULL)
strcpy(name, "SHA1");
else if (cid_v2->hash_alg == NULL)
strcpy(name, "SHA256");
else
OBJ_obj2txt(name, sizeof(name), cid_v2->hash_alg->algorithm, 0);
(void)ERR_set_mark();
md = EVP_MD_fetch(NULL, name, NULL);
if (md == NULL)
md = (EVP_MD *)EVP_get_digestbyname(name);
if (md == NULL) {
(void)ERR_clear_last_mark();
ERR_raise(ERR_LIB_ESS, ESS_R_ESS_DIGEST_ALG_UNKNOWN);
goto end;
}
(void)ERR_pop_to_mark();
for (i = 0; i < sk_X509_num(certs); ++i) {
cert = sk_X509_value(certs, i);
cid_hash_len = cid != NULL ? cid->hash->length : cid_v2->hash->length;
if (!X509_digest(cert, md, cert_digest, &len)
|| cid_hash_len != len) {
ERR_raise(ERR_LIB_ESS, ESS_R_ESS_CERT_DIGEST_ERROR);
goto end;
}
if (memcmp(cid != NULL ? cid->hash->data : cid_v2->hash->data,
cert_digest, len) == 0) {
is = cid != NULL ? cid->issuer_serial : cid_v2->issuer_serial;
/* Well, it's not really required to match the serial numbers. */
if (is == NULL || ess_issuer_serial_cmp(is, cert) == 0) {
if ((i == 0) == (index == 0)) {
ret = i + 1;
goto end;
}
ERR_raise(ERR_LIB_ESS, ESS_R_ESS_CERT_ID_WRONG_ORDER);
goto end;
}
}
}
ret = 0;
ERR_raise(ERR_LIB_ESS, ESS_R_ESS_CERT_ID_NOT_FOUND);
end:
EVP_MD_free(md);
return ret;
}
int OSSL_ESS_check_signing_certs(const ESS_SIGNING_CERT *ss,
const ESS_SIGNING_CERT_V2 *ssv2,
const STACK_OF(X509) *chain,
int require_signing_cert)
{
int n_v1 = ss == NULL ? -1 : sk_ESS_CERT_ID_num(ss->cert_ids);
int n_v2 = ssv2 == NULL ? -1 : sk_ESS_CERT_ID_V2_num(ssv2->cert_ids);
int i, ret;
if (require_signing_cert && ss == NULL && ssv2 == NULL) {
- ERR_raise(ERR_LIB_CMS, ESS_R_MISSING_SIGNING_CERTIFICATE_ATTRIBUTE);
+ ERR_raise(ERR_LIB_ESS, ESS_R_MISSING_SIGNING_CERTIFICATE_ATTRIBUTE);
return -1;
}
if (n_v1 == 0 || n_v2 == 0) {
ERR_raise(ERR_LIB_ESS, ESS_R_EMPTY_ESS_CERT_ID_LIST);
return -1;
}
/* If both ss and ssv2 exist, as required evaluate them independently. */
for (i = 0; i < n_v1; i++) {
ret = find(sk_ESS_CERT_ID_value(ss->cert_ids, i), NULL, i, chain);
if (ret <= 0)
return ret;
}
for (i = 0; i < n_v2; i++) {
ret = find(NULL, sk_ESS_CERT_ID_V2_value(ssv2->cert_ids, i), i, chain);
if (ret <= 0)
return ret;
}
return 1;
}
diff --git a/crypto/openssl/crypto/evp/keymgmt_lib.c b/crypto/openssl/crypto/evp/keymgmt_lib.c
index 8369d9578cbd..9512cc9cf0f7 100644
--- a/crypto/openssl/crypto/evp/keymgmt_lib.c
+++ b/crypto/openssl/crypto/evp/keymgmt_lib.c
@@ -1,589 +1,594 @@
/*
- * Copyright 2019-2022 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2019-2024 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 <openssl/core_names.h>
#include "internal/cryptlib.h"
#include "internal/nelem.h"
#include "crypto/evp.h"
#include "internal/core.h"
#include "internal/provider.h"
#include "evp_local.h"
/*
* match_type() checks if two EVP_KEYMGMT are matching key types. This
* function assumes that the caller has made all the necessary NULL checks.
*/
static int match_type(const EVP_KEYMGMT *keymgmt1, const EVP_KEYMGMT *keymgmt2)
{
const char *name2 = EVP_KEYMGMT_get0_name(keymgmt2);
return EVP_KEYMGMT_is_a(keymgmt1, name2);
}
int evp_keymgmt_util_try_import(const OSSL_PARAM params[], void *arg)
{
struct evp_keymgmt_util_try_import_data_st *data = arg;
int delete_on_error = 0;
/* Just in time creation of keydata */
if (data->keydata == NULL) {
if ((data->keydata = evp_keymgmt_newdata(data->keymgmt)) == NULL) {
ERR_raise(ERR_LIB_EVP, ERR_R_MALLOC_FAILURE);
return 0;
}
delete_on_error = 1;
}
/*
* It's fine if there was no data to transfer, we just end up with an
* empty destination key.
*/
if (params[0].key == NULL)
return 1;
if (evp_keymgmt_import(data->keymgmt, data->keydata, data->selection,
params))
return 1;
if (delete_on_error) {
evp_keymgmt_freedata(data->keymgmt, data->keydata);
data->keydata = NULL;
}
return 0;
}
int evp_keymgmt_util_assign_pkey(EVP_PKEY *pkey, EVP_KEYMGMT *keymgmt,
void *keydata)
{
if (pkey == NULL || keymgmt == NULL || keydata == NULL
|| !EVP_PKEY_set_type_by_keymgmt(pkey, keymgmt)) {
ERR_raise(ERR_LIB_EVP, ERR_R_INTERNAL_ERROR);
return 0;
}
pkey->keydata = keydata;
evp_keymgmt_util_cache_keyinfo(pkey);
return 1;
}
EVP_PKEY *evp_keymgmt_util_make_pkey(EVP_KEYMGMT *keymgmt, void *keydata)
{
EVP_PKEY *pkey = NULL;
if (keymgmt == NULL
|| keydata == NULL
|| (pkey = EVP_PKEY_new()) == NULL
|| !evp_keymgmt_util_assign_pkey(pkey, keymgmt, keydata)) {
EVP_PKEY_free(pkey);
return NULL;
}
return pkey;
}
int evp_keymgmt_util_export(const EVP_PKEY *pk, int selection,
OSSL_CALLBACK *export_cb, void *export_cbarg)
{
if (pk == NULL || export_cb == NULL)
return 0;
return evp_keymgmt_export(pk->keymgmt, pk->keydata, selection,
export_cb, export_cbarg);
}
void *evp_keymgmt_util_export_to_provider(EVP_PKEY *pk, EVP_KEYMGMT *keymgmt,
int selection)
{
struct evp_keymgmt_util_try_import_data_st import_data;
OP_CACHE_ELEM *op;
/* Export to where? */
if (keymgmt == NULL)
return NULL;
/* If we have an unassigned key, give up */
if (pk->keydata == NULL)
return NULL;
/*
* If |keymgmt| matches the "origin" |keymgmt|, there is no more to do.
* The "origin" is determined by the |keymgmt| pointers being identical
* or when the provider and the name ID match. The latter case handles the
* situation where the fetch cache is flushed and a "new" key manager is
* created.
*/
if (pk->keymgmt == keymgmt
|| (pk->keymgmt->name_id == keymgmt->name_id
&& pk->keymgmt->prov == keymgmt->prov))
return pk->keydata;
if (!CRYPTO_THREAD_read_lock(pk->lock))
return NULL;
/*
* If the provider native "origin" hasn't changed since last time, we
* try to find our keymgmt in the operation cache. If it has changed
* and our keymgmt isn't found, we will clear the cache further down.
*/
if (pk->dirty_cnt == pk->dirty_cnt_copy) {
/* If this key is already exported to |keymgmt|, no more to do */
op = evp_keymgmt_util_find_operation_cache(pk, keymgmt, selection);
if (op != NULL && op->keymgmt != NULL) {
void *ret = op->keydata;
CRYPTO_THREAD_unlock(pk->lock);
return ret;
}
}
CRYPTO_THREAD_unlock(pk->lock);
/* If the "origin" |keymgmt| doesn't support exporting, give up */
if (pk->keymgmt->export == NULL)
return NULL;
/*
* Make sure that the type of the keymgmt to export to matches the type
* of the "origin"
*/
if (!ossl_assert(match_type(pk->keymgmt, keymgmt)))
return NULL;
/*
* We look at the already cached provider keys, and import from the
* first that supports it (i.e. use its export function), and export
* the imported data to the new provider.
*/
/* Setup for the export callback */
import_data.keydata = NULL; /* evp_keymgmt_util_try_import will create it */
import_data.keymgmt = keymgmt;
import_data.selection = selection;
/*
* The export function calls the callback (evp_keymgmt_util_try_import),
* which does the import for us. If successful, we're done.
*/
if (!evp_keymgmt_util_export(pk, selection,
&evp_keymgmt_util_try_import, &import_data))
/* If there was an error, bail out */
return NULL;
if (!CRYPTO_THREAD_write_lock(pk->lock)) {
evp_keymgmt_freedata(keymgmt, import_data.keydata);
return NULL;
}
/* Check to make sure some other thread didn't get there first */
op = evp_keymgmt_util_find_operation_cache(pk, keymgmt, selection);
if (op != NULL && op->keydata != NULL) {
void *ret = op->keydata;
CRYPTO_THREAD_unlock(pk->lock);
/*
* Another thread seemms to have already exported this so we abandon
* all the work we just did.
*/
evp_keymgmt_freedata(keymgmt, import_data.keydata);
return ret;
}
/*
* If the dirty counter changed since last time, then clear the
* operation cache. In that case, we know that |i| is zero.
*/
if (pk->dirty_cnt != pk->dirty_cnt_copy)
evp_keymgmt_util_clear_operation_cache(pk, 0);
/* Add the new export to the operation cache */
if (!evp_keymgmt_util_cache_keydata(pk, keymgmt, import_data.keydata,
selection)) {
CRYPTO_THREAD_unlock(pk->lock);
evp_keymgmt_freedata(keymgmt, import_data.keydata);
return NULL;
}
/* Synchronize the dirty count */
pk->dirty_cnt_copy = pk->dirty_cnt;
CRYPTO_THREAD_unlock(pk->lock);
return import_data.keydata;
}
static void op_cache_free(OP_CACHE_ELEM *e)
{
evp_keymgmt_freedata(e->keymgmt, e->keydata);
EVP_KEYMGMT_free(e->keymgmt);
OPENSSL_free(e);
}
int evp_keymgmt_util_clear_operation_cache(EVP_PKEY *pk, int locking)
{
if (pk != NULL) {
if (locking && pk->lock != NULL && !CRYPTO_THREAD_write_lock(pk->lock))
return 0;
sk_OP_CACHE_ELEM_pop_free(pk->operation_cache, op_cache_free);
pk->operation_cache = NULL;
if (locking && pk->lock != NULL)
CRYPTO_THREAD_unlock(pk->lock);
}
return 1;
}
OP_CACHE_ELEM *evp_keymgmt_util_find_operation_cache(EVP_PKEY *pk,
EVP_KEYMGMT *keymgmt,
int selection)
{
int i, end = sk_OP_CACHE_ELEM_num(pk->operation_cache);
OP_CACHE_ELEM *p;
/*
* A comparison and sk_P_CACHE_ELEM_find() are avoided to not cause
* problems when we've only a read lock.
+ * A keymgmt is a match if the |keymgmt| pointers are identical or if the
+ * provider and the name ID match
*/
for (i = 0; i < end; i++) {
p = sk_OP_CACHE_ELEM_value(pk->operation_cache, i);
- if (keymgmt == p->keymgmt && (p->selection & selection) == selection)
+ if ((p->selection & selection) == selection
+ && (keymgmt == p->keymgmt
+ || (keymgmt->name_id == p->keymgmt->name_id
+ && keymgmt->prov == p->keymgmt->prov)))
return p;
}
return NULL;
}
int evp_keymgmt_util_cache_keydata(EVP_PKEY *pk, EVP_KEYMGMT *keymgmt,
void *keydata, int selection)
{
OP_CACHE_ELEM *p = NULL;
if (keydata != NULL) {
if (pk->operation_cache == NULL) {
pk->operation_cache = sk_OP_CACHE_ELEM_new_null();
if (pk->operation_cache == NULL)
return 0;
}
p = OPENSSL_malloc(sizeof(*p));
if (p == NULL)
return 0;
p->keydata = keydata;
p->keymgmt = keymgmt;
p->selection = selection;
if (!EVP_KEYMGMT_up_ref(keymgmt)) {
OPENSSL_free(p);
return 0;
}
if (!sk_OP_CACHE_ELEM_push(pk->operation_cache, p)) {
EVP_KEYMGMT_free(keymgmt);
OPENSSL_free(p);
return 0;
}
}
return 1;
}
void evp_keymgmt_util_cache_keyinfo(EVP_PKEY *pk)
{
/*
* Cache information about the provider "origin" key.
*
* This services functions like EVP_PKEY_get_size, EVP_PKEY_get_bits, etc
*/
if (pk->keydata != NULL) {
int bits = 0;
int security_bits = 0;
int size = 0;
OSSL_PARAM params[4];
params[0] = OSSL_PARAM_construct_int(OSSL_PKEY_PARAM_BITS, &bits);
params[1] = OSSL_PARAM_construct_int(OSSL_PKEY_PARAM_SECURITY_BITS,
&security_bits);
params[2] = OSSL_PARAM_construct_int(OSSL_PKEY_PARAM_MAX_SIZE, &size);
params[3] = OSSL_PARAM_construct_end();
if (evp_keymgmt_get_params(pk->keymgmt, pk->keydata, params)) {
pk->cache.size = size;
pk->cache.bits = bits;
pk->cache.security_bits = security_bits;
}
}
}
void *evp_keymgmt_util_fromdata(EVP_PKEY *target, EVP_KEYMGMT *keymgmt,
int selection, const OSSL_PARAM params[])
{
void *keydata = NULL;
if ((keydata = evp_keymgmt_newdata(keymgmt)) == NULL
|| !evp_keymgmt_import(keymgmt, keydata, selection, params)
|| !evp_keymgmt_util_assign_pkey(target, keymgmt, keydata)) {
evp_keymgmt_freedata(keymgmt, keydata);
keydata = NULL;
}
return keydata;
}
int evp_keymgmt_util_has(EVP_PKEY *pk, int selection)
{
/* Check if key is even assigned */
if (pk->keymgmt == NULL)
return 0;
return evp_keymgmt_has(pk->keymgmt, pk->keydata, selection);
}
/*
* evp_keymgmt_util_match() doesn't just look at the provider side "origin",
* but also in the operation cache to see if there's any common keymgmt that
* supplies OP_keymgmt_match.
*
* evp_keymgmt_util_match() adheres to the return values that EVP_PKEY_eq()
* and EVP_PKEY_parameters_eq() return, i.e.:
*
* 1 same key
* 0 not same key
* -1 not same key type
* -2 unsupported operation
*/
int evp_keymgmt_util_match(EVP_PKEY *pk1, EVP_PKEY *pk2, int selection)
{
EVP_KEYMGMT *keymgmt1 = NULL, *keymgmt2 = NULL;
void *keydata1 = NULL, *keydata2 = NULL;
if (pk1 == NULL || pk2 == NULL) {
if (pk1 == NULL && pk2 == NULL)
return 1;
return 0;
}
keymgmt1 = pk1->keymgmt;
keydata1 = pk1->keydata;
keymgmt2 = pk2->keymgmt;
keydata2 = pk2->keydata;
if (keymgmt1 != keymgmt2) {
/*
* The condition for a successful cross export is that the
* keydata to be exported is NULL (typed, but otherwise empty
* EVP_PKEY), or that it was possible to export it with
* evp_keymgmt_util_export_to_provider().
*
* We use |ok| to determine if it's ok to cross export one way,
* but also to determine if we should attempt a cross export
* the other way. There's no point doing it both ways.
*/
int ok = 0;
/* Complex case, where the keymgmt differ */
if (keymgmt1 != NULL
&& keymgmt2 != NULL
&& !match_type(keymgmt1, keymgmt2)) {
ERR_raise(ERR_LIB_EVP, EVP_R_DIFFERENT_KEY_TYPES);
return -1; /* Not the same type */
}
/*
* The key types are determined to match, so we try cross export,
* but only to keymgmt's that supply a matching function.
*/
if (keymgmt2 != NULL
&& keymgmt2->match != NULL) {
void *tmp_keydata = NULL;
ok = 1;
if (keydata1 != NULL) {
tmp_keydata =
evp_keymgmt_util_export_to_provider(pk1, keymgmt2,
selection);
ok = (tmp_keydata != NULL);
}
if (ok) {
keymgmt1 = keymgmt2;
keydata1 = tmp_keydata;
}
}
/*
* If we've successfully cross exported one way, there's no point
* doing it the other way, hence the |!ok| check.
*/
if (!ok
&& keymgmt1 != NULL
&& keymgmt1->match != NULL) {
void *tmp_keydata = NULL;
ok = 1;
if (keydata2 != NULL) {
tmp_keydata =
evp_keymgmt_util_export_to_provider(pk2, keymgmt1,
selection);
ok = (tmp_keydata != NULL);
}
if (ok) {
keymgmt2 = keymgmt1;
keydata2 = tmp_keydata;
}
}
}
/* If we still don't have matching keymgmt implementations, we give up */
if (keymgmt1 != keymgmt2)
return -2;
/* If both keydata are NULL, then they're the same key */
if (keydata1 == NULL && keydata2 == NULL)
return 1;
/* If only one of the keydata is NULL, then they're different keys */
if (keydata1 == NULL || keydata2 == NULL)
return 0;
/* If both keydata are non-NULL, we let the backend decide */
return evp_keymgmt_match(keymgmt1, keydata1, keydata2, selection);
}
int evp_keymgmt_util_copy(EVP_PKEY *to, EVP_PKEY *from, int selection)
{
/* Save copies of pointers we want to play with without affecting |to| */
EVP_KEYMGMT *to_keymgmt = to->keymgmt;
void *to_keydata = to->keydata, *alloc_keydata = NULL;
/* An unassigned key can't be copied */
if (from == NULL || from->keydata == NULL)
return 0;
/*
* If |to| is unassigned, ensure it gets the same KEYMGMT as |from|,
* Note that the final setting of KEYMGMT is done further down, with
* EVP_PKEY_set_type_by_keymgmt(); we don't want to do that prematurely.
*/
if (to_keymgmt == NULL)
to_keymgmt = from->keymgmt;
if (to_keymgmt == from->keymgmt && to_keymgmt->dup != NULL
&& to_keydata == NULL) {
to_keydata = alloc_keydata = evp_keymgmt_dup(to_keymgmt,
from->keydata,
selection);
if (to_keydata == NULL)
return 0;
} else if (match_type(to_keymgmt, from->keymgmt)) {
struct evp_keymgmt_util_try_import_data_st import_data;
import_data.keymgmt = to_keymgmt;
import_data.keydata = to_keydata;
import_data.selection = selection;
if (!evp_keymgmt_util_export(from, selection,
&evp_keymgmt_util_try_import,
&import_data))
return 0;
/*
* In case to_keydata was previously unallocated,
* evp_keymgmt_util_try_import() may have created it for us.
*/
if (to_keydata == NULL)
to_keydata = alloc_keydata = import_data.keydata;
} else {
ERR_raise(ERR_LIB_EVP, EVP_R_DIFFERENT_KEY_TYPES);
return 0;
}
/*
* We only need to set the |to| type when its |keymgmt| isn't set.
* We can then just set its |keydata| to what we have, which might
* be exactly what it had when entering this function.
* This is a bit different from using evp_keymgmt_util_assign_pkey(),
* which isn't as careful with |to|'s original |keymgmt|, since it's
* meant to forcibly reassign an EVP_PKEY no matter what, which is
* why we don't use that one here.
*/
if (to->keymgmt == NULL
&& !EVP_PKEY_set_type_by_keymgmt(to, to_keymgmt)) {
evp_keymgmt_freedata(to_keymgmt, alloc_keydata);
return 0;
}
to->keydata = to_keydata;
evp_keymgmt_util_cache_keyinfo(to);
return 1;
}
void *evp_keymgmt_util_gen(EVP_PKEY *target, EVP_KEYMGMT *keymgmt,
void *genctx, OSSL_CALLBACK *cb, void *cbarg)
{
void *keydata = NULL;
if ((keydata = evp_keymgmt_gen(keymgmt, genctx, cb, cbarg)) == NULL
|| !evp_keymgmt_util_assign_pkey(target, keymgmt, keydata)) {
evp_keymgmt_freedata(keymgmt, keydata);
keydata = NULL;
}
return keydata;
}
/*
* Returns the same numbers as EVP_PKEY_get_default_digest_name()
* When the string from the EVP_KEYMGMT implementation is "", we use
* SN_undef, since that corresponds to what EVP_PKEY_get_default_nid()
* returns for no digest.
*/
int evp_keymgmt_util_get_deflt_digest_name(EVP_KEYMGMT *keymgmt,
void *keydata,
char *mdname, size_t mdname_sz)
{
OSSL_PARAM params[3];
char mddefault[100] = "";
char mdmandatory[100] = "";
char *result = NULL;
int rv = -2;
params[0] =
OSSL_PARAM_construct_utf8_string(OSSL_PKEY_PARAM_DEFAULT_DIGEST,
mddefault, sizeof(mddefault));
params[1] =
OSSL_PARAM_construct_utf8_string(OSSL_PKEY_PARAM_MANDATORY_DIGEST,
mdmandatory,
sizeof(mdmandatory));
params[2] = OSSL_PARAM_construct_end();
if (!evp_keymgmt_get_params(keymgmt, keydata, params))
return 0;
if (OSSL_PARAM_modified(params + 1)) {
if (params[1].return_size <= 1) /* Only a NUL byte */
result = SN_undef;
else
result = mdmandatory;
rv = 2;
} else if (OSSL_PARAM_modified(params)) {
if (params[0].return_size <= 1) /* Only a NUL byte */
result = SN_undef;
else
result = mddefault;
rv = 1;
}
if (rv > 0)
OPENSSL_strlcpy(mdname, result, mdname_sz);
return rv;
}
/*
* If |keymgmt| has the method function |query_operation_name|, use it to get
* the name of a supported operation identity. Otherwise, return the keytype,
* assuming that it works as a default operation name.
*/
const char *evp_keymgmt_util_query_operation_name(EVP_KEYMGMT *keymgmt,
int op_id)
{
const char *name = NULL;
if (keymgmt != NULL) {
if (keymgmt->query_operation_name != NULL)
name = keymgmt->query_operation_name(op_id);
if (name == NULL)
name = EVP_KEYMGMT_get0_name(keymgmt);
}
return name;
}
diff --git a/crypto/openssl/crypto/evp/p_lib.c b/crypto/openssl/crypto/evp/p_lib.c
index 04b148a91218..6ff7eb7e02cf 100644
--- a/crypto/openssl/crypto/evp/p_lib.c
+++ b/crypto/openssl/crypto/evp/p_lib.c
@@ -1,2476 +1,2484 @@
/*
- * Copyright 1995-2023 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 1995-2024 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 <assert.h>
#include <stdio.h>
#include "internal/cryptlib.h"
#include "internal/refcount.h"
#include "internal/namemap.h"
#include <openssl/bn.h>
#include <openssl/err.h>
#include <openssl/objects.h>
#include <openssl/evp.h>
#include <openssl/rsa.h>
#include <openssl/dsa.h>
#include <openssl/dh.h>
#include <openssl/ec.h>
#include <openssl/cmac.h>
#ifndef FIPS_MODULE
# include <openssl/engine.h>
#endif
#include <openssl/params.h>
#include <openssl/param_build.h>
#include <openssl/encoder.h>
#include <openssl/core_names.h>
#include "internal/numbers.h" /* includes SIZE_MAX */
#include "internal/ffc.h"
#include "crypto/evp.h"
#include "crypto/dh.h"
#include "crypto/dsa.h"
#include "crypto/ec.h"
#include "crypto/ecx.h"
#include "crypto/rsa.h"
#ifndef FIPS_MODULE
# include "crypto/asn1.h"
# include "crypto/x509.h"
#endif
#include "internal/provider.h"
#include "evp_local.h"
static int pkey_set_type(EVP_PKEY *pkey, ENGINE *e, int type, const char *str,
int len, EVP_KEYMGMT *keymgmt);
static void evp_pkey_free_it(EVP_PKEY *key);
#ifndef FIPS_MODULE
/* The type of parameters selected in key parameter functions */
# define SELECT_PARAMETERS OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS
int EVP_PKEY_get_bits(const EVP_PKEY *pkey)
{
int size = 0;
if (pkey != NULL) {
size = pkey->cache.bits;
if (pkey->ameth != NULL && pkey->ameth->pkey_bits != NULL)
size = pkey->ameth->pkey_bits(pkey);
}
return size < 0 ? 0 : size;
}
int EVP_PKEY_get_security_bits(const EVP_PKEY *pkey)
{
int size = 0;
if (pkey != NULL) {
size = pkey->cache.security_bits;
if (pkey->ameth != NULL && pkey->ameth->pkey_security_bits != NULL)
size = pkey->ameth->pkey_security_bits(pkey);
}
return size < 0 ? 0 : size;
}
int EVP_PKEY_save_parameters(EVP_PKEY *pkey, int mode)
{
# ifndef OPENSSL_NO_DSA
if (pkey->type == EVP_PKEY_DSA) {
int ret = pkey->save_parameters;
if (mode >= 0)
pkey->save_parameters = mode;
return ret;
}
# endif
# ifndef OPENSSL_NO_EC
if (pkey->type == EVP_PKEY_EC) {
int ret = pkey->save_parameters;
if (mode >= 0)
pkey->save_parameters = mode;
return ret;
}
# endif
return 0;
}
int EVP_PKEY_set_ex_data(EVP_PKEY *key, int idx, void *arg)
{
return CRYPTO_set_ex_data(&key->ex_data, idx, arg);
}
void *EVP_PKEY_get_ex_data(const EVP_PKEY *key, int idx)
{
return CRYPTO_get_ex_data(&key->ex_data, idx);
}
int EVP_PKEY_copy_parameters(EVP_PKEY *to, const EVP_PKEY *from)
{
/*
* Clean up legacy stuff from this function when legacy support is gone.
*/
EVP_PKEY *downgraded_from = NULL;
int ok = 0;
/*
* If |to| is a legacy key and |from| isn't, we must make a downgraded
* copy of |from|. If that fails, this function fails.
*/
if (evp_pkey_is_legacy(to) && evp_pkey_is_provided(from)) {
if (!evp_pkey_copy_downgraded(&downgraded_from, from))
goto end;
from = downgraded_from;
}
/*
* Make sure |to| is typed. Content is less important at this early
* stage.
*
* 1. If |to| is untyped, assign |from|'s key type to it.
* 2. If |to| contains a legacy key, compare its |type| to |from|'s.
* (|from| was already downgraded above)
*
* If |to| is a provided key, there's nothing more to do here, functions
* like evp_keymgmt_util_copy() and evp_pkey_export_to_provider() called
* further down help us find out if they are the same or not.
*/
if (evp_pkey_is_blank(to)) {
if (evp_pkey_is_legacy(from)) {
if (EVP_PKEY_set_type(to, from->type) == 0)
goto end;
} else {
if (EVP_PKEY_set_type_by_keymgmt(to, from->keymgmt) == 0)
goto end;
}
} else if (evp_pkey_is_legacy(to)) {
if (to->type != from->type) {
ERR_raise(ERR_LIB_EVP, EVP_R_DIFFERENT_KEY_TYPES);
goto end;
}
}
if (EVP_PKEY_missing_parameters(from)) {
ERR_raise(ERR_LIB_EVP, EVP_R_MISSING_PARAMETERS);
goto end;
}
if (!EVP_PKEY_missing_parameters(to)) {
if (EVP_PKEY_parameters_eq(to, from) == 1)
ok = 1;
else
ERR_raise(ERR_LIB_EVP, EVP_R_DIFFERENT_PARAMETERS);
goto end;
}
/* For purely provided keys, we just call the keymgmt utility */
if (to->keymgmt != NULL && from->keymgmt != NULL) {
ok = evp_keymgmt_util_copy(to, (EVP_PKEY *)from, SELECT_PARAMETERS);
goto end;
}
/*
* If |to| is provided, we know that |from| is legacy at this point.
* Try exporting |from| to |to|'s keymgmt, then use evp_keymgmt_dup()
* to copy the appropriate data to |to|'s keydata.
* We cannot override existing data so do it only if there is no keydata
* in |to| yet.
*/
if (to->keymgmt != NULL && to->keydata == NULL) {
EVP_KEYMGMT *to_keymgmt = to->keymgmt;
void *from_keydata =
evp_pkey_export_to_provider((EVP_PKEY *)from, NULL, &to_keymgmt,
NULL);
/*
* If we get a NULL, it could be an internal error, or it could be
* that there's a key mismatch. We're pretending the latter...
*/
if (from_keydata == NULL)
ERR_raise(ERR_LIB_EVP, EVP_R_DIFFERENT_KEY_TYPES);
else
ok = (to->keydata = evp_keymgmt_dup(to->keymgmt,
from_keydata,
SELECT_PARAMETERS)) != NULL;
goto end;
}
/* Both keys are legacy */
if (from->ameth != NULL && from->ameth->param_copy != NULL)
ok = from->ameth->param_copy(to, from);
end:
EVP_PKEY_free(downgraded_from);
return ok;
}
int EVP_PKEY_missing_parameters(const EVP_PKEY *pkey)
{
if (pkey != NULL) {
if (pkey->keymgmt != NULL)
return !evp_keymgmt_util_has((EVP_PKEY *)pkey, SELECT_PARAMETERS);
else if (pkey->ameth != NULL && pkey->ameth->param_missing != NULL)
return pkey->ameth->param_missing(pkey);
}
return 0;
}
/*
* This function is called for any mixture of keys except pure legacy pair.
* When legacy keys are gone, we replace a call to this functions with
* a call to evp_keymgmt_util_match().
*/
static int evp_pkey_cmp_any(const EVP_PKEY *a, const EVP_PKEY *b,
int selection)
{
EVP_KEYMGMT *keymgmt1 = NULL, *keymgmt2 = NULL;
void *keydata1 = NULL, *keydata2 = NULL, *tmp_keydata = NULL;
/* If none of them are provided, this function shouldn't have been called */
if (!ossl_assert(evp_pkey_is_provided(a) || evp_pkey_is_provided(b)))
return -2;
/* For purely provided keys, we just call the keymgmt utility */
if (evp_pkey_is_provided(a) && evp_pkey_is_provided(b))
return evp_keymgmt_util_match((EVP_PKEY *)a, (EVP_PKEY *)b, selection);
/*
* At this point, one of them is provided, the other not. This allows
* us to compare types using legacy NIDs.
*/
if (evp_pkey_is_legacy(a)
&& !EVP_KEYMGMT_is_a(b->keymgmt, OBJ_nid2sn(a->type)))
return -1; /* not the same key type */
if (evp_pkey_is_legacy(b)
&& !EVP_KEYMGMT_is_a(a->keymgmt, OBJ_nid2sn(b->type)))
return -1; /* not the same key type */
/*
* We've determined that they both are the same keytype, so the next
* step is to do a bit of cross export to ensure we have keydata for
* both keys in the same keymgmt.
*/
keymgmt1 = a->keymgmt;
keydata1 = a->keydata;
keymgmt2 = b->keymgmt;
keydata2 = b->keydata;
if (keymgmt2 != NULL && keymgmt2->match != NULL) {
tmp_keydata =
evp_pkey_export_to_provider((EVP_PKEY *)a, NULL, &keymgmt2, NULL);
if (tmp_keydata != NULL) {
keymgmt1 = keymgmt2;
keydata1 = tmp_keydata;
}
}
if (tmp_keydata == NULL && keymgmt1 != NULL && keymgmt1->match != NULL) {
tmp_keydata =
evp_pkey_export_to_provider((EVP_PKEY *)b, NULL, &keymgmt1, NULL);
if (tmp_keydata != NULL) {
keymgmt2 = keymgmt1;
keydata2 = tmp_keydata;
}
}
/* If we still don't have matching keymgmt implementations, we give up */
if (keymgmt1 != keymgmt2)
return -2;
/* If the keymgmt implementations are NULL, the export failed */
if (keymgmt1 == NULL)
return -2;
return evp_keymgmt_match(keymgmt1, keydata1, keydata2, selection);
}
# ifndef OPENSSL_NO_DEPRECATED_3_0
int EVP_PKEY_cmp_parameters(const EVP_PKEY *a, const EVP_PKEY *b)
{
return EVP_PKEY_parameters_eq(a, b);
}
#endif
int EVP_PKEY_parameters_eq(const EVP_PKEY *a, const EVP_PKEY *b)
{
/*
* This will just call evp_keymgmt_util_match when legacy support
* is gone.
*/
if (a->keymgmt != NULL || b->keymgmt != NULL)
return evp_pkey_cmp_any(a, b, SELECT_PARAMETERS);
/* All legacy keys */
if (a->type != b->type)
return -1;
if (a->ameth != NULL && a->ameth->param_cmp != NULL)
return a->ameth->param_cmp(a, b);
return -2;
}
# ifndef OPENSSL_NO_DEPRECATED_3_0
int EVP_PKEY_cmp(const EVP_PKEY *a, const EVP_PKEY *b)
{
return EVP_PKEY_eq(a, b);
}
#endif
int EVP_PKEY_eq(const EVP_PKEY *a, const EVP_PKEY *b)
{
/*
* This will just call evp_keymgmt_util_match when legacy support
* is gone.
*/
/* Trivial shortcuts */
if (a == b)
return 1;
if (a == NULL || b == NULL)
return 0;
if (a->keymgmt != NULL || b->keymgmt != NULL) {
int selection = SELECT_PARAMETERS;
if (evp_keymgmt_util_has((EVP_PKEY *)a, OSSL_KEYMGMT_SELECT_PUBLIC_KEY)
&& evp_keymgmt_util_has((EVP_PKEY *)b, OSSL_KEYMGMT_SELECT_PUBLIC_KEY))
selection |= OSSL_KEYMGMT_SELECT_PUBLIC_KEY;
else
selection |= OSSL_KEYMGMT_SELECT_KEYPAIR;
return evp_pkey_cmp_any(a, b, selection);
}
/* All legacy keys */
if (a->type != b->type)
return -1;
if (a->ameth != NULL) {
int ret;
/* Compare parameters if the algorithm has them */
if (a->ameth->param_cmp != NULL) {
ret = a->ameth->param_cmp(a, b);
if (ret <= 0)
return ret;
}
if (a->ameth->pub_cmp != NULL)
return a->ameth->pub_cmp(a, b);
}
return -2;
}
static EVP_PKEY *new_raw_key_int(OSSL_LIB_CTX *libctx,
const char *strtype,
const char *propq,
int nidtype,
ENGINE *e,
const unsigned char *key,
size_t len,
int key_is_priv)
{
EVP_PKEY *pkey = NULL;
EVP_PKEY_CTX *ctx = NULL;
const EVP_PKEY_ASN1_METHOD *ameth = NULL;
int result = 0;
# ifndef OPENSSL_NO_ENGINE
/* Check if there is an Engine for this type */
if (e == NULL) {
ENGINE *tmpe = NULL;
if (strtype != NULL)
ameth = EVP_PKEY_asn1_find_str(&tmpe, strtype, -1);
else if (nidtype != EVP_PKEY_NONE)
ameth = EVP_PKEY_asn1_find(&tmpe, nidtype);
/* If tmpe is NULL then no engine is claiming to support this type */
if (tmpe == NULL)
ameth = NULL;
ENGINE_finish(tmpe);
}
# endif
if (e == NULL && ameth == NULL) {
/*
* No engine is claiming to support this type, so lets see if we have
* a provider.
*/
ctx = EVP_PKEY_CTX_new_from_name(libctx,
strtype != NULL ? strtype
: OBJ_nid2sn(nidtype),
propq);
if (ctx == NULL)
goto err;
/* May fail if no provider available */
ERR_set_mark();
if (EVP_PKEY_fromdata_init(ctx) == 1) {
OSSL_PARAM params[] = { OSSL_PARAM_END, OSSL_PARAM_END };
ERR_clear_last_mark();
params[0] = OSSL_PARAM_construct_octet_string(
key_is_priv ? OSSL_PKEY_PARAM_PRIV_KEY
: OSSL_PKEY_PARAM_PUB_KEY,
(void *)key, len);
if (EVP_PKEY_fromdata(ctx, &pkey, EVP_PKEY_KEYPAIR, params) != 1) {
ERR_raise(ERR_LIB_EVP, EVP_R_KEY_SETUP_FAILED);
goto err;
}
EVP_PKEY_CTX_free(ctx);
return pkey;
}
ERR_pop_to_mark();
/* else not supported so fallback to legacy */
}
/* Legacy code path */
pkey = EVP_PKEY_new();
if (pkey == NULL) {
ERR_raise(ERR_LIB_EVP, ERR_R_MALLOC_FAILURE);
goto err;
}
if (!pkey_set_type(pkey, e, nidtype, strtype, -1, NULL)) {
/* EVPerr already called */
goto err;
}
if (!ossl_assert(pkey->ameth != NULL))
goto err;
if (key_is_priv) {
if (pkey->ameth->set_priv_key == NULL) {
ERR_raise(ERR_LIB_EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE);
goto err;
}
if (!pkey->ameth->set_priv_key(pkey, key, len)) {
ERR_raise(ERR_LIB_EVP, EVP_R_KEY_SETUP_FAILED);
goto err;
}
} else {
if (pkey->ameth->set_pub_key == NULL) {
ERR_raise(ERR_LIB_EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE);
goto err;
}
if (!pkey->ameth->set_pub_key(pkey, key, len)) {
ERR_raise(ERR_LIB_EVP, EVP_R_KEY_SETUP_FAILED);
goto err;
}
}
result = 1;
err:
if (!result) {
EVP_PKEY_free(pkey);
pkey = NULL;
}
EVP_PKEY_CTX_free(ctx);
return pkey;
}
EVP_PKEY *EVP_PKEY_new_raw_private_key_ex(OSSL_LIB_CTX *libctx,
const char *keytype,
const char *propq,
const unsigned char *priv, size_t len)
{
return new_raw_key_int(libctx, keytype, propq, EVP_PKEY_NONE, NULL, priv,
len, 1);
}
EVP_PKEY *EVP_PKEY_new_raw_private_key(int type, ENGINE *e,
const unsigned char *priv,
size_t len)
{
return new_raw_key_int(NULL, NULL, NULL, type, e, priv, len, 1);
}
EVP_PKEY *EVP_PKEY_new_raw_public_key_ex(OSSL_LIB_CTX *libctx,
const char *keytype, const char *propq,
const unsigned char *pub, size_t len)
{
return new_raw_key_int(libctx, keytype, propq, EVP_PKEY_NONE, NULL, pub,
len, 0);
}
EVP_PKEY *EVP_PKEY_new_raw_public_key(int type, ENGINE *e,
const unsigned char *pub,
size_t len)
{
return new_raw_key_int(NULL, NULL, NULL, type, e, pub, len, 0);
}
struct raw_key_details_st
{
unsigned char **key;
size_t *len;
int selection;
};
static OSSL_CALLBACK get_raw_key_details;
static int get_raw_key_details(const OSSL_PARAM params[], void *arg)
{
const OSSL_PARAM *p = NULL;
struct raw_key_details_st *raw_key = arg;
if (raw_key->selection == OSSL_KEYMGMT_SELECT_PRIVATE_KEY) {
if ((p = OSSL_PARAM_locate_const(params, OSSL_PKEY_PARAM_PRIV_KEY))
!= NULL)
return OSSL_PARAM_get_octet_string(p, (void **)raw_key->key,
raw_key->key == NULL ? 0 : *raw_key->len,
raw_key->len);
} else if (raw_key->selection == OSSL_KEYMGMT_SELECT_PUBLIC_KEY) {
if ((p = OSSL_PARAM_locate_const(params, OSSL_PKEY_PARAM_PUB_KEY))
!= NULL)
return OSSL_PARAM_get_octet_string(p, (void **)raw_key->key,
raw_key->key == NULL ? 0 : *raw_key->len,
raw_key->len);
}
return 0;
}
int EVP_PKEY_get_raw_private_key(const EVP_PKEY *pkey, unsigned char *priv,
size_t *len)
{
if (pkey->keymgmt != NULL) {
struct raw_key_details_st raw_key;
raw_key.key = priv == NULL ? NULL : &priv;
raw_key.len = len;
raw_key.selection = OSSL_KEYMGMT_SELECT_PRIVATE_KEY;
return evp_keymgmt_util_export(pkey, OSSL_KEYMGMT_SELECT_PRIVATE_KEY,
get_raw_key_details, &raw_key);
}
if (pkey->ameth == NULL) {
ERR_raise(ERR_LIB_EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE);
return 0;
}
if (pkey->ameth->get_priv_key == NULL) {
ERR_raise(ERR_LIB_EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE);
return 0;
}
if (!pkey->ameth->get_priv_key(pkey, priv, len)) {
ERR_raise(ERR_LIB_EVP, EVP_R_GET_RAW_KEY_FAILED);
return 0;
}
return 1;
}
int EVP_PKEY_get_raw_public_key(const EVP_PKEY *pkey, unsigned char *pub,
size_t *len)
{
if (pkey->keymgmt != NULL) {
struct raw_key_details_st raw_key;
raw_key.key = pub == NULL ? NULL : &pub;
raw_key.len = len;
raw_key.selection = OSSL_KEYMGMT_SELECT_PUBLIC_KEY;
return evp_keymgmt_util_export(pkey, OSSL_KEYMGMT_SELECT_PUBLIC_KEY,
get_raw_key_details, &raw_key);
}
if (pkey->ameth == NULL) {
ERR_raise(ERR_LIB_EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE);
return 0;
}
if (pkey->ameth->get_pub_key == NULL) {
ERR_raise(ERR_LIB_EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE);
return 0;
}
if (!pkey->ameth->get_pub_key(pkey, pub, len)) {
ERR_raise(ERR_LIB_EVP, EVP_R_GET_RAW_KEY_FAILED);
return 0;
}
return 1;
}
static EVP_PKEY *new_cmac_key_int(const unsigned char *priv, size_t len,
const char *cipher_name,
const EVP_CIPHER *cipher,
OSSL_LIB_CTX *libctx,
const char *propq, ENGINE *e)
{
# ifndef OPENSSL_NO_CMAC
# ifndef OPENSSL_NO_ENGINE
const char *engine_id = e != NULL ? ENGINE_get_id(e) : NULL;
# endif
OSSL_PARAM params[5], *p = params;
EVP_PKEY *pkey = NULL;
EVP_PKEY_CTX *ctx;
if (cipher != NULL)
cipher_name = EVP_CIPHER_get0_name(cipher);
if (cipher_name == NULL) {
ERR_raise(ERR_LIB_EVP, EVP_R_KEY_SETUP_FAILED);
return NULL;
}
ctx = EVP_PKEY_CTX_new_from_name(libctx, "CMAC", propq);
if (ctx == NULL)
goto err;
if (EVP_PKEY_fromdata_init(ctx) <= 0) {
ERR_raise(ERR_LIB_EVP, EVP_R_KEY_SETUP_FAILED);
goto err;
}
*p++ = OSSL_PARAM_construct_octet_string(OSSL_PKEY_PARAM_PRIV_KEY,
(void *)priv, len);
*p++ = OSSL_PARAM_construct_utf8_string(OSSL_PKEY_PARAM_CIPHER,
(char *)cipher_name, 0);
if (propq != NULL)
*p++ = OSSL_PARAM_construct_utf8_string(OSSL_PKEY_PARAM_PROPERTIES,
(char *)propq, 0);
# ifndef OPENSSL_NO_ENGINE
if (engine_id != NULL)
*p++ = OSSL_PARAM_construct_utf8_string(OSSL_PKEY_PARAM_ENGINE,
(char *)engine_id, 0);
# endif
*p = OSSL_PARAM_construct_end();
if (EVP_PKEY_fromdata(ctx, &pkey, EVP_PKEY_KEYPAIR, params) <= 0) {
ERR_raise(ERR_LIB_EVP, EVP_R_KEY_SETUP_FAILED);
goto err;
}
err:
EVP_PKEY_CTX_free(ctx);
return pkey;
# else
ERR_raise(ERR_LIB_EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE);
return NULL;
# endif
}
EVP_PKEY *EVP_PKEY_new_CMAC_key(ENGINE *e, const unsigned char *priv,
size_t len, const EVP_CIPHER *cipher)
{
return new_cmac_key_int(priv, len, NULL, cipher, NULL, NULL, e);
}
int EVP_PKEY_set_type(EVP_PKEY *pkey, int type)
{
return pkey_set_type(pkey, NULL, type, NULL, -1, NULL);
}
int EVP_PKEY_set_type_str(EVP_PKEY *pkey, const char *str, int len)
{
return pkey_set_type(pkey, NULL, EVP_PKEY_NONE, str, len, NULL);
}
# ifndef OPENSSL_NO_ENGINE
int EVP_PKEY_set1_engine(EVP_PKEY *pkey, ENGINE *e)
{
if (e != NULL) {
if (!ENGINE_init(e)) {
ERR_raise(ERR_LIB_EVP, ERR_R_ENGINE_LIB);
return 0;
}
if (ENGINE_get_pkey_meth(e, pkey->type) == NULL) {
ENGINE_finish(e);
ERR_raise(ERR_LIB_EVP, EVP_R_UNSUPPORTED_ALGORITHM);
return 0;
}
}
ENGINE_finish(pkey->pmeth_engine);
pkey->pmeth_engine = e;
return 1;
}
ENGINE *EVP_PKEY_get0_engine(const EVP_PKEY *pkey)
{
return pkey->engine;
}
# endif
# ifndef OPENSSL_NO_DEPRECATED_3_0
static void detect_foreign_key(EVP_PKEY *pkey)
{
switch (pkey->type) {
case EVP_PKEY_RSA:
case EVP_PKEY_RSA_PSS:
pkey->foreign = pkey->pkey.rsa != NULL
&& ossl_rsa_is_foreign(pkey->pkey.rsa);
break;
# ifndef OPENSSL_NO_EC
case EVP_PKEY_SM2:
break;
case EVP_PKEY_EC:
pkey->foreign = pkey->pkey.ec != NULL
&& ossl_ec_key_is_foreign(pkey->pkey.ec);
break;
# endif
# ifndef OPENSSL_NO_DSA
case EVP_PKEY_DSA:
pkey->foreign = pkey->pkey.dsa != NULL
&& ossl_dsa_is_foreign(pkey->pkey.dsa);
break;
#endif
# ifndef OPENSSL_NO_DH
case EVP_PKEY_DH:
pkey->foreign = pkey->pkey.dh != NULL
&& ossl_dh_is_foreign(pkey->pkey.dh);
break;
#endif
default:
pkey->foreign = 0;
break;
}
}
int EVP_PKEY_assign(EVP_PKEY *pkey, int type, void *key)
{
# ifndef OPENSSL_NO_EC
int pktype;
pktype = EVP_PKEY_type(type);
if ((key != NULL) && (pktype == EVP_PKEY_EC || pktype == EVP_PKEY_SM2)) {
const EC_GROUP *group = EC_KEY_get0_group(key);
if (group != NULL) {
int curve = EC_GROUP_get_curve_name(group);
/*
* Regardless of what is requested the SM2 curve must be SM2 type,
* and non SM2 curves are EC type.
*/
if (curve == NID_sm2 && pktype == EVP_PKEY_EC)
type = EVP_PKEY_SM2;
else if(curve != NID_sm2 && pktype == EVP_PKEY_SM2)
type = EVP_PKEY_EC;
}
}
# endif
if (pkey == NULL || !EVP_PKEY_set_type(pkey, type))
return 0;
pkey->pkey.ptr = key;
detect_foreign_key(pkey);
return (key != NULL);
}
# endif
void *EVP_PKEY_get0(const EVP_PKEY *pkey)
{
if (pkey == NULL)
return NULL;
if (!evp_pkey_is_provided(pkey))
return pkey->pkey.ptr;
return NULL;
}
const unsigned char *EVP_PKEY_get0_hmac(const EVP_PKEY *pkey, size_t *len)
{
const ASN1_OCTET_STRING *os = NULL;
if (pkey->type != EVP_PKEY_HMAC) {
ERR_raise(ERR_LIB_EVP, EVP_R_EXPECTING_AN_HMAC_KEY);
return NULL;
}
os = evp_pkey_get_legacy((EVP_PKEY *)pkey);
if (os != NULL) {
*len = os->length;
return os->data;
}
return NULL;
}
# ifndef OPENSSL_NO_POLY1305
const unsigned char *EVP_PKEY_get0_poly1305(const EVP_PKEY *pkey, size_t *len)
{
const ASN1_OCTET_STRING *os = NULL;
if (pkey->type != EVP_PKEY_POLY1305) {
ERR_raise(ERR_LIB_EVP, EVP_R_EXPECTING_A_POLY1305_KEY);
return NULL;
}
os = evp_pkey_get_legacy((EVP_PKEY *)pkey);
if (os != NULL) {
*len = os->length;
return os->data;
}
return NULL;
}
# endif
# ifndef OPENSSL_NO_SIPHASH
const unsigned char *EVP_PKEY_get0_siphash(const EVP_PKEY *pkey, size_t *len)
{
const ASN1_OCTET_STRING *os = NULL;
if (pkey->type != EVP_PKEY_SIPHASH) {
ERR_raise(ERR_LIB_EVP, EVP_R_EXPECTING_A_SIPHASH_KEY);
return NULL;
}
os = evp_pkey_get_legacy((EVP_PKEY *)pkey);
if (os != NULL) {
*len = os->length;
return os->data;
}
return NULL;
}
# endif
# ifndef OPENSSL_NO_DSA
static DSA *evp_pkey_get0_DSA_int(const EVP_PKEY *pkey)
{
if (pkey->type != EVP_PKEY_DSA) {
ERR_raise(ERR_LIB_EVP, EVP_R_EXPECTING_A_DSA_KEY);
return NULL;
}
return evp_pkey_get_legacy((EVP_PKEY *)pkey);
}
const DSA *EVP_PKEY_get0_DSA(const EVP_PKEY *pkey)
{
return evp_pkey_get0_DSA_int(pkey);
}
int EVP_PKEY_set1_DSA(EVP_PKEY *pkey, DSA *key)
{
int ret = EVP_PKEY_assign_DSA(pkey, key);
if (ret)
DSA_up_ref(key);
return ret;
}
DSA *EVP_PKEY_get1_DSA(EVP_PKEY *pkey)
{
DSA *ret = evp_pkey_get0_DSA_int(pkey);
if (ret != NULL)
DSA_up_ref(ret);
return ret;
}
# endif /* OPENSSL_NO_DSA */
# ifndef OPENSSL_NO_EC
static const ECX_KEY *evp_pkey_get0_ECX_KEY(const EVP_PKEY *pkey, int type)
{
if (EVP_PKEY_get_base_id(pkey) != type) {
ERR_raise(ERR_LIB_EVP, EVP_R_EXPECTING_A_ECX_KEY);
return NULL;
}
return evp_pkey_get_legacy((EVP_PKEY *)pkey);
}
static ECX_KEY *evp_pkey_get1_ECX_KEY(EVP_PKEY *pkey, int type)
{
ECX_KEY *ret = (ECX_KEY *)evp_pkey_get0_ECX_KEY(pkey, type);
if (ret != NULL && !ossl_ecx_key_up_ref(ret))
ret = NULL;
return ret;
}
# define IMPLEMENT_ECX_VARIANT(NAME) \
ECX_KEY *ossl_evp_pkey_get1_##NAME(EVP_PKEY *pkey) \
{ \
return evp_pkey_get1_ECX_KEY(pkey, EVP_PKEY_##NAME); \
}
IMPLEMENT_ECX_VARIANT(X25519)
IMPLEMENT_ECX_VARIANT(X448)
IMPLEMENT_ECX_VARIANT(ED25519)
IMPLEMENT_ECX_VARIANT(ED448)
# endif
# if !defined(OPENSSL_NO_DH) && !defined(OPENSSL_NO_DEPRECATED_3_0)
int EVP_PKEY_set1_DH(EVP_PKEY *pkey, DH *dhkey)
{
int ret, type;
/*
* ossl_dh_is_named_safe_prime_group() returns 1 for named safe prime groups
* related to ffdhe and modp (which cache q = (p - 1) / 2),
* and returns 0 for all other dh parameter generation types including
* RFC5114 named groups.
*
* The EVP_PKEY_DH type is used for dh parameter generation types:
* - named safe prime groups related to ffdhe and modp
* - safe prime generator
*
* The type EVP_PKEY_DHX is used for dh parameter generation types
* - fips186-4 and fips186-2
* - rfc5114 named groups.
*
* The EVP_PKEY_DH type is used to save PKCS#3 data than can be stored
* without a q value.
* The EVP_PKEY_DHX type is used to save X9.42 data that requires the
* q value to be stored.
*/
if (ossl_dh_is_named_safe_prime_group(dhkey))
type = EVP_PKEY_DH;
else
type = DH_get0_q(dhkey) == NULL ? EVP_PKEY_DH : EVP_PKEY_DHX;
ret = EVP_PKEY_assign(pkey, type, dhkey);
if (ret)
DH_up_ref(dhkey);
return ret;
}
DH *evp_pkey_get0_DH_int(const EVP_PKEY *pkey)
{
if (pkey->type != EVP_PKEY_DH && pkey->type != EVP_PKEY_DHX) {
ERR_raise(ERR_LIB_EVP, EVP_R_EXPECTING_A_DH_KEY);
return NULL;
}
return evp_pkey_get_legacy((EVP_PKEY *)pkey);
}
const DH *EVP_PKEY_get0_DH(const EVP_PKEY *pkey)
{
return evp_pkey_get0_DH_int(pkey);
}
DH *EVP_PKEY_get1_DH(EVP_PKEY *pkey)
{
DH *ret = evp_pkey_get0_DH_int(pkey);
if (ret != NULL)
DH_up_ref(ret);
return ret;
}
# endif
int EVP_PKEY_type(int type)
{
int ret;
const EVP_PKEY_ASN1_METHOD *ameth;
ENGINE *e;
ameth = EVP_PKEY_asn1_find(&e, type);
if (ameth)
ret = ameth->pkey_id;
else
ret = NID_undef;
# ifndef OPENSSL_NO_ENGINE
ENGINE_finish(e);
# endif
return ret;
}
int EVP_PKEY_get_id(const EVP_PKEY *pkey)
{
return pkey->type;
}
int EVP_PKEY_get_base_id(const EVP_PKEY *pkey)
{
return EVP_PKEY_type(pkey->type);
}
/*
* These hard coded cases are pure hackery to get around the fact
* that names in crypto/objects/objects.txt are a mess. There is
* no "EC", and "RSA" leads to the NID for 2.5.8.1.1, an OID that's
* fallen out in favor of { pkcs-1 1 }, i.e. 1.2.840.113549.1.1.1,
* the NID of which is used for EVP_PKEY_RSA. Strangely enough,
* "DSA" is accurate... but still, better be safe and hard-code
* names that we know.
* On a similar topic, EVP_PKEY_type(EVP_PKEY_SM2) will result in
* EVP_PKEY_EC, because of aliasing.
* This should be cleaned away along with all other #legacy support.
*/
static const OSSL_ITEM standard_name2type[] = {
{ EVP_PKEY_RSA, "RSA" },
{ EVP_PKEY_RSA_PSS, "RSA-PSS" },
{ EVP_PKEY_EC, "EC" },
{ EVP_PKEY_ED25519, "ED25519" },
{ EVP_PKEY_ED448, "ED448" },
{ EVP_PKEY_X25519, "X25519" },
{ EVP_PKEY_X448, "X448" },
{ EVP_PKEY_SM2, "SM2" },
{ EVP_PKEY_DH, "DH" },
{ EVP_PKEY_DHX, "X9.42 DH" },
{ EVP_PKEY_DHX, "DHX" },
{ EVP_PKEY_DSA, "DSA" },
};
int evp_pkey_name2type(const char *name)
{
int type;
size_t i;
for (i = 0; i < OSSL_NELEM(standard_name2type); i++) {
if (OPENSSL_strcasecmp(name, standard_name2type[i].ptr) == 0)
return (int)standard_name2type[i].id;
}
if ((type = EVP_PKEY_type(OBJ_sn2nid(name))) != NID_undef)
return type;
return EVP_PKEY_type(OBJ_ln2nid(name));
}
const char *evp_pkey_type2name(int type)
{
size_t i;
for (i = 0; i < OSSL_NELEM(standard_name2type); i++) {
if (type == (int)standard_name2type[i].id)
return standard_name2type[i].ptr;
}
return OBJ_nid2sn(type);
}
int EVP_PKEY_is_a(const EVP_PKEY *pkey, const char *name)
{
if (pkey == NULL)
return 0;
if (pkey->keymgmt == NULL)
return pkey->type == evp_pkey_name2type(name);
return EVP_KEYMGMT_is_a(pkey->keymgmt, name);
}
int EVP_PKEY_type_names_do_all(const EVP_PKEY *pkey,
void (*fn)(const char *name, void *data),
void *data)
{
if (!evp_pkey_is_typed(pkey))
return 0;
if (!evp_pkey_is_provided(pkey)) {
const char *name = OBJ_nid2sn(EVP_PKEY_get_id(pkey));
fn(name, data);
return 1;
}
return EVP_KEYMGMT_names_do_all(pkey->keymgmt, fn, data);
}
int EVP_PKEY_can_sign(const EVP_PKEY *pkey)
{
if (pkey->keymgmt == NULL) {
switch (EVP_PKEY_get_base_id(pkey)) {
case EVP_PKEY_RSA:
case EVP_PKEY_RSA_PSS:
return 1;
# ifndef OPENSSL_NO_DSA
case EVP_PKEY_DSA:
return 1;
# endif
# ifndef OPENSSL_NO_EC
case EVP_PKEY_ED25519:
case EVP_PKEY_ED448:
return 1;
case EVP_PKEY_EC: /* Including SM2 */
return EC_KEY_can_sign(pkey->pkey.ec);
# endif
default:
break;
}
} else {
const OSSL_PROVIDER *prov = EVP_KEYMGMT_get0_provider(pkey->keymgmt);
OSSL_LIB_CTX *libctx = ossl_provider_libctx(prov);
const char *supported_sig =
pkey->keymgmt->query_operation_name != NULL
? pkey->keymgmt->query_operation_name(OSSL_OP_SIGNATURE)
: EVP_KEYMGMT_get0_name(pkey->keymgmt);
EVP_SIGNATURE *signature = NULL;
signature = EVP_SIGNATURE_fetch(libctx, supported_sig, NULL);
if (signature != NULL) {
EVP_SIGNATURE_free(signature);
return 1;
}
}
return 0;
}
static int print_reset_indent(BIO **out, int pop_f_prefix, long saved_indent)
{
BIO_set_indent(*out, saved_indent);
if (pop_f_prefix) {
BIO *next = BIO_pop(*out);
BIO_free(*out);
*out = next;
}
return 1;
}
static int print_set_indent(BIO **out, int *pop_f_prefix, long *saved_indent,
long indent)
{
*pop_f_prefix = 0;
*saved_indent = 0;
if (indent > 0) {
long i = BIO_get_indent(*out);
*saved_indent = (i < 0 ? 0 : i);
if (BIO_set_indent(*out, indent) <= 0) {
BIO *prefbio = BIO_new(BIO_f_prefix());
if (prefbio == NULL)
return 0;
*out = BIO_push(prefbio, *out);
*pop_f_prefix = 1;
}
if (BIO_set_indent(*out, indent) <= 0) {
print_reset_indent(out, *pop_f_prefix, *saved_indent);
return 0;
}
}
return 1;
}
static int unsup_alg(BIO *out, const EVP_PKEY *pkey, int indent,
const char *kstr)
{
return BIO_indent(out, indent, 128)
&& BIO_printf(out, "%s algorithm \"%s\" unsupported\n",
kstr, OBJ_nid2ln(pkey->type)) > 0;
}
static int print_pkey(const EVP_PKEY *pkey, BIO *out, int indent,
int selection /* For provided encoding */,
const char *propquery /* For provided encoding */,
int (*legacy_print)(BIO *out, const EVP_PKEY *pkey,
int indent, ASN1_PCTX *pctx),
ASN1_PCTX *legacy_pctx /* For legacy print */)
{
int pop_f_prefix;
long saved_indent;
OSSL_ENCODER_CTX *ctx = NULL;
int ret = -2; /* default to unsupported */
if (!print_set_indent(&out, &pop_f_prefix, &saved_indent, indent))
return 0;
ctx = OSSL_ENCODER_CTX_new_for_pkey(pkey, selection, "TEXT", NULL,
propquery);
if (OSSL_ENCODER_CTX_get_num_encoders(ctx) != 0)
ret = OSSL_ENCODER_to_bio(ctx, out);
OSSL_ENCODER_CTX_free(ctx);
if (ret != -2)
goto end;
/* legacy fallback */
if (legacy_print != NULL)
ret = legacy_print(out, pkey, 0, legacy_pctx);
else
ret = unsup_alg(out, pkey, 0, "Public Key");
end:
print_reset_indent(&out, pop_f_prefix, saved_indent);
return ret;
}
int EVP_PKEY_print_public(BIO *out, const EVP_PKEY *pkey,
int indent, ASN1_PCTX *pctx)
{
return print_pkey(pkey, out, indent, EVP_PKEY_PUBLIC_KEY, NULL,
(pkey->ameth != NULL ? pkey->ameth->pub_print : NULL),
pctx);
}
int EVP_PKEY_print_private(BIO *out, const EVP_PKEY *pkey,
int indent, ASN1_PCTX *pctx)
{
return print_pkey(pkey, out, indent, EVP_PKEY_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;
}
int EVP_PKEY_set1_encoded_public_key(EVP_PKEY *pkey, const unsigned char *pub,
size_t publen)
{
if (pkey == NULL)
return 0;
if (evp_pkey_is_provided(pkey))
return
EVP_PKEY_set_octet_string_param(pkey,
OSSL_PKEY_PARAM_ENCODED_PUBLIC_KEY,
(unsigned char *)pub, publen);
if (publen > INT_MAX)
return 0;
/* Historically this function was EVP_PKEY_set1_tls_encodedpoint */
if (evp_pkey_asn1_ctrl(pkey, ASN1_PKEY_CTRL_SET1_TLS_ENCPT, publen,
(void *)pub) <= 0)
return 0;
return 1;
}
size_t EVP_PKEY_get1_encoded_public_key(EVP_PKEY *pkey, unsigned char **ppub)
{
int rv;
if (pkey == NULL)
return 0;
if (evp_pkey_is_provided(pkey)) {
size_t return_size = OSSL_PARAM_UNMODIFIED;
unsigned char *buf;
/*
* We know that this is going to fail, but it will give us a size
* to allocate.
*/
EVP_PKEY_get_octet_string_param(pkey,
OSSL_PKEY_PARAM_ENCODED_PUBLIC_KEY,
NULL, 0, &return_size);
if (return_size == OSSL_PARAM_UNMODIFIED)
return 0;
*ppub = NULL;
buf = OPENSSL_malloc(return_size);
if (buf == NULL)
return 0;
if (!EVP_PKEY_get_octet_string_param(pkey,
OSSL_PKEY_PARAM_ENCODED_PUBLIC_KEY,
buf, return_size, NULL)) {
OPENSSL_free(buf);
return 0;
}
*ppub = buf;
return return_size;
}
rv = evp_pkey_asn1_ctrl(pkey, ASN1_PKEY_CTRL_GET1_TLS_ENCPT, 0, ppub);
if (rv <= 0)
return 0;
return rv;
}
#endif /* FIPS_MODULE */
/*- All methods below can also be used in FIPS_MODULE */
EVP_PKEY *EVP_PKEY_new(void)
{
EVP_PKEY *ret = OPENSSL_zalloc(sizeof(*ret));
if (ret == NULL) {
ERR_raise(ERR_LIB_EVP, ERR_R_MALLOC_FAILURE);
return NULL;
}
ret->type = EVP_PKEY_NONE;
ret->save_type = EVP_PKEY_NONE;
ret->references = 1;
ret->lock = CRYPTO_THREAD_lock_new();
if (ret->lock == NULL) {
EVPerr(ERR_LIB_EVP, ERR_R_MALLOC_FAILURE);
goto err;
}
#ifndef FIPS_MODULE
ret->save_parameters = 1;
if (!CRYPTO_new_ex_data(CRYPTO_EX_INDEX_EVP_PKEY, ret, &ret->ex_data)) {
ERR_raise(ERR_LIB_EVP, ERR_R_MALLOC_FAILURE);
goto err;
}
#endif
return ret;
err:
CRYPTO_THREAD_lock_free(ret->lock);
OPENSSL_free(ret);
return NULL;
}
/*
* Setup a public key management method.
*
* For legacy keys, either |type| or |str| is expected to have the type
* information. In this case, the setup consists of finding an ASN1 method
* and potentially an ENGINE, and setting those fields in |pkey|.
*
* For provider side keys, |keymgmt| is expected to be non-NULL. In this
* case, the setup consists of setting the |keymgmt| field in |pkey|.
*
* If pkey is NULL just return 1 or 0 if the key management method exists.
*/
static int pkey_set_type(EVP_PKEY *pkey, ENGINE *e, int type, const char *str,
int len, EVP_KEYMGMT *keymgmt)
{
#ifndef FIPS_MODULE
const EVP_PKEY_ASN1_METHOD *ameth = NULL;
ENGINE **eptr = (e == NULL) ? &e : NULL;
#endif
/*
* The setups can't set both legacy and provider side methods.
* It is forbidden
*/
if (!ossl_assert(type == EVP_PKEY_NONE || keymgmt == NULL)
|| !ossl_assert(e == NULL || keymgmt == NULL)) {
ERR_raise(ERR_LIB_EVP, ERR_R_INTERNAL_ERROR);
return 0;
}
if (pkey != NULL) {
int free_it = 0;
#ifndef FIPS_MODULE
free_it = free_it || pkey->pkey.ptr != NULL;
#endif
free_it = free_it || pkey->keydata != NULL;
if (free_it)
evp_pkey_free_it(pkey);
#ifndef FIPS_MODULE
/*
* If key type matches and a method exists then this lookup has
* succeeded once so just indicate success.
*/
if (pkey->type != EVP_PKEY_NONE
&& type == pkey->save_type
&& pkey->ameth != NULL)
return 1;
# ifndef OPENSSL_NO_ENGINE
/* If we have ENGINEs release them */
ENGINE_finish(pkey->engine);
pkey->engine = NULL;
ENGINE_finish(pkey->pmeth_engine);
pkey->pmeth_engine = NULL;
# endif
#endif
}
#ifndef FIPS_MODULE
if (str != NULL)
ameth = EVP_PKEY_asn1_find_str(eptr, str, len);
else if (type != EVP_PKEY_NONE)
ameth = EVP_PKEY_asn1_find(eptr, type);
# ifndef OPENSSL_NO_ENGINE
if (pkey == NULL && eptr != NULL)
ENGINE_finish(e);
# endif
#endif
{
int check = 1;
#ifndef FIPS_MODULE
check = check && ameth == NULL;
#endif
check = check && keymgmt == NULL;
if (check) {
ERR_raise(ERR_LIB_EVP, EVP_R_UNSUPPORTED_ALGORITHM);
return 0;
}
}
if (pkey != NULL) {
if (keymgmt != NULL && !EVP_KEYMGMT_up_ref(keymgmt)) {
ERR_raise(ERR_LIB_EVP, ERR_R_INTERNAL_ERROR);
return 0;
}
pkey->keymgmt = keymgmt;
pkey->save_type = type;
pkey->type = type;
#ifndef FIPS_MODULE
/*
* If the internal "origin" key is provider side, don't save |ameth|.
* The main reason is that |ameth| is one factor to detect that the
* internal "origin" key is a legacy one.
*/
if (keymgmt == NULL)
pkey->ameth = ameth;
/*
* The EVP_PKEY_ASN1_METHOD |pkey_id| retains its legacy key purpose
* for any key type that has a legacy implementation, regardless of
* if the internal key is a legacy or a provider side one. When
* there is no legacy implementation for the key, the type becomes
* EVP_PKEY_KEYMGMT, which indicates that one should be cautious
* with functions that expect legacy internal keys.
*/
if (ameth != NULL) {
if (type == EVP_PKEY_NONE)
pkey->type = ameth->pkey_id;
} else {
pkey->type = EVP_PKEY_KEYMGMT;
}
# ifndef OPENSSL_NO_ENGINE
if (eptr == NULL && e != NULL && !ENGINE_init(e)) {
ERR_raise(ERR_LIB_EVP, EVP_R_INITIALIZATION_ERROR);
return 0;
}
# endif
pkey->engine = e;
#endif
}
return 1;
}
#ifndef FIPS_MODULE
static void find_ameth(const char *name, void *data)
{
const char **str = data;
/*
* The error messages from pkey_set_type() are uninteresting here,
* and misleading.
*/
ERR_set_mark();
if (pkey_set_type(NULL, NULL, EVP_PKEY_NONE, name, strlen(name),
NULL)) {
if (str[0] == NULL)
str[0] = name;
else if (str[1] == NULL)
str[1] = name;
}
ERR_pop_to_mark();
}
#endif
int EVP_PKEY_set_type_by_keymgmt(EVP_PKEY *pkey, EVP_KEYMGMT *keymgmt)
{
#ifndef FIPS_MODULE
# define EVP_PKEY_TYPE_STR str[0]
# define EVP_PKEY_TYPE_STRLEN (str[0] == NULL ? -1 : (int)strlen(str[0]))
/*
* Find at most two strings that have an associated EVP_PKEY_ASN1_METHOD
* Ideally, only one should be found. If two (or more) are found, the
* match is ambiguous. This should never happen, but...
*/
const char *str[2] = { NULL, NULL };
if (!EVP_KEYMGMT_names_do_all(keymgmt, find_ameth, &str)
|| str[1] != NULL) {
ERR_raise(ERR_LIB_EVP, ERR_R_INTERNAL_ERROR);
return 0;
}
#else
# define EVP_PKEY_TYPE_STR NULL
# define EVP_PKEY_TYPE_STRLEN -1
#endif
return pkey_set_type(pkey, NULL, EVP_PKEY_NONE,
EVP_PKEY_TYPE_STR, EVP_PKEY_TYPE_STRLEN,
keymgmt);
#undef EVP_PKEY_TYPE_STR
#undef EVP_PKEY_TYPE_STRLEN
}
int EVP_PKEY_up_ref(EVP_PKEY *pkey)
{
int i;
if (CRYPTO_UP_REF(&pkey->references, &i, pkey->lock) <= 0)
return 0;
REF_PRINT_COUNT("EVP_PKEY", pkey);
REF_ASSERT_ISNT(i < 2);
return ((i > 1) ? 1 : 0);
}
#ifndef FIPS_MODULE
EVP_PKEY *EVP_PKEY_dup(EVP_PKEY *pkey)
{
EVP_PKEY *dup_pk;
if (pkey == NULL) {
ERR_raise(ERR_LIB_EVP, ERR_R_PASSED_NULL_PARAMETER);
return NULL;
}
if ((dup_pk = EVP_PKEY_new()) == NULL)
return NULL;
if (evp_pkey_is_blank(pkey))
goto done;
if (evp_pkey_is_provided(pkey)) {
if (!evp_keymgmt_util_copy(dup_pk, pkey,
OSSL_KEYMGMT_SELECT_ALL))
goto err;
goto done;
}
if (evp_pkey_is_legacy(pkey)) {
const EVP_PKEY_ASN1_METHOD *ameth = pkey->ameth;
if (ameth == NULL || ameth->copy == NULL) {
if (pkey->pkey.ptr == NULL /* empty key, just set type */
&& EVP_PKEY_set_type(dup_pk, pkey->type) != 0)
goto done;
ERR_raise(ERR_LIB_EVP, EVP_R_UNSUPPORTED_KEY_TYPE);
goto err;
}
if (!ameth->copy(dup_pk, pkey))
goto err;
goto done;
}
goto err;
done:
/* copy auxiliary data */
if (!CRYPTO_dup_ex_data(CRYPTO_EX_INDEX_EVP_PKEY,
&dup_pk->ex_data, &pkey->ex_data))
goto err;
if (pkey->attributes != NULL) {
if ((dup_pk->attributes = ossl_x509at_dup(pkey->attributes)) == NULL)
goto err;
}
return dup_pk;
err:
EVP_PKEY_free(dup_pk);
return NULL;
}
void evp_pkey_free_legacy(EVP_PKEY *x)
{
const EVP_PKEY_ASN1_METHOD *ameth = x->ameth;
ENGINE *tmpe = NULL;
if (ameth == NULL && x->legacy_cache_pkey.ptr != NULL)
ameth = EVP_PKEY_asn1_find(&tmpe, x->type);
if (ameth != NULL) {
if (x->legacy_cache_pkey.ptr != NULL) {
/*
* We should never have both a legacy origin key, and a key in the
* legacy cache.
*/
assert(x->pkey.ptr == NULL);
/*
* For the purposes of freeing we make the legacy cache look like
* a legacy origin key.
*/
x->pkey = x->legacy_cache_pkey;
x->legacy_cache_pkey.ptr = NULL;
}
if (ameth->pkey_free != NULL)
ameth->pkey_free(x);
x->pkey.ptr = NULL;
}
# ifndef OPENSSL_NO_ENGINE
ENGINE_finish(tmpe);
ENGINE_finish(x->engine);
x->engine = NULL;
ENGINE_finish(x->pmeth_engine);
x->pmeth_engine = NULL;
# endif
}
#endif /* FIPS_MODULE */
static void evp_pkey_free_it(EVP_PKEY *x)
{
/* internal function; x is never NULL */
evp_keymgmt_util_clear_operation_cache(x, 1);
#ifndef FIPS_MODULE
evp_pkey_free_legacy(x);
#endif
if (x->keymgmt != NULL) {
evp_keymgmt_freedata(x->keymgmt, x->keydata);
EVP_KEYMGMT_free(x->keymgmt);
x->keymgmt = NULL;
x->keydata = NULL;
}
x->type = EVP_PKEY_NONE;
}
void EVP_PKEY_free(EVP_PKEY *x)
{
int i;
if (x == NULL)
return;
CRYPTO_DOWN_REF(&x->references, &i, x->lock);
REF_PRINT_COUNT("EVP_PKEY", x);
if (i > 0)
return;
REF_ASSERT_ISNT(i < 0);
evp_pkey_free_it(x);
#ifndef FIPS_MODULE
CRYPTO_free_ex_data(CRYPTO_EX_INDEX_EVP_PKEY, x, &x->ex_data);
#endif
CRYPTO_THREAD_lock_free(x->lock);
#ifndef FIPS_MODULE
sk_X509_ATTRIBUTE_pop_free(x->attributes, X509_ATTRIBUTE_free);
#endif
OPENSSL_free(x);
}
int EVP_PKEY_get_size(const EVP_PKEY *pkey)
{
int size = 0;
if (pkey != NULL) {
size = pkey->cache.size;
#ifndef FIPS_MODULE
if (pkey->ameth != NULL && pkey->ameth->pkey_size != NULL)
size = pkey->ameth->pkey_size(pkey);
#endif
}
return size < 0 ? 0 : size;
}
const char *EVP_PKEY_get0_description(const EVP_PKEY *pkey)
{
if (!evp_pkey_is_assigned(pkey))
return NULL;
if (evp_pkey_is_provided(pkey) && pkey->keymgmt->description != NULL)
return pkey->keymgmt->description;
#ifndef FIPS_MODULE
if (pkey->ameth != NULL)
return pkey->ameth->info;
#endif
return NULL;
}
void *evp_pkey_export_to_provider(EVP_PKEY *pk, OSSL_LIB_CTX *libctx,
EVP_KEYMGMT **keymgmt,
const char *propquery)
{
EVP_KEYMGMT *allocated_keymgmt = NULL;
EVP_KEYMGMT *tmp_keymgmt = NULL;
int selection = OSSL_KEYMGMT_SELECT_ALL;
void *keydata = NULL;
int check;
if (pk == NULL)
return NULL;
/* No key data => nothing to export */
check = 1;
#ifndef FIPS_MODULE
check = check && pk->pkey.ptr == NULL;
#endif
check = check && pk->keydata == NULL;
if (check)
return NULL;
#ifndef FIPS_MODULE
if (pk->pkey.ptr != NULL) {
/*
* If the legacy key doesn't have an dirty counter or export function,
* give up
*/
if (pk->ameth->dirty_cnt == NULL || pk->ameth->export_to == NULL)
return NULL;
}
#endif
if (keymgmt != NULL) {
tmp_keymgmt = *keymgmt;
*keymgmt = NULL;
}
/*
* If no keymgmt was given or found, get a default keymgmt. We do so by
* letting EVP_PKEY_CTX_new_from_pkey() do it for us, then we steal it.
*/
if (tmp_keymgmt == NULL) {
EVP_PKEY_CTX *ctx = EVP_PKEY_CTX_new_from_pkey(libctx, pk, propquery);
if (ctx == NULL)
goto end;
allocated_keymgmt = tmp_keymgmt = ctx->keymgmt;
ctx->keymgmt = NULL;
EVP_PKEY_CTX_free(ctx);
}
/* If there's still no keymgmt to be had, give up */
if (tmp_keymgmt == NULL)
goto end;
#ifndef FIPS_MODULE
if (pk->pkey.ptr != NULL) {
OP_CACHE_ELEM *op;
/*
* If the legacy "origin" hasn't changed since last time, we try
* to find our keymgmt in the operation cache. If it has changed,
* |i| remains zero, and we will clear the cache further down.
*/
if (pk->ameth->dirty_cnt(pk) == pk->dirty_cnt_copy) {
if (!CRYPTO_THREAD_read_lock(pk->lock))
goto end;
op = evp_keymgmt_util_find_operation_cache(pk, tmp_keymgmt,
selection);
/*
* If |tmp_keymgmt| is present in the operation cache, it means
* that export doesn't need to be redone. In that case, we take
* token copies of the cached pointers, to have token success
- * values to return.
+ * 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, 0)) {
CRYPTO_THREAD_unlock(pk->lock);
evp_keymgmt_freedata(tmp_keymgmt, keydata);
keydata = NULL;
EVP_KEYMGMT_free(tmp_keymgmt);
goto end;
}
EVP_KEYMGMT_free(tmp_keymgmt); /* refcnt-- */
/* Check to make sure some other thread didn't get there first */
op = evp_keymgmt_util_find_operation_cache(pk, tmp_keymgmt, selection);
if (op != NULL && op->keymgmt != NULL) {
void *tmp_keydata = op->keydata;
CRYPTO_THREAD_unlock(pk->lock);
evp_keymgmt_freedata(tmp_keymgmt, keydata);
keydata = tmp_keydata;
goto end;
}
/* Add the new export to the operation cache */
if (!evp_keymgmt_util_cache_keydata(pk, tmp_keymgmt, keydata,
selection)) {
CRYPTO_THREAD_unlock(pk->lock);
evp_keymgmt_freedata(tmp_keymgmt, keydata);
keydata = NULL;
goto end;
}
/* Synchronize the dirty count */
pk->dirty_cnt_copy = pk->ameth->dirty_cnt(pk);
CRYPTO_THREAD_unlock(pk->lock);
goto end;
}
#endif /* FIPS_MODULE */
keydata = evp_keymgmt_util_export_to_provider(pk, tmp_keymgmt, selection);
end:
/*
* If nothing was exported, |tmp_keymgmt| might point at a freed
* EVP_KEYMGMT, so we clear it to be safe. It shouldn't be useful for
* the caller either way in that case.
*/
if (keydata == NULL)
tmp_keymgmt = NULL;
if (keymgmt != NULL && tmp_keymgmt != NULL) {
*keymgmt = tmp_keymgmt;
allocated_keymgmt = NULL;
}
EVP_KEYMGMT_free(allocated_keymgmt);
return keydata;
}
#ifndef FIPS_MODULE
int evp_pkey_copy_downgraded(EVP_PKEY **dest, const EVP_PKEY *src)
{
EVP_PKEY *allocpkey = NULL;
if (!ossl_assert(dest != NULL))
return 0;
if (evp_pkey_is_assigned(src) && evp_pkey_is_provided(src)) {
EVP_KEYMGMT *keymgmt = src->keymgmt;
void *keydata = src->keydata;
int type = src->type;
const char *keytype = NULL;
keytype = EVP_KEYMGMT_get0_name(keymgmt);
/*
* If the type is EVP_PKEY_NONE, then we have a problem somewhere
* else in our code. If it's not one of the well known EVP_PKEY_xxx
* values, it should at least be EVP_PKEY_KEYMGMT at this point.
* The check is kept as a safety measure.
*/
if (!ossl_assert(type != EVP_PKEY_NONE)) {
ERR_raise_data(ERR_LIB_EVP, ERR_R_INTERNAL_ERROR,
"keymgmt key type = %s but legacy type = EVP_PKEY_NONE",
keytype);
return 0;
}
/* Prefer the legacy key type name for error reporting */
if (type != EVP_PKEY_KEYMGMT)
keytype = OBJ_nid2sn(type);
/* Make sure we have a clean slate to copy into */
if (*dest == NULL) {
allocpkey = *dest = EVP_PKEY_new();
if (*dest == NULL) {
ERR_raise(ERR_LIB_EVP, ERR_R_MALLOC_FAILURE);
return 0;
}
} else {
evp_pkey_free_it(*dest);
}
if (EVP_PKEY_set_type(*dest, type)) {
/* If the key is typed but empty, we're done */
if (keydata == NULL)
return 1;
if ((*dest)->ameth->import_from == NULL) {
ERR_raise_data(ERR_LIB_EVP, EVP_R_NO_IMPORT_FUNCTION,
"key type = %s", keytype);
} else {
/*
* We perform the export in the same libctx as the keymgmt
* that we are using.
*/
OSSL_LIB_CTX *libctx =
ossl_provider_libctx(keymgmt->prov);
EVP_PKEY_CTX *pctx =
EVP_PKEY_CTX_new_from_pkey(libctx, *dest, NULL);
if (pctx == NULL)
ERR_raise(ERR_LIB_EVP, ERR_R_MALLOC_FAILURE);
if (pctx != NULL
&& evp_keymgmt_export(keymgmt, keydata,
OSSL_KEYMGMT_SELECT_ALL,
(*dest)->ameth->import_from,
pctx)) {
/* Synchronize the dirty count */
(*dest)->dirty_cnt_copy = (*dest)->ameth->dirty_cnt(*dest);
EVP_PKEY_CTX_free(pctx);
return 1;
}
EVP_PKEY_CTX_free(pctx);
}
ERR_raise_data(ERR_LIB_EVP, EVP_R_KEYMGMT_EXPORT_FAILURE,
"key type = %s", keytype);
}
}
if (allocpkey != NULL) {
EVP_PKEY_free(allocpkey);
*dest = NULL;
}
return 0;
}
void *evp_pkey_get_legacy(EVP_PKEY *pk)
{
EVP_PKEY *tmp_copy = NULL;
void *ret = NULL;
if (!ossl_assert(pk != NULL))
return NULL;
/*
* If this isn't an assigned provider side key, we just use any existing
* origin legacy key.
*/
if (!evp_pkey_is_assigned(pk))
return NULL;
if (!evp_pkey_is_provided(pk))
return pk->pkey.ptr;
if (!CRYPTO_THREAD_read_lock(pk->lock))
return NULL;
ret = pk->legacy_cache_pkey.ptr;
if (!CRYPTO_THREAD_unlock(pk->lock))
return NULL;
if (ret != NULL)
return ret;
if (!evp_pkey_copy_downgraded(&tmp_copy, pk))
goto err;
if (!CRYPTO_THREAD_write_lock(pk->lock))
goto err;
/* Check again in case some other thread has updated it in the meantime */
ret = pk->legacy_cache_pkey.ptr;
if (ret == NULL) {
/* Steal the legacy key reference from the temporary copy */
ret = pk->legacy_cache_pkey.ptr = tmp_copy->pkey.ptr;
tmp_copy->pkey.ptr = NULL;
}
if (!CRYPTO_THREAD_unlock(pk->lock)) {
ret = NULL;
goto err;
}
err:
EVP_PKEY_free(tmp_copy);
return ret;
}
#endif /* FIPS_MODULE */
int EVP_PKEY_get_bn_param(const EVP_PKEY *pkey, const char *key_name,
BIGNUM **bn)
{
int ret = 0;
OSSL_PARAM params[2];
unsigned char buffer[2048];
unsigned char *buf = NULL;
size_t buf_sz = 0;
if (key_name == NULL
|| bn == NULL)
return 0;
memset(buffer, 0, sizeof(buffer));
params[0] = OSSL_PARAM_construct_BN(key_name, buffer, sizeof(buffer));
params[1] = OSSL_PARAM_construct_end();
if (!EVP_PKEY_get_params(pkey, params)) {
if (!OSSL_PARAM_modified(params) || params[0].return_size == 0)
return 0;
buf_sz = params[0].return_size;
/*
* If it failed because the buffer was too small then allocate the
* required buffer size and retry.
*/
buf = OPENSSL_zalloc(buf_sz);
if (buf == NULL)
return 0;
params[0].data = buf;
params[0].data_size = buf_sz;
if (!EVP_PKEY_get_params(pkey, params))
goto err;
}
/* Fail if the param was not found */
if (!OSSL_PARAM_modified(params))
goto err;
ret = OSSL_PARAM_get_BN(params, bn);
err:
if (buf != NULL) {
if (OSSL_PARAM_modified(params))
OPENSSL_clear_free(buf, buf_sz);
else
OPENSSL_free(buf);
} else if (OSSL_PARAM_modified(params)) {
OPENSSL_cleanse(buffer, params[0].data_size);
}
return ret;
}
int EVP_PKEY_get_octet_string_param(const EVP_PKEY *pkey, const char *key_name,
unsigned char *buf, size_t max_buf_sz,
size_t *out_len)
{
OSSL_PARAM params[2];
int ret1 = 0, ret2 = 0;
if (key_name == NULL)
return 0;
params[0] = OSSL_PARAM_construct_octet_string(key_name, buf, max_buf_sz);
params[1] = OSSL_PARAM_construct_end();
if ((ret1 = EVP_PKEY_get_params(pkey, params)))
ret2 = OSSL_PARAM_modified(params);
if (ret2 && out_len != NULL)
*out_len = params[0].return_size;
return ret1 && ret2;
}
int EVP_PKEY_get_utf8_string_param(const EVP_PKEY *pkey, const char *key_name,
char *str, size_t max_buf_sz,
size_t *out_len)
{
OSSL_PARAM params[2];
int ret1 = 0, ret2 = 0;
if (key_name == NULL)
return 0;
params[0] = OSSL_PARAM_construct_utf8_string(key_name, str, max_buf_sz);
params[1] = OSSL_PARAM_construct_end();
if ((ret1 = EVP_PKEY_get_params(pkey, params)))
ret2 = OSSL_PARAM_modified(params);
if (ret2 && out_len != NULL)
*out_len = params[0].return_size;
if (ret2 && params[0].return_size == max_buf_sz)
/* There was no space for a NUL byte */
return 0;
/* Add a terminating NUL byte for good measure */
if (ret2 && str != NULL)
str[params[0].return_size] = '\0';
return ret1 && ret2;
}
int EVP_PKEY_get_int_param(const EVP_PKEY *pkey, const char *key_name,
int *out)
{
OSSL_PARAM params[2];
if (key_name == NULL)
return 0;
params[0] = OSSL_PARAM_construct_int(key_name, out);
params[1] = OSSL_PARAM_construct_end();
return EVP_PKEY_get_params(pkey, params)
&& OSSL_PARAM_modified(params);
}
int EVP_PKEY_get_size_t_param(const EVP_PKEY *pkey, const char *key_name,
size_t *out)
{
OSSL_PARAM params[2];
if (key_name == NULL)
return 0;
params[0] = OSSL_PARAM_construct_size_t(key_name, out);
params[1] = OSSL_PARAM_construct_end();
return EVP_PKEY_get_params(pkey, params)
&& OSSL_PARAM_modified(params);
}
int EVP_PKEY_set_int_param(EVP_PKEY *pkey, const char *key_name, int in)
{
OSSL_PARAM params[2];
if (key_name == NULL)
return 0;
params[0] = OSSL_PARAM_construct_int(key_name, &in);
params[1] = OSSL_PARAM_construct_end();
return EVP_PKEY_set_params(pkey, params);
}
int EVP_PKEY_set_size_t_param(EVP_PKEY *pkey, const char *key_name, size_t in)
{
OSSL_PARAM params[2];
if (key_name == NULL)
return 0;
params[0] = OSSL_PARAM_construct_size_t(key_name, &in);
params[1] = OSSL_PARAM_construct_end();
return EVP_PKEY_set_params(pkey, params);
}
int EVP_PKEY_set_bn_param(EVP_PKEY *pkey, const char *key_name,
const BIGNUM *bn)
{
OSSL_PARAM params[2];
unsigned char buffer[2048];
int bsize = 0;
if (key_name == NULL
|| bn == NULL
|| pkey == NULL
|| !evp_pkey_is_assigned(pkey))
return 0;
bsize = BN_num_bytes(bn);
if (!ossl_assert(bsize <= (int)sizeof(buffer)))
return 0;
if (BN_bn2nativepad(bn, buffer, bsize) < 0)
return 0;
params[0] = OSSL_PARAM_construct_BN(key_name, buffer, bsize);
params[1] = OSSL_PARAM_construct_end();
return EVP_PKEY_set_params(pkey, params);
}
int EVP_PKEY_set_utf8_string_param(EVP_PKEY *pkey, const char *key_name,
const char *str)
{
OSSL_PARAM params[2];
if (key_name == NULL)
return 0;
params[0] = OSSL_PARAM_construct_utf8_string(key_name, (char *)str, 0);
params[1] = OSSL_PARAM_construct_end();
return EVP_PKEY_set_params(pkey, params);
}
int EVP_PKEY_set_octet_string_param(EVP_PKEY *pkey, const char *key_name,
const unsigned char *buf, size_t bsize)
{
OSSL_PARAM params[2];
if (key_name == NULL)
return 0;
params[0] = OSSL_PARAM_construct_octet_string(key_name,
(unsigned char *)buf, bsize);
params[1] = OSSL_PARAM_construct_end();
return EVP_PKEY_set_params(pkey, params);
}
const OSSL_PARAM *EVP_PKEY_settable_params(const EVP_PKEY *pkey)
{
return (pkey != NULL && evp_pkey_is_provided(pkey))
? EVP_KEYMGMT_settable_params(pkey->keymgmt)
: NULL;
}
int EVP_PKEY_set_params(EVP_PKEY *pkey, OSSL_PARAM params[])
{
if (pkey != NULL) {
if (evp_pkey_is_provided(pkey)) {
pkey->dirty_cnt++;
return evp_keymgmt_set_params(pkey->keymgmt, pkey->keydata, params);
}
#ifndef FIPS_MODULE
/*
* We will hopefully never find the need to set individual data in
* EVP_PKEYs with a legacy internal key, but we can't be entirely
* sure. This bit of code can be enabled if we find the need. If
* not, it can safely be removed when #legacy support is removed.
*/
# if 0
else if (evp_pkey_is_legacy(pkey)) {
return evp_pkey_set_params_to_ctrl(pkey, params);
}
# endif
#endif
}
ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_KEY);
return 0;
}
const OSSL_PARAM *EVP_PKEY_gettable_params(const EVP_PKEY *pkey)
{
return (pkey != NULL && evp_pkey_is_provided(pkey))
? EVP_KEYMGMT_gettable_params(pkey->keymgmt)
: NULL;
}
int EVP_PKEY_get_params(const EVP_PKEY *pkey, OSSL_PARAM params[])
{
if (pkey != NULL) {
if (evp_pkey_is_provided(pkey))
return evp_keymgmt_get_params(pkey->keymgmt, pkey->keydata, params) > 0;
#ifndef FIPS_MODULE
else if (evp_pkey_is_legacy(pkey))
return evp_pkey_get_params_to_ctrl(pkey, params) > 0;
#endif
}
ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_KEY);
return 0;
}
#ifndef FIPS_MODULE
int EVP_PKEY_get_ec_point_conv_form(const EVP_PKEY *pkey)
{
char name[80];
size_t name_len;
if (pkey == NULL)
return 0;
if (pkey->keymgmt == NULL
|| pkey->keydata == NULL) {
# ifndef OPENSSL_NO_EC
/* Might work through the legacy route */
const EC_KEY *ec = EVP_PKEY_get0_EC_KEY(pkey);
if (ec == NULL)
return 0;
return EC_KEY_get_conv_form(ec);
# else
return 0;
# endif
}
if (!EVP_PKEY_get_utf8_string_param(pkey,
OSSL_PKEY_PARAM_EC_POINT_CONVERSION_FORMAT,
name, sizeof(name), &name_len))
return 0;
if (strcmp(name, "uncompressed") == 0)
return POINT_CONVERSION_UNCOMPRESSED;
if (strcmp(name, "compressed") == 0)
return POINT_CONVERSION_COMPRESSED;
if (strcmp(name, "hybrid") == 0)
return POINT_CONVERSION_HYBRID;
return 0;
}
int EVP_PKEY_get_field_type(const EVP_PKEY *pkey)
{
char fstr[80];
size_t fstrlen;
if (pkey == NULL)
return 0;
if (pkey->keymgmt == NULL
|| pkey->keydata == NULL) {
# ifndef OPENSSL_NO_EC
/* Might work through the legacy route */
const EC_KEY *ec = EVP_PKEY_get0_EC_KEY(pkey);
const EC_GROUP *grp;
if (ec == NULL)
return 0;
grp = EC_KEY_get0_group(ec);
if (grp == NULL)
return 0;
return EC_GROUP_get_field_type(grp);
# else
return 0;
# endif
}
if (!EVP_PKEY_get_utf8_string_param(pkey, OSSL_PKEY_PARAM_EC_FIELD_TYPE,
fstr, sizeof(fstr), &fstrlen))
return 0;
if (strcmp(fstr, SN_X9_62_prime_field) == 0)
return NID_X9_62_prime_field;
else if (strcmp(fstr, SN_X9_62_characteristic_two_field))
return NID_X9_62_characteristic_two_field;
return 0;
}
#endif
diff --git a/crypto/openssl/crypto/evp/pmeth_lib.c b/crypto/openssl/crypto/evp/pmeth_lib.c
index ba1971ce461d..cffd88725c85 100644
--- a/crypto/openssl/crypto/evp/pmeth_lib.c
+++ b/crypto/openssl/crypto/evp/pmeth_lib.c
@@ -1,2069 +1,2134 @@
/*
- * Copyright 2006-2023 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2006-2024 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
*/
/*
* Low level key APIs (DH etc) are deprecated for public use, but still ok for
* internal use.
*/
#include "internal/deprecated.h"
#include <stdio.h>
#include <stdlib.h>
#ifndef FIPS_MODULE
# include <openssl/engine.h>
#endif
#include <openssl/evp.h>
#include <openssl/core_names.h>
#include <openssl/dh.h>
#include <openssl/rsa.h>
#include <openssl/kdf.h>
#include "internal/cryptlib.h"
#ifndef FIPS_MODULE
# include "crypto/asn1.h"
#endif
#include "crypto/evp.h"
#include "crypto/dh.h"
#include "crypto/ec.h"
#include "internal/ffc.h"
#include "internal/numbers.h"
#include "internal/provider.h"
#include "evp_local.h"
#ifndef FIPS_MODULE
static int evp_pkey_ctx_store_cached_data(EVP_PKEY_CTX *ctx,
int keytype, int optype,
int cmd, const char *name,
const void *data, size_t data_len);
static void evp_pkey_ctx_free_cached_data(EVP_PKEY_CTX *ctx,
int cmd, const char *name);
static void evp_pkey_ctx_free_all_cached_data(EVP_PKEY_CTX *ctx);
typedef const EVP_PKEY_METHOD *(*pmeth_fn)(void);
typedef int sk_cmp_fn_type(const char *const *a, const char *const *b);
static STACK_OF(EVP_PKEY_METHOD) *app_pkey_methods = NULL;
/* This array needs to be in order of NIDs */
static pmeth_fn standard_methods[] = {
ossl_rsa_pkey_method,
# ifndef OPENSSL_NO_DH
ossl_dh_pkey_method,
# endif
# ifndef OPENSSL_NO_DSA
ossl_dsa_pkey_method,
# endif
# ifndef OPENSSL_NO_EC
ossl_ec_pkey_method,
# endif
ossl_rsa_pss_pkey_method,
# ifndef OPENSSL_NO_DH
ossl_dhx_pkey_method,
# endif
# ifndef OPENSSL_NO_EC
ossl_ecx25519_pkey_method,
ossl_ecx448_pkey_method,
# endif
# ifndef OPENSSL_NO_EC
ossl_ed25519_pkey_method,
ossl_ed448_pkey_method,
# endif
};
DECLARE_OBJ_BSEARCH_CMP_FN(const EVP_PKEY_METHOD *, pmeth_fn, pmeth_func);
static int pmeth_func_cmp(const EVP_PKEY_METHOD *const *a, pmeth_fn const *b)
{
return ((*a)->pkey_id - ((**b)())->pkey_id);
}
IMPLEMENT_OBJ_BSEARCH_CMP_FN(const EVP_PKEY_METHOD *, pmeth_fn, pmeth_func);
static int pmeth_cmp(const EVP_PKEY_METHOD *const *a,
const EVP_PKEY_METHOD *const *b)
{
return ((*a)->pkey_id - (*b)->pkey_id);
}
static const EVP_PKEY_METHOD *evp_pkey_meth_find_added_by_application(int type)
{
if (app_pkey_methods != NULL) {
int idx;
EVP_PKEY_METHOD tmp;
tmp.pkey_id = type;
idx = sk_EVP_PKEY_METHOD_find(app_pkey_methods, &tmp);
if (idx >= 0)
return sk_EVP_PKEY_METHOD_value(app_pkey_methods, idx);
}
return NULL;
}
const EVP_PKEY_METHOD *EVP_PKEY_meth_find(int type)
{
pmeth_fn *ret;
EVP_PKEY_METHOD tmp;
const EVP_PKEY_METHOD *t;
if ((t = evp_pkey_meth_find_added_by_application(type)) != NULL)
return t;
tmp.pkey_id = type;
t = &tmp;
ret = OBJ_bsearch_pmeth_func(&t, standard_methods,
OSSL_NELEM(standard_methods));
if (ret == NULL || *ret == NULL)
return NULL;
return (**ret)();
}
EVP_PKEY_METHOD *EVP_PKEY_meth_new(int id, int flags)
{
EVP_PKEY_METHOD *pmeth;
pmeth = OPENSSL_zalloc(sizeof(*pmeth));
if (pmeth == NULL) {
ERR_raise(ERR_LIB_EVP, ERR_R_MALLOC_FAILURE);
return NULL;
}
pmeth->pkey_id = id;
pmeth->flags = flags | EVP_PKEY_FLAG_DYNAMIC;
return pmeth;
}
static void help_get_legacy_alg_type_from_keymgmt(const char *keytype,
void *arg)
{
int *type = arg;
if (*type == NID_undef)
*type = evp_pkey_name2type(keytype);
}
static int get_legacy_alg_type_from_keymgmt(const EVP_KEYMGMT *keymgmt)
{
int type = NID_undef;
EVP_KEYMGMT_names_do_all(keymgmt, help_get_legacy_alg_type_from_keymgmt,
&type);
return type;
}
#endif /* FIPS_MODULE */
int evp_pkey_ctx_state(const EVP_PKEY_CTX *ctx)
{
if (ctx->operation == EVP_PKEY_OP_UNDEFINED)
return EVP_PKEY_STATE_UNKNOWN;
if ((EVP_PKEY_CTX_IS_DERIVE_OP(ctx)
&& ctx->op.kex.algctx != NULL)
|| (EVP_PKEY_CTX_IS_SIGNATURE_OP(ctx)
&& ctx->op.sig.algctx != NULL)
|| (EVP_PKEY_CTX_IS_ASYM_CIPHER_OP(ctx)
&& ctx->op.ciph.algctx != NULL)
|| (EVP_PKEY_CTX_IS_GEN_OP(ctx)
&& ctx->op.keymgmt.genctx != NULL)
|| (EVP_PKEY_CTX_IS_KEM_OP(ctx)
&& ctx->op.encap.algctx != NULL))
return EVP_PKEY_STATE_PROVIDER;
return EVP_PKEY_STATE_LEGACY;
}
static EVP_PKEY_CTX *int_ctx_new(OSSL_LIB_CTX *libctx,
EVP_PKEY *pkey, ENGINE *e,
const char *keytype, const char *propquery,
int id)
{
EVP_PKEY_CTX *ret = NULL;
const EVP_PKEY_METHOD *pmeth = NULL, *app_pmeth = NULL;
EVP_KEYMGMT *keymgmt = NULL;
/* Code below to be removed when legacy support is dropped. */
/* BEGIN legacy */
if (id == -1) {
if (pkey != NULL && !evp_pkey_is_provided(pkey)) {
id = pkey->type;
} else {
if (pkey != NULL) {
/* Must be provided if we get here */
keytype = EVP_KEYMGMT_get0_name(pkey->keymgmt);
}
#ifndef FIPS_MODULE
if (keytype != NULL) {
id = evp_pkey_name2type(keytype);
if (id == NID_undef)
id = -1;
}
#endif
}
}
/* If no ID was found here, we can only resort to find a keymgmt */
if (id == -1) {
#ifndef FIPS_MODULE
/* Using engine with a key without id will not work */
if (e != NULL) {
ERR_raise(ERR_LIB_EVP, EVP_R_UNSUPPORTED_ALGORITHM);
return NULL;
}
#endif
goto common;
}
#ifndef FIPS_MODULE
/*
* Here, we extract what information we can for the purpose of
* supporting usage with implementations from providers, to make
* for a smooth transition from legacy stuff to provider based stuff.
*
* If an engine is given, this is entirely legacy, and we should not
* pretend anything else, so we clear the name.
*/
if (e != NULL)
keytype = NULL;
if (e == NULL && (pkey == NULL || pkey->foreign == 0))
keytype = OBJ_nid2sn(id);
# ifndef OPENSSL_NO_ENGINE
if (e == NULL && pkey != NULL)
e = pkey->pmeth_engine != NULL ? pkey->pmeth_engine : pkey->engine;
/* Try to find an ENGINE which implements this method */
if (e != NULL) {
if (!ENGINE_init(e)) {
ERR_raise(ERR_LIB_EVP, ERR_R_ENGINE_LIB);
return NULL;
}
} else {
e = ENGINE_get_pkey_meth_engine(id);
}
/*
* If an ENGINE handled this method look it up. Otherwise use internal
* tables.
*/
if (e != NULL)
pmeth = ENGINE_get_pkey_meth(e, id);
else
# endif /* OPENSSL_NO_ENGINE */
if (pkey != NULL && pkey->foreign)
pmeth = EVP_PKEY_meth_find(id);
else
app_pmeth = pmeth = evp_pkey_meth_find_added_by_application(id);
/* END legacy */
#endif /* FIPS_MODULE */
common:
/*
* If there's no engine and no app supplied pmeth and there's a name, we try
* fetching a provider implementation.
*/
if (e == NULL && app_pmeth == NULL && keytype != NULL) {
/*
* If |pkey| is given and is provided, we take a reference to its
* keymgmt. Otherwise, we fetch one for the keytype we got. This
* is to ensure that operation init functions can access what they
* need through this single pointer.
*/
if (pkey != NULL && pkey->keymgmt != NULL) {
if (!EVP_KEYMGMT_up_ref(pkey->keymgmt))
ERR_raise(ERR_LIB_EVP, EVP_R_INITIALIZATION_ERROR);
else
keymgmt = pkey->keymgmt;
} else {
keymgmt = EVP_KEYMGMT_fetch(libctx, keytype, propquery);
}
if (keymgmt == NULL)
return NULL; /* EVP_KEYMGMT_fetch() recorded an error */
#ifndef FIPS_MODULE
/*
* Chase down the legacy NID, as that might be needed for diverse
* purposes, such as ensure that EVP_PKEY_type() can return sensible
* values. We go through all keymgmt names, because the keytype
* that's passed to this function doesn't necessarily translate
* directly.
*/
if (keymgmt != NULL) {
int tmp_id = get_legacy_alg_type_from_keymgmt(keymgmt);
if (tmp_id != NID_undef) {
if (id == -1) {
id = tmp_id;
} else {
/*
* It really really shouldn't differ. If it still does,
* something is very wrong.
*/
if (!ossl_assert(id == tmp_id)) {
ERR_raise(ERR_LIB_EVP, ERR_R_INTERNAL_ERROR);
EVP_KEYMGMT_free(keymgmt);
return NULL;
}
}
}
}
#endif
}
if (pmeth == NULL && keymgmt == NULL) {
ERR_raise(ERR_LIB_EVP, EVP_R_UNSUPPORTED_ALGORITHM);
} else {
ret = OPENSSL_zalloc(sizeof(*ret));
if (ret == NULL)
ERR_raise(ERR_LIB_EVP, ERR_R_MALLOC_FAILURE);
}
#if !defined(OPENSSL_NO_ENGINE) && !defined(FIPS_MODULE)
if ((ret == NULL || pmeth == NULL) && e != NULL)
ENGINE_finish(e);
#endif
if (ret == NULL) {
EVP_KEYMGMT_free(keymgmt);
return NULL;
}
if (propquery != NULL) {
ret->propquery = OPENSSL_strdup(propquery);
if (ret->propquery == NULL) {
OPENSSL_free(ret);
EVP_KEYMGMT_free(keymgmt);
return NULL;
}
}
ret->libctx = libctx;
ret->keytype = keytype;
ret->keymgmt = keymgmt;
ret->legacy_keytype = id;
ret->engine = e;
ret->pmeth = pmeth;
ret->operation = EVP_PKEY_OP_UNDEFINED;
ret->pkey = pkey;
if (pkey != NULL)
EVP_PKEY_up_ref(pkey);
if (pmeth != NULL && pmeth->init != NULL) {
if (pmeth->init(ret) <= 0) {
ret->pmeth = NULL;
EVP_PKEY_CTX_free(ret);
return NULL;
}
}
return ret;
}
/*- All methods below can also be used in FIPS_MODULE */
EVP_PKEY_CTX *EVP_PKEY_CTX_new_from_name(OSSL_LIB_CTX *libctx,
const char *name,
const char *propquery)
{
return int_ctx_new(libctx, NULL, NULL, name, propquery, -1);
}
EVP_PKEY_CTX *EVP_PKEY_CTX_new_from_pkey(OSSL_LIB_CTX *libctx, EVP_PKEY *pkey,
const char *propquery)
{
return int_ctx_new(libctx, pkey, NULL, NULL, propquery, -1);
}
void evp_pkey_ctx_free_old_ops(EVP_PKEY_CTX *ctx)
{
if (EVP_PKEY_CTX_IS_SIGNATURE_OP(ctx)) {
if (ctx->op.sig.algctx != NULL && ctx->op.sig.signature != NULL)
ctx->op.sig.signature->freectx(ctx->op.sig.algctx);
EVP_SIGNATURE_free(ctx->op.sig.signature);
ctx->op.sig.algctx = NULL;
ctx->op.sig.signature = NULL;
} else if (EVP_PKEY_CTX_IS_DERIVE_OP(ctx)) {
if (ctx->op.kex.algctx != NULL && ctx->op.kex.exchange != NULL)
ctx->op.kex.exchange->freectx(ctx->op.kex.algctx);
EVP_KEYEXCH_free(ctx->op.kex.exchange);
ctx->op.kex.algctx = NULL;
ctx->op.kex.exchange = NULL;
} else if (EVP_PKEY_CTX_IS_KEM_OP(ctx)) {
if (ctx->op.encap.algctx != NULL && ctx->op.encap.kem != NULL)
ctx->op.encap.kem->freectx(ctx->op.encap.algctx);
EVP_KEM_free(ctx->op.encap.kem);
ctx->op.encap.algctx = NULL;
ctx->op.encap.kem = NULL;
}
else if (EVP_PKEY_CTX_IS_ASYM_CIPHER_OP(ctx)) {
if (ctx->op.ciph.algctx != NULL && ctx->op.ciph.cipher != NULL)
ctx->op.ciph.cipher->freectx(ctx->op.ciph.algctx);
EVP_ASYM_CIPHER_free(ctx->op.ciph.cipher);
ctx->op.ciph.algctx = NULL;
ctx->op.ciph.cipher = NULL;
} else if (EVP_PKEY_CTX_IS_GEN_OP(ctx)) {
if (ctx->op.keymgmt.genctx != NULL && ctx->keymgmt != NULL)
evp_keymgmt_gen_cleanup(ctx->keymgmt, ctx->op.keymgmt.genctx);
}
}
void EVP_PKEY_CTX_free(EVP_PKEY_CTX *ctx)
{
if (ctx == NULL)
return;
if (ctx->pmeth && ctx->pmeth->cleanup)
ctx->pmeth->cleanup(ctx);
evp_pkey_ctx_free_old_ops(ctx);
#ifndef FIPS_MODULE
evp_pkey_ctx_free_all_cached_data(ctx);
#endif
EVP_KEYMGMT_free(ctx->keymgmt);
OPENSSL_free(ctx->propquery);
EVP_PKEY_free(ctx->pkey);
EVP_PKEY_free(ctx->peerkey);
#if !defined(OPENSSL_NO_ENGINE) && !defined(FIPS_MODULE)
ENGINE_finish(ctx->engine);
#endif
BN_free(ctx->rsa_pubexp);
OPENSSL_free(ctx);
}
#ifndef FIPS_MODULE
void EVP_PKEY_meth_get0_info(int *ppkey_id, int *pflags,
const EVP_PKEY_METHOD *meth)
{
if (ppkey_id)
*ppkey_id = meth->pkey_id;
if (pflags)
*pflags = meth->flags;
}
void EVP_PKEY_meth_copy(EVP_PKEY_METHOD *dst, const EVP_PKEY_METHOD *src)
{
int pkey_id = dst->pkey_id;
int flags = dst->flags;
*dst = *src;
/* We only copy the function pointers so restore the other values */
dst->pkey_id = pkey_id;
dst->flags = flags;
}
void EVP_PKEY_meth_free(EVP_PKEY_METHOD *pmeth)
{
if (pmeth && (pmeth->flags & EVP_PKEY_FLAG_DYNAMIC))
OPENSSL_free(pmeth);
}
EVP_PKEY_CTX *EVP_PKEY_CTX_new(EVP_PKEY *pkey, ENGINE *e)
{
return int_ctx_new(NULL, pkey, e, NULL, NULL, -1);
}
EVP_PKEY_CTX *EVP_PKEY_CTX_new_id(int id, ENGINE *e)
{
return int_ctx_new(NULL, NULL, e, NULL, NULL, id);
}
EVP_PKEY_CTX *EVP_PKEY_CTX_dup(const EVP_PKEY_CTX *pctx)
{
EVP_PKEY_CTX *rctx;
# ifndef OPENSSL_NO_ENGINE
/* Make sure it's safe to copy a pkey context using an ENGINE */
if (pctx->engine && !ENGINE_init(pctx->engine)) {
ERR_raise(ERR_LIB_EVP, ERR_R_ENGINE_LIB);
return 0;
}
# endif
rctx = OPENSSL_zalloc(sizeof(*rctx));
if (rctx == NULL) {
ERR_raise(ERR_LIB_EVP, ERR_R_MALLOC_FAILURE);
return NULL;
}
if (pctx->pkey != NULL)
EVP_PKEY_up_ref(pctx->pkey);
rctx->pkey = pctx->pkey;
rctx->operation = pctx->operation;
rctx->libctx = pctx->libctx;
rctx->keytype = pctx->keytype;
rctx->propquery = NULL;
if (pctx->propquery != NULL) {
rctx->propquery = OPENSSL_strdup(pctx->propquery);
if (rctx->propquery == NULL)
goto err;
}
rctx->legacy_keytype = pctx->legacy_keytype;
if (EVP_PKEY_CTX_IS_DERIVE_OP(pctx)) {
if (pctx->op.kex.exchange != NULL) {
rctx->op.kex.exchange = pctx->op.kex.exchange;
if (!EVP_KEYEXCH_up_ref(rctx->op.kex.exchange))
goto err;
}
if (pctx->op.kex.algctx != NULL) {
if (!ossl_assert(pctx->op.kex.exchange != NULL))
goto err;
if (pctx->op.kex.exchange->dupctx != NULL)
rctx->op.kex.algctx
= pctx->op.kex.exchange->dupctx(pctx->op.kex.algctx);
if (rctx->op.kex.algctx == NULL) {
EVP_KEYEXCH_free(rctx->op.kex.exchange);
rctx->op.kex.exchange = NULL;
goto err;
}
return rctx;
}
} else if (EVP_PKEY_CTX_IS_SIGNATURE_OP(pctx)) {
if (pctx->op.sig.signature != NULL) {
rctx->op.sig.signature = pctx->op.sig.signature;
if (!EVP_SIGNATURE_up_ref(rctx->op.sig.signature))
goto err;
}
if (pctx->op.sig.algctx != NULL) {
if (!ossl_assert(pctx->op.sig.signature != NULL))
goto err;
if (pctx->op.sig.signature->dupctx != NULL)
rctx->op.sig.algctx
= pctx->op.sig.signature->dupctx(pctx->op.sig.algctx);
if (rctx->op.sig.algctx == NULL) {
EVP_SIGNATURE_free(rctx->op.sig.signature);
rctx->op.sig.signature = NULL;
goto err;
}
return rctx;
}
} else if (EVP_PKEY_CTX_IS_ASYM_CIPHER_OP(pctx)) {
if (pctx->op.ciph.cipher != NULL) {
rctx->op.ciph.cipher = pctx->op.ciph.cipher;
if (!EVP_ASYM_CIPHER_up_ref(rctx->op.ciph.cipher))
goto err;
}
if (pctx->op.ciph.algctx != NULL) {
if (!ossl_assert(pctx->op.ciph.cipher != NULL))
goto err;
if (pctx->op.ciph.cipher->dupctx != NULL)
rctx->op.ciph.algctx
= pctx->op.ciph.cipher->dupctx(pctx->op.ciph.algctx);
if (rctx->op.ciph.algctx == NULL) {
EVP_ASYM_CIPHER_free(rctx->op.ciph.cipher);
rctx->op.ciph.cipher = NULL;
goto err;
}
return rctx;
}
} else if (EVP_PKEY_CTX_IS_KEM_OP(pctx)) {
if (pctx->op.encap.kem != NULL) {
rctx->op.encap.kem = pctx->op.encap.kem;
if (!EVP_KEM_up_ref(rctx->op.encap.kem))
goto err;
}
if (pctx->op.encap.algctx != NULL) {
if (!ossl_assert(pctx->op.encap.kem != NULL))
goto err;
if (pctx->op.encap.kem->dupctx != NULL)
rctx->op.encap.algctx
= pctx->op.encap.kem->dupctx(pctx->op.encap.algctx);
if (rctx->op.encap.algctx == NULL) {
EVP_KEM_free(rctx->op.encap.kem);
rctx->op.encap.kem = NULL;
goto err;
}
return rctx;
}
} else if (EVP_PKEY_CTX_IS_GEN_OP(pctx)) {
/* Not supported - This would need a gen_dupctx() to work */
goto err;
}
rctx->pmeth = pctx->pmeth;
# ifndef OPENSSL_NO_ENGINE
rctx->engine = pctx->engine;
# endif
if (pctx->peerkey != NULL)
EVP_PKEY_up_ref(pctx->peerkey);
rctx->peerkey = pctx->peerkey;
if (pctx->pmeth == NULL) {
if (rctx->operation == EVP_PKEY_OP_UNDEFINED) {
EVP_KEYMGMT *tmp_keymgmt = pctx->keymgmt;
void *provkey;
provkey = evp_pkey_export_to_provider(pctx->pkey, pctx->libctx,
&tmp_keymgmt, pctx->propquery);
if (provkey == NULL)
goto err;
if (!EVP_KEYMGMT_up_ref(tmp_keymgmt))
goto err;
EVP_KEYMGMT_free(rctx->keymgmt);
rctx->keymgmt = tmp_keymgmt;
return rctx;
}
} else if (pctx->pmeth->copy(rctx, pctx) > 0) {
return rctx;
}
err:
rctx->pmeth = NULL;
EVP_PKEY_CTX_free(rctx);
return NULL;
}
int EVP_PKEY_meth_add0(const EVP_PKEY_METHOD *pmeth)
{
if (app_pkey_methods == NULL) {
app_pkey_methods = sk_EVP_PKEY_METHOD_new(pmeth_cmp);
if (app_pkey_methods == NULL){
ERR_raise(ERR_LIB_EVP, ERR_R_MALLOC_FAILURE);
return 0;
}
}
if (!sk_EVP_PKEY_METHOD_push(app_pkey_methods, pmeth)) {
ERR_raise(ERR_LIB_EVP, ERR_R_MALLOC_FAILURE);
return 0;
}
sk_EVP_PKEY_METHOD_sort(app_pkey_methods);
return 1;
}
void evp_app_cleanup_int(void)
{
if (app_pkey_methods != NULL)
sk_EVP_PKEY_METHOD_pop_free(app_pkey_methods, EVP_PKEY_meth_free);
}
int EVP_PKEY_meth_remove(const EVP_PKEY_METHOD *pmeth)
{
const EVP_PKEY_METHOD *ret;
ret = sk_EVP_PKEY_METHOD_delete_ptr(app_pkey_methods, pmeth);
return ret == NULL ? 0 : 1;
}
size_t EVP_PKEY_meth_get_count(void)
{
size_t rv = OSSL_NELEM(standard_methods);
if (app_pkey_methods)
rv += sk_EVP_PKEY_METHOD_num(app_pkey_methods);
return rv;
}
const EVP_PKEY_METHOD *EVP_PKEY_meth_get0(size_t idx)
{
if (idx < OSSL_NELEM(standard_methods))
return (standard_methods[idx])();
if (app_pkey_methods == NULL)
return NULL;
idx -= OSSL_NELEM(standard_methods);
if (idx >= (size_t)sk_EVP_PKEY_METHOD_num(app_pkey_methods))
return NULL;
return sk_EVP_PKEY_METHOD_value(app_pkey_methods, idx);
}
#endif
int EVP_PKEY_CTX_is_a(EVP_PKEY_CTX *ctx, const char *keytype)
{
#ifndef FIPS_MODULE
if (evp_pkey_ctx_is_legacy(ctx))
return (ctx->pmeth->pkey_id == evp_pkey_name2type(keytype));
#endif
return EVP_KEYMGMT_is_a(ctx->keymgmt, keytype);
}
int EVP_PKEY_CTX_set_params(EVP_PKEY_CTX *ctx, const OSSL_PARAM *params)
{
switch (evp_pkey_ctx_state(ctx)) {
case EVP_PKEY_STATE_PROVIDER:
if (EVP_PKEY_CTX_IS_DERIVE_OP(ctx)
&& ctx->op.kex.exchange != NULL
&& ctx->op.kex.exchange->set_ctx_params != NULL)
return
ctx->op.kex.exchange->set_ctx_params(ctx->op.kex.algctx,
params);
if (EVP_PKEY_CTX_IS_SIGNATURE_OP(ctx)
&& ctx->op.sig.signature != NULL
&& ctx->op.sig.signature->set_ctx_params != NULL)
return
ctx->op.sig.signature->set_ctx_params(ctx->op.sig.algctx,
params);
if (EVP_PKEY_CTX_IS_ASYM_CIPHER_OP(ctx)
&& ctx->op.ciph.cipher != NULL
&& ctx->op.ciph.cipher->set_ctx_params != NULL)
return
ctx->op.ciph.cipher->set_ctx_params(ctx->op.ciph.algctx,
params);
if (EVP_PKEY_CTX_IS_GEN_OP(ctx)
&& ctx->keymgmt != NULL
&& ctx->keymgmt->gen_set_params != NULL)
return
evp_keymgmt_gen_set_params(ctx->keymgmt, ctx->op.keymgmt.genctx,
params);
if (EVP_PKEY_CTX_IS_KEM_OP(ctx)
&& ctx->op.encap.kem != NULL
&& ctx->op.encap.kem->set_ctx_params != NULL)
return
ctx->op.encap.kem->set_ctx_params(ctx->op.encap.algctx,
params);
break;
#ifndef FIPS_MODULE
case EVP_PKEY_STATE_UNKNOWN:
case EVP_PKEY_STATE_LEGACY:
return evp_pkey_ctx_set_params_to_ctrl(ctx, params);
#endif
}
return 0;
}
int EVP_PKEY_CTX_get_params(EVP_PKEY_CTX *ctx, OSSL_PARAM *params)
{
switch (evp_pkey_ctx_state(ctx)) {
case EVP_PKEY_STATE_PROVIDER:
if (EVP_PKEY_CTX_IS_DERIVE_OP(ctx)
&& ctx->op.kex.exchange != NULL
&& ctx->op.kex.exchange->get_ctx_params != NULL)
return
ctx->op.kex.exchange->get_ctx_params(ctx->op.kex.algctx,
params);
if (EVP_PKEY_CTX_IS_SIGNATURE_OP(ctx)
&& ctx->op.sig.signature != NULL
&& ctx->op.sig.signature->get_ctx_params != NULL)
return
ctx->op.sig.signature->get_ctx_params(ctx->op.sig.algctx,
params);
if (EVP_PKEY_CTX_IS_ASYM_CIPHER_OP(ctx)
&& ctx->op.ciph.cipher != NULL
&& ctx->op.ciph.cipher->get_ctx_params != NULL)
return
ctx->op.ciph.cipher->get_ctx_params(ctx->op.ciph.algctx,
params);
if (EVP_PKEY_CTX_IS_KEM_OP(ctx)
&& ctx->op.encap.kem != NULL
&& ctx->op.encap.kem->get_ctx_params != NULL)
return
ctx->op.encap.kem->get_ctx_params(ctx->op.encap.algctx,
params);
break;
#ifndef FIPS_MODULE
case EVP_PKEY_STATE_UNKNOWN:
case EVP_PKEY_STATE_LEGACY:
return evp_pkey_ctx_get_params_to_ctrl(ctx, params);
#endif
}
return 0;
}
#ifndef FIPS_MODULE
const OSSL_PARAM *EVP_PKEY_CTX_gettable_params(const EVP_PKEY_CTX *ctx)
{
void *provctx;
if (EVP_PKEY_CTX_IS_DERIVE_OP(ctx)
&& ctx->op.kex.exchange != NULL
&& ctx->op.kex.exchange->gettable_ctx_params != NULL) {
provctx = ossl_provider_ctx(EVP_KEYEXCH_get0_provider(ctx->op.kex.exchange));
return ctx->op.kex.exchange->gettable_ctx_params(ctx->op.kex.algctx,
provctx);
}
if (EVP_PKEY_CTX_IS_SIGNATURE_OP(ctx)
&& ctx->op.sig.signature != NULL
&& ctx->op.sig.signature->gettable_ctx_params != NULL) {
provctx = ossl_provider_ctx(
EVP_SIGNATURE_get0_provider(ctx->op.sig.signature));
return ctx->op.sig.signature->gettable_ctx_params(ctx->op.sig.algctx,
provctx);
}
if (EVP_PKEY_CTX_IS_ASYM_CIPHER_OP(ctx)
&& ctx->op.ciph.cipher != NULL
&& ctx->op.ciph.cipher->gettable_ctx_params != NULL) {
provctx = ossl_provider_ctx(
EVP_ASYM_CIPHER_get0_provider(ctx->op.ciph.cipher));
return ctx->op.ciph.cipher->gettable_ctx_params(ctx->op.ciph.algctx,
provctx);
}
if (EVP_PKEY_CTX_IS_KEM_OP(ctx)
&& ctx->op.encap.kem != NULL
&& ctx->op.encap.kem->gettable_ctx_params != NULL) {
provctx = ossl_provider_ctx(EVP_KEM_get0_provider(ctx->op.encap.kem));
return ctx->op.encap.kem->gettable_ctx_params(ctx->op.encap.algctx,
provctx);
}
return NULL;
}
const OSSL_PARAM *EVP_PKEY_CTX_settable_params(const EVP_PKEY_CTX *ctx)
{
void *provctx;
if (EVP_PKEY_CTX_IS_DERIVE_OP(ctx)
&& ctx->op.kex.exchange != NULL
&& ctx->op.kex.exchange->settable_ctx_params != NULL) {
provctx = ossl_provider_ctx(EVP_KEYEXCH_get0_provider(ctx->op.kex.exchange));
return ctx->op.kex.exchange->settable_ctx_params(ctx->op.kex.algctx,
provctx);
}
if (EVP_PKEY_CTX_IS_SIGNATURE_OP(ctx)
&& ctx->op.sig.signature != NULL
&& ctx->op.sig.signature->settable_ctx_params != NULL) {
provctx = ossl_provider_ctx(
EVP_SIGNATURE_get0_provider(ctx->op.sig.signature));
return ctx->op.sig.signature->settable_ctx_params(ctx->op.sig.algctx,
provctx);
}
if (EVP_PKEY_CTX_IS_ASYM_CIPHER_OP(ctx)
&& ctx->op.ciph.cipher != NULL
&& ctx->op.ciph.cipher->settable_ctx_params != NULL) {
provctx = ossl_provider_ctx(
EVP_ASYM_CIPHER_get0_provider(ctx->op.ciph.cipher));
return ctx->op.ciph.cipher->settable_ctx_params(ctx->op.ciph.algctx,
provctx);
}
if (EVP_PKEY_CTX_IS_GEN_OP(ctx)
&& ctx->keymgmt != NULL
&& ctx->keymgmt->gen_settable_params != NULL) {
provctx = ossl_provider_ctx(EVP_KEYMGMT_get0_provider(ctx->keymgmt));
return ctx->keymgmt->gen_settable_params(ctx->op.keymgmt.genctx,
provctx);
}
if (EVP_PKEY_CTX_IS_KEM_OP(ctx)
&& ctx->op.encap.kem != NULL
&& ctx->op.encap.kem->settable_ctx_params != NULL) {
provctx = ossl_provider_ctx(EVP_KEM_get0_provider(ctx->op.encap.kem));
return ctx->op.encap.kem->settable_ctx_params(ctx->op.encap.algctx,
provctx);
}
return NULL;
}
/*
* Internal helpers for stricter EVP_PKEY_CTX_{set,get}_params().
*
* Return 1 on success, 0 or negative for errors.
*
* In particular they return -2 if any of the params is not supported.
*
* They are not available in FIPS_MODULE as they depend on
* - EVP_PKEY_CTX_{get,set}_params()
* - EVP_PKEY_CTX_{gettable,settable}_params()
*
*/
int evp_pkey_ctx_set_params_strict(EVP_PKEY_CTX *ctx, OSSL_PARAM *params)
{
if (ctx == NULL || params == NULL)
return 0;
/*
* We only check for provider side EVP_PKEY_CTX. For #legacy, we
* depend on the translation that happens in EVP_PKEY_CTX_set_params()
* call, and that the resulting ctrl call will return -2 if it doesn't
* known the ctrl command number.
*/
if (evp_pkey_ctx_is_provided(ctx)) {
const OSSL_PARAM *settable = EVP_PKEY_CTX_settable_params(ctx);
const OSSL_PARAM *p;
for (p = params; p->key != NULL; p++) {
/* Check the ctx actually understands this parameter */
if (OSSL_PARAM_locate_const(settable, p->key) == NULL )
return -2;
}
}
return EVP_PKEY_CTX_set_params(ctx, params);
}
int evp_pkey_ctx_get_params_strict(EVP_PKEY_CTX *ctx, OSSL_PARAM *params)
{
if (ctx == NULL || params == NULL)
return 0;
/*
* We only check for provider side EVP_PKEY_CTX. For #legacy, we
* depend on the translation that happens in EVP_PKEY_CTX_get_params()
* call, and that the resulting ctrl call will return -2 if it doesn't
* known the ctrl command number.
*/
if (evp_pkey_ctx_is_provided(ctx)) {
const OSSL_PARAM *gettable = EVP_PKEY_CTX_gettable_params(ctx);
const OSSL_PARAM *p;
for (p = params; p->key != NULL; p++ ) {
/* Check the ctx actually understands this parameter */
if (OSSL_PARAM_locate_const(gettable, p->key) == NULL )
return -2;
}
}
return EVP_PKEY_CTX_get_params(ctx, params);
}
int EVP_PKEY_CTX_get_signature_md(EVP_PKEY_CTX *ctx, const EVP_MD **md)
{
OSSL_PARAM sig_md_params[2], *p = sig_md_params;
/* 80 should be big enough */
char name[80] = "";
const EVP_MD *tmp;
if (ctx == NULL || !EVP_PKEY_CTX_IS_SIGNATURE_OP(ctx)) {
ERR_raise(ERR_LIB_EVP, EVP_R_COMMAND_NOT_SUPPORTED);
/* Uses the same return values as EVP_PKEY_CTX_ctrl */
return -2;
}
if (ctx->op.sig.algctx == NULL)
return EVP_PKEY_CTX_ctrl(ctx, -1, EVP_PKEY_OP_TYPE_SIG,
EVP_PKEY_CTRL_GET_MD, 0, (void *)(md));
*p++ = OSSL_PARAM_construct_utf8_string(OSSL_SIGNATURE_PARAM_DIGEST,
name,
sizeof(name));
*p = OSSL_PARAM_construct_end();
if (!EVP_PKEY_CTX_get_params(ctx, sig_md_params))
return 0;
tmp = evp_get_digestbyname_ex(ctx->libctx, name);
if (tmp == NULL)
return 0;
*md = tmp;
return 1;
}
static int evp_pkey_ctx_set_md(EVP_PKEY_CTX *ctx, const EVP_MD *md,
int fallback, const char *param, int op,
int ctrl)
{
OSSL_PARAM md_params[2], *p = md_params;
const char *name;
if (ctx == NULL || (ctx->operation & op) == 0) {
ERR_raise(ERR_LIB_EVP, EVP_R_COMMAND_NOT_SUPPORTED);
/* Uses the same return values as EVP_PKEY_CTX_ctrl */
return -2;
}
if (fallback)
return EVP_PKEY_CTX_ctrl(ctx, -1, op, ctrl, 0, (void *)(md));
if (md == NULL) {
name = "";
} else {
name = EVP_MD_get0_name(md);
}
*p++ = OSSL_PARAM_construct_utf8_string(param,
/*
* Cast away the const. This is read
* only so should be safe
*/
(char *)name, 0);
*p = OSSL_PARAM_construct_end();
return EVP_PKEY_CTX_set_params(ctx, md_params);
}
int EVP_PKEY_CTX_set_signature_md(EVP_PKEY_CTX *ctx, const EVP_MD *md)
{
return evp_pkey_ctx_set_md(ctx, md, ctx->op.sig.algctx == NULL,
OSSL_SIGNATURE_PARAM_DIGEST,
EVP_PKEY_OP_TYPE_SIG, EVP_PKEY_CTRL_MD);
}
int EVP_PKEY_CTX_set_tls1_prf_md(EVP_PKEY_CTX *ctx, const EVP_MD *md)
{
return evp_pkey_ctx_set_md(ctx, md, ctx->op.kex.algctx == NULL,
OSSL_KDF_PARAM_DIGEST,
EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_TLS_MD);
}
static int evp_pkey_ctx_set1_octet_string(EVP_PKEY_CTX *ctx, int fallback,
const char *param, int op, int ctrl,
const unsigned char *data,
int datalen)
{
OSSL_PARAM octet_string_params[2], *p = octet_string_params;
if (ctx == NULL || (ctx->operation & op) == 0) {
ERR_raise(ERR_LIB_EVP, EVP_R_COMMAND_NOT_SUPPORTED);
/* Uses the same return values as EVP_PKEY_CTX_ctrl */
return -2;
}
/* Code below to be removed when legacy support is dropped. */
if (fallback)
return EVP_PKEY_CTX_ctrl(ctx, -1, op, ctrl, datalen, (void *)(data));
/* end of legacy support */
if (datalen < 0) {
ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_LENGTH);
return 0;
}
*p++ = OSSL_PARAM_construct_octet_string(param,
/*
* Cast away the const. This is read
* only so should be safe
*/
(unsigned char *)data,
(size_t)datalen);
*p = OSSL_PARAM_construct_end();
return EVP_PKEY_CTX_set_params(ctx, octet_string_params);
}
+static int evp_pkey_ctx_add1_octet_string(EVP_PKEY_CTX *ctx, int fallback,
+ const char *param, int op, int ctrl,
+ const unsigned char *data,
+ int datalen)
+{
+ OSSL_PARAM os_params[2];
+ unsigned char *info = NULL;
+ size_t info_len = 0;
+ size_t info_alloc = 0;
+ int ret = 0;
+
+ if (ctx == NULL || (ctx->operation & op) == 0) {
+ ERR_raise(ERR_LIB_EVP, EVP_R_COMMAND_NOT_SUPPORTED);
+ /* Uses the same return values as EVP_PKEY_CTX_ctrl */
+ return -2;
+ }
+
+ /* Code below to be removed when legacy support is dropped. */
+ if (fallback)
+ return EVP_PKEY_CTX_ctrl(ctx, -1, op, ctrl, datalen, (void *)(data));
+ /* end of legacy support */
+
+ if (datalen < 0) {
+ ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_LENGTH);
+ return 0;
+ } else if (datalen == 0) {
+ return 1;
+ }
+
+ /* Get the original value length */
+ os_params[0] = OSSL_PARAM_construct_octet_string(param, NULL, 0);
+ os_params[1] = OSSL_PARAM_construct_end();
+
+ if (!EVP_PKEY_CTX_get_params(ctx, os_params))
+ return 0;
+
+ /* Older provider that doesn't support getting this parameter */
+ if (os_params[0].return_size == OSSL_PARAM_UNMODIFIED)
+ return evp_pkey_ctx_set1_octet_string(ctx, fallback, param, op, ctrl, data, datalen);
+
+ info_alloc = os_params[0].return_size + datalen;
+ if (info_alloc == 0)
+ return 0;
+ info = OPENSSL_zalloc(info_alloc);
+ if (info == NULL)
+ return 0;
+ info_len = os_params[0].return_size;
+
+ os_params[0] = OSSL_PARAM_construct_octet_string(param, info, info_alloc);
+
+ /* if we have data, then go get it */
+ if (info_len > 0) {
+ if (!EVP_PKEY_CTX_get_params(ctx, os_params))
+ goto error;
+ }
+
+ /* Copy the input data */
+ memcpy(&info[info_len], data, datalen);
+ ret = EVP_PKEY_CTX_set_params(ctx, os_params);
+
+ error:
+ OPENSSL_clear_free(info, info_alloc);
+ return ret;
+}
+
int EVP_PKEY_CTX_set1_tls1_prf_secret(EVP_PKEY_CTX *ctx,
const unsigned char *sec, int seclen)
{
return evp_pkey_ctx_set1_octet_string(ctx, ctx->op.kex.algctx == NULL,
OSSL_KDF_PARAM_SECRET,
EVP_PKEY_OP_DERIVE,
EVP_PKEY_CTRL_TLS_SECRET,
sec, seclen);
}
int EVP_PKEY_CTX_add1_tls1_prf_seed(EVP_PKEY_CTX *ctx,
const unsigned char *seed, int seedlen)
{
return evp_pkey_ctx_set1_octet_string(ctx, ctx->op.kex.algctx == NULL,
OSSL_KDF_PARAM_SEED,
EVP_PKEY_OP_DERIVE,
EVP_PKEY_CTRL_TLS_SEED,
seed, seedlen);
}
int EVP_PKEY_CTX_set_hkdf_md(EVP_PKEY_CTX *ctx, const EVP_MD *md)
{
return evp_pkey_ctx_set_md(ctx, md, ctx->op.kex.algctx == NULL,
OSSL_KDF_PARAM_DIGEST,
EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_HKDF_MD);
}
int EVP_PKEY_CTX_set1_hkdf_salt(EVP_PKEY_CTX *ctx,
const unsigned char *salt, int saltlen)
{
return evp_pkey_ctx_set1_octet_string(ctx, ctx->op.kex.algctx == NULL,
OSSL_KDF_PARAM_SALT,
EVP_PKEY_OP_DERIVE,
EVP_PKEY_CTRL_HKDF_SALT,
salt, saltlen);
}
int EVP_PKEY_CTX_set1_hkdf_key(EVP_PKEY_CTX *ctx,
const unsigned char *key, int keylen)
{
return evp_pkey_ctx_set1_octet_string(ctx, ctx->op.kex.algctx == NULL,
OSSL_KDF_PARAM_KEY,
EVP_PKEY_OP_DERIVE,
EVP_PKEY_CTRL_HKDF_KEY,
key, keylen);
}
int EVP_PKEY_CTX_add1_hkdf_info(EVP_PKEY_CTX *ctx,
const unsigned char *info, int infolen)
{
- return evp_pkey_ctx_set1_octet_string(ctx, ctx->op.kex.algctx == NULL,
+ return evp_pkey_ctx_add1_octet_string(ctx, ctx->op.kex.algctx == NULL,
OSSL_KDF_PARAM_INFO,
EVP_PKEY_OP_DERIVE,
EVP_PKEY_CTRL_HKDF_INFO,
info, infolen);
}
int EVP_PKEY_CTX_set_hkdf_mode(EVP_PKEY_CTX *ctx, int mode)
{
OSSL_PARAM int_params[2], *p = int_params;
if (ctx == NULL || !EVP_PKEY_CTX_IS_DERIVE_OP(ctx)) {
ERR_raise(ERR_LIB_EVP, EVP_R_COMMAND_NOT_SUPPORTED);
/* Uses the same return values as EVP_PKEY_CTX_ctrl */
return -2;
}
/* Code below to be removed when legacy support is dropped. */
if (ctx->op.kex.algctx == NULL)
return EVP_PKEY_CTX_ctrl(ctx, -1, EVP_PKEY_OP_DERIVE,
EVP_PKEY_CTRL_HKDF_MODE, mode, NULL);
/* end of legacy support */
if (mode < 0) {
ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_VALUE);
return 0;
}
*p++ = OSSL_PARAM_construct_int(OSSL_KDF_PARAM_MODE, &mode);
*p = OSSL_PARAM_construct_end();
return EVP_PKEY_CTX_set_params(ctx, int_params);
}
int EVP_PKEY_CTX_set1_pbe_pass(EVP_PKEY_CTX *ctx, const char *pass,
int passlen)
{
return evp_pkey_ctx_set1_octet_string(ctx, ctx->op.kex.algctx == NULL,
OSSL_KDF_PARAM_PASSWORD,
EVP_PKEY_OP_DERIVE,
EVP_PKEY_CTRL_PASS,
(const unsigned char *)pass, passlen);
}
int EVP_PKEY_CTX_set1_scrypt_salt(EVP_PKEY_CTX *ctx,
const unsigned char *salt, int saltlen)
{
return evp_pkey_ctx_set1_octet_string(ctx, ctx->op.kex.algctx == NULL,
OSSL_KDF_PARAM_SALT,
EVP_PKEY_OP_DERIVE,
EVP_PKEY_CTRL_SCRYPT_SALT,
salt, saltlen);
}
static int evp_pkey_ctx_set_uint64(EVP_PKEY_CTX *ctx, const char *param,
int op, int ctrl, uint64_t val)
{
OSSL_PARAM uint64_params[2], *p = uint64_params;
if (ctx == NULL || !EVP_PKEY_CTX_IS_DERIVE_OP(ctx)) {
ERR_raise(ERR_LIB_EVP, EVP_R_COMMAND_NOT_SUPPORTED);
/* Uses the same return values as EVP_PKEY_CTX_ctrl */
return -2;
}
/* Code below to be removed when legacy support is dropped. */
if (ctx->op.kex.algctx == NULL)
return EVP_PKEY_CTX_ctrl_uint64(ctx, -1, op, ctrl, val);
/* end of legacy support */
*p++ = OSSL_PARAM_construct_uint64(param, &val);
*p = OSSL_PARAM_construct_end();
return EVP_PKEY_CTX_set_params(ctx, uint64_params);
}
int EVP_PKEY_CTX_set_scrypt_N(EVP_PKEY_CTX *ctx, uint64_t n)
{
return evp_pkey_ctx_set_uint64(ctx, OSSL_KDF_PARAM_SCRYPT_N,
EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_SCRYPT_N,
n);
}
int EVP_PKEY_CTX_set_scrypt_r(EVP_PKEY_CTX *ctx, uint64_t r)
{
return evp_pkey_ctx_set_uint64(ctx, OSSL_KDF_PARAM_SCRYPT_R,
EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_SCRYPT_R,
r);
}
int EVP_PKEY_CTX_set_scrypt_p(EVP_PKEY_CTX *ctx, uint64_t p)
{
return evp_pkey_ctx_set_uint64(ctx, OSSL_KDF_PARAM_SCRYPT_P,
EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_SCRYPT_P,
p);
}
int EVP_PKEY_CTX_set_scrypt_maxmem_bytes(EVP_PKEY_CTX *ctx,
uint64_t maxmem_bytes)
{
return evp_pkey_ctx_set_uint64(ctx, OSSL_KDF_PARAM_SCRYPT_MAXMEM,
EVP_PKEY_OP_DERIVE,
EVP_PKEY_CTRL_SCRYPT_MAXMEM_BYTES,
maxmem_bytes);
}
int EVP_PKEY_CTX_set_mac_key(EVP_PKEY_CTX *ctx, const unsigned char *key,
int keylen)
{
return evp_pkey_ctx_set1_octet_string(ctx, ctx->op.keymgmt.genctx == NULL,
OSSL_PKEY_PARAM_PRIV_KEY,
EVP_PKEY_OP_KEYGEN,
EVP_PKEY_CTRL_SET_MAC_KEY,
key, keylen);
}
int EVP_PKEY_CTX_set_kem_op(EVP_PKEY_CTX *ctx, const char *op)
{
OSSL_PARAM params[2], *p = params;
if (ctx == NULL || op == NULL) {
ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_VALUE);
return 0;
}
if (!EVP_PKEY_CTX_IS_KEM_OP(ctx)) {
ERR_raise(ERR_LIB_EVP, EVP_R_COMMAND_NOT_SUPPORTED);
return -2;
}
*p++ = OSSL_PARAM_construct_utf8_string(OSSL_KEM_PARAM_OPERATION,
(char *)op, 0);
*p = OSSL_PARAM_construct_end();
return EVP_PKEY_CTX_set_params(ctx, params);
}
int evp_pkey_ctx_set1_id_prov(EVP_PKEY_CTX *ctx, const void *id, int len)
{
OSSL_PARAM params[2], *p = params;
int ret;
if (!EVP_PKEY_CTX_IS_SIGNATURE_OP(ctx)) {
ERR_raise(ERR_LIB_EVP, EVP_R_COMMAND_NOT_SUPPORTED);
/* Uses the same return values as EVP_PKEY_CTX_ctrl */
return -2;
}
*p++ = OSSL_PARAM_construct_octet_string(OSSL_PKEY_PARAM_DIST_ID,
/*
* Cast away the const. This is
* read only so should be safe
*/
(void *)id, (size_t)len);
*p++ = OSSL_PARAM_construct_end();
ret = evp_pkey_ctx_set_params_strict(ctx, params);
if (ret == -2)
ERR_raise(ERR_LIB_EVP, EVP_R_COMMAND_NOT_SUPPORTED);
return ret;
}
int EVP_PKEY_CTX_set1_id(EVP_PKEY_CTX *ctx, const void *id, int len)
{
return EVP_PKEY_CTX_ctrl(ctx, -1, -1,
EVP_PKEY_CTRL_SET1_ID, (int)len, (void*)(id));
}
static int get1_id_data(EVP_PKEY_CTX *ctx, void *id, size_t *id_len)
{
int ret;
void *tmp_id = NULL;
OSSL_PARAM params[2], *p = params;
if (!EVP_PKEY_CTX_IS_SIGNATURE_OP(ctx)) {
ERR_raise(ERR_LIB_EVP, EVP_R_COMMAND_NOT_SUPPORTED);
/* Uses the same return values as EVP_PKEY_CTX_ctrl */
return -2;
}
*p++ = OSSL_PARAM_construct_octet_ptr(OSSL_PKEY_PARAM_DIST_ID,
&tmp_id, 0);
*p++ = OSSL_PARAM_construct_end();
ret = evp_pkey_ctx_get_params_strict(ctx, params);
if (ret == -2) {
ERR_raise(ERR_LIB_EVP, EVP_R_COMMAND_NOT_SUPPORTED);
} else if (ret > 0) {
size_t tmp_id_len = params[0].return_size;
if (id != NULL)
memcpy(id, tmp_id, tmp_id_len);
if (id_len != NULL)
*id_len = tmp_id_len;
}
return ret;
}
int evp_pkey_ctx_get1_id_prov(EVP_PKEY_CTX *ctx, void *id)
{
return get1_id_data(ctx, id, NULL);
}
int evp_pkey_ctx_get1_id_len_prov(EVP_PKEY_CTX *ctx, size_t *id_len)
{
return get1_id_data(ctx, NULL, id_len);
}
int EVP_PKEY_CTX_get1_id(EVP_PKEY_CTX *ctx, void *id)
{
return EVP_PKEY_CTX_ctrl(ctx, -1, -1, EVP_PKEY_CTRL_GET1_ID, 0, (void*)id);
}
int EVP_PKEY_CTX_get1_id_len(EVP_PKEY_CTX *ctx, size_t *id_len)
{
return EVP_PKEY_CTX_ctrl(ctx, -1, -1,
EVP_PKEY_CTRL_GET1_ID_LEN, 0, (void*)id_len);
}
static int evp_pkey_ctx_ctrl_int(EVP_PKEY_CTX *ctx, int keytype, int optype,
int cmd, int p1, void *p2)
{
int ret = 0;
/*
* If the method has a |digest_custom| function, we can relax the
* operation type check, since this can be called before the operation
* is initialized.
*/
if (ctx->pmeth == NULL || ctx->pmeth->digest_custom == NULL) {
if (ctx->operation == EVP_PKEY_OP_UNDEFINED) {
ERR_raise(ERR_LIB_EVP, EVP_R_NO_OPERATION_SET);
return -1;
}
if ((optype != -1) && !(ctx->operation & optype)) {
ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_OPERATION);
return -1;
}
}
switch (evp_pkey_ctx_state(ctx)) {
case EVP_PKEY_STATE_PROVIDER:
return evp_pkey_ctx_ctrl_to_param(ctx, keytype, optype, cmd, p1, p2);
case EVP_PKEY_STATE_UNKNOWN:
case EVP_PKEY_STATE_LEGACY:
if (ctx->pmeth == NULL || ctx->pmeth->ctrl == NULL) {
ERR_raise(ERR_LIB_EVP, EVP_R_COMMAND_NOT_SUPPORTED);
return -2;
}
if ((keytype != -1) && (ctx->pmeth->pkey_id != keytype))
return -1;
ret = ctx->pmeth->ctrl(ctx, cmd, p1, p2);
if (ret == -2)
ERR_raise(ERR_LIB_EVP, EVP_R_COMMAND_NOT_SUPPORTED);
break;
}
return ret;
}
int EVP_PKEY_CTX_ctrl(EVP_PKEY_CTX *ctx, int keytype, int optype,
int cmd, int p1, void *p2)
{
int ret = 0;
if (ctx == NULL) {
ERR_raise(ERR_LIB_EVP, EVP_R_COMMAND_NOT_SUPPORTED);
return -2;
}
/* If unsupported, we don't want that reported here */
ERR_set_mark();
ret = evp_pkey_ctx_store_cached_data(ctx, keytype, optype,
cmd, NULL, p2, p1);
if (ret == -2) {
ERR_pop_to_mark();
} else {
ERR_clear_last_mark();
/*
* If there was an error, there was an error.
* If the operation isn't initialized yet, we also return, as
* the saved values will be used then anyway.
*/
if (ret < 1 || ctx->operation == EVP_PKEY_OP_UNDEFINED)
return ret;
}
return evp_pkey_ctx_ctrl_int(ctx, keytype, optype, cmd, p1, p2);
}
int EVP_PKEY_CTX_ctrl_uint64(EVP_PKEY_CTX *ctx, int keytype, int optype,
int cmd, uint64_t value)
{
return EVP_PKEY_CTX_ctrl(ctx, keytype, optype, cmd, 0, &value);
}
static int evp_pkey_ctx_ctrl_str_int(EVP_PKEY_CTX *ctx,
const char *name, const char *value)
{
int ret = 0;
if (ctx == NULL) {
ERR_raise(ERR_LIB_EVP, EVP_R_COMMAND_NOT_SUPPORTED);
return -2;
}
switch (evp_pkey_ctx_state(ctx)) {
case EVP_PKEY_STATE_PROVIDER:
return evp_pkey_ctx_ctrl_str_to_param(ctx, name, value);
case EVP_PKEY_STATE_UNKNOWN:
case EVP_PKEY_STATE_LEGACY:
if (ctx == NULL || ctx->pmeth == NULL || ctx->pmeth->ctrl_str == NULL) {
ERR_raise(ERR_LIB_EVP, EVP_R_COMMAND_NOT_SUPPORTED);
return -2;
}
if (strcmp(name, "digest") == 0)
ret = EVP_PKEY_CTX_md(ctx,
EVP_PKEY_OP_TYPE_SIG | EVP_PKEY_OP_TYPE_CRYPT,
EVP_PKEY_CTRL_MD, value);
else
ret = ctx->pmeth->ctrl_str(ctx, name, value);
break;
}
return ret;
}
int EVP_PKEY_CTX_ctrl_str(EVP_PKEY_CTX *ctx,
const char *name, const char *value)
{
int ret = 0;
/* If unsupported, we don't want that reported here */
ERR_set_mark();
ret = evp_pkey_ctx_store_cached_data(ctx, -1, -1, -1,
name, value, strlen(value) + 1);
if (ret == -2) {
ERR_pop_to_mark();
} else {
ERR_clear_last_mark();
/*
* If there was an error, there was an error.
* If the operation isn't initialized yet, we also return, as
* the saved values will be used then anyway.
*/
if (ret < 1 || ctx->operation == EVP_PKEY_OP_UNDEFINED)
return ret;
}
return evp_pkey_ctx_ctrl_str_int(ctx, name, value);
}
static int decode_cmd(int cmd, const char *name)
{
if (cmd == -1) {
/*
* The consequence of the assertion not being true is that this
* function will return -1, which will cause the calling functions
* to signal that the command is unsupported... in non-debug mode.
*/
if (ossl_assert(name != NULL))
if (strcmp(name, "distid") == 0 || strcmp(name, "hexdistid") == 0)
cmd = EVP_PKEY_CTRL_SET1_ID;
}
return cmd;
}
static int evp_pkey_ctx_store_cached_data(EVP_PKEY_CTX *ctx,
int keytype, int optype,
int cmd, const char *name,
const void *data, size_t data_len)
{
/*
* Check that it's one of the supported commands. The ctrl commands
* number cases here must correspond to the cases in the bottom switch
* in this function.
*/
switch (cmd = decode_cmd(cmd, name)) {
case EVP_PKEY_CTRL_SET1_ID:
break;
default:
ERR_raise(ERR_LIB_EVP, EVP_R_COMMAND_NOT_SUPPORTED);
return -2;
}
if (keytype != -1) {
switch (evp_pkey_ctx_state(ctx)) {
case EVP_PKEY_STATE_PROVIDER:
if (ctx->keymgmt == NULL) {
ERR_raise(ERR_LIB_EVP, EVP_R_COMMAND_NOT_SUPPORTED);
return -2;
}
if (!EVP_KEYMGMT_is_a(ctx->keymgmt,
evp_pkey_type2name(keytype))) {
ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_OPERATION);
return -1;
}
break;
case EVP_PKEY_STATE_UNKNOWN:
case EVP_PKEY_STATE_LEGACY:
if (ctx->pmeth == NULL) {
ERR_raise(ERR_LIB_EVP, EVP_R_COMMAND_NOT_SUPPORTED);
return -2;
}
if (EVP_PKEY_type(ctx->pmeth->pkey_id) != EVP_PKEY_type(keytype)) {
ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_OPERATION);
return -1;
}
break;
}
}
if (optype != -1 && (ctx->operation & optype) == 0) {
ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_OPERATION);
return -1;
}
switch (cmd) {
case EVP_PKEY_CTRL_SET1_ID:
evp_pkey_ctx_free_cached_data(ctx, cmd, name);
if (name != NULL) {
ctx->cached_parameters.dist_id_name = OPENSSL_strdup(name);
if (ctx->cached_parameters.dist_id_name == NULL) {
ERR_raise(ERR_LIB_EVP, ERR_R_MALLOC_FAILURE);
return 0;
}
}
if (data_len > 0) {
ctx->cached_parameters.dist_id = OPENSSL_memdup(data, data_len);
if (ctx->cached_parameters.dist_id == NULL) {
ERR_raise(ERR_LIB_EVP, ERR_R_MALLOC_FAILURE);
return 0;
}
}
ctx->cached_parameters.dist_id_set = 1;
ctx->cached_parameters.dist_id_len = data_len;
break;
}
return 1;
}
static void evp_pkey_ctx_free_cached_data(EVP_PKEY_CTX *ctx,
int cmd, const char *name)
{
cmd = decode_cmd(cmd, name);
switch (cmd) {
case EVP_PKEY_CTRL_SET1_ID:
OPENSSL_free(ctx->cached_parameters.dist_id);
OPENSSL_free(ctx->cached_parameters.dist_id_name);
ctx->cached_parameters.dist_id = NULL;
ctx->cached_parameters.dist_id_name = NULL;
break;
}
}
static void evp_pkey_ctx_free_all_cached_data(EVP_PKEY_CTX *ctx)
{
evp_pkey_ctx_free_cached_data(ctx, EVP_PKEY_CTRL_SET1_ID, NULL);
}
int evp_pkey_ctx_use_cached_data(EVP_PKEY_CTX *ctx)
{
int ret = 1;
if (ret && ctx->cached_parameters.dist_id_set) {
const char *name = ctx->cached_parameters.dist_id_name;
const void *val = ctx->cached_parameters.dist_id;
size_t len = ctx->cached_parameters.dist_id_len;
if (name != NULL)
ret = evp_pkey_ctx_ctrl_str_int(ctx, name, val);
else
ret = evp_pkey_ctx_ctrl_int(ctx, -1, ctx->operation,
EVP_PKEY_CTRL_SET1_ID,
(int)len, (void *)val);
}
return ret;
}
OSSL_LIB_CTX *EVP_PKEY_CTX_get0_libctx(EVP_PKEY_CTX *ctx)
{
return ctx->libctx;
}
const char *EVP_PKEY_CTX_get0_propq(const EVP_PKEY_CTX *ctx)
{
return ctx->propquery;
}
const OSSL_PROVIDER *EVP_PKEY_CTX_get0_provider(const EVP_PKEY_CTX *ctx)
{
if (EVP_PKEY_CTX_IS_SIGNATURE_OP(ctx)) {
if (ctx->op.sig.signature != NULL)
return EVP_SIGNATURE_get0_provider(ctx->op.sig.signature);
} else if (EVP_PKEY_CTX_IS_DERIVE_OP(ctx)) {
if (ctx->op.kex.exchange != NULL)
return EVP_KEYEXCH_get0_provider(ctx->op.kex.exchange);
} else if (EVP_PKEY_CTX_IS_KEM_OP(ctx)) {
if (ctx->op.encap.kem != NULL)
return EVP_KEM_get0_provider(ctx->op.encap.kem);
} else if (EVP_PKEY_CTX_IS_ASYM_CIPHER_OP(ctx)) {
if (ctx->op.ciph.cipher != NULL)
return EVP_ASYM_CIPHER_get0_provider(ctx->op.ciph.cipher);
} else if (EVP_PKEY_CTX_IS_GEN_OP(ctx)) {
if (ctx->keymgmt != NULL)
return EVP_KEYMGMT_get0_provider(ctx->keymgmt);
}
return NULL;
}
/* Utility functions to send a string of hex string to a ctrl */
int EVP_PKEY_CTX_str2ctrl(EVP_PKEY_CTX *ctx, int cmd, const char *str)
{
size_t len;
len = strlen(str);
if (len > INT_MAX)
return -1;
return ctx->pmeth->ctrl(ctx, cmd, len, (void *)str);
}
int EVP_PKEY_CTX_hex2ctrl(EVP_PKEY_CTX *ctx, int cmd, const char *hex)
{
unsigned char *bin;
long binlen;
int rv = -1;
bin = OPENSSL_hexstr2buf(hex, &binlen);
if (bin == NULL)
return 0;
if (binlen <= INT_MAX)
rv = ctx->pmeth->ctrl(ctx, cmd, binlen, bin);
OPENSSL_free(bin);
return rv;
}
/* Pass a message digest to a ctrl */
int EVP_PKEY_CTX_md(EVP_PKEY_CTX *ctx, int optype, int cmd, const char *md)
{
const EVP_MD *m;
if (md == NULL || (m = EVP_get_digestbyname(md)) == NULL) {
ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_DIGEST);
return 0;
}
return EVP_PKEY_CTX_ctrl(ctx, -1, optype, cmd, 0, (void *)m);
}
int EVP_PKEY_CTX_get_operation(EVP_PKEY_CTX *ctx)
{
return ctx->operation;
}
void EVP_PKEY_CTX_set0_keygen_info(EVP_PKEY_CTX *ctx, int *dat, int datlen)
{
ctx->keygen_info = dat;
ctx->keygen_info_count = datlen;
}
void EVP_PKEY_CTX_set_data(EVP_PKEY_CTX *ctx, void *data)
{
ctx->data = data;
}
void *EVP_PKEY_CTX_get_data(const EVP_PKEY_CTX *ctx)
{
return ctx->data;
}
EVP_PKEY *EVP_PKEY_CTX_get0_pkey(EVP_PKEY_CTX *ctx)
{
return ctx->pkey;
}
EVP_PKEY *EVP_PKEY_CTX_get0_peerkey(EVP_PKEY_CTX *ctx)
{
return ctx->peerkey;
}
void EVP_PKEY_CTX_set_app_data(EVP_PKEY_CTX *ctx, void *data)
{
ctx->app_data = data;
}
void *EVP_PKEY_CTX_get_app_data(EVP_PKEY_CTX *ctx)
{
return ctx->app_data;
}
void EVP_PKEY_meth_set_init(EVP_PKEY_METHOD *pmeth,
int (*init) (EVP_PKEY_CTX *ctx))
{
pmeth->init = init;
}
void EVP_PKEY_meth_set_copy(EVP_PKEY_METHOD *pmeth,
int (*copy) (EVP_PKEY_CTX *dst,
const EVP_PKEY_CTX *src))
{
pmeth->copy = copy;
}
void EVP_PKEY_meth_set_cleanup(EVP_PKEY_METHOD *pmeth,
void (*cleanup) (EVP_PKEY_CTX *ctx))
{
pmeth->cleanup = cleanup;
}
void EVP_PKEY_meth_set_paramgen(EVP_PKEY_METHOD *pmeth,
int (*paramgen_init) (EVP_PKEY_CTX *ctx),
int (*paramgen) (EVP_PKEY_CTX *ctx,
EVP_PKEY *pkey))
{
pmeth->paramgen_init = paramgen_init;
pmeth->paramgen = paramgen;
}
void EVP_PKEY_meth_set_keygen(EVP_PKEY_METHOD *pmeth,
int (*keygen_init) (EVP_PKEY_CTX *ctx),
int (*keygen) (EVP_PKEY_CTX *ctx,
EVP_PKEY *pkey))
{
pmeth->keygen_init = keygen_init;
pmeth->keygen = keygen;
}
void EVP_PKEY_meth_set_sign(EVP_PKEY_METHOD *pmeth,
int (*sign_init) (EVP_PKEY_CTX *ctx),
int (*sign) (EVP_PKEY_CTX *ctx,
unsigned char *sig, size_t *siglen,
const unsigned char *tbs,
size_t tbslen))
{
pmeth->sign_init = sign_init;
pmeth->sign = sign;
}
void EVP_PKEY_meth_set_verify(EVP_PKEY_METHOD *pmeth,
int (*verify_init) (EVP_PKEY_CTX *ctx),
int (*verify) (EVP_PKEY_CTX *ctx,
const unsigned char *sig,
size_t siglen,
const unsigned char *tbs,
size_t tbslen))
{
pmeth->verify_init = verify_init;
pmeth->verify = verify;
}
void EVP_PKEY_meth_set_verify_recover(EVP_PKEY_METHOD *pmeth,
int (*verify_recover_init) (EVP_PKEY_CTX
*ctx),
int (*verify_recover) (EVP_PKEY_CTX
*ctx,
unsigned char
*sig,
size_t *siglen,
const unsigned
char *tbs,
size_t tbslen))
{
pmeth->verify_recover_init = verify_recover_init;
pmeth->verify_recover = verify_recover;
}
void EVP_PKEY_meth_set_signctx(EVP_PKEY_METHOD *pmeth,
int (*signctx_init) (EVP_PKEY_CTX *ctx,
EVP_MD_CTX *mctx),
int (*signctx) (EVP_PKEY_CTX *ctx,
unsigned char *sig,
size_t *siglen,
EVP_MD_CTX *mctx))
{
pmeth->signctx_init = signctx_init;
pmeth->signctx = signctx;
}
void EVP_PKEY_meth_set_verifyctx(EVP_PKEY_METHOD *pmeth,
int (*verifyctx_init) (EVP_PKEY_CTX *ctx,
EVP_MD_CTX *mctx),
int (*verifyctx) (EVP_PKEY_CTX *ctx,
const unsigned char *sig,
int siglen,
EVP_MD_CTX *mctx))
{
pmeth->verifyctx_init = verifyctx_init;
pmeth->verifyctx = verifyctx;
}
void EVP_PKEY_meth_set_encrypt(EVP_PKEY_METHOD *pmeth,
int (*encrypt_init) (EVP_PKEY_CTX *ctx),
int (*encryptfn) (EVP_PKEY_CTX *ctx,
unsigned char *out,
size_t *outlen,
const unsigned char *in,
size_t inlen))
{
pmeth->encrypt_init = encrypt_init;
pmeth->encrypt = encryptfn;
}
void EVP_PKEY_meth_set_decrypt(EVP_PKEY_METHOD *pmeth,
int (*decrypt_init) (EVP_PKEY_CTX *ctx),
int (*decrypt) (EVP_PKEY_CTX *ctx,
unsigned char *out,
size_t *outlen,
const unsigned char *in,
size_t inlen))
{
pmeth->decrypt_init = decrypt_init;
pmeth->decrypt = decrypt;
}
void EVP_PKEY_meth_set_derive(EVP_PKEY_METHOD *pmeth,
int (*derive_init) (EVP_PKEY_CTX *ctx),
int (*derive) (EVP_PKEY_CTX *ctx,
unsigned char *key,
size_t *keylen))
{
pmeth->derive_init = derive_init;
pmeth->derive = derive;
}
void EVP_PKEY_meth_set_ctrl(EVP_PKEY_METHOD *pmeth,
int (*ctrl) (EVP_PKEY_CTX *ctx, int type, int p1,
void *p2),
int (*ctrl_str) (EVP_PKEY_CTX *ctx,
const char *type,
const char *value))
{
pmeth->ctrl = ctrl;
pmeth->ctrl_str = ctrl_str;
}
void EVP_PKEY_meth_set_digestsign(EVP_PKEY_METHOD *pmeth,
int (*digestsign) (EVP_MD_CTX *ctx, unsigned char *sig, size_t *siglen,
const unsigned char *tbs, size_t tbslen))
{
pmeth->digestsign = digestsign;
}
void EVP_PKEY_meth_set_digestverify(EVP_PKEY_METHOD *pmeth,
int (*digestverify) (EVP_MD_CTX *ctx, const unsigned char *sig,
size_t siglen, const unsigned char *tbs,
size_t tbslen))
{
pmeth->digestverify = digestverify;
}
void EVP_PKEY_meth_set_check(EVP_PKEY_METHOD *pmeth,
int (*check) (EVP_PKEY *pkey))
{
pmeth->check = check;
}
void EVP_PKEY_meth_set_public_check(EVP_PKEY_METHOD *pmeth,
int (*check) (EVP_PKEY *pkey))
{
pmeth->public_check = check;
}
void EVP_PKEY_meth_set_param_check(EVP_PKEY_METHOD *pmeth,
int (*check) (EVP_PKEY *pkey))
{
pmeth->param_check = check;
}
void EVP_PKEY_meth_set_digest_custom(EVP_PKEY_METHOD *pmeth,
int (*digest_custom) (EVP_PKEY_CTX *ctx,
EVP_MD_CTX *mctx))
{
pmeth->digest_custom = digest_custom;
}
void EVP_PKEY_meth_get_init(const EVP_PKEY_METHOD *pmeth,
int (**pinit) (EVP_PKEY_CTX *ctx))
{
*pinit = pmeth->init;
}
void EVP_PKEY_meth_get_copy(const EVP_PKEY_METHOD *pmeth,
int (**pcopy) (EVP_PKEY_CTX *dst,
const EVP_PKEY_CTX *src))
{
*pcopy = pmeth->copy;
}
void EVP_PKEY_meth_get_cleanup(const EVP_PKEY_METHOD *pmeth,
void (**pcleanup) (EVP_PKEY_CTX *ctx))
{
*pcleanup = pmeth->cleanup;
}
void EVP_PKEY_meth_get_paramgen(const EVP_PKEY_METHOD *pmeth,
int (**pparamgen_init) (EVP_PKEY_CTX *ctx),
int (**pparamgen) (EVP_PKEY_CTX *ctx,
EVP_PKEY *pkey))
{
if (pparamgen_init)
*pparamgen_init = pmeth->paramgen_init;
if (pparamgen)
*pparamgen = pmeth->paramgen;
}
void EVP_PKEY_meth_get_keygen(const EVP_PKEY_METHOD *pmeth,
int (**pkeygen_init) (EVP_PKEY_CTX *ctx),
int (**pkeygen) (EVP_PKEY_CTX *ctx,
EVP_PKEY *pkey))
{
if (pkeygen_init)
*pkeygen_init = pmeth->keygen_init;
if (pkeygen)
*pkeygen = pmeth->keygen;
}
void EVP_PKEY_meth_get_sign(const EVP_PKEY_METHOD *pmeth,
int (**psign_init) (EVP_PKEY_CTX *ctx),
int (**psign) (EVP_PKEY_CTX *ctx,
unsigned char *sig, size_t *siglen,
const unsigned char *tbs,
size_t tbslen))
{
if (psign_init)
*psign_init = pmeth->sign_init;
if (psign)
*psign = pmeth->sign;
}
void EVP_PKEY_meth_get_verify(const EVP_PKEY_METHOD *pmeth,
int (**pverify_init) (EVP_PKEY_CTX *ctx),
int (**pverify) (EVP_PKEY_CTX *ctx,
const unsigned char *sig,
size_t siglen,
const unsigned char *tbs,
size_t tbslen))
{
if (pverify_init)
*pverify_init = pmeth->verify_init;
if (pverify)
*pverify = pmeth->verify;
}
void EVP_PKEY_meth_get_verify_recover(const EVP_PKEY_METHOD *pmeth,
int (**pverify_recover_init) (EVP_PKEY_CTX
*ctx),
int (**pverify_recover) (EVP_PKEY_CTX
*ctx,
unsigned char
*sig,
size_t *siglen,
const unsigned
char *tbs,
size_t tbslen))
{
if (pverify_recover_init)
*pverify_recover_init = pmeth->verify_recover_init;
if (pverify_recover)
*pverify_recover = pmeth->verify_recover;
}
void EVP_PKEY_meth_get_signctx(const EVP_PKEY_METHOD *pmeth,
int (**psignctx_init) (EVP_PKEY_CTX *ctx,
EVP_MD_CTX *mctx),
int (**psignctx) (EVP_PKEY_CTX *ctx,
unsigned char *sig,
size_t *siglen,
EVP_MD_CTX *mctx))
{
if (psignctx_init)
*psignctx_init = pmeth->signctx_init;
if (psignctx)
*psignctx = pmeth->signctx;
}
void EVP_PKEY_meth_get_verifyctx(const EVP_PKEY_METHOD *pmeth,
int (**pverifyctx_init) (EVP_PKEY_CTX *ctx,
EVP_MD_CTX *mctx),
int (**pverifyctx) (EVP_PKEY_CTX *ctx,
const unsigned char *sig,
int siglen,
EVP_MD_CTX *mctx))
{
if (pverifyctx_init)
*pverifyctx_init = pmeth->verifyctx_init;
if (pverifyctx)
*pverifyctx = pmeth->verifyctx;
}
void EVP_PKEY_meth_get_encrypt(const EVP_PKEY_METHOD *pmeth,
int (**pencrypt_init) (EVP_PKEY_CTX *ctx),
int (**pencryptfn) (EVP_PKEY_CTX *ctx,
unsigned char *out,
size_t *outlen,
const unsigned char *in,
size_t inlen))
{
if (pencrypt_init)
*pencrypt_init = pmeth->encrypt_init;
if (pencryptfn)
*pencryptfn = pmeth->encrypt;
}
void EVP_PKEY_meth_get_decrypt(const EVP_PKEY_METHOD *pmeth,
int (**pdecrypt_init) (EVP_PKEY_CTX *ctx),
int (**pdecrypt) (EVP_PKEY_CTX *ctx,
unsigned char *out,
size_t *outlen,
const unsigned char *in,
size_t inlen))
{
if (pdecrypt_init)
*pdecrypt_init = pmeth->decrypt_init;
if (pdecrypt)
*pdecrypt = pmeth->decrypt;
}
void EVP_PKEY_meth_get_derive(const EVP_PKEY_METHOD *pmeth,
int (**pderive_init) (EVP_PKEY_CTX *ctx),
int (**pderive) (EVP_PKEY_CTX *ctx,
unsigned char *key,
size_t *keylen))
{
if (pderive_init)
*pderive_init = pmeth->derive_init;
if (pderive)
*pderive = pmeth->derive;
}
void EVP_PKEY_meth_get_ctrl(const EVP_PKEY_METHOD *pmeth,
int (**pctrl) (EVP_PKEY_CTX *ctx, int type, int p1,
void *p2),
int (**pctrl_str) (EVP_PKEY_CTX *ctx,
const char *type,
const char *value))
{
if (pctrl)
*pctrl = pmeth->ctrl;
if (pctrl_str)
*pctrl_str = pmeth->ctrl_str;
}
void EVP_PKEY_meth_get_digestsign(const EVP_PKEY_METHOD *pmeth,
int (**digestsign) (EVP_MD_CTX *ctx, unsigned char *sig, size_t *siglen,
const unsigned char *tbs, size_t tbslen))
{
if (digestsign)
*digestsign = pmeth->digestsign;
}
void EVP_PKEY_meth_get_digestverify(const EVP_PKEY_METHOD *pmeth,
int (**digestverify) (EVP_MD_CTX *ctx, const unsigned char *sig,
size_t siglen, const unsigned char *tbs,
size_t tbslen))
{
if (digestverify)
*digestverify = pmeth->digestverify;
}
void EVP_PKEY_meth_get_check(const EVP_PKEY_METHOD *pmeth,
int (**pcheck) (EVP_PKEY *pkey))
{
if (pcheck != NULL)
*pcheck = pmeth->check;
}
void EVP_PKEY_meth_get_public_check(const EVP_PKEY_METHOD *pmeth,
int (**pcheck) (EVP_PKEY *pkey))
{
if (pcheck != NULL)
*pcheck = pmeth->public_check;
}
void EVP_PKEY_meth_get_param_check(const EVP_PKEY_METHOD *pmeth,
int (**pcheck) (EVP_PKEY *pkey))
{
if (pcheck != NULL)
*pcheck = pmeth->param_check;
}
void EVP_PKEY_meth_get_digest_custom(const EVP_PKEY_METHOD *pmeth,
int (**pdigest_custom) (EVP_PKEY_CTX *ctx,
EVP_MD_CTX *mctx))
{
if (pdigest_custom != NULL)
*pdigest_custom = pmeth->digest_custom;
}
#endif /* FIPS_MODULE */
diff --git a/crypto/openssl/crypto/evp/signature.c b/crypto/openssl/crypto/evp/signature.c
index fb269b3bfd07..8adf254d5eec 100644
--- a/crypto/openssl/crypto/evp/signature.c
+++ b/crypto/openssl/crypto/evp/signature.c
@@ -1,748 +1,763 @@
/*
- * Copyright 2006-2022 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2006-2024 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 <stdio.h>
#include <stdlib.h>
#include <openssl/objects.h>
#include <openssl/evp.h>
#include "internal/numbers.h" /* includes SIZE_MAX */
#include "internal/cryptlib.h"
#include "internal/provider.h"
#include "internal/core.h"
#include "crypto/evp.h"
#include "evp_local.h"
static EVP_SIGNATURE *evp_signature_new(OSSL_PROVIDER *prov)
{
EVP_SIGNATURE *signature = OPENSSL_zalloc(sizeof(EVP_SIGNATURE));
if (signature == NULL) {
ERR_raise(ERR_LIB_EVP, ERR_R_MALLOC_FAILURE);
return NULL;
}
signature->lock = CRYPTO_THREAD_lock_new();
if (signature->lock == NULL) {
ERR_raise(ERR_LIB_EVP, ERR_R_MALLOC_FAILURE);
OPENSSL_free(signature);
return NULL;
}
signature->prov = prov;
ossl_provider_up_ref(prov);
signature->refcnt = 1;
return signature;
}
static void *evp_signature_from_algorithm(int name_id,
const OSSL_ALGORITHM *algodef,
OSSL_PROVIDER *prov)
{
const OSSL_DISPATCH *fns = algodef->implementation;
EVP_SIGNATURE *signature = NULL;
int ctxfncnt = 0, signfncnt = 0, verifyfncnt = 0, verifyrecfncnt = 0;
int digsignfncnt = 0, digverifyfncnt = 0;
int gparamfncnt = 0, sparamfncnt = 0, gmdparamfncnt = 0, smdparamfncnt = 0;
if ((signature = evp_signature_new(prov)) == NULL) {
ERR_raise(ERR_LIB_EVP, ERR_R_MALLOC_FAILURE);
goto err;
}
signature->name_id = name_id;
if ((signature->type_name = ossl_algorithm_get1_first_name(algodef)) == NULL)
goto err;
signature->description = algodef->algorithm_description;
for (; fns->function_id != 0; fns++) {
switch (fns->function_id) {
case OSSL_FUNC_SIGNATURE_NEWCTX:
if (signature->newctx != NULL)
break;
signature->newctx = OSSL_FUNC_signature_newctx(fns);
ctxfncnt++;
break;
case OSSL_FUNC_SIGNATURE_SIGN_INIT:
if (signature->sign_init != NULL)
break;
signature->sign_init = OSSL_FUNC_signature_sign_init(fns);
signfncnt++;
break;
case OSSL_FUNC_SIGNATURE_SIGN:
if (signature->sign != NULL)
break;
signature->sign = OSSL_FUNC_signature_sign(fns);
signfncnt++;
break;
case OSSL_FUNC_SIGNATURE_VERIFY_INIT:
if (signature->verify_init != NULL)
break;
signature->verify_init = OSSL_FUNC_signature_verify_init(fns);
verifyfncnt++;
break;
case OSSL_FUNC_SIGNATURE_VERIFY:
if (signature->verify != NULL)
break;
signature->verify = OSSL_FUNC_signature_verify(fns);
verifyfncnt++;
break;
case OSSL_FUNC_SIGNATURE_VERIFY_RECOVER_INIT:
if (signature->verify_recover_init != NULL)
break;
signature->verify_recover_init
= OSSL_FUNC_signature_verify_recover_init(fns);
verifyrecfncnt++;
break;
case OSSL_FUNC_SIGNATURE_VERIFY_RECOVER:
if (signature->verify_recover != NULL)
break;
signature->verify_recover
= OSSL_FUNC_signature_verify_recover(fns);
verifyrecfncnt++;
break;
case OSSL_FUNC_SIGNATURE_DIGEST_SIGN_INIT:
if (signature->digest_sign_init != NULL)
break;
signature->digest_sign_init
= OSSL_FUNC_signature_digest_sign_init(fns);
break;
case OSSL_FUNC_SIGNATURE_DIGEST_SIGN_UPDATE:
if (signature->digest_sign_update != NULL)
break;
signature->digest_sign_update
= OSSL_FUNC_signature_digest_sign_update(fns);
digsignfncnt++;
break;
case OSSL_FUNC_SIGNATURE_DIGEST_SIGN_FINAL:
if (signature->digest_sign_final != NULL)
break;
signature->digest_sign_final
= OSSL_FUNC_signature_digest_sign_final(fns);
digsignfncnt++;
break;
case OSSL_FUNC_SIGNATURE_DIGEST_SIGN:
if (signature->digest_sign != NULL)
break;
signature->digest_sign
= OSSL_FUNC_signature_digest_sign(fns);
break;
case OSSL_FUNC_SIGNATURE_DIGEST_VERIFY_INIT:
if (signature->digest_verify_init != NULL)
break;
signature->digest_verify_init
= OSSL_FUNC_signature_digest_verify_init(fns);
break;
case OSSL_FUNC_SIGNATURE_DIGEST_VERIFY_UPDATE:
if (signature->digest_verify_update != NULL)
break;
signature->digest_verify_update
= OSSL_FUNC_signature_digest_verify_update(fns);
digverifyfncnt++;
break;
case OSSL_FUNC_SIGNATURE_DIGEST_VERIFY_FINAL:
if (signature->digest_verify_final != NULL)
break;
signature->digest_verify_final
= OSSL_FUNC_signature_digest_verify_final(fns);
digverifyfncnt++;
break;
case OSSL_FUNC_SIGNATURE_DIGEST_VERIFY:
if (signature->digest_verify != NULL)
break;
signature->digest_verify
= OSSL_FUNC_signature_digest_verify(fns);
break;
case OSSL_FUNC_SIGNATURE_FREECTX:
if (signature->freectx != NULL)
break;
signature->freectx = OSSL_FUNC_signature_freectx(fns);
ctxfncnt++;
break;
case OSSL_FUNC_SIGNATURE_DUPCTX:
if (signature->dupctx != NULL)
break;
signature->dupctx = OSSL_FUNC_signature_dupctx(fns);
break;
case OSSL_FUNC_SIGNATURE_GET_CTX_PARAMS:
if (signature->get_ctx_params != NULL)
break;
signature->get_ctx_params
= OSSL_FUNC_signature_get_ctx_params(fns);
gparamfncnt++;
break;
case OSSL_FUNC_SIGNATURE_GETTABLE_CTX_PARAMS:
if (signature->gettable_ctx_params != NULL)
break;
signature->gettable_ctx_params
= OSSL_FUNC_signature_gettable_ctx_params(fns);
gparamfncnt++;
break;
case OSSL_FUNC_SIGNATURE_SET_CTX_PARAMS:
if (signature->set_ctx_params != NULL)
break;
signature->set_ctx_params
= OSSL_FUNC_signature_set_ctx_params(fns);
sparamfncnt++;
break;
case OSSL_FUNC_SIGNATURE_SETTABLE_CTX_PARAMS:
if (signature->settable_ctx_params != NULL)
break;
signature->settable_ctx_params
= OSSL_FUNC_signature_settable_ctx_params(fns);
sparamfncnt++;
break;
case OSSL_FUNC_SIGNATURE_GET_CTX_MD_PARAMS:
if (signature->get_ctx_md_params != NULL)
break;
signature->get_ctx_md_params
= OSSL_FUNC_signature_get_ctx_md_params(fns);
gmdparamfncnt++;
break;
case OSSL_FUNC_SIGNATURE_GETTABLE_CTX_MD_PARAMS:
if (signature->gettable_ctx_md_params != NULL)
break;
signature->gettable_ctx_md_params
= OSSL_FUNC_signature_gettable_ctx_md_params(fns);
gmdparamfncnt++;
break;
case OSSL_FUNC_SIGNATURE_SET_CTX_MD_PARAMS:
if (signature->set_ctx_md_params != NULL)
break;
signature->set_ctx_md_params
= OSSL_FUNC_signature_set_ctx_md_params(fns);
smdparamfncnt++;
break;
case OSSL_FUNC_SIGNATURE_SETTABLE_CTX_MD_PARAMS:
if (signature->settable_ctx_md_params != NULL)
break;
signature->settable_ctx_md_params
= OSSL_FUNC_signature_settable_ctx_md_params(fns);
smdparamfncnt++;
break;
}
}
if (ctxfncnt != 2
|| (signfncnt == 0
&& verifyfncnt == 0
&& verifyrecfncnt == 0
&& digsignfncnt == 0
&& digverifyfncnt == 0
&& signature->digest_sign == NULL
&& signature->digest_verify == NULL)
|| (signfncnt != 0 && signfncnt != 2)
|| (verifyfncnt != 0 && verifyfncnt != 2)
|| (verifyrecfncnt != 0 && verifyrecfncnt != 2)
|| (digsignfncnt != 0 && digsignfncnt != 2)
|| (digsignfncnt == 2 && signature->digest_sign_init == NULL)
|| (digverifyfncnt != 0 && digverifyfncnt != 2)
|| (digverifyfncnt == 2 && signature->digest_verify_init == NULL)
|| (signature->digest_sign != NULL
&& signature->digest_sign_init == NULL)
|| (signature->digest_verify != NULL
&& signature->digest_verify_init == NULL)
|| (gparamfncnt != 0 && gparamfncnt != 2)
|| (sparamfncnt != 0 && sparamfncnt != 2)
|| (gmdparamfncnt != 0 && gmdparamfncnt != 2)
|| (smdparamfncnt != 0 && smdparamfncnt != 2)) {
/*
* In order to be a consistent set of functions we must have at least
* a set of context functions (newctx and freectx) as well as a set of
* "signature" functions:
* (sign_init, sign) or
* (verify_init verify) or
* (verify_recover_init, verify_recover) or
* (digest_sign_init, digest_sign_update, digest_sign_final) or
* (digest_verify_init, digest_verify_update, digest_verify_final) or
* (digest_sign_init, digest_sign) or
* (digest_verify_init, digest_verify).
*
* set_ctx_params and settable_ctx_params are optional, but if one of
* them is present then the other one must also be present. The same
* applies to get_ctx_params and gettable_ctx_params. The same rules
* apply to the "md_params" functions. The dupctx function is optional.
*/
ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_PROVIDER_FUNCTIONS);
goto err;
}
return signature;
err:
EVP_SIGNATURE_free(signature);
return NULL;
}
void EVP_SIGNATURE_free(EVP_SIGNATURE *signature)
{
int i;
if (signature == NULL)
return;
CRYPTO_DOWN_REF(&signature->refcnt, &i, signature->lock);
if (i > 0)
return;
OPENSSL_free(signature->type_name);
ossl_provider_free(signature->prov);
CRYPTO_THREAD_lock_free(signature->lock);
OPENSSL_free(signature);
}
int EVP_SIGNATURE_up_ref(EVP_SIGNATURE *signature)
{
int ref = 0;
CRYPTO_UP_REF(&signature->refcnt, &ref, signature->lock);
return 1;
}
OSSL_PROVIDER *EVP_SIGNATURE_get0_provider(const EVP_SIGNATURE *signature)
{
return signature->prov;
}
EVP_SIGNATURE *EVP_SIGNATURE_fetch(OSSL_LIB_CTX *ctx, const char *algorithm,
const char *properties)
{
return evp_generic_fetch(ctx, OSSL_OP_SIGNATURE, algorithm, properties,
evp_signature_from_algorithm,
(int (*)(void *))EVP_SIGNATURE_up_ref,
(void (*)(void *))EVP_SIGNATURE_free);
}
EVP_SIGNATURE *evp_signature_fetch_from_prov(OSSL_PROVIDER *prov,
const char *algorithm,
const char *properties)
{
return evp_generic_fetch_from_prov(prov, OSSL_OP_SIGNATURE,
algorithm, properties,
evp_signature_from_algorithm,
(int (*)(void *))EVP_SIGNATURE_up_ref,
(void (*)(void *))EVP_SIGNATURE_free);
}
int EVP_SIGNATURE_is_a(const EVP_SIGNATURE *signature, const char *name)
{
return signature != NULL
&& evp_is_a(signature->prov, signature->name_id, NULL, name);
}
int evp_signature_get_number(const EVP_SIGNATURE *signature)
{
return signature->name_id;
}
const char *EVP_SIGNATURE_get0_name(const EVP_SIGNATURE *signature)
{
return signature->type_name;
}
const char *EVP_SIGNATURE_get0_description(const EVP_SIGNATURE *signature)
{
return signature->description;
}
void EVP_SIGNATURE_do_all_provided(OSSL_LIB_CTX *libctx,
void (*fn)(EVP_SIGNATURE *signature,
void *arg),
void *arg)
{
evp_generic_do_all(libctx, OSSL_OP_SIGNATURE,
(void (*)(void *, void *))fn, arg,
evp_signature_from_algorithm,
(int (*)(void *))EVP_SIGNATURE_up_ref,
(void (*)(void *))EVP_SIGNATURE_free);
}
int EVP_SIGNATURE_names_do_all(const EVP_SIGNATURE *signature,
void (*fn)(const char *name, void *data),
void *data)
{
if (signature->prov != NULL)
return evp_names_do_all(signature->prov, signature->name_id, fn, data);
return 1;
}
const OSSL_PARAM *EVP_SIGNATURE_gettable_ctx_params(const EVP_SIGNATURE *sig)
{
void *provctx;
if (sig == NULL || sig->gettable_ctx_params == NULL)
return NULL;
provctx = ossl_provider_ctx(EVP_SIGNATURE_get0_provider(sig));
return sig->gettable_ctx_params(NULL, provctx);
}
const OSSL_PARAM *EVP_SIGNATURE_settable_ctx_params(const EVP_SIGNATURE *sig)
{
void *provctx;
if (sig == NULL || sig->settable_ctx_params == NULL)
return NULL;
provctx = ossl_provider_ctx(EVP_SIGNATURE_get0_provider(sig));
return sig->settable_ctx_params(NULL, provctx);
}
static int evp_pkey_signature_init(EVP_PKEY_CTX *ctx, int operation,
const OSSL_PARAM params[])
{
int ret = 0;
void *provkey = NULL;
EVP_SIGNATURE *signature = NULL;
EVP_KEYMGMT *tmp_keymgmt = NULL;
const OSSL_PROVIDER *tmp_prov = NULL;
const char *supported_sig = NULL;
int iter;
if (ctx == NULL) {
- ERR_raise(ERR_LIB_EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE);
- return -2;
+ ERR_raise(ERR_LIB_EVP, ERR_R_PASSED_NULL_PARAMETER);
+ return -1;
}
evp_pkey_ctx_free_old_ops(ctx);
ctx->operation = operation;
ERR_set_mark();
if (evp_pkey_ctx_is_legacy(ctx))
goto legacy;
if (ctx->pkey == NULL) {
ERR_clear_last_mark();
ERR_raise(ERR_LIB_EVP, EVP_R_NO_KEY_SET);
goto err;
}
/*
* Try to derive the supported signature from |ctx->keymgmt|.
*/
if (!ossl_assert(ctx->pkey->keymgmt == NULL
|| ctx->pkey->keymgmt == ctx->keymgmt)) {
ERR_clear_last_mark();
ERR_raise(ERR_LIB_EVP, ERR_R_INTERNAL_ERROR);
goto err;
}
supported_sig = evp_keymgmt_util_query_operation_name(ctx->keymgmt,
OSSL_OP_SIGNATURE);
if (supported_sig == NULL) {
ERR_clear_last_mark();
ERR_raise(ERR_LIB_EVP, EVP_R_INITIALIZATION_ERROR);
goto err;
}
/*
* We perform two iterations:
*
* 1. Do the normal signature fetch, using the fetching data given by
* the EVP_PKEY_CTX.
* 2. Do the provider specific signature fetch, from the same provider
* as |ctx->keymgmt|
*
* We then try to fetch the keymgmt from the same provider as the
* signature, and try to export |ctx->pkey| to that keymgmt (when
* this keymgmt happens to be the same as |ctx->keymgmt|, the export
* is a no-op, but we call it anyway to not complicate the code even
* more).
* If the export call succeeds (returns a non-NULL provider key pointer),
* we're done and can perform the operation itself. If not, we perform
* the second iteration, or jump to legacy.
*/
for (iter = 1; iter < 3 && provkey == NULL; iter++) {
EVP_KEYMGMT *tmp_keymgmt_tofree = NULL;
/*
* If we're on the second iteration, free the results from the first.
* They are NULL on the first iteration, so no need to check what
* iteration we're on.
*/
EVP_SIGNATURE_free(signature);
EVP_KEYMGMT_free(tmp_keymgmt);
switch (iter) {
case 1:
signature =
EVP_SIGNATURE_fetch(ctx->libctx, supported_sig, ctx->propquery);
if (signature != NULL)
tmp_prov = EVP_SIGNATURE_get0_provider(signature);
break;
case 2:
tmp_prov = EVP_KEYMGMT_get0_provider(ctx->keymgmt);
signature =
evp_signature_fetch_from_prov((OSSL_PROVIDER *)tmp_prov,
supported_sig, ctx->propquery);
if (signature == NULL)
goto legacy;
break;
}
if (signature == NULL)
continue;
/*
* Ensure that the key is provided, either natively, or as a cached
* export. We start by fetching the keymgmt with the same name as
* |ctx->pkey|, but from the provider of the signature method, using
* the same property query as when fetching the signature method.
* With the keymgmt we found (if we did), we try to export |ctx->pkey|
* to it (evp_pkey_export_to_provider() is smart enough to only actually
* export it if |tmp_keymgmt| is different from |ctx->pkey|'s keymgmt)
*/
tmp_keymgmt_tofree = tmp_keymgmt =
evp_keymgmt_fetch_from_prov((OSSL_PROVIDER *)tmp_prov,
EVP_KEYMGMT_get0_name(ctx->keymgmt),
ctx->propquery);
if (tmp_keymgmt != NULL)
provkey = evp_pkey_export_to_provider(ctx->pkey, ctx->libctx,
&tmp_keymgmt, ctx->propquery);
if (tmp_keymgmt == NULL)
EVP_KEYMGMT_free(tmp_keymgmt_tofree);
}
if (provkey == NULL) {
EVP_SIGNATURE_free(signature);
goto legacy;
}
ERR_pop_to_mark();
/* No more legacy from here down to legacy: */
ctx->op.sig.signature = signature;
ctx->op.sig.algctx =
signature->newctx(ossl_provider_ctx(signature->prov), ctx->propquery);
if (ctx->op.sig.algctx == NULL) {
/* The provider key can stay in the cache */
ERR_raise(ERR_LIB_EVP, EVP_R_INITIALIZATION_ERROR);
goto err;
}
switch (operation) {
case EVP_PKEY_OP_SIGN:
if (signature->sign_init == NULL) {
ERR_raise(ERR_LIB_EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE);
ret = -2;
goto err;
}
ret = signature->sign_init(ctx->op.sig.algctx, provkey, params);
break;
case EVP_PKEY_OP_VERIFY:
if (signature->verify_init == NULL) {
ERR_raise(ERR_LIB_EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE);
ret = -2;
goto err;
}
ret = signature->verify_init(ctx->op.sig.algctx, provkey, params);
break;
case EVP_PKEY_OP_VERIFYRECOVER:
if (signature->verify_recover_init == NULL) {
ERR_raise(ERR_LIB_EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE);
ret = -2;
goto err;
}
ret = signature->verify_recover_init(ctx->op.sig.algctx, provkey,
params);
break;
default:
ERR_raise(ERR_LIB_EVP, EVP_R_INITIALIZATION_ERROR);
goto err;
}
if (ret <= 0) {
signature->freectx(ctx->op.sig.algctx);
ctx->op.sig.algctx = NULL;
goto err;
}
goto end;
legacy:
/*
* If we don't have the full support we need with provided methods,
* let's go see if legacy does.
*/
ERR_pop_to_mark();
EVP_KEYMGMT_free(tmp_keymgmt);
tmp_keymgmt = NULL;
if (ctx->pmeth == NULL
|| (operation == EVP_PKEY_OP_SIGN && ctx->pmeth->sign == NULL)
|| (operation == EVP_PKEY_OP_VERIFY && ctx->pmeth->verify == NULL)
|| (operation == EVP_PKEY_OP_VERIFYRECOVER
&& ctx->pmeth->verify_recover == NULL)) {
ERR_raise(ERR_LIB_EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE);
return -2;
}
switch (operation) {
case EVP_PKEY_OP_SIGN:
if (ctx->pmeth->sign_init == NULL)
return 1;
ret = ctx->pmeth->sign_init(ctx);
break;
case EVP_PKEY_OP_VERIFY:
if (ctx->pmeth->verify_init == NULL)
return 1;
ret = ctx->pmeth->verify_init(ctx);
break;
case EVP_PKEY_OP_VERIFYRECOVER:
if (ctx->pmeth->verify_recover_init == NULL)
return 1;
ret = ctx->pmeth->verify_recover_init(ctx);
break;
default:
ERR_raise(ERR_LIB_EVP, EVP_R_INITIALIZATION_ERROR);
goto err;
}
if (ret <= 0)
goto err;
end:
#ifndef FIPS_MODULE
if (ret > 0)
ret = evp_pkey_ctx_use_cached_data(ctx);
#endif
EVP_KEYMGMT_free(tmp_keymgmt);
return ret;
err:
evp_pkey_ctx_free_old_ops(ctx);
ctx->operation = EVP_PKEY_OP_UNDEFINED;
EVP_KEYMGMT_free(tmp_keymgmt);
return ret;
}
int EVP_PKEY_sign_init(EVP_PKEY_CTX *ctx)
{
return evp_pkey_signature_init(ctx, EVP_PKEY_OP_SIGN, NULL);
}
int EVP_PKEY_sign_init_ex(EVP_PKEY_CTX *ctx, const OSSL_PARAM params[])
{
return evp_pkey_signature_init(ctx, EVP_PKEY_OP_SIGN, params);
}
int EVP_PKEY_sign(EVP_PKEY_CTX *ctx,
unsigned char *sig, size_t *siglen,
const unsigned char *tbs, size_t tbslen)
{
int ret;
if (ctx == NULL) {
- ERR_raise(ERR_LIB_EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE);
- return -2;
+ ERR_raise(ERR_LIB_EVP, ERR_R_PASSED_NULL_PARAMETER);
+ return -1;
}
if (ctx->operation != EVP_PKEY_OP_SIGN) {
ERR_raise(ERR_LIB_EVP, EVP_R_OPERATION_NOT_INITIALIZED);
return -1;
}
if (ctx->op.sig.algctx == NULL)
goto legacy;
+ if (ctx->op.sig.signature->sign == NULL) {
+ ERR_raise(ERR_LIB_EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE);
+ return -2;
+ }
+
ret = ctx->op.sig.signature->sign(ctx->op.sig.algctx, sig, siglen,
(sig == NULL) ? 0 : *siglen, tbs, tbslen);
return ret;
legacy:
if (ctx->pmeth == NULL || ctx->pmeth->sign == NULL) {
ERR_raise(ERR_LIB_EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE);
return -2;
}
M_check_autoarg(ctx, sig, siglen, EVP_F_EVP_PKEY_SIGN)
return ctx->pmeth->sign(ctx, sig, siglen, tbs, tbslen);
}
int EVP_PKEY_verify_init(EVP_PKEY_CTX *ctx)
{
return evp_pkey_signature_init(ctx, EVP_PKEY_OP_VERIFY, NULL);
}
int EVP_PKEY_verify_init_ex(EVP_PKEY_CTX *ctx, const OSSL_PARAM params[])
{
return evp_pkey_signature_init(ctx, EVP_PKEY_OP_VERIFY, params);
}
int EVP_PKEY_verify(EVP_PKEY_CTX *ctx,
const unsigned char *sig, size_t siglen,
const unsigned char *tbs, size_t tbslen)
{
int ret;
if (ctx == NULL) {
- ERR_raise(ERR_LIB_EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE);
- return -2;
+ ERR_raise(ERR_LIB_EVP, ERR_R_PASSED_NULL_PARAMETER);
+ return -1;
}
if (ctx->operation != EVP_PKEY_OP_VERIFY) {
ERR_raise(ERR_LIB_EVP, EVP_R_OPERATION_NOT_INITIALIZED);
return -1;
}
if (ctx->op.sig.algctx == NULL)
goto legacy;
+ if (ctx->op.sig.signature->verify == NULL) {
+ ERR_raise(ERR_LIB_EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE);
+ return -2;
+ }
+
ret = ctx->op.sig.signature->verify(ctx->op.sig.algctx, sig, siglen,
tbs, tbslen);
return ret;
legacy:
if (ctx->pmeth == NULL || ctx->pmeth->verify == NULL) {
ERR_raise(ERR_LIB_EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE);
return -2;
}
return ctx->pmeth->verify(ctx, sig, siglen, tbs, tbslen);
}
int EVP_PKEY_verify_recover_init(EVP_PKEY_CTX *ctx)
{
return evp_pkey_signature_init(ctx, EVP_PKEY_OP_VERIFYRECOVER, NULL);
}
int EVP_PKEY_verify_recover_init_ex(EVP_PKEY_CTX *ctx,
const OSSL_PARAM params[])
{
return evp_pkey_signature_init(ctx, EVP_PKEY_OP_VERIFYRECOVER, params);
}
int EVP_PKEY_verify_recover(EVP_PKEY_CTX *ctx,
unsigned char *rout, size_t *routlen,
const unsigned char *sig, size_t siglen)
{
int ret;
if (ctx == NULL) {
- ERR_raise(ERR_LIB_EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE);
- return -2;
+ ERR_raise(ERR_LIB_EVP, ERR_R_PASSED_NULL_PARAMETER);
+ return -1;
}
if (ctx->operation != EVP_PKEY_OP_VERIFYRECOVER) {
ERR_raise(ERR_LIB_EVP, EVP_R_OPERATION_NOT_INITIALIZED);
return -1;
}
if (ctx->op.sig.algctx == NULL)
goto legacy;
+ if (ctx->op.sig.signature->verify_recover == NULL) {
+ ERR_raise(ERR_LIB_EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE);
+ return -2;
+ }
+
ret = ctx->op.sig.signature->verify_recover(ctx->op.sig.algctx, rout,
routlen,
(rout == NULL ? 0 : *routlen),
sig, siglen);
return ret;
legacy:
if (ctx->pmeth == NULL || ctx->pmeth->verify_recover == NULL) {
ERR_raise(ERR_LIB_EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE);
return -2;
}
M_check_autoarg(ctx, rout, routlen, EVP_F_EVP_PKEY_VERIFY_RECOVER)
return ctx->pmeth->verify_recover(ctx, rout, routlen, sig, siglen);
}
diff --git a/crypto/openssl/crypto/init.c b/crypto/openssl/crypto/init.c
index cacf637c89f8..659a660eeced 100644
--- a/crypto/openssl/crypto/init.c
+++ b/crypto/openssl/crypto/init.c
@@ -1,720 +1,722 @@
/*
- * Copyright 2016-2022 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2016-2024 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
/* We need to use some engine deprecated APIs */
#define OPENSSL_SUPPRESS_DEPRECATED
#include "e_os.h"
#include "crypto/cryptlib.h"
#include <openssl/err.h>
#include "crypto/rand.h"
#include "internal/bio.h"
#include <openssl/evp.h>
#include "crypto/evp.h"
#include "internal/conf.h"
#include "crypto/async.h"
#include "crypto/engine.h"
#include "internal/comp.h"
#include "internal/err.h"
#include "crypto/err.h"
#include "crypto/objects.h"
#include <stdlib.h>
#include <assert.h>
#include "internal/thread_once.h"
#include "crypto/dso_conf.h"
#include "internal/dso.h"
#include "crypto/store.h"
#include <openssl/cmp_util.h> /* for OSSL_CMP_log_close() */
#include <openssl/trace.h>
#include "crypto/ctype.h"
static int stopped = 0;
static uint64_t optsdone = 0;
typedef struct ossl_init_stop_st OPENSSL_INIT_STOP;
struct ossl_init_stop_st {
void (*handler)(void);
OPENSSL_INIT_STOP *next;
};
static OPENSSL_INIT_STOP *stop_handlers = NULL;
/* Guards access to the optsdone variable on platforms without atomics */
static CRYPTO_RWLOCK *optsdone_lock = NULL;
/* Guards simultaneous INIT_LOAD_CONFIG calls with non-NULL settings */
static CRYPTO_RWLOCK *init_lock = NULL;
static CRYPTO_THREAD_LOCAL in_init_config_local;
static CRYPTO_ONCE base = CRYPTO_ONCE_STATIC_INIT;
static int base_inited = 0;
DEFINE_RUN_ONCE_STATIC(ossl_init_base)
{
/* no need to init trace */
OSSL_TRACE(INIT, "ossl_init_base: setting up stop handlers\n");
#ifndef OPENSSL_NO_CRYPTO_MDEBUG
ossl_malloc_setup_failures();
#endif
if ((optsdone_lock = CRYPTO_THREAD_lock_new()) == NULL
|| (init_lock = CRYPTO_THREAD_lock_new()) == NULL)
goto err;
OPENSSL_cpuid_setup();
if (!ossl_init_thread())
goto err;
if (!CRYPTO_THREAD_init_local(&in_init_config_local, NULL))
goto err;
base_inited = 1;
return 1;
err:
OSSL_TRACE(INIT, "ossl_init_base failed!\n");
CRYPTO_THREAD_lock_free(optsdone_lock);
optsdone_lock = NULL;
CRYPTO_THREAD_lock_free(init_lock);
init_lock = NULL;
return 0;
}
static CRYPTO_ONCE register_atexit = CRYPTO_ONCE_STATIC_INIT;
#if !defined(OPENSSL_SYS_UEFI) && defined(_WIN32)
static int win32atexit(void)
{
OPENSSL_cleanup();
return 0;
}
#endif
DEFINE_RUN_ONCE_STATIC(ossl_init_register_atexit)
{
-#ifdef OPENSSL_INIT_DEBUG
+#ifndef OPENSSL_NO_ATEXIT
+# ifdef OPENSSL_INIT_DEBUG
fprintf(stderr, "OPENSSL_INIT: ossl_init_register_atexit()\n");
-#endif
-#ifndef OPENSSL_SYS_UEFI
-# if defined(_WIN32) && !defined(__BORLANDC__)
+# endif
+# ifndef OPENSSL_SYS_UEFI
+# if defined(_WIN32) && !defined(__BORLANDC__)
/* We use _onexit() in preference because it gets called on DLL unload */
if (_onexit(win32atexit) == NULL)
return 0;
-# else
+# else
if (atexit(OPENSSL_cleanup) != 0)
return 0;
+# endif
# endif
#endif
return 1;
}
DEFINE_RUN_ONCE_STATIC_ALT(ossl_init_no_register_atexit,
ossl_init_register_atexit)
{
#ifdef OPENSSL_INIT_DEBUG
fprintf(stderr, "OPENSSL_INIT: ossl_init_no_register_atexit ok!\n");
#endif
/* Do nothing in this case */
return 1;
}
static CRYPTO_ONCE load_crypto_nodelete = CRYPTO_ONCE_STATIC_INIT;
DEFINE_RUN_ONCE_STATIC(ossl_init_load_crypto_nodelete)
{
OSSL_TRACE(INIT, "ossl_init_load_crypto_nodelete()\n");
#if !defined(OPENSSL_USE_NODELETE) \
&& !defined(OPENSSL_NO_PINSHARED)
# if defined(DSO_WIN32) && !defined(_WIN32_WCE)
{
HMODULE handle = NULL;
BOOL ret;
/* We don't use the DSO route for WIN32 because there is a better way */
ret = GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS
| GET_MODULE_HANDLE_EX_FLAG_PIN,
(void *)&base_inited, &handle);
OSSL_TRACE1(INIT,
"ossl_init_load_crypto_nodelete: "
"obtained DSO reference? %s\n",
(ret == TRUE ? "No!" : "Yes."));
return (ret == TRUE) ? 1 : 0;
}
# elif !defined(DSO_NONE)
/*
* Deliberately leak a reference to ourselves. This will force the library
* to remain loaded until the atexit() handler is run at process exit.
*/
{
DSO *dso;
void *err;
if (!err_shelve_state(&err))
return 0;
dso = DSO_dsobyaddr(&base_inited, DSO_FLAG_NO_UNLOAD_ON_FREE);
/*
* In case of No!, it is uncertain our exit()-handlers can still be
* called. After dlclose() the whole library might have been unloaded
* already.
*/
OSSL_TRACE1(INIT, "obtained DSO reference? %s\n",
(dso == NULL ? "No!" : "Yes."));
DSO_free(dso);
err_unshelve_state(err);
}
# endif
#endif
return 1;
}
static CRYPTO_ONCE load_crypto_strings = CRYPTO_ONCE_STATIC_INIT;
DEFINE_RUN_ONCE_STATIC(ossl_init_load_crypto_strings)
{
int ret = 1;
/*
* OPENSSL_NO_AUTOERRINIT is provided here to prevent at compile time
* pulling in all the error strings during static linking
*/
#if !defined(OPENSSL_NO_ERR) && !defined(OPENSSL_NO_AUTOERRINIT)
OSSL_TRACE(INIT, "ossl_err_load_crypto_strings()\n");
ret = ossl_err_load_crypto_strings();
#endif
return ret;
}
DEFINE_RUN_ONCE_STATIC_ALT(ossl_init_no_load_crypto_strings,
ossl_init_load_crypto_strings)
{
/* Do nothing in this case */
return 1;
}
static CRYPTO_ONCE add_all_ciphers = CRYPTO_ONCE_STATIC_INIT;
DEFINE_RUN_ONCE_STATIC(ossl_init_add_all_ciphers)
{
/*
* OPENSSL_NO_AUTOALGINIT is provided here to prevent at compile time
* pulling in all the ciphers during static linking
*/
#ifndef OPENSSL_NO_AUTOALGINIT
OSSL_TRACE(INIT, "openssl_add_all_ciphers_int()\n");
openssl_add_all_ciphers_int();
#endif
return 1;
}
DEFINE_RUN_ONCE_STATIC_ALT(ossl_init_no_add_all_ciphers,
ossl_init_add_all_ciphers)
{
/* Do nothing */
return 1;
}
static CRYPTO_ONCE add_all_digests = CRYPTO_ONCE_STATIC_INIT;
DEFINE_RUN_ONCE_STATIC(ossl_init_add_all_digests)
{
/*
* OPENSSL_NO_AUTOALGINIT is provided here to prevent at compile time
* pulling in all the ciphers during static linking
*/
#ifndef OPENSSL_NO_AUTOALGINIT
OSSL_TRACE(INIT, "openssl_add_all_digests()\n");
openssl_add_all_digests_int();
#endif
return 1;
}
DEFINE_RUN_ONCE_STATIC_ALT(ossl_init_no_add_all_digests,
ossl_init_add_all_digests)
{
/* Do nothing */
return 1;
}
static CRYPTO_ONCE config = CRYPTO_ONCE_STATIC_INIT;
static int config_inited = 0;
static const OPENSSL_INIT_SETTINGS *conf_settings = NULL;
DEFINE_RUN_ONCE_STATIC(ossl_init_config)
{
int ret = ossl_config_int(NULL);
config_inited = 1;
return ret;
}
DEFINE_RUN_ONCE_STATIC_ALT(ossl_init_config_settings, ossl_init_config)
{
int ret = ossl_config_int(conf_settings);
config_inited = 1;
return ret;
}
DEFINE_RUN_ONCE_STATIC_ALT(ossl_init_no_config, ossl_init_config)
{
OSSL_TRACE(INIT, "ossl_no_config_int()\n");
ossl_no_config_int();
config_inited = 1;
return 1;
}
static CRYPTO_ONCE async = CRYPTO_ONCE_STATIC_INIT;
static int async_inited = 0;
DEFINE_RUN_ONCE_STATIC(ossl_init_async)
{
OSSL_TRACE(INIT, "async_init()\n");
if (!async_init())
return 0;
async_inited = 1;
return 1;
}
#ifndef OPENSSL_NO_ENGINE
static CRYPTO_ONCE engine_openssl = CRYPTO_ONCE_STATIC_INIT;
DEFINE_RUN_ONCE_STATIC(ossl_init_engine_openssl)
{
OSSL_TRACE(INIT, "engine_load_openssl_int()\n");
engine_load_openssl_int();
return 1;
}
# ifndef OPENSSL_NO_RDRAND
static CRYPTO_ONCE engine_rdrand = CRYPTO_ONCE_STATIC_INIT;
DEFINE_RUN_ONCE_STATIC(ossl_init_engine_rdrand)
{
OSSL_TRACE(INIT, "engine_load_rdrand_int()\n");
engine_load_rdrand_int();
return 1;
}
# endif
static CRYPTO_ONCE engine_dynamic = CRYPTO_ONCE_STATIC_INIT;
DEFINE_RUN_ONCE_STATIC(ossl_init_engine_dynamic)
{
OSSL_TRACE(INIT, "engine_load_dynamic_int()\n");
engine_load_dynamic_int();
return 1;
}
# ifndef OPENSSL_NO_STATIC_ENGINE
# ifndef OPENSSL_NO_DEVCRYPTOENG
static CRYPTO_ONCE engine_devcrypto = CRYPTO_ONCE_STATIC_INIT;
DEFINE_RUN_ONCE_STATIC(ossl_init_engine_devcrypto)
{
OSSL_TRACE(INIT, "engine_load_devcrypto_int()\n");
engine_load_devcrypto_int();
return 1;
}
# endif
# if !defined(OPENSSL_NO_PADLOCKENG)
static CRYPTO_ONCE engine_padlock = CRYPTO_ONCE_STATIC_INIT;
DEFINE_RUN_ONCE_STATIC(ossl_init_engine_padlock)
{
OSSL_TRACE(INIT, "engine_load_padlock_int()\n");
engine_load_padlock_int();
return 1;
}
# endif
# if defined(OPENSSL_SYS_WIN32) && !defined(OPENSSL_NO_CAPIENG)
static CRYPTO_ONCE engine_capi = CRYPTO_ONCE_STATIC_INIT;
DEFINE_RUN_ONCE_STATIC(ossl_init_engine_capi)
{
OSSL_TRACE(INIT, "engine_load_capi_int()\n");
engine_load_capi_int();
return 1;
}
# endif
# if !defined(OPENSSL_NO_AFALGENG)
static CRYPTO_ONCE engine_afalg = CRYPTO_ONCE_STATIC_INIT;
DEFINE_RUN_ONCE_STATIC(ossl_init_engine_afalg)
{
OSSL_TRACE(INIT, "engine_load_afalg_int()\n");
engine_load_afalg_int();
return 1;
}
# endif
# endif
#endif
void OPENSSL_cleanup(void)
{
OPENSSL_INIT_STOP *currhandler, *lasthandler;
/*
* At some point we should consider looking at this function with a view to
* moving most/all of this into onfree handlers in OSSL_LIB_CTX.
*/
/* If we've not been inited then no need to deinit */
if (!base_inited)
return;
/* Might be explicitly called and also by atexit */
if (stopped)
return;
stopped = 1;
/*
* Thread stop may not get automatically called by the thread library for
* the very last thread in some situations, so call it directly.
*/
OPENSSL_thread_stop();
currhandler = stop_handlers;
while (currhandler != NULL) {
currhandler->handler();
lasthandler = currhandler;
currhandler = currhandler->next;
OPENSSL_free(lasthandler);
}
stop_handlers = NULL;
CRYPTO_THREAD_lock_free(optsdone_lock);
optsdone_lock = NULL;
CRYPTO_THREAD_lock_free(init_lock);
init_lock = NULL;
CRYPTO_THREAD_cleanup_local(&in_init_config_local);
/*
* We assume we are single-threaded for this function, i.e. no race
* conditions for the various "*_inited" vars below.
*/
#ifndef OPENSSL_NO_COMP
OSSL_TRACE(INIT, "OPENSSL_cleanup: ossl_comp_zlib_cleanup()\n");
ossl_comp_zlib_cleanup();
#endif
if (async_inited) {
OSSL_TRACE(INIT, "OPENSSL_cleanup: async_deinit()\n");
async_deinit();
}
/*
* Note that cleanup order is important:
* - ossl_rand_cleanup_int could call an ENGINE's RAND cleanup function so
* must be called before engine_cleanup_int()
* - ENGINEs use CRYPTO_EX_DATA and therefore, must be cleaned up
* before the ex data handlers are wiped during default ossl_lib_ctx deinit.
* - ossl_config_modules_free() can end up in ENGINE code so must be called
* before engine_cleanup_int()
* - ENGINEs and additional EVP algorithms might use added OIDs names so
* ossl_obj_cleanup_int() must be called last
*/
OSSL_TRACE(INIT, "OPENSSL_cleanup: ossl_rand_cleanup_int()\n");
ossl_rand_cleanup_int();
OSSL_TRACE(INIT, "OPENSSL_cleanup: ossl_config_modules_free()\n");
ossl_config_modules_free();
#ifndef OPENSSL_NO_ENGINE
OSSL_TRACE(INIT, "OPENSSL_cleanup: engine_cleanup_int()\n");
engine_cleanup_int();
#endif
#ifndef OPENSSL_NO_DEPRECATED_3_0
OSSL_TRACE(INIT, "OPENSSL_cleanup: ossl_store_cleanup_int()\n");
ossl_store_cleanup_int();
#endif
OSSL_TRACE(INIT, "OPENSSL_cleanup: ossl_lib_ctx_default_deinit()\n");
ossl_lib_ctx_default_deinit();
ossl_cleanup_thread();
OSSL_TRACE(INIT, "OPENSSL_cleanup: bio_cleanup()\n");
bio_cleanup();
OSSL_TRACE(INIT, "OPENSSL_cleanup: evp_cleanup_int()\n");
evp_cleanup_int();
OSSL_TRACE(INIT, "OPENSSL_cleanup: ossl_obj_cleanup_int()\n");
ossl_obj_cleanup_int();
OSSL_TRACE(INIT, "OPENSSL_cleanup: err_int()\n");
err_cleanup();
OSSL_TRACE(INIT, "OPENSSL_cleanup: CRYPTO_secure_malloc_done()\n");
CRYPTO_secure_malloc_done();
#ifndef OPENSSL_NO_CMP
OSSL_TRACE(INIT, "OPENSSL_cleanup: OSSL_CMP_log_close()\n");
OSSL_CMP_log_close();
#endif
OSSL_TRACE(INIT, "OPENSSL_cleanup: ossl_trace_cleanup()\n");
ossl_trace_cleanup();
base_inited = 0;
}
/*
* If this function is called with a non NULL settings value then it must be
* called prior to any threads making calls to any OpenSSL functions,
* i.e. passing a non-null settings value is assumed to be single-threaded.
*/
int OPENSSL_init_crypto(uint64_t opts, const OPENSSL_INIT_SETTINGS *settings)
{
uint64_t tmp;
int aloaddone = 0;
/* Applications depend on 0 being returned when cleanup was already done */
if (stopped) {
if (!(opts & OPENSSL_INIT_BASE_ONLY))
ERR_raise(ERR_LIB_CRYPTO, ERR_R_INIT_FAIL);
return 0;
}
/*
* We ignore failures from this function. It is probably because we are
* on a platform that doesn't support lockless atomic loads (we may not
* have created optsdone_lock yet so we can't use it). This is just an
* optimisation to skip the full checks in this function if we don't need
* to, so we carry on regardless in the event of failure.
*
* There could be a race here with other threads, so that optsdone has not
* been updated yet, even though the options have in fact been initialised.
* This doesn't matter - it just means we will run the full function
* unnecessarily - but all the critical code is contained in RUN_ONCE
* functions anyway so we are safe.
*/
if (CRYPTO_atomic_load(&optsdone, &tmp, NULL)) {
if ((tmp & opts) == opts)
return 1;
aloaddone = 1;
}
/*
* At some point we should look at this function with a view to moving
* most/all of this into OSSL_LIB_CTX.
*
* When the caller specifies OPENSSL_INIT_BASE_ONLY, that should be the
* *only* option specified. With that option we return immediately after
* doing the requested limited initialization. Note that
* err_shelve_state() called by us via ossl_init_load_crypto_nodelete()
* re-enters OPENSSL_init_crypto() with OPENSSL_INIT_BASE_ONLY, but with
* base already initialized this is a harmless NOOP.
*
* If we remain the only caller of err_shelve_state() the recursion should
* perhaps be removed, but if in doubt, it can be left in place.
*/
if (!RUN_ONCE(&base, ossl_init_base))
return 0;
if (opts & OPENSSL_INIT_BASE_ONLY)
return 1;
/*
* optsdone_lock should definitely be set up now, so we can now repeat the
* same check from above but be sure that it will work even on platforms
* without lockless CRYPTO_atomic_load
*/
if (!aloaddone) {
if (!CRYPTO_atomic_load(&optsdone, &tmp, optsdone_lock))
return 0;
if ((tmp & opts) == opts)
return 1;
}
/*
* Now we don't always set up exit handlers, the INIT_BASE_ONLY calls
* should not have the side-effect of setting up exit handlers, and
* therefore, this code block is below the INIT_BASE_ONLY-conditioned early
* return above.
*/
if ((opts & OPENSSL_INIT_NO_ATEXIT) != 0) {
if (!RUN_ONCE_ALT(&register_atexit, ossl_init_no_register_atexit,
ossl_init_register_atexit))
return 0;
} else if (!RUN_ONCE(&register_atexit, ossl_init_register_atexit)) {
return 0;
}
if (!RUN_ONCE(&load_crypto_nodelete, ossl_init_load_crypto_nodelete))
return 0;
if ((opts & OPENSSL_INIT_NO_LOAD_CRYPTO_STRINGS)
&& !RUN_ONCE_ALT(&load_crypto_strings,
ossl_init_no_load_crypto_strings,
ossl_init_load_crypto_strings))
return 0;
if ((opts & OPENSSL_INIT_LOAD_CRYPTO_STRINGS)
&& !RUN_ONCE(&load_crypto_strings, ossl_init_load_crypto_strings))
return 0;
if ((opts & OPENSSL_INIT_NO_ADD_ALL_CIPHERS)
&& !RUN_ONCE_ALT(&add_all_ciphers, ossl_init_no_add_all_ciphers,
ossl_init_add_all_ciphers))
return 0;
if ((opts & OPENSSL_INIT_ADD_ALL_CIPHERS)
&& !RUN_ONCE(&add_all_ciphers, ossl_init_add_all_ciphers))
return 0;
if ((opts & OPENSSL_INIT_NO_ADD_ALL_DIGESTS)
&& !RUN_ONCE_ALT(&add_all_digests, ossl_init_no_add_all_digests,
ossl_init_add_all_digests))
return 0;
if ((opts & OPENSSL_INIT_ADD_ALL_DIGESTS)
&& !RUN_ONCE(&add_all_digests, ossl_init_add_all_digests))
return 0;
if ((opts & OPENSSL_INIT_ATFORK)
&& !openssl_init_fork_handlers())
return 0;
if ((opts & OPENSSL_INIT_NO_LOAD_CONFIG)
&& !RUN_ONCE_ALT(&config, ossl_init_no_config, ossl_init_config))
return 0;
if (opts & OPENSSL_INIT_LOAD_CONFIG) {
int loading = CRYPTO_THREAD_get_local(&in_init_config_local) != NULL;
/* If called recursively from OBJ_ calls, just skip it. */
if (!loading) {
int ret;
if (!CRYPTO_THREAD_set_local(&in_init_config_local, (void *)-1))
return 0;
if (settings == NULL) {
ret = RUN_ONCE(&config, ossl_init_config);
} else {
if (!CRYPTO_THREAD_write_lock(init_lock))
return 0;
conf_settings = settings;
ret = RUN_ONCE_ALT(&config, ossl_init_config_settings,
ossl_init_config);
conf_settings = NULL;
CRYPTO_THREAD_unlock(init_lock);
}
if (ret <= 0)
return 0;
}
}
if ((opts & OPENSSL_INIT_ASYNC)
&& !RUN_ONCE(&async, ossl_init_async))
return 0;
#ifndef OPENSSL_NO_ENGINE
if ((opts & OPENSSL_INIT_ENGINE_OPENSSL)
&& !RUN_ONCE(&engine_openssl, ossl_init_engine_openssl))
return 0;
# ifndef OPENSSL_NO_RDRAND
if ((opts & OPENSSL_INIT_ENGINE_RDRAND)
&& !RUN_ONCE(&engine_rdrand, ossl_init_engine_rdrand))
return 0;
# endif
if ((opts & OPENSSL_INIT_ENGINE_DYNAMIC)
&& !RUN_ONCE(&engine_dynamic, ossl_init_engine_dynamic))
return 0;
# ifndef OPENSSL_NO_STATIC_ENGINE
# ifndef OPENSSL_NO_DEVCRYPTOENG
if ((opts & OPENSSL_INIT_ENGINE_CRYPTODEV)
&& !RUN_ONCE(&engine_devcrypto, ossl_init_engine_devcrypto))
return 0;
# endif
# if !defined(OPENSSL_NO_PADLOCKENG)
if ((opts & OPENSSL_INIT_ENGINE_PADLOCK)
&& !RUN_ONCE(&engine_padlock, ossl_init_engine_padlock))
return 0;
# endif
# if defined(OPENSSL_SYS_WIN32) && !defined(OPENSSL_NO_CAPIENG)
if ((opts & OPENSSL_INIT_ENGINE_CAPI)
&& !RUN_ONCE(&engine_capi, ossl_init_engine_capi))
return 0;
# endif
# if !defined(OPENSSL_NO_AFALGENG)
if ((opts & OPENSSL_INIT_ENGINE_AFALG)
&& !RUN_ONCE(&engine_afalg, ossl_init_engine_afalg))
return 0;
# endif
# endif
if (opts & (OPENSSL_INIT_ENGINE_ALL_BUILTIN
| OPENSSL_INIT_ENGINE_OPENSSL
| OPENSSL_INIT_ENGINE_AFALG)) {
ENGINE_register_all_complete();
}
#endif
if (!CRYPTO_atomic_or(&optsdone, opts, &tmp, optsdone_lock))
return 0;
return 1;
}
int OPENSSL_atexit(void (*handler)(void))
{
OPENSSL_INIT_STOP *newhand;
#if !defined(OPENSSL_USE_NODELETE)\
&& !defined(OPENSSL_NO_PINSHARED)
{
# if defined(DSO_WIN32) && !defined(_WIN32_WCE)
HMODULE handle = NULL;
BOOL ret;
union {
void *sym;
void (*func)(void);
} handlersym;
handlersym.func = handler;
/*
* We don't use the DSO route for WIN32 because there is a better
* way
*/
ret = GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS
| GET_MODULE_HANDLE_EX_FLAG_PIN,
handlersym.sym, &handle);
if (!ret)
return 0;
# elif !defined(DSO_NONE)
/*
* Deliberately leak a reference to the handler. This will force the
* library/code containing the handler to remain loaded until we run the
* atexit handler. If -znodelete has been used then this is
* unnecessary.
*/
DSO *dso = NULL;
union {
void *sym;
void (*func)(void);
} handlersym;
handlersym.func = handler;
ERR_set_mark();
dso = DSO_dsobyaddr(handlersym.sym, DSO_FLAG_NO_UNLOAD_ON_FREE);
/* See same code above in ossl_init_base() for an explanation. */
OSSL_TRACE1(INIT,
"atexit: obtained DSO reference? %s\n",
(dso == NULL ? "No!" : "Yes."));
DSO_free(dso);
ERR_pop_to_mark();
# endif
}
#endif
if ((newhand = OPENSSL_malloc(sizeof(*newhand))) == NULL) {
ERR_raise(ERR_LIB_CRYPTO, ERR_R_MALLOC_FAILURE);
return 0;
}
newhand->handler = handler;
newhand->next = stop_handlers;
stop_handlers = newhand;
return 1;
}
diff --git a/crypto/openssl/crypto/o_str.c b/crypto/openssl/crypto/o_str.c
index 7fa487dd5fcd..c631f8aff26a 100644
--- a/crypto/openssl/crypto/o_str.c
+++ b/crypto/openssl/crypto/o_str.c
@@ -1,366 +1,366 @@
/*
- * Copyright 2003-2022 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2003-2024 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include "e_os.h"
#include <string.h>
#include <limits.h>
#include <openssl/crypto.h>
#include "crypto/ctype.h"
#include "internal/cryptlib.h"
#include "internal/thread_once.h"
#define DEFAULT_SEPARATOR ':'
#define CH_ZERO '\0'
char *CRYPTO_strdup(const char *str, const char* file, int line)
{
char *ret;
if (str == NULL)
return NULL;
ret = CRYPTO_malloc(strlen(str) + 1, file, line);
if (ret != NULL)
strcpy(ret, str);
return ret;
}
char *CRYPTO_strndup(const char *str, size_t s, const char* file, int line)
{
size_t maxlen;
char *ret;
if (str == NULL)
return NULL;
maxlen = OPENSSL_strnlen(str, s);
ret = CRYPTO_malloc(maxlen + 1, file, line);
if (ret) {
memcpy(ret, str, maxlen);
ret[maxlen] = CH_ZERO;
}
return ret;
}
void *CRYPTO_memdup(const void *data, size_t siz, const char* file, int line)
{
void *ret;
if (data == NULL || siz >= INT_MAX)
return NULL;
ret = CRYPTO_malloc(siz, file, line);
if (ret == NULL) {
ERR_raise(ERR_LIB_CRYPTO, ERR_R_MALLOC_FAILURE);
return NULL;
}
return memcpy(ret, data, siz);
}
size_t OPENSSL_strnlen(const char *str, size_t maxlen)
{
const char *p;
for (p = str; maxlen-- != 0 && *p != CH_ZERO; ++p) ;
return p - str;
}
size_t OPENSSL_strlcpy(char *dst, const char *src, size_t size)
{
size_t l = 0;
for (; size > 1 && *src; size--) {
*dst++ = *src++;
l++;
}
if (size)
*dst = CH_ZERO;
return l + strlen(src);
}
size_t OPENSSL_strlcat(char *dst, const char *src, size_t size)
{
size_t l = 0;
for (; size > 0 && *dst; size--, dst++)
l++;
return l + OPENSSL_strlcpy(dst, src, size);
}
int OPENSSL_hexchar2int(unsigned char c)
{
#ifdef CHARSET_EBCDIC
c = os_toebcdic[c];
#endif
switch (c) {
case '0':
return 0;
case '1':
return 1;
case '2':
return 2;
case '3':
return 3;
case '4':
return 4;
case '5':
return 5;
case '6':
return 6;
case '7':
return 7;
case '8':
return 8;
case '9':
return 9;
case 'a': case 'A':
return 0x0A;
case 'b': case 'B':
return 0x0B;
case 'c': case 'C':
return 0x0C;
case 'd': case 'D':
return 0x0D;
case 'e': case 'E':
return 0x0E;
case 'f': case 'F':
return 0x0F;
}
return -1;
}
static int hexstr2buf_sep(unsigned char *buf, size_t buf_n, size_t *buflen,
const char *str, const char sep)
{
unsigned char *q;
unsigned char ch, cl;
int chi, cli;
const unsigned char *p;
size_t cnt;
for (p = (const unsigned char *)str, q = buf, cnt = 0; *p; ) {
ch = *p++;
/* A separator of CH_ZERO means there is no separator */
if (ch == sep && sep != CH_ZERO)
continue;
cl = *p++;
if (!cl) {
ERR_raise(ERR_LIB_CRYPTO, CRYPTO_R_ODD_NUMBER_OF_DIGITS);
return 0;
}
cli = OPENSSL_hexchar2int(cl);
chi = OPENSSL_hexchar2int(ch);
if (cli < 0 || chi < 0) {
ERR_raise(ERR_LIB_CRYPTO, CRYPTO_R_ILLEGAL_HEX_DIGIT);
return 0;
}
cnt++;
if (q != NULL) {
if (cnt > buf_n) {
ERR_raise(ERR_LIB_CRYPTO, CRYPTO_R_TOO_SMALL_BUFFER);
return 0;
}
*q++ = (unsigned char)((chi << 4) | cli);
}
}
if (buflen != NULL)
*buflen = cnt;
return 1;
}
/*
* Given a string of hex digits convert to a buffer
*/
int OPENSSL_hexstr2buf_ex(unsigned char *buf, size_t buf_n, size_t *buflen,
const char *str, const char sep)
{
return hexstr2buf_sep(buf, buf_n, buflen, str, sep);
}
unsigned char *ossl_hexstr2buf_sep(const char *str, long *buflen,
const char sep)
{
unsigned char *buf;
size_t buf_n, tmp_buflen;
buf_n = strlen(str);
if (buf_n <= 1) {
ERR_raise(ERR_LIB_CRYPTO, CRYPTO_R_HEX_STRING_TOO_SHORT);
return NULL;
}
buf_n /= 2;
if ((buf = OPENSSL_malloc(buf_n)) == NULL) {
ERR_raise(ERR_LIB_CRYPTO, ERR_R_MALLOC_FAILURE);
return NULL;
}
if (buflen != NULL)
*buflen = 0;
tmp_buflen = 0;
if (hexstr2buf_sep(buf, buf_n, &tmp_buflen, str, sep)) {
if (buflen != NULL)
*buflen = (long)tmp_buflen;
return buf;
}
OPENSSL_free(buf);
return NULL;
}
unsigned char *OPENSSL_hexstr2buf(const char *str, long *buflen)
{
return ossl_hexstr2buf_sep(str, buflen, DEFAULT_SEPARATOR);
}
static int buf2hexstr_sep(char *str, size_t str_n, size_t *strlength,
const unsigned char *buf, size_t buflen,
const char sep)
{
static const char hexdig[] = "0123456789ABCDEF";
const unsigned char *p;
char *q;
size_t i;
int has_sep = (sep != CH_ZERO);
size_t len = has_sep ? buflen * 3 : 1 + buflen * 2;
if (strlength != NULL)
*strlength = len;
if (str == NULL)
return 1;
if (str_n < (unsigned long)len) {
ERR_raise(ERR_LIB_CRYPTO, CRYPTO_R_TOO_SMALL_BUFFER);
return 0;
}
q = str;
for (i = 0, p = buf; i < buflen; i++, p++) {
*q++ = hexdig[(*p >> 4) & 0xf];
*q++ = hexdig[*p & 0xf];
if (has_sep)
*q++ = sep;
}
if (has_sep)
--q;
*q = CH_ZERO;
#ifdef CHARSET_EBCDIC
- ebcdic2ascii(str, str, q - str - 1);
+ ebcdic2ascii(str, str, q - str);
#endif
return 1;
}
int OPENSSL_buf2hexstr_ex(char *str, size_t str_n, size_t *strlength,
const unsigned char *buf, size_t buflen,
const char sep)
{
return buf2hexstr_sep(str, str_n, strlength, buf, buflen, sep);
}
char *ossl_buf2hexstr_sep(const unsigned char *buf, long buflen, char sep)
{
char *tmp;
size_t tmp_n;
if (buflen == 0)
return OPENSSL_zalloc(1);
tmp_n = (sep != CH_ZERO) ? buflen * 3 : 1 + buflen * 2;
if ((tmp = OPENSSL_malloc(tmp_n)) == NULL) {
ERR_raise(ERR_LIB_CRYPTO, ERR_R_MALLOC_FAILURE);
return NULL;
}
if (buf2hexstr_sep(tmp, tmp_n, NULL, buf, buflen, sep))
return tmp;
OPENSSL_free(tmp);
return NULL;
}
/*
* Given a buffer of length 'len' return a OPENSSL_malloc'ed string with its
* hex representation @@@ (Contents of buffer are always kept in ASCII, also
* on EBCDIC machines)
*/
char *OPENSSL_buf2hexstr(const unsigned char *buf, long buflen)
{
return ossl_buf2hexstr_sep(buf, buflen, ':');
}
int openssl_strerror_r(int errnum, char *buf, size_t buflen)
{
#if defined(_MSC_VER) && _MSC_VER>=1400 && !defined(_WIN32_WCE)
return !strerror_s(buf, buflen, errnum);
#elif defined(_GNU_SOURCE)
char *err;
/*
* GNU strerror_r may not actually set buf.
* It can return a pointer to some (immutable) static string in which case
* buf is left unused.
*/
err = strerror_r(errnum, buf, buflen);
if (err == NULL || buflen == 0)
return 0;
/*
* If err is statically allocated, err != buf and we need to copy the data.
* If err points somewhere inside buf, OPENSSL_strlcpy can handle this,
* since src and dest are not annotated with __restrict and the function
* reads src byte for byte and writes to dest.
* If err == buf we do not have to copy anything.
*/
if (err != buf)
OPENSSL_strlcpy(buf, err, buflen);
return 1;
#elif (defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 200112L) || \
(defined(_XOPEN_SOURCE) && _XOPEN_SOURCE >= 600)
/*
* We can use "real" strerror_r. The OpenSSL version differs in that it
* gives 1 on success and 0 on failure for consistency with other OpenSSL
* functions. Real strerror_r does it the other way around
*/
return !strerror_r(errnum, buf, buflen);
#else
char *err;
/* Fall back to non-thread safe strerror()...its all we can do */
if (buflen < 2)
return 0;
err = strerror(errnum);
/* Can this ever happen? */
if (err == NULL)
return 0;
OPENSSL_strlcpy(buf, err, buflen);
return 1;
#endif
}
int OPENSSL_strcasecmp(const char *s1, const char *s2)
{
int t;
while ((t = ossl_tolower(*s1) - ossl_tolower(*s2++)) == 0)
if (*s1++ == '\0')
return 0;
return t;
}
int OPENSSL_strncasecmp(const char *s1, const char *s2, size_t n)
{
int t;
size_t i;
for (i = 0; i < n; i++)
if ((t = ossl_tolower(*s1) - ossl_tolower(*s2++)) != 0)
return t;
else if (*s1++ == '\0')
return 0;
return 0;
}
diff --git a/crypto/openssl/crypto/property/property_parse.c b/crypto/openssl/crypto/property/property_parse.c
index 19ea39a786eb..45c798f1b50b 100644
--- a/crypto/openssl/crypto/property/property_parse.c
+++ b/crypto/openssl/crypto/property/property_parse.c
@@ -1,762 +1,763 @@
/*
- * Copyright 2019-2023 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2019-2024 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 <string.h>
#include <stdio.h>
#include <stdarg.h>
#include <openssl/err.h>
#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 "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;
if (n != t)
r = OPENSSL_realloc(r, sizeof(*r) + (n - 1) * sizeof(r->properties[0]));
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) {
*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/openssl/crypto/provider_core.c b/crypto/openssl/crypto/provider_core.c
index 4cadb6a9f02e..cb4233eb52fd 100644
--- a/crypto/openssl/crypto/provider_core.c
+++ b/crypto/openssl/crypto/provider_core.c
@@ -1,2173 +1,2180 @@
/*
- * Copyright 2019-2023 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2019-2024 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 <assert.h>
#include <openssl/core.h>
#include <openssl/core_dispatch.h>
#include <openssl/core_names.h>
#include <openssl/provider.h>
#include <openssl/params.h>
#include <openssl/opensslv.h>
#include "crypto/cryptlib.h"
#ifndef FIPS_MODULE
#include "crypto/decoder.h" /* ossl_decoder_store_cache_flush */
#include "crypto/encoder.h" /* ossl_encoder_store_cache_flush */
#include "crypto/store.h" /* ossl_store_loader_store_cache_flush */
#endif
#include "crypto/evp.h" /* evp_method_store_cache_flush */
#include "crypto/rand.h"
#include "internal/nelem.h"
#include "internal/thread_once.h"
#include "internal/provider.h"
#include "internal/refcount.h"
#include "internal/bio.h"
#include "internal/core.h"
#include "provider_local.h"
#ifndef FIPS_MODULE
# include <openssl/self_test.h>
#endif
/*
* This file defines and uses a number of different structures:
*
* OSSL_PROVIDER (provider_st): Used to represent all information related to a
* single instance of a provider.
*
* provider_store_st: Holds information about the collection of providers that
* are available within the current library context (OSSL_LIB_CTX). It also
* holds configuration information about providers that could be loaded at some
* future point.
*
* OSSL_PROVIDER_CHILD_CB: An instance of this structure holds the callbacks
* that have been registered for a child library context and the associated
* provider that registered those callbacks.
*
* Where a child library context exists then it has its own instance of the
* provider store. Each provider that exists in the parent provider store, has
* an associated child provider in the child library context's provider store.
* As providers get activated or deactivated this needs to be mirrored in the
* associated child providers.
*
* LOCKING
* =======
*
* There are a number of different locks used in this file and it is important
* to understand how they should be used in order to avoid deadlocks.
*
* Fields within a structure can often be "write once" on creation, and then
* "read many". Creation of a structure is done by a single thread, and
* therefore no lock is required for the "write once/read many" fields. It is
* safe for multiple threads to read these fields without a lock, because they
* will never be changed.
*
* However some fields may be changed after a structure has been created and
* shared between multiple threads. Where this is the case a lock is required.
*
* The locks available are:
*
* The provider flag_lock: Used to control updates to the various provider
* "flags" (flag_initialized, flag_activated, flag_fallback) and associated
* "counts" (activatecnt).
*
* The provider refcnt_lock: Only ever used to control updates to the provider
* refcnt value.
*
* The provider optbits_lock: Used to control access to the provider's
* operation_bits and operation_bits_sz fields.
*
* The store default_path_lock: Used to control access to the provider store's
* default search path value (default_path)
*
* The store lock: Used to control the stack of provider's held within the
* provider store, as well as the stack of registered child provider callbacks.
*
* As a general rule-of-thumb it is best to:
* - keep the scope of the code that is protected by a lock to the absolute
* minimum possible;
* - try to keep the scope of the lock to within a single function (i.e. avoid
* making calls to other functions while holding a lock);
* - try to only ever hold one lock at a time.
*
* Unfortunately, it is not always possible to stick to the above guidelines.
* Where they are not adhered to there is always a danger of inadvertently
* introducing the possibility of deadlock. The following rules MUST be adhered
* to in order to avoid that:
* - Holding multiple locks at the same time is only allowed for the
* provider store lock, the provider flag_lock and the provider refcnt_lock.
* - When holding multiple locks they must be acquired in the following order of
* precedence:
* 1) provider store lock
* 2) provider flag_lock
* 3) provider refcnt_lock
* - When releasing locks they must be released in the reverse order to which
* they were acquired
* - No locks may be held when making an upcall. NOTE: Some common functions
* can make upcalls as part of their normal operation. If you need to call
* some other function while holding a lock make sure you know whether it
* will make any upcalls or not. For example ossl_provider_up_ref() can call
* ossl_provider_up_ref_parent() which can call the c_prov_up_ref() upcall.
* - It is permissible to hold the store and flag locks when calling child
* provider callbacks. No other locks may be held during such callbacks.
*/
static OSSL_PROVIDER *provider_new(const char *name,
OSSL_provider_init_fn *init_function,
STACK_OF(INFOPAIR) *parameters);
/*-
* Provider Object structure
* =========================
*/
#ifndef FIPS_MODULE
typedef struct {
OSSL_PROVIDER *prov;
int (*create_cb)(const OSSL_CORE_HANDLE *provider, void *cbdata);
int (*remove_cb)(const OSSL_CORE_HANDLE *provider, void *cbdata);
int (*global_props_cb)(const char *props, void *cbdata);
void *cbdata;
} OSSL_PROVIDER_CHILD_CB;
DEFINE_STACK_OF(OSSL_PROVIDER_CHILD_CB)
#endif
struct provider_store_st; /* Forward declaration */
struct ossl_provider_st {
/* Flag bits */
unsigned int flag_initialized:1;
unsigned int flag_activated:1;
unsigned int flag_fallback:1; /* Can be used as fallback */
/* Getting and setting the flags require synchronization */
CRYPTO_RWLOCK *flag_lock;
/* OpenSSL library side data */
CRYPTO_REF_COUNT refcnt;
CRYPTO_RWLOCK *refcnt_lock; /* For the ref counter */
int activatecnt;
char *name;
char *path;
DSO *module;
OSSL_provider_init_fn *init_function;
STACK_OF(INFOPAIR) *parameters;
OSSL_LIB_CTX *libctx; /* The library context this instance is in */
struct provider_store_st *store; /* The store this instance belongs to */
#ifndef FIPS_MODULE
/*
* In the FIPS module inner provider, this isn't needed, since the
* error upcalls are always direct calls to the outer provider.
*/
int error_lib; /* ERR library number, one for each provider */
# ifndef OPENSSL_NO_ERR
ERR_STRING_DATA *error_strings; /* Copy of what the provider gives us */
# endif
#endif
/* Provider side functions */
OSSL_FUNC_provider_teardown_fn *teardown;
OSSL_FUNC_provider_gettable_params_fn *gettable_params;
OSSL_FUNC_provider_get_params_fn *get_params;
OSSL_FUNC_provider_get_capabilities_fn *get_capabilities;
OSSL_FUNC_provider_self_test_fn *self_test;
OSSL_FUNC_provider_query_operation_fn *query_operation;
OSSL_FUNC_provider_unquery_operation_fn *unquery_operation;
/*
* Cache of bit to indicate of query_operation() has been called on
* a specific operation or not.
*/
unsigned char *operation_bits;
size_t operation_bits_sz;
CRYPTO_RWLOCK *opbits_lock;
#ifndef FIPS_MODULE
/* Whether this provider is the child of some other provider */
const OSSL_CORE_HANDLE *handle;
unsigned int ischild:1;
#endif
/* Provider side data */
void *provctx;
const OSSL_DISPATCH *dispatch;
};
DEFINE_STACK_OF(OSSL_PROVIDER)
static int ossl_provider_cmp(const OSSL_PROVIDER * const *a,
const OSSL_PROVIDER * const *b)
{
return strcmp((*a)->name, (*b)->name);
}
/*-
* Provider Object store
* =====================
*
* The Provider Object store is a library context object, and therefore needs
* an index.
*/
struct provider_store_st {
OSSL_LIB_CTX *libctx;
STACK_OF(OSSL_PROVIDER) *providers;
STACK_OF(OSSL_PROVIDER_CHILD_CB) *child_cbs;
CRYPTO_RWLOCK *default_path_lock;
CRYPTO_RWLOCK *lock;
char *default_path;
OSSL_PROVIDER_INFO *provinfo;
size_t numprovinfo;
size_t provinfosz;
unsigned int use_fallbacks:1;
unsigned int freeing:1;
};
/*
* provider_deactivate_free() is a wrapper around ossl_provider_deactivate()
* and ossl_provider_free(), called as needed.
* Since this is only called when the provider store is being emptied, we
* don't need to care about any lock.
*/
static void provider_deactivate_free(OSSL_PROVIDER *prov)
{
if (prov->flag_activated)
ossl_provider_deactivate(prov, 1);
ossl_provider_free(prov);
}
#ifndef FIPS_MODULE
static void ossl_provider_child_cb_free(OSSL_PROVIDER_CHILD_CB *cb)
{
OPENSSL_free(cb);
}
#endif
static void infopair_free(INFOPAIR *pair)
{
OPENSSL_free(pair->name);
OPENSSL_free(pair->value);
OPENSSL_free(pair);
}
static INFOPAIR *infopair_copy(const INFOPAIR *src)
{
INFOPAIR *dest = OPENSSL_zalloc(sizeof(*dest));
if (dest == NULL)
return NULL;
if (src->name != NULL) {
dest->name = OPENSSL_strdup(src->name);
if (dest->name == NULL)
goto err;
}
if (src->value != NULL) {
dest->value = OPENSSL_strdup(src->value);
if (dest->value == NULL)
goto err;
}
return dest;
err:
OPENSSL_free(dest->name);
OPENSSL_free(dest);
return NULL;
}
void ossl_provider_info_clear(OSSL_PROVIDER_INFO *info)
{
OPENSSL_free(info->name);
OPENSSL_free(info->path);
sk_INFOPAIR_pop_free(info->parameters, infopair_free);
}
static void provider_store_free(void *vstore)
{
struct provider_store_st *store = vstore;
size_t i;
if (store == NULL)
return;
store->freeing = 1;
OPENSSL_free(store->default_path);
sk_OSSL_PROVIDER_pop_free(store->providers, provider_deactivate_free);
#ifndef FIPS_MODULE
sk_OSSL_PROVIDER_CHILD_CB_pop_free(store->child_cbs,
ossl_provider_child_cb_free);
#endif
CRYPTO_THREAD_lock_free(store->default_path_lock);
CRYPTO_THREAD_lock_free(store->lock);
for (i = 0; i < store->numprovinfo; i++)
ossl_provider_info_clear(&store->provinfo[i]);
OPENSSL_free(store->provinfo);
OPENSSL_free(store);
}
static void *provider_store_new(OSSL_LIB_CTX *ctx)
{
struct provider_store_st *store = OPENSSL_zalloc(sizeof(*store));
if (store == NULL
|| (store->providers = sk_OSSL_PROVIDER_new(ossl_provider_cmp)) == NULL
|| (store->default_path_lock = CRYPTO_THREAD_lock_new()) == NULL
#ifndef FIPS_MODULE
|| (store->child_cbs = sk_OSSL_PROVIDER_CHILD_CB_new_null()) == NULL
#endif
|| (store->lock = CRYPTO_THREAD_lock_new()) == NULL) {
provider_store_free(store);
return NULL;
}
store->libctx = ctx;
store->use_fallbacks = 1;
return store;
}
static const OSSL_LIB_CTX_METHOD provider_store_method = {
/* Needs to be freed before the child provider data is freed */
OSSL_LIB_CTX_METHOD_PRIORITY_1,
provider_store_new,
provider_store_free,
};
static struct provider_store_st *get_provider_store(OSSL_LIB_CTX *libctx)
{
struct provider_store_st *store = NULL;
store = ossl_lib_ctx_get_data(libctx, OSSL_LIB_CTX_PROVIDER_STORE_INDEX,
&provider_store_method);
if (store == NULL)
ERR_raise(ERR_LIB_CRYPTO, ERR_R_INTERNAL_ERROR);
return store;
}
int ossl_provider_disable_fallback_loading(OSSL_LIB_CTX *libctx)
{
struct provider_store_st *store;
if ((store = get_provider_store(libctx)) != NULL) {
if (!CRYPTO_THREAD_write_lock(store->lock))
return 0;
store->use_fallbacks = 0;
CRYPTO_THREAD_unlock(store->lock);
return 1;
}
return 0;
}
#define BUILTINS_BLOCK_SIZE 10
int ossl_provider_info_add_to_store(OSSL_LIB_CTX *libctx,
OSSL_PROVIDER_INFO *entry)
{
struct provider_store_st *store = get_provider_store(libctx);
int ret = 0;
if (entry->name == NULL) {
ERR_raise(ERR_LIB_CRYPTO, ERR_R_PASSED_NULL_PARAMETER);
return 0;
}
if (store == NULL) {
ERR_raise(ERR_LIB_CRYPTO, ERR_R_INTERNAL_ERROR);
return 0;
}
if (!CRYPTO_THREAD_write_lock(store->lock))
return 0;
if (store->provinfosz == 0) {
store->provinfo = OPENSSL_zalloc(sizeof(*store->provinfo)
* BUILTINS_BLOCK_SIZE);
if (store->provinfo == NULL) {
ERR_raise(ERR_LIB_CRYPTO, ERR_R_MALLOC_FAILURE);
goto err;
}
store->provinfosz = BUILTINS_BLOCK_SIZE;
} else if (store->numprovinfo == store->provinfosz) {
OSSL_PROVIDER_INFO *tmpbuiltins;
size_t newsz = store->provinfosz + BUILTINS_BLOCK_SIZE;
tmpbuiltins = OPENSSL_realloc(store->provinfo,
sizeof(*store->provinfo) * newsz);
if (tmpbuiltins == NULL) {
ERR_raise(ERR_LIB_CRYPTO, ERR_R_MALLOC_FAILURE);
goto err;
}
store->provinfo = tmpbuiltins;
store->provinfosz = newsz;
}
store->provinfo[store->numprovinfo] = *entry;
store->numprovinfo++;
ret = 1;
err:
CRYPTO_THREAD_unlock(store->lock);
return ret;
}
OSSL_PROVIDER *ossl_provider_find(OSSL_LIB_CTX *libctx, const char *name,
ossl_unused int noconfig)
{
struct provider_store_st *store = NULL;
OSSL_PROVIDER *prov = NULL;
if ((store = get_provider_store(libctx)) != NULL) {
OSSL_PROVIDER tmpl = { 0, };
int i;
#if !defined(FIPS_MODULE) && !defined(OPENSSL_NO_AUTOLOAD_CONFIG)
/*
* Make sure any providers are loaded from config before we try to find
* them.
*/
if (!noconfig) {
if (ossl_lib_ctx_is_default(libctx))
OPENSSL_init_crypto(OPENSSL_INIT_LOAD_CONFIG, NULL);
}
#endif
tmpl.name = (char *)name;
/*
* A "find" operation can sort the stack, and therefore a write lock is
* required.
*/
if (!CRYPTO_THREAD_write_lock(store->lock))
return NULL;
if ((i = sk_OSSL_PROVIDER_find(store->providers, &tmpl)) != -1)
prov = sk_OSSL_PROVIDER_value(store->providers, i);
CRYPTO_THREAD_unlock(store->lock);
if (prov != NULL && !ossl_provider_up_ref(prov))
prov = NULL;
}
return prov;
}
/*-
* Provider Object methods
* =======================
*/
static OSSL_PROVIDER *provider_new(const char *name,
OSSL_provider_init_fn *init_function,
STACK_OF(INFOPAIR) *parameters)
{
OSSL_PROVIDER *prov = NULL;
if ((prov = OPENSSL_zalloc(sizeof(*prov))) == NULL
#ifndef HAVE_ATOMICS
|| (prov->refcnt_lock = CRYPTO_THREAD_lock_new()) == NULL
#endif
) {
OPENSSL_free(prov);
ERR_raise(ERR_LIB_CRYPTO, ERR_R_MALLOC_FAILURE);
return NULL;
}
prov->refcnt = 1; /* 1 One reference to be returned */
if ((prov->opbits_lock = CRYPTO_THREAD_lock_new()) == NULL
|| (prov->flag_lock = CRYPTO_THREAD_lock_new()) == NULL
|| (prov->name = OPENSSL_strdup(name)) == NULL
|| (prov->parameters = sk_INFOPAIR_deep_copy(parameters,
infopair_copy,
infopair_free)) == NULL) {
ossl_provider_free(prov);
ERR_raise(ERR_LIB_CRYPTO, ERR_R_MALLOC_FAILURE);
return NULL;
}
prov->init_function = init_function;
return prov;
}
int ossl_provider_up_ref(OSSL_PROVIDER *prov)
{
int ref = 0;
if (CRYPTO_UP_REF(&prov->refcnt, &ref, prov->refcnt_lock) <= 0)
return 0;
#ifndef FIPS_MODULE
if (prov->ischild) {
if (!ossl_provider_up_ref_parent(prov, 0)) {
ossl_provider_free(prov);
return 0;
}
}
#endif
return ref;
}
#ifndef FIPS_MODULE
static int provider_up_ref_intern(OSSL_PROVIDER *prov, int activate)
{
if (activate)
return ossl_provider_activate(prov, 1, 0);
return ossl_provider_up_ref(prov);
}
static int provider_free_intern(OSSL_PROVIDER *prov, int deactivate)
{
if (deactivate)
return ossl_provider_deactivate(prov, 1);
ossl_provider_free(prov);
return 1;
}
#endif
/*
* We assume that the requested provider does not already exist in the store.
* The caller should check. If it does exist then adding it to the store later
* will fail.
*/
OSSL_PROVIDER *ossl_provider_new(OSSL_LIB_CTX *libctx, const char *name,
OSSL_provider_init_fn *init_function,
int noconfig)
{
struct provider_store_st *store = NULL;
OSSL_PROVIDER_INFO template;
OSSL_PROVIDER *prov = NULL;
if ((store = get_provider_store(libctx)) == NULL)
return NULL;
memset(&template, 0, sizeof(template));
if (init_function == NULL) {
const OSSL_PROVIDER_INFO *p;
size_t i;
/* Check if this is a predefined builtin provider */
for (p = ossl_predefined_providers; p->name != NULL; p++) {
if (strcmp(p->name, name) == 0) {
template = *p;
break;
}
}
if (p->name == NULL) {
/* Check if this is a user added builtin provider */
if (!CRYPTO_THREAD_read_lock(store->lock))
return NULL;
for (i = 0, p = store->provinfo; i < store->numprovinfo; p++, i++) {
if (strcmp(p->name, name) == 0) {
template = *p;
break;
}
}
CRYPTO_THREAD_unlock(store->lock);
}
} else {
template.init = init_function;
}
/* provider_new() generates an error, so no need here */
- if ((prov = provider_new(name, template.init, template.parameters)) == NULL)
+ prov = provider_new(name, template.init, template.parameters);
+
+ if (prov == NULL)
+ return NULL;
+
+ if (!ossl_provider_set_module_path(prov, template.path)) {
+ ossl_provider_free(prov);
return NULL;
+ }
prov->libctx = libctx;
#ifndef FIPS_MODULE
prov->error_lib = ERR_get_next_error_library();
#endif
/*
* At this point, the provider is only partially "loaded". To be
* fully "loaded", ossl_provider_activate() must also be called and it must
* then be added to the provider store.
*/
return prov;
}
/* Assumes that the store lock is held */
static int create_provider_children(OSSL_PROVIDER *prov)
{
int ret = 1;
#ifndef FIPS_MODULE
struct provider_store_st *store = prov->store;
OSSL_PROVIDER_CHILD_CB *child_cb;
int i, max;
max = sk_OSSL_PROVIDER_CHILD_CB_num(store->child_cbs);
for (i = 0; i < max; i++) {
/*
* This is newly activated (activatecnt == 1), so we need to
* create child providers as necessary.
*/
child_cb = sk_OSSL_PROVIDER_CHILD_CB_value(store->child_cbs, i);
ret &= child_cb->create_cb((OSSL_CORE_HANDLE *)prov, child_cb->cbdata);
}
#endif
return ret;
}
int ossl_provider_add_to_store(OSSL_PROVIDER *prov, OSSL_PROVIDER **actualprov,
int retain_fallbacks)
{
struct provider_store_st *store;
int idx;
OSSL_PROVIDER tmpl = { 0, };
OSSL_PROVIDER *actualtmp = NULL;
if (actualprov != NULL)
*actualprov = NULL;
if ((store = get_provider_store(prov->libctx)) == NULL)
return 0;
if (!CRYPTO_THREAD_write_lock(store->lock))
return 0;
tmpl.name = (char *)prov->name;
idx = sk_OSSL_PROVIDER_find(store->providers, &tmpl);
if (idx == -1)
actualtmp = prov;
else
actualtmp = sk_OSSL_PROVIDER_value(store->providers, idx);
if (idx == -1) {
if (sk_OSSL_PROVIDER_push(store->providers, prov) == 0)
goto err;
prov->store = store;
if (!create_provider_children(prov)) {
sk_OSSL_PROVIDER_delete_ptr(store->providers, prov);
goto err;
}
if (!retain_fallbacks)
store->use_fallbacks = 0;
}
CRYPTO_THREAD_unlock(store->lock);
if (actualprov != NULL) {
if (!ossl_provider_up_ref(actualtmp)) {
ERR_raise(ERR_LIB_CRYPTO, ERR_R_MALLOC_FAILURE);
actualtmp = NULL;
return 0;
}
*actualprov = actualtmp;
}
if (idx >= 0) {
/*
* The provider is already in the store. Probably two threads
* independently initialised their own provider objects with the same
* name and raced to put them in the store. This thread lost. We
* deactivate the one we just created and use the one that already
* exists instead.
* If we get here then we know we did not create provider children
* above, so we inform ossl_provider_deactivate not to attempt to remove
* any.
*/
ossl_provider_deactivate(prov, 0);
ossl_provider_free(prov);
}
return 1;
err:
CRYPTO_THREAD_unlock(store->lock);
return 0;
}
void ossl_provider_free(OSSL_PROVIDER *prov)
{
if (prov != NULL) {
int ref = 0;
CRYPTO_DOWN_REF(&prov->refcnt, &ref, prov->refcnt_lock);
/*
* When the refcount drops to zero, we clean up the provider.
* Note that this also does teardown, which may seem late,
* considering that init happens on first activation. However,
* there may be other structures hanging on to the provider after
* the last deactivation and may therefore need full access to the
* provider's services. Therefore, we deinit late.
*/
if (ref == 0) {
if (prov->flag_initialized) {
ossl_provider_teardown(prov);
#ifndef OPENSSL_NO_ERR
# ifndef FIPS_MODULE
if (prov->error_strings != NULL) {
ERR_unload_strings(prov->error_lib, prov->error_strings);
OPENSSL_free(prov->error_strings);
prov->error_strings = NULL;
}
# endif
#endif
OPENSSL_free(prov->operation_bits);
prov->operation_bits = NULL;
prov->operation_bits_sz = 0;
prov->flag_initialized = 0;
}
#ifndef FIPS_MODULE
/*
* We deregister thread handling whether or not the provider was
* initialized. If init was attempted but was not successful then
* the provider may still have registered a thread handler.
*/
ossl_init_thread_deregister(prov);
DSO_free(prov->module);
#endif
OPENSSL_free(prov->name);
OPENSSL_free(prov->path);
sk_INFOPAIR_pop_free(prov->parameters, infopair_free);
CRYPTO_THREAD_lock_free(prov->opbits_lock);
CRYPTO_THREAD_lock_free(prov->flag_lock);
#ifndef HAVE_ATOMICS
CRYPTO_THREAD_lock_free(prov->refcnt_lock);
#endif
OPENSSL_free(prov);
}
#ifndef FIPS_MODULE
else if (prov->ischild) {
ossl_provider_free_parent(prov, 0);
}
#endif
}
}
/* Setters */
int ossl_provider_set_module_path(OSSL_PROVIDER *prov, const char *module_path)
{
OPENSSL_free(prov->path);
prov->path = NULL;
if (module_path == NULL)
return 1;
if ((prov->path = OPENSSL_strdup(module_path)) != NULL)
return 1;
ERR_raise(ERR_LIB_CRYPTO, ERR_R_MALLOC_FAILURE);
return 0;
}
static int infopair_add(STACK_OF(INFOPAIR) **infopairsk, const char *name,
const char *value)
{
INFOPAIR *pair = NULL;
if ((pair = OPENSSL_zalloc(sizeof(*pair))) != NULL
&& (*infopairsk != NULL
|| (*infopairsk = sk_INFOPAIR_new_null()) != NULL)
&& (pair->name = OPENSSL_strdup(name)) != NULL
&& (pair->value = OPENSSL_strdup(value)) != NULL
&& sk_INFOPAIR_push(*infopairsk, pair) > 0)
return 1;
if (pair != NULL) {
OPENSSL_free(pair->name);
OPENSSL_free(pair->value);
OPENSSL_free(pair);
}
ERR_raise(ERR_LIB_CRYPTO, ERR_R_MALLOC_FAILURE);
return 0;
}
int ossl_provider_add_parameter(OSSL_PROVIDER *prov,
const char *name, const char *value)
{
return infopair_add(&prov->parameters, name, value);
}
int ossl_provider_info_add_parameter(OSSL_PROVIDER_INFO *provinfo,
const char *name,
const char *value)
{
return infopair_add(&provinfo->parameters, name, value);
}
/*
* Provider activation.
*
* What "activation" means depends on the provider form; for built in
* providers (in the library or the application alike), the provider
* can already be considered to be loaded, all that's needed is to
* initialize it. However, for dynamically loadable provider modules,
* we must first load that module.
*
* Built in modules are distinguished from dynamically loaded modules
* with an already assigned init function.
*/
static const OSSL_DISPATCH *core_dispatch; /* Define further down */
int OSSL_PROVIDER_set_default_search_path(OSSL_LIB_CTX *libctx,
const char *path)
{
struct provider_store_st *store;
char *p = NULL;
if (path != NULL) {
p = OPENSSL_strdup(path);
if (p == NULL) {
ERR_raise(ERR_LIB_CRYPTO, ERR_R_MALLOC_FAILURE);
return 0;
}
}
if ((store = get_provider_store(libctx)) != NULL
&& CRYPTO_THREAD_write_lock(store->default_path_lock)) {
OPENSSL_free(store->default_path);
store->default_path = p;
CRYPTO_THREAD_unlock(store->default_path_lock);
return 1;
}
OPENSSL_free(p);
return 0;
}
/*
* Internal version that doesn't affect the store flags, and thereby avoid
* locking. Direct callers must remember to set the store flags when
* appropriate.
*/
static int provider_init(OSSL_PROVIDER *prov)
{
const OSSL_DISPATCH *provider_dispatch = NULL;
void *tmp_provctx = NULL; /* safety measure */
#ifndef OPENSSL_NO_ERR
# ifndef FIPS_MODULE
OSSL_FUNC_provider_get_reason_strings_fn *p_get_reason_strings = NULL;
# endif
#endif
int ok = 0;
if (!ossl_assert(!prov->flag_initialized)) {
ERR_raise(ERR_LIB_CRYPTO, ERR_R_INTERNAL_ERROR);
goto end;
}
/*
* If the init function isn't set, it indicates that this provider is
* a loadable module.
*/
if (prov->init_function == NULL) {
#ifdef FIPS_MODULE
goto end;
#else
if (prov->module == NULL) {
char *allocated_path = NULL;
const char *module_path = NULL;
char *merged_path = NULL;
const char *load_dir = NULL;
char *allocated_load_dir = NULL;
struct provider_store_st *store;
if ((prov->module = DSO_new()) == NULL) {
/* DSO_new() generates an error already */
goto end;
}
if ((store = get_provider_store(prov->libctx)) == NULL
|| !CRYPTO_THREAD_read_lock(store->default_path_lock))
goto end;
if (store->default_path != NULL) {
allocated_load_dir = OPENSSL_strdup(store->default_path);
CRYPTO_THREAD_unlock(store->default_path_lock);
if (allocated_load_dir == NULL) {
ERR_raise(ERR_LIB_CRYPTO, ERR_R_MALLOC_FAILURE);
goto end;
}
load_dir = allocated_load_dir;
} else {
CRYPTO_THREAD_unlock(store->default_path_lock);
}
if (load_dir == NULL) {
load_dir = ossl_safe_getenv("OPENSSL_MODULES");
if (load_dir == NULL)
load_dir = MODULESDIR;
}
DSO_ctrl(prov->module, DSO_CTRL_SET_FLAGS,
DSO_FLAG_NAME_TRANSLATION_EXT_ONLY, NULL);
module_path = prov->path;
if (module_path == NULL)
module_path = allocated_path =
DSO_convert_filename(prov->module, prov->name);
if (module_path != NULL)
merged_path = DSO_merge(prov->module, module_path, load_dir);
if (merged_path == NULL
|| (DSO_load(prov->module, merged_path, NULL, 0)) == NULL) {
DSO_free(prov->module);
prov->module = NULL;
}
OPENSSL_free(merged_path);
OPENSSL_free(allocated_path);
OPENSSL_free(allocated_load_dir);
}
if (prov->module == NULL) {
/* DSO has already recorded errors, this is just a tracepoint */
ERR_raise_data(ERR_LIB_CRYPTO, ERR_R_DSO_LIB,
"name=%s", prov->name);
goto end;
}
prov->init_function = (OSSL_provider_init_fn *)
DSO_bind_func(prov->module, "OSSL_provider_init");
#endif
}
/* Check for and call the initialise function for the provider. */
if (prov->init_function == NULL) {
ERR_raise_data(ERR_LIB_CRYPTO, ERR_R_UNSUPPORTED,
"name=%s, provider has no provider init function",
prov->name);
goto end;
}
if (!prov->init_function((OSSL_CORE_HANDLE *)prov, core_dispatch,
&provider_dispatch, &tmp_provctx)) {
ERR_raise_data(ERR_LIB_CRYPTO, ERR_R_INIT_FAIL,
"name=%s", prov->name);
goto end;
}
prov->provctx = tmp_provctx;
prov->dispatch = provider_dispatch;
if (provider_dispatch != NULL) {
for (; provider_dispatch->function_id != 0; provider_dispatch++) {
switch (provider_dispatch->function_id) {
case OSSL_FUNC_PROVIDER_TEARDOWN:
prov->teardown =
OSSL_FUNC_provider_teardown(provider_dispatch);
break;
case OSSL_FUNC_PROVIDER_GETTABLE_PARAMS:
prov->gettable_params =
OSSL_FUNC_provider_gettable_params(provider_dispatch);
break;
case OSSL_FUNC_PROVIDER_GET_PARAMS:
prov->get_params =
OSSL_FUNC_provider_get_params(provider_dispatch);
break;
case OSSL_FUNC_PROVIDER_SELF_TEST:
prov->self_test =
OSSL_FUNC_provider_self_test(provider_dispatch);
break;
case OSSL_FUNC_PROVIDER_GET_CAPABILITIES:
prov->get_capabilities =
OSSL_FUNC_provider_get_capabilities(provider_dispatch);
break;
case OSSL_FUNC_PROVIDER_QUERY_OPERATION:
prov->query_operation =
OSSL_FUNC_provider_query_operation(provider_dispatch);
break;
case OSSL_FUNC_PROVIDER_UNQUERY_OPERATION:
prov->unquery_operation =
OSSL_FUNC_provider_unquery_operation(provider_dispatch);
break;
#ifndef OPENSSL_NO_ERR
# ifndef FIPS_MODULE
case OSSL_FUNC_PROVIDER_GET_REASON_STRINGS:
p_get_reason_strings =
OSSL_FUNC_provider_get_reason_strings(provider_dispatch);
break;
# endif
#endif
}
}
}
#ifndef OPENSSL_NO_ERR
# ifndef FIPS_MODULE
if (p_get_reason_strings != NULL) {
const OSSL_ITEM *reasonstrings = p_get_reason_strings(prov->provctx);
size_t cnt, cnt2;
/*
* ERR_load_strings() handles ERR_STRING_DATA rather than OSSL_ITEM,
* although they are essentially the same type.
* Furthermore, ERR_load_strings() patches the array's error number
* with the error library number, so we need to make a copy of that
* array either way.
*/
cnt = 0;
while (reasonstrings[cnt].id != 0) {
if (ERR_GET_LIB(reasonstrings[cnt].id) != 0)
goto end;
cnt++;
}
cnt++; /* One for the terminating item */
/* Allocate one extra item for the "library" name */
prov->error_strings =
OPENSSL_zalloc(sizeof(ERR_STRING_DATA) * (cnt + 1));
if (prov->error_strings == NULL)
goto end;
/*
* Set the "library" name.
*/
prov->error_strings[0].error = ERR_PACK(prov->error_lib, 0, 0);
prov->error_strings[0].string = prov->name;
/*
* Copy reasonstrings item 0..cnt-1 to prov->error_trings positions
* 1..cnt.
*/
for (cnt2 = 1; cnt2 <= cnt; cnt2++) {
prov->error_strings[cnt2].error = (int)reasonstrings[cnt2-1].id;
prov->error_strings[cnt2].string = reasonstrings[cnt2-1].ptr;
}
ERR_load_strings(prov->error_lib, prov->error_strings);
}
# endif
#endif
/* With this flag set, this provider has become fully "loaded". */
prov->flag_initialized = 1;
ok = 1;
end:
return ok;
}
/*
* Deactivate a provider. If upcalls is 0 then we suppress any upcalls to a
* parent provider. If removechildren is 0 then we suppress any calls to remove
* child providers.
* Return -1 on failure and the activation count on success
*/
static int provider_deactivate(OSSL_PROVIDER *prov, int upcalls,
int removechildren)
{
int count;
struct provider_store_st *store;
#ifndef FIPS_MODULE
int freeparent = 0;
#endif
int lock = 1;
if (!ossl_assert(prov != NULL))
return -1;
/*
* No need to lock if we've got no store because we've not been shared with
* other threads.
*/
store = get_provider_store(prov->libctx);
if (store == NULL)
lock = 0;
if (lock && !CRYPTO_THREAD_read_lock(store->lock))
return -1;
if (lock && !CRYPTO_THREAD_write_lock(prov->flag_lock)) {
CRYPTO_THREAD_unlock(store->lock);
return -1;
}
#ifndef FIPS_MODULE
if (prov->activatecnt >= 2 && prov->ischild && upcalls) {
/*
* We have had a direct activation in this child libctx so we need to
* now down the ref count in the parent provider. We do the actual down
* ref outside of the flag_lock, since it could involve getting other
* locks.
*/
freeparent = 1;
}
#endif
if ((count = --prov->activatecnt) < 1)
prov->flag_activated = 0;
#ifndef FIPS_MODULE
else
removechildren = 0;
#endif
#ifndef FIPS_MODULE
if (removechildren && store != NULL) {
int i, max = sk_OSSL_PROVIDER_CHILD_CB_num(store->child_cbs);
OSSL_PROVIDER_CHILD_CB *child_cb;
for (i = 0; i < max; i++) {
child_cb = sk_OSSL_PROVIDER_CHILD_CB_value(store->child_cbs, i);
child_cb->remove_cb((OSSL_CORE_HANDLE *)prov, child_cb->cbdata);
}
}
#endif
if (lock) {
CRYPTO_THREAD_unlock(prov->flag_lock);
CRYPTO_THREAD_unlock(store->lock);
}
#ifndef FIPS_MODULE
if (freeparent)
ossl_provider_free_parent(prov, 1);
#endif
/* We don't deinit here, that's done in ossl_provider_free() */
return count;
}
/*
* Activate a provider.
* Return -1 on failure and the activation count on success
*/
static int provider_activate(OSSL_PROVIDER *prov, int lock, int upcalls)
{
int count = -1;
struct provider_store_st *store;
int ret = 1;
store = prov->store;
/*
* If the provider hasn't been added to the store, then we don't need
* any locks because we've not shared it with other threads.
*/
if (store == NULL) {
lock = 0;
if (!provider_init(prov))
return -1;
}
#ifndef FIPS_MODULE
if (prov->ischild && upcalls && !ossl_provider_up_ref_parent(prov, 1))
return -1;
#endif
if (lock && !CRYPTO_THREAD_read_lock(store->lock)) {
#ifndef FIPS_MODULE
if (prov->ischild && upcalls)
ossl_provider_free_parent(prov, 1);
#endif
return -1;
}
if (lock && !CRYPTO_THREAD_write_lock(prov->flag_lock)) {
CRYPTO_THREAD_unlock(store->lock);
#ifndef FIPS_MODULE
if (prov->ischild && upcalls)
ossl_provider_free_parent(prov, 1);
#endif
return -1;
}
count = ++prov->activatecnt;
prov->flag_activated = 1;
if (prov->activatecnt == 1 && store != NULL) {
ret = create_provider_children(prov);
}
if (lock) {
CRYPTO_THREAD_unlock(prov->flag_lock);
CRYPTO_THREAD_unlock(store->lock);
}
if (!ret)
return -1;
return count;
}
static int provider_flush_store_cache(const OSSL_PROVIDER *prov)
{
struct provider_store_st *store;
int freeing;
if ((store = get_provider_store(prov->libctx)) == NULL)
return 0;
if (!CRYPTO_THREAD_read_lock(store->lock))
return 0;
freeing = store->freeing;
CRYPTO_THREAD_unlock(store->lock);
if (!freeing) {
int acc
= evp_method_store_cache_flush(prov->libctx)
#ifndef FIPS_MODULE
+ ossl_encoder_store_cache_flush(prov->libctx)
+ ossl_decoder_store_cache_flush(prov->libctx)
+ ossl_store_loader_store_cache_flush(prov->libctx)
#endif
;
#ifndef FIPS_MODULE
return acc == 4;
#else
return acc == 1;
#endif
}
return 1;
}
static int provider_remove_store_methods(OSSL_PROVIDER *prov)
{
struct provider_store_st *store;
int freeing;
if ((store = get_provider_store(prov->libctx)) == NULL)
return 0;
if (!CRYPTO_THREAD_read_lock(store->lock))
return 0;
freeing = store->freeing;
CRYPTO_THREAD_unlock(store->lock);
if (!freeing) {
int acc;
if (!CRYPTO_THREAD_write_lock(prov->opbits_lock))
return 0;
OPENSSL_free(prov->operation_bits);
prov->operation_bits = NULL;
prov->operation_bits_sz = 0;
CRYPTO_THREAD_unlock(prov->opbits_lock);
acc = evp_method_store_remove_all_provided(prov)
#ifndef FIPS_MODULE
+ ossl_encoder_store_remove_all_provided(prov)
+ ossl_decoder_store_remove_all_provided(prov)
+ ossl_store_loader_store_remove_all_provided(prov)
#endif
;
#ifndef FIPS_MODULE
return acc == 4;
#else
return acc == 1;
#endif
}
return 1;
}
int ossl_provider_activate(OSSL_PROVIDER *prov, int upcalls, int aschild)
{
int count;
if (prov == NULL)
return 0;
#ifndef FIPS_MODULE
/*
* If aschild is true, then we only actually do the activation if the
* provider is a child. If its not, this is still success.
*/
if (aschild && !prov->ischild)
return 1;
#endif
if ((count = provider_activate(prov, 1, upcalls)) > 0)
return count == 1 ? provider_flush_store_cache(prov) : 1;
return 0;
}
int ossl_provider_deactivate(OSSL_PROVIDER *prov, int removechildren)
{
int count;
if (prov == NULL
|| (count = provider_deactivate(prov, 1, removechildren)) < 0)
return 0;
return count == 0 ? provider_remove_store_methods(prov) : 1;
}
void *ossl_provider_ctx(const OSSL_PROVIDER *prov)
{
return prov != NULL ? prov->provctx : NULL;
}
/*
* This function only does something once when store->use_fallbacks == 1,
* and then sets store->use_fallbacks = 0, so the second call and so on is
* effectively a no-op.
*/
static int provider_activate_fallbacks(struct provider_store_st *store)
{
int use_fallbacks;
int activated_fallback_count = 0;
int ret = 0;
const OSSL_PROVIDER_INFO *p;
if (!CRYPTO_THREAD_read_lock(store->lock))
return 0;
use_fallbacks = store->use_fallbacks;
CRYPTO_THREAD_unlock(store->lock);
if (!use_fallbacks)
return 1;
if (!CRYPTO_THREAD_write_lock(store->lock))
return 0;
/* Check again, just in case another thread changed it */
use_fallbacks = store->use_fallbacks;
if (!use_fallbacks) {
CRYPTO_THREAD_unlock(store->lock);
return 1;
}
for (p = ossl_predefined_providers; p->name != NULL; p++) {
OSSL_PROVIDER *prov = NULL;
if (!p->is_fallback)
continue;
/*
* We use the internal constructor directly here,
* otherwise we get a call loop
*/
prov = provider_new(p->name, p->init, NULL);
if (prov == NULL)
goto err;
prov->libctx = store->libctx;
#ifndef FIPS_MODULE
prov->error_lib = ERR_get_next_error_library();
#endif
/*
* We are calling provider_activate while holding the store lock. This
* means the init function will be called while holding a lock. Normally
* we try to avoid calling a user callback while holding a lock.
* However, fallbacks are never third party providers so we accept this.
*/
if (provider_activate(prov, 0, 0) < 0) {
ossl_provider_free(prov);
goto err;
}
prov->store = store;
if (sk_OSSL_PROVIDER_push(store->providers, prov) == 0) {
ossl_provider_free(prov);
goto err;
}
activated_fallback_count++;
}
if (activated_fallback_count > 0) {
store->use_fallbacks = 0;
ret = 1;
}
err:
CRYPTO_THREAD_unlock(store->lock);
return ret;
}
int ossl_provider_doall_activated(OSSL_LIB_CTX *ctx,
int (*cb)(OSSL_PROVIDER *provider,
void *cbdata),
void *cbdata)
{
int ret = 0, curr, max, ref = 0;
struct provider_store_st *store = get_provider_store(ctx);
STACK_OF(OSSL_PROVIDER) *provs = NULL;
#if !defined(FIPS_MODULE) && !defined(OPENSSL_NO_AUTOLOAD_CONFIG)
/*
* Make sure any providers are loaded from config before we try to use
* them.
*/
if (ossl_lib_ctx_is_default(ctx))
OPENSSL_init_crypto(OPENSSL_INIT_LOAD_CONFIG, NULL);
#endif
if (store == NULL)
return 1;
if (!provider_activate_fallbacks(store))
return 0;
/*
* Under lock, grab a copy of the provider list and up_ref each
* provider so that they don't disappear underneath us.
*/
if (!CRYPTO_THREAD_read_lock(store->lock))
return 0;
provs = sk_OSSL_PROVIDER_dup(store->providers);
if (provs == NULL) {
CRYPTO_THREAD_unlock(store->lock);
return 0;
}
max = sk_OSSL_PROVIDER_num(provs);
/*
* We work backwards through the stack so that we can safely delete items
* as we go.
*/
for (curr = max - 1; curr >= 0; curr--) {
OSSL_PROVIDER *prov = sk_OSSL_PROVIDER_value(provs, curr);
if (!CRYPTO_THREAD_write_lock(prov->flag_lock))
goto err_unlock;
if (prov->flag_activated) {
/*
* We call CRYPTO_UP_REF directly rather than ossl_provider_up_ref
* to avoid upping the ref count on the parent provider, which we
* must not do while holding locks.
*/
if (CRYPTO_UP_REF(&prov->refcnt, &ref, prov->refcnt_lock) <= 0) {
CRYPTO_THREAD_unlock(prov->flag_lock);
goto err_unlock;
}
/*
* It's already activated, but we up the activated count to ensure
* it remains activated until after we've called the user callback.
* We do this with no locking (because we already hold the locks)
* and no upcalls (which must not be called when locks are held). In
* theory this could mean the parent provider goes inactive, whilst
* still activated in the child for a short period. That's ok.
*/
if (provider_activate(prov, 0, 0) < 0) {
CRYPTO_DOWN_REF(&prov->refcnt, &ref, prov->refcnt_lock);
CRYPTO_THREAD_unlock(prov->flag_lock);
goto err_unlock;
}
} else {
sk_OSSL_PROVIDER_delete(provs, curr);
max--;
}
CRYPTO_THREAD_unlock(prov->flag_lock);
}
CRYPTO_THREAD_unlock(store->lock);
/*
* Now, we sweep through all providers not under lock
*/
for (curr = 0; curr < max; curr++) {
OSSL_PROVIDER *prov = sk_OSSL_PROVIDER_value(provs, curr);
if (!cb(prov, cbdata)) {
curr = -1;
goto finish;
}
}
curr = -1;
ret = 1;
goto finish;
err_unlock:
CRYPTO_THREAD_unlock(store->lock);
finish:
/*
* The pop_free call doesn't do what we want on an error condition. We
* either start from the first item in the stack, or part way through if
* we only processed some of the items.
*/
for (curr++; curr < max; curr++) {
OSSL_PROVIDER *prov = sk_OSSL_PROVIDER_value(provs, curr);
provider_deactivate(prov, 0, 1);
/*
* As above where we did the up-ref, we don't call ossl_provider_free
* to avoid making upcalls. There should always be at least one ref
* to the provider in the store, so this should never drop to 0.
*/
CRYPTO_DOWN_REF(&prov->refcnt, &ref, prov->refcnt_lock);
/*
* Not much we can do if this assert ever fails. So we don't use
* ossl_assert here.
*/
assert(ref > 0);
}
sk_OSSL_PROVIDER_free(provs);
return ret;
}
int OSSL_PROVIDER_available(OSSL_LIB_CTX *libctx, const char *name)
{
OSSL_PROVIDER *prov = NULL;
int available = 0;
struct provider_store_st *store = get_provider_store(libctx);
if (store == NULL || !provider_activate_fallbacks(store))
return 0;
prov = ossl_provider_find(libctx, name, 0);
if (prov != NULL) {
if (!CRYPTO_THREAD_read_lock(prov->flag_lock))
return 0;
available = prov->flag_activated;
CRYPTO_THREAD_unlock(prov->flag_lock);
ossl_provider_free(prov);
}
return available;
}
/* Setters of Provider Object data */
int ossl_provider_set_fallback(OSSL_PROVIDER *prov)
{
if (prov == NULL)
return 0;
prov->flag_fallback = 1;
return 1;
}
/* Getters of Provider Object data */
const char *ossl_provider_name(const OSSL_PROVIDER *prov)
{
return prov->name;
}
const DSO *ossl_provider_dso(const OSSL_PROVIDER *prov)
{
return prov->module;
}
const char *ossl_provider_module_name(const OSSL_PROVIDER *prov)
{
#ifdef FIPS_MODULE
return NULL;
#else
return DSO_get_filename(prov->module);
#endif
}
const char *ossl_provider_module_path(const OSSL_PROVIDER *prov)
{
#ifdef FIPS_MODULE
return NULL;
#else
/* FIXME: Ensure it's a full path */
return DSO_get_filename(prov->module);
#endif
}
void *ossl_provider_prov_ctx(const OSSL_PROVIDER *prov)
{
if (prov != NULL)
return prov->provctx;
return NULL;
}
const OSSL_DISPATCH *ossl_provider_get0_dispatch(const OSSL_PROVIDER *prov)
{
if (prov != NULL)
return prov->dispatch;
return NULL;
}
OSSL_LIB_CTX *ossl_provider_libctx(const OSSL_PROVIDER *prov)
{
return prov != NULL ? prov->libctx : NULL;
}
/* Wrappers around calls to the provider */
void ossl_provider_teardown(const OSSL_PROVIDER *prov)
{
if (prov->teardown != NULL
#ifndef FIPS_MODULE
&& !prov->ischild
#endif
)
prov->teardown(prov->provctx);
}
const OSSL_PARAM *ossl_provider_gettable_params(const OSSL_PROVIDER *prov)
{
return prov->gettable_params == NULL
? NULL : prov->gettable_params(prov->provctx);
}
int ossl_provider_get_params(const OSSL_PROVIDER *prov, OSSL_PARAM params[])
{
return prov->get_params == NULL
? 0 : prov->get_params(prov->provctx, params);
}
int ossl_provider_self_test(const OSSL_PROVIDER *prov)
{
int ret;
if (prov->self_test == NULL)
return 1;
ret = prov->self_test(prov->provctx);
if (ret == 0)
(void)provider_remove_store_methods((OSSL_PROVIDER *)prov);
return ret;
}
int ossl_provider_get_capabilities(const OSSL_PROVIDER *prov,
const char *capability,
OSSL_CALLBACK *cb,
void *arg)
{
return prov->get_capabilities == NULL
? 1 : prov->get_capabilities(prov->provctx, capability, cb, arg);
}
const OSSL_ALGORITHM *ossl_provider_query_operation(const OSSL_PROVIDER *prov,
int operation_id,
int *no_cache)
{
const OSSL_ALGORITHM *res;
if (prov->query_operation == NULL)
return NULL;
res = prov->query_operation(prov->provctx, operation_id, no_cache);
#if defined(OPENSSL_NO_CACHED_FETCH)
/* Forcing the non-caching of queries */
if (no_cache != NULL)
*no_cache = 1;
#endif
return res;
}
void ossl_provider_unquery_operation(const OSSL_PROVIDER *prov,
int operation_id,
const OSSL_ALGORITHM *algs)
{
if (prov->unquery_operation != NULL)
prov->unquery_operation(prov->provctx, operation_id, algs);
}
int ossl_provider_set_operation_bit(OSSL_PROVIDER *provider, size_t bitnum)
{
size_t byte = bitnum / 8;
unsigned char bit = (1 << (bitnum % 8)) & 0xFF;
if (!CRYPTO_THREAD_write_lock(provider->opbits_lock))
return 0;
if (provider->operation_bits_sz <= byte) {
unsigned char *tmp = OPENSSL_realloc(provider->operation_bits,
byte + 1);
if (tmp == NULL) {
CRYPTO_THREAD_unlock(provider->opbits_lock);
ERR_raise(ERR_LIB_CRYPTO, ERR_R_MALLOC_FAILURE);
return 0;
}
provider->operation_bits = tmp;
memset(provider->operation_bits + provider->operation_bits_sz,
'\0', byte + 1 - provider->operation_bits_sz);
provider->operation_bits_sz = byte + 1;
}
provider->operation_bits[byte] |= bit;
CRYPTO_THREAD_unlock(provider->opbits_lock);
return 1;
}
int ossl_provider_test_operation_bit(OSSL_PROVIDER *provider, size_t bitnum,
int *result)
{
size_t byte = bitnum / 8;
unsigned char bit = (1 << (bitnum % 8)) & 0xFF;
if (!ossl_assert(result != NULL)) {
ERR_raise(ERR_LIB_CRYPTO, ERR_R_PASSED_NULL_PARAMETER);
return 0;
}
*result = 0;
if (!CRYPTO_THREAD_read_lock(provider->opbits_lock))
return 0;
if (provider->operation_bits_sz > byte)
*result = ((provider->operation_bits[byte] & bit) != 0);
CRYPTO_THREAD_unlock(provider->opbits_lock);
return 1;
}
#ifndef FIPS_MODULE
const OSSL_CORE_HANDLE *ossl_provider_get_parent(OSSL_PROVIDER *prov)
{
return prov->handle;
}
int ossl_provider_is_child(const OSSL_PROVIDER *prov)
{
return prov->ischild;
}
int ossl_provider_set_child(OSSL_PROVIDER *prov, const OSSL_CORE_HANDLE *handle)
{
prov->handle = handle;
prov->ischild = 1;
return 1;
}
int ossl_provider_default_props_update(OSSL_LIB_CTX *libctx, const char *props)
{
#ifndef FIPS_MODULE
struct provider_store_st *store = NULL;
int i, max;
OSSL_PROVIDER_CHILD_CB *child_cb;
if ((store = get_provider_store(libctx)) == NULL)
return 0;
if (!CRYPTO_THREAD_read_lock(store->lock))
return 0;
max = sk_OSSL_PROVIDER_CHILD_CB_num(store->child_cbs);
for (i = 0; i < max; i++) {
child_cb = sk_OSSL_PROVIDER_CHILD_CB_value(store->child_cbs, i);
child_cb->global_props_cb(props, child_cb->cbdata);
}
CRYPTO_THREAD_unlock(store->lock);
#endif
return 1;
}
static int ossl_provider_register_child_cb(const OSSL_CORE_HANDLE *handle,
int (*create_cb)(
const OSSL_CORE_HANDLE *provider,
void *cbdata),
int (*remove_cb)(
const OSSL_CORE_HANDLE *provider,
void *cbdata),
int (*global_props_cb)(
const char *props,
void *cbdata),
void *cbdata)
{
/*
* This is really an OSSL_PROVIDER that we created and cast to
* OSSL_CORE_HANDLE originally. Therefore it is safe to cast it back.
*/
OSSL_PROVIDER *thisprov = (OSSL_PROVIDER *)handle;
OSSL_PROVIDER *prov;
OSSL_LIB_CTX *libctx = thisprov->libctx;
struct provider_store_st *store = NULL;
int ret = 0, i, max;
OSSL_PROVIDER_CHILD_CB *child_cb;
char *propsstr = NULL;
if ((store = get_provider_store(libctx)) == NULL)
return 0;
child_cb = OPENSSL_malloc(sizeof(*child_cb));
if (child_cb == NULL)
return 0;
child_cb->prov = thisprov;
child_cb->create_cb = create_cb;
child_cb->remove_cb = remove_cb;
child_cb->global_props_cb = global_props_cb;
child_cb->cbdata = cbdata;
if (!CRYPTO_THREAD_write_lock(store->lock)) {
OPENSSL_free(child_cb);
return 0;
}
propsstr = evp_get_global_properties_str(libctx, 0);
if (propsstr != NULL) {
global_props_cb(propsstr, cbdata);
OPENSSL_free(propsstr);
}
max = sk_OSSL_PROVIDER_num(store->providers);
for (i = 0; i < max; i++) {
int activated;
prov = sk_OSSL_PROVIDER_value(store->providers, i);
if (!CRYPTO_THREAD_read_lock(prov->flag_lock))
break;
activated = prov->flag_activated;
CRYPTO_THREAD_unlock(prov->flag_lock);
/*
* We hold the store lock while calling the user callback. This means
* that the user callback must be short and simple and not do anything
* likely to cause a deadlock. We don't hold the flag_lock during this
* call. In theory this means that another thread could deactivate it
* while we are calling create. This is ok because the other thread
* will also call remove_cb, but won't be able to do so until we release
* the store lock.
*/
if (activated && !create_cb((OSSL_CORE_HANDLE *)prov, cbdata))
break;
}
if (i == max) {
/* Success */
ret = sk_OSSL_PROVIDER_CHILD_CB_push(store->child_cbs, child_cb);
}
if (i != max || ret <= 0) {
/* Failed during creation. Remove everything we just added */
for (; i >= 0; i--) {
prov = sk_OSSL_PROVIDER_value(store->providers, i);
remove_cb((OSSL_CORE_HANDLE *)prov, cbdata);
}
OPENSSL_free(child_cb);
ret = 0;
}
CRYPTO_THREAD_unlock(store->lock);
return ret;
}
static void ossl_provider_deregister_child_cb(const OSSL_CORE_HANDLE *handle)
{
/*
* This is really an OSSL_PROVIDER that we created and cast to
* OSSL_CORE_HANDLE originally. Therefore it is safe to cast it back.
*/
OSSL_PROVIDER *thisprov = (OSSL_PROVIDER *)handle;
OSSL_LIB_CTX *libctx = thisprov->libctx;
struct provider_store_st *store = NULL;
int i, max;
OSSL_PROVIDER_CHILD_CB *child_cb;
if ((store = get_provider_store(libctx)) == NULL)
return;
if (!CRYPTO_THREAD_write_lock(store->lock))
return;
max = sk_OSSL_PROVIDER_CHILD_CB_num(store->child_cbs);
for (i = 0; i < max; i++) {
child_cb = sk_OSSL_PROVIDER_CHILD_CB_value(store->child_cbs, i);
if (child_cb->prov == thisprov) {
/* Found an entry */
sk_OSSL_PROVIDER_CHILD_CB_delete(store->child_cbs, i);
OPENSSL_free(child_cb);
break;
}
}
CRYPTO_THREAD_unlock(store->lock);
}
#endif
/*-
* Core functions for the provider
* ===============================
*
* This is the set of functions that the core makes available to the provider
*/
/*
* This returns a list of Provider Object parameters with their types, for
* discovery. We do not expect that many providers will use this, but one
* never knows.
*/
static const OSSL_PARAM param_types[] = {
OSSL_PARAM_DEFN(OSSL_PROV_PARAM_CORE_VERSION, OSSL_PARAM_UTF8_PTR, NULL, 0),
OSSL_PARAM_DEFN(OSSL_PROV_PARAM_CORE_PROV_NAME, OSSL_PARAM_UTF8_PTR,
NULL, 0),
#ifndef FIPS_MODULE
OSSL_PARAM_DEFN(OSSL_PROV_PARAM_CORE_MODULE_FILENAME, OSSL_PARAM_UTF8_PTR,
NULL, 0),
#endif
OSSL_PARAM_END
};
/*
* Forward declare all the functions that are provided aa dispatch.
* This ensures that the compiler will complain if they aren't defined
* with the correct signature.
*/
static OSSL_FUNC_core_gettable_params_fn core_gettable_params;
static OSSL_FUNC_core_get_params_fn core_get_params;
static OSSL_FUNC_core_get_libctx_fn core_get_libctx;
static OSSL_FUNC_core_thread_start_fn core_thread_start;
#ifndef FIPS_MODULE
static OSSL_FUNC_core_new_error_fn core_new_error;
static OSSL_FUNC_core_set_error_debug_fn core_set_error_debug;
static OSSL_FUNC_core_vset_error_fn core_vset_error;
static OSSL_FUNC_core_set_error_mark_fn core_set_error_mark;
static OSSL_FUNC_core_clear_last_error_mark_fn core_clear_last_error_mark;
static OSSL_FUNC_core_pop_error_to_mark_fn core_pop_error_to_mark;
OSSL_FUNC_BIO_new_file_fn ossl_core_bio_new_file;
OSSL_FUNC_BIO_new_membuf_fn ossl_core_bio_new_mem_buf;
OSSL_FUNC_BIO_read_ex_fn ossl_core_bio_read_ex;
OSSL_FUNC_BIO_write_ex_fn ossl_core_bio_write_ex;
OSSL_FUNC_BIO_gets_fn ossl_core_bio_gets;
OSSL_FUNC_BIO_puts_fn ossl_core_bio_puts;
OSSL_FUNC_BIO_up_ref_fn ossl_core_bio_up_ref;
OSSL_FUNC_BIO_free_fn ossl_core_bio_free;
OSSL_FUNC_BIO_vprintf_fn ossl_core_bio_vprintf;
OSSL_FUNC_BIO_vsnprintf_fn BIO_vsnprintf;
static OSSL_FUNC_self_test_cb_fn core_self_test_get_callback;
OSSL_FUNC_get_entropy_fn ossl_rand_get_entropy;
OSSL_FUNC_cleanup_entropy_fn ossl_rand_cleanup_entropy;
OSSL_FUNC_get_nonce_fn ossl_rand_get_nonce;
OSSL_FUNC_cleanup_nonce_fn ossl_rand_cleanup_nonce;
#endif
OSSL_FUNC_CRYPTO_malloc_fn CRYPTO_malloc;
OSSL_FUNC_CRYPTO_zalloc_fn CRYPTO_zalloc;
OSSL_FUNC_CRYPTO_free_fn CRYPTO_free;
OSSL_FUNC_CRYPTO_clear_free_fn CRYPTO_clear_free;
OSSL_FUNC_CRYPTO_realloc_fn CRYPTO_realloc;
OSSL_FUNC_CRYPTO_clear_realloc_fn CRYPTO_clear_realloc;
OSSL_FUNC_CRYPTO_secure_malloc_fn CRYPTO_secure_malloc;
OSSL_FUNC_CRYPTO_secure_zalloc_fn CRYPTO_secure_zalloc;
OSSL_FUNC_CRYPTO_secure_free_fn CRYPTO_secure_free;
OSSL_FUNC_CRYPTO_secure_clear_free_fn CRYPTO_secure_clear_free;
OSSL_FUNC_CRYPTO_secure_allocated_fn CRYPTO_secure_allocated;
OSSL_FUNC_OPENSSL_cleanse_fn OPENSSL_cleanse;
#ifndef FIPS_MODULE
OSSL_FUNC_provider_register_child_cb_fn ossl_provider_register_child_cb;
OSSL_FUNC_provider_deregister_child_cb_fn ossl_provider_deregister_child_cb;
static OSSL_FUNC_provider_name_fn core_provider_get0_name;
static OSSL_FUNC_provider_get0_provider_ctx_fn core_provider_get0_provider_ctx;
static OSSL_FUNC_provider_get0_dispatch_fn core_provider_get0_dispatch;
static OSSL_FUNC_provider_up_ref_fn core_provider_up_ref_intern;
static OSSL_FUNC_provider_free_fn core_provider_free_intern;
static OSSL_FUNC_core_obj_add_sigid_fn core_obj_add_sigid;
static OSSL_FUNC_core_obj_create_fn core_obj_create;
#endif
static const OSSL_PARAM *core_gettable_params(const OSSL_CORE_HANDLE *handle)
{
return param_types;
}
static int core_get_params(const OSSL_CORE_HANDLE *handle, OSSL_PARAM params[])
{
int i;
OSSL_PARAM *p;
/*
* We created this object originally and we know it is actually an
* OSSL_PROVIDER *, so the cast is safe
*/
OSSL_PROVIDER *prov = (OSSL_PROVIDER *)handle;
if ((p = OSSL_PARAM_locate(params, OSSL_PROV_PARAM_CORE_VERSION)) != NULL)
OSSL_PARAM_set_utf8_ptr(p, OPENSSL_VERSION_STR);
if ((p = OSSL_PARAM_locate(params, OSSL_PROV_PARAM_CORE_PROV_NAME)) != NULL)
OSSL_PARAM_set_utf8_ptr(p, prov->name);
#ifndef FIPS_MODULE
if ((p = OSSL_PARAM_locate(params,
OSSL_PROV_PARAM_CORE_MODULE_FILENAME)) != NULL)
OSSL_PARAM_set_utf8_ptr(p, ossl_provider_module_path(prov));
#endif
if (prov->parameters == NULL)
return 1;
for (i = 0; i < sk_INFOPAIR_num(prov->parameters); i++) {
INFOPAIR *pair = sk_INFOPAIR_value(prov->parameters, i);
if ((p = OSSL_PARAM_locate(params, pair->name)) != NULL)
OSSL_PARAM_set_utf8_ptr(p, pair->value);
}
return 1;
}
static OPENSSL_CORE_CTX *core_get_libctx(const OSSL_CORE_HANDLE *handle)
{
/*
* We created this object originally and we know it is actually an
* OSSL_PROVIDER *, so the cast is safe
*/
OSSL_PROVIDER *prov = (OSSL_PROVIDER *)handle;
/*
* Using ossl_provider_libctx would be wrong as that returns
* NULL for |prov| == NULL and NULL libctx has a special meaning
* that does not apply here. Here |prov| == NULL can happen only in
* case of a coding error.
*/
assert(prov != NULL);
return (OPENSSL_CORE_CTX *)prov->libctx;
}
static int core_thread_start(const OSSL_CORE_HANDLE *handle,
OSSL_thread_stop_handler_fn handfn,
void *arg)
{
/*
* We created this object originally and we know it is actually an
* OSSL_PROVIDER *, so the cast is safe
*/
OSSL_PROVIDER *prov = (OSSL_PROVIDER *)handle;
return ossl_init_thread_start(prov, arg, handfn);
}
/*
* The FIPS module inner provider doesn't implement these. They aren't
* needed there, since the FIPS module upcalls are always the outer provider
* ones.
*/
#ifndef FIPS_MODULE
/*
* These error functions should use |handle| to select the proper
* library context to report in the correct error stack if error
* stacks become tied to the library context.
* We cannot currently do that since there's no support for it in the
* ERR subsystem.
*/
static void core_new_error(const OSSL_CORE_HANDLE *handle)
{
ERR_new();
}
static void core_set_error_debug(const OSSL_CORE_HANDLE *handle,
const char *file, int line, const char *func)
{
ERR_set_debug(file, line, func);
}
static void core_vset_error(const OSSL_CORE_HANDLE *handle,
uint32_t reason, const char *fmt, va_list args)
{
/*
* We created this object originally and we know it is actually an
* OSSL_PROVIDER *, so the cast is safe
*/
OSSL_PROVIDER *prov = (OSSL_PROVIDER *)handle;
/*
* If the uppermost 8 bits are non-zero, it's an OpenSSL library
* error and will be treated as such. Otherwise, it's a new style
* provider error and will be treated as such.
*/
if (ERR_GET_LIB(reason) != 0) {
ERR_vset_error(ERR_GET_LIB(reason), ERR_GET_REASON(reason), fmt, args);
} else {
ERR_vset_error(prov->error_lib, (int)reason, fmt, args);
}
}
static int core_set_error_mark(const OSSL_CORE_HANDLE *handle)
{
return ERR_set_mark();
}
static int core_clear_last_error_mark(const OSSL_CORE_HANDLE *handle)
{
return ERR_clear_last_mark();
}
static int core_pop_error_to_mark(const OSSL_CORE_HANDLE *handle)
{
return ERR_pop_to_mark();
}
static void core_self_test_get_callback(OPENSSL_CORE_CTX *libctx,
OSSL_CALLBACK **cb, void **cbarg)
{
OSSL_SELF_TEST_get_callback((OSSL_LIB_CTX *)libctx, cb, cbarg);
}
static const char *core_provider_get0_name(const OSSL_CORE_HANDLE *prov)
{
return OSSL_PROVIDER_get0_name((const OSSL_PROVIDER *)prov);
}
static void *core_provider_get0_provider_ctx(const OSSL_CORE_HANDLE *prov)
{
return OSSL_PROVIDER_get0_provider_ctx((const OSSL_PROVIDER *)prov);
}
static const OSSL_DISPATCH *
core_provider_get0_dispatch(const OSSL_CORE_HANDLE *prov)
{
return OSSL_PROVIDER_get0_dispatch((const OSSL_PROVIDER *)prov);
}
static int core_provider_up_ref_intern(const OSSL_CORE_HANDLE *prov,
int activate)
{
return provider_up_ref_intern((OSSL_PROVIDER *)prov, activate);
}
static int core_provider_free_intern(const OSSL_CORE_HANDLE *prov,
int deactivate)
{
return provider_free_intern((OSSL_PROVIDER *)prov, deactivate);
}
static int core_obj_add_sigid(const OSSL_CORE_HANDLE *prov,
const char *sign_name, const char *digest_name,
const char *pkey_name)
{
int sign_nid = OBJ_txt2nid(sign_name);
int digest_nid = NID_undef;
int pkey_nid = OBJ_txt2nid(pkey_name);
if (digest_name != NULL && digest_name[0] != '\0'
&& (digest_nid = OBJ_txt2nid(digest_name)) == NID_undef)
return 0;
if (sign_nid == NID_undef)
return 0;
/*
* Check if it already exists. This is a success if so (even if we don't
* have nids for the digest/pkey)
*/
if (OBJ_find_sigid_algs(sign_nid, NULL, NULL))
return 1;
if (pkey_nid == NID_undef)
return 0;
return OBJ_add_sigid(sign_nid, digest_nid, pkey_nid);
}
static int core_obj_create(const OSSL_CORE_HANDLE *prov, const char *oid,
const char *sn, const char *ln)
{
/* Check if it already exists and create it if not */
return OBJ_txt2nid(oid) != NID_undef
|| OBJ_create(oid, sn, ln) != NID_undef;
}
#endif /* FIPS_MODULE */
/*
* Functions provided by the core.
*/
static const OSSL_DISPATCH core_dispatch_[] = {
{ OSSL_FUNC_CORE_GETTABLE_PARAMS, (void (*)(void))core_gettable_params },
{ OSSL_FUNC_CORE_GET_PARAMS, (void (*)(void))core_get_params },
{ OSSL_FUNC_CORE_GET_LIBCTX, (void (*)(void))core_get_libctx },
{ OSSL_FUNC_CORE_THREAD_START, (void (*)(void))core_thread_start },
#ifndef FIPS_MODULE
{ OSSL_FUNC_CORE_NEW_ERROR, (void (*)(void))core_new_error },
{ OSSL_FUNC_CORE_SET_ERROR_DEBUG, (void (*)(void))core_set_error_debug },
{ OSSL_FUNC_CORE_VSET_ERROR, (void (*)(void))core_vset_error },
{ OSSL_FUNC_CORE_SET_ERROR_MARK, (void (*)(void))core_set_error_mark },
{ OSSL_FUNC_CORE_CLEAR_LAST_ERROR_MARK,
(void (*)(void))core_clear_last_error_mark },
{ OSSL_FUNC_CORE_POP_ERROR_TO_MARK, (void (*)(void))core_pop_error_to_mark },
{ OSSL_FUNC_BIO_NEW_FILE, (void (*)(void))ossl_core_bio_new_file },
{ OSSL_FUNC_BIO_NEW_MEMBUF, (void (*)(void))ossl_core_bio_new_mem_buf },
{ OSSL_FUNC_BIO_READ_EX, (void (*)(void))ossl_core_bio_read_ex },
{ OSSL_FUNC_BIO_WRITE_EX, (void (*)(void))ossl_core_bio_write_ex },
{ OSSL_FUNC_BIO_GETS, (void (*)(void))ossl_core_bio_gets },
{ OSSL_FUNC_BIO_PUTS, (void (*)(void))ossl_core_bio_puts },
{ OSSL_FUNC_BIO_CTRL, (void (*)(void))ossl_core_bio_ctrl },
{ OSSL_FUNC_BIO_UP_REF, (void (*)(void))ossl_core_bio_up_ref },
{ OSSL_FUNC_BIO_FREE, (void (*)(void))ossl_core_bio_free },
{ OSSL_FUNC_BIO_VPRINTF, (void (*)(void))ossl_core_bio_vprintf },
{ OSSL_FUNC_BIO_VSNPRINTF, (void (*)(void))BIO_vsnprintf },
{ OSSL_FUNC_SELF_TEST_CB, (void (*)(void))core_self_test_get_callback },
{ OSSL_FUNC_GET_ENTROPY, (void (*)(void))ossl_rand_get_entropy },
{ OSSL_FUNC_CLEANUP_ENTROPY, (void (*)(void))ossl_rand_cleanup_entropy },
{ OSSL_FUNC_GET_NONCE, (void (*)(void))ossl_rand_get_nonce },
{ OSSL_FUNC_CLEANUP_NONCE, (void (*)(void))ossl_rand_cleanup_nonce },
#endif
{ OSSL_FUNC_CRYPTO_MALLOC, (void (*)(void))CRYPTO_malloc },
{ OSSL_FUNC_CRYPTO_ZALLOC, (void (*)(void))CRYPTO_zalloc },
{ OSSL_FUNC_CRYPTO_FREE, (void (*)(void))CRYPTO_free },
{ OSSL_FUNC_CRYPTO_CLEAR_FREE, (void (*)(void))CRYPTO_clear_free },
{ OSSL_FUNC_CRYPTO_REALLOC, (void (*)(void))CRYPTO_realloc },
{ OSSL_FUNC_CRYPTO_CLEAR_REALLOC, (void (*)(void))CRYPTO_clear_realloc },
{ OSSL_FUNC_CRYPTO_SECURE_MALLOC, (void (*)(void))CRYPTO_secure_malloc },
{ OSSL_FUNC_CRYPTO_SECURE_ZALLOC, (void (*)(void))CRYPTO_secure_zalloc },
{ OSSL_FUNC_CRYPTO_SECURE_FREE, (void (*)(void))CRYPTO_secure_free },
{ OSSL_FUNC_CRYPTO_SECURE_CLEAR_FREE,
(void (*)(void))CRYPTO_secure_clear_free },
{ OSSL_FUNC_CRYPTO_SECURE_ALLOCATED,
(void (*)(void))CRYPTO_secure_allocated },
{ OSSL_FUNC_OPENSSL_CLEANSE, (void (*)(void))OPENSSL_cleanse },
#ifndef FIPS_MODULE
{ OSSL_FUNC_PROVIDER_REGISTER_CHILD_CB,
(void (*)(void))ossl_provider_register_child_cb },
{ OSSL_FUNC_PROVIDER_DEREGISTER_CHILD_CB,
(void (*)(void))ossl_provider_deregister_child_cb },
{ OSSL_FUNC_PROVIDER_NAME,
(void (*)(void))core_provider_get0_name },
{ OSSL_FUNC_PROVIDER_GET0_PROVIDER_CTX,
(void (*)(void))core_provider_get0_provider_ctx },
{ OSSL_FUNC_PROVIDER_GET0_DISPATCH,
(void (*)(void))core_provider_get0_dispatch },
{ OSSL_FUNC_PROVIDER_UP_REF,
(void (*)(void))core_provider_up_ref_intern },
{ OSSL_FUNC_PROVIDER_FREE,
(void (*)(void))core_provider_free_intern },
{ OSSL_FUNC_CORE_OBJ_ADD_SIGID, (void (*)(void))core_obj_add_sigid },
{ OSSL_FUNC_CORE_OBJ_CREATE, (void (*)(void))core_obj_create },
#endif
{ 0, NULL }
};
static const OSSL_DISPATCH *core_dispatch = core_dispatch_;
diff --git a/crypto/openssl/crypto/sha/build.info b/crypto/openssl/crypto/sha/build.info
index 556a658d8b55..deb7b1530d46 100644
--- a/crypto/openssl/crypto/sha/build.info
+++ b/crypto/openssl/crypto/sha/build.info
@@ -1,177 +1,177 @@
LIBS=../../libcrypto
$SHA1ASM=
IF[{- !$disabled{asm} -}]
$SHA1ASM_x86=sha1-586.S sha256-586.S sha512-586.S
$SHA1DEF_x86=SHA1_ASM SHA256_ASM SHA512_ASM
$SHA1ASM_x86_64=\
sha1-x86_64.s sha256-x86_64.s sha512-x86_64.s sha1-mb-x86_64.s \
sha256-mb-x86_64.s
$SHA1DEF_x86_64=SHA1_ASM SHA256_ASM SHA512_ASM
$SHA1ASM_ia64=sha1-ia64.s sha256-ia64.s sha512-ia64.s
$SHA1DEF_ia64=SHA1_ASM SHA256_ASM SHA512_ASM
$SHA1ASM_sparcv9=sha1-sparcv9.S sha256-sparcv9.S sha512-sparcv9.S
$SHA1DEF_sparcv9=SHA1_ASM SHA256_ASM SHA512_ASM
$SHA1ASM_alpha=sha1-alpha.S
$SHA1DEF_alpha=SHA1_ASM
$SHA1ASM_mips32=sha1-mips.S sha256-mips.S
$SHA1DEF_mips32=SHA1_ASM SHA256_ASM
$SHA1ASM_mips64=$SHA1ASM_mips32 sha512-mips.S
$SHA1DEF_mips64=$SHA1DEF_mips32 SHA512_ASM
$SHA1ASM_s390x=sha1-s390x.S sha256-s390x.S sha512-s390x.S
$SHA1DEF_s390x=SHA1_ASM SHA256_ASM SHA512_ASM
$SHA1ASM_armv4=sha1-armv4-large.S sha256-armv4.S sha512-armv4.S
$SHA1DEF_armv4=SHA1_ASM SHA256_ASM SHA512_ASM
$SHA1ASM_aarch64=sha1-armv8.S sha256-armv8.S sha512-armv8.S
$SHA1DEF_aarch64=SHA1_ASM SHA256_ASM SHA512_ASM
$SHA1ASM_parisc11=sha1-parisc.s sha256-parisc.s sha512-parisc.s
$SHA1DEF_parisc11=SHA1_ASM SHA256_ASM SHA512_ASM
$SHA1ASM_parisc20_64=$SHA1ASM_parisc11
$SHA1DEF_parisc20_64=$SHA1DEF_parisc11
$SHA1ASM_ppc32=\
sha_ppc.c sha1-ppc.s sha256-ppc.s sha512-ppc.s sha256p8-ppc.s \
sha512p8-ppc.s
$SHA1DEF_ppc32=SHA1_ASM SHA256_ASM SHA512_ASM
$SHA1ASM_ppc64=$SHA1ASM_ppc32
$SHA1DEF_ppc64=$SHA1DEF_ppc32
$SHA1ASM_c64xplus=sha1-c64xplus.s sha256-c64xplus.s sha512-c64xplus.s
$SHA1DEF_c64xplus=SHA1_ASM SHA256_ASM SHA512_ASM
# Now that we have defined all the arch specific variables, use the
# appropriate one, and define the appropriate macros
IF[$SHA1ASM_{- $target{asm_arch} -}]
$SHA1ASM=$SHA1ASM_{- $target{asm_arch} -}
$SHA1DEF=$SHA1DEF_{- $target{asm_arch} -}
ENDIF
ENDIF
$KECCAK1600ASM=keccak1600.c
IF[{- !$disabled{asm} -}]
$KECCAK1600ASM_x86=
$KECCAK1600ASM_x86_64=keccak1600-x86_64.s
$KECCAK1600ASM_s390x=keccak1600-s390x.S
$KECCAK1600ASM_armv4=keccak1600-armv4.S
$KECCAK1600ASM_aarch64=keccak1600-armv8.S
$KECCAK1600ASM_ppc64=keccak1600-ppc64.s
# Now that we have defined all the arch specific variables, use the
# appropriate one, and define the appropriate macros
IF[$KECCAK1600ASM_{- $target{asm_arch} -}]
$KECCAK1600ASM=$KECCAK1600ASM_{- $target{asm_arch} -}
$KECCAK1600DEF=KECCAK1600_ASM
ENDIF
ENDIF
$COMMON=sha1dgst.c sha256.c sha512.c sha3.c $SHA1ASM $KECCAK1600ASM
SOURCE[../../libcrypto]=$COMMON sha1_one.c
SOURCE[../../providers/libfips.a]= $COMMON
# Implementations are now spread across several libraries, so the defines
# need to be applied to all affected libraries and modules.
DEFINE[../../libcrypto]=$SHA1DEF $KECCAK1600DEF
DEFINE[../../providers/libfips.a]=$SHA1DEF $KECCAK1600DEF
DEFINE[../../providers/libdefault.a]=$SHA1DEF $KECCAK1600DEF
# We only need to include the SHA1DEF and KECCAK1600DEF stuff in the
# legacy provider when it's a separate module and it's dynamically
# linked with libcrypto. Otherwise, it already gets everything that
# the static libcrypto.a has, and doesn't need it added again.
IF[{- !$disabled{module} && !$disabled{shared} -}]
- DEFINE[../providers/liblegacy.a]=$SHA1DEF $KECCAK1600DEF
+ DEFINE[../../providers/liblegacy.a]=$SHA1DEF $KECCAK1600DEF
ENDIF
GENERATE[sha1-586.S]=asm/sha1-586.pl
DEPEND[sha1-586.S]=../perlasm/x86asm.pl
GENERATE[sha256-586.S]=asm/sha256-586.pl
DEPEND[sha256-586.S]=../perlasm/x86asm.pl
GENERATE[sha512-586.S]=asm/sha512-586.pl
DEPEND[sha512-586.S]=../perlasm/x86asm.pl
GENERATE[sha1-ia64.s]=asm/sha1-ia64.pl
GENERATE[sha256-ia64.s]=asm/sha512-ia64.pl
GENERATE[sha512-ia64.s]=asm/sha512-ia64.pl
GENERATE[sha1-alpha.S]=asm/sha1-alpha.pl
GENERATE[sha1-x86_64.s]=asm/sha1-x86_64.pl
GENERATE[sha1-mb-x86_64.s]=asm/sha1-mb-x86_64.pl
GENERATE[sha256-x86_64.s]=asm/sha512-x86_64.pl
GENERATE[sha256-mb-x86_64.s]=asm/sha256-mb-x86_64.pl
GENERATE[sha512-x86_64.s]=asm/sha512-x86_64.pl
GENERATE[keccak1600-x86_64.s]=asm/keccak1600-x86_64.pl
GENERATE[sha1-sparcv9a.S]=asm/sha1-sparcv9a.pl
GENERATE[sha1-sparcv9.S]=asm/sha1-sparcv9.pl
INCLUDE[sha1-sparcv9.o]=..
GENERATE[sha256-sparcv9.S]=asm/sha512-sparcv9.pl
INCLUDE[sha256-sparcv9.o]=..
GENERATE[sha512-sparcv9.S]=asm/sha512-sparcv9.pl
INCLUDE[sha512-sparcv9.o]=..
GENERATE[sha1-ppc.s]=asm/sha1-ppc.pl
GENERATE[sha256-ppc.s]=asm/sha512-ppc.pl
GENERATE[sha512-ppc.s]=asm/sha512-ppc.pl
GENERATE[sha256p8-ppc.s]=asm/sha512p8-ppc.pl
GENERATE[sha512p8-ppc.s]=asm/sha512p8-ppc.pl
GENERATE[keccak1600-ppc64.s]=asm/keccak1600-ppc64.pl
GENERATE[sha1-parisc.s]=asm/sha1-parisc.pl
GENERATE[sha256-parisc.s]=asm/sha512-parisc.pl
GENERATE[sha512-parisc.s]=asm/sha512-parisc.pl
GENERATE[sha1-mips.S]=asm/sha1-mips.pl
INCLUDE[sha1-mips.o]=..
GENERATE[sha256-mips.S]=asm/sha512-mips.pl
INCLUDE[sha256-mips.o]=..
GENERATE[sha512-mips.S]=asm/sha512-mips.pl
INCLUDE[sha512-mips.o]=..
GENERATE[sha1-armv4-large.S]=asm/sha1-armv4-large.pl
INCLUDE[sha1-armv4-large.o]=..
GENERATE[sha256-armv4.S]=asm/sha256-armv4.pl
INCLUDE[sha256-armv4.o]=..
GENERATE[sha512-armv4.S]=asm/sha512-armv4.pl
INCLUDE[sha512-armv4.o]=..
GENERATE[keccak1600-armv4.S]=asm/keccak1600-armv4.pl
INCLUDE[keccak1600-armv4.o]=..
GENERATE[sha1-armv8.S]=asm/sha1-armv8.pl
INCLUDE[sha1-armv8.o]=..
GENERATE[sha256-armv8.S]=asm/sha512-armv8.pl
INCLUDE[sha256-armv8.o]=..
GENERATE[sha512-armv8.S]=asm/sha512-armv8.pl
INCLUDE[sha512-armv8.o]=..
GENERATE[keccak1600-armv8.S]=asm/keccak1600-armv8.pl
INCLUDE[keccak1600-armv8.o]=..
GENERATE[sha1-s390x.S]=asm/sha1-s390x.pl
INCLUDE[sha1-s390x.o]=..
GENERATE[sha256-s390x.S]=asm/sha512-s390x.pl
INCLUDE[sha256-s390x.o]=..
GENERATE[sha512-s390x.S]=asm/sha512-s390x.pl
INCLUDE[sha512-s390x.o]=..
GENERATE[keccak1600-s390x.S]=asm/keccak1600-s390x.pl
GENERATE[sha1-c64xplus.S]=asm/sha1-c64xplus.pl
GENERATE[sha256-c64xplus.S]=asm/sha256-c64xplus.pl
GENERATE[sha512-c64xplus.S]=asm/sha512-c64xplus.pl
GENERATE[keccak1600-c64x.S]=asm/keccak1600-c64x.pl
# These are not yet used
GENERATE[keccak1600-avx2.S]=asm/keccak1600-avx2.pl
GENERATE[keccak1600-avx512.S]=asm/keccak1600-avx512.pl
GENERATE[keccak1600-avx512vl.S]=asm/keccak1600-avx512vl.pl
GENERATE[keccak1600-mmx.S]=asm/keccak1600-mmx.pl
GENERATE[keccak1600p8-ppc.S]=asm/keccak1600p8-ppc.pl
GENERATE[sha1-thumb.S]=asm/sha1-thumb.pl
diff --git a/crypto/openssl/crypto/sm2/sm2_crypt.c b/crypto/openssl/crypto/sm2/sm2_crypt.c
index 5318c6199f68..ff8171e39280 100644
--- a/crypto/openssl/crypto/sm2/sm2_crypt.c
+++ b/crypto/openssl/crypto/sm2/sm2_crypt.c
@@ -1,406 +1,429 @@
/*
- * Copyright 2017-2021 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2017-2024 The OpenSSL Project Authors. All Rights Reserved.
* Copyright 2017 Ribose Inc. All Rights Reserved.
* Ported from Ribose contributions from Botan.
*
* 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
*/
/*
* ECDSA low level APIs are deprecated for public use, but still ok for
* internal use.
*/
#include "internal/deprecated.h"
#include "crypto/sm2.h"
#include "crypto/sm2err.h"
#include "crypto/ec.h" /* ossl_ecdh_kdf_X9_63() */
#include <openssl/err.h>
#include <openssl/evp.h>
#include <openssl/bn.h>
#include <openssl/asn1.h>
#include <openssl/asn1t.h>
#include <string.h>
typedef struct SM2_Ciphertext_st SM2_Ciphertext;
DECLARE_ASN1_FUNCTIONS(SM2_Ciphertext)
struct SM2_Ciphertext_st {
BIGNUM *C1x;
BIGNUM *C1y;
ASN1_OCTET_STRING *C3;
ASN1_OCTET_STRING *C2;
};
ASN1_SEQUENCE(SM2_Ciphertext) = {
ASN1_SIMPLE(SM2_Ciphertext, C1x, BIGNUM),
ASN1_SIMPLE(SM2_Ciphertext, C1y, BIGNUM),
ASN1_SIMPLE(SM2_Ciphertext, C3, ASN1_OCTET_STRING),
ASN1_SIMPLE(SM2_Ciphertext, C2, ASN1_OCTET_STRING),
} ASN1_SEQUENCE_END(SM2_Ciphertext)
IMPLEMENT_ASN1_FUNCTIONS(SM2_Ciphertext)
static size_t ec_field_size(const EC_GROUP *group)
{
/* Is there some simpler way to do this? */
BIGNUM *p = BN_new();
BIGNUM *a = BN_new();
BIGNUM *b = BN_new();
size_t field_size = 0;
if (p == NULL || a == NULL || b == NULL)
goto done;
if (!EC_GROUP_get_curve(group, p, a, b, NULL))
goto done;
field_size = (BN_num_bits(p) + 7) / 8;
done:
BN_free(p);
BN_free(a);
BN_free(b);
return field_size;
}
+static int is_all_zeros(const unsigned char *msg, size_t msglen)
+{
+ unsigned char re = 0;
+ size_t i;
+
+ for (i = 0; i < msglen; i++) {
+ re |= msg[i];
+ }
+
+ return re == 0 ? 1 : 0;
+}
+
int ossl_sm2_plaintext_size(const unsigned char *ct, size_t ct_size,
size_t *pt_size)
{
struct SM2_Ciphertext_st *sm2_ctext = NULL;
sm2_ctext = d2i_SM2_Ciphertext(NULL, &ct, ct_size);
if (sm2_ctext == NULL) {
ERR_raise(ERR_LIB_SM2, SM2_R_INVALID_ENCODING);
return 0;
}
*pt_size = sm2_ctext->C2->length;
SM2_Ciphertext_free(sm2_ctext);
return 1;
}
int ossl_sm2_ciphertext_size(const EC_KEY *key, const EVP_MD *digest,
size_t msg_len, size_t *ct_size)
{
const size_t field_size = ec_field_size(EC_KEY_get0_group(key));
const int md_size = EVP_MD_get_size(digest);
size_t sz;
if (field_size == 0 || md_size < 0)
return 0;
/* Integer and string are simple type; set constructed = 0, means primitive and definite length encoding. */
sz = 2 * ASN1_object_size(0, field_size + 1, V_ASN1_INTEGER)
+ ASN1_object_size(0, md_size, V_ASN1_OCTET_STRING)
+ ASN1_object_size(0, msg_len, V_ASN1_OCTET_STRING);
/* Sequence is structured type; set constructed = 1, means constructed and definite length encoding. */
*ct_size = ASN1_object_size(1, sz, V_ASN1_SEQUENCE);
return 1;
}
int ossl_sm2_encrypt(const EC_KEY *key,
const EVP_MD *digest,
const uint8_t *msg, size_t msg_len,
uint8_t *ciphertext_buf, size_t *ciphertext_len)
{
int rc = 0, ciphertext_leni;
size_t i;
BN_CTX *ctx = NULL;
BIGNUM *k = NULL;
BIGNUM *x1 = NULL;
BIGNUM *y1 = NULL;
BIGNUM *x2 = NULL;
BIGNUM *y2 = NULL;
EVP_MD_CTX *hash = EVP_MD_CTX_new();
struct SM2_Ciphertext_st ctext_struct;
const EC_GROUP *group = EC_KEY_get0_group(key);
const BIGNUM *order = EC_GROUP_get0_order(group);
const EC_POINT *P = EC_KEY_get0_public_key(key);
EC_POINT *kG = NULL;
EC_POINT *kP = NULL;
uint8_t *msg_mask = NULL;
uint8_t *x2y2 = NULL;
uint8_t *C3 = NULL;
size_t field_size;
const int C3_size = EVP_MD_get_size(digest);
EVP_MD *fetched_digest = NULL;
OSSL_LIB_CTX *libctx = ossl_ec_key_get_libctx(key);
const char *propq = ossl_ec_key_get0_propq(key);
/* NULL these before any "goto done" */
ctext_struct.C2 = NULL;
ctext_struct.C3 = NULL;
if (hash == NULL || C3_size <= 0) {
ERR_raise(ERR_LIB_SM2, ERR_R_INTERNAL_ERROR);
goto done;
}
field_size = ec_field_size(group);
if (field_size == 0) {
ERR_raise(ERR_LIB_SM2, ERR_R_INTERNAL_ERROR);
goto done;
}
kG = EC_POINT_new(group);
kP = EC_POINT_new(group);
ctx = BN_CTX_new_ex(libctx);
if (kG == NULL || kP == NULL || ctx == NULL) {
ERR_raise(ERR_LIB_SM2, ERR_R_MALLOC_FAILURE);
goto done;
}
BN_CTX_start(ctx);
k = BN_CTX_get(ctx);
x1 = BN_CTX_get(ctx);
x2 = BN_CTX_get(ctx);
y1 = BN_CTX_get(ctx);
y2 = BN_CTX_get(ctx);
if (y2 == NULL) {
ERR_raise(ERR_LIB_SM2, ERR_R_BN_LIB);
goto done;
}
x2y2 = OPENSSL_zalloc(2 * field_size);
C3 = OPENSSL_zalloc(C3_size);
if (x2y2 == NULL || C3 == NULL) {
ERR_raise(ERR_LIB_SM2, ERR_R_MALLOC_FAILURE);
goto done;
}
memset(ciphertext_buf, 0, *ciphertext_len);
+ msg_mask = OPENSSL_zalloc(msg_len);
+ if (msg_mask == NULL) {
+ ERR_raise(ERR_LIB_SM2, ERR_R_MALLOC_FAILURE);
+ goto done;
+ }
+
+again:
if (!BN_priv_rand_range_ex(k, order, 0, ctx)) {
ERR_raise(ERR_LIB_SM2, ERR_R_INTERNAL_ERROR);
goto done;
}
if (!EC_POINT_mul(group, kG, k, NULL, NULL, ctx)
|| !EC_POINT_get_affine_coordinates(group, kG, x1, y1, ctx)
|| !EC_POINT_mul(group, kP, NULL, P, k, ctx)
|| !EC_POINT_get_affine_coordinates(group, kP, x2, y2, ctx)) {
ERR_raise(ERR_LIB_SM2, ERR_R_EC_LIB);
goto done;
}
if (BN_bn2binpad(x2, x2y2, field_size) < 0
|| BN_bn2binpad(y2, x2y2 + field_size, field_size) < 0) {
ERR_raise(ERR_LIB_SM2, ERR_R_INTERNAL_ERROR);
goto done;
}
- msg_mask = OPENSSL_zalloc(msg_len);
- if (msg_mask == NULL) {
- ERR_raise(ERR_LIB_SM2, ERR_R_MALLOC_FAILURE);
- goto done;
- }
-
/* X9.63 with no salt happens to match the KDF used in SM2 */
if (!ossl_ecdh_kdf_X9_63(msg_mask, msg_len, x2y2, 2 * field_size, NULL, 0,
digest, libctx, propq)) {
ERR_raise(ERR_LIB_SM2, ERR_R_EVP_LIB);
goto done;
}
+ if (is_all_zeros(msg_mask, msg_len)) {
+ memset(x2y2, 0, 2 * field_size);
+ goto again;
+ }
+
for (i = 0; i != msg_len; ++i)
msg_mask[i] ^= msg[i];
fetched_digest = EVP_MD_fetch(libctx, EVP_MD_get0_name(digest), propq);
if (fetched_digest == NULL) {
ERR_raise(ERR_LIB_SM2, ERR_R_INTERNAL_ERROR);
goto done;
}
if (EVP_DigestInit(hash, fetched_digest) == 0
|| EVP_DigestUpdate(hash, x2y2, field_size) == 0
|| EVP_DigestUpdate(hash, msg, msg_len) == 0
|| EVP_DigestUpdate(hash, x2y2 + field_size, field_size) == 0
|| EVP_DigestFinal(hash, C3, NULL) == 0) {
ERR_raise(ERR_LIB_SM2, ERR_R_EVP_LIB);
goto done;
}
ctext_struct.C1x = x1;
ctext_struct.C1y = y1;
ctext_struct.C3 = ASN1_OCTET_STRING_new();
ctext_struct.C2 = ASN1_OCTET_STRING_new();
if (ctext_struct.C3 == NULL || ctext_struct.C2 == NULL) {
ERR_raise(ERR_LIB_SM2, ERR_R_MALLOC_FAILURE);
goto done;
}
if (!ASN1_OCTET_STRING_set(ctext_struct.C3, C3, C3_size)
|| !ASN1_OCTET_STRING_set(ctext_struct.C2, msg_mask, msg_len)) {
ERR_raise(ERR_LIB_SM2, ERR_R_INTERNAL_ERROR);
goto done;
}
ciphertext_leni = i2d_SM2_Ciphertext(&ctext_struct, &ciphertext_buf);
/* Ensure cast to size_t is safe */
if (ciphertext_leni < 0) {
ERR_raise(ERR_LIB_SM2, ERR_R_INTERNAL_ERROR);
goto done;
}
*ciphertext_len = (size_t)ciphertext_leni;
rc = 1;
done:
EVP_MD_free(fetched_digest);
ASN1_OCTET_STRING_free(ctext_struct.C2);
ASN1_OCTET_STRING_free(ctext_struct.C3);
OPENSSL_free(msg_mask);
OPENSSL_free(x2y2);
OPENSSL_free(C3);
EVP_MD_CTX_free(hash);
BN_CTX_free(ctx);
EC_POINT_free(kG);
EC_POINT_free(kP);
return rc;
}
int ossl_sm2_decrypt(const EC_KEY *key,
const EVP_MD *digest,
const uint8_t *ciphertext, size_t ciphertext_len,
uint8_t *ptext_buf, size_t *ptext_len)
{
int rc = 0;
int i;
BN_CTX *ctx = NULL;
const EC_GROUP *group = EC_KEY_get0_group(key);
EC_POINT *C1 = NULL;
struct SM2_Ciphertext_st *sm2_ctext = NULL;
BIGNUM *x2 = NULL;
BIGNUM *y2 = NULL;
uint8_t *x2y2 = NULL;
uint8_t *computed_C3 = NULL;
const size_t field_size = ec_field_size(group);
const int hash_size = EVP_MD_get_size(digest);
uint8_t *msg_mask = NULL;
const uint8_t *C2 = NULL;
const uint8_t *C3 = NULL;
int msg_len = 0;
EVP_MD_CTX *hash = NULL;
OSSL_LIB_CTX *libctx = ossl_ec_key_get_libctx(key);
const char *propq = ossl_ec_key_get0_propq(key);
if (field_size == 0 || hash_size <= 0)
goto done;
memset(ptext_buf, 0xFF, *ptext_len);
sm2_ctext = d2i_SM2_Ciphertext(NULL, &ciphertext, ciphertext_len);
if (sm2_ctext == NULL) {
ERR_raise(ERR_LIB_SM2, SM2_R_ASN1_ERROR);
goto done;
}
if (sm2_ctext->C3->length != hash_size) {
ERR_raise(ERR_LIB_SM2, SM2_R_INVALID_ENCODING);
goto done;
}
C2 = sm2_ctext->C2->data;
C3 = sm2_ctext->C3->data;
msg_len = sm2_ctext->C2->length;
if (*ptext_len < (size_t)msg_len) {
ERR_raise(ERR_LIB_SM2, SM2_R_BUFFER_TOO_SMALL);
goto done;
}
ctx = BN_CTX_new_ex(libctx);
if (ctx == NULL) {
ERR_raise(ERR_LIB_SM2, ERR_R_MALLOC_FAILURE);
goto done;
}
BN_CTX_start(ctx);
x2 = BN_CTX_get(ctx);
y2 = BN_CTX_get(ctx);
if (y2 == NULL) {
ERR_raise(ERR_LIB_SM2, ERR_R_BN_LIB);
goto done;
}
msg_mask = OPENSSL_zalloc(msg_len);
x2y2 = OPENSSL_zalloc(2 * field_size);
computed_C3 = OPENSSL_zalloc(hash_size);
if (msg_mask == NULL || x2y2 == NULL || computed_C3 == NULL) {
ERR_raise(ERR_LIB_SM2, ERR_R_MALLOC_FAILURE);
goto done;
}
C1 = EC_POINT_new(group);
if (C1 == NULL) {
ERR_raise(ERR_LIB_SM2, ERR_R_MALLOC_FAILURE);
goto done;
}
if (!EC_POINT_set_affine_coordinates(group, C1, sm2_ctext->C1x,
sm2_ctext->C1y, ctx)
|| !EC_POINT_mul(group, C1, NULL, C1, EC_KEY_get0_private_key(key),
ctx)
|| !EC_POINT_get_affine_coordinates(group, C1, x2, y2, ctx)) {
ERR_raise(ERR_LIB_SM2, ERR_R_EC_LIB);
goto done;
}
if (BN_bn2binpad(x2, x2y2, field_size) < 0
|| BN_bn2binpad(y2, x2y2 + field_size, field_size) < 0
|| !ossl_ecdh_kdf_X9_63(msg_mask, msg_len, x2y2, 2 * field_size,
NULL, 0, digest, libctx, propq)) {
ERR_raise(ERR_LIB_SM2, ERR_R_INTERNAL_ERROR);
goto done;
}
+ if (is_all_zeros(msg_mask, msg_len)) {
+ ERR_raise(ERR_LIB_SM2, SM2_R_INVALID_ENCODING);
+ goto done;
+ }
+
for (i = 0; i != msg_len; ++i)
ptext_buf[i] = C2[i] ^ msg_mask[i];
hash = EVP_MD_CTX_new();
if (hash == NULL) {
ERR_raise(ERR_LIB_SM2, ERR_R_MALLOC_FAILURE);
goto done;
}
if (!EVP_DigestInit(hash, digest)
|| !EVP_DigestUpdate(hash, x2y2, field_size)
|| !EVP_DigestUpdate(hash, ptext_buf, msg_len)
|| !EVP_DigestUpdate(hash, x2y2 + field_size, field_size)
|| !EVP_DigestFinal(hash, computed_C3, NULL)) {
ERR_raise(ERR_LIB_SM2, ERR_R_EVP_LIB);
goto done;
}
if (CRYPTO_memcmp(computed_C3, C3, hash_size) != 0) {
ERR_raise(ERR_LIB_SM2, SM2_R_INVALID_DIGEST);
goto done;
}
rc = 1;
*ptext_len = msg_len;
done:
if (rc == 0)
memset(ptext_buf, 0, *ptext_len);
OPENSSL_free(msg_mask);
OPENSSL_free(x2y2);
OPENSSL_free(computed_C3);
EC_POINT_free(C1);
BN_CTX_free(ctx);
SM2_Ciphertext_free(sm2_ctext);
EVP_MD_CTX_free(hash);
return rc;
}
diff --git a/crypto/openssl/crypto/sm2/sm2_sign.c b/crypto/openssl/crypto/sm2/sm2_sign.c
index ff5be9b73e9f..71ccfcfc4c3d 100644
--- a/crypto/openssl/crypto/sm2/sm2_sign.c
+++ b/crypto/openssl/crypto/sm2/sm2_sign.c
@@ -1,512 +1,524 @@
/*
- * Copyright 2017-2023 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2017-2024 The OpenSSL Project Authors. All Rights Reserved.
* Copyright 2017 Ribose Inc. All Rights Reserved.
* Ported from Ribose contributions from Botan.
*
* 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/deprecated.h"
#include "crypto/sm2.h"
#include "crypto/sm2err.h"
#include "crypto/ec.h" /* ossl_ec_group_do_inverse_ord() */
#include "internal/numbers.h"
#include <openssl/err.h>
#include <openssl/evp.h>
#include <openssl/err.h>
#include <openssl/bn.h>
#include <string.h>
int ossl_sm2_compute_z_digest(uint8_t *out,
const EVP_MD *digest,
const uint8_t *id,
const size_t id_len,
const EC_KEY *key)
{
int rc = 0;
const EC_GROUP *group = EC_KEY_get0_group(key);
+ const EC_POINT *pubkey = EC_KEY_get0_public_key(key);
BN_CTX *ctx = NULL;
EVP_MD_CTX *hash = NULL;
BIGNUM *p = NULL;
BIGNUM *a = NULL;
BIGNUM *b = NULL;
BIGNUM *xG = NULL;
BIGNUM *yG = NULL;
BIGNUM *xA = NULL;
BIGNUM *yA = NULL;
int p_bytes = 0;
uint8_t *buf = NULL;
uint16_t entl = 0;
uint8_t e_byte = 0;
+ /* SM2 Signatures require a public key, check for it */
+ if (pubkey == NULL) {
+ ERR_raise(ERR_LIB_SM2, ERR_R_PASSED_NULL_PARAMETER);
+ goto done;
+ }
+
hash = EVP_MD_CTX_new();
ctx = BN_CTX_new_ex(ossl_ec_key_get_libctx(key));
if (hash == NULL || ctx == NULL) {
ERR_raise(ERR_LIB_SM2, ERR_R_MALLOC_FAILURE);
goto done;
}
p = BN_CTX_get(ctx);
a = BN_CTX_get(ctx);
b = BN_CTX_get(ctx);
xG = BN_CTX_get(ctx);
yG = BN_CTX_get(ctx);
xA = BN_CTX_get(ctx);
yA = BN_CTX_get(ctx);
if (yA == NULL) {
ERR_raise(ERR_LIB_SM2, ERR_R_MALLOC_FAILURE);
goto done;
}
if (!EVP_DigestInit(hash, digest)) {
ERR_raise(ERR_LIB_SM2, ERR_R_EVP_LIB);
goto done;
}
/* Z = h(ENTL || ID || a || b || xG || yG || xA || yA) */
if (id_len >= (UINT16_MAX / 8)) {
/* too large */
ERR_raise(ERR_LIB_SM2, SM2_R_ID_TOO_LARGE);
goto done;
}
entl = (uint16_t)(8 * id_len);
e_byte = entl >> 8;
if (!EVP_DigestUpdate(hash, &e_byte, 1)) {
ERR_raise(ERR_LIB_SM2, ERR_R_EVP_LIB);
goto done;
}
e_byte = entl & 0xFF;
if (!EVP_DigestUpdate(hash, &e_byte, 1)) {
ERR_raise(ERR_LIB_SM2, ERR_R_EVP_LIB);
goto done;
}
if (id_len > 0 && !EVP_DigestUpdate(hash, id, id_len)) {
ERR_raise(ERR_LIB_SM2, ERR_R_EVP_LIB);
goto done;
}
if (!EC_GROUP_get_curve(group, p, a, b, ctx)) {
ERR_raise(ERR_LIB_SM2, ERR_R_EC_LIB);
goto done;
}
p_bytes = BN_num_bytes(p);
buf = OPENSSL_zalloc(p_bytes);
if (buf == NULL) {
ERR_raise(ERR_LIB_SM2, ERR_R_MALLOC_FAILURE);
goto done;
}
if (BN_bn2binpad(a, buf, p_bytes) < 0
|| !EVP_DigestUpdate(hash, buf, p_bytes)
|| BN_bn2binpad(b, buf, p_bytes) < 0
|| !EVP_DigestUpdate(hash, buf, p_bytes)
|| !EC_POINT_get_affine_coordinates(group,
EC_GROUP_get0_generator(group),
xG, yG, ctx)
|| BN_bn2binpad(xG, buf, p_bytes) < 0
|| !EVP_DigestUpdate(hash, buf, p_bytes)
|| BN_bn2binpad(yG, buf, p_bytes) < 0
|| !EVP_DigestUpdate(hash, buf, p_bytes)
|| !EC_POINT_get_affine_coordinates(group,
- EC_KEY_get0_public_key(key),
+ pubkey,
xA, yA, ctx)
|| BN_bn2binpad(xA, buf, p_bytes) < 0
|| !EVP_DigestUpdate(hash, buf, p_bytes)
|| BN_bn2binpad(yA, buf, p_bytes) < 0
|| !EVP_DigestUpdate(hash, buf, p_bytes)
|| !EVP_DigestFinal(hash, out, NULL)) {
ERR_raise(ERR_LIB_SM2, ERR_R_INTERNAL_ERROR);
goto done;
}
rc = 1;
done:
OPENSSL_free(buf);
BN_CTX_free(ctx);
EVP_MD_CTX_free(hash);
return rc;
}
static BIGNUM *sm2_compute_msg_hash(const EVP_MD *digest,
const EC_KEY *key,
const uint8_t *id,
const size_t id_len,
const uint8_t *msg, size_t msg_len)
{
EVP_MD_CTX *hash = EVP_MD_CTX_new();
const int md_size = EVP_MD_get_size(digest);
uint8_t *z = NULL;
BIGNUM *e = NULL;
EVP_MD *fetched_digest = NULL;
OSSL_LIB_CTX *libctx = ossl_ec_key_get_libctx(key);
const char *propq = ossl_ec_key_get0_propq(key);
if (md_size < 0) {
ERR_raise(ERR_LIB_SM2, SM2_R_INVALID_DIGEST);
goto done;
}
z = OPENSSL_zalloc(md_size);
if (hash == NULL || z == NULL) {
ERR_raise(ERR_LIB_SM2, ERR_R_MALLOC_FAILURE);
goto done;
}
fetched_digest = EVP_MD_fetch(libctx, EVP_MD_get0_name(digest), propq);
if (fetched_digest == NULL) {
ERR_raise(ERR_LIB_SM2, ERR_R_INTERNAL_ERROR);
goto done;
}
if (!ossl_sm2_compute_z_digest(z, fetched_digest, id, id_len, key)) {
/* SM2err already called */
goto done;
}
if (!EVP_DigestInit(hash, fetched_digest)
|| !EVP_DigestUpdate(hash, z, md_size)
|| !EVP_DigestUpdate(hash, msg, msg_len)
/* reuse z buffer to hold H(Z || M) */
|| !EVP_DigestFinal(hash, z, NULL)) {
ERR_raise(ERR_LIB_SM2, ERR_R_EVP_LIB);
goto done;
}
e = BN_bin2bn(z, md_size, NULL);
if (e == NULL)
ERR_raise(ERR_LIB_SM2, ERR_R_INTERNAL_ERROR);
done:
EVP_MD_free(fetched_digest);
OPENSSL_free(z);
EVP_MD_CTX_free(hash);
return e;
}
static ECDSA_SIG *sm2_sig_gen(const EC_KEY *key, const BIGNUM *e)
{
const BIGNUM *dA = EC_KEY_get0_private_key(key);
const EC_GROUP *group = EC_KEY_get0_group(key);
const BIGNUM *order = EC_GROUP_get0_order(group);
ECDSA_SIG *sig = NULL;
EC_POINT *kG = NULL;
BN_CTX *ctx = NULL;
BIGNUM *k = NULL;
BIGNUM *rk = NULL;
BIGNUM *r = NULL;
BIGNUM *s = NULL;
BIGNUM *x1 = NULL;
BIGNUM *tmp = NULL;
OSSL_LIB_CTX *libctx = ossl_ec_key_get_libctx(key);
kG = EC_POINT_new(group);
ctx = BN_CTX_new_ex(libctx);
if (kG == NULL || ctx == NULL) {
ERR_raise(ERR_LIB_SM2, ERR_R_MALLOC_FAILURE);
goto done;
}
BN_CTX_start(ctx);
k = BN_CTX_get(ctx);
rk = BN_CTX_get(ctx);
x1 = BN_CTX_get(ctx);
tmp = BN_CTX_get(ctx);
if (tmp == NULL) {
ERR_raise(ERR_LIB_SM2, ERR_R_MALLOC_FAILURE);
goto done;
}
/*
* These values are returned and so should not be allocated out of the
* context
*/
r = BN_new();
s = BN_new();
if (r == NULL || s == NULL) {
ERR_raise(ERR_LIB_SM2, ERR_R_MALLOC_FAILURE);
goto done;
}
/*
* A3: Generate a random number k in [1,n-1] using random number generators;
* A4: Compute (x1,y1)=[k]G, and convert the type of data x1 to be integer
* as specified in clause 4.2.8 of GM/T 0003.1-2012;
* A5: Compute r=(e+x1) mod n. If r=0 or r+k=n, then go to A3;
* A6: Compute s=(1/(1+dA)*(k-r*dA)) mod n. If s=0, then go to A3;
* A7: Convert the type of data (r,s) to be bit strings according to the details
* in clause 4.2.2 of GM/T 0003.1-2012. Then the signature of message M is (r,s).
*/
for (;;) {
if (!BN_priv_rand_range_ex(k, order, 0, ctx)) {
ERR_raise(ERR_LIB_SM2, ERR_R_INTERNAL_ERROR);
goto done;
}
if (!EC_POINT_mul(group, kG, k, NULL, NULL, ctx)
|| !EC_POINT_get_affine_coordinates(group, kG, x1, NULL,
ctx)
|| !BN_mod_add(r, e, x1, order, ctx)) {
ERR_raise(ERR_LIB_SM2, ERR_R_INTERNAL_ERROR);
goto done;
}
/* try again if r == 0 or r+k == n */
if (BN_is_zero(r))
continue;
if (!BN_add(rk, r, k)) {
ERR_raise(ERR_LIB_SM2, ERR_R_INTERNAL_ERROR);
goto done;
}
if (BN_cmp(rk, order) == 0)
continue;
if (!BN_add(s, dA, BN_value_one())
|| !ossl_ec_group_do_inverse_ord(group, s, s, ctx)
|| !BN_mod_mul(tmp, dA, r, order, ctx)
|| !BN_sub(tmp, k, tmp)
|| !BN_mod_mul(s, s, tmp, order, ctx)) {
ERR_raise(ERR_LIB_SM2, ERR_R_BN_LIB);
goto done;
}
/* try again if s == 0 */
if (BN_is_zero(s))
continue;
sig = ECDSA_SIG_new();
if (sig == NULL) {
ERR_raise(ERR_LIB_SM2, ERR_R_MALLOC_FAILURE);
goto done;
}
/* takes ownership of r and s */
ECDSA_SIG_set0(sig, r, s);
break;
}
done:
if (sig == NULL) {
BN_free(r);
BN_free(s);
}
BN_CTX_free(ctx);
EC_POINT_free(kG);
return sig;
}
static int sm2_sig_verify(const EC_KEY *key, const ECDSA_SIG *sig,
const BIGNUM *e)
{
int ret = 0;
const EC_GROUP *group = EC_KEY_get0_group(key);
const BIGNUM *order = EC_GROUP_get0_order(group);
BN_CTX *ctx = NULL;
EC_POINT *pt = NULL;
BIGNUM *t = NULL;
BIGNUM *x1 = NULL;
const BIGNUM *r = NULL;
const BIGNUM *s = NULL;
OSSL_LIB_CTX *libctx = ossl_ec_key_get_libctx(key);
ctx = BN_CTX_new_ex(libctx);
pt = EC_POINT_new(group);
if (ctx == NULL || pt == NULL) {
ERR_raise(ERR_LIB_SM2, ERR_R_MALLOC_FAILURE);
goto done;
}
BN_CTX_start(ctx);
t = BN_CTX_get(ctx);
x1 = BN_CTX_get(ctx);
if (x1 == NULL) {
ERR_raise(ERR_LIB_SM2, ERR_R_MALLOC_FAILURE);
goto done;
}
/*
* B1: verify whether r' in [1,n-1], verification failed if not
* B2: verify whether s' in [1,n-1], verification failed if not
* B3: set M'~=ZA || M'
* B4: calculate e'=Hv(M'~)
* B5: calculate t = (r' + s') modn, verification failed if t=0
* B6: calculate the point (x1', y1')=[s']G + [t]PA
* B7: calculate R=(e'+x1') modn, verification pass if yes, otherwise failed
*/
ECDSA_SIG_get0(sig, &r, &s);
if (BN_cmp(r, BN_value_one()) < 0
|| BN_cmp(s, BN_value_one()) < 0
|| BN_cmp(order, r) <= 0
|| BN_cmp(order, s) <= 0) {
ERR_raise(ERR_LIB_SM2, SM2_R_BAD_SIGNATURE);
goto done;
}
if (!BN_mod_add(t, r, s, order, ctx)) {
ERR_raise(ERR_LIB_SM2, ERR_R_BN_LIB);
goto done;
}
if (BN_is_zero(t)) {
ERR_raise(ERR_LIB_SM2, SM2_R_BAD_SIGNATURE);
goto done;
}
if (!EC_POINT_mul(group, pt, s, EC_KEY_get0_public_key(key), t, ctx)
|| !EC_POINT_get_affine_coordinates(group, pt, x1, NULL, ctx)) {
ERR_raise(ERR_LIB_SM2, ERR_R_EC_LIB);
goto done;
}
if (!BN_mod_add(t, e, x1, order, ctx)) {
ERR_raise(ERR_LIB_SM2, ERR_R_BN_LIB);
goto done;
}
if (BN_cmp(r, t) == 0)
ret = 1;
done:
EC_POINT_free(pt);
BN_CTX_free(ctx);
return ret;
}
ECDSA_SIG *ossl_sm2_do_sign(const EC_KEY *key,
const EVP_MD *digest,
const uint8_t *id,
const size_t id_len,
const uint8_t *msg, size_t msg_len)
{
BIGNUM *e = NULL;
ECDSA_SIG *sig = NULL;
e = sm2_compute_msg_hash(digest, key, id, id_len, msg, msg_len);
if (e == NULL) {
/* SM2err already called */
goto done;
}
sig = sm2_sig_gen(key, e);
done:
BN_free(e);
return sig;
}
int ossl_sm2_do_verify(const EC_KEY *key,
const EVP_MD *digest,
const ECDSA_SIG *sig,
const uint8_t *id,
const size_t id_len,
const uint8_t *msg, size_t msg_len)
{
BIGNUM *e = NULL;
int ret = 0;
e = sm2_compute_msg_hash(digest, key, id, id_len, msg, msg_len);
if (e == NULL) {
/* SM2err already called */
goto done;
}
ret = sm2_sig_verify(key, sig, e);
done:
BN_free(e);
return ret;
}
int ossl_sm2_internal_sign(const unsigned char *dgst, int dgstlen,
unsigned char *sig, unsigned int *siglen,
EC_KEY *eckey)
{
BIGNUM *e = NULL;
ECDSA_SIG *s = NULL;
int sigleni;
int ret = -1;
+ if (sig == NULL) {
+ ERR_raise(ERR_LIB_SM2, ERR_R_PASSED_NULL_PARAMETER);
+ goto done;
+ }
+
e = BN_bin2bn(dgst, dgstlen, NULL);
if (e == NULL) {
ERR_raise(ERR_LIB_SM2, ERR_R_BN_LIB);
goto done;
}
s = sm2_sig_gen(eckey, e);
if (s == NULL) {
ERR_raise(ERR_LIB_SM2, ERR_R_INTERNAL_ERROR);
goto done;
}
- sigleni = i2d_ECDSA_SIG(s, sig != NULL ? &sig : NULL);
+ sigleni = i2d_ECDSA_SIG(s, &sig);
if (sigleni < 0) {
ERR_raise(ERR_LIB_SM2, ERR_R_INTERNAL_ERROR);
goto done;
}
*siglen = (unsigned int)sigleni;
ret = 1;
done:
ECDSA_SIG_free(s);
BN_free(e);
return ret;
}
int ossl_sm2_internal_verify(const unsigned char *dgst, int dgstlen,
const unsigned char *sig, int sig_len,
EC_KEY *eckey)
{
ECDSA_SIG *s = NULL;
BIGNUM *e = NULL;
const unsigned char *p = sig;
unsigned char *der = NULL;
int derlen = -1;
int ret = -1;
s = ECDSA_SIG_new();
if (s == NULL) {
ERR_raise(ERR_LIB_SM2, ERR_R_MALLOC_FAILURE);
goto done;
}
if (d2i_ECDSA_SIG(&s, &p, sig_len) == NULL) {
ERR_raise(ERR_LIB_SM2, SM2_R_INVALID_ENCODING);
goto done;
}
/* Ensure signature uses DER and doesn't have trailing garbage */
derlen = i2d_ECDSA_SIG(s, &der);
if (derlen != sig_len || memcmp(sig, der, derlen) != 0) {
ERR_raise(ERR_LIB_SM2, SM2_R_INVALID_ENCODING);
goto done;
}
e = BN_bin2bn(dgst, dgstlen, NULL);
if (e == NULL) {
ERR_raise(ERR_LIB_SM2, ERR_R_BN_LIB);
goto done;
}
ret = sm2_sig_verify(eckey, s, e);
done:
OPENSSL_free(der);
BN_free(e);
ECDSA_SIG_free(s);
return ret;
}
diff --git a/crypto/openssl/crypto/x509/v3_addr.c b/crypto/openssl/crypto/x509/v3_addr.c
index 4930f3312422..20f3d2ba70de 100644
--- a/crypto/openssl/crypto/x509/v3_addr.c
+++ b/crypto/openssl/crypto/x509/v3_addr.c
@@ -1,1361 +1,1361 @@
/*
* Copyright 2006-2024 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
*/
/*
* Implementation of RFC 3779 section 2.2.
*/
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <string.h>
#include "internal/cryptlib.h"
#include <openssl/conf.h>
#include <openssl/asn1.h>
#include <openssl/asn1t.h>
#include <openssl/buffer.h>
#include <openssl/x509v3.h>
#include "crypto/x509.h"
#include "ext_dat.h"
#include "x509_local.h"
#ifndef OPENSSL_NO_RFC3779
/*
* OpenSSL ASN.1 template translation of RFC 3779 2.2.3.
*/
ASN1_SEQUENCE(IPAddressRange) = {
ASN1_SIMPLE(IPAddressRange, min, ASN1_BIT_STRING),
ASN1_SIMPLE(IPAddressRange, max, ASN1_BIT_STRING)
} ASN1_SEQUENCE_END(IPAddressRange)
ASN1_CHOICE(IPAddressOrRange) = {
ASN1_SIMPLE(IPAddressOrRange, u.addressPrefix, ASN1_BIT_STRING),
ASN1_SIMPLE(IPAddressOrRange, u.addressRange, IPAddressRange)
} ASN1_CHOICE_END(IPAddressOrRange)
ASN1_CHOICE(IPAddressChoice) = {
ASN1_SIMPLE(IPAddressChoice, u.inherit, ASN1_NULL),
ASN1_SEQUENCE_OF(IPAddressChoice, u.addressesOrRanges, IPAddressOrRange)
} ASN1_CHOICE_END(IPAddressChoice)
ASN1_SEQUENCE(IPAddressFamily) = {
ASN1_SIMPLE(IPAddressFamily, addressFamily, ASN1_OCTET_STRING),
ASN1_SIMPLE(IPAddressFamily, ipAddressChoice, IPAddressChoice)
} ASN1_SEQUENCE_END(IPAddressFamily)
ASN1_ITEM_TEMPLATE(IPAddrBlocks) =
ASN1_EX_TEMPLATE_TYPE(ASN1_TFLG_SEQUENCE_OF, 0,
IPAddrBlocks, IPAddressFamily)
static_ASN1_ITEM_TEMPLATE_END(IPAddrBlocks)
IMPLEMENT_ASN1_FUNCTIONS(IPAddressRange)
IMPLEMENT_ASN1_FUNCTIONS(IPAddressOrRange)
IMPLEMENT_ASN1_FUNCTIONS(IPAddressChoice)
IMPLEMENT_ASN1_FUNCTIONS(IPAddressFamily)
/*
* How much buffer space do we need for a raw address?
*/
#define ADDR_RAW_BUF_LEN 16
/*
* What's the address length associated with this AFI?
*/
static int length_from_afi(const unsigned afi)
{
switch (afi) {
case IANA_AFI_IPV4:
return 4;
case IANA_AFI_IPV6:
return 16;
default:
return 0;
}
}
/*
* Extract the AFI from an IPAddressFamily.
*/
unsigned int X509v3_addr_get_afi(const IPAddressFamily *f)
{
if (f == NULL
|| f->addressFamily == NULL
|| f->addressFamily->data == NULL
|| f->addressFamily->length < 2)
return 0;
return (f->addressFamily->data[0] << 8) | f->addressFamily->data[1];
}
/*
* Expand the bitstring form of an address into a raw byte array.
* At the moment this is coded for simplicity, not speed.
*/
static int addr_expand(unsigned char *addr,
const ASN1_BIT_STRING *bs,
const int length, const unsigned char fill)
{
if (bs->length < 0 || bs->length > length)
return 0;
if (bs->length > 0) {
memcpy(addr, bs->data, bs->length);
if ((bs->flags & 7) != 0) {
unsigned char mask = 0xFF >> (8 - (bs->flags & 7));
if (fill == 0)
addr[bs->length - 1] &= ~mask;
else
addr[bs->length - 1] |= mask;
}
}
memset(addr + bs->length, fill, length - bs->length);
return 1;
}
/*
* Extract the prefix length from a bitstring.
*/
#define addr_prefixlen(bs) ((int) ((bs)->length * 8 - ((bs)->flags & 7)))
/*
* i2r handler for one address bitstring.
*/
static int i2r_address(BIO *out,
const unsigned afi,
const unsigned char fill, const ASN1_BIT_STRING *bs)
{
unsigned char addr[ADDR_RAW_BUF_LEN];
int i, n;
if (bs->length < 0)
return 0;
switch (afi) {
case IANA_AFI_IPV4:
if (!addr_expand(addr, bs, 4, fill))
return 0;
BIO_printf(out, "%d.%d.%d.%d", addr[0], addr[1], addr[2], addr[3]);
break;
case IANA_AFI_IPV6:
if (!addr_expand(addr, bs, 16, fill))
return 0;
for (n = 16; n > 1 && addr[n - 1] == 0x00 && addr[n - 2] == 0x00;
n -= 2) ;
for (i = 0; i < n; i += 2)
BIO_printf(out, "%x%s", (addr[i] << 8) | addr[i + 1],
(i < 14 ? ":" : ""));
if (i < 16)
BIO_puts(out, ":");
if (i == 0)
BIO_puts(out, ":");
break;
default:
for (i = 0; i < bs->length; i++)
BIO_printf(out, "%s%02x", (i > 0 ? ":" : ""), bs->data[i]);
BIO_printf(out, "[%d]", (int)(bs->flags & 7));
break;
}
return 1;
}
/*
* i2r handler for a sequence of addresses and ranges.
*/
static int i2r_IPAddressOrRanges(BIO *out,
const int indent,
const IPAddressOrRanges *aors,
const unsigned afi)
{
int i;
for (i = 0; i < sk_IPAddressOrRange_num(aors); i++) {
const IPAddressOrRange *aor = sk_IPAddressOrRange_value(aors, i);
BIO_printf(out, "%*s", indent, "");
switch (aor->type) {
case IPAddressOrRange_addressPrefix:
if (!i2r_address(out, afi, 0x00, aor->u.addressPrefix))
return 0;
BIO_printf(out, "/%d\n", addr_prefixlen(aor->u.addressPrefix));
continue;
case IPAddressOrRange_addressRange:
if (!i2r_address(out, afi, 0x00, aor->u.addressRange->min))
return 0;
BIO_puts(out, "-");
if (!i2r_address(out, afi, 0xFF, aor->u.addressRange->max))
return 0;
BIO_puts(out, "\n");
continue;
}
}
return 1;
}
/*
* i2r handler for an IPAddrBlocks extension.
*/
static int i2r_IPAddrBlocks(const X509V3_EXT_METHOD *method,
void *ext, BIO *out, int indent)
{
const IPAddrBlocks *addr = ext;
int i;
for (i = 0; i < sk_IPAddressFamily_num(addr); i++) {
IPAddressFamily *f = sk_IPAddressFamily_value(addr, i);
const unsigned int afi = X509v3_addr_get_afi(f);
switch (afi) {
case IANA_AFI_IPV4:
BIO_printf(out, "%*sIPv4", indent, "");
break;
case IANA_AFI_IPV6:
BIO_printf(out, "%*sIPv6", indent, "");
break;
default:
BIO_printf(out, "%*sUnknown AFI %u", indent, "", afi);
break;
}
if (f->addressFamily->length > 2) {
switch (f->addressFamily->data[2]) {
case 1:
BIO_puts(out, " (Unicast)");
break;
case 2:
BIO_puts(out, " (Multicast)");
break;
case 3:
BIO_puts(out, " (Unicast/Multicast)");
break;
case 4:
BIO_puts(out, " (MPLS)");
break;
case 64:
BIO_puts(out, " (Tunnel)");
break;
case 65:
BIO_puts(out, " (VPLS)");
break;
case 66:
BIO_puts(out, " (BGP MDT)");
break;
case 128:
BIO_puts(out, " (MPLS-labeled VPN)");
break;
default:
BIO_printf(out, " (Unknown SAFI %u)",
(unsigned)f->addressFamily->data[2]);
break;
}
}
switch (f->ipAddressChoice->type) {
case IPAddressChoice_inherit:
BIO_puts(out, ": inherit\n");
break;
case IPAddressChoice_addressesOrRanges:
BIO_puts(out, ":\n");
if (!i2r_IPAddressOrRanges(out,
indent + 2,
f->ipAddressChoice->
u.addressesOrRanges, afi))
return 0;
break;
}
}
return 1;
}
/*
* Sort comparison function for a sequence of IPAddressOrRange
* elements.
*
* There's no sane answer we can give if addr_expand() fails, and an
* assertion failure on externally supplied data is seriously uncool,
* so we just arbitrarily declare that if given invalid inputs this
* function returns -1. If this messes up your preferred sort order
* for garbage input, tough noogies.
*/
static int IPAddressOrRange_cmp(const IPAddressOrRange *a,
const IPAddressOrRange *b, const int length)
{
unsigned char addr_a[ADDR_RAW_BUF_LEN], addr_b[ADDR_RAW_BUF_LEN];
int prefixlen_a = 0, prefixlen_b = 0;
int r;
switch (a->type) {
case IPAddressOrRange_addressPrefix:
if (!addr_expand(addr_a, a->u.addressPrefix, length, 0x00))
return -1;
prefixlen_a = addr_prefixlen(a->u.addressPrefix);
break;
case IPAddressOrRange_addressRange:
if (!addr_expand(addr_a, a->u.addressRange->min, length, 0x00))
return -1;
prefixlen_a = length * 8;
break;
}
switch (b->type) {
case IPAddressOrRange_addressPrefix:
if (!addr_expand(addr_b, b->u.addressPrefix, length, 0x00))
return -1;
prefixlen_b = addr_prefixlen(b->u.addressPrefix);
break;
case IPAddressOrRange_addressRange:
if (!addr_expand(addr_b, b->u.addressRange->min, length, 0x00))
return -1;
prefixlen_b = length * 8;
break;
}
if ((r = memcmp(addr_a, addr_b, length)) != 0)
return r;
else
return prefixlen_a - prefixlen_b;
}
/*
* IPv4-specific closure over IPAddressOrRange_cmp, since sk_sort()
* comparison routines are only allowed two arguments.
*/
static int v4IPAddressOrRange_cmp(const IPAddressOrRange *const *a,
const IPAddressOrRange *const *b)
{
return IPAddressOrRange_cmp(*a, *b, 4);
}
/*
* IPv6-specific closure over IPAddressOrRange_cmp, since sk_sort()
* comparison routines are only allowed two arguments.
*/
static int v6IPAddressOrRange_cmp(const IPAddressOrRange *const *a,
const IPAddressOrRange *const *b)
{
return IPAddressOrRange_cmp(*a, *b, 16);
}
/*
* Calculate whether a range collapses to a prefix.
* See last paragraph of RFC 3779 2.2.3.7.
*/
static int range_should_be_prefix(const unsigned char *min,
const unsigned char *max, const int length)
{
unsigned char mask;
int i, j;
/*
* It is the responsibility of the caller to confirm min <= max. We don't
* use ossl_assert() here since we have no way of signalling an error from
* this function - so we just use a plain assert instead.
*/
assert(memcmp(min, max, length) <= 0);
for (i = 0; i < length && min[i] == max[i]; i++) ;
for (j = length - 1; j >= 0 && min[j] == 0x00 && max[j] == 0xFF; j--) ;
if (i < j)
return -1;
if (i > j)
return i * 8;
mask = min[i] ^ max[i];
switch (mask) {
case 0x01:
j = 7;
break;
case 0x03:
j = 6;
break;
case 0x07:
j = 5;
break;
case 0x0F:
j = 4;
break;
case 0x1F:
j = 3;
break;
case 0x3F:
j = 2;
break;
case 0x7F:
j = 1;
break;
default:
return -1;
}
if ((min[i] & mask) != 0 || (max[i] & mask) != mask)
return -1;
else
return i * 8 + j;
}
/*
* Construct a prefix.
*/
static int make_addressPrefix(IPAddressOrRange **result, unsigned char *addr,
const int prefixlen, const int afilen)
{
int bytelen = (prefixlen + 7) / 8, bitlen = prefixlen % 8;
- IPAddressOrRange *aor = IPAddressOrRange_new();
+ IPAddressOrRange *aor;
if (prefixlen < 0 || prefixlen > (afilen * 8))
return 0;
- if (aor == NULL)
+ if ((aor = IPAddressOrRange_new()) == NULL)
return 0;
aor->type = IPAddressOrRange_addressPrefix;
if (aor->u.addressPrefix == NULL &&
(aor->u.addressPrefix = ASN1_BIT_STRING_new()) == NULL)
goto err;
if (!ASN1_BIT_STRING_set(aor->u.addressPrefix, addr, bytelen))
goto err;
aor->u.addressPrefix->flags &= ~7;
aor->u.addressPrefix->flags |= ASN1_STRING_FLAG_BITS_LEFT;
if (bitlen > 0) {
aor->u.addressPrefix->data[bytelen - 1] &= ~(0xFF >> bitlen);
aor->u.addressPrefix->flags |= 8 - bitlen;
}
*result = aor;
return 1;
err:
IPAddressOrRange_free(aor);
return 0;
}
/*
* Construct a range. If it can be expressed as a prefix,
* return a prefix instead. Doing this here simplifies
* the rest of the code considerably.
*/
static int make_addressRange(IPAddressOrRange **result,
unsigned char *min,
unsigned char *max, const int length)
{
IPAddressOrRange *aor;
int i, prefixlen;
if (memcmp(min, max, length) > 0)
return 0;
if ((prefixlen = range_should_be_prefix(min, max, length)) >= 0)
return make_addressPrefix(result, min, prefixlen, length);
if ((aor = IPAddressOrRange_new()) == NULL)
return 0;
aor->type = IPAddressOrRange_addressRange;
if ((aor->u.addressRange = IPAddressRange_new()) == NULL)
goto err;
if (aor->u.addressRange->min == NULL &&
(aor->u.addressRange->min = ASN1_BIT_STRING_new()) == NULL)
goto err;
if (aor->u.addressRange->max == NULL &&
(aor->u.addressRange->max = ASN1_BIT_STRING_new()) == NULL)
goto err;
for (i = length; i > 0 && min[i - 1] == 0x00; --i) ;
if (!ASN1_BIT_STRING_set(aor->u.addressRange->min, min, i))
goto err;
aor->u.addressRange->min->flags &= ~7;
aor->u.addressRange->min->flags |= ASN1_STRING_FLAG_BITS_LEFT;
if (i > 0) {
unsigned char b = min[i - 1];
int j = 1;
while ((b & (0xFFU >> j)) != 0)
++j;
aor->u.addressRange->min->flags |= 8 - j;
}
for (i = length; i > 0 && max[i - 1] == 0xFF; --i) ;
if (!ASN1_BIT_STRING_set(aor->u.addressRange->max, max, i))
goto err;
aor->u.addressRange->max->flags &= ~7;
aor->u.addressRange->max->flags |= ASN1_STRING_FLAG_BITS_LEFT;
if (i > 0) {
unsigned char b = max[i - 1];
int j = 1;
while ((b & (0xFFU >> j)) != (0xFFU >> j))
++j;
aor->u.addressRange->max->flags |= 8 - j;
}
*result = aor;
return 1;
err:
IPAddressOrRange_free(aor);
return 0;
}
/*
* Construct a new address family or find an existing one.
*/
static IPAddressFamily *make_IPAddressFamily(IPAddrBlocks *addr,
const unsigned afi,
const unsigned *safi)
{
IPAddressFamily *f;
unsigned char key[3];
int keylen;
int i;
key[0] = (afi >> 8) & 0xFF;
key[1] = afi & 0xFF;
if (safi != NULL) {
key[2] = *safi & 0xFF;
keylen = 3;
} else {
keylen = 2;
}
for (i = 0; i < sk_IPAddressFamily_num(addr); i++) {
f = sk_IPAddressFamily_value(addr, i);
if (f->addressFamily->length == keylen &&
!memcmp(f->addressFamily->data, key, keylen))
return f;
}
if ((f = IPAddressFamily_new()) == NULL)
goto err;
if (f->ipAddressChoice == NULL &&
(f->ipAddressChoice = IPAddressChoice_new()) == NULL)
goto err;
if (f->addressFamily == NULL &&
(f->addressFamily = ASN1_OCTET_STRING_new()) == NULL)
goto err;
if (!ASN1_OCTET_STRING_set(f->addressFamily, key, keylen))
goto err;
if (!sk_IPAddressFamily_push(addr, f))
goto err;
return f;
err:
IPAddressFamily_free(f);
return NULL;
}
/*
* Add an inheritance element.
*/
int X509v3_addr_add_inherit(IPAddrBlocks *addr,
const unsigned afi, const unsigned *safi)
{
IPAddressFamily *f = make_IPAddressFamily(addr, afi, safi);
if (f == NULL ||
f->ipAddressChoice == NULL ||
(f->ipAddressChoice->type == IPAddressChoice_addressesOrRanges &&
f->ipAddressChoice->u.addressesOrRanges != NULL))
return 0;
if (f->ipAddressChoice->type == IPAddressChoice_inherit &&
f->ipAddressChoice->u.inherit != NULL)
return 1;
if (f->ipAddressChoice->u.inherit == NULL &&
(f->ipAddressChoice->u.inherit = ASN1_NULL_new()) == NULL)
return 0;
f->ipAddressChoice->type = IPAddressChoice_inherit;
return 1;
}
/*
* Construct an IPAddressOrRange sequence, or return an existing one.
*/
static IPAddressOrRanges *make_prefix_or_range(IPAddrBlocks *addr,
const unsigned afi,
const unsigned *safi)
{
IPAddressFamily *f = make_IPAddressFamily(addr, afi, safi);
IPAddressOrRanges *aors = NULL;
if (f == NULL ||
f->ipAddressChoice == NULL ||
(f->ipAddressChoice->type == IPAddressChoice_inherit &&
f->ipAddressChoice->u.inherit != NULL))
return NULL;
if (f->ipAddressChoice->type == IPAddressChoice_addressesOrRanges)
aors = f->ipAddressChoice->u.addressesOrRanges;
if (aors != NULL)
return aors;
if ((aors = sk_IPAddressOrRange_new_null()) == NULL)
return NULL;
switch (afi) {
case IANA_AFI_IPV4:
(void)sk_IPAddressOrRange_set_cmp_func(aors, v4IPAddressOrRange_cmp);
break;
case IANA_AFI_IPV6:
(void)sk_IPAddressOrRange_set_cmp_func(aors, v6IPAddressOrRange_cmp);
break;
}
f->ipAddressChoice->type = IPAddressChoice_addressesOrRanges;
f->ipAddressChoice->u.addressesOrRanges = aors;
return aors;
}
/*
* Add a prefix.
*/
int X509v3_addr_add_prefix(IPAddrBlocks *addr,
const unsigned afi,
const unsigned *safi,
unsigned char *a, const int prefixlen)
{
IPAddressOrRanges *aors = make_prefix_or_range(addr, afi, safi);
IPAddressOrRange *aor;
if (aors == NULL
|| !make_addressPrefix(&aor, a, prefixlen, length_from_afi(afi)))
return 0;
if (sk_IPAddressOrRange_push(aors, aor))
return 1;
IPAddressOrRange_free(aor);
return 0;
}
/*
* Add a range.
*/
int X509v3_addr_add_range(IPAddrBlocks *addr,
const unsigned afi,
const unsigned *safi,
unsigned char *min, unsigned char *max)
{
IPAddressOrRanges *aors = make_prefix_or_range(addr, afi, safi);
IPAddressOrRange *aor;
int length = length_from_afi(afi);
if (aors == NULL)
return 0;
if (!make_addressRange(&aor, min, max, length))
return 0;
if (sk_IPAddressOrRange_push(aors, aor))
return 1;
IPAddressOrRange_free(aor);
return 0;
}
/*
* Extract min and max values from an IPAddressOrRange.
*/
static int extract_min_max(IPAddressOrRange *aor,
unsigned char *min, unsigned char *max, int length)
{
if (aor == NULL || min == NULL || max == NULL)
return 0;
switch (aor->type) {
case IPAddressOrRange_addressPrefix:
return (addr_expand(min, aor->u.addressPrefix, length, 0x00) &&
addr_expand(max, aor->u.addressPrefix, length, 0xFF));
case IPAddressOrRange_addressRange:
return (addr_expand(min, aor->u.addressRange->min, length, 0x00) &&
addr_expand(max, aor->u.addressRange->max, length, 0xFF));
}
return 0;
}
/*
* Public wrapper for extract_min_max().
*/
int X509v3_addr_get_range(IPAddressOrRange *aor,
const unsigned afi,
unsigned char *min,
unsigned char *max, const int length)
{
int afi_length = length_from_afi(afi);
if (aor == NULL || min == NULL || max == NULL ||
afi_length == 0 || length < afi_length ||
(aor->type != IPAddressOrRange_addressPrefix &&
aor->type != IPAddressOrRange_addressRange) ||
!extract_min_max(aor, min, max, afi_length))
return 0;
return afi_length;
}
/*
* Sort comparison function for a sequence of IPAddressFamily.
*
* The last paragraph of RFC 3779 2.2.3.3 is slightly ambiguous about
* the ordering: I can read it as meaning that IPv6 without a SAFI
* comes before IPv4 with a SAFI, which seems pretty weird. The
* examples in appendix B suggest that the author intended the
* null-SAFI rule to apply only within a single AFI, which is what I
* would have expected and is what the following code implements.
*/
static int IPAddressFamily_cmp(const IPAddressFamily *const *a_,
const IPAddressFamily *const *b_)
{
const ASN1_OCTET_STRING *a = (*a_)->addressFamily;
const ASN1_OCTET_STRING *b = (*b_)->addressFamily;
int len = ((a->length <= b->length) ? a->length : b->length);
int cmp = memcmp(a->data, b->data, len);
return cmp ? cmp : a->length - b->length;
}
static int IPAddressFamily_check_len(const IPAddressFamily *f)
{
if (f->addressFamily->length < 2 || f->addressFamily->length > 3)
return 0;
else
return 1;
}
/*
* Check whether an IPAddrBLocks is in canonical form.
*/
int X509v3_addr_is_canonical(IPAddrBlocks *addr)
{
unsigned char a_min[ADDR_RAW_BUF_LEN], a_max[ADDR_RAW_BUF_LEN];
unsigned char b_min[ADDR_RAW_BUF_LEN], b_max[ADDR_RAW_BUF_LEN];
IPAddressOrRanges *aors;
int i, j, k;
/*
* Empty extension is canonical.
*/
if (addr == NULL)
return 1;
/*
* Check whether the top-level list is in order.
*/
for (i = 0; i < sk_IPAddressFamily_num(addr) - 1; i++) {
const IPAddressFamily *a = sk_IPAddressFamily_value(addr, i);
const IPAddressFamily *b = sk_IPAddressFamily_value(addr, i + 1);
if (!IPAddressFamily_check_len(a) || !IPAddressFamily_check_len(b))
return 0;
if (IPAddressFamily_cmp(&a, &b) >= 0)
return 0;
}
/*
* Top level's ok, now check each address family.
*/
for (i = 0; i < sk_IPAddressFamily_num(addr); i++) {
IPAddressFamily *f = sk_IPAddressFamily_value(addr, i);
int length = length_from_afi(X509v3_addr_get_afi(f));
/*
* Inheritance is canonical. Anything other than inheritance or
* a SEQUENCE OF IPAddressOrRange is an ASN.1 error or something.
*/
if (f == NULL || f->ipAddressChoice == NULL)
return 0;
switch (f->ipAddressChoice->type) {
case IPAddressChoice_inherit:
continue;
case IPAddressChoice_addressesOrRanges:
break;
default:
return 0;
}
if (!IPAddressFamily_check_len(f))
return 0;
/*
* It's an IPAddressOrRanges sequence, check it.
*/
aors = f->ipAddressChoice->u.addressesOrRanges;
if (sk_IPAddressOrRange_num(aors) == 0)
return 0;
for (j = 0; j < sk_IPAddressOrRange_num(aors) - 1; j++) {
IPAddressOrRange *a = sk_IPAddressOrRange_value(aors, j);
IPAddressOrRange *b = sk_IPAddressOrRange_value(aors, j + 1);
if (!extract_min_max(a, a_min, a_max, length) ||
!extract_min_max(b, b_min, b_max, length))
return 0;
/*
* Punt misordered list, overlapping start, or inverted range.
*/
if (memcmp(a_min, b_min, length) >= 0 ||
memcmp(a_min, a_max, length) > 0 ||
memcmp(b_min, b_max, length) > 0)
return 0;
/*
* Punt if adjacent or overlapping. Check for adjacency by
* subtracting one from b_min first.
*/
for (k = length - 1; k >= 0 && b_min[k]-- == 0x00; k--) ;
if (memcmp(a_max, b_min, length) >= 0)
return 0;
/*
* Check for range that should be expressed as a prefix.
*/
if (a->type == IPAddressOrRange_addressRange &&
range_should_be_prefix(a_min, a_max, length) >= 0)
return 0;
}
/*
* Check range to see if it's inverted or should be a
* prefix.
*/
j = sk_IPAddressOrRange_num(aors) - 1;
{
IPAddressOrRange *a = sk_IPAddressOrRange_value(aors, j);
if (a != NULL && a->type == IPAddressOrRange_addressRange) {
if (!extract_min_max(a, a_min, a_max, length))
return 0;
if (memcmp(a_min, a_max, length) > 0 ||
range_should_be_prefix(a_min, a_max, length) >= 0)
return 0;
}
}
}
/*
* If we made it through all that, we're happy.
*/
return 1;
}
/*
* Whack an IPAddressOrRanges into canonical form.
*/
static int IPAddressOrRanges_canonize(IPAddressOrRanges *aors,
const unsigned afi)
{
int i, j, length = length_from_afi(afi);
/*
* Sort the IPAddressOrRanges sequence.
*/
sk_IPAddressOrRange_sort(aors);
/*
* Clean up representation issues, punt on duplicates or overlaps.
*/
for (i = 0; i < sk_IPAddressOrRange_num(aors) - 1; i++) {
IPAddressOrRange *a = sk_IPAddressOrRange_value(aors, i);
IPAddressOrRange *b = sk_IPAddressOrRange_value(aors, i + 1);
unsigned char a_min[ADDR_RAW_BUF_LEN], a_max[ADDR_RAW_BUF_LEN];
unsigned char b_min[ADDR_RAW_BUF_LEN], b_max[ADDR_RAW_BUF_LEN];
if (!extract_min_max(a, a_min, a_max, length) ||
!extract_min_max(b, b_min, b_max, length))
return 0;
/*
* Punt inverted ranges.
*/
if (memcmp(a_min, a_max, length) > 0 ||
memcmp(b_min, b_max, length) > 0)
return 0;
/*
* Punt overlaps.
*/
if (memcmp(a_max, b_min, length) >= 0)
return 0;
/*
* Merge if a and b are adjacent. We check for
* adjacency by subtracting one from b_min first.
*/
for (j = length - 1; j >= 0 && b_min[j]-- == 0x00; j--) ;
if (memcmp(a_max, b_min, length) == 0) {
IPAddressOrRange *merged;
if (!make_addressRange(&merged, a_min, b_max, length))
return 0;
(void)sk_IPAddressOrRange_set(aors, i, merged);
(void)sk_IPAddressOrRange_delete(aors, i + 1);
IPAddressOrRange_free(a);
IPAddressOrRange_free(b);
--i;
continue;
}
}
/*
* Check for inverted final range.
*/
j = sk_IPAddressOrRange_num(aors) - 1;
{
IPAddressOrRange *a = sk_IPAddressOrRange_value(aors, j);
if (a != NULL && a->type == IPAddressOrRange_addressRange) {
unsigned char a_min[ADDR_RAW_BUF_LEN], a_max[ADDR_RAW_BUF_LEN];
if (!extract_min_max(a, a_min, a_max, length))
return 0;
if (memcmp(a_min, a_max, length) > 0)
return 0;
}
}
return 1;
}
/*
* Whack an IPAddrBlocks extension into canonical form.
*/
int X509v3_addr_canonize(IPAddrBlocks *addr)
{
int i;
for (i = 0; i < sk_IPAddressFamily_num(addr); i++) {
IPAddressFamily *f = sk_IPAddressFamily_value(addr, i);
if (!IPAddressFamily_check_len(f))
return 0;
if (f->ipAddressChoice->type == IPAddressChoice_addressesOrRanges &&
!IPAddressOrRanges_canonize(f->ipAddressChoice->
u.addressesOrRanges,
X509v3_addr_get_afi(f)))
return 0;
}
(void)sk_IPAddressFamily_set_cmp_func(addr, IPAddressFamily_cmp);
sk_IPAddressFamily_sort(addr);
if (!ossl_assert(X509v3_addr_is_canonical(addr)))
return 0;
return 1;
}
/*
* v2i handler for the IPAddrBlocks extension.
*/
static void *v2i_IPAddrBlocks(const struct v3_ext_method *method,
struct v3_ext_ctx *ctx,
STACK_OF(CONF_VALUE) *values)
{
static const char v4addr_chars[] = "0123456789.";
static const char v6addr_chars[] = "0123456789.:abcdefABCDEF";
IPAddrBlocks *addr = NULL;
char *s = NULL, *t;
int i;
if ((addr = sk_IPAddressFamily_new(IPAddressFamily_cmp)) == NULL) {
ERR_raise(ERR_LIB_X509V3, ERR_R_MALLOC_FAILURE);
return NULL;
}
for (i = 0; i < sk_CONF_VALUE_num(values); i++) {
CONF_VALUE *val = sk_CONF_VALUE_value(values, i);
unsigned char min[ADDR_RAW_BUF_LEN], max[ADDR_RAW_BUF_LEN];
unsigned afi, *safi = NULL, safi_;
const char *addr_chars = NULL;
int prefixlen, i1, i2, delim, length;
if (!ossl_v3_name_cmp(val->name, "IPv4")) {
afi = IANA_AFI_IPV4;
} else if (!ossl_v3_name_cmp(val->name, "IPv6")) {
afi = IANA_AFI_IPV6;
} else if (!ossl_v3_name_cmp(val->name, "IPv4-SAFI")) {
afi = IANA_AFI_IPV4;
safi = &safi_;
} else if (!ossl_v3_name_cmp(val->name, "IPv6-SAFI")) {
afi = IANA_AFI_IPV6;
safi = &safi_;
} else {
ERR_raise_data(ERR_LIB_X509V3, X509V3_R_EXTENSION_NAME_ERROR,
"%s", val->name);
goto err;
}
switch (afi) {
case IANA_AFI_IPV4:
addr_chars = v4addr_chars;
break;
case IANA_AFI_IPV6:
addr_chars = v6addr_chars;
break;
}
length = length_from_afi(afi);
/*
* Handle SAFI, if any, and OPENSSL_strdup() so we can null-terminate
* the other input values.
*/
if (safi != NULL) {
if (val->value == NULL) {
ERR_raise(ERR_LIB_X509V3, X509V3_R_MISSING_VALUE);
goto err;
}
*safi = strtoul(val->value, &t, 0);
t += strspn(t, " \t");
if (*safi > 0xFF || *t++ != ':') {
ERR_raise(ERR_LIB_X509V3, X509V3_R_INVALID_SAFI);
X509V3_conf_add_error_name_value(val);
goto err;
}
t += strspn(t, " \t");
s = OPENSSL_strdup(t);
} else {
s = OPENSSL_strdup(val->value);
}
if (s == NULL) {
ERR_raise(ERR_LIB_X509V3, ERR_R_MALLOC_FAILURE);
goto err;
}
/*
* Check for inheritance. Not worth additional complexity to
* optimize this (seldom-used) case.
*/
if (strcmp(s, "inherit") == 0) {
if (!X509v3_addr_add_inherit(addr, afi, safi)) {
ERR_raise(ERR_LIB_X509V3, X509V3_R_INVALID_INHERITANCE);
X509V3_conf_add_error_name_value(val);
goto err;
}
OPENSSL_free(s);
s = NULL;
continue;
}
i1 = strspn(s, addr_chars);
i2 = i1 + strspn(s + i1, " \t");
delim = s[i2++];
s[i1] = '\0';
if (ossl_a2i_ipadd(min, s) != length) {
ERR_raise(ERR_LIB_X509V3, X509V3_R_INVALID_IPADDRESS);
X509V3_conf_add_error_name_value(val);
goto err;
}
switch (delim) {
case '/':
prefixlen = (int)strtoul(s + i2, &t, 10);
if (t == s + i2
|| *t != '\0'
|| prefixlen > (length * 8)
|| prefixlen < 0) {
ERR_raise(ERR_LIB_X509V3, X509V3_R_EXTENSION_VALUE_ERROR);
X509V3_conf_add_error_name_value(val);
goto err;
}
if (!X509v3_addr_add_prefix(addr, afi, safi, min, prefixlen)) {
ERR_raise(ERR_LIB_X509V3, ERR_R_MALLOC_FAILURE);
goto err;
}
break;
case '-':
i1 = i2 + strspn(s + i2, " \t");
i2 = i1 + strspn(s + i1, addr_chars);
if (i1 == i2 || s[i2] != '\0') {
ERR_raise(ERR_LIB_X509V3, X509V3_R_EXTENSION_VALUE_ERROR);
X509V3_conf_add_error_name_value(val);
goto err;
}
if (ossl_a2i_ipadd(max, s + i1) != length) {
ERR_raise(ERR_LIB_X509V3, X509V3_R_INVALID_IPADDRESS);
X509V3_conf_add_error_name_value(val);
goto err;
}
if (memcmp(min, max, length_from_afi(afi)) > 0) {
ERR_raise(ERR_LIB_X509V3, X509V3_R_EXTENSION_VALUE_ERROR);
X509V3_conf_add_error_name_value(val);
goto err;
}
if (!X509v3_addr_add_range(addr, afi, safi, min, max)) {
ERR_raise(ERR_LIB_X509V3, ERR_R_MALLOC_FAILURE);
goto err;
}
break;
case '\0':
if (!X509v3_addr_add_prefix(addr, afi, safi, min, length * 8)) {
ERR_raise(ERR_LIB_X509V3, ERR_R_MALLOC_FAILURE);
goto err;
}
break;
default:
ERR_raise(ERR_LIB_X509V3, X509V3_R_EXTENSION_VALUE_ERROR);
X509V3_conf_add_error_name_value(val);
goto err;
}
OPENSSL_free(s);
s = NULL;
}
/*
* Canonize the result, then we're done.
*/
if (!X509v3_addr_canonize(addr))
goto err;
return addr;
err:
OPENSSL_free(s);
sk_IPAddressFamily_pop_free(addr, IPAddressFamily_free);
return NULL;
}
/*
* OpenSSL dispatch
*/
const X509V3_EXT_METHOD ossl_v3_addr = {
NID_sbgp_ipAddrBlock, /* nid */
0, /* flags */
ASN1_ITEM_ref(IPAddrBlocks), /* template */
0, 0, 0, 0, /* old functions, ignored */
0, /* i2s */
0, /* s2i */
0, /* i2v */
v2i_IPAddrBlocks, /* v2i */
i2r_IPAddrBlocks, /* i2r */
0, /* r2i */
NULL /* extension-specific data */
};
/*
* Figure out whether extension sues inheritance.
*/
int X509v3_addr_inherits(IPAddrBlocks *addr)
{
int i;
if (addr == NULL)
return 0;
for (i = 0; i < sk_IPAddressFamily_num(addr); i++) {
IPAddressFamily *f = sk_IPAddressFamily_value(addr, i);
if (f->ipAddressChoice->type == IPAddressChoice_inherit)
return 1;
}
return 0;
}
/*
* Figure out whether parent contains child.
*/
static int addr_contains(IPAddressOrRanges *parent,
IPAddressOrRanges *child, int length)
{
unsigned char p_min[ADDR_RAW_BUF_LEN], p_max[ADDR_RAW_BUF_LEN];
unsigned char c_min[ADDR_RAW_BUF_LEN], c_max[ADDR_RAW_BUF_LEN];
int p, c;
if (child == NULL || parent == child)
return 1;
if (parent == NULL)
return 0;
p = 0;
for (c = 0; c < sk_IPAddressOrRange_num(child); c++) {
if (!extract_min_max(sk_IPAddressOrRange_value(child, c),
c_min, c_max, length))
return 0;
for (;; p++) {
if (p >= sk_IPAddressOrRange_num(parent))
return 0;
if (!extract_min_max(sk_IPAddressOrRange_value(parent, p),
p_min, p_max, length))
return 0;
if (memcmp(p_max, c_max, length) < 0)
continue;
if (memcmp(p_min, c_min, length) > 0)
return 0;
break;
}
}
return 1;
}
/*
* Test whether a is a subset of b.
*/
int X509v3_addr_subset(IPAddrBlocks *a, IPAddrBlocks *b)
{
int i;
if (a == NULL || a == b)
return 1;
if (b == NULL || X509v3_addr_inherits(a) || X509v3_addr_inherits(b))
return 0;
(void)sk_IPAddressFamily_set_cmp_func(b, IPAddressFamily_cmp);
for (i = 0; i < sk_IPAddressFamily_num(a); i++) {
IPAddressFamily *fa = sk_IPAddressFamily_value(a, i);
int j = sk_IPAddressFamily_find(b, fa);
IPAddressFamily *fb = sk_IPAddressFamily_value(b, j);
if (fb == NULL)
return 0;
if (!IPAddressFamily_check_len(fa) || !IPAddressFamily_check_len(fb))
return 0;
if (!addr_contains(fb->ipAddressChoice->u.addressesOrRanges,
fa->ipAddressChoice->u.addressesOrRanges,
length_from_afi(X509v3_addr_get_afi(fb))))
return 0;
}
return 1;
}
/*
* Validation error handling via callback.
*/
# define validation_err(_err_) \
do { \
if (ctx != NULL) { \
ctx->error = _err_; \
ctx->error_depth = i; \
ctx->current_cert = x; \
rv = ctx->verify_cb(0, ctx); \
} else { \
rv = 0; \
} \
if (rv == 0) \
goto done; \
} while (0)
/*
* Core code for RFC 3779 2.3 path validation.
*
* Returns 1 for success, 0 on error.
*
* When returning 0, ctx->error MUST be set to an appropriate value other than
* X509_V_OK.
*/
static int addr_validate_path_internal(X509_STORE_CTX *ctx,
STACK_OF(X509) *chain,
IPAddrBlocks *ext)
{
IPAddrBlocks *child = NULL;
int i, j, ret = 0, rv;
X509 *x;
if (!ossl_assert(chain != NULL && sk_X509_num(chain) > 0)
|| !ossl_assert(ctx != NULL || ext != NULL)
|| !ossl_assert(ctx == NULL || ctx->verify_cb != NULL)) {
if (ctx != NULL)
ctx->error = X509_V_ERR_UNSPECIFIED;
return 0;
}
/*
* Figure out where to start. If we don't have an extension to
* check, we're done. Otherwise, check canonical form and
* set up for walking up the chain.
*/
if (ext != NULL) {
i = -1;
x = NULL;
} else {
i = 0;
x = sk_X509_value(chain, i);
if ((ext = x->rfc3779_addr) == NULL)
return 1; /* Return success */
}
if (!X509v3_addr_is_canonical(ext))
validation_err(X509_V_ERR_INVALID_EXTENSION);
(void)sk_IPAddressFamily_set_cmp_func(ext, IPAddressFamily_cmp);
if ((child = sk_IPAddressFamily_dup(ext)) == NULL) {
ERR_raise(ERR_LIB_X509V3, ERR_R_MALLOC_FAILURE);
if (ctx != NULL)
ctx->error = X509_V_ERR_OUT_OF_MEM;
goto done;
}
/*
* Now walk up the chain. No cert may list resources that its
* parent doesn't list.
*/
for (i++; i < sk_X509_num(chain); i++) {
x = sk_X509_value(chain, i);
if (!X509v3_addr_is_canonical(x->rfc3779_addr))
validation_err(X509_V_ERR_INVALID_EXTENSION);
if (x->rfc3779_addr == NULL) {
for (j = 0; j < sk_IPAddressFamily_num(child); j++) {
IPAddressFamily *fc = sk_IPAddressFamily_value(child, j);
if (!IPAddressFamily_check_len(fc))
goto done;
if (fc->ipAddressChoice->type != IPAddressChoice_inherit) {
validation_err(X509_V_ERR_UNNESTED_RESOURCE);
break;
}
}
continue;
}
(void)sk_IPAddressFamily_set_cmp_func(x->rfc3779_addr,
IPAddressFamily_cmp);
for (j = 0; j < sk_IPAddressFamily_num(child); j++) {
IPAddressFamily *fc = sk_IPAddressFamily_value(child, j);
int k = sk_IPAddressFamily_find(x->rfc3779_addr, fc);
IPAddressFamily *fp =
sk_IPAddressFamily_value(x->rfc3779_addr, k);
if (fp == NULL) {
if (fc->ipAddressChoice->type ==
IPAddressChoice_addressesOrRanges) {
validation_err(X509_V_ERR_UNNESTED_RESOURCE);
break;
}
continue;
}
if (!IPAddressFamily_check_len(fc) || !IPAddressFamily_check_len(fp))
goto done;
if (fp->ipAddressChoice->type ==
IPAddressChoice_addressesOrRanges) {
if (fc->ipAddressChoice->type == IPAddressChoice_inherit
|| addr_contains(fp->ipAddressChoice->u.addressesOrRanges,
fc->ipAddressChoice->u.addressesOrRanges,
length_from_afi(X509v3_addr_get_afi(fc))))
(void)sk_IPAddressFamily_set(child, j, fp);
else
validation_err(X509_V_ERR_UNNESTED_RESOURCE);
}
}
}
/*
* Trust anchor can't inherit.
*/
if (x->rfc3779_addr != NULL) {
for (j = 0; j < sk_IPAddressFamily_num(x->rfc3779_addr); j++) {
IPAddressFamily *fp = sk_IPAddressFamily_value(x->rfc3779_addr, j);
if (!IPAddressFamily_check_len(fp))
goto done;
if (fp->ipAddressChoice->type == IPAddressChoice_inherit
&& sk_IPAddressFamily_find(child, fp) >= 0)
validation_err(X509_V_ERR_UNNESTED_RESOURCE);
}
}
ret = 1;
done:
sk_IPAddressFamily_free(child);
return ret;
}
#undef validation_err
/*
* RFC 3779 2.3 path validation -- called from X509_verify_cert().
*/
int X509v3_addr_validate_path(X509_STORE_CTX *ctx)
{
if (ctx->chain == NULL
|| sk_X509_num(ctx->chain) == 0
|| ctx->verify_cb == NULL) {
ctx->error = X509_V_ERR_UNSPECIFIED;
return 0;
}
return addr_validate_path_internal(ctx, ctx->chain, NULL);
}
/*
* RFC 3779 2.3 path validation of an extension.
* Test whether chain covers extension.
*/
int X509v3_addr_validate_resource_set(STACK_OF(X509) *chain,
IPAddrBlocks *ext, int allow_inheritance)
{
if (ext == NULL)
return 1;
if (chain == NULL || sk_X509_num(chain) == 0)
return 0;
if (!allow_inheritance && X509v3_addr_inherits(ext))
return 0;
return addr_validate_path_internal(NULL, chain, ext);
}
#endif /* OPENSSL_NO_RFC3779 */
diff --git a/crypto/openssl/demos/digest/EVP_MD_demo.c b/crypto/openssl/demos/digest/EVP_MD_demo.c
index 99589bd3446b..79e585d0ba4f 100644
--- a/crypto/openssl/demos/digest/EVP_MD_demo.c
+++ b/crypto/openssl/demos/digest/EVP_MD_demo.c
@@ -1,183 +1,183 @@
/*-
- * Copyright 2021 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2021-2024 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
*/
/*
* Example of using EVP_MD_fetch and EVP_Digest* methods to calculate
* a digest of static buffers
*/
#include <string.h>
#include <stdio.h>
#include <openssl/err.h>
#include <openssl/evp.h>
/*-
* This demonstration will show how to digest data using
* the soliloqy from Hamlet scene 1 act 3
* The soliloqy is split into two parts to demonstrate using EVP_DigestUpdate
* more than once.
*/
const char * hamlet_1 =
"To be, or not to be, that is the question,\n"
"Whether tis nobler in the minde to suffer\n"
"The ſlings and arrowes of outragious fortune,\n"
"Or to take Armes again in a sea of troubles,\n"
"And by opposing, end them, to die to sleep;\n"
"No more, and by a sleep, to say we end\n"
"The heart-ache, and the thousand natural shocks\n"
"That flesh is heir to? tis a consumation\n"
"Devoutly to be wished. To die to sleep,\n"
"To sleepe, perchance to dreame, Aye, there's the rub,\n"
"For in that sleep of death what dreams may come\n"
"When we haue shuffled off this mortal coil\n"
"Must give us pause. There's the respect\n"
"That makes calamity of so long life:\n"
"For who would bear the Ships and Scorns of time,\n"
"The oppressor's wrong, the proud man's Contumely,\n"
"The pangs of dispised love, the Law's delay,\n"
;
const char * hamlet_2 =
"The insolence of Office, and the spurns\n"
"That patient merit of the'unworthy takes,\n"
"When he himself might his Quietas make\n"
"With a bare bodkin? Who would fardels bear,\n"
"To grunt and sweat under a weary life,\n"
"But that the dread of something after death,\n"
"The undiscovered country, from whose bourn\n"
"No traveller returns, puzzles the will,\n"
"And makes us rather bear those ills we have,\n"
"Then fly to others we know not of?\n"
"Thus conscience does make cowards of us all,\n"
"And thus the native hue of Resolution\n"
"Is sickled o'er with the pale cast of Thought,\n"
"And enterprises of great pith and moment,\n"
"With this regard their currents turn awry,\n"
"And lose the name of Action. Soft you now,\n"
"The fair Ophelia? Nymph in thy Orisons\n"
"Be all my sins remember'd.\n"
;
/* The known value of the SHA3-512 digest of the above soliloqy */
const unsigned char known_answer[] = {
0xbb, 0x69, 0xf8, 0x09, 0x9c, 0x2e, 0x00, 0x3d,
0xa4, 0x29, 0x5f, 0x59, 0x4b, 0x89, 0xe4, 0xd9,
0xdb, 0xa2, 0xe5, 0xaf, 0xa5, 0x87, 0x73, 0x9d,
0x83, 0x72, 0xcf, 0xea, 0x84, 0x66, 0xc1, 0xf9,
0xc9, 0x78, 0xef, 0xba, 0x3d, 0xe9, 0xc1, 0xff,
0xa3, 0x75, 0xc7, 0x58, 0x74, 0x8e, 0x9c, 0x1d,
0x14, 0xd9, 0xdd, 0xd1, 0xfd, 0x24, 0x30, 0xd6,
0x81, 0xca, 0x8f, 0x78, 0x29, 0x19, 0x9a, 0xfe,
};
int demonstrate_digest(void)
{
OSSL_LIB_CTX *library_context;
int result = 0;
const char *option_properties = NULL;
EVP_MD *message_digest = NULL;
EVP_MD_CTX *digest_context = NULL;
- unsigned int digest_length;
+ int digest_length;
unsigned char *digest_value = NULL;
int j;
library_context = OSSL_LIB_CTX_new();
if (library_context == NULL) {
fprintf(stderr, "OSSL_LIB_CTX_new() returned NULL\n");
goto cleanup;
}
/*
* Fetch a message digest by name
* The algorithm name is case insensitive.
* See providers(7) for details about algorithm fetching
*/
message_digest = EVP_MD_fetch(library_context,
"SHA3-512", option_properties);
if (message_digest == NULL) {
fprintf(stderr, "EVP_MD_fetch could not find SHA3-512.");
goto cleanup;
}
/* Determine the length of the fetched digest type */
digest_length = EVP_MD_get_size(message_digest);
if (digest_length <= 0) {
fprintf(stderr, "EVP_MD_get_size returned invalid size.\n");
goto cleanup;
}
digest_value = OPENSSL_malloc(digest_length);
if (digest_value == NULL) {
fprintf(stderr, "No memory.\n");
goto cleanup;
}
/*
* Make a message digest context to hold temporary state
* during digest creation
*/
digest_context = EVP_MD_CTX_new();
if (digest_context == NULL) {
fprintf(stderr, "EVP_MD_CTX_new failed.\n");
goto cleanup;
}
/*
* Initialize the message digest context to use the fetched
* digest provider
*/
if (EVP_DigestInit(digest_context, message_digest) != 1) {
fprintf(stderr, "EVP_DigestInit failed.\n");
goto cleanup;
}
/* Digest parts one and two of the soliloqy */
if (EVP_DigestUpdate(digest_context, hamlet_1, strlen(hamlet_1)) != 1) {
fprintf(stderr, "EVP_DigestUpdate(hamlet_1) failed.\n");
goto cleanup;
}
if (EVP_DigestUpdate(digest_context, hamlet_2, strlen(hamlet_2)) != 1) {
fprintf(stderr, "EVP_DigestUpdate(hamlet_2) failed.\n");
goto cleanup;
}
if (EVP_DigestFinal(digest_context, digest_value, &digest_length) != 1) {
fprintf(stderr, "EVP_DigestFinal() failed.\n");
goto cleanup;
}
for (j=0; j<digest_length; j++) {
fprintf(stdout, "%02x", digest_value[j]);
}
fprintf(stdout, "\n");
/* Check digest_value against the known answer */
if ((size_t)digest_length != sizeof(known_answer)) {
fprintf(stdout, "Digest length(%d) not equal to known answer length(%lu).\n",
digest_length, sizeof(known_answer));
} else if (memcmp(digest_value, known_answer, digest_length) != 0) {
for (j=0; j<sizeof(known_answer); j++) {
fprintf(stdout, "%02x", known_answer[j] );
}
fprintf(stdout, "\nDigest does not match known answer\n");
} else {
fprintf(stdout, "Digest computed properly.\n");
result = 1;
}
cleanup:
if (result != 1)
ERR_print_errors_fp(stderr);
/* OpenSSL free functions will ignore NULL arguments */
EVP_MD_CTX_free(digest_context);
OPENSSL_free(digest_value);
EVP_MD_free(message_digest);
OSSL_LIB_CTX_free(library_context);
return result;
}
int main(void)
{
return demonstrate_digest() == 0;
}
diff --git a/crypto/openssl/demos/digest/EVP_MD_stdin.c b/crypto/openssl/demos/digest/EVP_MD_stdin.c
index 71a3d325a364..47e6b523857c 100644
--- a/crypto/openssl/demos/digest/EVP_MD_stdin.c
+++ b/crypto/openssl/demos/digest/EVP_MD_stdin.c
@@ -1,134 +1,134 @@
/*-
- * Copyright 2019-2021 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2019-2024 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
*/
/*-
* Example of using EVP_MD_fetch and EVP_Digest* methods to calculate
* a digest of static buffers
* You can find SHA3 test vectors from NIST here:
* https://csrc.nist.gov/CSRC/media/Projects/Cryptographic-Algorithm-Validation-Program/documents/sha3/sha-3bytetestvectors.zip
* For example, contains these lines:
Len = 80
Msg = 1ca984dcc913344370cf
MD = 6915ea0eeffb99b9b246a0e34daf3947852684c3d618260119a22835659e4f23d4eb66a15d0affb8e93771578f5e8f25b7a5f2a55f511fb8b96325ba2cd14816
* use xxd convert the hex message string to binary input for EVP_MD_stdin:
* echo "1ca984dcc913344370cf" | xxd -r -p | ./EVP_MD_stdin
* and then verify the output matches MD above.
*/
#include <string.h>
#include <stdio.h>
#include <openssl/err.h>
#include <openssl/evp.h>
/*-
* This demonstration will show how to digest data using
* a BIO created to read from stdin
*/
int demonstrate_digest(BIO *input)
{
OSSL_LIB_CTX *library_context = NULL;
int result = 0;
const char * option_properties = NULL;
EVP_MD *message_digest = NULL;
EVP_MD_CTX *digest_context = NULL;
- unsigned int digest_length;
+ int digest_length;
unsigned char *digest_value = NULL;
unsigned char buffer[512];
int ii;
library_context = OSSL_LIB_CTX_new();
if (library_context == NULL) {
fprintf(stderr, "OSSL_LIB_CTX_new() returned NULL\n");
goto cleanup;
}
/*
* Fetch a message digest by name
* The algorithm name is case insensitive.
* See providers(7) for details about algorithm fetching
*/
message_digest = EVP_MD_fetch(library_context,
"SHA3-512", option_properties);
if (message_digest == NULL) {
fprintf(stderr, "EVP_MD_fetch could not find SHA3-512.");
ERR_print_errors_fp(stderr);
OSSL_LIB_CTX_free(library_context);
return 0;
}
/* Determine the length of the fetched digest type */
digest_length = EVP_MD_get_size(message_digest);
if (digest_length <= 0) {
fprintf(stderr, "EVP_MD_get_size returned invalid size.\n");
goto cleanup;
}
digest_value = OPENSSL_malloc(digest_length);
if (digest_value == NULL) {
fprintf(stderr, "No memory.\n");
goto cleanup;
}
/*
* Make a message digest context to hold temporary state
* during digest creation
*/
digest_context = EVP_MD_CTX_new();
if (digest_context == NULL) {
fprintf(stderr, "EVP_MD_CTX_new failed.\n");
ERR_print_errors_fp(stderr);
goto cleanup;
}
/*
* Initialize the message digest context to use the fetched
* digest provider
*/
if (EVP_DigestInit(digest_context, message_digest) != 1) {
fprintf(stderr, "EVP_DigestInit failed.\n");
ERR_print_errors_fp(stderr);
goto cleanup;
}
while ((ii = BIO_read(input, buffer, sizeof(buffer))) > 0) {
if (EVP_DigestUpdate(digest_context, buffer, ii) != 1) {
fprintf(stderr, "EVP_DigestUpdate() failed.\n");
goto cleanup;
}
}
if (EVP_DigestFinal(digest_context, digest_value, &digest_length) != 1) {
fprintf(stderr, "EVP_DigestFinal() failed.\n");
goto cleanup;
}
result = 1;
for (ii=0; ii<digest_length; ii++) {
fprintf(stdout, "%02x", digest_value[ii]);
}
fprintf(stdout, "\n");
cleanup:
if (result != 1)
ERR_print_errors_fp(stderr);
/* OpenSSL free functions will ignore NULL arguments */
EVP_MD_CTX_free(digest_context);
OPENSSL_free(digest_value);
EVP_MD_free(message_digest);
OSSL_LIB_CTX_free(library_context);
return result;
}
int main(void)
{
int result = 1;
BIO *input = BIO_new_fd( fileno(stdin), 1 );
if (input != NULL) {
result = demonstrate_digest(input);
BIO_free(input);
}
return result;
}
diff --git a/crypto/openssl/doc/fingerprints.txt b/crypto/openssl/doc/fingerprints.txt
index 9a26f7c66722..9613cbac9848 100644
--- a/crypto/openssl/doc/fingerprints.txt
+++ b/crypto/openssl/doc/fingerprints.txt
@@ -1,28 +1,31 @@
Fingerprints for Signing Releases
OpenSSL releases are signed with PGP/GnuPG keys. This file contains
the fingerprints of team members who are "authorized" to sign the
next release.
The signature is a detached cleartxt signature, with the same name
as the release but with ".asc" appended. For example, release
1.0.1h can be found in openssl-1.0.1h.tar.gz with the signature
in the file named openssl-1.0.1h.tar.gz.asc.
The following is the list of fingerprints for the keys that are
currently in use to sign OpenSSL distributions:
OpenSSL OMC:
EFC0 A467 D613 CB83 C7ED 6D30 D894 E2CE 8B3D 79F5
+OpenSSL:
+BA54 73A2 B058 7B07 FB27 CF2D 2160 94DF D0CB 81EF
+
Richard Levitte:
7953 AC1F BC3D C8B3 B292 393E D5E9 E43F 7DF9 EE8C
Matt Caswell:
8657 ABB2 60F0 56B1 E519 0839 D9C4 D26D 0E60 4491
Paul Dale:
B7C1 C143 60F3 53A3 6862 E4D5 231C 84CD DCC6 9C45
Tomáš Mráz:
A21F AB74 B008 8AA3 6115 2586 B8EF 1A6B A9DA 2D5C
diff --git a/crypto/openssl/doc/internal/man3/OPTIONS.pod b/crypto/openssl/doc/internal/man3/OPTIONS.pod
index 90593ca46f6f..dbdd39a2ee64 100644
--- a/crypto/openssl/doc/internal/man3/OPTIONS.pod
+++ b/crypto/openssl/doc/internal/man3/OPTIONS.pod
@@ -1,343 +1,343 @@
=pod
=head1 NAME
OPTIONS, OPT_PAIR, OPT_COMMON, OPT_ERR, OPT_EOF, OPT_HELP,
opt_init, opt_progname, opt_appname, opt_getprog, opt_help,
opt_begin, opt_next, opt_flag, opt_arg, opt_unknown, opt_cipher,
opt_cipher_any, opt_cipher_silent, opt_md,
opt_int, opt_int_arg, opt_long, opt_ulong, opt_intmax, opt_uintmax,
opt_format, opt_isdir, opt_string, opt_pair,
opt_num_rest, opt_rest, opt_legacy_okay
- Option parsing for commands and tests
=head1 SYNOPSIS
#include "opt.h"
typedef struct { ... } OPTIONS;
typedef struct { ... } OPT_PAIR;
#define OPT_COMMON
#define OPT_ERR
#define OPT_EOF
#define OPT_HELP
char *opt_init(int argc, char **argv, const OPTIONS *o);
char *opt_progname(const char *argv0);
char *opt_appname(const char *argv0);
char *opt_getprog(void);
void opt_help(const OPTIONS *list);
void opt_begin(void);
int opt_next(void);
char *opt_flag(void);
char *opt_arg(void);
char *opt_unknown(void);
int opt_cipher(const char *name, EVP_CIPHER **cipherp);
int opt_cipher_any(const char *name, EVP_CIPHER **cipherp);
int opt_cipher_silent(const char *name, EVP_CIPHER **cipherp);
int opt_md(const char *name, EVP_MD **mdp);
int opt_int(const char *value, int *result);
int opt_int_arg(void);
int opt_long(const char *value, long *result);
int opt_ulong(const char *value, unsigned long *result);
int opt_intmax(const char *value, intmax_t *result);
int opt_uintmax(const char *value, uintmax_t *result);
int opt_format(const char *s, unsigned long flags, int *result);
int opt_isdir(const char *name);
int opt_string(const char *name, const char **options);
int opt_pair(const char *name, const OPT_PAIR* pairs, int *result);
int opt_num_rest(void);
char **opt_rest(void);
int opt_legacy_okay(void);
=head1 DESCRIPTION
The functions on this page provide a common set of option-parsing for
the OpenSSL command and the internal test programs.
It is intended to be used like the standard getopt(3) routine, except
that multi-character flag names are supported, and a variety of parsing
and other utility functions are also provided.
Programs that use this should make sure to set the appropriate C<-I>
flag.
These routines expect a global B<BIO> named B<bio_err> to point to
the equivalent of B<stderr>. This is already done in the OpenSSL
application.
=head2 Data Types
Each program should define, near the main() routine, an enumeration
that is the set of options the program accepts. For example:
typedef enum OPTION_choice {
OPT_COMMON,
OPT_YES, OPT_NAME, OPT_COUNT, OPT_OFILE,
...
} OPTION_CHOICE;
The first two lines must appear exactly as shown.
OPT_COMMON is a macro that expands to C<OPT_ERR = -1, OPT_EOF = 0, OPT_HELP>.
In addition to defining symbolic names for the constants that opt_next()
returns, it also helps guarantee that every command has a C<-help> option.
The third line is a sample
set of flags, and the closing C<typedef> name is used for error-checking
as discussed below.
By declaring the variable as an C<OPTION_CHOICE>, with the right warning
flags, the compiler could check that all specified options are handled.
The B<OPTIONS> C<typedef> specifies an option: what type of argument
it takes (if any), and an optional "help" string. It is a C<struct>
containing these fields:
const char *name;
int retval;
int valtype;
const char *helpstr;
The B<name> is the name of the option that the user would type. Options
are words prefaced with a minus sign. If the user uses two minus signs,
this is also accepted for compatibility with other GNU software. Some
names are special, and are described below.
The B<retval> is the value to return if the option is found. It should be
one of the choices in the enumeration above.
The B<valtype> defines what the option's parameter must be. It should
be chosen from the following set:
\0 No value
'-' No value
's' A text string
'/' A directory
'<' Name of file to open for input
'>' Name of file to open for output
'n' A signed number that fits in the C<int> type
'p' A positive number that fits in the C<int> type
'N' A nonnegative number that fits in the C<int> type
'M' A signed number that fits in the C<intmax_t> type
'U' An unsigned number that fits in the C<uintmax_t> type
'l' A signed number that fits in the C<long> type
'u' An unsigned number that fits in the C<unsigned long> type
'c' File in PEM, DER, or S/MIME format
'F' A file in PEM or DER format
'E' Like 'F' but also allows ENGINE
'f' Any file format
The B<helpstr> is what to display when the user uses the help option,
which should be C<"help">.
A program should declare its options right after the enumeration,
and should follow the ordering of the enumeration as this helps
readability and maintainability:
static OPTIONS my_options[] = {
{"help", OPT_HELP, '-', "Display this summary"},
{"yes", OPT_YES, '-', "Print an affirmative reply"},
{"count", OPT_COUNT, 'p', "Repeat count"},
{"output" OPT_OFILE, '>', "Output file; default is stdout"},
{NULL}
};
Note that the B<OPT_HELP> option is explicitly listed, and the list ends with
an entry of all-null's. The other two special options, B<OPT_ERR> and B<OPT_EOF>
should not appear in the array.
If the help string is too long to fit into one line, it may be continued
on multiple lines; each entry should use B<OPT_MORE_STR>, like this:
{"output" OPT_OFILE, '>', "Output file; default is stdout"},
{OPT_MORE_STR, 0, 0,
"This flag is not really needed on Unix systems"},
{OPT_MORE_STR, 0, 0,
- "(Unix and descendents for ths win!)"}
+ "(Unix and descendents for the win!)"}
Each subsequent line will be indented the correct amount.
By default, the help display will include a standard prolog:
Usage: PROGRAM [options]
Valid options are:
...detailed list of options...
Sometimes there are parameters that should appear in the synopsis.
Use B<OPT_HELP_STR> as the first entry in your array:
{OPT_HELP_STR, 1, '-', Usage: %s [options] [text...]\n"}
The B<retval> and B<valtype> are ignored, and the B<helpstr> should
follow the general construction as shown. The C<%s> will get the program
name.
If a command has a large set of options, it can be useful to break them
into sections. Use the macro B<OPT_SECTION> or B<OPT_SECTION_STR>
to indicate this. The two lines below are equivalent:
OPT_SECTION("Validation"),
{OPT_SECTION_STR, 1, '-', "Validation options:\n"},
In addition to providing help about options, you can provide a description
of the parameters a command takes. These should appear at the end of
the options and are indicated by using B<OPT_PARAM_STR> or the
B<OPT_PARAMETERS> macro:
OPT_PARAMETERS()
{OPT_PARAM_STR, 1, '-', "Parameters:\n"}
Every "option" after after this should contain the parameter and
the help string:
{"text", 0, 0, "Words to display (optional)"},
=head2 Functions
The opt_init() function takes the I<argc> and I<argv> arguments given to main()
and a pointer I<o> to the list of options. It returns the simple program
name, as defined by opt_progname().
The opt_progname() function takes the full pathname C<argv[0]> in its I<arg0>
parameter and returns
the simple short name of the executable, to be used for error messages and
the like.
The opt_appname() function takes in its I<argv0> parameter
the "application" name (such
as the specific command from L<openssl(1)> and appends it to the program
name. This function should only be called once.
The opt_getprog() function returns the value set by opt_appname().
The opt_help() function takes a list of option definitions and prints a
nicely-formatted output.
The opt_begin() function, which is called automatically by opt_init(),
can be used to reset the option parsing loop.
The opt_next() function is called, once opt_init() has been called,
in a loop to fetch each option in turn. It returns -1, or B<OPT_EOF> when the
end of arguments has been reached. This is typically done like this:
prog = opt_init(argc, argv, my_options);
while ((o = opt_next()) != OPT_EOF) {
switch (o) {
case OPT_EOF:
case OPT_ERR:
opthelp:
fprintf(stderr, "%s: Use -help for summary\n", prog);
exit(1);
case OPT_HELP:
opt_help(my_options);
exit(0);
...other options...
}
}
Within the option parsing loop, the following functions may be called.
The opt_flag() function returns the most recent option name
including the preceding C<->.
The opt_arg() function returns the option's argument value, if there is one.
The opt_unknown() function returns the unknown option.
In an option list, there can be at most one option with the empty string.
This is a "wildcard" or "unknown" option. For example, it allows an
option to be be taken as digest algorithm, like C<-sha1>. The function
opt_md() takes the specified I<name> and fills in the digest into I<mdp>.
The functions opt_cipher(), opt_cipher_any() and opt_cipher_silent()
each takes the specified I<name> and fills in the cipher into I<cipherp>.
The function opt_cipher() only accepts ciphers which are not
AEAD and are not using XTS mode. The functions opt_cipher_any() and
opt_cipher_silent() accept any cipher, the latter not emitting an error
if the cipher is not located.
There are a several useful functions for parsing numbers. These are
opt_int(), opt_long(), opt_ulong(), opt_intmax(), and opt_uintmax(). They all
take C<0x> to mean hexadecimal and C<0> to mean octal, and will do the
necessary range-checking. They return 1 if successful and fill in the
C<result> pointer with the value, or 0 on error. Note that opt_next()
will also do range-check on the argument if the appropriate B<valtype>
field is specified for the option. This means that error-checking inside
the C<switch> C<case> can often be elided.
The opt_int_arg() function is a convenience abbreviation to opt_int().
It parses and returns an integer, assuming its range has been checked before.
The opt_format() function takes a string value,
such as used with the B<-informat> or similar option, and fills
the value from the constants in F<fmt.h> file.
The opt_isdir() function returns 1 if the specified I<name> is
a directory, or 0 if not.
The opt_string() function checks that I<name> appears in the
NULL-terminated array of strings. It returns 1 if found,
or prints a diagnostic and returns 0 if not.
The opt_pair() function takes a list of I<pairs>, each of which
has a text name and an integer. The specified I<name> is
found on the list, it puts the index in I<*result>, and returns
1. If not found, it returns 0.
The following functions can be used after processing all the options.
The opt_num_rest() function returns what is left.
The opt_rest() function returns a pointer to the first non-option.
If there were no parameters, it will point to the NULL that is
at the end of the standard I<argv> array.
The opt_legacy_okay() function returns true if no options have been
specified that would preclude using legacy code paths. Currently,
the various provider options preclude legacy operation. This means,
for example, that specifying both B<-provider> and B<-engine> in the
same command line will not work as expected.
=head2 Common Options
There are a few groups of options that are common to many OpenSSL programs.
These are handled with sets of macros that define common option names
and common code to handle them. The categories are identified by a
letter:
V Validation
X Extended certificate
S TLS/SSL
R Random state
The B<OPT_x_ENUM> macro is used to define the numeration values, where B<x>
is one of the letters above. The B<OPT_x_OPTIONS> macro is used to
list the set of common options, and the B<OPT_x_CASES> is used in
the C<switch> statement.
The common options are used throughout the sources for the OpenSSL commands.
They are also used with common descriptions when generating the
manpages, in the file F<doc/perlvars.pm>, which follow a similar naming
convention.
=head1 RETURN VALUES
Detailed above.
=head1 EXAMPLES
The best examples can be found in sources for the commands in the F<apps>
directory of the source tree.
A notable exception is F<apps/cmp.c> which uses this API, but does
things very differently.
=head1 COPYRIGHT
-Copyright 2021 The OpenSSL Project Authors. All Rights Reserved.
+Copyright 2021-2024 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<https://www.openssl.org/source/license.html>.
=cut
diff --git a/crypto/openssl/doc/internal/man3/ossl_method_construct.pod b/crypto/openssl/doc/internal/man3/ossl_method_construct.pod
index 3683798b06b4..422d7a5b6850 100644
--- a/crypto/openssl/doc/internal/man3/ossl_method_construct.pod
+++ b/crypto/openssl/doc/internal/man3/ossl_method_construct.pod
@@ -1,158 +1,158 @@
=pod
=head1 NAME
OSSL_METHOD_CONSTRUCT_METHOD, ossl_method_construct
- generic method constructor
=head1 SYNOPSIS
#include "internal/core.h"
struct ossl_method_construct_method_st {
/* Get a temporary store */
void *(*get_tmp_store)(void *data);
/* Get an already existing method from a store */
void *(*get)(void *store, const OSSL_PROVIDER *prov, void *data);
/* Store a method in a store */
int (*put)(void *store, void *method, const OSSL_PROVIDER *prov,
const char *name, const char *propdef, void *data);
/* Construct a new method */
void *(*construct)(const OSSL_ALGORITHM *algodef, OSSL_PROVIDER *prov,
void *data);
/* Destruct a method */
void (*destruct)(void *method, void *data);
};
typedef struct ossl_method_construct_method OSSL_METHOD_CONSTRUCT_METHOD;
void *ossl_method_construct(OSSL_LIB_CTX *ctx, int operation_id,
OSSL_PROVIDER *prov, int force_cache,
OSSL_METHOD_CONSTRUCT_METHOD *mcm, void *mcm_data);
=head1 DESCRIPTION
All libcrypto subsystems that want to create their own methods based
on provider dispatch tables need to do so in exactly the same way.
ossl_method_construct() does this while leaving it to the subsystems
to define more precisely how the methods are created, stored, etc.
It's important to keep in mind that a method is identified by three things:
=over 4
=item The operation identity
=item The name of the algorithm
=item The properties associated with the algorithm implementation
=back
=head2 Functions
ossl_method_construct() creates a method by asking all available
providers for a dispatch table given an I<operation_id>, and then
calling the appropriate functions given by the subsystem specific
method creator through I<mcm> and the data in I<mcm_data> (which is
passed by ossl_method_construct()).
If I<prov> is not NULL, only that provider is considered, which is
useful in the case a method must be found in that particular
provider.
This function assumes that the subsystem method creator implements
reference counting and acts accordingly (i.e. it will call the
subsystem destruct() method to decrement the reference count when
appropriate).
=head2 Structures
A central part of constructing a subsystem specific method is to give
ossl_method_construct a set of functions, all in the
B<OSSL_METHOD_CONSTRUCT_METHOD> structure, which holds the following
function pointers:
=over 4
=item get_tmp_store()
Create a temporary method store in the scope of the library context I<ctx>.
This store is used to temporarily store methods for easier lookup, for
when the provider doesn't want its dispatch table stored in a longer
term cache.
=item get()
Look up an already existing method from a store by name.
The store may be given with I<store>.
NULL is a valid value and means that a subsystem default store
must be used.
This default store should be stored in the library context I<libctx>.
The method to be looked up should be identified with data found in I<data>
(which is the I<mcm_data> that was passed to ossl_construct_method()).
In other words, the ossl_method_construct() caller is entirely responsible
-for ensuring the necesssary data is made available.
+for ensuring the necessary data is made available.
Optionally, I<prov> may be given as a search criterion, to narrow down the
search of a method belonging to just one provider.
This function is expected to increment the resulting method's reference count.
=item put()
Places the I<method> created by the construct() function (see below)
in a store.
The store may be given with I<store>.
NULL is a valid value and means that a subsystem default store
must be used.
This default store should be stored in the library context I<libctx>.
The method should be associated with the given provider I<prov>,
I<name> and property definition I<propdef> as well as any
identification data given through I<data> (which is the I<mcm_data>
that was passed to ossl_construct_method()).
This function is expected to increment the I<method>'s reference count.
=item construct()
Constructs a subsystem method for the given I<name> and the given
dispatch table I<fns>.
The associated provider object I<prov> is passed as well, to make
it possible for the subsystem constructor to keep a reference, which
is recommended.
If such a reference is kept, the I<provider object> reference counter
must be incremented, using ossl_provider_up_ref().
This function is expected to set the method's reference count to 1.
=item destruct()
Decrement the I<method>'s reference count, and destruct it when
the reference count reaches zero.
=back
=head1 RETURN VALUES
ossl_method_construct() returns a constructed method on success, or
NULL on error.
=head1 HISTORY
This functionality was added to OpenSSL 3.0.
=head1 COPYRIGHT
-Copyright 2019-2021 The OpenSSL Project Authors. All Rights Reserved.
+Copyright 2019-2024 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<https://www.openssl.org/source/license.html>.
=cut
diff --git a/crypto/openssl/doc/internal/man3/ossl_provider_new.pod b/crypto/openssl/doc/internal/man3/ossl_provider_new.pod
index 8bd5594c484c..193472462b38 100644
--- a/crypto/openssl/doc/internal/man3/ossl_provider_new.pod
+++ b/crypto/openssl/doc/internal/man3/ossl_provider_new.pod
@@ -1,400 +1,400 @@
=pod
=head1 NAME
ossl_provider_find, ossl_provider_new, ossl_provider_up_ref,
ossl_provider_free,
ossl_provider_set_fallback, ossl_provider_set_module_path,
ossl_provider_add_parameter, ossl_provider_set_child, ossl_provider_get_parent,
ossl_provider_up_ref_parent, ossl_provider_free_parent,
ossl_provider_default_props_update, ossl_provider_get0_dispatch,
ossl_provider_init_as_child, ossl_provider_deinit_child,
ossl_provider_activate, ossl_provider_deactivate, ossl_provider_add_to_store,
ossl_provider_ctx,
ossl_provider_doall_activated,
ossl_provider_name, ossl_provider_dso,
ossl_provider_module_name, ossl_provider_module_path,
ossl_provider_libctx,
ossl_provider_teardown, ossl_provider_gettable_params,
ossl_provider_get_params,
ossl_provider_query_operation, ossl_provider_unquery_operation,
ossl_provider_set_operation_bit, ossl_provider_test_operation_bit,
ossl_provider_get_capabilities
- internal provider routines
=head1 SYNOPSIS
#include "internal/provider.h"
OSSL_PROVIDER *ossl_provider_find(OSSL_LIB_CTX *libctx, const char *name,
int noconfig);
OSSL_PROVIDER *ossl_provider_new(OSSL_LIB_CTX *libctx, const char *name,
ossl_provider_init_fn *init_function
int noconfig);
int ossl_provider_up_ref(OSSL_PROVIDER *prov);
void ossl_provider_free(OSSL_PROVIDER *prov);
/* Setters */
int ossl_provider_set_fallback(OSSL_PROVIDER *prov);
int ossl_provider_set_module_path(OSSL_PROVIDER *prov, const char *path);
int ossl_provider_add_parameter(OSSL_PROVIDER *prov, const char *name,
const char *value);
/* Child Providers */
int ossl_provider_set_child(OSSL_PROVIDER *prov,
const OSSL_CORE_HANDLE *handle);
const OSSL_CORE_HANDLE *ossl_provider_get_parent(OSSL_PROVIDER *prov);
int ossl_provider_up_ref_parent(OSSL_PROVIDER *prov, int activate);
int ossl_provider_free_parent(OSSL_PROVIDER *prov, int deactivate);
int ossl_provider_default_props_update(OSSL_LIB_CTX *libctx,
const char *props);
/*
* Activate the Provider
* If the Provider is a module, the module will be loaded
*/
int ossl_provider_activate(OSSL_PROVIDER *prov, int upcalls, int aschild);
int ossl_provider_deactivate(OSSL_PROVIDER *prov, int removechildren);
int ossl_provider_add_to_store(OSSL_PROVIDER *prov, OSSL_PROVIDER **actualprov,
int retain_fallbacks);
/* Return pointer to the provider's context */
void *ossl_provider_ctx(const OSSL_PROVIDER *prov);
const OSSL_DISPATCH *ossl_provider_get0_dispatch(const OSSL_PROVIDER *prov);
/* Iterate over all loaded providers */
int ossl_provider_doall_activated(OSSL_LIB_CTX *,
int (*cb)(OSSL_PROVIDER *provider,
void *cbdata),
void *cbdata);
/* Getters for other library functions */
const char *ossl_provider_name(OSSL_PROVIDER *prov);
const DSO *ossl_provider_dso(OSSL_PROVIDER *prov);
const char *ossl_provider_module_name(OSSL_PROVIDER *prov);
const char *ossl_provider_module_path(OSSL_PROVIDER *prov);
OSSL_LIB_CTX *ossl_provider_libctx(const OSSL_PROVIDER *prov);
/* Thin wrappers around calls to the provider */
void ossl_provider_teardown(const OSSL_PROVIDER *prov);
const OSSL_PARAM *ossl_provider_gettable_params(const OSSL_PROVIDER *prov);
int ossl_provider_get_params(const OSSL_PROVIDER *prov, OSSL_PARAM params[]);
int ossl_provider_get_capabilities(const OSSL_PROVIDER *prov,
const char *capability,
OSSL_CALLBACK *cb,
void *arg);
const OSSL_ALGORITHM *ossl_provider_query_operation(const OSSL_PROVIDER *prov,
int operation_id,
int *no_cache);
void ossl_provider_unquery_operation(const OSSL_PROVIDER *prov,
int operation_id,
const OSSL_ALGORITHM *algs);
int ossl_provider_set_operation_bit(OSSL_PROVIDER *provider, size_t bitnum);
int ossl_provider_test_operation_bit(OSSL_PROVIDER *provider, size_t bitnum,
int *result);
int ossl_provider_init_as_child(OSSL_LIB_CTX *ctx,
const OSSL_CORE_HANDLE *handle,
const OSSL_DISPATCH *in);
void ossl_provider_deinit_child(OSSL_LIB_CTX *ctx);
=head1 DESCRIPTION
I<OSSL_PROVIDER> is a type that holds all the necessary information
to handle a provider, regardless of if it's built in to the
application or the OpenSSL libraries, or if it's a loadable provider
module.
Instances of this type are commonly referred to as "provider objects".
A provider object is always stored in a set of provider objects
in the library context.
Provider objects are reference counted.
Provider objects are initially inactive, i.e. they are only recorded
in the store, but are not used.
They are activated with the first call to ossl_provider_activate(),
and are deactivated with the last call to ossl_provider_deactivate().
Activation affects a separate counter.
=head2 Functions
ossl_provider_find() finds an existing provider object in the provider
object store by I<name>.
The config file will be automatically loaded unless I<noconfig> is set.
Typically I<noconfig> should be 0.
We set I<noconfig> to 1 only when calling these functions while processing a
config file in order to avoid recursively attempting to load the file.
The provider object it finds has its reference count incremented.
ossl_provider_new() creates a new provider object named I<name> and
stores it in the provider object store, unless there already is one
there with the same name.
If there already is one with the same name, it's returned with its
reference count incremented.
The config file will be automatically loaded unless I<noconfig> is set.
Typically I<noconfig> should be 0.
We set I<noconfig> to 1 only when calling these functions while processing a
config file in order to avoid recursively attempting to load the file.
The reference count of a newly created provider object will always
be 2; one for being added to the store, and one for the returned
reference.
If I<init_function> is NULL, the provider is assumed to be a
dynamically loadable module, with the symbol B<OSSL_provider_init> as
its initialisation function.
If I<init_function> isn't NULL, the provider is assumed to be built
in, with I<init_function> being the pointer to its initialisation
function.
For further description of the initialisation function, see the
description of ossl_provider_activate() below.
ossl_provider_up_ref() increments the provider object I<prov>'s
reference count.
ossl_provider_free() decrements the provider object I<prov>'s
reference count; when it drops to zero, the provider object is assumed
to have fallen out of use and will be deinitialized (its I<teardown>
function is called), and the associated module will be unloaded if one
was loaded, and I<prov> itself will be freed.
ossl_provider_set_fallback() marks an available provider I<prov> as
fallback.
Note that after this call, the provider object pointer that was
used can simply be dropped, but not freed.
ossl_provider_set_module_path() sets the module path to load the
provider module given the provider object I<prov>.
This will be used in preference to automatically trying to figure out
the path from the provider name and the default module directory (more
on this in L</NOTES>).
ossl_provider_libctx() returns the library context the given
provider I<prov> is registered in.
ossl_provider_add_parameter() adds a global parameter for the provider
to retrieve as it sees fit.
The parameters are a combination of I<name> and I<value>, and the
provider will use the name to find the value it wants.
Only text parameters can be given, and it's up to the provider to
interpret them.
ossl_provider_set_child() marks this provider as a child of a provider in the
parent library context. I<handle> is the B<OSSL_CORE_HANDLE> object passed to
the provider's B<OSSL_provider_init> function.
ossl_provider_get_parent() obtains the handle on the parent provider.
ossl_provider_up_ref_parent() increases the reference count on the parent
provider. If I<activate> is nonzero then the parent provider is also activated.
ossl_provider_free_parent() decreases the reference count on the parent
provider. If I<deactivate> is nonzero then the parent provider is also
deactivated.
ossl_provider_default_props_update() is responsible for informing any child
providers of an update to the default properties. The new properties are
supplied in the I<props> string.
ossl_provider_activate() "activates" the provider for the given
provider object I<prov> by incrementing its activation count, flagging
it as activated, and initializing it if it isn't already initialized.
Initializing means one of the following:
=over 4
=item *
If an initialization function was given with ossl_provider_new(), that
function will get called.
=item *
If no initialization function was given with ossl_provider_new(), a
loadable module with the I<name> that was given to ossl_provider_new()
will be located and loaded, then the symbol B<OSSL_provider_init> will
be located in that module, and called.
=back
If I<upcalls> is nonzero then, if this is a child provider, upcalls to the
parent libctx will be made to inform it of an up-ref. If I<aschild> is nonzero
then the provider will only be activated if it is a child provider. Otherwise
no action is taken and ossl_provider_activate() returns success.
ossl_provider_deactivate() "deactivates" the provider for the given
provider object I<prov> by decrementing its activation count. When
that count reaches zero, the activation flag is cleared. If the
I<removechildren> parameter is 0 then no attempt is made to remove any
associated child providers.
ossl_provider_add_to_store() adds the provider I<prov> to the provider store and
makes it available to other threads. This will prevent future automatic loading
of fallback providers, unless I<retain_fallbacks> is true. If a provider of the
same name already exists in the store then it is not added but this function
still returns success. On success the I<actualprov> value is populated with a
pointer to the provider of the given name that is now in the store. The
reference passed in the I<prov> argument is consumed by this function. A
reference to the provider that should be used is passed back in the
I<actualprov> argument.
ossl_provider_ctx() returns a context created by the provider.
Outside of the provider, it's completely opaque, but it needs to be
passed back to some of the provider functions.
ossl_provider_get0_dispatch() returns the dispatch table that the provider
initially returned in the I<out> parameter of its B<OSSL_provider_init>
function.
ossl_provider_doall_activated() iterates over all the currently
"activated" providers, and calls I<cb> for each of them.
If no providers have been "activated" yet, it tries to activate all
available fallback providers before iterating over them.
ossl_provider_name() returns the name that was given with
ossl_provider_new().
ossl_provider_dso() returns a reference to the module, for providers
that come in the form of loadable modules.
ossl_provider_module_name() returns the filename of the module, for
providers that come in the form of loadable modules.
ossl_provider_module_path() returns the full path of the module file,
for providers that come in the form of loadable modules.
ossl_provider_teardown() calls the provider's I<teardown> function, if
the provider has one.
ossl_provider_gettable_params() calls the provider's I<gettable_params>
function, if the provider has one.
It should return an array of I<OSSL_PARAM> to describe all the
parameters that the provider has for the provider object.
ossl_provider_get_params() calls the provider's parameter request
responder.
It should treat the given I<OSSL_PARAM> array as described in
L<OSSL_PARAM(3)>.
ossl_provider_get_capabilities() calls the provider's I<get_capabilities> function,
if the provider has one. It provides the name of the I<capability> and a
callback I<cb> parameter to call for each capability that has a matching name in
the provider. The callback gets passed OSSL_PARAM details about the capability as
well as the caller supplied argument I<arg>.
ossl_provider_query_operation() calls the provider's
I<query_operation> function, if the provider has one.
It should return an array of I<OSSL_ALGORITHM> for the given
I<operation_id>.
ossl_provider_unquery_operation() informs the provider that the result of
ossl_provider_query_operation() is no longer going to be directly accessed and
that all relevant information has been copied.
ossl_provider_set_operation_bit() registers a 1 for operation I<bitnum>
in a bitstring that's internal to I<provider>.
ossl_provider_test_operation_bit() checks if the bit operation I<bitnum>
is set (1) or not (0) in the internal I<provider> bitstring, and sets
-I<*result> to 1 or 0 accorddingly.
+I<*result> to 1 or 0 accordingly.
ossl_provider_init_as_child() stores in the library context I<ctx> references to
the necessary upcalls for managing child providers. The I<handle> and I<in>
parameters are the B<OSSL_CORE_HANDLE> and L<OSSL_DISPATCH(3)> pointers that were
passed to the provider's B<OSSL_provider_init> function.
ossl_provider_deinit_child() deregisters callbacks from the parent library
context about provider creation or removal events for the child library context
I<ctx>. Must only be called if I<ctx> is a child library context.
=head1 NOTES
Locating a provider module happens as follows:
=over 4
=item 1.
If a path was given with ossl_provider_set_module_path(), use that as
module path.
Otherwise, use the provider object's name as module path, with
platform specific standard extensions added.
=item 2.
If the environment variable B<OPENSSL_MODULES> is defined, assume its
value is a directory specification and merge it with the module path.
Otherwise, merge the value of the OpenSSL built in macro B<MODULESDIR>
with the module path.
=back
When this process is done, the result is used when trying to load the
provider module.
The command C<openssl version -m> can be used to find out the value
of the built in macro B<MODULESDIR>.
=head1 RETURN VALUES
ossl_provider_find() and ossl_provider_new() return a pointer to a
provider object (I<OSSL_PROVIDER>) on success, or NULL on error.
ossl_provider_up_ref() returns the value of the reference count after
it has been incremented.
ossl_provider_free() doesn't return any value.
ossl_provider_doall_activated() returns 1 if the callback was called for all
activated providers. A return value of 0 means that the callback was not
called for any activated providers.
ossl_provider_set_module_path(), ossl_provider_set_fallback(),
ossl_provider_activate(), ossl_provider_activate_leave_fallbacks() and
ossl_provider_deactivate(), ossl_provider_add_to_store(),
ossl_provider_default_props_update() return 1 on success, or 0 on error.
ossl_provider_name(), ossl_provider_dso(),
ossl_provider_module_name(), and ossl_provider_module_path() return a
pointer to their respective data if it's available, otherwise NULL
is returned.
ossl_provider_libctx() return a pointer to the library context.
This may be NULL, and is perfectly valid, as it denotes the default
global library context.
ossl_provider_teardown() doesn't return any value.
ossl_provider_gettable_params() returns a pointer to a constant
I<OSSL_PARAM> array if this function is available in the provider,
otherwise NULL.
ossl_provider_get_params() returns 1 on success, or 0 on error.
If this function isn't available in the provider, 0 is returned.
ossl_provider_set_operation_bit() and ossl_provider_test_operation_bit()
return 1 on success, or 0 on error.
ossl_provider_get_capabilities() returns 1 on success, or 0 on error.
If this function isn't available in the provider or the provider does not
support the requested capability then 0 is returned.
=head1 SEE ALSO
L<OSSL_PROVIDER(3)>, L<provider(7)>, L<openssl(1)>
=head1 HISTORY
The functions described here were all added in OpenSSL 3.0.
=head1 COPYRIGHT
-Copyright 2019-2022 The OpenSSL Project Authors. All Rights Reserved.
+Copyright 2019-2024 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<https://www.openssl.org/source/license.html>.
=cut
diff --git a/crypto/openssl/doc/internal/man3/ossl_random_add_conf_module.pod b/crypto/openssl/doc/internal/man3/ossl_random_add_conf_module.pod
index 6d4f5810dcdd..a3c1285fe01b 100644
--- a/crypto/openssl/doc/internal/man3/ossl_random_add_conf_module.pod
+++ b/crypto/openssl/doc/internal/man3/ossl_random_add_conf_module.pod
@@ -1,42 +1,42 @@
=pod
=head1 NAME
ossl_random_add_conf_module - internal random configuration module
=head1 SYNOPSIS
#include "crypto/rand.h"
/* Configuration */
void ossl_random_add_conf_module(void);
=head1 DESCRIPTION
ossl_random_add_conf_module() adds the random configuration module
for providers.
-This allows the type and parameters of the stardard setup of random number
+This allows the type and parameters of the standard setup of random number
generators to be configured with an OpenSSL L<config(5)> file.
=head1 RETURN VALUES
ossl_random_add_conf_module() doesn't return any value.
=head1 SEE ALSO
L<OSSL_PROVIDER(3)>, L<ossl_provider_new(3)>, L<provider-rand(7)>
=head1 HISTORY
The functions described here were all added in OpenSSL 3.0.
=head1 COPYRIGHT
-Copyright 2020 The OpenSSL Project Authors. All Rights Reserved.
+Copyright 2020-2024 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<https://www.openssl.org/source/license.html>.
=cut
diff --git a/crypto/openssl/doc/internal/man7/EVP_PKEY.pod b/crypto/openssl/doc/internal/man7/EVP_PKEY.pod
index cc738b9c28eb..3dc10fa4104c 100644
--- a/crypto/openssl/doc/internal/man7/EVP_PKEY.pod
+++ b/crypto/openssl/doc/internal/man7/EVP_PKEY.pod
@@ -1,212 +1,212 @@
=pod
=head1 NAME
EVP_PKEY - an internal description
=head1 SYNOPSIS
#include "crypto/evp.h"
typedef struct evp_pkey_st EVP_PKEY;
=head1 DESCRIPTION
I<This is not a complete description yet>
B<EVP_PKEY> is a complex type that's essentially a container for
private/public key pairs, but has had other uses as well.
=for comment "uses" could as well be "abuses"...
-The private/public key pair that an B<EVP_PKEY> contains is refered to
+The private/public key pair that an B<EVP_PKEY> contains is referred to
as its "internal key" or "origin" (the reason for "origin" is
explained further down, in L</Export cache for provider operations>),
and it can take one of the following forms:
=over 4
=item legacy origin
This is the form that an B<EVP_PKEY> in OpenSSL prior to 3.0 had. The
internal key in the B<EVP_PKEY> is a pointer to the low-level key
types, such as B<RSA>, B<DSA> and B<EC>, or an engine driven
structure, and is governed by an associated L<EVP_PKEY_METHOD(3)> and
an L<EVP_PKEY_ASN1_METHOD(3)>.
The functions available through those two method structures get full
access to the B<EVP_PKEY> and therefore have a lot of freedom to
modify whatever they want. This also means that an B<EVP_PKEY> is a
shared structure between libcrypto and any ENGINE that serves such
methods.
=item provider-native origin
This is a new form in OpenSSL 3.0, which permits providers to hold the
key data (see L<provider-keymgmt(7)>). The internal key in the
B<EVP_PKEY> is a pointer to that key data held by the provider, and
is governed by an associated L<EVP_KEYMGMT(3)> method structure.
The functions available through the L<EVP_KEYMGMT(3)> have no access
to the B<EVP_PKEY>, and can therefore not make any direct changes.
Similarly, the key data that the B<EVP_PKEY> points at is only known
to the functions pointed at in the L<EVP_KEYMGMT(3)>.
=back
These two forms can never co-exist in the same B<EVP_PKEY>, the main
reason being that having both at the same time will create problems
with synchronising between the two forms, and potentially make it
confusing which one of the two is the origin.
=head2 Key mutability
The B<EVP_PKEY> internal keys are mutable.
This is especially visible with internal legacy keys, since they can
be extracted with functions like L<EVP_PKEY_get0_RSA(3)> and then
modified at will with functions like L<RSA_set0_key(3)>. Note that if the
internal key is a provider key then the return value from functions such as
L<EVP_PKEY_get0_RSA(3)> is a cached copy of the key. Changes to the cached
copy are not reflected back in the provider key.
Internal provider native keys are also possible to be modified, if the
associated L<EVP_KEYMGMT(3)> implementation allows it. This is done
with L<EVP_PKEY_set_params(3)> and its specialised derivatives. The
OpenSSL providers allow it for the following:
=over 4
=item DH, EC, X25519, X448:
It's possible to set the encoded public key. This is supported in
particular through L<EVP_PKEY_set1_encoded_public_key(3)>.
=item EC:
It's possible to flip the ECDH cofactor mode.
=back
Every time the B<EVP_PKEY> internal key mutates, an internal dirty
count is incremented. The need for a dirty count is explained further
in L</Export cache for provider operations>.
For provider native origin keys, this doesn't require any help from
the L<EVP_KEYMGMT(3)>, the dirty count is maintained in the B<EVP_PKEY>
itself, and is incremented every time L<EVP_PKEY_set_params(3)> or its
specialised derivatives are called.
For legacy origin keys, this requires the associated
L<EVP_PKEY_ASN1_METHOD(3)> to implement the dirty_cnt() function. All
of OpenSSL's built-in L<EVP_PKEY_ASN1_METHOD(3)> implement this
function.
=head2 Export cache for provider operations
OpenSSL 3.0 can handle operations such as signing, encrypting, etc in
diverse providers, potentially others than the provider of the
L<EVP_KEYMGMT(3)>. Two providers, possibly from different vendors,
can't be expected to share internal key structures. There are
therefore instances where key data will need to be exported to the
provider that is going to perform the operation (this also implies
that every provider that implements a key pair based operation must
also implement an L<EVP_KEYMGMT(3)>).
For performance reasons, libcrypto tries to minimize the need to
perform such an export, so it maintains a cache of such exports in the
B<EVP_PKEY>. Each cache entry has two items, a pointer to the
provider side key data and the associated L<EVP_KEYMGMT(3)>.
I<This cache is often referred to as the "operation key cache", and
the key data that the cached keys came from is the "origin", and since
there are two forms of the latter, we have the "legacy origin" and the
"provider native origin".>
The export to the operation key cache can be performed independent of
what form the origin has.
For a legacy origin, this requires that the associated
L<EVP_PKEY_ASN1_METHOD(3)> implements the functions export_to() and
dirty_cnt().
For a provider native origin, this requires that the associated
L<EVP_KEYMGMT(3)> implements the OSSL_FUNC_keymgmt_export() function
(see L<provider-keymgmt(7)>).
In all cases, the receiving L<EVP_KEYMGMT(3)> (the one associated with
the exported key data) must implement OSSL_FUNC_keymgmt_import().
If such caching isn't supported, the operations that can be performed
with that key are limited to the same backend as the origin key
(ENGINE for legacy origin keys, provider for provider side origin
keys).
=head3 Exporting implementation details
Exporting a key to the operation cache involves the following:
=over 4
=item 1.
Check if the dirty count for the internal origin key has changed since
the previous time. This is done by comparing it with a copy of the
dirty count, which is maintained by the export function.
If the dirty count has changed, the export cache is cleared.
=item 2.
Check if there's an entry in the export cache with the same
L<EVP_KEYMGMT(3)> that's the same provider that an export is to be
made to (which is the provider that's going to perform an operation
for which the current B<EVP_PKEY> is going to be used).
If such an entry is found, nothing more is done, the key data and
L<EVP_KEYMGMT(3)> found in that export cache entry will be used for
the operation to be performed.
=item 3.
Export the internal origin key to the provider, using the appropriate
method.
For legacy origin keys, that's done with the help of the
L<EVP_PKEY_ASN1_METHOD(3)> export_to() function.
For provider native origin keys, that's done by retrieving the key
data in L<OSSL_PARAM(3)> form from the origin keys, using the
OSSL_FUNC_keymgmt_export() functions of the associated
L<EVP_KEYMGMT(3)>, and sending that data to the L<EVP_KEYMGMT(3)> of
the provider that's to perform the operation, using its
OSSL_FUNC_keymgmt_import() function.
=back
=head2 Changing a key origin
It is never possible to change the origin of a key. An B<EVP_PKEY> with a legacy
origin will I<never> be upgraded to become an B<EVP_PKEY> with a provider
native origin. Instead, we have the operation cache as described above, that
takes care of the needs of the diverse operation the application may want to
perform.
Similarly an B<EVP_PKEY> with a provider native origin, will I<never> be
I<transformed> into an B<EVP_PKEY> with a legacy origin. Instead we may have a
cached copy of the provider key in legacy form. Once the cached copy is created
it is never updated. Changes made to the provider key are not reflected back in
the cached legacy copy. Similarly changes made to the cached legacy copy are not
reflected back in the provider key.
=head1 SEE ALSO
L<provider-keymgmt(7)>
=head1 COPYRIGHT
-Copyright 2020-2021 The OpenSSL Project Authors. All Rights Reserved.
+Copyright 2020-2024 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<https://www.openssl.org/source/license.html>.
=cut
diff --git a/crypto/openssl/doc/man1/openssl-crl.pod.in b/crypto/openssl/doc/man1/openssl-crl.pod.in
index 7e15f6445a6f..5ace18f5807f 100644
--- a/crypto/openssl/doc/man1/openssl-crl.pod.in
+++ b/crypto/openssl/doc/man1/openssl-crl.pod.in
@@ -1,172 +1,175 @@
=pod
{- OpenSSL::safe::output_do_not_edit_headers(); -}
=head1 NAME
openssl-crl - CRL command
=head1 SYNOPSIS
B<openssl> B<crl>
[B<-help>]
[B<-inform> B<DER>|B<PEM>]
[B<-outform> B<DER>|B<PEM>]
[B<-key> I<filename>]
[B<-keyform> B<DER>|B<PEM>|B<P12>]
[B<-dateopt>]
[B<-text>]
[B<-in> I<filename>]
[B<-out> I<filename>]
[B<-gendelta> I<filename>]
[B<-badsig>]
[B<-verify>]
[B<-noout>]
[B<-hash>]
[B<-hash_old>]
[B<-fingerprint>]
[B<-crlnumber>]
[B<-issuer>]
[B<-lastupdate>]
[B<-nextupdate>]
{- $OpenSSL::safe::opt_name_synopsis -}
{- $OpenSSL::safe::opt_trust_synopsis -}
{- $OpenSSL::safe::opt_provider_synopsis -}
=head1 DESCRIPTION
This command processes CRL files in DER or PEM format.
=head1 OPTIONS
=over 4
=item B<-help>
Print out a usage message.
=item B<-inform> B<DER>|B<PEM>
The CRL input format; unspecified by default.
See L<openssl-format-options(1)> for details.
=item B<-outform> B<DER>|B<PEM>
The CRL output format; the default is B<PEM>.
See L<openssl-format-options(1)> for details.
=item B<-key> I<filename>
The private key to be used to sign the CRL.
=item B<-keyform> B<DER>|B<PEM>|B<P12>
The format of the private key file; unspecified by default.
See L<openssl-format-options(1)> for details.
=item B<-in> I<filename>
This specifies the input filename to read from or standard input if this
option is not specified.
=item B<-out> I<filename>
Specifies the output filename to write to or standard output by
default.
=item B<-gendelta> I<filename>
Output a comparison of the main CRL and the one specified here.
=item B<-badsig>
Corrupt the signature before writing it; this can be useful
for testing.
=item B<-dateopt>
Specify the date output format. Values are: rfc_822 and iso_8601.
Defaults to rfc_822.
=item B<-text>
Print out the CRL in text form.
=item B<-verify>
Verify the signature in the CRL.
+This option is implicitly enabled if any of B<-CApath>, B<-CAfile>
+or B<-CAstore> is specified.
+
=item B<-noout>
Don't output the encoded version of the CRL.
=item B<-fingerprint>
Output the fingerprint of the CRL.
=item B<-crlnumber>
Output the number of the CRL.
=item B<-hash>
Output a hash of the issuer name. This can be use to lookup CRLs in
a directory by issuer name.
=item B<-hash_old>
Outputs the "hash" of the CRL issuer name using the older algorithm
as used by OpenSSL before version 1.0.0.
=item B<-issuer>
Output the issuer name.
=item B<-lastupdate>
Output the lastUpdate field.
=item B<-nextupdate>
Output the nextUpdate field.
{- $OpenSSL::safe::opt_name_item -}
{- $OpenSSL::safe::opt_trust_item -}
{- $OpenSSL::safe::opt_provider_item -}
=back
=head1 EXAMPLES
Convert a CRL file from PEM to DER:
openssl crl -in crl.pem -outform DER -out crl.der
Output the text form of a DER encoded certificate:
openssl crl -in crl.der -text -noout
=head1 BUGS
Ideally it should be possible to create a CRL using appropriate options
and files too.
=head1 SEE ALSO
L<openssl(1)>,
L<openssl-crl2pkcs7(1)>,
L<openssl-ca(1)>,
L<openssl-x509(1)>,
L<ossl_store-file(7)>
=head1 COPYRIGHT
-Copyright 2000-2021 The OpenSSL Project Authors. All Rights Reserved.
+Copyright 2000-2024 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<https://www.openssl.org/source/license.html>.
=cut
diff --git a/crypto/openssl/doc/man1/openssl-mac.pod.in b/crypto/openssl/doc/man1/openssl-mac.pod.in
index 563974799109..5ed979697381 100644
--- a/crypto/openssl/doc/man1/openssl-mac.pod.in
+++ b/crypto/openssl/doc/man1/openssl-mac.pod.in
@@ -1,175 +1,180 @@
=pod
{- OpenSSL::safe::output_do_not_edit_headers(); -}
=head1 NAME
openssl-mac - perform Message Authentication Code operations
=head1 SYNOPSIS
B<openssl mac>
[B<-help>]
[B<-cipher>]
[B<-digest>]
[B<-macopt>]
[B<-in> I<filename>]
[B<-out> I<filename>]
[B<-binary>]
{- $OpenSSL::safe::opt_provider_synopsis -}
I<mac_name>
=head1 DESCRIPTION
The message authentication code functions output the MAC of a supplied input
file.
=head1 OPTIONS
=over 4
=item B<-help>
Print a usage message.
=item B<-in> I<filename>
Input filename to calculate a MAC for, or standard input by default.
Standard input is used if the filename is '-'.
Files and standard input are expected to be in binary format.
=item B<-out> I<filename>
Filename to output to, or standard output by default.
=item B<-binary>
Output the MAC in binary form. Uses hexadecimal text format if not specified.
=item B<-cipher> I<name>
Used by CMAC and GMAC to specify the cipher algorithm.
For CMAC it must be one of AES-128-CBC, AES-192-CBC, AES-256-CBC or
DES-EDE3-CBC.
For GMAC it should be a GCM mode cipher e.g. AES-128-GCM.
=item B<-digest> I<name>
Used by HMAC as an alphanumeric string (use if the key contains printable
characters only).
The string length must conform to any restrictions of the MAC algorithm.
To see the list of supported digests, use C<openssl list -digest-commands>.
=item B<-macopt> I<nm>:I<v>
Passes options to the MAC algorithm.
A comprehensive list of controls can be found in the EVP_MAC implementation
documentation.
Common parameter names used by EVP_MAC_CTX_get_params() are:
=over 4
=item B<key:>I<string>
Specifies the MAC key as an alphanumeric string (use if the key contains
printable characters only).
The string length must conform to any restrictions of the MAC algorithm.
A key must be specified for every MAC algorithm.
=item B<hexkey:>I<string>
Specifies the MAC key in hexadecimal form (two hex digits per byte).
The key length must conform to any restrictions of the MAC algorithm.
A key must be specified for every MAC algorithm.
=item B<iv:>I<string>
Used by GMAC to specify an IV as an alphanumeric string (use if the IV contains
printable characters only).
=item B<hexiv:>I<string>
Used by GMAC to specify an IV in hexadecimal form (two hex digits per byte).
=item B<size:>I<int>
Used by KMAC128 or KMAC256 to specify an output length.
The default sizes are 32 or 64 bytes respectively.
=item B<custom:>I<string>
Used by KMAC128 or KMAC256 to specify a customization string.
The default is the empty string "".
=item B<digest:>I<string>
This option is identical to the B<-digest> option.
=item B<cipher:>I<string>
This option is identical to the B<-cipher> option.
=back
{- $OpenSSL::safe::opt_provider_item -}
=item I<mac_name>
Specifies the name of a supported MAC algorithm which will be used.
To see the list of supported MAC's use the command C<openssl list
-mac-algorithms>.
=back
=head1 EXAMPLES
-To create a hex-encoded HMAC-SHA1 MAC of a file and write to stdout: \
+To create a hex-encoded HMAC-SHA1 MAC of a file and write to stdout:
+
openssl mac -digest SHA1 \
-macopt hexkey:000102030405060708090A0B0C0D0E0F10111213 \
-in msg.bin HMAC
-To create a SipHash MAC from a file with a binary file output: \
+To create a SipHash MAC from a file with a binary file output:
+
openssl mac -macopt hexkey:000102030405060708090A0B0C0D0E0F \
-in msg.bin -out out.bin -binary SipHash
-To create a hex-encoded CMAC-AES-128-CBC MAC from a file:\
+To create a hex-encoded CMAC-AES-128-CBC MAC from a file:
+
openssl mac -cipher AES-128-CBC \
-macopt hexkey:77A77FAF290C1FA30C683DF16BA7A77B \
-in msg.bin CMAC
To create a hex-encoded KMAC128 MAC from a file with a Customisation String
-'Tag' and output length of 16: \
+'Tag' and output length of 16:
+
openssl mac -macopt custom:Tag -macopt hexkey:40414243444546 \
-macopt size:16 -in msg.bin KMAC128
-To create a hex-encoded GMAC-AES-128-GCM with a IV from a file: \
+To create a hex-encoded GMAC-AES-128-GCM with a IV from a file:
+
openssl mac -cipher AES-128-GCM -macopt hexiv:E0E00F19FED7BA0136A797F3 \
-macopt hexkey:77A77FAF290C1FA30C683DF16BA7A77B -in msg.bin GMAC
=head1 NOTES
The MAC mechanisms that are available will depend on the options
used when building OpenSSL.
Use C<openssl list -mac-algorithms> to list them.
=head1 SEE ALSO
L<openssl(1)>,
L<EVP_MAC(3)>,
L<EVP_MAC-CMAC(7)>,
L<EVP_MAC-GMAC(7)>,
L<EVP_MAC-HMAC(7)>,
L<EVP_MAC-KMAC(7)>,
L<EVP_MAC-Siphash(7)>,
L<EVP_MAC-Poly1305(7)>
=head1 COPYRIGHT
-Copyright 2018-2022 The OpenSSL Project Authors. All Rights Reserved.
+Copyright 2018-2024 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<https://www.openssl.org/source/license.html>.
=cut
diff --git a/crypto/openssl/doc/man1/openssl-req.pod.in b/crypto/openssl/doc/man1/openssl-req.pod.in
index 31fd71418773..a56f548de8ee 100644
--- a/crypto/openssl/doc/man1/openssl-req.pod.in
+++ b/crypto/openssl/doc/man1/openssl-req.pod.in
@@ -1,775 +1,788 @@
=pod
{- OpenSSL::safe::output_do_not_edit_headers(); -}
=head1 NAME
openssl-req - PKCS#10 certificate request and certificate generating command
=head1 SYNOPSIS
B<openssl> B<req>
[B<-help>]
[B<-inform> B<DER>|B<PEM>]
[B<-outform> B<DER>|B<PEM>]
[B<-in> I<filename>]
[B<-passin> I<arg>]
[B<-out> I<filename>]
[B<-passout> I<arg>]
[B<-text>]
[B<-pubkey>]
[B<-noout>]
[B<-verify>]
[B<-modulus>]
[B<-new>]
[B<-newkey> I<arg>]
[B<-pkeyopt> I<opt>:I<value>]
[B<-noenc>]
[B<-nodes>]
[B<-key> I<filename>|I<uri>]
[B<-keyform> B<DER>|B<PEM>|B<P12>|B<ENGINE>]
[B<-keyout> I<filename>]
[B<-keygen_engine> I<id>]
[B<-I<digest>>]
[B<-config> I<filename>]
[B<-section> I<name>]
[B<-x509>]
[B<-CA> I<filename>|I<uri>]
[B<-CAkey> I<filename>|I<uri>]
[B<-days> I<n>]
[B<-set_serial> I<n>]
[B<-newhdr>]
[B<-copy_extensions> I<arg>]
[B<-addext> I<ext>]
[B<-extensions> I<section>]
[B<-reqexts> I<section>]
[B<-precert>]
[B<-utf8>]
[B<-reqopt>]
[B<-subject>]
[B<-subj> I<arg>]
[B<-multivalue-rdn>]
[B<-sigopt> I<nm>:I<v>]
[B<-vfyopt> I<nm>:I<v>]
[B<-batch>]
[B<-verbose>]
{- $OpenSSL::safe::opt_name_synopsis -}
{- $OpenSSL::safe::opt_r_synopsis -}
{- $OpenSSL::safe::opt_engine_synopsis -}{- $OpenSSL::safe::opt_provider_synopsis -}
=head1 DESCRIPTION
This command primarily creates and processes certificate requests (CSRs)
in PKCS#10 format. It can additionally create self-signed certificates
for use as root CAs for example.
=head1 OPTIONS
=over 4
=item B<-help>
Print out a usage message.
=item B<-inform> B<DER>|B<PEM>, B<-outform> B<DER>|B<PEM>
The input and output formats; unspecified by default.
See L<openssl-format-options(1)> for details.
The data is a PKCS#10 object.
=item B<-in> I<filename>
This specifies the input filename to read a request from.
This defaults to standard input unless B<-x509> or B<-CA> is specified.
A request is only read if the creation options
(B<-new> or B<-newkey> or B<-precert>) are not specified.
=item B<-sigopt> I<nm>:I<v>
Pass options to the signature algorithm during sign operations.
Names and values of these options are algorithm-specific.
=item B<-vfyopt> I<nm>:I<v>
Pass options to the signature algorithm during verify operations.
Names and values of these options are algorithm-specific.
=begin comment
Maybe it would be preferable to only have -opts instead of -sigopt and
-vfyopt? They are both present here to be compatible with L<openssl-ca(1)>,
which supports both options for good reasons.
=end comment
=item B<-passin> I<arg>
The password source for private key and certificate input.
For more information about the format of B<arg>
see L<openssl-passphrase-options(1)>.
=item B<-passout> I<arg>
The password source for the output file.
For more information about the format of B<arg>
see L<openssl-passphrase-options(1)>.
=item B<-out> I<filename>
This specifies the output filename to write to or standard output by default.
=item B<-text>
Prints out the certificate request in text form.
=item B<-subject>
Prints out the certificate request subject
(or certificate subject if B<-x509> is in use).
=item B<-pubkey>
Prints out the public key.
=item B<-noout>
This option prevents output of the encoded version of the certificate request.
=item B<-modulus>
Prints out the value of the modulus of the public key contained in the request.
=item B<-verify>
Verifies the self-signature on the request.
=item B<-new>
This option generates a new certificate request. It will prompt
the user for the relevant field values. The actual fields
prompted for and their maximum and minimum sizes are specified
in the configuration file and any requested extensions.
If the B<-key> option is not given it will generate a new private key
using information specified in the configuration file or given with
the B<-newkey> and B<-pkeyopt> options,
else by default an RSA key with 2048 bits length.
=item B<-newkey> I<arg>
This option is used to generate a new private key unless B<-key> is given.
It is subsequently used as if it was given using the B<-key> option.
This option implies the B<-new> flag to create a new certificate request
or a new certificate in case B<-x509> is given.
The argument takes one of several forms.
[B<rsa:>]I<nbits> generates an RSA key I<nbits> in size.
If I<nbits> is omitted, i.e., B<-newkey> B<rsa> is specified,
the default key size specified in the configuration file
with the B<default_bits> option is used if present, else 2048.
All other algorithms support the B<-newkey> I<algname>:I<file> form, where
I<file> is an algorithm parameter file, created with C<openssl genpkey -genparam>
or an X.509 certificate for a key with appropriate algorithm.
B<param:>I<file> generates a key using the parameter file or certificate
I<file>, the algorithm is determined by the parameters.
I<algname>[:I<file>] generates a key using the given algorithm I<algname>.
If a parameter file I<file> is given then the parameters specified there
are used, where the algorithm parameters must match I<algname>.
If algorithm parameters are not given,
any necessary parameters should be specified via the B<-pkeyopt> option.
B<dsa:>I<filename> generates a DSA key using the parameters
in the file I<filename>. B<ec:>I<filename> generates EC key (usable both with
ECDSA or ECDH algorithms), B<gost2001:>I<filename> generates GOST R
34.10-2001 key (requires B<gost> engine configured in the configuration
file). If just B<gost2001> is specified a parameter set should be
specified by B<-pkeyopt> I<paramset:X>
=item B<-pkeyopt> I<opt>:I<value>
Set the public key algorithm option I<opt> to I<value>. The precise set of
options supported depends on the public key algorithm used and its
implementation.
See L<openssl-genpkey(1)/KEY GENERATION OPTIONS> for more details.
=item B<-key> I<filename>|I<uri>
This option provides the private key for signing a new certificate or
certificate request.
Unless B<-in> is given, the corresponding public key is placed in
the new certificate or certificate request, resulting in a self-signature.
For certificate signing this option is overridden by the B<-CA> option.
This option also accepts PKCS#8 format private keys for PEM format files.
=item B<-keyform> B<DER>|B<PEM>|B<P12>|B<ENGINE>
The format of the private key; unspecified by default.
See L<openssl-format-options(1)> for details.
=item B<-keyout> I<filename>
This gives the filename to write any private key to that has been newly created
or read from B<-key>. If neither the B<-keyout> option nor the B<-key> option
are given then the filename specified in the configuration file with the
B<default_keyfile> option is used, if present. Thus, if you want to write the
private key and the B<-key> option is provided, you should provide the
B<-keyout> option explicitly. If a new key is generated and no filename is
specified the key is written to standard output.
=item B<-noenc>
If this option is specified then if a private key is created it
will not be encrypted.
=item B<-nodes>
This option is deprecated since OpenSSL 3.0; use B<-noenc> instead.
=item B<-I<digest>>
This specifies the message digest to sign the request.
Any digest supported by the OpenSSL B<dgst> command can be used.
This overrides the digest algorithm specified in
the configuration file.
Some public key algorithms may override this choice. For instance, DSA
signatures always use SHA1, GOST R 34.10 signatures always use
GOST R 34.11-94 (B<-md_gost94>), Ed25519 and Ed448 never use any digest.
=item B<-config> I<filename>
This allows an alternative configuration file to be specified.
Optional; for a description of the default value,
see L<openssl(1)/COMMAND SUMMARY>.
=item B<-section> I<name>
Specifies the name of the section to use; the default is B<req>.
=item B<-subj> I<arg>
Sets subject name for new request or supersedes the subject name
when processing a certificate request.
The arg must be formatted as C</type0=value0/type1=value1/type2=...>.
Special characters may be escaped by C<\> (backslash), whitespace is retained.
Empty values are permitted, but the corresponding type will not be included
in the request.
Giving a single C</> will lead to an empty sequence of RDNs (a NULL-DN).
Multi-valued RDNs can be formed by placing a C<+> character instead of a C</>
between the AttributeValueAssertions (AVAs) that specify the members of the set.
Example:
C</DC=org/DC=OpenSSL/DC=users/UID=123456+CN=John Doe>
=item B<-multivalue-rdn>
This option has been deprecated and has no effect.
=item B<-x509>
This option outputs a certificate instead of a certificate request.
This is typically used to generate test certificates.
It is implied by the B<-CA> option.
This option implies the B<-new> flag if B<-in> is not given.
If an existing request is specified with the B<-in> option, it is converted
to a certificate; otherwise a request is created from scratch.
Unless specified using the B<-set_serial> option,
a large random number will be used for the serial number.
Unless the B<-copy_extensions> option is used,
X.509 extensions are not copied from any provided request input file.
X.509 extensions to be added can be specified in the configuration file
or using the B<-addext> option.
=item B<-CA> I<filename>|I<uri>
Specifies the "CA" certificate to be used for signing a new certificate
and implies use of B<-x509>.
When present, this behaves like a "micro CA" as follows:
The subject name of the "CA" certificate is placed as issuer name in the new
certificate, which is then signed using the "CA" key given as specified below.
=item B<-CAkey> I<filename>|I<uri>
Sets the "CA" private key to sign a certificate with.
The private key must match the public key of the certificate given with B<-CA>.
If this option is not provided then the key must be present in the B<-CA> input.
=item B<-days> I<n>
When B<-x509> is in use this specifies the number of
days to certify the certificate for, otherwise it is ignored. I<n> should
be a positive integer. The default is 30 days.
=item B<-set_serial> I<n>
Serial number to use when outputting a self-signed certificate.
This may be specified as a decimal value or a hex value if preceded by C<0x>.
If not given, a large random number will be used.
=item B<-copy_extensions> I<arg>
Determines how X.509 extensions in certificate requests should be handled
when B<-x509> is in use.
If I<arg> is B<none> or this option is not present then extensions are ignored.
If I<arg> is B<copy> or B<copyall> then
all extensions in the request are copied to the certificate.
The main use of this option is to allow a certificate request to supply
values for certain extensions such as subjectAltName.
=item B<-addext> I<ext>
Add a specific extension to the certificate (if B<-x509> is in use)
or certificate request. The argument must have the form of
a key=value pair as it would appear in a config file.
This option can be given multiple times.
=item B<-extensions> I<section>
=item B<-reqexts> I<section>
These options specify alternative sections to include certificate
extensions (if B<-x509> is in use) or certificate request extensions.
This allows several different sections to
be used in the same configuration file to specify requests for
a variety of purposes.
=item B<-precert>
A poison extension will be added to the certificate, making it a
"pre-certificate" (see RFC6962). This can be submitted to Certificate
Transparency logs in order to obtain signed certificate timestamps (SCTs).
These SCTs can then be embedded into the pre-certificate as an extension, before
removing the poison and signing the certificate.
This implies the B<-new> flag.
=item B<-utf8>
This option causes field values to be interpreted as UTF8 strings, by
default they are interpreted as ASCII. This means that the field
values, whether prompted from a terminal or obtained from a
configuration file, must be valid UTF8 strings.
=item B<-reqopt> I<option>
Customise the printing format used with B<-text>. The I<option> argument can be
a single option or multiple options separated by commas.
See discussion of the B<-certopt> parameter in the L<openssl-x509(1)>
command.
=item B<-newhdr>
Adds the word B<NEW> to the PEM file header and footer lines on the outputted
request. Some software (Netscape certificate server) and some CAs need this.
=item B<-batch>
Non-interactive mode.
=item B<-verbose>
Print extra details about the operations being performed.
=item B<-keygen_engine> I<id>
Specifies an engine (by its unique I<id> string) which would be used
for key generation operations.
{- $OpenSSL::safe::opt_name_item -}
{- $OpenSSL::safe::opt_r_item -}
{- $OpenSSL::safe::opt_engine_item -}
{- $OpenSSL::safe::opt_provider_item -}
=back
=head1 CONFIGURATION FILE FORMAT
The configuration options are specified in the B<req> section of
the configuration file. An alternate name be specified by using the
B<-section> option.
As with all configuration files, if no
value is specified in the specific section then
the initial unnamed or B<default> section is searched too.
The options available are described in detail below.
=over 4
=item B<input_password>, B<output_password>
The passwords for the input private key file (if present) and
the output private key file (if one will be created). The
command line options B<passin> and B<passout> override the
configuration file values.
=item B<default_bits>
Specifies the default key size in bits.
This option is used in conjunction with the B<-new> option to generate
a new key. It can be overridden by specifying an explicit key size in
the B<-newkey> option. The smallest accepted key size is 512 bits. If
no key size is specified then 2048 bits is used.
=item B<default_keyfile>
This is the default filename to write a private key to. If not
specified the key is written to standard output. This can be
overridden by the B<-keyout> option.
=item B<oid_file>
This specifies a file containing additional B<OBJECT IDENTIFIERS>.
Each line of the file should consist of the numerical form of the
object identifier followed by whitespace then the short name followed
by whitespace and finally the long name.
=item B<oid_section>
This specifies a section in the configuration file containing extra
object identifiers. Each line should consist of the short name of the
object identifier followed by B<=> and the numerical form. The short
and long names are the same when this option is used.
=item B<RANDFILE>
At startup the specified file is loaded into the random number generator,
and at exit 256 bytes will be written to it.
It is used for private key generation.
=item B<encrypt_key>
If this is set to B<no> then if a private key is generated it is
B<not> encrypted. This is equivalent to the B<-noenc> command line
option. For compatibility B<encrypt_rsa_key> is an equivalent option.
=item B<default_md>
This option specifies the digest algorithm to use. Any digest supported by the
OpenSSL B<dgst> command can be used. This option can be overridden on the
command line. Certain signing algorithms (i.e. Ed25519 and Ed448) will ignore
any digest that has been set.
=item B<string_mask>
This option masks out the use of certain string types in certain
-fields. Most users will not need to change this option.
+fields. Most users will not need to change this option. It can be set to
+several values:
-It can be set to several values B<default> which is also the default
-option uses PrintableStrings, T61Strings and BMPStrings if the
-B<pkix> value is used then only PrintableStrings and BMPStrings will
-be used. This follows the PKIX recommendation in RFC2459. If the
-B<utf8only> option is used then only UTF8Strings will be used: this
-is the PKIX recommendation in RFC2459 after 2003. Finally the B<nombstr>
-option just uses PrintableStrings and T61Strings: certain software has
-problems with BMPStrings and UTF8Strings: in particular Netscape.
+=over 4
+
+=item B<utf8only>
+- only UTF8Strings are used (this is the default value)
+
+=item B<pkix>
+- any string type except T61Strings
+
+=item B<nombstr>
+- any string type except BMPStrings and UTF8Strings
+
+=item B<default>
+- any kind of string type
+
+=back
+
+Note that B<utf8only> is the PKIX recommendation in RFC2459 after 2003, and the
+default B<string_mask>; B<default> is not the default option. The B<nombstr>
+value is a workaround for some software that has problems with variable-sized
+BMPStrings and UTF8Strings.
=item B<req_extensions>
This specifies the configuration file section containing a list of
extensions to add to the certificate request. It can be overridden
by the B<-reqexts> command line switch. See the
L<x509v3_config(5)> manual page for details of the
extension section format.
=item B<x509_extensions>
This specifies the configuration file section containing a list of
extensions to add to certificate generated when B<-x509> is in use.
It can be overridden by the B<-extensions> command line switch.
=item B<prompt>
If set to the value B<no> this disables prompting of certificate fields
and just takes values from the config file directly. It also changes the
expected format of the B<distinguished_name> and B<attributes> sections.
=item B<utf8>
If set to the value B<yes> then field values to be interpreted as UTF8
strings, by default they are interpreted as ASCII. This means that
the field values, whether prompted from a terminal or obtained from a
configuration file, must be valid UTF8 strings.
=item B<attributes>
This specifies the section containing any request attributes: its format
is the same as B<distinguished_name>. Typically these may contain the
challengePassword or unstructuredName types. They are currently ignored
by OpenSSL's request signing utilities but some CAs might want them.
=item B<distinguished_name>
This specifies the section containing the distinguished name fields to
prompt for when generating a certificate or certificate request. The format
is described in the next section.
=back
=head1 DISTINGUISHED NAME AND ATTRIBUTE SECTION FORMAT
There are two separate formats for the distinguished name and attribute
sections. If the B<prompt> option is set to B<no> then these sections
just consist of field names and values: for example,
CN=My Name
OU=My Organization
emailAddress=someone@somewhere.org
This allows external programs (e.g. GUI based) to generate a template file with
all the field names and values and just pass it to this command. An example
of this kind of configuration file is contained in the B<EXAMPLES> section.
Alternatively if the B<prompt> option is absent or not set to B<no> then the
file contains field prompting information. It consists of lines of the form:
fieldName="prompt"
fieldName_default="default field value"
fieldName_min= 2
fieldName_max= 4
"fieldName" is the field name being used, for example commonName (or CN).
The "prompt" string is used to ask the user to enter the relevant
details. If the user enters nothing then the default value is used if no
default value is present then the field is omitted. A field can
still be omitted if a default value is present if the user just
enters the '.' character.
The number of characters entered must be between the fieldName_min and
fieldName_max limits: there may be additional restrictions based
on the field being used (for example countryName can only ever be
two characters long and must fit in a PrintableString).
Some fields (such as organizationName) can be used more than once
in a DN. This presents a problem because configuration files will
not recognize the same name occurring twice. To avoid this problem
if the fieldName contains some characters followed by a full stop
they will be ignored. So for example a second organizationName can
be input by calling it "1.organizationName".
The actual permitted field names are any object identifier short or
long names. These are compiled into OpenSSL and include the usual
values such as commonName, countryName, localityName, organizationName,
organizationalUnitName, stateOrProvinceName. Additionally emailAddress
is included as well as name, surname, givenName, initials, and dnQualifier.
Additional object identifiers can be defined with the B<oid_file> or
B<oid_section> options in the configuration file. Any additional fields
will be treated as though they were a DirectoryString.
=head1 EXAMPLES
Examine and verify certificate request:
openssl req -in req.pem -text -verify -noout
Create a private key and then generate a certificate request from it:
openssl genrsa -out key.pem 2048
openssl req -new -key key.pem -out req.pem
The same but just using req:
openssl req -newkey rsa:2048 -keyout key.pem -out req.pem
Generate a self-signed root certificate:
openssl req -x509 -newkey rsa:2048 -keyout key.pem -out req.pem
Create an SM2 private key and then generate a certificate request from it:
openssl ecparam -genkey -name SM2 -out sm2.key
openssl req -new -key sm2.key -out sm2.csr -sm3 -sigopt "distid:1234567812345678"
Examine and verify an SM2 certificate request:
openssl req -verify -in sm2.csr -sm3 -vfyopt "distid:1234567812345678"
Example of a file pointed to by the B<oid_file> option:
1.2.3.4 shortName A longer Name
1.2.3.6 otherName Other longer Name
Example of a section pointed to by B<oid_section> making use of variable
expansion:
testoid1=1.2.3.5
testoid2=${testoid1}.6
Sample configuration file prompting for field values:
[ req ]
default_bits = 2048
default_keyfile = privkey.pem
distinguished_name = req_distinguished_name
attributes = req_attributes
req_extensions = v3_ca
dirstring_type = nobmp
[ req_distinguished_name ]
countryName = Country Name (2 letter code)
countryName_default = AU
countryName_min = 2
countryName_max = 2
localityName = Locality Name (eg, city)
organizationalUnitName = Organizational Unit Name (eg, section)
commonName = Common Name (eg, YOUR name)
commonName_max = 64
emailAddress = Email Address
emailAddress_max = 40
[ req_attributes ]
challengePassword = A challenge password
challengePassword_min = 4
challengePassword_max = 20
[ v3_ca ]
subjectKeyIdentifier=hash
authorityKeyIdentifier=keyid:always,issuer:always
basicConstraints = critical, CA:true
Sample configuration containing all field values:
[ req ]
default_bits = 2048
default_keyfile = keyfile.pem
distinguished_name = req_distinguished_name
attributes = req_attributes
prompt = no
output_password = mypass
[ req_distinguished_name ]
C = GB
ST = Test State or Province
L = Test Locality
O = Organization Name
OU = Organizational Unit Name
CN = Common Name
emailAddress = test@email.address
[ req_attributes ]
challengePassword = A challenge password
Example of giving the most common attributes (subject and extensions)
on the command line:
openssl req -new -subj "/C=GB/CN=foo" \
-addext "subjectAltName = DNS:foo.co.uk" \
-addext "certificatePolicies = 1.2.3.4" \
-newkey rsa:2048 -keyout key.pem -out req.pem
=head1 NOTES
The certificate requests generated by B<Xenroll> with MSIE have extensions
added. It includes the B<keyUsage> extension which determines the type of
key (signature only or general purpose) and any additional OIDs entered
by the script in an B<extendedKeyUsage> extension.
=head1 DIAGNOSTICS
The following messages are frequently asked about:
Using configuration from /some/path/openssl.cnf
Unable to load config info
This is followed some time later by:
unable to find 'distinguished_name' in config
problems making Certificate Request
The first error message is the clue: it can't find the configuration
file! Certain operations (like examining a certificate request) don't
need a configuration file so its use isn't enforced. Generation of
certificates or requests however does need a configuration file. This
could be regarded as a bug.
Another puzzling message is this:
Attributes:
a0:00
this is displayed when no attributes are present and the request includes
the correct empty B<SET OF> structure (the DER encoding of which is 0xa0
0x00). If you just see:
Attributes:
then the B<SET OF> is missing and the encoding is technically invalid (but
it is tolerated). See the description of the command line option B<-asn1-kludge>
for more information.
=head1 BUGS
OpenSSL's handling of T61Strings (aka TeletexStrings) is broken: it effectively
treats them as ISO-8859-1 (Latin 1), Netscape and MSIE have similar behaviour.
This can cause problems if you need characters that aren't available in
PrintableStrings and you don't want to or can't use BMPStrings.
As a consequence of the T61String handling the only correct way to represent
accented characters in OpenSSL is to use a BMPString: unfortunately Netscape
currently chokes on these. If you have to use accented characters with Netscape
and MSIE then you currently need to use the invalid T61String form.
The current prompting is not very friendly. It doesn't allow you to confirm what
you've just entered. Other things like extensions in certificate requests are
statically defined in the configuration file. Some of these: like an email
address in subjectAltName should be input by the user.
=head1 SEE ALSO
L<openssl(1)>,
L<openssl-x509(1)>,
L<openssl-ca(1)>,
L<openssl-genrsa(1)>,
L<openssl-gendsa(1)>,
L<config(5)>,
L<x509v3_config(5)>
=head1 HISTORY
The B<-section> option was added in OpenSSL 3.0.0.
The B<-multivalue-rdn> option has become obsolete in OpenSSL 3.0.0 and
has no effect.
The B<-engine> option was deprecated in OpenSSL 3.0.
The <-nodes> option was deprecated in OpenSSL 3.0, too; use B<-noenc> instead.
=head1 COPYRIGHT
-Copyright 2000-2021 The OpenSSL Project Authors. All Rights Reserved.
+Copyright 2000-2024 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<https://www.openssl.org/source/license.html>.
=cut
diff --git a/crypto/openssl/doc/man1/openssl-smime.pod.in b/crypto/openssl/doc/man1/openssl-smime.pod.in
index e438c866c383..0b5dbb5df8f7 100644
--- a/crypto/openssl/doc/man1/openssl-smime.pod.in
+++ b/crypto/openssl/doc/man1/openssl-smime.pod.in
@@ -1,492 +1,484 @@
=pod
{- OpenSSL::safe::output_do_not_edit_headers(); -}
=head1 NAME
openssl-smime - S/MIME command
=head1 SYNOPSIS
B<openssl> B<smime>
[B<-help>]
[B<-encrypt>]
[B<-decrypt>]
[B<-sign>]
[B<-resign>]
[B<-verify>]
[B<-pk7out>]
[B<-binary>]
[B<-crlfeol>]
[B<-I<cipher>>]
[B<-in> I<file>]
[B<-certfile> I<file>]
[B<-signer> I<file>]
[B<-nointern>]
[B<-noverify>]
[B<-nochain>]
[B<-nosigs>]
[B<-nocerts>]
[B<-noattr>]
[B<-nodetach>]
[B<-nosmimecap>]
[B<-recip> I< file>]
[B<-inform> B<DER>|B<PEM>|B<SMIME>]
[B<-outform> B<DER>|B<PEM>|B<SMIME>]
[B<-keyform> B<DER>|B<PEM>|B<P12>|B<ENGINE>]
[B<-passin> I<arg>]
[B<-inkey> I<filename>|I<uri>]
[B<-out> I<file>]
[B<-content> I<file>]
[B<-to> I<addr>]
[B<-from> I<ad>]
[B<-subject> I<s>]
[B<-text>]
[B<-indef>]
[B<-noindef>]
[B<-stream>]
[B<-md> I<digest>]
{- $OpenSSL::safe::opt_trust_synopsis -}
{- $OpenSSL::safe::opt_engine_synopsis -}{- $OpenSSL::safe::opt_r_synopsis -}
{- $OpenSSL::safe::opt_v_synopsis -}
{- $OpenSSL::safe::opt_provider_synopsis -}
{- $OpenSSL::safe::opt_config_synopsis -}
I<recipcert> ...
=head1 DESCRIPTION
This command handles S/MIME mail. It can encrypt, decrypt, sign
and verify S/MIME messages.
=head1 OPTIONS
There are six operation options that set the type of operation to be performed.
The meaning of the other options varies according to the operation type.
=over 4
=item B<-help>
Print out a usage message.
=item B<-encrypt>
Encrypt mail for the given recipient certificates. Input file is the message
to be encrypted. The output file is the encrypted mail in MIME format.
Note that no revocation check is done for the recipient cert, so if that
key has been compromised, others may be able to decrypt the text.
=item B<-decrypt>
Decrypt mail using the supplied certificate and private key. Expects an
encrypted mail message in MIME format for the input file. The decrypted mail
is written to the output file.
=item B<-sign>
Sign mail using the supplied certificate and private key. Input file is
the message to be signed. The signed message in MIME format is written
to the output file.
=item B<-verify>
Verify signed mail. Expects a signed mail message on input and outputs
the signed data. Both clear text and opaque signing is supported.
=item B<-pk7out>
Takes an input message and writes out a PEM encoded PKCS#7 structure.
=item B<-resign>
Resign a message: take an existing message and one or more new signers.
=item B<-in> I<filename>
The input message to be encrypted or signed or the MIME message to
be decrypted or verified.
=item B<-out> I<filename>
The message text that has been decrypted or verified or the output MIME
format message that has been signed or verified.
=item B<-inform> B<DER>|B<PEM>|B<SMIME>
The input format of the PKCS#7 (S/MIME) structure (if one is being read);
the default is B<SMIME>.
See L<openssl-format-options(1)> for details.
=item B<-outform> B<DER>|B<PEM>|B<SMIME>
The output format of the PKCS#7 (S/MIME) structure (if one is being written);
the default is B<SMIME>.
See L<openssl-format-options(1)> for details.
=item B<-keyform> B<DER>|B<PEM>|B<P12>|B<ENGINE>
The key format; unspecified by default.
See L<openssl-format-options(1)> for details.
=item B<-stream>, B<-indef>, B<-noindef>
The B<-stream> and B<-indef> options are equivalent and enable streaming I/O
for encoding operations. This permits single pass processing of data without
the need to hold the entire contents in memory, potentially supporting very
large files. Streaming is automatically set for S/MIME signing with detached
data if the output format is B<SMIME> it is currently off by default for all
other operations.
=item B<-noindef>
Disable streaming I/O where it would produce and indefinite length constructed
encoding. This option currently has no effect. In future streaming will be
enabled by default on all relevant operations and this option will disable it.
=item B<-content> I<filename>
This specifies a file containing the detached content, this is only
useful with the B<-verify> command. This is only usable if the PKCS#7
structure is using the detached signature form where the content is
not included. This option will override any content if the input format
is S/MIME and it uses the multipart/signed MIME content type.
=item B<-text>
This option adds plain text (text/plain) MIME headers to the supplied
message if encrypting or signing. If decrypting or verifying it strips
off text headers: if the decrypted or verified message is not of MIME
type text/plain then an error occurs.
=item B<-md> I<digest>
Digest algorithm to use when signing or resigning. If not present then the
default digest algorithm for the signing key will be used (usually SHA1).
=item B<-I<cipher>>
The encryption algorithm to use. For example DES (56 bits) - B<-des>,
triple DES (168 bits) - B<-des3>,
EVP_get_cipherbyname() function) can also be used preceded by a dash, for
example B<-aes-128-cbc>. See L<openssl-enc(1)> for list of ciphers
supported by your version of OpenSSL.
If not specified triple DES is used. Only used with B<-encrypt>.
=item B<-nointern>
When verifying a message normally certificates (if any) included in
the message are searched for the signing certificate. With this option
only the certificates specified in the B<-certfile> option are used.
The supplied certificates can still be used as untrusted CAs however.
=item B<-noverify>
Do not verify the signers certificate of a signed message.
=item B<-nochain>
Do not do chain verification of signers certificates; that is, do not
use the certificates in the signed message as untrusted CAs.
=item B<-nosigs>
Don't try to verify the signatures on the message.
=item B<-nocerts>
-When signing a message the signer's certificate is normally included
-with this option it is excluded. This will reduce the size of the
-signed message but the verifier must have a copy of the signers certificate
+When signing a message, the signer's certificate is normally included.
+With this option it is excluded. This will reduce the size of the
+signed message, but the verifier must have a copy of the signers certificate
available locally (passed using the B<-certfile> option for example).
=item B<-noattr>
-Normally when a message is signed a set of attributes are included which
+Normally, when a message is signed, a set of attributes are included which
include the signing time and supported symmetric algorithms. With this
option they are not included.
=item B<-nodetach>
When signing a message use opaque signing. This form is more resistant
to translation by mail relays but it cannot be read by mail agents that
do not support S/MIME. Without this option cleartext signing with
the MIME type multipart/signed is used.
=item B<-nosmimecap>
When signing a message, do not include the B<SMIMECapabilities> attribute.
=item B<-binary>
Normally the input message is converted to "canonical" format which is
effectively using CR and LF as end of line: as required by the S/MIME
specification. When this option is present no translation occurs. This
is useful when handling binary data which may not be in MIME format.
=item B<-crlfeol>
Normally the output file uses a single B<LF> as end of line. When this
option is present B<CRLF> is used instead.
=item B<-certfile> I<file>
Allows additional certificates to be specified. When signing these will
be included with the message. When verifying these will be searched for
the signers certificates.
The input can be in PEM, DER, or PKCS#12 format.
=item B<-signer> I<file>
A signing certificate when signing or resigning a message, this option can be
used multiple times if more than one signer is required. If a message is being
verified then the signers certificates will be written to this file if the
verification was successful.
-=item B<-nocerts>
-
-Don't include signers certificate when signing.
-
-=item B<-noattr>
-
-Don't include any signed attributes when signing.
-
=item B<-recip> I<file>
The recipients certificate when decrypting a message. This certificate
must match one of the recipients of the message or an error occurs.
=item B<-inkey> I<filename>|I<uri>
The private key to use when signing or decrypting. This must match the
corresponding certificate. If this option is not specified then the
private key must be included in the certificate file specified with
the B<-recip> or B<-signer> file. When signing this option can be used
multiple times to specify successive keys.
=item B<-passin> I<arg>
The private key password source. For more information about the format of I<arg>
see L<openssl-passphrase-options(1)>.
=item B<-to>, B<-from>, B<-subject>
The relevant mail headers. These are included outside the signed
portion of a message so they may be included manually. If signing
then many S/MIME mail clients check the signers certificate's email
address matches that specified in the From: address.
{- $OpenSSL::safe::opt_v_item -}
Any verification errors cause the command to exit.
{- $OpenSSL::safe::opt_trust_item -}
{- $OpenSSL::safe::opt_engine_item -}
{- $OpenSSL::safe::opt_r_item -}
{- $OpenSSL::safe::opt_provider_item -}
{- $OpenSSL::safe::opt_config_item -}
=item I<recipcert> ...
One or more certificates of message recipients, used when encrypting
a message.
=back
=head1 NOTES
The MIME message must be sent without any blank lines between the
headers and the output. Some mail programs will automatically add
a blank line. Piping the mail directly to sendmail is one way to
achieve the correct format.
The supplied message to be signed or encrypted must include the
necessary MIME headers or many S/MIME clients won't display it
properly (if at all). You can use the B<-text> option to automatically
add plain text headers.
A "signed and encrypted" message is one where a signed message is
then encrypted. This can be produced by encrypting an already signed
message: see the examples section.
This version of the program only allows one signer per message but it
will verify multiple signers on received messages. Some S/MIME clients
choke if a message contains multiple signers. It is possible to sign
messages "in parallel" by signing an already signed message.
The options B<-encrypt> and B<-decrypt> reflect common usage in S/MIME
clients. Strictly speaking these process PKCS#7 enveloped data: PKCS#7
encrypted data is used for other purposes.
The B<-resign> option uses an existing message digest when adding a new
signer. This means that attributes must be present in at least one existing
signer using the same message digest or this operation will fail.
The B<-stream> and B<-indef> options enable streaming I/O support.
As a result the encoding is BER using indefinite length constructed encoding
and no longer DER. Streaming is supported for the B<-encrypt> operation and the
B<-sign> operation if the content is not detached.
Streaming is always used for the B<-sign> operation with detached data but
since the content is no longer part of the PKCS#7 structure the encoding
remains DER.
=head1 EXIT CODES
=over 4
=item Z<>0
The operation was completely successfully.
=item Z<>1
An error occurred parsing the command options.
=item Z<>2
One of the input files could not be read.
=item Z<>3
An error occurred creating the PKCS#7 file or when reading the MIME
message.
=item Z<>4
An error occurred decrypting or verifying the message.
=item Z<>5
The message was verified correctly but an error occurred writing out
the signers certificates.
=back
=head1 EXAMPLES
Create a cleartext signed message:
openssl smime -sign -in message.txt -text -out mail.msg \
-signer mycert.pem
Create an opaque signed message:
openssl smime -sign -in message.txt -text -out mail.msg -nodetach \
-signer mycert.pem
Create a signed message, include some additional certificates and
read the private key from another file:
openssl smime -sign -in in.txt -text -out mail.msg \
-signer mycert.pem -inkey mykey.pem -certfile mycerts.pem
Create a signed message with two signers:
openssl smime -sign -in message.txt -text -out mail.msg \
-signer mycert.pem -signer othercert.pem
Send a signed message under Unix directly to sendmail, including headers:
openssl smime -sign -in in.txt -text -signer mycert.pem \
-from steve@openssl.org -to someone@somewhere \
-subject "Signed message" | sendmail someone@somewhere
Verify a message and extract the signer's certificate if successful:
openssl smime -verify -in mail.msg -signer user.pem -out signedtext.txt
Send encrypted mail using triple DES:
openssl smime -encrypt -in in.txt -from steve@openssl.org \
-to someone@somewhere -subject "Encrypted message" \
-des3 user.pem -out mail.msg
Sign and encrypt mail:
openssl smime -sign -in ml.txt -signer my.pem -text \
| openssl smime -encrypt -out mail.msg \
-from steve@openssl.org -to someone@somewhere \
-subject "Signed and Encrypted message" -des3 user.pem
Note: the encryption command does not include the B<-text> option because the
message being encrypted already has MIME headers.
Decrypt mail:
openssl smime -decrypt -in mail.msg -recip mycert.pem -inkey key.pem
The output from Netscape form signing is a PKCS#7 structure with the
detached signature format. You can use this program to verify the
signature by line wrapping the base64 encoded structure and surrounding
it with:
-----BEGIN PKCS7-----
-----END PKCS7-----
and using the command:
openssl smime -verify -inform PEM -in signature.pem -content content.txt
Alternatively you can base64 decode the signature and use:
openssl smime -verify -inform DER -in signature.der -content content.txt
Create an encrypted message using 128 bit Camellia:
openssl smime -encrypt -in plain.txt -camellia128 -out mail.msg cert.pem
Add a signer to an existing message:
openssl smime -resign -in mail.msg -signer newsign.pem -out mail2.msg
=head1 BUGS
The MIME parser isn't very clever: it seems to handle most messages that I've
thrown at it but it may choke on others.
The code currently will only write out the signer's certificate to a file: if
the signer has a separate encryption certificate this must be manually
extracted. There should be some heuristic that determines the correct
encryption certificate.
Ideally a database should be maintained of a certificates for each email
address.
The code doesn't currently take note of the permitted symmetric encryption
algorithms as supplied in the SMIMECapabilities signed attribute. This means the
user has to manually include the correct encryption algorithm. It should store
the list of permitted ciphers in a database and only use those.
No revocation checking is done on the signer's certificate.
The current code can only handle S/MIME v2 messages, the more complex S/MIME v3
structures may cause parsing errors.
=head1 SEE ALSO
L<ossl_store-file(7)>
=head1 HISTORY
The use of multiple B<-signer> options and the B<-resign> command were first
added in OpenSSL 1.0.0
The -no_alt_chains option was added in OpenSSL 1.1.0.
The B<-engine> option was deprecated in OpenSSL 3.0.
=head1 COPYRIGHT
-Copyright 2000-2021 The OpenSSL Project Authors. All Rights Reserved.
+Copyright 2000-2024 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<https://www.openssl.org/source/license.html>.
=cut
diff --git a/crypto/openssl/doc/man1/openssl-storeutl.pod.in b/crypto/openssl/doc/man1/openssl-storeutl.pod.in
index 26d5ee28e647..2b619d7c356e 100644
--- a/crypto/openssl/doc/man1/openssl-storeutl.pod.in
+++ b/crypto/openssl/doc/man1/openssl-storeutl.pod.in
@@ -1,147 +1,150 @@
=pod
=begin comment
{- join("\n", @autowarntext) -}
=end comment
=head1 NAME
openssl-storeutl - STORE command
=head1 SYNOPSIS
B<openssl> B<storeutl>
[B<-help>]
[B<-out> I<file>]
[B<-noout>]
[B<-passin> I<arg>]
[B<-text> I<arg>]
[B<-r>]
[B<-certs>]
[B<-keys>]
[B<-crls>]
[B<-subject> I<arg>]
[B<-issuer> I<arg>]
[B<-serial> I<arg>]
[B<-alias> I<arg>]
[B<-fingerprint> I<arg>]
[B<-I<digest>>]
{- $OpenSSL::safe::opt_engine_synopsis -}{- $OpenSSL::safe::opt_provider_synopsis -}
I<uri>
=head1 DESCRIPTION
This command can be used to display the contents (after
decryption as the case may be) fetched from the given URI.
=head1 OPTIONS
=over 4
=item B<-help>
Print out a usage message.
=item B<-out> I<filename>
specifies the output filename to write to or standard output by
default.
=item B<-noout>
this option prevents output of the PEM data.
=item B<-passin> I<arg>
the key password source. For more information about the format of I<arg>
see L<openssl-passphrase-options(1)>.
=item B<-text>
Prints out the objects in text form, similarly to the B<-text> output from
L<openssl-x509(1)>, L<openssl-pkey(1)>, etc.
=item B<-r>
Fetch objects recursively when possible.
=item B<-certs>
=item B<-keys>
=item B<-crls>
Only select the certificates, keys or CRLs from the given URI.
However, if this URI would return a set of names (URIs), those are always
returned.
Note that all options must be given before the I<uri> argument.
Otherwise they are ignored.
+Note I<-keys> selects exclusively private keys, there is no selector for public
+keys only.
+
=item B<-subject> I<arg>
Search for an object having the subject name I<arg>.
The arg must be formatted as C</type0=value0/type1=value1/type2=...>.
Special characters may be escaped by C<\> (backslash), whitespace is retained.
Empty values are permitted but are ignored for the search. That is,
a search with an empty value will have the same effect as not specifying
the type at all.
Giving a single C</> will lead to an empty sequence of RDNs (a NULL-DN).
Multi-valued RDNs can be formed by placing a C<+> character instead of a C</>
between the AttributeValueAssertions (AVAs) that specify the members of the set.
Example:
C</DC=org/DC=OpenSSL/DC=users/UID=123456+CN=John Doe>
=item B<-issuer> I<arg>
=item B<-serial> I<arg>
Search for an object having the given issuer name and serial number.
These two options I<must> be used together.
The issuer arg must be formatted as C</type0=value0/type1=value1/type2=...>,
characters may be escaped by \ (backslash), no spaces are skipped.
The serial arg may be specified as a decimal value or a hex value if preceded
by C<0x>.
=item B<-alias> I<arg>
Search for an object having the given alias.
=item B<-fingerprint> I<arg>
Search for an object having the given fingerprint.
=item B<-I<digest>>
The digest that was used to compute the fingerprint given with B<-fingerprint>.
{- $OpenSSL::safe::opt_engine_item -}
{- $OpenSSL::safe::opt_provider_item -}
=back
=head1 SEE ALSO
L<openssl(1)>
=head1 HISTORY
This command was added in OpenSSL 1.1.1.
The B<-engine> option was deprecated in OpenSSL 3.0.
=head1 COPYRIGHT
-Copyright 2016-2023 The OpenSSL Project Authors. All Rights Reserved.
+Copyright 2016-2024 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<https://www.openssl.org/source/license.html>.
=cut
diff --git a/crypto/openssl/doc/man1/openssl-ts.pod.in b/crypto/openssl/doc/man1/openssl-ts.pod.in
index 3e7f7c4be94b..5f4895b34d6c 100644
--- a/crypto/openssl/doc/man1/openssl-ts.pod.in
+++ b/crypto/openssl/doc/man1/openssl-ts.pod.in
@@ -1,662 +1,662 @@
=pod
{- OpenSSL::safe::output_do_not_edit_headers(); -}
=head1 NAME
openssl-ts - Time Stamping Authority command
=head1 SYNOPSIS
B<openssl> B<ts>
B<-help>
B<openssl> B<ts>
B<-query>
[B<-config> I<configfile>]
[B<-data> I<file_to_hash>]
[B<-digest> I<digest_bytes>]
[B<-I<digest>>]
[B<-tspolicy> I<object_id>]
[B<-no_nonce>]
[B<-cert>]
[B<-in> I<request.tsq>]
[B<-out> I<request.tsq>]
[B<-text>]
{- $OpenSSL::safe::opt_r_synopsis -}
{- $OpenSSL::safe::opt_provider_synopsis -}
B<openssl> B<ts>
B<-reply>
[B<-config> I<configfile>]
[B<-section> I<tsa_section>]
[B<-queryfile> I<request.tsq>]
[B<-passin> I<password_src>]
[B<-signer> I<tsa_cert.pem>]
[B<-inkey> I<filename>|I<uri>]
[B<-I<digest>>]
[B<-chain> I<certs_file.pem>]
[B<-tspolicy> I<object_id>]
[B<-in> I<response.tsr>]
[B<-token_in>]
[B<-out> I<response.tsr>]
[B<-token_out>]
[B<-text>]
{- $OpenSSL::safe::opt_engine_synopsis -}{- $OpenSSL::safe::opt_provider_synopsis -}
B<openssl> B<ts>
B<-verify>
[B<-data> I<file_to_hash>]
[B<-digest> I<digest_bytes>]
[B<-queryfile> I<request.tsq>]
[B<-in> I<response.tsr>]
[B<-token_in>]
[B<-untrusted> I<files>|I<uris>]
[B<-CAfile> I<file>]
[B<-CApath> I<dir>]
[B<-CAstore> I<uri>]
{- $OpenSSL::safe::opt_v_synopsis -}
{- $OpenSSL::safe::opt_provider_synopsis -}
=head1 DESCRIPTION
This command is a basic Time Stamping Authority (TSA) client and
server application as specified in RFC 3161 (Time-Stamp Protocol, TSP). A
TSA can be part of a PKI deployment and its role is to provide long
term proof of the existence of a certain datum before a particular
time. Here is a brief description of the protocol:
=over 4
=item 1.
The TSA client computes a one-way hash value for a data file and sends
the hash to the TSA.
=item 2.
The TSA attaches the current date and time to the received hash value,
signs them and sends the timestamp token back to the client. By
creating this token the TSA certifies the existence of the original
data file at the time of response generation.
=item 3.
The TSA client receives the timestamp token and verifies the
signature on it. It also checks if the token contains the same hash
value that it had sent to the TSA.
=back
There is one DER encoded protocol data unit defined for transporting a
timestamp request to the TSA and one for sending the timestamp response
back to the client. This command has three main functions:
creating a timestamp request based on a data file,
creating a timestamp response based on a request, verifying if a
response corresponds to a particular request or a data file.
There is no support for sending the requests/responses automatically
over HTTP or TCP yet as suggested in RFC 3161. The users must send the
requests either by ftp or e-mail.
=head1 OPTIONS
=over 4
=item B<-help>
Print out a usage message.
=item B<-query>
Generate a TS query. For details see L</Timestamp Request generation>.
=item B<-reply>
Generate a TS reply. For details see L</Timestamp Response generation>.
=item B<-verify>
Verify a TS response. For details see L</Timestamp Response verification>.
=back
=head2 Timestamp Request generation
The B<-query> command can be used for creating and printing a timestamp
request with the following options:
=over 4
=item B<-config> I<configfile>
The configuration file to use.
Optional; for a description of the default value,
see L<openssl(1)/COMMAND SUMMARY>.
=item B<-data> I<file_to_hash>
The data file for which the timestamp request needs to be
created. stdin is the default if neither the B<-data> nor the B<-digest>
parameter is specified. (Optional)
=item B<-digest> I<digest_bytes>
It is possible to specify the message imprint explicitly without the data
file. The imprint must be specified in a hexadecimal format, two characters
per byte, the bytes optionally separated by colons (e.g. 1A:F6:01:... or
1AF601...). The number of bytes must match the message digest algorithm
in use. (Optional)
=item B<-I<digest>>
The message digest to apply to the data file.
Any digest supported by the L<openssl-dgst(1)> command can be used.
The default is SHA-256. (Optional)
=item B<-tspolicy> I<object_id>
The policy that the client expects the TSA to use for creating the
timestamp token. Either the dotted OID notation or OID names defined
in the config file can be used. If no policy is requested the TSA will
use its own default policy. (Optional)
=item B<-no_nonce>
No nonce is specified in the request if this option is
-given. Otherwise a 64 bit long pseudo-random none is
-included in the request. It is recommended to use nonce to
-protect against replay-attacks. (Optional)
+given. Otherwise, a 64-bit long pseudo-random nonce is
+included in the request. It is recommended to use a nonce to
+protect against replay attacks. (Optional)
=item B<-cert>
The TSA is expected to include its signing certificate in the
response. (Optional)
=item B<-in> I<request.tsq>
This option specifies a previously created timestamp request in DER
format that will be printed into the output file. Useful when you need
to examine the content of a request in human-readable
format. (Optional)
=item B<-out> I<request.tsq>
Name of the output file to which the request will be written. Default
is stdout. (Optional)
=item B<-text>
If this option is specified the output is human-readable text format
instead of DER. (Optional)
{- $OpenSSL::safe::opt_r_item -}
=back
=head2 Timestamp Response generation
A timestamp response (TimeStampResp) consists of a response status
and the timestamp token itself (ContentInfo), if the token generation was
successful. The B<-reply> command is for creating a timestamp
response or timestamp token based on a request and printing the
response/token in human-readable format. If B<-token_out> is not
specified the output is always a timestamp response (TimeStampResp),
otherwise it is a timestamp token (ContentInfo).
=over 4
=item B<-config> I<configfile>
The configuration file to use.
Optional; for a description of the default value,
see L<openssl(1)/COMMAND SUMMARY>.
See L</CONFIGURATION FILE OPTIONS> for configurable variables.
=item B<-section> I<tsa_section>
The name of the config file section containing the settings for the
response generation. If not specified the default TSA section is
used, see L</CONFIGURATION FILE OPTIONS> for details. (Optional)
=item B<-queryfile> I<request.tsq>
The name of the file containing a DER encoded timestamp request. (Optional)
=item B<-passin> I<password_src>
Specifies the password source for the private key of the TSA. See
description in L<openssl(1)>. (Optional)
=item B<-signer> I<tsa_cert.pem>
The signer certificate of the TSA in PEM format. The TSA signing
certificate must have exactly one extended key usage assigned to it:
timeStamping. The extended key usage must also be critical, otherwise
the certificate is going to be refused. Overrides the B<signer_cert>
variable of the config file. (Optional)
=item B<-inkey> I<filename>|I<uri>
The signer private key of the TSA in PEM format. Overrides the
B<signer_key> config file option. (Optional)
=item B<-I<digest>>
Signing digest to use. Overrides the B<signer_digest> config file
option. (Mandatory unless specified in the config file)
=item B<-chain> I<certs_file.pem>
The collection of certificates in PEM format that will all
be included in the response in addition to the signer certificate if
the B<-cert> option was used for the request. This file is supposed to
contain the certificate chain for the signer certificate from its
issuer upwards. The B<-reply> command does not build a certificate
chain automatically. (Optional)
=item B<-tspolicy> I<object_id>
The default policy to use for the response unless the client
explicitly requires a particular TSA policy. The OID can be specified
either in dotted notation or with its name. Overrides the
B<default_policy> config file option. (Optional)
=item B<-in> I<response.tsr>
Specifies a previously created timestamp response or timestamp token
(if B<-token_in> is also specified) in DER format that will be written
to the output file. This option does not require a request, it is
useful e.g. when you need to examine the content of a response or
token or you want to extract the timestamp token from a response. If
the input is a token and the output is a timestamp response a default
'granted' status info is added to the token. (Optional)
=item B<-token_in>
This flag can be used together with the B<-in> option and indicates
that the input is a DER encoded timestamp token (ContentInfo) instead
of a timestamp response (TimeStampResp). (Optional)
=item B<-out> I<response.tsr>
The response is written to this file. The format and content of the
file depends on other options (see B<-text>, B<-token_out>). The default is
stdout. (Optional)
=item B<-token_out>
The output is a timestamp token (ContentInfo) instead of timestamp
response (TimeStampResp). (Optional)
=item B<-text>
If this option is specified the output is human-readable text format
instead of DER. (Optional)
{- $OpenSSL::safe::opt_engine_item -}
{- $OpenSSL::safe::opt_provider_item -}
=back
=head2 Timestamp Response verification
The B<-verify> command is for verifying if a timestamp response or
timestamp token is valid and matches a particular timestamp request or
data file. The B<-verify> command does not use the configuration file.
=over 4
=item B<-data> I<file_to_hash>
The response or token must be verified against file_to_hash. The file
is hashed with the message digest algorithm specified in the token.
The B<-digest> and B<-queryfile> options must not be specified with this one.
(Optional)
=item B<-digest> I<digest_bytes>
The response or token must be verified against the message digest specified
with this option. The number of bytes must match the message digest algorithm
specified in the token. The B<-data> and B<-queryfile> options must not be
specified with this one. (Optional)
=item B<-queryfile> I<request.tsq>
The original timestamp request in DER format. The B<-data> and B<-digest>
options must not be specified with this one. (Optional)
=item B<-in> I<response.tsr>
The timestamp response that needs to be verified in DER format. (Mandatory)
=item B<-token_in>
This flag can be used together with the B<-in> option and indicates
that the input is a DER encoded timestamp token (ContentInfo) instead
of a timestamp response (TimeStampResp). (Optional)
=item B<-untrusted> I<files>|I<uris>
A set of additional untrusted certificates which may be
needed when building the certificate chain for the TSA's signing certificate.
These do not need to contain the TSA signing certificate and intermediate CA
certificates as far as the response already includes them.
(Optional)
Multiple sources may be given, separated by commas and/or whitespace.
Each file may contain multiple certificates.
=item B<-CAfile> I<file>, B<-CApath> I<dir>, B<-CAstore> I<uri>
See L<openssl-verification-options(1)/Trusted Certificate Options> for details.
At least one of B<-CAfile>, B<-CApath> or B<-CAstore> must be specified.
{- $OpenSSL::safe::opt_v_item -}
Any verification errors cause the command to exit.
=back
=head1 CONFIGURATION FILE OPTIONS
The B<-query> and B<-reply> commands make use of a configuration file.
See L<config(5)>
for a general description of the syntax of the config file. The
B<-query> command uses only the symbolic OID names section
and it can work without it. However, the B<-reply> command needs the
config file for its operation.
When there is a command line switch equivalent of a variable the
switch always overrides the settings in the config file.
=over 4
=item B<tsa> section, B<default_tsa>
This is the main section and it specifies the name of another section
that contains all the options for the B<-reply> command. This default
section can be overridden with the B<-section> command line switch. (Optional)
=item B<oid_file>
This specifies a file containing additional B<OBJECT IDENTIFIERS>.
Each line of the file should consist of the numerical form of the
object identifier followed by whitespace then the short name followed
by whitespace and finally the long name. (Optional)
=item B<oid_section>
This specifies a section in the configuration file containing extra
object identifiers. Each line should consist of the short name of the
object identifier followed by B<=> and the numerical form. The short
and long names are the same when this option is used. (Optional)
=item B<RANDFILE>
At startup the specified file is loaded into the random number generator,
and at exit 256 bytes will be written to it. (Note: Using a RANDFILE is
not necessary anymore, see the L</HISTORY> section.
=item B<serial>
The name of the file containing the hexadecimal serial number of the
last timestamp response created. This number is incremented by 1 for
each response. If the file does not exist at the time of response
generation a new file is created with serial number 1. (Mandatory)
=item B<crypto_device>
Specifies the OpenSSL engine that will be set as the default for
all available algorithms. The default value is built-in, you can specify
any other engines supported by OpenSSL (e.g. use chil for the NCipher HSM).
(Optional)
=item B<signer_cert>
TSA signing certificate in PEM format. The same as the B<-signer>
command line option. (Optional)
=item B<certs>
A file containing a set of PEM encoded certificates that need to be
included in the response. The same as the B<-chain> command line
option. (Optional)
=item B<signer_key>
The private key of the TSA in PEM format. The same as the B<-inkey>
command line option. (Optional)
=item B<signer_digest>
Signing digest to use. The same as the
B<-I<digest>> command line option. (Mandatory unless specified on the command
line)
=item B<default_policy>
The default policy to use when the request does not mandate any
policy. The same as the B<-tspolicy> command line option. (Optional)
=item B<other_policies>
Comma separated list of policies that are also acceptable by the TSA
and used only if the request explicitly specifies one of them. (Optional)
=item B<digests>
The list of message digest algorithms that the TSA accepts. At least
one algorithm must be specified. (Mandatory)
=item B<accuracy>
The accuracy of the time source of the TSA in seconds, milliseconds
and microseconds. E.g. secs:1, millisecs:500, microsecs:100. If any of
the components is missing zero is assumed for that field. (Optional)
=item B<clock_precision_digits>
Specifies the maximum number of digits, which represent the fraction of
seconds, that need to be included in the time field. The trailing zeros
must be removed from the time, so there might actually be fewer digits,
or no fraction of seconds at all. Supported only on UNIX platforms.
The maximum value is 6, default is 0.
(Optional)
=item B<ordering>
If this option is yes the responses generated by this TSA can always
be ordered, even if the time difference between two responses is less
than the sum of their accuracies. Default is no. (Optional)
=item B<tsa_name>
Set this option to yes if the subject name of the TSA must be included in
the TSA name field of the response. Default is no. (Optional)
=item B<ess_cert_id_chain>
The SignedData objects created by the TSA always contain the
certificate identifier of the signing certificate in a signed
attribute (see RFC 2634, Enhanced Security Services).
If this variable is set to no, only this signing certificate identifier
is included in the SigningCertificate signed attribute.
If this variable is set to yes and the B<certs> variable or the B<-chain> option
is specified then the certificate identifiers of the chain will also
be included, where the B<-chain> option overrides the B<certs> variable.
Default is no. (Optional)
=item B<ess_cert_id_alg>
This option specifies the hash function to be used to calculate the TSA's
public key certificate identifier. Default is sha1. (Optional)
=back
=head1 EXAMPLES
All the examples below presume that B<OPENSSL_CONF> is set to a proper
configuration file, e.g. the example configuration file
F<openssl/apps/openssl.cnf> will do.
=head2 Timestamp Request
To create a timestamp request for F<design1.txt> with SHA-256 digest,
without nonce and policy, and without requirement for a certificate
in the response:
openssl ts -query -data design1.txt -no_nonce \
-out design1.tsq
To create a similar timestamp request with specifying the message imprint
explicitly:
openssl ts -query -digest b7e5d3f93198b38379852f2c04e78d73abdd0f4b \
-no_nonce -out design1.tsq
To print the content of the previous request in human readable format:
openssl ts -query -in design1.tsq -text
To create a timestamp request which includes the SHA-512 digest
of F<design2.txt>, requests the signer certificate and nonce, and
specifies a policy id (assuming the tsa_policy1 name is defined in the
OID section of the config file):
openssl ts -query -data design2.txt -sha512 \
-tspolicy tsa_policy1 -cert -out design2.tsq
=head2 Timestamp Response
Before generating a response a signing certificate must be created for
the TSA that contains the B<timeStamping> critical extended key usage extension
without any other key usage extensions. You can add this line to the
user certificate section of the config file to generate a proper certificate;
extendedKeyUsage = critical,timeStamping
See L<openssl-req(1)>, L<openssl-ca(1)>, and L<openssl-x509(1)> for
instructions. The examples below assume that F<cacert.pem> contains the
certificate of the CA, F<tsacert.pem> is the signing certificate issued
by F<cacert.pem> and F<tsakey.pem> is the private key of the TSA.
To create a timestamp response for a request:
openssl ts -reply -queryfile design1.tsq -inkey tsakey.pem \
-signer tsacert.pem -out design1.tsr
If you want to use the settings in the config file you could just write:
openssl ts -reply -queryfile design1.tsq -out design1.tsr
To print a timestamp reply to stdout in human readable format:
openssl ts -reply -in design1.tsr -text
To create a timestamp token instead of timestamp response:
openssl ts -reply -queryfile design1.tsq -out design1_token.der -token_out
To print a timestamp token to stdout in human readable format:
openssl ts -reply -in design1_token.der -token_in -text -token_out
To extract the timestamp token from a response:
openssl ts -reply -in design1.tsr -out design1_token.der -token_out
To add 'granted' status info to a timestamp token thereby creating a
valid response:
openssl ts -reply -in design1_token.der -token_in -out design1.tsr
=head2 Timestamp Verification
To verify a timestamp reply against a request:
openssl ts -verify -queryfile design1.tsq -in design1.tsr \
-CAfile cacert.pem -untrusted tsacert.pem
To verify a timestamp reply that includes the certificate chain:
openssl ts -verify -queryfile design2.tsq -in design2.tsr \
-CAfile cacert.pem
To verify a timestamp token against the original data file:
openssl ts -verify -data design2.txt -in design2.tsr \
-CAfile cacert.pem
To verify a timestamp token against a message imprint:
openssl ts -verify -digest b7e5d3f93198b38379852f2c04e78d73abdd0f4b \
-in design2.tsr -CAfile cacert.pem
You could also look at the 'test' directory for more examples.
=head1 BUGS
=for openssl foreign manual procmail(1) perl(1)
=over 2
=item *
No support for timestamps over SMTP, though it is quite easy
to implement an automatic e-mail based TSA with L<procmail(1)>
and L<perl(1)>. HTTP server support is provided in the form of
a separate apache module. HTTP client support is provided by
L<tsget(1)>. Pure TCP/IP protocol is not supported.
=item *
The file containing the last serial number of the TSA is not
locked when being read or written. This is a problem if more than one
instance of L<openssl(1)> is trying to create a timestamp
response at the same time. This is not an issue when using the apache
server module, it does proper locking.
=item *
Look for the FIXME word in the source files.
=item *
The source code should really be reviewed by somebody else, too.
=item *
More testing is needed, I have done only some basic tests (see
test/testtsa).
=back
=head1 HISTORY
OpenSSL 1.1.1 introduced a new random generator (CSPRNG) with an improved
seeding mechanism. The new seeding mechanism makes it unnecessary to
define a RANDFILE for saving and restoring randomness. This option is
retained mainly for compatibility reasons.
The B<-engine> option was deprecated in OpenSSL 3.0.
=head1 SEE ALSO
L<openssl(1)>,
L<tsget(1)>,
L<openssl-req(1)>,
L<openssl-x509(1)>,
L<openssl-ca(1)>,
L<openssl-genrsa(1)>,
L<config(5)>,
L<ossl_store-file(7)>
=head1 COPYRIGHT
-Copyright 2006-2023 The OpenSSL Project Authors. All Rights Reserved.
+Copyright 2006-2024 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<https://www.openssl.org/source/license.html>.
=cut
diff --git a/crypto/openssl/doc/man3/DEFINE_STACK_OF.pod b/crypto/openssl/doc/man3/DEFINE_STACK_OF.pod
index 0775214fb5d7..3ebd473afcb2 100644
--- a/crypto/openssl/doc/man3/DEFINE_STACK_OF.pod
+++ b/crypto/openssl/doc/man3/DEFINE_STACK_OF.pod
@@ -1,307 +1,307 @@
=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 <openssl/safestack.h>
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(const STACK_OF(TYPE) *sk);
- void sk_TYPE_zero(const STACK_OF(TYPE) *sk);
+ 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<OPENSSL_sk_> API.
In the description here, B<I<TYPE>> is used
as a placeholder for any of the OpenSSL datatypes, such as B<X509>.
The STACK_OF() macro returns the name for a stack of the specified B<I<TYPE>>.
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<DEFINE...> 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<I<TYPE>> elements.
The type is referenced by
B<STACK_OF>(B<I<TYPE>>) and each function name begins with B<sk_I<TYPE>_>.
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<FUNCNAME> 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<sk_I<TYPE>_num>() returns the number of elements in I<sk> or -1 if I<sk> is
NULL.
B<sk_I<TYPE>_value>() returns element I<idx> in I<sk>, where I<idx> starts at
zero. If I<idx> is out of range then NULL is returned.
B<sk_I<TYPE>_new>() allocates a new empty stack using comparison function
I<compare>. If I<compare> is NULL then no comparison function is used. This
function is equivalent to B<sk_I<TYPE>_new_reserve>(I<compare>, 0).
B<sk_I<TYPE>_new_null>() allocates a new empty stack with no comparison
function. This function is equivalent to B<sk_I<TYPE>_new_reserve>(NULL, 0).
B<sk_I<TYPE>_reserve>() allocates additional memory in the I<sk> structure
such that the next I<n> calls to B<sk_I<TYPE>_insert>(), B<sk_I<TYPE>_push>()
or B<sk_I<TYPE>_unshift>() will not fail or cause memory to be allocated
or reallocated. If I<n> is zero, any excess space allocated in the
I<sk> structure is freed. On error I<sk> is unchanged.
B<sk_I<TYPE>_new_reserve>() allocates a new stack. The new stack will have
additional memory allocated to hold I<n> elements if I<n> is positive.
The next I<n> calls to B<sk_I<TYPE>_insert>(), B<sk_I<TYPE>_push>() or
B<sk_I<TYPE>_unshift>() will not fail or cause memory to be allocated or
reallocated. If I<n> is zero or less than zero, no memory is allocated.
B<sk_I<TYPE>_new_reserve>() also sets the comparison function I<compare>
to the newly created stack. If I<compare> is NULL then no comparison
function is used.
B<sk_I<TYPE>_set_cmp_func>() sets the comparison function of I<sk> to
I<compare>. The previous comparison function is returned or NULL if there
was no previous comparison function.
B<sk_I<TYPE>_free>() frees up the I<sk> structure. It does I<not> free up any
elements of I<sk>. After this call I<sk> is no longer valid.
B<sk_I<TYPE>_zero>() sets the number of elements in I<sk> to zero. It does not
free I<sk> so after this call I<sk> is still valid.
B<sk_I<TYPE>_pop_free>() frees up all elements of I<sk> and I<sk> itself. The
free function freefunc() is called on each element to free it.
B<sk_I<TYPE>_delete>() deletes element I<i> from I<sk>. It returns the deleted
element or NULL if I<i> is out of range.
B<sk_I<TYPE>_delete_ptr>() deletes element matching I<ptr> from I<sk>. It
returns the deleted element or NULL if no element matching I<ptr> was found.
B<sk_I<TYPE>_insert>() inserts I<ptr> into I<sk> at position I<idx>. Any
existing elements at or after I<idx> are moved downwards. If I<idx> is out
of range the new element is appended to I<sk>. B<sk_I<TYPE>_insert>() either
returns the number of elements in I<sk> after the new element is inserted or
zero if an error (such as memory allocation failure) occurred.
B<sk_I<TYPE>_push>() appends I<ptr> to I<sk> it is equivalent to:
sk_TYPE_insert(sk, ptr, -1);
B<sk_I<TYPE>_unshift>() inserts I<ptr> at the start of I<sk> it is equivalent
to:
sk_TYPE_insert(sk, ptr, 0);
B<sk_I<TYPE>_pop>() returns and removes the last element from I<sk>.
B<sk_I<TYPE>_shift>() returns and removes the first element from I<sk>.
B<sk_I<TYPE>_set>() sets element I<idx> of I<sk> to I<ptr> replacing the current
element. The new element value is returned or NULL if an error occurred:
this will only happen if I<sk> is NULL or I<idx> is out of range.
B<sk_I<TYPE>_find>() searches I<sk> for the element I<ptr>. In the case
where no comparison function has been specified, the function performs
a linear search for a pointer equal to I<ptr>. 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<sk> is sorted and
B<sk_I<TYPE>_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<sk> can change. Note that because the stack may be
sorted as the result of a B<sk_I<TYPE>_find>() call, if a lock is being used to
synchronise access to the stack across multiple threads, then that lock must be
a "write" lock.
B<sk_I<TYPE>_find_ex>() operates like B<sk_I<TYPE>_find>() except when a
comparison function has been specified and no matching element is found.
Instead of returning B<-1>, B<sk_I<TYPE>_find_ex>() returns the index of the
element either before or after the location where I<ptr> would be if it were
present in I<sk>. The function also does not guarantee that the first matching
element in the sorted stack is returned.
B<sk_I<TYPE>_find_all>() operates like B<sk_I<TYPE>_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<sk_I<TYPE>_sort>() sorts I<sk> using the supplied comparison function.
B<sk_I<TYPE>_is_sorted>() returns B<1> if I<sk> is sorted and B<0> otherwise.
B<sk_I<TYPE>_dup>() returns a shallow copy of I<sk>
or an empty stack if the passed stack is NULL.
Note the pointers in the copy are identical to the original.
B<sk_I<TYPE>_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<sk_I<TYPE>_insert>()
or B<sk_I<TYPE>_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<sk_I<TYPE>_find>() and B<sk_I<TYPE>_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<a> is equal to, greater than
or less than I<b> respectively.
Care should be taken when checking the return values of the functions
B<sk_I<TYPE>_find>() and B<sk_I<TYPE>_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<sk_I<TYPE>_num>(), B<sk_I<TYPE>_value>(),
B<sk_I<TYPE>_free>(), B<sk_I<TYPE>_zero>(), B<sk_I<TYPE>_pop_free>(),
B<sk_I<TYPE>_delete>(), B<sk_I<TYPE>_delete_ptr>(), B<sk_I<TYPE>_pop>(),
B<sk_I<TYPE>_shift>(), B<sk_I<TYPE>_find>(), B<sk_I<TYPE>_find_ex>(),
and B<sk_I<TYPE>_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<OPENSSL_sk_> 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<sk_I<TYPE>_num>() returns the number of elements in the stack or B<-1> if the
passed stack is NULL.
B<sk_I<TYPE>_value>() returns a pointer to a stack element or NULL if the
index is out of range.
B<sk_I<TYPE>_new>(), B<sk_I<TYPE>_new_null>() and B<sk_I<TYPE>_new_reserve>()
return an empty stack or NULL if an error occurs.
B<sk_I<TYPE>_reserve>() returns B<1> on successful allocation of the required
memory or B<0> on error.
B<sk_I<TYPE>_set_cmp_func>() returns the old comparison function or NULL if
there was no old comparison function.
B<sk_I<TYPE>_free>(), B<sk_I<TYPE>_zero>(), B<sk_I<TYPE>_pop_free>() and
B<sk_I<TYPE>_sort>() do not return values.
B<sk_I<TYPE>_pop>(), B<sk_I<TYPE>_shift>(), B<sk_I<TYPE>_delete>() and
B<sk_I<TYPE>_delete_ptr>() return a pointer to the deleted element or NULL
on error.
B<sk_I<TYPE>_insert>(), B<sk_I<TYPE>_push>() and B<sk_I<TYPE>_unshift>() return
the total number of elements in the stack and 0 if an error occurred.
B<sk_I<TYPE>_push>() further returns -1 if I<sk> is NULL.
B<sk_I<TYPE>_set>() returns a pointer to the replacement element or NULL on
error.
B<sk_I<TYPE>_find>() and B<sk_I<TYPE>_find_ex>() return an index to the found
element or B<-1> on error.
B<sk_I<TYPE>_is_sorted>() returns B<1> if the stack is sorted and B<0> if it is
not.
B<sk_I<TYPE>_dup>() and B<sk_I<TYPE>_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<sk_I<TYPE>_reserve>() and B<sk_I<TYPE>_new_reserve>() were added in OpenSSL
1.1.1.
=head1 COPYRIGHT
-Copyright 2000-2022 The OpenSSL Project Authors. All Rights Reserved.
+Copyright 2000-2024 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<https://www.openssl.org/source/license.html>.
=cut
diff --git a/crypto/openssl/doc/man3/EVP_DigestInit.pod b/crypto/openssl/doc/man3/EVP_DigestInit.pod
index 1953df3c5e8d..d7202c538172 100644
--- a/crypto/openssl/doc/man3/EVP_DigestInit.pod
+++ b/crypto/openssl/doc/man3/EVP_DigestInit.pod
@@ -1,794 +1,794 @@
=pod
=head1 NAME
EVP_MD_fetch, EVP_MD_up_ref, EVP_MD_free,
EVP_MD_get_params, EVP_MD_gettable_params,
EVP_MD_CTX_new, EVP_MD_CTX_reset, EVP_MD_CTX_free, EVP_MD_CTX_copy,
EVP_MD_CTX_copy_ex, EVP_MD_CTX_ctrl,
EVP_MD_CTX_set_params, EVP_MD_CTX_get_params,
EVP_MD_settable_ctx_params, EVP_MD_gettable_ctx_params,
EVP_MD_CTX_settable_params, EVP_MD_CTX_gettable_params,
EVP_MD_CTX_set_flags, EVP_MD_CTX_clear_flags, EVP_MD_CTX_test_flags,
EVP_Q_digest, EVP_Digest, EVP_DigestInit_ex2, EVP_DigestInit_ex, EVP_DigestInit,
EVP_DigestUpdate, EVP_DigestFinal_ex, EVP_DigestFinalXOF, EVP_DigestFinal,
EVP_MD_is_a, EVP_MD_get0_name, EVP_MD_get0_description,
EVP_MD_names_do_all, EVP_MD_get0_provider, EVP_MD_get_type,
EVP_MD_get_pkey_type, EVP_MD_get_size, EVP_MD_get_block_size, EVP_MD_get_flags,
EVP_MD_CTX_get0_name, EVP_MD_CTX_md, EVP_MD_CTX_get0_md, EVP_MD_CTX_get1_md,
EVP_MD_CTX_get_type, EVP_MD_CTX_get_size, EVP_MD_CTX_get_block_size,
EVP_MD_CTX_get0_md_data, EVP_MD_CTX_update_fn, EVP_MD_CTX_set_update_fn,
EVP_md_null,
EVP_get_digestbyname, EVP_get_digestbynid, EVP_get_digestbyobj,
EVP_MD_CTX_get_pkey_ctx, EVP_MD_CTX_set_pkey_ctx,
EVP_MD_do_all_provided,
EVP_MD_type, EVP_MD_nid, EVP_MD_name, EVP_MD_pkey_type, EVP_MD_size,
EVP_MD_block_size, EVP_MD_flags, EVP_MD_CTX_size, EVP_MD_CTX_block_size,
EVP_MD_CTX_type, EVP_MD_CTX_pkey_ctx, EVP_MD_CTX_md_data
- EVP digest routines
=head1 SYNOPSIS
#include <openssl/evp.h>
EVP_MD *EVP_MD_fetch(OSSL_LIB_CTX *ctx, const char *algorithm,
const char *properties);
int EVP_MD_up_ref(EVP_MD *md);
void EVP_MD_free(EVP_MD *md);
int EVP_MD_get_params(const EVP_MD *digest, OSSL_PARAM params[]);
const OSSL_PARAM *EVP_MD_gettable_params(const EVP_MD *digest);
EVP_MD_CTX *EVP_MD_CTX_new(void);
int EVP_MD_CTX_reset(EVP_MD_CTX *ctx);
void EVP_MD_CTX_free(EVP_MD_CTX *ctx);
void EVP_MD_CTX_ctrl(EVP_MD_CTX *ctx, int cmd, int p1, void* p2);
int EVP_MD_CTX_get_params(EVP_MD_CTX *ctx, OSSL_PARAM params[]);
int EVP_MD_CTX_set_params(EVP_MD_CTX *ctx, const OSSL_PARAM params[]);
const OSSL_PARAM *EVP_MD_settable_ctx_params(const EVP_MD *md);
const OSSL_PARAM *EVP_MD_gettable_ctx_params(const EVP_MD *md);
const OSSL_PARAM *EVP_MD_CTX_settable_params(EVP_MD_CTX *ctx);
const OSSL_PARAM *EVP_MD_CTX_gettable_params(EVP_MD_CTX *ctx);
void EVP_MD_CTX_set_flags(EVP_MD_CTX *ctx, int flags);
void EVP_MD_CTX_clear_flags(EVP_MD_CTX *ctx, int flags);
int EVP_MD_CTX_test_flags(const EVP_MD_CTX *ctx, int flags);
int EVP_Q_digest(OSSL_LIB_CTX *libctx, const char *name, const char *propq,
const void *data, size_t datalen,
unsigned char *md, size_t *mdlen);
int EVP_Digest(const void *data, size_t count, unsigned char *md,
unsigned int *size, const EVP_MD *type, ENGINE *impl);
int EVP_DigestInit_ex2(EVP_MD_CTX *ctx, const EVP_MD *type,
const OSSL_PARAM params[]);
int EVP_DigestInit_ex(EVP_MD_CTX *ctx, const EVP_MD *type, ENGINE *impl);
int EVP_DigestUpdate(EVP_MD_CTX *ctx, const void *d, size_t cnt);
int EVP_DigestFinal_ex(EVP_MD_CTX *ctx, unsigned char *md, unsigned int *s);
int EVP_DigestFinalXOF(EVP_MD_CTX *ctx, unsigned char *md, size_t len);
int EVP_MD_CTX_copy_ex(EVP_MD_CTX *out, const EVP_MD_CTX *in);
int EVP_DigestInit(EVP_MD_CTX *ctx, const EVP_MD *type);
int EVP_DigestFinal(EVP_MD_CTX *ctx, unsigned char *md, unsigned int *s);
int EVP_MD_CTX_copy(EVP_MD_CTX *out, EVP_MD_CTX *in);
const char *EVP_MD_get0_name(const EVP_MD *md);
const char *EVP_MD_get0_description(const EVP_MD *md);
int EVP_MD_is_a(const EVP_MD *md, const char *name);
int EVP_MD_names_do_all(const EVP_MD *md,
void (*fn)(const char *name, void *data),
void *data);
const OSSL_PROVIDER *EVP_MD_get0_provider(const EVP_MD *md);
int EVP_MD_get_type(const EVP_MD *md);
int EVP_MD_get_pkey_type(const EVP_MD *md);
int EVP_MD_get_size(const EVP_MD *md);
int EVP_MD_get_block_size(const EVP_MD *md);
unsigned long EVP_MD_get_flags(const EVP_MD *md);
const EVP_MD *EVP_MD_CTX_get0_md(const EVP_MD_CTX *ctx);
EVP_MD *EVP_MD_CTX_get1_md(EVP_MD_CTX *ctx);
const char *EVP_MD_CTX_get0_name(const EVP_MD_CTX *ctx);
int EVP_MD_CTX_get_size(const EVP_MD_CTX *ctx);
int EVP_MD_CTX_get_block_size(const EVP_MD_CTX *ctx);
int EVP_MD_CTX_get_type(const EVP_MD_CTX *ctx);
void *EVP_MD_CTX_get0_md_data(const EVP_MD_CTX *ctx);
const EVP_MD *EVP_md_null(void);
const EVP_MD *EVP_get_digestbyname(const char *name);
const EVP_MD *EVP_get_digestbynid(int type);
const EVP_MD *EVP_get_digestbyobj(const ASN1_OBJECT *o);
EVP_PKEY_CTX *EVP_MD_CTX_get_pkey_ctx(const EVP_MD_CTX *ctx);
void EVP_MD_CTX_set_pkey_ctx(EVP_MD_CTX *ctx, EVP_PKEY_CTX *pctx);
void EVP_MD_do_all_provided(OSSL_LIB_CTX *libctx,
void (*fn)(EVP_MD *mac, void *arg),
void *arg);
#define EVP_MD_type EVP_MD_get_type
#define EVP_MD_nid EVP_MD_get_type
#define EVP_MD_name EVP_MD_get0_name
#define EVP_MD_pkey_type EVP_MD_get_pkey_type
#define EVP_MD_size EVP_MD_get_size
#define EVP_MD_block_size EVP_MD_get_block_size
#define EVP_MD_flags EVP_MD_get_flags
#define EVP_MD_CTX_size EVP_MD_CTX_get_size
#define EVP_MD_CTX_block_size EVP_MD_CTX_get_block_size
#define EVP_MD_CTX_type EVP_MD_CTX_get_type
#define EVP_MD_CTX_pkey_ctx EVP_MD_CTX_get_pkey_ctx
#define EVP_MD_CTX_md_data EVP_MD_CTX_get0_md_data
The following functions have been deprecated since OpenSSL 3.0, and can be
hidden entirely by defining B<OPENSSL_API_COMPAT> with a suitable version value,
see L<openssl_user_macros(7)>:
const EVP_MD *EVP_MD_CTX_md(const EVP_MD_CTX *ctx);
int (*EVP_MD_CTX_update_fn(EVP_MD_CTX *ctx))(EVP_MD_CTX *ctx,
const void *data, size_t count);
void EVP_MD_CTX_set_update_fn(EVP_MD_CTX *ctx,
int (*update)(EVP_MD_CTX *ctx,
const void *data, size_t count));
=head1 DESCRIPTION
The EVP digest routines are a high-level interface to message digests,
and should be used instead of the digest-specific functions.
The B<EVP_MD> type is a structure for digest method implementation.
=over 4
=item EVP_MD_fetch()
Fetches the digest implementation for the given I<algorithm> from any
provider offering it, within the criteria given by the I<properties>.
See L<crypto(7)/ALGORITHM FETCHING> for further information.
The returned value must eventually be freed with EVP_MD_free().
Fetched B<EVP_MD> structures are reference counted.
=item EVP_MD_up_ref()
Increments the reference count for an B<EVP_MD> structure.
=item EVP_MD_free()
Decrements the reference count for the fetched B<EVP_MD> structure.
If the reference count drops to 0 then the structure is freed.
=item EVP_MD_CTX_new()
Allocates and returns a digest context.
=item EVP_MD_CTX_reset()
Resets the digest context I<ctx>. This can be used to reuse an already
existing context.
=item EVP_MD_CTX_free()
Cleans up digest context I<ctx> and frees up the space allocated to it.
=item EVP_MD_CTX_ctrl()
I<This is a legacy method. EVP_MD_CTX_set_params() and EVP_MD_CTX_get_params()
is the mechanism that should be used to set and get parameters that are used by
providers.>
Performs digest-specific control actions on context I<ctx>. The control command
is indicated in I<cmd> and any additional arguments in I<p1> and I<p2>.
EVP_MD_CTX_ctrl() must be called after EVP_DigestInit_ex2(). Other restrictions
may apply depending on the control type and digest implementation.
If this function happens to be used with a fetched B<EVP_MD>, it will
translate the controls that are known to OpenSSL into L<OSSL_PARAM(3)>
parameters with keys defined by OpenSSL and call EVP_MD_CTX_get_params() or
EVP_MD_CTX_set_params() as is appropriate for each control command.
See L</CONTROLS> below for more information, including what translations are
being done.
=item EVP_MD_get_params()
Retrieves the requested list of I<params> from a MD I<md>.
See L</PARAMETERS> below for more information.
=item EVP_MD_CTX_get_params()
Retrieves the requested list of I<params> from a MD context I<ctx>.
See L</PARAMETERS> below for more information.
=item EVP_MD_CTX_set_params()
Sets the list of I<params> into a MD context I<ctx>.
See L</PARAMETERS> below for more information.
=item EVP_MD_gettable_params()
Get a constant L<OSSL_PARAM(3)> array that describes the retrievable parameters
that can be used with EVP_MD_get_params().
=item EVP_MD_gettable_ctx_params(), EVP_MD_CTX_gettable_params()
Get a constant L<OSSL_PARAM(3)> array that describes the retrievable parameters
that can be used with EVP_MD_CTX_get_params(). EVP_MD_gettable_ctx_params()
returns the parameters that can be retrieved from the algorithm, whereas
EVP_MD_CTX_gettable_params() returns the parameters that can be retrieved
in the context's current state.
=item EVP_MD_settable_ctx_params(), EVP_MD_CTX_settable_params()
Get a constant L<OSSL_PARAM(3)> array that describes the settable parameters
that can be used with EVP_MD_CTX_set_params(). EVP_MD_settable_ctx_params()
returns the parameters that can be set from the algorithm, whereas
EVP_MD_CTX_settable_params() returns the parameters that can be set in the
context's current state.
=item EVP_MD_CTX_set_flags(), EVP_MD_CTX_clear_flags(), EVP_MD_CTX_test_flags()
Sets, clears and tests I<ctx> flags. See L</FLAGS> below for more information.
=item EVP_Q_digest() is a quick one-shot digest function.
It hashes I<datalen> bytes of data at I<data> using the digest algorithm
I<name>, which is fetched using the optional I<libctx> and I<propq> parameters.
The digest value is placed in I<md> and its length is written at I<mdlen>
if the pointer is not NULL. At most B<EVP_MAX_MD_SIZE> bytes will be written.
=item EVP_Digest()
A wrapper around the Digest Init_ex, Update and Final_ex functions.
Hashes I<count> bytes of data at I<data> using a digest I<type> from ENGINE
I<impl>. The digest value is placed in I<md> and its length is written at I<size>
if the pointer is not NULL. At most B<EVP_MAX_MD_SIZE> bytes will be written.
If I<impl> is NULL the default implementation of digest I<type> is used.
=item EVP_DigestInit_ex2()
Sets up digest context I<ctx> to use a digest I<type>.
I<type> is typically supplied by a function such as EVP_sha1(), or a
value explicitly fetched with EVP_MD_fetch().
The parameters B<params> are set on the context after initialisation.
The I<type> parameter can be NULL if I<ctx> has been already initialized
with another EVP_DigestInit_ex() call and has not been reset with
EVP_MD_CTX_reset().
=item EVP_DigestInit_ex()
Sets up digest context I<ctx> to use a digest I<type>.
I<type> is typically supplied by a function such as EVP_sha1(), or a
value explicitly fetched with EVP_MD_fetch().
If I<impl> is non-NULL, its implementation of the digest I<type> is used if
there is one, and if not, the default implementation is used.
The I<type> parameter can be NULL if I<ctx> has been already initialized
with another EVP_DigestInit_ex() call and has not been reset with
EVP_MD_CTX_reset().
=item EVP_DigestUpdate()
Hashes I<cnt> bytes of data at I<d> into the digest context I<ctx>. This
function can be called several times on the same I<ctx> to hash additional
data.
=item EVP_DigestFinal_ex()
Retrieves the digest value from I<ctx> and places it in I<md>. If the I<s>
parameter is not NULL then the number of bytes of data written (i.e. the
length of the digest) will be written to the integer at I<s>, at most
B<EVP_MAX_MD_SIZE> bytes will be written. After calling EVP_DigestFinal_ex()
no additional calls to EVP_DigestUpdate() can be made, but
EVP_DigestInit_ex2() can be called to initialize a new digest operation.
=item EVP_DigestFinalXOF()
Interfaces to extendable-output functions, XOFs, such as SHAKE128 and SHAKE256.
It retrieves the digest value from I<ctx> and places it in I<len>-sized I<md>.
After calling this function no additional calls to EVP_DigestUpdate() can be
made, but EVP_DigestInit_ex2() can be called to initialize a new operation.
=item EVP_MD_CTX_copy_ex()
Can be used to copy the message digest state from I<in> to I<out>. This is
useful if large amounts of data are to be hashed which only differ in the last
few bytes.
=item EVP_DigestInit()
Behaves in the same way as EVP_DigestInit_ex2() except it doesn't set any
parameters and calls EVP_MD_CTX_reset() so it cannot be used with an I<type>
of NULL.
=item EVP_DigestFinal()
Similar to EVP_DigestFinal_ex() except after computing the digest
the digest context I<ctx> is automatically cleaned up with EVP_MD_CTX_reset().
=item EVP_MD_CTX_copy()
Similar to EVP_MD_CTX_copy_ex() except the destination I<out> does not have to
be initialized.
=item EVP_MD_is_a()
Returns 1 if I<md> is an implementation of an algorithm that's
identifiable with I<name>, otherwise 0.
If I<md> is a legacy digest (it's the return value from the likes of
EVP_sha256() rather than the result of an EVP_MD_fetch()), only cipher
names registered with the default library context (see
L<OSSL_LIB_CTX(3)>) will be considered.
=item EVP_MD_get0_name(),
EVP_MD_CTX_get0_name()
Return the name of the given message digest. For fetched message
digests with multiple names, only one of them is returned; it's
recommended to use EVP_MD_names_do_all() instead.
=item EVP_MD_names_do_all()
Traverses all names for the I<md>, and calls I<fn> with each name and
I<data>. This is only useful with fetched B<EVP_MD>s.
=item EVP_MD_get0_description()
Returns a description of the digest, meant for display and human consumption.
The description is at the discretion of the digest implementation.
=item EVP_MD_get0_provider()
Returns an B<OSSL_PROVIDER> pointer to the provider that implements the given
B<EVP_MD>.
=item EVP_MD_get_size(),
EVP_MD_CTX_get_size()
Return the size of the message digest when passed an B<EVP_MD> or an
B<EVP_MD_CTX> structure, i.e. the size of the hash.
=item EVP_MD_get_block_size(),
EVP_MD_CTX_get_block_size()
Return the block size of the message digest when passed an B<EVP_MD> or an
B<EVP_MD_CTX> structure.
=item EVP_MD_get_type(),
EVP_MD_CTX_get_type()
Return the NID of the OBJECT IDENTIFIER representing the given message digest
when passed an B<EVP_MD> structure. For example, C<EVP_MD_get_type(EVP_sha1())>
returns B<NID_sha1>. This function is normally used when setting ASN1 OIDs.
=item EVP_MD_CTX_get0_md_data()
Return the digest method private data for the passed B<EVP_MD_CTX>.
The space is allocated by OpenSSL and has the size originally set with
EVP_MD_meth_set_app_datasize().
=item EVP_MD_CTX_get0_md(), EVP_MD_CTX_get1_md()
EVP_MD_CTX_get0_md() returns
the B<EVP_MD> structure corresponding to the passed B<EVP_MD_CTX>. This
will be the same B<EVP_MD> object originally passed to EVP_DigestInit_ex2() (or
other similar function) when the EVP_MD_CTX was first initialised. Note that
where explicit fetch is in use (see L<EVP_MD_fetch(3)>) the value returned from
this function will not have its reference count incremented and therefore it
should not be used after the EVP_MD_CTX is freed.
EVP_MD_CTX_get1_md() is the same except the ownership is passed to the
caller and is from the passed B<EVP_MD_CTX>.
=item EVP_MD_CTX_set_update_fn()
Sets the update function for I<ctx> to I<update>.
This is the function that is called by EVP_DigestUpdate(). If not set, the
update function from the B<EVP_MD> type specified at initialization is used.
=item EVP_MD_CTX_update_fn()
Returns the update function for I<ctx>.
=item EVP_MD_get_flags()
Returns the I<md> flags. Note that these are different from the B<EVP_MD_CTX>
ones. See L<EVP_MD_meth_set_flags(3)> for more information.
=item EVP_MD_get_pkey_type()
Returns the NID of the public key signing algorithm associated with this
digest. For example EVP_sha1() is associated with RSA so this will return
B<NID_sha1WithRSAEncryption>. Since digests and signature algorithms are no
longer linked this function is only retained for compatibility reasons.
=item EVP_md_null()
A "null" message digest that does nothing: i.e. the hash it returns is of zero
length.
=item EVP_get_digestbyname(),
EVP_get_digestbynid(),
EVP_get_digestbyobj()
Returns an B<EVP_MD> structure when passed a digest name, a digest B<NID> or an
B<ASN1_OBJECT> structure respectively.
The EVP_get_digestbyname() function is present for backwards compatibility with
OpenSSL prior to version 3 and is different to the EVP_MD_fetch() function
since it does not attempt to "fetch" an implementation of the cipher.
Additionally, it only knows about digests that are built-in to OpenSSL and have
an associated NID. Similarly EVP_get_digestbynid() and EVP_get_digestbyobj()
also return objects without an associated implementation.
When the digest objects returned by these functions are used (such as in a call
to EVP_DigestInit_ex()) an implementation of the digest will be implicitly
fetched from the loaded providers. This fetch could fail if no suitable
implementation is available. Use EVP_MD_fetch() instead to explicitly fetch
the algorithm and an associated implementation from a provider.
See L<crypto(7)/ALGORITHM FETCHING> for more information about fetching.
The digest objects returned from these functions do not need to be freed with
EVP_MD_free().
=item EVP_MD_CTX_get_pkey_ctx()
Returns the B<EVP_PKEY_CTX> assigned to I<ctx>. The returned pointer should not
be freed by the caller.
=item EVP_MD_CTX_set_pkey_ctx()
Assigns an B<EVP_PKEY_CTX> to B<EVP_MD_CTX>. This is usually used to provide
a customized B<EVP_PKEY_CTX> to L<EVP_DigestSignInit(3)> or
L<EVP_DigestVerifyInit(3)>. The I<pctx> passed to this function should be freed
by the caller. A NULL I<pctx> pointer is also allowed to clear the B<EVP_PKEY_CTX>
assigned to I<ctx>. In such case, freeing the cleared B<EVP_PKEY_CTX> or not
depends on how the B<EVP_PKEY_CTX> is created.
=item EVP_MD_do_all_provided()
Traverses all messages digests implemented by all activated providers
in the given library context I<libctx>, and for each of the implementations,
calls the given function I<fn> with the implementation method and the given
I<arg> as argument.
=back
=head1 PARAMETERS
See L<OSSL_PARAM(3)> for information about passing parameters.
EVP_MD_CTX_set_params() can be used with the following OSSL_PARAM keys:
=over 4
=item "xoflen" (B<OSSL_DIGEST_PARAM_XOFLEN>) <unsigned integer>
Sets the digest length for extendable output functions.
It is used by the SHAKE algorithm and should not exceed what can be given
using a B<size_t>.
=item "pad-type" (B<OSSL_DIGEST_PARAM_PAD_TYPE>) <unsigned integer>
Sets the padding type.
It is used by the MDC2 algorithm.
=back
EVP_MD_CTX_get_params() can be used with the following OSSL_PARAM keys:
=over 4
-=item "micalg" (B<OSSL_PARAM_DIGEST_KEY_MICALG>) <UTF8 string>.
+=item "micalg" (B<OSSL_DIGEST_PARAM_MICALG>) <UTF8 string>.
Gets the digest Message Integrity Check algorithm string. This is used when
creating S/MIME multipart/signed messages, as specified in RFC 3851.
It may be used by external engines or providers.
=back
=head1 CONTROLS
EVP_MD_CTX_ctrl() can be used to send the following standard controls:
=over 4
=item EVP_MD_CTRL_MICALG
Gets the digest Message Integrity Check algorithm string. This is used when
creating S/MIME multipart/signed messages, as specified in RFC 3851.
The string value is written to I<p2>.
When used with a fetched B<EVP_MD>, EVP_MD_CTX_get_params() gets called with
an L<OSSL_PARAM(3)> item with the key "micalg" (B<OSSL_DIGEST_PARAM_MICALG>).
=item EVP_MD_CTRL_XOF_LEN
This control sets the digest length for extendable output functions to I<p1>.
Sending this control directly should not be necessary, the use of
EVP_DigestFinalXOF() is preferred.
Currently used by SHAKE.
When used with a fetched B<EVP_MD>, EVP_MD_CTX_get_params() gets called with
an L<OSSL_PARAM(3)> item with the key "xoflen" (B<OSSL_DIGEST_PARAM_XOFLEN>).
=back
=head1 FLAGS
EVP_MD_CTX_set_flags(), EVP_MD_CTX_clear_flags() and EVP_MD_CTX_test_flags()
can be used the manipulate and test these B<EVP_MD_CTX> flags:
=over 4
=item EVP_MD_CTX_FLAG_ONESHOT
This flag instructs the digest to optimize for one update only, if possible.
=for comment EVP_MD_CTX_FLAG_CLEANED is internal, don't mention it
=for comment EVP_MD_CTX_FLAG_REUSE is internal, don't mention it
=for comment We currently avoid documenting flags that are only bit holder:
EVP_MD_CTX_FLAG_NON_FIPS_ALLOW, EVP_MD_CTX_FLAGS_PAD_*
=item EVP_MD_CTX_FLAG_NO_INIT
This flag instructs EVP_DigestInit() and similar not to initialise the
implementation specific data.
=item EVP_MD_CTX_FLAG_FINALISE
Some functions such as EVP_DigestSign only finalise copies of internal
contexts so additional data can be included after the finalisation call.
This is inefficient if this functionality is not required, and can be
disabled with this flag.
=back
=head1 RETURN VALUES
=over 4
=item EVP_MD_fetch()
Returns a pointer to a B<EVP_MD> for success or NULL for failure.
=item EVP_MD_up_ref()
Returns 1 for success or 0 for failure.
=item EVP_Q_digest(),
EVP_Digest(),
EVP_DigestInit_ex2(),
EVP_DigestInit_ex(),
EVP_DigestInit(),
EVP_DigestUpdate(),
EVP_DigestFinal_ex(),
EVP_DigestFinalXOF(), and
EVP_DigestFinal()
return 1 for
success and 0 for failure.
=item EVP_MD_CTX_ctrl()
Returns 1 if successful or 0 for failure.
=item EVP_MD_CTX_set_params(),
EVP_MD_CTX_get_params()
Returns 1 if successful or 0 for failure.
=item EVP_MD_CTX_settable_params(),
EVP_MD_CTX_gettable_params()
Return an array of constant L<OSSL_PARAM(3)>s, or NULL if there is none
to get.
=item EVP_MD_CTX_copy_ex()
Returns 1 if successful or 0 for failure.
=item EVP_MD_get_type(),
EVP_MD_get_pkey_type()
Returns the NID of the corresponding OBJECT IDENTIFIER or NID_undef if none
exists.
=item EVP_MD_get_size(),
EVP_MD_get_block_size(),
EVP_MD_CTX_get_size(),
EVP_MD_CTX_get_block_size()
Returns the digest or block size in bytes or -1 for failure.
=item EVP_md_null()
Returns a pointer to the B<EVP_MD> structure of the "null" message digest.
=item EVP_get_digestbyname(),
EVP_get_digestbynid(),
EVP_get_digestbyobj()
Returns either an B<EVP_MD> structure or NULL if an error occurs.
=item EVP_MD_CTX_set_pkey_ctx()
This function has no return value.
=item EVP_MD_names_do_all()
Returns 1 if the callback was called for all names. A return value of 0 means
that the callback was not called for any names.
=back
=head1 NOTES
The B<EVP> interface to message digests should almost always be used in
preference to the low-level interfaces. This is because the code then becomes
transparent to the digest used and much more flexible.
New applications should use the SHA-2 (such as L<EVP_sha256(3)>) or the SHA-3
digest algorithms (such as L<EVP_sha3_512(3)>). The other digest algorithms
are still in common use.
For most applications the I<impl> parameter to EVP_DigestInit_ex() will be
set to NULL to use the default digest implementation.
Ignoring failure returns of EVP_DigestInit_ex(), EVP_DigestInit_ex2(), or
EVP_DigestInit() can lead to undefined behavior on subsequent calls
updating or finalizing the B<EVP_MD_CTX> such as the EVP_DigestUpdate() or
EVP_DigestFinal() functions. The only valid calls on the B<EVP_MD_CTX>
when initialization fails are calls that attempt another initialization of
the context or release the context.
The functions EVP_DigestInit(), EVP_DigestFinal() and EVP_MD_CTX_copy() are
obsolete but are retained to maintain compatibility with existing code. New
applications should use EVP_DigestInit_ex(), EVP_DigestFinal_ex() and
EVP_MD_CTX_copy_ex() because they can efficiently reuse a digest context
instead of initializing and cleaning it up on each call and allow non default
implementations of digests to be specified.
If digest contexts are not cleaned up after use,
memory leaks will occur.
EVP_MD_CTX_get0_name(), EVP_MD_CTX_get_size(), EVP_MD_CTX_get_block_size(),
EVP_MD_CTX_get_type(), EVP_get_digestbynid() and EVP_get_digestbyobj() are
defined as macros.
EVP_MD_CTX_ctrl() sends commands to message digests for additional configuration
or control.
=head1 EXAMPLES
This example digests the data "Test Message\n" and "Hello World\n", using the
digest name passed on the command line.
#include <stdio.h>
#include <string.h>
#include <openssl/evp.h>
int main(int argc, char *argv[])
{
EVP_MD_CTX *mdctx;
const EVP_MD *md;
char mess1[] = "Test Message\n";
char mess2[] = "Hello World\n";
unsigned char md_value[EVP_MAX_MD_SIZE];
unsigned int md_len, i;
if (argv[1] == NULL) {
printf("Usage: mdtest digestname\n");
exit(1);
}
md = EVP_get_digestbyname(argv[1]);
if (md == NULL) {
printf("Unknown message digest %s\n", argv[1]);
exit(1);
}
mdctx = EVP_MD_CTX_new();
if (!EVP_DigestInit_ex2(mdctx, md, NULL)) {
printf("Message digest initialization failed.\n");
EVP_MD_CTX_free(mdctx);
exit(1);
}
if (!EVP_DigestUpdate(mdctx, mess1, strlen(mess1))) {
printf("Message digest update failed.\n");
EVP_MD_CTX_free(mdctx);
exit(1);
}
if (!EVP_DigestUpdate(mdctx, mess2, strlen(mess2))) {
printf("Message digest update failed.\n");
EVP_MD_CTX_free(mdctx);
exit(1);
}
if (!EVP_DigestFinal_ex(mdctx, md_value, &md_len)) {
printf("Message digest finalization failed.\n");
EVP_MD_CTX_free(mdctx);
exit(1);
}
EVP_MD_CTX_free(mdctx);
printf("Digest is: ");
for (i = 0; i < md_len; i++)
printf("%02x", md_value[i]);
printf("\n");
exit(0);
}
=head1 SEE ALSO
L<EVP_MD_meth_new(3)>,
L<openssl-dgst(1)>,
L<evp(7)>,
L<OSSL_PROVIDER(3)>,
L<OSSL_PARAM(3)>,
L<property(7)>,
L<crypto(7)/ALGORITHM FETCHING>,
L<provider-digest(7)>,
L<life_cycle-digest(7)>
The full list of digest algorithms are provided below.
L<EVP_blake2b512(3)>,
L<EVP_md2(3)>,
L<EVP_md4(3)>,
L<EVP_md5(3)>,
L<EVP_mdc2(3)>,
L<EVP_ripemd160(3)>,
L<EVP_sha1(3)>,
L<EVP_sha224(3)>,
L<EVP_sha3_224(3)>,
L<EVP_sm3(3)>,
L<EVP_whirlpool(3)>
=head1 HISTORY
The EVP_MD_CTX_create() and EVP_MD_CTX_destroy() functions were renamed to
EVP_MD_CTX_new() and EVP_MD_CTX_free() in OpenSSL 1.1.0, respectively.
The link between digests and signing algorithms was fixed in OpenSSL 1.0 and
later, so now EVP_sha1() can be used with RSA and DSA.
The EVP_dss1() function was removed in OpenSSL 1.1.0.
The EVP_MD_CTX_set_pkey_ctx() function was added in OpenSSL 1.1.1.
The EVP_Q_digest(), EVP_DigestInit_ex2(),
EVP_MD_fetch(), EVP_MD_free(), EVP_MD_up_ref(),
EVP_MD_get_params(), EVP_MD_CTX_set_params(), EVP_MD_CTX_get_params(),
EVP_MD_gettable_params(), EVP_MD_gettable_ctx_params(),
EVP_MD_settable_ctx_params(), EVP_MD_CTX_settable_params() and
EVP_MD_CTX_gettable_params() functions were added in OpenSSL 3.0.
The EVP_MD_type(), EVP_MD_nid(), EVP_MD_name(), EVP_MD_pkey_type(),
EVP_MD_size(), EVP_MD_block_size(), EVP_MD_flags(), EVP_MD_CTX_size(),
EVP_MD_CTX_block_size(), EVP_MD_CTX_type(), and EVP_MD_CTX_md_data()
functions were renamed to include C<get> or C<get0> in their names in
OpenSSL 3.0, respectively. The old names are kept as non-deprecated
alias macros.
The EVP_MD_CTX_md() function was deprecated in OpenSSL 3.0; use
EVP_MD_CTX_get0_md() instead.
EVP_MD_CTX_update_fn() and EVP_MD_CTX_set_update_fn() were deprecated
in OpenSSL 3.0.
=head1 COPYRIGHT
-Copyright 2000-2023 The OpenSSL Project Authors. All Rights Reserved.
+Copyright 2000-2024 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<https://www.openssl.org/source/license.html>.
=cut
diff --git a/crypto/openssl/doc/man3/EVP_KDF.pod b/crypto/openssl/doc/man3/EVP_KDF.pod
index 31d61b2a3df0..9447651a340e 100644
--- a/crypto/openssl/doc/man3/EVP_KDF.pod
+++ b/crypto/openssl/doc/man3/EVP_KDF.pod
@@ -1,314 +1,314 @@
=pod
=head1 NAME
EVP_KDF, EVP_KDF_fetch, EVP_KDF_free, EVP_KDF_up_ref,
EVP_KDF_CTX, EVP_KDF_CTX_new, EVP_KDF_CTX_free, EVP_KDF_CTX_dup,
EVP_KDF_CTX_reset, EVP_KDF_derive,
EVP_KDF_CTX_get_kdf_size,
EVP_KDF_get0_provider, EVP_KDF_CTX_kdf, EVP_KDF_is_a,
EVP_KDF_get0_name, EVP_KDF_names_do_all, EVP_KDF_get0_description,
EVP_KDF_CTX_get_params, EVP_KDF_CTX_set_params, EVP_KDF_do_all_provided,
EVP_KDF_get_params, EVP_KDF_gettable_params,
EVP_KDF_gettable_ctx_params, EVP_KDF_settable_ctx_params,
EVP_KDF_CTX_gettable_params, EVP_KDF_CTX_settable_params - EVP KDF routines
=head1 SYNOPSIS
#include <openssl/kdf.h>
typedef struct evp_kdf_st EVP_KDF;
typedef struct evp_kdf_ctx_st EVP_KDF_CTX;
- EVP_KDF_CTX *EVP_KDF_CTX_new(const EVP_KDF *kdf);
+ EVP_KDF_CTX *EVP_KDF_CTX_new(EVP_KDF *kdf);
const EVP_KDF *EVP_KDF_CTX_kdf(EVP_KDF_CTX *ctx);
void EVP_KDF_CTX_free(EVP_KDF_CTX *ctx);
EVP_KDF_CTX *EVP_KDF_CTX_dup(const EVP_KDF_CTX *src);
void EVP_KDF_CTX_reset(EVP_KDF_CTX *ctx);
size_t EVP_KDF_CTX_get_kdf_size(EVP_KDF_CTX *ctx);
int EVP_KDF_derive(EVP_KDF_CTX *ctx, unsigned char *key, size_t keylen,
const OSSL_PARAM params[]);
int EVP_KDF_up_ref(EVP_KDF *kdf);
void EVP_KDF_free(EVP_KDF *kdf);
EVP_KDF *EVP_KDF_fetch(OSSL_LIB_CTX *libctx, const char *algorithm,
const char *properties);
int EVP_KDF_is_a(const EVP_KDF *kdf, const char *name);
const char *EVP_KDF_get0_name(const EVP_KDF *kdf);
const char *EVP_KDF_get0_description(const EVP_KDF *kdf);
const OSSL_PROVIDER *EVP_KDF_get0_provider(const EVP_KDF *kdf);
void EVP_KDF_do_all_provided(OSSL_LIB_CTX *libctx,
void (*fn)(EVP_KDF *kdf, void *arg),
void *arg);
int EVP_KDF_names_do_all(const EVP_KDF *kdf,
void (*fn)(const char *name, void *data),
void *data);
int EVP_KDF_get_params(EVP_KDF *kdf, OSSL_PARAM params[]);
int EVP_KDF_CTX_get_params(EVP_KDF_CTX *ctx, OSSL_PARAM params[]);
int EVP_KDF_CTX_set_params(EVP_KDF_CTX *ctx, const OSSL_PARAM params[]);
const OSSL_PARAM *EVP_KDF_gettable_params(const EVP_KDF *kdf);
const OSSL_PARAM *EVP_KDF_gettable_ctx_params(const EVP_KDF *kdf);
const OSSL_PARAM *EVP_KDF_settable_ctx_params(const EVP_KDF *kdf);
const OSSL_PARAM *EVP_KDF_CTX_gettable_params(const EVP_KDF *kdf);
const OSSL_PARAM *EVP_KDF_CTX_settable_params(const EVP_KDF *kdf);
const OSSL_PROVIDER *EVP_KDF_get0_provider(const EVP_KDF *kdf);
=head1 DESCRIPTION
The EVP KDF routines are a high-level interface to Key Derivation Function
algorithms and should be used instead of algorithm-specific functions.
After creating a B<EVP_KDF_CTX> for the required algorithm using
EVP_KDF_CTX_new(), inputs to the algorithm are supplied either by
passing them as part of the EVP_KDF_derive() call or using calls
to EVP_KDF_CTX_set_params() before calling EVP_KDF_derive() to derive
the key.
=head2 Types
B<EVP_KDF> is a type that holds the implementation of a KDF.
B<EVP_KDF_CTX> is a context type that holds the algorithm inputs.
=head2 Algorithm implementation fetching
EVP_KDF_fetch() fetches an implementation of a KDF I<algorithm>, given
a library context I<libctx> and a set of I<properties>.
See L<crypto(7)/ALGORITHM FETCHING> for further information.
See L<OSSL_PROVIDER-default(7)/Key Derivation Function (KDF)> for the lists of
algorithms supported by the default provider.
The returned value must eventually be freed with
L<EVP_KDF_free(3)>.
EVP_KDF_up_ref() increments the reference count of an already fetched
KDF.
EVP_KDF_free() frees a fetched algorithm.
NULL is a valid parameter, for which this function is a no-op.
=head2 Context manipulation functions
EVP_KDF_CTX_new() creates a new context for the KDF implementation I<kdf>.
EVP_KDF_CTX_free() frees up the context I<ctx>. If I<ctx> is NULL, nothing
is done.
EVP_KDF_CTX_kdf() returns the B<EVP_KDF> associated with the context
I<ctx>.
=head2 Computing functions
EVP_KDF_CTX_reset() resets the context to the default state as if the context
had just been created.
EVP_KDF_derive() processes any parameters in I<Params> and then derives
I<keylen> bytes of key material and places it in the I<key> buffer.
If the algorithm produces a fixed amount of output then an error will
occur unless the I<keylen> parameter is equal to that output size,
as returned by EVP_KDF_CTX_get_kdf_size().
EVP_KDF_get_params() retrieves details about the implementation
I<kdf>.
The set of parameters given with I<params> determine exactly what
parameters should be retrieved.
Note that a parameter that is unknown in the underlying context is
simply ignored.
EVP_KDF_CTX_get_params() retrieves chosen parameters, given the
context I<ctx> and its underlying context.
The set of parameters given with I<params> determine exactly what
parameters should be retrieved.
Note that a parameter that is unknown in the underlying context is
simply ignored.
EVP_KDF_CTX_set_params() passes chosen parameters to the underlying
context, given a context I<ctx>.
The set of parameters given with I<params> determine exactly what
parameters are passed down.
Note that a parameter that is unknown in the underlying context is
simply ignored.
Also, what happens when a needed parameter isn't passed down is
defined by the implementation.
EVP_KDF_gettable_params() returns an L<OSSL_PARAM(3)> array that describes
the retrievable and settable parameters. EVP_KDF_gettable_params()
returns parameters that can be used with EVP_KDF_get_params().
EVP_KDF_gettable_ctx_params() and EVP_KDF_CTX_gettable_params()
return constant L<OSSL_PARAM(3)> arrays that describe the retrievable
parameters that can be used with EVP_KDF_CTX_get_params().
EVP_KDF_gettable_ctx_params() returns the parameters that can be retrieved
from the algorithm, whereas EVP_KDF_CTX_gettable_params() returns
the parameters that can be retrieved in the context's current state.
EVP_KDF_settable_ctx_params() and EVP_KDF_CTX_settable_params() return
constant L<OSSL_PARAM(3)> arrays that describe the settable parameters that
can be used with EVP_KDF_CTX_set_params(). EVP_KDF_settable_ctx_params()
returns the parameters that can be retrieved from the algorithm,
whereas EVP_KDF_CTX_settable_params() returns the parameters that can
be retrieved in the context's current state.
=head2 Information functions
EVP_KDF_CTX_get_kdf_size() returns the output size if the algorithm produces a fixed amount
of output and B<SIZE_MAX> otherwise. If an error occurs then 0 is returned.
For some algorithms an error may result if input parameters necessary to
calculate a fixed output size have not yet been supplied.
EVP_KDF_is_a() returns 1 if I<kdf> is an implementation of an
algorithm that's identifiable with I<name>, otherwise 0.
EVP_KDF_get0_provider() returns the provider that holds the implementation
of the given I<kdf>.
EVP_KDF_do_all_provided() traverses all KDF implemented by all activated
providers in the given library context I<libctx>, and for each of the
implementations, calls the given function I<fn> with the implementation method
and the given I<arg> as argument.
EVP_KDF_get0_name() return the name of the given KDF. For fetched KDFs
with multiple names, only one of them is returned; it's
recommended to use EVP_KDF_names_do_all() instead.
EVP_KDF_names_do_all() traverses all names for I<kdf>, and calls
I<fn> with each name and I<data>.
EVP_KDF_get0_description() returns a description of the I<kdf>, meant for
display and human consumption. The description is at the discretion of
the I<kdf> implementation.
=head1 PARAMETERS
The standard parameter names are:
=over 4
=item "pass" (B<OSSL_KDF_PARAM_PASSWORD>) <octet string>
Some KDF implementations require a password.
For those KDF implementations that support it, this parameter sets the password.
=item "salt" (B<OSSL_KDF_PARAM_SALT>) <octet string>
Some KDF implementations can take a non-secret unique cryptographic salt.
For those KDF implementations that support it, this parameter sets the salt.
The default value, if any, is implementation dependent.
=item "iter" (B<OSSL_KDF_PARAM_ITER>) <unsigned integer>
Some KDF implementations require an iteration count.
For those KDF implementations that support it, this parameter sets the
iteration count.
The default value, if any, is implementation dependent.
=item "properties" (B<OSSL_KDF_PARAM_PROPERTIES>) <UTF8 string>
=item "mac" (B<OSSL_KDF_PARAM_MAC>) <UTF8 string>
=item "digest" (B<OSSL_KDF_PARAM_DIGEST>) <UTF8 string>
=item "cipher" (B<OSSL_KDF_PARAM_CIPHER>) <UTF8 string>
For KDF implementations that use an underlying computation MAC, digest or
cipher, these parameters set what the algorithm should be.
The value is always the name of the intended algorithm,
or the properties.
Note that not all algorithms may support all possible underlying
implementations.
=item "key" (B<OSSL_KDF_PARAM_KEY>) <octet string>
Some KDF implementations require a key.
For those KDF implementations that support it, this octet string parameter
sets the key.
=item "info" (B<OSSL_KDF_PARAM_INFO>) <octet string>
Some KDF implementations, such as L<EVP_KDF-HKDF(7)>, take an 'info' parameter
for binding the derived key material
to application- and context-specific information.
This parameter sets the info, fixed info, other info or shared info argument.
You can specify this parameter multiple times, and each instance will
be concatenated to form the final value.
=item "maclen" (B<OSSL_KDF_PARAM_MAC_SIZE>) <unsigned integer>
Used by implementations that use a MAC with a variable output size (KMAC).
For those KDF implementations that support it, this parameter
sets the MAC output size.
The default value, if any, is implementation dependent.
The length must never exceed what can be given with a B<size_t>.
=item "maxmem_bytes" (B<OSSL_KDF_PARAM_SCRYPT_MAXMEM>) <unsigned integer>
Memory-hard password-based KDF algorithms, such as scrypt, use an amount of
memory that depends on the load factors provided as input.
For those KDF implementations that support it, this B<uint64_t> parameter sets
an upper limit on the amount of memory that may be consumed while performing
a key derivation.
If this memory usage limit is exceeded because the load factors are chosen
too high, the key derivation will fail.
The default value is implementation dependent.
The memory size must never exceed what can be given with a B<size_t>.
=back
=head1 RETURN VALUES
EVP_KDF_fetch() returns a pointer to a newly fetched B<EVP_KDF>, or
NULL if allocation failed.
EVP_KDF_get0_provider() returns a pointer to the provider for the KDF, or
NULL on error.
EVP_KDF_up_ref() returns 1 on success, 0 on error.
EVP_KDF_CTX_new() returns either the newly allocated
B<EVP_KDF_CTX> structure or NULL if an error occurred.
EVP_KDF_CTX_free() and EVP_KDF_CTX_reset() do not return a value.
EVP_KDF_CTX_get_kdf_size() returns the output size. B<SIZE_MAX> is returned to indicate
that the algorithm produces a variable amount of output; 0 to indicate failure.
EVP_KDF_get0_name() returns the name of the KDF, or NULL on error.
EVP_KDF_names_do_all() returns 1 if the callback was called for all names. A
return value of 0 means that the callback was not called for any names.
The remaining functions return 1 for success and 0 or a negative value for
failure. In particular, a return value of -2 indicates the operation is not
supported by the KDF algorithm.
=head1 NOTES
The KDF life-cycle is described in L<life_cycle-kdf(7)>. In the future,
the transitions described there will be enforced. When this is done, it will
not be considered a breaking change to the API.
=head1 SEE ALSO
L<OSSL_PROVIDER-default(7)/Key Derivation Function (KDF)>,
L<life_cycle-kdf(7)>.
=head1 HISTORY
This functionality was added in OpenSSL 3.0.
=head1 COPYRIGHT
-Copyright 2019-2023 The OpenSSL Project Authors. All Rights Reserved.
+Copyright 2019-2024 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<https://www.openssl.org/source/license.html>.
=cut
diff --git a/crypto/openssl/doc/man3/EVP_PKEY_CTX_set_params.pod b/crypto/openssl/doc/man3/EVP_PKEY_CTX_set_params.pod
index c02151654c3a..8947648ccbe6 100644
--- a/crypto/openssl/doc/man3/EVP_PKEY_CTX_set_params.pod
+++ b/crypto/openssl/doc/man3/EVP_PKEY_CTX_set_params.pod
@@ -1,94 +1,96 @@
=pod
=head1 NAME
EVP_PKEY_CTX_set_params,
EVP_PKEY_CTX_settable_params,
EVP_PKEY_CTX_get_params,
EVP_PKEY_CTX_gettable_params
- provider parameter passing operations
=head1 SYNOPSIS
#include <openssl/evp.h>
int EVP_PKEY_CTX_set_params(EVP_PKEY_CTX *ctx, const OSSL_PARAM *params);
const OSSL_PARAM *EVP_PKEY_CTX_settable_params(const EVP_PKEY_CTX *ctx);
int EVP_PKEY_CTX_get_params(EVP_PKEY_CTX *ctx, OSSL_PARAM *params);
const OSSL_PARAM *EVP_PKEY_CTX_gettable_params(const EVP_PKEY_CTX *ctx);
=head1 DESCRIPTION
The EVP_PKEY_CTX_get_params() and EVP_PKEY_CTX_set_params() functions allow
transfer of arbitrary key parameters to and from providers.
Not all parameters may be supported by all providers.
See L<OSSL_PROVIDER(3)> for more information on providers.
-See L<OSSL_PARAM(3)> for more information on parameters.
+The I<params> field is a pointer to a list of B<OSSL_PARAM> structures,
+terminated with a L<OSSL_PARAM_END(3)> struct.
+See L<OSSL_PARAM(3)> for information about passing parameters.
These functions must only be called after the EVP_PKEY_CTX has been initialised
for use in an operation.
These methods replace the EVP_PKEY_CTX_ctrl() mechanism. (EVP_PKEY_CTX_ctrl now
calls these methods internally to interact with providers).
EVP_PKEY_CTX_gettable_params() and EVP_PKEY_CTX_settable_params() get a
constant L<OSSL_PARAM(3)> array that describes the gettable and
settable parameters for the current algorithm implementation, i.e. parameters
that can be used with EVP_PKEY_CTX_get_params() and EVP_PKEY_CTX_set_params()
respectively.
These functions must only be called after the EVP_PKEY_CTX has been initialised
for use in an operation.
=head2 Parameters
Examples of EVP_PKEY parameters include the following:
L<provider-keymgmt(7)/Common parameters>
L<provider-keyexch(7)/Key Exchange parameters>
L<provider-signature(7)/Signature parameters>
L<EVP_PKEY-RSA(7)/Common RSA parameters>
L<EVP_PKEY-RSA(7)/RSA key generation parameters>
L<EVP_PKEY-FFC(7)/FFC parameters>
L<EVP_PKEY-FFC(7)/FFC key generation parameters>
L<EVP_PKEY-DSA(7)/DSA parameters>
L<EVP_PKEY-DSA(7)/DSA key generation parameters>
L<EVP_PKEY-DH(7)/DH parameters>
L<EVP_PKEY-DH(7)/DH key generation parameters>
L<EVP_PKEY-EC(7)/Common EC parameters>
L<EVP_PKEY-X25519(7)/Common X25519, X448, ED25519 and ED448 parameters>
=head1 RETURN VALUES
EVP_PKEY_CTX_set_params() returns 1 for success or 0 otherwise.
EVP_PKEY_CTX_settable_params() returns an OSSL_PARAM array on success or NULL on
error.
It may also return NULL if there are no settable parameters available.
All other functions and macros described on this page return a positive value
for success and 0 or a negative value for failure. In particular a return value
of -2 indicates the operation is not supported by the public key algorithm.
=head1 SEE ALSO
L<EVP_PKEY_CTX_new(3)>,
L<EVP_PKEY_encrypt(3)>,
L<EVP_PKEY_decrypt(3)>,
L<EVP_PKEY_sign(3)>,
L<EVP_PKEY_verify(3)>,
L<EVP_PKEY_verify_recover(3)>,
L<EVP_PKEY_derive(3)>,
L<EVP_PKEY_keygen(3)>
=head1 HISTORY
All functions were added in OpenSSL 3.0.
=head1 COPYRIGHT
-Copyright 2020-2021 The OpenSSL Project Authors. All Rights Reserved.
+Copyright 2020-2024 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<https://www.openssl.org/source/license.html>.
=cut
diff --git a/crypto/openssl/doc/man3/EVP_PKEY_check.pod b/crypto/openssl/doc/man3/EVP_PKEY_check.pod
index a16fdbbd508f..04751f0bd5c7 100644
--- a/crypto/openssl/doc/man3/EVP_PKEY_check.pod
+++ b/crypto/openssl/doc/man3/EVP_PKEY_check.pod
@@ -1,96 +1,101 @@
=pod
=head1 NAME
EVP_PKEY_check, EVP_PKEY_param_check, EVP_PKEY_param_check_quick,
EVP_PKEY_public_check, EVP_PKEY_public_check_quick, EVP_PKEY_private_check,
EVP_PKEY_pairwise_check
- key and parameter validation functions
=head1 SYNOPSIS
#include <openssl/evp.h>
int EVP_PKEY_check(EVP_PKEY_CTX *ctx);
int EVP_PKEY_param_check(EVP_PKEY_CTX *ctx);
int EVP_PKEY_param_check_quick(EVP_PKEY_CTX *ctx);
int EVP_PKEY_public_check(EVP_PKEY_CTX *ctx);
int EVP_PKEY_public_check_quick(EVP_PKEY_CTX *ctx);
int EVP_PKEY_private_check(EVP_PKEY_CTX *ctx);
int EVP_PKEY_pairwise_check(EVP_PKEY_CTX *ctx);
=head1 DESCRIPTION
EVP_PKEY_param_check() validates the parameters component of the key
given by B<ctx>. This check will always succeed for key types that do not have
parameters.
EVP_PKEY_param_check_quick() validates the parameters component of the key
given by B<ctx> like EVP_PKEY_param_check() does. However some algorithm
implementations may offer a quicker form of validation that omits some checks in
order to perform a lightweight sanity check of the key. If a quicker form is not
provided then this function call does the same thing as EVP_PKEY_param_check().
EVP_PKEY_public_check() validates the public component of the key given by B<ctx>.
EVP_PKEY_public_check_quick() validates the public component of the key
given by B<ctx> like EVP_PKEY_public_check() does. However some algorithm
implementations may offer a quicker form of validation that omits some checks in
order to perform a lightweight sanity check of the key. If a quicker form is not
provided then this function call does the same thing as EVP_PKEY_public_check().
EVP_PKEY_private_check() validates the private component of the key given by B<ctx>.
EVP_PKEY_pairwise_check() validates that the public and private components have
the correct mathematical relationship to each other for the key given by B<ctx>.
EVP_PKEY_check() is an alias for the EVP_PKEY_pairwise_check() function.
=head1 NOTES
Key validation used by the OpenSSL FIPS provider complies with the rules
within SP800-56A and SP800-56B. For backwards compatibility reasons the OpenSSL
default provider may use checks that are not as restrictive for certain key types.
For further information see L<EVP_PKEY-DSA(7)/DSA key validation>,
L<EVP_PKEY-DH(7)/DH key validation>, L<EVP_PKEY-EC(7)/EC key validation> and
L<EVP_PKEY-RSA(7)/RSA key validation>.
Refer to SP800-56A and SP800-56B for rules relating to when these functions
should be called during key establishment.
It is not necessary to call these functions after locally calling an approved key
generation method, but may be required for assurance purposes when receiving
keys from a third party.
+The EVP_PKEY_pairwise_check() and EVP_PKEY_private_check() might not be bounded
+by any key size limits as private keys are not expected to be supplied by
+attackers. For that reason they might take an unbounded time if run on
+arbitrarily large keys.
+
=head1 RETURN VALUES
All functions return 1 for success or others for failure.
They return -2 if the operation is not supported for the specific algorithm.
=head1 SEE ALSO
L<EVP_PKEY_CTX_new(3)>,
L<EVP_PKEY_fromdata(3)>,
L<EVP_PKEY-DH(7)>,
L<EVP_PKEY-FFC(7)>,
L<EVP_PKEY-DSA(7)>,
L<EVP_PKEY-EC(7)>,
L<EVP_PKEY-RSA(7)>,
=head1 HISTORY
EVP_PKEY_check(), EVP_PKEY_public_check() and EVP_PKEY_param_check() were added
in OpenSSL 1.1.1.
EVP_PKEY_param_check_quick(), EVP_PKEY_public_check_quick(),
EVP_PKEY_private_check() and EVP_PKEY_pairwise_check() were added in OpenSSL 3.0.
=head1 COPYRIGHT
-Copyright 2006-2022 The OpenSSL Project Authors. All Rights Reserved.
+Copyright 2006-2024 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<https://www.openssl.org/source/license.html>.
=cut
diff --git a/crypto/openssl/doc/man3/SSL_CIPHER_get_name.pod b/crypto/openssl/doc/man3/SSL_CIPHER_get_name.pod
index e22a85a06370..09b7280bdd58 100644
--- a/crypto/openssl/doc/man3/SSL_CIPHER_get_name.pod
+++ b/crypto/openssl/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 <openssl/ssl.h>
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);
=head1 DESCRIPTION
SSL_CIPHER_get_name() returns a pointer to the name of B<cipher>. If the
B<cipher> is NULL, it returns "(NONE)".
SSL_CIPHER_standard_name() returns a pointer to the standard RFC name of
B<cipher>. If the B<cipher> is NULL, it returns "(NONE)". If the B<cipher>
has no standard name, it returns B<NULL>. If B<cipher> was defined in both
SSLv3 and TLS, it returns the TLS name.
OPENSSL_cipher_name() returns a pointer to the OpenSSL name of B<stdname>.
If the B<stdname> is NULL, or B<stdname> has no corresponding OpenSSL name,
it returns "(NONE)". Where both exist, B<stdname> should be the TLS name rather
than the SSLv3 name.
SSL_CIPHER_get_bits() returns the number of secret bits used for B<cipher>.
If B<cipher> 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<cipher> is NULL.
SSL_CIPHER_get_cipher_nid() returns the cipher NID corresponding to B<c>.
If there is no cipher (e.g. for cipher suites with no encryption) then
B<NID_undef> is returned.
SSL_CIPHER_get_digest_nid() returns the digest NID corresponding to the MAC
used by B<c> during record encryption/decryption. If there is no digest (e.g.
for AEAD cipher suites) then B<NID_undef> 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<c>. 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<c>. If there is no key exchange, then B<NID_undef> is returned.
If any appropriate key exchange algorithm can be used (as in the case of TLS 1.3
cipher suites) B<NID_kx_any> 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<c>. If there is no authentication, then B<NID_undef> is returned.
If any appropriate authentication algorithm can be used (as in the case of
TLS 1.3 cipher suites) B<NID_auth_any> is returned. Examples (not comprehensive):
NID_auth_rsa
NID_auth_ecdsa
NID_auth_psk
SSL_CIPHER_is_aead() returns 1 if the cipher B<c> is AEAD (e.g. GCM or
ChaCha20/Poly1305), and 0 if it is not AEAD.
SSL_CIPHER_find() returns a B<SSL_CIPHER> structure which has the cipher ID stored
in B<ptr>. The B<ptr> parameter is a two element array of B<char>, 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_client_hello_get0_ciphers(3)>. 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<c>. 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<c>.
SSL_CIPHER_description() returns a textual description of the cipher used
into the buffer B<buf> of length B<len> provided. If B<buf> is provided, it
-must be at least 128 bytes, otherwise a buffer will be allocated using
+must be at least 128 bytes. If B<buf> is NULL it will be allocated using
OPENSSL_malloc(). If the provided buffer is too small, or the allocation fails,
B<NULL> is returned.
The string returned by SSL_CIPHER_description() consists of several fields
separated by whitespace:
=over 4
=item <ciphername>
Textual representation of the cipher name.
=item <protocol version>
The minimum protocol version that the ciphersuite supports, such as B<TLSv1.2>.
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>
Key exchange method such as B<RSA>, B<ECDHE>, etc.
=item Au=<authentication>
Authentication method such as B<RSA>, B<None>, etc.. None is the
representation of anonymous ciphers.
=item Enc=<symmetric encryption method>
Encryption method, with number of secret bits, such as B<AESGCM(128)>.
=item Mac=<message authentication code>
Message digest, such as B<SHA256>.
=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<NID_undef> if an error occurred.
SSL_CIPHER_get_handshake_digest() returns a valid B<EVP_MD> 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<SSL_CIPHER> 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<ssl(7)>, L<SSL_get_current_cipher(3)>,
L<SSL_get_ciphers(3)>, L<openssl-ciphers(1)>
=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<NULL> 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<enable-ssl-trace> 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-2021 The OpenSSL Project Authors. All Rights Reserved.
+Copyright 2000-2024 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<https://www.openssl.org/source/license.html>.
=cut
diff --git a/crypto/openssl/doc/man3/SSL_CTX_set_cert_store.pod b/crypto/openssl/doc/man3/SSL_CTX_set_cert_store.pod
index f1fef9e649cd..246f413136b6 100644
--- a/crypto/openssl/doc/man3/SSL_CTX_set_cert_store.pod
+++ b/crypto/openssl/doc/man3/SSL_CTX_set_cert_store.pod
@@ -1,89 +1,91 @@
=pod
=head1 NAME
SSL_CTX_set_cert_store, SSL_CTX_set1_cert_store, SSL_CTX_get_cert_store - manipulate X509 certificate verification storage
=head1 SYNOPSIS
#include <openssl/ssl.h>
void SSL_CTX_set_cert_store(SSL_CTX *ctx, X509_STORE *store);
void SSL_CTX_set1_cert_store(SSL_CTX *ctx, X509_STORE *store);
X509_STORE *SSL_CTX_get_cert_store(const SSL_CTX *ctx);
=head1 DESCRIPTION
SSL_CTX_set_cert_store() sets/replaces the certificate verification storage
of B<ctx> to/with B<store>. If another X509_STORE object is currently
-set in B<ctx>, it will be X509_STORE_free()ed.
+set in B<ctx>, it will be X509_STORE_free()ed. SSL_CTX_set_cert_store() will
+take ownership of the B<store>, i.e., the call C<X509_STORE_free(store)> is no
+longer needed.
SSL_CTX_set1_cert_store() sets/replaces the certificate verification storage
of B<ctx> to/with B<store>. The B<store>'s reference count is incremented.
If another X509_STORE object is currently set in B<ctx>, it will be X509_STORE_free()ed.
SSL_CTX_get_cert_store() returns a pointer to the current certificate
verification storage.
=head1 NOTES
In order to verify the certificates presented by the peer, trusted CA
certificates must be accessed. These CA certificates are made available
via lookup methods, handled inside the X509_STORE. From the X509_STORE
the X509_STORE_CTX used when verifying certificates is created.
Typically the trusted certificate store is handled indirectly via using
L<SSL_CTX_load_verify_locations(3)>.
Using the SSL_CTX_set_cert_store() and SSL_CTX_get_cert_store() functions
it is possible to manipulate the X509_STORE object beyond the
L<SSL_CTX_load_verify_locations(3)>
call.
Currently no detailed documentation on how to use the X509_STORE
object is available. Not all members of the X509_STORE are used when
the verification takes place. So will e.g. the verify_callback() be
overridden with the verify_callback() set via the
L<SSL_CTX_set_verify(3)> family of functions.
This document must therefore be updated when documentation about the
X509_STORE object and its handling becomes available.
SSL_CTX_set_cert_store() does not increment the B<store>'s reference
count, so it should not be used to assign an X509_STORE that is owned
by another SSL_CTX.
To share X509_STOREs between two SSL_CTXs, use SSL_CTX_get_cert_store()
to get the X509_STORE from the first SSL_CTX, and then use
SSL_CTX_set1_cert_store() to assign to the second SSL_CTX and
increment the reference count of the X509_STORE.
=head1 RESTRICTIONS
The X509_STORE structure used by an SSL_CTX is used for verifying peer
certificates and building certificate chains, it is also shared by
every child SSL structure. Applications wanting finer control can use
functions such as SSL_CTX_set1_verify_cert_store() instead.
=head1 RETURN VALUES
SSL_CTX_set_cert_store() does not return diagnostic output.
SSL_CTX_set1_cert_store() does not return diagnostic output.
SSL_CTX_get_cert_store() returns the current setting.
=head1 SEE ALSO
L<ssl(7)>,
L<SSL_CTX_load_verify_locations(3)>,
L<SSL_CTX_set_verify(3)>
=head1 COPYRIGHT
-Copyright 2001-2016 The OpenSSL Project Authors. All Rights Reserved.
+Copyright 2001-2024 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<https://www.openssl.org/source/license.html>.
=cut
diff --git a/crypto/openssl/doc/man3/SSL_CTX_set_verify.pod b/crypto/openssl/doc/man3/SSL_CTX_set_verify.pod
index 9d4abac30eba..346aa8452974 100644
--- a/crypto/openssl/doc/man3/SSL_CTX_set_verify.pod
+++ b/crypto/openssl/doc/man3/SSL_CTX_set_verify.pod
@@ -1,373 +1,376 @@
=pod
=head1 NAME
SSL_get_ex_data_X509_STORE_CTX_idx,
SSL_CTX_set_verify, SSL_set_verify,
SSL_CTX_set_verify_depth, SSL_set_verify_depth,
SSL_verify_cb,
SSL_verify_client_post_handshake,
SSL_set_post_handshake_auth,
SSL_CTX_set_post_handshake_auth
- set various SSL/TLS parameters for peer certificate verification
=head1 SYNOPSIS
#include <openssl/ssl.h>
typedef int (*SSL_verify_cb)(int preverify_ok, X509_STORE_CTX *x509_ctx);
void SSL_CTX_set_verify(SSL_CTX *ctx, int mode, SSL_verify_cb verify_callback);
void SSL_set_verify(SSL *ssl, int mode, SSL_verify_cb verify_callback);
SSL_get_ex_data_X509_STORE_CTX_idx(void);
void SSL_CTX_set_verify_depth(SSL_CTX *ctx, int depth);
void SSL_set_verify_depth(SSL *ssl, int depth);
int SSL_verify_client_post_handshake(SSL *ssl);
void SSL_CTX_set_post_handshake_auth(SSL_CTX *ctx, int val);
void SSL_set_post_handshake_auth(SSL *ssl, int val);
=head1 DESCRIPTION
SSL_CTX_set_verify() sets the verification flags for B<ctx> to be B<mode> and
specifies the B<verify_callback> function to be used. If no callback function
shall be specified, the NULL pointer can be used for B<verify_callback>.
SSL_set_verify() sets the verification flags for B<ssl> to be B<mode> and
specifies the B<verify_callback> function to be used. If no callback function
shall be specified, the NULL pointer can be used for B<verify_callback>. In
this case last B<verify_callback> set specifically for this B<ssl> remains. If
no special B<callback> was set before, the default callback for the underlying
B<ctx> is used, that was valid at the time B<ssl> was created with
L<SSL_new(3)>. Within the callback function,
B<SSL_get_ex_data_X509_STORE_CTX_idx> can be called to get the data index
of the current SSL object that is doing the verification.
In client mode B<verify_callback> may also call the L<SSL_set_retry_verify(3)>
function on the B<SSL> object set in the I<x509_store_ctx> ex data (see
L<SSL_get_ex_data_X509_STORE_CTX_idx(3)>) and return 1.
This would be typically done in case the certificate verification was not yet
able to succeed.
This makes the handshake suspend and return control to the calling application
with B<SSL_ERROR_WANT_RETRY_VERIFY>.
The application can for instance fetch further certificates or cert status
information needed for the verification.
Calling L<SSL_connect(3)> again resumes the connection attempt by retrying the
server certificate verification step.
This process may even be repeated if need be.
Note that the handshake may still be aborted if a subsequent invocation of the
callback (e.g., at a lower depth, or for a separate error condition) returns 0.
SSL_CTX_set_verify_depth() sets the maximum B<depth> for the certificate chain
verification that shall be allowed for B<ctx>.
SSL_set_verify_depth() sets the maximum B<depth> for the certificate chain
verification that shall be allowed for B<ssl>.
SSL_CTX_set_post_handshake_auth() and SSL_set_post_handshake_auth() enable the
Post-Handshake Authentication extension to be added to the ClientHello such that
post-handshake authentication can be requested by the server. If B<val> is 0
then the extension is not sent, otherwise it is. By default the extension is not
sent. A certificate callback will need to be set via
SSL_CTX_set_client_cert_cb() if no certificate is provided at initialization.
SSL_verify_client_post_handshake() causes a CertificateRequest message to be
sent by a server on the given B<ssl> connection. The SSL_VERIFY_PEER flag must
be set; the SSL_VERIFY_POST_HANDSHAKE flag is optional.
=head1 NOTES
The verification of certificates can be controlled by a set of logically
or'ed B<mode> flags:
=over 4
=item SSL_VERIFY_NONE
B<Server mode:> the server will not send a client certificate request to the
client, so the client will not send a certificate.
B<Client mode:> if not using an anonymous cipher (by default disabled), the
server will send a certificate which will be checked. The result of the
certificate verification process can be checked after the TLS/SSL handshake
using the L<SSL_get_verify_result(3)> function.
The handshake will be continued regardless of the verification result.
=item SSL_VERIFY_PEER
B<Server mode:> the server sends a client certificate request to the client.
The certificate returned (if any) is checked. If the verification process
fails, the TLS/SSL handshake is
immediately terminated with an alert message containing the reason for
the verification failure.
The behaviour can be controlled by the additional
SSL_VERIFY_FAIL_IF_NO_PEER_CERT, SSL_VERIFY_CLIENT_ONCE and
SSL_VERIFY_POST_HANDSHAKE flags.
B<Client mode:> the server certificate is verified. If the verification process
fails, the TLS/SSL handshake is
immediately terminated with an alert message containing the reason for
the verification failure. If no server certificate is sent, because an
anonymous cipher is used, SSL_VERIFY_PEER is ignored.
=item SSL_VERIFY_FAIL_IF_NO_PEER_CERT
B<Server mode:> if the client did not return a certificate, the TLS/SSL
handshake is immediately terminated with a "handshake failure" alert.
This flag must be used together with SSL_VERIFY_PEER.
B<Client mode:> ignored (see BUGS)
=item SSL_VERIFY_CLIENT_ONCE
B<Server mode:> only request a client certificate once during the
connection. Do not ask for a client certificate again during
renegotiation or post-authentication if a certificate was requested
during the initial handshake. This flag must be used together with
SSL_VERIFY_PEER.
B<Client mode:> ignored (see BUGS)
=item SSL_VERIFY_POST_HANDSHAKE
B<Server mode:> the server will not send a client certificate request
during the initial handshake, but will send the request via
SSL_verify_client_post_handshake(). This allows the SSL_CTX or SSL
to be configured for post-handshake peer verification before the
handshake occurs. This flag must be used together with
SSL_VERIFY_PEER. TLSv1.3 only; no effect on pre-TLSv1.3 connections.
B<Client mode:> ignored (see BUGS)
=back
If the B<mode> is SSL_VERIFY_NONE none of the other flags may be set.
+If verification flags are not modified explicitly by C<SSL_CTX_set_verify()>
+or C<SSL_set_verify()>, the default value will be SSL_VERIFY_NONE.
+
The actual verification procedure is performed either using the built-in
verification procedure or using another application provided verification
function set with
L<SSL_CTX_set_cert_verify_callback(3)>.
The following descriptions apply in the case of the built-in procedure. An
application provided procedure also has access to the verify depth information
and the verify_callback() function, but the way this information is used
may be different.
SSL_CTX_set_verify_depth() and SSL_set_verify_depth() set a limit on the
number of certificates between the end-entity and trust-anchor certificates.
Neither the
end-entity nor the trust-anchor certificates count against B<depth>. If the
certificate chain needed to reach a trusted issuer is longer than B<depth+2>,
X509_V_ERR_CERT_CHAIN_TOO_LONG will be issued.
The depth count is "level 0:peer certificate", "level 1: CA certificate",
"level 2: higher level CA certificate", and so on. Setting the maximum
depth to 2 allows the levels 0, 1, 2 and 3 (0 being the end-entity and 3 the
trust-anchor).
The default depth limit is 100,
allowing for the peer certificate, at most 100 intermediate CA certificates and
a final trust anchor certificate.
The B<verify_callback> function is used to control the behaviour when the
SSL_VERIFY_PEER flag is set. It must be supplied by the application and
receives two arguments: B<preverify_ok> indicates, whether the verification of
the certificate in question was passed (preverify_ok=1) or not
(preverify_ok=0). B<x509_ctx> is a pointer to the complete context used
for the certificate chain verification.
The certificate chain is checked starting with the deepest nesting level
(the root CA certificate) and worked upward to the peer's certificate.
At each level signatures and issuer attributes are checked. Whenever
a verification error is found, the error number is stored in B<x509_ctx>
and B<verify_callback> is called with B<preverify_ok>=0. By applying
X509_CTX_store_* functions B<verify_callback> can locate the certificate
in question and perform additional steps (see EXAMPLES). If no error is
found for a certificate, B<verify_callback> is called with B<preverify_ok>=1
before advancing to the next level.
The return value of B<verify_callback> controls the strategy of the further
verification process. If B<verify_callback> returns 0, the verification
process is immediately stopped with "verification failed" state. If
SSL_VERIFY_PEER is set, a verification failure alert is sent to the peer and
the TLS/SSL handshake is terminated. If B<verify_callback> returns 1,
the verification process is continued. If B<verify_callback> always returns
1, the TLS/SSL handshake will not be terminated with respect to verification
failures and the connection will be established. The calling process can
however retrieve the error code of the last verification error using
L<SSL_get_verify_result(3)> or by maintaining its
own error storage managed by B<verify_callback>.
If no B<verify_callback> is specified, the default callback will be used.
Its return value is identical to B<preverify_ok>, so that any verification
failure will lead to a termination of the TLS/SSL handshake with an
alert message, if SSL_VERIFY_PEER is set.
After calling SSL_set_post_handshake_auth(), the client will need to add a
certificate or certificate callback to its configuration before it can
successfully authenticate. This must be called before SSL_connect().
SSL_verify_client_post_handshake() requires that verify flags have been
previously set, and that a client sent the post-handshake authentication
extension. When the client returns a certificate the verify callback will be
invoked. A write operation must take place for the Certificate Request to be
sent to the client, this can be done with SSL_do_handshake() or SSL_write_ex().
Only one certificate request may be outstanding at any time.
When post-handshake authentication occurs, a refreshed NewSessionTicket
message is sent to the client.
=head1 BUGS
In client mode, it is not checked whether the SSL_VERIFY_PEER flag
is set, but whether any flags other than SSL_VERIFY_NONE are set. This can
lead to unexpected behaviour if SSL_VERIFY_PEER and other flags are not used as
required.
=head1 RETURN VALUES
The SSL*_set_verify*() functions do not provide diagnostic information.
The SSL_verify_client_post_handshake() function returns 1 if the request
succeeded, and 0 if the request failed. The error stack can be examined
to determine the failure reason.
=head1 EXAMPLES
The following code sequence realizes an example B<verify_callback> function
that will always continue the TLS/SSL handshake regardless of verification
failure, if wished. The callback realizes a verification depth limit with
more informational output.
All verification errors are printed; information about the certificate chain
is printed on request.
The example is realized for a server that does allow but not require client
certificates.
The example makes use of the ex_data technique to store application data
into/retrieve application data from the SSL structure
(see L<CRYPTO_get_ex_new_index(3)>,
L<SSL_get_ex_data_X509_STORE_CTX_idx(3)>).
...
typedef struct {
int verbose_mode;
int verify_depth;
int always_continue;
} mydata_t;
int mydata_index;
...
static int verify_callback(int preverify_ok, X509_STORE_CTX *ctx)
{
char buf[256];
X509 *err_cert;
int err, depth;
SSL *ssl;
mydata_t *mydata;
err_cert = X509_STORE_CTX_get_current_cert(ctx);
err = X509_STORE_CTX_get_error(ctx);
depth = X509_STORE_CTX_get_error_depth(ctx);
/*
* Retrieve the pointer to the SSL of the connection currently treated
* and the application specific data stored into the SSL object.
*/
ssl = X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
mydata = SSL_get_ex_data(ssl, mydata_index);
X509_NAME_oneline(X509_get_subject_name(err_cert), buf, 256);
/*
* Catch a too long certificate chain. The depth limit set using
* SSL_CTX_set_verify_depth() is by purpose set to "limit+1" so
* that whenever the "depth>verify_depth" condition is met, we
* have violated the limit and want to log this error condition.
* We must do it here, because the CHAIN_TOO_LONG error would not
* be found explicitly; only errors introduced by cutting off the
* additional certificates would be logged.
*/
if (depth > mydata->verify_depth) {
preverify_ok = 0;
err = X509_V_ERR_CERT_CHAIN_TOO_LONG;
X509_STORE_CTX_set_error(ctx, err);
}
if (!preverify_ok) {
printf("verify error:num=%d:%s:depth=%d:%s\n", err,
X509_verify_cert_error_string(err), depth, buf);
} else if (mydata->verbose_mode) {
printf("depth=%d:%s\n", depth, buf);
}
/*
* At this point, err contains the last verification error. We can use
* it for something special
*/
if (!preverify_ok && (err == X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT)) {
X509_NAME_oneline(X509_get_issuer_name(err_cert), buf, 256);
printf("issuer= %s\n", buf);
}
if (mydata->always_continue)
return 1;
else
return preverify_ok;
}
...
mydata_t mydata;
...
mydata_index = SSL_get_ex_new_index(0, "mydata index", NULL, NULL, NULL);
...
SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE,
verify_callback);
/*
* Let the verify_callback catch the verify_depth error so that we get
* an appropriate error in the logfile.
*/
SSL_CTX_set_verify_depth(verify_depth + 1);
/*
* Set up the SSL specific data into "mydata" and store it into th SSL
* structure.
*/
mydata.verify_depth = verify_depth; ...
SSL_set_ex_data(ssl, mydata_index, &mydata);
...
SSL_accept(ssl); /* check of success left out for clarity */
if (peer = SSL_get_peer_certificate(ssl)) {
if (SSL_get_verify_result(ssl) == X509_V_OK) {
/* The client sent a certificate which verified OK */
}
}
=head1 SEE ALSO
L<ssl(7)>, L<SSL_new(3)>,
L<SSL_CTX_get_verify_mode(3)>,
L<SSL_get_verify_result(3)>,
L<SSL_CTX_load_verify_locations(3)>,
L<SSL_get_peer_certificate(3)>,
L<SSL_CTX_set_cert_verify_callback(3)>,
L<SSL_get_ex_data_X509_STORE_CTX_idx(3)>,
L<SSL_CTX_set_client_cert_cb(3)>,
L<CRYPTO_get_ex_new_index(3)>
=head1 HISTORY
The SSL_VERIFY_POST_HANDSHAKE option, and the SSL_verify_client_post_handshake()
and SSL_set_post_handshake_auth() functions were added in OpenSSL 1.1.1.
=head1 COPYRIGHT
-Copyright 2000-2022 The OpenSSL Project Authors. All Rights Reserved.
+Copyright 2000-2024 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<https://www.openssl.org/source/license.html>.
=cut
diff --git a/crypto/openssl/doc/man3/SSL_CTX_use_certificate.pod b/crypto/openssl/doc/man3/SSL_CTX_use_certificate.pod
index ca1827dada8a..dd6f831b8658 100644
--- a/crypto/openssl/doc/man3/SSL_CTX_use_certificate.pod
+++ b/crypto/openssl/doc/man3/SSL_CTX_use_certificate.pod
@@ -1,205 +1,206 @@
=pod
=head1 NAME
SSL_CTX_use_certificate, SSL_CTX_use_certificate_ASN1,
SSL_CTX_use_certificate_file, SSL_use_certificate, SSL_use_certificate_ASN1,
SSL_use_certificate_file, SSL_CTX_use_certificate_chain_file,
SSL_use_certificate_chain_file,
SSL_CTX_use_PrivateKey, SSL_CTX_use_PrivateKey_ASN1,
SSL_CTX_use_PrivateKey_file, SSL_CTX_use_RSAPrivateKey,
SSL_CTX_use_RSAPrivateKey_ASN1, SSL_CTX_use_RSAPrivateKey_file,
SSL_use_PrivateKey_file, SSL_use_PrivateKey_ASN1, SSL_use_PrivateKey,
SSL_use_RSAPrivateKey, SSL_use_RSAPrivateKey_ASN1,
SSL_use_RSAPrivateKey_file, SSL_CTX_check_private_key, SSL_check_private_key,
SSL_CTX_use_cert_and_key, SSL_use_cert_and_key
- load certificate and key data
=head1 SYNOPSIS
#include <openssl/ssl.h>
int SSL_CTX_use_certificate(SSL_CTX *ctx, X509 *x);
int SSL_CTX_use_certificate_ASN1(SSL_CTX *ctx, int len, const unsigned char *d);
int SSL_CTX_use_certificate_file(SSL_CTX *ctx, const char *file, int type);
int SSL_use_certificate(SSL *ssl, X509 *x);
int SSL_use_certificate_ASN1(SSL *ssl, const unsigned char *d, int len);
int SSL_use_certificate_file(SSL *ssl, const char *file, int type);
int SSL_CTX_use_certificate_chain_file(SSL_CTX *ctx, const char *file);
int SSL_use_certificate_chain_file(SSL *ssl, const char *file);
int SSL_CTX_use_PrivateKey(SSL_CTX *ctx, EVP_PKEY *pkey);
int SSL_CTX_use_PrivateKey_ASN1(int pk, SSL_CTX *ctx, const unsigned char *d,
long len);
int SSL_CTX_use_PrivateKey_file(SSL_CTX *ctx, const char *file, int type);
int SSL_CTX_use_RSAPrivateKey(SSL_CTX *ctx, RSA *rsa);
int SSL_CTX_use_RSAPrivateKey_ASN1(SSL_CTX *ctx, const unsigned char *d, long len);
int SSL_CTX_use_RSAPrivateKey_file(SSL_CTX *ctx, const char *file, int type);
int SSL_use_PrivateKey(SSL *ssl, EVP_PKEY *pkey);
int SSL_use_PrivateKey_ASN1(int pk, SSL *ssl, const unsigned char *d, long len);
int SSL_use_PrivateKey_file(SSL *ssl, const char *file, int type);
int SSL_use_RSAPrivateKey(SSL *ssl, RSA *rsa);
int SSL_use_RSAPrivateKey_ASN1(SSL *ssl, const unsigned char *d, long len);
int SSL_use_RSAPrivateKey_file(SSL *ssl, const char *file, int type);
int SSL_CTX_check_private_key(const SSL_CTX *ctx);
int SSL_check_private_key(const SSL *ssl);
int SSL_CTX_use_cert_and_key(SSL_CTX *ctx, X509 *x, EVP_PKEY *pkey, STACK_OF(X509) *chain, int override);
int SSL_use_cert_and_key(SSL *ssl, X509 *x, EVP_PKEY *pkey, STACK_OF(X509) *chain, int override);
=head1 DESCRIPTION
These functions load the certificates and private keys into the SSL_CTX
or SSL object, respectively.
The SSL_CTX_* class of functions loads the certificates and keys into the
SSL_CTX object B<ctx>. The information is passed to SSL objects B<ssl>
created from B<ctx> with L<SSL_new(3)> by copying, so that
changes applied to B<ctx> do not propagate to already existing SSL objects.
The SSL_* class of functions only loads certificates and keys into a
specific SSL object. The specific information is kept, when
L<SSL_clear(3)> is called for this SSL object.
SSL_CTX_use_certificate() loads the certificate B<x> into B<ctx>,
SSL_use_certificate() loads B<x> into B<ssl>. The rest of the
certificates needed to form the complete certificate chain can be
specified using the
L<SSL_CTX_add_extra_chain_cert(3)>
-function.
+function. On success the reference counter of the B<x> is incremented.
SSL_CTX_use_certificate_ASN1() loads the ASN1 encoded certificate from
the memory location B<d> (with length B<len>) into B<ctx>,
SSL_use_certificate_ASN1() loads the ASN1 encoded certificate into B<ssl>.
SSL_CTX_use_certificate_file() loads the first certificate stored in B<file>
into B<ctx>. The formatting B<type> of the certificate must be specified
from the known types SSL_FILETYPE_PEM, SSL_FILETYPE_ASN1.
SSL_use_certificate_file() loads the certificate from B<file> into B<ssl>.
See the NOTES section on why SSL_CTX_use_certificate_chain_file()
should be preferred.
SSL_CTX_use_certificate_chain_file() loads a certificate chain from
B<file> into B<ctx>. The certificates must be in PEM format and must
be sorted starting with the subject's certificate (actual client or server
certificate), followed by intermediate CA certificates if applicable, and
ending at the highest level (root) CA. SSL_use_certificate_chain_file() is
similar except it loads the certificate chain into B<ssl>.
SSL_CTX_use_PrivateKey() adds B<pkey> as private key to B<ctx>.
SSL_CTX_use_RSAPrivateKey() adds the private key B<rsa> of type RSA
to B<ctx>. SSL_use_PrivateKey() adds B<pkey> as private key to B<ssl>;
SSL_use_RSAPrivateKey() adds B<rsa> as private key of type RSA to B<ssl>.
If a certificate has already been set and the private key does not belong
to the certificate an error is returned. To change a [certificate/private-key]
pair, the new certificate needs to be set first with SSL_use_certificate() or
SSL_CTX_use_certificate() before setting the private key with
SSL_CTX_use_PrivateKey() or SSL_use_PrivateKey().
+On success the reference counter of the B<pkey>/B<rsa> is incremented.
SSL_CTX_use_cert_and_key() and SSL_use_cert_and_key() assign the X.509
certificate B<x>, private key B<key>, and certificate B<chain> onto the
corresponding B<ssl> or B<ctx>. The B<pkey> argument must be the private
key of the X.509 certificate B<x>. If the B<override> argument is 0, then
B<x>, B<pkey> and B<chain> are set only if all were not previously set.
If B<override> is non-0, then the certificate, private key and chain certs
are always set. If B<pkey> is NULL, then the public key of B<x> is used as
the private key. This is intended to be used with hardware (via the ENGINE
interface) that stores the private key securely, such that it cannot be
accessed by OpenSSL. The reference count of the public key is incremented
(twice if there is no private key); it is not copied nor duplicated. This
allows all private key validations checks to succeed without an actual
private key being assigned via SSL_CTX_use_PrivateKey(), etc.
SSL_CTX_use_PrivateKey_ASN1() adds the private key of type B<pk>
stored at memory location B<d> (length B<len>) to B<ctx>.
SSL_CTX_use_RSAPrivateKey_ASN1() adds the private key of type RSA
stored at memory location B<d> (length B<len>) to B<ctx>.
SSL_use_PrivateKey_ASN1() and SSL_use_RSAPrivateKey_ASN1() add the private
key to B<ssl>.
SSL_CTX_use_PrivateKey_file() adds the first private key found in
B<file> to B<ctx>. The formatting B<type> of the private key must be specified
from the known types SSL_FILETYPE_PEM, SSL_FILETYPE_ASN1.
SSL_CTX_use_RSAPrivateKey_file() adds the first private RSA key found in
B<file> to B<ctx>. SSL_use_PrivateKey_file() adds the first private key found
in B<file> to B<ssl>; SSL_use_RSAPrivateKey_file() adds the first private
RSA key found to B<ssl>.
SSL_CTX_check_private_key() checks the consistency of a private key with
the corresponding certificate loaded into B<ctx>. If more than one
key/certificate pair (RSA/DSA) is installed, the last item installed will
be checked. If e.g. the last item was an RSA certificate or key, the RSA
key/certificate pair will be checked. SSL_check_private_key() performs
the same check for B<ssl>. If no key/certificate was explicitly added for
this B<ssl>, the last item added into B<ctx> will be checked.
=head1 NOTES
The internal certificate store of OpenSSL can hold several private
key/certificate pairs at a time. The certificate used depends on the
cipher selected, see also L<SSL_CTX_set_cipher_list(3)>.
When reading certificates and private keys from file, files of type
SSL_FILETYPE_ASN1 (also known as B<DER>, binary encoding) can only contain
one certificate or private key, consequently
SSL_CTX_use_certificate_chain_file() is only applicable to PEM formatting.
Files of type SSL_FILETYPE_PEM can contain more than one item.
SSL_CTX_use_certificate_chain_file() adds the first certificate found
in the file to the certificate store. The other certificates are added
to the store of chain certificates using L<SSL_CTX_add1_chain_cert(3)>.
Note: versions of OpenSSL before 1.0.2 only had a single
certificate chain store for all certificate types, OpenSSL 1.0.2 and later
have a separate chain store for each type. SSL_CTX_use_certificate_chain_file()
should be used instead of the SSL_CTX_use_certificate_file() function in order
to allow the use of complete certificate chains even when no trusted CA
storage is used or when the CA issuing the certificate shall not be added to
the trusted CA storage.
If additional certificates are needed to complete the chain during the
TLS negotiation, CA certificates are additionally looked up in the
locations of trusted CA certificates, see
L<SSL_CTX_load_verify_locations(3)>.
The private keys loaded from file can be encrypted. In order to successfully
load encrypted keys, a function returning the passphrase must have been
supplied, see
L<SSL_CTX_set_default_passwd_cb(3)>.
(Certificate files might be encrypted as well from the technical point
of view, it however does not make sense as the data in the certificate
is considered public anyway.)
All of the functions to set a new certificate will replace any existing
certificate of the same type that has already been set. Similarly all of the
functions to set a new private key will replace any private key that has already
been set. Applications should call L<SSL_CTX_check_private_key(3)> or
L<SSL_check_private_key(3)> as appropriate after loading a new certificate and
private key to confirm that the certificate and key match.
=head1 RETURN VALUES
On success, the functions return 1.
Otherwise check out the error stack to find out the reason.
=head1 SEE ALSO
L<ssl(7)>, L<SSL_new(3)>, L<SSL_clear(3)>,
L<SSL_CTX_load_verify_locations(3)>,
L<SSL_CTX_set_default_passwd_cb(3)>,
L<SSL_CTX_set_cipher_list(3)>,
L<SSL_CTX_set_client_CA_list(3)>,
L<SSL_CTX_set_client_cert_cb(3)>,
L<SSL_CTX_add_extra_chain_cert(3)>
=head1 COPYRIGHT
-Copyright 2000-2022 The OpenSSL Project Authors. All Rights Reserved.
+Copyright 2000-2024 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<https://www.openssl.org/source/license.html>.
=cut
diff --git a/crypto/openssl/doc/man3/SSL_load_client_CA_file.pod b/crypto/openssl/doc/man3/SSL_load_client_CA_file.pod
index 988c7e893407..08a6c15e46d9 100644
--- a/crypto/openssl/doc/man3/SSL_load_client_CA_file.pod
+++ b/crypto/openssl/doc/man3/SSL_load_client_CA_file.pod
@@ -1,106 +1,122 @@
=pod
=head1 NAME
SSL_load_client_CA_file_ex, SSL_load_client_CA_file,
SSL_add_file_cert_subjects_to_stack,
SSL_add_dir_cert_subjects_to_stack,
SSL_add_store_cert_subjects_to_stack
- load certificate names
=head1 SYNOPSIS
#include <openssl/ssl.h>
STACK_OF(X509_NAME) *SSL_load_client_CA_file_ex(const char *file,
OSSL_LIB_CTX *libctx,
const char *propq);
STACK_OF(X509_NAME) *SSL_load_client_CA_file(const char *file);
int SSL_add_file_cert_subjects_to_stack(STACK_OF(X509_NAME) *stack,
const char *file);
int SSL_add_dir_cert_subjects_to_stack(STACK_OF(X509_NAME) *stack,
const char *dir);
int SSL_add_store_cert_subjects_to_stack(STACK_OF(X509_NAME) *stack,
const char *store);
=head1 DESCRIPTION
SSL_load_client_CA_file_ex() reads certificates from I<file> and returns
a STACK_OF(X509_NAME) with the subject names found. The library context I<libctx>
and property query I<propq> are used when fetching algorithms from providers.
SSL_load_client_CA_file() is similar to SSL_load_client_CA_file_ex()
but uses NULL for the library context I<libctx> and property query I<propq>.
SSL_add_file_cert_subjects_to_stack() reads certificates from I<file>,
and adds their subject name to the already existing I<stack>.
SSL_add_dir_cert_subjects_to_stack() reads certificates from every
file in the directory I<dir>, and adds their subject name to the
already existing I<stack>.
SSL_add_store_cert_subjects_to_stack() loads certificates from the
I<store> URI, and adds their subject name to the already existing
I<stack>.
=head1 NOTES
SSL_load_client_CA_file() reads a file of PEM formatted certificates and
extracts the X509_NAMES of the certificates found. While the name suggests
the specific usage as support function for
L<SSL_CTX_set_client_CA_list(3)>,
it is not limited to CA certificates.
=head1 RETURN VALUES
-The following return values can occur:
+The following return values can occur for SSL_load_client_CA_file_ex(), and
+SSL_load_client_CA_file():
=over 4
=item NULL
The operation failed, check out the error stack for the reason.
=item Pointer to STACK_OF(X509_NAME)
Pointer to the subject names of the successfully read certificates.
=back
+The following return values can occur for SSL_add_file_cert_subjects_to_stack(),
+SSL_add_dir_cert_subjects_to_stack(), and SSL_add_store_cert_subjects_to_stack():
+
+=over 4
+
+=item 0 (Failure)
+
+The operation failed.
+
+=item 1 (Success)
+
+The operation succeeded.
+
+=back
+
=head1 EXAMPLES
Load names of CAs from file and use it as a client CA list:
SSL_CTX *ctx;
STACK_OF(X509_NAME) *cert_names;
...
cert_names = SSL_load_client_CA_file("/path/to/CAfile.pem");
if (cert_names != NULL)
SSL_CTX_set_client_CA_list(ctx, cert_names);
else
/* error */
...
=head1 SEE ALSO
L<ssl(7)>,
L<ossl_store(7)>,
L<SSL_CTX_set_client_CA_list(3)>
=head1 HISTORY
SSL_load_client_CA_file_ex() and SSL_add_store_cert_subjects_to_stack()
were added in OpenSSL 3.0.
=head1 COPYRIGHT
-Copyright 2000-2021 The OpenSSL Project Authors. All Rights Reserved.
+Copyright 2000-2024 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<https://www.openssl.org/source/license.html>.
=cut
diff --git a/crypto/openssl/doc/man7/EVP_PKEY-SM2.pod b/crypto/openssl/doc/man7/EVP_PKEY-SM2.pod
index 8bdc506cec21..28a0e995d5d1 100644
--- a/crypto/openssl/doc/man7/EVP_PKEY-SM2.pod
+++ b/crypto/openssl/doc/man7/EVP_PKEY-SM2.pod
@@ -1,94 +1,97 @@
=pod
=head1 NAME
EVP_PKEY-SM2, EVP_KEYMGMT-SM2, SM2
- EVP_PKEY keytype support for the Chinese SM2 signature and encryption algorithms
=head1 DESCRIPTION
The B<SM2> algorithm was first defined by the Chinese national standard GM/T
0003-2012 and was later standardized by ISO as ISO/IEC 14888. B<SM2> is actually
an elliptic curve based algorithm. The current implementation in OpenSSL supports
both signature and encryption schemes via the EVP interface.
When doing the B<SM2> signature algorithm, it requires a distinguishing identifier
to form the message prefix which is hashed before the real message is hashed.
=head2 Common SM2 parameters
SM2 uses the parameters defined in L<EVP_PKEY-EC(7)/Common EC parameters>.
The following parameters are different:
=over 4
=item "cofactor" (B<OSSL_PKEY_PARAM_EC_COFACTOR>) <unsigned integer>
This parameter is ignored for B<SM2>.
=item (B<OSSL_PKEY_PARAM_DEFAULT_DIGEST>) <UTF8 string>
Getter that returns the default digest name.
(Currently returns "SM3" as of OpenSSL 3.0).
=back
=head1 NOTES
B<SM2> signatures can be generated by using the 'DigestSign' series of APIs, for
instance, EVP_DigestSignInit(), EVP_DigestSignUpdate() and EVP_DigestSignFinal().
Ditto for the verification process by calling the 'DigestVerify' series of APIs.
+Note that the SM2 algorithm requires the presence of the public key for signatures,
+as such the B<OSSL_PKEY_PARAM_PUB_KEY> option must be set on any key used in signature
+generation.
Before computing an B<SM2> signature, an B<EVP_PKEY_CTX> needs to be created,
and an B<SM2> ID must be set for it, like this:
EVP_PKEY_CTX_set1_id(pctx, id, id_len);
Before calling the EVP_DigestSignInit() or EVP_DigestVerifyInit() functions,
that B<EVP_PKEY_CTX> should be assigned to the B<EVP_MD_CTX>, like this:
EVP_MD_CTX_set_pkey_ctx(mctx, pctx);
There is normally no need to pass a B<pctx> parameter to EVP_DigestSignInit()
or EVP_DigestVerifyInit() in such a scenario.
SM2 can be tested with the L<openssl-speed(1)> application since version 3.0.
Currently, the only valid algorithm name is B<sm2>.
Since version 3.0, SM2 keys can be generated and loaded only when the domain
parameters specify the SM2 elliptic curve.
=head1 EXAMPLES
This example demonstrates the calling sequence for using an B<EVP_PKEY> to verify
a message with the SM2 signature algorithm and the SM3 hash algorithm:
#include <openssl/evp.h>
/* obtain an EVP_PKEY using whatever methods... */
mctx = EVP_MD_CTX_new();
pctx = EVP_PKEY_CTX_new(pkey, NULL);
EVP_PKEY_CTX_set1_id(pctx, id, id_len);
EVP_MD_CTX_set_pkey_ctx(mctx, pctx);
EVP_DigestVerifyInit(mctx, NULL, EVP_sm3(), NULL, pkey);
EVP_DigestVerifyUpdate(mctx, msg, msg_len);
EVP_DigestVerifyFinal(mctx, sig, sig_len)
=head1 SEE ALSO
L<EVP_PKEY_CTX_new(3)>,
L<EVP_DigestSignInit(3)>,
L<EVP_DigestVerifyInit(3)>,
L<EVP_PKEY_CTX_set1_id(3)>,
L<EVP_MD_CTX_set_pkey_ctx(3)>
=head1 COPYRIGHT
-Copyright 2018-2021 The OpenSSL Project Authors. All Rights Reserved.
+Copyright 2018-2024 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<https://www.openssl.org/source/license.html>.
=cut
diff --git a/crypto/openssl/doc/man7/migration_guide.pod b/crypto/openssl/doc/man7/migration_guide.pod
index 61641324a7fc..e5ab29b95370 100644
--- a/crypto/openssl/doc/man7/migration_guide.pod
+++ b/crypto/openssl/doc/man7/migration_guide.pod
@@ -1,2472 +1,2494 @@
=pod
=head1 NAME
migration_guide - OpenSSL migration guide
=head1 SYNOPSIS
See the individual manual pages for details.
=head1 DESCRIPTION
This guide details the changes required to migrate to new versions of OpenSSL.
Currently this covers OpenSSL 3.0. For earlier versions refer to
L<https://github.com/openssl/openssl/blob/master/CHANGES.md>.
For an overview of some of the key concepts introduced in OpenSSL 3.0 see
L<crypto(7)>.
=head1 OPENSSL 3.0
=head2 Main Changes from OpenSSL 1.1.1
=head3 Major Release
OpenSSL 3.0 is a major release and consequently any application that currently
uses an older version of OpenSSL will at the very least need to be recompiled in
order to work with the new version. It is the intention that the large majority
of applications will work unchanged with OpenSSL 3.0 if those applications
previously worked with OpenSSL 1.1.1. However this is not guaranteed and some
changes may be required in some cases. Changes may also be required if
applications need to take advantage of some of the new features available in
OpenSSL 3.0 such as the availability of the FIPS module.
=head3 License Change
In previous versions, OpenSSL was licensed under the L<dual OpenSSL and SSLeay
licenses|https://www.openssl.org/source/license-openssl-ssleay.txt>
(both licenses apply). From OpenSSL 3.0 this is replaced by the
L<Apache License v2|https://www.openssl.org/source/apache-license-2.0.txt>.
=head3 Providers and FIPS support
One of the key changes from OpenSSL 1.1.1 is the introduction of the Provider
concept. Providers collect together and make available algorithm implementations.
With OpenSSL 3.0 it is possible to specify, either programmatically or via a
config file, which providers you want to use for any given application.
OpenSSL 3.0 comes with 5 different providers as standard. Over time third
parties may distribute additional providers that can be plugged into OpenSSL.
All algorithm implementations available via providers are accessed through the
"high level" APIs (for example those functions prefixed with C<EVP>). They cannot
be accessed using the L</Low Level APIs>.
One of the standard providers available is the FIPS provider. This makes
available FIPS validated cryptographic algorithms.
The FIPS provider is disabled by default and needs to be enabled explicitly
at configuration time using the C<enable-fips> option. If it is enabled,
the FIPS provider gets built and installed in addition to the other standard
providers. No separate installation procedure is necessary.
There is however a dedicated C<install_fips> make target, which serves the
special purpose of installing only the FIPS provider into an existing
OpenSSL installation.
Not all algorithms may be available for the application at a particular moment.
If the application code uses any digest or cipher algorithm via the EVP interface,
the application should verify the result of the L<EVP_EncryptInit(3)>,
L<EVP_EncryptInit_ex(3)>, and L<EVP_DigestInit(3)> functions. In case when
the requested algorithm is not available, these functions will fail.
See also L</Legacy Algorithms> for information on the legacy provider.
See also L</Completing the installation of the FIPS Module> and
L</Using the FIPS Module in applications>.
=head3 Low Level APIs
OpenSSL has historically provided two sets of APIs for invoking cryptographic
algorithms: the "high level" APIs (such as the C<EVP> APIs) and the "low level"
APIs. The high level APIs are typically designed to work across all algorithm
types. The "low level" APIs are targeted at a specific algorithm implementation.
For example, the EVP APIs provide the functions L<EVP_EncryptInit_ex(3)>,
L<EVP_EncryptUpdate(3)> and L<EVP_EncryptFinal(3)> to perform symmetric
encryption. Those functions can be used with the algorithms AES, CHACHA, 3DES etc.
On the other hand, to do AES encryption using the low level APIs you would have
to call AES specific functions such as L<AES_set_encrypt_key(3)>,
L<AES_encrypt(3)>, and so on. The functions for 3DES are different.
Use of the low level APIs has been informally discouraged by the OpenSSL
development team for a long time. However in OpenSSL 3.0 this is made more
formal. All such low level APIs have been deprecated. You may still use them in
your applications, but you may start to see deprecation warnings during
compilation (dependent on compiler support for this). Deprecated APIs may be
removed from future versions of OpenSSL so you are strongly encouraged to update
your code to use the high level APIs instead.
This is described in more detail in L</Deprecation of Low Level Functions>
=head3 Legacy Algorithms
Some cryptographic algorithms such as B<MD2> and B<DES> that were available via
the EVP APIs are now considered legacy and their use is strongly discouraged.
These legacy EVP algorithms are still available in OpenSSL 3.0 but not by
default. If you want to use them then you must load the legacy provider.
This can be as simple as a config file change, or can be done programmatically.
See L<OSSL_PROVIDER-legacy(7)> for a complete list of algorithms.
Applications using the EVP APIs to access these algorithms should instead use
more modern algorithms. If that is not possible then these applications
should ensure that the legacy provider has been loaded. This can be achieved
either programmatically or via configuration. See L<crypto(7)> man page for
more information about providers.
=head3 Engines and "METHOD" APIs
The refactoring to support Providers conflicts internally with the APIs used to
support engines, including the ENGINE API and any function that creates or
modifies custom "METHODS" (for example L<EVP_MD_meth_new(3)>,
L<EVP_CIPHER_meth_new(3)>, L<EVP_PKEY_meth_new(3)>, L<RSA_meth_new(3)>,
L<EC_KEY_METHOD_new(3)>, etc.). These functions are being deprecated in
OpenSSL 3.0, and users of these APIs should know that their use can likely
bypass provider selection and configuration, with unintended consequences.
This is particularly relevant for applications written to use the OpenSSL 3.0
FIPS module, as detailed below. Authors and maintainers of external engines are
strongly encouraged to refactor their code transforming engines into providers
using the new Provider API and avoiding deprecated methods.
=head3 Support of legacy engines
If openssl is not built without engine support or deprecated API support, engines
will still work. However, their applicability will be limited.
New algorithms provided via engines will still work.
Engine-backed keys can be loaded via custom B<OSSL_STORE> implementation.
In this case the B<EVP_PKEY> objects created via L<ENGINE_load_private_key(3)>
will be considered legacy and will continue to work.
To ensure the future compatibility, the engines should be turned to providers.
To prefer the provider-based hardware offload, you can specify the default
properties to prefer your provider.
+Setting engine-based or application-based default low-level crypto method such
+as B<RSA_METHOD> or B<EC_KEY_METHOD> is still possible and keys inside the
+default provider will use the engine-based implementation for the crypto
+operations. However B<EVP_PKEY>s created by decoding by using B<OSSL_DECODER>,
+B<PEM_> or B<d2i_> APIs will be provider-based. To create a fully legacy
+B<EVP_PKEY>s L<EVP_PKEY_set1_RSA(3)>, L<EVP_PKEY_set1_EC_KEY(3)> or similar
+functions must be used.
+
=head3 Versioning Scheme
The OpenSSL versioning scheme has changed with the OpenSSL 3.0 release. The new
versioning scheme has this format:
MAJOR.MINOR.PATCH
For OpenSSL 1.1.1 and below, different patch levels were indicated by a letter
at the end of the release version number. This will no longer be used and
instead the patch level is indicated by the final number in the version. A
change in the second (MINOR) number indicates that new features may have been
added. OpenSSL versions with the same major number are API and ABI compatible.
If the major number changes then API and ABI compatibility is not guaranteed.
For more information, see L<OpenSSL_version(3)>.
=head3 Other major new features
=head4 Certificate Management Protocol (CMP, RFC 4210)
This also covers CRMF (RFC 4211) and HTTP transfer (RFC 6712)
See L<openssl-cmp(1)> and L<OSSL_CMP_exec_certreq(3)> as starting points.
=head4 HTTP(S) client
A proper HTTP(S) client that supports GET and POST, redirection, plain and
ASN.1-encoded contents, proxies, and timeouts.
=head4 Key Derivation Function API (EVP_KDF)
This simplifies the process of adding new KDF and PRF implementations.
Previously KDF algorithms had been shoe-horned into using the EVP_PKEY object
which was not a logical mapping.
Existing applications that use KDF algorithms using EVP_PKEY
(scrypt, TLS1 PRF and HKDF) may be slower as they use an EVP_KDF bridge
internally.
All new applications should use the new L<EVP_KDF(3)> interface.
See also L<OSSL_PROVIDER-default(7)/Key Derivation Function (KDF)> and
L<OSSL_PROVIDER-FIPS(7)/Key Derivation Function (KDF)>.
=head4 Message Authentication Code API (EVP_MAC)
This simplifies the process of 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
L<EVP_DigestSign(3)> and L<EVP_DigestVerify(3)>.
All new applications should use the new L<EVP_MAC(3)> interface.
See also L<OSSL_PROVIDER-default(7)/Message Authentication Code (MAC)>
and L<OSSL_PROVIDER-FIPS(7)/Message Authentication Code (MAC)>.
=head4 Algorithm Fetching
Using calls to convenience functions such as EVP_sha256() and EVP_aes_256_gcm() may
incur a performance penalty when using providers.
Retrieving algorithms from providers involves searching for an algorithm by name.
This is much slower than directly accessing a method table.
It is recommended to prefetch algorithms if an algorithm is used many times.
See L<crypto(7)/Performance>, L<crypto(7)/Explicit fetching> and L<crypto(7)/Implicit fetching>.
=head4 Support for Linux Kernel TLS
In order to use KTLS, support for it must be compiled in using the
C<enable-ktls> configuration option. It must also be enabled at run time using
the B<SSL_OP_ENABLE_KTLS> option.
=head4 New Algorithms
=over 4
=item *
KDF algorithms "SINGLE STEP" and "SSH"
See L<EVP_KDF-SS(7)> and L<EVP_KDF-SSHKDF(7)>
=item *
MAC Algorithms "GMAC" and "KMAC"
See L<EVP_MAC-GMAC(7)> and L<EVP_MAC-KMAC(7)>.
=item *
KEM Algorithm "RSASVE"
See L<EVP_KEM-RSA(7)>.
=item *
Cipher Algorithm "AES-SIV"
See L<EVP_EncryptInit(3)/SIV Mode>.
=item *
AES Key Wrap inverse ciphers supported by EVP layer.
The inverse ciphers use AES decryption for wrapping, and AES encryption for
unwrapping. The algorithms are: "AES-128-WRAP-INV", "AES-192-WRAP-INV",
"AES-256-WRAP-INV", "AES-128-WRAP-PAD-INV", "AES-192-WRAP-PAD-INV" and
"AES-256-WRAP-PAD-INV".
=item *
CTS ciphers added to EVP layer.
The algorithms are "AES-128-CBC-CTS", "AES-192-CBC-CTS", "AES-256-CBC-CTS",
"CAMELLIA-128-CBC-CTS", "CAMELLIA-192-CBC-CTS" and "CAMELLIA-256-CBC-CTS".
CS1, CS2 and CS3 variants are supported.
=back
=head4 CMS and PKCS#7 updates
=over 4
=item *
Added CAdES-BES signature verification support.
=item *
Added CAdES-BES signature scheme and attributes support (RFC 5126) to CMS API.
=item *
Added AuthEnvelopedData content type structure (RFC 5083) using AES_GCM
This uses the AES-GCM parameter (RFC 5084) for the Cryptographic Message Syntax.
Its purpose is to support encryption and decryption of a digital envelope that
is both authenticated and encrypted using AES GCM mode.
=item *
L<PKCS7_get_octet_string(3)> and L<PKCS7_type_is_other(3)> were made public.
=back
=head4 PKCS#12 API updates
The default algorithms for pkcs12 creation with the PKCS12_create() function
were changed to more modern PBKDF2 and AES based algorithms. The default
MAC iteration count was changed to PKCS12_DEFAULT_ITER to make it equal
with the password-based encryption iteration count. The default digest
algorithm for the MAC computation was changed to SHA-256. The pkcs12
application now supports -legacy option that restores the previous
default algorithms to support interoperability with legacy systems.
Added enhanced PKCS#12 APIs which accept a library context B<OSSL_LIB_CTX>
and (where relevant) a property query. Other APIs which handle PKCS#7 and
PKCS#8 objects have also been enhanced where required. This includes:
L<PKCS12_add_key_ex(3)>, L<PKCS12_add_safe_ex(3)>, L<PKCS12_add_safes_ex(3)>,
L<PKCS12_create_ex(3)>, L<PKCS12_decrypt_skey_ex(3)>, L<PKCS12_init_ex(3)>,
L<PKCS12_item_decrypt_d2i_ex(3)>, L<PKCS12_item_i2d_encrypt_ex(3)>,
L<PKCS12_key_gen_asc_ex(3)>, L<PKCS12_key_gen_uni_ex(3)>, L<PKCS12_key_gen_utf8_ex(3)>,
L<PKCS12_pack_p7encdata_ex(3)>, L<PKCS12_pbe_crypt_ex(3)>, L<PKCS12_PBE_keyivgen_ex(3)>,
L<PKCS12_SAFEBAG_create_pkcs8_encrypt_ex(3)>, L<PKCS5_pbe2_set_iv_ex(3)>,
L<PKCS5_pbe_set0_algor_ex(3)>, L<PKCS5_pbe_set_ex(3)>, L<PKCS5_pbkdf2_set_ex(3)>,
L<PKCS5_v2_PBE_keyivgen_ex(3)>, L<PKCS5_v2_scrypt_keyivgen_ex(3)>,
L<PKCS8_decrypt_ex(3)>, L<PKCS8_encrypt_ex(3)>, L<PKCS8_set0_pbe_ex(3)>.
As part of this change the EVP_PBE_xxx APIs can also accept a library
context and property query and will call an extended version of the key/IV
derivation function which supports these parameters. This includes
L<EVP_PBE_CipherInit_ex(3)>, L<EVP_PBE_find_ex(3)> and L<EVP_PBE_scrypt_ex(3)>.
=head4 PKCS#12 KDF versus FIPS
Unlike in 1.x.y, the PKCS12KDF algorithm used when a PKCS#12 structure
is created with a MAC that does not work with the FIPS provider as the PKCS12KDF
is not a FIPS approvable mechanism.
See L<EVP_KDF-PKCS12KDF(7)>, L<PKCS12_create(3)>, L<openssl-pkcs12(1)>,
L<OSSL_PROVIDER-FIPS(7)>.
=head4 Windows thread synchronization changes
Windows thread synchronization uses read/write primitives (SRWLock) when
supported by the OS, otherwise CriticalSection continues to be used.
=head4 Trace API
A new generic trace API has been added which provides support for enabling
instrumentation through trace output. This feature is mainly intended as an aid
for developers and is disabled by default. To utilize it, OpenSSL needs to be
configured with the C<enable-trace> option.
If the tracing API is enabled, the application can activate trace output by
registering BIOs as trace channels for a number of tracing and debugging
categories. See L<OSSL_trace_enabled(3)>.
=head4 Key validation updates
L<EVP_PKEY_public_check(3)> and L<EVP_PKEY_param_check(3)> now work for
more key types. This includes RSA, DSA, ED25519, X25519, ED448 and X448.
Previously (in 1.1.1) they would return -2. For key types that do not have
parameters then L<EVP_PKEY_param_check(3)> will always return 1.
=head3 Other notable deprecations and changes
=head4 The function code part of an OpenSSL error code is no longer relevant
This code is now always set to zero. Related functions are deprecated.
=head4 STACK and HASH macros have been cleaned up
The type-safe wrappers are declared everywhere and implemented once.
See L<DEFINE_STACK_OF(3)> and L<DECLARE_LHASH_OF(3)>.
=head4 The RAND_DRBG subsystem has been removed
The new L<EVP_RAND(3)> is a partial replacement: the DRBG callback framework is
absent. The RAND_DRBG API did not fit well into the new provider concept as
implemented by EVP_RAND and EVP_RAND_CTX.
=head4 Removed FIPS_mode() and FIPS_mode_set()
These functions are legacy APIs that are not applicable to the new provider
model. Applications should instead use
L<EVP_default_properties_is_fips_enabled(3)> and
L<EVP_default_properties_enable_fips(3)>.
=head4 Key generation is slower
The Miller-Rabin test now uses 64 rounds, which is used for all prime generation,
including RSA key generation. This affects the time for larger keys sizes.
The default key generation method for the regular 2-prime RSA keys was changed
to the FIPS186-4 B.3.6 method (Generation of Probable Primes with Conditions
Based on Auxiliary Probable Primes). This method is slower than the original
method.
=head4 Change PBKDF2 to conform to SP800-132 instead of the older PKCS5 RFC2898
This checks that the salt length is at least 128 bits, the derived key length is
at least 112 bits, and that the iteration count is at least 1000.
For backwards compatibility these checks are disabled by default in the
default provider, but are enabled by default in the FIPS provider.
To enable or disable the checks see B<OSSL_KDF_PARAM_PKCS5> in
L<EVP_KDF-PBKDF2(7)>. The parameter can be set using L<EVP_KDF_derive(3)>.
=head4 Enforce a minimum DH modulus size of 512 bits
Smaller sizes now result in an error.
=head4 SM2 key changes
EC EVP_PKEYs with the SM2 curve have been reworked to automatically become
EVP_PKEY_SM2 rather than EVP_PKEY_EC.
Unlike in previous OpenSSL versions, this means that applications cannot
call C<EVP_PKEY_set_alias_type(pkey, EVP_PKEY_SM2)> to get SM2 computations.
Parameter and key generation is also reworked to make it possible
to generate EVP_PKEY_SM2 parameters and keys. Applications must now generate
SM2 keys directly and must not create an EVP_PKEY_EC key first. It is no longer
possible to import an SM2 key with domain parameters other than the SM2 elliptic
curve ones.
Validation of SM2 keys has been separated from the validation of regular EC
keys, allowing to improve the SM2 validation process to reject loaded private
keys that are not conforming to the SM2 ISO standard.
In particular, a private scalar I<k> outside the range I<< 1 <= k < n-1 >> is
now correctly rejected.
=head4 EVP_PKEY_set_alias_type() method has been removed
This function made a B<EVP_PKEY> object mutable after it had been set up. In
OpenSSL 3.0 it was decided that a provided key should not be able to change its
type, so this function has been removed.
=head4 Functions that return an internal key should be treated as read only
Functions such as L<EVP_PKEY_get0_RSA(3)> behave slightly differently in
OpenSSL 3.0. Previously they returned a pointer to the low-level key used
internally by libcrypto. From OpenSSL 3.0 this key may now be held in a
provider. Calling these functions will only return a handle on the internal key
where the EVP_PKEY was constructed using this key in the first place, for
example using a function or macro such as L<EVP_PKEY_assign_RSA(3)>,
L<EVP_PKEY_set1_RSA(3)>, etc.
Where the EVP_PKEY holds a provider managed key, then these functions now return
a cached copy of the key. Changes to the internal provider key that take place
after the first time the cached key is accessed will not be reflected back in
the cached copy. Similarly any changes made to the cached copy by application
code will not be reflected back in the internal provider key.
For the above reasons the keys returned from these functions should typically be
treated as read-only. To emphasise this the value returned from
L<EVP_PKEY_get0_RSA(3)>, L<EVP_PKEY_get0_DSA(3)>, L<EVP_PKEY_get0_EC_KEY(3)> and
L<EVP_PKEY_get0_DH(3)> have been made const. This may break some existing code.
Applications broken by this change should be modified. The preferred solution is
to refactor the code to avoid the use of these deprecated functions. Failing
this the code should be modified to use a const pointer instead.
The L<EVP_PKEY_get1_RSA(3)>, L<EVP_PKEY_get1_DSA(3)>, L<EVP_PKEY_get1_EC_KEY(3)>
and L<EVP_PKEY_get1_DH(3)> functions continue to return a non-const pointer to
enable them to be "freed". However they should also be treated as read-only.
=head4 The public key check has moved from EVP_PKEY_derive() to EVP_PKEY_derive_set_peer()
This may mean result in an error in L<EVP_PKEY_derive_set_peer(3)> rather than
during L<EVP_PKEY_derive(3)>.
To disable this check use EVP_PKEY_derive_set_peer_ex(dh, peer, 0).
=head4 The print format has cosmetic changes for some functions
The output from numerous "printing" functions such as L<X509_signature_print(3)>,
L<X509_print_ex(3)>, L<X509_CRL_print_ex(3)>, and other similar functions has been
amended such that there may be cosmetic differences between the output
observed in 1.1.1 and 3.0. This also applies to the B<-text> output from the
B<openssl x509> and B<openssl crl> applications.
=head4 Interactive mode from the B<openssl> program has been removed
From now on, running it without arguments is equivalent to B<openssl help>.
=head4 The error return values from some control calls (ctrl) have changed
One significant change is that controls which used to return -2 for
invalid inputs, now return -1 indicating a generic error condition instead.
=head4 DH and DHX key types have different settable parameters
Previously (in 1.1.1) these conflicting parameters were allowed, but will now
result in errors. See L<EVP_PKEY-DH(7)> for further details. This affects the
behaviour of L<openssl-genpkey(1)> for DH parameter generation.
=head4 EVP_CIPHER_CTX_set_flags() ordering change
If using a cipher from a provider the B<EVP_CIPH_FLAG_LENGTH_BITS> flag can only
be set B<after> the cipher has been assigned to the cipher context.
See L<EVP_EncryptInit(3)/FLAGS> for more information.
=head4 Validation of operation context parameters
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.
=head4 Removal of function code from the error codes
The function code part of the error code is now always set to 0. For that
reason the ERR_GET_FUNC() macro was removed. Applications must resolve
the error codes only using the library number and the reason code.
=head4 ChaCha20-Poly1305 cipher does not allow a truncated IV length to be used
In OpenSSL 3.0 setting the IV length to any value other than 12 will result in an
error.
Prior to OpenSSL 3.0 the ivlen could be smaller that the required 12 byte length,
using EVP_CIPHER_CTX_ctrl(ctx, EVP_CRTL_AEAD_SET_IVLEN, ivlen, NULL). This resulted
in an IV that had leading zero padding.
=head2 Installation and Compilation
Please refer to the INSTALL.md file in the top of the distribution for
instructions on how to build and install OpenSSL 3.0. Please also refer to the
various platform specific NOTES files for your specific platform.
=head2 Upgrading from OpenSSL 1.1.1
Upgrading to OpenSSL 3.0 from OpenSSL 1.1.1 should be relatively straight
forward in most cases. The most likely area where you will encounter problems
is if you have used low level APIs in your code (as discussed above). In that
case you are likely to start seeing deprecation warnings when compiling your
application. If this happens you have 3 options:
=over 4
=item 1.
Ignore the warnings. They are just warnings. The deprecated functions are still present and you may still use them. However be aware that they may be removed from a future version of OpenSSL.
=item 2.
Suppress the warnings. Refer to your compiler documentation on how to do this.
=item 3.
Remove your usage of the low level APIs. In this case you will need to rewrite your code to use the high level APIs instead
=back
=head3 Error code changes
As OpenSSL 3.0 provides a brand new Encoder/Decoder mechanism for working with
widely used file formats, application code that checks for particular error
reason codes on key loading failures might need an update.
Password-protected keys may deserve special attention. If only some errors
are treated as an indicator that the user should be asked about the password again,
it's worth testing these scenarios and processing the newly relevant codes.
There may be more cases to treat specially, depending on the calling application code.
=head2 Upgrading from OpenSSL 1.0.2
Upgrading to OpenSSL 3.0 from OpenSSL 1.0.2 is likely to be significantly more
difficult. In addition to the issues discussed above in the section about
L</Upgrading from OpenSSL 1.1.1>, the main things to be aware of are:
=over 4
=item 1.
The build and installation procedure has changed significantly.
Check the file INSTALL.md in the top of the installation for instructions on how
to build and install OpenSSL for your platform. Also read the various NOTES
files in the same directory, as applicable for your platform.
=item 2.
Many structures have been made opaque in OpenSSL 3.0.
The structure definitions have been removed from the public header files and
moved to internal header files. In practice this means that you can no longer
stack allocate some structures. Instead they must be heap allocated through some
function call (typically those function names have a C<_new> suffix to them).
Additionally you must use "setter" or "getter" functions to access the fields
within those structures.
For example code that previously looked like this:
EVP_MD_CTX md_ctx;
/* This line will now generate compiler errors */
EVP_MD_CTX_init(&md_ctx);
The code needs to be amended to look like this:
EVP_MD_CTX *md_ctx;
md_ctx = EVP_MD_CTX_new();
...
...
EVP_MD_CTX_free(md_ctx);
=item 3.
Support for TLSv1.3 has been added.
This has a number of implications for SSL/TLS applications. See the
L<TLS1.3 page|https://wiki.openssl.org/index.php/TLS1.3> for further details.
=back
More details about the breaking changes between OpenSSL versions 1.0.2 and 1.1.0
can be found on the
L<OpenSSL 1.1.0 Changes page|https://wiki.openssl.org/index.php/OpenSSL_1.1.0_Changes>.
=head3 Upgrading from the OpenSSL 2.0 FIPS Object Module
The OpenSSL 2.0 FIPS Object Module was a separate download that had to be built
separately and then integrated into your main OpenSSL 1.0.2 build.
In OpenSSL 3.0 the FIPS support is fully integrated into the mainline version of
OpenSSL and is no longer a separate download. For further information see
L</Completing the installation of the FIPS Module>.
The function calls FIPS_mode() and FIPS_mode_set() have been removed
from OpenSSL 3.0. You should rewrite your application to not use them.
See L<fips_module(7)> and L<OSSL_PROVIDER-FIPS(7)> for details.
=head2 Completing the installation of the FIPS Module
The FIPS Module will be built and installed automatically if FIPS support has
been configured. The current documentation can be found in the
L<README-FIPS|https://github.com/openssl/openssl/blob/master/README-FIPS.md> file.
=head2 Programming
Applications written to work with OpenSSL 1.1.1 will mostly just work with
OpenSSL 3.0. However changes will be required if you want to take advantage of
some of the new features that OpenSSL 3.0 makes available. In order to do that
you need to understand some new concepts introduced in OpenSSL 3.0.
Read L<crypto(7)/Library contexts> for further information.
=head3 Library Context
A library context allows different components of a complex application to each
use a different library context and have different providers loaded with
different configuration settings.
See L<crypto(7)/Library contexts> for further info.
If the user creates an B<OSSL_LIB_CTX> via L<OSSL_LIB_CTX_new(3)> then many
functions may need to be changed to pass additional parameters to handle the
library context.
=head4 Using a Library Context - Old functions that should be changed
If a library context is needed then all EVP_* digest functions that return a
B<const EVP_MD *> such as EVP_sha256() should be replaced with a call to
L<EVP_MD_fetch(3)>. See L<crypto(7)/ALGORITHM FETCHING>.
If a library context is needed then all EVP_* cipher functions that return a
B<const EVP_CIPHER *> such as EVP_aes_128_cbc() should be replaced vith a call to
L<EVP_CIPHER_fetch(3)>. See L<crypto(7)/ALGORITHM FETCHING>.
Some functions can be passed an object that has already been set up with a library
context such as L<d2i_X509(3)>, L<d2i_X509_CRL(3)>, L<d2i_X509_REQ(3)> and
L<d2i_X509_PUBKEY(3)>. If NULL is passed instead then the created object will be
set up with the default library context. Use L<X509_new_ex(3)>,
L<X509_CRL_new_ex(3)>, L<X509_REQ_new_ex(3)> and L<X509_PUBKEY_new_ex(3)> if a
library context is required.
All functions listed below with a I<NAME> have a replacement function I<NAME_ex>
that takes B<OSSL_LIB_CTX> as an additional argument. Functions that have other
mappings are listed along with the respective name.
=over 4
=item *
L<ASN1_item_new(3)>, L<ASN1_item_d2i(3)>, L<ASN1_item_d2i_fp(3)>,
L<ASN1_item_d2i_bio(3)>, L<ASN1_item_sign(3)> and L<ASN1_item_verify(3)>
=item *
L<BIO_new(3)>
=item *
b2i_RSA_PVK_bio() and i2b_PVK_bio()
=item *
L<BN_CTX_new(3)> and L<BN_CTX_secure_new(3)>
=item *
L<CMS_AuthEnvelopedData_create(3)>, L<CMS_ContentInfo_new(3)>, L<CMS_data_create(3)>,
L<CMS_digest_create(3)>, L<CMS_EncryptedData_encrypt(3)>, L<CMS_encrypt(3)>,
L<CMS_EnvelopedData_create(3)>, L<CMS_ReceiptRequest_create0(3)> and L<CMS_sign(3)>
=item *
L<CONF_modules_load_file(3)>
=item *
L<CTLOG_new(3)>, L<CTLOG_new_from_base64(3)> and L<CTLOG_STORE_new(3)>
=item *
L<CT_POLICY_EVAL_CTX_new(3)>
=item *
L<d2i_AutoPrivateKey(3)>, L<d2i_PrivateKey(3)> and L<d2i_PUBKEY(3)>
=item *
L<d2i_PrivateKey_bio(3)> and L<d2i_PrivateKey_fp(3)>
Use L<d2i_PrivateKey_ex_bio(3)> and L<d2i_PrivateKey_ex_fp(3)>
=item *
L<EC_GROUP_new(3)>
Use L<EC_GROUP_new_by_curve_name_ex(3)> or L<EC_GROUP_new_from_params(3)>.
=item *
L<EVP_DigestSignInit(3)> and L<EVP_DigestVerifyInit(3)>
=item *
L<EVP_PBE_CipherInit(3)>, L<EVP_PBE_find(3)> and L<EVP_PBE_scrypt(3)>
=item *
L<PKCS5_PBE_keyivgen(3)>
=item *
L<EVP_PKCS82PKEY(3)>
=item *
L<EVP_PKEY_CTX_new_id(3)>
Use L<EVP_PKEY_CTX_new_from_name(3)>
=item *
L<EVP_PKEY_derive_set_peer(3)>, L<EVP_PKEY_new_raw_private_key(3)>
and L<EVP_PKEY_new_raw_public_key(3)>
=item *
L<EVP_SignFinal(3)> and L<EVP_VerifyFinal(3)>
=item *
L<NCONF_new(3)>
=item *
L<OCSP_RESPID_match(3)> and L<OCSP_RESPID_set_by_key(3)>
=item *
L<OPENSSL_thread_stop(3)>
=item *
L<OSSL_STORE_open(3)>
=item *
L<PEM_read_bio_Parameters(3)>, L<PEM_read_bio_PrivateKey(3)>, L<PEM_read_bio_PUBKEY(3)>,
L<PEM_read_PrivateKey(3)> and L<PEM_read_PUBKEY(3)>
=item *
L<PEM_write_bio_PrivateKey(3)>, L<PEM_write_bio_PUBKEY(3)>, L<PEM_write_PrivateKey(3)>
and L<PEM_write_PUBKEY(3)>
=item *
L<PEM_X509_INFO_read_bio(3)> and L<PEM_X509_INFO_read(3)>
=item *
L<PKCS12_add_key(3)>, L<PKCS12_add_safe(3)>, L<PKCS12_add_safes(3)>,
L<PKCS12_create(3)>, L<PKCS12_decrypt_skey(3)>, L<PKCS12_init(3)>, L<PKCS12_item_decrypt_d2i(3)>,
L<PKCS12_item_i2d_encrypt(3)>, L<PKCS12_key_gen_asc(3)>, L<PKCS12_key_gen_uni(3)>,
L<PKCS12_key_gen_utf8(3)>, L<PKCS12_pack_p7encdata(3)>, L<PKCS12_pbe_crypt(3)>,
L<PKCS12_PBE_keyivgen(3)>, L<PKCS12_SAFEBAG_create_pkcs8_encrypt(3)>
=item *
L<PKCS5_pbe_set0_algor(3)>, L<PKCS5_pbe_set(3)>, L<PKCS5_pbe2_set_iv(3)>,
L<PKCS5_pbkdf2_set(3)> and L<PKCS5_v2_scrypt_keyivgen(3)>
=item *
L<PKCS7_encrypt(3)>, L<PKCS7_new(3)> and L<PKCS7_sign(3)>
=item *
L<PKCS8_decrypt(3)>, L<PKCS8_encrypt(3)> and L<PKCS8_set0_pbe(3)>
=item *
L<RAND_bytes(3)> and L<RAND_priv_bytes(3)>
=item *
L<SMIME_write_ASN1(3)>
=item *
L<SSL_load_client_CA_file(3)>
=item *
L<SSL_CTX_new(3)>
=item *
L<TS_RESP_CTX_new(3)>
=item *
L<X509_CRL_new(3)>
=item *
L<X509_load_cert_crl_file(3)> and L<X509_load_cert_file(3)>
=item *
L<X509_LOOKUP_by_subject(3)> and L<X509_LOOKUP_ctrl(3)>
=item *
L<X509_NAME_hash(3)>
=item *
L<X509_new(3)>
=item *
L<X509_REQ_new(3)> and L<X509_REQ_verify(3)>
=item *
L<X509_STORE_CTX_new(3)>, L<X509_STORE_set_default_paths(3)>, L<X509_STORE_load_file(3)>,
L<X509_STORE_load_locations(3)> and L<X509_STORE_load_store(3)>
=back
=head4 New functions that use a Library context
The following functions can be passed a library context if required.
Passing NULL will use the default library context.
=over 4
=item *
L<BIO_new_from_core_bio(3)>
=item *
L<EVP_ASYM_CIPHER_fetch(3)> and L<EVP_ASYM_CIPHER_do_all_provided(3)>
=item *
L<EVP_CIPHER_fetch(3)> and L<EVP_CIPHER_do_all_provided(3)>
=item *
L<EVP_default_properties_enable_fips(3)> and
L<EVP_default_properties_is_fips_enabled(3)>
=item *
L<EVP_KDF_fetch(3)> and L<EVP_KDF_do_all_provided(3)>
=item *
L<EVP_KEM_fetch(3)> and L<EVP_KEM_do_all_provided(3)>
=item *
L<EVP_KEYEXCH_fetch(3)> and L<EVP_KEYEXCH_do_all_provided(3)>
=item *
L<EVP_KEYMGMT_fetch(3)> and L<EVP_KEYMGMT_do_all_provided(3)>
=item *
L<EVP_MAC_fetch(3)> and L<EVP_MAC_do_all_provided(3)>
=item *
L<EVP_MD_fetch(3)> and L<EVP_MD_do_all_provided(3)>
=item *
L<EVP_PKEY_CTX_new_from_pkey(3)>
=item *
L<EVP_PKEY_Q_keygen(3)>
=item *
L<EVP_Q_mac(3)> and L<EVP_Q_digest(3)>
=item *
L<EVP_RAND(3)> and L<EVP_RAND_do_all_provided(3)>
=item *
L<EVP_set_default_properties(3)>
=item *
L<EVP_SIGNATURE_fetch(3)> and L<EVP_SIGNATURE_do_all_provided(3)>
=item *
L<OSSL_CMP_CTX_new(3)> and L<OSSL_CMP_SRV_CTX_new(3)>
=item *
L<OSSL_CRMF_ENCRYPTEDVALUE_get1_encCert(3)>
=item *
L<OSSL_CRMF_MSG_create_popo(3)> and L<OSSL_CRMF_MSGS_verify_popo(3)>
=item *
L<OSSL_CRMF_pbm_new(3)> and L<OSSL_CRMF_pbmp_new(3)>
=item *
L<OSSL_DECODER_CTX_add_extra(3)> and L<OSSL_DECODER_CTX_new_for_pkey(3)>
=item *
L<OSSL_DECODER_fetch(3)> and L<OSSL_DECODER_do_all_provided(3)>
=item *
L<OSSL_ENCODER_CTX_add_extra(3)>
=item *
L<OSSL_ENCODER_fetch(3)> and L<OSSL_ENCODER_do_all_provided(3)>
=item *
L<OSSL_LIB_CTX_free(3)>, L<OSSL_LIB_CTX_load_config(3)> and L<OSSL_LIB_CTX_set0_default(3)>
=item *
L<OSSL_PROVIDER_add_builtin(3)>, L<OSSL_PROVIDER_available(3)>,
L<OSSL_PROVIDER_do_all(3)>, L<OSSL_PROVIDER_load(3)>,
L<OSSL_PROVIDER_set_default_search_path(3)> and L<OSSL_PROVIDER_try_load(3)>
=item *
L<OSSL_SELF_TEST_get_callback(3)> and L<OSSL_SELF_TEST_set_callback(3)>
=item *
L<OSSL_STORE_attach(3)>
=item *
L<OSSL_STORE_LOADER_fetch(3)> and L<OSSL_STORE_LOADER_do_all_provided(3)>
=item *
L<RAND_get0_primary(3)>, L<RAND_get0_private(3)>, L<RAND_get0_public(3)>,
L<RAND_set_DRBG_type(3)> and L<RAND_set_seed_source_type(3)>
=back
=head3 Providers
Providers are described in detail here L<crypto(7)/Providers>.
See also L<crypto(7)/OPENSSL PROVIDERS>.
=head3 Fetching algorithms and property queries
Implicit and Explicit Fetching is described in detail here
L<crypto(7)/ALGORITHM FETCHING>.
=head3 Mapping EVP controls and flags to provider L<OSSL_PARAM(3)> parameters
The existing functions for controls (such as L<EVP_CIPHER_CTX_ctrl(3)>) and
manipulating flags (such as L<EVP_MD_CTX_set_flags(3)>)internally use
B<OSSL_PARAMS> to pass information to/from provider objects.
See L<OSSL_PARAM(3)> for additional information related to parameters.
For ciphers see L<EVP_EncryptInit(3)/CONTROLS>, L<EVP_EncryptInit(3)/FLAGS> and
L<EVP_EncryptInit(3)/PARAMETERS>.
For digests see L<EVP_DigestInit(3)/CONTROLS>, L<EVP_DigestInit(3)/FLAGS> and
L<EVP_DigestInit(3)/PARAMETERS>.
=head3 Deprecation of Low Level Functions
A significant number of APIs have been deprecated in OpenSSL 3.0.
This section describes some common categories of deprecations.
See L</Deprecated function mappings> for the list of deprecated functions
that refer to these categories.
=head4 Providers are a replacement for engines and low-level method overrides
Any accessor that uses an ENGINE is deprecated (such as EVP_PKEY_set1_engine()).
Applications using engines should instead use providers.
Before providers were added algorithms were overridden by changing the methods
used by algorithms. All these methods such as RSA_new_method() and RSA_meth_new()
are now deprecated and can be replaced by using providers instead.
=head4 Deprecated i2d and d2i functions for low-level key types
Any i2d and d2i functions such as d2i_DHparams() that take a low-level key type
have been deprecated. Applications should instead use the L<OSSL_DECODER(3)> and
L<OSSL_ENCODER(3)> APIs to read and write files.
See L<d2i_RSAPrivateKey(3)/Migration> for further details.
=head4 Deprecated low-level key object getters and setters
Applications that set or get low-level key objects (such as EVP_PKEY_set1_DH()
or EVP_PKEY_get0()) should instead use the OSSL_ENCODER
(See L<OSSL_ENCODER_to_bio(3)>) or OSSL_DECODER (See L<OSSL_DECODER_from_bio(3)>)
APIs, or alternatively use L<EVP_PKEY_fromdata(3)> or L<EVP_PKEY_todata(3)>.
=head4 Deprecated low-level key parameter getters
Functions that access low-level objects directly such as L<RSA_get0_n(3)> are now
deprecated. Applications should use one of L<EVP_PKEY_get_bn_param(3)>,
L<EVP_PKEY_get_int_param(3)>, l<EVP_PKEY_get_size_t_param(3)>,
L<EVP_PKEY_get_utf8_string_param(3)>, L<EVP_PKEY_get_octet_string_param(3)> or
L<EVP_PKEY_get_params(3)> to access fields from an EVP_PKEY.
Gettable parameters are listed in L<EVP_PKEY-RSA(7)/Common RSA parameters>,
L<EVP_PKEY-DH(7)/DH parameters>, L<EVP_PKEY-DSA(7)/DSA parameters>,
L<EVP_PKEY-FFC(7)/FFC parameters>, L<EVP_PKEY-EC(7)/Common EC parameters> and
L<EVP_PKEY-X25519(7)/Common X25519, X448, ED25519 and ED448 parameters>.
Applications may also use L<EVP_PKEY_todata(3)> to return all fields.
=head4 Deprecated low-level key parameter setters
Functions that access low-level objects directly such as L<RSA_set0_crt_params(3)>
are now deprecated. Applications should use L<EVP_PKEY_fromdata(3)> to create
new keys from user provided key data. Keys should be immutable once they are
created, so if required the user may use L<EVP_PKEY_todata(3)>, L<OSSL_PARAM_merge(3)>,
and L<EVP_PKEY_fromdata(3)> to create a modified key.
See L<EVP_PKEY-DH(7)/Examples> for more information.
See L</Deprecated low-level key generation functions> for information on
generating a key using parameters.
=head4 Deprecated low-level object creation
Low-level objects were created using methods such as L<RSA_new(3)>,
L<RSA_up_ref(3)> and L<RSA_free(3)>. Applications should instead use the
high-level EVP_PKEY APIs, e.g. L<EVP_PKEY_new(3)>, L<EVP_PKEY_up_ref(3)> and
L<EVP_PKEY_free(3)>.
See also L<EVP_PKEY_CTX_new_from_name(3)> and L<EVP_PKEY_CTX_new_from_pkey(3)>.
EVP_PKEYs may be created in a variety of ways:
See also L</Deprecated low-level key generation functions>,
L</Deprecated low-level key reading and writing functions> and
L</Deprecated low-level key parameter setters>.
=head4 Deprecated low-level encryption functions
Low-level encryption functions such as L<AES_encrypt(3)> and L<AES_decrypt(3)>
have been informally discouraged from use for a long time. Applications should
instead use the high level EVP APIs L<EVP_EncryptInit_ex(3)>,
L<EVP_EncryptUpdate(3)>, and L<EVP_EncryptFinal_ex(3)> or
L<EVP_DecryptInit_ex(3)>, L<EVP_DecryptUpdate(3)> and L<EVP_DecryptFinal_ex(3)>.
=head4 Deprecated low-level digest functions
Use of low-level digest functions such as L<SHA1_Init(3)> have been
informally discouraged from use for a long time. Applications should instead
use the the high level EVP APIs L<EVP_DigestInit_ex(3)>, L<EVP_DigestUpdate(3)>
and L<EVP_DigestFinal_ex(3)>, or the quick one-shot L<EVP_Q_digest(3)>.
Note that the functions L<SHA1(3)>, L<SHA224(3)>, L<SHA256(3)>, L<SHA384(3)>
and L<SHA512(3)> have changed to macros that use L<EVP_Q_digest(3)>.
=head4 Deprecated low-level signing functions
Use of low-level signing functions such as L<DSA_sign(3)> have been
informally discouraged for a long time. Instead applications should use
L<EVP_DigestSign(3)> and L<EVP_DigestVerify(3)>.
See also L<EVP_SIGNATURE-RSA(7)>, L<EVP_SIGNATURE-DSA(7)>,
L<EVP_SIGNATURE-ECDSA(7)> and L<EVP_SIGNATURE-ED25519(7)>.
=head4 Deprecated low-level MAC functions
Low-level mac functions such as L<CMAC_Init(3)> are deprecated.
Applications should instead use the new L<EVP_MAC(3)> interface, using
L<EVP_MAC_CTX_new(3)>, L<EVP_MAC_CTX_free(3)>, L<EVP_MAC_init(3)>,
L<EVP_MAC_update(3)> and L<EVP_MAC_final(3)> or the single-shot MAC function
L<EVP_Q_mac(3)>.
See L<EVP_MAC(3)>, L<EVP_MAC-HMAC(7)>, L<EVP_MAC-CMAC(7)>, L<EVP_MAC-GMAC(7)>,
L<EVP_MAC-KMAC(7)>, L<EVP_MAC-BLAKE2(7)>, L<EVP_MAC-Poly1305(7)> and
L<EVP_MAC-Siphash(7)> for additional information.
Note that the one-shot method HMAC() is still available for compatibility purposes,
but this can also be replaced by using EVP_Q_MAC if a library context is required.
=head4 Deprecated low-level validation functions
Low-level validation functions such as L<DH_check(3)> have been informally
discouraged from use for a long time. Applications should instead use the high-level
EVP_PKEY APIs such as L<EVP_PKEY_check(3)>, L<EVP_PKEY_param_check(3)>,
L<EVP_PKEY_param_check_quick(3)>, L<EVP_PKEY_public_check(3)>,
L<EVP_PKEY_public_check_quick(3)>, L<EVP_PKEY_private_check(3)>,
and L<EVP_PKEY_pairwise_check(3)>.
=head4 Deprecated low-level key exchange functions
Many low-level functions have been informally discouraged from use for a long
time. Applications should instead use L<EVP_PKEY_derive(3)>.
See L<EVP_KEYEXCH-DH(7)>, L<EVP_KEYEXCH-ECDH(7)> and L<EVP_KEYEXCH-X25519(7)>.
=head4 Deprecated low-level key generation functions
Many low-level functions have been informally discouraged from use for a long
time. Applications should instead use L<EVP_PKEY_keygen_init(3)> and
L<EVP_PKEY_generate(3)> as described in L<EVP_PKEY-DSA(7)>, L<EVP_PKEY-DH(7)>,
L<EVP_PKEY-RSA(7)>, L<EVP_PKEY-EC(7)> and L<EVP_PKEY-X25519(7)>.
The 'quick' one-shot function L<EVP_PKEY_Q_keygen(3)> and macros for the most
common cases: <EVP_RSA_gen(3)> and L<EVP_EC_gen(3)> may also be used.
=head4 Deprecated low-level key reading and writing functions
Use of low-level objects (such as DSA) has been informally discouraged from use
for a long time. Functions to read and write these low-level objects (such as
PEM_read_DSA_PUBKEY()) should be replaced. Applications should instead use
L<OSSL_ENCODER_to_bio(3)> and L<OSSL_DECODER_from_bio(3)>.
=head4 Deprecated low-level key printing functions
Use of low-level objects (such as DSA) has been informally discouraged from use
for a long time. Functions to print these low-level objects such as
DSA_print() should be replaced with the equivalent EVP_PKEY functions.
Application should use one of L<EVP_PKEY_print_public(3)>,
L<EVP_PKEY_print_private(3)>, L<EVP_PKEY_print_params(3)>,
L<EVP_PKEY_print_public_fp(3)>, L<EVP_PKEY_print_private_fp(3)> or
L<EVP_PKEY_print_params_fp(3)>. Note that internally these use
L<OSSL_ENCODER_to_bio(3)> and L<OSSL_DECODER_from_bio(3)>.
=head3 Deprecated function mappings
The following functions have been deprecated in 3.0.
=over 4
=item *
AES_bi_ige_encrypt() and AES_ige_encrypt()
There is no replacement for the IGE functions. New code should not use these modes.
These undocumented functions were never integrated into the EVP layer.
They implemented the AES Infinite Garble Extension (IGE) mode and AES
Bi-directional IGE mode. These modes were never formally standardised and
usage of these functions is believed to be very small. In particular
AES_bi_ige_encrypt() has a known bug. It accepts 2 AES keys, but only one
is ever used. The security implications are believed to be minimal, but
this issue was never fixed for backwards compatibility reasons.
=item *
AES_encrypt(), AES_decrypt(), AES_set_encrypt_key(), AES_set_decrypt_key(),
AES_cbc_encrypt(), AES_cfb128_encrypt(), AES_cfb1_encrypt(), AES_cfb8_encrypt(),
AES_ecb_encrypt(), AES_ofb128_encrypt()
=item *
AES_unwrap_key(), AES_wrap_key()
See L</Deprecated low-level encryption functions>
=item *
AES_options()
There is no replacement. It returned a string indicating if the AES code was unrolled.
=item *
ASN1_digest(), ASN1_sign(), ASN1_verify()
There are no replacements. These old functions are not used, and could be
disabled with the macro NO_ASN1_OLD since OpenSSL 0.9.7.
=item *
ASN1_STRING_length_set()
Use L<ASN1_STRING_set(3)> or L<ASN1_STRING_set0(3)> instead.
This was a potentially unsafe function that could change the bounds of a
previously passed in pointer.
=item *
BF_encrypt(), BF_decrypt(), BF_set_key(), BF_cbc_encrypt(), BF_cfb64_encrypt(),
BF_ecb_encrypt(), BF_ofb64_encrypt()
See L</Deprecated low-level encryption functions>.
The Blowfish algorithm has been moved to the L<Legacy Provider|/Legacy Algorithms>.
=item *
BF_options()
There is no replacement. This option returned a constant string.
=item *
BIO_get_callback(), BIO_set_callback(), BIO_debug_callback()
Use the respective non-deprecated _ex() functions.
=item *
BN_is_prime_ex(), BN_is_prime_fasttest_ex()
Use L<BN_check_prime(3)> which avoids possible misuse and always uses at least
64 rounds of the Miller-Rabin primality test.
=item *
BN_pseudo_rand(), BN_pseudo_rand_range()
Use L<BN_rand(3)> and L<BN_rand_range(3)>.
=item *
BN_X931_derive_prime_ex(), BN_X931_generate_prime_ex(), BN_X931_generate_Xpq()
There are no replacements for these low-level functions. They were used internally
by RSA_X931_derive_ex() and RSA_X931_generate_key_ex() which are also deprecated.
Use L<EVP_PKEY_keygen(3)> instead.
=item *
Camellia_encrypt(), Camellia_decrypt(), Camellia_set_key(),
Camellia_cbc_encrypt(), Camellia_cfb128_encrypt(), Camellia_cfb1_encrypt(),
Camellia_cfb8_encrypt(), Camellia_ctr128_encrypt(), Camellia_ecb_encrypt(),
Camellia_ofb128_encrypt()
See L</Deprecated low-level encryption functions>.
=item *
CAST_encrypt(), CAST_decrypt(), CAST_set_key(), CAST_cbc_encrypt(),
CAST_cfb64_encrypt(), CAST_ecb_encrypt(), CAST_ofb64_encrypt()
See L</Deprecated low-level encryption functions>.
The CAST algorithm has been moved to the L<Legacy Provider|/Legacy Algorithms>.
=item *
CMAC_CTX_new(), CMAC_CTX_cleanup(), CMAC_CTX_copy(), CMAC_CTX_free(),
CMAC_CTX_get0_cipher_ctx()
See L</Deprecated low-level MAC functions>.
=item *
CMAC_Init(), CMAC_Update(), CMAC_Final(), CMAC_resume()
See L</Deprecated low-level MAC functions>.
=item *
CRYPTO_mem_ctrl(), CRYPTO_mem_debug_free(), CRYPTO_mem_debug_malloc(),
CRYPTO_mem_debug_pop(), CRYPTO_mem_debug_push(), CRYPTO_mem_debug_realloc(),
CRYPTO_mem_leaks(), CRYPTO_mem_leaks_cb(), CRYPTO_mem_leaks_fp(),
CRYPTO_set_mem_debug()
Memory-leak checking has been deprecated in favor of more modern development
tools, such as compiler memory and leak sanitizers or Valgrind.
=item *
CRYPTO_cts128_encrypt_block(), CRYPTO_cts128_encrypt(),
CRYPTO_cts128_decrypt_block(), CRYPTO_cts128_decrypt(),
CRYPTO_nistcts128_encrypt_block(), CRYPTO_nistcts128_encrypt(),
CRYPTO_nistcts128_decrypt_block(), CRYPTO_nistcts128_decrypt()
Use the higher level functions EVP_CipherInit_ex2(), EVP_CipherUpdate() and
EVP_CipherFinal_ex() instead.
See the "cts_mode" parameter in
L<EVP_EncryptInit(3)/Gettable and Settable EVP_CIPHER_CTX parameters>.
See L<EVP_EncryptInit(3)/EXAMPLES> for a AES-256-CBC-CTS example.
=item *
d2i_DHparams(), d2i_DHxparams(), d2i_DSAparams(), d2i_DSAPrivateKey(),
d2i_DSAPrivateKey_bio(), d2i_DSAPrivateKey_fp(), d2i_DSA_PUBKEY(),
d2i_DSA_PUBKEY_bio(), d2i_DSA_PUBKEY_fp(), d2i_DSAPublicKey(),
d2i_ECParameters(), d2i_ECPrivateKey(), d2i_ECPrivateKey_bio(),
d2i_ECPrivateKey_fp(), d2i_EC_PUBKEY(), d2i_EC_PUBKEY_bio(),
-d2i_EC_PUBKEY_fp(), o2i_ECPublicKey(), d2i_RSAPrivateKey(),
+d2i_EC_PUBKEY_fp(), d2i_RSAPrivateKey(),
d2i_RSAPrivateKey_bio(), d2i_RSAPrivateKey_fp(), d2i_RSA_PUBKEY(),
d2i_RSA_PUBKEY_bio(), d2i_RSA_PUBKEY_fp(), d2i_RSAPublicKey(),
d2i_RSAPublicKey_bio(), d2i_RSAPublicKey_fp()
See L</Deprecated i2d and d2i functions for low-level key types>
=item *
+o2i_ECPublicKey()
+
+Use L<EVP_PKEY_set1_encoded_public_key(3)>.
+See L</Deprecated low-level key parameter setters>
+
+=item *
+
DES_crypt(), DES_fcrypt(), DES_encrypt1(), DES_encrypt2(), DES_encrypt3(),
DES_decrypt3(), DES_ede3_cbc_encrypt(), DES_ede3_cfb64_encrypt(),
DES_ede3_cfb_encrypt(),DES_ede3_ofb64_encrypt(),
DES_ecb_encrypt(), DES_ecb3_encrypt(), DES_ofb64_encrypt(), DES_ofb_encrypt(),
DES_cfb64_encrypt DES_cfb_encrypt(), DES_cbc_encrypt(), DES_ncbc_encrypt(),
DES_pcbc_encrypt(), DES_xcbc_encrypt(), DES_cbc_cksum(), DES_quad_cksum(),
DES_check_key_parity(), DES_is_weak_key(), DES_key_sched(), DES_options(),
DES_random_key(), DES_set_key(), DES_set_key_checked(), DES_set_key_unchecked(),
DES_set_odd_parity(), DES_string_to_2keys(), DES_string_to_key()
See L</Deprecated low-level encryption functions>.
Algorithms for "DESX-CBC", "DES-ECB", "DES-CBC", "DES-OFB", "DES-CFB",
"DES-CFB1" and "DES-CFB8" have been moved to the L<Legacy Provider|/Legacy Algorithms>.
=item *
DH_bits(), DH_security_bits(), DH_size()
Use L<EVP_PKEY_get_bits(3)>, L<EVP_PKEY_get_security_bits(3)> and
L<EVP_PKEY_get_size(3)>.
=item *
DH_check(), DH_check_ex(), DH_check_params(), DH_check_params_ex(),
DH_check_pub_key(), DH_check_pub_key_ex()
See L</Deprecated low-level validation functions>
=item *
DH_clear_flags(), DH_test_flags(), DH_set_flags()
The B<DH_FLAG_CACHE_MONT_P> flag has been deprecated without replacement.
The B<DH_FLAG_TYPE_DH> and B<DH_FLAG_TYPE_DHX> have been deprecated.
Use EVP_PKEY_is_a() to determine the type of a key.
There is no replacement for setting these flags.
=item *
DH_compute_key() DH_compute_key_padded()
See L</Deprecated low-level key exchange functions>.
=item *
DH_new(), DH_new_by_nid(), DH_free(), DH_up_ref()
See L</Deprecated low-level object creation>
=item *
DH_generate_key(), DH_generate_parameters_ex()
See L</Deprecated low-level key generation functions>.
=item *
DH_get0_pqg(), DH_get0_p(), DH_get0_q(), DH_get0_g(), DH_get0_key(),
DH_get0_priv_key(), DH_get0_pub_key(), DH_get_length(), DH_get_nid()
See L</Deprecated low-level key parameter getters>
=item *
DH_get_1024_160(), DH_get_2048_224(), DH_get_2048_256()
Applications should instead set the B<OSSL_PKEY_PARAM_GROUP_NAME> as specified in
L<EVP_PKEY-DH(7)/DH parameters>) to one of "dh_1024_160", "dh_2048_224" or
"dh_2048_256" when generating a DH key.
=item *
DH_KDF_X9_42()
Applications should use L<EVP_PKEY_CTX_set_dh_kdf_type(3)> instead.
=item *
DH_get_default_method(), DH_get0_engine(), DH_meth_*(), DH_new_method(),
DH_OpenSSL(), DH_get_ex_data(), DH_set_default_method(), DH_set_method(),
DH_set_ex_data()
See L</Providers are a replacement for engines and low-level method overrides>
=item *
DHparams_print(), DHparams_print_fp()
See L</Deprecated low-level key printing functions>
=item *
DH_set0_key(), DH_set0_pqg(), DH_set_length()
See L</Deprecated low-level key parameter setters>
=item *
DSA_bits(), DSA_security_bits(), DSA_size()
Use L<EVP_PKEY_get_bits(3)>, L<EVP_PKEY_get_security_bits(3)> and
L<EVP_PKEY_get_size(3)>.
=item *
DHparams_dup(), DSA_dup_DH()
There is no direct replacement. Applications may use L<EVP_PKEY_copy_parameters(3)>
and L<EVP_PKEY_dup(3)> instead.
=item *
DSA_generate_key(), DSA_generate_parameters_ex()
See L</Deprecated low-level key generation functions>.
=item *
DSA_get0_engine(), DSA_get_default_method(), DSA_get_ex_data(),
DSA_get_method(), DSA_meth_*(), DSA_new_method(), DSA_OpenSSL(),
DSA_set_default_method(), DSA_set_ex_data(), DSA_set_method()
See L</Providers are a replacement for engines and low-level method overrides>.
=item *
DSA_get0_p(), DSA_get0_q(), DSA_get0_g(), DSA_get0_pqg(), DSA_get0_key(),
DSA_get0_priv_key(), DSA_get0_pub_key()
See L</Deprecated low-level key parameter getters>.
=item *
DSA_new(), DSA_free(), DSA_up_ref()
See L</Deprecated low-level object creation>
=item *
DSAparams_dup()
There is no direct replacement. Applications may use L<EVP_PKEY_copy_parameters(3)>
and L<EVP_PKEY_dup(3)> instead.
=item *
DSAparams_print(), DSAparams_print_fp(), DSA_print(), DSA_print_fp()
See L</Deprecated low-level key printing functions>
=item *
DSA_set0_key(), DSA_set0_pqg()
See L</Deprecated low-level key parameter setters>
=item *
DSA_set_flags(), DSA_clear_flags(), DSA_test_flags()
The B<DSA_FLAG_CACHE_MONT_P> flag has been deprecated without replacement.
=item *
DSA_sign(), DSA_do_sign(), DSA_sign_setup(), DSA_verify(), DSA_do_verify()
See L</Deprecated low-level signing functions>.
=item *
ECDH_compute_key()
See L</Deprecated low-level key exchange functions>.
=item *
ECDH_KDF_X9_62()
Applications may either set this using the helper function
L<EVP_PKEY_CTX_set_ecdh_kdf_type(3)> or by setting an L<OSSL_PARAM(3)> using the
"kdf-type" as shown in L<EVP_KEYEXCH-ECDH(7)/EXAMPLES>
=item *
ECDSA_sign(), ECDSA_sign_ex(), ECDSA_sign_setup(), ECDSA_do_sign(),
ECDSA_do_sign_ex(), ECDSA_verify(), ECDSA_do_verify()
See L</Deprecated low-level signing functions>.
=item *
ECDSA_size()
Applications should use L<EVP_PKEY_get_size(3)>.
=item *
EC_GF2m_simple_method(), EC_GFp_mont_method(), EC_GFp_nist_method(),
EC_GFp_nistp224_method(), EC_GFp_nistp256_method(), EC_GFp_nistp521_method(),
EC_GFp_simple_method()
There are no replacements for these functions. Applications should rely on the
library automatically assigning a suitable method internally when an EC_GROUP
is constructed.
=item *
EC_GROUP_clear_free()
Use L<EC_GROUP_free(3)> instead.
=item *
EC_GROUP_get_curve_GF2m(), EC_GROUP_get_curve_GFp(), EC_GROUP_set_curve_GF2m(),
EC_GROUP_set_curve_GFp()
Applications should use L<EC_GROUP_get_curve(3)> and L<EC_GROUP_set_curve(3)>.
=item *
EC_GROUP_have_precompute_mult(), EC_GROUP_precompute_mult(),
EC_KEY_precompute_mult()
These functions are not widely used. Applications should instead switch to
named curves which OpenSSL has hardcoded lookup tables for.
=item *
EC_GROUP_new(), EC_GROUP_method_of(), EC_POINT_method_of()
EC_METHOD is now an internal-only concept and a suitable EC_METHOD is assigned
internally without application intervention.
Users of EC_GROUP_new() should switch to a different suitable constructor.
=item *
EC_KEY_can_sign()
Applications should use L<EVP_PKEY_can_sign(3)> instead.
=item *
EC_KEY_check_key()
See L</Deprecated low-level validation functions>
=item *
EC_KEY_set_flags(), EC_KEY_get_flags(), EC_KEY_clear_flags()
See L<EVP_PKEY-EC(7)/Common EC parameters> which handles flags as separate
parameters for B<OSSL_PKEY_PARAM_EC_POINT_CONVERSION_FORMAT>,
B<OSSL_PKEY_PARAM_EC_GROUP_CHECK_TYPE>, B<OSSL_PKEY_PARAM_EC_ENCODING>,
B<OSSL_PKEY_PARAM_USE_COFACTOR_ECDH> and
B<OSSL_PKEY_PARAM_EC_INCLUDE_PUBLIC>.
See also L<EVP_PKEY-EC(7)/EXAMPLES>
=item *
EC_KEY_dup(), EC_KEY_copy()
There is no direct replacement. Applications may use L<EVP_PKEY_copy_parameters(3)>
and L<EVP_PKEY_dup(3)> instead.
=item *
EC_KEY_decoded_from_explicit_params()
There is no replacement.
=item *
EC_KEY_generate_key()
See L</Deprecated low-level key generation functions>.
=item *
EC_KEY_get0_group(), EC_KEY_get0_private_key(), EC_KEY_get0_public_key(),
EC_KEY_get_conv_form(), EC_KEY_get_enc_flags()
See L</Deprecated low-level key parameter getters>.
=item *
EC_KEY_get0_engine(), EC_KEY_get_default_method(), EC_KEY_get_method(),
EC_KEY_new_method(), EC_KEY_get_ex_data(), EC_KEY_OpenSSL(),
EC_KEY_set_ex_data(), EC_KEY_set_default_method(), EC_KEY_METHOD_*(),
EC_KEY_set_method()
See L</Providers are a replacement for engines and low-level method overrides>
=item *
EC_METHOD_get_field_type()
Use L<EC_GROUP_get_field_type(3)> instead.
See L</Providers are a replacement for engines and low-level method overrides>
=item *
EC_KEY_key2buf(), EC_KEY_oct2key(), EC_KEY_oct2priv(), EC_KEY_priv2buf(),
EC_KEY_priv2oct()
There are no replacements for these.
=item *
EC_KEY_new(), EC_KEY_new_by_curve_name(), EC_KEY_free(), EC_KEY_up_ref()
See L</Deprecated low-level object creation>
=item *
EC_KEY_print(), EC_KEY_print_fp()
See L</Deprecated low-level key printing functions>
=item *
EC_KEY_set_asn1_flag(), EC_KEY_set_conv_form(), EC_KEY_set_enc_flags()
See L</Deprecated low-level key parameter setters>.
=item *
EC_KEY_set_group(), EC_KEY_set_private_key(), EC_KEY_set_public_key(),
EC_KEY_set_public_key_affine_coordinates()
See L</Deprecated low-level key parameter setters>.
=item *
ECParameters_print(), ECParameters_print_fp(), ECPKParameters_print(),
ECPKParameters_print_fp()
See L</Deprecated low-level key printing functions>
=item *
EC_POINT_bn2point(), EC_POINT_point2bn()
These functions were not particularly useful, since EC point serialization
formats are not individual big-endian integers.
=item *
EC_POINT_get_affine_coordinates_GF2m(), EC_POINT_get_affine_coordinates_GFp(),
EC_POINT_set_affine_coordinates_GF2m(), EC_POINT_set_affine_coordinates_GFp()
Applications should use L<EC_POINT_get_affine_coordinates(3)> and
L<EC_POINT_set_affine_coordinates(3)> instead.
=item *
EC_POINT_get_Jprojective_coordinates_GFp(), EC_POINT_set_Jprojective_coordinates_GFp()
These functions are not widely used. Applications should instead use the
L<EC_POINT_set_affine_coordinates(3)> and L<EC_POINT_get_affine_coordinates(3)>
functions.
=item *
EC_POINT_make_affine(), EC_POINTs_make_affine()
There is no replacement. These functions were not widely used, and OpenSSL
automatically performs this conversion when needed.
=item *
EC_POINT_set_compressed_coordinates_GF2m(), EC_POINT_set_compressed_coordinates_GFp()
Applications should use L<EC_POINT_set_compressed_coordinates(3)> instead.
=item *
EC_POINTs_mul()
This function is not widely used. Applications should instead use the
L<EC_POINT_mul(3)> function.
=item *
B<ENGINE_*()>
All engine functions are deprecated. An engine should be rewritten as a provider.
See L</Providers are a replacement for engines and low-level method overrides>.
=item *
B<ERR_load_*()>, ERR_func_error_string(), ERR_get_error_line(),
ERR_get_error_line_data(), ERR_get_state()
OpenSSL now loads error strings automatically so these functions are not needed.
=item *
ERR_peek_error_line_data(), ERR_peek_last_error_line_data()
The new functions are L<ERR_peek_error_func(3)>, L<ERR_peek_last_error_func(3)>,
L<ERR_peek_error_data(3)>, L<ERR_peek_last_error_data(3)>, L<ERR_get_error_all(3)>,
L<ERR_peek_error_all(3)> and L<ERR_peek_last_error_all(3)>.
Applications should use L<ERR_get_error_all(3)>, or pick information
with ERR_peek functions and finish off with getting the error code by using
L<ERR_get_error(3)>.
=item *
EVP_CIPHER_CTX_iv(), EVP_CIPHER_CTX_iv_noconst(), EVP_CIPHER_CTX_original_iv()
Applications should instead use L<EVP_CIPHER_CTX_get_updated_iv(3)>,
L<EVP_CIPHER_CTX_get_updated_iv(3)> and L<EVP_CIPHER_CTX_get_original_iv(3)>
respectively.
See L<EVP_CIPHER_CTX_get_original_iv(3)> for further information.
=item *
B<EVP_CIPHER_meth_*()>, EVP_MD_CTX_set_update_fn(), EVP_MD_CTX_update_fn(),
B<EVP_MD_meth_*()>
See L</Providers are a replacement for engines and low-level method overrides>.
=item *
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()
These control operations are not invoked by the OpenSSL library anymore and
are replaced by direct checks of the key operation against the key type
when the operation is initialized.
=item *
EVP_PKEY_CTX_get0_dh_kdf_ukm(), EVP_PKEY_CTX_get0_ecdh_kdf_ukm()
See the "kdf-ukm" item in L<EVP_KEYEXCH-DH(7)/DH key exchange parameters> and
L<EVP_KEYEXCH-ECDH(7)/ECDH Key Exchange parameters>.
These functions are obsolete and should not be required.
=item *
EVP_PKEY_CTX_set_rsa_keygen_pubexp()
Applications should use L<EVP_PKEY_CTX_set1_rsa_keygen_pubexp(3)> instead.
=item *
EVP_PKEY_cmp(), EVP_PKEY_cmp_parameters()
Applications should use L<EVP_PKEY_eq(3)> and L<EVP_PKEY_parameters_eq(3)> instead.
See L<EVP_PKEY_copy_parameters(3)> for further details.
=item *
EVP_PKEY_encrypt_old(), EVP_PKEY_decrypt_old(),
Applications should use L<EVP_PKEY_encrypt_init(3)> and L<EVP_PKEY_encrypt(3)> or
L<EVP_PKEY_decrypt_init(3)> and L<EVP_PKEY_decrypt(3)> instead.
=item *
EVP_PKEY_get0()
This function returns NULL if the key comes from a provider.
=item *
EVP_PKEY_get0_DH(), EVP_PKEY_get0_DSA(), EVP_PKEY_get0_EC_KEY(), EVP_PKEY_get0_RSA(),
EVP_PKEY_get1_DH(), EVP_PKEY_get1_DSA(), EVP_PKEY_get1_EC_KEY and EVP_PKEY_get1_RSA(),
EVP_PKEY_get0_hmac(), EVP_PKEY_get0_poly1305(), EVP_PKEY_get0_siphash()
See L</Functions that return an internal key should be treated as read only>.
=item *
B<EVP_PKEY_meth_*()>
See L</Providers are a replacement for engines and low-level method overrides>.
=item *
EVP_PKEY_new_CMAC_key()
See L</Deprecated low-level MAC functions>.
=item *
EVP_PKEY_assign(), EVP_PKEY_set1_DH(), EVP_PKEY_set1_DSA(),
EVP_PKEY_set1_EC_KEY(), EVP_PKEY_set1_RSA()
See L</Deprecated low-level key object getters and setters>
=item *
EVP_PKEY_set1_tls_encodedpoint() EVP_PKEY_get1_tls_encodedpoint()
These functions were previously used by libssl to set or get an encoded public
key into/from an EVP_PKEY object. With OpenSSL 3.0 these are replaced by the more
generic functions L<EVP_PKEY_set1_encoded_public_key(3)> and
L<EVP_PKEY_get1_encoded_public_key(3)>.
The old versions have been converted to deprecated macros that just call the
new functions.
=item *
EVP_PKEY_set1_engine(), EVP_PKEY_get0_engine()
See L</Providers are a replacement for engines and low-level method overrides>.
=item *
EVP_PKEY_set_alias_type()
This function has been removed. There is no replacement.
See L</EVP_PKEY_set_alias_type() method has been removed>
=item *
HMAC_Init_ex(), HMAC_Update(), HMAC_Final(), HMAC_size()
See L</Deprecated low-level MAC functions>.
=item *
HMAC_CTX_new(), HMAC_CTX_free(), HMAC_CTX_copy(), HMAC_CTX_reset(),
HMAC_CTX_set_flags(), HMAC_CTX_get_md()
See L</Deprecated low-level MAC functions>.
=item *
i2d_DHparams(), i2d_DHxparams()
See L</Deprecated low-level key reading and writing functions>
and L<d2i_RSAPrivateKey(3)/Migration>
=item *
i2d_DSAparams(), i2d_DSAPrivateKey(), i2d_DSAPrivateKey_bio(),
i2d_DSAPrivateKey_fp(), i2d_DSA_PUBKEY(), i2d_DSA_PUBKEY_bio(),
i2d_DSA_PUBKEY_fp(), i2d_DSAPublicKey()
See L</Deprecated low-level key reading and writing functions>
and L<d2i_RSAPrivateKey(3)/Migration>
=item *
i2d_ECParameters(), i2d_ECPrivateKey(), i2d_ECPrivateKey_bio(),
i2d_ECPrivateKey_fp(), i2d_EC_PUBKEY(), i2d_EC_PUBKEY_bio(),
-i2d_EC_PUBKEY_fp(), i2o_ECPublicKey()
+i2d_EC_PUBKEY_fp()
See L</Deprecated low-level key reading and writing functions>
and L<d2i_RSAPrivateKey(3)/Migration>
=item *
+i2o_ECPublicKey()
+
+Use L<EVP_PKEY_get1_encoded_public_key(3)>.
+See L</Deprecated low-level key parameter getters>
+
+=item *
+
i2d_RSAPrivateKey(), i2d_RSAPrivateKey_bio(), i2d_RSAPrivateKey_fp(),
i2d_RSA_PUBKEY(), i2d_RSA_PUBKEY_bio(), i2d_RSA_PUBKEY_fp(),
i2d_RSAPublicKey(), i2d_RSAPublicKey_bio(), i2d_RSAPublicKey_fp()
See L</Deprecated low-level key reading and writing functions>
and L<d2i_RSAPrivateKey(3)/Migration>
=item *
IDEA_encrypt(), IDEA_set_decrypt_key(), IDEA_set_encrypt_key(),
IDEA_cbc_encrypt(), IDEA_cfb64_encrypt(), IDEA_ecb_encrypt(),
IDEA_ofb64_encrypt()
See L</Deprecated low-level encryption functions>.
IDEA has been moved to the L<Legacy Provider|/Legacy Algorithms>.
=item *
IDEA_options()
There is no replacement. This function returned a constant string.
=item *
MD2(), MD2_Init(), MD2_Update(), MD2_Final()
See L</Deprecated low-level encryption functions>.
MD2 has been moved to the L<Legacy Provider|/Legacy Algorithms>.
=item *
MD2_options()
There is no replacement. This function returned a constant string.
=item *
MD4(), MD4_Init(), MD4_Update(), MD4_Final(), MD4_Transform()
See L</Deprecated low-level encryption functions>.
MD4 has been moved to the L<Legacy Provider|/Legacy Algorithms>.
=item *
MDC2(), MDC2_Init(), MDC2_Update(), MDC2_Final()
See L</Deprecated low-level encryption functions>.
MDC2 has been moved to the L<Legacy Provider|/Legacy Algorithms>.
=item *
MD5(), MD5_Init(), MD5_Update(), MD5_Final(), MD5_Transform()
See L</Deprecated low-level encryption functions>.
=item *
NCONF_WIN32()
This undocumented function has no replacement.
See L<config(5)/HISTORY> for more details.
=item *
OCSP_parse_url()
Use L<OSSL_HTTP_parse_url(3)> instead.
=item *
B<OCSP_REQ_CTX> type and B<OCSP_REQ_CTX_*()> functions
These methods were used to collect all necessary data to form a HTTP request,
and to perform the HTTP transfer with that request. With OpenSSL 3.0, the
type is B<OSSL_HTTP_REQ_CTX>, and the deprecated functions are replaced
with B<OSSL_HTTP_REQ_CTX_*()>. See L<OSSL_HTTP_REQ_CTX(3)> for additional
details.
=item *
OPENSSL_fork_child(), OPENSSL_fork_parent(), OPENSSL_fork_prepare()
There is no replacement for these functions. These pthread fork support methods
were unused by OpenSSL.
=item *
OSSL_STORE_ctrl(), OSSL_STORE_do_all_loaders(), OSSL_STORE_LOADER_get0_engine(),
OSSL_STORE_LOADER_get0_scheme(), OSSL_STORE_LOADER_new(),
OSSL_STORE_LOADER_set_attach(), OSSL_STORE_LOADER_set_close(),
OSSL_STORE_LOADER_set_ctrl(), OSSL_STORE_LOADER_set_eof(),
OSSL_STORE_LOADER_set_error(), OSSL_STORE_LOADER_set_expect(),
OSSL_STORE_LOADER_set_find(), OSSL_STORE_LOADER_set_load(),
OSSL_STORE_LOADER_set_open(), OSSL_STORE_LOADER_set_open_ex(),
OSSL_STORE_register_loader(), OSSL_STORE_unregister_loader(),
OSSL_STORE_vctrl()
These functions helped applications and engines create loaders for
schemes they supported. These are all deprecated and discouraged in favour of
provider implementations, see L<provider-storemgmt(7)>.
=item *
PEM_read_DHparams(), PEM_read_bio_DHparams(),
PEM_read_DSAparams(), PEM_read_bio_DSAparams(),
PEM_read_DSAPrivateKey(), PEM_read_DSA_PUBKEY(),
PEM_read_bio_DSAPrivateKey and PEM_read_bio_DSA_PUBKEY(),
PEM_read_ECPKParameters(), PEM_read_ECPrivateKey(), PEM_read_EC_PUBKEY(),
PEM_read_bio_ECPKParameters(), PEM_read_bio_ECPrivateKey(), PEM_read_bio_EC_PUBKEY(),
PEM_read_RSAPrivateKey(), PEM_read_RSA_PUBKEY(), PEM_read_RSAPublicKey(),
PEM_read_bio_RSAPrivateKey(), PEM_read_bio_RSA_PUBKEY(), PEM_read_bio_RSAPublicKey(),
PEM_write_bio_DHparams(), PEM_write_bio_DHxparams(), PEM_write_DHparams(), PEM_write_DHxparams(),
PEM_write_DSAparams(), PEM_write_DSAPrivateKey(), PEM_write_DSA_PUBKEY(),
PEM_write_bio_DSAparams(), PEM_write_bio_DSAPrivateKey(), PEM_write_bio_DSA_PUBKEY(),
PEM_write_ECPKParameters(), PEM_write_ECPrivateKey(), PEM_write_EC_PUBKEY(),
PEM_write_bio_ECPKParameters(), PEM_write_bio_ECPrivateKey(), PEM_write_bio_EC_PUBKEY(),
PEM_write_RSAPrivateKey(), PEM_write_RSA_PUBKEY(), PEM_write_RSAPublicKey(),
PEM_write_bio_RSAPrivateKey(), PEM_write_bio_RSA_PUBKEY(),
PEM_write_bio_RSAPublicKey(),
See L</Deprecated low-level key reading and writing functions>
=item *
PKCS1_MGF1()
See L</Deprecated low-level encryption functions>.
=item *
RAND_get_rand_method(), RAND_set_rand_method(), RAND_OpenSSL(),
RAND_set_rand_engine()
Applications should instead use L<RAND_set_DRBG_type(3)>,
L<EVP_RAND(3)> and L<EVP_RAND(7)>.
See L<RAND_set_rand_method(3)> for more details.
=item *
RC2_encrypt(), RC2_decrypt(), RC2_set_key(), RC2_cbc_encrypt(), RC2_cfb64_encrypt(),
RC2_ecb_encrypt(), RC2_ofb64_encrypt(),
RC4(), RC4_set_key(), RC4_options(),
RC5_32_encrypt(), RC5_32_set_key(), RC5_32_decrypt(), RC5_32_cbc_encrypt(),
RC5_32_cfb64_encrypt(), RC5_32_ecb_encrypt(), RC5_32_ofb64_encrypt()
See L</Deprecated low-level encryption functions>.
The Algorithms "RC2", "RC4" and "RC5" have been moved to the L<Legacy Provider|/Legacy Algorithms>.
=item *
RIPEMD160(), RIPEMD160_Init(), RIPEMD160_Update(), RIPEMD160_Final(),
RIPEMD160_Transform()
See L</Deprecated low-level digest functions>.
The RIPE algorithm has been moved to the L<Legacy Provider|/Legacy Algorithms>.
=item *
RSA_bits(), RSA_security_bits(), RSA_size()
Use L<EVP_PKEY_get_bits(3)>, L<EVP_PKEY_get_security_bits(3)> and
L<EVP_PKEY_get_size(3)>.
=item *
RSA_check_key(), RSA_check_key_ex()
See L</Deprecated low-level validation functions>
=item *
RSA_clear_flags(), RSA_flags(), RSA_set_flags(), RSA_test_flags(),
RSA_setup_blinding(), RSA_blinding_off(), RSA_blinding_on()
All of these RSA flags have been deprecated without replacement:
B<RSA_FLAG_BLINDING>, B<RSA_FLAG_CACHE_PRIVATE>, B<RSA_FLAG_CACHE_PUBLIC>,
B<RSA_FLAG_EXT_PKEY>, B<RSA_FLAG_NO_BLINDING>, B<RSA_FLAG_THREAD_SAFE>
B<RSA_METHOD_FLAG_NO_CHECK>
=item *
RSA_generate_key_ex(), RSA_generate_multi_prime_key()
See L</Deprecated low-level key generation functions>.
=item *
RSA_get0_engine()
See L</Providers are a replacement for engines and low-level method overrides>
=item *
RSA_get0_crt_params(), RSA_get0_d(), RSA_get0_dmp1(), RSA_get0_dmq1(),
RSA_get0_e(), RSA_get0_factors(), RSA_get0_iqmp(), RSA_get0_key(),
RSA_get0_multi_prime_crt_params(), RSA_get0_multi_prime_factors(), RSA_get0_n(),
RSA_get0_p(), RSA_get0_pss_params(), RSA_get0_q(),
RSA_get_multi_prime_extra_count()
See L</Deprecated low-level key parameter getters>
=item *
RSA_new(), RSA_free(), RSA_up_ref()
See L</Deprecated low-level object creation>.
=item *
RSA_get_default_method(), RSA_get_ex_data and RSA_get_method()
See L</Providers are a replacement for engines and low-level method overrides>.
=item *
RSA_get_version()
There is no replacement.
=item *
B<RSA_meth_*()>, RSA_new_method(), RSA_null_method and RSA_PKCS1_OpenSSL()
See L</Providers are a replacement for engines and low-level method overrides>.
=item *
B<RSA_padding_add_*()>, B<RSA_padding_check_*()>
See L</Deprecated low-level signing functions> and
L</Deprecated low-level encryption functions>.
=item *
RSA_print(), RSA_print_fp()
See L</Deprecated low-level key printing functions>
=item *
RSA_public_encrypt(), RSA_private_decrypt()
See L</Deprecated low-level encryption functions>
=item *
RSA_private_encrypt(), RSA_public_decrypt()
This is equivalent to doing sign and verify recover operations (with a padding
mode of none). See L</Deprecated low-level signing functions>.
=item *
RSAPrivateKey_dup(), RSAPublicKey_dup()
There is no direct replacement. Applications may use L<EVP_PKEY_dup(3)>.
=item *
RSAPublicKey_it(), RSAPrivateKey_it()
See L</Deprecated low-level key reading and writing functions>
=item *
RSA_set0_crt_params(), RSA_set0_factors(), RSA_set0_key(),
RSA_set0_multi_prime_params()
See L</Deprecated low-level key parameter setters>.
=item *
RSA_set_default_method(), RSA_set_method(), RSA_set_ex_data()
See L</Providers are a replacement for engines and low-level method overrides>
=item *
RSA_sign(), RSA_sign_ASN1_OCTET_STRING(), RSA_verify(),
RSA_verify_ASN1_OCTET_STRING(), RSA_verify_PKCS1_PSS(),
RSA_verify_PKCS1_PSS_mgf1()
See L</Deprecated low-level signing functions>.
=item *
RSA_X931_derive_ex(), RSA_X931_generate_key_ex(), RSA_X931_hash_id()
There are no replacements for these functions.
X931 padding can be set using L<EVP_SIGNATURE-RSA(7)/Signature Parameters>.
See B<OSSL_SIGNATURE_PARAM_PAD_MODE>.
=item *
SEED_encrypt(), SEED_decrypt(), SEED_set_key(), SEED_cbc_encrypt(),
SEED_cfb128_encrypt(), SEED_ecb_encrypt(), SEED_ofb128_encrypt()
See L</Deprecated low-level encryption functions>.
The SEED algorithm has been moved to the L<Legacy Provider|/Legacy Algorithms>.
=item *
SHA1_Init(), SHA1_Update(), SHA1_Final(), SHA1_Transform(),
SHA224_Init(), SHA224_Update(), SHA224_Final(),
SHA256_Init(), SHA256_Update(), SHA256_Final(), SHA256_Transform(),
SHA384_Init(), SHA384_Update(), SHA384_Final(),
SHA512_Init(), SHA512_Update(), SHA512_Final(), SHA512_Transform()
See L</Deprecated low-level digest functions>.
=item *
SRP_Calc_A(), SRP_Calc_B(), SRP_Calc_client_key(), SRP_Calc_server_key(),
SRP_Calc_u(), SRP_Calc_x(), SRP_check_known_gN_param(), SRP_create_verifier(),
SRP_create_verifier_BN(), SRP_get_default_gN(), SRP_user_pwd_free(), SRP_user_pwd_new(),
SRP_user_pwd_set0_sv(), SRP_user_pwd_set1_ids(), SRP_user_pwd_set_gN(),
SRP_VBASE_add0_user(), SRP_VBASE_free(), SRP_VBASE_get1_by_user(), SRP_VBASE_init(),
SRP_VBASE_new(), SRP_Verify_A_mod_N(), SRP_Verify_B_mod_N()
There are no replacements for the SRP functions.
=item *
SSL_CTX_set_tmp_dh_callback(), SSL_set_tmp_dh_callback(),
SSL_CTX_set_tmp_dh(), SSL_set_tmp_dh()
These are used to set the Diffie-Hellman (DH) parameters that are to be used by
servers requiring ephemeral DH keys. Instead applications should consider using
the built-in DH parameters that are available by calling L<SSL_CTX_set_dh_auto(3)>
or L<SSL_set_dh_auto(3)>. If custom parameters are necessary then applications can
use the alternative functions L<SSL_CTX_set0_tmp_dh_pkey(3)> and
L<SSL_set0_tmp_dh_pkey(3)>. There is no direct replacement for the "callback"
functions. The callback was originally useful in order to have different
parameters for export and non-export ciphersuites. Export ciphersuites are no
longer supported by OpenSSL. Use of the callback functions should be replaced
by one of the other methods described above.
=item *
SSL_CTX_set_tlsext_ticket_key_cb()
Use the new L<SSL_CTX_set_tlsext_ticket_key_evp_cb(3)> function instead.
=item *
WHIRLPOOL(), WHIRLPOOL_Init(), WHIRLPOOL_Update(), WHIRLPOOL_Final(),
WHIRLPOOL_BitUpdate()
See L</Deprecated low-level digest functions>.
The Whirlpool algorithm has been moved to the L<Legacy Provider|/Legacy Algorithms>.
=item *
X509_certificate_type()
This was an undocumented function. Applications can use L<X509_get0_pubkey(3)>
and L<X509_get0_signature(3)> instead.
=item *
X509_http_nbio(), X509_CRL_http_nbio()
Use L<X509_load_http(3)> and L<X509_CRL_load_http(3)> instead.
=back
=head3 NID handling for provided keys and algorithms
The following functions for NID (numeric id) handling have changed semantics.
=over 4
=item *
EVP_PKEY_id(), EVP_PKEY_get_id()
This function was previously used to reliably return the NID of
an EVP_PKEY object, e.g., to look up the name of the algorithm of
such EVP_PKEY by calling L<OBJ_nid2sn(3)>. With the introduction
of L<provider(7)>s EVP_PKEY_id() or its new equivalent
L<EVP_PKEY_get_id(3)> might now also return the value -1
(B<EVP_PKEY_KEYMGMT>) indicating the use of a provider to
implement the EVP_PKEY object. Therefore, the use of
L<EVP_PKEY_get0_type_name(3)> is recommended for retrieving
the name of the EVP_PKEY algorithm.
=back
=head2 Using the FIPS Module in applications
See L<fips_module(7)> and L<OSSL_PROVIDER-FIPS(7)> for details.
=head2 OpenSSL command line application changes
=head3 New applications
L<B<openssl kdf>|openssl-kdf(1)> uses the new L<EVP_KDF(3)> API.
L<B<openssl kdf>|openssl-mac(1)> uses the new L<EVP_MAC(3)> API.
=head3 Added options
B<-provider_path> and B<-provider> are available to all apps and can be used
multiple times to load any providers, such as the 'legacy' provider or third
party providers. If used then the 'default' provider would also need to be
specified if required. The B<-provider_path> must be specified before the
B<-provider> option.
The B<list> app has many new options. See L<openssl-list(1)> for more
information.
B<-crl_lastupdate> and B<-crl_nextupdate> used by B<openssl ca> allows
explicit setting of fields in the generated CRL.
=head3 Removed options
Interactive mode is not longer available.
The B<-crypt> option used by B<openssl passwd>.
The B<-c> option used by B<openssl x509>, B<openssl dhparam>,
B<openssl dsaparam>, and B<openssl ecparam>.
=head3 Other Changes
The output of Command line applications may have minor changes.
These are primarily changes in capitalisation and white space. However, in some
cases, there are additional differences.
For example, the DH parameters output from B<openssl dhparam> now lists 'P',
'Q', 'G' and 'pcounter' instead of 'prime', 'generator', 'subgroup order' and
'counter' respectively.
The B<openssl> commands that read keys, certificates, and CRLs now
automatically detect the PEM or DER format of the input files so it is not
necessary to explicitly specify the input format anymore. However if the
input format option is used the specified format will be required.
B<openssl speed> no longer uses low-level API calls.
This implies some of the performance numbers might not be comparable with the
previous releases due to higher overhead. This applies particularly to
measuring performance on smaller data chunks.
b<openssl dhparam>, B<openssl dsa>, B<openssl gendsa>, B<openssl dsaparam>,
B<openssl genrsa> and B<openssl rsa> have been modified to use PKEY APIs.
B<openssl genrsa> and B<openssl rsa> now write PKCS #8 keys by default.
=head3 Default settings
"SHA256" is now the default digest for TS query used by B<openssl ts>.
=head3 Deprecated apps
B<openssl rsautl> is deprecated, use B<openssl pkeyutl> instead.
B<openssl dhparam>, B<openssl dsa>, B<openssl gendsa>, B<openssl dsaparam>,
B<openssl genrsa>, B<openssl rsa>, B<openssl genrsa> and B<openssl rsa> are
now in maintenance mode and no new features will be added to them.
=head2 TLS Changes
=over 4
=item *
TLS 1.3 FFDHE key exchange support added
This uses DH safe prime named groups.
=item *
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.
=item *
SSL and SSL_CTX options are now 64 bit instead of 32 bit.
The signatures of the functions to get and set options on SSL and
SSL_CTX objects changed from "unsigned long" to "uint64_t" type.
This may require source code changes. For example it is no longer possible
to use the B<SSL_OP_> macro values in preprocessor C<#if> conditions.
However it is still possible to test whether these macros are defined or not.
See L<SSL_CTX_get_options(3)>, L<SSL_CTX_set_options(3)>,
L<SSL_get_options(3)> and L<SSL_set_options(3)>.
=item *
SSL_set1_host() and SSL_add1_host() Changes
These functions now take IP literal addresses as well as actual hostnames.
=item *
Added SSL option SSL_OP_CLEANSE_PLAINTEXT
If the option is set, openssl cleanses (zeroizes) plaintext bytes from
internal buffers after delivering them to the application. Note,
the application is still responsible for cleansing other copies
(e.g.: data received by L<SSL_read(3)>).
=item *
Client-initiated renegotiation is disabled by default.
To allow it, use the B<-client_renegotiation> option,
the B<SSL_OP_ALLOW_CLIENT_RENEGOTIATION> flag, or the C<ClientRenegotiation>
config parameter as appropriate.
=item *
Secure renegotiation is now required by default for TLS connections
Support for RFC 5746 secure renegotiation is now required by default for
SSL or TLS connections to succeed. Applications that require the ability
to connect to legacy peers will need to explicitly set
SSL_OP_LEGACY_SERVER_CONNECT. Accordingly, SSL_OP_LEGACY_SERVER_CONNECT
is no longer set as part of SSL_OP_ALL.
=item *
Combining the Configure options no-ec and no-dh no longer disables TLSv1.3
Typically if OpenSSL has no EC or DH algorithms then it cannot support
connections with TLSv1.3. However OpenSSL now supports "pluggable" groups
through providers. Therefore third party providers may supply group
implementations even where there are no built-in ones. Attempting to create
TLS connections in such a build without also disabling TLSv1.3 at run time or
using third party provider groups may result in handshake failures. TLSv1.3
can be disabled at compile time using the "no-tls1_3" Configure option.
=item *
SSL_CTX_set_ciphersuites() and SSL_set_ciphersuites() changes.
The methods now ignore unknown ciphers.
=item *
Security callback change.
The security callback, which can be customised by application code, supports
the security operation SSL_SECOP_TMP_DH. This is defined to take an EVP_PKEY
in the "other" parameter. In most places this is what is passed. All these
places occur server side. However there was one client side call of this
security operation and it passed a DH object instead. This is incorrect
according to the definition of SSL_SECOP_TMP_DH, and is inconsistent with all
of the other locations. Therefore this client side call has been changed to
pass an EVP_PKEY instead.
=item *
New SSL option SSL_OP_IGNORE_UNEXPECTED_EOF
The SSL option SSL_OP_IGNORE_UNEXPECTED_EOF is introduced. If that option
is set, an unexpected EOF is ignored, it pretends a close notify was received
instead and so the returned error becomes SSL_ERROR_ZERO_RETURN.
=item *
The security strength of SHA1 and MD5 based signatures in TLS has been reduced.
This results in SSL 3, TLS 1.0, TLS 1.1 and DTLS 1.0 no longer
working at the default security level of 1 and instead requires security
level 0. The security level can be changed either using the cipher string
with C<@SECLEVEL>, or calling L<SSL_CTX_set_security_level(3)>. This also means
that where the signature algorithms extension is missing from a ClientHello
then the handshake will fail in TLS 1.2 at security level 1. This is because,
although this extension is optional, failing to provide one means that
OpenSSL will fallback to a default set of signature algorithms. This default
set requires the availability of SHA1.
=item *
X509 certificates signed using SHA1 are no longer allowed at security level 1 and above.
In TLS/SSL the default security level is 1. It can be set either using the cipher
string with C<@SECLEVEL>, or calling L<SSL_CTX_set_security_level(3)>. If the
leaf certificate is signed with SHA-1, a call to L<SSL_CTX_use_certificate(3)>
will fail if the security level is not lowered first.
Outside TLS/SSL, the default security level is -1 (effectively 0). It can
be set using L<X509_VERIFY_PARAM_set_auth_level(3)> or using the B<-auth_level>
options of the commands.
=back
=head1 SEE ALSO
L<fips_module(7)>
=head1 HISTORY
The migration guide was created for OpenSSL 3.0.
=head1 COPYRIGHT
-Copyright 2021-2023 The OpenSSL Project Authors. All Rights Reserved.
+Copyright 2021-2024 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<https://www.openssl.org/source/license.html>.
=cut
diff --git a/crypto/openssl/e_os.h b/crypto/openssl/e_os.h
index db05b7f8150f..72eab92eeb4b 100644
--- a/crypto/openssl/e_os.h
+++ b/crypto/openssl/e_os.h
@@ -1,432 +1,430 @@
/*
- * Copyright 1995-2022 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 1995-2024 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_E_OS_H
# define OSSL_E_OS_H
# include <limits.h>
# include <openssl/opensslconf.h>
# include <openssl/e_os2.h>
# include <openssl/crypto.h>
# include "internal/nelem.h"
/*
* <openssl/e_os2.h> contains what we can justify to make visible to the
* outside; this file e_os.h is not part of the exported interface.
*/
# if defined(OPENSSL_SYS_VXWORKS) || defined(OPENSSL_SYS_UEFI)
# define NO_CHMOD
# define NO_SYSLOG
# endif
# define get_last_sys_error() errno
# define clear_sys_error() errno=0
# define set_sys_error(e) errno=(e)
/********************************************************************
The Microsoft section
********************************************************************/
# if defined(OPENSSL_SYS_WIN32) && !defined(WIN32)
# define WIN32
# endif
# if defined(OPENSSL_SYS_WINDOWS) && !defined(WINDOWS)
# define WINDOWS
# endif
# if defined(OPENSSL_SYS_MSDOS) && !defined(MSDOS)
# define MSDOS
# endif
# ifdef WIN32
# undef get_last_sys_error
# undef clear_sys_error
# undef set_sys_error
# define get_last_sys_error() GetLastError()
# define clear_sys_error() SetLastError(0)
# define set_sys_error(e) SetLastError(e)
# if !defined(WINNT)
# define WIN_CONSOLE_BUG
# endif
# else
# endif
# if (defined(WINDOWS) || defined(MSDOS))
# ifdef __DJGPP__
# include <unistd.h>
# include <sys/stat.h>
# define _setmode setmode
# define _O_TEXT O_TEXT
# define _O_BINARY O_BINARY
# undef DEVRANDOM_EGD /* Neither MS-DOS nor FreeDOS provide 'egd' sockets. */
# undef DEVRANDOM
# define DEVRANDOM "/dev/urandom\x24"
# endif /* __DJGPP__ */
# ifndef S_IFDIR
# define S_IFDIR _S_IFDIR
# endif
# ifndef S_IFMT
# define S_IFMT _S_IFMT
# endif
# if !defined(WINNT) && !defined(__DJGPP__)
# define NO_SYSLOG
# endif
# ifdef WINDOWS
# if !defined(_WIN32_WCE) && !defined(_WIN32_WINNT)
/*
* Defining _WIN32_WINNT here in e_os.h implies certain "discipline."
* Most notably we ought to check for availability of each specific
* routine that was introduced after denoted _WIN32_WINNT with
* GetProcAddress(). Normally newer functions are masked with higher
* _WIN32_WINNT in SDK headers. So that if you wish to use them in
* some module, you'd need to override _WIN32_WINNT definition in
* the target module in order to "reach for" prototypes, but replace
* calls to new functions with indirect calls. Alternatively it
* might be possible to achieve the goal by /DELAYLOAD-ing .DLLs
* and check for current OS version instead.
*/
# define _WIN32_WINNT 0x0501
# endif
# if defined(_WIN32_WINNT) || defined(_WIN32_WCE)
/*
* Just like defining _WIN32_WINNT including winsock2.h implies
* certain "discipline" for maintaining [broad] binary compatibility.
* As long as structures are invariant among Winsock versions,
* it's sufficient to check for specific Winsock2 API availability
* at run-time [DSO_global_lookup is recommended]...
*/
# include <winsock2.h>
# include <ws2tcpip.h>
/*
* Clang-based C++Builder 10.3.3 toolchains cannot find C inline
* definitions at link-time. This header defines WspiapiLoad() as an
* __inline function. https://quality.embarcadero.com/browse/RSP-33806
*/
# if !defined(__BORLANDC__) || !defined(__clang__)
# include <wspiapi.h>
# endif
/* yes, they have to be #included prior to <windows.h> */
# endif
# include <windows.h>
# include <stdio.h>
# include <stddef.h>
# include <errno.h>
# if defined(_WIN32_WCE) && !defined(EACCES)
# define EACCES 13
# endif
# include <string.h>
# ifdef _WIN64
# define strlen(s) _strlen31(s)
/* cut strings to 2GB */
static __inline unsigned int _strlen31(const char *str)
{
unsigned int len = 0;
while (*str && len < 0x80000000U)
str++, len++;
return len & 0x7FFFFFFF;
}
# endif
# include <malloc.h>
# if defined(_MSC_VER) && !defined(_WIN32_WCE) && !defined(_DLL) && defined(stdin)
# if _MSC_VER>=1300 && _MSC_VER<1600
# undef stdin
# undef stdout
# undef stderr
FILE *__iob_func();
# define stdin (&__iob_func()[0])
# define stdout (&__iob_func()[1])
# define stderr (&__iob_func()[2])
# endif
# endif
# endif
# include <io.h>
# include <fcntl.h>
# ifdef OPENSSL_SYS_WINCE
# define OPENSSL_NO_POSIX_IO
# endif
# define EXIT(n) exit(n)
# define LIST_SEPARATOR_CHAR ';'
# ifndef W_OK
# define W_OK 2
# endif
# ifndef R_OK
# define R_OK 4
# endif
# ifdef OPENSSL_SYS_WINCE
# define DEFAULT_HOME ""
# else
# define DEFAULT_HOME "C:"
# endif
/* Avoid Visual Studio 13 GetVersion deprecated problems */
# if defined(_MSC_VER) && _MSC_VER>=1800
# define check_winnt() (1)
# define check_win_minplat(x) (1)
# else
# define check_winnt() (GetVersion() < 0x80000000)
# define check_win_minplat(x) (LOBYTE(LOWORD(GetVersion())) >= (x))
# endif
# else /* The non-microsoft world */
# if defined(OPENSSL_SYS_VXWORKS)
# include <time.h>
# else
# include <sys/time.h>
# endif
# ifdef OPENSSL_SYS_VMS
# define VMS 1
/*
* some programs don't include stdlib, so exit() and others give implicit
* function warnings
*/
# include <stdlib.h>
# if defined(__DECC)
# include <unistd.h>
# else
# include <unixlib.h>
# endif
# define LIST_SEPARATOR_CHAR ','
/* We don't have any well-defined random devices on VMS, yet... */
# undef DEVRANDOM
/*-
We need to do this since VMS has the following coding on status codes:
Bits 0-2: status type: 0 = warning, 1 = success, 2 = error, 3 = info ...
The important thing to know is that odd numbers are considered
good, while even ones are considered errors.
Bits 3-15: actual status number
Bits 16-27: facility number. 0 is considered "unknown"
Bits 28-31: control bits. If bit 28 is set, the shell won't try to
output the message (which, for random codes, just looks ugly)
So, what we do here is to change 0 to 1 to get the default success status,
and everything else is shifted up to fit into the status number field, and
the status is tagged as an error, which is what is wanted here.
Finally, we add the VMS C facility code 0x35a000, because there are some
programs, such as Perl, that will reinterpret the code back to something
POSIX. 'man perlvms' explains it further.
NOTE: the perlvms manual wants to turn all codes 2 to 255 into success
codes (status type = 1). I couldn't disagree more. Fortunately, the
status type doesn't seem to bother Perl.
-- Richard Levitte
*/
# define EXIT(n) exit((n) ? (((n) << 3) | 2 | 0x10000000 | 0x35a000) : 1)
# define DEFAULT_HOME "SYS$LOGIN:"
# else
/* !defined VMS */
# include <unistd.h>
# include <sys/types.h>
# ifdef OPENSSL_SYS_WIN32_CYGWIN
# include <io.h>
# include <fcntl.h>
# endif
# define LIST_SEPARATOR_CHAR ':'
# define EXIT(n) exit(n)
# endif
# endif
/***********************************************/
# if defined(OPENSSL_SYS_WINDOWS)
# if (_MSC_VER >= 1310) && !defined(_WIN32_WCE)
# define open _open
# define fdopen _fdopen
# define close _close
# ifndef strdup
# define strdup _strdup
# endif
# define unlink _unlink
# define fileno _fileno
# endif
# else
# include <strings.h>
# endif
/* vxworks */
# if defined(OPENSSL_SYS_VXWORKS)
# include <ioLib.h>
# include <tickLib.h>
# include <sysLib.h>
# include <vxWorks.h>
# include <sockLib.h>
# include <taskLib.h>
# define TTY_STRUCT int
# define sleep(a) taskDelay((a) * sysClkRateGet())
/*
* NOTE: these are implemented by helpers in database app! if the database is
* not linked, we need to implement them elsewhere
*/
struct hostent *gethostbyname(const char *name);
struct hostent *gethostbyaddr(const char *addr, int length, int type);
struct servent *getservbyname(const char *name, const char *proto);
# endif
/* end vxworks */
/* system-specific variants defining ossl_sleep() */
#if defined(OPENSSL_SYS_UNIX) || defined(__DJGPP__)
# include <unistd.h>
static ossl_inline void ossl_sleep(unsigned long millis)
{
# ifdef OPENSSL_SYS_VXWORKS
struct timespec ts;
ts.tv_sec = (long int) (millis / 1000);
ts.tv_nsec = (long int) (millis % 1000) * 1000000ul;
nanosleep(&ts, NULL);
-# elif defined(__TANDEM)
-# if !defined(_REENTRANT)
+# elif defined(__TANDEM) && !defined(_REENTRANT)
# include <cextdecs.h(PROCESS_DELAY_)>
+
/* HPNS does not support usleep for non threaded apps */
PROCESS_DELAY_(millis * 1000);
-# elif defined(_SPT_MODEL_)
-# include <spthread.h>
-# include <spt_extensions.h>
- usleep(millis * 1000);
-# else
- usleep(millis * 1000);
-# endif
# else
- usleep(millis * 1000);
+ unsigned int s = (unsigned int)(millis / 1000);
+ unsigned int us = (unsigned int)((millis % 1000) * 1000);
+
+ if (s > 0)
+ sleep(s);
+ usleep(us);
# endif
}
#elif defined(_WIN32)
# include <windows.h>
static ossl_inline void ossl_sleep(unsigned long millis)
{
Sleep(millis);
}
#else
/* Fallback to a busy wait */
static ossl_inline void ossl_sleep(unsigned long millis)
{
struct timeval start, now;
unsigned long elapsedms;
gettimeofday(&start, NULL);
do {
gettimeofday(&now, NULL);
elapsedms = (((now.tv_sec - start.tv_sec) * 1000000)
+ now.tv_usec - start.tv_usec) / 1000;
} while (elapsedms < millis);
}
#endif /* defined OPENSSL_SYS_UNIX */
/* ----------------------------- HP NonStop -------------------------------- */
/* Required to support platform variant without getpid() and pid_t. */
# if defined(__TANDEM) && defined(_GUARDIAN_TARGET)
# include <strings.h>
# include <netdb.h>
# define getservbyname(name,proto) getservbyname((char*)name,proto)
# define gethostbyname(name) gethostbyname((char*)name)
# define ioctlsocket(a,b,c) ioctl(a,b,c)
# ifdef NO_GETPID
inline int nssgetpid();
# ifndef NSSGETPID_MACRO
# define NSSGETPID_MACRO
# include <cextdecs.h(PROCESSHANDLE_GETMINE_)>
# include <cextdecs.h(PROCESSHANDLE_DECOMPOSE_)>
inline int nssgetpid()
{
short phandle[10]={0};
union pseudo_pid {
struct {
short cpu;
short pin;
} cpu_pin ;
int ppid;
} ppid = { 0 };
PROCESSHANDLE_GETMINE_(phandle);
PROCESSHANDLE_DECOMPOSE_(phandle, &ppid.cpu_pin.cpu, &ppid.cpu_pin.pin);
return ppid.ppid;
}
# define getpid(a) nssgetpid(a)
# endif /* NSSGETPID_MACRO */
# endif /* NO_GETPID */
/*# define setsockopt(a,b,c,d,f) setsockopt(a,b,c,(char*)d,f)*/
/*# define getsockopt(a,b,c,d,f) getsockopt(a,b,c,(char*)d,f)*/
/*# define connect(a,b,c) connect(a,(struct sockaddr *)b,c)*/
/*# define bind(a,b,c) bind(a,(struct sockaddr *)b,c)*/
/*# define sendto(a,b,c,d,e,f) sendto(a,(char*)b,c,d,(struct sockaddr *)e,f)*/
# if defined(OPENSSL_THREADS) && !defined(_PUT_MODEL_)
/*
* HPNS SPT threads
*/
# define SPT_THREAD_SIGNAL 1
# define SPT_THREAD_AWARE 1
# include <spthread.h>
# undef close
# define close spt_close
/*
# define get_last_socket_error() errno
# define clear_socket_error() errno=0
# define ioctlsocket(a,b,c) ioctl(a,b,c)
# define closesocket(s) close(s)
# define readsocket(s,b,n) read((s),(char*)(b),(n))
# define writesocket(s,b,n) write((s),(char*)(b),(n)
*/
# define accept(a,b,c) accept(a,(struct sockaddr *)b,c)
# define recvfrom(a,b,c,d,e,f) recvfrom(a,b,(socklen_t)c,d,e,f)
# endif
# endif
# ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
# define CRYPTO_memcmp memcmp
# endif
# ifndef OPENSSL_NO_SECURE_MEMORY
/* unistd.h defines _POSIX_VERSION */
# if (defined(OPENSSL_SYS_UNIX) \
&& ( (defined(_POSIX_VERSION) && _POSIX_VERSION >= 200112L) \
|| defined(__sun) || defined(__hpux) || defined(__sgi) \
|| defined(__osf__) )) \
|| defined(_WIN32)
/* secure memory is implemented */
# else
# define OPENSSL_NO_SECURE_MEMORY
# endif
# endif
/*
* str[n]casecmp_l is defined in POSIX 2008-01. Value is taken accordingly
* https://www.gnu.org/software/libc/manual/html_node/Feature-Test-Macros.html
* There are also equivalent functions on Windows.
* There is no locale_t on NONSTOP.
*/
# if defined(OPENSSL_SYS_WINDOWS)
# define locale_t _locale_t
# define freelocale _free_locale
# define strcasecmp_l _stricmp_l
# define strncasecmp_l _strnicmp_l
# define strcasecmp _stricmp
# define strncasecmp _strnicmp
# elif !defined(_POSIX_C_SOURCE) || _POSIX_C_SOURCE < 200809L \
|| defined(OPENSSL_SYS_TANDEM)
# ifndef OPENSSL_NO_LOCALE
# define OPENSSL_NO_LOCALE
# endif
# endif
#endif
diff --git a/crypto/openssl/engines/e_afalg.c b/crypto/openssl/engines/e_afalg.c
index 2c08cbb28dde..ec4e21c582c8 100644
--- a/crypto/openssl/engines/e_afalg.c
+++ b/crypto/openssl/engines/e_afalg.c
@@ -1,933 +1,935 @@
/*
- * Copyright 2016-2021 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2016-2024 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
/* We need to use some deprecated APIs */
#define OPENSSL_SUPPRESS_DEPRECATED
/* Required for vmsplice */
#ifndef _GNU_SOURCE
# define _GNU_SOURCE
#endif
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <openssl/engine.h>
#include <openssl/async.h>
#include <openssl/err.h>
#include "internal/nelem.h"
#include <sys/socket.h>
#include <linux/version.h>
#define K_MAJ 4
#define K_MIN1 1
#define K_MIN2 0
#if LINUX_VERSION_CODE < KERNEL_VERSION(K_MAJ, K_MIN1, K_MIN2) || \
!defined(AF_ALG)
# ifndef PEDANTIC
# warning "AFALG ENGINE requires Kernel Headers >= 4.1.0"
# warning "Skipping Compilation of AFALG engine"
# endif
void engine_load_afalg_int(void);
void engine_load_afalg_int(void)
{
}
#else
# include <linux/if_alg.h>
# include <fcntl.h>
# include <sys/utsname.h>
# include <linux/aio_abi.h>
# include <sys/syscall.h>
# include <errno.h>
# include "e_afalg.h"
# include "e_afalg_err.c"
# ifndef SOL_ALG
# define SOL_ALG 279
# endif
# ifdef ALG_ZERO_COPY
# ifndef SPLICE_F_GIFT
# define SPLICE_F_GIFT (0x08)
# endif
# endif
# define ALG_AES_IV_LEN 16
# define ALG_IV_LEN(len) (sizeof(struct af_alg_iv) + (len))
# define ALG_OP_TYPE unsigned int
# define ALG_OP_LEN (sizeof(ALG_OP_TYPE))
# ifdef OPENSSL_NO_DYNAMIC_ENGINE
void engine_load_afalg_int(void);
# endif
/* Local Linkage Functions */
static int afalg_init_aio(afalg_aio *aio);
static int afalg_fin_cipher_aio(afalg_aio *ptr, int sfd,
unsigned char *buf, size_t len);
static int afalg_create_sk(afalg_ctx *actx, const char *ciphertype,
const char *ciphername);
static int afalg_destroy(ENGINE *e);
static int afalg_init(ENGINE *e);
static int afalg_finish(ENGINE *e);
static const EVP_CIPHER *afalg_aes_cbc(int nid);
static cbc_handles *get_cipher_handle(int nid);
static int afalg_ciphers(ENGINE *e, const EVP_CIPHER **cipher,
const int **nids, int nid);
static int afalg_cipher_init(EVP_CIPHER_CTX *ctx, const unsigned char *key,
const unsigned char *iv, int enc);
static int afalg_do_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
const unsigned char *in, size_t inl);
static int afalg_cipher_cleanup(EVP_CIPHER_CTX *ctx);
static int afalg_chk_platform(void);
/* Engine Id and Name */
static const char *engine_afalg_id = "afalg";
static const char *engine_afalg_name = "AFALG engine support";
static int afalg_cipher_nids[] = {
NID_aes_128_cbc,
NID_aes_192_cbc,
NID_aes_256_cbc,
};
static cbc_handles cbc_handle[] = {{AES_KEY_SIZE_128, NULL},
{AES_KEY_SIZE_192, NULL},
{AES_KEY_SIZE_256, NULL}};
static ossl_inline int io_setup(unsigned n, aio_context_t *ctx)
{
return syscall(__NR_io_setup, n, ctx);
}
static ossl_inline int eventfd(int n)
{
return syscall(__NR_eventfd2, n, 0);
}
static ossl_inline int io_destroy(aio_context_t ctx)
{
return syscall(__NR_io_destroy, ctx);
}
static ossl_inline int io_read(aio_context_t ctx, long n, struct iocb **iocb)
{
return syscall(__NR_io_submit, ctx, n, iocb);
}
/* A version of 'struct timespec' with 32-bit time_t and nanoseconds. */
struct __timespec32
{
__kernel_long_t tv_sec;
__kernel_long_t tv_nsec;
};
static ossl_inline int io_getevents(aio_context_t ctx, long min, long max,
struct io_event *events,
struct timespec *timeout)
{
#if defined(__NR_io_pgetevents_time64)
/* Check if we are a 32-bit architecture with a 64-bit time_t */
if (sizeof(*timeout) != sizeof(struct __timespec32)) {
int ret = syscall(__NR_io_pgetevents_time64, ctx, min, max, events,
timeout, NULL);
if (ret == 0 || errno != ENOSYS)
return ret;
}
#endif
#if defined(__NR_io_getevents)
if (sizeof(*timeout) == sizeof(struct __timespec32))
/*
* time_t matches our architecture length, we can just use
* __NR_io_getevents
*/
return syscall(__NR_io_getevents, ctx, min, max, events, timeout);
else {
/*
* We don't have __NR_io_pgetevents_time64, but we are using a
* 64-bit time_t on a 32-bit architecture. If we can fit the
* timeout value in a 32-bit time_t, then let's do that
* and then use the __NR_io_getevents syscall.
*/
if (timeout && timeout->tv_sec == (long)timeout->tv_sec) {
struct __timespec32 ts32;
ts32.tv_sec = (__kernel_long_t) timeout->tv_sec;
ts32.tv_nsec = (__kernel_long_t) timeout->tv_nsec;
return syscall(__NR_io_getevents, ctx, min, max, events, ts32);
} else {
return syscall(__NR_io_getevents, ctx, min, max, events, NULL);
}
}
#endif
errno = ENOSYS;
return -1;
}
static void afalg_waitfd_cleanup(ASYNC_WAIT_CTX *ctx, const void *key,
OSSL_ASYNC_FD waitfd, void *custom)
{
close(waitfd);
}
static int afalg_setup_async_event_notification(afalg_aio *aio)
{
ASYNC_JOB *job;
ASYNC_WAIT_CTX *waitctx;
void *custom = NULL;
int ret;
if ((job = ASYNC_get_current_job()) != NULL) {
/* Async mode */
waitctx = ASYNC_get_wait_ctx(job);
if (waitctx == NULL) {
ALG_WARN("%s(%d): ASYNC_get_wait_ctx error", __FILE__, __LINE__);
return 0;
}
/* Get waitfd from ASYNC_WAIT_CTX if it is already set */
ret = ASYNC_WAIT_CTX_get_fd(waitctx, engine_afalg_id,
&aio->efd, &custom);
if (ret == 0) {
/*
* waitfd is not set in ASYNC_WAIT_CTX, create a new one
* and set it. efd will be signaled when AIO operation completes
*/
aio->efd = eventfd(0);
if (aio->efd == -1) {
ALG_PERR("%s(%d): Failed to get eventfd : ", __FILE__,
__LINE__);
AFALGerr(AFALG_F_AFALG_SETUP_ASYNC_EVENT_NOTIFICATION,
AFALG_R_EVENTFD_FAILED);
return 0;
}
ret = ASYNC_WAIT_CTX_set_wait_fd(waitctx, engine_afalg_id,
aio->efd, custom,
afalg_waitfd_cleanup);
if (ret == 0) {
ALG_WARN("%s(%d): Failed to set wait fd", __FILE__, __LINE__);
close(aio->efd);
return 0;
}
/* make fd non-blocking in async mode */
if (fcntl(aio->efd, F_SETFL, O_NONBLOCK) != 0) {
ALG_WARN("%s(%d): Failed to set event fd as NONBLOCKING",
__FILE__, __LINE__);
}
}
aio->mode = MODE_ASYNC;
} else {
/* Sync mode */
aio->efd = eventfd(0);
if (aio->efd == -1) {
ALG_PERR("%s(%d): Failed to get eventfd : ", __FILE__, __LINE__);
AFALGerr(AFALG_F_AFALG_SETUP_ASYNC_EVENT_NOTIFICATION,
AFALG_R_EVENTFD_FAILED);
return 0;
}
aio->mode = MODE_SYNC;
}
return 1;
}
static int afalg_init_aio(afalg_aio *aio)
{
int r = -1;
/* Initialise for AIO */
aio->aio_ctx = 0;
r = io_setup(MAX_INFLIGHTS, &aio->aio_ctx);
if (r < 0) {
ALG_PERR("%s(%d): io_setup error : ", __FILE__, __LINE__);
AFALGerr(AFALG_F_AFALG_INIT_AIO, AFALG_R_IO_SETUP_FAILED);
return 0;
}
memset(aio->cbt, 0, sizeof(aio->cbt));
aio->efd = -1;
aio->mode = MODE_UNINIT;
return 1;
}
static int afalg_fin_cipher_aio(afalg_aio *aio, int sfd, unsigned char *buf,
size_t len)
{
int r;
int retry = 0;
unsigned int done = 0;
struct iocb *cb;
struct timespec timeout;
struct io_event events[MAX_INFLIGHTS];
u_int64_t eval = 0;
timeout.tv_sec = 0;
timeout.tv_nsec = 0;
/* if efd has not been initialised yet do it here */
if (aio->mode == MODE_UNINIT) {
r = afalg_setup_async_event_notification(aio);
if (r == 0)
return 0;
}
cb = &(aio->cbt[0 % MAX_INFLIGHTS]);
memset(cb, '\0', sizeof(*cb));
cb->aio_fildes = sfd;
cb->aio_lio_opcode = IOCB_CMD_PREAD;
/*
* The pointer has to be converted to unsigned value first to avoid
* sign extension on cast to 64 bit value in 32-bit builds
*/
cb->aio_buf = (size_t)buf;
cb->aio_offset = 0;
cb->aio_data = 0;
cb->aio_nbytes = len;
cb->aio_flags = IOCB_FLAG_RESFD;
cb->aio_resfd = aio->efd;
/*
* Perform AIO read on AFALG socket, this in turn performs an async
* crypto operation in kernel space
*/
r = io_read(aio->aio_ctx, 1, &cb);
if (r < 0) {
ALG_PWARN("%s(%d): io_read failed : ", __FILE__, __LINE__);
return 0;
}
do {
/* While AIO read is being performed pause job */
ASYNC_pause_job();
/* Check for completion of AIO read */
r = read(aio->efd, &eval, sizeof(eval));
if (r < 0) {
if (errno == EAGAIN || errno == EWOULDBLOCK)
continue;
ALG_PERR("%s(%d): read failed for event fd : ", __FILE__, __LINE__);
return 0;
} else if (r == 0 || eval <= 0) {
ALG_WARN("%s(%d): eventfd read %d bytes, eval = %lu\n", __FILE__,
__LINE__, r, eval);
}
if (eval > 0) {
#ifdef OSSL_SANITIZE_MEMORY
/*
* In a memory sanitiser build, the changes to memory made by the
* system call aren't reliably detected. By initialising the
* memory here, the sanitiser is told that they are okay.
*/
memset(events, 0, sizeof(events));
#endif
/* Get results of AIO read */
r = io_getevents(aio->aio_ctx, 1, MAX_INFLIGHTS,
events, &timeout);
if (r > 0) {
/*
* events.res indicates the actual status of the operation.
* Handle the error condition first.
*/
if (events[0].res < 0) {
/*
* Underlying operation cannot be completed at the time
* of previous submission. Resubmit for the operation.
*/
if (events[0].res == -EBUSY && retry++ < 3) {
r = io_read(aio->aio_ctx, 1, &cb);
if (r < 0) {
ALG_PERR("%s(%d): retry %d for io_read failed : ",
__FILE__, __LINE__, retry);
return 0;
}
continue;
} else {
/*
* Retries exceed for -EBUSY or unrecoverable error
* condition for this instance of operation.
*/
ALG_WARN
("%s(%d): Crypto Operation failed with code %lld\n",
__FILE__, __LINE__, events[0].res);
return 0;
}
}
/* Operation successful. */
done = 1;
} else if (r < 0) {
ALG_PERR("%s(%d): io_getevents failed : ", __FILE__, __LINE__);
return 0;
} else {
ALG_WARN("%s(%d): io_geteventd read 0 bytes\n", __FILE__,
__LINE__);
}
}
} while (!done);
return 1;
}
static ossl_inline void afalg_set_op_sk(struct cmsghdr *cmsg,
const ALG_OP_TYPE op)
{
cmsg->cmsg_level = SOL_ALG;
cmsg->cmsg_type = ALG_SET_OP;
cmsg->cmsg_len = CMSG_LEN(ALG_OP_LEN);
memcpy(CMSG_DATA(cmsg), &op, ALG_OP_LEN);
}
static void afalg_set_iv_sk(struct cmsghdr *cmsg, const unsigned char *iv,
const unsigned int len)
{
struct af_alg_iv *aiv;
cmsg->cmsg_level = SOL_ALG;
cmsg->cmsg_type = ALG_SET_IV;
cmsg->cmsg_len = CMSG_LEN(ALG_IV_LEN(len));
aiv = (struct af_alg_iv *)CMSG_DATA(cmsg);
aiv->ivlen = len;
memcpy(aiv->iv, iv, len);
}
static ossl_inline int afalg_set_key(afalg_ctx *actx, const unsigned char *key,
const int klen)
{
int ret;
ret = setsockopt(actx->bfd, SOL_ALG, ALG_SET_KEY, key, klen);
if (ret < 0) {
ALG_PERR("%s(%d): Failed to set socket option : ", __FILE__, __LINE__);
AFALGerr(AFALG_F_AFALG_SET_KEY, AFALG_R_SOCKET_SET_KEY_FAILED);
return 0;
}
return 1;
}
static int afalg_create_sk(afalg_ctx *actx, const char *ciphertype,
const char *ciphername)
{
struct sockaddr_alg sa;
int r = -1;
actx->bfd = actx->sfd = -1;
memset(&sa, 0, sizeof(sa));
sa.salg_family = AF_ALG;
OPENSSL_strlcpy((char *) sa.salg_type, ciphertype, sizeof(sa.salg_type));
OPENSSL_strlcpy((char *) sa.salg_name, ciphername, sizeof(sa.salg_name));
actx->bfd = socket(AF_ALG, SOCK_SEQPACKET, 0);
if (actx->bfd == -1) {
ALG_PERR("%s(%d): Failed to open socket : ", __FILE__, __LINE__);
AFALGerr(AFALG_F_AFALG_CREATE_SK, AFALG_R_SOCKET_CREATE_FAILED);
goto err;
}
r = bind(actx->bfd, (struct sockaddr *)&sa, sizeof(sa));
if (r < 0) {
ALG_PERR("%s(%d): Failed to bind socket : ", __FILE__, __LINE__);
AFALGerr(AFALG_F_AFALG_CREATE_SK, AFALG_R_SOCKET_BIND_FAILED);
goto err;
}
actx->sfd = accept(actx->bfd, NULL, 0);
if (actx->sfd < 0) {
ALG_PERR("%s(%d): Socket Accept Failed : ", __FILE__, __LINE__);
AFALGerr(AFALG_F_AFALG_CREATE_SK, AFALG_R_SOCKET_ACCEPT_FAILED);
goto err;
}
return 1;
err:
if (actx->bfd >= 0)
close(actx->bfd);
if (actx->sfd >= 0)
close(actx->sfd);
actx->bfd = actx->sfd = -1;
return 0;
}
static int afalg_start_cipher_sk(afalg_ctx *actx, const unsigned char *in,
size_t inl, const unsigned char *iv,
unsigned int enc)
{
struct msghdr msg;
struct cmsghdr *cmsg;
struct iovec iov;
ssize_t sbytes;
# ifdef ALG_ZERO_COPY
int ret;
# endif
char cbuf[CMSG_SPACE(ALG_IV_LEN(ALG_AES_IV_LEN)) + CMSG_SPACE(ALG_OP_LEN)];
memset(&msg, 0, sizeof(msg));
memset(cbuf, 0, sizeof(cbuf));
msg.msg_control = cbuf;
msg.msg_controllen = sizeof(cbuf);
/*
* cipher direction (i.e. encrypt or decrypt) and iv are sent to the
* kernel as part of sendmsg()'s ancillary data
*/
cmsg = CMSG_FIRSTHDR(&msg);
afalg_set_op_sk(cmsg, enc);
cmsg = CMSG_NXTHDR(&msg, cmsg);
afalg_set_iv_sk(cmsg, iv, ALG_AES_IV_LEN);
/* iov that describes input data */
iov.iov_base = (unsigned char *)in;
iov.iov_len = inl;
msg.msg_flags = MSG_MORE;
# ifdef ALG_ZERO_COPY
/*
* ZERO_COPY mode
* Works best when buffer is 4k aligned
* OPENS: out of place processing (i.e. out != in)
*/
/* Input data is not sent as part of call to sendmsg() */
msg.msg_iovlen = 0;
msg.msg_iov = NULL;
/* Sendmsg() sends iv and cipher direction to the kernel */
sbytes = sendmsg(actx->sfd, &msg, 0);
if (sbytes < 0) {
ALG_PERR("%s(%d): sendmsg failed for zero copy cipher operation : ",
__FILE__, __LINE__);
return 0;
}
/*
* vmsplice and splice are used to pin the user space input buffer for
* kernel space processing avoiding copies from user to kernel space
*/
ret = vmsplice(actx->zc_pipe[1], &iov, 1, SPLICE_F_GIFT);
if (ret < 0) {
ALG_PERR("%s(%d): vmsplice failed : ", __FILE__, __LINE__);
return 0;
}
ret = splice(actx->zc_pipe[0], NULL, actx->sfd, NULL, inl, 0);
if (ret < 0) {
ALG_PERR("%s(%d): splice failed : ", __FILE__, __LINE__);
return 0;
}
# else
msg.msg_iovlen = 1;
msg.msg_iov = &iov;
/* Sendmsg() sends iv, cipher direction and input data to the kernel */
sbytes = sendmsg(actx->sfd, &msg, 0);
if (sbytes < 0) {
ALG_PERR("%s(%d): sendmsg failed for cipher operation : ", __FILE__,
__LINE__);
return 0;
}
if (sbytes != (ssize_t) inl) {
ALG_WARN("Cipher operation send bytes %zd != inlen %zd\n", sbytes,
inl);
return 0;
}
# endif
return 1;
}
static int afalg_cipher_init(EVP_CIPHER_CTX *ctx, const unsigned char *key,
const unsigned char *iv, int enc)
{
int ciphertype;
int ret, len;
afalg_ctx *actx;
const char *ciphername;
if (ctx == NULL || key == NULL) {
ALG_WARN("%s(%d): Null Parameter\n", __FILE__, __LINE__);
return 0;
}
if (EVP_CIPHER_CTX_get0_cipher(ctx) == NULL) {
ALG_WARN("%s(%d): Cipher object NULL\n", __FILE__, __LINE__);
return 0;
}
actx = EVP_CIPHER_CTX_get_cipher_data(ctx);
if (actx == NULL) {
ALG_WARN("%s(%d): Cipher data NULL\n", __FILE__, __LINE__);
return 0;
}
ciphertype = EVP_CIPHER_CTX_get_nid(ctx);
switch (ciphertype) {
case NID_aes_128_cbc:
case NID_aes_192_cbc:
case NID_aes_256_cbc:
ciphername = "cbc(aes)";
break;
default:
ALG_WARN("%s(%d): Unsupported Cipher type %d\n", __FILE__, __LINE__,
ciphertype);
return 0;
}
if (ALG_AES_IV_LEN != EVP_CIPHER_CTX_get_iv_length(ctx)) {
ALG_WARN("%s(%d): Unsupported IV length :%d\n", __FILE__, __LINE__,
EVP_CIPHER_CTX_get_iv_length(ctx));
return 0;
}
/* Setup AFALG socket for crypto processing */
ret = afalg_create_sk(actx, "skcipher", ciphername);
if (ret < 1)
return 0;
if ((len = EVP_CIPHER_CTX_get_key_length(ctx)) <= 0)
goto err;
ret = afalg_set_key(actx, key, len);
if (ret < 1)
goto err;
/* Setup AIO ctx to allow async AFALG crypto processing */
if (afalg_init_aio(&actx->aio) == 0)
goto err;
# ifdef ALG_ZERO_COPY
pipe(actx->zc_pipe);
# endif
actx->init_done = MAGIC_INIT_NUM;
return 1;
err:
close(actx->sfd);
close(actx->bfd);
return 0;
}
static int afalg_do_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
const unsigned char *in, size_t inl)
{
afalg_ctx *actx;
int ret;
char nxtiv[ALG_AES_IV_LEN] = { 0 };
if (ctx == NULL || out == NULL || in == NULL) {
ALG_WARN("NULL parameter passed to function %s(%d)\n", __FILE__,
__LINE__);
return 0;
}
actx = (afalg_ctx *) EVP_CIPHER_CTX_get_cipher_data(ctx);
if (actx == NULL || actx->init_done != MAGIC_INIT_NUM) {
ALG_WARN("%s afalg ctx passed\n",
ctx == NULL ? "NULL" : "Uninitialised");
return 0;
}
/*
* set iv now for decrypt operation as the input buffer can be
* overwritten for inplace operation where in = out.
*/
if (EVP_CIPHER_CTX_is_encrypting(ctx) == 0) {
memcpy(nxtiv, in + (inl - ALG_AES_IV_LEN), ALG_AES_IV_LEN);
}
/* Send input data to kernel space */
ret = afalg_start_cipher_sk(actx, (unsigned char *)in, inl,
EVP_CIPHER_CTX_iv(ctx),
EVP_CIPHER_CTX_is_encrypting(ctx));
if (ret < 1) {
return 0;
}
/* Perform async crypto operation in kernel space */
ret = afalg_fin_cipher_aio(&actx->aio, actx->sfd, out, inl);
if (ret < 1)
return 0;
if (EVP_CIPHER_CTX_is_encrypting(ctx)) {
memcpy(EVP_CIPHER_CTX_iv_noconst(ctx), out + (inl - ALG_AES_IV_LEN),
ALG_AES_IV_LEN);
} else {
memcpy(EVP_CIPHER_CTX_iv_noconst(ctx), nxtiv, ALG_AES_IV_LEN);
}
return 1;
}
static int afalg_cipher_cleanup(EVP_CIPHER_CTX *ctx)
{
afalg_ctx *actx;
if (ctx == NULL) {
ALG_WARN("NULL parameter passed to function %s(%d)\n", __FILE__,
__LINE__);
return 0;
}
actx = (afalg_ctx *) EVP_CIPHER_CTX_get_cipher_data(ctx);
if (actx == NULL || actx->init_done != MAGIC_INIT_NUM)
return 1;
close(actx->sfd);
close(actx->bfd);
# ifdef ALG_ZERO_COPY
close(actx->zc_pipe[0]);
close(actx->zc_pipe[1]);
# endif
/* close efd in sync mode, async mode is closed in afalg_waitfd_cleanup() */
if (actx->aio.mode == MODE_SYNC)
close(actx->aio.efd);
io_destroy(actx->aio.aio_ctx);
return 1;
}
static cbc_handles *get_cipher_handle(int nid)
{
switch (nid) {
case NID_aes_128_cbc:
return &cbc_handle[AES_CBC_128];
case NID_aes_192_cbc:
return &cbc_handle[AES_CBC_192];
case NID_aes_256_cbc:
return &cbc_handle[AES_CBC_256];
default:
return NULL;
}
}
static const EVP_CIPHER *afalg_aes_cbc(int nid)
{
cbc_handles *cipher_handle = get_cipher_handle(nid);
if (cipher_handle == NULL)
return NULL;
if (cipher_handle->_hidden == NULL
&& ((cipher_handle->_hidden =
EVP_CIPHER_meth_new(nid,
AES_BLOCK_SIZE,
cipher_handle->key_size)) == NULL
|| !EVP_CIPHER_meth_set_iv_length(cipher_handle->_hidden,
AES_IV_LEN)
|| !EVP_CIPHER_meth_set_flags(cipher_handle->_hidden,
EVP_CIPH_CBC_MODE |
EVP_CIPH_FLAG_DEFAULT_ASN1)
|| !EVP_CIPHER_meth_set_init(cipher_handle->_hidden,
afalg_cipher_init)
|| !EVP_CIPHER_meth_set_do_cipher(cipher_handle->_hidden,
afalg_do_cipher)
|| !EVP_CIPHER_meth_set_cleanup(cipher_handle->_hidden,
afalg_cipher_cleanup)
|| !EVP_CIPHER_meth_set_impl_ctx_size(cipher_handle->_hidden,
sizeof(afalg_ctx)))) {
EVP_CIPHER_meth_free(cipher_handle->_hidden);
cipher_handle->_hidden= NULL;
}
return cipher_handle->_hidden;
}
static int afalg_ciphers(ENGINE *e, const EVP_CIPHER **cipher,
const int **nids, int nid)
{
int r = 1;
if (cipher == NULL) {
*nids = afalg_cipher_nids;
return (sizeof(afalg_cipher_nids) / sizeof(afalg_cipher_nids[0]));
}
switch (nid) {
case NID_aes_128_cbc:
case NID_aes_192_cbc:
case NID_aes_256_cbc:
*cipher = afalg_aes_cbc(nid);
break;
default:
*cipher = NULL;
r = 0;
}
return r;
}
static int bind_afalg(ENGINE *e)
{
/* Ensure the afalg error handling is set up */
unsigned short i;
ERR_load_AFALG_strings();
if (!ENGINE_set_id(e, engine_afalg_id)
|| !ENGINE_set_name(e, engine_afalg_name)
|| !ENGINE_set_destroy_function(e, afalg_destroy)
|| !ENGINE_set_init_function(e, afalg_init)
|| !ENGINE_set_finish_function(e, afalg_finish)) {
AFALGerr(AFALG_F_BIND_AFALG, AFALG_R_INIT_FAILED);
return 0;
}
/*
* Create _hidden_aes_xxx_cbc by calling afalg_aes_xxx_cbc
* now, as bind_aflag can only be called by one thread at a
* time.
*/
for(i = 0; i < OSSL_NELEM(afalg_cipher_nids); i++) {
if (afalg_aes_cbc(afalg_cipher_nids[i]) == NULL) {
AFALGerr(AFALG_F_BIND_AFALG, AFALG_R_INIT_FAILED);
return 0;
}
}
if (!ENGINE_set_ciphers(e, afalg_ciphers)) {
AFALGerr(AFALG_F_BIND_AFALG, AFALG_R_INIT_FAILED);
return 0;
}
return 1;
}
# ifndef OPENSSL_NO_DYNAMIC_ENGINE
static int bind_helper(ENGINE *e, const char *id)
{
if (id && (strcmp(id, engine_afalg_id) != 0))
return 0;
if (!afalg_chk_platform())
return 0;
- if (!bind_afalg(e))
+ if (!bind_afalg(e)) {
+ afalg_destroy(e);
return 0;
+ }
return 1;
}
IMPLEMENT_DYNAMIC_CHECK_FN()
IMPLEMENT_DYNAMIC_BIND_FN(bind_helper)
# endif
static int afalg_chk_platform(void)
{
int ret;
int i;
int kver[3] = { -1, -1, -1 };
int sock;
char *str;
struct utsname ut;
ret = uname(&ut);
if (ret != 0) {
AFALGerr(AFALG_F_AFALG_CHK_PLATFORM,
AFALG_R_FAILED_TO_GET_PLATFORM_INFO);
return 0;
}
str = strtok(ut.release, ".");
for (i = 0; i < 3 && str != NULL; i++) {
kver[i] = atoi(str);
str = strtok(NULL, ".");
}
if (KERNEL_VERSION(kver[0], kver[1], kver[2])
< KERNEL_VERSION(K_MAJ, K_MIN1, K_MIN2)) {
ALG_ERR("ASYNC AFALG not supported this kernel(%d.%d.%d)\n",
kver[0], kver[1], kver[2]);
ALG_ERR("ASYNC AFALG requires kernel version %d.%d.%d or later\n",
K_MAJ, K_MIN1, K_MIN2);
AFALGerr(AFALG_F_AFALG_CHK_PLATFORM,
AFALG_R_KERNEL_DOES_NOT_SUPPORT_ASYNC_AFALG);
return 0;
}
/* Test if we can actually create an AF_ALG socket */
sock = socket(AF_ALG, SOCK_SEQPACKET, 0);
if (sock == -1) {
AFALGerr(AFALG_F_AFALG_CHK_PLATFORM, AFALG_R_SOCKET_CREATE_FAILED);
return 0;
}
close(sock);
return 1;
}
# ifdef OPENSSL_NO_DYNAMIC_ENGINE
static ENGINE *engine_afalg(void)
{
ENGINE *ret = ENGINE_new();
if (ret == NULL)
return NULL;
if (!bind_afalg(ret)) {
ENGINE_free(ret);
return NULL;
}
return ret;
}
void engine_load_afalg_int(void)
{
ENGINE *toadd;
if (!afalg_chk_platform())
return;
toadd = engine_afalg();
if (toadd == NULL)
return;
ERR_set_mark();
ENGINE_add(toadd);
/*
* If the "add" worked, it gets a structural reference. So either way, we
* release our just-created reference.
*/
ENGINE_free(toadd);
/*
* If the "add" didn't work, it was probably a conflict because it was
* already added (eg. someone calling ENGINE_load_blah then calling
* ENGINE_load_builtin_engines() perhaps).
*/
ERR_pop_to_mark();
}
# endif
static int afalg_init(ENGINE *e)
{
return 1;
}
static int afalg_finish(ENGINE *e)
{
return 1;
}
static int free_cbc(void)
{
short unsigned int i;
for(i = 0; i < OSSL_NELEM(afalg_cipher_nids); i++) {
EVP_CIPHER_meth_free(cbc_handle[i]._hidden);
cbc_handle[i]._hidden = NULL;
}
return 1;
}
static int afalg_destroy(ENGINE *e)
{
ERR_unload_AFALG_strings();
free_cbc();
return 1;
}
#endif /* KERNEL VERSION */
diff --git a/crypto/openssl/engines/e_dasync.c b/crypto/openssl/engines/e_dasync.c
index 7974106ae219..329d618f5552 100644
--- a/crypto/openssl/engines/e_dasync.c
+++ b/crypto/openssl/engines/e_dasync.c
@@ -1,1010 +1,1010 @@
/*
- * Copyright 2015-2021 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2015-2024 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
/* We need to use some engine deprecated APIs */
#define OPENSSL_SUPPRESS_DEPRECATED
/*
* SHA-1 low level APIs are deprecated for public use, but still ok for
* internal use. Note, that due to symbols not being exported, only the
* #defines and strucures can be accessed, in this case SHA_CBLOCK and
* sizeof(SHA_CTX).
*/
#include "internal/deprecated.h"
#include <openssl/opensslconf.h>
#if defined(_WIN32)
# include <windows.h>
#endif
#include <stdio.h>
#include <string.h>
#include <openssl/engine.h>
#include <openssl/sha.h>
#include <openssl/aes.h>
#include <openssl/rsa.h>
#include <openssl/evp.h>
#include <openssl/async.h>
#include <openssl/bn.h>
#include <openssl/crypto.h>
#include <openssl/ssl.h>
#include <openssl/modes.h>
#if defined(OPENSSL_SYS_UNIX) && defined(OPENSSL_THREADS)
# undef ASYNC_POSIX
# define ASYNC_POSIX
# include <unistd.h>
#elif defined(_WIN32)
# undef ASYNC_WIN
# define ASYNC_WIN
#endif
#include "e_dasync_err.c"
/* Engine Id and Name */
static const char *engine_dasync_id = "dasync";
static const char *engine_dasync_name = "Dummy Async engine support";
/* Engine Lifetime functions */
static int dasync_destroy(ENGINE *e);
static int dasync_init(ENGINE *e);
static int dasync_finish(ENGINE *e);
void engine_load_dasync_int(void);
/* Set up digests. Just SHA1 for now */
static int dasync_digests(ENGINE *e, const EVP_MD **digest,
const int **nids, int nid);
static void dummy_pause_job(void);
/* SHA1 */
static int dasync_sha1_init(EVP_MD_CTX *ctx);
static int dasync_sha1_update(EVP_MD_CTX *ctx, const void *data,
size_t count);
static int dasync_sha1_final(EVP_MD_CTX *ctx, unsigned char *md);
/*
* Holds the EVP_MD object for sha1 in this engine. Set up once only during
* engine bind and can then be reused many times.
*/
static EVP_MD *_hidden_sha1_md = NULL;
static const EVP_MD *dasync_sha1(void)
{
return _hidden_sha1_md;
}
static void destroy_digests(void)
{
EVP_MD_meth_free(_hidden_sha1_md);
_hidden_sha1_md = NULL;
}
static int dasync_digest_nids(const int **nids)
{
static int digest_nids[2] = { 0, 0 };
static int pos = 0;
static int init = 0;
if (!init) {
const EVP_MD *md;
if ((md = dasync_sha1()) != NULL)
digest_nids[pos++] = EVP_MD_get_type(md);
digest_nids[pos] = 0;
init = 1;
}
*nids = digest_nids;
return pos;
}
/* RSA */
static int dasync_pkey(ENGINE *e, EVP_PKEY_METHOD **pmeth,
const int **pnids, int nid);
static int dasync_rsa_init(EVP_PKEY_CTX *ctx);
static void dasync_rsa_cleanup(EVP_PKEY_CTX *ctx);
static int dasync_rsa_paramgen_init(EVP_PKEY_CTX *ctx);
static int dasync_rsa_paramgen(EVP_PKEY_CTX *ctx, EVP_PKEY *pkey);
static int dasync_rsa_keygen_init(EVP_PKEY_CTX *ctx);
static int dasync_rsa_keygen(EVP_PKEY_CTX *ctx, EVP_PKEY *pkey);
static int dasync_rsa_encrypt_init(EVP_PKEY_CTX *ctx);
static int dasync_rsa_encrypt(EVP_PKEY_CTX *ctx, unsigned char *out,
size_t *outlen, const unsigned char *in,
size_t inlen);
static int dasync_rsa_decrypt_init(EVP_PKEY_CTX *ctx);
static int dasync_rsa_decrypt(EVP_PKEY_CTX *ctx, unsigned char *out,
size_t *outlen, const unsigned char *in,
size_t inlen);
static int dasync_rsa_ctrl(EVP_PKEY_CTX *ctx, int type, int p1, void *p2);
static int dasync_rsa_ctrl_str(EVP_PKEY_CTX *ctx, const char *type,
const char *value);
static EVP_PKEY_METHOD *dasync_rsa;
static const EVP_PKEY_METHOD *dasync_rsa_orig;
/* AES */
static int dasync_aes128_cbc_ctrl(EVP_CIPHER_CTX *ctx, int type, int arg,
void *ptr);
static int dasync_aes128_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key,
const unsigned char *iv, int enc);
static int dasync_aes128_cbc_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
const unsigned char *in, size_t inl);
static int dasync_aes128_cbc_cleanup(EVP_CIPHER_CTX *ctx);
static int dasync_aes256_ctr_ctrl(EVP_CIPHER_CTX *ctx, int type, int arg,
void *ptr);
static int dasync_aes256_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key,
const unsigned char *iv, int enc);
static int dasync_aes256_ctr_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
const unsigned char *in, size_t inl);
static int dasync_aes256_ctr_cleanup(EVP_CIPHER_CTX *ctx);
static int dasync_aes128_cbc_hmac_sha1_ctrl(EVP_CIPHER_CTX *ctx, int type,
int arg, void *ptr);
static int dasync_aes128_cbc_hmac_sha1_init_key(EVP_CIPHER_CTX *ctx,
const unsigned char *key,
const unsigned char *iv,
int enc);
static int dasync_aes128_cbc_hmac_sha1_cipher(EVP_CIPHER_CTX *ctx,
unsigned char *out,
const unsigned char *in,
size_t inl);
static int dasync_aes128_cbc_hmac_sha1_cleanup(EVP_CIPHER_CTX *ctx);
struct dasync_pipeline_ctx {
void *inner_cipher_data;
unsigned int numpipes;
unsigned char **inbufs;
unsigned char **outbufs;
size_t *lens;
unsigned char tlsaad[SSL_MAX_PIPELINES][EVP_AEAD_TLS1_AAD_LEN];
unsigned int aadctr;
};
/*
* Holds the EVP_CIPHER object for aes_128_cbc in this engine. Set up once only
* during engine bind and can then be reused many times.
*/
static EVP_CIPHER *_hidden_aes_128_cbc = NULL;
static const EVP_CIPHER *dasync_aes_128_cbc(void)
{
return _hidden_aes_128_cbc;
}
static EVP_CIPHER *_hidden_aes_256_ctr = NULL;
static const EVP_CIPHER *dasync_aes_256_ctr(void)
{
return _hidden_aes_256_ctr;
}
/*
* Holds the EVP_CIPHER object for aes_128_cbc_hmac_sha1 in this engine. Set up
* once only during engine bind and can then be reused many times.
*
* This 'stitched' cipher depends on the EVP_aes_128_cbc_hmac_sha1() cipher,
* which is implemented only if the AES-NI instruction set extension is available
* (see OPENSSL_IA32CAP(3)). If that's not the case, then this cipher will not
* be available either.
*
* Note: Since it is a legacy mac-then-encrypt cipher, modern TLS peers (which
* negotiate the encrypt-then-mac extension) won't negotiate it anyway.
*/
static EVP_CIPHER *_hidden_aes_128_cbc_hmac_sha1 = NULL;
static const EVP_CIPHER *dasync_aes_128_cbc_hmac_sha1(void)
{
return _hidden_aes_128_cbc_hmac_sha1;
}
static void destroy_ciphers(void)
{
EVP_CIPHER_meth_free(_hidden_aes_128_cbc);
EVP_CIPHER_meth_free(_hidden_aes_256_ctr);
EVP_CIPHER_meth_free(_hidden_aes_128_cbc_hmac_sha1);
_hidden_aes_128_cbc = NULL;
_hidden_aes_256_ctr = NULL;
_hidden_aes_128_cbc_hmac_sha1 = NULL;
}
static int dasync_ciphers(ENGINE *e, const EVP_CIPHER **cipher,
const int **nids, int nid);
static int dasync_cipher_nids[] = {
NID_aes_128_cbc,
NID_aes_256_ctr,
NID_aes_128_cbc_hmac_sha1,
0
};
static int bind_dasync(ENGINE *e)
{
/* Setup RSA */
;
if ((dasync_rsa_orig = EVP_PKEY_meth_find(EVP_PKEY_RSA)) == NULL
|| (dasync_rsa = EVP_PKEY_meth_new(EVP_PKEY_RSA,
EVP_PKEY_FLAG_AUTOARGLEN)) == NULL)
return 0;
EVP_PKEY_meth_set_init(dasync_rsa, dasync_rsa_init);
EVP_PKEY_meth_set_cleanup(dasync_rsa, dasync_rsa_cleanup);
EVP_PKEY_meth_set_paramgen(dasync_rsa, dasync_rsa_paramgen_init,
dasync_rsa_paramgen);
EVP_PKEY_meth_set_keygen(dasync_rsa, dasync_rsa_keygen_init,
dasync_rsa_keygen);
EVP_PKEY_meth_set_encrypt(dasync_rsa, dasync_rsa_encrypt_init,
dasync_rsa_encrypt);
EVP_PKEY_meth_set_decrypt(dasync_rsa, dasync_rsa_decrypt_init,
dasync_rsa_decrypt);
EVP_PKEY_meth_set_ctrl(dasync_rsa, dasync_rsa_ctrl,
dasync_rsa_ctrl_str);
/* Ensure the dasync error handling is set up */
ERR_load_DASYNC_strings();
if (!ENGINE_set_id(e, engine_dasync_id)
|| !ENGINE_set_name(e, engine_dasync_name)
|| !ENGINE_set_pkey_meths(e, dasync_pkey)
|| !ENGINE_set_digests(e, dasync_digests)
|| !ENGINE_set_ciphers(e, dasync_ciphers)
|| !ENGINE_set_destroy_function(e, dasync_destroy)
|| !ENGINE_set_init_function(e, dasync_init)
|| !ENGINE_set_finish_function(e, dasync_finish)) {
DASYNCerr(DASYNC_F_BIND_DASYNC, DASYNC_R_INIT_FAILED);
return 0;
}
/*
* Set up the EVP_CIPHER and EVP_MD objects for the ciphers/digests
* supplied by this engine
*/
_hidden_sha1_md = EVP_MD_meth_new(NID_sha1, NID_sha1WithRSAEncryption);
if (_hidden_sha1_md == NULL
|| !EVP_MD_meth_set_result_size(_hidden_sha1_md, SHA_DIGEST_LENGTH)
|| !EVP_MD_meth_set_input_blocksize(_hidden_sha1_md, SHA_CBLOCK)
|| !EVP_MD_meth_set_app_datasize(_hidden_sha1_md,
sizeof(EVP_MD *) + sizeof(SHA_CTX))
|| !EVP_MD_meth_set_flags(_hidden_sha1_md, EVP_MD_FLAG_DIGALGID_ABSENT)
|| !EVP_MD_meth_set_init(_hidden_sha1_md, dasync_sha1_init)
|| !EVP_MD_meth_set_update(_hidden_sha1_md, dasync_sha1_update)
|| !EVP_MD_meth_set_final(_hidden_sha1_md, dasync_sha1_final)) {
EVP_MD_meth_free(_hidden_sha1_md);
_hidden_sha1_md = NULL;
}
_hidden_aes_128_cbc = EVP_CIPHER_meth_new(NID_aes_128_cbc,
16 /* block size */,
16 /* key len */);
if (_hidden_aes_128_cbc == NULL
|| !EVP_CIPHER_meth_set_iv_length(_hidden_aes_128_cbc,16)
|| !EVP_CIPHER_meth_set_flags(_hidden_aes_128_cbc,
EVP_CIPH_FLAG_DEFAULT_ASN1
| EVP_CIPH_CBC_MODE
| EVP_CIPH_FLAG_PIPELINE
| EVP_CIPH_CUSTOM_COPY)
|| !EVP_CIPHER_meth_set_init(_hidden_aes_128_cbc,
dasync_aes128_init_key)
|| !EVP_CIPHER_meth_set_do_cipher(_hidden_aes_128_cbc,
dasync_aes128_cbc_cipher)
|| !EVP_CIPHER_meth_set_cleanup(_hidden_aes_128_cbc,
dasync_aes128_cbc_cleanup)
|| !EVP_CIPHER_meth_set_ctrl(_hidden_aes_128_cbc,
dasync_aes128_cbc_ctrl)
|| !EVP_CIPHER_meth_set_impl_ctx_size(_hidden_aes_128_cbc,
sizeof(struct dasync_pipeline_ctx))) {
EVP_CIPHER_meth_free(_hidden_aes_128_cbc);
_hidden_aes_128_cbc = NULL;
}
_hidden_aes_256_ctr = EVP_CIPHER_meth_new(NID_aes_256_ctr,
1 /* block size */,
32 /* key len */);
if (_hidden_aes_256_ctr == NULL
|| !EVP_CIPHER_meth_set_iv_length(_hidden_aes_256_ctr,16)
|| !EVP_CIPHER_meth_set_flags(_hidden_aes_256_ctr,
EVP_CIPH_FLAG_DEFAULT_ASN1
| EVP_CIPH_CTR_MODE
| EVP_CIPH_FLAG_PIPELINE
| EVP_CIPH_CUSTOM_COPY)
|| !EVP_CIPHER_meth_set_init(_hidden_aes_256_ctr,
dasync_aes256_init_key)
|| !EVP_CIPHER_meth_set_do_cipher(_hidden_aes_256_ctr,
dasync_aes256_ctr_cipher)
|| !EVP_CIPHER_meth_set_cleanup(_hidden_aes_256_ctr,
dasync_aes256_ctr_cleanup)
|| !EVP_CIPHER_meth_set_ctrl(_hidden_aes_256_ctr,
dasync_aes256_ctr_ctrl)
|| !EVP_CIPHER_meth_set_impl_ctx_size(_hidden_aes_256_ctr,
sizeof(struct dasync_pipeline_ctx))) {
EVP_CIPHER_meth_free(_hidden_aes_256_ctr);
_hidden_aes_256_ctr = NULL;
}
_hidden_aes_128_cbc_hmac_sha1 = EVP_CIPHER_meth_new(
NID_aes_128_cbc_hmac_sha1,
16 /* block size */,
16 /* key len */);
if (_hidden_aes_128_cbc_hmac_sha1 == NULL
|| !EVP_CIPHER_meth_set_iv_length(_hidden_aes_128_cbc_hmac_sha1,16)
|| !EVP_CIPHER_meth_set_flags(_hidden_aes_128_cbc_hmac_sha1,
EVP_CIPH_CBC_MODE
| EVP_CIPH_FLAG_DEFAULT_ASN1
| EVP_CIPH_FLAG_AEAD_CIPHER
| EVP_CIPH_FLAG_PIPELINE
| EVP_CIPH_CUSTOM_COPY)
|| !EVP_CIPHER_meth_set_init(_hidden_aes_128_cbc_hmac_sha1,
dasync_aes128_cbc_hmac_sha1_init_key)
|| !EVP_CIPHER_meth_set_do_cipher(_hidden_aes_128_cbc_hmac_sha1,
dasync_aes128_cbc_hmac_sha1_cipher)
|| !EVP_CIPHER_meth_set_cleanup(_hidden_aes_128_cbc_hmac_sha1,
dasync_aes128_cbc_hmac_sha1_cleanup)
|| !EVP_CIPHER_meth_set_ctrl(_hidden_aes_128_cbc_hmac_sha1,
dasync_aes128_cbc_hmac_sha1_ctrl)
|| !EVP_CIPHER_meth_set_impl_ctx_size(_hidden_aes_128_cbc_hmac_sha1,
sizeof(struct dasync_pipeline_ctx))) {
EVP_CIPHER_meth_free(_hidden_aes_128_cbc_hmac_sha1);
_hidden_aes_128_cbc_hmac_sha1 = NULL;
}
return 1;
}
static void destroy_pkey(void)
{
/*
* We don't actually need to free the dasync_rsa method since this is
* automatically freed for us by libcrypto.
*/
dasync_rsa_orig = NULL;
dasync_rsa = NULL;
}
# ifndef OPENSSL_NO_DYNAMIC_ENGINE
static int bind_helper(ENGINE *e, const char *id)
{
if (id && (strcmp(id, engine_dasync_id) != 0))
return 0;
if (!bind_dasync(e))
return 0;
return 1;
}
IMPLEMENT_DYNAMIC_CHECK_FN()
IMPLEMENT_DYNAMIC_BIND_FN(bind_helper)
# endif
static ENGINE *engine_dasync(void)
{
ENGINE *ret = ENGINE_new();
if (!ret)
return NULL;
if (!bind_dasync(ret)) {
ENGINE_free(ret);
return NULL;
}
return ret;
}
void engine_load_dasync_int(void)
{
ENGINE *toadd = engine_dasync();
if (!toadd)
return;
ERR_set_mark();
ENGINE_add(toadd);
/*
* If the "add" worked, it gets a structural reference. So either way, we
* release our just-created reference.
*/
ENGINE_free(toadd);
/*
* If the "add" didn't work, it was probably a conflict because it was
* already added (eg. someone calling ENGINE_load_blah then calling
* ENGINE_load_builtin_engines() perhaps).
*/
ERR_pop_to_mark();
}
static int dasync_init(ENGINE *e)
{
return 1;
}
static int dasync_finish(ENGINE *e)
{
return 1;
}
static int dasync_destroy(ENGINE *e)
{
destroy_digests();
destroy_ciphers();
destroy_pkey();
ERR_unload_DASYNC_strings();
return 1;
}
static int dasync_pkey(ENGINE *e, EVP_PKEY_METHOD **pmeth,
const int **pnids, int nid)
{
static const int rnid = EVP_PKEY_RSA;
if (pmeth == NULL) {
*pnids = &rnid;
return 1;
}
if (nid == EVP_PKEY_RSA) {
*pmeth = dasync_rsa;
return 1;
}
*pmeth = NULL;
return 0;
}
static int dasync_digests(ENGINE *e, const EVP_MD **digest,
const int **nids, int nid)
{
int ok = 1;
if (!digest) {
/* We are returning a list of supported nids */
return dasync_digest_nids(nids);
}
/* We are being asked for a specific digest */
switch (nid) {
case NID_sha1:
*digest = dasync_sha1();
break;
default:
ok = 0;
*digest = NULL;
break;
}
return ok;
}
static int dasync_ciphers(ENGINE *e, const EVP_CIPHER **cipher,
const int **nids, int nid)
{
int ok = 1;
if (cipher == NULL) {
/* We are returning a list of supported nids */
*nids = dasync_cipher_nids;
return (sizeof(dasync_cipher_nids) -
1) / sizeof(dasync_cipher_nids[0]);
}
/* We are being asked for a specific cipher */
switch (nid) {
case NID_aes_128_cbc:
*cipher = dasync_aes_128_cbc();
break;
case NID_aes_256_ctr:
*cipher = dasync_aes_256_ctr();
break;
case NID_aes_128_cbc_hmac_sha1:
*cipher = dasync_aes_128_cbc_hmac_sha1();
break;
default:
ok = 0;
*cipher = NULL;
break;
}
return ok;
}
static void wait_cleanup(ASYNC_WAIT_CTX *ctx, const void *key,
OSSL_ASYNC_FD readfd, void *pvwritefd)
{
OSSL_ASYNC_FD *pwritefd = (OSSL_ASYNC_FD *)pvwritefd;
#if defined(ASYNC_WIN)
CloseHandle(readfd);
CloseHandle(*pwritefd);
#elif defined(ASYNC_POSIX)
close(readfd);
close(*pwritefd);
#endif
OPENSSL_free(pwritefd);
}
#define DUMMY_CHAR 'X'
static void dummy_pause_job(void) {
ASYNC_JOB *job;
ASYNC_WAIT_CTX *waitctx;
ASYNC_callback_fn callback;
void * callback_arg;
OSSL_ASYNC_FD pipefds[2] = {0, 0};
OSSL_ASYNC_FD *writefd;
#if defined(ASYNC_WIN)
DWORD numwritten, numread;
char buf = DUMMY_CHAR;
#elif defined(ASYNC_POSIX)
char buf = DUMMY_CHAR;
#endif
if ((job = ASYNC_get_current_job()) == NULL)
return;
waitctx = ASYNC_get_wait_ctx(job);
if (ASYNC_WAIT_CTX_get_callback(waitctx, &callback, &callback_arg) && callback != NULL) {
/*
* In the Dummy async engine we are cheating. We call the callback that the job
* is complete before the call to ASYNC_pause_job(). A real
* async engine would only call the callback when the job was actually complete
*/
(*callback)(callback_arg);
ASYNC_pause_job();
return;
}
if (ASYNC_WAIT_CTX_get_fd(waitctx, engine_dasync_id, &pipefds[0],
(void **)&writefd)) {
pipefds[1] = *writefd;
} else {
writefd = OPENSSL_malloc(sizeof(*writefd));
if (writefd == NULL)
return;
#if defined(ASYNC_WIN)
if (CreatePipe(&pipefds[0], &pipefds[1], NULL, 256) == 0) {
OPENSSL_free(writefd);
return;
}
#elif defined(ASYNC_POSIX)
if (pipe(pipefds) != 0) {
OPENSSL_free(writefd);
return;
}
#endif
*writefd = pipefds[1];
if (!ASYNC_WAIT_CTX_set_wait_fd(waitctx, engine_dasync_id, pipefds[0],
writefd, wait_cleanup)) {
wait_cleanup(waitctx, engine_dasync_id, pipefds[0], writefd);
return;
}
}
/*
* In the Dummy async engine we are cheating. We signal that the job
* is complete by waking it before the call to ASYNC_pause_job(). A real
* async engine would only wake when the job was actually complete
*/
#if defined(ASYNC_WIN)
WriteFile(pipefds[1], &buf, 1, &numwritten, NULL);
#elif defined(ASYNC_POSIX)
if (write(pipefds[1], &buf, 1) < 0)
return;
#endif
/* Ignore errors - we carry on anyway */
ASYNC_pause_job();
/* Clear the wake signal */
#if defined(ASYNC_WIN)
ReadFile(pipefds[0], &buf, 1, &numread, NULL);
#elif defined(ASYNC_POSIX)
if (read(pipefds[0], &buf, 1) < 0)
return;
#endif
}
/*
* SHA1 implementation. At the moment we just defer to the standard
* implementation
*/
static int dasync_sha1_init(EVP_MD_CTX *ctx)
{
dummy_pause_job();
return EVP_MD_meth_get_init(EVP_sha1())(ctx);
}
static int dasync_sha1_update(EVP_MD_CTX *ctx, const void *data,
size_t count)
{
dummy_pause_job();
return EVP_MD_meth_get_update(EVP_sha1())(ctx, data, count);
}
static int dasync_sha1_final(EVP_MD_CTX *ctx, unsigned char *md)
{
dummy_pause_job();
return EVP_MD_meth_get_final(EVP_sha1())(ctx, md);
}
/* Cipher helper functions */
static int dasync_cipher_ctrl_helper(EVP_CIPHER_CTX *ctx, int type, int arg,
void *ptr, int aeadcapable,
const EVP_CIPHER *ciph)
{
int ret;
struct dasync_pipeline_ctx *pipe_ctx =
(struct dasync_pipeline_ctx *)EVP_CIPHER_CTX_get_cipher_data(ctx);
if (pipe_ctx == NULL)
return 0;
switch (type) {
case EVP_CTRL_COPY:
{
size_t sz = EVP_CIPHER_impl_ctx_size(ciph);
void *inner_cipher_data = OPENSSL_malloc(sz);
if (inner_cipher_data == NULL)
return -1;
memcpy(inner_cipher_data, pipe_ctx->inner_cipher_data, sz);
pipe_ctx->inner_cipher_data = inner_cipher_data;
}
break;
case EVP_CTRL_SET_PIPELINE_OUTPUT_BUFS:
pipe_ctx->numpipes = arg;
pipe_ctx->outbufs = (unsigned char **)ptr;
break;
case EVP_CTRL_SET_PIPELINE_INPUT_BUFS:
pipe_ctx->numpipes = arg;
pipe_ctx->inbufs = (unsigned char **)ptr;
break;
case EVP_CTRL_SET_PIPELINE_INPUT_LENS:
pipe_ctx->numpipes = arg;
pipe_ctx->lens = (size_t *)ptr;
break;
case EVP_CTRL_AEAD_SET_MAC_KEY:
if (!aeadcapable)
return -1;
EVP_CIPHER_CTX_set_cipher_data(ctx, pipe_ctx->inner_cipher_data);
ret = EVP_CIPHER_meth_get_ctrl(EVP_aes_128_cbc_hmac_sha1())
(ctx, type, arg, ptr);
EVP_CIPHER_CTX_set_cipher_data(ctx, pipe_ctx);
return ret;
case EVP_CTRL_AEAD_TLS1_AAD:
{
unsigned char *p = ptr;
unsigned int len;
if (!aeadcapable || arg != EVP_AEAD_TLS1_AAD_LEN)
return -1;
if (pipe_ctx->aadctr >= SSL_MAX_PIPELINES)
return -1;
memcpy(pipe_ctx->tlsaad[pipe_ctx->aadctr], ptr,
EVP_AEAD_TLS1_AAD_LEN);
pipe_ctx->aadctr++;
len = p[arg - 2] << 8 | p[arg - 1];
if (EVP_CIPHER_CTX_is_encrypting(ctx)) {
if ((p[arg - 4] << 8 | p[arg - 3]) >= TLS1_1_VERSION) {
if (len < AES_BLOCK_SIZE)
return 0;
len -= AES_BLOCK_SIZE;
}
return ((len + SHA_DIGEST_LENGTH + AES_BLOCK_SIZE)
& -AES_BLOCK_SIZE) - len;
} else {
return SHA_DIGEST_LENGTH;
}
}
default:
return 0;
}
return 1;
}
static int dasync_cipher_init_key_helper(EVP_CIPHER_CTX *ctx,
const unsigned char *key,
const unsigned char *iv, int enc,
const EVP_CIPHER *cipher)
{
int ret;
struct dasync_pipeline_ctx *pipe_ctx =
(struct dasync_pipeline_ctx *)EVP_CIPHER_CTX_get_cipher_data(ctx);
if (pipe_ctx->inner_cipher_data == NULL
&& EVP_CIPHER_impl_ctx_size(cipher) != 0) {
pipe_ctx->inner_cipher_data = OPENSSL_zalloc(
EVP_CIPHER_impl_ctx_size(cipher));
if (pipe_ctx->inner_cipher_data == NULL) {
DASYNCerr(DASYNC_F_DASYNC_CIPHER_INIT_KEY_HELPER,
ERR_R_MALLOC_FAILURE);
return 0;
}
}
pipe_ctx->numpipes = 0;
pipe_ctx->aadctr = 0;
EVP_CIPHER_CTX_set_cipher_data(ctx, pipe_ctx->inner_cipher_data);
ret = EVP_CIPHER_meth_get_init(cipher)(ctx, key, iv, enc);
EVP_CIPHER_CTX_set_cipher_data(ctx, pipe_ctx);
return ret;
}
static int dasync_cipher_helper(EVP_CIPHER_CTX *ctx, unsigned char *out,
const unsigned char *in, size_t inl,
const EVP_CIPHER *cipher)
{
int ret = 1;
unsigned int i, pipes;
struct dasync_pipeline_ctx *pipe_ctx =
(struct dasync_pipeline_ctx *)EVP_CIPHER_CTX_get_cipher_data(ctx);
pipes = pipe_ctx->numpipes;
EVP_CIPHER_CTX_set_cipher_data(ctx, pipe_ctx->inner_cipher_data);
if (pipes == 0) {
if (pipe_ctx->aadctr != 0) {
if (pipe_ctx->aadctr != 1)
return -1;
EVP_CIPHER_meth_get_ctrl(cipher)
(ctx, EVP_CTRL_AEAD_TLS1_AAD,
EVP_AEAD_TLS1_AAD_LEN,
pipe_ctx->tlsaad[0]);
}
ret = EVP_CIPHER_meth_get_do_cipher(cipher)
(ctx, out, in, inl);
} else {
if (pipe_ctx->aadctr > 0 && pipe_ctx->aadctr != pipes)
return -1;
for (i = 0; i < pipes; i++) {
if (pipe_ctx->aadctr > 0) {
EVP_CIPHER_meth_get_ctrl(cipher)
(ctx, EVP_CTRL_AEAD_TLS1_AAD,
EVP_AEAD_TLS1_AAD_LEN,
pipe_ctx->tlsaad[i]);
}
ret = ret && EVP_CIPHER_meth_get_do_cipher(cipher)
(ctx, pipe_ctx->outbufs[i], pipe_ctx->inbufs[i],
pipe_ctx->lens[i]);
}
pipe_ctx->numpipes = 0;
}
pipe_ctx->aadctr = 0;
EVP_CIPHER_CTX_set_cipher_data(ctx, pipe_ctx);
return ret;
}
static int dasync_cipher_cleanup_helper(EVP_CIPHER_CTX *ctx,
const EVP_CIPHER *cipher)
{
struct dasync_pipeline_ctx *pipe_ctx =
(struct dasync_pipeline_ctx *)EVP_CIPHER_CTX_get_cipher_data(ctx);
OPENSSL_clear_free(pipe_ctx->inner_cipher_data,
EVP_CIPHER_impl_ctx_size(cipher));
return 1;
}
/*
* AES128 CBC Implementation
*/
static int dasync_aes128_cbc_ctrl(EVP_CIPHER_CTX *ctx, int type, int arg,
void *ptr)
{
return dasync_cipher_ctrl_helper(ctx, type, arg, ptr, 0, EVP_aes_128_cbc());
}
static int dasync_aes128_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key,
const unsigned char *iv, int enc)
{
return dasync_cipher_init_key_helper(ctx, key, iv, enc, EVP_aes_128_cbc());
}
static int dasync_aes128_cbc_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
const unsigned char *in, size_t inl)
{
return dasync_cipher_helper(ctx, out, in, inl, EVP_aes_128_cbc());
}
static int dasync_aes128_cbc_cleanup(EVP_CIPHER_CTX *ctx)
{
return dasync_cipher_cleanup_helper(ctx, EVP_aes_128_cbc());
}
static int dasync_aes256_ctr_ctrl(EVP_CIPHER_CTX *ctx, int type, int arg,
void *ptr)
{
return dasync_cipher_ctrl_helper(ctx, type, arg, ptr, 0, EVP_aes_256_ctr());
}
static int dasync_aes256_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key,
const unsigned char *iv, int enc)
{
return dasync_cipher_init_key_helper(ctx, key, iv, enc, EVP_aes_256_ctr());
}
static int dasync_aes256_ctr_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
const unsigned char *in, size_t inl)
{
return dasync_cipher_helper(ctx, out, in, inl, EVP_aes_256_ctr());
}
static int dasync_aes256_ctr_cleanup(EVP_CIPHER_CTX *ctx)
{
return dasync_cipher_cleanup_helper(ctx, EVP_aes_256_ctr());
}
/*
* AES128 CBC HMAC SHA1 Implementation
*/
static int dasync_aes128_cbc_hmac_sha1_ctrl(EVP_CIPHER_CTX *ctx, int type,
int arg, void *ptr)
{
return dasync_cipher_ctrl_helper(ctx, type, arg, ptr, 1, EVP_aes_128_cbc_hmac_sha1());
}
static int dasync_aes128_cbc_hmac_sha1_init_key(EVP_CIPHER_CTX *ctx,
const unsigned char *key,
const unsigned char *iv,
int enc)
{
/*
* We can safely assume that EVP_aes_128_cbc_hmac_sha1() != NULL,
* see comment before the definition of dasync_aes_128_cbc_hmac_sha1().
*/
return dasync_cipher_init_key_helper(ctx, key, iv, enc,
EVP_aes_128_cbc_hmac_sha1());
}
static int dasync_aes128_cbc_hmac_sha1_cipher(EVP_CIPHER_CTX *ctx,
unsigned char *out,
const unsigned char *in,
size_t inl)
{
return dasync_cipher_helper(ctx, out, in, inl, EVP_aes_128_cbc_hmac_sha1());
}
static int dasync_aes128_cbc_hmac_sha1_cleanup(EVP_CIPHER_CTX *ctx)
{
/*
* We can safely assume that EVP_aes_128_cbc_hmac_sha1() != NULL,
* see comment before the definition of dasync_aes_128_cbc_hmac_sha1().
*/
return dasync_cipher_cleanup_helper(ctx, EVP_aes_128_cbc_hmac_sha1());
}
/*
* RSA implementation
*/
static int dasync_rsa_init(EVP_PKEY_CTX *ctx)
{
static int (*pinit)(EVP_PKEY_CTX *ctx);
if (pinit == NULL)
EVP_PKEY_meth_get_init(dasync_rsa_orig, &pinit);
return pinit(ctx);
}
static void dasync_rsa_cleanup(EVP_PKEY_CTX *ctx)
{
static void (*pcleanup)(EVP_PKEY_CTX *ctx);
if (pcleanup == NULL)
EVP_PKEY_meth_get_cleanup(dasync_rsa_orig, &pcleanup);
pcleanup(ctx);
}
static int dasync_rsa_paramgen_init(EVP_PKEY_CTX *ctx)
{
static int (*pparamgen_init)(EVP_PKEY_CTX *ctx);
if (pparamgen_init == NULL)
EVP_PKEY_meth_get_paramgen(dasync_rsa_orig, &pparamgen_init, NULL);
return pparamgen_init != NULL ? pparamgen_init(ctx) : 1;
}
static int dasync_rsa_paramgen(EVP_PKEY_CTX *ctx, EVP_PKEY *pkey)
{
static int (*pparamgen)(EVP_PKEY_CTX *c, EVP_PKEY *pkey);
if (pparamgen == NULL)
EVP_PKEY_meth_get_paramgen(dasync_rsa_orig, NULL, &pparamgen);
return pparamgen != NULL ? pparamgen(ctx, pkey) : 1;
}
static int dasync_rsa_keygen_init(EVP_PKEY_CTX *ctx)
{
static int (*pkeygen_init)(EVP_PKEY_CTX *ctx);
if (pkeygen_init == NULL)
EVP_PKEY_meth_get_keygen(dasync_rsa_orig, &pkeygen_init, NULL);
return pkeygen_init != NULL ? pkeygen_init(ctx) : 1;
}
static int dasync_rsa_keygen(EVP_PKEY_CTX *ctx, EVP_PKEY *pkey)
{
static int (*pkeygen)(EVP_PKEY_CTX *c, EVP_PKEY *pkey);
if (pkeygen == NULL)
EVP_PKEY_meth_get_keygen(dasync_rsa_orig, NULL, &pkeygen);
return pkeygen(ctx, pkey);
}
static int dasync_rsa_encrypt_init(EVP_PKEY_CTX *ctx)
{
static int (*pencrypt_init)(EVP_PKEY_CTX *ctx);
if (pencrypt_init == NULL)
EVP_PKEY_meth_get_encrypt(dasync_rsa_orig, &pencrypt_init, NULL);
return pencrypt_init != NULL ? pencrypt_init(ctx) : 1;
}
static int dasync_rsa_encrypt(EVP_PKEY_CTX *ctx, unsigned char *out,
size_t *outlen, const unsigned char *in,
size_t inlen)
{
static int (*pencryptfn)(EVP_PKEY_CTX *ctx, unsigned char *out,
size_t *outlen, const unsigned char *in,
size_t inlen);
if (pencryptfn == NULL)
EVP_PKEY_meth_get_encrypt(dasync_rsa_orig, NULL, &pencryptfn);
return pencryptfn(ctx, out, outlen, in, inlen);
}
static int dasync_rsa_decrypt_init(EVP_PKEY_CTX *ctx)
{
static int (*pdecrypt_init)(EVP_PKEY_CTX *ctx);
if (pdecrypt_init == NULL)
EVP_PKEY_meth_get_decrypt(dasync_rsa_orig, &pdecrypt_init, NULL);
return pdecrypt_init != NULL ? pdecrypt_init(ctx) : 1;
}
static int dasync_rsa_decrypt(EVP_PKEY_CTX *ctx, unsigned char *out,
size_t *outlen, const unsigned char *in,
size_t inlen)
{
static int (*pdecrypt)(EVP_PKEY_CTX *ctx, unsigned char *out,
size_t *outlen, const unsigned char *in,
size_t inlen);
if (pdecrypt == NULL)
- EVP_PKEY_meth_get_encrypt(dasync_rsa_orig, NULL, &pdecrypt);
+ EVP_PKEY_meth_get_decrypt(dasync_rsa_orig, NULL, &pdecrypt);
return pdecrypt(ctx, out, outlen, in, inlen);
}
static int dasync_rsa_ctrl(EVP_PKEY_CTX *ctx, int type, int p1, void *p2)
{
static int (*pctrl)(EVP_PKEY_CTX *ctx, int type, int p1, void *p2);
if (pctrl == NULL)
EVP_PKEY_meth_get_ctrl(dasync_rsa_orig, &pctrl, NULL);
return pctrl(ctx, type, p1, p2);
}
static int dasync_rsa_ctrl_str(EVP_PKEY_CTX *ctx, const char *type,
const char *value)
{
static int (*pctrl_str)(EVP_PKEY_CTX *ctx, const char *type,
const char *value);
if (pctrl_str == NULL)
EVP_PKEY_meth_get_ctrl(dasync_rsa_orig, NULL, &pctrl_str);
return pctrl_str(ctx, type, value);
}
diff --git a/crypto/openssl/fuzz/asn1.c b/crypto/openssl/fuzz/asn1.c
index ee602a08a3d9..f7a019774b9d 100644
--- a/crypto/openssl/fuzz/asn1.c
+++ b/crypto/openssl/fuzz/asn1.c
@@ -1,375 +1,381 @@
/*
- * Copyright 2016-2022 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2016-2024 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.
*/
/*
* Fuzz ASN.1 parsing for various data structures. Specify which on the
* command line:
*
* asn1 <data structure>
*/
/* We need to use some deprecated APIs */
#define OPENSSL_SUPPRESS_DEPRECATED
#include <stdio.h>
#include <string.h>
#include <openssl/asn1.h>
#include <openssl/asn1t.h>
#include <openssl/dh.h>
#include <openssl/dsa.h>
#include <openssl/ec.h>
#include <openssl/ocsp.h>
#include <openssl/pkcs12.h>
#include <openssl/rsa.h>
#include <openssl/ts.h>
#include <openssl/x509v3.h>
#include <openssl/cms.h>
#include <openssl/ess.h>
#include <openssl/err.h>
#include <openssl/rand.h>
#include <openssl/bio.h>
#include <openssl/evp.h>
#include <openssl/ssl.h>
#include "internal/nelem.h"
#include "fuzzer.h"
static ASN1_ITEM_EXP *item_type[] = {
ASN1_ITEM_ref(ACCESS_DESCRIPTION),
#ifndef OPENSSL_NO_RFC3779
ASN1_ITEM_ref(ASIdentifierChoice),
ASN1_ITEM_ref(ASIdentifiers),
ASN1_ITEM_ref(ASIdOrRange),
#endif
ASN1_ITEM_ref(ASN1_ANY),
ASN1_ITEM_ref(ASN1_BIT_STRING),
ASN1_ITEM_ref(ASN1_BMPSTRING),
ASN1_ITEM_ref(ASN1_BOOLEAN),
ASN1_ITEM_ref(ASN1_ENUMERATED),
ASN1_ITEM_ref(ASN1_FBOOLEAN),
ASN1_ITEM_ref(ASN1_GENERALIZEDTIME),
ASN1_ITEM_ref(ASN1_GENERALSTRING),
ASN1_ITEM_ref(ASN1_IA5STRING),
ASN1_ITEM_ref(ASN1_INTEGER),
ASN1_ITEM_ref(ASN1_NULL),
ASN1_ITEM_ref(ASN1_OBJECT),
ASN1_ITEM_ref(ASN1_OCTET_STRING),
ASN1_ITEM_ref(ASN1_OCTET_STRING_NDEF),
ASN1_ITEM_ref(ASN1_PRINTABLE),
ASN1_ITEM_ref(ASN1_PRINTABLESTRING),
ASN1_ITEM_ref(ASN1_SEQUENCE),
ASN1_ITEM_ref(ASN1_SEQUENCE_ANY),
ASN1_ITEM_ref(ASN1_SET_ANY),
ASN1_ITEM_ref(ASN1_T61STRING),
ASN1_ITEM_ref(ASN1_TBOOLEAN),
ASN1_ITEM_ref(ASN1_TIME),
ASN1_ITEM_ref(ASN1_UNIVERSALSTRING),
ASN1_ITEM_ref(ASN1_UTCTIME),
ASN1_ITEM_ref(ASN1_UTF8STRING),
ASN1_ITEM_ref(ASN1_VISIBLESTRING),
#ifndef OPENSSL_NO_RFC3779
ASN1_ITEM_ref(ASRange),
#endif
ASN1_ITEM_ref(AUTHORITY_INFO_ACCESS),
ASN1_ITEM_ref(AUTHORITY_KEYID),
ASN1_ITEM_ref(BASIC_CONSTRAINTS),
ASN1_ITEM_ref(BIGNUM),
ASN1_ITEM_ref(CBIGNUM),
ASN1_ITEM_ref(CERTIFICATEPOLICIES),
#ifndef OPENSSL_NO_CMS
ASN1_ITEM_ref(CMS_ContentInfo),
ASN1_ITEM_ref(CMS_ReceiptRequest),
ASN1_ITEM_ref(CRL_DIST_POINTS),
#endif
#ifndef OPENSSL_NO_DH
ASN1_ITEM_ref(DHparams),
#endif
ASN1_ITEM_ref(DIRECTORYSTRING),
ASN1_ITEM_ref(DISPLAYTEXT),
ASN1_ITEM_ref(DIST_POINT),
ASN1_ITEM_ref(DIST_POINT_NAME),
#if !defined(OPENSSL_NO_EC) && !defined(OPENSSL_NO_DEPRECATED_3_0)
ASN1_ITEM_ref(ECPARAMETERS),
ASN1_ITEM_ref(ECPKPARAMETERS),
#endif
ASN1_ITEM_ref(EDIPARTYNAME),
ASN1_ITEM_ref(EXTENDED_KEY_USAGE),
ASN1_ITEM_ref(GENERAL_NAME),
ASN1_ITEM_ref(GENERAL_NAMES),
ASN1_ITEM_ref(GENERAL_SUBTREE),
#ifndef OPENSSL_NO_RFC3779
ASN1_ITEM_ref(IPAddressChoice),
ASN1_ITEM_ref(IPAddressFamily),
ASN1_ITEM_ref(IPAddressOrRange),
ASN1_ITEM_ref(IPAddressRange),
#endif
ASN1_ITEM_ref(ISSUING_DIST_POINT),
#ifndef OPENSSL_NO_DEPRECATED_3_0
ASN1_ITEM_ref(LONG),
#endif
ASN1_ITEM_ref(NAME_CONSTRAINTS),
ASN1_ITEM_ref(NETSCAPE_CERT_SEQUENCE),
ASN1_ITEM_ref(NETSCAPE_SPKAC),
ASN1_ITEM_ref(NETSCAPE_SPKI),
ASN1_ITEM_ref(NOTICEREF),
#ifndef OPENSSL_NO_OCSP
ASN1_ITEM_ref(OCSP_BASICRESP),
ASN1_ITEM_ref(OCSP_CERTID),
ASN1_ITEM_ref(OCSP_CERTSTATUS),
ASN1_ITEM_ref(OCSP_CRLID),
ASN1_ITEM_ref(OCSP_ONEREQ),
ASN1_ITEM_ref(OCSP_REQINFO),
ASN1_ITEM_ref(OCSP_REQUEST),
ASN1_ITEM_ref(OCSP_RESPBYTES),
ASN1_ITEM_ref(OCSP_RESPDATA),
ASN1_ITEM_ref(OCSP_RESPID),
ASN1_ITEM_ref(OCSP_RESPONSE),
ASN1_ITEM_ref(OCSP_REVOKEDINFO),
ASN1_ITEM_ref(OCSP_SERVICELOC),
ASN1_ITEM_ref(OCSP_SIGNATURE),
ASN1_ITEM_ref(OCSP_SINGLERESP),
#endif
ASN1_ITEM_ref(OTHERNAME),
ASN1_ITEM_ref(PBE2PARAM),
ASN1_ITEM_ref(PBEPARAM),
ASN1_ITEM_ref(PBKDF2PARAM),
ASN1_ITEM_ref(PKCS12),
ASN1_ITEM_ref(PKCS12_AUTHSAFES),
ASN1_ITEM_ref(PKCS12_BAGS),
ASN1_ITEM_ref(PKCS12_MAC_DATA),
ASN1_ITEM_ref(PKCS12_SAFEBAG),
ASN1_ITEM_ref(PKCS12_SAFEBAGS),
ASN1_ITEM_ref(PKCS7),
ASN1_ITEM_ref(PKCS7_ATTR_SIGN),
ASN1_ITEM_ref(PKCS7_ATTR_VERIFY),
ASN1_ITEM_ref(PKCS7_DIGEST),
ASN1_ITEM_ref(PKCS7_ENC_CONTENT),
ASN1_ITEM_ref(PKCS7_ENCRYPT),
ASN1_ITEM_ref(PKCS7_ENVELOPE),
ASN1_ITEM_ref(PKCS7_ISSUER_AND_SERIAL),
ASN1_ITEM_ref(PKCS7_RECIP_INFO),
ASN1_ITEM_ref(PKCS7_SIGNED),
ASN1_ITEM_ref(PKCS7_SIGN_ENVELOPE),
ASN1_ITEM_ref(PKCS7_SIGNER_INFO),
ASN1_ITEM_ref(PKCS8_PRIV_KEY_INFO),
ASN1_ITEM_ref(PKEY_USAGE_PERIOD),
ASN1_ITEM_ref(POLICY_CONSTRAINTS),
ASN1_ITEM_ref(POLICYINFO),
ASN1_ITEM_ref(POLICY_MAPPING),
ASN1_ITEM_ref(POLICY_MAPPINGS),
ASN1_ITEM_ref(POLICYQUALINFO),
ASN1_ITEM_ref(PROXY_CERT_INFO_EXTENSION),
ASN1_ITEM_ref(PROXY_POLICY),
ASN1_ITEM_ref(RSA_OAEP_PARAMS),
ASN1_ITEM_ref(RSA_PSS_PARAMS),
#ifndef OPENSSL_NO_DEPRECATED_3_0
ASN1_ITEM_ref(RSAPrivateKey),
ASN1_ITEM_ref(RSAPublicKey),
#endif
ASN1_ITEM_ref(SXNET),
ASN1_ITEM_ref(SXNETID),
ASN1_ITEM_ref(USERNOTICE),
ASN1_ITEM_ref(X509),
ASN1_ITEM_ref(X509_ALGOR),
ASN1_ITEM_ref(X509_ALGORS),
ASN1_ITEM_ref(X509_ATTRIBUTE),
ASN1_ITEM_ref(X509_CERT_AUX),
ASN1_ITEM_ref(X509_CINF),
ASN1_ITEM_ref(X509_CRL),
ASN1_ITEM_ref(X509_CRL_INFO),
ASN1_ITEM_ref(X509_EXTENSION),
ASN1_ITEM_ref(X509_EXTENSIONS),
ASN1_ITEM_ref(X509_NAME),
ASN1_ITEM_ref(X509_NAME_ENTRY),
ASN1_ITEM_ref(X509_PUBKEY),
ASN1_ITEM_ref(X509_REQ),
ASN1_ITEM_ref(X509_REQ_INFO),
ASN1_ITEM_ref(X509_REVOKED),
ASN1_ITEM_ref(X509_SIG),
ASN1_ITEM_ref(X509_VAL),
#ifndef OPENSSL_NO_DEPRECATED_3_0
ASN1_ITEM_ref(ZLONG),
#endif
ASN1_ITEM_ref(INT32),
ASN1_ITEM_ref(ZINT32),
ASN1_ITEM_ref(UINT32),
ASN1_ITEM_ref(ZUINT32),
ASN1_ITEM_ref(INT64),
ASN1_ITEM_ref(ZINT64),
ASN1_ITEM_ref(UINT64),
ASN1_ITEM_ref(ZUINT64),
NULL
};
static ASN1_PCTX *pctx;
#define DO_TEST(TYPE, D2I, I2D, PRINT) { \
const unsigned char *p = buf; \
unsigned char *der = NULL; \
TYPE *type = D2I(NULL, &p, len); \
\
if (type != NULL) { \
int len2; \
BIO *bio = BIO_new(BIO_s_null()); \
\
if (bio != NULL) { \
PRINT(bio, type); \
BIO_free(bio); \
} \
len2 = I2D(type, &der); \
if (len2 != 0) {} \
OPENSSL_free(der); \
TYPE ## _free(type); \
} \
}
#define DO_TEST_PRINT_OFFSET(TYPE, D2I, I2D, PRINT) { \
const unsigned char *p = buf; \
unsigned char *der = NULL; \
TYPE *type = D2I(NULL, &p, len); \
\
if (type != NULL) { \
BIO *bio = BIO_new(BIO_s_null()); \
\
if (bio != NULL) { \
PRINT(bio, type, 0); \
BIO_free(bio); \
} \
I2D(type, &der); \
OPENSSL_free(der); \
TYPE ## _free(type); \
} \
}
#define DO_TEST_PRINT_PCTX(TYPE, D2I, I2D, PRINT) { \
const unsigned char *p = buf; \
unsigned char *der = NULL; \
TYPE *type = D2I(NULL, &p, len); \
\
if (type != NULL) { \
BIO *bio = BIO_new(BIO_s_null()); \
\
if (bio != NULL) { \
PRINT(bio, type, 0, pctx); \
BIO_free(bio); \
} \
I2D(type, &der); \
OPENSSL_free(der); \
TYPE ## _free(type); \
} \
}
#define DO_TEST_NO_PRINT(TYPE, D2I, I2D) { \
const unsigned char *p = buf; \
unsigned char *der = NULL; \
TYPE *type = D2I(NULL, &p, len); \
\
if (type != NULL) { \
BIO *bio = BIO_new(BIO_s_null()); \
\
BIO_free(bio); \
I2D(type, &der); \
OPENSSL_free(der); \
TYPE ## _free(type); \
} \
}
int FuzzerInitialize(int *argc, char ***argv)
{
FuzzerSetRand();
pctx = ASN1_PCTX_new();
ASN1_PCTX_set_flags(pctx, ASN1_PCTX_FLAGS_SHOW_ABSENT |
ASN1_PCTX_FLAGS_SHOW_SEQUENCE | ASN1_PCTX_FLAGS_SHOW_SSOF |
ASN1_PCTX_FLAGS_SHOW_TYPE | ASN1_PCTX_FLAGS_SHOW_FIELD_STRUCT_NAME);
ASN1_PCTX_set_str_flags(pctx, ASN1_STRFLGS_UTF8_CONVERT |
ASN1_STRFLGS_SHOW_TYPE | ASN1_STRFLGS_DUMP_ALL);
OPENSSL_init_crypto(OPENSSL_INIT_LOAD_CRYPTO_STRINGS, NULL);
OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS, NULL);
ERR_clear_error();
CRYPTO_free_ex_index(0, -1);
return 1;
}
int FuzzerTestOneInput(const uint8_t *buf, size_t len)
{
int n;
for (n = 0; item_type[n] != NULL; ++n) {
const uint8_t *b = buf;
unsigned char *der = NULL;
const ASN1_ITEM *i = ASN1_ITEM_ptr(item_type[n]);
ASN1_VALUE *o = ASN1_item_d2i(NULL, &b, len, i);
if (o != NULL) {
- BIO *bio = BIO_new(BIO_s_null());
- if (bio != NULL) {
- ASN1_item_print(bio, o, 4, i, pctx);
- BIO_free(bio);
+ /*
+ * Don't print excessively long output to prevent spurious fuzzer
+ * timeouts.
+ */
+ if (b - buf < 10000) {
+ BIO *bio = BIO_new(BIO_s_null());
+ if (bio != NULL) {
+ ASN1_item_print(bio, o, 4, i, pctx);
+ BIO_free(bio);
+ }
}
if (ASN1_item_i2d(o, &der, i) > 0) {
OPENSSL_free(der);
}
ASN1_item_free(o, i);
}
}
#ifndef OPENSSL_NO_TS
DO_TEST(TS_REQ, d2i_TS_REQ, i2d_TS_REQ, TS_REQ_print_bio);
DO_TEST(TS_MSG_IMPRINT, d2i_TS_MSG_IMPRINT, i2d_TS_MSG_IMPRINT, TS_MSG_IMPRINT_print_bio);
DO_TEST(TS_RESP, d2i_TS_RESP, i2d_TS_RESP, TS_RESP_print_bio);
DO_TEST(TS_STATUS_INFO, d2i_TS_STATUS_INFO, i2d_TS_STATUS_INFO, TS_STATUS_INFO_print_bio);
DO_TEST(TS_TST_INFO, d2i_TS_TST_INFO, i2d_TS_TST_INFO, TS_TST_INFO_print_bio);
DO_TEST_NO_PRINT(TS_ACCURACY, d2i_TS_ACCURACY, i2d_TS_ACCURACY);
#endif
DO_TEST_NO_PRINT(ESS_ISSUER_SERIAL, d2i_ESS_ISSUER_SERIAL, i2d_ESS_ISSUER_SERIAL);
DO_TEST_NO_PRINT(ESS_CERT_ID, d2i_ESS_CERT_ID, i2d_ESS_CERT_ID);
DO_TEST_NO_PRINT(ESS_SIGNING_CERT, d2i_ESS_SIGNING_CERT, i2d_ESS_SIGNING_CERT);
DO_TEST_NO_PRINT(ESS_CERT_ID_V2, d2i_ESS_CERT_ID_V2, i2d_ESS_CERT_ID_V2);
DO_TEST_NO_PRINT(ESS_SIGNING_CERT_V2, d2i_ESS_SIGNING_CERT_V2, i2d_ESS_SIGNING_CERT_V2);
#if !defined(OPENSSL_NO_DH) && !defined(OPENSSL_NO_DEPRECATED_3_0)
DO_TEST_NO_PRINT(DH, d2i_DHparams, i2d_DHparams);
DO_TEST_NO_PRINT(DH, d2i_DHxparams, i2d_DHxparams);
#endif
#ifndef OPENSSL_NO_DSA
DO_TEST_NO_PRINT(DSA_SIG, d2i_DSA_SIG, i2d_DSA_SIG);
# ifndef OPENSSL_NO_DEPRECATED_3_0
DO_TEST_NO_PRINT(DSA, d2i_DSAPrivateKey, i2d_DSAPrivateKey);
DO_TEST_NO_PRINT(DSA, d2i_DSAPublicKey, i2d_DSAPublicKey);
DO_TEST_NO_PRINT(DSA, d2i_DSAparams, i2d_DSAparams);
# endif
#endif
#ifndef OPENSSL_NO_DEPRECATED_3_0
DO_TEST_NO_PRINT(RSA, d2i_RSAPublicKey, i2d_RSAPublicKey);
#endif
#ifndef OPENSSL_NO_EC
# ifndef OPENSSL_NO_DEPRECATED_3_0
DO_TEST_PRINT_OFFSET(EC_GROUP, d2i_ECPKParameters, i2d_ECPKParameters, ECPKParameters_print);
DO_TEST_PRINT_OFFSET(EC_KEY, d2i_ECPrivateKey, i2d_ECPrivateKey, EC_KEY_print);
DO_TEST(EC_KEY, d2i_ECParameters, i2d_ECParameters, ECParameters_print);
DO_TEST_NO_PRINT(ECDSA_SIG, d2i_ECDSA_SIG, i2d_ECDSA_SIG);
# endif
#endif
DO_TEST_PRINT_PCTX(EVP_PKEY, d2i_AutoPrivateKey, i2d_PrivateKey, EVP_PKEY_print_private);
DO_TEST(SSL_SESSION, d2i_SSL_SESSION, i2d_SSL_SESSION, SSL_SESSION_print);
ERR_clear_error();
return 0;
}
void FuzzerCleanup(void)
{
ASN1_PCTX_free(pctx);
FuzzerClearRand();
}
diff --git a/crypto/openssl/include/crypto/bn.h b/crypto/openssl/include/crypto/bn.h
index fd1c09d997de..4cc23bd146fe 100644
--- a/crypto/openssl/include/crypto/bn.h
+++ b/crypto/openssl/include/crypto/bn.h
@@ -1,117 +1,125 @@
/*
- * Copyright 2014-2023 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2014-2024 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#ifndef OSSL_CRYPTO_BN_H
# define OSSL_CRYPTO_BN_H
# pragma once
# include <openssl/bn.h>
# include <limits.h>
BIGNUM *bn_wexpand(BIGNUM *a, int words);
BIGNUM *bn_expand2(BIGNUM *a, int words);
void bn_correct_top(BIGNUM *a);
/*
* Determine the modified width-(w+1) Non-Adjacent Form (wNAF) of 'scalar'.
* This is an array r[] of values that are either zero or odd with an
* absolute value less than 2^w satisfying scalar = \sum_j r[j]*2^j where at
* most one of any w+1 consecutive digits is non-zero with the exception that
* the most significant digit may be only w-1 zeros away from that next
* non-zero digit.
*/
signed char *bn_compute_wNAF(const BIGNUM *scalar, int w, size_t *ret_len);
int bn_get_top(const BIGNUM *a);
int bn_get_dmax(const BIGNUM *a);
/* Set all words to zero */
void bn_set_all_zero(BIGNUM *a);
/*
* Copy the internal BIGNUM words into out which holds size elements (and size
* must be bigger than top)
*/
int bn_copy_words(BN_ULONG *out, const BIGNUM *in, int size);
BN_ULONG *bn_get_words(const BIGNUM *a);
/*
* Set the internal data words in a to point to words which contains size
* elements. The BN_FLG_STATIC_DATA flag is set
*/
void bn_set_static_words(BIGNUM *a, const BN_ULONG *words, int size);
/*
* Copy words into the BIGNUM |a|, reallocating space as necessary.
* The negative flag of |a| is not modified.
* Returns 1 on success and 0 on failure.
*/
/*
* |num_words| is int because bn_expand2 takes an int. This is an internal
* function so we simply trust callers not to pass negative values.
*/
int bn_set_words(BIGNUM *a, const BN_ULONG *words, int num_words);
/*
* Some BIGNUM functions assume most significant limb to be non-zero, which
* is customarily arranged by bn_correct_top. Output from below functions
* is not processed with bn_correct_top, and for this reason it may not be
* returned out of public API. It may only be passed internally into other
* functions known to support non-minimal or zero-padded BIGNUMs. Even
* though the goal is to facilitate constant-time-ness, not each subroutine
* is constant-time by itself. They all have pre-conditions, consult source
* code...
*/
int bn_mul_mont_fixed_top(BIGNUM *r, const BIGNUM *a, const BIGNUM *b,
BN_MONT_CTX *mont, BN_CTX *ctx);
int bn_to_mont_fixed_top(BIGNUM *r, const BIGNUM *a, BN_MONT_CTX *mont,
BN_CTX *ctx);
int bn_from_mont_fixed_top(BIGNUM *r, const BIGNUM *a, BN_MONT_CTX *mont,
BN_CTX *ctx);
int bn_mod_add_fixed_top(BIGNUM *r, const BIGNUM *a, const BIGNUM *b,
const BIGNUM *m);
int bn_mod_sub_fixed_top(BIGNUM *r, const BIGNUM *a, const BIGNUM *b,
const BIGNUM *m);
int bn_mul_fixed_top(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, BN_CTX *ctx);
int bn_sqr_fixed_top(BIGNUM *r, const BIGNUM *a, BN_CTX *ctx);
int bn_lshift_fixed_top(BIGNUM *r, const BIGNUM *a, int n);
int bn_rshift_fixed_top(BIGNUM *r, const BIGNUM *a, int n);
int bn_div_fixed_top(BIGNUM *dv, BIGNUM *rem, const BIGNUM *m,
const BIGNUM *d, BN_CTX *ctx);
+int ossl_bn_mask_bits_fixed_top(BIGNUM *a, int n);
+int ossl_bn_is_word_fixed_top(const BIGNUM *a, BN_ULONG w);
+int ossl_bn_priv_rand_range_fixed_top(BIGNUM *r, const BIGNUM *range,
+ unsigned int strength, BN_CTX *ctx);
+int ossl_bn_gen_dsa_nonce_fixed_top(BIGNUM *out, const BIGNUM *range,
+ const BIGNUM *priv,
+ const unsigned char *message,
+ size_t message_len, BN_CTX *ctx);
#define BN_PRIMETEST_COMPOSITE 0
#define BN_PRIMETEST_COMPOSITE_WITH_FACTOR 1
#define BN_PRIMETEST_COMPOSITE_NOT_POWER_OF_PRIME 2
#define BN_PRIMETEST_PROBABLY_PRIME 3
int ossl_bn_miller_rabin_is_prime(const BIGNUM *w, int iterations, BN_CTX *ctx,
BN_GENCB *cb, int enhanced, int *status);
const BIGNUM *ossl_bn_get0_small_factors(void);
int ossl_bn_rsa_fips186_4_gen_prob_primes(BIGNUM *p, BIGNUM *Xpout,
BIGNUM *p1, BIGNUM *p2,
const BIGNUM *Xp, const BIGNUM *Xp1,
const BIGNUM *Xp2, int nlen,
const BIGNUM *e, BN_CTX *ctx,
BN_GENCB *cb);
int ossl_bn_rsa_fips186_4_derive_prime(BIGNUM *Y, BIGNUM *X, const BIGNUM *Xin,
const BIGNUM *r1, const BIGNUM *r2,
int nlen, const BIGNUM *e, BN_CTX *ctx,
BN_GENCB *cb);
OSSL_LIB_CTX *ossl_bn_get_libctx(BN_CTX *ctx);
extern const BIGNUM ossl_bn_inv_sqrt_2;
#endif
diff --git a/crypto/openssl/include/internal/constant_time.h b/crypto/openssl/include/internal/constant_time.h
index 0ed6f823c11e..2b49afe1ea2a 100644
--- a/crypto/openssl/include/internal/constant_time.h
+++ b/crypto/openssl/include/internal/constant_time.h
@@ -1,421 +1,444 @@
/*
- * Copyright 2014-2021 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2014-2024 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_CONSTANT_TIME_H
# define OSSL_INTERNAL_CONSTANT_TIME_H
# pragma once
# include <stdlib.h>
# include <string.h>
# include <openssl/e_os2.h> /* For 'ossl_inline' */
/*-
* The boolean methods return a bitmask of all ones (0xff...f) for true
* and 0 for false. This is useful for choosing a value based on the result
* of a conditional in constant time. For example,
* if (a < b) {
* c = a;
* } else {
* c = b;
* }
* can be written as
* unsigned int lt = constant_time_lt(a, b);
* c = constant_time_select(lt, a, b);
*/
/* Returns the given value with the MSB copied to all the other bits. */
static ossl_inline unsigned int constant_time_msb(unsigned int a);
/* Convenience method for uint32_t. */
static ossl_inline uint32_t constant_time_msb_32(uint32_t a);
/* Convenience method for uint64_t. */
static ossl_inline uint64_t constant_time_msb_64(uint64_t a);
/* Returns 0xff..f if a < b and 0 otherwise. */
static ossl_inline unsigned int constant_time_lt(unsigned int a,
unsigned int b);
/* Convenience method for getting an 8-bit mask. */
static ossl_inline unsigned char constant_time_lt_8(unsigned int a,
unsigned int b);
/* Convenience method for uint64_t. */
static ossl_inline uint64_t constant_time_lt_64(uint64_t a, uint64_t b);
/* Returns 0xff..f if a >= b and 0 otherwise. */
static ossl_inline unsigned int constant_time_ge(unsigned int a,
unsigned int b);
/* Convenience method for getting an 8-bit mask. */
static ossl_inline unsigned char constant_time_ge_8(unsigned int a,
unsigned int b);
/* Returns 0xff..f if a == 0 and 0 otherwise. */
static ossl_inline unsigned int constant_time_is_zero(unsigned int a);
/* Convenience method for getting an 8-bit mask. */
static ossl_inline unsigned char constant_time_is_zero_8(unsigned int a);
/* Convenience method for getting a 32-bit mask. */
static ossl_inline uint32_t constant_time_is_zero_32(uint32_t a);
/* Returns 0xff..f if a == b and 0 otherwise. */
static ossl_inline unsigned int constant_time_eq(unsigned int a,
unsigned int b);
/* Convenience method for getting an 8-bit mask. */
static ossl_inline unsigned char constant_time_eq_8(unsigned int a,
unsigned int b);
/* Signed integers. */
static ossl_inline unsigned int constant_time_eq_int(int a, int b);
/* Convenience method for getting an 8-bit mask. */
static ossl_inline unsigned char constant_time_eq_int_8(int a, int b);
/*-
* Returns (mask & a) | (~mask & b).
*
* When |mask| is all 1s or all 0s (as returned by the methods above),
* the select methods return either |a| (if |mask| is nonzero) or |b|
* (if |mask| is zero).
*/
static ossl_inline unsigned int constant_time_select(unsigned int mask,
unsigned int a,
unsigned int b);
/* Convenience method for unsigned chars. */
static ossl_inline unsigned char constant_time_select_8(unsigned char mask,
unsigned char a,
unsigned char b);
/* Convenience method for uint32_t. */
static ossl_inline uint32_t constant_time_select_32(uint32_t mask, uint32_t a,
uint32_t b);
/* Convenience method for uint64_t. */
static ossl_inline uint64_t constant_time_select_64(uint64_t mask, uint64_t a,
uint64_t b);
/* Convenience method for signed integers. */
static ossl_inline int constant_time_select_int(unsigned int mask, int a,
int b);
static ossl_inline unsigned int constant_time_msb(unsigned int a)
{
return 0 - (a >> (sizeof(a) * 8 - 1));
}
static ossl_inline uint32_t constant_time_msb_32(uint32_t a)
{
return 0 - (a >> 31);
}
static ossl_inline uint64_t constant_time_msb_64(uint64_t a)
{
return 0 - (a >> 63);
}
static ossl_inline size_t constant_time_msb_s(size_t a)
{
return 0 - (a >> (sizeof(a) * 8 - 1));
}
static ossl_inline unsigned int constant_time_lt(unsigned int a,
unsigned int b)
{
return constant_time_msb(a ^ ((a ^ b) | ((a - b) ^ b)));
}
static ossl_inline size_t constant_time_lt_s(size_t a, size_t b)
{
return constant_time_msb_s(a ^ ((a ^ b) | ((a - b) ^ b)));
}
static ossl_inline unsigned char constant_time_lt_8(unsigned int a,
unsigned int b)
{
return (unsigned char)constant_time_lt(a, b);
}
static ossl_inline uint64_t constant_time_lt_64(uint64_t a, uint64_t b)
{
return constant_time_msb_64(a ^ ((a ^ b) | ((a - b) ^ b)));
}
+#ifdef BN_ULONG
+static ossl_inline BN_ULONG constant_time_msb_bn(BN_ULONG a)
+{
+ return 0 - (a >> (sizeof(a) * 8 - 1));
+}
+
+static ossl_inline BN_ULONG constant_time_lt_bn(BN_ULONG a, BN_ULONG b)
+{
+ return constant_time_msb_bn(a ^ ((a ^ b) | ((a - b) ^ b)));
+}
+
+static ossl_inline BN_ULONG constant_time_is_zero_bn(BN_ULONG a)
+{
+ return constant_time_msb_bn(~a & (a - 1));
+}
+
+static ossl_inline BN_ULONG constant_time_eq_bn(BN_ULONG a,
+ BN_ULONG b)
+{
+ return constant_time_is_zero_bn(a ^ b);
+}
+#endif
+
static ossl_inline unsigned int constant_time_ge(unsigned int a,
unsigned int b)
{
return ~constant_time_lt(a, b);
}
static ossl_inline size_t constant_time_ge_s(size_t a, size_t b)
{
return ~constant_time_lt_s(a, b);
}
static ossl_inline unsigned char constant_time_ge_8(unsigned int a,
unsigned int b)
{
return (unsigned char)constant_time_ge(a, b);
}
static ossl_inline unsigned char constant_time_ge_8_s(size_t a, size_t b)
{
return (unsigned char)constant_time_ge_s(a, b);
}
static ossl_inline unsigned int constant_time_is_zero(unsigned int a)
{
return constant_time_msb(~a & (a - 1));
}
static ossl_inline size_t constant_time_is_zero_s(size_t a)
{
return constant_time_msb_s(~a & (a - 1));
}
static ossl_inline unsigned char constant_time_is_zero_8(unsigned int a)
{
return (unsigned char)constant_time_is_zero(a);
}
static ossl_inline uint32_t constant_time_is_zero_32(uint32_t a)
{
return constant_time_msb_32(~a & (a - 1));
}
static ossl_inline uint64_t constant_time_is_zero_64(uint64_t a)
{
return constant_time_msb_64(~a & (a - 1));
}
static ossl_inline unsigned int constant_time_eq(unsigned int a,
unsigned int b)
{
return constant_time_is_zero(a ^ b);
}
static ossl_inline size_t constant_time_eq_s(size_t a, size_t b)
{
return constant_time_is_zero_s(a ^ b);
}
static ossl_inline unsigned char constant_time_eq_8(unsigned int a,
unsigned int b)
{
return (unsigned char)constant_time_eq(a, b);
}
static ossl_inline unsigned char constant_time_eq_8_s(size_t a, size_t b)
{
return (unsigned char)constant_time_eq_s(a, b);
}
static ossl_inline unsigned int constant_time_eq_int(int a, int b)
{
return constant_time_eq((unsigned)(a), (unsigned)(b));
}
static ossl_inline unsigned char constant_time_eq_int_8(int a, int b)
{
return constant_time_eq_8((unsigned)(a), (unsigned)(b));
}
/*
* Returns the value unmodified, but avoids optimizations.
* The barriers prevent the compiler from narrowing down the
* possible value range of the mask and ~mask in the select
* statements, which avoids the recognition of the select
* and turning it into a conditional load or branch.
*/
static ossl_inline unsigned int value_barrier(unsigned int a)
{
#if !defined(OPENSSL_NO_ASM) && defined(__GNUC__)
unsigned int r;
__asm__("" : "=r"(r) : "0"(a));
#else
volatile unsigned int r = a;
#endif
return r;
}
/* Convenience method for uint32_t. */
static ossl_inline uint32_t value_barrier_32(uint32_t a)
{
#if !defined(OPENSSL_NO_ASM) && defined(__GNUC__)
uint32_t r;
__asm__("" : "=r"(r) : "0"(a));
#else
volatile uint32_t r = a;
#endif
return r;
}
/* Convenience method for uint64_t. */
static ossl_inline uint64_t value_barrier_64(uint64_t a)
{
#if !defined(OPENSSL_NO_ASM) && defined(__GNUC__)
uint64_t r;
__asm__("" : "=r"(r) : "0"(a));
#else
volatile uint64_t r = a;
#endif
return r;
}
/* Convenience method for size_t. */
static ossl_inline size_t value_barrier_s(size_t a)
{
#if !defined(OPENSSL_NO_ASM) && defined(__GNUC__)
size_t r;
__asm__("" : "=r"(r) : "0"(a));
#else
volatile size_t r = a;
#endif
return r;
}
static ossl_inline unsigned int constant_time_select(unsigned int mask,
unsigned int a,
unsigned int b)
{
return (value_barrier(mask) & a) | (value_barrier(~mask) & b);
}
static ossl_inline size_t constant_time_select_s(size_t mask,
size_t a,
size_t b)
{
return (value_barrier_s(mask) & a) | (value_barrier_s(~mask) & b);
}
static ossl_inline unsigned char constant_time_select_8(unsigned char mask,
unsigned char a,
unsigned char b)
{
return (unsigned char)constant_time_select(mask, a, b);
}
static ossl_inline int constant_time_select_int(unsigned int mask, int a,
int b)
{
return (int)constant_time_select(mask, (unsigned)(a), (unsigned)(b));
}
static ossl_inline int constant_time_select_int_s(size_t mask, int a, int b)
{
return (int)constant_time_select((unsigned)mask, (unsigned)(a),
(unsigned)(b));
}
static ossl_inline uint32_t constant_time_select_32(uint32_t mask, uint32_t a,
uint32_t b)
{
return (value_barrier_32(mask) & a) | (value_barrier_32(~mask) & b);
}
static ossl_inline uint64_t constant_time_select_64(uint64_t mask, uint64_t a,
uint64_t b)
{
return (value_barrier_64(mask) & a) | (value_barrier_64(~mask) & b);
}
/*
* mask must be 0xFFFFFFFF or 0x00000000.
*
* if (mask) {
* uint32_t tmp = *a;
*
* *a = *b;
* *b = tmp;
* }
*/
static ossl_inline void constant_time_cond_swap_32(uint32_t mask, uint32_t *a,
uint32_t *b)
{
uint32_t xor = *a ^ *b;
xor &= mask;
*a ^= xor;
*b ^= xor;
}
/*
* mask must be 0xFFFFFFFF or 0x00000000.
*
* if (mask) {
* uint64_t tmp = *a;
*
* *a = *b;
* *b = tmp;
* }
*/
static ossl_inline void constant_time_cond_swap_64(uint64_t mask, uint64_t *a,
uint64_t *b)
{
uint64_t xor = *a ^ *b;
xor &= mask;
*a ^= xor;
*b ^= xor;
}
/*
* mask must be 0xFF or 0x00.
* "constant time" is per len.
*
* if (mask) {
* unsigned char tmp[len];
*
* memcpy(tmp, a, len);
* memcpy(a, b);
* memcpy(b, tmp);
* }
*/
static ossl_inline void constant_time_cond_swap_buff(unsigned char mask,
unsigned char *a,
unsigned char *b,
size_t len)
{
size_t i;
unsigned char tmp;
for (i = 0; i < len; i++) {
tmp = a[i] ^ b[i];
tmp &= mask;
a[i] ^= tmp;
b[i] ^= tmp;
}
}
/*
* table is a two dimensional array of bytes. Each row has rowsize elements.
* Copies row number idx into out. rowsize and numrows are not considered
* private.
*/
static ossl_inline void constant_time_lookup(void *out,
const void *table,
size_t rowsize,
size_t numrows,
size_t idx)
{
size_t i, j;
const unsigned char *tablec = (const unsigned char *)table;
unsigned char *outc = (unsigned char *)out;
unsigned char mask;
memset(out, 0, rowsize);
/* Note idx may underflow - but that is well defined */
for (i = 0; i < numrows; i++, idx--) {
mask = (unsigned char)constant_time_is_zero_s(idx);
for (j = 0; j < rowsize; j++)
*(outc + j) |= constant_time_select_8(mask, *(tablec++), 0);
}
}
/*
* Expected usage pattern is to unconditionally set error and then
* wipe it if there was no actual error. |clear| is 1 or 0.
*/
void err_clear_last_constant_time(int clear);
#endif /* OSSL_INTERNAL_CONSTANT_TIME_H */
diff --git a/crypto/openssl/include/openssl/sslerr.h b/crypto/openssl/include/openssl/sslerr.h
index b156fc2ffd7b..1e36405e32c0 100644
--- a/crypto/openssl/include/openssl/sslerr.h
+++ b/crypto/openssl/include/openssl/sslerr.h
@@ -1,344 +1,346 @@
/*
* Generated by util/mkerr.pl DO NOT EDIT
- * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 1995-2024 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_SSLERR_H
# define OPENSSL_SSLERR_H
# pragma once
# include <openssl/opensslconf.h>
# include <openssl/symhacks.h>
# include <openssl/sslerr_legacy.h>
/*
* SSL reason codes.
*/
# define SSL_R_APPLICATION_DATA_AFTER_CLOSE_NOTIFY 291
# define SSL_R_APP_DATA_IN_HANDSHAKE 100
# define SSL_R_ATTEMPT_TO_REUSE_SESSION_IN_DIFFERENT_CONTEXT 272
# define SSL_R_AT_LEAST_TLS_1_2_NEEDED_IN_SUITEB_MODE 158
# define SSL_R_BAD_CHANGE_CIPHER_SPEC 103
# define SSL_R_BAD_CIPHER 186
# define SSL_R_BAD_DATA 390
# define SSL_R_BAD_DATA_RETURNED_BY_CALLBACK 106
# define SSL_R_BAD_DECOMPRESSION 107
# define SSL_R_BAD_DH_VALUE 102
# define SSL_R_BAD_DIGEST_LENGTH 111
# define SSL_R_BAD_EARLY_DATA 233
# define SSL_R_BAD_ECC_CERT 304
# define SSL_R_BAD_ECPOINT 306
# define SSL_R_BAD_EXTENSION 110
# define SSL_R_BAD_HANDSHAKE_LENGTH 332
# define SSL_R_BAD_HANDSHAKE_STATE 236
# define SSL_R_BAD_HELLO_REQUEST 105
# define SSL_R_BAD_HRR_VERSION 263
# define SSL_R_BAD_KEY_SHARE 108
# define SSL_R_BAD_KEY_UPDATE 122
# define SSL_R_BAD_LEGACY_VERSION 292
# define SSL_R_BAD_LENGTH 271
# define SSL_R_BAD_PACKET 240
# define SSL_R_BAD_PACKET_LENGTH 115
# define SSL_R_BAD_PROTOCOL_VERSION_NUMBER 116
# define SSL_R_BAD_PSK 219
# define SSL_R_BAD_PSK_IDENTITY 114
# define SSL_R_BAD_RECORD_TYPE 443
# define SSL_R_BAD_RSA_ENCRYPT 119
# define SSL_R_BAD_SIGNATURE 123
# define SSL_R_BAD_SRP_A_LENGTH 347
# define SSL_R_BAD_SRP_PARAMETERS 371
# define SSL_R_BAD_SRTP_MKI_VALUE 352
# define SSL_R_BAD_SRTP_PROTECTION_PROFILE_LIST 353
# define SSL_R_BAD_SSL_FILETYPE 124
# define SSL_R_BAD_VALUE 384
# define SSL_R_BAD_WRITE_RETRY 127
# define SSL_R_BINDER_DOES_NOT_VERIFY 253
# define SSL_R_BIO_NOT_SET 128
# define SSL_R_BLOCK_CIPHER_PAD_IS_WRONG 129
# define SSL_R_BN_LIB 130
# define SSL_R_CALLBACK_FAILED 234
# define SSL_R_CANNOT_CHANGE_CIPHER 109
# define SSL_R_CANNOT_GET_GROUP_NAME 299
# define SSL_R_CA_DN_LENGTH_MISMATCH 131
# define SSL_R_CA_KEY_TOO_SMALL 397
# define SSL_R_CA_MD_TOO_WEAK 398
# define SSL_R_CCS_RECEIVED_EARLY 133
# define SSL_R_CERTIFICATE_VERIFY_FAILED 134
# define SSL_R_CERT_CB_ERROR 377
# define SSL_R_CERT_LENGTH_MISMATCH 135
# define SSL_R_CIPHERSUITE_DIGEST_HAS_CHANGED 218
# define SSL_R_CIPHER_CODE_WRONG_LENGTH 137
# define SSL_R_CLIENTHELLO_TLSEXT 226
# define SSL_R_COMPRESSED_LENGTH_TOO_LONG 140
# define SSL_R_COMPRESSION_DISABLED 343
# define SSL_R_COMPRESSION_FAILURE 141
# define SSL_R_COMPRESSION_ID_NOT_WITHIN_PRIVATE_RANGE 307
# define SSL_R_COMPRESSION_LIBRARY_ERROR 142
# define SSL_R_CONNECTION_TYPE_NOT_SET 144
# define SSL_R_CONTEXT_NOT_DANE_ENABLED 167
# define SSL_R_COOKIE_GEN_CALLBACK_FAILURE 400
# define SSL_R_COOKIE_MISMATCH 308
# define SSL_R_COPY_PARAMETERS_FAILED 296
# define SSL_R_CUSTOM_EXT_HANDLER_ALREADY_INSTALLED 206
# define SSL_R_DANE_ALREADY_ENABLED 172
# define SSL_R_DANE_CANNOT_OVERRIDE_MTYPE_FULL 173
# define SSL_R_DANE_NOT_ENABLED 175
# define SSL_R_DANE_TLSA_BAD_CERTIFICATE 180
# define SSL_R_DANE_TLSA_BAD_CERTIFICATE_USAGE 184
# define SSL_R_DANE_TLSA_BAD_DATA_LENGTH 189
# define SSL_R_DANE_TLSA_BAD_DIGEST_LENGTH 192
# define SSL_R_DANE_TLSA_BAD_MATCHING_TYPE 200
# define SSL_R_DANE_TLSA_BAD_PUBLIC_KEY 201
# define SSL_R_DANE_TLSA_BAD_SELECTOR 202
# define SSL_R_DANE_TLSA_NULL_DATA 203
# define SSL_R_DATA_BETWEEN_CCS_AND_FINISHED 145
# define SSL_R_DATA_LENGTH_TOO_LONG 146
# define SSL_R_DECRYPTION_FAILED 147
# define SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC 281
# define SSL_R_DH_KEY_TOO_SMALL 394
# define SSL_R_DH_PUBLIC_VALUE_LENGTH_IS_WRONG 148
# define SSL_R_DIGEST_CHECK_FAILED 149
# define SSL_R_DTLS_MESSAGE_TOO_BIG 334
# define SSL_R_DUPLICATE_COMPRESSION_ID 309
# define SSL_R_ECC_CERT_NOT_FOR_SIGNING 318
# define SSL_R_ECDH_REQUIRED_FOR_SUITEB_MODE 374
# define SSL_R_EE_KEY_TOO_SMALL 399
# define SSL_R_EMPTY_SRTP_PROTECTION_PROFILE_LIST 354
# define SSL_R_ENCRYPTED_LENGTH_TOO_LONG 150
# define SSL_R_ERROR_IN_RECEIVED_CIPHER_LIST 151
# define SSL_R_ERROR_SETTING_TLSA_BASE_DOMAIN 204
# define SSL_R_EXCEEDS_MAX_FRAGMENT_SIZE 194
# define SSL_R_EXCESSIVE_MESSAGE_SIZE 152
# define SSL_R_EXTENSION_NOT_RECEIVED 279
# define SSL_R_EXTRA_DATA_IN_MESSAGE 153
# define SSL_R_EXT_LENGTH_MISMATCH 163
# define SSL_R_FAILED_TO_INIT_ASYNC 405
# define SSL_R_FRAGMENTED_CLIENT_HELLO 401
# define SSL_R_GOT_A_FIN_BEFORE_A_CCS 154
# define SSL_R_HTTPS_PROXY_REQUEST 155
# define SSL_R_HTTP_REQUEST 156
# define SSL_R_ILLEGAL_POINT_COMPRESSION 162
# define SSL_R_ILLEGAL_SUITEB_DIGEST 380
# define SSL_R_INAPPROPRIATE_FALLBACK 373
# define SSL_R_INCONSISTENT_COMPRESSION 340
# define SSL_R_INCONSISTENT_EARLY_DATA_ALPN 222
# define SSL_R_INCONSISTENT_EARLY_DATA_SNI 231
# define SSL_R_INCONSISTENT_EXTMS 104
# define SSL_R_INSUFFICIENT_SECURITY 241
# define SSL_R_INVALID_ALERT 205
# define SSL_R_INVALID_CCS_MESSAGE 260
# define SSL_R_INVALID_CERTIFICATE_OR_ALG 238
# define SSL_R_INVALID_COMMAND 280
# define SSL_R_INVALID_COMPRESSION_ALGORITHM 341
# define SSL_R_INVALID_CONFIG 283
# define SSL_R_INVALID_CONFIGURATION_NAME 113
# define SSL_R_INVALID_CONTEXT 282
# define SSL_R_INVALID_CT_VALIDATION_TYPE 212
# define SSL_R_INVALID_KEY_UPDATE_TYPE 120
# define SSL_R_INVALID_MAX_EARLY_DATA 174
# define SSL_R_INVALID_NULL_CMD_NAME 385
# define SSL_R_INVALID_SEQUENCE_NUMBER 402
# define SSL_R_INVALID_SERVERINFO_DATA 388
# define SSL_R_INVALID_SESSION_ID 999
# define SSL_R_INVALID_SRP_USERNAME 357
# define SSL_R_INVALID_STATUS_RESPONSE 328
# define SSL_R_INVALID_TICKET_KEYS_LENGTH 325
# define SSL_R_LEGACY_SIGALG_DISALLOWED_OR_UNSUPPORTED 333
# define SSL_R_LENGTH_MISMATCH 159
# define SSL_R_LENGTH_TOO_LONG 404
# define SSL_R_LENGTH_TOO_SHORT 160
# define SSL_R_LIBRARY_BUG 274
# define SSL_R_LIBRARY_HAS_NO_CIPHERS 161
# define SSL_R_MISSING_DSA_SIGNING_CERT 165
# define SSL_R_MISSING_ECDSA_SIGNING_CERT 381
# define SSL_R_MISSING_FATAL 256
# define SSL_R_MISSING_PARAMETERS 290
# define SSL_R_MISSING_PSK_KEX_MODES_EXTENSION 310
# define SSL_R_MISSING_RSA_CERTIFICATE 168
# define SSL_R_MISSING_RSA_ENCRYPTING_CERT 169
# define SSL_R_MISSING_RSA_SIGNING_CERT 170
# define SSL_R_MISSING_SIGALGS_EXTENSION 112
# define SSL_R_MISSING_SIGNING_CERT 221
# define SSL_R_MISSING_SRP_PARAM 358
# define SSL_R_MISSING_SUPPORTED_GROUPS_EXTENSION 209
# define SSL_R_MISSING_TMP_DH_KEY 171
# define SSL_R_MISSING_TMP_ECDH_KEY 311
# define SSL_R_MIXED_HANDSHAKE_AND_NON_HANDSHAKE_DATA 293
# define SSL_R_NOT_ON_RECORD_BOUNDARY 182
# define SSL_R_NOT_REPLACING_CERTIFICATE 289
# define SSL_R_NOT_SERVER 284
# define SSL_R_NO_APPLICATION_PROTOCOL 235
# define SSL_R_NO_CERTIFICATES_RETURNED 176
# define SSL_R_NO_CERTIFICATE_ASSIGNED 177
# define SSL_R_NO_CERTIFICATE_SET 179
# define SSL_R_NO_CHANGE_FOLLOWING_HRR 214
# define SSL_R_NO_CIPHERS_AVAILABLE 181
# define SSL_R_NO_CIPHERS_SPECIFIED 183
# define SSL_R_NO_CIPHER_MATCH 185
# define SSL_R_NO_CLIENT_CERT_METHOD 331
# define SSL_R_NO_COMPRESSION_SPECIFIED 187
# define SSL_R_NO_COOKIE_CALLBACK_SET 287
# define SSL_R_NO_GOST_CERTIFICATE_SENT_BY_PEER 330
# define SSL_R_NO_METHOD_SPECIFIED 188
# define SSL_R_NO_PEM_EXTENSIONS 389
# define SSL_R_NO_PRIVATE_KEY_ASSIGNED 190
# define SSL_R_NO_PROTOCOLS_AVAILABLE 191
# define SSL_R_NO_RENEGOTIATION 339
# define SSL_R_NO_REQUIRED_DIGEST 324
# define SSL_R_NO_SHARED_CIPHER 193
# define SSL_R_NO_SHARED_GROUPS 410
# define SSL_R_NO_SHARED_SIGNATURE_ALGORITHMS 376
# define SSL_R_NO_SRTP_PROFILES 359
# define SSL_R_NO_SUITABLE_DIGEST_ALGORITHM 297
# define SSL_R_NO_SUITABLE_GROUPS 295
# define SSL_R_NO_SUITABLE_KEY_SHARE 101
# define SSL_R_NO_SUITABLE_SIGNATURE_ALGORITHM 118
# define SSL_R_NO_VALID_SCTS 216
# define SSL_R_NO_VERIFY_COOKIE_CALLBACK 403
# define SSL_R_NULL_SSL_CTX 195
# define SSL_R_NULL_SSL_METHOD_PASSED 196
# define SSL_R_OCSP_CALLBACK_FAILURE 305
# define SSL_R_OLD_SESSION_CIPHER_NOT_RETURNED 197
# define SSL_R_OLD_SESSION_COMPRESSION_ALGORITHM_NOT_RETURNED 344
# define SSL_R_OVERFLOW_ERROR 237
# define SSL_R_PACKET_LENGTH_TOO_LONG 198
# define SSL_R_PARSE_TLSEXT 227
# define SSL_R_PATH_TOO_LONG 270
# define SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE 199
# define SSL_R_PEM_NAME_BAD_PREFIX 391
# define SSL_R_PEM_NAME_TOO_SHORT 392
# define SSL_R_PIPELINE_FAILURE 406
# define SSL_R_POST_HANDSHAKE_AUTH_ENCODING_ERR 278
# define SSL_R_PRIVATE_KEY_MISMATCH 288
# define SSL_R_PROTOCOL_IS_SHUTDOWN 207
# define SSL_R_PSK_IDENTITY_NOT_FOUND 223
# define SSL_R_PSK_NO_CLIENT_CB 224
# define SSL_R_PSK_NO_SERVER_CB 225
# define SSL_R_READ_BIO_NOT_SET 211
# define SSL_R_READ_TIMEOUT_EXPIRED 312
# define SSL_R_RECORD_LENGTH_MISMATCH 213
# define SSL_R_RECORD_TOO_SMALL 298
# define SSL_R_RENEGOTIATE_EXT_TOO_LONG 335
# define SSL_R_RENEGOTIATION_ENCODING_ERR 336
# define SSL_R_RENEGOTIATION_MISMATCH 337
# define SSL_R_REQUEST_PENDING 285
# define SSL_R_REQUEST_SENT 286
# define SSL_R_REQUIRED_CIPHER_MISSING 215
# define SSL_R_REQUIRED_COMPRESSION_ALGORITHM_MISSING 342
# define SSL_R_SCSV_RECEIVED_WHEN_RENEGOTIATING 345
# define SSL_R_SCT_VERIFICATION_FAILED 208
# define SSL_R_SERVERHELLO_TLSEXT 275
# define SSL_R_SESSION_ID_CONTEXT_UNINITIALIZED 277
# define SSL_R_SHUTDOWN_WHILE_IN_INIT 407
# define SSL_R_SIGNATURE_ALGORITHMS_ERROR 360
# define SSL_R_SIGNATURE_FOR_NON_SIGNING_CERTIFICATE 220
# define SSL_R_SRP_A_CALC 361
# define SSL_R_SRTP_COULD_NOT_ALLOCATE_PROFILES 362
# define SSL_R_SRTP_PROTECTION_PROFILE_LIST_TOO_LONG 363
# define SSL_R_SRTP_UNKNOWN_PROTECTION_PROFILE 364
# define SSL_R_SSL3_EXT_INVALID_MAX_FRAGMENT_LENGTH 232
# define SSL_R_SSL3_EXT_INVALID_SERVERNAME 319
# define SSL_R_SSL3_EXT_INVALID_SERVERNAME_TYPE 320
# define SSL_R_SSL3_SESSION_ID_TOO_LONG 300
# define SSL_R_SSLV3_ALERT_BAD_CERTIFICATE 1042
# define SSL_R_SSLV3_ALERT_BAD_RECORD_MAC 1020
# define SSL_R_SSLV3_ALERT_CERTIFICATE_EXPIRED 1045
# define SSL_R_SSLV3_ALERT_CERTIFICATE_REVOKED 1044
# define SSL_R_SSLV3_ALERT_CERTIFICATE_UNKNOWN 1046
# define SSL_R_SSLV3_ALERT_DECOMPRESSION_FAILURE 1030
# define SSL_R_SSLV3_ALERT_HANDSHAKE_FAILURE 1040
# define SSL_R_SSLV3_ALERT_ILLEGAL_PARAMETER 1047
# define SSL_R_SSLV3_ALERT_NO_CERTIFICATE 1041
# define SSL_R_SSLV3_ALERT_UNEXPECTED_MESSAGE 1010
# define SSL_R_SSLV3_ALERT_UNSUPPORTED_CERTIFICATE 1043
# define SSL_R_SSL_COMMAND_SECTION_EMPTY 117
# define SSL_R_SSL_COMMAND_SECTION_NOT_FOUND 125
# define SSL_R_SSL_CTX_HAS_NO_DEFAULT_SSL_VERSION 228
# define SSL_R_SSL_HANDSHAKE_FAILURE 229
# define SSL_R_SSL_LIBRARY_HAS_NO_CIPHERS 230
# define SSL_R_SSL_NEGATIVE_LENGTH 372
# define SSL_R_SSL_SECTION_EMPTY 126
# define SSL_R_SSL_SECTION_NOT_FOUND 136
# define SSL_R_SSL_SESSION_ID_CALLBACK_FAILED 301
# define SSL_R_SSL_SESSION_ID_CONFLICT 302
# define SSL_R_SSL_SESSION_ID_CONTEXT_TOO_LONG 273
# define SSL_R_SSL_SESSION_ID_HAS_BAD_LENGTH 303
# define SSL_R_SSL_SESSION_ID_TOO_LONG 408
# define SSL_R_SSL_SESSION_VERSION_MISMATCH 210
# define SSL_R_STILL_IN_INIT 121
# define SSL_R_TLSV13_ALERT_CERTIFICATE_REQUIRED 1116
# define SSL_R_TLSV13_ALERT_MISSING_EXTENSION 1109
# define SSL_R_TLSV1_ALERT_ACCESS_DENIED 1049
# define SSL_R_TLSV1_ALERT_DECODE_ERROR 1050
# define SSL_R_TLSV1_ALERT_DECRYPTION_FAILED 1021
# define SSL_R_TLSV1_ALERT_DECRYPT_ERROR 1051
# define SSL_R_TLSV1_ALERT_EXPORT_RESTRICTION 1060
# define SSL_R_TLSV1_ALERT_INAPPROPRIATE_FALLBACK 1086
# define SSL_R_TLSV1_ALERT_INSUFFICIENT_SECURITY 1071
# define SSL_R_TLSV1_ALERT_INTERNAL_ERROR 1080
+# define SSL_R_TLSV1_ALERT_NO_APPLICATION_PROTOCOL 1120
# define SSL_R_TLSV1_ALERT_NO_RENEGOTIATION 1100
# define SSL_R_TLSV1_ALERT_PROTOCOL_VERSION 1070
# define SSL_R_TLSV1_ALERT_RECORD_OVERFLOW 1022
# define SSL_R_TLSV1_ALERT_UNKNOWN_CA 1048
+# define SSL_R_TLSV1_ALERT_UNKNOWN_PSK_IDENTITY 1115
# define SSL_R_TLSV1_ALERT_USER_CANCELLED 1090
# define SSL_R_TLSV1_BAD_CERTIFICATE_HASH_VALUE 1114
# define SSL_R_TLSV1_BAD_CERTIFICATE_STATUS_RESPONSE 1113
# define SSL_R_TLSV1_CERTIFICATE_UNOBTAINABLE 1111
# define SSL_R_TLSV1_UNRECOGNIZED_NAME 1112
# define SSL_R_TLSV1_UNSUPPORTED_EXTENSION 1110
# define SSL_R_TLS_ILLEGAL_EXPORTER_LABEL 367
# define SSL_R_TLS_INVALID_ECPOINTFORMAT_LIST 157
# define SSL_R_TOO_MANY_KEY_UPDATES 132
# define SSL_R_TOO_MANY_WARN_ALERTS 409
# define SSL_R_TOO_MUCH_EARLY_DATA 164
# define SSL_R_UNABLE_TO_FIND_ECDH_PARAMETERS 314
# define SSL_R_UNABLE_TO_FIND_PUBLIC_KEY_PARAMETERS 239
# define SSL_R_UNABLE_TO_LOAD_SSL3_MD5_ROUTINES 242
# define SSL_R_UNABLE_TO_LOAD_SSL3_SHA1_ROUTINES 243
# define SSL_R_UNEXPECTED_CCS_MESSAGE 262
# define SSL_R_UNEXPECTED_END_OF_EARLY_DATA 178
# define SSL_R_UNEXPECTED_EOF_WHILE_READING 294
# define SSL_R_UNEXPECTED_MESSAGE 244
# define SSL_R_UNEXPECTED_RECORD 245
# define SSL_R_UNINITIALIZED 276
# define SSL_R_UNKNOWN_ALERT_TYPE 246
# define SSL_R_UNKNOWN_CERTIFICATE_TYPE 247
# define SSL_R_UNKNOWN_CIPHER_RETURNED 248
# define SSL_R_UNKNOWN_CIPHER_TYPE 249
# define SSL_R_UNKNOWN_CMD_NAME 386
# define SSL_R_UNKNOWN_COMMAND 139
# define SSL_R_UNKNOWN_DIGEST 368
# define SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE 250
# define SSL_R_UNKNOWN_PKEY_TYPE 251
# define SSL_R_UNKNOWN_PROTOCOL 252
# define SSL_R_UNKNOWN_SSL_VERSION 254
# define SSL_R_UNKNOWN_STATE 255
# define SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED 338
# define SSL_R_UNSOLICITED_EXTENSION 217
# define SSL_R_UNSUPPORTED_COMPRESSION_ALGORITHM 257
# define SSL_R_UNSUPPORTED_ELLIPTIC_CURVE 315
# define SSL_R_UNSUPPORTED_PROTOCOL 258
# define SSL_R_UNSUPPORTED_SSL_VERSION 259
# define SSL_R_UNSUPPORTED_STATUS_TYPE 329
# define SSL_R_USE_SRTP_NOT_NEGOTIATED 369
# define SSL_R_VERSION_TOO_HIGH 166
# define SSL_R_VERSION_TOO_LOW 396
# define SSL_R_WRONG_CERTIFICATE_TYPE 383
# define SSL_R_WRONG_CIPHER_RETURNED 261
# define SSL_R_WRONG_CURVE 378
# define SSL_R_WRONG_SIGNATURE_LENGTH 264
# define SSL_R_WRONG_SIGNATURE_SIZE 265
# define SSL_R_WRONG_SIGNATURE_TYPE 370
# define SSL_R_WRONG_SSL_VERSION 266
# define SSL_R_WRONG_VERSION_NUMBER 267
# define SSL_R_X509_LIB 268
# define SSL_R_X509_VERIFICATION_SETUP_PROBLEMS 269
#endif
diff --git a/crypto/openssl/os-dep/Apple/PrivacyInfo.xcprivacy b/crypto/openssl/os-dep/Apple/PrivacyInfo.xcprivacy
new file mode 100644
index 000000000000..285dd5bebae8
--- /dev/null
+++ b/crypto/openssl/os-dep/Apple/PrivacyInfo.xcprivacy
@@ -0,0 +1,23 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <key>NSPrivacyAccessedAPITypes</key>
+ <array>
+ <dict>
+ <key>NSPrivacyAccessedAPIType</key>
+ <string>NSPrivacyAccessedAPICategoryFileTimestamp</string>
+ <key>NSPrivacyAccessedAPITypeReasons</key>
+ <array>
+ <string>C617.1</string>
+ </array>
+ </dict>
+ </array>
+ <key>NSPrivacyCollectedDataTypes</key>
+ <array/>
+ <key>NSPrivacyTrackingDomains</key>
+ <array/>
+ <key>NSPrivacyTracking</key>
+ <false/>
+</dict>
+</plist>
diff --git a/crypto/openssl/providers/fips-sources.checksums b/crypto/openssl/providers/fips-sources.checksums
index c45b03060675..1a6e37329763 100644
--- a/crypto/openssl/providers/fips-sources.checksums
+++ b/crypto/openssl/providers/fips-sources.checksums
@@ -1,595 +1,595 @@
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
+2eef5f20f1410b48bdaaafa24ded24f56f34c4ca79db1d38fa6bf1b3b19535bf crypto/aes/asm/aes-armv4.pl
+38c2cf8ed3910efd89d8721e1b0763a8fde073b91f6529d251165a0496ef9555 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
-ecbfe826f4c514810c3ee20e265f4f621149694c298554b2682e5de4f029f14f crypto/aes/asm/aes-s390x.pl
-ee4e8cacef972942d2a89c1a83c984df9cad87c61a54383403c5c4864c403ba1 crypto/aes/asm/aes-sparcv9.pl
-2b3b9ac56bf54334d053857a24bdb08592151e8a7a60b89b8195846b7f8ee7b5 crypto/aes/asm/aes-x86_64.pl
-c56c324667b67d726e040d70379efba5b270e2937f403c1b5979018b836903c7 crypto/aes/asm/aesfx-sparcv9.pl
-14359dc32b7f4e5c08227fb9ac8f9232c1287399463b233fec4a2ab0c19f68d1 crypto/aes/asm/aesni-mb-x86_64.pl
-2fe016e8098d1c959b6199ce98e91dfed9a3a543d6b068daf88d4c4c402701ec crypto/aes/asm/aesni-sha1-x86_64.pl
-1d3acabadedb88d1327eeb76201ea9b3f4814f44898018ffae6c73e3f400b89b crypto/aes/asm/aesni-sha256-x86_64.pl
+b4ef595194fe1692e1ab2b561f385da01b277cf004902e8fc99e8ac5389bbd35 crypto/aes/asm/aes-mips.pl
+123c4498c94040b70708fdd911cb08c6411b020b4cf3eb761d6fa22c583c3e6f crypto/aes/asm/aes-parisc.pl
+7a7f2f90791415ef4ffc1ba2a6f6b6fe994bfe0e03d3bf9dab6e428e6874695c crypto/aes/asm/aes-ppc.pl
+d139e5ad69560fd0ffd8aa2e72304e463650cea4c657be7a90e0d1eb782d580a crypto/aes/asm/aes-s390x.pl
+133ba35d77002abcd430414749c4e98c4a319630da898e45ff8dbc5800176df1 crypto/aes/asm/aes-sparcv9.pl
+c98690249d490d23e6fee84f672f1463ffc029427110a4329244a59e4e4aaed8 crypto/aes/asm/aes-x86_64.pl
+7ec99947b47e56595f0b085b8bda0b3113112f694e78b1f71b63ecd1f0fa2c67 crypto/aes/asm/aesfx-sparcv9.pl
+ab94a27e533e164bcf09898a6f6019f43609d51a3b374cf75482dcf2914d464e crypto/aes/asm/aesni-mb-x86_64.pl
+74939261340a0056eb9333fff1c843c8758b9f93de3d94650cd6d2899c6790d8 crypto/aes/asm/aesni-sha1-x86_64.pl
+ce91f0893a2a35fdf4c024ccb0fd8329b30fdbd955f0ae011ab948101ee14951 crypto/aes/asm/aesni-sha256-x86_64.pl
4ff74d4e629a88ef5a9e3d3f5b340fc0a4793d16d7cc7f1b70da62512a856248 crypto/aes/asm/aesni-x86.pl
-c7c6694480bb5319690f94826139a93f5c460ebea6dba101b520a76cb956ec93 crypto/aes/asm/aesni-x86_64.pl
-f3a8f3c960c0f47aaa8fc2633d18b14e7c7feeccc536b0115a08bc58333122b6 crypto/aes/asm/aesp8-ppc.pl
-e397a5781893e97dd90a5a52049633be12a43f379ec5751bca2a6350c39444c8 crypto/aes/asm/aest4-sparcv9.pl
-e3955352a92d56905d63e68937e4758f13190a14a10a3dcb1e5c641c49913c0c crypto/aes/asm/aesv8-armx.pl
-5e8005fdb6641df465bdda20c3476f7176e6bcd63d5073044a0c02a327c7f172 crypto/aes/asm/bsaes-armv7.pl
-0726a2c4c15c27a12b2f7d5e16863df4a1b1daa7b7d9b728f621b2b224d290e6 crypto/aes/asm/bsaes-x86_64.pl
-1ff94d6bf6c8ae4809f64657eb89260fe3cb22137f649d3c73f72cb190258196 crypto/aes/asm/vpaes-armv8.pl
-c3541865cd02d81101cdbab4877ed82772e6980d2c677b9008b38fa1b26d36d4 crypto/aes/asm/vpaes-ppc.pl
+30103cfe3b29d06b34feff48a927e0fa649e9109d35a3db64b09cfeb15426fa2 crypto/aes/asm/aesni-x86_64.pl
+67c73dbf78b5f3c8a436800dc43bf122cd1f0c4fefab357359edaae4fbb27e8e crypto/aes/asm/aesp8-ppc.pl
+a5807ed92ec8a16d123061487c385bf1f65e50878cee95c8e8096844454129f8 crypto/aes/asm/aest4-sparcv9.pl
+d34cf129a8c63e2b77a74117ed4440a4f35408dabd90e21e70eae92d208fa516 crypto/aes/asm/aesv8-armx.pl
+a0b578b7d2787c91013547df07dfa73d8d7a420446dd624c66f7c55159817eb2 crypto/aes/asm/bsaes-armv7.pl
+34accd08242a6bf4a751105f89b0c4de2cd7e54320753587815647abff7124de crypto/aes/asm/bsaes-x86_64.pl
+d9bc047db9b2f54f27fe0d6e2ede9239b4a1f57a14bf89fa3cfba6b836599386 crypto/aes/asm/vpaes-armv8.pl
+516421b1a321b842f879ad69e7b82ae3e1f3efc8288c83bb34d6577996e85787 crypto/aes/asm/vpaes-ppc.pl
3ec24185750a995377516bc2fb2eae8b1c52094c6fff093bff591837fc12d6c3 crypto/aes/asm/vpaes-x86.pl
-060bb6620f50af9afecdf97df051b45b9a50be9daf343dfec1cbb29693ce00a4 crypto/aes/asm/vpaes-x86_64.pl
-2bc67270155e2d6c7da87d9070e005ee79cea18311004907edfd6a078003532a crypto/alphacpuid.pl
-0255a480b78bdcc71f76676f496962a9828eb900f53b7be13be96ae3f67fe6db crypto/arm64cpuid.pl
+47bedbe6a04254eede121e71f11a657b1f1940aee1916bbfc04fa9fb8454f9b8 crypto/aes/asm/vpaes-x86_64.pl
+1c9a2a0e8cee4a1283c74b2e306f46f79890f6d236394de2a80d1994fd411d1d crypto/alphacpuid.pl
+7a37cadacdbecb50304228dfcb087ad7fbb6e31f6ab69c52dd161e79afb2f9ca crypto/arm64cpuid.pl
e0daf54f72dd8fd1bc537d93f34e2a6a887a9ed6027bb33e15a327ef5ff37a42 crypto/armcap.c
-a43f2c1eef16146943745f684f2add7d186924932a47abf7fb0760cba02804e6 crypto/armv4cpuid.pl
+24cc7611225df0e20e414c14e80516c36d48bf99659946e85a876d8757356686 crypto/armv4cpuid.pl
16739d54200fb81ca7835b5814f965022a2ab41589c7787e2697e3ea72d4fafa crypto/asn1_dsa.c
-819c9fd2b0cae9aab81c3cbd1815c2e22949d75f132f649b5883812d0bbaa39a crypto/bn/asm/alpha-mont.pl
-0070595128b250b9ebdebe48ce53d2d27ca16ec4f7c6c8bd169ab2e4a913b2d1 crypto/bn/asm/armv4-gf2m.pl
-8c1c53a725b8a4f92b8a353bfeeb393be94198df41c912e3270f9e654417b250 crypto/bn/asm/armv4-mont.pl
-8d6192337fedb0012764229d600634f8357c3b74fd38bcbfe8b86ddc6ca96ea2 crypto/bn/asm/armv8-mont.pl
+155eff9d747eed808398cfa2af4b276dfc1f9aac8a0f9d801b314ab3f2bf5b56 crypto/bn/asm/alpha-mont.pl
+894cc71b2d783e4e1b54dbef45e9e9280165a2c43981ebdd03282f0e90914928 crypto/bn/asm/armv4-gf2m.pl
+0d2e31dc9cdce02c619adfc9ac720ccf7171384e76a84cdf0e686a805dd7006e crypto/bn/asm/armv4-mont.pl
+d7df31176f725c1ae7241fee8f681fdcf2ab9eb4d3cc6c80d49c2248ae40a56a crypto/bn/asm/armv8-mont.pl
cb4ad7b7461fcb8e2a0d52881158d0211b79544842d4eae36fc566869a2d62c8 crypto/bn/asm/bn-586.pl
-636da7e2a66272a81f9c99e90b36c6f132ad6236c739e8b9f2e7315f30b72edd crypto/bn/asm/c64xplus-gf2m.pl
+10fb73a6cc1bc064ebdcf6d7fe3c7407ea1c28b0d65ad0123046f8b1518fa75a crypto/bn/asm/c64xplus-gf2m.pl
c86664fb974362ee52a454c83c2c4b23fd5b7d64b3c9e23ef1e0dfd130a46ee5 crypto/bn/asm/co-586.pl
-199b9b100f194a2a128c14f2a71be5a04d50d069666d90ca5b69baee1318ccb7 crypto/bn/asm/ia64-mont.pl
+b88190d748056e6a64988bf1a3d19efc4c292e3d338a65f4505cf769a2041077 crypto/bn/asm/ia64-mont.pl
a511aafbf76647a0c83705d4491c898a5584d300aa449fa6166c8803372946eb crypto/bn/asm/ia64.S
-687c5d6606fdfd0e242005972d15db74a9cbac2b8a9a54a56fcb1e99d3880ff3 crypto/bn/asm/mips-mont.pl
-8aca83d2ec45a40af15e59cff1ac2dc33737a3d25f0a0b74d401fa778a5c5eb8 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
+fee42cabeeb87cdf0fa0a6ff3698b2fe98a8a47d10a756052df572097161a8b9 crypto/bn/asm/mips-mont.pl
+b197a8e1be79b8c21f8d26b34b9a282ca42ec4bcd1f3212fde3889747082a1f7 crypto/bn/asm/mips.pl
+13df09cee06a21669137294f92e5c31b4bf05a8035be6800c1cb4403d7cd8290 crypto/bn/asm/parisc-mont.pl
+25c96e545b4981d45557eb14ea5c83aa2d6375ae0df806cb6e6ded2f59ddfed3 crypto/bn/asm/ppc-mont.pl
+1c057083546fa1a3bb1b9819dc5110f5a3b11b7bf5a2fb275012323bd7412403 crypto/bn/asm/ppc.pl
e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 crypto/bn/asm/ppc64-mont-fixed.pl
-a25be64867ab837d93855af232e2bfa71b85b2c6f00e35e620fdc5618187fb6f crypto/bn/asm/ppc64-mont.pl
-231579e532443665020d4d522d9f11713d9c5d5c814b95b434b0f65452e16de4 crypto/bn/asm/rsaz-avx2.pl
-1657600d320ea549b527b2d878a7658533d60d26eeb38f42ea470fc612f9bb53 crypto/bn/asm/rsaz-avx512.pl
-31e84dc905b13e38850071528d3abbfcaf8910bbc8b46f38d19c2b386a5f838e crypto/bn/asm/rsaz-x86_64.pl
-30fedf48dfc5fec1c2044b6c226dd9fc42a92522cc589797a23a79d452bdd2cf crypto/bn/asm/s390x-gf2m.pl
-590388d69d7ac3a0e9af4014792f4f0fdb9552719e8fb48ebc7e5dfca2a491d4 crypto/bn/asm/s390x-mont.pl
+fe9278a2504fb40257637a4718081775c29c4eb81f87a8528e5c85f8d0c6281a crypto/bn/asm/ppc64-mont.pl
+94b2d5cf0faf2efddeb5fb7c575dabc35c1791715cc9299d59a01d9f96cb2d6f crypto/bn/asm/rsaz-avx2.pl
+cd0861a565231f67252e172420f6914fe47a324b35916c29f6304491447fe84c crypto/bn/asm/rsaz-avx512.pl
+c19c717d87dd1ba74f138af05c044c05f5d025e26323637f46ba54a8c871a378 crypto/bn/asm/rsaz-x86_64.pl
+ae26becda9f6d30e9edde8bb89c251a0c40a9a6c879c4cdaec273d8c09af9cd6 crypto/bn/asm/s390x-gf2m.pl
+2700337ef133d6688047a1a8e1c671db06016aae777679923ce2b301896762cf crypto/bn/asm/s390x-mont.pl
aa02597f3dc09cfbc190aedb75711859ba0f3efff87067ebfba1ec78ebee40d7 crypto/bn/asm/s390x.S
-2f7cbc2c3d93b1bbc4953dda38b9ae0ab3a0a8331a0418d94d9b286183736c9e crypto/bn/asm/sparct4-mont.pl
+87d49e83a7df467097fdfc577aa206be9ee622c40fcbbbe5133b35d9783b7816 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
+2ec1497fa06826f7bc574239e425dd8dda0d4a2743e1fe87669ede900291fcb6 crypto/bn/asm/sparcv9-gf2m.pl
+1f490fe184c7a51b2d0646a59e69aa659bfe51270ad21594951b8d7b785bac38 crypto/bn/asm/sparcv9-mont.pl
+277dcb7faa1913b25fd43946c50039bcdd45cb643fd9ddeedd6c207cefa4dd50 crypto/bn/asm/sparcv9a-mont.pl
d404375a21d33396824a3da212d6646d4f3150dd141ee4b4a250aefae3482efb crypto/bn/asm/via-mont.pl
-d24f3e97239c8eed5efc721521b025b7256c15e67a54ea6b5c4cf8f7cd0f89ea crypto/bn/asm/vis3-mont.pl
+d632edf9b9bab7d2cd2d616512a98d15cf4b3ebba7a8e7b83650d654ceb52ecb 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
-259fb8d7f40c0dba46920b1f169d5b37de03b0fda645463d19e3ae2b56de851d crypto/bn/asm/x86_64-mont5.pl
+a5481ca55d94dc7ebdc93173610d38ae2569cea1fe9b5180debe0ab94e455ce1 crypto/bn/asm/x86_64-gf2m.pl
+d8cc080824a72774cb3343a3d50ddf8f41a5b8321203d4c9a764762b62498b96 crypto/bn/asm/x86_64-mont.pl
+03788cb685268e6a50ddfa742ea1fe937570c9b86f2ebc88ee35f3304f67c045 crypto/bn/asm/x86_64-mont5.pl
0ea8185a037a2951bb3d1e590bbbdeac305176d5e618f3e43a04c09733a9de34 crypto/bn/bn_add.c
759c2b9df808b3562fe8b0c7778dbadbf35f261e14fc2d5090d18c35b4181760 crypto/bn/bn_asm.c
14bd5a35c05fcf454854b92fb30b356d7ac618c1eb699dd798f6ad2936d1f5ee crypto/bn/bn_blind.c
7b761d541e3b7f6a3f2b14a09b2b3836a079a845cf67a54db4853e3fd38277c6 crypto/bn/bn_const.c
58b587e20404efa408b31a88ba9c357059ced709bea78c07deb91df7b687db81 crypto/bn/bn_conv.c
2893b6d03d4850d09c15959941b0759bbb50d8c20e873bed088e7cde4e15a65a crypto/bn/bn_ctx.c
d94295953ab91469fe2b9da2a542b8ea11ac38551ecde8f8202b7f645c2dea16 crypto/bn/bn_dh.c
74b63a4515894592b7241fb30b91b21510beaa3d397809e3d74bc9a73e879d18 crypto/bn/bn_div.c
49e59eac540db304ab0ca7bee3ba9d45f89548fff98155561bbdb6602d0aab1d crypto/bn/bn_exp.c
ec2b6e3af6df473a23e7f1a8522f2554cb0eb5d34e3282458c4a66d242278434 crypto/bn/bn_exp2.c
baba7c8ae95af6aa36bc9f4be3a2eed33d500451e568ca4bfc6bc7cb48d4f7ea crypto/bn/bn_gcd.c
5fbb1ab8463cd5544a1d95cf7996b6387ae634984a42256b7a21482ce3ac30a2 crypto/bn/bn_gf2m.c
081e8a6abc23599307dab3b1a92113a65e0bf8717cbc40c970c7469350bc4581 crypto/bn/bn_intern.c
602ed46fbfe12c899dfb7d9d99ff0dbfff96b454fce3cd02817f3e2488dd9192 crypto/bn/bn_kron.c
-bf73a1788a92142963177fb698bc518af9981bbf0ad9784701fbb2462ca10607 crypto/bn/bn_lib.c
+81a4afc27dd1e90c4bfa81c8d385214ce8a2b5884537752944a71ebebd91f4b0 crypto/bn/bn_lib.c
d5beb9fbac2ff5dc3ccbdfa4d1aabca7225c778cff4e3b05b6d6c63e182637f5 crypto/bn/bn_local.h
96f98cdf50087c5b567c31bf2581728623206d79b3f97f5a0c5fdaa0009e6e3c crypto/bn/bn_mod.c
f60f3d49b183b04bcdf9b82f7c961b8c1bcb00e68a2c1166fe9edd95a783356e crypto/bn/bn_mont.c
2da73a76b746a47d8cf8ec8b3e0708c2a34e810abde4b4f1241a49e7f5bb2b60 crypto/bn/bn_mpi.c
76982b18b0803d59b33168b260677e7412970757d3b9513de5c80025290f211d crypto/bn/bn_mul.c
b3677b73ac29aab660c9a549f7af154ca14347fac5cffd43b153a75211f1373f crypto/bn/bn_nist.c
c6760a724d696b7209f0a71f8483fabcf4f081f7e93e2628284c32ef78f69365 crypto/bn/bn_prime.c
c56ad3073108a0de21c5820a48beae2bccdbf5aa8075ec21738878222eb9adc3 crypto/bn/bn_prime.h
-628419eabdb88b265823e43a7a1c88fdfecef79771180836f6089050dc9eadb1 crypto/bn/bn_rand.c
+71186d5bd40d467a919e6449d8aa23d13df88e0c85765d1a165f3eeec6bd33a7 crypto/bn/bn_rand.c
4df8f204c8a06de2b4395be613ca0b9943613c523586e2005876d5c7bb891c75 crypto/bn/bn_recp.c
a5c5c9f99961a5a7f22a3dcdce964c8a330f822be17f08652223a20fed747d0a crypto/bn/bn_rsa_fips186_4.c
-704b0b4723e5c9e9bae5f3e35f9ae8ae8dca3383929e954de9e5169845abfdb2 crypto/bn/bn_shift.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
be27115efd36f0077a3ec26b1ff1f586b0b8969ba05d8ffa34b2ff4badf227bf crypto/bn/rsaz_exp.c
c4d64da1cdc732ea918fccd6a7bb2746b03365dd26f7ba1e74e08c307ca4c58e crypto/bn/rsaz_exp.h
5b82cb8dbf3087c2e671871cb0a92e4039223a51af533a2ee996f3bfd47453a7 crypto/bn/rsaz_exp_x2.c
834db8ff36006e5cb53e09ca6c44290124bd23692f4341ea6563b66fcade4cea crypto/bsearch.c
c39334b70e1394e43f378ae8d31b6e6dc125e4d9181e6536d38e649c4eaadb75 crypto/buffer/buffer.c
-5f43844b5d8665de9ab895f93599150a327d73ec2674bbf7d7c512d30163022d crypto/c64xpluscpuid.pl
+d2bfdfd96b182741d2d51f91478ffcc48491b0da44662bc1c32bc506b3eef1ba crypto/c64xpluscpuid.pl
0e1a41a2d81b5765bca3df448f60bf1fad91e485fe89dd65a7300ffc419e316d crypto/cmac/cmac.c
ff9be205d6d7ff00b0e64508f0eb8d9ec0415fbabc0948d26e308212b3f7b2d8 crypto/context.c
c309d81ea991ddf5be4337afad2fd132169f7443c76f863349d3f3c82f3374e4 crypto/core_algorithm.c
f0fd9eb38bf7f196bbb4d26ce8fdf86d0a4f9db219157e66b2c0ffefb4f42005 crypto/core_fetch.c
799c84d224639c6760c5c28e0e287500a973ca6d0c3d7c1bdcd61b0da4018b3c crypto/core_namemap.c
469e2f53b5f76cd487a60d3d4c44c8fc3a6c4d08405597ba664661ba485508d3 crypto/cpuid.c
71f0fff881eb4c5505fb17662f0ea4bbff24c6858c045a013ad8f786b07da5c4 crypto/cryptlib.c
66dbfc58916709d5a6913777346083247942a8d9458ee9b2bf443f0ea4988d64 crypto/ctype.c
51e56541daea6d4a26d5bae2ea458414063bf08b045bab8df370f6695903e0a5 crypto/der_writer.c
fea3ba4225df97aee90690adf387625b746d8edfdc5af2357ee65151a3d236ac crypto/des/des_enc.c
4971cdc016ee262d81e31f96c1617a33a63c0d90139e440c2ff32a368ee07bbd crypto/des/des_local.h
eeef5722ad56bf1af2ff71681bcc8b8525bc7077e973c98cee920ce9bcc66c81 crypto/des/ecb3_enc.c
04d4cc355200b57f1e7d265a2cebdf094df1eb6e96621b533adddc3d60d31fbe crypto/des/fcrypt_b.c
499513b3ad386fe694c4e04b3c8a9fd4c4e18fc44bb6c4f94d6bf2d9362a3a5a crypto/des/ncbc_enc.c
61926e30dd940616e80936d1c94c5f522daf0d475fb3a40a9e589e78f322901e crypto/des/set_key.c
8344811b14d151f6cd40a7bc45c8f4a1106252b119c1d5e6a589a023f39b107d crypto/des/spr.h
816472a54c273906d0a2b58650e0b9d28cc2c8023d120f0d77160f1fe34c4ca3 crypto/dh/dh_backend.c
24cf9462da6632c52b726041271f8a43dfb3f74414abe460d9cc9c7fd2fd2d7d crypto/dh/dh_check.c
7838e9a35870b0fbcba0aff2f52a2439f64d026e9922bce6e5978c2f22c51120 crypto/dh/dh_gen.c
6b17861887b2535159b9e6ca4f927767dad3e71b6e8be50055bc784f78e92d64 crypto/dh/dh_group_params.c
a5cf5cb464b40f1bc5457dc2a6f2c5ec0f050196603cd2ba7037a23ab64adbf7 crypto/dh/dh_kdf.c
b0c248efc7dad48eaceb939a18cb2592cbfe5b02dd406592e5e590645488b153 crypto/dh/dh_key.c
92345c259ea2a8c09e6d6b069d0942bd6ca4642231580f3e8148ae7a832a1115 crypto/dh/dh_lib.c
8300775d88db0a1aa26a77eb49d6c4f7252e7fee69e1440de4c40edadc9da044 crypto/dh/dh_local.h
bbcf4fc3067ac462a27d7277973180b7dc140df9262a686c7fbe4318ca01f7b8 crypto/dsa/dsa_backend.c
-d7e0d87494e3b3f0898a56785a219e87a2ce14416393ec32d8c0b5f539c7bdbf crypto/dsa/dsa_check.c
+786d6c65ced7ee4e25f5dd7c3150259ec95b6aa321a7590d905757b8139f8230 crypto/dsa/dsa_check.c
ae727bf6319eb57e682de35d75ea357921987953b3688365c710e7fba51c7c58 crypto/dsa/dsa_gen.c
b1de1624e590dbf76f76953802ff162cc8de7c5e2eaba897313c866424d6902b crypto/dsa/dsa_key.c
9f4837c5abe53613a2dc1c5db81d073d4f42bd28b6a2d1e93a2b350d8e25d52a crypto/dsa/dsa_lib.c
f4d52d3897219786c6046bf76abb2f174655c584caa50272bf5d281720df5022 crypto/dsa/dsa_local.h
-c5c252f205482a71efeabe226d51a1c541a6ba2dfa9b8b8a70901087a9dc1667 crypto/dsa/dsa_ossl.c
-d612fd05ff98816ba6cf37f84c0e31443ad9d840ed587a7ab2066027da390325 crypto/dsa/dsa_sign.c
+196dc024873e413d92672c3a9b6c062ed6269250b0da6d41c0da1c03cfec9ef8 crypto/dsa/dsa_ossl.c
+9f501a59c09fc3cb3caafaff25abd44397a94d1062950a4d62e855d2c8986b5a crypto/dsa/dsa_sign.c
53fa10cc87ac63e35df661882852dc46ae68e6fee83b842f1aeefe00b8900ee1 crypto/dsa/dsa_vrf.c
-d9722ad8c6b6e209865a921f3cda831d09bf54a55cacd1edd9802edb6559190a crypto/ec/asm/ecp_nistp521-ppc64.pl
-78ad06b88fcc8689a3a846b82f9ee01546e5734acd1bccf2494e523b71dc74d1 crypto/ec/asm/ecp_nistz256-armv4.pl
-4617351d2de4d0b2abfd358c58050cee00702d0b4c1acca09312ec870e351c7d crypto/ec/asm/ecp_nistz256-armv8.pl
-3715ddd921425f3018741037f01455ed26a840ace08691a800708170a66cf4d2 crypto/ec/asm/ecp_nistz256-ppc64.pl
-cfe7e75a2fddc87a7251684469a8808b9da82b2f5725eafad5806920f89932bd crypto/ec/asm/ecp_nistz256-sparcv9.pl
+786779d7014bc04846832f80638743784a3850c7ee36e4a8062fe8eb7ac31c9b crypto/ec/asm/ecp_nistp521-ppc64.pl
+2e3056ea14fab8b306b0281d6a6f4317a6e86dbf652a79ade726e716cd79bb1e crypto/ec/asm/ecp_nistz256-armv4.pl
+a02edef19d22c5aba196080942111ab0172fc2ebe6d6c40db2beb6a1a2d885c6 crypto/ec/asm/ecp_nistz256-armv8.pl
+729729f8233c95138158f4647b33a36cf175e707ce29563db0eedc811f324ec0 crypto/ec/asm/ecp_nistz256-ppc64.pl
+78a5b172f7c13ae8ac622439ffb9d99b240dbb4bbda3f5c88d1533ae74a445ad crypto/ec/asm/ecp_nistz256-sparcv9.pl
922725c4761cfa567af6ed9ecab04f2c7729ae2595f2fc0fa46dc67879dc87b0 crypto/ec/asm/ecp_nistz256-x86.pl
-ac327475c7ec828d11aa05628b4e3b81ec3b1400f30fe7bec01daf3cf71f2dc9 crypto/ec/asm/ecp_nistz256-x86_64.pl
-cc727533130f5f1a29229929b3d4e8454585d647be25d6344f3c6a0240998368 crypto/ec/asm/x25519-ppc64.pl
-ee897e230964511baa0d1bf95fb938312407a40a88ebe01476879c2763e5f732 crypto/ec/asm/x25519-x86_64.pl
+19ba01af58788e2873ebc1d5b503a76604bec0b9b6296fa794946e141fc945a4 crypto/ec/asm/ecp_nistz256-x86_64.pl
+e806141073aa3792e2748f6feeee6d3017124b3bc6059a9eca0d53a2f5785346 crypto/ec/asm/x25519-ppc64.pl
+a397592dc9fdb13016311db6184b4a3a4f2e198aacb03528f770f30ea4966cc4 crypto/ec/asm/x25519-x86_64.pl
340336e01aa04fcde9bfd56536f90c9bc0ad56a002b6cfa321a1e421f1e93ceb crypto/ec/curve25519.c
9a95ec8366154bb20aeb24f4767a8cbb9953ca0380708eb2f39caca6078cd59e 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
-1689097ae10e4982a8cbe50c2f6eddb03c83436f331f0b67edb98d6b58adc962 crypto/ec/curve448/arch_64/f_impl64.c
+012d4a9c8aed4a66cd3a3eef17d4b4d8f3c6f384449cd057bd292b98e072a283 crypto/ec/curve448/arch_64/f_impl64.c
9b408ec0d43f3b6d714ef5963147e2c2abaddc88633db7dd759193d3c56ed727 crypto/ec/curve448/curve448.c
3c12d90e3fdd59b5d32d63186f1a6f15c75eb73f5035b844a2054356a9459780 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
a1211ed3991af967c728b9f6d0774b9ea098d43cef0631ff88984a2580d2ac4f crypto/ec/curve448/eddsa.c
450946e1cccb81e45e5601b6154e2311666b06e294aab926369995af06d1a328 crypto/ec/curve448/f_generic.c
f6447921a0031fa5beddedd298e82096fb3fdb189b712fab328b61f6beae0c23 crypto/ec/curve448/field.h
2ad8331e893b5db33198e27603891587686c0dfdab29706dc52a7097c5d6f219 crypto/ec/curve448/point_448.h
1ff6e467d72530c71d21c310180d04a24f0a9cb41168fba94b43309ecdda3888 crypto/ec/curve448/scalar.c
3052a044afae2e91b677542fc8b34b3ec9d033e0c6562b0d43098cfb34ab3c9d crypto/ec/curve448/word.h
ae1637d89287c9d22a34bdc0d67f6e01262a2f8dcef9b61369dba8c334f5a80d crypto/ec/ec2_oct.c
6bbbf570ce31f5b579f7e03ec9f8a774663c7c1eb5e475bd31f8fee94a021ffc crypto/ec/ec2_smpl.c
2a71bd8dbe4f427c117d990581709a4ddce07fa8e530794b5a9574fef7c48a0c crypto/ec/ec_asn1.c
69b1b3acb4295f5fff961b339e8ace913176ca63fcedf4af0da4c27171f24f94 crypto/ec/ec_backend.c
86e2becf9b3870979e2abefa1bd318e1a31820d275e2b50e03b17fc287abb20a crypto/ec/ec_check.c
265f911b9d4aada326a2d52cd8a589b556935c8b641598dcd36c6f85d29ce655 crypto/ec/ec_curve.c
8cfd0dcfb5acbf6105691a2d5e2826dba1ff3906707bc9dd6ff9bffcc306468f crypto/ec/ec_cvt.c
95ce53663ab8a1d05bd6f4999f30113e1edce771fb6d218a772fe02de7bdaf4d crypto/ec/ec_key.c
7e40fc646863e0675bbb90f075b809f61bdf0600d8095c8366858d9533ab7700 crypto/ec/ec_kmeth.c
bbd6f618c3dfe425ce0ba1c6710fe59418130e06351881162a590475e6438c44 crypto/ec/ec_lib.c
a8a4690e42b4af60aad822aa8b16196df337906af53ea4db926707f7b596ff27 crypto/ec/ec_local.h
fa901b996eb0e460359cd470843bdb03af7a77a2f1136c5e1d30daef70f3e4d2 crypto/ec/ec_mult.c
129c6b42417bfcf582f4a959cfd65433e6f85b158274f4fa38f9c62615ac9166 crypto/ec/ec_oct.c
c7fba2f2c33f67dafa23caef8c3abd12f5336274a9a07d412b83be0366969ee6 crypto/ec/ecdh_kdf.c
b2cf8f052a5716137da7b0e857ed7a5df5fb513b6d14534199a05e32f2b5a866 crypto/ec/ecdh_ossl.c
-099f7836a31643c58bda3829090ea81fe3d5acaa4c6f7b145d8355a4293d0ccc crypto/ec/ecdsa_ossl.c
+031f99c746ac746c1d4f243dd71c8246b502ff00c1d7ca29f7ca024f0e37e14a 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
f288c23b6f83740956886b2303c64d5a3098c98b530859c3bb4b698c01c1643b crypto/ec/ecp_nistz256.c
51cb98e7e9c241e33261589f0d74103238baaa850e333c61ff1da360e127518a crypto/ec/ecp_oct.c
b4b7c683279454ba41438f50a015cb63ef056ccb9be0168918dfbae00313dc68 crypto/ec/ecp_smpl.c
e2705097cfab64e8d7eb2feba37c3f12b18aec74b135ad0c7f073efccf336d4c crypto/ec/ecx_backend.c
5ee19c357c318b2948ff5d9118a626a6207af2b2eade7d8536051d4a522668d3 crypto/ec/ecx_backend.h
22c44f561ab42d1bd7fd3a3c538ebaba375a704f98056b035e7949d73963c580 crypto/ec/ecx_key.c
28abc295dad8888b5482eb61d31cd78dd80545ecb67dc6f9446a36deb8c40a5e crypto/evp/asymcipher.c
0e75a058dcbbb62cfe39fec6c4a85385dc1a8fce794e4278ce6cebb29763b82b crypto/evp/dh_support.c
1af3872164b4a4757bc7896a24b4d2f8eb2cfb4cba0d872a93db69975693e0a6 crypto/evp/digest.c
838277f228cd3025cf95a9cd435e5606ad1fb5d207bbb057aa29892e6a657c55 crypto/evp/ec_support.c
61df3942752307b7006f09d7628348a0cc9e5555469a3a8862349067a52824b7 crypto/evp/evp_enc.c
62c994fd91dc4a5a1a81dfa9391d6eadae62d3549b2e1b22acb2e7c4cd278f27 crypto/evp/evp_fetch.c
ebe32b2895f7f9767710674352c8949efe93b4bbb5e7b71c27bb5d1822339b46 crypto/evp/evp_lib.c
78f07bf50b6999611a4e9414ab3a20b219b0ab29ca2bd05002d6919a3f67b8eb crypto/evp/evp_local.h
117e679d49d2ae87e49d3c942ff0ce768959e8b9713f84a99025cabba462ccd5 crypto/evp/evp_rand.c
2a128617ec0178e9eeacbe41d75a5530755f41ea524cd124607543cf73456a0c crypto/evp/evp_utils.c
ca8c6cfd30efd53f2e5d1f19bcf09a3a3d0dff6d8947c3943d07a3f4b354aa86 crypto/evp/exchange.c
9e25042581b73e295c059c6217f3ecf809134d518eb79b1b67f34e3ca9145677 crypto/evp/kdf_lib.c
1d72f5506984df1df8606e8c7045f041cf517223e2e1b50c4da8ba8bf1c6c186 crypto/evp/kdf_meth.c
5179624b8e03615dc9caedc9ec16d094fa081495613dd552d71c2c39475bcd83 crypto/evp/kem.c
-5016dd7ef8b4cf7e9ea8465c18d1daa4c8808cb589261cf236058ee75bc868d7 crypto/evp/keymgmt_lib.c
+5cf3e490bf917bd37ae70313d126ae4720432fbec518e4a45e8fa886d5e1689a crypto/evp/keymgmt_lib.c
46ffdc73f8a7fc314dc8988f2751a6e9f9784719f4f162dc4be2450b65b55261 crypto/evp/keymgmt_meth.c
e1a052839b8b70dca20dbac1282d61abd1c415bf4fb6afb56b811e8770d8a2e1 crypto/evp/m_sigver.c
4290c95f63b43688a8da57690d122add5161a6811f9753da1444d28f46739961 crypto/evp/mac_lib.c
e7e8eb5683cd3fbd409df888020dc353b65ac291361829cc4131d5bc86c9fcb3 crypto/evp/mac_meth.c
546d83abecf8973e2d872102a03bde5a46552909fa9e7d1402e1464a27453801 crypto/evp/p_lib.c
3b4228b92eebd04616ecc3ee58684095313dd5ffd1b43cf698a7d6c202cb4622 crypto/evp/pmeth_check.c
1f0e9e94e9b0ad322956521b438b78d44cfcd8eb974e8921d05f9e21ba1c05cf crypto/evp/pmeth_gn.c
76511fba789089a50ef87774817a5482c33633a76a94ecf7b6e8eb915585575d crypto/evp/pmeth_lib.c
-4b2dbddf0f9ceed34c3822347138be754fb194febca1c21c46bcc3a5cce33674 crypto/evp/signature.c
+53058617c153a7676e7ca18c98c23df867a93087d67935907076f3c5bd65c15e crypto/evp/signature.c
f2acfb82aac20251d05a9c252cc6c282bd44e43feac4ac2e0faf68b9a38aef57 crypto/ex_data.c
1c8389c5d49616d491978f0f2b2a54ba82d805ec41c8f75c67853216953cf46a 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
8b72d5a7452b2c15aec6d20027053a83f7df89d49a3b6cfedd77e2b1a29e9fc1 crypto/ffc/ffc_params.c
1a1d227f9a0f427d2ec93bc646c726c9cd49a84a343b4aff0c9c744fa6df05a9 crypto/ffc/ffc_params_generate.c
73dac805abab36cd9df53a421221c71d06a366a4ce479fa788be777f11b47159 crypto/ffc/ffc_params_validate.c
0a4fc92e408b0562cf95c480df93a9907a318a2c92356642903a5d50ed04fd88 crypto/hmac/hmac.c
0395c1b0834f2f4a0ca1756385f4dc1a4ef6fb925b2db3743df7f57256c5166f crypto/hmac/hmac_local.h
0e2d6129504d15ffaf5baa63158ccec0e4b6193a8275333956d8f868ef35127e crypto/ia64cpuid.S
f897493b50f4e9dd4cacb2a7accda6683c10ece602641874cdff1dac7128a751 crypto/initthread.c
7290d8d7ec31a98b17618f218d4f27b393501c7606c814a43db8af1975ad1d10 crypto/lhash/lhash.c
5d49ce00fc06df1b64cbc139ef45c71e0faf08a33f966bc608c82d574521a49e crypto/lhash/lhash_local.h
f866aafae928db1b439ac950dc90744a2397dfe222672fe68b3798396190c8b0 crypto/mem_clr.c
-e14f48d4112c0efe3826b4aa390cc24045a85298cc551ec7f3f36ac4236d7d81 crypto/modes/asm/aes-gcm-armv8_64.pl
-1d686af304f94743038f916125effcb51790c025f3165d8d37b526bbeee781f0 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
-6fb4332ac88113a20915ad4de1931ef88b0114b5379b16e1d967820e1229fbb0 crypto/modes/asm/ghash-s390x.pl
-6af1a05981e1d41e4dea51e58938360e3abc4a4f58e179908242466d032b1a8a crypto/modes/asm/ghash-sparcv9.pl
+78a20112586dbce2b8b6e509a0f46f6a36f2a4acf53c3f3511daf7932a71c391 crypto/modes/asm/aes-gcm-armv8_64.pl
+e482f02932d77d61142548ca4f3c8d5709d88ec14ab84723d82331444c0f57da crypto/modes/asm/aesni-gcm-x86_64.pl
+8fdcb4313fa3a6e541a697525856b9527a06ddf4c794f9393e843f86d67f543c crypto/modes/asm/ghash-alpha.pl
+ace8c376b394439301cecaf468d2a9a8adae21eff1d43191cefbf6765023452d crypto/modes/asm/ghash-armv4.pl
+c22f4945e7de3bd7bfef73447f09983e40a3e4dd0938244d902a1c44c98a8467 crypto/modes/asm/ghash-c64xplus.pl
+315a76491cdba48c88df6549c9efd96b50515400810b185a568b7a871681e03d crypto/modes/asm/ghash-ia64.pl
+25e9f494fcb6eb636c04af2f322736fae8aa339037e199332c96b8c9c3a50afa crypto/modes/asm/ghash-parisc.pl
+f22d5fa646b4fc2db008b6b05ec07c8790d3ad5485d2b10218fd11d0e81030ba crypto/modes/asm/ghash-s390x.pl
+de97107e0c19ff9dd4069f0761eccb00e0b3ced345e1f119ab3b918dd2f9c5f6 crypto/modes/asm/ghash-sparcv9.pl
26f55a57e77f774d17dfba93d757f78edfa3a03f68a71ffa37ccf3bfc468b1e2 crypto/modes/asm/ghash-x86.pl
-72744131007d2389c09665a59a862f5f6bb61b64bd3456e9b400985cb56586b8 crypto/modes/asm/ghash-x86_64.pl
-a4e9f2e496bd9362b17a1b5989aa4682647cefcff6117f0607122a9e11a9dfd9 crypto/modes/asm/ghashp8-ppc.pl
-69a13f423ca74c22543900c14aef4a848e3bc75504b65d2f51c6903aebcc17a7 crypto/modes/asm/ghashv8-armx.pl
+2a0d23a644083e46745c7cb1ca79de393af9336a2e8eab7c85ffeb3b7b1a286f crypto/modes/asm/ghash-x86_64.pl
+b407d9fc6ea65fe1a05edc2d139298d78391f3c165314fa6d56dd375b8e453cd crypto/modes/asm/ghashp8-ppc.pl
+d8436f6dc43a18d49b1a16999ecb513ccf4483f418f75edc01ce68e777c614a9 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
2413852b46ee90bcbb711c0d4fb79fc6b0cac1f837b4df4896a0003935d4211a crypto/modes/gcm128.c
bdf25257b15eca206be4d950d2dd807ca5f058f91f54edbd7a0d312ed83eef8e crypto/modes/ofb128.c
e55a816c356b2d526bc6e40c8b81afa02576e4d44c7d7b6bbe444fb8b01aad41 crypto/modes/wrap128.c
608a04f387be2a509b4d4ad414b7015ab833e56b85020e692e193160f36883a2 crypto/modes/xts128.c
-8aa2504f84a0637b5122f0c963c9d82773ba248bad972ab92be7169995d162b5 crypto/o_str.c
+fecd75b0e1646fb18eeb6b1f528015296157a9bcf97191d0f32b9619aa4f0ffb crypto/o_str.c
8ddbbdf43131c10dcd4428aef0eff2b1e98b0410accada0fad41a4925868beef crypto/packet.c
c698d5166d091d6bb6e9df3c211fe1cc916fd43a26ec844f28f547cd708f9c55 crypto/param_build.c
2a0f272dd553b698e8c6fa57962694ebd6064cb03fe26a60df529205568d315d crypto/param_build_set.c
0e4a5388a92fabbe5a540176c0b4c5ce258b78dc9168ecc2e805352a06aaf0ba crypto/params.c
4fda13f6af05d80b0ab89ec4f5813c274a21a9b4565be958a02d006236cef05c crypto/params_dup.c
b6cbfc8791b31587f32a3f9e4c117549793528ebddc34a361bad1ad8cf8d4c42 crypto/params_from_text.c
97cb7414dc2f165d5849ee3b46cdfff0afb067729435d9c01a747e0ca41e230c crypto/ppccap.c
-3ca43596a7528dec8ff9d1a3cd0d68b62640f84b1d6a8b5e4842cfd0be1133ad crypto/ppccpuid.pl
+826a78afb376cbf1e87f12a2a67eef2ee47059a0fd3f9cba7ce7f035e34f8052 crypto/ppccpuid.pl
b4d34272a0bd1fbe6562022bf7ea6259b6a5a021a48222d415be47ef5ef2a905 crypto/property/defn_cache.c
3c4ade2fed4605e374d85ec1134a98da34e7124f89f44b81a754e8cfe81f14ba crypto/property/property.c
66da4f28d408133fb544b14aeb9ad4913e7c5c67e2826e53f0dc5bf4d8fada26 crypto/property/property_local.h
-37dba5e1f8a2f8cb8a69e491d52386359c9d08a3c7e43ac1c7a989b72b71593c crypto/property/property_parse.c
+b0b382ce829192d2537561cfb0fb5c7afb04305f321f7b3c91441b4ba99b9c92 crypto/property/property_parse.c
a7cefda6a117550e2c76e0f307565ce1e11640b11ba10c80e469a837fd1212a3 crypto/property/property_query.c
065698c8d88a5facc0cbc02a3bd0c642c94687a8c5dd79901c942138b406067d crypto/property/property_string.c
-0b38639ffc696d6037ace06cc0169bb5c411ee1c6bacc1fa18b3abd82000e69f crypto/provider_core.c
+dcc44eba5d01dc248c37ec7b394d48660627c0fa4933d2b93993e1f2ac4b71da crypto/provider_core.c
d0af10d4091b2032aac1b7db80f8c2e14fa7176592716b25b9437ab6b53c0a89 crypto/provider_local.h
5ba2e1c74ddcd0453d02e32612299d1eef18eff8493a7606c15d0dc3738ad1d9 crypto/provider_predefined.c
a5a4472636b8b0095ad8d4acd37e275ad79da1a67ecff7b7b5c3e46c9ebc65b7 crypto/rand/rand_lib.c
fd03b9bb2c23470fa40880ed3bf9847bb17d50592101a78c0ad7a0f121209788 crypto/rand/rand_local.h
f0c8792a99132e0b9c027cfa7370f45594a115934cdc9e8f23bdd64abecaf7fd crypto/rsa/rsa_acvp_test_params.c
5834d7c518ad53ea0dd3db811c0e51568c81cc6c117012030101d29003d0725c crypto/rsa/rsa_backend.c
38a102cd1da1f6ca5a46e6a22f018237964336274385f5c70cbedcaa6997647e crypto/rsa/rsa_chk.c
e32cfa04221a2a3ea33f7bcb93ee51b84cbeba97e94c1fbf6e420b24f97fc9ce crypto/rsa/rsa_crpt.c
e995da1c2e5007bd7f5907f369fe45ed15f4e657143a85078c755bd5e6863d0b crypto/rsa/rsa_gen.c
f2222f270e57559537d3da8abbeb1390bc5376b73dae59d536af6e73eb48bba0 crypto/rsa/rsa_lib.c
a65e85be5269d8cb88e86b3413c978fa8994419a671092cbf104ff1a08fda23b crypto/rsa/rsa_local.h
cf0b75cd54b61b9b9a290ef18d0ddce9fb26a029a54eb3f720d9b25188440f00 crypto/rsa/rsa_mp_names.c
5c60f6e05db82e13178d805deb1947b8eee4a905e6e77523d3b288da70a46bb5 crypto/rsa/rsa_none.c
33de2accc3af530fd0a4758eb83d5e1d994bf49bac4512b01387dbae656e1a7d crypto/rsa/rsa_oaep.c
e05fcad237b7e4e7842ad6e142789fe25d060247283c337c78703be6ecc31ed9 crypto/rsa/rsa_ossl.c
be3f39c1fcb777d6c0122061f9ef735d10a6bee95d67fcc1ca6ae2a664022d2b crypto/rsa/rsa_pk1.c
174a42e156be48927fe6d6bf0d95575619b8e643a99761275bff933bc3449722 crypto/rsa/rsa_pss.c
bf6d300b7e7e9e512a47c5bd1f8713806ae3033a140d83dfae4a16ad58d11170 crypto/rsa/rsa_schemes.c
f01af62704dbf9457e2669c3e7c1d4d740f0388faa49df93611b987a8aa2bf11 crypto/rsa/rsa_sign.c
42d821612b0b0d62f587beb8a0cab8b8d876fedccd6913fec6d2044f8ac52b63 crypto/rsa/rsa_sp800_56b_check.c
3aba73dacebb046faf8d09dc279149b52c629004b524ec33e6d81c8ad0bc31a8 crypto/rsa/rsa_sp800_56b_gen.c
1c1c2aeeb18bf1d69e8f134315b7e50d8f43d30eb1aa5bf42983eec9136a2fdc crypto/rsa/rsa_x931.c
0acbebed48f6242d595c21e3c1ad69da0daa960d62062e8970209deda144f337 crypto/s390xcap.c
-22205848cfb55116ebf999dced8331b575886a609ce29e6886e6267b2310c337 crypto/s390xcpuid.pl
+370d98549d4d98e04b60677b319b85904259359bd9401dd5385aa728278e6626 crypto/s390xcpuid.pl
5fa59240ca885cbc0c1cd026934b226d44fc9c3fdf0c2e7e3a7bd7f4963ca2e5 crypto/self_test_core.c
-05c533fde7fdba0c76103e97d881b7224c8427451b453e2f6413552996063e31 crypto/sha/asm/keccak1600-armv4.pl
-ca3b2b654f9a8c4bc2fa2538c1f19d17acd4a6b9e0df6a4b81df04efa697e67e 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
+58a1a8aeb45421954fa0e4bc87157addb96d086ac4e6aade47da96523cecaa74 crypto/sha/asm/keccak1600-armv4.pl
+d6df6cfdd4e2fee52dc16fd31c91768c45c48c22700c486406d70ecb37e8a8bb crypto/sha/asm/keccak1600-armv8.pl
+81bfb4484d68a3a3e1d704855f76356090867fe10a75db7707b6f7364e8ee8da crypto/sha/asm/keccak1600-avx2.pl
+b7bb35d51d439abbf3810454ccb9bfb5a51e2111eaf389fb95796ad6220a61a0 crypto/sha/asm/keccak1600-avx512.pl
+37365dcc576f99006132271968bab990e2bebdab7f4168c726bd449a2fa51c6a crypto/sha/asm/keccak1600-avx512vl.pl
+2767ae2f379a7a3d0c6dd1471d4d90dd896545b456cb6efd6c230df29e511d70 crypto/sha/asm/keccak1600-c64x.pl
09fc831dd39bd90a701e9b16d9e9987cc215252a22e1e0355f5da6c495fca35a crypto/sha/asm/keccak1600-mmx.pl
-ce4a58129e5ee3ac4c9dfec5ecc010440570ebf7bf869e3e9977f2121a64b27a crypto/sha/asm/keccak1600-ppc64.pl
-a859fc8cb073b2d0012a93f3155a75fb6eb677441462b0de4f8cf8df1445e970 crypto/sha/asm/keccak1600-s390x.pl
-618dcd4891b4064d3b8aa6dcd74bea7ef55f4962a64957b05a05448f6e3e0f17 crypto/sha/asm/keccak1600-x86_64.pl
-831b8b02ab25d78ba6300ce960d96c13439bfba5844e13061e19c4e25cbacc3d crypto/sha/asm/keccak1600p8-ppc.pl
+485dcc50a51705b86c6dc47e6f58d092fec05dfbfcdf4f2785e4235c67cfe742 crypto/sha/asm/keccak1600-ppc64.pl
+49535b60a1a981059a2a9636fdeeab22942d2a15e775b1ec9b5af8937a46aa76 crypto/sha/asm/keccak1600-s390x.pl
+093751655b460d33b2fa6aa4d63a86e902f7f20b2d2a02ed948b78e5698c0dd5 crypto/sha/asm/keccak1600-x86_64.pl
+e0a4a1df82716053a3f01ec0b096c735a0e3c4f6c9d9ec6b2006b37aaac64448 crypto/sha/asm/keccak1600p8-ppc.pl
75d832db9bf0e98e7a5c522169060a6dd276c5118cfb297fc3f1111f55cd4007 crypto/sha/asm/sha1-586.pl
-c96e87d4f5311cd73bbdf499acc03418588be12426d878e157dd67e0099e0219 crypto/sha/asm/sha1-alpha.pl
-4ba6d1c7f12fe76bf39babea966f0a4b7f8769e0c0510cbfc2c46a65dd62d45c crypto/sha/asm/sha1-armv4-large.pl
-efc69cb0d867b7fac6b3fa8985c343d1f984d552bc8e75bbbbace0adf9ee5f15 crypto/sha/asm/sha1-armv8.pl
-11d332b4e058e9fa418d6633316d2e9f9bf520a08b2d933e877bdf38b2edefcf crypto/sha/asm/sha1-c64xplus.pl
-32ff0e701a7b8f25bcfe8477b20795de54f536527bd87d3ce694fd9aaae356d4 crypto/sha/asm/sha1-ia64.pl
-471c27efca685b2a82ad7fefe329ca54172df9f49b9785da6d706b913b75e693 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
-a59a86293e28f5600609dc8af2b39c5285580ae8636520990b000eeeb67bb889 crypto/sha/asm/sha1-x86_64.pl
+8d937771993f04407f5fdcca8ca8565f9f8a4d9c9a8f7bfd4e9f9121dd0450bb crypto/sha/asm/sha1-alpha.pl
+ab7ecd62896324393b1fd9020515b9c0d2b9cc34d559f2efafa35affc9a1485d crypto/sha/asm/sha1-armv4-large.pl
+0acc4e40f793d4d2b960af2baaecc91176ba6742ddd62dca0c33ddc838c58772 crypto/sha/asm/sha1-armv8.pl
+c36f51761e7f59bdd0f61230297fb802542ac5d2d1c6d2b1096ed937131bd583 crypto/sha/asm/sha1-c64xplus.pl
+4ab7c9153b085274a579b388ddff97a4ac7e11585e01811ca95b93a3ec786605 crypto/sha/asm/sha1-ia64.pl
+7a392c5ef7dc19c39d67c7080e0c5214e7a80572c85c022be7e7d4378a5f740d crypto/sha/asm/sha1-mb-x86_64.pl
+c0fea5a0d32001263c8bcf7fc0757aa68c6a7377f20fef8d28708e1b81de5dec crypto/sha/asm/sha1-mips.pl
+f11b75a54c5f42aa3a052de8091bfba47d7cac01920b2fe0ddcb637d4c9d0eb9 crypto/sha/asm/sha1-parisc.pl
+d46ef3fc166271a83144d90985034e2c514bd1020b84ec0fe5427ad593bfeb74 crypto/sha/asm/sha1-ppc.pl
+a48c7d9403fe99fbd4daec60e96eb22058da766ab9e606d084a63613962851a2 crypto/sha/asm/sha1-s390x.pl
+0e2951e0574c64ee055ffddf16ceefdec00823107d60362976605f139ad8ae68 crypto/sha/asm/sha1-sparcv9.pl
+5da48400d4fae85e205e95a2fa368e7bf525e51e274b1dd680dfb48645426c85 crypto/sha/asm/sha1-sparcv9a.pl
+04b73c902d36c28b5a7eab47cb85f743eb9c648ed5936f64f655524a1010a1b5 crypto/sha/asm/sha1-thumb.pl
+f36d7ec7464c932230585a754b91f13cea4cde5a381fc9f798d959256d07910e crypto/sha/asm/sha1-x86_64.pl
c099059ef107f548ea2c2bab64a4eb8c277070ce6d74c4d32bb9808dc19c5fa3 crypto/sha/asm/sha256-586.pl
-b9cee5c5a283f61f601d2dba68a7a76e7aba10bfafffc1a5c4987f9c0aa6f87d crypto/sha/asm/sha256-armv4.pl
-93ddc97651ee3e779144a3c6b3e46a1bc4aa81e75cd7b9df068a2aef8743d25f crypto/sha/asm/sha256-c64xplus.pl
-8be5c5d69733ecb16774aa8410b4bcb3623a9f060d2be103d8aa67bf6e4c5843 crypto/sha/asm/sha256-mb-x86_64.pl
+3a8cf38dd398a7ab1d9c6701fa61c428b07c4431a0041ed3a2ddf937897825c1 crypto/sha/asm/sha256-armv4.pl
+c394bb5b0ff05595a9e6848b6602a0f29f73a79fc006593740f3ca645ad9d316 crypto/sha/asm/sha256-c64xplus.pl
+f33af8e2e2f57b7b63b8c8b35722d7d11ca6ef1f73fb6c4ccebdd3e86912f4b1 crypto/sha/asm/sha256-mb-x86_64.pl
dd82e1311703abb019975fc7b61fb87d67e1ed916dddd065aced051e851114b9 crypto/sha/asm/sha512-586.pl
-8d84164f3cfd53290c0c14bb5655510b7a9238857866328c0604d64b4e76fe21 crypto/sha/asm/sha512-armv4.pl
-dadacb6d66b160913bffb4e1a6c3e5f7be6509b26e2c099701d8d3fdb92c1be0 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
-38e0455fd6a2b93a7a5385379ca92bc6526585ca1eb4af365fac4c78f7285c72 crypto/sha/asm/sha512-s390x.pl
-0611845c52091b0208dd41f22ddef9dd1e68d3d92fa4c4360738b840a6314de6 crypto/sha/asm/sha512-sparcv9.pl
-f64d16c1e5c3fa4a7969de494a8372127502171a517c14be7a1e3a43a7308699 crypto/sha/asm/sha512-x86_64.pl
-8725cabb8d695c576619f19283b034074a3fa0f1c0be952a9dbe9793be15b907 crypto/sha/asm/sha512p8-ppc.pl
+1f9ba79b1d591b7aa37b62382422cb025f5b45784d26cc5790c05cf4eb52b792 crypto/sha/asm/sha512-armv4.pl
+8136196fce18b736f671a4b4945cd4aa4ab25a28c90c6fc9ab31ff771e8e0d9f crypto/sha/asm/sha512-armv8.pl
+5b6796a9978b69fd78ee2ff1adc5cf35d44cad8194a38d1c2aba2023012cf252 crypto/sha/asm/sha512-c64xplus.pl
+e8df660671ba61aa2e8f51358baf5d8ca913093e2ee1a40c9cb46d9c2c0851f6 crypto/sha/asm/sha512-ia64.pl
+525f253ef8051bfb0e344ac2e40688ce359a42707fe360d23a03f522cc88c81a crypto/sha/asm/sha512-mips.pl
+3c3e03529d8514467f8d77c01978348636bb339315feb8041fbde7640565001e crypto/sha/asm/sha512-parisc.pl
+952ef1b10e8bbe3f638cc798b91ab9c5b47b66ed8fe94647b1beec9874f2e71e crypto/sha/asm/sha512-ppc.pl
+193a0ea240264b29dd68a425f604a6da4b18e28838dcf909dd7e711af880f782 crypto/sha/asm/sha512-s390x.pl
+dcb466a1e5938fb64ecb38b0533602192d61334da864ee8dfdcfa12d3cdfa273 crypto/sha/asm/sha512-sparcv9.pl
+bb6503967a58b767a3e73441cfabc77f15c8ac747f377e276d4aa63d05f2c3c4 crypto/sha/asm/sha512-x86_64.pl
+68d2f3b2dccb978ee42640f4fb4d2eae6b74d071017a3eedd9e7cb77762817dc crypto/sha/asm/sha512p8-ppc.pl
57f6cf54b1b5d2cac7a8f622b7b6bd1878f360fff3fa0f02352061c24162ebbb crypto/sha/keccak1600.c
306cacd3f86e5cacaca74c58ef862516515e5c0cafaff48636d537fd84f1c2fb crypto/sha/sha1dgst.c
4d8cf04f5806611e7586aab47fb28165ec1afb00168e2c9876bb36cb5c29bf8b crypto/sha/sha256.c
3d972a11be18bfbfcd45790028635d63548bfe0a2e45d2fc56b6051b759d22f0 crypto/sha/sha3.c
8038a5a97f826f519424db634be5b082b3f7eca3ccb89875ca40fa6bd7dfdcfd crypto/sha/sha512.c
6c6f0e6069ac98e407a5810b84deace2d1396d252c584703bcd154d1a015c3ea crypto/sha/sha_local.h
9ef5a01caccc2eb15f72e367d0424737040ac8018479bbbbce3d216c655765c2 crypto/sparccpuid.S
5056b14a55665ffa342a9a1bb32c1c36886add5d0819869193427f33cee028f7 crypto/sparcv9cap.c
c50c584c55e56347bb43aca4b796b5344d70daece3061f586b79c871c21f5d1a crypto/sparse_array.c
8da78169fa8c09dc3c29c9bf1602b22e88c5eac4815e274ba1864c166e31584b crypto/stack/stack.c
7b4efa594d8d1f3ecbf4605cf54f72fb296a3b1d951bdc69e415aaa08f34e5c8 crypto/threads_lib.c
a41ae93a755e2ec89b3cb5b4932e2b508fdda92ace2e025a2650a6da0e9e972c crypto/threads_none.c
3729e2bd36f945808b578e0d89fac0fcb3114e4fc9381614bcbd8a9869991716 crypto/threads_pthread.c
88423960f0414f6fd41fba4f4c67f9f7260c2741e4788adcd52493e895ec8027 crypto/threads_win.c
-fd6c27cf7c6b5449b17f2b725f4203c4c10207f1973db09fd41571efe5de08fd crypto/x86_64cpuid.pl
+af0af59fe2cb8668a96751f343232d7faa3e7a937beb2bda09ed74fe60b9cb5f crypto/x86_64cpuid.pl
bbec287bb9bf35379885f8f8998b7fd9e8fc22efee9e1b299109af0f33a7ee16 crypto/x86cpuid.pl
-0a9c484f640d96e918921f57f592e82e99ccdbe35d3138d64b10c7af839e9a07 e_os.h
+acbb841170d4d3eb91d969be1c0e4973b1babfd5fcd76440b0628f509f82fd76 e_os.h
6f353dc7c8c4d8f24f7ffbf920668ccb224ebb5810805a7c80d96770cd858005 include/crypto/aes_platform.h
8c6f308c1ca774e6127e325c3b80511dbcdc99631f032694d8db53a5c02364ee include/crypto/asn1_dsa.h
-8ce1b35c6924555ef316c7c51d6c27656869e6da7f513f45b7a7051579e3e54d include/crypto/bn.h
+f6b01cff254311e973361190011cb6aa4d24b3a8c92f54e5191b7e2f669b8745 include/crypto/bn.h
1c46818354d42bd1b1c4e5fdae9e019814936e775fd8c918ca49959c2a6416df include/crypto/bn_conf.h.in
7a43a4898fcc8446065e6c99249bcc14e475716e8c1d40d50408c0ab179520e6 include/crypto/bn_dh.h
e69b2b20fb415e24b970941c84a62b752b5d0175bc68126e467f7cc970495504 include/crypto/cryptlib.h
6c72cfa9e59d276c1debcfd36a0aff277539b43d2272267147fad4165d72747c include/crypto/ctype.h
89693e0a7528a9574e1d2f80644b29e3b895d3684111dd07c18cc5bed28b45b7 include/crypto/des_platform.h
daf508bb7ed5783f1c8c622f0c230e179244dd3f584e1223a19ab95930fbcb4f include/crypto/dh.h
20d99c9a740e4d7d67e23fa4ae4c6a39d114e486c66ad41b65d91a8244cd1dea include/crypto/dsa.h
2ea47c059e84ce9d14cc31f4faf45f64d631de9e2937aa1d7a83de5571c63574 include/crypto/ec.h
edbfae8720502a4708983b60eac72aa04f031059f197ada31627cb5e72812858 include/crypto/ecx.h
9dab9af8b0a657fe5de46375b71aefcad7e98af272b69ed69c7c104e9e057414 include/crypto/evp.h
bbe5e52d84e65449a13e42cd2d6adce59b8ed6e73d6950917aa77dc1f3f5dff6 include/crypto/lhash.h
162812058c69f65a824906193057cd3edeabc22f51a4220aea7cb9064379a9b6 include/crypto/md32_common.h
f12bfc145290444bcc7bf408874bded348e742443c145b8b5bc70ae558d96c31 include/crypto/modes.h
f326212c978576c5346c89ae0336c2428594494b54054f6045b1f1038bfbc004 include/crypto/rand.h
90930fc8788d6e04e57829346e0405293ac7a678c3cef23d0692c742e9586d09 include/crypto/rand_pool.h
306abf9d327a9e63fff2cdef730275abc4d2781254a032b1f370f3428eb5a2ef include/crypto/rsa.h
32f0149ab1d82fddbdfbbc44e3078b4a4cc6936d35187e0f8d02cc0bc19f2401 include/crypto/security_bits.h
0f743762f646656b5480648c05632575fe8acc7506460c63e0fcdf42cf20c08a include/crypto/sha.h
7676b02824b2d68df6bddeb251e9b8a8fa2e35a95dad9a7ebeca53f9ab8d2dad include/crypto/sparse_array.h
7ad02c7de77304c3b298deeb038ab2550cf8b2bce03021994477c6c43dbcf86e include/crypto/types.h
782a83d4e489fd865e2768a20bfa31e78c2071fd0ceeb9eb077276ae2bcc6590 include/internal/bio.h
-92aacb3e49288f91b44f97e41933e88fe455706e1dd21a365683c2ab545db131 include/internal/constant_time.h
+8e984890c7c62cdd6356963f034831831f7167c65096cb4d23bc765d84d2c598 include/internal/constant_time.h
c5bb97f654984130c8b44c09a52395bce0b22985d5dbc9c4d9377d86283f11f8 include/internal/core.h
0b572801dfb8a41cc239e3439f8097a0ad11bbdf5d54811d10ceba3175cf2f17 include/internal/cryptlib.h
9571cfd3d5666749084b354a6d65adee443deeb5713a58c098c7b03bc69dbc63 include/internal/deprecated.h
3325b895d15c0a6341f456a8d866a0f83e80fc8a31a01c34fcfd717715b33075 include/internal/der.h
fd1722d6b79520ee4ac477280d5131eb1b744c3b422fd15f5e737ef966a97c3b include/internal/dso.h
f144daebef828a5bd4416466257a50f06b894e0ce0adf1601aa381f34f25a9e7 include/internal/dsoerr.h
70d3e0d5a1bd8db58dcc57bea4d1c3ed816c735fe0e6b2f4b07073712d2dc5ef include/internal/endian.h
7854b5c1cd786dc01d052204c5b3ea946dc9929590f47ec4c27697387c5b7ce5 include/internal/ffc.h
100053a1bad1a85a98c5b919cf81ace0ee147b2164732963e40474d7b5fbbb99 include/internal/namemap.h
b02701592960eb4608bb83b297eed90184004828c7fc03ea81568062f347623d include/internal/nelem.h
ae41a2fb41bf592bbb47e4855cf4efd9ef85fc11f910a7e195ceef78fb4321dc include/internal/numbers.h
b89cca3b727d4526b459246de11e768a20333555bf3a9ed9a9b8beb2b565dc7f include/internal/packet.h
dd7ddecf30bef3002313e6b776ce34d660931e783b2f6edacf64c7c6e729e688 include/internal/param_build_set.h
d4ac19b28ea61f03383364cfad1e941cac44fc36787d80882c5b76ecc9d34e29 include/internal/property.h
727326afb3d33fdffdf26471e313f27892708318c0934089369e4b28267e2635 include/internal/propertyerr.h
6a899ef3e360c7144d84d3c3dbbd14aa457f5d38b83b13c0be7ec7f372076595 include/internal/provider.h
34432d71c49dc8ee9926218ba78bdcd03c46cee4e966ee20d100e4519d85b064 include/internal/refcount.h
11ee9893f7774c83fcfdee6e0ca593af3d28b779107883553facdbfdae3a68f5 include/internal/sha3.h
494ab5c802716bf38032986674fb094dde927a21752fe395d82e6044d81801d1 include/internal/sizes.h
24f41a1985fa305833c3f58030c494d2563d15fc922cdf3eeb6a7ea8c135a880 include/internal/symhacks.h
640cc6a2aae208073a7f495c08b4c5006a69e8ac1c2d9aaaafd56b0e74d5f859 include/internal/thread_once.h
415b725d7f949a6191ab7bb30b48931bafc01c7aa93607e529fabbc853a4ddc5 include/internal/tlsgroups.h
fc0f9199487ef278b9fd317d1572db3e3fb95e182055f0e49c4d8faf78ed7dd2 include/internal/tsan_assist.h
2b38fb6e65d549aca3b2c76907daf67124f395251c0261dec26faa54da8d6d73 include/openssl/aes.h
98aa2fc5eae9ef2a36d3d0053212696d58893baa083fa1fcf720660fb4bc0a9f include/openssl/asn1.h.in
d4733dcd490b3a2554eaf859d1ea964fe76f7d24f78e42be1094bdad6dee7429 include/openssl/asn1err.h
1550474ee05423896ec4abfb6346f1bc44c7be22329efac9ea25de10e81d549c include/openssl/asn1t.h.in
dbd1501acb0804eec0f2aa7bbac4dbc483cf2b4691c6eb1436461b5ed4685b42 include/openssl/bio.h.in
0a26138aaded05cafe2326e11fdc19b28408e054cfe3dda40d45ef95ce8136b0 include/openssl/bioerr.h
7d1f9880976a926ba6e0cad08e8de6f326aae48d8350b499aa79127f63d4d108 include/openssl/bn.h
9ad8b04764797f5138f01f549ba18b44cf698ffc7fe795fef42c1822d84a6ff4 include/openssl/bnerr.h
93954e6c450716e158948d67f64736a451ea9473d02f3a908f3bc8a96cf049a5 include/openssl/buffer.h
9d48e6cab2ee98ae94d7113e4c65f000d97e125fdb3445642865ace3f34d06ac include/openssl/buffererr.h
8e772c24b051e59d2f65339f54584e3e44165a3eaf997d497faea764990130f5 include/openssl/cmac.h
55aa91482d327d1784484922389e8277bdcdff7a7df27e84200d5c908bd40454 include/openssl/conf.h.in
bb45de4eafdd89c14096e9af9b0aee12b09adcee43b9313a3a373294dec99142 include/openssl/conferr.h
02a1baff7b71a298419c6c5dcb43eaa9cc13e9beeb88c03fb14854b4e84e8862 include/openssl/configuration.h.in
6b3810dac6c9d6f5ee36a10ad6d895a5e4553afdfb9641ce9b7dc5db7eef30b7 include/openssl/conftypes.h
df5e60af861665675e4a00d40d15e36884f940e3379c7b45c9f717eaf1942697 include/openssl/core.h
00110e80b9b4f621c604ea99f05e7a75d3db4721fc2779224e6fa7e52f06e345 include/openssl/core_dispatch.h
cbd9d7855ca3ba4240207fc025c22bbfef7411116446ff63511e336a0559bed0 include/openssl/core_names.h
194f96a30bdc4dab3f65693c09326ef53c54ebfd613c2513d8258a0aa35a6996 include/openssl/crypto.h.in
1d1697bd3e35920ff9eaec23c29472d727a7fc4d108150957f41f6f5ecf80f1a include/openssl/cryptoerr.h
bbc82260cbcadd406091f39b9e3b5ea63146d9a4822623ead16fa12c43ab9fc6 include/openssl/cryptoerr_legacy.h
fa3e6b6c2e6222424b9cd7005e3c5499a2334c831cd5d6a29256ce945be8cb1d include/openssl/des.h
75fba45d6fc66e3aaef216959327157613f08070935aae4a5260e740184f031f include/openssl/dh.h
ab7ba5d7eb18d2ea8abc6862ae2ceaa1fa116a702c2bff617c5ae1651d97b6bc include/openssl/dherr.h
92ae2c907fd56859e3ae28a085071611be5c9245879305cdf8bad027219e64b6 include/openssl/dsa.h
276d1f6e111ba933bc708e6a0670047cbe0d0b67aabe31807abbbc231de4d8cf include/openssl/dsaerr.h
41bf49e64e1c341a8c17778147ddeba35e88dfd7ff131db6210e801ef25a8fd5 include/openssl/e_os2.h
bc9ec2be442a4f49980ba2c63c8f0da701de1f6e23d7db35d781658f833dd7b9 include/openssl/ebcdic.h
33b6321d1c6b7b1621198346946401bb81472054aa236b03c6f22f247248d2ad include/openssl/ec.h
7aa8c5bee779af59d4733f6a50f7f6be39f1eb43409e5b3357440f9a7d0ca115 include/openssl/ecerr.h
61c76ee3f12ed0e42503a56421ca00f1cb9a0f4caa5f9c4421c374bcd45917d7 include/openssl/encoder.h
69dd983f45b8ccd551f084796519446552963a18c52b70470d978b597c81b2dc include/openssl/encodererr.h
c6ee8f17d7252bdd0807a124dc6d50a95c32c04e17688b7c2e061998570b7028 include/openssl/err.h.in
b23bf3e2d0a60fe4d768afbe7aab48b47791e1274ae42b28895255119ae7f61d include/openssl/evp.h
5bd1b5dcd14067a1fe490d49df911002793c0b4f0bd4492cd8f71cfed7bf9f2a include/openssl/evperr.h
5381d96fe867a4ee0ebc09b9e3a262a0d7a27edc5f91dccfb010c7d713cd0820 include/openssl/fips_names.h
b1d41beba560a41383f899a361b786e04f889106fb5960ec831b0af7996c9783 include/openssl/fipskey.h.in
47a088c98ad536ea99f2c6a9333e372507cb61b9bdffb930c586ed52f8f261eb include/openssl/hmac.h
faab8accc9520269dd874126ae164a43526d5784e6280521c7ab3772c02b0a0c include/openssl/kdf.h
c6db6926e90c9efd530a7bdb018be8c62f2c2b3c2f7b90228e9f73b8437dd785 include/openssl/lhash.h.in
fd5c049ac6c3498750fa8f8dcbf88b2a31c02fa62dfe43a33d7b490fb86f61c8 include/openssl/macros.h
9184207c562fd1fa7bd3a4f1fadcb984130561279818f0cdfcf3e9c55be8a7d1 include/openssl/modes.h
7c71200e35f4cc1b4011a4bc14e521e4dc037b9b2d640a74bc30ef334b813de3 include/openssl/obj_mac.h
157797b450215f973eb10be96a04e58048ab9c131ad29427e80d0e37e230ed98 include/openssl/objects.h
d25537af264684dff033dd8ae62b0348f868fcfec4aa51fa8f07bcfa4bd807ad include/openssl/objectserr.h
fe6acd42c3e90db31aaafc2236a7d30ebfa53c4c07ea4d8265064c7fcb951970 include/openssl/opensslconf.h
1bf52d136e94f727a96651c1f48ad040482f35dae152519ccd585efd410b92f0 include/openssl/opensslv.h.in
767d9d7d5051c937a3ce8a268c702902fda93eeaa210a94dfde1f45c23277d20 include/openssl/param_build.h
30085f4d1b4934bb25ffe7aa9a30859966318a1b4d4dcea937c426e90e6e1984 include/openssl/params.h
097615b849375e2903967521f76c570512e5be47b8159fdbcd31e433f8a4cca7 include/openssl/prov_ssl.h
bdadffba7b7b8294c9f7450ce2563ae31145ca0f196f5ce7b8c2f19ed7fba816 include/openssl/proverr.h
b97e8ad49b38683817387596aefec0abd5f4d572643beef48be4f7acba26768d include/openssl/provider.h
7c9b5f479d9b22cfc8db0976dddfc2a1ee6e757b436e01a2b4d2744bcb6d81a5 include/openssl/rand.h
108966f56c82fedff53df76a4aa7861c82be4db1fd1ddafb59dc086ea155831c include/openssl/randerr.h
c1015b77c444a3816d2ea7ad770f1c3b79a1e54887930af6dd662895701f3323 include/openssl/rsa.h
2f339ba2f22b8faa406692289a6e51fdbbb04b03f85cf3ca849835e58211ad23 include/openssl/rsaerr.h
6586f2187991731835353de0ffad0b6b57609b495e53d0f32644491ece629eb2 include/openssl/safestack.h.in
af5cc56fb31161ccd87cf925f3d3f22119dfbca78bc39a2e2d65d78bfcf0f0c6 include/openssl/self_test.h
2964274ab32b1ba8578a06b06663db2eda4317ae806369271d889176bb5a7d04 include/openssl/sha.h
c169a015d7be52b7b99dd41c418a48d97e52ad21687c39c512a83a7c3f3ddb70 include/openssl/stack.h
22d7584ad609e30e818b54dca1dfae8dea38913fffedd25cd540c550372fb9a6 include/openssl/symhacks.h
5e452bf61d802fdf7b6a65d1c8a1e3f72a7885e4bf2f521eca6443cea69f4ce5 include/openssl/trace.h
873d2ec2054ec24c52df4abe830cb2b9666fe4e75cc62b4de0f50ef9d20c5812 include/openssl/types.h
c0a9551efccf43f3dd748d4fd8ec897ddaabbc629c00ec1ad76ce983e1195a13 providers/common/bio_prov.c
4546387d6642603c81ec4cd8d5fc4af8ba60ac7359eb6f31e7d24827031e68ad 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
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
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
ce605f32413b09d33ce5795de9498a08183895c3347f33344f9ae5d31c29ccac providers/common/include/prov/der_rsa.h.in
6c1fa3f229c6f049c3ac152c4c265f3eb056d94221b82df95a15400649690e93 providers/common/include/prov/der_wrap.h.in
76087f04f4de6414c240f88807659fb2a04af914108f0c5f2515a4cb5482f655 providers/common/include/prov/proverr.h
83a57505d88a6a9cc4f7781c9f7f4af07668e7923502dfd6c5960bb492c1d24e providers/common/include/prov/provider_ctx.h
03fcfea9ed6e23d1df7ffd230af15f0f9b91a6aa635f77b9cbe52d5112168d09 providers/common/include/prov/provider_util.h
e1ef8b2be828a54312d6561b37751a5b6e9d5ebdb6c3e63589728c3d8adca7dc providers/common/include/prov/providercommon.h
73d0e15963759fcb7c5c434bb214b50bc32f6066e90ac07fb53dad11c2fd1939 providers/common/include/prov/securitycheck.h
737cc1228106e555e9bab24e3c2438982e04e05b0d5b9ee6995d71df16c49143 providers/common/provider_ctx.c
a8b73b10ab0100942dd2bc45f2fc9c9238b70bec0e49708ba113bc7479c8b92a providers/common/provider_err.c
9eae3e2cac89c7b63d091fdca1b6d80c5c5d52aa79c8ba4ce0158c5437ad62f3 providers/common/provider_seeding.c
eec462d685dd3b4764b076a3c18ecd9dd254350a0b78ddc2f8a60587829e1ce3 providers/common/provider_util.c
5b94312727ca33e4f5c038f4caaae8417bf584cfde22df83d91f3c55c30c81ee providers/common/securitycheck.c
527eda471e26763a5fcf123b2d290234d5c836de7b8ef6eef2166ef439919d82 providers/common/securitycheck_fips.c
abd5997bc33b681a4ab275978b92aebca0806a4a3f0c2f41dacf11b3b6f4e101 providers/fips/fips_entry.c
-0f761a26c8fa6ad8d5a15c817afe1741352b21769b2164a2eb7dd50e1f6fe04f providers/fips/fipsprov.c
+4a5ed1059ea6c5ef8d4b2a074b3da332443468852f58c18555f67f5d6d98606a providers/fips/fipsprov.c
5d24ba30f9cc7ca48546fb85dc285bd68590f3a604a0bd471bcb0c2a61169591 providers/fips/self_test.c
f822a03138e8b83ccaa910b89d72f31691da6778bf6638181f993ec7ae1167e3 providers/fips/self_test.h
d3c95c9c6cc4e3b1a5e4b2bfb2ae735a4109d763bcda7b1e9b8f9eb253f79820 providers/fips/self_test_data.inc
629f619ad055723e42624230c08430a3ef53e17ab405dc0fd35499e9ca4e389c providers/fips/self_test_kats.c
99baeec10374301e90352ab637056104a8ea28a6880804f44c640d0c9ee16eba providers/implementations/asymciphers/rsa_enc.c
4db1826ecce8b60cb641bcd7a61430ec8cef73d2fe3cbc06aa33526afe1c954a providers/implementations/ciphers/cipher_aes.c
6ba7d817081cf0d87ba7bfb38cd9d70e41505480bb8bc796ef896f68d4514ea6 providers/implementations/ciphers/cipher_aes.h
aef500281e7cd5a25a806a9bd45ec00a5b73984673202527dac5896fbcc9fa9c 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
f37c3cf9e2e6fcfcbed941f3670b790fe09990349db72eb065bef51705d46e96 providers/implementations/ciphers/cipher_aes_ccm.c
00f36bf48e522dbb5ec71df0ec13e387955fa3672e6ff90e8a412ae95c4a642f providers/implementations/ciphers/cipher_aes_ccm.h
6337b570e0dc4e98af07aa9704254d3ab958cf605584e250fbd76cd1d2a25ac7 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
7e886ecc088b5903aa082eac72a4c46f9064392bdf5723a592368ecebfeb71c0 providers/implementations/ciphers/cipher_aes_gcm.c
79f5a732820d2512a7f4fc2a99ece7e6e2523a51e62561eb67a4b70d5538b0c4 providers/implementations/ciphers/cipher_aes_gcm.h
ab298c5f89f3165fa11093fad8063b7bcbff0924b43fb3107148ae66d54adcb5 providers/implementations/ciphers/cipher_aes_gcm_hw.c
8ed4a100e4756c31c56147b4b0fab76a4c6e5292aa2f079045f37b5502fd41b9 providers/implementations/ciphers/cipher_aes_gcm_hw_aesni.inc
4c6f3a2818754a5aa7b6db36dae53e248504f9e82cc5af2ed68c723903d4f9d5 providers/implementations/ciphers/cipher_aes_hw.c
89de794c090192459d99d95bc4a422e7782e62192cd0fdb3bdef4128cfedee68 providers/implementations/ciphers/cipher_aes_hw_aesni.inc
fac3a1878dc9c0c363d0ecdd9f74926157df54ca4f40adf8c479927395082008 providers/implementations/ciphers/cipher_aes_ocb.c
88138a1aff9705e608c0557653be92eb4de65b152555a2b79ec8b2a8fae73e8f providers/implementations/ciphers/cipher_aes_ocb.h
855869ab5a8d7a61a11674cfe5d503dfa67f59e7e393730835d1d8cf0ab85c70 providers/implementations/ciphers/cipher_aes_ocb_hw.c
6a8782c728575d69c86b735c9f47acda5c0daa04e17f1e0faef2c963f23fab20 providers/implementations/ciphers/cipher_aes_wrp.c
527ff9277b92606517ee7af13225a9d5fcffbbc36eb18bce39f59d594cbe4931 providers/implementations/ciphers/cipher_aes_xts.c
c4a2499b214d7cf786dafaaee5c8c6963b3d5d1c27c144eec4b460f839074a3b providers/implementations/ciphers/cipher_aes_xts.h
281157d1da4d7285d878978e6d42d0d33b3a6bc16e3bc5b6879e39093a7d70da providers/implementations/ciphers/cipher_aes_xts_fips.c
f358c4121a8a223e2c6cf009fd28b8a195520279016462890214e8858880f632 providers/implementations/ciphers/cipher_aes_xts_hw.c
46ba8271917b53fd8fdf77aee19cc326a219c950b94e043d6d118dcac25ad7ad providers/implementations/ciphers/cipher_cts.c
74640ce402acc704af72e055fb7f27e6aa8efd417babc56f710478e571d8631c providers/implementations/ciphers/cipher_cts.h
fcc3bb0637864252402aaa9d543209909df9a39611127f777b168bc888498dc0 providers/implementations/ciphers/cipher_tdes.c
77709f7fc3f7c08986cd4f0ebf2ef6e44bacb975c1483ef444b3cf5e5071f9d6 providers/implementations/ciphers/cipher_tdes.h
f6b81faf6abf3baa926be7c054cda1ff2be109b0a2143b34b2f2d266b6cb2c52 providers/implementations/ciphers/cipher_tdes_common.c
50645122f08ef4891cd96cace833bd550be7f5278ab785515fd61fe8993c8c25 providers/implementations/ciphers/cipher_tdes_hw.c
1f44963b1ac450cb77d75df9fbf956b04742e38d236d316c7eb8021bdf0573a4 providers/implementations/ciphers/ciphercommon.c
dd72ea861edf70b94197821ceb00e07165d550934a2e851d62afa5034b79f468 providers/implementations/ciphers/ciphercommon_block.c
8af515e63a0c16ff35dcedcc43c7b4735a10943f1e937eeeb73eb1af3dc92782 providers/implementations/ciphers/ciphercommon_ccm.c
8b6828f188c2590c7d9c6cac13fa0eb6d38a522b0f2859e7c8a766580fa9b66e providers/implementations/ciphers/ciphercommon_ccm_hw.c
142785a128a0d694e2457e7d79da545791b73ae388dcf700b538763099f91f65 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
80551b53302d95faea257df3edbdbd02d48427ce42da2c4335f998456400d057 providers/implementations/digests/sha2_prov.c
de342d04be6af69037922d5c97bdc40c0c27f6740636e72786a765d0d8ad9173 providers/implementations/digests/sha3_prov.c
b5f94d597df72ca58486c59b2a70b4057d13f09528f861ed41a84b7125b54a82 providers/implementations/exchange/dh_exch.c
9c46dc0d859875fcc0bc3d61a7b610cd3520b1bf63718775c1124f54a1fe5f24 providers/implementations/exchange/ecdh_exch.c
9bf87b8429398a6465c7e9f749a33b84974303a458736b56f3359b30726d3969 providers/implementations/exchange/ecx_exch.c
-0cc02005660c5c340660123decac838c59b7460ef1003d9d50edc604cfd8e375 providers/implementations/exchange/kdf_exch.c
-a0d1c1d49557d32497877b2d549d2a7a7729a550306275bfe6ddcefca0d8fc80 providers/implementations/include/prov/ciphercommon.h
+4692ea3852bf5763db576359bd793fc1ec3bcd0ca42fc906991d7ec4cced7b2a providers/implementations/exchange/kdf_exch.c
+996f1397f61b9eab1e31b5d06bccd9ac958dbd5982fd41fdb263ee889b84275c providers/implementations/include/prov/ciphercommon.h
a9f5de1623221f327245957ec1dfd66a1914bff25adf4bcb81213c7955d19382 providers/implementations/include/prov/ciphercommon_aead.h
dd07797d61988fd4124cfb920616df672938da80649fac5977bfd061c981edc5 providers/implementations/include/prov/ciphercommon_ccm.h
0c1e99d70155402a790e4de65923228c8df8ad970741caccfe8b513837457d7f providers/implementations/include/prov/ciphercommon_gcm.h
b9a61ce951c1904d8315b1bb26c0ab0aaadb47e71d4ead5df0a891608c728c4b providers/implementations/include/prov/digestcommon.h
3e2558c36298cdb4fdaebe5a0cfa1dbbc78e0f60a9012f3a34e711cafb09c7b5 providers/implementations/include/prov/implementations.h
5f09fc71874b00419d71646714f21ebbdcceda277463b6f77d3d3ea6946914e8 providers/implementations/include/prov/kdfexchange.h
c95ce5498e724b9b3d58e3c2f4723e7e3e4beb07f9bea9422e43182cbadb43af providers/implementations/include/prov/macsignature.h
29d1a112b799e1f45fdf8bcee8361c2ed67428c250c1cdf408a9fbb7ebf4cce1 providers/implementations/include/prov/names.h
2187713b446d8b6d24ee986748b941ac3e24292c71e07ff9fb53a33021decdda providers/implementations/include/prov/seeding.h
-4e71ffd329f1715d14b54e14036b4b2618deb2fd81675287ce5eeb6c76a31d54 providers/implementations/kdfs/hkdf.c
+d376c58489ae36fbece94bb88939845ced04a2a0bdd55d6a3562e45a56577ae1 providers/implementations/kdfs/hkdf.c
a62e3af09f5af84dcf36f951ba4ac90ca1694adaf3747126186020b155f94186 providers/implementations/kdfs/kbkdf.c
e0644e727aacfea4da3cf2c4d2602d7ef0626ebb760b6467432ffd54d5fbb24d providers/implementations/kdfs/pbkdf2.c
c0778565abff112c0c5257329a7750ec4605e62f26cc36851fa1fbee6e03c70c providers/implementations/kdfs/pbkdf2.h
abe2b0f3711eaa34846e155cffc9242e4051c45de896f747afd5ac9d87f637dc providers/implementations/kdfs/pbkdf2_fips.c
9cc42a4b0a8089e6d1be64637dbb9e41bd21ae5e3386022a27a8f29308ad25c9 providers/implementations/kdfs/sshkdf.c
8571556d77d10e8edc98212473a38f09632e3f19e9995dde89ee6c95f2e84ccf providers/implementations/kdfs/sskdf.c
589f6133799da80760e8bc3ab0191a341ab6d4d2706e92e6eb4a24b0250fefa6 providers/implementations/kdfs/tls1_prf.c
4d4a6d9a562d2dcfec941d3f113a544663b5ac2fbe4accd89ec70c1cc11751d0 providers/implementations/kdfs/x942kdf.c
6b6c776b12664164f3cb54c21df61e1c4477c7855d89431a16fb338cdae58d43 providers/implementations/kem/rsa_kem.c
11a0d0fb88ed88e965f10b3a0ef6c880f60341df995128f57ad943053aaf15b2 providers/implementations/keymgmt/dh_kmgmt.c
a329f57cb041cd03907e9d996fbc2f378ee116c7f8d7fbf1ea08b7a5df7e0304 providers/implementations/keymgmt/dsa_kmgmt.c
9bc88451d3ae110c7a108ee73d3b3b6bda801ec3494d2dfb9c9970b85c2d34fe providers/implementations/keymgmt/ec_kmgmt.c
258ae17bb2dd87ed1511a8eb3fe99eed9b77f5c2f757215ff6b3d0e8791fc251 providers/implementations/keymgmt/ec_kmgmt_imexport.inc
011c36aad6834729043f23eacab417732541ee23916d9afa5bb9164862be00bb providers/implementations/keymgmt/ecx_kmgmt.c
053a2be39a87f50b877ebdbbf799cf5faf8b2de33b04311d819d212ee1ea329b providers/implementations/keymgmt/kdf_legacy_kmgmt.c
1646b477fa231dd0f6c22444c99098f9b447cab0d39ff69b811262469d4dbe09 providers/implementations/keymgmt/mac_legacy_kmgmt.c
19f22fc70a6321441e56d5bd4aab3d01d52d17069d4e4b5cefce0f411ecece75 providers/implementations/keymgmt/rsa_kmgmt.c
5eb96ea2df635cf79c5aeccae270fbe896b5e6384a5b3e4b187ce8c10fe8dfc7 providers/implementations/macs/cmac_prov.c
e69aa06f8f3c6f5a26702b9f44a844b8589b99dc0ee590953a29e8b9ef10acbe providers/implementations/macs/gmac_prov.c
895c8dc7235b9ad5ff893be0293cbc245a5455e8850195ac7d446646e4ea71d0 providers/implementations/macs/hmac_prov.c
8640b63fd8325aaf8f7128d6cc448d9af448a65bf51a8978075467d33a67944e providers/implementations/macs/kmac_prov.c
bf30274dd6b528ae913984775bd8f29c6c48c0ef06d464d0f738217727b7aa5c providers/implementations/rands/crngt.c
-9d23df7f99beec7392c9d4ed813407050bc2d150098888fe802e2c9705fc33fa providers/implementations/rands/drbg.c
-bb5f8161a80d0d1a7ee919af2b167972b00afd62e326252ca6aa93101f315f19 providers/implementations/rands/drbg_ctr.c
-a05adc3f6d9d6f948e5ead75f0522ed3164cb5b2d301169242f3cb97c4a7fac3 providers/implementations/rands/drbg_hash.c
-0876dfae991028c569631938946e458e6829cacf4cfb673d2b144ae50a3160bb providers/implementations/rands/drbg_hmac.c
-fc43558964bdf12442d3f6ab6cc3e6849f7adb42f4d0123a1279819befcf71cb providers/implementations/rands/drbg_local.h
+f9457255fc57ef5739aa2584e535195e38cc947e31fd044d28d64c28c8a946ce providers/implementations/rands/drbg.c
+7e8fa6333845778474ed1313a66867512512372c9397f699a8f68fa6d5fc05fa providers/implementations/rands/drbg_ctr.c
+8337994f4bc95e421d6d2833bb4481ad9d84deb3913d0faec6e1791ea372a793 providers/implementations/rands/drbg_hash.c
+1f040090f596f88cb64d6eb89109a8b75e66caee113708fb59335ad2547027fc providers/implementations/rands/drbg_hmac.c
+7a1b8516f891f25f3dc07ffe0455200f20d3a1f0345a917f00c7d9afe900bb0a providers/implementations/rands/drbg_local.h
04339b66c10017229ef368cb48077f58a252ebfda9ab12b9f919e4149b1036ed providers/implementations/rands/test_rng.c
cafb9e6f54ad15889fcebddac6df61336bff7d78936f7de3bb5aab8aee5728d2 providers/implementations/signature/dsa_sig.c
a30dc6308de0ca33406e7ce909f3bcf7580fb84d863b0976b275839f866258df providers/implementations/signature/ecdsa_sig.c
02e833a767afbe98247d6f09dfb1eb5a5cf7304a93f2c5427a9f6af9c8a3b549 providers/implementations/signature/eddsa_sig.c
3bb0f342b4cc1b4594ed0986adc47791c0a7b5c1ae7b1888c1fb5edb268a78d9 providers/implementations/signature/mac_legacy_sig.c
166d7e3a049b28ae2c6f94415070720d176a82e46af1613511c4b073ea705476 providers/implementations/signature/rsa_sig.c
a14e901b02fe095713624db4080b3aa3ca685d43f9ebec03041f992240973346 ssl/record/tls_pad.c
3f2e01a98d9e3fda6cc5cb4b44dd43f6cae4ec34994e8f734d11b1e643e58636 ssl/s3_cbc.c
diff --git a/crypto/openssl/providers/fips.checksum b/crypto/openssl/providers/fips.checksum
index 8fe82e025706..7b84d2271d3a 100644
--- a/crypto/openssl/providers/fips.checksum
+++ b/crypto/openssl/providers/fips.checksum
@@ -1 +1 @@
-9597c676c418928e2ba5075a6352a7d5b398e64db622b577822391424300ed43 providers/fips-sources.checksums
+4e1960f3d68410e8daf1893c9133ba9840912974ec65f885054c46b6bbeff5cd providers/fips-sources.checksums
diff --git a/crypto/openssl/providers/fips/fipsprov.c b/crypto/openssl/providers/fips/fipsprov.c
index 6a88039423d9..3889dcd88a71 100644
--- a/crypto/openssl/providers/fips/fipsprov.c
+++ b/crypto/openssl/providers/fips/fipsprov.c
@@ -1,915 +1,917 @@
/*
- * Copyright 2019-2022 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2019-2024 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 <assert.h>
#include <openssl/core_dispatch.h>
#include <openssl/core_names.h>
#include <openssl/params.h>
#include <openssl/fips_names.h>
#include <openssl/rand.h> /* RAND_get0_public() */
#include <openssl/proverr.h>
#include "internal/cryptlib.h"
#include "prov/implementations.h"
#include "prov/names.h"
#include "prov/provider_ctx.h"
#include "prov/providercommon.h"
#include "prov/provider_util.h"
#include "prov/seeding.h"
#include "self_test.h"
#include "internal/core.h"
static const char FIPS_DEFAULT_PROPERTIES[] = "provider=fips,fips=yes";
static const char FIPS_UNAPPROVED_PROPERTIES[] = "provider=fips,fips=no";
/*
* Forward declarations to ensure that interface functions are correctly
* defined.
*/
static OSSL_FUNC_provider_teardown_fn fips_teardown;
static OSSL_FUNC_provider_gettable_params_fn fips_gettable_params;
static OSSL_FUNC_provider_get_params_fn fips_get_params;
static OSSL_FUNC_provider_query_operation_fn fips_query;
#define ALGC(NAMES, FUNC, CHECK) { { NAMES, FIPS_DEFAULT_PROPERTIES, FUNC }, CHECK }
#define ALG(NAMES, FUNC) ALGC(NAMES, FUNC, NULL)
extern OSSL_FUNC_core_thread_start_fn *c_thread_start;
int FIPS_security_check_enabled(OSSL_LIB_CTX *libctx);
/*
* Should these function pointers be stored in the provider side provctx? Could
* they ever be different from one init to the next? We assume not for now.
*/
/* Functions provided by the core */
static OSSL_FUNC_core_gettable_params_fn *c_gettable_params;
static OSSL_FUNC_core_get_params_fn *c_get_params;
OSSL_FUNC_core_thread_start_fn *c_thread_start;
static OSSL_FUNC_core_new_error_fn *c_new_error;
static OSSL_FUNC_core_set_error_debug_fn *c_set_error_debug;
static OSSL_FUNC_core_vset_error_fn *c_vset_error;
static OSSL_FUNC_core_set_error_mark_fn *c_set_error_mark;
static OSSL_FUNC_core_clear_last_error_mark_fn *c_clear_last_error_mark;
static OSSL_FUNC_core_pop_error_to_mark_fn *c_pop_error_to_mark;
static OSSL_FUNC_CRYPTO_malloc_fn *c_CRYPTO_malloc;
static OSSL_FUNC_CRYPTO_zalloc_fn *c_CRYPTO_zalloc;
static OSSL_FUNC_CRYPTO_free_fn *c_CRYPTO_free;
static OSSL_FUNC_CRYPTO_clear_free_fn *c_CRYPTO_clear_free;
static OSSL_FUNC_CRYPTO_realloc_fn *c_CRYPTO_realloc;
static OSSL_FUNC_CRYPTO_clear_realloc_fn *c_CRYPTO_clear_realloc;
static OSSL_FUNC_CRYPTO_secure_malloc_fn *c_CRYPTO_secure_malloc;
static OSSL_FUNC_CRYPTO_secure_zalloc_fn *c_CRYPTO_secure_zalloc;
static OSSL_FUNC_CRYPTO_secure_free_fn *c_CRYPTO_secure_free;
static OSSL_FUNC_CRYPTO_secure_clear_free_fn *c_CRYPTO_secure_clear_free;
static OSSL_FUNC_CRYPTO_secure_allocated_fn *c_CRYPTO_secure_allocated;
static OSSL_FUNC_BIO_vsnprintf_fn *c_BIO_vsnprintf;
static OSSL_FUNC_self_test_cb_fn *c_stcbfn = NULL;
static OSSL_FUNC_core_get_libctx_fn *c_get_libctx = NULL;
typedef struct fips_global_st {
const OSSL_CORE_HANDLE *handle;
SELF_TEST_POST_PARAMS selftest_params;
int fips_security_checks;
const char *fips_security_check_option;
} FIPS_GLOBAL;
static void *fips_prov_ossl_ctx_new(OSSL_LIB_CTX *libctx)
{
FIPS_GLOBAL *fgbl = OPENSSL_zalloc(sizeof(*fgbl));
if (fgbl == NULL)
return NULL;
fgbl->fips_security_checks = 1;
fgbl->fips_security_check_option = "1";
return fgbl;
}
static void fips_prov_ossl_ctx_free(void *fgbl)
{
OPENSSL_free(fgbl);
}
static const OSSL_LIB_CTX_METHOD fips_prov_ossl_ctx_method = {
OSSL_LIB_CTX_METHOD_DEFAULT_PRIORITY,
fips_prov_ossl_ctx_new,
fips_prov_ossl_ctx_free,
};
/* Parameters we provide to the core */
static const OSSL_PARAM fips_param_types[] = {
OSSL_PARAM_DEFN(OSSL_PROV_PARAM_NAME, OSSL_PARAM_UTF8_PTR, NULL, 0),
OSSL_PARAM_DEFN(OSSL_PROV_PARAM_VERSION, OSSL_PARAM_UTF8_PTR, NULL, 0),
OSSL_PARAM_DEFN(OSSL_PROV_PARAM_BUILDINFO, OSSL_PARAM_UTF8_PTR, NULL, 0),
OSSL_PARAM_DEFN(OSSL_PROV_PARAM_STATUS, OSSL_PARAM_INTEGER, NULL, 0),
OSSL_PARAM_DEFN(OSSL_PROV_PARAM_SECURITY_CHECKS, OSSL_PARAM_INTEGER, NULL, 0),
OSSL_PARAM_END
};
static int fips_get_params_from_core(FIPS_GLOBAL *fgbl)
{
/*
* Parameters to retrieve from the core provider - required for self testing.
* NOTE: inside core_get_params() these will be loaded from config items
* stored inside prov->parameters (except for
* OSSL_PROV_PARAM_CORE_MODULE_FILENAME).
* OSSL_PROV_FIPS_PARAM_SECURITY_CHECKS is not a self test parameter.
*/
OSSL_PARAM core_params[8], *p = core_params;
*p++ = OSSL_PARAM_construct_utf8_ptr(
OSSL_PROV_PARAM_CORE_MODULE_FILENAME,
(char **)&fgbl->selftest_params.module_filename,
sizeof(fgbl->selftest_params.module_filename));
*p++ = OSSL_PARAM_construct_utf8_ptr(
OSSL_PROV_FIPS_PARAM_MODULE_MAC,
(char **)&fgbl->selftest_params.module_checksum_data,
sizeof(fgbl->selftest_params.module_checksum_data));
*p++ = OSSL_PARAM_construct_utf8_ptr(
OSSL_PROV_FIPS_PARAM_INSTALL_MAC,
(char **)&fgbl->selftest_params.indicator_checksum_data,
sizeof(fgbl->selftest_params.indicator_checksum_data));
*p++ = OSSL_PARAM_construct_utf8_ptr(
OSSL_PROV_FIPS_PARAM_INSTALL_STATUS,
(char **)&fgbl->selftest_params.indicator_data,
sizeof(fgbl->selftest_params.indicator_data));
*p++ = OSSL_PARAM_construct_utf8_ptr(
OSSL_PROV_FIPS_PARAM_INSTALL_VERSION,
(char **)&fgbl->selftest_params.indicator_version,
sizeof(fgbl->selftest_params.indicator_version));
*p++ = OSSL_PARAM_construct_utf8_ptr(
OSSL_PROV_FIPS_PARAM_CONDITIONAL_ERRORS,
(char **)&fgbl->selftest_params.conditional_error_check,
sizeof(fgbl->selftest_params.conditional_error_check));
*p++ = OSSL_PARAM_construct_utf8_ptr(
OSSL_PROV_FIPS_PARAM_SECURITY_CHECKS,
(char **)&fgbl->fips_security_check_option,
sizeof(fgbl->fips_security_check_option));
*p = OSSL_PARAM_construct_end();
if (!c_get_params(fgbl->handle, core_params)) {
ERR_raise(ERR_LIB_PROV, PROV_R_FAILED_TO_GET_PARAMETER);
return 0;
}
return 1;
}
static const OSSL_PARAM *fips_gettable_params(void *provctx)
{
return fips_param_types;
}
static int fips_get_params(void *provctx, OSSL_PARAM params[])
{
OSSL_PARAM *p;
FIPS_GLOBAL *fgbl = ossl_lib_ctx_get_data(ossl_prov_ctx_get0_libctx(provctx),
OSSL_LIB_CTX_FIPS_PROV_INDEX,
&fips_prov_ossl_ctx_method);
p = OSSL_PARAM_locate(params, OSSL_PROV_PARAM_NAME);
if (p != NULL && !OSSL_PARAM_set_utf8_ptr(p, "OpenSSL FIPS Provider"))
return 0;
p = OSSL_PARAM_locate(params, OSSL_PROV_PARAM_VERSION);
if (p != NULL && !OSSL_PARAM_set_utf8_ptr(p, OPENSSL_VERSION_STR))
return 0;
p = OSSL_PARAM_locate(params, OSSL_PROV_PARAM_BUILDINFO);
if (p != NULL && !OSSL_PARAM_set_utf8_ptr(p, OPENSSL_FULL_VERSION_STR))
return 0;
p = OSSL_PARAM_locate(params, OSSL_PROV_PARAM_STATUS);
if (p != NULL && !OSSL_PARAM_set_int(p, ossl_prov_is_running()))
return 0;
p = OSSL_PARAM_locate(params, OSSL_PROV_PARAM_SECURITY_CHECKS);
if (p != NULL && !OSSL_PARAM_set_int(p, fgbl->fips_security_checks))
return 0;
return 1;
}
static void set_self_test_cb(FIPS_GLOBAL *fgbl)
{
const OSSL_CORE_HANDLE *handle =
FIPS_get_core_handle(fgbl->selftest_params.libctx);
if (c_stcbfn != NULL && c_get_libctx != NULL) {
c_stcbfn(c_get_libctx(handle), &fgbl->selftest_params.cb,
&fgbl->selftest_params.cb_arg);
} else {
fgbl->selftest_params.cb = NULL;
fgbl->selftest_params.cb_arg = NULL;
}
}
static int fips_self_test(void *provctx)
{
FIPS_GLOBAL *fgbl = ossl_lib_ctx_get_data(ossl_prov_ctx_get0_libctx(provctx),
OSSL_LIB_CTX_FIPS_PROV_INDEX,
&fips_prov_ossl_ctx_method);
set_self_test_cb(fgbl);
return SELF_TEST_post(&fgbl->selftest_params, 1) ? 1 : 0;
}
/*
* For the algorithm names, we use the following formula for our primary
* names:
*
* ALGNAME[VERSION?][-SUBNAME[VERSION?]?][-SIZE?][-MODE?]
*
* VERSION is only present if there are multiple versions of
* an alg (MD2, MD4, MD5). It may be omitted if there is only
* one version (if a subsequent version is released in the future,
* we can always change the canonical name, and add the old name
* as an alias).
*
* SUBNAME may be present where we are combining multiple
* algorithms together, e.g. MD5-SHA1.
*
* SIZE is only present if multiple versions of an algorithm exist
* with different sizes (e.g. AES-128-CBC, AES-256-CBC)
*
* MODE is only present where applicable.
*
* We add diverse other names where applicable, such as the names that
* NIST uses, or that are used for ASN.1 OBJECT IDENTIFIERs, or names
* we have used historically.
*/
static const OSSL_ALGORITHM fips_digests[] = {
/* Our primary name:NiST name[:our older names] */
{ PROV_NAMES_SHA1, FIPS_DEFAULT_PROPERTIES, ossl_sha1_functions },
{ PROV_NAMES_SHA2_224, FIPS_DEFAULT_PROPERTIES, ossl_sha224_functions },
{ PROV_NAMES_SHA2_256, FIPS_DEFAULT_PROPERTIES, ossl_sha256_functions },
{ PROV_NAMES_SHA2_384, FIPS_DEFAULT_PROPERTIES, ossl_sha384_functions },
{ PROV_NAMES_SHA2_512, FIPS_DEFAULT_PROPERTIES, ossl_sha512_functions },
{ PROV_NAMES_SHA2_512_224, FIPS_DEFAULT_PROPERTIES,
ossl_sha512_224_functions },
{ PROV_NAMES_SHA2_512_256, FIPS_DEFAULT_PROPERTIES,
ossl_sha512_256_functions },
/* We agree with NIST here, so one name only */
{ PROV_NAMES_SHA3_224, FIPS_DEFAULT_PROPERTIES, ossl_sha3_224_functions },
{ PROV_NAMES_SHA3_256, FIPS_DEFAULT_PROPERTIES, ossl_sha3_256_functions },
{ PROV_NAMES_SHA3_384, FIPS_DEFAULT_PROPERTIES, ossl_sha3_384_functions },
{ PROV_NAMES_SHA3_512, FIPS_DEFAULT_PROPERTIES, ossl_sha3_512_functions },
{ PROV_NAMES_SHAKE_128, FIPS_DEFAULT_PROPERTIES, ossl_shake_128_functions },
{ PROV_NAMES_SHAKE_256, FIPS_DEFAULT_PROPERTIES, ossl_shake_256_functions },
/*
* KECCAK-KMAC-128 and KECCAK-KMAC-256 as hashes are mostly useful for
* KMAC128 and KMAC256.
*/
{ PROV_NAMES_KECCAK_KMAC_128, FIPS_DEFAULT_PROPERTIES,
ossl_keccak_kmac_128_functions },
{ PROV_NAMES_KECCAK_KMAC_256, FIPS_DEFAULT_PROPERTIES,
ossl_keccak_kmac_256_functions },
{ NULL, NULL, NULL }
};
static const OSSL_ALGORITHM_CAPABLE fips_ciphers[] = {
/* Our primary name[:ASN.1 OID name][:our older names] */
ALG(PROV_NAMES_AES_256_ECB, ossl_aes256ecb_functions),
ALG(PROV_NAMES_AES_192_ECB, ossl_aes192ecb_functions),
ALG(PROV_NAMES_AES_128_ECB, ossl_aes128ecb_functions),
ALG(PROV_NAMES_AES_256_CBC, ossl_aes256cbc_functions),
ALG(PROV_NAMES_AES_192_CBC, ossl_aes192cbc_functions),
ALG(PROV_NAMES_AES_128_CBC, ossl_aes128cbc_functions),
ALG(PROV_NAMES_AES_256_CBC_CTS, ossl_aes256cbc_cts_functions),
ALG(PROV_NAMES_AES_192_CBC_CTS, ossl_aes192cbc_cts_functions),
ALG(PROV_NAMES_AES_128_CBC_CTS, ossl_aes128cbc_cts_functions),
ALG(PROV_NAMES_AES_256_OFB, ossl_aes256ofb_functions),
ALG(PROV_NAMES_AES_192_OFB, ossl_aes192ofb_functions),
ALG(PROV_NAMES_AES_128_OFB, ossl_aes128ofb_functions),
ALG(PROV_NAMES_AES_256_CFB, ossl_aes256cfb_functions),
ALG(PROV_NAMES_AES_192_CFB, ossl_aes192cfb_functions),
ALG(PROV_NAMES_AES_128_CFB, ossl_aes128cfb_functions),
ALG(PROV_NAMES_AES_256_CFB1, ossl_aes256cfb1_functions),
ALG(PROV_NAMES_AES_192_CFB1, ossl_aes192cfb1_functions),
ALG(PROV_NAMES_AES_128_CFB1, ossl_aes128cfb1_functions),
ALG(PROV_NAMES_AES_256_CFB8, ossl_aes256cfb8_functions),
ALG(PROV_NAMES_AES_192_CFB8, ossl_aes192cfb8_functions),
ALG(PROV_NAMES_AES_128_CFB8, ossl_aes128cfb8_functions),
ALG(PROV_NAMES_AES_256_CTR, ossl_aes256ctr_functions),
ALG(PROV_NAMES_AES_192_CTR, ossl_aes192ctr_functions),
ALG(PROV_NAMES_AES_128_CTR, ossl_aes128ctr_functions),
ALG(PROV_NAMES_AES_256_XTS, ossl_aes256xts_functions),
ALG(PROV_NAMES_AES_128_XTS, ossl_aes128xts_functions),
ALG(PROV_NAMES_AES_256_GCM, ossl_aes256gcm_functions),
ALG(PROV_NAMES_AES_192_GCM, ossl_aes192gcm_functions),
ALG(PROV_NAMES_AES_128_GCM, ossl_aes128gcm_functions),
ALG(PROV_NAMES_AES_256_CCM, ossl_aes256ccm_functions),
ALG(PROV_NAMES_AES_192_CCM, ossl_aes192ccm_functions),
ALG(PROV_NAMES_AES_128_CCM, ossl_aes128ccm_functions),
ALG(PROV_NAMES_AES_256_WRAP, ossl_aes256wrap_functions),
ALG(PROV_NAMES_AES_192_WRAP, ossl_aes192wrap_functions),
ALG(PROV_NAMES_AES_128_WRAP, ossl_aes128wrap_functions),
ALG(PROV_NAMES_AES_256_WRAP_PAD, ossl_aes256wrappad_functions),
ALG(PROV_NAMES_AES_192_WRAP_PAD, ossl_aes192wrappad_functions),
ALG(PROV_NAMES_AES_128_WRAP_PAD, ossl_aes128wrappad_functions),
ALG(PROV_NAMES_AES_256_WRAP_INV, ossl_aes256wrapinv_functions),
ALG(PROV_NAMES_AES_192_WRAP_INV, ossl_aes192wrapinv_functions),
ALG(PROV_NAMES_AES_128_WRAP_INV, ossl_aes128wrapinv_functions),
ALG(PROV_NAMES_AES_256_WRAP_PAD_INV, ossl_aes256wrappadinv_functions),
ALG(PROV_NAMES_AES_192_WRAP_PAD_INV, ossl_aes192wrappadinv_functions),
ALG(PROV_NAMES_AES_128_WRAP_PAD_INV, ossl_aes128wrappadinv_functions),
ALGC(PROV_NAMES_AES_128_CBC_HMAC_SHA1, ossl_aes128cbc_hmac_sha1_functions,
ossl_cipher_capable_aes_cbc_hmac_sha1),
ALGC(PROV_NAMES_AES_256_CBC_HMAC_SHA1, ossl_aes256cbc_hmac_sha1_functions,
ossl_cipher_capable_aes_cbc_hmac_sha1),
ALGC(PROV_NAMES_AES_128_CBC_HMAC_SHA256, ossl_aes128cbc_hmac_sha256_functions,
ossl_cipher_capable_aes_cbc_hmac_sha256),
ALGC(PROV_NAMES_AES_256_CBC_HMAC_SHA256, ossl_aes256cbc_hmac_sha256_functions,
ossl_cipher_capable_aes_cbc_hmac_sha256),
#ifndef OPENSSL_NO_DES
ALG(PROV_NAMES_DES_EDE3_ECB, ossl_tdes_ede3_ecb_functions),
ALG(PROV_NAMES_DES_EDE3_CBC, ossl_tdes_ede3_cbc_functions),
#endif /* OPENSSL_NO_DES */
{ { NULL, NULL, NULL }, NULL }
};
static OSSL_ALGORITHM exported_fips_ciphers[OSSL_NELEM(fips_ciphers)];
static const OSSL_ALGORITHM fips_macs[] = {
#ifndef OPENSSL_NO_CMAC
{ PROV_NAMES_CMAC, FIPS_DEFAULT_PROPERTIES, ossl_cmac_functions },
#endif
{ PROV_NAMES_GMAC, FIPS_DEFAULT_PROPERTIES, ossl_gmac_functions },
{ PROV_NAMES_HMAC, FIPS_DEFAULT_PROPERTIES, ossl_hmac_functions },
{ PROV_NAMES_KMAC_128, FIPS_DEFAULT_PROPERTIES, ossl_kmac128_functions },
{ PROV_NAMES_KMAC_256, FIPS_DEFAULT_PROPERTIES, ossl_kmac256_functions },
{ NULL, NULL, NULL }
};
static const OSSL_ALGORITHM fips_kdfs[] = {
{ PROV_NAMES_HKDF, FIPS_DEFAULT_PROPERTIES, ossl_kdf_hkdf_functions },
{ PROV_NAMES_TLS1_3_KDF, FIPS_DEFAULT_PROPERTIES,
ossl_kdf_tls1_3_kdf_functions },
{ PROV_NAMES_SSKDF, FIPS_DEFAULT_PROPERTIES, ossl_kdf_sskdf_functions },
{ PROV_NAMES_PBKDF2, FIPS_DEFAULT_PROPERTIES, ossl_kdf_pbkdf2_functions },
{ PROV_NAMES_SSHKDF, FIPS_DEFAULT_PROPERTIES, ossl_kdf_sshkdf_functions },
{ PROV_NAMES_X963KDF, FIPS_DEFAULT_PROPERTIES,
ossl_kdf_x963_kdf_functions },
{ PROV_NAMES_X942KDF_ASN1, FIPS_DEFAULT_PROPERTIES,
ossl_kdf_x942_kdf_functions },
{ PROV_NAMES_TLS1_PRF, FIPS_DEFAULT_PROPERTIES,
ossl_kdf_tls1_prf_functions },
{ PROV_NAMES_KBKDF, FIPS_DEFAULT_PROPERTIES, ossl_kdf_kbkdf_functions },
{ NULL, NULL, NULL }
};
static const OSSL_ALGORITHM fips_rands[] = {
{ PROV_NAMES_CTR_DRBG, FIPS_DEFAULT_PROPERTIES, ossl_drbg_ctr_functions },
{ PROV_NAMES_HASH_DRBG, FIPS_DEFAULT_PROPERTIES, ossl_drbg_hash_functions },
{ PROV_NAMES_HMAC_DRBG, FIPS_DEFAULT_PROPERTIES, ossl_drbg_ossl_hmac_functions },
{ PROV_NAMES_TEST_RAND, FIPS_UNAPPROVED_PROPERTIES, ossl_test_rng_functions },
{ NULL, NULL, NULL }
};
static const OSSL_ALGORITHM fips_keyexch[] = {
#ifndef OPENSSL_NO_DH
{ PROV_NAMES_DH, FIPS_DEFAULT_PROPERTIES, ossl_dh_keyexch_functions },
#endif
#ifndef OPENSSL_NO_EC
{ PROV_NAMES_ECDH, FIPS_DEFAULT_PROPERTIES, ossl_ecdh_keyexch_functions },
{ PROV_NAMES_X25519, FIPS_DEFAULT_PROPERTIES, ossl_x25519_keyexch_functions },
{ PROV_NAMES_X448, FIPS_DEFAULT_PROPERTIES, ossl_x448_keyexch_functions },
#endif
{ PROV_NAMES_TLS1_PRF, FIPS_DEFAULT_PROPERTIES,
ossl_kdf_tls1_prf_keyexch_functions },
{ PROV_NAMES_HKDF, FIPS_DEFAULT_PROPERTIES, ossl_kdf_hkdf_keyexch_functions },
{ NULL, NULL, NULL }
};
static const OSSL_ALGORITHM fips_signature[] = {
#ifndef OPENSSL_NO_DSA
{ PROV_NAMES_DSA, FIPS_DEFAULT_PROPERTIES, ossl_dsa_signature_functions },
#endif
{ PROV_NAMES_RSA, FIPS_DEFAULT_PROPERTIES, ossl_rsa_signature_functions },
#ifndef OPENSSL_NO_EC
{ PROV_NAMES_ED25519, FIPS_DEFAULT_PROPERTIES, ossl_ed25519_signature_functions },
{ PROV_NAMES_ED448, FIPS_DEFAULT_PROPERTIES, ossl_ed448_signature_functions },
{ PROV_NAMES_ECDSA, FIPS_DEFAULT_PROPERTIES, ossl_ecdsa_signature_functions },
#endif
{ PROV_NAMES_HMAC, FIPS_DEFAULT_PROPERTIES,
ossl_mac_legacy_hmac_signature_functions },
#ifndef OPENSSL_NO_CMAC
{ PROV_NAMES_CMAC, FIPS_DEFAULT_PROPERTIES,
ossl_mac_legacy_cmac_signature_functions },
#endif
{ NULL, NULL, NULL }
};
static const OSSL_ALGORITHM fips_asym_cipher[] = {
{ PROV_NAMES_RSA, FIPS_DEFAULT_PROPERTIES, ossl_rsa_asym_cipher_functions },
{ NULL, NULL, NULL }
};
static const OSSL_ALGORITHM fips_asym_kem[] = {
{ PROV_NAMES_RSA, FIPS_DEFAULT_PROPERTIES, ossl_rsa_asym_kem_functions },
{ NULL, NULL, NULL }
};
static const OSSL_ALGORITHM fips_keymgmt[] = {
#ifndef OPENSSL_NO_DH
{ PROV_NAMES_DH, FIPS_DEFAULT_PROPERTIES, ossl_dh_keymgmt_functions,
PROV_DESCS_DH },
{ PROV_NAMES_DHX, FIPS_DEFAULT_PROPERTIES, ossl_dhx_keymgmt_functions,
PROV_DESCS_DHX },
#endif
#ifndef OPENSSL_NO_DSA
{ PROV_NAMES_DSA, FIPS_DEFAULT_PROPERTIES, ossl_dsa_keymgmt_functions,
PROV_DESCS_DSA },
#endif
{ PROV_NAMES_RSA, FIPS_DEFAULT_PROPERTIES, ossl_rsa_keymgmt_functions,
PROV_DESCS_RSA },
{ PROV_NAMES_RSA_PSS, FIPS_DEFAULT_PROPERTIES,
ossl_rsapss_keymgmt_functions, PROV_DESCS_RSA_PSS },
#ifndef OPENSSL_NO_EC
{ PROV_NAMES_EC, FIPS_DEFAULT_PROPERTIES, ossl_ec_keymgmt_functions,
PROV_DESCS_EC },
{ PROV_NAMES_X25519, FIPS_DEFAULT_PROPERTIES, ossl_x25519_keymgmt_functions,
PROV_DESCS_X25519 },
{ PROV_NAMES_X448, FIPS_DEFAULT_PROPERTIES, ossl_x448_keymgmt_functions,
PROV_DESCS_X448 },
{ PROV_NAMES_ED25519, FIPS_DEFAULT_PROPERTIES, ossl_ed25519_keymgmt_functions,
PROV_DESCS_ED25519 },
{ PROV_NAMES_ED448, FIPS_DEFAULT_PROPERTIES, ossl_ed448_keymgmt_functions,
PROV_DESCS_ED448 },
#endif
{ PROV_NAMES_TLS1_PRF, FIPS_DEFAULT_PROPERTIES, ossl_kdf_keymgmt_functions,
PROV_DESCS_TLS1_PRF_SIGN },
{ PROV_NAMES_HKDF, FIPS_DEFAULT_PROPERTIES, ossl_kdf_keymgmt_functions,
PROV_DESCS_HKDF_SIGN },
{ PROV_NAMES_HMAC, FIPS_DEFAULT_PROPERTIES, ossl_mac_legacy_keymgmt_functions,
PROV_DESCS_HMAC_SIGN },
#ifndef OPENSSL_NO_CMAC
{ PROV_NAMES_CMAC, FIPS_DEFAULT_PROPERTIES,
ossl_cmac_legacy_keymgmt_functions, PROV_DESCS_CMAC_SIGN },
#endif
{ NULL, NULL, NULL }
};
static const OSSL_ALGORITHM *fips_query(void *provctx, int operation_id,
int *no_cache)
{
*no_cache = 0;
if (!ossl_prov_is_running())
return NULL;
switch (operation_id) {
case OSSL_OP_DIGEST:
return fips_digests;
case OSSL_OP_CIPHER:
return exported_fips_ciphers;
case OSSL_OP_MAC:
return fips_macs;
case OSSL_OP_KDF:
return fips_kdfs;
case OSSL_OP_RAND:
return fips_rands;
case OSSL_OP_KEYMGMT:
return fips_keymgmt;
case OSSL_OP_KEYEXCH:
return fips_keyexch;
case OSSL_OP_SIGNATURE:
return fips_signature;
case OSSL_OP_ASYM_CIPHER:
return fips_asym_cipher;
case OSSL_OP_KEM:
return fips_asym_kem;
}
return NULL;
}
static void fips_teardown(void *provctx)
{
OSSL_LIB_CTX_free(PROV_LIBCTX_OF(provctx));
ossl_prov_ctx_free(provctx);
}
static void fips_intern_teardown(void *provctx)
{
/*
* We know that the library context is the same as for the outer provider,
* so no need to destroy it here.
*/
ossl_prov_ctx_free(provctx);
}
/* Functions we provide to the core */
static const OSSL_DISPATCH fips_dispatch_table[] = {
{ OSSL_FUNC_PROVIDER_TEARDOWN, (void (*)(void))fips_teardown },
{ OSSL_FUNC_PROVIDER_GETTABLE_PARAMS, (void (*)(void))fips_gettable_params },
{ OSSL_FUNC_PROVIDER_GET_PARAMS, (void (*)(void))fips_get_params },
{ OSSL_FUNC_PROVIDER_QUERY_OPERATION, (void (*)(void))fips_query },
{ OSSL_FUNC_PROVIDER_GET_CAPABILITIES,
(void (*)(void))ossl_prov_get_capabilities },
{ OSSL_FUNC_PROVIDER_SELF_TEST, (void (*)(void))fips_self_test },
{ 0, NULL }
};
/* Functions we provide to ourself */
static const OSSL_DISPATCH intern_dispatch_table[] = {
{ OSSL_FUNC_PROVIDER_TEARDOWN, (void (*)(void))fips_intern_teardown },
{ OSSL_FUNC_PROVIDER_QUERY_OPERATION, (void (*)(void))fips_query },
{ 0, NULL }
};
/*
* On VMS, the provider init function name is expected to be uppercase,
* see the pragmas in <openssl/core.h>. Let's do the same with this
* internal name. This is how symbol names are treated by default
* by the compiler if nothing else is said, but since this is part
* of libfips, and we build our libraries with mixed case symbol names,
* we must switch back to this default explicitly here.
*/
#ifdef __VMS
# pragma names save
# pragma names uppercase,truncated
#endif
OSSL_provider_init_fn OSSL_provider_init_int;
#ifdef __VMS
# pragma names restore
#endif
int OSSL_provider_init_int(const OSSL_CORE_HANDLE *handle,
const OSSL_DISPATCH *in,
const OSSL_DISPATCH **out,
void **provctx)
{
FIPS_GLOBAL *fgbl;
OSSL_LIB_CTX *libctx = NULL;
SELF_TEST_POST_PARAMS selftest_params;
memset(&selftest_params, 0, sizeof(selftest_params));
if (!ossl_prov_seeding_from_dispatch(in))
goto err;
for (; in->function_id != 0; in++) {
/*
* We do not support the scenario of an application linked against
* multiple versions of libcrypto (e.g. one static and one dynamic), but
* sharing a single fips.so. We do a simple sanity check here.
*/
#define set_func(c, f) if (c == NULL) c = f; else if (c != f) return 0;
switch (in->function_id) {
case OSSL_FUNC_CORE_GET_LIBCTX:
set_func(c_get_libctx, OSSL_FUNC_core_get_libctx(in));
break;
case OSSL_FUNC_CORE_GETTABLE_PARAMS:
set_func(c_gettable_params, OSSL_FUNC_core_gettable_params(in));
break;
case OSSL_FUNC_CORE_GET_PARAMS:
set_func(c_get_params, OSSL_FUNC_core_get_params(in));
break;
case OSSL_FUNC_CORE_THREAD_START:
set_func(c_thread_start, OSSL_FUNC_core_thread_start(in));
break;
case OSSL_FUNC_CORE_NEW_ERROR:
set_func(c_new_error, OSSL_FUNC_core_new_error(in));
break;
case OSSL_FUNC_CORE_SET_ERROR_DEBUG:
set_func(c_set_error_debug, OSSL_FUNC_core_set_error_debug(in));
break;
case OSSL_FUNC_CORE_VSET_ERROR:
set_func(c_vset_error, OSSL_FUNC_core_vset_error(in));
break;
case OSSL_FUNC_CORE_SET_ERROR_MARK:
set_func(c_set_error_mark, OSSL_FUNC_core_set_error_mark(in));
break;
case OSSL_FUNC_CORE_CLEAR_LAST_ERROR_MARK:
set_func(c_clear_last_error_mark,
OSSL_FUNC_core_clear_last_error_mark(in));
break;
case OSSL_FUNC_CORE_POP_ERROR_TO_MARK:
set_func(c_pop_error_to_mark, OSSL_FUNC_core_pop_error_to_mark(in));
break;
case OSSL_FUNC_CRYPTO_MALLOC:
set_func(c_CRYPTO_malloc, OSSL_FUNC_CRYPTO_malloc(in));
break;
case OSSL_FUNC_CRYPTO_ZALLOC:
set_func(c_CRYPTO_zalloc, OSSL_FUNC_CRYPTO_zalloc(in));
break;
case OSSL_FUNC_CRYPTO_FREE:
set_func(c_CRYPTO_free, OSSL_FUNC_CRYPTO_free(in));
break;
case OSSL_FUNC_CRYPTO_CLEAR_FREE:
set_func(c_CRYPTO_clear_free, OSSL_FUNC_CRYPTO_clear_free(in));
break;
case OSSL_FUNC_CRYPTO_REALLOC:
set_func(c_CRYPTO_realloc, OSSL_FUNC_CRYPTO_realloc(in));
break;
case OSSL_FUNC_CRYPTO_CLEAR_REALLOC:
set_func(c_CRYPTO_clear_realloc,
OSSL_FUNC_CRYPTO_clear_realloc(in));
break;
case OSSL_FUNC_CRYPTO_SECURE_MALLOC:
set_func(c_CRYPTO_secure_malloc,
OSSL_FUNC_CRYPTO_secure_malloc(in));
break;
case OSSL_FUNC_CRYPTO_SECURE_ZALLOC:
set_func(c_CRYPTO_secure_zalloc,
OSSL_FUNC_CRYPTO_secure_zalloc(in));
break;
case OSSL_FUNC_CRYPTO_SECURE_FREE:
set_func(c_CRYPTO_secure_free,
OSSL_FUNC_CRYPTO_secure_free(in));
break;
case OSSL_FUNC_CRYPTO_SECURE_CLEAR_FREE:
set_func(c_CRYPTO_secure_clear_free,
OSSL_FUNC_CRYPTO_secure_clear_free(in));
break;
case OSSL_FUNC_CRYPTO_SECURE_ALLOCATED:
set_func(c_CRYPTO_secure_allocated,
OSSL_FUNC_CRYPTO_secure_allocated(in));
break;
case OSSL_FUNC_BIO_NEW_FILE:
set_func(selftest_params.bio_new_file_cb,
OSSL_FUNC_BIO_new_file(in));
break;
case OSSL_FUNC_BIO_NEW_MEMBUF:
set_func(selftest_params.bio_new_buffer_cb,
OSSL_FUNC_BIO_new_membuf(in));
break;
case OSSL_FUNC_BIO_READ_EX:
set_func(selftest_params.bio_read_ex_cb,
OSSL_FUNC_BIO_read_ex(in));
break;
case OSSL_FUNC_BIO_FREE:
set_func(selftest_params.bio_free_cb, OSSL_FUNC_BIO_free(in));
break;
case OSSL_FUNC_BIO_VSNPRINTF:
set_func(c_BIO_vsnprintf, OSSL_FUNC_BIO_vsnprintf(in));
break;
case OSSL_FUNC_SELF_TEST_CB:
set_func(c_stcbfn, OSSL_FUNC_self_test_cb(in));
break;
default:
/* Just ignore anything we don't understand */
break;
}
}
+ OPENSSL_cpuid_setup();
+
/* Create a context. */
if ((*provctx = ossl_prov_ctx_new()) == NULL
|| (libctx = OSSL_LIB_CTX_new()) == NULL) {
/*
* We free libctx separately here and only here because it hasn't
* been attached to *provctx. All other error paths below rely
* solely on fips_teardown.
*/
OSSL_LIB_CTX_free(libctx);
goto err;
}
if ((fgbl = ossl_lib_ctx_get_data(libctx, OSSL_LIB_CTX_FIPS_PROV_INDEX,
&fips_prov_ossl_ctx_method)) == NULL)
goto err;
fgbl->handle = handle;
/*
* We did initial set up of selftest_params in a local copy, because we
* could not create fgbl until c_CRYPTO_zalloc was defined in the loop
* above.
*/
fgbl->selftest_params = selftest_params;
fgbl->selftest_params.libctx = libctx;
set_self_test_cb(fgbl);
if (!fips_get_params_from_core(fgbl)) {
/* Error already raised */
goto err;
}
/*
* Disable the conditional error check if it's disabled in the fips config
* file.
*/
if (fgbl->selftest_params.conditional_error_check != NULL
&& strcmp(fgbl->selftest_params.conditional_error_check, "0") == 0)
SELF_TEST_disable_conditional_error_state();
/* Disable the security check if it's disabled in the fips config file. */
if (fgbl->fips_security_check_option != NULL
&& strcmp(fgbl->fips_security_check_option, "0") == 0)
fgbl->fips_security_checks = 0;
ossl_prov_cache_exported_algorithms(fips_ciphers, exported_fips_ciphers);
if (!SELF_TEST_post(&fgbl->selftest_params, 0)) {
ERR_raise(ERR_LIB_PROV, PROV_R_SELF_TEST_POST_FAILURE);
goto err;
}
ossl_prov_ctx_set0_libctx(*provctx, libctx);
ossl_prov_ctx_set0_handle(*provctx, handle);
*out = fips_dispatch_table;
return 1;
err:
fips_teardown(*provctx);
OSSL_LIB_CTX_free(libctx);
*provctx = NULL;
return 0;
}
/*
* The internal init function used when the FIPS module uses EVP to call
* another algorithm also in the FIPS module. This is a recursive call that has
* been made from within the FIPS module itself. To make this work, we populate
* the provider context of this inner instance with the same library context
* that was used in the EVP call that initiated this recursive call.
*/
OSSL_provider_init_fn ossl_fips_intern_provider_init;
int ossl_fips_intern_provider_init(const OSSL_CORE_HANDLE *handle,
const OSSL_DISPATCH *in,
const OSSL_DISPATCH **out,
void **provctx)
{
OSSL_FUNC_core_get_libctx_fn *c_internal_get_libctx = NULL;
for (; in->function_id != 0; in++) {
switch (in->function_id) {
case OSSL_FUNC_CORE_GET_LIBCTX:
c_internal_get_libctx = OSSL_FUNC_core_get_libctx(in);
break;
default:
break;
}
}
if (c_internal_get_libctx == NULL)
return 0;
if ((*provctx = ossl_prov_ctx_new()) == NULL)
return 0;
/*
* Using the parent library context only works because we are a built-in
* internal provider. This is not something that most providers would be
* able to do.
*/
ossl_prov_ctx_set0_libctx(*provctx,
(OSSL_LIB_CTX *)c_internal_get_libctx(handle));
ossl_prov_ctx_set0_handle(*provctx, handle);
*out = intern_dispatch_table;
return 1;
}
void ERR_new(void)
{
c_new_error(NULL);
}
void ERR_set_debug(const char *file, int line, const char *func)
{
c_set_error_debug(NULL, file, line, func);
}
void ERR_set_error(int lib, int reason, const char *fmt, ...)
{
va_list args;
va_start(args, fmt);
c_vset_error(NULL, ERR_PACK(lib, 0, reason), fmt, args);
va_end(args);
}
void ERR_vset_error(int lib, int reason, const char *fmt, va_list args)
{
c_vset_error(NULL, ERR_PACK(lib, 0, reason), fmt, args);
}
int ERR_set_mark(void)
{
return c_set_error_mark(NULL);
}
int ERR_clear_last_mark(void)
{
return c_clear_last_error_mark(NULL);
}
int ERR_pop_to_mark(void)
{
return c_pop_error_to_mark(NULL);
}
/*
* This must take a library context, since it's called from the depths
* of crypto/initthread.c code, where it's (correctly) assumed that the
* passed caller argument is an OSSL_LIB_CTX pointer (since the same routine
* is also called from other parts of libcrypto, which all pass around a
* OSSL_LIB_CTX pointer)
*/
const OSSL_CORE_HANDLE *FIPS_get_core_handle(OSSL_LIB_CTX *libctx)
{
FIPS_GLOBAL *fgbl = ossl_lib_ctx_get_data(libctx,
OSSL_LIB_CTX_FIPS_PROV_INDEX,
&fips_prov_ossl_ctx_method);
if (fgbl == NULL)
return NULL;
return fgbl->handle;
}
void *CRYPTO_malloc(size_t num, const char *file, int line)
{
return c_CRYPTO_malloc(num, file, line);
}
void *CRYPTO_zalloc(size_t num, const char *file, int line)
{
return c_CRYPTO_zalloc(num, file, line);
}
void CRYPTO_free(void *ptr, const char *file, int line)
{
c_CRYPTO_free(ptr, file, line);
}
void CRYPTO_clear_free(void *ptr, size_t num, const char *file, int line)
{
c_CRYPTO_clear_free(ptr, num, file, line);
}
void *CRYPTO_realloc(void *addr, size_t num, const char *file, int line)
{
return c_CRYPTO_realloc(addr, num, file, line);
}
void *CRYPTO_clear_realloc(void *addr, size_t old_num, size_t num,
const char *file, int line)
{
return c_CRYPTO_clear_realloc(addr, old_num, num, file, line);
}
void *CRYPTO_secure_malloc(size_t num, const char *file, int line)
{
return c_CRYPTO_secure_malloc(num, file, line);
}
void *CRYPTO_secure_zalloc(size_t num, const char *file, int line)
{
return c_CRYPTO_secure_zalloc(num, file, line);
}
void CRYPTO_secure_free(void *ptr, const char *file, int line)
{
c_CRYPTO_secure_free(ptr, file, line);
}
void CRYPTO_secure_clear_free(void *ptr, size_t num, const char *file, int line)
{
c_CRYPTO_secure_clear_free(ptr, num, file, line);
}
int CRYPTO_secure_allocated(const void *ptr)
{
return c_CRYPTO_secure_allocated(ptr);
}
int BIO_snprintf(char *buf, size_t n, const char *format, ...)
{
va_list args;
int ret;
va_start(args, format);
ret = c_BIO_vsnprintf(buf, n, format, args);
va_end(args);
return ret;
}
int FIPS_security_check_enabled(OSSL_LIB_CTX *libctx)
{
FIPS_GLOBAL *fgbl = ossl_lib_ctx_get_data(libctx,
OSSL_LIB_CTX_FIPS_PROV_INDEX,
&fips_prov_ossl_ctx_method);
return fgbl->fips_security_checks;
}
void OSSL_SELF_TEST_get_callback(OSSL_LIB_CTX *libctx, OSSL_CALLBACK **cb,
void **cbarg)
{
assert(libctx != NULL);
if (c_stcbfn != NULL && c_get_libctx != NULL) {
/* Get the parent libctx */
c_stcbfn(c_get_libctx(FIPS_get_core_handle(libctx)), cb, cbarg);
} else {
if (cb != NULL)
*cb = NULL;
if (cbarg != NULL)
*cbarg = NULL;
}
}
diff --git a/crypto/openssl/providers/implementations/exchange/kdf_exch.c b/crypto/openssl/providers/implementations/exchange/kdf_exch.c
index 527a866c3d8d..148a3c422a8f 100644
--- a/crypto/openssl/providers/implementations/exchange/kdf_exch.c
+++ b/crypto/openssl/providers/implementations/exchange/kdf_exch.c
@@ -1,215 +1,257 @@
/*
- * Copyright 2020-2022 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2020-2024 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 <openssl/crypto.h>
#include <openssl/kdf.h>
#include <openssl/core_dispatch.h>
#include <openssl/core_names.h>
#include <openssl/err.h>
#include <openssl/proverr.h>
#include <openssl/params.h>
#include "internal/numbers.h"
#include "prov/implementations.h"
#include "prov/provider_ctx.h"
#include "prov/kdfexchange.h"
#include "prov/providercommon.h"
static OSSL_FUNC_keyexch_newctx_fn kdf_tls1_prf_newctx;
static OSSL_FUNC_keyexch_newctx_fn kdf_hkdf_newctx;
static OSSL_FUNC_keyexch_newctx_fn kdf_scrypt_newctx;
static OSSL_FUNC_keyexch_init_fn kdf_init;
static OSSL_FUNC_keyexch_derive_fn kdf_derive;
static OSSL_FUNC_keyexch_freectx_fn kdf_freectx;
static OSSL_FUNC_keyexch_dupctx_fn kdf_dupctx;
static OSSL_FUNC_keyexch_set_ctx_params_fn kdf_set_ctx_params;
+static OSSL_FUNC_keyexch_get_ctx_params_fn kdf_get_ctx_params;
static OSSL_FUNC_keyexch_settable_ctx_params_fn kdf_tls1_prf_settable_ctx_params;
static OSSL_FUNC_keyexch_settable_ctx_params_fn kdf_hkdf_settable_ctx_params;
static OSSL_FUNC_keyexch_settable_ctx_params_fn kdf_scrypt_settable_ctx_params;
+static OSSL_FUNC_keyexch_gettable_ctx_params_fn kdf_tls1_prf_gettable_ctx_params;
+static OSSL_FUNC_keyexch_gettable_ctx_params_fn kdf_hkdf_gettable_ctx_params;
+static OSSL_FUNC_keyexch_gettable_ctx_params_fn kdf_scrypt_gettable_ctx_params;
typedef struct {
void *provctx;
EVP_KDF_CTX *kdfctx;
KDF_DATA *kdfdata;
} PROV_KDF_CTX;
static void *kdf_newctx(const char *kdfname, void *provctx)
{
PROV_KDF_CTX *kdfctx;
EVP_KDF *kdf = NULL;
if (!ossl_prov_is_running())
return NULL;
kdfctx = OPENSSL_zalloc(sizeof(PROV_KDF_CTX));
if (kdfctx == NULL)
return NULL;
kdfctx->provctx = provctx;
kdf = EVP_KDF_fetch(PROV_LIBCTX_OF(provctx), kdfname, NULL);
if (kdf == NULL)
goto err;
kdfctx->kdfctx = EVP_KDF_CTX_new(kdf);
EVP_KDF_free(kdf);
if (kdfctx->kdfctx == NULL)
goto err;
return kdfctx;
err:
OPENSSL_free(kdfctx);
return NULL;
}
#define KDF_NEWCTX(funcname, kdfname) \
static void *kdf_##funcname##_newctx(void *provctx) \
{ \
return kdf_newctx(kdfname, provctx); \
}
KDF_NEWCTX(tls1_prf, "TLS1-PRF")
KDF_NEWCTX(hkdf, "HKDF")
KDF_NEWCTX(scrypt, "SCRYPT")
static int kdf_init(void *vpkdfctx, void *vkdf, const OSSL_PARAM params[])
{
PROV_KDF_CTX *pkdfctx = (PROV_KDF_CTX *)vpkdfctx;
if (!ossl_prov_is_running()
|| pkdfctx == NULL
|| vkdf == NULL
|| !ossl_kdf_data_up_ref(vkdf))
return 0;
pkdfctx->kdfdata = vkdf;
return kdf_set_ctx_params(pkdfctx, params);
}
static int kdf_derive(void *vpkdfctx, unsigned char *secret, size_t *secretlen,
size_t outlen)
{
PROV_KDF_CTX *pkdfctx = (PROV_KDF_CTX *)vpkdfctx;
size_t kdfsize;
int ret;
if (!ossl_prov_is_running())
return 0;
kdfsize = EVP_KDF_CTX_get_kdf_size(pkdfctx->kdfctx);
if (secret == NULL) {
*secretlen = kdfsize;
return 1;
}
if (kdfsize != SIZE_MAX) {
if (outlen < kdfsize) {
ERR_raise(ERR_LIB_PROV, PROV_R_OUTPUT_BUFFER_TOO_SMALL);
return 0;
}
outlen = kdfsize;
}
ret = EVP_KDF_derive(pkdfctx->kdfctx, secret, outlen, NULL);
if (ret <= 0)
return 0;
*secretlen = outlen;
return 1;
}
static void kdf_freectx(void *vpkdfctx)
{
PROV_KDF_CTX *pkdfctx = (PROV_KDF_CTX *)vpkdfctx;
EVP_KDF_CTX_free(pkdfctx->kdfctx);
ossl_kdf_data_free(pkdfctx->kdfdata);
OPENSSL_free(pkdfctx);
}
static void *kdf_dupctx(void *vpkdfctx)
{
PROV_KDF_CTX *srcctx = (PROV_KDF_CTX *)vpkdfctx;
PROV_KDF_CTX *dstctx;
if (!ossl_prov_is_running())
return NULL;
dstctx = OPENSSL_zalloc(sizeof(*srcctx));
if (dstctx == NULL)
return NULL;
*dstctx = *srcctx;
dstctx->kdfctx = EVP_KDF_CTX_dup(srcctx->kdfctx);
if (dstctx->kdfctx == NULL) {
OPENSSL_free(dstctx);
return NULL;
}
if (!ossl_kdf_data_up_ref(dstctx->kdfdata)) {
EVP_KDF_CTX_free(dstctx->kdfctx);
OPENSSL_free(dstctx);
return NULL;
}
return dstctx;
}
static int kdf_set_ctx_params(void *vpkdfctx, const OSSL_PARAM params[])
{
PROV_KDF_CTX *pkdfctx = (PROV_KDF_CTX *)vpkdfctx;
return EVP_KDF_CTX_set_params(pkdfctx->kdfctx, params);
}
+static int kdf_get_ctx_params(void *vpkdfctx, OSSL_PARAM params[])
+{
+ PROV_KDF_CTX *pkdfctx = (PROV_KDF_CTX *)vpkdfctx;
+
+ return EVP_KDF_CTX_get_params(pkdfctx->kdfctx, params);
+}
+
static const OSSL_PARAM *kdf_settable_ctx_params(ossl_unused void *vpkdfctx,
void *provctx,
const char *kdfname)
{
EVP_KDF *kdf = EVP_KDF_fetch(PROV_LIBCTX_OF(provctx), kdfname,
NULL);
const OSSL_PARAM *params;
if (kdf == NULL)
return NULL;
params = EVP_KDF_settable_ctx_params(kdf);
EVP_KDF_free(kdf);
return params;
}
#define KDF_SETTABLE_CTX_PARAMS(funcname, kdfname) \
static const OSSL_PARAM *kdf_##funcname##_settable_ctx_params(void *vpkdfctx, \
void *provctx) \
{ \
return kdf_settable_ctx_params(vpkdfctx, provctx, kdfname); \
}
KDF_SETTABLE_CTX_PARAMS(tls1_prf, "TLS1-PRF")
KDF_SETTABLE_CTX_PARAMS(hkdf, "HKDF")
KDF_SETTABLE_CTX_PARAMS(scrypt, "SCRYPT")
+static const OSSL_PARAM *kdf_gettable_ctx_params(ossl_unused void *vpkdfctx,
+ void *provctx,
+ const char *kdfname)
+{
+ EVP_KDF *kdf = EVP_KDF_fetch(PROV_LIBCTX_OF(provctx), kdfname,
+ NULL);
+ const OSSL_PARAM *params;
+
+ if (kdf == NULL)
+ return NULL;
+
+ params = EVP_KDF_gettable_ctx_params(kdf);
+ EVP_KDF_free(kdf);
+
+ return params;
+}
+
+#define KDF_GETTABLE_CTX_PARAMS(funcname, kdfname) \
+ static const OSSL_PARAM *kdf_##funcname##_gettable_ctx_params(void *vpkdfctx, \
+ void *provctx) \
+ { \
+ return kdf_gettable_ctx_params(vpkdfctx, provctx, kdfname); \
+ }
+
+KDF_GETTABLE_CTX_PARAMS(tls1_prf, "TLS1-PRF")
+KDF_GETTABLE_CTX_PARAMS(hkdf, "HKDF")
+KDF_GETTABLE_CTX_PARAMS(scrypt, "SCRYPT")
+
#define KDF_KEYEXCH_FUNCTIONS(funcname) \
const OSSL_DISPATCH ossl_kdf_##funcname##_keyexch_functions[] = { \
{ OSSL_FUNC_KEYEXCH_NEWCTX, (void (*)(void))kdf_##funcname##_newctx }, \
{ OSSL_FUNC_KEYEXCH_INIT, (void (*)(void))kdf_init }, \
{ OSSL_FUNC_KEYEXCH_DERIVE, (void (*)(void))kdf_derive }, \
{ OSSL_FUNC_KEYEXCH_FREECTX, (void (*)(void))kdf_freectx }, \
{ OSSL_FUNC_KEYEXCH_DUPCTX, (void (*)(void))kdf_dupctx }, \
{ OSSL_FUNC_KEYEXCH_SET_CTX_PARAMS, (void (*)(void))kdf_set_ctx_params }, \
+ { OSSL_FUNC_KEYEXCH_GET_CTX_PARAMS, (void (*)(void))kdf_get_ctx_params }, \
{ OSSL_FUNC_KEYEXCH_SETTABLE_CTX_PARAMS, \
(void (*)(void))kdf_##funcname##_settable_ctx_params }, \
+ { OSSL_FUNC_KEYEXCH_GETTABLE_CTX_PARAMS, \
+ (void (*)(void))kdf_##funcname##_gettable_ctx_params }, \
{ 0, NULL } \
};
KDF_KEYEXCH_FUNCTIONS(tls1_prf)
KDF_KEYEXCH_FUNCTIONS(hkdf)
KDF_KEYEXCH_FUNCTIONS(scrypt)
diff --git a/crypto/openssl/providers/implementations/include/prov/ciphercommon.h b/crypto/openssl/providers/implementations/include/prov/ciphercommon.h
index 383b759304d4..aacd49707f84 100644
--- a/crypto/openssl/providers/implementations/include/prov/ciphercommon.h
+++ b/crypto/openssl/providers/implementations/include/prov/ciphercommon.h
@@ -1,362 +1,363 @@
/*
- * Copyright 2019-2022 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2019-2024 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 <openssl/params.h>
#include <openssl/core_dispatch.h>
#include <openssl/core_names.h>
#include <openssl/evp.h>
#include "internal/cryptlib.h"
#include "crypto/modes.h"
# define MAXCHUNK ((size_t)1 << 30)
# define MAXBITCHUNK ((size_t)1 << (sizeof(size_t) * 8 - 4))
#define GENERIC_BLOCK_SIZE 16
#define IV_STATE_UNINITIALISED 0 /* initial state is not initialized */
#define IV_STATE_BUFFERED 1 /* iv has been copied to the iv buffer */
#define IV_STATE_COPIED 2 /* iv has been copied from the iv buffer */
#define IV_STATE_FINISHED 3 /* the iv has been used - so don't reuse it */
#define PROV_CIPHER_FUNC(type, name, args) typedef type (* OSSL_##name##_fn)args
typedef struct prov_cipher_hw_st PROV_CIPHER_HW;
typedef struct prov_cipher_ctx_st PROV_CIPHER_CTX;
typedef int (PROV_CIPHER_HW_FN)(PROV_CIPHER_CTX *dat, unsigned char *out,
const unsigned char *in, size_t len);
/* Internal flags that can be queried */
#define PROV_CIPHER_FLAG_AEAD 0x0001
#define PROV_CIPHER_FLAG_CUSTOM_IV 0x0002
#define PROV_CIPHER_FLAG_CTS 0x0004
#define PROV_CIPHER_FLAG_TLS1_MULTIBLOCK 0x0008
#define PROV_CIPHER_FLAG_RAND_KEY 0x0010
/* Internal flags that are only used within the provider */
#define PROV_CIPHER_FLAG_VARIABLE_LENGTH 0x0100
#define PROV_CIPHER_FLAG_INVERSE_CIPHER 0x0200
struct prov_cipher_ctx_st {
+ /* place buffer at the beginning for memory alignment */
+ /* The original value of the iv */
+ unsigned char oiv[GENERIC_BLOCK_SIZE];
+ /* Buffer of partial blocks processed via update calls */
+ unsigned char buf[GENERIC_BLOCK_SIZE];
+ unsigned char iv[GENERIC_BLOCK_SIZE];
+
block128_f block;
union {
cbc128_f cbc;
ctr128_f ctr;
ecb128_f ecb;
} stream;
unsigned int mode;
size_t keylen; /* key size (in bytes) */
size_t ivlen;
size_t blocksize;
size_t bufsz; /* Number of bytes in buf */
unsigned int cts_mode; /* Use to set the type for CTS modes */
unsigned int pad : 1; /* Whether padding should be used or not */
unsigned int enc : 1; /* Set to 1 for encrypt, or 0 otherwise */
unsigned int iv_set : 1; /* Set when the iv is copied to the iv/oiv buffers */
unsigned int key_set : 1; /* Set when key is set on the context */
unsigned int updated : 1; /* Set to 1 during update for one shot ciphers */
unsigned int variable_keylength : 1;
unsigned int inverse_cipher : 1; /* set to 1 to use inverse cipher */
unsigned int use_bits : 1; /* Set to 0 for cfb1 to use bits instead of bytes */
unsigned int tlsversion; /* If TLS padding is in use the TLS version number */
unsigned char *tlsmac; /* tls MAC extracted from the last record */
int alloced; /*
* Whether the tlsmac data has been allocated or
* points into the user buffer.
*/
size_t tlsmacsize; /* Size of the TLS MAC */
int removetlspad; /* Whether TLS padding should be removed or not */
size_t removetlsfixed; /*
* Length of the fixed size data to remove when
* processing TLS data (equals mac size plus
* IV size if applicable)
*/
/*
* num contains the number of bytes of |iv| which are valid for modes that
* manage partial blocks themselves.
*/
unsigned int num;
-
- /* The original value of the iv */
- unsigned char oiv[GENERIC_BLOCK_SIZE];
- /* Buffer of partial blocks processed via update calls */
- unsigned char buf[GENERIC_BLOCK_SIZE];
- unsigned char iv[GENERIC_BLOCK_SIZE];
const PROV_CIPHER_HW *hw; /* hardware specific functions */
const void *ks; /* Pointer to algorithm specific key data */
OSSL_LIB_CTX *libctx;
};
struct prov_cipher_hw_st {
int (*init)(PROV_CIPHER_CTX *dat, const uint8_t *key, size_t keylen);
PROV_CIPHER_HW_FN *cipher;
void (*copyctx)(PROV_CIPHER_CTX *dst, const PROV_CIPHER_CTX *src);
};
void ossl_cipher_generic_reset_ctx(PROV_CIPHER_CTX *ctx);
OSSL_FUNC_cipher_encrypt_init_fn ossl_cipher_generic_einit;
OSSL_FUNC_cipher_decrypt_init_fn ossl_cipher_generic_dinit;
OSSL_FUNC_cipher_update_fn ossl_cipher_generic_block_update;
OSSL_FUNC_cipher_final_fn ossl_cipher_generic_block_final;
OSSL_FUNC_cipher_update_fn ossl_cipher_generic_stream_update;
OSSL_FUNC_cipher_final_fn ossl_cipher_generic_stream_final;
OSSL_FUNC_cipher_cipher_fn ossl_cipher_generic_cipher;
OSSL_FUNC_cipher_get_ctx_params_fn ossl_cipher_generic_get_ctx_params;
OSSL_FUNC_cipher_set_ctx_params_fn ossl_cipher_generic_set_ctx_params;
OSSL_FUNC_cipher_gettable_params_fn ossl_cipher_generic_gettable_params;
OSSL_FUNC_cipher_gettable_ctx_params_fn ossl_cipher_generic_gettable_ctx_params;
OSSL_FUNC_cipher_settable_ctx_params_fn ossl_cipher_generic_settable_ctx_params;
OSSL_FUNC_cipher_set_ctx_params_fn ossl_cipher_var_keylen_set_ctx_params;
OSSL_FUNC_cipher_settable_ctx_params_fn ossl_cipher_var_keylen_settable_ctx_params;
OSSL_FUNC_cipher_gettable_ctx_params_fn ossl_cipher_aead_gettable_ctx_params;
OSSL_FUNC_cipher_settable_ctx_params_fn ossl_cipher_aead_settable_ctx_params;
int ossl_cipher_generic_get_params(OSSL_PARAM params[], unsigned int md,
uint64_t flags,
size_t kbits, size_t blkbits, size_t ivbits);
void ossl_cipher_generic_initkey(void *vctx, size_t kbits, size_t blkbits,
size_t ivbits, unsigned int mode,
uint64_t flags,
const PROV_CIPHER_HW *hw, void *provctx);
#define IMPLEMENT_generic_cipher_func(alg, UCALG, lcmode, UCMODE, flags, kbits,\
blkbits, ivbits, typ) \
const OSSL_DISPATCH ossl_##alg##kbits##lcmode##_functions[] = { \
{ OSSL_FUNC_CIPHER_NEWCTX, \
(void (*)(void)) alg##_##kbits##_##lcmode##_newctx }, \
{ OSSL_FUNC_CIPHER_FREECTX, (void (*)(void)) alg##_freectx }, \
{ OSSL_FUNC_CIPHER_DUPCTX, (void (*)(void)) alg##_dupctx }, \
{ OSSL_FUNC_CIPHER_ENCRYPT_INIT, (void (*)(void))ossl_cipher_generic_einit }, \
{ OSSL_FUNC_CIPHER_DECRYPT_INIT, (void (*)(void))ossl_cipher_generic_dinit }, \
{ OSSL_FUNC_CIPHER_UPDATE, (void (*)(void))ossl_cipher_generic_##typ##_update },\
{ OSSL_FUNC_CIPHER_FINAL, (void (*)(void))ossl_cipher_generic_##typ##_final }, \
{ OSSL_FUNC_CIPHER_CIPHER, (void (*)(void))ossl_cipher_generic_cipher }, \
{ OSSL_FUNC_CIPHER_GET_PARAMS, \
(void (*)(void)) alg##_##kbits##_##lcmode##_get_params }, \
{ OSSL_FUNC_CIPHER_GET_CTX_PARAMS, \
(void (*)(void))ossl_cipher_generic_get_ctx_params }, \
{ OSSL_FUNC_CIPHER_SET_CTX_PARAMS, \
(void (*)(void))ossl_cipher_generic_set_ctx_params }, \
{ OSSL_FUNC_CIPHER_GETTABLE_PARAMS, \
(void (*)(void))ossl_cipher_generic_gettable_params }, \
{ OSSL_FUNC_CIPHER_GETTABLE_CTX_PARAMS, \
(void (*)(void))ossl_cipher_generic_gettable_ctx_params }, \
{ OSSL_FUNC_CIPHER_SETTABLE_CTX_PARAMS, \
(void (*)(void))ossl_cipher_generic_settable_ctx_params }, \
{ 0, NULL } \
};
#define IMPLEMENT_var_keylen_cipher_func(alg, UCALG, lcmode, UCMODE, flags, \
kbits, blkbits, ivbits, typ) \
const OSSL_DISPATCH ossl_##alg##kbits##lcmode##_functions[] = { \
{ OSSL_FUNC_CIPHER_NEWCTX, \
(void (*)(void)) alg##_##kbits##_##lcmode##_newctx }, \
{ OSSL_FUNC_CIPHER_FREECTX, (void (*)(void)) alg##_freectx }, \
{ OSSL_FUNC_CIPHER_DUPCTX, (void (*)(void)) alg##_dupctx }, \
{ OSSL_FUNC_CIPHER_ENCRYPT_INIT, (void (*)(void))ossl_cipher_generic_einit },\
{ OSSL_FUNC_CIPHER_DECRYPT_INIT, (void (*)(void))ossl_cipher_generic_dinit },\
{ OSSL_FUNC_CIPHER_UPDATE, (void (*)(void))ossl_cipher_generic_##typ##_update },\
{ OSSL_FUNC_CIPHER_FINAL, (void (*)(void))ossl_cipher_generic_##typ##_final }, \
{ OSSL_FUNC_CIPHER_CIPHER, (void (*)(void))ossl_cipher_generic_cipher }, \
{ OSSL_FUNC_CIPHER_GET_PARAMS, \
(void (*)(void)) alg##_##kbits##_##lcmode##_get_params }, \
{ OSSL_FUNC_CIPHER_GET_CTX_PARAMS, \
(void (*)(void))ossl_cipher_generic_get_ctx_params }, \
{ OSSL_FUNC_CIPHER_SET_CTX_PARAMS, \
(void (*)(void))ossl_cipher_var_keylen_set_ctx_params }, \
{ OSSL_FUNC_CIPHER_GETTABLE_PARAMS, \
(void (*)(void))ossl_cipher_generic_gettable_params }, \
{ OSSL_FUNC_CIPHER_GETTABLE_CTX_PARAMS, \
(void (*)(void))ossl_cipher_generic_gettable_ctx_params }, \
{ OSSL_FUNC_CIPHER_SETTABLE_CTX_PARAMS, \
(void (*)(void))ossl_cipher_var_keylen_settable_ctx_params }, \
{ 0, NULL } \
};
#define IMPLEMENT_generic_cipher_genfn(alg, UCALG, lcmode, UCMODE, flags, \
kbits, blkbits, ivbits, typ) \
static OSSL_FUNC_cipher_get_params_fn alg##_##kbits##_##lcmode##_get_params; \
static int alg##_##kbits##_##lcmode##_get_params(OSSL_PARAM params[]) \
{ \
return ossl_cipher_generic_get_params(params, EVP_CIPH_##UCMODE##_MODE, \
flags, kbits, blkbits, ivbits); \
} \
static OSSL_FUNC_cipher_newctx_fn alg##_##kbits##_##lcmode##_newctx; \
static void * alg##_##kbits##_##lcmode##_newctx(void *provctx) \
{ \
PROV_##UCALG##_CTX *ctx = ossl_prov_is_running() ? OPENSSL_zalloc(sizeof(*ctx))\
: NULL; \
if (ctx != NULL) { \
ossl_cipher_generic_initkey(ctx, kbits, blkbits, ivbits, \
EVP_CIPH_##UCMODE##_MODE, flags, \
ossl_prov_cipher_hw_##alg##_##lcmode(kbits),\
provctx); \
} \
return ctx; \
} \
#define IMPLEMENT_generic_cipher(alg, UCALG, lcmode, UCMODE, flags, kbits, \
blkbits, ivbits, typ) \
IMPLEMENT_generic_cipher_genfn(alg, UCALG, lcmode, UCMODE, flags, kbits, \
blkbits, ivbits, typ) \
IMPLEMENT_generic_cipher_func(alg, UCALG, lcmode, UCMODE, flags, kbits, \
blkbits, ivbits, typ)
#define IMPLEMENT_var_keylen_cipher(alg, UCALG, lcmode, UCMODE, flags, kbits, \
blkbits, ivbits, typ) \
IMPLEMENT_generic_cipher_genfn(alg, UCALG, lcmode, UCMODE, flags, kbits, \
blkbits, ivbits, typ) \
IMPLEMENT_var_keylen_cipher_func(alg, UCALG, lcmode, UCMODE, flags, kbits, \
blkbits, ivbits, typ)
PROV_CIPHER_HW_FN ossl_cipher_hw_generic_cbc;
PROV_CIPHER_HW_FN ossl_cipher_hw_generic_ecb;
PROV_CIPHER_HW_FN ossl_cipher_hw_generic_ofb128;
PROV_CIPHER_HW_FN ossl_cipher_hw_generic_cfb128;
PROV_CIPHER_HW_FN ossl_cipher_hw_generic_cfb8;
PROV_CIPHER_HW_FN ossl_cipher_hw_generic_cfb1;
PROV_CIPHER_HW_FN ossl_cipher_hw_generic_ctr;
PROV_CIPHER_HW_FN ossl_cipher_hw_chunked_cbc;
PROV_CIPHER_HW_FN ossl_cipher_hw_chunked_cfb8;
PROV_CIPHER_HW_FN ossl_cipher_hw_chunked_cfb128;
PROV_CIPHER_HW_FN ossl_cipher_hw_chunked_ofb128;
#define ossl_cipher_hw_chunked_ecb ossl_cipher_hw_generic_ecb
#define ossl_cipher_hw_chunked_ctr ossl_cipher_hw_generic_ctr
#define ossl_cipher_hw_chunked_cfb1 ossl_cipher_hw_generic_cfb1
#define IMPLEMENT_CIPHER_HW_OFB(MODE, NAME, CTX_NAME, KEY_NAME, FUNC_PREFIX) \
static int cipher_hw_##NAME##_##MODE##_cipher(PROV_CIPHER_CTX *ctx, \
unsigned char *out, \
const unsigned char *in, size_t len) \
{ \
int num = ctx->num; \
KEY_NAME *key = &(((CTX_NAME *)ctx)->ks.ks); \
\
while (len >= MAXCHUNK) { \
FUNC_PREFIX##_encrypt(in, out, MAXCHUNK, key, ctx->iv, &num); \
len -= MAXCHUNK; \
in += MAXCHUNK; \
out += MAXCHUNK; \
} \
if (len > 0) { \
FUNC_PREFIX##_encrypt(in, out, (long)len, key, ctx->iv, &num); \
} \
ctx->num = num; \
return 1; \
}
#define IMPLEMENT_CIPHER_HW_ECB(MODE, NAME, CTX_NAME, KEY_NAME, FUNC_PREFIX) \
static int cipher_hw_##NAME##_##MODE##_cipher(PROV_CIPHER_CTX *ctx, \
unsigned char *out, \
const unsigned char *in, size_t len) \
{ \
size_t i, bl = ctx->blocksize; \
KEY_NAME *key = &(((CTX_NAME *)ctx)->ks.ks); \
\
if (len < bl) \
return 1; \
for (i = 0, len -= bl; i <= len; i += bl) \
FUNC_PREFIX##_encrypt(in + i, out + i, key, ctx->enc); \
return 1; \
}
#define IMPLEMENT_CIPHER_HW_CBC(MODE, NAME, CTX_NAME, KEY_NAME, FUNC_PREFIX) \
static int cipher_hw_##NAME##_##MODE##_cipher(PROV_CIPHER_CTX *ctx, \
unsigned char *out, \
const unsigned char *in, size_t len) \
{ \
KEY_NAME *key = &(((CTX_NAME *)ctx)->ks.ks); \
\
while (len >= MAXCHUNK) { \
FUNC_PREFIX##_encrypt(in, out, MAXCHUNK, key, ctx->iv, ctx->enc); \
len -= MAXCHUNK; \
in += MAXCHUNK; \
out += MAXCHUNK; \
} \
if (len > 0) \
FUNC_PREFIX##_encrypt(in, out, (long)len, key, ctx->iv, ctx->enc); \
return 1; \
}
#define IMPLEMENT_CIPHER_HW_CFB(MODE, NAME, CTX_NAME, KEY_NAME, FUNC_PREFIX) \
static int cipher_hw_##NAME##_##MODE##_cipher(PROV_CIPHER_CTX *ctx, \
unsigned char *out, \
const unsigned char *in, size_t len) \
{ \
size_t chunk = MAXCHUNK; \
KEY_NAME *key = &(((CTX_NAME *)ctx)->ks.ks); \
int num = ctx->num; \
\
if (len < chunk) \
chunk = len; \
while (len > 0 && len >= chunk) { \
FUNC_PREFIX##_encrypt(in, out, (long)chunk, key, ctx->iv, &num, \
ctx->enc); \
len -= chunk; \
in += chunk; \
out += chunk; \
if (len < chunk) \
chunk = len; \
} \
ctx->num = num; \
return 1; \
}
#define IMPLEMENT_CIPHER_HW_COPYCTX(name, CTX_TYPE) \
static void name(PROV_CIPHER_CTX *dst, const PROV_CIPHER_CTX *src) \
{ \
CTX_TYPE *sctx = (CTX_TYPE *)src; \
CTX_TYPE *dctx = (CTX_TYPE *)dst; \
\
*dctx = *sctx; \
dst->ks = &dctx->ks.ks; \
}
#define CIPHER_DEFAULT_GETTABLE_CTX_PARAMS_START(name) \
static const OSSL_PARAM name##_known_gettable_ctx_params[] = { \
OSSL_PARAM_size_t(OSSL_CIPHER_PARAM_KEYLEN, NULL), \
OSSL_PARAM_size_t(OSSL_CIPHER_PARAM_IVLEN, NULL), \
OSSL_PARAM_uint(OSSL_CIPHER_PARAM_PADDING, NULL), \
OSSL_PARAM_uint(OSSL_CIPHER_PARAM_NUM, NULL), \
OSSL_PARAM_octet_string(OSSL_CIPHER_PARAM_IV, NULL, 0), \
OSSL_PARAM_octet_string(OSSL_CIPHER_PARAM_UPDATED_IV, NULL, 0),
#define CIPHER_DEFAULT_GETTABLE_CTX_PARAMS_END(name) \
OSSL_PARAM_END \
}; \
const OSSL_PARAM * name##_gettable_ctx_params(ossl_unused void *cctx, \
ossl_unused void *provctx) \
{ \
return name##_known_gettable_ctx_params; \
}
#define CIPHER_DEFAULT_SETTABLE_CTX_PARAMS_START(name) \
static const OSSL_PARAM name##_known_settable_ctx_params[] = { \
OSSL_PARAM_uint(OSSL_CIPHER_PARAM_PADDING, NULL), \
OSSL_PARAM_uint(OSSL_CIPHER_PARAM_NUM, NULL),
#define CIPHER_DEFAULT_SETTABLE_CTX_PARAMS_END(name) \
OSSL_PARAM_END \
}; \
const OSSL_PARAM * name##_settable_ctx_params(ossl_unused void *cctx, \
ossl_unused void *provctx) \
{ \
return name##_known_settable_ctx_params; \
}
int ossl_cipher_generic_initiv(PROV_CIPHER_CTX *ctx, const unsigned char *iv,
size_t ivlen);
size_t ossl_cipher_fillblock(unsigned char *buf, size_t *buflen,
size_t blocksize,
const unsigned char **in, size_t *inlen);
int ossl_cipher_trailingdata(unsigned char *buf, size_t *buflen,
size_t blocksize,
const unsigned char **in, size_t *inlen);
diff --git a/crypto/openssl/providers/implementations/kdfs/hkdf.c b/crypto/openssl/providers/implementations/kdfs/hkdf.c
index 25819ea23977..3db8b43891a0 100644
--- a/crypto/openssl/providers/implementations/kdfs/hkdf.c
+++ b/crypto/openssl/providers/implementations/kdfs/hkdf.c
@@ -1,783 +1,791 @@
/*
- * Copyright 2016-2023 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2016-2024 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
*/
/*
* HMAC low level APIs are deprecated for public use, but still ok for internal
* use.
*/
#include "internal/deprecated.h"
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <openssl/hmac.h>
#include <openssl/evp.h>
#include <openssl/kdf.h>
#include <openssl/core_names.h>
#include <openssl/proverr.h>
#include "internal/cryptlib.h"
#include "internal/numbers.h"
#include "internal/packet.h"
#include "crypto/evp.h"
#include "prov/provider_ctx.h"
#include "prov/providercommon.h"
#include "prov/implementations.h"
#include "prov/provider_util.h"
#include "e_os.h"
#define HKDF_MAXBUF 2048
#define HKDF_MAXINFO (32*1024)
static OSSL_FUNC_kdf_newctx_fn kdf_hkdf_new;
static OSSL_FUNC_kdf_freectx_fn kdf_hkdf_free;
static OSSL_FUNC_kdf_reset_fn kdf_hkdf_reset;
static OSSL_FUNC_kdf_derive_fn kdf_hkdf_derive;
static OSSL_FUNC_kdf_settable_ctx_params_fn kdf_hkdf_settable_ctx_params;
static OSSL_FUNC_kdf_set_ctx_params_fn kdf_hkdf_set_ctx_params;
static OSSL_FUNC_kdf_gettable_ctx_params_fn kdf_hkdf_gettable_ctx_params;
static OSSL_FUNC_kdf_get_ctx_params_fn kdf_hkdf_get_ctx_params;
static OSSL_FUNC_kdf_derive_fn kdf_tls1_3_derive;
static OSSL_FUNC_kdf_settable_ctx_params_fn kdf_tls1_3_settable_ctx_params;
static OSSL_FUNC_kdf_set_ctx_params_fn kdf_tls1_3_set_ctx_params;
static int HKDF(OSSL_LIB_CTX *libctx, const EVP_MD *evp_md,
const unsigned char *salt, size_t salt_len,
const unsigned char *key, size_t key_len,
const unsigned char *info, size_t info_len,
unsigned char *okm, size_t okm_len);
static int HKDF_Extract(OSSL_LIB_CTX *libctx, const EVP_MD *evp_md,
const unsigned char *salt, size_t salt_len,
const unsigned char *ikm, size_t ikm_len,
unsigned char *prk, size_t prk_len);
static int HKDF_Expand(const EVP_MD *evp_md,
const unsigned char *prk, size_t prk_len,
const unsigned char *info, size_t info_len,
unsigned char *okm, size_t okm_len);
/* Settable context parameters that are common across HKDF and the TLS KDF */
#define HKDF_COMMON_SETTABLES \
OSSL_PARAM_utf8_string(OSSL_KDF_PARAM_MODE, NULL, 0), \
OSSL_PARAM_int(OSSL_KDF_PARAM_MODE, NULL), \
OSSL_PARAM_utf8_string(OSSL_KDF_PARAM_PROPERTIES, NULL, 0), \
OSSL_PARAM_utf8_string(OSSL_KDF_PARAM_DIGEST, NULL, 0), \
OSSL_PARAM_octet_string(OSSL_KDF_PARAM_KEY, NULL, 0), \
OSSL_PARAM_octet_string(OSSL_KDF_PARAM_SALT, NULL, 0)
typedef struct {
void *provctx;
int mode;
PROV_DIGEST digest;
unsigned char *salt;
size_t salt_len;
unsigned char *key;
size_t key_len;
unsigned char *prefix;
size_t prefix_len;
unsigned char *label;
size_t label_len;
unsigned char *data;
size_t data_len;
unsigned char *info;
size_t info_len;
} KDF_HKDF;
static void *kdf_hkdf_new(void *provctx)
{
KDF_HKDF *ctx;
if (!ossl_prov_is_running())
return NULL;
if ((ctx = OPENSSL_zalloc(sizeof(*ctx))) == NULL)
ERR_raise(ERR_LIB_PROV, ERR_R_MALLOC_FAILURE);
else
ctx->provctx = provctx;
return ctx;
}
static void kdf_hkdf_free(void *vctx)
{
KDF_HKDF *ctx = (KDF_HKDF *)vctx;
if (ctx != NULL) {
kdf_hkdf_reset(ctx);
OPENSSL_free(ctx);
}
}
static void kdf_hkdf_reset(void *vctx)
{
KDF_HKDF *ctx = (KDF_HKDF *)vctx;
void *provctx = ctx->provctx;
ossl_prov_digest_reset(&ctx->digest);
OPENSSL_free(ctx->salt);
OPENSSL_free(ctx->prefix);
OPENSSL_free(ctx->label);
OPENSSL_clear_free(ctx->data, ctx->data_len);
OPENSSL_clear_free(ctx->key, ctx->key_len);
OPENSSL_clear_free(ctx->info, ctx->info_len);
memset(ctx, 0, sizeof(*ctx));
ctx->provctx = provctx;
}
static size_t kdf_hkdf_size(KDF_HKDF *ctx)
{
int sz;
const EVP_MD *md = ossl_prov_digest_md(&ctx->digest);
if (ctx->mode != EVP_KDF_HKDF_MODE_EXTRACT_ONLY)
return SIZE_MAX;
if (md == NULL) {
ERR_raise(ERR_LIB_PROV, PROV_R_MISSING_MESSAGE_DIGEST);
return 0;
}
sz = EVP_MD_get_size(md);
if (sz < 0)
return 0;
return sz;
}
static int kdf_hkdf_derive(void *vctx, unsigned char *key, size_t keylen,
const OSSL_PARAM params[])
{
KDF_HKDF *ctx = (KDF_HKDF *)vctx;
OSSL_LIB_CTX *libctx = PROV_LIBCTX_OF(ctx->provctx);
const EVP_MD *md;
if (!ossl_prov_is_running() || !kdf_hkdf_set_ctx_params(ctx, params))
return 0;
md = ossl_prov_digest_md(&ctx->digest);
if (md == NULL) {
ERR_raise(ERR_LIB_PROV, PROV_R_MISSING_MESSAGE_DIGEST);
return 0;
}
if (ctx->key == NULL) {
ERR_raise(ERR_LIB_PROV, PROV_R_MISSING_KEY);
return 0;
}
if (keylen == 0) {
ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_KEY_LENGTH);
return 0;
}
switch (ctx->mode) {
case EVP_KDF_HKDF_MODE_EXTRACT_AND_EXPAND:
default:
return HKDF(libctx, md, ctx->salt, ctx->salt_len,
ctx->key, ctx->key_len, ctx->info, ctx->info_len, key, keylen);
case EVP_KDF_HKDF_MODE_EXTRACT_ONLY:
return HKDF_Extract(libctx, md, ctx->salt, ctx->salt_len,
ctx->key, ctx->key_len, key, keylen);
case EVP_KDF_HKDF_MODE_EXPAND_ONLY:
return HKDF_Expand(md, ctx->key, ctx->key_len, ctx->info,
ctx->info_len, key, keylen);
}
}
static int hkdf_common_set_ctx_params(KDF_HKDF *ctx, const OSSL_PARAM params[])
{
OSSL_LIB_CTX *libctx = PROV_LIBCTX_OF(ctx->provctx);
const OSSL_PARAM *p;
int n;
if (params == NULL)
return 1;
if (!ossl_prov_digest_load_from_params(&ctx->digest, params, libctx))
return 0;
if ((p = OSSL_PARAM_locate_const(params, OSSL_KDF_PARAM_MODE)) != NULL) {
if (p->data_type == OSSL_PARAM_UTF8_STRING) {
if (OPENSSL_strcasecmp(p->data, "EXTRACT_AND_EXPAND") == 0) {
ctx->mode = EVP_KDF_HKDF_MODE_EXTRACT_AND_EXPAND;
} else if (OPENSSL_strcasecmp(p->data, "EXTRACT_ONLY") == 0) {
ctx->mode = EVP_KDF_HKDF_MODE_EXTRACT_ONLY;
} else if (OPENSSL_strcasecmp(p->data, "EXPAND_ONLY") == 0) {
ctx->mode = EVP_KDF_HKDF_MODE_EXPAND_ONLY;
} else {
ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_MODE);
return 0;
}
} else if (OSSL_PARAM_get_int(p, &n)) {
if (n != EVP_KDF_HKDF_MODE_EXTRACT_AND_EXPAND
&& n != EVP_KDF_HKDF_MODE_EXTRACT_ONLY
&& n != EVP_KDF_HKDF_MODE_EXPAND_ONLY) {
ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_MODE);
return 0;
}
ctx->mode = n;
} else {
ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_MODE);
return 0;
}
}
if ((p = OSSL_PARAM_locate_const(params, OSSL_KDF_PARAM_KEY)) != NULL) {
OPENSSL_clear_free(ctx->key, ctx->key_len);
ctx->key = NULL;
if (!OSSL_PARAM_get_octet_string(p, (void **)&ctx->key, 0,
&ctx->key_len))
return 0;
}
if ((p = OSSL_PARAM_locate_const(params, OSSL_KDF_PARAM_SALT)) != NULL) {
if (p->data_size != 0 && p->data != NULL) {
OPENSSL_free(ctx->salt);
ctx->salt = NULL;
if (!OSSL_PARAM_get_octet_string(p, (void **)&ctx->salt, 0,
&ctx->salt_len))
return 0;
}
}
return 1;
}
/*
* Use WPACKET to concat one or more OSSL_KDF_PARAM_INFO fields into a fixed
* out buffer of size *outlen.
* If out is NULL then outlen is used to return the required buffer size.
*/
static int setinfo_fromparams(const OSSL_PARAM *p, unsigned char *out, size_t *outlen)
{
int ret = 0;
WPACKET pkt;
if (out == NULL) {
if (!WPACKET_init_null(&pkt, 0))
return 0;
} else {
if (!WPACKET_init_static_len(&pkt, out, *outlen, 0))
return 0;
}
for (; p != NULL; p = OSSL_PARAM_locate_const(p + 1, OSSL_KDF_PARAM_INFO)) {
if (p->data_type != OSSL_PARAM_OCTET_STRING)
goto err;
if (p->data != NULL
&& p->data_size != 0
&& !WPACKET_memcpy(&pkt, p->data, p->data_size))
goto err;
}
if (!WPACKET_get_total_written(&pkt, outlen)
|| !WPACKET_finish(&pkt))
goto err;
ret = 1;
err:
WPACKET_cleanup(&pkt);
return ret;
}
static int kdf_hkdf_set_ctx_params(void *vctx, const OSSL_PARAM params[])
{
const OSSL_PARAM *p;
KDF_HKDF *ctx = vctx;
if (params == NULL)
return 1;
if (!hkdf_common_set_ctx_params(ctx, params))
return 0;
/* The info fields concatenate, so process them all */
if ((p = OSSL_PARAM_locate_const(params, OSSL_KDF_PARAM_INFO)) != NULL) {
size_t sz = 0;
/* calculate the total size */
if (!setinfo_fromparams(p, NULL, &sz))
return 0;
if (sz > HKDF_MAXINFO)
return 0;
OPENSSL_clear_free(ctx->info, ctx->info_len);
ctx->info = NULL;
if (sz == 0)
return 1;
/* Alloc the buffer */
ctx->info = OPENSSL_malloc(sz);
if (ctx->info == NULL)
return 0;
ctx->info_len = sz;
/* Concat one or more OSSL_KDF_PARAM_INFO fields */
if (!setinfo_fromparams(p, ctx->info, &sz))
return 0;
}
return 1;
}
static const OSSL_PARAM *kdf_hkdf_settable_ctx_params(ossl_unused void *ctx,
ossl_unused void *provctx)
{
static const OSSL_PARAM known_settable_ctx_params[] = {
HKDF_COMMON_SETTABLES,
OSSL_PARAM_octet_string(OSSL_KDF_PARAM_INFO, NULL, 0),
OSSL_PARAM_END
};
return known_settable_ctx_params;
}
static int kdf_hkdf_get_ctx_params(void *vctx, OSSL_PARAM params[])
{
KDF_HKDF *ctx = (KDF_HKDF *)vctx;
OSSL_PARAM *p;
if ((p = OSSL_PARAM_locate(params, OSSL_KDF_PARAM_SIZE)) != NULL) {
size_t sz = kdf_hkdf_size(ctx);
if (sz == 0)
return 0;
return OSSL_PARAM_set_size_t(p, sz);
}
+ if ((p = OSSL_PARAM_locate(params, OSSL_KDF_PARAM_INFO)) != NULL) {
+ if (ctx->info == NULL || ctx->info_len == 0) {
+ p->return_size = 0;
+ return 1;
+ }
+ return OSSL_PARAM_set_octet_string(p, ctx->info, ctx->info_len);
+ }
return -2;
}
static const OSSL_PARAM *kdf_hkdf_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_octet_string(OSSL_KDF_PARAM_INFO, NULL, 0),
OSSL_PARAM_END
};
return known_gettable_ctx_params;
}
const OSSL_DISPATCH ossl_kdf_hkdf_functions[] = {
{ OSSL_FUNC_KDF_NEWCTX, (void(*)(void))kdf_hkdf_new },
{ OSSL_FUNC_KDF_FREECTX, (void(*)(void))kdf_hkdf_free },
{ OSSL_FUNC_KDF_RESET, (void(*)(void))kdf_hkdf_reset },
{ OSSL_FUNC_KDF_DERIVE, (void(*)(void))kdf_hkdf_derive },
{ OSSL_FUNC_KDF_SETTABLE_CTX_PARAMS,
(void(*)(void))kdf_hkdf_settable_ctx_params },
{ OSSL_FUNC_KDF_SET_CTX_PARAMS, (void(*)(void))kdf_hkdf_set_ctx_params },
{ OSSL_FUNC_KDF_GETTABLE_CTX_PARAMS,
(void(*)(void))kdf_hkdf_gettable_ctx_params },
{ OSSL_FUNC_KDF_GET_CTX_PARAMS, (void(*)(void))kdf_hkdf_get_ctx_params },
{ 0, NULL }
};
/*
* Refer to "HMAC-based Extract-and-Expand Key Derivation Function (HKDF)"
* Section 2 (https://tools.ietf.org/html/rfc5869#section-2) and
* "Cryptographic Extraction and Key Derivation: The HKDF Scheme"
* Section 4.2 (https://eprint.iacr.org/2010/264.pdf).
*
* From the paper:
* The scheme HKDF is specified as:
* HKDF(XTS, SKM, CTXinfo, L) = K(1) | K(2) | ... | K(t)
*
* where:
* SKM is source key material
* XTS is extractor salt (which may be null or constant)
* CTXinfo is context information (may be null)
* L is the number of key bits to be produced by KDF
* k is the output length in bits of the hash function used with HMAC
* t = ceil(L/k)
* the value K(t) is truncated to its first d = L mod k bits.
*
* From RFC 5869:
* 2.2. Step 1: Extract
* HKDF-Extract(salt, IKM) -> PRK
* 2.3. Step 2: Expand
* HKDF-Expand(PRK, info, L) -> OKM
*/
static int HKDF(OSSL_LIB_CTX *libctx, const EVP_MD *evp_md,
const unsigned char *salt, size_t salt_len,
const unsigned char *ikm, size_t ikm_len,
const unsigned char *info, size_t info_len,
unsigned char *okm, size_t okm_len)
{
unsigned char prk[EVP_MAX_MD_SIZE];
int ret, sz;
size_t prk_len;
sz = EVP_MD_get_size(evp_md);
if (sz < 0)
return 0;
prk_len = (size_t)sz;
/* Step 1: HKDF-Extract(salt, IKM) -> PRK */
if (!HKDF_Extract(libctx, evp_md,
salt, salt_len, ikm, ikm_len, prk, prk_len))
return 0;
/* Step 2: HKDF-Expand(PRK, info, L) -> OKM */
ret = HKDF_Expand(evp_md, prk, prk_len, info, info_len, okm, okm_len);
OPENSSL_cleanse(prk, sizeof(prk));
return ret;
}
/*
* Refer to "HMAC-based Extract-and-Expand Key Derivation Function (HKDF)"
* Section 2.2 (https://tools.ietf.org/html/rfc5869#section-2.2).
*
* 2.2. Step 1: Extract
*
* HKDF-Extract(salt, IKM) -> PRK
*
* Options:
* Hash a hash function; HashLen denotes the length of the
* hash function output in octets
*
* Inputs:
* salt optional salt value (a non-secret random value);
* if not provided, it is set to a string of HashLen zeros.
* IKM input keying material
*
* Output:
* PRK a pseudorandom key (of HashLen octets)
*
* The output PRK is calculated as follows:
*
* PRK = HMAC-Hash(salt, IKM)
*/
static int HKDF_Extract(OSSL_LIB_CTX *libctx, const EVP_MD *evp_md,
const unsigned char *salt, size_t salt_len,
const unsigned char *ikm, size_t ikm_len,
unsigned char *prk, size_t prk_len)
{
int sz = EVP_MD_get_size(evp_md);
if (sz < 0)
return 0;
if (prk_len != (size_t)sz) {
ERR_raise(ERR_LIB_PROV, PROV_R_WRONG_OUTPUT_BUFFER_SIZE);
return 0;
}
/* calc: PRK = HMAC-Hash(salt, IKM) */
return
EVP_Q_mac(libctx, "HMAC", NULL, EVP_MD_get0_name(evp_md), NULL, salt,
salt_len, ikm, ikm_len, prk, EVP_MD_get_size(evp_md), NULL)
!= NULL;
}
/*
* Refer to "HMAC-based Extract-and-Expand Key Derivation Function (HKDF)"
* Section 2.3 (https://tools.ietf.org/html/rfc5869#section-2.3).
*
* 2.3. Step 2: Expand
*
* HKDF-Expand(PRK, info, L) -> OKM
*
* Options:
* Hash a hash function; HashLen denotes the length of the
* hash function output in octets
*
* Inputs:
* PRK a pseudorandom key of at least HashLen octets
* (usually, the output from the extract step)
* info optional context and application specific information
* (can be a zero-length string)
* L length of output keying material in octets
* (<= 255*HashLen)
*
* Output:
* OKM output keying material (of L octets)
*
* The output OKM is calculated as follows:
*
* N = ceil(L/HashLen)
* T = T(1) | T(2) | T(3) | ... | T(N)
* OKM = first L octets of T
*
* where:
* T(0) = empty string (zero length)
* T(1) = HMAC-Hash(PRK, T(0) | info | 0x01)
* T(2) = HMAC-Hash(PRK, T(1) | info | 0x02)
* T(3) = HMAC-Hash(PRK, T(2) | info | 0x03)
* ...
*
* (where the constant concatenated to the end of each T(n) is a
* single octet.)
*/
static int HKDF_Expand(const EVP_MD *evp_md,
const unsigned char *prk, size_t prk_len,
const unsigned char *info, size_t info_len,
unsigned char *okm, size_t okm_len)
{
HMAC_CTX *hmac;
int ret = 0, sz;
unsigned int i;
unsigned char prev[EVP_MAX_MD_SIZE];
size_t done_len = 0, dig_len, n;
sz = EVP_MD_get_size(evp_md);
if (sz <= 0)
return 0;
dig_len = (size_t)sz;
/* calc: N = ceil(L/HashLen) */
n = okm_len / dig_len;
if (okm_len % dig_len)
n++;
if (n > 255 || okm == NULL)
return 0;
if ((hmac = HMAC_CTX_new()) == NULL)
return 0;
if (!HMAC_Init_ex(hmac, prk, prk_len, evp_md, NULL))
goto err;
for (i = 1; i <= n; i++) {
size_t copy_len;
const unsigned char ctr = i;
/* calc: T(i) = HMAC-Hash(PRK, T(i - 1) | info | i) */
if (i > 1) {
if (!HMAC_Init_ex(hmac, NULL, 0, NULL, NULL))
goto err;
if (!HMAC_Update(hmac, prev, dig_len))
goto err;
}
if (!HMAC_Update(hmac, info, info_len))
goto err;
if (!HMAC_Update(hmac, &ctr, 1))
goto err;
if (!HMAC_Final(hmac, prev, NULL))
goto err;
copy_len = (dig_len > okm_len - done_len) ?
okm_len - done_len :
dig_len;
memcpy(okm + done_len, prev, copy_len);
done_len += copy_len;
}
ret = 1;
err:
OPENSSL_cleanse(prev, sizeof(prev));
HMAC_CTX_free(hmac);
return ret;
}
/*
* TLS uses slight variations of the above and for FIPS validation purposes,
* they need to be present here.
* Refer to RFC 8446 section 7 for specific details.
*/
/*
* Given a |secret|; a |label| of length |labellen|; and |data| of length
* |datalen| (e.g. typically a hash of the handshake messages), derive a new
* secret |outlen| bytes long and store it in the location pointed to be |out|.
* The |data| value may be zero length. Returns 1 on success and 0 on failure.
*/
static int prov_tls13_hkdf_expand(const EVP_MD *md,
const unsigned char *key, size_t keylen,
const unsigned char *prefix, size_t prefixlen,
const unsigned char *label, size_t labellen,
const unsigned char *data, size_t datalen,
unsigned char *out, size_t outlen)
{
size_t hkdflabellen;
unsigned char hkdflabel[HKDF_MAXBUF];
WPACKET pkt;
/*
* 2 bytes for length of derived secret + 1 byte for length of combined
* prefix and label + bytes for the label itself + 1 byte length of hash
* + bytes for the hash itself. We've got the maximum the KDF can handle
* which should always be sufficient.
*/
if (!WPACKET_init_static_len(&pkt, hkdflabel, sizeof(hkdflabel), 0)
|| !WPACKET_put_bytes_u16(&pkt, outlen)
|| !WPACKET_start_sub_packet_u8(&pkt)
|| !WPACKET_memcpy(&pkt, prefix, prefixlen)
|| !WPACKET_memcpy(&pkt, label, labellen)
|| !WPACKET_close(&pkt)
|| !WPACKET_sub_memcpy_u8(&pkt, data, (data == NULL) ? 0 : datalen)
|| !WPACKET_get_total_written(&pkt, &hkdflabellen)
|| !WPACKET_finish(&pkt)) {
WPACKET_cleanup(&pkt);
return 0;
}
return HKDF_Expand(md, key, keylen, hkdflabel, hkdflabellen,
out, outlen);
}
static int prov_tls13_hkdf_generate_secret(OSSL_LIB_CTX *libctx,
const EVP_MD *md,
const unsigned char *prevsecret,
size_t prevsecretlen,
const unsigned char *insecret,
size_t insecretlen,
const unsigned char *prefix,
size_t prefixlen,
const unsigned char *label,
size_t labellen,
unsigned char *out, size_t outlen)
{
size_t mdlen;
int ret;
unsigned char preextractsec[EVP_MAX_MD_SIZE];
/* Always filled with zeros */
static const unsigned char default_zeros[EVP_MAX_MD_SIZE];
ret = EVP_MD_get_size(md);
/* Ensure cast to size_t is safe */
if (ret <= 0)
return 0;
mdlen = (size_t)ret;
if (insecret == NULL) {
insecret = default_zeros;
insecretlen = mdlen;
}
if (prevsecret == NULL) {
prevsecret = default_zeros;
prevsecretlen = 0;
} else {
EVP_MD_CTX *mctx = EVP_MD_CTX_new();
unsigned char hash[EVP_MAX_MD_SIZE];
/* The pre-extract derive step uses a hash of no messages */
if (mctx == NULL
|| EVP_DigestInit_ex(mctx, md, NULL) <= 0
|| EVP_DigestFinal_ex(mctx, hash, NULL) <= 0) {
EVP_MD_CTX_free(mctx);
return 0;
}
EVP_MD_CTX_free(mctx);
/* Generate the pre-extract secret */
if (!prov_tls13_hkdf_expand(md, prevsecret, mdlen,
prefix, prefixlen, label, labellen,
hash, mdlen, preextractsec, mdlen))
return 0;
prevsecret = preextractsec;
prevsecretlen = mdlen;
}
ret = HKDF_Extract(libctx, md, prevsecret, prevsecretlen,
insecret, insecretlen, out, outlen);
if (prevsecret == preextractsec)
OPENSSL_cleanse(preextractsec, mdlen);
return ret;
}
static int kdf_tls1_3_derive(void *vctx, unsigned char *key, size_t keylen,
const OSSL_PARAM params[])
{
KDF_HKDF *ctx = (KDF_HKDF *)vctx;
const EVP_MD *md;
if (!ossl_prov_is_running() || !kdf_tls1_3_set_ctx_params(ctx, params))
return 0;
md = ossl_prov_digest_md(&ctx->digest);
if (md == NULL) {
ERR_raise(ERR_LIB_PROV, PROV_R_MISSING_MESSAGE_DIGEST);
return 0;
}
switch (ctx->mode) {
default:
return 0;
case EVP_KDF_HKDF_MODE_EXTRACT_ONLY:
return prov_tls13_hkdf_generate_secret(PROV_LIBCTX_OF(ctx->provctx),
md,
ctx->salt, ctx->salt_len,
ctx->key, ctx->key_len,
ctx->prefix, ctx->prefix_len,
ctx->label, ctx->label_len,
key, keylen);
case EVP_KDF_HKDF_MODE_EXPAND_ONLY:
return prov_tls13_hkdf_expand(md, ctx->key, ctx->key_len,
ctx->prefix, ctx->prefix_len,
ctx->label, ctx->label_len,
ctx->data, ctx->data_len,
key, keylen);
}
}
static int kdf_tls1_3_set_ctx_params(void *vctx, const OSSL_PARAM params[])
{
const OSSL_PARAM *p;
KDF_HKDF *ctx = vctx;
if (params == NULL)
return 1;
if (!hkdf_common_set_ctx_params(ctx, params))
return 0;
if (ctx->mode == EVP_KDF_HKDF_MODE_EXTRACT_AND_EXPAND) {
ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_MODE);
return 0;
}
if ((p = OSSL_PARAM_locate_const(params, OSSL_KDF_PARAM_PREFIX)) != NULL) {
OPENSSL_free(ctx->prefix);
ctx->prefix = NULL;
if (!OSSL_PARAM_get_octet_string(p, (void **)&ctx->prefix, 0,
&ctx->prefix_len))
return 0;
}
if ((p = OSSL_PARAM_locate_const(params, OSSL_KDF_PARAM_LABEL)) != NULL) {
OPENSSL_free(ctx->label);
ctx->label = NULL;
if (!OSSL_PARAM_get_octet_string(p, (void **)&ctx->label, 0,
&ctx->label_len))
return 0;
}
OPENSSL_clear_free(ctx->data, ctx->data_len);
ctx->data = NULL;
if ((p = OSSL_PARAM_locate_const(params, OSSL_KDF_PARAM_DATA)) != NULL
&& !OSSL_PARAM_get_octet_string(p, (void **)&ctx->data, 0,
&ctx->data_len))
return 0;
return 1;
}
static const OSSL_PARAM *kdf_tls1_3_settable_ctx_params(ossl_unused void *ctx,
ossl_unused void *provctx)
{
static const OSSL_PARAM known_settable_ctx_params[] = {
HKDF_COMMON_SETTABLES,
OSSL_PARAM_octet_string(OSSL_KDF_PARAM_PREFIX, NULL, 0),
OSSL_PARAM_octet_string(OSSL_KDF_PARAM_LABEL, NULL, 0),
OSSL_PARAM_octet_string(OSSL_KDF_PARAM_DATA, NULL, 0),
OSSL_PARAM_END
};
return known_settable_ctx_params;
}
const OSSL_DISPATCH ossl_kdf_tls1_3_kdf_functions[] = {
{ OSSL_FUNC_KDF_NEWCTX, (void(*)(void))kdf_hkdf_new },
{ OSSL_FUNC_KDF_FREECTX, (void(*)(void))kdf_hkdf_free },
{ OSSL_FUNC_KDF_RESET, (void(*)(void))kdf_hkdf_reset },
{ OSSL_FUNC_KDF_DERIVE, (void(*)(void))kdf_tls1_3_derive },
{ OSSL_FUNC_KDF_SETTABLE_CTX_PARAMS,
(void(*)(void))kdf_tls1_3_settable_ctx_params },
{ OSSL_FUNC_KDF_SET_CTX_PARAMS, (void(*)(void))kdf_tls1_3_set_ctx_params },
{ OSSL_FUNC_KDF_GETTABLE_CTX_PARAMS,
(void(*)(void))kdf_hkdf_gettable_ctx_params },
{ OSSL_FUNC_KDF_GET_CTX_PARAMS, (void(*)(void))kdf_hkdf_get_ctx_params },
{ 0, NULL }
};
diff --git a/crypto/openssl/providers/implementations/rands/drbg.c b/crypto/openssl/providers/implementations/rands/drbg.c
index e30836c53cab..41ff2a8e33f6 100644
--- a/crypto/openssl/providers/implementations/rands/drbg.c
+++ b/crypto/openssl/providers/implementations/rands/drbg.c
@@ -1,934 +1,935 @@
/*
- * Copyright 2011-2023 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2011-2024 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 <string.h>
#include <openssl/crypto.h>
#include <openssl/err.h>
#include <openssl/rand.h>
#include <openssl/evp.h>
#include "crypto/rand.h"
#include <openssl/proverr.h>
#include "drbg_local.h"
#include "internal/thread_once.h"
#include "crypto/cryptlib.h"
#include "prov/seeding.h"
#include "crypto/rand_pool.h"
#include "prov/provider_ctx.h"
#include "prov/providercommon.h"
/*
* Support framework for NIST SP 800-90A DRBG
*
* See manual page PROV_DRBG(7) for a general overview.
*
* The OpenSSL model is to have new and free functions, and that new
* does all initialization. That is not the NIST model, which has
* instantiation and un-instantiate, and re-use within a new/free
* lifecycle. (No doubt this comes from the desire to support hardware
* DRBG, where allocation of resources on something like an HSM is
* a much bigger deal than just re-setting an allocated resource.)
*/
/* NIST SP 800-90A DRBG recommends the use of a personalization string. */
static const char ossl_pers_string[] = DRBG_DEFAULT_PERS_STRING;
static const OSSL_DISPATCH *find_call(const OSSL_DISPATCH *dispatch,
int function);
static int rand_drbg_restart(PROV_DRBG *drbg);
int ossl_drbg_lock(void *vctx)
{
PROV_DRBG *drbg = vctx;
if (drbg == NULL || drbg->lock == NULL)
return 1;
return CRYPTO_THREAD_write_lock(drbg->lock);
}
void ossl_drbg_unlock(void *vctx)
{
PROV_DRBG *drbg = vctx;
if (drbg != NULL && drbg->lock != NULL)
CRYPTO_THREAD_unlock(drbg->lock);
}
static int ossl_drbg_lock_parent(PROV_DRBG *drbg)
{
void *parent = drbg->parent;
if (parent != NULL
&& drbg->parent_lock != NULL
&& !drbg->parent_lock(parent)) {
ERR_raise(ERR_LIB_PROV, PROV_R_PARENT_LOCKING_NOT_ENABLED);
return 0;
}
return 1;
}
static void ossl_drbg_unlock_parent(PROV_DRBG *drbg)
{
void *parent = drbg->parent;
if (parent != NULL && drbg->parent_unlock != NULL)
drbg->parent_unlock(parent);
}
static int get_parent_strength(PROV_DRBG *drbg, unsigned int *str)
{
OSSL_PARAM params[2] = { OSSL_PARAM_END, OSSL_PARAM_END };
void *parent = drbg->parent;
int res;
if (drbg->parent_get_ctx_params == NULL) {
ERR_raise(ERR_LIB_PROV, PROV_R_UNABLE_TO_GET_PARENT_STRENGTH);
return 0;
}
*params = OSSL_PARAM_construct_uint(OSSL_RAND_PARAM_STRENGTH, str);
if (!ossl_drbg_lock_parent(drbg)) {
ERR_raise(ERR_LIB_PROV, PROV_R_UNABLE_TO_LOCK_PARENT);
return 0;
}
res = drbg->parent_get_ctx_params(parent, params);
ossl_drbg_unlock_parent(drbg);
if (!res) {
ERR_raise(ERR_LIB_PROV, PROV_R_UNABLE_TO_GET_PARENT_STRENGTH);
return 0;
}
return 1;
}
static unsigned int get_parent_reseed_count(PROV_DRBG *drbg)
{
OSSL_PARAM params[2] = { OSSL_PARAM_END, OSSL_PARAM_END };
void *parent = drbg->parent;
unsigned int r = 0;
*params = OSSL_PARAM_construct_uint(OSSL_DRBG_PARAM_RESEED_COUNTER, &r);
if (!ossl_drbg_lock_parent(drbg)) {
ERR_raise(ERR_LIB_PROV, PROV_R_UNABLE_TO_LOCK_PARENT);
goto err;
}
if (!drbg->parent_get_ctx_params(parent, params))
r = 0;
ossl_drbg_unlock_parent(drbg);
return r;
err:
r = tsan_load(&drbg->reseed_counter) - 2;
if (r == 0)
r = UINT_MAX;
return r;
}
/*
* Implements the get_entropy() callback
*
* If the DRBG has a parent, then the required amount of entropy input
* is fetched using the parent's ossl_prov_drbg_generate().
*
* Otherwise, the entropy is polled from the system entropy sources
* using ossl_pool_acquire_entropy().
*
* If a random pool has been added to the DRBG using RAND_add(), then
* its entropy will be used up first.
*/
size_t ossl_drbg_get_seed(void *vdrbg, unsigned char **pout,
int entropy, size_t min_len,
size_t max_len, int prediction_resistance,
const unsigned char *adin, size_t adin_len)
{
PROV_DRBG *drbg = (PROV_DRBG *)vdrbg;
size_t bytes_needed;
unsigned char *buffer;
/* Figure out how many bytes we need */
bytes_needed = entropy >= 0 ? (entropy + 7) / 8 : 0;
if (bytes_needed < min_len)
bytes_needed = min_len;
if (bytes_needed > max_len)
bytes_needed = max_len;
/* Allocate storage */
buffer = OPENSSL_secure_malloc(bytes_needed);
if (buffer == NULL) {
ERR_raise(ERR_LIB_PROV, ERR_R_MALLOC_FAILURE);
return 0;
}
/*
* Get random data. Include our DRBG address as
* additional input, in order to provide a distinction between
* different DRBG child instances.
*
* Note: using the sizeof() operator on a pointer triggers
* a warning in some static code analyzers, but it's
* intentional and correct here.
*/
if (!ossl_prov_drbg_generate(drbg, buffer, bytes_needed,
drbg->strength, prediction_resistance,
(unsigned char *)&drbg, sizeof(drbg))) {
OPENSSL_secure_clear_free(buffer, bytes_needed);
ERR_raise(ERR_LIB_PROV, PROV_R_GENERATE_ERROR);
return 0;
}
*pout = buffer;
return bytes_needed;
}
/* Implements the cleanup_entropy() callback */
void ossl_drbg_clear_seed(ossl_unused void *vdrbg,
unsigned char *out, size_t outlen)
{
OPENSSL_secure_clear_free(out, outlen);
}
static size_t get_entropy(PROV_DRBG *drbg, unsigned char **pout, int entropy,
size_t min_len, size_t max_len,
int prediction_resistance)
{
size_t bytes;
unsigned int p_str;
if (drbg->parent == NULL)
#ifdef FIPS_MODULE
return ossl_crngt_get_entropy(drbg, pout, entropy, min_len, max_len,
prediction_resistance);
#else
return ossl_prov_get_entropy(drbg->provctx, pout, entropy, min_len,
max_len);
#endif
if (drbg->parent_get_seed == NULL) {
ERR_raise(ERR_LIB_PROV, PROV_R_PARENT_CANNOT_SUPPLY_ENTROPY_SEED);
return 0;
}
if (!get_parent_strength(drbg, &p_str))
return 0;
if (drbg->strength > p_str) {
/*
* We currently don't support the algorithm from NIST SP 800-90C
* 10.1.2 to use a weaker DRBG as source
*/
ERR_raise(ERR_LIB_PROV, PROV_R_PARENT_STRENGTH_TOO_WEAK);
return 0;
}
/*
* Our lock is already held, but we need to lock our parent before
* generating bits from it. Note: taking the lock will be a no-op
* if locking is not required (while drbg->parent->lock == NULL).
*/
if (!ossl_drbg_lock_parent(drbg))
return 0;
/*
* Get random data from parent. Include our DRBG address as
* additional input, in order to provide a distinction between
* different DRBG child instances.
*
* Note: using the sizeof() operator on a pointer triggers
* a warning in some static code analyzers, but it's
* intentional and correct here.
*/
bytes = drbg->parent_get_seed(drbg->parent, pout, drbg->strength,
min_len, max_len, prediction_resistance,
(unsigned char *)&drbg, sizeof(drbg));
ossl_drbg_unlock_parent(drbg);
return bytes;
}
static void cleanup_entropy(PROV_DRBG *drbg, unsigned char *out, size_t outlen)
{
if (drbg->parent == NULL) {
#ifdef FIPS_MODULE
ossl_crngt_cleanup_entropy(drbg, out, outlen);
#else
ossl_prov_cleanup_entropy(drbg->provctx, out, outlen);
#endif
} else if (drbg->parent_clear_seed != NULL) {
if (!ossl_drbg_lock_parent(drbg))
return;
drbg->parent_clear_seed(drbg->parent, out, outlen);
ossl_drbg_unlock_parent(drbg);
}
}
#ifndef PROV_RAND_GET_RANDOM_NONCE
typedef struct prov_drbg_nonce_global_st {
CRYPTO_RWLOCK *rand_nonce_lock;
int rand_nonce_count;
} PROV_DRBG_NONCE_GLOBAL;
/*
* drbg_ossl_ctx_new() calls drgb_setup() which calls rand_drbg_get_nonce()
* which needs to get the rand_nonce_lock out of the OSSL_LIB_CTX...but since
* drbg_ossl_ctx_new() hasn't finished running yet we need the rand_nonce_lock
* to be in a different global data object. Otherwise we will go into an
* infinite recursion loop.
*/
static void *prov_drbg_nonce_ossl_ctx_new(OSSL_LIB_CTX *libctx)
{
PROV_DRBG_NONCE_GLOBAL *dngbl = OPENSSL_zalloc(sizeof(*dngbl));
if (dngbl == NULL)
return NULL;
dngbl->rand_nonce_lock = CRYPTO_THREAD_lock_new();
if (dngbl->rand_nonce_lock == NULL) {
OPENSSL_free(dngbl);
return NULL;
}
return dngbl;
}
static void prov_drbg_nonce_ossl_ctx_free(void *vdngbl)
{
PROV_DRBG_NONCE_GLOBAL *dngbl = vdngbl;
if (dngbl == NULL)
return;
CRYPTO_THREAD_lock_free(dngbl->rand_nonce_lock);
OPENSSL_free(dngbl);
}
static const OSSL_LIB_CTX_METHOD drbg_nonce_ossl_ctx_method = {
OSSL_LIB_CTX_METHOD_DEFAULT_PRIORITY,
prov_drbg_nonce_ossl_ctx_new,
prov_drbg_nonce_ossl_ctx_free,
};
/* Get a nonce from the operating system */
static size_t prov_drbg_get_nonce(PROV_DRBG *drbg, unsigned char **pout,
size_t min_len, size_t max_len)
{
size_t ret = 0, n;
unsigned char *buf = NULL;
OSSL_LIB_CTX *libctx = ossl_prov_ctx_get0_libctx(drbg->provctx);
PROV_DRBG_NONCE_GLOBAL *dngbl
= ossl_lib_ctx_get_data(libctx, OSSL_LIB_CTX_DRBG_NONCE_INDEX,
&drbg_nonce_ossl_ctx_method);
struct {
void *drbg;
int count;
} data;
if (dngbl == NULL)
return 0;
if (drbg->parent != NULL && drbg->parent_nonce != NULL) {
n = drbg->parent_nonce(drbg->parent, NULL, 0, drbg->min_noncelen,
drbg->max_noncelen);
if (n > 0 && (buf = OPENSSL_malloc(n)) != NULL) {
ret = drbg->parent_nonce(drbg->parent, buf, 0,
drbg->min_noncelen, drbg->max_noncelen);
if (ret == n) {
*pout = buf;
return ret;
}
OPENSSL_free(buf);
}
}
/* Use the built in nonce source plus some of our specifics */
memset(&data, 0, sizeof(data));
data.drbg = drbg;
CRYPTO_atomic_add(&dngbl->rand_nonce_count, 1, &data.count,
dngbl->rand_nonce_lock);
return ossl_prov_get_nonce(drbg->provctx, pout, min_len, max_len,
&data, sizeof(data));
}
#endif /* PROV_RAND_GET_RANDOM_NONCE */
/*
* Instantiate |drbg|, after it has been initialized. Use |pers| and
* |perslen| as prediction-resistance input.
*
* Requires that drbg->lock is already locked for write, if non-null.
*
* Returns 1 on success, 0 on failure.
*/
int ossl_prov_drbg_instantiate(PROV_DRBG *drbg, unsigned int strength,
int prediction_resistance,
const unsigned char *pers, size_t perslen)
{
unsigned char *nonce = NULL, *entropy = NULL;
size_t noncelen = 0, entropylen = 0;
size_t min_entropy, min_entropylen, max_entropylen;
if (strength > drbg->strength) {
ERR_raise(ERR_LIB_PROV, PROV_R_INSUFFICIENT_DRBG_STRENGTH);
goto end;
}
min_entropy = drbg->strength;
min_entropylen = drbg->min_entropylen;
max_entropylen = drbg->max_entropylen;
if (pers == NULL) {
pers = (const unsigned char *)ossl_pers_string;
perslen = sizeof(ossl_pers_string);
}
if (perslen > drbg->max_perslen) {
ERR_raise(ERR_LIB_PROV, PROV_R_PERSONALISATION_STRING_TOO_LONG);
goto end;
}
if (drbg->state != EVP_RAND_STATE_UNINITIALISED) {
if (drbg->state == EVP_RAND_STATE_ERROR)
ERR_raise(ERR_LIB_PROV, PROV_R_IN_ERROR_STATE);
else
ERR_raise(ERR_LIB_PROV, PROV_R_ALREADY_INSTANTIATED);
goto end;
}
drbg->state = EVP_RAND_STATE_ERROR;
if (drbg->min_noncelen > 0) {
if (drbg->parent_nonce != NULL) {
noncelen = drbg->parent_nonce(drbg->parent, NULL, drbg->strength,
drbg->min_noncelen,
drbg->max_noncelen);
if (noncelen == 0) {
ERR_raise(ERR_LIB_PROV, PROV_R_ERROR_RETRIEVING_NONCE);
goto end;
}
nonce = OPENSSL_malloc(noncelen);
if (nonce == NULL) {
ERR_raise(ERR_LIB_PROV, PROV_R_ERROR_RETRIEVING_NONCE);
goto end;
}
if (noncelen != drbg->parent_nonce(drbg->parent, nonce,
drbg->strength,
drbg->min_noncelen,
drbg->max_noncelen)) {
ERR_raise(ERR_LIB_PROV, PROV_R_ERROR_RETRIEVING_NONCE);
goto end;
}
#ifndef PROV_RAND_GET_RANDOM_NONCE
} else if (drbg->parent != NULL) {
#endif
/*
* NIST SP800-90Ar1 section 9.1 says you can combine getting
* the entropy and nonce in 1 call by increasing the entropy
* with 50% and increasing the minimum length to accommodate
* the length of the nonce. We do this in case a nonce is
* required and there is no parental nonce capability.
*/
min_entropy += drbg->strength / 2;
min_entropylen += drbg->min_noncelen;
max_entropylen += drbg->max_noncelen;
}
#ifndef PROV_RAND_GET_RANDOM_NONCE
else { /* parent == NULL */
noncelen = prov_drbg_get_nonce(drbg, &nonce, drbg->min_noncelen,
drbg->max_noncelen);
if (noncelen < drbg->min_noncelen
|| noncelen > drbg->max_noncelen) {
ERR_raise(ERR_LIB_PROV, PROV_R_ERROR_RETRIEVING_NONCE);
goto end;
}
}
#endif
}
drbg->reseed_next_counter = tsan_load(&drbg->reseed_counter);
if (drbg->reseed_next_counter) {
drbg->reseed_next_counter++;
if (!drbg->reseed_next_counter)
drbg->reseed_next_counter = 1;
}
entropylen = get_entropy(drbg, &entropy, min_entropy,
min_entropylen, max_entropylen,
prediction_resistance);
if (entropylen < min_entropylen
|| entropylen > max_entropylen) {
ERR_raise(ERR_LIB_PROV, PROV_R_ERROR_RETRIEVING_ENTROPY);
goto end;
}
if (!drbg->instantiate(drbg, entropy, entropylen, nonce, noncelen,
pers, perslen)) {
cleanup_entropy(drbg, entropy, entropylen);
ERR_raise(ERR_LIB_PROV, PROV_R_ERROR_INSTANTIATING_DRBG);
goto end;
}
cleanup_entropy(drbg, entropy, entropylen);
drbg->state = EVP_RAND_STATE_READY;
drbg->generate_counter = 1;
drbg->reseed_time = time(NULL);
tsan_store(&drbg->reseed_counter, drbg->reseed_next_counter);
end:
if (nonce != NULL)
ossl_prov_cleanup_nonce(drbg->provctx, nonce, noncelen);
if (drbg->state == EVP_RAND_STATE_READY)
return 1;
return 0;
}
/*
* Uninstantiate |drbg|. Must be instantiated before it can be used.
*
* Requires that drbg->lock is already locked for write, if non-null.
*
* Returns 1 on success, 0 on failure.
*/
int ossl_prov_drbg_uninstantiate(PROV_DRBG *drbg)
{
drbg->state = EVP_RAND_STATE_UNINITIALISED;
return 1;
}
/*
* Reseed |drbg|, mixing in the specified data
*
* Requires that drbg->lock is already locked for write, if non-null.
*
* Returns 1 on success, 0 on failure.
*/
int ossl_prov_drbg_reseed(PROV_DRBG *drbg, int prediction_resistance,
const unsigned char *ent, size_t ent_len,
const unsigned char *adin, size_t adinlen)
{
unsigned char *entropy = NULL;
size_t entropylen = 0;
if (!ossl_prov_is_running())
return 0;
if (drbg->state != EVP_RAND_STATE_READY) {
/* try to recover from previous errors */
rand_drbg_restart(drbg);
if (drbg->state == EVP_RAND_STATE_ERROR) {
ERR_raise(ERR_LIB_PROV, PROV_R_IN_ERROR_STATE);
return 0;
}
if (drbg->state == EVP_RAND_STATE_UNINITIALISED) {
ERR_raise(ERR_LIB_PROV, PROV_R_NOT_INSTANTIATED);
return 0;
}
}
if (ent != NULL) {
if (ent_len < drbg->min_entropylen) {
ERR_raise(ERR_LIB_RAND, RAND_R_ENTROPY_OUT_OF_RANGE);
drbg->state = EVP_RAND_STATE_ERROR;
return 0;
}
if (ent_len > drbg->max_entropylen) {
ERR_raise(ERR_LIB_RAND, RAND_R_ENTROPY_INPUT_TOO_LONG);
drbg->state = EVP_RAND_STATE_ERROR;
return 0;
}
}
if (adin == NULL) {
adinlen = 0;
} else if (adinlen > drbg->max_adinlen) {
ERR_raise(ERR_LIB_PROV, PROV_R_ADDITIONAL_INPUT_TOO_LONG);
return 0;
}
drbg->state = EVP_RAND_STATE_ERROR;
drbg->reseed_next_counter = tsan_load(&drbg->reseed_counter);
if (drbg->reseed_next_counter) {
drbg->reseed_next_counter++;
if (!drbg->reseed_next_counter)
drbg->reseed_next_counter = 1;
}
if (ent != NULL) {
#ifdef FIPS_MODULE
/*
* NIST SP-800-90A mandates that entropy *shall not* be provided
* by the consuming application. Instead the data is added as additional
* input.
*
* (NIST SP-800-90Ar1, Sections 9.1 and 9.2)
*/
if (!drbg->reseed(drbg, NULL, 0, ent, ent_len)) {
ERR_raise(ERR_LIB_PROV, PROV_R_UNABLE_TO_RESEED);
return 0;
}
#else
if (!drbg->reseed(drbg, ent, ent_len, adin, adinlen)) {
ERR_raise(ERR_LIB_PROV, PROV_R_UNABLE_TO_RESEED);
return 0;
}
/* There isn't much point adding the same additional input twice */
adin = NULL;
adinlen = 0;
#endif
}
/* Reseed using our sources in addition */
entropylen = get_entropy(drbg, &entropy, drbg->strength,
drbg->min_entropylen, drbg->max_entropylen,
prediction_resistance);
if (entropylen < drbg->min_entropylen
|| entropylen > drbg->max_entropylen) {
ERR_raise(ERR_LIB_PROV, PROV_R_ERROR_RETRIEVING_ENTROPY);
goto end;
}
if (!drbg->reseed(drbg, entropy, entropylen, adin, adinlen))
goto end;
drbg->state = EVP_RAND_STATE_READY;
drbg->generate_counter = 1;
drbg->reseed_time = time(NULL);
tsan_store(&drbg->reseed_counter, drbg->reseed_next_counter);
if (drbg->parent != NULL)
drbg->parent_reseed_counter = get_parent_reseed_count(drbg);
end:
cleanup_entropy(drbg, entropy, entropylen);
if (drbg->state == EVP_RAND_STATE_READY)
return 1;
return 0;
}
/*
* Generate |outlen| bytes into the buffer at |out|. Reseed if we need
* to or if |prediction_resistance| is set. Additional input can be
* sent in |adin| and |adinlen|.
*
* Requires that drbg->lock is already locked for write, if non-null.
*
* Returns 1 on success, 0 on failure.
*
*/
int ossl_prov_drbg_generate(PROV_DRBG *drbg, unsigned char *out, size_t outlen,
unsigned int strength, int prediction_resistance,
const unsigned char *adin, size_t adinlen)
{
int fork_id;
int reseed_required = 0;
if (!ossl_prov_is_running())
return 0;
if (drbg->state != EVP_RAND_STATE_READY) {
/* try to recover from previous errors */
rand_drbg_restart(drbg);
if (drbg->state == EVP_RAND_STATE_ERROR) {
ERR_raise(ERR_LIB_PROV, PROV_R_IN_ERROR_STATE);
return 0;
}
if (drbg->state == EVP_RAND_STATE_UNINITIALISED) {
ERR_raise(ERR_LIB_PROV, PROV_R_NOT_INSTANTIATED);
return 0;
}
}
if (strength > drbg->strength) {
ERR_raise(ERR_LIB_PROV, PROV_R_INSUFFICIENT_DRBG_STRENGTH);
return 0;
}
if (outlen > drbg->max_request) {
ERR_raise(ERR_LIB_PROV, PROV_R_REQUEST_TOO_LARGE_FOR_DRBG);
return 0;
}
if (adinlen > drbg->max_adinlen) {
ERR_raise(ERR_LIB_PROV, PROV_R_ADDITIONAL_INPUT_TOO_LONG);
return 0;
}
fork_id = openssl_get_fork_id();
if (drbg->fork_id != fork_id) {
drbg->fork_id = fork_id;
reseed_required = 1;
}
if (drbg->reseed_interval > 0) {
if (drbg->generate_counter >= drbg->reseed_interval)
reseed_required = 1;
}
if (drbg->reseed_time_interval > 0) {
time_t now = time(NULL);
if (now < drbg->reseed_time
|| now - drbg->reseed_time >= drbg->reseed_time_interval)
reseed_required = 1;
}
if (drbg->parent != NULL
&& get_parent_reseed_count(drbg) != drbg->parent_reseed_counter)
reseed_required = 1;
if (reseed_required || prediction_resistance) {
if (!ossl_prov_drbg_reseed(drbg, prediction_resistance, NULL, 0,
adin, adinlen)) {
ERR_raise(ERR_LIB_PROV, PROV_R_RESEED_ERROR);
return 0;
}
adin = NULL;
adinlen = 0;
}
if (!drbg->generate(drbg, out, outlen, adin, adinlen)) {
drbg->state = EVP_RAND_STATE_ERROR;
ERR_raise(ERR_LIB_PROV, PROV_R_GENERATE_ERROR);
return 0;
}
drbg->generate_counter++;
return 1;
}
/*
* Restart |drbg|, using the specified entropy or additional input
*
* Tries its best to get the drbg instantiated by all means,
* regardless of its current state.
*
* Optionally, a |buffer| of |len| random bytes can be passed,
* which is assumed to contain at least |entropy| bits of entropy.
*
* If |entropy| > 0, the buffer content is used as entropy input.
*
* If |entropy| == 0, the buffer content is used as additional input
*
* Returns 1 on success, 0 on failure.
*
* This function is used internally only.
*/
static int rand_drbg_restart(PROV_DRBG *drbg)
{
/* repair error state */
if (drbg->state == EVP_RAND_STATE_ERROR)
drbg->uninstantiate(drbg);
/* repair uninitialized state */
if (drbg->state == EVP_RAND_STATE_UNINITIALISED)
/* reinstantiate drbg */
ossl_prov_drbg_instantiate(drbg, drbg->strength, 0, NULL, 0);
return drbg->state == EVP_RAND_STATE_READY;
}
/* Provider support from here down */
static const OSSL_DISPATCH *find_call(const OSSL_DISPATCH *dispatch,
int function)
{
if (dispatch != NULL)
while (dispatch->function_id != 0) {
if (dispatch->function_id == function)
return dispatch;
dispatch++;
}
return NULL;
}
int ossl_drbg_enable_locking(void *vctx)
{
PROV_DRBG *drbg = vctx;
if (drbg != NULL && drbg->lock == NULL) {
if (drbg->parent_enable_locking != NULL)
if (!drbg->parent_enable_locking(drbg->parent)) {
ERR_raise(ERR_LIB_PROV, PROV_R_PARENT_LOCKING_NOT_ENABLED);
return 0;
}
drbg->lock = CRYPTO_THREAD_lock_new();
if (drbg->lock == NULL) {
ERR_raise(ERR_LIB_PROV, PROV_R_FAILED_TO_CREATE_LOCK);
return 0;
}
}
return 1;
}
/*
* Allocate memory and initialize a new DRBG. The DRBG is allocated on
* the secure heap if |secure| is nonzero and the secure heap is enabled.
* The |parent|, if not NULL, will be used as random source for reseeding.
* This also requires the parent's provider context and the parent's lock.
*
* Returns a pointer to the new DRBG instance on success, NULL on failure.
*/
PROV_DRBG *ossl_rand_drbg_new
(void *provctx, void *parent, const OSSL_DISPATCH *p_dispatch,
int (*dnew)(PROV_DRBG *ctx),
+ void (*dfree)(void *vctx),
int (*instantiate)(PROV_DRBG *drbg,
const unsigned char *entropy, size_t entropylen,
const unsigned char *nonce, size_t noncelen,
const unsigned char *pers, size_t perslen),
int (*uninstantiate)(PROV_DRBG *ctx),
int (*reseed)(PROV_DRBG *drbg, const unsigned char *ent, size_t ent_len,
const unsigned char *adin, size_t adin_len),
int (*generate)(PROV_DRBG *, unsigned char *out, size_t outlen,
const unsigned char *adin, size_t adin_len))
{
PROV_DRBG *drbg;
unsigned int p_str;
const OSSL_DISPATCH *pfunc;
if (!ossl_prov_is_running())
return NULL;
drbg = OPENSSL_zalloc(sizeof(*drbg));
if (drbg == NULL) {
ERR_raise(ERR_LIB_PROV, ERR_R_MALLOC_FAILURE);
return NULL;
}
drbg->provctx = provctx;
drbg->instantiate = instantiate;
drbg->uninstantiate = uninstantiate;
drbg->reseed = reseed;
drbg->generate = generate;
drbg->fork_id = openssl_get_fork_id();
/* Extract parent's functions */
drbg->parent = parent;
if ((pfunc = find_call(p_dispatch, OSSL_FUNC_RAND_ENABLE_LOCKING)) != NULL)
drbg->parent_enable_locking = OSSL_FUNC_rand_enable_locking(pfunc);
if ((pfunc = find_call(p_dispatch, OSSL_FUNC_RAND_LOCK)) != NULL)
drbg->parent_lock = OSSL_FUNC_rand_lock(pfunc);
if ((pfunc = find_call(p_dispatch, OSSL_FUNC_RAND_UNLOCK)) != NULL)
drbg->parent_unlock = OSSL_FUNC_rand_unlock(pfunc);
if ((pfunc = find_call(p_dispatch, OSSL_FUNC_RAND_GET_CTX_PARAMS)) != NULL)
drbg->parent_get_ctx_params = OSSL_FUNC_rand_get_ctx_params(pfunc);
if ((pfunc = find_call(p_dispatch, OSSL_FUNC_RAND_NONCE)) != NULL)
drbg->parent_nonce = OSSL_FUNC_rand_nonce(pfunc);
if ((pfunc = find_call(p_dispatch, OSSL_FUNC_RAND_GET_SEED)) != NULL)
drbg->parent_get_seed = OSSL_FUNC_rand_get_seed(pfunc);
if ((pfunc = find_call(p_dispatch, OSSL_FUNC_RAND_CLEAR_SEED)) != NULL)
drbg->parent_clear_seed = OSSL_FUNC_rand_clear_seed(pfunc);
/* Set some default maximums up */
drbg->max_entropylen = DRBG_MAX_LENGTH;
drbg->max_noncelen = DRBG_MAX_LENGTH;
drbg->max_perslen = DRBG_MAX_LENGTH;
drbg->max_adinlen = DRBG_MAX_LENGTH;
drbg->generate_counter = 1;
drbg->reseed_counter = 1;
drbg->reseed_interval = RESEED_INTERVAL;
drbg->reseed_time_interval = TIME_INTERVAL;
if (!dnew(drbg))
goto err;
if (parent != NULL) {
if (!get_parent_strength(drbg, &p_str))
goto err;
if (drbg->strength > p_str) {
/*
* We currently don't support the algorithm from NIST SP 800-90C
* 10.1.2 to use a weaker DRBG as source
*/
ERR_raise(ERR_LIB_PROV, PROV_R_PARENT_STRENGTH_TOO_WEAK);
goto err;
}
}
#ifdef TSAN_REQUIRES_LOCKING
if (!ossl_drbg_enable_locking(drbg))
goto err;
#endif
return drbg;
err:
- ossl_rand_drbg_free(drbg);
+ dfree(drbg);
return NULL;
}
void ossl_rand_drbg_free(PROV_DRBG *drbg)
{
if (drbg == NULL)
return;
CRYPTO_THREAD_lock_free(drbg->lock);
OPENSSL_free(drbg);
}
int ossl_drbg_get_ctx_params(PROV_DRBG *drbg, OSSL_PARAM params[])
{
OSSL_PARAM *p;
p = OSSL_PARAM_locate(params, OSSL_RAND_PARAM_STATE);
if (p != NULL && !OSSL_PARAM_set_int(p, drbg->state))
return 0;
p = OSSL_PARAM_locate(params, OSSL_RAND_PARAM_STRENGTH);
if (p != NULL && !OSSL_PARAM_set_int(p, drbg->strength))
return 0;
p = OSSL_PARAM_locate(params, OSSL_RAND_PARAM_MAX_REQUEST);
if (p != NULL && !OSSL_PARAM_set_size_t(p, drbg->max_request))
return 0;
p = OSSL_PARAM_locate(params, OSSL_DRBG_PARAM_MIN_ENTROPYLEN);
if (p != NULL && !OSSL_PARAM_set_size_t(p, drbg->min_entropylen))
return 0;
p = OSSL_PARAM_locate(params, OSSL_DRBG_PARAM_MAX_ENTROPYLEN);
if (p != NULL && !OSSL_PARAM_set_size_t(p, drbg->max_entropylen))
return 0;
p = OSSL_PARAM_locate(params, OSSL_DRBG_PARAM_MIN_NONCELEN);
if (p != NULL && !OSSL_PARAM_set_size_t(p, drbg->min_noncelen))
return 0;
p = OSSL_PARAM_locate(params, OSSL_DRBG_PARAM_MAX_NONCELEN);
if (p != NULL && !OSSL_PARAM_set_size_t(p, drbg->max_noncelen))
return 0;
p = OSSL_PARAM_locate(params, OSSL_DRBG_PARAM_MAX_PERSLEN);
if (p != NULL && !OSSL_PARAM_set_size_t(p, drbg->max_perslen))
return 0;
p = OSSL_PARAM_locate(params, OSSL_DRBG_PARAM_MAX_ADINLEN);
if (p != NULL && !OSSL_PARAM_set_size_t(p, drbg->max_adinlen))
return 0;
p = OSSL_PARAM_locate(params, OSSL_DRBG_PARAM_RESEED_REQUESTS);
if (p != NULL && !OSSL_PARAM_set_uint(p, drbg->reseed_interval))
return 0;
p = OSSL_PARAM_locate(params, OSSL_DRBG_PARAM_RESEED_TIME);
if (p != NULL && !OSSL_PARAM_set_time_t(p, drbg->reseed_time))
return 0;
p = OSSL_PARAM_locate(params, OSSL_DRBG_PARAM_RESEED_TIME_INTERVAL);
if (p != NULL && !OSSL_PARAM_set_time_t(p, drbg->reseed_time_interval))
return 0;
p = OSSL_PARAM_locate(params, OSSL_DRBG_PARAM_RESEED_COUNTER);
if (p != NULL
&& !OSSL_PARAM_set_uint(p, tsan_load(&drbg->reseed_counter)))
return 0;
return 1;
}
int ossl_drbg_set_ctx_params(PROV_DRBG *drbg, const OSSL_PARAM params[])
{
const OSSL_PARAM *p;
if (params == NULL)
return 1;
p = OSSL_PARAM_locate_const(params, OSSL_DRBG_PARAM_RESEED_REQUESTS);
if (p != NULL && !OSSL_PARAM_get_uint(p, &drbg->reseed_interval))
return 0;
p = OSSL_PARAM_locate_const(params, OSSL_DRBG_PARAM_RESEED_TIME_INTERVAL);
if (p != NULL && !OSSL_PARAM_get_time_t(p, &drbg->reseed_time_interval))
return 0;
return 1;
}
diff --git a/crypto/openssl/providers/implementations/rands/drbg_ctr.c b/crypto/openssl/providers/implementations/rands/drbg_ctr.c
index 451113c4d162..21fdce640816 100644
--- a/crypto/openssl/providers/implementations/rands/drbg_ctr.c
+++ b/crypto/openssl/providers/implementations/rands/drbg_ctr.c
@@ -1,755 +1,756 @@
/*
- * Copyright 2011-2022 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2011-2024 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 <stdlib.h>
#include <string.h>
#include <openssl/crypto.h>
#include <openssl/err.h>
#include <openssl/rand.h>
#include <openssl/aes.h>
#include <openssl/proverr.h>
#include "crypto/modes.h"
#include "internal/thread_once.h"
#include "prov/implementations.h"
#include "prov/providercommon.h"
#include "prov/provider_ctx.h"
#include "drbg_local.h"
static OSSL_FUNC_rand_newctx_fn drbg_ctr_new_wrapper;
static OSSL_FUNC_rand_freectx_fn drbg_ctr_free;
static OSSL_FUNC_rand_instantiate_fn drbg_ctr_instantiate_wrapper;
static OSSL_FUNC_rand_uninstantiate_fn drbg_ctr_uninstantiate_wrapper;
static OSSL_FUNC_rand_generate_fn drbg_ctr_generate_wrapper;
static OSSL_FUNC_rand_reseed_fn drbg_ctr_reseed_wrapper;
static OSSL_FUNC_rand_settable_ctx_params_fn drbg_ctr_settable_ctx_params;
static OSSL_FUNC_rand_set_ctx_params_fn drbg_ctr_set_ctx_params;
static OSSL_FUNC_rand_gettable_ctx_params_fn drbg_ctr_gettable_ctx_params;
static OSSL_FUNC_rand_get_ctx_params_fn drbg_ctr_get_ctx_params;
static OSSL_FUNC_rand_verify_zeroization_fn drbg_ctr_verify_zeroization;
/*
* The state of a DRBG AES-CTR.
*/
typedef struct rand_drbg_ctr_st {
EVP_CIPHER_CTX *ctx_ecb;
EVP_CIPHER_CTX *ctx_ctr;
EVP_CIPHER_CTX *ctx_df;
EVP_CIPHER *cipher_ecb;
EVP_CIPHER *cipher_ctr;
size_t keylen;
int use_df;
unsigned char K[32];
unsigned char V[16];
/* Temporary block storage used by ctr_df */
unsigned char bltmp[16];
size_t bltmp_pos;
unsigned char KX[48];
} PROV_DRBG_CTR;
/*
* Implementation of NIST SP 800-90A CTR DRBG.
*/
static void inc_128(PROV_DRBG_CTR *ctr)
{
unsigned char *p = &ctr->V[0];
u32 n = 16, c = 1;
do {
--n;
c += p[n];
p[n] = (u8)c;
c >>= 8;
} while (n);
}
static void ctr_XOR(PROV_DRBG_CTR *ctr, const unsigned char *in, size_t inlen)
{
size_t i, n;
if (in == NULL || inlen == 0)
return;
/*
* Any zero padding will have no effect on the result as we
* are XORing. So just process however much input we have.
*/
n = inlen < ctr->keylen ? inlen : ctr->keylen;
for (i = 0; i < n; i++)
ctr->K[i] ^= in[i];
if (inlen <= ctr->keylen)
return;
n = inlen - ctr->keylen;
if (n > 16) {
/* Should never happen */
n = 16;
}
for (i = 0; i < n; i++)
ctr->V[i] ^= in[i + ctr->keylen];
}
/*
* Process a complete block using BCC algorithm of SP 800-90A 10.3.3
*/
__owur static int ctr_BCC_block(PROV_DRBG_CTR *ctr, unsigned char *out,
const unsigned char *in, int len)
{
int i, outlen = AES_BLOCK_SIZE;
for (i = 0; i < len; i++)
out[i] ^= in[i];
if (!EVP_CipherUpdate(ctr->ctx_df, out, &outlen, out, len)
|| outlen != len)
return 0;
return 1;
}
/*
* Handle several BCC operations for as much data as we need for K and X
*/
__owur static int ctr_BCC_blocks(PROV_DRBG_CTR *ctr, const unsigned char *in)
{
unsigned char in_tmp[48];
unsigned char num_of_blk = 2;
memcpy(in_tmp, in, 16);
memcpy(in_tmp + 16, in, 16);
if (ctr->keylen != 16) {
memcpy(in_tmp + 32, in, 16);
num_of_blk = 3;
}
return ctr_BCC_block(ctr, ctr->KX, in_tmp, AES_BLOCK_SIZE * num_of_blk);
}
/*
* Initialise BCC blocks: these have the value 0,1,2 in leftmost positions:
* see 10.3.1 stage 7.
*/
__owur static int ctr_BCC_init(PROV_DRBG_CTR *ctr)
{
unsigned char bltmp[48] = {0};
unsigned char num_of_blk;
memset(ctr->KX, 0, 48);
num_of_blk = ctr->keylen == 16 ? 2 : 3;
bltmp[(AES_BLOCK_SIZE * 1) + 3] = 1;
bltmp[(AES_BLOCK_SIZE * 2) + 3] = 2;
return ctr_BCC_block(ctr, ctr->KX, bltmp, num_of_blk * AES_BLOCK_SIZE);
}
/*
* Process several blocks into BCC algorithm, some possibly partial
*/
__owur static int ctr_BCC_update(PROV_DRBG_CTR *ctr,
const unsigned char *in, size_t inlen)
{
if (in == NULL || inlen == 0)
return 1;
/* If we have partial block handle it first */
if (ctr->bltmp_pos) {
size_t left = 16 - ctr->bltmp_pos;
/* If we now have a complete block process it */
if (inlen >= left) {
memcpy(ctr->bltmp + ctr->bltmp_pos, in, left);
if (!ctr_BCC_blocks(ctr, ctr->bltmp))
return 0;
ctr->bltmp_pos = 0;
inlen -= left;
in += left;
}
}
/* Process zero or more complete blocks */
for (; inlen >= 16; in += 16, inlen -= 16) {
if (!ctr_BCC_blocks(ctr, in))
return 0;
}
/* Copy any remaining partial block to the temporary buffer */
if (inlen > 0) {
memcpy(ctr->bltmp + ctr->bltmp_pos, in, inlen);
ctr->bltmp_pos += inlen;
}
return 1;
}
__owur static int ctr_BCC_final(PROV_DRBG_CTR *ctr)
{
if (ctr->bltmp_pos) {
memset(ctr->bltmp + ctr->bltmp_pos, 0, 16 - ctr->bltmp_pos);
if (!ctr_BCC_blocks(ctr, ctr->bltmp))
return 0;
}
return 1;
}
__owur static int ctr_df(PROV_DRBG_CTR *ctr,
const unsigned char *in1, size_t in1len,
const unsigned char *in2, size_t in2len,
const unsigned char *in3, size_t in3len)
{
static unsigned char c80 = 0x80;
size_t inlen;
unsigned char *p = ctr->bltmp;
int outlen = AES_BLOCK_SIZE;
if (!ctr_BCC_init(ctr))
return 0;
if (in1 == NULL)
in1len = 0;
if (in2 == NULL)
in2len = 0;
if (in3 == NULL)
in3len = 0;
inlen = in1len + in2len + in3len;
/* Initialise L||N in temporary block */
*p++ = (inlen >> 24) & 0xff;
*p++ = (inlen >> 16) & 0xff;
*p++ = (inlen >> 8) & 0xff;
*p++ = inlen & 0xff;
/* NB keylen is at most 32 bytes */
*p++ = 0;
*p++ = 0;
*p++ = 0;
*p = (unsigned char)((ctr->keylen + 16) & 0xff);
ctr->bltmp_pos = 8;
if (!ctr_BCC_update(ctr, in1, in1len)
|| !ctr_BCC_update(ctr, in2, in2len)
|| !ctr_BCC_update(ctr, in3, in3len)
|| !ctr_BCC_update(ctr, &c80, 1)
|| !ctr_BCC_final(ctr))
return 0;
/* Set up key K */
if (!EVP_CipherInit_ex(ctr->ctx_ecb, NULL, NULL, ctr->KX, NULL, -1))
return 0;
/* X follows key K */
if (!EVP_CipherUpdate(ctr->ctx_ecb, ctr->KX, &outlen, ctr->KX + ctr->keylen,
AES_BLOCK_SIZE)
|| outlen != AES_BLOCK_SIZE)
return 0;
if (!EVP_CipherUpdate(ctr->ctx_ecb, ctr->KX + 16, &outlen, ctr->KX,
AES_BLOCK_SIZE)
|| outlen != AES_BLOCK_SIZE)
return 0;
if (ctr->keylen != 16)
if (!EVP_CipherUpdate(ctr->ctx_ecb, ctr->KX + 32, &outlen,
ctr->KX + 16, AES_BLOCK_SIZE)
|| outlen != AES_BLOCK_SIZE)
return 0;
return 1;
}
/*
* NB the no-df Update in SP800-90A specifies a constant input length
* of seedlen, however other uses of this algorithm pad the input with
* zeroes if necessary and have up to two parameters XORed together,
* so we handle both cases in this function instead.
*/
__owur static int ctr_update(PROV_DRBG *drbg,
const unsigned char *in1, size_t in1len,
const unsigned char *in2, size_t in2len,
const unsigned char *nonce, size_t noncelen)
{
PROV_DRBG_CTR *ctr = (PROV_DRBG_CTR *)drbg->data;
int outlen = AES_BLOCK_SIZE;
unsigned char V_tmp[48], out[48];
unsigned char len;
/* correct key is already set up. */
memcpy(V_tmp, ctr->V, 16);
inc_128(ctr);
memcpy(V_tmp + 16, ctr->V, 16);
if (ctr->keylen == 16) {
len = 32;
} else {
inc_128(ctr);
memcpy(V_tmp + 32, ctr->V, 16);
len = 48;
}
if (!EVP_CipherUpdate(ctr->ctx_ecb, out, &outlen, V_tmp, len)
|| outlen != len)
return 0;
memcpy(ctr->K, out, ctr->keylen);
memcpy(ctr->V, out + ctr->keylen, 16);
if (ctr->use_df) {
/* If no input reuse existing derived value */
if (in1 != NULL || nonce != NULL || in2 != NULL)
if (!ctr_df(ctr, in1, in1len, nonce, noncelen, in2, in2len))
return 0;
/* If this a reuse input in1len != 0 */
if (in1len)
ctr_XOR(ctr, ctr->KX, drbg->seedlen);
} else {
ctr_XOR(ctr, in1, in1len);
ctr_XOR(ctr, in2, in2len);
}
if (!EVP_CipherInit_ex(ctr->ctx_ecb, NULL, NULL, ctr->K, NULL, -1)
|| !EVP_CipherInit_ex(ctr->ctx_ctr, NULL, NULL, ctr->K, NULL, -1))
return 0;
return 1;
}
static int drbg_ctr_instantiate(PROV_DRBG *drbg,
const unsigned char *entropy, size_t entropylen,
const unsigned char *nonce, size_t noncelen,
const unsigned char *pers, size_t perslen)
{
PROV_DRBG_CTR *ctr = (PROV_DRBG_CTR *)drbg->data;
if (entropy == NULL)
return 0;
memset(ctr->K, 0, sizeof(ctr->K));
memset(ctr->V, 0, sizeof(ctr->V));
if (!EVP_CipherInit_ex(ctr->ctx_ecb, NULL, NULL, ctr->K, NULL, -1))
return 0;
inc_128(ctr);
if (!ctr_update(drbg, entropy, entropylen, pers, perslen, nonce, noncelen))
return 0;
return 1;
}
static int drbg_ctr_instantiate_wrapper(void *vdrbg, unsigned int strength,
int prediction_resistance,
const unsigned char *pstr,
size_t pstr_len,
const OSSL_PARAM params[])
{
PROV_DRBG *drbg = (PROV_DRBG *)vdrbg;
if (!ossl_prov_is_running() || !drbg_ctr_set_ctx_params(drbg, params))
return 0;
return ossl_prov_drbg_instantiate(drbg, strength, prediction_resistance,
pstr, pstr_len);
}
static int drbg_ctr_reseed(PROV_DRBG *drbg,
const unsigned char *entropy, size_t entropylen,
const unsigned char *adin, size_t adinlen)
{
PROV_DRBG_CTR *ctr = (PROV_DRBG_CTR *)drbg->data;
if (entropy == NULL)
return 0;
inc_128(ctr);
if (!ctr_update(drbg, entropy, entropylen, adin, adinlen, NULL, 0))
return 0;
return 1;
}
static int drbg_ctr_reseed_wrapper(void *vdrbg, int prediction_resistance,
const unsigned char *ent, size_t ent_len,
const unsigned char *adin, size_t adin_len)
{
PROV_DRBG *drbg = (PROV_DRBG *)vdrbg;
return ossl_prov_drbg_reseed(drbg, prediction_resistance, ent, ent_len,
adin, adin_len);
}
static void ctr96_inc(unsigned char *counter)
{
u32 n = 12, c = 1;
do {
--n;
c += counter[n];
counter[n] = (u8)c;
c >>= 8;
} while (n);
}
static int drbg_ctr_generate(PROV_DRBG *drbg,
unsigned char *out, size_t outlen,
const unsigned char *adin, size_t adinlen)
{
PROV_DRBG_CTR *ctr = (PROV_DRBG_CTR *)drbg->data;
unsigned int ctr32, blocks;
int outl, buflen;
if (adin != NULL && adinlen != 0) {
inc_128(ctr);
if (!ctr_update(drbg, adin, adinlen, NULL, 0, NULL, 0))
return 0;
/* This means we reuse derived value */
if (ctr->use_df) {
adin = NULL;
adinlen = 1;
}
} else {
adinlen = 0;
}
inc_128(ctr);
if (outlen == 0) {
inc_128(ctr);
if (!ctr_update(drbg, adin, adinlen, NULL, 0, NULL, 0))
return 0;
return 1;
}
memset(out, 0, outlen);
do {
if (!EVP_CipherInit_ex(ctr->ctx_ctr,
NULL, NULL, NULL, ctr->V, -1))
return 0;
/*-
* outlen has type size_t while EVP_CipherUpdate takes an
* int argument and thus cannot be guaranteed to process more
* than 2^31-1 bytes at a time. We process such huge generate
* requests in 2^30 byte chunks, which is the greatest multiple
* of AES block size lower than or equal to 2^31-1.
*/
buflen = outlen > (1U << 30) ? (1U << 30) : outlen;
blocks = (buflen + 15) / 16;
ctr32 = GETU32(ctr->V + 12) + blocks;
if (ctr32 < blocks) {
/* 32-bit counter overflow into V. */
if (ctr32 != 0) {
blocks -= ctr32;
buflen = blocks * 16;
ctr32 = 0;
}
ctr96_inc(ctr->V);
}
PUTU32(ctr->V + 12, ctr32);
if (!EVP_CipherUpdate(ctr->ctx_ctr, out, &outl, out, buflen)
|| outl != buflen)
return 0;
out += buflen;
outlen -= buflen;
} while (outlen);
if (!ctr_update(drbg, adin, adinlen, NULL, 0, NULL, 0))
return 0;
return 1;
}
static int drbg_ctr_generate_wrapper
(void *vdrbg, unsigned char *out, size_t outlen,
unsigned int strength, int prediction_resistance,
const unsigned char *adin, size_t adin_len)
{
PROV_DRBG *drbg = (PROV_DRBG *)vdrbg;
return ossl_prov_drbg_generate(drbg, out, outlen, strength,
prediction_resistance, adin, adin_len);
}
static int drbg_ctr_uninstantiate(PROV_DRBG *drbg)
{
PROV_DRBG_CTR *ctr = (PROV_DRBG_CTR *)drbg->data;
OPENSSL_cleanse(ctr->K, sizeof(ctr->K));
OPENSSL_cleanse(ctr->V, sizeof(ctr->V));
OPENSSL_cleanse(ctr->bltmp, sizeof(ctr->bltmp));
OPENSSL_cleanse(ctr->KX, sizeof(ctr->KX));
ctr->bltmp_pos = 0;
return ossl_prov_drbg_uninstantiate(drbg);
}
static int drbg_ctr_uninstantiate_wrapper(void *vdrbg)
{
return drbg_ctr_uninstantiate((PROV_DRBG *)vdrbg);
}
static int drbg_ctr_verify_zeroization(void *vdrbg)
{
PROV_DRBG *drbg = (PROV_DRBG *)vdrbg;
PROV_DRBG_CTR *ctr = (PROV_DRBG_CTR *)drbg->data;
PROV_DRBG_VERYIFY_ZEROIZATION(ctr->K);
PROV_DRBG_VERYIFY_ZEROIZATION(ctr->V);
PROV_DRBG_VERYIFY_ZEROIZATION(ctr->bltmp);
PROV_DRBG_VERYIFY_ZEROIZATION(ctr->KX);
if (ctr->bltmp_pos != 0)
return 0;
return 1;
}
static int drbg_ctr_init_lengths(PROV_DRBG *drbg)
{
PROV_DRBG_CTR *ctr = (PROV_DRBG_CTR *)drbg->data;
int res = 1;
/* Maximum number of bits per request = 2^19 = 2^16 bytes */
drbg->max_request = 1 << 16;
if (ctr->use_df) {
drbg->min_entropylen = 0;
drbg->max_entropylen = DRBG_MAX_LENGTH;
drbg->min_noncelen = 0;
drbg->max_noncelen = DRBG_MAX_LENGTH;
drbg->max_perslen = DRBG_MAX_LENGTH;
drbg->max_adinlen = DRBG_MAX_LENGTH;
if (ctr->keylen > 0) {
drbg->min_entropylen = ctr->keylen;
drbg->min_noncelen = drbg->min_entropylen / 2;
}
} else {
const size_t len = ctr->keylen > 0 ? drbg->seedlen : DRBG_MAX_LENGTH;
drbg->min_entropylen = len;
drbg->max_entropylen = len;
/* Nonce not used */
drbg->min_noncelen = 0;
drbg->max_noncelen = 0;
drbg->max_perslen = len;
drbg->max_adinlen = len;
}
return res;
}
static int drbg_ctr_init(PROV_DRBG *drbg)
{
PROV_DRBG_CTR *ctr = (PROV_DRBG_CTR *)drbg->data;
size_t keylen;
if (ctr->cipher_ctr == NULL) {
ERR_raise(ERR_LIB_PROV, PROV_R_MISSING_CIPHER);
return 0;
}
ctr->keylen = keylen = EVP_CIPHER_get_key_length(ctr->cipher_ctr);
if (ctr->ctx_ecb == NULL)
ctr->ctx_ecb = EVP_CIPHER_CTX_new();
if (ctr->ctx_ctr == NULL)
ctr->ctx_ctr = EVP_CIPHER_CTX_new();
if (ctr->ctx_ecb == NULL || ctr->ctx_ctr == NULL) {
ERR_raise(ERR_LIB_PROV, ERR_R_MALLOC_FAILURE);
goto err;
}
if (!EVP_CipherInit_ex(ctr->ctx_ecb,
ctr->cipher_ecb, NULL, NULL, NULL, 1)
|| !EVP_CipherInit_ex(ctr->ctx_ctr,
ctr->cipher_ctr, NULL, NULL, NULL, 1)) {
ERR_raise(ERR_LIB_PROV, PROV_R_UNABLE_TO_INITIALISE_CIPHERS);
goto err;
}
drbg->strength = keylen * 8;
drbg->seedlen = keylen + 16;
if (ctr->use_df) {
/* df initialisation */
static const unsigned char df_key[32] = {
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
};
if (ctr->ctx_df == NULL)
ctr->ctx_df = EVP_CIPHER_CTX_new();
if (ctr->ctx_df == NULL) {
ERR_raise(ERR_LIB_PROV, ERR_R_MALLOC_FAILURE);
goto err;
}
/* Set key schedule for df_key */
if (!EVP_CipherInit_ex(ctr->ctx_df,
ctr->cipher_ecb, NULL, df_key, NULL, 1)) {
ERR_raise(ERR_LIB_PROV, PROV_R_DERIVATION_FUNCTION_INIT_FAILED);
goto err;
}
}
return drbg_ctr_init_lengths(drbg);
err:
EVP_CIPHER_CTX_free(ctr->ctx_ecb);
EVP_CIPHER_CTX_free(ctr->ctx_ctr);
ctr->ctx_ecb = ctr->ctx_ctr = NULL;
- return 0;
+ return 0;
}
static int drbg_ctr_new(PROV_DRBG *drbg)
{
PROV_DRBG_CTR *ctr;
ctr = OPENSSL_secure_zalloc(sizeof(*ctr));
if (ctr == NULL) {
ERR_raise(ERR_LIB_PROV, ERR_R_MALLOC_FAILURE);
return 0;
}
ctr->use_df = 1;
drbg->data = ctr;
return drbg_ctr_init_lengths(drbg);
}
static void *drbg_ctr_new_wrapper(void *provctx, void *parent,
const OSSL_DISPATCH *parent_dispatch)
{
- return ossl_rand_drbg_new(provctx, parent, parent_dispatch, &drbg_ctr_new,
+ return ossl_rand_drbg_new(provctx, parent, parent_dispatch,
+ &drbg_ctr_new, &drbg_ctr_free,
&drbg_ctr_instantiate, &drbg_ctr_uninstantiate,
&drbg_ctr_reseed, &drbg_ctr_generate);
}
static void drbg_ctr_free(void *vdrbg)
{
PROV_DRBG *drbg = (PROV_DRBG *)vdrbg;
PROV_DRBG_CTR *ctr;
if (drbg != NULL && (ctr = (PROV_DRBG_CTR *)drbg->data) != NULL) {
EVP_CIPHER_CTX_free(ctr->ctx_ecb);
EVP_CIPHER_CTX_free(ctr->ctx_ctr);
EVP_CIPHER_CTX_free(ctr->ctx_df);
EVP_CIPHER_free(ctr->cipher_ecb);
EVP_CIPHER_free(ctr->cipher_ctr);
OPENSSL_secure_clear_free(ctr, sizeof(*ctr));
}
ossl_rand_drbg_free(drbg);
}
static int drbg_ctr_get_ctx_params(void *vdrbg, OSSL_PARAM params[])
{
PROV_DRBG *drbg = (PROV_DRBG *)vdrbg;
PROV_DRBG_CTR *ctr = (PROV_DRBG_CTR *)drbg->data;
OSSL_PARAM *p;
p = OSSL_PARAM_locate(params, OSSL_DRBG_PARAM_USE_DF);
if (p != NULL && !OSSL_PARAM_set_int(p, ctr->use_df))
return 0;
p = OSSL_PARAM_locate(params, OSSL_DRBG_PARAM_CIPHER);
if (p != NULL) {
if (ctr->cipher_ctr == NULL
|| !OSSL_PARAM_set_utf8_string(p,
EVP_CIPHER_get0_name(ctr->cipher_ctr)))
return 0;
}
return ossl_drbg_get_ctx_params(drbg, params);
}
static const OSSL_PARAM *drbg_ctr_gettable_ctx_params(ossl_unused void *vctx,
ossl_unused void *provctx)
{
static const OSSL_PARAM known_gettable_ctx_params[] = {
OSSL_PARAM_utf8_string(OSSL_DRBG_PARAM_CIPHER, NULL, 0),
OSSL_PARAM_int(OSSL_DRBG_PARAM_USE_DF, NULL),
OSSL_PARAM_DRBG_GETTABLE_CTX_COMMON,
OSSL_PARAM_END
};
return known_gettable_ctx_params;
}
static int drbg_ctr_set_ctx_params(void *vctx, const OSSL_PARAM params[])
{
PROV_DRBG *ctx = (PROV_DRBG *)vctx;
PROV_DRBG_CTR *ctr = (PROV_DRBG_CTR *)ctx->data;
OSSL_LIB_CTX *libctx = PROV_LIBCTX_OF(ctx->provctx);
const OSSL_PARAM *p;
char *ecb;
const char *propquery = NULL;
int i, cipher_init = 0;
if ((p = OSSL_PARAM_locate_const(params, OSSL_DRBG_PARAM_USE_DF)) != NULL
&& OSSL_PARAM_get_int(p, &i)) {
/* FIPS errors out in the drbg_ctr_init() call later */
ctr->use_df = i != 0;
cipher_init = 1;
}
if ((p = OSSL_PARAM_locate_const(params,
OSSL_DRBG_PARAM_PROPERTIES)) != NULL) {
if (p->data_type != OSSL_PARAM_UTF8_STRING)
return 0;
propquery = (const char *)p->data;
}
if ((p = OSSL_PARAM_locate_const(params, OSSL_DRBG_PARAM_CIPHER)) != NULL) {
const char *base = (const char *)p->data;
size_t ctr_str_len = sizeof("CTR") - 1;
size_t ecb_str_len = sizeof("ECB") - 1;
if (p->data_type != OSSL_PARAM_UTF8_STRING
|| p->data_size < ctr_str_len)
return 0;
if (OPENSSL_strcasecmp("CTR", base + p->data_size - ctr_str_len) != 0) {
ERR_raise(ERR_LIB_PROV, PROV_R_REQUIRE_CTR_MODE_CIPHER);
return 0;
}
if ((ecb = OPENSSL_strndup(base, p->data_size)) == NULL) {
ERR_raise(ERR_LIB_PROV, ERR_R_MALLOC_FAILURE);
return 0;
}
strcpy(ecb + p->data_size - ecb_str_len, "ECB");
EVP_CIPHER_free(ctr->cipher_ecb);
EVP_CIPHER_free(ctr->cipher_ctr);
ctr->cipher_ctr = EVP_CIPHER_fetch(libctx, base, propquery);
ctr->cipher_ecb = EVP_CIPHER_fetch(libctx, ecb, propquery);
OPENSSL_free(ecb);
if (ctr->cipher_ctr == NULL || ctr->cipher_ecb == NULL) {
ERR_raise(ERR_LIB_PROV, PROV_R_UNABLE_TO_FIND_CIPHERS);
return 0;
}
cipher_init = 1;
}
if (cipher_init && !drbg_ctr_init(ctx))
return 0;
return ossl_drbg_set_ctx_params(ctx, params);
}
static const OSSL_PARAM *drbg_ctr_settable_ctx_params(ossl_unused void *vctx,
ossl_unused void *provctx)
{
static const OSSL_PARAM known_settable_ctx_params[] = {
OSSL_PARAM_utf8_string(OSSL_DRBG_PARAM_PROPERTIES, NULL, 0),
OSSL_PARAM_utf8_string(OSSL_DRBG_PARAM_CIPHER, NULL, 0),
OSSL_PARAM_int(OSSL_DRBG_PARAM_USE_DF, NULL),
OSSL_PARAM_DRBG_SETTABLE_CTX_COMMON,
OSSL_PARAM_END
};
return known_settable_ctx_params;
}
const OSSL_DISPATCH ossl_drbg_ctr_functions[] = {
{ OSSL_FUNC_RAND_NEWCTX, (void(*)(void))drbg_ctr_new_wrapper },
{ OSSL_FUNC_RAND_FREECTX, (void(*)(void))drbg_ctr_free },
{ OSSL_FUNC_RAND_INSTANTIATE,
(void(*)(void))drbg_ctr_instantiate_wrapper },
{ OSSL_FUNC_RAND_UNINSTANTIATE,
(void(*)(void))drbg_ctr_uninstantiate_wrapper },
{ OSSL_FUNC_RAND_GENERATE, (void(*)(void))drbg_ctr_generate_wrapper },
{ OSSL_FUNC_RAND_RESEED, (void(*)(void))drbg_ctr_reseed_wrapper },
{ OSSL_FUNC_RAND_ENABLE_LOCKING, (void(*)(void))ossl_drbg_enable_locking },
{ OSSL_FUNC_RAND_LOCK, (void(*)(void))ossl_drbg_lock },
{ OSSL_FUNC_RAND_UNLOCK, (void(*)(void))ossl_drbg_unlock },
{ OSSL_FUNC_RAND_SETTABLE_CTX_PARAMS,
(void(*)(void))drbg_ctr_settable_ctx_params },
{ OSSL_FUNC_RAND_SET_CTX_PARAMS, (void(*)(void))drbg_ctr_set_ctx_params },
{ OSSL_FUNC_RAND_GETTABLE_CTX_PARAMS,
(void(*)(void))drbg_ctr_gettable_ctx_params },
{ OSSL_FUNC_RAND_GET_CTX_PARAMS, (void(*)(void))drbg_ctr_get_ctx_params },
{ OSSL_FUNC_RAND_VERIFY_ZEROIZATION,
(void(*)(void))drbg_ctr_verify_zeroization },
{ OSSL_FUNC_RAND_GET_SEED, (void(*)(void))ossl_drbg_get_seed },
{ OSSL_FUNC_RAND_CLEAR_SEED, (void(*)(void))ossl_drbg_clear_seed },
{ 0, NULL }
};
diff --git a/crypto/openssl/providers/implementations/rands/drbg_hash.c b/crypto/openssl/providers/implementations/rands/drbg_hash.c
index 6deb0a29256b..de9375793d5a 100644
--- a/crypto/openssl/providers/implementations/rands/drbg_hash.c
+++ b/crypto/openssl/providers/implementations/rands/drbg_hash.c
@@ -1,529 +1,530 @@
/*
- * Copyright 2011-2021 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2011-2024 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 <assert.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/sha.h>
#include <openssl/crypto.h>
#include <openssl/err.h>
#include <openssl/rand.h>
#include <openssl/core_dispatch.h>
#include <openssl/proverr.h>
#include "internal/thread_once.h"
#include "prov/providercommon.h"
#include "prov/provider_ctx.h"
#include "prov/provider_util.h"
#include "prov/implementations.h"
#include "drbg_local.h"
static OSSL_FUNC_rand_newctx_fn drbg_hash_new_wrapper;
static OSSL_FUNC_rand_freectx_fn drbg_hash_free;
static OSSL_FUNC_rand_instantiate_fn drbg_hash_instantiate_wrapper;
static OSSL_FUNC_rand_uninstantiate_fn drbg_hash_uninstantiate_wrapper;
static OSSL_FUNC_rand_generate_fn drbg_hash_generate_wrapper;
static OSSL_FUNC_rand_reseed_fn drbg_hash_reseed_wrapper;
static OSSL_FUNC_rand_settable_ctx_params_fn drbg_hash_settable_ctx_params;
static OSSL_FUNC_rand_set_ctx_params_fn drbg_hash_set_ctx_params;
static OSSL_FUNC_rand_gettable_ctx_params_fn drbg_hash_gettable_ctx_params;
static OSSL_FUNC_rand_get_ctx_params_fn drbg_hash_get_ctx_params;
static OSSL_FUNC_rand_verify_zeroization_fn drbg_hash_verify_zeroization;
/* 888 bits from SP800-90Ar1 10.1 table 2 */
#define HASH_PRNG_MAX_SEEDLEN (888/8)
/* 440 bits from SP800-90Ar1 10.1 table 2 */
#define HASH_PRNG_SMALL_SEEDLEN (440/8)
/* Determine what seedlen to use based on the block length */
#define MAX_BLOCKLEN_USING_SMALL_SEEDLEN (256/8)
#define INBYTE_IGNORE ((unsigned char)0xFF)
typedef struct rand_drbg_hash_st {
PROV_DIGEST digest;
EVP_MD_CTX *ctx;
size_t blocklen;
unsigned char V[HASH_PRNG_MAX_SEEDLEN];
unsigned char C[HASH_PRNG_MAX_SEEDLEN];
/* Temporary value storage: should always exceed max digest length */
unsigned char vtmp[HASH_PRNG_MAX_SEEDLEN];
} PROV_DRBG_HASH;
/*
* SP800-90Ar1 10.3.1 Derivation function using a Hash Function (Hash_df).
* The input string used is composed of:
* inbyte - An optional leading byte (ignore if equal to INBYTE_IGNORE)
* in - input string 1 (A Non NULL value).
* in2 - optional input string (Can be NULL).
* in3 - optional input string (Can be NULL).
* These are concatenated as part of the DigestUpdate process.
*/
static int hash_df(PROV_DRBG *drbg, unsigned char *out,
const unsigned char inbyte,
const unsigned char *in, size_t inlen,
const unsigned char *in2, size_t in2len,
const unsigned char *in3, size_t in3len)
{
PROV_DRBG_HASH *hash = (PROV_DRBG_HASH *)drbg->data;
EVP_MD_CTX *ctx = hash->ctx;
unsigned char *vtmp = hash->vtmp;
/* tmp = counter || num_bits_returned || [inbyte] */
unsigned char tmp[1 + 4 + 1];
int tmp_sz = 0;
size_t outlen = drbg->seedlen;
size_t num_bits_returned = outlen * 8;
/*
* No need to check outlen size here, as the standard only ever needs
* seedlen bytes which is always less than the maximum permitted.
*/
/* (Step 3) counter = 1 (tmp[0] is the 8 bit counter) */
tmp[tmp_sz++] = 1;
/* tmp[1..4] is the fixed 32 bit no_of_bits_to_return */
tmp[tmp_sz++] = (unsigned char)((num_bits_returned >> 24) & 0xff);
tmp[tmp_sz++] = (unsigned char)((num_bits_returned >> 16) & 0xff);
tmp[tmp_sz++] = (unsigned char)((num_bits_returned >> 8) & 0xff);
tmp[tmp_sz++] = (unsigned char)(num_bits_returned & 0xff);
/* Tack the additional input byte onto the end of tmp if it exists */
if (inbyte != INBYTE_IGNORE)
tmp[tmp_sz++] = inbyte;
/* (Step 4) */
for (;;) {
/*
* (Step 4.1) out = out || Hash(tmp || in || [in2] || [in3])
* (where tmp = counter || num_bits_returned || [inbyte])
*/
if (!(EVP_DigestInit_ex(ctx, ossl_prov_digest_md(&hash->digest), NULL)
&& EVP_DigestUpdate(ctx, tmp, tmp_sz)
&& EVP_DigestUpdate(ctx, in, inlen)
&& (in2 == NULL || EVP_DigestUpdate(ctx, in2, in2len))
&& (in3 == NULL || EVP_DigestUpdate(ctx, in3, in3len))))
return 0;
if (outlen < hash->blocklen) {
if (!EVP_DigestFinal(ctx, vtmp, NULL))
return 0;
memcpy(out, vtmp, outlen);
OPENSSL_cleanse(vtmp, hash->blocklen);
break;
} else if(!EVP_DigestFinal(ctx, out, NULL)) {
return 0;
}
outlen -= hash->blocklen;
if (outlen == 0)
break;
/* (Step 4.2) counter++ */
tmp[0]++;
out += hash->blocklen;
}
return 1;
}
/* Helper function that just passes 2 input parameters to hash_df() */
static int hash_df1(PROV_DRBG *drbg, unsigned char *out,
const unsigned char in_byte,
const unsigned char *in1, size_t in1len)
{
return hash_df(drbg, out, in_byte, in1, in1len, NULL, 0, NULL, 0);
}
/*
* Add 2 byte buffers together. The first elements in each buffer are the top
* most bytes. The result is stored in the dst buffer.
* The final carry is ignored i.e: dst = (dst + in) mod (2^seedlen_bits).
* where dst size is drbg->seedlen, and inlen <= drbg->seedlen.
*/
static int add_bytes(PROV_DRBG *drbg, unsigned char *dst,
unsigned char *in, size_t inlen)
{
size_t i;
int result;
const unsigned char *add;
unsigned char carry = 0, *d;
assert(drbg->seedlen >= 1 && inlen >= 1 && inlen <= drbg->seedlen);
d = &dst[drbg->seedlen - 1];
add = &in[inlen - 1];
for (i = inlen; i > 0; i--, d--, add--) {
result = *d + *add + carry;
carry = (unsigned char)(result >> 8);
*d = (unsigned char)(result & 0xff);
}
if (carry != 0) {
/* Add the carry to the top of the dst if inlen is not the same size */
for (i = drbg->seedlen - inlen; i > 0; --i, d--) {
*d += 1; /* Carry can only be 1 */
if (*d != 0) /* exit if carry doesnt propagate to the next byte */
break;
}
}
return 1;
}
/* V = (V + Hash(inbyte || V || [additional_input]) mod (2^seedlen) */
static int add_hash_to_v(PROV_DRBG *drbg, unsigned char inbyte,
const unsigned char *adin, size_t adinlen)
{
PROV_DRBG_HASH *hash = (PROV_DRBG_HASH *)drbg->data;
EVP_MD_CTX *ctx = hash->ctx;
return EVP_DigestInit_ex(ctx, ossl_prov_digest_md(&hash->digest), NULL)
&& EVP_DigestUpdate(ctx, &inbyte, 1)
&& EVP_DigestUpdate(ctx, hash->V, drbg->seedlen)
&& (adin == NULL || EVP_DigestUpdate(ctx, adin, adinlen))
&& EVP_DigestFinal(ctx, hash->vtmp, NULL)
&& add_bytes(drbg, hash->V, hash->vtmp, hash->blocklen);
}
/*
* The Hashgen() as listed in SP800-90Ar1 10.1.1.4 Hash_DRBG_Generate_Process.
*
* drbg contains the current value of V.
* outlen is the requested number of bytes.
* out is a buffer to return the generated bits.
*
* The algorithm to generate the bits is:
* data = V
* w = NULL
* for (i = 1 to m) {
* W = W || Hash(data)
* data = (data + 1) mod (2^seedlen)
* }
* out = Leftmost(W, outlen)
*
* Returns zero if an error occurs otherwise it returns 1.
*/
static int hash_gen(PROV_DRBG *drbg, unsigned char *out, size_t outlen)
{
PROV_DRBG_HASH *hash = (PROV_DRBG_HASH *)drbg->data;
unsigned char one = 1;
if (outlen == 0)
return 1;
memcpy(hash->vtmp, hash->V, drbg->seedlen);
for(;;) {
if (!EVP_DigestInit_ex(hash->ctx, ossl_prov_digest_md(&hash->digest),
NULL)
|| !EVP_DigestUpdate(hash->ctx, hash->vtmp, drbg->seedlen))
return 0;
if (outlen < hash->blocklen) {
if (!EVP_DigestFinal(hash->ctx, hash->vtmp, NULL))
return 0;
memcpy(out, hash->vtmp, outlen);
return 1;
} else {
if (!EVP_DigestFinal(hash->ctx, out, NULL))
return 0;
outlen -= hash->blocklen;
if (outlen == 0)
break;
out += hash->blocklen;
}
add_bytes(drbg, hash->vtmp, &one, 1);
}
return 1;
}
/*
* SP800-90Ar1 10.1.1.2 Hash_DRBG_Instantiate_Process:
*
* ent is entropy input obtained from a randomness source of length ent_len.
* nonce is a string of bytes of length nonce_len.
* pstr is a personalization string received from an application. May be NULL.
*
* Returns zero if an error occurs otherwise it returns 1.
*/
static int drbg_hash_instantiate(PROV_DRBG *drbg,
const unsigned char *ent, size_t ent_len,
const unsigned char *nonce, size_t nonce_len,
const unsigned char *pstr, size_t pstr_len)
{
PROV_DRBG_HASH *hash = (PROV_DRBG_HASH *)drbg->data;
EVP_MD_CTX_free(hash->ctx);
hash->ctx = EVP_MD_CTX_new();
/* (Step 1-3) V = Hash_df(entropy||nonce||pers, seedlen) */
return hash->ctx != NULL
&& hash_df(drbg, hash->V, INBYTE_IGNORE,
ent, ent_len, nonce, nonce_len, pstr, pstr_len)
/* (Step 4) C = Hash_df(0x00||V, seedlen) */
&& hash_df1(drbg, hash->C, 0x00, hash->V, drbg->seedlen);
}
static int drbg_hash_instantiate_wrapper(void *vdrbg, unsigned int strength,
int prediction_resistance,
const unsigned char *pstr,
size_t pstr_len,
const OSSL_PARAM params[])
{
PROV_DRBG *drbg = (PROV_DRBG *)vdrbg;
if (!ossl_prov_is_running() || !drbg_hash_set_ctx_params(drbg, params))
return 0;
return ossl_prov_drbg_instantiate(drbg, strength, prediction_resistance,
pstr, pstr_len);
}
/*
* SP800-90Ar1 10.1.1.3 Hash_DRBG_Reseed_Process:
*
* ent is entropy input bytes obtained from a randomness source.
* addin is additional input received from an application. May be NULL.
*
* Returns zero if an error occurs otherwise it returns 1.
*/
static int drbg_hash_reseed(PROV_DRBG *drbg,
const unsigned char *ent, size_t ent_len,
const unsigned char *adin, size_t adin_len)
{
PROV_DRBG_HASH *hash = (PROV_DRBG_HASH *)drbg->data;
/* (Step 1-2) V = Hash_df(0x01 || V || entropy_input || additional_input) */
/* V about to be updated so use C as output instead */
if (!hash_df(drbg, hash->C, 0x01, hash->V, drbg->seedlen, ent, ent_len,
adin, adin_len))
return 0;
memcpy(hash->V, hash->C, drbg->seedlen);
/* (Step 4) C = Hash_df(0x00||V, seedlen) */
return hash_df1(drbg, hash->C, 0x00, hash->V, drbg->seedlen);
}
static int drbg_hash_reseed_wrapper(void *vdrbg, int prediction_resistance,
const unsigned char *ent, size_t ent_len,
const unsigned char *adin, size_t adin_len)
{
PROV_DRBG *drbg = (PROV_DRBG *)vdrbg;
return ossl_prov_drbg_reseed(drbg, prediction_resistance, ent, ent_len,
adin, adin_len);
}
/*
* SP800-90Ar1 10.1.1.4 Hash_DRBG_Generate_Process:
*
* Generates pseudo random bytes using the drbg.
* out is a buffer to fill with outlen bytes of pseudo random data.
* addin is additional input received from an application. May be NULL.
*
* Returns zero if an error occurs otherwise it returns 1.
*/
static int drbg_hash_generate(PROV_DRBG *drbg,
unsigned char *out, size_t outlen,
const unsigned char *adin, size_t adin_len)
{
PROV_DRBG_HASH *hash = (PROV_DRBG_HASH *)drbg->data;
unsigned char counter[4];
int reseed_counter = drbg->generate_counter;
counter[0] = (unsigned char)((reseed_counter >> 24) & 0xff);
counter[1] = (unsigned char)((reseed_counter >> 16) & 0xff);
counter[2] = (unsigned char)((reseed_counter >> 8) & 0xff);
counter[3] = (unsigned char)(reseed_counter & 0xff);
return hash->ctx != NULL
&& (adin == NULL
/* (Step 2) if adin != NULL then V = V + Hash(0x02||V||adin) */
|| adin_len == 0
|| add_hash_to_v(drbg, 0x02, adin, adin_len))
/* (Step 3) Hashgen(outlen, V) */
&& hash_gen(drbg, out, outlen)
/* (Step 4/5) H = V = (V + Hash(0x03||V) mod (2^seedlen_bits) */
&& add_hash_to_v(drbg, 0x03, NULL, 0)
/* (Step 5) V = (V + H + C + reseed_counter) mod (2^seedlen_bits) */
/* V = (V + C) mod (2^seedlen_bits) */
&& add_bytes(drbg, hash->V, hash->C, drbg->seedlen)
/* V = (V + reseed_counter) mod (2^seedlen_bits) */
&& add_bytes(drbg, hash->V, counter, 4);
}
static int drbg_hash_generate_wrapper
(void *vdrbg, unsigned char *out, size_t outlen, unsigned int strength,
int prediction_resistance, const unsigned char *adin, size_t adin_len)
{
PROV_DRBG *drbg = (PROV_DRBG *)vdrbg;
return ossl_prov_drbg_generate(drbg, out, outlen, strength,
prediction_resistance, adin, adin_len);
}
static int drbg_hash_uninstantiate(PROV_DRBG *drbg)
{
PROV_DRBG_HASH *hash = (PROV_DRBG_HASH *)drbg->data;
OPENSSL_cleanse(hash->V, sizeof(hash->V));
OPENSSL_cleanse(hash->C, sizeof(hash->C));
OPENSSL_cleanse(hash->vtmp, sizeof(hash->vtmp));
return ossl_prov_drbg_uninstantiate(drbg);
}
static int drbg_hash_uninstantiate_wrapper(void *vdrbg)
{
return drbg_hash_uninstantiate((PROV_DRBG *)vdrbg);
}
static int drbg_hash_verify_zeroization(void *vdrbg)
{
PROV_DRBG *drbg = (PROV_DRBG *)vdrbg;
PROV_DRBG_HASH *hash = (PROV_DRBG_HASH *)drbg->data;
PROV_DRBG_VERYIFY_ZEROIZATION(hash->V);
PROV_DRBG_VERYIFY_ZEROIZATION(hash->C);
PROV_DRBG_VERYIFY_ZEROIZATION(hash->vtmp);
return 1;
}
static int drbg_hash_new(PROV_DRBG *ctx)
{
PROV_DRBG_HASH *hash;
hash = OPENSSL_secure_zalloc(sizeof(*hash));
if (hash == NULL) {
ERR_raise(ERR_LIB_PROV, ERR_R_MALLOC_FAILURE);
return 0;
}
ctx->data = hash;
ctx->seedlen = HASH_PRNG_MAX_SEEDLEN;
ctx->max_entropylen = DRBG_MAX_LENGTH;
ctx->max_noncelen = DRBG_MAX_LENGTH;
ctx->max_perslen = DRBG_MAX_LENGTH;
ctx->max_adinlen = DRBG_MAX_LENGTH;
/* Maximum number of bits per request = 2^19 = 2^16 bytes */
ctx->max_request = 1 << 16;
return 1;
}
static void *drbg_hash_new_wrapper(void *provctx, void *parent,
const OSSL_DISPATCH *parent_dispatch)
{
- return ossl_rand_drbg_new(provctx, parent, parent_dispatch, &drbg_hash_new,
+ return ossl_rand_drbg_new(provctx, parent, parent_dispatch,
+ &drbg_hash_new, &drbg_hash_free,
&drbg_hash_instantiate, &drbg_hash_uninstantiate,
&drbg_hash_reseed, &drbg_hash_generate);
}
static void drbg_hash_free(void *vdrbg)
{
PROV_DRBG *drbg = (PROV_DRBG *)vdrbg;
PROV_DRBG_HASH *hash;
if (drbg != NULL && (hash = (PROV_DRBG_HASH *)drbg->data) != NULL) {
EVP_MD_CTX_free(hash->ctx);
ossl_prov_digest_reset(&hash->digest);
OPENSSL_secure_clear_free(hash, sizeof(*hash));
}
ossl_rand_drbg_free(drbg);
}
static int drbg_hash_get_ctx_params(void *vdrbg, OSSL_PARAM params[])
{
PROV_DRBG *drbg = (PROV_DRBG *)vdrbg;
PROV_DRBG_HASH *hash = (PROV_DRBG_HASH *)drbg->data;
const EVP_MD *md;
OSSL_PARAM *p;
p = OSSL_PARAM_locate(params, OSSL_DRBG_PARAM_DIGEST);
if (p != NULL) {
md = ossl_prov_digest_md(&hash->digest);
if (md == NULL || !OSSL_PARAM_set_utf8_string(p, EVP_MD_get0_name(md)))
return 0;
}
return ossl_drbg_get_ctx_params(drbg, params);
}
static const OSSL_PARAM *drbg_hash_gettable_ctx_params(ossl_unused void *vctx,
ossl_unused void *p_ctx)
{
static const OSSL_PARAM known_gettable_ctx_params[] = {
OSSL_PARAM_utf8_string(OSSL_DRBG_PARAM_DIGEST, NULL, 0),
OSSL_PARAM_DRBG_GETTABLE_CTX_COMMON,
OSSL_PARAM_END
};
return known_gettable_ctx_params;
}
static int drbg_hash_set_ctx_params(void *vctx, const OSSL_PARAM params[])
{
PROV_DRBG *ctx = (PROV_DRBG *)vctx;
PROV_DRBG_HASH *hash = (PROV_DRBG_HASH *)ctx->data;
OSSL_LIB_CTX *libctx = PROV_LIBCTX_OF(ctx->provctx);
const EVP_MD *md;
if (!ossl_prov_digest_load_from_params(&hash->digest, params, libctx))
return 0;
md = ossl_prov_digest_md(&hash->digest);
if (md != NULL) {
if ((EVP_MD_get_flags(md) & EVP_MD_FLAG_XOF) != 0) {
ERR_raise(ERR_LIB_PROV, PROV_R_XOF_DIGESTS_NOT_ALLOWED);
return 0;
}
/* These are taken from SP 800-90 10.1 Table 2 */
hash->blocklen = EVP_MD_get_size(md);
/* See SP800-57 Part1 Rev4 5.6.1 Table 3 */
ctx->strength = 64 * (hash->blocklen >> 3);
if (ctx->strength > 256)
ctx->strength = 256;
if (hash->blocklen > MAX_BLOCKLEN_USING_SMALL_SEEDLEN)
ctx->seedlen = HASH_PRNG_MAX_SEEDLEN;
else
ctx->seedlen = HASH_PRNG_SMALL_SEEDLEN;
ctx->min_entropylen = ctx->strength / 8;
ctx->min_noncelen = ctx->min_entropylen / 2;
}
return ossl_drbg_set_ctx_params(ctx, params);
}
static const OSSL_PARAM *drbg_hash_settable_ctx_params(ossl_unused void *vctx,
ossl_unused void *p_ctx)
{
static const OSSL_PARAM known_settable_ctx_params[] = {
OSSL_PARAM_utf8_string(OSSL_DRBG_PARAM_PROPERTIES, NULL, 0),
OSSL_PARAM_utf8_string(OSSL_DRBG_PARAM_DIGEST, NULL, 0),
OSSL_PARAM_DRBG_SETTABLE_CTX_COMMON,
OSSL_PARAM_END
};
return known_settable_ctx_params;
}
const OSSL_DISPATCH ossl_drbg_hash_functions[] = {
{ OSSL_FUNC_RAND_NEWCTX, (void(*)(void))drbg_hash_new_wrapper },
{ OSSL_FUNC_RAND_FREECTX, (void(*)(void))drbg_hash_free },
{ OSSL_FUNC_RAND_INSTANTIATE,
(void(*)(void))drbg_hash_instantiate_wrapper },
{ OSSL_FUNC_RAND_UNINSTANTIATE,
(void(*)(void))drbg_hash_uninstantiate_wrapper },
{ OSSL_FUNC_RAND_GENERATE, (void(*)(void))drbg_hash_generate_wrapper },
{ OSSL_FUNC_RAND_RESEED, (void(*)(void))drbg_hash_reseed_wrapper },
{ OSSL_FUNC_RAND_ENABLE_LOCKING, (void(*)(void))ossl_drbg_enable_locking },
{ OSSL_FUNC_RAND_LOCK, (void(*)(void))ossl_drbg_lock },
{ OSSL_FUNC_RAND_UNLOCK, (void(*)(void))ossl_drbg_unlock },
{ OSSL_FUNC_RAND_SETTABLE_CTX_PARAMS,
(void(*)(void))drbg_hash_settable_ctx_params },
{ OSSL_FUNC_RAND_SET_CTX_PARAMS, (void(*)(void))drbg_hash_set_ctx_params },
{ OSSL_FUNC_RAND_GETTABLE_CTX_PARAMS,
(void(*)(void))drbg_hash_gettable_ctx_params },
{ OSSL_FUNC_RAND_GET_CTX_PARAMS, (void(*)(void))drbg_hash_get_ctx_params },
{ OSSL_FUNC_RAND_VERIFY_ZEROIZATION,
(void(*)(void))drbg_hash_verify_zeroization },
{ OSSL_FUNC_RAND_GET_SEED, (void(*)(void))ossl_drbg_get_seed },
{ OSSL_FUNC_RAND_CLEAR_SEED, (void(*)(void))ossl_drbg_clear_seed },
{ 0, NULL }
};
diff --git a/crypto/openssl/providers/implementations/rands/drbg_hmac.c b/crypto/openssl/providers/implementations/rands/drbg_hmac.c
index e68465a78cd9..4eb78de0653d 100644
--- a/crypto/openssl/providers/implementations/rands/drbg_hmac.c
+++ b/crypto/openssl/providers/implementations/rands/drbg_hmac.c
@@ -1,432 +1,433 @@
/*
- * Copyright 2011-2021 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2011-2024 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 <stdlib.h>
#include <string.h>
#include <openssl/crypto.h>
#include <openssl/err.h>
#include <openssl/rand.h>
#include <openssl/proverr.h>
#include "prov/provider_util.h"
#include "internal/thread_once.h"
#include "prov/providercommon.h"
#include "prov/implementations.h"
#include "prov/provider_ctx.h"
#include "drbg_local.h"
static OSSL_FUNC_rand_newctx_fn drbg_hmac_new_wrapper;
static OSSL_FUNC_rand_freectx_fn drbg_hmac_free;
static OSSL_FUNC_rand_instantiate_fn drbg_hmac_instantiate_wrapper;
static OSSL_FUNC_rand_uninstantiate_fn drbg_hmac_uninstantiate_wrapper;
static OSSL_FUNC_rand_generate_fn drbg_hmac_generate_wrapper;
static OSSL_FUNC_rand_reseed_fn drbg_hmac_reseed_wrapper;
static OSSL_FUNC_rand_settable_ctx_params_fn drbg_hmac_settable_ctx_params;
static OSSL_FUNC_rand_set_ctx_params_fn drbg_hmac_set_ctx_params;
static OSSL_FUNC_rand_gettable_ctx_params_fn drbg_hmac_gettable_ctx_params;
static OSSL_FUNC_rand_get_ctx_params_fn drbg_hmac_get_ctx_params;
static OSSL_FUNC_rand_verify_zeroization_fn drbg_hmac_verify_zeroization;
typedef struct rand_drbg_hmac_st {
EVP_MAC_CTX *ctx; /* H(x) = HMAC_hash OR H(x) = KMAC */
PROV_DIGEST digest; /* H(x) = hash(x) */
size_t blocklen;
unsigned char K[EVP_MAX_MD_SIZE];
unsigned char V[EVP_MAX_MD_SIZE];
} PROV_DRBG_HMAC;
/*
* Called twice by SP800-90Ar1 10.1.2.2 HMAC_DRBG_Update_Process.
*
* hmac is an object that holds the input/output Key and Value (K and V).
* inbyte is 0x00 on the first call and 0x01 on the second call.
* in1, in2, in3 are optional inputs that can be NULL.
* in1len, in2len, in3len are the lengths of the input buffers.
*
* The returned K,V is:
* hmac->K = HMAC(hmac->K, hmac->V || inbyte || [in1] || [in2] || [in3])
* hmac->V = HMAC(hmac->K, hmac->V)
*
* Returns zero if an error occurs otherwise it returns 1.
*/
static int do_hmac(PROV_DRBG_HMAC *hmac, unsigned char inbyte,
const unsigned char *in1, size_t in1len,
const unsigned char *in2, size_t in2len,
const unsigned char *in3, size_t in3len)
{
EVP_MAC_CTX *ctx = hmac->ctx;
if (!EVP_MAC_init(ctx, hmac->K, hmac->blocklen, NULL)
/* K = HMAC(K, V || inbyte || [in1] || [in2] || [in3]) */
|| !EVP_MAC_update(ctx, hmac->V, hmac->blocklen)
|| !EVP_MAC_update(ctx, &inbyte, 1)
|| !(in1 == NULL || in1len == 0 || EVP_MAC_update(ctx, in1, in1len))
|| !(in2 == NULL || in2len == 0 || EVP_MAC_update(ctx, in2, in2len))
|| !(in3 == NULL || in3len == 0 || EVP_MAC_update(ctx, in3, in3len))
|| !EVP_MAC_final(ctx, hmac->K, NULL, sizeof(hmac->K)))
return 0;
/* V = HMAC(K, V) */
return EVP_MAC_init(ctx, hmac->K, hmac->blocklen, NULL)
&& EVP_MAC_update(ctx, hmac->V, hmac->blocklen)
&& EVP_MAC_final(ctx, hmac->V, NULL, sizeof(hmac->V));
}
/*
* SP800-90Ar1 10.1.2.2 HMAC_DRBG_Update_Process
*
*
* Updates the drbg objects Key(K) and Value(V) using the following algorithm:
* K,V = do_hmac(hmac, 0, in1, in2, in3)
* if (any input is not NULL)
* K,V = do_hmac(hmac, 1, in1, in2, in3)
*
* where in1, in2, in3 are optional input buffers that can be NULL.
* in1len, in2len, in3len are the lengths of the input buffers.
*
* Returns zero if an error occurs otherwise it returns 1.
*/
static int drbg_hmac_update(PROV_DRBG *drbg,
const unsigned char *in1, size_t in1len,
const unsigned char *in2, size_t in2len,
const unsigned char *in3, size_t in3len)
{
PROV_DRBG_HMAC *hmac = (PROV_DRBG_HMAC *)drbg->data;
/* (Steps 1-2) K = HMAC(K, V||0x00||provided_data). V = HMAC(K,V) */
if (!do_hmac(hmac, 0x00, in1, in1len, in2, in2len, in3, in3len))
return 0;
/* (Step 3) If provided_data == NULL then return (K,V) */
if (in1len == 0 && in2len == 0 && in3len == 0)
return 1;
/* (Steps 4-5) K = HMAC(K, V||0x01||provided_data). V = HMAC(K,V) */
return do_hmac(hmac, 0x01, in1, in1len, in2, in2len, in3, in3len);
}
/*
* SP800-90Ar1 10.1.2.3 HMAC_DRBG_Instantiate_Process:
*
* This sets the drbg Key (K) to all zeros, and Value (V) to all 1's.
* and then calls (K,V) = drbg_hmac_update() with input parameters:
* ent = entropy data (Can be NULL) of length ent_len.
* nonce = nonce data (Can be NULL) of length nonce_len.
* pstr = personalization data (Can be NULL) of length pstr_len.
*
* Returns zero if an error occurs otherwise it returns 1.
*/
static int drbg_hmac_instantiate(PROV_DRBG *drbg,
const unsigned char *ent, size_t ent_len,
const unsigned char *nonce, size_t nonce_len,
const unsigned char *pstr, size_t pstr_len)
{
PROV_DRBG_HMAC *hmac = (PROV_DRBG_HMAC *)drbg->data;
if (hmac->ctx == NULL) {
ERR_raise(ERR_LIB_PROV, PROV_R_MISSING_MAC);
return 0;
}
/* (Step 2) Key = 0x00 00...00 */
memset(hmac->K, 0x00, hmac->blocklen);
/* (Step 3) V = 0x01 01...01 */
memset(hmac->V, 0x01, hmac->blocklen);
/* (Step 4) (K,V) = HMAC_DRBG_Update(entropy||nonce||pers string, K, V) */
return drbg_hmac_update(drbg, ent, ent_len, nonce, nonce_len, pstr,
pstr_len);
}
static int drbg_hmac_instantiate_wrapper(void *vdrbg, unsigned int strength,
int prediction_resistance,
const unsigned char *pstr,
size_t pstr_len,
const OSSL_PARAM params[])
{
PROV_DRBG *drbg = (PROV_DRBG *)vdrbg;
if (!ossl_prov_is_running() || !drbg_hmac_set_ctx_params(drbg, params))
return 0;
return ossl_prov_drbg_instantiate(drbg, strength, prediction_resistance,
pstr, pstr_len);
}
/*
* SP800-90Ar1 10.1.2.4 HMAC_DRBG_Reseed_Process:
*
* Reseeds the drbg's Key (K) and Value (V) by calling
* (K,V) = drbg_hmac_update() with the following input parameters:
* ent = entropy input data (Can be NULL) of length ent_len.
* adin = additional input data (Can be NULL) of length adin_len.
*
* Returns zero if an error occurs otherwise it returns 1.
*/
static int drbg_hmac_reseed(PROV_DRBG *drbg,
const unsigned char *ent, size_t ent_len,
const unsigned char *adin, size_t adin_len)
{
/* (Step 2) (K,V) = HMAC_DRBG_Update(entropy||additional_input, K, V) */
return drbg_hmac_update(drbg, ent, ent_len, adin, adin_len, NULL, 0);
}
static int drbg_hmac_reseed_wrapper(void *vdrbg, int prediction_resistance,
const unsigned char *ent, size_t ent_len,
const unsigned char *adin, size_t adin_len)
{
PROV_DRBG *drbg = (PROV_DRBG *)vdrbg;
return ossl_prov_drbg_reseed(drbg, prediction_resistance, ent, ent_len,
adin, adin_len);
}
/*
* SP800-90Ar1 10.1.2.5 HMAC_DRBG_Generate_Process:
*
* Generates pseudo random bytes and updates the internal K,V for the drbg.
* out is a buffer to fill with outlen bytes of pseudo random data.
* adin is an additional_input string of size adin_len that may be NULL.
*
* Returns zero if an error occurs otherwise it returns 1.
*/
static int drbg_hmac_generate(PROV_DRBG *drbg,
unsigned char *out, size_t outlen,
const unsigned char *adin, size_t adin_len)
{
PROV_DRBG_HMAC *hmac = (PROV_DRBG_HMAC *)drbg->data;
EVP_MAC_CTX *ctx = hmac->ctx;
const unsigned char *temp = hmac->V;
/* (Step 2) if adin != NULL then (K,V) = HMAC_DRBG_Update(adin, K, V) */
if (adin != NULL
&& adin_len > 0
&& !drbg_hmac_update(drbg, adin, adin_len, NULL, 0, NULL, 0))
return 0;
/*
* (Steps 3-5) temp = NULL
* while (len(temp) < outlen) {
* V = HMAC(K, V)
* temp = temp || V
* }
*/
for (;;) {
if (!EVP_MAC_init(ctx, hmac->K, hmac->blocklen, NULL)
|| !EVP_MAC_update(ctx, temp, hmac->blocklen))
return 0;
if (outlen > hmac->blocklen) {
if (!EVP_MAC_final(ctx, out, NULL, outlen))
return 0;
temp = out;
} else {
if (!EVP_MAC_final(ctx, hmac->V, NULL, sizeof(hmac->V)))
return 0;
memcpy(out, hmac->V, outlen);
break;
}
out += hmac->blocklen;
outlen -= hmac->blocklen;
}
/* (Step 6) (K,V) = HMAC_DRBG_Update(adin, K, V) */
if (!drbg_hmac_update(drbg, adin, adin_len, NULL, 0, NULL, 0))
return 0;
return 1;
}
static int drbg_hmac_generate_wrapper
(void *vdrbg, unsigned char *out, size_t outlen, unsigned int strength,
int prediction_resistance, const unsigned char *adin, size_t adin_len)
{
PROV_DRBG *drbg = (PROV_DRBG *)vdrbg;
return ossl_prov_drbg_generate(drbg, out, outlen, strength,
prediction_resistance, adin, adin_len);
}
static int drbg_hmac_uninstantiate(PROV_DRBG *drbg)
{
PROV_DRBG_HMAC *hmac = (PROV_DRBG_HMAC *)drbg->data;
OPENSSL_cleanse(hmac->K, sizeof(hmac->K));
OPENSSL_cleanse(hmac->V, sizeof(hmac->V));
return ossl_prov_drbg_uninstantiate(drbg);
}
static int drbg_hmac_uninstantiate_wrapper(void *vdrbg)
{
return drbg_hmac_uninstantiate((PROV_DRBG *)vdrbg);
}
static int drbg_hmac_verify_zeroization(void *vdrbg)
{
PROV_DRBG *drbg = (PROV_DRBG *)vdrbg;
PROV_DRBG_HMAC *hmac = (PROV_DRBG_HMAC *)drbg->data;
PROV_DRBG_VERYIFY_ZEROIZATION(hmac->K);
PROV_DRBG_VERYIFY_ZEROIZATION(hmac->V);
return 1;
}
static int drbg_hmac_new(PROV_DRBG *drbg)
{
PROV_DRBG_HMAC *hmac;
hmac = OPENSSL_secure_zalloc(sizeof(*hmac));
if (hmac == NULL) {
ERR_raise(ERR_LIB_PROV, ERR_R_MALLOC_FAILURE);
return 0;
}
drbg->data = hmac;
/* See SP800-57 Part1 Rev4 5.6.1 Table 3 */
drbg->max_entropylen = DRBG_MAX_LENGTH;
drbg->max_noncelen = DRBG_MAX_LENGTH;
drbg->max_perslen = DRBG_MAX_LENGTH;
drbg->max_adinlen = DRBG_MAX_LENGTH;
/* Maximum number of bits per request = 2^19 = 2^16 bytes */
drbg->max_request = 1 << 16;
return 1;
}
static void *drbg_hmac_new_wrapper(void *provctx, void *parent,
const OSSL_DISPATCH *parent_dispatch)
{
- return ossl_rand_drbg_new(provctx, parent, parent_dispatch, &drbg_hmac_new,
+ return ossl_rand_drbg_new(provctx, parent, parent_dispatch,
+ &drbg_hmac_new, &drbg_hmac_free,
&drbg_hmac_instantiate, &drbg_hmac_uninstantiate,
&drbg_hmac_reseed, &drbg_hmac_generate);
}
static void drbg_hmac_free(void *vdrbg)
{
PROV_DRBG *drbg = (PROV_DRBG *)vdrbg;
PROV_DRBG_HMAC *hmac;
if (drbg != NULL && (hmac = (PROV_DRBG_HMAC *)drbg->data) != NULL) {
EVP_MAC_CTX_free(hmac->ctx);
ossl_prov_digest_reset(&hmac->digest);
OPENSSL_secure_clear_free(hmac, sizeof(*hmac));
}
ossl_rand_drbg_free(drbg);
}
static int drbg_hmac_get_ctx_params(void *vdrbg, OSSL_PARAM params[])
{
PROV_DRBG *drbg = (PROV_DRBG *)vdrbg;
PROV_DRBG_HMAC *hmac = (PROV_DRBG_HMAC *)drbg->data;
const char *name;
const EVP_MD *md;
OSSL_PARAM *p;
p = OSSL_PARAM_locate(params, OSSL_DRBG_PARAM_MAC);
if (p != NULL) {
if (hmac->ctx == NULL)
return 0;
name = EVP_MAC_get0_name(EVP_MAC_CTX_get0_mac(hmac->ctx));
if (!OSSL_PARAM_set_utf8_string(p, name))
return 0;
}
p = OSSL_PARAM_locate(params, OSSL_DRBG_PARAM_DIGEST);
if (p != NULL) {
md = ossl_prov_digest_md(&hmac->digest);
if (md == NULL || !OSSL_PARAM_set_utf8_string(p, EVP_MD_get0_name(md)))
return 0;
}
return ossl_drbg_get_ctx_params(drbg, params);
}
static const OSSL_PARAM *drbg_hmac_gettable_ctx_params(ossl_unused void *vctx,
ossl_unused void *p_ctx)
{
static const OSSL_PARAM known_gettable_ctx_params[] = {
OSSL_PARAM_utf8_string(OSSL_DRBG_PARAM_MAC, NULL, 0),
OSSL_PARAM_utf8_string(OSSL_DRBG_PARAM_DIGEST, NULL, 0),
OSSL_PARAM_DRBG_GETTABLE_CTX_COMMON,
OSSL_PARAM_END
};
return known_gettable_ctx_params;
}
static int drbg_hmac_set_ctx_params(void *vctx, const OSSL_PARAM params[])
{
PROV_DRBG *ctx = (PROV_DRBG *)vctx;
PROV_DRBG_HMAC *hmac = (PROV_DRBG_HMAC *)ctx->data;
OSSL_LIB_CTX *libctx = PROV_LIBCTX_OF(ctx->provctx);
const EVP_MD *md;
if (!ossl_prov_digest_load_from_params(&hmac->digest, params, libctx))
return 0;
/*
* Confirm digest is allowed. We allow all digests that are not XOF
* (such as SHAKE). In FIPS mode, the fetch will fail for non-approved
* digests.
*/
md = ossl_prov_digest_md(&hmac->digest);
if (md != NULL && (EVP_MD_get_flags(md) & EVP_MD_FLAG_XOF) != 0) {
ERR_raise(ERR_LIB_PROV, PROV_R_XOF_DIGESTS_NOT_ALLOWED);
return 0;
}
if (!ossl_prov_macctx_load_from_params(&hmac->ctx, params,
NULL, NULL, NULL, libctx))
return 0;
if (hmac->ctx != NULL) {
/* These are taken from SP 800-90 10.1 Table 2 */
hmac->blocklen = EVP_MD_get_size(md);
/* See SP800-57 Part1 Rev4 5.6.1 Table 3 */
ctx->strength = 64 * (int)(hmac->blocklen >> 3);
if (ctx->strength > 256)
ctx->strength = 256;
ctx->seedlen = hmac->blocklen;
ctx->min_entropylen = ctx->strength / 8;
ctx->min_noncelen = ctx->min_entropylen / 2;
}
return ossl_drbg_set_ctx_params(ctx, params);
}
static const OSSL_PARAM *drbg_hmac_settable_ctx_params(ossl_unused void *vctx,
ossl_unused void *p_ctx)
{
static const OSSL_PARAM known_settable_ctx_params[] = {
OSSL_PARAM_utf8_string(OSSL_DRBG_PARAM_PROPERTIES, NULL, 0),
OSSL_PARAM_utf8_string(OSSL_DRBG_PARAM_DIGEST, NULL, 0),
OSSL_PARAM_utf8_string(OSSL_DRBG_PARAM_MAC, NULL, 0),
OSSL_PARAM_DRBG_SETTABLE_CTX_COMMON,
OSSL_PARAM_END
};
return known_settable_ctx_params;
}
const OSSL_DISPATCH ossl_drbg_ossl_hmac_functions[] = {
{ OSSL_FUNC_RAND_NEWCTX, (void(*)(void))drbg_hmac_new_wrapper },
{ OSSL_FUNC_RAND_FREECTX, (void(*)(void))drbg_hmac_free },
{ OSSL_FUNC_RAND_INSTANTIATE,
(void(*)(void))drbg_hmac_instantiate_wrapper },
{ OSSL_FUNC_RAND_UNINSTANTIATE,
(void(*)(void))drbg_hmac_uninstantiate_wrapper },
{ OSSL_FUNC_RAND_GENERATE, (void(*)(void))drbg_hmac_generate_wrapper },
{ OSSL_FUNC_RAND_RESEED, (void(*)(void))drbg_hmac_reseed_wrapper },
{ OSSL_FUNC_RAND_ENABLE_LOCKING, (void(*)(void))ossl_drbg_enable_locking },
{ OSSL_FUNC_RAND_LOCK, (void(*)(void))ossl_drbg_lock },
{ OSSL_FUNC_RAND_UNLOCK, (void(*)(void))ossl_drbg_unlock },
{ OSSL_FUNC_RAND_SETTABLE_CTX_PARAMS,
(void(*)(void))drbg_hmac_settable_ctx_params },
{ OSSL_FUNC_RAND_SET_CTX_PARAMS, (void(*)(void))drbg_hmac_set_ctx_params },
{ OSSL_FUNC_RAND_GETTABLE_CTX_PARAMS,
(void(*)(void))drbg_hmac_gettable_ctx_params },
{ OSSL_FUNC_RAND_GET_CTX_PARAMS, (void(*)(void))drbg_hmac_get_ctx_params },
{ OSSL_FUNC_RAND_VERIFY_ZEROIZATION,
(void(*)(void))drbg_hmac_verify_zeroization },
{ OSSL_FUNC_RAND_GET_SEED, (void(*)(void))ossl_drbg_get_seed },
{ OSSL_FUNC_RAND_CLEAR_SEED, (void(*)(void))ossl_drbg_clear_seed },
{ 0, NULL }
};
diff --git a/crypto/openssl/providers/implementations/rands/drbg_local.h b/crypto/openssl/providers/implementations/rands/drbg_local.h
index 8bc5df89c236..2f3aacdea871 100644
--- a/crypto/openssl/providers/implementations/rands/drbg_local.h
+++ b/crypto/openssl/providers/implementations/rands/drbg_local.h
@@ -1,259 +1,260 @@
/*
- * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 1995-2024 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#ifndef OSSL_CRYPTO_PROV_LOCAL_H
# define OSSL_CRYPTO_PROV_LOCAL_H
# include <openssl/evp.h>
# include <openssl/core_dispatch.h>
# include <openssl/core_names.h>
# include <openssl/params.h>
# include "internal/tsan_assist.h"
# include "internal/nelem.h"
# include "internal/numbers.h"
# include "prov/provider_ctx.h"
/* How many times to read the TSC as a randomness source. */
# define TSC_READ_COUNT 4
/* Maximum reseed intervals */
# define MAX_RESEED_INTERVAL (1 << 24)
# define MAX_RESEED_TIME_INTERVAL (1 << 20) /* approx. 12 days */
/* Default reseed intervals */
# define RESEED_INTERVAL (1 << 8)
# define TIME_INTERVAL (60*60) /* 1 hour */
/*
* The number of bytes that constitutes an atomic lump of entropy with respect
* to the FIPS 140-2 section 4.9.2 Conditional Tests. The size is somewhat
* arbitrary, the smaller the value, the less entropy is consumed on first
* read but the higher the probability of the test failing by accident.
*
* The value is in bytes.
*/
#define CRNGT_BUFSIZ 16
/*
* Maximum input size for the DRBG (entropy, nonce, personalization string)
*
* NIST SP800 90Ar1 allows a maximum of (1 << 35) bits i.e., (1 << 32) bytes.
*
* We lower it to 'only' INT32_MAX bytes, which is equivalent to 2 gigabytes.
*/
# define DRBG_MAX_LENGTH INT32_MAX
/* The default nonce */
#ifdef CHARSET_EBCDIC
# define DRBG_DEFAULT_PERS_STRING { 0x4f, 0x70, 0x65, 0x6e, 0x53, 0x53, \
0x4c, 0x20, 0x4e, 0x49, 0x53, 0x54, 0x20, 0x53, 0x50, 0x20, 0x38, 0x30, \
0x30, 0x2d, 0x39, 0x30, 0x41, 0x20, 0x44, 0x52, 0x42, 0x47, 0x00};
#else
# define DRBG_DEFAULT_PERS_STRING "OpenSSL NIST SP 800-90A DRBG"
#endif
typedef struct prov_drbg_st PROV_DRBG;
/* DRBG status values */
typedef enum drbg_status_e {
DRBG_UNINITIALISED,
DRBG_READY,
DRBG_ERROR
} DRBG_STATUS;
/*
* The state of all types of DRBGs.
*/
struct prov_drbg_st {
CRYPTO_RWLOCK *lock;
PROV_CTX *provctx;
/* Virtual functions are cache here */
int (*instantiate)(PROV_DRBG *drbg,
const unsigned char *entropy, size_t entropylen,
const unsigned char *nonce, size_t noncelen,
const unsigned char *pers, size_t perslen);
int (*uninstantiate)(PROV_DRBG *ctx);
int (*reseed)(PROV_DRBG *drbg, const unsigned char *ent, size_t ent_len,
const unsigned char *adin, size_t adin_len);
int (*generate)(PROV_DRBG *, unsigned char *out, size_t outlen,
const unsigned char *adin, size_t adin_len);
/* Parent PROV_RAND and its dispatch table functions */
void *parent;
OSSL_FUNC_rand_enable_locking_fn *parent_enable_locking;
OSSL_FUNC_rand_lock_fn *parent_lock;
OSSL_FUNC_rand_unlock_fn *parent_unlock;
OSSL_FUNC_rand_get_ctx_params_fn *parent_get_ctx_params;
OSSL_FUNC_rand_nonce_fn *parent_nonce;
OSSL_FUNC_rand_get_seed_fn *parent_get_seed;
OSSL_FUNC_rand_clear_seed_fn *parent_clear_seed;
const OSSL_DISPATCH *parent_dispatch;
/*
* Stores the return value of openssl_get_fork_id() as of when we last
* reseeded. The DRBG reseeds automatically whenever drbg->fork_id !=
* openssl_get_fork_id(). Used to provide fork-safety and reseed this
* DRBG in the child process.
*/
int fork_id;
unsigned short flags; /* various external flags */
/*
* The following parameters are setup by the per-type "init" function.
*
* The supported types and their init functions are:
* (1) CTR_DRBG: drbg_ctr_init().
* (2) HMAC_DRBG: drbg_hmac_init().
* (3) HASH_DRBG: drbg_hash_init().
*
* The parameters are closely related to the ones described in
* section '10.2.1 CTR_DRBG' of [NIST SP 800-90Ar1], with one
* crucial difference: In the NIST standard, all counts are given
* in bits, whereas in OpenSSL entropy counts are given in bits
* and buffer lengths are given in bytes.
*
* Since this difference has lead to some confusion in the past,
* (see [GitHub Issue #2443], formerly [rt.openssl.org #4055])
* the 'len' suffix has been added to all buffer sizes for
* clarification.
*/
unsigned int strength;
size_t max_request;
size_t min_entropylen, max_entropylen;
size_t min_noncelen, max_noncelen;
size_t max_perslen, max_adinlen;
/*
* Counts the number of generate requests since the last reseed
* (Starts at 1). This value is the reseed_counter as defined in
* NIST SP 800-90Ar1
*/
unsigned int generate_counter;
/*
* Maximum number of generate requests until a reseed is required.
* This value is ignored if it is zero.
*/
unsigned int reseed_interval;
/* Stores the time when the last reseeding occurred */
time_t reseed_time;
/*
* Specifies the maximum time interval (in seconds) between reseeds.
* This value is ignored if it is zero.
*/
time_t reseed_time_interval;
/*
* Counts the number of reseeds since instantiation.
* This value is ignored if it is zero.
*
* This counter is used only for seed propagation from the <master> DRBG
* to its two children, the <public> and <private> DRBG. This feature is
* very special and its sole purpose is to ensure that any randomness which
* is added by PROV_add() or PROV_seed() will have an immediate effect on
* the output of PROV_bytes() resp. PROV_priv_bytes().
*/
TSAN_QUALIFIER unsigned int reseed_counter;
unsigned int reseed_next_counter;
unsigned int parent_reseed_counter;
size_t seedlen;
DRBG_STATUS state;
/* DRBG specific data */
void *data;
/* Entropy and nonce gathering callbacks */
void *callback_arg;
OSSL_INOUT_CALLBACK *get_entropy_fn;
OSSL_CALLBACK *cleanup_entropy_fn;
OSSL_INOUT_CALLBACK *get_nonce_fn;
OSSL_CALLBACK *cleanup_nonce_fn;
};
PROV_DRBG *ossl_rand_drbg_new
(void *provctx, void *parent, const OSSL_DISPATCH *parent_dispatch,
int (*dnew)(PROV_DRBG *ctx),
+ void (*dfree)(void *vctx),
int (*instantiate)(PROV_DRBG *drbg,
const unsigned char *entropy, size_t entropylen,
const unsigned char *nonce, size_t noncelen,
const unsigned char *pers, size_t perslen),
int (*uninstantiate)(PROV_DRBG *ctx),
int (*reseed)(PROV_DRBG *drbg, const unsigned char *ent, size_t ent_len,
const unsigned char *adin, size_t adin_len),
int (*generate)(PROV_DRBG *, unsigned char *out, size_t outlen,
const unsigned char *adin, size_t adin_len));
void ossl_rand_drbg_free(PROV_DRBG *drbg);
int ossl_prov_drbg_instantiate(PROV_DRBG *drbg, unsigned int strength,
int prediction_resistance,
const unsigned char *pers, size_t perslen);
int ossl_prov_drbg_uninstantiate(PROV_DRBG *drbg);
int ossl_prov_drbg_reseed(PROV_DRBG *drbg, int prediction_resistance,
const unsigned char *ent, size_t ent_len,
const unsigned char *adin, size_t adinlen);
int ossl_prov_drbg_generate(PROV_DRBG *drbg, unsigned char *out, size_t outlen,
unsigned int strength, int prediction_resistance,
const unsigned char *adin, size_t adinlen);
/* Seeding api */
OSSL_FUNC_rand_get_seed_fn ossl_drbg_get_seed;
OSSL_FUNC_rand_clear_seed_fn ossl_drbg_clear_seed;
/* Verify that an array of numeric values is all zero */
#define PROV_DRBG_VERYIFY_ZEROIZATION(v) \
{ \
size_t i; \
\
for (i = 0; i < OSSL_NELEM(v); i++) \
if ((v)[i] != 0) \
return 0; \
}
/* locking api */
OSSL_FUNC_rand_enable_locking_fn ossl_drbg_enable_locking;
OSSL_FUNC_rand_lock_fn ossl_drbg_lock;
OSSL_FUNC_rand_unlock_fn ossl_drbg_unlock;
/* Common parameters for all of our DRBGs */
int ossl_drbg_get_ctx_params(PROV_DRBG *drbg, OSSL_PARAM params[]);
int ossl_drbg_set_ctx_params(PROV_DRBG *drbg, const OSSL_PARAM params[]);
#define OSSL_PARAM_DRBG_SETTABLE_CTX_COMMON \
OSSL_PARAM_uint(OSSL_DRBG_PARAM_RESEED_REQUESTS, NULL), \
OSSL_PARAM_uint64(OSSL_DRBG_PARAM_RESEED_TIME_INTERVAL, NULL)
#define OSSL_PARAM_DRBG_GETTABLE_CTX_COMMON \
OSSL_PARAM_int(OSSL_RAND_PARAM_STATE, NULL), \
OSSL_PARAM_uint(OSSL_RAND_PARAM_STRENGTH, NULL), \
OSSL_PARAM_size_t(OSSL_RAND_PARAM_MAX_REQUEST, NULL), \
OSSL_PARAM_size_t(OSSL_DRBG_PARAM_MIN_ENTROPYLEN, NULL), \
OSSL_PARAM_size_t(OSSL_DRBG_PARAM_MAX_ENTROPYLEN, NULL), \
OSSL_PARAM_size_t(OSSL_DRBG_PARAM_MIN_NONCELEN, NULL), \
OSSL_PARAM_size_t(OSSL_DRBG_PARAM_MAX_NONCELEN, NULL), \
OSSL_PARAM_size_t(OSSL_DRBG_PARAM_MAX_PERSLEN, NULL), \
OSSL_PARAM_size_t(OSSL_DRBG_PARAM_MAX_ADINLEN, NULL), \
OSSL_PARAM_uint(OSSL_DRBG_PARAM_RESEED_COUNTER, NULL), \
OSSL_PARAM_time_t(OSSL_DRBG_PARAM_RESEED_TIME, NULL), \
OSSL_PARAM_uint(OSSL_DRBG_PARAM_RESEED_REQUESTS, NULL), \
OSSL_PARAM_uint64(OSSL_DRBG_PARAM_RESEED_TIME_INTERVAL, NULL)
/* Continuous test "entropy" calls */
size_t ossl_crngt_get_entropy(PROV_DRBG *drbg,
unsigned char **pout,
int entropy, size_t min_len, size_t max_len,
int prediction_resistance);
void ossl_crngt_cleanup_entropy(PROV_DRBG *drbg,
unsigned char *out, size_t outlen);
#endif
diff --git a/crypto/openssl/ssl/record/rec_layer_s3.c b/crypto/openssl/ssl/record/rec_layer_s3.c
index 4bcffcc41e36..779e998bb6ee 100644
--- a/crypto/openssl/ssl/record/rec_layer_s3.c
+++ b/crypto/openssl/ssl/record/rec_layer_s3.c
@@ -1,1819 +1,1834 @@
/*
* Copyright 1995-2024 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 <stdio.h>
#include <limits.h>
#include <errno.h>
#include "../ssl_local.h"
#include <openssl/evp.h>
#include <openssl/buffer.h>
#include <openssl/rand.h>
#include "record_local.h"
#include "internal/packet.h"
#include "internal/cryptlib.h"
#if defined(OPENSSL_SMALL_FOOTPRINT) || \
!( defined(AES_ASM) && ( \
defined(__x86_64) || defined(__x86_64__) || \
defined(_M_AMD64) || defined(_M_X64) ) \
)
# undef EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK
# define EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK 0
#endif
void RECORD_LAYER_init(RECORD_LAYER *rl, SSL *s)
{
rl->s = s;
RECORD_LAYER_set_first_record(&s->rlayer);
SSL3_RECORD_clear(rl->rrec, SSL_MAX_PIPELINES);
}
void RECORD_LAYER_clear(RECORD_LAYER *rl)
{
rl->rstate = SSL_ST_READ_HEADER;
/*
* Do I need to clear read_ahead? As far as I can tell read_ahead did not
* previously get reset by SSL_clear...so I'll keep it that way..but is
* that right?
*/
rl->packet = NULL;
rl->packet_length = 0;
rl->wnum = 0;
memset(rl->handshake_fragment, 0, sizeof(rl->handshake_fragment));
rl->handshake_fragment_len = 0;
rl->wpend_tot = 0;
rl->wpend_type = 0;
rl->wpend_ret = 0;
rl->wpend_buf = NULL;
SSL3_BUFFER_clear(&rl->rbuf);
ssl3_release_write_buffer(rl->s);
rl->numrpipes = 0;
SSL3_RECORD_clear(rl->rrec, SSL_MAX_PIPELINES);
RECORD_LAYER_reset_read_sequence(rl);
RECORD_LAYER_reset_write_sequence(rl);
if (rl->d)
DTLS_RECORD_LAYER_clear(rl);
}
void RECORD_LAYER_release(RECORD_LAYER *rl)
{
if (SSL3_BUFFER_is_initialised(&rl->rbuf))
ssl3_release_read_buffer(rl->s);
if (rl->numwpipes > 0)
ssl3_release_write_buffer(rl->s);
SSL3_RECORD_release(rl->rrec, SSL_MAX_PIPELINES);
}
/* Checks if we have unprocessed read ahead data pending */
int RECORD_LAYER_read_pending(const RECORD_LAYER *rl)
{
return SSL3_BUFFER_get_left(&rl->rbuf) != 0;
}
+int RECORD_LAYER_data_present(const RECORD_LAYER *rl)
+{
+ if (rl->rstate == SSL_ST_READ_BODY)
+ return 1;
+ if (RECORD_LAYER_processed_read_pending(rl))
+ return 1;
+ return 0;
+}
+
/* Checks if we have decrypted unread record data pending */
int RECORD_LAYER_processed_read_pending(const RECORD_LAYER *rl)
{
size_t curr_rec = 0, num_recs = RECORD_LAYER_get_numrpipes(rl);
const SSL3_RECORD *rr = rl->rrec;
while (curr_rec < num_recs && SSL3_RECORD_is_read(&rr[curr_rec]))
curr_rec++;
return curr_rec < num_recs;
}
int RECORD_LAYER_write_pending(const RECORD_LAYER *rl)
{
return (rl->numwpipes > 0)
&& SSL3_BUFFER_get_left(&rl->wbuf[rl->numwpipes - 1]) != 0;
}
void RECORD_LAYER_reset_read_sequence(RECORD_LAYER *rl)
{
memset(rl->read_sequence, 0, sizeof(rl->read_sequence));
}
void RECORD_LAYER_reset_write_sequence(RECORD_LAYER *rl)
{
memset(rl->write_sequence, 0, sizeof(rl->write_sequence));
}
size_t ssl3_pending(const SSL *s)
{
size_t i, num = 0;
if (s->rlayer.rstate == SSL_ST_READ_BODY)
return 0;
/* Take into account DTLS buffered app data */
if (SSL_IS_DTLS(s)) {
DTLS1_RECORD_DATA *rdata;
pitem *item, *iter;
iter = pqueue_iterator(s->rlayer.d->buffered_app_data.q);
while ((item = pqueue_next(&iter)) != NULL) {
rdata = item->data;
num += rdata->rrec.length;
}
}
for (i = 0; i < RECORD_LAYER_get_numrpipes(&s->rlayer); i++) {
if (SSL3_RECORD_get_type(&s->rlayer.rrec[i])
!= SSL3_RT_APPLICATION_DATA)
return num;
num += SSL3_RECORD_get_length(&s->rlayer.rrec[i]);
}
return num;
}
void SSL_CTX_set_default_read_buffer_len(SSL_CTX *ctx, size_t len)
{
ctx->default_read_buf_len = len;
}
void SSL_set_default_read_buffer_len(SSL *s, size_t len)
{
SSL3_BUFFER_set_default_len(RECORD_LAYER_get_rbuf(&s->rlayer), len);
}
const char *SSL_rstate_string_long(const SSL *s)
{
switch (s->rlayer.rstate) {
case SSL_ST_READ_HEADER:
return "read header";
case SSL_ST_READ_BODY:
return "read body";
case SSL_ST_READ_DONE:
return "read done";
default:
return "unknown";
}
}
const char *SSL_rstate_string(const SSL *s)
{
switch (s->rlayer.rstate) {
case SSL_ST_READ_HEADER:
return "RH";
case SSL_ST_READ_BODY:
return "RB";
case SSL_ST_READ_DONE:
return "RD";
default:
return "unknown";
}
}
/*
* Return values are as per SSL_read()
*/
int ssl3_read_n(SSL *s, 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
* s->rlayer.rbuf.buf specified by s->rlayer.packet and
* s->rlayer.packet_length. (If s->rlayer.read_ahead is set, 'max' bytes may
* be stored in rbuf [plus s->rlayer.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;
SSL3_BUFFER *rb;
if (n == 0)
return 0;
rb = &s->rlayer.rbuf;
if (rb->buf == NULL)
if (!ssl3_setup_read_buffer(s)) {
/* SSLfatal() already called */
return -1;
}
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;
s->rlayer.packet = rb->buf + rb->offset;
s->rlayer.packet_length = 0;
/* ... now we can act as if 'extend' was set */
}
+ if (!ossl_assert(s->rlayer.packet != NULL)) {
+ /* does not happen */
+ SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
+ return -1;
+ }
+
len = s->rlayer.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 (s->rlayer.packet != pkt && clearold == 1) {
memmove(pkt, s->rlayer.packet, len + left);
s->rlayer.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 (SSL_IS_DTLS(s)) {
if (left == 0 && extend)
return 0;
if (left > 0 && n > left)
n = left;
}
/* if there is enough in the buffer from a previous read, take some */
if (left >= n) {
s->rlayer.packet_length += n;
rb->left = left - n;
rb->offset += n;
*readbytes = n;
return 1;
}
/* else we need to read more data */
if (n > rb->len - rb->offset) {
/* does not happen */
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return -1;
}
/*
* Ktls always reads full records.
* Also, we always act like read_ahead is set for DTLS.
*/
if (!BIO_get_ktls_recv(s->rbio) && !s->rlayer.read_ahead
&& !SSL_IS_DTLS(s)) {
/* 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;
/*
* Now we have len+left bytes at the front of s->s3.rbuf.buf and
* need to read in more until we have len+n (up to len+max if
* possible)
*/
clear_sys_error();
if (s->rbio != NULL) {
s->rwstate = SSL_READING;
ret = BIO_read(s->rbio, pkt + len + left, max - left);
if (ret >= 0)
bioread = ret;
if (ret <= 0
&& !BIO_should_retry(s->rbio)
&& BIO_eof(s->rbio)) {
if (s->options & SSL_OP_IGNORE_UNEXPECTED_EOF) {
SSL_set_shutdown(s, SSL_RECEIVED_SHUTDOWN);
s->s3.warn_alert = SSL_AD_CLOSE_NOTIFY;
} else {
/*
* This reason code is part of the API and may be used by
* applications for control flow decisions.
*/
SSLfatal(s, SSL_AD_DECODE_ERROR,
SSL_R_UNEXPECTED_EOF_WHILE_READING);
}
}
} else {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_READ_BIO_NOT_SET);
ret = -1;
}
if (ret <= 0) {
rb->left = left;
if (s->mode & SSL_MODE_RELEASE_BUFFERS && !SSL_IS_DTLS(s))
if (len + left == 0)
ssl3_release_read_buffer(s);
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 (SSL_IS_DTLS(s)) {
if (n > left)
n = left; /* makes the while condition false */
}
}
/* done reading, now the book-keeping */
rb->offset += n;
rb->left = left - n;
s->rlayer.packet_length += n;
s->rwstate = SSL_NOTHING;
*readbytes = n;
return 1;
}
/*
* Call this to write data in records of type 'type' It will return <= 0 if
* not all data has been sent or non-blocking IO.
*/
int ssl3_write_bytes(SSL *s, int type, const void *buf_, size_t len,
size_t *written)
{
const unsigned char *buf = buf_;
size_t tot;
size_t n, max_send_fragment, split_send_fragment, maxpipes;
#if !defined(OPENSSL_NO_MULTIBLOCK) && EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK
size_t nw;
#endif
SSL3_BUFFER *wb = &s->rlayer.wbuf[0];
int i;
size_t tmpwrit;
s->rwstate = SSL_NOTHING;
tot = s->rlayer.wnum;
/*
* ensure that if we end up with a smaller value of data to write out
* than the original len from a write which didn't complete for
* non-blocking I/O and also somehow ended up avoiding the check for
* this in ssl3_write_pending/SSL_R_BAD_WRITE_RETRY as it must never be
* possible to end up with (len-tot) as a large number that will then
* promptly send beyond the end of the users buffer ... so we trap and
* report the error in a way the user will notice
*/
if ((len < s->rlayer.wnum)
|| ((wb->left != 0) && (len < (s->rlayer.wnum + s->rlayer.wpend_tot)))) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_BAD_LENGTH);
return -1;
}
if (s->early_data_state == SSL_EARLY_DATA_WRITING
&& !early_data_count_ok(s, len, 0, 1)) {
/* SSLfatal() already called */
return -1;
}
s->rlayer.wnum = 0;
/*
* If we are supposed to be sending a KeyUpdate or NewSessionTicket then go
* into init unless we have writes pending - in which case we should finish
* doing that first.
*/
if (wb->left == 0 && (s->key_update != SSL_KEY_UPDATE_NONE
|| s->ext.extra_tickets_expected > 0))
ossl_statem_set_in_init(s, 1);
/*
* When writing early data on the server side we could be "in_init" in
* between receiving the EoED and the CF - but we don't want to handle those
* messages yet.
*/
if (SSL_in_init(s) && !ossl_statem_get_in_handshake(s)
&& s->early_data_state != SSL_EARLY_DATA_UNAUTH_WRITING) {
i = s->handshake_func(s);
/* SSLfatal() already called */
if (i < 0)
return i;
if (i == 0) {
return -1;
}
}
/*
* first check if there is a SSL3_BUFFER still being written out. This
* will happen with non blocking IO
*/
if (wb->left != 0) {
/* SSLfatal() already called if appropriate */
i = ssl3_write_pending(s, type, &buf[tot], s->rlayer.wpend_tot,
&tmpwrit);
if (i <= 0) {
/* XXX should we ssl3_release_write_buffer if i<0? */
s->rlayer.wnum = tot;
return i;
}
tot += tmpwrit; /* this might be last fragment */
}
#if !defined(OPENSSL_NO_MULTIBLOCK) && EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK
/*
* Depending on platform multi-block can deliver several *times*
* better performance. Downside is that it has to allocate
* jumbo buffer to accommodate up to 8 records, but the
* compromise is considered worthy.
*/
if (type == SSL3_RT_APPLICATION_DATA
&& len >= 4 * (max_send_fragment = ssl_get_max_send_fragment(s))
&& s->compress == NULL
&& s->msg_callback == NULL
&& !SSL_WRITE_ETM(s)
&& SSL_USE_EXPLICIT_IV(s)
&& BIO_get_ktls_send(s->wbio) == 0
&& (EVP_CIPHER_get_flags(EVP_CIPHER_CTX_get0_cipher(s->enc_write_ctx))
& EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK) != 0) {
unsigned char aad[13];
EVP_CTRL_TLS1_1_MULTIBLOCK_PARAM mb_param;
size_t packlen;
int packleni;
/* minimize address aliasing conflicts */
if ((max_send_fragment & 0xfff) == 0)
max_send_fragment -= 512;
if (tot == 0 || wb->buf == NULL) { /* allocate jumbo buffer */
ssl3_release_write_buffer(s);
packlen = EVP_CIPHER_CTX_ctrl(s->enc_write_ctx,
EVP_CTRL_TLS1_1_MULTIBLOCK_MAX_BUFSIZE,
(int)max_send_fragment, NULL);
if (len >= 8 * max_send_fragment)
packlen *= 8;
else
packlen *= 4;
if (!ssl3_setup_write_buffer(s, 1, packlen)) {
/* SSLfatal() already called */
return -1;
}
} else if (tot == len) { /* done? */
/* free jumbo buffer */
ssl3_release_write_buffer(s);
*written = tot;
return 1;
}
n = (len - tot);
for (;;) {
if (n < 4 * max_send_fragment) {
/* free jumbo buffer */
ssl3_release_write_buffer(s);
break;
}
if (s->s3.alert_dispatch) {
i = s->method->ssl_dispatch_alert(s);
if (i <= 0) {
/* SSLfatal() already called if appropriate */
s->rlayer.wnum = tot;
return i;
}
}
if (n >= 8 * max_send_fragment)
nw = max_send_fragment * (mb_param.interleave = 8);
else
nw = max_send_fragment * (mb_param.interleave = 4);
memcpy(aad, s->rlayer.write_sequence, 8);
aad[8] = type;
aad[9] = (unsigned char)(s->version >> 8);
aad[10] = (unsigned char)(s->version);
aad[11] = 0;
aad[12] = 0;
mb_param.out = NULL;
mb_param.inp = aad;
mb_param.len = nw;
packleni = EVP_CIPHER_CTX_ctrl(s->enc_write_ctx,
EVP_CTRL_TLS1_1_MULTIBLOCK_AAD,
sizeof(mb_param), &mb_param);
packlen = (size_t)packleni;
if (packleni <= 0 || packlen > wb->len) { /* never happens */
/* free jumbo buffer */
ssl3_release_write_buffer(s);
break;
}
mb_param.out = wb->buf;
mb_param.inp = &buf[tot];
mb_param.len = nw;
if (EVP_CIPHER_CTX_ctrl(s->enc_write_ctx,
EVP_CTRL_TLS1_1_MULTIBLOCK_ENCRYPT,
sizeof(mb_param), &mb_param) <= 0)
return -1;
s->rlayer.write_sequence[7] += mb_param.interleave;
if (s->rlayer.write_sequence[7] < mb_param.interleave) {
int j = 6;
while (j >= 0 && (++s->rlayer.write_sequence[j--]) == 0) ;
}
wb->offset = 0;
wb->left = packlen;
s->rlayer.wpend_tot = nw;
s->rlayer.wpend_buf = &buf[tot];
s->rlayer.wpend_type = type;
s->rlayer.wpend_ret = nw;
i = ssl3_write_pending(s, type, &buf[tot], nw, &tmpwrit);
if (i <= 0) {
/* SSLfatal() already called if appropriate */
if (i < 0 && (!s->wbio || !BIO_should_retry(s->wbio))) {
/* free jumbo buffer */
ssl3_release_write_buffer(s);
}
s->rlayer.wnum = tot;
return i;
}
if (tmpwrit == n) {
/* free jumbo buffer */
ssl3_release_write_buffer(s);
*written = tot + tmpwrit;
return 1;
}
n -= tmpwrit;
tot += tmpwrit;
}
} else
#endif /* !defined(OPENSSL_NO_MULTIBLOCK) && EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK */
if (tot == len) { /* done? */
if (s->mode & SSL_MODE_RELEASE_BUFFERS && !SSL_IS_DTLS(s))
ssl3_release_write_buffer(s);
*written = tot;
return 1;
}
n = (len - tot);
max_send_fragment = ssl_get_max_send_fragment(s);
split_send_fragment = ssl_get_split_send_fragment(s);
/*
* If max_pipelines is 0 then this means "undefined" and we default to
* 1 pipeline. Similarly if the cipher does not support pipelined
* processing then we also only use 1 pipeline, or if we're not using
* explicit IVs
*/
maxpipes = s->max_pipelines;
if (maxpipes > SSL_MAX_PIPELINES) {
/*
* We should have prevented this when we set max_pipelines so we
* shouldn't get here
*/
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return -1;
}
if (maxpipes == 0
|| s->enc_write_ctx == NULL
|| (EVP_CIPHER_get_flags(EVP_CIPHER_CTX_get0_cipher(s->enc_write_ctx))
& EVP_CIPH_FLAG_PIPELINE) == 0
|| !SSL_USE_EXPLICIT_IV(s))
maxpipes = 1;
if (max_send_fragment == 0
|| split_send_fragment == 0
|| split_send_fragment > max_send_fragment) {
/*
* We should have prevented this when we set/get the split and max send
* fragments so we shouldn't get here
*/
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return -1;
}
for (;;) {
size_t pipelens[SSL_MAX_PIPELINES], tmppipelen, remain;
size_t numpipes, j;
if (n == 0)
numpipes = 1;
else
numpipes = ((n - 1) / split_send_fragment) + 1;
if (numpipes > maxpipes)
numpipes = maxpipes;
if (n / numpipes >= split_send_fragment) {
/*
* We have enough data to completely fill all available
* pipelines
*/
for (j = 0; j < numpipes; j++)
pipelens[j] = split_send_fragment;
} else {
/* We can partially fill all available pipelines */
tmppipelen = n / numpipes;
remain = n % numpipes;
for (j = 0; j < numpipes; j++) {
pipelens[j] = tmppipelen;
if (j < remain)
pipelens[j]++;
}
}
i = do_ssl3_write(s, type, &(buf[tot]), pipelens, numpipes, 0,
&tmpwrit);
if (i <= 0) {
/* SSLfatal() already called if appropriate */
/* XXX should we ssl3_release_write_buffer if i<0? */
s->rlayer.wnum = tot;
return i;
}
if (tmpwrit == n ||
(type == SSL3_RT_APPLICATION_DATA &&
(s->mode & SSL_MODE_ENABLE_PARTIAL_WRITE))) {
/*
* next chunk of data should get another prepended empty fragment
* in ciphersuites with known-IV weakness:
*/
s->s3.empty_fragment_done = 0;
if (tmpwrit == n
&& (s->mode & SSL_MODE_RELEASE_BUFFERS) != 0
&& !SSL_IS_DTLS(s))
ssl3_release_write_buffer(s);
*written = tot + tmpwrit;
return 1;
}
n -= tmpwrit;
tot += tmpwrit;
}
}
int do_ssl3_write(SSL *s, int type, const unsigned char *buf,
size_t *pipelens, size_t numpipes,
int create_empty_fragment, size_t *written)
{
WPACKET pkt[SSL_MAX_PIPELINES];
SSL3_RECORD wr[SSL_MAX_PIPELINES];
WPACKET *thispkt;
SSL3_RECORD *thiswr;
unsigned char *recordstart;
int i, mac_size, clear = 0;
size_t prefix_len = 0;
int eivlen = 0;
size_t align = 0;
SSL3_BUFFER *wb;
SSL_SESSION *sess;
size_t totlen = 0, len, wpinited = 0;
size_t j;
for (j = 0; j < numpipes; j++)
totlen += pipelens[j];
/*
* first check if there is a SSL3_BUFFER still being written out. This
* will happen with non blocking IO
*/
if (RECORD_LAYER_write_pending(&s->rlayer)) {
/* Calls SSLfatal() as required */
return ssl3_write_pending(s, type, buf, totlen, written);
}
/* If we have an alert to send, lets send it */
if (s->s3.alert_dispatch) {
i = s->method->ssl_dispatch_alert(s);
if (i <= 0) {
/* SSLfatal() already called if appropriate */
return i;
}
/* if it went, fall through and send more stuff */
}
if (s->rlayer.numwpipes < numpipes) {
if (!ssl3_setup_write_buffer(s, numpipes, 0)) {
/* SSLfatal() already called */
return -1;
}
}
if (totlen == 0 && !create_empty_fragment)
return 0;
sess = s->session;
if ((sess == NULL)
|| (s->enc_write_ctx == NULL)
|| (EVP_MD_CTX_get0_md(s->write_hash) == NULL)) {
clear = s->enc_write_ctx ? 0 : 1; /* must be AEAD cipher */
mac_size = 0;
} else {
mac_size = EVP_MD_CTX_get_size(s->write_hash);
if (mac_size < 0) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
goto err;
}
}
/*
* 'create_empty_fragment' is true only when this function calls itself
*/
if (!clear && !create_empty_fragment && !s->s3.empty_fragment_done) {
/*
* countermeasure against known-IV weakness in CBC ciphersuites (see
* http://www.openssl.org/~bodo/tls-cbc.txt)
*/
if (s->s3.need_empty_fragments && type == SSL3_RT_APPLICATION_DATA) {
/*
* recursive function call with 'create_empty_fragment' set; this
* prepares and buffers the data for an empty fragment (these
* 'prefix_len' bytes are sent out later together with the actual
* payload)
*/
size_t tmppipelen = 0;
int ret;
ret = do_ssl3_write(s, type, buf, &tmppipelen, 1, 1, &prefix_len);
if (ret <= 0) {
/* SSLfatal() already called if appropriate */
goto err;
}
if (prefix_len >
(SSL3_RT_HEADER_LENGTH + SSL3_RT_SEND_MAX_ENCRYPTED_OVERHEAD)) {
/* insufficient space */
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
goto err;
}
}
s->s3.empty_fragment_done = 1;
}
if (BIO_get_ktls_send(s->wbio)) {
/*
* ktls doesn't modify the buffer, but to avoid a warning we need to
* discard the const qualifier.
* This doesn't leak memory because the buffers have been released when
* switching to ktls.
*/
SSL3_BUFFER_set_buf(&s->rlayer.wbuf[0], (unsigned char *)buf);
SSL3_BUFFER_set_offset(&s->rlayer.wbuf[0], 0);
SSL3_BUFFER_set_app_buffer(&s->rlayer.wbuf[0], 1);
goto wpacket_init_complete;
}
if (create_empty_fragment) {
wb = &s->rlayer.wbuf[0];
#if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD!=0
/*
* extra fragment would be couple of cipher blocks, which would be
* multiple of SSL3_ALIGN_PAYLOAD, so if we want to align the real
* payload, then we can just pretend we simply have two headers.
*/
align = (size_t)SSL3_BUFFER_get_buf(wb) + 2 * SSL3_RT_HEADER_LENGTH;
align = SSL3_ALIGN_PAYLOAD - 1 - ((align - 1) % SSL3_ALIGN_PAYLOAD);
#endif
SSL3_BUFFER_set_offset(wb, align);
if (!WPACKET_init_static_len(&pkt[0], SSL3_BUFFER_get_buf(wb),
SSL3_BUFFER_get_len(wb), 0)
|| !WPACKET_allocate_bytes(&pkt[0], align, NULL)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
goto err;
}
wpinited = 1;
} else if (prefix_len) {
wb = &s->rlayer.wbuf[0];
if (!WPACKET_init_static_len(&pkt[0],
SSL3_BUFFER_get_buf(wb),
SSL3_BUFFER_get_len(wb), 0)
|| !WPACKET_allocate_bytes(&pkt[0], SSL3_BUFFER_get_offset(wb)
+ prefix_len, NULL)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
goto err;
}
wpinited = 1;
} else {
for (j = 0; j < numpipes; j++) {
thispkt = &pkt[j];
wb = &s->rlayer.wbuf[j];
#if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD != 0
align = (size_t)SSL3_BUFFER_get_buf(wb) + SSL3_RT_HEADER_LENGTH;
align = SSL3_ALIGN_PAYLOAD - 1 - ((align - 1) % SSL3_ALIGN_PAYLOAD);
#endif
SSL3_BUFFER_set_offset(wb, align);
if (!WPACKET_init_static_len(thispkt, SSL3_BUFFER_get_buf(wb),
SSL3_BUFFER_get_len(wb), 0)
|| !WPACKET_allocate_bytes(thispkt, align, NULL)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
goto err;
}
wpinited++;
}
}
/* Explicit IV length, block ciphers appropriate version flag */
if (s->enc_write_ctx && SSL_USE_EXPLICIT_IV(s) && !SSL_TREAT_AS_TLS13(s)) {
int mode = EVP_CIPHER_CTX_get_mode(s->enc_write_ctx);
if (mode == EVP_CIPH_CBC_MODE) {
eivlen = EVP_CIPHER_CTX_get_iv_length(s->enc_write_ctx);
if (eivlen < 0) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_LIBRARY_BUG);
goto err;
}
if (eivlen <= 1)
eivlen = 0;
} else if (mode == EVP_CIPH_GCM_MODE) {
/* Need explicit part of IV for GCM mode */
eivlen = EVP_GCM_TLS_EXPLICIT_IV_LEN;
} else if (mode == EVP_CIPH_CCM_MODE) {
eivlen = EVP_CCM_TLS_EXPLICIT_IV_LEN;
}
}
wpacket_init_complete:
totlen = 0;
/* Clear our SSL3_RECORD structures */
memset(wr, 0, sizeof(wr));
for (j = 0; j < numpipes; j++) {
unsigned int version = (s->version == TLS1_3_VERSION) ? TLS1_2_VERSION
: s->version;
unsigned char *compressdata = NULL;
size_t maxcomplen;
unsigned int rectype;
thispkt = &pkt[j];
thiswr = &wr[j];
/*
* In TLSv1.3, once encrypting, we always use application data for the
* record type
*/
if (SSL_TREAT_AS_TLS13(s)
&& s->enc_write_ctx != NULL
&& (s->statem.enc_write_state != ENC_WRITE_STATE_WRITE_PLAIN_ALERTS
|| type != SSL3_RT_ALERT))
rectype = SSL3_RT_APPLICATION_DATA;
else
rectype = type;
SSL3_RECORD_set_type(thiswr, rectype);
/*
* Some servers hang if initial client hello is larger than 256 bytes
* and record version number > TLS 1.0
*/
if (SSL_get_state(s) == TLS_ST_CW_CLNT_HELLO
&& !s->renegotiate
&& TLS1_get_version(s) > TLS1_VERSION
&& s->hello_retry_request == SSL_HRR_NONE)
version = TLS1_VERSION;
SSL3_RECORD_set_rec_version(thiswr, version);
maxcomplen = pipelens[j];
if (s->compress != NULL)
maxcomplen += SSL3_RT_MAX_COMPRESSED_OVERHEAD;
/*
* When using offload kernel will write the header.
* Otherwise write the header now
*/
if (!BIO_get_ktls_send(s->wbio)
&& (!WPACKET_put_bytes_u8(thispkt, rectype)
|| !WPACKET_put_bytes_u16(thispkt, version)
|| !WPACKET_start_sub_packet_u16(thispkt)
|| (eivlen > 0
&& !WPACKET_allocate_bytes(thispkt, eivlen, NULL))
|| (maxcomplen > 0
&& !WPACKET_reserve_bytes(thispkt, maxcomplen,
&compressdata)))) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
goto err;
}
/* lets setup the record stuff. */
SSL3_RECORD_set_data(thiswr, compressdata);
SSL3_RECORD_set_length(thiswr, pipelens[j]);
SSL3_RECORD_set_input(thiswr, (unsigned char *)&buf[totlen]);
totlen += pipelens[j];
/*
* we now 'read' from thiswr->input, thiswr->length bytes into
* thiswr->data
*/
/* first we compress */
if (s->compress != NULL) {
if (!ssl3_do_compress(s, thiswr)
|| !WPACKET_allocate_bytes(thispkt, thiswr->length, NULL)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_COMPRESSION_FAILURE);
goto err;
}
} else {
if (BIO_get_ktls_send(s->wbio)) {
SSL3_RECORD_reset_data(&wr[j]);
} else {
if (!WPACKET_memcpy(thispkt, thiswr->input, thiswr->length)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
goto err;
}
SSL3_RECORD_reset_input(&wr[j]);
}
}
if (SSL_TREAT_AS_TLS13(s)
&& !BIO_get_ktls_send(s->wbio)
&& s->enc_write_ctx != NULL
&& (s->statem.enc_write_state != ENC_WRITE_STATE_WRITE_PLAIN_ALERTS
|| type != SSL3_RT_ALERT)) {
size_t rlen, max_send_fragment;
if (!WPACKET_put_bytes_u8(thispkt, type)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
goto err;
}
SSL3_RECORD_add_length(thiswr, 1);
/* Add TLS1.3 padding */
max_send_fragment = ssl_get_max_send_fragment(s);
rlen = SSL3_RECORD_get_length(thiswr);
if (rlen < max_send_fragment) {
size_t padding = 0;
size_t max_padding = max_send_fragment - rlen;
if (s->record_padding_cb != NULL) {
padding = s->record_padding_cb(s, type, rlen, s->record_padding_arg);
} else if (s->block_padding > 0) {
size_t mask = s->block_padding - 1;
size_t remainder;
/* optimize for power of 2 */
if ((s->block_padding & mask) == 0)
remainder = rlen & mask;
else
remainder = rlen % s->block_padding;
/* don't want to add a block of padding if we don't have to */
if (remainder == 0)
padding = 0;
else
padding = s->block_padding - remainder;
}
if (padding > 0) {
/* do not allow the record to exceed max plaintext length */
if (padding > max_padding)
padding = max_padding;
if (!WPACKET_memset(thispkt, 0, padding)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR,
ERR_R_INTERNAL_ERROR);
goto err;
}
SSL3_RECORD_add_length(thiswr, padding);
}
}
}
/*
* 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 (!BIO_get_ktls_send(s->wbio) && !SSL_WRITE_ETM(s) && mac_size != 0) {
unsigned char *mac;
if (!WPACKET_allocate_bytes(thispkt, mac_size, &mac)
|| !s->method->ssl3_enc->mac(s, thiswr, mac, 1)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
goto err;
}
}
/*
* 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 (!BIO_get_ktls_send(s->wbio)) {
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)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
goto err;
}
/* Get a pointer to the start of this record excluding header */
recordstart = WPACKET_get_curr(thispkt) - len;
SSL3_RECORD_set_data(thiswr, recordstart);
SSL3_RECORD_reset_input(thiswr);
SSL3_RECORD_set_length(thiswr, len);
}
}
if (s->statem.enc_write_state == ENC_WRITE_STATE_WRITE_PLAIN_ALERTS) {
/*
* We haven't actually negotiated the version yet, but we're trying to
* send early data - so we need to use the tls13enc function.
*/
if (tls13_enc(s, wr, numpipes, 1, NULL, mac_size) < 1) {
if (!ossl_statem_in_error(s)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
}
goto err;
}
} else {
if (!BIO_get_ktls_send(s->wbio)) {
if (s->method->ssl3_enc->enc(s, wr, numpipes, 1, NULL,
mac_size) < 1) {
if (!ossl_statem_in_error(s)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
}
goto err;
}
}
}
for (j = 0; j < numpipes; j++) {
size_t origlen;
thispkt = &pkt[j];
thiswr = &wr[j];
if (BIO_get_ktls_send(s->wbio))
goto mac_done;
/* 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))) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
goto err;
}
if (SSL_WRITE_ETM(s) && mac_size != 0) {
unsigned char *mac;
if (!WPACKET_allocate_bytes(thispkt, mac_size, &mac)
|| !s->method->ssl3_enc->mac(s, thiswr, mac, 1)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
goto err;
}
SSL3_RECORD_add_length(thiswr, mac_size);
}
if (!WPACKET_get_length(thispkt, &len)
|| !WPACKET_close(thispkt)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
goto err;
}
if (s->msg_callback) {
recordstart = WPACKET_get_curr(thispkt) - len
- SSL3_RT_HEADER_LENGTH;
s->msg_callback(1, thiswr->rec_version, SSL3_RT_HEADER, recordstart,
SSL3_RT_HEADER_LENGTH, s,
s->msg_callback_arg);
if (SSL_TREAT_AS_TLS13(s) && s->enc_write_ctx != NULL) {
unsigned char ctype = type;
s->msg_callback(1, thiswr->rec_version, SSL3_RT_INNER_CONTENT_TYPE,
&ctype, 1, s, s->msg_callback_arg);
}
}
if (!WPACKET_finish(thispkt)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
goto err;
}
/* header is added by the kernel when using offload */
SSL3_RECORD_add_length(&wr[j], SSL3_RT_HEADER_LENGTH);
if (create_empty_fragment) {
/*
* we are in a recursive call; just return the length, don't write
* out anything here
*/
if (j > 0) {
/* We should never be pipelining an empty fragment!! */
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
goto err;
}
*written = SSL3_RECORD_get_length(thiswr);
return 1;
}
mac_done:
/*
* we should now have thiswr->data pointing to the encrypted data, which
* is thiswr->length long
*/
SSL3_RECORD_set_type(thiswr, type); /* not needed but helps for
* debugging */
/* now let's set up wb */
SSL3_BUFFER_set_left(&s->rlayer.wbuf[j],
prefix_len + SSL3_RECORD_get_length(thiswr));
}
/*
* memorize arguments so that ssl3_write_pending can detect bad write
* retries later
*/
s->rlayer.wpend_tot = totlen;
s->rlayer.wpend_buf = buf;
s->rlayer.wpend_type = type;
s->rlayer.wpend_ret = totlen;
/* we now just need to write the buffer */
return ssl3_write_pending(s, type, buf, totlen, written);
err:
for (j = 0; j < wpinited; j++)
WPACKET_cleanup(&pkt[j]);
return -1;
}
/* if s->s3.wbuf.left != 0, we need to call this
*
* Return values are as per SSL_write()
*/
int ssl3_write_pending(SSL *s, int type, const unsigned char *buf, size_t len,
size_t *written)
{
int i;
SSL3_BUFFER *wb = s->rlayer.wbuf;
size_t currbuf = 0;
size_t tmpwrit = 0;
if ((s->rlayer.wpend_tot > len)
|| (!(s->mode & SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER)
&& (s->rlayer.wpend_buf != buf))
|| (s->rlayer.wpend_type != type)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_BAD_WRITE_RETRY);
return -1;
}
for (;;) {
/* Loop until we find a buffer we haven't written out yet */
if (SSL3_BUFFER_get_left(&wb[currbuf]) == 0
&& currbuf < s->rlayer.numwpipes - 1) {
currbuf++;
continue;
}
clear_sys_error();
if (s->wbio != NULL) {
s->rwstate = SSL_WRITING;
/*
* To prevent coalescing of control and data messages,
* such as in buffer_write, we flush the BIO
*/
if (BIO_get_ktls_send(s->wbio) && type != SSL3_RT_APPLICATION_DATA) {
i = BIO_flush(s->wbio);
if (i <= 0)
return i;
BIO_set_ktls_ctrl_msg(s->wbio, type);
}
i = BIO_write(s->wbio, (char *)
&(SSL3_BUFFER_get_buf(&wb[currbuf])
[SSL3_BUFFER_get_offset(&wb[currbuf])]),
(unsigned int)SSL3_BUFFER_get_left(&wb[currbuf]));
if (i >= 0)
tmpwrit = i;
} else {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_BIO_NOT_SET);
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 == SSL3_BUFFER_get_left(&wb[currbuf])) {
SSL3_BUFFER_set_left(&wb[currbuf], 0);
SSL3_BUFFER_add_offset(&wb[currbuf], tmpwrit);
if (currbuf + 1 < s->rlayer.numwpipes)
continue;
s->rwstate = SSL_NOTHING;
*written = s->rlayer.wpend_ret;
return 1;
} else if (i <= 0) {
if (SSL_IS_DTLS(s)) {
/*
* For DTLS, just drop it. That's kind of the whole point in
* using a datagram service
*/
SSL3_BUFFER_set_left(&wb[currbuf], 0);
}
return i;
}
SSL3_BUFFER_add_offset(&wb[currbuf], tmpwrit);
SSL3_BUFFER_sub_left(&wb[currbuf], tmpwrit);
}
}
/*-
* Return up to 'len' payload bytes received in 'type' records.
* 'type' is one of the following:
*
* - SSL3_RT_HANDSHAKE (when ssl3_get_message calls us)
* - SSL3_RT_APPLICATION_DATA (when ssl3_read calls us)
* - 0 (during a shutdown, no data has to be returned)
*
* If we don't have stored data to work from, read a SSL/TLS record first
* (possibly multiple records if we still don't have anything to return).
*
* This function must handle any surprises the peer may have for us, such as
* Alert records (e.g. close_notify) or renegotiation requests. ChangeCipherSpec
* messages are treated as if they were handshake messages *if* the |recvd_type|
* argument is non NULL.
* Also if record payloads contain fragments too small to process, we store
* them until there is enough for the respective protocol (the record protocol
* may use arbitrary fragmentation and even interleaving):
* Change cipher spec protocol
* just 1 byte needed, no need for keeping anything stored
* Alert protocol
* 2 bytes needed (AlertLevel, AlertDescription)
* Handshake protocol
* 4 bytes needed (HandshakeType, uint24 length) -- we just have
* to detect unexpected Client Hello and Hello Request messages
* here, anything else is handled by higher layers
* Application data protocol
* none of our business
*/
int ssl3_read_bytes(SSL *s, int type, int *recvd_type, unsigned char *buf,
size_t len, int peek, size_t *readbytes)
{
int i, j, ret;
size_t n, curr_rec, num_recs, totalbytes;
SSL3_RECORD *rr;
SSL3_BUFFER *rbuf;
void (*cb) (const SSL *ssl, int type2, int val) = NULL;
int is_tls13 = SSL_IS_TLS13(s);
rbuf = &s->rlayer.rbuf;
if (!SSL3_BUFFER_is_initialised(rbuf)) {
/* Not initialized yet */
if (!ssl3_setup_read_buffer(s)) {
/* SSLfatal() already called */
return -1;
}
}
if ((type && (type != SSL3_RT_APPLICATION_DATA)
&& (type != SSL3_RT_HANDSHAKE)) || (peek
&& (type !=
SSL3_RT_APPLICATION_DATA))) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return -1;
}
if ((type == SSL3_RT_HANDSHAKE) && (s->rlayer.handshake_fragment_len > 0))
/* (partially) satisfy request from storage */
{
unsigned char *src = s->rlayer.handshake_fragment;
unsigned char *dst = buf;
unsigned int k;
/* peek == 0 */
n = 0;
while ((len > 0) && (s->rlayer.handshake_fragment_len > 0)) {
*dst++ = *src++;
len--;
s->rlayer.handshake_fragment_len--;
n++;
}
/* move any remaining fragment bytes: */
for (k = 0; k < s->rlayer.handshake_fragment_len; k++)
s->rlayer.handshake_fragment[k] = *src++;
if (recvd_type != NULL)
*recvd_type = SSL3_RT_HANDSHAKE;
*readbytes = n;
return 1;
}
/*
* Now s->rlayer.handshake_fragment_len == 0 if type == SSL3_RT_HANDSHAKE.
*/
if (!ossl_statem_get_in_handshake(s) && SSL_in_init(s)) {
/* type == SSL3_RT_APPLICATION_DATA */
i = s->handshake_func(s);
/* SSLfatal() already called */
if (i < 0)
return i;
if (i == 0)
return -1;
}
start:
s->rwstate = SSL_NOTHING;
/*-
* For each record 'i' up to |num_recs]
* rr[i].type - is the type of record
* rr[i].data, - data
* rr[i].off, - offset into 'data' for next read
* rr[i].length, - number of bytes.
*/
rr = s->rlayer.rrec;
num_recs = RECORD_LAYER_get_numrpipes(&s->rlayer);
do {
/* get new records if necessary */
if (num_recs == 0) {
ret = ssl3_get_record(s);
if (ret <= 0) {
/* SSLfatal() already called if appropriate */
return ret;
}
num_recs = RECORD_LAYER_get_numrpipes(&s->rlayer);
if (num_recs == 0) {
/* Shouldn't happen */
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return -1;
}
}
/* Skip over any records we have already read */
for (curr_rec = 0;
curr_rec < num_recs && SSL3_RECORD_is_read(&rr[curr_rec]);
curr_rec++) ;
if (curr_rec == num_recs) {
RECORD_LAYER_set_numrpipes(&s->rlayer, 0);
num_recs = 0;
curr_rec = 0;
}
} while (num_recs == 0);
rr = &rr[curr_rec];
if (s->rlayer.handshake_fragment_len > 0
&& SSL3_RECORD_get_type(rr) != SSL3_RT_HANDSHAKE
&& SSL_IS_TLS13(s)) {
SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
SSL_R_MIXED_HANDSHAKE_AND_NON_HANDSHAKE_DATA);
return -1;
}
/*
* Reset the count of consecutive warning alerts if we've got a non-empty
* record that isn't an alert.
*/
if (SSL3_RECORD_get_type(rr) != SSL3_RT_ALERT
&& SSL3_RECORD_get_length(rr) != 0)
s->rlayer.alert_count = 0;
/* we now have a packet which can be read and processed */
if (s->s3.change_cipher_spec /* set when we receive ChangeCipherSpec,
* reset by ssl3_get_finished */
&& (SSL3_RECORD_get_type(rr) != SSL3_RT_HANDSHAKE)) {
SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
SSL_R_DATA_BETWEEN_CCS_AND_FINISHED);
return -1;
}
/*
* If the other end has shut down, throw anything we read away (even in
* 'peek' mode)
*/
if (s->shutdown & SSL_RECEIVED_SHUTDOWN) {
SSL3_RECORD_set_length(rr, 0);
s->rwstate = SSL_NOTHING;
return 0;
}
if (type == SSL3_RECORD_get_type(rr)
|| (SSL3_RECORD_get_type(rr) == SSL3_RT_CHANGE_CIPHER_SPEC
&& type == SSL3_RT_HANDSHAKE && recvd_type != NULL
&& !is_tls13)) {
/*
* SSL3_RT_APPLICATION_DATA or
* SSL3_RT_HANDSHAKE or
* SSL3_RT_CHANGE_CIPHER_SPEC
*/
/*
* make sure that we are not getting application data when we are
* doing a handshake for the first time
*/
if (SSL_in_init(s) && (type == SSL3_RT_APPLICATION_DATA) &&
(s->enc_read_ctx == NULL)) {
SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_APP_DATA_IN_HANDSHAKE);
return -1;
}
if (type == SSL3_RT_HANDSHAKE
&& SSL3_RECORD_get_type(rr) == SSL3_RT_CHANGE_CIPHER_SPEC
&& s->rlayer.handshake_fragment_len > 0) {
SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_CCS_RECEIVED_EARLY);
return -1;
}
if (recvd_type != NULL)
*recvd_type = SSL3_RECORD_get_type(rr);
if (len == 0) {
/*
* Mark a zero length record as read. This ensures multiple calls to
* SSL_read() with a zero length buffer will eventually cause
* SSL_pending() to report data as being available.
*/
if (SSL3_RECORD_get_length(rr) == 0)
SSL3_RECORD_set_read(rr);
return 0;
}
totalbytes = 0;
do {
if (len - totalbytes > SSL3_RECORD_get_length(rr))
n = SSL3_RECORD_get_length(rr);
else
n = len - totalbytes;
memcpy(buf, &(rr->data[rr->off]), n);
buf += n;
if (peek) {
/* Mark any zero length record as consumed CVE-2016-6305 */
if (SSL3_RECORD_get_length(rr) == 0)
SSL3_RECORD_set_read(rr);
} else {
if (s->options & SSL_OP_CLEANSE_PLAINTEXT)
OPENSSL_cleanse(&(rr->data[rr->off]), n);
SSL3_RECORD_sub_length(rr, n);
SSL3_RECORD_add_off(rr, n);
if (SSL3_RECORD_get_length(rr) == 0) {
s->rlayer.rstate = SSL_ST_READ_HEADER;
SSL3_RECORD_set_off(rr, 0);
SSL3_RECORD_set_read(rr);
}
}
if (SSL3_RECORD_get_length(rr) == 0
|| (peek && n == SSL3_RECORD_get_length(rr))) {
curr_rec++;
rr++;
}
totalbytes += n;
} while (type == SSL3_RT_APPLICATION_DATA && curr_rec < num_recs
&& totalbytes < len);
if (totalbytes == 0) {
/* We must have read empty records. Get more data */
goto start;
}
if (!peek && curr_rec == num_recs
&& (s->mode & SSL_MODE_RELEASE_BUFFERS)
&& SSL3_BUFFER_get_left(rbuf) == 0)
ssl3_release_read_buffer(s);
*readbytes = totalbytes;
return 1;
}
/*
* If we get here, then type != rr->type; if we have a handshake message,
* then it was unexpected (Hello Request or Client Hello) or invalid (we
* were actually expecting a CCS).
*/
/*
* Lets just double check that we've not got an SSLv2 record
*/
if (rr->rec_version == SSL2_VERSION) {
/*
* Should never happen. ssl3_get_record() should only give us an SSLv2
* record back if this is the first packet and we are looking for an
* initial ClientHello. Therefore |type| should always be equal to
* |rr->type|. If not then something has gone horribly wrong
*/
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return -1;
}
if (s->method->version == TLS_ANY_VERSION
&& (s->server || rr->type != SSL3_RT_ALERT)) {
/*
* If we've got this far and still haven't decided on what version
* we're using then this must be a client side alert we're dealing
* with. We shouldn't be receiving anything other than a ClientHello
* if we are a server.
*/
s->version = rr->rec_version;
SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_MESSAGE);
return -1;
}
/*-
* s->rlayer.handshake_fragment_len == 4 iff rr->type == SSL3_RT_HANDSHAKE;
* (Possibly rr is 'empty' now, i.e. rr->length may be 0.)
*/
if (SSL3_RECORD_get_type(rr) == SSL3_RT_ALERT) {
unsigned int alert_level, alert_descr;
unsigned char *alert_bytes = SSL3_RECORD_get_data(rr)
+ SSL3_RECORD_get_off(rr);
PACKET alert;
if (!PACKET_buf_init(&alert, alert_bytes, SSL3_RECORD_get_length(rr))
|| !PACKET_get_1(&alert, &alert_level)
|| !PACKET_get_1(&alert, &alert_descr)
|| PACKET_remaining(&alert) != 0) {
SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_INVALID_ALERT);
return -1;
}
if (s->msg_callback)
s->msg_callback(0, s->version, SSL3_RT_ALERT, alert_bytes, 2, s,
s->msg_callback_arg);
if (s->info_callback != NULL)
cb = s->info_callback;
else if (s->ctx->info_callback != NULL)
cb = s->ctx->info_callback;
if (cb != NULL) {
j = (alert_level << 8) | alert_descr;
cb(s, SSL_CB_READ_ALERT, j);
}
if (alert_level == SSL3_AL_WARNING
|| (is_tls13 && alert_descr == SSL_AD_USER_CANCELLED)) {
s->s3.warn_alert = alert_descr;
SSL3_RECORD_set_read(rr);
s->rlayer.alert_count++;
if (s->rlayer.alert_count == MAX_WARN_ALERT_COUNT) {
SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
SSL_R_TOO_MANY_WARN_ALERTS);
return -1;
}
}
/*
* Apart from close_notify the only other warning alert in TLSv1.3
* is user_cancelled - which we just ignore.
*/
if (is_tls13 && alert_descr == SSL_AD_USER_CANCELLED) {
goto start;
} else if (alert_descr == SSL_AD_CLOSE_NOTIFY
&& (is_tls13 || alert_level == SSL3_AL_WARNING)) {
s->shutdown |= SSL_RECEIVED_SHUTDOWN;
return 0;
} else if (alert_level == SSL3_AL_FATAL || is_tls13) {
s->rwstate = SSL_NOTHING;
s->s3.fatal_alert = alert_descr;
SSLfatal_data(s, SSL_AD_NO_ALERT,
SSL_AD_REASON_OFFSET + alert_descr,
"SSL alert number %d", alert_descr);
s->shutdown |= SSL_RECEIVED_SHUTDOWN;
SSL3_RECORD_set_read(rr);
SSL_CTX_remove_session(s->session_ctx, s->session);
return 0;
} else if (alert_descr == SSL_AD_NO_RENEGOTIATION) {
/*
* This is a warning but we receive it if we requested
* renegotiation and the peer denied it. Terminate with a fatal
* alert because if application tried to renegotiate it
* presumably had a good reason and expects it to succeed. In
* future we might have a renegotiation where we don't care if
* the peer refused it where we carry on.
*/
SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_NO_RENEGOTIATION);
return -1;
} else if (alert_level == SSL3_AL_WARNING) {
/* We ignore any other warning alert in TLSv1.2 and below */
goto start;
}
SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_UNKNOWN_ALERT_TYPE);
return -1;
}
if ((s->shutdown & SSL_SENT_SHUTDOWN) != 0) {
if (SSL3_RECORD_get_type(rr) == SSL3_RT_HANDSHAKE) {
BIO *rbio;
/*
* We ignore any handshake messages sent to us unless they are
* TLSv1.3 in which case we want to process them. For all other
* handshake messages we can't do anything reasonable with them
* because we are unable to write any response due to having already
* sent close_notify.
*/
if (!SSL_IS_TLS13(s)) {
SSL3_RECORD_set_length(rr, 0);
SSL3_RECORD_set_read(rr);
if ((s->mode & SSL_MODE_AUTO_RETRY) != 0)
goto start;
s->rwstate = SSL_READING;
rbio = SSL_get_rbio(s);
BIO_clear_retry_flags(rbio);
BIO_set_retry_read(rbio);
return -1;
}
} else {
/*
* The peer is continuing to send application data, but we have
* already sent close_notify. If this was expected we should have
* been called via SSL_read() and this would have been handled
* above.
* No alert sent because we already sent close_notify
*/
SSL3_RECORD_set_length(rr, 0);
SSL3_RECORD_set_read(rr);
SSLfatal(s, SSL_AD_NO_ALERT,
SSL_R_APPLICATION_DATA_AFTER_CLOSE_NOTIFY);
return -1;
}
}
/*
* For handshake data we have 'fragment' storage, so fill that so that we
* can process the header at a fixed place. This is done after the
* "SHUTDOWN" code above to avoid filling the fragment storage with data
* that we're just going to discard.
*/
if (SSL3_RECORD_get_type(rr) == SSL3_RT_HANDSHAKE) {
size_t dest_maxlen = sizeof(s->rlayer.handshake_fragment);
unsigned char *dest = s->rlayer.handshake_fragment;
size_t *dest_len = &s->rlayer.handshake_fragment_len;
n = dest_maxlen - *dest_len; /* available space in 'dest' */
if (SSL3_RECORD_get_length(rr) < n)
n = SSL3_RECORD_get_length(rr); /* available bytes */
/* now move 'n' bytes: */
memcpy(dest + *dest_len,
SSL3_RECORD_get_data(rr) + SSL3_RECORD_get_off(rr), n);
SSL3_RECORD_add_off(rr, n);
SSL3_RECORD_sub_length(rr, n);
*dest_len += n;
if (SSL3_RECORD_get_length(rr) == 0)
SSL3_RECORD_set_read(rr);
if (*dest_len < dest_maxlen)
goto start; /* fragment was too small */
}
if (SSL3_RECORD_get_type(rr) == SSL3_RT_CHANGE_CIPHER_SPEC) {
SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_CCS_RECEIVED_EARLY);
return -1;
}
/*
* Unexpected handshake message (ClientHello, NewSessionTicket (TLS1.3) or
* protocol violation)
*/
if ((s->rlayer.handshake_fragment_len >= 4)
&& !ossl_statem_get_in_handshake(s)) {
int ined = (s->early_data_state == SSL_EARLY_DATA_READING);
/* We found handshake data, so we're going back into init */
ossl_statem_set_in_init(s, 1);
i = s->handshake_func(s);
/* SSLfatal() already called if appropriate */
if (i < 0)
return i;
if (i == 0) {
return -1;
}
/*
* If we were actually trying to read early data and we found a
* handshake message, then we don't want to continue to try and read
* the application data any more. It won't be "early" now.
*/
if (ined)
return -1;
if (!(s->mode & SSL_MODE_AUTO_RETRY)) {
if (SSL3_BUFFER_get_left(rbuf) == 0) {
/* no read-ahead left? */
BIO *bio;
/*
* In the case where we try to read application data, but we
* trigger an SSL handshake, we return -1 with the retry
* option set. Otherwise renegotiation may cause nasty
* problems in the blocking world
*/
s->rwstate = SSL_READING;
bio = SSL_get_rbio(s);
BIO_clear_retry_flags(bio);
BIO_set_retry_read(bio);
return -1;
}
}
goto start;
}
switch (SSL3_RECORD_get_type(rr)) {
default:
/*
* TLS 1.0 and 1.1 say you SHOULD ignore unrecognised record types, but
* TLS 1.2 says you MUST send an unexpected message alert. We use the
* TLS 1.2 behaviour for all protocol versions to prevent issues where
* no progress is being made and the peer continually sends unrecognised
* record types, using up resources processing them.
*/
SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_RECORD);
return -1;
case SSL3_RT_CHANGE_CIPHER_SPEC:
case SSL3_RT_ALERT:
case SSL3_RT_HANDSHAKE:
/*
* we already handled all of these, with the possible exception of
* SSL3_RT_HANDSHAKE when ossl_statem_get_in_handshake(s) is true, but
* that should not happen when type != rr->type
*/
SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, ERR_R_INTERNAL_ERROR);
return -1;
case SSL3_RT_APPLICATION_DATA:
/*
* At this point, we were expecting handshake data, but have
* application data. If the library was running inside ssl3_read()
* (i.e. in_read_app_data is set) and it makes sense to read
* application data at this point (session renegotiation not yet
* started), we will indulge it.
*/
if (ossl_statem_app_data_allowed(s)) {
s->s3.in_read_app_data = 2;
return -1;
} else if (ossl_statem_skip_early_data(s)) {
/*
* This can happen after a client sends a CH followed by early_data,
* but the server responds with a HelloRetryRequest. The server
* reads the next record from the client expecting to find a
* plaintext ClientHello but gets a record which appears to be
* application data. The trial decrypt "works" because null
* decryption was applied. We just skip it and move on to the next
* record.
*/
if (!early_data_count_ok(s, rr->length,
EARLY_DATA_CIPHERTEXT_OVERHEAD, 0)) {
/* SSLfatal() already called */
return -1;
}
SSL3_RECORD_set_read(rr);
goto start;
} else {
SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_RECORD);
return -1;
}
}
}
void ssl3_record_sequence_update(unsigned char *seq)
{
int i;
for (i = 7; i >= 0; i--) {
++seq[i];
if (seq[i] != 0)
break;
}
}
/*
* Returns true if the current rrec was sent in SSLv2 backwards compatible
* format and false otherwise.
*/
int RECORD_LAYER_is_sslv2_record(RECORD_LAYER *rl)
{
return SSL3_RECORD_is_sslv2_record(&rl->rrec[0]);
}
/*
* Returns the length in bytes of the current rrec
*/
size_t RECORD_LAYER_get_rrec_length(RECORD_LAYER *rl)
{
return SSL3_RECORD_get_length(&rl->rrec[0]);
}
diff --git a/crypto/openssl/ssl/record/record.h b/crypto/openssl/ssl/record/record.h
index 234656bf9394..a2db6aa88e14 100644
--- a/crypto/openssl/ssl/record/record.h
+++ b/crypto/openssl/ssl/record/record.h
@@ -1,247 +1,248 @@
/*
- * Copyright 1995-2020 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 1995-2024 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
*/
/*****************************************************************************
* *
* These structures should be considered PRIVATE to the record layer. No *
* non-record layer code should be using these structures in any way. *
* *
*****************************************************************************/
typedef struct ssl3_buffer_st {
/* at least SSL3_RT_MAX_PACKET_SIZE bytes, see ssl3_setup_buffers() */
unsigned char *buf;
/* default buffer size (or 0 if no default set) */
size_t default_len;
/* buffer size */
size_t len;
/* where to 'copy from' */
size_t offset;
/* how many bytes left */
size_t left;
/* 'buf' is from application for KTLS */
int app_buffer;
} SSL3_BUFFER;
#define SEQ_NUM_SIZE 8
typedef struct ssl3_record_st {
/* Record layer version */
/* r */
int rec_version;
/* type of record */
/* r */
int type;
/* How many bytes available */
/* rw */
size_t length;
/*
* How many bytes were available before padding was removed? This is used
* to implement the MAC check in constant time for CBC records.
*/
/* rw */
size_t orig_len;
/* read/write offset into 'buf' */
/* r */
size_t off;
/* pointer to the record data */
/* rw */
unsigned char *data;
/* where the decode bytes are */
/* rw */
unsigned char *input;
/* only used with decompression - malloc()ed */
/* r */
unsigned char *comp;
/* Whether the data from this record has already been read or not */
/* r */
unsigned int read;
/* epoch number, needed by DTLS1 */
/* r */
unsigned long epoch;
/* sequence number, needed by DTLS1 */
/* r */
unsigned char seq_num[SEQ_NUM_SIZE];
} SSL3_RECORD;
typedef struct dtls1_bitmap_st {
/* Track 32 packets on 32-bit systems and 64 - on 64-bit systems */
unsigned long map;
/* Max record number seen so far, 64-bit value in big-endian encoding */
unsigned char max_seq_num[SEQ_NUM_SIZE];
} DTLS1_BITMAP;
typedef struct record_pqueue_st {
unsigned short epoch;
struct pqueue_st *q;
} record_pqueue;
typedef struct dtls1_record_data_st {
unsigned char *packet;
size_t packet_length;
SSL3_BUFFER rbuf;
SSL3_RECORD rrec;
#ifndef OPENSSL_NO_SCTP
struct bio_dgram_sctp_rcvinfo recordinfo;
#endif
} DTLS1_RECORD_DATA;
typedef struct dtls_record_layer_st {
/*
* The current data and handshake epoch. This is initially
* undefined, and starts at zero once the initial handshake is
* completed
*/
unsigned short r_epoch;
unsigned short w_epoch;
/* records being received in the current epoch */
DTLS1_BITMAP bitmap;
/* renegotiation starts a new set of sequence numbers */
DTLS1_BITMAP next_bitmap;
/* Received handshake records (processed and unprocessed) */
record_pqueue unprocessed_rcds;
record_pqueue processed_rcds;
/*
* Buffered application records. Only for records between CCS and
* Finished to prevent either protocol violation or unnecessary message
* loss.
*/
record_pqueue buffered_app_data;
/* save last and current sequence numbers for retransmissions */
unsigned char last_write_sequence[8];
unsigned char curr_write_sequence[8];
} DTLS_RECORD_LAYER;
/*****************************************************************************
* *
* This structure should be considered "opaque" to anything outside of the *
* record layer. No non-record layer code should be accessing the members of *
* this structure. *
* *
*****************************************************************************/
typedef struct record_layer_st {
/* The parent SSL structure */
SSL *s;
/*
* Read as many input bytes as possible (for
* non-blocking reads)
*/
int read_ahead;
/* where we are when reading */
int rstate;
/* How many pipelines can be used to read data */
size_t numrpipes;
/* How many pipelines can be used to write data */
size_t numwpipes;
/* read IO goes into here */
SSL3_BUFFER rbuf;
/* write IO goes into here */
SSL3_BUFFER wbuf[SSL_MAX_PIPELINES];
/* each decoded record goes in here */
SSL3_RECORD rrec[SSL_MAX_PIPELINES];
/* used internally to point at a raw packet */
unsigned char *packet;
size_t packet_length;
/* number of bytes sent so far */
size_t wnum;
unsigned char handshake_fragment[4];
size_t handshake_fragment_len;
/* The number of consecutive empty records we have received */
size_t empty_record_count;
/* partial write - check the numbers match */
/* number bytes written */
size_t wpend_tot;
int wpend_type;
/* number of bytes submitted */
size_t wpend_ret;
const unsigned char *wpend_buf;
unsigned char read_sequence[SEQ_NUM_SIZE];
unsigned char write_sequence[SEQ_NUM_SIZE];
/* Set to true if this is the first record in a connection */
unsigned int is_first_record;
/* Count of the number of consecutive warning alerts received */
unsigned int alert_count;
DTLS_RECORD_LAYER *d;
} RECORD_LAYER;
/*****************************************************************************
* *
* The following macros/functions represent the libssl internal API to the *
* record layer. Any libssl code may call these functions/macros *
* *
*****************************************************************************/
struct ssl_mac_buf_st {
unsigned char *mac;
int alloced;
};
typedef struct ssl_mac_buf_st SSL_MAC_BUF;
#define MIN_SSL2_RECORD_LEN 9
#define RECORD_LAYER_set_read_ahead(rl, ra) ((rl)->read_ahead = (ra))
#define RECORD_LAYER_get_read_ahead(rl) ((rl)->read_ahead)
#define RECORD_LAYER_get_packet(rl) ((rl)->packet)
#define RECORD_LAYER_get_packet_length(rl) ((rl)->packet_length)
#define RECORD_LAYER_add_packet_length(rl, inc) ((rl)->packet_length += (inc))
#define DTLS_RECORD_LAYER_get_w_epoch(rl) ((rl)->d->w_epoch)
#define DTLS_RECORD_LAYER_get_processed_rcds(rl) \
((rl)->d->processed_rcds)
#define DTLS_RECORD_LAYER_get_unprocessed_rcds(rl) \
((rl)->d->unprocessed_rcds)
#define RECORD_LAYER_get_rbuf(rl) (&(rl)->rbuf)
#define RECORD_LAYER_get_wbuf(rl) ((rl)->wbuf)
void RECORD_LAYER_init(RECORD_LAYER *rl, SSL *s);
void RECORD_LAYER_clear(RECORD_LAYER *rl);
void RECORD_LAYER_release(RECORD_LAYER *rl);
int RECORD_LAYER_read_pending(const RECORD_LAYER *rl);
int RECORD_LAYER_processed_read_pending(const RECORD_LAYER *rl);
int RECORD_LAYER_write_pending(const RECORD_LAYER *rl);
+int RECORD_LAYER_data_present(const RECORD_LAYER *rl);
void RECORD_LAYER_reset_read_sequence(RECORD_LAYER *rl);
void RECORD_LAYER_reset_write_sequence(RECORD_LAYER *rl);
int RECORD_LAYER_is_sslv2_record(RECORD_LAYER *rl);
size_t RECORD_LAYER_get_rrec_length(RECORD_LAYER *rl);
__owur size_t ssl3_pending(const SSL *s);
__owur int ssl3_write_bytes(SSL *s, int type, const void *buf, size_t len,
size_t *written);
int do_ssl3_write(SSL *s, int type, const unsigned char *buf,
size_t *pipelens, size_t numpipes,
int create_empty_fragment, size_t *written);
__owur int ssl3_read_bytes(SSL *s, int type, int *recvd_type,
unsigned char *buf, size_t len, int peek,
size_t *readbytes);
__owur int ssl3_setup_buffers(SSL *s);
__owur int ssl3_enc(SSL *s, SSL3_RECORD *inrecs, size_t n_recs, int send,
SSL_MAC_BUF *mac, size_t macsize);
__owur int n_ssl3_mac(SSL *ssl, SSL3_RECORD *rec, unsigned char *md, int send);
__owur int ssl3_write_pending(SSL *s, int type, const unsigned char *buf, size_t len,
size_t *written);
__owur int tls1_enc(SSL *s, SSL3_RECORD *recs, size_t n_recs, int sending,
SSL_MAC_BUF *mac, size_t macsize);
__owur int tls1_mac(SSL *ssl, SSL3_RECORD *rec, unsigned char *md, int send);
__owur int tls13_enc(SSL *s, SSL3_RECORD *recs, size_t n_recs, int send,
SSL_MAC_BUF *mac, size_t macsize);
int DTLS_RECORD_LAYER_new(RECORD_LAYER *rl);
void DTLS_RECORD_LAYER_free(RECORD_LAYER *rl);
void DTLS_RECORD_LAYER_clear(RECORD_LAYER *rl);
void DTLS_RECORD_LAYER_set_saved_w_epoch(RECORD_LAYER *rl, unsigned short e);
void DTLS_RECORD_LAYER_clear(RECORD_LAYER *rl);
void DTLS_RECORD_LAYER_set_write_sequence(RECORD_LAYER *rl, unsigned char *seq);
__owur int dtls1_read_bytes(SSL *s, int type, int *recvd_type,
unsigned char *buf, size_t len, int peek,
size_t *readbytes);
__owur int dtls1_write_bytes(SSL *s, int type, const void *buf, size_t len,
size_t *written);
int do_dtls1_write(SSL *s, int type, const unsigned char *buf,
size_t len, int create_empty_fragment, size_t *written);
void dtls1_reset_seq_numbers(SSL *s, int rw);
int dtls_buffer_listen_record(SSL *s, size_t len, unsigned char *seq,
size_t off);
diff --git a/crypto/openssl/ssl/record/ssl3_buffer.c b/crypto/openssl/ssl/record/ssl3_buffer.c
index 97b0c26ced81..e769235fe0de 100644
--- a/crypto/openssl/ssl/record/ssl3_buffer.c
+++ b/crypto/openssl/ssl/record/ssl3_buffer.c
@@ -1,195 +1,197 @@
/*
- * Copyright 1995-2023 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 1995-2024 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"
#include "record_local.h"
void SSL3_BUFFER_set_data(SSL3_BUFFER *b, const unsigned char *d, size_t n)
{
if (d != NULL)
memcpy(b->buf, d, n);
b->left = n;
b->offset = 0;
}
/*
* Clear the contents of an SSL3_BUFFER but retain any memory allocated. Also
* retains the default_len setting
*/
void SSL3_BUFFER_clear(SSL3_BUFFER *b)
{
b->offset = 0;
b->left = 0;
}
void SSL3_BUFFER_release(SSL3_BUFFER *b)
{
OPENSSL_free(b->buf);
b->buf = NULL;
}
int ssl3_setup_read_buffer(SSL *s)
{
unsigned char *p;
size_t len, align = 0, headerlen;
SSL3_BUFFER *b;
b = RECORD_LAYER_get_rbuf(&s->rlayer);
if (SSL_IS_DTLS(s))
headerlen = DTLS1_RT_HEADER_LENGTH;
else
headerlen = SSL3_RT_HEADER_LENGTH;
#if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD!=0
align = (-SSL3_RT_HEADER_LENGTH) & (SSL3_ALIGN_PAYLOAD - 1);
#endif
if (b->buf == NULL) {
len = SSL3_RT_MAX_PLAIN_LENGTH
+ SSL3_RT_MAX_ENCRYPTED_OVERHEAD + headerlen + align;
#ifndef OPENSSL_NO_COMP
if (ssl_allow_compression(s))
len += SSL3_RT_MAX_COMPRESSED_OVERHEAD;
#endif
/* Ensure our buffer is large enough to support all our pipelines */
if (s->max_pipelines > 1)
len *= s->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.
*/
SSLfatal(s, SSL_AD_NO_ALERT, ERR_R_MALLOC_FAILURE);
return 0;
}
b->buf = p;
b->len = len;
}
return 1;
}
int ssl3_setup_write_buffer(SSL *s, size_t numwpipes, size_t len)
{
unsigned char *p;
size_t align = 0, headerlen;
SSL3_BUFFER *wb;
size_t currpipe;
s->rlayer.numwpipes = numwpipes;
if (len == 0) {
if (SSL_IS_DTLS(s))
headerlen = DTLS1_RT_HEADER_LENGTH + 1;
else
headerlen = SSL3_RT_HEADER_LENGTH;
#if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD!=0
align = SSL3_ALIGN_PAYLOAD - 1;
#endif
len = ssl_get_max_send_fragment(s)
+ SSL3_RT_SEND_MAX_ENCRYPTED_OVERHEAD + headerlen + align
+ SSL_RT_MAX_CIPHER_BLOCK_SIZE /* Explicit IV allowance */;
#ifndef OPENSSL_NO_COMP
if (ssl_allow_compression(s))
len += SSL3_RT_MAX_COMPRESSED_OVERHEAD;
#endif
/*
* We don't need to add an allowance for eivlen here since empty
* fragments only occur when we don't have an explicit IV
*/
if (!(s->options & SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS))
len += headerlen + align + SSL3_RT_SEND_MAX_ENCRYPTED_OVERHEAD;
}
wb = RECORD_LAYER_get_wbuf(&s->rlayer);
for (currpipe = 0; currpipe < numwpipes; currpipe++) {
SSL3_BUFFER *thiswb = &wb[currpipe];
if (thiswb->len != len) {
OPENSSL_free(thiswb->buf);
thiswb->buf = NULL; /* force reallocation */
}
if (thiswb->buf == NULL) {
if (s->wbio == NULL || !BIO_get_ktls_send(s->wbio)) {
p = OPENSSL_malloc(len);
if (p == NULL) {
s->rlayer.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.
*/
SSLfatal(s, SSL_AD_NO_ALERT, ERR_R_MALLOC_FAILURE);
return 0;
}
} else {
p = NULL;
}
memset(thiswb, 0, sizeof(SSL3_BUFFER));
thiswb->buf = p;
thiswb->len = len;
}
}
return 1;
}
int ssl3_setup_buffers(SSL *s)
{
if (!ssl3_setup_read_buffer(s)) {
/* SSLfatal() already called */
return 0;
}
if (!ssl3_setup_write_buffer(s, 1, 0)) {
/* SSLfatal() already called */
return 0;
}
return 1;
}
int ssl3_release_write_buffer(SSL *s)
{
SSL3_BUFFER *wb;
size_t pipes;
pipes = s->rlayer.numwpipes;
while (pipes > 0) {
wb = &RECORD_LAYER_get_wbuf(&s->rlayer)[pipes - 1];
if (SSL3_BUFFER_is_app_buffer(wb))
SSL3_BUFFER_set_app_buffer(wb, 0);
else
OPENSSL_free(wb->buf);
wb->buf = NULL;
pipes--;
}
s->rlayer.numwpipes = 0;
return 1;
}
int ssl3_release_read_buffer(SSL *s)
{
SSL3_BUFFER *b;
b = RECORD_LAYER_get_rbuf(&s->rlayer);
if (s->options & SSL_OP_CLEANSE_PLAINTEXT)
OPENSSL_cleanse(b->buf, b->len);
OPENSSL_free(b->buf);
b->buf = NULL;
+ s->rlayer.packet = NULL;
+ s->rlayer.packet_length = 0;
return 1;
}
diff --git a/crypto/openssl/ssl/ssl_err.c b/crypto/openssl/ssl/ssl_err.c
index 41898844ff97..75be692e0007 100644
--- a/crypto/openssl/ssl/ssl_err.c
+++ b/crypto/openssl/ssl/ssl_err.c
@@ -1,571 +1,575 @@
/*
* Generated by util/mkerr.pl DO NOT EDIT
- * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 1995-2024 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 <openssl/err.h>
#include <openssl/sslerr.h>
#include "sslerr.h"
#ifndef OPENSSL_NO_ERR
static const ERR_STRING_DATA SSL_str_reasons[] = {
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_APPLICATION_DATA_AFTER_CLOSE_NOTIFY),
"application data after close notify"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_APP_DATA_IN_HANDSHAKE),
"app data in handshake"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_ATTEMPT_TO_REUSE_SESSION_IN_DIFFERENT_CONTEXT),
"attempt to reuse session in different context"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_AT_LEAST_TLS_1_2_NEEDED_IN_SUITEB_MODE),
"at least (D)TLS 1.2 needed in Suite B mode"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_BAD_CHANGE_CIPHER_SPEC),
"bad change cipher spec"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_BAD_CIPHER), "bad cipher"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_BAD_DATA), "bad data"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_BAD_DATA_RETURNED_BY_CALLBACK),
"bad data returned by callback"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_BAD_DECOMPRESSION), "bad decompression"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_BAD_DH_VALUE), "bad dh value"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_BAD_DIGEST_LENGTH), "bad digest length"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_BAD_EARLY_DATA), "bad early data"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_BAD_ECC_CERT), "bad ecc cert"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_BAD_ECPOINT), "bad ecpoint"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_BAD_EXTENSION), "bad extension"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_BAD_HANDSHAKE_LENGTH),
"bad handshake length"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_BAD_HANDSHAKE_STATE),
"bad handshake state"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_BAD_HELLO_REQUEST), "bad hello request"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_BAD_HRR_VERSION), "bad hrr version"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_BAD_KEY_SHARE), "bad key share"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_BAD_KEY_UPDATE), "bad key update"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_BAD_LEGACY_VERSION), "bad legacy version"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_BAD_LENGTH), "bad length"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_BAD_PACKET), "bad packet"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_BAD_PACKET_LENGTH), "bad packet length"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_BAD_PROTOCOL_VERSION_NUMBER),
"bad protocol version number"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_BAD_PSK), "bad psk"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_BAD_PSK_IDENTITY), "bad psk identity"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_BAD_RECORD_TYPE), "bad record type"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_BAD_RSA_ENCRYPT), "bad rsa encrypt"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_BAD_SIGNATURE), "bad signature"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_BAD_SRP_A_LENGTH), "bad srp a length"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_BAD_SRP_PARAMETERS), "bad srp parameters"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_BAD_SRTP_MKI_VALUE), "bad srtp mki value"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_BAD_SRTP_PROTECTION_PROFILE_LIST),
"bad srtp protection profile list"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_BAD_SSL_FILETYPE), "bad ssl filetype"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_BAD_VALUE), "bad value"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_BAD_WRITE_RETRY), "bad write retry"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_BINDER_DOES_NOT_VERIFY),
"binder does not verify"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_BIO_NOT_SET), "bio not set"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_BLOCK_CIPHER_PAD_IS_WRONG),
"block cipher pad is wrong"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_BN_LIB), "bn lib"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_CALLBACK_FAILED), "callback failed"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_CANNOT_CHANGE_CIPHER),
"cannot change cipher"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_CANNOT_GET_GROUP_NAME),
"cannot get group name"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_CA_DN_LENGTH_MISMATCH),
"ca dn length mismatch"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_CA_KEY_TOO_SMALL), "ca key too small"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_CA_MD_TOO_WEAK), "ca md too weak"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_CCS_RECEIVED_EARLY), "ccs received early"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_CERTIFICATE_VERIFY_FAILED),
"certificate verify failed"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_CERT_CB_ERROR), "cert cb error"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_CERT_LENGTH_MISMATCH),
"cert length mismatch"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_CIPHERSUITE_DIGEST_HAS_CHANGED),
"ciphersuite digest has changed"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_CIPHER_CODE_WRONG_LENGTH),
"cipher code wrong length"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_CLIENTHELLO_TLSEXT), "clienthello tlsext"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_COMPRESSED_LENGTH_TOO_LONG),
"compressed length too long"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_COMPRESSION_DISABLED),
"compression disabled"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_COMPRESSION_FAILURE),
"compression failure"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_COMPRESSION_ID_NOT_WITHIN_PRIVATE_RANGE),
"compression id not within private range"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_COMPRESSION_LIBRARY_ERROR),
"compression library error"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_CONNECTION_TYPE_NOT_SET),
"connection type not set"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_CONTEXT_NOT_DANE_ENABLED),
"context not dane enabled"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_COOKIE_GEN_CALLBACK_FAILURE),
"cookie gen callback failure"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_COOKIE_MISMATCH), "cookie mismatch"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_COPY_PARAMETERS_FAILED),
"copy parameters failed"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_CUSTOM_EXT_HANDLER_ALREADY_INSTALLED),
"custom ext handler already installed"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_DANE_ALREADY_ENABLED),
"dane already enabled"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_DANE_CANNOT_OVERRIDE_MTYPE_FULL),
"dane cannot override mtype full"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_DANE_NOT_ENABLED), "dane not enabled"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_DANE_TLSA_BAD_CERTIFICATE),
"dane tlsa bad certificate"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_DANE_TLSA_BAD_CERTIFICATE_USAGE),
"dane tlsa bad certificate usage"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_DANE_TLSA_BAD_DATA_LENGTH),
"dane tlsa bad data length"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_DANE_TLSA_BAD_DIGEST_LENGTH),
"dane tlsa bad digest length"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_DANE_TLSA_BAD_MATCHING_TYPE),
"dane tlsa bad matching type"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_DANE_TLSA_BAD_PUBLIC_KEY),
"dane tlsa bad public key"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_DANE_TLSA_BAD_SELECTOR),
"dane tlsa bad selector"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_DANE_TLSA_NULL_DATA),
"dane tlsa null data"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_DATA_BETWEEN_CCS_AND_FINISHED),
"data between ccs and finished"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_DATA_LENGTH_TOO_LONG),
"data length too long"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_DECRYPTION_FAILED), "decryption failed"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC),
"decryption failed or bad record mac"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_DH_KEY_TOO_SMALL), "dh key too small"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_DH_PUBLIC_VALUE_LENGTH_IS_WRONG),
"dh public value length is wrong"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_DIGEST_CHECK_FAILED),
"digest check failed"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_DTLS_MESSAGE_TOO_BIG),
"dtls message too big"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_DUPLICATE_COMPRESSION_ID),
"duplicate compression id"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_ECC_CERT_NOT_FOR_SIGNING),
"ecc cert not for signing"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_ECDH_REQUIRED_FOR_SUITEB_MODE),
"ecdh required for suiteb mode"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_EE_KEY_TOO_SMALL), "ee key too small"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_EMPTY_SRTP_PROTECTION_PROFILE_LIST),
"empty srtp protection profile list"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_ENCRYPTED_LENGTH_TOO_LONG),
"encrypted length too long"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_ERROR_IN_RECEIVED_CIPHER_LIST),
"error in received cipher list"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_ERROR_SETTING_TLSA_BASE_DOMAIN),
"error setting tlsa base domain"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_EXCEEDS_MAX_FRAGMENT_SIZE),
"exceeds max fragment size"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_EXCESSIVE_MESSAGE_SIZE),
"excessive message size"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_EXTENSION_NOT_RECEIVED),
"extension not received"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_EXTRA_DATA_IN_MESSAGE),
"extra data in message"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_EXT_LENGTH_MISMATCH),
"ext length mismatch"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_FAILED_TO_INIT_ASYNC),
"failed to init async"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_FRAGMENTED_CLIENT_HELLO),
"fragmented client hello"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_GOT_A_FIN_BEFORE_A_CCS),
"got a fin before a ccs"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_HTTPS_PROXY_REQUEST),
"https proxy request"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_HTTP_REQUEST), "http request"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_ILLEGAL_POINT_COMPRESSION),
"illegal point compression"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_ILLEGAL_SUITEB_DIGEST),
"illegal Suite B digest"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_INAPPROPRIATE_FALLBACK),
"inappropriate fallback"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_INCONSISTENT_COMPRESSION),
"inconsistent compression"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_INCONSISTENT_EARLY_DATA_ALPN),
"inconsistent early data alpn"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_INCONSISTENT_EARLY_DATA_SNI),
"inconsistent early data sni"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_INCONSISTENT_EXTMS), "inconsistent extms"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_INSUFFICIENT_SECURITY),
"insufficient security"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_INVALID_ALERT), "invalid alert"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_INVALID_CCS_MESSAGE),
"invalid ccs message"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_INVALID_CERTIFICATE_OR_ALG),
"invalid certificate or alg"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_INVALID_COMMAND), "invalid command"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_INVALID_COMPRESSION_ALGORITHM),
"invalid compression algorithm"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_INVALID_CONFIG), "invalid config"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_INVALID_CONFIGURATION_NAME),
"invalid configuration name"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_INVALID_CONTEXT), "invalid context"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_INVALID_CT_VALIDATION_TYPE),
"invalid ct validation type"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_INVALID_KEY_UPDATE_TYPE),
"invalid key update type"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_INVALID_MAX_EARLY_DATA),
"invalid max early data"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_INVALID_NULL_CMD_NAME),
"invalid null cmd name"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_INVALID_SEQUENCE_NUMBER),
"invalid sequence number"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_INVALID_SERVERINFO_DATA),
"invalid serverinfo data"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_INVALID_SESSION_ID), "invalid session id"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_INVALID_SRP_USERNAME),
"invalid srp username"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_INVALID_STATUS_RESPONSE),
"invalid status response"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_INVALID_TICKET_KEYS_LENGTH),
"invalid ticket keys length"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_LEGACY_SIGALG_DISALLOWED_OR_UNSUPPORTED),
"legacy sigalg disallowed or unsupported"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_LENGTH_MISMATCH), "length mismatch"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_LENGTH_TOO_LONG), "length too long"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_LENGTH_TOO_SHORT), "length too short"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_LIBRARY_BUG), "library bug"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_LIBRARY_HAS_NO_CIPHERS),
"library has no ciphers"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_MISSING_DSA_SIGNING_CERT),
"missing dsa signing cert"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_MISSING_ECDSA_SIGNING_CERT),
"missing ecdsa signing cert"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_MISSING_FATAL), "missing fatal"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_MISSING_PARAMETERS), "missing parameters"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_MISSING_PSK_KEX_MODES_EXTENSION),
"missing psk kex modes extension"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_MISSING_RSA_CERTIFICATE),
"missing rsa certificate"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_MISSING_RSA_ENCRYPTING_CERT),
"missing rsa encrypting cert"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_MISSING_RSA_SIGNING_CERT),
"missing rsa signing cert"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_MISSING_SIGALGS_EXTENSION),
"missing sigalgs extension"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_MISSING_SIGNING_CERT),
"missing signing cert"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_MISSING_SRP_PARAM),
"can't find SRP server param"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_MISSING_SUPPORTED_GROUPS_EXTENSION),
"missing supported groups extension"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_MISSING_TMP_DH_KEY), "missing tmp dh key"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_MISSING_TMP_ECDH_KEY),
"missing tmp ecdh key"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_MIXED_HANDSHAKE_AND_NON_HANDSHAKE_DATA),
"mixed handshake and non handshake data"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_NOT_ON_RECORD_BOUNDARY),
"not on record boundary"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_NOT_REPLACING_CERTIFICATE),
"not replacing certificate"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_NOT_SERVER), "not server"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_NO_APPLICATION_PROTOCOL),
"no application protocol"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_NO_CERTIFICATES_RETURNED),
"no certificates returned"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_NO_CERTIFICATE_ASSIGNED),
"no certificate assigned"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_NO_CERTIFICATE_SET), "no certificate set"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_NO_CHANGE_FOLLOWING_HRR),
"no change following hrr"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_NO_CIPHERS_AVAILABLE),
"no ciphers available"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_NO_CIPHERS_SPECIFIED),
"no ciphers specified"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_NO_CIPHER_MATCH), "no cipher match"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_NO_CLIENT_CERT_METHOD),
"no client cert method"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_NO_COMPRESSION_SPECIFIED),
"no compression specified"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_NO_COOKIE_CALLBACK_SET),
"no cookie callback set"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_NO_GOST_CERTIFICATE_SENT_BY_PEER),
"Peer haven't sent GOST certificate, required for selected ciphersuite"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_NO_METHOD_SPECIFIED),
"no method specified"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_NO_PEM_EXTENSIONS), "no pem extensions"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_NO_PRIVATE_KEY_ASSIGNED),
"no private key assigned"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_NO_PROTOCOLS_AVAILABLE),
"no protocols available"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_NO_RENEGOTIATION), "no renegotiation"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_NO_REQUIRED_DIGEST), "no required digest"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_NO_SHARED_CIPHER), "no shared cipher"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_NO_SHARED_GROUPS), "no shared groups"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_NO_SHARED_SIGNATURE_ALGORITHMS),
"no shared signature algorithms"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_NO_SRTP_PROFILES), "no srtp profiles"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_NO_SUITABLE_DIGEST_ALGORITHM),
"no suitable digest algorithm"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_NO_SUITABLE_GROUPS), "no suitable groups"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_NO_SUITABLE_KEY_SHARE),
"no suitable key share"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_NO_SUITABLE_SIGNATURE_ALGORITHM),
"no suitable signature algorithm"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_NO_VALID_SCTS), "no valid scts"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_NO_VERIFY_COOKIE_CALLBACK),
"no verify cookie callback"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_NULL_SSL_CTX), "null ssl ctx"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_NULL_SSL_METHOD_PASSED),
"null ssl method passed"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_OCSP_CALLBACK_FAILURE),
"ocsp callback failure"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_OLD_SESSION_CIPHER_NOT_RETURNED),
"old session cipher not returned"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_OLD_SESSION_COMPRESSION_ALGORITHM_NOT_RETURNED),
"old session compression algorithm not returned"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_OVERFLOW_ERROR), "overflow error"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_PACKET_LENGTH_TOO_LONG),
"packet length too long"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_PARSE_TLSEXT), "parse tlsext"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_PATH_TOO_LONG), "path too long"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE),
"peer did not return a certificate"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_PEM_NAME_BAD_PREFIX),
"pem name bad prefix"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_PEM_NAME_TOO_SHORT), "pem name too short"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_PIPELINE_FAILURE), "pipeline failure"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_POST_HANDSHAKE_AUTH_ENCODING_ERR),
"post handshake auth encoding err"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_PRIVATE_KEY_MISMATCH),
"private key mismatch"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_PROTOCOL_IS_SHUTDOWN),
"protocol is shutdown"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_PSK_IDENTITY_NOT_FOUND),
"psk identity not found"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_PSK_NO_CLIENT_CB), "psk no client cb"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_PSK_NO_SERVER_CB), "psk no server cb"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_READ_BIO_NOT_SET), "read bio not set"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_READ_TIMEOUT_EXPIRED),
"read timeout expired"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_RECORD_LENGTH_MISMATCH),
"record length mismatch"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_RECORD_TOO_SMALL), "record too small"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_RENEGOTIATE_EXT_TOO_LONG),
"renegotiate ext too long"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_RENEGOTIATION_ENCODING_ERR),
"renegotiation encoding err"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_RENEGOTIATION_MISMATCH),
"renegotiation mismatch"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_REQUEST_PENDING), "request pending"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_REQUEST_SENT), "request sent"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_REQUIRED_CIPHER_MISSING),
"required cipher missing"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_REQUIRED_COMPRESSION_ALGORITHM_MISSING),
"required compression algorithm missing"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_SCSV_RECEIVED_WHEN_RENEGOTIATING),
"scsv received when renegotiating"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_SCT_VERIFICATION_FAILED),
"sct verification failed"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_SERVERHELLO_TLSEXT), "serverhello tlsext"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_SESSION_ID_CONTEXT_UNINITIALIZED),
"session id context uninitialized"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_SHUTDOWN_WHILE_IN_INIT),
"shutdown while in init"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_SIGNATURE_ALGORITHMS_ERROR),
"signature algorithms error"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_SIGNATURE_FOR_NON_SIGNING_CERTIFICATE),
"signature for non signing certificate"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_SRP_A_CALC), "error with the srp params"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_SRTP_COULD_NOT_ALLOCATE_PROFILES),
"srtp could not allocate profiles"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_SRTP_PROTECTION_PROFILE_LIST_TOO_LONG),
"srtp protection profile list too long"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_SRTP_UNKNOWN_PROTECTION_PROFILE),
"srtp unknown protection profile"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_SSL3_EXT_INVALID_MAX_FRAGMENT_LENGTH),
"ssl3 ext invalid max fragment length"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_SSL3_EXT_INVALID_SERVERNAME),
"ssl3 ext invalid servername"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_SSL3_EXT_INVALID_SERVERNAME_TYPE),
"ssl3 ext invalid servername type"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_SSL3_SESSION_ID_TOO_LONG),
"ssl3 session id too long"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_SSLV3_ALERT_BAD_CERTIFICATE),
"sslv3 alert bad certificate"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_SSLV3_ALERT_BAD_RECORD_MAC),
"sslv3 alert bad record mac"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_SSLV3_ALERT_CERTIFICATE_EXPIRED),
"sslv3 alert certificate expired"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_SSLV3_ALERT_CERTIFICATE_REVOKED),
"sslv3 alert certificate revoked"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_SSLV3_ALERT_CERTIFICATE_UNKNOWN),
"sslv3 alert certificate unknown"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_SSLV3_ALERT_DECOMPRESSION_FAILURE),
"sslv3 alert decompression failure"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_SSLV3_ALERT_HANDSHAKE_FAILURE),
"sslv3 alert handshake failure"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_SSLV3_ALERT_ILLEGAL_PARAMETER),
"sslv3 alert illegal parameter"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_SSLV3_ALERT_NO_CERTIFICATE),
"sslv3 alert no certificate"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_SSLV3_ALERT_UNEXPECTED_MESSAGE),
"sslv3 alert unexpected message"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_SSLV3_ALERT_UNSUPPORTED_CERTIFICATE),
"sslv3 alert unsupported certificate"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_SSL_COMMAND_SECTION_EMPTY),
"ssl command section empty"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_SSL_COMMAND_SECTION_NOT_FOUND),
"ssl command section not found"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_SSL_CTX_HAS_NO_DEFAULT_SSL_VERSION),
"ssl ctx has no default ssl version"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_SSL_HANDSHAKE_FAILURE),
"ssl handshake failure"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_SSL_LIBRARY_HAS_NO_CIPHERS),
"ssl library has no ciphers"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_SSL_NEGATIVE_LENGTH),
"ssl negative length"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_SSL_SECTION_EMPTY), "ssl section empty"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_SSL_SECTION_NOT_FOUND),
"ssl section not found"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_SSL_SESSION_ID_CALLBACK_FAILED),
"ssl session id callback failed"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_SSL_SESSION_ID_CONFLICT),
"ssl session id conflict"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_SSL_SESSION_ID_CONTEXT_TOO_LONG),
"ssl session id context too long"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_SSL_SESSION_ID_HAS_BAD_LENGTH),
"ssl session id has bad length"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_SSL_SESSION_ID_TOO_LONG),
"ssl session id too long"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_SSL_SESSION_VERSION_MISMATCH),
"ssl session version mismatch"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_STILL_IN_INIT), "still in init"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_TLSV13_ALERT_CERTIFICATE_REQUIRED),
"tlsv13 alert certificate required"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_TLSV13_ALERT_MISSING_EXTENSION),
"tlsv13 alert missing extension"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_TLSV1_ALERT_ACCESS_DENIED),
"tlsv1 alert access denied"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_TLSV1_ALERT_DECODE_ERROR),
"tlsv1 alert decode error"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_TLSV1_ALERT_DECRYPTION_FAILED),
"tlsv1 alert decryption failed"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_TLSV1_ALERT_DECRYPT_ERROR),
"tlsv1 alert decrypt error"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_TLSV1_ALERT_EXPORT_RESTRICTION),
"tlsv1 alert export restriction"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_TLSV1_ALERT_INAPPROPRIATE_FALLBACK),
"tlsv1 alert inappropriate fallback"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_TLSV1_ALERT_INSUFFICIENT_SECURITY),
"tlsv1 alert insufficient security"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_TLSV1_ALERT_INTERNAL_ERROR),
"tlsv1 alert internal error"},
+ {ERR_PACK(ERR_LIB_SSL, 0, SSL_R_TLSV1_ALERT_NO_APPLICATION_PROTOCOL),
+ "tlsv1 alert no application protocol"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_TLSV1_ALERT_NO_RENEGOTIATION),
"tlsv1 alert no renegotiation"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_TLSV1_ALERT_PROTOCOL_VERSION),
"tlsv1 alert protocol version"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_TLSV1_ALERT_RECORD_OVERFLOW),
"tlsv1 alert record overflow"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_TLSV1_ALERT_UNKNOWN_CA),
"tlsv1 alert unknown ca"},
+ {ERR_PACK(ERR_LIB_SSL, 0, SSL_R_TLSV1_ALERT_UNKNOWN_PSK_IDENTITY),
+ "tlsv1 alert unknown psk identity"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_TLSV1_ALERT_USER_CANCELLED),
"tlsv1 alert user cancelled"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_TLSV1_BAD_CERTIFICATE_HASH_VALUE),
"tlsv1 bad certificate hash value"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_TLSV1_BAD_CERTIFICATE_STATUS_RESPONSE),
"tlsv1 bad certificate status response"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_TLSV1_CERTIFICATE_UNOBTAINABLE),
"tlsv1 certificate unobtainable"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_TLSV1_UNRECOGNIZED_NAME),
"tlsv1 unrecognized name"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_TLSV1_UNSUPPORTED_EXTENSION),
"tlsv1 unsupported extension"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_TLS_ILLEGAL_EXPORTER_LABEL),
"tls illegal exporter label"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_TLS_INVALID_ECPOINTFORMAT_LIST),
"tls invalid ecpointformat list"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_TOO_MANY_KEY_UPDATES),
"too many key updates"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_TOO_MANY_WARN_ALERTS),
"too many warn alerts"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_TOO_MUCH_EARLY_DATA),
"too much early data"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_UNABLE_TO_FIND_ECDH_PARAMETERS),
"unable to find ecdh parameters"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_UNABLE_TO_FIND_PUBLIC_KEY_PARAMETERS),
"unable to find public key parameters"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_UNABLE_TO_LOAD_SSL3_MD5_ROUTINES),
"unable to load ssl3 md5 routines"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_UNABLE_TO_LOAD_SSL3_SHA1_ROUTINES),
"unable to load ssl3 sha1 routines"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_UNEXPECTED_CCS_MESSAGE),
"unexpected ccs message"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_UNEXPECTED_END_OF_EARLY_DATA),
"unexpected end of early data"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_UNEXPECTED_EOF_WHILE_READING),
"unexpected eof while reading"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_UNEXPECTED_MESSAGE), "unexpected message"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_UNEXPECTED_RECORD), "unexpected record"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_UNINITIALIZED), "uninitialized"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_UNKNOWN_ALERT_TYPE), "unknown alert type"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_UNKNOWN_CERTIFICATE_TYPE),
"unknown certificate type"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_UNKNOWN_CIPHER_RETURNED),
"unknown cipher returned"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_UNKNOWN_CIPHER_TYPE),
"unknown cipher type"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_UNKNOWN_CMD_NAME), "unknown cmd name"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_UNKNOWN_COMMAND), "unknown command"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_UNKNOWN_DIGEST), "unknown digest"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE),
"unknown key exchange type"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_UNKNOWN_PKEY_TYPE), "unknown pkey type"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_UNKNOWN_PROTOCOL), "unknown protocol"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_UNKNOWN_SSL_VERSION),
"unknown ssl version"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_UNKNOWN_STATE), "unknown state"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED),
"unsafe legacy renegotiation disabled"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_UNSOLICITED_EXTENSION),
"unsolicited extension"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_UNSUPPORTED_COMPRESSION_ALGORITHM),
"unsupported compression algorithm"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_UNSUPPORTED_ELLIPTIC_CURVE),
"unsupported elliptic curve"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_UNSUPPORTED_PROTOCOL),
"unsupported protocol"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_UNSUPPORTED_SSL_VERSION),
"unsupported ssl version"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_UNSUPPORTED_STATUS_TYPE),
"unsupported status type"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_USE_SRTP_NOT_NEGOTIATED),
"use srtp not negotiated"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_VERSION_TOO_HIGH), "version too high"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_VERSION_TOO_LOW), "version too low"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_WRONG_CERTIFICATE_TYPE),
"wrong certificate type"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_WRONG_CIPHER_RETURNED),
"wrong cipher returned"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_WRONG_CURVE), "wrong curve"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_WRONG_SIGNATURE_LENGTH),
"wrong signature length"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_WRONG_SIGNATURE_SIZE),
"wrong signature size"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_WRONG_SIGNATURE_TYPE),
"wrong signature type"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_WRONG_SSL_VERSION), "wrong ssl version"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_WRONG_VERSION_NUMBER),
"wrong version number"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_X509_LIB), "x509 lib"},
{ERR_PACK(ERR_LIB_SSL, 0, SSL_R_X509_VERIFICATION_SETUP_PROBLEMS),
"x509 verification setup problems"},
{0, NULL}
};
#endif
int ossl_err_load_SSL_strings(void)
{
#ifndef OPENSSL_NO_ERR
if (ERR_reason_error_string(SSL_str_reasons[0].error) == NULL)
ERR_load_strings_const(SSL_str_reasons);
#endif
return 1;
}
diff --git a/crypto/openssl/ssl/ssl_lib.c b/crypto/openssl/ssl/ssl_lib.c
index 2c8479eb5fc6..cb4e006ea7a3 100644
--- a/crypto/openssl/ssl/ssl_lib.c
+++ b/crypto/openssl/ssl/ssl_lib.c
@@ -1,6057 +1,6061 @@
/*
- * Copyright 1995-2023 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 1995-2024 The OpenSSL Project Authors. All Rights Reserved.
* Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved
* Copyright 2005 Nokia. All rights reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <stdio.h>
#include "ssl_local.h"
#include "e_os.h"
#include <openssl/objects.h>
#include <openssl/x509v3.h>
#include <openssl/rand.h>
#include <openssl/ocsp.h>
#include <openssl/dh.h>
#include <openssl/engine.h>
#include <openssl/async.h>
#include <openssl/ct.h>
#include <openssl/trace.h>
#include "internal/cryptlib.h"
#include "internal/refcount.h"
#include "internal/ktls.h"
static int ssl_undefined_function_1(SSL *ssl, SSL3_RECORD *r, size_t s, int t,
SSL_MAC_BUF *mac, size_t macsize)
{
return ssl_undefined_function(ssl);
}
static int ssl_undefined_function_2(SSL *ssl, SSL3_RECORD *r, unsigned char *s,
int t)
{
return ssl_undefined_function(ssl);
}
static int ssl_undefined_function_3(SSL *ssl, unsigned char *r,
unsigned char *s, size_t t, size_t *u)
{
return ssl_undefined_function(ssl);
}
static int ssl_undefined_function_4(SSL *ssl, int r)
{
return ssl_undefined_function(ssl);
}
static size_t ssl_undefined_function_5(SSL *ssl, const char *r, size_t s,
unsigned char *t)
{
return ssl_undefined_function(ssl);
}
static int ssl_undefined_function_6(int r)
{
return ssl_undefined_function(NULL);
}
static int ssl_undefined_function_7(SSL *ssl, unsigned char *r, size_t s,
const char *t, size_t u,
const unsigned char *v, size_t w, int x)
{
return ssl_undefined_function(ssl);
}
SSL3_ENC_METHOD ssl3_undef_enc_method = {
ssl_undefined_function_1,
ssl_undefined_function_2,
ssl_undefined_function,
ssl_undefined_function_3,
ssl_undefined_function_4,
ssl_undefined_function_5,
NULL, /* client_finished_label */
0, /* client_finished_label_len */
NULL, /* server_finished_label */
0, /* server_finished_label_len */
ssl_undefined_function_6,
ssl_undefined_function_7,
};
struct ssl_async_args {
SSL *s;
void *buf;
size_t num;
enum { READFUNC, WRITEFUNC, OTHERFUNC } type;
union {
int (*func_read) (SSL *, void *, size_t, size_t *);
int (*func_write) (SSL *, const void *, size_t, size_t *);
int (*func_other) (SSL *);
} f;
};
static const struct {
uint8_t mtype;
uint8_t ord;
int nid;
} dane_mds[] = {
{
DANETLS_MATCHING_FULL, 0, NID_undef
},
{
DANETLS_MATCHING_2256, 1, NID_sha256
},
{
DANETLS_MATCHING_2512, 2, NID_sha512
},
};
static int dane_ctx_enable(struct dane_ctx_st *dctx)
{
const EVP_MD **mdevp;
uint8_t *mdord;
uint8_t mdmax = DANETLS_MATCHING_LAST;
int n = ((int)mdmax) + 1; /* int to handle PrivMatch(255) */
size_t i;
if (dctx->mdevp != NULL)
return 1;
mdevp = OPENSSL_zalloc(n * sizeof(*mdevp));
mdord = OPENSSL_zalloc(n * sizeof(*mdord));
if (mdord == NULL || mdevp == NULL) {
OPENSSL_free(mdord);
OPENSSL_free(mdevp);
ERR_raise(ERR_LIB_SSL, ERR_R_MALLOC_FAILURE);
return 0;
}
/* Install default entries */
for (i = 0; i < OSSL_NELEM(dane_mds); ++i) {
const EVP_MD *md;
if (dane_mds[i].nid == NID_undef ||
(md = EVP_get_digestbynid(dane_mds[i].nid)) == NULL)
continue;
mdevp[dane_mds[i].mtype] = md;
mdord[dane_mds[i].mtype] = dane_mds[i].ord;
}
dctx->mdevp = mdevp;
dctx->mdord = mdord;
dctx->mdmax = mdmax;
return 1;
}
static void dane_ctx_final(struct dane_ctx_st *dctx)
{
OPENSSL_free(dctx->mdevp);
dctx->mdevp = NULL;
OPENSSL_free(dctx->mdord);
dctx->mdord = NULL;
dctx->mdmax = 0;
}
static void tlsa_free(danetls_record *t)
{
if (t == NULL)
return;
OPENSSL_free(t->data);
EVP_PKEY_free(t->spki);
OPENSSL_free(t);
}
static void dane_final(SSL_DANE *dane)
{
sk_danetls_record_pop_free(dane->trecs, tlsa_free);
dane->trecs = NULL;
sk_X509_pop_free(dane->certs, X509_free);
dane->certs = NULL;
X509_free(dane->mcert);
dane->mcert = NULL;
dane->mtlsa = NULL;
dane->mdpth = -1;
dane->pdpth = -1;
}
/*
* dane_copy - Copy dane configuration, sans verification state.
*/
static int ssl_dane_dup(SSL *to, SSL *from)
{
int num;
int i;
if (!DANETLS_ENABLED(&from->dane))
return 1;
num = sk_danetls_record_num(from->dane.trecs);
dane_final(&to->dane);
to->dane.flags = from->dane.flags;
to->dane.dctx = &to->ctx->dane;
to->dane.trecs = sk_danetls_record_new_reserve(NULL, num);
if (to->dane.trecs == NULL) {
ERR_raise(ERR_LIB_SSL, ERR_R_MALLOC_FAILURE);
return 0;
}
for (i = 0; i < num; ++i) {
danetls_record *t = sk_danetls_record_value(from->dane.trecs, i);
if (SSL_dane_tlsa_add(to, t->usage, t->selector, t->mtype,
t->data, t->dlen) <= 0)
return 0;
}
return 1;
}
static int dane_mtype_set(struct dane_ctx_st *dctx,
const EVP_MD *md, uint8_t mtype, uint8_t ord)
{
int i;
if (mtype == DANETLS_MATCHING_FULL && md != NULL) {
ERR_raise(ERR_LIB_SSL, SSL_R_DANE_CANNOT_OVERRIDE_MTYPE_FULL);
return 0;
}
if (mtype > dctx->mdmax) {
const EVP_MD **mdevp;
uint8_t *mdord;
int n = ((int)mtype) + 1;
mdevp = OPENSSL_realloc(dctx->mdevp, n * sizeof(*mdevp));
if (mdevp == NULL) {
ERR_raise(ERR_LIB_SSL, ERR_R_MALLOC_FAILURE);
return -1;
}
dctx->mdevp = mdevp;
mdord = OPENSSL_realloc(dctx->mdord, n * sizeof(*mdord));
if (mdord == NULL) {
ERR_raise(ERR_LIB_SSL, ERR_R_MALLOC_FAILURE);
return -1;
}
dctx->mdord = mdord;
/* Zero-fill any gaps */
for (i = dctx->mdmax + 1; i < mtype; ++i) {
mdevp[i] = NULL;
mdord[i] = 0;
}
dctx->mdmax = mtype;
}
dctx->mdevp[mtype] = md;
/* Coerce ordinal of disabled matching types to 0 */
dctx->mdord[mtype] = (md == NULL) ? 0 : ord;
return 1;
}
static const EVP_MD *tlsa_md_get(SSL_DANE *dane, uint8_t mtype)
{
if (mtype > dane->dctx->mdmax)
return NULL;
return dane->dctx->mdevp[mtype];
}
static int dane_tlsa_add(SSL_DANE *dane,
uint8_t usage,
uint8_t selector,
uint8_t mtype, const unsigned char *data, size_t dlen)
{
danetls_record *t;
const EVP_MD *md = NULL;
int ilen = (int)dlen;
int i;
int num;
if (dane->trecs == NULL) {
ERR_raise(ERR_LIB_SSL, SSL_R_DANE_NOT_ENABLED);
return -1;
}
if (ilen < 0 || dlen != (size_t)ilen) {
ERR_raise(ERR_LIB_SSL, SSL_R_DANE_TLSA_BAD_DATA_LENGTH);
return 0;
}
if (usage > DANETLS_USAGE_LAST) {
ERR_raise(ERR_LIB_SSL, SSL_R_DANE_TLSA_BAD_CERTIFICATE_USAGE);
return 0;
}
if (selector > DANETLS_SELECTOR_LAST) {
ERR_raise(ERR_LIB_SSL, SSL_R_DANE_TLSA_BAD_SELECTOR);
return 0;
}
if (mtype != DANETLS_MATCHING_FULL) {
md = tlsa_md_get(dane, mtype);
if (md == NULL) {
ERR_raise(ERR_LIB_SSL, SSL_R_DANE_TLSA_BAD_MATCHING_TYPE);
return 0;
}
}
if (md != NULL && dlen != (size_t)EVP_MD_get_size(md)) {
ERR_raise(ERR_LIB_SSL, SSL_R_DANE_TLSA_BAD_DIGEST_LENGTH);
return 0;
}
if (!data) {
ERR_raise(ERR_LIB_SSL, SSL_R_DANE_TLSA_NULL_DATA);
return 0;
}
if ((t = OPENSSL_zalloc(sizeof(*t))) == NULL) {
ERR_raise(ERR_LIB_SSL, ERR_R_MALLOC_FAILURE);
return -1;
}
t->usage = usage;
t->selector = selector;
t->mtype = mtype;
t->data = OPENSSL_malloc(dlen);
if (t->data == NULL) {
tlsa_free(t);
ERR_raise(ERR_LIB_SSL, ERR_R_MALLOC_FAILURE);
return -1;
}
memcpy(t->data, data, dlen);
t->dlen = dlen;
/* Validate and cache full certificate or public key */
if (mtype == DANETLS_MATCHING_FULL) {
const unsigned char *p = data;
X509 *cert = NULL;
EVP_PKEY *pkey = NULL;
switch (selector) {
case DANETLS_SELECTOR_CERT:
if (!d2i_X509(&cert, &p, ilen) || p < data ||
dlen != (size_t)(p - data)) {
X509_free(cert);
tlsa_free(t);
ERR_raise(ERR_LIB_SSL, SSL_R_DANE_TLSA_BAD_CERTIFICATE);
return 0;
}
if (X509_get0_pubkey(cert) == NULL) {
X509_free(cert);
tlsa_free(t);
ERR_raise(ERR_LIB_SSL, SSL_R_DANE_TLSA_BAD_CERTIFICATE);
return 0;
}
if ((DANETLS_USAGE_BIT(usage) & DANETLS_TA_MASK) == 0) {
/*
* The Full(0) certificate decodes to a seemingly valid X.509
* object with a plausible key, so the TLSA record is well
* formed. However, we don't actually need the certifiate for
* usages PKIX-EE(1) or DANE-EE(3), because at least the EE
* certificate is always presented by the peer. We discard the
* certificate, and just use the TLSA data as an opaque blob
* for matching the raw presented DER octets.
*
* DO NOT FREE `t` here, it will be added to the TLSA record
* list below!
*/
X509_free(cert);
break;
}
/*
* For usage DANE-TA(2), we support authentication via "2 0 0" TLSA
* records that contain full certificates of trust-anchors that are
* not present in the wire chain. For usage PKIX-TA(0), we augment
* the chain with untrusted Full(0) certificates from DNS, in case
* they are missing from the chain.
*/
if ((dane->certs == NULL &&
(dane->certs = sk_X509_new_null()) == NULL) ||
!sk_X509_push(dane->certs, cert)) {
ERR_raise(ERR_LIB_SSL, ERR_R_MALLOC_FAILURE);
X509_free(cert);
tlsa_free(t);
return -1;
}
break;
case DANETLS_SELECTOR_SPKI:
if (!d2i_PUBKEY(&pkey, &p, ilen) || p < data ||
dlen != (size_t)(p - data)) {
EVP_PKEY_free(pkey);
tlsa_free(t);
ERR_raise(ERR_LIB_SSL, SSL_R_DANE_TLSA_BAD_PUBLIC_KEY);
return 0;
}
/*
* For usage DANE-TA(2), we support authentication via "2 1 0" TLSA
* records that contain full bare keys of trust-anchors that are
* not present in the wire chain.
*/
if (usage == DANETLS_USAGE_DANE_TA)
t->spki = pkey;
else
EVP_PKEY_free(pkey);
break;
}
}
/*-
* Find the right insertion point for the new record.
*
* See crypto/x509/x509_vfy.c. We sort DANE-EE(3) records first, so that
* they can be processed first, as they require no chain building, and no
* expiration or hostname checks. Because DANE-EE(3) is numerically
* largest, this is accomplished via descending sort by "usage".
*
* We also sort in descending order by matching ordinal to simplify
* the implementation of digest agility in the verification code.
*
* The choice of order for the selector is not significant, so we
* use the same descending order for consistency.
*/
num = sk_danetls_record_num(dane->trecs);
for (i = 0; i < num; ++i) {
danetls_record *rec = sk_danetls_record_value(dane->trecs, i);
if (rec->usage > usage)
continue;
if (rec->usage < usage)
break;
if (rec->selector > selector)
continue;
if (rec->selector < selector)
break;
if (dane->dctx->mdord[rec->mtype] > dane->dctx->mdord[mtype])
continue;
break;
}
if (!sk_danetls_record_insert(dane->trecs, t, i)) {
tlsa_free(t);
ERR_raise(ERR_LIB_SSL, ERR_R_MALLOC_FAILURE);
return -1;
}
dane->umask |= DANETLS_USAGE_BIT(usage);
return 1;
}
/*
* Return 0 if there is only one version configured and it was disabled
* at configure time. Return 1 otherwise.
*/
static int ssl_check_allowed_versions(int min_version, int max_version)
{
int minisdtls = 0, maxisdtls = 0;
/* Figure out if we're doing DTLS versions or TLS versions */
if (min_version == DTLS1_BAD_VER
|| min_version >> 8 == DTLS1_VERSION_MAJOR)
minisdtls = 1;
if (max_version == DTLS1_BAD_VER
|| max_version >> 8 == DTLS1_VERSION_MAJOR)
maxisdtls = 1;
/* A wildcard version of 0 could be DTLS or TLS. */
if ((minisdtls && !maxisdtls && max_version != 0)
|| (maxisdtls && !minisdtls && min_version != 0)) {
/* Mixing DTLS and TLS versions will lead to sadness; deny it. */
return 0;
}
if (minisdtls || maxisdtls) {
/* Do DTLS version checks. */
if (min_version == 0)
/* Ignore DTLS1_BAD_VER */
min_version = DTLS1_VERSION;
if (max_version == 0)
max_version = DTLS1_2_VERSION;
#ifdef OPENSSL_NO_DTLS1_2
if (max_version == DTLS1_2_VERSION)
max_version = DTLS1_VERSION;
#endif
#ifdef OPENSSL_NO_DTLS1
if (min_version == DTLS1_VERSION)
min_version = DTLS1_2_VERSION;
#endif
/* Done massaging versions; do the check. */
if (0
#ifdef OPENSSL_NO_DTLS1
|| (DTLS_VERSION_GE(min_version, DTLS1_VERSION)
&& DTLS_VERSION_GE(DTLS1_VERSION, max_version))
#endif
#ifdef OPENSSL_NO_DTLS1_2
|| (DTLS_VERSION_GE(min_version, DTLS1_2_VERSION)
&& DTLS_VERSION_GE(DTLS1_2_VERSION, max_version))
#endif
)
return 0;
} else {
/* Regular TLS version checks. */
if (min_version == 0)
min_version = SSL3_VERSION;
if (max_version == 0)
max_version = TLS1_3_VERSION;
#ifdef OPENSSL_NO_TLS1_3
if (max_version == TLS1_3_VERSION)
max_version = TLS1_2_VERSION;
#endif
#ifdef OPENSSL_NO_TLS1_2
if (max_version == TLS1_2_VERSION)
max_version = TLS1_1_VERSION;
#endif
#ifdef OPENSSL_NO_TLS1_1
if (max_version == TLS1_1_VERSION)
max_version = TLS1_VERSION;
#endif
#ifdef OPENSSL_NO_TLS1
if (max_version == TLS1_VERSION)
max_version = SSL3_VERSION;
#endif
#ifdef OPENSSL_NO_SSL3
if (min_version == SSL3_VERSION)
min_version = TLS1_VERSION;
#endif
#ifdef OPENSSL_NO_TLS1
if (min_version == TLS1_VERSION)
min_version = TLS1_1_VERSION;
#endif
#ifdef OPENSSL_NO_TLS1_1
if (min_version == TLS1_1_VERSION)
min_version = TLS1_2_VERSION;
#endif
#ifdef OPENSSL_NO_TLS1_2
if (min_version == TLS1_2_VERSION)
min_version = TLS1_3_VERSION;
#endif
/* Done massaging versions; do the check. */
if (0
#ifdef OPENSSL_NO_SSL3
|| (min_version <= SSL3_VERSION && SSL3_VERSION <= max_version)
#endif
#ifdef OPENSSL_NO_TLS1
|| (min_version <= TLS1_VERSION && TLS1_VERSION <= max_version)
#endif
#ifdef OPENSSL_NO_TLS1_1
|| (min_version <= TLS1_1_VERSION && TLS1_1_VERSION <= max_version)
#endif
#ifdef OPENSSL_NO_TLS1_2
|| (min_version <= TLS1_2_VERSION && TLS1_2_VERSION <= max_version)
#endif
#ifdef OPENSSL_NO_TLS1_3
|| (min_version <= TLS1_3_VERSION && TLS1_3_VERSION <= max_version)
#endif
)
return 0;
}
return 1;
}
#if defined(__TANDEM) && defined(OPENSSL_VPROC)
/*
* Define a VPROC function for HP NonStop build ssl library.
* This is used by platform version identification tools.
* Do not inline this procedure or make it static.
*/
# define OPENSSL_VPROC_STRING_(x) x##_SSL
# define OPENSSL_VPROC_STRING(x) OPENSSL_VPROC_STRING_(x)
# define OPENSSL_VPROC_FUNC OPENSSL_VPROC_STRING(OPENSSL_VPROC)
void OPENSSL_VPROC_FUNC(void) {}
#endif
static void clear_ciphers(SSL *s)
{
/* clear the current cipher */
ssl_clear_cipher_ctx(s);
ssl_clear_hash_ctx(&s->read_hash);
ssl_clear_hash_ctx(&s->write_hash);
}
int SSL_clear(SSL *s)
{
if (s->method == NULL) {
ERR_raise(ERR_LIB_SSL, SSL_R_NO_METHOD_SPECIFIED);
return 0;
}
if (ssl_clear_bad_session(s)) {
SSL_SESSION_free(s->session);
s->session = NULL;
}
SSL_SESSION_free(s->psksession);
s->psksession = NULL;
OPENSSL_free(s->psksession_id);
s->psksession_id = NULL;
s->psksession_id_len = 0;
s->hello_retry_request = SSL_HRR_NONE;
s->sent_tickets = 0;
s->error = 0;
s->hit = 0;
s->shutdown = 0;
if (s->renegotiate) {
ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
return 0;
}
ossl_statem_clear(s);
s->version = s->method->version;
s->client_version = s->version;
s->rwstate = SSL_NOTHING;
BUF_MEM_free(s->init_buf);
s->init_buf = NULL;
clear_ciphers(s);
s->first_packet = 0;
s->key_update = SSL_KEY_UPDATE_NONE;
EVP_MD_CTX_free(s->pha_dgst);
s->pha_dgst = NULL;
/* Reset DANE verification result state */
s->dane.mdpth = -1;
s->dane.pdpth = -1;
X509_free(s->dane.mcert);
s->dane.mcert = NULL;
s->dane.mtlsa = NULL;
/* Clear the verification result peername */
X509_VERIFY_PARAM_move_peername(s->param, NULL);
/* Clear any shared connection state */
OPENSSL_free(s->shared_sigalgs);
s->shared_sigalgs = NULL;
s->shared_sigalgslen = 0;
/*
* Check to see if we were changed into a different method, if so, revert
* back.
*/
if (s->method != s->ctx->method) {
s->method->ssl_free(s);
s->method = s->ctx->method;
if (!s->method->ssl_new(s))
return 0;
} else {
if (!s->method->ssl_clear(s))
return 0;
}
RECORD_LAYER_clear(&s->rlayer);
return 1;
}
#ifndef OPENSSL_NO_DEPRECATED_3_0
/** Used to change an SSL_CTXs default SSL method type */
int SSL_CTX_set_ssl_version(SSL_CTX *ctx, const SSL_METHOD *meth)
{
STACK_OF(SSL_CIPHER) *sk;
ctx->method = meth;
if (!SSL_CTX_set_ciphersuites(ctx, OSSL_default_ciphersuites())) {
ERR_raise(ERR_LIB_SSL, SSL_R_SSL_LIBRARY_HAS_NO_CIPHERS);
return 0;
}
sk = ssl_create_cipher_list(ctx,
ctx->tls13_ciphersuites,
&(ctx->cipher_list),
&(ctx->cipher_list_by_id),
OSSL_default_cipher_list(), ctx->cert);
if ((sk == NULL) || (sk_SSL_CIPHER_num(sk) <= 0)) {
ERR_raise(ERR_LIB_SSL, SSL_R_SSL_LIBRARY_HAS_NO_CIPHERS);
return 0;
}
return 1;
}
#endif
SSL *SSL_new(SSL_CTX *ctx)
{
SSL *s;
if (ctx == NULL) {
ERR_raise(ERR_LIB_SSL, SSL_R_NULL_SSL_CTX);
return NULL;
}
if (ctx->method == NULL) {
ERR_raise(ERR_LIB_SSL, SSL_R_SSL_CTX_HAS_NO_DEFAULT_SSL_VERSION);
return NULL;
}
s = OPENSSL_zalloc(sizeof(*s));
if (s == NULL)
goto err;
s->references = 1;
s->lock = CRYPTO_THREAD_lock_new();
if (s->lock == NULL) {
OPENSSL_free(s);
s = NULL;
goto err;
}
RECORD_LAYER_init(&s->rlayer, s);
s->options = ctx->options;
s->dane.flags = ctx->dane.flags;
s->min_proto_version = ctx->min_proto_version;
s->max_proto_version = ctx->max_proto_version;
s->mode = ctx->mode;
s->max_cert_list = ctx->max_cert_list;
s->max_early_data = ctx->max_early_data;
s->recv_max_early_data = ctx->recv_max_early_data;
s->num_tickets = ctx->num_tickets;
s->pha_enabled = ctx->pha_enabled;
/* Shallow copy of the ciphersuites stack */
s->tls13_ciphersuites = sk_SSL_CIPHER_dup(ctx->tls13_ciphersuites);
if (s->tls13_ciphersuites == NULL)
goto err;
/*
* Earlier library versions used to copy the pointer to the CERT, not
* its contents; only when setting new parameters for the per-SSL
* copy, ssl_cert_new would be called (and the direct reference to
* the per-SSL_CTX settings would be lost, but those still were
* indirectly accessed for various purposes, and for that reason they
* used to be known as s->ctx->default_cert). Now we don't look at the
* SSL_CTX's CERT after having duplicated it once.
*/
s->cert = ssl_cert_dup(ctx->cert);
if (s->cert == NULL)
goto err;
RECORD_LAYER_set_read_ahead(&s->rlayer, ctx->read_ahead);
s->msg_callback = ctx->msg_callback;
s->msg_callback_arg = ctx->msg_callback_arg;
s->verify_mode = ctx->verify_mode;
s->not_resumable_session_cb = ctx->not_resumable_session_cb;
s->record_padding_cb = ctx->record_padding_cb;
s->record_padding_arg = ctx->record_padding_arg;
s->block_padding = ctx->block_padding;
s->sid_ctx_length = ctx->sid_ctx_length;
if (!ossl_assert(s->sid_ctx_length <= sizeof(s->sid_ctx)))
goto err;
memcpy(&s->sid_ctx, &ctx->sid_ctx, sizeof(s->sid_ctx));
s->verify_callback = ctx->default_verify_callback;
s->generate_session_id = ctx->generate_session_id;
s->param = X509_VERIFY_PARAM_new();
if (s->param == NULL)
goto err;
X509_VERIFY_PARAM_inherit(s->param, ctx->param);
s->quiet_shutdown = ctx->quiet_shutdown;
s->ext.max_fragment_len_mode = ctx->ext.max_fragment_len_mode;
s->max_send_fragment = ctx->max_send_fragment;
s->split_send_fragment = ctx->split_send_fragment;
s->max_pipelines = ctx->max_pipelines;
if (s->max_pipelines > 1)
RECORD_LAYER_set_read_ahead(&s->rlayer, 1);
if (ctx->default_read_buf_len > 0)
SSL_set_default_read_buffer_len(s, ctx->default_read_buf_len);
SSL_CTX_up_ref(ctx);
s->ctx = ctx;
s->ext.debug_cb = 0;
s->ext.debug_arg = NULL;
s->ext.ticket_expected = 0;
s->ext.status_type = ctx->ext.status_type;
s->ext.status_expected = 0;
s->ext.ocsp.ids = NULL;
s->ext.ocsp.exts = NULL;
s->ext.ocsp.resp = NULL;
s->ext.ocsp.resp_len = 0;
SSL_CTX_up_ref(ctx);
s->session_ctx = ctx;
if (ctx->ext.ecpointformats) {
s->ext.ecpointformats =
OPENSSL_memdup(ctx->ext.ecpointformats,
ctx->ext.ecpointformats_len);
if (!s->ext.ecpointformats) {
s->ext.ecpointformats_len = 0;
goto err;
}
s->ext.ecpointformats_len =
ctx->ext.ecpointformats_len;
}
if (ctx->ext.supportedgroups) {
s->ext.supportedgroups =
OPENSSL_memdup(ctx->ext.supportedgroups,
ctx->ext.supportedgroups_len
* sizeof(*ctx->ext.supportedgroups));
if (!s->ext.supportedgroups) {
s->ext.supportedgroups_len = 0;
goto err;
}
s->ext.supportedgroups_len = ctx->ext.supportedgroups_len;
}
#ifndef OPENSSL_NO_NEXTPROTONEG
s->ext.npn = NULL;
#endif
if (s->ctx->ext.alpn) {
s->ext.alpn = OPENSSL_malloc(s->ctx->ext.alpn_len);
if (s->ext.alpn == NULL) {
s->ext.alpn_len = 0;
goto err;
}
memcpy(s->ext.alpn, s->ctx->ext.alpn, s->ctx->ext.alpn_len);
s->ext.alpn_len = s->ctx->ext.alpn_len;
}
s->verified_chain = NULL;
s->verify_result = X509_V_OK;
s->default_passwd_callback = ctx->default_passwd_callback;
s->default_passwd_callback_userdata = ctx->default_passwd_callback_userdata;
s->method = ctx->method;
s->key_update = SSL_KEY_UPDATE_NONE;
s->allow_early_data_cb = ctx->allow_early_data_cb;
s->allow_early_data_cb_data = ctx->allow_early_data_cb_data;
if (!s->method->ssl_new(s))
goto err;
s->server = (ctx->method->ssl_accept == ssl_undefined_function) ? 0 : 1;
if (!SSL_clear(s))
goto err;
if (!CRYPTO_new_ex_data(CRYPTO_EX_INDEX_SSL, s, &s->ex_data))
goto err;
#ifndef OPENSSL_NO_PSK
s->psk_client_callback = ctx->psk_client_callback;
s->psk_server_callback = ctx->psk_server_callback;
#endif
s->psk_find_session_cb = ctx->psk_find_session_cb;
s->psk_use_session_cb = ctx->psk_use_session_cb;
s->async_cb = ctx->async_cb;
s->async_cb_arg = ctx->async_cb_arg;
s->job = NULL;
#ifndef OPENSSL_NO_CT
if (!SSL_set_ct_validation_callback(s, ctx->ct_validation_callback,
ctx->ct_validation_callback_arg))
goto err;
#endif
return s;
err:
SSL_free(s);
ERR_raise(ERR_LIB_SSL, ERR_R_MALLOC_FAILURE);
return NULL;
}
int SSL_is_dtls(const SSL *s)
{
return SSL_IS_DTLS(s) ? 1 : 0;
}
int SSL_up_ref(SSL *s)
{
int i;
if (CRYPTO_UP_REF(&s->references, &i, s->lock) <= 0)
return 0;
REF_PRINT_COUNT("SSL", s);
REF_ASSERT_ISNT(i < 2);
return ((i > 1) ? 1 : 0);
}
int SSL_CTX_set_session_id_context(SSL_CTX *ctx, const unsigned char *sid_ctx,
unsigned int sid_ctx_len)
{
if (sid_ctx_len > SSL_MAX_SID_CTX_LENGTH) {
ERR_raise(ERR_LIB_SSL, SSL_R_SSL_SESSION_ID_CONTEXT_TOO_LONG);
return 0;
}
ctx->sid_ctx_length = sid_ctx_len;
memcpy(ctx->sid_ctx, sid_ctx, sid_ctx_len);
return 1;
}
int SSL_set_session_id_context(SSL *ssl, const unsigned char *sid_ctx,
unsigned int sid_ctx_len)
{
if (sid_ctx_len > SSL_MAX_SID_CTX_LENGTH) {
ERR_raise(ERR_LIB_SSL, SSL_R_SSL_SESSION_ID_CONTEXT_TOO_LONG);
return 0;
}
ssl->sid_ctx_length = sid_ctx_len;
memcpy(ssl->sid_ctx, sid_ctx, sid_ctx_len);
return 1;
}
int SSL_CTX_set_generate_session_id(SSL_CTX *ctx, GEN_SESSION_CB cb)
{
if (!CRYPTO_THREAD_write_lock(ctx->lock))
return 0;
ctx->generate_session_id = cb;
CRYPTO_THREAD_unlock(ctx->lock);
return 1;
}
int SSL_set_generate_session_id(SSL *ssl, GEN_SESSION_CB cb)
{
if (!CRYPTO_THREAD_write_lock(ssl->lock))
return 0;
ssl->generate_session_id = cb;
CRYPTO_THREAD_unlock(ssl->lock);
return 1;
}
int SSL_has_matching_session_id(const SSL *ssl, const unsigned char *id,
unsigned int id_len)
{
/*
* A quick examination of SSL_SESSION_hash and SSL_SESSION_cmp shows how
* we can "construct" a session to give us the desired check - i.e. to
* find if there's a session in the hash table that would conflict with
* any new session built out of this id/id_len and the ssl_version in use
* by this SSL.
*/
SSL_SESSION r, *p;
if (id_len > sizeof(r.session_id))
return 0;
r.ssl_version = ssl->version;
r.session_id_length = id_len;
memcpy(r.session_id, id, id_len);
if (!CRYPTO_THREAD_read_lock(ssl->session_ctx->lock))
return 0;
p = lh_SSL_SESSION_retrieve(ssl->session_ctx->sessions, &r);
CRYPTO_THREAD_unlock(ssl->session_ctx->lock);
return (p != NULL);
}
int SSL_CTX_set_purpose(SSL_CTX *s, int purpose)
{
return X509_VERIFY_PARAM_set_purpose(s->param, purpose);
}
int SSL_set_purpose(SSL *s, int purpose)
{
return X509_VERIFY_PARAM_set_purpose(s->param, purpose);
}
int SSL_CTX_set_trust(SSL_CTX *s, int trust)
{
return X509_VERIFY_PARAM_set_trust(s->param, trust);
}
int SSL_set_trust(SSL *s, int trust)
{
return X509_VERIFY_PARAM_set_trust(s->param, trust);
}
int SSL_set1_host(SSL *s, const char *hostname)
{
/* If a hostname is provided and parses as an IP address,
* treat it as such. */
if (hostname && X509_VERIFY_PARAM_set1_ip_asc(s->param, hostname) == 1)
return 1;
return X509_VERIFY_PARAM_set1_host(s->param, hostname, 0);
}
int SSL_add1_host(SSL *s, const char *hostname)
{
/* If a hostname is provided and parses as an IP address,
* treat it as such. */
if (hostname)
{
ASN1_OCTET_STRING *ip;
char *old_ip;
ip = a2i_IPADDRESS(hostname);
if (ip) {
/* We didn't want it; only to check if it *is* an IP address */
ASN1_OCTET_STRING_free(ip);
old_ip = X509_VERIFY_PARAM_get1_ip_asc(s->param);
if (old_ip)
{
OPENSSL_free(old_ip);
/* There can be only one IP address */
return 0;
}
return X509_VERIFY_PARAM_set1_ip_asc(s->param, hostname);
}
}
return X509_VERIFY_PARAM_add1_host(s->param, hostname, 0);
}
void SSL_set_hostflags(SSL *s, unsigned int flags)
{
X509_VERIFY_PARAM_set_hostflags(s->param, flags);
}
const char *SSL_get0_peername(SSL *s)
{
return X509_VERIFY_PARAM_get0_peername(s->param);
}
int SSL_CTX_dane_enable(SSL_CTX *ctx)
{
return dane_ctx_enable(&ctx->dane);
}
unsigned long SSL_CTX_dane_set_flags(SSL_CTX *ctx, unsigned long flags)
{
unsigned long orig = ctx->dane.flags;
ctx->dane.flags |= flags;
return orig;
}
unsigned long SSL_CTX_dane_clear_flags(SSL_CTX *ctx, unsigned long flags)
{
unsigned long orig = ctx->dane.flags;
ctx->dane.flags &= ~flags;
return orig;
}
int SSL_dane_enable(SSL *s, const char *basedomain)
{
SSL_DANE *dane = &s->dane;
if (s->ctx->dane.mdmax == 0) {
ERR_raise(ERR_LIB_SSL, SSL_R_CONTEXT_NOT_DANE_ENABLED);
return 0;
}
if (dane->trecs != NULL) {
ERR_raise(ERR_LIB_SSL, SSL_R_DANE_ALREADY_ENABLED);
return 0;
}
/*
* Default SNI name. This rejects empty names, while set1_host below
* accepts them and disables host name checks. To avoid side-effects with
* invalid input, set the SNI name first.
*/
if (s->ext.hostname == NULL) {
if (!SSL_set_tlsext_host_name(s, basedomain)) {
ERR_raise(ERR_LIB_SSL, SSL_R_ERROR_SETTING_TLSA_BASE_DOMAIN);
return -1;
}
}
/* Primary RFC6125 reference identifier */
if (!X509_VERIFY_PARAM_set1_host(s->param, basedomain, 0)) {
ERR_raise(ERR_LIB_SSL, SSL_R_ERROR_SETTING_TLSA_BASE_DOMAIN);
return -1;
}
dane->mdpth = -1;
dane->pdpth = -1;
dane->dctx = &s->ctx->dane;
dane->trecs = sk_danetls_record_new_null();
if (dane->trecs == NULL) {
ERR_raise(ERR_LIB_SSL, ERR_R_MALLOC_FAILURE);
return -1;
}
return 1;
}
unsigned long SSL_dane_set_flags(SSL *ssl, unsigned long flags)
{
unsigned long orig = ssl->dane.flags;
ssl->dane.flags |= flags;
return orig;
}
unsigned long SSL_dane_clear_flags(SSL *ssl, unsigned long flags)
{
unsigned long orig = ssl->dane.flags;
ssl->dane.flags &= ~flags;
return orig;
}
int SSL_get0_dane_authority(SSL *s, X509 **mcert, EVP_PKEY **mspki)
{
SSL_DANE *dane = &s->dane;
if (!DANETLS_ENABLED(dane) || s->verify_result != X509_V_OK)
return -1;
if (dane->mtlsa) {
if (mcert)
*mcert = dane->mcert;
if (mspki)
*mspki = (dane->mcert == NULL) ? dane->mtlsa->spki : NULL;
}
return dane->mdpth;
}
int SSL_get0_dane_tlsa(SSL *s, uint8_t *usage, uint8_t *selector,
uint8_t *mtype, const unsigned char **data, size_t *dlen)
{
SSL_DANE *dane = &s->dane;
if (!DANETLS_ENABLED(dane) || s->verify_result != X509_V_OK)
return -1;
if (dane->mtlsa) {
if (usage)
*usage = dane->mtlsa->usage;
if (selector)
*selector = dane->mtlsa->selector;
if (mtype)
*mtype = dane->mtlsa->mtype;
if (data)
*data = dane->mtlsa->data;
if (dlen)
*dlen = dane->mtlsa->dlen;
}
return dane->mdpth;
}
SSL_DANE *SSL_get0_dane(SSL *s)
{
return &s->dane;
}
int SSL_dane_tlsa_add(SSL *s, uint8_t usage, uint8_t selector,
uint8_t mtype, const unsigned char *data, size_t dlen)
{
return dane_tlsa_add(&s->dane, usage, selector, mtype, data, dlen);
}
int SSL_CTX_dane_mtype_set(SSL_CTX *ctx, const EVP_MD *md, uint8_t mtype,
uint8_t ord)
{
return dane_mtype_set(&ctx->dane, md, mtype, ord);
}
int SSL_CTX_set1_param(SSL_CTX *ctx, X509_VERIFY_PARAM *vpm)
{
return X509_VERIFY_PARAM_set1(ctx->param, vpm);
}
int SSL_set1_param(SSL *ssl, X509_VERIFY_PARAM *vpm)
{
return X509_VERIFY_PARAM_set1(ssl->param, vpm);
}
X509_VERIFY_PARAM *SSL_CTX_get0_param(SSL_CTX *ctx)
{
return ctx->param;
}
X509_VERIFY_PARAM *SSL_get0_param(SSL *ssl)
{
return ssl->param;
}
void SSL_certs_clear(SSL *s)
{
ssl_cert_clear_certs(s->cert);
}
void SSL_free(SSL *s)
{
int i;
if (s == NULL)
return;
CRYPTO_DOWN_REF(&s->references, &i, s->lock);
REF_PRINT_COUNT("SSL", s);
if (i > 0)
return;
REF_ASSERT_ISNT(i < 0);
X509_VERIFY_PARAM_free(s->param);
dane_final(&s->dane);
CRYPTO_free_ex_data(CRYPTO_EX_INDEX_SSL, s, &s->ex_data);
RECORD_LAYER_release(&s->rlayer);
/* Ignore return value */
ssl_free_wbio_buffer(s);
BIO_free_all(s->wbio);
s->wbio = NULL;
BIO_free_all(s->rbio);
s->rbio = NULL;
BUF_MEM_free(s->init_buf);
/* add extra stuff */
sk_SSL_CIPHER_free(s->cipher_list);
sk_SSL_CIPHER_free(s->cipher_list_by_id);
sk_SSL_CIPHER_free(s->tls13_ciphersuites);
sk_SSL_CIPHER_free(s->peer_ciphers);
/* Make the next call work :-) */
if (s->session != NULL) {
ssl_clear_bad_session(s);
SSL_SESSION_free(s->session);
}
SSL_SESSION_free(s->psksession);
OPENSSL_free(s->psksession_id);
ssl_cert_free(s->cert);
OPENSSL_free(s->shared_sigalgs);
/* Free up if allocated */
OPENSSL_free(s->ext.hostname);
SSL_CTX_free(s->session_ctx);
OPENSSL_free(s->ext.ecpointformats);
OPENSSL_free(s->ext.peer_ecpointformats);
OPENSSL_free(s->ext.supportedgroups);
OPENSSL_free(s->ext.peer_supportedgroups);
sk_X509_EXTENSION_pop_free(s->ext.ocsp.exts, X509_EXTENSION_free);
#ifndef OPENSSL_NO_OCSP
sk_OCSP_RESPID_pop_free(s->ext.ocsp.ids, OCSP_RESPID_free);
#endif
#ifndef OPENSSL_NO_CT
SCT_LIST_free(s->scts);
OPENSSL_free(s->ext.scts);
#endif
OPENSSL_free(s->ext.ocsp.resp);
OPENSSL_free(s->ext.alpn);
OPENSSL_free(s->ext.tls13_cookie);
if (s->clienthello != NULL)
OPENSSL_free(s->clienthello->pre_proc_exts);
OPENSSL_free(s->clienthello);
OPENSSL_free(s->pha_context);
EVP_MD_CTX_free(s->pha_dgst);
sk_X509_NAME_pop_free(s->ca_names, X509_NAME_free);
sk_X509_NAME_pop_free(s->client_ca_names, X509_NAME_free);
sk_X509_pop_free(s->verified_chain, X509_free);
if (s->method != NULL)
s->method->ssl_free(s);
/*
* Must occur after s->method->ssl_free(). The DTLS sent_messages queue
* may reference the EVP_CIPHER_CTX/EVP_MD_CTX that are freed here.
*/
clear_ciphers(s);
SSL_CTX_free(s->ctx);
ASYNC_WAIT_CTX_free(s->waitctx);
#if !defined(OPENSSL_NO_NEXTPROTONEG)
OPENSSL_free(s->ext.npn);
#endif
#ifndef OPENSSL_NO_SRTP
sk_SRTP_PROTECTION_PROFILE_free(s->srtp_profiles);
#endif
CRYPTO_THREAD_lock_free(s->lock);
OPENSSL_free(s);
}
void SSL_set0_rbio(SSL *s, BIO *rbio)
{
BIO_free_all(s->rbio);
s->rbio = rbio;
}
void SSL_set0_wbio(SSL *s, BIO *wbio)
{
/*
* If the output buffering BIO is still in place, remove it
*/
if (s->bbio != NULL)
s->wbio = BIO_pop(s->wbio);
BIO_free_all(s->wbio);
s->wbio = wbio;
/* Re-attach |bbio| to the new |wbio|. */
if (s->bbio != NULL)
s->wbio = BIO_push(s->bbio, s->wbio);
}
void SSL_set_bio(SSL *s, BIO *rbio, BIO *wbio)
{
/*
* For historical reasons, this function has many different cases in
* ownership handling.
*/
/* If nothing has changed, do nothing */
if (rbio == SSL_get_rbio(s) && wbio == SSL_get_wbio(s))
return;
/*
* If the two arguments are equal then one fewer reference is granted by the
* caller than we want to take
*/
if (rbio != NULL && rbio == wbio)
BIO_up_ref(rbio);
/*
* If only the wbio is changed only adopt one reference.
*/
if (rbio == SSL_get_rbio(s)) {
SSL_set0_wbio(s, wbio);
return;
}
/*
* There is an asymmetry here for historical reasons. If only the rbio is
* changed AND the rbio and wbio were originally different, then we only
* adopt one reference.
*/
if (wbio == SSL_get_wbio(s) && SSL_get_rbio(s) != SSL_get_wbio(s)) {
SSL_set0_rbio(s, rbio);
return;
}
/* Otherwise, adopt both references. */
SSL_set0_rbio(s, rbio);
SSL_set0_wbio(s, wbio);
}
BIO *SSL_get_rbio(const SSL *s)
{
return s->rbio;
}
BIO *SSL_get_wbio(const SSL *s)
{
if (s->bbio != NULL) {
/*
* If |bbio| is active, the true caller-configured BIO is its
* |next_bio|.
*/
return BIO_next(s->bbio);
}
return s->wbio;
}
int SSL_get_fd(const SSL *s)
{
return SSL_get_rfd(s);
}
int SSL_get_rfd(const SSL *s)
{
int ret = -1;
BIO *b, *r;
b = SSL_get_rbio(s);
r = BIO_find_type(b, BIO_TYPE_DESCRIPTOR);
if (r != NULL)
BIO_get_fd(r, &ret);
return ret;
}
int SSL_get_wfd(const SSL *s)
{
int ret = -1;
BIO *b, *r;
b = SSL_get_wbio(s);
r = BIO_find_type(b, BIO_TYPE_DESCRIPTOR);
if (r != NULL)
BIO_get_fd(r, &ret);
return ret;
}
#ifndef OPENSSL_NO_SOCK
int SSL_set_fd(SSL *s, int fd)
{
int ret = 0;
BIO *bio = NULL;
bio = BIO_new(BIO_s_socket());
if (bio == NULL) {
ERR_raise(ERR_LIB_SSL, ERR_R_BUF_LIB);
goto err;
}
BIO_set_fd(bio, fd, BIO_NOCLOSE);
SSL_set_bio(s, bio, bio);
#ifndef OPENSSL_NO_KTLS
/*
* The new socket is created successfully regardless of ktls_enable.
* ktls_enable doesn't change any functionality of the socket, except
* changing the setsockopt to enable the processing of ktls_start.
* Thus, it is not a problem to call it for non-TLS sockets.
*/
ktls_enable(fd);
#endif /* OPENSSL_NO_KTLS */
ret = 1;
err:
return ret;
}
int SSL_set_wfd(SSL *s, int fd)
{
BIO *rbio = SSL_get_rbio(s);
if (rbio == NULL || BIO_method_type(rbio) != BIO_TYPE_SOCKET
|| (int)BIO_get_fd(rbio, NULL) != fd) {
BIO *bio = BIO_new(BIO_s_socket());
if (bio == NULL) {
ERR_raise(ERR_LIB_SSL, ERR_R_BUF_LIB);
return 0;
}
BIO_set_fd(bio, fd, BIO_NOCLOSE);
SSL_set0_wbio(s, bio);
#ifndef OPENSSL_NO_KTLS
/*
* The new socket is created successfully regardless of ktls_enable.
* ktls_enable doesn't change any functionality of the socket, except
* changing the setsockopt to enable the processing of ktls_start.
* Thus, it is not a problem to call it for non-TLS sockets.
*/
ktls_enable(fd);
#endif /* OPENSSL_NO_KTLS */
} else {
BIO_up_ref(rbio);
SSL_set0_wbio(s, rbio);
}
return 1;
}
int SSL_set_rfd(SSL *s, int fd)
{
BIO *wbio = SSL_get_wbio(s);
if (wbio == NULL || BIO_method_type(wbio) != BIO_TYPE_SOCKET
|| ((int)BIO_get_fd(wbio, NULL) != fd)) {
BIO *bio = BIO_new(BIO_s_socket());
if (bio == NULL) {
ERR_raise(ERR_LIB_SSL, ERR_R_BUF_LIB);
return 0;
}
BIO_set_fd(bio, fd, BIO_NOCLOSE);
SSL_set0_rbio(s, bio);
} else {
BIO_up_ref(wbio);
SSL_set0_rbio(s, wbio);
}
return 1;
}
#endif
/* return length of latest Finished message we sent, copy to 'buf' */
size_t SSL_get_finished(const SSL *s, void *buf, size_t count)
{
size_t ret = 0;
ret = s->s3.tmp.finish_md_len;
if (count > ret)
count = ret;
memcpy(buf, s->s3.tmp.finish_md, count);
return ret;
}
/* return length of latest Finished message we expected, copy to 'buf' */
size_t SSL_get_peer_finished(const SSL *s, void *buf, size_t count)
{
size_t ret = 0;
ret = s->s3.tmp.peer_finish_md_len;
if (count > ret)
count = ret;
memcpy(buf, s->s3.tmp.peer_finish_md, count);
return ret;
}
int SSL_get_verify_mode(const SSL *s)
{
return s->verify_mode;
}
int SSL_get_verify_depth(const SSL *s)
{
return X509_VERIFY_PARAM_get_depth(s->param);
}
int (*SSL_get_verify_callback(const SSL *s)) (int, X509_STORE_CTX *) {
return s->verify_callback;
}
int SSL_CTX_get_verify_mode(const SSL_CTX *ctx)
{
return ctx->verify_mode;
}
int SSL_CTX_get_verify_depth(const SSL_CTX *ctx)
{
return X509_VERIFY_PARAM_get_depth(ctx->param);
}
int (*SSL_CTX_get_verify_callback(const SSL_CTX *ctx)) (int, X509_STORE_CTX *) {
return ctx->default_verify_callback;
}
void SSL_set_verify(SSL *s, int mode,
int (*callback) (int ok, X509_STORE_CTX *ctx))
{
s->verify_mode = mode;
if (callback != NULL)
s->verify_callback = callback;
}
void SSL_set_verify_depth(SSL *s, int depth)
{
X509_VERIFY_PARAM_set_depth(s->param, depth);
}
void SSL_set_read_ahead(SSL *s, int yes)
{
RECORD_LAYER_set_read_ahead(&s->rlayer, yes);
}
int SSL_get_read_ahead(const SSL *s)
{
return RECORD_LAYER_get_read_ahead(&s->rlayer);
}
int SSL_pending(const SSL *s)
{
size_t pending = s->method->ssl_pending(s);
/*
* SSL_pending cannot work properly if read-ahead is enabled
* (SSL_[CTX_]ctrl(..., SSL_CTRL_SET_READ_AHEAD, 1, NULL)), and it is
* impossible to fix since SSL_pending cannot report errors that may be
* observed while scanning the new data. (Note that SSL_pending() is
* often used as a boolean value, so we'd better not return -1.)
*
* SSL_pending also cannot work properly if the value >INT_MAX. In that case
* we just return INT_MAX.
*/
return pending < INT_MAX ? (int)pending : INT_MAX;
}
int SSL_has_pending(const SSL *s)
{
/*
* Similar to SSL_pending() but returns a 1 to indicate that we have
* processed or unprocessed data available or 0 otherwise (as opposed to the
* number of bytes available). Unlike SSL_pending() this will take into
* account read_ahead data. A 1 return simply indicates that we have data.
* That data may not result in any application data, or we may fail to parse
* the records for some reason.
*/
/* Check buffered app data if any first */
if (SSL_IS_DTLS(s)) {
DTLS1_RECORD_DATA *rdata;
pitem *item, *iter;
iter = pqueue_iterator(s->rlayer.d->buffered_app_data.q);
while ((item = pqueue_next(&iter)) != NULL) {
rdata = item->data;
if (rdata->rrec.length > 0)
return 1;
}
}
if (RECORD_LAYER_processed_read_pending(&s->rlayer))
return 1;
return RECORD_LAYER_read_pending(&s->rlayer);
}
X509 *SSL_get1_peer_certificate(const SSL *s)
{
X509 *r = SSL_get0_peer_certificate(s);
if (r != NULL)
X509_up_ref(r);
return r;
}
X509 *SSL_get0_peer_certificate(const SSL *s)
{
if ((s == NULL) || (s->session == NULL))
return NULL;
else
return s->session->peer;
}
STACK_OF(X509) *SSL_get_peer_cert_chain(const SSL *s)
{
STACK_OF(X509) *r;
if ((s == NULL) || (s->session == NULL))
r = NULL;
else
r = s->session->peer_chain;
/*
* If we are a client, cert_chain includes the peer's own certificate; if
* we are a server, it does not.
*/
return r;
}
/*
* Now in theory, since the calling process own 't' it should be safe to
* modify. We need to be able to read f without being hassled
*/
int SSL_copy_session_id(SSL *t, const SSL *f)
{
int i;
/* Do we need to do SSL locking? */
if (!SSL_set_session(t, SSL_get_session(f))) {
return 0;
}
/*
* what if we are setup for one protocol version but want to talk another
*/
if (t->method != f->method) {
t->method->ssl_free(t);
t->method = f->method;
if (t->method->ssl_new(t) == 0)
return 0;
}
CRYPTO_UP_REF(&f->cert->references, &i, f->cert->lock);
ssl_cert_free(t->cert);
t->cert = f->cert;
if (!SSL_set_session_id_context(t, f->sid_ctx, (int)f->sid_ctx_length)) {
return 0;
}
return 1;
}
/* Fix this so it checks all the valid key/cert options */
int SSL_CTX_check_private_key(const SSL_CTX *ctx)
{
if ((ctx == NULL) || (ctx->cert->key->x509 == NULL)) {
ERR_raise(ERR_LIB_SSL, SSL_R_NO_CERTIFICATE_ASSIGNED);
return 0;
}
if (ctx->cert->key->privatekey == NULL) {
ERR_raise(ERR_LIB_SSL, SSL_R_NO_PRIVATE_KEY_ASSIGNED);
return 0;
}
return X509_check_private_key
(ctx->cert->key->x509, ctx->cert->key->privatekey);
}
/* Fix this function so that it takes an optional type parameter */
int SSL_check_private_key(const SSL *ssl)
{
if (ssl == NULL) {
ERR_raise(ERR_LIB_SSL, ERR_R_PASSED_NULL_PARAMETER);
return 0;
}
if (ssl->cert->key->x509 == NULL) {
ERR_raise(ERR_LIB_SSL, SSL_R_NO_CERTIFICATE_ASSIGNED);
return 0;
}
if (ssl->cert->key->privatekey == NULL) {
ERR_raise(ERR_LIB_SSL, SSL_R_NO_PRIVATE_KEY_ASSIGNED);
return 0;
}
return X509_check_private_key(ssl->cert->key->x509,
ssl->cert->key->privatekey);
}
int SSL_waiting_for_async(SSL *s)
{
if (s->job)
return 1;
return 0;
}
int SSL_get_all_async_fds(SSL *s, OSSL_ASYNC_FD *fds, size_t *numfds)
{
ASYNC_WAIT_CTX *ctx = s->waitctx;
if (ctx == NULL)
return 0;
return ASYNC_WAIT_CTX_get_all_fds(ctx, fds, numfds);
}
int SSL_get_changed_async_fds(SSL *s, OSSL_ASYNC_FD *addfd, size_t *numaddfds,
OSSL_ASYNC_FD *delfd, size_t *numdelfds)
{
ASYNC_WAIT_CTX *ctx = s->waitctx;
if (ctx == NULL)
return 0;
return ASYNC_WAIT_CTX_get_changed_fds(ctx, addfd, numaddfds, delfd,
numdelfds);
}
int SSL_CTX_set_async_callback(SSL_CTX *ctx, SSL_async_callback_fn callback)
{
ctx->async_cb = callback;
return 1;
}
int SSL_CTX_set_async_callback_arg(SSL_CTX *ctx, void *arg)
{
ctx->async_cb_arg = arg;
return 1;
}
int SSL_set_async_callback(SSL *s, SSL_async_callback_fn callback)
{
s->async_cb = callback;
return 1;
}
int SSL_set_async_callback_arg(SSL *s, void *arg)
{
s->async_cb_arg = arg;
return 1;
}
int SSL_get_async_status(SSL *s, int *status)
{
ASYNC_WAIT_CTX *ctx = s->waitctx;
if (ctx == NULL)
return 0;
*status = ASYNC_WAIT_CTX_get_status(ctx);
return 1;
}
int SSL_accept(SSL *s)
{
if (s->handshake_func == NULL) {
/* Not properly initialized yet */
SSL_set_accept_state(s);
}
return SSL_do_handshake(s);
}
int SSL_connect(SSL *s)
{
if (s->handshake_func == NULL) {
/* Not properly initialized yet */
SSL_set_connect_state(s);
}
return SSL_do_handshake(s);
}
long SSL_get_default_timeout(const SSL *s)
{
return s->method->get_timeout();
}
static int ssl_async_wait_ctx_cb(void *arg)
{
SSL *s = (SSL *)arg;
return s->async_cb(s, s->async_cb_arg);
}
static int ssl_start_async_job(SSL *s, struct ssl_async_args *args,
int (*func) (void *))
{
int ret;
if (s->waitctx == NULL) {
s->waitctx = ASYNC_WAIT_CTX_new();
if (s->waitctx == NULL)
return -1;
if (s->async_cb != NULL
&& !ASYNC_WAIT_CTX_set_callback
(s->waitctx, ssl_async_wait_ctx_cb, s))
return -1;
}
s->rwstate = SSL_NOTHING;
switch (ASYNC_start_job(&s->job, s->waitctx, &ret, func, args,
sizeof(struct ssl_async_args))) {
case ASYNC_ERR:
s->rwstate = SSL_NOTHING;
ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_INIT_ASYNC);
return -1;
case ASYNC_PAUSE:
s->rwstate = SSL_ASYNC_PAUSED;
return -1;
case ASYNC_NO_JOBS:
s->rwstate = SSL_ASYNC_NO_JOBS;
return -1;
case ASYNC_FINISH:
s->job = NULL;
return ret;
default:
s->rwstate = SSL_NOTHING;
ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
/* Shouldn't happen */
return -1;
}
}
static int ssl_io_intern(void *vargs)
{
struct ssl_async_args *args;
SSL *s;
void *buf;
size_t num;
args = (struct ssl_async_args *)vargs;
s = args->s;
buf = args->buf;
num = args->num;
switch (args->type) {
case READFUNC:
return args->f.func_read(s, buf, num, &s->asyncrw);
case WRITEFUNC:
return args->f.func_write(s, buf, num, &s->asyncrw);
case OTHERFUNC:
return args->f.func_other(s);
}
return -1;
}
int ssl_read_internal(SSL *s, void *buf, size_t num, size_t *readbytes)
{
if (s->handshake_func == NULL) {
ERR_raise(ERR_LIB_SSL, SSL_R_UNINITIALIZED);
return -1;
}
if (s->shutdown & SSL_RECEIVED_SHUTDOWN) {
s->rwstate = SSL_NOTHING;
return 0;
}
if (s->early_data_state == SSL_EARLY_DATA_CONNECT_RETRY
|| s->early_data_state == SSL_EARLY_DATA_ACCEPT_RETRY) {
ERR_raise(ERR_LIB_SSL, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
return 0;
}
/*
* If we are a client and haven't received the ServerHello etc then we
* better do that
*/
ossl_statem_check_finish_init(s, 0);
if ((s->mode & SSL_MODE_ASYNC) && ASYNC_get_current_job() == NULL) {
struct ssl_async_args args;
int ret;
args.s = s;
args.buf = buf;
args.num = num;
args.type = READFUNC;
args.f.func_read = s->method->ssl_read;
ret = ssl_start_async_job(s, &args, ssl_io_intern);
*readbytes = s->asyncrw;
return ret;
} else {
return s->method->ssl_read(s, buf, num, readbytes);
}
}
int SSL_read(SSL *s, void *buf, int num)
{
int ret;
size_t readbytes;
if (num < 0) {
ERR_raise(ERR_LIB_SSL, SSL_R_BAD_LENGTH);
return -1;
}
ret = ssl_read_internal(s, buf, (size_t)num, &readbytes);
/*
* The cast is safe here because ret should be <= INT_MAX because num is
* <= INT_MAX
*/
if (ret > 0)
ret = (int)readbytes;
return ret;
}
int SSL_read_ex(SSL *s, void *buf, size_t num, size_t *readbytes)
{
int ret = ssl_read_internal(s, buf, num, readbytes);
if (ret < 0)
ret = 0;
return ret;
}
int SSL_read_early_data(SSL *s, void *buf, size_t num, size_t *readbytes)
{
int ret;
if (!s->server) {
ERR_raise(ERR_LIB_SSL, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
return SSL_READ_EARLY_DATA_ERROR;
}
switch (s->early_data_state) {
case SSL_EARLY_DATA_NONE:
if (!SSL_in_before(s)) {
ERR_raise(ERR_LIB_SSL, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
return SSL_READ_EARLY_DATA_ERROR;
}
/* fall through */
case SSL_EARLY_DATA_ACCEPT_RETRY:
s->early_data_state = SSL_EARLY_DATA_ACCEPTING;
ret = SSL_accept(s);
if (ret <= 0) {
/* NBIO or error */
s->early_data_state = SSL_EARLY_DATA_ACCEPT_RETRY;
return SSL_READ_EARLY_DATA_ERROR;
}
/* fall through */
case SSL_EARLY_DATA_READ_RETRY:
if (s->ext.early_data == SSL_EARLY_DATA_ACCEPTED) {
s->early_data_state = SSL_EARLY_DATA_READING;
ret = SSL_read_ex(s, buf, num, readbytes);
/*
* State machine will update early_data_state to
* SSL_EARLY_DATA_FINISHED_READING if we get an EndOfEarlyData
* message
*/
if (ret > 0 || (ret <= 0 && s->early_data_state
!= SSL_EARLY_DATA_FINISHED_READING)) {
s->early_data_state = SSL_EARLY_DATA_READ_RETRY;
return ret > 0 ? SSL_READ_EARLY_DATA_SUCCESS
: SSL_READ_EARLY_DATA_ERROR;
}
} else {
s->early_data_state = SSL_EARLY_DATA_FINISHED_READING;
}
*readbytes = 0;
return SSL_READ_EARLY_DATA_FINISH;
default:
ERR_raise(ERR_LIB_SSL, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
return SSL_READ_EARLY_DATA_ERROR;
}
}
int SSL_get_early_data_status(const SSL *s)
{
return s->ext.early_data;
}
static int ssl_peek_internal(SSL *s, void *buf, size_t num, size_t *readbytes)
{
if (s->handshake_func == NULL) {
ERR_raise(ERR_LIB_SSL, SSL_R_UNINITIALIZED);
return -1;
}
if (s->shutdown & SSL_RECEIVED_SHUTDOWN) {
return 0;
}
if ((s->mode & SSL_MODE_ASYNC) && ASYNC_get_current_job() == NULL) {
struct ssl_async_args args;
int ret;
args.s = s;
args.buf = buf;
args.num = num;
args.type = READFUNC;
args.f.func_read = s->method->ssl_peek;
ret = ssl_start_async_job(s, &args, ssl_io_intern);
*readbytes = s->asyncrw;
return ret;
} else {
return s->method->ssl_peek(s, buf, num, readbytes);
}
}
int SSL_peek(SSL *s, void *buf, int num)
{
int ret;
size_t readbytes;
if (num < 0) {
ERR_raise(ERR_LIB_SSL, SSL_R_BAD_LENGTH);
return -1;
}
ret = ssl_peek_internal(s, buf, (size_t)num, &readbytes);
/*
* The cast is safe here because ret should be <= INT_MAX because num is
* <= INT_MAX
*/
if (ret > 0)
ret = (int)readbytes;
return ret;
}
int SSL_peek_ex(SSL *s, void *buf, size_t num, size_t *readbytes)
{
int ret = ssl_peek_internal(s, buf, num, readbytes);
if (ret < 0)
ret = 0;
return ret;
}
int ssl_write_internal(SSL *s, const void *buf, size_t num, size_t *written)
{
if (s->handshake_func == NULL) {
ERR_raise(ERR_LIB_SSL, SSL_R_UNINITIALIZED);
return -1;
}
if (s->shutdown & SSL_SENT_SHUTDOWN) {
s->rwstate = SSL_NOTHING;
ERR_raise(ERR_LIB_SSL, SSL_R_PROTOCOL_IS_SHUTDOWN);
return -1;
}
if (s->early_data_state == SSL_EARLY_DATA_CONNECT_RETRY
|| s->early_data_state == SSL_EARLY_DATA_ACCEPT_RETRY
|| s->early_data_state == SSL_EARLY_DATA_READ_RETRY) {
ERR_raise(ERR_LIB_SSL, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
return 0;
}
/* If we are a client and haven't sent the Finished we better do that */
ossl_statem_check_finish_init(s, 1);
if ((s->mode & SSL_MODE_ASYNC) && ASYNC_get_current_job() == NULL) {
int ret;
struct ssl_async_args args;
args.s = s;
args.buf = (void *)buf;
args.num = num;
args.type = WRITEFUNC;
args.f.func_write = s->method->ssl_write;
ret = ssl_start_async_job(s, &args, ssl_io_intern);
*written = s->asyncrw;
return ret;
} else {
return s->method->ssl_write(s, buf, num, written);
}
}
ossl_ssize_t SSL_sendfile(SSL *s, int fd, off_t offset, size_t size, int flags)
{
ossl_ssize_t ret;
if (s->handshake_func == NULL) {
ERR_raise(ERR_LIB_SSL, SSL_R_UNINITIALIZED);
return -1;
}
if (s->shutdown & SSL_SENT_SHUTDOWN) {
s->rwstate = SSL_NOTHING;
ERR_raise(ERR_LIB_SSL, SSL_R_PROTOCOL_IS_SHUTDOWN);
return -1;
}
if (!BIO_get_ktls_send(s->wbio)) {
ERR_raise(ERR_LIB_SSL, SSL_R_UNINITIALIZED);
return -1;
}
/* If we have an alert to send, lets send it */
if (s->s3.alert_dispatch) {
ret = (ossl_ssize_t)s->method->ssl_dispatch_alert(s);
if (ret <= 0) {
/* SSLfatal() already called if appropriate */
return ret;
}
/* if it went, fall through and send more stuff */
}
s->rwstate = SSL_WRITING;
if (BIO_flush(s->wbio) <= 0) {
if (!BIO_should_retry(s->wbio)) {
s->rwstate = SSL_NOTHING;
} else {
#ifdef EAGAIN
set_sys_error(EAGAIN);
#endif
}
return -1;
}
#ifdef OPENSSL_NO_KTLS
ERR_raise_data(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR,
"can't call ktls_sendfile(), ktls disabled");
return -1;
#else
ret = ktls_sendfile(SSL_get_wfd(s), fd, offset, size, flags);
if (ret < 0) {
#if defined(EAGAIN) && defined(EINTR) && defined(EBUSY)
if ((get_last_sys_error() == EAGAIN) ||
(get_last_sys_error() == EINTR) ||
(get_last_sys_error() == EBUSY))
BIO_set_retry_write(s->wbio);
else
#endif
ERR_raise(ERR_LIB_SSL, SSL_R_UNINITIALIZED);
return ret;
}
s->rwstate = SSL_NOTHING;
return ret;
#endif
}
int SSL_write(SSL *s, const void *buf, int num)
{
int ret;
size_t written;
if (num < 0) {
ERR_raise(ERR_LIB_SSL, SSL_R_BAD_LENGTH);
return -1;
}
ret = ssl_write_internal(s, buf, (size_t)num, &written);
/*
* The cast is safe here because ret should be <= INT_MAX because num is
* <= INT_MAX
*/
if (ret > 0)
ret = (int)written;
return ret;
}
int SSL_write_ex(SSL *s, const void *buf, size_t num, size_t *written)
{
int ret = ssl_write_internal(s, buf, num, written);
if (ret < 0)
ret = 0;
return ret;
}
int SSL_write_early_data(SSL *s, const void *buf, size_t num, size_t *written)
{
int ret, early_data_state;
size_t writtmp;
uint32_t partialwrite;
switch (s->early_data_state) {
case SSL_EARLY_DATA_NONE:
if (s->server
|| !SSL_in_before(s)
|| ((s->session == NULL || s->session->ext.max_early_data == 0)
&& (s->psk_use_session_cb == NULL))) {
ERR_raise(ERR_LIB_SSL, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
return 0;
}
/* fall through */
case SSL_EARLY_DATA_CONNECT_RETRY:
s->early_data_state = SSL_EARLY_DATA_CONNECTING;
ret = SSL_connect(s);
if (ret <= 0) {
/* NBIO or error */
s->early_data_state = SSL_EARLY_DATA_CONNECT_RETRY;
return 0;
}
/* fall through */
case SSL_EARLY_DATA_WRITE_RETRY:
s->early_data_state = SSL_EARLY_DATA_WRITING;
/*
* We disable partial write for early data because we don't keep track
* of how many bytes we've written between the SSL_write_ex() call and
* the flush if the flush needs to be retried)
*/
partialwrite = s->mode & SSL_MODE_ENABLE_PARTIAL_WRITE;
s->mode &= ~SSL_MODE_ENABLE_PARTIAL_WRITE;
ret = SSL_write_ex(s, buf, num, &writtmp);
s->mode |= partialwrite;
if (!ret) {
s->early_data_state = SSL_EARLY_DATA_WRITE_RETRY;
return ret;
}
s->early_data_state = SSL_EARLY_DATA_WRITE_FLUSH;
/* fall through */
case SSL_EARLY_DATA_WRITE_FLUSH:
/* The buffering BIO is still in place so we need to flush it */
if (statem_flush(s) != 1)
return 0;
*written = num;
s->early_data_state = SSL_EARLY_DATA_WRITE_RETRY;
return 1;
case SSL_EARLY_DATA_FINISHED_READING:
case SSL_EARLY_DATA_READ_RETRY:
early_data_state = s->early_data_state;
/* We are a server writing to an unauthenticated client */
s->early_data_state = SSL_EARLY_DATA_UNAUTH_WRITING;
ret = SSL_write_ex(s, buf, num, written);
/* The buffering BIO is still in place */
if (ret)
(void)BIO_flush(s->wbio);
s->early_data_state = early_data_state;
return ret;
default:
ERR_raise(ERR_LIB_SSL, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
return 0;
}
}
int SSL_shutdown(SSL *s)
{
/*
* Note that this function behaves differently from what one might
* expect. Return values are 0 for no success (yet), 1 for success; but
* calling it once is usually not enough, even if blocking I/O is used
* (see ssl3_shutdown).
*/
if (s->handshake_func == NULL) {
ERR_raise(ERR_LIB_SSL, SSL_R_UNINITIALIZED);
return -1;
}
if (!SSL_in_init(s)) {
if ((s->mode & SSL_MODE_ASYNC) && ASYNC_get_current_job() == NULL) {
struct ssl_async_args args;
memset(&args, 0, sizeof(args));
args.s = s;
args.type = OTHERFUNC;
args.f.func_other = s->method->ssl_shutdown;
return ssl_start_async_job(s, &args, ssl_io_intern);
} else {
return s->method->ssl_shutdown(s);
}
} else {
ERR_raise(ERR_LIB_SSL, SSL_R_SHUTDOWN_WHILE_IN_INIT);
return -1;
}
}
int SSL_key_update(SSL *s, int updatetype)
{
if (!SSL_IS_TLS13(s)) {
ERR_raise(ERR_LIB_SSL, SSL_R_WRONG_SSL_VERSION);
return 0;
}
if (updatetype != SSL_KEY_UPDATE_NOT_REQUESTED
&& updatetype != SSL_KEY_UPDATE_REQUESTED) {
ERR_raise(ERR_LIB_SSL, SSL_R_INVALID_KEY_UPDATE_TYPE);
return 0;
}
if (!SSL_is_init_finished(s)) {
ERR_raise(ERR_LIB_SSL, SSL_R_STILL_IN_INIT);
return 0;
}
if (RECORD_LAYER_write_pending(&s->rlayer)) {
ERR_raise(ERR_LIB_SSL, SSL_R_BAD_WRITE_RETRY);
return 0;
}
ossl_statem_set_in_init(s, 1);
s->key_update = updatetype;
return 1;
}
int SSL_get_key_update_type(const SSL *s)
{
return s->key_update;
}
/*
* Can we accept a renegotiation request? If yes, set the flag and
* return 1 if yes. If not, raise error and return 0.
*/
static int can_renegotiate(const SSL *s)
{
if (SSL_IS_TLS13(s)) {
ERR_raise(ERR_LIB_SSL, SSL_R_WRONG_SSL_VERSION);
return 0;
}
if ((s->options & SSL_OP_NO_RENEGOTIATION) != 0) {
ERR_raise(ERR_LIB_SSL, SSL_R_NO_RENEGOTIATION);
return 0;
}
return 1;
}
int SSL_renegotiate(SSL *s)
{
if (!can_renegotiate(s))
return 0;
s->renegotiate = 1;
s->new_session = 1;
return s->method->ssl_renegotiate(s);
}
int SSL_renegotiate_abbreviated(SSL *s)
{
if (!can_renegotiate(s))
return 0;
s->renegotiate = 1;
s->new_session = 0;
return s->method->ssl_renegotiate(s);
}
int SSL_renegotiate_pending(const SSL *s)
{
/*
* becomes true when negotiation is requested; false again once a
* handshake has finished
*/
return (s->renegotiate != 0);
}
int SSL_new_session_ticket(SSL *s)
{
/* If we are in init because we're sending tickets, okay to send more. */
if ((SSL_in_init(s) && s->ext.extra_tickets_expected == 0)
|| SSL_IS_FIRST_HANDSHAKE(s) || !s->server
|| !SSL_IS_TLS13(s))
return 0;
s->ext.extra_tickets_expected++;
if (!RECORD_LAYER_write_pending(&s->rlayer) && !SSL_in_init(s))
ossl_statem_set_in_init(s, 1);
return 1;
}
long SSL_ctrl(SSL *s, int cmd, long larg, void *parg)
{
long l;
switch (cmd) {
case SSL_CTRL_GET_READ_AHEAD:
return RECORD_LAYER_get_read_ahead(&s->rlayer);
case SSL_CTRL_SET_READ_AHEAD:
l = RECORD_LAYER_get_read_ahead(&s->rlayer);
RECORD_LAYER_set_read_ahead(&s->rlayer, larg);
return l;
case SSL_CTRL_SET_MSG_CALLBACK_ARG:
s->msg_callback_arg = parg;
return 1;
case SSL_CTRL_MODE:
return (s->mode |= larg);
case SSL_CTRL_CLEAR_MODE:
return (s->mode &= ~larg);
case SSL_CTRL_GET_MAX_CERT_LIST:
return (long)s->max_cert_list;
case SSL_CTRL_SET_MAX_CERT_LIST:
if (larg < 0)
return 0;
l = (long)s->max_cert_list;
s->max_cert_list = (size_t)larg;
return l;
case SSL_CTRL_SET_MAX_SEND_FRAGMENT:
if (larg < 512 || larg > SSL3_RT_MAX_PLAIN_LENGTH)
return 0;
#ifndef OPENSSL_NO_KTLS
if (s->wbio != NULL && BIO_get_ktls_send(s->wbio))
return 0;
#endif /* OPENSSL_NO_KTLS */
s->max_send_fragment = larg;
if (s->max_send_fragment < s->split_send_fragment)
s->split_send_fragment = s->max_send_fragment;
return 1;
case SSL_CTRL_SET_SPLIT_SEND_FRAGMENT:
if ((size_t)larg > s->max_send_fragment || larg == 0)
return 0;
s->split_send_fragment = larg;
return 1;
case SSL_CTRL_SET_MAX_PIPELINES:
if (larg < 1 || larg > SSL_MAX_PIPELINES)
return 0;
s->max_pipelines = larg;
if (larg > 1)
RECORD_LAYER_set_read_ahead(&s->rlayer, 1);
return 1;
case SSL_CTRL_GET_RI_SUPPORT:
return s->s3.send_connection_binding;
case SSL_CTRL_SET_RETRY_VERIFY:
s->rwstate = SSL_RETRY_VERIFY;
return 1;
case SSL_CTRL_CERT_FLAGS:
return (s->cert->cert_flags |= larg);
case SSL_CTRL_CLEAR_CERT_FLAGS:
return (s->cert->cert_flags &= ~larg);
case SSL_CTRL_GET_RAW_CIPHERLIST:
if (parg) {
if (s->s3.tmp.ciphers_raw == NULL)
return 0;
*(unsigned char **)parg = s->s3.tmp.ciphers_raw;
return (int)s->s3.tmp.ciphers_rawlen;
} else {
return TLS_CIPHER_LEN;
}
case SSL_CTRL_GET_EXTMS_SUPPORT:
if (!s->session || SSL_in_init(s) || ossl_statem_get_in_handshake(s))
return -1;
if (s->session->flags & SSL_SESS_FLAG_EXTMS)
return 1;
else
return 0;
case SSL_CTRL_SET_MIN_PROTO_VERSION:
return ssl_check_allowed_versions(larg, s->max_proto_version)
&& ssl_set_version_bound(s->ctx->method->version, (int)larg,
&s->min_proto_version);
case SSL_CTRL_GET_MIN_PROTO_VERSION:
return s->min_proto_version;
case SSL_CTRL_SET_MAX_PROTO_VERSION:
return ssl_check_allowed_versions(s->min_proto_version, larg)
&& ssl_set_version_bound(s->ctx->method->version, (int)larg,
&s->max_proto_version);
case SSL_CTRL_GET_MAX_PROTO_VERSION:
return s->max_proto_version;
default:
return s->method->ssl_ctrl(s, cmd, larg, parg);
}
}
long SSL_callback_ctrl(SSL *s, int cmd, void (*fp) (void))
{
switch (cmd) {
case SSL_CTRL_SET_MSG_CALLBACK:
s->msg_callback = (void (*)
(int write_p, int version, int content_type,
const void *buf, size_t len, SSL *ssl,
void *arg))(fp);
return 1;
default:
return s->method->ssl_callback_ctrl(s, cmd, fp);
}
}
LHASH_OF(SSL_SESSION) *SSL_CTX_sessions(SSL_CTX *ctx)
{
return ctx->sessions;
}
static int ssl_tsan_load(SSL_CTX *ctx, TSAN_QUALIFIER int *stat)
{
int res = 0;
if (ssl_tsan_lock(ctx)) {
res = tsan_load(stat);
ssl_tsan_unlock(ctx);
}
return res;
}
long SSL_CTX_ctrl(SSL_CTX *ctx, int cmd, long larg, void *parg)
{
long l;
/* For some cases with ctx == NULL perform syntax checks */
if (ctx == NULL) {
switch (cmd) {
case SSL_CTRL_SET_GROUPS_LIST:
return tls1_set_groups_list(ctx, NULL, NULL, parg);
case SSL_CTRL_SET_SIGALGS_LIST:
case SSL_CTRL_SET_CLIENT_SIGALGS_LIST:
return tls1_set_sigalgs_list(NULL, parg, 0);
default:
return 0;
}
}
switch (cmd) {
case SSL_CTRL_GET_READ_AHEAD:
return ctx->read_ahead;
case SSL_CTRL_SET_READ_AHEAD:
l = ctx->read_ahead;
ctx->read_ahead = larg;
return l;
case SSL_CTRL_SET_MSG_CALLBACK_ARG:
ctx->msg_callback_arg = parg;
return 1;
case SSL_CTRL_GET_MAX_CERT_LIST:
return (long)ctx->max_cert_list;
case SSL_CTRL_SET_MAX_CERT_LIST:
if (larg < 0)
return 0;
l = (long)ctx->max_cert_list;
ctx->max_cert_list = (size_t)larg;
return l;
case SSL_CTRL_SET_SESS_CACHE_SIZE:
if (larg < 0)
return 0;
l = (long)ctx->session_cache_size;
ctx->session_cache_size = (size_t)larg;
return l;
case SSL_CTRL_GET_SESS_CACHE_SIZE:
return (long)ctx->session_cache_size;
case SSL_CTRL_SET_SESS_CACHE_MODE:
l = ctx->session_cache_mode;
ctx->session_cache_mode = larg;
return l;
case SSL_CTRL_GET_SESS_CACHE_MODE:
return ctx->session_cache_mode;
case SSL_CTRL_SESS_NUMBER:
return lh_SSL_SESSION_num_items(ctx->sessions);
case SSL_CTRL_SESS_CONNECT:
return ssl_tsan_load(ctx, &ctx->stats.sess_connect);
case SSL_CTRL_SESS_CONNECT_GOOD:
return ssl_tsan_load(ctx, &ctx->stats.sess_connect_good);
case SSL_CTRL_SESS_CONNECT_RENEGOTIATE:
return ssl_tsan_load(ctx, &ctx->stats.sess_connect_renegotiate);
case SSL_CTRL_SESS_ACCEPT:
return ssl_tsan_load(ctx, &ctx->stats.sess_accept);
case SSL_CTRL_SESS_ACCEPT_GOOD:
return ssl_tsan_load(ctx, &ctx->stats.sess_accept_good);
case SSL_CTRL_SESS_ACCEPT_RENEGOTIATE:
return ssl_tsan_load(ctx, &ctx->stats.sess_accept_renegotiate);
case SSL_CTRL_SESS_HIT:
return ssl_tsan_load(ctx, &ctx->stats.sess_hit);
case SSL_CTRL_SESS_CB_HIT:
return ssl_tsan_load(ctx, &ctx->stats.sess_cb_hit);
case SSL_CTRL_SESS_MISSES:
return ssl_tsan_load(ctx, &ctx->stats.sess_miss);
case SSL_CTRL_SESS_TIMEOUTS:
return ssl_tsan_load(ctx, &ctx->stats.sess_timeout);
case SSL_CTRL_SESS_CACHE_FULL:
return ssl_tsan_load(ctx, &ctx->stats.sess_cache_full);
case SSL_CTRL_MODE:
return (ctx->mode |= larg);
case SSL_CTRL_CLEAR_MODE:
return (ctx->mode &= ~larg);
case SSL_CTRL_SET_MAX_SEND_FRAGMENT:
if (larg < 512 || larg > SSL3_RT_MAX_PLAIN_LENGTH)
return 0;
ctx->max_send_fragment = larg;
if (ctx->max_send_fragment < ctx->split_send_fragment)
ctx->split_send_fragment = ctx->max_send_fragment;
return 1;
case SSL_CTRL_SET_SPLIT_SEND_FRAGMENT:
if ((size_t)larg > ctx->max_send_fragment || larg == 0)
return 0;
ctx->split_send_fragment = larg;
return 1;
case SSL_CTRL_SET_MAX_PIPELINES:
if (larg < 1 || larg > SSL_MAX_PIPELINES)
return 0;
ctx->max_pipelines = larg;
return 1;
case SSL_CTRL_CERT_FLAGS:
return (ctx->cert->cert_flags |= larg);
case SSL_CTRL_CLEAR_CERT_FLAGS:
return (ctx->cert->cert_flags &= ~larg);
case SSL_CTRL_SET_MIN_PROTO_VERSION:
return ssl_check_allowed_versions(larg, ctx->max_proto_version)
&& ssl_set_version_bound(ctx->method->version, (int)larg,
&ctx->min_proto_version);
case SSL_CTRL_GET_MIN_PROTO_VERSION:
return ctx->min_proto_version;
case SSL_CTRL_SET_MAX_PROTO_VERSION:
return ssl_check_allowed_versions(ctx->min_proto_version, larg)
&& ssl_set_version_bound(ctx->method->version, (int)larg,
&ctx->max_proto_version);
case SSL_CTRL_GET_MAX_PROTO_VERSION:
return ctx->max_proto_version;
default:
return ctx->method->ssl_ctx_ctrl(ctx, cmd, larg, parg);
}
}
long SSL_CTX_callback_ctrl(SSL_CTX *ctx, int cmd, void (*fp) (void))
{
switch (cmd) {
case SSL_CTRL_SET_MSG_CALLBACK:
ctx->msg_callback = (void (*)
(int write_p, int version, int content_type,
const void *buf, size_t len, SSL *ssl,
void *arg))(fp);
return 1;
default:
return ctx->method->ssl_ctx_callback_ctrl(ctx, cmd, fp);
}
}
int ssl_cipher_id_cmp(const SSL_CIPHER *a, const SSL_CIPHER *b)
{
if (a->id > b->id)
return 1;
if (a->id < b->id)
return -1;
return 0;
}
int ssl_cipher_ptr_id_cmp(const SSL_CIPHER *const *ap,
const SSL_CIPHER *const *bp)
{
if ((*ap)->id > (*bp)->id)
return 1;
if ((*ap)->id < (*bp)->id)
return -1;
return 0;
}
/** return a STACK of the ciphers available for the SSL and in order of
* preference */
STACK_OF(SSL_CIPHER) *SSL_get_ciphers(const SSL *s)
{
if (s != NULL) {
if (s->cipher_list != NULL) {
return s->cipher_list;
} else if ((s->ctx != NULL) && (s->ctx->cipher_list != NULL)) {
return s->ctx->cipher_list;
}
}
return NULL;
}
STACK_OF(SSL_CIPHER) *SSL_get_client_ciphers(const SSL *s)
{
if ((s == NULL) || !s->server)
return NULL;
return s->peer_ciphers;
}
STACK_OF(SSL_CIPHER) *SSL_get1_supported_ciphers(SSL *s)
{
STACK_OF(SSL_CIPHER) *sk = NULL, *ciphers;
int i;
ciphers = SSL_get_ciphers(s);
if (!ciphers)
return NULL;
if (!ssl_set_client_disabled(s))
return NULL;
for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
const SSL_CIPHER *c = sk_SSL_CIPHER_value(ciphers, i);
if (!ssl_cipher_disabled(s, c, SSL_SECOP_CIPHER_SUPPORTED, 0)) {
if (!sk)
sk = sk_SSL_CIPHER_new_null();
if (!sk)
return NULL;
if (!sk_SSL_CIPHER_push(sk, c)) {
sk_SSL_CIPHER_free(sk);
return NULL;
}
}
}
return sk;
}
/** return a STACK of the ciphers available for the SSL and in order of
* algorithm id */
STACK_OF(SSL_CIPHER) *ssl_get_ciphers_by_id(SSL *s)
{
if (s != NULL) {
if (s->cipher_list_by_id != NULL) {
return s->cipher_list_by_id;
} else if ((s->ctx != NULL) && (s->ctx->cipher_list_by_id != NULL)) {
return s->ctx->cipher_list_by_id;
}
}
return NULL;
}
/** The old interface to get the same thing as SSL_get_ciphers() */
const char *SSL_get_cipher_list(const SSL *s, int n)
{
const SSL_CIPHER *c;
STACK_OF(SSL_CIPHER) *sk;
if (s == NULL)
return NULL;
sk = SSL_get_ciphers(s);
if ((sk == NULL) || (sk_SSL_CIPHER_num(sk) <= n))
return NULL;
c = sk_SSL_CIPHER_value(sk, n);
if (c == NULL)
return NULL;
return c->name;
}
/** return a STACK of the ciphers available for the SSL_CTX and in order of
* preference */
STACK_OF(SSL_CIPHER) *SSL_CTX_get_ciphers(const SSL_CTX *ctx)
{
if (ctx != NULL)
return ctx->cipher_list;
return NULL;
}
/*
* Distinguish between ciphers controlled by set_ciphersuite() and
* set_cipher_list() when counting.
*/
static int cipher_list_tls12_num(STACK_OF(SSL_CIPHER) *sk)
{
int i, num = 0;
const SSL_CIPHER *c;
if (sk == NULL)
return 0;
for (i = 0; i < sk_SSL_CIPHER_num(sk); ++i) {
c = sk_SSL_CIPHER_value(sk, i);
if (c->min_tls >= TLS1_3_VERSION)
continue;
num++;
}
return num;
}
/** specify the ciphers to be used by default by the SSL_CTX */
int SSL_CTX_set_cipher_list(SSL_CTX *ctx, const char *str)
{
STACK_OF(SSL_CIPHER) *sk;
sk = ssl_create_cipher_list(ctx, ctx->tls13_ciphersuites,
&ctx->cipher_list, &ctx->cipher_list_by_id, str,
ctx->cert);
/*
* ssl_create_cipher_list may return an empty stack if it was unable to
* find a cipher matching the given rule string (for example if the rule
* string specifies a cipher which has been disabled). This is not an
* error as far as ssl_create_cipher_list is concerned, and hence
* ctx->cipher_list and ctx->cipher_list_by_id has been updated.
*/
if (sk == NULL)
return 0;
else if (cipher_list_tls12_num(sk) == 0) {
ERR_raise(ERR_LIB_SSL, SSL_R_NO_CIPHER_MATCH);
return 0;
}
return 1;
}
/** specify the ciphers to be used by the SSL */
int SSL_set_cipher_list(SSL *s, const char *str)
{
STACK_OF(SSL_CIPHER) *sk;
sk = ssl_create_cipher_list(s->ctx, s->tls13_ciphersuites,
&s->cipher_list, &s->cipher_list_by_id, str,
s->cert);
/* see comment in SSL_CTX_set_cipher_list */
if (sk == NULL)
return 0;
else if (cipher_list_tls12_num(sk) == 0) {
ERR_raise(ERR_LIB_SSL, SSL_R_NO_CIPHER_MATCH);
return 0;
}
return 1;
}
char *SSL_get_shared_ciphers(const SSL *s, char *buf, int size)
{
char *p;
STACK_OF(SSL_CIPHER) *clntsk, *srvrsk;
const SSL_CIPHER *c;
int i;
if (!s->server
|| s->peer_ciphers == NULL
|| size < 2)
return NULL;
p = buf;
clntsk = s->peer_ciphers;
srvrsk = SSL_get_ciphers(s);
if (clntsk == NULL || srvrsk == NULL)
return NULL;
if (sk_SSL_CIPHER_num(clntsk) == 0 || sk_SSL_CIPHER_num(srvrsk) == 0)
return NULL;
for (i = 0; i < sk_SSL_CIPHER_num(clntsk); i++) {
int n;
c = sk_SSL_CIPHER_value(clntsk, i);
if (sk_SSL_CIPHER_find(srvrsk, c) < 0)
continue;
n = OPENSSL_strnlen(c->name, size);
if (n >= size) {
if (p != buf)
--p;
*p = '\0';
return buf;
}
memcpy(p, c->name, n);
p += n;
*(p++) = ':';
size -= n + 1;
}
p[-1] = '\0';
return buf;
}
/**
* Return the requested servername (SNI) value. Note that the behaviour varies
* depending on:
* - whether this is called by the client or the server,
* - if we are before or during/after the handshake,
* - if a resumption or normal handshake is being attempted/has occurred
* - whether we have negotiated TLSv1.2 (or below) or TLSv1.3
*
* Note that only the host_name type is defined (RFC 3546).
*/
const char *SSL_get_servername(const SSL *s, const int type)
{
/*
* If we don't know if we are the client or the server yet then we assume
* client.
*/
int server = s->handshake_func == NULL ? 0 : s->server;
if (type != TLSEXT_NAMETYPE_host_name)
return NULL;
if (server) {
/**
* Server side
* In TLSv1.3 on the server SNI is not associated with the session
* but in TLSv1.2 or below it is.
*
* Before the handshake:
* - return NULL
*
* During/after the handshake (TLSv1.2 or below resumption occurred):
* - If a servername was accepted by the server in the original
* handshake then it will return that servername, or NULL otherwise.
*
* During/after the handshake (TLSv1.2 or below resumption did not occur):
* - The function will return the servername requested by the client in
* this handshake or NULL if none was requested.
*/
if (s->hit && !SSL_IS_TLS13(s))
return s->session->ext.hostname;
} else {
/**
* Client side
*
* Before the handshake:
* - If a servername has been set via a call to
* SSL_set_tlsext_host_name() then it will return that servername
* - If one has not been set, but a TLSv1.2 resumption is being
* attempted and the session from the original handshake had a
* servername accepted by the server then it will return that
* servername
* - Otherwise it returns NULL
*
* During/after the handshake (TLSv1.2 or below resumption occurred):
* - If the session from the original handshake had a servername accepted
* by the server then it will return that servername.
* - Otherwise it returns the servername set via
* SSL_set_tlsext_host_name() (or NULL if it was not called).
*
* During/after the handshake (TLSv1.2 or below resumption did not occur):
* - It will return the servername set via SSL_set_tlsext_host_name()
* (or NULL if it was not called).
*/
if (SSL_in_before(s)) {
if (s->ext.hostname == NULL
&& s->session != NULL
&& s->session->ssl_version != TLS1_3_VERSION)
return s->session->ext.hostname;
} else {
if (!SSL_IS_TLS13(s) && s->hit && s->session->ext.hostname != NULL)
return s->session->ext.hostname;
}
}
return s->ext.hostname;
}
int SSL_get_servername_type(const SSL *s)
{
if (SSL_get_servername(s, TLSEXT_NAMETYPE_host_name) != NULL)
return TLSEXT_NAMETYPE_host_name;
return -1;
}
/*
* SSL_select_next_proto implements the standard protocol selection. It is
* expected that this function is called from the callback set by
* SSL_CTX_set_next_proto_select_cb. The protocol data is assumed to be a
* vector of 8-bit, length prefixed byte strings. The length byte itself is
* not included in the length. A byte string of length 0 is invalid. No byte
* string may be truncated. The current, but experimental algorithm for
* selecting the protocol is: 1) If the server doesn't support NPN then this
* is indicated to the callback. In this case, the client application has to
* abort the connection or have a default application level protocol. 2) If
* the server supports NPN, but advertises an empty list then the client
* selects the first protocol in its list, but indicates via the API that this
* fallback case was enacted. 3) Otherwise, the client finds the first
* protocol in the server's list that it supports and selects this protocol.
* This is because it's assumed that the server has better information about
* which protocol a client should use. 4) If the client doesn't support any
* of the server's advertised protocols, then this is treated the same as
* case 2. It returns either OPENSSL_NPN_NEGOTIATED if a common protocol was
* found, or OPENSSL_NPN_NO_OVERLAP if the fallback case was reached.
*/
int SSL_select_next_proto(unsigned char **out, unsigned char *outlen,
const unsigned char *server,
unsigned int server_len,
const unsigned char *client, unsigned int client_len)
{
unsigned int i, j;
const unsigned char *result;
int status = OPENSSL_NPN_UNSUPPORTED;
/*
* For each protocol in server preference order, see if we support it.
*/
for (i = 0; i < server_len;) {
for (j = 0; j < client_len;) {
if (server[i] == client[j] &&
memcmp(&server[i + 1], &client[j + 1], server[i]) == 0) {
/* We found a match */
result = &server[i];
status = OPENSSL_NPN_NEGOTIATED;
goto found;
}
j += client[j];
j++;
}
i += server[i];
i++;
}
/* There's no overlap between our protocols and the server's list. */
result = client;
status = OPENSSL_NPN_NO_OVERLAP;
found:
*out = (unsigned char *)result + 1;
*outlen = result[0];
return status;
}
#ifndef OPENSSL_NO_NEXTPROTONEG
/*
* SSL_get0_next_proto_negotiated sets *data and *len to point to the
* client's requested protocol for this connection and returns 0. If the
* client didn't request any protocol, then *data is set to NULL. Note that
* the client can request any protocol it chooses. The value returned from
* this function need not be a member of the list of supported protocols
* provided by the callback.
*/
void SSL_get0_next_proto_negotiated(const SSL *s, const unsigned char **data,
unsigned *len)
{
*data = s->ext.npn;
if (*data == NULL) {
*len = 0;
} else {
*len = (unsigned int)s->ext.npn_len;
}
}
/*
* SSL_CTX_set_npn_advertised_cb sets a callback that is called when
* a TLS server needs a list of supported protocols for Next Protocol
* Negotiation. The returned list must be in wire format. The list is
* returned by setting |out| to point to it and |outlen| to its length. This
* memory will not be modified, but one should assume that the SSL* keeps a
* reference to it. The callback should return SSL_TLSEXT_ERR_OK if it
* wishes to advertise. Otherwise, no such extension will be included in the
* ServerHello.
*/
void SSL_CTX_set_npn_advertised_cb(SSL_CTX *ctx,
SSL_CTX_npn_advertised_cb_func cb,
void *arg)
{
ctx->ext.npn_advertised_cb = cb;
ctx->ext.npn_advertised_cb_arg = arg;
}
/*
* SSL_CTX_set_next_proto_select_cb sets a callback that is called when a
* client needs to select a protocol from the server's provided list. |out|
* must be set to point to the selected protocol (which may be within |in|).
* The length of the protocol name must be written into |outlen|. The
* server's advertised protocols are provided in |in| and |inlen|. The
* callback can assume that |in| is syntactically valid. The client must
* select a protocol. It is fatal to the connection if this callback returns
* a value other than SSL_TLSEXT_ERR_OK.
*/
void SSL_CTX_set_npn_select_cb(SSL_CTX *ctx,
SSL_CTX_npn_select_cb_func cb,
void *arg)
{
ctx->ext.npn_select_cb = cb;
ctx->ext.npn_select_cb_arg = arg;
}
#endif
static int alpn_value_ok(const unsigned char *protos, unsigned int protos_len)
{
unsigned int idx;
if (protos_len < 2 || protos == NULL)
return 0;
for (idx = 0; idx < protos_len; idx += protos[idx] + 1) {
if (protos[idx] == 0)
return 0;
}
return idx == protos_len;
}
/*
* SSL_CTX_set_alpn_protos sets the ALPN protocol list on |ctx| to |protos|.
* |protos| must be in wire-format (i.e. a series of non-empty, 8-bit
* length-prefixed strings). Returns 0 on success.
*/
int SSL_CTX_set_alpn_protos(SSL_CTX *ctx, const unsigned char *protos,
unsigned int protos_len)
{
unsigned char *alpn;
if (protos_len == 0 || protos == NULL) {
OPENSSL_free(ctx->ext.alpn);
ctx->ext.alpn = NULL;
ctx->ext.alpn_len = 0;
return 0;
}
/* Not valid per RFC */
if (!alpn_value_ok(protos, protos_len))
return 1;
alpn = OPENSSL_memdup(protos, protos_len);
if (alpn == NULL) {
ERR_raise(ERR_LIB_SSL, ERR_R_MALLOC_FAILURE);
return 1;
}
OPENSSL_free(ctx->ext.alpn);
ctx->ext.alpn = alpn;
ctx->ext.alpn_len = protos_len;
return 0;
}
/*
* SSL_set_alpn_protos sets the ALPN protocol list on |ssl| to |protos|.
* |protos| must be in wire-format (i.e. a series of non-empty, 8-bit
* length-prefixed strings). Returns 0 on success.
*/
int SSL_set_alpn_protos(SSL *ssl, const unsigned char *protos,
unsigned int protos_len)
{
unsigned char *alpn;
if (protos_len == 0 || protos == NULL) {
OPENSSL_free(ssl->ext.alpn);
ssl->ext.alpn = NULL;
ssl->ext.alpn_len = 0;
return 0;
}
/* Not valid per RFC */
if (!alpn_value_ok(protos, protos_len))
return 1;
alpn = OPENSSL_memdup(protos, protos_len);
if (alpn == NULL) {
ERR_raise(ERR_LIB_SSL, ERR_R_MALLOC_FAILURE);
return 1;
}
OPENSSL_free(ssl->ext.alpn);
ssl->ext.alpn = alpn;
ssl->ext.alpn_len = protos_len;
return 0;
}
/*
* SSL_CTX_set_alpn_select_cb sets a callback function on |ctx| that is
* called during ClientHello processing in order to select an ALPN protocol
* from the client's list of offered protocols.
*/
void SSL_CTX_set_alpn_select_cb(SSL_CTX *ctx,
SSL_CTX_alpn_select_cb_func cb,
void *arg)
{
ctx->ext.alpn_select_cb = cb;
ctx->ext.alpn_select_cb_arg = arg;
}
/*
* SSL_get0_alpn_selected gets the selected ALPN protocol (if any) from |ssl|.
* On return it sets |*data| to point to |*len| bytes of protocol name
* (not including the leading length-prefix byte). If the server didn't
* respond with a negotiated protocol then |*len| will be zero.
*/
void SSL_get0_alpn_selected(const SSL *ssl, const unsigned char **data,
unsigned int *len)
{
*data = ssl->s3.alpn_selected;
if (*data == NULL)
*len = 0;
else
*len = (unsigned int)ssl->s3.alpn_selected_len;
}
int SSL_export_keying_material(SSL *s, unsigned char *out, size_t olen,
const char *label, size_t llen,
const unsigned char *context, size_t contextlen,
int use_context)
{
if (s->session == NULL
|| (s->version < TLS1_VERSION && s->version != DTLS1_BAD_VER))
return -1;
return s->method->ssl3_enc->export_keying_material(s, out, olen, label,
llen, context,
contextlen, use_context);
}
int SSL_export_keying_material_early(SSL *s, unsigned char *out, size_t olen,
const char *label, size_t llen,
const unsigned char *context,
size_t contextlen)
{
if (s->version != TLS1_3_VERSION)
return 0;
return tls13_export_keying_material_early(s, out, olen, label, llen,
context, contextlen);
}
static unsigned long ssl_session_hash(const SSL_SESSION *a)
{
const unsigned char *session_id = a->session_id;
unsigned long l;
unsigned char tmp_storage[4];
if (a->session_id_length < sizeof(tmp_storage)) {
memset(tmp_storage, 0, sizeof(tmp_storage));
memcpy(tmp_storage, a->session_id, a->session_id_length);
session_id = tmp_storage;
}
l = (unsigned long)
((unsigned long)session_id[0]) |
((unsigned long)session_id[1] << 8L) |
((unsigned long)session_id[2] << 16L) |
((unsigned long)session_id[3] << 24L);
return l;
}
/*
* NB: If this function (or indeed the hash function which uses a sort of
* coarser function than this one) is changed, ensure
* SSL_CTX_has_matching_session_id() is checked accordingly. It relies on
* being able to construct an SSL_SESSION that will collide with any existing
* session with a matching session ID.
*/
static int ssl_session_cmp(const SSL_SESSION *a, const SSL_SESSION *b)
{
if (a->ssl_version != b->ssl_version)
return 1;
if (a->session_id_length != b->session_id_length)
return 1;
return memcmp(a->session_id, b->session_id, a->session_id_length);
}
/*
* These wrapper functions should remain rather than redeclaring
* SSL_SESSION_hash and SSL_SESSION_cmp for void* types and casting each
* variable. The reason is that the functions aren't static, they're exposed
* via ssl.h.
*/
SSL_CTX *SSL_CTX_new_ex(OSSL_LIB_CTX *libctx, const char *propq,
const SSL_METHOD *meth)
{
SSL_CTX *ret = NULL;
if (meth == NULL) {
ERR_raise(ERR_LIB_SSL, SSL_R_NULL_SSL_METHOD_PASSED);
return NULL;
}
if (!OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS, NULL))
return NULL;
if (SSL_get_ex_data_X509_STORE_CTX_idx() < 0) {
ERR_raise(ERR_LIB_SSL, SSL_R_X509_VERIFICATION_SETUP_PROBLEMS);
goto err;
}
ret = OPENSSL_zalloc(sizeof(*ret));
if (ret == NULL)
goto err;
/* Init the reference counting before any call to SSL_CTX_free */
ret->references = 1;
ret->lock = CRYPTO_THREAD_lock_new();
if (ret->lock == NULL) {
ERR_raise(ERR_LIB_SSL, ERR_R_MALLOC_FAILURE);
OPENSSL_free(ret);
return NULL;
}
#ifdef TSAN_REQUIRES_LOCKING
ret->tsan_lock = CRYPTO_THREAD_lock_new();
if (ret->tsan_lock == NULL) {
ERR_raise(ERR_LIB_SSL, ERR_R_MALLOC_FAILURE);
goto err;
}
#endif
ret->libctx = libctx;
if (propq != NULL) {
ret->propq = OPENSSL_strdup(propq);
if (ret->propq == NULL)
goto err;
}
ret->method = meth;
ret->min_proto_version = 0;
ret->max_proto_version = 0;
ret->mode = SSL_MODE_AUTO_RETRY;
ret->session_cache_mode = SSL_SESS_CACHE_SERVER;
ret->session_cache_size = SSL_SESSION_CACHE_MAX_SIZE_DEFAULT;
/* We take the system default. */
ret->session_timeout = meth->get_timeout();
ret->max_cert_list = SSL_MAX_CERT_LIST_DEFAULT;
ret->verify_mode = SSL_VERIFY_NONE;
if ((ret->cert = ssl_cert_new()) == NULL)
goto err;
ret->sessions = lh_SSL_SESSION_new(ssl_session_hash, ssl_session_cmp);
if (ret->sessions == NULL)
goto err;
ret->cert_store = X509_STORE_new();
if (ret->cert_store == NULL)
goto err;
#ifndef OPENSSL_NO_CT
ret->ctlog_store = CTLOG_STORE_new_ex(libctx, propq);
if (ret->ctlog_store == NULL)
goto err;
#endif
/* initialize cipher/digest methods table */
if (!ssl_load_ciphers(ret))
goto err2;
/* initialise sig algs */
if (!ssl_setup_sig_algs(ret))
goto err2;
if (!ssl_load_groups(ret))
goto err2;
if (!SSL_CTX_set_ciphersuites(ret, OSSL_default_ciphersuites()))
goto err;
if (!ssl_create_cipher_list(ret,
ret->tls13_ciphersuites,
&ret->cipher_list, &ret->cipher_list_by_id,
OSSL_default_cipher_list(), ret->cert)
|| sk_SSL_CIPHER_num(ret->cipher_list) <= 0) {
ERR_raise(ERR_LIB_SSL, SSL_R_LIBRARY_HAS_NO_CIPHERS);
goto err2;
}
ret->param = X509_VERIFY_PARAM_new();
if (ret->param == NULL)
goto err;
/*
* If these aren't available from the provider we'll get NULL returns.
* That's fine but will cause errors later if SSLv3 is negotiated
*/
ret->md5 = ssl_evp_md_fetch(libctx, NID_md5, propq);
ret->sha1 = ssl_evp_md_fetch(libctx, NID_sha1, propq);
if ((ret->ca_names = sk_X509_NAME_new_null()) == NULL)
goto err;
if ((ret->client_ca_names = sk_X509_NAME_new_null()) == NULL)
goto err;
if (!CRYPTO_new_ex_data(CRYPTO_EX_INDEX_SSL_CTX, ret, &ret->ex_data))
goto err;
if ((ret->ext.secure = OPENSSL_secure_zalloc(sizeof(*ret->ext.secure))) == NULL)
goto err;
/* No compression for DTLS */
if (!(meth->ssl3_enc->enc_flags & SSL_ENC_FLAG_DTLS))
ret->comp_methods = SSL_COMP_get_compression_methods();
ret->max_send_fragment = SSL3_RT_MAX_PLAIN_LENGTH;
ret->split_send_fragment = SSL3_RT_MAX_PLAIN_LENGTH;
/* Setup RFC5077 ticket keys */
if ((RAND_bytes_ex(libctx, ret->ext.tick_key_name,
sizeof(ret->ext.tick_key_name), 0) <= 0)
|| (RAND_priv_bytes_ex(libctx, ret->ext.secure->tick_hmac_key,
sizeof(ret->ext.secure->tick_hmac_key), 0) <= 0)
|| (RAND_priv_bytes_ex(libctx, ret->ext.secure->tick_aes_key,
sizeof(ret->ext.secure->tick_aes_key), 0) <= 0))
ret->options |= SSL_OP_NO_TICKET;
if (RAND_priv_bytes_ex(libctx, ret->ext.cookie_hmac_key,
sizeof(ret->ext.cookie_hmac_key), 0) <= 0)
goto err;
#ifndef OPENSSL_NO_SRP
if (!ssl_ctx_srp_ctx_init_intern(ret))
goto err;
#endif
#ifndef OPENSSL_NO_ENGINE
# ifdef OPENSSL_SSL_CLIENT_ENGINE_AUTO
# define eng_strx(x) #x
# define eng_str(x) eng_strx(x)
/* Use specific client engine automatically... ignore errors */
{
ENGINE *eng;
eng = ENGINE_by_id(eng_str(OPENSSL_SSL_CLIENT_ENGINE_AUTO));
if (!eng) {
ERR_clear_error();
ENGINE_load_builtin_engines();
eng = ENGINE_by_id(eng_str(OPENSSL_SSL_CLIENT_ENGINE_AUTO));
}
if (!eng || !SSL_CTX_set_client_cert_engine(ret, eng))
ERR_clear_error();
}
# endif
#endif
/*
* Disable compression by default to prevent CRIME. Applications can
* re-enable compression by configuring
* SSL_CTX_clear_options(ctx, SSL_OP_NO_COMPRESSION);
* or by using the SSL_CONF library. Similarly we also enable TLSv1.3
* middlebox compatibility by default. This may be disabled by default in
* a later OpenSSL version.
*/
ret->options |= SSL_OP_NO_COMPRESSION | SSL_OP_ENABLE_MIDDLEBOX_COMPAT;
ret->ext.status_type = TLSEXT_STATUSTYPE_nothing;
/*
* We cannot usefully set a default max_early_data here (which gets
* propagated in SSL_new(), for the following reason: setting the
* SSL field causes tls_construct_stoc_early_data() to tell the
* client that early data will be accepted when constructing a TLS 1.3
* session ticket, and the client will accordingly send us early data
* when using that ticket (if the client has early data to send).
* However, in order for the early data to actually be consumed by
* the application, the application must also have calls to
* SSL_read_early_data(); otherwise we'll just skip past the early data
* and ignore it. So, since the application must add calls to
* SSL_read_early_data(), we also require them to add
* calls to SSL_CTX_set_max_early_data() in order to use early data,
* eliminating the bandwidth-wasting early data in the case described
* above.
*/
ret->max_early_data = 0;
/*
* Default recv_max_early_data is a fully loaded single record. Could be
* split across multiple records in practice. We set this differently to
* max_early_data so that, in the default case, we do not advertise any
* support for early_data, but if a client were to send us some (e.g.
* because of an old, stale ticket) then we will tolerate it and skip over
* it.
*/
ret->recv_max_early_data = SSL3_RT_MAX_PLAIN_LENGTH;
/* By default we send two session tickets automatically in TLSv1.3 */
ret->num_tickets = 2;
ssl_ctx_system_config(ret);
return ret;
err:
ERR_raise(ERR_LIB_SSL, ERR_R_MALLOC_FAILURE);
err2:
SSL_CTX_free(ret);
return NULL;
}
SSL_CTX *SSL_CTX_new(const SSL_METHOD *meth)
{
return SSL_CTX_new_ex(NULL, NULL, meth);
}
int SSL_CTX_up_ref(SSL_CTX *ctx)
{
int i;
if (CRYPTO_UP_REF(&ctx->references, &i, ctx->lock) <= 0)
return 0;
REF_PRINT_COUNT("SSL_CTX", ctx);
REF_ASSERT_ISNT(i < 2);
return ((i > 1) ? 1 : 0);
}
void SSL_CTX_free(SSL_CTX *a)
{
int i;
size_t j;
if (a == NULL)
return;
CRYPTO_DOWN_REF(&a->references, &i, a->lock);
REF_PRINT_COUNT("SSL_CTX", a);
if (i > 0)
return;
REF_ASSERT_ISNT(i < 0);
X509_VERIFY_PARAM_free(a->param);
dane_ctx_final(&a->dane);
/*
* Free internal session cache. However: the remove_cb() may reference
* the ex_data of SSL_CTX, thus the ex_data store can only be removed
* after the sessions were flushed.
* As the ex_data handling routines might also touch the session cache,
* the most secure solution seems to be: empty (flush) the cache, then
* free ex_data, then finally free the cache.
* (See ticket [openssl.org #212].)
*/
if (a->sessions != NULL)
SSL_CTX_flush_sessions(a, 0);
CRYPTO_free_ex_data(CRYPTO_EX_INDEX_SSL_CTX, a, &a->ex_data);
lh_SSL_SESSION_free(a->sessions);
X509_STORE_free(a->cert_store);
#ifndef OPENSSL_NO_CT
CTLOG_STORE_free(a->ctlog_store);
#endif
sk_SSL_CIPHER_free(a->cipher_list);
sk_SSL_CIPHER_free(a->cipher_list_by_id);
sk_SSL_CIPHER_free(a->tls13_ciphersuites);
ssl_cert_free(a->cert);
sk_X509_NAME_pop_free(a->ca_names, X509_NAME_free);
sk_X509_NAME_pop_free(a->client_ca_names, X509_NAME_free);
sk_X509_pop_free(a->extra_certs, X509_free);
a->comp_methods = NULL;
#ifndef OPENSSL_NO_SRTP
sk_SRTP_PROTECTION_PROFILE_free(a->srtp_profiles);
#endif
#ifndef OPENSSL_NO_SRP
ssl_ctx_srp_ctx_free_intern(a);
#endif
#ifndef OPENSSL_NO_ENGINE
tls_engine_finish(a->client_cert_engine);
#endif
OPENSSL_free(a->ext.ecpointformats);
OPENSSL_free(a->ext.supportedgroups);
OPENSSL_free(a->ext.supported_groups_default);
OPENSSL_free(a->ext.alpn);
OPENSSL_secure_free(a->ext.secure);
ssl_evp_md_free(a->md5);
ssl_evp_md_free(a->sha1);
for (j = 0; j < SSL_ENC_NUM_IDX; j++)
ssl_evp_cipher_free(a->ssl_cipher_methods[j]);
for (j = 0; j < SSL_MD_NUM_IDX; j++)
ssl_evp_md_free(a->ssl_digest_methods[j]);
for (j = 0; j < a->group_list_len; j++) {
OPENSSL_free(a->group_list[j].tlsname);
OPENSSL_free(a->group_list[j].realname);
OPENSSL_free(a->group_list[j].algorithm);
}
OPENSSL_free(a->group_list);
OPENSSL_free(a->sigalg_lookup_cache);
CRYPTO_THREAD_lock_free(a->lock);
#ifdef TSAN_REQUIRES_LOCKING
CRYPTO_THREAD_lock_free(a->tsan_lock);
#endif
OPENSSL_free(a->propq);
OPENSSL_free(a);
}
void SSL_CTX_set_default_passwd_cb(SSL_CTX *ctx, pem_password_cb *cb)
{
ctx->default_passwd_callback = cb;
}
void SSL_CTX_set_default_passwd_cb_userdata(SSL_CTX *ctx, void *u)
{
ctx->default_passwd_callback_userdata = u;
}
pem_password_cb *SSL_CTX_get_default_passwd_cb(SSL_CTX *ctx)
{
return ctx->default_passwd_callback;
}
void *SSL_CTX_get_default_passwd_cb_userdata(SSL_CTX *ctx)
{
return ctx->default_passwd_callback_userdata;
}
void SSL_set_default_passwd_cb(SSL *s, pem_password_cb *cb)
{
s->default_passwd_callback = cb;
}
void SSL_set_default_passwd_cb_userdata(SSL *s, void *u)
{
s->default_passwd_callback_userdata = u;
}
pem_password_cb *SSL_get_default_passwd_cb(SSL *s)
{
return s->default_passwd_callback;
}
void *SSL_get_default_passwd_cb_userdata(SSL *s)
{
return s->default_passwd_callback_userdata;
}
void SSL_CTX_set_cert_verify_callback(SSL_CTX *ctx,
int (*cb) (X509_STORE_CTX *, void *),
void *arg)
{
ctx->app_verify_callback = cb;
ctx->app_verify_arg = arg;
}
void SSL_CTX_set_verify(SSL_CTX *ctx, int mode,
int (*cb) (int, X509_STORE_CTX *))
{
ctx->verify_mode = mode;
ctx->default_verify_callback = cb;
}
void SSL_CTX_set_verify_depth(SSL_CTX *ctx, int depth)
{
X509_VERIFY_PARAM_set_depth(ctx->param, depth);
}
void SSL_CTX_set_cert_cb(SSL_CTX *c, int (*cb) (SSL *ssl, void *arg), void *arg)
{
ssl_cert_set_cert_cb(c->cert, cb, arg);
}
void SSL_set_cert_cb(SSL *s, int (*cb) (SSL *ssl, void *arg), void *arg)
{
ssl_cert_set_cert_cb(s->cert, cb, arg);
}
void ssl_set_masks(SSL *s)
{
CERT *c = s->cert;
uint32_t *pvalid = s->s3.tmp.valid_flags;
int rsa_enc, rsa_sign, dh_tmp, dsa_sign;
unsigned long mask_k, mask_a;
int have_ecc_cert, ecdsa_ok;
if (c == NULL)
return;
dh_tmp = (c->dh_tmp != NULL
|| c->dh_tmp_cb != NULL
|| c->dh_tmp_auto);
rsa_enc = pvalid[SSL_PKEY_RSA] & CERT_PKEY_VALID;
rsa_sign = pvalid[SSL_PKEY_RSA] & CERT_PKEY_VALID;
dsa_sign = pvalid[SSL_PKEY_DSA_SIGN] & CERT_PKEY_VALID;
have_ecc_cert = pvalid[SSL_PKEY_ECC] & CERT_PKEY_VALID;
mask_k = 0;
mask_a = 0;
OSSL_TRACE4(TLS_CIPHER, "dh_tmp=%d rsa_enc=%d rsa_sign=%d dsa_sign=%d\n",
dh_tmp, rsa_enc, rsa_sign, dsa_sign);
#ifndef OPENSSL_NO_GOST
if (ssl_has_cert(s, SSL_PKEY_GOST12_512)) {
mask_k |= SSL_kGOST | SSL_kGOST18;
mask_a |= SSL_aGOST12;
}
if (ssl_has_cert(s, SSL_PKEY_GOST12_256)) {
mask_k |= SSL_kGOST | SSL_kGOST18;
mask_a |= SSL_aGOST12;
}
if (ssl_has_cert(s, SSL_PKEY_GOST01)) {
mask_k |= SSL_kGOST;
mask_a |= SSL_aGOST01;
}
#endif
if (rsa_enc)
mask_k |= SSL_kRSA;
if (dh_tmp)
mask_k |= SSL_kDHE;
/*
* If we only have an RSA-PSS certificate allow RSA authentication
* if TLS 1.2 and peer supports it.
*/
if (rsa_enc || rsa_sign || (ssl_has_cert(s, SSL_PKEY_RSA_PSS_SIGN)
&& pvalid[SSL_PKEY_RSA_PSS_SIGN] & CERT_PKEY_EXPLICIT_SIGN
&& TLS1_get_version(s) == TLS1_2_VERSION))
mask_a |= SSL_aRSA;
if (dsa_sign) {
mask_a |= SSL_aDSS;
}
mask_a |= SSL_aNULL;
/*
* An ECC certificate may be usable for ECDH and/or ECDSA cipher suites
* depending on the key usage extension.
*/
if (have_ecc_cert) {
uint32_t ex_kusage;
ex_kusage = X509_get_key_usage(c->pkeys[SSL_PKEY_ECC].x509);
ecdsa_ok = ex_kusage & X509v3_KU_DIGITAL_SIGNATURE;
if (!(pvalid[SSL_PKEY_ECC] & CERT_PKEY_SIGN))
ecdsa_ok = 0;
if (ecdsa_ok)
mask_a |= SSL_aECDSA;
}
/* Allow Ed25519 for TLS 1.2 if peer supports it */
if (!(mask_a & SSL_aECDSA) && ssl_has_cert(s, SSL_PKEY_ED25519)
&& pvalid[SSL_PKEY_ED25519] & CERT_PKEY_EXPLICIT_SIGN
&& TLS1_get_version(s) == TLS1_2_VERSION)
mask_a |= SSL_aECDSA;
/* Allow Ed448 for TLS 1.2 if peer supports it */
if (!(mask_a & SSL_aECDSA) && ssl_has_cert(s, SSL_PKEY_ED448)
&& pvalid[SSL_PKEY_ED448] & CERT_PKEY_EXPLICIT_SIGN
&& TLS1_get_version(s) == TLS1_2_VERSION)
mask_a |= SSL_aECDSA;
mask_k |= SSL_kECDHE;
#ifndef OPENSSL_NO_PSK
mask_k |= SSL_kPSK;
mask_a |= SSL_aPSK;
if (mask_k & SSL_kRSA)
mask_k |= SSL_kRSAPSK;
if (mask_k & SSL_kDHE)
mask_k |= SSL_kDHEPSK;
if (mask_k & SSL_kECDHE)
mask_k |= SSL_kECDHEPSK;
#endif
s->s3.tmp.mask_k = mask_k;
s->s3.tmp.mask_a = mask_a;
}
int ssl_check_srvr_ecc_cert_and_alg(X509 *x, SSL *s)
{
if (s->s3.tmp.new_cipher->algorithm_auth & SSL_aECDSA) {
/* key usage, if present, must allow signing */
if (!(X509_get_key_usage(x) & X509v3_KU_DIGITAL_SIGNATURE)) {
ERR_raise(ERR_LIB_SSL, SSL_R_ECC_CERT_NOT_FOR_SIGNING);
return 0;
}
}
return 1; /* all checks are ok */
}
int ssl_get_server_cert_serverinfo(SSL *s, const unsigned char **serverinfo,
size_t *serverinfo_length)
{
CERT_PKEY *cpk = s->s3.tmp.cert;
*serverinfo_length = 0;
if (cpk == NULL || cpk->serverinfo == NULL)
return 0;
*serverinfo = cpk->serverinfo;
*serverinfo_length = cpk->serverinfo_length;
return 1;
}
void ssl_update_cache(SSL *s, int mode)
{
int i;
/*
* If the session_id_length is 0, we are not supposed to cache it, and it
- * would be rather hard to do anyway :-)
+ * would be rather hard to do anyway :-). Also if the session has already
+ * been marked as not_resumable we should not cache it for later reuse.
*/
- if (s->session->session_id_length == 0)
+ if (s->session->session_id_length == 0 || s->session->not_resumable)
return;
/*
* If sid_ctx_length is 0 there is no specific application context
* associated with this session, so when we try to resume it and
* SSL_VERIFY_PEER is requested to verify the client identity, we have no
* indication that this is actually a session for the proper application
* context, and the *handshake* will fail, not just the resumption attempt.
* Do not cache (on the server) these sessions that are not resumable
* (clients can set SSL_VERIFY_PEER without needing a sid_ctx set).
*/
if (s->server && s->session->sid_ctx_length == 0
&& (s->verify_mode & SSL_VERIFY_PEER) != 0)
return;
i = s->session_ctx->session_cache_mode;
if ((i & mode) != 0
&& (!s->hit || SSL_IS_TLS13(s))) {
/*
* Add the session to the internal cache. In server side TLSv1.3 we
* normally don't do this because by default it's a full stateless ticket
* with only a dummy session id so there is no reason to cache it,
* unless:
* - we are doing early_data, in which case we cache so that we can
* detect replays
* - the application has set a remove_session_cb so needs to know about
* session timeout events
* - SSL_OP_NO_TICKET is set in which case it is a stateful ticket
*/
if ((i & SSL_SESS_CACHE_NO_INTERNAL_STORE) == 0
&& (!SSL_IS_TLS13(s)
|| !s->server
|| (s->max_early_data > 0
&& (s->options & SSL_OP_NO_ANTI_REPLAY) == 0)
|| s->session_ctx->remove_session_cb != NULL
|| (s->options & SSL_OP_NO_TICKET) != 0))
SSL_CTX_add_session(s->session_ctx, s->session);
/*
* Add the session to the external cache. We do this even in server side
* TLSv1.3 without early data because some applications just want to
* know about the creation of a session and aren't doing a full cache.
*/
if (s->session_ctx->new_session_cb != NULL) {
SSL_SESSION_up_ref(s->session);
if (!s->session_ctx->new_session_cb(s, s->session))
SSL_SESSION_free(s->session);
}
}
/* auto flush every 255 connections */
if ((!(i & SSL_SESS_CACHE_NO_AUTO_CLEAR)) && ((i & mode) == mode)) {
TSAN_QUALIFIER int *stat;
if (mode & SSL_SESS_CACHE_CLIENT)
stat = &s->session_ctx->stats.sess_connect_good;
else
stat = &s->session_ctx->stats.sess_accept_good;
if ((ssl_tsan_load(s->session_ctx, stat) & 0xff) == 0xff)
SSL_CTX_flush_sessions(s->session_ctx, (unsigned long)time(NULL));
}
}
const SSL_METHOD *SSL_CTX_get_ssl_method(const SSL_CTX *ctx)
{
return ctx->method;
}
const SSL_METHOD *SSL_get_ssl_method(const SSL *s)
{
return s->method;
}
int SSL_set_ssl_method(SSL *s, const SSL_METHOD *meth)
{
int ret = 1;
if (s->method != meth) {
const SSL_METHOD *sm = s->method;
int (*hf) (SSL *) = s->handshake_func;
if (sm->version == meth->version)
s->method = meth;
else {
sm->ssl_free(s);
s->method = meth;
ret = s->method->ssl_new(s);
}
if (hf == sm->ssl_connect)
s->handshake_func = meth->ssl_connect;
else if (hf == sm->ssl_accept)
s->handshake_func = meth->ssl_accept;
}
return ret;
}
int SSL_get_error(const SSL *s, int i)
{
int reason;
unsigned long l;
BIO *bio;
if (i > 0)
return SSL_ERROR_NONE;
/*
* Make things return SSL_ERROR_SYSCALL when doing SSL_do_handshake etc,
* where we do encode the error
*/
if ((l = ERR_peek_error()) != 0) {
if (ERR_GET_LIB(l) == ERR_LIB_SYS)
return SSL_ERROR_SYSCALL;
else
return SSL_ERROR_SSL;
}
if (SSL_want_read(s)) {
bio = SSL_get_rbio(s);
if (BIO_should_read(bio))
return SSL_ERROR_WANT_READ;
else if (BIO_should_write(bio))
/*
* This one doesn't make too much sense ... We never try to write
* to the rbio, and an application program where rbio and wbio
* are separate couldn't even know what it should wait for.
* However if we ever set s->rwstate incorrectly (so that we have
* SSL_want_read(s) instead of SSL_want_write(s)) and rbio and
* wbio *are* the same, this test works around that bug; so it
* might be safer to keep it.
*/
return SSL_ERROR_WANT_WRITE;
else if (BIO_should_io_special(bio)) {
reason = BIO_get_retry_reason(bio);
if (reason == BIO_RR_CONNECT)
return SSL_ERROR_WANT_CONNECT;
else if (reason == BIO_RR_ACCEPT)
return SSL_ERROR_WANT_ACCEPT;
else
return SSL_ERROR_SYSCALL; /* unknown */
}
}
if (SSL_want_write(s)) {
/* Access wbio directly - in order to use the buffered bio if present */
bio = s->wbio;
if (BIO_should_write(bio))
return SSL_ERROR_WANT_WRITE;
else if (BIO_should_read(bio))
/*
* See above (SSL_want_read(s) with BIO_should_write(bio))
*/
return SSL_ERROR_WANT_READ;
else if (BIO_should_io_special(bio)) {
reason = BIO_get_retry_reason(bio);
if (reason == BIO_RR_CONNECT)
return SSL_ERROR_WANT_CONNECT;
else if (reason == BIO_RR_ACCEPT)
return SSL_ERROR_WANT_ACCEPT;
else
return SSL_ERROR_SYSCALL;
}
}
if (SSL_want_x509_lookup(s))
return SSL_ERROR_WANT_X509_LOOKUP;
if (SSL_want_retry_verify(s))
return SSL_ERROR_WANT_RETRY_VERIFY;
if (SSL_want_async(s))
return SSL_ERROR_WANT_ASYNC;
if (SSL_want_async_job(s))
return SSL_ERROR_WANT_ASYNC_JOB;
if (SSL_want_client_hello_cb(s))
return SSL_ERROR_WANT_CLIENT_HELLO_CB;
if ((s->shutdown & SSL_RECEIVED_SHUTDOWN) &&
(s->s3.warn_alert == SSL_AD_CLOSE_NOTIFY))
return SSL_ERROR_ZERO_RETURN;
return SSL_ERROR_SYSCALL;
}
static int ssl_do_handshake_intern(void *vargs)
{
struct ssl_async_args *args;
SSL *s;
args = (struct ssl_async_args *)vargs;
s = args->s;
return s->handshake_func(s);
}
int SSL_do_handshake(SSL *s)
{
int ret = 1;
if (s->handshake_func == NULL) {
ERR_raise(ERR_LIB_SSL, SSL_R_CONNECTION_TYPE_NOT_SET);
return -1;
}
ossl_statem_check_finish_init(s, -1);
s->method->ssl_renegotiate_check(s, 0);
if (SSL_in_init(s) || SSL_in_before(s)) {
if ((s->mode & SSL_MODE_ASYNC) && ASYNC_get_current_job() == NULL) {
struct ssl_async_args args;
memset(&args, 0, sizeof(args));
args.s = s;
ret = ssl_start_async_job(s, &args, ssl_do_handshake_intern);
} else {
ret = s->handshake_func(s);
}
}
return ret;
}
void SSL_set_accept_state(SSL *s)
{
s->server = 1;
s->shutdown = 0;
ossl_statem_clear(s);
s->handshake_func = s->method->ssl_accept;
clear_ciphers(s);
}
void SSL_set_connect_state(SSL *s)
{
s->server = 0;
s->shutdown = 0;
ossl_statem_clear(s);
s->handshake_func = s->method->ssl_connect;
clear_ciphers(s);
}
int ssl_undefined_function(SSL *s)
{
ERR_raise(ERR_LIB_SSL, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
return 0;
}
int ssl_undefined_void_function(void)
{
ERR_raise(ERR_LIB_SSL, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
return 0;
}
int ssl_undefined_const_function(const SSL *s)
{
return 0;
}
const SSL_METHOD *ssl_bad_method(int ver)
{
ERR_raise(ERR_LIB_SSL, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
return NULL;
}
const char *ssl_protocol_to_string(int version)
{
switch(version)
{
case TLS1_3_VERSION:
return "TLSv1.3";
case TLS1_2_VERSION:
return "TLSv1.2";
case TLS1_1_VERSION:
return "TLSv1.1";
case TLS1_VERSION:
return "TLSv1";
case SSL3_VERSION:
return "SSLv3";
case DTLS1_BAD_VER:
return "DTLSv0.9";
case DTLS1_VERSION:
return "DTLSv1";
case DTLS1_2_VERSION:
return "DTLSv1.2";
default:
return "unknown";
}
}
const char *SSL_get_version(const SSL *s)
{
return ssl_protocol_to_string(s->version);
}
static int dup_ca_names(STACK_OF(X509_NAME) **dst, STACK_OF(X509_NAME) *src)
{
STACK_OF(X509_NAME) *sk;
X509_NAME *xn;
int i;
if (src == NULL) {
*dst = NULL;
return 1;
}
if ((sk = sk_X509_NAME_new_null()) == NULL)
return 0;
for (i = 0; i < sk_X509_NAME_num(src); i++) {
xn = X509_NAME_dup(sk_X509_NAME_value(src, i));
if (xn == NULL) {
sk_X509_NAME_pop_free(sk, X509_NAME_free);
return 0;
}
if (sk_X509_NAME_insert(sk, xn, i) == 0) {
X509_NAME_free(xn);
sk_X509_NAME_pop_free(sk, X509_NAME_free);
return 0;
}
}
*dst = sk;
return 1;
}
SSL *SSL_dup(SSL *s)
{
SSL *ret;
int i;
/* If we're not quiescent, just up_ref! */
if (!SSL_in_init(s) || !SSL_in_before(s)) {
CRYPTO_UP_REF(&s->references, &i, s->lock);
return s;
}
/*
* Otherwise, copy configuration state, and session if set.
*/
if ((ret = SSL_new(SSL_get_SSL_CTX(s))) == NULL)
return NULL;
if (s->session != NULL) {
/*
* Arranges to share the same session via up_ref. This "copies"
* session-id, SSL_METHOD, sid_ctx, and 'cert'
*/
if (!SSL_copy_session_id(ret, s))
goto err;
} else {
/*
* No session has been established yet, so we have to expect that
* s->cert or ret->cert will be changed later -- they should not both
* point to the same object, and thus we can't use
* SSL_copy_session_id.
*/
if (!SSL_set_ssl_method(ret, s->method))
goto err;
if (s->cert != NULL) {
ssl_cert_free(ret->cert);
ret->cert = ssl_cert_dup(s->cert);
if (ret->cert == NULL)
goto err;
}
if (!SSL_set_session_id_context(ret, s->sid_ctx,
(int)s->sid_ctx_length))
goto err;
}
if (!ssl_dane_dup(ret, s))
goto err;
ret->version = s->version;
ret->options = s->options;
ret->min_proto_version = s->min_proto_version;
ret->max_proto_version = s->max_proto_version;
ret->mode = s->mode;
SSL_set_max_cert_list(ret, SSL_get_max_cert_list(s));
SSL_set_read_ahead(ret, SSL_get_read_ahead(s));
ret->msg_callback = s->msg_callback;
ret->msg_callback_arg = s->msg_callback_arg;
SSL_set_verify(ret, SSL_get_verify_mode(s), SSL_get_verify_callback(s));
SSL_set_verify_depth(ret, SSL_get_verify_depth(s));
ret->generate_session_id = s->generate_session_id;
SSL_set_info_callback(ret, SSL_get_info_callback(s));
/* copy app data, a little dangerous perhaps */
if (!CRYPTO_dup_ex_data(CRYPTO_EX_INDEX_SSL, &ret->ex_data, &s->ex_data))
goto err;
ret->server = s->server;
if (s->handshake_func) {
if (s->server)
SSL_set_accept_state(ret);
else
SSL_set_connect_state(ret);
}
ret->shutdown = s->shutdown;
ret->hit = s->hit;
ret->default_passwd_callback = s->default_passwd_callback;
ret->default_passwd_callback_userdata = s->default_passwd_callback_userdata;
X509_VERIFY_PARAM_inherit(ret->param, s->param);
/* dup the cipher_list and cipher_list_by_id stacks */
if (s->cipher_list != NULL) {
if ((ret->cipher_list = sk_SSL_CIPHER_dup(s->cipher_list)) == NULL)
goto err;
}
if (s->cipher_list_by_id != NULL)
if ((ret->cipher_list_by_id = sk_SSL_CIPHER_dup(s->cipher_list_by_id))
== NULL)
goto err;
/* Dup the client_CA list */
if (!dup_ca_names(&ret->ca_names, s->ca_names)
|| !dup_ca_names(&ret->client_ca_names, s->client_ca_names))
goto err;
return ret;
err:
SSL_free(ret);
return NULL;
}
void ssl_clear_cipher_ctx(SSL *s)
{
if (s->enc_read_ctx != NULL) {
EVP_CIPHER_CTX_free(s->enc_read_ctx);
s->enc_read_ctx = NULL;
}
if (s->enc_write_ctx != NULL) {
EVP_CIPHER_CTX_free(s->enc_write_ctx);
s->enc_write_ctx = NULL;
}
#ifndef OPENSSL_NO_COMP
COMP_CTX_free(s->expand);
s->expand = NULL;
COMP_CTX_free(s->compress);
s->compress = NULL;
#endif
}
X509 *SSL_get_certificate(const SSL *s)
{
if (s->cert != NULL)
return s->cert->key->x509;
else
return NULL;
}
EVP_PKEY *SSL_get_privatekey(const SSL *s)
{
if (s->cert != NULL)
return s->cert->key->privatekey;
else
return NULL;
}
X509 *SSL_CTX_get0_certificate(const SSL_CTX *ctx)
{
if (ctx->cert != NULL)
return ctx->cert->key->x509;
else
return NULL;
}
EVP_PKEY *SSL_CTX_get0_privatekey(const SSL_CTX *ctx)
{
if (ctx->cert != NULL)
return ctx->cert->key->privatekey;
else
return NULL;
}
const SSL_CIPHER *SSL_get_current_cipher(const SSL *s)
{
if ((s->session != NULL) && (s->session->cipher != NULL))
return s->session->cipher;
return NULL;
}
const SSL_CIPHER *SSL_get_pending_cipher(const SSL *s)
{
return s->s3.tmp.new_cipher;
}
const COMP_METHOD *SSL_get_current_compression(const SSL *s)
{
#ifndef OPENSSL_NO_COMP
return s->compress ? COMP_CTX_get_method(s->compress) : NULL;
#else
return NULL;
#endif
}
const COMP_METHOD *SSL_get_current_expansion(const SSL *s)
{
#ifndef OPENSSL_NO_COMP
return s->expand ? COMP_CTX_get_method(s->expand) : NULL;
#else
return NULL;
#endif
}
int ssl_init_wbio_buffer(SSL *s)
{
BIO *bbio;
if (s->bbio != NULL) {
/* Already buffered. */
return 1;
}
bbio = BIO_new(BIO_f_buffer());
if (bbio == NULL || BIO_set_read_buffer_size(bbio, 1) <= 0) {
BIO_free(bbio);
ERR_raise(ERR_LIB_SSL, ERR_R_BUF_LIB);
return 0;
}
s->bbio = bbio;
s->wbio = BIO_push(bbio, s->wbio);
return 1;
}
int ssl_free_wbio_buffer(SSL *s)
{
/* callers ensure s is never null */
if (s->bbio == NULL)
return 1;
s->wbio = BIO_pop(s->wbio);
BIO_free(s->bbio);
s->bbio = NULL;
return 1;
}
void SSL_CTX_set_quiet_shutdown(SSL_CTX *ctx, int mode)
{
ctx->quiet_shutdown = mode;
}
int SSL_CTX_get_quiet_shutdown(const SSL_CTX *ctx)
{
return ctx->quiet_shutdown;
}
void SSL_set_quiet_shutdown(SSL *s, int mode)
{
s->quiet_shutdown = mode;
}
int SSL_get_quiet_shutdown(const SSL *s)
{
return s->quiet_shutdown;
}
void SSL_set_shutdown(SSL *s, int mode)
{
s->shutdown = mode;
}
int SSL_get_shutdown(const SSL *s)
{
return s->shutdown;
}
int SSL_version(const SSL *s)
{
return s->version;
}
int SSL_client_version(const SSL *s)
{
return s->client_version;
}
SSL_CTX *SSL_get_SSL_CTX(const SSL *ssl)
{
return ssl->ctx;
}
SSL_CTX *SSL_set_SSL_CTX(SSL *ssl, SSL_CTX *ctx)
{
CERT *new_cert;
if (ssl->ctx == ctx)
return ssl->ctx;
if (ctx == NULL)
ctx = ssl->session_ctx;
new_cert = ssl_cert_dup(ctx->cert);
if (new_cert == NULL) {
return NULL;
}
if (!custom_exts_copy_flags(&new_cert->custext, &ssl->cert->custext)) {
ssl_cert_free(new_cert);
return NULL;
}
ssl_cert_free(ssl->cert);
ssl->cert = new_cert;
/*
* Program invariant: |sid_ctx| has fixed size (SSL_MAX_SID_CTX_LENGTH),
* so setter APIs must prevent invalid lengths from entering the system.
*/
if (!ossl_assert(ssl->sid_ctx_length <= sizeof(ssl->sid_ctx)))
return NULL;
/*
* If the session ID context matches that of the parent SSL_CTX,
* inherit it from the new SSL_CTX as well. If however the context does
* not match (i.e., it was set per-ssl with SSL_set_session_id_context),
* leave it unchanged.
*/
if ((ssl->ctx != NULL) &&
(ssl->sid_ctx_length == ssl->ctx->sid_ctx_length) &&
(memcmp(ssl->sid_ctx, ssl->ctx->sid_ctx, ssl->sid_ctx_length) == 0)) {
ssl->sid_ctx_length = ctx->sid_ctx_length;
memcpy(&ssl->sid_ctx, &ctx->sid_ctx, sizeof(ssl->sid_ctx));
}
SSL_CTX_up_ref(ctx);
SSL_CTX_free(ssl->ctx); /* decrement reference count */
ssl->ctx = ctx;
return ssl->ctx;
}
int SSL_CTX_set_default_verify_paths(SSL_CTX *ctx)
{
return X509_STORE_set_default_paths_ex(ctx->cert_store, ctx->libctx,
ctx->propq);
}
int SSL_CTX_set_default_verify_dir(SSL_CTX *ctx)
{
X509_LOOKUP *lookup;
lookup = X509_STORE_add_lookup(ctx->cert_store, X509_LOOKUP_hash_dir());
if (lookup == NULL)
return 0;
/* We ignore errors, in case the directory doesn't exist */
ERR_set_mark();
X509_LOOKUP_add_dir(lookup, NULL, X509_FILETYPE_DEFAULT);
ERR_pop_to_mark();
return 1;
}
int SSL_CTX_set_default_verify_file(SSL_CTX *ctx)
{
X509_LOOKUP *lookup;
lookup = X509_STORE_add_lookup(ctx->cert_store, X509_LOOKUP_file());
if (lookup == NULL)
return 0;
/* We ignore errors, in case the file doesn't exist */
ERR_set_mark();
X509_LOOKUP_load_file_ex(lookup, NULL, X509_FILETYPE_DEFAULT, ctx->libctx,
ctx->propq);
ERR_pop_to_mark();
return 1;
}
int SSL_CTX_set_default_verify_store(SSL_CTX *ctx)
{
X509_LOOKUP *lookup;
lookup = X509_STORE_add_lookup(ctx->cert_store, X509_LOOKUP_store());
if (lookup == NULL)
return 0;
/* We ignore errors, in case the directory doesn't exist */
ERR_set_mark();
X509_LOOKUP_add_store_ex(lookup, NULL, ctx->libctx, ctx->propq);
ERR_pop_to_mark();
return 1;
}
int SSL_CTX_load_verify_file(SSL_CTX *ctx, const char *CAfile)
{
return X509_STORE_load_file_ex(ctx->cert_store, CAfile, ctx->libctx,
ctx->propq);
}
int SSL_CTX_load_verify_dir(SSL_CTX *ctx, const char *CApath)
{
return X509_STORE_load_path(ctx->cert_store, CApath);
}
int SSL_CTX_load_verify_store(SSL_CTX *ctx, const char *CAstore)
{
return X509_STORE_load_store_ex(ctx->cert_store, CAstore, ctx->libctx,
ctx->propq);
}
int SSL_CTX_load_verify_locations(SSL_CTX *ctx, const char *CAfile,
const char *CApath)
{
if (CAfile == NULL && CApath == NULL)
return 0;
if (CAfile != NULL && !SSL_CTX_load_verify_file(ctx, CAfile))
return 0;
if (CApath != NULL && !SSL_CTX_load_verify_dir(ctx, CApath))
return 0;
return 1;
}
void SSL_set_info_callback(SSL *ssl,
void (*cb) (const SSL *ssl, int type, int val))
{
ssl->info_callback = cb;
}
/*
* One compiler (Diab DCC) doesn't like argument names in returned function
* pointer.
*/
void (*SSL_get_info_callback(const SSL *ssl)) (const SSL * /* ssl */ ,
int /* type */ ,
int /* val */ ) {
return ssl->info_callback;
}
void SSL_set_verify_result(SSL *ssl, long arg)
{
ssl->verify_result = arg;
}
long SSL_get_verify_result(const SSL *ssl)
{
return ssl->verify_result;
}
size_t SSL_get_client_random(const SSL *ssl, unsigned char *out, size_t outlen)
{
if (outlen == 0)
return sizeof(ssl->s3.client_random);
if (outlen > sizeof(ssl->s3.client_random))
outlen = sizeof(ssl->s3.client_random);
memcpy(out, ssl->s3.client_random, outlen);
return outlen;
}
size_t SSL_get_server_random(const SSL *ssl, unsigned char *out, size_t outlen)
{
if (outlen == 0)
return sizeof(ssl->s3.server_random);
if (outlen > sizeof(ssl->s3.server_random))
outlen = sizeof(ssl->s3.server_random);
memcpy(out, ssl->s3.server_random, outlen);
return outlen;
}
size_t SSL_SESSION_get_master_key(const SSL_SESSION *session,
unsigned char *out, size_t outlen)
{
if (outlen == 0)
return session->master_key_length;
if (outlen > session->master_key_length)
outlen = session->master_key_length;
memcpy(out, session->master_key, outlen);
return outlen;
}
int SSL_SESSION_set1_master_key(SSL_SESSION *sess, const unsigned char *in,
size_t len)
{
if (len > sizeof(sess->master_key))
return 0;
memcpy(sess->master_key, in, len);
sess->master_key_length = len;
return 1;
}
int SSL_set_ex_data(SSL *s, int idx, void *arg)
{
return CRYPTO_set_ex_data(&s->ex_data, idx, arg);
}
void *SSL_get_ex_data(const SSL *s, int idx)
{
return CRYPTO_get_ex_data(&s->ex_data, idx);
}
int SSL_CTX_set_ex_data(SSL_CTX *s, int idx, void *arg)
{
return CRYPTO_set_ex_data(&s->ex_data, idx, arg);
}
void *SSL_CTX_get_ex_data(const SSL_CTX *s, int idx)
{
return CRYPTO_get_ex_data(&s->ex_data, idx);
}
X509_STORE *SSL_CTX_get_cert_store(const SSL_CTX *ctx)
{
return ctx->cert_store;
}
void SSL_CTX_set_cert_store(SSL_CTX *ctx, X509_STORE *store)
{
X509_STORE_free(ctx->cert_store);
ctx->cert_store = store;
}
void SSL_CTX_set1_cert_store(SSL_CTX *ctx, X509_STORE *store)
{
if (store != NULL)
X509_STORE_up_ref(store);
SSL_CTX_set_cert_store(ctx, store);
}
int SSL_want(const SSL *s)
{
return s->rwstate;
}
#ifndef OPENSSL_NO_PSK
int SSL_CTX_use_psk_identity_hint(SSL_CTX *ctx, const char *identity_hint)
{
if (identity_hint != NULL && strlen(identity_hint) > PSK_MAX_IDENTITY_LEN) {
ERR_raise(ERR_LIB_SSL, SSL_R_DATA_LENGTH_TOO_LONG);
return 0;
}
OPENSSL_free(ctx->cert->psk_identity_hint);
if (identity_hint != NULL) {
ctx->cert->psk_identity_hint = OPENSSL_strdup(identity_hint);
if (ctx->cert->psk_identity_hint == NULL)
return 0;
} else
ctx->cert->psk_identity_hint = NULL;
return 1;
}
int SSL_use_psk_identity_hint(SSL *s, const char *identity_hint)
{
if (s == NULL)
return 0;
if (identity_hint != NULL && strlen(identity_hint) > PSK_MAX_IDENTITY_LEN) {
ERR_raise(ERR_LIB_SSL, SSL_R_DATA_LENGTH_TOO_LONG);
return 0;
}
OPENSSL_free(s->cert->psk_identity_hint);
if (identity_hint != NULL) {
s->cert->psk_identity_hint = OPENSSL_strdup(identity_hint);
if (s->cert->psk_identity_hint == NULL)
return 0;
} else
s->cert->psk_identity_hint = NULL;
return 1;
}
const char *SSL_get_psk_identity_hint(const SSL *s)
{
if (s == NULL || s->session == NULL)
return NULL;
return s->session->psk_identity_hint;
}
const char *SSL_get_psk_identity(const SSL *s)
{
if (s == NULL || s->session == NULL)
return NULL;
return s->session->psk_identity;
}
void SSL_set_psk_client_callback(SSL *s, SSL_psk_client_cb_func cb)
{
s->psk_client_callback = cb;
}
void SSL_CTX_set_psk_client_callback(SSL_CTX *ctx, SSL_psk_client_cb_func cb)
{
ctx->psk_client_callback = cb;
}
void SSL_set_psk_server_callback(SSL *s, SSL_psk_server_cb_func cb)
{
s->psk_server_callback = cb;
}
void SSL_CTX_set_psk_server_callback(SSL_CTX *ctx, SSL_psk_server_cb_func cb)
{
ctx->psk_server_callback = cb;
}
#endif
void SSL_set_psk_find_session_callback(SSL *s, SSL_psk_find_session_cb_func cb)
{
s->psk_find_session_cb = cb;
}
void SSL_CTX_set_psk_find_session_callback(SSL_CTX *ctx,
SSL_psk_find_session_cb_func cb)
{
ctx->psk_find_session_cb = cb;
}
void SSL_set_psk_use_session_callback(SSL *s, SSL_psk_use_session_cb_func cb)
{
s->psk_use_session_cb = cb;
}
void SSL_CTX_set_psk_use_session_callback(SSL_CTX *ctx,
SSL_psk_use_session_cb_func cb)
{
ctx->psk_use_session_cb = cb;
}
void SSL_CTX_set_msg_callback(SSL_CTX *ctx,
void (*cb) (int write_p, int version,
int content_type, const void *buf,
size_t len, SSL *ssl, void *arg))
{
SSL_CTX_callback_ctrl(ctx, SSL_CTRL_SET_MSG_CALLBACK, (void (*)(void))cb);
}
void SSL_set_msg_callback(SSL *ssl,
void (*cb) (int write_p, int version,
int content_type, const void *buf,
size_t len, SSL *ssl, void *arg))
{
SSL_callback_ctrl(ssl, SSL_CTRL_SET_MSG_CALLBACK, (void (*)(void))cb);
}
void SSL_CTX_set_not_resumable_session_callback(SSL_CTX *ctx,
int (*cb) (SSL *ssl,
int
is_forward_secure))
{
SSL_CTX_callback_ctrl(ctx, SSL_CTRL_SET_NOT_RESUMABLE_SESS_CB,
(void (*)(void))cb);
}
void SSL_set_not_resumable_session_callback(SSL *ssl,
int (*cb) (SSL *ssl,
int is_forward_secure))
{
SSL_callback_ctrl(ssl, SSL_CTRL_SET_NOT_RESUMABLE_SESS_CB,
(void (*)(void))cb);
}
void SSL_CTX_set_record_padding_callback(SSL_CTX *ctx,
size_t (*cb) (SSL *ssl, int type,
size_t len, void *arg))
{
ctx->record_padding_cb = cb;
}
void SSL_CTX_set_record_padding_callback_arg(SSL_CTX *ctx, void *arg)
{
ctx->record_padding_arg = arg;
}
void *SSL_CTX_get_record_padding_callback_arg(const SSL_CTX *ctx)
{
return ctx->record_padding_arg;
}
int SSL_CTX_set_block_padding(SSL_CTX *ctx, size_t block_size)
{
/* block size of 0 or 1 is basically no padding */
if (block_size == 1)
ctx->block_padding = 0;
else if (block_size <= SSL3_RT_MAX_PLAIN_LENGTH)
ctx->block_padding = block_size;
else
return 0;
return 1;
}
int SSL_set_record_padding_callback(SSL *ssl,
size_t (*cb) (SSL *ssl, int type,
size_t len, void *arg))
{
BIO *b;
b = SSL_get_wbio(ssl);
if (b == NULL || !BIO_get_ktls_send(b)) {
ssl->record_padding_cb = cb;
return 1;
}
return 0;
}
void SSL_set_record_padding_callback_arg(SSL *ssl, void *arg)
{
ssl->record_padding_arg = arg;
}
void *SSL_get_record_padding_callback_arg(const SSL *ssl)
{
return ssl->record_padding_arg;
}
int SSL_set_block_padding(SSL *ssl, size_t block_size)
{
/* block size of 0 or 1 is basically no padding */
if (block_size == 1)
ssl->block_padding = 0;
else if (block_size <= SSL3_RT_MAX_PLAIN_LENGTH)
ssl->block_padding = block_size;
else
return 0;
return 1;
}
int SSL_set_num_tickets(SSL *s, size_t num_tickets)
{
s->num_tickets = num_tickets;
return 1;
}
size_t SSL_get_num_tickets(const SSL *s)
{
return s->num_tickets;
}
int SSL_CTX_set_num_tickets(SSL_CTX *ctx, size_t num_tickets)
{
ctx->num_tickets = num_tickets;
return 1;
}
size_t SSL_CTX_get_num_tickets(const SSL_CTX *ctx)
{
return ctx->num_tickets;
}
/*
* Allocates new EVP_MD_CTX and sets pointer to it into given pointer
* variable, freeing EVP_MD_CTX previously stored in that variable, if any.
* If EVP_MD pointer is passed, initializes ctx with this |md|.
* Returns the newly allocated ctx;
*/
EVP_MD_CTX *ssl_replace_hash(EVP_MD_CTX **hash, const EVP_MD *md)
{
ssl_clear_hash_ctx(hash);
*hash = EVP_MD_CTX_new();
if (*hash == NULL || (md && EVP_DigestInit_ex(*hash, md, NULL) <= 0)) {
EVP_MD_CTX_free(*hash);
*hash = NULL;
return NULL;
}
return *hash;
}
void ssl_clear_hash_ctx(EVP_MD_CTX **hash)
{
EVP_MD_CTX_free(*hash);
*hash = NULL;
}
/* Retrieve handshake hashes */
int ssl_handshake_hash(SSL *s, unsigned char *out, size_t outlen,
size_t *hashlen)
{
EVP_MD_CTX *ctx = NULL;
EVP_MD_CTX *hdgst = s->s3.handshake_dgst;
int hashleni = EVP_MD_CTX_get_size(hdgst);
int ret = 0;
if (hashleni < 0 || (size_t)hashleni > outlen) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
goto err;
}
ctx = EVP_MD_CTX_new();
if (ctx == NULL) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
goto err;
}
if (!EVP_MD_CTX_copy_ex(ctx, hdgst)
|| EVP_DigestFinal_ex(ctx, out, NULL) <= 0) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
goto err;
}
*hashlen = hashleni;
ret = 1;
err:
EVP_MD_CTX_free(ctx);
return ret;
}
int SSL_session_reused(const SSL *s)
{
return s->hit;
}
int SSL_is_server(const SSL *s)
{
return s->server;
}
#ifndef OPENSSL_NO_DEPRECATED_1_1_0
void SSL_set_debug(SSL *s, int debug)
{
/* Old function was do-nothing anyway... */
(void)s;
(void)debug;
}
#endif
void SSL_set_security_level(SSL *s, int level)
{
s->cert->sec_level = level;
}
int SSL_get_security_level(const SSL *s)
{
return s->cert->sec_level;
}
void SSL_set_security_callback(SSL *s,
int (*cb) (const SSL *s, const SSL_CTX *ctx,
int op, int bits, int nid,
void *other, void *ex))
{
s->cert->sec_cb = cb;
}
int (*SSL_get_security_callback(const SSL *s)) (const SSL *s,
const SSL_CTX *ctx, int op,
int bits, int nid, void *other,
void *ex) {
return s->cert->sec_cb;
}
void SSL_set0_security_ex_data(SSL *s, void *ex)
{
s->cert->sec_ex = ex;
}
void *SSL_get0_security_ex_data(const SSL *s)
{
return s->cert->sec_ex;
}
void SSL_CTX_set_security_level(SSL_CTX *ctx, int level)
{
ctx->cert->sec_level = level;
}
int SSL_CTX_get_security_level(const SSL_CTX *ctx)
{
return ctx->cert->sec_level;
}
void SSL_CTX_set_security_callback(SSL_CTX *ctx,
int (*cb) (const SSL *s, const SSL_CTX *ctx,
int op, int bits, int nid,
void *other, void *ex))
{
ctx->cert->sec_cb = cb;
}
int (*SSL_CTX_get_security_callback(const SSL_CTX *ctx)) (const SSL *s,
const SSL_CTX *ctx,
int op, int bits,
int nid,
void *other,
void *ex) {
return ctx->cert->sec_cb;
}
void SSL_CTX_set0_security_ex_data(SSL_CTX *ctx, void *ex)
{
ctx->cert->sec_ex = ex;
}
void *SSL_CTX_get0_security_ex_data(const SSL_CTX *ctx)
{
return ctx->cert->sec_ex;
}
uint64_t SSL_CTX_get_options(const SSL_CTX *ctx)
{
return ctx->options;
}
uint64_t SSL_get_options(const SSL *s)
{
return s->options;
}
uint64_t SSL_CTX_set_options(SSL_CTX *ctx, uint64_t op)
{
return ctx->options |= op;
}
uint64_t SSL_set_options(SSL *s, uint64_t op)
{
return s->options |= op;
}
uint64_t SSL_CTX_clear_options(SSL_CTX *ctx, uint64_t op)
{
return ctx->options &= ~op;
}
uint64_t SSL_clear_options(SSL *s, uint64_t op)
{
return s->options &= ~op;
}
STACK_OF(X509) *SSL_get0_verified_chain(const SSL *s)
{
return s->verified_chain;
}
IMPLEMENT_OBJ_BSEARCH_GLOBAL_CMP_FN(SSL_CIPHER, SSL_CIPHER, ssl_cipher_id);
#ifndef OPENSSL_NO_CT
/*
* Moves SCTs from the |src| stack to the |dst| stack.
* The source of each SCT will be set to |origin|.
* If |dst| points to a NULL pointer, a new stack will be created and owned by
* the caller.
* Returns the number of SCTs moved, or a negative integer if an error occurs.
* The |dst| stack is created and possibly partially populated even in case
* of error, likewise the |src| stack may be left in an intermediate state.
*/
static int ct_move_scts(STACK_OF(SCT) **dst, STACK_OF(SCT) *src,
sct_source_t origin)
{
int scts_moved = 0;
SCT *sct = NULL;
if (*dst == NULL) {
*dst = sk_SCT_new_null();
if (*dst == NULL) {
ERR_raise(ERR_LIB_SSL, ERR_R_MALLOC_FAILURE);
goto err;
}
}
while ((sct = sk_SCT_pop(src)) != NULL) {
if (SCT_set_source(sct, origin) != 1)
goto err;
if (!sk_SCT_push(*dst, sct))
goto err;
scts_moved += 1;
}
return scts_moved;
err:
SCT_free(sct);
return -1;
}
/*
* Look for data collected during ServerHello and parse if found.
* Returns the number of SCTs extracted.
*/
static int ct_extract_tls_extension_scts(SSL *s)
{
int scts_extracted = 0;
if (s->ext.scts != NULL) {
const unsigned char *p = s->ext.scts;
STACK_OF(SCT) *scts = o2i_SCT_LIST(NULL, &p, s->ext.scts_len);
scts_extracted = ct_move_scts(&s->scts, scts, SCT_SOURCE_TLS_EXTENSION);
SCT_LIST_free(scts);
}
return scts_extracted;
}
/*
* Checks for an OCSP response and then attempts to extract any SCTs found if it
* contains an SCT X509 extension. They will be stored in |s->scts|.
* Returns:
* - The number of SCTs extracted, assuming an OCSP response exists.
* - 0 if no OCSP response exists or it contains no SCTs.
* - A negative integer if an error occurs.
*/
static int ct_extract_ocsp_response_scts(SSL *s)
{
# ifndef OPENSSL_NO_OCSP
int scts_extracted = 0;
const unsigned char *p;
OCSP_BASICRESP *br = NULL;
OCSP_RESPONSE *rsp = NULL;
STACK_OF(SCT) *scts = NULL;
int i;
if (s->ext.ocsp.resp == NULL || s->ext.ocsp.resp_len == 0)
goto err;
p = s->ext.ocsp.resp;
rsp = d2i_OCSP_RESPONSE(NULL, &p, (int)s->ext.ocsp.resp_len);
if (rsp == NULL)
goto err;
br = OCSP_response_get1_basic(rsp);
if (br == NULL)
goto err;
for (i = 0; i < OCSP_resp_count(br); ++i) {
OCSP_SINGLERESP *single = OCSP_resp_get0(br, i);
if (single == NULL)
continue;
scts =
OCSP_SINGLERESP_get1_ext_d2i(single, NID_ct_cert_scts, NULL, NULL);
scts_extracted =
ct_move_scts(&s->scts, scts, SCT_SOURCE_OCSP_STAPLED_RESPONSE);
if (scts_extracted < 0)
goto err;
}
err:
SCT_LIST_free(scts);
OCSP_BASICRESP_free(br);
OCSP_RESPONSE_free(rsp);
return scts_extracted;
# else
/* Behave as if no OCSP response exists */
return 0;
# endif
}
/*
* Attempts to extract SCTs from the peer certificate.
* Return the number of SCTs extracted, or a negative integer if an error
* occurs.
*/
static int ct_extract_x509v3_extension_scts(SSL *s)
{
int scts_extracted = 0;
X509 *cert = s->session != NULL ? s->session->peer : NULL;
if (cert != NULL) {
STACK_OF(SCT) *scts =
X509_get_ext_d2i(cert, NID_ct_precert_scts, NULL, NULL);
scts_extracted =
ct_move_scts(&s->scts, scts, SCT_SOURCE_X509V3_EXTENSION);
SCT_LIST_free(scts);
}
return scts_extracted;
}
/*
* Attempts to find all received SCTs by checking TLS extensions, the OCSP
* response (if it exists) and X509v3 extensions in the certificate.
* Returns NULL if an error occurs.
*/
const STACK_OF(SCT) *SSL_get0_peer_scts(SSL *s)
{
if (!s->scts_parsed) {
if (ct_extract_tls_extension_scts(s) < 0 ||
ct_extract_ocsp_response_scts(s) < 0 ||
ct_extract_x509v3_extension_scts(s) < 0)
goto err;
s->scts_parsed = 1;
}
return s->scts;
err:
return NULL;
}
static int ct_permissive(const CT_POLICY_EVAL_CTX * ctx,
const STACK_OF(SCT) *scts, void *unused_arg)
{
return 1;
}
static int ct_strict(const CT_POLICY_EVAL_CTX * ctx,
const STACK_OF(SCT) *scts, void *unused_arg)
{
int count = scts != NULL ? sk_SCT_num(scts) : 0;
int i;
for (i = 0; i < count; ++i) {
SCT *sct = sk_SCT_value(scts, i);
int status = SCT_get_validation_status(sct);
if (status == SCT_VALIDATION_STATUS_VALID)
return 1;
}
ERR_raise(ERR_LIB_SSL, SSL_R_NO_VALID_SCTS);
return 0;
}
int SSL_set_ct_validation_callback(SSL *s, ssl_ct_validation_cb callback,
void *arg)
{
/*
* Since code exists that uses the custom extension handler for CT, look
* for this and throw an error if they have already registered to use CT.
*/
if (callback != NULL && SSL_CTX_has_client_custom_ext(s->ctx,
TLSEXT_TYPE_signed_certificate_timestamp))
{
ERR_raise(ERR_LIB_SSL, SSL_R_CUSTOM_EXT_HANDLER_ALREADY_INSTALLED);
return 0;
}
if (callback != NULL) {
/*
* If we are validating CT, then we MUST accept SCTs served via OCSP
*/
if (!SSL_set_tlsext_status_type(s, TLSEXT_STATUSTYPE_ocsp))
return 0;
}
s->ct_validation_callback = callback;
s->ct_validation_callback_arg = arg;
return 1;
}
int SSL_CTX_set_ct_validation_callback(SSL_CTX *ctx,
ssl_ct_validation_cb callback, void *arg)
{
/*
* Since code exists that uses the custom extension handler for CT, look for
* this and throw an error if they have already registered to use CT.
*/
if (callback != NULL && SSL_CTX_has_client_custom_ext(ctx,
TLSEXT_TYPE_signed_certificate_timestamp))
{
ERR_raise(ERR_LIB_SSL, SSL_R_CUSTOM_EXT_HANDLER_ALREADY_INSTALLED);
return 0;
}
ctx->ct_validation_callback = callback;
ctx->ct_validation_callback_arg = arg;
return 1;
}
int SSL_ct_is_enabled(const SSL *s)
{
return s->ct_validation_callback != NULL;
}
int SSL_CTX_ct_is_enabled(const SSL_CTX *ctx)
{
return ctx->ct_validation_callback != NULL;
}
int ssl_validate_ct(SSL *s)
{
int ret = 0;
X509 *cert = s->session != NULL ? s->session->peer : NULL;
X509 *issuer;
SSL_DANE *dane = &s->dane;
CT_POLICY_EVAL_CTX *ctx = NULL;
const STACK_OF(SCT) *scts;
/*
* If no callback is set, the peer is anonymous, or its chain is invalid,
* skip SCT validation - just return success. Applications that continue
* handshakes without certificates, with unverified chains, or pinned leaf
* certificates are outside the scope of the WebPKI and CT.
*
* The above exclusions notwithstanding the vast majority of peers will
* have rather ordinary certificate chains validated by typical
* applications that perform certificate verification and therefore will
* process SCTs when enabled.
*/
if (s->ct_validation_callback == NULL || cert == NULL ||
s->verify_result != X509_V_OK ||
s->verified_chain == NULL || sk_X509_num(s->verified_chain) <= 1)
return 1;
/*
* CT not applicable for chains validated via DANE-TA(2) or DANE-EE(3)
* trust-anchors. See https://tools.ietf.org/html/rfc7671#section-4.2
*/
if (DANETLS_ENABLED(dane) && dane->mtlsa != NULL) {
switch (dane->mtlsa->usage) {
case DANETLS_USAGE_DANE_TA:
case DANETLS_USAGE_DANE_EE:
return 1;
}
}
ctx = CT_POLICY_EVAL_CTX_new_ex(s->ctx->libctx, s->ctx->propq);
if (ctx == NULL) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_MALLOC_FAILURE);
goto end;
}
issuer = sk_X509_value(s->verified_chain, 1);
CT_POLICY_EVAL_CTX_set1_cert(ctx, cert);
CT_POLICY_EVAL_CTX_set1_issuer(ctx, issuer);
CT_POLICY_EVAL_CTX_set_shared_CTLOG_STORE(ctx, s->ctx->ctlog_store);
CT_POLICY_EVAL_CTX_set_time(
ctx, (uint64_t)SSL_SESSION_get_time(SSL_get0_session(s)) * 1000);
scts = SSL_get0_peer_scts(s);
/*
* This function returns success (> 0) only when all the SCTs are valid, 0
* when some are invalid, and < 0 on various internal errors (out of
* memory, etc.). Having some, or even all, invalid SCTs is not sufficient
* reason to abort the handshake, that decision is up to the callback.
* Therefore, we error out only in the unexpected case that the return
* value is negative.
*
* XXX: One might well argue that the return value of this function is an
* unfortunate design choice. Its job is only to determine the validation
* status of each of the provided SCTs. So long as it correctly separates
* the wheat from the chaff it should return success. Failure in this case
* ought to correspond to an inability to carry out its duties.
*/
if (SCT_LIST_validate(scts, ctx) < 0) {
SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_SCT_VERIFICATION_FAILED);
goto end;
}
ret = s->ct_validation_callback(ctx, scts, s->ct_validation_callback_arg);
if (ret < 0)
ret = 0; /* This function returns 0 on failure */
if (!ret)
SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_CALLBACK_FAILED);
end:
CT_POLICY_EVAL_CTX_free(ctx);
/*
* With SSL_VERIFY_NONE the session may be cached and re-used despite a
* failure return code here. Also the application may wish the complete
* the handshake, and then disconnect cleanly at a higher layer, after
* checking the verification status of the completed connection.
*
* We therefore force a certificate verification failure which will be
* visible via SSL_get_verify_result() and cached as part of any resumed
* session.
*
* Note: the permissive callback is for information gathering only, always
* returns success, and does not affect verification status. Only the
* strict callback or a custom application-specified callback can trigger
* connection failure or record a verification error.
*/
if (ret <= 0)
s->verify_result = X509_V_ERR_NO_VALID_SCTS;
return ret;
}
int SSL_CTX_enable_ct(SSL_CTX *ctx, int validation_mode)
{
switch (validation_mode) {
default:
ERR_raise(ERR_LIB_SSL, SSL_R_INVALID_CT_VALIDATION_TYPE);
return 0;
case SSL_CT_VALIDATION_PERMISSIVE:
return SSL_CTX_set_ct_validation_callback(ctx, ct_permissive, NULL);
case SSL_CT_VALIDATION_STRICT:
return SSL_CTX_set_ct_validation_callback(ctx, ct_strict, NULL);
}
}
int SSL_enable_ct(SSL *s, int validation_mode)
{
switch (validation_mode) {
default:
ERR_raise(ERR_LIB_SSL, SSL_R_INVALID_CT_VALIDATION_TYPE);
return 0;
case SSL_CT_VALIDATION_PERMISSIVE:
return SSL_set_ct_validation_callback(s, ct_permissive, NULL);
case SSL_CT_VALIDATION_STRICT:
return SSL_set_ct_validation_callback(s, ct_strict, NULL);
}
}
int SSL_CTX_set_default_ctlog_list_file(SSL_CTX *ctx)
{
return CTLOG_STORE_load_default_file(ctx->ctlog_store);
}
int SSL_CTX_set_ctlog_list_file(SSL_CTX *ctx, const char *path)
{
return CTLOG_STORE_load_file(ctx->ctlog_store, path);
}
void SSL_CTX_set0_ctlog_store(SSL_CTX *ctx, CTLOG_STORE * logs)
{
CTLOG_STORE_free(ctx->ctlog_store);
ctx->ctlog_store = logs;
}
const CTLOG_STORE *SSL_CTX_get0_ctlog_store(const SSL_CTX *ctx)
{
return ctx->ctlog_store;
}
#endif /* OPENSSL_NO_CT */
void SSL_CTX_set_client_hello_cb(SSL_CTX *c, SSL_client_hello_cb_fn cb,
void *arg)
{
c->client_hello_cb = cb;
c->client_hello_cb_arg = arg;
}
int SSL_client_hello_isv2(SSL *s)
{
if (s->clienthello == NULL)
return 0;
return s->clienthello->isv2;
}
unsigned int SSL_client_hello_get0_legacy_version(SSL *s)
{
if (s->clienthello == NULL)
return 0;
return s->clienthello->legacy_version;
}
size_t SSL_client_hello_get0_random(SSL *s, const unsigned char **out)
{
if (s->clienthello == NULL)
return 0;
if (out != NULL)
*out = s->clienthello->random;
return SSL3_RANDOM_SIZE;
}
size_t SSL_client_hello_get0_session_id(SSL *s, const unsigned char **out)
{
if (s->clienthello == NULL)
return 0;
if (out != NULL)
*out = s->clienthello->session_id;
return s->clienthello->session_id_len;
}
size_t SSL_client_hello_get0_ciphers(SSL *s, const unsigned char **out)
{
if (s->clienthello == NULL)
return 0;
if (out != NULL)
*out = PACKET_data(&s->clienthello->ciphersuites);
return PACKET_remaining(&s->clienthello->ciphersuites);
}
size_t SSL_client_hello_get0_compression_methods(SSL *s, const unsigned char **out)
{
if (s->clienthello == NULL)
return 0;
if (out != NULL)
*out = s->clienthello->compressions;
return s->clienthello->compressions_len;
}
int SSL_client_hello_get1_extensions_present(SSL *s, int **out, size_t *outlen)
{
RAW_EXTENSION *ext;
int *present;
size_t num = 0, i;
if (s->clienthello == NULL || out == NULL || outlen == NULL)
return 0;
for (i = 0; i < s->clienthello->pre_proc_exts_len; i++) {
ext = s->clienthello->pre_proc_exts + i;
if (ext->present)
num++;
}
if (num == 0) {
*out = NULL;
*outlen = 0;
return 1;
}
if ((present = OPENSSL_malloc(sizeof(*present) * num)) == NULL) {
ERR_raise(ERR_LIB_SSL, ERR_R_MALLOC_FAILURE);
return 0;
}
for (i = 0; i < s->clienthello->pre_proc_exts_len; i++) {
ext = s->clienthello->pre_proc_exts + i;
if (ext->present) {
if (ext->received_order >= num)
goto err;
present[ext->received_order] = ext->type;
}
}
*out = present;
*outlen = num;
return 1;
err:
OPENSSL_free(present);
return 0;
}
int SSL_client_hello_get0_ext(SSL *s, unsigned int type, const unsigned char **out,
size_t *outlen)
{
size_t i;
RAW_EXTENSION *r;
if (s->clienthello == NULL)
return 0;
for (i = 0; i < s->clienthello->pre_proc_exts_len; ++i) {
r = s->clienthello->pre_proc_exts + i;
if (r->present && r->type == type) {
if (out != NULL)
*out = PACKET_data(&r->data);
if (outlen != NULL)
*outlen = PACKET_remaining(&r->data);
return 1;
}
}
return 0;
}
int SSL_free_buffers(SSL *ssl)
{
RECORD_LAYER *rl = &ssl->rlayer;
if (RECORD_LAYER_read_pending(rl) || RECORD_LAYER_write_pending(rl))
return 0;
+ if (RECORD_LAYER_data_present(rl))
+ return 0;
+
RECORD_LAYER_release(rl);
return 1;
}
int SSL_alloc_buffers(SSL *ssl)
{
return ssl3_setup_buffers(ssl);
}
void SSL_CTX_set_keylog_callback(SSL_CTX *ctx, SSL_CTX_keylog_cb_func cb)
{
ctx->keylog_callback = cb;
}
SSL_CTX_keylog_cb_func SSL_CTX_get_keylog_callback(const SSL_CTX *ctx)
{
return ctx->keylog_callback;
}
static int nss_keylog_int(const char *prefix,
SSL *ssl,
const uint8_t *parameter_1,
size_t parameter_1_len,
const uint8_t *parameter_2,
size_t parameter_2_len)
{
char *out = NULL;
char *cursor = NULL;
size_t out_len = 0;
size_t i;
size_t prefix_len;
if (ssl->ctx->keylog_callback == NULL)
return 1;
/*
* Our output buffer will contain the following strings, rendered with
* space characters in between, terminated by a NULL character: first the
* prefix, then the first parameter, then the second parameter. The
* meaning of each parameter depends on the specific key material being
* logged. Note that the first and second parameters are encoded in
* hexadecimal, so we need a buffer that is twice their lengths.
*/
prefix_len = strlen(prefix);
out_len = prefix_len + (2 * parameter_1_len) + (2 * parameter_2_len) + 3;
if ((out = cursor = OPENSSL_malloc(out_len)) == NULL) {
SSLfatal(ssl, SSL_AD_INTERNAL_ERROR, ERR_R_MALLOC_FAILURE);
return 0;
}
strcpy(cursor, prefix);
cursor += prefix_len;
*cursor++ = ' ';
for (i = 0; i < parameter_1_len; i++) {
sprintf(cursor, "%02x", parameter_1[i]);
cursor += 2;
}
*cursor++ = ' ';
for (i = 0; i < parameter_2_len; i++) {
sprintf(cursor, "%02x", parameter_2[i]);
cursor += 2;
}
*cursor = '\0';
ssl->ctx->keylog_callback(ssl, (const char *)out);
OPENSSL_clear_free(out, out_len);
return 1;
}
int ssl_log_rsa_client_key_exchange(SSL *ssl,
const uint8_t *encrypted_premaster,
size_t encrypted_premaster_len,
const uint8_t *premaster,
size_t premaster_len)
{
if (encrypted_premaster_len < 8) {
SSLfatal(ssl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return 0;
}
/* We only want the first 8 bytes of the encrypted premaster as a tag. */
return nss_keylog_int("RSA",
ssl,
encrypted_premaster,
8,
premaster,
premaster_len);
}
int ssl_log_secret(SSL *ssl,
const char *label,
const uint8_t *secret,
size_t secret_len)
{
return nss_keylog_int(label,
ssl,
ssl->s3.client_random,
SSL3_RANDOM_SIZE,
secret,
secret_len);
}
#define SSLV2_CIPHER_LEN 3
int ssl_cache_cipherlist(SSL *s, PACKET *cipher_suites, int sslv2format)
{
int n;
n = sslv2format ? SSLV2_CIPHER_LEN : TLS_CIPHER_LEN;
if (PACKET_remaining(cipher_suites) == 0) {
SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_NO_CIPHERS_SPECIFIED);
return 0;
}
if (PACKET_remaining(cipher_suites) % n != 0) {
SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_ERROR_IN_RECEIVED_CIPHER_LIST);
return 0;
}
OPENSSL_free(s->s3.tmp.ciphers_raw);
s->s3.tmp.ciphers_raw = NULL;
s->s3.tmp.ciphers_rawlen = 0;
if (sslv2format) {
size_t numciphers = PACKET_remaining(cipher_suites) / n;
PACKET sslv2ciphers = *cipher_suites;
unsigned int leadbyte;
unsigned char *raw;
/*
* We store the raw ciphers list in SSLv3+ format so we need to do some
* preprocessing to convert the list first. If there are any SSLv2 only
* ciphersuites with a non-zero leading byte then we are going to
* slightly over allocate because we won't store those. But that isn't a
* problem.
*/
raw = OPENSSL_malloc(numciphers * TLS_CIPHER_LEN);
s->s3.tmp.ciphers_raw = raw;
if (raw == NULL) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_MALLOC_FAILURE);
return 0;
}
for (s->s3.tmp.ciphers_rawlen = 0;
PACKET_remaining(&sslv2ciphers) > 0;
raw += TLS_CIPHER_LEN) {
if (!PACKET_get_1(&sslv2ciphers, &leadbyte)
|| (leadbyte == 0
&& !PACKET_copy_bytes(&sslv2ciphers, raw,
TLS_CIPHER_LEN))
|| (leadbyte != 0
&& !PACKET_forward(&sslv2ciphers, TLS_CIPHER_LEN))) {
SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_PACKET);
OPENSSL_free(s->s3.tmp.ciphers_raw);
s->s3.tmp.ciphers_raw = NULL;
s->s3.tmp.ciphers_rawlen = 0;
return 0;
}
if (leadbyte == 0)
s->s3.tmp.ciphers_rawlen += TLS_CIPHER_LEN;
}
} else if (!PACKET_memdup(cipher_suites, &s->s3.tmp.ciphers_raw,
&s->s3.tmp.ciphers_rawlen)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return 0;
}
return 1;
}
int SSL_bytes_to_cipher_list(SSL *s, const unsigned char *bytes, size_t len,
int isv2format, STACK_OF(SSL_CIPHER) **sk,
STACK_OF(SSL_CIPHER) **scsvs)
{
PACKET pkt;
if (!PACKET_buf_init(&pkt, bytes, len))
return 0;
return bytes_to_cipher_list(s, &pkt, sk, scsvs, isv2format, 0);
}
int bytes_to_cipher_list(SSL *s, PACKET *cipher_suites,
STACK_OF(SSL_CIPHER) **skp,
STACK_OF(SSL_CIPHER) **scsvs_out,
int sslv2format, int fatal)
{
const SSL_CIPHER *c;
STACK_OF(SSL_CIPHER) *sk = NULL;
STACK_OF(SSL_CIPHER) *scsvs = NULL;
int n;
/* 3 = SSLV2_CIPHER_LEN > TLS_CIPHER_LEN = 2. */
unsigned char cipher[SSLV2_CIPHER_LEN];
n = sslv2format ? SSLV2_CIPHER_LEN : TLS_CIPHER_LEN;
if (PACKET_remaining(cipher_suites) == 0) {
if (fatal)
SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_NO_CIPHERS_SPECIFIED);
else
ERR_raise(ERR_LIB_SSL, SSL_R_NO_CIPHERS_SPECIFIED);
return 0;
}
if (PACKET_remaining(cipher_suites) % n != 0) {
if (fatal)
SSLfatal(s, SSL_AD_DECODE_ERROR,
SSL_R_ERROR_IN_RECEIVED_CIPHER_LIST);
else
ERR_raise(ERR_LIB_SSL, SSL_R_ERROR_IN_RECEIVED_CIPHER_LIST);
return 0;
}
sk = sk_SSL_CIPHER_new_null();
scsvs = sk_SSL_CIPHER_new_null();
if (sk == NULL || scsvs == NULL) {
if (fatal)
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_MALLOC_FAILURE);
else
ERR_raise(ERR_LIB_SSL, ERR_R_MALLOC_FAILURE);
goto err;
}
while (PACKET_copy_bytes(cipher_suites, cipher, n)) {
/*
* SSLv3 ciphers wrapped in an SSLv2-compatible ClientHello have the
* first byte set to zero, while true SSLv2 ciphers have a non-zero
* first byte. We don't support any true SSLv2 ciphers, so skip them.
*/
if (sslv2format && cipher[0] != '\0')
continue;
/* For SSLv2-compat, ignore leading 0-byte. */
c = ssl_get_cipher_by_char(s, sslv2format ? &cipher[1] : cipher, 1);
if (c != NULL) {
if ((c->valid && !sk_SSL_CIPHER_push(sk, c)) ||
(!c->valid && !sk_SSL_CIPHER_push(scsvs, c))) {
if (fatal)
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_MALLOC_FAILURE);
else
ERR_raise(ERR_LIB_SSL, ERR_R_MALLOC_FAILURE);
goto err;
}
}
}
if (PACKET_remaining(cipher_suites) > 0) {
if (fatal)
SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_LENGTH);
else
ERR_raise(ERR_LIB_SSL, SSL_R_BAD_LENGTH);
goto err;
}
if (skp != NULL)
*skp = sk;
else
sk_SSL_CIPHER_free(sk);
if (scsvs_out != NULL)
*scsvs_out = scsvs;
else
sk_SSL_CIPHER_free(scsvs);
return 1;
err:
sk_SSL_CIPHER_free(sk);
sk_SSL_CIPHER_free(scsvs);
return 0;
}
int SSL_CTX_set_max_early_data(SSL_CTX *ctx, uint32_t max_early_data)
{
ctx->max_early_data = max_early_data;
return 1;
}
uint32_t SSL_CTX_get_max_early_data(const SSL_CTX *ctx)
{
return ctx->max_early_data;
}
int SSL_set_max_early_data(SSL *s, uint32_t max_early_data)
{
s->max_early_data = max_early_data;
return 1;
}
uint32_t SSL_get_max_early_data(const SSL *s)
{
return s->max_early_data;
}
int SSL_CTX_set_recv_max_early_data(SSL_CTX *ctx, uint32_t recv_max_early_data)
{
ctx->recv_max_early_data = recv_max_early_data;
return 1;
}
uint32_t SSL_CTX_get_recv_max_early_data(const SSL_CTX *ctx)
{
return ctx->recv_max_early_data;
}
int SSL_set_recv_max_early_data(SSL *s, uint32_t recv_max_early_data)
{
s->recv_max_early_data = recv_max_early_data;
return 1;
}
uint32_t SSL_get_recv_max_early_data(const SSL *s)
{
return s->recv_max_early_data;
}
__owur unsigned int ssl_get_max_send_fragment(const SSL *ssl)
{
/* Return any active Max Fragment Len extension */
if (ssl->session != NULL && USE_MAX_FRAGMENT_LENGTH_EXT(ssl->session))
return GET_MAX_FRAGMENT_LENGTH(ssl->session);
/* return current SSL connection setting */
return ssl->max_send_fragment;
}
__owur unsigned int ssl_get_split_send_fragment(const SSL *ssl)
{
/* Return a value regarding an active Max Fragment Len extension */
if (ssl->session != NULL && USE_MAX_FRAGMENT_LENGTH_EXT(ssl->session)
&& ssl->split_send_fragment > GET_MAX_FRAGMENT_LENGTH(ssl->session))
return GET_MAX_FRAGMENT_LENGTH(ssl->session);
/* else limit |split_send_fragment| to current |max_send_fragment| */
if (ssl->split_send_fragment > ssl->max_send_fragment)
return ssl->max_send_fragment;
/* return current SSL connection setting */
return ssl->split_send_fragment;
}
int SSL_stateless(SSL *s)
{
int ret;
/* Ensure there is no state left over from a previous invocation */
if (!SSL_clear(s))
return 0;
ERR_clear_error();
s->s3.flags |= TLS1_FLAGS_STATELESS;
ret = SSL_accept(s);
s->s3.flags &= ~TLS1_FLAGS_STATELESS;
if (ret > 0 && s->ext.cookieok)
return 1;
if (s->hello_retry_request == SSL_HRR_PENDING && !ossl_statem_in_error(s))
return 0;
return -1;
}
void SSL_CTX_set_post_handshake_auth(SSL_CTX *ctx, int val)
{
ctx->pha_enabled = val;
}
void SSL_set_post_handshake_auth(SSL *ssl, int val)
{
ssl->pha_enabled = val;
}
int SSL_verify_client_post_handshake(SSL *ssl)
{
if (!SSL_IS_TLS13(ssl)) {
ERR_raise(ERR_LIB_SSL, SSL_R_WRONG_SSL_VERSION);
return 0;
}
if (!ssl->server) {
ERR_raise(ERR_LIB_SSL, SSL_R_NOT_SERVER);
return 0;
}
if (!SSL_is_init_finished(ssl)) {
ERR_raise(ERR_LIB_SSL, SSL_R_STILL_IN_INIT);
return 0;
}
switch (ssl->post_handshake_auth) {
case SSL_PHA_NONE:
ERR_raise(ERR_LIB_SSL, SSL_R_EXTENSION_NOT_RECEIVED);
return 0;
default:
case SSL_PHA_EXT_SENT:
ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
return 0;
case SSL_PHA_EXT_RECEIVED:
break;
case SSL_PHA_REQUEST_PENDING:
ERR_raise(ERR_LIB_SSL, SSL_R_REQUEST_PENDING);
return 0;
case SSL_PHA_REQUESTED:
ERR_raise(ERR_LIB_SSL, SSL_R_REQUEST_SENT);
return 0;
}
ssl->post_handshake_auth = SSL_PHA_REQUEST_PENDING;
/* checks verify_mode and algorithm_auth */
if (!send_certificate_request(ssl)) {
ssl->post_handshake_auth = SSL_PHA_EXT_RECEIVED; /* restore on error */
ERR_raise(ERR_LIB_SSL, SSL_R_INVALID_CONFIG);
return 0;
}
ossl_statem_set_in_init(ssl, 1);
return 1;
}
int SSL_CTX_set_session_ticket_cb(SSL_CTX *ctx,
SSL_CTX_generate_session_ticket_fn gen_cb,
SSL_CTX_decrypt_session_ticket_fn dec_cb,
void *arg)
{
ctx->generate_ticket_cb = gen_cb;
ctx->decrypt_ticket_cb = dec_cb;
ctx->ticket_cb_data = arg;
return 1;
}
void SSL_CTX_set_allow_early_data_cb(SSL_CTX *ctx,
SSL_allow_early_data_cb_fn cb,
void *arg)
{
ctx->allow_early_data_cb = cb;
ctx->allow_early_data_cb_data = arg;
}
void SSL_set_allow_early_data_cb(SSL *s,
SSL_allow_early_data_cb_fn cb,
void *arg)
{
s->allow_early_data_cb = cb;
s->allow_early_data_cb_data = arg;
}
const EVP_CIPHER *ssl_evp_cipher_fetch(OSSL_LIB_CTX *libctx,
int nid,
const char *properties)
{
const EVP_CIPHER *ciph;
ciph = tls_get_cipher_from_engine(nid);
if (ciph != NULL)
return ciph;
/*
* If there is no engine cipher then we do an explicit fetch. This may fail
* and that could be ok
*/
ERR_set_mark();
ciph = EVP_CIPHER_fetch(libctx, OBJ_nid2sn(nid), properties);
ERR_pop_to_mark();
return ciph;
}
int ssl_evp_cipher_up_ref(const EVP_CIPHER *cipher)
{
/* Don't up-ref an implicit EVP_CIPHER */
if (EVP_CIPHER_get0_provider(cipher) == NULL)
return 1;
/*
* The cipher was explicitly fetched and therefore it is safe to cast
* away the const
*/
return EVP_CIPHER_up_ref((EVP_CIPHER *)cipher);
}
void ssl_evp_cipher_free(const EVP_CIPHER *cipher)
{
if (cipher == NULL)
return;
if (EVP_CIPHER_get0_provider(cipher) != NULL) {
/*
* The cipher was explicitly fetched and therefore it is safe to cast
* away the const
*/
EVP_CIPHER_free((EVP_CIPHER *)cipher);
}
}
const EVP_MD *ssl_evp_md_fetch(OSSL_LIB_CTX *libctx,
int nid,
const char *properties)
{
const EVP_MD *md;
md = tls_get_digest_from_engine(nid);
if (md != NULL)
return md;
/* Otherwise we do an explicit fetch */
ERR_set_mark();
md = EVP_MD_fetch(libctx, OBJ_nid2sn(nid), properties);
ERR_pop_to_mark();
return md;
}
int ssl_evp_md_up_ref(const EVP_MD *md)
{
/* Don't up-ref an implicit EVP_MD */
if (EVP_MD_get0_provider(md) == NULL)
return 1;
/*
* The digest was explicitly fetched and therefore it is safe to cast
* away the const
*/
return EVP_MD_up_ref((EVP_MD *)md);
}
void ssl_evp_md_free(const EVP_MD *md)
{
if (md == NULL)
return;
if (EVP_MD_get0_provider(md) != NULL) {
/*
* The digest was explicitly fetched and therefore it is safe to cast
* away the const
*/
EVP_MD_free((EVP_MD *)md);
}
}
int SSL_set0_tmp_dh_pkey(SSL *s, EVP_PKEY *dhpkey)
{
if (!ssl_security(s, SSL_SECOP_TMP_DH,
EVP_PKEY_get_security_bits(dhpkey), 0, dhpkey)) {
ERR_raise(ERR_LIB_SSL, SSL_R_DH_KEY_TOO_SMALL);
return 0;
}
EVP_PKEY_free(s->cert->dh_tmp);
s->cert->dh_tmp = dhpkey;
return 1;
}
int SSL_CTX_set0_tmp_dh_pkey(SSL_CTX *ctx, EVP_PKEY *dhpkey)
{
if (!ssl_ctx_security(ctx, SSL_SECOP_TMP_DH,
EVP_PKEY_get_security_bits(dhpkey), 0, dhpkey)) {
ERR_raise(ERR_LIB_SSL, SSL_R_DH_KEY_TOO_SMALL);
return 0;
}
EVP_PKEY_free(ctx->cert->dh_tmp);
ctx->cert->dh_tmp = dhpkey;
return 1;
}
diff --git a/crypto/openssl/ssl/ssl_sess.c b/crypto/openssl/ssl/ssl_sess.c
index d836b33ed0e8..56854fc89023 100644
--- a/crypto/openssl/ssl/ssl_sess.c
+++ b/crypto/openssl/ssl/ssl_sess.c
@@ -1,1398 +1,1420 @@
/*
- * Copyright 1995-2023 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 1995-2024 The OpenSSL Project Authors. All Rights Reserved.
* Copyright 2005 Nokia. All rights reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#if defined(__TANDEM) && defined(_SPT_MODEL_)
# include <spthread.h>
# include <spt_extensions.h> /* timeval */
#endif
#include <stdio.h>
#include <openssl/rand.h>
#include <openssl/engine.h>
#include "internal/refcount.h"
#include "internal/cryptlib.h"
#include "ssl_local.h"
#include "statem/statem_local.h"
static void SSL_SESSION_list_remove(SSL_CTX *ctx, SSL_SESSION *s);
static void SSL_SESSION_list_add(SSL_CTX *ctx, SSL_SESSION *s);
static int remove_session_lock(SSL_CTX *ctx, SSL_SESSION *c, int lck);
DEFINE_STACK_OF(SSL_SESSION)
__owur static int sess_timedout(time_t t, SSL_SESSION *ss)
{
/* if timeout overflowed, it can never timeout! */
if (ss->timeout_ovf)
return 0;
return t > ss->calc_timeout;
}
/*
* Returns -1/0/+1 as other XXXcmp-type functions
* Takes overflow of calculated timeout into consideration
*/
__owur static int timeoutcmp(SSL_SESSION *a, SSL_SESSION *b)
{
/* if only one overflowed, then it is greater */
if (a->timeout_ovf && !b->timeout_ovf)
return 1;
if (!a->timeout_ovf && b->timeout_ovf)
return -1;
/* No overflow, or both overflowed, so straight compare is safe */
if (a->calc_timeout < b->calc_timeout)
return -1;
if (a->calc_timeout > b->calc_timeout)
return 1;
return 0;
}
/*
* Calculates effective timeout, saving overflow state
* Locking must be done by the caller of this function
*/
void ssl_session_calculate_timeout(SSL_SESSION *ss)
{
/* Force positive timeout */
if (ss->timeout < 0)
ss->timeout = 0;
ss->calc_timeout = ss->time + ss->timeout;
/*
* |timeout| is always zero or positive, so the check for
* overflow only needs to consider if |time| is positive
*/
ss->timeout_ovf = ss->time > 0 && ss->calc_timeout < ss->time;
/*
* N.B. Realistic overflow can only occur in our lifetimes on a
* 32-bit machine in January 2038.
* However, There are no controls to limit the |timeout|
* value, except to keep it positive.
*/
}
/*
* SSL_get_session() and SSL_get1_session() are problematic in TLS1.3 because,
* unlike in earlier protocol versions, the session ticket may not have been
* sent yet even though a handshake has finished. The session ticket data could
* come in sometime later...or even change if multiple session ticket messages
* are sent from the server. The preferred way for applications to obtain
* a resumable session is to use SSL_CTX_sess_set_new_cb().
*/
SSL_SESSION *SSL_get_session(const SSL *ssl)
/* aka SSL_get0_session; gets 0 objects, just returns a copy of the pointer */
{
return ssl->session;
}
SSL_SESSION *SSL_get1_session(SSL *ssl)
/* variant of SSL_get_session: caller really gets something */
{
SSL_SESSION *sess;
/*
* Need to lock this all up rather than just use CRYPTO_add so that
* somebody doesn't free ssl->session between when we check it's non-null
* and when we up the reference count.
*/
if (!CRYPTO_THREAD_read_lock(ssl->lock))
return NULL;
sess = ssl->session;
if (sess)
SSL_SESSION_up_ref(sess);
CRYPTO_THREAD_unlock(ssl->lock);
return sess;
}
int SSL_SESSION_set_ex_data(SSL_SESSION *s, int idx, void *arg)
{
return CRYPTO_set_ex_data(&s->ex_data, idx, arg);
}
void *SSL_SESSION_get_ex_data(const SSL_SESSION *s, int idx)
{
return CRYPTO_get_ex_data(&s->ex_data, idx);
}
SSL_SESSION *SSL_SESSION_new(void)
{
SSL_SESSION *ss;
if (!OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS, NULL))
return NULL;
ss = OPENSSL_zalloc(sizeof(*ss));
if (ss == NULL) {
ERR_raise(ERR_LIB_SSL, ERR_R_MALLOC_FAILURE);
return NULL;
}
ss->verify_result = 1; /* avoid 0 (= X509_V_OK) just in case */
ss->references = 1;
ss->timeout = 60 * 5 + 4; /* 5 minute timeout by default */
ss->time = time(NULL);
ssl_session_calculate_timeout(ss);
ss->lock = CRYPTO_THREAD_lock_new();
if (ss->lock == NULL) {
ERR_raise(ERR_LIB_SSL, ERR_R_MALLOC_FAILURE);
OPENSSL_free(ss);
return NULL;
}
if (!CRYPTO_new_ex_data(CRYPTO_EX_INDEX_SSL_SESSION, ss, &ss->ex_data)) {
CRYPTO_THREAD_lock_free(ss->lock);
OPENSSL_free(ss);
return NULL;
}
return ss;
}
-SSL_SESSION *SSL_SESSION_dup(const SSL_SESSION *src)
-{
- return ssl_session_dup(src, 1);
-}
-
/*
* Create a new SSL_SESSION and duplicate the contents of |src| into it. If
* ticket == 0 then no ticket information is duplicated, otherwise it is.
*/
-SSL_SESSION *ssl_session_dup(const SSL_SESSION *src, int ticket)
+static SSL_SESSION *ssl_session_dup_intern(const SSL_SESSION *src, int ticket)
{
SSL_SESSION *dest;
dest = OPENSSL_malloc(sizeof(*dest));
if (dest == NULL) {
goto err;
}
memcpy(dest, src, sizeof(*dest));
/*
* Set the various pointers to NULL so that we can call SSL_SESSION_free in
* the case of an error whilst halfway through constructing dest
*/
#ifndef OPENSSL_NO_PSK
dest->psk_identity_hint = NULL;
dest->psk_identity = NULL;
#endif
dest->ext.hostname = NULL;
dest->ext.tick = NULL;
dest->ext.alpn_selected = NULL;
#ifndef OPENSSL_NO_SRP
dest->srp_username = NULL;
#endif
dest->peer_chain = NULL;
dest->peer = NULL;
dest->ticket_appdata = NULL;
memset(&dest->ex_data, 0, sizeof(dest->ex_data));
/* As the copy is not in the cache, we remove the associated pointers */
dest->prev = NULL;
dest->next = NULL;
dest->owner = NULL;
dest->references = 1;
dest->lock = CRYPTO_THREAD_lock_new();
if (dest->lock == NULL) {
OPENSSL_free(dest);
dest = NULL;
goto err;
}
if (!CRYPTO_new_ex_data(CRYPTO_EX_INDEX_SSL_SESSION, dest, &dest->ex_data))
goto err;
if (src->peer != NULL) {
if (!X509_up_ref(src->peer))
goto err;
dest->peer = src->peer;
}
if (src->peer_chain != NULL) {
dest->peer_chain = X509_chain_up_ref(src->peer_chain);
if (dest->peer_chain == NULL)
goto err;
}
#ifndef OPENSSL_NO_PSK
if (src->psk_identity_hint) {
dest->psk_identity_hint = OPENSSL_strdup(src->psk_identity_hint);
if (dest->psk_identity_hint == NULL) {
goto err;
}
}
if (src->psk_identity) {
dest->psk_identity = OPENSSL_strdup(src->psk_identity);
if (dest->psk_identity == NULL) {
goto err;
}
}
#endif
if (!CRYPTO_dup_ex_data(CRYPTO_EX_INDEX_SSL_SESSION,
&dest->ex_data, &src->ex_data)) {
goto err;
}
if (src->ext.hostname) {
dest->ext.hostname = OPENSSL_strdup(src->ext.hostname);
if (dest->ext.hostname == NULL) {
goto err;
}
}
if (ticket != 0 && src->ext.tick != NULL) {
dest->ext.tick =
OPENSSL_memdup(src->ext.tick, src->ext.ticklen);
if (dest->ext.tick == NULL)
goto err;
} else {
dest->ext.tick_lifetime_hint = 0;
dest->ext.ticklen = 0;
}
if (src->ext.alpn_selected != NULL) {
dest->ext.alpn_selected = OPENSSL_memdup(src->ext.alpn_selected,
src->ext.alpn_selected_len);
if (dest->ext.alpn_selected == NULL)
goto err;
}
#ifndef OPENSSL_NO_SRP
if (src->srp_username) {
dest->srp_username = OPENSSL_strdup(src->srp_username);
if (dest->srp_username == NULL) {
goto err;
}
}
#endif
if (src->ticket_appdata != NULL) {
dest->ticket_appdata =
OPENSSL_memdup(src->ticket_appdata, src->ticket_appdata_len);
if (dest->ticket_appdata == NULL)
goto err;
}
return dest;
err:
ERR_raise(ERR_LIB_SSL, ERR_R_MALLOC_FAILURE);
SSL_SESSION_free(dest);
return NULL;
}
+SSL_SESSION *SSL_SESSION_dup(const SSL_SESSION *src)
+{
+ return ssl_session_dup_intern(src, 1);
+}
+
+/*
+ * Used internally when duplicating a session which might be already shared.
+ * We will have resumed the original session. Subsequently we might have marked
+ * it as non-resumable (e.g. in another thread) - but this copy should be ok to
+ * resume from.
+ */
+SSL_SESSION *ssl_session_dup(const SSL_SESSION *src, int ticket)
+{
+ SSL_SESSION *sess = ssl_session_dup_intern(src, ticket);
+
+ if (sess != NULL)
+ sess->not_resumable = 0;
+
+ return sess;
+}
+
const unsigned char *SSL_SESSION_get_id(const SSL_SESSION *s, unsigned int *len)
{
if (len)
*len = (unsigned int)s->session_id_length;
return s->session_id;
}
const unsigned char *SSL_SESSION_get0_id_context(const SSL_SESSION *s,
unsigned int *len)
{
if (len != NULL)
*len = (unsigned int)s->sid_ctx_length;
return s->sid_ctx;
}
unsigned int SSL_SESSION_get_compress_id(const SSL_SESSION *s)
{
return s->compress_meth;
}
/*
* SSLv3/TLSv1 has 32 bytes (256 bits) of session ID space. As such, filling
* the ID with random junk repeatedly until we have no conflict is going to
* complete in one iteration pretty much "most" of the time (btw:
* understatement). So, if it takes us 10 iterations and we still can't avoid
* a conflict - well that's a reasonable point to call it quits. Either the
* RAND code is broken or someone is trying to open roughly very close to
* 2^256 SSL sessions to our server. How you might store that many sessions
* is perhaps a more interesting question ...
*/
#define MAX_SESS_ID_ATTEMPTS 10
static int def_generate_session_id(SSL *ssl, unsigned char *id,
unsigned int *id_len)
{
unsigned int retry = 0;
do
if (RAND_bytes_ex(ssl->ctx->libctx, id, *id_len, 0) <= 0)
return 0;
while (SSL_has_matching_session_id(ssl, id, *id_len) &&
(++retry < MAX_SESS_ID_ATTEMPTS)) ;
if (retry < MAX_SESS_ID_ATTEMPTS)
return 1;
/* else - woops a session_id match */
/*
* XXX We should also check the external cache -- but the probability of
* a collision is negligible, and we could not prevent the concurrent
* creation of sessions with identical IDs since we currently don't have
* means to atomically check whether a session ID already exists and make
* a reservation for it if it does not (this problem applies to the
* internal cache as well).
*/
return 0;
}
int ssl_generate_session_id(SSL *s, SSL_SESSION *ss)
{
unsigned int tmp;
GEN_SESSION_CB cb = def_generate_session_id;
switch (s->version) {
case SSL3_VERSION:
case TLS1_VERSION:
case TLS1_1_VERSION:
case TLS1_2_VERSION:
case TLS1_3_VERSION:
case DTLS1_BAD_VER:
case DTLS1_VERSION:
case DTLS1_2_VERSION:
ss->session_id_length = SSL3_SSL_SESSION_ID_LENGTH;
break;
default:
SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_UNSUPPORTED_SSL_VERSION);
return 0;
}
/*-
* If RFC5077 ticket, use empty session ID (as server).
* Note that:
* (a) ssl_get_prev_session() does lookahead into the
* ClientHello extensions to find the session ticket.
* When ssl_get_prev_session() fails, statem_srvr.c calls
* ssl_get_new_session() in tls_process_client_hello().
* At that point, it has not yet parsed the extensions,
* however, because of the lookahead, it already knows
* whether a ticket is expected or not.
*
* (b) statem_clnt.c calls ssl_get_new_session() before parsing
* ServerHello extensions, and before recording the session
* ID received from the server, so this block is a noop.
*/
if (s->ext.ticket_expected) {
ss->session_id_length = 0;
return 1;
}
/* Choose which callback will set the session ID */
if (!CRYPTO_THREAD_read_lock(s->lock))
return 0;
if (!CRYPTO_THREAD_read_lock(s->session_ctx->lock)) {
CRYPTO_THREAD_unlock(s->lock);
SSLfatal(s, SSL_AD_INTERNAL_ERROR,
SSL_R_SESSION_ID_CONTEXT_UNINITIALIZED);
return 0;
}
if (s->generate_session_id)
cb = s->generate_session_id;
else if (s->session_ctx->generate_session_id)
cb = s->session_ctx->generate_session_id;
CRYPTO_THREAD_unlock(s->session_ctx->lock);
CRYPTO_THREAD_unlock(s->lock);
/* Choose a session ID */
memset(ss->session_id, 0, ss->session_id_length);
tmp = (int)ss->session_id_length;
if (!cb(s, ss->session_id, &tmp)) {
/* The callback failed */
SSLfatal(s, SSL_AD_INTERNAL_ERROR,
SSL_R_SSL_SESSION_ID_CALLBACK_FAILED);
return 0;
}
/*
* Don't allow the callback to set the session length to zero. nor
* set it higher than it was.
*/
if (tmp == 0 || tmp > ss->session_id_length) {
/* The callback set an illegal length */
SSLfatal(s, SSL_AD_INTERNAL_ERROR,
SSL_R_SSL_SESSION_ID_HAS_BAD_LENGTH);
return 0;
}
ss->session_id_length = tmp;
/* Finally, check for a conflict */
if (SSL_has_matching_session_id(s, ss->session_id,
(unsigned int)ss->session_id_length)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_SSL_SESSION_ID_CONFLICT);
return 0;
}
return 1;
}
int ssl_get_new_session(SSL *s, int session)
{
/* This gets used by clients and servers. */
SSL_SESSION *ss = NULL;
if ((ss = SSL_SESSION_new()) == NULL) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_MALLOC_FAILURE);
return 0;
}
/* If the context has a default timeout, use it */
if (s->session_ctx->session_timeout == 0)
ss->timeout = SSL_get_default_timeout(s);
else
ss->timeout = s->session_ctx->session_timeout;
ssl_session_calculate_timeout(ss);
SSL_SESSION_free(s->session);
s->session = NULL;
if (session) {
if (SSL_IS_TLS13(s)) {
/*
* We generate the session id while constructing the
* NewSessionTicket in TLSv1.3.
*/
ss->session_id_length = 0;
} else if (!ssl_generate_session_id(s, ss)) {
/* SSLfatal() already called */
SSL_SESSION_free(ss);
return 0;
}
} else {
ss->session_id_length = 0;
}
if (s->sid_ctx_length > sizeof(ss->sid_ctx)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
SSL_SESSION_free(ss);
return 0;
}
memcpy(ss->sid_ctx, s->sid_ctx, s->sid_ctx_length);
ss->sid_ctx_length = s->sid_ctx_length;
s->session = ss;
ss->ssl_version = s->version;
ss->verify_result = X509_V_OK;
/* If client supports extended master secret set it in session */
if (s->s3.flags & TLS1_FLAGS_RECEIVED_EXTMS)
ss->flags |= SSL_SESS_FLAG_EXTMS;
return 1;
}
SSL_SESSION *lookup_sess_in_cache(SSL *s, const unsigned char *sess_id,
size_t sess_id_len)
{
SSL_SESSION *ret = NULL;
if ((s->session_ctx->session_cache_mode
& SSL_SESS_CACHE_NO_INTERNAL_LOOKUP) == 0) {
SSL_SESSION data;
data.ssl_version = s->version;
if (!ossl_assert(sess_id_len <= SSL_MAX_SSL_SESSION_ID_LENGTH))
return NULL;
memcpy(data.session_id, sess_id, sess_id_len);
data.session_id_length = sess_id_len;
if (!CRYPTO_THREAD_read_lock(s->session_ctx->lock))
return NULL;
ret = lh_SSL_SESSION_retrieve(s->session_ctx->sessions, &data);
if (ret != NULL) {
/* don't allow other threads to steal it: */
SSL_SESSION_up_ref(ret);
}
CRYPTO_THREAD_unlock(s->session_ctx->lock);
if (ret == NULL)
ssl_tsan_counter(s->session_ctx, &s->session_ctx->stats.sess_miss);
}
if (ret == NULL && s->session_ctx->get_session_cb != NULL) {
int copy = 1;
ret = s->session_ctx->get_session_cb(s, sess_id, sess_id_len, &copy);
if (ret != NULL) {
+ if (ret->not_resumable) {
+ /* If its not resumable then ignore this session */
+ if (!copy)
+ SSL_SESSION_free(ret);
+ return NULL;
+ }
ssl_tsan_counter(s->session_ctx,
&s->session_ctx->stats.sess_cb_hit);
/*
* Increment reference count now if the session callback asks us
* to do so (note that if the session structures returned by the
* callback are shared between threads, it must handle the
* reference count itself [i.e. copy == 0], or things won't be
* thread-safe).
*/
if (copy)
SSL_SESSION_up_ref(ret);
/*
* Add the externally cached session to the internal cache as
* well if and only if we are supposed to.
*/
if ((s->session_ctx->session_cache_mode &
SSL_SESS_CACHE_NO_INTERNAL_STORE) == 0) {
/*
* Either return value of SSL_CTX_add_session should not
* interrupt the session resumption process. The return
* value is intentionally ignored.
*/
(void)SSL_CTX_add_session(s->session_ctx, ret);
}
}
}
return ret;
}
/*-
* ssl_get_prev attempts to find an SSL_SESSION to be used to resume this
* connection. It is only called by servers.
*
* hello: The parsed ClientHello data
*
* Returns:
* -1: fatal error
* 0: no session found
* 1: a session may have been found.
*
* Side effects:
* - If a session is found then s->session is pointed at it (after freeing an
* existing session if need be) and s->verify_result is set from the session.
* - Both for new and resumed sessions, s->ext.ticket_expected is set to 1
* if the server should issue a new session ticket (to 0 otherwise).
*/
int ssl_get_prev_session(SSL *s, CLIENTHELLO_MSG *hello)
{
/* This is used only by servers. */
SSL_SESSION *ret = NULL;
int fatal = 0;
int try_session_cache = 0;
SSL_TICKET_STATUS r;
if (SSL_IS_TLS13(s)) {
/*
* By default we will send a new ticket. This can be overridden in the
* ticket processing.
*/
s->ext.ticket_expected = 1;
if (!tls_parse_extension(s, TLSEXT_IDX_psk_kex_modes,
SSL_EXT_CLIENT_HELLO, hello->pre_proc_exts,
NULL, 0)
|| !tls_parse_extension(s, TLSEXT_IDX_psk, SSL_EXT_CLIENT_HELLO,
hello->pre_proc_exts, NULL, 0))
return -1;
ret = s->session;
} else {
/* sets s->ext.ticket_expected */
r = tls_get_ticket_from_client(s, hello, &ret);
switch (r) {
case SSL_TICKET_FATAL_ERR_MALLOC:
case SSL_TICKET_FATAL_ERR_OTHER:
fatal = 1;
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
goto err;
case SSL_TICKET_NONE:
case SSL_TICKET_EMPTY:
if (hello->session_id_len > 0) {
try_session_cache = 1;
ret = lookup_sess_in_cache(s, hello->session_id,
hello->session_id_len);
}
break;
case SSL_TICKET_NO_DECRYPT:
case SSL_TICKET_SUCCESS:
case SSL_TICKET_SUCCESS_RENEW:
break;
}
}
if (ret == NULL)
goto err;
/* Now ret is non-NULL and we own one of its reference counts. */
/* Check TLS version consistency */
if (ret->ssl_version != s->version)
goto err;
if (ret->sid_ctx_length != s->sid_ctx_length
|| memcmp(ret->sid_ctx, s->sid_ctx, ret->sid_ctx_length)) {
/*
* We have the session requested by the client, but we don't want to
* use it in this context.
*/
goto err; /* treat like cache miss */
}
if ((s->verify_mode & SSL_VERIFY_PEER) && s->sid_ctx_length == 0) {
/*
* We can't be sure if this session is being used out of context,
* which is especially important for SSL_VERIFY_PEER. The application
* should have used SSL[_CTX]_set_session_id_context. For this error
* case, we generate an error instead of treating the event like a
* cache miss (otherwise it would be easy for applications to
* effectively disable the session cache by accident without anyone
* noticing).
*/
SSLfatal(s, SSL_AD_INTERNAL_ERROR,
SSL_R_SESSION_ID_CONTEXT_UNINITIALIZED);
fatal = 1;
goto err;
}
if (sess_timedout(time(NULL), ret)) {
ssl_tsan_counter(s->session_ctx, &s->session_ctx->stats.sess_timeout);
if (try_session_cache) {
/* session was from the cache, so remove it */
SSL_CTX_remove_session(s->session_ctx, ret);
}
goto err;
}
/* Check extended master secret extension consistency */
if (ret->flags & SSL_SESS_FLAG_EXTMS) {
/* If old session includes extms, but new does not: abort handshake */
if (!(s->s3.flags & TLS1_FLAGS_RECEIVED_EXTMS)) {
SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_INCONSISTENT_EXTMS);
fatal = 1;
goto err;
}
} else if (s->s3.flags & TLS1_FLAGS_RECEIVED_EXTMS) {
/* If new session includes extms, but old does not: do not resume */
goto err;
}
if (!SSL_IS_TLS13(s)) {
/* We already did this for TLS1.3 */
SSL_SESSION_free(s->session);
s->session = ret;
}
ssl_tsan_counter(s->session_ctx, &s->session_ctx->stats.sess_hit);
s->verify_result = s->session->verify_result;
return 1;
err:
if (ret != NULL) {
SSL_SESSION_free(ret);
/* In TLSv1.3 s->session was already set to ret, so we NULL it out */
if (SSL_IS_TLS13(s))
s->session = NULL;
if (!try_session_cache) {
/*
* The session was from a ticket, so we should issue a ticket for
* the new session
*/
s->ext.ticket_expected = 1;
}
}
if (fatal)
return -1;
return 0;
}
int SSL_CTX_add_session(SSL_CTX *ctx, SSL_SESSION *c)
{
int ret = 0;
SSL_SESSION *s;
/*
* add just 1 reference count for the SSL_CTX's session cache even though
* it has two ways of access: each session is in a doubly linked list and
* an lhash
*/
SSL_SESSION_up_ref(c);
/*
* if session c is in already in cache, we take back the increment later
*/
if (!CRYPTO_THREAD_write_lock(ctx->lock)) {
SSL_SESSION_free(c);
return 0;
}
s = lh_SSL_SESSION_insert(ctx->sessions, c);
/*
* s != NULL iff we already had a session with the given PID. In this
* case, s == c should hold (then we did not really modify
* ctx->sessions), or we're in trouble.
*/
if (s != NULL && s != c) {
/* We *are* in trouble ... */
SSL_SESSION_list_remove(ctx, s);
SSL_SESSION_free(s);
/*
* ... so pretend the other session did not exist in cache (we cannot
* handle two SSL_SESSION structures with identical session ID in the
* same cache, which could happen e.g. when two threads concurrently
* obtain the same session from an external cache)
*/
s = NULL;
} else if (s == NULL &&
lh_SSL_SESSION_retrieve(ctx->sessions, c) == NULL) {
/* s == NULL can also mean OOM error in lh_SSL_SESSION_insert ... */
/*
* ... so take back the extra reference and also don't add
* the session to the SSL_SESSION_list at this time
*/
s = c;
}
/* Adjust last used time, and add back into the cache at the appropriate spot */
if (ctx->session_cache_mode & SSL_SESS_CACHE_UPDATE_TIME) {
c->time = time(NULL);
ssl_session_calculate_timeout(c);
}
if (s == NULL) {
/*
* new cache entry -- remove old ones if cache has become too large
* delete cache entry *before* add, so we don't remove the one we're adding!
*/
ret = 1;
if (SSL_CTX_sess_get_cache_size(ctx) > 0) {
while (SSL_CTX_sess_number(ctx) >= SSL_CTX_sess_get_cache_size(ctx)) {
if (!remove_session_lock(ctx, ctx->session_cache_tail, 0))
break;
else
ssl_tsan_counter(ctx, &ctx->stats.sess_cache_full);
}
}
}
SSL_SESSION_list_add(ctx, c);
if (s != NULL) {
/*
* existing cache entry -- decrement previously incremented reference
* count because it already takes into account the cache
*/
SSL_SESSION_free(s); /* s == c */
ret = 0;
}
CRYPTO_THREAD_unlock(ctx->lock);
return ret;
}
int SSL_CTX_remove_session(SSL_CTX *ctx, SSL_SESSION *c)
{
return remove_session_lock(ctx, c, 1);
}
static int remove_session_lock(SSL_CTX *ctx, SSL_SESSION *c, int lck)
{
SSL_SESSION *r;
int ret = 0;
if ((c != NULL) && (c->session_id_length != 0)) {
if (lck) {
if (!CRYPTO_THREAD_write_lock(ctx->lock))
return 0;
}
if ((r = lh_SSL_SESSION_retrieve(ctx->sessions, c)) != NULL) {
ret = 1;
r = lh_SSL_SESSION_delete(ctx->sessions, r);
SSL_SESSION_list_remove(ctx, r);
}
c->not_resumable = 1;
if (lck)
CRYPTO_THREAD_unlock(ctx->lock);
if (ctx->remove_session_cb != NULL)
ctx->remove_session_cb(ctx, c);
if (ret)
SSL_SESSION_free(r);
}
return ret;
}
void SSL_SESSION_free(SSL_SESSION *ss)
{
int i;
if (ss == NULL)
return;
CRYPTO_DOWN_REF(&ss->references, &i, ss->lock);
REF_PRINT_COUNT("SSL_SESSION", ss);
if (i > 0)
return;
REF_ASSERT_ISNT(i < 0);
CRYPTO_free_ex_data(CRYPTO_EX_INDEX_SSL_SESSION, ss, &ss->ex_data);
OPENSSL_cleanse(ss->master_key, sizeof(ss->master_key));
OPENSSL_cleanse(ss->session_id, sizeof(ss->session_id));
X509_free(ss->peer);
sk_X509_pop_free(ss->peer_chain, X509_free);
OPENSSL_free(ss->ext.hostname);
OPENSSL_free(ss->ext.tick);
#ifndef OPENSSL_NO_PSK
OPENSSL_free(ss->psk_identity_hint);
OPENSSL_free(ss->psk_identity);
#endif
#ifndef OPENSSL_NO_SRP
OPENSSL_free(ss->srp_username);
#endif
OPENSSL_free(ss->ext.alpn_selected);
OPENSSL_free(ss->ticket_appdata);
CRYPTO_THREAD_lock_free(ss->lock);
OPENSSL_clear_free(ss, sizeof(*ss));
}
int SSL_SESSION_up_ref(SSL_SESSION *ss)
{
int i;
if (CRYPTO_UP_REF(&ss->references, &i, ss->lock) <= 0)
return 0;
REF_PRINT_COUNT("SSL_SESSION", ss);
REF_ASSERT_ISNT(i < 2);
return ((i > 1) ? 1 : 0);
}
int SSL_set_session(SSL *s, SSL_SESSION *session)
{
ssl_clear_bad_session(s);
if (s->ctx->method != s->method) {
if (!SSL_set_ssl_method(s, s->ctx->method))
return 0;
}
if (session != NULL) {
SSL_SESSION_up_ref(session);
s->verify_result = session->verify_result;
}
SSL_SESSION_free(s->session);
s->session = session;
return 1;
}
int SSL_SESSION_set1_id(SSL_SESSION *s, const unsigned char *sid,
unsigned int sid_len)
{
if (sid_len > SSL_MAX_SSL_SESSION_ID_LENGTH) {
ERR_raise(ERR_LIB_SSL, SSL_R_SSL_SESSION_ID_TOO_LONG);
return 0;
}
s->session_id_length = sid_len;
if (sid != s->session_id)
memcpy(s->session_id, sid, sid_len);
return 1;
}
long SSL_SESSION_set_timeout(SSL_SESSION *s, long t)
{
time_t new_timeout = (time_t)t;
if (s == NULL || t < 0)
return 0;
if (s->owner != NULL) {
if (!CRYPTO_THREAD_write_lock(s->owner->lock))
return 0;
s->timeout = new_timeout;
ssl_session_calculate_timeout(s);
SSL_SESSION_list_add(s->owner, s);
CRYPTO_THREAD_unlock(s->owner->lock);
} else {
s->timeout = new_timeout;
ssl_session_calculate_timeout(s);
}
return 1;
}
long SSL_SESSION_get_timeout(const SSL_SESSION *s)
{
if (s == NULL)
return 0;
return (long)s->timeout;
}
long SSL_SESSION_get_time(const SSL_SESSION *s)
{
if (s == NULL)
return 0;
return (long)s->time;
}
long SSL_SESSION_set_time(SSL_SESSION *s, long t)
{
time_t new_time = (time_t)t;
if (s == NULL)
return 0;
if (s->owner != NULL) {
if (!CRYPTO_THREAD_write_lock(s->owner->lock))
return 0;
s->time = new_time;
ssl_session_calculate_timeout(s);
SSL_SESSION_list_add(s->owner, s);
CRYPTO_THREAD_unlock(s->owner->lock);
} else {
s->time = new_time;
ssl_session_calculate_timeout(s);
}
return t;
}
int SSL_SESSION_get_protocol_version(const SSL_SESSION *s)
{
return s->ssl_version;
}
int SSL_SESSION_set_protocol_version(SSL_SESSION *s, int version)
{
s->ssl_version = version;
return 1;
}
const SSL_CIPHER *SSL_SESSION_get0_cipher(const SSL_SESSION *s)
{
return s->cipher;
}
int SSL_SESSION_set_cipher(SSL_SESSION *s, const SSL_CIPHER *cipher)
{
s->cipher = cipher;
return 1;
}
const char *SSL_SESSION_get0_hostname(const SSL_SESSION *s)
{
return s->ext.hostname;
}
int SSL_SESSION_set1_hostname(SSL_SESSION *s, const char *hostname)
{
OPENSSL_free(s->ext.hostname);
if (hostname == NULL) {
s->ext.hostname = NULL;
return 1;
}
s->ext.hostname = OPENSSL_strdup(hostname);
return s->ext.hostname != NULL;
}
int SSL_SESSION_has_ticket(const SSL_SESSION *s)
{
return (s->ext.ticklen > 0) ? 1 : 0;
}
unsigned long SSL_SESSION_get_ticket_lifetime_hint(const SSL_SESSION *s)
{
return s->ext.tick_lifetime_hint;
}
void SSL_SESSION_get0_ticket(const SSL_SESSION *s, const unsigned char **tick,
size_t *len)
{
*len = s->ext.ticklen;
if (tick != NULL)
*tick = s->ext.tick;
}
uint32_t SSL_SESSION_get_max_early_data(const SSL_SESSION *s)
{
return s->ext.max_early_data;
}
int SSL_SESSION_set_max_early_data(SSL_SESSION *s, uint32_t max_early_data)
{
s->ext.max_early_data = max_early_data;
return 1;
}
void SSL_SESSION_get0_alpn_selected(const SSL_SESSION *s,
const unsigned char **alpn,
size_t *len)
{
*alpn = s->ext.alpn_selected;
*len = s->ext.alpn_selected_len;
}
int SSL_SESSION_set1_alpn_selected(SSL_SESSION *s, const unsigned char *alpn,
size_t len)
{
OPENSSL_free(s->ext.alpn_selected);
if (alpn == NULL || len == 0) {
s->ext.alpn_selected = NULL;
s->ext.alpn_selected_len = 0;
return 1;
}
s->ext.alpn_selected = OPENSSL_memdup(alpn, len);
if (s->ext.alpn_selected == NULL) {
s->ext.alpn_selected_len = 0;
return 0;
}
s->ext.alpn_selected_len = len;
return 1;
}
X509 *SSL_SESSION_get0_peer(SSL_SESSION *s)
{
return s->peer;
}
int SSL_SESSION_set1_id_context(SSL_SESSION *s, const unsigned char *sid_ctx,
unsigned int sid_ctx_len)
{
if (sid_ctx_len > SSL_MAX_SID_CTX_LENGTH) {
ERR_raise(ERR_LIB_SSL, SSL_R_SSL_SESSION_ID_CONTEXT_TOO_LONG);
return 0;
}
s->sid_ctx_length = sid_ctx_len;
if (sid_ctx != s->sid_ctx)
memcpy(s->sid_ctx, sid_ctx, sid_ctx_len);
return 1;
}
int SSL_SESSION_is_resumable(const SSL_SESSION *s)
{
/*
* In the case of EAP-FAST, we can have a pre-shared "ticket" without a
* session ID.
*/
return !s->not_resumable
&& (s->session_id_length > 0 || s->ext.ticklen > 0);
}
long SSL_CTX_set_timeout(SSL_CTX *s, long t)
{
long l;
if (s == NULL)
return 0;
l = s->session_timeout;
s->session_timeout = t;
return l;
}
long SSL_CTX_get_timeout(const SSL_CTX *s)
{
if (s == NULL)
return 0;
return s->session_timeout;
}
int SSL_set_session_secret_cb(SSL *s,
tls_session_secret_cb_fn tls_session_secret_cb,
void *arg)
{
if (s == NULL)
return 0;
s->ext.session_secret_cb = tls_session_secret_cb;
s->ext.session_secret_cb_arg = arg;
return 1;
}
int SSL_set_session_ticket_ext_cb(SSL *s, tls_session_ticket_ext_cb_fn cb,
void *arg)
{
if (s == NULL)
return 0;
s->ext.session_ticket_cb = cb;
s->ext.session_ticket_cb_arg = arg;
return 1;
}
int SSL_set_session_ticket_ext(SSL *s, void *ext_data, int ext_len)
{
if (s->version >= TLS1_VERSION) {
OPENSSL_free(s->ext.session_ticket);
s->ext.session_ticket = NULL;
s->ext.session_ticket =
OPENSSL_malloc(sizeof(TLS_SESSION_TICKET_EXT) + ext_len);
if (s->ext.session_ticket == NULL) {
ERR_raise(ERR_LIB_SSL, ERR_R_MALLOC_FAILURE);
return 0;
}
if (ext_data != NULL) {
s->ext.session_ticket->length = ext_len;
s->ext.session_ticket->data = s->ext.session_ticket + 1;
memcpy(s->ext.session_ticket->data, ext_data, ext_len);
} else {
s->ext.session_ticket->length = 0;
s->ext.session_ticket->data = NULL;
}
return 1;
}
return 0;
}
void SSL_CTX_flush_sessions(SSL_CTX *s, long t)
{
STACK_OF(SSL_SESSION) *sk;
SSL_SESSION *current;
unsigned long i;
if (!CRYPTO_THREAD_write_lock(s->lock))
return;
sk = sk_SSL_SESSION_new_null();
i = lh_SSL_SESSION_get_down_load(s->sessions);
lh_SSL_SESSION_set_down_load(s->sessions, 0);
/*
* Iterate over the list from the back (oldest), and stop
* when a session can no longer be removed.
* Add the session to a temporary list to be freed outside
* the SSL_CTX lock.
* But still do the remove_session_cb() within the lock.
*/
while (s->session_cache_tail != NULL) {
current = s->session_cache_tail;
if (t == 0 || sess_timedout((time_t)t, current)) {
lh_SSL_SESSION_delete(s->sessions, current);
SSL_SESSION_list_remove(s, current);
current->not_resumable = 1;
if (s->remove_session_cb != NULL)
s->remove_session_cb(s, current);
/*
* Throw the session on a stack, it's entirely plausible
* that while freeing outside the critical section, the
* session could be re-added, so avoid using the next/prev
* pointers. If the stack failed to create, or the session
* couldn't be put on the stack, just free it here
*/
if (sk == NULL || !sk_SSL_SESSION_push(sk, current))
SSL_SESSION_free(current);
} else {
break;
}
}
lh_SSL_SESSION_set_down_load(s->sessions, i);
CRYPTO_THREAD_unlock(s->lock);
sk_SSL_SESSION_pop_free(sk, SSL_SESSION_free);
}
int ssl_clear_bad_session(SSL *s)
{
if ((s->session != NULL) &&
!(s->shutdown & SSL_SENT_SHUTDOWN) &&
!(SSL_in_init(s) || SSL_in_before(s))) {
SSL_CTX_remove_session(s->session_ctx, s->session);
return 1;
} else
return 0;
}
/* locked by SSL_CTX in the calling function */
static void SSL_SESSION_list_remove(SSL_CTX *ctx, SSL_SESSION *s)
{
if ((s->next == NULL) || (s->prev == NULL))
return;
if (s->next == (SSL_SESSION *)&(ctx->session_cache_tail)) {
/* last element in list */
if (s->prev == (SSL_SESSION *)&(ctx->session_cache_head)) {
/* only one element in list */
ctx->session_cache_head = NULL;
ctx->session_cache_tail = NULL;
} else {
ctx->session_cache_tail = s->prev;
s->prev->next = (SSL_SESSION *)&(ctx->session_cache_tail);
}
} else {
if (s->prev == (SSL_SESSION *)&(ctx->session_cache_head)) {
/* first element in list */
ctx->session_cache_head = s->next;
s->next->prev = (SSL_SESSION *)&(ctx->session_cache_head);
} else {
/* middle of list */
s->next->prev = s->prev;
s->prev->next = s->next;
}
}
s->prev = s->next = NULL;
s->owner = NULL;
}
static void SSL_SESSION_list_add(SSL_CTX *ctx, SSL_SESSION *s)
{
SSL_SESSION *next;
if ((s->next != NULL) && (s->prev != NULL))
SSL_SESSION_list_remove(ctx, s);
if (ctx->session_cache_head == NULL) {
ctx->session_cache_head = s;
ctx->session_cache_tail = s;
s->prev = (SSL_SESSION *)&(ctx->session_cache_head);
s->next = (SSL_SESSION *)&(ctx->session_cache_tail);
} else {
if (timeoutcmp(s, ctx->session_cache_head) >= 0) {
/*
* if we timeout after (or the same time as) the first
* session, put us first - usual case
*/
s->next = ctx->session_cache_head;
s->next->prev = s;
s->prev = (SSL_SESSION *)&(ctx->session_cache_head);
ctx->session_cache_head = s;
} else if (timeoutcmp(s, ctx->session_cache_tail) < 0) {
/* if we timeout before the last session, put us last */
s->prev = ctx->session_cache_tail;
s->prev->next = s;
s->next = (SSL_SESSION *)&(ctx->session_cache_tail);
ctx->session_cache_tail = s;
} else {
/*
* we timeout somewhere in-between - if there is only
* one session in the cache it will be caught above
*/
next = ctx->session_cache_head->next;
while (next != (SSL_SESSION*)&(ctx->session_cache_tail)) {
if (timeoutcmp(s, next) >= 0) {
s->next = next;
s->prev = next->prev;
next->prev->next = s;
next->prev = s;
break;
}
next = next->next;
}
}
}
s->owner = ctx;
}
void SSL_CTX_sess_set_new_cb(SSL_CTX *ctx,
int (*cb) (struct ssl_st *ssl, SSL_SESSION *sess))
{
ctx->new_session_cb = cb;
}
int (*SSL_CTX_sess_get_new_cb(SSL_CTX *ctx)) (SSL *ssl, SSL_SESSION *sess) {
return ctx->new_session_cb;
}
void SSL_CTX_sess_set_remove_cb(SSL_CTX *ctx,
void (*cb) (SSL_CTX *ctx, SSL_SESSION *sess))
{
ctx->remove_session_cb = cb;
}
void (*SSL_CTX_sess_get_remove_cb(SSL_CTX *ctx)) (SSL_CTX *ctx,
SSL_SESSION *sess) {
return ctx->remove_session_cb;
}
void SSL_CTX_sess_set_get_cb(SSL_CTX *ctx,
SSL_SESSION *(*cb) (struct ssl_st *ssl,
const unsigned char *data,
int len, int *copy))
{
ctx->get_session_cb = cb;
}
SSL_SESSION *(*SSL_CTX_sess_get_get_cb(SSL_CTX *ctx)) (SSL *ssl,
const unsigned char
*data, int len,
int *copy) {
return ctx->get_session_cb;
}
void SSL_CTX_set_info_callback(SSL_CTX *ctx,
void (*cb) (const SSL *ssl, int type, int val))
{
ctx->info_callback = cb;
}
void (*SSL_CTX_get_info_callback(SSL_CTX *ctx)) (const SSL *ssl, int type,
int val) {
return ctx->info_callback;
}
void SSL_CTX_set_client_cert_cb(SSL_CTX *ctx,
int (*cb) (SSL *ssl, X509 **x509,
EVP_PKEY **pkey))
{
ctx->client_cert_cb = cb;
}
int (*SSL_CTX_get_client_cert_cb(SSL_CTX *ctx)) (SSL *ssl, X509 **x509,
EVP_PKEY **pkey) {
return ctx->client_cert_cb;
}
void SSL_CTX_set_cookie_generate_cb(SSL_CTX *ctx,
int (*cb) (SSL *ssl,
unsigned char *cookie,
unsigned int *cookie_len))
{
ctx->app_gen_cookie_cb = cb;
}
void SSL_CTX_set_cookie_verify_cb(SSL_CTX *ctx,
int (*cb) (SSL *ssl,
const unsigned char *cookie,
unsigned int cookie_len))
{
ctx->app_verify_cookie_cb = cb;
}
int SSL_SESSION_set1_ticket_appdata(SSL_SESSION *ss, const void *data, size_t len)
{
OPENSSL_free(ss->ticket_appdata);
ss->ticket_appdata_len = 0;
if (data == NULL || len == 0) {
ss->ticket_appdata = NULL;
return 1;
}
ss->ticket_appdata = OPENSSL_memdup(data, len);
if (ss->ticket_appdata != NULL) {
ss->ticket_appdata_len = len;
return 1;
}
return 0;
}
int SSL_SESSION_get0_ticket_appdata(SSL_SESSION *ss, void **data, size_t *len)
{
*data = ss->ticket_appdata;
*len = ss->ticket_appdata_len;
return 1;
}
void SSL_CTX_set_stateless_cookie_generate_cb(
SSL_CTX *ctx,
int (*cb) (SSL *ssl,
unsigned char *cookie,
size_t *cookie_len))
{
ctx->gen_stateless_cookie_cb = cb;
}
void SSL_CTX_set_stateless_cookie_verify_cb(
SSL_CTX *ctx,
int (*cb) (SSL *ssl,
const unsigned char *cookie,
size_t cookie_len))
{
ctx->verify_stateless_cookie_cb = cb;
}
IMPLEMENT_PEM_rw(SSL_SESSION, SSL_SESSION, PEM_STRING_SSL_SESSION, SSL_SESSION)
diff --git a/crypto/openssl/ssl/statem/statem_srvr.c b/crypto/openssl/ssl/statem/statem_srvr.c
index a9e67f9d32a7..df7c868eff71 100644
--- a/crypto/openssl/ssl/statem/statem_srvr.c
+++ b/crypto/openssl/ssl/statem/statem_srvr.c
@@ -1,4138 +1,4137 @@
/*
- * Copyright 1995-2022 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 1995-2024 The OpenSSL Project Authors. All Rights Reserved.
* Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved
* Copyright 2005 Nokia. All rights reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <stdio.h>
#include "../ssl_local.h"
#include "statem_local.h"
#include "internal/constant_time.h"
#include "internal/cryptlib.h"
#include <openssl/buffer.h>
#include <openssl/rand.h>
#include <openssl/objects.h>
#include <openssl/evp.h>
#include <openssl/x509.h>
#include <openssl/dh.h>
#include <openssl/rsa.h>
#include <openssl/bn.h>
#include <openssl/md5.h>
#include <openssl/trace.h>
#include <openssl/core_names.h>
#include <openssl/asn1t.h>
#define TICKET_NONCE_SIZE 8
typedef struct {
ASN1_TYPE *kxBlob;
ASN1_TYPE *opaqueBlob;
} GOST_KX_MESSAGE;
DECLARE_ASN1_FUNCTIONS(GOST_KX_MESSAGE)
ASN1_SEQUENCE(GOST_KX_MESSAGE) = {
ASN1_SIMPLE(GOST_KX_MESSAGE, kxBlob, ASN1_ANY),
ASN1_OPT(GOST_KX_MESSAGE, opaqueBlob, ASN1_ANY),
} ASN1_SEQUENCE_END(GOST_KX_MESSAGE)
IMPLEMENT_ASN1_FUNCTIONS(GOST_KX_MESSAGE)
static int tls_construct_encrypted_extensions(SSL *s, WPACKET *pkt);
/*
* ossl_statem_server13_read_transition() encapsulates the logic for the allowed
* handshake state transitions when a TLSv1.3 server is reading messages from
* the client. The message type that the client has sent is provided in |mt|.
* The current state is in |s->statem.hand_state|.
*
* Return values are 1 for success (transition allowed) and 0 on error
* (transition not allowed)
*/
static int ossl_statem_server13_read_transition(SSL *s, int mt)
{
OSSL_STATEM *st = &s->statem;
/*
* Note: There is no case for TLS_ST_BEFORE because at that stage we have
* not negotiated TLSv1.3 yet, so that case is handled by
* ossl_statem_server_read_transition()
*/
switch (st->hand_state) {
default:
break;
case TLS_ST_EARLY_DATA:
if (s->hello_retry_request == SSL_HRR_PENDING) {
if (mt == SSL3_MT_CLIENT_HELLO) {
st->hand_state = TLS_ST_SR_CLNT_HELLO;
return 1;
}
break;
} else if (s->ext.early_data == SSL_EARLY_DATA_ACCEPTED) {
if (mt == SSL3_MT_END_OF_EARLY_DATA) {
st->hand_state = TLS_ST_SR_END_OF_EARLY_DATA;
return 1;
}
break;
}
/* Fall through */
case TLS_ST_SR_END_OF_EARLY_DATA:
case TLS_ST_SW_FINISHED:
if (s->s3.tmp.cert_request) {
if (mt == SSL3_MT_CERTIFICATE) {
st->hand_state = TLS_ST_SR_CERT;
return 1;
}
} else {
if (mt == SSL3_MT_FINISHED) {
st->hand_state = TLS_ST_SR_FINISHED;
return 1;
}
}
break;
case TLS_ST_SR_CERT:
if (s->session->peer == NULL) {
if (mt == SSL3_MT_FINISHED) {
st->hand_state = TLS_ST_SR_FINISHED;
return 1;
}
} else {
if (mt == SSL3_MT_CERTIFICATE_VERIFY) {
st->hand_state = TLS_ST_SR_CERT_VRFY;
return 1;
}
}
break;
case TLS_ST_SR_CERT_VRFY:
if (mt == SSL3_MT_FINISHED) {
st->hand_state = TLS_ST_SR_FINISHED;
return 1;
}
break;
case TLS_ST_OK:
/*
* Its never ok to start processing handshake messages in the middle of
* early data (i.e. before we've received the end of early data alert)
*/
if (s->early_data_state == SSL_EARLY_DATA_READING)
break;
if (mt == SSL3_MT_CERTIFICATE
&& s->post_handshake_auth == SSL_PHA_REQUESTED) {
st->hand_state = TLS_ST_SR_CERT;
return 1;
}
if (mt == SSL3_MT_KEY_UPDATE) {
st->hand_state = TLS_ST_SR_KEY_UPDATE;
return 1;
}
break;
}
/* No valid transition found */
return 0;
}
/*
* ossl_statem_server_read_transition() encapsulates the logic for the allowed
* handshake state transitions when the server is reading messages from the
* client. The message type that the client has sent is provided in |mt|. The
* current state is in |s->statem.hand_state|.
*
* Return values are 1 for success (transition allowed) and 0 on error
* (transition not allowed)
*/
int ossl_statem_server_read_transition(SSL *s, int mt)
{
OSSL_STATEM *st = &s->statem;
if (SSL_IS_TLS13(s)) {
if (!ossl_statem_server13_read_transition(s, mt))
goto err;
return 1;
}
switch (st->hand_state) {
default:
break;
case TLS_ST_BEFORE:
case TLS_ST_OK:
case DTLS_ST_SW_HELLO_VERIFY_REQUEST:
if (mt == SSL3_MT_CLIENT_HELLO) {
st->hand_state = TLS_ST_SR_CLNT_HELLO;
return 1;
}
break;
case TLS_ST_SW_SRVR_DONE:
/*
* If we get a CKE message after a ServerDone then either
* 1) We didn't request a Certificate
* OR
* 2) If we did request one then
* a) We allow no Certificate to be returned
* AND
* b) We are running SSL3 (in TLS1.0+ the client must return a 0
* list if we requested a certificate)
*/
if (mt == SSL3_MT_CLIENT_KEY_EXCHANGE) {
if (s->s3.tmp.cert_request) {
if (s->version == SSL3_VERSION) {
if ((s->verify_mode & SSL_VERIFY_PEER)
&& (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) {
/*
* This isn't an unexpected message as such - we're just
* not going to accept it because we require a client
* cert.
*/
SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
return 0;
}
st->hand_state = TLS_ST_SR_KEY_EXCH;
return 1;
}
} else {
st->hand_state = TLS_ST_SR_KEY_EXCH;
return 1;
}
} else if (s->s3.tmp.cert_request) {
if (mt == SSL3_MT_CERTIFICATE) {
st->hand_state = TLS_ST_SR_CERT;
return 1;
}
}
break;
case TLS_ST_SR_CERT:
if (mt == SSL3_MT_CLIENT_KEY_EXCHANGE) {
st->hand_state = TLS_ST_SR_KEY_EXCH;
return 1;
}
break;
case TLS_ST_SR_KEY_EXCH:
/*
* We should only process a CertificateVerify message if we have
* received a Certificate from the client. If so then |s->session->peer|
* will be non NULL. In some instances a CertificateVerify message is
* not required even if the peer has sent a Certificate (e.g. such as in
* the case of static DH). In that case |st->no_cert_verify| should be
* set.
*/
if (s->session->peer == NULL || st->no_cert_verify) {
if (mt == SSL3_MT_CHANGE_CIPHER_SPEC) {
/*
* For the ECDH ciphersuites when the client sends its ECDH
* pub key in a certificate, the CertificateVerify message is
* not sent. Also for GOST ciphersuites when the client uses
* its key from the certificate for key exchange.
*/
st->hand_state = TLS_ST_SR_CHANGE;
return 1;
}
} else {
if (mt == SSL3_MT_CERTIFICATE_VERIFY) {
st->hand_state = TLS_ST_SR_CERT_VRFY;
return 1;
}
}
break;
case TLS_ST_SR_CERT_VRFY:
if (mt == SSL3_MT_CHANGE_CIPHER_SPEC) {
st->hand_state = TLS_ST_SR_CHANGE;
return 1;
}
break;
case TLS_ST_SR_CHANGE:
#ifndef OPENSSL_NO_NEXTPROTONEG
if (s->s3.npn_seen) {
if (mt == SSL3_MT_NEXT_PROTO) {
st->hand_state = TLS_ST_SR_NEXT_PROTO;
return 1;
}
} else {
#endif
if (mt == SSL3_MT_FINISHED) {
st->hand_state = TLS_ST_SR_FINISHED;
return 1;
}
#ifndef OPENSSL_NO_NEXTPROTONEG
}
#endif
break;
#ifndef OPENSSL_NO_NEXTPROTONEG
case TLS_ST_SR_NEXT_PROTO:
if (mt == SSL3_MT_FINISHED) {
st->hand_state = TLS_ST_SR_FINISHED;
return 1;
}
break;
#endif
case TLS_ST_SW_FINISHED:
if (mt == SSL3_MT_CHANGE_CIPHER_SPEC) {
st->hand_state = TLS_ST_SR_CHANGE;
return 1;
}
break;
}
err:
/* No valid transition found */
if (SSL_IS_DTLS(s) && mt == SSL3_MT_CHANGE_CIPHER_SPEC) {
BIO *rbio;
/*
* CCS messages don't have a message sequence number so this is probably
* because of an out-of-order CCS. We'll just drop it.
*/
s->init_num = 0;
s->rwstate = SSL_READING;
rbio = SSL_get_rbio(s);
BIO_clear_retry_flags(rbio);
BIO_set_retry_read(rbio);
return 0;
}
SSLfatal(s, SSL3_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_MESSAGE);
return 0;
}
/*
* Should we send a ServerKeyExchange message?
*
* Valid return values are:
* 1: Yes
* 0: No
*/
static int send_server_key_exchange(SSL *s)
{
unsigned long alg_k = s->s3.tmp.new_cipher->algorithm_mkey;
/*
* only send a ServerKeyExchange if DH or fortezza but we have a
* sign only certificate PSK: may send PSK identity hints For
* ECC ciphersuites, we send a serverKeyExchange message only if
* the cipher suite is either ECDH-anon or ECDHE. In other cases,
* the server certificate contains the server's public key for
* key exchange.
*/
if (alg_k & (SSL_kDHE | SSL_kECDHE)
/*
* PSK: send ServerKeyExchange if PSK identity hint if
* provided
*/
#ifndef OPENSSL_NO_PSK
/* Only send SKE if we have identity hint for plain PSK */
|| ((alg_k & (SSL_kPSK | SSL_kRSAPSK))
&& s->cert->psk_identity_hint)
/* For other PSK always send SKE */
|| (alg_k & (SSL_PSK & (SSL_kDHEPSK | SSL_kECDHEPSK)))
#endif
#ifndef OPENSSL_NO_SRP
/* SRP: send ServerKeyExchange */
|| (alg_k & SSL_kSRP)
#endif
) {
return 1;
}
return 0;
}
/*
* Should we send a CertificateRequest message?
*
* Valid return values are:
* 1: Yes
* 0: No
*/
int send_certificate_request(SSL *s)
{
if (
/* don't request cert unless asked for it: */
s->verify_mode & SSL_VERIFY_PEER
/*
* don't request if post-handshake-only unless doing
* post-handshake in TLSv1.3:
*/
&& (!SSL_IS_TLS13(s) || !(s->verify_mode & SSL_VERIFY_POST_HANDSHAKE)
|| s->post_handshake_auth == SSL_PHA_REQUEST_PENDING)
/*
* if SSL_VERIFY_CLIENT_ONCE is set, don't request cert
* a second time:
*/
&& (s->certreqs_sent < 1 ||
!(s->verify_mode & SSL_VERIFY_CLIENT_ONCE))
/*
* never request cert in anonymous ciphersuites (see
* section "Certificate request" in SSL 3 drafts and in
* RFC 2246):
*/
&& (!(s->s3.tmp.new_cipher->algorithm_auth & SSL_aNULL)
/*
* ... except when the application insists on
* verification (against the specs, but statem_clnt.c accepts
* this for SSL 3)
*/
|| (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT))
/* don't request certificate for SRP auth */
&& !(s->s3.tmp.new_cipher->algorithm_auth & SSL_aSRP)
/*
* With normal PSK Certificates and Certificate Requests
* are omitted
*/
&& !(s->s3.tmp.new_cipher->algorithm_auth & SSL_aPSK)) {
return 1;
}
return 0;
}
/*
* ossl_statem_server13_write_transition() works out what handshake state to
* move to next when a TLSv1.3 server is writing messages to be sent to the
* client.
*/
static WRITE_TRAN ossl_statem_server13_write_transition(SSL *s)
{
OSSL_STATEM *st = &s->statem;
/*
* No case for TLS_ST_BEFORE, because at that stage we have not negotiated
* TLSv1.3 yet, so that is handled by ossl_statem_server_write_transition()
*/
switch (st->hand_state) {
default:
/* Shouldn't happen */
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return WRITE_TRAN_ERROR;
case TLS_ST_OK:
if (s->key_update != SSL_KEY_UPDATE_NONE) {
st->hand_state = TLS_ST_SW_KEY_UPDATE;
return WRITE_TRAN_CONTINUE;
}
if (s->post_handshake_auth == SSL_PHA_REQUEST_PENDING) {
st->hand_state = TLS_ST_SW_CERT_REQ;
return WRITE_TRAN_CONTINUE;
}
if (s->ext.extra_tickets_expected > 0) {
st->hand_state = TLS_ST_SW_SESSION_TICKET;
return WRITE_TRAN_CONTINUE;
}
/* Try to read from the client instead */
return WRITE_TRAN_FINISHED;
case TLS_ST_SR_CLNT_HELLO:
st->hand_state = TLS_ST_SW_SRVR_HELLO;
return WRITE_TRAN_CONTINUE;
case TLS_ST_SW_SRVR_HELLO:
if ((s->options & SSL_OP_ENABLE_MIDDLEBOX_COMPAT) != 0
&& s->hello_retry_request != SSL_HRR_COMPLETE)
st->hand_state = TLS_ST_SW_CHANGE;
else if (s->hello_retry_request == SSL_HRR_PENDING)
st->hand_state = TLS_ST_EARLY_DATA;
else
st->hand_state = TLS_ST_SW_ENCRYPTED_EXTENSIONS;
return WRITE_TRAN_CONTINUE;
case TLS_ST_SW_CHANGE:
if (s->hello_retry_request == SSL_HRR_PENDING)
st->hand_state = TLS_ST_EARLY_DATA;
else
st->hand_state = TLS_ST_SW_ENCRYPTED_EXTENSIONS;
return WRITE_TRAN_CONTINUE;
case TLS_ST_SW_ENCRYPTED_EXTENSIONS:
if (s->hit)
st->hand_state = TLS_ST_SW_FINISHED;
else if (send_certificate_request(s))
st->hand_state = TLS_ST_SW_CERT_REQ;
else
st->hand_state = TLS_ST_SW_CERT;
return WRITE_TRAN_CONTINUE;
case TLS_ST_SW_CERT_REQ:
if (s->post_handshake_auth == SSL_PHA_REQUEST_PENDING) {
s->post_handshake_auth = SSL_PHA_REQUESTED;
st->hand_state = TLS_ST_OK;
} else {
st->hand_state = TLS_ST_SW_CERT;
}
return WRITE_TRAN_CONTINUE;
case TLS_ST_SW_CERT:
st->hand_state = TLS_ST_SW_CERT_VRFY;
return WRITE_TRAN_CONTINUE;
case TLS_ST_SW_CERT_VRFY:
st->hand_state = TLS_ST_SW_FINISHED;
return WRITE_TRAN_CONTINUE;
case TLS_ST_SW_FINISHED:
st->hand_state = TLS_ST_EARLY_DATA;
return WRITE_TRAN_CONTINUE;
case TLS_ST_EARLY_DATA:
return WRITE_TRAN_FINISHED;
case TLS_ST_SR_FINISHED:
/*
* Technically we have finished the handshake at this point, but we're
* going to remain "in_init" for now and write out any session tickets
* immediately.
*/
if (s->post_handshake_auth == SSL_PHA_REQUESTED) {
s->post_handshake_auth = SSL_PHA_EXT_RECEIVED;
} else if (!s->ext.ticket_expected) {
/*
* If we're not going to renew the ticket then we just finish the
* handshake at this point.
*/
st->hand_state = TLS_ST_OK;
return WRITE_TRAN_CONTINUE;
}
if (s->num_tickets > s->sent_tickets)
st->hand_state = TLS_ST_SW_SESSION_TICKET;
else
st->hand_state = TLS_ST_OK;
return WRITE_TRAN_CONTINUE;
case TLS_ST_SR_KEY_UPDATE:
case TLS_ST_SW_KEY_UPDATE:
st->hand_state = TLS_ST_OK;
return WRITE_TRAN_CONTINUE;
case TLS_ST_SW_SESSION_TICKET:
/* In a resumption we only ever send a maximum of one new ticket.
* Following an initial handshake we send the number of tickets we have
* been configured for.
*/
if (!SSL_IS_FIRST_HANDSHAKE(s) && s->ext.extra_tickets_expected > 0) {
return WRITE_TRAN_CONTINUE;
} else if (s->hit || s->num_tickets <= s->sent_tickets) {
/* We've written enough tickets out. */
st->hand_state = TLS_ST_OK;
}
return WRITE_TRAN_CONTINUE;
}
}
/*
* ossl_statem_server_write_transition() works out what handshake state to move
* to next when the server is writing messages to be sent to the client.
*/
WRITE_TRAN ossl_statem_server_write_transition(SSL *s)
{
OSSL_STATEM *st = &s->statem;
/*
* Note that before the ClientHello we don't know what version we are going
* to negotiate yet, so we don't take this branch until later
*/
if (SSL_IS_TLS13(s))
return ossl_statem_server13_write_transition(s);
switch (st->hand_state) {
default:
/* Shouldn't happen */
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return WRITE_TRAN_ERROR;
case TLS_ST_OK:
if (st->request_state == TLS_ST_SW_HELLO_REQ) {
/* We must be trying to renegotiate */
st->hand_state = TLS_ST_SW_HELLO_REQ;
st->request_state = TLS_ST_BEFORE;
return WRITE_TRAN_CONTINUE;
}
/* Must be an incoming ClientHello */
if (!tls_setup_handshake(s)) {
/* SSLfatal() already called */
return WRITE_TRAN_ERROR;
}
/* Fall through */
case TLS_ST_BEFORE:
/* Just go straight to trying to read from the client */
return WRITE_TRAN_FINISHED;
case TLS_ST_SW_HELLO_REQ:
st->hand_state = TLS_ST_OK;
return WRITE_TRAN_CONTINUE;
case TLS_ST_SR_CLNT_HELLO:
if (SSL_IS_DTLS(s) && !s->d1->cookie_verified
&& (SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE)) {
st->hand_state = DTLS_ST_SW_HELLO_VERIFY_REQUEST;
} else if (s->renegotiate == 0 && !SSL_IS_FIRST_HANDSHAKE(s)) {
/* We must have rejected the renegotiation */
st->hand_state = TLS_ST_OK;
return WRITE_TRAN_CONTINUE;
} else {
st->hand_state = TLS_ST_SW_SRVR_HELLO;
}
return WRITE_TRAN_CONTINUE;
case DTLS_ST_SW_HELLO_VERIFY_REQUEST:
return WRITE_TRAN_FINISHED;
case TLS_ST_SW_SRVR_HELLO:
if (s->hit) {
if (s->ext.ticket_expected)
st->hand_state = TLS_ST_SW_SESSION_TICKET;
else
st->hand_state = TLS_ST_SW_CHANGE;
} else {
/* Check if it is anon DH or anon ECDH, */
/* normal PSK or SRP */
if (!(s->s3.tmp.new_cipher->algorithm_auth &
(SSL_aNULL | SSL_aSRP | SSL_aPSK))) {
st->hand_state = TLS_ST_SW_CERT;
} else if (send_server_key_exchange(s)) {
st->hand_state = TLS_ST_SW_KEY_EXCH;
} else if (send_certificate_request(s)) {
st->hand_state = TLS_ST_SW_CERT_REQ;
} else {
st->hand_state = TLS_ST_SW_SRVR_DONE;
}
}
return WRITE_TRAN_CONTINUE;
case TLS_ST_SW_CERT:
if (s->ext.status_expected) {
st->hand_state = TLS_ST_SW_CERT_STATUS;
return WRITE_TRAN_CONTINUE;
}
/* Fall through */
case TLS_ST_SW_CERT_STATUS:
if (send_server_key_exchange(s)) {
st->hand_state = TLS_ST_SW_KEY_EXCH;
return WRITE_TRAN_CONTINUE;
}
/* Fall through */
case TLS_ST_SW_KEY_EXCH:
if (send_certificate_request(s)) {
st->hand_state = TLS_ST_SW_CERT_REQ;
return WRITE_TRAN_CONTINUE;
}
/* Fall through */
case TLS_ST_SW_CERT_REQ:
st->hand_state = TLS_ST_SW_SRVR_DONE;
return WRITE_TRAN_CONTINUE;
case TLS_ST_SW_SRVR_DONE:
return WRITE_TRAN_FINISHED;
case TLS_ST_SR_FINISHED:
if (s->hit) {
st->hand_state = TLS_ST_OK;
return WRITE_TRAN_CONTINUE;
} else if (s->ext.ticket_expected) {
st->hand_state = TLS_ST_SW_SESSION_TICKET;
} else {
st->hand_state = TLS_ST_SW_CHANGE;
}
return WRITE_TRAN_CONTINUE;
case TLS_ST_SW_SESSION_TICKET:
st->hand_state = TLS_ST_SW_CHANGE;
return WRITE_TRAN_CONTINUE;
case TLS_ST_SW_CHANGE:
st->hand_state = TLS_ST_SW_FINISHED;
return WRITE_TRAN_CONTINUE;
case TLS_ST_SW_FINISHED:
if (s->hit) {
return WRITE_TRAN_FINISHED;
}
st->hand_state = TLS_ST_OK;
return WRITE_TRAN_CONTINUE;
}
}
/*
* Perform any pre work that needs to be done prior to sending a message from
* the server to the client.
*/
WORK_STATE ossl_statem_server_pre_work(SSL *s, WORK_STATE wst)
{
OSSL_STATEM *st = &s->statem;
switch (st->hand_state) {
default:
/* No pre work to be done */
break;
case TLS_ST_SW_HELLO_REQ:
s->shutdown = 0;
if (SSL_IS_DTLS(s))
dtls1_clear_sent_buffer(s);
break;
case DTLS_ST_SW_HELLO_VERIFY_REQUEST:
s->shutdown = 0;
if (SSL_IS_DTLS(s)) {
dtls1_clear_sent_buffer(s);
/* We don't buffer this message so don't use the timer */
st->use_timer = 0;
}
break;
case TLS_ST_SW_SRVR_HELLO:
if (SSL_IS_DTLS(s)) {
/*
* Messages we write from now on should be buffered and
* retransmitted if necessary, so we need to use the timer now
*/
st->use_timer = 1;
}
break;
case TLS_ST_SW_SRVR_DONE:
#ifndef OPENSSL_NO_SCTP
if (SSL_IS_DTLS(s) && BIO_dgram_is_sctp(SSL_get_wbio(s))) {
/* Calls SSLfatal() as required */
return dtls_wait_for_dry(s);
}
#endif
return WORK_FINISHED_CONTINUE;
case TLS_ST_SW_SESSION_TICKET:
if (SSL_IS_TLS13(s) && s->sent_tickets == 0
&& s->ext.extra_tickets_expected == 0) {
/*
* Actually this is the end of the handshake, but we're going
* straight into writing the session ticket out. So we finish off
* the handshake, but keep the various buffers active.
*
* Calls SSLfatal as required.
*/
return tls_finish_handshake(s, wst, 0, 0);
}
if (SSL_IS_DTLS(s)) {
/*
* We're into the last flight. We don't retransmit the last flight
* unless we need to, so we don't use the timer
*/
st->use_timer = 0;
}
break;
case TLS_ST_SW_CHANGE:
if (SSL_IS_TLS13(s))
break;
/* Writes to s->session are only safe for initial handshakes */
if (s->session->cipher == NULL) {
s->session->cipher = s->s3.tmp.new_cipher;
} else if (s->session->cipher != s->s3.tmp.new_cipher) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return WORK_ERROR;
}
if (!s->method->ssl3_enc->setup_key_block(s)) {
/* SSLfatal() already called */
return WORK_ERROR;
}
if (SSL_IS_DTLS(s)) {
/*
* We're into the last flight. We don't retransmit the last flight
* unless we need to, so we don't use the timer. This might have
* already been set to 0 if we sent a NewSessionTicket message,
* but we'll set it again here in case we didn't.
*/
st->use_timer = 0;
}
return WORK_FINISHED_CONTINUE;
case TLS_ST_EARLY_DATA:
if (s->early_data_state != SSL_EARLY_DATA_ACCEPTING
&& (s->s3.flags & TLS1_FLAGS_STATELESS) == 0)
return WORK_FINISHED_CONTINUE;
/* Fall through */
case TLS_ST_OK:
/* Calls SSLfatal() as required */
return tls_finish_handshake(s, wst, 1, 1);
}
return WORK_FINISHED_CONTINUE;
}
static ossl_inline int conn_is_closed(void)
{
switch (get_last_sys_error()) {
#if defined(EPIPE)
case EPIPE:
return 1;
#endif
#if defined(ECONNRESET)
case ECONNRESET:
return 1;
#endif
#if defined(WSAECONNRESET)
case WSAECONNRESET:
return 1;
#endif
default:
return 0;
}
}
/*
* Perform any work that needs to be done after sending a message from the
* server to the client.
*/
WORK_STATE ossl_statem_server_post_work(SSL *s, WORK_STATE wst)
{
OSSL_STATEM *st = &s->statem;
s->init_num = 0;
switch (st->hand_state) {
default:
/* No post work to be done */
break;
case TLS_ST_SW_HELLO_REQ:
if (statem_flush(s) != 1)
return WORK_MORE_A;
if (!ssl3_init_finished_mac(s)) {
/* SSLfatal() already called */
return WORK_ERROR;
}
break;
case DTLS_ST_SW_HELLO_VERIFY_REQUEST:
if (statem_flush(s) != 1)
return WORK_MORE_A;
/* HelloVerifyRequest resets Finished MAC */
if (s->version != DTLS1_BAD_VER && !ssl3_init_finished_mac(s)) {
/* SSLfatal() already called */
return WORK_ERROR;
}
/*
* The next message should be another ClientHello which we need to
* treat like it was the first packet
*/
s->first_packet = 1;
break;
case TLS_ST_SW_SRVR_HELLO:
if (SSL_IS_TLS13(s) && s->hello_retry_request == SSL_HRR_PENDING) {
if ((s->options & SSL_OP_ENABLE_MIDDLEBOX_COMPAT) == 0
&& statem_flush(s) != 1)
return WORK_MORE_A;
break;
}
#ifndef OPENSSL_NO_SCTP
if (SSL_IS_DTLS(s) && s->hit) {
unsigned char sctpauthkey[64];
char labelbuffer[sizeof(DTLS1_SCTP_AUTH_LABEL)];
size_t labellen;
/*
* Add new shared key for SCTP-Auth, will be ignored if no
* SCTP used.
*/
memcpy(labelbuffer, DTLS1_SCTP_AUTH_LABEL,
sizeof(DTLS1_SCTP_AUTH_LABEL));
/* Don't include the terminating zero. */
labellen = sizeof(labelbuffer) - 1;
if (s->mode & SSL_MODE_DTLS_SCTP_LABEL_LENGTH_BUG)
labellen += 1;
if (SSL_export_keying_material(s, sctpauthkey,
sizeof(sctpauthkey), labelbuffer,
labellen, NULL, 0,
0) <= 0) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return WORK_ERROR;
}
BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_ADD_AUTH_KEY,
sizeof(sctpauthkey), sctpauthkey);
}
#endif
if (!SSL_IS_TLS13(s)
|| ((s->options & SSL_OP_ENABLE_MIDDLEBOX_COMPAT) != 0
&& s->hello_retry_request != SSL_HRR_COMPLETE))
break;
/* Fall through */
case TLS_ST_SW_CHANGE:
if (s->hello_retry_request == SSL_HRR_PENDING) {
if (!statem_flush(s))
return WORK_MORE_A;
break;
}
if (SSL_IS_TLS13(s)) {
if (!s->method->ssl3_enc->setup_key_block(s)
|| !s->method->ssl3_enc->change_cipher_state(s,
SSL3_CC_HANDSHAKE | SSL3_CHANGE_CIPHER_SERVER_WRITE)) {
/* SSLfatal() already called */
return WORK_ERROR;
}
if (s->ext.early_data != SSL_EARLY_DATA_ACCEPTED
&& !s->method->ssl3_enc->change_cipher_state(s,
SSL3_CC_HANDSHAKE |SSL3_CHANGE_CIPHER_SERVER_READ)) {
/* SSLfatal() already called */
return WORK_ERROR;
}
/*
* We don't yet know whether the next record we are going to receive
* is an unencrypted alert, an encrypted alert, or an encrypted
* handshake message. We temporarily tolerate unencrypted alerts.
*/
s->statem.enc_read_state = ENC_READ_STATE_ALLOW_PLAIN_ALERTS;
break;
}
#ifndef OPENSSL_NO_SCTP
if (SSL_IS_DTLS(s) && !s->hit) {
/*
* Change to new shared key of SCTP-Auth, will be ignored if
* no SCTP used.
*/
BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_NEXT_AUTH_KEY,
0, NULL);
}
#endif
if (!s->method->ssl3_enc->change_cipher_state(s,
SSL3_CHANGE_CIPHER_SERVER_WRITE))
{
/* SSLfatal() already called */
return WORK_ERROR;
}
if (SSL_IS_DTLS(s))
dtls1_reset_seq_numbers(s, SSL3_CC_WRITE);
break;
case TLS_ST_SW_SRVR_DONE:
if (statem_flush(s) != 1)
return WORK_MORE_A;
break;
case TLS_ST_SW_FINISHED:
if (statem_flush(s) != 1)
return WORK_MORE_A;
#ifndef OPENSSL_NO_SCTP
if (SSL_IS_DTLS(s) && s->hit) {
/*
* Change to new shared key of SCTP-Auth, will be ignored if
* no SCTP used.
*/
BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_NEXT_AUTH_KEY,
0, NULL);
}
#endif
if (SSL_IS_TLS13(s)) {
/* TLS 1.3 gets the secret size from the handshake md */
size_t dummy;
if (!s->method->ssl3_enc->generate_master_secret(s,
s->master_secret, s->handshake_secret, 0,
&dummy)
|| !s->method->ssl3_enc->change_cipher_state(s,
SSL3_CC_APPLICATION | SSL3_CHANGE_CIPHER_SERVER_WRITE))
/* SSLfatal() already called */
return WORK_ERROR;
}
break;
case TLS_ST_SW_CERT_REQ:
if (s->post_handshake_auth == SSL_PHA_REQUEST_PENDING) {
if (statem_flush(s) != 1)
return WORK_MORE_A;
}
break;
case TLS_ST_SW_KEY_UPDATE:
if (statem_flush(s) != 1)
return WORK_MORE_A;
if (!tls13_update_key(s, 1)) {
/* SSLfatal() already called */
return WORK_ERROR;
}
break;
case TLS_ST_SW_SESSION_TICKET:
clear_sys_error();
if (SSL_IS_TLS13(s) && statem_flush(s) != 1) {
if (SSL_get_error(s, 0) == SSL_ERROR_SYSCALL
&& conn_is_closed()) {
/*
* We ignore connection closed errors in TLSv1.3 when sending a
* NewSessionTicket and behave as if we were successful. This is
* so that we are still able to read data sent to us by a client
* that closes soon after the end of the handshake without
* waiting to read our post-handshake NewSessionTickets.
*/
s->rwstate = SSL_NOTHING;
break;
}
return WORK_MORE_A;
}
break;
}
return WORK_FINISHED_CONTINUE;
}
/*
* Get the message construction function and message type for sending from the
* server
*
* Valid return values are:
* 1: Success
* 0: Error
*/
int ossl_statem_server_construct_message(SSL *s, WPACKET *pkt,
confunc_f *confunc, int *mt)
{
OSSL_STATEM *st = &s->statem;
switch (st->hand_state) {
default:
/* Shouldn't happen */
SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_BAD_HANDSHAKE_STATE);
return 0;
case TLS_ST_SW_CHANGE:
if (SSL_IS_DTLS(s))
*confunc = dtls_construct_change_cipher_spec;
else
*confunc = tls_construct_change_cipher_spec;
*mt = SSL3_MT_CHANGE_CIPHER_SPEC;
break;
case DTLS_ST_SW_HELLO_VERIFY_REQUEST:
*confunc = dtls_construct_hello_verify_request;
*mt = DTLS1_MT_HELLO_VERIFY_REQUEST;
break;
case TLS_ST_SW_HELLO_REQ:
/* No construction function needed */
*confunc = NULL;
*mt = SSL3_MT_HELLO_REQUEST;
break;
case TLS_ST_SW_SRVR_HELLO:
*confunc = tls_construct_server_hello;
*mt = SSL3_MT_SERVER_HELLO;
break;
case TLS_ST_SW_CERT:
*confunc = tls_construct_server_certificate;
*mt = SSL3_MT_CERTIFICATE;
break;
case TLS_ST_SW_CERT_VRFY:
*confunc = tls_construct_cert_verify;
*mt = SSL3_MT_CERTIFICATE_VERIFY;
break;
case TLS_ST_SW_KEY_EXCH:
*confunc = tls_construct_server_key_exchange;
*mt = SSL3_MT_SERVER_KEY_EXCHANGE;
break;
case TLS_ST_SW_CERT_REQ:
*confunc = tls_construct_certificate_request;
*mt = SSL3_MT_CERTIFICATE_REQUEST;
break;
case TLS_ST_SW_SRVR_DONE:
*confunc = tls_construct_server_done;
*mt = SSL3_MT_SERVER_DONE;
break;
case TLS_ST_SW_SESSION_TICKET:
*confunc = tls_construct_new_session_ticket;
*mt = SSL3_MT_NEWSESSION_TICKET;
break;
case TLS_ST_SW_CERT_STATUS:
*confunc = tls_construct_cert_status;
*mt = SSL3_MT_CERTIFICATE_STATUS;
break;
case TLS_ST_SW_FINISHED:
*confunc = tls_construct_finished;
*mt = SSL3_MT_FINISHED;
break;
case TLS_ST_EARLY_DATA:
*confunc = NULL;
*mt = SSL3_MT_DUMMY;
break;
case TLS_ST_SW_ENCRYPTED_EXTENSIONS:
*confunc = tls_construct_encrypted_extensions;
*mt = SSL3_MT_ENCRYPTED_EXTENSIONS;
break;
case TLS_ST_SW_KEY_UPDATE:
*confunc = tls_construct_key_update;
*mt = SSL3_MT_KEY_UPDATE;
break;
}
return 1;
}
/*
* Maximum size (excluding the Handshake header) of a ClientHello message,
* calculated as follows:
*
* 2 + # client_version
* 32 + # only valid length for random
* 1 + # length of session_id
* 32 + # maximum size for session_id
* 2 + # length of cipher suites
* 2^16-2 + # maximum length of cipher suites array
* 1 + # length of compression_methods
* 2^8-1 + # maximum length of compression methods
* 2 + # length of extensions
* 2^16-1 # maximum length of extensions
*/
#define CLIENT_HELLO_MAX_LENGTH 131396
#define CLIENT_KEY_EXCH_MAX_LENGTH 2048
#define NEXT_PROTO_MAX_LENGTH 514
/*
* Returns the maximum allowed length for the current message that we are
* reading. Excludes the message header.
*/
size_t ossl_statem_server_max_message_size(SSL *s)
{
OSSL_STATEM *st = &s->statem;
switch (st->hand_state) {
default:
/* Shouldn't happen */
return 0;
case TLS_ST_SR_CLNT_HELLO:
return CLIENT_HELLO_MAX_LENGTH;
case TLS_ST_SR_END_OF_EARLY_DATA:
return END_OF_EARLY_DATA_MAX_LENGTH;
case TLS_ST_SR_CERT:
return s->max_cert_list;
case TLS_ST_SR_KEY_EXCH:
return CLIENT_KEY_EXCH_MAX_LENGTH;
case TLS_ST_SR_CERT_VRFY:
return SSL3_RT_MAX_PLAIN_LENGTH;
#ifndef OPENSSL_NO_NEXTPROTONEG
case TLS_ST_SR_NEXT_PROTO:
return NEXT_PROTO_MAX_LENGTH;
#endif
case TLS_ST_SR_CHANGE:
return CCS_MAX_LENGTH;
case TLS_ST_SR_FINISHED:
return FINISHED_MAX_LENGTH;
case TLS_ST_SR_KEY_UPDATE:
return KEY_UPDATE_MAX_LENGTH;
}
}
/*
* Process a message that the server has received from the client.
*/
MSG_PROCESS_RETURN ossl_statem_server_process_message(SSL *s, PACKET *pkt)
{
OSSL_STATEM *st = &s->statem;
switch (st->hand_state) {
default:
/* Shouldn't happen */
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return MSG_PROCESS_ERROR;
case TLS_ST_SR_CLNT_HELLO:
return tls_process_client_hello(s, pkt);
case TLS_ST_SR_END_OF_EARLY_DATA:
return tls_process_end_of_early_data(s, pkt);
case TLS_ST_SR_CERT:
return tls_process_client_certificate(s, pkt);
case TLS_ST_SR_KEY_EXCH:
return tls_process_client_key_exchange(s, pkt);
case TLS_ST_SR_CERT_VRFY:
return tls_process_cert_verify(s, pkt);
#ifndef OPENSSL_NO_NEXTPROTONEG
case TLS_ST_SR_NEXT_PROTO:
return tls_process_next_proto(s, pkt);
#endif
case TLS_ST_SR_CHANGE:
return tls_process_change_cipher_spec(s, pkt);
case TLS_ST_SR_FINISHED:
return tls_process_finished(s, pkt);
case TLS_ST_SR_KEY_UPDATE:
return tls_process_key_update(s, pkt);
}
}
/*
* Perform any further processing required following the receipt of a message
* from the client
*/
WORK_STATE ossl_statem_server_post_process_message(SSL *s, WORK_STATE wst)
{
OSSL_STATEM *st = &s->statem;
switch (st->hand_state) {
default:
/* Shouldn't happen */
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return WORK_ERROR;
case TLS_ST_SR_CLNT_HELLO:
return tls_post_process_client_hello(s, wst);
case TLS_ST_SR_KEY_EXCH:
return tls_post_process_client_key_exchange(s, wst);
}
}
#ifndef OPENSSL_NO_SRP
/* Returns 1 on success, 0 for retryable error, -1 for fatal error */
static int ssl_check_srp_ext_ClientHello(SSL *s)
{
int ret;
int al = SSL_AD_UNRECOGNIZED_NAME;
if ((s->s3.tmp.new_cipher->algorithm_mkey & SSL_kSRP) &&
(s->srp_ctx.TLS_ext_srp_username_callback != NULL)) {
if (s->srp_ctx.login == NULL) {
/*
* RFC 5054 says SHOULD reject, we do so if There is no srp
* login name
*/
SSLfatal(s, SSL_AD_UNKNOWN_PSK_IDENTITY,
SSL_R_PSK_IDENTITY_NOT_FOUND);
return -1;
} else {
ret = ssl_srp_server_param_with_username_intern(s, &al);
if (ret < 0)
return 0;
if (ret == SSL3_AL_FATAL) {
SSLfatal(s, al,
al == SSL_AD_UNKNOWN_PSK_IDENTITY
? SSL_R_PSK_IDENTITY_NOT_FOUND
: SSL_R_CLIENTHELLO_TLSEXT);
return -1;
}
}
}
return 1;
}
#endif
int dtls_raw_hello_verify_request(WPACKET *pkt, unsigned char *cookie,
size_t cookie_len)
{
/* Always use DTLS 1.0 version: see RFC 6347 */
if (!WPACKET_put_bytes_u16(pkt, DTLS1_VERSION)
|| !WPACKET_sub_memcpy_u8(pkt, cookie, cookie_len))
return 0;
return 1;
}
int dtls_construct_hello_verify_request(SSL *s, WPACKET *pkt)
{
unsigned int cookie_leni;
if (s->ctx->app_gen_cookie_cb == NULL ||
s->ctx->app_gen_cookie_cb(s, s->d1->cookie,
&cookie_leni) == 0 ||
cookie_leni > DTLS1_COOKIE_LENGTH) {
SSLfatal(s, SSL_AD_NO_ALERT, SSL_R_COOKIE_GEN_CALLBACK_FAILURE);
return 0;
}
s->d1->cookie_len = cookie_leni;
if (!dtls_raw_hello_verify_request(pkt, s->d1->cookie,
s->d1->cookie_len)) {
SSLfatal(s, SSL_AD_NO_ALERT, ERR_R_INTERNAL_ERROR);
return 0;
}
return 1;
}
/*-
* ssl_check_for_safari attempts to fingerprint Safari using OS X
* SecureTransport using the TLS extension block in |hello|.
* Safari, since 10.6, sends exactly these extensions, in this order:
* SNI,
* elliptic_curves
* ec_point_formats
* signature_algorithms (for TLSv1.2 only)
*
* We wish to fingerprint Safari because they broke ECDHE-ECDSA support in 10.8,
* but they advertise support. So enabling ECDHE-ECDSA ciphers breaks them.
* Sadly we cannot differentiate 10.6, 10.7 and 10.8.4 (which work), from
* 10.8..10.8.3 (which don't work).
*/
static void ssl_check_for_safari(SSL *s, const CLIENTHELLO_MSG *hello)
{
static const unsigned char kSafariExtensionsBlock[] = {
0x00, 0x0a, /* elliptic_curves extension */
0x00, 0x08, /* 8 bytes */
0x00, 0x06, /* 6 bytes of curve ids */
0x00, 0x17, /* P-256 */
0x00, 0x18, /* P-384 */
0x00, 0x19, /* P-521 */
0x00, 0x0b, /* ec_point_formats */
0x00, 0x02, /* 2 bytes */
0x01, /* 1 point format */
0x00, /* uncompressed */
/* The following is only present in TLS 1.2 */
0x00, 0x0d, /* signature_algorithms */
0x00, 0x0c, /* 12 bytes */
0x00, 0x0a, /* 10 bytes */
0x05, 0x01, /* SHA-384/RSA */
0x04, 0x01, /* SHA-256/RSA */
0x02, 0x01, /* SHA-1/RSA */
0x04, 0x03, /* SHA-256/ECDSA */
0x02, 0x03, /* SHA-1/ECDSA */
};
/* Length of the common prefix (first two extensions). */
static const size_t kSafariCommonExtensionsLength = 18;
unsigned int type;
PACKET sni, tmppkt;
size_t ext_len;
tmppkt = hello->extensions;
if (!PACKET_forward(&tmppkt, 2)
|| !PACKET_get_net_2(&tmppkt, &type)
|| !PACKET_get_length_prefixed_2(&tmppkt, &sni)) {
return;
}
if (type != TLSEXT_TYPE_server_name)
return;
ext_len = TLS1_get_client_version(s) >= TLS1_2_VERSION ?
sizeof(kSafariExtensionsBlock) : kSafariCommonExtensionsLength;
s->s3.is_probably_safari = PACKET_equal(&tmppkt, kSafariExtensionsBlock,
ext_len);
}
#define RENEG_OPTIONS_OK(options) \
((options & SSL_OP_NO_RENEGOTIATION) == 0 \
&& (options & SSL_OP_ALLOW_CLIENT_RENEGOTIATION) != 0)
MSG_PROCESS_RETURN tls_process_client_hello(SSL *s, PACKET *pkt)
{
/* |cookie| will only be initialized for DTLS. */
PACKET session_id, compression, extensions, cookie;
static const unsigned char null_compression = 0;
CLIENTHELLO_MSG *clienthello = NULL;
/* Check if this is actually an unexpected renegotiation ClientHello */
if (s->renegotiate == 0 && !SSL_IS_FIRST_HANDSHAKE(s)) {
if (!ossl_assert(!SSL_IS_TLS13(s))) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
goto err;
}
if (!RENEG_OPTIONS_OK(s->options)
|| (!s->s3.send_connection_binding
&& (s->options
& SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION) == 0)) {
ssl3_send_alert(s, SSL3_AL_WARNING, SSL_AD_NO_RENEGOTIATION);
return MSG_PROCESS_FINISHED_READING;
}
s->renegotiate = 1;
s->new_session = 1;
}
clienthello = OPENSSL_zalloc(sizeof(*clienthello));
if (clienthello == NULL) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
goto err;
}
/*
* First, parse the raw ClientHello data into the CLIENTHELLO_MSG structure.
*/
clienthello->isv2 = RECORD_LAYER_is_sslv2_record(&s->rlayer);
PACKET_null_init(&cookie);
if (clienthello->isv2) {
unsigned int mt;
if (!SSL_IS_FIRST_HANDSHAKE(s)
|| s->hello_retry_request != SSL_HRR_NONE) {
SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_MESSAGE);
goto err;
}
/*-
* An SSLv3/TLSv1 backwards-compatible CLIENT-HELLO in an SSLv2
* header is sent directly on the wire, not wrapped as a TLS
* record. Our record layer just processes the message length and passes
* the rest right through. Its format is:
* Byte Content
* 0-1 msg_length - decoded by the record layer
* 2 msg_type - s->init_msg points here
* 3-4 version
* 5-6 cipher_spec_length
* 7-8 session_id_length
* 9-10 challenge_length
* ... ...
*/
if (!PACKET_get_1(pkt, &mt)
|| mt != SSL2_MT_CLIENT_HELLO) {
/*
* Should never happen. We should have tested this in the record
* layer in order to have determined that this is a SSLv2 record
* in the first place
*/
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
goto err;
}
}
if (!PACKET_get_net_2(pkt, &clienthello->legacy_version)) {
SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_TOO_SHORT);
goto err;
}
/* Parse the message and load client random. */
if (clienthello->isv2) {
/*
* Handle an SSLv2 backwards compatible ClientHello
* Note, this is only for SSLv3+ using the backward compatible format.
* Real SSLv2 is not supported, and is rejected below.
*/
unsigned int ciphersuite_len, session_id_len, challenge_len;
PACKET challenge;
if (!PACKET_get_net_2(pkt, &ciphersuite_len)
|| !PACKET_get_net_2(pkt, &session_id_len)
|| !PACKET_get_net_2(pkt, &challenge_len)) {
SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_RECORD_LENGTH_MISMATCH);
goto err;
}
if (session_id_len > SSL_MAX_SSL_SESSION_ID_LENGTH) {
SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_LENGTH_MISMATCH);
goto err;
}
if (!PACKET_get_sub_packet(pkt, &clienthello->ciphersuites,
ciphersuite_len)
|| !PACKET_copy_bytes(pkt, clienthello->session_id, session_id_len)
|| !PACKET_get_sub_packet(pkt, &challenge, challenge_len)
/* No extensions. */
|| PACKET_remaining(pkt) != 0) {
SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_RECORD_LENGTH_MISMATCH);
goto err;
}
clienthello->session_id_len = session_id_len;
/* Load the client random and compression list. We use SSL3_RANDOM_SIZE
* here rather than sizeof(clienthello->random) because that is the limit
* for SSLv3 and it is fixed. It won't change even if
* sizeof(clienthello->random) does.
*/
challenge_len = challenge_len > SSL3_RANDOM_SIZE
? SSL3_RANDOM_SIZE : challenge_len;
memset(clienthello->random, 0, SSL3_RANDOM_SIZE);
if (!PACKET_copy_bytes(&challenge,
clienthello->random + SSL3_RANDOM_SIZE -
challenge_len, challenge_len)
/* Advertise only null compression. */
|| !PACKET_buf_init(&compression, &null_compression, 1)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
goto err;
}
PACKET_null_init(&clienthello->extensions);
} else {
/* Regular ClientHello. */
if (!PACKET_copy_bytes(pkt, clienthello->random, SSL3_RANDOM_SIZE)
|| !PACKET_get_length_prefixed_1(pkt, &session_id)
|| !PACKET_copy_all(&session_id, clienthello->session_id,
SSL_MAX_SSL_SESSION_ID_LENGTH,
&clienthello->session_id_len)) {
SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
goto err;
}
if (SSL_IS_DTLS(s)) {
if (!PACKET_get_length_prefixed_1(pkt, &cookie)) {
SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
goto err;
}
if (!PACKET_copy_all(&cookie, clienthello->dtls_cookie,
DTLS1_COOKIE_LENGTH,
&clienthello->dtls_cookie_len)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
goto err;
}
/*
* If we require cookies and this ClientHello doesn't contain one,
* just return since we do not want to allocate any memory yet.
* So check cookie length...
*/
if (SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE) {
if (clienthello->dtls_cookie_len == 0) {
OPENSSL_free(clienthello);
return MSG_PROCESS_FINISHED_READING;
}
}
}
if (!PACKET_get_length_prefixed_2(pkt, &clienthello->ciphersuites)) {
SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
goto err;
}
if (!PACKET_get_length_prefixed_1(pkt, &compression)) {
SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
goto err;
}
/* Could be empty. */
if (PACKET_remaining(pkt) == 0) {
PACKET_null_init(&clienthello->extensions);
} else {
if (!PACKET_get_length_prefixed_2(pkt, &clienthello->extensions)
|| PACKET_remaining(pkt) != 0) {
SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
goto err;
}
}
}
if (!PACKET_copy_all(&compression, clienthello->compressions,
MAX_COMPRESSIONS_SIZE,
&clienthello->compressions_len)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
goto err;
}
/* Preserve the raw extensions PACKET for later use */
extensions = clienthello->extensions;
if (!tls_collect_extensions(s, &extensions, SSL_EXT_CLIENT_HELLO,
&clienthello->pre_proc_exts,
&clienthello->pre_proc_exts_len, 1)) {
/* SSLfatal already been called */
goto err;
}
s->clienthello = clienthello;
return MSG_PROCESS_CONTINUE_PROCESSING;
err:
if (clienthello != NULL)
OPENSSL_free(clienthello->pre_proc_exts);
OPENSSL_free(clienthello);
return MSG_PROCESS_ERROR;
}
static int tls_early_post_process_client_hello(SSL *s)
{
unsigned int j;
int i, al = SSL_AD_INTERNAL_ERROR;
int protverr;
size_t loop;
unsigned long id;
#ifndef OPENSSL_NO_COMP
SSL_COMP *comp = NULL;
#endif
const SSL_CIPHER *c;
STACK_OF(SSL_CIPHER) *ciphers = NULL;
STACK_OF(SSL_CIPHER) *scsvs = NULL;
CLIENTHELLO_MSG *clienthello = s->clienthello;
DOWNGRADE dgrd = DOWNGRADE_NONE;
/* Finished parsing the ClientHello, now we can start processing it */
/* Give the ClientHello callback a crack at things */
if (s->ctx->client_hello_cb != NULL) {
/* A failure in the ClientHello callback terminates the connection. */
switch (s->ctx->client_hello_cb(s, &al, s->ctx->client_hello_cb_arg)) {
case SSL_CLIENT_HELLO_SUCCESS:
break;
case SSL_CLIENT_HELLO_RETRY:
s->rwstate = SSL_CLIENT_HELLO_CB;
return -1;
case SSL_CLIENT_HELLO_ERROR:
default:
SSLfatal(s, al, SSL_R_CALLBACK_FAILED);
goto err;
}
}
/* Set up the client_random */
memcpy(s->s3.client_random, clienthello->random, SSL3_RANDOM_SIZE);
/* Choose the version */
if (clienthello->isv2) {
if (clienthello->legacy_version == SSL2_VERSION
|| (clienthello->legacy_version & 0xff00)
!= (SSL3_VERSION_MAJOR << 8)) {
/*
* This is real SSLv2 or something completely unknown. We don't
* support it.
*/
SSLfatal(s, SSL_AD_PROTOCOL_VERSION, SSL_R_UNKNOWN_PROTOCOL);
goto err;
}
/* SSLv3/TLS */
s->client_version = clienthello->legacy_version;
}
/*
* Do SSL/TLS version negotiation if applicable. For DTLS we just check
* versions are potentially compatible. Version negotiation comes later.
*/
if (!SSL_IS_DTLS(s)) {
protverr = ssl_choose_server_version(s, clienthello, &dgrd);
} else if (s->method->version != DTLS_ANY_VERSION &&
DTLS_VERSION_LT((int)clienthello->legacy_version, s->version)) {
protverr = SSL_R_VERSION_TOO_LOW;
} else {
protverr = 0;
}
if (protverr) {
if (SSL_IS_FIRST_HANDSHAKE(s)) {
/* like ssl3_get_record, send alert using remote version number */
s->version = s->client_version = clienthello->legacy_version;
}
SSLfatal(s, SSL_AD_PROTOCOL_VERSION, protverr);
goto err;
}
/* TLSv1.3 specifies that a ClientHello must end on a record boundary */
if (SSL_IS_TLS13(s) && RECORD_LAYER_processed_read_pending(&s->rlayer)) {
SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_NOT_ON_RECORD_BOUNDARY);
goto err;
}
if (SSL_IS_DTLS(s)) {
/* Empty cookie was already handled above by returning early. */
if (SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE) {
if (s->ctx->app_verify_cookie_cb != NULL) {
if (s->ctx->app_verify_cookie_cb(s, clienthello->dtls_cookie,
clienthello->dtls_cookie_len) == 0) {
SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
SSL_R_COOKIE_MISMATCH);
goto err;
/* else cookie verification succeeded */
}
/* default verification */
} else if (s->d1->cookie_len != clienthello->dtls_cookie_len
|| memcmp(clienthello->dtls_cookie, s->d1->cookie,
s->d1->cookie_len) != 0) {
SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_COOKIE_MISMATCH);
goto err;
}
s->d1->cookie_verified = 1;
}
if (s->method->version == DTLS_ANY_VERSION) {
protverr = ssl_choose_server_version(s, clienthello, &dgrd);
if (protverr != 0) {
s->version = s->client_version;
SSLfatal(s, SSL_AD_PROTOCOL_VERSION, protverr);
goto err;
}
}
}
s->hit = 0;
if (!ssl_cache_cipherlist(s, &clienthello->ciphersuites,
clienthello->isv2) ||
!bytes_to_cipher_list(s, &clienthello->ciphersuites, &ciphers, &scsvs,
clienthello->isv2, 1)) {
/* SSLfatal() already called */
goto err;
}
s->s3.send_connection_binding = 0;
/* Check what signalling cipher-suite values were received. */
if (scsvs != NULL) {
for(i = 0; i < sk_SSL_CIPHER_num(scsvs); i++) {
c = sk_SSL_CIPHER_value(scsvs, i);
if (SSL_CIPHER_get_id(c) == SSL3_CK_SCSV) {
if (s->renegotiate) {
/* SCSV is fatal if renegotiating */
SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
SSL_R_SCSV_RECEIVED_WHEN_RENEGOTIATING);
goto err;
}
s->s3.send_connection_binding = 1;
} else if (SSL_CIPHER_get_id(c) == SSL3_CK_FALLBACK_SCSV &&
!ssl_check_version_downgrade(s)) {
/*
* This SCSV indicates that the client previously tried
* a higher version. We should fail if the current version
* is an unexpected downgrade, as that indicates that the first
* connection may have been tampered with in order to trigger
* an insecure downgrade.
*/
SSLfatal(s, SSL_AD_INAPPROPRIATE_FALLBACK,
SSL_R_INAPPROPRIATE_FALLBACK);
goto err;
}
}
}
/* For TLSv1.3 we must select the ciphersuite *before* session resumption */
if (SSL_IS_TLS13(s)) {
const SSL_CIPHER *cipher =
ssl3_choose_cipher(s, ciphers, SSL_get_ciphers(s));
if (cipher == NULL) {
SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_NO_SHARED_CIPHER);
goto err;
}
if (s->hello_retry_request == SSL_HRR_PENDING
&& (s->s3.tmp.new_cipher == NULL
|| s->s3.tmp.new_cipher->id != cipher->id)) {
/*
* A previous HRR picked a different ciphersuite to the one we
* just selected. Something must have changed.
*/
SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_BAD_CIPHER);
goto err;
}
s->s3.tmp.new_cipher = cipher;
}
/* We need to do this before getting the session */
if (!tls_parse_extension(s, TLSEXT_IDX_extended_master_secret,
SSL_EXT_CLIENT_HELLO,
clienthello->pre_proc_exts, NULL, 0)) {
/* SSLfatal() already called */
goto err;
}
/*
* We don't allow resumption in a backwards compatible ClientHello.
* In TLS1.1+, session_id MUST be empty.
*
* Versions before 0.9.7 always allow clients to resume sessions in
* renegotiation. 0.9.7 and later allow this by default, but optionally
* ignore resumption requests with flag
* SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (it's a new flag rather
* than a change to default behavior so that applications relying on
* this for security won't even compile against older library versions).
* 1.0.1 and later also have a function SSL_renegotiate_abbreviated() to
* request renegotiation but not a new session (s->new_session remains
* unset): for servers, this essentially just means that the
* SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION setting will be
* ignored.
*/
if (clienthello->isv2 ||
(s->new_session &&
(s->options & SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION))) {
if (!ssl_get_new_session(s, 1)) {
/* SSLfatal() already called */
goto err;
}
} else {
i = ssl_get_prev_session(s, clienthello);
if (i == 1) {
/* previous session */
s->hit = 1;
} else if (i == -1) {
/* SSLfatal() already called */
goto err;
} else {
/* i == 0 */
if (!ssl_get_new_session(s, 1)) {
/* SSLfatal() already called */
goto err;
}
}
}
if (SSL_IS_TLS13(s)) {
memcpy(s->tmp_session_id, s->clienthello->session_id,
s->clienthello->session_id_len);
s->tmp_session_id_len = s->clienthello->session_id_len;
}
/*
* If it is a hit, check that the cipher is in the list. In TLSv1.3 we check
* ciphersuite compatibility with the session as part of resumption.
*/
if (!SSL_IS_TLS13(s) && s->hit) {
j = 0;
id = s->session->cipher->id;
OSSL_TRACE_BEGIN(TLS_CIPHER) {
BIO_printf(trc_out, "client sent %d ciphers\n",
sk_SSL_CIPHER_num(ciphers));
}
for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
c = sk_SSL_CIPHER_value(ciphers, i);
if (trc_out != NULL)
BIO_printf(trc_out, "client [%2d of %2d]:%s\n", i,
sk_SSL_CIPHER_num(ciphers), SSL_CIPHER_get_name(c));
if (c->id == id) {
j = 1;
break;
}
}
if (j == 0) {
/*
* we need to have the cipher in the cipher list if we are asked
* to reuse it
*/
SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
SSL_R_REQUIRED_CIPHER_MISSING);
OSSL_TRACE_CANCEL(TLS_CIPHER);
goto err;
}
OSSL_TRACE_END(TLS_CIPHER);
}
for (loop = 0; loop < clienthello->compressions_len; loop++) {
if (clienthello->compressions[loop] == 0)
break;
}
if (loop >= clienthello->compressions_len) {
/* no compress */
SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_NO_COMPRESSION_SPECIFIED);
goto err;
}
if (s->options & SSL_OP_SAFARI_ECDHE_ECDSA_BUG)
ssl_check_for_safari(s, clienthello);
/* TLS extensions */
if (!tls_parse_all_extensions(s, SSL_EXT_CLIENT_HELLO,
clienthello->pre_proc_exts, NULL, 0, 1)) {
/* SSLfatal() already called */
goto err;
}
/*
* Check if we want to use external pre-shared secret for this handshake
* for not reused session only. We need to generate server_random before
* calling tls_session_secret_cb in order to allow SessionTicket
* processing to use it in key derivation.
*/
{
unsigned char *pos;
pos = s->s3.server_random;
if (ssl_fill_hello_random(s, 1, pos, SSL3_RANDOM_SIZE, dgrd) <= 0) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
goto err;
}
}
if (!s->hit
&& s->version >= TLS1_VERSION
&& !SSL_IS_TLS13(s)
&& !SSL_IS_DTLS(s)
&& s->ext.session_secret_cb) {
const SSL_CIPHER *pref_cipher = NULL;
/*
* s->session->master_key_length is a size_t, but this is an int for
* backwards compat reasons
*/
int master_key_length;
master_key_length = sizeof(s->session->master_key);
if (s->ext.session_secret_cb(s, s->session->master_key,
&master_key_length, ciphers,
&pref_cipher,
s->ext.session_secret_cb_arg)
&& master_key_length > 0) {
s->session->master_key_length = master_key_length;
s->hit = 1;
s->peer_ciphers = ciphers;
s->session->verify_result = X509_V_OK;
ciphers = NULL;
/* check if some cipher was preferred by call back */
if (pref_cipher == NULL)
pref_cipher = ssl3_choose_cipher(s, s->peer_ciphers,
SSL_get_ciphers(s));
if (pref_cipher == NULL) {
SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_NO_SHARED_CIPHER);
goto err;
}
s->session->cipher = pref_cipher;
sk_SSL_CIPHER_free(s->cipher_list);
s->cipher_list = sk_SSL_CIPHER_dup(s->peer_ciphers);
sk_SSL_CIPHER_free(s->cipher_list_by_id);
s->cipher_list_by_id = sk_SSL_CIPHER_dup(s->peer_ciphers);
}
}
/*
* Worst case, we will use the NULL compression, but if we have other
* options, we will now look for them. We have complen-1 compression
* algorithms from the client, starting at q.
*/
s->s3.tmp.new_compression = NULL;
if (SSL_IS_TLS13(s)) {
/*
* We already checked above that the NULL compression method appears in
* the list. Now we check there aren't any others (which is illegal in
* a TLSv1.3 ClientHello.
*/
if (clienthello->compressions_len != 1) {
SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
SSL_R_INVALID_COMPRESSION_ALGORITHM);
goto err;
}
}
#ifndef OPENSSL_NO_COMP
/* This only happens if we have a cache hit */
else if (s->session->compress_meth != 0) {
int m, comp_id = s->session->compress_meth;
unsigned int k;
/* Perform sanity checks on resumed compression algorithm */
/* Can't disable compression */
if (!ssl_allow_compression(s)) {
SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
SSL_R_INCONSISTENT_COMPRESSION);
goto err;
}
/* Look for resumed compression method */
for (m = 0; m < sk_SSL_COMP_num(s->ctx->comp_methods); m++) {
comp = sk_SSL_COMP_value(s->ctx->comp_methods, m);
if (comp_id == comp->id) {
s->s3.tmp.new_compression = comp;
break;
}
}
if (s->s3.tmp.new_compression == NULL) {
SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
SSL_R_INVALID_COMPRESSION_ALGORITHM);
goto err;
}
/* Look for resumed method in compression list */
for (k = 0; k < clienthello->compressions_len; k++) {
if (clienthello->compressions[k] == comp_id)
break;
}
if (k >= clienthello->compressions_len) {
SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
SSL_R_REQUIRED_COMPRESSION_ALGORITHM_MISSING);
goto err;
}
} else if (s->hit) {
comp = NULL;
} else if (ssl_allow_compression(s) && s->ctx->comp_methods) {
/* See if we have a match */
int m, nn, v, done = 0;
unsigned int o;
nn = sk_SSL_COMP_num(s->ctx->comp_methods);
for (m = 0; m < nn; m++) {
comp = sk_SSL_COMP_value(s->ctx->comp_methods, m);
v = comp->id;
for (o = 0; o < clienthello->compressions_len; o++) {
if (v == clienthello->compressions[o]) {
done = 1;
break;
}
}
if (done)
break;
}
if (done)
s->s3.tmp.new_compression = comp;
else
comp = NULL;
}
#else
/*
* If compression is disabled we'd better not try to resume a session
* using compression.
*/
if (s->session->compress_meth != 0) {
SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_INCONSISTENT_COMPRESSION);
goto err;
}
#endif
/*
* Given s->peer_ciphers and SSL_get_ciphers, we must pick a cipher
*/
if (!s->hit || SSL_IS_TLS13(s)) {
sk_SSL_CIPHER_free(s->peer_ciphers);
s->peer_ciphers = ciphers;
if (ciphers == NULL) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
goto err;
}
ciphers = NULL;
}
if (!s->hit) {
#ifdef OPENSSL_NO_COMP
s->session->compress_meth = 0;
#else
s->session->compress_meth = (comp == NULL) ? 0 : comp->id;
#endif
if (!tls1_set_server_sigalgs(s)) {
/* SSLfatal() already called */
goto err;
}
}
sk_SSL_CIPHER_free(ciphers);
sk_SSL_CIPHER_free(scsvs);
OPENSSL_free(clienthello->pre_proc_exts);
OPENSSL_free(s->clienthello);
s->clienthello = NULL;
return 1;
err:
sk_SSL_CIPHER_free(ciphers);
sk_SSL_CIPHER_free(scsvs);
OPENSSL_free(clienthello->pre_proc_exts);
OPENSSL_free(s->clienthello);
s->clienthello = NULL;
return 0;
}
/*
* Call the status request callback if needed. Upon success, returns 1.
* Upon failure, returns 0.
*/
static int tls_handle_status_request(SSL *s)
{
s->ext.status_expected = 0;
/*
* If status request then ask callback what to do. Note: this must be
* called after servername callbacks in case the certificate has changed,
* and must be called after the cipher has been chosen because this may
* influence which certificate is sent
*/
if (s->ext.status_type != TLSEXT_STATUSTYPE_nothing && s->ctx != NULL
&& s->ctx->ext.status_cb != NULL) {
int ret;
/* If no certificate can't return certificate status */
if (s->s3.tmp.cert != NULL) {
/*
* Set current certificate to one we will use so SSL_get_certificate
* et al can pick it up.
*/
s->cert->key = s->s3.tmp.cert;
ret = s->ctx->ext.status_cb(s, s->ctx->ext.status_arg);
switch (ret) {
/* We don't want to send a status request response */
case SSL_TLSEXT_ERR_NOACK:
s->ext.status_expected = 0;
break;
/* status request response should be sent */
case SSL_TLSEXT_ERR_OK:
if (s->ext.ocsp.resp)
s->ext.status_expected = 1;
break;
/* something bad happened */
case SSL_TLSEXT_ERR_ALERT_FATAL:
default:
SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_CLIENTHELLO_TLSEXT);
return 0;
}
}
}
return 1;
}
/*
* Call the alpn_select callback if needed. Upon success, returns 1.
* Upon failure, returns 0.
*/
int tls_handle_alpn(SSL *s)
{
const unsigned char *selected = NULL;
unsigned char selected_len = 0;
if (s->ctx->ext.alpn_select_cb != NULL && s->s3.alpn_proposed != NULL) {
int r = s->ctx->ext.alpn_select_cb(s, &selected, &selected_len,
s->s3.alpn_proposed,
(unsigned int)s->s3.alpn_proposed_len,
s->ctx->ext.alpn_select_cb_arg);
if (r == SSL_TLSEXT_ERR_OK) {
OPENSSL_free(s->s3.alpn_selected);
s->s3.alpn_selected = OPENSSL_memdup(selected, selected_len);
if (s->s3.alpn_selected == NULL) {
s->s3.alpn_selected_len = 0;
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return 0;
}
s->s3.alpn_selected_len = selected_len;
#ifndef OPENSSL_NO_NEXTPROTONEG
/* ALPN takes precedence over NPN. */
s->s3.npn_seen = 0;
#endif
/* Check ALPN is consistent with session */
if (s->session->ext.alpn_selected == NULL
|| selected_len != s->session->ext.alpn_selected_len
|| memcmp(selected, s->session->ext.alpn_selected,
selected_len) != 0) {
/* Not consistent so can't be used for early_data */
s->ext.early_data_ok = 0;
if (!s->hit) {
/*
* This is a new session and so alpn_selected should have
* been initialised to NULL. We should update it with the
* selected ALPN.
*/
if (!ossl_assert(s->session->ext.alpn_selected == NULL)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR,
ERR_R_INTERNAL_ERROR);
return 0;
}
s->session->ext.alpn_selected = OPENSSL_memdup(selected,
selected_len);
if (s->session->ext.alpn_selected == NULL) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR,
ERR_R_INTERNAL_ERROR);
return 0;
}
s->session->ext.alpn_selected_len = selected_len;
}
}
return 1;
} else if (r != SSL_TLSEXT_ERR_NOACK) {
SSLfatal(s, SSL_AD_NO_APPLICATION_PROTOCOL,
SSL_R_NO_APPLICATION_PROTOCOL);
return 0;
}
/*
* If r == SSL_TLSEXT_ERR_NOACK then behave as if no callback was
* present.
*/
}
/* Check ALPN is consistent with session */
if (s->session->ext.alpn_selected != NULL) {
/* Not consistent so can't be used for early_data */
s->ext.early_data_ok = 0;
}
return 1;
}
WORK_STATE tls_post_process_client_hello(SSL *s, WORK_STATE wst)
{
const SSL_CIPHER *cipher;
if (wst == WORK_MORE_A) {
int rv = tls_early_post_process_client_hello(s);
if (rv == 0) {
/* SSLfatal() was already called */
goto err;
}
if (rv < 0)
return WORK_MORE_A;
wst = WORK_MORE_B;
}
if (wst == WORK_MORE_B) {
if (!s->hit || SSL_IS_TLS13(s)) {
/* Let cert callback update server certificates if required */
if (!s->hit && s->cert->cert_cb != NULL) {
int rv = s->cert->cert_cb(s, s->cert->cert_cb_arg);
if (rv == 0) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_CERT_CB_ERROR);
goto err;
}
if (rv < 0) {
s->rwstate = SSL_X509_LOOKUP;
return WORK_MORE_B;
}
s->rwstate = SSL_NOTHING;
}
/* In TLSv1.3 we selected the ciphersuite before resumption */
if (!SSL_IS_TLS13(s)) {
cipher =
ssl3_choose_cipher(s, s->peer_ciphers, SSL_get_ciphers(s));
if (cipher == NULL) {
SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
SSL_R_NO_SHARED_CIPHER);
goto err;
}
s->s3.tmp.new_cipher = cipher;
}
if (!s->hit) {
if (!tls_choose_sigalg(s, 1)) {
/* SSLfatal already called */
goto err;
}
/* check whether we should disable session resumption */
if (s->not_resumable_session_cb != NULL)
s->session->not_resumable =
s->not_resumable_session_cb(s,
((s->s3.tmp.new_cipher->algorithm_mkey
& (SSL_kDHE | SSL_kECDHE)) != 0));
if (s->session->not_resumable)
/* do not send a session ticket */
s->ext.ticket_expected = 0;
}
} else {
/* Session-id reuse */
s->s3.tmp.new_cipher = s->session->cipher;
}
/*-
* we now have the following setup.
* client_random
* cipher_list - our preferred list of ciphers
* ciphers - the clients preferred list of ciphers
* compression - basically ignored right now
* ssl version is set - sslv3
* s->session - The ssl session has been setup.
* s->hit - session reuse flag
* s->s3.tmp.new_cipher - the new cipher to use.
*/
/*
* Call status_request callback if needed. Has to be done after the
* certificate callbacks etc above.
*/
if (!tls_handle_status_request(s)) {
/* SSLfatal() already called */
goto err;
}
/*
* Call alpn_select callback if needed. Has to be done after SNI and
* cipher negotiation (HTTP/2 restricts permitted ciphers). In TLSv1.3
* we already did this because cipher negotiation happens earlier, and
* we must handle ALPN before we decide whether to accept early_data.
*/
if (!SSL_IS_TLS13(s) && !tls_handle_alpn(s)) {
/* SSLfatal() already called */
goto err;
}
wst = WORK_MORE_C;
}
#ifndef OPENSSL_NO_SRP
if (wst == WORK_MORE_C) {
int ret;
if ((ret = ssl_check_srp_ext_ClientHello(s)) == 0) {
/*
* callback indicates further work to be done
*/
s->rwstate = SSL_X509_LOOKUP;
return WORK_MORE_C;
}
if (ret < 0) {
/* SSLfatal() already called */
goto err;
}
}
#endif
return WORK_FINISHED_STOP;
err:
return WORK_ERROR;
}
int tls_construct_server_hello(SSL *s, WPACKET *pkt)
{
int compm;
size_t sl, len;
int version;
unsigned char *session_id;
int usetls13 = SSL_IS_TLS13(s) || s->hello_retry_request == SSL_HRR_PENDING;
version = usetls13 ? TLS1_2_VERSION : s->version;
if (!WPACKET_put_bytes_u16(pkt, version)
/*
* Random stuff. Filling of the server_random takes place in
* tls_process_client_hello()
*/
|| !WPACKET_memcpy(pkt,
s->hello_retry_request == SSL_HRR_PENDING
? hrrrandom : s->s3.server_random,
SSL3_RANDOM_SIZE)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return 0;
}
/*-
* There are several cases for the session ID to send
* back in the server hello:
* - For session reuse from the session cache,
* we send back the old session ID.
* - If stateless session reuse (using a session ticket)
* is successful, we send back the client's "session ID"
* (which doesn't actually identify the session).
* - If it is a new session, we send back the new
* session ID.
* - However, if we want the new session to be single-use,
* we send back a 0-length session ID.
* - In TLSv1.3 we echo back the session id sent to us by the client
* regardless
* s->hit is non-zero in either case of session reuse,
* so the following won't overwrite an ID that we're supposed
* to send back.
*/
- if (s->session->not_resumable ||
- (!(s->ctx->session_cache_mode & SSL_SESS_CACHE_SERVER)
- && !s->hit))
+ if (!(s->ctx->session_cache_mode & SSL_SESS_CACHE_SERVER)
+ && !s->hit)
s->session->session_id_length = 0;
if (usetls13) {
sl = s->tmp_session_id_len;
session_id = s->tmp_session_id;
} else {
sl = s->session->session_id_length;
session_id = s->session->session_id;
}
if (sl > sizeof(s->session->session_id)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return 0;
}
/* set up the compression method */
#ifdef OPENSSL_NO_COMP
compm = 0;
#else
if (usetls13 || s->s3.tmp.new_compression == NULL)
compm = 0;
else
compm = s->s3.tmp.new_compression->id;
#endif
if (!WPACKET_sub_memcpy_u8(pkt, session_id, sl)
|| !s->method->put_cipher_by_char(s->s3.tmp.new_cipher, pkt, &len)
|| !WPACKET_put_bytes_u8(pkt, compm)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return 0;
}
if (!tls_construct_extensions(s, pkt,
s->hello_retry_request == SSL_HRR_PENDING
? SSL_EXT_TLS1_3_HELLO_RETRY_REQUEST
: (SSL_IS_TLS13(s)
? SSL_EXT_TLS1_3_SERVER_HELLO
: SSL_EXT_TLS1_2_SERVER_HELLO),
NULL, 0)) {
/* SSLfatal() already called */
return 0;
}
if (s->hello_retry_request == SSL_HRR_PENDING) {
/* Ditch the session. We'll create a new one next time around */
SSL_SESSION_free(s->session);
s->session = NULL;
s->hit = 0;
/*
* Re-initialise the Transcript Hash. We're going to prepopulate it with
* a synthetic message_hash in place of ClientHello1.
*/
if (!create_synthetic_message_hash(s, NULL, 0, NULL, 0)) {
/* SSLfatal() already called */
return 0;
}
} else if (!(s->verify_mode & SSL_VERIFY_PEER)
&& !ssl3_digest_cached_records(s, 0)) {
/* SSLfatal() already called */;
return 0;
}
return 1;
}
int tls_construct_server_done(SSL *s, WPACKET *pkt)
{
if (!s->s3.tmp.cert_request) {
if (!ssl3_digest_cached_records(s, 0)) {
/* SSLfatal() already called */
return 0;
}
}
return 1;
}
int tls_construct_server_key_exchange(SSL *s, WPACKET *pkt)
{
EVP_PKEY *pkdh = NULL;
unsigned char *encodedPoint = NULL;
size_t encodedlen = 0;
int curve_id = 0;
const SIGALG_LOOKUP *lu = s->s3.tmp.sigalg;
int i;
unsigned long type;
BIGNUM *r[4];
EVP_MD_CTX *md_ctx = EVP_MD_CTX_new();
EVP_PKEY_CTX *pctx = NULL;
size_t paramlen, paramoffset;
int freer = 0, ret = 0;
if (!WPACKET_get_total_written(pkt, &paramoffset)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
goto err;
}
if (md_ctx == NULL) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_MALLOC_FAILURE);
goto err;
}
type = s->s3.tmp.new_cipher->algorithm_mkey;
r[0] = r[1] = r[2] = r[3] = NULL;
#ifndef OPENSSL_NO_PSK
/* Plain PSK or RSAPSK nothing to do */
if (type & (SSL_kPSK | SSL_kRSAPSK)) {
} else
#endif /* !OPENSSL_NO_PSK */
if (type & (SSL_kDHE | SSL_kDHEPSK)) {
CERT *cert = s->cert;
EVP_PKEY *pkdhp = NULL;
if (s->cert->dh_tmp_auto) {
pkdh = ssl_get_auto_dh(s);
if (pkdh == NULL) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
goto err;
}
pkdhp = pkdh;
} else {
pkdhp = cert->dh_tmp;
}
#if !defined(OPENSSL_NO_DEPRECATED_3_0)
if ((pkdhp == NULL) && (s->cert->dh_tmp_cb != NULL)) {
pkdh = ssl_dh_to_pkey(s->cert->dh_tmp_cb(s, 0, 1024));
if (pkdh == NULL) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
goto err;
}
pkdhp = pkdh;
}
#endif
if (pkdhp == NULL) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_MISSING_TMP_DH_KEY);
goto err;
}
if (!ssl_security(s, SSL_SECOP_TMP_DH,
EVP_PKEY_get_security_bits(pkdhp), 0, pkdhp)) {
SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_DH_KEY_TOO_SMALL);
goto err;
}
if (s->s3.tmp.pkey != NULL) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
goto err;
}
s->s3.tmp.pkey = ssl_generate_pkey(s, pkdhp);
if (s->s3.tmp.pkey == NULL) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
goto err;
}
EVP_PKEY_free(pkdh);
pkdh = NULL;
/* These BIGNUMs need to be freed when we're finished */
freer = 1;
if (!EVP_PKEY_get_bn_param(s->s3.tmp.pkey, OSSL_PKEY_PARAM_FFC_P,
&r[0])
|| !EVP_PKEY_get_bn_param(s->s3.tmp.pkey, OSSL_PKEY_PARAM_FFC_G,
&r[1])
|| !EVP_PKEY_get_bn_param(s->s3.tmp.pkey,
OSSL_PKEY_PARAM_PUB_KEY, &r[2])) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
goto err;
}
} else if (type & (SSL_kECDHE | SSL_kECDHEPSK)) {
if (s->s3.tmp.pkey != NULL) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
goto err;
}
/* Get NID of appropriate shared curve */
curve_id = tls1_shared_group(s, -2);
if (curve_id == 0) {
SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
SSL_R_UNSUPPORTED_ELLIPTIC_CURVE);
goto err;
}
/* Cache the group used in the SSL_SESSION */
s->session->kex_group = curve_id;
/* Generate a new key for this curve */
s->s3.tmp.pkey = ssl_generate_pkey_group(s, curve_id);
if (s->s3.tmp.pkey == NULL) {
/* SSLfatal() already called */
goto err;
}
/* Encode the public key. */
encodedlen = EVP_PKEY_get1_encoded_public_key(s->s3.tmp.pkey,
&encodedPoint);
if (encodedlen == 0) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EC_LIB);
goto err;
}
/*
* We'll generate the serverKeyExchange message explicitly so we
* can set these to NULLs
*/
r[0] = NULL;
r[1] = NULL;
r[2] = NULL;
r[3] = NULL;
} else
#ifndef OPENSSL_NO_SRP
if (type & SSL_kSRP) {
if ((s->srp_ctx.N == NULL) ||
(s->srp_ctx.g == NULL) ||
(s->srp_ctx.s == NULL) || (s->srp_ctx.B == NULL)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_MISSING_SRP_PARAM);
goto err;
}
r[0] = s->srp_ctx.N;
r[1] = s->srp_ctx.g;
r[2] = s->srp_ctx.s;
r[3] = s->srp_ctx.B;
} else
#endif
{
SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE);
goto err;
}
if (((s->s3.tmp.new_cipher->algorithm_auth & (SSL_aNULL | SSL_aSRP)) != 0)
|| ((s->s3.tmp.new_cipher->algorithm_mkey & SSL_PSK)) != 0) {
lu = NULL;
} else if (lu == NULL) {
SSLfatal(s, SSL_AD_DECODE_ERROR, ERR_R_INTERNAL_ERROR);
goto err;
}
#ifndef OPENSSL_NO_PSK
if (type & SSL_PSK) {
size_t len = (s->cert->psk_identity_hint == NULL)
? 0 : strlen(s->cert->psk_identity_hint);
/*
* It should not happen that len > PSK_MAX_IDENTITY_LEN - we already
* checked this when we set the identity hint - but just in case
*/
if (len > PSK_MAX_IDENTITY_LEN
|| !WPACKET_sub_memcpy_u16(pkt, s->cert->psk_identity_hint,
len)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
goto err;
}
}
#endif
for (i = 0; i < 4 && r[i] != NULL; i++) {
unsigned char *binval;
int res;
#ifndef OPENSSL_NO_SRP
if ((i == 2) && (type & SSL_kSRP)) {
res = WPACKET_start_sub_packet_u8(pkt);
} else
#endif
res = WPACKET_start_sub_packet_u16(pkt);
if (!res) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
goto err;
}
/*-
* for interoperability with some versions of the Microsoft TLS
* stack, we need to zero pad the DHE pub key to the same length
* as the prime
*/
if ((i == 2) && (type & (SSL_kDHE | SSL_kDHEPSK))) {
size_t len = BN_num_bytes(r[0]) - BN_num_bytes(r[2]);
if (len > 0) {
if (!WPACKET_allocate_bytes(pkt, len, &binval)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
goto err;
}
memset(binval, 0, len);
}
}
if (!WPACKET_allocate_bytes(pkt, BN_num_bytes(r[i]), &binval)
|| !WPACKET_close(pkt)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
goto err;
}
BN_bn2bin(r[i], binval);
}
if (type & (SSL_kECDHE | SSL_kECDHEPSK)) {
/*
* We only support named (not generic) curves. In this situation, the
* ServerKeyExchange message has: [1 byte CurveType], [2 byte CurveName]
* [1 byte length of encoded point], followed by the actual encoded
* point itself
*/
if (!WPACKET_put_bytes_u8(pkt, NAMED_CURVE_TYPE)
|| !WPACKET_put_bytes_u8(pkt, 0)
|| !WPACKET_put_bytes_u8(pkt, curve_id)
|| !WPACKET_sub_memcpy_u8(pkt, encodedPoint, encodedlen)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
goto err;
}
OPENSSL_free(encodedPoint);
encodedPoint = NULL;
}
/* not anonymous */
if (lu != NULL) {
EVP_PKEY *pkey = s->s3.tmp.cert->privatekey;
const EVP_MD *md;
unsigned char *sigbytes1, *sigbytes2, *tbs;
size_t siglen = 0, tbslen;
if (pkey == NULL || !tls1_lookup_md(s->ctx, lu, &md)) {
/* Should never happen */
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
goto err;
}
/* Get length of the parameters we have written above */
if (!WPACKET_get_length(pkt, &paramlen)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
goto err;
}
/* send signature algorithm */
if (SSL_USE_SIGALGS(s) && !WPACKET_put_bytes_u16(pkt, lu->sigalg)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
goto err;
}
if (EVP_DigestSignInit_ex(md_ctx, &pctx,
md == NULL ? NULL : EVP_MD_get0_name(md),
s->ctx->libctx, s->ctx->propq, pkey,
NULL) <= 0) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
goto err;
}
if (lu->sig == EVP_PKEY_RSA_PSS) {
if (EVP_PKEY_CTX_set_rsa_padding(pctx, RSA_PKCS1_PSS_PADDING) <= 0
|| EVP_PKEY_CTX_set_rsa_pss_saltlen(pctx, RSA_PSS_SALTLEN_DIGEST) <= 0) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
goto err;
}
}
tbslen = construct_key_exchange_tbs(s, &tbs,
s->init_buf->data + paramoffset,
paramlen);
if (tbslen == 0) {
/* SSLfatal() already called */
goto err;
}
if (EVP_DigestSign(md_ctx, NULL, &siglen, tbs, tbslen) <=0
|| !WPACKET_sub_reserve_bytes_u16(pkt, siglen, &sigbytes1)
|| EVP_DigestSign(md_ctx, sigbytes1, &siglen, tbs, tbslen) <= 0
|| !WPACKET_sub_allocate_bytes_u16(pkt, siglen, &sigbytes2)
|| sigbytes1 != sigbytes2) {
OPENSSL_free(tbs);
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
goto err;
}
OPENSSL_free(tbs);
}
ret = 1;
err:
EVP_PKEY_free(pkdh);
OPENSSL_free(encodedPoint);
EVP_MD_CTX_free(md_ctx);
if (freer) {
BN_free(r[0]);
BN_free(r[1]);
BN_free(r[2]);
BN_free(r[3]);
}
return ret;
}
int tls_construct_certificate_request(SSL *s, WPACKET *pkt)
{
if (SSL_IS_TLS13(s)) {
/* Send random context when doing post-handshake auth */
if (s->post_handshake_auth == SSL_PHA_REQUEST_PENDING) {
OPENSSL_free(s->pha_context);
s->pha_context_len = 32;
if ((s->pha_context = OPENSSL_malloc(s->pha_context_len)) == NULL) {
s->pha_context_len = 0;
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return 0;
}
if (RAND_bytes_ex(s->ctx->libctx, s->pha_context,
s->pha_context_len, 0) <= 0
|| !WPACKET_sub_memcpy_u8(pkt, s->pha_context,
s->pha_context_len)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return 0;
}
/* reset the handshake hash back to just after the ClientFinished */
if (!tls13_restore_handshake_digest_for_pha(s)) {
/* SSLfatal() already called */
return 0;
}
} else {
if (!WPACKET_put_bytes_u8(pkt, 0)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return 0;
}
}
if (!tls_construct_extensions(s, pkt,
SSL_EXT_TLS1_3_CERTIFICATE_REQUEST, NULL,
0)) {
/* SSLfatal() already called */
return 0;
}
goto done;
}
/* get the list of acceptable cert types */
if (!WPACKET_start_sub_packet_u8(pkt)
|| !ssl3_get_req_cert_type(s, pkt) || !WPACKET_close(pkt)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return 0;
}
if (SSL_USE_SIGALGS(s)) {
const uint16_t *psigs;
size_t nl = tls12_get_psigalgs(s, 1, &psigs);
if (!WPACKET_start_sub_packet_u16(pkt)
|| !WPACKET_set_flags(pkt, WPACKET_FLAGS_NON_ZERO_LENGTH)
|| !tls12_copy_sigalgs(s, pkt, psigs, nl)
|| !WPACKET_close(pkt)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return 0;
}
}
if (!construct_ca_names(s, get_ca_names(s), pkt)) {
/* SSLfatal() already called */
return 0;
}
done:
s->certreqs_sent++;
s->s3.tmp.cert_request = 1;
return 1;
}
static int tls_process_cke_psk_preamble(SSL *s, PACKET *pkt)
{
#ifndef OPENSSL_NO_PSK
unsigned char psk[PSK_MAX_PSK_LEN];
size_t psklen;
PACKET psk_identity;
if (!PACKET_get_length_prefixed_2(pkt, &psk_identity)) {
SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
return 0;
}
if (PACKET_remaining(&psk_identity) > PSK_MAX_IDENTITY_LEN) {
SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_DATA_LENGTH_TOO_LONG);
return 0;
}
if (s->psk_server_callback == NULL) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_PSK_NO_SERVER_CB);
return 0;
}
if (!PACKET_strndup(&psk_identity, &s->session->psk_identity)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return 0;
}
psklen = s->psk_server_callback(s, s->session->psk_identity,
psk, sizeof(psk));
if (psklen > PSK_MAX_PSK_LEN) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return 0;
} else if (psklen == 0) {
/*
* PSK related to the given identity not found
*/
SSLfatal(s, SSL_AD_UNKNOWN_PSK_IDENTITY, SSL_R_PSK_IDENTITY_NOT_FOUND);
return 0;
}
OPENSSL_free(s->s3.tmp.psk);
s->s3.tmp.psk = OPENSSL_memdup(psk, psklen);
OPENSSL_cleanse(psk, psklen);
if (s->s3.tmp.psk == NULL) {
s->s3.tmp.psklen = 0;
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_MALLOC_FAILURE);
return 0;
}
s->s3.tmp.psklen = psklen;
return 1;
#else
/* Should never happen */
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return 0;
#endif
}
static int tls_process_cke_rsa(SSL *s, PACKET *pkt)
{
size_t outlen;
PACKET enc_premaster;
EVP_PKEY *rsa = NULL;
unsigned char *rsa_decrypt = NULL;
int ret = 0;
EVP_PKEY_CTX *ctx = NULL;
OSSL_PARAM params[3], *p = params;
rsa = s->cert->pkeys[SSL_PKEY_RSA].privatekey;
if (rsa == NULL) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_MISSING_RSA_CERTIFICATE);
return 0;
}
/* SSLv3 and pre-standard DTLS omit the length bytes. */
if (s->version == SSL3_VERSION || s->version == DTLS1_BAD_VER) {
enc_premaster = *pkt;
} else {
if (!PACKET_get_length_prefixed_2(pkt, &enc_premaster)
|| PACKET_remaining(pkt) != 0) {
SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
return 0;
}
}
outlen = SSL_MAX_MASTER_KEY_LENGTH;
rsa_decrypt = OPENSSL_malloc(outlen);
if (rsa_decrypt == NULL) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_MALLOC_FAILURE);
return 0;
}
ctx = EVP_PKEY_CTX_new_from_pkey(s->ctx->libctx, rsa, s->ctx->propq);
if (ctx == NULL) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_MALLOC_FAILURE);
goto err;
}
/*
* We must not leak whether a decryption failure occurs because of
* Bleichenbacher's attack on PKCS #1 v1.5 RSA padding (see RFC 2246,
* section 7.4.7.1). We use the special padding type
* RSA_PKCS1_WITH_TLS_PADDING to do that. It will automaticaly decrypt the
* RSA, check the padding and check that the client version is as expected
* in the premaster secret. If any of that fails then the function appears
* to return successfully but with a random result. The call below could
* still fail if the input is publicly invalid.
* See https://tools.ietf.org/html/rfc5246#section-7.4.7.1
*/
if (EVP_PKEY_decrypt_init(ctx) <= 0
|| EVP_PKEY_CTX_set_rsa_padding(ctx, RSA_PKCS1_WITH_TLS_PADDING) <= 0) {
SSLfatal(s, SSL_AD_DECRYPT_ERROR, SSL_R_DECRYPTION_FAILED);
goto err;
}
*p++ = OSSL_PARAM_construct_uint(OSSL_ASYM_CIPHER_PARAM_TLS_CLIENT_VERSION,
(unsigned int *)&s->client_version);
if ((s->options & SSL_OP_TLS_ROLLBACK_BUG) != 0)
*p++ = OSSL_PARAM_construct_uint(
OSSL_ASYM_CIPHER_PARAM_TLS_NEGOTIATED_VERSION,
(unsigned int *)&s->version);
*p++ = OSSL_PARAM_construct_end();
if (!EVP_PKEY_CTX_set_params(ctx, params)
|| EVP_PKEY_decrypt(ctx, rsa_decrypt, &outlen,
PACKET_data(&enc_premaster),
PACKET_remaining(&enc_premaster)) <= 0) {
SSLfatal(s, SSL_AD_DECRYPT_ERROR, SSL_R_DECRYPTION_FAILED);
goto err;
}
/*
* This test should never fail (otherwise we should have failed above) but
* we double check anyway.
*/
if (outlen != SSL_MAX_MASTER_KEY_LENGTH) {
OPENSSL_cleanse(rsa_decrypt, SSL_MAX_MASTER_KEY_LENGTH);
SSLfatal(s, SSL_AD_DECRYPT_ERROR, SSL_R_DECRYPTION_FAILED);
goto err;
}
/* Also cleanses rsa_decrypt (on success or failure) */
if (!ssl_generate_master_secret(s, rsa_decrypt,
SSL_MAX_MASTER_KEY_LENGTH, 0)) {
/* SSLfatal() already called */
goto err;
}
ret = 1;
err:
OPENSSL_free(rsa_decrypt);
EVP_PKEY_CTX_free(ctx);
return ret;
}
static int tls_process_cke_dhe(SSL *s, PACKET *pkt)
{
EVP_PKEY *skey = NULL;
unsigned int i;
const unsigned char *data;
EVP_PKEY *ckey = NULL;
int ret = 0;
if (!PACKET_get_net_2(pkt, &i) || PACKET_remaining(pkt) != i) {
SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_DH_PUBLIC_VALUE_LENGTH_IS_WRONG);
goto err;
}
skey = s->s3.tmp.pkey;
if (skey == NULL) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_MISSING_TMP_DH_KEY);
goto err;
}
if (PACKET_remaining(pkt) == 0L) {
SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_MISSING_TMP_DH_KEY);
goto err;
}
if (!PACKET_get_bytes(pkt, &data, i)) {
/* We already checked we have enough data */
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
goto err;
}
ckey = EVP_PKEY_new();
if (ckey == NULL || EVP_PKEY_copy_parameters(ckey, skey) == 0) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_COPY_PARAMETERS_FAILED);
goto err;
}
if (!EVP_PKEY_set1_encoded_public_key(ckey, data, i)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
goto err;
}
if (ssl_derive(s, skey, ckey, 1) == 0) {
/* SSLfatal() already called */
goto err;
}
ret = 1;
EVP_PKEY_free(s->s3.tmp.pkey);
s->s3.tmp.pkey = NULL;
err:
EVP_PKEY_free(ckey);
return ret;
}
static int tls_process_cke_ecdhe(SSL *s, PACKET *pkt)
{
EVP_PKEY *skey = s->s3.tmp.pkey;
EVP_PKEY *ckey = NULL;
int ret = 0;
if (PACKET_remaining(pkt) == 0L) {
/* We don't support ECDH client auth */
SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_MISSING_TMP_ECDH_KEY);
goto err;
} else {
unsigned int i;
const unsigned char *data;
/*
* Get client's public key from encoded point in the
* ClientKeyExchange message.
*/
/* Get encoded point length */
if (!PACKET_get_1(pkt, &i) || !PACKET_get_bytes(pkt, &data, i)
|| PACKET_remaining(pkt) != 0) {
SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
goto err;
}
if (skey == NULL) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_MISSING_TMP_ECDH_KEY);
goto err;
}
ckey = EVP_PKEY_new();
if (ckey == NULL || EVP_PKEY_copy_parameters(ckey, skey) <= 0) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_COPY_PARAMETERS_FAILED);
goto err;
}
if (EVP_PKEY_set1_encoded_public_key(ckey, data, i) <= 0) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EC_LIB);
goto err;
}
}
if (ssl_derive(s, skey, ckey, 1) == 0) {
/* SSLfatal() already called */
goto err;
}
ret = 1;
EVP_PKEY_free(s->s3.tmp.pkey);
s->s3.tmp.pkey = NULL;
err:
EVP_PKEY_free(ckey);
return ret;
}
static int tls_process_cke_srp(SSL *s, PACKET *pkt)
{
#ifndef OPENSSL_NO_SRP
unsigned int i;
const unsigned char *data;
if (!PACKET_get_net_2(pkt, &i)
|| !PACKET_get_bytes(pkt, &data, i)) {
SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_SRP_A_LENGTH);
return 0;
}
if ((s->srp_ctx.A = BN_bin2bn(data, i, NULL)) == NULL) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_BN_LIB);
return 0;
}
if (BN_ucmp(s->srp_ctx.A, s->srp_ctx.N) >= 0 || BN_is_zero(s->srp_ctx.A)) {
SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_BAD_SRP_PARAMETERS);
return 0;
}
OPENSSL_free(s->session->srp_username);
s->session->srp_username = OPENSSL_strdup(s->srp_ctx.login);
if (s->session->srp_username == NULL) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_MALLOC_FAILURE);
return 0;
}
if (!srp_generate_server_master_secret(s)) {
/* SSLfatal() already called */
return 0;
}
return 1;
#else
/* Should never happen */
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return 0;
#endif
}
static int tls_process_cke_gost(SSL *s, PACKET *pkt)
{
#ifndef OPENSSL_NO_GOST
EVP_PKEY_CTX *pkey_ctx;
EVP_PKEY *client_pub_pkey = NULL, *pk = NULL;
unsigned char premaster_secret[32];
const unsigned char *start;
size_t outlen = 32, inlen;
unsigned long alg_a;
GOST_KX_MESSAGE *pKX = NULL;
const unsigned char *ptr;
int ret = 0;
/* Get our certificate private key */
alg_a = s->s3.tmp.new_cipher->algorithm_auth;
if (alg_a & SSL_aGOST12) {
/*
* New GOST ciphersuites have SSL_aGOST01 bit too
*/
pk = s->cert->pkeys[SSL_PKEY_GOST12_512].privatekey;
if (pk == NULL) {
pk = s->cert->pkeys[SSL_PKEY_GOST12_256].privatekey;
}
if (pk == NULL) {
pk = s->cert->pkeys[SSL_PKEY_GOST01].privatekey;
}
} else if (alg_a & SSL_aGOST01) {
pk = s->cert->pkeys[SSL_PKEY_GOST01].privatekey;
}
pkey_ctx = EVP_PKEY_CTX_new_from_pkey(s->ctx->libctx, pk, s->ctx->propq);
if (pkey_ctx == NULL) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_MALLOC_FAILURE);
return 0;
}
if (EVP_PKEY_decrypt_init(pkey_ctx) <= 0) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
- return 0;
+ goto err;
}
/*
* If client certificate is present and is of the same type, maybe
* use it for key exchange. Don't mind errors from
* EVP_PKEY_derive_set_peer, because it is completely valid to use a
* client certificate for authorization only.
*/
client_pub_pkey = X509_get0_pubkey(s->session->peer);
if (client_pub_pkey) {
if (EVP_PKEY_derive_set_peer(pkey_ctx, client_pub_pkey) <= 0)
ERR_clear_error();
}
ptr = PACKET_data(pkt);
/* Some implementations provide extra data in the opaqueBlob
* We have nothing to do with this blob so we just skip it */
pKX = d2i_GOST_KX_MESSAGE(NULL, &ptr, PACKET_remaining(pkt));
if (pKX == NULL
|| pKX->kxBlob == NULL
|| ASN1_TYPE_get(pKX->kxBlob) != V_ASN1_SEQUENCE) {
SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_DECRYPTION_FAILED);
goto err;
}
if (!PACKET_forward(pkt, ptr - PACKET_data(pkt))) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_DECRYPTION_FAILED);
goto err;
}
if (PACKET_remaining(pkt) != 0) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_DECRYPTION_FAILED);
goto err;
}
inlen = pKX->kxBlob->value.sequence->length;
start = pKX->kxBlob->value.sequence->data;
if (EVP_PKEY_decrypt(pkey_ctx, premaster_secret, &outlen, start,
inlen) <= 0) {
SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_DECRYPTION_FAILED);
goto err;
}
/* Generate master secret */
if (!ssl_generate_master_secret(s, premaster_secret,
sizeof(premaster_secret), 0)) {
/* SSLfatal() already called */
goto err;
}
/* Check if pubkey from client certificate was used */
if (EVP_PKEY_CTX_ctrl(pkey_ctx, -1, -1, EVP_PKEY_CTRL_PEER_KEY, 2,
NULL) > 0)
s->statem.no_cert_verify = 1;
ret = 1;
err:
EVP_PKEY_CTX_free(pkey_ctx);
GOST_KX_MESSAGE_free(pKX);
return ret;
#else
/* Should never happen */
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return 0;
#endif
}
static int tls_process_cke_gost18(SSL *s, PACKET *pkt)
{
#ifndef OPENSSL_NO_GOST
unsigned char rnd_dgst[32];
EVP_PKEY_CTX *pkey_ctx = NULL;
EVP_PKEY *pk = NULL;
unsigned char premaster_secret[32];
const unsigned char *start = NULL;
size_t outlen = 32, inlen = 0;
int ret = 0;
int cipher_nid = ossl_gost18_cke_cipher_nid(s);
if (cipher_nid == NID_undef) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return 0;
}
if (ossl_gost_ukm(s, rnd_dgst) <= 0) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
goto err;
}
/* Get our certificate private key */
pk = s->cert->pkeys[SSL_PKEY_GOST12_512].privatekey != NULL ?
s->cert->pkeys[SSL_PKEY_GOST12_512].privatekey :
s->cert->pkeys[SSL_PKEY_GOST12_256].privatekey;
if (pk == NULL) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_BAD_HANDSHAKE_STATE);
goto err;
}
pkey_ctx = EVP_PKEY_CTX_new_from_pkey(s->ctx->libctx, pk, s->ctx->propq);
if (pkey_ctx == NULL) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_MALLOC_FAILURE);
goto err;
}
if (EVP_PKEY_decrypt_init(pkey_ctx) <= 0) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
goto err;
}
/* Reuse EVP_PKEY_CTRL_SET_IV, make choice in engine code depending on size */
if (EVP_PKEY_CTX_ctrl(pkey_ctx, -1, EVP_PKEY_OP_DECRYPT,
EVP_PKEY_CTRL_SET_IV, 32, rnd_dgst) <= 0) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_LIBRARY_BUG);
goto err;
}
if (EVP_PKEY_CTX_ctrl(pkey_ctx, -1, EVP_PKEY_OP_DECRYPT,
EVP_PKEY_CTRL_CIPHER, cipher_nid, NULL) <= 0) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_LIBRARY_BUG);
goto err;
}
inlen = PACKET_remaining(pkt);
start = PACKET_data(pkt);
if (EVP_PKEY_decrypt(pkey_ctx, premaster_secret, &outlen, start, inlen) <= 0) {
SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_DECRYPTION_FAILED);
goto err;
}
/* Generate master secret */
if (!ssl_generate_master_secret(s, premaster_secret,
sizeof(premaster_secret), 0)) {
/* SSLfatal() already called */
goto err;
}
ret = 1;
err:
EVP_PKEY_CTX_free(pkey_ctx);
return ret;
#else
/* Should never happen */
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return 0;
#endif
}
MSG_PROCESS_RETURN tls_process_client_key_exchange(SSL *s, PACKET *pkt)
{
unsigned long alg_k;
alg_k = s->s3.tmp.new_cipher->algorithm_mkey;
/* For PSK parse and retrieve identity, obtain PSK key */
if ((alg_k & SSL_PSK) && !tls_process_cke_psk_preamble(s, pkt)) {
/* SSLfatal() already called */
goto err;
}
if (alg_k & SSL_kPSK) {
/* Identity extracted earlier: should be nothing left */
if (PACKET_remaining(pkt) != 0) {
SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
goto err;
}
/* PSK handled by ssl_generate_master_secret */
if (!ssl_generate_master_secret(s, NULL, 0, 0)) {
/* SSLfatal() already called */
goto err;
}
} else if (alg_k & (SSL_kRSA | SSL_kRSAPSK)) {
if (!tls_process_cke_rsa(s, pkt)) {
/* SSLfatal() already called */
goto err;
}
} else if (alg_k & (SSL_kDHE | SSL_kDHEPSK)) {
if (!tls_process_cke_dhe(s, pkt)) {
/* SSLfatal() already called */
goto err;
}
} else if (alg_k & (SSL_kECDHE | SSL_kECDHEPSK)) {
if (!tls_process_cke_ecdhe(s, pkt)) {
/* SSLfatal() already called */
goto err;
}
} else if (alg_k & SSL_kSRP) {
if (!tls_process_cke_srp(s, pkt)) {
/* SSLfatal() already called */
goto err;
}
} else if (alg_k & SSL_kGOST) {
if (!tls_process_cke_gost(s, pkt)) {
/* SSLfatal() already called */
goto err;
}
} else if (alg_k & SSL_kGOST18) {
if (!tls_process_cke_gost18(s, pkt)) {
/* SSLfatal() already called */
goto err;
}
} else {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_UNKNOWN_CIPHER_TYPE);
goto err;
}
return MSG_PROCESS_CONTINUE_PROCESSING;
err:
#ifndef OPENSSL_NO_PSK
OPENSSL_clear_free(s->s3.tmp.psk, s->s3.tmp.psklen);
s->s3.tmp.psk = NULL;
s->s3.tmp.psklen = 0;
#endif
return MSG_PROCESS_ERROR;
}
WORK_STATE tls_post_process_client_key_exchange(SSL *s, WORK_STATE wst)
{
#ifndef OPENSSL_NO_SCTP
if (wst == WORK_MORE_A) {
if (SSL_IS_DTLS(s)) {
unsigned char sctpauthkey[64];
char labelbuffer[sizeof(DTLS1_SCTP_AUTH_LABEL)];
size_t labellen;
/*
* Add new shared key for SCTP-Auth, will be ignored if no SCTP
* used.
*/
memcpy(labelbuffer, DTLS1_SCTP_AUTH_LABEL,
sizeof(DTLS1_SCTP_AUTH_LABEL));
/* Don't include the terminating zero. */
labellen = sizeof(labelbuffer) - 1;
if (s->mode & SSL_MODE_DTLS_SCTP_LABEL_LENGTH_BUG)
labellen += 1;
if (SSL_export_keying_material(s, sctpauthkey,
sizeof(sctpauthkey), labelbuffer,
labellen, NULL, 0,
0) <= 0) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return WORK_ERROR;
}
BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_ADD_AUTH_KEY,
sizeof(sctpauthkey), sctpauthkey);
}
}
#endif
if (s->statem.no_cert_verify || !s->session->peer) {
/*
* No certificate verify or no peer certificate so we no longer need
* the handshake_buffer
*/
if (!ssl3_digest_cached_records(s, 0)) {
/* SSLfatal() already called */
return WORK_ERROR;
}
return WORK_FINISHED_CONTINUE;
} else {
if (!s->s3.handshake_buffer) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return WORK_ERROR;
}
/*
* For sigalgs freeze the handshake buffer. If we support
* extms we've done this already so this is a no-op
*/
if (!ssl3_digest_cached_records(s, 1)) {
/* SSLfatal() already called */
return WORK_ERROR;
}
}
return WORK_FINISHED_CONTINUE;
}
MSG_PROCESS_RETURN tls_process_client_certificate(SSL *s, PACKET *pkt)
{
int i;
MSG_PROCESS_RETURN ret = MSG_PROCESS_ERROR;
X509 *x = NULL;
unsigned long l;
const unsigned char *certstart, *certbytes;
STACK_OF(X509) *sk = NULL;
PACKET spkt, context;
size_t chainidx;
SSL_SESSION *new_sess = NULL;
/*
* To get this far we must have read encrypted data from the client. We no
* longer tolerate unencrypted alerts. This value is ignored if less than
* TLSv1.3
*/
s->statem.enc_read_state = ENC_READ_STATE_VALID;
if ((sk = sk_X509_new_null()) == NULL) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_MALLOC_FAILURE);
goto err;
}
if (SSL_IS_TLS13(s) && (!PACKET_get_length_prefixed_1(pkt, &context)
|| (s->pha_context == NULL && PACKET_remaining(&context) != 0)
|| (s->pha_context != NULL &&
!PACKET_equal(&context, s->pha_context, s->pha_context_len)))) {
SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_INVALID_CONTEXT);
goto err;
}
if (!PACKET_get_length_prefixed_3(pkt, &spkt)
|| PACKET_remaining(pkt) != 0) {
SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
goto err;
}
for (chainidx = 0; PACKET_remaining(&spkt) > 0; chainidx++) {
if (!PACKET_get_net_3(&spkt, &l)
|| !PACKET_get_bytes(&spkt, &certbytes, l)) {
SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_CERT_LENGTH_MISMATCH);
goto err;
}
certstart = certbytes;
x = X509_new_ex(s->ctx->libctx, s->ctx->propq);
if (x == NULL) {
SSLfatal(s, SSL_AD_DECODE_ERROR, ERR_R_MALLOC_FAILURE);
goto err;
}
if (d2i_X509(&x, (const unsigned char **)&certbytes, l) == NULL) {
SSLfatal(s, SSL_AD_DECODE_ERROR, ERR_R_ASN1_LIB);
goto err;
}
if (certbytes != (certstart + l)) {
SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_CERT_LENGTH_MISMATCH);
goto err;
}
if (SSL_IS_TLS13(s)) {
RAW_EXTENSION *rawexts = NULL;
PACKET extensions;
if (!PACKET_get_length_prefixed_2(&spkt, &extensions)) {
SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_LENGTH);
goto err;
}
if (!tls_collect_extensions(s, &extensions,
SSL_EXT_TLS1_3_CERTIFICATE, &rawexts,
NULL, chainidx == 0)
|| !tls_parse_all_extensions(s, SSL_EXT_TLS1_3_CERTIFICATE,
rawexts, x, chainidx,
PACKET_remaining(&spkt) == 0)) {
OPENSSL_free(rawexts);
goto err;
}
OPENSSL_free(rawexts);
}
if (!sk_X509_push(sk, x)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_MALLOC_FAILURE);
goto err;
}
x = NULL;
}
if (sk_X509_num(sk) <= 0) {
/* TLS does not mind 0 certs returned */
if (s->version == SSL3_VERSION) {
SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
SSL_R_NO_CERTIFICATES_RETURNED);
goto err;
}
/* Fail for TLS only if we required a certificate */
else if ((s->verify_mode & SSL_VERIFY_PEER) &&
(s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) {
SSLfatal(s, SSL_AD_CERTIFICATE_REQUIRED,
SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
goto err;
}
/* No client certificate so digest cached records */
if (s->s3.handshake_buffer && !ssl3_digest_cached_records(s, 0)) {
/* SSLfatal() already called */
goto err;
}
} else {
EVP_PKEY *pkey;
i = ssl_verify_cert_chain(s, sk);
if (i <= 0) {
SSLfatal(s, ssl_x509err2alert(s->verify_result),
SSL_R_CERTIFICATE_VERIFY_FAILED);
goto err;
}
pkey = X509_get0_pubkey(sk_X509_value(sk, 0));
if (pkey == NULL) {
SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
SSL_R_UNKNOWN_CERTIFICATE_TYPE);
goto err;
}
}
/*
* Sessions must be immutable once they go into the session cache. Otherwise
* we can get multi-thread problems. Therefore we don't "update" sessions,
* we replace them with a duplicate. Here, we need to do this every time
* a new certificate is received via post-handshake authentication, as the
* session may have already gone into the session cache.
*/
if (s->post_handshake_auth == SSL_PHA_REQUESTED) {
if ((new_sess = ssl_session_dup(s->session, 0)) == 0) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_MALLOC_FAILURE);
goto err;
}
SSL_SESSION_free(s->session);
s->session = new_sess;
}
X509_free(s->session->peer);
s->session->peer = sk_X509_shift(sk);
s->session->verify_result = s->verify_result;
sk_X509_pop_free(s->session->peer_chain, X509_free);
s->session->peer_chain = sk;
sk = NULL;
/*
* Freeze the handshake buffer. For <TLS1.3 we do this after the CKE
* message
*/
if (SSL_IS_TLS13(s) && !ssl3_digest_cached_records(s, 1)) {
/* SSLfatal() already called */
goto err;
}
/*
* Inconsistency alert: cert_chain does *not* include the peer's own
* certificate, while we do include it in statem_clnt.c
*/
/* Save the current hash state for when we receive the CertificateVerify */
if (SSL_IS_TLS13(s)) {
if (!ssl_handshake_hash(s, s->cert_verify_hash,
sizeof(s->cert_verify_hash),
&s->cert_verify_hash_len)) {
/* SSLfatal() already called */
goto err;
}
/* Resend session tickets */
s->sent_tickets = 0;
}
ret = MSG_PROCESS_CONTINUE_READING;
err:
X509_free(x);
sk_X509_pop_free(sk, X509_free);
return ret;
}
int tls_construct_server_certificate(SSL *s, WPACKET *pkt)
{
CERT_PKEY *cpk = s->s3.tmp.cert;
if (cpk == NULL) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return 0;
}
/*
* In TLSv1.3 the certificate chain is always preceded by a 0 length context
* for the server Certificate message
*/
if (SSL_IS_TLS13(s) && !WPACKET_put_bytes_u8(pkt, 0)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return 0;
}
if (!ssl3_output_cert_chain(s, pkt, cpk)) {
/* SSLfatal() already called */
return 0;
}
return 1;
}
static int create_ticket_prequel(SSL *s, WPACKET *pkt, uint32_t age_add,
unsigned char *tick_nonce)
{
uint32_t timeout = (uint32_t)s->session->timeout;
/*
* Ticket lifetime hint:
* In TLSv1.3 we reset the "time" field above, and always specify the
* timeout, limited to a 1 week period per RFC8446.
* For TLSv1.2 this is advisory only and we leave this unspecified for
* resumed session (for simplicity).
*/
#define ONE_WEEK_SEC (7 * 24 * 60 * 60)
if (SSL_IS_TLS13(s)) {
if (s->session->timeout > ONE_WEEK_SEC)
timeout = ONE_WEEK_SEC;
} else if (s->hit)
timeout = 0;
if (!WPACKET_put_bytes_u32(pkt, timeout)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return 0;
}
if (SSL_IS_TLS13(s)) {
if (!WPACKET_put_bytes_u32(pkt, age_add)
|| !WPACKET_sub_memcpy_u8(pkt, tick_nonce, TICKET_NONCE_SIZE)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return 0;
}
}
/* Start the sub-packet for the actual ticket data */
if (!WPACKET_start_sub_packet_u16(pkt)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return 0;
}
return 1;
}
/*
* Returns 1 on success, 0 to abort construction of the ticket (non-fatal), or
* -1 on fatal error
*/
static int construct_stateless_ticket(SSL *s, WPACKET *pkt, uint32_t age_add,
unsigned char *tick_nonce)
{
unsigned char *senc = NULL;
EVP_CIPHER_CTX *ctx = NULL;
SSL_HMAC *hctx = NULL;
unsigned char *p, *encdata1, *encdata2, *macdata1, *macdata2;
const unsigned char *const_p;
int len, slen_full, slen, lenfinal;
SSL_SESSION *sess;
size_t hlen;
SSL_CTX *tctx = s->session_ctx;
unsigned char iv[EVP_MAX_IV_LENGTH];
unsigned char key_name[TLSEXT_KEYNAME_LENGTH];
int iv_len, ok = -1;
size_t macoffset, macendoffset;
/* get session encoding length */
slen_full = i2d_SSL_SESSION(s->session, NULL);
/*
* Some length values are 16 bits, so forget it if session is too
* long
*/
if (slen_full == 0 || slen_full > 0xFF00) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
goto err;
}
senc = OPENSSL_malloc(slen_full);
if (senc == NULL) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_MALLOC_FAILURE);
goto err;
}
ctx = EVP_CIPHER_CTX_new();
hctx = ssl_hmac_new(tctx);
if (ctx == NULL || hctx == NULL) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_MALLOC_FAILURE);
goto err;
}
p = senc;
if (!i2d_SSL_SESSION(s->session, &p)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
goto err;
}
/*
* create a fresh copy (not shared with other threads) to clean up
*/
const_p = senc;
sess = d2i_SSL_SESSION(NULL, &const_p, slen_full);
if (sess == NULL) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
goto err;
}
slen = i2d_SSL_SESSION(sess, NULL);
if (slen == 0 || slen > slen_full) {
/* shouldn't ever happen */
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
SSL_SESSION_free(sess);
goto err;
}
p = senc;
if (!i2d_SSL_SESSION(sess, &p)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
SSL_SESSION_free(sess);
goto err;
}
SSL_SESSION_free(sess);
/*
* Initialize HMAC and cipher contexts. If callback present it does
* all the work otherwise use generated values from parent ctx.
*/
#ifndef OPENSSL_NO_DEPRECATED_3_0
if (tctx->ext.ticket_key_evp_cb != NULL || tctx->ext.ticket_key_cb != NULL)
#else
if (tctx->ext.ticket_key_evp_cb != NULL)
#endif
{
int ret = 0;
if (tctx->ext.ticket_key_evp_cb != NULL)
ret = tctx->ext.ticket_key_evp_cb(s, key_name, iv, ctx,
ssl_hmac_get0_EVP_MAC_CTX(hctx),
1);
#ifndef OPENSSL_NO_DEPRECATED_3_0
else if (tctx->ext.ticket_key_cb != NULL)
/* if 0 is returned, write an empty ticket */
ret = tctx->ext.ticket_key_cb(s, key_name, iv, ctx,
ssl_hmac_get0_HMAC_CTX(hctx), 1);
#endif
if (ret == 0) {
/*
* In TLSv1.2 we construct a 0 length ticket. In TLSv1.3 a 0
* length ticket is not allowed so we abort construction of the
* ticket
*/
if (SSL_IS_TLS13(s)) {
ok = 0;
goto err;
}
/* Put timeout and length */
if (!WPACKET_put_bytes_u32(pkt, 0)
|| !WPACKET_put_bytes_u16(pkt, 0)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
goto err;
}
OPENSSL_free(senc);
EVP_CIPHER_CTX_free(ctx);
ssl_hmac_free(hctx);
return 1;
}
if (ret < 0) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_CALLBACK_FAILED);
goto err;
}
iv_len = EVP_CIPHER_CTX_get_iv_length(ctx);
if (iv_len < 0) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
goto err;
}
} else {
EVP_CIPHER *cipher = EVP_CIPHER_fetch(s->ctx->libctx, "AES-256-CBC",
s->ctx->propq);
if (cipher == NULL) {
/* Error is already recorded */
SSLfatal_alert(s, SSL_AD_INTERNAL_ERROR);
goto err;
}
iv_len = EVP_CIPHER_get_iv_length(cipher);
if (iv_len < 0
|| RAND_bytes_ex(s->ctx->libctx, iv, iv_len, 0) <= 0
|| !EVP_EncryptInit_ex(ctx, cipher, NULL,
tctx->ext.secure->tick_aes_key, iv)
|| !ssl_hmac_init(hctx, tctx->ext.secure->tick_hmac_key,
sizeof(tctx->ext.secure->tick_hmac_key),
"SHA256")) {
EVP_CIPHER_free(cipher);
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
goto err;
}
EVP_CIPHER_free(cipher);
memcpy(key_name, tctx->ext.tick_key_name,
sizeof(tctx->ext.tick_key_name));
}
if (!create_ticket_prequel(s, pkt, age_add, tick_nonce)) {
/* SSLfatal() already called */
goto err;
}
if (!WPACKET_get_total_written(pkt, &macoffset)
/* Output key name */
|| !WPACKET_memcpy(pkt, key_name, sizeof(key_name))
/* output IV */
|| !WPACKET_memcpy(pkt, iv, iv_len)
|| !WPACKET_reserve_bytes(pkt, slen + EVP_MAX_BLOCK_LENGTH,
&encdata1)
/* Encrypt session data */
|| !EVP_EncryptUpdate(ctx, encdata1, &len, senc, slen)
|| !WPACKET_allocate_bytes(pkt, len, &encdata2)
|| encdata1 != encdata2
|| !EVP_EncryptFinal(ctx, encdata1 + len, &lenfinal)
|| !WPACKET_allocate_bytes(pkt, lenfinal, &encdata2)
|| encdata1 + len != encdata2
|| len + lenfinal > slen + EVP_MAX_BLOCK_LENGTH
|| !WPACKET_get_total_written(pkt, &macendoffset)
|| !ssl_hmac_update(hctx,
(unsigned char *)s->init_buf->data + macoffset,
macendoffset - macoffset)
|| !WPACKET_reserve_bytes(pkt, EVP_MAX_MD_SIZE, &macdata1)
|| !ssl_hmac_final(hctx, macdata1, &hlen, EVP_MAX_MD_SIZE)
|| hlen > EVP_MAX_MD_SIZE
|| !WPACKET_allocate_bytes(pkt, hlen, &macdata2)
|| macdata1 != macdata2) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
goto err;
}
/* Close the sub-packet created by create_ticket_prequel() */
if (!WPACKET_close(pkt)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
goto err;
}
ok = 1;
err:
OPENSSL_free(senc);
EVP_CIPHER_CTX_free(ctx);
ssl_hmac_free(hctx);
return ok;
}
static int construct_stateful_ticket(SSL *s, WPACKET *pkt, uint32_t age_add,
unsigned char *tick_nonce)
{
if (!create_ticket_prequel(s, pkt, age_add, tick_nonce)) {
/* SSLfatal() already called */
return 0;
}
if (!WPACKET_memcpy(pkt, s->session->session_id,
s->session->session_id_length)
|| !WPACKET_close(pkt)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return 0;
}
return 1;
}
static void tls_update_ticket_counts(SSL *s)
{
/*
* Increment both |sent_tickets| and |next_ticket_nonce|. |sent_tickets|
* gets reset to 0 if we send more tickets following a post-handshake
* auth, but |next_ticket_nonce| does not. If we're sending extra
* tickets, decrement the count of pending extra tickets.
*/
s->sent_tickets++;
s->next_ticket_nonce++;
if (s->ext.extra_tickets_expected > 0)
s->ext.extra_tickets_expected--;
}
int tls_construct_new_session_ticket(SSL *s, WPACKET *pkt)
{
SSL_CTX *tctx = s->session_ctx;
unsigned char tick_nonce[TICKET_NONCE_SIZE];
union {
unsigned char age_add_c[sizeof(uint32_t)];
uint32_t age_add;
} age_add_u;
int ret = 0;
age_add_u.age_add = 0;
if (SSL_IS_TLS13(s)) {
size_t i, hashlen;
uint64_t nonce;
static const unsigned char nonce_label[] = "resumption";
const EVP_MD *md = ssl_handshake_md(s);
int hashleni = EVP_MD_get_size(md);
/* Ensure cast to size_t is safe */
if (!ossl_assert(hashleni >= 0)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
goto err;
}
hashlen = (size_t)hashleni;
/*
* If we already sent one NewSessionTicket, or we resumed then
* s->session may already be in a cache and so we must not modify it.
* Instead we need to take a copy of it and modify that.
*/
if (s->sent_tickets != 0 || s->hit) {
SSL_SESSION *new_sess = ssl_session_dup(s->session, 0);
if (new_sess == NULL) {
/* SSLfatal already called */
goto err;
}
SSL_SESSION_free(s->session);
s->session = new_sess;
}
if (!ssl_generate_session_id(s, s->session)) {
/* SSLfatal() already called */
goto err;
}
if (RAND_bytes_ex(s->ctx->libctx, age_add_u.age_add_c,
sizeof(age_add_u), 0) <= 0) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
goto err;
}
s->session->ext.tick_age_add = age_add_u.age_add;
nonce = s->next_ticket_nonce;
for (i = TICKET_NONCE_SIZE; i > 0; i--) {
tick_nonce[i - 1] = (unsigned char)(nonce & 0xff);
nonce >>= 8;
}
if (!tls13_hkdf_expand(s, md, s->resumption_master_secret,
nonce_label,
sizeof(nonce_label) - 1,
tick_nonce,
TICKET_NONCE_SIZE,
s->session->master_key,
hashlen, 1)) {
/* SSLfatal() already called */
goto err;
}
s->session->master_key_length = hashlen;
s->session->time = time(NULL);
ssl_session_calculate_timeout(s->session);
if (s->s3.alpn_selected != NULL) {
OPENSSL_free(s->session->ext.alpn_selected);
s->session->ext.alpn_selected =
OPENSSL_memdup(s->s3.alpn_selected, s->s3.alpn_selected_len);
if (s->session->ext.alpn_selected == NULL) {
s->session->ext.alpn_selected_len = 0;
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_MALLOC_FAILURE);
goto err;
}
s->session->ext.alpn_selected_len = s->s3.alpn_selected_len;
}
s->session->ext.max_early_data = s->max_early_data;
}
if (tctx->generate_ticket_cb != NULL &&
tctx->generate_ticket_cb(s, tctx->ticket_cb_data) == 0) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
goto err;
}
/*
* If we are using anti-replay protection then we behave as if
* SSL_OP_NO_TICKET is set - we are caching tickets anyway so there
* is no point in using full stateless tickets.
*/
if (SSL_IS_TLS13(s)
&& ((s->options & SSL_OP_NO_TICKET) != 0
|| (s->max_early_data > 0
&& (s->options & SSL_OP_NO_ANTI_REPLAY) == 0))) {
if (!construct_stateful_ticket(s, pkt, age_add_u.age_add, tick_nonce)) {
/* SSLfatal() already called */
goto err;
}
} else {
int tmpret;
tmpret = construct_stateless_ticket(s, pkt, age_add_u.age_add,
tick_nonce);
if (tmpret != 1) {
if (tmpret == 0) {
ret = 2; /* Non-fatal. Abort construction but continue */
/* We count this as a success so update the counts anwyay */
tls_update_ticket_counts(s);
}
/* else SSLfatal() already called */
goto err;
}
}
if (SSL_IS_TLS13(s)) {
if (!tls_construct_extensions(s, pkt,
SSL_EXT_TLS1_3_NEW_SESSION_TICKET,
NULL, 0)) {
/* SSLfatal() already called */
goto err;
}
tls_update_ticket_counts(s);
ssl_update_cache(s, SSL_SESS_CACHE_SERVER);
}
ret = 1;
err:
return ret;
}
/*
* In TLSv1.3 this is called from the extensions code, otherwise it is used to
* create a separate message. Returns 1 on success or 0 on failure.
*/
int tls_construct_cert_status_body(SSL *s, WPACKET *pkt)
{
if (!WPACKET_put_bytes_u8(pkt, s->ext.status_type)
|| !WPACKET_sub_memcpy_u24(pkt, s->ext.ocsp.resp,
s->ext.ocsp.resp_len)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return 0;
}
return 1;
}
int tls_construct_cert_status(SSL *s, WPACKET *pkt)
{
if (!tls_construct_cert_status_body(s, pkt)) {
/* SSLfatal() already called */
return 0;
}
return 1;
}
#ifndef OPENSSL_NO_NEXTPROTONEG
/*
* tls_process_next_proto reads a Next Protocol Negotiation handshake message.
* It sets the next_proto member in s if found
*/
MSG_PROCESS_RETURN tls_process_next_proto(SSL *s, PACKET *pkt)
{
PACKET next_proto, padding;
size_t next_proto_len;
/*-
* The payload looks like:
* uint8 proto_len;
* uint8 proto[proto_len];
* uint8 padding_len;
* uint8 padding[padding_len];
*/
if (!PACKET_get_length_prefixed_1(pkt, &next_proto)
|| !PACKET_get_length_prefixed_1(pkt, &padding)
|| PACKET_remaining(pkt) > 0) {
SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
return MSG_PROCESS_ERROR;
}
if (!PACKET_memdup(&next_proto, &s->ext.npn, &next_proto_len)) {
s->ext.npn_len = 0;
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return MSG_PROCESS_ERROR;
}
s->ext.npn_len = (unsigned char)next_proto_len;
return MSG_PROCESS_CONTINUE_READING;
}
#endif
static int tls_construct_encrypted_extensions(SSL *s, WPACKET *pkt)
{
if (!tls_construct_extensions(s, pkt, SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS,
NULL, 0)) {
/* SSLfatal() already called */
return 0;
}
return 1;
}
MSG_PROCESS_RETURN tls_process_end_of_early_data(SSL *s, PACKET *pkt)
{
if (PACKET_remaining(pkt) != 0) {
SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
return MSG_PROCESS_ERROR;
}
if (s->early_data_state != SSL_EARLY_DATA_READING
&& s->early_data_state != SSL_EARLY_DATA_READ_RETRY) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return MSG_PROCESS_ERROR;
}
/*
* EndOfEarlyData signals a key change so the end of the message must be on
* a record boundary.
*/
if (RECORD_LAYER_processed_read_pending(&s->rlayer)) {
SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_NOT_ON_RECORD_BOUNDARY);
return MSG_PROCESS_ERROR;
}
s->early_data_state = SSL_EARLY_DATA_FINISHED_READING;
if (!s->method->ssl3_enc->change_cipher_state(s,
SSL3_CC_HANDSHAKE | SSL3_CHANGE_CIPHER_SERVER_READ)) {
/* SSLfatal() already called */
return MSG_PROCESS_ERROR;
}
return MSG_PROCESS_CONTINUE_READING;
}
diff --git a/crypto/openssl/ssl/t1_lib.c b/crypto/openssl/ssl/t1_lib.c
index 8be00a4f3405..673e2f0f0248 100644
--- a/crypto/openssl/ssl/t1_lib.c
+++ b/crypto/openssl/ssl/t1_lib.c
@@ -1,3530 +1,3531 @@
/*
- * Copyright 1995-2023 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 1995-2024 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 <stdio.h>
#include <stdlib.h>
#include <openssl/objects.h>
#include <openssl/evp.h>
#include <openssl/hmac.h>
#include <openssl/core_names.h>
#include <openssl/ocsp.h>
#include <openssl/conf.h>
#include <openssl/x509v3.h>
#include <openssl/dh.h>
#include <openssl/bn.h>
#include <openssl/provider.h>
#include <openssl/param_build.h>
#include "internal/nelem.h"
#include "internal/sizes.h"
#include "internal/tlsgroups.h"
#include "internal/cryptlib.h"
#include "ssl_local.h"
#include <openssl/ct.h>
static const SIGALG_LOOKUP *find_sig_alg(SSL *s, X509 *x, EVP_PKEY *pkey);
static int tls12_sigalg_allowed(const SSL *s, int op, const SIGALG_LOOKUP *lu);
SSL3_ENC_METHOD const TLSv1_enc_data = {
tls1_enc,
tls1_mac,
tls1_setup_key_block,
tls1_generate_master_secret,
tls1_change_cipher_state,
tls1_final_finish_mac,
TLS_MD_CLIENT_FINISH_CONST, TLS_MD_CLIENT_FINISH_CONST_SIZE,
TLS_MD_SERVER_FINISH_CONST, TLS_MD_SERVER_FINISH_CONST_SIZE,
tls1_alert_code,
tls1_export_keying_material,
0,
ssl3_set_handshake_header,
tls_close_construct_packet,
ssl3_handshake_write
};
SSL3_ENC_METHOD const TLSv1_1_enc_data = {
tls1_enc,
tls1_mac,
tls1_setup_key_block,
tls1_generate_master_secret,
tls1_change_cipher_state,
tls1_final_finish_mac,
TLS_MD_CLIENT_FINISH_CONST, TLS_MD_CLIENT_FINISH_CONST_SIZE,
TLS_MD_SERVER_FINISH_CONST, TLS_MD_SERVER_FINISH_CONST_SIZE,
tls1_alert_code,
tls1_export_keying_material,
SSL_ENC_FLAG_EXPLICIT_IV,
ssl3_set_handshake_header,
tls_close_construct_packet,
ssl3_handshake_write
};
SSL3_ENC_METHOD const TLSv1_2_enc_data = {
tls1_enc,
tls1_mac,
tls1_setup_key_block,
tls1_generate_master_secret,
tls1_change_cipher_state,
tls1_final_finish_mac,
TLS_MD_CLIENT_FINISH_CONST, TLS_MD_CLIENT_FINISH_CONST_SIZE,
TLS_MD_SERVER_FINISH_CONST, TLS_MD_SERVER_FINISH_CONST_SIZE,
tls1_alert_code,
tls1_export_keying_material,
SSL_ENC_FLAG_EXPLICIT_IV | SSL_ENC_FLAG_SIGALGS | SSL_ENC_FLAG_SHA256_PRF
| SSL_ENC_FLAG_TLS1_2_CIPHERS,
ssl3_set_handshake_header,
tls_close_construct_packet,
ssl3_handshake_write
};
SSL3_ENC_METHOD const TLSv1_3_enc_data = {
tls13_enc,
tls1_mac,
tls13_setup_key_block,
tls13_generate_master_secret,
tls13_change_cipher_state,
tls13_final_finish_mac,
TLS_MD_CLIENT_FINISH_CONST, TLS_MD_CLIENT_FINISH_CONST_SIZE,
TLS_MD_SERVER_FINISH_CONST, TLS_MD_SERVER_FINISH_CONST_SIZE,
tls13_alert_code,
tls13_export_keying_material,
SSL_ENC_FLAG_SIGALGS | SSL_ENC_FLAG_SHA256_PRF,
ssl3_set_handshake_header,
tls_close_construct_packet,
ssl3_handshake_write
};
long tls1_default_timeout(void)
{
/*
* 2 hours, the 24 hours mentioned in the TLSv1 spec is way too long for
* http, the cache would over fill
*/
return (60 * 60 * 2);
}
int tls1_new(SSL *s)
{
if (!ssl3_new(s))
return 0;
if (!s->method->ssl_clear(s))
return 0;
return 1;
}
void tls1_free(SSL *s)
{
OPENSSL_free(s->ext.session_ticket);
ssl3_free(s);
}
int tls1_clear(SSL *s)
{
if (!ssl3_clear(s))
return 0;
if (s->method->version == TLS_ANY_VERSION)
s->version = TLS_MAX_VERSION_INTERNAL;
else
s->version = s->method->version;
return 1;
}
/* Legacy NID to group_id mapping. Only works for groups we know about */
static struct {
int nid;
uint16_t group_id;
} nid_to_group[] = {
{NID_sect163k1, OSSL_TLS_GROUP_ID_sect163k1},
{NID_sect163r1, OSSL_TLS_GROUP_ID_sect163r1},
{NID_sect163r2, OSSL_TLS_GROUP_ID_sect163r2},
{NID_sect193r1, OSSL_TLS_GROUP_ID_sect193r1},
{NID_sect193r2, OSSL_TLS_GROUP_ID_sect193r2},
{NID_sect233k1, OSSL_TLS_GROUP_ID_sect233k1},
{NID_sect233r1, OSSL_TLS_GROUP_ID_sect233r1},
{NID_sect239k1, OSSL_TLS_GROUP_ID_sect239k1},
{NID_sect283k1, OSSL_TLS_GROUP_ID_sect283k1},
{NID_sect283r1, OSSL_TLS_GROUP_ID_sect283r1},
{NID_sect409k1, OSSL_TLS_GROUP_ID_sect409k1},
{NID_sect409r1, OSSL_TLS_GROUP_ID_sect409r1},
{NID_sect571k1, OSSL_TLS_GROUP_ID_sect571k1},
{NID_sect571r1, OSSL_TLS_GROUP_ID_sect571r1},
{NID_secp160k1, OSSL_TLS_GROUP_ID_secp160k1},
{NID_secp160r1, OSSL_TLS_GROUP_ID_secp160r1},
{NID_secp160r2, OSSL_TLS_GROUP_ID_secp160r2},
{NID_secp192k1, OSSL_TLS_GROUP_ID_secp192k1},
{NID_X9_62_prime192v1, OSSL_TLS_GROUP_ID_secp192r1},
{NID_secp224k1, OSSL_TLS_GROUP_ID_secp224k1},
{NID_secp224r1, OSSL_TLS_GROUP_ID_secp224r1},
{NID_secp256k1, OSSL_TLS_GROUP_ID_secp256k1},
{NID_X9_62_prime256v1, OSSL_TLS_GROUP_ID_secp256r1},
{NID_secp384r1, OSSL_TLS_GROUP_ID_secp384r1},
{NID_secp521r1, OSSL_TLS_GROUP_ID_secp521r1},
{NID_brainpoolP256r1, OSSL_TLS_GROUP_ID_brainpoolP256r1},
{NID_brainpoolP384r1, OSSL_TLS_GROUP_ID_brainpoolP384r1},
{NID_brainpoolP512r1, OSSL_TLS_GROUP_ID_brainpoolP512r1},
{EVP_PKEY_X25519, OSSL_TLS_GROUP_ID_x25519},
{EVP_PKEY_X448, OSSL_TLS_GROUP_ID_x448},
{NID_id_tc26_gost_3410_2012_256_paramSetA, 0x0022},
{NID_id_tc26_gost_3410_2012_256_paramSetB, 0x0023},
{NID_id_tc26_gost_3410_2012_256_paramSetC, 0x0024},
{NID_id_tc26_gost_3410_2012_256_paramSetD, 0x0025},
{NID_id_tc26_gost_3410_2012_512_paramSetA, 0x0026},
{NID_id_tc26_gost_3410_2012_512_paramSetB, 0x0027},
{NID_id_tc26_gost_3410_2012_512_paramSetC, 0x0028},
{NID_ffdhe2048, OSSL_TLS_GROUP_ID_ffdhe2048},
{NID_ffdhe3072, OSSL_TLS_GROUP_ID_ffdhe3072},
{NID_ffdhe4096, OSSL_TLS_GROUP_ID_ffdhe4096},
{NID_ffdhe6144, OSSL_TLS_GROUP_ID_ffdhe6144},
{NID_ffdhe8192, OSSL_TLS_GROUP_ID_ffdhe8192}
};
static const unsigned char ecformats_default[] = {
TLSEXT_ECPOINTFORMAT_uncompressed,
TLSEXT_ECPOINTFORMAT_ansiX962_compressed_prime,
TLSEXT_ECPOINTFORMAT_ansiX962_compressed_char2
};
/* The default curves */
static const uint16_t supported_groups_default[] = {
29, /* X25519 (29) */
23, /* secp256r1 (23) */
30, /* X448 (30) */
25, /* secp521r1 (25) */
24, /* secp384r1 (24) */
34, /* GC256A (34) */
35, /* GC256B (35) */
36, /* GC256C (36) */
37, /* GC256D (37) */
38, /* GC512A (38) */
39, /* GC512B (39) */
40, /* GC512C (40) */
0x100, /* ffdhe2048 (0x100) */
0x101, /* ffdhe3072 (0x101) */
0x102, /* ffdhe4096 (0x102) */
0x103, /* ffdhe6144 (0x103) */
0x104, /* ffdhe8192 (0x104) */
};
static const uint16_t suiteb_curves[] = {
TLSEXT_curve_P_256,
TLSEXT_curve_P_384
};
struct provider_group_data_st {
SSL_CTX *ctx;
OSSL_PROVIDER *provider;
};
#define TLS_GROUP_LIST_MALLOC_BLOCK_SIZE 10
static OSSL_CALLBACK add_provider_groups;
static int add_provider_groups(const OSSL_PARAM params[], void *data)
{
struct provider_group_data_st *pgd = data;
SSL_CTX *ctx = pgd->ctx;
OSSL_PROVIDER *provider = pgd->provider;
const OSSL_PARAM *p;
TLS_GROUP_INFO *ginf = NULL;
EVP_KEYMGMT *keymgmt;
unsigned int gid;
unsigned int is_kem = 0;
int ret = 0;
if (ctx->group_list_max_len == ctx->group_list_len) {
TLS_GROUP_INFO *tmp = NULL;
if (ctx->group_list_max_len == 0)
tmp = OPENSSL_malloc(sizeof(TLS_GROUP_INFO)
* TLS_GROUP_LIST_MALLOC_BLOCK_SIZE);
else
tmp = OPENSSL_realloc(ctx->group_list,
(ctx->group_list_max_len
+ TLS_GROUP_LIST_MALLOC_BLOCK_SIZE)
* sizeof(TLS_GROUP_INFO));
if (tmp == NULL) {
ERR_raise(ERR_LIB_SSL, ERR_R_MALLOC_FAILURE);
return 0;
}
ctx->group_list = tmp;
memset(tmp + ctx->group_list_max_len,
0,
sizeof(TLS_GROUP_INFO) * TLS_GROUP_LIST_MALLOC_BLOCK_SIZE);
ctx->group_list_max_len += TLS_GROUP_LIST_MALLOC_BLOCK_SIZE;
}
ginf = &ctx->group_list[ctx->group_list_len];
p = OSSL_PARAM_locate_const(params, OSSL_CAPABILITY_TLS_GROUP_NAME);
if (p == NULL || p->data_type != OSSL_PARAM_UTF8_STRING) {
ERR_raise(ERR_LIB_SSL, ERR_R_PASSED_INVALID_ARGUMENT);
goto err;
}
ginf->tlsname = OPENSSL_strdup(p->data);
if (ginf->tlsname == NULL) {
ERR_raise(ERR_LIB_SSL, ERR_R_MALLOC_FAILURE);
goto err;
}
p = OSSL_PARAM_locate_const(params, OSSL_CAPABILITY_TLS_GROUP_NAME_INTERNAL);
if (p == NULL || p->data_type != OSSL_PARAM_UTF8_STRING) {
ERR_raise(ERR_LIB_SSL, ERR_R_PASSED_INVALID_ARGUMENT);
goto err;
}
ginf->realname = OPENSSL_strdup(p->data);
if (ginf->realname == NULL) {
ERR_raise(ERR_LIB_SSL, ERR_R_MALLOC_FAILURE);
goto err;
}
p = OSSL_PARAM_locate_const(params, OSSL_CAPABILITY_TLS_GROUP_ID);
if (p == NULL || !OSSL_PARAM_get_uint(p, &gid) || gid > UINT16_MAX) {
ERR_raise(ERR_LIB_SSL, ERR_R_PASSED_INVALID_ARGUMENT);
goto err;
}
ginf->group_id = (uint16_t)gid;
p = OSSL_PARAM_locate_const(params, OSSL_CAPABILITY_TLS_GROUP_ALG);
if (p == NULL || p->data_type != OSSL_PARAM_UTF8_STRING) {
ERR_raise(ERR_LIB_SSL, ERR_R_PASSED_INVALID_ARGUMENT);
goto err;
}
ginf->algorithm = OPENSSL_strdup(p->data);
if (ginf->algorithm == NULL) {
ERR_raise(ERR_LIB_SSL, ERR_R_MALLOC_FAILURE);
goto err;
}
p = OSSL_PARAM_locate_const(params, OSSL_CAPABILITY_TLS_GROUP_SECURITY_BITS);
if (p == NULL || !OSSL_PARAM_get_uint(p, &ginf->secbits)) {
ERR_raise(ERR_LIB_SSL, ERR_R_PASSED_INVALID_ARGUMENT);
goto err;
}
p = OSSL_PARAM_locate_const(params, OSSL_CAPABILITY_TLS_GROUP_IS_KEM);
if (p != NULL && (!OSSL_PARAM_get_uint(p, &is_kem) || is_kem > 1)) {
ERR_raise(ERR_LIB_SSL, ERR_R_PASSED_INVALID_ARGUMENT);
goto err;
}
ginf->is_kem = 1 & is_kem;
p = OSSL_PARAM_locate_const(params, OSSL_CAPABILITY_TLS_GROUP_MIN_TLS);
if (p == NULL || !OSSL_PARAM_get_int(p, &ginf->mintls)) {
ERR_raise(ERR_LIB_SSL, ERR_R_PASSED_INVALID_ARGUMENT);
goto err;
}
p = OSSL_PARAM_locate_const(params, OSSL_CAPABILITY_TLS_GROUP_MAX_TLS);
if (p == NULL || !OSSL_PARAM_get_int(p, &ginf->maxtls)) {
ERR_raise(ERR_LIB_SSL, ERR_R_PASSED_INVALID_ARGUMENT);
goto err;
}
p = OSSL_PARAM_locate_const(params, OSSL_CAPABILITY_TLS_GROUP_MIN_DTLS);
if (p == NULL || !OSSL_PARAM_get_int(p, &ginf->mindtls)) {
ERR_raise(ERR_LIB_SSL, ERR_R_PASSED_INVALID_ARGUMENT);
goto err;
}
p = OSSL_PARAM_locate_const(params, OSSL_CAPABILITY_TLS_GROUP_MAX_DTLS);
if (p == NULL || !OSSL_PARAM_get_int(p, &ginf->maxdtls)) {
ERR_raise(ERR_LIB_SSL, ERR_R_PASSED_INVALID_ARGUMENT);
goto err;
}
/*
* Now check that the algorithm is actually usable for our property query
* string. Regardless of the result we still return success because we have
* successfully processed this group, even though we may decide not to use
* it.
*/
ret = 1;
ERR_set_mark();
keymgmt = EVP_KEYMGMT_fetch(ctx->libctx, ginf->algorithm, ctx->propq);
if (keymgmt != NULL) {
/*
* We have successfully fetched the algorithm - however if the provider
* doesn't match this one then we ignore it.
*
* Note: We're cheating a little here. Technically if the same algorithm
* is available from more than one provider then it is undefined which
* implementation you will get back. Theoretically this could be
* different every time...we assume here that you'll always get the
* same one back if you repeat the exact same fetch. Is this a reasonable
* assumption to make (in which case perhaps we should document this
* behaviour)?
*/
if (EVP_KEYMGMT_get0_provider(keymgmt) == provider) {
/* We have a match - so we will use this group */
ctx->group_list_len++;
ginf = NULL;
}
EVP_KEYMGMT_free(keymgmt);
}
ERR_pop_to_mark();
err:
if (ginf != NULL) {
OPENSSL_free(ginf->tlsname);
OPENSSL_free(ginf->realname);
OPENSSL_free(ginf->algorithm);
ginf->algorithm = ginf->tlsname = ginf->realname = NULL;
}
return ret;
}
static int discover_provider_groups(OSSL_PROVIDER *provider, void *vctx)
{
struct provider_group_data_st pgd;
pgd.ctx = vctx;
pgd.provider = provider;
return OSSL_PROVIDER_get_capabilities(provider, "TLS-GROUP",
add_provider_groups, &pgd);
}
int ssl_load_groups(SSL_CTX *ctx)
{
size_t i, j, num_deflt_grps = 0;
uint16_t tmp_supp_groups[OSSL_NELEM(supported_groups_default)];
if (!OSSL_PROVIDER_do_all(ctx->libctx, discover_provider_groups, ctx))
return 0;
for (i = 0; i < OSSL_NELEM(supported_groups_default); i++) {
for (j = 0; j < ctx->group_list_len; j++) {
if (ctx->group_list[j].group_id == supported_groups_default[i]) {
tmp_supp_groups[num_deflt_grps++] = ctx->group_list[j].group_id;
break;
}
}
}
if (num_deflt_grps == 0)
return 1;
ctx->ext.supported_groups_default
= OPENSSL_malloc(sizeof(uint16_t) * num_deflt_grps);
if (ctx->ext.supported_groups_default == NULL) {
ERR_raise(ERR_LIB_SSL, ERR_R_MALLOC_FAILURE);
return 0;
}
memcpy(ctx->ext.supported_groups_default,
tmp_supp_groups,
num_deflt_grps * sizeof(tmp_supp_groups[0]));
ctx->ext.supported_groups_default_len = num_deflt_grps;
return 1;
}
static uint16_t tls1_group_name2id(SSL_CTX *ctx, const char *name)
{
size_t i;
for (i = 0; i < ctx->group_list_len; i++) {
if (strcmp(ctx->group_list[i].tlsname, name) == 0
|| strcmp(ctx->group_list[i].realname, name) == 0)
return ctx->group_list[i].group_id;
}
return 0;
}
const TLS_GROUP_INFO *tls1_group_id_lookup(SSL_CTX *ctx, uint16_t group_id)
{
size_t i;
for (i = 0; i < ctx->group_list_len; i++) {
if (ctx->group_list[i].group_id == group_id)
return &ctx->group_list[i];
}
return NULL;
}
int tls1_group_id2nid(uint16_t group_id, int include_unknown)
{
size_t i;
if (group_id == 0)
return NID_undef;
/*
* Return well known Group NIDs - for backwards compatibility. This won't
* work for groups we don't know about.
*/
for (i = 0; i < OSSL_NELEM(nid_to_group); i++)
{
if (nid_to_group[i].group_id == group_id)
return nid_to_group[i].nid;
}
if (!include_unknown)
return NID_undef;
return TLSEXT_nid_unknown | (int)group_id;
}
uint16_t tls1_nid2group_id(int nid)
{
size_t i;
/*
* Return well known Group ids - for backwards compatibility. This won't
* work for groups we don't know about.
*/
for (i = 0; i < OSSL_NELEM(nid_to_group); i++)
{
if (nid_to_group[i].nid == nid)
return nid_to_group[i].group_id;
}
return 0;
}
/*
* Set *pgroups to the supported groups list and *pgroupslen to
* the number of groups supported.
*/
void tls1_get_supported_groups(SSL *s, const uint16_t **pgroups,
size_t *pgroupslen)
{
/* For Suite B mode only include P-256, P-384 */
switch (tls1_suiteb(s)) {
case SSL_CERT_FLAG_SUITEB_128_LOS:
*pgroups = suiteb_curves;
*pgroupslen = OSSL_NELEM(suiteb_curves);
break;
case SSL_CERT_FLAG_SUITEB_128_LOS_ONLY:
*pgroups = suiteb_curves;
*pgroupslen = 1;
break;
case SSL_CERT_FLAG_SUITEB_192_LOS:
*pgroups = suiteb_curves + 1;
*pgroupslen = 1;
break;
default:
if (s->ext.supportedgroups == NULL) {
*pgroups = s->ctx->ext.supported_groups_default;
*pgroupslen = s->ctx->ext.supported_groups_default_len;
} else {
*pgroups = s->ext.supportedgroups;
*pgroupslen = s->ext.supportedgroups_len;
}
break;
}
}
int tls_valid_group(SSL *s, uint16_t group_id, int minversion, int maxversion,
int isec, int *okfortls13)
{
const TLS_GROUP_INFO *ginfo = tls1_group_id_lookup(s->ctx, group_id);
int ret;
if (okfortls13 != NULL)
*okfortls13 = 0;
if (ginfo == NULL)
return 0;
if (SSL_IS_DTLS(s)) {
if (ginfo->mindtls < 0 || ginfo->maxdtls < 0)
return 0;
if (ginfo->maxdtls == 0)
ret = 1;
else
ret = DTLS_VERSION_LE(minversion, ginfo->maxdtls);
if (ginfo->mindtls > 0)
ret &= DTLS_VERSION_GE(maxversion, ginfo->mindtls);
} else {
if (ginfo->mintls < 0 || ginfo->maxtls < 0)
return 0;
if (ginfo->maxtls == 0)
ret = 1;
else
ret = (minversion <= ginfo->maxtls);
if (ginfo->mintls > 0)
ret &= (maxversion >= ginfo->mintls);
if (ret && okfortls13 != NULL && maxversion == TLS1_3_VERSION)
*okfortls13 = (ginfo->maxtls == 0)
|| (ginfo->maxtls >= TLS1_3_VERSION);
}
ret &= !isec
|| strcmp(ginfo->algorithm, "EC") == 0
|| strcmp(ginfo->algorithm, "X25519") == 0
|| strcmp(ginfo->algorithm, "X448") == 0;
return ret;
}
/* See if group is allowed by security callback */
int tls_group_allowed(SSL *s, uint16_t group, int op)
{
const TLS_GROUP_INFO *ginfo = tls1_group_id_lookup(s->ctx, group);
unsigned char gtmp[2];
if (ginfo == NULL)
return 0;
gtmp[0] = group >> 8;
gtmp[1] = group & 0xff;
return ssl_security(s, op, ginfo->secbits,
tls1_group_id2nid(ginfo->group_id, 0), (void *)gtmp);
}
/* Return 1 if "id" is in "list" */
static int tls1_in_list(uint16_t id, const uint16_t *list, size_t listlen)
{
size_t i;
for (i = 0; i < listlen; i++)
if (list[i] == id)
return 1;
return 0;
}
/*-
* For nmatch >= 0, return the id of the |nmatch|th shared group or 0
* if there is no match.
* For nmatch == -1, return number of matches
* For nmatch == -2, return the id of the group to use for
* a tmp key, or 0 if there is no match.
*/
uint16_t tls1_shared_group(SSL *s, int nmatch)
{
const uint16_t *pref, *supp;
size_t num_pref, num_supp, i;
int k;
SSL_CTX *ctx = s->ctx;
/* Can't do anything on client side */
if (s->server == 0)
return 0;
if (nmatch == -2) {
if (tls1_suiteb(s)) {
/*
* For Suite B ciphersuite determines curve: we already know
* these are acceptable due to previous checks.
*/
unsigned long cid = s->s3.tmp.new_cipher->id;
if (cid == TLS1_CK_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256)
return TLSEXT_curve_P_256;
if (cid == TLS1_CK_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384)
return TLSEXT_curve_P_384;
/* Should never happen */
return 0;
}
/* If not Suite B just return first preference shared curve */
nmatch = 0;
}
/*
* If server preference set, our groups are the preference order
* otherwise peer decides.
*/
if (s->options & SSL_OP_CIPHER_SERVER_PREFERENCE) {
tls1_get_supported_groups(s, &pref, &num_pref);
tls1_get_peer_groups(s, &supp, &num_supp);
} else {
tls1_get_peer_groups(s, &pref, &num_pref);
tls1_get_supported_groups(s, &supp, &num_supp);
}
for (k = 0, i = 0; i < num_pref; i++) {
uint16_t id = pref[i];
const TLS_GROUP_INFO *inf;
if (!tls1_in_list(id, supp, num_supp)
|| !tls_group_allowed(s, id, SSL_SECOP_CURVE_SHARED))
continue;
inf = tls1_group_id_lookup(ctx, id);
if (!ossl_assert(inf != NULL))
return 0;
if (SSL_IS_DTLS(s)) {
if (inf->maxdtls == -1)
continue;
if ((inf->mindtls != 0 && DTLS_VERSION_LT(s->version, inf->mindtls))
|| (inf->maxdtls != 0
&& DTLS_VERSION_GT(s->version, inf->maxdtls)))
continue;
} else {
if (inf->maxtls == -1)
continue;
if ((inf->mintls != 0 && s->version < inf->mintls)
|| (inf->maxtls != 0 && s->version > inf->maxtls))
continue;
}
if (nmatch == k)
return id;
k++;
}
if (nmatch == -1)
return k;
/* Out of range (nmatch > k). */
return 0;
}
int tls1_set_groups(uint16_t **pext, size_t *pextlen,
int *groups, size_t ngroups)
{
uint16_t *glist;
size_t i;
/*
* Bitmap of groups included to detect duplicates: two variables are added
* to detect duplicates as some values are more than 32.
*/
unsigned long *dup_list = NULL;
unsigned long dup_list_egrp = 0;
unsigned long dup_list_dhgrp = 0;
if (ngroups == 0) {
ERR_raise(ERR_LIB_SSL, SSL_R_BAD_LENGTH);
return 0;
}
if ((glist = OPENSSL_malloc(ngroups * sizeof(*glist))) == NULL) {
ERR_raise(ERR_LIB_SSL, ERR_R_MALLOC_FAILURE);
return 0;
}
for (i = 0; i < ngroups; i++) {
unsigned long idmask;
uint16_t id;
id = tls1_nid2group_id(groups[i]);
if ((id & 0x00FF) >= (sizeof(unsigned long) * 8))
goto err;
idmask = 1L << (id & 0x00FF);
dup_list = (id < 0x100) ? &dup_list_egrp : &dup_list_dhgrp;
if (!id || ((*dup_list) & idmask))
goto err;
*dup_list |= idmask;
glist[i] = id;
}
OPENSSL_free(*pext);
*pext = glist;
*pextlen = ngroups;
return 1;
err:
OPENSSL_free(glist);
return 0;
}
# define GROUPLIST_INCREMENT 40
# define GROUP_NAME_BUFFER_LENGTH 64
typedef struct {
SSL_CTX *ctx;
size_t gidcnt;
size_t gidmax;
uint16_t *gid_arr;
} gid_cb_st;
static int gid_cb(const char *elem, int len, void *arg)
{
gid_cb_st *garg = arg;
size_t i;
uint16_t gid = 0;
char etmp[GROUP_NAME_BUFFER_LENGTH];
if (elem == NULL)
return 0;
if (garg->gidcnt == garg->gidmax) {
uint16_t *tmp =
- OPENSSL_realloc(garg->gid_arr, garg->gidmax + GROUPLIST_INCREMENT);
+ OPENSSL_realloc(garg->gid_arr,
+ (garg->gidmax + GROUPLIST_INCREMENT) * sizeof(*garg->gid_arr));
if (tmp == NULL)
return 0;
garg->gidmax += GROUPLIST_INCREMENT;
garg->gid_arr = tmp;
}
if (len > (int)(sizeof(etmp) - 1))
return 0;
memcpy(etmp, elem, len);
etmp[len] = 0;
gid = tls1_group_name2id(garg->ctx, etmp);
if (gid == 0) {
ERR_raise_data(ERR_LIB_SSL, ERR_R_PASSED_INVALID_ARGUMENT,
"group '%s' cannot be set", etmp);
return 0;
}
for (i = 0; i < garg->gidcnt; i++)
if (garg->gid_arr[i] == gid)
return 0;
garg->gid_arr[garg->gidcnt++] = gid;
return 1;
}
/* Set groups based on a colon separated list */
int tls1_set_groups_list(SSL_CTX *ctx, uint16_t **pext, size_t *pextlen,
const char *str)
{
gid_cb_st gcb;
uint16_t *tmparr;
int ret = 0;
gcb.gidcnt = 0;
gcb.gidmax = GROUPLIST_INCREMENT;
gcb.gid_arr = OPENSSL_malloc(gcb.gidmax * sizeof(*gcb.gid_arr));
if (gcb.gid_arr == NULL)
return 0;
gcb.ctx = ctx;
if (!CONF_parse_list(str, ':', 1, gid_cb, &gcb))
goto end;
if (pext == NULL) {
ret = 1;
goto end;
}
/*
* gid_cb ensurse there are no duplicates so we can just go ahead and set
* the result
*/
tmparr = OPENSSL_memdup(gcb.gid_arr, gcb.gidcnt * sizeof(*tmparr));
if (tmparr == NULL)
goto end;
OPENSSL_free(*pext);
*pext = tmparr;
*pextlen = gcb.gidcnt;
ret = 1;
end:
OPENSSL_free(gcb.gid_arr);
return ret;
}
/* Check a group id matches preferences */
int tls1_check_group_id(SSL *s, uint16_t group_id, int check_own_groups)
{
const uint16_t *groups;
size_t groups_len;
if (group_id == 0)
return 0;
/* Check for Suite B compliance */
if (tls1_suiteb(s) && s->s3.tmp.new_cipher != NULL) {
unsigned long cid = s->s3.tmp.new_cipher->id;
if (cid == TLS1_CK_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256) {
if (group_id != TLSEXT_curve_P_256)
return 0;
} else if (cid == TLS1_CK_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384) {
if (group_id != TLSEXT_curve_P_384)
return 0;
} else {
/* Should never happen */
return 0;
}
}
if (check_own_groups) {
/* Check group is one of our preferences */
tls1_get_supported_groups(s, &groups, &groups_len);
if (!tls1_in_list(group_id, groups, groups_len))
return 0;
}
if (!tls_group_allowed(s, group_id, SSL_SECOP_CURVE_CHECK))
return 0;
/* For clients, nothing more to check */
if (!s->server)
return 1;
/* Check group is one of peers preferences */
tls1_get_peer_groups(s, &groups, &groups_len);
/*
* RFC 4492 does not require the supported elliptic curves extension
* so if it is not sent we can just choose any curve.
* It is invalid to send an empty list in the supported groups
* extension, so groups_len == 0 always means no extension.
*/
if (groups_len == 0)
return 1;
return tls1_in_list(group_id, groups, groups_len);
}
void tls1_get_formatlist(SSL *s, const unsigned char **pformats,
size_t *num_formats)
{
/*
* If we have a custom point format list use it otherwise use default
*/
if (s->ext.ecpointformats) {
*pformats = s->ext.ecpointformats;
*num_formats = s->ext.ecpointformats_len;
} else {
*pformats = ecformats_default;
/* For Suite B we don't support char2 fields */
if (tls1_suiteb(s))
*num_formats = sizeof(ecformats_default) - 1;
else
*num_formats = sizeof(ecformats_default);
}
}
/* Check a key is compatible with compression extension */
static int tls1_check_pkey_comp(SSL *s, EVP_PKEY *pkey)
{
unsigned char comp_id;
size_t i;
int point_conv;
/* If not an EC key nothing to check */
if (!EVP_PKEY_is_a(pkey, "EC"))
return 1;
/* Get required compression id */
point_conv = EVP_PKEY_get_ec_point_conv_form(pkey);
if (point_conv == 0)
return 0;
if (point_conv == POINT_CONVERSION_UNCOMPRESSED) {
comp_id = TLSEXT_ECPOINTFORMAT_uncompressed;
} else if (SSL_IS_TLS13(s)) {
/*
* ec_point_formats extension is not used in TLSv1.3 so we ignore
* this check.
*/
return 1;
} else {
int field_type = EVP_PKEY_get_field_type(pkey);
if (field_type == NID_X9_62_prime_field)
comp_id = TLSEXT_ECPOINTFORMAT_ansiX962_compressed_prime;
else if (field_type == NID_X9_62_characteristic_two_field)
comp_id = TLSEXT_ECPOINTFORMAT_ansiX962_compressed_char2;
else
return 0;
}
/*
* If point formats extension present check it, otherwise everything is
* supported (see RFC4492).
*/
if (s->ext.peer_ecpointformats == NULL)
return 1;
for (i = 0; i < s->ext.peer_ecpointformats_len; i++) {
if (s->ext.peer_ecpointformats[i] == comp_id)
return 1;
}
return 0;
}
/* Return group id of a key */
static uint16_t tls1_get_group_id(EVP_PKEY *pkey)
{
int curve_nid = ssl_get_EC_curve_nid(pkey);
if (curve_nid == NID_undef)
return 0;
return tls1_nid2group_id(curve_nid);
}
/*
* Check cert parameters compatible with extensions: currently just checks EC
* certificates have compatible curves and compression.
*/
static int tls1_check_cert_param(SSL *s, X509 *x, int check_ee_md)
{
uint16_t group_id;
EVP_PKEY *pkey;
pkey = X509_get0_pubkey(x);
if (pkey == NULL)
return 0;
/* If not EC nothing to do */
if (!EVP_PKEY_is_a(pkey, "EC"))
return 1;
/* Check compression */
if (!tls1_check_pkey_comp(s, pkey))
return 0;
group_id = tls1_get_group_id(pkey);
/*
* For a server we allow the certificate to not be in our list of supported
* groups.
*/
if (!tls1_check_group_id(s, group_id, !s->server))
return 0;
/*
* Special case for suite B. We *MUST* sign using SHA256+P-256 or
* SHA384+P-384.
*/
if (check_ee_md && tls1_suiteb(s)) {
int check_md;
size_t i;
/* Check to see we have necessary signing algorithm */
if (group_id == TLSEXT_curve_P_256)
check_md = NID_ecdsa_with_SHA256;
else if (group_id == TLSEXT_curve_P_384)
check_md = NID_ecdsa_with_SHA384;
else
return 0; /* Should never happen */
for (i = 0; i < s->shared_sigalgslen; i++) {
if (check_md == s->shared_sigalgs[i]->sigandhash)
return 1;;
}
return 0;
}
return 1;
}
/*
* tls1_check_ec_tmp_key - Check EC temporary key compatibility
* @s: SSL connection
* @cid: Cipher ID we're considering using
*
* Checks that the kECDHE cipher suite we're considering using
* is compatible with the client extensions.
*
* Returns 0 when the cipher can't be used or 1 when it can.
*/
int tls1_check_ec_tmp_key(SSL *s, unsigned long cid)
{
/* If not Suite B just need a shared group */
if (!tls1_suiteb(s))
return tls1_shared_group(s, 0) != 0;
/*
* If Suite B, AES128 MUST use P-256 and AES256 MUST use P-384, no other
* curves permitted.
*/
if (cid == TLS1_CK_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256)
return tls1_check_group_id(s, TLSEXT_curve_P_256, 1);
if (cid == TLS1_CK_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384)
return tls1_check_group_id(s, TLSEXT_curve_P_384, 1);
return 0;
}
/* Default sigalg schemes */
static const uint16_t tls12_sigalgs[] = {
TLSEXT_SIGALG_ecdsa_secp256r1_sha256,
TLSEXT_SIGALG_ecdsa_secp384r1_sha384,
TLSEXT_SIGALG_ecdsa_secp521r1_sha512,
TLSEXT_SIGALG_ed25519,
TLSEXT_SIGALG_ed448,
TLSEXT_SIGALG_rsa_pss_pss_sha256,
TLSEXT_SIGALG_rsa_pss_pss_sha384,
TLSEXT_SIGALG_rsa_pss_pss_sha512,
TLSEXT_SIGALG_rsa_pss_rsae_sha256,
TLSEXT_SIGALG_rsa_pss_rsae_sha384,
TLSEXT_SIGALG_rsa_pss_rsae_sha512,
TLSEXT_SIGALG_rsa_pkcs1_sha256,
TLSEXT_SIGALG_rsa_pkcs1_sha384,
TLSEXT_SIGALG_rsa_pkcs1_sha512,
TLSEXT_SIGALG_ecdsa_sha224,
TLSEXT_SIGALG_ecdsa_sha1,
TLSEXT_SIGALG_rsa_pkcs1_sha224,
TLSEXT_SIGALG_rsa_pkcs1_sha1,
TLSEXT_SIGALG_dsa_sha224,
TLSEXT_SIGALG_dsa_sha1,
TLSEXT_SIGALG_dsa_sha256,
TLSEXT_SIGALG_dsa_sha384,
TLSEXT_SIGALG_dsa_sha512,
#ifndef OPENSSL_NO_GOST
TLSEXT_SIGALG_gostr34102012_256_intrinsic,
TLSEXT_SIGALG_gostr34102012_512_intrinsic,
TLSEXT_SIGALG_gostr34102012_256_gostr34112012_256,
TLSEXT_SIGALG_gostr34102012_512_gostr34112012_512,
TLSEXT_SIGALG_gostr34102001_gostr3411,
#endif
};
static const uint16_t suiteb_sigalgs[] = {
TLSEXT_SIGALG_ecdsa_secp256r1_sha256,
TLSEXT_SIGALG_ecdsa_secp384r1_sha384
};
static const SIGALG_LOOKUP sigalg_lookup_tbl[] = {
{"ecdsa_secp256r1_sha256", TLSEXT_SIGALG_ecdsa_secp256r1_sha256,
NID_sha256, SSL_MD_SHA256_IDX, EVP_PKEY_EC, SSL_PKEY_ECC,
NID_ecdsa_with_SHA256, NID_X9_62_prime256v1, 1},
{"ecdsa_secp384r1_sha384", TLSEXT_SIGALG_ecdsa_secp384r1_sha384,
NID_sha384, SSL_MD_SHA384_IDX, EVP_PKEY_EC, SSL_PKEY_ECC,
NID_ecdsa_with_SHA384, NID_secp384r1, 1},
{"ecdsa_secp521r1_sha512", TLSEXT_SIGALG_ecdsa_secp521r1_sha512,
NID_sha512, SSL_MD_SHA512_IDX, EVP_PKEY_EC, SSL_PKEY_ECC,
NID_ecdsa_with_SHA512, NID_secp521r1, 1},
{"ed25519", TLSEXT_SIGALG_ed25519,
NID_undef, -1, EVP_PKEY_ED25519, SSL_PKEY_ED25519,
NID_undef, NID_undef, 1},
{"ed448", TLSEXT_SIGALG_ed448,
NID_undef, -1, EVP_PKEY_ED448, SSL_PKEY_ED448,
NID_undef, NID_undef, 1},
{NULL, TLSEXT_SIGALG_ecdsa_sha224,
NID_sha224, SSL_MD_SHA224_IDX, EVP_PKEY_EC, SSL_PKEY_ECC,
NID_ecdsa_with_SHA224, NID_undef, 1},
{NULL, TLSEXT_SIGALG_ecdsa_sha1,
NID_sha1, SSL_MD_SHA1_IDX, EVP_PKEY_EC, SSL_PKEY_ECC,
NID_ecdsa_with_SHA1, NID_undef, 1},
{"rsa_pss_rsae_sha256", TLSEXT_SIGALG_rsa_pss_rsae_sha256,
NID_sha256, SSL_MD_SHA256_IDX, EVP_PKEY_RSA_PSS, SSL_PKEY_RSA,
NID_undef, NID_undef, 1},
{"rsa_pss_rsae_sha384", TLSEXT_SIGALG_rsa_pss_rsae_sha384,
NID_sha384, SSL_MD_SHA384_IDX, EVP_PKEY_RSA_PSS, SSL_PKEY_RSA,
NID_undef, NID_undef, 1},
{"rsa_pss_rsae_sha512", TLSEXT_SIGALG_rsa_pss_rsae_sha512,
NID_sha512, SSL_MD_SHA512_IDX, EVP_PKEY_RSA_PSS, SSL_PKEY_RSA,
NID_undef, NID_undef, 1},
{"rsa_pss_pss_sha256", TLSEXT_SIGALG_rsa_pss_pss_sha256,
NID_sha256, SSL_MD_SHA256_IDX, EVP_PKEY_RSA_PSS, SSL_PKEY_RSA_PSS_SIGN,
NID_undef, NID_undef, 1},
{"rsa_pss_pss_sha384", TLSEXT_SIGALG_rsa_pss_pss_sha384,
NID_sha384, SSL_MD_SHA384_IDX, EVP_PKEY_RSA_PSS, SSL_PKEY_RSA_PSS_SIGN,
NID_undef, NID_undef, 1},
{"rsa_pss_pss_sha512", TLSEXT_SIGALG_rsa_pss_pss_sha512,
NID_sha512, SSL_MD_SHA512_IDX, EVP_PKEY_RSA_PSS, SSL_PKEY_RSA_PSS_SIGN,
NID_undef, NID_undef, 1},
{"rsa_pkcs1_sha256", TLSEXT_SIGALG_rsa_pkcs1_sha256,
NID_sha256, SSL_MD_SHA256_IDX, EVP_PKEY_RSA, SSL_PKEY_RSA,
NID_sha256WithRSAEncryption, NID_undef, 1},
{"rsa_pkcs1_sha384", TLSEXT_SIGALG_rsa_pkcs1_sha384,
NID_sha384, SSL_MD_SHA384_IDX, EVP_PKEY_RSA, SSL_PKEY_RSA,
NID_sha384WithRSAEncryption, NID_undef, 1},
{"rsa_pkcs1_sha512", TLSEXT_SIGALG_rsa_pkcs1_sha512,
NID_sha512, SSL_MD_SHA512_IDX, EVP_PKEY_RSA, SSL_PKEY_RSA,
NID_sha512WithRSAEncryption, NID_undef, 1},
{"rsa_pkcs1_sha224", TLSEXT_SIGALG_rsa_pkcs1_sha224,
NID_sha224, SSL_MD_SHA224_IDX, EVP_PKEY_RSA, SSL_PKEY_RSA,
NID_sha224WithRSAEncryption, NID_undef, 1},
{"rsa_pkcs1_sha1", TLSEXT_SIGALG_rsa_pkcs1_sha1,
NID_sha1, SSL_MD_SHA1_IDX, EVP_PKEY_RSA, SSL_PKEY_RSA,
NID_sha1WithRSAEncryption, NID_undef, 1},
{NULL, TLSEXT_SIGALG_dsa_sha256,
NID_sha256, SSL_MD_SHA256_IDX, EVP_PKEY_DSA, SSL_PKEY_DSA_SIGN,
NID_dsa_with_SHA256, NID_undef, 1},
{NULL, TLSEXT_SIGALG_dsa_sha384,
NID_sha384, SSL_MD_SHA384_IDX, EVP_PKEY_DSA, SSL_PKEY_DSA_SIGN,
NID_undef, NID_undef, 1},
{NULL, TLSEXT_SIGALG_dsa_sha512,
NID_sha512, SSL_MD_SHA512_IDX, EVP_PKEY_DSA, SSL_PKEY_DSA_SIGN,
NID_undef, NID_undef, 1},
{NULL, TLSEXT_SIGALG_dsa_sha224,
NID_sha224, SSL_MD_SHA224_IDX, EVP_PKEY_DSA, SSL_PKEY_DSA_SIGN,
NID_undef, NID_undef, 1},
{NULL, TLSEXT_SIGALG_dsa_sha1,
NID_sha1, SSL_MD_SHA1_IDX, EVP_PKEY_DSA, SSL_PKEY_DSA_SIGN,
NID_dsaWithSHA1, NID_undef, 1},
#ifndef OPENSSL_NO_GOST
{NULL, TLSEXT_SIGALG_gostr34102012_256_intrinsic,
NID_id_GostR3411_2012_256, SSL_MD_GOST12_256_IDX,
NID_id_GostR3410_2012_256, SSL_PKEY_GOST12_256,
NID_undef, NID_undef, 1},
{NULL, TLSEXT_SIGALG_gostr34102012_512_intrinsic,
NID_id_GostR3411_2012_512, SSL_MD_GOST12_512_IDX,
NID_id_GostR3410_2012_512, SSL_PKEY_GOST12_512,
NID_undef, NID_undef, 1},
{NULL, TLSEXT_SIGALG_gostr34102012_256_gostr34112012_256,
NID_id_GostR3411_2012_256, SSL_MD_GOST12_256_IDX,
NID_id_GostR3410_2012_256, SSL_PKEY_GOST12_256,
NID_undef, NID_undef, 1},
{NULL, TLSEXT_SIGALG_gostr34102012_512_gostr34112012_512,
NID_id_GostR3411_2012_512, SSL_MD_GOST12_512_IDX,
NID_id_GostR3410_2012_512, SSL_PKEY_GOST12_512,
NID_undef, NID_undef, 1},
{NULL, TLSEXT_SIGALG_gostr34102001_gostr3411,
NID_id_GostR3411_94, SSL_MD_GOST94_IDX,
NID_id_GostR3410_2001, SSL_PKEY_GOST01,
NID_undef, NID_undef, 1}
#endif
};
/* Legacy sigalgs for TLS < 1.2 RSA TLS signatures */
static const SIGALG_LOOKUP legacy_rsa_sigalg = {
"rsa_pkcs1_md5_sha1", 0,
NID_md5_sha1, SSL_MD_MD5_SHA1_IDX,
EVP_PKEY_RSA, SSL_PKEY_RSA,
NID_undef, NID_undef, 1
};
/*
* Default signature algorithm values used if signature algorithms not present.
* From RFC5246. Note: order must match certificate index order.
*/
static const uint16_t tls_default_sigalg[] = {
TLSEXT_SIGALG_rsa_pkcs1_sha1, /* SSL_PKEY_RSA */
0, /* SSL_PKEY_RSA_PSS_SIGN */
TLSEXT_SIGALG_dsa_sha1, /* SSL_PKEY_DSA_SIGN */
TLSEXT_SIGALG_ecdsa_sha1, /* SSL_PKEY_ECC */
TLSEXT_SIGALG_gostr34102001_gostr3411, /* SSL_PKEY_GOST01 */
TLSEXT_SIGALG_gostr34102012_256_intrinsic, /* SSL_PKEY_GOST12_256 */
TLSEXT_SIGALG_gostr34102012_512_intrinsic, /* SSL_PKEY_GOST12_512 */
0, /* SSL_PKEY_ED25519 */
0, /* SSL_PKEY_ED448 */
};
int ssl_setup_sig_algs(SSL_CTX *ctx)
{
size_t i;
const SIGALG_LOOKUP *lu;
SIGALG_LOOKUP *cache
= OPENSSL_malloc(sizeof(*lu) * OSSL_NELEM(sigalg_lookup_tbl));
EVP_PKEY *tmpkey = EVP_PKEY_new();
int ret = 0;
if (cache == NULL || tmpkey == NULL)
goto err;
ERR_set_mark();
for (i = 0, lu = sigalg_lookup_tbl;
i < OSSL_NELEM(sigalg_lookup_tbl); lu++, i++) {
EVP_PKEY_CTX *pctx;
cache[i] = *lu;
/*
* Check hash is available.
* This test is not perfect. A provider could have support
* for a signature scheme, but not a particular hash. However the hash
* could be available from some other loaded provider. In that case it
* could be that the signature is available, and the hash is available
* independently - but not as a combination. We ignore this for now.
*/
if (lu->hash != NID_undef
&& ctx->ssl_digest_methods[lu->hash_idx] == NULL) {
cache[i].enabled = 0;
continue;
}
if (!EVP_PKEY_set_type(tmpkey, lu->sig)) {
cache[i].enabled = 0;
continue;
}
pctx = EVP_PKEY_CTX_new_from_pkey(ctx->libctx, tmpkey, ctx->propq);
/* If unable to create pctx we assume the sig algorithm is unavailable */
if (pctx == NULL)
cache[i].enabled = 0;
EVP_PKEY_CTX_free(pctx);
}
ERR_pop_to_mark();
ctx->sigalg_lookup_cache = cache;
cache = NULL;
ret = 1;
err:
OPENSSL_free(cache);
EVP_PKEY_free(tmpkey);
return ret;
}
/* Lookup TLS signature algorithm */
static const SIGALG_LOOKUP *tls1_lookup_sigalg(const SSL *s, uint16_t sigalg)
{
size_t i;
const SIGALG_LOOKUP *lu;
for (i = 0, lu = s->ctx->sigalg_lookup_cache;
/* cache should have the same number of elements as sigalg_lookup_tbl */
i < OSSL_NELEM(sigalg_lookup_tbl);
lu++, i++) {
if (lu->sigalg == sigalg) {
if (!lu->enabled)
return NULL;
return lu;
}
}
return NULL;
}
/* Lookup hash: return 0 if invalid or not enabled */
int tls1_lookup_md(SSL_CTX *ctx, const SIGALG_LOOKUP *lu, const EVP_MD **pmd)
{
const EVP_MD *md;
if (lu == NULL)
return 0;
/* lu->hash == NID_undef means no associated digest */
if (lu->hash == NID_undef) {
md = NULL;
} else {
md = ssl_md(ctx, lu->hash_idx);
if (md == NULL)
return 0;
}
if (pmd)
*pmd = md;
return 1;
}
/*
* Check if key is large enough to generate RSA-PSS signature.
*
* The key must greater than or equal to 2 * hash length + 2.
* SHA512 has a hash length of 64 bytes, which is incompatible
* with a 128 byte (1024 bit) key.
*/
#define RSA_PSS_MINIMUM_KEY_SIZE(md) (2 * EVP_MD_get_size(md) + 2)
static int rsa_pss_check_min_key_size(SSL_CTX *ctx, const EVP_PKEY *pkey,
const SIGALG_LOOKUP *lu)
{
const EVP_MD *md;
if (pkey == NULL)
return 0;
if (!tls1_lookup_md(ctx, lu, &md) || md == NULL)
return 0;
if (EVP_PKEY_get_size(pkey) < RSA_PSS_MINIMUM_KEY_SIZE(md))
return 0;
return 1;
}
/*
* Returns a signature algorithm when the peer did not send a list of supported
* signature algorithms. The signature algorithm is fixed for the certificate
* type. |idx| is a certificate type index (SSL_PKEY_*). When |idx| is -1 the
* certificate type from |s| will be used.
* Returns the signature algorithm to use, or NULL on error.
*/
static const SIGALG_LOOKUP *tls1_get_legacy_sigalg(const SSL *s, int idx)
{
if (idx == -1) {
if (s->server) {
size_t i;
/* Work out index corresponding to ciphersuite */
for (i = 0; i < SSL_PKEY_NUM; i++) {
const SSL_CERT_LOOKUP *clu = ssl_cert_lookup_by_idx(i);
if (clu == NULL)
continue;
if (clu->amask & s->s3.tmp.new_cipher->algorithm_auth) {
idx = i;
break;
}
}
/*
* Some GOST ciphersuites allow more than one signature algorithms
* */
if (idx == SSL_PKEY_GOST01 && s->s3.tmp.new_cipher->algorithm_auth != SSL_aGOST01) {
int real_idx;
for (real_idx = SSL_PKEY_GOST12_512; real_idx >= SSL_PKEY_GOST01;
real_idx--) {
if (s->cert->pkeys[real_idx].privatekey != NULL) {
idx = real_idx;
break;
}
}
}
/*
* As both SSL_PKEY_GOST12_512 and SSL_PKEY_GOST12_256 indices can be used
* with new (aGOST12-only) ciphersuites, we should find out which one is available really.
*/
else if (idx == SSL_PKEY_GOST12_256) {
int real_idx;
for (real_idx = SSL_PKEY_GOST12_512; real_idx >= SSL_PKEY_GOST12_256;
real_idx--) {
if (s->cert->pkeys[real_idx].privatekey != NULL) {
idx = real_idx;
break;
}
}
}
} else {
idx = s->cert->key - s->cert->pkeys;
}
}
if (idx < 0 || idx >= (int)OSSL_NELEM(tls_default_sigalg))
return NULL;
if (SSL_USE_SIGALGS(s) || idx != SSL_PKEY_RSA) {
const SIGALG_LOOKUP *lu = tls1_lookup_sigalg(s, tls_default_sigalg[idx]);
if (lu == NULL)
return NULL;
if (!tls1_lookup_md(s->ctx, lu, NULL))
return NULL;
if (!tls12_sigalg_allowed(s, SSL_SECOP_SIGALG_SUPPORTED, lu))
return NULL;
return lu;
}
if (!tls12_sigalg_allowed(s, SSL_SECOP_SIGALG_SUPPORTED, &legacy_rsa_sigalg))
return NULL;
return &legacy_rsa_sigalg;
}
/* Set peer sigalg based key type */
int tls1_set_peer_legacy_sigalg(SSL *s, const EVP_PKEY *pkey)
{
size_t idx;
const SIGALG_LOOKUP *lu;
if (ssl_cert_lookup_by_pkey(pkey, &idx) == NULL)
return 0;
lu = tls1_get_legacy_sigalg(s, idx);
if (lu == NULL)
return 0;
s->s3.tmp.peer_sigalg = lu;
return 1;
}
size_t tls12_get_psigalgs(SSL *s, int sent, const uint16_t **psigs)
{
/*
* If Suite B mode use Suite B sigalgs only, ignore any other
* preferences.
*/
switch (tls1_suiteb(s)) {
case SSL_CERT_FLAG_SUITEB_128_LOS:
*psigs = suiteb_sigalgs;
return OSSL_NELEM(suiteb_sigalgs);
case SSL_CERT_FLAG_SUITEB_128_LOS_ONLY:
*psigs = suiteb_sigalgs;
return 1;
case SSL_CERT_FLAG_SUITEB_192_LOS:
*psigs = suiteb_sigalgs + 1;
return 1;
}
/*
* We use client_sigalgs (if not NULL) if we're a server
* and sending a certificate request or if we're a client and
* determining which shared algorithm to use.
*/
if ((s->server == sent) && s->cert->client_sigalgs != NULL) {
*psigs = s->cert->client_sigalgs;
return s->cert->client_sigalgslen;
} else if (s->cert->conf_sigalgs) {
*psigs = s->cert->conf_sigalgs;
return s->cert->conf_sigalgslen;
} else {
*psigs = tls12_sigalgs;
return OSSL_NELEM(tls12_sigalgs);
}
}
/*
* Called by servers only. Checks that we have a sig alg that supports the
* specified EC curve.
*/
int tls_check_sigalg_curve(const SSL *s, int curve)
{
const uint16_t *sigs;
size_t siglen, i;
if (s->cert->conf_sigalgs) {
sigs = s->cert->conf_sigalgs;
siglen = s->cert->conf_sigalgslen;
} else {
sigs = tls12_sigalgs;
siglen = OSSL_NELEM(tls12_sigalgs);
}
for (i = 0; i < siglen; i++) {
const SIGALG_LOOKUP *lu = tls1_lookup_sigalg(s, sigs[i]);
if (lu == NULL)
continue;
if (lu->sig == EVP_PKEY_EC
&& lu->curve != NID_undef
&& curve == lu->curve)
return 1;
}
return 0;
}
/*
* Return the number of security bits for the signature algorithm, or 0 on
* error.
*/
static int sigalg_security_bits(SSL_CTX *ctx, const SIGALG_LOOKUP *lu)
{
const EVP_MD *md = NULL;
int secbits = 0;
if (!tls1_lookup_md(ctx, lu, &md))
return 0;
if (md != NULL)
{
int md_type = EVP_MD_get_type(md);
/* Security bits: half digest bits */
secbits = EVP_MD_get_size(md) * 4;
/*
* SHA1 and MD5 are known to be broken. Reduce security bits so that
* they're no longer accepted at security level 1. The real values don't
* really matter as long as they're lower than 80, which is our
* security level 1.
* https://eprint.iacr.org/2020/014 puts a chosen-prefix attack for
* SHA1 at 2^63.4 and MD5+SHA1 at 2^67.2
* https://documents.epfl.ch/users/l/le/lenstra/public/papers/lat.pdf
* puts a chosen-prefix attack for MD5 at 2^39.
*/
if (md_type == NID_sha1)
secbits = 64;
else if (md_type == NID_md5_sha1)
secbits = 67;
else if (md_type == NID_md5)
secbits = 39;
} else {
/* Values from https://tools.ietf.org/html/rfc8032#section-8.5 */
if (lu->sigalg == TLSEXT_SIGALG_ed25519)
secbits = 128;
else if (lu->sigalg == TLSEXT_SIGALG_ed448)
secbits = 224;
}
return secbits;
}
/*
* Check signature algorithm is consistent with sent supported signature
* algorithms and if so set relevant digest and signature scheme in
* s.
*/
int tls12_check_peer_sigalg(SSL *s, uint16_t sig, EVP_PKEY *pkey)
{
const uint16_t *sent_sigs;
const EVP_MD *md = NULL;
char sigalgstr[2];
size_t sent_sigslen, i, cidx;
int pkeyid = -1;
const SIGALG_LOOKUP *lu;
int secbits = 0;
pkeyid = EVP_PKEY_get_id(pkey);
/* Should never happen */
if (pkeyid == -1)
return -1;
if (SSL_IS_TLS13(s)) {
/* Disallow DSA for TLS 1.3 */
if (pkeyid == EVP_PKEY_DSA) {
SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_WRONG_SIGNATURE_TYPE);
return 0;
}
/* Only allow PSS for TLS 1.3 */
if (pkeyid == EVP_PKEY_RSA)
pkeyid = EVP_PKEY_RSA_PSS;
}
lu = tls1_lookup_sigalg(s, sig);
/*
* Check sigalgs is known. Disallow SHA1/SHA224 with TLS 1.3. Check key type
* is consistent with signature: RSA keys can be used for RSA-PSS
*/
if (lu == NULL
|| (SSL_IS_TLS13(s) && (lu->hash == NID_sha1 || lu->hash == NID_sha224))
|| (pkeyid != lu->sig
&& (lu->sig != EVP_PKEY_RSA_PSS || pkeyid != EVP_PKEY_RSA))) {
SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_WRONG_SIGNATURE_TYPE);
return 0;
}
/* Check the sigalg is consistent with the key OID */
if (!ssl_cert_lookup_by_nid(EVP_PKEY_get_id(pkey), &cidx)
|| lu->sig_idx != (int)cidx) {
SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_WRONG_SIGNATURE_TYPE);
return 0;
}
if (pkeyid == EVP_PKEY_EC) {
/* Check point compression is permitted */
if (!tls1_check_pkey_comp(s, pkey)) {
SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
SSL_R_ILLEGAL_POINT_COMPRESSION);
return 0;
}
/* For TLS 1.3 or Suite B check curve matches signature algorithm */
if (SSL_IS_TLS13(s) || tls1_suiteb(s)) {
int curve = ssl_get_EC_curve_nid(pkey);
if (lu->curve != NID_undef && curve != lu->curve) {
SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_WRONG_CURVE);
return 0;
}
}
if (!SSL_IS_TLS13(s)) {
/* Check curve matches extensions */
if (!tls1_check_group_id(s, tls1_get_group_id(pkey), 1)) {
SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_WRONG_CURVE);
return 0;
}
if (tls1_suiteb(s)) {
/* Check sigalg matches a permissible Suite B value */
if (sig != TLSEXT_SIGALG_ecdsa_secp256r1_sha256
&& sig != TLSEXT_SIGALG_ecdsa_secp384r1_sha384) {
SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
SSL_R_WRONG_SIGNATURE_TYPE);
return 0;
}
}
}
} else if (tls1_suiteb(s)) {
SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_WRONG_SIGNATURE_TYPE);
return 0;
}
/* Check signature matches a type we sent */
sent_sigslen = tls12_get_psigalgs(s, 1, &sent_sigs);
for (i = 0; i < sent_sigslen; i++, sent_sigs++) {
if (sig == *sent_sigs)
break;
}
/* Allow fallback to SHA1 if not strict mode */
if (i == sent_sigslen && (lu->hash != NID_sha1
|| s->cert->cert_flags & SSL_CERT_FLAGS_CHECK_TLS_STRICT)) {
SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_WRONG_SIGNATURE_TYPE);
return 0;
}
if (!tls1_lookup_md(s->ctx, lu, &md)) {
SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_UNKNOWN_DIGEST);
return 0;
}
/*
* Make sure security callback allows algorithm. For historical
* reasons we have to pass the sigalg as a two byte char array.
*/
sigalgstr[0] = (sig >> 8) & 0xff;
sigalgstr[1] = sig & 0xff;
secbits = sigalg_security_bits(s->ctx, lu);
if (secbits == 0 ||
!ssl_security(s, SSL_SECOP_SIGALG_CHECK, secbits,
md != NULL ? EVP_MD_get_type(md) : NID_undef,
(void *)sigalgstr)) {
SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_WRONG_SIGNATURE_TYPE);
return 0;
}
/* Store the sigalg the peer uses */
s->s3.tmp.peer_sigalg = lu;
return 1;
}
int SSL_get_peer_signature_type_nid(const SSL *s, int *pnid)
{
if (s->s3.tmp.peer_sigalg == NULL)
return 0;
*pnid = s->s3.tmp.peer_sigalg->sig;
return 1;
}
int SSL_get_signature_type_nid(const SSL *s, int *pnid)
{
if (s->s3.tmp.sigalg == NULL)
return 0;
*pnid = s->s3.tmp.sigalg->sig;
return 1;
}
/*
* Set a mask of disabled algorithms: an algorithm is disabled if it isn't
* supported, doesn't appear in supported signature algorithms, isn't supported
* by the enabled protocol versions or by the security level.
*
* This function should only be used for checking which ciphers are supported
* by the client.
*
* Call ssl_cipher_disabled() to check that it's enabled or not.
*/
int ssl_set_client_disabled(SSL *s)
{
s->s3.tmp.mask_a = 0;
s->s3.tmp.mask_k = 0;
ssl_set_sig_mask(&s->s3.tmp.mask_a, s, SSL_SECOP_SIGALG_MASK);
if (ssl_get_min_max_version(s, &s->s3.tmp.min_ver,
&s->s3.tmp.max_ver, NULL) != 0)
return 0;
#ifndef OPENSSL_NO_PSK
/* with PSK there must be client callback set */
if (!s->psk_client_callback) {
s->s3.tmp.mask_a |= SSL_aPSK;
s->s3.tmp.mask_k |= SSL_PSK;
}
#endif /* OPENSSL_NO_PSK */
#ifndef OPENSSL_NO_SRP
if (!(s->srp_ctx.srp_Mask & SSL_kSRP)) {
s->s3.tmp.mask_a |= SSL_aSRP;
s->s3.tmp.mask_k |= SSL_kSRP;
}
#endif
return 1;
}
/*
* ssl_cipher_disabled - check that a cipher is disabled or not
* @s: SSL connection that you want to use the cipher on
* @c: cipher to check
* @op: Security check that you want to do
* @ecdhe: If set to 1 then TLSv1 ECDHE ciphers are also allowed in SSLv3
*
* Returns 1 when it's disabled, 0 when enabled.
*/
int ssl_cipher_disabled(const SSL *s, const SSL_CIPHER *c, int op, int ecdhe)
{
if (c->algorithm_mkey & s->s3.tmp.mask_k
|| c->algorithm_auth & s->s3.tmp.mask_a)
return 1;
if (s->s3.tmp.max_ver == 0)
return 1;
if (!SSL_IS_DTLS(s)) {
int min_tls = c->min_tls;
/*
* For historical reasons we will allow ECHDE to be selected by a server
* in SSLv3 if we are a client
*/
if (min_tls == TLS1_VERSION && ecdhe
&& (c->algorithm_mkey & (SSL_kECDHE | SSL_kECDHEPSK)) != 0)
min_tls = SSL3_VERSION;
if ((min_tls > s->s3.tmp.max_ver) || (c->max_tls < s->s3.tmp.min_ver))
return 1;
}
if (SSL_IS_DTLS(s) && (DTLS_VERSION_GT(c->min_dtls, s->s3.tmp.max_ver)
|| DTLS_VERSION_LT(c->max_dtls, s->s3.tmp.min_ver)))
return 1;
return !ssl_security(s, op, c->strength_bits, 0, (void *)c);
}
int tls_use_ticket(SSL *s)
{
if ((s->options & SSL_OP_NO_TICKET))
return 0;
return ssl_security(s, SSL_SECOP_TICKET, 0, 0, NULL);
}
int tls1_set_server_sigalgs(SSL *s)
{
size_t i;
/* Clear any shared signature algorithms */
OPENSSL_free(s->shared_sigalgs);
s->shared_sigalgs = NULL;
s->shared_sigalgslen = 0;
/* Clear certificate validity flags */
for (i = 0; i < SSL_PKEY_NUM; i++)
s->s3.tmp.valid_flags[i] = 0;
/*
* If peer sent no signature algorithms check to see if we support
* the default algorithm for each certificate type
*/
if (s->s3.tmp.peer_cert_sigalgs == NULL
&& s->s3.tmp.peer_sigalgs == NULL) {
const uint16_t *sent_sigs;
size_t sent_sigslen = tls12_get_psigalgs(s, 1, &sent_sigs);
for (i = 0; i < SSL_PKEY_NUM; i++) {
const SIGALG_LOOKUP *lu = tls1_get_legacy_sigalg(s, i);
size_t j;
if (lu == NULL)
continue;
/* Check default matches a type we sent */
for (j = 0; j < sent_sigslen; j++) {
if (lu->sigalg == sent_sigs[j]) {
s->s3.tmp.valid_flags[i] = CERT_PKEY_SIGN;
break;
}
}
}
return 1;
}
if (!tls1_process_sigalgs(s)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return 0;
}
if (s->shared_sigalgs != NULL)
return 1;
/* Fatal error if no shared signature algorithms */
SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
SSL_R_NO_SHARED_SIGNATURE_ALGORITHMS);
return 0;
}
/*-
* Gets the ticket information supplied by the client if any.
*
* hello: The parsed ClientHello data
* ret: (output) on return, if a ticket was decrypted, then this is set to
* point to the resulting session.
*/
SSL_TICKET_STATUS tls_get_ticket_from_client(SSL *s, CLIENTHELLO_MSG *hello,
SSL_SESSION **ret)
{
size_t size;
RAW_EXTENSION *ticketext;
*ret = NULL;
s->ext.ticket_expected = 0;
/*
* If tickets disabled or not supported by the protocol version
* (e.g. TLSv1.3) behave as if no ticket present to permit stateful
* resumption.
*/
if (s->version <= SSL3_VERSION || !tls_use_ticket(s))
return SSL_TICKET_NONE;
ticketext = &hello->pre_proc_exts[TLSEXT_IDX_session_ticket];
if (!ticketext->present)
return SSL_TICKET_NONE;
size = PACKET_remaining(&ticketext->data);
return tls_decrypt_ticket(s, PACKET_data(&ticketext->data), size,
hello->session_id, hello->session_id_len, ret);
}
/*-
* tls_decrypt_ticket attempts to decrypt a session ticket.
*
* If s->tls_session_secret_cb is set and we're not doing TLSv1.3 then we are
* expecting a pre-shared key ciphersuite, in which case we have no use for
* session tickets and one will never be decrypted, nor will
* s->ext.ticket_expected be set to 1.
*
* Side effects:
* Sets s->ext.ticket_expected to 1 if the server will have to issue
* a new session ticket to the client because the client indicated support
* (and s->tls_session_secret_cb is NULL) but the client either doesn't have
* a session ticket or we couldn't use the one it gave us, or if
* s->ctx->ext.ticket_key_cb asked to renew the client's ticket.
* Otherwise, s->ext.ticket_expected is set to 0.
*
* etick: points to the body of the session ticket extension.
* eticklen: the length of the session tickets extension.
* sess_id: points at the session ID.
* sesslen: the length of the session ID.
* psess: (output) on return, if a ticket was decrypted, then this is set to
* point to the resulting session.
*/
SSL_TICKET_STATUS tls_decrypt_ticket(SSL *s, const unsigned char *etick,
size_t eticklen, const unsigned char *sess_id,
size_t sesslen, SSL_SESSION **psess)
{
SSL_SESSION *sess = NULL;
unsigned char *sdec;
const unsigned char *p;
int slen, ivlen, renew_ticket = 0, declen;
SSL_TICKET_STATUS ret = SSL_TICKET_FATAL_ERR_OTHER;
size_t mlen;
unsigned char tick_hmac[EVP_MAX_MD_SIZE];
SSL_HMAC *hctx = NULL;
EVP_CIPHER_CTX *ctx = NULL;
SSL_CTX *tctx = s->session_ctx;
if (eticklen == 0) {
/*
* The client will accept a ticket but doesn't currently have
* one (TLSv1.2 and below), or treated as a fatal error in TLSv1.3
*/
ret = SSL_TICKET_EMPTY;
goto end;
}
if (!SSL_IS_TLS13(s) && s->ext.session_secret_cb) {
/*
* Indicate that the ticket couldn't be decrypted rather than
* generating the session from ticket now, trigger
* abbreviated handshake based on external mechanism to
* calculate the master secret later.
*/
ret = SSL_TICKET_NO_DECRYPT;
goto end;
}
/* Need at least keyname + iv */
if (eticklen < TLSEXT_KEYNAME_LENGTH + EVP_MAX_IV_LENGTH) {
ret = SSL_TICKET_NO_DECRYPT;
goto end;
}
/* Initialize session ticket encryption and HMAC contexts */
hctx = ssl_hmac_new(tctx);
if (hctx == NULL) {
ret = SSL_TICKET_FATAL_ERR_MALLOC;
goto end;
}
ctx = EVP_CIPHER_CTX_new();
if (ctx == NULL) {
ret = SSL_TICKET_FATAL_ERR_MALLOC;
goto end;
}
#ifndef OPENSSL_NO_DEPRECATED_3_0
if (tctx->ext.ticket_key_evp_cb != NULL || tctx->ext.ticket_key_cb != NULL)
#else
if (tctx->ext.ticket_key_evp_cb != NULL)
#endif
{
unsigned char *nctick = (unsigned char *)etick;
int rv = 0;
if (tctx->ext.ticket_key_evp_cb != NULL)
rv = tctx->ext.ticket_key_evp_cb(s, nctick,
nctick + TLSEXT_KEYNAME_LENGTH,
ctx,
ssl_hmac_get0_EVP_MAC_CTX(hctx),
0);
#ifndef OPENSSL_NO_DEPRECATED_3_0
else if (tctx->ext.ticket_key_cb != NULL)
/* if 0 is returned, write an empty ticket */
rv = tctx->ext.ticket_key_cb(s, nctick,
nctick + TLSEXT_KEYNAME_LENGTH,
ctx, ssl_hmac_get0_HMAC_CTX(hctx), 0);
#endif
if (rv < 0) {
ret = SSL_TICKET_FATAL_ERR_OTHER;
goto end;
}
if (rv == 0) {
ret = SSL_TICKET_NO_DECRYPT;
goto end;
}
if (rv == 2)
renew_ticket = 1;
} else {
EVP_CIPHER *aes256cbc = NULL;
/* Check key name matches */
if (memcmp(etick, tctx->ext.tick_key_name,
TLSEXT_KEYNAME_LENGTH) != 0) {
ret = SSL_TICKET_NO_DECRYPT;
goto end;
}
aes256cbc = EVP_CIPHER_fetch(s->ctx->libctx, "AES-256-CBC",
s->ctx->propq);
if (aes256cbc == NULL
|| ssl_hmac_init(hctx, tctx->ext.secure->tick_hmac_key,
sizeof(tctx->ext.secure->tick_hmac_key),
"SHA256") <= 0
|| EVP_DecryptInit_ex(ctx, aes256cbc, NULL,
tctx->ext.secure->tick_aes_key,
etick + TLSEXT_KEYNAME_LENGTH) <= 0) {
EVP_CIPHER_free(aes256cbc);
ret = SSL_TICKET_FATAL_ERR_OTHER;
goto end;
}
EVP_CIPHER_free(aes256cbc);
if (SSL_IS_TLS13(s))
renew_ticket = 1;
}
/*
* Attempt to process session ticket, first conduct sanity and integrity
* checks on ticket.
*/
mlen = ssl_hmac_size(hctx);
if (mlen == 0) {
ret = SSL_TICKET_FATAL_ERR_OTHER;
goto end;
}
ivlen = EVP_CIPHER_CTX_get_iv_length(ctx);
if (ivlen < 0) {
ret = SSL_TICKET_FATAL_ERR_OTHER;
goto end;
}
/* Sanity check ticket length: must exceed keyname + IV + HMAC */
if (eticklen <= TLSEXT_KEYNAME_LENGTH + ivlen + mlen) {
ret = SSL_TICKET_NO_DECRYPT;
goto end;
}
eticklen -= mlen;
/* Check HMAC of encrypted ticket */
if (ssl_hmac_update(hctx, etick, eticklen) <= 0
|| ssl_hmac_final(hctx, tick_hmac, NULL, sizeof(tick_hmac)) <= 0) {
ret = SSL_TICKET_FATAL_ERR_OTHER;
goto end;
}
if (CRYPTO_memcmp(tick_hmac, etick + eticklen, mlen)) {
ret = SSL_TICKET_NO_DECRYPT;
goto end;
}
/* Attempt to decrypt session data */
/* Move p after IV to start of encrypted ticket, update length */
p = etick + TLSEXT_KEYNAME_LENGTH + ivlen;
eticklen -= TLSEXT_KEYNAME_LENGTH + ivlen;
sdec = OPENSSL_malloc(eticklen);
if (sdec == NULL || EVP_DecryptUpdate(ctx, sdec, &slen, p,
(int)eticklen) <= 0) {
OPENSSL_free(sdec);
ret = SSL_TICKET_FATAL_ERR_OTHER;
goto end;
}
if (EVP_DecryptFinal(ctx, sdec + slen, &declen) <= 0) {
OPENSSL_free(sdec);
ret = SSL_TICKET_NO_DECRYPT;
goto end;
}
slen += declen;
p = sdec;
sess = d2i_SSL_SESSION(NULL, &p, slen);
slen -= p - sdec;
OPENSSL_free(sdec);
if (sess) {
/* Some additional consistency checks */
if (slen != 0) {
SSL_SESSION_free(sess);
sess = NULL;
ret = SSL_TICKET_NO_DECRYPT;
goto end;
}
/*
* The session ID, if non-empty, is used by some clients to detect
* that the ticket has been accepted. So we copy it to the session
* structure. If it is empty set length to zero as required by
* standard.
*/
if (sesslen) {
memcpy(sess->session_id, sess_id, sesslen);
sess->session_id_length = sesslen;
}
if (renew_ticket)
ret = SSL_TICKET_SUCCESS_RENEW;
else
ret = SSL_TICKET_SUCCESS;
goto end;
}
ERR_clear_error();
/*
* For session parse failure, indicate that we need to send a new ticket.
*/
ret = SSL_TICKET_NO_DECRYPT;
end:
EVP_CIPHER_CTX_free(ctx);
ssl_hmac_free(hctx);
/*
* If set, the decrypt_ticket_cb() is called unless a fatal error was
* detected above. The callback is responsible for checking |ret| before it
* performs any action
*/
if (s->session_ctx->decrypt_ticket_cb != NULL
&& (ret == SSL_TICKET_EMPTY
|| ret == SSL_TICKET_NO_DECRYPT
|| ret == SSL_TICKET_SUCCESS
|| ret == SSL_TICKET_SUCCESS_RENEW)) {
size_t keyname_len = eticklen;
int retcb;
if (keyname_len > TLSEXT_KEYNAME_LENGTH)
keyname_len = TLSEXT_KEYNAME_LENGTH;
retcb = s->session_ctx->decrypt_ticket_cb(s, sess, etick, keyname_len,
ret,
s->session_ctx->ticket_cb_data);
switch (retcb) {
case SSL_TICKET_RETURN_ABORT:
ret = SSL_TICKET_FATAL_ERR_OTHER;
break;
case SSL_TICKET_RETURN_IGNORE:
ret = SSL_TICKET_NONE;
SSL_SESSION_free(sess);
sess = NULL;
break;
case SSL_TICKET_RETURN_IGNORE_RENEW:
if (ret != SSL_TICKET_EMPTY && ret != SSL_TICKET_NO_DECRYPT)
ret = SSL_TICKET_NO_DECRYPT;
/* else the value of |ret| will already do the right thing */
SSL_SESSION_free(sess);
sess = NULL;
break;
case SSL_TICKET_RETURN_USE:
case SSL_TICKET_RETURN_USE_RENEW:
if (ret != SSL_TICKET_SUCCESS
&& ret != SSL_TICKET_SUCCESS_RENEW)
ret = SSL_TICKET_FATAL_ERR_OTHER;
else if (retcb == SSL_TICKET_RETURN_USE)
ret = SSL_TICKET_SUCCESS;
else
ret = SSL_TICKET_SUCCESS_RENEW;
break;
default:
ret = SSL_TICKET_FATAL_ERR_OTHER;
}
}
if (s->ext.session_secret_cb == NULL || SSL_IS_TLS13(s)) {
switch (ret) {
case SSL_TICKET_NO_DECRYPT:
case SSL_TICKET_SUCCESS_RENEW:
case SSL_TICKET_EMPTY:
s->ext.ticket_expected = 1;
}
}
*psess = sess;
return ret;
}
/* Check to see if a signature algorithm is allowed */
static int tls12_sigalg_allowed(const SSL *s, int op, const SIGALG_LOOKUP *lu)
{
unsigned char sigalgstr[2];
int secbits;
if (lu == NULL || !lu->enabled)
return 0;
/* DSA is not allowed in TLS 1.3 */
if (SSL_IS_TLS13(s) && lu->sig == EVP_PKEY_DSA)
return 0;
/*
* At some point we should fully axe DSA/etc. in ClientHello as per TLS 1.3
* spec
*/
if (!s->server && !SSL_IS_DTLS(s) && s->s3.tmp.min_ver >= TLS1_3_VERSION
&& (lu->sig == EVP_PKEY_DSA || lu->hash_idx == SSL_MD_SHA1_IDX
|| lu->hash_idx == SSL_MD_MD5_IDX
|| lu->hash_idx == SSL_MD_SHA224_IDX))
return 0;
/* See if public key algorithm allowed */
if (ssl_cert_is_disabled(s->ctx, lu->sig_idx))
return 0;
if (lu->sig == NID_id_GostR3410_2012_256
|| lu->sig == NID_id_GostR3410_2012_512
|| lu->sig == NID_id_GostR3410_2001) {
/* We never allow GOST sig algs on the server with TLSv1.3 */
if (s->server && SSL_IS_TLS13(s))
return 0;
if (!s->server
&& s->method->version == TLS_ANY_VERSION
&& s->s3.tmp.max_ver >= TLS1_3_VERSION) {
int i, num;
STACK_OF(SSL_CIPHER) *sk;
/*
* We're a client that could negotiate TLSv1.3. We only allow GOST
* sig algs if we could negotiate TLSv1.2 or below and we have GOST
* ciphersuites enabled.
*/
if (s->s3.tmp.min_ver >= TLS1_3_VERSION)
return 0;
sk = SSL_get_ciphers(s);
num = sk != NULL ? sk_SSL_CIPHER_num(sk) : 0;
for (i = 0; i < num; i++) {
const SSL_CIPHER *c;
c = sk_SSL_CIPHER_value(sk, i);
/* Skip disabled ciphers */
if (ssl_cipher_disabled(s, c, SSL_SECOP_CIPHER_SUPPORTED, 0))
continue;
if ((c->algorithm_mkey & (SSL_kGOST | SSL_kGOST18)) != 0)
break;
}
if (i == num)
return 0;
}
}
/* Finally see if security callback allows it */
secbits = sigalg_security_bits(s->ctx, lu);
sigalgstr[0] = (lu->sigalg >> 8) & 0xff;
sigalgstr[1] = lu->sigalg & 0xff;
return ssl_security(s, op, secbits, lu->hash, (void *)sigalgstr);
}
/*
* Get a mask of disabled public key algorithms based on supported signature
* algorithms. For example if no signature algorithm supports RSA then RSA is
* disabled.
*/
void ssl_set_sig_mask(uint32_t *pmask_a, SSL *s, int op)
{
const uint16_t *sigalgs;
size_t i, sigalgslen;
uint32_t disabled_mask = SSL_aRSA | SSL_aDSS | SSL_aECDSA;
/*
* Go through all signature algorithms seeing if we support any
* in disabled_mask.
*/
sigalgslen = tls12_get_psigalgs(s, 1, &sigalgs);
for (i = 0; i < sigalgslen; i++, sigalgs++) {
const SIGALG_LOOKUP *lu = tls1_lookup_sigalg(s, *sigalgs);
const SSL_CERT_LOOKUP *clu;
if (lu == NULL)
continue;
clu = ssl_cert_lookup_by_idx(lu->sig_idx);
if (clu == NULL)
continue;
/* If algorithm is disabled see if we can enable it */
if ((clu->amask & disabled_mask) != 0
&& tls12_sigalg_allowed(s, op, lu))
disabled_mask &= ~clu->amask;
}
*pmask_a |= disabled_mask;
}
int tls12_copy_sigalgs(SSL *s, WPACKET *pkt,
const uint16_t *psig, size_t psiglen)
{
size_t i;
int rv = 0;
for (i = 0; i < psiglen; i++, psig++) {
const SIGALG_LOOKUP *lu = tls1_lookup_sigalg(s, *psig);
if (lu == NULL
|| !tls12_sigalg_allowed(s, SSL_SECOP_SIGALG_SUPPORTED, lu))
continue;
if (!WPACKET_put_bytes_u16(pkt, *psig))
return 0;
/*
* If TLS 1.3 must have at least one valid TLS 1.3 message
* signing algorithm: i.e. neither RSA nor SHA1/SHA224
*/
if (rv == 0 && (!SSL_IS_TLS13(s)
|| (lu->sig != EVP_PKEY_RSA
&& lu->hash != NID_sha1
&& lu->hash != NID_sha224)))
rv = 1;
}
if (rv == 0)
ERR_raise(ERR_LIB_SSL, SSL_R_NO_SUITABLE_SIGNATURE_ALGORITHM);
return rv;
}
/* Given preference and allowed sigalgs set shared sigalgs */
static size_t tls12_shared_sigalgs(SSL *s, const SIGALG_LOOKUP **shsig,
const uint16_t *pref, size_t preflen,
const uint16_t *allow, size_t allowlen)
{
const uint16_t *ptmp, *atmp;
size_t i, j, nmatch = 0;
for (i = 0, ptmp = pref; i < preflen; i++, ptmp++) {
const SIGALG_LOOKUP *lu = tls1_lookup_sigalg(s, *ptmp);
/* Skip disabled hashes or signature algorithms */
if (lu == NULL
|| !tls12_sigalg_allowed(s, SSL_SECOP_SIGALG_SHARED, lu))
continue;
for (j = 0, atmp = allow; j < allowlen; j++, atmp++) {
if (*ptmp == *atmp) {
nmatch++;
if (shsig)
*shsig++ = lu;
break;
}
}
}
return nmatch;
}
/* Set shared signature algorithms for SSL structures */
static int tls1_set_shared_sigalgs(SSL *s)
{
const uint16_t *pref, *allow, *conf;
size_t preflen, allowlen, conflen;
size_t nmatch;
const SIGALG_LOOKUP **salgs = NULL;
CERT *c = s->cert;
unsigned int is_suiteb = tls1_suiteb(s);
OPENSSL_free(s->shared_sigalgs);
s->shared_sigalgs = NULL;
s->shared_sigalgslen = 0;
/* If client use client signature algorithms if not NULL */
if (!s->server && c->client_sigalgs && !is_suiteb) {
conf = c->client_sigalgs;
conflen = c->client_sigalgslen;
} else if (c->conf_sigalgs && !is_suiteb) {
conf = c->conf_sigalgs;
conflen = c->conf_sigalgslen;
} else
conflen = tls12_get_psigalgs(s, 0, &conf);
if (s->options & SSL_OP_CIPHER_SERVER_PREFERENCE || is_suiteb) {
pref = conf;
preflen = conflen;
allow = s->s3.tmp.peer_sigalgs;
allowlen = s->s3.tmp.peer_sigalgslen;
} else {
allow = conf;
allowlen = conflen;
pref = s->s3.tmp.peer_sigalgs;
preflen = s->s3.tmp.peer_sigalgslen;
}
nmatch = tls12_shared_sigalgs(s, NULL, pref, preflen, allow, allowlen);
if (nmatch) {
if ((salgs = OPENSSL_malloc(nmatch * sizeof(*salgs))) == NULL) {
ERR_raise(ERR_LIB_SSL, ERR_R_MALLOC_FAILURE);
return 0;
}
nmatch = tls12_shared_sigalgs(s, salgs, pref, preflen, allow, allowlen);
} else {
salgs = NULL;
}
s->shared_sigalgs = salgs;
s->shared_sigalgslen = nmatch;
return 1;
}
int tls1_save_u16(PACKET *pkt, uint16_t **pdest, size_t *pdestlen)
{
unsigned int stmp;
size_t size, i;
uint16_t *buf;
size = PACKET_remaining(pkt);
/* Invalid data length */
if (size == 0 || (size & 1) != 0)
return 0;
size >>= 1;
if ((buf = OPENSSL_malloc(size * sizeof(*buf))) == NULL) {
ERR_raise(ERR_LIB_SSL, ERR_R_MALLOC_FAILURE);
return 0;
}
for (i = 0; i < size && PACKET_get_net_2(pkt, &stmp); i++)
buf[i] = stmp;
if (i != size) {
OPENSSL_free(buf);
return 0;
}
OPENSSL_free(*pdest);
*pdest = buf;
*pdestlen = size;
return 1;
}
int tls1_save_sigalgs(SSL *s, PACKET *pkt, int cert)
{
/* Extension ignored for inappropriate versions */
if (!SSL_USE_SIGALGS(s))
return 1;
/* Should never happen */
if (s->cert == NULL)
return 0;
if (cert)
return tls1_save_u16(pkt, &s->s3.tmp.peer_cert_sigalgs,
&s->s3.tmp.peer_cert_sigalgslen);
else
return tls1_save_u16(pkt, &s->s3.tmp.peer_sigalgs,
&s->s3.tmp.peer_sigalgslen);
}
/* Set preferred digest for each key type */
int tls1_process_sigalgs(SSL *s)
{
size_t i;
uint32_t *pvalid = s->s3.tmp.valid_flags;
if (!tls1_set_shared_sigalgs(s))
return 0;
for (i = 0; i < SSL_PKEY_NUM; i++)
pvalid[i] = 0;
for (i = 0; i < s->shared_sigalgslen; i++) {
const SIGALG_LOOKUP *sigptr = s->shared_sigalgs[i];
int idx = sigptr->sig_idx;
/* Ignore PKCS1 based sig algs in TLSv1.3 */
if (SSL_IS_TLS13(s) && sigptr->sig == EVP_PKEY_RSA)
continue;
/* If not disabled indicate we can explicitly sign */
if (pvalid[idx] == 0 && !ssl_cert_is_disabled(s->ctx, idx))
pvalid[idx] = CERT_PKEY_EXPLICIT_SIGN | CERT_PKEY_SIGN;
}
return 1;
}
int SSL_get_sigalgs(SSL *s, int idx,
int *psign, int *phash, int *psignhash,
unsigned char *rsig, unsigned char *rhash)
{
uint16_t *psig = s->s3.tmp.peer_sigalgs;
size_t numsigalgs = s->s3.tmp.peer_sigalgslen;
if (psig == NULL || numsigalgs > INT_MAX)
return 0;
if (idx >= 0) {
const SIGALG_LOOKUP *lu;
if (idx >= (int)numsigalgs)
return 0;
psig += idx;
if (rhash != NULL)
*rhash = (unsigned char)((*psig >> 8) & 0xff);
if (rsig != NULL)
*rsig = (unsigned char)(*psig & 0xff);
lu = tls1_lookup_sigalg(s, *psig);
if (psign != NULL)
*psign = lu != NULL ? lu->sig : NID_undef;
if (phash != NULL)
*phash = lu != NULL ? lu->hash : NID_undef;
if (psignhash != NULL)
*psignhash = lu != NULL ? lu->sigandhash : NID_undef;
}
return (int)numsigalgs;
}
int SSL_get_shared_sigalgs(SSL *s, int idx,
int *psign, int *phash, int *psignhash,
unsigned char *rsig, unsigned char *rhash)
{
const SIGALG_LOOKUP *shsigalgs;
if (s->shared_sigalgs == NULL
|| idx < 0
|| idx >= (int)s->shared_sigalgslen
|| s->shared_sigalgslen > INT_MAX)
return 0;
shsigalgs = s->shared_sigalgs[idx];
if (phash != NULL)
*phash = shsigalgs->hash;
if (psign != NULL)
*psign = shsigalgs->sig;
if (psignhash != NULL)
*psignhash = shsigalgs->sigandhash;
if (rsig != NULL)
*rsig = (unsigned char)(shsigalgs->sigalg & 0xff);
if (rhash != NULL)
*rhash = (unsigned char)((shsigalgs->sigalg >> 8) & 0xff);
return (int)s->shared_sigalgslen;
}
/* Maximum possible number of unique entries in sigalgs array */
#define TLS_MAX_SIGALGCNT (OSSL_NELEM(sigalg_lookup_tbl) * 2)
typedef struct {
size_t sigalgcnt;
/* TLSEXT_SIGALG_XXX values */
uint16_t sigalgs[TLS_MAX_SIGALGCNT];
} sig_cb_st;
static void get_sigorhash(int *psig, int *phash, const char *str)
{
if (strcmp(str, "RSA") == 0) {
*psig = EVP_PKEY_RSA;
} else if (strcmp(str, "RSA-PSS") == 0 || strcmp(str, "PSS") == 0) {
*psig = EVP_PKEY_RSA_PSS;
} else if (strcmp(str, "DSA") == 0) {
*psig = EVP_PKEY_DSA;
} else if (strcmp(str, "ECDSA") == 0) {
*psig = EVP_PKEY_EC;
} else {
*phash = OBJ_sn2nid(str);
if (*phash == NID_undef)
*phash = OBJ_ln2nid(str);
}
}
/* Maximum length of a signature algorithm string component */
#define TLS_MAX_SIGSTRING_LEN 40
static int sig_cb(const char *elem, int len, void *arg)
{
sig_cb_st *sarg = arg;
size_t i;
const SIGALG_LOOKUP *s;
char etmp[TLS_MAX_SIGSTRING_LEN], *p;
int sig_alg = NID_undef, hash_alg = NID_undef;
if (elem == NULL)
return 0;
if (sarg->sigalgcnt == TLS_MAX_SIGALGCNT)
return 0;
if (len > (int)(sizeof(etmp) - 1))
return 0;
memcpy(etmp, elem, len);
etmp[len] = 0;
p = strchr(etmp, '+');
/*
* We only allow SignatureSchemes listed in the sigalg_lookup_tbl;
* if there's no '+' in the provided name, look for the new-style combined
* name. If not, match both sig+hash to find the needed SIGALG_LOOKUP.
* Just sig+hash is not unique since TLS 1.3 adds rsa_pss_pss_* and
* rsa_pss_rsae_* that differ only by public key OID; in such cases
* we will pick the _rsae_ variant, by virtue of them appearing earlier
* in the table.
*/
if (p == NULL) {
for (i = 0, s = sigalg_lookup_tbl; i < OSSL_NELEM(sigalg_lookup_tbl);
i++, s++) {
if (s->name != NULL && strcmp(etmp, s->name) == 0) {
sarg->sigalgs[sarg->sigalgcnt++] = s->sigalg;
break;
}
}
if (i == OSSL_NELEM(sigalg_lookup_tbl))
return 0;
} else {
*p = 0;
p++;
if (*p == 0)
return 0;
get_sigorhash(&sig_alg, &hash_alg, etmp);
get_sigorhash(&sig_alg, &hash_alg, p);
if (sig_alg == NID_undef || hash_alg == NID_undef)
return 0;
for (i = 0, s = sigalg_lookup_tbl; i < OSSL_NELEM(sigalg_lookup_tbl);
i++, s++) {
if (s->hash == hash_alg && s->sig == sig_alg) {
sarg->sigalgs[sarg->sigalgcnt++] = s->sigalg;
break;
}
}
if (i == OSSL_NELEM(sigalg_lookup_tbl))
return 0;
}
/* Reject duplicates */
for (i = 0; i < sarg->sigalgcnt - 1; i++) {
if (sarg->sigalgs[i] == sarg->sigalgs[sarg->sigalgcnt - 1]) {
sarg->sigalgcnt--;
return 0;
}
}
return 1;
}
/*
* Set supported signature algorithms based on a colon separated list of the
* form sig+hash e.g. RSA+SHA512:DSA+SHA512
*/
int tls1_set_sigalgs_list(CERT *c, const char *str, int client)
{
sig_cb_st sig;
sig.sigalgcnt = 0;
if (!CONF_parse_list(str, ':', 1, sig_cb, &sig))
return 0;
if (c == NULL)
return 1;
return tls1_set_raw_sigalgs(c, sig.sigalgs, sig.sigalgcnt, client);
}
int tls1_set_raw_sigalgs(CERT *c, const uint16_t *psigs, size_t salglen,
int client)
{
uint16_t *sigalgs;
if ((sigalgs = OPENSSL_malloc(salglen * sizeof(*sigalgs))) == NULL) {
ERR_raise(ERR_LIB_SSL, ERR_R_MALLOC_FAILURE);
return 0;
}
memcpy(sigalgs, psigs, salglen * sizeof(*sigalgs));
if (client) {
OPENSSL_free(c->client_sigalgs);
c->client_sigalgs = sigalgs;
c->client_sigalgslen = salglen;
} else {
OPENSSL_free(c->conf_sigalgs);
c->conf_sigalgs = sigalgs;
c->conf_sigalgslen = salglen;
}
return 1;
}
int tls1_set_sigalgs(CERT *c, const int *psig_nids, size_t salglen, int client)
{
uint16_t *sigalgs, *sptr;
size_t i;
if (salglen & 1)
return 0;
if ((sigalgs = OPENSSL_malloc((salglen / 2) * sizeof(*sigalgs))) == NULL) {
ERR_raise(ERR_LIB_SSL, ERR_R_MALLOC_FAILURE);
return 0;
}
for (i = 0, sptr = sigalgs; i < salglen; i += 2) {
size_t j;
const SIGALG_LOOKUP *curr;
int md_id = *psig_nids++;
int sig_id = *psig_nids++;
for (j = 0, curr = sigalg_lookup_tbl; j < OSSL_NELEM(sigalg_lookup_tbl);
j++, curr++) {
if (curr->hash == md_id && curr->sig == sig_id) {
*sptr++ = curr->sigalg;
break;
}
}
if (j == OSSL_NELEM(sigalg_lookup_tbl))
goto err;
}
if (client) {
OPENSSL_free(c->client_sigalgs);
c->client_sigalgs = sigalgs;
c->client_sigalgslen = salglen / 2;
} else {
OPENSSL_free(c->conf_sigalgs);
c->conf_sigalgs = sigalgs;
c->conf_sigalgslen = salglen / 2;
}
return 1;
err:
OPENSSL_free(sigalgs);
return 0;
}
static int tls1_check_sig_alg(SSL *s, X509 *x, int default_nid)
{
int sig_nid, use_pc_sigalgs = 0;
size_t i;
const SIGALG_LOOKUP *sigalg;
size_t sigalgslen;
if (default_nid == -1)
return 1;
sig_nid = X509_get_signature_nid(x);
if (default_nid)
return sig_nid == default_nid ? 1 : 0;
if (SSL_IS_TLS13(s) && s->s3.tmp.peer_cert_sigalgs != NULL) {
/*
* If we're in TLSv1.3 then we only get here if we're checking the
* chain. If the peer has specified peer_cert_sigalgs then we use them
* otherwise we default to normal sigalgs.
*/
sigalgslen = s->s3.tmp.peer_cert_sigalgslen;
use_pc_sigalgs = 1;
} else {
sigalgslen = s->shared_sigalgslen;
}
for (i = 0; i < sigalgslen; i++) {
sigalg = use_pc_sigalgs
? tls1_lookup_sigalg(s, s->s3.tmp.peer_cert_sigalgs[i])
: s->shared_sigalgs[i];
if (sigalg != NULL && sig_nid == sigalg->sigandhash)
return 1;
}
return 0;
}
/* Check to see if a certificate issuer name matches list of CA names */
static int ssl_check_ca_name(STACK_OF(X509_NAME) *names, X509 *x)
{
const X509_NAME *nm;
int i;
nm = X509_get_issuer_name(x);
for (i = 0; i < sk_X509_NAME_num(names); i++) {
if (!X509_NAME_cmp(nm, sk_X509_NAME_value(names, i)))
return 1;
}
return 0;
}
/*
* Check certificate chain is consistent with TLS extensions and is usable by
* server. This servers two purposes: it allows users to check chains before
* passing them to the server and it allows the server to check chains before
* attempting to use them.
*/
/* Flags which need to be set for a certificate when strict mode not set */
#define CERT_PKEY_VALID_FLAGS \
(CERT_PKEY_EE_SIGNATURE|CERT_PKEY_EE_PARAM)
/* Strict mode flags */
#define CERT_PKEY_STRICT_FLAGS \
(CERT_PKEY_VALID_FLAGS|CERT_PKEY_CA_SIGNATURE|CERT_PKEY_CA_PARAM \
| CERT_PKEY_ISSUER_NAME|CERT_PKEY_CERT_TYPE)
int tls1_check_chain(SSL *s, X509 *x, EVP_PKEY *pk, STACK_OF(X509) *chain,
int idx)
{
int i;
int rv = 0;
int check_flags = 0, strict_mode;
CERT_PKEY *cpk = NULL;
CERT *c = s->cert;
uint32_t *pvalid;
unsigned int suiteb_flags = tls1_suiteb(s);
/* idx == -1 means checking server chains */
if (idx != -1) {
/* idx == -2 means checking client certificate chains */
if (idx == -2) {
cpk = c->key;
idx = (int)(cpk - c->pkeys);
} else
cpk = c->pkeys + idx;
pvalid = s->s3.tmp.valid_flags + idx;
x = cpk->x509;
pk = cpk->privatekey;
chain = cpk->chain;
strict_mode = c->cert_flags & SSL_CERT_FLAGS_CHECK_TLS_STRICT;
/* If no cert or key, forget it */
if (!x || !pk)
goto end;
} else {
size_t certidx;
if (!x || !pk)
return 0;
if (ssl_cert_lookup_by_pkey(pk, &certidx) == NULL)
return 0;
idx = certidx;
pvalid = s->s3.tmp.valid_flags + idx;
if (c->cert_flags & SSL_CERT_FLAGS_CHECK_TLS_STRICT)
check_flags = CERT_PKEY_STRICT_FLAGS;
else
check_flags = CERT_PKEY_VALID_FLAGS;
strict_mode = 1;
}
if (suiteb_flags) {
int ok;
if (check_flags)
check_flags |= CERT_PKEY_SUITEB;
ok = X509_chain_check_suiteb(NULL, x, chain, suiteb_flags);
if (ok == X509_V_OK)
rv |= CERT_PKEY_SUITEB;
else if (!check_flags)
goto end;
}
/*
* Check all signature algorithms are consistent with signature
* algorithms extension if TLS 1.2 or later and strict mode.
*/
if (TLS1_get_version(s) >= TLS1_2_VERSION && strict_mode) {
int default_nid;
int rsign = 0;
if (s->s3.tmp.peer_cert_sigalgs != NULL
|| s->s3.tmp.peer_sigalgs != NULL) {
default_nid = 0;
/* If no sigalgs extension use defaults from RFC5246 */
} else {
switch (idx) {
case SSL_PKEY_RSA:
rsign = EVP_PKEY_RSA;
default_nid = NID_sha1WithRSAEncryption;
break;
case SSL_PKEY_DSA_SIGN:
rsign = EVP_PKEY_DSA;
default_nid = NID_dsaWithSHA1;
break;
case SSL_PKEY_ECC:
rsign = EVP_PKEY_EC;
default_nid = NID_ecdsa_with_SHA1;
break;
case SSL_PKEY_GOST01:
rsign = NID_id_GostR3410_2001;
default_nid = NID_id_GostR3411_94_with_GostR3410_2001;
break;
case SSL_PKEY_GOST12_256:
rsign = NID_id_GostR3410_2012_256;
default_nid = NID_id_tc26_signwithdigest_gost3410_2012_256;
break;
case SSL_PKEY_GOST12_512:
rsign = NID_id_GostR3410_2012_512;
default_nid = NID_id_tc26_signwithdigest_gost3410_2012_512;
break;
default:
default_nid = -1;
break;
}
}
/*
* If peer sent no signature algorithms extension and we have set
* preferred signature algorithms check we support sha1.
*/
if (default_nid > 0 && c->conf_sigalgs) {
size_t j;
const uint16_t *p = c->conf_sigalgs;
for (j = 0; j < c->conf_sigalgslen; j++, p++) {
const SIGALG_LOOKUP *lu = tls1_lookup_sigalg(s, *p);
if (lu != NULL && lu->hash == NID_sha1 && lu->sig == rsign)
break;
}
if (j == c->conf_sigalgslen) {
if (check_flags)
goto skip_sigs;
else
goto end;
}
}
/* Check signature algorithm of each cert in chain */
if (SSL_IS_TLS13(s)) {
/*
* We only get here if the application has called SSL_check_chain(),
* so check_flags is always set.
*/
if (find_sig_alg(s, x, pk) != NULL)
rv |= CERT_PKEY_EE_SIGNATURE;
} else if (!tls1_check_sig_alg(s, x, default_nid)) {
if (!check_flags)
goto end;
} else
rv |= CERT_PKEY_EE_SIGNATURE;
rv |= CERT_PKEY_CA_SIGNATURE;
for (i = 0; i < sk_X509_num(chain); i++) {
if (!tls1_check_sig_alg(s, sk_X509_value(chain, i), default_nid)) {
if (check_flags) {
rv &= ~CERT_PKEY_CA_SIGNATURE;
break;
} else
goto end;
}
}
}
/* Else not TLS 1.2, so mark EE and CA signing algorithms OK */
else if (check_flags)
rv |= CERT_PKEY_EE_SIGNATURE | CERT_PKEY_CA_SIGNATURE;
skip_sigs:
/* Check cert parameters are consistent */
if (tls1_check_cert_param(s, x, 1))
rv |= CERT_PKEY_EE_PARAM;
else if (!check_flags)
goto end;
if (!s->server)
rv |= CERT_PKEY_CA_PARAM;
/* In strict mode check rest of chain too */
else if (strict_mode) {
rv |= CERT_PKEY_CA_PARAM;
for (i = 0; i < sk_X509_num(chain); i++) {
X509 *ca = sk_X509_value(chain, i);
if (!tls1_check_cert_param(s, ca, 0)) {
if (check_flags) {
rv &= ~CERT_PKEY_CA_PARAM;
break;
} else
goto end;
}
}
}
if (!s->server && strict_mode) {
STACK_OF(X509_NAME) *ca_dn;
int check_type = 0;
if (EVP_PKEY_is_a(pk, "RSA"))
check_type = TLS_CT_RSA_SIGN;
else if (EVP_PKEY_is_a(pk, "DSA"))
check_type = TLS_CT_DSS_SIGN;
else if (EVP_PKEY_is_a(pk, "EC"))
check_type = TLS_CT_ECDSA_SIGN;
if (check_type) {
const uint8_t *ctypes = s->s3.tmp.ctype;
size_t j;
for (j = 0; j < s->s3.tmp.ctype_len; j++, ctypes++) {
if (*ctypes == check_type) {
rv |= CERT_PKEY_CERT_TYPE;
break;
}
}
if (!(rv & CERT_PKEY_CERT_TYPE) && !check_flags)
goto end;
} else {
rv |= CERT_PKEY_CERT_TYPE;
}
ca_dn = s->s3.tmp.peer_ca_names;
if (ca_dn == NULL
|| sk_X509_NAME_num(ca_dn) == 0
|| ssl_check_ca_name(ca_dn, x))
rv |= CERT_PKEY_ISSUER_NAME;
else
for (i = 0; i < sk_X509_num(chain); i++) {
X509 *xtmp = sk_X509_value(chain, i);
if (ssl_check_ca_name(ca_dn, xtmp)) {
rv |= CERT_PKEY_ISSUER_NAME;
break;
}
}
if (!check_flags && !(rv & CERT_PKEY_ISSUER_NAME))
goto end;
} else
rv |= CERT_PKEY_ISSUER_NAME | CERT_PKEY_CERT_TYPE;
if (!check_flags || (rv & check_flags) == check_flags)
rv |= CERT_PKEY_VALID;
end:
if (TLS1_get_version(s) >= TLS1_2_VERSION)
rv |= *pvalid & (CERT_PKEY_EXPLICIT_SIGN | CERT_PKEY_SIGN);
else
rv |= CERT_PKEY_SIGN | CERT_PKEY_EXPLICIT_SIGN;
/*
* When checking a CERT_PKEY structure all flags are irrelevant if the
* chain is invalid.
*/
if (!check_flags) {
if (rv & CERT_PKEY_VALID) {
*pvalid = rv;
} else {
/* Preserve sign and explicit sign flag, clear rest */
*pvalid &= CERT_PKEY_EXPLICIT_SIGN | CERT_PKEY_SIGN;
return 0;
}
}
return rv;
}
/* Set validity of certificates in an SSL structure */
void tls1_set_cert_validity(SSL *s)
{
tls1_check_chain(s, NULL, NULL, NULL, SSL_PKEY_RSA);
tls1_check_chain(s, NULL, NULL, NULL, SSL_PKEY_RSA_PSS_SIGN);
tls1_check_chain(s, NULL, NULL, NULL, SSL_PKEY_DSA_SIGN);
tls1_check_chain(s, NULL, NULL, NULL, SSL_PKEY_ECC);
tls1_check_chain(s, NULL, NULL, NULL, SSL_PKEY_GOST01);
tls1_check_chain(s, NULL, NULL, NULL, SSL_PKEY_GOST12_256);
tls1_check_chain(s, NULL, NULL, NULL, SSL_PKEY_GOST12_512);
tls1_check_chain(s, NULL, NULL, NULL, SSL_PKEY_ED25519);
tls1_check_chain(s, NULL, NULL, NULL, SSL_PKEY_ED448);
}
/* User level utility function to check a chain is suitable */
int SSL_check_chain(SSL *s, X509 *x, EVP_PKEY *pk, STACK_OF(X509) *chain)
{
return tls1_check_chain(s, x, pk, chain, -1);
}
EVP_PKEY *ssl_get_auto_dh(SSL *s)
{
EVP_PKEY *dhp = NULL;
BIGNUM *p;
int dh_secbits = 80, sec_level_bits;
EVP_PKEY_CTX *pctx = NULL;
OSSL_PARAM_BLD *tmpl = NULL;
OSSL_PARAM *params = NULL;
if (s->cert->dh_tmp_auto != 2) {
if (s->s3.tmp.new_cipher->algorithm_auth & (SSL_aNULL | SSL_aPSK)) {
if (s->s3.tmp.new_cipher->strength_bits == 256)
dh_secbits = 128;
else
dh_secbits = 80;
} else {
if (s->s3.tmp.cert == NULL)
return NULL;
dh_secbits = EVP_PKEY_get_security_bits(s->s3.tmp.cert->privatekey);
}
}
/* Do not pick a prime that is too weak for the current security level */
sec_level_bits = ssl_get_security_level_bits(s, NULL, NULL);
if (dh_secbits < sec_level_bits)
dh_secbits = sec_level_bits;
if (dh_secbits >= 192)
p = BN_get_rfc3526_prime_8192(NULL);
else if (dh_secbits >= 152)
p = BN_get_rfc3526_prime_4096(NULL);
else if (dh_secbits >= 128)
p = BN_get_rfc3526_prime_3072(NULL);
else if (dh_secbits >= 112)
p = BN_get_rfc3526_prime_2048(NULL);
else
p = BN_get_rfc2409_prime_1024(NULL);
if (p == NULL)
goto err;
pctx = EVP_PKEY_CTX_new_from_name(s->ctx->libctx, "DH", s->ctx->propq);
if (pctx == NULL
|| EVP_PKEY_fromdata_init(pctx) != 1)
goto err;
tmpl = OSSL_PARAM_BLD_new();
if (tmpl == NULL
|| !OSSL_PARAM_BLD_push_BN(tmpl, OSSL_PKEY_PARAM_FFC_P, p)
|| !OSSL_PARAM_BLD_push_uint(tmpl, OSSL_PKEY_PARAM_FFC_G, 2))
goto err;
params = OSSL_PARAM_BLD_to_param(tmpl);
if (params == NULL
|| EVP_PKEY_fromdata(pctx, &dhp, EVP_PKEY_KEY_PARAMETERS, params) != 1)
goto err;
err:
OSSL_PARAM_free(params);
OSSL_PARAM_BLD_free(tmpl);
EVP_PKEY_CTX_free(pctx);
BN_free(p);
return dhp;
}
static int ssl_security_cert_key(SSL *s, SSL_CTX *ctx, X509 *x, int op)
{
int secbits = -1;
EVP_PKEY *pkey = X509_get0_pubkey(x);
if (pkey) {
/*
* If no parameters this will return -1 and fail using the default
* security callback for any non-zero security level. This will
* reject keys which omit parameters but this only affects DSA and
* omission of parameters is never (?) done in practice.
*/
secbits = EVP_PKEY_get_security_bits(pkey);
}
if (s)
return ssl_security(s, op, secbits, 0, x);
else
return ssl_ctx_security(ctx, op, secbits, 0, x);
}
static int ssl_security_cert_sig(SSL *s, SSL_CTX *ctx, X509 *x, int op)
{
/* Lookup signature algorithm digest */
int secbits, nid, pknid;
/* Don't check signature if self signed */
if ((X509_get_extension_flags(x) & EXFLAG_SS) != 0)
return 1;
if (!X509_get_signature_info(x, &nid, &pknid, &secbits, NULL))
secbits = -1;
/* If digest NID not defined use signature NID */
if (nid == NID_undef)
nid = pknid;
if (s)
return ssl_security(s, op, secbits, nid, x);
else
return ssl_ctx_security(ctx, op, secbits, nid, x);
}
int ssl_security_cert(SSL *s, SSL_CTX *ctx, X509 *x, int vfy, int is_ee)
{
if (vfy)
vfy = SSL_SECOP_PEER;
if (is_ee) {
if (!ssl_security_cert_key(s, ctx, x, SSL_SECOP_EE_KEY | vfy))
return SSL_R_EE_KEY_TOO_SMALL;
} else {
if (!ssl_security_cert_key(s, ctx, x, SSL_SECOP_CA_KEY | vfy))
return SSL_R_CA_KEY_TOO_SMALL;
}
if (!ssl_security_cert_sig(s, ctx, x, SSL_SECOP_CA_MD | vfy))
return SSL_R_CA_MD_TOO_WEAK;
return 1;
}
/*
* Check security of a chain, if |sk| includes the end entity certificate then
* |x| is NULL. If |vfy| is 1 then we are verifying a peer chain and not sending
* one to the peer. Return values: 1 if ok otherwise error code to use
*/
int ssl_security_cert_chain(SSL *s, STACK_OF(X509) *sk, X509 *x, int vfy)
{
int rv, start_idx, i;
if (x == NULL) {
x = sk_X509_value(sk, 0);
if (x == NULL)
return ERR_R_INTERNAL_ERROR;
start_idx = 1;
} else
start_idx = 0;
rv = ssl_security_cert(s, NULL, x, vfy, 1);
if (rv != 1)
return rv;
for (i = start_idx; i < sk_X509_num(sk); i++) {
x = sk_X509_value(sk, i);
rv = ssl_security_cert(s, NULL, x, vfy, 0);
if (rv != 1)
return rv;
}
return 1;
}
/*
* For TLS 1.2 servers check if we have a certificate which can be used
* with the signature algorithm "lu" and return index of certificate.
*/
static int tls12_get_cert_sigalg_idx(const SSL *s, const SIGALG_LOOKUP *lu)
{
int sig_idx = lu->sig_idx;
const SSL_CERT_LOOKUP *clu = ssl_cert_lookup_by_idx(sig_idx);
/* If not recognised or not supported by cipher mask it is not suitable */
if (clu == NULL
|| (clu->amask & s->s3.tmp.new_cipher->algorithm_auth) == 0
|| (clu->nid == EVP_PKEY_RSA_PSS
&& (s->s3.tmp.new_cipher->algorithm_mkey & SSL_kRSA) != 0))
return -1;
return s->s3.tmp.valid_flags[sig_idx] & CERT_PKEY_VALID ? sig_idx : -1;
}
/*
* Checks the given cert against signature_algorithm_cert restrictions sent by
* the peer (if any) as well as whether the hash from the sigalg is usable with
* the key.
* Returns true if the cert is usable and false otherwise.
*/
static int check_cert_usable(SSL *s, const SIGALG_LOOKUP *sig, X509 *x,
EVP_PKEY *pkey)
{
const SIGALG_LOOKUP *lu;
int mdnid, pknid, supported;
size_t i;
const char *mdname = NULL;
/*
* If the given EVP_PKEY cannot support signing with this digest,
* the answer is simply 'no'.
*/
if (sig->hash != NID_undef)
mdname = OBJ_nid2sn(sig->hash);
supported = EVP_PKEY_digestsign_supports_digest(pkey, s->ctx->libctx,
mdname,
s->ctx->propq);
if (supported <= 0)
return 0;
/*
* The TLS 1.3 signature_algorithms_cert extension places restrictions
* on the sigalg with which the certificate was signed (by its issuer).
*/
if (s->s3.tmp.peer_cert_sigalgs != NULL) {
if (!X509_get_signature_info(x, &mdnid, &pknid, NULL, NULL))
return 0;
for (i = 0; i < s->s3.tmp.peer_cert_sigalgslen; i++) {
lu = tls1_lookup_sigalg(s, s->s3.tmp.peer_cert_sigalgs[i]);
if (lu == NULL)
continue;
/*
* This does not differentiate between the
* rsa_pss_pss_* and rsa_pss_rsae_* schemes since we do not
* have a chain here that lets us look at the key OID in the
* signing certificate.
*/
if (mdnid == lu->hash && pknid == lu->sig)
return 1;
}
return 0;
}
/*
* Without signat_algorithms_cert, any certificate for which we have
* a viable public key is permitted.
*/
return 1;
}
/*
* Returns true if |s| has a usable certificate configured for use
* with signature scheme |sig|.
* "Usable" includes a check for presence as well as applying
* the signature_algorithm_cert restrictions sent by the peer (if any).
* Returns false if no usable certificate is found.
*/
static int has_usable_cert(SSL *s, const SIGALG_LOOKUP *sig, int idx)
{
/* TLS 1.2 callers can override sig->sig_idx, but not TLS 1.3 callers. */
if (idx == -1)
idx = sig->sig_idx;
if (!ssl_has_cert(s, idx))
return 0;
return check_cert_usable(s, sig, s->cert->pkeys[idx].x509,
s->cert->pkeys[idx].privatekey);
}
/*
* Returns true if the supplied cert |x| and key |pkey| is usable with the
* specified signature scheme |sig|, or false otherwise.
*/
static int is_cert_usable(SSL *s, const SIGALG_LOOKUP *sig, X509 *x,
EVP_PKEY *pkey)
{
size_t idx;
if (ssl_cert_lookup_by_pkey(pkey, &idx) == NULL)
return 0;
/* Check the key is consistent with the sig alg */
if ((int)idx != sig->sig_idx)
return 0;
return check_cert_usable(s, sig, x, pkey);
}
/*
* Find a signature scheme that works with the supplied certificate |x| and key
* |pkey|. |x| and |pkey| may be NULL in which case we additionally look at our
* available certs/keys to find one that works.
*/
static const SIGALG_LOOKUP *find_sig_alg(SSL *s, X509 *x, EVP_PKEY *pkey)
{
const SIGALG_LOOKUP *lu = NULL;
size_t i;
int curve = -1;
EVP_PKEY *tmppkey;
/* Look for a shared sigalgs matching possible certificates */
for (i = 0; i < s->shared_sigalgslen; i++) {
lu = s->shared_sigalgs[i];
/* Skip SHA1, SHA224, DSA and RSA if not PSS */
if (lu->hash == NID_sha1
|| lu->hash == NID_sha224
|| lu->sig == EVP_PKEY_DSA
|| lu->sig == EVP_PKEY_RSA)
continue;
/* Check that we have a cert, and signature_algorithms_cert */
if (!tls1_lookup_md(s->ctx, lu, NULL))
continue;
if ((pkey == NULL && !has_usable_cert(s, lu, -1))
|| (pkey != NULL && !is_cert_usable(s, lu, x, pkey)))
continue;
tmppkey = (pkey != NULL) ? pkey
: s->cert->pkeys[lu->sig_idx].privatekey;
if (lu->sig == EVP_PKEY_EC) {
if (curve == -1)
curve = ssl_get_EC_curve_nid(tmppkey);
if (lu->curve != NID_undef && curve != lu->curve)
continue;
} else if (lu->sig == EVP_PKEY_RSA_PSS) {
/* validate that key is large enough for the signature algorithm */
if (!rsa_pss_check_min_key_size(s->ctx, tmppkey, lu))
continue;
}
break;
}
if (i == s->shared_sigalgslen)
return NULL;
return lu;
}
/*
* Choose an appropriate signature algorithm based on available certificates
* Sets chosen certificate and signature algorithm.
*
* For servers if we fail to find a required certificate it is a fatal error,
* an appropriate error code is set and a TLS alert is sent.
*
* For clients fatalerrs is set to 0. If a certificate is not suitable it is not
* a fatal error: we will either try another certificate or not present one
* to the server. In this case no error is set.
*/
int tls_choose_sigalg(SSL *s, int fatalerrs)
{
const SIGALG_LOOKUP *lu = NULL;
int sig_idx = -1;
s->s3.tmp.cert = NULL;
s->s3.tmp.sigalg = NULL;
if (SSL_IS_TLS13(s)) {
lu = find_sig_alg(s, NULL, NULL);
if (lu == NULL) {
if (!fatalerrs)
return 1;
SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
SSL_R_NO_SUITABLE_SIGNATURE_ALGORITHM);
return 0;
}
} else {
/* If ciphersuite doesn't require a cert nothing to do */
if (!(s->s3.tmp.new_cipher->algorithm_auth & SSL_aCERT))
return 1;
if (!s->server && !ssl_has_cert(s, s->cert->key - s->cert->pkeys))
return 1;
if (SSL_USE_SIGALGS(s)) {
size_t i;
if (s->s3.tmp.peer_sigalgs != NULL) {
int curve = -1;
/* For Suite B need to match signature algorithm to curve */
if (tls1_suiteb(s))
curve = ssl_get_EC_curve_nid(s->cert->pkeys[SSL_PKEY_ECC]
.privatekey);
/*
* Find highest preference signature algorithm matching
* cert type
*/
for (i = 0; i < s->shared_sigalgslen; i++) {
lu = s->shared_sigalgs[i];
if (s->server) {
if ((sig_idx = tls12_get_cert_sigalg_idx(s, lu)) == -1)
continue;
} else {
int cc_idx = s->cert->key - s->cert->pkeys;
sig_idx = lu->sig_idx;
if (cc_idx != sig_idx)
continue;
}
/* Check that we have a cert, and sig_algs_cert */
if (!has_usable_cert(s, lu, sig_idx))
continue;
if (lu->sig == EVP_PKEY_RSA_PSS) {
/* validate that key is large enough for the signature algorithm */
EVP_PKEY *pkey = s->cert->pkeys[sig_idx].privatekey;
if (!rsa_pss_check_min_key_size(s->ctx, pkey, lu))
continue;
}
if (curve == -1 || lu->curve == curve)
break;
}
#ifndef OPENSSL_NO_GOST
/*
* Some Windows-based implementations do not send GOST algorithms indication
* in supported_algorithms extension, so when we have GOST-based ciphersuite,
* we have to assume GOST support.
*/
if (i == s->shared_sigalgslen && s->s3.tmp.new_cipher->algorithm_auth & (SSL_aGOST01 | SSL_aGOST12)) {
if ((lu = tls1_get_legacy_sigalg(s, -1)) == NULL) {
if (!fatalerrs)
return 1;
SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
SSL_R_NO_SUITABLE_SIGNATURE_ALGORITHM);
return 0;
} else {
i = 0;
sig_idx = lu->sig_idx;
}
}
#endif
if (i == s->shared_sigalgslen) {
if (!fatalerrs)
return 1;
SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
SSL_R_NO_SUITABLE_SIGNATURE_ALGORITHM);
return 0;
}
} else {
/*
* If we have no sigalg use defaults
*/
const uint16_t *sent_sigs;
size_t sent_sigslen;
if ((lu = tls1_get_legacy_sigalg(s, -1)) == NULL) {
if (!fatalerrs)
return 1;
SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
SSL_R_NO_SUITABLE_SIGNATURE_ALGORITHM);
return 0;
}
/* Check signature matches a type we sent */
sent_sigslen = tls12_get_psigalgs(s, 1, &sent_sigs);
for (i = 0; i < sent_sigslen; i++, sent_sigs++) {
if (lu->sigalg == *sent_sigs
&& has_usable_cert(s, lu, lu->sig_idx))
break;
}
if (i == sent_sigslen) {
if (!fatalerrs)
return 1;
SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
SSL_R_WRONG_SIGNATURE_TYPE);
return 0;
}
}
} else {
if ((lu = tls1_get_legacy_sigalg(s, -1)) == NULL) {
if (!fatalerrs)
return 1;
SSLfatal(s, SSL_AD_INTERNAL_ERROR,
SSL_R_NO_SUITABLE_SIGNATURE_ALGORITHM);
return 0;
}
}
}
if (sig_idx == -1)
sig_idx = lu->sig_idx;
s->s3.tmp.cert = &s->cert->pkeys[sig_idx];
s->cert->key = s->s3.tmp.cert;
s->s3.tmp.sigalg = lu;
return 1;
}
int SSL_CTX_set_tlsext_max_fragment_length(SSL_CTX *ctx, uint8_t mode)
{
if (mode != TLSEXT_max_fragment_length_DISABLED
&& !IS_MAX_FRAGMENT_LENGTH_EXT_VALID(mode)) {
ERR_raise(ERR_LIB_SSL, SSL_R_SSL3_EXT_INVALID_MAX_FRAGMENT_LENGTH);
return 0;
}
ctx->ext.max_fragment_len_mode = mode;
return 1;
}
int SSL_set_tlsext_max_fragment_length(SSL *ssl, uint8_t mode)
{
if (mode != TLSEXT_max_fragment_length_DISABLED
&& !IS_MAX_FRAGMENT_LENGTH_EXT_VALID(mode)) {
ERR_raise(ERR_LIB_SSL, SSL_R_SSL3_EXT_INVALID_MAX_FRAGMENT_LENGTH);
return 0;
}
ssl->ext.max_fragment_len_mode = mode;
return 1;
}
uint8_t SSL_SESSION_get_max_fragment_length(const SSL_SESSION *session)
{
return session->ext.max_fragment_len_mode;
}
/*
* Helper functions for HMAC access with legacy support included.
*/
SSL_HMAC *ssl_hmac_new(const SSL_CTX *ctx)
{
SSL_HMAC *ret = OPENSSL_zalloc(sizeof(*ret));
EVP_MAC *mac = NULL;
if (ret == NULL)
return NULL;
#ifndef OPENSSL_NO_DEPRECATED_3_0
if (ctx->ext.ticket_key_evp_cb == NULL
&& ctx->ext.ticket_key_cb != NULL) {
if (!ssl_hmac_old_new(ret))
goto err;
return ret;
}
#endif
mac = EVP_MAC_fetch(ctx->libctx, "HMAC", ctx->propq);
if (mac == NULL || (ret->ctx = EVP_MAC_CTX_new(mac)) == NULL)
goto err;
EVP_MAC_free(mac);
return ret;
err:
EVP_MAC_CTX_free(ret->ctx);
EVP_MAC_free(mac);
OPENSSL_free(ret);
return NULL;
}
void ssl_hmac_free(SSL_HMAC *ctx)
{
if (ctx != NULL) {
EVP_MAC_CTX_free(ctx->ctx);
#ifndef OPENSSL_NO_DEPRECATED_3_0
ssl_hmac_old_free(ctx);
#endif
OPENSSL_free(ctx);
}
}
EVP_MAC_CTX *ssl_hmac_get0_EVP_MAC_CTX(SSL_HMAC *ctx)
{
return ctx->ctx;
}
int ssl_hmac_init(SSL_HMAC *ctx, void *key, size_t len, char *md)
{
OSSL_PARAM params[2], *p = params;
if (ctx->ctx != NULL) {
*p++ = OSSL_PARAM_construct_utf8_string(OSSL_MAC_PARAM_DIGEST, md, 0);
*p = OSSL_PARAM_construct_end();
if (EVP_MAC_init(ctx->ctx, key, len, params))
return 1;
}
#ifndef OPENSSL_NO_DEPRECATED_3_0
if (ctx->old_ctx != NULL)
return ssl_hmac_old_init(ctx, key, len, md);
#endif
return 0;
}
int ssl_hmac_update(SSL_HMAC *ctx, const unsigned char *data, size_t len)
{
if (ctx->ctx != NULL)
return EVP_MAC_update(ctx->ctx, data, len);
#ifndef OPENSSL_NO_DEPRECATED_3_0
if (ctx->old_ctx != NULL)
return ssl_hmac_old_update(ctx, data, len);
#endif
return 0;
}
int ssl_hmac_final(SSL_HMAC *ctx, unsigned char *md, size_t *len,
size_t max_size)
{
if (ctx->ctx != NULL)
return EVP_MAC_final(ctx->ctx, md, len, max_size);
#ifndef OPENSSL_NO_DEPRECATED_3_0
if (ctx->old_ctx != NULL)
return ssl_hmac_old_final(ctx, md, len);
#endif
return 0;
}
size_t ssl_hmac_size(const SSL_HMAC *ctx)
{
if (ctx->ctx != NULL)
return EVP_MAC_CTX_get_mac_size(ctx->ctx);
#ifndef OPENSSL_NO_DEPRECATED_3_0
if (ctx->old_ctx != NULL)
return ssl_hmac_old_size(ctx);
#endif
return 0;
}
int ssl_get_EC_curve_nid(const EVP_PKEY *pkey)
{
char gname[OSSL_MAX_NAME_SIZE];
if (EVP_PKEY_get_group_name(pkey, gname, sizeof(gname), NULL) > 0)
return OBJ_txt2nid(gname);
return NID_undef;
}
__owur int tls13_set_encoded_pub_key(EVP_PKEY *pkey,
const unsigned char *enckey,
size_t enckeylen)
{
if (EVP_PKEY_is_a(pkey, "DH")) {
int bits = EVP_PKEY_get_bits(pkey);
if (bits <= 0 || enckeylen != (size_t)bits / 8)
/* the encoded key must be padded to the length of the p */
return 0;
} else if (EVP_PKEY_is_a(pkey, "EC")) {
if (enckeylen < 3 /* point format and at least 1 byte for x and y */
|| enckey[0] != 0x04)
return 0;
}
return EVP_PKEY_set1_encoded_public_key(pkey, enckey, enckeylen);
}
diff --git a/crypto/openssl/test/bad_dtls_test.c b/crypto/openssl/test/bad_dtls_test.c
index e6ee1ea09f6d..dc3d4bc0d750 100644
--- a/crypto/openssl/test/bad_dtls_test.c
+++ b/crypto/openssl/test/bad_dtls_test.c
@@ -1,607 +1,607 @@
/*
- * Copyright 2016-2022 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2016-2024 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
*/
/*
* Unit test for Cisco DTLS1_BAD_VER session resume, as used by
* AnyConnect VPN protocol.
*
* This is designed to exercise the code paths in
* http://git.infradead.org/users/dwmw2/openconnect.git/blob/HEAD:/dtls.c
* which have frequently been affected by regressions in DTLS1_BAD_VER
* support.
*
* Note that unlike other SSL tests, we don't test against our own SSL
* server method. Firstly because we don't have one; we *only* support
* DTLS1_BAD_VER as a client. And secondly because even if that were
* fixed up it's the wrong thing to test against - because if changes
* are made in generic DTLS code which don't take DTLS1_BAD_VER into
* account, there's plenty of scope for making those changes such that
* they break *both* the client and the server in the same way.
*
* So we handle the server side manually. In a session resume there isn't
* much to be done anyway.
*/
#include <string.h>
#include <openssl/core_names.h>
#include <openssl/params.h>
#include <openssl/opensslconf.h>
#include <openssl/bio.h>
#include <openssl/crypto.h>
#include <openssl/evp.h>
#include <openssl/ssl.h>
#include <openssl/err.h>
#include <openssl/rand.h>
#include <openssl/kdf.h>
#include "internal/packet.h"
#include "internal/nelem.h"
#include "testutil.h"
/* For DTLS1_BAD_VER packets the MAC doesn't include the handshake header */
#define MAC_OFFSET (DTLS1_RT_HEADER_LENGTH + DTLS1_HM_HEADER_LENGTH)
static unsigned char client_random[SSL3_RANDOM_SIZE];
static unsigned char server_random[SSL3_RANDOM_SIZE];
/* These are all generated locally, sized purely according to our own whim */
static unsigned char session_id[32];
static unsigned char master_secret[48];
static unsigned char cookie[20];
/* We've hard-coded the cipher suite; we know it's 104 bytes */
static unsigned char key_block[104];
#define mac_key (key_block + 20)
#define dec_key (key_block + 40)
#define enc_key (key_block + 56)
static EVP_MD_CTX *handshake_md;
static int do_PRF(const void *seed1, int seed1_len,
const void *seed2, int seed2_len,
const void *seed3, int seed3_len,
unsigned char *out, int olen)
{
EVP_PKEY_CTX *pctx = EVP_PKEY_CTX_new_id(EVP_PKEY_TLS1_PRF, NULL);
size_t outlen = olen;
/* No error handling. If it all screws up, the test will fail anyway */
EVP_PKEY_derive_init(pctx);
EVP_PKEY_CTX_set_tls1_prf_md(pctx, EVP_md5_sha1());
EVP_PKEY_CTX_set1_tls1_prf_secret(pctx, master_secret, sizeof(master_secret));
EVP_PKEY_CTX_add1_tls1_prf_seed(pctx, seed1, seed1_len);
EVP_PKEY_CTX_add1_tls1_prf_seed(pctx, seed2, seed2_len);
EVP_PKEY_CTX_add1_tls1_prf_seed(pctx, seed3, seed3_len);
EVP_PKEY_derive(pctx, out, &outlen);
EVP_PKEY_CTX_free(pctx);
return 1;
}
static SSL_SESSION *client_session(void)
{
static unsigned char session_asn1[] = {
0x30, 0x5F, /* SEQUENCE, length 0x5F */
0x02, 0x01, 0x01, /* INTEGER, SSL_SESSION_ASN1_VERSION */
0x02, 0x02, 0x01, 0x00, /* INTEGER, DTLS1_BAD_VER */
0x04, 0x02, 0x00, 0x2F, /* OCTET_STRING, AES128-SHA */
0x04, 0x20, /* OCTET_STRING, session id */
#define SS_SESSID_OFS 15 /* Session ID goes here */
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,
0x04, 0x30, /* OCTET_STRING, master secret */
#define SS_SECRET_OFS 49 /* Master secret goes here */
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,
};
const unsigned char *p = session_asn1;
/* Copy the randomly-generated fields into the above ASN1 */
memcpy(session_asn1 + SS_SESSID_OFS, session_id, sizeof(session_id));
memcpy(session_asn1 + SS_SECRET_OFS, master_secret, sizeof(master_secret));
return d2i_SSL_SESSION(NULL, &p, sizeof(session_asn1));
}
/* Returns 1 for initial ClientHello, 2 for ClientHello with cookie */
static int validate_client_hello(BIO *wbio)
{
PACKET pkt, pkt2;
long len;
unsigned char *data;
int cookie_found = 0;
unsigned int u = 0;
if ((len = BIO_get_mem_data(wbio, (char **)&data)) < 0)
return 0;
if (!PACKET_buf_init(&pkt, data, len))
return 0;
/* Check record header type */
if (!PACKET_get_1(&pkt, &u) || u != SSL3_RT_HANDSHAKE)
return 0;
/* Version */
if (!PACKET_get_net_2(&pkt, &u) || u != DTLS1_BAD_VER)
return 0;
/* Skip the rest of the record header */
if (!PACKET_forward(&pkt, DTLS1_RT_HEADER_LENGTH - 3))
return 0;
/* Check it's a ClientHello */
if (!PACKET_get_1(&pkt, &u) || u != SSL3_MT_CLIENT_HELLO)
return 0;
/* Skip the rest of the handshake message header */
if (!PACKET_forward(&pkt, DTLS1_HM_HEADER_LENGTH - 1))
return 0;
/* Check client version */
if (!PACKET_get_net_2(&pkt, &u) || u != DTLS1_BAD_VER)
return 0;
/* Store random */
if (!PACKET_copy_bytes(&pkt, client_random, SSL3_RANDOM_SIZE))
return 0;
/* Check session id length and content */
if (!PACKET_get_length_prefixed_1(&pkt, &pkt2) ||
!PACKET_equal(&pkt2, session_id, sizeof(session_id)))
return 0;
/* Check cookie */
if (!PACKET_get_length_prefixed_1(&pkt, &pkt2))
return 0;
if (PACKET_remaining(&pkt2)) {
if (!PACKET_equal(&pkt2, cookie, sizeof(cookie)))
return 0;
cookie_found = 1;
}
/* Skip ciphers */
if (!PACKET_get_net_2(&pkt, &u) || !PACKET_forward(&pkt, u))
return 0;
/* Skip compression */
if (!PACKET_get_1(&pkt, &u) || !PACKET_forward(&pkt, u))
return 0;
/* Skip extensions */
if (!PACKET_get_net_2(&pkt, &u) || !PACKET_forward(&pkt, u))
return 0;
/* Now we are at the end */
if (PACKET_remaining(&pkt))
return 0;
/* Update handshake MAC for second ClientHello (with cookie) */
if (cookie_found && !EVP_DigestUpdate(handshake_md, data + MAC_OFFSET,
len - MAC_OFFSET))
return 0;
(void)BIO_reset(wbio);
return 1 + cookie_found;
}
static int send_hello_verify(BIO *rbio)
{
static unsigned char hello_verify[] = {
0x16, /* Handshake */
0x01, 0x00, /* DTLS1_BAD_VER */
0x00, 0x00, /* Epoch 0 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* Seq# 0 */
0x00, 0x23, /* Length */
0x03, /* Hello Verify */
0x00, 0x00, 0x17, /* Length */
0x00, 0x00, /* Seq# 0 */
0x00, 0x00, 0x00, /* Fragment offset */
0x00, 0x00, 0x17, /* Fragment length */
0x01, 0x00, /* DTLS1_BAD_VER */
0x14, /* Cookie length */
#define HV_COOKIE_OFS 28 /* Cookie goes here */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
};
memcpy(hello_verify + HV_COOKIE_OFS, cookie, sizeof(cookie));
BIO_write(rbio, hello_verify, sizeof(hello_verify));
return 1;
}
static int send_server_hello(BIO *rbio)
{
static unsigned char server_hello[] = {
0x16, /* Handshake */
0x01, 0x00, /* DTLS1_BAD_VER */
0x00, 0x00, /* Epoch 0 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x01, /* Seq# 1 */
0x00, 0x52, /* Length */
0x02, /* Server Hello */
0x00, 0x00, 0x46, /* Length */
0x00, 0x01, /* Seq# */
0x00, 0x00, 0x00, /* Fragment offset */
0x00, 0x00, 0x46, /* Fragment length */
0x01, 0x00, /* DTLS1_BAD_VER */
#define SH_RANDOM_OFS 27 /* Server random goes here */
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,
0x20, /* Session ID length */
#define SH_SESSID_OFS 60 /* Session ID goes here */
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, 0x2f, /* Cipher suite AES128-SHA */
0x00, /* Compression null */
};
static unsigned char change_cipher_spec[] = {
0x14, /* Change Cipher Spec */
0x01, 0x00, /* DTLS1_BAD_VER */
0x00, 0x00, /* Epoch 0 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x02, /* Seq# 2 */
0x00, 0x03, /* Length */
0x01, 0x00, 0x02, /* Message */
};
memcpy(server_hello + SH_RANDOM_OFS, server_random, sizeof(server_random));
memcpy(server_hello + SH_SESSID_OFS, session_id, sizeof(session_id));
if (!EVP_DigestUpdate(handshake_md, server_hello + MAC_OFFSET,
sizeof(server_hello) - MAC_OFFSET))
return 0;
BIO_write(rbio, server_hello, sizeof(server_hello));
BIO_write(rbio, change_cipher_spec, sizeof(change_cipher_spec));
return 1;
}
/* Create header, HMAC, pad, encrypt and send a record */
static int send_record(BIO *rbio, unsigned char type, uint64_t seqnr,
const void *msg, size_t len)
{
/* Note that the order of the record header fields on the wire,
* and in the HMAC, is different. So we just keep them in separate
* variables and handle them individually. */
static unsigned char epoch[2] = { 0x00, 0x01 };
static unsigned char seq[6] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
static unsigned char ver[2] = { 0x01, 0x00 }; /* DTLS1_BAD_VER */
unsigned char lenbytes[2];
EVP_MAC *hmac = NULL;
EVP_MAC_CTX *ctx = NULL;
EVP_CIPHER_CTX *enc_ctx = NULL;
unsigned char iv[16];
unsigned char pad;
unsigned char *enc;
OSSL_PARAM params[2];
int ret = 0;
seq[0] = (seqnr >> 40) & 0xff;
seq[1] = (seqnr >> 32) & 0xff;
seq[2] = (seqnr >> 24) & 0xff;
seq[3] = (seqnr >> 16) & 0xff;
seq[4] = (seqnr >> 8) & 0xff;
seq[5] = seqnr & 0xff;
pad = 15 - ((len + SHA_DIGEST_LENGTH) % 16);
enc = OPENSSL_malloc(len + SHA_DIGEST_LENGTH + 1 + pad);
if (enc == NULL)
return 0;
/* Copy record to encryption buffer */
memcpy(enc, msg, len);
/* Append HMAC to data */
if (!TEST_ptr(hmac = EVP_MAC_fetch(NULL, "HMAC", NULL))
|| !TEST_ptr(ctx = EVP_MAC_CTX_new(hmac)))
goto end;
params[0] = OSSL_PARAM_construct_utf8_string(OSSL_MAC_PARAM_DIGEST,
"SHA1", 0);
params[1] = OSSL_PARAM_construct_end();
lenbytes[0] = (unsigned char)(len >> 8);
lenbytes[1] = (unsigned char)(len);
if (!EVP_MAC_init(ctx, mac_key, 20, params)
|| !EVP_MAC_update(ctx, epoch, 2)
|| !EVP_MAC_update(ctx, seq, 6)
|| !EVP_MAC_update(ctx, &type, 1)
|| !EVP_MAC_update(ctx, ver, 2) /* Version */
|| !EVP_MAC_update(ctx, lenbytes, 2) /* Length */
|| !EVP_MAC_update(ctx, enc, len) /* Finally the data itself */
|| !EVP_MAC_final(ctx, enc + len, NULL, SHA_DIGEST_LENGTH))
goto end;
/* Append padding bytes */
len += SHA_DIGEST_LENGTH;
do {
enc[len++] = pad;
} while (len % 16);
/* Generate IV, and encrypt */
if (!TEST_int_gt(RAND_bytes(iv, sizeof(iv)), 0)
|| !TEST_ptr(enc_ctx = EVP_CIPHER_CTX_new())
|| !TEST_true(EVP_CipherInit_ex(enc_ctx, EVP_aes_128_cbc(), NULL,
enc_key, iv, 1))
|| !TEST_int_ge(EVP_Cipher(enc_ctx, enc, enc, len), 0))
goto end;
/* Finally write header (from fragmented variables), IV and encrypted record */
BIO_write(rbio, &type, 1);
BIO_write(rbio, ver, 2);
BIO_write(rbio, epoch, 2);
BIO_write(rbio, seq, 6);
lenbytes[0] = (unsigned char)((len + sizeof(iv)) >> 8);
lenbytes[1] = (unsigned char)(len + sizeof(iv));
BIO_write(rbio, lenbytes, 2);
BIO_write(rbio, iv, sizeof(iv));
BIO_write(rbio, enc, len);
ret = 1;
end:
EVP_MAC_free(hmac);
EVP_MAC_CTX_free(ctx);
EVP_CIPHER_CTX_free(enc_ctx);
OPENSSL_free(enc);
return ret;
}
static int send_finished(SSL *s, BIO *rbio)
{
static unsigned char finished_msg[DTLS1_HM_HEADER_LENGTH +
TLS1_FINISH_MAC_LENGTH] = {
0x14, /* Finished */
0x00, 0x00, 0x0c, /* Length */
0x00, 0x03, /* Seq# 3 */
0x00, 0x00, 0x00, /* Fragment offset */
0x00, 0x00, 0x0c, /* Fragment length */
/* Finished MAC (12 bytes) */
};
unsigned char handshake_hash[EVP_MAX_MD_SIZE];
/* Derive key material */
do_PRF(TLS_MD_KEY_EXPANSION_CONST, TLS_MD_KEY_EXPANSION_CONST_SIZE,
server_random, SSL3_RANDOM_SIZE,
client_random, SSL3_RANDOM_SIZE,
key_block, sizeof(key_block));
/* Generate Finished MAC */
if (!EVP_DigestFinal_ex(handshake_md, handshake_hash, NULL))
return 0;
do_PRF(TLS_MD_SERVER_FINISH_CONST, TLS_MD_SERVER_FINISH_CONST_SIZE,
handshake_hash, EVP_MD_CTX_get_size(handshake_md),
NULL, 0,
finished_msg + DTLS1_HM_HEADER_LENGTH, TLS1_FINISH_MAC_LENGTH);
return send_record(rbio, SSL3_RT_HANDSHAKE, 0,
finished_msg, sizeof(finished_msg));
}
static int validate_ccs(BIO *wbio)
{
PACKET pkt;
long len;
unsigned char *data;
unsigned int u;
len = BIO_get_mem_data(wbio, (char **)&data);
if (len < 0)
return 0;
if (!PACKET_buf_init(&pkt, data, len))
return 0;
/* Check record header type */
if (!PACKET_get_1(&pkt, &u) || u != SSL3_RT_CHANGE_CIPHER_SPEC)
return 0;
/* Version */
if (!PACKET_get_net_2(&pkt, &u) || u != DTLS1_BAD_VER)
return 0;
/* Skip the rest of the record header */
if (!PACKET_forward(&pkt, DTLS1_RT_HEADER_LENGTH - 3))
return 0;
/* Check ChangeCipherSpec message */
if (!PACKET_get_1(&pkt, &u) || u != SSL3_MT_CCS)
return 0;
/* A DTLS1_BAD_VER ChangeCipherSpec also contains the
* handshake sequence number (which is 2 here) */
if (!PACKET_get_net_2(&pkt, &u) || u != 0x0002)
return 0;
/* Now check the Finished packet */
if (!PACKET_get_1(&pkt, &u) || u != SSL3_RT_HANDSHAKE)
return 0;
if (!PACKET_get_net_2(&pkt, &u) || u != DTLS1_BAD_VER)
return 0;
/* Check epoch is now 1 */
if (!PACKET_get_net_2(&pkt, &u) || u != 0x0001)
return 0;
/* That'll do for now. If OpenSSL accepted *our* Finished packet
* then it's evidently remembered that DTLS1_BAD_VER doesn't
* include the handshake header in the MAC. There's not a lot of
* point in implementing decryption here, just to check that it
* continues to get it right for one more packet. */
return 1;
}
#define NODROP(x) { x##UL, 0 }
#define DROP(x) { x##UL, 1 }
static struct {
uint64_t seq;
int drop;
} tests[] = {
NODROP(1), NODROP(3), NODROP(2),
NODROP(0x1234), NODROP(0x1230), NODROP(0x1235),
NODROP(0xffff), NODROP(0x10001), NODROP(0xfffe), NODROP(0x10000),
DROP(0x10001), DROP(0xff), NODROP(0x100000), NODROP(0x800000), NODROP(0x7fffe1),
NODROP(0xffffff), NODROP(0x1000000), NODROP(0xfffffe), DROP(0xffffff), NODROP(0x1000010),
NODROP(0xfffffd), NODROP(0x1000011), DROP(0x12), NODROP(0x1000012),
NODROP(0x1ffffff), NODROP(0x2000000), DROP(0x1ff00fe), NODROP(0x2000001),
NODROP(0x20fffff), NODROP(0x2105500), DROP(0x20ffffe), NODROP(0x21054ff),
NODROP(0x211ffff), DROP(0x2110000), NODROP(0x2120000)
/* The last test should be NODROP, because a DROP wouldn't get tested. */
};
static int test_bad_dtls(void)
{
SSL_SESSION *sess = NULL;
SSL_CTX *ctx = NULL;
SSL *con = NULL;
BIO *rbio = NULL;
BIO *wbio = NULL;
time_t now = 0;
int testresult = 0;
int ret;
int i;
RAND_bytes(session_id, sizeof(session_id));
RAND_bytes(master_secret, sizeof(master_secret));
RAND_bytes(cookie, sizeof(cookie));
RAND_bytes(server_random + 4, sizeof(server_random) - 4);
now = time(NULL);
memcpy(server_random, &now, sizeof(now));
sess = client_session();
if (!TEST_ptr(sess))
goto end;
handshake_md = EVP_MD_CTX_new();
if (!TEST_ptr(handshake_md)
|| !TEST_true(EVP_DigestInit_ex(handshake_md, EVP_md5_sha1(),
NULL)))
goto end;
ctx = SSL_CTX_new(DTLS_client_method());
if (!TEST_ptr(ctx)
|| !TEST_true(SSL_CTX_set_min_proto_version(ctx, DTLS1_BAD_VER))
|| !TEST_true(SSL_CTX_set_max_proto_version(ctx, DTLS1_BAD_VER))
|| !TEST_true(SSL_CTX_set_options(ctx,
SSL_OP_LEGACY_SERVER_CONNECT))
|| !TEST_true(SSL_CTX_set_cipher_list(ctx, "AES128-SHA")))
goto end;
con = SSL_new(ctx);
if (!TEST_ptr(con)
|| !TEST_true(SSL_set_session(con, sess)))
goto end;
- SSL_SESSION_free(sess);
rbio = BIO_new(BIO_s_mem());
wbio = BIO_new(BIO_s_mem());
if (!TEST_ptr(rbio)
|| !TEST_ptr(wbio))
goto end;
SSL_set_bio(con, rbio, wbio);
if (!TEST_true(BIO_up_ref(rbio))) {
/*
* We can't up-ref but we assigned ownership to con, so we shouldn't
* free in the "end" block
*/
rbio = wbio = NULL;
goto end;
}
if (!TEST_true(BIO_up_ref(wbio))) {
wbio = NULL;
goto end;
}
SSL_set_connect_state(con);
/* Send initial ClientHello */
ret = SSL_do_handshake(con);
if (!TEST_int_le(ret, 0)
|| !TEST_int_eq(SSL_get_error(con, ret), SSL_ERROR_WANT_READ)
|| !TEST_int_eq(validate_client_hello(wbio), 1)
|| !TEST_true(send_hello_verify(rbio)))
goto end;
ret = SSL_do_handshake(con);
if (!TEST_int_le(ret, 0)
|| !TEST_int_eq(SSL_get_error(con, ret), SSL_ERROR_WANT_READ)
|| !TEST_int_eq(validate_client_hello(wbio), 2)
|| !TEST_true(send_server_hello(rbio)))
goto end;
ret = SSL_do_handshake(con);
if (!TEST_int_le(ret, 0)
|| !TEST_int_eq(SSL_get_error(con, ret), SSL_ERROR_WANT_READ)
|| !TEST_true(send_finished(con, rbio)))
goto end;
ret = SSL_do_handshake(con);
if (!TEST_int_gt(ret, 0)
|| !TEST_true(validate_ccs(wbio)))
goto end;
/* While we're here and crafting packets by hand, we might as well do a
bit of a stress test on the DTLS record replay handling. Not Cisco-DTLS
specific but useful anyway for the general case. It's been broken
before, and in fact was broken even for a basic 0, 2, 1 test case
when this test was first added.... */
for (i = 0; i < (int)OSSL_NELEM(tests); i++) {
uint64_t recv_buf[2];
if (!TEST_true(send_record(rbio, SSL3_RT_APPLICATION_DATA, tests[i].seq,
&tests[i].seq, sizeof(uint64_t)))) {
TEST_error("Failed to send data seq #0x%x%08x (%d)\n",
(unsigned int)(tests[i].seq >> 32), (unsigned int)tests[i].seq, i);
goto end;
}
if (tests[i].drop)
continue;
ret = SSL_read(con, recv_buf, 2 * sizeof(uint64_t));
if (!TEST_int_eq(ret, (int)sizeof(uint64_t))) {
TEST_error("SSL_read failed or wrong size on seq#0x%x%08x (%d)\n",
(unsigned int)(tests[i].seq >> 32), (unsigned int)tests[i].seq, i);
goto end;
}
if (!TEST_true(recv_buf[0] == tests[i].seq))
goto end;
}
/* The last test cannot be DROP() */
if (!TEST_false(tests[i-1].drop))
goto end;
testresult = 1;
end:
+ SSL_SESSION_free(sess);
BIO_free(rbio);
BIO_free(wbio);
SSL_free(con);
SSL_CTX_free(ctx);
EVP_MD_CTX_free(handshake_md);
return testresult;
}
int setup_tests(void)
{
ADD_TEST(test_bad_dtls);
return 1;
}
diff --git a/crypto/openssl/test/build.info b/crypto/openssl/test/build.info
index 416c2270771a..25ab0430b731 100644
--- a/crypto/openssl/test/build.info
+++ b/crypto/openssl/test/build.info
@@ -1,976 +1,977 @@
# 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.
#
# 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 $LIBAPPSSRC
INCLUDE[libtestutil.a]=../include ../apps/include ..
DEPEND[libtestutil.a]=../libcrypto
PROGRAMS{noinst}= \
confdump \
versions \
aborttest test_test pkcs12_format_test \
sanitytest 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 punycode_test \
crltest danetest bad_dtls_test lhash_test sparse_array_test \
conf_include_test params_api_test params_conversion_test \
constant_time_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 param_build_test \
bioprinttest sslapitest dtlstest sslcorrupttest \
bio_enc_test pkey_meth_test pkey_meth_kdf_test evp_kdf_test uitest \
cipherbytes_test threadstest_fips \
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 \
http_test servername_test ocspapitest fatalerrtest tls13ccstest \
sysdefaulttest errtest ssl_ctx_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 fips_version_test \
nodefltctxtest
IF[{- !$disabled{'deprecated-3.0'} -}]
PROGRAMS{noinst}=enginetest
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 libtestutil.a
SOURCE[rand_test]=rand_test.c
INCLUDE[rand_test]=../include ../apps/include
DEPEND[rand_test]=../libcrypto 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
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
INCLUDE[evp_extra_test]=../include ../apps/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
INCLUDE[evp_extra_test]=../providers/common/include \
../providers/implementations/include
DEPEND[evp_extra_test]=../providers/liblegacy.a \
../providers/libcommon.a
ENDIF
SOURCE[evp_extra_test2]=evp_extra_test2.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[nodefltctxtest]=nodefltctxtest.c
INCLUDE[nodefltctxtest]=../include ../apps/include
DEPEND[nodefltctxtest]=../libcrypto.a libtestutil.a
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
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[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
INCLUDE[packettest]=../include ../apps/include
DEPEND[packettest]=../libcrypto libtestutil.a
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[pkcs7_test]=pkcs7_test.c
INCLUDE[pkcs7_test]=../include ../apps/include
DEPEND[pkcs7_test]=../libcrypto libtestutil.a
SOURCE[punycode_test]=punycode_test.c
INCLUDE[punycode_test]=../include ../apps/include
DEPEND[punycode_test]=../libcrypto.a 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 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[threadstest]=threadstest.c
INCLUDE[threadstest]=../include ../apps/include
DEPEND[threadstest]=../libcrypto 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[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[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 ..
DEPEND[sslapitest]=../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} -}]
PROGRAMS{noinst}=http_test
ENDIF
SOURCE[http_test]=http_test.c
INCLUDE[http_test]=../include ../apps/include
DEPEND[http_test]=../libcrypto libtestutil.a
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_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_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[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
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_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[http_test]=http_test.c
INCLUDE[http_test]=../include ../apps/include
DEPEND[http_test]=../libcrypto 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
# 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 \
rdrand_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 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
SOURCE[dhtest]=dhtest.c
INCLUDE[dhtest]=../include ../apps/include
DEPEND[dhtest]=../libcrypto.a 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
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
SOURCE[rc4test]=rc4test.c
INCLUDE[rc4test]=../include ../apps/include
DEPEND[rc4test]=../libcrypto.a libtestutil.a
SOURCE[rdrand_sanitytest]=rdrand_sanitytest.c
INCLUDE[rdrand_sanitytest]=../include ../apps/include
DEPEND[rdrand_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
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
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
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
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
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}=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{'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}=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
{-
use File::Spec::Functions;
use File::Basename;
use OpenSSL::Glob;
my @nogo_headers = ( "asn1_mac.h",
"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/crypto/openssl/test/cmp_hdr_test.c b/crypto/openssl/test/cmp_hdr_test.c
index ed49a0bb6199..e2bd210118d8 100644
--- a/crypto/openssl/test/cmp_hdr_test.c
+++ b/crypto/openssl/test/cmp_hdr_test.c
@@ -1,494 +1,509 @@
/*
- * Copyright 2007-2023 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2007-2024 The OpenSSL Project Authors. All Rights Reserved.
* Copyright Nokia 2007-2019
* Copyright Siemens AG 2015-2019
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include "helpers/cmp_testlib.h"
static unsigned char rand_data[OSSL_CMP_TRANSACTIONID_LENGTH];
typedef struct test_fixture {
const char *test_case_name;
int expected;
OSSL_CMP_CTX *cmp_ctx;
OSSL_CMP_PKIHEADER *hdr;
} CMP_HDR_TEST_FIXTURE;
static void tear_down(CMP_HDR_TEST_FIXTURE *fixture)
{
OSSL_CMP_PKIHEADER_free(fixture->hdr);
OSSL_CMP_CTX_free(fixture->cmp_ctx);
OPENSSL_free(fixture);
}
static CMP_HDR_TEST_FIXTURE *set_up(const char *const test_case_name)
{
CMP_HDR_TEST_FIXTURE *fixture;
if (!TEST_ptr(fixture = OPENSSL_zalloc(sizeof(*fixture))))
return NULL;
fixture->test_case_name = test_case_name;
if (!TEST_ptr(fixture->cmp_ctx = OSSL_CMP_CTX_new(NULL, NULL)))
goto err;
if (!TEST_ptr(fixture->hdr = OSSL_CMP_PKIHEADER_new()))
goto err;
return fixture;
err:
tear_down(fixture);
return NULL;
}
static int execute_HDR_set_get_pvno_test(CMP_HDR_TEST_FIXTURE *fixture)
{
int pvno = 77;
if (!TEST_int_eq(ossl_cmp_hdr_set_pvno(fixture->hdr, pvno), 1))
return 0;
if (!TEST_int_eq(ossl_cmp_hdr_get_pvno(fixture->hdr), pvno))
return 0;
return 1;
}
static int test_HDR_set_get_pvno(void)
{
SETUP_TEST_FIXTURE(CMP_HDR_TEST_FIXTURE, set_up);
fixture->expected = 1;
EXECUTE_TEST(execute_HDR_set_get_pvno_test, tear_down);
return result;
}
#define X509_NAME_ADD(n, rd, s) \
X509_NAME_add_entry_by_txt((n), (rd), MBSTRING_ASC, (unsigned char *)(s), \
-1, -1, 0)
static int execute_HDR_get0_senderNonce_test(CMP_HDR_TEST_FIXTURE *fixture)
{
+ int res = 0;
X509_NAME *sender = X509_NAME_new();
ASN1_OCTET_STRING *sn;
if (!TEST_ptr(sender))
- return 0;
+ goto err;
X509_NAME_ADD(sender, "CN", "A common sender name");
if (!TEST_int_eq(OSSL_CMP_CTX_set1_subjectName(fixture->cmp_ctx, sender),
1))
- return 0;
+ goto err;
if (!TEST_int_eq(ossl_cmp_hdr_init(fixture->cmp_ctx, fixture->hdr),
1))
- return 0;
+ goto err;
sn = ossl_cmp_hdr_get0_senderNonce(fixture->hdr);
if (!TEST_int_eq(ASN1_OCTET_STRING_cmp(fixture->cmp_ctx->senderNonce, sn),
0))
- return 0;
+ goto err;
+
+ res = 1;
+err:
X509_NAME_free(sender);
- return 1;
+
+ return res;
}
static int test_HDR_get0_senderNonce(void)
{
SETUP_TEST_FIXTURE(CMP_HDR_TEST_FIXTURE, set_up);
fixture->expected = 1;
EXECUTE_TEST(execute_HDR_get0_senderNonce_test, tear_down);
return result;
}
static int execute_HDR_set1_sender_test(CMP_HDR_TEST_FIXTURE *fixture)
{
+ int res = 0;
X509_NAME *x509name = X509_NAME_new();
if (!TEST_ptr(x509name))
- return 0;
+ goto err;
X509_NAME_ADD(x509name, "CN", "A common sender name");
if (!TEST_int_eq(ossl_cmp_hdr_set1_sender(fixture->hdr, x509name), 1))
- return 0;
+ goto err;
+
if (!TEST_int_eq(fixture->hdr->sender->type, GEN_DIRNAME))
- return 0;
+ goto err;
if (!TEST_int_eq(X509_NAME_cmp(fixture->hdr->sender->d.directoryName,
x509name), 0))
- return 0;
+ goto err;
+ res = 1;
+err:
X509_NAME_free(x509name);
- return 1;
+
+ return res;
}
static int test_HDR_set1_sender(void)
{
SETUP_TEST_FIXTURE(CMP_HDR_TEST_FIXTURE, set_up);
fixture->expected = 1;
EXECUTE_TEST(execute_HDR_set1_sender_test, tear_down);
return result;
}
static int execute_HDR_set1_recipient_test(CMP_HDR_TEST_FIXTURE *fixture)
{
+ int res = 0;
X509_NAME *x509name = X509_NAME_new();
if (!TEST_ptr(x509name))
- return 0;
+ goto err;
X509_NAME_ADD(x509name, "CN", "A common recipient name");
if (!TEST_int_eq(ossl_cmp_hdr_set1_recipient(fixture->hdr, x509name), 1))
- return 0;
+ goto err;
if (!TEST_int_eq(fixture->hdr->recipient->type, GEN_DIRNAME))
- return 0;
+ goto err;
if (!TEST_int_eq(X509_NAME_cmp(fixture->hdr->recipient->d.directoryName,
x509name), 0))
- return 0;
+ goto err;
+ res = 1;
+err:
X509_NAME_free(x509name);
- return 1;
+
+ return res;
}
static int test_HDR_set1_recipient(void)
{
SETUP_TEST_FIXTURE(CMP_HDR_TEST_FIXTURE, set_up);
fixture->expected = 1;
EXECUTE_TEST(execute_HDR_set1_recipient_test, tear_down);
return result;
}
static int execute_HDR_update_messageTime_test(CMP_HDR_TEST_FIXTURE *fixture)
{
struct tm hdrtm, tmptm;
time_t hdrtime, before, after, now;
now = time(NULL);
/*
* Trial and error reveals that passing the return value from gmtime
* directly to mktime in a mingw 32 bit build gives unexpected results. To
* work around this we take a copy of the return value first.
*/
tmptm = *gmtime(&now);
before = mktime(&tmptm);
if (!TEST_true(ossl_cmp_hdr_update_messageTime(fixture->hdr)))
return 0;
if (!TEST_true(ASN1_TIME_to_tm(fixture->hdr->messageTime, &hdrtm)))
return 0;
hdrtime = mktime(&hdrtm);
if (!TEST_time_t_le(before, hdrtime))
return 0;
now = time(NULL);
tmptm = *gmtime(&now);
after = mktime(&tmptm);
return TEST_time_t_le(hdrtime, after);
}
static int test_HDR_update_messageTime(void)
{
SETUP_TEST_FIXTURE(CMP_HDR_TEST_FIXTURE, set_up);
fixture->expected = 1;
EXECUTE_TEST(execute_HDR_update_messageTime_test, tear_down);
return result;
}
static int execute_HDR_set1_senderKID_test(CMP_HDR_TEST_FIXTURE *fixture)
{
ASN1_OCTET_STRING *senderKID = ASN1_OCTET_STRING_new();
int res = 0;
if (!TEST_ptr(senderKID))
- return 0;
+ goto err;
if (!TEST_int_eq(ASN1_OCTET_STRING_set(senderKID, rand_data,
sizeof(rand_data)), 1))
goto err;
if (!TEST_int_eq(ossl_cmp_hdr_set1_senderKID(fixture->hdr, senderKID), 1))
goto err;
if (!TEST_int_eq(ASN1_OCTET_STRING_cmp(fixture->hdr->senderKID,
senderKID), 0))
goto err;
res = 1;
err:
ASN1_OCTET_STRING_free(senderKID);
return res;
}
static int test_HDR_set1_senderKID(void)
{
SETUP_TEST_FIXTURE(CMP_HDR_TEST_FIXTURE, set_up);
fixture->expected = 1;
EXECUTE_TEST(execute_HDR_set1_senderKID_test, tear_down);
return result;
}
static int execute_HDR_push0_freeText_test(CMP_HDR_TEST_FIXTURE *fixture)
{
ASN1_UTF8STRING *text = ASN1_UTF8STRING_new();
if (!TEST_ptr(text))
return 0;
if (!ASN1_STRING_set(text, "A free text", -1))
goto err;
if (!TEST_int_eq(ossl_cmp_hdr_push0_freeText(fixture->hdr, text), 1))
goto err;
if (!TEST_true(text == sk_ASN1_UTF8STRING_value(fixture->hdr->freeText, 0)))
goto err;
return 1;
err:
ASN1_UTF8STRING_free(text);
return 0;
}
static int test_HDR_push0_freeText(void)
{
SETUP_TEST_FIXTURE(CMP_HDR_TEST_FIXTURE, set_up);
fixture->expected = 1;
EXECUTE_TEST(execute_HDR_push0_freeText_test, tear_down);
return result;
}
static int execute_HDR_push1_freeText_test(CMP_HDR_TEST_FIXTURE *fixture)
{
ASN1_UTF8STRING *text = ASN1_UTF8STRING_new();
ASN1_UTF8STRING *pushed_text;
int res = 0;
if (!TEST_ptr(text))
- return 0;
+ goto err;
if (!ASN1_STRING_set(text, "A free text", -1))
goto err;
if (!TEST_int_eq(ossl_cmp_hdr_push1_freeText(fixture->hdr, text), 1))
goto err;
pushed_text = sk_ASN1_UTF8STRING_value(fixture->hdr->freeText, 0);
if (!TEST_int_eq(ASN1_STRING_cmp(text, pushed_text), 0))
goto err;
res = 1;
err:
ASN1_UTF8STRING_free(text);
+
return res;
}
static int test_HDR_push1_freeText(void)
{
SETUP_TEST_FIXTURE(CMP_HDR_TEST_FIXTURE, set_up);
fixture->expected = 1;
EXECUTE_TEST(execute_HDR_push1_freeText_test, tear_down);
return result;
}
static int
execute_HDR_generalInfo_push0_item_test(CMP_HDR_TEST_FIXTURE *fixture)
{
OSSL_CMP_ITAV *itav = OSSL_CMP_ITAV_new();
if (!TEST_ptr(itav))
return 0;
if (!TEST_int_eq(ossl_cmp_hdr_generalInfo_push0_item(fixture->hdr, itav),
1))
return 0;
if (!TEST_true(itav == sk_OSSL_CMP_ITAV_value(fixture->hdr->generalInfo,
0)))
return 0;
return 1;
}
static int test_HDR_generalInfo_push0_item(void)
{
SETUP_TEST_FIXTURE(CMP_HDR_TEST_FIXTURE, set_up);
fixture->expected = 1;
EXECUTE_TEST(execute_HDR_generalInfo_push0_item_test, tear_down);
return result;
}
static int
execute_HDR_generalInfo_push1_items_test(CMP_HDR_TEST_FIXTURE *fixture)
{
const char oid[] = "1.2.3.4";
char buf[20];
OSSL_CMP_ITAV *itav, *pushed_itav;
STACK_OF(OSSL_CMP_ITAV) *itavs = NULL, *ginfo;
ASN1_INTEGER *asn1int = ASN1_INTEGER_new();
ASN1_TYPE *val = ASN1_TYPE_new();
ASN1_TYPE *pushed_val;
int res = 0;
if (!TEST_ptr(asn1int))
return 0;
if (!TEST_ptr(val)
|| !TEST_true(ASN1_INTEGER_set(asn1int, 88))) {
ASN1_INTEGER_free(asn1int);
return 0;
}
ASN1_TYPE_set(val, V_ASN1_INTEGER, asn1int);
if (!TEST_ptr(itav = OSSL_CMP_ITAV_create(OBJ_txt2obj(oid, 1), val))) {
ASN1_TYPE_free(val);
return 0;
}
if (!TEST_true(OSSL_CMP_ITAV_push0_stack_item(&itavs, itav))) {
OSSL_CMP_ITAV_free(itav);
return 0;
}
if (!TEST_int_eq(ossl_cmp_hdr_generalInfo_push1_items(fixture->hdr, itavs),
1))
goto err;
ginfo = fixture->hdr->generalInfo;
pushed_itav = sk_OSSL_CMP_ITAV_value(ginfo, 0);
OBJ_obj2txt(buf, sizeof(buf), OSSL_CMP_ITAV_get0_type(pushed_itav), 0);
if (!TEST_int_eq(memcmp(oid, buf, sizeof(oid)), 0))
goto err;
pushed_val = OSSL_CMP_ITAV_get0_value(sk_OSSL_CMP_ITAV_value(ginfo, 0));
if (!TEST_int_eq(ASN1_TYPE_cmp(itav->infoValue.other, pushed_val), 0))
goto err;
res = 1;
err:
sk_OSSL_CMP_ITAV_pop_free(itavs, OSSL_CMP_ITAV_free);
return res;
}
static int test_HDR_generalInfo_push1_items(void)
{
SETUP_TEST_FIXTURE(CMP_HDR_TEST_FIXTURE, set_up);
fixture->expected = 1;
EXECUTE_TEST(execute_HDR_generalInfo_push1_items_test, tear_down);
return result;
}
static int
execute_HDR_set_and_check_implicitConfirm_test(CMP_HDR_TEST_FIXTURE
* fixture)
{
return TEST_false(ossl_cmp_hdr_has_implicitConfirm(fixture->hdr))
&& TEST_true(ossl_cmp_hdr_set_implicitConfirm(fixture->hdr))
&& TEST_true(ossl_cmp_hdr_has_implicitConfirm(fixture->hdr));
}
static int test_HDR_set_and_check_implicit_confirm(void)
{
SETUP_TEST_FIXTURE(CMP_HDR_TEST_FIXTURE, set_up);
EXECUTE_TEST(execute_HDR_set_and_check_implicitConfirm_test, tear_down);
return result;
}
static int execute_HDR_init_test(CMP_HDR_TEST_FIXTURE *fixture)
{
ASN1_OCTET_STRING *header_nonce, *header_transactionID;
ASN1_OCTET_STRING *ctx_nonce;
if (!TEST_int_eq(fixture->expected,
ossl_cmp_hdr_init(fixture->cmp_ctx, fixture->hdr)))
return 0;
if (fixture->expected == 0)
return 1;
if (!TEST_int_eq(ossl_cmp_hdr_get_pvno(fixture->hdr), OSSL_CMP_PVNO))
return 0;
header_nonce = ossl_cmp_hdr_get0_senderNonce(fixture->hdr);
if (!TEST_int_eq(0, ASN1_OCTET_STRING_cmp(header_nonce,
fixture->cmp_ctx->senderNonce)))
return 0;
header_transactionID = OSSL_CMP_HDR_get0_transactionID(fixture->hdr);
if (!TEST_true(0 == ASN1_OCTET_STRING_cmp(header_transactionID,
fixture->cmp_ctx->transactionID)))
return 0;
header_nonce = OSSL_CMP_HDR_get0_recipNonce(fixture->hdr);
ctx_nonce = fixture->cmp_ctx->recipNonce;
if (ctx_nonce != NULL
&& (!TEST_ptr(header_nonce)
|| !TEST_int_eq(0, ASN1_OCTET_STRING_cmp(header_nonce,
ctx_nonce))))
return 0;
return 1;
}
static int test_HDR_init_with_ref(void)
{
unsigned char ref[CMP_TEST_REFVALUE_LENGTH];
SETUP_TEST_FIXTURE(CMP_HDR_TEST_FIXTURE, set_up);
fixture->expected = 1;
if (!TEST_int_eq(1, RAND_bytes(ref, sizeof(ref)))
|| !TEST_true(OSSL_CMP_CTX_set1_referenceValue(fixture->cmp_ctx,
ref, sizeof(ref)))) {
tear_down(fixture);
fixture = NULL;
}
EXECUTE_TEST(execute_HDR_init_test, tear_down);
return result;
}
static int test_HDR_init_with_subject(void)
{
X509_NAME *subject = NULL;
SETUP_TEST_FIXTURE(CMP_HDR_TEST_FIXTURE, set_up);
fixture->expected = 1;
if (!TEST_ptr(subject = X509_NAME_new())
|| !TEST_true(X509_NAME_ADD(subject, "CN", "Common Name"))
|| !TEST_true(OSSL_CMP_CTX_set1_subjectName(fixture->cmp_ctx,
subject))) {
tear_down(fixture);
fixture = NULL;
}
X509_NAME_free(subject);
EXECUTE_TEST(execute_HDR_init_test, tear_down);
return result;
}
void cleanup_tests(void)
{
return;
}
int setup_tests(void)
{
RAND_bytes(rand_data, OSSL_CMP_TRANSACTIONID_LENGTH);
/* Message header tests */
ADD_TEST(test_HDR_set_get_pvno);
ADD_TEST(test_HDR_get0_senderNonce);
ADD_TEST(test_HDR_set1_sender);
ADD_TEST(test_HDR_set1_recipient);
ADD_TEST(test_HDR_update_messageTime);
ADD_TEST(test_HDR_set1_senderKID);
ADD_TEST(test_HDR_push0_freeText);
/* indirectly tests ossl_cmp_pkifreetext_push_str(): */
ADD_TEST(test_HDR_push1_freeText);
ADD_TEST(test_HDR_generalInfo_push0_item);
ADD_TEST(test_HDR_generalInfo_push1_items);
ADD_TEST(test_HDR_set_and_check_implicit_confirm);
/* also tests public function OSSL_CMP_HDR_get0_transactionID(): */
/* also tests public function OSSL_CMP_HDR_get0_recipNonce(): */
/* also tests internal function ossl_cmp_hdr_get_pvno(): */
ADD_TEST(test_HDR_init_with_ref);
ADD_TEST(test_HDR_init_with_subject);
return 1;
}
diff --git a/crypto/openssl/test/ct_test.c b/crypto/openssl/test/ct_test.c
index 26d5bc108450..ff253414f806 100644
--- a/crypto/openssl/test/ct_test.c
+++ b/crypto/openssl/test/ct_test.c
@@ -1,527 +1,532 @@
/*
- * Copyright 2016-2022 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2016-2024 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 <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/ct.h>
#include <openssl/err.h>
#include <openssl/pem.h>
#include <openssl/x509.h>
#include <openssl/x509v3.h>
#include "testutil.h"
#include <openssl/crypto.h>
#ifndef OPENSSL_NO_CT
/* Used when declaring buffers to read text files into */
# define CT_TEST_MAX_FILE_SIZE 8096
static char *certs_dir = NULL;
static char *ct_dir = NULL;
typedef struct ct_test_fixture {
const char *test_case_name;
/* The current time in milliseconds */
uint64_t epoch_time_in_ms;
/* The CT log store to use during tests */
CTLOG_STORE* ctlog_store;
/* Set the following to test handling of SCTs in X509 certificates */
const char *certs_dir;
char *certificate_file;
char *issuer_file;
/* Expected number of SCTs */
int expected_sct_count;
/* Expected number of valid SCTS */
int expected_valid_sct_count;
/* Set the following to test handling of SCTs in TLS format */
const unsigned char *tls_sct_list;
size_t tls_sct_list_len;
STACK_OF(SCT) *sct_list;
/*
* A file to load the expected SCT text from.
* This text will be compared to the actual text output during the test.
* A maximum of |CT_TEST_MAX_FILE_SIZE| bytes will be read of this file.
*/
const char *sct_dir;
const char *sct_text_file;
/* Whether to test the validity of the SCT(s) */
int test_validity;
} CT_TEST_FIXTURE;
static CT_TEST_FIXTURE *set_up(const char *const test_case_name)
{
CT_TEST_FIXTURE *fixture = NULL;
if (!TEST_ptr(fixture = OPENSSL_zalloc(sizeof(*fixture))))
goto end;
fixture->test_case_name = test_case_name;
fixture->epoch_time_in_ms = 1580335307000ULL; /* Wed 29 Jan 2020 10:01:47 PM UTC */
if (!TEST_ptr(fixture->ctlog_store = CTLOG_STORE_new())
|| !TEST_int_eq(
CTLOG_STORE_load_default_file(fixture->ctlog_store), 1))
goto end;
return fixture;
end:
if (fixture != NULL)
CTLOG_STORE_free(fixture->ctlog_store);
OPENSSL_free(fixture);
TEST_error("Failed to setup");
return NULL;
}
static void tear_down(CT_TEST_FIXTURE *fixture)
{
if (fixture != NULL) {
CTLOG_STORE_free(fixture->ctlog_store);
SCT_LIST_free(fixture->sct_list);
}
OPENSSL_free(fixture);
}
static X509 *load_pem_cert(const char *dir, const char *file)
{
X509 *cert = NULL;
char *file_path = test_mk_file_path(dir, file);
if (file_path != NULL) {
BIO *cert_io = BIO_new_file(file_path, "r");
if (cert_io != NULL)
cert = PEM_read_bio_X509(cert_io, NULL, NULL, NULL);
BIO_free(cert_io);
}
OPENSSL_free(file_path);
return cert;
}
static int read_text_file(const char *dir, const char *file,
char *buffer, int buffer_length)
{
int len = -1;
char *file_path = test_mk_file_path(dir, file);
if (file_path != NULL) {
BIO *file_io = BIO_new_file(file_path, "r");
if (file_io != NULL)
len = BIO_read(file_io, buffer, buffer_length);
BIO_free(file_io);
}
OPENSSL_free(file_path);
return len;
}
static int compare_sct_list_printout(STACK_OF(SCT) *sct,
const char *expected_output)
{
BIO *text_buffer = NULL;
char *actual_output = NULL;
int result = 0;
if (!TEST_ptr(text_buffer = BIO_new(BIO_s_mem())))
goto end;
SCT_LIST_print(sct, text_buffer, 0, "\n", NULL);
/* Append \0 because we're about to use the buffer contents as a string. */
if (!TEST_true(BIO_write(text_buffer, "\0", 1)))
goto end;
BIO_get_mem_data(text_buffer, &actual_output);
if (!TEST_str_eq(actual_output, expected_output))
goto end;
result = 1;
end:
BIO_free(text_buffer);
return result;
}
static int compare_extension_printout(X509_EXTENSION *extension,
const char *expected_output)
{
BIO *text_buffer = NULL;
char *actual_output = NULL;
int result = 0;
if (!TEST_ptr(text_buffer = BIO_new(BIO_s_mem()))
|| !TEST_true(X509V3_EXT_print(text_buffer, extension,
X509V3_EXT_DEFAULT, 0)))
goto end;
/* Append \n because it's easier to create files that end with one. */
if (!TEST_true(BIO_write(text_buffer, "\n", 1)))
goto end;
/* Append \0 because we're about to use the buffer contents as a string. */
if (!TEST_true(BIO_write(text_buffer, "\0", 1)))
goto end;
BIO_get_mem_data(text_buffer, &actual_output);
if (!TEST_str_eq(actual_output, expected_output))
goto end;
result = 1;
end:
BIO_free(text_buffer);
return result;
}
static int assert_validity(CT_TEST_FIXTURE *fixture, STACK_OF(SCT) *scts,
CT_POLICY_EVAL_CTX *policy_ctx)
{
int invalid_sct_count = 0;
int valid_sct_count = 0;
int i;
if (!TEST_int_ge(SCT_LIST_validate(scts, policy_ctx), 0))
return 0;
for (i = 0; i < sk_SCT_num(scts); ++i) {
SCT *sct_i = sk_SCT_value(scts, i);
switch (SCT_get_validation_status(sct_i)) {
case SCT_VALIDATION_STATUS_VALID:
++valid_sct_count;
break;
case SCT_VALIDATION_STATUS_INVALID:
++invalid_sct_count;
break;
case SCT_VALIDATION_STATUS_NOT_SET:
case SCT_VALIDATION_STATUS_UNKNOWN_LOG:
case SCT_VALIDATION_STATUS_UNVERIFIED:
case SCT_VALIDATION_STATUS_UNKNOWN_VERSION:
/* Ignore other validation statuses. */
break;
}
}
if (!TEST_int_eq(valid_sct_count, fixture->expected_valid_sct_count)) {
int unverified_sct_count = sk_SCT_num(scts) -
invalid_sct_count - valid_sct_count;
TEST_info("%d SCTs failed, %d SCTs unverified",
invalid_sct_count, unverified_sct_count);
return 0;
}
return 1;
}
static int execute_cert_test(CT_TEST_FIXTURE *fixture)
{
int success = 0;
X509 *cert = NULL, *issuer = NULL;
STACK_OF(SCT) *scts = NULL;
SCT *sct = NULL;
char expected_sct_text[CT_TEST_MAX_FILE_SIZE];
int sct_text_len = 0;
unsigned char *tls_sct_list = NULL;
size_t tls_sct_list_len = 0;
CT_POLICY_EVAL_CTX *ct_policy_ctx = CT_POLICY_EVAL_CTX_new();
if (fixture->sct_text_file != NULL) {
sct_text_len = read_text_file(fixture->sct_dir, fixture->sct_text_file,
expected_sct_text,
CT_TEST_MAX_FILE_SIZE - 1);
if (!TEST_int_ge(sct_text_len, 0))
goto end;
expected_sct_text[sct_text_len] = '\0';
}
CT_POLICY_EVAL_CTX_set_shared_CTLOG_STORE(
ct_policy_ctx, fixture->ctlog_store);
CT_POLICY_EVAL_CTX_set_time(ct_policy_ctx, fixture->epoch_time_in_ms);
if (fixture->certificate_file != NULL) {
int sct_extension_index;
int i;
X509_EXTENSION *sct_extension = NULL;
if (!TEST_ptr(cert = load_pem_cert(fixture->certs_dir,
fixture->certificate_file)))
goto end;
CT_POLICY_EVAL_CTX_set1_cert(ct_policy_ctx, cert);
if (fixture->issuer_file != NULL) {
if (!TEST_ptr(issuer = load_pem_cert(fixture->certs_dir,
fixture->issuer_file)))
goto end;
CT_POLICY_EVAL_CTX_set1_issuer(ct_policy_ctx, issuer);
}
sct_extension_index =
X509_get_ext_by_NID(cert, NID_ct_precert_scts, -1);
sct_extension = X509_get_ext(cert, sct_extension_index);
if (fixture->expected_sct_count > 0) {
if (!TEST_ptr(sct_extension))
goto end;
if (fixture->sct_text_file
&& !compare_extension_printout(sct_extension,
expected_sct_text))
goto end;
scts = X509V3_EXT_d2i(sct_extension);
for (i = 0; i < sk_SCT_num(scts); ++i) {
SCT *sct_i = sk_SCT_value(scts, i);
if (!TEST_int_eq(SCT_get_source(sct_i),
SCT_SOURCE_X509V3_EXTENSION)) {
goto end;
}
}
if (fixture->test_validity) {
if (!assert_validity(fixture, scts, ct_policy_ctx))
goto end;
}
} else if (!TEST_ptr_null(sct_extension)) {
goto end;
}
}
if (fixture->tls_sct_list != NULL) {
const unsigned char *p = fixture->tls_sct_list;
if (!TEST_ptr(o2i_SCT_LIST(&scts, &p, fixture->tls_sct_list_len)))
goto end;
if (fixture->test_validity && cert != NULL) {
if (!assert_validity(fixture, scts, ct_policy_ctx))
goto end;
}
if (fixture->sct_text_file
&& !compare_sct_list_printout(scts, expected_sct_text)) {
goto end;
}
tls_sct_list_len = i2o_SCT_LIST(scts, &tls_sct_list);
if (!TEST_mem_eq(fixture->tls_sct_list, fixture->tls_sct_list_len,
tls_sct_list, tls_sct_list_len))
goto end;
}
success = 1;
end:
X509_free(cert);
X509_free(issuer);
SCT_LIST_free(scts);
SCT_free(sct);
CT_POLICY_EVAL_CTX_free(ct_policy_ctx);
OPENSSL_free(tls_sct_list);
return success;
}
# define SETUP_CT_TEST_FIXTURE() SETUP_TEST_FIXTURE(CT_TEST_FIXTURE, set_up)
# define EXECUTE_CT_TEST() EXECUTE_TEST(execute_cert_test, tear_down)
static int test_no_scts_in_certificate(void)
{
SETUP_CT_TEST_FIXTURE();
fixture->certs_dir = certs_dir;
fixture->certificate_file = "leaf.pem";
fixture->issuer_file = "subinterCA.pem";
fixture->expected_sct_count = 0;
EXECUTE_CT_TEST();
return result;
}
static int test_one_sct_in_certificate(void)
{
SETUP_CT_TEST_FIXTURE();
fixture->certs_dir = certs_dir;
fixture->certificate_file = "embeddedSCTs1.pem";
fixture->issuer_file = "embeddedSCTs1_issuer.pem";
fixture->expected_sct_count = 1;
fixture->sct_dir = certs_dir;
fixture->sct_text_file = "embeddedSCTs1.sct";
EXECUTE_CT_TEST();
return result;
}
static int test_multiple_scts_in_certificate(void)
{
SETUP_CT_TEST_FIXTURE();
fixture->certs_dir = certs_dir;
fixture->certificate_file = "embeddedSCTs3.pem";
fixture->issuer_file = "embeddedSCTs3_issuer.pem";
fixture->expected_sct_count = 3;
fixture->sct_dir = certs_dir;
fixture->sct_text_file = "embeddedSCTs3.sct";
EXECUTE_CT_TEST();
return result;
}
static int test_verify_one_sct(void)
{
SETUP_CT_TEST_FIXTURE();
fixture->certs_dir = certs_dir;
fixture->certificate_file = "embeddedSCTs1.pem";
fixture->issuer_file = "embeddedSCTs1_issuer.pem";
fixture->expected_sct_count = fixture->expected_valid_sct_count = 1;
fixture->test_validity = 1;
EXECUTE_CT_TEST();
return result;
}
static int test_verify_multiple_scts(void)
{
SETUP_CT_TEST_FIXTURE();
fixture->certs_dir = certs_dir;
fixture->certificate_file = "embeddedSCTs3.pem";
fixture->issuer_file = "embeddedSCTs3_issuer.pem";
fixture->expected_sct_count = fixture->expected_valid_sct_count = 3;
fixture->test_validity = 1;
EXECUTE_CT_TEST();
return result;
}
static int test_verify_fails_for_future_sct(void)
{
SETUP_CT_TEST_FIXTURE();
fixture->epoch_time_in_ms = 1365094800000ULL; /* Apr 4 17:00:00 2013 GMT */
fixture->certs_dir = certs_dir;
fixture->certificate_file = "embeddedSCTs1.pem";
fixture->issuer_file = "embeddedSCTs1_issuer.pem";
fixture->expected_sct_count = 1;
fixture->expected_valid_sct_count = 0;
fixture->test_validity = 1;
EXECUTE_CT_TEST();
return result;
}
static int test_decode_tls_sct(void)
{
const unsigned char tls_sct_list[] = "\x00\x78" /* length of list */
"\x00\x76"
"\x00" /* version */
/* log ID */
"\xDF\x1C\x2E\xC1\x15\x00\x94\x52\x47\xA9\x61\x68\x32\x5D\xDC\x5C\x79"
"\x59\xE8\xF7\xC6\xD3\x88\xFC\x00\x2E\x0B\xBD\x3F\x74\xD7\x64"
"\x00\x00\x01\x3D\xDB\x27\xDF\x93" /* timestamp */
"\x00\x00" /* extensions length */
"" /* extensions */
"\x04\x03" /* hash and signature algorithms */
"\x00\x47" /* signature length */
/* signature */
"\x30\x45\x02\x20\x48\x2F\x67\x51\xAF\x35\xDB\xA6\x54\x36\xBE\x1F\xD6"
"\x64\x0F\x3D\xBF\x9A\x41\x42\x94\x95\x92\x45\x30\x28\x8F\xA3\xE5\xE2"
"\x3E\x06\x02\x21\x00\xE4\xED\xC0\xDB\x3A\xC5\x72\xB1\xE2\xF5\xE8\xAB"
"\x6A\x68\x06\x53\x98\x7D\xCF\x41\x02\x7D\xFE\xFF\xA1\x05\x51\x9D\x89"
"\xED\xBF\x08";
SETUP_CT_TEST_FIXTURE();
fixture->tls_sct_list = tls_sct_list;
fixture->tls_sct_list_len = 0x7a;
fixture->sct_dir = ct_dir;
fixture->sct_text_file = "tls1.sct";
EXECUTE_CT_TEST();
return result;
}
static int test_encode_tls_sct(void)
{
const char log_id[] = "3xwuwRUAlFJHqWFoMl3cXHlZ6PfG04j8AC4LvT9012Q=";
const uint64_t timestamp = 1;
const char extensions[] = "";
const char signature[] = "BAMARzBAMiBIL2dRrzXbplQ2vh/WZA89v5pBQpSVkkUwKI+j5"
"eI+BgIhAOTtwNs6xXKx4vXoq2poBlOYfc9BAn3+/6EFUZ2J7b8I";
SCT *sct = NULL;
SETUP_CT_TEST_FIXTURE();
fixture->sct_list = sk_SCT_new_null();
if (fixture->sct_list == NULL)
- return 0;
+ {
+ tear_down(fixture);
+ return 0;
+ }
if (!TEST_ptr(sct = SCT_new_from_base64(SCT_VERSION_V1, log_id,
CT_LOG_ENTRY_TYPE_X509, timestamp,
extensions, signature)))
-
+ {
+ tear_down(fixture);
return 0;
+ }
sk_SCT_push(fixture->sct_list, sct);
fixture->sct_dir = ct_dir;
fixture->sct_text_file = "tls1.sct";
EXECUTE_CT_TEST();
return result;
}
/*
* Tests that the CT_POLICY_EVAL_CTX default time is approximately now.
* Allow +-10 minutes, as it may compensate for clock skew.
*/
static int test_default_ct_policy_eval_ctx_time_is_now(void)
{
int success = 0;
CT_POLICY_EVAL_CTX *ct_policy_ctx = CT_POLICY_EVAL_CTX_new();
const time_t default_time =
(time_t)(CT_POLICY_EVAL_CTX_get_time(ct_policy_ctx) / 1000);
const time_t time_tolerance = 600; /* 10 minutes */
if (!TEST_time_t_le(abs((int)difftime(time(NULL), default_time)),
time_tolerance))
goto end;
success = 1;
end:
CT_POLICY_EVAL_CTX_free(ct_policy_ctx);
return success;
}
static int test_ctlog_from_base64(void)
{
CTLOG *ctlogp = NULL;
const char notb64[] = "\01\02\03\04";
const char pad[] = "====";
const char name[] = "name";
/* We expect these to both fail! */
if (!TEST_true(!CTLOG_new_from_base64(&ctlogp, notb64, name))
|| !TEST_true(!CTLOG_new_from_base64(&ctlogp, pad, name)))
return 0;
return 1;
}
#endif
int setup_tests(void)
{
#ifndef OPENSSL_NO_CT
if ((ct_dir = getenv("CT_DIR")) == NULL)
ct_dir = "ct";
if ((certs_dir = getenv("CERTS_DIR")) == NULL)
certs_dir = "certs";
ADD_TEST(test_no_scts_in_certificate);
ADD_TEST(test_one_sct_in_certificate);
ADD_TEST(test_multiple_scts_in_certificate);
ADD_TEST(test_verify_one_sct);
ADD_TEST(test_verify_multiple_scts);
ADD_TEST(test_verify_fails_for_future_sct);
ADD_TEST(test_decode_tls_sct);
ADD_TEST(test_encode_tls_sct);
ADD_TEST(test_default_ct_policy_eval_ctx_time_is_now);
ADD_TEST(test_ctlog_from_base64);
#else
printf("No CT support\n");
#endif
return 1;
}
diff --git a/crypto/openssl/test/dsatest.c b/crypto/openssl/test/dsatest.c
index 5fa83020f87a..b849105d33d8 100644
--- a/crypto/openssl/test/dsatest.c
+++ b/crypto/openssl/test/dsatest.c
@@ -1,501 +1,505 @@
/*
- * Copyright 1995-2023 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 1995-2024 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 <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <openssl/crypto.h>
#include <openssl/rand.h>
#include <openssl/bn.h>
#include <openssl/dsa.h>
#include <openssl/evp.h>
#include <openssl/core_names.h>
#include "testutil.h"
#include "internal/nelem.h"
#ifndef OPENSSL_NO_DSA
static int dsa_cb(int p, int n, BN_GENCB *arg);
static unsigned char out_p[] = {
0x8d, 0xf2, 0xa4, 0x94, 0x49, 0x22, 0x76, 0xaa,
0x3d, 0x25, 0x75, 0x9b, 0xb0, 0x68, 0x69, 0xcb,
0xea, 0xc0, 0xd8, 0x3a, 0xfb, 0x8d, 0x0c, 0xf7,
0xcb, 0xb8, 0x32, 0x4f, 0x0d, 0x78, 0x82, 0xe5,
0xd0, 0x76, 0x2f, 0xc5, 0xb7, 0x21, 0x0e, 0xaf,
0xc2, 0xe9, 0xad, 0xac, 0x32, 0xab, 0x7a, 0xac,
0x49, 0x69, 0x3d, 0xfb, 0xf8, 0x37, 0x24, 0xc2,
0xec, 0x07, 0x36, 0xee, 0x31, 0xc8, 0x02, 0x91,
};
static unsigned char out_q[] = {
0xc7, 0x73, 0x21, 0x8c, 0x73, 0x7e, 0xc8, 0xee,
0x99, 0x3b, 0x4f, 0x2d, 0xed, 0x30, 0xf4, 0x8e,
0xda, 0xce, 0x91, 0x5f,
};
static unsigned char out_g[] = {
0x62, 0x6d, 0x02, 0x78, 0x39, 0xea, 0x0a, 0x13,
0x41, 0x31, 0x63, 0xa5, 0x5b, 0x4c, 0xb5, 0x00,
0x29, 0x9d, 0x55, 0x22, 0x95, 0x6c, 0xef, 0xcb,
0x3b, 0xff, 0x10, 0xf3, 0x99, 0xce, 0x2c, 0x2e,
0x71, 0xcb, 0x9d, 0xe5, 0xfa, 0x24, 0xba, 0xbf,
0x58, 0xe5, 0xb7, 0x95, 0x21, 0x92, 0x5c, 0x9c,
0xc4, 0x2e, 0x9f, 0x6f, 0x46, 0x4b, 0x08, 0x8c,
0xc5, 0x72, 0xaf, 0x53, 0xe6, 0xd7, 0x88, 0x02,
};
static int dsa_test(void)
{
BN_GENCB *cb;
DSA *dsa = NULL;
int counter, ret = 0, i, j;
unsigned char buf[256];
unsigned long h;
unsigned char sig[256];
unsigned int siglen;
const BIGNUM *p = NULL, *q = NULL, *g = NULL;
/*
* seed, out_p, out_q, out_g are taken from the updated Appendix 5 to FIPS
* PUB 186 and also appear in Appendix 5 to FIPS PIB 186-1
*/
static unsigned char seed[20] = {
0xd5, 0x01, 0x4e, 0x4b, 0x60, 0xef, 0x2b, 0xa8,
0xb6, 0x21, 0x1b, 0x40, 0x62, 0xba, 0x32, 0x24,
0xe0, 0x42, 0x7d, 0xd3,
};
static const unsigned char str1[] = "12345678901234567890";
if (!TEST_ptr(cb = BN_GENCB_new()))
goto end;
BN_GENCB_set(cb, dsa_cb, NULL);
if (!TEST_ptr(dsa = DSA_new())
|| !TEST_true(DSA_generate_parameters_ex(dsa, 512, seed, 20,
&counter, &h, cb)))
goto end;
if (!TEST_int_eq(counter, 105))
goto end;
if (!TEST_int_eq(h, 2))
goto end;
DSA_get0_pqg(dsa, &p, &q, &g);
i = BN_bn2bin(q, buf);
j = sizeof(out_q);
if (!TEST_int_eq(i, j) || !TEST_mem_eq(buf, i, out_q, i))
goto end;
i = BN_bn2bin(p, buf);
j = sizeof(out_p);
if (!TEST_int_eq(i, j) || !TEST_mem_eq(buf, i, out_p, i))
goto end;
i = BN_bn2bin(g, buf);
j = sizeof(out_g);
if (!TEST_int_eq(i, j) || !TEST_mem_eq(buf, i, out_g, i))
goto end;
if (!TEST_true(DSA_generate_key(dsa)))
goto end;
if (!TEST_true(DSA_sign(0, str1, 20, sig, &siglen, dsa)))
goto end;
if (TEST_int_gt(DSA_verify(0, str1, 20, sig, siglen, dsa), 0))
ret = 1;
end:
DSA_free(dsa);
BN_GENCB_free(cb);
return ret;
}
static int dsa_cb(int p, int n, BN_GENCB *arg)
{
static int ok = 0, num = 0;
if (p == 0)
num++;
if (p == 2)
ok++;
if (!ok && (p == 0) && (num > 1)) {
TEST_error("dsa_cb error");
return 0;
}
return 1;
}
# define P 0
# define Q 1
# define G 2
# define SEED 3
# define PCOUNT 4
# define GINDEX 5
# define HCOUNT 6
# define GROUP 7
static int dsa_keygen_test(void)
{
int ret = 0;
EVP_PKEY *param_key = NULL, *key = NULL;
EVP_PKEY_CTX *pg_ctx = NULL, *kg_ctx = NULL;
BIGNUM *p_in = NULL, *q_in = NULL, *g_in = NULL;
BIGNUM *p_out = NULL, *q_out = NULL, *g_out = NULL;
int gindex_out = 0, pcount_out = 0, hcount_out = 0;
unsigned char seed_out[32];
char group_out[32];
size_t len = 0;
const OSSL_PARAM *settables = NULL;
static const unsigned char seed_data[] = {
0xa6, 0xf5, 0x28, 0x8c, 0x50, 0x77, 0xa5, 0x68,
0x6d, 0x3a, 0xf5, 0xf1, 0xc6, 0x4c, 0xdc, 0x35,
0x95, 0x26, 0x3f, 0x03, 0xdc, 0x00, 0x3f, 0x44,
0x7b, 0x2a, 0xc7, 0x29
};
static const unsigned char expected_p[]= {
0xdb, 0x47, 0x07, 0xaf, 0xf0, 0x06, 0x49, 0x55,
0xc9, 0xbb, 0x09, 0x41, 0xb8, 0xdb, 0x1f, 0xbc,
0xa8, 0xed, 0x12, 0x06, 0x7f, 0x88, 0x49, 0xb8,
0xc9, 0x12, 0x87, 0x21, 0xbb, 0x08, 0x6c, 0xbd,
0xf1, 0x89, 0xef, 0x84, 0xd9, 0x7a, 0x93, 0xe8,
0x45, 0x40, 0x81, 0xec, 0x37, 0x27, 0x1a, 0xa4,
0x22, 0x51, 0x99, 0xf0, 0xde, 0x04, 0xdb, 0xea,
0xa1, 0xf9, 0x37, 0x83, 0x80, 0x96, 0x36, 0x53,
0xf6, 0xae, 0x14, 0x73, 0x33, 0x0f, 0xdf, 0x0b,
0xf9, 0x2f, 0x08, 0x46, 0x31, 0xf9, 0x66, 0xcd,
0x5a, 0xeb, 0x6c, 0xf3, 0xbb, 0x74, 0xf3, 0x88,
0xf0, 0x31, 0x5c, 0xa4, 0xc8, 0x0f, 0x86, 0xf3,
0x0f, 0x9f, 0xc0, 0x8c, 0x57, 0xe4, 0x7f, 0x95,
0xb3, 0x62, 0xc8, 0x4e, 0xae, 0xf3, 0xd8, 0x14,
0xcc, 0x47, 0xc2, 0x4b, 0x4f, 0xef, 0xaf, 0xcd,
0xcf, 0xb2, 0xbb, 0xe8, 0xbe, 0x08, 0xca, 0x15,
0x90, 0x59, 0x35, 0xef, 0x35, 0x1c, 0xfe, 0xeb,
0x33, 0x2e, 0x25, 0x22, 0x57, 0x9c, 0x55, 0x23,
0x0c, 0x6f, 0xed, 0x7c, 0xb6, 0xc7, 0x36, 0x0b,
0xcb, 0x2b, 0x6a, 0x21, 0xa1, 0x1d, 0x55, 0x77,
0xd9, 0x91, 0xcd, 0xc1, 0xcd, 0x3d, 0x82, 0x16,
0x9c, 0xa0, 0x13, 0xa5, 0x83, 0x55, 0x3a, 0x73,
0x7e, 0x2c, 0x44, 0x3e, 0x70, 0x2e, 0x50, 0x91,
0x6e, 0xca, 0x3b, 0xef, 0xff, 0x85, 0x35, 0x70,
0xff, 0x61, 0x0c, 0xb1, 0xb2, 0xb7, 0x94, 0x6f,
0x65, 0xa4, 0x57, 0x62, 0xef, 0x21, 0x83, 0x0f,
0x3e, 0x71, 0xae, 0x7d, 0xe4, 0xad, 0xfb, 0xe3,
0xdd, 0xd6, 0x03, 0xda, 0x9a, 0xd8, 0x8f, 0x2d,
0xbb, 0x90, 0x87, 0xf8, 0xdb, 0xdc, 0xec, 0x71,
0xf2, 0xdb, 0x0b, 0x8e, 0xfc, 0x1a, 0x7e, 0x79,
0xb1, 0x1b, 0x0d, 0xfc, 0x70, 0xec, 0x85, 0xc2,
0xc5, 0xba, 0xb9, 0x69, 0x3f, 0x88, 0xbc, 0xcb
};
static const unsigned char expected_q[]= {
0x99, 0xb6, 0xa0, 0xee, 0xb3, 0xa6, 0x99, 0x1a,
0xb6, 0x67, 0x8d, 0xc1, 0x2b, 0x9b, 0xce, 0x2b,
0x01, 0x72, 0x5a, 0x65, 0x76, 0x3d, 0x93, 0x69,
0xe2, 0x56, 0xae, 0xd7
};
static const unsigned char expected_g[]= {
0x63, 0xf8, 0xb6, 0xee, 0x2a, 0x27, 0xaf, 0x4f,
0x4c, 0xf6, 0x08, 0x28, 0x87, 0x4a, 0xe7, 0x1f,
0x45, 0x46, 0x27, 0x52, 0x3b, 0x7f, 0x6f, 0xd2,
0x29, 0xcb, 0xe8, 0x11, 0x19, 0x25, 0x35, 0x76,
0x99, 0xcb, 0x4f, 0x1b, 0xe0, 0xed, 0x32, 0x9e,
0x05, 0xb5, 0xbe, 0xd7, 0xf6, 0x5a, 0xb2, 0xf6,
0x0e, 0x0c, 0x7e, 0xf5, 0xe1, 0x05, 0xfe, 0xda,
0xaf, 0x0f, 0x27, 0x1e, 0x40, 0x2a, 0xf7, 0xa7,
0x23, 0x49, 0x2c, 0xd9, 0x1b, 0x0a, 0xbe, 0xff,
0xc7, 0x7c, 0x7d, 0x60, 0xca, 0xa3, 0x19, 0xc3,
0xb7, 0xe4, 0x43, 0xb0, 0xf5, 0x75, 0x44, 0x90,
0x46, 0x47, 0xb1, 0xa6, 0x48, 0x0b, 0x21, 0x8e,
0xee, 0x75, 0xe6, 0x3d, 0xa7, 0xd3, 0x7b, 0x31,
0xd1, 0xd2, 0x9d, 0xe2, 0x8a, 0xfc, 0x57, 0xfd,
0x8a, 0x10, 0x31, 0xeb, 0x87, 0x36, 0x3f, 0x65,
0x72, 0x23, 0x2c, 0xd3, 0xd6, 0x17, 0xa5, 0x62,
0x58, 0x65, 0x57, 0x6a, 0xd4, 0xa8, 0xfe, 0xec,
0x57, 0x76, 0x0c, 0xb1, 0x4c, 0x93, 0xed, 0xb0,
0xb4, 0xf9, 0x45, 0xb3, 0x3e, 0xdd, 0x47, 0xf1,
0xfb, 0x7d, 0x25, 0x79, 0x3d, 0xfc, 0xa7, 0x39,
0x90, 0x68, 0x6a, 0x6b, 0xae, 0xf2, 0x6e, 0x64,
0x8c, 0xfb, 0xb8, 0xdd, 0x76, 0x4e, 0x4a, 0x69,
0x8c, 0x97, 0x15, 0x77, 0xb2, 0x67, 0xdc, 0xeb,
0x4a, 0x40, 0x6b, 0xb9, 0x47, 0x8f, 0xa6, 0xab,
0x6e, 0x98, 0xc0, 0x97, 0x9a, 0x0c, 0xea, 0x00,
0xfd, 0x56, 0x1a, 0x74, 0x9a, 0x32, 0x6b, 0xfe,
0xbd, 0xdf, 0x6c, 0x82, 0x54, 0x53, 0x4d, 0x70,
0x65, 0xe3, 0x8b, 0x37, 0xb8, 0xe4, 0x70, 0x08,
0xb7, 0x3b, 0x30, 0x27, 0xaf, 0x1c, 0x77, 0xf3,
0x62, 0xd4, 0x9a, 0x59, 0xba, 0xd1, 0x6e, 0x89,
0x5c, 0x34, 0x9a, 0xa1, 0xb7, 0x4f, 0x7d, 0x8c,
0xdc, 0xbc, 0x74, 0x25, 0x5e, 0xbf, 0x77, 0x46
};
int expected_c = 1316;
int expected_h = 2;
if (!TEST_ptr(p_in = BN_bin2bn(expected_p, sizeof(expected_p), NULL))
|| !TEST_ptr(q_in = BN_bin2bn(expected_q, sizeof(expected_q), NULL))
|| !TEST_ptr(g_in = BN_bin2bn(expected_g, sizeof(expected_g), NULL)))
goto end;
if (!TEST_ptr(pg_ctx = EVP_PKEY_CTX_new_from_name(NULL, "DSA", NULL))
|| !TEST_int_gt(EVP_PKEY_paramgen_init(pg_ctx), 0)
|| !TEST_ptr_null(EVP_PKEY_CTX_gettable_params(pg_ctx))
|| !TEST_ptr(settables = EVP_PKEY_CTX_settable_params(pg_ctx))
|| !TEST_ptr(OSSL_PARAM_locate_const(settables,
OSSL_PKEY_PARAM_FFC_PBITS))
|| !TEST_true(EVP_PKEY_CTX_set_dsa_paramgen_type(pg_ctx, "fips186_4"))
|| !TEST_true(EVP_PKEY_CTX_set_dsa_paramgen_bits(pg_ctx, 2048))
|| !TEST_true(EVP_PKEY_CTX_set_dsa_paramgen_q_bits(pg_ctx, 224))
|| !TEST_true(EVP_PKEY_CTX_set_dsa_paramgen_seed(pg_ctx, seed_data,
sizeof(seed_data)))
|| !TEST_true(EVP_PKEY_CTX_set_dsa_paramgen_md_props(pg_ctx, "SHA256",
""))
|| !TEST_int_gt(EVP_PKEY_generate(pg_ctx, &param_key), 0)
|| !TEST_ptr(kg_ctx = EVP_PKEY_CTX_new_from_pkey(NULL, param_key, NULL))
|| !TEST_int_gt(EVP_PKEY_keygen_init(kg_ctx), 0)
|| !TEST_int_gt(EVP_PKEY_generate(kg_ctx, &key), 0))
goto end;
if (!TEST_true(EVP_PKEY_get_bn_param(key, OSSL_PKEY_PARAM_FFC_P, &p_out))
|| !TEST_BN_eq(p_in, p_out)
|| !TEST_true(EVP_PKEY_get_bn_param(key, OSSL_PKEY_PARAM_FFC_Q, &q_out))
|| !TEST_BN_eq(q_in, q_out)
|| !TEST_true(EVP_PKEY_get_bn_param(key, OSSL_PKEY_PARAM_FFC_G, &g_out))
|| !TEST_BN_eq(g_in, g_out)
|| !TEST_true(EVP_PKEY_get_octet_string_param(
key, OSSL_PKEY_PARAM_FFC_SEED, seed_out,
sizeof(seed_out), &len))
|| !TEST_mem_eq(seed_out, len, seed_data, sizeof(seed_data))
|| !TEST_true(EVP_PKEY_get_int_param(key, OSSL_PKEY_PARAM_FFC_GINDEX,
&gindex_out))
|| !TEST_int_eq(gindex_out, -1)
|| !TEST_true(EVP_PKEY_get_int_param(key, OSSL_PKEY_PARAM_FFC_H,
&hcount_out))
|| !TEST_int_eq(hcount_out, expected_h)
|| !TEST_true(EVP_PKEY_get_int_param(key,
OSSL_PKEY_PARAM_FFC_PCOUNTER,
&pcount_out))
|| !TEST_int_eq(pcount_out, expected_c)
|| !TEST_false(EVP_PKEY_get_utf8_string_param(key,
OSSL_PKEY_PARAM_GROUP_NAME,
group_out,
sizeof(group_out), &len)))
goto end;
ret = 1;
end:
BN_free(p_in);
BN_free(q_in);
BN_free(g_in);
BN_free(p_out);
BN_free(q_out);
BN_free(g_out);
EVP_PKEY_free(param_key);
EVP_PKEY_free(key);
EVP_PKEY_CTX_free(kg_ctx);
EVP_PKEY_CTX_free(pg_ctx);
return ret;
}
static int test_dsa_default_paramgen_validate(int i)
{
int ret;
EVP_PKEY_CTX *gen_ctx = NULL;
EVP_PKEY_CTX *check_ctx = NULL;
EVP_PKEY *params = NULL;
ret = TEST_ptr(gen_ctx = EVP_PKEY_CTX_new_from_name(NULL, "DSA", NULL))
&& TEST_int_gt(EVP_PKEY_paramgen_init(gen_ctx), 0)
&& (i == 0
|| TEST_true(EVP_PKEY_CTX_set_dsa_paramgen_bits(gen_ctx, 512)))
&& TEST_int_gt(EVP_PKEY_generate(gen_ctx, &params), 0)
&& TEST_ptr(check_ctx = EVP_PKEY_CTX_new_from_pkey(NULL, params, NULL))
&& TEST_int_gt(EVP_PKEY_param_check(check_ctx), 0);
EVP_PKEY_free(params);
EVP_PKEY_CTX_free(check_ctx);
EVP_PKEY_CTX_free(gen_ctx);
return ret;
}
static int test_dsa_sig_infinite_loop(void)
{
int ret = 0;
DSA *dsa = NULL;
BIGNUM *p = NULL, *q = NULL, *g = NULL, *priv = NULL, *pub = NULL, *priv2 = NULL;
BIGNUM *badq = NULL, *badpriv = NULL;
const unsigned char msg[] = { 0x00 };
+ unsigned int signature_len0;
unsigned int signature_len;
unsigned char signature[64];
static unsigned char out_priv[] = {
0x17, 0x00, 0xb2, 0x8d, 0xcb, 0x24, 0xc9, 0x98,
0xd0, 0x7f, 0x1f, 0x83, 0x1a, 0xa1, 0xc4, 0xa4,
0xf8, 0x0f, 0x7f, 0x12
};
static unsigned char out_pub[] = {
0x04, 0x72, 0xee, 0x8d, 0xaa, 0x4d, 0x89, 0x60,
0x0e, 0xb2, 0xd4, 0x38, 0x84, 0xa2, 0x2a, 0x60,
0x5f, 0x67, 0xd7, 0x9e, 0x24, 0xdd, 0xe8, 0x50,
0xf2, 0x23, 0x71, 0x55, 0x53, 0x94, 0x0d, 0x6b,
0x2e, 0xcd, 0x30, 0xda, 0x6f, 0x1e, 0x2c, 0xcf,
0x59, 0xbe, 0x05, 0x6c, 0x07, 0x0e, 0xc6, 0x38,
0x05, 0xcb, 0x0c, 0x44, 0x0a, 0x08, 0x13, 0xb6,
0x0f, 0x14, 0xde, 0x4a, 0xf6, 0xed, 0x4e, 0xc3
};
if (!TEST_ptr(p = BN_bin2bn(out_p, sizeof(out_p), NULL))
|| !TEST_ptr(q = BN_bin2bn(out_q, sizeof(out_q), NULL))
|| !TEST_ptr(g = BN_bin2bn(out_g, sizeof(out_g), NULL))
|| !TEST_ptr(pub = BN_bin2bn(out_pub, sizeof(out_pub), NULL))
|| !TEST_ptr(priv = BN_bin2bn(out_priv, sizeof(out_priv), NULL))
|| !TEST_ptr(priv2 = BN_dup(priv))
|| !TEST_ptr(badq = BN_new())
|| !TEST_true(BN_set_word(badq, 1))
|| !TEST_ptr(badpriv = BN_new())
|| !TEST_true(BN_set_word(badpriv, 0))
|| !TEST_ptr(dsa = DSA_new()))
goto err;
if (!TEST_true(DSA_set0_pqg(dsa, p, q, g)))
goto err;
p = q = g = NULL;
if (!TEST_true(DSA_set0_key(dsa, pub, priv)))
goto err;
pub = priv = NULL;
if (!TEST_int_le(DSA_size(dsa), sizeof(signature)))
goto err;
/* Test passing signature as NULL */
- if (!TEST_true(DSA_sign(0, msg, sizeof(msg), NULL, &signature_len, dsa)))
+ if (!TEST_true(DSA_sign(0, msg, sizeof(msg), NULL, &signature_len0, dsa))
+ || !TEST_int_gt(signature_len0, 0))
goto err;
- if (!TEST_true(DSA_sign(0, msg, sizeof(msg), signature, &signature_len, dsa)))
+ if (!TEST_true(DSA_sign(0, msg, sizeof(msg), signature, &signature_len, dsa))
+ || !TEST_int_gt(signature_len, 0)
+ || !TEST_int_le(signature_len, signature_len0))
goto err;
/* Test using a private key of zero fails - this causes an infinite loop without the retry test */
if (!TEST_true(DSA_set0_key(dsa, NULL, badpriv)))
goto err;
badpriv = NULL;
if (!TEST_false(DSA_sign(0, msg, sizeof(msg), signature, &signature_len, dsa)))
goto err;
/* Restore private and set a bad q - this caused an infinite loop in the setup */
if (!TEST_true(DSA_set0_key(dsa, NULL, priv2)))
goto err;
priv2 = NULL;
if (!TEST_true(DSA_set0_pqg(dsa, NULL, badq, NULL)))
goto err;
badq = NULL;
if (!TEST_false(DSA_sign(0, msg, sizeof(msg), signature, &signature_len, dsa)))
goto err;
ret = 1;
err:
BN_free(badq);
BN_free(badpriv);
BN_free(pub);
BN_free(priv);
BN_free(priv2);
BN_free(g);
BN_free(q);
BN_free(p);
DSA_free(dsa);
return ret;
}
static int test_dsa_sig_neg_param(void)
{
int ret = 0, setpqg = 0;
DSA *dsa = NULL;
BIGNUM *p = NULL, *q = NULL, *g = NULL, *priv = NULL, *pub = NULL;
const unsigned char msg[] = { 0x00 };
unsigned int signature_len;
unsigned char signature[64];
static unsigned char out_priv[] = {
0x17, 0x00, 0xb2, 0x8d, 0xcb, 0x24, 0xc9, 0x98,
0xd0, 0x7f, 0x1f, 0x83, 0x1a, 0xa1, 0xc4, 0xa4,
0xf8, 0x0f, 0x7f, 0x12
};
static unsigned char out_pub[] = {
0x04, 0x72, 0xee, 0x8d, 0xaa, 0x4d, 0x89, 0x60,
0x0e, 0xb2, 0xd4, 0x38, 0x84, 0xa2, 0x2a, 0x60,
0x5f, 0x67, 0xd7, 0x9e, 0x24, 0xdd, 0xe8, 0x50,
0xf2, 0x23, 0x71, 0x55, 0x53, 0x94, 0x0d, 0x6b,
0x2e, 0xcd, 0x30, 0xda, 0x6f, 0x1e, 0x2c, 0xcf,
0x59, 0xbe, 0x05, 0x6c, 0x07, 0x0e, 0xc6, 0x38,
0x05, 0xcb, 0x0c, 0x44, 0x0a, 0x08, 0x13, 0xb6,
0x0f, 0x14, 0xde, 0x4a, 0xf6, 0xed, 0x4e, 0xc3
};
if (!TEST_ptr(p = BN_bin2bn(out_p, sizeof(out_p), NULL))
|| !TEST_ptr(q = BN_bin2bn(out_q, sizeof(out_q), NULL))
|| !TEST_ptr(g = BN_bin2bn(out_g, sizeof(out_g), NULL))
|| !TEST_ptr(pub = BN_bin2bn(out_pub, sizeof(out_pub), NULL))
|| !TEST_ptr(priv = BN_bin2bn(out_priv, sizeof(out_priv), NULL))
|| !TEST_ptr(dsa = DSA_new()))
goto err;
if (!TEST_true(DSA_set0_pqg(dsa, p, q, g)))
goto err;
setpqg = 1;
if (!TEST_true(DSA_set0_key(dsa, pub, priv)))
goto err;
pub = priv = NULL;
BN_set_negative(p, 1);
if (!TEST_false(DSA_sign(0, msg, sizeof(msg), signature, &signature_len, dsa)))
goto err;
BN_set_negative(p, 0);
BN_set_negative(q, 1);
if (!TEST_false(DSA_sign(0, msg, sizeof(msg), signature, &signature_len, dsa)))
goto err;
BN_set_negative(q, 0);
BN_set_negative(g, 1);
if (!TEST_false(DSA_sign(0, msg, sizeof(msg), signature, &signature_len, dsa)))
goto err;
BN_set_negative(p, 1);
BN_set_negative(q, 1);
BN_set_negative(g, 1);
if (!TEST_false(DSA_sign(0, msg, sizeof(msg), signature, &signature_len, dsa)))
goto err;
ret = 1;
err:
BN_free(pub);
BN_free(priv);
if (setpqg == 0) {
BN_free(g);
BN_free(q);
BN_free(p);
}
DSA_free(dsa);
return ret;
}
#endif /* OPENSSL_NO_DSA */
int setup_tests(void)
{
#ifndef OPENSSL_NO_DSA
ADD_TEST(dsa_test);
ADD_TEST(dsa_keygen_test);
ADD_TEST(test_dsa_sig_infinite_loop);
ADD_TEST(test_dsa_sig_neg_param);
ADD_ALL_TESTS(test_dsa_default_paramgen_validate, 2);
#endif
return 1;
}
diff --git a/crypto/openssl/test/ecdsatest.c b/crypto/openssl/test/ecdsatest.c
index 33a52eb1b562..0ddbf6690dca 100644
--- a/crypto/openssl/test/ecdsatest.c
+++ b/crypto/openssl/test/ecdsatest.c
@@ -1,399 +1,423 @@
/*
- * Copyright 2002-2023 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2002-2024 The OpenSSL Project Authors. All Rights Reserved.
* Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
/*
* Low level APIs are deprecated for public use, but still ok for internal use.
*/
#include "internal/deprecated.h"
#include <openssl/opensslconf.h> /* To see if OPENSSL_NO_EC is defined */
#include "testutil.h"
#ifndef OPENSSL_NO_EC
# include <openssl/evp.h>
# include <openssl/bn.h>
# include <openssl/ec.h>
# include <openssl/rand.h>
# include "internal/nelem.h"
# include "ecdsatest.h"
static fake_random_generate_cb fbytes;
static const char *numbers[2];
static size_t crv_len = 0;
static EC_builtin_curve *curves = NULL;
static OSSL_PROVIDER *fake_rand = NULL;
static int fbytes(unsigned char *buf, size_t num, ossl_unused const char *name,
EVP_RAND_CTX *ctx)
{
int ret = 0;
static int fbytes_counter = 0;
BIGNUM *tmp = NULL;
fake_rand_set_callback(ctx, NULL);
if (!TEST_ptr(tmp = BN_new())
|| !TEST_int_lt(fbytes_counter, OSSL_NELEM(numbers))
|| !TEST_true(BN_hex2bn(&tmp, numbers[fbytes_counter]))
/* tmp might need leading zeros so pad it out */
|| !TEST_int_le(BN_num_bytes(tmp), num)
|| !TEST_int_gt(BN_bn2binpad(tmp, buf, num), 0))
goto err;
fbytes_counter = (fbytes_counter + 1) % OSSL_NELEM(numbers);
ret = 1;
err:
BN_free(tmp);
return ret;
}
/*-
* This function hijacks the RNG to feed it the chosen ECDSA key and nonce.
* The ECDSA KATs are from:
* - the X9.62 draft (4)
* - NIST CAVP (720)
*
* It uses the low-level ECDSA_sign_setup instead of EVP to control the RNG.
* NB: This is not how applications should use ECDSA; this is only for testing.
*
* Tests the library can successfully:
* - generate public keys that matches those KATs
* - create ECDSA signatures that match those KATs
* - accept those signatures as valid
*/
static int x9_62_tests(int n)
{
int nid, md_nid, ret = 0;
const char *r_in = NULL, *s_in = NULL, *tbs = NULL;
unsigned char *pbuf = NULL, *qbuf = NULL, *message = NULL;
unsigned char digest[EVP_MAX_MD_SIZE];
unsigned int dgst_len = 0;
long q_len, msg_len = 0;
size_t p_len;
EVP_MD_CTX *mctx = NULL;
EC_KEY *key = NULL;
ECDSA_SIG *signature = NULL;
BIGNUM *r = NULL, *s = NULL;
BIGNUM *kinv = NULL, *rp = NULL;
const BIGNUM *sig_r = NULL, *sig_s = NULL;
nid = ecdsa_cavs_kats[n].nid;
md_nid = ecdsa_cavs_kats[n].md_nid;
r_in = ecdsa_cavs_kats[n].r;
s_in = ecdsa_cavs_kats[n].s;
tbs = ecdsa_cavs_kats[n].msg;
numbers[0] = ecdsa_cavs_kats[n].d;
numbers[1] = ecdsa_cavs_kats[n].k;
TEST_info("ECDSA KATs for curve %s", OBJ_nid2sn(nid));
#ifdef FIPS_MODULE
if (EC_curve_nid2nist(nid) == NULL)
return TEST_skip("skip non approved curves");
#endif /* FIPS_MODULE */
if (!TEST_ptr(mctx = EVP_MD_CTX_new())
/* get the message digest */
|| !TEST_ptr(message = OPENSSL_hexstr2buf(tbs, &msg_len))
|| !TEST_true(EVP_DigestInit_ex(mctx, EVP_get_digestbynid(md_nid), NULL))
|| !TEST_true(EVP_DigestUpdate(mctx, message, msg_len))
|| !TEST_true(EVP_DigestFinal_ex(mctx, digest, &dgst_len))
/* create the key */
|| !TEST_ptr(key = EC_KEY_new_by_curve_name(nid))
/* load KAT variables */
|| !TEST_ptr(r = BN_new())
|| !TEST_ptr(s = BN_new())
|| !TEST_true(BN_hex2bn(&r, r_in))
|| !TEST_true(BN_hex2bn(&s, s_in)))
goto err;
/* public key must match KAT */
fake_rand_set_callback(RAND_get0_private(NULL), &fbytes);
if (!TEST_true(EC_KEY_generate_key(key))
|| !TEST_true(p_len = EC_KEY_key2buf(key, POINT_CONVERSION_UNCOMPRESSED,
&pbuf, NULL))
|| !TEST_ptr(qbuf = OPENSSL_hexstr2buf(ecdsa_cavs_kats[n].Q, &q_len))
|| !TEST_int_eq(q_len, p_len)
|| !TEST_mem_eq(qbuf, q_len, pbuf, p_len))
goto err;
/* create the signature via ECDSA_sign_setup to avoid use of ECDSA nonces */
fake_rand_set_callback(RAND_get0_private(NULL), &fbytes);
if (!TEST_true(ECDSA_sign_setup(key, NULL, &kinv, &rp))
|| !TEST_ptr(signature = ECDSA_do_sign_ex(digest, dgst_len,
kinv, rp, key))
/* verify the signature */
|| !TEST_int_eq(ECDSA_do_verify(digest, dgst_len, signature, key), 1))
goto err;
/* compare the created signature with the expected signature */
ECDSA_SIG_get0(signature, &sig_r, &sig_s);
if (!TEST_BN_eq(sig_r, r)
|| !TEST_BN_eq(sig_s, s))
goto err;
ret = 1;
err:
OPENSSL_free(message);
OPENSSL_free(pbuf);
OPENSSL_free(qbuf);
EC_KEY_free(key);
ECDSA_SIG_free(signature);
BN_free(r);
BN_free(s);
EVP_MD_CTX_free(mctx);
BN_clear_free(kinv);
BN_clear_free(rp);
return ret;
}
/*-
* Positive and negative ECDSA testing through EVP interface:
* - EVP_DigestSign (this is the one-shot version)
* - EVP_DigestVerify
*
* Tests the library can successfully:
* - create a key
* - create a signature
* - accept that signature
* - reject that signature with a different public key
* - reject that signature if its length is not correct
* - reject that signature after modifying the message
* - accept that signature after un-modifying the message
* - reject that signature after modifying the signature
* - accept that signature after un-modifying the signature
*/
static int set_sm2_id(EVP_MD_CTX *mctx, EVP_PKEY *pkey)
{
/* With the SM2 key type, the SM2 ID is mandatory */
static const char sm2_id[] = { 1, 2, 3, 4, 'l', 'e', 't', 't', 'e', 'r' };
EVP_PKEY_CTX *pctx;
if (!TEST_ptr(pctx = EVP_MD_CTX_get_pkey_ctx(mctx))
|| !TEST_int_gt(EVP_PKEY_CTX_set1_id(pctx, sm2_id, sizeof(sm2_id)), 0))
return 0;
return 1;
}
static int test_builtin(int n, int as)
{
EC_KEY *eckey_neg = NULL, *eckey = NULL;
unsigned char dirt, offset, tbs[128];
unsigned char *sig = NULL;
EVP_PKEY *pkey_neg = NULL, *pkey = NULL, *dup_pk = NULL;
EVP_MD_CTX *mctx = NULL;
size_t sig_len;
int nid, ret = 0;
int temp;
nid = curves[n].nid;
/* skip built-in curves where ord(G) is not prime */
if (nid == NID_ipsec4 || nid == NID_ipsec3) {
TEST_info("skipped: ECDSA unsupported for curve %s", OBJ_nid2sn(nid));
return 1;
}
/*
* skip SM2 curve if 'as' is equal to EVP_PKEY_EC or, skip all curves
* except SM2 curve if 'as' is equal to EVP_PKEY_SM2
*/
if (nid == NID_sm2 && as == EVP_PKEY_EC) {
TEST_info("skipped: EC key type unsupported for curve %s",
OBJ_nid2sn(nid));
return 1;
} else if (nid != NID_sm2 && as == EVP_PKEY_SM2) {
TEST_info("skipped: SM2 key type unsupported for curve %s",
OBJ_nid2sn(nid));
return 1;
}
TEST_info("testing ECDSA for curve %s as %s key type", OBJ_nid2sn(nid),
as == EVP_PKEY_EC ? "EC" : "SM2");
if (!TEST_ptr(mctx = EVP_MD_CTX_new())
/* get some random message data */
|| !TEST_int_gt(RAND_bytes(tbs, sizeof(tbs)), 0)
/* real key */
|| !TEST_ptr(eckey = EC_KEY_new_by_curve_name(nid))
|| !TEST_true(EC_KEY_generate_key(eckey))
|| !TEST_ptr(pkey = EVP_PKEY_new())
|| !TEST_true(EVP_PKEY_assign_EC_KEY(pkey, eckey))
/* fake key for negative testing */
|| !TEST_ptr(eckey_neg = EC_KEY_new_by_curve_name(nid))
|| !TEST_true(EC_KEY_generate_key(eckey_neg))
|| !TEST_ptr(pkey_neg = EVP_PKEY_new())
|| !TEST_false(EVP_PKEY_assign_EC_KEY(pkey_neg, NULL))
|| !TEST_true(EVP_PKEY_assign_EC_KEY(pkey_neg, eckey_neg)))
goto err;
if (!TEST_ptr(dup_pk = EVP_PKEY_dup(pkey))
|| !TEST_int_eq(EVP_PKEY_eq(pkey, dup_pk), 1))
goto err;
temp = ECDSA_size(eckey);
if (!TEST_int_ge(temp, 0)
|| !TEST_ptr(sig = OPENSSL_malloc(sig_len = (size_t)temp))
/* create a signature */
|| !TEST_true(EVP_DigestSignInit(mctx, NULL, NULL, NULL, pkey))
|| (as == EVP_PKEY_SM2 && !set_sm2_id(mctx, pkey))
|| !TEST_true(EVP_DigestSign(mctx, sig, &sig_len, tbs, sizeof(tbs)))
|| !TEST_int_le(sig_len, ECDSA_size(eckey))
|| !TEST_true(EVP_MD_CTX_reset(mctx))
/* negative test, verify with wrong key, 0 return */
|| !TEST_true(EVP_DigestVerifyInit(mctx, NULL, NULL, NULL, pkey_neg))
|| (as == EVP_PKEY_SM2 && !set_sm2_id(mctx, pkey_neg))
|| !TEST_int_eq(EVP_DigestVerify(mctx, sig, sig_len, tbs, sizeof(tbs)), 0)
|| !TEST_true(EVP_MD_CTX_reset(mctx))
/* negative test, verify with wrong signature length, -1 return */
|| !TEST_true(EVP_DigestVerifyInit(mctx, NULL, NULL, NULL, pkey))
|| (as == EVP_PKEY_SM2 && !set_sm2_id(mctx, pkey))
|| !TEST_int_eq(EVP_DigestVerify(mctx, sig, sig_len - 1, tbs, sizeof(tbs)), -1)
|| !TEST_true(EVP_MD_CTX_reset(mctx))
/* positive test, verify with correct key, 1 return */
|| !TEST_true(EVP_DigestVerifyInit(mctx, NULL, NULL, NULL, pkey))
|| (as == EVP_PKEY_SM2 && !set_sm2_id(mctx, pkey))
|| !TEST_int_eq(EVP_DigestVerify(mctx, sig, sig_len, tbs, sizeof(tbs)), 1)
|| !TEST_true(EVP_MD_CTX_reset(mctx)))
goto err;
/* muck with the message, test it fails with 0 return */
tbs[0] ^= 1;
if (!TEST_true(EVP_DigestVerifyInit(mctx, NULL, NULL, NULL, pkey))
|| (as == EVP_PKEY_SM2 && !set_sm2_id(mctx, pkey))
|| !TEST_int_eq(EVP_DigestVerify(mctx, sig, sig_len, tbs, sizeof(tbs)), 0)
|| !TEST_true(EVP_MD_CTX_reset(mctx)))
goto err;
/* un-muck and test it verifies */
tbs[0] ^= 1;
if (!TEST_true(EVP_DigestVerifyInit(mctx, NULL, NULL, NULL, pkey))
|| (as == EVP_PKEY_SM2 && !set_sm2_id(mctx, pkey))
|| !TEST_int_eq(EVP_DigestVerify(mctx, sig, sig_len, tbs, sizeof(tbs)), 1)
|| !TEST_true(EVP_MD_CTX_reset(mctx)))
goto err;
/*-
* Muck with the ECDSA signature. The DER encoding is one of:
* - 30 LL 02 ..
* - 30 81 LL 02 ..
*
* - Sometimes this mucks with the high level DER sequence wrapper:
* in that case, DER-parsing of the whole signature should fail.
*
* - Sometimes this mucks with the DER-encoding of ECDSA.r:
* in that case, DER-parsing of ECDSA.r should fail.
*
* - Sometimes this mucks with the DER-encoding of ECDSA.s:
* in that case, DER-parsing of ECDSA.s should fail.
*
* - Sometimes this mucks with ECDSA.r:
* in that case, the signature verification should fail.
*
* - Sometimes this mucks with ECDSA.s:
* in that case, the signature verification should fail.
*
* The usual case is changing the integer value of ECDSA.r or ECDSA.s.
* Because the ratio of DER overhead to signature bytes is small.
* So most of the time it will be one of the last two cases.
*
* In any case, EVP_PKEY_verify should not return 1 for valid.
*/
offset = tbs[0] % sig_len;
dirt = tbs[1] ? tbs[1] : 1;
sig[offset] ^= dirt;
if (!TEST_true(EVP_DigestVerifyInit(mctx, NULL, NULL, NULL, pkey))
|| (as == EVP_PKEY_SM2 && !set_sm2_id(mctx, pkey))
|| !TEST_int_ne(EVP_DigestVerify(mctx, sig, sig_len, tbs, sizeof(tbs)), 1)
|| !TEST_true(EVP_MD_CTX_reset(mctx)))
goto err;
/* un-muck and test it verifies */
sig[offset] ^= dirt;
if (!TEST_true(EVP_DigestVerifyInit(mctx, NULL, NULL, NULL, pkey))
|| (as == EVP_PKEY_SM2 && !set_sm2_id(mctx, pkey))
|| !TEST_int_eq(EVP_DigestVerify(mctx, sig, sig_len, tbs, sizeof(tbs)), 1)
|| !TEST_true(EVP_MD_CTX_reset(mctx)))
goto err;
ret = 1;
err:
EVP_PKEY_free(pkey);
EVP_PKEY_free(pkey_neg);
EVP_PKEY_free(dup_pk);
EVP_MD_CTX_free(mctx);
OPENSSL_free(sig);
return ret;
}
static int test_builtin_as_ec(int n)
{
return test_builtin(n, EVP_PKEY_EC);
}
# ifndef OPENSSL_NO_SM2
static int test_builtin_as_sm2(int n)
{
return test_builtin(n, EVP_PKEY_SM2);
}
# endif
static int test_ecdsa_sig_NULL(void)
{
int ret;
+ unsigned int siglen0;
unsigned int siglen;
unsigned char dgst[128] = { 0 };
EC_KEY *eckey = NULL;
+ unsigned char *sig = NULL;
+ BIGNUM *kinv = NULL, *rp = NULL;
ret = TEST_ptr(eckey = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1))
&& TEST_int_eq(EC_KEY_generate_key(eckey), 1)
- && TEST_int_eq(ECDSA_sign(0, dgst, sizeof(dgst), NULL, &siglen, eckey), 1)
- && TEST_int_gt(siglen, 0);
+ && TEST_int_eq(ECDSA_sign(0, dgst, sizeof(dgst), NULL, &siglen0,
+ eckey), 1)
+ && TEST_int_gt(siglen0, 0)
+ && TEST_ptr(sig = OPENSSL_malloc(siglen0))
+ && TEST_int_eq(ECDSA_sign(0, dgst, sizeof(dgst), sig, &siglen,
+ eckey), 1)
+ && TEST_int_gt(siglen, 0)
+ && TEST_int_le(siglen, siglen0)
+ && TEST_int_eq(ECDSA_verify(0, dgst, sizeof(dgst), sig, siglen,
+ eckey), 1)
+ && TEST_int_eq(ECDSA_sign_setup(eckey, NULL, &kinv, &rp), 1)
+ && TEST_int_eq(ECDSA_sign_ex(0, dgst, sizeof(dgst), NULL, &siglen,
+ kinv, rp, eckey), 1)
+ && TEST_int_gt(siglen, 0)
+ && TEST_int_le(siglen, siglen0)
+ && TEST_int_eq(ECDSA_sign_ex(0, dgst, sizeof(dgst), sig, &siglen0,
+ kinv, rp, eckey), 1)
+ && TEST_int_eq(siglen, siglen0)
+ && TEST_int_eq(ECDSA_verify(0, dgst, sizeof(dgst), sig, siglen,
+ eckey), 1);
EC_KEY_free(eckey);
+ OPENSSL_free(sig);
+ BN_free(kinv);
+ BN_free(rp);
return ret;
}
#endif /* OPENSSL_NO_EC */
int setup_tests(void)
{
#ifdef OPENSSL_NO_EC
TEST_note("Elliptic curves are disabled.");
#else
fake_rand = fake_rand_start(NULL);
if (fake_rand == NULL)
return 0;
/* get a list of all internal curves */
crv_len = EC_get_builtin_curves(NULL, 0);
if (!TEST_ptr(curves = OPENSSL_malloc(sizeof(*curves) * crv_len))
|| !TEST_true(EC_get_builtin_curves(curves, crv_len))) {
fake_rand_finish(fake_rand);
return 0;
}
ADD_ALL_TESTS(test_builtin_as_ec, crv_len);
ADD_TEST(test_ecdsa_sig_NULL);
# ifndef OPENSSL_NO_SM2
ADD_ALL_TESTS(test_builtin_as_sm2, crv_len);
# endif
ADD_ALL_TESTS(x9_62_tests, OSSL_NELEM(ecdsa_cavs_kats));
#endif
return 1;
}
void cleanup_tests(void)
{
#ifndef OPENSSL_NO_EC
fake_rand_finish(fake_rand);
OPENSSL_free(curves);
#endif
}
diff --git a/crypto/openssl/test/ecstresstest.c b/crypto/openssl/test/ecstresstest.c
index 22d46c50da2c..237def095c7e 100644
--- a/crypto/openssl/test/ecstresstest.c
+++ b/crypto/openssl/test/ecstresstest.c
@@ -1,156 +1,156 @@
/*
- * Copyright 2017-2021 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2017-2024 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 "internal/nelem.h"
#include "testutil.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define NUM_REPEATS "1000000"
static ossl_intmax_t num_repeats;
static int print_mode = 0;
#ifndef OPENSSL_NO_EC
# include <openssl/ec.h>
# include <openssl/err.h>
# include <openssl/obj_mac.h>
# include <openssl/objects.h>
# include <openssl/rand.h>
# include <openssl/bn.h>
# include <openssl/opensslconf.h>
static const char *kP256DefaultResult =
"A1E24B223B8E81BC1FFF99BAFB909EDB895FACDE7D6DA5EF5E7B3255FB378E0F";
/*
* Perform a deterministic walk on the curve, by starting from |point| and
* using the X-coordinate of the previous point as the next scalar for
* point multiplication.
* Returns the X-coordinate of the end result or NULL on error.
*/
static BIGNUM *walk_curve(const EC_GROUP *group, EC_POINT *point,
ossl_intmax_t num)
{
BIGNUM *scalar = NULL;
ossl_intmax_t i;
if (!TEST_ptr(scalar = BN_new())
|| !TEST_true(EC_POINT_get_affine_coordinates(group, point, scalar,
NULL, NULL)))
goto err;
for (i = 0; i < num; i++) {
if (!TEST_true(EC_POINT_mul(group, point, NULL, point, scalar, NULL))
|| !TEST_true(EC_POINT_get_affine_coordinates(group, point,
scalar,
NULL, NULL)))
goto err;
}
return scalar;
err:
BN_free(scalar);
return NULL;
}
static int test_curve(void)
{
EC_GROUP *group = NULL;
EC_POINT *point = NULL;
BIGNUM *result = NULL, *expected_result = NULL;
int ret = 0;
/*
* We currently hard-code P-256, though adaptation to other curves.
* would be straightforward.
*/
if (!TEST_ptr(group = EC_GROUP_new_by_curve_name(NID_X9_62_prime256v1))
|| !TEST_ptr(point = EC_POINT_dup(EC_GROUP_get0_generator(group),
group))
|| !TEST_ptr(result = walk_curve(group, point, num_repeats)))
- return 0;
+ goto err;
if (print_mode) {
BN_print(bio_out, result);
BIO_printf(bio_out, "\n");
ret = 1;
} else {
if (!TEST_true(BN_hex2bn(&expected_result, kP256DefaultResult))
|| !TEST_ptr(expected_result)
|| !TEST_BN_eq(result, expected_result))
goto err;
ret = 1;
}
err:
EC_GROUP_free(group);
EC_POINT_free(point);
BN_free(result);
BN_free(expected_result);
return ret;
}
#endif
typedef enum OPTION_choice {
OPT_ERR = -1,
OPT_EOF = 0,
OPT_NUM_REPEATS,
OPT_TEST_ENUM
} OPTION_CHOICE;
const OPTIONS *test_get_options(void)
{
static const OPTIONS test_options[] = {
OPT_TEST_OPTIONS_DEFAULT_USAGE,
{ "num", OPT_NUM_REPEATS, 'M', "Number of repeats" },
{ NULL }
};
return test_options;
}
/*
* Stress test the curve. If the '-num' argument is given, runs the loop
* |num| times and prints the resulting X-coordinate. Otherwise runs the test
* the default number of times and compares against the expected result.
*/
int setup_tests(void)
{
OPTION_CHOICE o;
if (!opt_intmax(NUM_REPEATS, &num_repeats)) {
TEST_error("Cannot parse " NUM_REPEATS);
return 0;
}
while ((o = opt_next()) != OPT_EOF) {
switch (o) {
case OPT_NUM_REPEATS:
if (!opt_intmax(opt_arg(), &num_repeats)
|| num_repeats < 0)
return 0;
print_mode = 1;
break;
case OPT_TEST_CASES:
break;
default:
case OPT_ERR:
return 0;
}
}
#ifndef OPENSSL_NO_EC
ADD_TEST(test_curve);
#endif
return 1;
}
diff --git a/crypto/openssl/test/evp_extra_test.c b/crypto/openssl/test/evp_extra_test.c
index 6b484f8711ce..7e97e2d34d5d 100644
--- a/crypto/openssl/test/evp_extra_test.c
+++ b/crypto/openssl/test/evp_extra_test.c
@@ -1,5480 +1,5526 @@
/*
* Copyright 2015-2024 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
/* We need to use some deprecated APIs */
#define OPENSSL_SUPPRESS_DEPRECATED
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/bio.h>
#include <openssl/conf.h>
#include <openssl/crypto.h>
#include <openssl/err.h>
#include <openssl/evp.h>
#include <openssl/x509.h>
#include <openssl/pem.h>
#include <openssl/kdf.h>
#include <openssl/provider.h>
#include <openssl/core_names.h>
#include <openssl/params.h>
#include <openssl/param_build.h>
#include <openssl/dsa.h>
#include <openssl/dh.h>
#include <openssl/aes.h>
#include <openssl/decoder.h>
#include <openssl/rsa.h>
#include <openssl/engine.h>
#include <openssl/proverr.h>
#include "testutil.h"
#include "internal/nelem.h"
#include "internal/sizes.h"
#include "crypto/evp.h"
#ifdef STATIC_LEGACY
OSSL_provider_init_fn ossl_legacy_provider_init;
#endif
static OSSL_LIB_CTX *testctx = NULL;
static char *testpropq = NULL;
static OSSL_PROVIDER *nullprov = NULL;
static OSSL_PROVIDER *deflprov = NULL;
static OSSL_PROVIDER *lgcyprov = NULL;
/*
* kExampleRSAKeyDER is an RSA private key in ASN.1, DER format. Of course, you
* should never use this key anywhere but in an example.
*/
static const unsigned char kExampleRSAKeyDER[] = {
0x30, 0x82, 0x02, 0x5c, 0x02, 0x01, 0x00, 0x02, 0x81, 0x81, 0x00, 0xf8,
0xb8, 0x6c, 0x83, 0xb4, 0xbc, 0xd9, 0xa8, 0x57, 0xc0, 0xa5, 0xb4, 0x59,
0x76, 0x8c, 0x54, 0x1d, 0x79, 0xeb, 0x22, 0x52, 0x04, 0x7e, 0xd3, 0x37,
0xeb, 0x41, 0xfd, 0x83, 0xf9, 0xf0, 0xa6, 0x85, 0x15, 0x34, 0x75, 0x71,
0x5a, 0x84, 0xa8, 0x3c, 0xd2, 0xef, 0x5a, 0x4e, 0xd3, 0xde, 0x97, 0x8a,
0xdd, 0xff, 0xbb, 0xcf, 0x0a, 0xaa, 0x86, 0x92, 0xbe, 0xb8, 0x50, 0xe4,
0xcd, 0x6f, 0x80, 0x33, 0x30, 0x76, 0x13, 0x8f, 0xca, 0x7b, 0xdc, 0xec,
0x5a, 0xca, 0x63, 0xc7, 0x03, 0x25, 0xef, 0xa8, 0x8a, 0x83, 0x58, 0x76,
0x20, 0xfa, 0x16, 0x77, 0xd7, 0x79, 0x92, 0x63, 0x01, 0x48, 0x1a, 0xd8,
0x7b, 0x67, 0xf1, 0x52, 0x55, 0x49, 0x4e, 0xd6, 0x6e, 0x4a, 0x5c, 0xd7,
0x7a, 0x37, 0x36, 0x0c, 0xde, 0xdd, 0x8f, 0x44, 0xe8, 0xc2, 0xa7, 0x2c,
0x2b, 0xb5, 0xaf, 0x64, 0x4b, 0x61, 0x07, 0x02, 0x03, 0x01, 0x00, 0x01,
0x02, 0x81, 0x80, 0x74, 0x88, 0x64, 0x3f, 0x69, 0x45, 0x3a, 0x6d, 0xc7,
0x7f, 0xb9, 0xa3, 0xc0, 0x6e, 0xec, 0xdc, 0xd4, 0x5a, 0xb5, 0x32, 0x85,
0x5f, 0x19, 0xd4, 0xf8, 0xd4, 0x3f, 0x3c, 0xfa, 0xc2, 0xf6, 0x5f, 0xee,
0xe6, 0xba, 0x87, 0x74, 0x2e, 0xc7, 0x0c, 0xd4, 0x42, 0xb8, 0x66, 0x85,
0x9c, 0x7b, 0x24, 0x61, 0xaa, 0x16, 0x11, 0xf6, 0xb5, 0xb6, 0xa4, 0x0a,
0xc9, 0x55, 0x2e, 0x81, 0xa5, 0x47, 0x61, 0xcb, 0x25, 0x8f, 0xc2, 0x15,
0x7b, 0x0e, 0x7c, 0x36, 0x9f, 0x3a, 0xda, 0x58, 0x86, 0x1c, 0x5b, 0x83,
0x79, 0xe6, 0x2b, 0xcc, 0xe6, 0xfa, 0x2c, 0x61, 0xf2, 0x78, 0x80, 0x1b,
0xe2, 0xf3, 0x9d, 0x39, 0x2b, 0x65, 0x57, 0x91, 0x3d, 0x71, 0x99, 0x73,
0xa5, 0xc2, 0x79, 0x20, 0x8c, 0x07, 0x4f, 0xe5, 0xb4, 0x60, 0x1f, 0x99,
0xa2, 0xb1, 0x4f, 0x0c, 0xef, 0xbc, 0x59, 0x53, 0x00, 0x7d, 0xb1, 0x02,
0x41, 0x00, 0xfc, 0x7e, 0x23, 0x65, 0x70, 0xf8, 0xce, 0xd3, 0x40, 0x41,
0x80, 0x6a, 0x1d, 0x01, 0xd6, 0x01, 0xff, 0xb6, 0x1b, 0x3d, 0x3d, 0x59,
0x09, 0x33, 0x79, 0xc0, 0x4f, 0xde, 0x96, 0x27, 0x4b, 0x18, 0xc6, 0xd9,
0x78, 0xf1, 0xf4, 0x35, 0x46, 0xe9, 0x7c, 0x42, 0x7a, 0x5d, 0x9f, 0xef,
0x54, 0xb8, 0xf7, 0x9f, 0xc4, 0x33, 0x6c, 0xf3, 0x8c, 0x32, 0x46, 0x87,
0x67, 0x30, 0x7b, 0xa7, 0xac, 0xe3, 0x02, 0x41, 0x00, 0xfc, 0x2c, 0xdf,
0x0c, 0x0d, 0x88, 0xf5, 0xb1, 0x92, 0xa8, 0x93, 0x47, 0x63, 0x55, 0xf5,
0xca, 0x58, 0x43, 0xba, 0x1c, 0xe5, 0x9e, 0xb6, 0x95, 0x05, 0xcd, 0xb5,
0x82, 0xdf, 0xeb, 0x04, 0x53, 0x9d, 0xbd, 0xc2, 0x38, 0x16, 0xb3, 0x62,
0xdd, 0xa1, 0x46, 0xdb, 0x6d, 0x97, 0x93, 0x9f, 0x8a, 0xc3, 0x9b, 0x64,
0x7e, 0x42, 0xe3, 0x32, 0x57, 0x19, 0x1b, 0xd5, 0x6e, 0x85, 0xfa, 0xb8,
0x8d, 0x02, 0x41, 0x00, 0xbc, 0x3d, 0xde, 0x6d, 0xd6, 0x97, 0xe8, 0xba,
0x9e, 0x81, 0x37, 0x17, 0xe5, 0xa0, 0x64, 0xc9, 0x00, 0xb7, 0xe7, 0xfe,
0xf4, 0x29, 0xd9, 0x2e, 0x43, 0x6b, 0x19, 0x20, 0xbd, 0x99, 0x75, 0xe7,
0x76, 0xf8, 0xd3, 0xae, 0xaf, 0x7e, 0xb8, 0xeb, 0x81, 0xf4, 0x9d, 0xfe,
0x07, 0x2b, 0x0b, 0x63, 0x0b, 0x5a, 0x55, 0x90, 0x71, 0x7d, 0xf1, 0xdb,
0xd9, 0xb1, 0x41, 0x41, 0x68, 0x2f, 0x4e, 0x39, 0x02, 0x40, 0x5a, 0x34,
0x66, 0xd8, 0xf5, 0xe2, 0x7f, 0x18, 0xb5, 0x00, 0x6e, 0x26, 0x84, 0x27,
0x14, 0x93, 0xfb, 0xfc, 0xc6, 0x0f, 0x5e, 0x27, 0xe6, 0xe1, 0xe9, 0xc0,
0x8a, 0xe4, 0x34, 0xda, 0xe9, 0xa2, 0x4b, 0x73, 0xbc, 0x8c, 0xb9, 0xba,
0x13, 0x6c, 0x7a, 0x2b, 0x51, 0x84, 0xa3, 0x4a, 0xe0, 0x30, 0x10, 0x06,
0x7e, 0xed, 0x17, 0x5a, 0x14, 0x00, 0xc9, 0xef, 0x85, 0xea, 0x52, 0x2c,
0xbc, 0x65, 0x02, 0x40, 0x51, 0xe3, 0xf2, 0x83, 0x19, 0x9b, 0xc4, 0x1e,
0x2f, 0x50, 0x3d, 0xdf, 0x5a, 0xa2, 0x18, 0xca, 0x5f, 0x2e, 0x49, 0xaf,
0x6f, 0xcc, 0xfa, 0x65, 0x77, 0x94, 0xb5, 0xa1, 0x0a, 0xa9, 0xd1, 0x8a,
0x39, 0x37, 0xf4, 0x0b, 0xa0, 0xd7, 0x82, 0x27, 0x5e, 0xae, 0x17, 0x17,
0xa1, 0x1e, 0x54, 0x34, 0xbf, 0x6e, 0xc4, 0x8e, 0x99, 0x5d, 0x08, 0xf1,
0x2d, 0x86, 0x9d, 0xa5, 0x20, 0x1b, 0xe5, 0xdf,
};
/*
* kExampleDSAKeyDER is a DSA private key in ASN.1, DER format. Of course, you
* should never use this key anywhere but in an example.
*/
#ifndef OPENSSL_NO_DSA
static const unsigned char kExampleDSAKeyDER[] = {
0x30, 0x82, 0x01, 0xba, 0x02, 0x01, 0x00, 0x02, 0x81, 0x81, 0x00, 0x9a,
0x05, 0x6d, 0x33, 0xcd, 0x5d, 0x78, 0xa1, 0xbb, 0xcb, 0x7d, 0x5b, 0x8d,
0xb4, 0xcc, 0xbf, 0x03, 0x99, 0x64, 0xde, 0x38, 0x78, 0x06, 0x15, 0x2f,
0x86, 0x26, 0x77, 0xf3, 0xb1, 0x85, 0x00, 0xed, 0xfc, 0x28, 0x3a, 0x42,
0x4d, 0xab, 0xab, 0xdf, 0xbc, 0x9c, 0x16, 0xd0, 0x22, 0x50, 0xd1, 0x38,
0xdd, 0x3f, 0x64, 0x05, 0x9e, 0x68, 0x7a, 0x1e, 0xf1, 0x56, 0xbf, 0x1e,
0x2c, 0xc5, 0x97, 0x2a, 0xfe, 0x7a, 0x22, 0xdc, 0x6c, 0x68, 0xb8, 0x2e,
0x06, 0xdb, 0x41, 0xca, 0x98, 0xd8, 0x54, 0xc7, 0x64, 0x48, 0x24, 0x04,
0x20, 0xbc, 0x59, 0xe3, 0x6b, 0xea, 0x7e, 0xfc, 0x7e, 0xc5, 0x4e, 0xd4,
0xd8, 0x3a, 0xed, 0xcd, 0x5d, 0x99, 0xb8, 0x5c, 0xa2, 0x8b, 0xbb, 0x0b,
0xac, 0xe6, 0x8e, 0x25, 0x56, 0x22, 0x3a, 0x2d, 0x3a, 0x56, 0x41, 0x14,
0x1f, 0x1c, 0x8f, 0x53, 0x46, 0x13, 0x85, 0x02, 0x15, 0x00, 0x98, 0x7e,
0x92, 0x81, 0x88, 0xc7, 0x3f, 0x70, 0x49, 0x54, 0xf6, 0x76, 0xb4, 0xa3,
0x9e, 0x1d, 0x45, 0x98, 0x32, 0x7f, 0x02, 0x81, 0x80, 0x69, 0x4d, 0xef,
0x55, 0xff, 0x4d, 0x59, 0x2c, 0x01, 0xfa, 0x6a, 0x38, 0xe0, 0x70, 0x9f,
0x9e, 0x66, 0x8e, 0x3e, 0x8c, 0x52, 0x22, 0x9d, 0x15, 0x7e, 0x3c, 0xef,
0x4c, 0x7a, 0x61, 0x26, 0xe0, 0x2b, 0x81, 0x3f, 0xeb, 0xaf, 0x35, 0x38,
0x8d, 0xfe, 0xed, 0x46, 0xff, 0x5f, 0x03, 0x9b, 0x81, 0x92, 0xe7, 0x6f,
0x76, 0x4f, 0x1d, 0xd9, 0xbb, 0x89, 0xc9, 0x3e, 0xd9, 0x0b, 0xf9, 0xf4,
0x78, 0x11, 0x59, 0xc0, 0x1d, 0xcd, 0x0e, 0xa1, 0x6f, 0x15, 0xf1, 0x4d,
0xc1, 0xc9, 0x22, 0xed, 0x8d, 0xad, 0x67, 0xc5, 0x4b, 0x95, 0x93, 0x86,
0xa6, 0xaf, 0x8a, 0xee, 0x06, 0x89, 0x2f, 0x37, 0x7e, 0x64, 0xaa, 0xf6,
0xe7, 0xb1, 0x5a, 0x0a, 0x93, 0x95, 0x5d, 0x3e, 0x53, 0x9a, 0xde, 0x8a,
0xc2, 0x95, 0x45, 0x81, 0xbe, 0x5c, 0x2f, 0xc2, 0xb2, 0x92, 0x58, 0x19,
0x72, 0x80, 0xe9, 0x79, 0xa1, 0x02, 0x81, 0x80, 0x07, 0xd7, 0x62, 0xff,
0xdf, 0x1a, 0x3f, 0xed, 0x32, 0xd4, 0xd4, 0x88, 0x7b, 0x2c, 0x63, 0x7f,
0x97, 0xdc, 0x44, 0xd4, 0x84, 0xa2, 0xdd, 0x17, 0x16, 0x85, 0x13, 0xe0,
0xac, 0x51, 0x8d, 0x29, 0x1b, 0x75, 0x9a, 0xe4, 0xe3, 0x8a, 0x92, 0x69,
0x09, 0x03, 0xc5, 0x68, 0xae, 0x5e, 0x94, 0xfe, 0xc9, 0x92, 0x6c, 0x07,
0xb4, 0x1e, 0x64, 0x62, 0x87, 0xc6, 0xa4, 0xfd, 0x0d, 0x5f, 0xe5, 0xf9,
0x1b, 0x4f, 0x85, 0x5f, 0xae, 0xf3, 0x11, 0xe5, 0x18, 0xd4, 0x4d, 0x79,
0x9f, 0xc4, 0x79, 0x26, 0x04, 0x27, 0xf0, 0x0b, 0xee, 0x2b, 0x86, 0x9f,
0x86, 0x61, 0xe6, 0x51, 0xce, 0x04, 0x9b, 0x5d, 0x6b, 0x34, 0x43, 0x8c,
0x85, 0x3c, 0xf1, 0x51, 0x9b, 0x08, 0x23, 0x1b, 0xf5, 0x7e, 0x33, 0x12,
0xea, 0xab, 0x1f, 0xb7, 0x2d, 0xe2, 0x5f, 0xe6, 0x97, 0x99, 0xb5, 0x45,
0x16, 0x5b, 0xc3, 0x41, 0x02, 0x14, 0x61, 0xbf, 0x51, 0x60, 0xcf, 0xc8,
0xf1, 0x8c, 0x82, 0x97, 0xf2, 0xf4, 0x19, 0xba, 0x2b, 0xf3, 0x16, 0xbe,
0x40, 0x48
};
#endif
/*
* kExampleBadRSAKeyDER is an RSA private key in ASN.1, DER format. The private
* components are not correct.
*/
static const unsigned char kExampleBadRSAKeyDER[] = {
0x30, 0x82, 0x04, 0x27, 0x02, 0x01, 0x00, 0x02, 0x82, 0x01, 0x01, 0x00,
0xa6, 0x1a, 0x1e, 0x6e, 0x7b, 0xee, 0xc6, 0x89, 0x66, 0xe7, 0x93, 0xef,
0x54, 0x12, 0x68, 0xea, 0xbf, 0x86, 0x2f, 0xdd, 0xd2, 0x79, 0xb8, 0xa9,
0x6e, 0x03, 0xc2, 0xa3, 0xb9, 0xa3, 0xe1, 0x4b, 0x2a, 0xb3, 0xf8, 0xb4,
0xcd, 0xea, 0xbe, 0x24, 0xa6, 0x57, 0x5b, 0x83, 0x1f, 0x0f, 0xf2, 0xd3,
0xb7, 0xac, 0x7e, 0xd6, 0x8e, 0x6e, 0x1e, 0xbf, 0xb8, 0x73, 0x8c, 0x05,
0x56, 0xe6, 0x35, 0x1f, 0xe9, 0x04, 0x0b, 0x09, 0x86, 0x7d, 0xf1, 0x26,
0x08, 0x99, 0xad, 0x7b, 0xc8, 0x4d, 0x94, 0xb0, 0x0b, 0x8b, 0x38, 0xa0,
0x5c, 0x62, 0xa0, 0xab, 0xd3, 0x8f, 0xd4, 0x09, 0x60, 0x72, 0x1e, 0x33,
0x50, 0x80, 0x6e, 0x22, 0xa6, 0x77, 0x57, 0x6b, 0x9a, 0x33, 0x21, 0x66,
0x87, 0x6e, 0x21, 0x7b, 0xc7, 0x24, 0x0e, 0xd8, 0x13, 0xdf, 0x83, 0xde,
0xcd, 0x40, 0x58, 0x1d, 0x84, 0x86, 0xeb, 0xb8, 0x12, 0x4e, 0xd2, 0xfa,
0x80, 0x1f, 0xe4, 0xe7, 0x96, 0x29, 0xb8, 0xcc, 0xce, 0x66, 0x6d, 0x53,
0xca, 0xb9, 0x5a, 0xd7, 0xf6, 0x84, 0x6c, 0x2d, 0x9a, 0x1a, 0x14, 0x1c,
0x4e, 0x93, 0x39, 0xba, 0x74, 0xed, 0xed, 0x87, 0x87, 0x5e, 0x48, 0x75,
0x36, 0xf0, 0xbc, 0x34, 0xfb, 0x29, 0xf9, 0x9f, 0x96, 0x5b, 0x0b, 0xa7,
0x54, 0x30, 0x51, 0x29, 0x18, 0x5b, 0x7d, 0xac, 0x0f, 0xd6, 0x5f, 0x7c,
0xf8, 0x98, 0x8c, 0xd8, 0x86, 0x62, 0xb3, 0xdc, 0xff, 0x0f, 0xff, 0x7a,
0xaf, 0x5c, 0x4c, 0x61, 0x49, 0x2e, 0xc8, 0x95, 0x86, 0xc4, 0x0e, 0x87,
0xfc, 0x1d, 0xcf, 0x8b, 0x7c, 0x61, 0xf6, 0xd8, 0xd0, 0x69, 0xf6, 0xcd,
0x8a, 0x8c, 0xf6, 0x62, 0xa2, 0x56, 0xa9, 0xe3, 0xd1, 0xcf, 0x4d, 0xa0,
0xf6, 0x2d, 0x20, 0x0a, 0x04, 0xb7, 0xa2, 0xf7, 0xb5, 0x99, 0x47, 0x18,
0x56, 0x85, 0x87, 0xc7, 0x02, 0x03, 0x01, 0x00, 0x01, 0x02, 0x82, 0x01,
0x01, 0x00, 0x99, 0x41, 0x38, 0x1a, 0xd0, 0x96, 0x7a, 0xf0, 0x83, 0xd5,
0xdf, 0x94, 0xce, 0x89, 0x3d, 0xec, 0x7a, 0x52, 0x21, 0x10, 0x16, 0x06,
0xe0, 0xee, 0xd2, 0xe6, 0xfd, 0x4b, 0x7b, 0x19, 0x4d, 0xe1, 0xc0, 0xc0,
0xd5, 0x14, 0x5d, 0x79, 0xdd, 0x7e, 0x8b, 0x4b, 0xc6, 0xcf, 0xb0, 0x75,
0x52, 0xa3, 0x2d, 0xb1, 0x26, 0x46, 0x68, 0x9c, 0x0a, 0x1a, 0xf2, 0xe1,
0x09, 0xac, 0x53, 0x85, 0x8c, 0x36, 0xa9, 0x14, 0x65, 0xea, 0xa0, 0x00,
0xcb, 0xe3, 0x3f, 0xc4, 0x2b, 0x61, 0x2e, 0x6b, 0x06, 0x69, 0x77, 0xfd,
0x38, 0x7e, 0x1d, 0x3f, 0x92, 0xe7, 0x77, 0x08, 0x19, 0xa7, 0x9d, 0x29,
0x2d, 0xdc, 0x42, 0xc6, 0x7c, 0xd7, 0xd3, 0xa8, 0x01, 0x2c, 0xf2, 0xd5,
0x82, 0x57, 0xcb, 0x55, 0x3d, 0xe7, 0xaa, 0xd2, 0x06, 0x30, 0x30, 0x05,
0xe6, 0xf2, 0x47, 0x86, 0xba, 0xc6, 0x61, 0x64, 0xeb, 0x4f, 0x2a, 0x5e,
0x07, 0x29, 0xe0, 0x96, 0xb2, 0x43, 0xff, 0x5f, 0x1a, 0x54, 0x16, 0xcf,
0xb5, 0x56, 0x5c, 0xa0, 0x9b, 0x0c, 0xfd, 0xb3, 0xd2, 0xe3, 0x79, 0x1d,
0x21, 0xe2, 0xd6, 0x13, 0xc4, 0x74, 0xa6, 0xf5, 0x8e, 0x8e, 0x81, 0xbb,
0xb4, 0xad, 0x8a, 0xf0, 0x93, 0x0a, 0xd8, 0x0a, 0x42, 0x36, 0xbc, 0xe5,
0x26, 0x2a, 0x0d, 0x5d, 0x57, 0x13, 0xc5, 0x4e, 0x2f, 0x12, 0x0e, 0xef,
0xa7, 0x81, 0x1e, 0xc3, 0xa5, 0xdb, 0xc9, 0x24, 0xeb, 0x1a, 0xa1, 0xf9,
0xf6, 0xa1, 0x78, 0x98, 0x93, 0x77, 0x42, 0x45, 0x03, 0xe2, 0xc9, 0xa2,
0xfe, 0x2d, 0x77, 0xc8, 0xc6, 0xac, 0x9b, 0x98, 0x89, 0x6d, 0x9a, 0xe7,
0x61, 0x63, 0xb7, 0xf2, 0xec, 0xd6, 0xb1, 0xa1, 0x6e, 0x0a, 0x1a, 0xff,
0xfd, 0x43, 0x28, 0xc3, 0x0c, 0xdc, 0xf2, 0x47, 0x4f, 0x27, 0xaa, 0x99,
0x04, 0x8e, 0xac, 0xe8, 0x7c, 0x01, 0x02, 0x04, 0x12, 0x34, 0x56, 0x78,
0x02, 0x81, 0x81, 0x00, 0xca, 0x69, 0xe5, 0xbb, 0x3a, 0x90, 0x82, 0xcb,
0x82, 0x50, 0x2f, 0x29, 0xe2, 0x76, 0x6a, 0x57, 0x55, 0x45, 0x4e, 0x35,
0x18, 0x61, 0xe0, 0x12, 0x70, 0xc0, 0xab, 0xc7, 0x80, 0xa2, 0xd4, 0x46,
0x34, 0x03, 0xa0, 0x19, 0x26, 0x23, 0x9e, 0xef, 0x1a, 0xcb, 0x75, 0xd6,
0xba, 0x81, 0xf4, 0x7e, 0x52, 0xe5, 0x2a, 0xe8, 0xf1, 0x49, 0x6c, 0x0f,
0x1a, 0xa0, 0xf9, 0xc6, 0xe7, 0xec, 0x60, 0xe4, 0xcb, 0x2a, 0xb5, 0x56,
0xe9, 0x9c, 0xcd, 0x19, 0x75, 0x92, 0xb1, 0x66, 0xce, 0xc3, 0xd9, 0x3d,
0x11, 0xcb, 0xc4, 0x09, 0xce, 0x1e, 0x30, 0xba, 0x2f, 0x60, 0x60, 0x55,
0x8d, 0x02, 0xdc, 0x5d, 0xaf, 0xf7, 0x52, 0x31, 0x17, 0x07, 0x53, 0x20,
0x33, 0xad, 0x8c, 0xd5, 0x2f, 0x5a, 0xd0, 0x57, 0xd7, 0xd1, 0x80, 0xd6,
0x3a, 0x9b, 0x04, 0x4f, 0x35, 0xbf, 0xe7, 0xd5, 0xbc, 0x8f, 0xd4, 0x81,
0x02, 0x81, 0x81, 0x00, 0xc0, 0x9f, 0xf8, 0xcd, 0xf7, 0x3f, 0x26, 0x8a,
0x3d, 0x4d, 0x2b, 0x0c, 0x01, 0xd0, 0xa2, 0xb4, 0x18, 0xfe, 0xf7, 0x5e,
0x2f, 0x06, 0x13, 0xcd, 0x63, 0xaa, 0x12, 0xa9, 0x24, 0x86, 0xe3, 0xf3,
0x7b, 0xda, 0x1a, 0x3c, 0xb1, 0x38, 0x80, 0x80, 0xef, 0x64, 0x64, 0xa1,
0x9b, 0xfe, 0x76, 0x63, 0x8e, 0x83, 0xd2, 0xd9, 0xb9, 0x86, 0xb0, 0xe6,
0xa6, 0x0c, 0x7e, 0xa8, 0x84, 0x90, 0x98, 0x0c, 0x1e, 0xf3, 0x14, 0x77,
0xe0, 0x5f, 0x81, 0x08, 0x11, 0x8f, 0xa6, 0x23, 0xc4, 0xba, 0xc0, 0x8a,
0xe4, 0xc6, 0xe3, 0x5c, 0xbe, 0xc5, 0xec, 0x2c, 0xb9, 0xd8, 0x8c, 0x4d,
0x1a, 0x9d, 0xe7, 0x7c, 0x85, 0x4c, 0x0d, 0x71, 0x4e, 0x72, 0x33, 0x1b,
0xfe, 0xa9, 0x17, 0x72, 0x76, 0x56, 0x9d, 0x74, 0x7e, 0x52, 0x67, 0x9a,
0x87, 0x9a, 0xdb, 0x30, 0xde, 0xe4, 0x49, 0x28, 0x3b, 0xd2, 0x67, 0xaf,
0x02, 0x81, 0x81, 0x00, 0x89, 0x74, 0x9a, 0x8e, 0xa7, 0xb9, 0xa5, 0x28,
0xc0, 0x68, 0xe5, 0x6e, 0x63, 0x1c, 0x99, 0x20, 0x8f, 0x86, 0x8e, 0x12,
0x9e, 0x69, 0x30, 0xfa, 0x34, 0xd9, 0x92, 0x8d, 0xdb, 0x7c, 0x37, 0xfd,
0x28, 0xab, 0x61, 0x98, 0x52, 0x7f, 0x14, 0x1a, 0x39, 0xae, 0xfb, 0x6a,
0x03, 0xa3, 0xe6, 0xbd, 0xb6, 0x5b, 0x6b, 0xe5, 0x5e, 0x9d, 0xc6, 0xa5,
0x07, 0x27, 0x54, 0x17, 0xd0, 0x3d, 0x84, 0x9b, 0x3a, 0xa0, 0xd9, 0x1e,
0x99, 0x6c, 0x63, 0x17, 0xab, 0xf1, 0x1f, 0x49, 0xba, 0x95, 0xe3, 0x3b,
0x86, 0x8f, 0x42, 0xa4, 0x89, 0xf5, 0x94, 0x8f, 0x8b, 0x46, 0xbe, 0x84,
0xba, 0x4a, 0xbc, 0x0d, 0x5f, 0x46, 0xeb, 0xe8, 0xec, 0x43, 0x8c, 0x1e,
0xad, 0x19, 0x69, 0x2f, 0x08, 0x86, 0x7a, 0x3f, 0x7d, 0x0f, 0x07, 0x97,
0xf3, 0x9a, 0x7b, 0xb5, 0xb2, 0xc1, 0x8c, 0x95, 0x68, 0x04, 0xa0, 0x81,
0x02, 0x81, 0x80, 0x4e, 0xbf, 0x7e, 0x1b, 0xcb, 0x13, 0x61, 0x75, 0x3b,
0xdb, 0x59, 0x5f, 0xb1, 0xd4, 0xb8, 0xeb, 0x9e, 0x73, 0xb5, 0xe7, 0xf6,
0x89, 0x3d, 0x1c, 0xda, 0xf0, 0x36, 0xff, 0x35, 0xbd, 0x1e, 0x0b, 0x74,
0xe3, 0x9e, 0xf0, 0xf2, 0xf7, 0xd7, 0x82, 0xb7, 0x7b, 0x6a, 0x1b, 0x0e,
0x30, 0x4a, 0x98, 0x0e, 0xb4, 0xf9, 0x81, 0x07, 0xe4, 0x75, 0x39, 0xe9,
0x53, 0xca, 0xbb, 0x5c, 0xaa, 0x93, 0x07, 0x0e, 0xa8, 0x2f, 0xba, 0x98,
0x49, 0x30, 0xa7, 0xcc, 0x1a, 0x3c, 0x68, 0x0c, 0xe1, 0xa4, 0xb1, 0x05,
0xe6, 0xe0, 0x25, 0x78, 0x58, 0x14, 0x37, 0xf5, 0x1f, 0xe3, 0x22, 0xef,
0xa8, 0x0e, 0x22, 0xa0, 0x94, 0x3a, 0xf6, 0xc9, 0x13, 0xe6, 0x06, 0xbf,
0x7f, 0x99, 0xc6, 0xcc, 0xd8, 0xc6, 0xbe, 0xd9, 0x2e, 0x24, 0xc7, 0x69,
0x8c, 0x95, 0xba, 0xf6, 0x04, 0xb3, 0x0a, 0xf4, 0xcb, 0xf0, 0xce,
};
/*
* kExampleBad2RSAKeyDER is an RSA private key in ASN.1, DER format. All
* values are 0.
*/
static const unsigned char kExampleBad2RSAKeyDER[] = {
0x30, 0x1b, 0x02, 0x01, 0x00, 0x02, 0x01, 0x00, 0x02, 0x01, 0x00, 0x02,
0x01, 0x00, 0x02, 0x01, 0x00, 0x02, 0x01, 0x00, 0x02, 0x01, 0x00, 0x02,
0x01, 0x00, 0x02, 0x01, 0x00
};
static const unsigned char kMsg[] = { 1, 2, 3, 4 };
static const unsigned char kSignature[] = {
0xa5, 0xf0, 0x8a, 0x47, 0x5d, 0x3c, 0xb3, 0xcc, 0xa9, 0x79, 0xaf, 0x4d,
0x8c, 0xae, 0x4c, 0x14, 0xef, 0xc2, 0x0b, 0x34, 0x36, 0xde, 0xf4, 0x3e,
0x3d, 0xbb, 0x4a, 0x60, 0x5c, 0xc8, 0x91, 0x28, 0xda, 0xfb, 0x7e, 0x04,
0x96, 0x7e, 0x63, 0x13, 0x90, 0xce, 0xb9, 0xb4, 0x62, 0x7a, 0xfd, 0x09,
0x3d, 0xc7, 0x67, 0x78, 0x54, 0x04, 0xeb, 0x52, 0x62, 0x6e, 0x24, 0x67,
0xb4, 0x40, 0xfc, 0x57, 0x62, 0xc6, 0xf1, 0x67, 0xc1, 0x97, 0x8f, 0x6a,
0xa8, 0xae, 0x44, 0x46, 0x5e, 0xab, 0x67, 0x17, 0x53, 0x19, 0x3a, 0xda,
0x5a, 0xc8, 0x16, 0x3e, 0x86, 0xd5, 0xc5, 0x71, 0x2f, 0xfc, 0x23, 0x48,
0xd9, 0x0b, 0x13, 0xdd, 0x7b, 0x5a, 0x25, 0x79, 0xef, 0xa5, 0x7b, 0x04,
0xed, 0x44, 0xf6, 0x18, 0x55, 0xe4, 0x0a, 0xe9, 0x57, 0x79, 0x5d, 0xd7,
0x55, 0xa7, 0xab, 0x45, 0x02, 0x97, 0x60, 0x42,
};
/*
* kExampleRSAKeyPKCS8 is kExampleRSAKeyDER encoded in a PKCS #8
* PrivateKeyInfo.
*/
static const unsigned char kExampleRSAKeyPKCS8[] = {
0x30, 0x82, 0x02, 0x76, 0x02, 0x01, 0x00, 0x30, 0x0d, 0x06, 0x09, 0x2a,
0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00, 0x04, 0x82,
0x02, 0x60, 0x30, 0x82, 0x02, 0x5c, 0x02, 0x01, 0x00, 0x02, 0x81, 0x81,
0x00, 0xf8, 0xb8, 0x6c, 0x83, 0xb4, 0xbc, 0xd9, 0xa8, 0x57, 0xc0, 0xa5,
0xb4, 0x59, 0x76, 0x8c, 0x54, 0x1d, 0x79, 0xeb, 0x22, 0x52, 0x04, 0x7e,
0xd3, 0x37, 0xeb, 0x41, 0xfd, 0x83, 0xf9, 0xf0, 0xa6, 0x85, 0x15, 0x34,
0x75, 0x71, 0x5a, 0x84, 0xa8, 0x3c, 0xd2, 0xef, 0x5a, 0x4e, 0xd3, 0xde,
0x97, 0x8a, 0xdd, 0xff, 0xbb, 0xcf, 0x0a, 0xaa, 0x86, 0x92, 0xbe, 0xb8,
0x50, 0xe4, 0xcd, 0x6f, 0x80, 0x33, 0x30, 0x76, 0x13, 0x8f, 0xca, 0x7b,
0xdc, 0xec, 0x5a, 0xca, 0x63, 0xc7, 0x03, 0x25, 0xef, 0xa8, 0x8a, 0x83,
0x58, 0x76, 0x20, 0xfa, 0x16, 0x77, 0xd7, 0x79, 0x92, 0x63, 0x01, 0x48,
0x1a, 0xd8, 0x7b, 0x67, 0xf1, 0x52, 0x55, 0x49, 0x4e, 0xd6, 0x6e, 0x4a,
0x5c, 0xd7, 0x7a, 0x37, 0x36, 0x0c, 0xde, 0xdd, 0x8f, 0x44, 0xe8, 0xc2,
0xa7, 0x2c, 0x2b, 0xb5, 0xaf, 0x64, 0x4b, 0x61, 0x07, 0x02, 0x03, 0x01,
0x00, 0x01, 0x02, 0x81, 0x80, 0x74, 0x88, 0x64, 0x3f, 0x69, 0x45, 0x3a,
0x6d, 0xc7, 0x7f, 0xb9, 0xa3, 0xc0, 0x6e, 0xec, 0xdc, 0xd4, 0x5a, 0xb5,
0x32, 0x85, 0x5f, 0x19, 0xd4, 0xf8, 0xd4, 0x3f, 0x3c, 0xfa, 0xc2, 0xf6,
0x5f, 0xee, 0xe6, 0xba, 0x87, 0x74, 0x2e, 0xc7, 0x0c, 0xd4, 0x42, 0xb8,
0x66, 0x85, 0x9c, 0x7b, 0x24, 0x61, 0xaa, 0x16, 0x11, 0xf6, 0xb5, 0xb6,
0xa4, 0x0a, 0xc9, 0x55, 0x2e, 0x81, 0xa5, 0x47, 0x61, 0xcb, 0x25, 0x8f,
0xc2, 0x15, 0x7b, 0x0e, 0x7c, 0x36, 0x9f, 0x3a, 0xda, 0x58, 0x86, 0x1c,
0x5b, 0x83, 0x79, 0xe6, 0x2b, 0xcc, 0xe6, 0xfa, 0x2c, 0x61, 0xf2, 0x78,
0x80, 0x1b, 0xe2, 0xf3, 0x9d, 0x39, 0x2b, 0x65, 0x57, 0x91, 0x3d, 0x71,
0x99, 0x73, 0xa5, 0xc2, 0x79, 0x20, 0x8c, 0x07, 0x4f, 0xe5, 0xb4, 0x60,
0x1f, 0x99, 0xa2, 0xb1, 0x4f, 0x0c, 0xef, 0xbc, 0x59, 0x53, 0x00, 0x7d,
0xb1, 0x02, 0x41, 0x00, 0xfc, 0x7e, 0x23, 0x65, 0x70, 0xf8, 0xce, 0xd3,
0x40, 0x41, 0x80, 0x6a, 0x1d, 0x01, 0xd6, 0x01, 0xff, 0xb6, 0x1b, 0x3d,
0x3d, 0x59, 0x09, 0x33, 0x79, 0xc0, 0x4f, 0xde, 0x96, 0x27, 0x4b, 0x18,
0xc6, 0xd9, 0x78, 0xf1, 0xf4, 0x35, 0x46, 0xe9, 0x7c, 0x42, 0x7a, 0x5d,
0x9f, 0xef, 0x54, 0xb8, 0xf7, 0x9f, 0xc4, 0x33, 0x6c, 0xf3, 0x8c, 0x32,
0x46, 0x87, 0x67, 0x30, 0x7b, 0xa7, 0xac, 0xe3, 0x02, 0x41, 0x00, 0xfc,
0x2c, 0xdf, 0x0c, 0x0d, 0x88, 0xf5, 0xb1, 0x92, 0xa8, 0x93, 0x47, 0x63,
0x55, 0xf5, 0xca, 0x58, 0x43, 0xba, 0x1c, 0xe5, 0x9e, 0xb6, 0x95, 0x05,
0xcd, 0xb5, 0x82, 0xdf, 0xeb, 0x04, 0x53, 0x9d, 0xbd, 0xc2, 0x38, 0x16,
0xb3, 0x62, 0xdd, 0xa1, 0x46, 0xdb, 0x6d, 0x97, 0x93, 0x9f, 0x8a, 0xc3,
0x9b, 0x64, 0x7e, 0x42, 0xe3, 0x32, 0x57, 0x19, 0x1b, 0xd5, 0x6e, 0x85,
0xfa, 0xb8, 0x8d, 0x02, 0x41, 0x00, 0xbc, 0x3d, 0xde, 0x6d, 0xd6, 0x97,
0xe8, 0xba, 0x9e, 0x81, 0x37, 0x17, 0xe5, 0xa0, 0x64, 0xc9, 0x00, 0xb7,
0xe7, 0xfe, 0xf4, 0x29, 0xd9, 0x2e, 0x43, 0x6b, 0x19, 0x20, 0xbd, 0x99,
0x75, 0xe7, 0x76, 0xf8, 0xd3, 0xae, 0xaf, 0x7e, 0xb8, 0xeb, 0x81, 0xf4,
0x9d, 0xfe, 0x07, 0x2b, 0x0b, 0x63, 0x0b, 0x5a, 0x55, 0x90, 0x71, 0x7d,
0xf1, 0xdb, 0xd9, 0xb1, 0x41, 0x41, 0x68, 0x2f, 0x4e, 0x39, 0x02, 0x40,
0x5a, 0x34, 0x66, 0xd8, 0xf5, 0xe2, 0x7f, 0x18, 0xb5, 0x00, 0x6e, 0x26,
0x84, 0x27, 0x14, 0x93, 0xfb, 0xfc, 0xc6, 0x0f, 0x5e, 0x27, 0xe6, 0xe1,
0xe9, 0xc0, 0x8a, 0xe4, 0x34, 0xda, 0xe9, 0xa2, 0x4b, 0x73, 0xbc, 0x8c,
0xb9, 0xba, 0x13, 0x6c, 0x7a, 0x2b, 0x51, 0x84, 0xa3, 0x4a, 0xe0, 0x30,
0x10, 0x06, 0x7e, 0xed, 0x17, 0x5a, 0x14, 0x00, 0xc9, 0xef, 0x85, 0xea,
0x52, 0x2c, 0xbc, 0x65, 0x02, 0x40, 0x51, 0xe3, 0xf2, 0x83, 0x19, 0x9b,
0xc4, 0x1e, 0x2f, 0x50, 0x3d, 0xdf, 0x5a, 0xa2, 0x18, 0xca, 0x5f, 0x2e,
0x49, 0xaf, 0x6f, 0xcc, 0xfa, 0x65, 0x77, 0x94, 0xb5, 0xa1, 0x0a, 0xa9,
0xd1, 0x8a, 0x39, 0x37, 0xf4, 0x0b, 0xa0, 0xd7, 0x82, 0x27, 0x5e, 0xae,
0x17, 0x17, 0xa1, 0x1e, 0x54, 0x34, 0xbf, 0x6e, 0xc4, 0x8e, 0x99, 0x5d,
0x08, 0xf1, 0x2d, 0x86, 0x9d, 0xa5, 0x20, 0x1b, 0xe5, 0xdf,
};
#ifndef OPENSSL_NO_EC
/*
* kExampleECKeyDER is a sample EC private key encoded as an ECPrivateKey
* structure.
*/
static const unsigned char kExampleECKeyDER[] = {
0x30, 0x77, 0x02, 0x01, 0x01, 0x04, 0x20, 0x07, 0x0f, 0x08, 0x72, 0x7a,
0xd4, 0xa0, 0x4a, 0x9c, 0xdd, 0x59, 0xc9, 0x4d, 0x89, 0x68, 0x77, 0x08,
0xb5, 0x6f, 0xc9, 0x5d, 0x30, 0x77, 0x0e, 0xe8, 0xd1, 0xc9, 0xce, 0x0a,
0x8b, 0xb4, 0x6a, 0xa0, 0x0a, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d,
0x03, 0x01, 0x07, 0xa1, 0x44, 0x03, 0x42, 0x00, 0x04, 0xe6, 0x2b, 0x69,
0xe2, 0xbf, 0x65, 0x9f, 0x97, 0xbe, 0x2f, 0x1e, 0x0d, 0x94, 0x8a, 0x4c,
0xd5, 0x97, 0x6b, 0xb7, 0xa9, 0x1e, 0x0d, 0x46, 0xfb, 0xdd, 0xa9, 0xa9,
0x1e, 0x9d, 0xdc, 0xba, 0x5a, 0x01, 0xe7, 0xd6, 0x97, 0xa8, 0x0a, 0x18,
0xf9, 0xc3, 0xc4, 0xa3, 0x1e, 0x56, 0xe2, 0x7c, 0x83, 0x48, 0xdb, 0x16,
0x1a, 0x1c, 0xf5, 0x1d, 0x7e, 0xf1, 0x94, 0x2d, 0x4b, 0xcf, 0x72, 0x22,
0xc1,
};
/*
* kExampleBadECKeyDER is a sample EC private key encoded as an ECPrivateKey
* structure. The private key is equal to the order and will fail to import
*/
static const unsigned char kExampleBadECKeyDER[] = {
0x30, 0x66, 0x02, 0x01, 0x00, 0x30, 0x13, 0x06, 0x07, 0x2A, 0x86, 0x48,
0xCE, 0x3D, 0x02, 0x01, 0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03,
0x01, 0x07, 0x04, 0x4C, 0x30, 0x4A, 0x02, 0x01, 0x01, 0x04, 0x20, 0xFF,
0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xBC, 0xE6, 0xFA, 0xAD, 0xA7, 0x17, 0x9E, 0x84, 0xF3,
0xB9, 0xCA, 0xC2, 0xFC, 0x63, 0x25, 0x51, 0xA1, 0x23, 0x03, 0x21, 0x00,
0x00, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xBC, 0xE6, 0xFA, 0xAD, 0xA7, 0x17, 0x9E, 0x84,
0xF3, 0xB9, 0xCA, 0xC2, 0xFC, 0x63, 0x25, 0x51
};
/* prime256v1 */
static const unsigned char kExampleECPubKeyDER[] = {
0x30, 0x59, 0x30, 0x13, 0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02,
0x01, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07, 0x03,
0x42, 0x00, 0x04, 0xba, 0xeb, 0x83, 0xfb, 0x3b, 0xb2, 0xff, 0x30, 0x53,
0xdb, 0xce, 0x32, 0xf2, 0xac, 0xae, 0x44, 0x0d, 0x3d, 0x13, 0x53, 0xb8,
0xd1, 0x68, 0x55, 0xde, 0x44, 0x46, 0x05, 0xa6, 0xc9, 0xd2, 0x04, 0xb7,
0xe3, 0xa2, 0x96, 0xc8, 0xb2, 0x5e, 0x22, 0x03, 0xd7, 0x03, 0x7a, 0x8b,
0x13, 0x5c, 0x42, 0x49, 0xc2, 0xab, 0x86, 0xd6, 0xac, 0x6b, 0x93, 0x20,
0x56, 0x6a, 0xc6, 0xc8, 0xa5, 0x0b, 0xe5
};
/*
* kExampleBadECPubKeyDER is a sample EC public key with a wrong OID
* 1.2.840.10045.2.2 instead of 1.2.840.10045.2.1 - EC Public Key
*/
static const unsigned char kExampleBadECPubKeyDER[] = {
0x30, 0x59, 0x30, 0x13, 0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02,
0x02, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07, 0x03,
0x42, 0x00, 0x04, 0xba, 0xeb, 0x83, 0xfb, 0x3b, 0xb2, 0xff, 0x30, 0x53,
0xdb, 0xce, 0x32, 0xf2, 0xac, 0xae, 0x44, 0x0d, 0x3d, 0x13, 0x53, 0xb8,
0xd1, 0x68, 0x55, 0xde, 0x44, 0x46, 0x05, 0xa6, 0xc9, 0xd2, 0x04, 0xb7,
0xe3, 0xa2, 0x96, 0xc8, 0xb2, 0x5e, 0x22, 0x03, 0xd7, 0x03, 0x7a, 0x8b,
0x13, 0x5c, 0x42, 0x49, 0xc2, 0xab, 0x86, 0xd6, 0xac, 0x6b, 0x93, 0x20,
0x56, 0x6a, 0xc6, 0xc8, 0xa5, 0x0b, 0xe5
};
static const unsigned char pExampleECParamDER[] = {
0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07
};
static const unsigned char kExampleED25519KeyDER[] = {
0x30, 0x2e, 0x02, 0x01, 0x00, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x70,
0x04, 0x22, 0x04, 0x20, 0xba, 0x7b, 0xba, 0x20, 0x1b, 0x02, 0x75, 0x3a,
0xe8, 0x88, 0xfe, 0x00, 0xcd, 0x8b, 0xc6, 0xf4, 0x5c, 0x47, 0x09, 0x46,
0x66, 0xe4, 0x72, 0x85, 0x25, 0x26, 0x5e, 0x12, 0x33, 0x48, 0xf6, 0x50
};
static const unsigned char kExampleED25519PubKeyDER[] = {
0x30, 0x2a, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x70, 0x03, 0x21, 0x00,
0xf5, 0xc5, 0xeb, 0x52, 0x3e, 0x7d, 0x07, 0x86, 0xb2, 0x55, 0x07, 0x45,
0xef, 0x5b, 0x7c, 0x20, 0xe8, 0x66, 0x28, 0x30, 0x3c, 0x8a, 0x82, 0x40,
0x97, 0xa3, 0x08, 0xdc, 0x65, 0x80, 0x39, 0x29
};
# ifndef OPENSSL_NO_DEPRECATED_3_0
static const unsigned char kExampleX25519KeyDER[] = {
0x30, 0x2e, 0x02, 0x01, 0x00, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x6e,
0x04, 0x22, 0x04, 0x20, 0xa0, 0x24, 0x3a, 0x31, 0x24, 0xc3, 0x3f, 0xf6,
0x7b, 0x96, 0x0b, 0xd4, 0x8f, 0xd1, 0xee, 0x67, 0xf2, 0x9b, 0x88, 0xac,
0x50, 0xce, 0x97, 0x36, 0xdd, 0xaf, 0x25, 0xf6, 0x10, 0x34, 0x96, 0x6e
};
# endif
#endif
/* kExampleDHKeyDER is a DH private key in ASN.1, DER format. */
#ifndef OPENSSL_NO_DEPRECATED_3_0
# ifndef OPENSSL_NO_DH
static const unsigned char kExampleDHKeyDER[] = {
0x30, 0x82, 0x01, 0x21, 0x02, 0x01, 0x00, 0x30, 0x81, 0x95, 0x06, 0x09,
0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x03, 0x01, 0x30, 0x81, 0x87,
0x02, 0x81, 0x81, 0x00, 0xf7, 0x52, 0xc2, 0x68, 0xcc, 0x66, 0xc4, 0x8d,
0x03, 0x3f, 0xfa, 0x9c, 0x52, 0xd0, 0xd8, 0x33, 0xf2, 0xe1, 0xc9, 0x9e,
0xb7, 0xe7, 0x6e, 0x90, 0x97, 0xeb, 0x92, 0x91, 0x6a, 0x9a, 0x85, 0x63,
0x92, 0x79, 0xab, 0xb6, 0x3d, 0x23, 0x58, 0x5a, 0xe8, 0x45, 0x06, 0x81,
0x97, 0x77, 0xe1, 0xcc, 0x34, 0x4e, 0xae, 0x36, 0x80, 0xf2, 0xc4, 0x7f,
0x8a, 0x52, 0xb8, 0xdb, 0x58, 0xc8, 0x4b, 0x12, 0x4c, 0xf1, 0x4c, 0x53,
0xc1, 0x89, 0x39, 0x8d, 0xb6, 0x06, 0xd8, 0xea, 0x7f, 0x2d, 0x36, 0x53,
0x96, 0x29, 0xbe, 0xb6, 0x75, 0xfc, 0xe7, 0xf3, 0x36, 0xd6, 0xf4, 0x8f,
0x16, 0xa6, 0xc7, 0xec, 0x7b, 0xce, 0x42, 0x8d, 0x48, 0x2e, 0xb7, 0x74,
0x00, 0x11, 0x52, 0x61, 0xb4, 0x19, 0x35, 0xec, 0x5c, 0xe4, 0xbe, 0x34,
0xc6, 0x59, 0x64, 0x5e, 0x42, 0x61, 0x70, 0x54, 0xf4, 0xe9, 0x6b, 0x53,
0x02, 0x01, 0x02, 0x04, 0x81, 0x83, 0x02, 0x81, 0x80, 0x64, 0xc2, 0xe3,
0x09, 0x69, 0x37, 0x3c, 0xd2, 0x4a, 0xba, 0xc3, 0x78, 0x6a, 0x9b, 0x8a,
0x2a, 0xdb, 0xe7, 0xe6, 0xc0, 0xfa, 0x3a, 0xbe, 0x39, 0x67, 0xc0, 0xa9,
0x2a, 0xf0, 0x0a, 0xc1, 0x53, 0x1c, 0xdb, 0xfa, 0x1a, 0x26, 0x98, 0xb0,
0x8c, 0xc6, 0x06, 0x4a, 0xa2, 0x48, 0xd3, 0xa4, 0x3b, 0xbd, 0x05, 0x48,
0xea, 0x59, 0xdb, 0x18, 0xa4, 0xca, 0x66, 0xd9, 0x5d, 0xb8, 0x95, 0xd1,
0xeb, 0x97, 0x3d, 0x66, 0x97, 0x5c, 0x86, 0x8f, 0x7e, 0x90, 0xd3, 0x43,
0xd1, 0xa2, 0x0d, 0xcb, 0xe7, 0xeb, 0x90, 0xea, 0x09, 0x40, 0xb1, 0x6f,
0xf7, 0x4c, 0xf2, 0x41, 0x83, 0x1d, 0xd0, 0x76, 0xef, 0xaf, 0x55, 0x6f,
0x5d, 0xa9, 0xa3, 0x55, 0x81, 0x2a, 0xd1, 0x5d, 0x9d, 0x22, 0x77, 0x97,
0x83, 0xde, 0xad, 0xb6, 0x5d, 0x19, 0xc1, 0x53, 0xec, 0xfb, 0xaf, 0x06,
0x2e, 0x87, 0x2a, 0x0b, 0x7a
};
# endif
#endif
static const unsigned char kCFBDefaultKey[] = {
0x2B, 0x7E, 0x15, 0x16, 0x28, 0xAE, 0xD2, 0xA6, 0xAB, 0xF7, 0x15, 0x88,
0x09, 0xCF, 0x4F, 0x3C
};
static const unsigned char kGCMDefaultKey[32] = { 0 };
static const unsigned char kGCMResetKey[] = {
0xfe, 0xff, 0xe9, 0x92, 0x86, 0x65, 0x73, 0x1c, 0x6d, 0x6a, 0x8f, 0x94,
0x67, 0x30, 0x83, 0x08, 0xfe, 0xff, 0xe9, 0x92, 0x86, 0x65, 0x73, 0x1c,
0x6d, 0x6a, 0x8f, 0x94, 0x67, 0x30, 0x83, 0x08
};
static const unsigned char iCFBIV[] = {
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B,
0x0C, 0x0D, 0x0E, 0x0F
};
static const unsigned char iGCMDefaultIV[12] = { 0 };
static const unsigned char iGCMResetIV1[] = {
0xca, 0xfe, 0xba, 0xbe, 0xfa, 0xce, 0xdb, 0xad
};
static const unsigned char iGCMResetIV2[] = {
0xca, 0xfe, 0xba, 0xbe, 0xfa, 0xce, 0xdb, 0xad, 0xde, 0xca, 0xf8, 0x88
};
static const unsigned char cfbPlaintext[] = {
0x6B, 0xC1, 0xBE, 0xE2, 0x2E, 0x40, 0x9F, 0x96, 0xE9, 0x3D, 0x7E, 0x11,
0x73, 0x93, 0x17, 0x2A
};
static const unsigned char cfbPlaintext_partial[] = {
0x6B, 0xC1, 0xBE, 0xE2, 0x2E, 0x40, 0x9F, 0x96, 0xE9, 0x3D, 0x7E, 0x11,
0x73, 0x93, 0x17, 0x2A, 0x6B, 0xC1, 0xBE, 0xE2, 0x2E, 0x40, 0x9F, 0x96,
};
static const unsigned char gcmDefaultPlaintext[16] = { 0 };
static const unsigned char gcmResetPlaintext[] = {
0xd9, 0x31, 0x32, 0x25, 0xf8, 0x84, 0x06, 0xe5, 0xa5, 0x59, 0x09, 0xc5,
0xaf, 0xf5, 0x26, 0x9a, 0x86, 0xa7, 0xa9, 0x53, 0x15, 0x34, 0xf7, 0xda,
0x2e, 0x4c, 0x30, 0x3d, 0x8a, 0x31, 0x8a, 0x72, 0x1c, 0x3c, 0x0c, 0x95,
0x95, 0x68, 0x09, 0x53, 0x2f, 0xcf, 0x0e, 0x24, 0x49, 0xa6, 0xb5, 0x25,
0xb1, 0x6a, 0xed, 0xf5, 0xaa, 0x0d, 0xe6, 0x57, 0xba, 0x63, 0x7b, 0x39
};
static const unsigned char cfbCiphertext[] = {
0x3B, 0x3F, 0xD9, 0x2E, 0xB7, 0x2D, 0xAD, 0x20, 0x33, 0x34, 0x49, 0xF8,
0xE8, 0x3C, 0xFB, 0x4A
};
static const unsigned char cfbCiphertext_partial[] = {
0x3B, 0x3F, 0xD9, 0x2E, 0xB7, 0x2D, 0xAD, 0x20, 0x33, 0x34, 0x49, 0xF8,
0xE8, 0x3C, 0xFB, 0x4A, 0x0D, 0x4A, 0x71, 0x82, 0x90, 0xF0, 0x9A, 0x35
};
static const unsigned char ofbCiphertext_partial[] = {
0x3B, 0x3F, 0xD9, 0x2E, 0xB7, 0x2D, 0xAD, 0x20, 0x33, 0x34, 0x49, 0xF8,
0xE8, 0x3C, 0xFB, 0x4A, 0xB2, 0x65, 0x64, 0x38, 0x26, 0xD2, 0xBC, 0x09
};
static const unsigned char gcmDefaultCiphertext[] = {
0xce, 0xa7, 0x40, 0x3d, 0x4d, 0x60, 0x6b, 0x6e, 0x07, 0x4e, 0xc5, 0xd3,
0xba, 0xf3, 0x9d, 0x18
};
static const unsigned char gcmResetCiphertext1[] = {
0xc3, 0x76, 0x2d, 0xf1, 0xca, 0x78, 0x7d, 0x32, 0xae, 0x47, 0xc1, 0x3b,
0xf1, 0x98, 0x44, 0xcb, 0xaf, 0x1a, 0xe1, 0x4d, 0x0b, 0x97, 0x6a, 0xfa,
0xc5, 0x2f, 0xf7, 0xd7, 0x9b, 0xba, 0x9d, 0xe0, 0xfe, 0xb5, 0x82, 0xd3,
0x39, 0x34, 0xa4, 0xf0, 0x95, 0x4c, 0xc2, 0x36, 0x3b, 0xc7, 0x3f, 0x78,
0x62, 0xac, 0x43, 0x0e, 0x64, 0xab, 0xe4, 0x99, 0xf4, 0x7c, 0x9b, 0x1f
};
static const unsigned char gcmResetCiphertext2[] = {
0x52, 0x2d, 0xc1, 0xf0, 0x99, 0x56, 0x7d, 0x07, 0xf4, 0x7f, 0x37, 0xa3,
0x2a, 0x84, 0x42, 0x7d, 0x64, 0x3a, 0x8c, 0xdc, 0xbf, 0xe5, 0xc0, 0xc9,
0x75, 0x98, 0xa2, 0xbd, 0x25, 0x55, 0xd1, 0xaa, 0x8c, 0xb0, 0x8e, 0x48,
0x59, 0x0d, 0xbb, 0x3d, 0xa7, 0xb0, 0x8b, 0x10, 0x56, 0x82, 0x88, 0x38,
0xc5, 0xf6, 0x1e, 0x63, 0x93, 0xba, 0x7a, 0x0a, 0xbc, 0xc9, 0xf6, 0x62
};
static const unsigned char gcmAAD[] = {
0xfe, 0xed, 0xfa, 0xce, 0xde, 0xad, 0xbe, 0xef, 0xfe, 0xed, 0xfa, 0xce,
0xde, 0xad, 0xbe, 0xef, 0xab, 0xad, 0xda, 0xd2
};
static const unsigned char gcmDefaultTag[] = {
0xd0, 0xd1, 0xc8, 0xa7, 0x99, 0x99, 0x6b, 0xf0, 0x26, 0x5b, 0x98, 0xb5,
0xd4, 0x8a, 0xb9, 0x19
};
static const unsigned char gcmResetTag1[] = {
0x3a, 0x33, 0x7d, 0xbf, 0x46, 0xa7, 0x92, 0xc4, 0x5e, 0x45, 0x49, 0x13,
0xfe, 0x2e, 0xa8, 0xf2
};
static const unsigned char gcmResetTag2[] = {
0x76, 0xfc, 0x6e, 0xce, 0x0f, 0x4e, 0x17, 0x68, 0xcd, 0xdf, 0x88, 0x53,
0xbb, 0x2d, 0x55, 0x1b
};
typedef struct APK_DATA_st {
const unsigned char *kder;
size_t size;
const char *keytype;
int evptype;
int check;
int pub_check;
int param_check;
int type; /* 0 for private, 1 for public, 2 for params */
} APK_DATA;
static APK_DATA keydata[] = {
{kExampleRSAKeyDER, sizeof(kExampleRSAKeyDER), "RSA", EVP_PKEY_RSA},
{kExampleRSAKeyPKCS8, sizeof(kExampleRSAKeyPKCS8), "RSA", EVP_PKEY_RSA},
#ifndef OPENSSL_NO_EC
{kExampleECKeyDER, sizeof(kExampleECKeyDER), "EC", EVP_PKEY_EC}
#endif
};
static APK_DATA keycheckdata[] = {
{kExampleRSAKeyDER, sizeof(kExampleRSAKeyDER), "RSA", EVP_PKEY_RSA, 1, 1, 1,
0},
{kExampleBadRSAKeyDER, sizeof(kExampleBadRSAKeyDER), "RSA", EVP_PKEY_RSA,
0, 1, 1, 0},
{kExampleBad2RSAKeyDER, sizeof(kExampleBad2RSAKeyDER), "RSA", EVP_PKEY_RSA,
0, 0, 1 /* Since there are no "params" in an RSA key this passes */, 0},
#ifndef OPENSSL_NO_EC
{kExampleECKeyDER, sizeof(kExampleECKeyDER), "EC", EVP_PKEY_EC, 1, 1, 1, 0},
/* group is also associated in our pub key */
{kExampleECPubKeyDER, sizeof(kExampleECPubKeyDER), "EC", EVP_PKEY_EC, 0, 1,
1, 1},
{pExampleECParamDER, sizeof(pExampleECParamDER), "EC", EVP_PKEY_EC, 0, 0, 1,
2},
{kExampleED25519KeyDER, sizeof(kExampleED25519KeyDER), "ED25519",
EVP_PKEY_ED25519, 1, 1, 1, 0},
{kExampleED25519PubKeyDER, sizeof(kExampleED25519PubKeyDER), "ED25519",
EVP_PKEY_ED25519, 0, 1, 1, 1},
#endif
};
static EVP_PKEY *load_example_key(const char *keytype,
const unsigned char *data, size_t data_len)
{
const unsigned char **pdata = &data;
EVP_PKEY *pkey = NULL;
OSSL_DECODER_CTX *dctx =
OSSL_DECODER_CTX_new_for_pkey(&pkey, "DER", NULL, keytype, 0,
testctx, testpropq);
/* |pkey| will be NULL on error */
(void)OSSL_DECODER_from_data(dctx, pdata, &data_len);
OSSL_DECODER_CTX_free(dctx);
return pkey;
}
static EVP_PKEY *load_example_rsa_key(void)
{
return load_example_key("RSA", kExampleRSAKeyDER,
sizeof(kExampleRSAKeyDER));
}
#ifndef OPENSSL_NO_DSA
static EVP_PKEY *load_example_dsa_key(void)
{
return load_example_key("DSA", kExampleDSAKeyDER,
sizeof(kExampleDSAKeyDER));
}
#endif
#ifndef OPENSSL_NO_EC
static EVP_PKEY *load_example_ec_key(void)
{
return load_example_key("EC", kExampleECKeyDER,
sizeof(kExampleECKeyDER));
}
#endif
#ifndef OPENSSL_NO_DEPRECATED_3_0
# ifndef OPENSSL_NO_DH
static EVP_PKEY *load_example_dh_key(void)
{
return load_example_key("DH", kExampleDHKeyDER,
sizeof(kExampleDHKeyDER));
}
# endif
# ifndef OPENSSL_NO_EC
static EVP_PKEY *load_example_ed25519_key(void)
{
return load_example_key("ED25519", kExampleED25519KeyDER,
sizeof(kExampleED25519KeyDER));
}
static EVP_PKEY *load_example_x25519_key(void)
{
return load_example_key("X25519", kExampleX25519KeyDER,
sizeof(kExampleX25519KeyDER));
}
# endif
#endif /* OPENSSL_NO_DEPRECATED_3_0 */
static EVP_PKEY *load_example_hmac_key(void)
{
EVP_PKEY *pkey = NULL;
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
};
pkey = EVP_PKEY_new_raw_private_key_ex(testctx, "HMAC",
NULL, key, sizeof(key));
if (!TEST_ptr(pkey))
return NULL;
return pkey;
}
static int test_EVP_set_default_properties(void)
{
OSSL_LIB_CTX *ctx;
EVP_MD *md = NULL;
int res = 0;
if (!TEST_ptr(ctx = OSSL_LIB_CTX_new())
|| !TEST_ptr(md = EVP_MD_fetch(ctx, "sha256", NULL)))
goto err;
EVP_MD_free(md);
md = NULL;
if (!TEST_true(EVP_set_default_properties(ctx, "provider=fizzbang"))
|| !TEST_ptr_null(md = EVP_MD_fetch(ctx, "sha256", NULL))
|| !TEST_ptr(md = EVP_MD_fetch(ctx, "sha256", "-provider")))
goto err;
EVP_MD_free(md);
md = NULL;
if (!TEST_true(EVP_set_default_properties(ctx, NULL))
|| !TEST_ptr(md = EVP_MD_fetch(ctx, "sha256", NULL)))
goto err;
res = 1;
err:
EVP_MD_free(md);
OSSL_LIB_CTX_free(ctx);
return res;
}
#if !defined(OPENSSL_NO_DH) || !defined(OPENSSL_NO_DSA) || !defined(OPENSSL_NO_EC)
static EVP_PKEY *make_key_fromdata(char *keytype, OSSL_PARAM *params)
{
EVP_PKEY_CTX *pctx = NULL;
EVP_PKEY *tmp_pkey = NULL, *pkey = NULL;
if (!TEST_ptr(pctx = EVP_PKEY_CTX_new_from_name(testctx, keytype, testpropq)))
goto err;
if (!TEST_int_gt(EVP_PKEY_fromdata_init(pctx), 0)
|| !TEST_int_gt(EVP_PKEY_fromdata(pctx, &tmp_pkey, EVP_PKEY_KEYPAIR,
params), 0))
goto err;
if (!TEST_ptr(tmp_pkey))
goto err;
pkey = tmp_pkey;
tmp_pkey = NULL;
err:
EVP_PKEY_free(tmp_pkey);
EVP_PKEY_CTX_free(pctx);
return pkey;
}
static int test_selection(EVP_PKEY *pkey, int selection)
{
int testresult = 0;
int ret;
BIO *bio = BIO_new(BIO_s_mem());
ret = PEM_write_bio_PUBKEY(bio, pkey);
if ((selection & OSSL_KEYMGMT_SELECT_PUBLIC_KEY) != 0) {
if (!TEST_true(ret))
goto err;
} else {
if (!TEST_false(ret))
goto err;
}
ret = PEM_write_bio_PrivateKey_ex(bio, pkey, NULL, NULL, 0, NULL, NULL,
testctx, NULL);
if ((selection & OSSL_KEYMGMT_SELECT_PRIVATE_KEY) != 0) {
if (!TEST_true(ret))
goto err;
} else {
if (!TEST_false(ret))
goto err;
}
testresult = 1;
err:
BIO_free(bio);
return testresult;
}
#endif /* !OPENSSL_NO_DH || !OPENSSL_NO_DSA || !OPENSSL_NO_EC */
/*
* Test combinations of private, public, missing and private + public key
* params to ensure they are all accepted
*/
#if !defined(OPENSSL_NO_DH) || !defined(OPENSSL_NO_DSA)
static int test_EVP_PKEY_ffc_priv_pub(char *keytype)
{
OSSL_PARAM_BLD *bld = NULL;
OSSL_PARAM *params = NULL;
EVP_PKEY *just_params = NULL;
EVP_PKEY *params_and_priv = NULL;
EVP_PKEY *params_and_pub = NULL;
EVP_PKEY *params_and_keypair = NULL;
BIGNUM *p = NULL, *q = NULL, *g = NULL, *pub = NULL, *priv = NULL;
int ret = 0;
/*
* Setup the parameters for our pkey object. For our purposes they don't
* have to actually be *valid* parameters. We just need to set something.
*/
if (!TEST_ptr(p = BN_new())
|| !TEST_ptr(q = BN_new())
|| !TEST_ptr(g = BN_new())
|| !TEST_ptr(pub = BN_new())
|| !TEST_ptr(priv = BN_new()))
goto err;
/* Test !priv and !pub */
if (!TEST_ptr(bld = OSSL_PARAM_BLD_new())
|| !TEST_true(OSSL_PARAM_BLD_push_BN(bld, OSSL_PKEY_PARAM_FFC_P, p))
|| !TEST_true(OSSL_PARAM_BLD_push_BN(bld, OSSL_PKEY_PARAM_FFC_Q, q))
|| !TEST_true(OSSL_PARAM_BLD_push_BN(bld, OSSL_PKEY_PARAM_FFC_G, g)))
goto err;
if (!TEST_ptr(params = OSSL_PARAM_BLD_to_param(bld))
|| !TEST_ptr(just_params = make_key_fromdata(keytype, params)))
goto err;
OSSL_PARAM_free(params);
OSSL_PARAM_BLD_free(bld);
params = NULL;
bld = NULL;
if (!test_selection(just_params, OSSL_KEYMGMT_SELECT_ALL_PARAMETERS)
|| test_selection(just_params, OSSL_KEYMGMT_SELECT_KEYPAIR))
goto err;
/* Test priv and !pub */
if (!TEST_ptr(bld = OSSL_PARAM_BLD_new())
|| !TEST_true(OSSL_PARAM_BLD_push_BN(bld, OSSL_PKEY_PARAM_FFC_P, p))
|| !TEST_true(OSSL_PARAM_BLD_push_BN(bld, OSSL_PKEY_PARAM_FFC_Q, q))
|| !TEST_true(OSSL_PARAM_BLD_push_BN(bld, OSSL_PKEY_PARAM_FFC_G, g))
|| !TEST_true(OSSL_PARAM_BLD_push_BN(bld, OSSL_PKEY_PARAM_PRIV_KEY,
priv)))
goto err;
if (!TEST_ptr(params = OSSL_PARAM_BLD_to_param(bld))
|| !TEST_ptr(params_and_priv = make_key_fromdata(keytype, params)))
goto err;
OSSL_PARAM_free(params);
OSSL_PARAM_BLD_free(bld);
params = NULL;
bld = NULL;
if (!test_selection(params_and_priv, OSSL_KEYMGMT_SELECT_PRIVATE_KEY)
|| test_selection(params_and_priv, OSSL_KEYMGMT_SELECT_PUBLIC_KEY))
goto err;
/* Test !priv and pub */
if (!TEST_ptr(bld = OSSL_PARAM_BLD_new())
|| !TEST_true(OSSL_PARAM_BLD_push_BN(bld, OSSL_PKEY_PARAM_FFC_P, p))
|| !TEST_true(OSSL_PARAM_BLD_push_BN(bld, OSSL_PKEY_PARAM_FFC_Q, q))
|| !TEST_true(OSSL_PARAM_BLD_push_BN(bld, OSSL_PKEY_PARAM_FFC_G, g))
|| !TEST_true(OSSL_PARAM_BLD_push_BN(bld, OSSL_PKEY_PARAM_PUB_KEY,
pub)))
goto err;
if (!TEST_ptr(params = OSSL_PARAM_BLD_to_param(bld))
|| !TEST_ptr(params_and_pub = make_key_fromdata(keytype, params)))
goto err;
OSSL_PARAM_free(params);
OSSL_PARAM_BLD_free(bld);
params = NULL;
bld = NULL;
if (!test_selection(params_and_pub, OSSL_KEYMGMT_SELECT_PUBLIC_KEY)
|| test_selection(params_and_pub, OSSL_KEYMGMT_SELECT_PRIVATE_KEY))
goto err;
/* Test priv and pub */
if (!TEST_ptr(bld = OSSL_PARAM_BLD_new())
|| !TEST_true(OSSL_PARAM_BLD_push_BN(bld, OSSL_PKEY_PARAM_FFC_P, p))
|| !TEST_true(OSSL_PARAM_BLD_push_BN(bld, OSSL_PKEY_PARAM_FFC_Q, q))
|| !TEST_true(OSSL_PARAM_BLD_push_BN(bld, OSSL_PKEY_PARAM_FFC_G, g))
|| !TEST_true(OSSL_PARAM_BLD_push_BN(bld, OSSL_PKEY_PARAM_PUB_KEY,
pub))
|| !TEST_true(OSSL_PARAM_BLD_push_BN(bld, OSSL_PKEY_PARAM_PRIV_KEY,
priv)))
goto err;
if (!TEST_ptr(params = OSSL_PARAM_BLD_to_param(bld))
|| !TEST_ptr(params_and_keypair = make_key_fromdata(keytype, params)))
goto err;
if (!test_selection(params_and_keypair, EVP_PKEY_KEYPAIR))
goto err;
ret = 1;
err:
OSSL_PARAM_free(params);
OSSL_PARAM_BLD_free(bld);
EVP_PKEY_free(just_params);
EVP_PKEY_free(params_and_priv);
EVP_PKEY_free(params_and_pub);
EVP_PKEY_free(params_and_keypair);
BN_free(p);
BN_free(q);
BN_free(g);
BN_free(pub);
BN_free(priv);
return ret;
}
#endif /* !OPENSSL_NO_DH || !OPENSSL_NO_DSA */
/*
* Test combinations of private, public, missing and private + public key
* params to ensure they are all accepted for EC keys
*/
#ifndef OPENSSL_NO_EC
static unsigned char ec_priv[] = {
0xe9, 0x25, 0xf7, 0x66, 0x58, 0xa4, 0xdd, 0x99, 0x61, 0xe7, 0xe8, 0x23,
0x85, 0xc2, 0xe8, 0x33, 0x27, 0xc5, 0x5c, 0xeb, 0xdb, 0x43, 0x9f, 0xd5,
0xf2, 0x5a, 0x75, 0x55, 0xd0, 0x2e, 0x6d, 0x16
};
static unsigned char ec_pub[] = {
0x04, 0xad, 0x11, 0x90, 0x77, 0x4b, 0x46, 0xee, 0x72, 0x51, 0x15, 0x97,
0x4a, 0x6a, 0xa7, 0xaf, 0x59, 0xfa, 0x4b, 0xf2, 0x41, 0xc8, 0x3a, 0x81,
0x23, 0xb6, 0x90, 0x04, 0x6c, 0x67, 0x66, 0xd0, 0xdc, 0xf2, 0x15, 0x1d,
0x41, 0x61, 0xb7, 0x95, 0x85, 0x38, 0x5a, 0x84, 0x56, 0xe8, 0xb3, 0x0e,
0xf5, 0xc6, 0x5d, 0xa4, 0x54, 0x26, 0xb0, 0xf7, 0xa5, 0x4a, 0x33, 0xf1,
0x08, 0x09, 0xb8, 0xdb, 0x03
};
static int test_EC_priv_pub(void)
{
OSSL_PARAM_BLD *bld = NULL;
OSSL_PARAM *params = NULL;
EVP_PKEY *just_params = NULL;
EVP_PKEY *params_and_priv = NULL;
EVP_PKEY *params_and_pub = NULL;
EVP_PKEY *params_and_keypair = NULL;
BIGNUM *priv = NULL;
int ret = 0;
unsigned char *encoded = NULL;
size_t len = 0;
unsigned char buffer[128];
/*
* Setup the parameters for our pkey object. For our purposes they don't
* have to actually be *valid* parameters. We just need to set something.
*/
if (!TEST_ptr(priv = BN_bin2bn(ec_priv, sizeof(ec_priv), NULL)))
goto err;
/* Test !priv and !pub */
if (!TEST_ptr(bld = OSSL_PARAM_BLD_new())
|| !TEST_true(OSSL_PARAM_BLD_push_utf8_string(bld,
OSSL_PKEY_PARAM_GROUP_NAME,
"P-256", 0)))
goto err;
if (!TEST_ptr(params = OSSL_PARAM_BLD_to_param(bld))
|| !TEST_ptr(just_params = make_key_fromdata("EC", params)))
goto err;
OSSL_PARAM_free(params);
OSSL_PARAM_BLD_free(bld);
params = NULL;
bld = NULL;
if (!test_selection(just_params, OSSL_KEYMGMT_SELECT_ALL_PARAMETERS)
|| test_selection(just_params, OSSL_KEYMGMT_SELECT_KEYPAIR))
goto err;
/* Test priv and !pub */
if (!TEST_ptr(bld = OSSL_PARAM_BLD_new())
|| !TEST_true(OSSL_PARAM_BLD_push_utf8_string(bld,
OSSL_PKEY_PARAM_GROUP_NAME,
"P-256", 0))
|| !TEST_true(OSSL_PARAM_BLD_push_BN(bld, OSSL_PKEY_PARAM_PRIV_KEY,
priv)))
goto err;
if (!TEST_ptr(params = OSSL_PARAM_BLD_to_param(bld))
|| !TEST_ptr(params_and_priv = make_key_fromdata("EC", params)))
goto err;
OSSL_PARAM_free(params);
OSSL_PARAM_BLD_free(bld);
params = NULL;
bld = NULL;
/*
* We indicate only parameters here, in spite of having built a key that
* has a private part, because the PEM_write_bio_PrivateKey_ex call is
* expected to fail because it does not support exporting a private EC
* key without a corresponding public key
*/
if (!test_selection(params_and_priv, OSSL_KEYMGMT_SELECT_ALL_PARAMETERS)
|| test_selection(params_and_priv, OSSL_KEYMGMT_SELECT_PUBLIC_KEY))
goto err;
/* Test !priv and pub */
if (!TEST_ptr(bld = OSSL_PARAM_BLD_new())
|| !TEST_true(OSSL_PARAM_BLD_push_utf8_string(bld,
OSSL_PKEY_PARAM_GROUP_NAME,
"P-256", 0))
|| !TEST_true(OSSL_PARAM_BLD_push_octet_string(bld,
OSSL_PKEY_PARAM_PUB_KEY,
ec_pub, sizeof(ec_pub))))
goto err;
if (!TEST_ptr(params = OSSL_PARAM_BLD_to_param(bld))
|| !TEST_ptr(params_and_pub = make_key_fromdata("EC", params)))
goto err;
OSSL_PARAM_free(params);
OSSL_PARAM_BLD_free(bld);
params = NULL;
bld = NULL;
if (!test_selection(params_and_pub, OSSL_KEYMGMT_SELECT_PUBLIC_KEY)
|| test_selection(params_and_pub, OSSL_KEYMGMT_SELECT_PRIVATE_KEY))
goto err;
/* Test priv and pub */
if (!TEST_ptr(bld = OSSL_PARAM_BLD_new())
|| !TEST_true(OSSL_PARAM_BLD_push_utf8_string(bld,
OSSL_PKEY_PARAM_GROUP_NAME,
"P-256", 0))
|| !TEST_true(OSSL_PARAM_BLD_push_octet_string(bld,
OSSL_PKEY_PARAM_PUB_KEY,
ec_pub, sizeof(ec_pub)))
|| !TEST_true(OSSL_PARAM_BLD_push_BN(bld, OSSL_PKEY_PARAM_PRIV_KEY,
priv)))
goto err;
if (!TEST_ptr(params = OSSL_PARAM_BLD_to_param(bld))
|| !TEST_ptr(params_and_keypair = make_key_fromdata("EC", params)))
goto err;
if (!test_selection(params_and_keypair, EVP_PKEY_KEYPAIR))
goto err;
/* Try key equality */
if (!TEST_int_gt(EVP_PKEY_parameters_eq(just_params, just_params), 0)
|| !TEST_int_gt(EVP_PKEY_parameters_eq(just_params, params_and_pub),
0)
|| !TEST_int_gt(EVP_PKEY_parameters_eq(just_params, params_and_priv),
0)
|| !TEST_int_gt(EVP_PKEY_parameters_eq(just_params, params_and_keypair),
0)
|| !TEST_int_gt(EVP_PKEY_eq(params_and_pub, params_and_pub), 0)
|| !TEST_int_gt(EVP_PKEY_eq(params_and_priv, params_and_priv), 0)
|| !TEST_int_gt(EVP_PKEY_eq(params_and_keypair, params_and_pub), 0)
|| !TEST_int_gt(EVP_PKEY_eq(params_and_keypair, params_and_priv), 0))
goto err;
/* Positive and negative testcase for EVP_PKEY_get1_encoded_public_key */
if (!TEST_int_gt(EVP_PKEY_get1_encoded_public_key(params_and_pub, &encoded), 0))
goto err;
OPENSSL_free(encoded);
encoded = NULL;
if (!TEST_int_eq(EVP_PKEY_get1_encoded_public_key(just_params, &encoded), 0)) {
OPENSSL_free(encoded);
encoded = NULL;
goto err;
}
/* Positive and negative testcase for EVP_PKEY_get_octet_string_param */
if (!TEST_int_eq(EVP_PKEY_get_octet_string_param(params_and_pub,
OSSL_PKEY_PARAM_ENCODED_PUBLIC_KEY,
buffer, sizeof(buffer), &len), 1)
|| !TEST_int_eq(len, 65))
goto err;
len = 0;
if (!TEST_int_eq(EVP_PKEY_get_octet_string_param(params_and_pub,
OSSL_PKEY_PARAM_ENCODED_PUBLIC_KEY,
NULL, 0, &len), 1)
|| !TEST_int_eq(len, 65))
goto err;
/* too-short buffer len*/
if (!TEST_int_eq(EVP_PKEY_get_octet_string_param(params_and_pub,
OSSL_PKEY_PARAM_ENCODED_PUBLIC_KEY,
buffer, 10, &len), 0))
goto err;
ret = 1;
err:
OSSL_PARAM_free(params);
OSSL_PARAM_BLD_free(bld);
EVP_PKEY_free(just_params);
EVP_PKEY_free(params_and_priv);
EVP_PKEY_free(params_and_pub);
EVP_PKEY_free(params_and_keypair);
BN_free(priv);
return ret;
}
/* Test that using a legacy EC key with only a private key in it works */
# ifndef OPENSSL_NO_DEPRECATED_3_0
static int test_EC_priv_only_legacy(void)
{
BIGNUM *priv = NULL;
int ret = 0;
EC_KEY *eckey = NULL;
EVP_PKEY *pkey = NULL, *dup_pk = NULL;
EVP_MD_CTX *ctx = NULL;
/* Create the low level EC_KEY */
if (!TEST_ptr(priv = BN_bin2bn(ec_priv, sizeof(ec_priv), NULL)))
goto err;
eckey = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
if (!TEST_ptr(eckey))
goto err;
if (!TEST_true(EC_KEY_set_private_key(eckey, priv)))
goto err;
pkey = EVP_PKEY_new();
if (!TEST_ptr(pkey))
goto err;
if (!TEST_true(EVP_PKEY_assign_EC_KEY(pkey, eckey)))
goto err;
eckey = NULL;
- while (dup_pk == NULL) {
+ for (;;) {
ret = 0;
ctx = EVP_MD_CTX_new();
if (!TEST_ptr(ctx))
goto err;
/*
* The EVP_DigestSignInit function should create the key on the
* provider side which is sufficient for this test.
*/
if (!TEST_true(EVP_DigestSignInit_ex(ctx, NULL, NULL, testctx,
testpropq, pkey, NULL)))
goto err;
EVP_MD_CTX_free(ctx);
ctx = NULL;
+ if (dup_pk != NULL)
+ break;
+
if (!TEST_ptr(dup_pk = EVP_PKEY_dup(pkey)))
goto err;
/* EVP_PKEY_eq() returns -2 with missing public keys */
ret = TEST_int_eq(EVP_PKEY_eq(pkey, dup_pk), -2);
EVP_PKEY_free(pkey);
pkey = dup_pk;
if (!ret)
goto err;
}
+ ret = 1;
err:
EVP_MD_CTX_free(ctx);
EVP_PKEY_free(pkey);
EC_KEY_free(eckey);
BN_free(priv);
return ret;
}
# endif /* OPENSSL_NO_DEPRECATED_3_0 */
#endif /* OPENSSL_NO_EC */
static int test_EVP_PKEY_sign(int tst)
{
int ret = 0;
EVP_PKEY *pkey = NULL;
unsigned char *sig = NULL;
size_t sig_len = 0, shortsig_len = 1;
EVP_PKEY_CTX *ctx = NULL;
unsigned char tbs[] = {
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b,
0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13
};
if (tst == 0 ) {
if (!TEST_ptr(pkey = load_example_rsa_key()))
goto out;
} else if (tst == 1) {
#ifndef OPENSSL_NO_DSA
if (!TEST_ptr(pkey = load_example_dsa_key()))
goto out;
#else
ret = 1;
goto out;
#endif
} else {
#ifndef OPENSSL_NO_EC
if (!TEST_ptr(pkey = load_example_ec_key()))
goto out;
#else
ret = 1;
goto out;
#endif
}
ctx = EVP_PKEY_CTX_new_from_pkey(testctx, pkey, NULL);
if (!TEST_ptr(ctx)
|| !TEST_int_gt(EVP_PKEY_sign_init(ctx), 0)
|| !TEST_int_gt(EVP_PKEY_sign(ctx, NULL, &sig_len, tbs,
sizeof(tbs)), 0))
goto out;
sig = OPENSSL_malloc(sig_len);
if (!TEST_ptr(sig)
/* Test sending a signature buffer that is too short is rejected */
|| !TEST_int_le(EVP_PKEY_sign(ctx, sig, &shortsig_len, tbs,
sizeof(tbs)), 0)
|| !TEST_int_gt(EVP_PKEY_sign(ctx, sig, &sig_len, tbs, sizeof(tbs)),
0)
/* Test the signature round-trips */
|| !TEST_int_gt(EVP_PKEY_verify_init(ctx), 0)
|| !TEST_int_gt(EVP_PKEY_verify(ctx, sig, sig_len, tbs, sizeof(tbs)),
0))
goto out;
ret = 1;
out:
EVP_PKEY_CTX_free(ctx);
OPENSSL_free(sig);
EVP_PKEY_free(pkey);
return ret;
}
#ifndef OPENSSL_NO_DEPRECATED_3_0
static int test_EVP_PKEY_sign_with_app_method(int tst)
{
int ret = 0;
EVP_PKEY *pkey = NULL;
RSA *rsa = NULL;
RSA_METHOD *rsa_meth = NULL;
#ifndef OPENSSL_NO_DSA
DSA *dsa = NULL;
DSA_METHOD *dsa_meth = NULL;
#endif
unsigned char *sig = NULL;
size_t sig_len = 0, shortsig_len = 1;
EVP_PKEY_CTX *ctx = NULL;
unsigned char tbs[] = {
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b,
0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13
};
if (tst == 0) {
if (!TEST_ptr(pkey = load_example_rsa_key()))
goto out;
if (!TEST_ptr(rsa_meth = RSA_meth_dup(RSA_get_default_method())))
goto out;
if (!TEST_ptr(rsa = EVP_PKEY_get1_RSA(pkey))
|| !TEST_int_gt(RSA_set_method(rsa, rsa_meth), 0)
|| !TEST_int_gt(EVP_PKEY_assign_RSA(pkey, rsa), 0))
goto out;
rsa = NULL; /* now owned by the pkey */
} else {
#ifndef OPENSSL_NO_DSA
if (!TEST_ptr(pkey = load_example_dsa_key()))
goto out;
if (!TEST_ptr(dsa_meth = DSA_meth_dup(DSA_get_default_method())))
goto out;
if (!TEST_ptr(dsa = EVP_PKEY_get1_DSA(pkey))
|| !TEST_int_gt(DSA_set_method(dsa, dsa_meth), 0)
|| !TEST_int_gt(EVP_PKEY_assign_DSA(pkey, dsa), 0))
goto out;
dsa = NULL; /* now owned by the pkey */
#else
ret = 1;
goto out;
#endif
}
ctx = EVP_PKEY_CTX_new_from_pkey(testctx, pkey, NULL);
if (!TEST_ptr(ctx)
|| !TEST_int_gt(EVP_PKEY_sign_init(ctx), 0)
|| !TEST_int_gt(EVP_PKEY_sign(ctx, NULL, &sig_len, tbs,
sizeof(tbs)), 0))
goto out;
sig = OPENSSL_malloc(sig_len);
if (!TEST_ptr(sig)
/* Test sending a signature buffer that is too short is rejected */
|| !TEST_int_le(EVP_PKEY_sign(ctx, sig, &shortsig_len, tbs,
sizeof(tbs)), 0)
|| !TEST_int_gt(EVP_PKEY_sign(ctx, sig, &sig_len, tbs, sizeof(tbs)),
0)
/* Test the signature round-trips */
|| !TEST_int_gt(EVP_PKEY_verify_init(ctx), 0)
|| !TEST_int_gt(EVP_PKEY_verify(ctx, sig, sig_len, tbs, sizeof(tbs)),
0))
goto out;
ret = 1;
out:
EVP_PKEY_CTX_free(ctx);
OPENSSL_free(sig);
EVP_PKEY_free(pkey);
RSA_free(rsa);
RSA_meth_free(rsa_meth);
#ifndef OPENSSL_NO_DSA
DSA_free(dsa);
DSA_meth_free(dsa_meth);
#endif
return ret;
}
#endif /* !OPENSSL_NO_DEPRECATED_3_0 */
/*
* n = 0 => test using legacy cipher
* n = 1 => test using fetched cipher
*/
static int test_EVP_Enveloped(int n)
{
int ret = 0;
EVP_CIPHER_CTX *ctx = NULL;
EVP_PKEY *keypair = NULL;
unsigned char *kek = NULL;
unsigned char iv[EVP_MAX_IV_LENGTH];
static const unsigned char msg[] = { 1, 2, 3, 4, 5, 6, 7, 8 };
int len, kek_len, ciphertext_len, plaintext_len;
unsigned char ciphertext[32], plaintext[16];
EVP_CIPHER *type = NULL;
if (nullprov != NULL)
return TEST_skip("Test does not support a non-default library context");
if (n == 0)
type = (EVP_CIPHER *)EVP_aes_256_cbc();
else if (!TEST_ptr(type = EVP_CIPHER_fetch(testctx, "AES-256-CBC",
testpropq)))
goto err;
if (!TEST_ptr(keypair = load_example_rsa_key())
|| !TEST_ptr(kek = OPENSSL_zalloc(EVP_PKEY_get_size(keypair)))
|| !TEST_ptr(ctx = EVP_CIPHER_CTX_new())
|| !TEST_true(EVP_SealInit(ctx, type, &kek, &kek_len, iv,
&keypair, 1))
|| !TEST_true(EVP_SealUpdate(ctx, ciphertext, &ciphertext_len,
msg, sizeof(msg)))
|| !TEST_true(EVP_SealFinal(ctx, ciphertext + ciphertext_len,
&len)))
goto err;
ciphertext_len += len;
if (!TEST_true(EVP_OpenInit(ctx, type, kek, kek_len, iv, keypair))
|| !TEST_true(EVP_OpenUpdate(ctx, plaintext, &plaintext_len,
ciphertext, ciphertext_len))
|| !TEST_true(EVP_OpenFinal(ctx, plaintext + plaintext_len, &len)))
goto err;
plaintext_len += len;
if (!TEST_mem_eq(msg, sizeof(msg), plaintext, plaintext_len))
goto err;
ret = 1;
err:
if (n != 0)
EVP_CIPHER_free(type);
OPENSSL_free(kek);
EVP_PKEY_free(keypair);
EVP_CIPHER_CTX_free(ctx);
return ret;
}
/*
* Test 0: Standard calls to EVP_DigestSignInit/Update/Final (Implicit fetch digest, RSA)
* Test 1: Standard calls to EVP_DigestSignInit/Update/Final (Implicit fetch digest, DSA)
* Test 2: Standard calls to EVP_DigestSignInit/Update/Final (Implicit fetch digest, HMAC)
* Test 3: Standard calls to EVP_DigestSignInit/Update/Final (Explicit fetch digest, RSA)
* Test 4: Standard calls to EVP_DigestSignInit/Update/Final (Explicit fetch digest, DSA)
* Test 5: Standard calls to EVP_DigestSignInit/Update/Final (Explicit fetch diegst, HMAC)
* Test 6: Use an MD BIO to do the Update calls instead (RSA)
* Test 7: Use an MD BIO to do the Update calls instead (DSA)
* Test 8: Use an MD BIO to do the Update calls instead (HMAC)
* Test 9: Use EVP_DigestSign (Implicit fetch digest, RSA, short sig)
* Test 10: Use EVP_DigestSign (Implicit fetch digest, DSA, short sig)
* Test 11: Use EVP_DigestSign (Implicit fetch digest, HMAC, short sig)
* Test 12: Use EVP_DigestSign (Implicit fetch digest, RSA)
* Test 13: Use EVP_DigestSign (Implicit fetch digest, DSA)
* Test 14: Use EVP_DigestSign (Implicit fetch digest, HMAC)
* Test 15-29: Same as above with reinitialization
*/
static int test_EVP_DigestSignInit(int tst)
{
int ret = 0;
EVP_PKEY *pkey = NULL;
unsigned char *sig = NULL, *sig2 = NULL;
size_t sig_len = 0, sig2_len = 0, shortsig_len = 1;
EVP_MD_CTX *md_ctx = NULL, *md_ctx_verify = NULL;
EVP_MD_CTX *a_md_ctx = NULL, *a_md_ctx_verify = NULL;
BIO *mdbio = NULL, *membio = NULL;
size_t written;
const EVP_MD *md;
EVP_MD *mdexp = NULL;
int reinit = 0;
if (nullprov != NULL)
return TEST_skip("Test does not support a non-default library context");
if (tst >= 15) {
reinit = 1;
tst -= 15;
}
if (tst >= 6 && tst <= 8) {
membio = BIO_new(BIO_s_mem());
mdbio = BIO_new(BIO_f_md());
if (!TEST_ptr(membio) || !TEST_ptr(mdbio))
goto out;
BIO_push(mdbio, membio);
if (!TEST_int_gt(BIO_get_md_ctx(mdbio, &md_ctx), 0))
goto out;
} else {
if (!TEST_ptr(a_md_ctx = md_ctx = EVP_MD_CTX_new())
|| !TEST_ptr(a_md_ctx_verify = md_ctx_verify = EVP_MD_CTX_new()))
goto out;
}
if (tst % 3 == 0) {
if (!TEST_ptr(pkey = load_example_rsa_key()))
goto out;
} else if (tst % 3 == 1) {
#ifndef OPENSSL_NO_DSA
if (!TEST_ptr(pkey = load_example_dsa_key()))
goto out;
#else
ret = 1;
goto out;
#endif
} else {
if (!TEST_ptr(pkey = load_example_hmac_key()))
goto out;
}
if (tst >= 3 && tst <= 5)
md = mdexp = EVP_MD_fetch(NULL, "SHA256", NULL);
else
md = EVP_sha256();
if (!TEST_true(EVP_DigestSignInit(md_ctx, NULL, md, NULL, pkey)))
goto out;
if (reinit && !TEST_true(EVP_DigestSignInit(md_ctx, NULL, NULL, NULL, NULL)))
goto out;
if (tst >= 6 && tst <= 8) {
if (!BIO_write_ex(mdbio, kMsg, sizeof(kMsg), &written))
goto out;
} else if (tst < 6) {
if (!TEST_true(EVP_DigestSignUpdate(md_ctx, kMsg, sizeof(kMsg))))
goto out;
}
if (tst >= 9) {
/* Determine the size of the signature. */
if (!TEST_true(EVP_DigestSign(md_ctx, NULL, &sig_len, kMsg,
sizeof(kMsg)))
|| !TEST_ptr(sig = OPENSSL_malloc(sig_len)))
goto out;
if (tst <= 11) {
/* Test that supply a short sig buffer fails */
if (!TEST_false(EVP_DigestSign(md_ctx, sig, &shortsig_len, kMsg,
sizeof(kMsg))))
goto out;
/*
* We end here because once EVP_DigestSign() has failed you should
* not call it again without re-initing the ctx
*/
ret = 1;
goto out;
}
if (!TEST_true(EVP_DigestSign(md_ctx, sig, &sig_len, kMsg,
sizeof(kMsg))))
goto out;
} else {
/* Determine the size of the signature. */
if (!TEST_true(EVP_DigestSignFinal(md_ctx, NULL, &sig_len))
|| !TEST_ptr(sig = OPENSSL_malloc(sig_len))
/*
* Trying to create a signature with a deliberately short
* buffer should fail.
*/
|| !TEST_false(EVP_DigestSignFinal(md_ctx, sig, &shortsig_len))
|| !TEST_true(EVP_DigestSignFinal(md_ctx, sig, &sig_len)))
goto out;
}
/*
* Ensure that the signature round-trips (Verification isn't supported for
* HMAC via EVP_DigestVerify*)
*/
if (tst % 3 != 2) {
if (tst >= 6 && tst <= 8) {
if (!TEST_int_gt(BIO_reset(mdbio), 0)
|| !TEST_int_gt(BIO_get_md_ctx(mdbio, &md_ctx_verify), 0))
goto out;
}
if (!TEST_true(EVP_DigestVerifyInit(md_ctx_verify, NULL, md,
NULL, pkey)))
goto out;
if (tst >= 6 && tst <= 8) {
if (!TEST_true(BIO_write_ex(mdbio, kMsg, sizeof(kMsg), &written)))
goto out;
} else {
if (!TEST_true(EVP_DigestVerifyUpdate(md_ctx_verify, kMsg,
sizeof(kMsg))))
goto out;
}
if (!TEST_int_gt(EVP_DigestVerifyFinal(md_ctx_verify, sig, sig_len), 0))
goto out;
/* Multiple calls to EVP_DigestVerifyFinal should work */
if (!TEST_int_gt(EVP_DigestVerifyFinal(md_ctx_verify, sig, sig_len), 0))
goto out;
} else {
/*
* For HMAC a doubled call to DigestSignFinal should produce the same
* value as finalization should not happen.
*/
if (!TEST_true(EVP_DigestSignFinal(md_ctx, NULL, &sig2_len))
|| !TEST_ptr(sig2 = OPENSSL_malloc(sig2_len))
|| !TEST_true(EVP_DigestSignFinal(md_ctx, sig2, &sig2_len)))
goto out;
if (!TEST_mem_eq(sig, sig_len, sig2, sig2_len))
goto out;
}
ret = 1;
out:
BIO_free(membio);
BIO_free(mdbio);
EVP_MD_CTX_free(a_md_ctx);
EVP_MD_CTX_free(a_md_ctx_verify);
EVP_PKEY_free(pkey);
OPENSSL_free(sig);
OPENSSL_free(sig2);
EVP_MD_free(mdexp);
return ret;
}
static int test_EVP_DigestVerifyInit(void)
{
int ret = 0;
EVP_PKEY *pkey = NULL;
EVP_MD_CTX *md_ctx = NULL;
if (nullprov != NULL)
return TEST_skip("Test does not support a non-default library context");
if (!TEST_ptr(md_ctx = EVP_MD_CTX_new())
|| !TEST_ptr(pkey = load_example_rsa_key()))
goto out;
if (!TEST_true(EVP_DigestVerifyInit(md_ctx, NULL, EVP_sha256(), NULL, pkey))
|| !TEST_true(EVP_DigestVerifyUpdate(md_ctx, kMsg, sizeof(kMsg)))
|| !TEST_int_gt(EVP_DigestVerifyFinal(md_ctx, kSignature,
sizeof(kSignature)), 0))
goto out;
/* test with reinitialization */
if (!TEST_true(EVP_DigestVerifyInit(md_ctx, NULL, NULL, NULL, NULL))
|| !TEST_true(EVP_DigestVerifyUpdate(md_ctx, kMsg, sizeof(kMsg)))
|| !TEST_int_gt(EVP_DigestVerifyFinal(md_ctx, kSignature,
sizeof(kSignature)), 0))
goto out;
ret = 1;
out:
EVP_MD_CTX_free(md_ctx);
EVP_PKEY_free(pkey);
return ret;
}
#ifndef OPENSSL_NO_SIPHASH
/* test SIPHASH MAC via EVP_PKEY with non-default parameters and reinit */
static int test_siphash_digestsign(void)
{
unsigned char key[16];
unsigned char buf[8], digest[8];
unsigned char expected[8] = {
0x6d, 0x3e, 0x54, 0xc2, 0x2f, 0xf1, 0xfe, 0xe2
};
EVP_PKEY *pkey = NULL;
EVP_MD_CTX *mdctx = NULL;
EVP_PKEY_CTX *ctx = NULL;
int ret = 0;
size_t len = 8;
if (nullprov != NULL)
return TEST_skip("Test does not support a non-default library context");
memset(buf, 0, 8);
memset(key, 1, 16);
if (!TEST_ptr(pkey = EVP_PKEY_new_raw_private_key(EVP_PKEY_SIPHASH, NULL,
key, 16)))
goto out;
if (!TEST_ptr(mdctx = EVP_MD_CTX_create()))
goto out;
if (!TEST_true(EVP_DigestSignInit(mdctx, &ctx, NULL, NULL, pkey)))
goto out;
if (!TEST_int_eq(EVP_PKEY_CTX_ctrl(ctx, -1, EVP_PKEY_OP_SIGNCTX,
EVP_PKEY_CTRL_SET_DIGEST_SIZE,
8, NULL), 1))
goto out;
/* reinitialize */
if (!TEST_true(EVP_DigestSignInit(mdctx, NULL, NULL, NULL, NULL)))
goto out;
if (!TEST_true(EVP_DigestSignUpdate(mdctx, buf, 8)))
goto out;
if (!TEST_true(EVP_DigestSignFinal(mdctx, digest, &len)))
goto out;
if (!TEST_mem_eq(digest, len, expected, sizeof(expected)))
goto out;
ret = 1;
out:
EVP_PKEY_free(pkey);
EVP_MD_CTX_free(mdctx);
return ret;
}
#endif
/*
* Test corner cases of EVP_DigestInit/Update/Final API call behavior.
*/
static int test_EVP_Digest(void)
{
int ret = 0;
EVP_MD_CTX *md_ctx = NULL;
unsigned char md[EVP_MAX_MD_SIZE];
EVP_MD *sha256 = NULL;
EVP_MD *shake256 = NULL;
if (!TEST_ptr(md_ctx = EVP_MD_CTX_new()))
goto out;
if (!TEST_ptr(sha256 = EVP_MD_fetch(testctx, "sha256", testpropq))
|| !TEST_ptr(shake256 = EVP_MD_fetch(testctx, "shake256", testpropq)))
goto out;
if (!TEST_true(EVP_DigestInit_ex(md_ctx, sha256, NULL))
|| !TEST_true(EVP_DigestUpdate(md_ctx, kMsg, sizeof(kMsg)))
|| !TEST_true(EVP_DigestFinal(md_ctx, md, NULL))
/* EVP_DigestFinal resets the EVP_MD_CTX. */
|| !TEST_ptr_eq(EVP_MD_CTX_get0_md(md_ctx), NULL))
goto out;
if (!TEST_true(EVP_DigestInit_ex(md_ctx, sha256, NULL))
|| !TEST_true(EVP_DigestUpdate(md_ctx, kMsg, sizeof(kMsg)))
|| !TEST_true(EVP_DigestFinal_ex(md_ctx, md, NULL))
/* EVP_DigestFinal_ex does not reset the EVP_MD_CTX. */
|| !TEST_ptr(EVP_MD_CTX_get0_md(md_ctx))
/*
* EVP_DigestInit_ex with NULL type should work on
* pre-initialized context.
*/
|| !TEST_true(EVP_DigestInit_ex(md_ctx, NULL, NULL)))
goto out;
if (!TEST_true(EVP_DigestInit_ex(md_ctx, shake256, NULL))
|| !TEST_true(EVP_DigestUpdate(md_ctx, kMsg, sizeof(kMsg)))
|| !TEST_true(EVP_DigestFinalXOF(md_ctx, md, sizeof(md)))
/* EVP_DigestFinalXOF does not reset the EVP_MD_CTX. */
|| !TEST_ptr(EVP_MD_CTX_get0_md(md_ctx))
|| !TEST_true(EVP_DigestInit_ex(md_ctx, NULL, NULL)))
goto out;
ret = 1;
out:
EVP_MD_CTX_free(md_ctx);
EVP_MD_free(sha256);
EVP_MD_free(shake256);
return ret;
}
static int test_EVP_md_null(void)
{
int ret = 0;
EVP_MD_CTX *md_ctx = NULL;
const EVP_MD *md_null = EVP_md_null();
unsigned char md_value[EVP_MAX_MD_SIZE];
unsigned int md_len = sizeof(md_value);
if (nullprov != NULL)
return TEST_skip("Test does not support a non-default library context");
if (!TEST_ptr(md_null)
|| !TEST_ptr(md_ctx = EVP_MD_CTX_new()))
goto out;
if (!TEST_true(EVP_DigestInit_ex(md_ctx, md_null, NULL))
|| !TEST_true(EVP_DigestUpdate(md_ctx, "test", 4))
|| !TEST_true(EVP_DigestFinal_ex(md_ctx, md_value, &md_len)))
goto out;
if (!TEST_uint_eq(md_len, 0))
goto out;
ret = 1;
out:
EVP_MD_CTX_free(md_ctx);
return ret;
}
static int test_d2i_AutoPrivateKey(int i)
{
int ret = 0;
const unsigned char *p;
EVP_PKEY *pkey = NULL;
const APK_DATA *ak = &keydata[i];
const unsigned char *input = ak->kder;
size_t input_len = ak->size;
int expected_id = ak->evptype;
p = input;
if (!TEST_ptr(pkey = d2i_AutoPrivateKey(NULL, &p, input_len))
|| !TEST_ptr_eq(p, input + input_len)
|| !TEST_int_eq(EVP_PKEY_get_id(pkey), expected_id))
goto done;
ret = 1;
done:
EVP_PKEY_free(pkey);
return ret;
}
#ifndef OPENSSL_NO_EC
static const unsigned char ec_public_sect163k1_validxy[] = {
0x30, 0x40, 0x30, 0x10, 0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02,
0x01, 0x06, 0x05, 0x2b, 0x81, 0x04, 0x00, 0x01, 0x03, 0x2c, 0x00, 0x04,
0x02, 0x84, 0x58, 0xa6, 0xd4, 0xa0, 0x35, 0x2b, 0xae, 0xf0, 0xc0, 0x69,
0x05, 0xcf, 0x2a, 0x50, 0x33, 0xf9, 0xe3, 0x92, 0x79, 0x02, 0xd1, 0x7b,
0x9f, 0x22, 0x00, 0xf0, 0x3b, 0x0e, 0x5d, 0x2e, 0xb7, 0x23, 0x24, 0xf3,
0x6a, 0xd8, 0x17, 0x65, 0x41, 0x2f
};
static const unsigned char ec_public_sect163k1_badx[] = {
0x30, 0x40, 0x30, 0x10, 0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02,
0x01, 0x06, 0x05, 0x2b, 0x81, 0x04, 0x00, 0x01, 0x03, 0x2c, 0x00, 0x04,
0x0a, 0x84, 0x58, 0xa6, 0xd4, 0xa0, 0x35, 0x2b, 0xae, 0xf0, 0xc0, 0x69,
0x05, 0xcf, 0x2a, 0x50, 0x33, 0xf9, 0xe3, 0x92, 0xb0, 0x02, 0xd1, 0x7b,
0x9f, 0x22, 0x00, 0xf0, 0x3b, 0x0e, 0x5d, 0x2e, 0xb7, 0x23, 0x24, 0xf3,
0x6a, 0xd8, 0x17, 0x65, 0x41, 0x2f
};
static const unsigned char ec_public_sect163k1_bady[] = {
0x30, 0x40, 0x30, 0x10, 0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02,
0x01, 0x06, 0x05, 0x2b, 0x81, 0x04, 0x00, 0x01, 0x03, 0x2c, 0x00, 0x04,
0x02, 0x84, 0x58, 0xa6, 0xd4, 0xa0, 0x35, 0x2b, 0xae, 0xf0, 0xc0, 0x69,
0x05, 0xcf, 0x2a, 0x50, 0x33, 0xf9, 0xe3, 0x92, 0x79, 0x0a, 0xd1, 0x7b,
0x9f, 0x22, 0x00, 0xf0, 0x3b, 0x0e, 0x5d, 0x2e, 0xb7, 0x23, 0x24, 0xf3,
0x6a, 0xd8, 0x17, 0x65, 0x41, 0xe6
};
static struct ec_der_pub_keys_st {
const unsigned char *der;
size_t len;
int valid;
} ec_der_pub_keys[] = {
{ ec_public_sect163k1_validxy, sizeof(ec_public_sect163k1_validxy), 1 },
{ ec_public_sect163k1_badx, sizeof(ec_public_sect163k1_badx), 0 },
{ ec_public_sect163k1_bady, sizeof(ec_public_sect163k1_bady), 0 },
};
/*
* Tests the range of the decoded EC char2 public point.
* See ec_GF2m_simple_oct2point().
*/
static int test_invalide_ec_char2_pub_range_decode(int id)
{
int ret = 0;
EVP_PKEY *pkey;
pkey = load_example_key("EC", ec_der_pub_keys[id].der,
ec_der_pub_keys[id].len);
ret = (ec_der_pub_keys[id].valid && TEST_ptr(pkey))
|| TEST_ptr_null(pkey);
EVP_PKEY_free(pkey);
return ret;
}
/* Tests loading a bad key in PKCS8 format */
static int test_EVP_PKCS82PKEY(void)
{
int ret = 0;
const unsigned char *derp = kExampleBadECKeyDER;
PKCS8_PRIV_KEY_INFO *p8inf = NULL;
EVP_PKEY *pkey = NULL;
if (!TEST_ptr(p8inf = d2i_PKCS8_PRIV_KEY_INFO(NULL, &derp,
sizeof(kExampleBadECKeyDER))))
goto done;
if (!TEST_ptr_eq(derp,
kExampleBadECKeyDER + sizeof(kExampleBadECKeyDER)))
goto done;
if (!TEST_ptr_null(pkey = EVP_PKCS82PKEY(p8inf)))
goto done;
ret = 1;
done:
PKCS8_PRIV_KEY_INFO_free(p8inf);
EVP_PKEY_free(pkey);
return ret;
}
#endif
static int test_EVP_PKCS82PKEY_wrong_tag(void)
{
EVP_PKEY *pkey = NULL;
EVP_PKEY *pkey2 = NULL;
BIO *membio = NULL;
char *membuf = NULL;
PKCS8_PRIV_KEY_INFO *p8inf = NULL;
int ok = 0;
if (testctx != NULL)
/* test not supported with non-default context */
return 1;
if (!TEST_ptr(membio = BIO_new(BIO_s_mem()))
|| !TEST_ptr(pkey = load_example_rsa_key())
|| !TEST_int_gt(i2d_PKCS8PrivateKey_bio(membio, pkey, NULL,
NULL, 0, NULL, NULL),
0)
|| !TEST_int_gt(BIO_get_mem_data(membio, &membuf), 0)
|| !TEST_ptr(p8inf = d2i_PKCS8_PRIV_KEY_INFO_bio(membio, NULL))
|| !TEST_ptr(pkey2 = EVP_PKCS82PKEY(p8inf))
|| !TEST_int_eq(ERR_peek_last_error(), 0)) {
goto done;
}
ok = 1;
done:
EVP_PKEY_free(pkey);
EVP_PKEY_free(pkey2);
PKCS8_PRIV_KEY_INFO_free(p8inf);
BIO_free_all(membio);
return ok;
}
/* This uses kExampleRSAKeyDER and kExampleRSAKeyPKCS8 to verify encoding */
static int test_privatekey_to_pkcs8(void)
{
EVP_PKEY *pkey = NULL;
BIO *membio = NULL;
char *membuf = NULL;
long membuf_len = 0;
int ok = 0;
if (!TEST_ptr(membio = BIO_new(BIO_s_mem()))
|| !TEST_ptr(pkey = load_example_rsa_key())
|| !TEST_int_gt(i2d_PKCS8PrivateKey_bio(membio, pkey, NULL,
NULL, 0, NULL, NULL),
0)
|| !TEST_int_gt(membuf_len = BIO_get_mem_data(membio, &membuf), 0)
|| !TEST_ptr(membuf)
|| !TEST_mem_eq(membuf, (size_t)membuf_len,
kExampleRSAKeyPKCS8, sizeof(kExampleRSAKeyPKCS8))
/*
* We try to write PEM as well, just to see that it doesn't err, but
* assume that the result is correct.
*/
|| !TEST_int_gt(PEM_write_bio_PKCS8PrivateKey(membio, pkey, NULL,
NULL, 0, NULL, NULL),
0))
goto done;
ok = 1;
done:
EVP_PKEY_free(pkey);
BIO_free_all(membio);
return ok;
}
#ifndef OPENSSL_NO_EC
static const struct {
int encoding;
const char *encoding_name;
} ec_encodings[] = {
{ OPENSSL_EC_EXPLICIT_CURVE, OSSL_PKEY_EC_ENCODING_EXPLICIT },
{ OPENSSL_EC_NAMED_CURVE, OSSL_PKEY_EC_ENCODING_GROUP }
};
static int ec_export_get_encoding_cb(const OSSL_PARAM params[], void *arg)
{
const OSSL_PARAM *p;
const char *enc_name = NULL;
int *enc = arg;
size_t i;
*enc = -1;
if (!TEST_ptr(p = OSSL_PARAM_locate_const(params,
OSSL_PKEY_PARAM_EC_ENCODING))
|| !TEST_true(OSSL_PARAM_get_utf8_string_ptr(p, &enc_name)))
return 0;
for (i = 0; i < OSSL_NELEM(ec_encodings); i++) {
if (OPENSSL_strcasecmp(enc_name, ec_encodings[i].encoding_name) == 0) {
*enc = ec_encodings[i].encoding;
break;
}
}
return (*enc != -1);
}
static int test_EC_keygen_with_enc(int idx)
{
EVP_PKEY *params = NULL, *key = NULL;
EVP_PKEY_CTX *pctx = NULL, *kctx = NULL;
int enc;
int ret = 0;
enc = ec_encodings[idx].encoding;
/* Create key parameters */
if (!TEST_ptr(pctx = EVP_PKEY_CTX_new_from_name(testctx, "EC", NULL))
|| !TEST_int_gt(EVP_PKEY_paramgen_init(pctx), 0)
|| !TEST_int_gt(EVP_PKEY_CTX_set_group_name(pctx, "P-256"), 0)
|| !TEST_int_gt(EVP_PKEY_CTX_set_ec_param_enc(pctx, enc), 0)
|| !TEST_true(EVP_PKEY_paramgen(pctx, &params))
|| !TEST_ptr(params))
goto done;
/* Create key */
if (!TEST_ptr(kctx = EVP_PKEY_CTX_new_from_pkey(testctx, params, NULL))
|| !TEST_int_gt(EVP_PKEY_keygen_init(kctx), 0)
|| !TEST_true(EVP_PKEY_keygen(kctx, &key))
|| !TEST_ptr(key))
goto done;
/* Check that the encoding got all the way into the key */
if (!TEST_true(evp_keymgmt_util_export(key, OSSL_KEYMGMT_SELECT_ALL,
ec_export_get_encoding_cb, &enc))
|| !TEST_int_eq(enc, ec_encodings[idx].encoding))
goto done;
ret = 1;
done:
EVP_PKEY_free(key);
EVP_PKEY_free(params);
EVP_PKEY_CTX_free(kctx);
EVP_PKEY_CTX_free(pctx);
return ret;
}
#endif
#if !defined(OPENSSL_NO_SM2)
static int test_EVP_SM2_verify(void)
{
const char *pubkey =
"-----BEGIN PUBLIC KEY-----\n"
"MFkwEwYHKoZIzj0CAQYIKoEcz1UBgi0DQgAEp1KLWq1ZE2jmoAnnBJE1LBGxVr18\n"
"YvvqECWCpXfAQ9qUJ+UmthnUPf0iM3SaXKHe6PlLIDyNlWMWb9RUh/yU3g==\n"
"-----END PUBLIC KEY-----\n";
const char *msg = "message digest";
const char *id = "ALICE123@YAHOO.COM";
const uint8_t signature[] = {
0x30, 0x44, 0x02, 0x20, 0x5b, 0xdb, 0xab, 0x81, 0x4f, 0xbb,
0x8b, 0x69, 0xb1, 0x05, 0x9c, 0x99, 0x3b, 0xb2, 0x45, 0x06,
0x4a, 0x30, 0x15, 0x59, 0x84, 0xcd, 0xee, 0x30, 0x60, 0x36,
0x57, 0x87, 0xef, 0x5c, 0xd0, 0xbe, 0x02, 0x20, 0x43, 0x8d,
0x1f, 0xc7, 0x77, 0x72, 0x39, 0xbb, 0x72, 0xe1, 0xfd, 0x07,
0x58, 0xd5, 0x82, 0xc8, 0x2d, 0xba, 0x3b, 0x2c, 0x46, 0x24,
0xe3, 0x50, 0xff, 0x04, 0xc7, 0xa0, 0x71, 0x9f, 0xa4, 0x70
};
int rc = 0;
BIO *bio = NULL;
EVP_PKEY *pkey = NULL;
EVP_MD_CTX *mctx = NULL;
EVP_PKEY_CTX *pctx = NULL;
EVP_MD *sm3 = NULL;
bio = BIO_new_mem_buf(pubkey, strlen(pubkey));
if (!TEST_true(bio != NULL))
goto done;
pkey = PEM_read_bio_PUBKEY_ex(bio, NULL, NULL, NULL, testctx, testpropq);
if (!TEST_true(pkey != NULL))
goto done;
if (!TEST_true(EVP_PKEY_is_a(pkey, "SM2")))
goto done;
if (!TEST_ptr(mctx = EVP_MD_CTX_new()))
goto done;
if (!TEST_ptr(pctx = EVP_PKEY_CTX_new_from_pkey(testctx, pkey, testpropq)))
goto done;
EVP_MD_CTX_set_pkey_ctx(mctx, pctx);
if (!TEST_ptr(sm3 = EVP_MD_fetch(testctx, "sm3", testpropq)))
goto done;
if (!TEST_true(EVP_DigestVerifyInit(mctx, NULL, sm3, NULL, pkey)))
goto done;
if (!TEST_int_gt(EVP_PKEY_CTX_set1_id(pctx, id, strlen(id)), 0))
goto done;
if (!TEST_true(EVP_DigestVerifyUpdate(mctx, msg, strlen(msg))))
goto done;
if (!TEST_int_gt(EVP_DigestVerifyFinal(mctx, signature, sizeof(signature)), 0))
goto done;
rc = 1;
done:
BIO_free(bio);
EVP_PKEY_free(pkey);
EVP_PKEY_CTX_free(pctx);
EVP_MD_CTX_free(mctx);
EVP_MD_free(sm3);
return rc;
}
static int test_EVP_SM2(void)
{
int ret = 0;
EVP_PKEY *pkey = NULL;
EVP_PKEY *pkeyparams = NULL;
EVP_PKEY_CTX *pctx = NULL;
EVP_PKEY_CTX *kctx = NULL;
EVP_PKEY_CTX *sctx = NULL;
size_t sig_len = 0;
unsigned char *sig = NULL;
EVP_MD_CTX *md_ctx = NULL;
EVP_MD_CTX *md_ctx_verify = NULL;
EVP_PKEY_CTX *cctx = NULL;
EVP_MD *check_md = NULL;
uint8_t ciphertext[128];
size_t ctext_len = sizeof(ciphertext);
uint8_t plaintext[8];
size_t ptext_len = sizeof(plaintext);
uint8_t sm2_id[] = {1, 2, 3, 4, 'l', 'e', 't', 't', 'e', 'r'};
OSSL_PARAM sparams[2] = {OSSL_PARAM_END, OSSL_PARAM_END};
OSSL_PARAM gparams[2] = {OSSL_PARAM_END, OSSL_PARAM_END};
int i;
char mdname[OSSL_MAX_NAME_SIZE];
if (!TEST_ptr(pctx = EVP_PKEY_CTX_new_from_name(testctx,
"SM2", testpropq)))
goto done;
if (!TEST_true(EVP_PKEY_paramgen_init(pctx) == 1))
goto done;
if (!TEST_int_gt(EVP_PKEY_CTX_set_ec_paramgen_curve_nid(pctx, NID_sm2), 0))
goto done;
if (!TEST_true(EVP_PKEY_paramgen(pctx, &pkeyparams)))
goto done;
if (!TEST_ptr(kctx = EVP_PKEY_CTX_new_from_pkey(testctx,
pkeyparams, testpropq)))
goto done;
if (!TEST_int_gt(EVP_PKEY_keygen_init(kctx), 0))
goto done;
if (!TEST_true(EVP_PKEY_keygen(kctx, &pkey)))
goto done;
if (!TEST_ptr(md_ctx = EVP_MD_CTX_new()))
goto done;
if (!TEST_ptr(md_ctx_verify = EVP_MD_CTX_new()))
goto done;
if (!TEST_ptr(sctx = EVP_PKEY_CTX_new_from_pkey(testctx, pkey, testpropq)))
goto done;
EVP_MD_CTX_set_pkey_ctx(md_ctx, sctx);
EVP_MD_CTX_set_pkey_ctx(md_ctx_verify, sctx);
if (!TEST_ptr(check_md = EVP_MD_fetch(testctx, "sm3", testpropq)))
goto done;
if (!TEST_true(EVP_DigestSignInit(md_ctx, NULL, check_md, NULL, pkey)))
goto done;
if (!TEST_int_gt(EVP_PKEY_CTX_set1_id(sctx, sm2_id, sizeof(sm2_id)), 0))
goto done;
if (!TEST_true(EVP_DigestSignUpdate(md_ctx, kMsg, sizeof(kMsg))))
goto done;
/* Determine the size of the signature. */
if (!TEST_true(EVP_DigestSignFinal(md_ctx, NULL, &sig_len)))
goto done;
if (!TEST_ptr(sig = OPENSSL_malloc(sig_len)))
goto done;
if (!TEST_true(EVP_DigestSignFinal(md_ctx, sig, &sig_len)))
goto done;
/* Ensure that the signature round-trips. */
if (!TEST_true(EVP_DigestVerifyInit(md_ctx_verify, NULL, check_md, NULL,
pkey)))
goto done;
if (!TEST_int_gt(EVP_PKEY_CTX_set1_id(sctx, sm2_id, sizeof(sm2_id)), 0))
goto done;
if (!TEST_true(EVP_DigestVerifyUpdate(md_ctx_verify, kMsg, sizeof(kMsg))))
goto done;
if (!TEST_int_gt(EVP_DigestVerifyFinal(md_ctx_verify, sig, sig_len), 0))
goto done;
/*
* Try verify again with non-matching 0 length id but ensure that it can
* be set on the context and overrides the previous value.
*/
if (!TEST_true(EVP_DigestVerifyInit(md_ctx_verify, NULL, check_md, NULL,
pkey)))
goto done;
if (!TEST_int_gt(EVP_PKEY_CTX_set1_id(sctx, NULL, 0), 0))
goto done;
if (!TEST_true(EVP_DigestVerifyUpdate(md_ctx_verify, kMsg, sizeof(kMsg))))
goto done;
if (!TEST_int_eq(EVP_DigestVerifyFinal(md_ctx_verify, sig, sig_len), 0))
goto done;
/* now check encryption/decryption */
gparams[0] = OSSL_PARAM_construct_utf8_string(OSSL_ASYM_CIPHER_PARAM_DIGEST,
mdname, sizeof(mdname));
for (i = 0; i < 2; i++) {
const char *mdnames[] = {
#ifndef OPENSSL_NO_SM3
"SM3",
#else
NULL,
#endif
"SHA2-256" };
EVP_PKEY_CTX_free(cctx);
if (mdnames[i] == NULL)
continue;
sparams[0] =
OSSL_PARAM_construct_utf8_string(OSSL_ASYM_CIPHER_PARAM_DIGEST,
(char *)mdnames[i], 0);
if (!TEST_ptr(cctx = EVP_PKEY_CTX_new_from_pkey(testctx,
pkey, testpropq)))
goto done;
if (!TEST_true(EVP_PKEY_encrypt_init(cctx)))
goto done;
if (!TEST_true(EVP_PKEY_CTX_set_params(cctx, sparams)))
goto done;
if (!TEST_true(EVP_PKEY_encrypt(cctx, ciphertext, &ctext_len, kMsg,
sizeof(kMsg))))
goto done;
if (!TEST_int_gt(EVP_PKEY_decrypt_init(cctx), 0))
goto done;
if (!TEST_true(EVP_PKEY_CTX_set_params(cctx, sparams)))
goto done;
if (!TEST_int_gt(EVP_PKEY_decrypt(cctx, plaintext, &ptext_len, ciphertext,
ctext_len), 0))
goto done;
if (!TEST_true(EVP_PKEY_CTX_get_params(cctx, gparams)))
goto done;
/*
* Test we're still using the digest we think we are.
* Because of aliases, the easiest is to fetch the digest and
* check the name with EVP_MD_is_a().
*/
EVP_MD_free(check_md);
if (!TEST_ptr(check_md = EVP_MD_fetch(testctx, mdname, testpropq)))
goto done;
if (!TEST_true(EVP_MD_is_a(check_md, mdnames[i]))) {
TEST_info("Fetched md %s isn't %s", mdname, mdnames[i]);
goto done;
}
if (!TEST_true(ptext_len == sizeof(kMsg)))
goto done;
if (!TEST_true(memcmp(plaintext, kMsg, sizeof(kMsg)) == 0))
goto done;
}
ret = 1;
done:
EVP_PKEY_CTX_free(pctx);
EVP_PKEY_CTX_free(kctx);
EVP_PKEY_CTX_free(sctx);
EVP_PKEY_CTX_free(cctx);
EVP_PKEY_free(pkey);
EVP_PKEY_free(pkeyparams);
EVP_MD_CTX_free(md_ctx);
EVP_MD_CTX_free(md_ctx_verify);
EVP_MD_free(check_md);
OPENSSL_free(sig);
return ret;
}
#endif
static struct keys_st {
int type;
char *priv;
char *pub;
} keys[] = {
{
EVP_PKEY_HMAC, "0123456789", NULL
},
{
EVP_PKEY_HMAC, "", NULL
#ifndef OPENSSL_NO_POLY1305
}, {
EVP_PKEY_POLY1305, "01234567890123456789012345678901", NULL
#endif
#ifndef OPENSSL_NO_SIPHASH
}, {
EVP_PKEY_SIPHASH, "0123456789012345", NULL
#endif
},
#ifndef OPENSSL_NO_EC
{
EVP_PKEY_X25519, "01234567890123456789012345678901",
"abcdefghijklmnopqrstuvwxyzabcdef"
}, {
EVP_PKEY_ED25519, "01234567890123456789012345678901",
"abcdefghijklmnopqrstuvwxyzabcdef"
}, {
EVP_PKEY_X448,
"01234567890123456789012345678901234567890123456789012345",
"abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcd"
}, {
EVP_PKEY_ED448,
"012345678901234567890123456789012345678901234567890123456",
"abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcde"
}
#endif
};
static int test_set_get_raw_keys_int(int tst, int pub, int uselibctx)
{
int ret = 0;
unsigned char buf[80];
unsigned char *in;
size_t inlen, len = 0, shortlen = 1;
EVP_PKEY *pkey;
/* Check if this algorithm supports public keys */
if (pub && keys[tst].pub == NULL)
return 1;
memset(buf, 0, sizeof(buf));
if (pub) {
#ifndef OPENSSL_NO_EC
inlen = strlen(keys[tst].pub);
in = (unsigned char *)keys[tst].pub;
if (uselibctx) {
pkey = EVP_PKEY_new_raw_public_key_ex(
testctx,
OBJ_nid2sn(keys[tst].type),
NULL,
in,
inlen);
} else {
pkey = EVP_PKEY_new_raw_public_key(keys[tst].type,
NULL,
in,
inlen);
}
#else
return 1;
#endif
} else {
inlen = strlen(keys[tst].priv);
in = (unsigned char *)keys[tst].priv;
if (uselibctx) {
pkey = EVP_PKEY_new_raw_private_key_ex(
testctx, OBJ_nid2sn(keys[tst].type),
NULL,
in,
inlen);
} else {
pkey = EVP_PKEY_new_raw_private_key(keys[tst].type,
NULL,
in,
inlen);
}
}
if (!TEST_ptr(pkey)
|| !TEST_int_eq(EVP_PKEY_eq(pkey, pkey), 1)
|| (!pub && !TEST_true(EVP_PKEY_get_raw_private_key(pkey, NULL, &len)))
|| (pub && !TEST_true(EVP_PKEY_get_raw_public_key(pkey, NULL, &len)))
|| !TEST_true(len == inlen))
goto done;
if (tst != 1) {
/*
* Test that supplying a buffer that is too small fails. Doesn't apply
* to HMAC with a zero length key
*/
if ((!pub && !TEST_false(EVP_PKEY_get_raw_private_key(pkey, buf,
&shortlen)))
|| (pub && !TEST_false(EVP_PKEY_get_raw_public_key(pkey, buf,
&shortlen))))
goto done;
}
if ((!pub && !TEST_true(EVP_PKEY_get_raw_private_key(pkey, buf, &len)))
|| (pub && !TEST_true(EVP_PKEY_get_raw_public_key(pkey, buf, &len)))
|| !TEST_mem_eq(in, inlen, buf, len))
goto done;
ret = 1;
done:
EVP_PKEY_free(pkey);
return ret;
}
static int test_set_get_raw_keys(int tst)
{
return (nullprov != NULL || test_set_get_raw_keys_int(tst, 0, 0))
&& test_set_get_raw_keys_int(tst, 0, 1)
&& (nullprov != NULL || test_set_get_raw_keys_int(tst, 1, 0))
&& test_set_get_raw_keys_int(tst, 1, 1);
}
#ifndef OPENSSL_NO_DEPRECATED_3_0
static int pkey_custom_check(EVP_PKEY *pkey)
{
return 0xbeef;
}
static int pkey_custom_pub_check(EVP_PKEY *pkey)
{
return 0xbeef;
}
static int pkey_custom_param_check(EVP_PKEY *pkey)
{
return 0xbeef;
}
static EVP_PKEY_METHOD *custom_pmeth;
#endif
static int test_EVP_PKEY_check(int i)
{
int ret = 0;
EVP_PKEY *pkey = NULL;
EVP_PKEY_CTX *ctx = NULL;
#ifndef OPENSSL_NO_DEPRECATED_3_0
EVP_PKEY_CTX *ctx2 = NULL;
#endif
const APK_DATA *ak = &keycheckdata[i];
const unsigned char *input = ak->kder;
size_t input_len = ak->size;
int expected_id = ak->evptype;
int expected_check = ak->check;
int expected_pub_check = ak->pub_check;
int expected_param_check = ak->param_check;
int type = ak->type;
if (!TEST_ptr(pkey = load_example_key(ak->keytype, input, input_len)))
goto done;
if (type == 0
&& !TEST_int_eq(EVP_PKEY_get_id(pkey), expected_id))
goto done;
if (!TEST_ptr(ctx = EVP_PKEY_CTX_new_from_pkey(testctx, pkey, testpropq)))
goto done;
if (!TEST_int_eq(EVP_PKEY_check(ctx), expected_check))
goto done;
if (!TEST_int_eq(EVP_PKEY_public_check(ctx), expected_pub_check))
goto done;
if (!TEST_int_eq(EVP_PKEY_param_check(ctx), expected_param_check))
goto done;
#ifndef OPENSSL_NO_DEPRECATED_3_0
ctx2 = EVP_PKEY_CTX_new_id(0xdefaced, NULL);
/* assign the pkey directly, as an internal test */
EVP_PKEY_up_ref(pkey);
ctx2->pkey = pkey;
if (!TEST_int_eq(EVP_PKEY_check(ctx2), 0xbeef))
goto done;
if (!TEST_int_eq(EVP_PKEY_public_check(ctx2), 0xbeef))
goto done;
if (!TEST_int_eq(EVP_PKEY_param_check(ctx2), 0xbeef))
goto done;
#endif
ret = 1;
done:
EVP_PKEY_CTX_free(ctx);
#ifndef OPENSSL_NO_DEPRECATED_3_0
EVP_PKEY_CTX_free(ctx2);
#endif
EVP_PKEY_free(pkey);
return ret;
}
#ifndef OPENSSL_NO_CMAC
static int get_cmac_val(EVP_PKEY *pkey, unsigned char *mac)
{
EVP_MD_CTX *mdctx = EVP_MD_CTX_new();
const char msg[] = "Hello World";
size_t maclen = AES_BLOCK_SIZE;
int ret = 1;
if (!TEST_ptr(mdctx)
|| !TEST_true(EVP_DigestSignInit_ex(mdctx, NULL, NULL, testctx,
testpropq, pkey, NULL))
|| !TEST_true(EVP_DigestSignUpdate(mdctx, msg, sizeof(msg)))
|| !TEST_true(EVP_DigestSignFinal(mdctx, mac, &maclen))
|| !TEST_size_t_eq(maclen, AES_BLOCK_SIZE))
ret = 0;
EVP_MD_CTX_free(mdctx);
return ret;
}
static int test_CMAC_keygen(void)
{
static 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
};
EVP_PKEY_CTX *kctx = NULL;
int ret = 0;
EVP_PKEY *pkey = NULL;
unsigned char mac[AES_BLOCK_SIZE];
# if !defined(OPENSSL_NO_DEPRECATED_3_0)
unsigned char mac2[AES_BLOCK_SIZE];
# endif
if (nullprov != NULL)
return TEST_skip("Test does not support a non-default library context");
/*
* This is a legacy method for CMACs, but should still work.
* This verifies that it works without an ENGINE.
*/
kctx = EVP_PKEY_CTX_new_id(EVP_PKEY_CMAC, NULL);
/* Test a CMAC key created using the "generated" method */
if (!TEST_int_gt(EVP_PKEY_keygen_init(kctx), 0)
|| !TEST_int_gt(EVP_PKEY_CTX_ctrl(kctx, -1, EVP_PKEY_OP_KEYGEN,
EVP_PKEY_CTRL_CIPHER,
0, (void *)EVP_aes_256_ecb()), 0)
|| !TEST_int_gt(EVP_PKEY_CTX_ctrl(kctx, -1, EVP_PKEY_OP_KEYGEN,
EVP_PKEY_CTRL_SET_MAC_KEY,
sizeof(key), (void *)key), 0)
|| !TEST_int_gt(EVP_PKEY_keygen(kctx, &pkey), 0)
|| !TEST_ptr(pkey)
|| !TEST_true(get_cmac_val(pkey, mac)))
goto done;
# if !defined(OPENSSL_NO_DEPRECATED_3_0)
EVP_PKEY_free(pkey);
/*
* Test a CMAC key using the direct method, and compare with the mac
* created above.
*/
pkey = EVP_PKEY_new_CMAC_key(NULL, key, sizeof(key), EVP_aes_256_ecb());
if (!TEST_ptr(pkey)
|| !TEST_true(get_cmac_val(pkey, mac2))
|| !TEST_mem_eq(mac, sizeof(mac), mac2, sizeof(mac2)))
goto done;
# endif
ret = 1;
done:
EVP_PKEY_free(pkey);
EVP_PKEY_CTX_free(kctx);
return ret;
}
#endif
static int test_HKDF(void)
{
EVP_PKEY_CTX *pctx;
unsigned char out[20];
size_t outlen;
int i, ret = 0;
unsigned char salt[] = "0123456789";
unsigned char key[] = "012345678901234567890123456789";
unsigned char info[] = "infostring";
const unsigned char expected[] = {
0xe5, 0x07, 0x70, 0x7f, 0xc6, 0x78, 0xd6, 0x54, 0x32, 0x5f, 0x7e, 0xc5,
0x7b, 0x59, 0x3e, 0xd8, 0x03, 0x6b, 0xed, 0xca
};
size_t expectedlen = sizeof(expected);
if (!TEST_ptr(pctx = EVP_PKEY_CTX_new_from_name(testctx, "HKDF", testpropq)))
goto done;
/* We do this twice to test reuse of the EVP_PKEY_CTX */
for (i = 0; i < 2; i++) {
outlen = sizeof(out);
memset(out, 0, outlen);
if (!TEST_int_gt(EVP_PKEY_derive_init(pctx), 0)
|| !TEST_int_gt(EVP_PKEY_CTX_set_hkdf_md(pctx, EVP_sha256()), 0)
|| !TEST_int_gt(EVP_PKEY_CTX_set1_hkdf_salt(pctx, salt,
sizeof(salt) - 1), 0)
|| !TEST_int_gt(EVP_PKEY_CTX_set1_hkdf_key(pctx, key,
sizeof(key) - 1), 0)
|| !TEST_int_gt(EVP_PKEY_CTX_add1_hkdf_info(pctx, info,
sizeof(info) - 1), 0)
|| !TEST_int_gt(EVP_PKEY_derive(pctx, out, &outlen), 0)
|| !TEST_mem_eq(out, outlen, expected, expectedlen))
goto done;
}
ret = 1;
done:
EVP_PKEY_CTX_free(pctx);
return ret;
}
static int test_emptyikm_HKDF(void)
{
EVP_PKEY_CTX *pctx;
unsigned char out[20];
size_t outlen;
int ret = 0;
unsigned char salt[] = "9876543210";
unsigned char key[] = "";
unsigned char info[] = "stringinfo";
const unsigned char expected[] = {
0x68, 0x81, 0xa5, 0x3e, 0x5b, 0x9c, 0x7b, 0x6f, 0x2e, 0xec, 0xc8, 0x47,
0x7c, 0xfa, 0x47, 0x35, 0x66, 0x82, 0x15, 0x30
};
size_t expectedlen = sizeof(expected);
if (!TEST_ptr(pctx = EVP_PKEY_CTX_new_from_name(testctx, "HKDF", testpropq)))
goto done;
outlen = sizeof(out);
memset(out, 0, outlen);
if (!TEST_int_gt(EVP_PKEY_derive_init(pctx), 0)
|| !TEST_int_gt(EVP_PKEY_CTX_set_hkdf_md(pctx, EVP_sha256()), 0)
|| !TEST_int_gt(EVP_PKEY_CTX_set1_hkdf_salt(pctx, salt,
sizeof(salt) - 1), 0)
|| !TEST_int_gt(EVP_PKEY_CTX_set1_hkdf_key(pctx, key,
sizeof(key) - 1), 0)
|| !TEST_int_gt(EVP_PKEY_CTX_add1_hkdf_info(pctx, info,
sizeof(info) - 1), 0)
|| !TEST_int_gt(EVP_PKEY_derive(pctx, out, &outlen), 0)
|| !TEST_mem_eq(out, outlen, expected, expectedlen))
goto done;
ret = 1;
done:
EVP_PKEY_CTX_free(pctx);
return ret;
}
+static int test_empty_salt_info_HKDF(void)
+{
+ EVP_PKEY_CTX *pctx;
+ unsigned char out[20];
+ size_t outlen;
+ int ret = 0;
+ unsigned char salt[] = "";
+ unsigned char key[] = "012345678901234567890123456789";
+ unsigned char info[] = "";
+ const unsigned char expected[] = {
+ 0x67, 0x12, 0xf9, 0x27, 0x8a, 0x8a, 0x3a, 0x8f, 0x7d, 0x2c, 0xa3, 0x6a,
+ 0xaa, 0xe9, 0xb3, 0xb9, 0x52, 0x5f, 0xe0, 0x06,
+ };
+ size_t expectedlen = sizeof(expected);
+
+ if (!TEST_ptr(pctx = EVP_PKEY_CTX_new_from_name(testctx, "HKDF", testpropq)))
+ goto done;
+
+ outlen = sizeof(out);
+ memset(out, 0, outlen);
+
+ if (!TEST_int_gt(EVP_PKEY_derive_init(pctx), 0)
+ || !TEST_int_gt(EVP_PKEY_CTX_set_hkdf_md(pctx, EVP_sha256()), 0)
+ || !TEST_int_gt(EVP_PKEY_CTX_set1_hkdf_salt(pctx, salt,
+ sizeof(salt) - 1), 0)
+ || !TEST_int_gt(EVP_PKEY_CTX_set1_hkdf_key(pctx, key,
+ sizeof(key) - 1), 0)
+ || !TEST_int_gt(EVP_PKEY_CTX_add1_hkdf_info(pctx, info,
+ sizeof(info) - 1), 0)
+ || !TEST_int_gt(EVP_PKEY_derive(pctx, out, &outlen), 0)
+ || !TEST_mem_eq(out, outlen, expected, expectedlen))
+ goto done;
+
+ ret = 1;
+
+ done:
+ EVP_PKEY_CTX_free(pctx);
+
+ return ret;
+}
+
#ifndef OPENSSL_NO_EC
static int test_X509_PUBKEY_inplace(void)
{
int ret = 0;
X509_PUBKEY *xp = X509_PUBKEY_new_ex(testctx, testpropq);
const unsigned char *p = kExampleECPubKeyDER;
size_t input_len = sizeof(kExampleECPubKeyDER);
if (!TEST_ptr(xp))
goto done;
if (!TEST_ptr(d2i_X509_PUBKEY(&xp, &p, input_len)))
goto done;
if (!TEST_ptr(X509_PUBKEY_get0(xp)))
goto done;
p = kExampleBadECPubKeyDER;
input_len = sizeof(kExampleBadECPubKeyDER);
if (!TEST_ptr(xp = d2i_X509_PUBKEY(&xp, &p, input_len)))
goto done;
if (!TEST_true(X509_PUBKEY_get0(xp) == NULL))
goto done;
ret = 1;
done:
X509_PUBKEY_free(xp);
return ret;
}
static int test_X509_PUBKEY_dup(void)
{
int ret = 0;
X509_PUBKEY *xp = NULL, *xq = NULL;
const unsigned char *p = kExampleECPubKeyDER;
size_t input_len = sizeof(kExampleECPubKeyDER);
xp = X509_PUBKEY_new_ex(testctx, testpropq);
if (!TEST_ptr(xp)
|| !TEST_ptr(d2i_X509_PUBKEY(&xp, &p, input_len))
|| !TEST_ptr(xq = X509_PUBKEY_dup(xp))
|| !TEST_ptr_ne(xp, xq))
goto done;
if (!TEST_ptr(X509_PUBKEY_get0(xq))
|| !TEST_ptr(X509_PUBKEY_get0(xp))
|| !TEST_ptr_ne(X509_PUBKEY_get0(xq), X509_PUBKEY_get0(xp)))
goto done;
X509_PUBKEY_free(xq);
xq = NULL;
p = kExampleBadECPubKeyDER;
input_len = sizeof(kExampleBadECPubKeyDER);
if (!TEST_ptr(xp = d2i_X509_PUBKEY(&xp, &p, input_len))
|| !TEST_ptr(xq = X509_PUBKEY_dup(xp)))
goto done;
X509_PUBKEY_free(xp);
xp = NULL;
if (!TEST_true(X509_PUBKEY_get0(xq) == NULL))
goto done;
ret = 1;
done:
X509_PUBKEY_free(xp);
X509_PUBKEY_free(xq);
return ret;
}
#endif /* OPENSSL_NO_EC */
/* Test getting and setting parameters on an EVP_PKEY_CTX */
static int test_EVP_PKEY_CTX_get_set_params(EVP_PKEY *pkey)
{
EVP_MD_CTX *mdctx = NULL;
EVP_PKEY_CTX *ctx = NULL;
const OSSL_PARAM *params;
OSSL_PARAM ourparams[2], *param = ourparams, *param_md;
int ret = 0;
const EVP_MD *md;
char mdname[OSSL_MAX_NAME_SIZE];
char ssl3ms[48];
/* Initialise a sign operation */
ctx = EVP_PKEY_CTX_new_from_pkey(testctx, pkey, testpropq);
if (!TEST_ptr(ctx)
|| !TEST_int_gt(EVP_PKEY_sign_init(ctx), 0))
goto err;
/*
* We should be able to query the parameters now.
*/
params = EVP_PKEY_CTX_settable_params(ctx);
if (!TEST_ptr(params)
|| !TEST_ptr(OSSL_PARAM_locate_const(params,
OSSL_SIGNATURE_PARAM_DIGEST)))
goto err;
params = EVP_PKEY_CTX_gettable_params(ctx);
if (!TEST_ptr(params)
|| !TEST_ptr(OSSL_PARAM_locate_const(params,
OSSL_SIGNATURE_PARAM_ALGORITHM_ID))
|| !TEST_ptr(OSSL_PARAM_locate_const(params,
OSSL_SIGNATURE_PARAM_DIGEST)))
goto err;
/*
* Test getting and setting params via EVP_PKEY_CTX_set_params() and
* EVP_PKEY_CTX_get_params()
*/
strcpy(mdname, "SHA512");
param_md = param;
*param++ = OSSL_PARAM_construct_utf8_string(OSSL_SIGNATURE_PARAM_DIGEST,
mdname, 0);
*param++ = OSSL_PARAM_construct_end();
if (!TEST_true(EVP_PKEY_CTX_set_params(ctx, ourparams)))
goto err;
mdname[0] = '\0';
*param_md = OSSL_PARAM_construct_utf8_string(OSSL_SIGNATURE_PARAM_DIGEST,
mdname, sizeof(mdname));
if (!TEST_true(EVP_PKEY_CTX_get_params(ctx, ourparams))
|| !TEST_str_eq(mdname, "SHA512"))
goto err;
/*
* Test the TEST_PKEY_CTX_set_signature_md() and
* TEST_PKEY_CTX_get_signature_md() functions
*/
if (!TEST_int_gt(EVP_PKEY_CTX_set_signature_md(ctx, EVP_sha256()), 0)
|| !TEST_int_gt(EVP_PKEY_CTX_get_signature_md(ctx, &md), 0)
|| !TEST_ptr_eq(md, EVP_sha256()))
goto err;
/*
* Test getting MD parameters via an associated EVP_PKEY_CTX
*/
mdctx = EVP_MD_CTX_new();
if (!TEST_ptr(mdctx)
|| !TEST_true(EVP_DigestSignInit_ex(mdctx, NULL, "SHA1", testctx, testpropq,
pkey, NULL)))
goto err;
/*
* We now have an EVP_MD_CTX with an EVP_PKEY_CTX inside it. We should be
* able to obtain the digest's settable parameters from the provider.
*/
params = EVP_MD_CTX_settable_params(mdctx);
if (!TEST_ptr(params)
|| !TEST_int_eq(strcmp(params[0].key, OSSL_DIGEST_PARAM_SSL3_MS), 0)
/* The final key should be NULL */
|| !TEST_ptr_null(params[1].key))
goto err;
param = ourparams;
memset(ssl3ms, 0, sizeof(ssl3ms));
*param++ = OSSL_PARAM_construct_octet_string(OSSL_DIGEST_PARAM_SSL3_MS,
ssl3ms, sizeof(ssl3ms));
*param++ = OSSL_PARAM_construct_end();
if (!TEST_true(EVP_MD_CTX_set_params(mdctx, ourparams)))
goto err;
ret = 1;
err:
EVP_MD_CTX_free(mdctx);
EVP_PKEY_CTX_free(ctx);
return ret;
}
#ifndef OPENSSL_NO_DSA
static int test_DSA_get_set_params(void)
{
OSSL_PARAM_BLD *bld = NULL;
OSSL_PARAM *params = NULL;
BIGNUM *p = NULL, *q = NULL, *g = NULL, *pub = NULL, *priv = NULL;
EVP_PKEY_CTX *pctx = NULL;
EVP_PKEY *pkey = NULL;
int ret = 0;
/*
* Setup the parameters for our DSA object. For our purposes they don't
* have to actually be *valid* parameters. We just need to set something.
*/
if (!TEST_ptr(pctx = EVP_PKEY_CTX_new_from_name(testctx, "DSA", NULL))
|| !TEST_ptr(bld = OSSL_PARAM_BLD_new())
|| !TEST_ptr(p = BN_new())
|| !TEST_ptr(q = BN_new())
|| !TEST_ptr(g = BN_new())
|| !TEST_ptr(pub = BN_new())
|| !TEST_ptr(priv = BN_new()))
goto err;
if (!TEST_true(OSSL_PARAM_BLD_push_BN(bld, OSSL_PKEY_PARAM_FFC_P, p))
|| !TEST_true(OSSL_PARAM_BLD_push_BN(bld, OSSL_PKEY_PARAM_FFC_Q, q))
|| !TEST_true(OSSL_PARAM_BLD_push_BN(bld, OSSL_PKEY_PARAM_FFC_G, g))
|| !TEST_true(OSSL_PARAM_BLD_push_BN(bld, OSSL_PKEY_PARAM_PUB_KEY,
pub))
|| !TEST_true(OSSL_PARAM_BLD_push_BN(bld, OSSL_PKEY_PARAM_PRIV_KEY,
priv)))
goto err;
if (!TEST_ptr(params = OSSL_PARAM_BLD_to_param(bld)))
goto err;
if (!TEST_int_gt(EVP_PKEY_fromdata_init(pctx), 0)
|| !TEST_int_gt(EVP_PKEY_fromdata(pctx, &pkey, EVP_PKEY_KEYPAIR,
params), 0))
goto err;
if (!TEST_ptr(pkey))
goto err;
ret = test_EVP_PKEY_CTX_get_set_params(pkey);
err:
EVP_PKEY_free(pkey);
EVP_PKEY_CTX_free(pctx);
OSSL_PARAM_free(params);
OSSL_PARAM_BLD_free(bld);
BN_free(p);
BN_free(q);
BN_free(g);
BN_free(pub);
BN_free(priv);
return ret;
}
/*
* Test combinations of private, public, missing and private + public key
* params to ensure they are all accepted
*/
static int test_DSA_priv_pub(void)
{
return test_EVP_PKEY_ffc_priv_pub("DSA");
}
#endif /* !OPENSSL_NO_DSA */
static int test_RSA_get_set_params(void)
{
OSSL_PARAM_BLD *bld = NULL;
OSSL_PARAM *params = NULL;
BIGNUM *n = NULL, *e = NULL, *d = NULL;
EVP_PKEY_CTX *pctx = NULL;
EVP_PKEY *pkey = NULL;
int ret = 0;
/*
* Setup the parameters for our RSA object. For our purposes they don't
* have to actually be *valid* parameters. We just need to set something.
*/
if (!TEST_ptr(pctx = EVP_PKEY_CTX_new_from_name(testctx, "RSA", NULL))
|| !TEST_ptr(bld = OSSL_PARAM_BLD_new())
|| !TEST_ptr(n = BN_new())
|| !TEST_ptr(e = BN_new())
|| !TEST_ptr(d = BN_new()))
goto err;
if (!TEST_true(OSSL_PARAM_BLD_push_BN(bld, OSSL_PKEY_PARAM_RSA_N, n))
|| !TEST_true(OSSL_PARAM_BLD_push_BN(bld, OSSL_PKEY_PARAM_RSA_E, e))
|| !TEST_true(OSSL_PARAM_BLD_push_BN(bld, OSSL_PKEY_PARAM_RSA_D, d)))
goto err;
if (!TEST_ptr(params = OSSL_PARAM_BLD_to_param(bld)))
goto err;
if (!TEST_int_gt(EVP_PKEY_fromdata_init(pctx), 0)
|| !TEST_int_gt(EVP_PKEY_fromdata(pctx, &pkey, EVP_PKEY_KEYPAIR,
params), 0))
goto err;
if (!TEST_ptr(pkey))
goto err;
ret = test_EVP_PKEY_CTX_get_set_params(pkey);
err:
EVP_PKEY_free(pkey);
EVP_PKEY_CTX_free(pctx);
OSSL_PARAM_free(params);
OSSL_PARAM_BLD_free(bld);
BN_free(n);
BN_free(e);
BN_free(d);
return ret;
}
static int test_RSA_OAEP_set_get_params(void)
{
int ret = 0;
EVP_PKEY *key = NULL;
EVP_PKEY_CTX *key_ctx = NULL;
if (nullprov != NULL)
return TEST_skip("Test does not support a non-default library context");
if (!TEST_ptr(key = load_example_rsa_key())
|| !TEST_ptr(key_ctx = EVP_PKEY_CTX_new_from_pkey(0, key, 0)))
goto err;
{
int padding = RSA_PKCS1_OAEP_PADDING;
OSSL_PARAM params[4];
params[0] = OSSL_PARAM_construct_int(OSSL_SIGNATURE_PARAM_PAD_MODE, &padding);
params[1] = OSSL_PARAM_construct_utf8_string(OSSL_ASYM_CIPHER_PARAM_OAEP_DIGEST,
OSSL_DIGEST_NAME_SHA2_256, 0);
params[2] = OSSL_PARAM_construct_utf8_string(OSSL_ASYM_CIPHER_PARAM_MGF1_DIGEST,
OSSL_DIGEST_NAME_SHA1, 0);
params[3] = OSSL_PARAM_construct_end();
if (!TEST_int_gt(EVP_PKEY_encrypt_init_ex(key_ctx, params),0))
goto err;
}
{
OSSL_PARAM params[3];
char oaepmd[30] = { '\0' };
char mgf1md[30] = { '\0' };
params[0] = OSSL_PARAM_construct_utf8_string(OSSL_ASYM_CIPHER_PARAM_OAEP_DIGEST,
oaepmd, sizeof(oaepmd));
params[1] = OSSL_PARAM_construct_utf8_string(OSSL_ASYM_CIPHER_PARAM_MGF1_DIGEST,
mgf1md, sizeof(mgf1md));
params[2] = OSSL_PARAM_construct_end();
if (!TEST_true(EVP_PKEY_CTX_get_params(key_ctx, params)))
goto err;
if (!TEST_str_eq(oaepmd, OSSL_DIGEST_NAME_SHA2_256)
|| !TEST_str_eq(mgf1md, OSSL_DIGEST_NAME_SHA1))
goto err;
}
ret = 1;
err:
EVP_PKEY_free(key);
EVP_PKEY_CTX_free(key_ctx);
return ret;
}
/* https://github.com/openssl/openssl/issues/21288 */
static int test_RSA_OAEP_set_null_label(void)
{
int ret = 0;
EVP_PKEY *key = NULL;
EVP_PKEY_CTX *key_ctx = NULL;
if (!TEST_ptr(key = load_example_rsa_key())
|| !TEST_ptr(key_ctx = EVP_PKEY_CTX_new_from_pkey(testctx, key, NULL))
|| !TEST_true(EVP_PKEY_encrypt_init(key_ctx)))
goto err;
if (!TEST_true(EVP_PKEY_CTX_set_rsa_padding(key_ctx, RSA_PKCS1_OAEP_PADDING)))
goto err;
if (!TEST_true(EVP_PKEY_CTX_set0_rsa_oaep_label(key_ctx, OPENSSL_strdup("foo"), 0)))
goto err;
if (!TEST_true(EVP_PKEY_CTX_set0_rsa_oaep_label(key_ctx, NULL, 0)))
goto err;
ret = 1;
err:
EVP_PKEY_free(key);
EVP_PKEY_CTX_free(key_ctx);
return ret;
}
#if !defined(OPENSSL_NO_CHACHA) && !defined(OPENSSL_NO_POLY1305)
static int test_decrypt_null_chunks(void)
{
EVP_CIPHER_CTX* ctx = NULL;
EVP_CIPHER *cipher = NULL;
const unsigned char key[32] = {
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, 0x1
};
unsigned char iv[12] = {
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b
};
unsigned char msg[] = "It was the best of times, it was the worst of times";
unsigned char ciphertext[80];
unsigned char plaintext[80];
/* We initialise tmp to a non zero value on purpose */
int ctlen, ptlen, tmp = 99;
int ret = 0;
const int enc_offset = 10, dec_offset = 20;
if (!TEST_ptr(cipher = EVP_CIPHER_fetch(testctx, "ChaCha20-Poly1305", testpropq))
|| !TEST_ptr(ctx = EVP_CIPHER_CTX_new())
|| !TEST_true(EVP_EncryptInit_ex(ctx, cipher, NULL,
key, iv))
|| !TEST_true(EVP_EncryptUpdate(ctx, ciphertext, &ctlen, msg,
enc_offset))
/* Deliberate add a zero length update */
|| !TEST_true(EVP_EncryptUpdate(ctx, ciphertext + ctlen, &tmp, NULL,
0))
|| !TEST_int_eq(tmp, 0)
|| !TEST_true(EVP_EncryptUpdate(ctx, ciphertext + ctlen, &tmp,
msg + enc_offset,
sizeof(msg) - enc_offset))
|| !TEST_int_eq(ctlen += tmp, sizeof(msg))
|| !TEST_true(EVP_EncryptFinal(ctx, ciphertext + ctlen, &tmp))
|| !TEST_int_eq(tmp, 0))
goto err;
/* Deliberately initialise tmp to a non zero value */
tmp = 99;
if (!TEST_true(EVP_DecryptInit_ex(ctx, cipher, NULL, key, iv))
|| !TEST_true(EVP_DecryptUpdate(ctx, plaintext, &ptlen, ciphertext,
dec_offset))
/*
* Deliberately add a zero length update. We also deliberately do
* this at a different offset than for encryption.
*/
|| !TEST_true(EVP_DecryptUpdate(ctx, plaintext + ptlen, &tmp, NULL,
0))
|| !TEST_int_eq(tmp, 0)
|| !TEST_true(EVP_DecryptUpdate(ctx, plaintext + ptlen, &tmp,
ciphertext + dec_offset,
ctlen - dec_offset))
|| !TEST_int_eq(ptlen += tmp, sizeof(msg))
|| !TEST_true(EVP_DecryptFinal(ctx, plaintext + ptlen, &tmp))
|| !TEST_int_eq(tmp, 0)
|| !TEST_mem_eq(msg, sizeof(msg), plaintext, ptlen))
goto err;
ret = 1;
err:
EVP_CIPHER_CTX_free(ctx);
EVP_CIPHER_free(cipher);
return ret;
}
#endif /* !defined(OPENSSL_NO_CHACHA) && !defined(OPENSSL_NO_POLY1305) */
#ifndef OPENSSL_NO_DH
/*
* Test combinations of private, public, missing and private + public key
* params to ensure they are all accepted
*/
static int test_DH_priv_pub(void)
{
return test_EVP_PKEY_ffc_priv_pub("DH");
}
# ifndef OPENSSL_NO_DEPRECATED_3_0
static int test_EVP_PKEY_set1_DH(void)
{
DH *x942dh = NULL, *noqdh = NULL;
EVP_PKEY *pkey1 = NULL, *pkey2 = NULL;
int ret = 0;
BIGNUM *p, *g = NULL;
BIGNUM *pubkey = NULL;
unsigned char pub[2048 / 8];
size_t len = 0;
if (!TEST_ptr(p = BN_new())
|| !TEST_ptr(g = BN_new())
|| !TEST_ptr(pubkey = BN_new())
|| !TEST_true(BN_set_word(p, 9999))
|| !TEST_true(BN_set_word(g, 2))
|| !TEST_true(BN_set_word(pubkey, 4321))
|| !TEST_ptr(noqdh = DH_new())
|| !TEST_true(DH_set0_pqg(noqdh, p, NULL, g))
|| !TEST_true(DH_set0_key(noqdh, pubkey, NULL))
|| !TEST_ptr(pubkey = BN_new())
|| !TEST_true(BN_set_word(pubkey, 4321)))
goto err;
p = g = NULL;
x942dh = DH_get_2048_256();
pkey1 = EVP_PKEY_new();
pkey2 = EVP_PKEY_new();
if (!TEST_ptr(x942dh)
|| !TEST_ptr(noqdh)
|| !TEST_ptr(pkey1)
|| !TEST_ptr(pkey2)
|| !TEST_true(DH_set0_key(x942dh, pubkey, NULL)))
goto err;
pubkey = NULL;
if (!TEST_true(EVP_PKEY_set1_DH(pkey1, x942dh))
|| !TEST_int_eq(EVP_PKEY_get_id(pkey1), EVP_PKEY_DHX))
goto err;
if (!TEST_true(EVP_PKEY_get_bn_param(pkey1, OSSL_PKEY_PARAM_PUB_KEY,
&pubkey))
|| !TEST_ptr(pubkey))
goto err;
if (!TEST_true(EVP_PKEY_set1_DH(pkey2, noqdh))
|| !TEST_int_eq(EVP_PKEY_get_id(pkey2), EVP_PKEY_DH))
goto err;
if (!TEST_true(EVP_PKEY_get_octet_string_param(pkey2,
OSSL_PKEY_PARAM_PUB_KEY,
pub, sizeof(pub), &len))
|| !TEST_size_t_ne(len, 0))
goto err;
ret = 1;
err:
BN_free(p);
BN_free(g);
BN_free(pubkey);
EVP_PKEY_free(pkey1);
EVP_PKEY_free(pkey2);
DH_free(x942dh);
DH_free(noqdh);
return ret;
}
# endif /* !OPENSSL_NO_DEPRECATED_3_0 */
#endif /* !OPENSSL_NO_DH */
/*
* We test what happens with an empty template. For the sake of this test,
* the template must be ignored, and we know that's the case for RSA keys
* (this might arguably be a misfeature, but that's what we currently do,
* even in provider code, since that's how the legacy RSA implementation
* does things)
*/
static int test_keygen_with_empty_template(int n)
{
EVP_PKEY_CTX *ctx = NULL;
EVP_PKEY *pkey = NULL;
EVP_PKEY *tkey = NULL;
int ret = 0;
if (nullprov != NULL)
return TEST_skip("Test does not support a non-default library context");
switch (n) {
case 0:
/* We do test with no template at all as well */
if (!TEST_ptr(ctx = EVP_PKEY_CTX_new_id(EVP_PKEY_RSA, NULL)))
goto err;
break;
case 1:
/* Here we create an empty RSA key that serves as our template */
if (!TEST_ptr(tkey = EVP_PKEY_new())
|| !TEST_true(EVP_PKEY_set_type(tkey, EVP_PKEY_RSA))
|| !TEST_ptr(ctx = EVP_PKEY_CTX_new(tkey, NULL)))
goto err;
break;
}
if (!TEST_int_gt(EVP_PKEY_keygen_init(ctx), 0)
|| !TEST_int_gt(EVP_PKEY_keygen(ctx, &pkey), 0))
goto err;
ret = 1;
err:
EVP_PKEY_CTX_free(ctx);
EVP_PKEY_free(pkey);
EVP_PKEY_free(tkey);
return ret;
}
/*
* Test that we fail if we attempt to use an algorithm that is not available
* in the current library context (unless we are using an algorithm that
* should be made available via legacy codepaths).
*
* 0: RSA
* 1: SM2
*/
static int test_pkey_ctx_fail_without_provider(int tst)
{
OSSL_LIB_CTX *tmpctx = OSSL_LIB_CTX_new();
OSSL_PROVIDER *tmpnullprov = NULL;
EVP_PKEY_CTX *pctx = NULL;
const char *keytype = NULL;
int expect_null = 0;
int ret = 0;
if (!TEST_ptr(tmpctx))
goto err;
tmpnullprov = OSSL_PROVIDER_load(tmpctx, "null");
if (!TEST_ptr(tmpnullprov))
goto err;
/*
* We check for certain algos in the null provider.
* If an algo is expected to have a provider keymgmt, contructing an
* EVP_PKEY_CTX is expected to fail (return NULL).
* Otherwise, if it's expected to have legacy support, contructing an
* EVP_PKEY_CTX is expected to succeed (return non-NULL).
*/
switch (tst) {
case 0:
keytype = "RSA";
expect_null = 1;
break;
case 1:
keytype = "SM2";
expect_null = 1;
#ifdef OPENSSL_NO_EC
TEST_info("EC disable, skipping SM2 check...");
goto end;
#endif
#ifdef OPENSSL_NO_SM2
TEST_info("SM2 disable, skipping SM2 check...");
goto end;
#endif
break;
default:
TEST_error("No test for case %d", tst);
goto err;
}
pctx = EVP_PKEY_CTX_new_from_name(tmpctx, keytype, "");
if (expect_null ? !TEST_ptr_null(pctx) : !TEST_ptr(pctx))
goto err;
#if defined(OPENSSL_NO_EC) || defined(OPENSSL_NO_SM2)
end:
#endif
ret = 1;
err:
EVP_PKEY_CTX_free(pctx);
OSSL_PROVIDER_unload(tmpnullprov);
OSSL_LIB_CTX_free(tmpctx);
return ret;
}
static int test_rand_agglomeration(void)
{
EVP_RAND *rand;
EVP_RAND_CTX *ctx;
OSSL_PARAM params[3], *p = params;
int res;
unsigned int step = 7;
static unsigned char seed[] = "It does not matter how slowly you go "
"as long as you do not stop.";
unsigned char out[sizeof(seed)];
if (!TEST_int_ne(sizeof(seed) % step, 0)
|| !TEST_ptr(rand = EVP_RAND_fetch(testctx, "TEST-RAND", testpropq)))
return 0;
ctx = EVP_RAND_CTX_new(rand, NULL);
EVP_RAND_free(rand);
if (!TEST_ptr(ctx))
return 0;
memset(out, 0, sizeof(out));
*p++ = OSSL_PARAM_construct_octet_string(OSSL_RAND_PARAM_TEST_ENTROPY,
seed, sizeof(seed));
*p++ = OSSL_PARAM_construct_uint(OSSL_RAND_PARAM_MAX_REQUEST, &step);
*p = OSSL_PARAM_construct_end();
res = TEST_true(EVP_RAND_CTX_set_params(ctx, params))
&& TEST_true(EVP_RAND_generate(ctx, out, sizeof(out), 0, 1, NULL, 0))
&& TEST_mem_eq(seed, sizeof(seed), out, sizeof(out));
EVP_RAND_CTX_free(ctx);
return res;
}
/*
* Test that we correctly return the original or "running" IV after
* an encryption operation.
* Run multiple times for some different relevant algorithms/modes.
*/
static int test_evp_iv_aes(int idx)
{
int ret = 0;
EVP_CIPHER_CTX *ctx = NULL;
unsigned char key[16] = {0x4c, 0x43, 0xdb, 0xdd, 0x42, 0x73, 0x47, 0xd1,
0xe5, 0x62, 0x7d, 0xcd, 0x4d, 0x76, 0x4d, 0x57};
unsigned char init_iv[EVP_MAX_IV_LENGTH] =
{0x57, 0x71, 0x7d, 0xad, 0xdb, 0x9b, 0x98, 0x82,
0x5a, 0x55, 0x91, 0x81, 0x42, 0xa8, 0x89, 0x34};
static const unsigned char msg[] = { 1, 2, 3, 4, 5, 6, 7, 8,
9, 10, 11, 12, 13, 14, 15, 16 };
unsigned char ciphertext[32], oiv[16], iv[16];
unsigned char *ref_iv;
unsigned char cbc_state[16] = {0x10, 0x2f, 0x05, 0xcc, 0xc2, 0x55, 0x72, 0xb9,
0x88, 0xe6, 0x4a, 0x17, 0x10, 0x74, 0x22, 0x5e};
unsigned char ofb_state[16] = {0x76, 0xe6, 0x66, 0x61, 0xd0, 0x8a, 0xe4, 0x64,
0xdd, 0x66, 0xbf, 0x00, 0xf0, 0xe3, 0x6f, 0xfd};
unsigned char cfb_state[16] = {0x77, 0xe4, 0x65, 0x65, 0xd5, 0x8c, 0xe3, 0x6c,
0xd4, 0x6c, 0xb4, 0x0c, 0xfd, 0xed, 0x60, 0xed};
unsigned char gcm_state[12] = {0x57, 0x71, 0x7d, 0xad, 0xdb, 0x9b,
0x98, 0x82, 0x5a, 0x55, 0x91, 0x81};
unsigned char ccm_state[7] = {0x57, 0x71, 0x7d, 0xad, 0xdb, 0x9b, 0x98};
#ifndef OPENSSL_NO_OCB
unsigned char ocb_state[12] = {0x57, 0x71, 0x7d, 0xad, 0xdb, 0x9b,
0x98, 0x82, 0x5a, 0x55, 0x91, 0x81};
#endif
int len = sizeof(ciphertext);
size_t ivlen, ref_len;
const EVP_CIPHER *type = NULL;
int iv_reset = 0;
if (nullprov != NULL && idx < 6)
return TEST_skip("Test does not support a non-default library context");
switch(idx) {
case 0:
type = EVP_aes_128_cbc();
/* FALLTHROUGH */
case 6:
type = (type != NULL) ? type :
EVP_CIPHER_fetch(testctx, "aes-128-cbc", testpropq);
ref_iv = cbc_state;
ref_len = sizeof(cbc_state);
iv_reset = 1;
break;
case 1:
type = EVP_aes_128_ofb();
/* FALLTHROUGH */
case 7:
type = (type != NULL) ? type :
EVP_CIPHER_fetch(testctx, "aes-128-ofb", testpropq);
ref_iv = ofb_state;
ref_len = sizeof(ofb_state);
iv_reset = 1;
break;
case 2:
type = EVP_aes_128_cfb();
/* FALLTHROUGH */
case 8:
type = (type != NULL) ? type :
EVP_CIPHER_fetch(testctx, "aes-128-cfb", testpropq);
ref_iv = cfb_state;
ref_len = sizeof(cfb_state);
iv_reset = 1;
break;
case 3:
type = EVP_aes_128_gcm();
/* FALLTHROUGH */
case 9:
type = (type != NULL) ? type :
EVP_CIPHER_fetch(testctx, "aes-128-gcm", testpropq);
ref_iv = gcm_state;
ref_len = sizeof(gcm_state);
break;
case 4:
type = EVP_aes_128_ccm();
/* FALLTHROUGH */
case 10:
type = (type != NULL) ? type :
EVP_CIPHER_fetch(testctx, "aes-128-ccm", testpropq);
ref_iv = ccm_state;
ref_len = sizeof(ccm_state);
break;
#ifdef OPENSSL_NO_OCB
case 5:
case 11:
return 1;
#else
case 5:
type = EVP_aes_128_ocb();
/* FALLTHROUGH */
case 11:
type = (type != NULL) ? type :
EVP_CIPHER_fetch(testctx, "aes-128-ocb", testpropq);
ref_iv = ocb_state;
ref_len = sizeof(ocb_state);
break;
#endif
default:
return 0;
}
if (!TEST_ptr(type)
|| !TEST_ptr((ctx = EVP_CIPHER_CTX_new()))
|| !TEST_true(EVP_EncryptInit_ex(ctx, type, NULL, key, init_iv))
|| !TEST_true(EVP_EncryptUpdate(ctx, ciphertext, &len, msg,
(int)sizeof(msg)))
|| !TEST_true(EVP_CIPHER_CTX_get_original_iv(ctx, oiv, sizeof(oiv)))
|| !TEST_true(EVP_CIPHER_CTX_get_updated_iv(ctx, iv, sizeof(iv)))
|| !TEST_true(EVP_EncryptFinal_ex(ctx, ciphertext, &len)))
goto err;
ivlen = EVP_CIPHER_CTX_get_iv_length(ctx);
if (!TEST_mem_eq(init_iv, ivlen, oiv, ivlen)
|| !TEST_mem_eq(ref_iv, ref_len, iv, ivlen))
goto err;
/* CBC, OFB, and CFB modes: the updated iv must be reset after reinit */
if (!TEST_true(EVP_EncryptInit_ex(ctx, NULL, NULL, NULL, NULL))
|| !TEST_true(EVP_CIPHER_CTX_get_updated_iv(ctx, iv, sizeof(iv))))
goto err;
if (iv_reset) {
if (!TEST_mem_eq(init_iv, ivlen, iv, ivlen))
goto err;
} else {
if (!TEST_mem_eq(ref_iv, ivlen, iv, ivlen))
goto err;
}
ret = 1;
err:
EVP_CIPHER_CTX_free(ctx);
if (idx >= 6)
EVP_CIPHER_free((EVP_CIPHER *)type);
return ret;
}
#ifndef OPENSSL_NO_DES
static int test_evp_iv_des(int idx)
{
int ret = 0;
EVP_CIPHER_CTX *ctx = NULL;
static const unsigned char key[24] = {
0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef,
0xf1, 0xe0, 0xd3, 0xc2, 0xb5, 0xa4, 0x97, 0x86,
0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54, 0x32, 0x10
};
static const unsigned char init_iv[8] = {
0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54, 0x32, 0x10
};
static const unsigned char msg[] = { 1, 2, 3, 4, 5, 6, 7, 8,
9, 10, 11, 12, 13, 14, 15, 16 };
unsigned char ciphertext[32], oiv[8], iv[8];
unsigned const char *ref_iv;
static const unsigned char cbc_state_des[8] = {
0x4f, 0xa3, 0x85, 0xcd, 0x8b, 0xf3, 0x06, 0x2a
};
static const unsigned char cbc_state_3des[8] = {
0x35, 0x27, 0x7d, 0x65, 0x6c, 0xfb, 0x50, 0xd9
};
static const unsigned char ofb_state_des[8] = {
0xa7, 0x0d, 0x1d, 0x45, 0xf9, 0x96, 0x3f, 0x2c
};
static const unsigned char ofb_state_3des[8] = {
0xab, 0x16, 0x24, 0xbb, 0x5b, 0xac, 0xed, 0x5e
};
static const unsigned char cfb_state_des[8] = {
0x91, 0xeb, 0x6d, 0x29, 0x4b, 0x08, 0xbd, 0x73
};
static const unsigned char cfb_state_3des[8] = {
0x34, 0xdd, 0xfb, 0x47, 0x33, 0x1c, 0x61, 0xf7
};
int len = sizeof(ciphertext);
size_t ivlen, ref_len;
EVP_CIPHER *type = NULL;
if (lgcyprov == NULL && idx < 3)
return TEST_skip("Test requires legacy provider to be loaded");
switch(idx) {
case 0:
type = EVP_CIPHER_fetch(testctx, "des-cbc", testpropq);
ref_iv = cbc_state_des;
ref_len = sizeof(cbc_state_des);
break;
case 1:
type = EVP_CIPHER_fetch(testctx, "des-ofb", testpropq);
ref_iv = ofb_state_des;
ref_len = sizeof(ofb_state_des);
break;
case 2:
type = EVP_CIPHER_fetch(testctx, "des-cfb", testpropq);
ref_iv = cfb_state_des;
ref_len = sizeof(cfb_state_des);
break;
case 3:
type = EVP_CIPHER_fetch(testctx, "des-ede3-cbc", testpropq);
ref_iv = cbc_state_3des;
ref_len = sizeof(cbc_state_3des);
break;
case 4:
type = EVP_CIPHER_fetch(testctx, "des-ede3-ofb", testpropq);
ref_iv = ofb_state_3des;
ref_len = sizeof(ofb_state_3des);
break;
case 5:
type = EVP_CIPHER_fetch(testctx, "des-ede3-cfb", testpropq);
ref_iv = cfb_state_3des;
ref_len = sizeof(cfb_state_3des);
break;
default:
return 0;
}
if (!TEST_ptr(type)
|| !TEST_ptr((ctx = EVP_CIPHER_CTX_new()))
|| !TEST_true(EVP_EncryptInit_ex(ctx, type, NULL, key, init_iv))
|| !TEST_true(EVP_EncryptUpdate(ctx, ciphertext, &len, msg,
(int)sizeof(msg)))
|| !TEST_true(EVP_CIPHER_CTX_get_original_iv(ctx, oiv, sizeof(oiv)))
|| !TEST_true(EVP_CIPHER_CTX_get_updated_iv(ctx, iv, sizeof(iv)))
|| !TEST_true(EVP_EncryptFinal_ex(ctx, ciphertext, &len)))
goto err;
ivlen = EVP_CIPHER_CTX_get_iv_length(ctx);
if (!TEST_mem_eq(init_iv, ivlen, oiv, ivlen)
|| !TEST_mem_eq(ref_iv, ref_len, iv, ivlen))
goto err;
if (!TEST_true(EVP_EncryptInit_ex(ctx, NULL, NULL, NULL, NULL))
|| !TEST_true(EVP_CIPHER_CTX_get_updated_iv(ctx, iv, sizeof(iv))))
goto err;
if (!TEST_mem_eq(init_iv, ivlen, iv, ivlen))
goto err;
ret = 1;
err:
EVP_CIPHER_CTX_free(ctx);
EVP_CIPHER_free(type);
return ret;
}
#endif
#ifndef OPENSSL_NO_BF
static int test_evp_bf_default_keylen(int idx)
{
int ret = 0;
static const char *algos[4] = {
"bf-ecb", "bf-cbc", "bf-cfb", "bf-ofb"
};
int ivlen[4] = { 0, 8, 8, 8 };
EVP_CIPHER *cipher = NULL;
if (lgcyprov == NULL)
return TEST_skip("Test requires legacy provider to be loaded");
if (!TEST_ptr(cipher = EVP_CIPHER_fetch(testctx, algos[idx], testpropq))
|| !TEST_int_eq(EVP_CIPHER_get_key_length(cipher), 16)
|| !TEST_int_eq(EVP_CIPHER_get_iv_length(cipher), ivlen[idx]))
goto err;
ret = 1;
err:
EVP_CIPHER_free(cipher);
return ret;
}
#endif
#ifndef OPENSSL_NO_EC
static int ecpub_nids[] = {
NID_brainpoolP256r1, NID_X9_62_prime256v1,
NID_secp384r1, NID_secp521r1,
# ifndef OPENSSL_NO_EC2M
NID_sect233k1, NID_sect233r1, NID_sect283r1,
NID_sect409k1, NID_sect409r1, NID_sect571k1, NID_sect571r1,
# endif
NID_brainpoolP384r1, NID_brainpoolP512r1
};
static int test_ecpub(int idx)
{
int ret = 0, len, savelen;
int nid;
unsigned char buf[1024];
unsigned char *p;
EVP_PKEY *pkey = NULL;
EVP_PKEY_CTX *ctx = NULL;
# ifndef OPENSSL_NO_DEPRECATED_3_0
const unsigned char *q;
EVP_PKEY *pkey2 = NULL;
EC_KEY *ec = NULL;
# endif
if (nullprov != NULL)
return TEST_skip("Test does not support a non-default library context");
nid = ecpub_nids[idx];
ctx = EVP_PKEY_CTX_new_id(EVP_PKEY_EC, NULL);
if (!TEST_ptr(ctx)
|| !TEST_int_gt(EVP_PKEY_keygen_init(ctx), 0)
|| !TEST_int_gt(EVP_PKEY_CTX_set_ec_paramgen_curve_nid(ctx, nid), 0)
|| !TEST_true(EVP_PKEY_keygen(ctx, &pkey)))
goto done;
len = i2d_PublicKey(pkey, NULL);
savelen = len;
if (!TEST_int_ge(len, 1)
|| !TEST_int_lt(len, 1024))
goto done;
p = buf;
len = i2d_PublicKey(pkey, &p);
if (!TEST_int_ge(len, 1)
|| !TEST_int_eq(len, savelen))
goto done;
# ifndef OPENSSL_NO_DEPRECATED_3_0
/* Now try to decode the just-created DER. */
q = buf;
if (!TEST_ptr((pkey2 = EVP_PKEY_new()))
|| !TEST_ptr((ec = EC_KEY_new_by_curve_name(nid)))
|| !TEST_true(EVP_PKEY_assign_EC_KEY(pkey2, ec)))
goto done;
/* EC_KEY ownership transferred */
ec = NULL;
if (!TEST_ptr(d2i_PublicKey(EVP_PKEY_EC, &pkey2, &q, savelen)))
goto done;
/* The keys should match. */
if (!TEST_int_eq(EVP_PKEY_eq(pkey, pkey2), 1))
goto done;
# endif
ret = 1;
done:
EVP_PKEY_CTX_free(ctx);
EVP_PKEY_free(pkey);
# ifndef OPENSSL_NO_DEPRECATED_3_0
EVP_PKEY_free(pkey2);
EC_KEY_free(ec);
# endif
return ret;
}
#endif
static int test_EVP_rsa_pss_with_keygen_bits(void)
{
int ret = 0;
EVP_PKEY_CTX *ctx = NULL;
EVP_PKEY *pkey = NULL;
EVP_MD *md;
md = EVP_MD_fetch(testctx, "sha256", testpropq);
ret = TEST_ptr(md)
&& TEST_ptr((ctx = EVP_PKEY_CTX_new_from_name(testctx, "RSA-PSS", testpropq)))
&& TEST_int_gt(EVP_PKEY_keygen_init(ctx), 0)
&& TEST_int_gt(EVP_PKEY_CTX_set_rsa_keygen_bits(ctx, 512), 0)
&& TEST_int_gt(EVP_PKEY_CTX_set_rsa_pss_keygen_md(ctx, md), 0)
&& TEST_true(EVP_PKEY_keygen(ctx, &pkey));
EVP_MD_free(md);
EVP_PKEY_free(pkey);
EVP_PKEY_CTX_free(ctx);
return ret;
}
static int test_EVP_rsa_pss_set_saltlen(void)
{
int ret = 0;
EVP_PKEY *pkey = NULL;
EVP_PKEY_CTX *pkey_ctx = NULL;
EVP_MD *sha256 = NULL;
EVP_MD_CTX *sha256_ctx = NULL;
int saltlen = 9999; /* buggy EVP_PKEY_CTX_get_rsa_pss_saltlen() didn't update this */
const int test_value = 32;
ret = TEST_ptr(pkey = load_example_rsa_key())
&& TEST_ptr(sha256 = EVP_MD_fetch(testctx, "sha256", NULL))
&& TEST_ptr(sha256_ctx = EVP_MD_CTX_new())
&& TEST_true(EVP_DigestSignInit(sha256_ctx, &pkey_ctx, sha256, NULL, pkey))
&& TEST_true(EVP_PKEY_CTX_set_rsa_padding(pkey_ctx, RSA_PKCS1_PSS_PADDING))
&& TEST_int_gt(EVP_PKEY_CTX_set_rsa_pss_saltlen(pkey_ctx, test_value), 0)
&& TEST_int_gt(EVP_PKEY_CTX_get_rsa_pss_saltlen(pkey_ctx, &saltlen), 0)
&& TEST_int_eq(saltlen, test_value);
EVP_MD_CTX_free(sha256_ctx);
EVP_PKEY_free(pkey);
EVP_MD_free(sha256);
return ret;
}
static int success = 1;
static void md_names(const char *name, void *vctx)
{
OSSL_LIB_CTX *ctx = (OSSL_LIB_CTX *)vctx;
/* Force a namemap update */
EVP_CIPHER *aes128 = EVP_CIPHER_fetch(ctx, "AES-128-CBC", NULL);
if (!TEST_ptr(aes128))
success = 0;
EVP_CIPHER_free(aes128);
}
/*
* Test that changing the namemap in a user callback works in a names_do_all
* function.
*/
static int test_names_do_all(void)
{
/* We use a custom libctx so that we know the state of the namemap */
OSSL_LIB_CTX *ctx = OSSL_LIB_CTX_new();
EVP_MD *sha256 = NULL;
int testresult = 0;
if (!TEST_ptr(ctx))
goto err;
sha256 = EVP_MD_fetch(ctx, "SHA2-256", NULL);
if (!TEST_ptr(sha256))
goto err;
/*
* We loop through all the names for a given digest. This should still work
* even if the namemap changes part way through.
*/
if (!TEST_true(EVP_MD_names_do_all(sha256, md_names, ctx)))
goto err;
if (!TEST_true(success))
goto err;
testresult = 1;
err:
EVP_MD_free(sha256);
OSSL_LIB_CTX_free(ctx);
return testresult;
}
typedef struct {
const char *cipher;
const unsigned char *key;
const unsigned char *iv;
const unsigned char *input;
const unsigned char *expected;
const unsigned char *tag;
size_t ivlen; /* 0 if we do not need to set a specific IV len */
size_t inlen;
size_t expectedlen;
size_t taglen;
int keyfirst;
int initenc;
int finalenc;
} EVP_INIT_TEST_st;
static const EVP_INIT_TEST_st evp_init_tests[] = {
{
"aes-128-cfb", kCFBDefaultKey, iCFBIV, cfbPlaintext,
cfbCiphertext, NULL, 0, sizeof(cfbPlaintext), sizeof(cfbCiphertext),
0, 1, 0, 1
},
{
"aes-256-gcm", kGCMDefaultKey, iGCMDefaultIV, gcmDefaultPlaintext,
gcmDefaultCiphertext, gcmDefaultTag, sizeof(iGCMDefaultIV),
sizeof(gcmDefaultPlaintext), sizeof(gcmDefaultCiphertext),
sizeof(gcmDefaultTag), 1, 0, 1
},
{
"aes-128-cfb", kCFBDefaultKey, iCFBIV, cfbPlaintext,
cfbCiphertext, NULL, 0, sizeof(cfbPlaintext), sizeof(cfbCiphertext),
0, 0, 0, 1
},
{
"aes-256-gcm", kGCMDefaultKey, iGCMDefaultIV, gcmDefaultPlaintext,
gcmDefaultCiphertext, gcmDefaultTag, sizeof(iGCMDefaultIV),
sizeof(gcmDefaultPlaintext), sizeof(gcmDefaultCiphertext),
sizeof(gcmDefaultTag), 0, 0, 1
},
{
"aes-128-cfb", kCFBDefaultKey, iCFBIV, cfbCiphertext,
cfbPlaintext, NULL, 0, sizeof(cfbCiphertext), sizeof(cfbPlaintext),
0, 1, 1, 0
},
{
"aes-256-gcm", kGCMDefaultKey, iGCMDefaultIV, gcmDefaultCiphertext,
gcmDefaultPlaintext, gcmDefaultTag, sizeof(iGCMDefaultIV),
sizeof(gcmDefaultCiphertext), sizeof(gcmDefaultPlaintext),
sizeof(gcmDefaultTag), 1, 1, 0
},
{
"aes-128-cfb", kCFBDefaultKey, iCFBIV, cfbCiphertext,
cfbPlaintext, NULL, 0, sizeof(cfbCiphertext), sizeof(cfbPlaintext),
0, 0, 1, 0
},
{
"aes-256-gcm", kGCMDefaultKey, iGCMDefaultIV, gcmDefaultCiphertext,
gcmDefaultPlaintext, gcmDefaultTag, sizeof(iGCMDefaultIV),
sizeof(gcmDefaultCiphertext), sizeof(gcmDefaultPlaintext),
sizeof(gcmDefaultTag), 0, 1, 0
}
};
/* use same key, iv and plaintext for cfb and ofb */
static const EVP_INIT_TEST_st evp_reinit_tests[] = {
{
"aes-128-cfb", kCFBDefaultKey, iCFBIV, cfbPlaintext_partial,
cfbCiphertext_partial, NULL, 0, sizeof(cfbPlaintext_partial),
sizeof(cfbCiphertext_partial), 0, 0, 1, 0
},
{
"aes-128-cfb", kCFBDefaultKey, iCFBIV, cfbCiphertext_partial,
cfbPlaintext_partial, NULL, 0, sizeof(cfbCiphertext_partial),
sizeof(cfbPlaintext_partial), 0, 0, 0, 0
},
{
"aes-128-ofb", kCFBDefaultKey, iCFBIV, cfbPlaintext_partial,
ofbCiphertext_partial, NULL, 0, sizeof(cfbPlaintext_partial),
sizeof(ofbCiphertext_partial), 0, 0, 1, 0
},
{
"aes-128-ofb", kCFBDefaultKey, iCFBIV, ofbCiphertext_partial,
cfbPlaintext_partial, NULL, 0, sizeof(ofbCiphertext_partial),
sizeof(cfbPlaintext_partial), 0, 0, 0, 0
},
};
static int evp_init_seq_set_iv(EVP_CIPHER_CTX *ctx, const EVP_INIT_TEST_st *t)
{
int res = 0;
if (t->ivlen != 0) {
if (!TEST_int_gt(EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, t->ivlen, NULL), 0))
goto err;
}
if (!TEST_true(EVP_CipherInit_ex(ctx, NULL, NULL, NULL, t->iv, -1)))
goto err;
res = 1;
err:
return res;
}
/*
* Test step-wise cipher initialization via EVP_CipherInit_ex where the
* arguments are given one at a time and a final adjustment to the enc
* parameter sets the correct operation.
*/
static int test_evp_init_seq(int idx)
{
int outlen1, outlen2;
int testresult = 0;
unsigned char outbuf[1024];
unsigned char tag[16];
const EVP_INIT_TEST_st *t = &evp_init_tests[idx];
EVP_CIPHER_CTX *ctx = NULL;
EVP_CIPHER *type = NULL;
size_t taglen = sizeof(tag);
char *errmsg = NULL;
ctx = EVP_CIPHER_CTX_new();
if (ctx == NULL) {
errmsg = "CTX_ALLOC";
goto err;
}
if (!TEST_ptr(type = EVP_CIPHER_fetch(testctx, t->cipher, testpropq))) {
errmsg = "CIPHER_FETCH";
goto err;
}
if (!TEST_true(EVP_CipherInit_ex(ctx, type, NULL, NULL, NULL, t->initenc))) {
errmsg = "EMPTY_ENC_INIT";
goto err;
}
if (!TEST_true(EVP_CIPHER_CTX_set_padding(ctx, 0))) {
errmsg = "PADDING";
goto err;
}
if (t->keyfirst && !TEST_true(EVP_CipherInit_ex(ctx, NULL, NULL, t->key, NULL, -1))) {
errmsg = "KEY_INIT (before iv)";
goto err;
}
if (!evp_init_seq_set_iv(ctx, t)) {
errmsg = "IV_INIT";
goto err;
}
if (t->keyfirst == 0 && !TEST_true(EVP_CipherInit_ex(ctx, NULL, NULL, t->key, NULL, -1))) {
errmsg = "KEY_INIT (after iv)";
goto err;
}
if (!TEST_true(EVP_CipherInit_ex(ctx, NULL, NULL, NULL, NULL, t->finalenc))) {
errmsg = "FINAL_ENC_INIT";
goto err;
}
if (!TEST_true(EVP_CipherUpdate(ctx, outbuf, &outlen1, t->input, t->inlen))) {
errmsg = "CIPHER_UPDATE";
goto err;
}
if (t->finalenc == 0 && t->tag != NULL) {
/* Set expected tag */
if (!TEST_int_gt(EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_TAG,
t->taglen, (void *)t->tag), 0)) {
errmsg = "SET_TAG";
goto err;
}
}
if (!TEST_true(EVP_CipherFinal_ex(ctx, outbuf + outlen1, &outlen2))) {
errmsg = "CIPHER_FINAL";
goto err;
}
if (!TEST_mem_eq(t->expected, t->expectedlen, outbuf, outlen1 + outlen2)) {
errmsg = "WRONG_RESULT";
goto err;
}
if (t->finalenc != 0 && t->tag != NULL) {
if (!TEST_int_gt(EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_GET_TAG, taglen, tag), 0)) {
errmsg = "GET_TAG";
goto err;
}
if (!TEST_mem_eq(t->tag, t->taglen, tag, taglen)) {
errmsg = "TAG_ERROR";
goto err;
}
}
testresult = 1;
err:
if (errmsg != NULL)
TEST_info("evp_init_test %d: %s", idx, errmsg);
EVP_CIPHER_CTX_free(ctx);
EVP_CIPHER_free(type);
return testresult;
}
/*
* Test re-initialization of cipher context without changing key or iv.
* The result of both iteration should be the same.
*/
static int test_evp_reinit_seq(int idx)
{
int outlen1, outlen2, outlen_final;
int testresult = 0;
unsigned char outbuf1[1024];
unsigned char outbuf2[1024];
const EVP_INIT_TEST_st *t = &evp_reinit_tests[idx];
EVP_CIPHER_CTX *ctx = NULL;
EVP_CIPHER *type = NULL;
if (!TEST_ptr(ctx = EVP_CIPHER_CTX_new())
|| !TEST_ptr(type = EVP_CIPHER_fetch(testctx, t->cipher, testpropq))
/* setup cipher context */
|| !TEST_true(EVP_CipherInit_ex2(ctx, type, t->key, t->iv, t->initenc, NULL))
/* first iteration */
|| !TEST_true(EVP_CipherUpdate(ctx, outbuf1, &outlen1, t->input, t->inlen))
|| !TEST_true(EVP_CipherFinal_ex(ctx, outbuf1, &outlen_final))
/* check test results iteration 1 */
|| !TEST_mem_eq(t->expected, t->expectedlen, outbuf1, outlen1 + outlen_final)
/* now re-init the context (same cipher, key and iv) */
|| !TEST_true(EVP_CipherInit_ex2(ctx, NULL, NULL, NULL, -1, NULL))
/* second iteration */
|| !TEST_true(EVP_CipherUpdate(ctx, outbuf2, &outlen2, t->input, t->inlen))
|| !TEST_true(EVP_CipherFinal_ex(ctx, outbuf2, &outlen_final))
/* check test results iteration 2 */
|| !TEST_mem_eq(t->expected, t->expectedlen, outbuf2, outlen2 + outlen_final))
goto err;
testresult = 1;
err:
EVP_CIPHER_CTX_free(ctx);
EVP_CIPHER_free(type);
return testresult;
}
typedef struct {
const unsigned char *input;
const unsigned char *expected;
size_t inlen;
size_t expectedlen;
int enc;
} EVP_RESET_TEST_st;
static const EVP_RESET_TEST_st evp_reset_tests[] = {
{
cfbPlaintext, cfbCiphertext,
sizeof(cfbPlaintext), sizeof(cfbCiphertext), 1
},
{
cfbCiphertext, cfbPlaintext,
sizeof(cfbCiphertext), sizeof(cfbPlaintext), 0
}
};
/*
* Test a reset of a cipher via EVP_CipherInit_ex after the cipher has already
* been used.
*/
static int test_evp_reset(int idx)
{
const EVP_RESET_TEST_st *t = &evp_reset_tests[idx];
int outlen1, outlen2;
int testresult = 0;
unsigned char outbuf[1024];
EVP_CIPHER_CTX *ctx = NULL;
EVP_CIPHER *type = NULL;
char *errmsg = NULL;
if (!TEST_ptr(ctx = EVP_CIPHER_CTX_new())) {
errmsg = "CTX_ALLOC";
goto err;
}
if (!TEST_ptr(type = EVP_CIPHER_fetch(testctx, "aes-128-cfb", testpropq))) {
errmsg = "CIPHER_FETCH";
goto err;
}
if (!TEST_true(EVP_CipherInit_ex(ctx, type, NULL, kCFBDefaultKey, iCFBIV, t->enc))) {
errmsg = "CIPHER_INIT";
goto err;
}
if (!TEST_true(EVP_CIPHER_CTX_set_padding(ctx, 0))) {
errmsg = "PADDING";
goto err;
}
if (!TEST_true(EVP_CipherUpdate(ctx, outbuf, &outlen1, t->input, t->inlen))) {
errmsg = "CIPHER_UPDATE";
goto err;
}
if (!TEST_true(EVP_CipherFinal_ex(ctx, outbuf + outlen1, &outlen2))) {
errmsg = "CIPHER_FINAL";
goto err;
}
if (!TEST_mem_eq(t->expected, t->expectedlen, outbuf, outlen1 + outlen2)) {
errmsg = "WRONG_RESULT";
goto err;
}
if (!TEST_true(EVP_CipherInit_ex(ctx, NULL, NULL, NULL, NULL, -1))) {
errmsg = "CIPHER_REINIT";
goto err;
}
if (!TEST_true(EVP_CipherUpdate(ctx, outbuf, &outlen1, t->input, t->inlen))) {
errmsg = "CIPHER_UPDATE (reinit)";
goto err;
}
if (!TEST_true(EVP_CipherFinal_ex(ctx, outbuf + outlen1, &outlen2))) {
errmsg = "CIPHER_FINAL (reinit)";
goto err;
}
if (!TEST_mem_eq(t->expected, t->expectedlen, outbuf, outlen1 + outlen2)) {
errmsg = "WRONG_RESULT (reinit)";
goto err;
}
testresult = 1;
err:
if (errmsg != NULL)
TEST_info("test_evp_reset %d: %s", idx, errmsg);
EVP_CIPHER_CTX_free(ctx);
EVP_CIPHER_free(type);
return testresult;
}
typedef struct {
const char *cipher;
int enc;
} EVP_UPDATED_IV_TEST_st;
static const EVP_UPDATED_IV_TEST_st evp_updated_iv_tests[] = {
{
"aes-128-cfb", 1
},
{
"aes-128-cfb", 0
},
{
"aes-128-cfb1", 1
},
{
"aes-128-cfb1", 0
},
{
"aes-128-cfb8", 1
},
{
"aes-128-cfb8", 0
},
{
"aes-128-ofb", 1
},
{
"aes-128-ofb", 0
},
{
"aes-128-ctr", 1
},
{
"aes-128-ctr", 0
},
{
"aes-128-cbc", 1
},
{
"aes-128-cbc", 0
}
};
/*
* Test that the IV in the context is updated during a crypto operation for CFB
* and OFB.
*/
static int test_evp_updated_iv(int idx)
{
const EVP_UPDATED_IV_TEST_st *t = &evp_updated_iv_tests[idx];
int outlen1, outlen2;
int testresult = 0;
unsigned char outbuf[1024];
EVP_CIPHER_CTX *ctx = NULL;
EVP_CIPHER *type = NULL;
unsigned char updated_iv[EVP_MAX_IV_LENGTH];
int iv_len;
char *errmsg = NULL;
if (!TEST_ptr(ctx = EVP_CIPHER_CTX_new())) {
errmsg = "CTX_ALLOC";
goto err;
}
if ((type = EVP_CIPHER_fetch(testctx, t->cipher, testpropq)) == NULL) {
TEST_info("cipher %s not supported, skipping", t->cipher);
goto ok;
}
if (!TEST_true(EVP_CipherInit_ex(ctx, type, NULL, kCFBDefaultKey, iCFBIV, t->enc))) {
errmsg = "CIPHER_INIT";
goto err;
}
if (!TEST_true(EVP_CIPHER_CTX_set_padding(ctx, 0))) {
errmsg = "PADDING";
goto err;
}
if (!TEST_true(EVP_CipherUpdate(ctx, outbuf, &outlen1, cfbPlaintext, sizeof(cfbPlaintext)))) {
errmsg = "CIPHER_UPDATE";
goto err;
}
if (!TEST_true(EVP_CIPHER_CTX_get_updated_iv(ctx, updated_iv, sizeof(updated_iv)))) {
errmsg = "CIPHER_CTX_GET_UPDATED_IV";
goto err;
}
if (!TEST_true(iv_len = EVP_CIPHER_CTX_get_iv_length(ctx))) {
errmsg = "CIPHER_CTX_GET_IV_LEN";
goto err;
}
if (!TEST_mem_ne(iCFBIV, sizeof(iCFBIV), updated_iv, iv_len)) {
errmsg = "IV_NOT_UPDATED";
goto err;
}
if (!TEST_true(EVP_CipherFinal_ex(ctx, outbuf + outlen1, &outlen2))) {
errmsg = "CIPHER_FINAL";
goto err;
}
ok:
testresult = 1;
err:
if (errmsg != NULL)
TEST_info("test_evp_updated_iv %d: %s", idx, errmsg);
EVP_CIPHER_CTX_free(ctx);
EVP_CIPHER_free(type);
return testresult;
}
typedef struct {
const unsigned char *iv1;
const unsigned char *iv2;
const unsigned char *expected1;
const unsigned char *expected2;
const unsigned char *tag1;
const unsigned char *tag2;
size_t ivlen1;
size_t ivlen2;
size_t expectedlen1;
size_t expectedlen2;
} TEST_GCM_IV_REINIT_st;
static const TEST_GCM_IV_REINIT_st gcm_reinit_tests[] = {
{
iGCMResetIV1, iGCMResetIV2, gcmResetCiphertext1, gcmResetCiphertext2,
gcmResetTag1, gcmResetTag2, sizeof(iGCMResetIV1), sizeof(iGCMResetIV2),
sizeof(gcmResetCiphertext1), sizeof(gcmResetCiphertext2)
},
{
iGCMResetIV2, iGCMResetIV1, gcmResetCiphertext2, gcmResetCiphertext1,
gcmResetTag2, gcmResetTag1, sizeof(iGCMResetIV2), sizeof(iGCMResetIV1),
sizeof(gcmResetCiphertext2), sizeof(gcmResetCiphertext1)
}
};
static int test_gcm_reinit(int idx)
{
int outlen1, outlen2, outlen3;
int testresult = 0;
unsigned char outbuf[1024];
unsigned char tag[16];
const TEST_GCM_IV_REINIT_st *t = &gcm_reinit_tests[idx];
EVP_CIPHER_CTX *ctx = NULL;
EVP_CIPHER *type = NULL;
size_t taglen = sizeof(tag);
char *errmsg = NULL;
if (!TEST_ptr(ctx = EVP_CIPHER_CTX_new())) {
errmsg = "CTX_ALLOC";
goto err;
}
if (!TEST_ptr(type = EVP_CIPHER_fetch(testctx, "aes-256-gcm", testpropq))) {
errmsg = "CIPHER_FETCH";
goto err;
}
if (!TEST_true(EVP_CipherInit_ex(ctx, type, NULL, NULL, NULL, 1))) {
errmsg = "ENC_INIT";
goto err;
}
if (!TEST_int_gt(EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, t->ivlen1, NULL), 0)) {
errmsg = "SET_IVLEN1";
goto err;
}
if (!TEST_true(EVP_CipherInit_ex(ctx, NULL, NULL, kGCMResetKey, t->iv1, 1))) {
errmsg = "SET_IV1";
goto err;
}
if (!TEST_true(EVP_CipherUpdate(ctx, NULL, &outlen3, gcmAAD, sizeof(gcmAAD)))) {
errmsg = "AAD1";
goto err;
}
EVP_CIPHER_CTX_set_padding(ctx, 0);
if (!TEST_true(EVP_CipherUpdate(ctx, outbuf, &outlen1, gcmResetPlaintext,
sizeof(gcmResetPlaintext)))) {
errmsg = "CIPHER_UPDATE1";
goto err;
}
if (!TEST_true(EVP_CipherFinal_ex(ctx, outbuf + outlen1, &outlen2))) {
errmsg = "CIPHER_FINAL1";
goto err;
}
if (!TEST_mem_eq(t->expected1, t->expectedlen1, outbuf, outlen1 + outlen2)) {
errmsg = "WRONG_RESULT1";
goto err;
}
if (!TEST_int_gt(EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_GET_TAG, taglen, tag), 0)) {
errmsg = "GET_TAG1";
goto err;
}
if (!TEST_mem_eq(t->tag1, taglen, tag, taglen)) {
errmsg = "TAG_ERROR1";
goto err;
}
/* Now reinit */
if (!TEST_int_gt(EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, t->ivlen2, NULL), 0)) {
errmsg = "SET_IVLEN2";
goto err;
}
if (!TEST_true(EVP_CipherInit_ex(ctx, NULL, NULL, NULL, t->iv2, -1))) {
errmsg = "SET_IV2";
goto err;
}
if (!TEST_true(EVP_CipherUpdate(ctx, NULL, &outlen3, gcmAAD, sizeof(gcmAAD)))) {
errmsg = "AAD2";
goto err;
}
if (!TEST_true(EVP_CipherUpdate(ctx, outbuf, &outlen1, gcmResetPlaintext,
sizeof(gcmResetPlaintext)))) {
errmsg = "CIPHER_UPDATE2";
goto err;
}
if (!TEST_true(EVP_CipherFinal_ex(ctx, outbuf + outlen1, &outlen2))) {
errmsg = "CIPHER_FINAL2";
goto err;
}
if (!TEST_mem_eq(t->expected2, t->expectedlen2, outbuf, outlen1 + outlen2)) {
errmsg = "WRONG_RESULT2";
goto err;
}
if (!TEST_int_gt(EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_GET_TAG, taglen, tag), 0)) {
errmsg = "GET_TAG2";
goto err;
}
if (!TEST_mem_eq(t->tag2, taglen, tag, taglen)) {
errmsg = "TAG_ERROR2";
goto err;
}
testresult = 1;
err:
if (errmsg != NULL)
TEST_info("evp_init_test %d: %s", idx, errmsg);
EVP_CIPHER_CTX_free(ctx);
EVP_CIPHER_free(type);
return testresult;
}
static const char *ivlen_change_ciphers[] = {
"AES-256-GCM",
#ifndef OPENSSL_NO_OCB
"AES-256-OCB",
#endif
"AES-256-CCM"
};
/* Negative test for ivlen change after iv being set */
static int test_ivlen_change(int idx)
{
int outlen;
int res = 0;
unsigned char outbuf[1024];
static const unsigned char iv[] = {
0x57, 0x71, 0x7d, 0xad, 0xdb, 0x9b, 0x98, 0x82,
0x5a, 0x55, 0x91, 0x81, 0x42, 0xa8, 0x89, 0x34
};
EVP_CIPHER_CTX *ctx = NULL;
EVP_CIPHER *ciph = NULL;
OSSL_PARAM params[] = { OSSL_PARAM_END, OSSL_PARAM_END };
size_t ivlen = 13; /* non-default IV length */
if (!TEST_ptr(ctx = EVP_CIPHER_CTX_new()))
goto err;
if (!TEST_ptr(ciph = EVP_CIPHER_fetch(testctx, ivlen_change_ciphers[idx],
testpropq)))
goto err;
if (!TEST_true(EVP_CipherInit_ex(ctx, ciph, NULL, kGCMDefaultKey, iv, 1)))
goto err;
if (!TEST_true(EVP_CipherUpdate(ctx, outbuf, &outlen, gcmDefaultPlaintext,
sizeof(gcmDefaultPlaintext))))
goto err;
params[0] = OSSL_PARAM_construct_size_t(OSSL_CIPHER_PARAM_AEAD_IVLEN,
&ivlen);
if (!TEST_true(EVP_CIPHER_CTX_set_params(ctx, params)))
goto err;
ERR_set_mark();
if (!TEST_false(EVP_CipherUpdate(ctx, outbuf, &outlen, gcmDefaultPlaintext,
sizeof(gcmDefaultPlaintext)))) {
ERR_clear_last_mark();
goto err;
}
ERR_pop_to_mark();
res = 1;
err:
EVP_CIPHER_CTX_free(ctx);
EVP_CIPHER_free(ciph);
return res;
}
static const char *keylen_change_ciphers[] = {
#ifndef OPENSSL_NO_BF
"BF-ECB",
#endif
#ifndef OPENSSL_NO_CAST
"CAST5-ECB",
#endif
#ifndef OPENSSL_NO_RC2
"RC2-ECB",
#endif
#ifndef OPENSSL_NO_RC4
"RC4",
#endif
#ifndef OPENSSL_NO_RC5
"RC5-ECB",
#endif
NULL
};
/* Negative test for keylen change after key was set */
static int test_keylen_change(int idx)
{
int outlen;
int res = 0;
unsigned char outbuf[1024];
static const unsigned char key[] = {
0x57, 0x71, 0x7d, 0xad, 0xdb, 0x9b, 0x98, 0x82,
0x5a, 0x55, 0x91, 0x81, 0x42, 0xa8, 0x89, 0x34
};
EVP_CIPHER_CTX *ctx = NULL;
EVP_CIPHER *ciph = NULL;
OSSL_PARAM params[] = { OSSL_PARAM_END, OSSL_PARAM_END };
size_t keylen = 12; /* non-default key length */
if (lgcyprov == NULL)
return TEST_skip("Test requires legacy provider to be loaded");
if (!TEST_ptr(ctx = EVP_CIPHER_CTX_new()))
goto err;
if (!TEST_ptr(ciph = EVP_CIPHER_fetch(testctx, keylen_change_ciphers[idx],
testpropq)))
goto err;
if (!TEST_true(EVP_CipherInit_ex(ctx, ciph, NULL, key, NULL, 1)))
goto err;
if (!TEST_true(EVP_CipherUpdate(ctx, outbuf, &outlen, gcmDefaultPlaintext,
sizeof(gcmDefaultPlaintext))))
goto err;
params[0] = OSSL_PARAM_construct_size_t(OSSL_CIPHER_PARAM_KEYLEN,
&keylen);
if (!TEST_true(EVP_CIPHER_CTX_set_params(ctx, params)))
goto err;
ERR_set_mark();
if (!TEST_false(EVP_CipherUpdate(ctx, outbuf, &outlen, gcmDefaultPlaintext,
sizeof(gcmDefaultPlaintext)))) {
ERR_clear_last_mark();
goto err;
}
ERR_pop_to_mark();
res = 1;
err:
EVP_CIPHER_CTX_free(ctx);
EVP_CIPHER_free(ciph);
return res;
}
#ifndef OPENSSL_NO_DEPRECATED_3_0
static EVP_PKEY_METHOD *custom_pmeth = NULL;
static const EVP_PKEY_METHOD *orig_pmeth = NULL;
# define EVP_PKEY_CTRL_MY_COMMAND 9999
static int custom_pmeth_init(EVP_PKEY_CTX *ctx)
{
int (*pinit)(EVP_PKEY_CTX *ctx);
EVP_PKEY_meth_get_init(orig_pmeth, &pinit);
return pinit(ctx);
}
static void custom_pmeth_cleanup(EVP_PKEY_CTX *ctx)
{
void (*pcleanup)(EVP_PKEY_CTX *ctx);
EVP_PKEY_meth_get_cleanup(orig_pmeth, &pcleanup);
pcleanup(ctx);
}
static int custom_pmeth_sign(EVP_PKEY_CTX *ctx, unsigned char *out,
size_t *outlen, const unsigned char *in,
size_t inlen)
{
int (*psign)(EVP_PKEY_CTX *ctx, unsigned char *sig, size_t *siglen,
const unsigned char *tbs, size_t tbslen);
EVP_PKEY_meth_get_sign(orig_pmeth, NULL, &psign);
return psign(ctx, out, outlen, in, inlen);
}
static int custom_pmeth_digestsign(EVP_MD_CTX *ctx, unsigned char *sig,
size_t *siglen, const unsigned char *tbs,
size_t tbslen)
{
int (*pdigestsign)(EVP_MD_CTX *ctx, unsigned char *sig, size_t *siglen,
const unsigned char *tbs, size_t tbslen);
EVP_PKEY_meth_get_digestsign(orig_pmeth, &pdigestsign);
return pdigestsign(ctx, sig, siglen, tbs, tbslen);
}
static int custom_pmeth_derive(EVP_PKEY_CTX *ctx, unsigned char *key,
size_t *keylen)
{
int (*pderive)(EVP_PKEY_CTX *ctx, unsigned char *key, size_t *keylen);
EVP_PKEY_meth_get_derive(orig_pmeth, NULL, &pderive);
return pderive(ctx, key, keylen);
}
static int custom_pmeth_copy(EVP_PKEY_CTX *dst, const EVP_PKEY_CTX *src)
{
int (*pcopy)(EVP_PKEY_CTX *dst, const EVP_PKEY_CTX *src);
EVP_PKEY_meth_get_copy(orig_pmeth, &pcopy);
return pcopy(dst, src);
}
static int ctrl_called;
static int custom_pmeth_ctrl(EVP_PKEY_CTX *ctx, int type, int p1, void *p2)
{
int (*pctrl)(EVP_PKEY_CTX *ctx, int type, int p1, void *p2);
EVP_PKEY_meth_get_ctrl(orig_pmeth, &pctrl, NULL);
if (type == EVP_PKEY_CTRL_MY_COMMAND) {
ctrl_called = 1;
return 1;
}
return pctrl(ctx, type, p1, p2);
}
static int test_custom_pmeth(int idx)
{
EVP_PKEY_CTX *pctx = NULL;
EVP_MD_CTX *ctx = NULL;
EVP_PKEY *pkey = NULL;
int id, orig_id, orig_flags;
int testresult = 0;
size_t reslen;
unsigned char *res = NULL;
unsigned char msg[] = { 'H', 'e', 'l', 'l', 'o' };
const EVP_MD *md = EVP_sha256();
int doderive = 0;
ctrl_called = 0;
/* We call deprecated APIs so this test doesn't support a custom libctx */
if (testctx != NULL)
return 1;
switch(idx) {
case 0:
case 6:
id = EVP_PKEY_RSA;
pkey = load_example_rsa_key();
break;
case 1:
case 7:
# ifndef OPENSSL_NO_DSA
id = EVP_PKEY_DSA;
pkey = load_example_dsa_key();
break;
# else
return 1;
# endif
case 2:
case 8:
# ifndef OPENSSL_NO_EC
id = EVP_PKEY_EC;
pkey = load_example_ec_key();
break;
# else
return 1;
# endif
case 3:
case 9:
# ifndef OPENSSL_NO_EC
id = EVP_PKEY_ED25519;
md = NULL;
pkey = load_example_ed25519_key();
break;
# else
return 1;
# endif
case 4:
case 10:
# ifndef OPENSSL_NO_DH
id = EVP_PKEY_DH;
doderive = 1;
pkey = load_example_dh_key();
break;
# else
return 1;
# endif
case 5:
case 11:
# ifndef OPENSSL_NO_EC
id = EVP_PKEY_X25519;
doderive = 1;
pkey = load_example_x25519_key();
break;
# else
return 1;
# endif
default:
TEST_error("Should not happen");
goto err;
}
if (!TEST_ptr(pkey))
goto err;
if (idx < 6) {
if (!TEST_true(evp_pkey_is_provided(pkey)))
goto err;
} else {
EVP_PKEY *tmp = pkey;
/* Convert to a legacy key */
pkey = EVP_PKEY_new();
if (!TEST_ptr(pkey)) {
pkey = tmp;
goto err;
}
if (!TEST_true(evp_pkey_copy_downgraded(&pkey, tmp))) {
EVP_PKEY_free(tmp);
goto err;
}
EVP_PKEY_free(tmp);
if (!TEST_true(evp_pkey_is_legacy(pkey)))
goto err;
}
if (!TEST_ptr(orig_pmeth = EVP_PKEY_meth_find(id))
|| !TEST_ptr(pkey))
goto err;
EVP_PKEY_meth_get0_info(&orig_id, &orig_flags, orig_pmeth);
if (!TEST_int_eq(orig_id, id)
|| !TEST_ptr(custom_pmeth = EVP_PKEY_meth_new(id, orig_flags)))
goto err;
if (id == EVP_PKEY_ED25519) {
EVP_PKEY_meth_set_digestsign(custom_pmeth, custom_pmeth_digestsign);
} if (id == EVP_PKEY_DH || id == EVP_PKEY_X25519) {
EVP_PKEY_meth_set_derive(custom_pmeth, NULL, custom_pmeth_derive);
} else {
EVP_PKEY_meth_set_sign(custom_pmeth, NULL, custom_pmeth_sign);
}
if (id != EVP_PKEY_ED25519 && id != EVP_PKEY_X25519) {
EVP_PKEY_meth_set_init(custom_pmeth, custom_pmeth_init);
EVP_PKEY_meth_set_cleanup(custom_pmeth, custom_pmeth_cleanup);
EVP_PKEY_meth_set_copy(custom_pmeth, custom_pmeth_copy);
}
EVP_PKEY_meth_set_ctrl(custom_pmeth, custom_pmeth_ctrl, NULL);
if (!TEST_true(EVP_PKEY_meth_add0(custom_pmeth)))
goto err;
if (doderive) {
pctx = EVP_PKEY_CTX_new(pkey, NULL);
if (!TEST_ptr(pctx)
|| !TEST_int_eq(EVP_PKEY_derive_init(pctx), 1)
|| !TEST_int_ge(EVP_PKEY_CTX_ctrl(pctx, -1, -1,
EVP_PKEY_CTRL_MY_COMMAND, 0, NULL),
1)
|| !TEST_int_eq(ctrl_called, 1)
|| !TEST_int_ge(EVP_PKEY_derive_set_peer(pctx, pkey), 1)
|| !TEST_int_ge(EVP_PKEY_derive(pctx, NULL, &reslen), 1)
|| !TEST_ptr(res = OPENSSL_malloc(reslen))
|| !TEST_int_ge(EVP_PKEY_derive(pctx, res, &reslen), 1))
goto err;
} else {
ctx = EVP_MD_CTX_new();
reslen = EVP_PKEY_size(pkey);
res = OPENSSL_malloc(reslen);
if (!TEST_ptr(ctx)
|| !TEST_ptr(res)
|| !TEST_true(EVP_DigestSignInit(ctx, &pctx, md, NULL, pkey))
|| !TEST_int_ge(EVP_PKEY_CTX_ctrl(pctx, -1, -1,
EVP_PKEY_CTRL_MY_COMMAND, 0, NULL),
1)
|| !TEST_int_eq(ctrl_called, 1))
goto err;
if (id == EVP_PKEY_ED25519) {
if (!TEST_true(EVP_DigestSign(ctx, res, &reslen, msg, sizeof(msg))))
goto err;
} else {
if (!TEST_true(EVP_DigestUpdate(ctx, msg, sizeof(msg)))
|| !TEST_true(EVP_DigestSignFinal(ctx, res, &reslen)))
goto err;
}
}
testresult = 1;
err:
OPENSSL_free(res);
EVP_MD_CTX_free(ctx);
if (doderive)
EVP_PKEY_CTX_free(pctx);
EVP_PKEY_free(pkey);
EVP_PKEY_meth_remove(custom_pmeth);
EVP_PKEY_meth_free(custom_pmeth);
custom_pmeth = NULL;
return testresult;
}
static int test_evp_md_cipher_meth(void)
{
EVP_MD *md = EVP_MD_meth_dup(EVP_sha256());
EVP_CIPHER *ciph = EVP_CIPHER_meth_dup(EVP_aes_128_cbc());
int testresult = 0;
if (!TEST_ptr(md) || !TEST_ptr(ciph))
goto err;
testresult = 1;
err:
EVP_MD_meth_free(md);
EVP_CIPHER_meth_free(ciph);
return testresult;
}
typedef struct {
int data;
} custom_dgst_ctx;
static int custom_md_init_called = 0;
static int custom_md_cleanup_called = 0;
static int custom_md_init(EVP_MD_CTX *ctx)
{
custom_dgst_ctx *p = EVP_MD_CTX_md_data(ctx);
if (p == NULL)
return 0;
custom_md_init_called++;
return 1;
}
static int custom_md_cleanup(EVP_MD_CTX *ctx)
{
custom_dgst_ctx *p = EVP_MD_CTX_md_data(ctx);
if (p == NULL)
/* Nothing to do */
return 1;
custom_md_cleanup_called++;
return 1;
}
static int test_custom_md_meth(void)
{
EVP_MD_CTX *mdctx = NULL;
EVP_MD *tmp = NULL;
char mess[] = "Test Message\n";
unsigned char md_value[EVP_MAX_MD_SIZE];
unsigned int md_len;
int testresult = 0;
int nid;
/*
* We are testing deprecated functions. We don't support a non-default
* library context in this test.
*/
if (testctx != NULL)
return TEST_skip("Non-default libctx");
custom_md_init_called = custom_md_cleanup_called = 0;
nid = OBJ_create("1.3.6.1.4.1.16604.998866.1", "custom-md", "custom-md");
if (!TEST_int_ne(nid, NID_undef))
goto err;
tmp = EVP_MD_meth_new(nid, NID_undef);
if (!TEST_ptr(tmp))
goto err;
if (!TEST_true(EVP_MD_meth_set_init(tmp, custom_md_init))
|| !TEST_true(EVP_MD_meth_set_cleanup(tmp, custom_md_cleanup))
|| !TEST_true(EVP_MD_meth_set_app_datasize(tmp,
sizeof(custom_dgst_ctx))))
goto err;
mdctx = EVP_MD_CTX_new();
if (!TEST_ptr(mdctx)
/*
* Initing our custom md and then initing another md should
* result in the init and cleanup functions of the custom md
* being called.
*/
|| !TEST_true(EVP_DigestInit_ex(mdctx, tmp, NULL))
|| !TEST_true(EVP_DigestInit_ex(mdctx, EVP_sha256(), NULL))
|| !TEST_true(EVP_DigestUpdate(mdctx, mess, strlen(mess)))
|| !TEST_true(EVP_DigestFinal_ex(mdctx, md_value, &md_len))
|| !TEST_int_eq(custom_md_init_called, 1)
|| !TEST_int_eq(custom_md_cleanup_called, 1))
goto err;
testresult = 1;
err:
EVP_MD_CTX_free(mdctx);
EVP_MD_meth_free(tmp);
return testresult;
}
typedef struct {
int data;
} custom_ciph_ctx;
static int custom_ciph_init_called = 0;
static int custom_ciph_cleanup_called = 0;
static int custom_ciph_init(EVP_CIPHER_CTX *ctx, const unsigned char *key,
const unsigned char *iv, int enc)
{
custom_ciph_ctx *p = EVP_CIPHER_CTX_get_cipher_data(ctx);
if (p == NULL)
return 0;
custom_ciph_init_called++;
return 1;
}
static int custom_ciph_cleanup(EVP_CIPHER_CTX *ctx)
{
custom_ciph_ctx *p = EVP_CIPHER_CTX_get_cipher_data(ctx);
if (p == NULL)
/* Nothing to do */
return 1;
custom_ciph_cleanup_called++;
return 1;
}
static int test_custom_ciph_meth(void)
{
EVP_CIPHER_CTX *ciphctx = NULL;
EVP_CIPHER *tmp = NULL;
int testresult = 0;
int nid;
/*
* We are testing deprecated functions. We don't support a non-default
* library context in this test.
*/
if (testctx != NULL)
return TEST_skip("Non-default libctx");
custom_ciph_init_called = custom_ciph_cleanup_called = 0;
nid = OBJ_create("1.3.6.1.4.1.16604.998866.2", "custom-ciph", "custom-ciph");
if (!TEST_int_ne(nid, NID_undef))
goto err;
tmp = EVP_CIPHER_meth_new(nid, 16, 16);
if (!TEST_ptr(tmp))
goto err;
if (!TEST_true(EVP_CIPHER_meth_set_init(tmp, custom_ciph_init))
|| !TEST_true(EVP_CIPHER_meth_set_flags(tmp, EVP_CIPH_ALWAYS_CALL_INIT))
|| !TEST_true(EVP_CIPHER_meth_set_cleanup(tmp, custom_ciph_cleanup))
|| !TEST_true(EVP_CIPHER_meth_set_impl_ctx_size(tmp,
sizeof(custom_ciph_ctx))))
goto err;
ciphctx = EVP_CIPHER_CTX_new();
if (!TEST_ptr(ciphctx)
/*
* Initing our custom cipher and then initing another cipher
* should result in the init and cleanup functions of the custom
* cipher being called.
*/
|| !TEST_true(EVP_CipherInit_ex(ciphctx, tmp, NULL, NULL, NULL, 1))
|| !TEST_true(EVP_CipherInit_ex(ciphctx, EVP_aes_128_cbc(), NULL,
NULL, NULL, 1))
|| !TEST_int_eq(custom_ciph_init_called, 1)
|| !TEST_int_eq(custom_ciph_cleanup_called, 1))
goto err;
testresult = 1;
err:
EVP_CIPHER_CTX_free(ciphctx);
EVP_CIPHER_meth_free(tmp);
return testresult;
}
# ifndef OPENSSL_NO_DYNAMIC_ENGINE
/* Test we can create a signature keys with an associated ENGINE */
static int test_signatures_with_engine(int tst)
{
ENGINE *e;
const char *engine_id = "dasync";
EVP_PKEY *pkey = NULL;
const unsigned char badcmackey[] = { 0x00, 0x01 };
const unsigned char cmackey[] = {
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b,
0x0c, 0x0d, 0x0e, 0x0f
};
const unsigned char ed25519key[] = {
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
};
const unsigned char msg[] = { 0x00, 0x01, 0x02, 0x03 };
int testresult = 0;
EVP_MD_CTX *ctx = NULL;
unsigned char *mac = NULL;
size_t maclen = 0;
int ret;
# ifdef OPENSSL_NO_CMAC
/* Skip CMAC tests in a no-cmac build */
if (tst <= 1)
return 1;
# endif
if (!TEST_ptr(e = ENGINE_by_id(engine_id)))
return 0;
if (!TEST_true(ENGINE_init(e))) {
ENGINE_free(e);
return 0;
}
switch (tst) {
case 0:
pkey = EVP_PKEY_new_CMAC_key(e, cmackey, sizeof(cmackey),
EVP_aes_128_cbc());
break;
case 1:
pkey = EVP_PKEY_new_CMAC_key(e, badcmackey, sizeof(badcmackey),
EVP_aes_128_cbc());
break;
case 2:
pkey = EVP_PKEY_new_raw_private_key(EVP_PKEY_ED25519, e, ed25519key,
sizeof(ed25519key));
break;
default:
TEST_error("Invalid test case");
goto err;
}
if (!TEST_ptr(pkey))
goto err;
if (!TEST_ptr(ctx = EVP_MD_CTX_new()))
goto err;
ret = EVP_DigestSignInit(ctx, NULL, tst == 2 ? NULL : EVP_sha256(), NULL,
pkey);
if (tst == 0) {
if (!TEST_true(ret))
goto err;
if (!TEST_true(EVP_DigestSignUpdate(ctx, msg, sizeof(msg)))
|| !TEST_true(EVP_DigestSignFinal(ctx, NULL, &maclen)))
goto err;
if (!TEST_ptr(mac = OPENSSL_malloc(maclen)))
goto err;
if (!TEST_true(EVP_DigestSignFinal(ctx, mac, &maclen)))
goto err;
} else {
/* We used a bad key. We expect a failure here */
if (!TEST_false(ret))
goto err;
}
testresult = 1;
err:
EVP_MD_CTX_free(ctx);
OPENSSL_free(mac);
EVP_PKEY_free(pkey);
ENGINE_finish(e);
ENGINE_free(e);
return testresult;
}
static int test_cipher_with_engine(void)
{
ENGINE *e;
const char *engine_id = "dasync";
const unsigned char keyiv[] = {
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b,
0x0c, 0x0d, 0x0e, 0x0f
};
const unsigned char msg[] = { 0x00, 0x01, 0x02, 0x03 };
int testresult = 0;
EVP_CIPHER_CTX *ctx = NULL, *ctx2 = NULL;
unsigned char buf[AES_BLOCK_SIZE];
int len = 0;
if (!TEST_ptr(e = ENGINE_by_id(engine_id)))
return 0;
if (!TEST_true(ENGINE_init(e))) {
ENGINE_free(e);
return 0;
}
if (!TEST_ptr(ctx = EVP_CIPHER_CTX_new())
|| !TEST_ptr(ctx2 = EVP_CIPHER_CTX_new()))
goto err;
if (!TEST_true(EVP_EncryptInit_ex(ctx, EVP_aes_128_cbc(), e, keyiv, keyiv)))
goto err;
/* Copy the ctx, and complete the operation with the new ctx */
if (!TEST_true(EVP_CIPHER_CTX_copy(ctx2, ctx)))
goto err;
if (!TEST_true(EVP_EncryptUpdate(ctx2, buf, &len, msg, sizeof(msg)))
|| !TEST_true(EVP_EncryptFinal_ex(ctx2, buf + len, &len)))
goto err;
testresult = 1;
err:
EVP_CIPHER_CTX_free(ctx);
EVP_CIPHER_CTX_free(ctx2);
ENGINE_finish(e);
ENGINE_free(e);
return testresult;
}
# endif /* OPENSSL_NO_DYNAMIC_ENGINE */
#endif /* OPENSSL_NO_DEPRECATED_3_0 */
static int ecxnids[] = {
NID_X25519,
NID_X448,
NID_ED25519,
NID_ED448
};
/* Test that creating ECX keys with a short private key fails as expected */
static int test_ecx_short_keys(int tst)
{
unsigned char ecxkeydata = 1;
EVP_PKEY *pkey;
pkey = EVP_PKEY_new_raw_private_key_ex(testctx, OBJ_nid2sn(ecxnids[tst]),
NULL, &ecxkeydata, 1);
if (!TEST_ptr_null(pkey)) {
EVP_PKEY_free(pkey);
return 0;
}
return 1;
}
typedef enum OPTION_choice {
OPT_ERR = -1,
OPT_EOF = 0,
OPT_CONTEXT,
OPT_TEST_ENUM
} OPTION_CHOICE;
const OPTIONS *test_get_options(void)
{
static const OPTIONS options[] = {
OPT_TEST_OPTIONS_DEFAULT_USAGE,
{ "context", OPT_CONTEXT, '-', "Explicitly use a non-default library context" },
{ NULL }
};
return options;
}
#ifndef OPENSSL_NO_EC
/* Test that trying to sign with a public key errors out gracefully */
static int test_ecx_not_private_key(int tst)
{
EVP_PKEY *pkey = NULL;
const unsigned char msg[] = { 0x00, 0x01, 0x02, 0x03 };
int testresult = 0;
EVP_MD_CTX *ctx = NULL;
unsigned char *mac = NULL;
size_t maclen = 0;
unsigned char *pubkey;
size_t pubkeylen;
switch (keys[tst].type) {
case NID_X25519:
case NID_X448:
return TEST_skip("signing not supported for X25519/X448");
}
/* Check if this algorithm supports public keys */
if (keys[tst].pub == NULL)
return TEST_skip("no public key present");
pubkey = (unsigned char *)keys[tst].pub;
pubkeylen = strlen(keys[tst].pub);
pkey = EVP_PKEY_new_raw_public_key_ex(testctx, OBJ_nid2sn(keys[tst].type),
NULL, pubkey, pubkeylen);
if (!TEST_ptr(pkey))
goto err;
if (!TEST_ptr(ctx = EVP_MD_CTX_new()))
goto err;
if (EVP_DigestSignInit(ctx, NULL, NULL, NULL, pkey) != 1)
goto check_err;
if (EVP_DigestSign(ctx, NULL, &maclen, msg, sizeof(msg)) != 1)
goto check_err;
if (!TEST_ptr(mac = OPENSSL_malloc(maclen)))
goto err;
if (!TEST_int_eq(EVP_DigestSign(ctx, mac, &maclen, msg, sizeof(msg)), 0))
goto err;
check_err:
/*
* Currently only EVP_DigestSign will throw PROV_R_NOT_A_PRIVATE_KEY,
* but we relax the check to allow error also thrown by
* EVP_DigestSignInit and EVP_DigestSign.
*/
if (ERR_GET_REASON(ERR_peek_error()) == PROV_R_NOT_A_PRIVATE_KEY) {
testresult = 1;
ERR_clear_error();
}
err:
EVP_MD_CTX_free(ctx);
OPENSSL_free(mac);
EVP_PKEY_free(pkey);
return testresult;
}
#endif /* OPENSSL_NO_EC */
static int aes_gcm_encrypt(const unsigned char *gcm_key, size_t gcm_key_s,
const unsigned char *gcm_iv, size_t gcm_ivlen,
const unsigned char *gcm_pt, size_t gcm_pt_s,
const unsigned char *gcm_aad, size_t gcm_aad_s,
const unsigned char *gcm_ct, size_t gcm_ct_s,
const unsigned char *gcm_tag, size_t gcm_tag_s)
{
int ret = 0;
EVP_CIPHER_CTX *ctx;
EVP_CIPHER *cipher = NULL;
int outlen, tmplen;
unsigned char outbuf[1024];
unsigned char outtag[16];
OSSL_PARAM params[2] = {
OSSL_PARAM_END, OSSL_PARAM_END
};
if (!TEST_ptr(ctx = EVP_CIPHER_CTX_new())
|| !TEST_ptr(cipher = EVP_CIPHER_fetch(testctx, "AES-256-GCM", "")))
goto err;
params[0] = OSSL_PARAM_construct_size_t(OSSL_CIPHER_PARAM_AEAD_IVLEN,
&gcm_ivlen);
if (!TEST_true(EVP_EncryptInit_ex2(ctx, cipher, gcm_key, gcm_iv, params))
|| (gcm_aad != NULL
&& !TEST_true(EVP_EncryptUpdate(ctx, NULL, &outlen,
gcm_aad, gcm_aad_s)))
|| !TEST_true(EVP_EncryptUpdate(ctx, outbuf, &outlen,
gcm_pt, gcm_pt_s))
|| !TEST_true(EVP_EncryptFinal_ex(ctx, outbuf, &tmplen)))
goto err;
params[0] = OSSL_PARAM_construct_octet_string(OSSL_CIPHER_PARAM_AEAD_TAG,
outtag, sizeof(outtag));
if (!TEST_true(EVP_CIPHER_CTX_get_params(ctx, params))
|| !TEST_mem_eq(outbuf, outlen, gcm_ct, gcm_ct_s)
|| !TEST_mem_eq(outtag, gcm_tag_s, gcm_tag, gcm_tag_s))
goto err;
ret = 1;
err:
EVP_CIPHER_free(cipher);
EVP_CIPHER_CTX_free(ctx);
return ret;
}
static int aes_gcm_decrypt(const unsigned char *gcm_key, size_t gcm_key_s,
const unsigned char *gcm_iv, size_t gcm_ivlen,
const unsigned char *gcm_pt, size_t gcm_pt_s,
const unsigned char *gcm_aad, size_t gcm_aad_s,
const unsigned char *gcm_ct, size_t gcm_ct_s,
const unsigned char *gcm_tag, size_t gcm_tag_s)
{
int ret = 0;
EVP_CIPHER_CTX *ctx;
EVP_CIPHER *cipher = NULL;
int outlen;
unsigned char outbuf[1024];
OSSL_PARAM params[2] = {
OSSL_PARAM_END, OSSL_PARAM_END
};
if ((ctx = EVP_CIPHER_CTX_new()) == NULL)
goto err;
if ((cipher = EVP_CIPHER_fetch(testctx, "AES-256-GCM", "")) == NULL)
goto err;
params[0] = OSSL_PARAM_construct_size_t(OSSL_CIPHER_PARAM_AEAD_IVLEN,
&gcm_ivlen);
if (!TEST_true(EVP_DecryptInit_ex2(ctx, cipher, gcm_key, gcm_iv, params))
|| (gcm_aad != NULL
&& !TEST_true(EVP_DecryptUpdate(ctx, NULL, &outlen,
gcm_aad, gcm_aad_s)))
|| !TEST_true(EVP_DecryptUpdate(ctx, outbuf, &outlen,
gcm_ct, gcm_ct_s))
|| !TEST_mem_eq(outbuf, outlen, gcm_pt, gcm_pt_s))
goto err;
params[0] = OSSL_PARAM_construct_octet_string(OSSL_CIPHER_PARAM_AEAD_TAG,
(void*)gcm_tag, gcm_tag_s);
if (!TEST_true(EVP_CIPHER_CTX_set_params(ctx, params))
||!TEST_true(EVP_DecryptFinal_ex(ctx, outbuf, &outlen)))
goto err;
ret = 1;
err:
EVP_CIPHER_free(cipher);
EVP_CIPHER_CTX_free(ctx);
return ret;
}
static int test_aes_gcm_ivlen_change_cve_2023_5363(void)
{
/* AES-GCM test data obtained from NIST public test vectors */
static const unsigned char gcm_key[] = {
0xd0, 0xc2, 0x67, 0xc1, 0x9f, 0x30, 0xd8, 0x0b, 0x89, 0x14, 0xbb, 0xbf,
0xb7, 0x2f, 0x73, 0xb8, 0xd3, 0xcd, 0x5f, 0x6a, 0x78, 0x70, 0x15, 0x84,
0x8a, 0x7b, 0x30, 0xe3, 0x8f, 0x16, 0xf1, 0x8b,
};
static const unsigned char gcm_iv[] = {
0xb6, 0xdc, 0xda, 0x95, 0xac, 0x99, 0x77, 0x76, 0x25, 0xae, 0x87, 0xf8,
0xa3, 0xa9, 0xdd, 0x64, 0xd7, 0x9b, 0xbd, 0x5f, 0x4a, 0x0e, 0x54, 0xca,
0x1a, 0x9f, 0xa2, 0xe3, 0xf4, 0x5f, 0x5f, 0xc2, 0xce, 0xa7, 0xb6, 0x14,
0x12, 0x6f, 0xf0, 0xaf, 0xfd, 0x3e, 0x17, 0x35, 0x6e, 0xa0, 0x16, 0x09,
0xdd, 0xa1, 0x3f, 0xd8, 0xdd, 0xf3, 0xdf, 0x4f, 0xcb, 0x18, 0x49, 0xb8,
0xb3, 0x69, 0x2c, 0x5d, 0x4f, 0xad, 0x30, 0x91, 0x08, 0xbc, 0xbe, 0x24,
0x01, 0x0f, 0xbe, 0x9c, 0xfb, 0x4f, 0x5d, 0x19, 0x7f, 0x4c, 0x53, 0xb0,
0x95, 0x90, 0xac, 0x7b, 0x1f, 0x7b, 0xa0, 0x99, 0xe1, 0xf3, 0x48, 0x54,
0xd0, 0xfc, 0xa9, 0xcc, 0x91, 0xf8, 0x1f, 0x9b, 0x6c, 0x9a, 0xe0, 0xdc,
0x63, 0xea, 0x7d, 0x2a, 0x4a, 0x7d, 0xa5, 0xed, 0x68, 0x57, 0x27, 0x6b,
0x68, 0xe0, 0xf2, 0xb8, 0x51, 0x50, 0x8d, 0x3d,
};
static const unsigned char gcm_pt[] = {
0xb8, 0xb6, 0x88, 0x36, 0x44, 0xe2, 0x34, 0xdf, 0x24, 0x32, 0x91, 0x07,
0x4f, 0xe3, 0x6f, 0x81,
};
static const unsigned char gcm_ct[] = {
0xff, 0x4f, 0xb3, 0xf3, 0xf9, 0xa2, 0x51, 0xd4, 0x82, 0xc2, 0xbe, 0xf3,
0xe2, 0xd0, 0xec, 0xed,
};
static const unsigned char gcm_tag[] = {
0xbd, 0x06, 0x38, 0x09, 0xf7, 0xe1, 0xc4, 0x72, 0x0e, 0xf2, 0xea, 0x63,
0xdb, 0x99, 0x6c, 0x21,
};
return aes_gcm_encrypt(gcm_key, sizeof(gcm_key), gcm_iv, sizeof(gcm_iv),
gcm_pt, sizeof(gcm_pt), NULL, 0,
gcm_ct, sizeof(gcm_ct), gcm_tag, sizeof(gcm_tag))
&& aes_gcm_decrypt(gcm_key, sizeof(gcm_key), gcm_iv, sizeof(gcm_iv),
gcm_pt, sizeof(gcm_pt), NULL, 0,
gcm_ct, sizeof(gcm_ct), gcm_tag, sizeof(gcm_tag));
}
#ifndef OPENSSL_NO_RC4
static int rc4_encrypt(const unsigned char *rc4_key, size_t rc4_key_s,
const unsigned char *rc4_pt, size_t rc4_pt_s,
const unsigned char *rc4_ct, size_t rc4_ct_s)
{
int ret = 0;
EVP_CIPHER_CTX *ctx;
EVP_CIPHER *cipher = NULL;
int outlen, tmplen;
unsigned char outbuf[1024];
OSSL_PARAM params[2] = {
OSSL_PARAM_END, OSSL_PARAM_END
};
if (!TEST_ptr(ctx = EVP_CIPHER_CTX_new())
|| !TEST_ptr(cipher = EVP_CIPHER_fetch(testctx, "RC4", "")))
goto err;
params[0] = OSSL_PARAM_construct_size_t(OSSL_CIPHER_PARAM_KEYLEN,
&rc4_key_s);
if (!TEST_true(EVP_EncryptInit_ex2(ctx, cipher, rc4_key, NULL, params))
|| !TEST_true(EVP_EncryptUpdate(ctx, outbuf, &outlen,
rc4_pt, rc4_pt_s))
|| !TEST_true(EVP_EncryptFinal_ex(ctx, outbuf, &tmplen)))
goto err;
if (!TEST_mem_eq(outbuf, outlen, rc4_ct, rc4_ct_s))
goto err;
ret = 1;
err:
EVP_CIPHER_free(cipher);
EVP_CIPHER_CTX_free(ctx);
return ret;
}
static int rc4_decrypt(const unsigned char *rc4_key, size_t rc4_key_s,
const unsigned char *rc4_pt, size_t rc4_pt_s,
const unsigned char *rc4_ct, size_t rc4_ct_s)
{
int ret = 0;
EVP_CIPHER_CTX *ctx;
EVP_CIPHER *cipher = NULL;
int outlen;
unsigned char outbuf[1024];
OSSL_PARAM params[2] = {
OSSL_PARAM_END, OSSL_PARAM_END
};
if ((ctx = EVP_CIPHER_CTX_new()) == NULL)
goto err;
if ((cipher = EVP_CIPHER_fetch(testctx, "RC4", "")) == NULL)
goto err;
params[0] = OSSL_PARAM_construct_size_t(OSSL_CIPHER_PARAM_KEYLEN,
&rc4_key_s);
if (!TEST_true(EVP_DecryptInit_ex2(ctx, cipher, rc4_key, NULL, params))
|| !TEST_true(EVP_DecryptUpdate(ctx, outbuf, &outlen,
rc4_ct, rc4_ct_s))
|| !TEST_mem_eq(outbuf, outlen, rc4_pt, rc4_pt_s))
goto err;
ret = 1;
err:
EVP_CIPHER_free(cipher);
EVP_CIPHER_CTX_free(ctx);
return ret;
}
static int test_aes_rc4_keylen_change_cve_2023_5363(void)
{
/* RC4 test data obtained from RFC 6229 */
static const struct {
unsigned char key[5];
unsigned char padding[11];
} rc4_key = {
{ /* Five bytes of key material */
0x83, 0x32, 0x22, 0x77, 0x2a,
},
{ /* Random padding to 16 bytes */
0x80, 0xad, 0x97, 0xbd, 0xc9, 0x73, 0xdf, 0x8a, 0xaa, 0x32, 0x91
}
};
static const unsigned char rc4_pt[] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};
static const unsigned char rc4_ct[] = {
0x80, 0xad, 0x97, 0xbd, 0xc9, 0x73, 0xdf, 0x8a,
0x2e, 0x87, 0x9e, 0x92, 0xa4, 0x97, 0xef, 0xda
};
if (lgcyprov == NULL)
return TEST_skip("Test requires legacy provider to be loaded");
return rc4_encrypt(rc4_key.key, sizeof(rc4_key.key),
rc4_pt, sizeof(rc4_pt), rc4_ct, sizeof(rc4_ct))
&& rc4_decrypt(rc4_key.key, sizeof(rc4_key.key),
rc4_pt, sizeof(rc4_pt), rc4_ct, sizeof(rc4_ct));
}
#endif
int setup_tests(void)
{
OPTION_CHOICE o;
while ((o = opt_next()) != OPT_EOF) {
switch (o) {
case OPT_CONTEXT:
/* Set up an alternate library context */
testctx = OSSL_LIB_CTX_new();
if (!TEST_ptr(testctx))
return 0;
#ifdef STATIC_LEGACY
/*
* This test is always statically linked against libcrypto. We must not
* attempt to load legacy.so that might be dynamically linked against
* libcrypto. Instead we use a built-in version of the legacy provider.
*/
if (!OSSL_PROVIDER_add_builtin(testctx, "legacy", ossl_legacy_provider_init))
return 0;
#endif
/* Swap the libctx to test non-default context only */
nullprov = OSSL_PROVIDER_load(NULL, "null");
deflprov = OSSL_PROVIDER_load(testctx, "default");
lgcyprov = OSSL_PROVIDER_load(testctx, "legacy");
break;
case OPT_TEST_CASES:
break;
default:
return 0;
}
}
ADD_TEST(test_EVP_set_default_properties);
ADD_ALL_TESTS(test_EVP_DigestSignInit, 30);
ADD_TEST(test_EVP_DigestVerifyInit);
#ifndef OPENSSL_NO_SIPHASH
ADD_TEST(test_siphash_digestsign);
#endif
ADD_TEST(test_EVP_Digest);
ADD_TEST(test_EVP_md_null);
ADD_ALL_TESTS(test_EVP_PKEY_sign, 3);
#ifndef OPENSSL_NO_DEPRECATED_3_0
ADD_ALL_TESTS(test_EVP_PKEY_sign_with_app_method, 2);
#endif
ADD_ALL_TESTS(test_EVP_Enveloped, 2);
ADD_ALL_TESTS(test_d2i_AutoPrivateKey, OSSL_NELEM(keydata));
ADD_TEST(test_privatekey_to_pkcs8);
ADD_TEST(test_EVP_PKCS82PKEY_wrong_tag);
#ifndef OPENSSL_NO_EC
ADD_TEST(test_EVP_PKCS82PKEY);
#endif
#ifndef OPENSSL_NO_EC
ADD_ALL_TESTS(test_EC_keygen_with_enc, OSSL_NELEM(ec_encodings));
#endif
#if !defined(OPENSSL_NO_SM2)
ADD_TEST(test_EVP_SM2);
ADD_TEST(test_EVP_SM2_verify);
#endif
ADD_ALL_TESTS(test_set_get_raw_keys, OSSL_NELEM(keys));
#ifndef OPENSSL_NO_DEPRECATED_3_0
custom_pmeth = EVP_PKEY_meth_new(0xdefaced, 0);
if (!TEST_ptr(custom_pmeth))
return 0;
EVP_PKEY_meth_set_check(custom_pmeth, pkey_custom_check);
EVP_PKEY_meth_set_public_check(custom_pmeth, pkey_custom_pub_check);
EVP_PKEY_meth_set_param_check(custom_pmeth, pkey_custom_param_check);
if (!TEST_int_eq(EVP_PKEY_meth_add0(custom_pmeth), 1))
return 0;
#endif
ADD_ALL_TESTS(test_EVP_PKEY_check, OSSL_NELEM(keycheckdata));
#ifndef OPENSSL_NO_CMAC
ADD_TEST(test_CMAC_keygen);
#endif
ADD_TEST(test_HKDF);
ADD_TEST(test_emptyikm_HKDF);
+ ADD_TEST(test_empty_salt_info_HKDF);
#ifndef OPENSSL_NO_EC
ADD_TEST(test_X509_PUBKEY_inplace);
ADD_TEST(test_X509_PUBKEY_dup);
ADD_ALL_TESTS(test_invalide_ec_char2_pub_range_decode,
OSSL_NELEM(ec_der_pub_keys));
#endif
#ifndef OPENSSL_NO_DSA
ADD_TEST(test_DSA_get_set_params);
ADD_TEST(test_DSA_priv_pub);
#endif
ADD_TEST(test_RSA_get_set_params);
ADD_TEST(test_RSA_OAEP_set_get_params);
ADD_TEST(test_RSA_OAEP_set_null_label);
#if !defined(OPENSSL_NO_CHACHA) && !defined(OPENSSL_NO_POLY1305)
ADD_TEST(test_decrypt_null_chunks);
#endif
#ifndef OPENSSL_NO_DH
ADD_TEST(test_DH_priv_pub);
# ifndef OPENSSL_NO_DEPRECATED_3_0
ADD_TEST(test_EVP_PKEY_set1_DH);
# endif
#endif
#ifndef OPENSSL_NO_EC
ADD_TEST(test_EC_priv_pub);
# ifndef OPENSSL_NO_DEPRECATED_3_0
ADD_TEST(test_EC_priv_only_legacy);
# endif
#endif
ADD_ALL_TESTS(test_keygen_with_empty_template, 2);
ADD_ALL_TESTS(test_pkey_ctx_fail_without_provider, 2);
ADD_TEST(test_rand_agglomeration);
ADD_ALL_TESTS(test_evp_iv_aes, 12);
#ifndef OPENSSL_NO_DES
ADD_ALL_TESTS(test_evp_iv_des, 6);
#endif
#ifndef OPENSSL_NO_BF
ADD_ALL_TESTS(test_evp_bf_default_keylen, 4);
#endif
ADD_TEST(test_EVP_rsa_pss_with_keygen_bits);
ADD_TEST(test_EVP_rsa_pss_set_saltlen);
#ifndef OPENSSL_NO_EC
ADD_ALL_TESTS(test_ecpub, OSSL_NELEM(ecpub_nids));
#endif
ADD_TEST(test_names_do_all);
ADD_ALL_TESTS(test_evp_init_seq, OSSL_NELEM(evp_init_tests));
ADD_ALL_TESTS(test_evp_reset, OSSL_NELEM(evp_reset_tests));
ADD_ALL_TESTS(test_evp_reinit_seq, OSSL_NELEM(evp_reinit_tests));
ADD_ALL_TESTS(test_gcm_reinit, OSSL_NELEM(gcm_reinit_tests));
ADD_ALL_TESTS(test_evp_updated_iv, OSSL_NELEM(evp_updated_iv_tests));
ADD_ALL_TESTS(test_ivlen_change, OSSL_NELEM(ivlen_change_ciphers));
if (OSSL_NELEM(keylen_change_ciphers) - 1 > 0)
ADD_ALL_TESTS(test_keylen_change, OSSL_NELEM(keylen_change_ciphers) - 1);
#ifndef OPENSSL_NO_DEPRECATED_3_0
ADD_ALL_TESTS(test_custom_pmeth, 12);
ADD_TEST(test_evp_md_cipher_meth);
ADD_TEST(test_custom_md_meth);
ADD_TEST(test_custom_ciph_meth);
# ifndef OPENSSL_NO_DYNAMIC_ENGINE
/* Tests only support the default libctx */
if (testctx == NULL) {
# ifndef OPENSSL_NO_EC
ADD_ALL_TESTS(test_signatures_with_engine, 3);
# else
ADD_ALL_TESTS(test_signatures_with_engine, 2);
# endif
ADD_TEST(test_cipher_with_engine);
}
# endif
#endif
ADD_ALL_TESTS(test_ecx_short_keys, OSSL_NELEM(ecxnids));
#ifndef OPENSSL_NO_EC
ADD_ALL_TESTS(test_ecx_not_private_key, OSSL_NELEM(keys));
#endif
/* Test cases for CVE-2023-5363 */
ADD_TEST(test_aes_gcm_ivlen_change_cve_2023_5363);
#ifndef OPENSSL_NO_RC4
ADD_TEST(test_aes_rc4_keylen_change_cve_2023_5363);
#endif
return 1;
}
void cleanup_tests(void)
{
OSSL_PROVIDER_unload(nullprov);
OSSL_PROVIDER_unload(deflprov);
OSSL_PROVIDER_unload(lgcyprov);
OSSL_LIB_CTX_free(testctx);
}
diff --git a/crypto/openssl/test/evp_pkey_provided_test.c b/crypto/openssl/test/evp_pkey_provided_test.c
index 27f90e42a7c1..688a8c1c5e55 100644
--- a/crypto/openssl/test/evp_pkey_provided_test.c
+++ b/crypto/openssl/test/evp_pkey_provided_test.c
@@ -1,1786 +1,1813 @@
/*
* Copyright 2019-2024 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 <string.h> /* memset */
#include <openssl/evp.h>
#include <openssl/pem.h>
#include <openssl/encoder.h>
#include <openssl/provider.h>
#include <openssl/param_build.h>
#include <openssl/core_names.h>
#include <openssl/sha.h>
#include "crypto/ecx.h"
#include "crypto/evp.h" /* For the internal API */
#include "crypto/bn_dh.h" /* _bignum_ffdhe2048_p */
#include "internal/nelem.h"
#include "testutil.h"
static char *datadir = NULL;
/*
* Do not change the order of the following defines unless you also
* update the for loop bounds used inside test_print_key_using_encoder() and
* test_print_key_using_encoder_public().
*/
#define PRIV_TEXT 0
#define PRIV_PEM 1
#define PRIV_DER 2
#define PUB_TEXT 3
#define PUB_PEM 4
#define PUB_DER 5
static void stripcr(char *buf, size_t *len)
{
size_t i;
char *curr, *writ;
for (i = *len, curr = buf, writ = buf; i > 0; i--, curr++) {
if (*curr == '\r') {
(*len)--;
continue;
}
if (curr != writ)
*writ = *curr;
writ++;
}
}
static int compare_with_file(const char *alg, int type, BIO *membio)
{
char filename[80];
BIO *file = NULL;
char buf[4096];
char *memdata, *fullfile = NULL;
const char *suffix;
size_t readbytes;
int ret = 0;
int len;
size_t slen;
switch (type) {
case PRIV_TEXT:
suffix = "priv.txt";
break;
case PRIV_PEM:
suffix = "priv.pem";
break;
case PRIV_DER:
suffix = "priv.der";
break;
case PUB_TEXT:
suffix = "pub.txt";
break;
case PUB_PEM:
suffix = "pub.pem";
break;
case PUB_DER:
suffix = "pub.der";
break;
default:
TEST_error("Invalid file type");
goto err;
}
BIO_snprintf(filename, sizeof(filename), "%s.%s", alg, suffix);
fullfile = test_mk_file_path(datadir, filename);
if (!TEST_ptr(fullfile))
goto err;
file = BIO_new_file(fullfile, "rb");
if (!TEST_ptr(file))
goto err;
if (!TEST_true(BIO_read_ex(file, buf, sizeof(buf), &readbytes))
|| !TEST_true(BIO_eof(file))
|| !TEST_size_t_lt(readbytes, sizeof(buf)))
goto err;
len = BIO_get_mem_data(membio, &memdata);
if (!TEST_int_gt(len, 0))
goto err;
slen = len;
if (type != PRIV_DER && type != PUB_DER) {
stripcr(memdata, &slen);
stripcr(buf, &readbytes);
}
if (!TEST_mem_eq(memdata, slen, buf, readbytes))
goto err;
ret = 1;
err:
OPENSSL_free(fullfile);
(void)BIO_reset(membio);
BIO_free(file);
return ret;
}
static int pass_cb(char *buf, int size, int rwflag, void *u)
{
return 0;
}
static int pass_cb_error(char *buf, int size, int rwflag, void *u)
{
return -1;
}
static int test_print_key_using_pem(const char *alg, const EVP_PKEY *pk)
{
BIO *membio = BIO_new(BIO_s_mem());
int ret = 0;
if (!TEST_ptr(membio))
goto err;
if (/* Output Encrypted private key in PEM form */
!TEST_true(PEM_write_bio_PrivateKey(bio_out, pk, EVP_aes_256_cbc(),
(unsigned char *)"pass", 4,
NULL, NULL))
/* Output zero-length passphrase encrypted private key in PEM form */
|| !TEST_true(PEM_write_bio_PKCS8PrivateKey(bio_out, pk,
EVP_aes_256_cbc(),
(const char *)~0, 0,
NULL, NULL))
|| !TEST_true(PEM_write_bio_PKCS8PrivateKey(bio_out, pk,
EVP_aes_256_cbc(),
NULL, 0, NULL, ""))
|| !TEST_true(PEM_write_bio_PKCS8PrivateKey(bio_out, pk,
EVP_aes_256_cbc(),
NULL, 0, pass_cb, NULL))
|| !TEST_false(PEM_write_bio_PKCS8PrivateKey(bio_out, pk,
EVP_aes_256_cbc(),
NULL, 0, pass_cb_error,
NULL))
#ifndef OPENSSL_NO_DES
|| !TEST_true(PEM_write_bio_PKCS8PrivateKey_nid(
bio_out, pk, NID_pbe_WithSHA1And3_Key_TripleDES_CBC,
(const char *)~0, 0, NULL, NULL))
|| !TEST_true(PEM_write_bio_PKCS8PrivateKey_nid(
bio_out, pk, NID_pbe_WithSHA1And3_Key_TripleDES_CBC, NULL, 0,
NULL, ""))
|| !TEST_true(PEM_write_bio_PKCS8PrivateKey_nid(
bio_out, pk, NID_pbe_WithSHA1And3_Key_TripleDES_CBC, NULL, 0,
pass_cb, NULL))
|| !TEST_false(PEM_write_bio_PKCS8PrivateKey_nid(
bio_out, pk, NID_pbe_WithSHA1And3_Key_TripleDES_CBC, NULL, 0,
pass_cb_error, NULL))
#endif
/* Private key in text form */
|| !TEST_int_gt(EVP_PKEY_print_private(membio, pk, 0, NULL), 0)
|| !TEST_true(compare_with_file(alg, PRIV_TEXT, membio))
/* Public key in PEM form */
|| !TEST_true(PEM_write_bio_PUBKEY(membio, pk))
|| !TEST_true(compare_with_file(alg, PUB_PEM, membio))
/* Unencrypted private key in PEM form */
|| !TEST_true(PEM_write_bio_PrivateKey(membio, pk,
NULL, NULL, 0, NULL, NULL))
|| !TEST_true(compare_with_file(alg, PRIV_PEM, membio))
/* NULL key */
|| !TEST_false(PEM_write_bio_PrivateKey(membio, NULL,
NULL, NULL, 0, NULL, NULL))
|| !TEST_false(PEM_write_bio_PrivateKey_traditional(membio, NULL,
NULL, NULL, 0, NULL, NULL)))
goto err;
ret = 1;
err:
BIO_free(membio);
return ret;
}
static int test_print_key_type_using_encoder(const char *alg, int type,
const EVP_PKEY *pk)
{
const char *output_type, *output_structure;
int selection;
OSSL_ENCODER_CTX *ctx = NULL;
BIO *membio = BIO_new(BIO_s_mem());
int ret = 0;
switch (type) {
case PRIV_TEXT:
output_type = "TEXT";
output_structure = NULL;
selection = OSSL_KEYMGMT_SELECT_KEYPAIR
| OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS;
break;
case PRIV_PEM:
output_type = "PEM";
output_structure = "PrivateKeyInfo";
selection = OSSL_KEYMGMT_SELECT_KEYPAIR
| OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS;
break;
case PRIV_DER:
output_type = "DER";
output_structure = "PrivateKeyInfo";
selection = OSSL_KEYMGMT_SELECT_KEYPAIR
| OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS;
break;
case PUB_TEXT:
output_type = "TEXT";
output_structure = NULL;
selection = OSSL_KEYMGMT_SELECT_PUBLIC_KEY
| OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS;
break;
case PUB_PEM:
output_type = "PEM";
output_structure = "SubjectPublicKeyInfo";
selection = OSSL_KEYMGMT_SELECT_PUBLIC_KEY
| OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS;
break;
case PUB_DER:
output_type = "DER";
output_structure = "SubjectPublicKeyInfo";
selection = OSSL_KEYMGMT_SELECT_PUBLIC_KEY
| OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS;
break;
default:
TEST_error("Invalid encoding type");
goto err;
}
if (!TEST_ptr(membio))
goto err;
/* Make a context, it's valid for several prints */
TEST_note("Setting up a OSSL_ENCODER context with passphrase");
if (!TEST_ptr(ctx = OSSL_ENCODER_CTX_new_for_pkey(pk, selection,
output_type,
output_structure,
NULL))
/* Check that this operation is supported */
|| !TEST_int_ne(OSSL_ENCODER_CTX_get_num_encoders(ctx), 0))
goto err;
/* Use no cipher. This should give us an unencrypted PEM */
TEST_note("Testing with no encryption");
if (!TEST_true(OSSL_ENCODER_to_bio(ctx, membio))
|| !TEST_true(compare_with_file(alg, type, membio)))
goto err;
if (type == PRIV_PEM) {
/* Set a passphrase to be used later */
if (!TEST_true(OSSL_ENCODER_CTX_set_passphrase(ctx,
(unsigned char *)"pass",
4)))
goto err;
/* Use a valid cipher name */
TEST_note("Displaying PEM encrypted with AES-256-CBC");
if (!TEST_true(OSSL_ENCODER_CTX_set_cipher(ctx, "AES-256-CBC", NULL))
|| !TEST_true(OSSL_ENCODER_to_bio(ctx, bio_out)))
goto err;
/* Use an invalid cipher name, which should generate no output */
TEST_note("NOT Displaying PEM encrypted with (invalid) FOO");
if (!TEST_false(OSSL_ENCODER_CTX_set_cipher(ctx, "FOO", NULL))
|| !TEST_false(OSSL_ENCODER_to_bio(ctx, bio_out)))
goto err;
/* Clear the cipher. This should give us an unencrypted PEM again */
TEST_note("Testing with encryption cleared (no encryption)");
if (!TEST_true(OSSL_ENCODER_CTX_set_cipher(ctx, NULL, NULL))
|| !TEST_true(OSSL_ENCODER_to_bio(ctx, membio))
|| !TEST_true(compare_with_file(alg, type, membio)))
goto err;
}
ret = 1;
err:
BIO_free(membio);
OSSL_ENCODER_CTX_free(ctx);
return ret;
}
static int test_print_key_using_encoder(const char *alg, const EVP_PKEY *pk)
{
int i;
int ret = 1;
for (i = PRIV_TEXT; i <= PUB_DER; i++)
ret = ret && test_print_key_type_using_encoder(alg, i, pk);
return ret;
}
#ifndef OPENSSL_NO_EC
static int test_print_key_using_encoder_public(const char *alg,
const EVP_PKEY *pk)
{
int i;
int ret = 1;
for (i = PUB_TEXT; i <= PUB_DER; i++)
ret = ret && test_print_key_type_using_encoder(alg, i, pk);
return ret;
}
#endif
/* Array indexes used in test_fromdata_rsa */
#define N 0
#define E 1
#define D 2
#define P 3
#define Q 4
#define DP 5
#define DQ 6
#define QINV 7
static int test_fromdata_rsa(void)
{
int ret = 0, i;
EVP_PKEY_CTX *ctx = NULL, *key_ctx = NULL;
EVP_PKEY *pk = NULL, *copy_pk = NULL, *dup_pk = NULL;
/*
* 32-bit RSA key, extracted from this command,
* executed with OpenSSL 1.0.2:
*
* openssl genrsa 32 | openssl rsa -text
*/
static unsigned long key_numbers[] = {
0xbc747fc5, /* N */
0x10001, /* E */
0x7b133399, /* D */
0xe963, /* P */
0xceb7, /* Q */
0x8599, /* DP */
0xbd87, /* DQ */
0xcc3b, /* QINV */
};
OSSL_PARAM fromdata_params[] = {
OSSL_PARAM_ulong(OSSL_PKEY_PARAM_RSA_N, &key_numbers[N]),
OSSL_PARAM_ulong(OSSL_PKEY_PARAM_RSA_E, &key_numbers[E]),
OSSL_PARAM_ulong(OSSL_PKEY_PARAM_RSA_D, &key_numbers[D]),
OSSL_PARAM_ulong(OSSL_PKEY_PARAM_RSA_FACTOR1, &key_numbers[P]),
OSSL_PARAM_ulong(OSSL_PKEY_PARAM_RSA_FACTOR2, &key_numbers[Q]),
OSSL_PARAM_ulong(OSSL_PKEY_PARAM_RSA_EXPONENT1, &key_numbers[DP]),
OSSL_PARAM_ulong(OSSL_PKEY_PARAM_RSA_EXPONENT2, &key_numbers[DQ]),
OSSL_PARAM_ulong(OSSL_PKEY_PARAM_RSA_COEFFICIENT1, &key_numbers[QINV]),
OSSL_PARAM_END
};
BIGNUM *bn = BN_new();
BIGNUM *bn_from = BN_new();
if (!TEST_ptr(ctx = EVP_PKEY_CTX_new_from_name(NULL, "RSA", NULL)))
goto err;
if (!TEST_int_eq(EVP_PKEY_fromdata_init(ctx), 1)
|| !TEST_int_eq(EVP_PKEY_fromdata(ctx, &pk, EVP_PKEY_KEYPAIR,
fromdata_params), 1))
goto err;
- while (dup_pk == NULL) {
+ for (;;) {
ret = 0;
if (!TEST_int_eq(EVP_PKEY_get_bits(pk), 32)
|| !TEST_int_eq(EVP_PKEY_get_security_bits(pk), 8)
|| !TEST_int_eq(EVP_PKEY_get_size(pk), 4)
|| !TEST_false(EVP_PKEY_missing_parameters(pk)))
goto err;
EVP_PKEY_CTX_free(key_ctx);
if (!TEST_ptr(key_ctx = EVP_PKEY_CTX_new_from_pkey(NULL, pk, "")))
goto err;
if (!TEST_int_gt(EVP_PKEY_check(key_ctx), 0)
|| !TEST_int_gt(EVP_PKEY_public_check(key_ctx), 0)
|| !TEST_int_gt(EVP_PKEY_private_check(key_ctx), 0)
|| !TEST_int_gt(EVP_PKEY_pairwise_check(key_ctx), 0))
goto err;
/* EVP_PKEY_copy_parameters() should fail for RSA */
if (!TEST_ptr(copy_pk = EVP_PKEY_new())
|| !TEST_false(EVP_PKEY_copy_parameters(copy_pk, pk)))
goto err;
EVP_PKEY_free(copy_pk);
copy_pk = NULL;
ret = test_print_key_using_pem("RSA", pk)
&& test_print_key_using_encoder("RSA", pk);
- if (!ret || !TEST_ptr(dup_pk = EVP_PKEY_dup(pk)))
+ if (!ret || dup_pk != NULL)
+ break;
+
+ if (!TEST_ptr(dup_pk = EVP_PKEY_dup(pk)))
goto err;
ret = ret && TEST_int_eq(EVP_PKEY_eq(pk, dup_pk), 1);
EVP_PKEY_free(pk);
pk = dup_pk;
if (!ret)
goto err;
}
err:
/* for better diagnostics always compare key params */
for (i = 0; fromdata_params[i].key != NULL; ++i) {
if (!TEST_true(BN_set_word(bn_from, key_numbers[i]))
|| !TEST_true(EVP_PKEY_get_bn_param(pk, fromdata_params[i].key, &bn))
|| !TEST_BN_eq(bn, bn_from))
ret = 0;
}
BN_free(bn_from);
BN_free(bn);
EVP_PKEY_free(pk);
EVP_PKEY_free(copy_pk);
EVP_PKEY_CTX_free(key_ctx);
EVP_PKEY_CTX_free(ctx);
return ret;
}
static int test_evp_pkey_get_bn_param_large(void)
{
int ret = 0;
EVP_PKEY_CTX *ctx = NULL, *key_ctx = NULL;
EVP_PKEY *pk = NULL;
OSSL_PARAM_BLD *bld = NULL;
OSSL_PARAM *fromdata_params = NULL;
BIGNUM *n = NULL, *e = NULL, *d = NULL, *n_out = NULL;
/*
* The buffer size chosen here for n_data larger than the buffer used
* internally in EVP_PKEY_get_bn_param.
*/
static unsigned char n_data[2050];
static const unsigned char e_data[] = {
0x1, 0x00, 0x01
};
static const unsigned char d_data[]= {
0x99, 0x33, 0x13, 0x7b
};
/* N is a large buffer */
memset(n_data, 0xCE, sizeof(n_data));
if (!TEST_ptr(bld = OSSL_PARAM_BLD_new())
|| !TEST_ptr(n = BN_bin2bn(n_data, sizeof(n_data), NULL))
|| !TEST_ptr(e = BN_bin2bn(e_data, sizeof(e_data), NULL))
|| !TEST_ptr(d = BN_bin2bn(d_data, sizeof(d_data), NULL))
|| !TEST_true(OSSL_PARAM_BLD_push_BN(bld, OSSL_PKEY_PARAM_RSA_N, n))
|| !TEST_true(OSSL_PARAM_BLD_push_BN(bld, OSSL_PKEY_PARAM_RSA_E, e))
|| !TEST_true(OSSL_PARAM_BLD_push_BN(bld, OSSL_PKEY_PARAM_RSA_D, d))
|| !TEST_ptr(fromdata_params = OSSL_PARAM_BLD_to_param(bld))
|| !TEST_ptr(ctx = EVP_PKEY_CTX_new_from_name(NULL, "RSA", NULL))
|| !TEST_int_eq(EVP_PKEY_fromdata_init(ctx), 1)
|| !TEST_int_eq(EVP_PKEY_fromdata(ctx, &pk, EVP_PKEY_KEYPAIR,
fromdata_params), 1)
|| !TEST_ptr(key_ctx = EVP_PKEY_CTX_new_from_pkey(NULL, pk, ""))
|| !TEST_true(EVP_PKEY_get_bn_param(pk, OSSL_PKEY_PARAM_RSA_N, &n_out))
|| !TEST_BN_eq(n, n_out))
goto err;
ret = 1;
err:
BN_free(n_out);
BN_free(n);
BN_free(e);
BN_free(d);
EVP_PKEY_free(pk);
EVP_PKEY_CTX_free(key_ctx);
EVP_PKEY_CTX_free(ctx);
OSSL_PARAM_free(fromdata_params);
OSSL_PARAM_BLD_free(bld);
return ret;
}
#ifndef OPENSSL_NO_DH
static int test_fromdata_dh_named_group(void)
{
int ret = 0;
int gindex = 0, pcounter = 0, hindex = 0;
EVP_PKEY_CTX *ctx = NULL, *key_ctx = NULL;
EVP_PKEY *pk = NULL, *copy_pk = NULL, *dup_pk = NULL;
size_t len;
BIGNUM *pub = NULL, *priv = NULL;
BIGNUM *pub_out = NULL, *priv_out = NULL;
BIGNUM *p = NULL, *q = NULL, *g = NULL, *j = NULL;
OSSL_PARAM *fromdata_params = NULL;
OSSL_PARAM_BLD *bld = NULL;
char name_out[80];
unsigned char seed_out[32];
/*
* DH key data was generated using the following:
* openssl genpkey -algorithm DH -pkeyopt group:ffdhe2048
* -pkeyopt priv_len:224 -text
*/
static const unsigned char priv_data[] = {
0x88, 0x85, 0xe7, 0x9f, 0xee, 0x6d, 0xc5, 0x7c, 0x78, 0xaf, 0x63, 0x5d,
0x38, 0x2a, 0xd0, 0xed, 0x56, 0x4b, 0x47, 0x21, 0x2b, 0xfa, 0x55, 0xfa,
0x87, 0xe8, 0xa9, 0x7b,
};
static const unsigned char pub_data[] = {
0x00, 0xd6, 0x2d, 0x77, 0xe0, 0xd3, 0x7d, 0xf8, 0xeb, 0x98, 0x50, 0xa1,
0x82, 0x22, 0x65, 0xd5, 0xd9, 0xfe, 0xc9, 0x3f, 0xbe, 0x16, 0x83, 0xbd,
0x33, 0xe9, 0xc6, 0x93, 0xcf, 0x08, 0xaf, 0x83, 0xfa, 0x80, 0x8a, 0x6c,
0x64, 0xdf, 0x70, 0x64, 0xd5, 0x0a, 0x7c, 0x5a, 0x72, 0xda, 0x66, 0xe6,
0xf9, 0xf5, 0x31, 0x21, 0x92, 0xb0, 0x60, 0x1a, 0xb5, 0xd3, 0xf0, 0xa5,
0xfa, 0x48, 0x95, 0x2e, 0x38, 0xd9, 0xc5, 0xe6, 0xda, 0xfb, 0x6c, 0x03,
0x9d, 0x4b, 0x69, 0xb7, 0x95, 0xe4, 0x5c, 0xc0, 0x93, 0x4f, 0x48, 0xd9,
0x7e, 0x06, 0x22, 0xb2, 0xde, 0xf3, 0x79, 0x24, 0xed, 0xe1, 0xd1, 0x4a,
0x57, 0xf1, 0x40, 0x86, 0x70, 0x42, 0x25, 0xc5, 0x27, 0x68, 0xc9, 0xfa,
0xe5, 0x8e, 0x62, 0x7e, 0xff, 0x49, 0x6c, 0x5b, 0xb5, 0xba, 0xf9, 0xef,
0x9a, 0x1a, 0x10, 0xd4, 0x81, 0x53, 0xcf, 0x83, 0x04, 0x18, 0x1c, 0xe1,
0xdb, 0xe1, 0x65, 0xa9, 0x7f, 0xe1, 0x33, 0xeb, 0xc3, 0x4f, 0xe3, 0xb7,
0x22, 0xf7, 0x1c, 0x09, 0x4f, 0xed, 0xc6, 0x07, 0x8e, 0x78, 0x05, 0x8f,
0x7c, 0x96, 0xd9, 0x12, 0xe0, 0x81, 0x74, 0x1a, 0xe9, 0x13, 0xc0, 0x20,
0x82, 0x65, 0xbb, 0x42, 0x3b, 0xed, 0x08, 0x6a, 0x84, 0x4f, 0xea, 0x77,
0x14, 0x32, 0xf9, 0xed, 0xc2, 0x12, 0xd6, 0xc5, 0xc6, 0xb3, 0xe5, 0xf2,
0x6e, 0xf6, 0x16, 0x7f, 0x37, 0xde, 0xbc, 0x09, 0xc7, 0x06, 0x6b, 0x12,
0xbc, 0xad, 0x2d, 0x49, 0x25, 0xd5, 0xdc, 0xf4, 0x18, 0x14, 0xd2, 0xf0,
0xf1, 0x1d, 0x1f, 0x3a, 0xaa, 0x15, 0x55, 0xbb, 0x0d, 0x7f, 0xbe, 0x67,
0xa1, 0xa7, 0xf0, 0xaa, 0xb3, 0xfb, 0x41, 0x82, 0x39, 0x49, 0x93, 0xbc,
0xa8, 0xee, 0x72, 0x13, 0x45, 0x65, 0x15, 0x42, 0x17, 0xaa, 0xd8, 0xab,
0xcf, 0x33, 0x42, 0x83, 0x42
};
static const char group_name[] = "ffdhe2048";
static const long priv_len = 224;
if (!TEST_ptr(bld = OSSL_PARAM_BLD_new())
|| !TEST_ptr(pub = BN_bin2bn(pub_data, sizeof(pub_data), NULL))
|| !TEST_ptr(priv = BN_bin2bn(priv_data, sizeof(priv_data), NULL))
|| !TEST_true(OSSL_PARAM_BLD_push_utf8_string(bld,
OSSL_PKEY_PARAM_GROUP_NAME,
group_name, 0))
|| !TEST_true(OSSL_PARAM_BLD_push_long(bld, OSSL_PKEY_PARAM_DH_PRIV_LEN,
priv_len))
|| !TEST_true(OSSL_PARAM_BLD_push_BN(bld, OSSL_PKEY_PARAM_PUB_KEY, pub))
|| !TEST_true(OSSL_PARAM_BLD_push_BN(bld, OSSL_PKEY_PARAM_PRIV_KEY, priv))
|| !TEST_ptr(fromdata_params = OSSL_PARAM_BLD_to_param(bld)))
goto err;
if (!TEST_ptr(ctx = EVP_PKEY_CTX_new_from_name(NULL, "DH", NULL)))
goto err;
if (!TEST_int_eq(EVP_PKEY_fromdata_init(ctx), 1)
|| !TEST_int_eq(EVP_PKEY_fromdata(ctx, &pk, EVP_PKEY_KEYPAIR,
fromdata_params), 1))
goto err;
/*
* A few extra checks of EVP_PKEY_get_utf8_string_param() to see that
* it behaves as expected with regards to string length and terminating
* NUL byte.
*/
if (!TEST_true(EVP_PKEY_get_utf8_string_param(pk,
OSSL_PKEY_PARAM_GROUP_NAME,
NULL, sizeof(name_out),
&len))
|| !TEST_size_t_eq(len, sizeof(group_name) - 1)
/* Just enough space to hold the group name and a terminating NUL */
|| !TEST_true(EVP_PKEY_get_utf8_string_param(pk,
OSSL_PKEY_PARAM_GROUP_NAME,
name_out,
sizeof(group_name),
&len))
|| !TEST_size_t_eq(len, sizeof(group_name) - 1)
/* Too small buffer to hold the terminating NUL byte */
|| !TEST_false(EVP_PKEY_get_utf8_string_param(pk,
OSSL_PKEY_PARAM_GROUP_NAME,
name_out,
sizeof(group_name) - 1,
&len))
/* Too small buffer to hold the whole group name, even! */
|| !TEST_false(EVP_PKEY_get_utf8_string_param(pk,
OSSL_PKEY_PARAM_GROUP_NAME,
name_out,
sizeof(group_name) - 2,
&len)))
goto err;
- while (dup_pk == NULL) {
+ for (;;) {
ret = 0;
if (!TEST_int_eq(EVP_PKEY_get_bits(pk), 2048)
|| !TEST_int_eq(EVP_PKEY_get_security_bits(pk), 112)
|| !TEST_int_eq(EVP_PKEY_get_size(pk), 256)
|| !TEST_false(EVP_PKEY_missing_parameters(pk)))
goto err;
if (!TEST_true(EVP_PKEY_get_utf8_string_param(pk,
OSSL_PKEY_PARAM_GROUP_NAME,
name_out,
sizeof(name_out),
&len))
|| !TEST_str_eq(name_out, group_name)
|| !TEST_true(EVP_PKEY_get_bn_param(pk, OSSL_PKEY_PARAM_PUB_KEY,
&pub_out))
|| !TEST_BN_eq(pub, pub_out)
|| !TEST_true(EVP_PKEY_get_bn_param(pk, OSSL_PKEY_PARAM_PRIV_KEY,
&priv_out))
|| !TEST_BN_eq(priv, priv_out)
|| !TEST_true(EVP_PKEY_get_bn_param(pk, OSSL_PKEY_PARAM_FFC_P, &p))
|| !TEST_BN_eq(&ossl_bignum_ffdhe2048_p, p)
|| !TEST_true(EVP_PKEY_get_bn_param(pk, OSSL_PKEY_PARAM_FFC_Q, &q))
|| !TEST_ptr(q)
|| !TEST_true(EVP_PKEY_get_bn_param(pk, OSSL_PKEY_PARAM_FFC_G, &g))
|| !TEST_BN_eq(&ossl_bignum_const_2, g)
|| !TEST_false(EVP_PKEY_get_bn_param(pk,
OSSL_PKEY_PARAM_FFC_COFACTOR,
&j))
|| !TEST_ptr_null(j)
|| !TEST_false(EVP_PKEY_get_octet_string_param(pk,
OSSL_PKEY_PARAM_FFC_SEED,
seed_out,
sizeof(seed_out),
&len))
|| !TEST_true(EVP_PKEY_get_int_param(pk, OSSL_PKEY_PARAM_FFC_GINDEX,
&gindex))
|| !TEST_int_eq(gindex, -1)
|| !TEST_true(EVP_PKEY_get_int_param(pk, OSSL_PKEY_PARAM_FFC_H,
&hindex))
|| !TEST_int_eq(hindex, 0)
|| !TEST_true(EVP_PKEY_get_int_param(pk,
OSSL_PKEY_PARAM_FFC_PCOUNTER,
&pcounter))
|| !TEST_int_eq(pcounter, -1))
goto err;
BN_free(p);
p = NULL;
BN_free(q);
q = NULL;
BN_free(g);
g = NULL;
BN_free(j);
j = NULL;
BN_free(pub_out);
pub_out = NULL;
BN_free(priv_out);
priv_out = NULL;
if (!TEST_ptr(key_ctx = EVP_PKEY_CTX_new_from_pkey(NULL, pk, "")))
goto err;
if (!TEST_int_gt(EVP_PKEY_check(key_ctx), 0)
|| !TEST_int_gt(EVP_PKEY_public_check(key_ctx), 0)
|| !TEST_int_gt(EVP_PKEY_private_check(key_ctx), 0)
|| !TEST_int_gt(EVP_PKEY_pairwise_check(key_ctx), 0))
goto err;
EVP_PKEY_CTX_free(key_ctx);
key_ctx = NULL;
if (!TEST_ptr(copy_pk = EVP_PKEY_new())
|| !TEST_true(EVP_PKEY_copy_parameters(copy_pk, pk)))
goto err;
EVP_PKEY_free(copy_pk);
copy_pk = NULL;
ret = test_print_key_using_pem("DH", pk)
&& test_print_key_using_encoder("DH", pk);
- if (!ret || !TEST_ptr(dup_pk = EVP_PKEY_dup(pk)))
+ if (!ret || dup_pk != NULL)
+ break;
+
+ if (!TEST_ptr(dup_pk = EVP_PKEY_dup(pk)))
goto err;
ret = ret && TEST_int_eq(EVP_PKEY_eq(pk, dup_pk), 1);
EVP_PKEY_free(pk);
pk = dup_pk;
if (!ret)
goto err;
}
err:
BN_free(p);
BN_free(q);
BN_free(g);
BN_free(j);
BN_free(pub);
BN_free(priv);
BN_free(pub_out);
BN_free(priv_out);
EVP_PKEY_free(copy_pk);
EVP_PKEY_free(pk);
EVP_PKEY_CTX_free(ctx);
EVP_PKEY_CTX_free(key_ctx);
OSSL_PARAM_free(fromdata_params);
OSSL_PARAM_BLD_free(bld);
return ret;
}
static int test_fromdata_dh_fips186_4(void)
{
int ret = 0;
int gindex = 0, pcounter = 0, hindex = 0;
EVP_PKEY_CTX *ctx = NULL, *key_ctx = NULL;
EVP_PKEY *pk = NULL, *dup_pk = NULL;
size_t len;
BIGNUM *pub = NULL, *priv = NULL;
BIGNUM *pub_out = NULL, *priv_out = NULL;
BIGNUM *p = NULL, *q = NULL, *g = NULL, *j = NULL;
OSSL_PARAM_BLD *bld = NULL;
OSSL_PARAM *fromdata_params = NULL;
char name_out[80];
unsigned char seed_out[32];
/*
* DH key data was generated using the following:
* openssl genpkey -algorithm DH
* -pkeyopt group:ffdhe2048 -pkeyopt priv_len:224 -text
*/
static const unsigned char priv_data[] = {
0x88, 0x85, 0xe7, 0x9f, 0xee, 0x6d, 0xc5, 0x7c, 0x78, 0xaf, 0x63, 0x5d,
0x38, 0x2a, 0xd0, 0xed, 0x56, 0x4b, 0x47, 0x21, 0x2b, 0xfa, 0x55, 0xfa,
0x87, 0xe8, 0xa9, 0x7b,
};
static const unsigned char pub_data[] = {
0xd6, 0x2d, 0x77, 0xe0, 0xd3, 0x7d, 0xf8, 0xeb, 0x98, 0x50, 0xa1, 0x82,
0x22, 0x65, 0xd5, 0xd9, 0xfe, 0xc9, 0x3f, 0xbe, 0x16, 0x83, 0xbd, 0x33,
0xe9, 0xc6, 0x93, 0xcf, 0x08, 0xaf, 0x83, 0xfa, 0x80, 0x8a, 0x6c, 0x64,
0xdf, 0x70, 0x64, 0xd5, 0x0a, 0x7c, 0x5a, 0x72, 0xda, 0x66, 0xe6, 0xf9,
0xf5, 0x31, 0x21, 0x92, 0xb0, 0x60, 0x1a, 0xb5, 0xd3, 0xf0, 0xa5, 0xfa,
0x48, 0x95, 0x2e, 0x38, 0xd9, 0xc5, 0xe6, 0xda, 0xfb, 0x6c, 0x03, 0x9d,
0x4b, 0x69, 0xb7, 0x95, 0xe4, 0x5c, 0xc0, 0x93, 0x4f, 0x48, 0xd9, 0x7e,
0x06, 0x22, 0xb2, 0xde, 0xf3, 0x79, 0x24, 0xed, 0xe1, 0xd1, 0x4a, 0x57,
0xf1, 0x40, 0x86, 0x70, 0x42, 0x25, 0xc5, 0x27, 0x68, 0xc9, 0xfa, 0xe5,
0x8e, 0x62, 0x7e, 0xff, 0x49, 0x6c, 0x5b, 0xb5, 0xba, 0xf9, 0xef, 0x9a,
0x1a, 0x10, 0xd4, 0x81, 0x53, 0xcf, 0x83, 0x04, 0x18, 0x1c, 0xe1, 0xdb,
0xe1, 0x65, 0xa9, 0x7f, 0xe1, 0x33, 0xeb, 0xc3, 0x4f, 0xe3, 0xb7, 0x22,
0xf7, 0x1c, 0x09, 0x4f, 0xed, 0xc6, 0x07, 0x8e, 0x78, 0x05, 0x8f, 0x7c,
0x96, 0xd9, 0x12, 0xe0, 0x81, 0x74, 0x1a, 0xe9, 0x13, 0xc0, 0x20, 0x82,
0x65, 0xbb, 0x42, 0x3b, 0xed, 0x08, 0x6a, 0x84, 0x4f, 0xea, 0x77, 0x14,
0x32, 0xf9, 0xed, 0xc2, 0x12, 0xd6, 0xc5, 0xc6, 0xb3, 0xe5, 0xf2, 0x6e,
0xf6, 0x16, 0x7f, 0x37, 0xde, 0xbc, 0x09, 0xc7, 0x06, 0x6b, 0x12, 0xbc,
0xad, 0x2d, 0x49, 0x25, 0xd5, 0xdc, 0xf4, 0x18, 0x14, 0xd2, 0xf0, 0xf1,
0x1d, 0x1f, 0x3a, 0xaa, 0x15, 0x55, 0xbb, 0x0d, 0x7f, 0xbe, 0x67, 0xa1,
0xa7, 0xf0, 0xaa, 0xb3, 0xfb, 0x41, 0x82, 0x39, 0x49, 0x93, 0xbc, 0xa8,
0xee, 0x72, 0x13, 0x45, 0x65, 0x15, 0x42, 0x17, 0xaa, 0xd8, 0xab, 0xcf,
0x33, 0x42, 0x83, 0x42
};
static const char group_name[] = "ffdhe2048";
static const long priv_len = 224;
if (!TEST_ptr(bld = OSSL_PARAM_BLD_new())
|| !TEST_ptr(pub = BN_bin2bn(pub_data, sizeof(pub_data), NULL))
|| !TEST_ptr(priv = BN_bin2bn(priv_data, sizeof(priv_data), NULL))
|| !TEST_true(OSSL_PARAM_BLD_push_utf8_string(bld,
OSSL_PKEY_PARAM_GROUP_NAME,
group_name, 0))
|| !TEST_true(OSSL_PARAM_BLD_push_long(bld, OSSL_PKEY_PARAM_DH_PRIV_LEN,
priv_len))
|| !TEST_true(OSSL_PARAM_BLD_push_BN(bld, OSSL_PKEY_PARAM_PUB_KEY, pub))
|| !TEST_true(OSSL_PARAM_BLD_push_BN(bld, OSSL_PKEY_PARAM_PRIV_KEY, priv))
|| !TEST_ptr(fromdata_params = OSSL_PARAM_BLD_to_param(bld)))
goto err;
if (!TEST_ptr(ctx = EVP_PKEY_CTX_new_from_name(NULL, "DH", NULL)))
goto err;
if (!TEST_int_eq(EVP_PKEY_fromdata_init(ctx), 1)
|| !TEST_int_eq(EVP_PKEY_fromdata(ctx, &pk, EVP_PKEY_KEYPAIR,
fromdata_params), 1))
goto err;
- while (dup_pk == NULL) {
+ for (;;) {
ret = 0;
if (!TEST_int_eq(EVP_PKEY_get_bits(pk), 2048)
|| !TEST_int_eq(EVP_PKEY_get_security_bits(pk), 112)
|| !TEST_int_eq(EVP_PKEY_get_size(pk), 256)
|| !TEST_false(EVP_PKEY_missing_parameters(pk)))
goto err;
if (!TEST_true(EVP_PKEY_get_utf8_string_param(pk,
OSSL_PKEY_PARAM_GROUP_NAME,
name_out,
sizeof(name_out),
&len))
|| !TEST_str_eq(name_out, group_name)
|| !TEST_true(EVP_PKEY_get_bn_param(pk, OSSL_PKEY_PARAM_PUB_KEY,
&pub_out))
|| !TEST_BN_eq(pub, pub_out)
|| !TEST_true(EVP_PKEY_get_bn_param(pk, OSSL_PKEY_PARAM_PRIV_KEY,
&priv_out))
|| !TEST_BN_eq(priv, priv_out)
|| !TEST_true(EVP_PKEY_get_bn_param(pk, OSSL_PKEY_PARAM_FFC_P, &p))
|| !TEST_BN_eq(&ossl_bignum_ffdhe2048_p, p)
|| !TEST_true(EVP_PKEY_get_bn_param(pk, OSSL_PKEY_PARAM_FFC_Q, &q))
|| !TEST_ptr(q)
|| !TEST_true(EVP_PKEY_get_bn_param(pk, OSSL_PKEY_PARAM_FFC_G, &g))
|| !TEST_BN_eq(&ossl_bignum_const_2, g)
|| !TEST_false(EVP_PKEY_get_bn_param(pk,
OSSL_PKEY_PARAM_FFC_COFACTOR,
&j))
|| !TEST_ptr_null(j)
|| !TEST_false(EVP_PKEY_get_octet_string_param(pk,
OSSL_PKEY_PARAM_FFC_SEED,
seed_out,
sizeof(seed_out),
&len))
|| !TEST_true(EVP_PKEY_get_int_param(pk,
OSSL_PKEY_PARAM_FFC_GINDEX,
&gindex))
|| !TEST_int_eq(gindex, -1)
|| !TEST_true(EVP_PKEY_get_int_param(pk, OSSL_PKEY_PARAM_FFC_H,
&hindex))
|| !TEST_int_eq(hindex, 0)
|| !TEST_true(EVP_PKEY_get_int_param(pk,
OSSL_PKEY_PARAM_FFC_PCOUNTER,
&pcounter))
|| !TEST_int_eq(pcounter, -1))
goto err;
BN_free(p);
p = NULL;
BN_free(q);
q = NULL;
BN_free(g);
g = NULL;
BN_free(j);
j = NULL;
BN_free(pub_out);
pub_out = NULL;
BN_free(priv_out);
priv_out = NULL;
if (!TEST_ptr(key_ctx = EVP_PKEY_CTX_new_from_pkey(NULL, pk, "")))
goto err;
if (!TEST_int_gt(EVP_PKEY_check(key_ctx), 0)
|| !TEST_int_gt(EVP_PKEY_public_check(key_ctx), 0)
|| !TEST_int_gt(EVP_PKEY_private_check(key_ctx), 0)
|| !TEST_int_gt(EVP_PKEY_pairwise_check(key_ctx), 0))
goto err;
EVP_PKEY_CTX_free(key_ctx);
key_ctx = NULL;
ret = test_print_key_using_pem("DH", pk)
&& test_print_key_using_encoder("DH", pk);
- if (!ret || !TEST_ptr(dup_pk = EVP_PKEY_dup(pk)))
+ if (!ret || dup_pk != NULL)
+ break;
+
+ if (!TEST_ptr(dup_pk = EVP_PKEY_dup(pk)))
goto err;
ret = ret && TEST_int_eq(EVP_PKEY_eq(pk, dup_pk), 1);
EVP_PKEY_free(pk);
pk = dup_pk;
if (!ret)
goto err;
}
err:
BN_free(p);
BN_free(q);
BN_free(g);
BN_free(j);
BN_free(pub);
BN_free(priv);
BN_free(pub_out);
BN_free(priv_out);
EVP_PKEY_free(pk);
EVP_PKEY_CTX_free(ctx);
EVP_PKEY_CTX_free(key_ctx);
OSSL_PARAM_free(fromdata_params);
OSSL_PARAM_BLD_free(bld);
return ret;
}
#endif
#ifndef OPENSSL_NO_EC
/* Array indexes used in test_fromdata_ecx */
# define PRIV_KEY 0
# define PUB_KEY 1
# define X25519_IDX 0
# define X448_IDX 1
# define ED25519_IDX 2
# define ED448_IDX 3
/*
* tst uses indexes 0 ... (3 * 4 - 1)
* For the 4 ECX key types (X25519_IDX..ED448_IDX)
* 0..3 = public + private key.
* 4..7 = private key (This will generate the public key from the private key)
* 8..11 = public key
*/
static int test_fromdata_ecx(int tst)
{
int ret = 0;
EVP_PKEY_CTX *ctx = NULL, *ctx2 = NULL;
EVP_PKEY *pk = NULL, *copy_pk = NULL, *dup_pk = NULL;
const char *alg = NULL;
size_t len;
unsigned char out_pub[ED448_KEYLEN];
unsigned char out_priv[ED448_KEYLEN];
OSSL_PARAM params[3] = { OSSL_PARAM_END, OSSL_PARAM_END, OSSL_PARAM_END };
/* ED448_KEYLEN > X448_KEYLEN > X25519_KEYLEN == ED25519_KEYLEN */
static unsigned char key_numbers[4][2][ED448_KEYLEN] = {
/* X25519: Keys from RFC 7748 6.1 */
{
/* Private Key */
{
0x77, 0x07, 0x6d, 0x0a, 0x73, 0x18, 0xa5, 0x7d, 0x3c, 0x16,
0xc1, 0x72, 0x51, 0xb2, 0x66, 0x45, 0xdf, 0x4c, 0x2f, 0x87,
0xeb, 0xc0, 0x99, 0x2a, 0xb1, 0x77, 0xfb, 0xa5, 0x1d, 0xb9,
0x2c, 0x2a
},
/* Public Key */
{
0x85, 0x20, 0xf0, 0x09, 0x89, 0x30, 0xa7, 0x54, 0x74, 0x8b,
0x7d, 0xdc, 0xb4, 0x3e, 0xf7, 0x5a, 0x0d, 0xbf, 0x3a, 0x0d,
0x26, 0x38, 0x1a, 0xf4, 0xeb, 0xa4, 0xa9, 0x8e, 0xaa, 0x9b,
0x4e, 0x6a
}
},
/* X448: Keys from RFC 7748 6.2 */
{
/* Private Key */
{
0x9a, 0x8f, 0x49, 0x25, 0xd1, 0x51, 0x9f, 0x57, 0x75, 0xcf,
0x46, 0xb0, 0x4b, 0x58, 0x00, 0xd4, 0xee, 0x9e, 0xe8, 0xba,
0xe8, 0xbc, 0x55, 0x65, 0xd4, 0x98, 0xc2, 0x8d, 0xd9, 0xc9,
0xba, 0xf5, 0x74, 0xa9, 0x41, 0x97, 0x44, 0x89, 0x73, 0x91,
0x00, 0x63, 0x82, 0xa6, 0xf1, 0x27, 0xab, 0x1d, 0x9a, 0xc2,
0xd8, 0xc0, 0xa5, 0x98, 0x72, 0x6b
},
/* Public Key */
{
0x9b, 0x08, 0xf7, 0xcc, 0x31, 0xb7, 0xe3, 0xe6, 0x7d, 0x22,
0xd5, 0xae, 0xa1, 0x21, 0x07, 0x4a, 0x27, 0x3b, 0xd2, 0xb8,
0x3d, 0xe0, 0x9c, 0x63, 0xfa, 0xa7, 0x3d, 0x2c, 0x22, 0xc5,
0xd9, 0xbb, 0xc8, 0x36, 0x64, 0x72, 0x41, 0xd9, 0x53, 0xd4,
0x0c, 0x5b, 0x12, 0xda, 0x88, 0x12, 0x0d, 0x53, 0x17, 0x7f,
0x80, 0xe5, 0x32, 0xc4, 0x1f, 0xa0
}
},
/* ED25519: Keys from RFC 8032 */
{
/* Private Key */
{
0x9d, 0x61, 0xb1, 0x9d, 0xef, 0xfd, 0x5a, 0x60, 0xba, 0x84,
0x4a, 0xf4, 0x92, 0xec, 0x2c, 0xc4, 0x44, 0x49, 0xc5, 0x69,
0x7b, 0x32, 0x69, 0x19, 0x70, 0x3b, 0xac, 0x03, 0x1c, 0xae,
0x7f, 0x60
},
/* Public Key */
{
0xd7, 0x5a, 0x98, 0x01, 0x82, 0xb1, 0x0a, 0xb7, 0xd5, 0x4b,
0xfe, 0xd3, 0xc9, 0x64, 0x07, 0x3a, 0x0e, 0xe1, 0x72, 0xf3,
0xda, 0xa6, 0x23, 0x25, 0xaf, 0x02, 0x1a, 0x68, 0xf7, 0x07,
0x51, 0x1a
}
},
/* ED448: Keys from RFC 8032 */
{
/* Private Key */
{
0x6c, 0x82, 0xa5, 0x62, 0xcb, 0x80, 0x8d, 0x10, 0xd6, 0x32,
0xbe, 0x89, 0xc8, 0x51, 0x3e, 0xbf, 0x6c, 0x92, 0x9f, 0x34,
0xdd, 0xfa, 0x8c, 0x9f, 0x63, 0xc9, 0x96, 0x0e, 0xf6, 0xe3,
0x48, 0xa3, 0x52, 0x8c, 0x8a, 0x3f, 0xcc, 0x2f, 0x04, 0x4e,
0x39, 0xa3, 0xfc, 0x5b, 0x94, 0x49, 0x2f, 0x8f, 0x03, 0x2e,
0x75, 0x49, 0xa2, 0x00, 0x98, 0xf9, 0x5b
},
/* Public Key */
{
0x5f, 0xd7, 0x44, 0x9b, 0x59, 0xb4, 0x61, 0xfd, 0x2c, 0xe7,
0x87, 0xec, 0x61, 0x6a, 0xd4, 0x6a, 0x1d, 0xa1, 0x34, 0x24,
0x85, 0xa7, 0x0e, 0x1f, 0x8a, 0x0e, 0xa7, 0x5d, 0x80, 0xe9,
0x67, 0x78, 0xed, 0xf1, 0x24, 0x76, 0x9b, 0x46, 0xc7, 0x06,
0x1b, 0xd6, 0x78, 0x3d, 0xf1, 0xe5, 0x0f, 0x6c, 0xd1, 0xfa,
0x1a, 0xbe, 0xaf, 0xe8, 0x25, 0x61, 0x80
}
}
};
OSSL_PARAM x25519_fromdata_params[] = {
OSSL_PARAM_octet_string(OSSL_PKEY_PARAM_PRIV_KEY,
key_numbers[X25519_IDX][PRIV_KEY],
X25519_KEYLEN),
OSSL_PARAM_octet_string(OSSL_PKEY_PARAM_PUB_KEY,
key_numbers[X25519_IDX][PUB_KEY],
X25519_KEYLEN),
OSSL_PARAM_END
};
OSSL_PARAM x448_fromdata_params[] = {
OSSL_PARAM_octet_string(OSSL_PKEY_PARAM_PRIV_KEY,
key_numbers[X448_IDX][PRIV_KEY],
X448_KEYLEN),
OSSL_PARAM_octet_string(OSSL_PKEY_PARAM_PUB_KEY,
key_numbers[X448_IDX][PUB_KEY],
X448_KEYLEN),
OSSL_PARAM_END
};
OSSL_PARAM ed25519_fromdata_params[] = {
OSSL_PARAM_octet_string(OSSL_PKEY_PARAM_PRIV_KEY,
key_numbers[ED25519_IDX][PRIV_KEY],
ED25519_KEYLEN),
OSSL_PARAM_octet_string(OSSL_PKEY_PARAM_PUB_KEY,
key_numbers[ED25519_IDX][PUB_KEY],
ED25519_KEYLEN),
OSSL_PARAM_END
};
OSSL_PARAM ed448_fromdata_params[] = {
OSSL_PARAM_octet_string(OSSL_PKEY_PARAM_PRIV_KEY,
key_numbers[ED448_IDX][PRIV_KEY],
ED448_KEYLEN),
OSSL_PARAM_octet_string(OSSL_PKEY_PARAM_PUB_KEY,
key_numbers[ED448_IDX][PUB_KEY],
ED448_KEYLEN),
OSSL_PARAM_END
};
OSSL_PARAM *fromdata_params = NULL;
int bits = 0, security_bits = 0, size = 0;
OSSL_PARAM *orig_fromdata_params = NULL;
switch (tst & 3) {
case X25519_IDX:
fromdata_params = x25519_fromdata_params;
bits = X25519_BITS;
security_bits = X25519_SECURITY_BITS;
size = X25519_KEYLEN;
alg = "X25519";
break;
case X448_IDX:
fromdata_params = x448_fromdata_params;
bits = X448_BITS;
security_bits = X448_SECURITY_BITS;
size = X448_KEYLEN;
alg = "X448";
break;
case ED25519_IDX:
fromdata_params = ed25519_fromdata_params;
bits = ED25519_BITS;
security_bits = ED25519_SECURITY_BITS;
size = ED25519_SIGSIZE;
alg = "ED25519";
break;
case ED448_IDX:
fromdata_params = ed448_fromdata_params;
bits = ED448_BITS;
security_bits = ED448_SECURITY_BITS;
size = ED448_SIGSIZE;
alg = "ED448";
break;
default:
goto err;
}
ctx = EVP_PKEY_CTX_new_from_name(NULL, alg, NULL);
if (!TEST_ptr(ctx))
goto err;
orig_fromdata_params = fromdata_params;
if (tst > 7) {
/* public key only */
fromdata_params++;
} else if (tst > 3) {
/* private key only */
params[0] = fromdata_params[0];
params[1] = fromdata_params[2];
fromdata_params = params;
}
if (!TEST_int_eq(EVP_PKEY_fromdata_init(ctx), 1)
|| !TEST_int_eq(EVP_PKEY_fromdata(ctx, &pk, EVP_PKEY_KEYPAIR,
fromdata_params), 1))
goto err;
- while (dup_pk == NULL) {
+ for (;;) {
ret = 0;
if (!TEST_int_eq(EVP_PKEY_get_bits(pk), bits)
|| !TEST_int_eq(EVP_PKEY_get_security_bits(pk), security_bits)
|| !TEST_int_eq(EVP_PKEY_get_size(pk), size)
|| !TEST_false(EVP_PKEY_missing_parameters(pk)))
goto err;
if (!TEST_ptr(ctx2 = EVP_PKEY_CTX_new_from_pkey(NULL, pk, NULL)))
goto err;
if (tst <= 7) {
if (!TEST_int_gt(EVP_PKEY_check(ctx2), 0))
goto err;
if (!TEST_true(EVP_PKEY_get_octet_string_param(
pk, orig_fromdata_params[PRIV_KEY].key,
out_priv, sizeof(out_priv), &len))
|| !TEST_mem_eq(out_priv, len,
orig_fromdata_params[PRIV_KEY].data,
orig_fromdata_params[PRIV_KEY].data_size)
|| !TEST_true(EVP_PKEY_get_octet_string_param(
pk, orig_fromdata_params[PUB_KEY].key,
out_pub, sizeof(out_pub), &len))
|| !TEST_mem_eq(out_pub, len,
orig_fromdata_params[PUB_KEY].data,
orig_fromdata_params[PUB_KEY].data_size))
goto err;
} else {
/* The private key check should fail if there is only a public key */
if (!TEST_int_gt(EVP_PKEY_public_check(ctx2), 0)
|| !TEST_int_le(EVP_PKEY_private_check(ctx2), 0)
|| !TEST_int_le(EVP_PKEY_check(ctx2), 0))
goto err;
}
EVP_PKEY_CTX_free(ctx2);
ctx2 = NULL;
if (!TEST_ptr(copy_pk = EVP_PKEY_new())
/* This should succeed because there are no parameters to copy */
|| !TEST_true(EVP_PKEY_copy_parameters(copy_pk, pk)))
goto err;
if (!TEST_ptr(ctx2 = EVP_PKEY_CTX_new_from_pkey(NULL, copy_pk, NULL))
/* This should fail because copy_pk has no pubkey */
|| !TEST_int_le(EVP_PKEY_public_check(ctx2), 0))
goto err;
EVP_PKEY_CTX_free(ctx2);
ctx2 = NULL;
EVP_PKEY_free(copy_pk);
copy_pk = NULL;
if (tst > 7)
ret = test_print_key_using_encoder_public(alg, pk);
else
ret = test_print_key_using_pem(alg, pk)
&& test_print_key_using_encoder(alg, pk);
- if (!ret || !TEST_ptr(dup_pk = EVP_PKEY_dup(pk)))
+ if (!ret || dup_pk != NULL)
+ break;
+
+ if (!TEST_ptr(dup_pk = EVP_PKEY_dup(pk)))
goto err;
ret = ret && TEST_int_eq(EVP_PKEY_eq(pk, dup_pk), 1);
EVP_PKEY_free(pk);
pk = dup_pk;
if (!ret)
goto err;
}
err:
EVP_PKEY_free(pk);
EVP_PKEY_free(copy_pk);
EVP_PKEY_CTX_free(ctx);
EVP_PKEY_CTX_free(ctx2);
return ret;
}
static int test_fromdata_ec(void)
{
int ret = 0;
EVP_PKEY_CTX *ctx = NULL;
EVP_PKEY *pk = NULL, *copy_pk = NULL, *dup_pk = NULL;
OSSL_PARAM_BLD *bld = NULL;
BIGNUM *ec_priv_bn = NULL;
BIGNUM *bn_priv = NULL;
OSSL_PARAM *fromdata_params = NULL;
const char *alg = "EC";
const char *curve = "prime256v1";
const char bad_curve[] = "nonexistent-curve";
OSSL_PARAM nokey_params[2] = {
OSSL_PARAM_END,
OSSL_PARAM_END
};
/* UNCOMPRESSED FORMAT */
static const unsigned char ec_pub_keydata[] = {
POINT_CONVERSION_UNCOMPRESSED,
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
};
/* SAME BUT COMPRESSED FORMAT */
static const unsigned char ec_pub_keydata_compressed[] = {
POINT_CONVERSION_COMPRESSED+1,
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
};
static const unsigned char ec_priv_keydata[] = {
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
};
unsigned char out_pub[sizeof(ec_pub_keydata)];
char out_curve_name[80];
const OSSL_PARAM *gettable = NULL;
size_t len;
EC_GROUP *group = NULL;
BIGNUM *group_a = NULL;
BIGNUM *group_b = NULL;
BIGNUM *group_p = NULL;
BIGNUM *a = NULL;
BIGNUM *b = NULL;
BIGNUM *p = NULL;
if (!TEST_ptr(bld = OSSL_PARAM_BLD_new()))
goto err;
if (!TEST_ptr(ec_priv_bn = BN_bin2bn(ec_priv_keydata,
sizeof(ec_priv_keydata), NULL)))
goto err;
if (OSSL_PARAM_BLD_push_utf8_string(bld, OSSL_PKEY_PARAM_GROUP_NAME,
curve, 0) <= 0)
goto err;
/*
* We intentionally provide the input point in compressed format,
* and avoid setting `OSSL_PKEY_PARAM_EC_POINT_CONVERSION_FORMAT`.
*
* Later on we check what format is used when exporting the
* `OSSL_PKEY_PARAM_PUB_KEY` and expect to default to uncompressed
* format.
*/
if (OSSL_PARAM_BLD_push_octet_string(bld, OSSL_PKEY_PARAM_PUB_KEY,
ec_pub_keydata_compressed,
sizeof(ec_pub_keydata_compressed)) <= 0)
goto err;
if (OSSL_PARAM_BLD_push_BN(bld, OSSL_PKEY_PARAM_PRIV_KEY, ec_priv_bn) <= 0)
goto err;
if (!TEST_ptr(fromdata_params = OSSL_PARAM_BLD_to_param(bld)))
goto err;
ctx = EVP_PKEY_CTX_new_from_name(NULL, alg, NULL);
if (!TEST_ptr(ctx))
goto err;
/* try importing parameters with bad curve first */
nokey_params[0] =
OSSL_PARAM_construct_utf8_string(OSSL_PKEY_PARAM_GROUP_NAME,
(char *)bad_curve, sizeof(bad_curve));
if (!TEST_int_eq(EVP_PKEY_fromdata_init(ctx), 1)
|| !TEST_int_eq(EVP_PKEY_fromdata(ctx, &pk, EVP_PKEY_KEY_PARAMETERS,
nokey_params), 0)
|| !TEST_ptr_null(pk))
goto err;
if (!TEST_int_eq(EVP_PKEY_fromdata_init(ctx), 1)
|| !TEST_int_eq(EVP_PKEY_fromdata(ctx, &pk, EVP_PKEY_KEYPAIR,
fromdata_params), 1))
goto err;
- while (dup_pk == NULL) {
+ for (;;) {
ret = 0;
if (!TEST_int_eq(EVP_PKEY_get_bits(pk), 256)
|| !TEST_int_eq(EVP_PKEY_get_security_bits(pk), 128)
|| !TEST_int_eq(EVP_PKEY_get_size(pk), 2 + 35 * 2)
|| !TEST_false(EVP_PKEY_missing_parameters(pk)))
goto err;
if (!TEST_ptr(copy_pk = EVP_PKEY_new())
|| !TEST_true(EVP_PKEY_copy_parameters(copy_pk, pk)))
goto err;
EVP_PKEY_free(copy_pk);
copy_pk = NULL;
if (!TEST_ptr(gettable = EVP_PKEY_gettable_params(pk))
|| !TEST_ptr(OSSL_PARAM_locate_const(gettable,
OSSL_PKEY_PARAM_GROUP_NAME))
|| !TEST_ptr(OSSL_PARAM_locate_const(gettable,
OSSL_PKEY_PARAM_PUB_KEY))
|| !TEST_ptr(OSSL_PARAM_locate_const(gettable,
OSSL_PKEY_PARAM_PRIV_KEY)))
goto err;
if (!TEST_ptr(group = EC_GROUP_new_by_curve_name(OBJ_sn2nid(curve)))
|| !TEST_ptr(group_p = BN_new())
|| !TEST_ptr(group_a = BN_new())
|| !TEST_ptr(group_b = BN_new())
|| !TEST_true(EC_GROUP_get_curve(group, group_p, group_a, group_b, NULL)))
goto err;
if (!TEST_true(EVP_PKEY_get_bn_param(pk, OSSL_PKEY_PARAM_EC_A, &a))
|| !TEST_true(EVP_PKEY_get_bn_param(pk, OSSL_PKEY_PARAM_EC_B, &b))
|| !TEST_true(EVP_PKEY_get_bn_param(pk, OSSL_PKEY_PARAM_EC_P, &p)))
goto err;
if (!TEST_BN_eq(group_p, p) || !TEST_BN_eq(group_a, a)
|| !TEST_BN_eq(group_b, b))
goto err;
+ EC_GROUP_free(group);
+ group = NULL;
+ BN_free(group_p);
+ group_p = NULL;
+ BN_free(group_a);
+ group_a = NULL;
+ BN_free(group_b);
+ group_b = NULL;
+
if (!EVP_PKEY_get_utf8_string_param(pk, OSSL_PKEY_PARAM_GROUP_NAME,
out_curve_name,
sizeof(out_curve_name),
&len)
|| !TEST_str_eq(out_curve_name, curve)
|| !EVP_PKEY_get_octet_string_param(pk, OSSL_PKEY_PARAM_PUB_KEY,
out_pub, sizeof(out_pub), &len)
/*
* Our providers use uncompressed format by default if
* `OSSL_PKEY_PARAM_EC_POINT_CONVERSION_FORMAT` was not
* explicitly set, irrespective of the format used for the
* input point given as a param to create this key.
*/
|| !TEST_true(out_pub[0] == POINT_CONVERSION_UNCOMPRESSED)
|| !TEST_mem_eq(out_pub + 1, len - 1,
ec_pub_keydata + 1, sizeof(ec_pub_keydata) - 1)
|| !TEST_true(EVP_PKEY_get_bn_param(pk, OSSL_PKEY_PARAM_PRIV_KEY,
&bn_priv))
|| !TEST_BN_eq(ec_priv_bn, bn_priv))
goto err;
BN_free(bn_priv);
bn_priv = NULL;
ret = test_print_key_using_pem(alg, pk)
&& test_print_key_using_encoder(alg, pk);
- if (!ret || !TEST_ptr(dup_pk = EVP_PKEY_dup(pk)))
+ if (!ret || dup_pk != NULL)
+ break;
+
+ if (!TEST_ptr(dup_pk = EVP_PKEY_dup(pk)))
goto err;
ret = ret && TEST_int_eq(EVP_PKEY_eq(pk, dup_pk), 1);
EVP_PKEY_free(pk);
pk = dup_pk;
if (!ret)
goto err;
}
err:
EC_GROUP_free(group);
BN_free(group_a);
BN_free(group_b);
BN_free(group_p);
BN_free(a);
BN_free(b);
BN_free(p);
BN_free(bn_priv);
BN_free(ec_priv_bn);
OSSL_PARAM_free(fromdata_params);
OSSL_PARAM_BLD_free(bld);
EVP_PKEY_free(pk);
EVP_PKEY_free(copy_pk);
EVP_PKEY_CTX_free(ctx);
return ret;
}
static int test_ec_dup_no_operation(void)
{
int ret = 0;
EVP_PKEY_CTX *pctx = NULL, *ctx = NULL, *kctx = NULL;
EVP_PKEY *param = NULL, *pkey = NULL;
if (!TEST_ptr(pctx = EVP_PKEY_CTX_new_id(EVP_PKEY_EC, NULL))
|| !TEST_int_gt(EVP_PKEY_paramgen_init(pctx), 0)
|| !TEST_int_gt(EVP_PKEY_CTX_set_ec_paramgen_curve_nid(pctx,
NID_X9_62_prime256v1), 0)
|| !TEST_int_gt(EVP_PKEY_paramgen(pctx, &param), 0)
|| !TEST_ptr(param))
goto err;
EVP_PKEY_CTX_free(pctx);
pctx = NULL;
if (!TEST_ptr(ctx = EVP_PKEY_CTX_new_from_pkey(NULL, param, NULL))
|| !TEST_ptr(kctx = EVP_PKEY_CTX_dup(ctx))
|| !TEST_int_gt(EVP_PKEY_keygen_init(kctx), 0)
|| !TEST_int_gt(EVP_PKEY_keygen(kctx, &pkey), 0))
goto err;
ret = 1;
err:
EVP_PKEY_free(pkey);
EVP_PKEY_free(param);
EVP_PKEY_CTX_free(ctx);
EVP_PKEY_CTX_free(kctx);
EVP_PKEY_CTX_free(pctx);
return ret;
}
/* Test that keygen doesn't support EVP_PKEY_CTX_dup */
static int test_ec_dup_keygen_operation(void)
{
int ret = 0;
EVP_PKEY_CTX *pctx = NULL, *ctx = NULL, *kctx = NULL;
EVP_PKEY *param = NULL, *pkey = NULL;
if (!TEST_ptr(pctx = EVP_PKEY_CTX_new_id(EVP_PKEY_EC, NULL))
|| !TEST_int_gt(EVP_PKEY_paramgen_init(pctx), 0)
|| !TEST_int_gt(EVP_PKEY_CTX_set_ec_paramgen_curve_nid(pctx,
NID_X9_62_prime256v1), 0)
|| !TEST_int_gt(EVP_PKEY_paramgen(pctx, &param), 0)
|| !TEST_ptr(param))
goto err;
EVP_PKEY_CTX_free(pctx);
pctx = NULL;
if (!TEST_ptr(ctx = EVP_PKEY_CTX_new_from_pkey(NULL, param, NULL))
|| !TEST_int_gt(EVP_PKEY_keygen_init(ctx), 0)
|| !TEST_ptr_null(kctx = EVP_PKEY_CTX_dup(ctx)))
goto err;
ret = 1;
err:
EVP_PKEY_free(pkey);
EVP_PKEY_free(param);
EVP_PKEY_CTX_free(ctx);
EVP_PKEY_CTX_free(kctx);
EVP_PKEY_CTX_free(pctx);
return ret;
}
#endif /* OPENSSL_NO_EC */
#ifndef OPENSSL_NO_DSA
static int test_fromdata_dsa_fips186_4(void)
{
int ret = 0;
EVP_PKEY_CTX *ctx = NULL, *key_ctx = NULL;
EVP_PKEY *pk = NULL, *copy_pk = NULL, *dup_pk = NULL;
BIGNUM *pub = NULL, *priv = NULL;
BIGNUM *p = NULL, *q = NULL, *g = NULL;
BIGNUM *pub_out = NULL, *priv_out = NULL;
BIGNUM *p_out = NULL, *q_out = NULL, *g_out = NULL, *j_out = NULL;
int gindex_out = 0, pcounter_out = 0, hindex_out = 0;
char name_out[80];
unsigned char seed_out[32];
size_t len;
OSSL_PARAM_BLD *bld = NULL;
OSSL_PARAM *fromdata_params = NULL;
/*
* DSA parameter data was generated using the following:
* openssl genpkey -genparam -algorithm DSA -pkeyopt pbits:2048 \
* -pkeyopt qbits:256 -pkeyopt type:0 \
* -pkeyopt gindex:1 -out dsa_params.pem -text
*/
static const unsigned char p_data[] = {
0x00, 0xa0, 0xb7, 0x02, 0xc4, 0xac, 0xa6, 0x42, 0xab, 0xf2, 0x34, 0x0b,
0x22, 0x47, 0x1f, 0x33, 0xcf, 0xd5, 0x04, 0xe4, 0x3e, 0xec, 0xa1, 0x21,
0xc8, 0x41, 0x2b, 0xef, 0xb8, 0x1f, 0x0b, 0x5b, 0x88, 0x8b, 0x67, 0xf8,
0x68, 0x6d, 0x7c, 0x4d, 0x96, 0x5f, 0x3c, 0x66, 0xef, 0x58, 0x34, 0xd7,
0xf6, 0xa2, 0x1b, 0xad, 0xc8, 0x12, 0x52, 0xb8, 0xe8, 0x2a, 0x63, 0xcc,
0xea, 0xe7, 0x4e, 0xc8, 0x34, 0x4c, 0x58, 0x59, 0x0a, 0xc2, 0x4a, 0xe4,
0xb4, 0x64, 0x20, 0xf4, 0xf6, 0x0a, 0xcf, 0x86, 0x01, 0x6c, 0x7f, 0x23,
0x4a, 0x51, 0x07, 0x99, 0x42, 0x28, 0x7a, 0xff, 0x18, 0x67, 0x52, 0x64,
0xf2, 0x9a, 0x62, 0x30, 0xc3, 0x00, 0xde, 0x23, 0xe9, 0x11, 0x95, 0x7e,
0xd1, 0x3d, 0x8d, 0xb4, 0x0e, 0x9f, 0x9e, 0xb1, 0x30, 0x03, 0xf0, 0x73,
0xa8, 0x40, 0x48, 0x42, 0x7b, 0x60, 0xa0, 0xc4, 0xf2, 0x3b, 0x2d, 0x0a,
0x0c, 0xb8, 0x19, 0xfb, 0xb4, 0xf8, 0xe0, 0x2a, 0xc7, 0xf1, 0xc0, 0xc6,
0x86, 0x14, 0x60, 0x12, 0x0f, 0xc0, 0xde, 0x4a, 0x67, 0xec, 0xc7, 0xde,
0x76, 0x21, 0x1a, 0x55, 0x7f, 0x86, 0xc3, 0x97, 0x98, 0xce, 0xf5, 0xcd,
0xf0, 0xe7, 0x12, 0xd6, 0x93, 0xee, 0x1b, 0x9b, 0x61, 0xef, 0x05, 0x8c,
0x45, 0x46, 0xd9, 0x64, 0x6f, 0xbe, 0x27, 0xaa, 0x67, 0x01, 0xcc, 0x71,
0xb1, 0x60, 0xce, 0x21, 0xd8, 0x51, 0x17, 0x27, 0x0d, 0x90, 0x3d, 0x18,
0x7c, 0x87, 0x15, 0x8e, 0x48, 0x4c, 0x6c, 0xc5, 0x72, 0xeb, 0xb7, 0x56,
0xf5, 0x6b, 0x60, 0x8f, 0xc2, 0xfd, 0x3f, 0x46, 0x5c, 0x00, 0x91, 0x85,
0x79, 0x45, 0x5b, 0x1c, 0x82, 0xc4, 0x87, 0x50, 0x79, 0xba, 0xcc, 0x1c,
0x32, 0x7e, 0x2e, 0xb8, 0x2e, 0xc5, 0x4e, 0xd1, 0x9b, 0xdb, 0x66, 0x79,
0x7c, 0xfe, 0xaf, 0x6a, 0x05
};
static const unsigned char q_data[] = {
0xa8, 0xcd, 0xf4, 0x33, 0x7b, 0x13, 0x0a, 0x24, 0xc1, 0xde, 0x4a, 0x04,
0x7b, 0x4b, 0x71, 0x51, 0x32, 0xe9, 0x47, 0x74, 0xbd, 0x0c, 0x21, 0x40,
0x84, 0x12, 0x0a, 0x17, 0x73, 0xdb, 0x29, 0xc7
};
static const unsigned char g_data[] = {
0x6c, 0xc6, 0xa4, 0x3e, 0x61, 0x84, 0xc1, 0xff, 0x6f, 0x4a, 0x1a, 0x6b,
0xb0, 0x24, 0x4b, 0xd2, 0x92, 0x5b, 0x29, 0x5c, 0x61, 0xb8, 0xc9, 0x2b,
0xd6, 0xf7, 0x59, 0xfd, 0xd8, 0x70, 0x66, 0x77, 0xfc, 0xc1, 0xa4, 0xd4,
0xb0, 0x1e, 0xd5, 0xbf, 0x59, 0x98, 0xb3, 0x66, 0x8b, 0xf4, 0x2e, 0xe6,
0x12, 0x3e, 0xcc, 0xf8, 0x02, 0xb8, 0xc6, 0xc3, 0x47, 0xd2, 0xf5, 0xaa,
0x0c, 0x5f, 0x51, 0xf5, 0xd0, 0x4c, 0x55, 0x3d, 0x07, 0x73, 0xa6, 0x57,
0xce, 0x5a, 0xad, 0x42, 0x0c, 0x13, 0x0f, 0xe2, 0x31, 0x25, 0x8e, 0x72,
0x12, 0x73, 0x10, 0xdb, 0x7f, 0x79, 0xeb, 0x59, 0xfc, 0xfe, 0xf7, 0x0c,
0x1a, 0x81, 0x53, 0x96, 0x22, 0xb8, 0xe7, 0x58, 0xd8, 0x67, 0x80, 0x60,
0xad, 0x8b, 0x55, 0x1c, 0x91, 0xf0, 0x72, 0x9a, 0x7e, 0xad, 0x37, 0xf1,
0x77, 0x18, 0x96, 0x8a, 0x68, 0x70, 0xfc, 0x71, 0xa9, 0xa2, 0xe8, 0x35,
0x27, 0x78, 0xf2, 0xef, 0x59, 0x36, 0x6d, 0x7c, 0xb6, 0x98, 0xd8, 0x1e,
0xfa, 0x25, 0x73, 0x97, 0x45, 0x58, 0xe3, 0xae, 0xbd, 0x52, 0x54, 0x05,
0xd8, 0x26, 0x26, 0xba, 0xba, 0x05, 0xb5, 0xe9, 0xe5, 0x76, 0xae, 0x25,
0xdd, 0xfc, 0x10, 0x89, 0x5a, 0xa9, 0xee, 0x59, 0xc5, 0x79, 0x8b, 0xeb,
0x1e, 0x2c, 0x61, 0xab, 0x0d, 0xd1, 0x10, 0x04, 0x91, 0x32, 0x77, 0x4a,
0xa6, 0x64, 0x53, 0xda, 0x4c, 0xd7, 0x3a, 0x29, 0xd4, 0xf3, 0x82, 0x25,
0x1d, 0x6f, 0x4a, 0x7f, 0xd3, 0x08, 0x3b, 0x42, 0x30, 0x10, 0xd8, 0xd0,
0x97, 0x3a, 0xeb, 0x92, 0x63, 0xec, 0x93, 0x2b, 0x6f, 0x32, 0xd8, 0xcd,
0x80, 0xd3, 0xc0, 0x4c, 0x03, 0xd5, 0xca, 0xbc, 0x8f, 0xc7, 0x43, 0x53,
0x64, 0x66, 0x1c, 0x82, 0x2d, 0xfb, 0xff, 0x39, 0xba, 0xd6, 0x42, 0x62,
0x02, 0x6f, 0x96, 0x36
};
static const unsigned char seed_data[] = {
0x64, 0x46, 0x07, 0x32, 0x8d, 0x70, 0x9c, 0xb3, 0x8a, 0x35, 0xde, 0x62,
0x00, 0xf2, 0x6d, 0x52, 0x37, 0x4d, 0xb3, 0x84, 0xe1, 0x9d, 0x41, 0x04,
0xda, 0x7b, 0xdc, 0x0d, 0x8b, 0x5e, 0xe0, 0x84
};
const int gindex = 1;
const int pcounter = 53;
/*
* The keypair was generated using
* openssl genpkey -paramfile dsa_params.pem --pkeyopt pcounter:53 \
* -pkeyopt gindex:1 \
* -pkeyopt hexseed:644607328d709cb38a35de6200f26d -text
*/
static const unsigned char priv_data[] = {
0x00, 0x8f, 0xc5, 0x9e, 0xd0, 0xf7, 0x2a, 0x0b, 0x66, 0xf1, 0x32, 0x73,
0xae, 0xf6, 0xd9, 0xd4, 0xdb, 0x2d, 0x96, 0x55, 0x89, 0xff, 0xef, 0xa8,
0x5f, 0x47, 0x8f, 0xca, 0x02, 0x8a, 0xe1, 0x35, 0x90
};
static const unsigned char pub_data[] = {
0x44, 0x19, 0xc9, 0x46, 0x45, 0x57, 0xc1, 0xa9, 0xd8, 0x30, 0x99, 0x29,
0x6a, 0x4b, 0x63, 0x71, 0x69, 0x96, 0x35, 0x17, 0xb2, 0x62, 0x9b, 0x80,
0x0a, 0x95, 0x9d, 0x6a, 0xc0, 0x32, 0x0d, 0x07, 0x5f, 0x19, 0x44, 0x02,
0xf1, 0xbd, 0xce, 0xdf, 0x10, 0xf8, 0x02, 0x5d, 0x7d, 0x98, 0x8a, 0x73,
0x89, 0x00, 0xb6, 0x24, 0xd6, 0x33, 0xe7, 0xcf, 0x8b, 0x49, 0x2a, 0xaf,
0x13, 0x1c, 0xb2, 0x52, 0x15, 0xfd, 0x9b, 0xd5, 0x40, 0x4a, 0x1a, 0xda,
0x29, 0x4c, 0x92, 0x7e, 0x66, 0x06, 0xdb, 0x61, 0x86, 0xac, 0xb5, 0xda,
0x3c, 0x7d, 0x73, 0x7e, 0x54, 0x32, 0x68, 0xa5, 0x02, 0xbc, 0x59, 0x47,
0x84, 0xd3, 0x87, 0x71, 0x5f, 0xeb, 0x43, 0x45, 0x24, 0xd3, 0xec, 0x08,
0x52, 0xc2, 0x89, 0x2d, 0x9c, 0x1a, 0xcc, 0x91, 0x65, 0x5d, 0xa3, 0xa1,
0x35, 0x31, 0x10, 0x1c, 0x3a, 0xa8, 0x4d, 0x18, 0xd5, 0x06, 0xaf, 0xb2,
0xec, 0x5c, 0x89, 0x9e, 0x90, 0x86, 0x10, 0x01, 0xeb, 0x51, 0xd5, 0x1b,
0x9c, 0xcb, 0x66, 0x07, 0x3f, 0xc4, 0x6e, 0x0a, 0x1b, 0x73, 0xa0, 0x4b,
0x5f, 0x4d, 0xab, 0x35, 0x28, 0xfa, 0xda, 0x3a, 0x0c, 0x08, 0xe8, 0xf3,
0xef, 0x42, 0x67, 0xbc, 0x21, 0xf2, 0xc2, 0xb8, 0xff, 0x1a, 0x81, 0x05,
0x68, 0x73, 0x62, 0xdf, 0xd7, 0xab, 0x0f, 0x22, 0x89, 0x57, 0x96, 0xd4,
0x93, 0xaf, 0xa1, 0x21, 0xa3, 0x48, 0xe9, 0xf0, 0x97, 0x47, 0xa0, 0x27,
0xba, 0x87, 0xb8, 0x15, 0x5f, 0xff, 0x2c, 0x50, 0x41, 0xf1, 0x7e, 0xc6,
0x81, 0xc4, 0x51, 0xf1, 0xfd, 0xd6, 0x86, 0xf7, 0x69, 0x97, 0xf1, 0x49,
0xc9, 0xf9, 0xf4, 0x9b, 0xf4, 0xe8, 0x85, 0xa7, 0xbd, 0x36, 0x55, 0x4a,
0x3d, 0xe8, 0x65, 0x09, 0x7b, 0xb7, 0x12, 0x64, 0xd2, 0x0a, 0x53, 0x60,
0x48, 0xd1, 0x8a, 0xbd
};
if (!TEST_ptr(bld = OSSL_PARAM_BLD_new())
|| !TEST_ptr(pub = BN_bin2bn(pub_data, sizeof(pub_data), NULL))
|| !TEST_ptr(priv = BN_bin2bn(priv_data, sizeof(priv_data), NULL))
|| !TEST_ptr(p = BN_bin2bn(p_data, sizeof(p_data), NULL))
|| !TEST_ptr(q = BN_bin2bn(q_data, sizeof(q_data), NULL))
|| !TEST_ptr(g = BN_bin2bn(g_data, sizeof(g_data), NULL))
|| !TEST_true(OSSL_PARAM_BLD_push_BN(bld, OSSL_PKEY_PARAM_FFC_P, p))
|| !TEST_true(OSSL_PARAM_BLD_push_BN(bld, OSSL_PKEY_PARAM_FFC_Q, q))
|| !TEST_true(OSSL_PARAM_BLD_push_BN(bld, OSSL_PKEY_PARAM_FFC_G, g))
|| !TEST_true(OSSL_PARAM_BLD_push_octet_string(bld,
OSSL_PKEY_PARAM_FFC_SEED,
seed_data,
sizeof(seed_data)))
|| !TEST_true(OSSL_PARAM_BLD_push_int(bld, OSSL_PKEY_PARAM_FFC_GINDEX,
gindex))
|| !TEST_true(OSSL_PARAM_BLD_push_int(bld,
OSSL_PKEY_PARAM_FFC_PCOUNTER,
pcounter))
|| !TEST_true(OSSL_PARAM_BLD_push_BN(bld, OSSL_PKEY_PARAM_PUB_KEY,
pub))
|| !TEST_true(OSSL_PARAM_BLD_push_BN(bld, OSSL_PKEY_PARAM_PRIV_KEY,
priv))
|| !TEST_ptr(fromdata_params = OSSL_PARAM_BLD_to_param(bld)))
goto err;
if (!TEST_ptr(ctx = EVP_PKEY_CTX_new_from_name(NULL, "DSA", NULL)))
goto err;
if (!TEST_int_eq(EVP_PKEY_fromdata_init(ctx), 1)
|| !TEST_int_eq(EVP_PKEY_fromdata(ctx, &pk, EVP_PKEY_KEYPAIR,
fromdata_params), 1))
goto err;
- while (dup_pk == NULL) {
+ for (;;) {
ret = 0;
if (!TEST_int_eq(EVP_PKEY_get_bits(pk), 2048)
|| !TEST_int_eq(EVP_PKEY_get_security_bits(pk), 112)
|| !TEST_int_eq(EVP_PKEY_get_size(pk), 2 + 2 * (3 + sizeof(q_data)))
|| !TEST_false(EVP_PKEY_missing_parameters(pk)))
goto err;
if (!TEST_false(EVP_PKEY_get_utf8_string_param(pk,
OSSL_PKEY_PARAM_GROUP_NAME,
name_out,
sizeof(name_out),
&len))
|| !TEST_true(EVP_PKEY_get_bn_param(pk, OSSL_PKEY_PARAM_PUB_KEY,
&pub_out))
|| !TEST_BN_eq(pub, pub_out)
|| !TEST_true(EVP_PKEY_get_bn_param(pk, OSSL_PKEY_PARAM_PRIV_KEY,
&priv_out))
|| !TEST_BN_eq(priv, priv_out)
|| !TEST_true(EVP_PKEY_get_bn_param(pk, OSSL_PKEY_PARAM_FFC_P,
&p_out))
|| !TEST_BN_eq(p, p_out)
|| !TEST_true(EVP_PKEY_get_bn_param(pk, OSSL_PKEY_PARAM_FFC_Q,
&q_out))
|| !TEST_BN_eq(q, q_out)
|| !TEST_true(EVP_PKEY_get_bn_param(pk, OSSL_PKEY_PARAM_FFC_G,
&g_out))
|| !TEST_BN_eq(g, g_out)
|| !TEST_false(EVP_PKEY_get_bn_param(pk,
OSSL_PKEY_PARAM_FFC_COFACTOR,
&j_out))
|| !TEST_ptr_null(j_out)
|| !TEST_true(EVP_PKEY_get_octet_string_param(pk,
OSSL_PKEY_PARAM_FFC_SEED,
seed_out,
sizeof(seed_out),
&len))
|| !TEST_true(EVP_PKEY_get_int_param(pk,
OSSL_PKEY_PARAM_FFC_GINDEX,
&gindex_out))
|| !TEST_int_eq(gindex, gindex_out)
|| !TEST_true(EVP_PKEY_get_int_param(pk, OSSL_PKEY_PARAM_FFC_H,
&hindex_out))
|| !TEST_int_eq(hindex_out, 0)
|| !TEST_true(EVP_PKEY_get_int_param(pk,
OSSL_PKEY_PARAM_FFC_PCOUNTER,
&pcounter_out))
|| !TEST_int_eq(pcounter, pcounter_out))
goto err;
- BN_free(p);
- p = NULL;
- BN_free(q);
- q = NULL;
- BN_free(g);
- g = NULL;
+ BN_free(p_out);
+ p_out = NULL;
+ BN_free(q_out);
+ q_out = NULL;
+ BN_free(g_out);
+ g_out = NULL;
BN_free(j_out);
j_out = NULL;
BN_free(pub_out);
pub_out = NULL;
BN_free(priv_out);
priv_out = NULL;
if (!TEST_ptr(key_ctx = EVP_PKEY_CTX_new_from_pkey(NULL, pk, "")))
goto err;
if (!TEST_int_gt(EVP_PKEY_check(key_ctx), 0)
|| !TEST_int_gt(EVP_PKEY_public_check(key_ctx), 0)
|| !TEST_int_gt(EVP_PKEY_private_check(key_ctx), 0)
|| !TEST_int_gt(EVP_PKEY_pairwise_check(key_ctx), 0))
goto err;
EVP_PKEY_CTX_free(key_ctx);
key_ctx = NULL;
if (!TEST_ptr(copy_pk = EVP_PKEY_new())
|| !TEST_true(EVP_PKEY_copy_parameters(copy_pk, pk)))
goto err;
EVP_PKEY_free(copy_pk);
copy_pk = NULL;
ret = test_print_key_using_pem("DSA", pk)
&& test_print_key_using_encoder("DSA", pk);
- if (!ret || !TEST_ptr(dup_pk = EVP_PKEY_dup(pk)))
+ if (!ret || dup_pk != NULL)
+ break;
+
+ if (!TEST_ptr(dup_pk = EVP_PKEY_dup(pk)))
goto err;
ret = ret && TEST_int_eq(EVP_PKEY_eq(pk, dup_pk), 1);
EVP_PKEY_free(pk);
pk = dup_pk;
if (!ret)
goto err;
}
err:
OSSL_PARAM_free(fromdata_params);
OSSL_PARAM_BLD_free(bld);
BN_free(p);
BN_free(q);
BN_free(g);
BN_free(pub);
BN_free(priv);
BN_free(p_out);
BN_free(q_out);
BN_free(g_out);
BN_free(pub_out);
BN_free(priv_out);
BN_free(j_out);
EVP_PKEY_free(pk);
EVP_PKEY_free(copy_pk);
EVP_PKEY_CTX_free(ctx);
EVP_PKEY_CTX_free(key_ctx);
return ret;
}
static int test_check_dsa(void)
{
int ret = 0;
EVP_PKEY_CTX *ctx = NULL;
if (!TEST_ptr(ctx = EVP_PKEY_CTX_new_from_name(NULL, "DSA", NULL))
|| !TEST_int_le(EVP_PKEY_check(ctx), 0)
|| !TEST_int_le(EVP_PKEY_public_check(ctx), 0)
|| !TEST_int_le(EVP_PKEY_private_check(ctx), 0)
|| !TEST_int_le(EVP_PKEY_pairwise_check(ctx), 0))
goto err;
ret = 1;
err:
EVP_PKEY_CTX_free(ctx);
return ret;
}
#endif /* OPENSSL_NO_DSA */
static OSSL_PARAM *do_construct_hkdf_params(char *digest, char *key,
size_t keylen, char *salt)
{
OSSL_PARAM *params = OPENSSL_malloc(sizeof(OSSL_PARAM) * 5);
OSSL_PARAM *p = params;
*p++ = OSSL_PARAM_construct_utf8_string(OSSL_KDF_PARAM_DIGEST, digest, 0);
*p++ = OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_SALT,
salt, strlen(salt));
*p++ = OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_KEY,
(unsigned char *)key, keylen);
*p++ = OSSL_PARAM_construct_utf8_string(OSSL_KDF_PARAM_MODE,
"EXTRACT_ONLY", 0);
*p = OSSL_PARAM_construct_end();
return params;
}
/* Test that EVP_PKEY_CTX_dup() fails gracefully for a KDF */
static int test_evp_pkey_ctx_dup_kdf_fail(void)
{
int ret = 0;
size_t len = 0;
EVP_PKEY_CTX *pctx = NULL, *dctx = NULL;
OSSL_PARAM *params = NULL;
if (!TEST_ptr(params = do_construct_hkdf_params("sha256", "secret", 6,
"salt")))
goto err;
if (!TEST_ptr(pctx = EVP_PKEY_CTX_new_from_name(NULL, "HKDF", NULL)))
goto err;
if (!TEST_int_eq(EVP_PKEY_derive_init_ex(pctx, params), 1))
goto err;
if (!TEST_int_eq(EVP_PKEY_derive(pctx, NULL, &len), 1)
|| !TEST_size_t_eq(len, SHA256_DIGEST_LENGTH))
goto err;
if (!TEST_ptr_null(dctx = EVP_PKEY_CTX_dup(pctx)))
goto err;
ret = 1;
err:
OPENSSL_free(params);
EVP_PKEY_CTX_free(dctx);
EVP_PKEY_CTX_free(pctx);
return ret;
}
int setup_tests(void)
{
if (!test_skip_common_options()) {
TEST_error("Error parsing test options\n");
return 0;
}
if (!TEST_ptr(datadir = test_get_argument(0)))
return 0;
ADD_TEST(test_evp_pkey_ctx_dup_kdf_fail);
ADD_TEST(test_evp_pkey_get_bn_param_large);
ADD_TEST(test_fromdata_rsa);
#ifndef OPENSSL_NO_DH
ADD_TEST(test_fromdata_dh_fips186_4);
ADD_TEST(test_fromdata_dh_named_group);
#endif
#ifndef OPENSSL_NO_DSA
ADD_TEST(test_check_dsa);
ADD_TEST(test_fromdata_dsa_fips186_4);
#endif
#ifndef OPENSSL_NO_EC
ADD_ALL_TESTS(test_fromdata_ecx, 4 * 3);
ADD_TEST(test_fromdata_ec);
ADD_TEST(test_ec_dup_no_operation);
ADD_TEST(test_ec_dup_keygen_operation);
#endif
return 1;
}
diff --git a/crypto/openssl/test/evp_test.c b/crypto/openssl/test/evp_test.c
index 782841a69258..2701040dabe7 100644
--- a/crypto/openssl/test/evp_test.c
+++ b/crypto/openssl/test/evp_test.c
@@ -1,4174 +1,4177 @@
/*
* Copyright 2015-2024 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
*/
#define OPENSSL_SUPPRESS_DEPRECATED /* EVP_PKEY_new_CMAC_key */
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <openssl/evp.h>
#include <openssl/pem.h>
#include <openssl/err.h>
#include <openssl/provider.h>
#include <openssl/x509v3.h>
#include <openssl/pkcs12.h>
#include <openssl/kdf.h>
#include <openssl/params.h>
#include <openssl/core_names.h>
#include <openssl/fips_names.h>
#include "internal/numbers.h"
#include "internal/nelem.h"
#include "crypto/evp.h"
#include "testutil.h"
typedef struct evp_test_buffer_st EVP_TEST_BUFFER;
DEFINE_STACK_OF(EVP_TEST_BUFFER)
#define AAD_NUM 4
typedef struct evp_test_method_st EVP_TEST_METHOD;
/* Structure holding test information */
typedef struct evp_test_st {
STANZA s; /* Common test stanza */
char *name;
int skip; /* Current test should be skipped */
const EVP_TEST_METHOD *meth; /* method for this test */
const char *err, *aux_err; /* Error string for test */
char *expected_err; /* Expected error value of test */
char *reason; /* Expected error reason string */
void *data; /* test specific data */
} EVP_TEST;
/* Test method structure */
struct evp_test_method_st {
/* Name of test as it appears in file */
const char *name;
/* Initialise test for "alg" */
int (*init) (EVP_TEST * t, const char *alg);
/* Clean up method */
void (*cleanup) (EVP_TEST * t);
/* Test specific name value pair processing */
int (*parse) (EVP_TEST * t, const char *name, const char *value);
/* Run the test itself */
int (*run_test) (EVP_TEST * t);
};
/* Linked list of named keys. */
typedef struct key_list_st {
char *name;
EVP_PKEY *key;
struct key_list_st *next;
} KEY_LIST;
typedef enum OPTION_choice {
OPT_ERR = -1,
OPT_EOF = 0,
OPT_CONFIG_FILE,
OPT_TEST_ENUM
} OPTION_CHOICE;
static OSSL_PROVIDER *prov_null = NULL;
static OSSL_LIB_CTX *libctx = NULL;
/* List of public and private keys */
static KEY_LIST *private_keys;
static KEY_LIST *public_keys;
static int find_key(EVP_PKEY **ppk, const char *name, KEY_LIST *lst);
static int parse_bin(const char *value, unsigned char **buf, size_t *buflen);
static int is_digest_disabled(const char *name);
static int is_pkey_disabled(const char *name);
static int is_mac_disabled(const char *name);
static int is_cipher_disabled(const char *name);
static int is_kdf_disabled(const char *name);
/*
* Compare two memory regions for equality, returning zero if they differ.
* However, if there is expected to be an error and the actual error
* matches then the memory is expected to be different so handle this
* case without producing unnecessary test framework output.
*/
static int memory_err_compare(EVP_TEST *t, const char *err,
const void *expected, size_t expected_len,
const void *got, size_t got_len)
{
int r;
if (t->expected_err != NULL && strcmp(t->expected_err, err) == 0)
r = !TEST_mem_ne(expected, expected_len, got, got_len);
else
r = TEST_mem_eq(expected, expected_len, got, got_len);
if (!r)
t->err = err;
return r;
}
/*
* Structure used to hold a list of blocks of memory to test
* calls to "update" like functions.
*/
struct evp_test_buffer_st {
unsigned char *buf;
size_t buflen;
size_t count;
int count_set;
};
static void evp_test_buffer_free(EVP_TEST_BUFFER *db)
{
if (db != NULL) {
OPENSSL_free(db->buf);
OPENSSL_free(db);
}
}
/* append buffer to a list */
static int evp_test_buffer_append(const char *value,
STACK_OF(EVP_TEST_BUFFER) **sk)
{
EVP_TEST_BUFFER *db = NULL;
if (!TEST_ptr(db = OPENSSL_malloc(sizeof(*db))))
goto err;
if (!parse_bin(value, &db->buf, &db->buflen))
goto err;
db->count = 1;
db->count_set = 0;
if (*sk == NULL && !TEST_ptr(*sk = sk_EVP_TEST_BUFFER_new_null()))
goto err;
if (!sk_EVP_TEST_BUFFER_push(*sk, db))
goto err;
return 1;
err:
evp_test_buffer_free(db);
return 0;
}
/* replace last buffer in list with copies of itself */
static int evp_test_buffer_ncopy(const char *value,
STACK_OF(EVP_TEST_BUFFER) *sk)
{
EVP_TEST_BUFFER *db;
unsigned char *tbuf, *p;
size_t tbuflen;
int ncopy = atoi(value);
int i;
if (ncopy <= 0)
return 0;
if (sk == NULL || sk_EVP_TEST_BUFFER_num(sk) == 0)
return 0;
db = sk_EVP_TEST_BUFFER_value(sk, sk_EVP_TEST_BUFFER_num(sk) - 1);
tbuflen = db->buflen * ncopy;
if (!TEST_ptr(tbuf = OPENSSL_malloc(tbuflen)))
return 0;
for (i = 0, p = tbuf; i < ncopy; i++, p += db->buflen)
memcpy(p, db->buf, db->buflen);
OPENSSL_free(db->buf);
db->buf = tbuf;
db->buflen = tbuflen;
return 1;
}
/* set repeat count for last buffer in list */
static int evp_test_buffer_set_count(const char *value,
STACK_OF(EVP_TEST_BUFFER) *sk)
{
EVP_TEST_BUFFER *db;
int count = atoi(value);
if (count <= 0)
return 0;
if (sk == NULL || sk_EVP_TEST_BUFFER_num(sk) == 0)
return 0;
db = sk_EVP_TEST_BUFFER_value(sk, sk_EVP_TEST_BUFFER_num(sk) - 1);
if (db->count_set != 0)
return 0;
db->count = (size_t)count;
db->count_set = 1;
return 1;
}
/* call "fn" with each element of the list in turn */
static int evp_test_buffer_do(STACK_OF(EVP_TEST_BUFFER) *sk,
int (*fn)(void *ctx,
const unsigned char *buf,
size_t buflen),
void *ctx)
{
int i;
for (i = 0; i < sk_EVP_TEST_BUFFER_num(sk); i++) {
EVP_TEST_BUFFER *tb = sk_EVP_TEST_BUFFER_value(sk, i);
size_t j;
for (j = 0; j < tb->count; j++) {
if (fn(ctx, tb->buf, tb->buflen) <= 0)
return 0;
}
}
return 1;
}
/*
* Unescape some sequences in string literals (only \n for now).
* Return an allocated buffer, set |out_len|. If |input_len|
* is zero, get an empty buffer but set length to zero.
*/
static unsigned char* unescape(const char *input, size_t input_len,
size_t *out_len)
{
unsigned char *ret, *p;
size_t i;
if (input_len == 0) {
*out_len = 0;
return OPENSSL_zalloc(1);
}
/* Escaping is non-expanding; over-allocate original size for simplicity. */
if (!TEST_ptr(ret = p = OPENSSL_malloc(input_len)))
return NULL;
for (i = 0; i < input_len; i++) {
if (*input == '\\') {
if (i == input_len - 1 || *++input != 'n') {
TEST_error("Bad escape sequence in file");
goto err;
}
*p++ = '\n';
i++;
input++;
} else {
*p++ = *input++;
}
}
*out_len = p - ret;
return ret;
err:
OPENSSL_free(ret);
return NULL;
}
/*
* For a hex string "value" convert to a binary allocated buffer.
* Return 1 on success or 0 on failure.
*/
static int parse_bin(const char *value, unsigned char **buf, size_t *buflen)
{
long len;
/* Check for NULL literal */
if (strcmp(value, "NULL") == 0) {
*buf = NULL;
*buflen = 0;
return 1;
}
/* Check for empty value */
if (*value == '\0') {
/*
* Don't return NULL for zero length buffer. This is needed for
* some tests with empty keys: HMAC_Init_ex() expects a non-NULL key
* buffer even if the key length is 0, in order to detect key reset.
*/
*buf = OPENSSL_malloc(1);
if (*buf == NULL)
return 0;
**buf = 0;
*buflen = 0;
return 1;
}
/* Check for string literal */
if (value[0] == '"') {
size_t vlen = strlen(++value);
if (vlen == 0 || value[vlen - 1] != '"')
return 0;
vlen--;
*buf = unescape(value, vlen, buflen);
return *buf == NULL ? 0 : 1;
}
/* Otherwise assume as hex literal and convert it to binary buffer */
if (!TEST_ptr(*buf = OPENSSL_hexstr2buf(value, &len))) {
TEST_info("Can't convert %s", value);
TEST_openssl_errors();
return -1;
}
/* Size of input buffer means we'll never overflow */
*buflen = len;
return 1;
}
/**
** MESSAGE DIGEST TESTS
**/
typedef struct digest_data_st {
/* Digest this test is for */
const EVP_MD *digest;
EVP_MD *fetched_digest;
/* Input to digest */
STACK_OF(EVP_TEST_BUFFER) *input;
/* Expected output */
unsigned char *output;
size_t output_len;
/* Padding type */
int pad_type;
} DIGEST_DATA;
static int digest_test_init(EVP_TEST *t, const char *alg)
{
DIGEST_DATA *mdat;
const EVP_MD *digest;
EVP_MD *fetched_digest;
if (is_digest_disabled(alg)) {
TEST_info("skipping, '%s' is disabled", alg);
t->skip = 1;
return 1;
}
if ((digest = fetched_digest = EVP_MD_fetch(libctx, alg, NULL)) == NULL
&& (digest = EVP_get_digestbyname(alg)) == NULL)
return 0;
if (!TEST_ptr(mdat = OPENSSL_zalloc(sizeof(*mdat))))
return 0;
t->data = mdat;
mdat->digest = digest;
mdat->fetched_digest = fetched_digest;
mdat->pad_type = 0;
if (fetched_digest != NULL)
TEST_info("%s is fetched", alg);
return 1;
}
static void digest_test_cleanup(EVP_TEST *t)
{
DIGEST_DATA *mdat = t->data;
sk_EVP_TEST_BUFFER_pop_free(mdat->input, evp_test_buffer_free);
OPENSSL_free(mdat->output);
EVP_MD_free(mdat->fetched_digest);
}
static int digest_test_parse(EVP_TEST *t,
const char *keyword, const char *value)
{
DIGEST_DATA *mdata = t->data;
if (strcmp(keyword, "Input") == 0)
return evp_test_buffer_append(value, &mdata->input);
if (strcmp(keyword, "Output") == 0)
return parse_bin(value, &mdata->output, &mdata->output_len);
if (strcmp(keyword, "Count") == 0)
return evp_test_buffer_set_count(value, mdata->input);
if (strcmp(keyword, "Ncopy") == 0)
return evp_test_buffer_ncopy(value, mdata->input);
if (strcmp(keyword, "Padding") == 0)
return (mdata->pad_type = atoi(value)) > 0;
return 0;
}
static int digest_update_fn(void *ctx, const unsigned char *buf, size_t buflen)
{
return EVP_DigestUpdate(ctx, buf, buflen);
}
static int digest_test_run(EVP_TEST *t)
{
DIGEST_DATA *expected = t->data;
EVP_TEST_BUFFER *inbuf;
EVP_MD_CTX *mctx;
unsigned char *got = NULL;
unsigned int got_len;
size_t size = 0;
int xof = 0;
OSSL_PARAM params[2];
t->err = "TEST_FAILURE";
if (!TEST_ptr(mctx = EVP_MD_CTX_new()))
goto err;
got = OPENSSL_malloc(expected->output_len > EVP_MAX_MD_SIZE ?
expected->output_len : EVP_MAX_MD_SIZE);
if (!TEST_ptr(got))
goto err;
if (!EVP_DigestInit_ex(mctx, expected->digest, NULL)) {
t->err = "DIGESTINIT_ERROR";
goto err;
}
if (expected->pad_type > 0) {
params[0] = OSSL_PARAM_construct_int(OSSL_DIGEST_PARAM_PAD_TYPE,
&expected->pad_type);
params[1] = OSSL_PARAM_construct_end();
if (!TEST_int_gt(EVP_MD_CTX_set_params(mctx, params), 0)) {
t->err = "PARAMS_ERROR";
goto err;
}
}
if (!evp_test_buffer_do(expected->input, digest_update_fn, mctx)) {
t->err = "DIGESTUPDATE_ERROR";
goto err;
}
xof = (EVP_MD_get_flags(expected->digest) & EVP_MD_FLAG_XOF) != 0;
if (xof) {
EVP_MD_CTX *mctx_cpy;
char dont[] = "touch";
if (!TEST_ptr(mctx_cpy = EVP_MD_CTX_new())) {
goto err;
}
if (!EVP_MD_CTX_copy(mctx_cpy, mctx)) {
EVP_MD_CTX_free(mctx_cpy);
goto err;
}
if (!EVP_DigestFinalXOF(mctx_cpy, (unsigned char *)dont, 0)) {
EVP_MD_CTX_free(mctx_cpy);
t->err = "DIGESTFINALXOF_ERROR";
goto err;
}
if (!TEST_str_eq(dont, "touch")) {
EVP_MD_CTX_free(mctx_cpy);
t->err = "DIGESTFINALXOF_ERROR";
goto err;
}
EVP_MD_CTX_free(mctx_cpy);
got_len = expected->output_len;
if (!EVP_DigestFinalXOF(mctx, got, got_len)) {
t->err = "DIGESTFINALXOF_ERROR";
goto err;
}
} else {
if (!EVP_DigestFinal(mctx, got, &got_len)) {
t->err = "DIGESTFINAL_ERROR";
goto err;
}
}
if (!TEST_int_eq(expected->output_len, got_len)) {
t->err = "DIGEST_LENGTH_MISMATCH";
goto err;
}
if (!memory_err_compare(t, "DIGEST_MISMATCH",
expected->output, expected->output_len,
got, got_len))
goto err;
t->err = NULL;
/* Test the EVP_Q_digest interface as well */
if (sk_EVP_TEST_BUFFER_num(expected->input) == 1
&& !xof
/* This should never fail but we need the returned pointer now */
&& !TEST_ptr(inbuf = sk_EVP_TEST_BUFFER_value(expected->input, 0))
&& !inbuf->count_set) {
OPENSSL_cleanse(got, got_len);
if (!TEST_true(EVP_Q_digest(libctx,
EVP_MD_get0_name(expected->fetched_digest),
NULL, inbuf->buf, inbuf->buflen,
got, &size))
|| !TEST_mem_eq(got, size,
expected->output, expected->output_len)) {
t->err = "EVP_Q_digest failed";
goto err;
}
}
err:
OPENSSL_free(got);
EVP_MD_CTX_free(mctx);
return 1;
}
static const EVP_TEST_METHOD digest_test_method = {
"Digest",
digest_test_init,
digest_test_cleanup,
digest_test_parse,
digest_test_run
};
/**
*** CIPHER TESTS
**/
typedef struct cipher_data_st {
const EVP_CIPHER *cipher;
EVP_CIPHER *fetched_cipher;
int enc;
/* EVP_CIPH_GCM_MODE, EVP_CIPH_CCM_MODE or EVP_CIPH_OCB_MODE if AEAD */
int aead;
unsigned char *key;
size_t key_len;
size_t key_bits; /* Used by RC2 */
unsigned char *iv;
unsigned char *next_iv; /* Expected IV state after operation */
unsigned int rounds;
size_t iv_len;
unsigned char *plaintext;
size_t plaintext_len;
unsigned char *ciphertext;
size_t ciphertext_len;
/* AEAD ciphers only */
unsigned char *aad[AAD_NUM];
size_t aad_len[AAD_NUM];
int tls_aad;
int tls_version;
unsigned char *tag;
const char *cts_mode;
size_t tag_len;
int tag_late;
unsigned char *mac_key;
size_t mac_key_len;
} CIPHER_DATA;
static int cipher_test_init(EVP_TEST *t, const char *alg)
{
const EVP_CIPHER *cipher;
EVP_CIPHER *fetched_cipher;
CIPHER_DATA *cdat;
int m;
if (is_cipher_disabled(alg)) {
t->skip = 1;
TEST_info("skipping, '%s' is disabled", alg);
return 1;
}
ERR_set_mark();
if ((cipher = fetched_cipher = EVP_CIPHER_fetch(libctx, alg, NULL)) == NULL
&& (cipher = EVP_get_cipherbyname(alg)) == NULL) {
/* a stitched cipher might not be available */
if (strstr(alg, "HMAC") != NULL) {
ERR_pop_to_mark();
t->skip = 1;
TEST_info("skipping, '%s' is not available", alg);
return 1;
}
ERR_clear_last_mark();
return 0;
}
ERR_clear_last_mark();
if (!TEST_ptr(cdat = OPENSSL_zalloc(sizeof(*cdat))))
return 0;
cdat->cipher = cipher;
cdat->fetched_cipher = fetched_cipher;
cdat->enc = -1;
m = EVP_CIPHER_get_mode(cipher);
if (EVP_CIPHER_get_flags(cipher) & EVP_CIPH_FLAG_AEAD_CIPHER)
cdat->aead = m != 0 ? m : -1;
else
cdat->aead = 0;
t->data = cdat;
if (fetched_cipher != NULL)
TEST_info("%s is fetched", alg);
return 1;
}
static void cipher_test_cleanup(EVP_TEST *t)
{
int i;
CIPHER_DATA *cdat = t->data;
OPENSSL_free(cdat->key);
OPENSSL_free(cdat->iv);
OPENSSL_free(cdat->next_iv);
OPENSSL_free(cdat->ciphertext);
OPENSSL_free(cdat->plaintext);
for (i = 0; i < AAD_NUM; i++)
OPENSSL_free(cdat->aad[i]);
OPENSSL_free(cdat->tag);
OPENSSL_free(cdat->mac_key);
EVP_CIPHER_free(cdat->fetched_cipher);
}
static int cipher_test_parse(EVP_TEST *t, const char *keyword,
const char *value)
{
CIPHER_DATA *cdat = t->data;
int i;
if (strcmp(keyword, "Key") == 0)
return parse_bin(value, &cdat->key, &cdat->key_len);
if (strcmp(keyword, "Rounds") == 0) {
i = atoi(value);
if (i < 0)
return -1;
cdat->rounds = (unsigned int)i;
return 1;
}
if (strcmp(keyword, "IV") == 0)
return parse_bin(value, &cdat->iv, &cdat->iv_len);
if (strcmp(keyword, "NextIV") == 0)
return parse_bin(value, &cdat->next_iv, &cdat->iv_len);
if (strcmp(keyword, "Plaintext") == 0)
return parse_bin(value, &cdat->plaintext, &cdat->plaintext_len);
if (strcmp(keyword, "Ciphertext") == 0)
return parse_bin(value, &cdat->ciphertext, &cdat->ciphertext_len);
if (strcmp(keyword, "KeyBits") == 0) {
i = atoi(value);
if (i < 0)
return -1;
cdat->key_bits = (size_t)i;
return 1;
}
if (cdat->aead) {
int tls_aad = 0;
if (strcmp(keyword, "TLSAAD") == 0)
cdat->tls_aad = tls_aad = 1;
if (strcmp(keyword, "AAD") == 0 || tls_aad) {
for (i = 0; i < AAD_NUM; i++) {
if (cdat->aad[i] == NULL)
return parse_bin(value, &cdat->aad[i], &cdat->aad_len[i]);
}
return -1;
}
if (strcmp(keyword, "Tag") == 0)
return parse_bin(value, &cdat->tag, &cdat->tag_len);
if (strcmp(keyword, "SetTagLate") == 0) {
if (strcmp(value, "TRUE") == 0)
cdat->tag_late = 1;
else if (strcmp(value, "FALSE") == 0)
cdat->tag_late = 0;
else
return -1;
return 1;
}
if (strcmp(keyword, "MACKey") == 0)
return parse_bin(value, &cdat->mac_key, &cdat->mac_key_len);
if (strcmp(keyword, "TLSVersion") == 0) {
char *endptr;
cdat->tls_version = (int)strtol(value, &endptr, 0);
return value[0] != '\0' && endptr[0] == '\0';
}
}
if (strcmp(keyword, "Operation") == 0) {
if (strcmp(value, "ENCRYPT") == 0)
cdat->enc = 1;
else if (strcmp(value, "DECRYPT") == 0)
cdat->enc = 0;
else
return -1;
return 1;
}
if (strcmp(keyword, "CTSMode") == 0) {
cdat->cts_mode = value;
return 1;
}
return 0;
}
static int cipher_test_enc(EVP_TEST *t, int enc,
size_t out_misalign, size_t inp_misalign, int frag)
{
CIPHER_DATA *expected = t->data;
unsigned char *in, *expected_out, *tmp = NULL;
size_t in_len, out_len, donelen = 0;
int ok = 0, tmplen, chunklen, tmpflen, i;
EVP_CIPHER_CTX *ctx_base = NULL;
EVP_CIPHER_CTX *ctx = NULL;
int fips_dupctx_supported = (fips_provider_version_gt(libctx, 3, 0, 12)
&& fips_provider_version_lt(libctx, 3, 1, 0))
|| fips_provider_version_ge(libctx, 3, 1, 3);
t->err = "TEST_FAILURE";
if (!TEST_ptr(ctx_base = EVP_CIPHER_CTX_new()))
goto err;
if (!TEST_ptr(ctx = EVP_CIPHER_CTX_new()))
goto err;
EVP_CIPHER_CTX_set_flags(ctx_base, EVP_CIPHER_CTX_FLAG_WRAP_ALLOW);
if (enc) {
in = expected->plaintext;
in_len = expected->plaintext_len;
expected_out = expected->ciphertext;
out_len = expected->ciphertext_len;
} else {
in = expected->ciphertext;
in_len = expected->ciphertext_len;
expected_out = expected->plaintext;
out_len = expected->plaintext_len;
}
if (inp_misalign == (size_t)-1) {
/* Exercise in-place encryption */
tmp = OPENSSL_malloc(out_misalign + in_len + 2 * EVP_MAX_BLOCK_LENGTH);
if (!tmp)
goto err;
in = memcpy(tmp + out_misalign, in, in_len);
} else {
inp_misalign += 16 - ((out_misalign + in_len) & 15);
/*
* 'tmp' will store both output and copy of input. We make the copy
* of input to specifically aligned part of 'tmp'. So we just
* figured out how much padding would ensure the required alignment,
* now we allocate extended buffer and finally copy the input just
* past inp_misalign in expression below. Output will be written
* past out_misalign...
*/
tmp = OPENSSL_malloc(out_misalign + in_len + 2 * EVP_MAX_BLOCK_LENGTH +
inp_misalign + in_len);
if (!tmp)
goto err;
in = memcpy(tmp + out_misalign + in_len + 2 * EVP_MAX_BLOCK_LENGTH +
inp_misalign, in, in_len);
}
if (!EVP_CipherInit_ex(ctx_base, expected->cipher, NULL, NULL, NULL, enc)) {
t->err = "CIPHERINIT_ERROR";
goto err;
}
if (expected->cts_mode != NULL) {
OSSL_PARAM params[2];
params[0] = OSSL_PARAM_construct_utf8_string(OSSL_CIPHER_PARAM_CTS_MODE,
(char *)expected->cts_mode,
0);
params[1] = OSSL_PARAM_construct_end();
if (!EVP_CIPHER_CTX_set_params(ctx_base, params)) {
t->err = "INVALID_CTS_MODE";
goto err;
}
}
if (expected->iv) {
if (expected->aead) {
if (EVP_CIPHER_CTX_ctrl(ctx_base, EVP_CTRL_AEAD_SET_IVLEN,
expected->iv_len, 0) <= 0) {
t->err = "INVALID_IV_LENGTH";
goto err;
}
} else if (expected->iv_len != (size_t)EVP_CIPHER_CTX_get_iv_length(ctx_base)) {
t->err = "INVALID_IV_LENGTH";
goto err;
}
}
if (expected->aead && !expected->tls_aad) {
unsigned char *tag;
/*
* If encrypting or OCB just set tag length initially, otherwise
* set tag length and value.
*/
if (enc || expected->aead == EVP_CIPH_OCB_MODE || expected->tag_late) {
t->err = "TAG_LENGTH_SET_ERROR";
tag = NULL;
} else {
t->err = "TAG_SET_ERROR";
tag = expected->tag;
}
if (tag || expected->aead != EVP_CIPH_GCM_MODE) {
if (EVP_CIPHER_CTX_ctrl(ctx_base, EVP_CTRL_AEAD_SET_TAG,
expected->tag_len, tag) <= 0)
goto err;
}
}
if (expected->rounds > 0) {
int rounds = (int)expected->rounds;
if (EVP_CIPHER_CTX_ctrl(ctx_base, EVP_CTRL_SET_RC5_ROUNDS, rounds, NULL) <= 0) {
t->err = "INVALID_ROUNDS";
goto err;
}
}
if (!EVP_CIPHER_CTX_set_key_length(ctx_base, expected->key_len)) {
t->err = "INVALID_KEY_LENGTH";
goto err;
}
if (expected->key_bits > 0) {
int bits = (int)expected->key_bits;
if (EVP_CIPHER_CTX_ctrl(ctx_base, EVP_CTRL_SET_RC2_KEY_BITS, bits, NULL) <= 0) {
t->err = "INVALID KEY BITS";
goto err;
}
}
if (!EVP_CipherInit_ex(ctx_base, NULL, NULL, expected->key, expected->iv, -1)) {
t->err = "KEY_SET_ERROR";
goto err;
}
/* Check that we get the same IV back */
if (expected->iv != NULL) {
/* Some (e.g., GCM) tests use IVs longer than EVP_MAX_IV_LENGTH. */
unsigned char iv[128];
if (!TEST_true(EVP_CIPHER_CTX_get_updated_iv(ctx_base, iv, sizeof(iv)))
|| ((EVP_CIPHER_get_flags(expected->cipher) & EVP_CIPH_CUSTOM_IV) == 0
&& !TEST_mem_eq(expected->iv, expected->iv_len, iv,
expected->iv_len))) {
t->err = "INVALID_IV";
goto err;
}
}
/* Test that the cipher dup functions correctly if it is supported */
ERR_set_mark();
if (!EVP_CIPHER_CTX_copy(ctx, ctx_base)) {
if (fips_dupctx_supported) {
TEST_info("Doing a copy of Cipher %s Fails!\n",
EVP_CIPHER_get0_name(expected->cipher));
ERR_print_errors_fp(stderr);
goto err;
} else {
TEST_info("Allowing copy fail as an old fips provider is in use.");
}
EVP_CIPHER_CTX_free(ctx);
ctx = ctx_base;
} else {
EVP_CIPHER_CTX_free(ctx_base);
ctx_base = NULL;
}
ERR_pop_to_mark();
if (expected->mac_key != NULL
&& EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_MAC_KEY,
(int)expected->mac_key_len,
(void *)expected->mac_key) <= 0) {
t->err = "SET_MAC_KEY_ERROR";
goto err;
}
if (expected->tls_version) {
OSSL_PARAM params[2];
params[0] = OSSL_PARAM_construct_int(OSSL_CIPHER_PARAM_TLS_VERSION,
&expected->tls_version);
params[1] = OSSL_PARAM_construct_end();
if (!EVP_CIPHER_CTX_set_params(ctx, params)) {
t->err = "SET_TLS_VERSION_ERROR";
goto err;
}
}
if (expected->aead == EVP_CIPH_CCM_MODE) {
if (!EVP_CipherUpdate(ctx, NULL, &tmplen, NULL, out_len)) {
t->err = "CCM_PLAINTEXT_LENGTH_SET_ERROR";
goto err;
}
}
if (expected->aad[0] != NULL && !expected->tls_aad) {
t->err = "AAD_SET_ERROR";
if (!frag) {
for (i = 0; expected->aad[i] != NULL; i++) {
if (!EVP_CipherUpdate(ctx, NULL, &chunklen, expected->aad[i],
expected->aad_len[i]))
goto err;
}
} else {
/*
* Supply the AAD in chunks less than the block size where possible
*/
for (i = 0; expected->aad[i] != NULL; i++) {
if (expected->aad_len[i] > 0) {
if (!EVP_CipherUpdate(ctx, NULL, &chunklen, expected->aad[i], 1))
goto err;
donelen++;
}
if (expected->aad_len[i] > 2) {
if (!EVP_CipherUpdate(ctx, NULL, &chunklen,
expected->aad[i] + donelen,
expected->aad_len[i] - 2))
goto err;
donelen += expected->aad_len[i] - 2;
}
if (expected->aad_len[i] > 1
&& !EVP_CipherUpdate(ctx, NULL, &chunklen,
expected->aad[i] + donelen, 1))
goto err;
}
}
}
if (expected->tls_aad) {
OSSL_PARAM params[2];
char *tls_aad;
/* duplicate the aad as the implementation might modify it */
if ((tls_aad = OPENSSL_memdup(expected->aad[0],
expected->aad_len[0])) == NULL)
goto err;
params[0] = OSSL_PARAM_construct_octet_string(OSSL_CIPHER_PARAM_AEAD_TLS1_AAD,
tls_aad,
expected->aad_len[0]);
params[1] = OSSL_PARAM_construct_end();
if (!EVP_CIPHER_CTX_set_params(ctx, params)) {
OPENSSL_free(tls_aad);
t->err = "TLS1_AAD_ERROR";
goto err;
}
OPENSSL_free(tls_aad);
} else if (!enc && (expected->aead == EVP_CIPH_OCB_MODE
|| expected->tag_late)) {
if (EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_TAG,
expected->tag_len, expected->tag) <= 0) {
t->err = "TAG_SET_ERROR";
goto err;
}
}
EVP_CIPHER_CTX_set_padding(ctx, 0);
t->err = "CIPHERUPDATE_ERROR";
tmplen = 0;
if (!frag) {
/* We supply the data all in one go */
if (!EVP_CipherUpdate(ctx, tmp + out_misalign, &tmplen, in, in_len))
goto err;
} else {
/* Supply the data in chunks less than the block size where possible */
if (in_len > 0) {
if (!EVP_CipherUpdate(ctx, tmp + out_misalign, &chunklen, in, 1))
goto err;
tmplen += chunklen;
in++;
in_len--;
}
if (in_len > 1) {
if (!EVP_CipherUpdate(ctx, tmp + out_misalign + tmplen, &chunklen,
in, in_len - 1))
goto err;
tmplen += chunklen;
in += in_len - 1;
in_len = 1;
}
if (in_len > 0 ) {
if (!EVP_CipherUpdate(ctx, tmp + out_misalign + tmplen, &chunklen,
in, 1))
goto err;
tmplen += chunklen;
}
}
if (!EVP_CipherFinal_ex(ctx, tmp + out_misalign + tmplen, &tmpflen)) {
t->err = "CIPHERFINAL_ERROR";
goto err;
}
if (!enc && expected->tls_aad) {
if (expected->tls_version >= TLS1_1_VERSION
&& (EVP_CIPHER_is_a(expected->cipher, "AES-128-CBC-HMAC-SHA1")
|| EVP_CIPHER_is_a(expected->cipher, "AES-256-CBC-HMAC-SHA1"))) {
tmplen -= expected->iv_len;
expected_out += expected->iv_len;
out_misalign += expected->iv_len;
}
if ((int)out_len > tmplen + tmpflen)
out_len = tmplen + tmpflen;
}
if (!memory_err_compare(t, "VALUE_MISMATCH", expected_out, out_len,
tmp + out_misalign, tmplen + tmpflen))
goto err;
if (enc && expected->aead && !expected->tls_aad) {
unsigned char rtag[16];
if (!TEST_size_t_le(expected->tag_len, sizeof(rtag))) {
t->err = "TAG_LENGTH_INTERNAL_ERROR";
goto err;
}
if (EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_GET_TAG,
expected->tag_len, rtag) <= 0) {
t->err = "TAG_RETRIEVE_ERROR";
goto err;
}
if (!memory_err_compare(t, "TAG_VALUE_MISMATCH",
expected->tag, expected->tag_len,
rtag, expected->tag_len))
goto err;
}
/* Check the updated IV */
if (expected->next_iv != NULL) {
/* Some (e.g., GCM) tests use IVs longer than EVP_MAX_IV_LENGTH. */
unsigned char iv[128];
if (!TEST_true(EVP_CIPHER_CTX_get_updated_iv(ctx, iv, sizeof(iv)))
|| ((EVP_CIPHER_get_flags(expected->cipher) & EVP_CIPH_CUSTOM_IV) == 0
&& !TEST_mem_eq(expected->next_iv, expected->iv_len, iv,
expected->iv_len))) {
t->err = "INVALID_NEXT_IV";
goto err;
}
}
t->err = NULL;
ok = 1;
err:
OPENSSL_free(tmp);
if (ctx != ctx_base)
EVP_CIPHER_CTX_free(ctx_base);
EVP_CIPHER_CTX_free(ctx);
return ok;
}
static int cipher_test_run(EVP_TEST *t)
{
CIPHER_DATA *cdat = t->data;
int rv, frag = 0;
size_t out_misalign, inp_misalign;
TEST_info("RUNNING TEST FOR CIPHER %s\n", EVP_CIPHER_get0_name(cdat->cipher));
if (!cdat->key) {
t->err = "NO_KEY";
return 0;
}
if (!cdat->iv && EVP_CIPHER_get_iv_length(cdat->cipher)) {
/* IV is optional and usually omitted in wrap mode */
if (EVP_CIPHER_get_mode(cdat->cipher) != EVP_CIPH_WRAP_MODE) {
t->err = "NO_IV";
return 0;
}
}
if (cdat->aead && cdat->tag == NULL && !cdat->tls_aad) {
t->err = "NO_TAG";
return 0;
}
for (out_misalign = 0; out_misalign <= 1;) {
static char aux_err[64];
t->aux_err = aux_err;
for (inp_misalign = (size_t)-1; inp_misalign != 2; inp_misalign++) {
if (inp_misalign == (size_t)-1) {
/* kludge: inp_misalign == -1 means "exercise in-place" */
BIO_snprintf(aux_err, sizeof(aux_err),
"%s in-place, %sfragmented",
out_misalign ? "misaligned" : "aligned",
frag ? "" : "not ");
} else {
BIO_snprintf(aux_err, sizeof(aux_err),
"%s output and %s input, %sfragmented",
out_misalign ? "misaligned" : "aligned",
inp_misalign ? "misaligned" : "aligned",
frag ? "" : "not ");
}
if (cdat->enc) {
rv = cipher_test_enc(t, 1, out_misalign, inp_misalign, frag);
/* Not fatal errors: return */
if (rv != 1) {
if (rv < 0)
return 0;
return 1;
}
}
if (cdat->enc != 1) {
rv = cipher_test_enc(t, 0, out_misalign, inp_misalign, frag);
/* Not fatal errors: return */
if (rv != 1) {
if (rv < 0)
return 0;
return 1;
}
}
}
if (out_misalign == 1 && frag == 0) {
/*
* XTS, SIV, CCM, stitched ciphers and Wrap modes have special
* requirements about input lengths so we don't fragment for those
*/
if (cdat->aead == EVP_CIPH_CCM_MODE
|| cdat->aead == EVP_CIPH_CBC_MODE
|| (cdat->aead == -1
&& EVP_CIPHER_get_mode(cdat->cipher) == EVP_CIPH_STREAM_CIPHER)
|| ((EVP_CIPHER_get_flags(cdat->cipher) & EVP_CIPH_FLAG_CTS) != 0)
|| EVP_CIPHER_get_mode(cdat->cipher) == EVP_CIPH_SIV_MODE
|| EVP_CIPHER_get_mode(cdat->cipher) == EVP_CIPH_XTS_MODE
|| EVP_CIPHER_get_mode(cdat->cipher) == EVP_CIPH_WRAP_MODE)
break;
out_misalign = 0;
frag++;
} else {
out_misalign++;
}
}
t->aux_err = NULL;
return 1;
}
static const EVP_TEST_METHOD cipher_test_method = {
"Cipher",
cipher_test_init,
cipher_test_cleanup,
cipher_test_parse,
cipher_test_run
};
/**
** MAC TESTS
**/
typedef struct mac_data_st {
/* MAC type in one form or another */
char *mac_name;
EVP_MAC *mac; /* for mac_test_run_mac */
int type; /* for mac_test_run_pkey */
/* Algorithm string for this MAC */
char *alg;
/* MAC key */
unsigned char *key;
size_t key_len;
/* MAC IV (GMAC) */
unsigned char *iv;
size_t iv_len;
/* Input to MAC */
unsigned char *input;
size_t input_len;
/* Expected output */
unsigned char *output;
size_t output_len;
unsigned char *custom;
size_t custom_len;
/* MAC salt (blake2) */
unsigned char *salt;
size_t salt_len;
/* XOF mode? */
int xof;
/* Reinitialization fails */
int no_reinit;
/* Collection of controls */
STACK_OF(OPENSSL_STRING) *controls;
/* Output size */
int output_size;
/* Block size */
int block_size;
} MAC_DATA;
static int mac_test_init(EVP_TEST *t, const char *alg)
{
EVP_MAC *mac = NULL;
int type = NID_undef;
MAC_DATA *mdat;
if (is_mac_disabled(alg)) {
TEST_info("skipping, '%s' is disabled", alg);
t->skip = 1;
return 1;
}
if ((mac = EVP_MAC_fetch(libctx, alg, NULL)) == NULL) {
/*
* Since we didn't find an EVP_MAC, we check for known EVP_PKEY methods
* For debugging purposes, we allow 'NNNN by EVP_PKEY' to force running
* the EVP_PKEY method.
*/
size_t sz = strlen(alg);
static const char epilogue[] = " by EVP_PKEY";
if (sz >= sizeof(epilogue)
&& strcmp(alg + sz - (sizeof(epilogue) - 1), epilogue) == 0)
sz -= sizeof(epilogue) - 1;
if (strncmp(alg, "HMAC", sz) == 0)
type = EVP_PKEY_HMAC;
else if (strncmp(alg, "CMAC", sz) == 0)
type = EVP_PKEY_CMAC;
else if (strncmp(alg, "Poly1305", sz) == 0)
type = EVP_PKEY_POLY1305;
else if (strncmp(alg, "SipHash", sz) == 0)
type = EVP_PKEY_SIPHASH;
else
return 0;
}
if (!TEST_ptr(mdat = OPENSSL_zalloc(sizeof(*mdat))))
return 0;
mdat->type = type;
if (!TEST_ptr(mdat->mac_name = OPENSSL_strdup(alg))) {
OPENSSL_free(mdat);
return 0;
}
mdat->mac = mac;
if (!TEST_ptr(mdat->controls = sk_OPENSSL_STRING_new_null())) {
OPENSSL_free(mdat->mac_name);
OPENSSL_free(mdat);
return 0;
}
mdat->output_size = mdat->block_size = -1;
t->data = mdat;
return 1;
}
/* Because OPENSSL_free is a macro, it can't be passed as a function pointer */
static void openssl_free(char *m)
{
OPENSSL_free(m);
}
static void mac_test_cleanup(EVP_TEST *t)
{
MAC_DATA *mdat = t->data;
EVP_MAC_free(mdat->mac);
OPENSSL_free(mdat->mac_name);
sk_OPENSSL_STRING_pop_free(mdat->controls, openssl_free);
OPENSSL_free(mdat->alg);
OPENSSL_free(mdat->key);
OPENSSL_free(mdat->iv);
OPENSSL_free(mdat->custom);
OPENSSL_free(mdat->salt);
OPENSSL_free(mdat->input);
OPENSSL_free(mdat->output);
}
static int mac_test_parse(EVP_TEST *t,
const char *keyword, const char *value)
{
MAC_DATA *mdata = t->data;
if (strcmp(keyword, "Key") == 0)
return parse_bin(value, &mdata->key, &mdata->key_len);
if (strcmp(keyword, "IV") == 0)
return parse_bin(value, &mdata->iv, &mdata->iv_len);
if (strcmp(keyword, "Custom") == 0)
return parse_bin(value, &mdata->custom, &mdata->custom_len);
if (strcmp(keyword, "Salt") == 0)
return parse_bin(value, &mdata->salt, &mdata->salt_len);
if (strcmp(keyword, "Algorithm") == 0) {
mdata->alg = OPENSSL_strdup(value);
if (mdata->alg == NULL)
return -1;
return 1;
}
if (strcmp(keyword, "Input") == 0)
return parse_bin(value, &mdata->input, &mdata->input_len);
if (strcmp(keyword, "Output") == 0)
return parse_bin(value, &mdata->output, &mdata->output_len);
if (strcmp(keyword, "XOF") == 0)
return mdata->xof = 1;
if (strcmp(keyword, "NoReinit") == 0)
return mdata->no_reinit = 1;
if (strcmp(keyword, "Ctrl") == 0) {
char *data = OPENSSL_strdup(value);
if (data == NULL)
return -1;
return sk_OPENSSL_STRING_push(mdata->controls, data) != 0;
}
if (strcmp(keyword, "OutputSize") == 0) {
mdata->output_size = atoi(value);
if (mdata->output_size < 0)
return -1;
return 1;
}
if (strcmp(keyword, "BlockSize") == 0) {
mdata->block_size = atoi(value);
if (mdata->block_size < 0)
return -1;
return 1;
}
return 0;
}
static int mac_test_ctrl_pkey(EVP_TEST *t, EVP_PKEY_CTX *pctx,
const char *value)
{
int rv = 0;
char *p, *tmpval;
if (!TEST_ptr(tmpval = OPENSSL_strdup(value)))
return 0;
p = strchr(tmpval, ':');
if (p != NULL) {
*p++ = '\0';
rv = EVP_PKEY_CTX_ctrl_str(pctx, tmpval, p);
}
if (rv == -2)
t->err = "PKEY_CTRL_INVALID";
else if (rv <= 0)
t->err = "PKEY_CTRL_ERROR";
else
rv = 1;
OPENSSL_free(tmpval);
return rv > 0;
}
static int mac_test_run_pkey(EVP_TEST *t)
{
MAC_DATA *expected = t->data;
EVP_MD_CTX *mctx = NULL;
EVP_PKEY_CTX *pctx = NULL, *genctx = NULL;
EVP_PKEY *key = NULL;
const char *mdname = NULL;
EVP_CIPHER *cipher = NULL;
unsigned char *got = NULL;
size_t got_len;
int i;
/* We don't do XOF mode via PKEY */
if (expected->xof)
return 1;
if (expected->alg == NULL)
TEST_info("Trying the EVP_PKEY %s test", OBJ_nid2sn(expected->type));
else
TEST_info("Trying the EVP_PKEY %s test with %s",
OBJ_nid2sn(expected->type), expected->alg);
if (expected->type == EVP_PKEY_CMAC) {
#ifdef OPENSSL_NO_DEPRECATED_3_0
TEST_info("skipping, PKEY CMAC '%s' is disabled", expected->alg);
t->skip = 1;
t->err = NULL;
goto err;
#else
OSSL_LIB_CTX *tmpctx;
if (expected->alg != NULL && is_cipher_disabled(expected->alg)) {
TEST_info("skipping, PKEY CMAC '%s' is disabled", expected->alg);
t->skip = 1;
t->err = NULL;
goto err;
}
if (!TEST_ptr(cipher = EVP_CIPHER_fetch(libctx, expected->alg, NULL))) {
t->err = "MAC_KEY_CREATE_ERROR";
goto err;
}
tmpctx = OSSL_LIB_CTX_set0_default(libctx);
key = EVP_PKEY_new_CMAC_key(NULL, expected->key, expected->key_len,
cipher);
OSSL_LIB_CTX_set0_default(tmpctx);
#endif
} else {
key = EVP_PKEY_new_raw_private_key_ex(libctx,
OBJ_nid2sn(expected->type), NULL,
expected->key, expected->key_len);
}
if (key == NULL) {
t->err = "MAC_KEY_CREATE_ERROR";
goto err;
}
if (expected->type == EVP_PKEY_HMAC && expected->alg != NULL) {
if (is_digest_disabled(expected->alg)) {
TEST_info("skipping, HMAC '%s' is disabled", expected->alg);
t->skip = 1;
t->err = NULL;
goto err;
}
mdname = expected->alg;
}
if (!TEST_ptr(mctx = EVP_MD_CTX_new())) {
t->err = "INTERNAL_ERROR";
goto err;
}
if (!EVP_DigestSignInit_ex(mctx, &pctx, mdname, libctx, NULL, key, NULL)) {
t->err = "DIGESTSIGNINIT_ERROR";
goto err;
}
for (i = 0; i < sk_OPENSSL_STRING_num(expected->controls); i++)
if (!mac_test_ctrl_pkey(t, pctx,
sk_OPENSSL_STRING_value(expected->controls,
i))) {
t->err = "EVPPKEYCTXCTRL_ERROR";
goto err;
}
if (!EVP_DigestSignUpdate(mctx, expected->input, expected->input_len)) {
t->err = "DIGESTSIGNUPDATE_ERROR";
goto err;
}
if (!EVP_DigestSignFinal(mctx, NULL, &got_len)) {
t->err = "DIGESTSIGNFINAL_LENGTH_ERROR";
goto err;
}
if (!TEST_ptr(got = OPENSSL_malloc(got_len))) {
t->err = "TEST_FAILURE";
goto err;
}
if (!EVP_DigestSignFinal(mctx, got, &got_len)
|| !memory_err_compare(t, "TEST_MAC_ERR",
expected->output, expected->output_len,
got, got_len)) {
t->err = "TEST_MAC_ERR";
goto err;
}
t->err = NULL;
err:
EVP_CIPHER_free(cipher);
EVP_MD_CTX_free(mctx);
OPENSSL_free(got);
EVP_PKEY_CTX_free(genctx);
EVP_PKEY_free(key);
return 1;
}
static int mac_test_run_mac(EVP_TEST *t)
{
MAC_DATA *expected = t->data;
EVP_MAC_CTX *ctx = NULL;
unsigned char *got = NULL;
size_t got_len = 0, size = 0;
size_t size_before_init = 0, size_after_init, size_val = 0;
int i, block_size = -1, output_size = -1;
OSSL_PARAM params[21], sizes[3], *psizes = sizes;
size_t params_n = 0;
size_t params_n_allocstart = 0;
const OSSL_PARAM *defined_params =
EVP_MAC_settable_ctx_params(expected->mac);
int xof;
int reinit = 1;
if (expected->alg == NULL)
TEST_info("Trying the EVP_MAC %s test", expected->mac_name);
else
TEST_info("Trying the EVP_MAC %s test with %s",
expected->mac_name, expected->alg);
if (expected->alg != NULL) {
int skip = 0;
/*
* The underlying algorithm may be a cipher or a digest.
* We don't know which it is, but we can ask the MAC what it
* should be and bet on that.
*/
if (OSSL_PARAM_locate_const(defined_params,
OSSL_MAC_PARAM_CIPHER) != NULL) {
if (is_cipher_disabled(expected->alg))
skip = 1;
else
params[params_n++] =
OSSL_PARAM_construct_utf8_string(OSSL_MAC_PARAM_CIPHER,
expected->alg, 0);
} else if (OSSL_PARAM_locate_const(defined_params,
OSSL_MAC_PARAM_DIGEST) != NULL) {
if (is_digest_disabled(expected->alg))
skip = 1;
else
params[params_n++] =
OSSL_PARAM_construct_utf8_string(OSSL_MAC_PARAM_DIGEST,
expected->alg, 0);
} else {
t->err = "MAC_BAD_PARAMS";
goto err;
}
if (skip) {
TEST_info("skipping, algorithm '%s' is disabled", expected->alg);
t->skip = 1;
t->err = NULL;
goto err;
}
}
if (expected->custom != NULL)
params[params_n++] =
OSSL_PARAM_construct_octet_string(OSSL_MAC_PARAM_CUSTOM,
expected->custom,
expected->custom_len);
if (expected->salt != NULL)
params[params_n++] =
OSSL_PARAM_construct_octet_string(OSSL_MAC_PARAM_SALT,
expected->salt,
expected->salt_len);
if (expected->iv != NULL)
params[params_n++] =
OSSL_PARAM_construct_octet_string(OSSL_MAC_PARAM_IV,
expected->iv,
expected->iv_len);
/* Unknown controls. They must match parameters that the MAC recognizes */
if (params_n + sk_OPENSSL_STRING_num(expected->controls)
>= OSSL_NELEM(params)) {
t->err = "MAC_TOO_MANY_PARAMETERS";
goto err;
}
params_n_allocstart = params_n;
for (i = 0; i < sk_OPENSSL_STRING_num(expected->controls); i++) {
char *tmpkey, *tmpval;
char *value = sk_OPENSSL_STRING_value(expected->controls, i);
if (!TEST_ptr(tmpkey = OPENSSL_strdup(value))) {
t->err = "MAC_PARAM_ERROR";
goto err;
}
tmpval = strchr(tmpkey, ':');
if (tmpval != NULL)
*tmpval++ = '\0';
if (tmpval == NULL
|| !OSSL_PARAM_allocate_from_text(&params[params_n],
defined_params,
tmpkey, tmpval,
strlen(tmpval), NULL)) {
OPENSSL_free(tmpkey);
t->err = "MAC_PARAM_ERROR";
goto err;
}
params_n++;
if (strcmp(tmpkey, "size") == 0)
size_val = (size_t)strtoul(tmpval, NULL, 0);
OPENSSL_free(tmpkey);
}
params[params_n] = OSSL_PARAM_construct_end();
if ((ctx = EVP_MAC_CTX_new(expected->mac)) == NULL) {
t->err = "MAC_CREATE_ERROR";
goto err;
}
if (fips_provider_version_gt(libctx, 3, 1, 4)
|| (fips_provider_version_lt(libctx, 3, 1, 0)
&& fips_provider_version_gt(libctx, 3, 0, 12)))
size_before_init = EVP_MAC_CTX_get_mac_size(ctx);
if (!EVP_MAC_init(ctx, expected->key, expected->key_len, params)) {
t->err = "MAC_INIT_ERROR";
goto err;
}
size_after_init = EVP_MAC_CTX_get_mac_size(ctx);
if (!TEST_false(size_before_init == 0 && size_after_init == 0)) {
t->err = "MAC SIZE not set";
goto err;
}
if (size_before_init != 0) {
/* mac-size not modified by init params */
if (size_val == 0 && !TEST_size_t_eq(size_before_init, size_after_init)) {
t->err = "MAC SIZE check failed";
goto err;
}
/* mac-size modified by init params */
if (size_val != 0 && !TEST_size_t_eq(size_val, size_after_init)) {
t->err = "MAC SIZE check failed";
goto err;
}
}
if (expected->output_size >= 0)
*psizes++ = OSSL_PARAM_construct_int(OSSL_MAC_PARAM_SIZE,
&output_size);
if (expected->block_size >= 0)
*psizes++ = OSSL_PARAM_construct_int(OSSL_MAC_PARAM_BLOCK_SIZE,
&block_size);
if (psizes != sizes) {
*psizes = OSSL_PARAM_construct_end();
if (!TEST_true(EVP_MAC_CTX_get_params(ctx, sizes))) {
t->err = "INTERNAL_ERROR";
goto err;
}
if (expected->output_size >= 0
&& !TEST_int_eq(output_size, expected->output_size)) {
t->err = "TEST_FAILURE";
goto err;
}
if (expected->block_size >= 0
&& !TEST_int_eq(block_size, expected->block_size)) {
t->err = "TEST_FAILURE";
goto err;
}
}
retry:
if (!EVP_MAC_update(ctx, expected->input, expected->input_len)) {
t->err = "MAC_UPDATE_ERROR";
goto err;
}
xof = expected->xof;
if (xof) {
if (!TEST_ptr(got = OPENSSL_malloc(expected->output_len))) {
t->err = "TEST_FAILURE";
goto err;
}
if (!EVP_MAC_finalXOF(ctx, got, expected->output_len)
|| !memory_err_compare(t, "TEST_MAC_ERR",
expected->output, expected->output_len,
got, expected->output_len)) {
t->err = "MAC_FINAL_ERROR";
goto err;
}
} else {
if (!EVP_MAC_final(ctx, NULL, &got_len, 0)) {
t->err = "MAC_FINAL_LENGTH_ERROR";
goto err;
}
if (!TEST_ptr(got = OPENSSL_malloc(got_len))) {
t->err = "TEST_FAILURE";
goto err;
}
if (!EVP_MAC_final(ctx, got, &got_len, got_len)
|| !memory_err_compare(t, "TEST_MAC_ERR",
expected->output, expected->output_len,
got, got_len)) {
t->err = "TEST_MAC_ERR";
goto err;
}
}
/* FIPS(3.0.0): can't reinitialise MAC contexts #18100 */
if (reinit-- && fips_provider_version_gt(libctx, 3, 0, 0)) {
OSSL_PARAM ivparams[2] = { OSSL_PARAM_END, OSSL_PARAM_END };
int ret;
/* If the MAC uses IV, we have to set it again */
if (expected->iv != NULL) {
ivparams[0] =
OSSL_PARAM_construct_octet_string(OSSL_MAC_PARAM_IV,
expected->iv,
expected->iv_len);
ivparams[1] = OSSL_PARAM_construct_end();
}
ERR_set_mark();
ret = EVP_MAC_init(ctx, NULL, 0, ivparams);
if (expected->no_reinit) {
if (ret) {
ERR_clear_last_mark();
t->err = "MAC_REINIT_SHOULD_FAIL";
goto err;
}
} else if (ret) {
ERR_clear_last_mark();
OPENSSL_free(got);
got = NULL;
goto retry;
} else {
ERR_clear_last_mark();
t->err = "MAC_REINIT_ERROR";
goto err;
}
/* If reinitialization fails, it is unsupported by the algorithm */
ERR_pop_to_mark();
}
t->err = NULL;
/* Test the EVP_Q_mac interface as well */
if (!xof) {
OPENSSL_cleanse(got, got_len);
if (!TEST_true(EVP_Q_mac(libctx, expected->mac_name, NULL,
expected->alg, params,
expected->key, expected->key_len,
expected->input, expected->input_len,
got, got_len, &size))
|| !TEST_mem_eq(got, size,
expected->output, expected->output_len)) {
t->err = "EVP_Q_mac failed";
goto err;
}
}
err:
while (params_n-- > params_n_allocstart) {
OPENSSL_free(params[params_n].data);
}
EVP_MAC_CTX_free(ctx);
OPENSSL_free(got);
return 1;
}
static int mac_test_run(EVP_TEST *t)
{
MAC_DATA *expected = t->data;
if (expected->mac != NULL)
return mac_test_run_mac(t);
return mac_test_run_pkey(t);
}
static const EVP_TEST_METHOD mac_test_method = {
"MAC",
mac_test_init,
mac_test_cleanup,
mac_test_parse,
mac_test_run
};
/**
** PUBLIC KEY TESTS
** These are all very similar and share much common code.
**/
typedef struct pkey_data_st {
/* Context for this operation */
EVP_PKEY_CTX *ctx;
/* Key operation to perform */
int (*keyop) (EVP_PKEY_CTX *ctx,
unsigned char *sig, size_t *siglen,
const unsigned char *tbs, size_t tbslen);
/* Input to MAC */
unsigned char *input;
size_t input_len;
/* Expected output */
unsigned char *output;
size_t output_len;
} PKEY_DATA;
/*
* Perform public key operation setup: lookup key, allocated ctx and call
* the appropriate initialisation function
*/
static int pkey_test_init(EVP_TEST *t, const char *name,
int use_public,
int (*keyopinit) (EVP_PKEY_CTX *ctx),
int (*keyop)(EVP_PKEY_CTX *ctx,
unsigned char *sig, size_t *siglen,
const unsigned char *tbs,
size_t tbslen))
{
PKEY_DATA *kdata;
EVP_PKEY *pkey = NULL;
int rv = 0;
if (use_public)
rv = find_key(&pkey, name, public_keys);
if (rv == 0)
rv = find_key(&pkey, name, private_keys);
if (rv == 0 || pkey == NULL) {
TEST_info("skipping, key '%s' is disabled", name);
t->skip = 1;
return 1;
}
if (!TEST_ptr(kdata = OPENSSL_zalloc(sizeof(*kdata)))) {
EVP_PKEY_free(pkey);
return 0;
}
kdata->keyop = keyop;
if (!TEST_ptr(kdata->ctx = EVP_PKEY_CTX_new_from_pkey(libctx, pkey, NULL))) {
EVP_PKEY_free(pkey);
OPENSSL_free(kdata);
return 0;
}
if (keyopinit(kdata->ctx) <= 0)
t->err = "KEYOP_INIT_ERROR";
t->data = kdata;
return 1;
}
static void pkey_test_cleanup(EVP_TEST *t)
{
PKEY_DATA *kdata = t->data;
OPENSSL_free(kdata->input);
OPENSSL_free(kdata->output);
EVP_PKEY_CTX_free(kdata->ctx);
}
static int pkey_test_ctrl(EVP_TEST *t, EVP_PKEY_CTX *pctx,
const char *value)
{
int rv = 0;
char *p, *tmpval;
if (!TEST_ptr(tmpval = OPENSSL_strdup(value)))
return 0;
p = strchr(tmpval, ':');
if (p != NULL) {
*p++ = '\0';
rv = EVP_PKEY_CTX_ctrl_str(pctx, tmpval, p);
}
if (rv == -2) {
t->err = "PKEY_CTRL_INVALID";
rv = 1;
} else if (p != NULL && rv <= 0) {
if (is_digest_disabled(p) || is_cipher_disabled(p)) {
TEST_info("skipping, '%s' is disabled", p);
t->skip = 1;
rv = 1;
} else {
t->err = "PKEY_CTRL_ERROR";
rv = 1;
}
}
OPENSSL_free(tmpval);
return rv > 0;
}
static int pkey_test_parse(EVP_TEST *t,
const char *keyword, const char *value)
{
PKEY_DATA *kdata = t->data;
if (strcmp(keyword, "Input") == 0)
return parse_bin(value, &kdata->input, &kdata->input_len);
if (strcmp(keyword, "Output") == 0)
return parse_bin(value, &kdata->output, &kdata->output_len);
if (strcmp(keyword, "Ctrl") == 0)
return pkey_test_ctrl(t, kdata->ctx, value);
return 0;
}
static int pkey_test_run(EVP_TEST *t)
{
PKEY_DATA *expected = t->data;
unsigned char *got = NULL;
size_t got_len;
EVP_PKEY_CTX *copy = NULL;
if (expected->keyop(expected->ctx, NULL, &got_len,
expected->input, expected->input_len) <= 0
|| !TEST_ptr(got = OPENSSL_malloc(got_len))) {
t->err = "KEYOP_LENGTH_ERROR";
goto err;
}
if (expected->keyop(expected->ctx, got, &got_len,
expected->input, expected->input_len) <= 0) {
t->err = "KEYOP_ERROR";
goto err;
}
if (!memory_err_compare(t, "KEYOP_MISMATCH",
expected->output, expected->output_len,
got, got_len))
goto err;
t->err = NULL;
OPENSSL_free(got);
got = NULL;
/* Repeat the test on a copy. */
if (!TEST_ptr(copy = EVP_PKEY_CTX_dup(expected->ctx))) {
t->err = "INTERNAL_ERROR";
goto err;
}
if (expected->keyop(copy, NULL, &got_len, expected->input,
expected->input_len) <= 0
|| !TEST_ptr(got = OPENSSL_malloc(got_len))) {
t->err = "KEYOP_LENGTH_ERROR";
goto err;
}
if (expected->keyop(copy, got, &got_len, expected->input,
expected->input_len) <= 0) {
t->err = "KEYOP_ERROR";
goto err;
}
if (!memory_err_compare(t, "KEYOP_MISMATCH",
expected->output, expected->output_len,
got, got_len))
goto err;
err:
OPENSSL_free(got);
EVP_PKEY_CTX_free(copy);
return 1;
}
static int sign_test_init(EVP_TEST *t, const char *name)
{
return pkey_test_init(t, name, 0, EVP_PKEY_sign_init, EVP_PKEY_sign);
}
static const EVP_TEST_METHOD psign_test_method = {
"Sign",
sign_test_init,
pkey_test_cleanup,
pkey_test_parse,
pkey_test_run
};
static int verify_recover_test_init(EVP_TEST *t, const char *name)
{
return pkey_test_init(t, name, 1, EVP_PKEY_verify_recover_init,
EVP_PKEY_verify_recover);
}
static const EVP_TEST_METHOD pverify_recover_test_method = {
"VerifyRecover",
verify_recover_test_init,
pkey_test_cleanup,
pkey_test_parse,
pkey_test_run
};
static int decrypt_test_init(EVP_TEST *t, const char *name)
{
return pkey_test_init(t, name, 0, EVP_PKEY_decrypt_init,
EVP_PKEY_decrypt);
}
static const EVP_TEST_METHOD pdecrypt_test_method = {
"Decrypt",
decrypt_test_init,
pkey_test_cleanup,
pkey_test_parse,
pkey_test_run
};
static int verify_test_init(EVP_TEST *t, const char *name)
{
return pkey_test_init(t, name, 1, EVP_PKEY_verify_init, 0);
}
static int verify_test_run(EVP_TEST *t)
{
PKEY_DATA *kdata = t->data;
if (EVP_PKEY_verify(kdata->ctx, kdata->output, kdata->output_len,
kdata->input, kdata->input_len) <= 0)
t->err = "VERIFY_ERROR";
return 1;
}
static const EVP_TEST_METHOD pverify_test_method = {
"Verify",
verify_test_init,
pkey_test_cleanup,
pkey_test_parse,
verify_test_run
};
static int pderive_test_init(EVP_TEST *t, const char *name)
{
return pkey_test_init(t, name, 0, EVP_PKEY_derive_init, 0);
}
static int pderive_test_parse(EVP_TEST *t,
const char *keyword, const char *value)
{
PKEY_DATA *kdata = t->data;
int validate = 0;
if (strcmp(keyword, "PeerKeyValidate") == 0)
validate = 1;
if (validate || strcmp(keyword, "PeerKey") == 0) {
EVP_PKEY *peer;
if (find_key(&peer, value, public_keys) == 0)
return -1;
if (EVP_PKEY_derive_set_peer_ex(kdata->ctx, peer, validate) <= 0) {
t->err = "DERIVE_SET_PEER_ERROR";
return 1;
}
t->err = NULL;
return 1;
}
if (strcmp(keyword, "SharedSecret") == 0)
return parse_bin(value, &kdata->output, &kdata->output_len);
if (strcmp(keyword, "Ctrl") == 0)
return pkey_test_ctrl(t, kdata->ctx, value);
if (strcmp(keyword, "KDFType") == 0) {
OSSL_PARAM params[2];
params[0] = OSSL_PARAM_construct_utf8_string(OSSL_EXCHANGE_PARAM_KDF_TYPE,
(char *)value, 0);
params[1] = OSSL_PARAM_construct_end();
if (EVP_PKEY_CTX_set_params(kdata->ctx, params) == 0)
return -1;
return 1;
}
if (strcmp(keyword, "KDFDigest") == 0) {
OSSL_PARAM params[2];
params[0] = OSSL_PARAM_construct_utf8_string(OSSL_EXCHANGE_PARAM_KDF_DIGEST,
(char *)value, 0);
params[1] = OSSL_PARAM_construct_end();
if (EVP_PKEY_CTX_set_params(kdata->ctx, params) == 0)
return -1;
return 1;
}
if (strcmp(keyword, "CEKAlg") == 0) {
OSSL_PARAM params[2];
params[0] = OSSL_PARAM_construct_utf8_string(OSSL_KDF_PARAM_CEK_ALG,
(char *)value, 0);
params[1] = OSSL_PARAM_construct_end();
if (EVP_PKEY_CTX_set_params(kdata->ctx, params) == 0)
return -1;
return 1;
}
if (strcmp(keyword, "KDFOutlen") == 0) {
OSSL_PARAM params[2];
char *endptr;
size_t outlen = (size_t)strtoul(value, &endptr, 0);
if (endptr[0] != '\0')
return -1;
params[0] = OSSL_PARAM_construct_size_t(OSSL_EXCHANGE_PARAM_KDF_OUTLEN,
&outlen);
params[1] = OSSL_PARAM_construct_end();
if (EVP_PKEY_CTX_set_params(kdata->ctx, params) == 0)
return -1;
return 1;
}
return 0;
}
static int pderive_test_run(EVP_TEST *t)
{
EVP_PKEY_CTX *dctx = NULL;
PKEY_DATA *expected = t->data;
unsigned char *got = NULL;
size_t got_len;
if (!TEST_ptr(dctx = EVP_PKEY_CTX_dup(expected->ctx))) {
t->err = "DERIVE_ERROR";
goto err;
}
if (EVP_PKEY_derive(dctx, NULL, &got_len) <= 0
|| !TEST_size_t_ne(got_len, 0)) {
t->err = "DERIVE_ERROR";
goto err;
}
if (!TEST_ptr(got = OPENSSL_malloc(got_len))) {
t->err = "DERIVE_ERROR";
goto err;
}
if (EVP_PKEY_derive(dctx, got, &got_len) <= 0) {
t->err = "DERIVE_ERROR";
goto err;
}
if (!memory_err_compare(t, "SHARED_SECRET_MISMATCH",
expected->output, expected->output_len,
got, got_len))
goto err;
t->err = NULL;
err:
OPENSSL_free(got);
EVP_PKEY_CTX_free(dctx);
return 1;
}
static const EVP_TEST_METHOD pderive_test_method = {
"Derive",
pderive_test_init,
pkey_test_cleanup,
pderive_test_parse,
pderive_test_run
};
/**
** PBE TESTS
**/
typedef enum pbe_type_enum {
PBE_TYPE_INVALID = 0,
PBE_TYPE_SCRYPT, PBE_TYPE_PBKDF2, PBE_TYPE_PKCS12
} PBE_TYPE;
typedef struct pbe_data_st {
PBE_TYPE pbe_type;
/* scrypt parameters */
uint64_t N, r, p, maxmem;
/* PKCS#12 parameters */
int id, iter;
const EVP_MD *md;
/* password */
unsigned char *pass;
size_t pass_len;
/* salt */
unsigned char *salt;
size_t salt_len;
/* Expected output */
unsigned char *key;
size_t key_len;
} PBE_DATA;
#ifndef OPENSSL_NO_SCRYPT
/* Parse unsigned decimal 64 bit integer value */
static int parse_uint64(const char *value, uint64_t *pr)
{
const char *p = value;
if (!TEST_true(*p)) {
TEST_info("Invalid empty integer value");
return -1;
}
for (*pr = 0; *p; ) {
if (*pr > UINT64_MAX / 10) {
TEST_error("Integer overflow in string %s", value);
return -1;
}
*pr *= 10;
if (!TEST_true(isdigit((unsigned char)*p))) {
TEST_error("Invalid character in string %s", value);
return -1;
}
*pr += *p - '0';
p++;
}
return 1;
}
static int scrypt_test_parse(EVP_TEST *t,
const char *keyword, const char *value)
{
PBE_DATA *pdata = t->data;
if (strcmp(keyword, "N") == 0)
return parse_uint64(value, &pdata->N);
if (strcmp(keyword, "p") == 0)
return parse_uint64(value, &pdata->p);
if (strcmp(keyword, "r") == 0)
return parse_uint64(value, &pdata->r);
if (strcmp(keyword, "maxmem") == 0)
return parse_uint64(value, &pdata->maxmem);
return 0;
}
#endif
static int pbkdf2_test_parse(EVP_TEST *t,
const char *keyword, const char *value)
{
PBE_DATA *pdata = t->data;
if (strcmp(keyword, "iter") == 0) {
pdata->iter = atoi(value);
if (pdata->iter <= 0)
return -1;
return 1;
}
if (strcmp(keyword, "MD") == 0) {
pdata->md = EVP_get_digestbyname(value);
if (pdata->md == NULL)
return -1;
return 1;
}
return 0;
}
static int pkcs12_test_parse(EVP_TEST *t,
const char *keyword, const char *value)
{
PBE_DATA *pdata = t->data;
if (strcmp(keyword, "id") == 0) {
pdata->id = atoi(value);
if (pdata->id <= 0)
return -1;
return 1;
}
return pbkdf2_test_parse(t, keyword, value);
}
static int pbe_test_init(EVP_TEST *t, const char *alg)
{
PBE_DATA *pdat;
PBE_TYPE pbe_type = PBE_TYPE_INVALID;
if (is_kdf_disabled(alg)) {
TEST_info("skipping, '%s' is disabled", alg);
t->skip = 1;
return 1;
}
if (strcmp(alg, "scrypt") == 0) {
pbe_type = PBE_TYPE_SCRYPT;
} else if (strcmp(alg, "pbkdf2") == 0) {
pbe_type = PBE_TYPE_PBKDF2;
} else if (strcmp(alg, "pkcs12") == 0) {
pbe_type = PBE_TYPE_PKCS12;
} else {
TEST_error("Unknown pbe algorithm %s", alg);
return 0;
}
if (!TEST_ptr(pdat = OPENSSL_zalloc(sizeof(*pdat))))
return 0;
pdat->pbe_type = pbe_type;
t->data = pdat;
return 1;
}
static void pbe_test_cleanup(EVP_TEST *t)
{
PBE_DATA *pdat = t->data;
OPENSSL_free(pdat->pass);
OPENSSL_free(pdat->salt);
OPENSSL_free(pdat->key);
}
static int pbe_test_parse(EVP_TEST *t,
const char *keyword, const char *value)
{
PBE_DATA *pdata = t->data;
if (strcmp(keyword, "Password") == 0)
return parse_bin(value, &pdata->pass, &pdata->pass_len);
if (strcmp(keyword, "Salt") == 0)
return parse_bin(value, &pdata->salt, &pdata->salt_len);
if (strcmp(keyword, "Key") == 0)
return parse_bin(value, &pdata->key, &pdata->key_len);
if (pdata->pbe_type == PBE_TYPE_PBKDF2)
return pbkdf2_test_parse(t, keyword, value);
else if (pdata->pbe_type == PBE_TYPE_PKCS12)
return pkcs12_test_parse(t, keyword, value);
#ifndef OPENSSL_NO_SCRYPT
else if (pdata->pbe_type == PBE_TYPE_SCRYPT)
return scrypt_test_parse(t, keyword, value);
#endif
return 0;
}
static int pbe_test_run(EVP_TEST *t)
{
PBE_DATA *expected = t->data;
unsigned char *key;
EVP_MD *fetched_digest = NULL;
OSSL_LIB_CTX *save_libctx;
save_libctx = OSSL_LIB_CTX_set0_default(libctx);
if (!TEST_ptr(key = OPENSSL_malloc(expected->key_len))) {
t->err = "INTERNAL_ERROR";
goto err;
}
if (expected->pbe_type == PBE_TYPE_PBKDF2) {
if (PKCS5_PBKDF2_HMAC((char *)expected->pass, expected->pass_len,
expected->salt, expected->salt_len,
expected->iter, expected->md,
expected->key_len, key) == 0) {
t->err = "PBKDF2_ERROR";
goto err;
}
#ifndef OPENSSL_NO_SCRYPT
} else if (expected->pbe_type == PBE_TYPE_SCRYPT) {
if (EVP_PBE_scrypt((const char *)expected->pass, expected->pass_len,
expected->salt, expected->salt_len,
expected->N, expected->r, expected->p,
expected->maxmem, key, expected->key_len) == 0) {
t->err = "SCRYPT_ERROR";
goto err;
}
#endif
} else if (expected->pbe_type == PBE_TYPE_PKCS12) {
fetched_digest = EVP_MD_fetch(libctx, EVP_MD_get0_name(expected->md),
NULL);
if (fetched_digest == NULL) {
t->err = "PKCS12_ERROR";
goto err;
}
if (PKCS12_key_gen_uni(expected->pass, expected->pass_len,
expected->salt, expected->salt_len,
expected->id, expected->iter, expected->key_len,
key, fetched_digest) == 0) {
t->err = "PKCS12_ERROR";
goto err;
}
}
if (!memory_err_compare(t, "KEY_MISMATCH", expected->key, expected->key_len,
key, expected->key_len))
goto err;
t->err = NULL;
err:
EVP_MD_free(fetched_digest);
OPENSSL_free(key);
OSSL_LIB_CTX_set0_default(save_libctx);
return 1;
}
static const EVP_TEST_METHOD pbe_test_method = {
"PBE",
pbe_test_init,
pbe_test_cleanup,
pbe_test_parse,
pbe_test_run
};
/**
** BASE64 TESTS
**/
typedef enum {
BASE64_CANONICAL_ENCODING = 0,
BASE64_VALID_ENCODING = 1,
BASE64_INVALID_ENCODING = 2
} base64_encoding_type;
typedef struct encode_data_st {
/* Input to encoding */
unsigned char *input;
size_t input_len;
/* Expected output */
unsigned char *output;
size_t output_len;
base64_encoding_type encoding;
} ENCODE_DATA;
static int encode_test_init(EVP_TEST *t, const char *encoding)
{
ENCODE_DATA *edata;
if (!TEST_ptr(edata = OPENSSL_zalloc(sizeof(*edata))))
return 0;
if (strcmp(encoding, "canonical") == 0) {
edata->encoding = BASE64_CANONICAL_ENCODING;
} else if (strcmp(encoding, "valid") == 0) {
edata->encoding = BASE64_VALID_ENCODING;
} else if (strcmp(encoding, "invalid") == 0) {
edata->encoding = BASE64_INVALID_ENCODING;
if (!TEST_ptr(t->expected_err = OPENSSL_strdup("DECODE_ERROR")))
goto err;
} else {
TEST_error("Bad encoding: %s."
" Should be one of {canonical, valid, invalid}",
encoding);
goto err;
}
t->data = edata;
return 1;
err:
OPENSSL_free(edata);
return 0;
}
static void encode_test_cleanup(EVP_TEST *t)
{
ENCODE_DATA *edata = t->data;
OPENSSL_free(edata->input);
OPENSSL_free(edata->output);
memset(edata, 0, sizeof(*edata));
}
static int encode_test_parse(EVP_TEST *t,
const char *keyword, const char *value)
{
ENCODE_DATA *edata = t->data;
if (strcmp(keyword, "Input") == 0)
return parse_bin(value, &edata->input, &edata->input_len);
if (strcmp(keyword, "Output") == 0)
return parse_bin(value, &edata->output, &edata->output_len);
return 0;
}
static int encode_test_run(EVP_TEST *t)
{
ENCODE_DATA *expected = t->data;
unsigned char *encode_out = NULL, *decode_out = NULL;
int output_len, chunk_len;
EVP_ENCODE_CTX *decode_ctx = NULL, *encode_ctx = NULL;
if (!TEST_ptr(decode_ctx = EVP_ENCODE_CTX_new())) {
t->err = "INTERNAL_ERROR";
goto err;
}
if (expected->encoding == BASE64_CANONICAL_ENCODING) {
if (!TEST_ptr(encode_ctx = EVP_ENCODE_CTX_new())
|| !TEST_ptr(encode_out =
OPENSSL_malloc(EVP_ENCODE_LENGTH(expected->input_len))))
goto err;
EVP_EncodeInit(encode_ctx);
if (!TEST_true(EVP_EncodeUpdate(encode_ctx, encode_out, &chunk_len,
expected->input, expected->input_len)))
goto err;
output_len = chunk_len;
EVP_EncodeFinal(encode_ctx, encode_out + chunk_len, &chunk_len);
output_len += chunk_len;
if (!memory_err_compare(t, "BAD_ENCODING",
expected->output, expected->output_len,
encode_out, output_len))
goto err;
}
if (!TEST_ptr(decode_out =
OPENSSL_malloc(EVP_DECODE_LENGTH(expected->output_len))))
goto err;
EVP_DecodeInit(decode_ctx);
if (EVP_DecodeUpdate(decode_ctx, decode_out, &chunk_len, expected->output,
expected->output_len) < 0) {
t->err = "DECODE_ERROR";
goto err;
}
output_len = chunk_len;
if (EVP_DecodeFinal(decode_ctx, decode_out + chunk_len, &chunk_len) != 1) {
t->err = "DECODE_ERROR";
goto err;
}
output_len += chunk_len;
if (expected->encoding != BASE64_INVALID_ENCODING
&& !memory_err_compare(t, "BAD_DECODING",
expected->input, expected->input_len,
decode_out, output_len)) {
t->err = "BAD_DECODING";
goto err;
}
t->err = NULL;
err:
OPENSSL_free(encode_out);
OPENSSL_free(decode_out);
EVP_ENCODE_CTX_free(decode_ctx);
EVP_ENCODE_CTX_free(encode_ctx);
return 1;
}
static const EVP_TEST_METHOD encode_test_method = {
"Encoding",
encode_test_init,
encode_test_cleanup,
encode_test_parse,
encode_test_run,
};
/**
** RAND TESTS
**/
#define MAX_RAND_REPEATS 15
typedef struct rand_data_pass_st {
unsigned char *entropy;
unsigned char *reseed_entropy;
unsigned char *nonce;
unsigned char *pers;
unsigned char *reseed_addin;
unsigned char *addinA;
unsigned char *addinB;
unsigned char *pr_entropyA;
unsigned char *pr_entropyB;
unsigned char *output;
size_t entropy_len, nonce_len, pers_len, addinA_len, addinB_len,
pr_entropyA_len, pr_entropyB_len, output_len, reseed_entropy_len,
reseed_addin_len;
} RAND_DATA_PASS;
typedef struct rand_data_st {
/* Context for this operation */
EVP_RAND_CTX *ctx;
EVP_RAND_CTX *parent;
int n;
int prediction_resistance;
int use_df;
unsigned int generate_bits;
char *cipher;
char *digest;
/* Expected output */
RAND_DATA_PASS data[MAX_RAND_REPEATS];
} RAND_DATA;
static int rand_test_init(EVP_TEST *t, const char *name)
{
RAND_DATA *rdata;
EVP_RAND *rand;
OSSL_PARAM params[2] = { OSSL_PARAM_END, OSSL_PARAM_END };
unsigned int strength = 256;
if (!TEST_ptr(rdata = OPENSSL_zalloc(sizeof(*rdata))))
return 0;
/* TEST-RAND is available in the FIPS provider but not with "fips=yes" */
rand = EVP_RAND_fetch(libctx, "TEST-RAND", "-fips");
if (rand == NULL)
goto err;
rdata->parent = EVP_RAND_CTX_new(rand, NULL);
EVP_RAND_free(rand);
if (rdata->parent == NULL)
goto err;
*params = OSSL_PARAM_construct_uint(OSSL_RAND_PARAM_STRENGTH, &strength);
if (!EVP_RAND_CTX_set_params(rdata->parent, params))
goto err;
rand = EVP_RAND_fetch(libctx, name, NULL);
if (rand == NULL)
goto err;
rdata->ctx = EVP_RAND_CTX_new(rand, rdata->parent);
EVP_RAND_free(rand);
if (rdata->ctx == NULL)
goto err;
rdata->n = -1;
t->data = rdata;
return 1;
err:
EVP_RAND_CTX_free(rdata->parent);
OPENSSL_free(rdata);
return 0;
}
static void rand_test_cleanup(EVP_TEST *t)
{
RAND_DATA *rdata = t->data;
int i;
OPENSSL_free(rdata->cipher);
OPENSSL_free(rdata->digest);
for (i = 0; i <= rdata->n; i++) {
OPENSSL_free(rdata->data[i].entropy);
OPENSSL_free(rdata->data[i].reseed_entropy);
OPENSSL_free(rdata->data[i].nonce);
OPENSSL_free(rdata->data[i].pers);
OPENSSL_free(rdata->data[i].reseed_addin);
OPENSSL_free(rdata->data[i].addinA);
OPENSSL_free(rdata->data[i].addinB);
OPENSSL_free(rdata->data[i].pr_entropyA);
OPENSSL_free(rdata->data[i].pr_entropyB);
OPENSSL_free(rdata->data[i].output);
}
EVP_RAND_CTX_free(rdata->ctx);
EVP_RAND_CTX_free(rdata->parent);
}
static int rand_test_parse(EVP_TEST *t,
const char *keyword, const char *value)
{
RAND_DATA *rdata = t->data;
RAND_DATA_PASS *item;
const char *p;
int n;
if ((p = strchr(keyword, '.')) != NULL) {
n = atoi(++p);
if (n >= MAX_RAND_REPEATS)
return 0;
if (n > rdata->n)
rdata->n = n;
item = rdata->data + n;
if (strncmp(keyword, "Entropy.", sizeof("Entropy")) == 0)
return parse_bin(value, &item->entropy, &item->entropy_len);
if (strncmp(keyword, "ReseedEntropy.", sizeof("ReseedEntropy")) == 0)
return parse_bin(value, &item->reseed_entropy,
&item->reseed_entropy_len);
if (strncmp(keyword, "Nonce.", sizeof("Nonce")) == 0)
return parse_bin(value, &item->nonce, &item->nonce_len);
if (strncmp(keyword, "PersonalisationString.",
sizeof("PersonalisationString")) == 0)
return parse_bin(value, &item->pers, &item->pers_len);
if (strncmp(keyword, "ReseedAdditionalInput.",
sizeof("ReseedAdditionalInput")) == 0)
return parse_bin(value, &item->reseed_addin,
&item->reseed_addin_len);
if (strncmp(keyword, "AdditionalInputA.",
sizeof("AdditionalInputA")) == 0)
return parse_bin(value, &item->addinA, &item->addinA_len);
if (strncmp(keyword, "AdditionalInputB.",
sizeof("AdditionalInputB")) == 0)
return parse_bin(value, &item->addinB, &item->addinB_len);
if (strncmp(keyword, "EntropyPredictionResistanceA.",
sizeof("EntropyPredictionResistanceA")) == 0)
return parse_bin(value, &item->pr_entropyA, &item->pr_entropyA_len);
if (strncmp(keyword, "EntropyPredictionResistanceB.",
sizeof("EntropyPredictionResistanceB")) == 0)
return parse_bin(value, &item->pr_entropyB, &item->pr_entropyB_len);
if (strncmp(keyword, "Output.", sizeof("Output")) == 0)
return parse_bin(value, &item->output, &item->output_len);
} else {
if (strcmp(keyword, "Cipher") == 0)
return TEST_ptr(rdata->cipher = OPENSSL_strdup(value));
if (strcmp(keyword, "Digest") == 0)
return TEST_ptr(rdata->digest = OPENSSL_strdup(value));
if (strcmp(keyword, "DerivationFunction") == 0) {
rdata->use_df = atoi(value) != 0;
return 1;
}
if (strcmp(keyword, "GenerateBits") == 0) {
if ((n = atoi(value)) <= 0 || n % 8 != 0)
return 0;
rdata->generate_bits = (unsigned int)n;
return 1;
}
if (strcmp(keyword, "PredictionResistance") == 0) {
rdata->prediction_resistance = atoi(value) != 0;
return 1;
}
}
return 0;
}
static int rand_test_run(EVP_TEST *t)
{
RAND_DATA *expected = t->data;
RAND_DATA_PASS *item;
unsigned char *got;
size_t got_len = expected->generate_bits / 8;
OSSL_PARAM params[5], *p = params;
int i = -1, ret = 0;
unsigned int strength;
unsigned char *z;
if (!TEST_ptr(got = OPENSSL_malloc(got_len)))
return 0;
*p++ = OSSL_PARAM_construct_int(OSSL_DRBG_PARAM_USE_DF, &expected->use_df);
if (expected->cipher != NULL)
*p++ = OSSL_PARAM_construct_utf8_string(OSSL_DRBG_PARAM_CIPHER,
expected->cipher, 0);
if (expected->digest != NULL)
*p++ = OSSL_PARAM_construct_utf8_string(OSSL_DRBG_PARAM_DIGEST,
expected->digest, 0);
*p++ = OSSL_PARAM_construct_utf8_string(OSSL_DRBG_PARAM_MAC, "HMAC", 0);
*p = OSSL_PARAM_construct_end();
if (!TEST_true(EVP_RAND_CTX_set_params(expected->ctx, params)))
goto err;
strength = EVP_RAND_get_strength(expected->ctx);
for (i = 0; i <= expected->n; i++) {
item = expected->data + i;
p = params;
z = item->entropy != NULL ? item->entropy : (unsigned char *)"";
*p++ = OSSL_PARAM_construct_octet_string(OSSL_RAND_PARAM_TEST_ENTROPY,
z, item->entropy_len);
z = item->nonce != NULL ? item->nonce : (unsigned char *)"";
*p++ = OSSL_PARAM_construct_octet_string(OSSL_RAND_PARAM_TEST_NONCE,
z, item->nonce_len);
*p = OSSL_PARAM_construct_end();
if (!TEST_true(EVP_RAND_instantiate(expected->parent, strength,
0, NULL, 0, params)))
goto err;
z = item->pers != NULL ? item->pers : (unsigned char *)"";
if (!TEST_true(EVP_RAND_instantiate
(expected->ctx, strength,
expected->prediction_resistance, z,
item->pers_len, NULL)))
goto err;
if (item->reseed_entropy != NULL) {
params[0] = OSSL_PARAM_construct_octet_string
(OSSL_RAND_PARAM_TEST_ENTROPY, item->reseed_entropy,
item->reseed_entropy_len);
params[1] = OSSL_PARAM_construct_end();
if (!TEST_true(EVP_RAND_CTX_set_params(expected->parent, params)))
goto err;
if (!TEST_true(EVP_RAND_reseed
(expected->ctx, expected->prediction_resistance,
NULL, 0, item->reseed_addin,
item->reseed_addin_len)))
goto err;
}
if (item->pr_entropyA != NULL) {
params[0] = OSSL_PARAM_construct_octet_string
(OSSL_RAND_PARAM_TEST_ENTROPY, item->pr_entropyA,
item->pr_entropyA_len);
params[1] = OSSL_PARAM_construct_end();
if (!TEST_true(EVP_RAND_CTX_set_params(expected->parent, params)))
goto err;
}
if (!TEST_true(EVP_RAND_generate
(expected->ctx, got, got_len,
strength, expected->prediction_resistance,
item->addinA, item->addinA_len)))
goto err;
if (item->pr_entropyB != NULL) {
params[0] = OSSL_PARAM_construct_octet_string
(OSSL_RAND_PARAM_TEST_ENTROPY, item->pr_entropyB,
item->pr_entropyB_len);
params[1] = OSSL_PARAM_construct_end();
if (!TEST_true(EVP_RAND_CTX_set_params(expected->parent, params)))
goto err;
}
if (!TEST_true(EVP_RAND_generate
(expected->ctx, got, got_len,
strength, expected->prediction_resistance,
item->addinB, item->addinB_len)))
goto err;
if (!TEST_mem_eq(got, got_len, item->output, item->output_len))
goto err;
if (!TEST_true(EVP_RAND_uninstantiate(expected->ctx))
|| !TEST_true(EVP_RAND_uninstantiate(expected->parent))
|| !TEST_true(EVP_RAND_verify_zeroization(expected->ctx))
|| !TEST_int_eq(EVP_RAND_get_state(expected->ctx),
EVP_RAND_STATE_UNINITIALISED))
goto err;
}
t->err = NULL;
ret = 1;
err:
if (ret == 0 && i >= 0)
TEST_info("Error in test case %d of %d\n", i, expected->n + 1);
OPENSSL_free(got);
return ret;
}
static const EVP_TEST_METHOD rand_test_method = {
"RAND",
rand_test_init,
rand_test_cleanup,
rand_test_parse,
rand_test_run
};
/**
** KDF TESTS
**/
typedef struct kdf_data_st {
/* Context for this operation */
EVP_KDF_CTX *ctx;
/* Expected output */
unsigned char *output;
size_t output_len;
OSSL_PARAM params[20];
OSSL_PARAM *p;
} KDF_DATA;
/*
* Perform public key operation setup: lookup key, allocated ctx and call
* the appropriate initialisation function
*/
static int kdf_test_init(EVP_TEST *t, const char *name)
{
KDF_DATA *kdata;
EVP_KDF *kdf;
if (is_kdf_disabled(name)) {
TEST_info("skipping, '%s' is disabled", name);
t->skip = 1;
return 1;
}
if (!TEST_ptr(kdata = OPENSSL_zalloc(sizeof(*kdata))))
return 0;
kdata->p = kdata->params;
*kdata->p = OSSL_PARAM_construct_end();
kdf = EVP_KDF_fetch(libctx, name, NULL);
if (kdf == NULL) {
OPENSSL_free(kdata);
return 0;
}
kdata->ctx = EVP_KDF_CTX_new(kdf);
EVP_KDF_free(kdf);
if (kdata->ctx == NULL) {
OPENSSL_free(kdata);
return 0;
}
t->data = kdata;
return 1;
}
static void kdf_test_cleanup(EVP_TEST *t)
{
KDF_DATA *kdata = t->data;
OSSL_PARAM *p;
for (p = kdata->params; p->key != NULL; p++)
OPENSSL_free(p->data);
OPENSSL_free(kdata->output);
EVP_KDF_CTX_free(kdata->ctx);
}
static int kdf_test_ctrl(EVP_TEST *t, EVP_KDF_CTX *kctx,
const char *value)
{
KDF_DATA *kdata = t->data;
int rv;
char *p, *name;
const OSSL_PARAM *defs = EVP_KDF_settable_ctx_params(EVP_KDF_CTX_kdf(kctx));
if (!TEST_ptr(name = OPENSSL_strdup(value)))
return 0;
p = strchr(name, ':');
- if (p != NULL)
+ if (p == NULL)
+ p = "";
+ else
*p++ = '\0';
rv = OSSL_PARAM_allocate_from_text(kdata->p, defs, name, p,
- p != NULL ? strlen(p) : 0, NULL);
+ strlen(p), NULL);
*++kdata->p = OSSL_PARAM_construct_end();
if (!rv) {
t->err = "KDF_PARAM_ERROR";
OPENSSL_free(name);
return 0;
}
- if (p != NULL && strcmp(name, "digest") == 0) {
+ if (strcmp(name, "digest") == 0) {
if (is_digest_disabled(p)) {
TEST_info("skipping, '%s' is disabled", p);
t->skip = 1;
}
}
- if (p != NULL
- && (strcmp(name, "cipher") == 0
- || strcmp(name, "cekalg") == 0)
+
+ if ((strcmp(name, "cipher") == 0
+ || strcmp(name, "cekalg") == 0)
&& is_cipher_disabled(p)) {
TEST_info("skipping, '%s' is disabled", p);
t->skip = 1;
}
+
OPENSSL_free(name);
return 1;
}
static int kdf_test_parse(EVP_TEST *t,
const char *keyword, const char *value)
{
KDF_DATA *kdata = t->data;
if (strcmp(keyword, "Output") == 0)
return parse_bin(value, &kdata->output, &kdata->output_len);
if (strncmp(keyword, "Ctrl", 4) == 0)
return kdf_test_ctrl(t, kdata->ctx, value);
return 0;
}
static int kdf_test_run(EVP_TEST *t)
{
KDF_DATA *expected = t->data;
unsigned char *got = NULL;
size_t got_len = expected->output_len;
if (!EVP_KDF_CTX_set_params(expected->ctx, expected->params)) {
t->err = "KDF_CTRL_ERROR";
return 1;
}
if (!TEST_ptr(got = OPENSSL_malloc(got_len == 0 ? 1 : got_len))) {
t->err = "INTERNAL_ERROR";
goto err;
}
if (EVP_KDF_derive(expected->ctx, got, got_len, NULL) <= 0) {
t->err = "KDF_DERIVE_ERROR";
goto err;
}
if (!memory_err_compare(t, "KDF_MISMATCH",
expected->output, expected->output_len,
got, got_len))
goto err;
t->err = NULL;
err:
OPENSSL_free(got);
return 1;
}
static const EVP_TEST_METHOD kdf_test_method = {
"KDF",
kdf_test_init,
kdf_test_cleanup,
kdf_test_parse,
kdf_test_run
};
/**
** PKEY KDF TESTS
**/
typedef struct pkey_kdf_data_st {
/* Context for this operation */
EVP_PKEY_CTX *ctx;
/* Expected output */
unsigned char *output;
size_t output_len;
} PKEY_KDF_DATA;
/*
* Perform public key operation setup: lookup key, allocated ctx and call
* the appropriate initialisation function
*/
static int pkey_kdf_test_init(EVP_TEST *t, const char *name)
{
PKEY_KDF_DATA *kdata = NULL;
if (is_kdf_disabled(name)) {
TEST_info("skipping, '%s' is disabled", name);
t->skip = 1;
return 1;
}
if (!TEST_ptr(kdata = OPENSSL_zalloc(sizeof(*kdata))))
return 0;
kdata->ctx = EVP_PKEY_CTX_new_from_name(libctx, name, NULL);
if (kdata->ctx == NULL
|| EVP_PKEY_derive_init(kdata->ctx) <= 0)
goto err;
t->data = kdata;
return 1;
err:
EVP_PKEY_CTX_free(kdata->ctx);
OPENSSL_free(kdata);
return 0;
}
static void pkey_kdf_test_cleanup(EVP_TEST *t)
{
PKEY_KDF_DATA *kdata = t->data;
OPENSSL_free(kdata->output);
EVP_PKEY_CTX_free(kdata->ctx);
}
static int pkey_kdf_test_parse(EVP_TEST *t,
const char *keyword, const char *value)
{
PKEY_KDF_DATA *kdata = t->data;
if (strcmp(keyword, "Output") == 0)
return parse_bin(value, &kdata->output, &kdata->output_len);
if (strncmp(keyword, "Ctrl", 4) == 0)
return pkey_test_ctrl(t, kdata->ctx, value);
return 0;
}
static int pkey_kdf_test_run(EVP_TEST *t)
{
PKEY_KDF_DATA *expected = t->data;
unsigned char *got = NULL;
size_t got_len = 0;
if (fips_provider_version_eq(libctx, 3, 0, 0)) {
/* FIPS(3.0.0): can't deal with oversized output buffers #18533 */
got_len = expected->output_len;
} else {
/* Find out the KDF output size */
if (EVP_PKEY_derive(expected->ctx, NULL, &got_len) <= 0) {
t->err = "INTERNAL_ERROR";
goto err;
}
/*
* We may get an absurd output size, which signals that anything goes.
* If not, we specify a too big buffer for the output, to test that
* EVP_PKEY_derive() can cope with it.
*/
if (got_len == SIZE_MAX || got_len == 0)
got_len = expected->output_len;
else
got_len = expected->output_len * 2;
}
if (!TEST_ptr(got = OPENSSL_malloc(got_len == 0 ? 1 : got_len))) {
t->err = "INTERNAL_ERROR";
goto err;
}
if (EVP_PKEY_derive(expected->ctx, got, &got_len) <= 0) {
t->err = "KDF_DERIVE_ERROR";
goto err;
}
if (!TEST_mem_eq(expected->output, expected->output_len, got, got_len)) {
t->err = "KDF_MISMATCH";
goto err;
}
t->err = NULL;
err:
OPENSSL_free(got);
return 1;
}
static const EVP_TEST_METHOD pkey_kdf_test_method = {
"PKEYKDF",
pkey_kdf_test_init,
pkey_kdf_test_cleanup,
pkey_kdf_test_parse,
pkey_kdf_test_run
};
/**
** KEYPAIR TESTS
**/
typedef struct keypair_test_data_st {
EVP_PKEY *privk;
EVP_PKEY *pubk;
} KEYPAIR_TEST_DATA;
static int keypair_test_init(EVP_TEST *t, const char *pair)
{
KEYPAIR_TEST_DATA *data;
int rv = 0;
EVP_PKEY *pk = NULL, *pubk = NULL;
char *pub, *priv = NULL;
/* Split private and public names. */
if (!TEST_ptr(priv = OPENSSL_strdup(pair))
|| !TEST_ptr(pub = strchr(priv, ':'))) {
t->err = "PARSING_ERROR";
goto end;
}
*pub++ = '\0';
if (!TEST_true(find_key(&pk, priv, private_keys))) {
TEST_info("Can't find private key: %s", priv);
t->err = "MISSING_PRIVATE_KEY";
goto end;
}
if (!TEST_true(find_key(&pubk, pub, public_keys))) {
TEST_info("Can't find public key: %s", pub);
t->err = "MISSING_PUBLIC_KEY";
goto end;
}
if (pk == NULL && pubk == NULL) {
/* Both keys are listed but unsupported: skip this test */
t->skip = 1;
rv = 1;
goto end;
}
if (!TEST_ptr(data = OPENSSL_malloc(sizeof(*data))))
goto end;
data->privk = pk;
data->pubk = pubk;
t->data = data;
rv = 1;
t->err = NULL;
end:
OPENSSL_free(priv);
return rv;
}
static void keypair_test_cleanup(EVP_TEST *t)
{
OPENSSL_free(t->data);
t->data = NULL;
}
/*
* For tests that do not accept any custom keywords.
*/
static int void_test_parse(EVP_TEST *t, const char *keyword, const char *value)
{
return 0;
}
static int keypair_test_run(EVP_TEST *t)
{
int rv = 0;
const KEYPAIR_TEST_DATA *pair = t->data;
if (pair->privk == NULL || pair->pubk == NULL) {
/*
* this can only happen if only one of the keys is not set
* which means that one of them was unsupported while the
* other isn't: hence a key type mismatch.
*/
t->err = "KEYPAIR_TYPE_MISMATCH";
rv = 1;
goto end;
}
if ((rv = EVP_PKEY_eq(pair->privk, pair->pubk)) != 1 ) {
if ( 0 == rv ) {
t->err = "KEYPAIR_MISMATCH";
} else if ( -1 == rv ) {
t->err = "KEYPAIR_TYPE_MISMATCH";
} else if ( -2 == rv ) {
t->err = "UNSUPPORTED_KEY_COMPARISON";
} else {
TEST_error("Unexpected error in key comparison");
rv = 0;
goto end;
}
rv = 1;
goto end;
}
rv = 1;
t->err = NULL;
end:
return rv;
}
static const EVP_TEST_METHOD keypair_test_method = {
"PrivPubKeyPair",
keypair_test_init,
keypair_test_cleanup,
void_test_parse,
keypair_test_run
};
/**
** KEYGEN TEST
**/
typedef struct keygen_test_data_st {
EVP_PKEY_CTX *genctx; /* Keygen context to use */
char *keyname; /* Key name to store key or NULL */
} KEYGEN_TEST_DATA;
static int keygen_test_init(EVP_TEST *t, const char *alg)
{
KEYGEN_TEST_DATA *data;
EVP_PKEY_CTX *genctx;
int nid = OBJ_sn2nid(alg);
if (nid == NID_undef) {
nid = OBJ_ln2nid(alg);
if (nid == NID_undef)
return 0;
}
if (is_pkey_disabled(alg)) {
t->skip = 1;
return 1;
}
if (!TEST_ptr(genctx = EVP_PKEY_CTX_new_from_name(libctx, alg, NULL)))
goto err;
if (EVP_PKEY_keygen_init(genctx) <= 0) {
t->err = "KEYGEN_INIT_ERROR";
goto err;
}
if (!TEST_ptr(data = OPENSSL_malloc(sizeof(*data))))
goto err;
data->genctx = genctx;
data->keyname = NULL;
t->data = data;
t->err = NULL;
return 1;
err:
EVP_PKEY_CTX_free(genctx);
return 0;
}
static void keygen_test_cleanup(EVP_TEST *t)
{
KEYGEN_TEST_DATA *keygen = t->data;
EVP_PKEY_CTX_free(keygen->genctx);
OPENSSL_free(keygen->keyname);
OPENSSL_free(t->data);
t->data = NULL;
}
static int keygen_test_parse(EVP_TEST *t,
const char *keyword, const char *value)
{
KEYGEN_TEST_DATA *keygen = t->data;
if (strcmp(keyword, "KeyName") == 0)
return TEST_ptr(keygen->keyname = OPENSSL_strdup(value));
if (strcmp(keyword, "Ctrl") == 0)
return pkey_test_ctrl(t, keygen->genctx, value);
return 0;
}
static int keygen_test_run(EVP_TEST *t)
{
KEYGEN_TEST_DATA *keygen = t->data;
EVP_PKEY *pkey = NULL;
int rv = 1;
if (EVP_PKEY_keygen(keygen->genctx, &pkey) <= 0) {
t->err = "KEYGEN_GENERATE_ERROR";
goto err;
}
if (!evp_pkey_is_provided(pkey)) {
TEST_info("Warning: legacy key generated %s", keygen->keyname);
goto err;
}
if (keygen->keyname != NULL) {
KEY_LIST *key;
rv = 0;
if (find_key(NULL, keygen->keyname, private_keys)) {
TEST_info("Duplicate key %s", keygen->keyname);
goto err;
}
if (!TEST_ptr(key = OPENSSL_malloc(sizeof(*key))))
goto err;
key->name = keygen->keyname;
keygen->keyname = NULL;
key->key = pkey;
key->next = private_keys;
private_keys = key;
rv = 1;
} else {
EVP_PKEY_free(pkey);
}
t->err = NULL;
err:
return rv;
}
static const EVP_TEST_METHOD keygen_test_method = {
"KeyGen",
keygen_test_init,
keygen_test_cleanup,
keygen_test_parse,
keygen_test_run,
};
/**
** DIGEST SIGN+VERIFY TESTS
**/
typedef struct {
int is_verify; /* Set to 1 if verifying */
int is_oneshot; /* Set to 1 for one shot operation */
const EVP_MD *md; /* Digest to use */
EVP_MD_CTX *ctx; /* Digest context */
EVP_PKEY_CTX *pctx;
STACK_OF(EVP_TEST_BUFFER) *input; /* Input data: streaming */
unsigned char *osin; /* Input data if one shot */
size_t osin_len; /* Input length data if one shot */
unsigned char *output; /* Expected output */
size_t output_len; /* Expected output length */
} DIGESTSIGN_DATA;
static int digestsigver_test_init(EVP_TEST *t, const char *alg, int is_verify,
int is_oneshot)
{
const EVP_MD *md = NULL;
DIGESTSIGN_DATA *mdat;
if (strcmp(alg, "NULL") != 0) {
if (is_digest_disabled(alg)) {
t->skip = 1;
return 1;
}
md = EVP_get_digestbyname(alg);
if (md == NULL)
return 0;
}
if (!TEST_ptr(mdat = OPENSSL_zalloc(sizeof(*mdat))))
return 0;
mdat->md = md;
if (!TEST_ptr(mdat->ctx = EVP_MD_CTX_new())) {
OPENSSL_free(mdat);
return 0;
}
mdat->is_verify = is_verify;
mdat->is_oneshot = is_oneshot;
t->data = mdat;
return 1;
}
static int digestsign_test_init(EVP_TEST *t, const char *alg)
{
return digestsigver_test_init(t, alg, 0, 0);
}
static void digestsigver_test_cleanup(EVP_TEST *t)
{
DIGESTSIGN_DATA *mdata = t->data;
EVP_MD_CTX_free(mdata->ctx);
sk_EVP_TEST_BUFFER_pop_free(mdata->input, evp_test_buffer_free);
OPENSSL_free(mdata->osin);
OPENSSL_free(mdata->output);
OPENSSL_free(mdata);
t->data = NULL;
}
static int digestsigver_test_parse(EVP_TEST *t,
const char *keyword, const char *value)
{
DIGESTSIGN_DATA *mdata = t->data;
if (strcmp(keyword, "Key") == 0) {
EVP_PKEY *pkey = NULL;
int rv = 0;
const char *name = mdata->md == NULL ? NULL : EVP_MD_get0_name(mdata->md);
if (mdata->is_verify)
rv = find_key(&pkey, value, public_keys);
if (rv == 0)
rv = find_key(&pkey, value, private_keys);
if (rv == 0 || pkey == NULL) {
t->skip = 1;
return 1;
}
if (mdata->is_verify) {
if (!EVP_DigestVerifyInit_ex(mdata->ctx, &mdata->pctx, name, libctx,
NULL, pkey, NULL))
t->err = "DIGESTVERIFYINIT_ERROR";
return 1;
}
if (!EVP_DigestSignInit_ex(mdata->ctx, &mdata->pctx, name, libctx, NULL,
pkey, NULL))
t->err = "DIGESTSIGNINIT_ERROR";
return 1;
}
if (strcmp(keyword, "Input") == 0) {
if (mdata->is_oneshot)
return parse_bin(value, &mdata->osin, &mdata->osin_len);
return evp_test_buffer_append(value, &mdata->input);
}
if (strcmp(keyword, "Output") == 0)
return parse_bin(value, &mdata->output, &mdata->output_len);
if (!mdata->is_oneshot) {
if (strcmp(keyword, "Count") == 0)
return evp_test_buffer_set_count(value, mdata->input);
if (strcmp(keyword, "Ncopy") == 0)
return evp_test_buffer_ncopy(value, mdata->input);
}
if (strcmp(keyword, "Ctrl") == 0) {
if (mdata->pctx == NULL)
return -1;
return pkey_test_ctrl(t, mdata->pctx, value);
}
return 0;
}
static int digestsign_update_fn(void *ctx, const unsigned char *buf,
size_t buflen)
{
return EVP_DigestSignUpdate(ctx, buf, buflen);
}
static int digestsign_test_run(EVP_TEST *t)
{
DIGESTSIGN_DATA *expected = t->data;
unsigned char *got = NULL;
size_t got_len;
if (!evp_test_buffer_do(expected->input, digestsign_update_fn,
expected->ctx)) {
t->err = "DIGESTUPDATE_ERROR";
goto err;
}
if (!EVP_DigestSignFinal(expected->ctx, NULL, &got_len)) {
t->err = "DIGESTSIGNFINAL_LENGTH_ERROR";
goto err;
}
if (!TEST_ptr(got = OPENSSL_malloc(got_len))) {
t->err = "MALLOC_FAILURE";
goto err;
}
got_len *= 2;
if (!EVP_DigestSignFinal(expected->ctx, got, &got_len)) {
t->err = "DIGESTSIGNFINAL_ERROR";
goto err;
}
if (!memory_err_compare(t, "SIGNATURE_MISMATCH",
expected->output, expected->output_len,
got, got_len))
goto err;
t->err = NULL;
err:
OPENSSL_free(got);
return 1;
}
static const EVP_TEST_METHOD digestsign_test_method = {
"DigestSign",
digestsign_test_init,
digestsigver_test_cleanup,
digestsigver_test_parse,
digestsign_test_run
};
static int digestverify_test_init(EVP_TEST *t, const char *alg)
{
return digestsigver_test_init(t, alg, 1, 0);
}
static int digestverify_update_fn(void *ctx, const unsigned char *buf,
size_t buflen)
{
return EVP_DigestVerifyUpdate(ctx, buf, buflen);
}
static int digestverify_test_run(EVP_TEST *t)
{
DIGESTSIGN_DATA *mdata = t->data;
if (!evp_test_buffer_do(mdata->input, digestverify_update_fn, mdata->ctx)) {
t->err = "DIGESTUPDATE_ERROR";
return 1;
}
if (EVP_DigestVerifyFinal(mdata->ctx, mdata->output,
mdata->output_len) <= 0)
t->err = "VERIFY_ERROR";
return 1;
}
static const EVP_TEST_METHOD digestverify_test_method = {
"DigestVerify",
digestverify_test_init,
digestsigver_test_cleanup,
digestsigver_test_parse,
digestverify_test_run
};
static int oneshot_digestsign_test_init(EVP_TEST *t, const char *alg)
{
return digestsigver_test_init(t, alg, 0, 1);
}
static int oneshot_digestsign_test_run(EVP_TEST *t)
{
DIGESTSIGN_DATA *expected = t->data;
unsigned char *got = NULL;
size_t got_len;
if (!EVP_DigestSign(expected->ctx, NULL, &got_len,
expected->osin, expected->osin_len)) {
t->err = "DIGESTSIGN_LENGTH_ERROR";
goto err;
}
if (!TEST_ptr(got = OPENSSL_malloc(got_len))) {
t->err = "MALLOC_FAILURE";
goto err;
}
got_len *= 2;
if (!EVP_DigestSign(expected->ctx, got, &got_len,
expected->osin, expected->osin_len)) {
t->err = "DIGESTSIGN_ERROR";
goto err;
}
if (!memory_err_compare(t, "SIGNATURE_MISMATCH",
expected->output, expected->output_len,
got, got_len))
goto err;
t->err = NULL;
err:
OPENSSL_free(got);
return 1;
}
static const EVP_TEST_METHOD oneshot_digestsign_test_method = {
"OneShotDigestSign",
oneshot_digestsign_test_init,
digestsigver_test_cleanup,
digestsigver_test_parse,
oneshot_digestsign_test_run
};
static int oneshot_digestverify_test_init(EVP_TEST *t, const char *alg)
{
return digestsigver_test_init(t, alg, 1, 1);
}
static int oneshot_digestverify_test_run(EVP_TEST *t)
{
DIGESTSIGN_DATA *mdata = t->data;
if (EVP_DigestVerify(mdata->ctx, mdata->output, mdata->output_len,
mdata->osin, mdata->osin_len) <= 0)
t->err = "VERIFY_ERROR";
return 1;
}
static const EVP_TEST_METHOD oneshot_digestverify_test_method = {
"OneShotDigestVerify",
oneshot_digestverify_test_init,
digestsigver_test_cleanup,
digestsigver_test_parse,
oneshot_digestverify_test_run
};
/**
** PARSING AND DISPATCH
**/
static const EVP_TEST_METHOD *evp_test_list[] = {
&rand_test_method,
&cipher_test_method,
&digest_test_method,
&digestsign_test_method,
&digestverify_test_method,
&encode_test_method,
&kdf_test_method,
&pkey_kdf_test_method,
&keypair_test_method,
&keygen_test_method,
&mac_test_method,
&oneshot_digestsign_test_method,
&oneshot_digestverify_test_method,
&pbe_test_method,
&pdecrypt_test_method,
&pderive_test_method,
&psign_test_method,
&pverify_recover_test_method,
&pverify_test_method,
NULL
};
static const EVP_TEST_METHOD *find_test(const char *name)
{
const EVP_TEST_METHOD **tt;
for (tt = evp_test_list; *tt; tt++) {
if (strcmp(name, (*tt)->name) == 0)
return *tt;
}
return NULL;
}
static void clear_test(EVP_TEST *t)
{
test_clearstanza(&t->s);
ERR_clear_error();
if (t->data != NULL) {
if (t->meth != NULL)
t->meth->cleanup(t);
OPENSSL_free(t->data);
t->data = NULL;
}
OPENSSL_free(t->expected_err);
t->expected_err = NULL;
OPENSSL_free(t->reason);
t->reason = NULL;
/* Text literal. */
t->err = NULL;
t->skip = 0;
t->meth = NULL;
}
/* Check for errors in the test structure; return 1 if okay, else 0. */
static int check_test_error(EVP_TEST *t)
{
unsigned long err;
const char *reason;
if (t->err == NULL && t->expected_err == NULL)
return 1;
if (t->err != NULL && t->expected_err == NULL) {
if (t->aux_err != NULL) {
TEST_info("%s:%d: Source of above error (%s); unexpected error %s",
t->s.test_file, t->s.start, t->aux_err, t->err);
} else {
TEST_info("%s:%d: Source of above error; unexpected error %s",
t->s.test_file, t->s.start, t->err);
}
return 0;
}
if (t->err == NULL && t->expected_err != NULL) {
TEST_info("%s:%d: Succeeded but was expecting %s",
t->s.test_file, t->s.start, t->expected_err);
return 0;
}
if (strcmp(t->err, t->expected_err) != 0) {
TEST_info("%s:%d: Expected %s got %s",
t->s.test_file, t->s.start, t->expected_err, t->err);
return 0;
}
if (t->reason == NULL)
return 1;
if (t->reason == NULL) {
TEST_info("%s:%d: Test is missing function or reason code",
t->s.test_file, t->s.start);
return 0;
}
err = ERR_peek_error();
if (err == 0) {
TEST_info("%s:%d: Expected error \"%s\" not set",
t->s.test_file, t->s.start, t->reason);
return 0;
}
reason = ERR_reason_error_string(err);
if (reason == NULL) {
TEST_info("%s:%d: Expected error \"%s\", no strings available."
" Assuming ok.",
t->s.test_file, t->s.start, t->reason);
return 1;
}
if (strcmp(reason, t->reason) == 0)
return 1;
TEST_info("%s:%d: Expected error \"%s\", got \"%s\"",
t->s.test_file, t->s.start, t->reason, reason);
return 0;
}
/* Run a parsed test. Log a message and return 0 on error. */
static int run_test(EVP_TEST *t)
{
if (t->meth == NULL)
return 1;
t->s.numtests++;
if (t->skip) {
t->s.numskip++;
} else {
/* run the test */
if (t->err == NULL && t->meth->run_test(t) != 1) {
TEST_info("%s:%d %s error",
t->s.test_file, t->s.start, t->meth->name);
return 0;
}
if (!check_test_error(t)) {
TEST_openssl_errors();
t->s.errors++;
}
}
/* clean it up */
return 1;
}
static int find_key(EVP_PKEY **ppk, const char *name, KEY_LIST *lst)
{
for (; lst != NULL; lst = lst->next) {
if (strcmp(lst->name, name) == 0) {
if (ppk != NULL)
*ppk = lst->key;
return 1;
}
}
return 0;
}
static void free_key_list(KEY_LIST *lst)
{
while (lst != NULL) {
KEY_LIST *next = lst->next;
EVP_PKEY_free(lst->key);
OPENSSL_free(lst->name);
OPENSSL_free(lst);
lst = next;
}
}
/*
* Is the key type an unsupported algorithm?
*/
static int key_unsupported(void)
{
long err = ERR_peek_last_error();
int lib = ERR_GET_LIB(err);
long reason = ERR_GET_REASON(err);
if ((lib == ERR_LIB_EVP && reason == EVP_R_UNSUPPORTED_ALGORITHM)
|| (lib == ERR_LIB_EVP && reason == EVP_R_DECODE_ERROR)
|| reason == ERR_R_UNSUPPORTED) {
ERR_clear_error();
return 1;
}
#ifndef OPENSSL_NO_EC
/*
* If EC support is enabled we should catch also EC_R_UNKNOWN_GROUP as an
* hint to an unsupported algorithm/curve (e.g. if binary EC support is
* disabled).
*/
if (lib == ERR_LIB_EC
&& (reason == EC_R_UNKNOWN_GROUP
|| reason == EC_R_INVALID_CURVE)) {
ERR_clear_error();
return 1;
}
#endif /* OPENSSL_NO_EC */
return 0;
}
/* NULL out the value from |pp| but return it. This "steals" a pointer. */
static char *take_value(PAIR *pp)
{
char *p = pp->value;
pp->value = NULL;
return p;
}
#if !defined(OPENSSL_NO_FIPS_SECURITYCHECKS)
static int securitycheck_enabled(void)
{
static int enabled = -1;
if (enabled == -1) {
if (OSSL_PROVIDER_available(libctx, "fips")) {
OSSL_PARAM params[2];
OSSL_PROVIDER *prov = NULL;
int check = 1;
prov = OSSL_PROVIDER_load(libctx, "fips");
if (prov != NULL) {
params[0] =
OSSL_PARAM_construct_int(OSSL_PROV_PARAM_SECURITY_CHECKS,
&check);
params[1] = OSSL_PARAM_construct_end();
OSSL_PROVIDER_get_params(prov, params);
OSSL_PROVIDER_unload(prov);
}
enabled = check;
return enabled;
}
enabled = 0;
}
return enabled;
}
#endif
/*
* Return 1 if one of the providers named in the string is available.
* The provider names are separated with whitespace.
* NOTE: destructive function, it inserts '\0' after each provider name.
*/
static int prov_available(char *providers)
{
char *p;
int more = 1;
while (more) {
for (; isspace((unsigned char)(*providers)); providers++)
continue;
if (*providers == '\0')
break; /* End of the road */
for (p = providers; *p != '\0' && !isspace((unsigned char)(*p)); p++)
continue;
if (*p == '\0')
more = 0;
else
*p = '\0';
if (OSSL_PROVIDER_available(libctx, providers))
return 1; /* Found one */
}
return 0;
}
/* Read and parse one test. Return 0 if failure, 1 if okay. */
static int parse(EVP_TEST *t)
{
KEY_LIST *key, **klist;
EVP_PKEY *pkey;
PAIR *pp;
int i, j, skipped = 0;
top:
do {
if (BIO_eof(t->s.fp))
return EOF;
clear_test(t);
if (!test_readstanza(&t->s))
return 0;
} while (t->s.numpairs == 0);
pp = &t->s.pairs[0];
/* Are we adding a key? */
klist = NULL;
pkey = NULL;
start:
if (strcmp(pp->key, "PrivateKey") == 0) {
pkey = PEM_read_bio_PrivateKey_ex(t->s.key, NULL, 0, NULL, libctx, NULL);
if (pkey == NULL && !key_unsupported()) {
EVP_PKEY_free(pkey);
TEST_info("Can't read private key %s", pp->value);
TEST_openssl_errors();
return 0;
}
klist = &private_keys;
} else if (strcmp(pp->key, "PublicKey") == 0) {
pkey = PEM_read_bio_PUBKEY_ex(t->s.key, NULL, 0, NULL, libctx, NULL);
if (pkey == NULL && !key_unsupported()) {
EVP_PKEY_free(pkey);
TEST_info("Can't read public key %s", pp->value);
TEST_openssl_errors();
return 0;
}
klist = &public_keys;
} else if (strcmp(pp->key, "PrivateKeyRaw") == 0
|| strcmp(pp->key, "PublicKeyRaw") == 0 ) {
char *strnid = NULL, *keydata = NULL;
unsigned char *keybin;
size_t keylen;
int nid;
if (strcmp(pp->key, "PrivateKeyRaw") == 0)
klist = &private_keys;
else
klist = &public_keys;
strnid = strchr(pp->value, ':');
if (strnid != NULL) {
*strnid++ = '\0';
keydata = strchr(strnid, ':');
if (keydata != NULL)
*keydata++ = '\0';
}
if (keydata == NULL) {
TEST_info("Failed to parse %s value", pp->key);
return 0;
}
nid = OBJ_txt2nid(strnid);
if (nid == NID_undef) {
TEST_info("Unrecognised algorithm NID");
return 0;
}
if (!parse_bin(keydata, &keybin, &keylen)) {
TEST_info("Failed to create binary key");
return 0;
}
if (klist == &private_keys)
pkey = EVP_PKEY_new_raw_private_key_ex(libctx, strnid, NULL, keybin,
keylen);
else
pkey = EVP_PKEY_new_raw_public_key_ex(libctx, strnid, NULL, keybin,
keylen);
if (pkey == NULL && !key_unsupported()) {
TEST_info("Can't read %s data", pp->key);
OPENSSL_free(keybin);
TEST_openssl_errors();
return 0;
}
OPENSSL_free(keybin);
} else if (strcmp(pp->key, "Availablein") == 0) {
if (!prov_available(pp->value)) {
TEST_info("skipping, '%s' provider not available: %s:%d",
pp->value, t->s.test_file, t->s.start);
t->skip = 1;
return 0;
}
skipped++;
pp++;
goto start;
} else if (strcmp(pp->key, "FIPSversion") == 0) {
if (prov_available("fips")) {
j = fips_provider_version_match(libctx, pp->value);
if (j < 0) {
TEST_info("Line %d: error matching FIPS versions\n", t->s.curr);
return 0;
} else if (j == 0) {
TEST_info("skipping, FIPS provider incompatible version: %s:%d",
t->s.test_file, t->s.start);
t->skip = 1;
return 0;
}
}
skipped++;
pp++;
goto start;
}
/* If we have a key add to list */
if (klist != NULL) {
if (find_key(NULL, pp->value, *klist)) {
TEST_info("Duplicate key %s", pp->value);
return 0;
}
if (!TEST_ptr(key = OPENSSL_malloc(sizeof(*key))))
return 0;
key->name = take_value(pp);
key->key = pkey;
key->next = *klist;
*klist = key;
/* Go back and start a new stanza. */
if ((t->s.numpairs - skipped) != 1)
TEST_info("Line %d: missing blank line\n", t->s.curr);
goto top;
}
/* Find the test, based on first keyword. */
if (!TEST_ptr(t->meth = find_test(pp->key)))
return 0;
if (!t->meth->init(t, pp->value)) {
TEST_error("unknown %s: %s\n", pp->key, pp->value);
return 0;
}
if (t->skip == 1) {
/* TEST_info("skipping %s %s", pp->key, pp->value); */
return 0;
}
for (pp++, i = 1; i < (t->s.numpairs - skipped); pp++, i++) {
if (strcmp(pp->key, "Securitycheck") == 0) {
#if defined(OPENSSL_NO_FIPS_SECURITYCHECKS)
#else
if (!securitycheck_enabled())
#endif
{
TEST_info("skipping, Securitycheck is disabled: %s:%d",
t->s.test_file, t->s.start);
t->skip = 1;
return 0;
}
} else if (strcmp(pp->key, "Availablein") == 0) {
TEST_info("Line %d: 'Availablein' should be the first option",
t->s.curr);
return 0;
} else if (strcmp(pp->key, "Result") == 0) {
if (t->expected_err != NULL) {
TEST_info("Line %d: multiple result lines", t->s.curr);
return 0;
}
t->expected_err = take_value(pp);
} else if (strcmp(pp->key, "Function") == 0) {
/* Ignore old line. */
} else if (strcmp(pp->key, "Reason") == 0) {
if (t->reason != NULL) {
TEST_info("Line %d: multiple reason lines", t->s.curr);
return 0;
}
t->reason = take_value(pp);
} else {
/* Must be test specific line: try to parse it */
int rv = t->meth->parse(t, pp->key, pp->value);
if (rv == 0) {
TEST_info("Line %d: unknown keyword %s", t->s.curr, pp->key);
return 0;
}
if (rv < 0) {
TEST_info("Line %d: error processing keyword %s = %s\n",
t->s.curr, pp->key, pp->value);
return 0;
}
}
}
return 1;
}
static int run_file_tests(int i)
{
EVP_TEST *t;
const char *testfile = test_get_argument(i);
int c;
if (!TEST_ptr(t = OPENSSL_zalloc(sizeof(*t))))
return 0;
if (!test_start_file(&t->s, testfile)) {
OPENSSL_free(t);
return 0;
}
while (!BIO_eof(t->s.fp)) {
c = parse(t);
if (t->skip) {
t->s.numskip++;
continue;
}
if (c == 0 || !run_test(t)) {
t->s.errors++;
break;
}
}
test_end_file(&t->s);
clear_test(t);
free_key_list(public_keys);
free_key_list(private_keys);
BIO_free(t->s.key);
c = t->s.errors;
OPENSSL_free(t);
return c == 0;
}
const OPTIONS *test_get_options(void)
{
static const OPTIONS test_options[] = {
OPT_TEST_OPTIONS_WITH_EXTRA_USAGE("[file...]\n"),
{ "config", OPT_CONFIG_FILE, '<',
"The configuration file to use for the libctx" },
{ OPT_HELP_STR, 1, '-', "file\tFile to run tests on.\n" },
{ NULL }
};
return test_options;
}
int setup_tests(void)
{
size_t n;
char *config_file = NULL;
OPTION_CHOICE o;
while ((o = opt_next()) != OPT_EOF) {
switch (o) {
case OPT_CONFIG_FILE:
config_file = opt_arg();
break;
case OPT_TEST_CASES:
break;
default:
case OPT_ERR:
return 0;
}
}
/*
* Load the provider via configuration into the created library context.
* Load the 'null' provider into the default library context to ensure that
* the tests do not fallback to using the default provider.
*/
if (!test_get_libctx(&libctx, &prov_null, config_file, NULL, NULL))
return 0;
n = test_get_argument_count();
if (n == 0)
return 0;
ADD_ALL_TESTS(run_file_tests, n);
return 1;
}
void cleanup_tests(void)
{
OSSL_PROVIDER_unload(prov_null);
OSSL_LIB_CTX_free(libctx);
}
#define STR_STARTS_WITH(str, pre) OPENSSL_strncasecmp(pre, str, strlen(pre)) == 0
#define STR_ENDS_WITH(str, pre) \
strlen(str) < strlen(pre) ? 0 : (OPENSSL_strcasecmp(pre, str + strlen(str) - strlen(pre)) == 0)
static int is_digest_disabled(const char *name)
{
#ifdef OPENSSL_NO_BLAKE2
if (STR_STARTS_WITH(name, "BLAKE"))
return 1;
#endif
#ifdef OPENSSL_NO_MD2
if (OPENSSL_strcasecmp(name, "MD2") == 0)
return 1;
#endif
#ifdef OPENSSL_NO_MDC2
if (OPENSSL_strcasecmp(name, "MDC2") == 0)
return 1;
#endif
#ifdef OPENSSL_NO_MD4
if (OPENSSL_strcasecmp(name, "MD4") == 0)
return 1;
#endif
#ifdef OPENSSL_NO_MD5
if (OPENSSL_strcasecmp(name, "MD5") == 0)
return 1;
#endif
#ifdef OPENSSL_NO_RMD160
if (OPENSSL_strcasecmp(name, "RIPEMD160") == 0)
return 1;
#endif
#ifdef OPENSSL_NO_SM3
if (OPENSSL_strcasecmp(name, "SM3") == 0)
return 1;
#endif
#ifdef OPENSSL_NO_WHIRLPOOL
if (OPENSSL_strcasecmp(name, "WHIRLPOOL") == 0)
return 1;
#endif
return 0;
}
static int is_pkey_disabled(const char *name)
{
#ifdef OPENSSL_NO_EC
if (STR_STARTS_WITH(name, "EC"))
return 1;
#endif
#ifdef OPENSSL_NO_DH
if (STR_STARTS_WITH(name, "DH"))
return 1;
#endif
#ifdef OPENSSL_NO_DSA
if (STR_STARTS_WITH(name, "DSA"))
return 1;
#endif
return 0;
}
static int is_mac_disabled(const char *name)
{
#ifdef OPENSSL_NO_BLAKE2
if (STR_STARTS_WITH(name, "BLAKE2BMAC")
|| STR_STARTS_WITH(name, "BLAKE2SMAC"))
return 1;
#endif
#ifdef OPENSSL_NO_CMAC
if (STR_STARTS_WITH(name, "CMAC"))
return 1;
#endif
#ifdef OPENSSL_NO_POLY1305
if (STR_STARTS_WITH(name, "Poly1305"))
return 1;
#endif
#ifdef OPENSSL_NO_SIPHASH
if (STR_STARTS_WITH(name, "SipHash"))
return 1;
#endif
return 0;
}
static int is_kdf_disabled(const char *name)
{
#ifdef OPENSSL_NO_SCRYPT
if (STR_ENDS_WITH(name, "SCRYPT"))
return 1;
#endif
return 0;
}
static int is_cipher_disabled(const char *name)
{
#ifdef OPENSSL_NO_ARIA
if (STR_STARTS_WITH(name, "ARIA"))
return 1;
#endif
#ifdef OPENSSL_NO_BF
if (STR_STARTS_WITH(name, "BF"))
return 1;
#endif
#ifdef OPENSSL_NO_CAMELLIA
if (STR_STARTS_WITH(name, "CAMELLIA"))
return 1;
#endif
#ifdef OPENSSL_NO_CAST
if (STR_STARTS_WITH(name, "CAST"))
return 1;
#endif
#ifdef OPENSSL_NO_CHACHA
if (STR_STARTS_WITH(name, "CHACHA"))
return 1;
#endif
#ifdef OPENSSL_NO_POLY1305
if (STR_ENDS_WITH(name, "Poly1305"))
return 1;
#endif
#ifdef OPENSSL_NO_DES
if (STR_STARTS_WITH(name, "DES"))
return 1;
if (STR_ENDS_WITH(name, "3DESwrap"))
return 1;
#endif
#ifdef OPENSSL_NO_OCB
if (STR_ENDS_WITH(name, "OCB"))
return 1;
#endif
#ifdef OPENSSL_NO_IDEA
if (STR_STARTS_WITH(name, "IDEA"))
return 1;
#endif
#ifdef OPENSSL_NO_RC2
if (STR_STARTS_WITH(name, "RC2"))
return 1;
#endif
#ifdef OPENSSL_NO_RC4
if (STR_STARTS_WITH(name, "RC4"))
return 1;
#endif
#ifdef OPENSSL_NO_RC5
if (STR_STARTS_WITH(name, "RC5"))
return 1;
#endif
#ifdef OPENSSL_NO_SEED
if (STR_STARTS_WITH(name, "SEED"))
return 1;
#endif
#ifdef OPENSSL_NO_SIV
if (STR_ENDS_WITH(name, "SIV"))
return 1;
#endif
#ifdef OPENSSL_NO_SM4
if (STR_STARTS_WITH(name, "SM4"))
return 1;
#endif
return 0;
}
diff --git a/crypto/openssl/test/helpers/ssltestlib.c b/crypto/openssl/test/helpers/ssltestlib.c
index ef4a6177aa7d..b0ef7d719c53 100644
--- a/crypto/openssl/test/helpers/ssltestlib.c
+++ b/crypto/openssl/test/helpers/ssltestlib.c
@@ -1,1184 +1,1217 @@
/*
- * Copyright 2016-2023 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2016-2024 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 ENGINE APIs for legacy purposes
+ * when the deprecated calls are not hidden
+ */
+#ifndef OPENSSL_NO_DEPRECATED_3_0
+# define OPENSSL_SUPPRESS_DEPRECATED
+#endif
+
#include <string.h>
+#include <openssl/engine.h>
#include "internal/nelem.h"
#include "ssltestlib.h"
#include "../testutil.h"
#include "e_os.h" /* for ossl_sleep() etc. */
#ifdef OPENSSL_SYS_UNIX
# include <unistd.h>
# ifndef OPENSSL_NO_KTLS
# include <netinet/in.h>
# include <netinet/in.h>
# include <arpa/inet.h>
# include <sys/socket.h>
# include <unistd.h>
# include <fcntl.h>
# endif
#endif
static int tls_dump_new(BIO *bi);
static int tls_dump_free(BIO *a);
static int tls_dump_read(BIO *b, char *out, int outl);
static int tls_dump_write(BIO *b, const char *in, int inl);
static long tls_dump_ctrl(BIO *b, int cmd, long num, void *ptr);
static int tls_dump_gets(BIO *bp, char *buf, int size);
static int tls_dump_puts(BIO *bp, const char *str);
/* Choose a sufficiently large type likely to be unused for this custom BIO */
#define BIO_TYPE_TLS_DUMP_FILTER (0x80 | BIO_TYPE_FILTER)
#define BIO_TYPE_MEMPACKET_TEST 0x81
#define BIO_TYPE_ALWAYS_RETRY 0x82
static BIO_METHOD *method_tls_dump = NULL;
static BIO_METHOD *meth_mem = NULL;
static BIO_METHOD *meth_always_retry = NULL;
static int retry_err = -1;
/* Note: Not thread safe! */
const BIO_METHOD *bio_f_tls_dump_filter(void)
{
if (method_tls_dump == NULL) {
method_tls_dump = BIO_meth_new(BIO_TYPE_TLS_DUMP_FILTER,
"TLS dump filter");
if ( method_tls_dump == NULL
|| !BIO_meth_set_write(method_tls_dump, tls_dump_write)
|| !BIO_meth_set_read(method_tls_dump, tls_dump_read)
|| !BIO_meth_set_puts(method_tls_dump, tls_dump_puts)
|| !BIO_meth_set_gets(method_tls_dump, tls_dump_gets)
|| !BIO_meth_set_ctrl(method_tls_dump, tls_dump_ctrl)
|| !BIO_meth_set_create(method_tls_dump, tls_dump_new)
|| !BIO_meth_set_destroy(method_tls_dump, tls_dump_free))
return NULL;
}
return method_tls_dump;
}
void bio_f_tls_dump_filter_free(void)
{
BIO_meth_free(method_tls_dump);
}
static int tls_dump_new(BIO *bio)
{
BIO_set_init(bio, 1);
return 1;
}
static int tls_dump_free(BIO *bio)
{
BIO_set_init(bio, 0);
return 1;
}
static void copy_flags(BIO *bio)
{
int flags;
BIO *next = BIO_next(bio);
flags = BIO_test_flags(next, BIO_FLAGS_SHOULD_RETRY | BIO_FLAGS_RWS);
BIO_clear_flags(bio, BIO_FLAGS_SHOULD_RETRY | BIO_FLAGS_RWS);
BIO_set_flags(bio, flags);
}
#define RECORD_CONTENT_TYPE 0
#define RECORD_VERSION_HI 1
#define RECORD_VERSION_LO 2
#define RECORD_EPOCH_HI 3
#define RECORD_EPOCH_LO 4
#define RECORD_SEQUENCE_START 5
#define RECORD_SEQUENCE_END 10
#define RECORD_LEN_HI 11
#define RECORD_LEN_LO 12
#define MSG_TYPE 0
#define MSG_LEN_HI 1
#define MSG_LEN_MID 2
#define MSG_LEN_LO 3
#define MSG_SEQ_HI 4
#define MSG_SEQ_LO 5
#define MSG_FRAG_OFF_HI 6
#define MSG_FRAG_OFF_MID 7
#define MSG_FRAG_OFF_LO 8
#define MSG_FRAG_LEN_HI 9
#define MSG_FRAG_LEN_MID 10
#define MSG_FRAG_LEN_LO 11
static void dump_data(const char *data, int len)
{
int rem, i, content, reclen, msglen, fragoff, fraglen, epoch;
unsigned char *rec;
printf("---- START OF PACKET ----\n");
rem = len;
rec = (unsigned char *)data;
while (rem > 0) {
if (rem != len)
printf("*\n");
printf("*---- START OF RECORD ----\n");
if (rem < DTLS1_RT_HEADER_LENGTH) {
printf("*---- RECORD TRUNCATED ----\n");
break;
}
content = rec[RECORD_CONTENT_TYPE];
printf("** Record Content-type: %d\n", content);
printf("** Record Version: %02x%02x\n",
rec[RECORD_VERSION_HI], rec[RECORD_VERSION_LO]);
epoch = (rec[RECORD_EPOCH_HI] << 8) | rec[RECORD_EPOCH_LO];
printf("** Record Epoch: %d\n", epoch);
printf("** Record Sequence: ");
for (i = RECORD_SEQUENCE_START; i <= RECORD_SEQUENCE_END; i++)
printf("%02x", rec[i]);
reclen = (rec[RECORD_LEN_HI] << 8) | rec[RECORD_LEN_LO];
printf("\n** Record Length: %d\n", reclen);
/* Now look at message */
rec += DTLS1_RT_HEADER_LENGTH;
rem -= DTLS1_RT_HEADER_LENGTH;
if (content == SSL3_RT_HANDSHAKE) {
printf("**---- START OF HANDSHAKE MESSAGE FRAGMENT ----\n");
if (epoch > 0) {
printf("**---- HANDSHAKE MESSAGE FRAGMENT ENCRYPTED ----\n");
} else if (rem < DTLS1_HM_HEADER_LENGTH
|| reclen < DTLS1_HM_HEADER_LENGTH) {
printf("**---- HANDSHAKE MESSAGE FRAGMENT TRUNCATED ----\n");
} else {
printf("*** Message Type: %d\n", rec[MSG_TYPE]);
msglen = (rec[MSG_LEN_HI] << 16) | (rec[MSG_LEN_MID] << 8)
| rec[MSG_LEN_LO];
printf("*** Message Length: %d\n", msglen);
printf("*** Message sequence: %d\n",
(rec[MSG_SEQ_HI] << 8) | rec[MSG_SEQ_LO]);
fragoff = (rec[MSG_FRAG_OFF_HI] << 16)
| (rec[MSG_FRAG_OFF_MID] << 8)
| rec[MSG_FRAG_OFF_LO];
printf("*** Message Fragment offset: %d\n", fragoff);
fraglen = (rec[MSG_FRAG_LEN_HI] << 16)
| (rec[MSG_FRAG_LEN_MID] << 8)
| rec[MSG_FRAG_LEN_LO];
printf("*** Message Fragment len: %d\n", fraglen);
if (fragoff + fraglen > msglen)
printf("***---- HANDSHAKE MESSAGE FRAGMENT INVALID ----\n");
else if (reclen < fraglen)
printf("**---- HANDSHAKE MESSAGE FRAGMENT TRUNCATED ----\n");
else
printf("**---- END OF HANDSHAKE MESSAGE FRAGMENT ----\n");
}
}
if (rem < reclen) {
printf("*---- RECORD TRUNCATED ----\n");
rem = 0;
} else {
rec += reclen;
rem -= reclen;
printf("*---- END OF RECORD ----\n");
}
}
printf("---- END OF PACKET ----\n\n");
fflush(stdout);
}
static int tls_dump_read(BIO *bio, char *out, int outl)
{
int ret;
BIO *next = BIO_next(bio);
ret = BIO_read(next, out, outl);
copy_flags(bio);
if (ret > 0) {
dump_data(out, ret);
}
return ret;
}
static int tls_dump_write(BIO *bio, const char *in, int inl)
{
int ret;
BIO *next = BIO_next(bio);
ret = BIO_write(next, in, inl);
copy_flags(bio);
return ret;
}
static long tls_dump_ctrl(BIO *bio, int cmd, long num, void *ptr)
{
long ret;
BIO *next = BIO_next(bio);
if (next == NULL)
return 0;
switch (cmd) {
case BIO_CTRL_DUP:
ret = 0L;
break;
default:
ret = BIO_ctrl(next, cmd, num, ptr);
break;
}
return ret;
}
static int tls_dump_gets(BIO *bio, char *buf, int size)
{
/* We don't support this - not needed anyway */
return -1;
}
static int tls_dump_puts(BIO *bio, const char *str)
{
return tls_dump_write(bio, str, strlen(str));
}
struct mempacket_st {
unsigned char *data;
int len;
unsigned int num;
unsigned int type;
};
static void mempacket_free(MEMPACKET *pkt)
{
if (pkt->data != NULL)
OPENSSL_free(pkt->data);
OPENSSL_free(pkt);
}
typedef struct mempacket_test_ctx_st {
STACK_OF(MEMPACKET) *pkts;
unsigned int epoch;
unsigned int currrec;
unsigned int currpkt;
unsigned int lastpkt;
unsigned int injected;
unsigned int noinject;
unsigned int dropepoch;
int droprec;
int duprec;
} MEMPACKET_TEST_CTX;
static int mempacket_test_new(BIO *bi);
static int mempacket_test_free(BIO *a);
static int mempacket_test_read(BIO *b, char *out, int outl);
static int mempacket_test_write(BIO *b, const char *in, int inl);
static long mempacket_test_ctrl(BIO *b, int cmd, long num, void *ptr);
static int mempacket_test_gets(BIO *bp, char *buf, int size);
static int mempacket_test_puts(BIO *bp, const char *str);
const BIO_METHOD *bio_s_mempacket_test(void)
{
if (meth_mem == NULL) {
if (!TEST_ptr(meth_mem = BIO_meth_new(BIO_TYPE_MEMPACKET_TEST,
"Mem Packet Test"))
|| !TEST_true(BIO_meth_set_write(meth_mem, mempacket_test_write))
|| !TEST_true(BIO_meth_set_read(meth_mem, mempacket_test_read))
|| !TEST_true(BIO_meth_set_puts(meth_mem, mempacket_test_puts))
|| !TEST_true(BIO_meth_set_gets(meth_mem, mempacket_test_gets))
|| !TEST_true(BIO_meth_set_ctrl(meth_mem, mempacket_test_ctrl))
|| !TEST_true(BIO_meth_set_create(meth_mem, mempacket_test_new))
|| !TEST_true(BIO_meth_set_destroy(meth_mem, mempacket_test_free)))
return NULL;
}
return meth_mem;
}
void bio_s_mempacket_test_free(void)
{
BIO_meth_free(meth_mem);
}
static int mempacket_test_new(BIO *bio)
{
MEMPACKET_TEST_CTX *ctx;
if (!TEST_ptr(ctx = OPENSSL_zalloc(sizeof(*ctx))))
return 0;
if (!TEST_ptr(ctx->pkts = sk_MEMPACKET_new_null())) {
OPENSSL_free(ctx);
return 0;
}
ctx->dropepoch = 0;
ctx->droprec = -1;
BIO_set_init(bio, 1);
BIO_set_data(bio, ctx);
return 1;
}
static int mempacket_test_free(BIO *bio)
{
MEMPACKET_TEST_CTX *ctx = BIO_get_data(bio);
sk_MEMPACKET_pop_free(ctx->pkts, mempacket_free);
OPENSSL_free(ctx);
BIO_set_data(bio, NULL);
BIO_set_init(bio, 0);
return 1;
}
/* Record Header values */
#define EPOCH_HI 3
#define EPOCH_LO 4
#define RECORD_SEQUENCE 10
#define RECORD_LEN_HI 11
#define RECORD_LEN_LO 12
#define STANDARD_PACKET 0
static int mempacket_test_read(BIO *bio, char *out, int outl)
{
MEMPACKET_TEST_CTX *ctx = BIO_get_data(bio);
MEMPACKET *thispkt;
unsigned char *rec;
int rem;
unsigned int seq, offset, len, epoch;
BIO_clear_retry_flags(bio);
if ((thispkt = sk_MEMPACKET_value(ctx->pkts, 0)) == NULL
|| thispkt->num != ctx->currpkt) {
/* Probably run out of data */
BIO_set_retry_read(bio);
return -1;
}
(void)sk_MEMPACKET_shift(ctx->pkts);
ctx->currpkt++;
if (outl > thispkt->len)
outl = thispkt->len;
if (thispkt->type != INJECT_PACKET_IGNORE_REC_SEQ
&& (ctx->injected || ctx->droprec >= 0)) {
/*
* Overwrite the record sequence number. We strictly number them in
* the order received. Since we are actually a reliable transport
* we know that there won't be any re-ordering. We overwrite to deal
* with any packets that have been injected
*/
for (rem = thispkt->len, rec = thispkt->data; rem > 0; rem -= len) {
if (rem < DTLS1_RT_HEADER_LENGTH)
return -1;
epoch = (rec[EPOCH_HI] << 8) | rec[EPOCH_LO];
if (epoch != ctx->epoch) {
ctx->epoch = epoch;
ctx->currrec = 0;
}
seq = ctx->currrec;
offset = 0;
do {
rec[RECORD_SEQUENCE - offset] = seq & 0xFF;
seq >>= 8;
offset++;
} while (seq > 0);
len = ((rec[RECORD_LEN_HI] << 8) | rec[RECORD_LEN_LO])
+ DTLS1_RT_HEADER_LENGTH;
if (rem < (int)len)
return -1;
if (ctx->droprec == (int)ctx->currrec && ctx->dropepoch == epoch) {
if (rem > (int)len)
memmove(rec, rec + len, rem - len);
outl -= len;
ctx->droprec = -1;
if (outl == 0)
BIO_set_retry_read(bio);
} else {
rec += len;
}
ctx->currrec++;
}
}
memcpy(out, thispkt->data, outl);
mempacket_free(thispkt);
return outl;
}
/*
* Look for records from different epochs in the last datagram and swap them
* around
*/
int mempacket_swap_epoch(BIO *bio)
{
MEMPACKET_TEST_CTX *ctx = BIO_get_data(bio);
MEMPACKET *thispkt;
int rem, len, prevlen = 0, pktnum;
unsigned char *rec, *prevrec = NULL, *tmp;
unsigned int epoch;
int numpkts = sk_MEMPACKET_num(ctx->pkts);
if (numpkts <= 0)
return 0;
/*
* If there are multiple packets we only look in the last one. This should
* always be the one where any epoch change occurs.
*/
thispkt = sk_MEMPACKET_value(ctx->pkts, numpkts - 1);
if (thispkt == NULL)
return 0;
for (rem = thispkt->len, rec = thispkt->data; rem > 0; rem -= len, rec += len) {
if (rem < DTLS1_RT_HEADER_LENGTH)
return 0;
epoch = (rec[EPOCH_HI] << 8) | rec[EPOCH_LO];
len = ((rec[RECORD_LEN_HI] << 8) | rec[RECORD_LEN_LO])
+ DTLS1_RT_HEADER_LENGTH;
if (rem < len)
return 0;
/* Assumes the epoch change does not happen on the first record */
if (epoch != ctx->epoch) {
if (prevrec == NULL)
return 0;
/*
* We found 2 records with different epochs. Take a copy of the
* earlier record
*/
tmp = OPENSSL_malloc(prevlen);
if (tmp == NULL)
return 0;
memcpy(tmp, prevrec, prevlen);
/*
* Move everything from this record onwards, including any trailing
* records, and overwrite the earlier record
*/
memmove(prevrec, rec, rem);
thispkt->len -= prevlen;
pktnum = thispkt->num;
/*
* Create a new packet for the earlier record that we took out and
* add it to the end of the packet list.
*/
thispkt = OPENSSL_malloc(sizeof(*thispkt));
if (thispkt == NULL) {
OPENSSL_free(tmp);
return 0;
}
thispkt->type = INJECT_PACKET;
thispkt->data = tmp;
thispkt->len = prevlen;
thispkt->num = pktnum + 1;
if (sk_MEMPACKET_insert(ctx->pkts, thispkt, numpkts) <= 0) {
OPENSSL_free(tmp);
OPENSSL_free(thispkt);
return 0;
}
return 1;
}
prevrec = rec;
prevlen = len;
}
return 0;
}
/* Move packet from position s to position d in the list (d < s) */
int mempacket_move_packet(BIO *bio, int d, int s)
{
MEMPACKET_TEST_CTX *ctx = BIO_get_data(bio);
MEMPACKET *thispkt;
int numpkts = sk_MEMPACKET_num(ctx->pkts);
int i;
if (d >= s)
return 0;
/* We need at least s + 1 packets to be able to swap them */
if (numpkts <= s)
return 0;
/* Get the packet at position s */
thispkt = sk_MEMPACKET_value(ctx->pkts, s);
if (thispkt == NULL)
return 0;
/* Remove and re-add it */
if (sk_MEMPACKET_delete(ctx->pkts, s) != thispkt)
return 0;
thispkt->num -= (s - d);
if (sk_MEMPACKET_insert(ctx->pkts, thispkt, d) <= 0)
return 0;
/* Increment the packet numbers for moved packets */
for (i = d + 1; i <= s; i++) {
thispkt = sk_MEMPACKET_value(ctx->pkts, i);
thispkt->num++;
}
return 1;
}
int mempacket_test_inject(BIO *bio, const char *in, int inl, int pktnum,
int type)
{
MEMPACKET_TEST_CTX *ctx = BIO_get_data(bio);
MEMPACKET *thispkt = NULL, *looppkt, *nextpkt, *allpkts[3];
int i, duprec;
const unsigned char *inu = (const unsigned char *)in;
size_t len = ((inu[RECORD_LEN_HI] << 8) | inu[RECORD_LEN_LO])
+ DTLS1_RT_HEADER_LENGTH;
if (ctx == NULL)
return -1;
if ((size_t)inl < len)
return -1;
if ((size_t)inl == len)
duprec = 0;
else
duprec = ctx->duprec > 0;
/* We don't support arbitrary injection when duplicating records */
if (duprec && pktnum != -1)
return -1;
/* We only allow injection before we've started writing any data */
if (pktnum >= 0) {
if (ctx->noinject)
return -1;
ctx->injected = 1;
} else {
ctx->noinject = 1;
}
for (i = 0; i < (duprec ? 3 : 1); i++) {
if (!TEST_ptr(allpkts[i] = OPENSSL_malloc(sizeof(*thispkt))))
goto err;
thispkt = allpkts[i];
if (!TEST_ptr(thispkt->data = OPENSSL_malloc(inl)))
goto err;
/*
* If we are duplicating the packet, we duplicate it three times. The
* first two times we drop the first record if there are more than one.
* In this way we know that libssl will not be able to make progress
* until it receives the last packet, and hence will be forced to
* buffer these records.
*/
if (duprec && i != 2) {
memcpy(thispkt->data, in + len, inl - len);
thispkt->len = inl - len;
} else {
memcpy(thispkt->data, in, inl);
thispkt->len = inl;
}
thispkt->num = (pktnum >= 0) ? (unsigned int)pktnum : ctx->lastpkt + i;
thispkt->type = type;
}
for (i = 0; i < sk_MEMPACKET_num(ctx->pkts); i++) {
if (!TEST_ptr(looppkt = sk_MEMPACKET_value(ctx->pkts, i)))
goto err;
/* Check if we found the right place to insert this packet */
if (looppkt->num > thispkt->num) {
if (sk_MEMPACKET_insert(ctx->pkts, thispkt, i) == 0)
goto err;
/* If we're doing up front injection then we're done */
if (pktnum >= 0)
return inl;
/*
* We need to do some accounting on lastpkt. We increment it first,
* but it might now equal the value of injected packets, so we need
* to skip over those
*/
ctx->lastpkt++;
do {
i++;
nextpkt = sk_MEMPACKET_value(ctx->pkts, i);
if (nextpkt != NULL && nextpkt->num == ctx->lastpkt)
ctx->lastpkt++;
else
return inl;
} while(1);
} else if (looppkt->num == thispkt->num) {
if (!ctx->noinject) {
/* We injected two packets with the same packet number! */
goto err;
}
ctx->lastpkt++;
thispkt->num++;
}
}
/*
* We didn't find any packets with a packet number equal to or greater than
* this one, so we just add it onto the end
*/
for (i = 0; i < (duprec ? 3 : 1); i++) {
thispkt = allpkts[i];
if (!sk_MEMPACKET_push(ctx->pkts, thispkt))
goto err;
if (pktnum < 0)
ctx->lastpkt++;
}
return inl;
err:
for (i = 0; i < (ctx->duprec > 0 ? 3 : 1); i++)
mempacket_free(allpkts[i]);
return -1;
}
static int mempacket_test_write(BIO *bio, const char *in, int inl)
{
return mempacket_test_inject(bio, in, inl, -1, STANDARD_PACKET);
}
static long mempacket_test_ctrl(BIO *bio, int cmd, long num, void *ptr)
{
long ret = 1;
MEMPACKET_TEST_CTX *ctx = BIO_get_data(bio);
MEMPACKET *thispkt;
switch (cmd) {
case BIO_CTRL_EOF:
ret = (long)(sk_MEMPACKET_num(ctx->pkts) == 0);
break;
case BIO_CTRL_GET_CLOSE:
ret = BIO_get_shutdown(bio);
break;
case BIO_CTRL_SET_CLOSE:
BIO_set_shutdown(bio, (int)num);
break;
case BIO_CTRL_WPENDING:
ret = 0L;
break;
case BIO_CTRL_PENDING:
thispkt = sk_MEMPACKET_value(ctx->pkts, 0);
if (thispkt == NULL)
ret = 0;
else
ret = thispkt->len;
break;
case BIO_CTRL_FLUSH:
ret = 1;
break;
case MEMPACKET_CTRL_SET_DROP_EPOCH:
ctx->dropepoch = (unsigned int)num;
break;
case MEMPACKET_CTRL_SET_DROP_REC:
ctx->droprec = (int)num;
break;
case MEMPACKET_CTRL_GET_DROP_REC:
ret = ctx->droprec;
break;
case MEMPACKET_CTRL_SET_DUPLICATE_REC:
ctx->duprec = (int)num;
break;
case BIO_CTRL_RESET:
case BIO_CTRL_DUP:
case BIO_CTRL_PUSH:
case BIO_CTRL_POP:
default:
ret = 0;
break;
}
return ret;
}
static int mempacket_test_gets(BIO *bio, char *buf, int size)
{
/* We don't support this - not needed anyway */
return -1;
}
static int mempacket_test_puts(BIO *bio, const char *str)
{
return mempacket_test_write(bio, str, strlen(str));
}
static int always_retry_new(BIO *bi);
static int always_retry_free(BIO *a);
static int always_retry_read(BIO *b, char *out, int outl);
static int always_retry_write(BIO *b, const char *in, int inl);
static long always_retry_ctrl(BIO *b, int cmd, long num, void *ptr);
static int always_retry_gets(BIO *bp, char *buf, int size);
static int always_retry_puts(BIO *bp, const char *str);
const BIO_METHOD *bio_s_always_retry(void)
{
if (meth_always_retry == NULL) {
if (!TEST_ptr(meth_always_retry = BIO_meth_new(BIO_TYPE_ALWAYS_RETRY,
"Always Retry"))
|| !TEST_true(BIO_meth_set_write(meth_always_retry,
always_retry_write))
|| !TEST_true(BIO_meth_set_read(meth_always_retry,
always_retry_read))
|| !TEST_true(BIO_meth_set_puts(meth_always_retry,
always_retry_puts))
|| !TEST_true(BIO_meth_set_gets(meth_always_retry,
always_retry_gets))
|| !TEST_true(BIO_meth_set_ctrl(meth_always_retry,
always_retry_ctrl))
|| !TEST_true(BIO_meth_set_create(meth_always_retry,
always_retry_new))
|| !TEST_true(BIO_meth_set_destroy(meth_always_retry,
always_retry_free)))
return NULL;
}
return meth_always_retry;
}
void bio_s_always_retry_free(void)
{
BIO_meth_free(meth_always_retry);
}
static int always_retry_new(BIO *bio)
{
BIO_set_init(bio, 1);
return 1;
}
static int always_retry_free(BIO *bio)
{
BIO_set_data(bio, NULL);
BIO_set_init(bio, 0);
return 1;
}
void set_always_retry_err_val(int err)
{
retry_err = err;
}
static int always_retry_read(BIO *bio, char *out, int outl)
{
BIO_set_retry_read(bio);
return retry_err;
}
static int always_retry_write(BIO *bio, const char *in, int inl)
{
BIO_set_retry_write(bio);
return retry_err;
}
static long always_retry_ctrl(BIO *bio, int cmd, long num, void *ptr)
{
long ret = 1;
switch (cmd) {
case BIO_CTRL_FLUSH:
BIO_set_retry_write(bio);
/* fall through */
case BIO_CTRL_EOF:
case BIO_CTRL_RESET:
case BIO_CTRL_DUP:
case BIO_CTRL_PUSH:
case BIO_CTRL_POP:
default:
ret = 0;
break;
}
return ret;
}
static int always_retry_gets(BIO *bio, char *buf, int size)
{
BIO_set_retry_read(bio);
return retry_err;
}
static int always_retry_puts(BIO *bio, const char *str)
{
BIO_set_retry_write(bio);
return retry_err;
}
int create_ssl_ctx_pair(OSSL_LIB_CTX *libctx, const SSL_METHOD *sm,
const SSL_METHOD *cm, int min_proto_version,
int max_proto_version, SSL_CTX **sctx, SSL_CTX **cctx,
char *certfile, char *privkeyfile)
{
SSL_CTX *serverctx = NULL;
SSL_CTX *clientctx = NULL;
if (sctx != NULL) {
if (*sctx != NULL)
serverctx = *sctx;
else if (!TEST_ptr(serverctx = SSL_CTX_new_ex(libctx, NULL, sm))
|| !TEST_true(SSL_CTX_set_options(serverctx,
SSL_OP_ALLOW_CLIENT_RENEGOTIATION)))
goto err;
}
if (cctx != NULL) {
if (*cctx != NULL)
clientctx = *cctx;
else if (!TEST_ptr(clientctx = SSL_CTX_new_ex(libctx, NULL, cm)))
goto err;
}
#if !defined(OPENSSL_NO_TLS1_3) \
&& defined(OPENSSL_NO_EC) \
&& defined(OPENSSL_NO_DH)
/*
* There are no usable built-in TLSv1.3 groups if ec and dh are both
* disabled
*/
if (max_proto_version == 0
&& (sm == TLS_server_method() || cm == TLS_client_method()))
max_proto_version = TLS1_2_VERSION;
#endif
if (serverctx != NULL
&& ((min_proto_version > 0
&& !TEST_true(SSL_CTX_set_min_proto_version(serverctx,
min_proto_version)))
|| (max_proto_version > 0
&& !TEST_true(SSL_CTX_set_max_proto_version(serverctx,
max_proto_version)))))
goto err;
if (clientctx != NULL
&& ((min_proto_version > 0
&& !TEST_true(SSL_CTX_set_min_proto_version(clientctx,
min_proto_version)))
|| (max_proto_version > 0
&& !TEST_true(SSL_CTX_set_max_proto_version(clientctx,
max_proto_version)))))
goto err;
if (serverctx != NULL && certfile != NULL && privkeyfile != NULL) {
if (!TEST_int_eq(SSL_CTX_use_certificate_file(serverctx, certfile,
SSL_FILETYPE_PEM), 1)
|| !TEST_int_eq(SSL_CTX_use_PrivateKey_file(serverctx,
privkeyfile,
SSL_FILETYPE_PEM), 1)
|| !TEST_int_eq(SSL_CTX_check_private_key(serverctx), 1))
goto err;
}
if (sctx != NULL)
*sctx = serverctx;
if (cctx != NULL)
*cctx = clientctx;
return 1;
err:
if (sctx != NULL && *sctx == NULL)
SSL_CTX_free(serverctx);
if (cctx != NULL && *cctx == NULL)
SSL_CTX_free(clientctx);
return 0;
}
#define MAXLOOPS 1000000
#if !defined(OPENSSL_NO_KTLS) && !defined(OPENSSL_NO_SOCK)
static int set_nb(int fd)
{
int flags;
flags = fcntl(fd,F_GETFL,0);
if (flags == -1)
return flags;
flags = fcntl(fd, F_SETFL, flags | O_NONBLOCK);
return flags;
}
int create_test_sockets(int *cfdp, int *sfdp)
{
struct sockaddr_in sin;
const char *host = "127.0.0.1";
int cfd_connected = 0, ret = 0;
socklen_t slen = sizeof(sin);
int afd = -1, cfd = -1, sfd = -1;
memset ((char *) &sin, 0, sizeof(sin));
sin.sin_family = AF_INET;
sin.sin_addr.s_addr = inet_addr(host);
afd = socket(AF_INET, SOCK_STREAM, 0);
if (afd < 0)
return 0;
if (bind(afd, (struct sockaddr*)&sin, sizeof(sin)) < 0)
goto out;
if (getsockname(afd, (struct sockaddr*)&sin, &slen) < 0)
goto out;
if (listen(afd, 1) < 0)
goto out;
cfd = socket(AF_INET, SOCK_STREAM, 0);
if (cfd < 0)
goto out;
if (set_nb(afd) == -1)
goto out;
while (sfd == -1 || !cfd_connected ) {
sfd = accept(afd, NULL, 0);
if (sfd == -1 && errno != EAGAIN)
goto out;
if (!cfd_connected && connect(cfd, (struct sockaddr*)&sin, sizeof(sin)) < 0)
goto out;
else
cfd_connected = 1;
}
if (set_nb(cfd) == -1 || set_nb(sfd) == -1)
goto out;
ret = 1;
*cfdp = cfd;
*sfdp = sfd;
goto success;
out:
if (cfd != -1)
close(cfd);
if (sfd != -1)
close(sfd);
success:
if (afd != -1)
close(afd);
return ret;
}
int create_ssl_objects2(SSL_CTX *serverctx, SSL_CTX *clientctx, SSL **sssl,
SSL **cssl, int sfd, int cfd)
{
SSL *serverssl = NULL, *clientssl = NULL;
BIO *s_to_c_bio = NULL, *c_to_s_bio = NULL;
if (*sssl != NULL)
serverssl = *sssl;
else if (!TEST_ptr(serverssl = SSL_new(serverctx)))
goto error;
if (*cssl != NULL)
clientssl = *cssl;
else if (!TEST_ptr(clientssl = SSL_new(clientctx)))
goto error;
if (!TEST_ptr(s_to_c_bio = BIO_new_socket(sfd, BIO_NOCLOSE))
|| !TEST_ptr(c_to_s_bio = BIO_new_socket(cfd, BIO_NOCLOSE)))
goto error;
SSL_set_bio(clientssl, c_to_s_bio, c_to_s_bio);
SSL_set_bio(serverssl, s_to_c_bio, s_to_c_bio);
*sssl = serverssl;
*cssl = clientssl;
return 1;
error:
SSL_free(serverssl);
SSL_free(clientssl);
BIO_free(s_to_c_bio);
BIO_free(c_to_s_bio);
return 0;
}
#endif
/*
* NOTE: Transfers control of the BIOs - this function will free them on error
*/
int create_ssl_objects(SSL_CTX *serverctx, SSL_CTX *clientctx, SSL **sssl,
SSL **cssl, BIO *s_to_c_fbio, BIO *c_to_s_fbio)
{
SSL *serverssl = NULL, *clientssl = NULL;
BIO *s_to_c_bio = NULL, *c_to_s_bio = NULL;
if (*sssl != NULL)
serverssl = *sssl;
else if (!TEST_ptr(serverssl = SSL_new(serverctx)))
goto error;
if (*cssl != NULL)
clientssl = *cssl;
else if (!TEST_ptr(clientssl = SSL_new(clientctx)))
goto error;
if (SSL_is_dtls(clientssl)) {
if (!TEST_ptr(s_to_c_bio = BIO_new(bio_s_mempacket_test()))
|| !TEST_ptr(c_to_s_bio = BIO_new(bio_s_mempacket_test())))
goto error;
} else {
if (!TEST_ptr(s_to_c_bio = BIO_new(BIO_s_mem()))
|| !TEST_ptr(c_to_s_bio = BIO_new(BIO_s_mem())))
goto error;
}
if (s_to_c_fbio != NULL
&& !TEST_ptr(s_to_c_bio = BIO_push(s_to_c_fbio, s_to_c_bio)))
goto error;
if (c_to_s_fbio != NULL
&& !TEST_ptr(c_to_s_bio = BIO_push(c_to_s_fbio, c_to_s_bio)))
goto error;
/* Set Non-blocking IO behaviour */
BIO_set_mem_eof_return(s_to_c_bio, -1);
BIO_set_mem_eof_return(c_to_s_bio, -1);
/* Up ref these as we are passing them to two SSL objects */
SSL_set_bio(serverssl, c_to_s_bio, s_to_c_bio);
BIO_up_ref(s_to_c_bio);
BIO_up_ref(c_to_s_bio);
SSL_set_bio(clientssl, s_to_c_bio, c_to_s_bio);
*sssl = serverssl;
*cssl = clientssl;
return 1;
error:
SSL_free(serverssl);
SSL_free(clientssl);
BIO_free(s_to_c_bio);
BIO_free(c_to_s_bio);
BIO_free(s_to_c_fbio);
BIO_free(c_to_s_fbio);
return 0;
}
/*
* Create an SSL connection, but does not read any post-handshake
* NewSessionTicket messages.
* If |read| is set and we're using DTLS then we will attempt to SSL_read on
* the connection once we've completed one half of it, to ensure any retransmits
* get triggered.
* We stop the connection attempt (and return a failure value) if either peer
* has SSL_get_error() return the value in the |want| parameter. The connection
* attempt could be restarted by a subsequent call to this function.
*/
int create_bare_ssl_connection(SSL *serverssl, SSL *clientssl, int want,
int read)
{
int retc = -1, rets = -1, err, abortctr = 0;
int clienterr = 0, servererr = 0;
int isdtls = SSL_is_dtls(serverssl);
do {
err = SSL_ERROR_WANT_WRITE;
while (!clienterr && retc <= 0 && err == SSL_ERROR_WANT_WRITE) {
retc = SSL_connect(clientssl);
if (retc <= 0)
err = SSL_get_error(clientssl, retc);
}
if (!clienterr && retc <= 0 && err != SSL_ERROR_WANT_READ) {
TEST_info("SSL_connect() failed %d, %d", retc, err);
if (want != SSL_ERROR_SSL)
TEST_openssl_errors();
clienterr = 1;
}
if (want != SSL_ERROR_NONE && err == want)
return 0;
err = SSL_ERROR_WANT_WRITE;
while (!servererr && rets <= 0 && err == SSL_ERROR_WANT_WRITE) {
rets = SSL_accept(serverssl);
if (rets <= 0)
err = SSL_get_error(serverssl, rets);
}
if (!servererr && rets <= 0
&& err != SSL_ERROR_WANT_READ
&& err != SSL_ERROR_WANT_X509_LOOKUP) {
TEST_info("SSL_accept() failed %d, %d", rets, err);
if (want != SSL_ERROR_SSL)
TEST_openssl_errors();
servererr = 1;
}
if (want != SSL_ERROR_NONE && err == want)
return 0;
if (clienterr && servererr)
return 0;
if (isdtls && read) {
unsigned char buf[20];
/* Trigger any retransmits that may be appropriate */
if (rets > 0 && retc <= 0) {
if (SSL_read(serverssl, buf, sizeof(buf)) > 0) {
/* We don't expect this to succeed! */
TEST_info("Unexpected SSL_read() success!");
return 0;
}
}
if (retc > 0 && rets <= 0) {
if (SSL_read(clientssl, buf, sizeof(buf)) > 0) {
/* We don't expect this to succeed! */
TEST_info("Unexpected SSL_read() success!");
return 0;
}
}
}
if (++abortctr == MAXLOOPS) {
TEST_info("No progress made");
return 0;
}
if (isdtls && abortctr <= 50 && (abortctr % 10) == 0) {
/*
* It looks like we're just spinning. Pause for a short period to
* give the DTLS timer a chance to do something. We only do this for
* the first few times to prevent hangs.
*/
ossl_sleep(50);
}
} while (retc <=0 || rets <= 0);
return 1;
}
/*
* Create an SSL connection including any post handshake NewSessionTicket
* messages.
*/
int create_ssl_connection(SSL *serverssl, SSL *clientssl, int want)
{
int i;
unsigned char buf;
size_t readbytes;
if (!create_bare_ssl_connection(serverssl, clientssl, want, 1))
return 0;
/*
* We attempt to read some data on the client side which we expect to fail.
* This will ensure we have received the NewSessionTicket in TLSv1.3 where
* appropriate. We do this twice because there are 2 NewSessionTickets.
*/
for (i = 0; i < 2; i++) {
if (SSL_read_ex(clientssl, &buf, sizeof(buf), &readbytes) > 0) {
if (!TEST_ulong_eq(readbytes, 0))
return 0;
} else if (!TEST_int_eq(SSL_get_error(clientssl, 0),
SSL_ERROR_WANT_READ)) {
return 0;
}
}
return 1;
}
void shutdown_ssl_connection(SSL *serverssl, SSL *clientssl)
{
SSL_shutdown(clientssl);
SSL_shutdown(serverssl);
SSL_free(serverssl);
SSL_free(clientssl);
}
+
+ENGINE *load_dasync(void)
+{
+#if !defined(OPENSSL_NO_TLS1_2) && !defined(OPENSSL_NO_DYNAMIC_ENGINE)
+ ENGINE *e;
+
+ if (!TEST_ptr(e = ENGINE_by_id("dasync")))
+ return NULL;
+
+ if (!TEST_true(ENGINE_init(e))) {
+ ENGINE_free(e);
+ return NULL;
+ }
+
+ if (!TEST_true(ENGINE_register_ciphers(e))) {
+ ENGINE_free(e);
+ return NULL;
+ }
+
+ return e;
+#else
+ return NULL;
+#endif
+}
diff --git a/crypto/openssl/test/helpers/ssltestlib.h b/crypto/openssl/test/helpers/ssltestlib.h
index 8e9daa5601d3..0fbca34afa75 100644
--- a/crypto/openssl/test/helpers/ssltestlib.h
+++ b/crypto/openssl/test/helpers/ssltestlib.h
@@ -1,62 +1,63 @@
/*
- * Copyright 2016-2023 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2016-2024 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_TEST_SSLTESTLIB_H
# define OSSL_TEST_SSLTESTLIB_H
# include <openssl/ssl.h>
int create_ssl_ctx_pair(OSSL_LIB_CTX *libctx, const SSL_METHOD *sm,
const SSL_METHOD *cm, int min_proto_version,
int max_proto_version, SSL_CTX **sctx, SSL_CTX **cctx,
char *certfile, char *privkeyfile);
int create_ssl_objects(SSL_CTX *serverctx, SSL_CTX *clientctx, SSL **sssl,
SSL **cssl, BIO *s_to_c_fbio, BIO *c_to_s_fbio);
int create_bare_ssl_connection(SSL *serverssl, SSL *clientssl, int want,
int read);
int create_ssl_objects2(SSL_CTX *serverctx, SSL_CTX *clientctx, SSL **sssl,
SSL **cssl, int sfd, int cfd);
int create_test_sockets(int *cfd, int *sfd);
int create_ssl_connection(SSL *serverssl, SSL *clientssl, int want);
void shutdown_ssl_connection(SSL *serverssl, SSL *clientssl);
/* Note: Not thread safe! */
const BIO_METHOD *bio_f_tls_dump_filter(void);
void bio_f_tls_dump_filter_free(void);
const BIO_METHOD *bio_s_mempacket_test(void);
void bio_s_mempacket_test_free(void);
const BIO_METHOD *bio_s_always_retry(void);
void bio_s_always_retry_free(void);
void set_always_retry_err_val(int err);
/* Packet types - value 0 is reserved */
#define INJECT_PACKET 1
#define INJECT_PACKET_IGNORE_REC_SEQ 2
/*
* Mempacket BIO ctrls. We make them large enough to not clash with standard BIO
* ctrl codes.
*/
#define MEMPACKET_CTRL_SET_DROP_EPOCH (1 << 15)
#define MEMPACKET_CTRL_SET_DROP_REC (2 << 15)
#define MEMPACKET_CTRL_GET_DROP_REC (3 << 15)
#define MEMPACKET_CTRL_SET_DUPLICATE_REC (4 << 15)
int mempacket_swap_epoch(BIO *bio);
int mempacket_move_packet(BIO *bio, int d, int s);
int mempacket_test_inject(BIO *bio, const char *in, int inl, int pktnum,
int type);
typedef struct mempacket_st MEMPACKET;
DEFINE_STACK_OF(MEMPACKET)
+ENGINE *load_dasync(void);
#endif /* OSSL_TEST_SSLTESTLIB_H */
diff --git a/crypto/openssl/test/keymgmt_internal_test.c b/crypto/openssl/test/keymgmt_internal_test.c
index ce2e458f8c31..8d5aa22dab3e 100644
--- a/crypto/openssl/test/keymgmt_internal_test.c
+++ b/crypto/openssl/test/keymgmt_internal_test.c
@@ -1,358 +1,362 @@
/*
- * Copyright 2019-2022 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2019-2024 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 <string.h>
#include <openssl/bio.h>
#include <openssl/bn.h>
#include <openssl/rsa.h>
#include <openssl/evp.h>
#include <openssl/pem.h>
#include <openssl/provider.h>
#include <openssl/core_names.h>
#include "internal/core.h"
#include "internal/nelem.h"
#include "crypto/evp.h" /* For the internal API */
#include "testutil.h"
typedef struct {
OSSL_LIB_CTX *ctx1;
OSSL_PROVIDER *prov1;
OSSL_LIB_CTX *ctx2;
OSSL_PROVIDER *prov2;
} FIXTURE;
/* Collected arguments */
static const char *cert_filename = NULL;
static void tear_down(FIXTURE *fixture)
{
if (fixture != NULL) {
OSSL_PROVIDER_unload(fixture->prov1);
OSSL_PROVIDER_unload(fixture->prov2);
OSSL_LIB_CTX_free(fixture->ctx1);
OSSL_LIB_CTX_free(fixture->ctx2);
OPENSSL_free(fixture);
}
}
static FIXTURE *set_up(const char *testcase_name)
{
FIXTURE *fixture;
if (!TEST_ptr(fixture = OPENSSL_zalloc(sizeof(*fixture)))
|| !TEST_ptr(fixture->ctx1 = OSSL_LIB_CTX_new())
|| !TEST_ptr(fixture->prov1 = OSSL_PROVIDER_load(fixture->ctx1,
"default"))
|| !TEST_ptr(fixture->ctx2 = OSSL_LIB_CTX_new())
|| !TEST_ptr(fixture->prov2 = OSSL_PROVIDER_load(fixture->ctx2,
"default"))) {
tear_down(fixture);
return NULL;
}
return fixture;
}
/* Array indexes */
#define N 0
#define E 1
#define D 2
#define P 3
#define Q 4
#define F3 5 /* Extra factor */
#define DP 6
#define DQ 7
#define E3 8 /* Extra exponent */
#define QINV 9
#define C2 10 /* Extra coefficient */
/*
* We have to do this because OSSL_PARAM_get_ulong() can't handle params
* holding data that isn't exactly sizeof(uint32_t) or sizeof(uint64_t),
* and because the other end deals with BIGNUM, the resulting param might
* be any size. In this particular test, we know that the expected data
* fits within an unsigned long, and we want to get the data in that form
* to make testing of values easier.
*/
static int get_ulong_via_BN(const OSSL_PARAM *p, unsigned long *goal)
{
BIGNUM *n = NULL;
int ret = 1; /* Ever so hopeful */
if (!TEST_true(OSSL_PARAM_get_BN(p, &n))
|| !TEST_int_ge(BN_bn2nativepad(n, (unsigned char *)goal, sizeof(*goal)), 0))
ret = 0;
BN_free(n);
return ret;
}
static int export_cb(const OSSL_PARAM *params, void *arg)
{
unsigned long *keydata = arg;
const OSSL_PARAM *p = NULL;
if (keydata == NULL)
return 0;
if (!TEST_ptr(p = OSSL_PARAM_locate_const(params, OSSL_PKEY_PARAM_RSA_N))
|| !TEST_true(get_ulong_via_BN(p, &keydata[N]))
|| !TEST_ptr(p = OSSL_PARAM_locate_const(params, OSSL_PKEY_PARAM_RSA_E))
|| !TEST_true(get_ulong_via_BN(p, &keydata[E]))
|| !TEST_ptr(p = OSSL_PARAM_locate_const(params, OSSL_PKEY_PARAM_RSA_D))
|| !TEST_true(get_ulong_via_BN(p, &keydata[D])))
return 0;
if (!TEST_ptr(p = OSSL_PARAM_locate_const(params, OSSL_PKEY_PARAM_RSA_FACTOR1))
|| !TEST_true(get_ulong_via_BN(p, &keydata[P]))
|| !TEST_ptr(p = OSSL_PARAM_locate_const(params, OSSL_PKEY_PARAM_RSA_FACTOR2))
|| !TEST_true(get_ulong_via_BN(p, &keydata[Q]))
|| !TEST_ptr(p = OSSL_PARAM_locate_const(params, OSSL_PKEY_PARAM_RSA_FACTOR3))
|| !TEST_true(get_ulong_via_BN(p, &keydata[F3])))
return 0;
if (!TEST_ptr(p = OSSL_PARAM_locate_const(params, OSSL_PKEY_PARAM_RSA_EXPONENT1))
|| !TEST_true(get_ulong_via_BN(p, &keydata[DP]))
|| !TEST_ptr(p = OSSL_PARAM_locate_const(params, OSSL_PKEY_PARAM_RSA_EXPONENT2))
|| !TEST_true(get_ulong_via_BN(p, &keydata[DQ]))
|| !TEST_ptr(p = OSSL_PARAM_locate_const(params, OSSL_PKEY_PARAM_RSA_EXPONENT3))
|| !TEST_true(get_ulong_via_BN(p, &keydata[E3])))
return 0;
if (!TEST_ptr(p = OSSL_PARAM_locate_const(params, OSSL_PKEY_PARAM_RSA_COEFFICIENT1))
|| !TEST_true(get_ulong_via_BN(p, &keydata[QINV]))
|| !TEST_ptr(p = OSSL_PARAM_locate_const(params, OSSL_PKEY_PARAM_RSA_COEFFICIENT2))
|| !TEST_true(get_ulong_via_BN(p, &keydata[C2])))
return 0;
return 1;
}
static int test_pass_rsa(FIXTURE *fixture)
{
size_t i;
int ret = 0;
RSA *rsa = NULL;
BIGNUM *bn1 = NULL, *bn2 = NULL, *bn3 = NULL;
EVP_PKEY *pk = NULL, *dup_pk = NULL;
EVP_KEYMGMT *km = NULL, *km1 = NULL, *km2 = NULL, *km3 = NULL;
void *provkey = NULL, *provkey2 = NULL;
BIGNUM *bn_primes[1] = { NULL };
BIGNUM *bn_exps[1] = { NULL };
BIGNUM *bn_coeffs[1] = { NULL };
/*
* 32-bit RSA key, extracted from this command,
* executed with OpenSSL 1.0.2:
* An extra factor was added just for testing purposes.
*
* openssl genrsa 32 | openssl rsa -text
*/
static BN_ULONG expected[] = {
0xbc747fc5, /* N */
0x10001, /* E */
0x7b133399, /* D */
0xe963, /* P */
0xceb7, /* Q */
1, /* F3 */
0x8599, /* DP */
0xbd87, /* DQ */
2, /* E3 */
0xcc3b, /* QINV */
3, /* C3 */
0 /* Extra, should remain zero */
};
static unsigned long keydata[OSSL_NELEM(expected)] = { 0, };
if (!TEST_ptr(rsa = RSA_new()))
goto err;
if (!TEST_ptr(bn1 = BN_new())
|| !TEST_true(BN_set_word(bn1, expected[N]))
|| !TEST_ptr(bn2 = BN_new())
|| !TEST_true(BN_set_word(bn2, expected[E]))
|| !TEST_ptr(bn3 = BN_new())
|| !TEST_true(BN_set_word(bn3, expected[D]))
|| !TEST_true(RSA_set0_key(rsa, bn1, bn2, bn3)))
goto err;
if (!TEST_ptr(bn1 = BN_new())
|| !TEST_true(BN_set_word(bn1, expected[P]))
|| !TEST_ptr(bn2 = BN_new())
|| !TEST_true(BN_set_word(bn2, expected[Q]))
|| !TEST_true(RSA_set0_factors(rsa, bn1, bn2)))
goto err;
if (!TEST_ptr(bn1 = BN_new())
|| !TEST_true(BN_set_word(bn1, expected[DP]))
|| !TEST_ptr(bn2 = BN_new())
|| !TEST_true(BN_set_word(bn2, expected[DQ]))
|| !TEST_ptr(bn3 = BN_new())
|| !TEST_true(BN_set_word(bn3, expected[QINV]))
|| !TEST_true(RSA_set0_crt_params(rsa, bn1, bn2, bn3)))
goto err;
bn1 = bn2 = bn3 = NULL;
if (!TEST_ptr(bn_primes[0] = BN_new())
|| !TEST_true(BN_set_word(bn_primes[0], expected[F3]))
|| !TEST_ptr(bn_exps[0] = BN_new())
|| !TEST_true(BN_set_word(bn_exps[0], expected[E3]))
|| !TEST_ptr(bn_coeffs[0] = BN_new())
|| !TEST_true(BN_set_word(bn_coeffs[0], expected[C2]))
|| !TEST_true(RSA_set0_multi_prime_params(rsa, bn_primes, bn_exps,
bn_coeffs, 1)))
goto err;
if (!TEST_ptr(pk = EVP_PKEY_new())
|| !TEST_true(EVP_PKEY_assign_RSA(pk, rsa)))
goto err;
rsa = NULL;
if (!TEST_ptr(km1 = EVP_KEYMGMT_fetch(fixture->ctx1, "RSA", NULL))
|| !TEST_ptr(km2 = EVP_KEYMGMT_fetch(fixture->ctx2, "RSA", NULL))
|| !TEST_ptr(km3 = EVP_KEYMGMT_fetch(fixture->ctx1, "RSA-PSS", NULL))
|| !TEST_ptr_ne(km1, km2))
goto err;
- while (dup_pk == NULL) {
+ for (;;) {
ret = 0;
km = km3;
/* Check that we can't export an RSA key into an RSA-PSS keymanager */
if (!TEST_ptr_null(provkey2 = evp_pkey_export_to_provider(pk, NULL,
&km,
NULL)))
goto err;
if (!TEST_ptr(provkey = evp_pkey_export_to_provider(pk, NULL, &km1,
NULL))
|| !TEST_true(evp_keymgmt_export(km2, provkey,
OSSL_KEYMGMT_SELECT_KEYPAIR,
&export_cb, keydata)))
goto err;
/*
* At this point, the hope is that keydata will have all the numbers
* from the key.
*/
for (i = 0; i < OSSL_NELEM(expected); i++) {
int rv = TEST_int_eq(expected[i], keydata[i]);
if (!rv)
TEST_info("i = %zu", i);
else
ret++;
}
ret = (ret == OSSL_NELEM(expected));
- if (!ret || !TEST_ptr(dup_pk = EVP_PKEY_dup(pk)))
+
+ if (!ret || dup_pk != NULL)
+ break;
+
+ if (!TEST_ptr(dup_pk = EVP_PKEY_dup(pk)))
goto err;
ret = TEST_int_eq(EVP_PKEY_eq(pk, dup_pk), 1);
EVP_PKEY_free(pk);
pk = dup_pk;
if (!ret)
goto err;
}
err:
RSA_free(rsa);
BN_free(bn1);
BN_free(bn2);
BN_free(bn3);
EVP_PKEY_free(pk);
EVP_KEYMGMT_free(km1);
EVP_KEYMGMT_free(km2);
EVP_KEYMGMT_free(km3);
return ret;
}
static int (*tests[])(FIXTURE *) = {
test_pass_rsa
};
static int test_pass_key(int n)
{
SETUP_TEST_FIXTURE(FIXTURE, set_up);
EXECUTE_TEST(tests[n], tear_down);
return result;
}
static int test_evp_pkey_export_to_provider(int n)
{
OSSL_LIB_CTX *libctx = NULL;
OSSL_PROVIDER *prov = NULL;
X509 *cert = NULL;
BIO *bio = NULL;
X509_PUBKEY *pubkey = NULL;
EVP_KEYMGMT *keymgmt = NULL;
EVP_PKEY *pkey = NULL;
void *keydata = NULL;
int ret = 0;
if (!TEST_ptr(libctx = OSSL_LIB_CTX_new())
|| !TEST_ptr(prov = OSSL_PROVIDER_load(libctx, "default")))
goto end;
if ((bio = BIO_new_file(cert_filename, "r")) == NULL) {
TEST_error("Couldn't open '%s' for reading\n", cert_filename);
TEST_openssl_errors();
goto end;
}
if ((cert = PEM_read_bio_X509(bio, NULL, NULL, NULL)) == NULL) {
TEST_error("'%s' doesn't appear to be a X.509 certificate in PEM format\n",
cert_filename);
TEST_openssl_errors();
goto end;
}
pubkey = X509_get_X509_PUBKEY(cert);
pkey = X509_PUBKEY_get0(pubkey);
if (n == 0) {
if (!TEST_ptr(keydata = evp_pkey_export_to_provider(pkey, NULL,
NULL, NULL)))
goto end;
} else if (n == 1) {
if (!TEST_ptr(keydata = evp_pkey_export_to_provider(pkey, NULL,
&keymgmt, NULL)))
goto end;
} else {
keymgmt = EVP_KEYMGMT_fetch(libctx, "RSA", NULL);
if (!TEST_ptr(keydata = evp_pkey_export_to_provider(pkey, NULL,
&keymgmt, NULL)))
goto end;
}
ret = 1;
end:
BIO_free(bio);
X509_free(cert);
EVP_KEYMGMT_free(keymgmt);
OSSL_PROVIDER_unload(prov);
OSSL_LIB_CTX_free(libctx);
return ret;
}
int setup_tests(void)
{
if (!TEST_ptr(cert_filename = test_get_argument(0)))
return 0;
ADD_ALL_TESTS(test_pass_key, 1);
ADD_ALL_TESTS(test_evp_pkey_export_to_provider, 3);
return 1;
}
diff --git a/crypto/openssl/test/pathed.cnf b/crypto/openssl/test/pathed.cnf
new file mode 100644
index 000000000000..07bdc1fdb209
--- /dev/null
+++ b/crypto/openssl/test/pathed.cnf
@@ -0,0 +1,22 @@
+openssl_conf = openssl_init
+
+# Comment out the next line to ignore configuration errors
+config_diagnostics = 1
+
+[openssl_init]
+providers = provider_sect
+
+[provider_sect]
+default = default_sect
+legacy = legacy_sect
+test = test_sect
+
+[test_sect]
+module = ../test/p_test.so
+activate = false
+
+[default_sect]
+activate = true
+
+[legacy_sect]
+activate = false
diff --git a/crypto/openssl/test/pkey_meth_kdf_test.c b/crypto/openssl/test/pkey_meth_kdf_test.c
index f816d24fb56f..ad58adf48261 100644
--- a/crypto/openssl/test/pkey_meth_kdf_test.c
+++ b/crypto/openssl/test/pkey_meth_kdf_test.c
@@ -1,204 +1,235 @@
/*
- * Copyright 2017-2020 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2017-2024 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 of the EVP_PKEY_CTX_set_* macro family */
#include <stdio.h>
#include <string.h>
#include <openssl/evp.h>
#include <openssl/kdf.h>
#include "testutil.h"
-static int test_kdf_tls1_prf(void)
+static int test_kdf_tls1_prf(int index)
{
int ret = 0;
EVP_PKEY_CTX *pctx;
unsigned char out[16];
size_t outlen = sizeof(out);
if ((pctx = EVP_PKEY_CTX_new_id(EVP_PKEY_TLS1_PRF, NULL)) == NULL) {
TEST_error("EVP_PKEY_TLS1_PRF");
goto err;
}
if (EVP_PKEY_derive_init(pctx) <= 0) {
TEST_error("EVP_PKEY_derive_init");
goto err;
}
if (EVP_PKEY_CTX_set_tls1_prf_md(pctx, EVP_sha256()) <= 0) {
TEST_error("EVP_PKEY_CTX_set_tls1_prf_md");
goto err;
}
if (EVP_PKEY_CTX_set1_tls1_prf_secret(pctx,
(unsigned char *)"secret", 6) <= 0) {
TEST_error("EVP_PKEY_CTX_set1_tls1_prf_secret");
goto err;
}
- if (EVP_PKEY_CTX_add1_tls1_prf_seed(pctx,
- (unsigned char *)"seed", 4) <= 0) {
- TEST_error("EVP_PKEY_CTX_add1_tls1_prf_seed");
- goto err;
+ if (index == 0) {
+ if (EVP_PKEY_CTX_add1_tls1_prf_seed(pctx,
+ (unsigned char *)"seed", 4) <= 0) {
+ TEST_error("EVP_PKEY_CTX_add1_tls1_prf_seed");
+ goto err;
+ }
+ } else {
+ if (EVP_PKEY_CTX_add1_tls1_prf_seed(pctx,
+ (unsigned char *)"se", 2) <= 0) {
+ TEST_error("EVP_PKEY_CTX_add1_tls1_prf_seed");
+ goto err;
+ }
+ if (EVP_PKEY_CTX_add1_tls1_prf_seed(pctx,
+ (unsigned char *)"ed", 2) <= 0) {
+ TEST_error("EVP_PKEY_CTX_add1_tls1_prf_seed");
+ goto err;
+ }
}
if (EVP_PKEY_derive(pctx, out, &outlen) <= 0) {
TEST_error("EVP_PKEY_derive");
goto err;
}
{
const unsigned char expected[sizeof(out)] = {
0x8e, 0x4d, 0x93, 0x25, 0x30, 0xd7, 0x65, 0xa0,
0xaa, 0xe9, 0x74, 0xc3, 0x04, 0x73, 0x5e, 0xcc
};
if (!TEST_mem_eq(out, sizeof(out), expected, sizeof(expected))) {
goto err;
}
}
ret = 1;
err:
EVP_PKEY_CTX_free(pctx);
return ret;
}
-static int test_kdf_hkdf(void)
+static int test_kdf_hkdf(int index)
{
int ret = 0;
EVP_PKEY_CTX *pctx;
unsigned char out[10];
size_t outlen = sizeof(out);
if ((pctx = EVP_PKEY_CTX_new_id(EVP_PKEY_HKDF, NULL)) == NULL) {
TEST_error("EVP_PKEY_HKDF");
goto err;
}
if (EVP_PKEY_derive_init(pctx) <= 0) {
TEST_error("EVP_PKEY_derive_init");
goto err;
}
if (EVP_PKEY_CTX_set_hkdf_md(pctx, EVP_sha256()) <= 0) {
TEST_error("EVP_PKEY_CTX_set_hkdf_md");
goto err;
}
if (EVP_PKEY_CTX_set1_hkdf_salt(pctx, (const unsigned char *)"salt", 4)
<= 0) {
TEST_error("EVP_PKEY_CTX_set1_hkdf_salt");
goto err;
}
if (EVP_PKEY_CTX_set1_hkdf_key(pctx, (const unsigned char *)"secret", 6)
<= 0) {
TEST_error("EVP_PKEY_CTX_set1_hkdf_key");
goto err;
}
- if (EVP_PKEY_CTX_add1_hkdf_info(pctx, (const unsigned char *)"label", 5)
+ if (index == 0) {
+ if (EVP_PKEY_CTX_add1_hkdf_info(pctx, (const unsigned char *)"label", 5)
<= 0) {
- TEST_error("EVP_PKEY_CTX_set1_hkdf_info");
- goto err;
+ TEST_error("EVP_PKEY_CTX_add1_hkdf_info");
+ goto err;
+ }
+ } else {
+ if (EVP_PKEY_CTX_add1_hkdf_info(pctx, (const unsigned char *)"lab", 3)
+ <= 0) {
+ TEST_error("EVP_PKEY_CTX_add1_hkdf_info");
+ goto err;
+ }
+ if (EVP_PKEY_CTX_add1_hkdf_info(pctx, (const unsigned char *)"el", 2)
+ <= 0) {
+ TEST_error("EVP_PKEY_CTX_add1_hkdf_info");
+ goto err;
+ }
}
if (EVP_PKEY_derive(pctx, out, &outlen) <= 0) {
TEST_error("EVP_PKEY_derive");
goto err;
}
{
const unsigned char expected[sizeof(out)] = {
0x2a, 0xc4, 0x36, 0x9f, 0x52, 0x59, 0x96, 0xf8, 0xde, 0x13
};
if (!TEST_mem_eq(out, sizeof(out), expected, sizeof(expected))) {
goto err;
}
}
ret = 1;
err:
EVP_PKEY_CTX_free(pctx);
return ret;
}
#ifndef OPENSSL_NO_SCRYPT
static int test_kdf_scrypt(void)
{
int ret = 0;
EVP_PKEY_CTX *pctx;
unsigned char out[64];
size_t outlen = sizeof(out);
if ((pctx = EVP_PKEY_CTX_new_id(EVP_PKEY_SCRYPT, NULL)) == NULL) {
TEST_error("EVP_PKEY_SCRYPT");
goto err;
}
if (EVP_PKEY_derive_init(pctx) <= 0) {
TEST_error("EVP_PKEY_derive_init");
goto err;
}
if (EVP_PKEY_CTX_set1_pbe_pass(pctx, "password", 8) <= 0) {
TEST_error("EVP_PKEY_CTX_set1_pbe_pass");
goto err;
}
if (EVP_PKEY_CTX_set1_scrypt_salt(pctx, (unsigned char *)"NaCl", 4) <= 0) {
TEST_error("EVP_PKEY_CTX_set1_scrypt_salt");
goto err;
}
if (EVP_PKEY_CTX_set_scrypt_N(pctx, 1024) <= 0) {
TEST_error("EVP_PKEY_CTX_set_scrypt_N");
goto err;
}
if (EVP_PKEY_CTX_set_scrypt_r(pctx, 8) <= 0) {
TEST_error("EVP_PKEY_CTX_set_scrypt_r");
goto err;
}
if (EVP_PKEY_CTX_set_scrypt_p(pctx, 16) <= 0) {
TEST_error("EVP_PKEY_CTX_set_scrypt_p");
goto err;
}
if (EVP_PKEY_CTX_set_scrypt_maxmem_bytes(pctx, 16) <= 0) {
TEST_error("EVP_PKEY_CTX_set_maxmem_bytes");
goto err;
}
if (EVP_PKEY_derive(pctx, out, &outlen) > 0) {
TEST_error("EVP_PKEY_derive should have failed");
goto err;
}
if (EVP_PKEY_CTX_set_scrypt_maxmem_bytes(pctx, 10 * 1024 * 1024) <= 0) {
TEST_error("EVP_PKEY_CTX_set_maxmem_bytes");
goto err;
}
if (EVP_PKEY_derive(pctx, out, &outlen) <= 0) {
TEST_error("EVP_PKEY_derive");
goto err;
}
{
const unsigned char expected[sizeof(out)] = {
0xfd, 0xba, 0xbe, 0x1c, 0x9d, 0x34, 0x72, 0x00,
0x78, 0x56, 0xe7, 0x19, 0x0d, 0x01, 0xe9, 0xfe,
0x7c, 0x6a, 0xd7, 0xcb, 0xc8, 0x23, 0x78, 0x30,
0xe7, 0x73, 0x76, 0x63, 0x4b, 0x37, 0x31, 0x62,
0x2e, 0xaf, 0x30, 0xd9, 0x2e, 0x22, 0xa3, 0x88,
0x6f, 0xf1, 0x09, 0x27, 0x9d, 0x98, 0x30, 0xda,
0xc7, 0x27, 0xaf, 0xb9, 0x4a, 0x83, 0xee, 0x6d,
0x83, 0x60, 0xcb, 0xdf, 0xa2, 0xcc, 0x06, 0x40
};
if (!TEST_mem_eq(out, sizeof(out), expected, sizeof(expected))) {
goto err;
}
}
ret = 1;
err:
EVP_PKEY_CTX_free(pctx);
return ret;
}
#endif
int setup_tests(void)
{
- ADD_TEST(test_kdf_tls1_prf);
- ADD_TEST(test_kdf_hkdf);
+ int tests = 1;
+
+ if (fips_provider_version_ge(NULL, 3, 3, 1))
+ tests = 2;
+
+ ADD_ALL_TESTS(test_kdf_tls1_prf, tests);
+ ADD_ALL_TESTS(test_kdf_hkdf, tests);
#ifndef OPENSSL_NO_SCRYPT
ADD_TEST(test_kdf_scrypt);
#endif
return 1;
}
diff --git a/crypto/openssl/test/prov_config_test.c b/crypto/openssl/test/prov_config_test.c
index b44ec78d8d24..f93d8d62be6a 100644
--- a/crypto/openssl/test/prov_config_test.c
+++ b/crypto/openssl/test/prov_config_test.c
@@ -1,91 +1,145 @@
/*
- * Copyright 2021 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2021-2024 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 <sys/stat.h>
#include <openssl/evp.h>
#include <openssl/conf.h>
#include "testutil.h"
static char *configfile = NULL;
static char *recurseconfigfile = NULL;
+static char *pathedconfig = NULL;
/*
* Test to make sure there are no leaks or failures from loading the config
* file twice.
*/
static int test_double_config(void)
{
OSSL_LIB_CTX *ctx = OSSL_LIB_CTX_new();
int testresult = 0;
EVP_MD *sha256 = NULL;
if (!TEST_ptr(configfile))
return 0;
if (!TEST_ptr(ctx))
return 0;
if (!TEST_true(OSSL_LIB_CTX_load_config(ctx, configfile)))
return 0;
if (!TEST_true(OSSL_LIB_CTX_load_config(ctx, configfile)))
return 0;
/* Check we can actually fetch something */
sha256 = EVP_MD_fetch(ctx, "SHA2-256", NULL);
if (!TEST_ptr(sha256))
goto err;
testresult = 1;
err:
EVP_MD_free(sha256);
OSSL_LIB_CTX_free(ctx);
return testresult;
}
static int test_recursive_config(void)
{
OSSL_LIB_CTX *ctx = OSSL_LIB_CTX_new();
int testresult = 0;
unsigned long err;
if (!TEST_ptr(recurseconfigfile))
goto err;
if (!TEST_ptr(ctx))
goto err;
if (!TEST_false(OSSL_LIB_CTX_load_config(ctx, recurseconfigfile)))
goto err;
err = ERR_peek_error();
/* We expect to get a recursion error here */
if (ERR_GET_REASON(err) == CONF_R_RECURSIVE_SECTION_REFERENCE)
testresult = 1;
err:
OSSL_LIB_CTX_free(ctx);
return testresult;
}
+#define P_TEST_PATH "/../test/p_test.so"
+static int test_path_config(void)
+{
+ OSSL_LIB_CTX *ctx = NULL;
+ OSSL_PROVIDER *prov;
+ int testresult = 0;
+ struct stat sbuf;
+ char *module_path = getenv("OPENSSL_MODULES");
+ char *full_path = NULL;
+ int rc;
+
+ if (!TEST_ptr(module_path))
+ return 0;
+
+ full_path = OPENSSL_zalloc(strlen(module_path) + strlen(P_TEST_PATH) + 1);
+ if (!TEST_ptr(full_path))
+ return 0;
+
+ strcpy(full_path, module_path);
+ full_path = strcat(full_path, P_TEST_PATH);
+ TEST_info("full path is %s", full_path);
+ rc = stat(full_path, &sbuf);
+ OPENSSL_free(full_path);
+ if (rc == -1)
+ return TEST_skip("Skipping modulepath test as provider not present");
+
+ if (!TEST_ptr(pathedconfig))
+ return 0;
+
+ ctx = OSSL_LIB_CTX_new();
+ if (!TEST_ptr(ctx))
+ return 0;
+
+ if (!TEST_true(OSSL_LIB_CTX_load_config(ctx, pathedconfig)))
+ goto err;
+
+ /* attempt to manually load the test provider */
+ if (!TEST_ptr(prov = OSSL_PROVIDER_load(ctx, "test")))
+ goto err;
+
+ OSSL_PROVIDER_unload(prov);
+
+ testresult = 1;
+ err:
+ OSSL_LIB_CTX_free(ctx);
+ return testresult;
+}
+
OPT_TEST_DECLARE_USAGE("configfile\n")
int setup_tests(void)
{
if (!test_skip_common_options()) {
TEST_error("Error parsing test options\n");
return 0;
}
if (!TEST_ptr(configfile = test_get_argument(0)))
return 0;
if (!TEST_ptr(recurseconfigfile = test_get_argument(1)))
return 0;
+ if (!TEST_ptr(pathedconfig = test_get_argument(2)))
+ return 0;
+
ADD_TEST(test_recursive_config);
ADD_TEST(test_double_config);
+ ADD_TEST(test_path_config);
return 1;
}
diff --git a/crypto/openssl/test/recipes/15-test_dsaparam_data/invalid/p10240_q256_too_big.pem b/crypto/openssl/test/recipes/15-test_dsaparam_data/invalid/p10240_q256_too_big.pem
new file mode 100644
index 000000000000..e85e2953b7a2
--- /dev/null
+++ b/crypto/openssl/test/recipes/15-test_dsaparam_data/invalid/p10240_q256_too_big.pem
@@ -0,0 +1,57 @@
+-----BEGIN DSA PARAMETERS-----
+MIIKLAKCBQEAym47LzPFZdbz16WvjczLKuzLtsP8yRk/exxL4bBthJhP1qOwctja
+p1586SF7gDxCMn7yWVEYdfRbFefGoq0gj1XOE917XqlbnkmZhMgxut2KbNJo/xil
+XNFUjGvKs3F413U9rAodC8f07cWHP1iTcWL+vPe6u2yilKWYYfnLWHQH+Z6aPrrF
+x/R08LI6DZ6nEsIo+hxaQnEtx+iqNTJC6Q1RIjWDqxQkFVTkJ0Y7miRDXmRdneWk
+oLrMZRpaXr5l5tSjEghh1pBgJcdyOv0lh4dlDy/alAiqE2Qlb667yHl6A9dDPlpW
+dAntpffy4LwOxfbuEhISvKjjQoBwIvYE4TBPqL0Q6bC6HgQ4+tqd9b44pQjdIQjb
+Xcjc6azheITSnPEex3OdKtKoQeRq01qCeLBpMXu1c+CTf4ApKArZvT3vZSg0hM1O
+pR71bRZrEEegDj0LH2HCgI5W6H3blOS9A0kUTddCoQXr2lsVdiPtRbPKH1gcd9FQ
+P8cGrvbakpTiC0dCczOMDaCteM1QNILlkM7ZoV6VghsKvDnFPxFsiIr5GgjasXP5
+hhbn3g7sDoq1LiTEo+IKQY28pBWx7etSOSRuXW/spnvCkivZla7lSEGljoy9QlQ2
+UZmsEQI9G3YyzgpxHvKZBK1CiZVTywdYKTZ4TYCxvqzhYhjv2bqbpjI12HRFLojB
+koyEmMSp53lldCzp158PrIanqSp2rksMR8SmmCL3FwfAp2OjqFMEglG9DT8x0WaN
+TLSkjGC6t2csMte7WyU1ekNoFDKfMjDSAz0+xIx21DEmZtYqFOg1DNPK1xYLS0pl
+RSMRRkJVN2mk/G7/1oxlB8Wb9wgi3GKUqqCYT11SnBjzq0NdoJ3E4GMedp5Lx3AZ
+4mFuRPUd4iV86tE0XDSHSFE7Y3ZkrOjD7Q/26/L53L/UH5z4HW6CHP5os7QERJjg
+c1S3x87wXWo9QXbB9b2xmf+c+aWwAAr1cviw38tru58jF3/IGyduj9H8claKQqBG
+cIOUF4aNe1hK2K3ArAOApUxr4KE+tCvrltRfiTmVFip0g9Jt1CPY3Zu7Bd4Z2ZkE
+DtSztpwa49HrWF5E9xpquvBL2U8jQ68E7Xd8Wp4orI/TIChriamBmdkgRz3H2LvN
+Ozb6+hsnEGrz3sp2RVAToSqA9ysa6nHZdfufPNtMEbQdO/k1ehmGRb0ljBRsO6b2
+rsG2eYuC8tg8eCrIkua0TGRI7g6a4K32AJdzaX6NsISaaIW+OYJuoDSscvD3oOg8
+PPEhU+zM7xJskTA+jxvPlikKx8V7MNHOCQECldJlUBwzJvqp40JvwfnDsF+8VYwd
+UaiieR3pzMzyTjpReXRmZbnRPusRcsVzxb2OhB79wmuy4UPjjQBX+7eD0rs8xxvW
+5a5q1Cjq4AvbwmmcA/wDrHDOjcbD/zodad2O1QtBWa/R4xyWea4zKsflgACE1zY9
+wW2br7+YQFekcrXkkkEzgxd6zxv8KVEDpXRZjmAM1cI5LvkoN64To4GedN8Qe/G7
+R9SZh9gnS17PTP64hK+aYqhFafMdu87q/+qLfxaSux727qE5hiW01u4nnWhACf9s
+xuOozowKqxZxkolMIyZv6Lddwy1Zv5qjCyd0DvM/1skpXWkb9kfabYC+OhjsjVhs
+0Ktfs6a5B3eixiw5x94hhIcTEcS4hmvhGUL72FiTca6ZeSERTKmNBy8CIQC9/ZUN
+uU/V5JTcnYyUGHzm7+XcZBjyGBagBj9rCmW3SQKCBQAJ/k9rb39f1cO+/3XDEMjy
+9bIEXSuS48g5RAc1UGd5nrrBQwuDxGWFyz0yvAY7LgyidZuJS21+MAp9EY7AOMmx
+TDttifNaBJYt4GZ8of166PcqTKkHQwq5uBpxeSDv/ZE8YbYfaCtLTcUC8KlO+l36
+gjJHSkdkflSsGy1yObSNDQDfVAAwQs//TjDMnuEtvlNXZllsTvFFBceXVETn10K2
+ZMmdSIJNfLnjReUKEN6PfeGqv7F4xoyGwUybEfRE4u5RmXrqCODaIjY3SNMrOq8B
+R3Ata/cCozsM1jIdIW2z+OybDJH+BYsYm2nkSZQjZS6javTYClLrntEKG/hAQwL8
+F16YLOQXpHhgiAaWnTZzANtLppB2+5qCVy5ElzKongOwT8JTjTFXOaRnqe/ngm9W
+SSbrxfDaoWUOyK9XD8Cydzpv3n4Y8nWNGayi7/yAFCU36Ri040ufgv/TZLuKacnl
++3ga3ZUpRlSigzx0kb1+KjTSWeQ8vE/psdWjvBukVEbzdUauMLyRLo/6znSVvvPX
+UGhviThE5uhrsUg+wEPFINriSHfF7JDKVhDcJnLBdaXvfN52pkF/naLBF5Rt3Gvq
+fjCxjx0Sy9Lag1hDN4dor7dzuO7wmwOS01DJW1PtNLuuH0Bbqh1kYSaQkmyXBZWX
+qo8K3nkoDM0niOtJJubOhTNrGmSaZpNXkK3Mcy9rBbdvEs5O0Jmqaax/eOdU0Yot
+B3lX+3ddOseT2ZEFjzObqTtkWuFBeBxuYNcRTsu3qMdIBsEb8URQdsTtjoIja2fK
+hreVgjK36GW70KXEl8V/vq5qjQulmqkBEjmilcDuiREKqQuyeagUOnhQaBplqVco
+4xznh5DMBMRbpGb5lHxKv4cPNi+uNAJ5i98zWUM1JRt6aXnRCuWcll1z8fRZ+5kD
+vK9FaZU3VRMK/eknEG49cGr8OuJ6ZRSaC+tKwV1y+amkSZpKPWnk2bUnQI3ApJv3
+k1e1EToeECpMUkLMDgNbpKBoz4nqMEvAAlYgw9xKNbLlQlahqTVEAmaJHh4yDMDy
+i7IZ9Wrn47IGoR7s3cvhDHUpRPeW4nsmgzj+tf5EAxemI61STZJTTWo0iaPGJxct
+9nhOOhw1I38Mvm4vkAbFH7YJ0B6QrjjYL2MbOTp5JiIh4vdOeWwNo9/y4ffyaN5+
+ADpxuuIAmcbdr6GPOhkOFFixRJa0B2eP1i032HESlLs8RB9oYtdTXdXQotnIgJGd
+Y8tSKOa1zjzeLHn3AVpRZTUW++/BxmApV3GKIeG8fsUjg/df0QRrBcdC/1uccdaG
+KKlAOwlywVn5jUlwHkTmDiTM9w5AqVVGHZ2b+4ZgQW8jnPKN0SrKf6U555D+zp7E
+x4uXoE8ojN9y8m8UKf0cTLnujH2XgZorjPfuMOt5VZEhQFMS2QaljSeni5CJJ8gk
+XtztNqfBlAtWR4V5iAHeQOfIB2YaOy8GESda89tyKraKeaez41VblpTVHTeq9IIF
+YB4cQA2PfuNaGVRGLMAgT3Dvl+mxxxeJyxnGAiUcETU/jJJt9QombiuszBlYGQ5d
+ELOSm/eQSRARV9zNSt5jaQlMSjMBqenIEM09BzYqa7jDwqoztFxNdO8bcuQPuKwa
+4z3bBZ1yYm63WFdNbQqqGEwc0OYmqg1raJ0zltgHyjFyw8IGu4g/wETs+nVQcH7D
+vKuje86bePD6kD/LH3wmkA==
+-----END DSA PARAMETERS-----
diff --git a/crypto/openssl/test/recipes/25-test_req.t b/crypto/openssl/test/recipes/25-test_req.t
index fe02d29c634f..932635f4b2c1 100644
--- a/crypto/openssl/test/recipes/25-test_req.t
+++ b/crypto/openssl/test/recipes/25-test_req.t
@@ -1,491 +1,492 @@
#! /usr/bin/env perl
# Copyright 2015-2024 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 OpenSSL::Test::Utils;
use OpenSSL::Test qw/:DEFAULT srctop_file/;
setup("test_req");
-plan tests => 49;
+plan tests => 50;
require_ok(srctop_file('test', 'recipes', 'tconversion.pl'));
my @certs = qw(test certs);
# What type of key to generate?
my @req_new;
if (disabled("rsa")) {
@req_new = ("-newkey", "dsa:".srctop_file("apps", "dsa512.pem"));
} else {
@req_new = ("-new");
note("There should be a 2 sequences of .'s and some +'s.");
note("There should not be more that at most 80 per line");
}
# Prevent MSys2 filename munging for arguments that look like file paths but
# aren't
$ENV{MSYS2_ARG_CONV_EXCL} = "/CN=";
# Check for duplicate -addext parameters, and one "working" case.
my @addext_args = ( "openssl", "req", "-new", "-out", "testreq.pem",
"-key", srctop_file("test", "certs", "ee-key.pem"),
"-config", srctop_file("test", "test.cnf"), @req_new );
my $val = "subjectAltName=DNS:example.com";
my $val1 = "subjectAltName=otherName:1.2.3.4;UTF8:test,email:info\@example.com";
my $val2 = " " . $val;
my $val3 = $val;
$val3 =~ s/=/ =/;
ok( run(app([@addext_args, "-addext", $val])));
ok( run(app([@addext_args, "-addext", $val1])));
$val1 =~ s/UTF8/XXXX/; # execute the error handling in do_othername
ok(!run(app([@addext_args, "-addext", $val1])));
ok(!run(app([@addext_args, "-addext", $val, "-addext", $val])));
ok(!run(app([@addext_args, "-addext", $val, "-addext", $val2])));
ok(!run(app([@addext_args, "-addext", $val, "-addext", $val3])));
ok(!run(app([@addext_args, "-addext", $val2, "-addext", $val3])));
ok(run(app([@addext_args, "-addext", "SXNetID=1:one, 2:two, 3:three"])));
+ok(run(app([@addext_args, "-addext", "subjectAltName=dirName:dirname_sec"])));
# If a CSR is provided with neither of -key or -CA/-CAkey, this should fail.
ok(!run(app(["openssl", "req", "-x509",
"-in", srctop_file(@certs, "x509-check.csr"),
"-out", "testreq.pem"])));
subtest "generating alt certificate requests with RSA" => sub {
plan tests => 3;
SKIP: {
skip "RSA is not supported by this OpenSSL build", 2
if disabled("rsa");
ok(run(app(["openssl", "req",
"-config", srctop_file("test", "test.cnf"),
"-section", "altreq",
"-new", "-out", "testreq-rsa.pem", "-utf8",
"-key", srctop_file("test", "testrsa.pem")])),
"Generating request");
ok(run(app(["openssl", "req",
"-config", srctop_file("test", "test.cnf"),
"-verify", "-in", "testreq-rsa.pem", "-noout"])),
"Verifying signature on request");
ok(run(app(["openssl", "req",
"-config", srctop_file("test", "test.cnf"),
"-section", "altreq",
"-verify", "-in", "testreq-rsa.pem", "-noout"])),
"Verifying signature on request");
}
};
subtest "generating certificate requests with RSA" => sub {
plan tests => 8;
SKIP: {
skip "RSA is not supported by this OpenSSL build", 2
if disabled("rsa");
ok(!run(app(["openssl", "req",
"-config", srctop_file("test", "test.cnf"),
"-new", "-out", "testreq-rsa.pem", "-utf8",
"-key", srctop_file("test", "testrsa.pem"),
"-keyform", "DER"])),
"Checking that mismatching keyform fails");
ok(run(app(["openssl", "req",
"-config", srctop_file("test", "test.cnf"),
"-new", "-out", "testreq-rsa.pem", "-utf8",
"-key", srctop_file("test", "testrsa.pem"),
"-keyform", "PEM"])),
"Generating request");
ok(run(app(["openssl", "req",
"-config", srctop_file("test", "test.cnf"),
"-verify", "-in", "testreq-rsa.pem", "-noout"])),
"Verifying signature on request");
ok(run(app(["openssl", "req",
"-config", srctop_file("test", "test.cnf"),
"-modulus", "-in", "testreq-rsa.pem", "-noout"])),
"Printing a modulus of the request key");
ok(run(app(["openssl", "req",
"-config", srctop_file("test", "test.cnf"),
"-new", "-out", "testreq_withattrs_pem.pem", "-utf8",
"-key", srctop_file("test", "testrsa_withattrs.pem")])),
"Generating request from a key with extra attributes - PEM");
ok(run(app(["openssl", "req",
"-config", srctop_file("test", "test.cnf"),
"-verify", "-in", "testreq_withattrs_pem.pem", "-noout"])),
"Verifying signature on request from a key with extra attributes - PEM");
ok(run(app(["openssl", "req",
"-config", srctop_file("test", "test.cnf"),
"-new", "-out", "testreq_withattrs_der.pem", "-utf8",
"-key", srctop_file("test", "testrsa_withattrs.der"),
"-keyform", "DER"])),
"Generating request from a key with extra attributes - PEM");
ok(run(app(["openssl", "req",
"-config", srctop_file("test", "test.cnf"),
"-verify", "-in", "testreq_withattrs_der.pem", "-noout"])),
"Verifying signature on request from a key with extra attributes - PEM");
}
};
subtest "generating certificate requests with RSA-PSS" => sub {
plan tests => 12;
SKIP: {
skip "RSA is not supported by this OpenSSL build", 2
if disabled("rsa");
ok(run(app(["openssl", "req",
"-config", srctop_file("test", "test.cnf"),
"-new", "-out", "testreq-rsapss.pem", "-utf8",
"-key", srctop_file("test", "testrsapss.pem")])),
"Generating request");
ok(run(app(["openssl", "req",
"-config", srctop_file("test", "test.cnf"),
"-verify", "-in", "testreq-rsapss.pem", "-noout"])),
"Verifying signature on request");
ok(run(app(["openssl", "req",
"-config", srctop_file("test", "test.cnf"),
"-new", "-out", "testreq-rsapss2.pem", "-utf8",
"-sigopt", "rsa_padding_mode:pss",
"-sigopt", "rsa_pss_saltlen:-1",
"-key", srctop_file("test", "testrsapss.pem")])),
"Generating request");
ok(run(app(["openssl", "req",
"-config", srctop_file("test", "test.cnf"),
"-verify", "-in", "testreq-rsapss2.pem", "-noout"])),
"Verifying signature on request");
ok(run(app(["openssl", "req",
"-config", srctop_file("test", "test.cnf"),
"-new", "-out", "testreq-rsapssmand.pem", "-utf8",
"-sigopt", "rsa_padding_mode:pss",
"-key", srctop_file("test", "testrsapssmandatory.pem")])),
"Generating request");
ok(run(app(["openssl", "req",
"-config", srctop_file("test", "test.cnf"),
"-verify", "-in", "testreq-rsapssmand.pem", "-noout"])),
"Verifying signature on request");
ok(run(app(["openssl", "req",
"-config", srctop_file("test", "test.cnf"),
"-new", "-out", "testreq-rsapssmand2.pem", "-utf8",
"-sigopt", "rsa_pss_saltlen:100",
"-key", srctop_file("test", "testrsapssmandatory.pem")])),
"Generating request");
ok(run(app(["openssl", "req",
"-config", srctop_file("test", "test.cnf"),
"-verify", "-in", "testreq-rsapssmand2.pem", "-noout"])),
"Verifying signature on request");
ok(!run(app(["openssl", "req",
"-config", srctop_file("test", "test.cnf"),
"-new", "-out", "testreq-rsapss3.pem", "-utf8",
"-sigopt", "rsa_padding_mode:pkcs1",
"-key", srctop_file("test", "testrsapss.pem")])),
"Generating request with expected failure");
ok(!run(app(["openssl", "req",
"-config", srctop_file("test", "test.cnf"),
"-new", "-out", "testreq-rsapss3.pem", "-utf8",
"-sigopt", "rsa_pss_saltlen:-4",
"-key", srctop_file("test", "testrsapss.pem")])),
"Generating request with expected failure");
ok(!run(app(["openssl", "req",
"-config", srctop_file("test", "test.cnf"),
"-new", "-out", "testreq-rsapssmand3.pem", "-utf8",
"-sigopt", "rsa_pss_saltlen:10",
"-key", srctop_file("test", "testrsapssmandatory.pem")])),
"Generating request with expected failure");
ok(!run(app(["openssl", "req",
"-config", srctop_file("test", "test.cnf"),
"-new", "-out", "testreq-rsapssmand3.pem", "-utf8",
"-sha256",
"-key", srctop_file("test", "testrsapssmandatory.pem")])),
"Generating request with expected failure");
}
};
subtest "generating certificate requests with DSA" => sub {
plan tests => 2;
SKIP: {
skip "DSA is not supported by this OpenSSL build", 2
if disabled("dsa");
ok(run(app(["openssl", "req",
"-config", srctop_file("test", "test.cnf"),
"-new", "-out", "testreq-dsa.pem", "-utf8",
"-key", srctop_file("test", "testdsa.pem")])),
"Generating request");
ok(run(app(["openssl", "req",
"-config", srctop_file("test", "test.cnf"),
"-verify", "-in", "testreq-dsa.pem", "-noout"])),
"Verifying signature on request");
}
};
subtest "generating certificate requests with ECDSA" => sub {
plan tests => 2;
SKIP: {
skip "ECDSA is not supported by this OpenSSL build", 2
if disabled("ec");
ok(run(app(["openssl", "req",
"-config", srctop_file("test", "test.cnf"),
"-new", "-out", "testreq-ec.pem", "-utf8",
"-key", srctop_file("test", "testec-p256.pem")])),
"Generating request");
ok(run(app(["openssl", "req",
"-config", srctop_file("test", "test.cnf"),
"-verify", "-in", "testreq-ec.pem", "-noout"])),
"Verifying signature on request");
}
};
subtest "generating certificate requests with Ed25519" => sub {
plan tests => 2;
SKIP: {
skip "Ed25519 is not supported by this OpenSSL build", 2
if disabled("ec");
ok(run(app(["openssl", "req",
"-config", srctop_file("test", "test.cnf"),
"-new", "-out", "testreq-ed25519.pem", "-utf8",
"-key", srctop_file("test", "tested25519.pem")])),
"Generating request");
ok(run(app(["openssl", "req",
"-config", srctop_file("test", "test.cnf"),
"-verify", "-in", "testreq-ed25519.pem", "-noout"])),
"Verifying signature on request");
}
};
subtest "generating certificate requests with Ed448" => sub {
plan tests => 2;
SKIP: {
skip "Ed448 is not supported by this OpenSSL build", 2
if disabled("ec");
ok(run(app(["openssl", "req",
"-config", srctop_file("test", "test.cnf"),
"-new", "-out", "testreq-ed448.pem", "-utf8",
"-key", srctop_file("test", "tested448.pem")])),
"Generating request");
ok(run(app(["openssl", "req",
"-config", srctop_file("test", "test.cnf"),
"-verify", "-in", "testreq-ed448.pem", "-noout"])),
"Verifying signature on request");
}
};
subtest "generating certificate requests" => sub {
plan tests => 2;
ok(run(app(["openssl", "req", "-config", srctop_file("test", "test.cnf"),
"-key", srctop_file("test", "certs", "ee-key.pem"),
@req_new, "-out", "testreq.pem"])),
"Generating request");
ok(run(app(["openssl", "req", "-config", srctop_file("test", "test.cnf"),
"-verify", "-in", "testreq.pem", "-noout"])),
"Verifying signature on request");
};
subtest "generating SM2 certificate requests" => sub {
plan tests => 4;
SKIP: {
skip "SM2 is not supported by this OpenSSL build", 4
if disabled("sm2");
ok(run(app(["openssl", "req",
"-config", srctop_file("test", "test.cnf"),
"-new", "-key", srctop_file(@certs, "sm2.key"),
"-sigopt", "distid:1234567812345678",
"-out", "testreq-sm2.pem", "-sm3"])),
"Generating SM2 certificate request");
ok(run(app(["openssl", "req",
"-config", srctop_file("test", "test.cnf"),
"-verify", "-in", "testreq-sm2.pem", "-noout",
"-vfyopt", "distid:1234567812345678", "-sm3"])),
"Verifying signature on SM2 certificate request");
ok(run(app(["openssl", "req",
"-config", srctop_file("test", "test.cnf"),
"-new", "-key", srctop_file(@certs, "sm2.key"),
"-sigopt", "hexdistid:DEADBEEF",
"-out", "testreq-sm2.pem", "-sm3"])),
"Generating SM2 certificate request with hex id");
ok(run(app(["openssl", "req",
"-config", srctop_file("test", "test.cnf"),
"-verify", "-in", "testreq-sm2.pem", "-noout",
"-vfyopt", "hexdistid:DEADBEEF", "-sm3"])),
"Verifying signature on SM2 certificate request");
}
};
my @openssl_args = ("req", "-config", srctop_file("apps", "openssl.cnf"));
run_conversion('req conversions',
"testreq.pem");
run_conversion('req conversions -- testreq2',
srctop_file("test", "testreq2.pem"));
sub run_conversion {
my $title = shift;
my $reqfile = shift;
subtest $title => sub {
run(app(["openssl", @openssl_args,
"-in", $reqfile, "-inform", "p",
"-noout", "-text"],
stderr => "req-check.err", stdout => undef));
open DATA, "req-check.err";
SKIP: {
plan skip_all => "skipping req conversion test for $reqfile"
if grep /Unknown Public Key/, map { s/\R//; } <DATA>;
tconversion( -type => 'req', -in => $reqfile,
-args => [ @openssl_args ] );
}
close DATA;
unlink "req-check.err";
done_testing();
};
}
# Test both generation and verification of certs w.r.t. RFC 5280 requirements
my $ca_cert; # will be set below
sub generate_cert {
my $cert = shift @_;
my $ss = $cert =~ m/self-signed/;
my $is_ca = $cert =~ m/CA/;
my $cn = $is_ca ? "CA" : "EE";
my $ca_key = srctop_file(@certs, "ca-key.pem");
my $key = $is_ca ? $ca_key : srctop_file(@certs, "ee-key.pem");
my @cmd = ("openssl", "req", "-config", "", "-x509",
"-subj", "/CN=$cn", @_, "-out", $cert);
push(@cmd, ("-key", $key)) if $ss;
push(@cmd, ("-CA", $ca_cert, "-CAkey", $ca_key)) unless $ss;
ok(run(app([@cmd])), "generate $cert");
}
sub has_SKID {
my $cert = shift @_;
my $expect = shift @_;
cert_contains($cert, "Subject Key Identifier", $expect);
}
sub has_AKID {
my $cert = shift @_;
my $expect = shift @_;
cert_contains($cert, "Authority Key Identifier", $expect);
}
sub has_keyUsage {
my $cert = shift @_;
my $expect = shift @_;
cert_contains($cert, "Key Usage", $expect);
}
sub strict_verify {
my $cert = shift @_;
my $expect = shift @_;
my $trusted = shift @_;
$trusted = $cert unless $trusted;
ok(run(app(["openssl", "verify", "-x509_strict", "-trusted", $trusted,
"-partial_chain", $cert])) == $expect,
"strict verify allow $cert");
}
my @v3_ca = ("-addext", "basicConstraints = critical,CA:true",
"-addext", "keyUsage = keyCertSign");
my $SKID_AKID = "subjectKeyIdentifier,authorityKeyIdentifier";
my $cert = "self-signed_v1_CA_no_KIDs.pem";
generate_cert($cert);
cert_ext_has_n_different_lines($cert, 0, $SKID_AKID); # no SKID and no AKID
#TODO strict_verify($cert, 1); # self-signed v1 root cert should be accepted as CA
$ca_cert = "self-signed_v3_CA_default_SKID.pem";
generate_cert($ca_cert, @v3_ca);
has_SKID($ca_cert, 1);
has_AKID($ca_cert, 0);
strict_verify($ca_cert, 1);
$cert = "self-signed_v3_CA_no_SKID.pem";
generate_cert($cert, @v3_ca, "-addext", "subjectKeyIdentifier = none");
cert_ext_has_n_different_lines($cert, 0, $SKID_AKID); # no SKID and no AKID
#TODO strict_verify($cert, 0);
$cert = "self-signed_v3_CA_both_KIDs.pem";
generate_cert($cert, @v3_ca, "-addext", "subjectKeyIdentifier = hash",
"-addext", "authorityKeyIdentifier = keyid:always");
cert_ext_has_n_different_lines($cert, 3, $SKID_AKID); # SKID == AKID
strict_verify($cert, 1);
$cert = "self-signed_v3_EE_wrong_keyUsage.pem";
generate_cert($cert, "-addext", "keyUsage = keyCertSign");
#TODO strict_verify($cert, 1); # should be accepted because RFC 5280 does not apply
$cert = "v3_EE_default_KIDs.pem";
generate_cert($cert, "-addext", "keyUsage = dataEncipherment",
"-key", srctop_file(@certs, "ee-key.pem"));
cert_ext_has_n_different_lines($cert, 4, $SKID_AKID); # SKID != AKID
strict_verify($cert, 1, $ca_cert);
$cert = "v3_EE_no_AKID.pem";
generate_cert($cert, "-addext", "authorityKeyIdentifier = none",
"-key", srctop_file(@certs, "ee-key.pem"));
has_SKID($cert, 1);
has_AKID($cert, 0);
strict_verify($cert, 0, $ca_cert);
$cert = "self-issued_v3_EE_default_KIDs.pem";
generate_cert($cert, "-addext", "keyUsage = dataEncipherment",
"-in", srctop_file(@certs, "x509-check.csr"));
cert_ext_has_n_different_lines($cert, 4, $SKID_AKID); # SKID != AKID
strict_verify($cert, 1);
my $cert = "self-signed_CA_no_keyUsage.pem";
generate_cert($cert, "-in", srctop_file(@certs, "ext-check.csr"));
has_keyUsage($cert, 0);
my $cert = "self-signed_CA_with_keyUsages.pem";
generate_cert($cert, "-in", srctop_file(@certs, "ext-check.csr"),
"-copy_extensions", "copy");
has_keyUsage($cert, 1);
# Generate cert using req with '-modulus'
ok(run(app(["openssl", "req", "-x509", "-new", "-days", "365",
"-key", srctop_file("test", "testrsa.pem"),
"-config", srctop_file('test', 'test.cnf'),
"-out", "testreq-cert.pem",
"-modulus"])), "cert req creation - with -modulus");
# Verify cert
ok(run(app(["openssl", "x509", "-in", "testreq-cert.pem",
"-noout", "-text"])), "cert verification");
diff --git a/crypto/openssl/test/recipes/30-test_prov_config.t b/crypto/openssl/test/recipes/30-test_prov_config.t
index 7f6350fd84e1..1ef8736209c6 100644
--- a/crypto/openssl/test/recipes/30-test_prov_config.t
+++ b/crypto/openssl/test/recipes/30-test_prov_config.t
@@ -1,35 +1,37 @@
#! /usr/bin/env perl
-# Copyright 2021 The OpenSSL Project Authors. All Rights Reserved.
+# Copyright 2021-2024 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::Simple;
use OpenSSL::Test qw/:DEFAULT srctop_file srctop_dir bldtop_dir/;
use OpenSSL::Test::Utils;
BEGIN {
setup("test_prov_config");
}
use lib srctop_dir('Configurations');
use lib bldtop_dir('.');
my $no_fips = disabled('fips') || ($ENV{NO_FIPS} // 0);
plan tests => 2;
ok(run(test(["prov_config_test", srctop_file("test", "default.cnf"),
- srctop_file("test", "recursive.cnf")])),
+ srctop_file("test", "recursive.cnf"),
+ srctop_file("test", "pathed.cnf")])),
"running prov_config_test default.cnf");
SKIP: {
skip "Skipping FIPS test in this build", 1 if $no_fips;
ok(run(test(["prov_config_test", srctop_file("test", "fips.cnf"),
- srctop_file("test", "recursive.cnf")])),
+ srctop_file("test", "recursive.cnf"),
+ srctop_file("test", "pathed.cnf")])),
"running prov_config_test fips.cnf");
}
diff --git a/crypto/openssl/test/recipes/80-test_pkcs12.t b/crypto/openssl/test/recipes/80-test_pkcs12.t
index 4c5bb5744b8c..de26cbdca4dc 100644
--- a/crypto/openssl/test/recipes/80-test_pkcs12.t
+++ b/crypto/openssl/test/recipes/80-test_pkcs12.t
@@ -1,172 +1,184 @@
#! /usr/bin/env perl
# Copyright 2016-2024 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 OpenSSL::Test qw/:DEFAULT srctop_file with/;
use OpenSSL::Test::Utils;
use Encode;
setup("test_pkcs12");
my $pass = "σύνθημα γνώρισμα";
my $savedcp;
if (eval { require Win32::API; 1; }) {
# Trouble is that Win32 perl uses CreateProcessA, which
# makes it problematic to pass non-ASCII arguments, from perl[!]
# that is. This is because CreateProcessA is just a wrapper for
# CreateProcessW and will call MultiByteToWideChar and use
# system default locale. Since we attempt Greek pass-phrase
# conversion can be done only with Greek locale.
Win32::API->Import("kernel32","UINT GetSystemDefaultLCID()");
if (GetSystemDefaultLCID() != 0x408) {
plan skip_all => "Non-Greek system locale";
} else {
# Ensure correct code page so that VERBOSE output is right.
Win32::API->Import("kernel32","UINT GetConsoleOutputCP()");
Win32::API->Import("kernel32","BOOL SetConsoleOutputCP(UINT cp)");
$savedcp = GetConsoleOutputCP();
SetConsoleOutputCP(1253);
$pass = Encode::encode("cp1253",Encode::decode("utf-8",$pass));
}
} elsif ($^O eq "MSWin32") {
plan skip_all => "Win32::API unavailable";
} elsif ($^O ne "VMS") {
# Running MinGW tests transparently under Wine apparently requires
# UTF-8 locale...
foreach(`locale -a`) {
s/\R$//;
if ($_ =~ m/^C\.UTF\-?8/i) {
$ENV{LC_ALL} = $_;
last;
}
}
}
$ENV{OPENSSL_WIN32_UTF8}=1;
-plan tests => 17;
+plan tests => 20;
# Test different PKCS#12 formats
ok(run(test(["pkcs12_format_test"])), "test pkcs12 formats");
# Test with legacy APIs
ok(run(test(["pkcs12_format_test", "-legacy"])), "test pkcs12 formats using legacy APIs");
# Test with a non-default library context (and no loaded providers in the default context)
ok(run(test(["pkcs12_format_test", "-context"])), "test pkcs12 formats using a non-default library context");
SKIP: {
skip "VMS doesn't have command line UTF-8 support yet in DCL", 1
if $^O eq "VMS";
# just see that we can read shibboleth.pfx protected with $pass
ok(run(app(["openssl", "pkcs12", "-noout",
"-password", "pass:$pass",
"-in", srctop_file("test", "shibboleth.pfx")])),
"test_load_cert_pkcs12");
}
my @path = qw(test certs);
my $outfile1 = "out1.p12";
my $outfile2 = "out2.p12";
my $outfile3 = "out3.p12";
my $outfile4 = "out4.p12";
my $outfile5 = "out5.p12";
# Test the -chain option with -untrusted
ok(run(app(["openssl", "pkcs12", "-export", "-chain",
"-CAfile", srctop_file(@path, "sroot-cert.pem"),
"-untrusted", srctop_file(@path, "ca-cert.pem"),
"-in", srctop_file(@path, "ee-cert.pem"),
"-nokeys", "-passout", "pass:", "-out", $outfile1])),
"test_pkcs12_chain_untrusted");
# Test the -passcerts option
SKIP: {
skip "Skipping PKCS#12 test because DES is disabled in this build", 1
if disabled("des");
ok(run(app(["openssl", "pkcs12", "-export",
"-in", srctop_file(@path, "ee-cert.pem"),
"-certfile", srctop_file(@path, "v3-certs-TDES.p12"),
"-passcerts", "pass:v3-certs",
"-nokeys", "-passout", "pass:v3-certs", "-descert",
"-out", $outfile2])),
"test_pkcs12_passcerts");
}
SKIP: {
skip "Skipping legacy PKCS#12 test because the required algorithms are disabled", 1
if disabled("des") || disabled("rc2") || disabled("legacy");
# Test reading legacy PKCS#12 file
ok(run(app(["openssl", "pkcs12", "-export",
"-in", srctop_file(@path, "v3-certs-RC2.p12"),
"-passin", "pass:v3-certs",
"-provider", "default", "-provider", "legacy",
"-nokeys", "-passout", "pass:v3-certs", "-descert",
"-out", $outfile3])),
"test_pkcs12_passcerts_legacy");
}
# Test export of PEM file with both cert and key
# -nomac necessary to avoid legacy provider requirement
ok(run(app(["openssl", "pkcs12", "-export",
"-inkey", srctop_file(@path, "cert-key-cert.pem"),
"-in", srctop_file(@path, "cert-key-cert.pem"),
"-passout", "pass:v3-certs",
"-nomac", "-out", $outfile4], stderr => "outerr.txt")),
"test_export_pkcs12_cert_key_cert");
open DATA, "outerr.txt";
my @match = grep /:error:/, <DATA>;
close DATA;
ok(scalar @match > 0 ? 0 : 1, "test_export_pkcs12_outerr_empty");
ok(run(app(["openssl", "pkcs12",
"-in", $outfile4,
"-passin", "pass:v3-certs",
"-nomacver", "-nodes"])),
"test_import_pkcs12_cert_key_cert");
ok(run(app(["openssl", "pkcs12", "-export", "-out", $outfile5,
"-in", srctop_file(@path, "ee-cert.pem"), "-caname", "testname",
"-nokeys", "-passout", "pass:", "-certpbe", "NONE"])),
"test nokeys single cert");
my @pkcs12info = run(app(["openssl", "pkcs12", "-info", "-in", $outfile5,
"-passin", "pass:"]), capture => 1);
# Test that with one input certificate, we get one output certificate
ok(grep(/subject=CN = server.example/, @pkcs12info) == 1,
"test one cert in output");
# Test that the expected friendly name is present in the output
ok(grep(/testname/, @pkcs12info) == 1, "test friendly name in output");
# Test some bad pkcs12 files
my $bad1 = srctop_file("test", "recipes", "80-test_pkcs12_data", "bad1.p12");
my $bad2 = srctop_file("test", "recipes", "80-test_pkcs12_data", "bad2.p12");
my $bad3 = srctop_file("test", "recipes", "80-test_pkcs12_data", "bad3.p12");
with({ exit_checker => sub { return shift == 1; } },
sub {
ok(run(app(["openssl", "pkcs12", "-in", $bad1, "-password", "pass:"])),
"test bad pkcs12 file 1");
ok(run(app(["openssl", "pkcs12", "-in", $bad1, "-password", "pass:",
"-nomacver"])),
"test bad pkcs12 file 1 (nomacver)");
+ ok(run(app(["openssl", "pkcs12", "-in", $bad1, "-password", "pass:",
+ "-info"])),
+ "test bad pkcs12 file 1 (info)");
+
ok(run(app(["openssl", "pkcs12", "-in", $bad2, "-password", "pass:"])),
"test bad pkcs12 file 2");
+ ok(run(app(["openssl", "pkcs12", "-in", $bad2, "-password", "pass:",
+ "-info"])),
+ "test bad pkcs12 file 2 (info)");
+
ok(run(app(["openssl", "pkcs12", "-in", $bad3, "-password", "pass:"])),
"test bad pkcs12 file 3");
+
+ ok(run(app(["openssl", "pkcs12", "-in", $bad3, "-password", "pass:",
+ "-info"])),
+ "test bad pkcs12 file 3 (info)");
});
SetConsoleOutputCP($savedcp) if (defined($savedcp));
diff --git a/crypto/openssl/test/recipes/90-test_shlibload.t b/crypto/openssl/test/recipes/90-test_shlibload.t
index 8f691dee38e8..67afff607e04 100644
--- a/crypto/openssl/test/recipes/90-test_shlibload.t
+++ b/crypto/openssl/test/recipes/90-test_shlibload.t
@@ -1,74 +1,75 @@
#! /usr/bin/env perl
-# Copyright 2016-2021 The OpenSSL Project Authors. All Rights Reserved.
+# Copyright 2016-2024 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 qw/:DEFAULT srctop_dir bldtop_dir/;
use OpenSSL::Test::Utils;
#Load configdata.pm
BEGIN {
setup("test_shlibload");
}
use lib srctop_dir('Configurations');
use lib bldtop_dir('.');
use platform;
plan skip_all => "Test only supported in a shared build" if disabled("shared");
plan skip_all => "Test is disabled on AIX" if config('target') =~ m|^aix|;
plan skip_all => "Test is disabled on NonStop" if config('target') =~ m|^nonstop|;
plan skip_all => "Test only supported in a dso build" if disabled("dso");
plan skip_all => "Test is disabled in an address sanitizer build" unless disabled("asan");
+plan skip_all => "Test is disabled in no-atexit build" if disabled("atexit");
plan tests => 10;
my $libcrypto = platform->sharedlib('libcrypto');
my $libssl = platform->sharedlib('libssl');
my $atexit_outfile;
$atexit_outfile = 'atexit-cryptofirst.txt';
1 while unlink $atexit_outfile;
ok(run(test(["shlibloadtest", "-crypto_first", $libcrypto, $libssl, $atexit_outfile])),
"running shlibloadtest -crypto_first $atexit_outfile");
ok(check_atexit($atexit_outfile));
$atexit_outfile = 'atexit-sslfirst.txt';
1 while unlink $atexit_outfile;
ok(run(test(["shlibloadtest", "-ssl_first", $libcrypto, $libssl, $atexit_outfile])),
"running shlibloadtest -ssl_first $atexit_outfile");
ok(check_atexit($atexit_outfile));
$atexit_outfile = 'atexit-justcrypto.txt';
1 while unlink $atexit_outfile;
ok(run(test(["shlibloadtest", "-just_crypto", $libcrypto, $libssl, $atexit_outfile])),
"running shlibloadtest -just_crypto $atexit_outfile");
ok(check_atexit($atexit_outfile));
$atexit_outfile = 'atexit-dsoref.txt';
1 while unlink $atexit_outfile;
ok(run(test(["shlibloadtest", "-dso_ref", $libcrypto, $libssl, $atexit_outfile])),
"running shlibloadtest -dso_ref $atexit_outfile");
ok(check_atexit($atexit_outfile));
$atexit_outfile = 'atexit-noatexit.txt';
1 while unlink $atexit_outfile;
ok(run(test(["shlibloadtest", "-no_atexit", $libcrypto, $libssl, $atexit_outfile])),
"running shlibloadtest -no_atexit $atexit_outfile");
ok(!check_atexit($atexit_outfile));
sub check_atexit {
my $filename = shift;
open my $fh, '<', $filename;
return 0 unless defined $fh;
my $data = <$fh>;
return 1 if (defined $data && $data =~ m/atexit\(\) run/);
return 0;
}
diff --git a/crypto/openssl/test/sm2_internal_test.c b/crypto/openssl/test/sm2_internal_test.c
index 4899d5e21313..bd0bf0efa74d 100644
--- a/crypto/openssl/test/sm2_internal_test.c
+++ b/crypto/openssl/test/sm2_internal_test.c
@@ -1,428 +1,449 @@
/*
- * Copyright 2017-2021 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2017-2024 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
*/
/*
* Low level APIs are deprecated for public use, but still ok for internal use.
*/
#include "internal/deprecated.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/bio.h>
#include <openssl/evp.h>
#include <openssl/bn.h>
#include <openssl/crypto.h>
#include <openssl/err.h>
#include <openssl/rand.h>
#include "testutil.h"
#ifndef OPENSSL_NO_SM2
# include "crypto/sm2.h"
static fake_random_generate_cb get_faked_bytes;
static OSSL_PROVIDER *fake_rand = NULL;
static uint8_t *fake_rand_bytes = NULL;
static size_t fake_rand_bytes_offset = 0;
static size_t fake_rand_size = 0;
static int get_faked_bytes(unsigned char *buf, size_t num,
ossl_unused const char *name,
ossl_unused EVP_RAND_CTX *ctx)
{
if (!TEST_ptr(fake_rand_bytes) || !TEST_size_t_gt(fake_rand_size, 0))
return 0;
while (num-- > 0) {
if (fake_rand_bytes_offset >= fake_rand_size)
fake_rand_bytes_offset = 0;
*buf++ = fake_rand_bytes[fake_rand_bytes_offset++];
}
return 1;
}
static int start_fake_rand(const char *hex_bytes)
{
OPENSSL_free(fake_rand_bytes);
fake_rand_bytes_offset = 0;
fake_rand_size = strlen(hex_bytes) / 2;
if (!TEST_ptr(fake_rand_bytes = OPENSSL_hexstr2buf(hex_bytes, NULL)))
return 0;
/* use own random function */
fake_rand_set_public_private_callbacks(NULL, get_faked_bytes);
return 1;
}
static void restore_rand(void)
{
fake_rand_set_public_private_callbacks(NULL, NULL);
OPENSSL_free(fake_rand_bytes);
fake_rand_bytes = NULL;
fake_rand_bytes_offset = 0;
}
static EC_GROUP *create_EC_group(const char *p_hex, const char *a_hex,
const char *b_hex, const char *x_hex,
const char *y_hex, const char *order_hex,
const char *cof_hex)
{
BIGNUM *p = NULL;
BIGNUM *a = NULL;
BIGNUM *b = NULL;
BIGNUM *g_x = NULL;
BIGNUM *g_y = NULL;
BIGNUM *order = NULL;
BIGNUM *cof = NULL;
EC_POINT *generator = NULL;
EC_GROUP *group = NULL;
int ok = 0;
if (!TEST_true(BN_hex2bn(&p, p_hex))
|| !TEST_true(BN_hex2bn(&a, a_hex))
|| !TEST_true(BN_hex2bn(&b, b_hex)))
goto done;
group = EC_GROUP_new_curve_GFp(p, a, b, NULL);
if (!TEST_ptr(group))
goto done;
generator = EC_POINT_new(group);
if (!TEST_ptr(generator))
goto done;
if (!TEST_true(BN_hex2bn(&g_x, x_hex))
|| !TEST_true(BN_hex2bn(&g_y, y_hex))
|| !TEST_true(EC_POINT_set_affine_coordinates(group, generator, g_x,
g_y, NULL)))
goto done;
if (!TEST_true(BN_hex2bn(&order, order_hex))
|| !TEST_true(BN_hex2bn(&cof, cof_hex))
|| !TEST_true(EC_GROUP_set_generator(group, generator, order, cof)))
goto done;
ok = 1;
done:
BN_free(p);
BN_free(a);
BN_free(b);
BN_free(g_x);
BN_free(g_y);
EC_POINT_free(generator);
BN_free(order);
BN_free(cof);
if (!ok) {
EC_GROUP_free(group);
group = NULL;
}
return group;
}
static int test_sm2_crypt(const EC_GROUP *group,
const EVP_MD *digest,
const char *privkey_hex,
const char *message,
const char *k_hex, const char *ctext_hex)
{
const size_t msg_len = strlen(message);
BIGNUM *priv = NULL;
EC_KEY *key = NULL;
EC_POINT *pt = NULL;
unsigned char *expected = OPENSSL_hexstr2buf(ctext_hex, NULL);
size_t ctext_len = 0;
size_t ptext_len = 0;
uint8_t *ctext = NULL;
uint8_t *recovered = NULL;
size_t recovered_len = msg_len;
int rc = 0;
if (!TEST_ptr(expected)
|| !TEST_true(BN_hex2bn(&priv, privkey_hex)))
goto done;
key = EC_KEY_new();
if (!TEST_ptr(key)
|| !TEST_true(EC_KEY_set_group(key, group))
|| !TEST_true(EC_KEY_set_private_key(key, priv)))
goto done;
pt = EC_POINT_new(group);
if (!TEST_ptr(pt)
|| !TEST_true(EC_POINT_mul(group, pt, priv, NULL, NULL, NULL))
|| !TEST_true(EC_KEY_set_public_key(key, pt))
|| !TEST_true(ossl_sm2_ciphertext_size(key, digest, msg_len,
&ctext_len)))
goto done;
ctext = OPENSSL_zalloc(ctext_len);
if (!TEST_ptr(ctext))
goto done;
start_fake_rand(k_hex);
if (!TEST_true(ossl_sm2_encrypt(key, digest,
(const uint8_t *)message, msg_len,
ctext, &ctext_len))) {
restore_rand();
goto done;
}
restore_rand();
if (!TEST_mem_eq(ctext, ctext_len, expected, ctext_len))
goto done;
if (!TEST_true(ossl_sm2_plaintext_size(ctext, ctext_len, &ptext_len))
|| !TEST_int_eq(ptext_len, msg_len))
goto done;
recovered = OPENSSL_zalloc(ptext_len);
if (!TEST_ptr(recovered)
|| !TEST_true(ossl_sm2_decrypt(key, digest, ctext, ctext_len,
recovered, &recovered_len))
|| !TEST_int_eq(recovered_len, msg_len)
|| !TEST_mem_eq(recovered, recovered_len, message, msg_len))
goto done;
rc = 1;
done:
BN_free(priv);
EC_POINT_free(pt);
OPENSSL_free(ctext);
OPENSSL_free(recovered);
OPENSSL_free(expected);
EC_KEY_free(key);
return rc;
}
static int sm2_crypt_test(void)
{
int testresult = 0;
EC_GROUP *gm_group = NULL;
EC_GROUP *test_group =
create_EC_group
("8542D69E4C044F18E8B92435BF6FF7DE457283915C45517D722EDB8B08F1DFC3",
"787968B4FA32C3FD2417842E73BBFEFF2F3C848B6831D7E0EC65228B3937E498",
"63E4C6D3B23B0C849CF84241484BFE48F61D59A5B16BA06E6E12D1DA27C5249A",
"421DEBD61B62EAB6746434EBC3CC315E32220B3BADD50BDC4C4E6C147FEDD43D",
"0680512BCBB42C07D47349D2153B70C4E5D7FDFCBFA36EA1A85841B9E46E09A2",
"8542D69E4C044F18E8B92435BF6FF7DD297720630485628D5AE74EE7C32E79B7",
"1");
if (!TEST_ptr(test_group))
goto done;
if (!test_sm2_crypt(
test_group,
EVP_sm3(),
"1649AB77A00637BD5E2EFE283FBF353534AA7F7CB89463F208DDBC2920BB0DA0",
"encryption standard",
"004C62EEFD6ECFC2B95B92FD6C3D9575148AFA17425546D49018E5388D49DD7B4F"
"0092e8ff62146873c258557548500ab2df2a365e0609ab67640a1f6d57d7b17820"
"008349312695a3e1d2f46905f39a766487f2432e95d6be0cb009fe8c69fd8825a7",
"307B0220245C26FB68B1DDDDB12C4B6BF9F2B6D5FE60A383B0D18D1C4144ABF1"
"7F6252E7022076CB9264C2A7E88E52B19903FDC47378F605E36811F5C07423A2"
"4B84400F01B804209C3D7360C30156FAB7C80A0276712DA9D8094A634B766D3A"
"285E07480653426D0413650053A89B41C418B0C3AAD00D886C00286467"))
goto done;
/* Same test as above except using SHA-256 instead of SM3 */
if (!test_sm2_crypt(
test_group,
EVP_sha256(),
"1649AB77A00637BD5E2EFE283FBF353534AA7F7CB89463F208DDBC2920BB0DA0",
"encryption standard",
"004C62EEFD6ECFC2B95B92FD6C3D9575148AFA17425546D49018E5388D49DD7B4F"
"003da18008784352192d70f22c26c243174a447ba272fec64163dd4742bae8bc98"
"00df17605cf304e9dd1dfeb90c015e93b393a6f046792f790a6fa4228af67d9588",
"307B0220245C26FB68B1DDDDB12C4B6BF9F2B6D5FE60A383B0D18D1C4144ABF17F"
"6252E7022076CB9264C2A7E88E52B19903FDC47378F605E36811F5C07423A24B84"
"400F01B80420BE89139D07853100EFA763F60CBE30099EA3DF7F8F364F9D10A5E9"
"88E3C5AAFC0413229E6C9AEE2BB92CAD649FE2C035689785DA33"))
goto done;
/* From Annex C in both GM/T0003.5-2012 and GB/T 32918.5-2016.*/
gm_group = create_EC_group(
"fffffffeffffffffffffffffffffffffffffffff00000000ffffffffffffffff",
"fffffffeffffffffffffffffffffffffffffffff00000000fffffffffffffffc",
"28e9fa9e9d9f5e344d5a9e4bcf6509a7f39789f515ab8f92ddbcbd414d940e93",
"32c4ae2c1f1981195f9904466a39c9948fe30bbff2660be1715a4589334c74c7",
"bc3736a2f4f6779c59bdcee36b692153d0a9877cc62a474002df32e52139f0a0",
"fffffffeffffffffffffffffffffffff7203df6b21c6052b53bbf40939d54123",
"1");
if (!TEST_ptr(gm_group))
goto done;
if (!test_sm2_crypt(
gm_group,
EVP_sm3(),
/* privkey (from which the encrypting public key is derived) */
"3945208F7B2144B13F36E38AC6D39F95889393692860B51A42FB81EF4DF7C5B8",
/* plaintext message */
"encryption standard",
/* ephemeral nonce k */
"59276E27D506861A16680F3AD9C02DCCEF3CC1FA3CDBE4CE6D54B80DEAC1BC21",
/*
* expected ciphertext, the field values are from GM/T 0003.5-2012
* (Annex C), but serialized following the ASN.1 format specified
* in GM/T 0009-2012 (Sec. 7.2).
*/
"307C" /* SEQUENCE, 0x7c bytes */
"0220" /* INTEGER, 0x20 bytes */
"04EBFC718E8D1798620432268E77FEB6415E2EDE0E073C0F4F640ECD2E149A73"
"0221" /* INTEGER, 0x21 bytes */
"00" /* leading 00 due to DER for pos. int with topmost bit set */
"E858F9D81E5430A57B36DAAB8F950A3C64E6EE6A63094D99283AFF767E124DF0"
"0420" /* OCTET STRING, 0x20 bytes */
"59983C18F809E262923C53AEC295D30383B54E39D609D160AFCB1908D0BD8766"
"0413" /* OCTET STRING, 0x13 bytes */
"21886CA989CA9C7D58087307CA93092D651EFA"))
goto done;
testresult = 1;
done:
EC_GROUP_free(test_group);
EC_GROUP_free(gm_group);
return testresult;
}
static int test_sm2_sign(const EC_GROUP *group,
const char *userid,
const char *privkey_hex,
const char *message,
const char *k_hex,
const char *r_hex,
- const char *s_hex)
+ const char *s_hex,
+ int omit_pubkey)
{
const size_t msg_len = strlen(message);
int ok = 0;
BIGNUM *priv = NULL;
EC_POINT *pt = NULL;
EC_KEY *key = NULL;
ECDSA_SIG *sig = NULL;
const BIGNUM *sig_r = NULL;
const BIGNUM *sig_s = NULL;
BIGNUM *r = NULL;
BIGNUM *s = NULL;
if (!TEST_true(BN_hex2bn(&priv, privkey_hex)))
goto done;
key = EC_KEY_new();
if (!TEST_ptr(key)
|| !TEST_true(EC_KEY_set_group(key, group))
|| !TEST_true(EC_KEY_set_private_key(key, priv)))
goto done;
- pt = EC_POINT_new(group);
- if (!TEST_ptr(pt)
- || !TEST_true(EC_POINT_mul(group, pt, priv, NULL, NULL, NULL))
- || !TEST_true(EC_KEY_set_public_key(key, pt)))
- goto done;
+ if (omit_pubkey == 0) {
+ pt = EC_POINT_new(group);
+ if (!TEST_ptr(pt)
+ || !TEST_true(EC_POINT_mul(group, pt, priv, NULL, NULL, NULL))
+ || !TEST_true(EC_KEY_set_public_key(key, pt)))
+ goto done;
+ }
start_fake_rand(k_hex);
sig = ossl_sm2_do_sign(key, EVP_sm3(), (const uint8_t *)userid,
strlen(userid), (const uint8_t *)message, msg_len);
if (!TEST_ptr(sig)) {
restore_rand();
goto done;
}
restore_rand();
ECDSA_SIG_get0(sig, &sig_r, &sig_s);
if (!TEST_true(BN_hex2bn(&r, r_hex))
|| !TEST_true(BN_hex2bn(&s, s_hex))
|| !TEST_BN_eq(r, sig_r)
|| !TEST_BN_eq(s, sig_s))
goto done;
ok = ossl_sm2_do_verify(key, EVP_sm3(), sig, (const uint8_t *)userid,
strlen(userid), (const uint8_t *)message, msg_len);
/* We goto done whether this passes or fails */
TEST_true(ok);
done:
ECDSA_SIG_free(sig);
EC_POINT_free(pt);
EC_KEY_free(key);
BN_free(priv);
BN_free(r);
BN_free(s);
return ok;
}
static int sm2_sig_test(void)
{
int testresult = 0;
/* From draft-shen-sm2-ecdsa-02 */
EC_GROUP *test_group =
create_EC_group
("8542D69E4C044F18E8B92435BF6FF7DE457283915C45517D722EDB8B08F1DFC3",
"787968B4FA32C3FD2417842E73BBFEFF2F3C848B6831D7E0EC65228B3937E498",
"63E4C6D3B23B0C849CF84241484BFE48F61D59A5B16BA06E6E12D1DA27C5249A",
"421DEBD61B62EAB6746434EBC3CC315E32220B3BADD50BDC4C4E6C147FEDD43D",
"0680512BCBB42C07D47349D2153B70C4E5D7FDFCBFA36EA1A85841B9E46E09A2",
"8542D69E4C044F18E8B92435BF6FF7DD297720630485628D5AE74EE7C32E79B7",
"1");
if (!TEST_ptr(test_group))
goto done;
if (!TEST_true(test_sm2_sign(
test_group,
"ALICE123@YAHOO.COM",
"128B2FA8BD433C6C068C8D803DFF79792A519A55171B1B650C23661D15897263",
"message digest",
"006CB28D99385C175C94F94E934817663FC176D925DD72B727260DBAAE1FB2F96F"
"007c47811054c6f99613a578eb8453706ccb96384fe7df5c171671e760bfa8be3a",
"40F1EC59F793D9F49E09DCEF49130D4194F79FB1EED2CAA55BACDB49C4E755D1",
- "6FC6DAC32C5D5CF10C77DFB20F7C2EB667A457872FB09EC56327A67EC7DEEBE7")))
+ "6FC6DAC32C5D5CF10C77DFB20F7C2EB667A457872FB09EC56327A67EC7DEEBE7", 0)))
+ goto done;
+
+ /* Make sure we fail if we omit the public portion of the key */
+ if (!TEST_false(test_sm2_sign(
+ test_group,
+ /* the default ID specified in GM/T 0009-2012 (Sec. 10).*/
+ SM2_DEFAULT_USERID,
+ /* privkey */
+ "3945208F7B2144B13F36E38AC6D39F95889393692860B51A42FB81EF4DF7C5B8",
+ /* plaintext message */
+ "message digest",
+ /* ephemeral nonce k */
+ "59276E27D506861A16680F3AD9C02DCCEF3CC1FA3CDBE4CE6D54B80DEAC1BC21",
+ /* expected signature, */
+ /* signature R, 0x20 bytes */
+ "F5A03B0648D2C4630EEAC513E1BB81A15944DA3827D5B74143AC7EACEEE720B3",
+ /* signature S, 0x20 bytes */
+ "B1B6AA29DF212FD8763182BC0D421CA1BB9038FD1F7F42D4840B69C485BBC1AA", 1)))
goto done;
testresult = 1;
done:
EC_GROUP_free(test_group);
return testresult;
}
#endif
int setup_tests(void)
{
#ifdef OPENSSL_NO_SM2
TEST_note("SM2 is disabled.");
#else
fake_rand = fake_rand_start(NULL);
if (fake_rand == NULL)
return 0;
ADD_TEST(sm2_crypt_test);
ADD_TEST(sm2_sig_test);
#endif
return 1;
}
void cleanup_tests(void)
{
#ifndef OPENSSL_NO_SM2
fake_rand_finish(fake_rand);
#endif
}
diff --git a/crypto/openssl/test/ssl-tests/14-curves.cnf.in b/crypto/openssl/test/ssl-tests/14-curves.cnf.in
index 1e003bace0b7..33201df281f7 100644
--- a/crypto/openssl/test/ssl-tests/14-curves.cnf.in
+++ b/crypto/openssl/test/ssl-tests/14-curves.cnf.in
@@ -1,177 +1,180 @@
# -*- mode: perl; -*-
## SSL test configurations
package ssltests;
use strict;
use warnings;
use OpenSSL::Test;
use OpenSSL::Test::Utils qw(anydisabled);
our $fips_mode;
-my @curves = ("prime256v1", "secp384r1", "secp521r1", "X25519",
- "X448");
+my @curves = ("prime256v1", "secp384r1", "secp521r1");
+
+my @curves_no_fips = ("X25519", "X448");
+
+push @curves, @curves_no_fips if !$fips_mode;
#Curves *only* suitable for use in TLSv1.3
my @curves_tls_1_3 = ("ffdhe2048", "ffdhe3072", "ffdhe4096", "ffdhe6144",
"ffdhe8192");
push @curves, @curves_tls_1_3;
my @curves_tls_1_2 = ("sect233k1", "sect233r1",
"sect283k1", "sect283r1", "sect409k1", "sect409r1",
"sect571k1", "sect571r1", "secp224r1");
my @curves_non_fips = ("sect163k1", "sect163r2", "prime192v1",
"sect163r1", "sect193r1", "sect193r2", "sect239k1",
"secp160k1", "secp160r1", "secp160r2", "secp192k1",
"secp224k1", "secp256k1", "brainpoolP256r1",
"brainpoolP384r1", "brainpoolP512r1");
push @curves_tls_1_2, @curves_non_fips if !$fips_mode;
our @tests = ();
sub get_key_type {
my $group = shift;
my $keyType;
if ($group =~ /ffdhe/) {
$keyType = "dhKeyAgreement";
} else {
$keyType = $group;
}
return $keyType;
}
sub generate_tests() {
foreach (0..$#curves) {
my $curve = $curves[$_];
push @tests, {
name => "curve-${curve}",
server => {
"Curves" => $curve,
"MaxProtocol" => "TLSv1.3"
},
client => {
"CipherString" => "ECDHE",
"MaxProtocol" => "TLSv1.3",
"Curves" => $curve
},
test => {
"ExpectedTmpKeyType" => get_key_type($curve),
"ExpectedProtocol" => "TLSv1.3",
"ExpectedResult" => "Success"
},
};
}
foreach (0..$#curves_tls_1_2) {
my $curve = $curves_tls_1_2[$_];
push @tests, {
name => "curve-${curve}",
server => {
"Curves" => $curve,
"MaxProtocol" => "TLSv1.3"
},
client => {
"CipherString" => "ECDHE",
"MaxProtocol" => "TLSv1.2",
"Curves" => $curve
},
test => {
"ExpectedTmpKeyType" => get_key_type($curve),
"ExpectedProtocol" => "TLSv1.2",
"ExpectedResult" => "Success"
},
};
}
foreach (0..$#curves_tls_1_2) {
my $curve = $curves_tls_1_2[$_];
push @tests, {
name => "curve-${curve}-tls12-in-tls13",
server => {
"Curves" => "$curve:P-256",
"CipherString" => 'DEFAULT@SECLEVEL=1',
"MaxProtocol" => "TLSv1.3"
},
client => {
"CipherString" => 'ECDHE@SECLEVEL=1',
"MaxProtocol" => "TLSv1.3",
"MinProtocol" => "TLSv1.3",
"Curves" => "$curve:P-256"
},
test => {
#This curve is not allowed in a TLSv1.3 key_share. We should
#succeed but fallback to P-256
"ExpectedTmpKeyType" => "P-256",
"ExpectedProtocol" => "TLSv1.3",
"ExpectedResult" => "Success"
},
};
}
foreach (0..$#curves_tls_1_2) {
my $curve = $curves_tls_1_2[$_];
push @tests, {
name => "curve-${curve}-tls13",
server => {
"Curves" => $curve,
"MaxProtocol" => "TLSv1.3"
},
client => {
"CipherString" => "ECDHE",
"MinProtocol" => "TLSv1.3",
"Curves" => $curve
},
test => {
"ExpectedResult" => "ClientFail"
},
};
}
foreach (0..$#curves_tls_1_3) {
my $curve = $curves_tls_1_3[$_];
push @tests, {
name => "curve-${curve}-tls13-in-tls12",
server => {
"Curves" => $curve,
"CipherString" => 'DEFAULT@SECLEVEL=1',
"MaxProtocol" => "TLSv1.3"
},
client => {
"CipherString" => 'ECDHE@SECLEVEL=1',
"MaxProtocol" => "TLSv1.2",
"Curves" => $curve
},
test => {
#These curves are only suitable for TLSv1.3 so we expect the
#server to fail because it has no shared groups for TLSv1.2
#ECDHE key exchange
"ExpectedResult" => "ServerFail"
},
};
push @tests, {
name => "curve-${curve}-tls13-in-tls12-2",
server => {
"Curves" => $curve,
"CipherString" => 'DEFAULT@SECLEVEL=1',
"MaxProtocol" => "TLSv1.2"
},
client => {
"CipherString" => 'DEFAULT@SECLEVEL=1',
"MaxProtocol" => "TLSv1.3",
"Curves" => $curve
},
test => {
#These curves are only suitable for TLSv1.3. We expect TLSv1.2
#negotiation to succeed because we fall back to some other
#ciphersuite
"ExpectedResult" => "Success"
},
};
}
}
generate_tests();
diff --git a/crypto/openssl/test/ssl-tests/20-cert-select.cnf b/crypto/openssl/test/ssl-tests/20-cert-select.cnf
index 79dcd4c8f4e2..6888d538ba35 100644
--- a/crypto/openssl/test/ssl-tests/20-cert-select.cnf
+++ b/crypto/openssl/test/ssl-tests/20-cert-select.cnf
@@ -1,1842 +1,1842 @@
# Generated with generate_ssl_tests.pl
num_tests = 57
test-0 = 0-ECDSA CipherString Selection
test-1 = 1-ECDSA CipherString Selection
test-2 = 2-ECDSA CipherString Selection
test-3 = 3-RSA CipherString Selection
test-4 = 4-P-256 CipherString and Signature Algorithm Selection
test-5 = 5-ECDSA CipherString Selection, no ECDSA certificate
test-6 = 6-ECDSA Signature Algorithm Selection
test-7 = 7-ECDSA Signature Algorithm Selection SHA384
test-8 = 8-ECDSA Signature Algorithm Selection compressed point
test-9 = 9-ECDSA Signature Algorithm Selection, no ECDSA certificate
test-10 = 10-RSA Signature Algorithm Selection
test-11 = 11-RSA-PSS Signature Algorithm Selection
test-12 = 12-RSA key exchange with all RSA certificate types
test-13 = 13-Suite B P-256 Hash Algorithm Selection
test-14 = 14-Suite B P-384 Hash Algorithm Selection
test-15 = 15-Ed25519 CipherString and Signature Algorithm Selection
test-16 = 16-Ed448 CipherString and Signature Algorithm Selection
-test-17 = 17-Ed25519 CipherString and Curves Selection
-test-18 = 18-Ed448 CipherString and Curves Selection
-test-19 = 19-TLS 1.2 Ed25519 Client Auth
-test-20 = 20-TLS 1.2 Ed448 Client Auth
-test-21 = 21-ECDSA Signature Algorithm Selection SHA1
-test-22 = 22-ECDSA with brainpool
+test-17 = 17-TLS 1.2 Ed25519 Client Auth
+test-18 = 18-TLS 1.2 Ed448 Client Auth
+test-19 = 19-ECDSA Signature Algorithm Selection SHA1
+test-20 = 20-ECDSA with brainpool
+test-21 = 21-Ed25519 CipherString and Curves Selection
+test-22 = 22-Ed448 CipherString and Curves Selection
test-23 = 23-RSA-PSS Certificate CipherString Selection
test-24 = 24-RSA-PSS Certificate Legacy Signature Algorithm Selection
test-25 = 25-RSA-PSS Certificate Unified Signature Algorithm Selection
test-26 = 26-Only RSA-PSS Certificate
test-27 = 27-Only RSA-PSS Certificate Valid Signature Algorithms
test-28 = 28-RSA-PSS Certificate, no PSS signature algorithms
test-29 = 29-Only RSA-PSS Restricted Certificate
test-30 = 30-RSA-PSS Restricted Certificate Valid Signature Algorithms
test-31 = 31-RSA-PSS Restricted Cert client prefers invalid Signature Algorithm
test-32 = 32-RSA-PSS Restricted Certificate Invalid Signature Algorithms
test-33 = 33-RSA key exchange with only RSA-PSS certificate
test-34 = 34-Only RSA-PSS Certificate, TLS v1.1
test-35 = 35-TLS 1.3 ECDSA Signature Algorithm Selection
test-36 = 36-TLS 1.3 ECDSA Signature Algorithm Selection compressed point
test-37 = 37-TLS 1.3 ECDSA Signature Algorithm Selection SHA1
test-38 = 38-TLS 1.3 ECDSA Signature Algorithm Selection with PSS
test-39 = 39-TLS 1.3 RSA Signature Algorithm Selection SHA384 with PSS
test-40 = 40-TLS 1.3 ECDSA Signature Algorithm Selection, no ECDSA certificate
test-41 = 41-TLS 1.3 RSA Signature Algorithm Selection, no PSS
test-42 = 42-TLS 1.3 RSA-PSS Signature Algorithm Selection
test-43 = 43-TLS 1.3 RSA Client Auth Signature Algorithm Selection
test-44 = 44-TLS 1.3 RSA Client Auth Signature Algorithm Selection non-empty CA Names
test-45 = 45-TLS 1.3 ECDSA Client Auth Signature Algorithm Selection
test-46 = 46-TLS 1.3 Ed25519 Signature Algorithm Selection
test-47 = 47-TLS 1.3 Ed448 Signature Algorithm Selection
test-48 = 48-TLS 1.3 Ed25519 CipherString and Groups Selection
test-49 = 49-TLS 1.3 Ed448 CipherString and Groups Selection
test-50 = 50-TLS 1.3 Ed25519 Client Auth
test-51 = 51-TLS 1.3 Ed448 Client Auth
test-52 = 52-TLS 1.3 ECDSA with brainpool but no suitable groups
test-53 = 53-TLS 1.3 ECDSA with brainpool
test-54 = 54-TLS 1.2 DSA Certificate Test
test-55 = 55-TLS 1.3 Client Auth No TLS 1.3 Signature Algorithms
test-56 = 56-TLS 1.3 DSA Certificate Test
# ===========================================================
[0-ECDSA CipherString Selection]
ssl_conf = 0-ECDSA CipherString Selection-ssl
[0-ECDSA CipherString Selection-ssl]
server = 0-ECDSA CipherString Selection-server
client = 0-ECDSA CipherString Selection-client
[0-ECDSA CipherString Selection-server]
Certificate = ${ENV::TEST_CERTS_DIR}/servercert.pem
CipherString = DEFAULT
ECDSA.Certificate = ${ENV::TEST_CERTS_DIR}/server-ecdsa-cert.pem
ECDSA.PrivateKey = ${ENV::TEST_CERTS_DIR}/server-ecdsa-key.pem
Ed25519.Certificate = ${ENV::TEST_CERTS_DIR}/server-ed25519-cert.pem
Ed25519.PrivateKey = ${ENV::TEST_CERTS_DIR}/server-ed25519-key.pem
Ed448.Certificate = ${ENV::TEST_CERTS_DIR}/server-ed448-cert.pem
Ed448.PrivateKey = ${ENV::TEST_CERTS_DIR}/server-ed448-key.pem
MaxProtocol = TLSv1.2
PrivateKey = ${ENV::TEST_CERTS_DIR}/serverkey.pem
[0-ECDSA CipherString Selection-client]
CipherString = aECDSA
MaxProtocol = TLSv1.2
RequestCAFile = ${ENV::TEST_CERTS_DIR}/root-cert.pem
VerifyCAFile = ${ENV::TEST_CERTS_DIR}/rootcert.pem
VerifyMode = Peer
[test-0]
ExpectedResult = Success
ExpectedServerCANames = empty
ExpectedServerCertType = P-256
ExpectedServerSignType = EC
# ===========================================================
[1-ECDSA CipherString Selection]
ssl_conf = 1-ECDSA CipherString Selection-ssl
[1-ECDSA CipherString Selection-ssl]
server = 1-ECDSA CipherString Selection-server
client = 1-ECDSA CipherString Selection-client
[1-ECDSA CipherString Selection-server]
Certificate = ${ENV::TEST_CERTS_DIR}/servercert.pem
CipherString = DEFAULT
ECDSA.Certificate = ${ENV::TEST_CERTS_DIR}/server-ecdsa-cert.pem
ECDSA.PrivateKey = ${ENV::TEST_CERTS_DIR}/server-ecdsa-key.pem
Groups = P-384
MaxProtocol = TLSv1.2
PrivateKey = ${ENV::TEST_CERTS_DIR}/serverkey.pem
[1-ECDSA CipherString Selection-client]
CipherString = aECDSA
Groups = P-256:P-384
MaxProtocol = TLSv1.2
RequestCAFile = ${ENV::TEST_CERTS_DIR}/root-cert.pem
VerifyCAFile = ${ENV::TEST_CERTS_DIR}/rootcert.pem
VerifyMode = Peer
[test-1]
ExpectedResult = Success
ExpectedServerCANames = empty
ExpectedServerCertType = P-256
ExpectedServerSignType = EC
# ===========================================================
[2-ECDSA CipherString Selection]
ssl_conf = 2-ECDSA CipherString Selection-ssl
[2-ECDSA CipherString Selection-ssl]
server = 2-ECDSA CipherString Selection-server
client = 2-ECDSA CipherString Selection-client
[2-ECDSA CipherString Selection-server]
Certificate = ${ENV::TEST_CERTS_DIR}/servercert.pem
CipherString = DEFAULT
ECDSA.Certificate = ${ENV::TEST_CERTS_DIR}/server-ecdsa-cert.pem
ECDSA.PrivateKey = ${ENV::TEST_CERTS_DIR}/server-ecdsa-key.pem
Groups = P-256:P-384
MaxProtocol = TLSv1.2
PrivateKey = ${ENV::TEST_CERTS_DIR}/serverkey.pem
[2-ECDSA CipherString Selection-client]
CipherString = aECDSA
Groups = P-384
MaxProtocol = TLSv1.2
RequestCAFile = ${ENV::TEST_CERTS_DIR}/root-cert.pem
VerifyCAFile = ${ENV::TEST_CERTS_DIR}/rootcert.pem
VerifyMode = Peer
[test-2]
ExpectedResult = ServerFail
# ===========================================================
[3-RSA CipherString Selection]
ssl_conf = 3-RSA CipherString Selection-ssl
[3-RSA CipherString Selection-ssl]
server = 3-RSA CipherString Selection-server
client = 3-RSA CipherString Selection-client
[3-RSA CipherString Selection-server]
Certificate = ${ENV::TEST_CERTS_DIR}/servercert.pem
CipherString = DEFAULT
ECDSA.Certificate = ${ENV::TEST_CERTS_DIR}/server-ecdsa-cert.pem
ECDSA.PrivateKey = ${ENV::TEST_CERTS_DIR}/server-ecdsa-key.pem
Ed25519.Certificate = ${ENV::TEST_CERTS_DIR}/server-ed25519-cert.pem
Ed25519.PrivateKey = ${ENV::TEST_CERTS_DIR}/server-ed25519-key.pem
Ed448.Certificate = ${ENV::TEST_CERTS_DIR}/server-ed448-cert.pem
Ed448.PrivateKey = ${ENV::TEST_CERTS_DIR}/server-ed448-key.pem
MaxProtocol = TLSv1.2
PrivateKey = ${ENV::TEST_CERTS_DIR}/serverkey.pem
[3-RSA CipherString Selection-client]
CipherString = aRSA
MaxProtocol = TLSv1.2
VerifyCAFile = ${ENV::TEST_CERTS_DIR}/rootcert.pem
VerifyMode = Peer
[test-3]
ExpectedResult = Success
ExpectedServerCertType = RSA
ExpectedServerSignType = RSA-PSS
# ===========================================================
[4-P-256 CipherString and Signature Algorithm Selection]
ssl_conf = 4-P-256 CipherString and Signature Algorithm Selection-ssl
[4-P-256 CipherString and Signature Algorithm Selection-ssl]
server = 4-P-256 CipherString and Signature Algorithm Selection-server
client = 4-P-256 CipherString and Signature Algorithm Selection-client
[4-P-256 CipherString and Signature Algorithm Selection-server]
Certificate = ${ENV::TEST_CERTS_DIR}/servercert.pem
CipherString = DEFAULT
ECDSA.Certificate = ${ENV::TEST_CERTS_DIR}/server-ecdsa-cert.pem
ECDSA.PrivateKey = ${ENV::TEST_CERTS_DIR}/server-ecdsa-key.pem
Ed25519.Certificate = ${ENV::TEST_CERTS_DIR}/server-ed25519-cert.pem
Ed25519.PrivateKey = ${ENV::TEST_CERTS_DIR}/server-ed25519-key.pem
Ed448.Certificate = ${ENV::TEST_CERTS_DIR}/server-ed448-cert.pem
Ed448.PrivateKey = ${ENV::TEST_CERTS_DIR}/server-ed448-key.pem
MaxProtocol = TLSv1.2
PrivateKey = ${ENV::TEST_CERTS_DIR}/serverkey.pem
[4-P-256 CipherString and Signature Algorithm Selection-client]
CipherString = aECDSA
MaxProtocol = TLSv1.2
SignatureAlgorithms = ECDSA+SHA256:ed25519
VerifyCAFile = ${ENV::TEST_CERTS_DIR}/rootcert.pem
VerifyMode = Peer
[test-4]
ExpectedResult = Success
ExpectedServerCertType = P-256
ExpectedServerSignHash = SHA256
ExpectedServerSignType = EC
# ===========================================================
[5-ECDSA CipherString Selection, no ECDSA certificate]
ssl_conf = 5-ECDSA CipherString Selection, no ECDSA certificate-ssl
[5-ECDSA CipherString Selection, no ECDSA certificate-ssl]
server = 5-ECDSA CipherString Selection, no ECDSA certificate-server
client = 5-ECDSA CipherString Selection, no ECDSA certificate-client
[5-ECDSA CipherString Selection, no ECDSA certificate-server]
Certificate = ${ENV::TEST_CERTS_DIR}/servercert.pem
CipherString = DEFAULT
MaxProtocol = TLSv1.2
PrivateKey = ${ENV::TEST_CERTS_DIR}/serverkey.pem
[5-ECDSA CipherString Selection, no ECDSA certificate-client]
CipherString = aECDSA
MaxProtocol = TLSv1.2
VerifyCAFile = ${ENV::TEST_CERTS_DIR}/rootcert.pem
VerifyMode = Peer
[test-5]
ExpectedResult = ServerFail
# ===========================================================
[6-ECDSA Signature Algorithm Selection]
ssl_conf = 6-ECDSA Signature Algorithm Selection-ssl
[6-ECDSA Signature Algorithm Selection-ssl]
server = 6-ECDSA Signature Algorithm Selection-server
client = 6-ECDSA Signature Algorithm Selection-client
[6-ECDSA Signature Algorithm Selection-server]
Certificate = ${ENV::TEST_CERTS_DIR}/servercert.pem
CipherString = DEFAULT
ECDSA.Certificate = ${ENV::TEST_CERTS_DIR}/server-ecdsa-cert.pem
ECDSA.PrivateKey = ${ENV::TEST_CERTS_DIR}/server-ecdsa-key.pem
Ed25519.Certificate = ${ENV::TEST_CERTS_DIR}/server-ed25519-cert.pem
Ed25519.PrivateKey = ${ENV::TEST_CERTS_DIR}/server-ed25519-key.pem
Ed448.Certificate = ${ENV::TEST_CERTS_DIR}/server-ed448-cert.pem
Ed448.PrivateKey = ${ENV::TEST_CERTS_DIR}/server-ed448-key.pem
MaxProtocol = TLSv1.2
PrivateKey = ${ENV::TEST_CERTS_DIR}/serverkey.pem
[6-ECDSA Signature Algorithm Selection-client]
CipherString = DEFAULT
SignatureAlgorithms = ECDSA+SHA256
VerifyCAFile = ${ENV::TEST_CERTS_DIR}/rootcert.pem
VerifyMode = Peer
[test-6]
ExpectedResult = Success
ExpectedServerCertType = P-256
ExpectedServerSignHash = SHA256
ExpectedServerSignType = EC
# ===========================================================
[7-ECDSA Signature Algorithm Selection SHA384]
ssl_conf = 7-ECDSA Signature Algorithm Selection SHA384-ssl
[7-ECDSA Signature Algorithm Selection SHA384-ssl]
server = 7-ECDSA Signature Algorithm Selection SHA384-server
client = 7-ECDSA Signature Algorithm Selection SHA384-client
[7-ECDSA Signature Algorithm Selection SHA384-server]
Certificate = ${ENV::TEST_CERTS_DIR}/servercert.pem
CipherString = DEFAULT
ECDSA.Certificate = ${ENV::TEST_CERTS_DIR}/server-ecdsa-cert.pem
ECDSA.PrivateKey = ${ENV::TEST_CERTS_DIR}/server-ecdsa-key.pem
Ed25519.Certificate = ${ENV::TEST_CERTS_DIR}/server-ed25519-cert.pem
Ed25519.PrivateKey = ${ENV::TEST_CERTS_DIR}/server-ed25519-key.pem
Ed448.Certificate = ${ENV::TEST_CERTS_DIR}/server-ed448-cert.pem
Ed448.PrivateKey = ${ENV::TEST_CERTS_DIR}/server-ed448-key.pem
MaxProtocol = TLSv1.2
PrivateKey = ${ENV::TEST_CERTS_DIR}/serverkey.pem
[7-ECDSA Signature Algorithm Selection SHA384-client]
CipherString = DEFAULT
SignatureAlgorithms = ECDSA+SHA384
VerifyCAFile = ${ENV::TEST_CERTS_DIR}/rootcert.pem
VerifyMode = Peer
[test-7]
ExpectedResult = Success
ExpectedServerCertType = P-256
ExpectedServerSignHash = SHA384
ExpectedServerSignType = EC
# ===========================================================
[8-ECDSA Signature Algorithm Selection compressed point]
ssl_conf = 8-ECDSA Signature Algorithm Selection compressed point-ssl
[8-ECDSA Signature Algorithm Selection compressed point-ssl]
server = 8-ECDSA Signature Algorithm Selection compressed point-server
client = 8-ECDSA Signature Algorithm Selection compressed point-client
[8-ECDSA Signature Algorithm Selection compressed point-server]
Certificate = ${ENV::TEST_CERTS_DIR}/servercert.pem
CipherString = DEFAULT
ECDSA.Certificate = ${ENV::TEST_CERTS_DIR}/server-cecdsa-cert.pem
ECDSA.PrivateKey = ${ENV::TEST_CERTS_DIR}/server-cecdsa-key.pem
MaxProtocol = TLSv1.2
PrivateKey = ${ENV::TEST_CERTS_DIR}/serverkey.pem
[8-ECDSA Signature Algorithm Selection compressed point-client]
CipherString = DEFAULT
SignatureAlgorithms = ECDSA+SHA256
VerifyCAFile = ${ENV::TEST_CERTS_DIR}/rootcert.pem
VerifyMode = Peer
[test-8]
ExpectedResult = Success
ExpectedServerCertType = P-256
ExpectedServerSignHash = SHA256
ExpectedServerSignType = EC
# ===========================================================
[9-ECDSA Signature Algorithm Selection, no ECDSA certificate]
ssl_conf = 9-ECDSA Signature Algorithm Selection, no ECDSA certificate-ssl
[9-ECDSA Signature Algorithm Selection, no ECDSA certificate-ssl]
server = 9-ECDSA Signature Algorithm Selection, no ECDSA certificate-server
client = 9-ECDSA Signature Algorithm Selection, no ECDSA certificate-client
[9-ECDSA Signature Algorithm Selection, no ECDSA certificate-server]
Certificate = ${ENV::TEST_CERTS_DIR}/servercert.pem
CipherString = DEFAULT
MaxProtocol = TLSv1.2
PrivateKey = ${ENV::TEST_CERTS_DIR}/serverkey.pem
[9-ECDSA Signature Algorithm Selection, no ECDSA certificate-client]
CipherString = DEFAULT
SignatureAlgorithms = ECDSA+SHA256
VerifyCAFile = ${ENV::TEST_CERTS_DIR}/rootcert.pem
VerifyMode = Peer
[test-9]
ExpectedResult = ServerFail
# ===========================================================
[10-RSA Signature Algorithm Selection]
ssl_conf = 10-RSA Signature Algorithm Selection-ssl
[10-RSA Signature Algorithm Selection-ssl]
server = 10-RSA Signature Algorithm Selection-server
client = 10-RSA Signature Algorithm Selection-client
[10-RSA Signature Algorithm Selection-server]
Certificate = ${ENV::TEST_CERTS_DIR}/servercert.pem
CipherString = DEFAULT
ECDSA.Certificate = ${ENV::TEST_CERTS_DIR}/server-ecdsa-cert.pem
ECDSA.PrivateKey = ${ENV::TEST_CERTS_DIR}/server-ecdsa-key.pem
Ed25519.Certificate = ${ENV::TEST_CERTS_DIR}/server-ed25519-cert.pem
Ed25519.PrivateKey = ${ENV::TEST_CERTS_DIR}/server-ed25519-key.pem
Ed448.Certificate = ${ENV::TEST_CERTS_DIR}/server-ed448-cert.pem
Ed448.PrivateKey = ${ENV::TEST_CERTS_DIR}/server-ed448-key.pem
MaxProtocol = TLSv1.2
PrivateKey = ${ENV::TEST_CERTS_DIR}/serverkey.pem
[10-RSA Signature Algorithm Selection-client]
CipherString = DEFAULT
SignatureAlgorithms = RSA+SHA256
VerifyCAFile = ${ENV::TEST_CERTS_DIR}/rootcert.pem
VerifyMode = Peer
[test-10]
ExpectedResult = Success
ExpectedServerCertType = RSA
ExpectedServerSignHash = SHA256
ExpectedServerSignType = RSA
# ===========================================================
[11-RSA-PSS Signature Algorithm Selection]
ssl_conf = 11-RSA-PSS Signature Algorithm Selection-ssl
[11-RSA-PSS Signature Algorithm Selection-ssl]
server = 11-RSA-PSS Signature Algorithm Selection-server
client = 11-RSA-PSS Signature Algorithm Selection-client
[11-RSA-PSS Signature Algorithm Selection-server]
Certificate = ${ENV::TEST_CERTS_DIR}/servercert.pem
CipherString = DEFAULT
ECDSA.Certificate = ${ENV::TEST_CERTS_DIR}/server-ecdsa-cert.pem
ECDSA.PrivateKey = ${ENV::TEST_CERTS_DIR}/server-ecdsa-key.pem
Ed25519.Certificate = ${ENV::TEST_CERTS_DIR}/server-ed25519-cert.pem
Ed25519.PrivateKey = ${ENV::TEST_CERTS_DIR}/server-ed25519-key.pem
Ed448.Certificate = ${ENV::TEST_CERTS_DIR}/server-ed448-cert.pem
Ed448.PrivateKey = ${ENV::TEST_CERTS_DIR}/server-ed448-key.pem
MaxProtocol = TLSv1.2
PrivateKey = ${ENV::TEST_CERTS_DIR}/serverkey.pem
[11-RSA-PSS Signature Algorithm Selection-client]
CipherString = DEFAULT
SignatureAlgorithms = RSA-PSS+SHA256
VerifyCAFile = ${ENV::TEST_CERTS_DIR}/rootcert.pem
VerifyMode = Peer
[test-11]
ExpectedResult = Success
ExpectedServerCertType = RSA
ExpectedServerSignHash = SHA256
ExpectedServerSignType = RSA-PSS
# ===========================================================
[12-RSA key exchange with all RSA certificate types]
ssl_conf = 12-RSA key exchange with all RSA certificate types-ssl
[12-RSA key exchange with all RSA certificate types-ssl]
server = 12-RSA key exchange with all RSA certificate types-server
client = 12-RSA key exchange with all RSA certificate types-client
[12-RSA key exchange with all RSA certificate types-server]
Certificate = ${ENV::TEST_CERTS_DIR}/servercert.pem
CipherString = DEFAULT
PSS.Certificate = ${ENV::TEST_CERTS_DIR}/server-pss-cert.pem
PSS.PrivateKey = ${ENV::TEST_CERTS_DIR}/server-pss-key.pem
PrivateKey = ${ENV::TEST_CERTS_DIR}/serverkey.pem
[12-RSA key exchange with all RSA certificate types-client]
CipherString = kRSA
MaxProtocol = TLSv1.2
VerifyCAFile = ${ENV::TEST_CERTS_DIR}/rootcert.pem
VerifyMode = Peer
[test-12]
ExpectedResult = Success
ExpectedServerCertType = RSA
# ===========================================================
[13-Suite B P-256 Hash Algorithm Selection]
ssl_conf = 13-Suite B P-256 Hash Algorithm Selection-ssl
[13-Suite B P-256 Hash Algorithm Selection-ssl]
server = 13-Suite B P-256 Hash Algorithm Selection-server
client = 13-Suite B P-256 Hash Algorithm Selection-client
[13-Suite B P-256 Hash Algorithm Selection-server]
Certificate = ${ENV::TEST_CERTS_DIR}/servercert.pem
CipherString = SUITEB128
ECDSA.Certificate = ${ENV::TEST_CERTS_DIR}/p256-server-cert.pem
ECDSA.PrivateKey = ${ENV::TEST_CERTS_DIR}/p256-server-key.pem
MaxProtocol = TLSv1.2
PrivateKey = ${ENV::TEST_CERTS_DIR}/serverkey.pem
[13-Suite B P-256 Hash Algorithm Selection-client]
CipherString = DEFAULT
SignatureAlgorithms = ECDSA+SHA384:ECDSA+SHA256
VerifyCAFile = ${ENV::TEST_CERTS_DIR}/p384-root.pem
VerifyMode = Peer
[test-13]
ExpectedResult = Success
ExpectedServerCertType = P-256
ExpectedServerSignHash = SHA256
ExpectedServerSignType = EC
# ===========================================================
[14-Suite B P-384 Hash Algorithm Selection]
ssl_conf = 14-Suite B P-384 Hash Algorithm Selection-ssl
[14-Suite B P-384 Hash Algorithm Selection-ssl]
server = 14-Suite B P-384 Hash Algorithm Selection-server
client = 14-Suite B P-384 Hash Algorithm Selection-client
[14-Suite B P-384 Hash Algorithm Selection-server]
Certificate = ${ENV::TEST_CERTS_DIR}/servercert.pem
CipherString = SUITEB128
ECDSA.Certificate = ${ENV::TEST_CERTS_DIR}/p384-server-cert.pem
ECDSA.PrivateKey = ${ENV::TEST_CERTS_DIR}/p384-server-key.pem
MaxProtocol = TLSv1.2
PrivateKey = ${ENV::TEST_CERTS_DIR}/serverkey.pem
[14-Suite B P-384 Hash Algorithm Selection-client]
CipherString = DEFAULT
SignatureAlgorithms = ECDSA+SHA256:ECDSA+SHA384
VerifyCAFile = ${ENV::TEST_CERTS_DIR}/p384-root.pem
VerifyMode = Peer
[test-14]
ExpectedResult = Success
ExpectedServerCertType = P-384
ExpectedServerSignHash = SHA384
ExpectedServerSignType = EC
# ===========================================================
[15-Ed25519 CipherString and Signature Algorithm Selection]
ssl_conf = 15-Ed25519 CipherString and Signature Algorithm Selection-ssl
[15-Ed25519 CipherString and Signature Algorithm Selection-ssl]
server = 15-Ed25519 CipherString and Signature Algorithm Selection-server
client = 15-Ed25519 CipherString and Signature Algorithm Selection-client
[15-Ed25519 CipherString and Signature Algorithm Selection-server]
Certificate = ${ENV::TEST_CERTS_DIR}/servercert.pem
CipherString = DEFAULT
ECDSA.Certificate = ${ENV::TEST_CERTS_DIR}/server-ecdsa-cert.pem
ECDSA.PrivateKey = ${ENV::TEST_CERTS_DIR}/server-ecdsa-key.pem
Ed25519.Certificate = ${ENV::TEST_CERTS_DIR}/server-ed25519-cert.pem
Ed25519.PrivateKey = ${ENV::TEST_CERTS_DIR}/server-ed25519-key.pem
Ed448.Certificate = ${ENV::TEST_CERTS_DIR}/server-ed448-cert.pem
Ed448.PrivateKey = ${ENV::TEST_CERTS_DIR}/server-ed448-key.pem
MaxProtocol = TLSv1.2
PrivateKey = ${ENV::TEST_CERTS_DIR}/serverkey.pem
[15-Ed25519 CipherString and Signature Algorithm Selection-client]
CipherString = aECDSA
MaxProtocol = TLSv1.2
RequestCAFile = ${ENV::TEST_CERTS_DIR}/root-cert.pem
SignatureAlgorithms = ed25519:ECDSA+SHA256
VerifyCAFile = ${ENV::TEST_CERTS_DIR}/rootcert.pem
VerifyMode = Peer
[test-15]
ExpectedResult = Success
ExpectedServerCANames = empty
ExpectedServerCertType = Ed25519
ExpectedServerSignType = Ed25519
# ===========================================================
[16-Ed448 CipherString and Signature Algorithm Selection]
ssl_conf = 16-Ed448 CipherString and Signature Algorithm Selection-ssl
[16-Ed448 CipherString and Signature Algorithm Selection-ssl]
server = 16-Ed448 CipherString and Signature Algorithm Selection-server
client = 16-Ed448 CipherString and Signature Algorithm Selection-client
[16-Ed448 CipherString and Signature Algorithm Selection-server]
Certificate = ${ENV::TEST_CERTS_DIR}/servercert.pem
CipherString = DEFAULT
ECDSA.Certificate = ${ENV::TEST_CERTS_DIR}/server-ecdsa-cert.pem
ECDSA.PrivateKey = ${ENV::TEST_CERTS_DIR}/server-ecdsa-key.pem
Ed25519.Certificate = ${ENV::TEST_CERTS_DIR}/server-ed25519-cert.pem
Ed25519.PrivateKey = ${ENV::TEST_CERTS_DIR}/server-ed25519-key.pem
Ed448.Certificate = ${ENV::TEST_CERTS_DIR}/server-ed448-cert.pem
Ed448.PrivateKey = ${ENV::TEST_CERTS_DIR}/server-ed448-key.pem
MaxProtocol = TLSv1.2
PrivateKey = ${ENV::TEST_CERTS_DIR}/serverkey.pem
[16-Ed448 CipherString and Signature Algorithm Selection-client]
CipherString = aECDSA
MaxProtocol = TLSv1.2
RequestCAFile = ${ENV::TEST_CERTS_DIR}/root-ed448-cert.pem
SignatureAlgorithms = ed448:ECDSA+SHA256
VerifyCAFile = ${ENV::TEST_CERTS_DIR}/root-ed448-cert.pem
VerifyMode = Peer
[test-16]
ExpectedResult = Success
ExpectedServerCANames = empty
ExpectedServerCertType = Ed448
ExpectedServerSignType = Ed448
# ===========================================================
-[17-Ed25519 CipherString and Curves Selection]
-ssl_conf = 17-Ed25519 CipherString and Curves Selection-ssl
+[17-TLS 1.2 Ed25519 Client Auth]
+ssl_conf = 17-TLS 1.2 Ed25519 Client Auth-ssl
-[17-Ed25519 CipherString and Curves Selection-ssl]
-server = 17-Ed25519 CipherString and Curves Selection-server
-client = 17-Ed25519 CipherString and Curves Selection-client
+[17-TLS 1.2 Ed25519 Client Auth-ssl]
+server = 17-TLS 1.2 Ed25519 Client Auth-server
+client = 17-TLS 1.2 Ed25519 Client Auth-client
-[17-Ed25519 CipherString and Curves Selection-server]
-Certificate = ${ENV::TEST_CERTS_DIR}/servercert.pem
-CipherString = DEFAULT
-ECDSA.Certificate = ${ENV::TEST_CERTS_DIR}/server-ecdsa-cert.pem
-ECDSA.PrivateKey = ${ENV::TEST_CERTS_DIR}/server-ecdsa-key.pem
-Ed25519.Certificate = ${ENV::TEST_CERTS_DIR}/server-ed25519-cert.pem
-Ed25519.PrivateKey = ${ENV::TEST_CERTS_DIR}/server-ed25519-key.pem
-Ed448.Certificate = ${ENV::TEST_CERTS_DIR}/server-ed448-cert.pem
-Ed448.PrivateKey = ${ENV::TEST_CERTS_DIR}/server-ed448-key.pem
-MaxProtocol = TLSv1.2
-PrivateKey = ${ENV::TEST_CERTS_DIR}/serverkey.pem
-
-[17-Ed25519 CipherString and Curves Selection-client]
-CipherString = aECDSA
-Curves = X25519
-MaxProtocol = TLSv1.2
-SignatureAlgorithms = ECDSA+SHA256:ed25519
-VerifyCAFile = ${ENV::TEST_CERTS_DIR}/rootcert.pem
-VerifyMode = Peer
-
-[test-17]
-ExpectedResult = Success
-ExpectedServerCertType = Ed25519
-ExpectedServerSignType = Ed25519
-
-
-# ===========================================================
-
-[18-Ed448 CipherString and Curves Selection]
-ssl_conf = 18-Ed448 CipherString and Curves Selection-ssl
-
-[18-Ed448 CipherString and Curves Selection-ssl]
-server = 18-Ed448 CipherString and Curves Selection-server
-client = 18-Ed448 CipherString and Curves Selection-client
-
-[18-Ed448 CipherString and Curves Selection-server]
-Certificate = ${ENV::TEST_CERTS_DIR}/servercert.pem
-CipherString = DEFAULT
-ECDSA.Certificate = ${ENV::TEST_CERTS_DIR}/server-ecdsa-cert.pem
-ECDSA.PrivateKey = ${ENV::TEST_CERTS_DIR}/server-ecdsa-key.pem
-Ed25519.Certificate = ${ENV::TEST_CERTS_DIR}/server-ed25519-cert.pem
-Ed25519.PrivateKey = ${ENV::TEST_CERTS_DIR}/server-ed25519-key.pem
-Ed448.Certificate = ${ENV::TEST_CERTS_DIR}/server-ed448-cert.pem
-Ed448.PrivateKey = ${ENV::TEST_CERTS_DIR}/server-ed448-key.pem
-MaxProtocol = TLSv1.2
-PrivateKey = ${ENV::TEST_CERTS_DIR}/serverkey.pem
-
-[18-Ed448 CipherString and Curves Selection-client]
-CipherString = aECDSA
-Curves = X448
-MaxProtocol = TLSv1.2
-SignatureAlgorithms = ECDSA+SHA256:ed448
-VerifyCAFile = ${ENV::TEST_CERTS_DIR}/root-ed448-cert.pem
-VerifyMode = Peer
-
-[test-18]
-ExpectedResult = Success
-ExpectedServerCertType = Ed448
-ExpectedServerSignType = Ed448
-
-
-# ===========================================================
-
-[19-TLS 1.2 Ed25519 Client Auth]
-ssl_conf = 19-TLS 1.2 Ed25519 Client Auth-ssl
-
-[19-TLS 1.2 Ed25519 Client Auth-ssl]
-server = 19-TLS 1.2 Ed25519 Client Auth-server
-client = 19-TLS 1.2 Ed25519 Client Auth-client
-
-[19-TLS 1.2 Ed25519 Client Auth-server]
+[17-TLS 1.2 Ed25519 Client Auth-server]
Certificate = ${ENV::TEST_CERTS_DIR}/servercert.pem
CipherString = DEFAULT
PrivateKey = ${ENV::TEST_CERTS_DIR}/serverkey.pem
VerifyCAFile = ${ENV::TEST_CERTS_DIR}/root-cert.pem
VerifyMode = Require
-[19-TLS 1.2 Ed25519 Client Auth-client]
+[17-TLS 1.2 Ed25519 Client Auth-client]
CipherString = DEFAULT
Ed25519.Certificate = ${ENV::TEST_CERTS_DIR}/client-ed25519-cert.pem
Ed25519.PrivateKey = ${ENV::TEST_CERTS_DIR}/client-ed25519-key.pem
MaxProtocol = TLSv1.2
MinProtocol = TLSv1.2
VerifyCAFile = ${ENV::TEST_CERTS_DIR}/rootcert.pem
VerifyMode = Peer
-[test-19]
+[test-17]
ExpectedClientCertType = Ed25519
ExpectedClientSignType = Ed25519
ExpectedResult = Success
# ===========================================================
-[20-TLS 1.2 Ed448 Client Auth]
-ssl_conf = 20-TLS 1.2 Ed448 Client Auth-ssl
+[18-TLS 1.2 Ed448 Client Auth]
+ssl_conf = 18-TLS 1.2 Ed448 Client Auth-ssl
-[20-TLS 1.2 Ed448 Client Auth-ssl]
-server = 20-TLS 1.2 Ed448 Client Auth-server
-client = 20-TLS 1.2 Ed448 Client Auth-client
+[18-TLS 1.2 Ed448 Client Auth-ssl]
+server = 18-TLS 1.2 Ed448 Client Auth-server
+client = 18-TLS 1.2 Ed448 Client Auth-client
-[20-TLS 1.2 Ed448 Client Auth-server]
+[18-TLS 1.2 Ed448 Client Auth-server]
Certificate = ${ENV::TEST_CERTS_DIR}/servercert.pem
CipherString = DEFAULT
PrivateKey = ${ENV::TEST_CERTS_DIR}/serverkey.pem
VerifyCAFile = ${ENV::TEST_CERTS_DIR}/root-cert.pem
VerifyMode = Require
-[20-TLS 1.2 Ed448 Client Auth-client]
+[18-TLS 1.2 Ed448 Client Auth-client]
CipherString = DEFAULT
Ed448.Certificate = ${ENV::TEST_CERTS_DIR}/client-ed448-cert.pem
Ed448.PrivateKey = ${ENV::TEST_CERTS_DIR}/client-ed448-key.pem
MaxProtocol = TLSv1.2
MinProtocol = TLSv1.2
VerifyCAFile = ${ENV::TEST_CERTS_DIR}/rootcert.pem
VerifyMode = Peer
-[test-20]
+[test-18]
ExpectedClientCertType = Ed448
ExpectedClientSignType = Ed448
ExpectedResult = Success
# ===========================================================
-[21-ECDSA Signature Algorithm Selection SHA1]
-ssl_conf = 21-ECDSA Signature Algorithm Selection SHA1-ssl
+[19-ECDSA Signature Algorithm Selection SHA1]
+ssl_conf = 19-ECDSA Signature Algorithm Selection SHA1-ssl
-[21-ECDSA Signature Algorithm Selection SHA1-ssl]
-server = 21-ECDSA Signature Algorithm Selection SHA1-server
-client = 21-ECDSA Signature Algorithm Selection SHA1-client
+[19-ECDSA Signature Algorithm Selection SHA1-ssl]
+server = 19-ECDSA Signature Algorithm Selection SHA1-server
+client = 19-ECDSA Signature Algorithm Selection SHA1-client
-[21-ECDSA Signature Algorithm Selection SHA1-server]
+[19-ECDSA Signature Algorithm Selection SHA1-server]
Certificate = ${ENV::TEST_CERTS_DIR}/servercert.pem
CipherString = DEFAULT:@SECLEVEL=0
ECDSA.Certificate = ${ENV::TEST_CERTS_DIR}/server-ecdsa-cert.pem
ECDSA.PrivateKey = ${ENV::TEST_CERTS_DIR}/server-ecdsa-key.pem
Ed25519.Certificate = ${ENV::TEST_CERTS_DIR}/server-ed25519-cert.pem
Ed25519.PrivateKey = ${ENV::TEST_CERTS_DIR}/server-ed25519-key.pem
Ed448.Certificate = ${ENV::TEST_CERTS_DIR}/server-ed448-cert.pem
Ed448.PrivateKey = ${ENV::TEST_CERTS_DIR}/server-ed448-key.pem
MaxProtocol = TLSv1.2
PrivateKey = ${ENV::TEST_CERTS_DIR}/serverkey.pem
-[21-ECDSA Signature Algorithm Selection SHA1-client]
+[19-ECDSA Signature Algorithm Selection SHA1-client]
CipherString = DEFAULT:@SECLEVEL=0
SignatureAlgorithms = ECDSA+SHA1
VerifyCAFile = ${ENV::TEST_CERTS_DIR}/rootcert.pem
VerifyMode = Peer
-[test-21]
+[test-19]
ExpectedResult = Success
ExpectedServerCertType = P-256
ExpectedServerSignHash = SHA1
ExpectedServerSignType = EC
# ===========================================================
-[22-ECDSA with brainpool]
-ssl_conf = 22-ECDSA with brainpool-ssl
+[20-ECDSA with brainpool]
+ssl_conf = 20-ECDSA with brainpool-ssl
-[22-ECDSA with brainpool-ssl]
-server = 22-ECDSA with brainpool-server
-client = 22-ECDSA with brainpool-client
+[20-ECDSA with brainpool-ssl]
+server = 20-ECDSA with brainpool-server
+client = 20-ECDSA with brainpool-client
-[22-ECDSA with brainpool-server]
+[20-ECDSA with brainpool-server]
Certificate = ${ENV::TEST_CERTS_DIR}/server-ecdsa-brainpoolP256r1-cert.pem
CipherString = DEFAULT
Groups = brainpoolP256r1
PrivateKey = ${ENV::TEST_CERTS_DIR}/server-ecdsa-brainpoolP256r1-key.pem
-[22-ECDSA with brainpool-client]
+[20-ECDSA with brainpool-client]
CipherString = aECDSA
Groups = brainpoolP256r1
MaxProtocol = TLSv1.2
RequestCAFile = ${ENV::TEST_CERTS_DIR}/root-cert.pem
VerifyCAFile = ${ENV::TEST_CERTS_DIR}/rootcert.pem
VerifyMode = Peer
-[test-22]
+[test-20]
ExpectedResult = Success
ExpectedServerCANames = empty
ExpectedServerCertType = brainpoolP256r1
ExpectedServerSignType = EC
+# ===========================================================
+
+[21-Ed25519 CipherString and Curves Selection]
+ssl_conf = 21-Ed25519 CipherString and Curves Selection-ssl
+
+[21-Ed25519 CipherString and Curves Selection-ssl]
+server = 21-Ed25519 CipherString and Curves Selection-server
+client = 21-Ed25519 CipherString and Curves Selection-client
+
+[21-Ed25519 CipherString and Curves Selection-server]
+Certificate = ${ENV::TEST_CERTS_DIR}/servercert.pem
+CipherString = DEFAULT
+ECDSA.Certificate = ${ENV::TEST_CERTS_DIR}/server-ecdsa-cert.pem
+ECDSA.PrivateKey = ${ENV::TEST_CERTS_DIR}/server-ecdsa-key.pem
+Ed25519.Certificate = ${ENV::TEST_CERTS_DIR}/server-ed25519-cert.pem
+Ed25519.PrivateKey = ${ENV::TEST_CERTS_DIR}/server-ed25519-key.pem
+Ed448.Certificate = ${ENV::TEST_CERTS_DIR}/server-ed448-cert.pem
+Ed448.PrivateKey = ${ENV::TEST_CERTS_DIR}/server-ed448-key.pem
+MaxProtocol = TLSv1.2
+PrivateKey = ${ENV::TEST_CERTS_DIR}/serverkey.pem
+
+[21-Ed25519 CipherString and Curves Selection-client]
+CipherString = aECDSA
+Curves = X25519
+MaxProtocol = TLSv1.2
+SignatureAlgorithms = ECDSA+SHA256:ed25519
+VerifyCAFile = ${ENV::TEST_CERTS_DIR}/rootcert.pem
+VerifyMode = Peer
+
+[test-21]
+ExpectedResult = Success
+ExpectedServerCertType = Ed25519
+ExpectedServerSignType = Ed25519
+
+
+# ===========================================================
+
+[22-Ed448 CipherString and Curves Selection]
+ssl_conf = 22-Ed448 CipherString and Curves Selection-ssl
+
+[22-Ed448 CipherString and Curves Selection-ssl]
+server = 22-Ed448 CipherString and Curves Selection-server
+client = 22-Ed448 CipherString and Curves Selection-client
+
+[22-Ed448 CipherString and Curves Selection-server]
+Certificate = ${ENV::TEST_CERTS_DIR}/servercert.pem
+CipherString = DEFAULT
+ECDSA.Certificate = ${ENV::TEST_CERTS_DIR}/server-ecdsa-cert.pem
+ECDSA.PrivateKey = ${ENV::TEST_CERTS_DIR}/server-ecdsa-key.pem
+Ed25519.Certificate = ${ENV::TEST_CERTS_DIR}/server-ed25519-cert.pem
+Ed25519.PrivateKey = ${ENV::TEST_CERTS_DIR}/server-ed25519-key.pem
+Ed448.Certificate = ${ENV::TEST_CERTS_DIR}/server-ed448-cert.pem
+Ed448.PrivateKey = ${ENV::TEST_CERTS_DIR}/server-ed448-key.pem
+MaxProtocol = TLSv1.2
+PrivateKey = ${ENV::TEST_CERTS_DIR}/serverkey.pem
+
+[22-Ed448 CipherString and Curves Selection-client]
+CipherString = aECDSA
+Curves = X448
+MaxProtocol = TLSv1.2
+SignatureAlgorithms = ECDSA+SHA256:ed448
+VerifyCAFile = ${ENV::TEST_CERTS_DIR}/root-ed448-cert.pem
+VerifyMode = Peer
+
+[test-22]
+ExpectedResult = Success
+ExpectedServerCertType = Ed448
+ExpectedServerSignType = Ed448
+
+
# ===========================================================
[23-RSA-PSS Certificate CipherString Selection]
ssl_conf = 23-RSA-PSS Certificate CipherString Selection-ssl
[23-RSA-PSS Certificate CipherString Selection-ssl]
server = 23-RSA-PSS Certificate CipherString Selection-server
client = 23-RSA-PSS Certificate CipherString Selection-client
[23-RSA-PSS Certificate CipherString Selection-server]
Certificate = ${ENV::TEST_CERTS_DIR}/servercert.pem
CipherString = DEFAULT
ECDSA.Certificate = ${ENV::TEST_CERTS_DIR}/server-ecdsa-cert.pem
ECDSA.PrivateKey = ${ENV::TEST_CERTS_DIR}/server-ecdsa-key.pem
Ed25519.Certificate = ${ENV::TEST_CERTS_DIR}/server-ed25519-cert.pem
Ed25519.PrivateKey = ${ENV::TEST_CERTS_DIR}/server-ed25519-key.pem
Ed448.Certificate = ${ENV::TEST_CERTS_DIR}/server-ed448-cert.pem
Ed448.PrivateKey = ${ENV::TEST_CERTS_DIR}/server-ed448-key.pem
MaxProtocol = TLSv1.2
PSS.Certificate = ${ENV::TEST_CERTS_DIR}/server-pss-cert.pem
PSS.PrivateKey = ${ENV::TEST_CERTS_DIR}/server-pss-key.pem
PrivateKey = ${ENV::TEST_CERTS_DIR}/serverkey.pem
[23-RSA-PSS Certificate CipherString Selection-client]
CipherString = aRSA
MaxProtocol = TLSv1.2
VerifyCAFile = ${ENV::TEST_CERTS_DIR}/rootcert.pem
VerifyMode = Peer
[test-23]
ExpectedResult = Success
ExpectedServerCertType = RSA-PSS
ExpectedServerSignType = RSA-PSS
# ===========================================================
[24-RSA-PSS Certificate Legacy Signature Algorithm Selection]
ssl_conf = 24-RSA-PSS Certificate Legacy Signature Algorithm Selection-ssl
[24-RSA-PSS Certificate Legacy Signature Algorithm Selection-ssl]
server = 24-RSA-PSS Certificate Legacy Signature Algorithm Selection-server
client = 24-RSA-PSS Certificate Legacy Signature Algorithm Selection-client
[24-RSA-PSS Certificate Legacy Signature Algorithm Selection-server]
Certificate = ${ENV::TEST_CERTS_DIR}/servercert.pem
CipherString = DEFAULT
ECDSA.Certificate = ${ENV::TEST_CERTS_DIR}/server-ecdsa-cert.pem
ECDSA.PrivateKey = ${ENV::TEST_CERTS_DIR}/server-ecdsa-key.pem
Ed25519.Certificate = ${ENV::TEST_CERTS_DIR}/server-ed25519-cert.pem
Ed25519.PrivateKey = ${ENV::TEST_CERTS_DIR}/server-ed25519-key.pem
Ed448.Certificate = ${ENV::TEST_CERTS_DIR}/server-ed448-cert.pem
Ed448.PrivateKey = ${ENV::TEST_CERTS_DIR}/server-ed448-key.pem
MaxProtocol = TLSv1.2
PSS.Certificate = ${ENV::TEST_CERTS_DIR}/server-pss-cert.pem
PSS.PrivateKey = ${ENV::TEST_CERTS_DIR}/server-pss-key.pem
PrivateKey = ${ENV::TEST_CERTS_DIR}/serverkey.pem
[24-RSA-PSS Certificate Legacy Signature Algorithm Selection-client]
CipherString = DEFAULT
SignatureAlgorithms = RSA-PSS+SHA256
VerifyCAFile = ${ENV::TEST_CERTS_DIR}/rootcert.pem
VerifyMode = Peer
[test-24]
ExpectedResult = Success
ExpectedServerCertType = RSA
ExpectedServerSignHash = SHA256
ExpectedServerSignType = RSA-PSS
# ===========================================================
[25-RSA-PSS Certificate Unified Signature Algorithm Selection]
ssl_conf = 25-RSA-PSS Certificate Unified Signature Algorithm Selection-ssl
[25-RSA-PSS Certificate Unified Signature Algorithm Selection-ssl]
server = 25-RSA-PSS Certificate Unified Signature Algorithm Selection-server
client = 25-RSA-PSS Certificate Unified Signature Algorithm Selection-client
[25-RSA-PSS Certificate Unified Signature Algorithm Selection-server]
Certificate = ${ENV::TEST_CERTS_DIR}/servercert.pem
CipherString = DEFAULT
ECDSA.Certificate = ${ENV::TEST_CERTS_DIR}/server-ecdsa-cert.pem
ECDSA.PrivateKey = ${ENV::TEST_CERTS_DIR}/server-ecdsa-key.pem
Ed25519.Certificate = ${ENV::TEST_CERTS_DIR}/server-ed25519-cert.pem
Ed25519.PrivateKey = ${ENV::TEST_CERTS_DIR}/server-ed25519-key.pem
Ed448.Certificate = ${ENV::TEST_CERTS_DIR}/server-ed448-cert.pem
Ed448.PrivateKey = ${ENV::TEST_CERTS_DIR}/server-ed448-key.pem
MaxProtocol = TLSv1.2
PSS.Certificate = ${ENV::TEST_CERTS_DIR}/server-pss-cert.pem
PSS.PrivateKey = ${ENV::TEST_CERTS_DIR}/server-pss-key.pem
PrivateKey = ${ENV::TEST_CERTS_DIR}/serverkey.pem
[25-RSA-PSS Certificate Unified Signature Algorithm Selection-client]
CipherString = DEFAULT
SignatureAlgorithms = rsa_pss_pss_sha256
VerifyCAFile = ${ENV::TEST_CERTS_DIR}/rootcert.pem
VerifyMode = Peer
[test-25]
ExpectedResult = Success
ExpectedServerCertType = RSA-PSS
ExpectedServerSignHash = SHA256
ExpectedServerSignType = RSA-PSS
# ===========================================================
[26-Only RSA-PSS Certificate]
ssl_conf = 26-Only RSA-PSS Certificate-ssl
[26-Only RSA-PSS Certificate-ssl]
server = 26-Only RSA-PSS Certificate-server
client = 26-Only RSA-PSS Certificate-client
[26-Only RSA-PSS Certificate-server]
Certificate = ${ENV::TEST_CERTS_DIR}/server-pss-cert.pem
CipherString = DEFAULT
PrivateKey = ${ENV::TEST_CERTS_DIR}/server-pss-key.pem
[26-Only RSA-PSS Certificate-client]
CipherString = DEFAULT
VerifyCAFile = ${ENV::TEST_CERTS_DIR}/rootcert.pem
VerifyMode = Peer
[test-26]
ExpectedResult = Success
ExpectedServerCertType = RSA-PSS
ExpectedServerSignHash = SHA256
ExpectedServerSignType = RSA-PSS
# ===========================================================
[27-Only RSA-PSS Certificate Valid Signature Algorithms]
ssl_conf = 27-Only RSA-PSS Certificate Valid Signature Algorithms-ssl
[27-Only RSA-PSS Certificate Valid Signature Algorithms-ssl]
server = 27-Only RSA-PSS Certificate Valid Signature Algorithms-server
client = 27-Only RSA-PSS Certificate Valid Signature Algorithms-client
[27-Only RSA-PSS Certificate Valid Signature Algorithms-server]
Certificate = ${ENV::TEST_CERTS_DIR}/server-pss-cert.pem
CipherString = DEFAULT
PrivateKey = ${ENV::TEST_CERTS_DIR}/server-pss-key.pem
[27-Only RSA-PSS Certificate Valid Signature Algorithms-client]
CipherString = DEFAULT
SignatureAlgorithms = rsa_pss_pss_sha512
VerifyCAFile = ${ENV::TEST_CERTS_DIR}/rootcert.pem
VerifyMode = Peer
[test-27]
ExpectedResult = Success
ExpectedServerCertType = RSA-PSS
ExpectedServerSignHash = SHA512
ExpectedServerSignType = RSA-PSS
# ===========================================================
[28-RSA-PSS Certificate, no PSS signature algorithms]
ssl_conf = 28-RSA-PSS Certificate, no PSS signature algorithms-ssl
[28-RSA-PSS Certificate, no PSS signature algorithms-ssl]
server = 28-RSA-PSS Certificate, no PSS signature algorithms-server
client = 28-RSA-PSS Certificate, no PSS signature algorithms-client
[28-RSA-PSS Certificate, no PSS signature algorithms-server]
Certificate = ${ENV::TEST_CERTS_DIR}/server-pss-cert.pem
CipherString = DEFAULT
PrivateKey = ${ENV::TEST_CERTS_DIR}/server-pss-key.pem
[28-RSA-PSS Certificate, no PSS signature algorithms-client]
CipherString = DEFAULT
SignatureAlgorithms = RSA+SHA256
VerifyCAFile = ${ENV::TEST_CERTS_DIR}/rootcert.pem
VerifyMode = Peer
[test-28]
ExpectedResult = ServerFail
# ===========================================================
[29-Only RSA-PSS Restricted Certificate]
ssl_conf = 29-Only RSA-PSS Restricted Certificate-ssl
[29-Only RSA-PSS Restricted Certificate-ssl]
server = 29-Only RSA-PSS Restricted Certificate-server
client = 29-Only RSA-PSS Restricted Certificate-client
[29-Only RSA-PSS Restricted Certificate-server]
Certificate = ${ENV::TEST_CERTS_DIR}/server-pss-restrict-cert.pem
CipherString = DEFAULT
PrivateKey = ${ENV::TEST_CERTS_DIR}/server-pss-restrict-key.pem
[29-Only RSA-PSS Restricted Certificate-client]
CipherString = DEFAULT
VerifyCAFile = ${ENV::TEST_CERTS_DIR}/rootcert.pem
VerifyMode = Peer
[test-29]
ExpectedResult = Success
ExpectedServerCertType = RSA-PSS
ExpectedServerSignHash = SHA256
ExpectedServerSignType = RSA-PSS
# ===========================================================
[30-RSA-PSS Restricted Certificate Valid Signature Algorithms]
ssl_conf = 30-RSA-PSS Restricted Certificate Valid Signature Algorithms-ssl
[30-RSA-PSS Restricted Certificate Valid Signature Algorithms-ssl]
server = 30-RSA-PSS Restricted Certificate Valid Signature Algorithms-server
client = 30-RSA-PSS Restricted Certificate Valid Signature Algorithms-client
[30-RSA-PSS Restricted Certificate Valid Signature Algorithms-server]
Certificate = ${ENV::TEST_CERTS_DIR}/server-pss-restrict-cert.pem
CipherString = DEFAULT
PrivateKey = ${ENV::TEST_CERTS_DIR}/server-pss-restrict-key.pem
[30-RSA-PSS Restricted Certificate Valid Signature Algorithms-client]
CipherString = DEFAULT
SignatureAlgorithms = rsa_pss_pss_sha256:rsa_pss_pss_sha512
VerifyCAFile = ${ENV::TEST_CERTS_DIR}/rootcert.pem
VerifyMode = Peer
[test-30]
ExpectedResult = Success
ExpectedServerCertType = RSA-PSS
ExpectedServerSignHash = SHA256
ExpectedServerSignType = RSA-PSS
# ===========================================================
[31-RSA-PSS Restricted Cert client prefers invalid Signature Algorithm]
ssl_conf = 31-RSA-PSS Restricted Cert client prefers invalid Signature Algorithm-ssl
[31-RSA-PSS Restricted Cert client prefers invalid Signature Algorithm-ssl]
server = 31-RSA-PSS Restricted Cert client prefers invalid Signature Algorithm-server
client = 31-RSA-PSS Restricted Cert client prefers invalid Signature Algorithm-client
[31-RSA-PSS Restricted Cert client prefers invalid Signature Algorithm-server]
Certificate = ${ENV::TEST_CERTS_DIR}/server-pss-restrict-cert.pem
CipherString = DEFAULT
PrivateKey = ${ENV::TEST_CERTS_DIR}/server-pss-restrict-key.pem
[31-RSA-PSS Restricted Cert client prefers invalid Signature Algorithm-client]
CipherString = DEFAULT
SignatureAlgorithms = rsa_pss_pss_sha512:rsa_pss_pss_sha256
VerifyCAFile = ${ENV::TEST_CERTS_DIR}/rootcert.pem
VerifyMode = Peer
[test-31]
ExpectedResult = Success
ExpectedServerCertType = RSA-PSS
ExpectedServerSignHash = SHA256
ExpectedServerSignType = RSA-PSS
# ===========================================================
[32-RSA-PSS Restricted Certificate Invalid Signature Algorithms]
ssl_conf = 32-RSA-PSS Restricted Certificate Invalid Signature Algorithms-ssl
[32-RSA-PSS Restricted Certificate Invalid Signature Algorithms-ssl]
server = 32-RSA-PSS Restricted Certificate Invalid Signature Algorithms-server
client = 32-RSA-PSS Restricted Certificate Invalid Signature Algorithms-client
[32-RSA-PSS Restricted Certificate Invalid Signature Algorithms-server]
Certificate = ${ENV::TEST_CERTS_DIR}/server-pss-restrict-cert.pem
CipherString = DEFAULT
PrivateKey = ${ENV::TEST_CERTS_DIR}/server-pss-restrict-key.pem
[32-RSA-PSS Restricted Certificate Invalid Signature Algorithms-client]
CipherString = DEFAULT
SignatureAlgorithms = rsa_pss_pss_sha512
VerifyCAFile = ${ENV::TEST_CERTS_DIR}/rootcert.pem
VerifyMode = Peer
[test-32]
ExpectedResult = ServerFail
# ===========================================================
[33-RSA key exchange with only RSA-PSS certificate]
ssl_conf = 33-RSA key exchange with only RSA-PSS certificate-ssl
[33-RSA key exchange with only RSA-PSS certificate-ssl]
server = 33-RSA key exchange with only RSA-PSS certificate-server
client = 33-RSA key exchange with only RSA-PSS certificate-client
[33-RSA key exchange with only RSA-PSS certificate-server]
Certificate = ${ENV::TEST_CERTS_DIR}/server-pss-cert.pem
CipherString = DEFAULT
PrivateKey = ${ENV::TEST_CERTS_DIR}/server-pss-key.pem
[33-RSA key exchange with only RSA-PSS certificate-client]
CipherString = kRSA
MaxProtocol = TLSv1.2
VerifyCAFile = ${ENV::TEST_CERTS_DIR}/rootcert.pem
VerifyMode = Peer
[test-33]
ExpectedResult = ServerFail
# ===========================================================
[34-Only RSA-PSS Certificate, TLS v1.1]
ssl_conf = 34-Only RSA-PSS Certificate, TLS v1.1-ssl
[34-Only RSA-PSS Certificate, TLS v1.1-ssl]
server = 34-Only RSA-PSS Certificate, TLS v1.1-server
client = 34-Only RSA-PSS Certificate, TLS v1.1-client
[34-Only RSA-PSS Certificate, TLS v1.1-server]
Certificate = ${ENV::TEST_CERTS_DIR}/server-pss-cert.pem
CipherString = DEFAULT
PrivateKey = ${ENV::TEST_CERTS_DIR}/server-pss-key.pem
[34-Only RSA-PSS Certificate, TLS v1.1-client]
CipherString = DEFAULT
MaxProtocol = TLSv1.1
VerifyCAFile = ${ENV::TEST_CERTS_DIR}/rootcert.pem
VerifyMode = Peer
[test-34]
ExpectedResult = ServerFail
# ===========================================================
[35-TLS 1.3 ECDSA Signature Algorithm Selection]
ssl_conf = 35-TLS 1.3 ECDSA Signature Algorithm Selection-ssl
[35-TLS 1.3 ECDSA Signature Algorithm Selection-ssl]
server = 35-TLS 1.3 ECDSA Signature Algorithm Selection-server
client = 35-TLS 1.3 ECDSA Signature Algorithm Selection-client
[35-TLS 1.3 ECDSA Signature Algorithm Selection-server]
Certificate = ${ENV::TEST_CERTS_DIR}/servercert.pem
CipherString = DEFAULT
ECDSA.Certificate = ${ENV::TEST_CERTS_DIR}/server-ecdsa-cert.pem
ECDSA.PrivateKey = ${ENV::TEST_CERTS_DIR}/server-ecdsa-key.pem
Ed25519.Certificate = ${ENV::TEST_CERTS_DIR}/server-ed25519-cert.pem
Ed25519.PrivateKey = ${ENV::TEST_CERTS_DIR}/server-ed25519-key.pem
Ed448.Certificate = ${ENV::TEST_CERTS_DIR}/server-ed448-cert.pem
Ed448.PrivateKey = ${ENV::TEST_CERTS_DIR}/server-ed448-key.pem
MaxProtocol = TLSv1.3
MinProtocol = TLSv1.3
PrivateKey = ${ENV::TEST_CERTS_DIR}/serverkey.pem
[35-TLS 1.3 ECDSA Signature Algorithm Selection-client]
CipherString = DEFAULT
SignatureAlgorithms = ECDSA+SHA256
VerifyCAFile = ${ENV::TEST_CERTS_DIR}/rootcert.pem
VerifyMode = Peer
[test-35]
ExpectedResult = Success
ExpectedServerCANames = empty
ExpectedServerCertType = P-256
ExpectedServerSignHash = SHA256
ExpectedServerSignType = EC
# ===========================================================
[36-TLS 1.3 ECDSA Signature Algorithm Selection compressed point]
ssl_conf = 36-TLS 1.3 ECDSA Signature Algorithm Selection compressed point-ssl
[36-TLS 1.3 ECDSA Signature Algorithm Selection compressed point-ssl]
server = 36-TLS 1.3 ECDSA Signature Algorithm Selection compressed point-server
client = 36-TLS 1.3 ECDSA Signature Algorithm Selection compressed point-client
[36-TLS 1.3 ECDSA Signature Algorithm Selection compressed point-server]
Certificate = ${ENV::TEST_CERTS_DIR}/servercert.pem
CipherString = DEFAULT
ECDSA.Certificate = ${ENV::TEST_CERTS_DIR}/server-cecdsa-cert.pem
ECDSA.PrivateKey = ${ENV::TEST_CERTS_DIR}/server-cecdsa-key.pem
MaxProtocol = TLSv1.3
MinProtocol = TLSv1.3
PrivateKey = ${ENV::TEST_CERTS_DIR}/serverkey.pem
[36-TLS 1.3 ECDSA Signature Algorithm Selection compressed point-client]
CipherString = DEFAULT
SignatureAlgorithms = ECDSA+SHA256
VerifyCAFile = ${ENV::TEST_CERTS_DIR}/rootcert.pem
VerifyMode = Peer
[test-36]
ExpectedResult = Success
ExpectedServerCANames = empty
ExpectedServerCertType = P-256
ExpectedServerSignHash = SHA256
ExpectedServerSignType = EC
# ===========================================================
[37-TLS 1.3 ECDSA Signature Algorithm Selection SHA1]
ssl_conf = 37-TLS 1.3 ECDSA Signature Algorithm Selection SHA1-ssl
[37-TLS 1.3 ECDSA Signature Algorithm Selection SHA1-ssl]
server = 37-TLS 1.3 ECDSA Signature Algorithm Selection SHA1-server
client = 37-TLS 1.3 ECDSA Signature Algorithm Selection SHA1-client
[37-TLS 1.3 ECDSA Signature Algorithm Selection SHA1-server]
Certificate = ${ENV::TEST_CERTS_DIR}/servercert.pem
CipherString = DEFAULT:@SECLEVEL=0
ECDSA.Certificate = ${ENV::TEST_CERTS_DIR}/server-ecdsa-cert.pem
ECDSA.PrivateKey = ${ENV::TEST_CERTS_DIR}/server-ecdsa-key.pem
Ed25519.Certificate = ${ENV::TEST_CERTS_DIR}/server-ed25519-cert.pem
Ed25519.PrivateKey = ${ENV::TEST_CERTS_DIR}/server-ed25519-key.pem
Ed448.Certificate = ${ENV::TEST_CERTS_DIR}/server-ed448-cert.pem
Ed448.PrivateKey = ${ENV::TEST_CERTS_DIR}/server-ed448-key.pem
MaxProtocol = TLSv1.3
MinProtocol = TLSv1.3
PrivateKey = ${ENV::TEST_CERTS_DIR}/serverkey.pem
[37-TLS 1.3 ECDSA Signature Algorithm Selection SHA1-client]
CipherString = DEFAULT:@SECLEVEL=0
SignatureAlgorithms = ECDSA+SHA1
VerifyCAFile = ${ENV::TEST_CERTS_DIR}/rootcert.pem
VerifyMode = Peer
[test-37]
ExpectedResult = ServerFail
# ===========================================================
[38-TLS 1.3 ECDSA Signature Algorithm Selection with PSS]
ssl_conf = 38-TLS 1.3 ECDSA Signature Algorithm Selection with PSS-ssl
[38-TLS 1.3 ECDSA Signature Algorithm Selection with PSS-ssl]
server = 38-TLS 1.3 ECDSA Signature Algorithm Selection with PSS-server
client = 38-TLS 1.3 ECDSA Signature Algorithm Selection with PSS-client
[38-TLS 1.3 ECDSA Signature Algorithm Selection with PSS-server]
Certificate = ${ENV::TEST_CERTS_DIR}/servercert.pem
CipherString = DEFAULT
ECDSA.Certificate = ${ENV::TEST_CERTS_DIR}/server-ecdsa-cert.pem
ECDSA.PrivateKey = ${ENV::TEST_CERTS_DIR}/server-ecdsa-key.pem
Ed25519.Certificate = ${ENV::TEST_CERTS_DIR}/server-ed25519-cert.pem
Ed25519.PrivateKey = ${ENV::TEST_CERTS_DIR}/server-ed25519-key.pem
Ed448.Certificate = ${ENV::TEST_CERTS_DIR}/server-ed448-cert.pem
Ed448.PrivateKey = ${ENV::TEST_CERTS_DIR}/server-ed448-key.pem
MaxProtocol = TLSv1.3
MinProtocol = TLSv1.3
PrivateKey = ${ENV::TEST_CERTS_DIR}/serverkey.pem
[38-TLS 1.3 ECDSA Signature Algorithm Selection with PSS-client]
CipherString = DEFAULT
RequestCAFile = ${ENV::TEST_CERTS_DIR}/root-cert.pem
SignatureAlgorithms = ECDSA+SHA256:RSA-PSS+SHA256
VerifyCAFile = ${ENV::TEST_CERTS_DIR}/rootcert.pem
VerifyMode = Peer
[test-38]
ExpectedResult = Success
ExpectedServerCANames = ${ENV::TEST_CERTS_DIR}/root-cert.pem
ExpectedServerCertType = P-256
ExpectedServerSignHash = SHA256
ExpectedServerSignType = EC
# ===========================================================
[39-TLS 1.3 RSA Signature Algorithm Selection SHA384 with PSS]
ssl_conf = 39-TLS 1.3 RSA Signature Algorithm Selection SHA384 with PSS-ssl
[39-TLS 1.3 RSA Signature Algorithm Selection SHA384 with PSS-ssl]
server = 39-TLS 1.3 RSA Signature Algorithm Selection SHA384 with PSS-server
client = 39-TLS 1.3 RSA Signature Algorithm Selection SHA384 with PSS-client
[39-TLS 1.3 RSA Signature Algorithm Selection SHA384 with PSS-server]
Certificate = ${ENV::TEST_CERTS_DIR}/servercert.pem
CipherString = DEFAULT
ECDSA.Certificate = ${ENV::TEST_CERTS_DIR}/server-ecdsa-cert.pem
ECDSA.PrivateKey = ${ENV::TEST_CERTS_DIR}/server-ecdsa-key.pem
Ed25519.Certificate = ${ENV::TEST_CERTS_DIR}/server-ed25519-cert.pem
Ed25519.PrivateKey = ${ENV::TEST_CERTS_DIR}/server-ed25519-key.pem
Ed448.Certificate = ${ENV::TEST_CERTS_DIR}/server-ed448-cert.pem
Ed448.PrivateKey = ${ENV::TEST_CERTS_DIR}/server-ed448-key.pem
MaxProtocol = TLSv1.3
MinProtocol = TLSv1.3
PrivateKey = ${ENV::TEST_CERTS_DIR}/serverkey.pem
[39-TLS 1.3 RSA Signature Algorithm Selection SHA384 with PSS-client]
CipherString = DEFAULT
SignatureAlgorithms = ECDSA+SHA384:RSA-PSS+SHA384
VerifyCAFile = ${ENV::TEST_CERTS_DIR}/rootcert.pem
VerifyMode = Peer
[test-39]
ExpectedResult = Success
ExpectedServerCertType = RSA
ExpectedServerSignHash = SHA384
ExpectedServerSignType = RSA-PSS
# ===========================================================
[40-TLS 1.3 ECDSA Signature Algorithm Selection, no ECDSA certificate]
ssl_conf = 40-TLS 1.3 ECDSA Signature Algorithm Selection, no ECDSA certificate-ssl
[40-TLS 1.3 ECDSA Signature Algorithm Selection, no ECDSA certificate-ssl]
server = 40-TLS 1.3 ECDSA Signature Algorithm Selection, no ECDSA certificate-server
client = 40-TLS 1.3 ECDSA Signature Algorithm Selection, no ECDSA certificate-client
[40-TLS 1.3 ECDSA Signature Algorithm Selection, no ECDSA certificate-server]
Certificate = ${ENV::TEST_CERTS_DIR}/servercert.pem
CipherString = DEFAULT
MaxProtocol = TLSv1.3
MinProtocol = TLSv1.3
PrivateKey = ${ENV::TEST_CERTS_DIR}/serverkey.pem
[40-TLS 1.3 ECDSA Signature Algorithm Selection, no ECDSA certificate-client]
CipherString = DEFAULT
SignatureAlgorithms = ECDSA+SHA256
VerifyCAFile = ${ENV::TEST_CERTS_DIR}/rootcert.pem
VerifyMode = Peer
[test-40]
ExpectedResult = ServerFail
# ===========================================================
[41-TLS 1.3 RSA Signature Algorithm Selection, no PSS]
ssl_conf = 41-TLS 1.3 RSA Signature Algorithm Selection, no PSS-ssl
[41-TLS 1.3 RSA Signature Algorithm Selection, no PSS-ssl]
server = 41-TLS 1.3 RSA Signature Algorithm Selection, no PSS-server
client = 41-TLS 1.3 RSA Signature Algorithm Selection, no PSS-client
[41-TLS 1.3 RSA Signature Algorithm Selection, no PSS-server]
Certificate = ${ENV::TEST_CERTS_DIR}/servercert.pem
CipherString = DEFAULT
ECDSA.Certificate = ${ENV::TEST_CERTS_DIR}/server-ecdsa-cert.pem
ECDSA.PrivateKey = ${ENV::TEST_CERTS_DIR}/server-ecdsa-key.pem
Ed25519.Certificate = ${ENV::TEST_CERTS_DIR}/server-ed25519-cert.pem
Ed25519.PrivateKey = ${ENV::TEST_CERTS_DIR}/server-ed25519-key.pem
Ed448.Certificate = ${ENV::TEST_CERTS_DIR}/server-ed448-cert.pem
Ed448.PrivateKey = ${ENV::TEST_CERTS_DIR}/server-ed448-key.pem
MaxProtocol = TLSv1.3
MinProtocol = TLSv1.3
PrivateKey = ${ENV::TEST_CERTS_DIR}/serverkey.pem
[41-TLS 1.3 RSA Signature Algorithm Selection, no PSS-client]
CipherString = DEFAULT
SignatureAlgorithms = RSA+SHA256
VerifyCAFile = ${ENV::TEST_CERTS_DIR}/rootcert.pem
VerifyMode = Peer
[test-41]
ExpectedResult = ServerFail
# ===========================================================
[42-TLS 1.3 RSA-PSS Signature Algorithm Selection]
ssl_conf = 42-TLS 1.3 RSA-PSS Signature Algorithm Selection-ssl
[42-TLS 1.3 RSA-PSS Signature Algorithm Selection-ssl]
server = 42-TLS 1.3 RSA-PSS Signature Algorithm Selection-server
client = 42-TLS 1.3 RSA-PSS Signature Algorithm Selection-client
[42-TLS 1.3 RSA-PSS Signature Algorithm Selection-server]
Certificate = ${ENV::TEST_CERTS_DIR}/servercert.pem
CipherString = DEFAULT
ECDSA.Certificate = ${ENV::TEST_CERTS_DIR}/server-ecdsa-cert.pem
ECDSA.PrivateKey = ${ENV::TEST_CERTS_DIR}/server-ecdsa-key.pem
Ed25519.Certificate = ${ENV::TEST_CERTS_DIR}/server-ed25519-cert.pem
Ed25519.PrivateKey = ${ENV::TEST_CERTS_DIR}/server-ed25519-key.pem
Ed448.Certificate = ${ENV::TEST_CERTS_DIR}/server-ed448-cert.pem
Ed448.PrivateKey = ${ENV::TEST_CERTS_DIR}/server-ed448-key.pem
MaxProtocol = TLSv1.3
MinProtocol = TLSv1.3
PrivateKey = ${ENV::TEST_CERTS_DIR}/serverkey.pem
[42-TLS 1.3 RSA-PSS Signature Algorithm Selection-client]
CipherString = DEFAULT
SignatureAlgorithms = RSA-PSS+SHA256
VerifyCAFile = ${ENV::TEST_CERTS_DIR}/rootcert.pem
VerifyMode = Peer
[test-42]
ExpectedResult = Success
ExpectedServerCertType = RSA
ExpectedServerSignHash = SHA256
ExpectedServerSignType = RSA-PSS
# ===========================================================
[43-TLS 1.3 RSA Client Auth Signature Algorithm Selection]
ssl_conf = 43-TLS 1.3 RSA Client Auth Signature Algorithm Selection-ssl
[43-TLS 1.3 RSA Client Auth Signature Algorithm Selection-ssl]
server = 43-TLS 1.3 RSA Client Auth Signature Algorithm Selection-server
client = 43-TLS 1.3 RSA Client Auth Signature Algorithm Selection-client
[43-TLS 1.3 RSA Client Auth Signature Algorithm Selection-server]
Certificate = ${ENV::TEST_CERTS_DIR}/servercert.pem
CipherString = DEFAULT
ClientSignatureAlgorithms = PSS+SHA256
PrivateKey = ${ENV::TEST_CERTS_DIR}/serverkey.pem
VerifyCAFile = ${ENV::TEST_CERTS_DIR}/root-cert.pem
VerifyMode = Require
[43-TLS 1.3 RSA Client Auth Signature Algorithm Selection-client]
CipherString = DEFAULT
ECDSA.Certificate = ${ENV::TEST_CERTS_DIR}/ee-ecdsa-client-chain.pem
ECDSA.PrivateKey = ${ENV::TEST_CERTS_DIR}/ee-ecdsa-key.pem
MaxProtocol = TLSv1.3
MinProtocol = TLSv1.3
RSA.Certificate = ${ENV::TEST_CERTS_DIR}/ee-client-chain.pem
RSA.PrivateKey = ${ENV::TEST_CERTS_DIR}/ee-key.pem
VerifyCAFile = ${ENV::TEST_CERTS_DIR}/rootcert.pem
VerifyMode = Peer
[test-43]
ExpectedClientCANames = empty
ExpectedClientCertType = RSA
ExpectedClientSignHash = SHA256
ExpectedClientSignType = RSA-PSS
ExpectedResult = Success
# ===========================================================
[44-TLS 1.3 RSA Client Auth Signature Algorithm Selection non-empty CA Names]
ssl_conf = 44-TLS 1.3 RSA Client Auth Signature Algorithm Selection non-empty CA Names-ssl
[44-TLS 1.3 RSA Client Auth Signature Algorithm Selection non-empty CA Names-ssl]
server = 44-TLS 1.3 RSA Client Auth Signature Algorithm Selection non-empty CA Names-server
client = 44-TLS 1.3 RSA Client Auth Signature Algorithm Selection non-empty CA Names-client
[44-TLS 1.3 RSA Client Auth Signature Algorithm Selection non-empty CA Names-server]
Certificate = ${ENV::TEST_CERTS_DIR}/servercert.pem
CipherString = DEFAULT
ClientSignatureAlgorithms = PSS+SHA256
PrivateKey = ${ENV::TEST_CERTS_DIR}/serverkey.pem
RequestCAFile = ${ENV::TEST_CERTS_DIR}/root-cert.pem
VerifyCAFile = ${ENV::TEST_CERTS_DIR}/root-cert.pem
VerifyMode = Require
[44-TLS 1.3 RSA Client Auth Signature Algorithm Selection non-empty CA Names-client]
CipherString = DEFAULT
ECDSA.Certificate = ${ENV::TEST_CERTS_DIR}/ee-ecdsa-client-chain.pem
ECDSA.PrivateKey = ${ENV::TEST_CERTS_DIR}/ee-ecdsa-key.pem
MaxProtocol = TLSv1.3
MinProtocol = TLSv1.3
RSA.Certificate = ${ENV::TEST_CERTS_DIR}/ee-client-chain.pem
RSA.PrivateKey = ${ENV::TEST_CERTS_DIR}/ee-key.pem
VerifyCAFile = ${ENV::TEST_CERTS_DIR}/rootcert.pem
VerifyMode = Peer
[test-44]
ExpectedClientCANames = ${ENV::TEST_CERTS_DIR}/root-cert.pem
ExpectedClientCertType = RSA
ExpectedClientSignHash = SHA256
ExpectedClientSignType = RSA-PSS
ExpectedResult = Success
# ===========================================================
[45-TLS 1.3 ECDSA Client Auth Signature Algorithm Selection]
ssl_conf = 45-TLS 1.3 ECDSA Client Auth Signature Algorithm Selection-ssl
[45-TLS 1.3 ECDSA Client Auth Signature Algorithm Selection-ssl]
server = 45-TLS 1.3 ECDSA Client Auth Signature Algorithm Selection-server
client = 45-TLS 1.3 ECDSA Client Auth Signature Algorithm Selection-client
[45-TLS 1.3 ECDSA Client Auth Signature Algorithm Selection-server]
Certificate = ${ENV::TEST_CERTS_DIR}/servercert.pem
CipherString = DEFAULT
ClientSignatureAlgorithms = ECDSA+SHA256
PrivateKey = ${ENV::TEST_CERTS_DIR}/serverkey.pem
VerifyCAFile = ${ENV::TEST_CERTS_DIR}/root-cert.pem
VerifyMode = Require
[45-TLS 1.3 ECDSA Client Auth Signature Algorithm Selection-client]
CipherString = DEFAULT
ECDSA.Certificate = ${ENV::TEST_CERTS_DIR}/ee-ecdsa-client-chain.pem
ECDSA.PrivateKey = ${ENV::TEST_CERTS_DIR}/ee-ecdsa-key.pem
MaxProtocol = TLSv1.3
MinProtocol = TLSv1.3
RSA.Certificate = ${ENV::TEST_CERTS_DIR}/ee-client-chain.pem
RSA.PrivateKey = ${ENV::TEST_CERTS_DIR}/ee-key.pem
VerifyCAFile = ${ENV::TEST_CERTS_DIR}/rootcert.pem
VerifyMode = Peer
[test-45]
ExpectedClientCertType = P-256
ExpectedClientSignHash = SHA256
ExpectedClientSignType = EC
ExpectedResult = Success
# ===========================================================
[46-TLS 1.3 Ed25519 Signature Algorithm Selection]
ssl_conf = 46-TLS 1.3 Ed25519 Signature Algorithm Selection-ssl
[46-TLS 1.3 Ed25519 Signature Algorithm Selection-ssl]
server = 46-TLS 1.3 Ed25519 Signature Algorithm Selection-server
client = 46-TLS 1.3 Ed25519 Signature Algorithm Selection-client
[46-TLS 1.3 Ed25519 Signature Algorithm Selection-server]
Certificate = ${ENV::TEST_CERTS_DIR}/servercert.pem
CipherString = DEFAULT
ECDSA.Certificate = ${ENV::TEST_CERTS_DIR}/server-ecdsa-cert.pem
ECDSA.PrivateKey = ${ENV::TEST_CERTS_DIR}/server-ecdsa-key.pem
Ed25519.Certificate = ${ENV::TEST_CERTS_DIR}/server-ed25519-cert.pem
Ed25519.PrivateKey = ${ENV::TEST_CERTS_DIR}/server-ed25519-key.pem
Ed448.Certificate = ${ENV::TEST_CERTS_DIR}/server-ed448-cert.pem
Ed448.PrivateKey = ${ENV::TEST_CERTS_DIR}/server-ed448-key.pem
MaxProtocol = TLSv1.3
MinProtocol = TLSv1.3
PrivateKey = ${ENV::TEST_CERTS_DIR}/serverkey.pem
[46-TLS 1.3 Ed25519 Signature Algorithm Selection-client]
CipherString = DEFAULT
SignatureAlgorithms = ed25519
VerifyCAFile = ${ENV::TEST_CERTS_DIR}/rootcert.pem
VerifyMode = Peer
[test-46]
ExpectedResult = Success
ExpectedServerCertType = Ed25519
ExpectedServerSignType = Ed25519
# ===========================================================
[47-TLS 1.3 Ed448 Signature Algorithm Selection]
ssl_conf = 47-TLS 1.3 Ed448 Signature Algorithm Selection-ssl
[47-TLS 1.3 Ed448 Signature Algorithm Selection-ssl]
server = 47-TLS 1.3 Ed448 Signature Algorithm Selection-server
client = 47-TLS 1.3 Ed448 Signature Algorithm Selection-client
[47-TLS 1.3 Ed448 Signature Algorithm Selection-server]
Certificate = ${ENV::TEST_CERTS_DIR}/servercert.pem
CipherString = DEFAULT
ECDSA.Certificate = ${ENV::TEST_CERTS_DIR}/server-ecdsa-cert.pem
ECDSA.PrivateKey = ${ENV::TEST_CERTS_DIR}/server-ecdsa-key.pem
Ed25519.Certificate = ${ENV::TEST_CERTS_DIR}/server-ed25519-cert.pem
Ed25519.PrivateKey = ${ENV::TEST_CERTS_DIR}/server-ed25519-key.pem
Ed448.Certificate = ${ENV::TEST_CERTS_DIR}/server-ed448-cert.pem
Ed448.PrivateKey = ${ENV::TEST_CERTS_DIR}/server-ed448-key.pem
MaxProtocol = TLSv1.3
MinProtocol = TLSv1.3
PrivateKey = ${ENV::TEST_CERTS_DIR}/serverkey.pem
[47-TLS 1.3 Ed448 Signature Algorithm Selection-client]
CipherString = DEFAULT
SignatureAlgorithms = ed448
VerifyCAFile = ${ENV::TEST_CERTS_DIR}/root-ed448-cert.pem
VerifyMode = Peer
[test-47]
ExpectedResult = Success
ExpectedServerCertType = Ed448
ExpectedServerSignType = Ed448
# ===========================================================
[48-TLS 1.3 Ed25519 CipherString and Groups Selection]
ssl_conf = 48-TLS 1.3 Ed25519 CipherString and Groups Selection-ssl
[48-TLS 1.3 Ed25519 CipherString and Groups Selection-ssl]
server = 48-TLS 1.3 Ed25519 CipherString and Groups Selection-server
client = 48-TLS 1.3 Ed25519 CipherString and Groups Selection-client
[48-TLS 1.3 Ed25519 CipherString and Groups Selection-server]
Certificate = ${ENV::TEST_CERTS_DIR}/servercert.pem
CipherString = DEFAULT
ECDSA.Certificate = ${ENV::TEST_CERTS_DIR}/server-ecdsa-cert.pem
ECDSA.PrivateKey = ${ENV::TEST_CERTS_DIR}/server-ecdsa-key.pem
Ed25519.Certificate = ${ENV::TEST_CERTS_DIR}/server-ed25519-cert.pem
Ed25519.PrivateKey = ${ENV::TEST_CERTS_DIR}/server-ed25519-key.pem
Ed448.Certificate = ${ENV::TEST_CERTS_DIR}/server-ed448-cert.pem
Ed448.PrivateKey = ${ENV::TEST_CERTS_DIR}/server-ed448-key.pem
MaxProtocol = TLSv1.3
MinProtocol = TLSv1.3
PrivateKey = ${ENV::TEST_CERTS_DIR}/serverkey.pem
[48-TLS 1.3 Ed25519 CipherString and Groups Selection-client]
CipherString = DEFAULT
Groups = X25519
SignatureAlgorithms = ECDSA+SHA256:ed25519
VerifyCAFile = ${ENV::TEST_CERTS_DIR}/rootcert.pem
VerifyMode = Peer
[test-48]
ExpectedResult = Success
ExpectedServerCertType = P-256
ExpectedServerSignType = EC
# ===========================================================
[49-TLS 1.3 Ed448 CipherString and Groups Selection]
ssl_conf = 49-TLS 1.3 Ed448 CipherString and Groups Selection-ssl
[49-TLS 1.3 Ed448 CipherString and Groups Selection-ssl]
server = 49-TLS 1.3 Ed448 CipherString and Groups Selection-server
client = 49-TLS 1.3 Ed448 CipherString and Groups Selection-client
[49-TLS 1.3 Ed448 CipherString and Groups Selection-server]
Certificate = ${ENV::TEST_CERTS_DIR}/servercert.pem
CipherString = DEFAULT
ECDSA.Certificate = ${ENV::TEST_CERTS_DIR}/server-ecdsa-cert.pem
ECDSA.PrivateKey = ${ENV::TEST_CERTS_DIR}/server-ecdsa-key.pem
Ed25519.Certificate = ${ENV::TEST_CERTS_DIR}/server-ed25519-cert.pem
Ed25519.PrivateKey = ${ENV::TEST_CERTS_DIR}/server-ed25519-key.pem
Ed448.Certificate = ${ENV::TEST_CERTS_DIR}/server-ed448-cert.pem
Ed448.PrivateKey = ${ENV::TEST_CERTS_DIR}/server-ed448-key.pem
MaxProtocol = TLSv1.3
MinProtocol = TLSv1.3
PrivateKey = ${ENV::TEST_CERTS_DIR}/serverkey.pem
[49-TLS 1.3 Ed448 CipherString and Groups Selection-client]
CipherString = DEFAULT
Groups = X448
SignatureAlgorithms = ECDSA+SHA256:ed448
VerifyCAFile = ${ENV::TEST_CERTS_DIR}/rootcert.pem
VerifyMode = Peer
[test-49]
ExpectedResult = Success
ExpectedServerCertType = P-256
ExpectedServerSignType = EC
# ===========================================================
[50-TLS 1.3 Ed25519 Client Auth]
ssl_conf = 50-TLS 1.3 Ed25519 Client Auth-ssl
[50-TLS 1.3 Ed25519 Client Auth-ssl]
server = 50-TLS 1.3 Ed25519 Client Auth-server
client = 50-TLS 1.3 Ed25519 Client Auth-client
[50-TLS 1.3 Ed25519 Client Auth-server]
Certificate = ${ENV::TEST_CERTS_DIR}/servercert.pem
CipherString = DEFAULT
PrivateKey = ${ENV::TEST_CERTS_DIR}/serverkey.pem
VerifyCAFile = ${ENV::TEST_CERTS_DIR}/root-cert.pem
VerifyMode = Require
[50-TLS 1.3 Ed25519 Client Auth-client]
CipherString = DEFAULT
EdDSA.Certificate = ${ENV::TEST_CERTS_DIR}/client-ed25519-cert.pem
EdDSA.PrivateKey = ${ENV::TEST_CERTS_DIR}/client-ed25519-key.pem
MaxProtocol = TLSv1.3
MinProtocol = TLSv1.3
VerifyCAFile = ${ENV::TEST_CERTS_DIR}/rootcert.pem
VerifyMode = Peer
[test-50]
ExpectedClientCertType = Ed25519
ExpectedClientSignType = Ed25519
ExpectedResult = Success
# ===========================================================
[51-TLS 1.3 Ed448 Client Auth]
ssl_conf = 51-TLS 1.3 Ed448 Client Auth-ssl
[51-TLS 1.3 Ed448 Client Auth-ssl]
server = 51-TLS 1.3 Ed448 Client Auth-server
client = 51-TLS 1.3 Ed448 Client Auth-client
[51-TLS 1.3 Ed448 Client Auth-server]
Certificate = ${ENV::TEST_CERTS_DIR}/servercert.pem
CipherString = DEFAULT
PrivateKey = ${ENV::TEST_CERTS_DIR}/serverkey.pem
VerifyCAFile = ${ENV::TEST_CERTS_DIR}/root-cert.pem
VerifyMode = Require
[51-TLS 1.3 Ed448 Client Auth-client]
CipherString = DEFAULT
EdDSA.Certificate = ${ENV::TEST_CERTS_DIR}/client-ed448-cert.pem
EdDSA.PrivateKey = ${ENV::TEST_CERTS_DIR}/client-ed448-key.pem
MaxProtocol = TLSv1.3
MinProtocol = TLSv1.3
VerifyCAFile = ${ENV::TEST_CERTS_DIR}/rootcert.pem
VerifyMode = Peer
[test-51]
ExpectedClientCertType = Ed448
ExpectedClientSignType = Ed448
ExpectedResult = Success
# ===========================================================
[52-TLS 1.3 ECDSA with brainpool but no suitable groups]
ssl_conf = 52-TLS 1.3 ECDSA with brainpool but no suitable groups-ssl
[52-TLS 1.3 ECDSA with brainpool but no suitable groups-ssl]
server = 52-TLS 1.3 ECDSA with brainpool but no suitable groups-server
client = 52-TLS 1.3 ECDSA with brainpool but no suitable groups-client
[52-TLS 1.3 ECDSA with brainpool but no suitable groups-server]
Certificate = ${ENV::TEST_CERTS_DIR}/server-ecdsa-brainpoolP256r1-cert.pem
CipherString = DEFAULT
Groups = brainpoolP256r1
PrivateKey = ${ENV::TEST_CERTS_DIR}/server-ecdsa-brainpoolP256r1-key.pem
[52-TLS 1.3 ECDSA with brainpool but no suitable groups-client]
CipherString = aECDSA
Groups = brainpoolP256r1
RequestCAFile = ${ENV::TEST_CERTS_DIR}/root-cert.pem
VerifyCAFile = ${ENV::TEST_CERTS_DIR}/rootcert.pem
VerifyMode = Peer
[test-52]
ExpectedResult = ClientFail
# ===========================================================
[53-TLS 1.3 ECDSA with brainpool]
ssl_conf = 53-TLS 1.3 ECDSA with brainpool-ssl
[53-TLS 1.3 ECDSA with brainpool-ssl]
server = 53-TLS 1.3 ECDSA with brainpool-server
client = 53-TLS 1.3 ECDSA with brainpool-client
[53-TLS 1.3 ECDSA with brainpool-server]
Certificate = ${ENV::TEST_CERTS_DIR}/server-ecdsa-brainpoolP256r1-cert.pem
CipherString = DEFAULT
PrivateKey = ${ENV::TEST_CERTS_DIR}/server-ecdsa-brainpoolP256r1-key.pem
[53-TLS 1.3 ECDSA with brainpool-client]
CipherString = DEFAULT
MaxProtocol = TLSv1.3
MinProtocol = TLSv1.3
RequestCAFile = ${ENV::TEST_CERTS_DIR}/root-cert.pem
VerifyCAFile = ${ENV::TEST_CERTS_DIR}/rootcert.pem
VerifyMode = Peer
[test-53]
ExpectedResult = ServerFail
# ===========================================================
[54-TLS 1.2 DSA Certificate Test]
ssl_conf = 54-TLS 1.2 DSA Certificate Test-ssl
[54-TLS 1.2 DSA Certificate Test-ssl]
server = 54-TLS 1.2 DSA Certificate Test-server
client = 54-TLS 1.2 DSA Certificate Test-client
[54-TLS 1.2 DSA Certificate Test-server]
Certificate = ${ENV::TEST_CERTS_DIR}/servercert.pem
CipherString = ALL
DHParameters = ${ENV::TEST_CERTS_DIR}/dhp2048.pem
DSA.Certificate = ${ENV::TEST_CERTS_DIR}/server-dsa-cert.pem
DSA.PrivateKey = ${ENV::TEST_CERTS_DIR}/server-dsa-key.pem
MaxProtocol = TLSv1.2
MinProtocol = TLSv1.2
PrivateKey = ${ENV::TEST_CERTS_DIR}/serverkey.pem
[54-TLS 1.2 DSA Certificate Test-client]
CipherString = ALL
SignatureAlgorithms = DSA+SHA256:DSA+SHA1
VerifyCAFile = ${ENV::TEST_CERTS_DIR}/rootcert.pem
VerifyMode = Peer
[test-54]
ExpectedResult = Success
# ===========================================================
[55-TLS 1.3 Client Auth No TLS 1.3 Signature Algorithms]
ssl_conf = 55-TLS 1.3 Client Auth No TLS 1.3 Signature Algorithms-ssl
[55-TLS 1.3 Client Auth No TLS 1.3 Signature Algorithms-ssl]
server = 55-TLS 1.3 Client Auth No TLS 1.3 Signature Algorithms-server
client = 55-TLS 1.3 Client Auth No TLS 1.3 Signature Algorithms-client
[55-TLS 1.3 Client Auth No TLS 1.3 Signature Algorithms-server]
Certificate = ${ENV::TEST_CERTS_DIR}/servercert.pem
CipherString = DEFAULT
ClientSignatureAlgorithms = ECDSA+SHA1:DSA+SHA256:RSA+SHA256
PrivateKey = ${ENV::TEST_CERTS_DIR}/serverkey.pem
VerifyCAFile = ${ENV::TEST_CERTS_DIR}/root-cert.pem
VerifyMode = Request
[55-TLS 1.3 Client Auth No TLS 1.3 Signature Algorithms-client]
CipherString = DEFAULT
VerifyCAFile = ${ENV::TEST_CERTS_DIR}/rootcert.pem
VerifyMode = Peer
[test-55]
ExpectedResult = ServerFail
# ===========================================================
[56-TLS 1.3 DSA Certificate Test]
ssl_conf = 56-TLS 1.3 DSA Certificate Test-ssl
[56-TLS 1.3 DSA Certificate Test-ssl]
server = 56-TLS 1.3 DSA Certificate Test-server
client = 56-TLS 1.3 DSA Certificate Test-client
[56-TLS 1.3 DSA Certificate Test-server]
Certificate = ${ENV::TEST_CERTS_DIR}/servercert.pem
CipherString = ALL
DSA.Certificate = ${ENV::TEST_CERTS_DIR}/server-dsa-cert.pem
DSA.PrivateKey = ${ENV::TEST_CERTS_DIR}/server-dsa-key.pem
MaxProtocol = TLSv1.3
MinProtocol = TLSv1.3
PrivateKey = ${ENV::TEST_CERTS_DIR}/serverkey.pem
[56-TLS 1.3 DSA Certificate Test-client]
CipherString = ALL
SignatureAlgorithms = DSA+SHA1:DSA+SHA256:ECDSA+SHA256
VerifyCAFile = ${ENV::TEST_CERTS_DIR}/rootcert.pem
VerifyMode = Peer
[test-56]
ExpectedResult = ServerFail
diff --git a/crypto/openssl/test/ssl-tests/20-cert-select.cnf.in b/crypto/openssl/test/ssl-tests/20-cert-select.cnf.in
index 30cde592c6d0..435932c4c181 100644
--- a/crypto/openssl/test/ssl-tests/20-cert-select.cnf.in
+++ b/crypto/openssl/test/ssl-tests/20-cert-select.cnf.in
@@ -1,991 +1,991 @@
# -*- mode: perl; -*-
## SSL test configurations
use strict;
use warnings;
package ssltests;
use OpenSSL::Test::Utils;
our $fips_mode;
our $no_deflt_libctx;
my $server = {
"ECDSA.Certificate" => test_pem("server-ecdsa-cert.pem"),
"ECDSA.PrivateKey" => test_pem("server-ecdsa-key.pem"),
"Ed25519.Certificate" => test_pem("server-ed25519-cert.pem"),
"Ed25519.PrivateKey" => test_pem("server-ed25519-key.pem"),
"Ed448.Certificate" => test_pem("server-ed448-cert.pem"),
"Ed448.PrivateKey" => test_pem("server-ed448-key.pem"),
"MaxProtocol" => "TLSv1.2"
};
my $server_pss = {
"PSS.Certificate" => test_pem("server-pss-cert.pem"),
"PSS.PrivateKey" => test_pem("server-pss-key.pem"),
"ECDSA.Certificate" => test_pem("server-ecdsa-cert.pem"),
"ECDSA.PrivateKey" => test_pem("server-ecdsa-key.pem"),
"Ed25519.Certificate" => test_pem("server-ed25519-cert.pem"),
"Ed25519.PrivateKey" => test_pem("server-ed25519-key.pem"),
"Ed448.Certificate" => test_pem("server-ed448-cert.pem"),
"Ed448.PrivateKey" => test_pem("server-ed448-key.pem"),
"MaxProtocol" => "TLSv1.2"
};
my $server_pss_only = {
"Certificate" => test_pem("server-pss-cert.pem"),
"PrivateKey" => test_pem("server-pss-key.pem"),
};
my $server_pss_restrict_only = {
"Certificate" => test_pem("server-pss-restrict-cert.pem"),
"PrivateKey" => test_pem("server-pss-restrict-key.pem"),
};
my $server_rsa_all;
if ($no_deflt_libctx) {
$server_rsa_all = {
"Certificate" => test_pem("servercert.pem"),
"PrivateKey" => test_pem("serverkey.pem"),
};
} else {
$server_rsa_all = {
"PSS.Certificate" => test_pem("server-pss-cert.pem"),
"PSS.PrivateKey" => test_pem("server-pss-key.pem"),
"Certificate" => test_pem("servercert.pem"),
"PrivateKey" => test_pem("serverkey.pem"),
};
}
our @tests = (
{
name => "ECDSA CipherString Selection",
server => $server,
client => {
"CipherString" => "aECDSA",
"MaxProtocol" => "TLSv1.2",
"RequestCAFile" => test_pem("root-cert.pem"),
},
test => {
"ExpectedServerCertType" =>, "P-256",
"ExpectedServerSignType" =>, "EC",
# Note: certificate_authorities not sent for TLS < 1.3
"ExpectedServerCANames" =>, "empty",
"ExpectedResult" => "Success"
},
},
{
name => "ECDSA CipherString Selection",
server => {
"ECDSA.Certificate" => test_pem("server-ecdsa-cert.pem"),
"ECDSA.PrivateKey" => test_pem("server-ecdsa-key.pem"),
"MaxProtocol" => "TLSv1.2",
#Deliberately set supported_groups to one not in the cert. This
#should be tolerated
"Groups" => "P-384"
},
client => {
"CipherString" => "aECDSA",
"MaxProtocol" => "TLSv1.2",
"Groups" => "P-256:P-384",
"RequestCAFile" => test_pem("root-cert.pem"),
},
test => {
"ExpectedServerCertType" =>, "P-256",
"ExpectedServerSignType" =>, "EC",
# Note: certificate_authorities not sent for TLS < 1.3
"ExpectedServerCANames" =>, "empty",
"ExpectedResult" => "Success"
},
},
{
name => "ECDSA CipherString Selection",
server => {
"ECDSA.Certificate" => test_pem("server-ecdsa-cert.pem"),
"ECDSA.PrivateKey" => test_pem("server-ecdsa-key.pem"),
"MaxProtocol" => "TLSv1.2",
"Groups" => "P-256:P-384"
},
client => {
"CipherString" => "aECDSA",
"MaxProtocol" => "TLSv1.2",
#Deliberately set groups to not include the certificate group. This
#should fail
"Groups" => "P-384",
"RequestCAFile" => test_pem("root-cert.pem"),
},
test => {
"ExpectedResult" => "ServerFail"
},
},
{
name => "RSA CipherString Selection",
server => $server,
client => {
"CipherString" => "aRSA",
"MaxProtocol" => "TLSv1.2",
},
test => {
"ExpectedServerCertType" =>, "RSA",
"ExpectedServerSignType" =>, "RSA-PSS",
"ExpectedResult" => "Success"
},
},
{
name => "P-256 CipherString and Signature Algorithm Selection",
server => $server,
client => {
"CipherString" => "aECDSA",
"MaxProtocol" => "TLSv1.2",
"SignatureAlgorithms" => "ECDSA+SHA256:ed25519",
},
test => {
"ExpectedServerCertType" => "P-256",
"ExpectedServerSignHash" => "SHA256",
"ExpectedServerSignType" => "EC",
"ExpectedResult" => "Success"
},
},
{
name => "ECDSA CipherString Selection, no ECDSA certificate",
server => {
"MaxProtocol" => "TLSv1.2"
},
client => {
"CipherString" => "aECDSA",
"MaxProtocol" => "TLSv1.2"
},
test => {
"ExpectedResult" => "ServerFail"
},
},
{
name => "ECDSA Signature Algorithm Selection",
server => $server,
client => {
"SignatureAlgorithms" => "ECDSA+SHA256",
},
test => {
"ExpectedServerCertType" => "P-256",
"ExpectedServerSignHash" => "SHA256",
"ExpectedServerSignType" => "EC",
"ExpectedResult" => "Success"
},
},
{
name => "ECDSA Signature Algorithm Selection SHA384",
server => $server,
client => {
"SignatureAlgorithms" => "ECDSA+SHA384",
},
test => {
"ExpectedServerCertType" => "P-256",
"ExpectedServerSignHash" => "SHA384",
"ExpectedServerSignType" => "EC",
"ExpectedResult" => "Success"
},
},
{
name => "ECDSA Signature Algorithm Selection compressed point",
server => {
"ECDSA.Certificate" => test_pem("server-cecdsa-cert.pem"),
"ECDSA.PrivateKey" => test_pem("server-cecdsa-key.pem"),
"MaxProtocol" => "TLSv1.2"
},
client => {
"SignatureAlgorithms" => "ECDSA+SHA256",
},
test => {
"ExpectedServerCertType" => "P-256",
"ExpectedServerSignHash" => "SHA256",
"ExpectedServerSignType" => "EC",
"ExpectedResult" => "Success"
},
},
{
name => "ECDSA Signature Algorithm Selection, no ECDSA certificate",
server => {
"MaxProtocol" => "TLSv1.2"
},
client => {
"SignatureAlgorithms" => "ECDSA+SHA256",
},
test => {
"ExpectedResult" => "ServerFail"
},
},
{
name => "RSA Signature Algorithm Selection",
server => $server,
client => {
"SignatureAlgorithms" => "RSA+SHA256",
},
test => {
"ExpectedServerCertType" => "RSA",
"ExpectedServerSignHash" => "SHA256",
"ExpectedServerSignType" => "RSA",
"ExpectedResult" => "Success"
},
},
{
name => "RSA-PSS Signature Algorithm Selection",
server => $server,
client => {
"SignatureAlgorithms" => "RSA-PSS+SHA256",
},
test => {
"ExpectedServerCertType" => "RSA",
"ExpectedServerSignHash" => "SHA256",
"ExpectedServerSignType" => "RSA-PSS",
"ExpectedResult" => "Success"
},
},
{
name => "RSA key exchange with all RSA certificate types",
server => $server_rsa_all,
client => {
"CipherString" => "kRSA",
"MaxProtocol" => "TLSv1.2",
},
test => {
"ExpectedServerCertType" =>, "RSA",
"ExpectedResult" => "Success"
},
},
{
name => "Suite B P-256 Hash Algorithm Selection",
server => {
"ECDSA.Certificate" => test_pem("p256-server-cert.pem"),
"ECDSA.PrivateKey" => test_pem("p256-server-key.pem"),
"MaxProtocol" => "TLSv1.2",
"CipherString" => "SUITEB128"
},
client => {
"VerifyCAFile" => test_pem("p384-root.pem"),
"SignatureAlgorithms" => "ECDSA+SHA384:ECDSA+SHA256"
},
test => {
"ExpectedServerCertType" => "P-256",
"ExpectedServerSignHash" => "SHA256",
"ExpectedServerSignType" => "EC",
"ExpectedResult" => "Success"
},
},
{
name => "Suite B P-384 Hash Algorithm Selection",
server => {
"ECDSA.Certificate" => test_pem("p384-server-cert.pem"),
"ECDSA.PrivateKey" => test_pem("p384-server-key.pem"),
"MaxProtocol" => "TLSv1.2",
"CipherString" => "SUITEB128"
},
client => {
"VerifyCAFile" => test_pem("p384-root.pem"),
"SignatureAlgorithms" => "ECDSA+SHA256:ECDSA+SHA384"
},
test => {
"ExpectedServerCertType" => "P-384",
"ExpectedServerSignHash" => "SHA384",
"ExpectedServerSignType" => "EC",
"ExpectedResult" => "Success"
},
},
{
name => "Ed25519 CipherString and Signature Algorithm Selection",
server => $server,
client => {
"CipherString" => "aECDSA",
"MaxProtocol" => "TLSv1.2",
"SignatureAlgorithms" => "ed25519:ECDSA+SHA256",
"RequestCAFile" => test_pem("root-cert.pem"),
},
test => {
"ExpectedServerCertType" =>, "Ed25519",
"ExpectedServerSignType" =>, "Ed25519",
# Note: certificate_authorities not sent for TLS < 1.3
"ExpectedServerCANames" =>, "empty",
"ExpectedResult" => "Success"
},
},
{
name => "Ed448 CipherString and Signature Algorithm Selection",
server => $server,
client => {
"CipherString" => "aECDSA",
"MaxProtocol" => "TLSv1.2",
"SignatureAlgorithms" => "ed448:ECDSA+SHA256",
"RequestCAFile" => test_pem("root-ed448-cert.pem"),
"VerifyCAFile" => test_pem("root-ed448-cert.pem"),
},
test => {
"ExpectedServerCertType" =>, "Ed448",
"ExpectedServerSignType" =>, "Ed448",
# Note: certificate_authorities not sent for TLS < 1.3
"ExpectedServerCANames" =>, "empty",
"ExpectedResult" => "Success"
},
},
- {
- name => "Ed25519 CipherString and Curves Selection",
- server => $server,
- client => {
- "CipherString" => "aECDSA",
- "MaxProtocol" => "TLSv1.2",
- "SignatureAlgorithms" => "ECDSA+SHA256:ed25519",
- # Excluding P-256 from the supported curves list means server
- # certificate should be Ed25519 and not P-256
- "Curves" => "X25519"
- },
- test => {
- "ExpectedServerCertType" =>, "Ed25519",
- "ExpectedServerSignType" =>, "Ed25519",
- "ExpectedResult" => "Success"
- },
- },
- {
- name => "Ed448 CipherString and Curves Selection",
- server => $server,
- client => {
- "CipherString" => "aECDSA",
- "MaxProtocol" => "TLSv1.2",
- "SignatureAlgorithms" => "ECDSA+SHA256:ed448",
- "VerifyCAFile" => test_pem("root-ed448-cert.pem"),
- # Excluding P-256 from the supported curves list means server
- # certificate should be Ed25519 and not P-256
- "Curves" => "X448"
- },
- test => {
- "ExpectedServerCertType" =>, "Ed448",
- "ExpectedServerSignType" =>, "Ed448",
- "ExpectedResult" => "Success"
- },
- },
{
name => "TLS 1.2 Ed25519 Client Auth",
server => {
"VerifyCAFile" => test_pem("root-cert.pem"),
"VerifyMode" => "Require"
},
client => {
"Ed25519.Certificate" => test_pem("client-ed25519-cert.pem"),
"Ed25519.PrivateKey" => test_pem("client-ed25519-key.pem"),
"MinProtocol" => "TLSv1.2",
"MaxProtocol" => "TLSv1.2"
},
test => {
"ExpectedClientCertType" => "Ed25519",
"ExpectedClientSignType" => "Ed25519",
"ExpectedResult" => "Success"
},
},
{
name => "TLS 1.2 Ed448 Client Auth",
server => {
"VerifyCAFile" => test_pem("root-cert.pem"),
"VerifyMode" => "Require"
},
client => {
"Ed448.Certificate" => test_pem("client-ed448-cert.pem"),
"Ed448.PrivateKey" => test_pem("client-ed448-key.pem"),
"MinProtocol" => "TLSv1.2",
"MaxProtocol" => "TLSv1.2"
},
test => {
"ExpectedClientCertType" => "Ed448",
"ExpectedClientSignType" => "Ed448",
"ExpectedResult" => "Success"
},
},
);
my @tests_non_fips = (
{
name => "ECDSA Signature Algorithm Selection SHA1",
server => {
"CipherString" => "DEFAULT:\@SECLEVEL=0",
"ECDSA.Certificate" => test_pem("server-ecdsa-cert.pem"),
"ECDSA.PrivateKey" => test_pem("server-ecdsa-key.pem"),
"Ed25519.Certificate" => test_pem("server-ed25519-cert.pem"),
"Ed25519.PrivateKey" => test_pem("server-ed25519-key.pem"),
"Ed448.Certificate" => test_pem("server-ed448-cert.pem"),
"Ed448.PrivateKey" => test_pem("server-ed448-key.pem"),
"MaxProtocol" => "TLSv1.2"
},
client => {
"CipherString" => "DEFAULT:\@SECLEVEL=0",
"SignatureAlgorithms" => "ECDSA+SHA1",
},
test => {
"ExpectedServerCertType" => "P-256",
"ExpectedServerSignHash" => "SHA1",
"ExpectedServerSignType" => "EC",
"ExpectedResult" => "Success"
},
},
{
name => "ECDSA with brainpool",
server => {
"Certificate" => test_pem("server-ecdsa-brainpoolP256r1-cert.pem"),
"PrivateKey" => test_pem("server-ecdsa-brainpoolP256r1-key.pem"),
"Groups" => "brainpoolP256r1",
},
client => {
"MaxProtocol" => "TLSv1.2",
"CipherString" => "aECDSA",
"RequestCAFile" => test_pem("root-cert.pem"),
"Groups" => "brainpoolP256r1",
},
test => {
"ExpectedServerCertType" =>, "brainpoolP256r1",
"ExpectedServerSignType" =>, "EC",
# Note: certificate_authorities not sent for TLS < 1.3
"ExpectedServerCANames" =>, "empty",
"ExpectedResult" => "Success"
},
},
+ {
+ name => "Ed25519 CipherString and Curves Selection",
+ server => $server,
+ client => {
+ "CipherString" => "aECDSA",
+ "MaxProtocol" => "TLSv1.2",
+ "SignatureAlgorithms" => "ECDSA+SHA256:ed25519",
+ # Excluding P-256 from the supported curves list means server
+ # certificate should be Ed25519 and not P-256
+ "Curves" => "X25519"
+ },
+ test => {
+ "ExpectedServerCertType" =>, "Ed25519",
+ "ExpectedServerSignType" =>, "Ed25519",
+ "ExpectedResult" => "Success"
+ },
+ },
+ {
+ name => "Ed448 CipherString and Curves Selection",
+ server => $server,
+ client => {
+ "CipherString" => "aECDSA",
+ "MaxProtocol" => "TLSv1.2",
+ "SignatureAlgorithms" => "ECDSA+SHA256:ed448",
+ "VerifyCAFile" => test_pem("root-ed448-cert.pem"),
+ # Excluding P-256 from the supported curves list means server
+ # certificate should be Ed25519 and not P-256
+ "Curves" => "X448"
+ },
+ test => {
+ "ExpectedServerCertType" =>, "Ed448",
+ "ExpectedServerSignType" =>, "Ed448",
+ "ExpectedResult" => "Success"
+ },
+ },
);
my @tests_pss = (
{
name => "RSA-PSS Certificate CipherString Selection",
server => $server_pss,
client => {
"CipherString" => "aRSA",
"MaxProtocol" => "TLSv1.2",
},
test => {
"ExpectedServerCertType" =>, "RSA-PSS",
"ExpectedServerSignType" =>, "RSA-PSS",
"ExpectedResult" => "Success"
},
},
{
name => "RSA-PSS Certificate Legacy Signature Algorithm Selection",
server => $server_pss,
client => {
"SignatureAlgorithms" => "RSA-PSS+SHA256",
},
test => {
"ExpectedServerCertType" => "RSA",
"ExpectedServerSignHash" => "SHA256",
"ExpectedServerSignType" => "RSA-PSS",
"ExpectedResult" => "Success"
},
},
{
name => "RSA-PSS Certificate Unified Signature Algorithm Selection",
server => $server_pss,
client => {
"SignatureAlgorithms" => "rsa_pss_pss_sha256",
},
test => {
"ExpectedServerCertType" => "RSA-PSS",
"ExpectedServerSignHash" => "SHA256",
"ExpectedServerSignType" => "RSA-PSS",
"ExpectedResult" => "Success"
},
},
{
name => "Only RSA-PSS Certificate",
server => $server_pss_only,
client => {},
test => {
"ExpectedServerCertType" => "RSA-PSS",
"ExpectedServerSignHash" => "SHA256",
"ExpectedServerSignType" => "RSA-PSS",
"ExpectedResult" => "Success"
},
},
{
name => "Only RSA-PSS Certificate Valid Signature Algorithms",
server => $server_pss_only,
client => {
"SignatureAlgorithms" => "rsa_pss_pss_sha512",
},
test => {
"ExpectedServerCertType" => "RSA-PSS",
"ExpectedServerSignHash" => "SHA512",
"ExpectedServerSignType" => "RSA-PSS",
"ExpectedResult" => "Success"
},
},
{
name => "RSA-PSS Certificate, no PSS signature algorithms",
server => $server_pss_only,
client => {
"SignatureAlgorithms" => "RSA+SHA256",
},
test => {
"ExpectedResult" => "ServerFail"
},
},
{
name => "Only RSA-PSS Restricted Certificate",
server => $server_pss_restrict_only,
client => {},
test => {
"ExpectedServerCertType" => "RSA-PSS",
"ExpectedServerSignHash" => "SHA256",
"ExpectedServerSignType" => "RSA-PSS",
"ExpectedResult" => "Success"
},
},
{
name => "RSA-PSS Restricted Certificate Valid Signature Algorithms",
server => $server_pss_restrict_only,
client => {
"SignatureAlgorithms" => "rsa_pss_pss_sha256:rsa_pss_pss_sha512",
},
test => {
"ExpectedServerCertType" => "RSA-PSS",
"ExpectedServerSignHash" => "SHA256",
"ExpectedServerSignType" => "RSA-PSS",
"ExpectedResult" => "Success"
},
},
{
name => "RSA-PSS Restricted Cert client prefers invalid Signature Algorithm",
server => $server_pss_restrict_only,
client => {
"SignatureAlgorithms" => "rsa_pss_pss_sha512:rsa_pss_pss_sha256",
},
test => {
"ExpectedServerCertType" => "RSA-PSS",
"ExpectedServerSignHash" => "SHA256",
"ExpectedServerSignType" => "RSA-PSS",
"ExpectedResult" => "Success"
},
},
{
name => "RSA-PSS Restricted Certificate Invalid Signature Algorithms",
server => $server_pss_restrict_only,
client => {
"SignatureAlgorithms" => "rsa_pss_pss_sha512",
},
test => {
"ExpectedResult" => "ServerFail"
},
},
{
name => "RSA key exchange with only RSA-PSS certificate",
server => $server_pss_only,
client => {
"CipherString" => "kRSA",
"MaxProtocol" => "TLSv1.2",
},
test => {
"ExpectedResult" => "ServerFail"
},
},
);
my @tests_tls_1_1 = (
{
name => "Only RSA-PSS Certificate, TLS v1.1",
server => $server_pss_only,
client => {
"MaxProtocol" => "TLSv1.1",
},
test => {
"ExpectedResult" => "ServerFail"
},
},
);
push @tests, @tests_non_fips unless $fips_mode;
push @tests, @tests_pss;
push @tests, @tests_tls_1_1 unless disabled("tls1_1") || $no_deflt_libctx;
my $server_tls_1_3;
if ($fips_mode) {
$server_tls_1_3 = {
"ECDSA.Certificate" => test_pem("server-ecdsa-cert.pem"),
"ECDSA.PrivateKey" => test_pem("server-ecdsa-key.pem"),
"MinProtocol" => "TLSv1.3",
"MaxProtocol" => "TLSv1.3"
};
} else {
$server_tls_1_3 = {
"ECDSA.Certificate" => test_pem("server-ecdsa-cert.pem"),
"ECDSA.PrivateKey" => test_pem("server-ecdsa-key.pem"),
"Ed25519.Certificate" => test_pem("server-ed25519-cert.pem"),
"Ed25519.PrivateKey" => test_pem("server-ed25519-key.pem"),
"Ed448.Certificate" => test_pem("server-ed448-cert.pem"),
"Ed448.PrivateKey" => test_pem("server-ed448-key.pem"),
"MinProtocol" => "TLSv1.3",
"MaxProtocol" => "TLSv1.3"
};
}
my $client_tls_1_3 = {
"RSA.Certificate" => test_pem("ee-client-chain.pem"),
"RSA.PrivateKey" => test_pem("ee-key.pem"),
"ECDSA.Certificate" => test_pem("ee-ecdsa-client-chain.pem"),
"ECDSA.PrivateKey" => test_pem("ee-ecdsa-key.pem"),
"MinProtocol" => "TLSv1.3",
"MaxProtocol" => "TLSv1.3"
};
my @tests_tls_1_3 = (
{
name => "TLS 1.3 ECDSA Signature Algorithm Selection",
server => $server_tls_1_3,
client => {
"SignatureAlgorithms" => "ECDSA+SHA256",
},
test => {
"ExpectedServerCertType" => "P-256",
"ExpectedServerSignHash" => "SHA256",
"ExpectedServerSignType" => "EC",
"ExpectedServerCANames" => "empty",
"ExpectedResult" => "Success"
},
},
{
name => "TLS 1.3 ECDSA Signature Algorithm Selection compressed point",
server => {
"ECDSA.Certificate" => test_pem("server-cecdsa-cert.pem"),
"ECDSA.PrivateKey" => test_pem("server-cecdsa-key.pem"),
"MinProtocol" => "TLSv1.3",
"MaxProtocol" => "TLSv1.3"
},
client => {
"SignatureAlgorithms" => "ECDSA+SHA256",
},
test => {
"ExpectedServerCertType" => "P-256",
"ExpectedServerSignHash" => "SHA256",
"ExpectedServerSignType" => "EC",
"ExpectedServerCANames" => "empty",
"ExpectedResult" => "Success"
},
},
{
name => "TLS 1.3 ECDSA Signature Algorithm Selection SHA1",
server => {
"CipherString" => "DEFAULT:\@SECLEVEL=0",
"ECDSA.Certificate" => test_pem("server-ecdsa-cert.pem"),
"ECDSA.PrivateKey" => test_pem("server-ecdsa-key.pem"),
"Ed25519.Certificate" => test_pem("server-ed25519-cert.pem"),
"Ed25519.PrivateKey" => test_pem("server-ed25519-key.pem"),
"Ed448.Certificate" => test_pem("server-ed448-cert.pem"),
"Ed448.PrivateKey" => test_pem("server-ed448-key.pem"),
"MinProtocol" => "TLSv1.3",
"MaxProtocol" => "TLSv1.3"
},
client => {
"CipherString" => "DEFAULT:\@SECLEVEL=0",
"SignatureAlgorithms" => "ECDSA+SHA1",
},
test => {
"ExpectedResult" => "ServerFail"
},
},
{
name => "TLS 1.3 ECDSA Signature Algorithm Selection with PSS",
server => $server_tls_1_3,
client => {
"SignatureAlgorithms" => "ECDSA+SHA256:RSA-PSS+SHA256",
"RequestCAFile" => test_pem("root-cert.pem"),
},
test => {
"ExpectedServerCertType" => "P-256",
"ExpectedServerSignHash" => "SHA256",
"ExpectedServerSignType" => "EC",
"ExpectedServerCANames" => test_pem("root-cert.pem"),
"ExpectedResult" => "Success"
},
},
{
name => "TLS 1.3 RSA Signature Algorithm Selection SHA384 with PSS",
server => $server_tls_1_3,
client => {
"SignatureAlgorithms" => "ECDSA+SHA384:RSA-PSS+SHA384",
},
test => {
"ExpectedServerCertType" => "RSA",
"ExpectedServerSignHash" => "SHA384",
"ExpectedServerSignType" => "RSA-PSS",
"ExpectedResult" => "Success"
},
},
{
name => "TLS 1.3 ECDSA Signature Algorithm Selection, no ECDSA certificate",
server => {
"MinProtocol" => "TLSv1.3",
"MaxProtocol" => "TLSv1.3"
},
client => {
"SignatureAlgorithms" => "ECDSA+SHA256",
},
test => {
"ExpectedResult" => "ServerFail"
},
},
{
name => "TLS 1.3 RSA Signature Algorithm Selection, no PSS",
server => $server_tls_1_3,
client => {
"SignatureAlgorithms" => "RSA+SHA256",
},
test => {
"ExpectedResult" => "ServerFail"
},
},
{
name => "TLS 1.3 RSA-PSS Signature Algorithm Selection",
server => $server_tls_1_3,
client => {
"SignatureAlgorithms" => "RSA-PSS+SHA256",
},
test => {
"ExpectedServerCertType" => "RSA",
"ExpectedServerSignHash" => "SHA256",
"ExpectedServerSignType" => "RSA-PSS",
"ExpectedResult" => "Success"
},
},
{
name => "TLS 1.3 RSA Client Auth Signature Algorithm Selection",
server => {
"ClientSignatureAlgorithms" => "PSS+SHA256",
"VerifyCAFile" => test_pem("root-cert.pem"),
"VerifyMode" => "Require"
},
client => $client_tls_1_3,
test => {
"ExpectedClientCertType" => "RSA",
"ExpectedClientSignHash" => "SHA256",
"ExpectedClientSignType" => "RSA-PSS",
"ExpectedClientCANames" => "empty",
"ExpectedResult" => "Success"
},
},
{
name => "TLS 1.3 RSA Client Auth Signature Algorithm Selection non-empty CA Names",
server => {
"ClientSignatureAlgorithms" => "PSS+SHA256",
"VerifyCAFile" => test_pem("root-cert.pem"),
"RequestCAFile" => test_pem("root-cert.pem"),
"VerifyMode" => "Require"
},
client => $client_tls_1_3,
test => {
"ExpectedClientCertType" => "RSA",
"ExpectedClientSignHash" => "SHA256",
"ExpectedClientSignType" => "RSA-PSS",
"ExpectedClientCANames" => test_pem("root-cert.pem"),
"ExpectedResult" => "Success"
},
},
{
name => "TLS 1.3 ECDSA Client Auth Signature Algorithm Selection",
server => {
"ClientSignatureAlgorithms" => "ECDSA+SHA256",
"VerifyCAFile" => test_pem("root-cert.pem"),
"VerifyMode" => "Require"
},
client => $client_tls_1_3,
test => {
"ExpectedClientCertType" => "P-256",
"ExpectedClientSignHash" => "SHA256",
"ExpectedClientSignType" => "EC",
"ExpectedResult" => "Success"
},
},
);
my @tests_tls_1_3_non_fips = (
{
name => "TLS 1.3 Ed25519 Signature Algorithm Selection",
server => $server_tls_1_3,
client => {
"SignatureAlgorithms" => "ed25519",
},
test => {
"ExpectedServerCertType" => "Ed25519",
"ExpectedServerSignType" => "Ed25519",
"ExpectedResult" => "Success"
},
},
{
name => "TLS 1.3 Ed448 Signature Algorithm Selection",
server => $server_tls_1_3,
client => {
"SignatureAlgorithms" => "ed448",
"VerifyCAFile" => test_pem("root-ed448-cert.pem"),
},
test => {
"ExpectedServerCertType" => "Ed448",
"ExpectedServerSignType" => "Ed448",
"ExpectedResult" => "Success"
},
},
{
name => "TLS 1.3 Ed25519 CipherString and Groups Selection",
server => $server_tls_1_3,
client => {
"SignatureAlgorithms" => "ECDSA+SHA256:ed25519",
# Excluding P-256 from the supported groups list should
# mean server still uses a P-256 certificate because supported
# groups is not used in signature selection for TLS 1.3
"Groups" => "X25519"
},
test => {
"ExpectedServerCertType" =>, "P-256",
"ExpectedServerSignType" =>, "EC",
"ExpectedResult" => "Success"
},
},
{
name => "TLS 1.3 Ed448 CipherString and Groups Selection",
server => $server_tls_1_3,
client => {
"SignatureAlgorithms" => "ECDSA+SHA256:ed448",
# Excluding P-256 from the supported groups list should
# mean server still uses a P-256 certificate because supported
# groups is not used in signature selection for TLS 1.3
"Groups" => "X448"
},
test => {
"ExpectedServerCertType" =>, "P-256",
"ExpectedServerSignType" =>, "EC",
"ExpectedResult" => "Success"
},
},
{
name => "TLS 1.3 Ed25519 Client Auth",
server => {
"VerifyCAFile" => test_pem("root-cert.pem"),
"VerifyMode" => "Require"
},
client => {
"EdDSA.Certificate" => test_pem("client-ed25519-cert.pem"),
"EdDSA.PrivateKey" => test_pem("client-ed25519-key.pem"),
"MinProtocol" => "TLSv1.3",
"MaxProtocol" => "TLSv1.3"
},
test => {
"ExpectedClientCertType" => "Ed25519",
"ExpectedClientSignType" => "Ed25519",
"ExpectedResult" => "Success"
},
},
{
name => "TLS 1.3 Ed448 Client Auth",
server => {
"VerifyCAFile" => test_pem("root-cert.pem"),
"VerifyMode" => "Require"
},
client => {
"EdDSA.Certificate" => test_pem("client-ed448-cert.pem"),
"EdDSA.PrivateKey" => test_pem("client-ed448-key.pem"),
"MinProtocol" => "TLSv1.3",
"MaxProtocol" => "TLSv1.3"
},
test => {
"ExpectedClientCertType" => "Ed448",
"ExpectedClientSignType" => "Ed448",
"ExpectedResult" => "Success"
},
},
{
name => "TLS 1.3 ECDSA with brainpool but no suitable groups",
server => {
"Certificate" => test_pem("server-ecdsa-brainpoolP256r1-cert.pem"),
"PrivateKey" => test_pem("server-ecdsa-brainpoolP256r1-key.pem"),
"Groups" => "brainpoolP256r1",
},
client => {
"CipherString" => "aECDSA",
"RequestCAFile" => test_pem("root-cert.pem"),
"Groups" => "brainpoolP256r1",
},
test => {
#We only configured brainpoolP256r1 on the client side, but TLSv1.3
#is enabled and this group is not allowed in TLSv1.3. Therefore this
#should fail
"ExpectedResult" => "ClientFail"
},
},
{
name => "TLS 1.3 ECDSA with brainpool",
server => {
"Certificate" => test_pem("server-ecdsa-brainpoolP256r1-cert.pem"),
"PrivateKey" => test_pem("server-ecdsa-brainpoolP256r1-key.pem"),
},
client => {
"RequestCAFile" => test_pem("root-cert.pem"),
"MinProtocol" => "TLSv1.3",
"MaxProtocol" => "TLSv1.3"
},
test => {
"ExpectedResult" => "ServerFail"
},
},
);
push @tests, @tests_tls_1_3 unless disabled("tls1_3");
push @tests, @tests_tls_1_3_non_fips unless disabled("tls1_3") || $fips_mode;
my @tests_dsa_tls_1_2 = (
{
name => "TLS 1.2 DSA Certificate Test",
server => {
"DSA.Certificate" => test_pem("server-dsa-cert.pem"),
"DSA.PrivateKey" => test_pem("server-dsa-key.pem"),
"DHParameters" => test_pem("dhp2048.pem"),
"MinProtocol" => "TLSv1.2",
"MaxProtocol" => "TLSv1.2",
"CipherString" => "ALL",
},
client => {
"SignatureAlgorithms" => "DSA+SHA256:DSA+SHA1",
"CipherString" => "ALL",
},
test => {
"ExpectedResult" => "Success"
},
},
);
my @tests_dsa_tls_1_3 = (
{
name => "TLS 1.3 Client Auth No TLS 1.3 Signature Algorithms",
server => {
"ClientSignatureAlgorithms" => "ECDSA+SHA1:DSA+SHA256:RSA+SHA256",
"VerifyCAFile" => test_pem("root-cert.pem"),
"VerifyMode" => "Request"
},
client => {},
test => {
"ExpectedResult" => "ServerFail"
},
},
{
name => "TLS 1.3 DSA Certificate Test",
server => {
"DSA.Certificate" => test_pem("server-dsa-cert.pem"),
"DSA.PrivateKey" => test_pem("server-dsa-key.pem"),
"MinProtocol" => "TLSv1.3",
"MaxProtocol" => "TLSv1.3",
"CipherString" => "ALL",
},
client => {
"SignatureAlgorithms" => "DSA+SHA1:DSA+SHA256:ECDSA+SHA256",
"CipherString" => "ALL",
},
test => {
"ExpectedResult" => "ServerFail"
},
},
);
if (!disabled("dsa")) {
push @tests, @tests_dsa_tls_1_2 unless disabled("dh");
push @tests, @tests_dsa_tls_1_3 unless disabled("tls1_3");
}
diff --git a/crypto/openssl/test/ssl-tests/28-seclevel.cnf.in b/crypto/openssl/test/ssl-tests/28-seclevel.cnf.in
index 945f4599d10e..3b97ac68eb3a 100644
--- a/crypto/openssl/test/ssl-tests/28-seclevel.cnf.in
+++ b/crypto/openssl/test/ssl-tests/28-seclevel.cnf.in
@@ -1,85 +1,89 @@
# -*- mode: perl; -*-
-# Copyright 2016-2021 The OpenSSL Project Authors. All Rights Reserved.
+# Copyright 2016-2024 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
## SSL test configurations
package ssltests;
use OpenSSL::Test::Utils;
our $fips_mode;
our @tests = (
{
name => "SECLEVEL 3 with default key",
server => { "CipherString" => "DEFAULT:\@SECLEVEL=3" },
client => { },
test => { "ExpectedResult" => "ServerFail" },
},
);
our @tests_ec = (
{
name => "SECLEVEL 4 with ED448 key",
server => { "CipherString" => "DEFAULT:\@SECLEVEL=4",
"Certificate" => test_pem("server-ed448-cert.pem"),
"PrivateKey" => test_pem("server-ed448-key.pem") },
client => { "CipherString" => "DEFAULT:\@SECLEVEL=4",
"VerifyCAFile" => test_pem("root-ed448-cert.pem") },
test => { "ExpectedResult" => "Success" },
},
{
# The Ed448 signature algorithm will not be enabled.
# Because of the config order, the certificate is first loaded, and
# then the security level is chaged. If you try this with s_server
# the order will be reversed and it will instead fail to load the key.
name => "SECLEVEL 5 server with ED448 key",
server => { "CipherString" => "DEFAULT:\@SECLEVEL=5",
"Certificate" => test_pem("server-ed448-cert.pem"),
"PrivateKey" => test_pem("server-ed448-key.pem") },
client => { "CipherString" => "DEFAULT:\@SECLEVEL=4",
"VerifyCAFile" => test_pem("root-ed448-cert.pem") },
test => { "ExpectedResult" => "ServerFail" },
},
{
# The client will not sent the Ed448 signature algorithm, so the server
# doesn't have a useable signature algorithm for the certificate.
name => "SECLEVEL 5 client with ED448 key",
server => { "CipherString" => "DEFAULT:\@SECLEVEL=4",
"Certificate" => test_pem("server-ed448-cert.pem"),
"PrivateKey" => test_pem("server-ed448-key.pem") },
client => { "CipherString" => "DEFAULT:\@SECLEVEL=5",
"VerifyCAFile" => test_pem("root-ed448-cert.pem") },
test => { "ExpectedResult" => "ServerFail" },
- },
+ }
+);
+
+our @tests_ec_non_fips = (
{
name => "SECLEVEL 3 with P-384 key, X25519 ECDHE",
server => { "CipherString" => "DEFAULT:\@SECLEVEL=3",
"Certificate" => test_pem("p384-server-cert.pem"),
"PrivateKey" => test_pem("p384-server-key.pem"),
"Groups" => "X25519" },
client => { "CipherString" => "ECDHE:\@SECLEVEL=3",
"VerifyCAFile" => test_pem("p384-root.pem") },
test => { "ExpectedResult" => "Success" },
},
);
our @tests_tls1_2 = (
{
name => "SECLEVEL 3 with ED448 key, TLSv1.2",
server => { "CipherString" => "DEFAULT:\@SECLEVEL=3",
"Certificate" => test_pem("server-ed448-cert.pem"),
"PrivateKey" => test_pem("server-ed448-key.pem"),
"MaxProtocol" => "TLSv1.2" },
client => { "VerifyCAFile" => test_pem("root-ed448-cert.pem") },
test => { "ExpectedResult" => "Success" },
},
);
+push @tests_ec, @tests_ec_non_fips unless $fips_mode;
push @tests, @tests_ec unless disabled("ec");
push @tests, @tests_tls1_2 unless disabled("tls1_2") || disabled("ec");
diff --git a/crypto/openssl/test/sslapitest.c b/crypto/openssl/test/sslapitest.c
index e0274f12f7cc..2b1c2fded322 100644
--- a/crypto/openssl/test/sslapitest.c
+++ b/crypto/openssl/test/sslapitest.c
@@ -1,10749 +1,11075 @@
/*
- * Copyright 2016-2023 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2016-2024 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 <stdio.h>
#include <string.h>
#include <openssl/opensslconf.h>
#include <openssl/bio.h>
#include <openssl/crypto.h>
#include <openssl/ssl.h>
#include <openssl/ocsp.h>
#include <openssl/srp.h>
#include <openssl/txt_db.h>
#include <openssl/aes.h>
#include <openssl/rand.h>
#include <openssl/core_names.h>
#include <openssl/core_dispatch.h>
#include <openssl/provider.h>
#include <openssl/param_build.h>
#include <openssl/x509v3.h>
#include <openssl/dh.h>
#include <openssl/engine.h>
#include "helpers/ssltestlib.h"
#include "testutil.h"
#include "testutil/output.h"
#include "internal/nelem.h"
#include "internal/ktls.h"
#include "../ssl/ssl_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 SSL_SESSION *create_a_psk(SSL *ssl, size_t mdsize);
#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 int is_fips = 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 NUM_EXTRA_CERTS 40
#define CLIENT_VERSION_LEN 2
/*
* 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) {
sprintf(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;
/* We only configure two ciphers, but the SCSV is added automatically. */
#ifdef OPENSSL_NO_EC
const unsigned char expected_ciphers[] = {0x00, 0x9d, 0x00, 0xff};
#else
const unsigned char expected_ciphers[] = {0x00, 0x9d, 0xc0,
0x2c, 0x00, 0xff};
#endif
const int expected_extensions[] = {
#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);
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;
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;
}
if (!create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)) {
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 conection 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 add_large_cert_chain(SSL_CTX *sctx)
{
BIO *certbio = NULL;
X509 *chaincert = NULL;
int certlen;
int ret = 0;
int i;
if (!TEST_ptr(certbio = BIO_new_file(cert, "r")))
goto end;
if (!TEST_ptr(chaincert = X509_new_ex(libctx, NULL)))
goto end;
if (PEM_read_bio_X509(certbio, &chaincert, NULL, NULL) == NULL)
goto end;
BIO_free(certbio);
certbio = NULL;
/*
* We assume the supplied certificate is big enough so that if we add
* NUM_EXTRA_CERTS it will make the overall message large enough. The
* default buffer size is requested to be 16k, but due to the way BUF_MEM
* works, it ends up allocating a little over 21k (16 * 4/3). So, in this
* test we need to have a message larger than that.
*/
certlen = i2d_X509(chaincert, NULL);
OPENSSL_assert(certlen * NUM_EXTRA_CERTS >
(SSL3_RT_MAX_PLAIN_LENGTH * 4) / 3);
for (i = 0; i < NUM_EXTRA_CERTS; i++) {
if (!X509_up_ref(chaincert))
goto end;
if (!SSL_CTX_add_extra_chain_cert(sctx, chaincert)) {
X509_free(chaincert);
goto end;
}
}
ret = 1;
end:
BIO_free(certbio);
X509_free(chaincert);
return ret;
}
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 <DTLS1.2 which is in security
* level 0
*/
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;
}
#endif
if (read_ahead) {
/*
* Test that read_ahead works correctly when dealing with large
* records
*/
SSL_CTX_set_read_ahead(cctx, 1);
}
if (!add_large_cert_chain(sctx))
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;
/*
* Calling SSL_clear() first is not required but this tests that SSL_clear()
* doesn't leak.
*/
if (!TEST_true(SSL_clear(serverssl)))
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_SOCK) && !defined(OPENSSL_NO_KTLS) && \
!(defined(OSSL_NO_USABLE_TLS1_3) && defined(OPENSSL_NO_TLS1_2))
/* sock must be connected */
static int ktls_chk_platform(int sock)
{
if (!ktls_enable(sock))
return 0;
return 1;
}
static int ping_pong_query(SSL *clientssl, SSL *serverssl)
{
static char count = 1;
unsigned char cbuf[16000] = {0};
unsigned char sbuf[16000];
size_t err = 0;
char crec_wseq_before[SEQ_NUM_SIZE];
char crec_wseq_after[SEQ_NUM_SIZE];
char crec_rseq_before[SEQ_NUM_SIZE];
char crec_rseq_after[SEQ_NUM_SIZE];
char srec_wseq_before[SEQ_NUM_SIZE];
char srec_wseq_after[SEQ_NUM_SIZE];
char srec_rseq_before[SEQ_NUM_SIZE];
char srec_rseq_after[SEQ_NUM_SIZE];
cbuf[0] = count++;
memcpy(crec_wseq_before, &clientssl->rlayer.write_sequence, SEQ_NUM_SIZE);
memcpy(crec_rseq_before, &clientssl->rlayer.read_sequence, SEQ_NUM_SIZE);
memcpy(srec_wseq_before, &serverssl->rlayer.write_sequence, SEQ_NUM_SIZE);
memcpy(srec_rseq_before, &serverssl->rlayer.read_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, &clientssl->rlayer.write_sequence, SEQ_NUM_SIZE);
memcpy(crec_rseq_after, &clientssl->rlayer.read_sequence, SEQ_NUM_SIZE);
memcpy(srec_wseq_after, &serverssl->rlayer.write_sequence, SEQ_NUM_SIZE);
memcpy(srec_rseq_after, &serverssl->rlayer.read_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(clientssl->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(serverssl->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(clientssl->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(serverssl->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;
if (!TEST_true(create_test_sockets(&cfd, &sfd)))
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 (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(clientssl->wbio)))
goto end;
} else {
if (BIO_get_ktls_send(clientssl->wbio))
ktls_used = 1;
}
if (!sis_ktls) {
if (!TEST_false(BIO_get_ktls_send(serverssl->wbio)))
goto end;
} else {
if (BIO_get_ktls_send(serverssl->wbio))
ktls_used = 1;
}
#if defined(OPENSSL_NO_KTLS_RX)
rx_supported = 0;
#else
rx_supported = (tls_version != TLS1_3_VERSION);
#endif
if (!cis_ktls || !rx_supported) {
if (!TEST_false(BIO_get_ktls_recv(clientssl->rbio)))
goto end;
} else {
if (BIO_get_ktls_send(clientssl->rbio))
ktls_used = 1;
}
if (!sis_ktls || !rx_supported) {
if (!TEST_false(BIO_get_ktls_recv(serverssl->rbio)))
goto end;
} else {
if (BIO_get_ktls_send(serverssl->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;
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;
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)
{
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;
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)))
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_true(SSL_set_options(serverssl, SSL_OP_ENABLE_KTLS)))
goto end;
if (!TEST_true(create_ssl_connection(serverssl, clientssl,
SSL_ERROR_NONE)))
goto end;
if (!BIO_get_ktls_send(serverssl->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 \
(sizeof(ktls_test_ciphers) / sizeof(ktls_test_ciphers[0]))
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 tst)
{
struct ktls_test_cipher *cipher;
OPENSSL_assert(tst < (int)NUM_KTLS_TEST_CIPHERS);
cipher = &ktls_test_ciphers[tst];
return execute_test_ktls_sendfile(cipher->tls_version, cipher->cipher);
}
#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 1;
#endif
case 1:
#ifndef OPENSSL_NO_TLS1_2
prot = TLS1_2_VERSION;
break;
#else
return 1;
#endif
case 2:
#ifndef OPENSSL_NO_TLS1_1
prot = TLS1_1_VERSION;
break;
#else
return 1;
#endif
case 3:
#ifndef OPENSSL_NO_TLS1
prot = TLS1_VERSION;
break;
#else
return 1;
#endif
case 4:
#ifndef OPENSSL_NO_SSL3
prot = SSL3_VERSION;
break;
#else
return 1;
#endif
case 5:
#ifndef OPENSSL_NO_DTLS1_2
prot = DTLS1_2_VERSION;
smeth = DTLS_server_method();
cmeth = DTLS_client_method();
break;
#else
return 1;
#endif
case 6:
#ifndef OPENSSL_NO_DTLS1
prot = DTLS1_VERSION;
smeth = DTLS_server_method();
cmeth = DTLS_client_method();
break;
#else
return 1;
#endif
default:
/* Shouldn't happen */
return 0;
}
if ((prot < TLS1_2_VERSION || prot == DTLS1_VERSION) && is_fips)
return 1;
/* 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;
SSL3_RECORD *rr;
void *zbuf;
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 <DTLS1.2 which is in security
* level 0
*/
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;
}
# endif
if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
NULL, NULL)))
goto end;
if (!TEST_true(SSL_set_options(serverssl, SSL_OP_CLEANSE_PLAINTEXT)))
goto end;
if (!TEST_true(create_ssl_connection(serverssl, clientssl,
SSL_ERROR_NONE)))
goto end;
for (i = 0; i < sizeof(cbuf); i++) {
cbuf[i] = i & 0xff;
}
if (!TEST_int_eq(SSL_write(clientssl, cbuf, sizeof(cbuf)), sizeof(cbuf)))
goto end;
if (!TEST_int_eq(SSL_peek(serverssl, &sbuf, sizeof(sbuf)), sizeof(sbuf)))
goto end;
if (!TEST_mem_eq(cbuf, sizeof(cbuf), sbuf, sizeof(sbuf)))
goto end;
/*
* Since we called SSL_peek(), we know the data in the record
* layer is a plaintext record. We can gather the pointer to check
* for zeroization after SSL_read().
*/
rr = serverssl->rlayer.rrec;
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_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 (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_long_gt(SSL_SESSION_set_time(sess1, 1000), 0)
|| !TEST_long_gt(SSL_SESSION_set_timeout(sess1, 1000), 0)
|| !TEST_long_gt(SSL_SESSION_set_time(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))
goto end;
SSL_SESSION_up_ref(clientpsk);
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);
if (iwbio != NULL && iwbio != irbio)
BIO_up_ref(iwbio);
}
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))
BIO_up_ref(nrbio);
if (nwbio != NULL
&& nwbio != nrbio
&& (nwbio != iwbio || (nwbio == iwbio && irbio == iwbio)))
BIO_up_ref(nwbio);
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},
# 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);
*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;
}
SSL_SESSION_up_ref(serverpsk);
*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."
#define TLS13_AES_128_GCM_SHA256_BYTES ((const unsigned char *)"\x13\x01")
#define TLS13_AES_256_GCM_SHA384_BYTES ((const unsigned char *)"\x13\x02")
#define TLS13_CHACHA20_POLY1305_SHA256_BYTES ((const unsigned char *)"\x13\x03")
#define TLS13_AES_128_CCM_SHA256_BYTES ((const unsigned char *)"\x13\x04")
#define TLS13_AES_128_CCM_8_SHA256_BYTES ((const unsigned char *)"\x13\05")
static SSL_SESSION *create_a_psk(SSL *ssl, size_t mdsize)
{
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 /* SHA384_DIGEST_LENGTH bytes */
};
SSL_SESSION *sess = NULL;
if (mdsize == SHA384_DIGEST_LENGTH) {
cipher = SSL_CIPHER_find(ssl, TLS13_AES_256_GCM_SHA384_BYTES);
} else if (mdsize == SHA256_DIGEST_LENGTH) {
/*
* Any ciphersuite using SHA256 will do - it will be compatible with
* the actual ciphersuite selected as long as it too is based on SHA256
*/
cipher = SSL_CIPHER_find(ssl, TLS13_AES_128_GCM_SHA256_BYTES);
} else {
/* Should not happen */
return NULL;
}
sess = SSL_SESSION_new();
if (!TEST_ptr(sess)
|| !TEST_ptr(cipher)
|| !TEST_true(SSL_SESSION_set1_master_key(sess, key, mdsize))
|| !TEST_true(SSL_SESSION_set_cipher(sess, cipher))
|| !TEST_true(
SSL_SESSION_set_protocol_version(sess,
TLS1_3_VERSION))) {
SSL_SESSION_free(sess);
return NULL;
}
return 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)
{
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 (!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;
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(time_t 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 = time(NULL) - timer;
+ if (timer >= 7)
+ 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;
+ time_t timer;
if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
&serverssl, &sess, idx,
SHA384_DIGEST_LENGTH)))
goto end;
/* Write and read some early data */
+ timer = time(NULL);
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(MSG1, readbytes, buf, strlen(MSG1))
+ || !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];
+ time_t 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 = time(NULL);
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)
- || !TEST_mem_eq(MSG1, strlen(MSG1), 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"
#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 (!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) {
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 ? 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-256")))
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(sess, (long)(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 {
+ time_t timer = time(NULL);
+
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)
- || (readearlyres == SSL_READ_EARLY_DATA_SUCCESS
+ &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 5 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
*/
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;
+ time_t 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
};
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 (cipher_str[idx] == NULL)
return 1;
/* Skip ChaCha20Poly1305 as currently FIPS module does not support it */
if (idx == 2 && 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 (!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 = time(NULL);
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)
- || !TEST_mem_eq(buf, readbytes, MSG1, strlen(MSG1))
+ 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"))
|| !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 ECDHE with TLSv1.2 client and server
* Test 13 = Test all FFDHE with TLSv1.2 client and server
*/
# ifndef OPENSSL_NO_EC
static int ecdhe_kexch_groups[] = {NID_X9_62_prime256v1, NID_secp384r1,
NID_secp521r1, NID_X25519, NID_X448};
# 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;
int *kexch_groups = &kexch_alg;
int kexch_groups_size = 1;
int max_version = TLS1_3_VERSION;
char *kexch_name0 = NULL;
switch (idx) {
# ifndef OPENSSL_NO_EC
# ifndef OPENSSL_NO_TLS1_2
case 12:
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;
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
# ifndef OPENSSL_NO_DH
# ifndef OPENSSL_NO_TLS1_2
case 13:
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
default:
/* We're skipping this test */
return 1;
}
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 (!TEST_true(SSL_set1_groups(serverssl, kexch_groups, kexch_groups_size))
|| !TEST_true(SSL_set1_groups(clientssl, kexch_groups, kexch_groups_size)))
goto end;
if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
goto end;
/*
* If Handshake succeeds the negotiated kexch alg should be the first one in
* configured, except in the case of FFDHE groups (idx 13), which are
* TLSv1.3 only so we expect no shared group to exist.
*/
if (!TEST_int_eq(SSL_get_shared_group(serverssl, 0),
idx == 13 ? 0 : kexch_groups[0]))
goto end;
if (!TEST_str_eq(SSL_group_to_name(serverssl, kexch_groups[0]),
kexch_name0))
goto end;
/* We don't implement RFC 7919 named groups for TLS 1.2. */
if (idx != 13) {
if (!TEST_int_eq(SSL_get_negotiated_group(serverssl), kexch_groups[0]))
goto end;
if (!TEST_int_eq(SSL_get_negotiated_group(clientssl), kexch_groups[0]))
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(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;
} t13_ciphers[] = {
{ TLS1_3_RFC_AES_128_GCM_SHA256, 1 },
{ TLS1_3_RFC_AES_256_GCM_SHA384, 1 },
{ TLS1_3_RFC_AES_128_CCM_SHA256, 1 },
# if !defined(OPENSSL_NO_CHACHA) && !defined(OPENSSL_NO_POLY1305)
{ TLS1_3_RFC_CHACHA20_POLY1305_SHA256, 0 },
{ TLS1_3_RFC_AES_256_GCM_SHA384
":" TLS1_3_RFC_CHACHA20_POLY1305_SHA256, 0 },
# endif
{ TLS1_3_RFC_AES_128_CCM_8_SHA256 ":" TLS1_3_RFC_AES_128_CCM_SHA256, 1 }
};
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 (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-256")))
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;
}
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 ckeymat1[80], ckeymat2[80], ckeymat3[80];
unsigned char skeymat1[80], skeymat2[80], skeymat3[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;
}
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_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)
/*
* 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))
/* 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))
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))
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;
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 */
static int test_ssl_clear(int idx)
{
SSL_CTX *cctx = NULL, *sctx = NULL;
SSL *clientssl = NULL, *serverssl = NULL;
int testresult = 0;
#ifdef OPENSSL_NO_TLS1_2
if (idx == 1)
return 1;
#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))
|| (idx == 1
&& !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;
SSL_shutdown(clientssl);
SSL_shutdown(serverssl);
SSL_free(serverssl);
serverssl = NULL;
/* Clear clientssl - we're going to reuse the object */
if (!TEST_true(SSL_clear(clientssl)))
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_true(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},
}, {
{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
*/
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) {
SSL_SESSION *sess = NULL;
size_t written, readbytes;
unsigned char buf[80];
+ time_t 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 = time(NULL);
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(MSG1, readbytes, buf, strlen(MSG1))
+ || !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 (!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 <DTLS1.2 which is in security
* level 0
*/
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;
# endif
#else
return 1;
#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;
if (!TEST_int_eq(SSL_pending(clientssl), 0)
|| !TEST_false(SSL_has_pending(clientssl))
|| !TEST_int_eq(SSL_pending(serverssl), 0)
|| !TEST_false(SSL_has_pending(serverssl))
|| !TEST_true(SSL_write_ex(serverssl, msg, sizeof(msg), &written))
|| !TEST_size_t_eq(written, sizeof(msg))
|| !TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes))
|| !TEST_size_t_eq(readbytes, sizeof(buf))
|| !TEST_int_eq(SSL_pending(clientssl), (int)(written - readbytes))
|| !TEST_true(SSL_has_pending(clientssl)))
goto end;
testresult = 1;
end:
SSL_free(serverssl);
SSL_free(clientssl);
SSL_CTX_free(sctx);
SSL_CTX_free(cctx);
return testresult;
}
static struct {
unsigned int maxprot;
const char *clntciphers;
const char *clnttls13ciphers;
const char *srvrciphers;
const char *srvrtls13ciphers;
const char *shared;
const char *fipsshared;
} shared_ciphers_data[] = {
/*
* We can't establish a connection (even in TLSv1.1) with these ciphersuites if
* TLSv1.3 is enabled but TLSv1.2 is disabled.
*/
#if defined(OSSL_NO_USABLE_TLS1_3) || !defined(OPENSSL_NO_TLS1_2)
{
TLS1_2_VERSION,
"AES128-SHA:AES256-SHA",
NULL,
"AES256-SHA:DHE-RSA-AES128-SHA",
NULL,
"AES256-SHA",
"AES256-SHA"
},
# if !defined(OPENSSL_NO_CHACHA) \
&& !defined(OPENSSL_NO_POLY1305) \
&& !defined(OPENSSL_NO_EC)
{
TLS1_2_VERSION,
"AES128-SHA:ECDHE-RSA-CHACHA20-POLY1305",
NULL,
"AES128-SHA:ECDHE-RSA-CHACHA20-POLY1305",
NULL,
"AES128-SHA:ECDHE-RSA-CHACHA20-POLY1305",
"AES128-SHA"
},
# endif
{
TLS1_2_VERSION,
"AES128-SHA:DHE-RSA-AES128-SHA:AES256-SHA",
NULL,
"AES128-SHA:DHE-RSA-AES256-SHA:AES256-SHA",
NULL,
"AES128-SHA:AES256-SHA",
"AES128-SHA:AES256-SHA"
},
{
TLS1_2_VERSION,
"AES128-SHA:AES256-SHA",
NULL,
"AES128-SHA:DHE-RSA-AES128-SHA",
NULL,
"AES128-SHA",
"AES128-SHA"
},
#endif
/*
* This test combines TLSv1.3 and TLSv1.2 ciphersuites so they must both be
* enabled.
*/
#if !defined(OSSL_NO_USABLE_TLS1_3) && !defined(OPENSSL_NO_TLS1_2) \
&& !defined(OPENSSL_NO_CHACHA) && !defined(OPENSSL_NO_POLY1305)
{
TLS1_3_VERSION,
"AES128-SHA:AES256-SHA",
NULL,
"AES256-SHA:AES128-SHA256",
NULL,
"TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_SHA256:"
"TLS_AES_128_GCM_SHA256:AES256-SHA",
"TLS_AES_256_GCM_SHA384:TLS_AES_128_GCM_SHA256:AES256-SHA"
},
#endif
#ifndef OSSL_NO_USABLE_TLS1_3
{
TLS1_3_VERSION,
"AES128-SHA",
"TLS_AES_256_GCM_SHA384",
"AES256-SHA",
"TLS_AES_256_GCM_SHA384",
"TLS_AES_256_GCM_SHA384",
"TLS_AES_256_GCM_SHA384"
},
#endif
};
static int int_test_ssl_get_shared_ciphers(int tst, int clnt)
{
SSL_CTX *cctx = NULL, *sctx = NULL;
SSL *clientssl = NULL, *serverssl = NULL;
int testresult = 0;
char buf[1024];
OSSL_LIB_CTX *tmplibctx = OSSL_LIB_CTX_new();
if (!TEST_ptr(tmplibctx))
goto end;
/*
* Regardless of whether we're testing with the FIPS provider loaded into
* libctx, we want one peer to always use the full set of ciphersuites
* available. Therefore we use a separate libctx with the default provider
* loaded into it. We run the same tests twice - once with the client side
* having the full set of ciphersuites and once with the server side.
*/
if (clnt) {
cctx = SSL_CTX_new_ex(tmplibctx, NULL, TLS_client_method());
if (!TEST_ptr(cctx))
goto end;
} else {
sctx = SSL_CTX_new_ex(tmplibctx, NULL, TLS_server_method());
if (!TEST_ptr(sctx))
goto end;
}
if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
TLS_client_method(),
TLS1_VERSION,
shared_ciphers_data[tst].maxprot,
&sctx, &cctx, cert, privkey)))
goto end;
if (!TEST_true(SSL_CTX_set_cipher_list(cctx,
shared_ciphers_data[tst].clntciphers))
|| (shared_ciphers_data[tst].clnttls13ciphers != NULL
&& !TEST_true(SSL_CTX_set_ciphersuites(cctx,
shared_ciphers_data[tst].clnttls13ciphers)))
|| !TEST_true(SSL_CTX_set_cipher_list(sctx,
shared_ciphers_data[tst].srvrciphers))
|| (shared_ciphers_data[tst].srvrtls13ciphers != NULL
&& !TEST_true(SSL_CTX_set_ciphersuites(sctx,
shared_ciphers_data[tst].srvrtls13ciphers))))
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 (!TEST_ptr(SSL_get_shared_ciphers(serverssl, buf, sizeof(buf)))
|| !TEST_int_eq(strcmp(buf,
is_fips
? shared_ciphers_data[tst].fipsshared
: shared_ciphers_data[tst].shared),
0)) {
TEST_info("Shared ciphers are: %s\n", buf);
goto end;
}
testresult = 1;
end:
SSL_free(serverssl);
SSL_free(clientssl);
SSL_CTX_free(sctx);
SSL_CTX_free(cctx);
OSSL_LIB_CTX_free(tmplibctx);
return testresult;
}
static int test_ssl_get_shared_ciphers(int tst)
{
return int_test_ssl_get_shared_ciphers(tst, 0)
&& int_test_ssl_get_shared_ciphers(tst, 1);
}
static const char *appdata = "Hello World";
static int gen_tick_called, dec_tick_called, tick_key_cb_called;
static int tick_key_renew = 0;
static SSL_TICKET_RETURN tick_dec_ret = SSL_TICKET_RETURN_ABORT;
static int gen_tick_cb(SSL *s, void *arg)
{
gen_tick_called = 1;
return SSL_SESSION_set1_ticket_appdata(SSL_get_session(s), appdata,
strlen(appdata));
}
static SSL_TICKET_RETURN dec_tick_cb(SSL *s, SSL_SESSION *ss,
const unsigned char *keyname,
size_t keyname_length,
SSL_TICKET_STATUS status,
void *arg)
{
void *tickdata;
size_t tickdlen;
dec_tick_called = 1;
if (status == SSL_TICKET_EMPTY)
return SSL_TICKET_RETURN_IGNORE_RENEW;
if (!TEST_true(status == SSL_TICKET_SUCCESS
|| status == SSL_TICKET_SUCCESS_RENEW))
return SSL_TICKET_RETURN_ABORT;
if (!TEST_true(SSL_SESSION_get0_ticket_appdata(ss, &tickdata,
&tickdlen))
|| !TEST_size_t_eq(tickdlen, strlen(appdata))
|| !TEST_int_eq(memcmp(tickdata, appdata, tickdlen), 0))
return SSL_TICKET_RETURN_ABORT;
if (tick_key_cb_called) {
/* Don't change what the ticket key callback wanted to do */
switch (status) {
case SSL_TICKET_NO_DECRYPT:
return SSL_TICKET_RETURN_IGNORE_RENEW;
case SSL_TICKET_SUCCESS:
return SSL_TICKET_RETURN_USE;
case SSL_TICKET_SUCCESS_RENEW:
return SSL_TICKET_RETURN_USE_RENEW;
default:
return SSL_TICKET_RETURN_ABORT;
}
}
return tick_dec_ret;
}
#ifndef OPENSSL_NO_DEPRECATED_3_0
static int tick_key_cb(SSL *s, unsigned char key_name[16],
unsigned char iv[EVP_MAX_IV_LENGTH], EVP_CIPHER_CTX *ctx,
HMAC_CTX *hctx, int enc)
{
const unsigned char tick_aes_key[16] = "0123456789abcdef";
const unsigned char tick_hmac_key[16] = "0123456789abcdef";
EVP_CIPHER *aes128cbc;
EVP_MD *sha256;
int ret;
tick_key_cb_called = 1;
if (tick_key_renew == -1)
return 0;
aes128cbc = EVP_CIPHER_fetch(libctx, "AES-128-CBC", NULL);
if (!TEST_ptr(aes128cbc))
return 0;
sha256 = EVP_MD_fetch(libctx, "SHA-256", NULL);
if (!TEST_ptr(sha256)) {
EVP_CIPHER_free(aes128cbc);
return 0;
}
memset(iv, 0, AES_BLOCK_SIZE);
memset(key_name, 0, 16);
if (aes128cbc == NULL
|| sha256 == NULL
|| !EVP_CipherInit_ex(ctx, aes128cbc, NULL, tick_aes_key, iv, enc)
|| !HMAC_Init_ex(hctx, tick_hmac_key, sizeof(tick_hmac_key), sha256,
NULL))
ret = -1;
else
ret = tick_key_renew ? 2 : 1;
EVP_CIPHER_free(aes128cbc);
EVP_MD_free(sha256);
return ret;
}
#endif
static int tick_key_evp_cb(SSL *s, unsigned char key_name[16],
unsigned char iv[EVP_MAX_IV_LENGTH],
EVP_CIPHER_CTX *ctx, EVP_MAC_CTX *hctx, int enc)
{
const unsigned char tick_aes_key[16] = "0123456789abcdef";
unsigned char tick_hmac_key[16] = "0123456789abcdef";
OSSL_PARAM params[2];
EVP_CIPHER *aes128cbc;
int ret;
tick_key_cb_called = 1;
if (tick_key_renew == -1)
return 0;
aes128cbc = EVP_CIPHER_fetch(libctx, "AES-128-CBC", NULL);
if (!TEST_ptr(aes128cbc))
return 0;
memset(iv, 0, AES_BLOCK_SIZE);
memset(key_name, 0, 16);
params[0] = OSSL_PARAM_construct_utf8_string(OSSL_MAC_PARAM_DIGEST,
"SHA256", 0);
params[1] = OSSL_PARAM_construct_end();
if (aes128cbc == NULL
|| !EVP_CipherInit_ex(ctx, aes128cbc, NULL, tick_aes_key, iv, enc)
|| !EVP_MAC_init(hctx, tick_hmac_key, sizeof(tick_hmac_key),
params))
ret = -1;
else
ret = tick_key_renew ? 2 : 1;
EVP_CIPHER_free(aes128cbc);
return ret;
}
/*
* Test the various ticket callbacks
* Test 0: TLSv1.2, no ticket key callback, no ticket, no renewal
* Test 1: TLSv1.3, no ticket key callback, no ticket, no renewal
* Test 2: TLSv1.2, no ticket key callback, no ticket, renewal
* Test 3: TLSv1.3, no ticket key callback, no ticket, renewal
* Test 4: TLSv1.2, no ticket key callback, ticket, no renewal
* Test 5: TLSv1.3, no ticket key callback, ticket, no renewal
* Test 6: TLSv1.2, no ticket key callback, ticket, renewal
* Test 7: TLSv1.3, no ticket key callback, ticket, renewal
* Test 8: TLSv1.2, old ticket key callback, ticket, no renewal
* Test 9: TLSv1.3, old ticket key callback, ticket, no renewal
* Test 10: TLSv1.2, old ticket key callback, ticket, renewal
* Test 11: TLSv1.3, old ticket key callback, ticket, renewal
* Test 12: TLSv1.2, old ticket key callback, no ticket
* Test 13: TLSv1.3, old ticket key callback, no ticket
* Test 14: TLSv1.2, ticket key callback, ticket, no renewal
* Test 15: TLSv1.3, ticket key callback, ticket, no renewal
* Test 16: TLSv1.2, ticket key callback, ticket, renewal
* Test 17: TLSv1.3, ticket key callback, ticket, renewal
* Test 18: TLSv1.2, ticket key callback, no ticket
* Test 19: TLSv1.3, ticket key callback, no ticket
*/
static int test_ticket_callbacks(int tst)
{
SSL_CTX *cctx = NULL, *sctx = NULL;
SSL *clientssl = NULL, *serverssl = NULL;
SSL_SESSION *clntsess = NULL;
int testresult = 0;
#ifdef OPENSSL_NO_TLS1_2
if (tst % 2 == 0)
return 1;
#endif
#ifdef OSSL_NO_USABLE_TLS1_3
if (tst % 2 == 1)
return 1;
#endif
#ifdef OPENSSL_NO_DEPRECATED_3_0
if (tst >= 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))
|| !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;
}
#if !defined(OPENSSL_NO_TLS1_2) || !defined(OSSL_NO_USABLE_TLS1_3)
static int cert_cb_cnt;
static int cert_cb(SSL *s, void *arg)
{
SSL_CTX *ctx = (SSL_CTX *)arg;
BIO *in = NULL;
EVP_PKEY *pkey = NULL;
X509 *x509 = NULL, *rootx = NULL;
STACK_OF(X509) *chain = NULL;
char *rootfile = NULL, *ecdsacert = NULL, *ecdsakey = 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;
rootfile = test_mk_file_path(certsdir, "rootcert.pem");
ecdsacert = test_mk_file_path(certsdir, "server-ecdsa-cert.pem");
ecdsakey = test_mk_file_path(certsdir, "server-ecdsa-key.pem");
if (!TEST_ptr(rootfile) || !TEST_ptr(ecdsacert) || !TEST_ptr(ecdsakey))
goto out;
chain = sk_X509_new_null();
if (!TEST_ptr(chain))
goto out;
if (!TEST_ptr(in = BIO_new(BIO_s_file()))
|| !TEST_int_gt(BIO_read_filename(in, rootfile), 0)
|| !TEST_ptr(rootx = X509_new_ex(libctx, NULL))
|| !TEST_ptr(PEM_read_bio_X509(in, &rootx, NULL, NULL))
|| !TEST_true(sk_X509_push(chain, rootx)))
goto out;
rootx = NULL;
BIO_free(in);
if (!TEST_ptr(in = BIO_new(BIO_s_file()))
|| !TEST_int_gt(BIO_read_filename(in, ecdsacert), 0)
|| !TEST_ptr(x509 = X509_new_ex(libctx, NULL))
|| !TEST_ptr(PEM_read_bio_X509(in, &x509, NULL, NULL)))
goto out;
BIO_free(in);
if (!TEST_ptr(in = BIO_new(BIO_s_file()))
|| !TEST_int_gt(BIO_read_filename(in, ecdsakey), 0)
|| !TEST_ptr(pkey = PEM_read_bio_PrivateKey_ex(in, NULL,
NULL, NULL,
libctx, 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:
OPENSSL_free(ecdsacert);
OPENSSL_free(ecdsakey);
OPENSSL_free(rootfile);
BIO_free(in);
EVP_PKEY_free(pkey);
X509_free(x509);
X509_free(rootx);
sk_X509_pop_free(chain, X509_free);
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(),
TLS1_VERSION,
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 they are removed as expected
*/
SSL_SESSION *early = NULL;
SSL_SESSION *middle = NULL;
SSL_SESSION *late = NULL;
SSL_CTX *ctx;
int testresult = 0;
long now = (long)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_int_ne(SSL_SESSION_set_time(early, now - 10), 0)
|| !TEST_int_ne(SSL_SESSION_set_time(middle, now), 0)
|| !TEST_int_ne(SSL_SESSION_set_time(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(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(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(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(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_int_ne(SSL_SESSION_set_time(early, now), 0)
|| !TEST_int_eq(SSL_CTX_add_session(ctx, early), 1)
|| !TEST_long_ne(SSL_SESSION_get_time(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 / 2))) {
+ 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;
}
#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;
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"))
|| !TEST_true(filter_provider_set_filter(OSSL_OP_KEYMGMT,
"EC:X25519:X448")))
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;
if (idx != 5) {
if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
TLS_client_method(),
TLS1_VERSION,
0,
&sctx, &cctx, cert, privkey)))
goto end;
} else {
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;
}
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 */
if (!TEST_int_eq(SSL_get_shared_sigalgs(serverssl, 0, &sig, &hash, NULL,
NULL, NULL),
(idx == 0 || idx == 3) ? 2 : 1))
goto end;
if (!TEST_int_eq(hash, idx == 0 ? NID_sha384 : NID_sha256))
goto end;
if (!TEST_int_eq(sig, (idx == 4 || idx == 5) ? EVP_PKEY_EC
: NID_rsassaPss))
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 ? "xorgroup" : "xorkemgroup";
+ const char *group_name = idx == 0 ? "xorkemgroup" : "xorgroup";
if (!TEST_ptr(tlsprov))
goto end;
- if (legacyprov == NULL) {
- /*
- * In this case we assume we've been built with "no-legacy" and skip
- * this test (there is no OPENSSL_NO_LEGACY)
- */
- testresult = 1;
- 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;
- if (!TEST_true(SSL_set1_groups_list(serverssl, group_name))
+ /* 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;
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;
}
#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;
}
# 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 = NULL, *sctx = NULL;
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";
switch (idx) {
case 0:
/* The FIPS provider doesn't support this DH size - so we ignore it */
if (is_fips)
return 1;
thiscert = cert1024;
thiskey = privkey1024;
expdhsize = 1024;
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)
return 1;
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, TLS_server_method(),
TLS_client_method(),
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
}
#if !defined(OPENSSL_NO_TLS1_2) && !defined(OPENSSL_NO_DYNAMIC_ENGINE)
-
-static ENGINE *load_dasync(void)
-{
- ENGINE *e;
-
- if (!TEST_ptr(e = ENGINE_by_id("dasync")))
- return NULL;
-
- if (!TEST_true(ENGINE_init(e))) {
- ENGINE_free(e);
- return NULL;
- }
-
- if (!TEST_true(ENGINE_register_ciphers(e))) {
- ENGINE_free(e);
- return NULL;
- }
-
- return e;
-}
-
/*
* 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) */
/*
* 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 && !add_large_cert_chain(sctx))
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;
}
+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;
+}
+
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;
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)
is_fips = 1;
/*
* 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 !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);
# 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, 5);
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 OPENSSL_NO_TLS1_2
/* Test with both TLSv1.3 and 1.2 versions */
ADD_ALL_TESTS(test_key_exchange, 14);
# 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, 12);
# 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, 2);
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
ADD_ALL_TESTS(test_info_callback, 6);
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_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);
#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);
#endif
#ifndef OPENSSL_NO_TLS1_2
ADD_TEST(test_ssl_dup);
# 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);
#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_handshake_retry, 16);
+ ADD_ALL_TESTS(test_multi_resume, 5);
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();
OSSL_PROVIDER_unload(defctxnull);
OSSL_LIB_CTX_free(libctx);
}
diff --git a/crypto/openssl/test/sslbuffertest.c b/crypto/openssl/test/sslbuffertest.c
index 3c3e69d61da8..f313151f686f 100644
--- a/crypto/openssl/test/sslbuffertest.c
+++ b/crypto/openssl/test/sslbuffertest.c
@@ -1,183 +1,357 @@
/*
- * Copyright 2016-2020 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2016-2024 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.
*/
+/*
+ * We need access to the deprecated low level Engine APIs for legacy purposes
+ * when the deprecated calls are not hidden
+ */
+#ifndef OPENSSL_NO_DEPRECATED_3_0
+# define OPENSSL_SUPPRESS_DEPRECATED
+#endif
+
#include <string.h>
#include <openssl/ssl.h>
#include <openssl/bio.h>
#include <openssl/err.h>
+#include <openssl/engine.h>
#include "internal/packet.h"
#include "helpers/ssltestlib.h"
#include "testutil.h"
struct async_ctrs {
unsigned int rctr;
unsigned int wctr;
};
static SSL_CTX *serverctx = NULL;
static SSL_CTX *clientctx = NULL;
#define MAX_ATTEMPTS 100
/*
* There are 9 passes in the tests
* 0 = control test
* tests during writes
* 1 = free buffers
* 2 = + allocate buffers after free
* 3 = + allocate buffers again
* 4 = + free buffers after allocation
* tests during reads
* 5 = + free buffers
* 6 = + free buffers again
* 7 = + allocate buffers after free
* 8 = + free buffers after allocation
*/
static int test_func(int test)
{
int result = 0;
SSL *serverssl = NULL, *clientssl = NULL;
int ret;
size_t i, j;
const char testdata[] = "Test data";
char buf[sizeof(testdata)];
if (!TEST_true(create_ssl_objects(serverctx, clientctx, &serverssl, &clientssl,
NULL, NULL))) {
TEST_error("Test %d failed: Create SSL objects failed\n", test);
goto end;
}
if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))) {
TEST_error("Test %d failed: Create SSL connection failed\n", test);
goto end;
}
/*
* Send and receive some test data. Do the whole thing twice to ensure
* we hit at least one async event in both reading and writing
*/
for (j = 0; j < 2; j++) {
int len;
/*
* Write some test data. It should never take more than 2 attempts
* (the first one might be a retryable fail).
*/
for (ret = -1, i = 0, len = 0; len != sizeof(testdata) && i < 2;
i++) {
/* test == 0 mean to free/allocate = control */
if (test >= 1 && !TEST_true(SSL_free_buffers(clientssl)))
goto end;
if (test >= 2 && !TEST_true(SSL_alloc_buffers(clientssl)))
goto end;
/* allocate a second time */
if (test >= 3 && !TEST_true(SSL_alloc_buffers(clientssl)))
goto end;
if (test >= 4 && !TEST_true(SSL_free_buffers(clientssl)))
goto end;
ret = SSL_write(clientssl, testdata + len,
sizeof(testdata) - len);
if (ret > 0) {
len += ret;
} else {
int ssl_error = SSL_get_error(clientssl, ret);
if (ssl_error == SSL_ERROR_SYSCALL ||
ssl_error == SSL_ERROR_SSL) {
TEST_error("Test %d failed: Failed to write app data\n", test);
goto end;
}
}
}
if (!TEST_size_t_eq(len, sizeof(testdata)))
goto end;
/*
* Now read the test data. It may take more attempts here because
* it could fail once for each byte read, including all overhead
* bytes from the record header/padding etc.
*/
for (ret = -1, i = 0, len = 0; len != sizeof(testdata) &&
i < MAX_ATTEMPTS; i++)
{
if (test >= 5 && !TEST_true(SSL_free_buffers(serverssl)))
goto end;
/* free a second time */
if (test >= 6 && !TEST_true(SSL_free_buffers(serverssl)))
goto end;
if (test >= 7 && !TEST_true(SSL_alloc_buffers(serverssl)))
goto end;
if (test >= 8 && !TEST_true(SSL_free_buffers(serverssl)))
goto end;
ret = SSL_read(serverssl, buf + len, sizeof(buf) - len);
if (ret > 0) {
len += ret;
} else {
int ssl_error = SSL_get_error(serverssl, ret);
if (ssl_error == SSL_ERROR_SYSCALL ||
ssl_error == SSL_ERROR_SSL) {
TEST_error("Test %d failed: Failed to read app data\n", test);
goto end;
}
}
}
if (!TEST_mem_eq(buf, len, testdata, sizeof(testdata)))
goto end;
}
result = 1;
end:
if (!result)
ERR_print_errors_fp(stderr);
SSL_free(clientssl);
SSL_free(serverssl);
return result;
}
+/*
+ * Test that attempting to free the buffers at points where they cannot be freed
+ * works as expected
+ * Test 0: Attempt to free buffers after a full record has been processed, but
+ * the application has only performed a partial read
+ * Test 1: Attempt to free buffers after only a partial record header has been
+ * received
+ * Test 2: Attempt to free buffers after a full record header but no record body
+ * Test 3: Attempt to free buffers after a full record hedaer and partial record
+ * body
+ * Test 4-7: We repeat tests 0-3 but including data from a second pipelined
+ * record
+ */
+static int test_free_buffers(int test)
+{
+ int result = 0;
+ SSL *serverssl = NULL, *clientssl = NULL;
+ const char testdata[] = "Test data";
+ char buf[120];
+ size_t written, readbytes;
+ int i, pipeline = test > 3;
+ ENGINE *e = NULL;
+
+ if (pipeline) {
+ e = load_dasync();
+ if (e == NULL)
+ goto end;
+ test -= 4;
+ }
+
+ if (!TEST_true(create_ssl_objects(serverctx, clientctx, &serverssl,
+ &clientssl, NULL, NULL)))
+ goto end;
+
+ if (pipeline) {
+ if (!TEST_true(SSL_set_cipher_list(serverssl, "AES128-SHA"))
+ || !TEST_true(SSL_set_max_proto_version(serverssl,
+ TLS1_2_VERSION))
+ || !TEST_true(SSL_set_max_pipelines(serverssl, 2)))
+ goto end;
+ }
+
+ if (!TEST_true(create_ssl_connection(serverssl, clientssl,
+ SSL_ERROR_NONE)))
+ goto end;
+
+ /*
+ * For the non-pipeline case we write one record. For pipelining we write
+ * two records.
+ */
+ for (i = 0; i <= pipeline; i++) {
+ if (!TEST_true(SSL_write_ex(clientssl, testdata, strlen(testdata),
+ &written)))
+ goto end;
+ }
+
+ if (test == 0) {
+ size_t readlen = 1;
+
+ /*
+ * Deliberately only read the first byte - so the remaining bytes are
+ * still buffered. In the pipelining case we read as far as the first
+ * byte from the second record.
+ */
+ if (pipeline)
+ readlen += strlen(testdata);
+
+ if (!TEST_true(SSL_read_ex(serverssl, buf, readlen, &readbytes))
+ || !TEST_size_t_eq(readlen, readbytes))
+ goto end;
+ } else {
+ BIO *tmp;
+ size_t partial_len;
+
+ /* Remove all the data that is pending for read by the server */
+ tmp = SSL_get_rbio(serverssl);
+ if (!TEST_true(BIO_read_ex(tmp, buf, sizeof(buf), &readbytes))
+ || !TEST_size_t_lt(readbytes, sizeof(buf))
+ || !TEST_size_t_gt(readbytes, SSL3_RT_HEADER_LENGTH))
+ goto end;
+
+ switch(test) {
+ case 1:
+ partial_len = SSL3_RT_HEADER_LENGTH - 1;
+ break;
+ case 2:
+ partial_len = SSL3_RT_HEADER_LENGTH;
+ break;
+ case 3:
+ partial_len = readbytes - 1;
+ break;
+ default:
+ TEST_error("Invalid test index");
+ goto end;
+ }
+
+ if (pipeline) {
+ /* We happen to know the first record is 57 bytes long */
+ const size_t first_rec_len = 57;
+
+ if (test != 3)
+ partial_len += first_rec_len;
+
+ /*
+ * Sanity check. If we got the record len right then this should
+ * never fail.
+ */
+ if (!TEST_int_eq(buf[first_rec_len], SSL3_RT_APPLICATION_DATA))
+ goto end;
+ }
+
+ /*
+ * Put back just the partial record (plus the whole initial record in
+ * the pipelining case)
+ */
+ if (!TEST_true(BIO_write_ex(tmp, buf, partial_len, &written)))
+ goto end;
+
+ if (pipeline) {
+ /*
+ * Attempt a read. This should pass but only return data from the
+ * first record. Only a partial record is available for the second
+ * record.
+ */
+ if (!TEST_true(SSL_read_ex(serverssl, buf, sizeof(buf),
+ &readbytes))
+ || !TEST_size_t_eq(readbytes, strlen(testdata)))
+ goto end;
+ } else {
+ /*
+ * Attempt a read. This should fail because only a partial record is
+ * available.
+ */
+ if (!TEST_false(SSL_read_ex(serverssl, buf, sizeof(buf),
+ &readbytes)))
+ goto end;
+ }
+ }
+
+ /*
+ * Attempting to free the buffers at this point should fail because they are
+ * still in use
+ */
+ if (!TEST_false(SSL_free_buffers(serverssl)))
+ goto end;
+
+ result = 1;
+ end:
+ SSL_free(clientssl);
+ SSL_free(serverssl);
+#ifndef OPENSSL_NO_DYNAMIC_ENGINE
+ if (e != NULL) {
+ ENGINE_unregister_ciphers(e);
+ ENGINE_finish(e);
+ ENGINE_free(e);
+ }
+#endif
+ return result;
+}
+
OPT_TEST_DECLARE_USAGE("certfile privkeyfile\n")
int setup_tests(void)
{
char *cert, *pkey;
if (!test_skip_common_options()) {
TEST_error("Error parsing test options\n");
return 0;
}
if (!TEST_ptr(cert = test_get_argument(0))
|| !TEST_ptr(pkey = test_get_argument(1)))
return 0;
if (!create_ssl_ctx_pair(NULL, TLS_server_method(), TLS_client_method(),
TLS1_VERSION, 0,
&serverctx, &clientctx, cert, pkey)) {
TEST_error("Failed to create SSL_CTX pair\n");
return 0;
}
ADD_ALL_TESTS(test_func, 9);
+#if !defined(OPENSSL_NO_TLS1_2) && !defined(OPENSSL_NO_DYNAMIC_ENGINE)
+ ADD_ALL_TESTS(test_free_buffers, 8);
+#else
+ ADD_ALL_TESTS(test_free_buffers, 4);
+#endif
return 1;
}
void cleanup_tests(void)
{
SSL_CTX_free(clientctx);
SSL_CTX_free(serverctx);
}
diff --git a/crypto/openssl/test/test.cnf b/crypto/openssl/test/test.cnf
index 8b2f92ad8e24..8f68982a9fa1 100644
--- a/crypto/openssl/test/test.cnf
+++ b/crypto/openssl/test/test.cnf
@@ -1,74 +1,80 @@
####################################################################
[ ca ]
default_ca = CA_default # The default ca section
####################################################################
[ CA_default ]
dir = ./demoCA # Where everything is kept
certs = $dir/certs # Where the issued certs are kept
crl_dir = $dir/crl # Where the issued crl are kept
database = $dir/index.txt # database index file.
new_certs_dir = $dir/new_certs # default place for new certs.
certificate = $dir/CAcert.pem # The CA certificate
serial = $dir/serial # The current serial number
crl = $dir/crl.pem # The current CRL
private_key = $dir/private/CAkey.pem# The private key
default_days = 365 # how long to certify for
default_crl_days= 30 # how long before next CRL
default_md = md5 # which md to use.
# A few difference way of specifying how similar the request should look
# For type CA, the listed attributes must be the same, and the optional
# and supplied fields are just that :-)
policy = policy_match
# For the CA policy
[ policy_match ]
countryName = match
stateOrProvinceName = match
organizationName = match
organizationalUnitName = optional
commonName = supplied
emailAddress = optional
# For the 'anything' policy
# At this point in time, you must list all acceptable 'object'
# types.
[ policy_anything ]
countryName = optional
stateOrProvinceName = optional
localityName = optional
organizationName = optional
organizationalUnitName = optional
commonName = supplied
emailAddress = optional
####################################################################
[ req ]
distinguished_name = req_distinguished_name
encrypt_rsa_key = no
# Make altreq be identical to req
[ altreq ]
distinguished_name = req_distinguished_name
encrypt_rsa_key = no
[ req_distinguished_name ]
countryName = C field
countryName_value = AU
stateOrProvinceName = SP field
stateOrProvinceName_value =
localityName = L field
localityName_value = Brisbane
organizationName = O field
organizationName_value = CryptSoft Pty Ltd
organizationalUnitName = OU field
organizationalUnitName_value = .
commonName = CN field
commonName_value = Eric Young
emailAddress = email field
emailAddress_value = eay@mincom.oz.au
+
+[ dirname_sec ]
+C = UK
+O = My Organization
+OU = My Unit
+CN = My Name
diff --git a/crypto/openssl/test/tls-provider.c b/crypto/openssl/test/tls-provider.c
index 5c44b6812e81..7375792c3125 100644
--- a/crypto/openssl/test/tls-provider.c
+++ b/crypto/openssl/test/tls-provider.c
@@ -1,857 +1,864 @@
/*
- * Copyright 2019-2022 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2019-2024 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 <string.h>
#include <openssl/core_names.h>
#include <openssl/core_dispatch.h>
#include <openssl/rand.h>
#include <openssl/params.h>
/* For TLS1_3_VERSION */
#include <openssl/ssl.h>
#include "internal/nelem.h"
static OSSL_FUNC_keymgmt_import_fn xor_import;
static OSSL_FUNC_keymgmt_import_types_fn xor_import_types;
static OSSL_FUNC_keymgmt_export_fn xor_export;
static OSSL_FUNC_keymgmt_export_types_fn xor_export_types;
int tls_provider_init(const OSSL_CORE_HANDLE *handle,
const OSSL_DISPATCH *in,
const OSSL_DISPATCH **out,
void **provctx);
#define XOR_KEY_SIZE 32
/*
* Top secret. This algorithm only works if no one knows what this number is.
* Please don't tell anyone what it is.
*
* This algorithm is for testing only - don't really use it!
*/
static const unsigned char private_constant[XOR_KEY_SIZE] = {
0xd3, 0x6b, 0x54, 0xec, 0x5b, 0xac, 0x89, 0x96, 0x8c, 0x2c, 0x66, 0xa5,
0x67, 0x0d, 0xe3, 0xdd, 0x43, 0x69, 0xbc, 0x83, 0x3d, 0x60, 0xc7, 0xb8,
0x2b, 0x1c, 0x5a, 0xfd, 0xb5, 0xcd, 0xd0, 0xf8
};
typedef struct xorkey_st {
unsigned char privkey[XOR_KEY_SIZE];
unsigned char pubkey[XOR_KEY_SIZE];
int hasprivkey;
int haspubkey;
} XORKEY;
/* Key Management for the dummy XOR KEX and KEM algorithms */
static OSSL_FUNC_keymgmt_new_fn xor_newdata;
static OSSL_FUNC_keymgmt_free_fn xor_freedata;
static OSSL_FUNC_keymgmt_has_fn xor_has;
static OSSL_FUNC_keymgmt_dup_fn xor_dup;
static OSSL_FUNC_keymgmt_gen_init_fn xor_gen_init;
static OSSL_FUNC_keymgmt_gen_set_params_fn xor_gen_set_params;
static OSSL_FUNC_keymgmt_gen_settable_params_fn xor_gen_settable_params;
static OSSL_FUNC_keymgmt_gen_fn xor_gen;
static OSSL_FUNC_keymgmt_gen_cleanup_fn xor_gen_cleanup;
static OSSL_FUNC_keymgmt_get_params_fn xor_get_params;
static OSSL_FUNC_keymgmt_gettable_params_fn xor_gettable_params;
static OSSL_FUNC_keymgmt_set_params_fn xor_set_params;
static OSSL_FUNC_keymgmt_settable_params_fn xor_settable_params;
/*
* Dummy "XOR" Key Exchange algorithm. We just xor the private and public keys
* together. Don't use this!
*/
static OSSL_FUNC_keyexch_newctx_fn xor_newctx;
static OSSL_FUNC_keyexch_init_fn xor_init;
static OSSL_FUNC_keyexch_set_peer_fn xor_set_peer;
static OSSL_FUNC_keyexch_derive_fn xor_derive;
static OSSL_FUNC_keyexch_freectx_fn xor_freectx;
static OSSL_FUNC_keyexch_dupctx_fn xor_dupctx;
/*
* Dummy "XOR" Key Encapsulation Method. We just build a KEM over the xor KEX.
* Don't use this!
*/
static OSSL_FUNC_kem_newctx_fn xor_newctx;
static OSSL_FUNC_kem_freectx_fn xor_freectx;
static OSSL_FUNC_kem_dupctx_fn xor_dupctx;
static OSSL_FUNC_kem_encapsulate_init_fn xor_init;
static OSSL_FUNC_kem_encapsulate_fn xor_encapsulate;
static OSSL_FUNC_kem_decapsulate_init_fn xor_init;
static OSSL_FUNC_kem_decapsulate_fn xor_decapsulate;
/*
* We define 2 dummy TLS groups called "xorgroup" and "xorkemgroup" for test
* purposes
*/
struct tls_group_st {
unsigned int group_id; /* for "tls-group-id", see provider-base(7) */
unsigned int secbits;
unsigned int mintls;
unsigned int maxtls;
unsigned int mindtls;
unsigned int maxdtls;
unsigned int is_kem; /* boolean */
};
#define XORGROUP_NAME "xorgroup"
#define XORGROUP_NAME_INTERNAL "xorgroup-int"
static struct tls_group_st xor_group = {
0, /* group_id, set by randomize_tls_group_id() */
128, /* secbits */
TLS1_3_VERSION, /* mintls */
0, /* maxtls */
-1, /* mindtls */
-1, /* maxdtls */
0 /* is_kem */
};
#define XORKEMGROUP_NAME "xorkemgroup"
#define XORKEMGROUP_NAME_INTERNAL "xorkemgroup-int"
static struct tls_group_st xor_kemgroup = {
0, /* group_id, set by randomize_tls_group_id() */
128, /* secbits */
TLS1_3_VERSION, /* mintls */
0, /* maxtls */
-1, /* mindtls */
-1, /* maxdtls */
1 /* is_kem */
};
#define ALGORITHM "XOR"
static const OSSL_PARAM xor_group_params[] = {
OSSL_PARAM_utf8_string(OSSL_CAPABILITY_TLS_GROUP_NAME,
XORGROUP_NAME, sizeof(XORGROUP_NAME)),
OSSL_PARAM_utf8_string(OSSL_CAPABILITY_TLS_GROUP_NAME_INTERNAL,
XORGROUP_NAME_INTERNAL,
sizeof(XORGROUP_NAME_INTERNAL)),
OSSL_PARAM_utf8_string(OSSL_CAPABILITY_TLS_GROUP_ALG, ALGORITHM,
sizeof(ALGORITHM)),
OSSL_PARAM_uint(OSSL_CAPABILITY_TLS_GROUP_ID, &xor_group.group_id),
OSSL_PARAM_uint(OSSL_CAPABILITY_TLS_GROUP_SECURITY_BITS,
&xor_group.secbits),
OSSL_PARAM_int(OSSL_CAPABILITY_TLS_GROUP_MIN_TLS, &xor_group.mintls),
OSSL_PARAM_int(OSSL_CAPABILITY_TLS_GROUP_MAX_TLS, &xor_group.maxtls),
OSSL_PARAM_int(OSSL_CAPABILITY_TLS_GROUP_MIN_DTLS, &xor_group.mindtls),
OSSL_PARAM_int(OSSL_CAPABILITY_TLS_GROUP_MAX_DTLS, &xor_group.maxdtls),
OSSL_PARAM_uint(OSSL_CAPABILITY_TLS_GROUP_IS_KEM, &xor_group.is_kem),
OSSL_PARAM_END
};
static const OSSL_PARAM xor_kemgroup_params[] = {
OSSL_PARAM_utf8_string(OSSL_CAPABILITY_TLS_GROUP_NAME,
XORKEMGROUP_NAME, sizeof(XORKEMGROUP_NAME)),
OSSL_PARAM_utf8_string(OSSL_CAPABILITY_TLS_GROUP_NAME_INTERNAL,
XORKEMGROUP_NAME_INTERNAL,
sizeof(XORKEMGROUP_NAME_INTERNAL)),
OSSL_PARAM_utf8_string(OSSL_CAPABILITY_TLS_GROUP_ALG, ALGORITHM,
sizeof(ALGORITHM)),
OSSL_PARAM_uint(OSSL_CAPABILITY_TLS_GROUP_ID, &xor_kemgroup.group_id),
OSSL_PARAM_uint(OSSL_CAPABILITY_TLS_GROUP_SECURITY_BITS,
&xor_kemgroup.secbits),
OSSL_PARAM_int(OSSL_CAPABILITY_TLS_GROUP_MIN_TLS, &xor_kemgroup.mintls),
OSSL_PARAM_int(OSSL_CAPABILITY_TLS_GROUP_MAX_TLS, &xor_kemgroup.maxtls),
OSSL_PARAM_int(OSSL_CAPABILITY_TLS_GROUP_MIN_DTLS, &xor_kemgroup.mindtls),
OSSL_PARAM_int(OSSL_CAPABILITY_TLS_GROUP_MAX_DTLS, &xor_kemgroup.maxdtls),
OSSL_PARAM_uint(OSSL_CAPABILITY_TLS_GROUP_IS_KEM, &xor_kemgroup.is_kem),
OSSL_PARAM_END
};
#define NUM_DUMMY_GROUPS 50
static char *dummy_group_names[NUM_DUMMY_GROUPS];
static int tls_prov_get_capabilities(void *provctx, const char *capability,
OSSL_CALLBACK *cb, void *arg)
{
int ret;
int i;
const char *dummy_base = "dummy";
const size_t dummy_name_max_size = strlen(dummy_base) + 3;
if (strcmp(capability, "TLS-GROUP") != 0) {
/* We don't support this capability */
return 0;
}
/* Register our 2 groups */
+ OPENSSL_assert(xor_group.group_id >= 65024
+ && xor_group.group_id < 65279 - NUM_DUMMY_GROUPS);
ret = cb(xor_group_params, arg);
ret &= cb(xor_kemgroup_params, arg);
/*
* Now register some dummy groups > GROUPLIST_INCREMENT (== 40) as defined
* in ssl/t1_lib.c, to make sure we exercise the code paths for registering
* large numbers of groups.
*/
for (i = 0; i < NUM_DUMMY_GROUPS; i++) {
OSSL_PARAM dummygroup[OSSL_NELEM(xor_group_params)];
+ unsigned int dummygroup_id;
memcpy(dummygroup, xor_group_params, sizeof(xor_group_params));
/* Give the dummy group a unique name */
if (dummy_group_names[i] == NULL) {
dummy_group_names[i] = OPENSSL_zalloc(dummy_name_max_size);
if (dummy_group_names[i] == NULL)
return 0;
BIO_snprintf(dummy_group_names[i],
dummy_name_max_size,
"%s%d", dummy_base, i);
}
dummygroup[0].data = dummy_group_names[i];
dummygroup[0].data_size = strlen(dummy_group_names[i]) + 1;
+ /* assign unique group IDs also to dummy groups for registration */
+ dummygroup_id = 65279 - NUM_DUMMY_GROUPS + i;
+ dummygroup[3].data = (unsigned char*)&dummygroup_id;
ret &= cb(dummygroup, arg);
}
return ret;
}
/*
* Dummy "XOR" Key Exchange algorithm. We just xor the private and public keys
* together. Don't use this!
*/
typedef struct {
XORKEY *key;
XORKEY *peerkey;
void *provctx;
} PROV_XOR_CTX;
static void *xor_newctx(void *provctx)
{
PROV_XOR_CTX *pxorctx = OPENSSL_zalloc(sizeof(PROV_XOR_CTX));
if (pxorctx == NULL)
return NULL;
pxorctx->provctx = provctx;
return pxorctx;
}
static int xor_init(void *vpxorctx, void *vkey,
ossl_unused const OSSL_PARAM params[])
{
PROV_XOR_CTX *pxorctx = (PROV_XOR_CTX *)vpxorctx;
if (pxorctx == NULL || vkey == NULL)
return 0;
pxorctx->key = vkey;
return 1;
}
static int xor_set_peer(void *vpxorctx, void *vpeerkey)
{
PROV_XOR_CTX *pxorctx = (PROV_XOR_CTX *)vpxorctx;
if (pxorctx == NULL || vpeerkey == NULL)
return 0;
pxorctx->peerkey = vpeerkey;
return 1;
}
static int xor_derive(void *vpxorctx, unsigned char *secret, size_t *secretlen,
size_t outlen)
{
PROV_XOR_CTX *pxorctx = (PROV_XOR_CTX *)vpxorctx;
int i;
if (pxorctx->key == NULL || pxorctx->peerkey == NULL)
return 0;
*secretlen = XOR_KEY_SIZE;
if (secret == NULL)
return 1;
if (outlen < XOR_KEY_SIZE)
return 0;
for (i = 0; i < XOR_KEY_SIZE; i++)
secret[i] = pxorctx->key->privkey[i] ^ pxorctx->peerkey->pubkey[i];
return 1;
}
static void xor_freectx(void *pxorctx)
{
OPENSSL_free(pxorctx);
}
static void *xor_dupctx(void *vpxorctx)
{
PROV_XOR_CTX *srcctx = (PROV_XOR_CTX *)vpxorctx;
PROV_XOR_CTX *dstctx;
dstctx = OPENSSL_zalloc(sizeof(*srcctx));
if (dstctx == NULL)
return NULL;
*dstctx = *srcctx;
return dstctx;
}
static const OSSL_DISPATCH xor_keyexch_functions[] = {
{ OSSL_FUNC_KEYEXCH_NEWCTX, (void (*)(void))xor_newctx },
{ OSSL_FUNC_KEYEXCH_INIT, (void (*)(void))xor_init },
{ OSSL_FUNC_KEYEXCH_DERIVE, (void (*)(void))xor_derive },
{ OSSL_FUNC_KEYEXCH_SET_PEER, (void (*)(void))xor_set_peer },
{ OSSL_FUNC_KEYEXCH_FREECTX, (void (*)(void))xor_freectx },
{ OSSL_FUNC_KEYEXCH_DUPCTX, (void (*)(void))xor_dupctx },
{ 0, NULL }
};
static const OSSL_ALGORITHM tls_prov_keyexch[] = {
/*
* Obviously this is not FIPS approved, but in order to test in conjuction
* with the FIPS provider we pretend that it is.
*/
{ "XOR", "provider=tls-provider,fips=yes", xor_keyexch_functions },
{ NULL, NULL, NULL }
};
/*
* Dummy "XOR" Key Encapsulation Method. We just build a KEM over the xor KEX.
* Don't use this!
*/
static int xor_encapsulate(void *vpxorctx,
unsigned char *ct, size_t *ctlen,
unsigned char *ss, size_t *sslen)
{
/*
* We are building this around a KEX:
*
* 1. we generate ephemeral keypair
* 2. we encode our ephemeral pubkey as the outgoing ct
* 3. we derive using our ephemeral privkey in combination with the peer
* pubkey from the ctx; the result is our ss.
*/
int rv = 0;
void *genctx = NULL, *derivectx = NULL;
XORKEY *ourkey = NULL;
PROV_XOR_CTX *pxorctx = vpxorctx;
if (ct == NULL || ss == NULL) {
/* Just return sizes */
if (ctlen == NULL && sslen == NULL)
return 0;
if (ctlen != NULL)
*ctlen = XOR_KEY_SIZE;
if (sslen != NULL)
*sslen = XOR_KEY_SIZE;
return 1;
}
/* 1. Generate keypair */
genctx = xor_gen_init(pxorctx->provctx, OSSL_KEYMGMT_SELECT_KEYPAIR, NULL);
if (genctx == NULL)
goto end;
ourkey = xor_gen(genctx, NULL, NULL);
if (ourkey == NULL)
goto end;
/* 2. Encode ephemeral pubkey as ct */
memcpy(ct, ourkey->pubkey, XOR_KEY_SIZE);
*ctlen = XOR_KEY_SIZE;
/* 3. Derive ss via KEX */
derivectx = xor_newctx(pxorctx->provctx);
if (derivectx == NULL
|| !xor_init(derivectx, ourkey, NULL)
|| !xor_set_peer(derivectx, pxorctx->key)
|| !xor_derive(derivectx, ss, sslen, XOR_KEY_SIZE))
goto end;
rv = 1;
end:
xor_gen_cleanup(genctx);
xor_freedata(ourkey);
xor_freectx(derivectx);
return rv;
}
static int xor_decapsulate(void *vpxorctx,
unsigned char *ss, size_t *sslen,
const unsigned char *ct, size_t ctlen)
{
/*
* We are building this around a KEX:
*
* - ct is our peer's pubkey
* - decapsulate is just derive.
*/
int rv = 0;
void *derivectx = NULL;
XORKEY *peerkey = NULL;
PROV_XOR_CTX *pxorctx = vpxorctx;
if (ss == NULL) {
/* Just return size */
if (sslen == NULL)
return 0;
*sslen = XOR_KEY_SIZE;
return 1;
}
if (ctlen != XOR_KEY_SIZE)
return 0;
peerkey = xor_newdata(pxorctx->provctx);
if (peerkey == NULL)
goto end;
memcpy(peerkey->pubkey, ct, XOR_KEY_SIZE);
/* Derive ss via KEX */
derivectx = xor_newctx(pxorctx->provctx);
if (derivectx == NULL
|| !xor_init(derivectx, pxorctx->key, NULL)
|| !xor_set_peer(derivectx, peerkey)
|| !xor_derive(derivectx, ss, sslen, XOR_KEY_SIZE))
goto end;
rv = 1;
end:
xor_freedata(peerkey);
xor_freectx(derivectx);
return rv;
}
static const OSSL_DISPATCH xor_kem_functions[] = {
{ OSSL_FUNC_KEM_NEWCTX, (void (*)(void))xor_newctx },
{ OSSL_FUNC_KEM_FREECTX, (void (*)(void))xor_freectx },
{ OSSL_FUNC_KEM_DUPCTX, (void (*)(void))xor_dupctx },
{ OSSL_FUNC_KEM_ENCAPSULATE_INIT, (void (*)(void))xor_init },
{ OSSL_FUNC_KEM_ENCAPSULATE, (void (*)(void))xor_encapsulate },
{ OSSL_FUNC_KEM_DECAPSULATE_INIT, (void (*)(void))xor_init },
{ OSSL_FUNC_KEM_DECAPSULATE, (void (*)(void))xor_decapsulate },
{ 0, NULL }
};
static const OSSL_ALGORITHM tls_prov_kem[] = {
/*
* Obviously this is not FIPS approved, but in order to test in conjuction
* with the FIPS provider we pretend that it is.
*/
{ "XOR", "provider=tls-provider,fips=yes", xor_kem_functions },
{ NULL, NULL, NULL }
};
/* Key Management for the dummy XOR key exchange algorithm */
static void *xor_newdata(void *provctx)
{
return OPENSSL_zalloc(sizeof(XORKEY));
}
static void xor_freedata(void *keydata)
{
OPENSSL_free(keydata);
}
static int xor_has(const void *vkey, int selection)
{
const XORKEY *key = vkey;
int ok = 0;
if (key != NULL) {
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->hasprivkey;
}
return ok;
}
static void *xor_dup(const void *vfromkey, int selection)
{
XORKEY *tokey = xor_newdata(NULL);
const XORKEY *fromkey = vfromkey;
int ok = 0;
if (tokey != NULL && fromkey != NULL) {
ok = 1;
if ((selection & OSSL_KEYMGMT_SELECT_PUBLIC_KEY) != 0) {
if (fromkey->haspubkey) {
memcpy(tokey->pubkey, fromkey->pubkey, XOR_KEY_SIZE);
tokey->haspubkey = 1;
} else {
tokey->haspubkey = 0;
}
}
if ((selection & OSSL_KEYMGMT_SELECT_PRIVATE_KEY) != 0) {
if (fromkey->hasprivkey) {
memcpy(tokey->privkey, fromkey->privkey, XOR_KEY_SIZE);
tokey->hasprivkey = 1;
} else {
tokey->hasprivkey = 0;
}
}
}
if (!ok) {
xor_freedata(tokey);
tokey = NULL;
}
return tokey;
}
static ossl_inline int xor_get_params(void *vkey, OSSL_PARAM params[])
{
XORKEY *key = vkey;
OSSL_PARAM *p;
if ((p = OSSL_PARAM_locate(params, OSSL_PKEY_PARAM_BITS)) != NULL
&& !OSSL_PARAM_set_int(p, XOR_KEY_SIZE))
return 0;
if ((p = OSSL_PARAM_locate(params, OSSL_PKEY_PARAM_SECURITY_BITS)) != NULL
&& !OSSL_PARAM_set_int(p, xor_group.secbits))
return 0;
if ((p = OSSL_PARAM_locate(params,
OSSL_PKEY_PARAM_ENCODED_PUBLIC_KEY)) != NULL) {
if (p->data_type != OSSL_PARAM_OCTET_STRING)
return 0;
p->return_size = XOR_KEY_SIZE;
if (p->data != NULL && p->data_size >= XOR_KEY_SIZE)
memcpy(p->data, key->pubkey, XOR_KEY_SIZE);
}
return 1;
}
static const OSSL_PARAM xor_params[] = {
OSSL_PARAM_int(OSSL_PKEY_PARAM_BITS, NULL),
OSSL_PARAM_int(OSSL_PKEY_PARAM_SECURITY_BITS, NULL),
OSSL_PARAM_octet_string(OSSL_PKEY_PARAM_ENCODED_PUBLIC_KEY, NULL, 0),
OSSL_PARAM_END
};
static const OSSL_PARAM *xor_gettable_params(void *provctx)
{
return xor_params;
}
static int xor_set_params(void *vkey, const OSSL_PARAM params[])
{
XORKEY *key = vkey;
const OSSL_PARAM *p;
p = OSSL_PARAM_locate_const(params, OSSL_PKEY_PARAM_ENCODED_PUBLIC_KEY);
if (p != NULL) {
if (p->data_type != OSSL_PARAM_OCTET_STRING
|| p->data_size != XOR_KEY_SIZE)
return 0;
memcpy(key->pubkey, p->data, XOR_KEY_SIZE);
key->haspubkey = 1;
}
return 1;
}
static const OSSL_PARAM xor_known_settable_params[] = {
OSSL_PARAM_octet_string(OSSL_PKEY_PARAM_ENCODED_PUBLIC_KEY, NULL, 0),
OSSL_PARAM_END
};
static const OSSL_PARAM *xor_settable_params(void *provctx)
{
return xor_known_settable_params;
}
struct xor_gen_ctx {
int selection;
OSSL_LIB_CTX *libctx;
};
static void *xor_gen_init(void *provctx, int selection,
const OSSL_PARAM params[])
{
struct xor_gen_ctx *gctx = NULL;
if ((selection & (OSSL_KEYMGMT_SELECT_KEYPAIR
| OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS)) == 0)
return NULL;
if ((gctx = OPENSSL_zalloc(sizeof(*gctx))) != NULL)
gctx->selection = selection;
/* Our provctx is really just an OSSL_LIB_CTX */
gctx->libctx = (OSSL_LIB_CTX *)provctx;
if (!xor_gen_set_params(gctx, params)) {
OPENSSL_free(gctx);
return NULL;
}
return gctx;
}
static int xor_gen_set_params(void *genctx, const OSSL_PARAM params[])
{
struct xor_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) {
if (p->data_type != OSSL_PARAM_UTF8_STRING
|| (strcmp(p->data, XORGROUP_NAME_INTERNAL) != 0
&& strcmp(p->data, XORKEMGROUP_NAME_INTERNAL) != 0))
return 0;
}
return 1;
}
static const OSSL_PARAM *xor_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_END
};
return settable;
}
static void *xor_gen(void *genctx, OSSL_CALLBACK *osslcb, void *cbarg)
{
struct xor_gen_ctx *gctx = genctx;
XORKEY *key = OPENSSL_zalloc(sizeof(*key));
size_t i;
if (key == NULL)
return NULL;
if ((gctx->selection & OSSL_KEYMGMT_SELECT_KEYPAIR) != 0) {
if (RAND_bytes_ex(gctx->libctx, key->privkey, XOR_KEY_SIZE, 0) <= 0) {
OPENSSL_free(key);
return NULL;
}
for (i = 0; i < XOR_KEY_SIZE; i++)
key->pubkey[i] = key->privkey[i] ^ private_constant[i];
key->hasprivkey = 1;
key->haspubkey = 1;
}
return key;
}
/* IMPORT + EXPORT */
static int xor_import(void *vkey, int select, const OSSL_PARAM params[])
{
XORKEY *key = vkey;
const OSSL_PARAM *param_priv_key, *param_pub_key;
unsigned char privkey[XOR_KEY_SIZE];
unsigned char pubkey[XOR_KEY_SIZE];
void *pprivkey = privkey, *ppubkey = pubkey;
size_t priv_len = 0, pub_len = 0;
int res = 0;
if (key == NULL || (select & OSSL_KEYMGMT_SELECT_KEYPAIR) == 0)
return 0;
memset(privkey, 0, sizeof(privkey));
memset(pubkey, 0, sizeof(pubkey));
param_priv_key = OSSL_PARAM_locate_const(params, OSSL_PKEY_PARAM_PRIV_KEY);
param_pub_key = OSSL_PARAM_locate_const(params, OSSL_PKEY_PARAM_PUB_KEY);
if ((param_priv_key != NULL
&& !OSSL_PARAM_get_octet_string(param_priv_key, &pprivkey,
sizeof(privkey), &priv_len))
|| (param_pub_key != NULL
&& !OSSL_PARAM_get_octet_string(param_pub_key, &ppubkey,
sizeof(pubkey), &pub_len)))
goto err;
if (priv_len > 0) {
memcpy(key->privkey, privkey, priv_len);
key->hasprivkey = 1;
}
if (pub_len > 0) {
memcpy(key->pubkey, pubkey, pub_len);
key->haspubkey = 1;
}
res = 1;
err:
return res;
}
static int xor_export(void *vkey, int select, OSSL_CALLBACK *param_cb,
void *cbarg)
{
XORKEY *key = vkey;
OSSL_PARAM params[3], *p = params;
if (key == NULL || (select & OSSL_KEYMGMT_SELECT_KEYPAIR) == 0)
return 0;
*p++ = OSSL_PARAM_construct_octet_string(OSSL_PKEY_PARAM_PRIV_KEY,
key->privkey,
sizeof(key->privkey));
*p++ = OSSL_PARAM_construct_octet_string(OSSL_PKEY_PARAM_PUB_KEY,
key->pubkey, sizeof(key->pubkey));
*p++ = OSSL_PARAM_construct_end();
return param_cb(params, cbarg);
}
static const OSSL_PARAM xor_key_types[] = {
OSSL_PARAM_BN(OSSL_PKEY_PARAM_PUB_KEY, NULL, 0),
OSSL_PARAM_BN(OSSL_PKEY_PARAM_PRIV_KEY, NULL, 0),
OSSL_PARAM_END
};
static const OSSL_PARAM *xor_import_types(int select)
{
return (select & OSSL_KEYMGMT_SELECT_KEYPAIR) != 0 ? xor_key_types : NULL;
}
static const OSSL_PARAM *xor_export_types(int select)
{
return (select & OSSL_KEYMGMT_SELECT_KEYPAIR) != 0 ? xor_key_types : NULL;
}
static void xor_gen_cleanup(void *genctx)
{
OPENSSL_free(genctx);
}
static const OSSL_DISPATCH xor_keymgmt_functions[] = {
{ OSSL_FUNC_KEYMGMT_NEW, (void (*)(void))xor_newdata },
{ OSSL_FUNC_KEYMGMT_GEN_INIT, (void (*)(void))xor_gen_init },
{ OSSL_FUNC_KEYMGMT_GEN_SET_PARAMS, (void (*)(void))xor_gen_set_params },
{ OSSL_FUNC_KEYMGMT_GEN_SETTABLE_PARAMS,
(void (*)(void))xor_gen_settable_params },
{ OSSL_FUNC_KEYMGMT_GEN, (void (*)(void))xor_gen },
{ OSSL_FUNC_KEYMGMT_GEN_CLEANUP, (void (*)(void))xor_gen_cleanup },
{ OSSL_FUNC_KEYMGMT_GET_PARAMS, (void (*) (void))xor_get_params },
{ OSSL_FUNC_KEYMGMT_GETTABLE_PARAMS, (void (*) (void))xor_gettable_params },
{ OSSL_FUNC_KEYMGMT_SET_PARAMS, (void (*) (void))xor_set_params },
{ OSSL_FUNC_KEYMGMT_SETTABLE_PARAMS, (void (*) (void))xor_settable_params },
{ OSSL_FUNC_KEYMGMT_HAS, (void (*)(void))xor_has },
{ OSSL_FUNC_KEYMGMT_DUP, (void (*)(void))xor_dup },
{ OSSL_FUNC_KEYMGMT_FREE, (void (*)(void))xor_freedata },
{ OSSL_FUNC_KEYMGMT_IMPORT, (void (*)(void))xor_import },
{ OSSL_FUNC_KEYMGMT_IMPORT_TYPES, (void (*)(void))xor_import_types },
{ OSSL_FUNC_KEYMGMT_EXPORT, (void (*)(void))xor_export },
{ OSSL_FUNC_KEYMGMT_EXPORT_TYPES, (void (*)(void))xor_export_types },
{ 0, NULL }
};
static const OSSL_ALGORITHM tls_prov_keymgmt[] = {
/*
* Obviously this is not FIPS approved, but in order to test in conjuction
* with the FIPS provider we pretend that it is.
*/
{ "XOR", "provider=tls-provider,fips=yes", xor_keymgmt_functions },
{ NULL, NULL, NULL }
};
static const OSSL_ALGORITHM *tls_prov_query(void *provctx, int operation_id,
int *no_cache)
{
*no_cache = 0;
switch (operation_id) {
case OSSL_OP_KEYMGMT:
return tls_prov_keymgmt;
case OSSL_OP_KEYEXCH:
return tls_prov_keyexch;
case OSSL_OP_KEM:
return tls_prov_kem;
}
return NULL;
}
static void tls_prov_teardown(void *provctx)
{
int i;
OSSL_LIB_CTX_free(provctx);
for (i = 0; i < NUM_DUMMY_GROUPS; i++) {
OPENSSL_free(dummy_group_names[i]);
dummy_group_names[i] = NULL;
}
}
/* Functions we provide to the core */
static const OSSL_DISPATCH tls_prov_dispatch_table[] = {
{ OSSL_FUNC_PROVIDER_TEARDOWN, (void (*)(void))tls_prov_teardown },
{ OSSL_FUNC_PROVIDER_QUERY_OPERATION, (void (*)(void))tls_prov_query },
{ OSSL_FUNC_PROVIDER_GET_CAPABILITIES, (void (*)(void))tls_prov_get_capabilities },
{ 0, NULL }
};
static
unsigned int randomize_tls_group_id(OSSL_LIB_CTX *libctx)
{
/*
* Randomise the group_id we're going to use to ensure we don't interoperate
* with anything but ourselves.
*/
unsigned int group_id;
static unsigned int mem[10] = { 0 };
static int in_mem = 0;
int i;
retry:
if (RAND_bytes_ex(libctx, (unsigned char *)&group_id, sizeof(group_id), 0) <= 0)
return 0;
/*
* Ensure group_id is within the IANA Reserved for private use range
- * (65024-65279)
+ * (65024-65279).
+ * Carve out NUM_DUMMY_GROUPS ids for properly registering those.
*/
- group_id %= 65279 - 65024;
+ group_id %= 65279 - NUM_DUMMY_GROUPS - 65024;
group_id += 65024;
/* Ensure we did not already issue this group_id */
for (i = 0; i < in_mem; i++)
if (mem[i] == group_id)
goto retry;
/* Add this group_id to the list of ids issued by this function */
mem[in_mem++] = group_id;
return group_id;
}
int tls_provider_init(const OSSL_CORE_HANDLE *handle,
const OSSL_DISPATCH *in,
const OSSL_DISPATCH **out,
void **provctx)
{
OSSL_LIB_CTX *libctx = OSSL_LIB_CTX_new();
if (libctx == NULL)
return 0;
*provctx = libctx;
/*
* Randomise the group_id we're going to use to ensure we don't interoperate
* with anything but ourselves.
*/
xor_group.group_id = randomize_tls_group_id(libctx);
xor_kemgroup.group_id = randomize_tls_group_id(libctx);
*out = tls_prov_dispatch_table;
return 1;
}
diff --git a/crypto/openssl/test/v3ext.c b/crypto/openssl/test/v3ext.c
index 88034db27155..9305a3010bf8 100644
--- a/crypto/openssl/test/v3ext.c
+++ b/crypto/openssl/test/v3ext.c
@@ -1,478 +1,487 @@
/*
- * Copyright 2016-2022 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2016-2024 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 <stdio.h>
#include <string.h>
#include <openssl/x509.h>
#include <openssl/x509v3.h>
#include <openssl/pem.h>
#include <openssl/err.h>
#include "internal/nelem.h"
#include "testutil.h"
static const char *infile;
static int test_pathlen(void)
{
X509 *x = NULL;
BIO *b = NULL;
long pathlen;
int ret = 0;
if (!TEST_ptr(b = BIO_new_file(infile, "r"))
|| !TEST_ptr(x = PEM_read_bio_X509(b, NULL, NULL, NULL))
|| !TEST_int_eq(pathlen = X509_get_pathlen(x), 6))
goto end;
ret = 1;
end:
BIO_free(b);
X509_free(x);
return ret;
}
#ifndef OPENSSL_NO_RFC3779
static int test_asid(void)
{
ASN1_INTEGER *val1 = NULL, *val2 = NULL;
ASIdentifiers *asid1 = ASIdentifiers_new(), *asid2 = ASIdentifiers_new(),
*asid3 = ASIdentifiers_new(), *asid4 = ASIdentifiers_new();
int testresult = 0;
if (!TEST_ptr(asid1)
|| !TEST_ptr(asid2)
|| !TEST_ptr(asid3))
goto err;
if (!TEST_ptr(val1 = ASN1_INTEGER_new())
|| !TEST_true(ASN1_INTEGER_set_int64(val1, 64496)))
goto err;
if (!TEST_true(X509v3_asid_add_id_or_range(asid1, V3_ASID_ASNUM, val1, NULL)))
goto err;
val1 = NULL;
if (!TEST_ptr(val2 = ASN1_INTEGER_new())
|| !TEST_true(ASN1_INTEGER_set_int64(val2, 64497)))
goto err;
if (!TEST_true(X509v3_asid_add_id_or_range(asid2, V3_ASID_ASNUM, val2, NULL)))
goto err;
val2 = NULL;
if (!TEST_ptr(val1 = ASN1_INTEGER_new())
|| !TEST_true(ASN1_INTEGER_set_int64(val1, 64496))
|| !TEST_ptr(val2 = ASN1_INTEGER_new())
|| !TEST_true(ASN1_INTEGER_set_int64(val2, 64497)))
goto err;
/*
* Just tests V3_ASID_ASNUM for now. Could be extended at some point to also
* test V3_ASID_RDI if we think it is worth it.
*/
if (!TEST_true(X509v3_asid_add_id_or_range(asid3, V3_ASID_ASNUM, val1, val2)))
goto err;
val1 = val2 = NULL;
/* Actual subsets */
if (!TEST_true(X509v3_asid_subset(NULL, NULL))
|| !TEST_true(X509v3_asid_subset(NULL, asid1))
|| !TEST_true(X509v3_asid_subset(asid1, asid1))
|| !TEST_true(X509v3_asid_subset(asid2, asid2))
|| !TEST_true(X509v3_asid_subset(asid1, asid3))
|| !TEST_true(X509v3_asid_subset(asid2, asid3))
|| !TEST_true(X509v3_asid_subset(asid3, asid3))
|| !TEST_true(X509v3_asid_subset(asid4, asid1))
|| !TEST_true(X509v3_asid_subset(asid4, asid2))
|| !TEST_true(X509v3_asid_subset(asid4, asid3)))
goto err;
/* Not subsets */
if (!TEST_false(X509v3_asid_subset(asid1, NULL))
|| !TEST_false(X509v3_asid_subset(asid1, asid2))
|| !TEST_false(X509v3_asid_subset(asid2, asid1))
|| !TEST_false(X509v3_asid_subset(asid3, asid1))
|| !TEST_false(X509v3_asid_subset(asid3, asid2))
|| !TEST_false(X509v3_asid_subset(asid1, asid4))
|| !TEST_false(X509v3_asid_subset(asid2, asid4))
|| !TEST_false(X509v3_asid_subset(asid3, asid4)))
goto err;
testresult = 1;
err:
ASN1_INTEGER_free(val1);
ASN1_INTEGER_free(val2);
ASIdentifiers_free(asid1);
ASIdentifiers_free(asid2);
ASIdentifiers_free(asid3);
ASIdentifiers_free(asid4);
return testresult;
}
static struct ip_ranges_st {
const unsigned int afi;
const char *ip1;
const char *ip2;
int rorp;
} ranges[] = {
{ IANA_AFI_IPV4, "192.168.0.0", "192.168.0.1", IPAddressOrRange_addressPrefix},
{ IANA_AFI_IPV4, "192.168.0.0", "192.168.0.2", IPAddressOrRange_addressRange},
{ IANA_AFI_IPV4, "192.168.0.0", "192.168.0.3", IPAddressOrRange_addressPrefix},
{ IANA_AFI_IPV4, "192.168.0.0", "192.168.0.254", IPAddressOrRange_addressRange},
{ IANA_AFI_IPV4, "192.168.0.0", "192.168.0.255", IPAddressOrRange_addressPrefix},
{ IANA_AFI_IPV4, "192.168.0.1", "192.168.0.255", IPAddressOrRange_addressRange},
{ IANA_AFI_IPV4, "192.168.0.1", "192.168.0.1", IPAddressOrRange_addressPrefix},
{ IANA_AFI_IPV4, "192.168.0.0", "192.168.255.255", IPAddressOrRange_addressPrefix},
{ IANA_AFI_IPV4, "192.168.1.0", "192.168.255.255", IPAddressOrRange_addressRange},
{ IANA_AFI_IPV6, "2001:0db8::0", "2001:0db8::1", IPAddressOrRange_addressPrefix},
{ IANA_AFI_IPV6, "2001:0db8::0", "2001:0db8::2", IPAddressOrRange_addressRange},
{ IANA_AFI_IPV6, "2001:0db8::0", "2001:0db8::3", IPAddressOrRange_addressPrefix},
{ IANA_AFI_IPV6, "2001:0db8::0", "2001:0db8::fffe", IPAddressOrRange_addressRange},
{ IANA_AFI_IPV6, "2001:0db8::0", "2001:0db8::ffff", IPAddressOrRange_addressPrefix},
{ IANA_AFI_IPV6, "2001:0db8::1", "2001:0db8::ffff", IPAddressOrRange_addressRange},
{ IANA_AFI_IPV6, "2001:0db8::1", "2001:0db8::1", IPAddressOrRange_addressPrefix},
{ IANA_AFI_IPV6, "2001:0db8::0:0", "2001:0db8::ffff:ffff", IPAddressOrRange_addressPrefix},
{ IANA_AFI_IPV6, "2001:0db8::1:0", "2001:0db8::ffff:ffff", IPAddressOrRange_addressRange}
};
static int check_addr(IPAddrBlocks *addr, int type)
{
IPAddressFamily *fam;
IPAddressOrRange *aorr;
if (!TEST_int_eq(sk_IPAddressFamily_num(addr), 1))
return 0;
fam = sk_IPAddressFamily_value(addr, 0);
if (!TEST_ptr(fam))
return 0;
if (!TEST_int_eq(fam->ipAddressChoice->type, IPAddressChoice_addressesOrRanges))
return 0;
if (!TEST_int_eq(sk_IPAddressOrRange_num(fam->ipAddressChoice->u.addressesOrRanges), 1))
return 0;
aorr = sk_IPAddressOrRange_value(fam->ipAddressChoice->u.addressesOrRanges, 0);
if (!TEST_ptr(aorr))
return 0;
if (!TEST_int_eq(aorr->type, type))
return 0;
return 1;
}
static int test_addr_ranges(void)
{
IPAddrBlocks *addr = NULL;
ASN1_OCTET_STRING *ip1 = NULL, *ip2 = NULL;
size_t i;
int testresult = 0;
for (i = 0; i < OSSL_NELEM(ranges); i++) {
addr = sk_IPAddressFamily_new_null();
if (!TEST_ptr(addr))
goto end;
/*
* Has the side effect of installing the comparison function onto the
* stack.
*/
if (!TEST_true(X509v3_addr_canonize(addr)))
goto end;
ip1 = a2i_IPADDRESS(ranges[i].ip1);
if (!TEST_ptr(ip1))
goto end;
if (!TEST_true(ip1->length == 4 || ip1->length == 16))
goto end;
ip2 = a2i_IPADDRESS(ranges[i].ip2);
if (!TEST_ptr(ip2))
goto end;
if (!TEST_int_eq(ip2->length, ip1->length))
goto end;
if (!TEST_true(memcmp(ip1->data, ip2->data, ip1->length) <= 0))
goto end;
if (!TEST_true(X509v3_addr_add_range(addr, ranges[i].afi, NULL, ip1->data, ip2->data)))
goto end;
if (!TEST_true(X509v3_addr_is_canonical(addr)))
goto end;
if (!check_addr(addr, ranges[i].rorp))
goto end;
sk_IPAddressFamily_pop_free(addr, IPAddressFamily_free);
addr = NULL;
ASN1_OCTET_STRING_free(ip1);
ASN1_OCTET_STRING_free(ip2);
ip1 = ip2 = NULL;
}
testresult = 1;
end:
sk_IPAddressFamily_pop_free(addr, IPAddressFamily_free);
ASN1_OCTET_STRING_free(ip1);
ASN1_OCTET_STRING_free(ip2);
return testresult;
}
static int test_addr_fam_len(void)
{
int testresult = 0;
IPAddrBlocks *addr = NULL;
IPAddressFamily *f1 = NULL;
ASN1_OCTET_STRING *ip1 = NULL, *ip2 = NULL;
unsigned char key[6];
unsigned int keylen;
unsigned afi = IANA_AFI_IPV4;
/* Create the IPAddrBlocks with a good IPAddressFamily */
addr = sk_IPAddressFamily_new_null();
if (!TEST_ptr(addr))
goto end;
ip1 = a2i_IPADDRESS(ranges[0].ip1);
if (!TEST_ptr(ip1))
goto end;
ip2 = a2i_IPADDRESS(ranges[0].ip2);
if (!TEST_ptr(ip2))
goto end;
if (!TEST_true(X509v3_addr_add_range(addr, ranges[0].afi, NULL, ip1->data, ip2->data)))
goto end;
if (!TEST_true(X509v3_addr_is_canonical(addr)))
goto end;
/* Create our malformed IPAddressFamily */
key[0] = (afi >> 8) & 0xFF;
key[1] = afi & 0xFF;
key[2] = 0xD;
key[3] = 0xE;
key[4] = 0xA;
key[5] = 0xD;
keylen = 6;
if ((f1 = IPAddressFamily_new()) == NULL)
goto end;
if (f1->ipAddressChoice == NULL &&
(f1->ipAddressChoice = IPAddressChoice_new()) == NULL)
goto end;
if (f1->addressFamily == NULL &&
(f1->addressFamily = ASN1_OCTET_STRING_new()) == NULL)
goto end;
if (!ASN1_OCTET_STRING_set(f1->addressFamily, key, keylen))
goto end;
+
+ /* Push and transfer memory ownership to stack */
if (!sk_IPAddressFamily_push(addr, f1))
goto end;
+ f1 = NULL;
/* Shouldn't be able to canonize this as the len is > 3*/
if (!TEST_false(X509v3_addr_canonize(addr)))
goto end;
- /* Create a well formed IPAddressFamily */
- f1 = sk_IPAddressFamily_pop(addr);
- IPAddressFamily_free(f1);
+ /* Pop and free the new stack element */
+ IPAddressFamily_free(sk_IPAddressFamily_pop(addr));
+ /* Create a well-formed IPAddressFamily */
key[0] = (afi >> 8) & 0xFF;
key[1] = afi & 0xFF;
key[2] = 0x1;
keylen = 3;
if ((f1 = IPAddressFamily_new()) == NULL)
goto end;
if (f1->ipAddressChoice == NULL &&
(f1->ipAddressChoice = IPAddressChoice_new()) == NULL)
goto end;
if (f1->addressFamily == NULL &&
(f1->addressFamily = ASN1_OCTET_STRING_new()) == NULL)
goto end;
if (!ASN1_OCTET_STRING_set(f1->addressFamily, key, keylen))
goto end;
/* Mark this as inheritance so we skip some of the is_canonize checks */
f1->ipAddressChoice->type = IPAddressChoice_inherit;
+
+ /* Push and transfer memory ownership to stack */
if (!sk_IPAddressFamily_push(addr, f1))
goto end;
+ f1 = NULL;
/* Should be able to canonize now */
if (!TEST_true(X509v3_addr_canonize(addr)))
goto end;
testresult = 1;
end:
+ /* Free stack and any memory owned by detached element */
+ IPAddressFamily_free(f1);
sk_IPAddressFamily_pop_free(addr, IPAddressFamily_free);
+
ASN1_OCTET_STRING_free(ip1);
ASN1_OCTET_STRING_free(ip2);
return testresult;
}
static struct extvalues_st {
const char *value;
int pass;
} extvalues[] = {
/* No prefix is ok */
{ "sbgp-ipAddrBlock = IPv4:192.0.0.1\n", 1 },
{ "sbgp-ipAddrBlock = IPv4:192.0.0.0/0\n", 1 },
{ "sbgp-ipAddrBlock = IPv4:192.0.0.0/1\n", 1 },
{ "sbgp-ipAddrBlock = IPv4:192.0.0.0/32\n", 1 },
/* Prefix is too long */
{ "sbgp-ipAddrBlock = IPv4:192.0.0.0/33\n", 0 },
/* Unreasonably large prefix */
{ "sbgp-ipAddrBlock = IPv4:192.0.0.0/12341234\n", 0 },
/* Invalid IP addresses */
{ "sbgp-ipAddrBlock = IPv4:192.0.0\n", 0 },
{ "sbgp-ipAddrBlock = IPv4:256.0.0.0\n", 0 },
{ "sbgp-ipAddrBlock = IPv4:-1.0.0.0\n", 0 },
{ "sbgp-ipAddrBlock = IPv4:192.0.0.0.0\n", 0 },
{ "sbgp-ipAddrBlock = IPv3:192.0.0.0\n", 0 },
/* IPv6 */
/* No prefix is ok */
{ "sbgp-ipAddrBlock = IPv6:2001:db8::\n", 1 },
{ "sbgp-ipAddrBlock = IPv6:2001::db8\n", 1 },
{ "sbgp-ipAddrBlock = IPv6:2001:0db8:0000:0000:0000:0000:0000:0000\n", 1 },
{ "sbgp-ipAddrBlock = IPv6:2001:db8::/0\n", 1 },
{ "sbgp-ipAddrBlock = IPv6:2001:db8::/1\n", 1 },
{ "sbgp-ipAddrBlock = IPv6:2001:db8::/32\n", 1 },
{ "sbgp-ipAddrBlock = IPv6:2001:0db8:0000:0000:0000:0000:0000:0000/32\n", 1 },
{ "sbgp-ipAddrBlock = IPv6:2001:db8::/128\n", 1 },
/* Prefix is too long */
{ "sbgp-ipAddrBlock = IPv6:2001:db8::/129\n", 0 },
/* Unreasonably large prefix */
{ "sbgp-ipAddrBlock = IPv6:2001:db8::/12341234\n", 0 },
/* Invalid IP addresses */
/* Not enough blocks of numbers */
{ "sbgp-ipAddrBlock = IPv6:2001:0db8:0000:0000:0000:0000:0000\n", 0 },
/* Too many blocks of numbers */
{ "sbgp-ipAddrBlock = IPv6:2001:0db8:0000:0000:0000:0000:0000:0000:0000\n", 0 },
/* First value too large */
{ "sbgp-ipAddrBlock = IPv6:1ffff:0db8:0000:0000:0000:0000:0000:0000\n", 0 },
/* First value with invalid characters */
{ "sbgp-ipAddrBlock = IPv6:fffg:0db8:0000:0000:0000:0000:0000:0000\n", 0 },
/* First value is negative */
{ "sbgp-ipAddrBlock = IPv6:-1:0db8:0000:0000:0000:0000:0000:0000\n", 0 }
};
static int test_ext_syntax(void)
{
size_t i;
int testresult = 1;
for (i = 0; i < OSSL_NELEM(extvalues); i++) {
X509V3_CTX ctx;
BIO *extbio = BIO_new_mem_buf(extvalues[i].value,
strlen(extvalues[i].value));
CONF *conf;
long eline;
if (!TEST_ptr(extbio))
return 0 ;
conf = NCONF_new_ex(NULL, NULL);
if (!TEST_ptr(conf)) {
BIO_free(extbio);
return 0;
}
if (!TEST_long_gt(NCONF_load_bio(conf, extbio, &eline), 0)) {
testresult = 0;
} else {
X509V3_set_ctx_test(&ctx);
X509V3_set_nconf(&ctx, conf);
if (extvalues[i].pass) {
if (!TEST_true(X509V3_EXT_add_nconf(conf, &ctx, "default",
NULL))) {
TEST_info("Value: %s", extvalues[i].value);
testresult = 0;
}
} else {
ERR_set_mark();
if (!TEST_false(X509V3_EXT_add_nconf(conf, &ctx, "default",
NULL))) {
testresult = 0;
TEST_info("Value: %s", extvalues[i].value);
ERR_clear_last_mark();
} else {
ERR_pop_to_mark();
}
}
}
BIO_free(extbio);
NCONF_free(conf);
}
return testresult;
}
static int test_addr_subset(void)
{
int i;
int ret = 0;
IPAddrBlocks *addrEmpty = NULL;
IPAddrBlocks *addr[3] = { NULL, NULL };
ASN1_OCTET_STRING *ip1[3] = { NULL, NULL };
ASN1_OCTET_STRING *ip2[3] = { NULL, NULL };
int sz = OSSL_NELEM(addr);
for (i = 0; i < sz; ++i) {
/* Create the IPAddrBlocks with a good IPAddressFamily */
if (!TEST_ptr(addr[i] = sk_IPAddressFamily_new_null())
|| !TEST_ptr(ip1[i] = a2i_IPADDRESS(ranges[i].ip1))
|| !TEST_ptr(ip2[i] = a2i_IPADDRESS(ranges[i].ip2))
|| !TEST_true(X509v3_addr_add_range(addr[i], ranges[i].afi, NULL,
ip1[i]->data, ip2[i]->data)))
goto end;
}
ret = TEST_ptr(addrEmpty = sk_IPAddressFamily_new_null())
&& TEST_true(X509v3_addr_subset(NULL, NULL))
&& TEST_true(X509v3_addr_subset(NULL, addr[0]))
&& TEST_true(X509v3_addr_subset(addrEmpty, addr[0]))
&& TEST_true(X509v3_addr_subset(addr[0], addr[0]))
&& TEST_true(X509v3_addr_subset(addr[0], addr[1]))
&& TEST_true(X509v3_addr_subset(addr[0], addr[2]))
&& TEST_true(X509v3_addr_subset(addr[1], addr[2]))
&& TEST_false(X509v3_addr_subset(addr[0], NULL))
&& TEST_false(X509v3_addr_subset(addr[1], addr[0]))
&& TEST_false(X509v3_addr_subset(addr[2], addr[1]))
&& TEST_false(X509v3_addr_subset(addr[0], addrEmpty));
end:
sk_IPAddressFamily_pop_free(addrEmpty, IPAddressFamily_free);
for (i = 0; i < sz; ++i) {
sk_IPAddressFamily_pop_free(addr[i], IPAddressFamily_free);
ASN1_OCTET_STRING_free(ip1[i]);
ASN1_OCTET_STRING_free(ip2[i]);
}
return ret;
}
#endif /* OPENSSL_NO_RFC3779 */
OPT_TEST_DECLARE_USAGE("cert.pem\n")
int setup_tests(void)
{
if (!test_skip_common_options()) {
TEST_error("Error parsing test options\n");
return 0;
}
if (!TEST_ptr(infile = test_get_argument(0)))
return 0;
ADD_TEST(test_pathlen);
#ifndef OPENSSL_NO_RFC3779
ADD_TEST(test_asid);
ADD_TEST(test_addr_ranges);
ADD_TEST(test_ext_syntax);
ADD_TEST(test_addr_fam_len);
ADD_TEST(test_addr_subset);
#endif /* OPENSSL_NO_RFC3779 */
return 1;
}

File Metadata

Mime Type
application/octet-stream
Expires
Sat, Jul 6, 6:47 AM (1 d, 23 h)
Storage Engine
chunks
Storage Format
Chunks
Storage Handle
iNlEtB0F0PLp
Default Alt Text
(4 MB)

Event Timeline