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 19e0fd6e25a5..e41181b5bbb0 100644
--- a/crypto/openssl/CHANGES.md
+++ b/crypto/openssl/CHANGES.md
@@ -1,20083 +1,20117 @@
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.14 and 3.0.15 [3 Sep 2024]
+
+ * Fixed possible denial of service in X.509 name checks.
+
+ Applications performing certificate name checks (e.g., TLS clients checking
+ server certificates) may attempt to read an invalid memory address when
+ comparing the expected name with an `otherName` subject alternative name of
+ an X.509 certificate. This may result in an exception that terminates the
+ application program.
+
+ ([CVE-2024-6119])
+
+ *Viktor Dukhovni*
+
+ * Fixed possible buffer overread in SSL_select_next_proto().
+
+ Calling the OpenSSL API function SSL_select_next_proto with an empty
+ supported client protocols buffer may cause a crash or memory contents
+ to be sent to the peer.
+
+ ([CVE-2024-5535])
+
+ *Matt Caswell*
+
### Changes between 3.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*
+ * Improved EC/DSA nonce generation routines to avoid bias and timing
+ side channel leaks.
+
+ Thanks to Florian Sieck from Universität zu Lübeck and George Pantelakis
+ and Hubert Kario from Red Hat for reporting the issues.
+
+ *Tomáš Mráz and Paul Dale*
+
* 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-6119]: https://www.openssl.org/news/vulnerabilities.html#CVE-2024-6119
+[CVE-2024-5535]: https://www.openssl.org/news/vulnerabilities.html#CVE-2024-5535
[CVE-2024-4741]: https://www.openssl.org/news/vulnerabilities.html#CVE-2024-4741
[CVE-2024-4603]: https://www.openssl.org/news/vulnerabilities.html#CVE-2024-4603
[CVE-2024-2511]: https://www.openssl.org/news/vulnerabilities.html#CVE-2024-2511
[CVE-2024-0727]: https://www.openssl.org/news/vulnerabilities.html#CVE-2024-0727
[CVE-2023-6237]: https://www.openssl.org/news/vulnerabilities.html#CVE-2023-6237
[CVE-2023-6129]: https://www.openssl.org/news/vulnerabilities.html#CVE-2023-6129
[CVE-2023-5678]: https://www.openssl.org/news/vulnerabilities.html#CVE-2023-5678
[CVE-2023-5363]: https://www.openssl.org/news/vulnerabilities.html#CVE-2023-5363
[CVE-2023-4807]: https://www.openssl.org/news/vulnerabilities.html#CVE-2023-4807
[CVE-2023-3817]: https://www.openssl.org/news/vulnerabilities.html#CVE-2023-3817
[CVE-2023-3446]: https://www.openssl.org/news/vulnerabilities.html#CVE-2023-3446
[CVE-2023-2975]: https://www.openssl.org/news/vulnerabilities.html#CVE-2023-2975
[RFC 2578 (STD 58), section 3.5]: https://datatracker.ietf.org/doc/html/rfc2578#section-3.5
[CVE-2023-2650]: https://www.openssl.org/news/vulnerabilities.html#CVE-2023-2650
[CVE-2023-1255]: https://www.openssl.org/news/vulnerabilities.html#CVE-2023-1255
[CVE-2023-0466]: https://www.openssl.org/news/vulnerabilities.html#CVE-2023-0466
[CVE-2023-0465]: https://www.openssl.org/news/vulnerabilities.html#CVE-2023-0465
[CVE-2023-0464]: https://www.openssl.org/news/vulnerabilities.html#CVE-2023-0464
[CVE-2023-0401]: https://www.openssl.org/news/vulnerabilities.html#CVE-2023-0401
[CVE-2023-0286]: https://www.openssl.org/news/vulnerabilities.html#CVE-2023-0286
[CVE-2023-0217]: https://www.openssl.org/news/vulnerabilities.html#CVE-2023-0217
[CVE-2023-0216]: https://www.openssl.org/news/vulnerabilities.html#CVE-2023-0216
[CVE-2023-0215]: https://www.openssl.org/news/vulnerabilities.html#CVE-2023-0215
[CVE-2022-4450]: https://www.openssl.org/news/vulnerabilities.html#CVE-2022-4450
[CVE-2022-4304]: https://www.openssl.org/news/vulnerabilities.html#CVE-2022-4304
[CVE-2022-4203]: https://www.openssl.org/news/vulnerabilities.html#CVE-2022-4203
[CVE-2022-3996]: https://www.openssl.org/news/vulnerabilities.html#CVE-2022-3996
[CVE-2022-2274]: https://www.openssl.org/news/vulnerabilities.html#CVE-2022-2274
[CVE-2022-2097]: https://www.openssl.org/news/vulnerabilities.html#CVE-2022-2097
[CVE-2020-1971]: https://www.openssl.org/news/vulnerabilities.html#CVE-2020-1971
[CVE-2020-1967]: https://www.openssl.org/news/vulnerabilities.html#CVE-2020-1967
[CVE-2019-1563]: https://www.openssl.org/news/vulnerabilities.html#CVE-2019-1563
[CVE-2019-1559]: https://www.openssl.org/news/vulnerabilities.html#CVE-2019-1559
[CVE-2019-1552]: https://www.openssl.org/news/vulnerabilities.html#CVE-2019-1552
[CVE-2019-1551]: https://www.openssl.org/news/vulnerabilities.html#CVE-2019-1551
[CVE-2019-1549]: https://www.openssl.org/news/vulnerabilities.html#CVE-2019-1549
[CVE-2019-1547]: https://www.openssl.org/news/vulnerabilities.html#CVE-2019-1547
[CVE-2019-1543]: https://www.openssl.org/news/vulnerabilities.html#CVE-2019-1543
[CVE-2018-5407]: https://www.openssl.org/news/vulnerabilities.html#CVE-2018-5407
[CVE-2018-0739]: https://www.openssl.org/news/vulnerabilities.html#CVE-2018-0739
[CVE-2018-0737]: https://www.openssl.org/news/vulnerabilities.html#CVE-2018-0737
[CVE-2018-0735]: https://www.openssl.org/news/vulnerabilities.html#CVE-2018-0735
[CVE-2018-0734]: https://www.openssl.org/news/vulnerabilities.html#CVE-2018-0734
[CVE-2018-0733]: https://www.openssl.org/news/vulnerabilities.html#CVE-2018-0733
[CVE-2018-0732]: https://www.openssl.org/news/vulnerabilities.html#CVE-2018-0732
[CVE-2017-3738]: https://www.openssl.org/news/vulnerabilities.html#CVE-2017-3738
[CVE-2017-3737]: https://www.openssl.org/news/vulnerabilities.html#CVE-2017-3737
[CVE-2017-3736]: https://www.openssl.org/news/vulnerabilities.html#CVE-2017-3736
[CVE-2017-3735]: https://www.openssl.org/news/vulnerabilities.html#CVE-2017-3735
[CVE-2017-3733]: https://www.openssl.org/news/vulnerabilities.html#CVE-2017-3733
[CVE-2017-3732]: https://www.openssl.org/news/vulnerabilities.html#CVE-2017-3732
[CVE-2017-3731]: https://www.openssl.org/news/vulnerabilities.html#CVE-2017-3731
[CVE-2017-3730]: https://www.openssl.org/news/vulnerabilities.html#CVE-2017-3730
[CVE-2016-7055]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-7055
[CVE-2016-7054]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-7054
[CVE-2016-7053]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-7053
[CVE-2016-7052]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-7052
[CVE-2016-6309]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-6309
[CVE-2016-6308]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-6308
[CVE-2016-6307]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-6307
[CVE-2016-6306]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-6306
[CVE-2016-6305]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-6305
[CVE-2016-6304]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-6304
[CVE-2016-6303]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-6303
[CVE-2016-6302]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-6302
[CVE-2016-2183]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-2183
[CVE-2016-2182]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-2182
[CVE-2016-2181]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-2181
[CVE-2016-2180]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-2180
[CVE-2016-2179]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-2179
[CVE-2016-2178]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-2178
[CVE-2016-2177]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-2177
[CVE-2016-2176]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-2176
[CVE-2016-2109]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-2109
[CVE-2016-2107]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-2107
[CVE-2016-2106]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-2106
[CVE-2016-2105]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-2105
[CVE-2016-0800]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-0800
[CVE-2016-0799]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-0799
[CVE-2016-0798]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-0798
[CVE-2016-0797]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-0797
[CVE-2016-0705]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-0705
[CVE-2016-0702]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-0702
[CVE-2016-0701]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-0701
[CVE-2015-3197]: https://www.openssl.org/news/vulnerabilities.html#CVE-2015-3197
[CVE-2015-3196]: https://www.openssl.org/news/vulnerabilities.html#CVE-2015-3196
[CVE-2015-3195]: https://www.openssl.org/news/vulnerabilities.html#CVE-2015-3195
[CVE-2015-3194]: https://www.openssl.org/news/vulnerabilities.html#CVE-2015-3194
[CVE-2015-3193]: https://www.openssl.org/news/vulnerabilities.html#CVE-2015-3193
[CVE-2015-1793]: https://www.openssl.org/news/vulnerabilities.html#CVE-2015-1793
[CVE-2015-1792]: https://www.openssl.org/news/vulnerabilities.html#CVE-2015-1792
[CVE-2015-1791]: https://www.openssl.org/news/vulnerabilities.html#CVE-2015-1791
[CVE-2015-1790]: https://www.openssl.org/news/vulnerabilities.html#CVE-2015-1790
[CVE-2015-1789]: https://www.openssl.org/news/vulnerabilities.html#CVE-2015-1789
[CVE-2015-1788]: https://www.openssl.org/news/vulnerabilities.html#CVE-2015-1788
[CVE-2015-1787]: https://www.openssl.org/news/vulnerabilities.html#CVE-2015-1787
[CVE-2015-0293]: https://www.openssl.org/news/vulnerabilities.html#CVE-2015-0293
[CVE-2015-0291]: https://www.openssl.org/news/vulnerabilities.html#CVE-2015-0291
[CVE-2015-0290]: https://www.openssl.org/news/vulnerabilities.html#CVE-2015-0290
[CVE-2015-0289]: https://www.openssl.org/news/vulnerabilities.html#CVE-2015-0289
[CVE-2015-0288]: https://www.openssl.org/news/vulnerabilities.html#CVE-2015-0288
[CVE-2015-0287]: https://www.openssl.org/news/vulnerabilities.html#CVE-2015-0287
[CVE-2015-0286]: https://www.openssl.org/news/vulnerabilities.html#CVE-2015-0286
[CVE-2015-0285]: https://www.openssl.org/news/vulnerabilities.html#CVE-2015-0285
[CVE-2015-0209]: https://www.openssl.org/news/vulnerabilities.html#CVE-2015-0209
[CVE-2015-0208]: https://www.openssl.org/news/vulnerabilities.html#CVE-2015-0208
[CVE-2015-0207]: https://www.openssl.org/news/vulnerabilities.html#CVE-2015-0207
[CVE-2015-0206]: https://www.openssl.org/news/vulnerabilities.html#CVE-2015-0206
[CVE-2015-0205]: https://www.openssl.org/news/vulnerabilities.html#CVE-2015-0205
[CVE-2015-0204]: https://www.openssl.org/news/vulnerabilities.html#CVE-2015-0204
[CVE-2014-8275]: https://www.openssl.org/news/vulnerabilities.html#CVE-2014-8275
[CVE-2014-5139]: https://www.openssl.org/news/vulnerabilities.html#CVE-2014-5139
[CVE-2014-3572]: https://www.openssl.org/news/vulnerabilities.html#CVE-2014-3572
[CVE-2014-3571]: https://www.openssl.org/news/vulnerabilities.html#CVE-2014-3571
[CVE-2014-3570]: https://www.openssl.org/news/vulnerabilities.html#CVE-2014-3570
[CVE-2014-3569]: https://www.openssl.org/news/vulnerabilities.html#CVE-2014-3569
[CVE-2014-3568]: https://www.openssl.org/news/vulnerabilities.html#CVE-2014-3568
[CVE-2014-3567]: https://www.openssl.org/news/vulnerabilities.html#CVE-2014-3567
[CVE-2014-3566]: https://www.openssl.org/news/vulnerabilities.html#CVE-2014-3566
[CVE-2014-3513]: https://www.openssl.org/news/vulnerabilities.html#CVE-2014-3513
[CVE-2014-3512]: https://www.openssl.org/news/vulnerabilities.html#CVE-2014-3512
[CVE-2014-3511]: https://www.openssl.org/news/vulnerabilities.html#CVE-2014-3511
[CVE-2014-3510]: https://www.openssl.org/news/vulnerabilities.html#CVE-2014-3510
[CVE-2014-3509]: https://www.openssl.org/news/vulnerabilities.html#CVE-2014-3509
[CVE-2014-3508]: https://www.openssl.org/news/vulnerabilities.html#CVE-2014-3508
[CVE-2014-3507]: https://www.openssl.org/news/vulnerabilities.html#CVE-2014-3507
[CVE-2014-3506]: https://www.openssl.org/news/vulnerabilities.html#CVE-2014-3506
[CVE-2014-3505]: https://www.openssl.org/news/vulnerabilities.html#CVE-2014-3505
[CVE-2014-3470]: https://www.openssl.org/news/vulnerabilities.html#CVE-2014-3470
[CVE-2014-0224]: https://www.openssl.org/news/vulnerabilities.html#CVE-2014-0224
[CVE-2014-0221]: https://www.openssl.org/news/vulnerabilities.html#CVE-2014-0221
[CVE-2014-0195]: https://www.openssl.org/news/vulnerabilities.html#CVE-2014-0195
[CVE-2014-0160]: https://www.openssl.org/news/vulnerabilities.html#CVE-2014-0160
[CVE-2014-0076]: https://www.openssl.org/news/vulnerabilities.html#CVE-2014-0076
[CVE-2013-6450]: https://www.openssl.org/news/vulnerabilities.html#CVE-2013-6450
[CVE-2013-4353]: https://www.openssl.org/news/vulnerabilities.html#CVE-2013-4353
[CVE-2013-0169]: https://www.openssl.org/news/vulnerabilities.html#CVE-2013-0169
[CVE-2013-0166]: https://www.openssl.org/news/vulnerabilities.html#CVE-2013-0166
[CVE-2012-2686]: https://www.openssl.org/news/vulnerabilities.html#CVE-2012-2686
[CVE-2012-2333]: https://www.openssl.org/news/vulnerabilities.html#CVE-2012-2333
[CVE-2012-2110]: https://www.openssl.org/news/vulnerabilities.html#CVE-2012-2110
[CVE-2012-0884]: https://www.openssl.org/news/vulnerabilities.html#CVE-2012-0884
[CVE-2012-0050]: https://www.openssl.org/news/vulnerabilities.html#CVE-2012-0050
[CVE-2012-0027]: https://www.openssl.org/news/vulnerabilities.html#CVE-2012-0027
[CVE-2011-4619]: https://www.openssl.org/news/vulnerabilities.html#CVE-2011-4619
[CVE-2011-4577]: https://www.openssl.org/news/vulnerabilities.html#CVE-2011-4577
[CVE-2011-4576]: https://www.openssl.org/news/vulnerabilities.html#CVE-2011-4576
[CVE-2011-4109]: https://www.openssl.org/news/vulnerabilities.html#CVE-2011-4109
[CVE-2011-4108]: https://www.openssl.org/news/vulnerabilities.html#CVE-2011-4108
[CVE-2011-3210]: https://www.openssl.org/news/vulnerabilities.html#CVE-2011-3210
[CVE-2011-3207]: https://www.openssl.org/news/vulnerabilities.html#CVE-2011-3207
[CVE-2011-0014]: https://www.openssl.org/news/vulnerabilities.html#CVE-2011-0014
[CVE-2010-4252]: https://www.openssl.org/news/vulnerabilities.html#CVE-2010-4252
[CVE-2010-4180]: https://www.openssl.org/news/vulnerabilities.html#CVE-2010-4180
[CVE-2010-3864]: https://www.openssl.org/news/vulnerabilities.html#CVE-2010-3864
[CVE-2010-1633]: https://www.openssl.org/news/vulnerabilities.html#CVE-2010-1633
[CVE-2010-0740]: https://www.openssl.org/news/vulnerabilities.html#CVE-2010-0740
[CVE-2010-0433]: https://www.openssl.org/news/vulnerabilities.html#CVE-2010-0433
[CVE-2009-4355]: https://www.openssl.org/news/vulnerabilities.html#CVE-2009-4355
[CVE-2009-3555]: https://www.openssl.org/news/vulnerabilities.html#CVE-2009-3555
[CVE-2009-3245]: https://www.openssl.org/news/vulnerabilities.html#CVE-2009-3245
[CVE-2009-1386]: https://www.openssl.org/news/vulnerabilities.html#CVE-2009-1386
[CVE-2009-1379]: https://www.openssl.org/news/vulnerabilities.html#CVE-2009-1379
[CVE-2009-1378]: https://www.openssl.org/news/vulnerabilities.html#CVE-2009-1378
[CVE-2009-1377]: https://www.openssl.org/news/vulnerabilities.html#CVE-2009-1377
[CVE-2009-0789]: https://www.openssl.org/news/vulnerabilities.html#CVE-2009-0789
[CVE-2009-0591]: https://www.openssl.org/news/vulnerabilities.html#CVE-2009-0591
[CVE-2009-0590]: https://www.openssl.org/news/vulnerabilities.html#CVE-2009-0590
[CVE-2008-5077]: https://www.openssl.org/news/vulnerabilities.html#CVE-2008-5077
[CVE-2008-1678]: https://www.openssl.org/news/vulnerabilities.html#CVE-2008-1678
[CVE-2008-1672]: https://www.openssl.org/news/vulnerabilities.html#CVE-2008-1672
[CVE-2008-0891]: https://www.openssl.org/news/vulnerabilities.html#CVE-2008-0891
[CVE-2007-5135]: https://www.openssl.org/news/vulnerabilities.html#CVE-2007-5135
[CVE-2007-4995]: https://www.openssl.org/news/vulnerabilities.html#CVE-2007-4995
[CVE-2006-4343]: https://www.openssl.org/news/vulnerabilities.html#CVE-2006-4343
[CVE-2006-4339]: https://www.openssl.org/news/vulnerabilities.html#CVE-2006-4339
[CVE-2006-3738]: https://www.openssl.org/news/vulnerabilities.html#CVE-2006-3738
[CVE-2006-2940]: https://www.openssl.org/news/vulnerabilities.html#CVE-2006-2940
[CVE-2006-2937]: https://www.openssl.org/news/vulnerabilities.html#CVE-2006-2937
[CVE-2005-2969]: https://www.openssl.org/news/vulnerabilities.html#CVE-2005-2969
[CVE-2004-0112]: https://www.openssl.org/news/vulnerabilities.html#CVE-2004-0112
[CVE-2004-0079]: https://www.openssl.org/news/vulnerabilities.html#CVE-2004-0079
[CVE-2003-0851]: https://www.openssl.org/news/vulnerabilities.html#CVE-2003-0851
[CVE-2003-0545]: https://www.openssl.org/news/vulnerabilities.html#CVE-2003-0545
[CVE-2003-0544]: https://www.openssl.org/news/vulnerabilities.html#CVE-2003-0544
[CVE-2003-0543]: https://www.openssl.org/news/vulnerabilities.html#CVE-2003-0543
[CVE-2003-0078]: https://www.openssl.org/news/vulnerabilities.html#CVE-2003-0078
[CVE-2002-0659]: https://www.openssl.org/news/vulnerabilities.html#CVE-2002-0659
[CVE-2002-0657]: https://www.openssl.org/news/vulnerabilities.html#CVE-2002-0657
[CVE-2002-0656]: https://www.openssl.org/news/vulnerabilities.html#CVE-2002-0656
[CVE-2002-0655]: https://www.openssl.org/news/vulnerabilities.html#CVE-2002-0655
diff --git a/crypto/openssl/CONTRIBUTING.md b/crypto/openssl/CONTRIBUTING.md
index fec6616e21fe..cced15347d05 100644
--- a/crypto/openssl/CONTRIBUTING.md
+++ b/crypto/openssl/CONTRIBUTING.md
@@ -1,112 +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>
+ [Getting Started]: <https://openssl-library.org/community/getting-started>
Development is done on GitHub in the [openssl/openssl] repository.
[openssl/openssl]: <https://github.com/openssl/openssl>
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 [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
+ [coding style]: https://openssl-library.org/policies/technical/coding-style/
+ [documentation policy]: https://openssl-library.org/policies/technical/documentation-policy/
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 1155d9859c56..e74adb50cc3c 100644
--- a/crypto/openssl/Configurations/10-main.conf
+++ b/crypto/openssl/Configurations/10-main.conf
@@ -1,1962 +1,1998 @@
## -*- 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"),
},
+ # To enable openxl compiler for aix
+ # If 17.1 openxl runtime is available, -latomic can be used
+ # instead of -DBROKEN_CLANG_ATOMICS
+ "aix-clang" => {
+ inherit_from => [ "aix-common" ],
+ CC => "ibm-clang",
+ CFLAGS => picker(debug => "-O0 -g",
+ release => "-O"),
+ cflags => combine("-Wno-implicit-function-declaration -mcmodel=large -DBROKEN_CLANG_ATOMICS",
+ threads("-pthread")),
+ ex_libs => add(threads("-pthread")),
+ bn_ops => "BN_LLONG RC4_CHAR",
+ asm_arch => 'ppc32',
+ perlasm_scheme => "aix32",
+ shared_cflag => "-fpic",
+ shared_ldflag => add("-shared"),
+ 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"),
},
+ "aix64-clang" => {
+ inherit_from => [ "aix-common" ],
+ CC => "ibm-clang",
+ CFLAGS => picker(debug => "-O0 -g",
+ release => "-O"),
+ cflags => combine("-maix64 -Wno-implicit-function-declaration -mcmodel=large",
+ threads("-pthread")),
+ ex_libs => add(threads("-pthread")),
+ bn_ops => "SIXTY_FOUR_BIT_LONG RC4_CHAR",
+ asm_arch => 'ppc64',
+ perlasm_scheme => "aix64",
+ shared_cflag => "-fpic",
+ shared_ldflag => add("-shared"),
+ 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 81e3d68bc7f0..84c9cfeb3a14 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" ],
+ disable => [ "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"),
},
"ios-cross" => {
inherit_from => [ "ios-xcrun" ],
CC => "cc",
cflags => add("-isysroot \"\$(CROSS_TOP)/SDKs/\$(CROSS_SDK)\""),
},
"ios64-cross" => {
inherit_from => [ "ios64-xcrun" ],
CC => "cc",
cflags => add("-isysroot \"\$(CROSS_TOP)/SDKs/\$(CROSS_SDK)\""),
},
);
diff --git a/crypto/openssl/Configure b/crypto/openssl/Configure
index 40c03ad0af32..0c60d1da1659 100755
--- a/crypto/openssl/Configure
+++ b/crypto/openssl/Configure
@@ -1,3597 +1,3603 @@
#! /usr/bin/env perl
# -*- mode: 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
## 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') {
+if (!$disabled{asm} && !$predefined_C{__MACH__} && $^O ne 'VMS' && !$predefined_C{_AIX}) {
# 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);
}
+ # realpath() on Windows seems to check if the directory actually exists,
+ # which isn't what is wanted here. All we want to know is if a directory
+ # spec is absolute, not if it exists.
+ if ($^O eq "MSWin32") {
+ 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/FAQ.md b/crypto/openssl/FAQ.md
deleted file mode 100644
index 30f5010ce3a4..000000000000
--- a/crypto/openssl/FAQ.md
+++ /dev/null
@@ -1,6 +0,0 @@
-Frequently Asked Questions (FAQ)
-================================
-
-The [Frequently Asked Questions][FAQ] are now maintained on the OpenSSL homepage.
-
- [FAQ]: https://www.openssl.org/docs/faq.html
diff --git a/crypto/openssl/INSTALL.md b/crypto/openssl/INSTALL.md
index c0dae491c94d..47d64b1a39d8 100644
--- a/crypto/openssl/INSTALL.md
+++ b/crypto/openssl/INSTALL.md
@@ -1,1832 +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 "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
+compiler and then called `Configure`. Starting with version 3.0, 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,
+If the `./config` 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 fb231bcd8459..e0a81703ee8d 100644
--- a/crypto/openssl/NEWS.md
+++ b/crypto/openssl/NEWS.md
@@ -1,1655 +1,1670 @@
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.14 and OpenSSL 3.0.15 [3 Sep 2024]
+
+OpenSSL 3.0.15 is a security patch release. The most severe CVE fixed in this
+release is Moderate.
+
+This release incorporates the following bug fixes and mitigations:
+
+ * Fixed possible denial of service in X.509 name checks
+ ([CVE-2024-6119])
+
+ * Fixed possible buffer overread in SSL_select_next_proto()
+ ([CVE-2024-5535])
+
### Major changes between OpenSSL 3.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-6119]: https://www.openssl.org/news/vulnerabilities.html#CVE-2024-6119
+[CVE-2024-5535]: https://www.openssl.org/news/vulnerabilities.html#CVE-2024-5535
[CVE-2024-4741]: https://www.openssl.org/news/vulnerabilities.html#CVE-2024-4741
[CVE-2024-4603]: https://www.openssl.org/news/vulnerabilities.html#CVE-2024-4603
[CVE-2024-2511]: https://www.openssl.org/news/vulnerabilities.html#CVE-2024-2511
[CVE-2024-0727]: https://www.openssl.org/news/vulnerabilities.html#CVE-2024-0727
[CVE-2023-6237]: https://www.openssl.org/news/vulnerabilities.html#CVE-2023-6237
[CVE-2023-6129]: https://www.openssl.org/news/vulnerabilities.html#CVE-2023-6129
[CVE-2023-5678]: https://www.openssl.org/news/vulnerabilities.html#CVE-2023-5678
[CVE-2023-5363]: https://www.openssl.org/news/vulnerabilities.html#CVE-2023-5363
[CVE-2023-4807]: https://www.openssl.org/news/vulnerabilities.html#CVE-2023-4807
[CVE-2023-3817]: https://www.openssl.org/news/vulnerabilities.html#CVE-2023-3817
[CVE-2023-3446]: https://www.openssl.org/news/vulnerabilities.html#CVE-2023-3446
[CVE-2023-2975]: https://www.openssl.org/news/vulnerabilities.html#CVE-2023-2975
[CVE-2023-2650]: https://www.openssl.org/news/vulnerabilities.html#CVE-2023-2650
[CVE-2023-1255]: https://www.openssl.org/news/vulnerabilities.html#CVE-2023-1255
[CVE-2023-0466]: https://www.openssl.org/news/vulnerabilities.html#CVE-2023-0466
[CVE-2023-0465]: https://www.openssl.org/news/vulnerabilities.html#CVE-2023-0465
[CVE-2023-0464]: https://www.openssl.org/news/vulnerabilities.html#CVE-2023-0464
[CVE-2023-0401]: https://www.openssl.org/news/vulnerabilities.html#CVE-2023-0401
[CVE-2023-0286]: https://www.openssl.org/news/vulnerabilities.html#CVE-2023-0286
[CVE-2023-0217]: https://www.openssl.org/news/vulnerabilities.html#CVE-2023-0217
[CVE-2023-0216]: https://www.openssl.org/news/vulnerabilities.html#CVE-2023-0216
[CVE-2023-0215]: https://www.openssl.org/news/vulnerabilities.html#CVE-2023-0215
[CVE-2022-4450]: https://www.openssl.org/news/vulnerabilities.html#CVE-2022-4450
[CVE-2022-4304]: https://www.openssl.org/news/vulnerabilities.html#CVE-2022-4304
[CVE-2022-4203]: https://www.openssl.org/news/vulnerabilities.html#CVE-2022-4203
[CVE-2022-3996]: https://www.openssl.org/news/vulnerabilities.html#CVE-2022-3996
[CVE-2022-2274]: https://www.openssl.org/news/vulnerabilities.html#CVE-2022-2274
[CVE-2022-2097]: https://www.openssl.org/news/vulnerabilities.html#CVE-2022-2097
[CVE-2020-1971]: https://www.openssl.org/news/vulnerabilities.html#CVE-2020-1971
[CVE-2020-1967]: https://www.openssl.org/news/vulnerabilities.html#CVE-2020-1967
[CVE-2019-1563]: https://www.openssl.org/news/vulnerabilities.html#CVE-2019-1563
[CVE-2019-1559]: https://www.openssl.org/news/vulnerabilities.html#CVE-2019-1559
[CVE-2019-1552]: https://www.openssl.org/news/vulnerabilities.html#CVE-2019-1552
[CVE-2019-1551]: https://www.openssl.org/news/vulnerabilities.html#CVE-2019-1551
[CVE-2019-1549]: https://www.openssl.org/news/vulnerabilities.html#CVE-2019-1549
[CVE-2019-1547]: https://www.openssl.org/news/vulnerabilities.html#CVE-2019-1547
[CVE-2019-1543]: https://www.openssl.org/news/vulnerabilities.html#CVE-2019-1543
[CVE-2018-5407]: https://www.openssl.org/news/vulnerabilities.html#CVE-2018-5407
[CVE-2018-0739]: https://www.openssl.org/news/vulnerabilities.html#CVE-2018-0739
[CVE-2018-0737]: https://www.openssl.org/news/vulnerabilities.html#CVE-2018-0737
[CVE-2018-0735]: https://www.openssl.org/news/vulnerabilities.html#CVE-2018-0735
[CVE-2018-0734]: https://www.openssl.org/news/vulnerabilities.html#CVE-2018-0734
[CVE-2018-0733]: https://www.openssl.org/news/vulnerabilities.html#CVE-2018-0733
[CVE-2018-0732]: https://www.openssl.org/news/vulnerabilities.html#CVE-2018-0732
[CVE-2017-3738]: https://www.openssl.org/news/vulnerabilities.html#CVE-2017-3738
[CVE-2017-3737]: https://www.openssl.org/news/vulnerabilities.html#CVE-2017-3737
[CVE-2017-3736]: https://www.openssl.org/news/vulnerabilities.html#CVE-2017-3736
[CVE-2017-3735]: https://www.openssl.org/news/vulnerabilities.html#CVE-2017-3735
[CVE-2017-3733]: https://www.openssl.org/news/vulnerabilities.html#CVE-2017-3733
[CVE-2017-3732]: https://www.openssl.org/news/vulnerabilities.html#CVE-2017-3732
[CVE-2017-3731]: https://www.openssl.org/news/vulnerabilities.html#CVE-2017-3731
[CVE-2017-3730]: https://www.openssl.org/news/vulnerabilities.html#CVE-2017-3730
[CVE-2016-7055]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-7055
[CVE-2016-7054]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-7054
[CVE-2016-7053]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-7053
[CVE-2016-7052]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-7052
[CVE-2016-6309]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-6309
[CVE-2016-6308]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-6308
[CVE-2016-6307]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-6307
[CVE-2016-6306]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-6306
[CVE-2016-6305]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-6305
[CVE-2016-6304]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-6304
[CVE-2016-6303]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-6303
[CVE-2016-6302]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-6302
[CVE-2016-2183]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-2183
[CVE-2016-2182]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-2182
[CVE-2016-2181]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-2181
[CVE-2016-2180]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-2180
[CVE-2016-2179]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-2179
[CVE-2016-2178]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-2178
[CVE-2016-2177]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-2177
[CVE-2016-2176]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-2176
[CVE-2016-2109]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-2109
[CVE-2016-2107]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-2107
[CVE-2016-2106]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-2106
[CVE-2016-2105]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-2105
[CVE-2016-0800]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-0800
[CVE-2016-0799]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-0799
[CVE-2016-0798]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-0798
[CVE-2016-0797]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-0797
[CVE-2016-0705]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-0705
[CVE-2016-0702]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-0702
[CVE-2016-0701]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-0701
[CVE-2015-3197]: https://www.openssl.org/news/vulnerabilities.html#CVE-2015-3197
[CVE-2015-3196]: https://www.openssl.org/news/vulnerabilities.html#CVE-2015-3196
[CVE-2015-3195]: https://www.openssl.org/news/vulnerabilities.html#CVE-2015-3195
[CVE-2015-3194]: https://www.openssl.org/news/vulnerabilities.html#CVE-2015-3194
[CVE-2015-3193]: https://www.openssl.org/news/vulnerabilities.html#CVE-2015-3193
[CVE-2015-1793]: https://www.openssl.org/news/vulnerabilities.html#CVE-2015-1793
[CVE-2015-1792]: https://www.openssl.org/news/vulnerabilities.html#CVE-2015-1792
[CVE-2015-1791]: https://www.openssl.org/news/vulnerabilities.html#CVE-2015-1791
[CVE-2015-1790]: https://www.openssl.org/news/vulnerabilities.html#CVE-2015-1790
[CVE-2015-1789]: https://www.openssl.org/news/vulnerabilities.html#CVE-2015-1789
[CVE-2015-1788]: https://www.openssl.org/news/vulnerabilities.html#CVE-2015-1788
[CVE-2015-1787]: https://www.openssl.org/news/vulnerabilities.html#CVE-2015-1787
[CVE-2015-0293]: https://www.openssl.org/news/vulnerabilities.html#CVE-2015-0293
[CVE-2015-0291]: https://www.openssl.org/news/vulnerabilities.html#CVE-2015-0291
[CVE-2015-0290]: https://www.openssl.org/news/vulnerabilities.html#CVE-2015-0290
[CVE-2015-0289]: https://www.openssl.org/news/vulnerabilities.html#CVE-2015-0289
[CVE-2015-0288]: https://www.openssl.org/news/vulnerabilities.html#CVE-2015-0288
[CVE-2015-0287]: https://www.openssl.org/news/vulnerabilities.html#CVE-2015-0287
[CVE-2015-0286]: https://www.openssl.org/news/vulnerabilities.html#CVE-2015-0286
[CVE-2015-0285]: https://www.openssl.org/news/vulnerabilities.html#CVE-2015-0285
[CVE-2015-0209]: https://www.openssl.org/news/vulnerabilities.html#CVE-2015-0209
[CVE-2015-0208]: https://www.openssl.org/news/vulnerabilities.html#CVE-2015-0208
[CVE-2015-0207]: https://www.openssl.org/news/vulnerabilities.html#CVE-2015-0207
[CVE-2015-0206]: https://www.openssl.org/news/vulnerabilities.html#CVE-2015-0206
[CVE-2015-0205]: https://www.openssl.org/news/vulnerabilities.html#CVE-2015-0205
[CVE-2015-0204]: https://www.openssl.org/news/vulnerabilities.html#CVE-2015-0204
[CVE-2014-8275]: https://www.openssl.org/news/vulnerabilities.html#CVE-2014-8275
[CVE-2014-5139]: https://www.openssl.org/news/vulnerabilities.html#CVE-2014-5139
[CVE-2014-3572]: https://www.openssl.org/news/vulnerabilities.html#CVE-2014-3572
[CVE-2014-3571]: https://www.openssl.org/news/vulnerabilities.html#CVE-2014-3571
[CVE-2014-3570]: https://www.openssl.org/news/vulnerabilities.html#CVE-2014-3570
[CVE-2014-3569]: https://www.openssl.org/news/vulnerabilities.html#CVE-2014-3569
[CVE-2014-3568]: https://www.openssl.org/news/vulnerabilities.html#CVE-2014-3568
[CVE-2014-3567]: https://www.openssl.org/news/vulnerabilities.html#CVE-2014-3567
[CVE-2014-3566]: https://www.openssl.org/news/vulnerabilities.html#CVE-2014-3566
[CVE-2014-3513]: https://www.openssl.org/news/vulnerabilities.html#CVE-2014-3513
[CVE-2014-3512]: https://www.openssl.org/news/vulnerabilities.html#CVE-2014-3512
[CVE-2014-3511]: https://www.openssl.org/news/vulnerabilities.html#CVE-2014-3511
[CVE-2014-3510]: https://www.openssl.org/news/vulnerabilities.html#CVE-2014-3510
[CVE-2014-3509]: https://www.openssl.org/news/vulnerabilities.html#CVE-2014-3509
[CVE-2014-3508]: https://www.openssl.org/news/vulnerabilities.html#CVE-2014-3508
[CVE-2014-3507]: https://www.openssl.org/news/vulnerabilities.html#CVE-2014-3507
[CVE-2014-3506]: https://www.openssl.org/news/vulnerabilities.html#CVE-2014-3506
[CVE-2014-3505]: https://www.openssl.org/news/vulnerabilities.html#CVE-2014-3505
[CVE-2014-3470]: https://www.openssl.org/news/vulnerabilities.html#CVE-2014-3470
[CVE-2014-0224]: https://www.openssl.org/news/vulnerabilities.html#CVE-2014-0224
[CVE-2014-0221]: https://www.openssl.org/news/vulnerabilities.html#CVE-2014-0221
[CVE-2014-0198]: https://www.openssl.org/news/vulnerabilities.html#CVE-2014-0198
[CVE-2014-0195]: https://www.openssl.org/news/vulnerabilities.html#CVE-2014-0195
[CVE-2014-0160]: https://www.openssl.org/news/vulnerabilities.html#CVE-2014-0160
[CVE-2014-0076]: https://www.openssl.org/news/vulnerabilities.html#CVE-2014-0076
[CVE-2013-6450]: https://www.openssl.org/news/vulnerabilities.html#CVE-2013-6450
[CVE-2013-6449]: https://www.openssl.org/news/vulnerabilities.html#CVE-2013-6449
[CVE-2013-4353]: https://www.openssl.org/news/vulnerabilities.html#CVE-2013-4353
[CVE-2013-0169]: https://www.openssl.org/news/vulnerabilities.html#CVE-2013-0169
[CVE-2013-0166]: https://www.openssl.org/news/vulnerabilities.html#CVE-2013-0166
[CVE-2012-2686]: https://www.openssl.org/news/vulnerabilities.html#CVE-2012-2686
[CVE-2012-2333]: https://www.openssl.org/news/vulnerabilities.html#CVE-2012-2333
[CVE-2012-2110]: https://www.openssl.org/news/vulnerabilities.html#CVE-2012-2110
[CVE-2012-0884]: https://www.openssl.org/news/vulnerabilities.html#CVE-2012-0884
[CVE-2012-0050]: https://www.openssl.org/news/vulnerabilities.html#CVE-2012-0050
[CVE-2012-0027]: https://www.openssl.org/news/vulnerabilities.html#CVE-2012-0027
[CVE-2011-4619]: https://www.openssl.org/news/vulnerabilities.html#CVE-2011-4619
[CVE-2011-4577]: https://www.openssl.org/news/vulnerabilities.html#CVE-2011-4577
[CVE-2011-4576]: https://www.openssl.org/news/vulnerabilities.html#CVE-2011-4576
[CVE-2011-4108]: https://www.openssl.org/news/vulnerabilities.html#CVE-2011-4108
[CVE-2011-3210]: https://www.openssl.org/news/vulnerabilities.html#CVE-2011-3210
[CVE-2011-3207]: https://www.openssl.org/news/vulnerabilities.html#CVE-2011-3207
[CVE-2011-0014]: https://www.openssl.org/news/vulnerabilities.html#CVE-2011-0014
[CVE-2010-5298]: https://www.openssl.org/news/vulnerabilities.html#CVE-2010-5298
[CVE-2010-4252]: https://www.openssl.org/news/vulnerabilities.html#CVE-2010-4252
[CVE-2010-4180]: https://www.openssl.org/news/vulnerabilities.html#CVE-2010-4180
[CVE-2010-3864]: https://www.openssl.org/news/vulnerabilities.html#CVE-2010-3864
[CVE-2010-2939]: https://www.openssl.org/news/vulnerabilities.html#CVE-2010-2939
[CVE-2010-1633]: https://www.openssl.org/news/vulnerabilities.html#CVE-2010-1633
[CVE-2010-0740]: https://www.openssl.org/news/vulnerabilities.html#CVE-2010-0740
[CVE-2010-0433]: https://www.openssl.org/news/vulnerabilities.html#CVE-2010-0433
[CVE-2009-3555]: https://www.openssl.org/news/vulnerabilities.html#CVE-2009-3555
[CVE-2009-0789]: https://www.openssl.org/news/vulnerabilities.html#CVE-2009-0789
[CVE-2009-0591]: https://www.openssl.org/news/vulnerabilities.html#CVE-2009-0591
[CVE-2009-0590]: https://www.openssl.org/news/vulnerabilities.html#CVE-2009-0590
[CVE-2008-5077]: https://www.openssl.org/news/vulnerabilities.html#CVE-2008-5077
[CVE-2006-4343]: https://www.openssl.org/news/vulnerabilities.html#CVE-2006-4343
[CVE-2006-4339]: https://www.openssl.org/news/vulnerabilities.html#CVE-2006-4339
[CVE-2006-3737]: https://www.openssl.org/news/vulnerabilities.html#CVE-2006-3737
[CVE-2006-2940]: https://www.openssl.org/news/vulnerabilities.html#CVE-2006-2940
[CVE-2006-2937]: https://www.openssl.org/news/vulnerabilities.html#CVE-2006-2937
[CVE-2005-2969]: https://www.openssl.org/news/vulnerabilities.html#CVE-2005-2969
diff --git a/crypto/openssl/VERSION.dat b/crypto/openssl/VERSION.dat
index 5de9bf3d01ba..0942ddc200ca 100644
--- a/crypto/openssl/VERSION.dat
+++ b/crypto/openssl/VERSION.dat
@@ -1,7 +1,7 @@
MAJOR=3
MINOR=0
-PATCH=14
+PATCH=15
PRE_RELEASE_TAG=
BUILD_METADATA=
-RELEASE_DATE="4 Jun 2024"
+RELEASE_DATE="3 Sep 2024"
SHLIB_VERSION=3
diff --git a/crypto/openssl/apps/cms.c b/crypto/openssl/apps/cms.c
index 3994cb0fcd58..abb9f196a760 100644
--- a/crypto/openssl/apps/cms.c
+++ b/crypto/openssl/apps/cms.c
@@ -1,1457 +1,1457 @@
/*
- * Copyright 2008-2023 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2008-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
*/
/* CMS utility function */
#include <stdio.h>
#include <string.h>
#include "apps.h"
#include "progs.h"
#include <openssl/crypto.h>
#include <openssl/pem.h>
#include <openssl/err.h>
#include <openssl/x509_vfy.h>
#include <openssl/x509v3.h>
#include <openssl/cms.h>
static int save_certs(char *signerfile, STACK_OF(X509) *signers);
static int cms_cb(int ok, X509_STORE_CTX *ctx);
static void receipt_request_print(CMS_ContentInfo *cms);
static CMS_ReceiptRequest
*make_receipt_request(STACK_OF(OPENSSL_STRING) *rr_to, int rr_allorfirst,
STACK_OF(OPENSSL_STRING) *rr_from);
static int cms_set_pkey_param(EVP_PKEY_CTX *pctx,
STACK_OF(OPENSSL_STRING) *param);
#define SMIME_OP 0x100
#define SMIME_IP 0x200
#define SMIME_SIGNERS 0x400
#define SMIME_ENCRYPT (1 | SMIME_OP)
#define SMIME_DECRYPT (2 | SMIME_IP)
#define SMIME_SIGN (3 | SMIME_OP | SMIME_SIGNERS)
#define SMIME_VERIFY (4 | SMIME_IP)
#define SMIME_RESIGN (5 | SMIME_IP | SMIME_OP | SMIME_SIGNERS)
#define SMIME_SIGN_RECEIPT (6 | SMIME_IP | SMIME_OP)
#define SMIME_VERIFY_RECEIPT (7 | SMIME_IP)
#define SMIME_DIGEST_CREATE (8 | SMIME_OP)
#define SMIME_DIGEST_VERIFY (9 | SMIME_IP)
#define SMIME_COMPRESS (10 | SMIME_OP)
#define SMIME_UNCOMPRESS (11 | SMIME_IP)
#define SMIME_ENCRYPTED_ENCRYPT (12 | SMIME_OP)
#define SMIME_ENCRYPTED_DECRYPT (13 | SMIME_IP)
#define SMIME_DATA_CREATE (14 | SMIME_OP)
#define SMIME_DATA_OUT (15 | SMIME_IP)
#define SMIME_CMSOUT (16 | SMIME_IP | SMIME_OP)
static int verify_err = 0;
typedef struct cms_key_param_st cms_key_param;
struct cms_key_param_st {
int idx;
STACK_OF(OPENSSL_STRING) *param;
cms_key_param *next;
};
typedef enum OPTION_choice {
OPT_COMMON,
OPT_INFORM, OPT_OUTFORM, OPT_IN, OPT_OUT, OPT_ENCRYPT,
OPT_DECRYPT, OPT_SIGN, OPT_CADES, OPT_SIGN_RECEIPT, OPT_RESIGN,
OPT_VERIFY, OPT_VERIFY_RETCODE, OPT_VERIFY_RECEIPT,
OPT_CMSOUT, OPT_DATA_OUT, OPT_DATA_CREATE, OPT_DIGEST_VERIFY,
OPT_DIGEST_CREATE, OPT_COMPRESS, OPT_UNCOMPRESS,
OPT_ED_DECRYPT, OPT_ED_ENCRYPT, OPT_DEBUG_DECRYPT, OPT_TEXT,
OPT_ASCIICRLF, OPT_NOINTERN, OPT_NOVERIFY, OPT_NOCERTS,
OPT_NOATTR, OPT_NODETACH, OPT_NOSMIMECAP, OPT_BINARY, OPT_KEYID,
OPT_NOSIGS, OPT_NO_CONTENT_VERIFY, OPT_NO_ATTR_VERIFY, OPT_INDEF,
OPT_NOINDEF, OPT_CRLFEOL, OPT_NOOUT, OPT_RR_PRINT,
OPT_RR_ALL, OPT_RR_FIRST, OPT_RCTFORM, OPT_CERTFILE, OPT_CAFILE,
OPT_CAPATH, OPT_CASTORE, OPT_NOCAPATH, OPT_NOCAFILE, OPT_NOCASTORE,
OPT_CONTENT, OPT_PRINT, OPT_NAMEOPT,
OPT_SECRETKEY, OPT_SECRETKEYID, OPT_PWRI_PASSWORD, OPT_ECONTENT_TYPE,
OPT_PASSIN, OPT_TO, OPT_FROM, OPT_SUBJECT, OPT_SIGNER, OPT_RECIP,
OPT_CERTSOUT, OPT_MD, OPT_INKEY, OPT_KEYFORM, OPT_KEYOPT, OPT_RR_FROM,
OPT_RR_TO, OPT_AES128_WRAP, OPT_AES192_WRAP, OPT_AES256_WRAP,
OPT_3DES_WRAP, OPT_WRAP, OPT_ENGINE,
OPT_R_ENUM,
OPT_PROV_ENUM, OPT_CONFIG,
OPT_V_ENUM,
OPT_CIPHER,
OPT_ORIGINATOR
} OPTION_CHOICE;
const OPTIONS cms_options[] = {
{OPT_HELP_STR, 1, '-', "Usage: %s [options] [cert...]\n"},
{"help", OPT_HELP, '-', "Display this summary"},
OPT_SECTION("General"),
{"in", OPT_IN, '<', "Input file"},
{"out", OPT_OUT, '>', "Output file"},
OPT_CONFIG_OPTION,
OPT_SECTION("Operation"),
{"encrypt", OPT_ENCRYPT, '-', "Encrypt message"},
{"decrypt", OPT_DECRYPT, '-', "Decrypt encrypted message"},
{"sign", OPT_SIGN, '-', "Sign message"},
{"verify", OPT_VERIFY, '-', "Verify signed message"},
{"resign", OPT_RESIGN, '-', "Resign a signed message"},
{"sign_receipt", OPT_SIGN_RECEIPT, '-',
"Generate a signed receipt for a message"},
{"verify_receipt", OPT_VERIFY_RECEIPT, '<',
"Verify receipts; exit if receipt signatures do not verify"},
{"digest_create", OPT_DIGEST_CREATE, '-',
"Create a CMS \"DigestedData\" object"},
{"digest_verify", OPT_DIGEST_VERIFY, '-',
"Verify a CMS \"DigestedData\" object and output it"},
{"compress", OPT_COMPRESS, '-', "Create a CMS \"CompressedData\" object"},
{"uncompress", OPT_UNCOMPRESS, '-',
"Uncompress a CMS \"CompressedData\" object"},
{"EncryptedData_encrypt", OPT_ED_ENCRYPT, '-',
"Create CMS \"EncryptedData\" object using symmetric key"},
{"EncryptedData_decrypt", OPT_ED_DECRYPT, '-',
"Decrypt CMS \"EncryptedData\" object using symmetric key"},
{"data_create", OPT_DATA_CREATE, '-', "Create a CMS \"Data\" object"},
{"data_out", OPT_DATA_OUT, '-', "Copy CMS \"Data\" object to output"},
{"cmsout", OPT_CMSOUT, '-', "Output CMS structure"},
OPT_SECTION("File format"),
{"inform", OPT_INFORM, 'c', "Input format SMIME (default), PEM or DER"},
{"outform", OPT_OUTFORM, 'c',
"Output format SMIME (default), PEM or DER"},
{"rctform", OPT_RCTFORM, 'F', "Receipt file format"},
{"stream", OPT_INDEF, '-', "Enable CMS streaming"},
{"indef", OPT_INDEF, '-', "Same as -stream"},
{"noindef", OPT_NOINDEF, '-', "Disable CMS streaming"},
{"binary", OPT_BINARY, '-',
"Treat input as binary: do not translate to canonical form"},
{"crlfeol", OPT_CRLFEOL, '-',
- "Use CRLF as EOL termination instead of CR only" },
+ "Use CRLF as EOL termination instead of LF only" },
{"asciicrlf", OPT_ASCIICRLF, '-',
"Perform CRLF canonicalisation when signing"},
OPT_SECTION("Keys and passwords"),
{"pwri_password", OPT_PWRI_PASSWORD, 's',
"Specific password for recipient"},
{"secretkey", OPT_SECRETKEY, 's',
"Use specified hex-encoded key to decrypt/encrypt recipients or content"},
{"secretkeyid", OPT_SECRETKEYID, 's',
"Identity of the -secretkey for CMS \"KEKRecipientInfo\" object"},
{"inkey", OPT_INKEY, 's',
"Input private key (if not signer or recipient)"},
{"passin", OPT_PASSIN, 's', "Input file pass phrase source"},
{"keyopt", OPT_KEYOPT, 's', "Set public key parameters as n:v pairs"},
{"keyform", OPT_KEYFORM, 'f',
"Input private key format (ENGINE, other values ignored)"},
#ifndef OPENSSL_NO_ENGINE
{"engine", OPT_ENGINE, 's', "Use engine e, possibly a hardware device"},
#endif
OPT_PROV_OPTIONS,
OPT_R_OPTIONS,
OPT_SECTION("Encryption and decryption"),
{"originator", OPT_ORIGINATOR, 's', "Originator certificate file"},
{"recip", OPT_RECIP, '<', "Recipient cert file"},
{"cert...", OPT_PARAM, '.',
"Recipient certs (optional; used only when encrypting)"},
{"", OPT_CIPHER, '-',
"The encryption algorithm to use (any supported cipher)"},
{"wrap", OPT_WRAP, 's',
"Key wrap algorithm to use when encrypting with key agreement"},
{"aes128-wrap", OPT_AES128_WRAP, '-', "Use AES128 to wrap key"},
{"aes192-wrap", OPT_AES192_WRAP, '-', "Use AES192 to wrap key"},
{"aes256-wrap", OPT_AES256_WRAP, '-', "Use AES256 to wrap key"},
{"des3-wrap", OPT_3DES_WRAP, '-', "Use 3DES-EDE to wrap key"},
{"debug_decrypt", OPT_DEBUG_DECRYPT, '-',
"Disable MMA protection, return error if no recipient found (see doc)"},
OPT_SECTION("Signing"),
{"md", OPT_MD, 's', "Digest algorithm to use"},
{"signer", OPT_SIGNER, 's', "Signer certificate input file"},
{"certfile", OPT_CERTFILE, '<', "Other certificates file"},
{"cades", OPT_CADES, '-',
"Include signingCertificate attribute (CAdES-BES)"},
{"nodetach", OPT_NODETACH, '-', "Use opaque signing"},
{"nocerts", OPT_NOCERTS, '-',
"Don't include signer's certificate when signing"},
{"noattr", OPT_NOATTR, '-', "Don't include any signed attributes"},
{"nosmimecap", OPT_NOSMIMECAP, '-', "Omit the SMIMECapabilities attribute"},
{"receipt_request_all", OPT_RR_ALL, '-',
"When signing, create a receipt request for all recipients"},
{"receipt_request_first", OPT_RR_FIRST, '-',
"When signing, create a receipt request for first recipient"},
{"receipt_request_from", OPT_RR_FROM, 's',
"Create signed receipt request with specified email address"},
{"receipt_request_to", OPT_RR_TO, 's',
"Create signed receipt targeted to specified address"},
OPT_SECTION("Verification"),
{"signer", OPT_DUP, 's', "Signer certificate(s) output file"},
{"content", OPT_CONTENT, '<',
"Supply or override content for detached signature"},
{"no_content_verify", OPT_NO_CONTENT_VERIFY, '-',
"Do not verify signed content signatures"},
{"no_attr_verify", OPT_NO_ATTR_VERIFY, '-',
"Do not verify signed attribute signatures"},
{"nosigs", OPT_NOSIGS, '-', "Don't verify message signature"},
{"noverify", OPT_NOVERIFY, '-', "Don't verify signers certificate"},
{"nointern", OPT_NOINTERN, '-',
"Don't search certificates in message for signer"},
{"cades", OPT_DUP, '-', "Check signingCertificate (CAdES-BES)"},
{"verify_retcode", OPT_VERIFY_RETCODE, '-',
"Exit non-zero on verification failure"},
{"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("Output"),
{"keyid", OPT_KEYID, '-', "Use subject key identifier"},
{"econtent_type", OPT_ECONTENT_TYPE, 's', "OID for external content"},
{"text", OPT_TEXT, '-', "Include or delete text MIME headers"},
{"certsout", OPT_CERTSOUT, '>', "Certificate output file"},
{"to", OPT_TO, 's', "To address"},
{"from", OPT_FROM, 's', "From address"},
{"subject", OPT_SUBJECT, 's', "Subject"},
OPT_SECTION("Printing"),
{"noout", OPT_NOOUT, '-',
"For the -cmsout operation do not output the parsed CMS structure"},
{"print", OPT_PRINT, '-',
"For the -cmsout operation print out all fields of the CMS structure"},
{"nameopt", OPT_NAMEOPT, 's',
"For the -print option specifies various strings printing options"},
{"receipt_request_print", OPT_RR_PRINT, '-', "Print CMS Receipt Request" },
OPT_V_OPTIONS,
{NULL}
};
static CMS_ContentInfo *load_content_info(int informat, BIO *in, int flags,
BIO **indata, const char *name)
{
CMS_ContentInfo *ret, *ci;
ret = CMS_ContentInfo_new_ex(app_get0_libctx(), app_get0_propq());
if (ret == NULL) {
BIO_printf(bio_err, "Error allocating CMS_contentinfo\n");
return NULL;
}
switch (informat) {
case FORMAT_SMIME:
ci = SMIME_read_CMS_ex(in, flags, indata, &ret);
break;
case FORMAT_PEM:
ci = PEM_read_bio_CMS(in, &ret, NULL, NULL);
break;
case FORMAT_ASN1:
ci = d2i_CMS_bio(in, &ret);
break;
default:
BIO_printf(bio_err, "Bad input format for %s\n", name);
goto err;
}
if (ci == NULL) {
BIO_printf(bio_err, "Error reading %s Content Info\n", name);
goto err;
}
return ret;
err:
CMS_ContentInfo_free(ret);
return NULL;
}
int cms_main(int argc, char **argv)
{
CONF *conf = NULL;
ASN1_OBJECT *econtent_type = NULL;
BIO *in = NULL, *out = NULL, *indata = NULL, *rctin = NULL;
CMS_ContentInfo *cms = NULL, *rcms = NULL;
CMS_ReceiptRequest *rr = NULL;
ENGINE *e = NULL;
EVP_PKEY *key = NULL;
EVP_CIPHER *cipher = NULL, *wrap_cipher = NULL;
EVP_MD *sign_md = NULL;
STACK_OF(OPENSSL_STRING) *rr_to = NULL, *rr_from = NULL;
STACK_OF(OPENSSL_STRING) *sksigners = NULL, *skkeys = NULL;
STACK_OF(X509) *encerts = sk_X509_new_null(), *other = NULL;
X509 *cert = NULL, *recip = NULL, *signer = NULL, *originator = NULL;
X509_STORE *store = NULL;
X509_VERIFY_PARAM *vpm = X509_VERIFY_PARAM_new();
char *certfile = NULL, *keyfile = NULL, *contfile = NULL;
const char *CAfile = NULL, *CApath = NULL, *CAstore = NULL;
char *certsoutfile = NULL, *digestname = NULL, *wrapname = NULL;
int noCAfile = 0, noCApath = 0, noCAstore = 0;
char *infile = NULL, *outfile = NULL, *rctfile = NULL;
char *passinarg = NULL, *passin = NULL, *signerfile = NULL;
char *originatorfile = NULL, *recipfile = NULL, *ciphername = NULL;
char *to = NULL, *from = NULL, *subject = NULL, *prog;
cms_key_param *key_first = NULL, *key_param = NULL;
int flags = CMS_DETACHED, binary_files = 0;
int noout = 0, print = 0, keyidx = -1, vpmtouched = 0;
int informat = FORMAT_SMIME, outformat = FORMAT_SMIME;
int operation = 0, ret = 1, rr_print = 0, rr_allorfirst = -1;
int verify_retcode = 0, rctformat = FORMAT_SMIME, keyform = FORMAT_UNDEF;
size_t secret_keylen = 0, secret_keyidlen = 0;
unsigned char *pwri_pass = NULL, *pwri_tmp = NULL;
unsigned char *secret_key = NULL, *secret_keyid = NULL;
long ltmp;
const char *mime_eol = "\n";
OPTION_CHOICE o;
OSSL_LIB_CTX *libctx = app_get0_libctx();
if (encerts == NULL || vpm == NULL)
goto end;
prog = opt_init(argc, argv, cms_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(cms_options);
ret = 0;
goto end;
case OPT_INFORM:
if (!opt_format(opt_arg(), OPT_FMT_PDS, &informat))
goto opthelp;
break;
case OPT_OUTFORM:
if (!opt_format(opt_arg(), OPT_FMT_PDS, &outformat))
goto opthelp;
break;
case OPT_OUT:
outfile = opt_arg();
break;
case OPT_ENCRYPT:
operation = SMIME_ENCRYPT;
break;
case OPT_DECRYPT:
operation = SMIME_DECRYPT;
break;
case OPT_SIGN:
operation = SMIME_SIGN;
break;
case OPT_VERIFY:
operation = SMIME_VERIFY;
break;
case OPT_RESIGN:
operation = SMIME_RESIGN;
break;
case OPT_SIGN_RECEIPT:
operation = SMIME_SIGN_RECEIPT;
break;
case OPT_VERIFY_RECEIPT:
operation = SMIME_VERIFY_RECEIPT;
rctfile = opt_arg();
break;
case OPT_VERIFY_RETCODE:
verify_retcode = 1;
break;
case OPT_DIGEST_CREATE:
operation = SMIME_DIGEST_CREATE;
break;
case OPT_DIGEST_VERIFY:
operation = SMIME_DIGEST_VERIFY;
break;
case OPT_COMPRESS:
operation = SMIME_COMPRESS;
break;
case OPT_UNCOMPRESS:
operation = SMIME_UNCOMPRESS;
break;
case OPT_ED_ENCRYPT:
operation = SMIME_ENCRYPTED_ENCRYPT;
break;
case OPT_ED_DECRYPT:
operation = SMIME_ENCRYPTED_DECRYPT;
break;
case OPT_DATA_CREATE:
operation = SMIME_DATA_CREATE;
break;
case OPT_DATA_OUT:
operation = SMIME_DATA_OUT;
break;
case OPT_CMSOUT:
operation = SMIME_CMSOUT;
break;
case OPT_DEBUG_DECRYPT:
flags |= CMS_DEBUG_DECRYPT;
break;
case OPT_TEXT:
flags |= CMS_TEXT;
break;
case OPT_ASCIICRLF:
flags |= CMS_ASCIICRLF;
break;
case OPT_NOINTERN:
flags |= CMS_NOINTERN;
break;
case OPT_NOVERIFY:
flags |= CMS_NO_SIGNER_CERT_VERIFY;
break;
case OPT_NOCERTS:
flags |= CMS_NOCERTS;
break;
case OPT_NOATTR:
flags |= CMS_NOATTR;
break;
case OPT_NODETACH:
flags &= ~CMS_DETACHED;
break;
case OPT_NOSMIMECAP:
flags |= CMS_NOSMIMECAP;
break;
case OPT_BINARY:
flags |= CMS_BINARY;
break;
case OPT_CADES:
flags |= CMS_CADES;
break;
case OPT_KEYID:
flags |= CMS_USE_KEYID;
break;
case OPT_NOSIGS:
flags |= CMS_NOSIGS;
break;
case OPT_NO_CONTENT_VERIFY:
flags |= CMS_NO_CONTENT_VERIFY;
break;
case OPT_NO_ATTR_VERIFY:
flags |= CMS_NO_ATTR_VERIFY;
break;
case OPT_INDEF:
flags |= CMS_STREAM;
break;
case OPT_NOINDEF:
flags &= ~CMS_STREAM;
break;
case OPT_CRLFEOL:
mime_eol = "\r\n";
flags |= CMS_CRLFEOL;
break;
case OPT_NOOUT:
noout = 1;
break;
case OPT_RR_PRINT:
rr_print = 1;
break;
case OPT_RR_ALL:
rr_allorfirst = 0;
break;
case OPT_RR_FIRST:
rr_allorfirst = 1;
break;
case OPT_RCTFORM:
if (!opt_format(opt_arg(),
OPT_FMT_PEMDER | OPT_FMT_SMIME, &rctformat))
goto opthelp;
break;
case OPT_CERTFILE:
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_IN:
infile = opt_arg();
break;
case OPT_CONTENT:
contfile = opt_arg();
break;
case OPT_RR_FROM:
if (rr_from == NULL
&& (rr_from = sk_OPENSSL_STRING_new_null()) == NULL)
goto end;
sk_OPENSSL_STRING_push(rr_from, opt_arg());
break;
case OPT_RR_TO:
if (rr_to == NULL
&& (rr_to = sk_OPENSSL_STRING_new_null()) == NULL)
goto end;
sk_OPENSSL_STRING_push(rr_to, opt_arg());
break;
case OPT_PRINT:
noout = print = 1;
break;
case OPT_NAMEOPT:
if (!set_nameopt(opt_arg()))
goto opthelp;
break;
case OPT_SECRETKEY:
if (secret_key != NULL) {
BIO_printf(bio_err, "Invalid key (supplied twice) %s\n",
opt_arg());
goto opthelp;
}
secret_key = OPENSSL_hexstr2buf(opt_arg(), &ltmp);
if (secret_key == NULL) {
BIO_printf(bio_err, "Invalid key %s\n", opt_arg());
goto end;
}
secret_keylen = (size_t)ltmp;
break;
case OPT_SECRETKEYID:
if (secret_keyid != NULL) {
BIO_printf(bio_err, "Invalid id (supplied twice) %s\n",
opt_arg());
goto opthelp;
}
secret_keyid = OPENSSL_hexstr2buf(opt_arg(), &ltmp);
if (secret_keyid == NULL) {
BIO_printf(bio_err, "Invalid id %s\n", opt_arg());
goto opthelp;
}
secret_keyidlen = (size_t)ltmp;
break;
case OPT_PWRI_PASSWORD:
pwri_pass = (unsigned char *)opt_arg();
break;
case OPT_ECONTENT_TYPE:
if (econtent_type != NULL) {
BIO_printf(bio_err, "Invalid OID (supplied twice) %s\n",
opt_arg());
goto opthelp;
}
econtent_type = OBJ_txt2obj(opt_arg(), 0);
if (econtent_type == NULL) {
BIO_printf(bio_err, "Invalid OID %s\n", opt_arg());
goto opthelp;
}
break;
case OPT_ENGINE:
e = setup_engine(opt_arg(), 0);
break;
case OPT_PASSIN:
passinarg = opt_arg();
break;
case OPT_TO:
to = opt_arg();
break;
case OPT_FROM:
from = opt_arg();
break;
case OPT_SUBJECT:
subject = opt_arg();
break;
case OPT_CERTSOUT:
certsoutfile = opt_arg();
break;
case OPT_MD:
digestname = opt_arg();
break;
case OPT_SIGNER:
/* If previous -signer argument add signer to list */
if (signerfile != NULL) {
if (sksigners == NULL
&& (sksigners = sk_OPENSSL_STRING_new_null()) == NULL)
goto end;
sk_OPENSSL_STRING_push(sksigners, signerfile);
if (keyfile == NULL)
keyfile = signerfile;
if (skkeys == NULL
&& (skkeys = sk_OPENSSL_STRING_new_null()) == NULL)
goto end;
sk_OPENSSL_STRING_push(skkeys, keyfile);
keyfile = NULL;
}
signerfile = opt_arg();
break;
case OPT_ORIGINATOR:
originatorfile = opt_arg();
break;
case OPT_INKEY:
/* If previous -inkey argument add signer to list */
if (keyfile != NULL) {
if (signerfile == NULL) {
BIO_puts(bio_err, "Illegal -inkey without -signer\n");
goto end;
}
if (sksigners == NULL
&& (sksigners = sk_OPENSSL_STRING_new_null()) == NULL)
goto end;
sk_OPENSSL_STRING_push(sksigners, signerfile);
signerfile = NULL;
if (skkeys == NULL
&& (skkeys = sk_OPENSSL_STRING_new_null()) == NULL)
goto end;
sk_OPENSSL_STRING_push(skkeys, keyfile);
}
keyfile = opt_arg();
break;
case OPT_KEYFORM:
if (!opt_format(opt_arg(), OPT_FMT_ANY, &keyform))
goto opthelp;
break;
case OPT_RECIP:
if (operation == SMIME_ENCRYPT) {
cert = load_cert(opt_arg(), FORMAT_UNDEF,
"recipient certificate file");
if (cert == NULL)
goto end;
if (!sk_X509_push(encerts, cert))
goto end;
cert = NULL;
} else {
recipfile = opt_arg();
}
break;
case OPT_CIPHER:
ciphername = opt_unknown();
break;
case OPT_KEYOPT:
keyidx = -1;
if (operation == SMIME_ENCRYPT) {
if (sk_X509_num(encerts) > 0)
keyidx += sk_X509_num(encerts);
} else {
if (keyfile != NULL || signerfile != NULL)
keyidx++;
if (skkeys != NULL)
keyidx += sk_OPENSSL_STRING_num(skkeys);
}
if (keyidx < 0) {
BIO_printf(bio_err, "No key specified\n");
goto opthelp;
}
if (key_param == NULL || key_param->idx != keyidx) {
cms_key_param *nparam;
nparam = app_malloc(sizeof(*nparam), "key param buffer");
if ((nparam->param = sk_OPENSSL_STRING_new_null()) == NULL) {
OPENSSL_free(nparam);
goto end;
}
nparam->idx = keyidx;
nparam->next = NULL;
if (key_first == NULL)
key_first = nparam;
else
key_param->next = nparam;
key_param = nparam;
}
sk_OPENSSL_STRING_push(key_param->param, opt_arg());
break;
case OPT_V_CASES:
if (!opt_verify(o, vpm))
goto end;
vpmtouched++;
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_CONFIG:
conf = app_load_config_modules(opt_arg());
if (conf == NULL)
goto end;
break;
case OPT_WRAP:
wrapname = opt_arg();
break;
case OPT_AES128_WRAP:
case OPT_AES192_WRAP:
case OPT_AES256_WRAP:
case OPT_3DES_WRAP:
wrapname = opt_flag() + 1;
break;
}
}
if (!app_RAND_load())
goto end;
if (digestname != NULL) {
if (!opt_md(digestname, &sign_md))
goto end;
}
if (ciphername != NULL) {
if (!opt_cipher_any(ciphername, &cipher))
goto end;
}
if (wrapname != NULL) {
if (!opt_cipher_any(wrapname, &wrap_cipher))
goto end;
}
/* Remaining args are files to process. */
argc = opt_num_rest();
argv = opt_rest();
if ((rr_allorfirst != -1 || rr_from != NULL) && rr_to == NULL) {
BIO_puts(bio_err, "No Signed Receipts Recipients\n");
goto opthelp;
}
if (!(operation & SMIME_SIGNERS) && (rr_to != NULL || rr_from != NULL)) {
BIO_puts(bio_err, "Signed receipts only allowed with -sign\n");
goto opthelp;
}
if (!(operation & SMIME_SIGNERS) && (skkeys != NULL || sksigners != NULL)) {
BIO_puts(bio_err, "Multiple signers or keys not allowed\n");
goto opthelp;
}
if ((flags & CMS_CADES) != 0) {
if ((flags & CMS_NOATTR) != 0) {
BIO_puts(bio_err, "Incompatible options: "
"CAdES requires signed attributes\n");
goto opthelp;
}
if (operation == SMIME_VERIFY
&& (flags & (CMS_NO_SIGNER_CERT_VERIFY | CMS_NO_ATTR_VERIFY)) != 0) {
BIO_puts(bio_err, "Incompatible options: CAdES validation requires"
" certs and signed attributes validations\n");
goto opthelp;
}
}
if (operation & SMIME_SIGNERS) {
if (keyfile != NULL && signerfile == NULL) {
BIO_puts(bio_err, "Illegal -inkey without -signer\n");
goto opthelp;
}
/* Check to see if any final signer needs to be appended */
if (signerfile != NULL) {
if (sksigners == NULL
&& (sksigners = sk_OPENSSL_STRING_new_null()) == NULL)
goto end;
sk_OPENSSL_STRING_push(sksigners, signerfile);
if (skkeys == NULL && (skkeys = sk_OPENSSL_STRING_new_null()) == NULL)
goto end;
if (keyfile == NULL)
keyfile = signerfile;
sk_OPENSSL_STRING_push(skkeys, keyfile);
}
if (sksigners == NULL) {
BIO_printf(bio_err, "No signer certificate specified\n");
goto opthelp;
}
signerfile = NULL;
keyfile = NULL;
} else if (operation == SMIME_DECRYPT) {
if (recipfile == NULL && keyfile == NULL
&& secret_key == NULL && pwri_pass == NULL) {
BIO_printf(bio_err,
"No recipient certificate or key specified\n");
goto opthelp;
}
} else if (operation == SMIME_ENCRYPT) {
if (*argv == NULL && secret_key == NULL
&& pwri_pass == NULL && sk_X509_num(encerts) <= 0) {
BIO_printf(bio_err, "No recipient(s) certificate(s) specified\n");
goto opthelp;
}
} else if (!operation) {
BIO_printf(bio_err, "No operation option (-encrypt|-decrypt|-sign|-verify|...) specified.\n");
goto opthelp;
}
if (!app_passwd(passinarg, NULL, &passin, NULL)) {
BIO_printf(bio_err, "Error getting password\n");
goto end;
}
ret = 2;
if ((operation & SMIME_SIGNERS) == 0) {
if ((flags & CMS_DETACHED) == 0)
BIO_printf(bio_err,
"Warning: -nodetach option is ignored for non-signing operation\n");
flags &= ~CMS_DETACHED;
}
if ((operation & SMIME_IP) == 0 && contfile != NULL)
BIO_printf(bio_err,
"Warning: -contfile option is ignored for the given operation\n");
if (operation != SMIME_ENCRYPT && *argv != NULL)
BIO_printf(bio_err,
"Warning: recipient certificate file parameters ignored for operation other than -encrypt\n");
if ((flags & CMS_BINARY) != 0) {
if (!(operation & SMIME_OP))
outformat = FORMAT_BINARY;
if (!(operation & SMIME_IP))
informat = FORMAT_BINARY;
if ((operation & SMIME_SIGNERS) != 0 && (flags & CMS_DETACHED) != 0)
binary_files = 1;
if ((operation & SMIME_IP) != 0 && contfile == NULL)
binary_files = 1;
}
if (operation == SMIME_ENCRYPT) {
if (!cipher) {
#ifndef OPENSSL_NO_DES
cipher = (EVP_CIPHER *)EVP_des_ede3_cbc();
#else
BIO_printf(bio_err, "No cipher selected\n");
goto end;
#endif
}
if (secret_key && !secret_keyid) {
BIO_printf(bio_err, "No secret key id\n");
goto end;
}
for (; *argv != NULL; argv++) {
cert = load_cert(*argv, FORMAT_UNDEF,
"recipient certificate file");
if (cert == NULL)
goto end;
if (!sk_X509_push(encerts, cert))
goto end;
cert = NULL;
}
}
if (certfile != NULL) {
if (!load_certs(certfile, 0, &other, NULL, "certificate file")) {
ERR_print_errors(bio_err);
goto end;
}
}
if (recipfile != NULL && (operation == SMIME_DECRYPT)) {
if ((recip = load_cert(recipfile, FORMAT_UNDEF,
"recipient certificate file")) == NULL) {
ERR_print_errors(bio_err);
goto end;
}
}
if (originatorfile != NULL) {
if ((originator = load_cert(originatorfile, FORMAT_UNDEF,
"originator certificate file")) == NULL) {
ERR_print_errors(bio_err);
goto end;
}
}
if (operation == SMIME_SIGN_RECEIPT) {
if ((signer = load_cert(signerfile, FORMAT_UNDEF,
"receipt signer certificate file")) == NULL) {
ERR_print_errors(bio_err);
goto end;
}
}
if ((operation == SMIME_DECRYPT) || (operation == SMIME_ENCRYPT)) {
if (keyfile == NULL)
keyfile = recipfile;
} else if ((operation == SMIME_SIGN) || (operation == SMIME_SIGN_RECEIPT)) {
if (keyfile == NULL)
keyfile = signerfile;
} else {
keyfile = NULL;
}
if (keyfile != NULL) {
key = load_key(keyfile, keyform, 0, passin, e, "signing key");
if (key == NULL)
goto end;
}
in = bio_open_default(infile, 'r',
binary_files ? FORMAT_BINARY : informat);
if (in == NULL)
goto end;
if (operation & SMIME_IP) {
cms = load_content_info(informat, in, flags, &indata, "SMIME");
if (cms == NULL)
goto end;
if (contfile != NULL) {
BIO_free(indata);
if ((indata = BIO_new_file(contfile, "rb")) == NULL) {
BIO_printf(bio_err, "Can't read content file %s\n", contfile);
goto end;
}
}
if (certsoutfile != NULL) {
STACK_OF(X509) *allcerts;
allcerts = CMS_get1_certs(cms);
if (!save_certs(certsoutfile, allcerts)) {
BIO_printf(bio_err,
"Error writing certs to %s\n", certsoutfile);
ret = 5;
goto end;
}
sk_X509_pop_free(allcerts, X509_free);
}
}
if (rctfile != NULL) {
char *rctmode = (rctformat == FORMAT_ASN1) ? "rb" : "r";
if ((rctin = BIO_new_file(rctfile, rctmode)) == NULL) {
BIO_printf(bio_err, "Can't open receipt file %s\n", rctfile);
goto end;
}
rcms = load_content_info(rctformat, rctin, 0, NULL, "receipt");
if (rcms == NULL)
goto end;
}
out = bio_open_default(outfile, 'w',
binary_files ? FORMAT_BINARY : outformat);
if (out == NULL)
goto end;
if ((operation == SMIME_VERIFY) || (operation == SMIME_VERIFY_RECEIPT)) {
if ((store = setup_verify(CAfile, noCAfile, CApath, noCApath,
CAstore, noCAstore)) == NULL)
goto end;
X509_STORE_set_verify_cb(store, cms_cb);
if (vpmtouched)
X509_STORE_set1_param(store, vpm);
}
ret = 3;
if (operation == SMIME_DATA_CREATE) {
cms = CMS_data_create_ex(in, flags, libctx, app_get0_propq());
} else if (operation == SMIME_DIGEST_CREATE) {
cms = CMS_digest_create_ex(in, sign_md, flags, libctx, app_get0_propq());
} else if (operation == SMIME_COMPRESS) {
cms = CMS_compress(in, -1, flags);
} else if (operation == SMIME_ENCRYPT) {
int i;
flags |= CMS_PARTIAL;
cms = CMS_encrypt_ex(NULL, in, cipher, flags, libctx, app_get0_propq());
if (cms == NULL)
goto end;
for (i = 0; i < sk_X509_num(encerts); i++) {
CMS_RecipientInfo *ri;
cms_key_param *kparam;
int tflags = flags | CMS_KEY_PARAM;
/* This flag enforces allocating the EVP_PKEY_CTX for the recipient here */
EVP_PKEY_CTX *pctx;
X509 *x = sk_X509_value(encerts, i);
int res;
for (kparam = key_first; kparam; kparam = kparam->next) {
if (kparam->idx == i) {
break;
}
}
ri = CMS_add1_recipient(cms, x, key, originator, tflags);
if (ri == NULL)
goto end;
pctx = CMS_RecipientInfo_get0_pkey_ctx(ri);
if (kparam != NULL) {
if (!cms_set_pkey_param(pctx, kparam->param))
goto end;
}
res = EVP_PKEY_CTX_ctrl(pctx, -1, -1,
EVP_PKEY_CTRL_CIPHER,
EVP_CIPHER_get_nid(cipher), NULL);
if (res <= 0 && res != -2)
goto end;
if (CMS_RecipientInfo_type(ri) == CMS_RECIPINFO_AGREE
&& wrap_cipher != NULL) {
EVP_CIPHER_CTX *wctx;
wctx = CMS_RecipientInfo_kari_get0_ctx(ri);
EVP_EncryptInit_ex(wctx, wrap_cipher, NULL, NULL, NULL);
}
}
if (secret_key != NULL) {
if (!CMS_add0_recipient_key(cms, NID_undef,
secret_key, secret_keylen,
secret_keyid, secret_keyidlen,
NULL, NULL, NULL))
goto end;
/* NULL these because call absorbs them */
secret_key = NULL;
secret_keyid = NULL;
}
if (pwri_pass != NULL) {
pwri_tmp = (unsigned char *)OPENSSL_strdup((char *)pwri_pass);
if (pwri_tmp == NULL)
goto end;
if (CMS_add0_recipient_password(cms,
-1, NID_undef, NID_undef,
pwri_tmp, -1, NULL) == NULL)
goto end;
pwri_tmp = NULL;
}
if (!(flags & CMS_STREAM)) {
if (!CMS_final(cms, in, NULL, flags))
goto end;
}
} else if (operation == SMIME_ENCRYPTED_ENCRYPT) {
cms = CMS_EncryptedData_encrypt_ex(in, cipher, secret_key,
secret_keylen, flags, libctx, app_get0_propq());
} else if (operation == SMIME_SIGN_RECEIPT) {
CMS_ContentInfo *srcms = NULL;
STACK_OF(CMS_SignerInfo) *sis;
CMS_SignerInfo *si;
sis = CMS_get0_SignerInfos(cms);
if (sis == NULL)
goto end;
si = sk_CMS_SignerInfo_value(sis, 0);
srcms = CMS_sign_receipt(si, signer, key, other, flags);
if (srcms == NULL)
goto end;
CMS_ContentInfo_free(cms);
cms = srcms;
} else if (operation & SMIME_SIGNERS) {
int i;
/*
* If detached data content we enable streaming if S/MIME output
* format.
*/
if (operation == SMIME_SIGN) {
if (flags & CMS_DETACHED) {
if (outformat == FORMAT_SMIME)
flags |= CMS_STREAM;
}
flags |= CMS_PARTIAL;
cms = CMS_sign_ex(NULL, NULL, other, in, flags, libctx, app_get0_propq());
if (cms == NULL)
goto end;
if (econtent_type != NULL)
CMS_set1_eContentType(cms, econtent_type);
if (rr_to != NULL
&& ((rr = make_receipt_request(rr_to, rr_allorfirst, rr_from))
== NULL)) {
BIO_puts(bio_err, "Signed Receipt Request Creation Error\n");
goto end;
}
} else {
flags |= CMS_REUSE_DIGEST;
}
for (i = 0; i < sk_OPENSSL_STRING_num(sksigners); i++) {
CMS_SignerInfo *si;
cms_key_param *kparam;
int tflags = flags;
signerfile = sk_OPENSSL_STRING_value(sksigners, i);
keyfile = sk_OPENSSL_STRING_value(skkeys, i);
signer = load_cert(signerfile, FORMAT_UNDEF, "signer certificate");
if (signer == NULL) {
ret = 2;
goto end;
}
key = load_key(keyfile, keyform, 0, passin, e, "signing key");
if (key == NULL) {
ret = 2;
goto end;
}
for (kparam = key_first; kparam; kparam = kparam->next) {
if (kparam->idx == i) {
tflags |= CMS_KEY_PARAM;
break;
}
}
si = CMS_add1_signer(cms, signer, key, sign_md, tflags);
if (si == NULL)
goto end;
if (kparam != NULL) {
EVP_PKEY_CTX *pctx;
pctx = CMS_SignerInfo_get0_pkey_ctx(si);
if (!cms_set_pkey_param(pctx, kparam->param))
goto end;
}
if (rr != NULL && !CMS_add1_ReceiptRequest(si, rr))
goto end;
X509_free(signer);
signer = NULL;
EVP_PKEY_free(key);
key = NULL;
}
/* If not streaming or resigning finalize structure */
if ((operation == SMIME_SIGN) && !(flags & CMS_STREAM)) {
if (!CMS_final(cms, in, NULL, flags))
goto end;
}
}
if (cms == NULL) {
BIO_printf(bio_err, "Error creating CMS structure\n");
goto end;
}
ret = 4;
if (operation == SMIME_DECRYPT) {
if (flags & CMS_DEBUG_DECRYPT)
CMS_decrypt(cms, NULL, NULL, NULL, NULL, flags);
if (secret_key != NULL) {
if (!CMS_decrypt_set1_key(cms,
secret_key, secret_keylen,
secret_keyid, secret_keyidlen)) {
BIO_puts(bio_err, "Error decrypting CMS using secret key\n");
goto end;
}
}
if (key != NULL) {
if (!CMS_decrypt_set1_pkey_and_peer(cms, key, recip, originator)) {
BIO_puts(bio_err, "Error decrypting CMS using private key\n");
goto end;
}
}
if (pwri_pass != NULL) {
if (!CMS_decrypt_set1_password(cms, pwri_pass, -1)) {
BIO_puts(bio_err, "Error decrypting CMS using password\n");
goto end;
}
}
if (!CMS_decrypt(cms, NULL, NULL, indata, out, flags)) {
BIO_printf(bio_err, "Error decrypting CMS structure\n");
goto end;
}
} else if (operation == SMIME_DATA_OUT) {
if (!CMS_data(cms, out, flags))
goto end;
} else if (operation == SMIME_UNCOMPRESS) {
if (!CMS_uncompress(cms, indata, out, flags))
goto end;
} else if (operation == SMIME_DIGEST_VERIFY) {
if (CMS_digest_verify(cms, indata, out, flags) > 0) {
BIO_printf(bio_err, "Verification successful\n");
} else {
BIO_printf(bio_err, "Verification failure\n");
goto end;
}
} else if (operation == SMIME_ENCRYPTED_DECRYPT) {
if (!CMS_EncryptedData_decrypt(cms, secret_key, secret_keylen,
indata, out, flags))
goto end;
} else if (operation == SMIME_VERIFY) {
if (CMS_verify(cms, other, store, indata, out, flags) > 0) {
BIO_printf(bio_err, "%s Verification successful\n",
(flags & CMS_CADES) != 0 ? "CAdES" : "CMS");
} else {
BIO_printf(bio_err, "%s Verification failure\n",
(flags & CMS_CADES) != 0 ? "CAdES" : "CMS");
if (verify_retcode)
ret = verify_err + 32;
goto end;
}
if (signerfile != NULL) {
STACK_OF(X509) *signers = CMS_get0_signers(cms);
if (!save_certs(signerfile, signers)) {
BIO_printf(bio_err,
"Error writing signers to %s\n", signerfile);
ret = 5;
goto end;
}
sk_X509_free(signers);
}
if (rr_print)
receipt_request_print(cms);
} else if (operation == SMIME_VERIFY_RECEIPT) {
if (CMS_verify_receipt(rcms, cms, other, store, flags) > 0) {
BIO_printf(bio_err, "Verification successful\n");
} else {
BIO_printf(bio_err, "Verification failure\n");
goto end;
}
} else {
if (noout) {
if (print) {
ASN1_PCTX *pctx = NULL;
if (get_nameopt() != XN_FLAG_ONELINE) {
pctx = ASN1_PCTX_new();
if (pctx != NULL) { /* Print anyway if malloc failed */
ASN1_PCTX_set_flags(pctx, ASN1_PCTX_FLAGS_SHOW_ABSENT);
ASN1_PCTX_set_str_flags(pctx, get_nameopt());
ASN1_PCTX_set_nm_flags(pctx, get_nameopt());
}
}
CMS_ContentInfo_print_ctx(out, cms, 0, pctx);
ASN1_PCTX_free(pctx);
}
} else if (outformat == FORMAT_SMIME) {
if (to)
BIO_printf(out, "To: %s%s", to, mime_eol);
if (from)
BIO_printf(out, "From: %s%s", from, mime_eol);
if (subject)
BIO_printf(out, "Subject: %s%s", subject, mime_eol);
if (operation == SMIME_RESIGN)
ret = SMIME_write_CMS(out, cms, indata, flags);
else
ret = SMIME_write_CMS(out, cms, in, flags);
} else if (outformat == FORMAT_PEM) {
ret = PEM_write_bio_CMS_stream(out, cms, in, flags);
} else if (outformat == FORMAT_ASN1) {
ret = i2d_CMS_bio_stream(out, cms, in, flags);
} else {
BIO_printf(bio_err, "Bad output format for CMS file\n");
goto end;
}
if (ret <= 0) {
ret = 6;
goto end;
}
}
ret = 0;
end:
if (ret)
ERR_print_errors(bio_err);
sk_X509_pop_free(encerts, X509_free);
sk_X509_pop_free(other, X509_free);
X509_VERIFY_PARAM_free(vpm);
sk_OPENSSL_STRING_free(sksigners);
sk_OPENSSL_STRING_free(skkeys);
OPENSSL_free(secret_key);
OPENSSL_free(secret_keyid);
OPENSSL_free(pwri_tmp);
ASN1_OBJECT_free(econtent_type);
CMS_ReceiptRequest_free(rr);
sk_OPENSSL_STRING_free(rr_to);
sk_OPENSSL_STRING_free(rr_from);
for (key_param = key_first; key_param;) {
cms_key_param *tparam;
sk_OPENSSL_STRING_free(key_param->param);
tparam = key_param->next;
OPENSSL_free(key_param);
key_param = tparam;
}
X509_STORE_free(store);
X509_free(cert);
X509_free(recip);
X509_free(signer);
EVP_PKEY_free(key);
EVP_CIPHER_free(cipher);
EVP_CIPHER_free(wrap_cipher);
EVP_MD_free(sign_md);
CMS_ContentInfo_free(cms);
CMS_ContentInfo_free(rcms);
release_engine(e);
BIO_free(rctin);
BIO_free(in);
BIO_free(indata);
BIO_free_all(out);
OPENSSL_free(passin);
NCONF_free(conf);
return ret;
}
static int save_certs(char *signerfile, STACK_OF(X509) *signers)
{
int i;
BIO *tmp;
if (signerfile == NULL)
return 1;
tmp = BIO_new_file(signerfile, "w");
if (tmp == NULL)
return 0;
for (i = 0; i < sk_X509_num(signers); i++)
PEM_write_bio_X509(tmp, sk_X509_value(signers, i));
BIO_free(tmp);
return 1;
}
/* Minimal callback just to output policy info (if any) */
static int cms_cb(int ok, X509_STORE_CTX *ctx)
{
int error;
error = X509_STORE_CTX_get_error(ctx);
verify_err = error;
if ((error != X509_V_ERR_NO_EXPLICIT_POLICY)
&& ((error != X509_V_OK) || (ok != 2)))
return ok;
policies_print(ctx);
return ok;
}
static void gnames_stack_print(STACK_OF(GENERAL_NAMES) *gns)
{
STACK_OF(GENERAL_NAME) *gens;
GENERAL_NAME *gen;
int i, j;
for (i = 0; i < sk_GENERAL_NAMES_num(gns); i++) {
gens = sk_GENERAL_NAMES_value(gns, i);
for (j = 0; j < sk_GENERAL_NAME_num(gens); j++) {
gen = sk_GENERAL_NAME_value(gens, j);
BIO_puts(bio_err, " ");
GENERAL_NAME_print(bio_err, gen);
BIO_puts(bio_err, "\n");
}
}
return;
}
static void receipt_request_print(CMS_ContentInfo *cms)
{
STACK_OF(CMS_SignerInfo) *sis;
CMS_SignerInfo *si;
CMS_ReceiptRequest *rr;
int allorfirst;
STACK_OF(GENERAL_NAMES) *rto, *rlist;
ASN1_STRING *scid;
int i, rv;
sis = CMS_get0_SignerInfos(cms);
for (i = 0; i < sk_CMS_SignerInfo_num(sis); i++) {
si = sk_CMS_SignerInfo_value(sis, i);
rv = CMS_get1_ReceiptRequest(si, &rr);
BIO_printf(bio_err, "Signer %d:\n", i + 1);
if (rv == 0) {
BIO_puts(bio_err, " No Receipt Request\n");
} else if (rv < 0) {
BIO_puts(bio_err, " Receipt Request Parse Error\n");
ERR_print_errors(bio_err);
} else {
const char *id;
int idlen;
CMS_ReceiptRequest_get0_values(rr, &scid, &allorfirst,
&rlist, &rto);
BIO_puts(bio_err, " Signed Content ID:\n");
idlen = ASN1_STRING_length(scid);
id = (const char *)ASN1_STRING_get0_data(scid);
BIO_dump_indent(bio_err, id, idlen, 4);
BIO_puts(bio_err, " Receipts From");
if (rlist != NULL) {
BIO_puts(bio_err, " List:\n");
gnames_stack_print(rlist);
} else if (allorfirst == 1) {
BIO_puts(bio_err, ": First Tier\n");
} else if (allorfirst == 0) {
BIO_puts(bio_err, ": All\n");
} else {
BIO_printf(bio_err, " Unknown (%d)\n", allorfirst);
}
BIO_puts(bio_err, " Receipts To:\n");
gnames_stack_print(rto);
}
CMS_ReceiptRequest_free(rr);
}
}
static STACK_OF(GENERAL_NAMES) *make_names_stack(STACK_OF(OPENSSL_STRING) *ns)
{
int i;
STACK_OF(GENERAL_NAMES) *ret;
GENERAL_NAMES *gens = NULL;
GENERAL_NAME *gen = NULL;
ret = sk_GENERAL_NAMES_new_null();
if (ret == NULL)
goto err;
for (i = 0; i < sk_OPENSSL_STRING_num(ns); i++) {
char *str = sk_OPENSSL_STRING_value(ns, i);
gen = a2i_GENERAL_NAME(NULL, NULL, NULL, GEN_EMAIL, str, 0);
if (gen == NULL)
goto err;
gens = GENERAL_NAMES_new();
if (gens == NULL)
goto err;
if (!sk_GENERAL_NAME_push(gens, gen))
goto err;
gen = NULL;
if (!sk_GENERAL_NAMES_push(ret, gens))
goto err;
gens = NULL;
}
return ret;
err:
sk_GENERAL_NAMES_pop_free(ret, GENERAL_NAMES_free);
GENERAL_NAMES_free(gens);
GENERAL_NAME_free(gen);
return NULL;
}
static CMS_ReceiptRequest
*make_receipt_request(STACK_OF(OPENSSL_STRING) *rr_to, int rr_allorfirst,
STACK_OF(OPENSSL_STRING) *rr_from)
{
STACK_OF(GENERAL_NAMES) *rct_to = NULL, *rct_from = NULL;
CMS_ReceiptRequest *rr;
rct_to = make_names_stack(rr_to);
if (rct_to == NULL)
goto err;
if (rr_from != NULL) {
rct_from = make_names_stack(rr_from);
if (rct_from == NULL)
goto err;
} else {
rct_from = NULL;
}
rr = CMS_ReceiptRequest_create0_ex(NULL, -1, rr_allorfirst, rct_from,
rct_to, app_get0_libctx());
if (rr == NULL)
goto err;
return rr;
err:
sk_GENERAL_NAMES_pop_free(rct_to, GENERAL_NAMES_free);
sk_GENERAL_NAMES_pop_free(rct_from, GENERAL_NAMES_free);
return NULL;
}
static int cms_set_pkey_param(EVP_PKEY_CTX *pctx,
STACK_OF(OPENSSL_STRING) *param)
{
char *keyopt;
int i;
if (sk_OPENSSL_STRING_num(param) <= 0)
return 1;
for (i = 0; i < sk_OPENSSL_STRING_num(param); i++) {
keyopt = sk_OPENSSL_STRING_value(param, i);
if (pkey_ctrl_string(pctx, keyopt) <= 0) {
BIO_printf(bio_err, "parameter error \"%s\"\n", keyopt);
ERR_print_errors(bio_err);
return 0;
}
}
return 1;
}
diff --git a/crypto/openssl/apps/dgst.c b/crypto/openssl/apps/dgst.c
index 3f02af0d5738..51383bec26ca 100644
--- a/crypto/openssl/apps/dgst.c
+++ b/crypto/openssl/apps/dgst.c
@@ -1,657 +1,658 @@
/*
- * 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 <string.h>
#include <stdlib.h>
#include "apps.h"
#include "progs.h"
#include <openssl/bio.h>
#include <openssl/err.h>
#include <openssl/evp.h>
#include <openssl/objects.h>
#include <openssl/x509.h>
#include <openssl/pem.h>
#include <openssl/hmac.h>
#include <ctype.h>
#undef BUFSIZE
#define BUFSIZE 1024*8
int do_fp(BIO *out, unsigned char *buf, BIO *bp, int sep, int binout, int xoflen,
EVP_PKEY *key, unsigned char *sigin, int siglen,
const char *sig_name, const char *md_name,
const char *file);
static void show_digests(const OBJ_NAME *name, void *bio_);
struct doall_dgst_digests {
BIO *bio;
int n;
};
typedef enum OPTION_choice {
OPT_COMMON,
OPT_LIST,
OPT_C, OPT_R, OPT_OUT, OPT_SIGN, OPT_PASSIN, OPT_VERIFY,
OPT_PRVERIFY, OPT_SIGNATURE, OPT_KEYFORM, OPT_ENGINE, OPT_ENGINE_IMPL,
OPT_HEX, OPT_BINARY, OPT_DEBUG, OPT_FIPS_FINGERPRINT,
OPT_HMAC, OPT_MAC, OPT_SIGOPT, OPT_MACOPT, OPT_XOFLEN,
OPT_DIGEST,
OPT_R_ENUM, OPT_PROV_ENUM
} OPTION_CHOICE;
const OPTIONS dgst_options[] = {
{OPT_HELP_STR, 1, '-', "Usage: %s [options] [file...]\n"},
OPT_SECTION("General"),
{"help", OPT_HELP, '-', "Display this summary"},
{"list", OPT_LIST, '-', "List digests"},
#ifndef OPENSSL_NO_ENGINE
{"engine", OPT_ENGINE, 's', "Use engine e, possibly a hardware device"},
{"engine_impl", OPT_ENGINE_IMPL, '-',
"Also use engine given by -engine for digest operations"},
#endif
{"passin", OPT_PASSIN, 's', "Input file pass phrase source"},
OPT_SECTION("Output"),
{"c", OPT_C, '-', "Print the digest with separating colons"},
{"r", OPT_R, '-', "Print the digest in coreutils format"},
{"out", OPT_OUT, '>', "Output to filename rather than stdout"},
{"keyform", OPT_KEYFORM, 'f', "Key file format (ENGINE, other values ignored)"},
{"hex", OPT_HEX, '-', "Print as hex dump"},
{"binary", OPT_BINARY, '-', "Print in binary form"},
{"xoflen", OPT_XOFLEN, 'p', "Output length for XOF algorithms. To obtain the maximum security strength set this to 32 (or greater) for SHAKE128, and 64 (or greater) for SHAKE256"},
{"d", OPT_DEBUG, '-', "Print debug info"},
{"debug", OPT_DEBUG, '-', "Print debug info"},
OPT_SECTION("Signing"),
{"sign", OPT_SIGN, 's', "Sign digest using private key"},
{"verify", OPT_VERIFY, 's', "Verify a signature using public key"},
{"prverify", OPT_PRVERIFY, 's', "Verify a signature using private key"},
{"sigopt", OPT_SIGOPT, 's', "Signature parameter in n:v form"},
{"signature", OPT_SIGNATURE, '<', "File with signature to verify"},
{"hmac", OPT_HMAC, 's', "Create hashed MAC with key"},
{"mac", OPT_MAC, 's', "Create MAC (not necessarily HMAC)"},
{"macopt", OPT_MACOPT, 's', "MAC algorithm parameters in n:v form or key"},
{"", OPT_DIGEST, '-', "Any supported digest"},
{"fips-fingerprint", OPT_FIPS_FINGERPRINT, '-',
"Compute HMAC with the key used in OpenSSL-FIPS fingerprint"},
OPT_R_OPTIONS,
OPT_PROV_OPTIONS,
OPT_PARAMETERS(),
{"file", 0, 0, "Files to digest (optional; default is stdin)"},
{NULL}
};
int dgst_main(int argc, char **argv)
{
BIO *in = NULL, *inp, *bmd = NULL, *out = NULL;
ENGINE *e = NULL, *impl = NULL;
EVP_PKEY *sigkey = NULL;
STACK_OF(OPENSSL_STRING) *sigopts = NULL, *macopts = NULL;
char *hmac_key = NULL;
char *mac_name = NULL, *digestname = NULL;
char *passinarg = NULL, *passin = NULL;
EVP_MD *md = NULL;
const char *outfile = NULL, *keyfile = NULL, *prog = NULL;
const char *sigfile = NULL;
const char *md_name = NULL;
OPTION_CHOICE o;
int separator = 0, debug = 0, keyform = FORMAT_UNDEF, siglen = 0;
int i, ret = EXIT_FAILURE, out_bin = -1, want_pub = 0, do_verify = 0;
int xoflen = 0;
unsigned char *buf = NULL, *sigbuf = NULL;
int engine_impl = 0;
struct doall_dgst_digests dec;
buf = app_malloc(BUFSIZE, "I/O buffer");
md = (EVP_MD *)EVP_get_digestbyname(argv[0]);
if (md != NULL)
digestname = argv[0];
prog = opt_init(argc, argv, dgst_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(dgst_options);
ret = EXIT_SUCCESS;
goto end;
case OPT_LIST:
BIO_printf(bio_out, "Supported digests:\n");
dec.bio = bio_out;
dec.n = 0;
OBJ_NAME_do_all_sorted(OBJ_NAME_TYPE_MD_METH,
show_digests, &dec);
BIO_printf(bio_out, "\n");
ret = EXIT_SUCCESS;
goto end;
case OPT_C:
separator = 1;
break;
case OPT_R:
separator = 2;
break;
case OPT_R_CASES:
if (!opt_rand(o))
goto end;
break;
case OPT_OUT:
outfile = opt_arg();
break;
case OPT_SIGN:
keyfile = opt_arg();
break;
case OPT_PASSIN:
passinarg = opt_arg();
break;
case OPT_VERIFY:
keyfile = opt_arg();
want_pub = do_verify = 1;
break;
case OPT_PRVERIFY:
keyfile = opt_arg();
do_verify = 1;
break;
case OPT_SIGNATURE:
sigfile = opt_arg();
break;
case OPT_KEYFORM:
if (!opt_format(opt_arg(), OPT_FMT_ANY, &keyform))
goto opthelp;
break;
case OPT_ENGINE:
e = setup_engine(opt_arg(), 0);
break;
case OPT_ENGINE_IMPL:
engine_impl = 1;
break;
case OPT_HEX:
out_bin = 0;
break;
case OPT_BINARY:
out_bin = 1;
break;
case OPT_XOFLEN:
xoflen = atoi(opt_arg());
break;
case OPT_DEBUG:
debug = 1;
break;
case OPT_FIPS_FINGERPRINT:
hmac_key = "etaonrishdlcupfm";
break;
case OPT_HMAC:
hmac_key = opt_arg();
break;
case OPT_MAC:
mac_name = opt_arg();
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_MACOPT:
if (!macopts)
macopts = sk_OPENSSL_STRING_new_null();
if (!macopts || !sk_OPENSSL_STRING_push(macopts, opt_arg()))
goto opthelp;
break;
case OPT_DIGEST:
digestname = opt_unknown();
break;
case OPT_PROV_CASES:
if (!opt_provider(o))
goto end;
break;
}
}
/* Remaining args are files to digest. */
argc = opt_num_rest();
argv = opt_rest();
if (keyfile != NULL && argc > 1) {
BIO_printf(bio_err, "%s: Can only sign or verify one file.\n", prog);
goto end;
}
if (!app_RAND_load())
goto end;
if (digestname != NULL) {
if (!opt_md(digestname, &md))
goto opthelp;
}
if (do_verify && sigfile == NULL) {
BIO_printf(bio_err,
"No signature to verify: use the -signature option\n");
goto end;
}
if (engine_impl)
impl = e;
in = BIO_new(BIO_s_file());
bmd = BIO_new(BIO_f_md());
if (in == NULL || bmd == NULL)
goto end;
if (debug) {
BIO_set_callback_ex(in, BIO_debug_callback_ex);
/* needed for windows 3.1 */
BIO_set_callback_arg(in, (char *)bio_err);
}
if (!app_passwd(passinarg, NULL, &passin, NULL)) {
BIO_printf(bio_err, "Error getting password\n");
goto end;
}
if (out_bin == -1) {
if (keyfile != NULL)
out_bin = 1;
else
out_bin = 0;
}
out = bio_open_default(outfile, 'w', out_bin ? FORMAT_BINARY : FORMAT_TEXT);
if (out == NULL)
goto end;
if ((!(mac_name == NULL) + !(keyfile == NULL) + !(hmac_key == NULL)) > 1) {
BIO_printf(bio_err, "MAC and signing key cannot both be specified\n");
goto end;
}
if (keyfile != NULL) {
int type;
if (want_pub)
sigkey = load_pubkey(keyfile, keyform, 0, NULL, e, "public key");
else
sigkey = load_key(keyfile, keyform, 0, passin, e, "private key");
if (sigkey == NULL) {
/*
* load_[pub]key() has already printed an appropriate message
*/
goto end;
}
type = EVP_PKEY_get_id(sigkey);
if (type == EVP_PKEY_ED25519 || type == EVP_PKEY_ED448) {
/*
* We implement PureEdDSA for these which doesn't have a separate
* digest, and only supports one shot.
*/
BIO_printf(bio_err, "Key type not supported for this operation\n");
goto end;
}
}
if (mac_name != NULL) {
EVP_PKEY_CTX *mac_ctx = NULL;
if (!init_gen_str(&mac_ctx, mac_name, impl, 0, NULL, NULL))
goto end;
if (macopts != NULL) {
for (i = 0; i < sk_OPENSSL_STRING_num(macopts); i++) {
char *macopt = sk_OPENSSL_STRING_value(macopts, i);
if (pkey_ctrl_string(mac_ctx, macopt) <= 0) {
EVP_PKEY_CTX_free(mac_ctx);
BIO_printf(bio_err, "MAC parameter error \"%s\"\n", macopt);
goto end;
}
}
}
sigkey = app_keygen(mac_ctx, mac_name, 0, 0 /* not verbose */);
/* Verbose output would make external-tests gost-engine fail */
EVP_PKEY_CTX_free(mac_ctx);
if (sigkey == NULL)
goto end;
}
if (hmac_key != NULL) {
if (md == NULL) {
md = (EVP_MD *)EVP_sha256();
digestname = SN_sha256;
}
sigkey = EVP_PKEY_new_raw_private_key(EVP_PKEY_HMAC, impl,
(unsigned char *)hmac_key,
strlen(hmac_key));
if (sigkey == NULL)
goto end;
}
if (sigkey != NULL) {
EVP_MD_CTX *mctx = NULL;
EVP_PKEY_CTX *pctx = NULL;
int res;
if (BIO_get_md_ctx(bmd, &mctx) <= 0) {
BIO_printf(bio_err, "Error getting context\n");
goto end;
}
if (do_verify)
if (impl == NULL)
res = EVP_DigestVerifyInit_ex(mctx, &pctx, digestname,
app_get0_libctx(),
app_get0_propq(), sigkey, NULL);
else
res = EVP_DigestVerifyInit(mctx, &pctx, md, impl, sigkey);
else
if (impl == NULL)
res = EVP_DigestSignInit_ex(mctx, &pctx, digestname,
app_get0_libctx(),
app_get0_propq(), sigkey, NULL);
else
res = EVP_DigestSignInit(mctx, &pctx, md, impl, sigkey);
if (res == 0) {
BIO_printf(bio_err, "Error setting context\n");
goto end;
}
if (sigopts != NULL) {
for (i = 0; i < sk_OPENSSL_STRING_num(sigopts); i++) {
char *sigopt = sk_OPENSSL_STRING_value(sigopts, i);
if (pkey_ctrl_string(pctx, sigopt) <= 0) {
BIO_printf(bio_err, "Signature parameter error \"%s\"\n",
sigopt);
goto end;
}
}
}
}
/* we use md as a filter, reading from 'in' */
else {
EVP_MD_CTX *mctx = NULL;
if (BIO_get_md_ctx(bmd, &mctx) <= 0) {
BIO_printf(bio_err, "Error getting context\n");
goto end;
}
if (md == NULL)
md = (EVP_MD *)EVP_sha256();
if (!EVP_DigestInit_ex(mctx, md, impl)) {
BIO_printf(bio_err, "Error setting digest\n");
goto end;
}
}
if (sigfile != NULL && sigkey != NULL) {
BIO *sigbio = BIO_new_file(sigfile, "rb");
if (sigbio == NULL) {
BIO_printf(bio_err, "Error opening signature file %s\n", sigfile);
goto end;
}
siglen = EVP_PKEY_get_size(sigkey);
sigbuf = app_malloc(siglen, "signature buffer");
siglen = BIO_read(sigbio, sigbuf, siglen);
BIO_free(sigbio);
if (siglen <= 0) {
BIO_printf(bio_err, "Error reading signature file %s\n", sigfile);
goto end;
}
}
inp = BIO_push(bmd, in);
if (md == NULL) {
EVP_MD_CTX *tctx;
BIO_get_md_ctx(bmd, &tctx);
md = EVP_MD_CTX_get1_md(tctx);
}
if (md != NULL)
md_name = EVP_MD_get0_name(md);
if (xoflen > 0) {
if (!(EVP_MD_get_flags(md) & EVP_MD_FLAG_XOF)) {
BIO_printf(bio_err, "Length can only be specified for XOF\n");
goto end;
}
/*
* Signing using XOF is not supported by any algorithms currently since
* each algorithm only calls EVP_DigestFinal_ex() in their sign_final
* and verify_final methods.
*/
if (sigkey != NULL) {
BIO_printf(bio_err, "Signing key cannot be specified for XOF\n");
goto end;
}
}
if (argc == 0) {
BIO_set_fp(in, stdin, BIO_NOCLOSE);
ret = do_fp(out, buf, inp, separator, out_bin, xoflen, sigkey, sigbuf,
siglen, NULL, md_name, "stdin");
} else {
const char *sig_name = NULL;
if (out_bin == 0) {
if (sigkey != NULL)
sig_name = EVP_PKEY_get0_type_name(sigkey);
}
ret = EXIT_SUCCESS;
for (i = 0; i < argc; i++) {
if (BIO_read_filename(in, argv[i]) <= 0) {
perror(argv[i]);
ret = EXIT_FAILURE;
continue;
} else {
if (do_fp(out, buf, inp, separator, out_bin, xoflen,
sigkey, sigbuf, siglen, sig_name, md_name, argv[i]))
ret = EXIT_FAILURE;
}
(void)BIO_reset(bmd);
}
}
end:
if (ret != EXIT_SUCCESS)
ERR_print_errors(bio_err);
OPENSSL_clear_free(buf, BUFSIZE);
BIO_free(in);
OPENSSL_free(passin);
BIO_free_all(out);
EVP_MD_free(md);
EVP_PKEY_free(sigkey);
sk_OPENSSL_STRING_free(sigopts);
sk_OPENSSL_STRING_free(macopts);
OPENSSL_free(sigbuf);
BIO_free(bmd);
release_engine(e);
return ret;
}
static void show_digests(const OBJ_NAME *name, void *arg)
{
struct doall_dgst_digests *dec = (struct doall_dgst_digests *)arg;
- const EVP_MD *md = NULL;
+ EVP_MD *md = NULL;
/* Filter out signed digests (a.k.a signature algorithms) */
if (strstr(name->name, "rsa") != NULL || strstr(name->name, "RSA") != NULL)
return;
if (!islower((unsigned char)*name->name))
return;
/* Filter out message digests that we cannot use */
md = EVP_MD_fetch(app_get0_libctx(), name->name, app_get0_propq());
if (md == NULL) {
- md = EVP_get_digestbyname(name->name);
- if (md == NULL)
+ if (EVP_get_digestbyname(name->name) == NULL)
return;
}
BIO_printf(dec->bio, "-%-25s", name->name);
if (++dec->n == 3) {
BIO_printf(dec->bio, "\n");
dec->n = 0;
} else {
BIO_printf(dec->bio, " ");
}
+
+ EVP_MD_free(md);
}
/*
* The newline_escape_filename function performs newline escaping for any
* filename that contains a newline. This function also takes a pointer
* to backslash. The backslash pointer is a flag to indicating whether a newline
* is present in the filename. If a newline is present, the backslash flag is
* set and the output format will contain a backslash at the beginning of the
* digest output. This output format is to replicate the output format found
* in the '*sum' checksum programs. This aims to preserve backward
* compatibility.
*/
static const char *newline_escape_filename(const char *file, int * backslash)
{
size_t i, e = 0, length = strlen(file), newline_count = 0, mem_len = 0;
char *file_cpy = NULL;
for (i = 0; i < length; i++)
if (file[i] == '\n')
newline_count++;
mem_len = length + newline_count + 1;
file_cpy = app_malloc(mem_len, file);
i = 0;
while(e < length) {
const char c = file[e];
if (c == '\n') {
file_cpy[i++] = '\\';
file_cpy[i++] = 'n';
*backslash = 1;
} else {
file_cpy[i++] = c;
}
e++;
}
file_cpy[i] = '\0';
return (const char*)file_cpy;
}
int do_fp(BIO *out, unsigned char *buf, BIO *bp, int sep, int binout, int xoflen,
EVP_PKEY *key, unsigned char *sigin, int siglen,
const char *sig_name, const char *md_name,
const char *file)
{
size_t len = BUFSIZE;
int i, backslash = 0, ret = EXIT_FAILURE;
unsigned char *allocated_buf = NULL;
while (BIO_pending(bp) || !BIO_eof(bp)) {
i = BIO_read(bp, (char *)buf, BUFSIZE);
if (i < 0) {
BIO_printf(bio_err, "Read error in %s\n", file);
goto end;
}
if (i == 0)
break;
}
if (sigin != NULL) {
EVP_MD_CTX *ctx;
BIO_get_md_ctx(bp, &ctx);
i = EVP_DigestVerifyFinal(ctx, sigin, (unsigned int)siglen);
if (i > 0) {
BIO_printf(out, "Verified OK\n");
} else if (i == 0) {
BIO_printf(out, "Verification failure\n");
goto end;
} else {
BIO_printf(bio_err, "Error verifying data\n");
goto end;
}
ret = EXIT_SUCCESS;
goto end;
}
if (key != NULL) {
EVP_MD_CTX *ctx;
size_t tmplen;
BIO_get_md_ctx(bp, &ctx);
if (!EVP_DigestSignFinal(ctx, NULL, &tmplen)) {
BIO_printf(bio_err, "Error getting maximum length of signed data\n");
goto end;
}
if (tmplen > BUFSIZE) {
len = tmplen;
allocated_buf = app_malloc(len, "Signature buffer");
buf = allocated_buf;
}
if (!EVP_DigestSignFinal(ctx, buf, &len)) {
BIO_printf(bio_err, "Error signing data\n");
goto end;
}
} else if (xoflen > 0) {
EVP_MD_CTX *ctx;
len = xoflen;
if (len > BUFSIZE) {
allocated_buf = app_malloc(len, "Digest buffer");
buf = allocated_buf;
}
BIO_get_md_ctx(bp, &ctx);
if (!EVP_DigestFinalXOF(ctx, buf, len)) {
BIO_printf(bio_err, "Error Digesting Data\n");
goto end;
}
} else {
len = BIO_gets(bp, (char *)buf, BUFSIZE);
if ((int)len < 0)
goto end;
}
if (binout) {
BIO_write(out, buf, len);
} else if (sep == 2) {
file = newline_escape_filename(file, &backslash);
if (backslash == 1)
BIO_puts(out, "\\");
for (i = 0; i < (int)len; i++)
BIO_printf(out, "%02x", buf[i]);
BIO_printf(out, " *%s\n", file);
OPENSSL_free((char *)file);
} else {
if (sig_name != NULL) {
BIO_puts(out, sig_name);
if (md_name != NULL)
BIO_printf(out, "-%s", md_name);
BIO_printf(out, "(%s)= ", file);
} else if (md_name != NULL) {
BIO_printf(out, "%s(%s)= ", md_name, file);
} else {
BIO_printf(out, "(%s)= ", file);
}
for (i = 0; i < (int)len; i++) {
if (sep && (i != 0))
BIO_printf(out, ":");
BIO_printf(out, "%02x", buf[i]);
}
BIO_printf(out, "\n");
}
ret = EXIT_SUCCESS;
end:
if (allocated_buf != NULL)
OPENSSL_clear_free(allocated_buf, len);
return ret;
}
diff --git a/crypto/openssl/apps/lib/opt.c b/crypto/openssl/apps/lib/opt.c
index d56964dbe7ba..88db9ad6947b 100644
--- a/crypto/openssl/apps/lib/opt.c
+++ b/crypto/openssl/apps/lib/opt.c
@@ -1,1203 +1,1203 @@
/*
- * 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
*/
/*
* This file is also used by the test suite. Do not #include "apps.h".
*/
#include "opt.h"
#include "fmt.h"
#include "app_libctx.h"
#include "internal/nelem.h"
#include "internal/numbers.h"
#include <string.h>
#if !defined(OPENSSL_SYS_MSDOS)
# include <unistd.h>
#endif
#include <stdlib.h>
#include <errno.h>
#include <ctype.h>
#include <limits.h>
#include <openssl/err.h>
#include <openssl/bio.h>
#include <openssl/x509v3.h>
#define MAX_OPT_HELP_WIDTH 30
const char OPT_HELP_STR[] = "-H";
const char OPT_MORE_STR[] = "-M";
const char OPT_SECTION_STR[] = "-S";
const char OPT_PARAM_STR[] = "-P";
/* Our state */
static char **argv;
static int argc;
static int opt_index;
static char *arg;
static char *flag;
static char *dunno;
static const OPTIONS *unknown;
static const OPTIONS *opts;
static char prog[40];
/*
* Return the simple name of the program; removing various platform gunk.
*/
#if defined(OPENSSL_SYS_WIN32)
const char *opt_path_end(const char *filename)
{
const char *p;
/* find the last '/', '\' or ':' */
for (p = filename + strlen(filename); --p > filename; )
if (*p == '/' || *p == '\\' || *p == ':') {
p++;
break;
}
return p;
}
char *opt_progname(const char *argv0)
{
size_t i, n;
const char *p;
char *q;
p = opt_path_end(argv0);
/* Strip off trailing nonsense. */
n = strlen(p);
if (n > 4 &&
(strcmp(&p[n - 4], ".exe") == 0 || strcmp(&p[n - 4], ".EXE") == 0))
n -= 4;
/* Copy over the name, in lowercase. */
if (n > sizeof(prog) - 1)
n = sizeof(prog) - 1;
for (q = prog, i = 0; i < n; i++, p++)
*q++ = tolower((unsigned char)*p);
*q = '\0';
return prog;
}
#elif defined(OPENSSL_SYS_VMS)
const char *opt_path_end(const char *filename)
{
const char *p;
/* Find last special character sys:[foo.bar]openssl */
for (p = filename + strlen(filename); --p > filename;)
if (*p == ':' || *p == ']' || *p == '>') {
p++;
break;
}
return p;
}
char *opt_progname(const char *argv0)
{
const char *p, *q;
/* Find last special character sys:[foo.bar]openssl */
p = opt_path_end(argv0);
q = strrchr(p, '.');
if (prog != p)
strncpy(prog, p, sizeof(prog) - 1);
prog[sizeof(prog) - 1] = '\0';
if (q != NULL && q - p < sizeof(prog))
prog[q - p] = '\0';
return prog;
}
#else
const char *opt_path_end(const char *filename)
{
const char *p;
/* Could use strchr, but this is like the ones above. */
for (p = filename + strlen(filename); --p > filename;)
if (*p == '/') {
p++;
break;
}
return p;
}
char *opt_progname(const char *argv0)
{
const char *p;
p = opt_path_end(argv0);
if (prog != p)
strncpy(prog, p, sizeof(prog) - 1);
prog[sizeof(prog) - 1] = '\0';
return prog;
}
#endif
char *opt_appname(const char *argv0)
{
size_t len = strlen(prog);
if (argv0 != NULL)
BIO_snprintf(prog + len, sizeof(prog) - len - 1, " %s", argv0);
return prog;
}
char *opt_getprog(void)
{
return prog;
}
/* Set up the arg parsing. */
char *opt_init(int ac, char **av, const OPTIONS *o)
{
/* Store state. */
argc = ac;
argv = av;
opt_begin();
opts = o;
unknown = NULL;
/* Make sure prog name is set for usage output */
(void)opt_progname(argv[0]);
/* Check all options up until the PARAM marker (if present) */
for (; o->name != NULL && o->name != OPT_PARAM_STR; ++o) {
#ifndef NDEBUG
const OPTIONS *next;
int duplicated, i;
#endif
if (o->name == OPT_HELP_STR
|| o->name == OPT_MORE_STR
|| o->name == OPT_SECTION_STR)
continue;
#ifndef NDEBUG
i = o->valtype;
/* Make sure options are legit. */
OPENSSL_assert(o->name[0] != '-');
if (o->valtype == '.')
OPENSSL_assert(o->retval == OPT_PARAM);
else
OPENSSL_assert(o->retval == OPT_DUP || o->retval > OPT_PARAM);
switch (i) {
case 0: case '-': case '.':
case '/': case '<': case '>': case 'E': case 'F':
case 'M': case 'U': case 'f': case 'l': case 'n': case 'p': case 's':
case 'u': case 'c': case ':': case 'N':
break;
default:
OPENSSL_assert(0);
}
/* Make sure there are no duplicates. */
for (next = o + 1; next->name; ++next) {
/*
* Some compilers inline strcmp and the assert string is too long.
*/
duplicated = next->retval != OPT_DUP
&& strcmp(o->name, next->name) == 0;
if (duplicated) {
opt_printf_stderr("%s: Internal error: duplicate option %s\n",
prog, o->name);
OPENSSL_assert(!duplicated);
}
}
#endif
if (o->name[0] == '\0') {
OPENSSL_assert(unknown == NULL);
unknown = o;
OPENSSL_assert(unknown->valtype == 0 || unknown->valtype == '-');
}
}
return prog;
}
static OPT_PAIR formats[] = {
{"PEM/DER", OPT_FMT_PEMDER},
{"pkcs12", OPT_FMT_PKCS12},
{"smime", OPT_FMT_SMIME},
{"engine", OPT_FMT_ENGINE},
{"msblob", OPT_FMT_MSBLOB},
{"nss", OPT_FMT_NSS},
{"text", OPT_FMT_TEXT},
{"http", OPT_FMT_HTTP},
{"pvk", OPT_FMT_PVK},
{NULL}
};
/* Print an error message about a failed format parse. */
static int opt_format_error(const char *s, unsigned long flags)
{
OPT_PAIR *ap;
if (flags == OPT_FMT_PEMDER) {
opt_printf_stderr("%s: Bad format \"%s\"; must be pem or der\n",
prog, s);
} else {
opt_printf_stderr("%s: Bad format \"%s\"; must be one of:\n",
prog, s);
for (ap = formats; ap->name; ap++)
if (flags & ap->retval)
opt_printf_stderr(" %s\n", ap->name);
}
return 0;
}
/* Parse a format string, put it into *result; return 0 on failure, else 1. */
int opt_format(const char *s, unsigned long flags, int *result)
{
switch (*s) {
default:
opt_printf_stderr("%s: Bad format \"%s\"\n", prog, s);
return 0;
case 'D':
case 'd':
if ((flags & OPT_FMT_PEMDER) == 0)
return opt_format_error(s, flags);
*result = FORMAT_ASN1;
break;
case 'T':
case 't':
if ((flags & OPT_FMT_TEXT) == 0)
return opt_format_error(s, flags);
*result = FORMAT_TEXT;
break;
case 'N':
case 'n':
if ((flags & OPT_FMT_NSS) == 0)
return opt_format_error(s, flags);
if (strcmp(s, "NSS") != 0 && strcmp(s, "nss") != 0)
return opt_format_error(s, flags);
*result = FORMAT_NSS;
break;
case 'S':
case 's':
if ((flags & OPT_FMT_SMIME) == 0)
return opt_format_error(s, flags);
*result = FORMAT_SMIME;
break;
case 'M':
case 'm':
if ((flags & OPT_FMT_MSBLOB) == 0)
return opt_format_error(s, flags);
*result = FORMAT_MSBLOB;
break;
case 'E':
case 'e':
if ((flags & OPT_FMT_ENGINE) == 0)
return opt_format_error(s, flags);
*result = FORMAT_ENGINE;
break;
case 'H':
case 'h':
if ((flags & OPT_FMT_HTTP) == 0)
return opt_format_error(s, flags);
*result = FORMAT_HTTP;
break;
case '1':
if ((flags & OPT_FMT_PKCS12) == 0)
return opt_format_error(s, flags);
*result = FORMAT_PKCS12;
break;
case 'P':
case 'p':
if (s[1] == '\0' || strcmp(s, "PEM") == 0 || strcmp(s, "pem") == 0) {
if ((flags & OPT_FMT_PEMDER) == 0)
return opt_format_error(s, flags);
*result = FORMAT_PEM;
} else if (strcmp(s, "PVK") == 0 || strcmp(s, "pvk") == 0) {
if ((flags & OPT_FMT_PVK) == 0)
return opt_format_error(s, flags);
*result = FORMAT_PVK;
} else if (strcmp(s, "P12") == 0 || strcmp(s, "p12") == 0
|| strcmp(s, "PKCS12") == 0 || strcmp(s, "pkcs12") == 0) {
if ((flags & OPT_FMT_PKCS12) == 0)
return opt_format_error(s, flags);
*result = FORMAT_PKCS12;
} else {
opt_printf_stderr("%s: Bad format \"%s\"\n", prog, s);
return 0;
}
break;
}
return 1;
}
/* Return string representing the given format. */
static const char *format2str(int format)
{
switch (format) {
default:
return "(undefined)";
case FORMAT_PEM:
return "PEM";
case FORMAT_ASN1:
return "DER";
case FORMAT_TEXT:
return "TEXT";
case FORMAT_NSS:
return "NSS";
case FORMAT_SMIME:
return "SMIME";
case FORMAT_MSBLOB:
return "MSBLOB";
case FORMAT_ENGINE:
return "ENGINE";
case FORMAT_HTTP:
return "HTTP";
case FORMAT_PKCS12:
return "P12";
case FORMAT_PVK:
return "PVK";
}
}
/* Print an error message about unsuitable/unsupported format requested. */
void print_format_error(int format, unsigned long flags)
{
(void)opt_format_error(format2str(format), flags);
}
/*
* Parse a cipher name, put it in *cipherp after freeing what was there, if
* cipherp is not NULL. Return 0 on failure, else 1.
*/
int opt_cipher_silent(const char *name, EVP_CIPHER **cipherp)
{
EVP_CIPHER *c;
ERR_set_mark();
if ((c = EVP_CIPHER_fetch(app_get0_libctx(), name,
app_get0_propq())) != NULL
|| (opt_legacy_okay()
&& (c = (EVP_CIPHER *)EVP_get_cipherbyname(name)) != NULL)) {
ERR_pop_to_mark();
if (cipherp != NULL) {
EVP_CIPHER_free(*cipherp);
*cipherp = c;
} else {
EVP_CIPHER_free(c);
}
return 1;
}
ERR_clear_last_mark();
return 0;
}
int opt_cipher_any(const char *name, EVP_CIPHER **cipherp)
{
int ret;
if ((ret = opt_cipher_silent(name, cipherp)) == 0)
opt_printf_stderr("%s: Unknown cipher: %s\n", prog, name);
return ret;
}
int opt_cipher(const char *name, EVP_CIPHER **cipherp)
{
int mode, ret = 0;
unsigned long int flags;
EVP_CIPHER *c = NULL;
if (opt_cipher_any(name, &c)) {
mode = EVP_CIPHER_get_mode(c);
flags = EVP_CIPHER_get_flags(c);
if (mode == EVP_CIPH_XTS_MODE) {
opt_printf_stderr("%s XTS ciphers not supported\n", prog);
} else if ((flags & EVP_CIPH_FLAG_AEAD_CIPHER) != 0) {
opt_printf_stderr("%s: AEAD ciphers not supported\n", prog);
} else {
ret = 1;
if (cipherp != NULL)
*cipherp = c;
}
}
return ret;
}
/*
* Parse message digest name, put it in *EVP_MD; return 0 on failure, else 1.
*/
int opt_md_silent(const char *name, EVP_MD **mdp)
{
EVP_MD *md;
ERR_set_mark();
if ((md = EVP_MD_fetch(app_get0_libctx(), name, app_get0_propq())) != NULL
|| (opt_legacy_okay()
&& (md = (EVP_MD *)EVP_get_digestbyname(name)) != NULL)) {
ERR_pop_to_mark();
if (mdp != NULL) {
EVP_MD_free(*mdp);
*mdp = md;
} else {
EVP_MD_free(md);
}
return 1;
}
ERR_clear_last_mark();
return 0;
}
int opt_md(const char *name, EVP_MD **mdp)
{
int ret;
if ((ret = opt_md_silent(name, mdp)) == 0)
opt_printf_stderr("%s: Unknown option or message digest: %s\n", prog,
name != NULL ? name : "\"\"");
return ret;
}
/* Look through a list of name/value pairs. */
int opt_pair(const char *name, const OPT_PAIR* pairs, int *result)
{
const OPT_PAIR *pp;
for (pp = pairs; pp->name; pp++)
if (strcmp(pp->name, name) == 0) {
*result = pp->retval;
return 1;
}
opt_printf_stderr("%s: Value must be one of:\n", prog);
for (pp = pairs; pp->name; pp++)
opt_printf_stderr("\t%s\n", pp->name);
return 0;
}
/* Look through a list of valid names */
int opt_string(const char *name, const char **options)
{
const char **p;
for (p = options; *p != NULL; p++)
if (strcmp(*p, name) == 0)
return 1;
opt_printf_stderr("%s: Value must be one of:\n", prog);
for (p = options; *p != NULL; p++)
opt_printf_stderr("\t%s\n", *p);
return 0;
}
/* Parse an int, put it into *result; return 0 on failure, else 1. */
int opt_int(const char *value, int *result)
{
long l;
if (!opt_long(value, &l))
return 0;
*result = (int)l;
if (*result != l) {
opt_printf_stderr("%s: Value \"%s\" outside integer range\n",
prog, value);
return 0;
}
return 1;
}
/* Parse and return an integer, assuming range has been checked before. */
int opt_int_arg(void)
{
int result = -1;
(void)opt_int(arg, &result);
return result;
}
static void opt_number_error(const char *v)
{
size_t i = 0;
struct strstr_pair_st {
char *prefix;
char *name;
} b[] = {
{"0x", "a hexadecimal"},
{"0X", "a hexadecimal"},
{"0", "an octal"}
};
for (i = 0; i < OSSL_NELEM(b); i++) {
if (strncmp(v, b[i].prefix, strlen(b[i].prefix)) == 0) {
opt_printf_stderr("%s: Can't parse \"%s\" as %s number\n",
prog, v, b[i].name);
return;
}
}
opt_printf_stderr("%s: Can't parse \"%s\" as a number\n", prog, v);
return;
}
/* Parse a long, put it into *result; return 0 on failure, else 1. */
int opt_long(const char *value, long *result)
{
int oerrno = errno;
long l;
char *endp;
errno = 0;
l = strtol(value, &endp, 0);
if (*endp
|| endp == value
|| ((l == LONG_MAX || l == LONG_MIN) && errno == ERANGE)
|| (l == 0 && errno != 0)) {
opt_number_error(value);
errno = oerrno;
return 0;
}
*result = l;
errno = oerrno;
return 1;
}
#if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L && \
defined(INTMAX_MAX) && defined(UINTMAX_MAX) && \
!defined(OPENSSL_NO_INTTYPES_H)
/* Parse an intmax_t, put it into *result; return 0 on failure, else 1. */
int opt_intmax(const char *value, ossl_intmax_t *result)
{
int oerrno = errno;
intmax_t m;
char *endp;
errno = 0;
m = strtoimax(value, &endp, 0);
if (*endp
|| endp == value
|| ((m == INTMAX_MAX || m == INTMAX_MIN)
&& errno == ERANGE)
|| (m == 0 && errno != 0)) {
opt_number_error(value);
errno = oerrno;
return 0;
}
/* Ensure that the value in |m| is never too big for |*result| */
if (sizeof(m) > sizeof(*result)
&& (m < OSSL_INTMAX_MIN || m > OSSL_INTMAX_MAX)) {
opt_number_error(value);
return 0;
}
*result = (ossl_intmax_t)m;
errno = oerrno;
return 1;
}
/* Parse a uintmax_t, put it into *result; return 0 on failure, else 1. */
int opt_uintmax(const char *value, ossl_uintmax_t *result)
{
int oerrno = errno;
uintmax_t m;
char *endp;
errno = 0;
m = strtoumax(value, &endp, 0);
if (*endp
|| endp == value
|| (m == UINTMAX_MAX && errno == ERANGE)
|| (m == 0 && errno != 0)) {
opt_number_error(value);
errno = oerrno;
return 0;
}
/* Ensure that the value in |m| is never too big for |*result| */
if (sizeof(m) > sizeof(*result)
&& m > OSSL_UINTMAX_MAX) {
opt_number_error(value);
return 0;
}
- *result = (ossl_intmax_t)m;
+ *result = (ossl_uintmax_t)m;
errno = oerrno;
return 1;
}
#else
/* Fallback implementations based on long */
int opt_intmax(const char *value, ossl_intmax_t *result)
{
long m;
int ret;
if ((ret = opt_long(value, &m)))
*result = m;
return ret;
}
int opt_uintmax(const char *value, ossl_uintmax_t *result)
{
unsigned long m;
int ret;
if ((ret = opt_ulong(value, &m)))
*result = m;
return ret;
}
#endif
/*
* Parse an unsigned long, put it into *result; return 0 on failure, else 1.
*/
int opt_ulong(const char *value, unsigned long *result)
{
int oerrno = errno;
char *endptr;
unsigned long l;
errno = 0;
l = strtoul(value, &endptr, 0);
if (*endptr
|| endptr == value
|| ((l == ULONG_MAX) && errno == ERANGE)
|| (l == 0 && errno != 0)) {
opt_number_error(value);
errno = oerrno;
return 0;
}
*result = l;
errno = oerrno;
return 1;
}
/*
* We pass opt as an int but cast it to "enum range" so that all the
* items in the OPT_V_ENUM enumeration are caught; this makes -Wswitch
* in gcc do the right thing.
*/
enum range { OPT_V_ENUM };
int opt_verify(int opt, X509_VERIFY_PARAM *vpm)
{
int i;
ossl_intmax_t t = 0;
ASN1_OBJECT *otmp;
X509_PURPOSE *xptmp;
const X509_VERIFY_PARAM *vtmp;
OPENSSL_assert(vpm != NULL);
OPENSSL_assert(opt > OPT_V__FIRST);
OPENSSL_assert(opt < OPT_V__LAST);
switch ((enum range)opt) {
case OPT_V__FIRST:
case OPT_V__LAST:
return 0;
case OPT_V_POLICY:
otmp = OBJ_txt2obj(opt_arg(), 0);
if (otmp == NULL) {
opt_printf_stderr("%s: Invalid Policy %s\n", prog, opt_arg());
return 0;
}
if (!X509_VERIFY_PARAM_add0_policy(vpm, otmp)) {
ASN1_OBJECT_free(otmp);
opt_printf_stderr("%s: Internal error adding Policy %s\n",
prog, opt_arg());
return 0;
}
break;
case OPT_V_PURPOSE:
/* purpose name -> purpose index */
i = X509_PURPOSE_get_by_sname(opt_arg());
if (i < 0) {
opt_printf_stderr("%s: Invalid purpose %s\n", prog, opt_arg());
return 0;
}
/* purpose index -> purpose object */
xptmp = X509_PURPOSE_get0(i);
/* purpose object -> purpose value */
i = X509_PURPOSE_get_id(xptmp);
if (!X509_VERIFY_PARAM_set_purpose(vpm, i)) {
opt_printf_stderr("%s: Internal error setting purpose %s\n",
prog, opt_arg());
return 0;
}
break;
case OPT_V_VERIFY_NAME:
vtmp = X509_VERIFY_PARAM_lookup(opt_arg());
if (vtmp == NULL) {
opt_printf_stderr("%s: Invalid verify name %s\n",
prog, opt_arg());
return 0;
}
X509_VERIFY_PARAM_set1(vpm, vtmp);
break;
case OPT_V_VERIFY_DEPTH:
i = atoi(opt_arg());
if (i >= 0)
X509_VERIFY_PARAM_set_depth(vpm, i);
break;
case OPT_V_VERIFY_AUTH_LEVEL:
i = atoi(opt_arg());
if (i >= 0)
X509_VERIFY_PARAM_set_auth_level(vpm, i);
break;
case OPT_V_ATTIME:
if (!opt_intmax(opt_arg(), &t))
return 0;
if (t != (time_t)t) {
opt_printf_stderr("%s: epoch time out of range %s\n",
prog, opt_arg());
return 0;
}
X509_VERIFY_PARAM_set_time(vpm, (time_t)t);
break;
case OPT_V_VERIFY_HOSTNAME:
if (!X509_VERIFY_PARAM_set1_host(vpm, opt_arg(), 0))
return 0;
break;
case OPT_V_VERIFY_EMAIL:
if (!X509_VERIFY_PARAM_set1_email(vpm, opt_arg(), 0))
return 0;
break;
case OPT_V_VERIFY_IP:
if (!X509_VERIFY_PARAM_set1_ip_asc(vpm, opt_arg()))
return 0;
break;
case OPT_V_IGNORE_CRITICAL:
X509_VERIFY_PARAM_set_flags(vpm, X509_V_FLAG_IGNORE_CRITICAL);
break;
case OPT_V_ISSUER_CHECKS:
/* NOP, deprecated */
break;
case OPT_V_CRL_CHECK:
X509_VERIFY_PARAM_set_flags(vpm, X509_V_FLAG_CRL_CHECK);
break;
case OPT_V_CRL_CHECK_ALL:
X509_VERIFY_PARAM_set_flags(vpm,
X509_V_FLAG_CRL_CHECK |
X509_V_FLAG_CRL_CHECK_ALL);
break;
case OPT_V_POLICY_CHECK:
X509_VERIFY_PARAM_set_flags(vpm, X509_V_FLAG_POLICY_CHECK);
break;
case OPT_V_EXPLICIT_POLICY:
X509_VERIFY_PARAM_set_flags(vpm, X509_V_FLAG_EXPLICIT_POLICY);
break;
case OPT_V_INHIBIT_ANY:
X509_VERIFY_PARAM_set_flags(vpm, X509_V_FLAG_INHIBIT_ANY);
break;
case OPT_V_INHIBIT_MAP:
X509_VERIFY_PARAM_set_flags(vpm, X509_V_FLAG_INHIBIT_MAP);
break;
case OPT_V_X509_STRICT:
X509_VERIFY_PARAM_set_flags(vpm, X509_V_FLAG_X509_STRICT);
break;
case OPT_V_EXTENDED_CRL:
X509_VERIFY_PARAM_set_flags(vpm, X509_V_FLAG_EXTENDED_CRL_SUPPORT);
break;
case OPT_V_USE_DELTAS:
X509_VERIFY_PARAM_set_flags(vpm, X509_V_FLAG_USE_DELTAS);
break;
case OPT_V_POLICY_PRINT:
X509_VERIFY_PARAM_set_flags(vpm, X509_V_FLAG_NOTIFY_POLICY);
break;
case OPT_V_CHECK_SS_SIG:
X509_VERIFY_PARAM_set_flags(vpm, X509_V_FLAG_CHECK_SS_SIGNATURE);
break;
case OPT_V_TRUSTED_FIRST:
X509_VERIFY_PARAM_set_flags(vpm, X509_V_FLAG_TRUSTED_FIRST);
break;
case OPT_V_SUITEB_128_ONLY:
X509_VERIFY_PARAM_set_flags(vpm, X509_V_FLAG_SUITEB_128_LOS_ONLY);
break;
case OPT_V_SUITEB_128:
X509_VERIFY_PARAM_set_flags(vpm, X509_V_FLAG_SUITEB_128_LOS);
break;
case OPT_V_SUITEB_192:
X509_VERIFY_PARAM_set_flags(vpm, X509_V_FLAG_SUITEB_192_LOS);
break;
case OPT_V_PARTIAL_CHAIN:
X509_VERIFY_PARAM_set_flags(vpm, X509_V_FLAG_PARTIAL_CHAIN);
break;
case OPT_V_NO_ALT_CHAINS:
X509_VERIFY_PARAM_set_flags(vpm, X509_V_FLAG_NO_ALT_CHAINS);
break;
case OPT_V_NO_CHECK_TIME:
X509_VERIFY_PARAM_set_flags(vpm, X509_V_FLAG_NO_CHECK_TIME);
break;
case OPT_V_ALLOW_PROXY_CERTS:
X509_VERIFY_PARAM_set_flags(vpm, X509_V_FLAG_ALLOW_PROXY_CERTS);
break;
}
return 1;
}
void opt_begin(void)
{
opt_index = 1;
arg = NULL;
flag = NULL;
}
/*
* Parse the next flag (and value if specified), return 0 if done, -1 on
* error, otherwise the flag's retval.
*/
int opt_next(void)
{
char *p;
const OPTIONS *o;
int ival;
long lval;
unsigned long ulval;
ossl_intmax_t imval;
ossl_uintmax_t umval;
/* Look at current arg; at end of the list? */
arg = NULL;
p = argv[opt_index];
if (p == NULL)
return 0;
/* If word doesn't start with a -, we're done. */
if (*p != '-')
return 0;
/* Hit "--" ? We're done. */
opt_index++;
if (strcmp(p, "--") == 0)
return 0;
/* Allow -nnn and --nnn */
if (*++p == '-')
p++;
flag = p - 1;
/* If we have --flag=foo, snip it off */
if ((arg = strchr(p, '=')) != NULL)
*arg++ = '\0';
for (o = opts; o->name; ++o) {
/* If not this option, move on to the next one. */
if (!(strcmp(p, "h") == 0 && strcmp(o->name, "help") == 0)
&& strcmp(p, o->name) != 0)
continue;
/* If it doesn't take a value, make sure none was given. */
if (o->valtype == 0 || o->valtype == '-') {
if (arg) {
opt_printf_stderr("%s: Option -%s does not take a value\n",
prog, p);
return -1;
}
return o->retval;
}
/* Want a value; get the next param if =foo not used. */
if (arg == NULL) {
if (argv[opt_index] == NULL) {
opt_printf_stderr("%s: Option -%s needs a value\n",
prog, o->name);
return -1;
}
arg = argv[opt_index++];
}
/* Syntax-check value. */
switch (o->valtype) {
default:
case 's':
case ':':
/* Just a string. */
break;
case '.':
/* Parameters */
break;
case '/':
if (opt_isdir(arg) > 0)
break;
opt_printf_stderr("%s: Not a directory: %s\n", prog, arg);
return -1;
case '<':
/* Input file. */
break;
case '>':
/* Output file. */
break;
case 'p':
case 'n':
case 'N':
if (!opt_int(arg, &ival))
return -1;
if (o->valtype == 'p' && ival <= 0) {
opt_printf_stderr("%s: Non-positive number \"%s\" for option -%s\n",
prog, arg, o->name);
return -1;
}
if (o->valtype == 'N' && ival < 0) {
opt_printf_stderr("%s: Negative number \"%s\" for option -%s\n",
prog, arg, o->name);
return -1;
}
break;
case 'M':
if (!opt_intmax(arg, &imval))
return -1;
break;
case 'U':
if (!opt_uintmax(arg, &umval))
return -1;
break;
case 'l':
if (!opt_long(arg, &lval))
return -1;
break;
case 'u':
if (!opt_ulong(arg, &ulval))
return -1;
break;
case 'c':
case 'E':
case 'F':
case 'f':
if (opt_format(arg,
o->valtype == 'c' ? OPT_FMT_PDS :
o->valtype == 'E' ? OPT_FMT_PDE :
o->valtype == 'F' ? OPT_FMT_PEMDER
: OPT_FMT_ANY, &ival))
break;
opt_printf_stderr("%s: Invalid format \"%s\" for option -%s\n",
prog, arg, o->name);
return -1;
}
/* Return the flag value. */
return o->retval;
}
if (unknown != NULL) {
dunno = p;
return unknown->retval;
}
opt_printf_stderr("%s: Unknown option: -%s\n", prog, p);
return -1;
}
/* Return the most recent flag parameter. */
char *opt_arg(void)
{
return arg;
}
/* Return the most recent flag (option name including the preceding '-'). */
char *opt_flag(void)
{
return flag;
}
/* Return the unknown option. */
char *opt_unknown(void)
{
return dunno;
}
/* Return the rest of the arguments after parsing flags. */
char **opt_rest(void)
{
return &argv[opt_index];
}
/* How many items in remaining args? */
int opt_num_rest(void)
{
int i = 0;
char **pp;
for (pp = opt_rest(); *pp; pp++, i++)
continue;
return i;
}
/* Return a string describing the parameter type. */
static const char *valtype2param(const OPTIONS *o)
{
switch (o->valtype) {
case 0:
case '-':
return "";
case ':':
return "uri";
case 's':
return "val";
case '/':
return "dir";
case '<':
return "infile";
case '>':
return "outfile";
case 'p':
return "+int";
case 'n':
return "int";
case 'l':
return "long";
case 'u':
return "ulong";
case 'E':
return "PEM|DER|ENGINE";
case 'F':
return "PEM|DER";
case 'f':
return "format";
case 'M':
return "intmax";
case 'N':
return "nonneg";
case 'U':
return "uintmax";
}
return "parm";
}
static void opt_print(const OPTIONS *o, int doingparams, int width)
{
const char* help;
char start[80 + 1];
char *p;
help = o->helpstr ? o->helpstr : "(No additional info)";
if (o->name == OPT_HELP_STR) {
opt_printf_stderr(help, prog);
return;
}
if (o->name == OPT_SECTION_STR) {
opt_printf_stderr("\n");
opt_printf_stderr(help, prog);
return;
}
if (o->name == OPT_PARAM_STR) {
opt_printf_stderr("\nParameters:\n");
return;
}
/* Pad out prefix */
memset(start, ' ', sizeof(start) - 1);
start[sizeof(start) - 1] = '\0';
if (o->name == OPT_MORE_STR) {
/* Continuation of previous line; pad and print. */
start[width] = '\0';
opt_printf_stderr("%s %s\n", start, help);
return;
}
/* Build up the "-flag [param]" part. */
p = start;
*p++ = ' ';
if (!doingparams)
*p++ = '-';
if (o->name[0])
p += strlen(strcpy(p, o->name));
else
*p++ = '*';
if (o->valtype != '-') {
*p++ = ' ';
p += strlen(strcpy(p, valtype2param(o)));
}
*p = ' ';
if ((int)(p - start) >= MAX_OPT_HELP_WIDTH) {
*p = '\0';
opt_printf_stderr("%s\n", start);
memset(start, ' ', sizeof(start));
}
start[width] = '\0';
opt_printf_stderr("%s %s\n", start, help);
}
void opt_help(const OPTIONS *list)
{
const OPTIONS *o;
int i, sawparams = 0, width = 5;
int standard_prolog;
char start[80 + 1];
/* Starts with its own help message? */
standard_prolog = list[0].name != OPT_HELP_STR;
/* Find the widest help. */
for (o = list; o->name; o++) {
if (o->name == OPT_MORE_STR)
continue;
i = 2 + (int)strlen(o->name);
if (o->valtype != '-')
i += 1 + strlen(valtype2param(o));
if (i < MAX_OPT_HELP_WIDTH && i > width)
width = i;
OPENSSL_assert(i < (int)sizeof(start));
}
if (standard_prolog) {
opt_printf_stderr("Usage: %s [options]\n", prog);
if (list[0].name != OPT_SECTION_STR)
opt_printf_stderr("Valid options are:\n", prog);
}
/* Now let's print. */
for (o = list; o->name; o++) {
if (o->name == OPT_PARAM_STR)
sawparams = 1;
opt_print(o, sawparams, width);
}
}
/* opt_isdir section */
#ifdef _WIN32
# include <windows.h>
int opt_isdir(const char *name)
{
DWORD attr;
# if defined(UNICODE) || defined(_UNICODE)
size_t i, len_0 = strlen(name) + 1;
WCHAR tempname[MAX_PATH];
if (len_0 > MAX_PATH)
return -1;
# if !defined(_WIN32_WCE) || _WIN32_WCE>=101
if (!MultiByteToWideChar(CP_ACP, 0, name, len_0, tempname, MAX_PATH))
# endif
for (i = 0; i < len_0; i++)
tempname[i] = (WCHAR)name[i];
attr = GetFileAttributes(tempname);
# else
attr = GetFileAttributes(name);
# endif
if (attr == INVALID_FILE_ATTRIBUTES)
return -1;
return ((attr & FILE_ATTRIBUTE_DIRECTORY) != 0);
}
#else
# include <sys/stat.h>
# ifndef S_ISDIR
# if defined(_S_IFMT) && defined(_S_IFDIR)
# define S_ISDIR(a) (((a) & _S_IFMT) == _S_IFDIR)
# else
# define S_ISDIR(a) (((a) & S_IFMT) == S_IFDIR)
# endif
# endif
int opt_isdir(const char *name)
{
# if defined(S_ISDIR)
struct stat st;
if (stat(name, &st) == 0)
return S_ISDIR(st.st_mode);
else
return -1;
# else
return -1;
# endif
}
#endif
diff --git a/crypto/openssl/apps/lib/s_cb.c b/crypto/openssl/apps/lib/s_cb.c
index 7881c1667626..6440b496099e 100644
--- a/crypto/openssl/apps/lib/s_cb.c
+++ b/crypto/openssl/apps/lib/s_cb.c
@@ -1,1571 +1,1572 @@
/*
* 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[] = {
+static const 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},
+ {"early_data", TLSEXT_TYPE_early_data},
{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);
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;
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/smime.c b/crypto/openssl/apps/smime.c
index 52b4a01c232f..651294e46daa 100644
--- a/crypto/openssl/apps/smime.c
+++ b/crypto/openssl/apps/smime.c
@@ -1,710 +1,710 @@
/*
- * Copyright 1999-2021 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
*/
/* S/MIME utility function */
#include <stdio.h>
#include <string.h>
#include "apps.h"
#include "progs.h"
#include <openssl/crypto.h>
#include <openssl/pem.h>
#include <openssl/err.h>
#include <openssl/x509_vfy.h>
#include <openssl/x509v3.h>
static int save_certs(char *signerfile, STACK_OF(X509) *signers);
static int smime_cb(int ok, X509_STORE_CTX *ctx);
#define SMIME_OP 0x10
#define SMIME_IP 0x20
#define SMIME_SIGNERS 0x40
#define SMIME_ENCRYPT (1 | SMIME_OP)
#define SMIME_DECRYPT (2 | SMIME_IP)
#define SMIME_SIGN (3 | SMIME_OP | SMIME_SIGNERS)
#define SMIME_VERIFY (4 | SMIME_IP)
#define SMIME_PK7OUT (5 | SMIME_IP | SMIME_OP)
#define SMIME_RESIGN (6 | SMIME_IP | SMIME_OP | SMIME_SIGNERS)
typedef enum OPTION_choice {
OPT_COMMON,
OPT_ENCRYPT, OPT_DECRYPT, OPT_SIGN, OPT_RESIGN, OPT_VERIFY,
OPT_PK7OUT, OPT_TEXT, OPT_NOINTERN, OPT_NOVERIFY, OPT_NOCHAIN,
OPT_NOCERTS, OPT_NOATTR, OPT_NODETACH, OPT_NOSMIMECAP,
OPT_BINARY, OPT_NOSIGS, OPT_STREAM, OPT_INDEF, OPT_NOINDEF,
OPT_CRLFEOL, OPT_ENGINE, OPT_PASSIN,
OPT_TO, OPT_FROM, OPT_SUBJECT, OPT_SIGNER, OPT_RECIP, OPT_MD,
OPT_CIPHER, OPT_INKEY, OPT_KEYFORM, OPT_CERTFILE, OPT_CAFILE,
OPT_CAPATH, OPT_CASTORE, OPT_NOCAFILE, OPT_NOCAPATH, OPT_NOCASTORE,
OPT_R_ENUM, OPT_PROV_ENUM, OPT_CONFIG,
OPT_V_ENUM,
OPT_IN, OPT_INFORM, OPT_OUT,
OPT_OUTFORM, OPT_CONTENT
} OPTION_CHOICE;
const OPTIONS smime_options[] = {
{OPT_HELP_STR, 1, '-', "Usage: %s [options] [cert...]\n"},
OPT_SECTION("General"),
{"help", OPT_HELP, '-', "Display this summary"},
{"in", OPT_IN, '<', "Input file"},
{"inform", OPT_INFORM, 'c', "Input format SMIME (default), PEM or DER"},
{"out", OPT_OUT, '>', "Output file"},
{"outform", OPT_OUTFORM, 'c',
"Output format SMIME (default), PEM or DER"},
{"inkey", OPT_INKEY, 's',
"Input private key (if not signer or recipient)"},
{"keyform", OPT_KEYFORM, 'f', "Input private key format (ENGINE, other values ignored)"},
#ifndef OPENSSL_NO_ENGINE
{"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"},
#endif
{"stream", OPT_STREAM, '-', "Enable CMS streaming" },
{"indef", OPT_INDEF, '-', "Same as -stream" },
{"noindef", OPT_NOINDEF, '-', "Disable CMS streaming"},
OPT_CONFIG_OPTION,
OPT_SECTION("Action"),
{"encrypt", OPT_ENCRYPT, '-', "Encrypt message"},
{"decrypt", OPT_DECRYPT, '-', "Decrypt encrypted message"},
{"sign", OPT_SIGN, '-', "Sign message"},
{"resign", OPT_RESIGN, '-', "Resign a signed message"},
{"verify", OPT_VERIFY, '-', "Verify signed message"},
OPT_SECTION("Signing/Encryption"),
{"passin", OPT_PASSIN, 's', "Input file pass phrase source"},
{"md", OPT_MD, 's', "Digest algorithm to use when signing or resigning"},
{"", OPT_CIPHER, '-', "Any supported cipher"},
{"pk7out", OPT_PK7OUT, '-', "Output PKCS#7 structure"},
{"nointern", OPT_NOINTERN, '-',
"Don't search certificates in message for signer"},
{"nodetach", OPT_NODETACH, '-', "Use opaque signing"},
{"noattr", OPT_NOATTR, '-', "Don't include any signed attributes"},
{"binary", OPT_BINARY, '-', "Don't translate message to text"},
{"signer", OPT_SIGNER, 's', "Signer certificate file"},
{"content", OPT_CONTENT, '<',
"Supply or override content for detached signature"},
{"nocerts", OPT_NOCERTS, '-',
"Don't include signers certificate when signing"},
OPT_SECTION("Verification/Decryption"),
{"nosigs", OPT_NOSIGS, '-', "Don't verify message signature"},
{"noverify", OPT_NOVERIFY, '-', "Don't verify signers certificate"},
{"certfile", OPT_CERTFILE, '<', "Other certificates file"},
{"recip", OPT_RECIP, '<', "Recipient certificate file for decryption"},
OPT_SECTION("Email"),
{"to", OPT_TO, 's', "To address"},
{"from", OPT_FROM, 's', "From address"},
{"subject", OPT_SUBJECT, 's', "Subject"},
{"text", OPT_TEXT, '-', "Include or delete text MIME headers"},
{"nosmimecap", OPT_NOSMIMECAP, '-', "Omit the SMIMECapabilities attribute"},
OPT_SECTION("Certificate chain"),
{"CApath", OPT_CAPATH, '/', "Trusted certificates directory"},
{"CAfile", OPT_CAFILE, '<', "Trusted certificates file"},
{"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"},
{"nochain", OPT_NOCHAIN, '-',
"set PKCS7_NOCHAIN so certificates contained in the message are not used as untrusted CAs" },
- {"crlfeol", OPT_CRLFEOL, '-', "Use CRLF as EOL termination instead of CR only"},
+ {"crlfeol", OPT_CRLFEOL, '-', "Use CRLF as EOL termination instead of LF only"},
OPT_R_OPTIONS,
OPT_V_OPTIONS,
OPT_PROV_OPTIONS,
OPT_PARAMETERS(),
{"cert", 0, 0, "Recipient certs, used when encrypting"},
{NULL}
};
int smime_main(int argc, char **argv)
{
CONF *conf = NULL;
BIO *in = NULL, *out = NULL, *indata = NULL;
EVP_PKEY *key = NULL;
PKCS7 *p7 = NULL;
STACK_OF(OPENSSL_STRING) *sksigners = NULL, *skkeys = NULL;
STACK_OF(X509) *encerts = NULL, *other = NULL;
X509 *cert = NULL, *recip = NULL, *signer = NULL;
X509_STORE *store = NULL;
X509_VERIFY_PARAM *vpm = NULL;
EVP_CIPHER *cipher = NULL;
EVP_MD *sign_md = NULL;
const char *CAfile = NULL, *CApath = NULL, *CAstore = NULL, *prog = NULL;
char *certfile = NULL, *keyfile = NULL, *contfile = NULL;
char *infile = NULL, *outfile = NULL, *signerfile = NULL, *recipfile = NULL;
char *passinarg = NULL, *passin = NULL, *to = NULL, *from = NULL;
char *subject = NULL, *digestname = NULL, *ciphername = NULL;
OPTION_CHOICE o;
int noCApath = 0, noCAfile = 0, noCAstore = 0;
int flags = PKCS7_DETACHED, operation = 0, ret = 0, indef = 0;
int informat = FORMAT_SMIME, outformat = FORMAT_SMIME, keyform =
FORMAT_UNDEF;
int vpmtouched = 0, rv = 0;
ENGINE *e = NULL;
const char *mime_eol = "\n";
OSSL_LIB_CTX *libctx = app_get0_libctx();
if ((vpm = X509_VERIFY_PARAM_new()) == NULL)
return 1;
prog = opt_init(argc, argv, smime_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(smime_options);
ret = 0;
goto end;
case OPT_INFORM:
if (!opt_format(opt_arg(), OPT_FMT_PDS, &informat))
goto opthelp;
break;
case OPT_IN:
infile = opt_arg();
break;
case OPT_OUTFORM:
if (!opt_format(opt_arg(), OPT_FMT_PDS, &outformat))
goto opthelp;
break;
case OPT_OUT:
outfile = opt_arg();
break;
case OPT_ENCRYPT:
operation = SMIME_ENCRYPT;
break;
case OPT_DECRYPT:
operation = SMIME_DECRYPT;
break;
case OPT_SIGN:
operation = SMIME_SIGN;
break;
case OPT_RESIGN:
operation = SMIME_RESIGN;
break;
case OPT_VERIFY:
operation = SMIME_VERIFY;
break;
case OPT_PK7OUT:
operation = SMIME_PK7OUT;
break;
case OPT_TEXT:
flags |= PKCS7_TEXT;
break;
case OPT_NOINTERN:
flags |= PKCS7_NOINTERN;
break;
case OPT_NOVERIFY:
flags |= PKCS7_NOVERIFY;
break;
case OPT_NOCHAIN:
flags |= PKCS7_NOCHAIN;
break;
case OPT_NOCERTS:
flags |= PKCS7_NOCERTS;
break;
case OPT_NOATTR:
flags |= PKCS7_NOATTR;
break;
case OPT_NODETACH:
flags &= ~PKCS7_DETACHED;
break;
case OPT_NOSMIMECAP:
flags |= PKCS7_NOSMIMECAP;
break;
case OPT_BINARY:
flags |= PKCS7_BINARY;
break;
case OPT_NOSIGS:
flags |= PKCS7_NOSIGS;
break;
case OPT_STREAM:
case OPT_INDEF:
indef = 1;
break;
case OPT_NOINDEF:
indef = 0;
break;
case OPT_CRLFEOL:
flags |= PKCS7_CRLFEOL;
mime_eol = "\r\n";
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_CONFIG:
conf = app_load_config_modules(opt_arg());
if (conf == NULL)
goto end;
break;
case OPT_ENGINE:
e = setup_engine(opt_arg(), 0);
break;
case OPT_PASSIN:
passinarg = opt_arg();
break;
case OPT_TO:
to = opt_arg();
break;
case OPT_FROM:
from = opt_arg();
break;
case OPT_SUBJECT:
subject = opt_arg();
break;
case OPT_SIGNER:
/* If previous -signer argument add signer to list */
if (signerfile != NULL) {
if (sksigners == NULL
&& (sksigners = sk_OPENSSL_STRING_new_null()) == NULL)
goto end;
sk_OPENSSL_STRING_push(sksigners, signerfile);
if (keyfile == NULL)
keyfile = signerfile;
if (skkeys == NULL
&& (skkeys = sk_OPENSSL_STRING_new_null()) == NULL)
goto end;
sk_OPENSSL_STRING_push(skkeys, keyfile);
keyfile = NULL;
}
signerfile = opt_arg();
break;
case OPT_RECIP:
recipfile = opt_arg();
break;
case OPT_MD:
digestname = opt_arg();
break;
case OPT_CIPHER:
ciphername = opt_unknown();
break;
case OPT_INKEY:
/* If previous -inkey argument add signer to list */
if (keyfile != NULL) {
if (signerfile == NULL) {
BIO_printf(bio_err,
"%s: Must have -signer before -inkey\n", prog);
goto opthelp;
}
if (sksigners == NULL
&& (sksigners = sk_OPENSSL_STRING_new_null()) == NULL)
goto end;
sk_OPENSSL_STRING_push(sksigners, signerfile);
signerfile = NULL;
if (skkeys == NULL
&& (skkeys = sk_OPENSSL_STRING_new_null()) == NULL)
goto end;
sk_OPENSSL_STRING_push(skkeys, keyfile);
}
keyfile = opt_arg();
break;
case OPT_KEYFORM:
if (!opt_format(opt_arg(), OPT_FMT_ANY, &keyform))
goto opthelp;
break;
case OPT_CERTFILE:
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_CONTENT:
contfile = opt_arg();
break;
case OPT_V_CASES:
if (!opt_verify(o, vpm))
goto opthelp;
vpmtouched++;
break;
}
}
/* Extra arguments are files with recipient keys. */
argc = opt_num_rest();
argv = opt_rest();
if (!app_RAND_load())
goto end;
if (digestname != NULL) {
if (!opt_md(digestname, &sign_md))
goto opthelp;
}
if (ciphername != NULL) {
if (!opt_cipher_any(ciphername, &cipher))
goto opthelp;
}
if (!(operation & SMIME_SIGNERS) && (skkeys != NULL || sksigners != NULL)) {
BIO_puts(bio_err, "Multiple signers or keys not allowed\n");
goto opthelp;
}
if (!operation) {
BIO_puts(bio_err,
"No operation (-encrypt|-sign|...) specified\n");
goto opthelp;
}
if (operation & SMIME_SIGNERS) {
/* Check to see if any final signer needs to be appended */
if (keyfile && !signerfile) {
BIO_puts(bio_err, "Illegal -inkey without -signer\n");
goto opthelp;
}
if (signerfile != NULL) {
if (sksigners == NULL
&& (sksigners = sk_OPENSSL_STRING_new_null()) == NULL)
goto end;
sk_OPENSSL_STRING_push(sksigners, signerfile);
if (!skkeys && (skkeys = sk_OPENSSL_STRING_new_null()) == NULL)
goto end;
if (!keyfile)
keyfile = signerfile;
sk_OPENSSL_STRING_push(skkeys, keyfile);
}
if (sksigners == NULL) {
BIO_printf(bio_err, "No signer certificate specified\n");
goto opthelp;
}
signerfile = NULL;
keyfile = NULL;
} else if (operation == SMIME_DECRYPT) {
if (recipfile == NULL && keyfile == NULL) {
BIO_printf(bio_err,
"No recipient certificate or key specified\n");
goto opthelp;
}
} else if (operation == SMIME_ENCRYPT) {
if (argc == 0) {
BIO_printf(bio_err, "No recipient(s) certificate(s) specified\n");
goto opthelp;
}
}
if (!app_passwd(passinarg, NULL, &passin, NULL)) {
BIO_printf(bio_err, "Error getting password\n");
goto end;
}
ret = 2;
if (!(operation & SMIME_SIGNERS))
flags &= ~PKCS7_DETACHED;
if (!(operation & SMIME_OP)) {
if (flags & PKCS7_BINARY)
outformat = FORMAT_BINARY;
}
if (!(operation & SMIME_IP)) {
if (flags & PKCS7_BINARY)
informat = FORMAT_BINARY;
}
if (operation == SMIME_ENCRYPT) {
if (cipher == NULL) {
#ifndef OPENSSL_NO_DES
cipher = (EVP_CIPHER *)EVP_des_ede3_cbc();
#else
BIO_printf(bio_err, "No cipher selected\n");
goto end;
#endif
}
encerts = sk_X509_new_null();
if (encerts == NULL)
goto end;
while (*argv != NULL) {
cert = load_cert(*argv, FORMAT_UNDEF,
"recipient certificate file");
if (cert == NULL)
goto end;
if (!sk_X509_push(encerts, cert))
goto end;
cert = NULL;
argv++;
}
}
if (certfile != NULL) {
if (!load_certs(certfile, 0, &other, NULL, "certificates")) {
ERR_print_errors(bio_err);
goto end;
}
}
if (recipfile != NULL && (operation == SMIME_DECRYPT)) {
if ((recip = load_cert(recipfile, FORMAT_UNDEF,
"recipient certificate file")) == NULL) {
ERR_print_errors(bio_err);
goto end;
}
}
if (operation == SMIME_DECRYPT) {
if (keyfile == NULL)
keyfile = recipfile;
} else if (operation == SMIME_SIGN) {
if (keyfile == NULL)
keyfile = signerfile;
} else {
keyfile = NULL;
}
if (keyfile != NULL) {
key = load_key(keyfile, keyform, 0, passin, e, "signing key");
if (key == NULL)
goto end;
}
in = bio_open_default(infile, 'r', informat);
if (in == NULL)
goto end;
if (operation & SMIME_IP) {
PKCS7 *p7_in = NULL;
p7 = PKCS7_new_ex(libctx, app_get0_propq());
if (p7 == NULL) {
BIO_printf(bio_err, "Error allocating PKCS7 object\n");
goto end;
}
if (informat == FORMAT_SMIME) {
p7_in = SMIME_read_PKCS7_ex(in, &indata, &p7);
} else if (informat == FORMAT_PEM) {
p7_in = PEM_read_bio_PKCS7(in, &p7, NULL, NULL);
} else if (informat == FORMAT_ASN1) {
p7_in = d2i_PKCS7_bio(in, &p7);
} else {
BIO_printf(bio_err, "Bad input format for PKCS#7 file\n");
goto end;
}
if (p7_in == NULL) {
BIO_printf(bio_err, "Error reading S/MIME message\n");
goto end;
}
if (contfile != NULL) {
BIO_free(indata);
if ((indata = BIO_new_file(contfile, "rb")) == NULL) {
BIO_printf(bio_err, "Can't read content file %s\n", contfile);
goto end;
}
}
}
out = bio_open_default(outfile, 'w', outformat);
if (out == NULL)
goto end;
if (operation == SMIME_VERIFY) {
if ((store = setup_verify(CAfile, noCAfile, CApath, noCApath,
CAstore, noCAstore)) == NULL)
goto end;
X509_STORE_set_verify_cb(store, smime_cb);
if (vpmtouched)
X509_STORE_set1_param(store, vpm);
}
ret = 3;
if (operation == SMIME_ENCRYPT) {
if (indef)
flags |= PKCS7_STREAM;
p7 = PKCS7_encrypt_ex(encerts, in, cipher, flags, libctx, app_get0_propq());
} else if (operation & SMIME_SIGNERS) {
int i;
/*
* If detached data content we only enable streaming if S/MIME output
* format.
*/
if (operation == SMIME_SIGN) {
if (flags & PKCS7_DETACHED) {
if (outformat == FORMAT_SMIME)
flags |= PKCS7_STREAM;
} else if (indef) {
flags |= PKCS7_STREAM;
}
flags |= PKCS7_PARTIAL;
p7 = PKCS7_sign_ex(NULL, NULL, other, in, flags, libctx, app_get0_propq());
if (p7 == NULL)
goto end;
if (flags & PKCS7_NOCERTS) {
for (i = 0; i < sk_X509_num(other); i++) {
X509 *x = sk_X509_value(other, i);
PKCS7_add_certificate(p7, x);
}
}
} else {
flags |= PKCS7_REUSE_DIGEST;
}
for (i = 0; i < sk_OPENSSL_STRING_num(sksigners); i++) {
signerfile = sk_OPENSSL_STRING_value(sksigners, i);
keyfile = sk_OPENSSL_STRING_value(skkeys, i);
signer = load_cert(signerfile, FORMAT_UNDEF, "signer certificate");
if (signer == NULL)
goto end;
key = load_key(keyfile, keyform, 0, passin, e, "signing key");
if (key == NULL)
goto end;
if (!PKCS7_sign_add_signer(p7, signer, key, sign_md, flags))
goto end;
X509_free(signer);
signer = NULL;
EVP_PKEY_free(key);
key = NULL;
}
/* If not streaming or resigning finalize structure */
if ((operation == SMIME_SIGN) && !(flags & PKCS7_STREAM)) {
if (!PKCS7_final(p7, in, flags))
goto end;
}
}
if (p7 == NULL) {
BIO_printf(bio_err, "Error creating PKCS#7 structure\n");
goto end;
}
ret = 4;
if (operation == SMIME_DECRYPT) {
if (!PKCS7_decrypt(p7, key, recip, out, flags)) {
BIO_printf(bio_err, "Error decrypting PKCS#7 structure\n");
goto end;
}
} else if (operation == SMIME_VERIFY) {
STACK_OF(X509) *signers;
if (PKCS7_verify(p7, other, store, indata, out, flags))
BIO_printf(bio_err, "Verification successful\n");
else {
BIO_printf(bio_err, "Verification failure\n");
goto end;
}
signers = PKCS7_get0_signers(p7, other, flags);
if (!save_certs(signerfile, signers)) {
BIO_printf(bio_err, "Error writing signers to %s\n", signerfile);
ret = 5;
goto end;
}
sk_X509_free(signers);
} else if (operation == SMIME_PK7OUT) {
PEM_write_bio_PKCS7(out, p7);
} else {
if (to)
BIO_printf(out, "To: %s%s", to, mime_eol);
if (from)
BIO_printf(out, "From: %s%s", from, mime_eol);
if (subject)
BIO_printf(out, "Subject: %s%s", subject, mime_eol);
if (outformat == FORMAT_SMIME) {
if (operation == SMIME_RESIGN)
rv = SMIME_write_PKCS7(out, p7, indata, flags);
else
rv = SMIME_write_PKCS7(out, p7, in, flags);
} else if (outformat == FORMAT_PEM) {
rv = PEM_write_bio_PKCS7_stream(out, p7, in, flags);
} else if (outformat == FORMAT_ASN1) {
rv = i2d_PKCS7_bio_stream(out, p7, in, flags);
} else {
BIO_printf(bio_err, "Bad output format for PKCS#7 file\n");
goto end;
}
if (rv == 0) {
BIO_printf(bio_err, "Error writing output\n");
ret = 3;
goto end;
}
}
ret = 0;
end:
if (ret)
ERR_print_errors(bio_err);
sk_X509_pop_free(encerts, X509_free);
sk_X509_pop_free(other, X509_free);
X509_VERIFY_PARAM_free(vpm);
sk_OPENSSL_STRING_free(sksigners);
sk_OPENSSL_STRING_free(skkeys);
X509_STORE_free(store);
X509_free(cert);
X509_free(recip);
X509_free(signer);
EVP_PKEY_free(key);
EVP_MD_free(sign_md);
EVP_CIPHER_free(cipher);
PKCS7_free(p7);
release_engine(e);
BIO_free(in);
BIO_free(indata);
BIO_free_all(out);
OPENSSL_free(passin);
NCONF_free(conf);
return ret;
}
static int save_certs(char *signerfile, STACK_OF(X509) *signers)
{
int i;
BIO *tmp;
if (signerfile == NULL)
return 1;
tmp = BIO_new_file(signerfile, "w");
if (tmp == NULL)
return 0;
for (i = 0; i < sk_X509_num(signers); i++)
PEM_write_bio_X509(tmp, sk_X509_value(signers, i));
BIO_free(tmp);
return 1;
}
/* Minimal callback just to output policy info (if any) */
static int smime_cb(int ok, X509_STORE_CTX *ctx)
{
int error;
error = X509_STORE_CTX_get_error(ctx);
if ((error != X509_V_ERR_NO_EXPLICIT_POLICY)
&& ((error != X509_V_OK) || (ok != 2)))
return ok;
policies_print(ctx);
return ok;
}
diff --git a/crypto/openssl/crypto/aes/asm/aesp8-ppc.pl b/crypto/openssl/crypto/aes/asm/aesp8-ppc.pl
index 60cf86f52aed..f7f78d04b0e1 100755
--- a/crypto/openssl/crypto/aes/asm/aesp8-ppc.pl
+++ b/crypto/openssl/crypto/aes/asm/aesp8-ppc.pl
@@ -1,3811 +1,3856 @@
#! /usr/bin/env perl
-# Copyright 2014-2020 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
#
# ====================================================================
# Written by Andy Polyakov <appro@openssl.org> for the OpenSSL
# project. The module is, however, dual licensed under OpenSSL and
# CRYPTOGAMS licenses depending on where you obtain it. For further
# details see http://www.openssl.org/~appro/cryptogams/.
# ====================================================================
#
# This module implements support for AES instructions as per PowerISA
# specification version 2.07, first implemented by POWER8 processor.
# The module is endian-agnostic in sense that it supports both big-
# and little-endian cases. Data alignment in parallelizable modes is
# handled with VSX loads and stores, which implies MSR.VSX flag being
# set. It should also be noted that ISA specification doesn't prohibit
# alignment exceptions for these instructions on page boundaries.
# Initially alignment was handled in pure AltiVec/VMX way [when data
# is aligned programmatically, which in turn guarantees exception-
# free execution], but it turned to hamper performance when vcipher
# instructions are interleaved. It's reckoned that eventual
# misalignment penalties at page boundaries are in average lower
# than additional overhead in pure AltiVec approach.
#
# May 2016
#
# Add XTS subroutine, 9x on little- and 12x improvement on big-endian
# systems were measured.
#
######################################################################
# Current large-block performance in cycles per byte processed with
# 128-bit key (less is better).
#
# CBC en-/decrypt CTR XTS
# POWER8[le] 3.96/0.72 0.74 1.1
# POWER8[be] 3.75/0.65 0.66 1.0
# POWER9[le] 4.02/0.86 0.84 1.05
# POWER9[be] 3.99/0.78 0.79 0.97
# $output is the last argument if it looks like a file (it has an extension)
# $flavour is the first argument if it doesn't look like a file
$output = $#ARGV >= 0 && $ARGV[$#ARGV] =~ m|\.\w+$| ? pop : undef;
$flavour = $#ARGV >= 0 && $ARGV[0] !~ m|\.| ? shift : undef;
if ($flavour =~ /64/) {
$SIZE_T =8;
$LRSAVE =2*$SIZE_T;
$STU ="stdu";
$POP ="ld";
$PUSH ="std";
$UCMP ="cmpld";
$SHL ="sldi";
} elsif ($flavour =~ /32/) {
$SIZE_T =4;
$LRSAVE =$SIZE_T;
$STU ="stwu";
$POP ="lwz";
$PUSH ="stw";
$UCMP ="cmplw";
$SHL ="slwi";
} else { die "nonsense $flavour"; }
$LITTLE_ENDIAN = ($flavour=~/le$/) ? $SIZE_T : 0;
$0 =~ m/(.*[\/\\])[^\/\\]+$/; $dir=$1;
( $xlate="${dir}ppc-xlate.pl" and -f $xlate ) or
( $xlate="${dir}../../perlasm/ppc-xlate.pl" and -f $xlate) or
die "can't locate ppc-xlate.pl";
open STDOUT,"| $^X $xlate $flavour \"$output\""
or die "can't call $xlate: $!";
$FRAME=8*$SIZE_T;
$prefix="aes_p8";
$sp="r1";
$vrsave="r12";
#########################################################################
{{{ # Key setup procedures #
my ($inp,$bits,$out,$ptr,$cnt,$rounds)=map("r$_",(3..8));
my ($zero,$in0,$in1,$key,$rcon,$mask,$tmp)=map("v$_",(0..6));
my ($stage,$outperm,$outmask,$outhead,$outtail)=map("v$_",(7..11));
$code.=<<___;
.machine "any"
.text
.align 7
rcon:
.long 0x01000000, 0x01000000, 0x01000000, 0x01000000 ?rev
.long 0x1b000000, 0x1b000000, 0x1b000000, 0x1b000000 ?rev
.long 0x0d0e0f0c, 0x0d0e0f0c, 0x0d0e0f0c, 0x0d0e0f0c ?rev
.long 0,0,0,0 ?asis
+.long 0x0f102132, 0x43546576, 0x8798a9ba, 0xcbdcedfe
Lconsts:
mflr r0
bcl 20,31,\$+4
mflr $ptr #vvvvv "distance between . and rcon
- addi $ptr,$ptr,-0x48
+ addi $ptr,$ptr,-0x58
mtlr r0
blr
.long 0
.byte 0,12,0x14,0,0,0,0,0
.asciz "AES for PowerISA 2.07, CRYPTOGAMS by <appro\@openssl.org>"
.globl .${prefix}_set_encrypt_key
.align 5
.${prefix}_set_encrypt_key:
Lset_encrypt_key:
mflr r11
$PUSH r11,$LRSAVE($sp)
li $ptr,-1
${UCMP}i $inp,0
beq- Lenc_key_abort # if ($inp==0) return -1;
${UCMP}i $out,0
beq- Lenc_key_abort # if ($out==0) return -1;
li $ptr,-2
cmpwi $bits,128
blt- Lenc_key_abort
cmpwi $bits,256
bgt- Lenc_key_abort
andi. r0,$bits,0x3f
bne- Lenc_key_abort
lis r0,0xfff0
mfspr $vrsave,256
mtspr 256,r0
bl Lconsts
mtlr r11
neg r9,$inp
lvx $in0,0,$inp
addi $inp,$inp,15 # 15 is not typo
lvsr $key,0,r9 # borrow $key
li r8,0x20
cmpwi $bits,192
lvx $in1,0,$inp
le?vspltisb $mask,0x0f # borrow $mask
lvx $rcon,0,$ptr
le?vxor $key,$key,$mask # adjust for byte swap
lvx $mask,r8,$ptr
addi $ptr,$ptr,0x10
vperm $in0,$in0,$in1,$key # align [and byte swap in LE]
li $cnt,8
vxor $zero,$zero,$zero
mtctr $cnt
?lvsr $outperm,0,$out
vspltisb $outmask,-1
lvx $outhead,0,$out
?vperm $outmask,$zero,$outmask,$outperm
blt Loop128
addi $inp,$inp,8
beq L192
addi $inp,$inp,8
b L256
.align 4
Loop128:
vperm $key,$in0,$in0,$mask # rotate-n-splat
vsldoi $tmp,$zero,$in0,12 # >>32
vperm $outtail,$in0,$in0,$outperm # rotate
vsel $stage,$outhead,$outtail,$outmask
vmr $outhead,$outtail
vcipherlast $key,$key,$rcon
stvx $stage,0,$out
addi $out,$out,16
vxor $in0,$in0,$tmp
vsldoi $tmp,$zero,$tmp,12 # >>32
vxor $in0,$in0,$tmp
vsldoi $tmp,$zero,$tmp,12 # >>32
vxor $in0,$in0,$tmp
vadduwm $rcon,$rcon,$rcon
vxor $in0,$in0,$key
bdnz Loop128
lvx $rcon,0,$ptr # last two round keys
vperm $key,$in0,$in0,$mask # rotate-n-splat
vsldoi $tmp,$zero,$in0,12 # >>32
vperm $outtail,$in0,$in0,$outperm # rotate
vsel $stage,$outhead,$outtail,$outmask
vmr $outhead,$outtail
vcipherlast $key,$key,$rcon
stvx $stage,0,$out
addi $out,$out,16
vxor $in0,$in0,$tmp
vsldoi $tmp,$zero,$tmp,12 # >>32
vxor $in0,$in0,$tmp
vsldoi $tmp,$zero,$tmp,12 # >>32
vxor $in0,$in0,$tmp
vadduwm $rcon,$rcon,$rcon
vxor $in0,$in0,$key
vperm $key,$in0,$in0,$mask # rotate-n-splat
vsldoi $tmp,$zero,$in0,12 # >>32
vperm $outtail,$in0,$in0,$outperm # rotate
vsel $stage,$outhead,$outtail,$outmask
vmr $outhead,$outtail
vcipherlast $key,$key,$rcon
stvx $stage,0,$out
addi $out,$out,16
vxor $in0,$in0,$tmp
vsldoi $tmp,$zero,$tmp,12 # >>32
vxor $in0,$in0,$tmp
vsldoi $tmp,$zero,$tmp,12 # >>32
vxor $in0,$in0,$tmp
vxor $in0,$in0,$key
vperm $outtail,$in0,$in0,$outperm # rotate
vsel $stage,$outhead,$outtail,$outmask
vmr $outhead,$outtail
stvx $stage,0,$out
addi $inp,$out,15 # 15 is not typo
addi $out,$out,0x50
li $rounds,10
b Ldone
.align 4
L192:
lvx $tmp,0,$inp
li $cnt,4
vperm $outtail,$in0,$in0,$outperm # rotate
vsel $stage,$outhead,$outtail,$outmask
vmr $outhead,$outtail
stvx $stage,0,$out
addi $out,$out,16
vperm $in1,$in1,$tmp,$key # align [and byte swap in LE]
vspltisb $key,8 # borrow $key
mtctr $cnt
vsububm $mask,$mask,$key # adjust the mask
Loop192:
vperm $key,$in1,$in1,$mask # roate-n-splat
vsldoi $tmp,$zero,$in0,12 # >>32
vcipherlast $key,$key,$rcon
vxor $in0,$in0,$tmp
vsldoi $tmp,$zero,$tmp,12 # >>32
vxor $in0,$in0,$tmp
vsldoi $tmp,$zero,$tmp,12 # >>32
vxor $in0,$in0,$tmp
vsldoi $stage,$zero,$in1,8
vspltw $tmp,$in0,3
vxor $tmp,$tmp,$in1
vsldoi $in1,$zero,$in1,12 # >>32
vadduwm $rcon,$rcon,$rcon
vxor $in1,$in1,$tmp
vxor $in0,$in0,$key
vxor $in1,$in1,$key
vsldoi $stage,$stage,$in0,8
vperm $key,$in1,$in1,$mask # rotate-n-splat
vsldoi $tmp,$zero,$in0,12 # >>32
vperm $outtail,$stage,$stage,$outperm # rotate
vsel $stage,$outhead,$outtail,$outmask
vmr $outhead,$outtail
vcipherlast $key,$key,$rcon
stvx $stage,0,$out
addi $out,$out,16
vsldoi $stage,$in0,$in1,8
vxor $in0,$in0,$tmp
vsldoi $tmp,$zero,$tmp,12 # >>32
vperm $outtail,$stage,$stage,$outperm # rotate
vsel $stage,$outhead,$outtail,$outmask
vmr $outhead,$outtail
vxor $in0,$in0,$tmp
vsldoi $tmp,$zero,$tmp,12 # >>32
vxor $in0,$in0,$tmp
stvx $stage,0,$out
addi $out,$out,16
vspltw $tmp,$in0,3
vxor $tmp,$tmp,$in1
vsldoi $in1,$zero,$in1,12 # >>32
vadduwm $rcon,$rcon,$rcon
vxor $in1,$in1,$tmp
vxor $in0,$in0,$key
vxor $in1,$in1,$key
vperm $outtail,$in0,$in0,$outperm # rotate
vsel $stage,$outhead,$outtail,$outmask
vmr $outhead,$outtail
stvx $stage,0,$out
addi $inp,$out,15 # 15 is not typo
addi $out,$out,16
bdnz Loop192
li $rounds,12
addi $out,$out,0x20
b Ldone
.align 4
L256:
lvx $tmp,0,$inp
li $cnt,7
li $rounds,14
vperm $outtail,$in0,$in0,$outperm # rotate
vsel $stage,$outhead,$outtail,$outmask
vmr $outhead,$outtail
stvx $stage,0,$out
addi $out,$out,16
vperm $in1,$in1,$tmp,$key # align [and byte swap in LE]
mtctr $cnt
Loop256:
vperm $key,$in1,$in1,$mask # rotate-n-splat
vsldoi $tmp,$zero,$in0,12 # >>32
vperm $outtail,$in1,$in1,$outperm # rotate
vsel $stage,$outhead,$outtail,$outmask
vmr $outhead,$outtail
vcipherlast $key,$key,$rcon
stvx $stage,0,$out
addi $out,$out,16
vxor $in0,$in0,$tmp
vsldoi $tmp,$zero,$tmp,12 # >>32
vxor $in0,$in0,$tmp
vsldoi $tmp,$zero,$tmp,12 # >>32
vxor $in0,$in0,$tmp
vadduwm $rcon,$rcon,$rcon
vxor $in0,$in0,$key
vperm $outtail,$in0,$in0,$outperm # rotate
vsel $stage,$outhead,$outtail,$outmask
vmr $outhead,$outtail
stvx $stage,0,$out
addi $inp,$out,15 # 15 is not typo
addi $out,$out,16
bdz Ldone
vspltw $key,$in0,3 # just splat
vsldoi $tmp,$zero,$in1,12 # >>32
vsbox $key,$key
vxor $in1,$in1,$tmp
vsldoi $tmp,$zero,$tmp,12 # >>32
vxor $in1,$in1,$tmp
vsldoi $tmp,$zero,$tmp,12 # >>32
vxor $in1,$in1,$tmp
vxor $in1,$in1,$key
b Loop256
.align 4
Ldone:
lvx $in1,0,$inp # redundant in aligned case
vsel $in1,$outhead,$in1,$outmask
stvx $in1,0,$inp
li $ptr,0
mtspr 256,$vrsave
stw $rounds,0($out)
Lenc_key_abort:
mr r3,$ptr
blr
.long 0
.byte 0,12,0x14,1,0,0,3,0
.long 0
.size .${prefix}_set_encrypt_key,.-.${prefix}_set_encrypt_key
.globl .${prefix}_set_decrypt_key
.align 5
.${prefix}_set_decrypt_key:
$STU $sp,-$FRAME($sp)
mflr r10
$PUSH r10,$FRAME+$LRSAVE($sp)
bl Lset_encrypt_key
mtlr r10
cmpwi r3,0
bne- Ldec_key_abort
slwi $cnt,$rounds,4
subi $inp,$out,240 # first round key
srwi $rounds,$rounds,1
add $out,$inp,$cnt # last round key
mtctr $rounds
Ldeckey:
lwz r0, 0($inp)
lwz r6, 4($inp)
lwz r7, 8($inp)
lwz r8, 12($inp)
addi $inp,$inp,16
lwz r9, 0($out)
lwz r10,4($out)
lwz r11,8($out)
lwz r12,12($out)
stw r0, 0($out)
stw r6, 4($out)
stw r7, 8($out)
stw r8, 12($out)
subi $out,$out,16
stw r9, -16($inp)
stw r10,-12($inp)
stw r11,-8($inp)
stw r12,-4($inp)
bdnz Ldeckey
xor r3,r3,r3 # return value
Ldec_key_abort:
addi $sp,$sp,$FRAME
blr
.long 0
.byte 0,12,4,1,0x80,0,3,0
.long 0
.size .${prefix}_set_decrypt_key,.-.${prefix}_set_decrypt_key
___
}}}
#########################################################################
{{{ # Single block en- and decrypt procedures #
sub gen_block () {
my $dir = shift;
my $n = $dir eq "de" ? "n" : "";
my ($inp,$out,$key,$rounds,$idx)=map("r$_",(3..7));
$code.=<<___;
.globl .${prefix}_${dir}crypt
.align 5
.${prefix}_${dir}crypt:
lwz $rounds,240($key)
lis r0,0xfc00
mfspr $vrsave,256
li $idx,15 # 15 is not typo
mtspr 256,r0
lvx v0,0,$inp
neg r11,$out
lvx v1,$idx,$inp
lvsl v2,0,$inp # inpperm
le?vspltisb v4,0x0f
?lvsl v3,0,r11 # outperm
le?vxor v2,v2,v4
li $idx,16
vperm v0,v0,v1,v2 # align [and byte swap in LE]
lvx v1,0,$key
?lvsl v5,0,$key # keyperm
srwi $rounds,$rounds,1
lvx v2,$idx,$key
addi $idx,$idx,16
subi $rounds,$rounds,1
?vperm v1,v1,v2,v5 # align round key
vxor v0,v0,v1
lvx v1,$idx,$key
addi $idx,$idx,16
mtctr $rounds
Loop_${dir}c:
?vperm v2,v2,v1,v5
v${n}cipher v0,v0,v2
lvx v2,$idx,$key
addi $idx,$idx,16
?vperm v1,v1,v2,v5
v${n}cipher v0,v0,v1
lvx v1,$idx,$key
addi $idx,$idx,16
bdnz Loop_${dir}c
?vperm v2,v2,v1,v5
v${n}cipher v0,v0,v2
lvx v2,$idx,$key
?vperm v1,v1,v2,v5
v${n}cipherlast v0,v0,v1
vspltisb v2,-1
vxor v1,v1,v1
li $idx,15 # 15 is not typo
?vperm v2,v1,v2,v3 # outmask
le?vxor v3,v3,v4
lvx v1,0,$out # outhead
vperm v0,v0,v0,v3 # rotate [and byte swap in LE]
vsel v1,v1,v0,v2
lvx v4,$idx,$out
stvx v1,0,$out
vsel v0,v0,v4,v2
stvx v0,$idx,$out
mtspr 256,$vrsave
blr
.long 0
.byte 0,12,0x14,0,0,0,3,0
.long 0
.size .${prefix}_${dir}crypt,.-.${prefix}_${dir}crypt
___
}
&gen_block("en");
&gen_block("de");
}}}
#########################################################################
{{{ # CBC en- and decrypt procedures #
my ($inp,$out,$len,$key,$ivp,$enc,$rounds,$idx)=map("r$_",(3..10));
my ($rndkey0,$rndkey1,$inout,$tmp)= map("v$_",(0..3));
my ($ivec,$inptail,$inpperm,$outhead,$outperm,$outmask,$keyperm)=
map("v$_",(4..10));
$code.=<<___;
.globl .${prefix}_cbc_encrypt
.align 5
.${prefix}_cbc_encrypt:
${UCMP}i $len,16
bltlr-
cmpwi $enc,0 # test direction
lis r0,0xffe0
mfspr $vrsave,256
mtspr 256,r0
li $idx,15
vxor $rndkey0,$rndkey0,$rndkey0
le?vspltisb $tmp,0x0f
lvx $ivec,0,$ivp # load [unaligned] iv
lvsl $inpperm,0,$ivp
lvx $inptail,$idx,$ivp
le?vxor $inpperm,$inpperm,$tmp
vperm $ivec,$ivec,$inptail,$inpperm
neg r11,$inp
?lvsl $keyperm,0,$key # prepare for unaligned key
lwz $rounds,240($key)
lvsr $inpperm,0,r11 # prepare for unaligned load
lvx $inptail,0,$inp
addi $inp,$inp,15 # 15 is not typo
le?vxor $inpperm,$inpperm,$tmp
?lvsr $outperm,0,$out # prepare for unaligned store
vspltisb $outmask,-1
lvx $outhead,0,$out
?vperm $outmask,$rndkey0,$outmask,$outperm
le?vxor $outperm,$outperm,$tmp
srwi $rounds,$rounds,1
li $idx,16
subi $rounds,$rounds,1
beq Lcbc_dec
Lcbc_enc:
vmr $inout,$inptail
lvx $inptail,0,$inp
addi $inp,$inp,16
mtctr $rounds
subi $len,$len,16 # len-=16
lvx $rndkey0,0,$key
vperm $inout,$inout,$inptail,$inpperm
lvx $rndkey1,$idx,$key
addi $idx,$idx,16
?vperm $rndkey0,$rndkey0,$rndkey1,$keyperm
vxor $inout,$inout,$rndkey0
lvx $rndkey0,$idx,$key
addi $idx,$idx,16
vxor $inout,$inout,$ivec
Loop_cbc_enc:
?vperm $rndkey1,$rndkey1,$rndkey0,$keyperm
vcipher $inout,$inout,$rndkey1
lvx $rndkey1,$idx,$key
addi $idx,$idx,16
?vperm $rndkey0,$rndkey0,$rndkey1,$keyperm
vcipher $inout,$inout,$rndkey0
lvx $rndkey0,$idx,$key
addi $idx,$idx,16
bdnz Loop_cbc_enc
?vperm $rndkey1,$rndkey1,$rndkey0,$keyperm
vcipher $inout,$inout,$rndkey1
lvx $rndkey1,$idx,$key
li $idx,16
?vperm $rndkey0,$rndkey0,$rndkey1,$keyperm
vcipherlast $ivec,$inout,$rndkey0
${UCMP}i $len,16
vperm $tmp,$ivec,$ivec,$outperm
vsel $inout,$outhead,$tmp,$outmask
vmr $outhead,$tmp
stvx $inout,0,$out
addi $out,$out,16
bge Lcbc_enc
b Lcbc_done
.align 4
Lcbc_dec:
${UCMP}i $len,128
bge _aesp8_cbc_decrypt8x
vmr $tmp,$inptail
lvx $inptail,0,$inp
addi $inp,$inp,16
mtctr $rounds
subi $len,$len,16 # len-=16
lvx $rndkey0,0,$key
vperm $tmp,$tmp,$inptail,$inpperm
lvx $rndkey1,$idx,$key
addi $idx,$idx,16
?vperm $rndkey0,$rndkey0,$rndkey1,$keyperm
vxor $inout,$tmp,$rndkey0
lvx $rndkey0,$idx,$key
addi $idx,$idx,16
Loop_cbc_dec:
?vperm $rndkey1,$rndkey1,$rndkey0,$keyperm
vncipher $inout,$inout,$rndkey1
lvx $rndkey1,$idx,$key
addi $idx,$idx,16
?vperm $rndkey0,$rndkey0,$rndkey1,$keyperm
vncipher $inout,$inout,$rndkey0
lvx $rndkey0,$idx,$key
addi $idx,$idx,16
bdnz Loop_cbc_dec
?vperm $rndkey1,$rndkey1,$rndkey0,$keyperm
vncipher $inout,$inout,$rndkey1
lvx $rndkey1,$idx,$key
li $idx,16
?vperm $rndkey0,$rndkey0,$rndkey1,$keyperm
vncipherlast $inout,$inout,$rndkey0
${UCMP}i $len,16
vxor $inout,$inout,$ivec
vmr $ivec,$tmp
vperm $tmp,$inout,$inout,$outperm
vsel $inout,$outhead,$tmp,$outmask
vmr $outhead,$tmp
stvx $inout,0,$out
addi $out,$out,16
bge Lcbc_dec
Lcbc_done:
addi $out,$out,-1
lvx $inout,0,$out # redundant in aligned case
vsel $inout,$outhead,$inout,$outmask
stvx $inout,0,$out
neg $enc,$ivp # write [unaligned] iv
li $idx,15 # 15 is not typo
vxor $rndkey0,$rndkey0,$rndkey0
vspltisb $outmask,-1
le?vspltisb $tmp,0x0f
?lvsl $outperm,0,$enc
?vperm $outmask,$rndkey0,$outmask,$outperm
le?vxor $outperm,$outperm,$tmp
lvx $outhead,0,$ivp
vperm $ivec,$ivec,$ivec,$outperm
vsel $inout,$outhead,$ivec,$outmask
lvx $inptail,$idx,$ivp
stvx $inout,0,$ivp
vsel $inout,$ivec,$inptail,$outmask
stvx $inout,$idx,$ivp
mtspr 256,$vrsave
blr
.long 0
.byte 0,12,0x14,0,0,0,6,0
.long 0
___
#########################################################################
{{ # Optimized CBC decrypt procedure #
my $key_="r11";
my ($x00,$x10,$x20,$x30,$x40,$x50,$x60,$x70)=map("r$_",(0,8,26..31));
$x00=0 if ($flavour =~ /osx/);
my ($in0, $in1, $in2, $in3, $in4, $in5, $in6, $in7 )=map("v$_",(0..3,10..13));
my ($out0,$out1,$out2,$out3,$out4,$out5,$out6,$out7)=map("v$_",(14..21));
my $rndkey0="v23"; # v24-v25 rotating buffer for first found keys
# v26-v31 last 6 round keys
my ($tmp,$keyperm)=($in3,$in4); # aliases with "caller", redundant assignment
$code.=<<___;
.align 5
_aesp8_cbc_decrypt8x:
$STU $sp,-`($FRAME+21*16+6*$SIZE_T)`($sp)
li r10,`$FRAME+8*16+15`
li r11,`$FRAME+8*16+31`
stvx v20,r10,$sp # ABI says so
addi r10,r10,32
stvx v21,r11,$sp
addi r11,r11,32
stvx v22,r10,$sp
addi r10,r10,32
stvx v23,r11,$sp
addi r11,r11,32
stvx v24,r10,$sp
addi r10,r10,32
stvx v25,r11,$sp
addi r11,r11,32
stvx v26,r10,$sp
addi r10,r10,32
stvx v27,r11,$sp
addi r11,r11,32
stvx v28,r10,$sp
addi r10,r10,32
stvx v29,r11,$sp
addi r11,r11,32
stvx v30,r10,$sp
stvx v31,r11,$sp
li r0,-1
stw $vrsave,`$FRAME+21*16-4`($sp) # save vrsave
li $x10,0x10
$PUSH r26,`$FRAME+21*16+0*$SIZE_T`($sp)
li $x20,0x20
$PUSH r27,`$FRAME+21*16+1*$SIZE_T`($sp)
li $x30,0x30
$PUSH r28,`$FRAME+21*16+2*$SIZE_T`($sp)
li $x40,0x40
$PUSH r29,`$FRAME+21*16+3*$SIZE_T`($sp)
li $x50,0x50
$PUSH r30,`$FRAME+21*16+4*$SIZE_T`($sp)
li $x60,0x60
$PUSH r31,`$FRAME+21*16+5*$SIZE_T`($sp)
li $x70,0x70
mtspr 256,r0
subi $rounds,$rounds,3 # -4 in total
subi $len,$len,128 # bias
lvx $rndkey0,$x00,$key # load key schedule
lvx v30,$x10,$key
addi $key,$key,0x20
lvx v31,$x00,$key
?vperm $rndkey0,$rndkey0,v30,$keyperm
addi $key_,$sp,$FRAME+15
mtctr $rounds
Load_cbc_dec_key:
?vperm v24,v30,v31,$keyperm
lvx v30,$x10,$key
addi $key,$key,0x20
stvx v24,$x00,$key_ # off-load round[1]
?vperm v25,v31,v30,$keyperm
lvx v31,$x00,$key
stvx v25,$x10,$key_ # off-load round[2]
addi $key_,$key_,0x20
bdnz Load_cbc_dec_key
lvx v26,$x10,$key
?vperm v24,v30,v31,$keyperm
lvx v27,$x20,$key
stvx v24,$x00,$key_ # off-load round[3]
?vperm v25,v31,v26,$keyperm
lvx v28,$x30,$key
stvx v25,$x10,$key_ # off-load round[4]
addi $key_,$sp,$FRAME+15 # rewind $key_
?vperm v26,v26,v27,$keyperm
lvx v29,$x40,$key
?vperm v27,v27,v28,$keyperm
lvx v30,$x50,$key
?vperm v28,v28,v29,$keyperm
lvx v31,$x60,$key
?vperm v29,v29,v30,$keyperm
lvx $out0,$x70,$key # borrow $out0
?vperm v30,v30,v31,$keyperm
lvx v24,$x00,$key_ # pre-load round[1]
?vperm v31,v31,$out0,$keyperm
lvx v25,$x10,$key_ # pre-load round[2]
#lvx $inptail,0,$inp # "caller" already did this
#addi $inp,$inp,15 # 15 is not typo
subi $inp,$inp,15 # undo "caller"
le?li $idx,8
lvx_u $in0,$x00,$inp # load first 8 "words"
le?lvsl $inpperm,0,$idx
le?vspltisb $tmp,0x0f
lvx_u $in1,$x10,$inp
le?vxor $inpperm,$inpperm,$tmp # transform for lvx_u/stvx_u
lvx_u $in2,$x20,$inp
le?vperm $in0,$in0,$in0,$inpperm
lvx_u $in3,$x30,$inp
le?vperm $in1,$in1,$in1,$inpperm
lvx_u $in4,$x40,$inp
le?vperm $in2,$in2,$in2,$inpperm
vxor $out0,$in0,$rndkey0
lvx_u $in5,$x50,$inp
le?vperm $in3,$in3,$in3,$inpperm
vxor $out1,$in1,$rndkey0
lvx_u $in6,$x60,$inp
le?vperm $in4,$in4,$in4,$inpperm
vxor $out2,$in2,$rndkey0
lvx_u $in7,$x70,$inp
addi $inp,$inp,0x80
le?vperm $in5,$in5,$in5,$inpperm
vxor $out3,$in3,$rndkey0
le?vperm $in6,$in6,$in6,$inpperm
vxor $out4,$in4,$rndkey0
le?vperm $in7,$in7,$in7,$inpperm
vxor $out5,$in5,$rndkey0
vxor $out6,$in6,$rndkey0
vxor $out7,$in7,$rndkey0
mtctr $rounds
b Loop_cbc_dec8x
.align 5
Loop_cbc_dec8x:
vncipher $out0,$out0,v24
vncipher $out1,$out1,v24
vncipher $out2,$out2,v24
vncipher $out3,$out3,v24
vncipher $out4,$out4,v24
vncipher $out5,$out5,v24
vncipher $out6,$out6,v24
vncipher $out7,$out7,v24
lvx v24,$x20,$key_ # round[3]
addi $key_,$key_,0x20
vncipher $out0,$out0,v25
vncipher $out1,$out1,v25
vncipher $out2,$out2,v25
vncipher $out3,$out3,v25
vncipher $out4,$out4,v25
vncipher $out5,$out5,v25
vncipher $out6,$out6,v25
vncipher $out7,$out7,v25
lvx v25,$x10,$key_ # round[4]
bdnz Loop_cbc_dec8x
subic $len,$len,128 # $len-=128
vncipher $out0,$out0,v24
vncipher $out1,$out1,v24
vncipher $out2,$out2,v24
vncipher $out3,$out3,v24
vncipher $out4,$out4,v24
vncipher $out5,$out5,v24
vncipher $out6,$out6,v24
vncipher $out7,$out7,v24
subfe. r0,r0,r0 # borrow?-1:0
vncipher $out0,$out0,v25
vncipher $out1,$out1,v25
vncipher $out2,$out2,v25
vncipher $out3,$out3,v25
vncipher $out4,$out4,v25
vncipher $out5,$out5,v25
vncipher $out6,$out6,v25
vncipher $out7,$out7,v25
and r0,r0,$len
vncipher $out0,$out0,v26
vncipher $out1,$out1,v26
vncipher $out2,$out2,v26
vncipher $out3,$out3,v26
vncipher $out4,$out4,v26
vncipher $out5,$out5,v26
vncipher $out6,$out6,v26
vncipher $out7,$out7,v26
add $inp,$inp,r0 # $inp is adjusted in such
# way that at exit from the
# loop inX-in7 are loaded
# with last "words"
vncipher $out0,$out0,v27
vncipher $out1,$out1,v27
vncipher $out2,$out2,v27
vncipher $out3,$out3,v27
vncipher $out4,$out4,v27
vncipher $out5,$out5,v27
vncipher $out6,$out6,v27
vncipher $out7,$out7,v27
addi $key_,$sp,$FRAME+15 # rewind $key_
vncipher $out0,$out0,v28
vncipher $out1,$out1,v28
vncipher $out2,$out2,v28
vncipher $out3,$out3,v28
vncipher $out4,$out4,v28
vncipher $out5,$out5,v28
vncipher $out6,$out6,v28
vncipher $out7,$out7,v28
lvx v24,$x00,$key_ # re-pre-load round[1]
vncipher $out0,$out0,v29
vncipher $out1,$out1,v29
vncipher $out2,$out2,v29
vncipher $out3,$out3,v29
vncipher $out4,$out4,v29
vncipher $out5,$out5,v29
vncipher $out6,$out6,v29
vncipher $out7,$out7,v29
lvx v25,$x10,$key_ # re-pre-load round[2]
vncipher $out0,$out0,v30
vxor $ivec,$ivec,v31 # xor with last round key
vncipher $out1,$out1,v30
vxor $in0,$in0,v31
vncipher $out2,$out2,v30
vxor $in1,$in1,v31
vncipher $out3,$out3,v30
vxor $in2,$in2,v31
vncipher $out4,$out4,v30
vxor $in3,$in3,v31
vncipher $out5,$out5,v30
vxor $in4,$in4,v31
vncipher $out6,$out6,v30
vxor $in5,$in5,v31
vncipher $out7,$out7,v30
vxor $in6,$in6,v31
vncipherlast $out0,$out0,$ivec
vncipherlast $out1,$out1,$in0
lvx_u $in0,$x00,$inp # load next input block
vncipherlast $out2,$out2,$in1
lvx_u $in1,$x10,$inp
vncipherlast $out3,$out3,$in2
le?vperm $in0,$in0,$in0,$inpperm
lvx_u $in2,$x20,$inp
vncipherlast $out4,$out4,$in3
le?vperm $in1,$in1,$in1,$inpperm
lvx_u $in3,$x30,$inp
vncipherlast $out5,$out5,$in4
le?vperm $in2,$in2,$in2,$inpperm
lvx_u $in4,$x40,$inp
vncipherlast $out6,$out6,$in5
le?vperm $in3,$in3,$in3,$inpperm
lvx_u $in5,$x50,$inp
vncipherlast $out7,$out7,$in6
le?vperm $in4,$in4,$in4,$inpperm
lvx_u $in6,$x60,$inp
vmr $ivec,$in7
le?vperm $in5,$in5,$in5,$inpperm
lvx_u $in7,$x70,$inp
addi $inp,$inp,0x80
le?vperm $out0,$out0,$out0,$inpperm
le?vperm $out1,$out1,$out1,$inpperm
stvx_u $out0,$x00,$out
le?vperm $in6,$in6,$in6,$inpperm
vxor $out0,$in0,$rndkey0
le?vperm $out2,$out2,$out2,$inpperm
stvx_u $out1,$x10,$out
le?vperm $in7,$in7,$in7,$inpperm
vxor $out1,$in1,$rndkey0
le?vperm $out3,$out3,$out3,$inpperm
stvx_u $out2,$x20,$out
vxor $out2,$in2,$rndkey0
le?vperm $out4,$out4,$out4,$inpperm
stvx_u $out3,$x30,$out
vxor $out3,$in3,$rndkey0
le?vperm $out5,$out5,$out5,$inpperm
stvx_u $out4,$x40,$out
vxor $out4,$in4,$rndkey0
le?vperm $out6,$out6,$out6,$inpperm
stvx_u $out5,$x50,$out
vxor $out5,$in5,$rndkey0
le?vperm $out7,$out7,$out7,$inpperm
stvx_u $out6,$x60,$out
vxor $out6,$in6,$rndkey0
stvx_u $out7,$x70,$out
addi $out,$out,0x80
vxor $out7,$in7,$rndkey0
mtctr $rounds
beq Loop_cbc_dec8x # did $len-=128 borrow?
addic. $len,$len,128
beq Lcbc_dec8x_done
nop
nop
Loop_cbc_dec8x_tail: # up to 7 "words" tail...
vncipher $out1,$out1,v24
vncipher $out2,$out2,v24
vncipher $out3,$out3,v24
vncipher $out4,$out4,v24
vncipher $out5,$out5,v24
vncipher $out6,$out6,v24
vncipher $out7,$out7,v24
lvx v24,$x20,$key_ # round[3]
addi $key_,$key_,0x20
vncipher $out1,$out1,v25
vncipher $out2,$out2,v25
vncipher $out3,$out3,v25
vncipher $out4,$out4,v25
vncipher $out5,$out5,v25
vncipher $out6,$out6,v25
vncipher $out7,$out7,v25
lvx v25,$x10,$key_ # round[4]
bdnz Loop_cbc_dec8x_tail
vncipher $out1,$out1,v24
vncipher $out2,$out2,v24
vncipher $out3,$out3,v24
vncipher $out4,$out4,v24
vncipher $out5,$out5,v24
vncipher $out6,$out6,v24
vncipher $out7,$out7,v24
vncipher $out1,$out1,v25
vncipher $out2,$out2,v25
vncipher $out3,$out3,v25
vncipher $out4,$out4,v25
vncipher $out5,$out5,v25
vncipher $out6,$out6,v25
vncipher $out7,$out7,v25
vncipher $out1,$out1,v26
vncipher $out2,$out2,v26
vncipher $out3,$out3,v26
vncipher $out4,$out4,v26
vncipher $out5,$out5,v26
vncipher $out6,$out6,v26
vncipher $out7,$out7,v26
vncipher $out1,$out1,v27
vncipher $out2,$out2,v27
vncipher $out3,$out3,v27
vncipher $out4,$out4,v27
vncipher $out5,$out5,v27
vncipher $out6,$out6,v27
vncipher $out7,$out7,v27
vncipher $out1,$out1,v28
vncipher $out2,$out2,v28
vncipher $out3,$out3,v28
vncipher $out4,$out4,v28
vncipher $out5,$out5,v28
vncipher $out6,$out6,v28
vncipher $out7,$out7,v28
vncipher $out1,$out1,v29
vncipher $out2,$out2,v29
vncipher $out3,$out3,v29
vncipher $out4,$out4,v29
vncipher $out5,$out5,v29
vncipher $out6,$out6,v29
vncipher $out7,$out7,v29
vncipher $out1,$out1,v30
vxor $ivec,$ivec,v31 # last round key
vncipher $out2,$out2,v30
vxor $in1,$in1,v31
vncipher $out3,$out3,v30
vxor $in2,$in2,v31
vncipher $out4,$out4,v30
vxor $in3,$in3,v31
vncipher $out5,$out5,v30
vxor $in4,$in4,v31
vncipher $out6,$out6,v30
vxor $in5,$in5,v31
vncipher $out7,$out7,v30
vxor $in6,$in6,v31
cmplwi $len,32 # switch($len)
blt Lcbc_dec8x_one
nop
beq Lcbc_dec8x_two
cmplwi $len,64
blt Lcbc_dec8x_three
nop
beq Lcbc_dec8x_four
cmplwi $len,96
blt Lcbc_dec8x_five
nop
beq Lcbc_dec8x_six
Lcbc_dec8x_seven:
vncipherlast $out1,$out1,$ivec
vncipherlast $out2,$out2,$in1
vncipherlast $out3,$out3,$in2
vncipherlast $out4,$out4,$in3
vncipherlast $out5,$out5,$in4
vncipherlast $out6,$out6,$in5
vncipherlast $out7,$out7,$in6
vmr $ivec,$in7
le?vperm $out1,$out1,$out1,$inpperm
le?vperm $out2,$out2,$out2,$inpperm
stvx_u $out1,$x00,$out
le?vperm $out3,$out3,$out3,$inpperm
stvx_u $out2,$x10,$out
le?vperm $out4,$out4,$out4,$inpperm
stvx_u $out3,$x20,$out
le?vperm $out5,$out5,$out5,$inpperm
stvx_u $out4,$x30,$out
le?vperm $out6,$out6,$out6,$inpperm
stvx_u $out5,$x40,$out
le?vperm $out7,$out7,$out7,$inpperm
stvx_u $out6,$x50,$out
stvx_u $out7,$x60,$out
addi $out,$out,0x70
b Lcbc_dec8x_done
.align 5
Lcbc_dec8x_six:
vncipherlast $out2,$out2,$ivec
vncipherlast $out3,$out3,$in2
vncipherlast $out4,$out4,$in3
vncipherlast $out5,$out5,$in4
vncipherlast $out6,$out6,$in5
vncipherlast $out7,$out7,$in6
vmr $ivec,$in7
le?vperm $out2,$out2,$out2,$inpperm
le?vperm $out3,$out3,$out3,$inpperm
stvx_u $out2,$x00,$out
le?vperm $out4,$out4,$out4,$inpperm
stvx_u $out3,$x10,$out
le?vperm $out5,$out5,$out5,$inpperm
stvx_u $out4,$x20,$out
le?vperm $out6,$out6,$out6,$inpperm
stvx_u $out5,$x30,$out
le?vperm $out7,$out7,$out7,$inpperm
stvx_u $out6,$x40,$out
stvx_u $out7,$x50,$out
addi $out,$out,0x60
b Lcbc_dec8x_done
.align 5
Lcbc_dec8x_five:
vncipherlast $out3,$out3,$ivec
vncipherlast $out4,$out4,$in3
vncipherlast $out5,$out5,$in4
vncipherlast $out6,$out6,$in5
vncipherlast $out7,$out7,$in6
vmr $ivec,$in7
le?vperm $out3,$out3,$out3,$inpperm
le?vperm $out4,$out4,$out4,$inpperm
stvx_u $out3,$x00,$out
le?vperm $out5,$out5,$out5,$inpperm
stvx_u $out4,$x10,$out
le?vperm $out6,$out6,$out6,$inpperm
stvx_u $out5,$x20,$out
le?vperm $out7,$out7,$out7,$inpperm
stvx_u $out6,$x30,$out
stvx_u $out7,$x40,$out
addi $out,$out,0x50
b Lcbc_dec8x_done
.align 5
Lcbc_dec8x_four:
vncipherlast $out4,$out4,$ivec
vncipherlast $out5,$out5,$in4
vncipherlast $out6,$out6,$in5
vncipherlast $out7,$out7,$in6
vmr $ivec,$in7
le?vperm $out4,$out4,$out4,$inpperm
le?vperm $out5,$out5,$out5,$inpperm
stvx_u $out4,$x00,$out
le?vperm $out6,$out6,$out6,$inpperm
stvx_u $out5,$x10,$out
le?vperm $out7,$out7,$out7,$inpperm
stvx_u $out6,$x20,$out
stvx_u $out7,$x30,$out
addi $out,$out,0x40
b Lcbc_dec8x_done
.align 5
Lcbc_dec8x_three:
vncipherlast $out5,$out5,$ivec
vncipherlast $out6,$out6,$in5
vncipherlast $out7,$out7,$in6
vmr $ivec,$in7
le?vperm $out5,$out5,$out5,$inpperm
le?vperm $out6,$out6,$out6,$inpperm
stvx_u $out5,$x00,$out
le?vperm $out7,$out7,$out7,$inpperm
stvx_u $out6,$x10,$out
stvx_u $out7,$x20,$out
addi $out,$out,0x30
b Lcbc_dec8x_done
.align 5
Lcbc_dec8x_two:
vncipherlast $out6,$out6,$ivec
vncipherlast $out7,$out7,$in6
vmr $ivec,$in7
le?vperm $out6,$out6,$out6,$inpperm
le?vperm $out7,$out7,$out7,$inpperm
stvx_u $out6,$x00,$out
stvx_u $out7,$x10,$out
addi $out,$out,0x20
b Lcbc_dec8x_done
.align 5
Lcbc_dec8x_one:
vncipherlast $out7,$out7,$ivec
vmr $ivec,$in7
le?vperm $out7,$out7,$out7,$inpperm
stvx_u $out7,0,$out
addi $out,$out,0x10
Lcbc_dec8x_done:
le?vperm $ivec,$ivec,$ivec,$inpperm
stvx_u $ivec,0,$ivp # write [unaligned] iv
li r10,`$FRAME+15`
li r11,`$FRAME+31`
stvx $inpperm,r10,$sp # wipe copies of round keys
addi r10,r10,32
stvx $inpperm,r11,$sp
addi r11,r11,32
stvx $inpperm,r10,$sp
addi r10,r10,32
stvx $inpperm,r11,$sp
addi r11,r11,32
stvx $inpperm,r10,$sp
addi r10,r10,32
stvx $inpperm,r11,$sp
addi r11,r11,32
stvx $inpperm,r10,$sp
addi r10,r10,32
stvx $inpperm,r11,$sp
addi r11,r11,32
mtspr 256,$vrsave
lvx v20,r10,$sp # ABI says so
addi r10,r10,32
lvx v21,r11,$sp
addi r11,r11,32
lvx v22,r10,$sp
addi r10,r10,32
lvx v23,r11,$sp
addi r11,r11,32
lvx v24,r10,$sp
addi r10,r10,32
lvx v25,r11,$sp
addi r11,r11,32
lvx v26,r10,$sp
addi r10,r10,32
lvx v27,r11,$sp
addi r11,r11,32
lvx v28,r10,$sp
addi r10,r10,32
lvx v29,r11,$sp
addi r11,r11,32
lvx v30,r10,$sp
lvx v31,r11,$sp
$POP r26,`$FRAME+21*16+0*$SIZE_T`($sp)
$POP r27,`$FRAME+21*16+1*$SIZE_T`($sp)
$POP r28,`$FRAME+21*16+2*$SIZE_T`($sp)
$POP r29,`$FRAME+21*16+3*$SIZE_T`($sp)
$POP r30,`$FRAME+21*16+4*$SIZE_T`($sp)
$POP r31,`$FRAME+21*16+5*$SIZE_T`($sp)
addi $sp,$sp,`$FRAME+21*16+6*$SIZE_T`
blr
.long 0
.byte 0,12,0x04,0,0x80,6,6,0
.long 0
.size .${prefix}_cbc_encrypt,.-.${prefix}_cbc_encrypt
___
}} }}}
#########################################################################
{{{ # CTR procedure[s] #
my ($inp,$out,$len,$key,$ivp,$x10,$rounds,$idx)=map("r$_",(3..10));
my ($rndkey0,$rndkey1,$inout,$tmp)= map("v$_",(0..3));
my ($ivec,$inptail,$inpperm,$outhead,$outperm,$outmask,$keyperm,$one)=
map("v$_",(4..11));
my $dat=$tmp;
$code.=<<___;
.globl .${prefix}_ctr32_encrypt_blocks
.align 5
.${prefix}_ctr32_encrypt_blocks:
${UCMP}i $len,1
bltlr-
lis r0,0xfff0
mfspr $vrsave,256
mtspr 256,r0
li $idx,15
vxor $rndkey0,$rndkey0,$rndkey0
le?vspltisb $tmp,0x0f
lvx $ivec,0,$ivp # load [unaligned] iv
lvsl $inpperm,0,$ivp
lvx $inptail,$idx,$ivp
vspltisb $one,1
le?vxor $inpperm,$inpperm,$tmp
vperm $ivec,$ivec,$inptail,$inpperm
vsldoi $one,$rndkey0,$one,1
neg r11,$inp
?lvsl $keyperm,0,$key # prepare for unaligned key
lwz $rounds,240($key)
lvsr $inpperm,0,r11 # prepare for unaligned load
lvx $inptail,0,$inp
addi $inp,$inp,15 # 15 is not typo
le?vxor $inpperm,$inpperm,$tmp
srwi $rounds,$rounds,1
li $idx,16
subi $rounds,$rounds,1
${UCMP}i $len,8
bge _aesp8_ctr32_encrypt8x
?lvsr $outperm,0,$out # prepare for unaligned store
vspltisb $outmask,-1
lvx $outhead,0,$out
?vperm $outmask,$rndkey0,$outmask,$outperm
le?vxor $outperm,$outperm,$tmp
lvx $rndkey0,0,$key
mtctr $rounds
lvx $rndkey1,$idx,$key
addi $idx,$idx,16
?vperm $rndkey0,$rndkey0,$rndkey1,$keyperm
vxor $inout,$ivec,$rndkey0
lvx $rndkey0,$idx,$key
addi $idx,$idx,16
b Loop_ctr32_enc
.align 5
Loop_ctr32_enc:
?vperm $rndkey1,$rndkey1,$rndkey0,$keyperm
vcipher $inout,$inout,$rndkey1
lvx $rndkey1,$idx,$key
addi $idx,$idx,16
?vperm $rndkey0,$rndkey0,$rndkey1,$keyperm
vcipher $inout,$inout,$rndkey0
lvx $rndkey0,$idx,$key
addi $idx,$idx,16
bdnz Loop_ctr32_enc
vadduwm $ivec,$ivec,$one
vmr $dat,$inptail
lvx $inptail,0,$inp
addi $inp,$inp,16
subic. $len,$len,1 # blocks--
?vperm $rndkey1,$rndkey1,$rndkey0,$keyperm
vcipher $inout,$inout,$rndkey1
lvx $rndkey1,$idx,$key
vperm $dat,$dat,$inptail,$inpperm
li $idx,16
?vperm $rndkey1,$rndkey0,$rndkey1,$keyperm
lvx $rndkey0,0,$key
vxor $dat,$dat,$rndkey1 # last round key
vcipherlast $inout,$inout,$dat
lvx $rndkey1,$idx,$key
addi $idx,$idx,16
vperm $inout,$inout,$inout,$outperm
vsel $dat,$outhead,$inout,$outmask
mtctr $rounds
?vperm $rndkey0,$rndkey0,$rndkey1,$keyperm
vmr $outhead,$inout
vxor $inout,$ivec,$rndkey0
lvx $rndkey0,$idx,$key
addi $idx,$idx,16
stvx $dat,0,$out
addi $out,$out,16
bne Loop_ctr32_enc
addi $out,$out,-1
lvx $inout,0,$out # redundant in aligned case
vsel $inout,$outhead,$inout,$outmask
stvx $inout,0,$out
mtspr 256,$vrsave
blr
.long 0
.byte 0,12,0x14,0,0,0,6,0
.long 0
___
#########################################################################
{{ # Optimized CTR procedure #
my $key_="r11";
my ($x00,$x10,$x20,$x30,$x40,$x50,$x60,$x70)=map("r$_",(0,8,26..31));
$x00=0 if ($flavour =~ /osx/);
my ($in0, $in1, $in2, $in3, $in4, $in5, $in6, $in7 )=map("v$_",(0..3,10,12..14));
my ($out0,$out1,$out2,$out3,$out4,$out5,$out6,$out7)=map("v$_",(15..22));
my $rndkey0="v23"; # v24-v25 rotating buffer for first found keys
# v26-v31 last 6 round keys
my ($tmp,$keyperm)=($in3,$in4); # aliases with "caller", redundant assignment
my ($two,$three,$four)=($outhead,$outperm,$outmask);
$code.=<<___;
.align 5
_aesp8_ctr32_encrypt8x:
$STU $sp,-`($FRAME+21*16+6*$SIZE_T)`($sp)
li r10,`$FRAME+8*16+15`
li r11,`$FRAME+8*16+31`
stvx v20,r10,$sp # ABI says so
addi r10,r10,32
stvx v21,r11,$sp
addi r11,r11,32
stvx v22,r10,$sp
addi r10,r10,32
stvx v23,r11,$sp
addi r11,r11,32
stvx v24,r10,$sp
addi r10,r10,32
stvx v25,r11,$sp
addi r11,r11,32
stvx v26,r10,$sp
addi r10,r10,32
stvx v27,r11,$sp
addi r11,r11,32
stvx v28,r10,$sp
addi r10,r10,32
stvx v29,r11,$sp
addi r11,r11,32
stvx v30,r10,$sp
stvx v31,r11,$sp
li r0,-1
stw $vrsave,`$FRAME+21*16-4`($sp) # save vrsave
li $x10,0x10
$PUSH r26,`$FRAME+21*16+0*$SIZE_T`($sp)
li $x20,0x20
$PUSH r27,`$FRAME+21*16+1*$SIZE_T`($sp)
li $x30,0x30
$PUSH r28,`$FRAME+21*16+2*$SIZE_T`($sp)
li $x40,0x40
$PUSH r29,`$FRAME+21*16+3*$SIZE_T`($sp)
li $x50,0x50
$PUSH r30,`$FRAME+21*16+4*$SIZE_T`($sp)
li $x60,0x60
$PUSH r31,`$FRAME+21*16+5*$SIZE_T`($sp)
li $x70,0x70
mtspr 256,r0
subi $rounds,$rounds,3 # -4 in total
lvx $rndkey0,$x00,$key # load key schedule
lvx v30,$x10,$key
addi $key,$key,0x20
lvx v31,$x00,$key
?vperm $rndkey0,$rndkey0,v30,$keyperm
addi $key_,$sp,$FRAME+15
mtctr $rounds
Load_ctr32_enc_key:
?vperm v24,v30,v31,$keyperm
lvx v30,$x10,$key
addi $key,$key,0x20
stvx v24,$x00,$key_ # off-load round[1]
?vperm v25,v31,v30,$keyperm
lvx v31,$x00,$key
stvx v25,$x10,$key_ # off-load round[2]
addi $key_,$key_,0x20
bdnz Load_ctr32_enc_key
lvx v26,$x10,$key
?vperm v24,v30,v31,$keyperm
lvx v27,$x20,$key
stvx v24,$x00,$key_ # off-load round[3]
?vperm v25,v31,v26,$keyperm
lvx v28,$x30,$key
stvx v25,$x10,$key_ # off-load round[4]
addi $key_,$sp,$FRAME+15 # rewind $key_
?vperm v26,v26,v27,$keyperm
lvx v29,$x40,$key
?vperm v27,v27,v28,$keyperm
lvx v30,$x50,$key
?vperm v28,v28,v29,$keyperm
lvx v31,$x60,$key
?vperm v29,v29,v30,$keyperm
lvx $out0,$x70,$key # borrow $out0
?vperm v30,v30,v31,$keyperm
lvx v24,$x00,$key_ # pre-load round[1]
?vperm v31,v31,$out0,$keyperm
lvx v25,$x10,$key_ # pre-load round[2]
vadduwm $two,$one,$one
subi $inp,$inp,15 # undo "caller"
$SHL $len,$len,4
vadduwm $out1,$ivec,$one # counter values ...
vadduwm $out2,$ivec,$two
vxor $out0,$ivec,$rndkey0 # ... xored with rndkey[0]
le?li $idx,8
vadduwm $out3,$out1,$two
vxor $out1,$out1,$rndkey0
le?lvsl $inpperm,0,$idx
vadduwm $out4,$out2,$two
vxor $out2,$out2,$rndkey0
le?vspltisb $tmp,0x0f
vadduwm $out5,$out3,$two
vxor $out3,$out3,$rndkey0
le?vxor $inpperm,$inpperm,$tmp # transform for lvx_u/stvx_u
vadduwm $out6,$out4,$two
vxor $out4,$out4,$rndkey0
vadduwm $out7,$out5,$two
vxor $out5,$out5,$rndkey0
vadduwm $ivec,$out6,$two # next counter value
vxor $out6,$out6,$rndkey0
vxor $out7,$out7,$rndkey0
mtctr $rounds
b Loop_ctr32_enc8x
.align 5
Loop_ctr32_enc8x:
vcipher $out0,$out0,v24
vcipher $out1,$out1,v24
vcipher $out2,$out2,v24
vcipher $out3,$out3,v24
vcipher $out4,$out4,v24
vcipher $out5,$out5,v24
vcipher $out6,$out6,v24
vcipher $out7,$out7,v24
Loop_ctr32_enc8x_middle:
lvx v24,$x20,$key_ # round[3]
addi $key_,$key_,0x20
vcipher $out0,$out0,v25
vcipher $out1,$out1,v25
vcipher $out2,$out2,v25
vcipher $out3,$out3,v25
vcipher $out4,$out4,v25
vcipher $out5,$out5,v25
vcipher $out6,$out6,v25
vcipher $out7,$out7,v25
lvx v25,$x10,$key_ # round[4]
bdnz Loop_ctr32_enc8x
subic r11,$len,256 # $len-256, borrow $key_
vcipher $out0,$out0,v24
vcipher $out1,$out1,v24
vcipher $out2,$out2,v24
vcipher $out3,$out3,v24
vcipher $out4,$out4,v24
vcipher $out5,$out5,v24
vcipher $out6,$out6,v24
vcipher $out7,$out7,v24
subfe r0,r0,r0 # borrow?-1:0
vcipher $out0,$out0,v25
vcipher $out1,$out1,v25
vcipher $out2,$out2,v25
vcipher $out3,$out3,v25
vcipher $out4,$out4,v25
vcipher $out5,$out5,v25
vcipher $out6,$out6,v25
vcipher $out7,$out7,v25
and r0,r0,r11
addi $key_,$sp,$FRAME+15 # rewind $key_
vcipher $out0,$out0,v26
vcipher $out1,$out1,v26
vcipher $out2,$out2,v26
vcipher $out3,$out3,v26
vcipher $out4,$out4,v26
vcipher $out5,$out5,v26
vcipher $out6,$out6,v26
vcipher $out7,$out7,v26
lvx v24,$x00,$key_ # re-pre-load round[1]
subic $len,$len,129 # $len-=129
vcipher $out0,$out0,v27
addi $len,$len,1 # $len-=128 really
vcipher $out1,$out1,v27
vcipher $out2,$out2,v27
vcipher $out3,$out3,v27
vcipher $out4,$out4,v27
vcipher $out5,$out5,v27
vcipher $out6,$out6,v27
vcipher $out7,$out7,v27
lvx v25,$x10,$key_ # re-pre-load round[2]
vcipher $out0,$out0,v28
lvx_u $in0,$x00,$inp # load input
vcipher $out1,$out1,v28
lvx_u $in1,$x10,$inp
vcipher $out2,$out2,v28
lvx_u $in2,$x20,$inp
vcipher $out3,$out3,v28
lvx_u $in3,$x30,$inp
vcipher $out4,$out4,v28
lvx_u $in4,$x40,$inp
vcipher $out5,$out5,v28
lvx_u $in5,$x50,$inp
vcipher $out6,$out6,v28
lvx_u $in6,$x60,$inp
vcipher $out7,$out7,v28
lvx_u $in7,$x70,$inp
addi $inp,$inp,0x80
vcipher $out0,$out0,v29
le?vperm $in0,$in0,$in0,$inpperm
vcipher $out1,$out1,v29
le?vperm $in1,$in1,$in1,$inpperm
vcipher $out2,$out2,v29
le?vperm $in2,$in2,$in2,$inpperm
vcipher $out3,$out3,v29
le?vperm $in3,$in3,$in3,$inpperm
vcipher $out4,$out4,v29
le?vperm $in4,$in4,$in4,$inpperm
vcipher $out5,$out5,v29
le?vperm $in5,$in5,$in5,$inpperm
vcipher $out6,$out6,v29
le?vperm $in6,$in6,$in6,$inpperm
vcipher $out7,$out7,v29
le?vperm $in7,$in7,$in7,$inpperm
add $inp,$inp,r0 # $inp is adjusted in such
# way that at exit from the
# loop inX-in7 are loaded
# with last "words"
subfe. r0,r0,r0 # borrow?-1:0
vcipher $out0,$out0,v30
vxor $in0,$in0,v31 # xor with last round key
vcipher $out1,$out1,v30
vxor $in1,$in1,v31
vcipher $out2,$out2,v30
vxor $in2,$in2,v31
vcipher $out3,$out3,v30
vxor $in3,$in3,v31
vcipher $out4,$out4,v30
vxor $in4,$in4,v31
vcipher $out5,$out5,v30
vxor $in5,$in5,v31
vcipher $out6,$out6,v30
vxor $in6,$in6,v31
vcipher $out7,$out7,v30
vxor $in7,$in7,v31
bne Lctr32_enc8x_break # did $len-129 borrow?
vcipherlast $in0,$out0,$in0
vcipherlast $in1,$out1,$in1
vadduwm $out1,$ivec,$one # counter values ...
vcipherlast $in2,$out2,$in2
vadduwm $out2,$ivec,$two
vxor $out0,$ivec,$rndkey0 # ... xored with rndkey[0]
vcipherlast $in3,$out3,$in3
vadduwm $out3,$out1,$two
vxor $out1,$out1,$rndkey0
vcipherlast $in4,$out4,$in4
vadduwm $out4,$out2,$two
vxor $out2,$out2,$rndkey0
vcipherlast $in5,$out5,$in5
vadduwm $out5,$out3,$two
vxor $out3,$out3,$rndkey0
vcipherlast $in6,$out6,$in6
vadduwm $out6,$out4,$two
vxor $out4,$out4,$rndkey0
vcipherlast $in7,$out7,$in7
vadduwm $out7,$out5,$two
vxor $out5,$out5,$rndkey0
le?vperm $in0,$in0,$in0,$inpperm
vadduwm $ivec,$out6,$two # next counter value
vxor $out6,$out6,$rndkey0
le?vperm $in1,$in1,$in1,$inpperm
vxor $out7,$out7,$rndkey0
mtctr $rounds
vcipher $out0,$out0,v24
stvx_u $in0,$x00,$out
le?vperm $in2,$in2,$in2,$inpperm
vcipher $out1,$out1,v24
stvx_u $in1,$x10,$out
le?vperm $in3,$in3,$in3,$inpperm
vcipher $out2,$out2,v24
stvx_u $in2,$x20,$out
le?vperm $in4,$in4,$in4,$inpperm
vcipher $out3,$out3,v24
stvx_u $in3,$x30,$out
le?vperm $in5,$in5,$in5,$inpperm
vcipher $out4,$out4,v24
stvx_u $in4,$x40,$out
le?vperm $in6,$in6,$in6,$inpperm
vcipher $out5,$out5,v24
stvx_u $in5,$x50,$out
le?vperm $in7,$in7,$in7,$inpperm
vcipher $out6,$out6,v24
stvx_u $in6,$x60,$out
vcipher $out7,$out7,v24
stvx_u $in7,$x70,$out
addi $out,$out,0x80
b Loop_ctr32_enc8x_middle
.align 5
Lctr32_enc8x_break:
cmpwi $len,-0x60
blt Lctr32_enc8x_one
nop
beq Lctr32_enc8x_two
cmpwi $len,-0x40
blt Lctr32_enc8x_three
nop
beq Lctr32_enc8x_four
cmpwi $len,-0x20
blt Lctr32_enc8x_five
nop
beq Lctr32_enc8x_six
cmpwi $len,0x00
blt Lctr32_enc8x_seven
Lctr32_enc8x_eight:
vcipherlast $out0,$out0,$in0
vcipherlast $out1,$out1,$in1
vcipherlast $out2,$out2,$in2
vcipherlast $out3,$out3,$in3
vcipherlast $out4,$out4,$in4
vcipherlast $out5,$out5,$in5
vcipherlast $out6,$out6,$in6
vcipherlast $out7,$out7,$in7
le?vperm $out0,$out0,$out0,$inpperm
le?vperm $out1,$out1,$out1,$inpperm
stvx_u $out0,$x00,$out
le?vperm $out2,$out2,$out2,$inpperm
stvx_u $out1,$x10,$out
le?vperm $out3,$out3,$out3,$inpperm
stvx_u $out2,$x20,$out
le?vperm $out4,$out4,$out4,$inpperm
stvx_u $out3,$x30,$out
le?vperm $out5,$out5,$out5,$inpperm
stvx_u $out4,$x40,$out
le?vperm $out6,$out6,$out6,$inpperm
stvx_u $out5,$x50,$out
le?vperm $out7,$out7,$out7,$inpperm
stvx_u $out6,$x60,$out
stvx_u $out7,$x70,$out
addi $out,$out,0x80
b Lctr32_enc8x_done
.align 5
Lctr32_enc8x_seven:
vcipherlast $out0,$out0,$in1
vcipherlast $out1,$out1,$in2
vcipherlast $out2,$out2,$in3
vcipherlast $out3,$out3,$in4
vcipherlast $out4,$out4,$in5
vcipherlast $out5,$out5,$in6
vcipherlast $out6,$out6,$in7
le?vperm $out0,$out0,$out0,$inpperm
le?vperm $out1,$out1,$out1,$inpperm
stvx_u $out0,$x00,$out
le?vperm $out2,$out2,$out2,$inpperm
stvx_u $out1,$x10,$out
le?vperm $out3,$out3,$out3,$inpperm
stvx_u $out2,$x20,$out
le?vperm $out4,$out4,$out4,$inpperm
stvx_u $out3,$x30,$out
le?vperm $out5,$out5,$out5,$inpperm
stvx_u $out4,$x40,$out
le?vperm $out6,$out6,$out6,$inpperm
stvx_u $out5,$x50,$out
stvx_u $out6,$x60,$out
addi $out,$out,0x70
b Lctr32_enc8x_done
.align 5
Lctr32_enc8x_six:
vcipherlast $out0,$out0,$in2
vcipherlast $out1,$out1,$in3
vcipherlast $out2,$out2,$in4
vcipherlast $out3,$out3,$in5
vcipherlast $out4,$out4,$in6
vcipherlast $out5,$out5,$in7
le?vperm $out0,$out0,$out0,$inpperm
le?vperm $out1,$out1,$out1,$inpperm
stvx_u $out0,$x00,$out
le?vperm $out2,$out2,$out2,$inpperm
stvx_u $out1,$x10,$out
le?vperm $out3,$out3,$out3,$inpperm
stvx_u $out2,$x20,$out
le?vperm $out4,$out4,$out4,$inpperm
stvx_u $out3,$x30,$out
le?vperm $out5,$out5,$out5,$inpperm
stvx_u $out4,$x40,$out
stvx_u $out5,$x50,$out
addi $out,$out,0x60
b Lctr32_enc8x_done
.align 5
Lctr32_enc8x_five:
vcipherlast $out0,$out0,$in3
vcipherlast $out1,$out1,$in4
vcipherlast $out2,$out2,$in5
vcipherlast $out3,$out3,$in6
vcipherlast $out4,$out4,$in7
le?vperm $out0,$out0,$out0,$inpperm
le?vperm $out1,$out1,$out1,$inpperm
stvx_u $out0,$x00,$out
le?vperm $out2,$out2,$out2,$inpperm
stvx_u $out1,$x10,$out
le?vperm $out3,$out3,$out3,$inpperm
stvx_u $out2,$x20,$out
le?vperm $out4,$out4,$out4,$inpperm
stvx_u $out3,$x30,$out
stvx_u $out4,$x40,$out
addi $out,$out,0x50
b Lctr32_enc8x_done
.align 5
Lctr32_enc8x_four:
vcipherlast $out0,$out0,$in4
vcipherlast $out1,$out1,$in5
vcipherlast $out2,$out2,$in6
vcipherlast $out3,$out3,$in7
le?vperm $out0,$out0,$out0,$inpperm
le?vperm $out1,$out1,$out1,$inpperm
stvx_u $out0,$x00,$out
le?vperm $out2,$out2,$out2,$inpperm
stvx_u $out1,$x10,$out
le?vperm $out3,$out3,$out3,$inpperm
stvx_u $out2,$x20,$out
stvx_u $out3,$x30,$out
addi $out,$out,0x40
b Lctr32_enc8x_done
.align 5
Lctr32_enc8x_three:
vcipherlast $out0,$out0,$in5
vcipherlast $out1,$out1,$in6
vcipherlast $out2,$out2,$in7
le?vperm $out0,$out0,$out0,$inpperm
le?vperm $out1,$out1,$out1,$inpperm
stvx_u $out0,$x00,$out
le?vperm $out2,$out2,$out2,$inpperm
stvx_u $out1,$x10,$out
stvx_u $out2,$x20,$out
addi $out,$out,0x30
b Lctr32_enc8x_done
.align 5
Lctr32_enc8x_two:
vcipherlast $out0,$out0,$in6
vcipherlast $out1,$out1,$in7
le?vperm $out0,$out0,$out0,$inpperm
le?vperm $out1,$out1,$out1,$inpperm
stvx_u $out0,$x00,$out
stvx_u $out1,$x10,$out
addi $out,$out,0x20
b Lctr32_enc8x_done
.align 5
Lctr32_enc8x_one:
vcipherlast $out0,$out0,$in7
le?vperm $out0,$out0,$out0,$inpperm
stvx_u $out0,0,$out
addi $out,$out,0x10
Lctr32_enc8x_done:
li r10,`$FRAME+15`
li r11,`$FRAME+31`
stvx $inpperm,r10,$sp # wipe copies of round keys
addi r10,r10,32
stvx $inpperm,r11,$sp
addi r11,r11,32
stvx $inpperm,r10,$sp
addi r10,r10,32
stvx $inpperm,r11,$sp
addi r11,r11,32
stvx $inpperm,r10,$sp
addi r10,r10,32
stvx $inpperm,r11,$sp
addi r11,r11,32
stvx $inpperm,r10,$sp
addi r10,r10,32
stvx $inpperm,r11,$sp
addi r11,r11,32
mtspr 256,$vrsave
lvx v20,r10,$sp # ABI says so
addi r10,r10,32
lvx v21,r11,$sp
addi r11,r11,32
lvx v22,r10,$sp
addi r10,r10,32
lvx v23,r11,$sp
addi r11,r11,32
lvx v24,r10,$sp
addi r10,r10,32
lvx v25,r11,$sp
addi r11,r11,32
lvx v26,r10,$sp
addi r10,r10,32
lvx v27,r11,$sp
addi r11,r11,32
lvx v28,r10,$sp
addi r10,r10,32
lvx v29,r11,$sp
addi r11,r11,32
lvx v30,r10,$sp
lvx v31,r11,$sp
$POP r26,`$FRAME+21*16+0*$SIZE_T`($sp)
$POP r27,`$FRAME+21*16+1*$SIZE_T`($sp)
$POP r28,`$FRAME+21*16+2*$SIZE_T`($sp)
$POP r29,`$FRAME+21*16+3*$SIZE_T`($sp)
$POP r30,`$FRAME+21*16+4*$SIZE_T`($sp)
$POP r31,`$FRAME+21*16+5*$SIZE_T`($sp)
addi $sp,$sp,`$FRAME+21*16+6*$SIZE_T`
blr
.long 0
.byte 0,12,0x04,0,0x80,6,6,0
.long 0
.size .${prefix}_ctr32_encrypt_blocks,.-.${prefix}_ctr32_encrypt_blocks
___
}} }}}
#########################################################################
{{{ # XTS procedures #
# int aes_p8_xts_[en|de]crypt(const char *inp, char *out, size_t len, #
# const AES_KEY *key1, const AES_KEY *key2, #
# [const] unsigned char iv[16]); #
# If $key2 is NULL, then a "tweak chaining" mode is engaged, in which #
# input tweak value is assumed to be encrypted already, and last tweak #
# value, one suitable for consecutive call on same chunk of data, is #
# written back to original buffer. In addition, in "tweak chaining" #
# mode only complete input blocks are processed. #
my ($inp,$out,$len,$key1,$key2,$ivp,$rounds,$idx) = map("r$_",(3..10));
my ($rndkey0,$rndkey1,$inout) = map("v$_",(0..2));
my ($output,$inptail,$inpperm,$leperm,$keyperm) = map("v$_",(3..7));
my ($tweak,$seven,$eighty7,$tmp,$tweak1) = map("v$_",(8..12));
my $taillen = $key2;
($inp,$idx) = ($idx,$inp); # reassign
$code.=<<___;
.globl .${prefix}_xts_encrypt
.align 5
.${prefix}_xts_encrypt:
mr $inp,r3 # reassign
li r3,-1
${UCMP}i $len,16
bltlr-
lis r0,0xfff0
mfspr r12,256 # save vrsave
li r11,0
mtspr 256,r0
vspltisb $seven,0x07 # 0x070707..07
le?lvsl $leperm,r11,r11
le?vspltisb $tmp,0x0f
le?vxor $leperm,$leperm,$seven
li $idx,15
lvx $tweak,0,$ivp # load [unaligned] iv
lvsl $inpperm,0,$ivp
lvx $inptail,$idx,$ivp
le?vxor $inpperm,$inpperm,$tmp
vperm $tweak,$tweak,$inptail,$inpperm
neg r11,$inp
lvsr $inpperm,0,r11 # prepare for unaligned load
lvx $inout,0,$inp
addi $inp,$inp,15 # 15 is not typo
le?vxor $inpperm,$inpperm,$tmp
${UCMP}i $key2,0 # key2==NULL?
beq Lxts_enc_no_key2
?lvsl $keyperm,0,$key2 # prepare for unaligned key
lwz $rounds,240($key2)
srwi $rounds,$rounds,1
subi $rounds,$rounds,1
li $idx,16
lvx $rndkey0,0,$key2
lvx $rndkey1,$idx,$key2
addi $idx,$idx,16
?vperm $rndkey0,$rndkey0,$rndkey1,$keyperm
vxor $tweak,$tweak,$rndkey0
lvx $rndkey0,$idx,$key2
addi $idx,$idx,16
mtctr $rounds
Ltweak_xts_enc:
?vperm $rndkey1,$rndkey1,$rndkey0,$keyperm
vcipher $tweak,$tweak,$rndkey1
lvx $rndkey1,$idx,$key2
addi $idx,$idx,16
?vperm $rndkey0,$rndkey0,$rndkey1,$keyperm
vcipher $tweak,$tweak,$rndkey0
lvx $rndkey0,$idx,$key2
addi $idx,$idx,16
bdnz Ltweak_xts_enc
?vperm $rndkey1,$rndkey1,$rndkey0,$keyperm
vcipher $tweak,$tweak,$rndkey1
lvx $rndkey1,$idx,$key2
?vperm $rndkey0,$rndkey0,$rndkey1,$keyperm
vcipherlast $tweak,$tweak,$rndkey0
li $ivp,0 # don't chain the tweak
b Lxts_enc
Lxts_enc_no_key2:
li $idx,-16
and $len,$len,$idx # in "tweak chaining"
# mode only complete
# blocks are processed
Lxts_enc:
lvx $inptail,0,$inp
addi $inp,$inp,16
?lvsl $keyperm,0,$key1 # prepare for unaligned key
lwz $rounds,240($key1)
srwi $rounds,$rounds,1
subi $rounds,$rounds,1
li $idx,16
vslb $eighty7,$seven,$seven # 0x808080..80
vor $eighty7,$eighty7,$seven # 0x878787..87
vspltisb $tmp,1 # 0x010101..01
vsldoi $eighty7,$eighty7,$tmp,15 # 0x870101..01
${UCMP}i $len,96
bge _aesp8_xts_encrypt6x
andi. $taillen,$len,15
subic r0,$len,32
subi $taillen,$taillen,16
subfe r0,r0,r0
and r0,r0,$taillen
add $inp,$inp,r0
lvx $rndkey0,0,$key1
lvx $rndkey1,$idx,$key1
addi $idx,$idx,16
vperm $inout,$inout,$inptail,$inpperm
?vperm $rndkey0,$rndkey0,$rndkey1,$keyperm
vxor $inout,$inout,$tweak
vxor $inout,$inout,$rndkey0
lvx $rndkey0,$idx,$key1
addi $idx,$idx,16
mtctr $rounds
b Loop_xts_enc
.align 5
Loop_xts_enc:
?vperm $rndkey1,$rndkey1,$rndkey0,$keyperm
vcipher $inout,$inout,$rndkey1
lvx $rndkey1,$idx,$key1
addi $idx,$idx,16
?vperm $rndkey0,$rndkey0,$rndkey1,$keyperm
vcipher $inout,$inout,$rndkey0
lvx $rndkey0,$idx,$key1
addi $idx,$idx,16
bdnz Loop_xts_enc
?vperm $rndkey1,$rndkey1,$rndkey0,$keyperm
vcipher $inout,$inout,$rndkey1
lvx $rndkey1,$idx,$key1
li $idx,16
?vperm $rndkey0,$rndkey0,$rndkey1,$keyperm
vxor $rndkey0,$rndkey0,$tweak
vcipherlast $output,$inout,$rndkey0
le?vperm $tmp,$output,$output,$leperm
be?nop
le?stvx_u $tmp,0,$out
be?stvx_u $output,0,$out
addi $out,$out,16
subic. $len,$len,16
beq Lxts_enc_done
vmr $inout,$inptail
lvx $inptail,0,$inp
addi $inp,$inp,16
lvx $rndkey0,0,$key1
lvx $rndkey1,$idx,$key1
addi $idx,$idx,16
subic r0,$len,32
subfe r0,r0,r0
and r0,r0,$taillen
add $inp,$inp,r0
vsrab $tmp,$tweak,$seven # next tweak value
vaddubm $tweak,$tweak,$tweak
vsldoi $tmp,$tmp,$tmp,15
vand $tmp,$tmp,$eighty7
vxor $tweak,$tweak,$tmp
vperm $inout,$inout,$inptail,$inpperm
?vperm $rndkey0,$rndkey0,$rndkey1,$keyperm
vxor $inout,$inout,$tweak
vxor $output,$output,$rndkey0 # just in case $len<16
vxor $inout,$inout,$rndkey0
lvx $rndkey0,$idx,$key1
addi $idx,$idx,16
mtctr $rounds
${UCMP}i $len,16
bge Loop_xts_enc
vxor $output,$output,$tweak
lvsr $inpperm,0,$len # $inpperm is no longer needed
vxor $inptail,$inptail,$inptail # $inptail is no longer needed
vspltisb $tmp,-1
vperm $inptail,$inptail,$tmp,$inpperm
vsel $inout,$inout,$output,$inptail
subi r11,$out,17
subi $out,$out,16
mtctr $len
li $len,16
Loop_xts_enc_steal:
lbzu r0,1(r11)
stb r0,16(r11)
bdnz Loop_xts_enc_steal
mtctr $rounds
b Loop_xts_enc # one more time...
Lxts_enc_done:
${UCMP}i $ivp,0
beq Lxts_enc_ret
vsrab $tmp,$tweak,$seven # next tweak value
vaddubm $tweak,$tweak,$tweak
vsldoi $tmp,$tmp,$tmp,15
vand $tmp,$tmp,$eighty7
vxor $tweak,$tweak,$tmp
le?vperm $tweak,$tweak,$tweak,$leperm
stvx_u $tweak,0,$ivp
Lxts_enc_ret:
mtspr 256,r12 # restore vrsave
li r3,0
blr
.long 0
.byte 0,12,0x04,0,0x80,6,6,0
.long 0
.size .${prefix}_xts_encrypt,.-.${prefix}_xts_encrypt
.globl .${prefix}_xts_decrypt
.align 5
.${prefix}_xts_decrypt:
mr $inp,r3 # reassign
li r3,-1
${UCMP}i $len,16
bltlr-
lis r0,0xfff8
mfspr r12,256 # save vrsave
li r11,0
mtspr 256,r0
andi. r0,$len,15
neg r0,r0
andi. r0,r0,16
sub $len,$len,r0
vspltisb $seven,0x07 # 0x070707..07
le?lvsl $leperm,r11,r11
le?vspltisb $tmp,0x0f
le?vxor $leperm,$leperm,$seven
li $idx,15
lvx $tweak,0,$ivp # load [unaligned] iv
lvsl $inpperm,0,$ivp
lvx $inptail,$idx,$ivp
le?vxor $inpperm,$inpperm,$tmp
vperm $tweak,$tweak,$inptail,$inpperm
neg r11,$inp
lvsr $inpperm,0,r11 # prepare for unaligned load
lvx $inout,0,$inp
addi $inp,$inp,15 # 15 is not typo
le?vxor $inpperm,$inpperm,$tmp
${UCMP}i $key2,0 # key2==NULL?
beq Lxts_dec_no_key2
?lvsl $keyperm,0,$key2 # prepare for unaligned key
lwz $rounds,240($key2)
srwi $rounds,$rounds,1
subi $rounds,$rounds,1
li $idx,16
lvx $rndkey0,0,$key2
lvx $rndkey1,$idx,$key2
addi $idx,$idx,16
?vperm $rndkey0,$rndkey0,$rndkey1,$keyperm
vxor $tweak,$tweak,$rndkey0
lvx $rndkey0,$idx,$key2
addi $idx,$idx,16
mtctr $rounds
Ltweak_xts_dec:
?vperm $rndkey1,$rndkey1,$rndkey0,$keyperm
vcipher $tweak,$tweak,$rndkey1
lvx $rndkey1,$idx,$key2
addi $idx,$idx,16
?vperm $rndkey0,$rndkey0,$rndkey1,$keyperm
vcipher $tweak,$tweak,$rndkey0
lvx $rndkey0,$idx,$key2
addi $idx,$idx,16
bdnz Ltweak_xts_dec
?vperm $rndkey1,$rndkey1,$rndkey0,$keyperm
vcipher $tweak,$tweak,$rndkey1
lvx $rndkey1,$idx,$key2
?vperm $rndkey0,$rndkey0,$rndkey1,$keyperm
vcipherlast $tweak,$tweak,$rndkey0
li $ivp,0 # don't chain the tweak
b Lxts_dec
Lxts_dec_no_key2:
neg $idx,$len
andi. $idx,$idx,15
add $len,$len,$idx # in "tweak chaining"
# mode only complete
# blocks are processed
Lxts_dec:
lvx $inptail,0,$inp
addi $inp,$inp,16
?lvsl $keyperm,0,$key1 # prepare for unaligned key
lwz $rounds,240($key1)
srwi $rounds,$rounds,1
subi $rounds,$rounds,1
li $idx,16
vslb $eighty7,$seven,$seven # 0x808080..80
vor $eighty7,$eighty7,$seven # 0x878787..87
vspltisb $tmp,1 # 0x010101..01
vsldoi $eighty7,$eighty7,$tmp,15 # 0x870101..01
${UCMP}i $len,96
bge _aesp8_xts_decrypt6x
lvx $rndkey0,0,$key1
lvx $rndkey1,$idx,$key1
addi $idx,$idx,16
vperm $inout,$inout,$inptail,$inpperm
?vperm $rndkey0,$rndkey0,$rndkey1,$keyperm
vxor $inout,$inout,$tweak
vxor $inout,$inout,$rndkey0
lvx $rndkey0,$idx,$key1
addi $idx,$idx,16
mtctr $rounds
${UCMP}i $len,16
blt Ltail_xts_dec
be?b Loop_xts_dec
.align 5
Loop_xts_dec:
?vperm $rndkey1,$rndkey1,$rndkey0,$keyperm
vncipher $inout,$inout,$rndkey1
lvx $rndkey1,$idx,$key1
addi $idx,$idx,16
?vperm $rndkey0,$rndkey0,$rndkey1,$keyperm
vncipher $inout,$inout,$rndkey0
lvx $rndkey0,$idx,$key1
addi $idx,$idx,16
bdnz Loop_xts_dec
?vperm $rndkey1,$rndkey1,$rndkey0,$keyperm
vncipher $inout,$inout,$rndkey1
lvx $rndkey1,$idx,$key1
li $idx,16
?vperm $rndkey0,$rndkey0,$rndkey1,$keyperm
vxor $rndkey0,$rndkey0,$tweak
vncipherlast $output,$inout,$rndkey0
le?vperm $tmp,$output,$output,$leperm
be?nop
le?stvx_u $tmp,0,$out
be?stvx_u $output,0,$out
addi $out,$out,16
subic. $len,$len,16
beq Lxts_dec_done
vmr $inout,$inptail
lvx $inptail,0,$inp
addi $inp,$inp,16
lvx $rndkey0,0,$key1
lvx $rndkey1,$idx,$key1
addi $idx,$idx,16
vsrab $tmp,$tweak,$seven # next tweak value
vaddubm $tweak,$tweak,$tweak
vsldoi $tmp,$tmp,$tmp,15
vand $tmp,$tmp,$eighty7
vxor $tweak,$tweak,$tmp
vperm $inout,$inout,$inptail,$inpperm
?vperm $rndkey0,$rndkey0,$rndkey1,$keyperm
vxor $inout,$inout,$tweak
vxor $inout,$inout,$rndkey0
lvx $rndkey0,$idx,$key1
addi $idx,$idx,16
mtctr $rounds
${UCMP}i $len,16
bge Loop_xts_dec
Ltail_xts_dec:
vsrab $tmp,$tweak,$seven # next tweak value
vaddubm $tweak1,$tweak,$tweak
vsldoi $tmp,$tmp,$tmp,15
vand $tmp,$tmp,$eighty7
vxor $tweak1,$tweak1,$tmp
subi $inp,$inp,16
add $inp,$inp,$len
vxor $inout,$inout,$tweak # :-(
vxor $inout,$inout,$tweak1 # :-)
Loop_xts_dec_short:
?vperm $rndkey1,$rndkey1,$rndkey0,$keyperm
vncipher $inout,$inout,$rndkey1
lvx $rndkey1,$idx,$key1
addi $idx,$idx,16
?vperm $rndkey0,$rndkey0,$rndkey1,$keyperm
vncipher $inout,$inout,$rndkey0
lvx $rndkey0,$idx,$key1
addi $idx,$idx,16
bdnz Loop_xts_dec_short
?vperm $rndkey1,$rndkey1,$rndkey0,$keyperm
vncipher $inout,$inout,$rndkey1
lvx $rndkey1,$idx,$key1
li $idx,16
?vperm $rndkey0,$rndkey0,$rndkey1,$keyperm
vxor $rndkey0,$rndkey0,$tweak1
vncipherlast $output,$inout,$rndkey0
le?vperm $tmp,$output,$output,$leperm
be?nop
le?stvx_u $tmp,0,$out
be?stvx_u $output,0,$out
vmr $inout,$inptail
lvx $inptail,0,$inp
#addi $inp,$inp,16
lvx $rndkey0,0,$key1
lvx $rndkey1,$idx,$key1
addi $idx,$idx,16
vperm $inout,$inout,$inptail,$inpperm
?vperm $rndkey0,$rndkey0,$rndkey1,$keyperm
lvsr $inpperm,0,$len # $inpperm is no longer needed
vxor $inptail,$inptail,$inptail # $inptail is no longer needed
vspltisb $tmp,-1
vperm $inptail,$inptail,$tmp,$inpperm
vsel $inout,$inout,$output,$inptail
vxor $rndkey0,$rndkey0,$tweak
vxor $inout,$inout,$rndkey0
lvx $rndkey0,$idx,$key1
addi $idx,$idx,16
subi r11,$out,1
mtctr $len
li $len,16
Loop_xts_dec_steal:
lbzu r0,1(r11)
stb r0,16(r11)
bdnz Loop_xts_dec_steal
mtctr $rounds
b Loop_xts_dec # one more time...
Lxts_dec_done:
${UCMP}i $ivp,0
beq Lxts_dec_ret
vsrab $tmp,$tweak,$seven # next tweak value
vaddubm $tweak,$tweak,$tweak
vsldoi $tmp,$tmp,$tmp,15
vand $tmp,$tmp,$eighty7
vxor $tweak,$tweak,$tmp
le?vperm $tweak,$tweak,$tweak,$leperm
stvx_u $tweak,0,$ivp
Lxts_dec_ret:
mtspr 256,r12 # restore vrsave
li r3,0
blr
.long 0
.byte 0,12,0x04,0,0x80,6,6,0
.long 0
.size .${prefix}_xts_decrypt,.-.${prefix}_xts_decrypt
___
#########################################################################
{{ # Optimized XTS procedures #
my $key_=$key2;
my ($x00,$x10,$x20,$x30,$x40,$x50,$x60,$x70)=map("r$_",(0,3,26..31));
$x00=0 if ($flavour =~ /osx/);
-my ($in0, $in1, $in2, $in3, $in4, $in5 )=map("v$_",(0..5));
+my ($in0, $in1, $in2, $in3, $in4, $in5)=map("v$_",(0..5));
my ($out0, $out1, $out2, $out3, $out4, $out5)=map("v$_",(7,12..16));
my ($twk0, $twk1, $twk2, $twk3, $twk4, $twk5)=map("v$_",(17..22));
my $rndkey0="v23"; # v24-v25 rotating buffer for first found keys
# v26-v31 last 6 round keys
my ($keyperm)=($out0); # aliases with "caller", redundant assignment
my $taillen=$x70;
$code.=<<___;
.align 5
_aesp8_xts_encrypt6x:
$STU $sp,-`($FRAME+21*16+6*$SIZE_T)`($sp)
mflr r11
li r7,`$FRAME+8*16+15`
li r3,`$FRAME+8*16+31`
$PUSH r11,`$FRAME+21*16+6*$SIZE_T+$LRSAVE`($sp)
stvx v20,r7,$sp # ABI says so
addi r7,r7,32
stvx v21,r3,$sp
addi r3,r3,32
stvx v22,r7,$sp
addi r7,r7,32
stvx v23,r3,$sp
addi r3,r3,32
stvx v24,r7,$sp
addi r7,r7,32
stvx v25,r3,$sp
addi r3,r3,32
stvx v26,r7,$sp
addi r7,r7,32
stvx v27,r3,$sp
addi r3,r3,32
stvx v28,r7,$sp
addi r7,r7,32
stvx v29,r3,$sp
addi r3,r3,32
stvx v30,r7,$sp
stvx v31,r3,$sp
li r0,-1
stw $vrsave,`$FRAME+21*16-4`($sp) # save vrsave
li $x10,0x10
$PUSH r26,`$FRAME+21*16+0*$SIZE_T`($sp)
li $x20,0x20
$PUSH r27,`$FRAME+21*16+1*$SIZE_T`($sp)
li $x30,0x30
$PUSH r28,`$FRAME+21*16+2*$SIZE_T`($sp)
li $x40,0x40
$PUSH r29,`$FRAME+21*16+3*$SIZE_T`($sp)
li $x50,0x50
$PUSH r30,`$FRAME+21*16+4*$SIZE_T`($sp)
li $x60,0x60
$PUSH r31,`$FRAME+21*16+5*$SIZE_T`($sp)
li $x70,0x70
mtspr 256,r0
+ # Reverse eighty7 to 0x010101..87
+ xxlor 2, 32+$eighty7, 32+$eighty7
+ vsldoi $eighty7,$tmp,$eighty7,1 # 0x010101..87
+ xxlor 1, 32+$eighty7, 32+$eighty7
+
+ # Load XOR contents. 0xf102132435465768798a9bacbdcedfe
+ mr $x70, r6
+ bl Lconsts
+ lxvw4x 0, $x40, r6 # load XOR contents
+ mr r6, $x70
+ li $x70,0x70
+
subi $rounds,$rounds,3 # -4 in total
lvx $rndkey0,$x00,$key1 # load key schedule
lvx v30,$x10,$key1
addi $key1,$key1,0x20
lvx v31,$x00,$key1
?vperm $rndkey0,$rndkey0,v30,$keyperm
addi $key_,$sp,$FRAME+15
mtctr $rounds
Load_xts_enc_key:
?vperm v24,v30,v31,$keyperm
lvx v30,$x10,$key1
addi $key1,$key1,0x20
stvx v24,$x00,$key_ # off-load round[1]
?vperm v25,v31,v30,$keyperm
lvx v31,$x00,$key1
stvx v25,$x10,$key_ # off-load round[2]
addi $key_,$key_,0x20
bdnz Load_xts_enc_key
lvx v26,$x10,$key1
?vperm v24,v30,v31,$keyperm
lvx v27,$x20,$key1
stvx v24,$x00,$key_ # off-load round[3]
?vperm v25,v31,v26,$keyperm
lvx v28,$x30,$key1
stvx v25,$x10,$key_ # off-load round[4]
addi $key_,$sp,$FRAME+15 # rewind $key_
?vperm v26,v26,v27,$keyperm
lvx v29,$x40,$key1
?vperm v27,v27,v28,$keyperm
lvx v30,$x50,$key1
?vperm v28,v28,v29,$keyperm
lvx v31,$x60,$key1
?vperm v29,v29,v30,$keyperm
lvx $twk5,$x70,$key1 # borrow $twk5
?vperm v30,v30,v31,$keyperm
lvx v24,$x00,$key_ # pre-load round[1]
?vperm v31,v31,$twk5,$keyperm
lvx v25,$x10,$key_ # pre-load round[2]
+ # Switch to use the following codes with 0x010101..87 to generate tweak.
+ # eighty7 = 0x010101..87
+ # vsrab tmp, tweak, seven # next tweak value, right shift 7 bits
+ # vand tmp, tmp, eighty7 # last byte with carry
+ # vaddubm tweak, tweak, tweak # left shift 1 bit (x2)
+ # xxlor vsx, 0, 0
+ # vpermxor tweak, tweak, tmp, vsx
+
vperm $in0,$inout,$inptail,$inpperm
subi $inp,$inp,31 # undo "caller"
vxor $twk0,$tweak,$rndkey0
vsrab $tmp,$tweak,$seven # next tweak value
vaddubm $tweak,$tweak,$tweak
- vsldoi $tmp,$tmp,$tmp,15
vand $tmp,$tmp,$eighty7
vxor $out0,$in0,$twk0
- vxor $tweak,$tweak,$tmp
+ xxlor 32+$in1, 0, 0
+ vpermxor $tweak, $tweak, $tmp, $in1
lvx_u $in1,$x10,$inp
vxor $twk1,$tweak,$rndkey0
vsrab $tmp,$tweak,$seven # next tweak value
vaddubm $tweak,$tweak,$tweak
- vsldoi $tmp,$tmp,$tmp,15
le?vperm $in1,$in1,$in1,$leperm
vand $tmp,$tmp,$eighty7
vxor $out1,$in1,$twk1
- vxor $tweak,$tweak,$tmp
+ xxlor 32+$in2, 0, 0
+ vpermxor $tweak, $tweak, $tmp, $in2
lvx_u $in2,$x20,$inp
andi. $taillen,$len,15
vxor $twk2,$tweak,$rndkey0
vsrab $tmp,$tweak,$seven # next tweak value
vaddubm $tweak,$tweak,$tweak
- vsldoi $tmp,$tmp,$tmp,15
le?vperm $in2,$in2,$in2,$leperm
vand $tmp,$tmp,$eighty7
vxor $out2,$in2,$twk2
- vxor $tweak,$tweak,$tmp
+ xxlor 32+$in3, 0, 0
+ vpermxor $tweak, $tweak, $tmp, $in3
lvx_u $in3,$x30,$inp
sub $len,$len,$taillen
vxor $twk3,$tweak,$rndkey0
vsrab $tmp,$tweak,$seven # next tweak value
vaddubm $tweak,$tweak,$tweak
- vsldoi $tmp,$tmp,$tmp,15
le?vperm $in3,$in3,$in3,$leperm
vand $tmp,$tmp,$eighty7
vxor $out3,$in3,$twk3
- vxor $tweak,$tweak,$tmp
+ xxlor 32+$in4, 0, 0
+ vpermxor $tweak, $tweak, $tmp, $in4
lvx_u $in4,$x40,$inp
subi $len,$len,0x60
vxor $twk4,$tweak,$rndkey0
vsrab $tmp,$tweak,$seven # next tweak value
vaddubm $tweak,$tweak,$tweak
- vsldoi $tmp,$tmp,$tmp,15
le?vperm $in4,$in4,$in4,$leperm
vand $tmp,$tmp,$eighty7
vxor $out4,$in4,$twk4
- vxor $tweak,$tweak,$tmp
+ xxlor 32+$in5, 0, 0
+ vpermxor $tweak, $tweak, $tmp, $in5
lvx_u $in5,$x50,$inp
addi $inp,$inp,0x60
vxor $twk5,$tweak,$rndkey0
vsrab $tmp,$tweak,$seven # next tweak value
vaddubm $tweak,$tweak,$tweak
- vsldoi $tmp,$tmp,$tmp,15
le?vperm $in5,$in5,$in5,$leperm
vand $tmp,$tmp,$eighty7
vxor $out5,$in5,$twk5
- vxor $tweak,$tweak,$tmp
+ xxlor 32+$in0, 0, 0
+ vpermxor $tweak, $tweak, $tmp, $in0
vxor v31,v31,$rndkey0
mtctr $rounds
b Loop_xts_enc6x
.align 5
Loop_xts_enc6x:
vcipher $out0,$out0,v24
vcipher $out1,$out1,v24
vcipher $out2,$out2,v24
vcipher $out3,$out3,v24
vcipher $out4,$out4,v24
vcipher $out5,$out5,v24
lvx v24,$x20,$key_ # round[3]
addi $key_,$key_,0x20
vcipher $out0,$out0,v25
vcipher $out1,$out1,v25
vcipher $out2,$out2,v25
vcipher $out3,$out3,v25
vcipher $out4,$out4,v25
vcipher $out5,$out5,v25
lvx v25,$x10,$key_ # round[4]
bdnz Loop_xts_enc6x
+ xxlor 32+$eighty7, 1, 1 # 0x010101..87
+
subic $len,$len,96 # $len-=96
vxor $in0,$twk0,v31 # xor with last round key
vcipher $out0,$out0,v24
vcipher $out1,$out1,v24
vsrab $tmp,$tweak,$seven # next tweak value
vxor $twk0,$tweak,$rndkey0
vaddubm $tweak,$tweak,$tweak
vcipher $out2,$out2,v24
vcipher $out3,$out3,v24
- vsldoi $tmp,$tmp,$tmp,15
vcipher $out4,$out4,v24
vcipher $out5,$out5,v24
subfe. r0,r0,r0 # borrow?-1:0
vand $tmp,$tmp,$eighty7
vcipher $out0,$out0,v25
vcipher $out1,$out1,v25
- vxor $tweak,$tweak,$tmp
+ xxlor 32+$in1, 0, 0
+ vpermxor $tweak, $tweak, $tmp, $in1
vcipher $out2,$out2,v25
vcipher $out3,$out3,v25
vxor $in1,$twk1,v31
vsrab $tmp,$tweak,$seven # next tweak value
vxor $twk1,$tweak,$rndkey0
vcipher $out4,$out4,v25
vcipher $out5,$out5,v25
and r0,r0,$len
vaddubm $tweak,$tweak,$tweak
- vsldoi $tmp,$tmp,$tmp,15
vcipher $out0,$out0,v26
vcipher $out1,$out1,v26
vand $tmp,$tmp,$eighty7
vcipher $out2,$out2,v26
vcipher $out3,$out3,v26
- vxor $tweak,$tweak,$tmp
+ xxlor 32+$in2, 0, 0
+ vpermxor $tweak, $tweak, $tmp, $in2
vcipher $out4,$out4,v26
vcipher $out5,$out5,v26
add $inp,$inp,r0 # $inp is adjusted in such
# way that at exit from the
# loop inX-in5 are loaded
# with last "words"
vxor $in2,$twk2,v31
vsrab $tmp,$tweak,$seven # next tweak value
vxor $twk2,$tweak,$rndkey0
vaddubm $tweak,$tweak,$tweak
vcipher $out0,$out0,v27
vcipher $out1,$out1,v27
- vsldoi $tmp,$tmp,$tmp,15
vcipher $out2,$out2,v27
vcipher $out3,$out3,v27
vand $tmp,$tmp,$eighty7
vcipher $out4,$out4,v27
vcipher $out5,$out5,v27
addi $key_,$sp,$FRAME+15 # rewind $key_
- vxor $tweak,$tweak,$tmp
+ xxlor 32+$in3, 0, 0
+ vpermxor $tweak, $tweak, $tmp, $in3
vcipher $out0,$out0,v28
vcipher $out1,$out1,v28
vxor $in3,$twk3,v31
vsrab $tmp,$tweak,$seven # next tweak value
vxor $twk3,$tweak,$rndkey0
vcipher $out2,$out2,v28
vcipher $out3,$out3,v28
vaddubm $tweak,$tweak,$tweak
- vsldoi $tmp,$tmp,$tmp,15
vcipher $out4,$out4,v28
vcipher $out5,$out5,v28
lvx v24,$x00,$key_ # re-pre-load round[1]
vand $tmp,$tmp,$eighty7
vcipher $out0,$out0,v29
vcipher $out1,$out1,v29
- vxor $tweak,$tweak,$tmp
+ xxlor 32+$in4, 0, 0
+ vpermxor $tweak, $tweak, $tmp, $in4
vcipher $out2,$out2,v29
vcipher $out3,$out3,v29
vxor $in4,$twk4,v31
vsrab $tmp,$tweak,$seven # next tweak value
vxor $twk4,$tweak,$rndkey0
vcipher $out4,$out4,v29
vcipher $out5,$out5,v29
lvx v25,$x10,$key_ # re-pre-load round[2]
vaddubm $tweak,$tweak,$tweak
- vsldoi $tmp,$tmp,$tmp,15
vcipher $out0,$out0,v30
vcipher $out1,$out1,v30
vand $tmp,$tmp,$eighty7
vcipher $out2,$out2,v30
vcipher $out3,$out3,v30
- vxor $tweak,$tweak,$tmp
+ xxlor 32+$in5, 0, 0
+ vpermxor $tweak, $tweak, $tmp, $in5
vcipher $out4,$out4,v30
vcipher $out5,$out5,v30
vxor $in5,$twk5,v31
vsrab $tmp,$tweak,$seven # next tweak value
vxor $twk5,$tweak,$rndkey0
vcipherlast $out0,$out0,$in0
lvx_u $in0,$x00,$inp # load next input block
vaddubm $tweak,$tweak,$tweak
- vsldoi $tmp,$tmp,$tmp,15
vcipherlast $out1,$out1,$in1
lvx_u $in1,$x10,$inp
vcipherlast $out2,$out2,$in2
le?vperm $in0,$in0,$in0,$leperm
lvx_u $in2,$x20,$inp
vand $tmp,$tmp,$eighty7
vcipherlast $out3,$out3,$in3
le?vperm $in1,$in1,$in1,$leperm
lvx_u $in3,$x30,$inp
vcipherlast $out4,$out4,$in4
le?vperm $in2,$in2,$in2,$leperm
lvx_u $in4,$x40,$inp
- vxor $tweak,$tweak,$tmp
+ xxlor 10, 32+$in0, 32+$in0
+ xxlor 32+$in0, 0, 0
+ vpermxor $tweak, $tweak, $tmp, $in0
+ xxlor 32+$in0, 10, 10
vcipherlast $tmp,$out5,$in5 # last block might be needed
# in stealing mode
le?vperm $in3,$in3,$in3,$leperm
lvx_u $in5,$x50,$inp
addi $inp,$inp,0x60
le?vperm $in4,$in4,$in4,$leperm
le?vperm $in5,$in5,$in5,$leperm
le?vperm $out0,$out0,$out0,$leperm
le?vperm $out1,$out1,$out1,$leperm
stvx_u $out0,$x00,$out # store output
vxor $out0,$in0,$twk0
le?vperm $out2,$out2,$out2,$leperm
stvx_u $out1,$x10,$out
vxor $out1,$in1,$twk1
le?vperm $out3,$out3,$out3,$leperm
stvx_u $out2,$x20,$out
vxor $out2,$in2,$twk2
le?vperm $out4,$out4,$out4,$leperm
stvx_u $out3,$x30,$out
vxor $out3,$in3,$twk3
le?vperm $out5,$tmp,$tmp,$leperm
stvx_u $out4,$x40,$out
vxor $out4,$in4,$twk4
le?stvx_u $out5,$x50,$out
be?stvx_u $tmp, $x50,$out
vxor $out5,$in5,$twk5
addi $out,$out,0x60
mtctr $rounds
beq Loop_xts_enc6x # did $len-=96 borrow?
+ xxlor 32+$eighty7, 2, 2 # 0x870101..01
+
addic. $len,$len,0x60
beq Lxts_enc6x_zero
cmpwi $len,0x20
blt Lxts_enc6x_one
nop
beq Lxts_enc6x_two
cmpwi $len,0x40
blt Lxts_enc6x_three
nop
beq Lxts_enc6x_four
Lxts_enc6x_five:
vxor $out0,$in1,$twk0
vxor $out1,$in2,$twk1
vxor $out2,$in3,$twk2
vxor $out3,$in4,$twk3
vxor $out4,$in5,$twk4
bl _aesp8_xts_enc5x
le?vperm $out0,$out0,$out0,$leperm
vmr $twk0,$twk5 # unused tweak
le?vperm $out1,$out1,$out1,$leperm
stvx_u $out0,$x00,$out # store output
le?vperm $out2,$out2,$out2,$leperm
stvx_u $out1,$x10,$out
le?vperm $out3,$out3,$out3,$leperm
stvx_u $out2,$x20,$out
vxor $tmp,$out4,$twk5 # last block prep for stealing
le?vperm $out4,$out4,$out4,$leperm
stvx_u $out3,$x30,$out
stvx_u $out4,$x40,$out
addi $out,$out,0x50
bne Lxts_enc6x_steal
b Lxts_enc6x_done
.align 4
Lxts_enc6x_four:
vxor $out0,$in2,$twk0
vxor $out1,$in3,$twk1
vxor $out2,$in4,$twk2
vxor $out3,$in5,$twk3
vxor $out4,$out4,$out4
bl _aesp8_xts_enc5x
le?vperm $out0,$out0,$out0,$leperm
vmr $twk0,$twk4 # unused tweak
le?vperm $out1,$out1,$out1,$leperm
stvx_u $out0,$x00,$out # store output
le?vperm $out2,$out2,$out2,$leperm
stvx_u $out1,$x10,$out
vxor $tmp,$out3,$twk4 # last block prep for stealing
le?vperm $out3,$out3,$out3,$leperm
stvx_u $out2,$x20,$out
stvx_u $out3,$x30,$out
addi $out,$out,0x40
bne Lxts_enc6x_steal
b Lxts_enc6x_done
.align 4
Lxts_enc6x_three:
vxor $out0,$in3,$twk0
vxor $out1,$in4,$twk1
vxor $out2,$in5,$twk2
vxor $out3,$out3,$out3
vxor $out4,$out4,$out4
bl _aesp8_xts_enc5x
le?vperm $out0,$out0,$out0,$leperm
vmr $twk0,$twk3 # unused tweak
le?vperm $out1,$out1,$out1,$leperm
stvx_u $out0,$x00,$out # store output
vxor $tmp,$out2,$twk3 # last block prep for stealing
le?vperm $out2,$out2,$out2,$leperm
stvx_u $out1,$x10,$out
stvx_u $out2,$x20,$out
addi $out,$out,0x30
bne Lxts_enc6x_steal
b Lxts_enc6x_done
.align 4
Lxts_enc6x_two:
vxor $out0,$in4,$twk0
vxor $out1,$in5,$twk1
vxor $out2,$out2,$out2
vxor $out3,$out3,$out3
vxor $out4,$out4,$out4
bl _aesp8_xts_enc5x
le?vperm $out0,$out0,$out0,$leperm
vmr $twk0,$twk2 # unused tweak
vxor $tmp,$out1,$twk2 # last block prep for stealing
le?vperm $out1,$out1,$out1,$leperm
stvx_u $out0,$x00,$out # store output
stvx_u $out1,$x10,$out
addi $out,$out,0x20
bne Lxts_enc6x_steal
b Lxts_enc6x_done
.align 4
Lxts_enc6x_one:
vxor $out0,$in5,$twk0
nop
Loop_xts_enc1x:
vcipher $out0,$out0,v24
lvx v24,$x20,$key_ # round[3]
addi $key_,$key_,0x20
vcipher $out0,$out0,v25
lvx v25,$x10,$key_ # round[4]
bdnz Loop_xts_enc1x
add $inp,$inp,$taillen
cmpwi $taillen,0
vcipher $out0,$out0,v24
subi $inp,$inp,16
vcipher $out0,$out0,v25
lvsr $inpperm,0,$taillen
vcipher $out0,$out0,v26
lvx_u $in0,0,$inp
vcipher $out0,$out0,v27
addi $key_,$sp,$FRAME+15 # rewind $key_
vcipher $out0,$out0,v28
lvx v24,$x00,$key_ # re-pre-load round[1]
vcipher $out0,$out0,v29
lvx v25,$x10,$key_ # re-pre-load round[2]
vxor $twk0,$twk0,v31
le?vperm $in0,$in0,$in0,$leperm
vcipher $out0,$out0,v30
vperm $in0,$in0,$in0,$inpperm
vcipherlast $out0,$out0,$twk0
vmr $twk0,$twk1 # unused tweak
vxor $tmp,$out0,$twk1 # last block prep for stealing
le?vperm $out0,$out0,$out0,$leperm
stvx_u $out0,$x00,$out # store output
addi $out,$out,0x10
bne Lxts_enc6x_steal
b Lxts_enc6x_done
.align 4
Lxts_enc6x_zero:
cmpwi $taillen,0
beq Lxts_enc6x_done
add $inp,$inp,$taillen
subi $inp,$inp,16
lvx_u $in0,0,$inp
lvsr $inpperm,0,$taillen # $in5 is no more
le?vperm $in0,$in0,$in0,$leperm
vperm $in0,$in0,$in0,$inpperm
vxor $tmp,$tmp,$twk0
Lxts_enc6x_steal:
vxor $in0,$in0,$twk0
vxor $out0,$out0,$out0
vspltisb $out1,-1
vperm $out0,$out0,$out1,$inpperm
vsel $out0,$in0,$tmp,$out0 # $tmp is last block, remember?
subi r30,$out,17
subi $out,$out,16
mtctr $taillen
Loop_xts_enc6x_steal:
lbzu r0,1(r30)
stb r0,16(r30)
bdnz Loop_xts_enc6x_steal
li $taillen,0
mtctr $rounds
b Loop_xts_enc1x # one more time...
.align 4
Lxts_enc6x_done:
${UCMP}i $ivp,0
beq Lxts_enc6x_ret
vxor $tweak,$twk0,$rndkey0
le?vperm $tweak,$tweak,$tweak,$leperm
stvx_u $tweak,0,$ivp
Lxts_enc6x_ret:
mtlr r11
li r10,`$FRAME+15`
li r11,`$FRAME+31`
stvx $seven,r10,$sp # wipe copies of round keys
addi r10,r10,32
stvx $seven,r11,$sp
addi r11,r11,32
stvx $seven,r10,$sp
addi r10,r10,32
stvx $seven,r11,$sp
addi r11,r11,32
stvx $seven,r10,$sp
addi r10,r10,32
stvx $seven,r11,$sp
addi r11,r11,32
stvx $seven,r10,$sp
addi r10,r10,32
stvx $seven,r11,$sp
addi r11,r11,32
mtspr 256,$vrsave
lvx v20,r10,$sp # ABI says so
addi r10,r10,32
lvx v21,r11,$sp
addi r11,r11,32
lvx v22,r10,$sp
addi r10,r10,32
lvx v23,r11,$sp
addi r11,r11,32
lvx v24,r10,$sp
addi r10,r10,32
lvx v25,r11,$sp
addi r11,r11,32
lvx v26,r10,$sp
addi r10,r10,32
lvx v27,r11,$sp
addi r11,r11,32
lvx v28,r10,$sp
addi r10,r10,32
lvx v29,r11,$sp
addi r11,r11,32
lvx v30,r10,$sp
lvx v31,r11,$sp
$POP r26,`$FRAME+21*16+0*$SIZE_T`($sp)
$POP r27,`$FRAME+21*16+1*$SIZE_T`($sp)
$POP r28,`$FRAME+21*16+2*$SIZE_T`($sp)
$POP r29,`$FRAME+21*16+3*$SIZE_T`($sp)
$POP r30,`$FRAME+21*16+4*$SIZE_T`($sp)
$POP r31,`$FRAME+21*16+5*$SIZE_T`($sp)
addi $sp,$sp,`$FRAME+21*16+6*$SIZE_T`
blr
.long 0
.byte 0,12,0x04,1,0x80,6,6,0
.long 0
.align 5
_aesp8_xts_enc5x:
vcipher $out0,$out0,v24
vcipher $out1,$out1,v24
vcipher $out2,$out2,v24
vcipher $out3,$out3,v24
vcipher $out4,$out4,v24
lvx v24,$x20,$key_ # round[3]
addi $key_,$key_,0x20
vcipher $out0,$out0,v25
vcipher $out1,$out1,v25
vcipher $out2,$out2,v25
vcipher $out3,$out3,v25
vcipher $out4,$out4,v25
lvx v25,$x10,$key_ # round[4]
bdnz _aesp8_xts_enc5x
add $inp,$inp,$taillen
cmpwi $taillen,0
vcipher $out0,$out0,v24
vcipher $out1,$out1,v24
vcipher $out2,$out2,v24
vcipher $out3,$out3,v24
vcipher $out4,$out4,v24
subi $inp,$inp,16
vcipher $out0,$out0,v25
vcipher $out1,$out1,v25
vcipher $out2,$out2,v25
vcipher $out3,$out3,v25
vcipher $out4,$out4,v25
vxor $twk0,$twk0,v31
vcipher $out0,$out0,v26
lvsr $inpperm,0,$taillen # $in5 is no more
vcipher $out1,$out1,v26
vcipher $out2,$out2,v26
vcipher $out3,$out3,v26
vcipher $out4,$out4,v26
vxor $in1,$twk1,v31
vcipher $out0,$out0,v27
lvx_u $in0,0,$inp
vcipher $out1,$out1,v27
vcipher $out2,$out2,v27
vcipher $out3,$out3,v27
vcipher $out4,$out4,v27
vxor $in2,$twk2,v31
addi $key_,$sp,$FRAME+15 # rewind $key_
vcipher $out0,$out0,v28
vcipher $out1,$out1,v28
vcipher $out2,$out2,v28
vcipher $out3,$out3,v28
vcipher $out4,$out4,v28
lvx v24,$x00,$key_ # re-pre-load round[1]
vxor $in3,$twk3,v31
vcipher $out0,$out0,v29
le?vperm $in0,$in0,$in0,$leperm
vcipher $out1,$out1,v29
vcipher $out2,$out2,v29
vcipher $out3,$out3,v29
vcipher $out4,$out4,v29
lvx v25,$x10,$key_ # re-pre-load round[2]
vxor $in4,$twk4,v31
vcipher $out0,$out0,v30
vperm $in0,$in0,$in0,$inpperm
vcipher $out1,$out1,v30
vcipher $out2,$out2,v30
vcipher $out3,$out3,v30
vcipher $out4,$out4,v30
vcipherlast $out0,$out0,$twk0
vcipherlast $out1,$out1,$in1
vcipherlast $out2,$out2,$in2
vcipherlast $out3,$out3,$in3
vcipherlast $out4,$out4,$in4
blr
.long 0
.byte 0,12,0x14,0,0,0,0,0
.align 5
_aesp8_xts_decrypt6x:
$STU $sp,-`($FRAME+21*16+6*$SIZE_T)`($sp)
mflr r11
li r7,`$FRAME+8*16+15`
li r3,`$FRAME+8*16+31`
$PUSH r11,`$FRAME+21*16+6*$SIZE_T+$LRSAVE`($sp)
stvx v20,r7,$sp # ABI says so
addi r7,r7,32
stvx v21,r3,$sp
addi r3,r3,32
stvx v22,r7,$sp
addi r7,r7,32
stvx v23,r3,$sp
addi r3,r3,32
stvx v24,r7,$sp
addi r7,r7,32
stvx v25,r3,$sp
addi r3,r3,32
stvx v26,r7,$sp
addi r7,r7,32
stvx v27,r3,$sp
addi r3,r3,32
stvx v28,r7,$sp
addi r7,r7,32
stvx v29,r3,$sp
addi r3,r3,32
stvx v30,r7,$sp
stvx v31,r3,$sp
li r0,-1
stw $vrsave,`$FRAME+21*16-4`($sp) # save vrsave
li $x10,0x10
$PUSH r26,`$FRAME+21*16+0*$SIZE_T`($sp)
li $x20,0x20
$PUSH r27,`$FRAME+21*16+1*$SIZE_T`($sp)
li $x30,0x30
$PUSH r28,`$FRAME+21*16+2*$SIZE_T`($sp)
li $x40,0x40
$PUSH r29,`$FRAME+21*16+3*$SIZE_T`($sp)
li $x50,0x50
$PUSH r30,`$FRAME+21*16+4*$SIZE_T`($sp)
li $x60,0x60
$PUSH r31,`$FRAME+21*16+5*$SIZE_T`($sp)
li $x70,0x70
mtspr 256,r0
+ # Reverse eighty7 to 0x010101..87
+ xxlor 2, 32+$eighty7, 32+$eighty7
+ vsldoi $eighty7,$tmp,$eighty7,1 # 0x010101..87
+ xxlor 1, 32+$eighty7, 32+$eighty7
+
+ # Load XOR contents. 0xf102132435465768798a9bacbdcedfe
+ mr $x70, r6
+ bl Lconsts
+ lxvw4x 0, $x40, r6 # load XOR contents
+ mr r6, $x70
+ li $x70,0x70
+
subi $rounds,$rounds,3 # -4 in total
lvx $rndkey0,$x00,$key1 # load key schedule
lvx v30,$x10,$key1
addi $key1,$key1,0x20
lvx v31,$x00,$key1
?vperm $rndkey0,$rndkey0,v30,$keyperm
addi $key_,$sp,$FRAME+15
mtctr $rounds
Load_xts_dec_key:
?vperm v24,v30,v31,$keyperm
lvx v30,$x10,$key1
addi $key1,$key1,0x20
stvx v24,$x00,$key_ # off-load round[1]
?vperm v25,v31,v30,$keyperm
lvx v31,$x00,$key1
stvx v25,$x10,$key_ # off-load round[2]
addi $key_,$key_,0x20
bdnz Load_xts_dec_key
lvx v26,$x10,$key1
?vperm v24,v30,v31,$keyperm
lvx v27,$x20,$key1
stvx v24,$x00,$key_ # off-load round[3]
?vperm v25,v31,v26,$keyperm
lvx v28,$x30,$key1
stvx v25,$x10,$key_ # off-load round[4]
addi $key_,$sp,$FRAME+15 # rewind $key_
?vperm v26,v26,v27,$keyperm
lvx v29,$x40,$key1
?vperm v27,v27,v28,$keyperm
lvx v30,$x50,$key1
?vperm v28,v28,v29,$keyperm
lvx v31,$x60,$key1
?vperm v29,v29,v30,$keyperm
lvx $twk5,$x70,$key1 # borrow $twk5
?vperm v30,v30,v31,$keyperm
lvx v24,$x00,$key_ # pre-load round[1]
?vperm v31,v31,$twk5,$keyperm
lvx v25,$x10,$key_ # pre-load round[2]
vperm $in0,$inout,$inptail,$inpperm
subi $inp,$inp,31 # undo "caller"
vxor $twk0,$tweak,$rndkey0
vsrab $tmp,$tweak,$seven # next tweak value
vaddubm $tweak,$tweak,$tweak
- vsldoi $tmp,$tmp,$tmp,15
vand $tmp,$tmp,$eighty7
vxor $out0,$in0,$twk0
- vxor $tweak,$tweak,$tmp
+ xxlor 32+$in1, 0, 0
+ vpermxor $tweak, $tweak, $tmp, $in1
lvx_u $in1,$x10,$inp
vxor $twk1,$tweak,$rndkey0
vsrab $tmp,$tweak,$seven # next tweak value
vaddubm $tweak,$tweak,$tweak
- vsldoi $tmp,$tmp,$tmp,15
le?vperm $in1,$in1,$in1,$leperm
vand $tmp,$tmp,$eighty7
vxor $out1,$in1,$twk1
- vxor $tweak,$tweak,$tmp
+ xxlor 32+$in2, 0, 0
+ vpermxor $tweak, $tweak, $tmp, $in2
lvx_u $in2,$x20,$inp
andi. $taillen,$len,15
vxor $twk2,$tweak,$rndkey0
vsrab $tmp,$tweak,$seven # next tweak value
vaddubm $tweak,$tweak,$tweak
- vsldoi $tmp,$tmp,$tmp,15
le?vperm $in2,$in2,$in2,$leperm
vand $tmp,$tmp,$eighty7
vxor $out2,$in2,$twk2
- vxor $tweak,$tweak,$tmp
+ xxlor 32+$in3, 0, 0
+ vpermxor $tweak, $tweak, $tmp, $in3
lvx_u $in3,$x30,$inp
sub $len,$len,$taillen
vxor $twk3,$tweak,$rndkey0
vsrab $tmp,$tweak,$seven # next tweak value
vaddubm $tweak,$tweak,$tweak
- vsldoi $tmp,$tmp,$tmp,15
le?vperm $in3,$in3,$in3,$leperm
vand $tmp,$tmp,$eighty7
vxor $out3,$in3,$twk3
- vxor $tweak,$tweak,$tmp
+ xxlor 32+$in4, 0, 0
+ vpermxor $tweak, $tweak, $tmp, $in4
lvx_u $in4,$x40,$inp
subi $len,$len,0x60
vxor $twk4,$tweak,$rndkey0
vsrab $tmp,$tweak,$seven # next tweak value
vaddubm $tweak,$tweak,$tweak
- vsldoi $tmp,$tmp,$tmp,15
le?vperm $in4,$in4,$in4,$leperm
vand $tmp,$tmp,$eighty7
vxor $out4,$in4,$twk4
- vxor $tweak,$tweak,$tmp
+ xxlor 32+$in5, 0, 0
+ vpermxor $tweak, $tweak, $tmp, $in5
lvx_u $in5,$x50,$inp
addi $inp,$inp,0x60
vxor $twk5,$tweak,$rndkey0
vsrab $tmp,$tweak,$seven # next tweak value
vaddubm $tweak,$tweak,$tweak
- vsldoi $tmp,$tmp,$tmp,15
le?vperm $in5,$in5,$in5,$leperm
vand $tmp,$tmp,$eighty7
vxor $out5,$in5,$twk5
- vxor $tweak,$tweak,$tmp
+ xxlor 32+$in0, 0, 0
+ vpermxor $tweak, $tweak, $tmp, $in0
vxor v31,v31,$rndkey0
mtctr $rounds
b Loop_xts_dec6x
.align 5
Loop_xts_dec6x:
vncipher $out0,$out0,v24
vncipher $out1,$out1,v24
vncipher $out2,$out2,v24
vncipher $out3,$out3,v24
vncipher $out4,$out4,v24
vncipher $out5,$out5,v24
lvx v24,$x20,$key_ # round[3]
addi $key_,$key_,0x20
vncipher $out0,$out0,v25
vncipher $out1,$out1,v25
vncipher $out2,$out2,v25
vncipher $out3,$out3,v25
vncipher $out4,$out4,v25
vncipher $out5,$out5,v25
lvx v25,$x10,$key_ # round[4]
bdnz Loop_xts_dec6x
+ xxlor 32+$eighty7, 1, 1
+
subic $len,$len,96 # $len-=96
vxor $in0,$twk0,v31 # xor with last round key
vncipher $out0,$out0,v24
vncipher $out1,$out1,v24
vsrab $tmp,$tweak,$seven # next tweak value
vxor $twk0,$tweak,$rndkey0
vaddubm $tweak,$tweak,$tweak
vncipher $out2,$out2,v24
vncipher $out3,$out3,v24
- vsldoi $tmp,$tmp,$tmp,15
vncipher $out4,$out4,v24
vncipher $out5,$out5,v24
subfe. r0,r0,r0 # borrow?-1:0
vand $tmp,$tmp,$eighty7
vncipher $out0,$out0,v25
vncipher $out1,$out1,v25
- vxor $tweak,$tweak,$tmp
+ xxlor 32+$in1, 0, 0
+ vpermxor $tweak, $tweak, $tmp, $in1
vncipher $out2,$out2,v25
vncipher $out3,$out3,v25
vxor $in1,$twk1,v31
vsrab $tmp,$tweak,$seven # next tweak value
vxor $twk1,$tweak,$rndkey0
vncipher $out4,$out4,v25
vncipher $out5,$out5,v25
and r0,r0,$len
vaddubm $tweak,$tweak,$tweak
- vsldoi $tmp,$tmp,$tmp,15
vncipher $out0,$out0,v26
vncipher $out1,$out1,v26
vand $tmp,$tmp,$eighty7
vncipher $out2,$out2,v26
vncipher $out3,$out3,v26
- vxor $tweak,$tweak,$tmp
+ xxlor 32+$in2, 0, 0
+ vpermxor $tweak, $tweak, $tmp, $in2
vncipher $out4,$out4,v26
vncipher $out5,$out5,v26
add $inp,$inp,r0 # $inp is adjusted in such
# way that at exit from the
# loop inX-in5 are loaded
# with last "words"
vxor $in2,$twk2,v31
vsrab $tmp,$tweak,$seven # next tweak value
vxor $twk2,$tweak,$rndkey0
vaddubm $tweak,$tweak,$tweak
vncipher $out0,$out0,v27
vncipher $out1,$out1,v27
- vsldoi $tmp,$tmp,$tmp,15
vncipher $out2,$out2,v27
vncipher $out3,$out3,v27
vand $tmp,$tmp,$eighty7
vncipher $out4,$out4,v27
vncipher $out5,$out5,v27
addi $key_,$sp,$FRAME+15 # rewind $key_
- vxor $tweak,$tweak,$tmp
+ xxlor 32+$in3, 0, 0
+ vpermxor $tweak, $tweak, $tmp, $in3
vncipher $out0,$out0,v28
vncipher $out1,$out1,v28
vxor $in3,$twk3,v31
vsrab $tmp,$tweak,$seven # next tweak value
vxor $twk3,$tweak,$rndkey0
vncipher $out2,$out2,v28
vncipher $out3,$out3,v28
vaddubm $tweak,$tweak,$tweak
- vsldoi $tmp,$tmp,$tmp,15
vncipher $out4,$out4,v28
vncipher $out5,$out5,v28
lvx v24,$x00,$key_ # re-pre-load round[1]
vand $tmp,$tmp,$eighty7
vncipher $out0,$out0,v29
vncipher $out1,$out1,v29
- vxor $tweak,$tweak,$tmp
+ xxlor 32+$in4, 0, 0
+ vpermxor $tweak, $tweak, $tmp, $in4
vncipher $out2,$out2,v29
vncipher $out3,$out3,v29
vxor $in4,$twk4,v31
vsrab $tmp,$tweak,$seven # next tweak value
vxor $twk4,$tweak,$rndkey0
vncipher $out4,$out4,v29
vncipher $out5,$out5,v29
lvx v25,$x10,$key_ # re-pre-load round[2]
vaddubm $tweak,$tweak,$tweak
- vsldoi $tmp,$tmp,$tmp,15
vncipher $out0,$out0,v30
vncipher $out1,$out1,v30
vand $tmp,$tmp,$eighty7
vncipher $out2,$out2,v30
vncipher $out3,$out3,v30
- vxor $tweak,$tweak,$tmp
+ xxlor 32+$in5, 0, 0
+ vpermxor $tweak, $tweak, $tmp, $in5
vncipher $out4,$out4,v30
vncipher $out5,$out5,v30
vxor $in5,$twk5,v31
vsrab $tmp,$tweak,$seven # next tweak value
vxor $twk5,$tweak,$rndkey0
vncipherlast $out0,$out0,$in0
lvx_u $in0,$x00,$inp # load next input block
vaddubm $tweak,$tweak,$tweak
- vsldoi $tmp,$tmp,$tmp,15
vncipherlast $out1,$out1,$in1
lvx_u $in1,$x10,$inp
vncipherlast $out2,$out2,$in2
le?vperm $in0,$in0,$in0,$leperm
lvx_u $in2,$x20,$inp
vand $tmp,$tmp,$eighty7
vncipherlast $out3,$out3,$in3
le?vperm $in1,$in1,$in1,$leperm
lvx_u $in3,$x30,$inp
vncipherlast $out4,$out4,$in4
le?vperm $in2,$in2,$in2,$leperm
lvx_u $in4,$x40,$inp
- vxor $tweak,$tweak,$tmp
+ xxlor 10, 32+$in0, 32+$in0
+ xxlor 32+$in0, 0, 0
+ vpermxor $tweak, $tweak, $tmp, $in0
+ xxlor 32+$in0, 10, 10
vncipherlast $out5,$out5,$in5
le?vperm $in3,$in3,$in3,$leperm
lvx_u $in5,$x50,$inp
addi $inp,$inp,0x60
le?vperm $in4,$in4,$in4,$leperm
le?vperm $in5,$in5,$in5,$leperm
le?vperm $out0,$out0,$out0,$leperm
le?vperm $out1,$out1,$out1,$leperm
stvx_u $out0,$x00,$out # store output
vxor $out0,$in0,$twk0
le?vperm $out2,$out2,$out2,$leperm
stvx_u $out1,$x10,$out
vxor $out1,$in1,$twk1
le?vperm $out3,$out3,$out3,$leperm
stvx_u $out2,$x20,$out
vxor $out2,$in2,$twk2
le?vperm $out4,$out4,$out4,$leperm
stvx_u $out3,$x30,$out
vxor $out3,$in3,$twk3
le?vperm $out5,$out5,$out5,$leperm
stvx_u $out4,$x40,$out
vxor $out4,$in4,$twk4
stvx_u $out5,$x50,$out
vxor $out5,$in5,$twk5
addi $out,$out,0x60
mtctr $rounds
beq Loop_xts_dec6x # did $len-=96 borrow?
+ xxlor 32+$eighty7, 2, 2
+
addic. $len,$len,0x60
beq Lxts_dec6x_zero
cmpwi $len,0x20
blt Lxts_dec6x_one
nop
beq Lxts_dec6x_two
cmpwi $len,0x40
blt Lxts_dec6x_three
nop
beq Lxts_dec6x_four
Lxts_dec6x_five:
vxor $out0,$in1,$twk0
vxor $out1,$in2,$twk1
vxor $out2,$in3,$twk2
vxor $out3,$in4,$twk3
vxor $out4,$in5,$twk4
bl _aesp8_xts_dec5x
le?vperm $out0,$out0,$out0,$leperm
vmr $twk0,$twk5 # unused tweak
vxor $twk1,$tweak,$rndkey0
le?vperm $out1,$out1,$out1,$leperm
stvx_u $out0,$x00,$out # store output
vxor $out0,$in0,$twk1
le?vperm $out2,$out2,$out2,$leperm
stvx_u $out1,$x10,$out
le?vperm $out3,$out3,$out3,$leperm
stvx_u $out2,$x20,$out
le?vperm $out4,$out4,$out4,$leperm
stvx_u $out3,$x30,$out
stvx_u $out4,$x40,$out
addi $out,$out,0x50
bne Lxts_dec6x_steal
b Lxts_dec6x_done
.align 4
Lxts_dec6x_four:
vxor $out0,$in2,$twk0
vxor $out1,$in3,$twk1
vxor $out2,$in4,$twk2
vxor $out3,$in5,$twk3
vxor $out4,$out4,$out4
bl _aesp8_xts_dec5x
le?vperm $out0,$out0,$out0,$leperm
vmr $twk0,$twk4 # unused tweak
vmr $twk1,$twk5
le?vperm $out1,$out1,$out1,$leperm
stvx_u $out0,$x00,$out # store output
vxor $out0,$in0,$twk5
le?vperm $out2,$out2,$out2,$leperm
stvx_u $out1,$x10,$out
le?vperm $out3,$out3,$out3,$leperm
stvx_u $out2,$x20,$out
stvx_u $out3,$x30,$out
addi $out,$out,0x40
bne Lxts_dec6x_steal
b Lxts_dec6x_done
.align 4
Lxts_dec6x_three:
vxor $out0,$in3,$twk0
vxor $out1,$in4,$twk1
vxor $out2,$in5,$twk2
vxor $out3,$out3,$out3
vxor $out4,$out4,$out4
bl _aesp8_xts_dec5x
le?vperm $out0,$out0,$out0,$leperm
vmr $twk0,$twk3 # unused tweak
vmr $twk1,$twk4
le?vperm $out1,$out1,$out1,$leperm
stvx_u $out0,$x00,$out # store output
vxor $out0,$in0,$twk4
le?vperm $out2,$out2,$out2,$leperm
stvx_u $out1,$x10,$out
stvx_u $out2,$x20,$out
addi $out,$out,0x30
bne Lxts_dec6x_steal
b Lxts_dec6x_done
.align 4
Lxts_dec6x_two:
vxor $out0,$in4,$twk0
vxor $out1,$in5,$twk1
vxor $out2,$out2,$out2
vxor $out3,$out3,$out3
vxor $out4,$out4,$out4
bl _aesp8_xts_dec5x
le?vperm $out0,$out0,$out0,$leperm
vmr $twk0,$twk2 # unused tweak
vmr $twk1,$twk3
le?vperm $out1,$out1,$out1,$leperm
stvx_u $out0,$x00,$out # store output
vxor $out0,$in0,$twk3
stvx_u $out1,$x10,$out
addi $out,$out,0x20
bne Lxts_dec6x_steal
b Lxts_dec6x_done
.align 4
Lxts_dec6x_one:
vxor $out0,$in5,$twk0
nop
Loop_xts_dec1x:
vncipher $out0,$out0,v24
lvx v24,$x20,$key_ # round[3]
addi $key_,$key_,0x20
vncipher $out0,$out0,v25
lvx v25,$x10,$key_ # round[4]
bdnz Loop_xts_dec1x
subi r0,$taillen,1
vncipher $out0,$out0,v24
andi. r0,r0,16
cmpwi $taillen,0
vncipher $out0,$out0,v25
sub $inp,$inp,r0
vncipher $out0,$out0,v26
lvx_u $in0,0,$inp
vncipher $out0,$out0,v27
addi $key_,$sp,$FRAME+15 # rewind $key_
vncipher $out0,$out0,v28
lvx v24,$x00,$key_ # re-pre-load round[1]
vncipher $out0,$out0,v29
lvx v25,$x10,$key_ # re-pre-load round[2]
vxor $twk0,$twk0,v31
le?vperm $in0,$in0,$in0,$leperm
vncipher $out0,$out0,v30
mtctr $rounds
vncipherlast $out0,$out0,$twk0
vmr $twk0,$twk1 # unused tweak
vmr $twk1,$twk2
le?vperm $out0,$out0,$out0,$leperm
stvx_u $out0,$x00,$out # store output
addi $out,$out,0x10
vxor $out0,$in0,$twk2
bne Lxts_dec6x_steal
b Lxts_dec6x_done
.align 4
Lxts_dec6x_zero:
cmpwi $taillen,0
beq Lxts_dec6x_done
lvx_u $in0,0,$inp
le?vperm $in0,$in0,$in0,$leperm
vxor $out0,$in0,$twk1
Lxts_dec6x_steal:
vncipher $out0,$out0,v24
lvx v24,$x20,$key_ # round[3]
addi $key_,$key_,0x20
vncipher $out0,$out0,v25
lvx v25,$x10,$key_ # round[4]
bdnz Lxts_dec6x_steal
add $inp,$inp,$taillen
vncipher $out0,$out0,v24
cmpwi $taillen,0
vncipher $out0,$out0,v25
lvx_u $in0,0,$inp
vncipher $out0,$out0,v26
lvsr $inpperm,0,$taillen # $in5 is no more
vncipher $out0,$out0,v27
addi $key_,$sp,$FRAME+15 # rewind $key_
vncipher $out0,$out0,v28
lvx v24,$x00,$key_ # re-pre-load round[1]
vncipher $out0,$out0,v29
lvx v25,$x10,$key_ # re-pre-load round[2]
vxor $twk1,$twk1,v31
le?vperm $in0,$in0,$in0,$leperm
vncipher $out0,$out0,v30
vperm $in0,$in0,$in0,$inpperm
vncipherlast $tmp,$out0,$twk1
le?vperm $out0,$tmp,$tmp,$leperm
le?stvx_u $out0,0,$out
be?stvx_u $tmp,0,$out
vxor $out0,$out0,$out0
vspltisb $out1,-1
vperm $out0,$out0,$out1,$inpperm
vsel $out0,$in0,$tmp,$out0
vxor $out0,$out0,$twk0
subi r30,$out,1
mtctr $taillen
Loop_xts_dec6x_steal:
lbzu r0,1(r30)
stb r0,16(r30)
bdnz Loop_xts_dec6x_steal
li $taillen,0
mtctr $rounds
b Loop_xts_dec1x # one more time...
.align 4
Lxts_dec6x_done:
${UCMP}i $ivp,0
beq Lxts_dec6x_ret
vxor $tweak,$twk0,$rndkey0
le?vperm $tweak,$tweak,$tweak,$leperm
stvx_u $tweak,0,$ivp
Lxts_dec6x_ret:
mtlr r11
li r10,`$FRAME+15`
li r11,`$FRAME+31`
stvx $seven,r10,$sp # wipe copies of round keys
addi r10,r10,32
stvx $seven,r11,$sp
addi r11,r11,32
stvx $seven,r10,$sp
addi r10,r10,32
stvx $seven,r11,$sp
addi r11,r11,32
stvx $seven,r10,$sp
addi r10,r10,32
stvx $seven,r11,$sp
addi r11,r11,32
stvx $seven,r10,$sp
addi r10,r10,32
stvx $seven,r11,$sp
addi r11,r11,32
mtspr 256,$vrsave
lvx v20,r10,$sp # ABI says so
addi r10,r10,32
lvx v21,r11,$sp
addi r11,r11,32
lvx v22,r10,$sp
addi r10,r10,32
lvx v23,r11,$sp
addi r11,r11,32
lvx v24,r10,$sp
addi r10,r10,32
lvx v25,r11,$sp
addi r11,r11,32
lvx v26,r10,$sp
addi r10,r10,32
lvx v27,r11,$sp
addi r11,r11,32
lvx v28,r10,$sp
addi r10,r10,32
lvx v29,r11,$sp
addi r11,r11,32
lvx v30,r10,$sp
lvx v31,r11,$sp
$POP r26,`$FRAME+21*16+0*$SIZE_T`($sp)
$POP r27,`$FRAME+21*16+1*$SIZE_T`($sp)
$POP r28,`$FRAME+21*16+2*$SIZE_T`($sp)
$POP r29,`$FRAME+21*16+3*$SIZE_T`($sp)
$POP r30,`$FRAME+21*16+4*$SIZE_T`($sp)
$POP r31,`$FRAME+21*16+5*$SIZE_T`($sp)
addi $sp,$sp,`$FRAME+21*16+6*$SIZE_T`
blr
.long 0
.byte 0,12,0x04,1,0x80,6,6,0
.long 0
.align 5
_aesp8_xts_dec5x:
vncipher $out0,$out0,v24
vncipher $out1,$out1,v24
vncipher $out2,$out2,v24
vncipher $out3,$out3,v24
vncipher $out4,$out4,v24
lvx v24,$x20,$key_ # round[3]
addi $key_,$key_,0x20
vncipher $out0,$out0,v25
vncipher $out1,$out1,v25
vncipher $out2,$out2,v25
vncipher $out3,$out3,v25
vncipher $out4,$out4,v25
lvx v25,$x10,$key_ # round[4]
bdnz _aesp8_xts_dec5x
subi r0,$taillen,1
vncipher $out0,$out0,v24
vncipher $out1,$out1,v24
vncipher $out2,$out2,v24
vncipher $out3,$out3,v24
vncipher $out4,$out4,v24
andi. r0,r0,16
cmpwi $taillen,0
vncipher $out0,$out0,v25
vncipher $out1,$out1,v25
vncipher $out2,$out2,v25
vncipher $out3,$out3,v25
vncipher $out4,$out4,v25
vxor $twk0,$twk0,v31
sub $inp,$inp,r0
vncipher $out0,$out0,v26
vncipher $out1,$out1,v26
vncipher $out2,$out2,v26
vncipher $out3,$out3,v26
vncipher $out4,$out4,v26
vxor $in1,$twk1,v31
vncipher $out0,$out0,v27
lvx_u $in0,0,$inp
vncipher $out1,$out1,v27
vncipher $out2,$out2,v27
vncipher $out3,$out3,v27
vncipher $out4,$out4,v27
vxor $in2,$twk2,v31
addi $key_,$sp,$FRAME+15 # rewind $key_
vncipher $out0,$out0,v28
vncipher $out1,$out1,v28
vncipher $out2,$out2,v28
vncipher $out3,$out3,v28
vncipher $out4,$out4,v28
lvx v24,$x00,$key_ # re-pre-load round[1]
vxor $in3,$twk3,v31
vncipher $out0,$out0,v29
le?vperm $in0,$in0,$in0,$leperm
vncipher $out1,$out1,v29
vncipher $out2,$out2,v29
vncipher $out3,$out3,v29
vncipher $out4,$out4,v29
lvx v25,$x10,$key_ # re-pre-load round[2]
vxor $in4,$twk4,v31
vncipher $out0,$out0,v30
vncipher $out1,$out1,v30
vncipher $out2,$out2,v30
vncipher $out3,$out3,v30
vncipher $out4,$out4,v30
vncipherlast $out0,$out0,$twk0
vncipherlast $out1,$out1,$in1
vncipherlast $out2,$out2,$in2
vncipherlast $out3,$out3,$in3
vncipherlast $out4,$out4,$in4
mtctr $rounds
blr
.long 0
.byte 0,12,0x14,0,0,0,0,0
___
}} }}}
my $consts=1;
foreach(split("\n",$code)) {
s/\`([^\`]*)\`/eval($1)/geo;
# constants table endian-specific conversion
if ($consts && m/\.(long|byte)\s+(.+)\s+(\?[a-z]*)$/o) {
my $conv=$3;
my @bytes=();
# convert to endian-agnostic format
if ($1 eq "long") {
foreach (split(/,\s*/,$2)) {
my $l = /^0/?oct:int;
push @bytes,($l>>24)&0xff,($l>>16)&0xff,($l>>8)&0xff,$l&0xff;
}
} else {
@bytes = map(/^0/?oct:int,split(/,\s*/,$2));
}
# little-endian conversion
if ($flavour =~ /le$/o) {
SWITCH: for($conv) {
/\?inv/ && do { @bytes=map($_^0xf,@bytes); last; };
/\?rev/ && do { @bytes=reverse(@bytes); last; };
}
}
#emit
print ".byte\t",join(',',map (sprintf("0x%02x",$_),@bytes)),"\n";
next;
}
$consts=0 if (m/Lconsts:/o); # end of table
# instructions prefixed with '?' are endian-specific and need
# to be adjusted accordingly...
if ($flavour =~ /le$/o) { # little-endian
s/le\?//o or
s/be\?/#be#/o or
s/\?lvsr/lvsl/o or
s/\?lvsl/lvsr/o or
s/\?(vperm\s+v[0-9]+,\s*)(v[0-9]+,\s*)(v[0-9]+,\s*)(v[0-9]+)/$1$3$2$4/o or
s/\?(vsldoi\s+v[0-9]+,\s*)(v[0-9]+,)\s*(v[0-9]+,\s*)([0-9]+)/$1$3$2 16-$4/o or
s/\?(vspltw\s+v[0-9]+,\s*)(v[0-9]+,)\s*([0-9])/$1$2 3-$3/o;
} else { # big-endian
s/le\?/#le#/o or
s/be\?//o or
s/\?([a-z]+)/$1/o;
}
print $_,"\n";
}
close STDOUT or die "error closing STDOUT: $!";
diff --git a/crypto/openssl/crypto/aes/build.info b/crypto/openssl/crypto/aes/build.info
index dec340779281..381cf69a64c8 100644
--- a/crypto/openssl/crypto/aes/build.info
+++ b/crypto/openssl/crypto/aes/build.info
@@ -1,129 +1,133 @@
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
+ IF[{- $target{sys_id} ne "MACOSX" -}]
$AESASM_ppc32=aes_core.c aes_cbc.c aes-ppc.s vpaes-ppc.s aesp8-ppc.s
+ ELSE
+ $AESASM_ppc32=aes_core.c aes_cbc.c aes-ppc.s vpaes-ppc.s
+ ENDIF
$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
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/asn1/a_d2i_fp.c b/crypto/openssl/crypto/asn1/a_d2i_fp.c
index e8602053f974..bd549215b400 100644
--- a/crypto/openssl/crypto/asn1/a_d2i_fp.c
+++ b/crypto/openssl/crypto/asn1/a_d2i_fp.c
@@ -1,253 +1,256 @@
/*
- * 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 <stdio.h>
#include <limits.h>
#include "internal/cryptlib.h"
#include "internal/numbers.h"
#include <openssl/buffer.h>
#include <openssl/asn1.h>
#include "internal/asn1.h"
#include "crypto/asn1.h"
#ifndef NO_OLD_ASN1
# ifndef OPENSSL_NO_STDIO
void *ASN1_d2i_fp(void *(*xnew) (void), d2i_of_void *d2i, FILE *in, void **x)
{
BIO *b;
void *ret;
if ((b = BIO_new(BIO_s_file())) == NULL) {
ERR_raise(ERR_LIB_ASN1, ERR_R_BUF_LIB);
return NULL;
}
BIO_set_fp(b, in, BIO_NOCLOSE);
ret = ASN1_d2i_bio(xnew, d2i, b, x);
BIO_free(b);
return ret;
}
# endif
void *ASN1_d2i_bio(void *(*xnew) (void), d2i_of_void *d2i, BIO *in, void **x)
{
BUF_MEM *b = NULL;
const unsigned char *p;
void *ret = NULL;
int len;
len = asn1_d2i_read_bio(in, &b);
if (len < 0)
goto err;
p = (unsigned char *)b->data;
ret = d2i(x, &p, len);
err:
BUF_MEM_free(b);
return ret;
}
#endif
void *ASN1_item_d2i_bio_ex(const ASN1_ITEM *it, BIO *in, void *x,
OSSL_LIB_CTX *libctx, const char *propq)
{
BUF_MEM *b = NULL;
const unsigned char *p;
void *ret = NULL;
int len;
if (in == NULL)
return NULL;
len = asn1_d2i_read_bio(in, &b);
if (len < 0)
goto err;
p = (const unsigned char *)b->data;
ret = ASN1_item_d2i_ex(x, &p, len, it, libctx, propq);
err:
BUF_MEM_free(b);
return ret;
}
void *ASN1_item_d2i_bio(const ASN1_ITEM *it, BIO *in, void *x)
{
return ASN1_item_d2i_bio_ex(it, in, x, NULL, NULL);
}
#ifndef OPENSSL_NO_STDIO
void *ASN1_item_d2i_fp_ex(const ASN1_ITEM *it, FILE *in, void *x,
OSSL_LIB_CTX *libctx, const char *propq)
{
BIO *b;
char *ret;
if ((b = BIO_new(BIO_s_file())) == NULL) {
ERR_raise(ERR_LIB_ASN1, ERR_R_BUF_LIB);
return NULL;
}
BIO_set_fp(b, in, BIO_NOCLOSE);
ret = ASN1_item_d2i_bio_ex(it, b, x, libctx, propq);
BIO_free(b);
return ret;
}
void *ASN1_item_d2i_fp(const ASN1_ITEM *it, FILE *in, void *x)
{
return ASN1_item_d2i_fp_ex(it, in, x, NULL, NULL);
}
#endif
#define HEADER_SIZE 8
#define ASN1_CHUNK_INITIAL_SIZE (16 * 1024)
int asn1_d2i_read_bio(BIO *in, BUF_MEM **pb)
{
BUF_MEM *b;
unsigned char *p;
int i;
size_t want = HEADER_SIZE;
uint32_t eos = 0;
size_t off = 0;
size_t len = 0;
size_t diff;
const unsigned char *q;
long slen;
int inf, tag, xclass;
b = BUF_MEM_new();
if (b == NULL) {
ERR_raise(ERR_LIB_ASN1, ERR_R_MALLOC_FAILURE);
return -1;
}
ERR_set_mark();
for (;;) {
diff = len - off;
if (want >= diff) {
want -= diff;
if (len + want < len || !BUF_MEM_grow_clean(b, len + want)) {
ERR_raise(ERR_LIB_ASN1, ERR_R_MALLOC_FAILURE);
goto err;
}
i = BIO_read(in, &(b->data[len]), want);
if (i < 0 && diff == 0) {
ERR_raise(ERR_LIB_ASN1, ASN1_R_NOT_ENOUGH_DATA);
goto err;
}
if (i > 0) {
if (len + i < len) {
ERR_raise(ERR_LIB_ASN1, ASN1_R_TOO_LONG);
goto err;
}
len += i;
+ if ((size_t)i < want)
+ continue;
+
}
}
/* else data already loaded */
p = (unsigned char *)&(b->data[off]);
q = p;
diff = len - off;
if (diff == 0)
goto err;
inf = ASN1_get_object(&q, &slen, &tag, &xclass, diff);
if (inf & 0x80) {
unsigned long e;
e = ERR_GET_REASON(ERR_peek_last_error());
if (e != ASN1_R_TOO_LONG)
goto err;
ERR_pop_to_mark();
}
i = q - p; /* header length */
off += i; /* end of data */
if (inf & 1) {
/* no data body so go round again */
if (eos == UINT32_MAX) {
ERR_raise(ERR_LIB_ASN1, ASN1_R_HEADER_TOO_LONG);
goto err;
}
eos++;
want = HEADER_SIZE;
} else if (eos && (slen == 0) && (tag == V_ASN1_EOC)) {
/* eos value, so go back and read another header */
eos--;
if (eos == 0)
break;
else
want = HEADER_SIZE;
} else {
/* suck in slen bytes of data */
want = slen;
if (want > (len - off)) {
size_t chunk_max = ASN1_CHUNK_INITIAL_SIZE;
want -= (len - off);
if (want > INT_MAX /* BIO_read takes an int length */ ||
len + want < len) {
ERR_raise(ERR_LIB_ASN1, ASN1_R_TOO_LONG);
goto err;
}
while (want > 0) {
/*
* Read content in chunks of increasing size
* so we can return an error for EOF without
* having to allocate the entire content length
* in one go.
*/
size_t chunk = want > chunk_max ? chunk_max : want;
if (!BUF_MEM_grow_clean(b, len + chunk)) {
ERR_raise(ERR_LIB_ASN1, ERR_R_MALLOC_FAILURE);
goto err;
}
want -= chunk;
while (chunk > 0) {
i = BIO_read(in, &(b->data[len]), chunk);
if (i <= 0) {
ERR_raise(ERR_LIB_ASN1, ASN1_R_NOT_ENOUGH_DATA);
goto err;
}
/*
* This can't overflow because |len+want| didn't
* overflow.
*/
len += i;
chunk -= i;
}
if (chunk_max < INT_MAX/2)
chunk_max *= 2;
}
}
if (off + slen < off) {
ERR_raise(ERR_LIB_ASN1, ASN1_R_TOO_LONG);
goto err;
}
off += slen;
if (eos == 0) {
break;
} else
want = HEADER_SIZE;
}
}
if (off > INT_MAX) {
ERR_raise(ERR_LIB_ASN1, ASN1_R_TOO_LONG);
goto err;
}
*pb = b;
return off;
err:
ERR_clear_last_mark();
BUF_MEM_free(b);
return -1;
}
diff --git a/crypto/openssl/crypto/asn1/a_mbstr.c b/crypto/openssl/crypto/asn1/a_mbstr.c
index 22dea873eeba..bca1458ad6a1 100644
--- a/crypto/openssl/crypto/asn1/a_mbstr.c
+++ b/crypto/openssl/crypto/asn1/a_mbstr.c
@@ -1,350 +1,354 @@
/*
- * Copyright 1999-2021 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 <stdio.h>
#include "crypto/ctype.h"
#include "internal/cryptlib.h"
#include "internal/unicode.h"
#include <openssl/asn1.h>
static int traverse_string(const unsigned char *p, int len, int inform,
int (*rfunc) (unsigned long value, void *in),
void *arg);
static int in_utf8(unsigned long value, void *arg);
static int out_utf8(unsigned long value, void *arg);
static int type_str(unsigned long value, void *arg);
static int cpy_asc(unsigned long value, void *arg);
static int cpy_bmp(unsigned long value, void *arg);
static int cpy_univ(unsigned long value, void *arg);
static int cpy_utf8(unsigned long value, void *arg);
/*
* These functions take a string in UTF8, ASCII or multibyte form and a mask
* of permissible ASN1 string types. It then works out the minimal type
* (using the order Numeric < Printable < IA5 < T61 < BMP < Universal < UTF8)
* and creates a string of the correct type with the supplied data. Yes this is
* horrible: it has to be :-( The 'ncopy' form checks minimum and maximum
* size limits too.
*/
int ASN1_mbstring_copy(ASN1_STRING **out, const unsigned char *in, int len,
int inform, unsigned long mask)
{
return ASN1_mbstring_ncopy(out, in, len, inform, mask, 0, 0);
}
int ASN1_mbstring_ncopy(ASN1_STRING **out, const unsigned char *in, int len,
int inform, unsigned long mask,
long minsize, long maxsize)
{
int str_type;
int ret;
char free_out;
int outform, outlen = 0;
ASN1_STRING *dest;
unsigned char *p;
int nchar;
int (*cpyfunc) (unsigned long, void *) = NULL;
if (len == -1)
len = strlen((const char *)in);
if (!mask)
mask = DIRSTRING_TYPE;
if (len < 0)
return -1;
/* First do a string check and work out the number of characters */
switch (inform) {
case MBSTRING_BMP:
if (len & 1) {
ERR_raise(ERR_LIB_ASN1, ASN1_R_INVALID_BMPSTRING_LENGTH);
return -1;
}
nchar = len >> 1;
break;
case MBSTRING_UNIV:
if (len & 3) {
ERR_raise(ERR_LIB_ASN1, ASN1_R_INVALID_UNIVERSALSTRING_LENGTH);
return -1;
}
nchar = len >> 2;
break;
case MBSTRING_UTF8:
nchar = 0;
/* This counts the characters and does utf8 syntax checking */
ret = traverse_string(in, len, MBSTRING_UTF8, in_utf8, &nchar);
if (ret < 0) {
ERR_raise(ERR_LIB_ASN1, ASN1_R_INVALID_UTF8STRING);
return -1;
}
break;
case MBSTRING_ASC:
nchar = len;
break;
default:
ERR_raise(ERR_LIB_ASN1, ASN1_R_UNKNOWN_FORMAT);
return -1;
}
if ((minsize > 0) && (nchar < minsize)) {
ERR_raise_data(ERR_LIB_ASN1, ASN1_R_STRING_TOO_SHORT,
"minsize=%ld", minsize);
return -1;
}
if ((maxsize > 0) && (nchar > maxsize)) {
ERR_raise_data(ERR_LIB_ASN1, ASN1_R_STRING_TOO_LONG,
"maxsize=%ld", maxsize);
return -1;
}
/* Now work out minimal type (if any) */
if (traverse_string(in, len, inform, type_str, &mask) < 0) {
ERR_raise(ERR_LIB_ASN1, ASN1_R_ILLEGAL_CHARACTERS);
return -1;
}
/* Now work out output format and string type */
outform = MBSTRING_ASC;
if (mask & B_ASN1_NUMERICSTRING)
str_type = V_ASN1_NUMERICSTRING;
else if (mask & B_ASN1_PRINTABLESTRING)
str_type = V_ASN1_PRINTABLESTRING;
else if (mask & B_ASN1_IA5STRING)
str_type = V_ASN1_IA5STRING;
else if (mask & B_ASN1_T61STRING)
str_type = V_ASN1_T61STRING;
else if (mask & B_ASN1_BMPSTRING) {
str_type = V_ASN1_BMPSTRING;
outform = MBSTRING_BMP;
} else if (mask & B_ASN1_UNIVERSALSTRING) {
str_type = V_ASN1_UNIVERSALSTRING;
outform = MBSTRING_UNIV;
} else {
str_type = V_ASN1_UTF8STRING;
outform = MBSTRING_UTF8;
}
if (!out)
return str_type;
if (*out) {
free_out = 0;
dest = *out;
- OPENSSL_free(dest->data);
- dest->data = NULL;
- dest->length = 0;
+ ASN1_STRING_set0(dest, NULL, 0);
dest->type = str_type;
} else {
free_out = 1;
dest = ASN1_STRING_type_new(str_type);
if (dest == NULL) {
ERR_raise(ERR_LIB_ASN1, ERR_R_MALLOC_FAILURE);
return -1;
}
*out = dest;
}
/* If both the same type just copy across */
if (inform == outform) {
if (!ASN1_STRING_set(dest, in, len)) {
+ if (free_out) {
+ ASN1_STRING_free(dest);
+ *out = NULL;
+ }
ERR_raise(ERR_LIB_ASN1, ERR_R_MALLOC_FAILURE);
return -1;
}
return str_type;
}
/* Work out how much space the destination will need */
switch (outform) {
case MBSTRING_ASC:
outlen = nchar;
cpyfunc = cpy_asc;
break;
case MBSTRING_BMP:
outlen = nchar << 1;
cpyfunc = cpy_bmp;
break;
case MBSTRING_UNIV:
outlen = nchar << 2;
cpyfunc = cpy_univ;
break;
case MBSTRING_UTF8:
outlen = 0;
traverse_string(in, len, inform, out_utf8, &outlen);
cpyfunc = cpy_utf8;
break;
}
if ((p = OPENSSL_malloc(outlen + 1)) == NULL) {
- if (free_out)
+ if (free_out) {
ASN1_STRING_free(dest);
+ *out = NULL;
+ }
ERR_raise(ERR_LIB_ASN1, ERR_R_MALLOC_FAILURE);
return -1;
}
dest->length = outlen;
dest->data = p;
p[outlen] = 0;
traverse_string(in, len, inform, cpyfunc, &p);
return str_type;
}
/*
* This function traverses a string and passes the value of each character to
* an optional function along with a void * argument.
*/
static int traverse_string(const unsigned char *p, int len, int inform,
int (*rfunc) (unsigned long value, void *in),
void *arg)
{
unsigned long value;
int ret;
while (len) {
if (inform == MBSTRING_ASC) {
value = *p++;
len--;
} else if (inform == MBSTRING_BMP) {
value = *p++ << 8;
value |= *p++;
len -= 2;
} else if (inform == MBSTRING_UNIV) {
value = ((unsigned long)*p++) << 24;
value |= ((unsigned long)*p++) << 16;
value |= *p++ << 8;
value |= *p++;
len -= 4;
} else {
ret = UTF8_getc(p, len, &value);
if (ret < 0)
return -1;
len -= ret;
p += ret;
}
if (rfunc) {
ret = rfunc(value, arg);
if (ret <= 0)
return ret;
}
}
return 1;
}
/* Various utility functions for traverse_string */
/* Just count number of characters */
static int in_utf8(unsigned long value, void *arg)
{
int *nchar;
if (!is_unicode_valid(value))
return -2;
nchar = arg;
(*nchar)++;
return 1;
}
/* Determine size of output as a UTF8 String */
static int out_utf8(unsigned long value, void *arg)
{
int *outlen, len;
len = UTF8_putc(NULL, -1, value);
if (len <= 0)
return len;
outlen = arg;
*outlen += len;
return 1;
}
/*
* Determine the "type" of a string: check each character against a supplied
* "mask".
*/
static int type_str(unsigned long value, void *arg)
{
unsigned long types = *((unsigned long *)arg);
const int native = value > INT_MAX ? INT_MAX : ossl_fromascii(value);
if ((types & B_ASN1_NUMERICSTRING) && !(ossl_isdigit(native)
|| native == ' '))
types &= ~B_ASN1_NUMERICSTRING;
if ((types & B_ASN1_PRINTABLESTRING) && !ossl_isasn1print(native))
types &= ~B_ASN1_PRINTABLESTRING;
if ((types & B_ASN1_IA5STRING) && !ossl_isascii(native))
types &= ~B_ASN1_IA5STRING;
if ((types & B_ASN1_T61STRING) && (value > 0xff))
types &= ~B_ASN1_T61STRING;
if ((types & B_ASN1_BMPSTRING) && (value > 0xffff))
types &= ~B_ASN1_BMPSTRING;
if ((types & B_ASN1_UTF8STRING) && !is_unicode_valid(value))
types &= ~B_ASN1_UTF8STRING;
if (!types)
return -1;
*((unsigned long *)arg) = types;
return 1;
}
/* Copy one byte per character ASCII like strings */
static int cpy_asc(unsigned long value, void *arg)
{
unsigned char **p, *q;
p = arg;
q = *p;
*q = (unsigned char)value;
(*p)++;
return 1;
}
/* Copy two byte per character BMPStrings */
static int cpy_bmp(unsigned long value, void *arg)
{
unsigned char **p, *q;
p = arg;
q = *p;
*q++ = (unsigned char)((value >> 8) & 0xff);
*q = (unsigned char)(value & 0xff);
*p += 2;
return 1;
}
/* Copy four byte per character UniversalStrings */
static int cpy_univ(unsigned long value, void *arg)
{
unsigned char **p, *q;
p = arg;
q = *p;
*q++ = (unsigned char)((value >> 24) & 0xff);
*q++ = (unsigned char)((value >> 16) & 0xff);
*q++ = (unsigned char)((value >> 8) & 0xff);
*q = (unsigned char)(value & 0xff);
*p += 4;
return 1;
}
/* Copy to a UTF8String */
static int cpy_utf8(unsigned long value, void *arg)
{
unsigned char **p;
int ret;
p = arg;
/* We already know there is enough room so pass 0xff as the length */
ret = UTF8_putc(*p, 0xff, value);
*p += ret;
return 1;
}
diff --git a/crypto/openssl/crypto/asn1/a_strex.c b/crypto/openssl/crypto/asn1/a_strex.c
index b31761aae6f5..a6049f7dd2ed 100644
--- a/crypto/openssl/crypto/asn1/a_strex.c
+++ b/crypto/openssl/crypto/asn1/a_strex.c
@@ -1,628 +1,631 @@
/*
- * 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
* https://www.openssl.org/source/license.html
*/
#include <stdio.h>
#include <string.h>
#include "internal/cryptlib.h"
+#include "internal/sizes.h"
#include "crypto/asn1.h"
#include <openssl/crypto.h>
#include <openssl/x509.h>
#include <openssl/asn1.h>
#include "charmap.h"
/*
* ASN1_STRING_print_ex() and X509_NAME_print_ex(). Enhanced string and name
* printing routines handling multibyte characters, RFC2253 and a host of
* other options.
*/
#define CHARTYPE_BS_ESC (ASN1_STRFLGS_ESC_2253 | CHARTYPE_FIRST_ESC_2253 | CHARTYPE_LAST_ESC_2253)
#define ESC_FLAGS (ASN1_STRFLGS_ESC_2253 | \
ASN1_STRFLGS_ESC_2254 | \
ASN1_STRFLGS_ESC_QUOTE | \
ASN1_STRFLGS_ESC_CTRL | \
ASN1_STRFLGS_ESC_MSB)
/*
* Three IO functions for sending data to memory, a BIO and a FILE
* pointer.
*/
static int send_bio_chars(void *arg, const void *buf, int len)
{
if (!arg)
return 1;
if (BIO_write(arg, buf, len) != len)
return 0;
return 1;
}
#ifndef OPENSSL_NO_STDIO
static int send_fp_chars(void *arg, const void *buf, int len)
{
if (!arg)
return 1;
if (fwrite(buf, 1, len, arg) != (unsigned int)len)
return 0;
return 1;
}
#endif
typedef int char_io (void *arg, const void *buf, int len);
/*
* This function handles display of strings, one character at a time. It is
* passed an unsigned long for each character because it could come from 2 or
* even 4 byte forms.
*/
static int do_esc_char(unsigned long c, unsigned short flags, char *do_quotes,
char_io *io_ch, void *arg)
{
unsigned short chflgs;
unsigned char chtmp;
char tmphex[HEX_SIZE(long) + 3];
if (c > 0xffffffffL)
return -1;
if (c > 0xffff) {
BIO_snprintf(tmphex, sizeof(tmphex), "\\W%08lX", c);
if (!io_ch(arg, tmphex, 10))
return -1;
return 10;
}
if (c > 0xff) {
BIO_snprintf(tmphex, sizeof(tmphex), "\\U%04lX", c);
if (!io_ch(arg, tmphex, 6))
return -1;
return 6;
}
chtmp = (unsigned char)c;
if (chtmp > 0x7f)
chflgs = flags & ASN1_STRFLGS_ESC_MSB;
else
chflgs = char_type[chtmp] & flags;
if (chflgs & CHARTYPE_BS_ESC) {
/* If we don't escape with quotes, signal we need quotes */
if (chflgs & ASN1_STRFLGS_ESC_QUOTE) {
if (do_quotes)
*do_quotes = 1;
if (!io_ch(arg, &chtmp, 1))
return -1;
return 1;
}
if (!io_ch(arg, "\\", 1))
return -1;
if (!io_ch(arg, &chtmp, 1))
return -1;
return 2;
}
if (chflgs & (ASN1_STRFLGS_ESC_CTRL
| ASN1_STRFLGS_ESC_MSB
| ASN1_STRFLGS_ESC_2254)) {
BIO_snprintf(tmphex, 11, "\\%02X", chtmp);
if (!io_ch(arg, tmphex, 3))
return -1;
return 3;
}
/*
* If we get this far and do any escaping at all must escape the escape
* character itself: backslash.
*/
if (chtmp == '\\' && (flags & ESC_FLAGS)) {
if (!io_ch(arg, "\\\\", 2))
return -1;
return 2;
}
if (!io_ch(arg, &chtmp, 1))
return -1;
return 1;
}
#define BUF_TYPE_WIDTH_MASK 0x7
#define BUF_TYPE_CONVUTF8 0x8
/*
* This function sends each character in a buffer to do_esc_char(). It
* interprets the content formats and converts to or from UTF8 as
* appropriate.
*/
static int do_buf(unsigned char *buf, int buflen,
int type, unsigned short flags, char *quotes, char_io *io_ch,
void *arg)
{
int i, outlen, len, charwidth;
unsigned short orflags;
unsigned char *p, *q;
unsigned long c;
p = buf;
q = buf + buflen;
outlen = 0;
charwidth = type & BUF_TYPE_WIDTH_MASK;
switch (charwidth) {
case 4:
if (buflen & 3) {
ERR_raise(ERR_LIB_ASN1, ASN1_R_INVALID_UNIVERSALSTRING_LENGTH);
return -1;
}
break;
case 2:
if (buflen & 1) {
ERR_raise(ERR_LIB_ASN1, ASN1_R_INVALID_BMPSTRING_LENGTH);
return -1;
}
break;
default:
break;
}
while (p != q) {
if (p == buf && flags & ASN1_STRFLGS_ESC_2253)
orflags = CHARTYPE_FIRST_ESC_2253;
else
orflags = 0;
switch (charwidth) {
case 4:
c = ((unsigned long)*p++) << 24;
c |= ((unsigned long)*p++) << 16;
c |= ((unsigned long)*p++) << 8;
c |= *p++;
break;
case 2:
c = ((unsigned long)*p++) << 8;
c |= *p++;
break;
case 1:
c = *p++;
break;
case 0:
i = UTF8_getc(p, buflen, &c);
if (i < 0)
return -1; /* Invalid UTF8String */
buflen -= i;
p += i;
break;
default:
return -1; /* invalid width */
}
if (p == q && flags & ASN1_STRFLGS_ESC_2253)
orflags = CHARTYPE_LAST_ESC_2253;
if (type & BUF_TYPE_CONVUTF8) {
unsigned char utfbuf[6];
int utflen;
utflen = UTF8_putc(utfbuf, sizeof(utfbuf), c);
for (i = 0; i < utflen; i++) {
/*
* We don't need to worry about setting orflags correctly
* because if utflen==1 its value will be correct anyway
* otherwise each character will be > 0x7f and so the
* character will never be escaped on first and last.
*/
len = do_esc_char(utfbuf[i], flags | orflags, quotes,
io_ch, arg);
if (len < 0)
return -1;
outlen += len;
}
} else {
len = do_esc_char(c, flags | orflags, quotes,
io_ch, arg);
if (len < 0)
return -1;
outlen += len;
}
}
return outlen;
}
/* This function hex dumps a buffer of characters */
static int do_hex_dump(char_io *io_ch, void *arg, unsigned char *buf,
int buflen)
{
static const char hexdig[] = "0123456789ABCDEF";
unsigned char *p, *q;
char hextmp[2];
if (arg) {
p = buf;
q = buf + buflen;
while (p != q) {
hextmp[0] = hexdig[*p >> 4];
hextmp[1] = hexdig[*p & 0xf];
if (!io_ch(arg, hextmp, 2))
return -1;
p++;
}
}
return buflen << 1;
}
/*
* "dump" a string. This is done when the type is unknown, or the flags
* request it. We can either dump the content octets or the entire DER
* encoding. This uses the RFC2253 #01234 format.
*/
static int do_dump(unsigned long lflags, char_io *io_ch, void *arg,
const ASN1_STRING *str)
{
/*
* Placing the ASN1_STRING in a temp ASN1_TYPE allows the DER encoding to
* readily obtained
*/
ASN1_TYPE t;
unsigned char *der_buf, *p;
int outlen, der_len;
if (!io_ch(arg, "#", 1))
return -1;
/* If we don't dump DER encoding just dump content octets */
if (!(lflags & ASN1_STRFLGS_DUMP_DER)) {
outlen = do_hex_dump(io_ch, arg, str->data, str->length);
if (outlen < 0)
return -1;
return outlen + 1;
}
t.type = str->type;
t.value.ptr = (char *)str;
der_len = i2d_ASN1_TYPE(&t, NULL);
if (der_len <= 0)
return -1;
if ((der_buf = OPENSSL_malloc(der_len)) == NULL) {
ERR_raise(ERR_LIB_ASN1, ERR_R_MALLOC_FAILURE);
return -1;
}
p = der_buf;
i2d_ASN1_TYPE(&t, &p);
outlen = do_hex_dump(io_ch, arg, der_buf, der_len);
OPENSSL_free(der_buf);
if (outlen < 0)
return -1;
return outlen + 1;
}
/*
* Lookup table to convert tags to character widths, 0 = UTF8 encoded, -1 is
* used for non string types otherwise it is the number of bytes per
* character
*/
static const signed char tag2nbyte[] = {
-1, -1, -1, -1, -1, /* 0-4 */
-1, -1, -1, -1, -1, /* 5-9 */
-1, -1, /* 10-11 */
0, /* 12 V_ASN1_UTF8STRING */
-1, -1, -1, -1, -1, /* 13-17 */
1, /* 18 V_ASN1_NUMERICSTRING */
1, /* 19 V_ASN1_PRINTABLESTRING */
1, /* 20 V_ASN1_T61STRING */
-1, /* 21 */
1, /* 22 V_ASN1_IA5STRING */
1, /* 23 V_ASN1_UTCTIME */
1, /* 24 V_ASN1_GENERALIZEDTIME */
-1, /* 25 */
1, /* 26 V_ASN1_ISO64STRING */
-1, /* 27 */
4, /* 28 V_ASN1_UNIVERSALSTRING */
-1, /* 29 */
2 /* 30 V_ASN1_BMPSTRING */
};
/*
* This is the main function, print out an ASN1_STRING taking note of various
* escape and display options. Returns number of characters written or -1 if
* an error occurred.
*/
static int do_print_ex(char_io *io_ch, void *arg, unsigned long lflags,
const ASN1_STRING *str)
{
int outlen, len;
int type;
char quotes;
unsigned short flags;
quotes = 0;
/* Keep a copy of escape flags */
flags = (unsigned short)(lflags & ESC_FLAGS);
type = str->type;
outlen = 0;
if (lflags & ASN1_STRFLGS_SHOW_TYPE) {
const char *tagname;
+
tagname = ASN1_tag2str(type);
- outlen += strlen(tagname);
+ /* We can directly cast here as tagname will never be too large. */
+ outlen += (int)strlen(tagname);
if (!io_ch(arg, tagname, outlen) || !io_ch(arg, ":", 1))
return -1;
outlen++;
}
/* Decide what to do with type, either dump content or display it */
/* Dump everything */
if (lflags & ASN1_STRFLGS_DUMP_ALL)
type = -1;
/* Ignore the string type */
else if (lflags & ASN1_STRFLGS_IGNORE_TYPE)
type = 1;
else {
/* Else determine width based on type */
if ((type > 0) && (type < 31))
type = tag2nbyte[type];
else
type = -1;
if ((type == -1) && !(lflags & ASN1_STRFLGS_DUMP_UNKNOWN))
type = 1;
}
if (type == -1) {
len = do_dump(lflags, io_ch, arg, str);
- if (len < 0)
+ if (len < 0 || len > INT_MAX - outlen)
return -1;
outlen += len;
return outlen;
}
if (lflags & ASN1_STRFLGS_UTF8_CONVERT) {
/*
* Note: if string is UTF8 and we want to convert to UTF8 then we
* just interpret it as 1 byte per character to avoid converting
* twice.
*/
if (!type)
type = 1;
else
type |= BUF_TYPE_CONVUTF8;
}
len = do_buf(str->data, str->length, type, flags, &quotes, io_ch, NULL);
- if (len < 0)
+ if (len < 0 || len > INT_MAX - 2 - outlen)
return -1;
outlen += len;
if (quotes)
outlen += 2;
if (!arg)
return outlen;
if (quotes && !io_ch(arg, "\"", 1))
return -1;
if (do_buf(str->data, str->length, type, flags, NULL, io_ch, arg) < 0)
return -1;
if (quotes && !io_ch(arg, "\"", 1))
return -1;
return outlen;
}
/* Used for line indenting: print 'indent' spaces */
static int do_indent(char_io *io_ch, void *arg, int indent)
{
int i;
for (i = 0; i < indent; i++)
if (!io_ch(arg, " ", 1))
return 0;
return 1;
}
#define FN_WIDTH_LN 25
#define FN_WIDTH_SN 10
static int do_name_ex(char_io *io_ch, void *arg, const X509_NAME *n,
int indent, unsigned long flags)
{
int i, prev = -1, orflags, cnt;
int fn_opt, fn_nid;
ASN1_OBJECT *fn;
const ASN1_STRING *val;
const X509_NAME_ENTRY *ent;
char objtmp[80];
const char *objbuf;
int outlen, len;
char *sep_dn, *sep_mv, *sep_eq;
int sep_dn_len, sep_mv_len, sep_eq_len;
if (indent < 0)
indent = 0;
outlen = indent;
if (!do_indent(io_ch, arg, indent))
return -1;
switch (flags & XN_FLAG_SEP_MASK) {
case XN_FLAG_SEP_MULTILINE:
sep_dn = "\n";
sep_dn_len = 1;
sep_mv = " + ";
sep_mv_len = 3;
break;
case XN_FLAG_SEP_COMMA_PLUS:
sep_dn = ",";
sep_dn_len = 1;
sep_mv = "+";
sep_mv_len = 1;
indent = 0;
break;
case XN_FLAG_SEP_CPLUS_SPC:
sep_dn = ", ";
sep_dn_len = 2;
sep_mv = " + ";
sep_mv_len = 3;
indent = 0;
break;
case XN_FLAG_SEP_SPLUS_SPC:
sep_dn = "; ";
sep_dn_len = 2;
sep_mv = " + ";
sep_mv_len = 3;
indent = 0;
break;
default:
return -1;
}
if (flags & XN_FLAG_SPC_EQ) {
sep_eq = " = ";
sep_eq_len = 3;
} else {
sep_eq = "=";
sep_eq_len = 1;
}
fn_opt = flags & XN_FLAG_FN_MASK;
cnt = X509_NAME_entry_count(n);
for (i = 0; i < cnt; i++) {
if (flags & XN_FLAG_DN_REV)
ent = X509_NAME_get_entry(n, cnt - i - 1);
else
ent = X509_NAME_get_entry(n, i);
if (prev != -1) {
if (prev == X509_NAME_ENTRY_set(ent)) {
if (!io_ch(arg, sep_mv, sep_mv_len))
return -1;
outlen += sep_mv_len;
} else {
if (!io_ch(arg, sep_dn, sep_dn_len))
return -1;
outlen += sep_dn_len;
if (!do_indent(io_ch, arg, indent))
return -1;
outlen += indent;
}
}
prev = X509_NAME_ENTRY_set(ent);
fn = X509_NAME_ENTRY_get_object(ent);
val = X509_NAME_ENTRY_get_data(ent);
fn_nid = OBJ_obj2nid(fn);
if (fn_opt != XN_FLAG_FN_NONE) {
int objlen, fld_len;
if ((fn_opt == XN_FLAG_FN_OID) || (fn_nid == NID_undef)) {
OBJ_obj2txt(objtmp, sizeof(objtmp), fn, 1);
fld_len = 0; /* XXX: what should this be? */
objbuf = objtmp;
} else {
if (fn_opt == XN_FLAG_FN_SN) {
fld_len = FN_WIDTH_SN;
objbuf = OBJ_nid2sn(fn_nid);
} else if (fn_opt == XN_FLAG_FN_LN) {
fld_len = FN_WIDTH_LN;
objbuf = OBJ_nid2ln(fn_nid);
} else {
fld_len = 0; /* XXX: what should this be? */
objbuf = "";
}
}
objlen = strlen(objbuf);
if (!io_ch(arg, objbuf, objlen))
return -1;
if ((objlen < fld_len) && (flags & XN_FLAG_FN_ALIGN)) {
if (!do_indent(io_ch, arg, fld_len - objlen))
return -1;
outlen += fld_len - objlen;
}
if (!io_ch(arg, sep_eq, sep_eq_len))
return -1;
outlen += objlen + sep_eq_len;
}
/*
* If the field name is unknown then fix up the DER dump flag. We
* might want to limit this further so it will DER dump on anything
* other than a few 'standard' fields.
*/
if ((fn_nid == NID_undef) && (flags & XN_FLAG_DUMP_UNKNOWN_FIELDS))
orflags = ASN1_STRFLGS_DUMP_ALL;
else
orflags = 0;
len = do_print_ex(io_ch, arg, flags | orflags, val);
if (len < 0)
return -1;
outlen += len;
}
return outlen;
}
/* Wrappers round the main functions */
int X509_NAME_print_ex(BIO *out, const X509_NAME *nm, int indent,
unsigned long flags)
{
if (flags == XN_FLAG_COMPAT)
return X509_NAME_print(out, nm, indent);
return do_name_ex(send_bio_chars, out, nm, indent, flags);
}
#ifndef OPENSSL_NO_STDIO
int X509_NAME_print_ex_fp(FILE *fp, const X509_NAME *nm, int indent,
unsigned long flags)
{
if (flags == XN_FLAG_COMPAT) {
BIO *btmp;
int ret;
btmp = BIO_new_fp(fp, BIO_NOCLOSE);
if (!btmp)
return -1;
ret = X509_NAME_print(btmp, nm, indent);
BIO_free(btmp);
return ret;
}
return do_name_ex(send_fp_chars, fp, nm, indent, flags);
}
#endif
int ASN1_STRING_print_ex(BIO *out, const ASN1_STRING *str, unsigned long flags)
{
return do_print_ex(send_bio_chars, out, flags, str);
}
#ifndef OPENSSL_NO_STDIO
int ASN1_STRING_print_ex_fp(FILE *fp, const ASN1_STRING *str, unsigned long flags)
{
return do_print_ex(send_fp_chars, fp, flags, str);
}
#endif
/*
* Utility function: convert any string type to UTF8, returns number of bytes
* in output string or a negative error code
*/
int ASN1_STRING_to_UTF8(unsigned char **out, const ASN1_STRING *in)
{
ASN1_STRING stmp, *str = &stmp;
int mbflag, type, ret;
if (!in)
return -1;
type = in->type;
if ((type < 0) || (type > 30))
return -1;
mbflag = tag2nbyte[type];
if (mbflag == -1)
return -1;
mbflag |= MBSTRING_FLAG;
stmp.data = NULL;
stmp.length = 0;
stmp.flags = 0;
ret =
ASN1_mbstring_copy(&str, in->data, in->length, mbflag,
B_ASN1_UTF8STRING);
if (ret < 0)
return ret;
*out = stmp.data;
return stmp.length;
}
diff --git a/crypto/openssl/crypto/asn1/a_verify.c b/crypto/openssl/crypto/asn1/a_verify.c
index 9bf9bdd14ecc..66809bd6d2ff 100644
--- a/crypto/openssl/crypto/asn1/a_verify.c
+++ b/crypto/openssl/crypto/asn1/a_verify.c
@@ -1,224 +1,226 @@
/*
- * 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 <stdio.h>
#include <time.h>
#include <sys/types.h>
#include "internal/cryptlib.h"
#include <openssl/bn.h>
#include <openssl/x509.h>
#include <openssl/objects.h>
#include <openssl/buffer.h>
#include <openssl/evp.h>
#include "crypto/asn1.h"
#include "crypto/evp.h"
#include "crypto/rsa.h"
#ifndef OPENSSL_NO_DEPRECATED_3_0
int ASN1_verify(i2d_of_void *i2d, X509_ALGOR *a, ASN1_BIT_STRING *signature,
char *data, EVP_PKEY *pkey)
{
EVP_MD_CTX *ctx = EVP_MD_CTX_new();
const EVP_MD *type;
unsigned char *p, *buf_in = NULL;
int ret = -1, i, inl;
if (ctx == NULL) {
ERR_raise(ERR_LIB_ASN1, ERR_R_MALLOC_FAILURE);
goto err;
}
i = OBJ_obj2nid(a->algorithm);
type = EVP_get_digestbyname(OBJ_nid2sn(i));
if (type == NULL) {
ERR_raise(ERR_LIB_ASN1, ASN1_R_UNKNOWN_MESSAGE_DIGEST_ALGORITHM);
goto err;
}
if (signature->type == V_ASN1_BIT_STRING && signature->flags & 0x7) {
ERR_raise(ERR_LIB_ASN1, ASN1_R_INVALID_BIT_STRING_BITS_LEFT);
goto err;
}
inl = i2d(data, NULL);
if (inl <= 0) {
ERR_raise(ERR_LIB_ASN1, ERR_R_INTERNAL_ERROR);
goto err;
}
buf_in = OPENSSL_malloc((unsigned int)inl);
if (buf_in == NULL) {
ERR_raise(ERR_LIB_ASN1, ERR_R_MALLOC_FAILURE);
goto err;
}
p = buf_in;
i2d(data, &p);
ret = EVP_VerifyInit_ex(ctx, type, NULL)
&& EVP_VerifyUpdate(ctx, (unsigned char *)buf_in, inl);
OPENSSL_clear_free(buf_in, (unsigned int)inl);
if (!ret) {
ERR_raise(ERR_LIB_ASN1, ERR_R_EVP_LIB);
goto err;
}
ret = -1;
if (EVP_VerifyFinal(ctx, (unsigned char *)signature->data,
(unsigned int)signature->length, pkey) <= 0) {
ERR_raise(ERR_LIB_ASN1, ERR_R_EVP_LIB);
ret = 0;
goto err;
}
ret = 1;
err:
EVP_MD_CTX_free(ctx);
return ret;
}
#endif
int ASN1_item_verify(const ASN1_ITEM *it, const X509_ALGOR *alg,
const ASN1_BIT_STRING *signature, const void *data,
EVP_PKEY *pkey)
{
return ASN1_item_verify_ex(it, alg, signature, data, NULL, pkey, NULL, NULL);
}
int ASN1_item_verify_ex(const ASN1_ITEM *it, const X509_ALGOR *alg,
const ASN1_BIT_STRING *signature, const void *data,
const ASN1_OCTET_STRING *id, EVP_PKEY *pkey,
OSSL_LIB_CTX *libctx, const char *propq)
{
EVP_MD_CTX *ctx;
int rv = -1;
if ((ctx = evp_md_ctx_new_ex(pkey, id, libctx, propq)) != NULL) {
rv = ASN1_item_verify_ctx(it, alg, signature, data, ctx);
EVP_PKEY_CTX_free(EVP_MD_CTX_get_pkey_ctx(ctx));
EVP_MD_CTX_free(ctx);
}
return rv;
}
int ASN1_item_verify_ctx(const ASN1_ITEM *it, const X509_ALGOR *alg,
const ASN1_BIT_STRING *signature, const void *data,
EVP_MD_CTX *ctx)
{
EVP_PKEY *pkey;
unsigned char *buf_in = NULL;
int ret = -1, inl = 0;
int mdnid, pknid;
size_t inll = 0;
pkey = EVP_PKEY_CTX_get0_pkey(EVP_MD_CTX_get_pkey_ctx(ctx));
if (pkey == NULL) {
ERR_raise(ERR_LIB_ASN1, ERR_R_PASSED_NULL_PARAMETER);
return -1;
}
if (signature->type == V_ASN1_BIT_STRING && signature->flags & 0x7) {
ERR_raise(ERR_LIB_ASN1, ASN1_R_INVALID_BIT_STRING_BITS_LEFT);
return -1;
}
/* Convert signature OID into digest and public key OIDs */
if (!OBJ_find_sigid_algs(OBJ_obj2nid(alg->algorithm), &mdnid, &pknid)) {
ERR_raise(ERR_LIB_ASN1, ASN1_R_UNKNOWN_SIGNATURE_ALGORITHM);
goto err;
}
if (mdnid == NID_undef && evp_pkey_is_legacy(pkey)) {
if (pkey->ameth == NULL || pkey->ameth->item_verify == NULL) {
ERR_raise(ERR_LIB_ASN1, ASN1_R_UNKNOWN_SIGNATURE_ALGORITHM);
goto err;
}
ret = pkey->ameth->item_verify(ctx, it, data, alg, signature, pkey);
/*
* Return values meaning:
* <=0: error.
* 1: method does everything.
* 2: carry on as normal, method has called EVP_DigestVerifyInit()
*/
if (ret <= 0)
ERR_raise(ERR_LIB_ASN1, ERR_R_EVP_LIB);
if (ret <= 1)
goto err;
} else {
const EVP_MD *type = NULL;
/*
* We don't yet have the ability for providers to be able to handle
* X509_ALGOR style parameters. Fortunately the only one that needs this
* so far is RSA-PSS, so we just special case this for now. In some
* future version of OpenSSL we should push this to the provider.
*/
if (mdnid == NID_undef && pknid == EVP_PKEY_RSA_PSS) {
if (!EVP_PKEY_is_a(pkey, "RSA") && !EVP_PKEY_is_a(pkey, "RSA-PSS")) {
ERR_raise(ERR_LIB_ASN1, ASN1_R_WRONG_PUBLIC_KEY_TYPE);
goto err;
}
/* This function also calls EVP_DigestVerifyInit */
if (ossl_rsa_pss_to_ctx(ctx, NULL, alg, pkey) <= 0) {
ERR_raise(ERR_LIB_ASN1, ERR_R_INTERNAL_ERROR);
goto err;
}
} else {
/* Check public key OID matches public key type */
if (!EVP_PKEY_is_a(pkey, OBJ_nid2sn(pknid))) {
ERR_raise(ERR_LIB_ASN1, ASN1_R_WRONG_PUBLIC_KEY_TYPE);
goto err;
}
if (mdnid != NID_undef) {
type = EVP_get_digestbynid(mdnid);
if (type == NULL) {
ERR_raise(ERR_LIB_ASN1,
ASN1_R_UNKNOWN_MESSAGE_DIGEST_ALGORITHM);
goto err;
}
}
/*
* Note that some algorithms (notably Ed25519 and Ed448) may allow
* a NULL digest value.
*/
if (!EVP_DigestVerifyInit(ctx, NULL, type, NULL, pkey)) {
ERR_raise(ERR_LIB_ASN1, ERR_R_EVP_LIB);
ret = 0;
goto err;
}
}
}
inl = ASN1_item_i2d(data, &buf_in, it);
if (inl <= 0) {
ERR_raise(ERR_LIB_ASN1, ERR_R_INTERNAL_ERROR);
+ ret = -1;
goto err;
}
if (buf_in == NULL) {
ERR_raise(ERR_LIB_ASN1, ERR_R_MALLOC_FAILURE);
+ ret = -1;
goto err;
}
inll = inl;
ret = EVP_DigestVerify(ctx, signature->data, (size_t)signature->length,
buf_in, inl);
if (ret <= 0) {
ERR_raise(ERR_LIB_ASN1, ERR_R_EVP_LIB);
goto err;
}
ret = 1;
err:
OPENSSL_clear_free(buf_in, inll);
return ret;
}
diff --git a/crypto/openssl/crypto/asn1/tasn_fre.c b/crypto/openssl/crypto/asn1/tasn_fre.c
index 13aa6a728e2c..f8068832ab67 100644
--- a/crypto/openssl/crypto/asn1/tasn_fre.c
+++ b/crypto/openssl/crypto/asn1/tasn_fre.c
@@ -1,208 +1,212 @@
/*
- * 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
* https://www.openssl.org/source/license.html
*/
#include <stddef.h>
#include <openssl/asn1.h>
#include <openssl/asn1t.h>
#include <openssl/objects.h>
#include "asn1_local.h"
/* Free up an ASN1 structure */
void ASN1_item_free(ASN1_VALUE *val, const ASN1_ITEM *it)
{
ossl_asn1_item_embed_free(&val, it, 0);
}
void ASN1_item_ex_free(ASN1_VALUE **pval, const ASN1_ITEM *it)
{
ossl_asn1_item_embed_free(pval, it, 0);
}
void ossl_asn1_item_embed_free(ASN1_VALUE **pval, const ASN1_ITEM *it, int embed)
{
const ASN1_TEMPLATE *tt = NULL, *seqtt;
const ASN1_EXTERN_FUNCS *ef;
const ASN1_AUX *aux = it->funcs;
ASN1_aux_cb *asn1_cb;
int i;
if (pval == NULL)
return;
if ((it->itype != ASN1_ITYPE_PRIMITIVE) && *pval == NULL)
return;
if (aux && aux->asn1_cb)
asn1_cb = aux->asn1_cb;
else
asn1_cb = 0;
switch (it->itype) {
case ASN1_ITYPE_PRIMITIVE:
if (it->templates)
ossl_asn1_template_free(pval, it->templates);
else
ossl_asn1_primitive_free(pval, it, embed);
break;
case ASN1_ITYPE_MSTRING:
ossl_asn1_primitive_free(pval, it, embed);
break;
case ASN1_ITYPE_CHOICE:
if (asn1_cb) {
i = asn1_cb(ASN1_OP_FREE_PRE, pval, it, NULL);
if (i == 2)
return;
}
i = ossl_asn1_get_choice_selector(pval, it);
if ((i >= 0) && (i < it->tcount)) {
ASN1_VALUE **pchval;
tt = it->templates + i;
pchval = ossl_asn1_get_field_ptr(pval, tt);
ossl_asn1_template_free(pchval, tt);
}
if (asn1_cb)
asn1_cb(ASN1_OP_FREE_POST, pval, it, NULL);
if (embed == 0) {
OPENSSL_free(*pval);
*pval = NULL;
}
break;
case ASN1_ITYPE_EXTERN:
ef = it->funcs;
if (ef && ef->asn1_ex_free)
ef->asn1_ex_free(pval, it);
break;
case ASN1_ITYPE_NDEF_SEQUENCE:
case ASN1_ITYPE_SEQUENCE:
- if (ossl_asn1_do_lock(pval, -1, it) != 0) /* if error or ref-counter > 0 */
+ if (ossl_asn1_do_lock(pval, -1, it) != 0) {
+ /* if error or ref-counter > 0 */
+ OPENSSL_assert(embed == 0);
+ *pval = NULL;
return;
+ }
if (asn1_cb) {
i = asn1_cb(ASN1_OP_FREE_PRE, pval, it, NULL);
if (i == 2)
return;
}
ossl_asn1_enc_free(pval, it);
/*
* If we free up as normal we will invalidate any ANY DEFINED BY
* field and we won't be able to determine the type of the field it
* defines. So free up in reverse order.
*/
tt = it->templates + it->tcount;
for (i = 0; i < it->tcount; i++) {
ASN1_VALUE **pseqval;
tt--;
seqtt = ossl_asn1_do_adb(*pval, tt, 0);
if (!seqtt)
continue;
pseqval = ossl_asn1_get_field_ptr(pval, seqtt);
ossl_asn1_template_free(pseqval, seqtt);
}
if (asn1_cb)
asn1_cb(ASN1_OP_FREE_POST, pval, it, NULL);
if (embed == 0) {
OPENSSL_free(*pval);
*pval = NULL;
}
break;
}
}
void ossl_asn1_template_free(ASN1_VALUE **pval, const ASN1_TEMPLATE *tt)
{
int embed = tt->flags & ASN1_TFLG_EMBED;
ASN1_VALUE *tval;
if (embed) {
tval = (ASN1_VALUE *)pval;
pval = &tval;
}
if (tt->flags & ASN1_TFLG_SK_MASK) {
STACK_OF(ASN1_VALUE) *sk = (STACK_OF(ASN1_VALUE) *)*pval;
int i;
for (i = 0; i < sk_ASN1_VALUE_num(sk); i++) {
ASN1_VALUE *vtmp = sk_ASN1_VALUE_value(sk, i);
ossl_asn1_item_embed_free(&vtmp, ASN1_ITEM_ptr(tt->item), embed);
}
sk_ASN1_VALUE_free(sk);
*pval = NULL;
} else {
ossl_asn1_item_embed_free(pval, ASN1_ITEM_ptr(tt->item), embed);
}
}
void ossl_asn1_primitive_free(ASN1_VALUE **pval, const ASN1_ITEM *it, int embed)
{
int utype;
/* Special case: if 'it' is a primitive with a free_func, use that. */
if (it) {
const ASN1_PRIMITIVE_FUNCS *pf = it->funcs;
if (embed) {
if (pf && pf->prim_clear) {
pf->prim_clear(pval, it);
return;
}
} else if (pf && pf->prim_free) {
pf->prim_free(pval, it);
return;
}
}
/* Special case: if 'it' is NULL, free contents of ASN1_TYPE */
if (!it) {
ASN1_TYPE *typ = (ASN1_TYPE *)*pval;
utype = typ->type;
pval = &typ->value.asn1_value;
if (*pval == NULL)
return;
} else if (it->itype == ASN1_ITYPE_MSTRING) {
utype = -1;
if (*pval == NULL)
return;
} else {
utype = it->utype;
if ((utype != V_ASN1_BOOLEAN) && *pval == NULL)
return;
}
switch (utype) {
case V_ASN1_OBJECT:
ASN1_OBJECT_free((ASN1_OBJECT *)*pval);
break;
case V_ASN1_BOOLEAN:
if (it)
*(ASN1_BOOLEAN *)pval = it->size;
else
*(ASN1_BOOLEAN *)pval = -1;
return;
case V_ASN1_NULL:
break;
case V_ASN1_ANY:
ossl_asn1_primitive_free(pval, NULL, 0);
OPENSSL_free(*pval);
break;
default:
ossl_asn1_string_embed_free((ASN1_STRING *)*pval, embed);
break;
}
*pval = NULL;
}
diff --git a/crypto/openssl/crypto/bio/bf_readbuff.c b/crypto/openssl/crypto/bio/bf_readbuff.c
index 135ccef83bf3..2409c9db97cc 100644
--- a/crypto/openssl/crypto/bio/bf_readbuff.c
+++ b/crypto/openssl/crypto/bio/bf_readbuff.c
@@ -1,288 +1,291 @@
/*
- * 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
*/
/*
* This is a read only BIO filter that can be used to add BIO_tell() and
* BIO_seek() support to source/sink BIO's (such as a file BIO that uses stdin).
* It does this by caching ALL data read from the BIO source/sink into a
* resizable memory buffer.
*/
#include <stdio.h>
#include <errno.h>
#include "bio_local.h"
#include "internal/cryptlib.h"
#define DEFAULT_BUFFER_SIZE 4096
static int readbuffer_write(BIO *h, const char *buf, int num);
static int readbuffer_read(BIO *h, char *buf, int size);
static int readbuffer_puts(BIO *h, const char *str);
static int readbuffer_gets(BIO *h, char *str, int size);
static long readbuffer_ctrl(BIO *h, int cmd, long arg1, void *arg2);
static int readbuffer_new(BIO *h);
static int readbuffer_free(BIO *data);
static long readbuffer_callback_ctrl(BIO *h, int cmd, BIO_info_cb *fp);
static const BIO_METHOD methods_readbuffer = {
BIO_TYPE_BUFFER,
"readbuffer",
bwrite_conv,
readbuffer_write,
bread_conv,
readbuffer_read,
readbuffer_puts,
readbuffer_gets,
readbuffer_ctrl,
readbuffer_new,
readbuffer_free,
readbuffer_callback_ctrl,
};
const BIO_METHOD *BIO_f_readbuffer(void)
{
return &methods_readbuffer;
}
static int readbuffer_new(BIO *bi)
{
BIO_F_BUFFER_CTX *ctx = OPENSSL_zalloc(sizeof(*ctx));
if (ctx == NULL)
return 0;
ctx->ibuf_size = DEFAULT_BUFFER_SIZE;
ctx->ibuf = OPENSSL_zalloc(DEFAULT_BUFFER_SIZE);
if (ctx->ibuf == NULL) {
OPENSSL_free(ctx);
return 0;
}
bi->init = 1;
bi->ptr = (char *)ctx;
bi->flags = 0;
return 1;
}
static int readbuffer_free(BIO *a)
{
BIO_F_BUFFER_CTX *b;
if (a == NULL)
return 0;
b = (BIO_F_BUFFER_CTX *)a->ptr;
OPENSSL_free(b->ibuf);
OPENSSL_free(a->ptr);
a->ptr = NULL;
a->init = 0;
a->flags = 0;
return 1;
}
static int readbuffer_resize(BIO_F_BUFFER_CTX *ctx, int sz)
{
char *tmp;
/* Figure out how many blocks are required */
sz += (ctx->ibuf_off + DEFAULT_BUFFER_SIZE - 1);
sz = DEFAULT_BUFFER_SIZE * (sz / DEFAULT_BUFFER_SIZE);
/* Resize if the buffer is not big enough */
if (sz > ctx->ibuf_size) {
tmp = OPENSSL_realloc(ctx->ibuf, sz);
if (tmp == NULL)
return 0;
ctx->ibuf = tmp;
ctx->ibuf_size = sz;
}
return 1;
}
static int readbuffer_read(BIO *b, char *out, int outl)
{
int i, num = 0;
BIO_F_BUFFER_CTX *ctx;
if (out == NULL || outl == 0)
return 0;
ctx = (BIO_F_BUFFER_CTX *)b->ptr;
if ((ctx == NULL) || (b->next_bio == NULL))
return 0;
BIO_clear_retry_flags(b);
for (;;) {
i = ctx->ibuf_len;
/* If there is something in the buffer just read it. */
if (i != 0) {
if (i > outl)
i = outl;
memcpy(out, &(ctx->ibuf[ctx->ibuf_off]), i);
ctx->ibuf_off += i;
ctx->ibuf_len -= i;
num += i;
/* Exit if we have read the bytes required out of the buffer */
if (outl == i)
return num;
outl -= i;
out += i;
}
/* Only gets here if the buffer has been consumed */
if (!readbuffer_resize(ctx, outl))
return 0;
/* Do some buffering by reading from the next bio */
i = BIO_read(b->next_bio, ctx->ibuf + ctx->ibuf_off, outl);
if (i <= 0) {
BIO_copy_next_retry(b);
if (i < 0)
return ((num > 0) ? num : i);
else
return num; /* i == 0 */
}
ctx->ibuf_len = i;
}
}
static int readbuffer_write(BIO *b, const char *in, int inl)
{
return 0;
}
static int readbuffer_puts(BIO *b, const char *str)
{
return 0;
}
static long readbuffer_ctrl(BIO *b, int cmd, long num, void *ptr)
{
BIO_F_BUFFER_CTX *ctx;
long ret = 1, sz;
ctx = (BIO_F_BUFFER_CTX *)b->ptr;
switch (cmd) {
case BIO_CTRL_EOF:
if (ctx->ibuf_len > 0)
return 0;
if (b->next_bio == NULL)
return 1;
ret = BIO_ctrl(b->next_bio, cmd, num, ptr);
break;
case BIO_C_FILE_SEEK:
case BIO_CTRL_RESET:
sz = ctx->ibuf_off + ctx->ibuf_len;
/* Assume it can only seek backwards */
if (num < 0 || num > sz)
return 0;
ctx->ibuf_off = num;
ctx->ibuf_len = sz - num;
break;
case BIO_C_FILE_TELL:
case BIO_CTRL_INFO:
ret = (long)ctx->ibuf_off;
break;
case BIO_CTRL_PENDING:
ret = (long)ctx->ibuf_len;
if (ret == 0) {
if (b->next_bio == NULL)
return 0;
ret = BIO_ctrl(b->next_bio, cmd, num, ptr);
}
break;
case BIO_CTRL_DUP:
case BIO_CTRL_FLUSH:
ret = 1;
break;
default:
ret = 0;
break;
}
return ret;
}
static long readbuffer_callback_ctrl(BIO *b, int cmd, BIO_info_cb *fp)
{
if (b->next_bio == NULL)
return 0;
return BIO_callback_ctrl(b->next_bio, cmd, fp);
}
static int readbuffer_gets(BIO *b, char *buf, int size)
{
BIO_F_BUFFER_CTX *ctx;
int num = 0, num_chars, found_newline;
char *p;
int i, j;
- if (size == 0)
+ if (buf == NULL || size == 0)
return 0;
--size; /* the passed in size includes the terminator - so remove it here */
ctx = (BIO_F_BUFFER_CTX *)b->ptr;
+
+ if (ctx == NULL || b->next_bio == NULL)
+ return 0;
BIO_clear_retry_flags(b);
/* If data is already buffered then use this first */
if (ctx->ibuf_len > 0) {
p = ctx->ibuf + ctx->ibuf_off;
found_newline = 0;
for (num_chars = 0;
(num_chars < ctx->ibuf_len) && (num_chars < size);
num_chars++) {
*buf++ = p[num_chars];
if (p[num_chars] == '\n') {
found_newline = 1;
num_chars++;
break;
}
}
num += num_chars;
size -= num_chars;
ctx->ibuf_len -= num_chars;
ctx->ibuf_off += num_chars;
if (found_newline || size == 0) {
*buf = '\0';
return num;
}
}
/*
* If there is no buffered data left then read any remaining data from the
* next bio.
*/
/* Resize if we have to */
if (!readbuffer_resize(ctx, 1 + size))
return 0;
/*
* Read more data from the next bio using BIO_read_ex:
* Note we cannot use BIO_gets() here as it does not work on a
* binary stream that contains 0x00. (Since strlen() will stop at
* any 0x00 not at the last read '\n' in a FILE bio).
* Also note that some applications open and close the file bio
* multiple times and need to read the next available block when using
* stdin - so we need to READ one byte at a time!
*/
p = ctx->ibuf + ctx->ibuf_off;
for (i = 0; i < size; ++i) {
j = BIO_read(b->next_bio, p, 1);
if (j <= 0) {
BIO_copy_next_retry(b);
*buf = '\0';
return num > 0 ? num : j;
}
*buf++ = *p;
num++;
ctx->ibuf_off++;
if (*p == '\n')
break;
++p;
}
*buf = '\0';
return num;
}
diff --git a/crypto/openssl/crypto/bio/bio_addr.c b/crypto/openssl/crypto/bio/bio_addr.c
index a80774bbd7ca..04d62f45b198 100644
--- a/crypto/openssl/crypto/bio/bio_addr.c
+++ b/crypto/openssl/crypto/bio/bio_addr.c
@@ -1,939 +1,937 @@
/*
- * 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
*/
#ifndef _GNU_SOURCE
# define _GNU_SOURCE
#endif
/*
* VC configurations may define UNICODE, to indicate to the C RTL that
* WCHAR functions are preferred.
* This affects functions like gai_strerror(), which is implemented as
* an alias macro for gai_strerrorA() (which returns a const char *) or
* gai_strerrorW() (which returns a const WCHAR *). This source file
* assumes POSIX declarations, so prefer the non-UNICODE definitions.
*/
#undef UNICODE
#include <assert.h>
#include <string.h>
#include "bio_local.h"
#include <openssl/crypto.h>
#ifndef OPENSSL_NO_SOCK
#include <openssl/err.h>
#include <openssl/buffer.h>
#include "internal/thread_once.h"
CRYPTO_RWLOCK *bio_lookup_lock;
static CRYPTO_ONCE bio_lookup_init = CRYPTO_ONCE_STATIC_INIT;
/*
* Throughout this file and bio_local.h, the existence of the macro
* AI_PASSIVE is used to detect the availability of struct addrinfo,
* getnameinfo() and getaddrinfo(). If that macro doesn't exist,
* we use our own implementation instead, using gethostbyname,
* getservbyname and a few other.
*/
/**********************************************************************
*
* Address structure
*
*/
BIO_ADDR *BIO_ADDR_new(void)
{
BIO_ADDR *ret = OPENSSL_zalloc(sizeof(*ret));
if (ret == NULL) {
ERR_raise(ERR_LIB_BIO, ERR_R_MALLOC_FAILURE);
return NULL;
}
ret->sa.sa_family = AF_UNSPEC;
return ret;
}
void BIO_ADDR_free(BIO_ADDR *ap)
{
OPENSSL_free(ap);
}
void BIO_ADDR_clear(BIO_ADDR *ap)
{
memset(ap, 0, sizeof(*ap));
ap->sa.sa_family = AF_UNSPEC;
}
/*
* BIO_ADDR_make - non-public routine to fill a BIO_ADDR with the contents
* of a struct sockaddr.
*/
int BIO_ADDR_make(BIO_ADDR *ap, const struct sockaddr *sa)
{
if (sa->sa_family == AF_INET) {
memcpy(&(ap->s_in), sa, sizeof(struct sockaddr_in));
return 1;
}
#ifdef AF_INET6
if (sa->sa_family == AF_INET6) {
memcpy(&(ap->s_in6), sa, sizeof(struct sockaddr_in6));
return 1;
}
#endif
#ifdef AF_UNIX
if (sa->sa_family == AF_UNIX) {
memcpy(&(ap->s_un), sa, sizeof(struct sockaddr_un));
return 1;
}
#endif
return 0;
}
int BIO_ADDR_rawmake(BIO_ADDR *ap, int family,
const void *where, size_t wherelen,
unsigned short port)
{
#ifdef AF_UNIX
if (family == AF_UNIX) {
if (wherelen + 1 > sizeof(ap->s_un.sun_path))
return 0;
memset(&ap->s_un, 0, sizeof(ap->s_un));
ap->s_un.sun_family = family;
strncpy(ap->s_un.sun_path, where, sizeof(ap->s_un.sun_path) - 1);
return 1;
}
#endif
if (family == AF_INET) {
if (wherelen != sizeof(struct in_addr))
return 0;
memset(&ap->s_in, 0, sizeof(ap->s_in));
ap->s_in.sin_family = family;
ap->s_in.sin_port = port;
ap->s_in.sin_addr = *(struct in_addr *)where;
return 1;
}
#ifdef AF_INET6
if (family == AF_INET6) {
if (wherelen != sizeof(struct in6_addr))
return 0;
memset(&ap->s_in6, 0, sizeof(ap->s_in6));
ap->s_in6.sin6_family = family;
ap->s_in6.sin6_port = port;
ap->s_in6.sin6_addr = *(struct in6_addr *)where;
return 1;
}
#endif
return 0;
}
int BIO_ADDR_family(const BIO_ADDR *ap)
{
return ap->sa.sa_family;
}
int BIO_ADDR_rawaddress(const BIO_ADDR *ap, void *p, size_t *l)
{
size_t len = 0;
const void *addrptr = NULL;
if (ap->sa.sa_family == AF_INET) {
len = sizeof(ap->s_in.sin_addr);
addrptr = &ap->s_in.sin_addr;
}
#ifdef AF_INET6
else if (ap->sa.sa_family == AF_INET6) {
len = sizeof(ap->s_in6.sin6_addr);
addrptr = &ap->s_in6.sin6_addr;
}
#endif
#ifdef AF_UNIX
else if (ap->sa.sa_family == AF_UNIX) {
len = strlen(ap->s_un.sun_path);
addrptr = &ap->s_un.sun_path;
}
#endif
if (addrptr == NULL)
return 0;
if (p != NULL) {
memcpy(p, addrptr, len);
}
if (l != NULL)
*l = len;
return 1;
}
unsigned short BIO_ADDR_rawport(const BIO_ADDR *ap)
{
if (ap->sa.sa_family == AF_INET)
return ap->s_in.sin_port;
#ifdef AF_INET6
if (ap->sa.sa_family == AF_INET6)
return ap->s_in6.sin6_port;
#endif
return 0;
}
/*-
* addr_strings - helper function to get host and service names
* @ap: the BIO_ADDR that has the input info
* @numeric: 0 if actual names should be returned, 1 if the numeric
* representation should be returned.
* @hostname: a pointer to a pointer to a memory area to store the
* host name or numeric representation. Unused if NULL.
* @service: a pointer to a pointer to a memory area to store the
* service name or numeric representation. Unused if NULL.
*
* The return value is 0 on failure, with the error code in the error
* stack, and 1 on success.
*/
static int addr_strings(const BIO_ADDR *ap, int numeric,
char **hostname, char **service)
{
if (BIO_sock_init() != 1)
return 0;
if (1) {
#ifdef AI_PASSIVE
int ret = 0;
char host[NI_MAXHOST] = "", serv[NI_MAXSERV] = "";
int flags = 0;
if (numeric)
flags |= NI_NUMERICHOST | NI_NUMERICSERV;
if ((ret = getnameinfo(BIO_ADDR_sockaddr(ap),
BIO_ADDR_sockaddr_size(ap),
host, sizeof(host), serv, sizeof(serv),
flags)) != 0) {
# ifdef EAI_SYSTEM
if (ret == EAI_SYSTEM) {
ERR_raise_data(ERR_LIB_SYS, get_last_socket_error(),
"calling getnameinfo()");
} else
# endif
{
ERR_raise_data(ERR_LIB_BIO, ERR_R_SYS_LIB, gai_strerror(ret));
}
return 0;
}
/* VMS getnameinfo() has a bug, it doesn't fill in serv, which
* leaves it with whatever garbage that happens to be there.
* However, we initialise serv with the empty string (serv[0]
* is therefore NUL), so it gets real easy to detect when things
* didn't go the way one might expect.
*/
if (serv[0] == '\0') {
BIO_snprintf(serv, sizeof(serv), "%d",
ntohs(BIO_ADDR_rawport(ap)));
}
if (hostname != NULL)
*hostname = OPENSSL_strdup(host);
if (service != NULL)
*service = OPENSSL_strdup(serv);
} else {
#endif
if (hostname != NULL)
*hostname = OPENSSL_strdup(inet_ntoa(ap->s_in.sin_addr));
if (service != NULL) {
char serv[6]; /* port is 16 bits => max 5 decimal digits */
BIO_snprintf(serv, sizeof(serv), "%d", ntohs(ap->s_in.sin_port));
*service = OPENSSL_strdup(serv);
}
}
if ((hostname != NULL && *hostname == NULL)
|| (service != NULL && *service == NULL)) {
if (hostname != NULL) {
OPENSSL_free(*hostname);
*hostname = NULL;
}
if (service != NULL) {
OPENSSL_free(*service);
*service = NULL;
}
ERR_raise(ERR_LIB_BIO, ERR_R_MALLOC_FAILURE);
return 0;
}
return 1;
}
char *BIO_ADDR_hostname_string(const BIO_ADDR *ap, int numeric)
{
char *hostname = NULL;
if (addr_strings(ap, numeric, &hostname, NULL))
return hostname;
return NULL;
}
char *BIO_ADDR_service_string(const BIO_ADDR *ap, int numeric)
{
char *service = NULL;
if (addr_strings(ap, numeric, NULL, &service))
return service;
return NULL;
}
char *BIO_ADDR_path_string(const BIO_ADDR *ap)
{
#ifdef AF_UNIX
if (ap->sa.sa_family == AF_UNIX)
return OPENSSL_strdup(ap->s_un.sun_path);
#endif
return NULL;
}
/*
* BIO_ADDR_sockaddr - non-public routine to return the struct sockaddr
* for a given BIO_ADDR. In reality, this is simply a type safe cast.
* The returned struct sockaddr is const, so it can't be tampered with.
*/
const struct sockaddr *BIO_ADDR_sockaddr(const BIO_ADDR *ap)
{
return &(ap->sa);
}
/*
* BIO_ADDR_sockaddr_noconst - non-public function that does the same
* as BIO_ADDR_sockaddr, but returns a non-const. USE WITH CARE, as
* it allows you to tamper with the data (and thereby the contents
* of the input BIO_ADDR).
*/
struct sockaddr *BIO_ADDR_sockaddr_noconst(BIO_ADDR *ap)
{
return &(ap->sa);
}
/*
* BIO_ADDR_sockaddr_size - non-public function that returns the size
* of the struct sockaddr the BIO_ADDR is using. If the protocol family
* isn't set or is something other than AF_INET, AF_INET6 or AF_UNIX,
* the size of the BIO_ADDR type is returned.
*/
socklen_t BIO_ADDR_sockaddr_size(const BIO_ADDR *ap)
{
if (ap->sa.sa_family == AF_INET)
return sizeof(ap->s_in);
#ifdef AF_INET6
if (ap->sa.sa_family == AF_INET6)
return sizeof(ap->s_in6);
#endif
#ifdef AF_UNIX
if (ap->sa.sa_family == AF_UNIX)
return sizeof(ap->s_un);
#endif
return sizeof(*ap);
}
/**********************************************************************
*
* Address info database
*
*/
const BIO_ADDRINFO *BIO_ADDRINFO_next(const BIO_ADDRINFO *bai)
{
if (bai != NULL)
return bai->bai_next;
return NULL;
}
int BIO_ADDRINFO_family(const BIO_ADDRINFO *bai)
{
if (bai != NULL)
return bai->bai_family;
return 0;
}
int BIO_ADDRINFO_socktype(const BIO_ADDRINFO *bai)
{
if (bai != NULL)
return bai->bai_socktype;
return 0;
}
int BIO_ADDRINFO_protocol(const BIO_ADDRINFO *bai)
{
if (bai != NULL) {
if (bai->bai_protocol != 0)
return bai->bai_protocol;
#ifdef AF_UNIX
if (bai->bai_family == AF_UNIX)
return 0;
#endif
switch (bai->bai_socktype) {
case SOCK_STREAM:
return IPPROTO_TCP;
case SOCK_DGRAM:
return IPPROTO_UDP;
default:
break;
}
}
return 0;
}
/*
* BIO_ADDRINFO_sockaddr_size - non-public function that returns the size
* of the struct sockaddr inside the BIO_ADDRINFO.
*/
socklen_t BIO_ADDRINFO_sockaddr_size(const BIO_ADDRINFO *bai)
{
if (bai != NULL)
return bai->bai_addrlen;
return 0;
}
/*
* BIO_ADDRINFO_sockaddr - non-public function that returns bai_addr
* as the struct sockaddr it is.
*/
const struct sockaddr *BIO_ADDRINFO_sockaddr(const BIO_ADDRINFO *bai)
{
if (bai != NULL)
return bai->bai_addr;
return NULL;
}
const BIO_ADDR *BIO_ADDRINFO_address(const BIO_ADDRINFO *bai)
{
if (bai != NULL)
return (BIO_ADDR *)bai->bai_addr;
return NULL;
}
void BIO_ADDRINFO_free(BIO_ADDRINFO *bai)
{
if (bai == NULL)
return;
#ifdef AI_PASSIVE
# ifdef AF_UNIX
# define _cond bai->bai_family != AF_UNIX
# else
# define _cond 1
# endif
if (_cond) {
freeaddrinfo(bai);
return;
}
#endif
/* Free manually when we know that addrinfo_wrap() was used.
* See further comment above addrinfo_wrap()
*/
while (bai != NULL) {
BIO_ADDRINFO *next = bai->bai_next;
OPENSSL_free(bai->bai_addr);
OPENSSL_free(bai);
bai = next;
}
}
/**********************************************************************
*
* Service functions
*
*/
/*-
* The specs in hostserv can take these forms:
*
* host:service => *host = "host", *service = "service"
* host:* => *host = "host", *service = NULL
* host: => *host = "host", *service = NULL
* :service => *host = NULL, *service = "service"
* *:service => *host = NULL, *service = "service"
*
* in case no : is present in the string, the result depends on
* hostserv_prio, as follows:
*
* when hostserv_prio == BIO_PARSE_PRIO_HOST
* host => *host = "host", *service untouched
*
* when hostserv_prio == BIO_PARSE_PRIO_SERV
* service => *host untouched, *service = "service"
*
*/
int BIO_parse_hostserv(const char *hostserv, char **host, char **service,
enum BIO_hostserv_priorities hostserv_prio)
{
const char *h = NULL; size_t hl = 0;
const char *p = NULL; size_t pl = 0;
if (*hostserv == '[') {
if ((p = strchr(hostserv, ']')) == NULL)
goto spec_err;
h = hostserv + 1;
hl = p - h;
p++;
if (*p == '\0')
p = NULL;
else if (*p != ':')
goto spec_err;
else {
p++;
pl = strlen(p);
}
} else {
const char *p2 = strrchr(hostserv, ':');
p = strchr(hostserv, ':');
/*-
* Check for more than one colon. There are three possible
* interpretations:
* 1. IPv6 address with port number, last colon being separator.
* 2. IPv6 address only.
* 3. IPv6 address only if hostserv_prio == BIO_PARSE_PRIO_HOST,
* IPv6 address and port number if hostserv_prio == BIO_PARSE_PRIO_SERV
* Because of this ambiguity, we currently choose to make it an
* error.
*/
if (p != p2)
goto amb_err;
if (p != NULL) {
h = hostserv;
hl = p - h;
p++;
pl = strlen(p);
} else if (hostserv_prio == BIO_PARSE_PRIO_HOST) {
h = hostserv;
hl = strlen(h);
} else {
p = hostserv;
pl = strlen(p);
}
}
if (p != NULL && strchr(p, ':'))
goto spec_err;
if (h != NULL && host != NULL) {
if (hl == 0
|| (hl == 1 && h[0] == '*')) {
*host = NULL;
} else {
*host = OPENSSL_strndup(h, hl);
if (*host == NULL)
goto memerr;
}
}
if (p != NULL && service != NULL) {
if (pl == 0
|| (pl == 1 && p[0] == '*')) {
*service = NULL;
} else {
*service = OPENSSL_strndup(p, pl);
if (*service == NULL)
goto memerr;
}
}
return 1;
amb_err:
ERR_raise(ERR_LIB_BIO, BIO_R_AMBIGUOUS_HOST_OR_SERVICE);
return 0;
spec_err:
ERR_raise(ERR_LIB_BIO, BIO_R_MALFORMED_HOST_OR_SERVICE);
return 0;
memerr:
ERR_raise(ERR_LIB_BIO, ERR_R_MALLOC_FAILURE);
return 0;
}
/* addrinfo_wrap is used to build our own addrinfo "chain".
* (it has only one entry, so calling it a chain may be a stretch)
* It should ONLY be called when getaddrinfo() and friends
* aren't available, OR when dealing with a non IP protocol
* family, such as AF_UNIX
*
* the return value is 1 on success, or 0 on failure, which
* only happens if a memory allocation error occurred.
*/
static int addrinfo_wrap(int family, int socktype,
const void *where, size_t wherelen,
unsigned short port,
BIO_ADDRINFO **bai)
{
if ((*bai = OPENSSL_zalloc(sizeof(**bai))) == NULL) {
ERR_raise(ERR_LIB_BIO, ERR_R_MALLOC_FAILURE);
return 0;
}
(*bai)->bai_family = family;
(*bai)->bai_socktype = socktype;
if (socktype == SOCK_STREAM)
(*bai)->bai_protocol = IPPROTO_TCP;
if (socktype == SOCK_DGRAM)
(*bai)->bai_protocol = IPPROTO_UDP;
#ifdef AF_UNIX
if (family == AF_UNIX)
(*bai)->bai_protocol = 0;
#endif
{
/* Magic: We know that BIO_ADDR_sockaddr_noconst is really
just an advanced cast of BIO_ADDR* to struct sockaddr *
by the power of union, so while it may seem that we're
creating a memory leak here, we are not. It will be
all right. */
BIO_ADDR *addr = BIO_ADDR_new();
if (addr != NULL) {
BIO_ADDR_rawmake(addr, family, where, wherelen, port);
(*bai)->bai_addr = BIO_ADDR_sockaddr_noconst(addr);
}
}
(*bai)->bai_next = NULL;
if ((*bai)->bai_addr == NULL) {
BIO_ADDRINFO_free(*bai);
*bai = NULL;
return 0;
}
return 1;
}
DEFINE_RUN_ONCE_STATIC(do_bio_lookup_init)
{
bio_lookup_lock = CRYPTO_THREAD_lock_new();
return bio_lookup_lock != NULL;
}
int BIO_lookup(const char *host, const char *service,
enum BIO_lookup_type lookup_type,
int family, int socktype, BIO_ADDRINFO **res)
{
return BIO_lookup_ex(host, service, lookup_type, family, socktype, 0, res);
}
/*-
* BIO_lookup_ex - look up the host and service you want to connect to.
* @host: the host (or node, in case family == AF_UNIX) you want to connect to.
* @service: the service you want to connect to.
* @lookup_type: declare intent with the result, client or server.
* @family: the address family you want to use. Use AF_UNSPEC for any, or
* AF_INET, AF_INET6 or AF_UNIX.
* @socktype: The socket type you want to use. Can be SOCK_STREAM, SOCK_DGRAM
* or 0 for all.
* @protocol: The protocol to use, e.g. IPPROTO_TCP or IPPROTO_UDP or 0 for all.
* Note that some platforms may not return IPPROTO_SCTP without
* explicitly requesting it (i.e. IPPROTO_SCTP may not be returned
* with 0 for the protocol)
* @res: Storage place for the resulting list of returned addresses
*
* This will do a lookup of the host and service that you want to connect to.
* It returns a linked list of different addresses you can try to connect to.
*
* When no longer needed you should call BIO_ADDRINFO_free() to free the result.
*
* The return value is 1 on success or 0 in case of error.
*/
int BIO_lookup_ex(const char *host, const char *service, int lookup_type,
int family, int socktype, int protocol, BIO_ADDRINFO **res)
{
int ret = 0; /* Assume failure */
switch(family) {
case AF_INET:
#ifdef AF_INET6
case AF_INET6:
#endif
#ifdef AF_UNIX
case AF_UNIX:
#endif
#ifdef AF_UNSPEC
case AF_UNSPEC:
#endif
break;
default:
ERR_raise(ERR_LIB_BIO, BIO_R_UNSUPPORTED_PROTOCOL_FAMILY);
return 0;
}
#ifdef AF_UNIX
if (family == AF_UNIX) {
if (addrinfo_wrap(family, socktype, host, strlen(host), 0, res))
return 1;
else
ERR_raise(ERR_LIB_BIO, ERR_R_MALLOC_FAILURE);
return 0;
}
#endif
if (BIO_sock_init() != 1)
return 0;
if (1) {
#ifdef AI_PASSIVE
int gai_ret = 0, old_ret = 0;
struct addrinfo hints;
memset(&hints, 0, sizeof(hints));
hints.ai_family = family;
hints.ai_socktype = socktype;
hints.ai_protocol = protocol;
# ifdef AI_ADDRCONFIG
# ifdef AF_UNSPEC
if (host != NULL && family == AF_UNSPEC)
# endif
hints.ai_flags |= AI_ADDRCONFIG;
# endif
if (lookup_type == BIO_LOOKUP_SERVER)
hints.ai_flags |= AI_PASSIVE;
/* Note that |res| SHOULD be a 'struct addrinfo **' thanks to
* macro magic in bio_local.h
*/
# if defined(AI_ADDRCONFIG) && defined(AI_NUMERICHOST)
retry:
# endif
switch ((gai_ret = getaddrinfo(host, service, &hints, res))) {
# ifdef EAI_SYSTEM
case EAI_SYSTEM:
ERR_raise_data(ERR_LIB_SYS, get_last_socket_error(),
"calling getaddrinfo()");
ERR_raise(ERR_LIB_BIO, ERR_R_SYS_LIB);
break;
# endif
# ifdef EAI_MEMORY
case EAI_MEMORY:
ERR_raise(ERR_LIB_BIO, ERR_R_MALLOC_FAILURE);
break;
# endif
case 0:
ret = 1; /* Success */
break;
default:
# if defined(AI_ADDRCONFIG) && defined(AI_NUMERICHOST)
if (hints.ai_flags & AI_ADDRCONFIG) {
hints.ai_flags &= ~AI_ADDRCONFIG;
hints.ai_flags |= AI_NUMERICHOST;
old_ret = gai_ret;
goto retry;
}
# endif
ERR_raise_data(ERR_LIB_BIO, ERR_R_SYS_LIB,
gai_strerror(old_ret ? old_ret : gai_ret));
break;
}
} else {
#endif
const struct hostent *he;
/*
* Because struct hostent is defined for 32-bit pointers only with
* VMS C, we need to make sure that '&he_fallback_address' and
* '&he_fallback_addresses' are 32-bit pointers
*/
#if defined(OPENSSL_SYS_VMS) && defined(__DECC)
# pragma pointer_size save
# pragma pointer_size 32
#endif
/* Windows doesn't seem to have in_addr_t */
#if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS)
static uint32_t he_fallback_address;
static const char *he_fallback_addresses[] =
{ (char *)&he_fallback_address, NULL };
#else
static in_addr_t he_fallback_address;
static const char *he_fallback_addresses[] =
{ (char *)&he_fallback_address, NULL };
#endif
static const struct hostent he_fallback =
{ NULL, NULL, AF_INET, sizeof(he_fallback_address),
(char **)&he_fallback_addresses };
#if defined(OPENSSL_SYS_VMS) && defined(__DECC)
# pragma pointer_size restore
#endif
struct servent *se;
/* Apparently, on WIN64, s_proto and s_port have traded places... */
#ifdef _WIN64
struct servent se_fallback = { NULL, NULL, NULL, 0 };
#else
struct servent se_fallback = { NULL, NULL, 0, NULL };
#endif
if (!RUN_ONCE(&bio_lookup_init, do_bio_lookup_init)) {
ERR_raise(ERR_LIB_BIO, ERR_R_MALLOC_FAILURE);
- ret = 0;
- goto err;
+ return 0;
}
- if (!CRYPTO_THREAD_write_lock(bio_lookup_lock)) {
- ret = 0;
- goto err;
- }
+ if (!CRYPTO_THREAD_write_lock(bio_lookup_lock))
+ return 0;
+
he_fallback_address = INADDR_ANY;
if (host == NULL) {
he = &he_fallback;
switch(lookup_type) {
case BIO_LOOKUP_CLIENT:
he_fallback_address = INADDR_LOOPBACK;
break;
case BIO_LOOKUP_SERVER:
he_fallback_address = INADDR_ANY;
break;
default:
/* We forgot to handle a lookup type! */
assert("We forgot to handle a lookup type!" == NULL);
ERR_raise(ERR_LIB_BIO, ERR_R_INTERNAL_ERROR);
ret = 0;
goto err;
}
} else {
he = gethostbyname(host);
if (he == NULL) {
#ifndef OPENSSL_SYS_WINDOWS
/*
* This might be misleading, because h_errno is used as if
* it was errno. To minimize mixup add 1000. Underlying
* reason for this is that hstrerror is declared obsolete,
* not to mention that a) h_errno is not always guaranteed
* to be meaningless; b) hstrerror can reside in yet another
* library, linking for sake of hstrerror is an overkill;
* c) this path is not executed on contemporary systems
* anyway [above getaddrinfo/gai_strerror is]. We just let
* system administrator figure this out...
*/
# if defined(OPENSSL_SYS_VXWORKS)
/* h_errno doesn't exist on VxWorks */
ERR_raise_data(ERR_LIB_SYS, 1000,
"calling gethostbyname()");
# else
ERR_raise_data(ERR_LIB_SYS, 1000 + h_errno,
"calling gethostbyname()");
# endif
#else
ERR_raise_data(ERR_LIB_SYS, get_last_socket_error(),
"calling gethostbyname()");
#endif
ret = 0;
goto err;
}
}
if (service == NULL) {
se_fallback.s_port = 0;
se_fallback.s_proto = NULL;
se = &se_fallback;
} else {
char *endp = NULL;
long portnum = strtol(service, &endp, 10);
/*
* Because struct servent is defined for 32-bit pointers only with
* VMS C, we need to make sure that 'proto' is a 32-bit pointer.
*/
#if defined(OPENSSL_SYS_VMS) && defined(__DECC)
# pragma pointer_size save
# pragma pointer_size 32
#endif
char *proto = NULL;
#if defined(OPENSSL_SYS_VMS) && defined(__DECC)
# pragma pointer_size restore
#endif
switch (socktype) {
case SOCK_STREAM:
proto = "tcp";
break;
case SOCK_DGRAM:
proto = "udp";
break;
}
if (endp != service && *endp == '\0'
&& portnum > 0 && portnum < 65536) {
se_fallback.s_port = htons((unsigned short)portnum);
se_fallback.s_proto = proto;
se = &se_fallback;
} else if (endp == service) {
se = getservbyname(service, proto);
if (se == NULL) {
ERR_raise_data(ERR_LIB_SYS, get_last_socket_error(),
"calling getservbyname()");
goto err;
}
} else {
ERR_raise(ERR_LIB_BIO, BIO_R_MALFORMED_HOST_OR_SERVICE);
goto err;
}
}
*res = NULL;
{
/*
* Because hostent::h_addr_list is an array of 32-bit pointers with VMS C,
* we must make sure our iterator designates the same element type, hence
* the pointer size dance.
*/
#if defined(OPENSSL_SYS_VMS) && defined(__DECC)
# pragma pointer_size save
# pragma pointer_size 32
#endif
char **addrlistp;
#if defined(OPENSSL_SYS_VMS) && defined(__DECC)
# pragma pointer_size restore
#endif
size_t addresses;
BIO_ADDRINFO *tmp_bai = NULL;
/* The easiest way to create a linked list from an
array is to start from the back */
for(addrlistp = he->h_addr_list; *addrlistp != NULL;
addrlistp++)
;
for(addresses = addrlistp - he->h_addr_list;
addrlistp--, addresses-- > 0; ) {
if (!addrinfo_wrap(he->h_addrtype, socktype,
*addrlistp, he->h_length,
se->s_port, &tmp_bai))
goto addrinfo_malloc_err;
tmp_bai->bai_next = *res;
*res = tmp_bai;
continue;
addrinfo_malloc_err:
BIO_ADDRINFO_free(*res);
*res = NULL;
ERR_raise(ERR_LIB_BIO, ERR_R_MALLOC_FAILURE);
ret = 0;
goto err;
}
ret = 1;
}
err:
CRYPTO_THREAD_unlock(bio_lookup_lock);
}
return ret;
}
#endif /* OPENSSL_NO_SOCK */
diff --git a/crypto/openssl/crypto/cmp/cmp_vfy.c b/crypto/openssl/crypto/cmp/cmp_vfy.c
index 7ce91ec5d167..b9951045c2e8 100644
--- a/crypto/openssl/crypto/cmp/cmp_vfy.c
+++ b/crypto/openssl/crypto/cmp/cmp_vfy.c
@@ -1,855 +1,855 @@
/*
- * Copyright 2007-2023 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2007-2024 The OpenSSL Project Authors. All Rights Reserved.
* Copyright Nokia 2007-2020
* Copyright Siemens AG 2015-2020
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
/* CMP functions for PKIMessage checking */
#include "cmp_local.h"
#include <openssl/cmp_util.h>
/* explicit #includes not strictly needed since implied by the above: */
#include <openssl/asn1t.h>
#include <openssl/cmp.h>
#include <openssl/crmf.h>
#include <openssl/err.h>
#include <openssl/x509.h>
/* Verify a message protected by signature according to RFC section 5.1.3.3 */
static int verify_signature(const OSSL_CMP_CTX *cmp_ctx,
const OSSL_CMP_MSG *msg, X509 *cert)
{
OSSL_CMP_PROTECTEDPART prot_part;
EVP_PKEY *pubkey = NULL;
BIO *bio;
int res = 0;
if (!ossl_assert(cmp_ctx != NULL && msg != NULL && cert != NULL))
return 0;
bio = BIO_new(BIO_s_mem()); /* may be NULL */
/* verify that keyUsage, if present, contains digitalSignature */
if (!cmp_ctx->ignore_keyusage
&& (X509_get_key_usage(cert) & X509v3_KU_DIGITAL_SIGNATURE) == 0) {
ERR_raise(ERR_LIB_CMP, CMP_R_MISSING_KEY_USAGE_DIGITALSIGNATURE);
goto sig_err;
}
pubkey = X509_get_pubkey(cert);
if (pubkey == NULL) {
ERR_raise(ERR_LIB_CMP, CMP_R_FAILED_EXTRACTING_PUBKEY);
goto sig_err;
}
prot_part.header = msg->header;
prot_part.body = msg->body;
if (ASN1_item_verify_ex(ASN1_ITEM_rptr(OSSL_CMP_PROTECTEDPART),
msg->header->protectionAlg, msg->protection,
&prot_part, NULL, pubkey, cmp_ctx->libctx,
cmp_ctx->propq) > 0) {
res = 1;
goto end;
}
sig_err:
res = ossl_x509_print_ex_brief(bio, cert, X509_FLAG_NO_EXTENSIONS);
ERR_raise(ERR_LIB_CMP, CMP_R_ERROR_VALIDATING_SIGNATURE);
if (res)
ERR_add_error_mem_bio("\n", bio);
res = 0;
end:
EVP_PKEY_free(pubkey);
BIO_free(bio);
return res;
}
/* Verify a message protected with PBMAC */
static int verify_PBMAC(OSSL_CMP_CTX *ctx, const OSSL_CMP_MSG *msg)
{
ASN1_BIT_STRING *protection = NULL;
int valid = 0;
/* generate expected protection for the message */
if ((protection = ossl_cmp_calc_protection(ctx, msg)) == NULL)
return 0; /* failed to generate protection string! */
valid = msg->protection != NULL && msg->protection->length >= 0
&& msg->protection->type == protection->type
&& msg->protection->length == protection->length
&& CRYPTO_memcmp(msg->protection->data, protection->data,
protection->length) == 0;
ASN1_BIT_STRING_free(protection);
if (!valid)
ERR_raise(ERR_LIB_CMP, CMP_R_WRONG_PBM_VALUE);
return valid;
}
/*-
* Attempt to validate certificate and path using any given store with trusted
* certs (possibly including CRLs and a cert verification callback function)
* and non-trusted intermediate certs from the given ctx.
*
* Returns 1 on successful validation and 0 otherwise.
*/
int OSSL_CMP_validate_cert_path(const OSSL_CMP_CTX *ctx,
X509_STORE *trusted_store, X509 *cert)
{
int valid = 0;
X509_STORE_CTX *csc = NULL;
int err;
if (ctx == NULL || cert == NULL) {
ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT);
return 0;
}
if (trusted_store == NULL) {
ERR_raise(ERR_LIB_CMP, CMP_R_MISSING_TRUST_STORE);
return 0;
}
if ((csc = X509_STORE_CTX_new_ex(ctx->libctx, ctx->propq)) == NULL
|| !X509_STORE_CTX_init(csc, trusted_store,
cert, ctx->untrusted))
goto err;
valid = X509_verify_cert(csc) > 0;
/* make sure suitable error is queued even if callback did not do */
err = ERR_peek_last_error();
if (!valid && ERR_GET_REASON(err) != CMP_R_POTENTIALLY_INVALID_CERTIFICATE)
ERR_raise(ERR_LIB_CMP, CMP_R_POTENTIALLY_INVALID_CERTIFICATE);
err:
/* directly output any fresh errors, needed for check_msg_find_cert() */
OSSL_CMP_CTX_print_errors(ctx);
X509_STORE_CTX_free(csc);
return valid;
}
/* Return 0 if expect_name != NULL and there is no matching actual_name */
static int check_name(const OSSL_CMP_CTX *ctx, int log_success,
const char *actual_desc, const X509_NAME *actual_name,
const char *expect_desc, const X509_NAME *expect_name)
{
char *str;
if (expect_name == NULL)
return 1; /* no expectation, thus trivially fulfilled */
/* make sure that a matching name is there */
if (actual_name == NULL) {
ossl_cmp_log1(WARN, ctx, "missing %s", actual_desc);
return 0;
}
str = X509_NAME_oneline(actual_name, NULL, 0);
if (X509_NAME_cmp(actual_name, expect_name) == 0) {
if (log_success && str != NULL)
ossl_cmp_log2(INFO, ctx, " subject matches %s: %s", expect_desc,
str);
OPENSSL_free(str);
return 1;
}
if (str != NULL)
ossl_cmp_log2(INFO, ctx, " actual name in %s = %s", actual_desc, str);
OPENSSL_free(str);
if ((str = X509_NAME_oneline(expect_name, NULL, 0)) != NULL)
ossl_cmp_log2(INFO, ctx, " does not match %s = %s", expect_desc, str);
OPENSSL_free(str);
return 0;
}
/* Return 0 if skid != NULL and there is no matching subject key ID in cert */
static int check_kid(const OSSL_CMP_CTX *ctx,
const ASN1_OCTET_STRING *ckid,
const ASN1_OCTET_STRING *skid)
{
char *str;
if (skid == NULL)
return 1; /* no expectation, thus trivially fulfilled */
/* make sure that the expected subject key identifier is there */
if (ckid == NULL) {
ossl_cmp_warn(ctx, "missing Subject Key Identifier in certificate");
return 0;
}
str = OPENSSL_buf2hexstr(ckid->data, ckid->length);
if (ASN1_OCTET_STRING_cmp(ckid, skid) == 0) {
if (str != NULL)
ossl_cmp_log1(INFO, ctx, " subjectKID matches senderKID: %s", str);
OPENSSL_free(str);
return 1;
}
if (str != NULL)
ossl_cmp_log1(INFO, ctx, " cert Subject Key Identifier = %s", str);
OPENSSL_free(str);
if ((str = OPENSSL_buf2hexstr(skid->data, skid->length)) != NULL)
ossl_cmp_log1(INFO, ctx, " does not match senderKID = %s", str);
OPENSSL_free(str);
return 0;
}
static int already_checked(const X509 *cert,
const STACK_OF(X509) *already_checked)
{
int i;
for (i = sk_X509_num(already_checked /* may be NULL */); i > 0; i--)
if (X509_cmp(sk_X509_value(already_checked, i - 1), cert) == 0)
return 1;
return 0;
}
/*-
* Check if the given cert is acceptable as sender cert of the given message.
* The subject DN must match, the subject key ID as well if present in the msg,
* and the cert must be current (checked if ctx->trusted is not NULL).
* Note that cert revocation etc. is checked by OSSL_CMP_validate_cert_path().
*
* Returns 0 on error or not acceptable, else 1.
*/
static int cert_acceptable(const OSSL_CMP_CTX *ctx,
const char *desc1, const char *desc2, X509 *cert,
const STACK_OF(X509) *already_checked1,
const STACK_OF(X509) *already_checked2,
const OSSL_CMP_MSG *msg)
{
X509_STORE *ts = ctx->trusted;
int self_issued = X509_check_issued(cert, cert) == X509_V_OK;
char *str;
X509_VERIFY_PARAM *vpm = ts != NULL ? X509_STORE_get0_param(ts) : NULL;
int time_cmp;
ossl_cmp_log3(INFO, ctx, " considering %s%s %s with..",
self_issued ? "self-issued ": "", desc1, desc2);
if ((str = X509_NAME_oneline(X509_get_subject_name(cert), NULL, 0)) != NULL)
ossl_cmp_log1(INFO, ctx, " subject = %s", str);
OPENSSL_free(str);
if (!self_issued) {
str = X509_NAME_oneline(X509_get_issuer_name(cert), NULL, 0);
if (str != NULL)
ossl_cmp_log1(INFO, ctx, " issuer = %s", str);
OPENSSL_free(str);
}
if (already_checked(cert, already_checked1)
|| already_checked(cert, already_checked2)) {
ossl_cmp_info(ctx, " cert has already been checked");
return 0;
}
time_cmp = X509_cmp_timeframe(vpm, X509_get0_notBefore(cert),
X509_get0_notAfter(cert));
if (time_cmp != 0) {
ossl_cmp_warn(ctx, time_cmp > 0 ? "cert has expired"
: "cert is not yet valid");
return 0;
}
if (!check_name(ctx, 1,
"cert subject", X509_get_subject_name(cert),
"sender field", msg->header->sender->d.directoryName))
return 0;
if (!check_kid(ctx, X509_get0_subject_key_id(cert), msg->header->senderKID))
return 0;
/* prevent misleading error later in case x509v3_cache_extensions() fails */
if (!ossl_x509v3_cache_extensions(cert)) {
ossl_cmp_warn(ctx, "cert appears to be invalid");
return 0;
}
if (!verify_signature(ctx, msg, cert)) {
ossl_cmp_warn(ctx, "msg signature verification failed");
return 0;
}
/* acceptable also if there is no senderKID in msg header */
ossl_cmp_info(ctx, " cert seems acceptable");
return 1;
}
static int check_cert_path(const OSSL_CMP_CTX *ctx, X509_STORE *store,
X509 *scrt)
{
if (OSSL_CMP_validate_cert_path(ctx, store, scrt))
return 1;
ossl_cmp_warn(ctx,
"msg signature validates but cert path validation failed");
return 0;
}
/*
* Exceptional handling for 3GPP TS 33.310 [3G/LTE Network Domain Security
* (NDS); Authentication Framework (AF)], only to use for IP messages
* and if the ctx option is explicitly set: use self-issued certificates
* from extraCerts as trust anchor to validate sender cert -
* provided it also can validate the newly enrolled certificate
*/
static int check_cert_path_3gpp(const OSSL_CMP_CTX *ctx,
const OSSL_CMP_MSG *msg, X509 *scrt)
{
int valid = 0;
X509_STORE *store;
if (!ctx->permitTAInExtraCertsForIR)
return 0;
if ((store = X509_STORE_new()) == NULL
|| !ossl_cmp_X509_STORE_add1_certs(store, msg->extraCerts,
1 /* self-issued only */))
goto err;
/* store does not include CRLs */
valid = OSSL_CMP_validate_cert_path(ctx, store, scrt);
if (!valid) {
ossl_cmp_warn(ctx,
"also exceptional 3GPP mode cert path validation failed");
} else {
/*
* verify that the newly enrolled certificate (which assumed rid ==
* OSSL_CMP_CERTREQID) can also be validated with the same trusted store
*/
OSSL_CMP_CERTRESPONSE *crep =
ossl_cmp_certrepmessage_get0_certresponse(msg->body->value.ip,
OSSL_CMP_CERTREQID);
X509 *newcrt = ossl_cmp_certresponse_get1_cert(ctx, crep);
/*
* maybe better use get_cert_status() from cmp_client.c, which catches
* errors
*/
valid = OSSL_CMP_validate_cert_path(ctx, store, newcrt);
X509_free(newcrt);
}
err:
X509_STORE_free(store);
return valid;
}
static int check_msg_given_cert(const OSSL_CMP_CTX *ctx, X509 *cert,
const OSSL_CMP_MSG *msg)
{
return cert_acceptable(ctx, "previously validated", "sender cert",
cert, NULL, NULL, msg)
&& (check_cert_path(ctx, ctx->trusted, cert)
|| check_cert_path_3gpp(ctx, msg, cert));
}
/*-
* Try all certs in given list for verifying msg, normally or in 3GPP mode.
* If already_checked1 == NULL then certs are assumed to be the msg->extraCerts.
* On success cache the found cert using ossl_cmp_ctx_set0_validatedSrvCert().
*/
static int check_msg_with_certs(OSSL_CMP_CTX *ctx, const STACK_OF(X509) *certs,
const char *desc,
const STACK_OF(X509) *already_checked1,
const STACK_OF(X509) *already_checked2,
const OSSL_CMP_MSG *msg, int mode_3gpp)
{
int in_extraCerts = already_checked1 == NULL;
int n_acceptable_certs = 0;
int i;
if (sk_X509_num(certs) <= 0) {
ossl_cmp_log1(WARN, ctx, "no %s", desc);
return 0;
}
for (i = 0; i < sk_X509_num(certs); i++) { /* certs may be NULL */
X509 *cert = sk_X509_value(certs, i);
if (!ossl_assert(cert != NULL))
return 0;
if (!cert_acceptable(ctx, "cert from", desc, cert,
already_checked1, already_checked2, msg))
continue;
n_acceptable_certs++;
if (mode_3gpp ? check_cert_path_3gpp(ctx, msg, cert)
: check_cert_path(ctx, ctx->trusted, cert)) {
/* store successful sender cert for further msgs in transaction */
if (!X509_up_ref(cert))
return 0;
if (!ossl_cmp_ctx_set0_validatedSrvCert(ctx, cert)) {
X509_free(cert);
return 0;
}
return 1;
}
}
if (in_extraCerts && n_acceptable_certs == 0)
ossl_cmp_warn(ctx, "no acceptable cert in extraCerts");
return 0;
}
/*-
* Verify msg trying first ctx->untrusted, which should include extraCerts
* at its front, then trying the trusted certs in truststore (if any) of ctx.
* On success cache the found cert using ossl_cmp_ctx_set0_validatedSrvCert().
*/
static int check_msg_all_certs(OSSL_CMP_CTX *ctx, const OSSL_CMP_MSG *msg,
int mode_3gpp)
{
int ret = 0;
if (mode_3gpp
&& ((!ctx->permitTAInExtraCertsForIR
|| OSSL_CMP_MSG_get_bodytype(msg) != OSSL_CMP_PKIBODY_IP)))
return 0;
ossl_cmp_info(ctx,
mode_3gpp ? "normal mode failed; trying now 3GPP mode trusting extraCerts"
: "trying first normal mode using trust store");
if (check_msg_with_certs(ctx, msg->extraCerts, "extraCerts",
NULL, NULL, msg, mode_3gpp))
return 1;
if (check_msg_with_certs(ctx, ctx->untrusted, "untrusted certs",
msg->extraCerts, NULL, msg, mode_3gpp))
return 1;
if (ctx->trusted == NULL) {
ossl_cmp_warn(ctx, mode_3gpp ? "no self-issued extraCerts"
: "no trusted store");
} else {
STACK_OF(X509) *trusted = X509_STORE_get1_all_certs(ctx->trusted);
ret = check_msg_with_certs(ctx, trusted,
mode_3gpp ? "self-issued extraCerts"
: "certs in trusted store",
msg->extraCerts, ctx->untrusted,
msg, mode_3gpp);
sk_X509_pop_free(trusted, X509_free);
}
return ret;
}
static int no_log_cb(const char *func, const char *file, int line,
OSSL_CMP_severity level, const char *msg)
{
return 1;
}
/*-
* Verify message signature with any acceptable and valid candidate cert.
* On success cache the found cert using ossl_cmp_ctx_set0_validatedSrvCert().
*/
static int check_msg_find_cert(OSSL_CMP_CTX *ctx, const OSSL_CMP_MSG *msg)
{
X509 *scrt = ctx->validatedSrvCert; /* previous successful sender cert */
GENERAL_NAME *sender = msg->header->sender;
char *sname = NULL;
char *skid_str = NULL;
const ASN1_OCTET_STRING *skid = msg->header->senderKID;
OSSL_CMP_log_cb_t backup_log_cb = ctx->log_cb;
int res = 0;
if (sender == NULL || msg->body == NULL)
return 0; /* other NULL cases already have been checked */
if (sender->type != GEN_DIRNAME) {
ERR_raise(ERR_LIB_CMP, CMP_R_SENDER_GENERALNAME_TYPE_NOT_SUPPORTED);
return 0;
}
/* dump any hitherto errors to avoid confusion when printing further ones */
OSSL_CMP_CTX_print_errors(ctx);
/* enable clearing irrelevant errors in attempts to validate sender certs */
(void)ERR_set_mark();
ctx->log_cb = no_log_cb; /* temporarily disable logging */
/*
* try first cached scrt, used successfully earlier in same transaction,
* for validating this and any further msgs where extraCerts may be left out
*/
if (scrt != NULL) {
if (check_msg_given_cert(ctx, scrt, msg)) {
ctx->log_cb = backup_log_cb;
(void)ERR_pop_to_mark();
return 1;
}
/* cached sender cert has shown to be no more successfully usable */
(void)ossl_cmp_ctx_set0_validatedSrvCert(ctx, NULL);
/* re-do the above check (just) for adding diagnostic information */
ossl_cmp_info(ctx,
"trying to verify msg signature with previously validated cert");
(void)check_msg_given_cert(ctx, scrt, msg);
}
res = check_msg_all_certs(ctx, msg, 0 /* using ctx->trusted */)
|| check_msg_all_certs(ctx, msg, 1 /* 3gpp */);
ctx->log_cb = backup_log_cb;
if (res) {
/* discard any diagnostic information on trying to use certs */
(void)ERR_pop_to_mark();
goto end;
}
/* failed finding a sender cert that verifies the message signature */
(void)ERR_clear_last_mark();
sname = X509_NAME_oneline(sender->d.directoryName, NULL, 0);
skid_str = skid == NULL ? NULL
: OPENSSL_buf2hexstr(skid->data, skid->length);
if (ctx->log_cb != NULL) {
ossl_cmp_info(ctx, "trying to verify msg signature with a valid cert that..");
if (sname != NULL)
ossl_cmp_log1(INFO, ctx, "matches msg sender = %s", sname);
if (skid_str != NULL)
ossl_cmp_log1(INFO, ctx, "matches msg senderKID = %s", skid_str);
else
ossl_cmp_info(ctx, "while msg header does not contain senderKID");
/* re-do the above checks (just) for adding diagnostic information */
(void)check_msg_all_certs(ctx, msg, 0 /* using ctx->trusted */);
(void)check_msg_all_certs(ctx, msg, 1 /* 3gpp */);
}
ERR_raise(ERR_LIB_CMP, CMP_R_NO_SUITABLE_SENDER_CERT);
if (sname != NULL) {
ERR_add_error_txt(NULL, "for msg sender name = ");
ERR_add_error_txt(NULL, sname);
}
if (skid_str != NULL) {
ERR_add_error_txt(" and ", "for msg senderKID = ");
ERR_add_error_txt(NULL, skid_str);
}
end:
OPENSSL_free(sname);
OPENSSL_free(skid_str);
return res;
}
/*-
* Validate the protection of the given PKIMessage using either password-
* based mac (PBM) or a signature algorithm. In the case of signature algorithm,
* the sender certificate can have been pinned by providing it in ctx->srvCert,
* else it is searched in msg->extraCerts, ctx->untrusted, in ctx->trusted
* (in this order) and is path is validated against ctx->trusted.
* On success cache the found cert using ossl_cmp_ctx_set0_validatedSrvCert().
*
* If ctx->permitTAInExtraCertsForIR is true and when validating a CMP IP msg,
* the trust anchor for validating the IP msg may be taken from msg->extraCerts
* if a self-issued certificate is found there that can be used to
* validate the enrolled certificate returned in the IP.
* This is according to the need given in 3GPP TS 33.310.
*
* Returns 1 on success, 0 on error or validation failed.
*/
int OSSL_CMP_validate_msg(OSSL_CMP_CTX *ctx, const OSSL_CMP_MSG *msg)
{
X509 *scrt;
ossl_cmp_debug(ctx, "validating CMP message");
if (ctx == NULL || msg == NULL
|| msg->header == NULL || msg->body == NULL) {
ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT);
return 0;
}
if (msg->header->protectionAlg == NULL /* unprotected message */
|| msg->protection == NULL || msg->protection->data == NULL) {
ERR_raise(ERR_LIB_CMP, CMP_R_MISSING_PROTECTION);
return 0;
}
switch (ossl_cmp_hdr_get_protection_nid(msg->header)) {
/* 5.1.3.1. Shared Secret Information */
case NID_id_PasswordBasedMAC:
if (ctx->secretValue == NULL) {
ossl_cmp_info(ctx, "no secret available for verifying PBM-based CMP message protection");
ERR_raise(ERR_LIB_CMP, CMP_R_MISSING_SECRET);
return 0;
}
if (verify_PBMAC(ctx, msg)) {
/*
* RFC 4210, 5.3.2: 'Note that if the PKI Message Protection is
* "shared secret information", then any certificate transported in
* the caPubs field may be directly trusted as a root CA
* certificate by the initiator.'
*/
switch (OSSL_CMP_MSG_get_bodytype(msg)) {
case -1:
return 0;
case OSSL_CMP_PKIBODY_IP:
case OSSL_CMP_PKIBODY_CP:
case OSSL_CMP_PKIBODY_KUP:
case OSSL_CMP_PKIBODY_CCP:
if (ctx->trusted != NULL) {
STACK_OF(X509) *certs = msg->body->value.ip->caPubs;
/* value.ip is same for cp, kup, and ccp */
if (!ossl_cmp_X509_STORE_add1_certs(ctx->trusted, certs, 0))
/* adds both self-issued and not self-issued certs */
return 0;
}
break;
default:
break;
}
ossl_cmp_debug(ctx,
"sucessfully validated PBM-based CMP message protection");
return 1;
}
ossl_cmp_warn(ctx, "verifying PBM-based CMP message protection failed");
break;
/*
* 5.1.3.2 DH Key Pairs
* Not yet supported
*/
case NID_id_DHBasedMac:
ERR_raise(ERR_LIB_CMP, CMP_R_UNSUPPORTED_PROTECTION_ALG_DHBASEDMAC);
break;
/*
* 5.1.3.3. Signature
*/
default:
scrt = ctx->srvCert;
if (scrt == NULL) {
- if (ctx->trusted == NULL) {
+ if (ctx->trusted == NULL && ctx->secretValue != NULL) {
ossl_cmp_info(ctx, "no trust store nor pinned server cert available for verifying signature-based CMP message protection");
ERR_raise(ERR_LIB_CMP, CMP_R_MISSING_TRUST_ANCHOR);
return 0;
}
if (check_msg_find_cert(ctx, msg))
return 1;
} else { /* use pinned sender cert */
/* use ctx->srvCert for signature check even if not acceptable */
if (verify_signature(ctx, msg, scrt)) {
ossl_cmp_debug(ctx,
"sucessfully validated signature-based CMP message protection");
return 1;
}
ossl_cmp_warn(ctx, "CMP message signature verification failed");
ERR_raise(ERR_LIB_CMP, CMP_R_SRVCERT_DOES_NOT_VALIDATE_MSG);
}
break;
}
return 0;
}
/*-
* Check received message (i.e., response by server or request from client)
* Any msg->extraCerts are prepended to ctx->untrusted.
*
* Ensures that:
* its sender is of appropriate type (curently only X509_NAME) and
* matches any expected sender or srvCert subject given in the ctx
* it has a valid body type
* its protection is valid (or invalid/absent, but only if a callback function
* is present and yields a positive result using also the supplied argument)
* its transaction ID matches the previous transaction ID stored in ctx (if any)
* its recipNonce matches the previous senderNonce stored in the ctx (if any)
*
* If everything is fine:
* learns the senderNonce from the received message,
* learns the transaction ID if it is not yet in ctx,
* and makes any certs in caPubs directly trusted.
*
* Returns 1 on success, 0 on error.
*/
int ossl_cmp_msg_check_update(OSSL_CMP_CTX *ctx, const OSSL_CMP_MSG *msg,
ossl_cmp_allow_unprotected_cb_t cb, int cb_arg)
{
OSSL_CMP_PKIHEADER *hdr;
const X509_NAME *expected_sender;
if (!ossl_assert(ctx != NULL && msg != NULL && msg->header != NULL))
return 0;
hdr = OSSL_CMP_MSG_get0_header(msg);
/* validate sender name of received msg */
if (hdr->sender->type != GEN_DIRNAME) {
ERR_raise(ERR_LIB_CMP, CMP_R_SENDER_GENERALNAME_TYPE_NOT_SUPPORTED);
return 0;
}
/*
* Compare actual sender name of response with expected sender name.
* Mitigates risk to accept misused PBM secret
* or misused certificate of an unauthorized entity of a trusted hierarchy.
*/
expected_sender = ctx->expected_sender;
if (expected_sender == NULL && ctx->srvCert != NULL)
expected_sender = X509_get_subject_name(ctx->srvCert);
if (!check_name(ctx, 0, "sender DN field", hdr->sender->d.directoryName,
"expected sender", expected_sender))
return 0;
/* Note: if recipient was NULL-DN it could be learned here if needed */
if (sk_X509_num(msg->extraCerts) > 10)
ossl_cmp_warn(ctx,
"received CMP message contains more than 10 extraCerts");
/*
* Store any provided extraCerts in ctx for use in OSSL_CMP_validate_msg()
* and for future use, such that they are available to ctx->certConf_cb and
* the peer does not need to send them again in the same transaction.
* Note that it does not help validating the message before storing the
* extraCerts because they do not belong to the protected msg part anyway.
* For efficiency, the extraCerts are prepended so they get used first.
*/
if (!X509_add_certs(ctx->untrusted, msg->extraCerts,
/* this allows self-signed certs */
X509_ADD_FLAG_UP_REF | X509_ADD_FLAG_NO_DUP
| X509_ADD_FLAG_PREPEND))
return 0;
/* validate message protection */
if (hdr->protectionAlg != NULL) {
/* detect explicitly permitted exceptions for invalid protection */
if (!OSSL_CMP_validate_msg(ctx, msg)
&& (cb == NULL || (*cb)(ctx, msg, 1, cb_arg) <= 0)) {
#ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
ERR_raise(ERR_LIB_CMP, CMP_R_ERROR_VALIDATING_PROTECTION);
return 0;
#endif
}
} else {
/* detect explicitly permitted exceptions for missing protection */
if (cb == NULL || (*cb)(ctx, msg, 0, cb_arg) <= 0) {
#ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
ERR_raise(ERR_LIB_CMP, CMP_R_MISSING_PROTECTION);
return 0;
#endif
}
}
/* check CMP version number in header */
if (ossl_cmp_hdr_get_pvno(hdr) != OSSL_CMP_PVNO) {
#ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
ERR_raise(ERR_LIB_CMP, CMP_R_UNEXPECTED_PVNO);
return 0;
#endif
}
if (OSSL_CMP_MSG_get_bodytype(msg) < 0) {
#ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
ERR_raise(ERR_LIB_CMP, CMP_R_PKIBODY_ERROR);
return 0;
#endif
}
/* compare received transactionID with the expected one in previous msg */
if (ctx->transactionID != NULL
&& (hdr->transactionID == NULL
|| ASN1_OCTET_STRING_cmp(ctx->transactionID,
hdr->transactionID) != 0)) {
#ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
ERR_raise(ERR_LIB_CMP, CMP_R_TRANSACTIONID_UNMATCHED);
return 0;
#endif
}
/* compare received nonce with the one we sent */
if (ctx->senderNonce != NULL
&& (msg->header->recipNonce == NULL
|| ASN1_OCTET_STRING_cmp(ctx->senderNonce,
hdr->recipNonce) != 0)) {
#ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
ERR_raise(ERR_LIB_CMP, CMP_R_RECIPNONCE_UNMATCHED);
return 0;
#endif
}
/* if not yet present, learn transactionID */
if (ctx->transactionID == NULL
&& !OSSL_CMP_CTX_set1_transactionID(ctx, hdr->transactionID))
return 0;
/*
* RFC 4210 section 5.1.1 states: the recipNonce is copied from
* the senderNonce of the previous message in the transaction.
* --> Store for setting in next message
*/
if (!ossl_cmp_ctx_set1_recipNonce(ctx, hdr->senderNonce))
return 0;
/*
* Store any provided extraCerts in ctx for future use,
* such that they are available to ctx->certConf_cb and
* the peer does not need to send them again in the same transaction.
* For efficiency, the extraCerts are prepended so they get used first.
*/
if (!X509_add_certs(ctx->untrusted, msg->extraCerts,
/* this allows self-signed certs */
X509_ADD_FLAG_UP_REF | X509_ADD_FLAG_NO_DUP
| X509_ADD_FLAG_PREPEND))
return 0;
if (ossl_cmp_hdr_get_protection_nid(hdr) == NID_id_PasswordBasedMAC) {
/*
* RFC 4210, 5.3.2: 'Note that if the PKI Message Protection is
* "shared secret information", then any certificate transported in
* the caPubs field may be directly trusted as a root CA
* certificate by the initiator.'
*/
switch (OSSL_CMP_MSG_get_bodytype(msg)) {
case OSSL_CMP_PKIBODY_IP:
case OSSL_CMP_PKIBODY_CP:
case OSSL_CMP_PKIBODY_KUP:
case OSSL_CMP_PKIBODY_CCP:
if (ctx->trusted != NULL) {
STACK_OF(X509) *certs = msg->body->value.ip->caPubs;
/* value.ip is same for cp, kup, and ccp */
if (!ossl_cmp_X509_STORE_add1_certs(ctx->trusted, certs, 0))
/* adds both self-issued and not self-issued certs */
return 0;
}
break;
default:
break;
}
}
return 1;
}
int ossl_cmp_verify_popo(const OSSL_CMP_CTX *ctx,
const OSSL_CMP_MSG *msg, int acceptRAVerified)
{
if (!ossl_assert(msg != NULL && msg->body != NULL))
return 0;
switch (msg->body->type) {
case OSSL_CMP_PKIBODY_P10CR:
{
X509_REQ *req = msg->body->value.p10cr;
if (X509_REQ_verify_ex(req, X509_REQ_get0_pubkey(req), ctx->libctx,
ctx->propq) <= 0) {
#ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
ERR_raise(ERR_LIB_CMP, CMP_R_REQUEST_NOT_ACCEPTED);
return 0;
#endif
}
}
break;
case OSSL_CMP_PKIBODY_IR:
case OSSL_CMP_PKIBODY_CR:
case OSSL_CMP_PKIBODY_KUR:
if (!OSSL_CRMF_MSGS_verify_popo(msg->body->value.ir, OSSL_CMP_CERTREQID,
acceptRAVerified,
ctx->libctx, ctx->propq)) {
#ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
return 0;
#endif
}
break;
default:
ERR_raise(ERR_LIB_CMP, CMP_R_PKIBODY_ERROR);
return 0;
}
return 1;
}
diff --git a/crypto/openssl/crypto/conf/conf_def.c b/crypto/openssl/crypto/conf/conf_def.c
index 5acc90b69e1c..cda2f3e26792 100644
--- a/crypto/openssl/crypto/conf/conf_def.c
+++ b/crypto/openssl/crypto/conf/conf_def.c
@@ -1,1024 +1,1024 @@
/*
- * 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
*/
/* Part of the code in here was originally in conf.c, which is now removed */
#include <stdio.h>
#include <string.h>
#include "e_os.h" /* struct stat */
#ifdef __TANDEM
# include <sys/types.h> /* needed for stat.h */
# include <sys/stat.h> /* struct stat */
#endif
#include "internal/cryptlib.h"
#include "internal/o_dir.h"
#include <openssl/lhash.h>
#include <openssl/conf.h>
#include <openssl/conf_api.h>
#include "conf_local.h"
#include "conf_def.h"
#include <openssl/buffer.h>
#include <openssl/err.h>
#ifndef OPENSSL_NO_POSIX_IO
# include <sys/stat.h>
# ifdef _WIN32
# define stat _stat
# endif
#endif
#ifndef S_ISDIR
# define S_ISDIR(a) (((a) & S_IFMT) == S_IFDIR)
#endif
/*
* The maximum length we can grow a value to after variable expansion. 64k
* should be more than enough for all reasonable uses.
*/
#define MAX_CONF_VALUE_LENGTH 65536
static int is_keytype(const CONF *conf, char c, unsigned short type);
static char *eat_ws(CONF *conf, char *p);
static void trim_ws(CONF *conf, char *start);
static char *eat_alpha_numeric(CONF *conf, char *p);
static void clear_comments(CONF *conf, char *p);
static int str_copy(CONF *conf, char *section, char **to, char *from);
static char *scan_quote(CONF *conf, char *p);
static char *scan_dquote(CONF *conf, char *p);
#define scan_esc(conf,p) (((IS_EOF((conf),(p)[1]))?((p)+1):((p)+2)))
#ifndef OPENSSL_NO_POSIX_IO
static BIO *process_include(char *include, OPENSSL_DIR_CTX **dirctx,
char **dirpath);
static BIO *get_next_file(const char *path, OPENSSL_DIR_CTX **dirctx);
#endif
static CONF *def_create(CONF_METHOD *meth);
static int def_init_default(CONF *conf);
#ifndef OPENSSL_NO_DEPRECATED_3_0
static int def_init_WIN32(CONF *conf);
#endif
static int def_destroy(CONF *conf);
static int def_destroy_data(CONF *conf);
static int def_load(CONF *conf, const char *name, long *eline);
static int def_load_bio(CONF *conf, BIO *bp, long *eline);
static int def_dump(const CONF *conf, BIO *bp);
static int def_is_number(const CONF *conf, char c);
static int def_to_int(const CONF *conf, char c);
static CONF_METHOD default_method = {
"OpenSSL default",
def_create,
def_init_default,
def_destroy,
def_destroy_data,
def_load_bio,
def_dump,
def_is_number,
def_to_int,
def_load
};
CONF_METHOD *NCONF_default(void)
{
return &default_method;
}
#ifndef OPENSSL_NO_DEPRECATED_3_0
static CONF_METHOD WIN32_method = {
"WIN32",
def_create,
def_init_WIN32,
def_destroy,
def_destroy_data,
def_load_bio,
def_dump,
def_is_number,
def_to_int,
def_load
};
CONF_METHOD *NCONF_WIN32(void)
{
return &WIN32_method;
}
#endif
static CONF *def_create(CONF_METHOD *meth)
{
CONF *ret;
ret = OPENSSL_malloc(sizeof(*ret));
if (ret != NULL)
if (meth->init(ret) == 0) {
OPENSSL_free(ret);
ret = NULL;
}
return ret;
}
static int def_init_default(CONF *conf)
{
if (conf == NULL)
return 0;
memset(conf, 0, sizeof(*conf));
conf->meth = &default_method;
conf->meth_data = (void *)CONF_type_default;
return 1;
}
#ifndef OPENSSL_NO_DEPRECATED_3_0
static int def_init_WIN32(CONF *conf)
{
if (conf == NULL)
return 0;
memset(conf, 0, sizeof(*conf));
conf->meth = &WIN32_method;
conf->meth_data = (void *)CONF_type_win32;
return 1;
}
#endif
static int def_destroy(CONF *conf)
{
if (def_destroy_data(conf)) {
OPENSSL_free(conf);
return 1;
}
return 0;
}
static int def_destroy_data(CONF *conf)
{
if (conf == NULL)
return 0;
_CONF_free_data(conf);
return 1;
}
static int def_load(CONF *conf, const char *name, long *line)
{
int ret;
BIO *in = NULL;
#ifdef OPENSSL_SYS_VMS
in = BIO_new_file(name, "r");
#else
in = BIO_new_file(name, "rb");
#endif
if (in == NULL) {
if (ERR_GET_REASON(ERR_peek_last_error()) == BIO_R_NO_SUCH_FILE)
ERR_raise(ERR_LIB_CONF, CONF_R_NO_SUCH_FILE);
else
ERR_raise(ERR_LIB_CONF, ERR_R_SYS_LIB);
return 0;
}
ret = def_load_bio(conf, in, line);
BIO_free(in);
return ret;
}
/* Parse a boolean value and fill in *flag. Return 0 on error. */
static int parsebool(const char *pval, int *flag)
{
if (OPENSSL_strcasecmp(pval, "on") == 0
|| OPENSSL_strcasecmp(pval, "true") == 0) {
*flag = 1;
} else if (OPENSSL_strcasecmp(pval, "off") == 0
|| OPENSSL_strcasecmp(pval, "false") == 0) {
*flag = 0;
} else {
ERR_raise(ERR_LIB_CONF, CONF_R_INVALID_PRAGMA);
return 0;
}
return 1;
}
static int def_load_bio(CONF *conf, BIO *in, long *line)
{
/* The macro BUFSIZE conflicts with a system macro in VxWorks */
#define CONFBUFSIZE 512
int bufnum = 0, i, ii;
BUF_MEM *buff = NULL;
char *s, *p, *end;
int again;
int first_call = 1;
long eline = 0;
char btmp[DECIMAL_SIZE(eline) + 1];
CONF_VALUE *v = NULL, *tv;
CONF_VALUE *sv = NULL;
char *section = NULL, *buf;
char *start, *psection, *pname;
void *h = (void *)(conf->data);
STACK_OF(BIO) *biosk = NULL;
#ifndef OPENSSL_NO_POSIX_IO
char *dirpath = NULL;
OPENSSL_DIR_CTX *dirctx = NULL;
#endif
#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
int numincludes = 0;
#endif
if ((buff = BUF_MEM_new()) == NULL) {
ERR_raise(ERR_LIB_CONF, ERR_R_BUF_LIB);
goto err;
}
section = OPENSSL_strdup("default");
if (section == NULL) {
ERR_raise(ERR_LIB_CONF, ERR_R_MALLOC_FAILURE);
goto err;
}
if (_CONF_new_data(conf) == 0) {
ERR_raise(ERR_LIB_CONF, ERR_R_MALLOC_FAILURE);
goto err;
}
sv = _CONF_new_section(conf, section);
if (sv == NULL) {
ERR_raise(ERR_LIB_CONF, CONF_R_UNABLE_TO_CREATE_NEW_SECTION);
goto err;
}
bufnum = 0;
again = 0;
for (;;) {
if (!BUF_MEM_grow(buff, bufnum + CONFBUFSIZE)) {
ERR_raise(ERR_LIB_CONF, ERR_R_BUF_LIB);
goto err;
}
p = &(buff->data[bufnum]);
*p = '\0';
read_retry:
if (in != NULL && BIO_gets(in, p, CONFBUFSIZE - 1) < 0)
goto err;
p[CONFBUFSIZE - 1] = '\0';
ii = i = strlen(p);
if (first_call) {
/* Other BOMs imply unsupported multibyte encoding,
* so don't strip them and let the error raise */
const unsigned char utf8_bom[3] = {0xEF, 0xBB, 0xBF};
if (i >= 3 && memcmp(p, utf8_bom, 3) == 0) {
memmove(p, p + 3, i - 3);
p[i - 3] = 0;
i -= 3;
ii -= 3;
}
first_call = 0;
}
if (i == 0 && !again) {
/* the currently processed BIO is NULL or at EOF */
BIO *parent;
#ifndef OPENSSL_NO_POSIX_IO
/* continue processing with the next file from directory */
if (dirctx != NULL) {
BIO *next;
if ((next = get_next_file(dirpath, &dirctx)) != NULL) {
BIO_vfree(in);
in = next;
goto read_retry;
} else {
OPENSSL_free(dirpath);
dirpath = NULL;
}
}
#endif
/* no more files in directory, continue with processing parent */
if ((parent = sk_BIO_pop(biosk)) == NULL) {
/* everything processed get out of the loop */
break;
} else {
BIO_vfree(in);
in = parent;
goto read_retry;
}
}
again = 0;
while (i > 0) {
if ((p[i - 1] != '\r') && (p[i - 1] != '\n'))
break;
else
i--;
}
/*
* we removed some trailing stuff so there is a new line on the end.
*/
if (ii && i == ii)
again = 1; /* long line */
else {
p[i] = '\0';
eline++; /* another input line */
}
/* we now have a line with trailing \r\n removed */
/* i is the number of bytes */
bufnum += i;
v = NULL;
/* check for line continuation */
- if (bufnum >= 1) {
+ if (!again && bufnum >= 1) {
/*
* If we have bytes and the last char '\\' and second last char
* is not '\\'
*/
p = &(buff->data[bufnum - 1]);
if (IS_ESC(conf, p[0]) && ((bufnum <= 1) || !IS_ESC(conf, p[-1]))) {
bufnum--;
again = 1;
}
}
if (again)
continue;
bufnum = 0;
buf = buff->data;
clear_comments(conf, buf);
s = eat_ws(conf, buf);
if (IS_EOF(conf, *s))
continue; /* blank line */
if (*s == '[') {
char *ss;
s++;
start = eat_ws(conf, s);
ss = start;
again:
end = eat_alpha_numeric(conf, ss);
p = eat_ws(conf, end);
if (*p != ']') {
if (*p != '\0' && ss != p) {
ss = p;
goto again;
}
ERR_raise(ERR_LIB_CONF, CONF_R_MISSING_CLOSE_SQUARE_BRACKET);
goto err;
}
*end = '\0';
if (!str_copy(conf, NULL, &section, start))
goto err;
if ((sv = _CONF_get_section(conf, section)) == NULL)
sv = _CONF_new_section(conf, section);
if (sv == NULL) {
ERR_raise(ERR_LIB_CONF, CONF_R_UNABLE_TO_CREATE_NEW_SECTION);
goto err;
}
continue;
} else {
pname = s;
end = eat_alpha_numeric(conf, s);
if ((end[0] == ':') && (end[1] == ':')) {
*end = '\0';
end += 2;
psection = pname;
pname = end;
end = eat_alpha_numeric(conf, end);
} else {
psection = section;
}
p = eat_ws(conf, end);
if (strncmp(pname, ".pragma", 7) == 0
&& (p != pname + 7 || *p == '=')) {
char *pval;
if (*p == '=') {
p++;
p = eat_ws(conf, p);
}
trim_ws(conf, p);
/* Pragma values take the form keyword:value */
pval = strchr(p, ':');
if (pval == NULL || pval == p || pval[1] == '\0') {
ERR_raise(ERR_LIB_CONF, CONF_R_INVALID_PRAGMA);
goto err;
}
*pval++ = '\0';
trim_ws(conf, p);
pval = eat_ws(conf, pval);
/*
* Known pragmas:
*
* dollarid takes "on", "true or "off", "false"
* abspath takes "on", "true or "off", "false"
* includedir directory prefix
*/
if (strcmp(p, "dollarid") == 0) {
if (!parsebool(pval, &conf->flag_dollarid))
goto err;
} else if (strcmp(p, "abspath") == 0) {
if (!parsebool(pval, &conf->flag_abspath))
goto err;
} else if (strcmp(p, "includedir") == 0) {
OPENSSL_free(conf->includedir);
if ((conf->includedir = OPENSSL_strdup(pval)) == NULL) {
ERR_raise(ERR_LIB_CONF, ERR_R_MALLOC_FAILURE);
goto err;
}
}
/*
* We *ignore* any unknown pragma.
*/
continue;
} else if (strncmp(pname, ".include", 8) == 0
&& (p != pname + 8 || *p == '=')) {
char *include = NULL;
BIO *next;
const char *include_dir = ossl_safe_getenv("OPENSSL_CONF_INCLUDE");
char *include_path = NULL;
#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
/*
* The include processing below can cause the "conf" fuzzer to
* timeout due to the fuzzer inserting large and complicated
* includes - with a large amount of time spent in
* OPENSSL_strlcat/OPENSSL_strcpy. This is not a security
* concern because config files should never come from untrusted
* sources. We just set an arbitrary limit on the allowed
* number of includes when fuzzing to prevent this timeout.
*/
if (numincludes++ > 10)
goto err;
#endif
if (include_dir == NULL)
include_dir = conf->includedir;
if (*p == '=') {
p++;
p = eat_ws(conf, p);
}
trim_ws(conf, p);
if (!str_copy(conf, psection, &include, p))
goto err;
if (include_dir != NULL && !ossl_is_absolute_path(include)) {
size_t newlen = strlen(include_dir) + strlen(include) + 2;
include_path = OPENSSL_malloc(newlen);
if (include_path == NULL) {
ERR_raise(ERR_LIB_CONF, ERR_R_MALLOC_FAILURE);
OPENSSL_free(include);
goto err;
}
OPENSSL_strlcpy(include_path, include_dir, newlen);
if (!ossl_ends_with_dirsep(include_path))
OPENSSL_strlcat(include_path, "/", newlen);
OPENSSL_strlcat(include_path, include, newlen);
OPENSSL_free(include);
} else {
include_path = include;
}
if (conf->flag_abspath
&& !ossl_is_absolute_path(include_path)) {
ERR_raise(ERR_LIB_CONF, CONF_R_RELATIVE_PATH);
OPENSSL_free(include_path);
goto err;
}
/* get the BIO of the included file */
#ifndef OPENSSL_NO_POSIX_IO
next = process_include(include_path, &dirctx, &dirpath);
if (include_path != dirpath) {
/* dirpath will contain include in case of a directory */
OPENSSL_free(include_path);
}
#else
next = BIO_new_file(include_path, "r");
OPENSSL_free(include_path);
#endif
if (next != NULL) {
/* push the currently processing BIO onto stack */
if (biosk == NULL) {
if ((biosk = sk_BIO_new_null()) == NULL) {
ERR_raise(ERR_LIB_CONF, ERR_R_MALLOC_FAILURE);
BIO_free(next);
goto err;
}
}
if (!sk_BIO_push(biosk, in)) {
ERR_raise(ERR_LIB_CONF, ERR_R_MALLOC_FAILURE);
BIO_free(next);
goto err;
}
/* continue with reading from the included BIO */
in = next;
}
continue;
} else if (*p != '=') {
ERR_raise_data(ERR_LIB_CONF, CONF_R_MISSING_EQUAL_SIGN,
"HERE-->%s", p);
goto err;
}
*end = '\0';
p++;
start = eat_ws(conf, p);
trim_ws(conf, start);
if ((v = OPENSSL_malloc(sizeof(*v))) == NULL) {
ERR_raise(ERR_LIB_CONF, ERR_R_MALLOC_FAILURE);
goto err;
}
v->name = OPENSSL_strdup(pname);
v->value = NULL;
if (v->name == NULL) {
ERR_raise(ERR_LIB_CONF, ERR_R_MALLOC_FAILURE);
goto err;
}
if (!str_copy(conf, psection, &(v->value), start))
goto err;
if (strcmp(psection, section) != 0) {
if ((tv = _CONF_get_section(conf, psection))
== NULL)
tv = _CONF_new_section(conf, psection);
if (tv == NULL) {
ERR_raise(ERR_LIB_CONF,
CONF_R_UNABLE_TO_CREATE_NEW_SECTION);
goto err;
}
} else
tv = sv;
if (_CONF_add_string(conf, tv, v) == 0) {
ERR_raise(ERR_LIB_CONF, ERR_R_MALLOC_FAILURE);
goto err;
}
v = NULL;
}
}
BUF_MEM_free(buff);
OPENSSL_free(section);
/*
* No need to pop, since we only get here if the stack is empty.
* If this causes a BIO leak, THE ISSUE IS SOMEWHERE ELSE!
*/
sk_BIO_free(biosk);
return 1;
err:
BUF_MEM_free(buff);
OPENSSL_free(section);
/*
* Since |in| is the first element of the stack and should NOT be freed
* here, we cannot use sk_BIO_pop_free(). Instead, we pop and free one
* BIO at a time, making sure that the last one popped isn't.
*/
while (sk_BIO_num(biosk) > 0) {
BIO *popped = sk_BIO_pop(biosk);
BIO_vfree(in);
in = popped;
}
sk_BIO_free(biosk);
#ifndef OPENSSL_NO_POSIX_IO
OPENSSL_free(dirpath);
if (dirctx != NULL)
OPENSSL_DIR_end(&dirctx);
#endif
if (line != NULL)
*line = eline;
BIO_snprintf(btmp, sizeof(btmp), "%ld", eline);
ERR_add_error_data(2, "line ", btmp);
if (h != conf->data) {
CONF_free(conf->data);
conf->data = NULL;
}
if (v != NULL) {
OPENSSL_free(v->name);
OPENSSL_free(v->value);
OPENSSL_free(v);
}
return 0;
}
static void clear_comments(CONF *conf, char *p)
{
for (;;) {
if (IS_FCOMMENT(conf, *p)) {
*p = '\0';
return;
}
if (!IS_WS(conf, *p)) {
break;
}
p++;
}
for (;;) {
if (IS_COMMENT(conf, *p)) {
*p = '\0';
return;
}
if (IS_DQUOTE(conf, *p)) {
p = scan_dquote(conf, p);
continue;
}
if (IS_QUOTE(conf, *p)) {
p = scan_quote(conf, p);
continue;
}
if (IS_ESC(conf, *p)) {
p = scan_esc(conf, p);
continue;
}
if (IS_EOF(conf, *p))
return;
else
p++;
}
}
static int str_copy(CONF *conf, char *section, char **pto, char *from)
{
int q, r, rr = 0, to = 0, len = 0;
char *s, *e, *rp, *p, *rrp, *np, *cp, v;
BUF_MEM *buf;
if ((buf = BUF_MEM_new()) == NULL)
return 0;
len = strlen(from) + 1;
if (!BUF_MEM_grow(buf, len))
goto err;
for (;;) {
if (IS_QUOTE(conf, *from)) {
q = *from;
from++;
while (!IS_EOF(conf, *from) && (*from != q)) {
if (IS_ESC(conf, *from)) {
from++;
if (IS_EOF(conf, *from))
break;
}
buf->data[to++] = *(from++);
}
if (*from == q)
from++;
} else if (IS_DQUOTE(conf, *from)) {
q = *from;
from++;
while (!IS_EOF(conf, *from)) {
if (*from == q) {
if (*(from + 1) == q) {
from++;
} else {
break;
}
}
buf->data[to++] = *(from++);
}
if (*from == q)
from++;
} else if (IS_ESC(conf, *from)) {
from++;
v = *(from++);
if (IS_EOF(conf, v))
break;
else if (v == 'r')
v = '\r';
else if (v == 'n')
v = '\n';
else if (v == 'b')
v = '\b';
else if (v == 't')
v = '\t';
buf->data[to++] = v;
} else if (IS_EOF(conf, *from))
break;
else if (*from == '$'
&& (!conf->flag_dollarid
|| from[1] == '{'
|| from[1] == '(')) {
size_t newsize;
/* try to expand it */
rrp = NULL;
s = &(from[1]);
if (*s == '{')
q = '}';
else if (*s == '(')
q = ')';
else
q = 0;
if (q)
s++;
cp = section;
e = np = s;
while (IS_ALNUM(conf, *e)
|| (conf->flag_dollarid && IS_DOLLAR(conf, *e)))
e++;
if ((e[0] == ':') && (e[1] == ':')) {
cp = np;
rrp = e;
rr = *e;
*rrp = '\0';
e += 2;
np = e;
while (IS_ALNUM(conf, *e)
|| (conf->flag_dollarid && IS_DOLLAR(conf, *e)))
e++;
}
r = *e;
*e = '\0';
rp = e;
if (q) {
if (r != q) {
ERR_raise(ERR_LIB_CONF, CONF_R_NO_CLOSE_BRACE);
goto err;
}
e++;
}
/*-
* So at this point we have
* np which is the start of the name string which is
* '\0' terminated.
* cp which is the start of the section string which is
* '\0' terminated.
* e is the 'next point after'.
* r and rr are the chars replaced by the '\0'
* rp and rrp is where 'r' and 'rr' came from.
*/
p = _CONF_get_string(conf, cp, np);
if (rrp != NULL)
*rrp = rr;
*rp = r;
if (p == NULL) {
ERR_raise(ERR_LIB_CONF, CONF_R_VARIABLE_HAS_NO_VALUE);
goto err;
}
newsize = strlen(p) + buf->length - (e - from);
if (newsize > MAX_CONF_VALUE_LENGTH) {
ERR_raise(ERR_LIB_CONF, CONF_R_VARIABLE_EXPANSION_TOO_LONG);
goto err;
}
if (!BUF_MEM_grow_clean(buf, newsize)) {
ERR_raise(ERR_LIB_CONF, ERR_R_MALLOC_FAILURE);
goto err;
}
while (*p)
buf->data[to++] = *(p++);
/*
* Since we change the pointer 'from', we also have to change the
* perceived length of the string it points at. /RL
*/
len -= e - from;
from = e;
/*
* In case there were no braces or parenthesis around the
* variable reference, we have to put back the character that was
* replaced with a '\0'. /RL
*/
*rp = r;
} else
buf->data[to++] = *(from++);
}
buf->data[to] = '\0';
OPENSSL_free(*pto);
*pto = buf->data;
OPENSSL_free(buf);
return 1;
err:
BUF_MEM_free(buf);
return 0;
}
#ifndef OPENSSL_NO_POSIX_IO
/*
* Check whether included path is a directory.
* Returns next BIO to process and in case of a directory
* also an opened directory context and the include path.
*/
static BIO *process_include(char *include, OPENSSL_DIR_CTX **dirctx,
char **dirpath)
{
struct stat st;
BIO *next;
if (stat(include, &st) < 0) {
ERR_raise_data(ERR_LIB_SYS, errno, "calling stat(%s)", include);
/* missing include file is not fatal error */
return NULL;
}
if (S_ISDIR(st.st_mode)) {
if (*dirctx != NULL) {
ERR_raise_data(ERR_LIB_CONF, CONF_R_RECURSIVE_DIRECTORY_INCLUDE,
"%s", include);
return NULL;
}
/* a directory, load its contents */
if ((next = get_next_file(include, dirctx)) != NULL)
*dirpath = include;
return next;
}
next = BIO_new_file(include, "r");
return next;
}
/*
* Get next file from the directory path.
* Returns BIO of the next file to read and updates dirctx.
*/
static BIO *get_next_file(const char *path, OPENSSL_DIR_CTX **dirctx)
{
const char *filename;
size_t pathlen;
pathlen = strlen(path);
while ((filename = OPENSSL_DIR_read(dirctx, path)) != NULL) {
size_t namelen;
namelen = strlen(filename);
if ((namelen > 5
&& OPENSSL_strcasecmp(filename + namelen - 5, ".conf") == 0)
|| (namelen > 4
&& OPENSSL_strcasecmp(filename + namelen - 4, ".cnf") == 0)) {
size_t newlen;
char *newpath;
BIO *bio;
newlen = pathlen + namelen + 2;
newpath = OPENSSL_zalloc(newlen);
if (newpath == NULL) {
ERR_raise(ERR_LIB_CONF, ERR_R_MALLOC_FAILURE);
break;
}
#ifdef OPENSSL_SYS_VMS
/*
* If the given path isn't clear VMS syntax,
* we treat it as on Unix.
*/
if (path[pathlen - 1] == ']'
|| path[pathlen - 1] == '>'
|| path[pathlen - 1] == ':') {
/* Clear VMS directory syntax, just copy as is */
OPENSSL_strlcpy(newpath, path, newlen);
}
#endif
if (newpath[0] == '\0') {
OPENSSL_strlcpy(newpath, path, newlen);
OPENSSL_strlcat(newpath, "/", newlen);
}
OPENSSL_strlcat(newpath, filename, newlen);
bio = BIO_new_file(newpath, "r");
OPENSSL_free(newpath);
/* Errors when opening files are non-fatal. */
if (bio != NULL)
return bio;
}
}
OPENSSL_DIR_end(dirctx);
*dirctx = NULL;
return NULL;
}
#endif
static int is_keytype(const CONF *conf, char c, unsigned short type)
{
const unsigned short * keytypes = (const unsigned short *) conf->meth_data;
unsigned char key = (unsigned char)c;
#ifdef CHARSET_EBCDIC
# if CHAR_BIT > 8
if (key > 255) {
/* key is out of range for os_toascii table */
return 0;
}
# endif
/* convert key from ebcdic to ascii */
key = os_toascii[key];
#endif
if (key > 127) {
/* key is not a seven bit ascii character */
return 0;
}
return (keytypes[key] & type) ? 1 : 0;
}
static char *eat_ws(CONF *conf, char *p)
{
while (IS_WS(conf, *p) && (!IS_EOF(conf, *p)))
p++;
return p;
}
static void trim_ws(CONF *conf, char *start)
{
char *p = start;
while (!IS_EOF(conf, *p))
p++;
p--;
while ((p >= start) && IS_WS(conf, *p))
p--;
p++;
*p = '\0';
}
static char *eat_alpha_numeric(CONF *conf, char *p)
{
for (;;) {
if (IS_ESC(conf, *p)) {
p = scan_esc(conf, p);
continue;
}
if (!(IS_ALNUM_PUNCT(conf, *p)
|| (conf->flag_dollarid && IS_DOLLAR(conf, *p))))
return p;
p++;
}
}
static char *scan_quote(CONF *conf, char *p)
{
int q = *p;
p++;
while (!(IS_EOF(conf, *p)) && (*p != q)) {
if (IS_ESC(conf, *p)) {
p++;
if (IS_EOF(conf, *p))
return p;
}
p++;
}
if (*p == q)
p++;
return p;
}
static char *scan_dquote(CONF *conf, char *p)
{
int q = *p;
p++;
while (!(IS_EOF(conf, *p))) {
if (*p == q) {
if (*(p + 1) == q) {
p++;
} else {
break;
}
}
p++;
}
if (*p == q)
p++;
return p;
}
static void dump_value_doall_arg(const CONF_VALUE *a, BIO *out)
{
if (a->name)
BIO_printf(out, "[%s] %s=%s\n", a->section, a->name, a->value);
else
BIO_printf(out, "[[%s]]\n", a->section);
}
IMPLEMENT_LHASH_DOALL_ARG_CONST(CONF_VALUE, BIO);
static int def_dump(const CONF *conf, BIO *out)
{
lh_CONF_VALUE_doall_BIO(conf->data, dump_value_doall_arg, out);
return 1;
}
static int def_is_number(const CONF *conf, char c)
{
return IS_NUMBER(conf, c);
}
static int def_to_int(const CONF *conf, char c)
{
return c - '0';
}
diff --git a/crypto/openssl/crypto/conf/conf_lib.c b/crypto/openssl/crypto/conf/conf_lib.c
index a2360035257a..719af7cb75c6 100644
--- a/crypto/openssl/crypto/conf/conf_lib.c
+++ b/crypto/openssl/crypto/conf/conf_lib.c
@@ -1,470 +1,473 @@
/*
- * 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
* https://www.openssl.org/source/license.html
*/
#include "e_os.h"
#include <stdio.h>
#include <string.h>
#include "internal/conf.h"
#include "crypto/ctype.h"
#include <openssl/crypto.h>
#include <openssl/err.h>
#include <openssl/conf.h>
#include <openssl/conf_api.h>
#include "conf_local.h"
#include <openssl/lhash.h>
static CONF_METHOD *default_CONF_method = NULL;
/* Init a 'CONF' structure from an old LHASH */
void CONF_set_nconf(CONF *conf, LHASH_OF(CONF_VALUE) *hash)
{
if (default_CONF_method == NULL)
default_CONF_method = NCONF_default();
default_CONF_method->init(conf);
conf->data = hash;
}
/*
* The following section contains the "CONF classic" functions, rewritten in
* terms of the new CONF interface.
*/
int CONF_set_default_method(CONF_METHOD *meth)
{
default_CONF_method = meth;
return 1;
}
LHASH_OF(CONF_VALUE) *CONF_load(LHASH_OF(CONF_VALUE) *conf, const char *file,
long *eline)
{
LHASH_OF(CONF_VALUE) *ltmp;
BIO *in = NULL;
#ifdef OPENSSL_SYS_VMS
in = BIO_new_file(file, "r");
#else
in = BIO_new_file(file, "rb");
#endif
if (in == NULL) {
ERR_raise(ERR_LIB_CONF, ERR_R_SYS_LIB);
return NULL;
}
ltmp = CONF_load_bio(conf, in, eline);
BIO_free(in);
return ltmp;
}
#ifndef OPENSSL_NO_STDIO
LHASH_OF(CONF_VALUE) *CONF_load_fp(LHASH_OF(CONF_VALUE) *conf, FILE *fp,
long *eline)
{
BIO *btmp;
LHASH_OF(CONF_VALUE) *ltmp;
if ((btmp = BIO_new_fp(fp, BIO_NOCLOSE)) == NULL) {
ERR_raise(ERR_LIB_CONF, ERR_R_BUF_LIB);
return NULL;
}
ltmp = CONF_load_bio(conf, btmp, eline);
BIO_free(btmp);
return ltmp;
}
#endif
LHASH_OF(CONF_VALUE) *CONF_load_bio(LHASH_OF(CONF_VALUE) *conf, BIO *bp,
long *eline)
{
CONF ctmp;
int ret;
CONF_set_nconf(&ctmp, conf);
ret = NCONF_load_bio(&ctmp, bp, eline);
if (ret)
return ctmp.data;
return NULL;
}
STACK_OF(CONF_VALUE) *CONF_get_section(LHASH_OF(CONF_VALUE) *conf,
const char *section)
{
if (conf == NULL) {
return NULL;
} else {
CONF ctmp;
CONF_set_nconf(&ctmp, conf);
return NCONF_get_section(&ctmp, section);
}
}
char *CONF_get_string(LHASH_OF(CONF_VALUE) *conf, const char *group,
const char *name)
{
if (conf == NULL) {
return NCONF_get_string(NULL, group, name);
} else {
CONF ctmp;
CONF_set_nconf(&ctmp, conf);
return NCONF_get_string(&ctmp, group, name);
}
}
long CONF_get_number(LHASH_OF(CONF_VALUE) *conf, const char *group,
const char *name)
{
int status;
long result = 0;
ERR_set_mark();
if (conf == NULL) {
status = NCONF_get_number_e(NULL, group, name, &result);
} else {
CONF ctmp;
CONF_set_nconf(&ctmp, conf);
status = NCONF_get_number_e(&ctmp, group, name, &result);
}
ERR_pop_to_mark();
return status == 0 ? 0L : result;
}
void CONF_free(LHASH_OF(CONF_VALUE) *conf)
{
CONF ctmp;
CONF_set_nconf(&ctmp, conf);
NCONF_free_data(&ctmp);
}
#ifndef OPENSSL_NO_STDIO
int CONF_dump_fp(LHASH_OF(CONF_VALUE) *conf, FILE *out)
{
BIO *btmp;
int ret;
if ((btmp = BIO_new_fp(out, BIO_NOCLOSE)) == NULL) {
ERR_raise(ERR_LIB_CONF, ERR_R_BUF_LIB);
return 0;
}
ret = CONF_dump_bio(conf, btmp);
BIO_free(btmp);
return ret;
}
#endif
int CONF_dump_bio(LHASH_OF(CONF_VALUE) *conf, BIO *out)
{
CONF ctmp;
CONF_set_nconf(&ctmp, conf);
return NCONF_dump_bio(&ctmp, out);
}
/*
* The following section contains the "New CONF" functions. They are
* completely centralised around a new CONF structure that may contain
* basically anything, but at least a method pointer and a table of data.
* These functions are also written in terms of the bridge functions used by
* the "CONF classic" functions, for consistency.
*/
CONF *NCONF_new_ex(OSSL_LIB_CTX *libctx, CONF_METHOD *meth)
{
CONF *ret;
if (meth == NULL)
meth = NCONF_default();
ret = meth->create(meth);
if (ret == NULL) {
ERR_raise(ERR_LIB_CONF, ERR_R_MALLOC_FAILURE);
return NULL;
}
ret->libctx = libctx;
return ret;
}
CONF *NCONF_new(CONF_METHOD *meth)
{
return NCONF_new_ex(NULL, meth);
}
void NCONF_free(CONF *conf)
{
if (conf == NULL)
return;
conf->meth->destroy(conf);
}
void NCONF_free_data(CONF *conf)
{
if (conf == NULL)
return;
conf->meth->destroy_data(conf);
}
OSSL_LIB_CTX *NCONF_get0_libctx(const CONF *conf)
{
return conf->libctx;
}
typedef STACK_OF(OPENSSL_CSTRING) SECTION_NAMES;
IMPLEMENT_LHASH_DOALL_ARG_CONST(CONF_VALUE, SECTION_NAMES);
static void collect_section_name(const CONF_VALUE *v, SECTION_NAMES *names)
{
/* A section is a CONF_VALUE with name == NULL */
if (v->name == NULL)
sk_OPENSSL_CSTRING_push(names, v->section);
}
static int section_name_cmp(OPENSSL_CSTRING const *a, OPENSSL_CSTRING const *b)
{
return strcmp(*a, *b);
}
STACK_OF(OPENSSL_CSTRING) *NCONF_get_section_names(const CONF *cnf)
{
SECTION_NAMES *names;
if ((names = sk_OPENSSL_CSTRING_new(section_name_cmp)) == NULL)
return NULL;
lh_CONF_VALUE_doall_SECTION_NAMES(cnf->data, collect_section_name, names);
sk_OPENSSL_CSTRING_sort(names);
return names;
}
int NCONF_load(CONF *conf, const char *file, long *eline)
{
if (conf == NULL) {
ERR_raise(ERR_LIB_CONF, CONF_R_NO_CONF);
return 0;
}
return conf->meth->load(conf, file, eline);
}
#ifndef OPENSSL_NO_STDIO
int NCONF_load_fp(CONF *conf, FILE *fp, long *eline)
{
BIO *btmp;
int ret;
if ((btmp = BIO_new_fp(fp, BIO_NOCLOSE)) == NULL) {
ERR_raise(ERR_LIB_CONF, ERR_R_BUF_LIB);
return 0;
}
ret = NCONF_load_bio(conf, btmp, eline);
BIO_free(btmp);
return ret;
}
#endif
int NCONF_load_bio(CONF *conf, BIO *bp, long *eline)
{
if (conf == NULL) {
ERR_raise(ERR_LIB_CONF, CONF_R_NO_CONF);
return 0;
}
return conf->meth->load_bio(conf, bp, eline);
}
STACK_OF(CONF_VALUE) *NCONF_get_section(const CONF *conf, const char *section)
{
if (conf == NULL) {
ERR_raise(ERR_LIB_CONF, CONF_R_NO_CONF);
return NULL;
}
if (section == NULL) {
ERR_raise(ERR_LIB_CONF, CONF_R_NO_SECTION);
return NULL;
}
return _CONF_get_section_values(conf, section);
}
char *NCONF_get_string(const CONF *conf, const char *group, const char *name)
{
char *s = _CONF_get_string(conf, group, name);
/*
* Since we may get a value from an environment variable even if conf is
* NULL, let's check the value first
*/
if (s)
return s;
if (conf == NULL) {
ERR_raise(ERR_LIB_CONF, CONF_R_NO_CONF_OR_ENVIRONMENT_VARIABLE);
return NULL;
}
ERR_raise_data(ERR_LIB_CONF, CONF_R_NO_VALUE,
"group=%s name=%s", group, name);
return NULL;
}
static int default_is_number(const CONF *conf, char c)
{
return ossl_isdigit(c);
}
static int default_to_int(const CONF *conf, char c)
{
return (int)(c - '0');
}
int NCONF_get_number_e(const CONF *conf, const char *group, const char *name,
long *result)
{
char *str;
long res;
int (*is_number)(const CONF *, char) = &default_is_number;
int (*to_int)(const CONF *, char) = &default_to_int;
if (result == NULL) {
ERR_raise(ERR_LIB_CONF, ERR_R_PASSED_NULL_PARAMETER);
return 0;
}
str = NCONF_get_string(conf, group, name);
if (str == NULL)
return 0;
if (conf != NULL) {
if (conf->meth->is_number != NULL)
is_number = conf->meth->is_number;
if (conf->meth->to_int != NULL)
to_int = conf->meth->to_int;
}
for (res = 0; is_number(conf, *str); str++) {
const int d = to_int(conf, *str);
if (res > (LONG_MAX - d) / 10L) {
ERR_raise(ERR_LIB_CONF, CONF_R_NUMBER_TOO_LARGE);
return 0;
}
res = res * 10 + d;
}
*result = res;
return 1;
}
long _CONF_get_number(const CONF *conf, const char *section,
const char *name)
{
int status;
long result = 0;
ERR_set_mark();
status = NCONF_get_number_e(conf, section, name, &result);
ERR_pop_to_mark();
return status == 0 ? 0L : result;
}
#ifndef OPENSSL_NO_STDIO
int NCONF_dump_fp(const CONF *conf, FILE *out)
{
BIO *btmp;
int ret;
if ((btmp = BIO_new_fp(out, BIO_NOCLOSE)) == NULL) {
ERR_raise(ERR_LIB_CONF, ERR_R_BUF_LIB);
return 0;
}
ret = NCONF_dump_bio(conf, btmp);
BIO_free(btmp);
return ret;
}
#endif
int NCONF_dump_bio(const CONF *conf, BIO *out)
{
if (conf == NULL) {
ERR_raise(ERR_LIB_CONF, CONF_R_NO_CONF);
return 0;
}
return conf->meth->dump(conf, out);
}
/*
* These routines call the C malloc/free, to avoid intermixing with
* OpenSSL function pointers before the library is initialized.
*/
OPENSSL_INIT_SETTINGS *OPENSSL_INIT_new(void)
{
OPENSSL_INIT_SETTINGS *ret = malloc(sizeof(*ret));
if (ret == NULL)
return NULL;
memset(ret, 0, sizeof(*ret));
ret->flags = DEFAULT_CONF_MFLAGS;
return ret;
}
#ifndef OPENSSL_NO_STDIO
int OPENSSL_INIT_set_config_filename(OPENSSL_INIT_SETTINGS *settings,
const char *filename)
{
char *newfilename = NULL;
if (filename != NULL) {
newfilename = strdup(filename);
if (newfilename == NULL)
return 0;
}
free(settings->filename);
settings->filename = newfilename;
return 1;
}
void OPENSSL_INIT_set_config_file_flags(OPENSSL_INIT_SETTINGS *settings,
unsigned long flags)
{
settings->flags = flags;
}
int OPENSSL_INIT_set_config_appname(OPENSSL_INIT_SETTINGS *settings,
const char *appname)
{
char *newappname = NULL;
if (appname != NULL) {
newappname = strdup(appname);
if (newappname == NULL)
return 0;
}
free(settings->appname);
settings->appname = newappname;
return 1;
}
#endif
void OPENSSL_INIT_free(OPENSSL_INIT_SETTINGS *settings)
{
+ if (settings == NULL)
+ return;
+
free(settings->filename);
free(settings->appname);
free(settings);
}
diff --git a/crypto/openssl/crypto/conf/conf_sap.c b/crypto/openssl/crypto/conf/conf_sap.c
index 3019bcf31af8..106434dcbf3d 100644
--- a/crypto/openssl/crypto/conf/conf_sap.c
+++ b/crypto/openssl/crypto/conf/conf_sap.c
@@ -1,80 +1,82 @@
/*
- * 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
*/
#include <stdio.h>
#include <openssl/crypto.h>
#include "internal/cryptlib.h"
#include "internal/conf.h"
#include "conf_local.h"
#include <openssl/x509.h>
#include <openssl/asn1.h>
#include <openssl/engine.h>
#if defined(_WIN32) && !defined(__BORLANDC__)
# define strdup _strdup
#endif
/*
* This is the automatic configuration loader: it is called automatically by
* OpenSSL when any of a number of standard initialisation functions are
* called, unless this is overridden by calling OPENSSL_no_config()
*/
static int openssl_configured = 0;
#ifndef OPENSSL_NO_DEPRECATED_1_1_0
void OPENSSL_config(const char *appname)
{
OPENSSL_INIT_SETTINGS settings;
memset(&settings, 0, sizeof(settings));
if (appname != NULL)
settings.appname = strdup(appname);
settings.flags = DEFAULT_CONF_MFLAGS;
OPENSSL_init_crypto(OPENSSL_INIT_LOAD_CONFIG, &settings);
+
+ free(settings.appname);
}
#endif
int ossl_config_int(const OPENSSL_INIT_SETTINGS *settings)
{
int ret = 0;
#if defined(OPENSSL_INIT_DEBUG) || !defined(OPENSSL_SYS_UEFI)
const char *filename;
const char *appname;
unsigned long flags;
#endif
if (openssl_configured)
return 1;
#if defined(OPENSSL_INIT_DEBUG) || !defined(OPENSSL_SYS_UEFI)
filename = settings ? settings->filename : NULL;
appname = settings ? settings->appname : NULL;
flags = settings ? settings->flags : DEFAULT_CONF_MFLAGS;
#endif
#ifdef OPENSSL_INIT_DEBUG
fprintf(stderr, "OPENSSL_INIT: ossl_config_int(%s, %s, %lu)\n",
filename, appname, flags);
#endif
#ifndef OPENSSL_SYS_UEFI
ret = CONF_modules_load_file_ex(OSSL_LIB_CTX_get0_global_default(),
filename, appname, flags);
#else
ret = 1;
#endif
openssl_configured = 1;
return ret;
}
void ossl_no_config_int(void)
{
openssl_configured = 1;
}
diff --git a/crypto/openssl/crypto/context.c b/crypto/openssl/crypto/context.c
index 548665fba265..ac6938e619eb 100644
--- a/crypto/openssl/crypto/context.c
+++ b/crypto/openssl/crypto/context.c
@@ -1,510 +1,510 @@
/*
- * 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 "crypto/cryptlib.h"
#include <openssl/conf.h>
#include "internal/thread_once.h"
#include "internal/property.h"
#include "internal/core.h"
#include "internal/bio.h"
#include "internal/provider.h"
#include "crypto/ctype.h"
#include "crypto/rand.h"
struct ossl_lib_ctx_onfree_list_st {
ossl_lib_ctx_onfree_fn *fn;
struct ossl_lib_ctx_onfree_list_st *next;
};
struct ossl_lib_ctx_st {
CRYPTO_RWLOCK *lock;
CRYPTO_EX_DATA data;
/*
* For most data in the OSSL_LIB_CTX we just use ex_data to store it. But
* that doesn't work for ex_data itself - so we store that directly.
*/
OSSL_EX_DATA_GLOBAL global;
/* Map internal static indexes to dynamically created indexes */
int dyn_indexes[OSSL_LIB_CTX_MAX_INDEXES];
/* Keep a separate lock for each index */
CRYPTO_RWLOCK *index_locks[OSSL_LIB_CTX_MAX_INDEXES];
CRYPTO_RWLOCK *oncelock;
int run_once_done[OSSL_LIB_CTX_MAX_RUN_ONCE];
int run_once_ret[OSSL_LIB_CTX_MAX_RUN_ONCE];
struct ossl_lib_ctx_onfree_list_st *onfreelist;
unsigned int ischild:1;
};
int ossl_lib_ctx_write_lock(OSSL_LIB_CTX *ctx)
{
return CRYPTO_THREAD_write_lock(ossl_lib_ctx_get_concrete(ctx)->lock);
}
int ossl_lib_ctx_read_lock(OSSL_LIB_CTX *ctx)
{
return CRYPTO_THREAD_read_lock(ossl_lib_ctx_get_concrete(ctx)->lock);
}
int ossl_lib_ctx_unlock(OSSL_LIB_CTX *ctx)
{
return CRYPTO_THREAD_unlock(ossl_lib_ctx_get_concrete(ctx)->lock);
}
int ossl_lib_ctx_is_child(OSSL_LIB_CTX *ctx)
{
ctx = ossl_lib_ctx_get_concrete(ctx);
if (ctx == NULL)
return 0;
return ctx->ischild;
}
static int context_init(OSSL_LIB_CTX *ctx)
{
size_t i;
int exdata_done = 0;
ctx->lock = CRYPTO_THREAD_lock_new();
if (ctx->lock == NULL)
return 0;
ctx->oncelock = CRYPTO_THREAD_lock_new();
if (ctx->oncelock == NULL)
goto err;
for (i = 0; i < OSSL_LIB_CTX_MAX_INDEXES; i++) {
ctx->index_locks[i] = CRYPTO_THREAD_lock_new();
ctx->dyn_indexes[i] = -1;
if (ctx->index_locks[i] == NULL)
goto err;
}
/* OSSL_LIB_CTX is built on top of ex_data so we initialise that directly */
if (!ossl_do_ex_data_init(ctx))
goto err;
exdata_done = 1;
if (!ossl_crypto_new_ex_data_ex(ctx, CRYPTO_EX_INDEX_OSSL_LIB_CTX, NULL,
&ctx->data))
goto err;
/* Everything depends on properties, so we also pre-initialise that */
if (!ossl_property_parse_init(ctx))
goto err;
return 1;
err:
if (exdata_done)
ossl_crypto_cleanup_all_ex_data_int(ctx);
for (i = 0; i < OSSL_LIB_CTX_MAX_INDEXES; i++)
CRYPTO_THREAD_lock_free(ctx->index_locks[i]);
CRYPTO_THREAD_lock_free(ctx->oncelock);
CRYPTO_THREAD_lock_free(ctx->lock);
memset(ctx, '\0', sizeof(*ctx));
return 0;
}
static int context_deinit(OSSL_LIB_CTX *ctx)
{
struct ossl_lib_ctx_onfree_list_st *tmp, *onfree;
int i;
if (ctx == NULL)
return 1;
ossl_ctx_thread_stop(ctx);
onfree = ctx->onfreelist;
while (onfree != NULL) {
onfree->fn(ctx);
tmp = onfree;
onfree = onfree->next;
OPENSSL_free(tmp);
}
CRYPTO_free_ex_data(CRYPTO_EX_INDEX_OSSL_LIB_CTX, NULL, &ctx->data);
ossl_crypto_cleanup_all_ex_data_int(ctx);
for (i = 0; i < OSSL_LIB_CTX_MAX_INDEXES; i++)
CRYPTO_THREAD_lock_free(ctx->index_locks[i]);
CRYPTO_THREAD_lock_free(ctx->oncelock);
CRYPTO_THREAD_lock_free(ctx->lock);
ctx->lock = NULL;
return 1;
}
#ifndef FIPS_MODULE
/* The default default context */
static OSSL_LIB_CTX default_context_int;
static CRYPTO_ONCE default_context_init = CRYPTO_ONCE_STATIC_INIT;
static CRYPTO_THREAD_LOCAL default_context_thread_local;
DEFINE_RUN_ONCE_STATIC(default_context_do_init)
{
return CRYPTO_THREAD_init_local(&default_context_thread_local, NULL)
&& context_init(&default_context_int);
}
void ossl_lib_ctx_default_deinit(void)
{
context_deinit(&default_context_int);
CRYPTO_THREAD_cleanup_local(&default_context_thread_local);
}
static OSSL_LIB_CTX *get_thread_default_context(void)
{
if (!RUN_ONCE(&default_context_init, default_context_do_init))
return NULL;
return CRYPTO_THREAD_get_local(&default_context_thread_local);
}
static OSSL_LIB_CTX *get_default_context(void)
{
OSSL_LIB_CTX *current_defctx = get_thread_default_context();
if (current_defctx == NULL)
current_defctx = &default_context_int;
return current_defctx;
}
static int set_default_context(OSSL_LIB_CTX *defctx)
{
if (defctx == &default_context_int)
defctx = NULL;
return CRYPTO_THREAD_set_local(&default_context_thread_local, defctx);
}
#endif
OSSL_LIB_CTX *OSSL_LIB_CTX_new(void)
{
OSSL_LIB_CTX *ctx = OPENSSL_zalloc(sizeof(*ctx));
if (ctx != NULL && !context_init(ctx)) {
OPENSSL_free(ctx);
ctx = NULL;
}
return ctx;
}
#ifndef FIPS_MODULE
OSSL_LIB_CTX *OSSL_LIB_CTX_new_from_dispatch(const OSSL_CORE_HANDLE *handle,
const OSSL_DISPATCH *in)
{
OSSL_LIB_CTX *ctx = OSSL_LIB_CTX_new();
if (ctx == NULL)
return NULL;
if (!ossl_bio_init_core(ctx, in)) {
OSSL_LIB_CTX_free(ctx);
return NULL;
}
return ctx;
}
OSSL_LIB_CTX *OSSL_LIB_CTX_new_child(const OSSL_CORE_HANDLE *handle,
const OSSL_DISPATCH *in)
{
OSSL_LIB_CTX *ctx = OSSL_LIB_CTX_new_from_dispatch(handle, in);
if (ctx == NULL)
return NULL;
if (!ossl_provider_init_as_child(ctx, handle, in)) {
OSSL_LIB_CTX_free(ctx);
return NULL;
}
ctx->ischild = 1;
return ctx;
}
int OSSL_LIB_CTX_load_config(OSSL_LIB_CTX *ctx, const char *config_file)
{
return CONF_modules_load_file_ex(ctx, config_file, NULL, 0) > 0;
}
#endif
void OSSL_LIB_CTX_free(OSSL_LIB_CTX *ctx)
{
- if (ossl_lib_ctx_is_default(ctx))
+ if (ctx == NULL || ossl_lib_ctx_is_default(ctx))
return;
#ifndef FIPS_MODULE
if (ctx->ischild)
ossl_provider_deinit_child(ctx);
#endif
context_deinit(ctx);
OPENSSL_free(ctx);
}
#ifndef FIPS_MODULE
OSSL_LIB_CTX *OSSL_LIB_CTX_get0_global_default(void)
{
if (!RUN_ONCE(&default_context_init, default_context_do_init))
return NULL;
return &default_context_int;
}
OSSL_LIB_CTX *OSSL_LIB_CTX_set0_default(OSSL_LIB_CTX *libctx)
{
OSSL_LIB_CTX *current_defctx;
if ((current_defctx = get_default_context()) != NULL) {
if (libctx != NULL)
set_default_context(libctx);
return current_defctx;
}
return NULL;
}
void ossl_release_default_drbg_ctx(void)
{
int dynidx = default_context_int.dyn_indexes[OSSL_LIB_CTX_DRBG_INDEX];
/* early release of the DRBG in global default libctx, no locking */
if (dynidx != -1) {
void *data;
data = CRYPTO_get_ex_data(&default_context_int.data, dynidx);
ossl_rand_ctx_free(data);
CRYPTO_set_ex_data(&default_context_int.data, dynidx, NULL);
}
}
#endif
OSSL_LIB_CTX *ossl_lib_ctx_get_concrete(OSSL_LIB_CTX *ctx)
{
#ifndef FIPS_MODULE
if (ctx == NULL)
return get_default_context();
#endif
return ctx;
}
int ossl_lib_ctx_is_default(OSSL_LIB_CTX *ctx)
{
#ifndef FIPS_MODULE
if (ctx == NULL || ctx == get_default_context())
return 1;
#endif
return 0;
}
int ossl_lib_ctx_is_global_default(OSSL_LIB_CTX *ctx)
{
#ifndef FIPS_MODULE
if (ossl_lib_ctx_get_concrete(ctx) == &default_context_int)
return 1;
#endif
return 0;
}
static void ossl_lib_ctx_generic_new(void *parent_ign, void *ptr_ign,
CRYPTO_EX_DATA *ad, int index,
long argl_ign, void *argp)
{
const OSSL_LIB_CTX_METHOD *meth = argp;
OSSL_LIB_CTX *ctx = ossl_crypto_ex_data_get_ossl_lib_ctx(ad);
void *ptr = meth->new_func(ctx);
if (ptr != NULL) {
if (!CRYPTO_THREAD_write_lock(ctx->lock))
/*
* Can't return something, so best to hope that something will
* fail later. :(
*/
return;
CRYPTO_set_ex_data(ad, index, ptr);
CRYPTO_THREAD_unlock(ctx->lock);
}
}
static void ossl_lib_ctx_generic_free(void *parent_ign, void *ptr,
CRYPTO_EX_DATA *ad, int index,
long argl_ign, void *argp)
{
const OSSL_LIB_CTX_METHOD *meth = argp;
meth->free_func(ptr);
}
static int ossl_lib_ctx_init_index(OSSL_LIB_CTX *ctx, int static_index,
const OSSL_LIB_CTX_METHOD *meth)
{
int idx;
ctx = ossl_lib_ctx_get_concrete(ctx);
if (ctx == NULL)
return 0;
idx = ossl_crypto_get_ex_new_index_ex(ctx, CRYPTO_EX_INDEX_OSSL_LIB_CTX, 0,
(void *)meth,
ossl_lib_ctx_generic_new,
NULL, ossl_lib_ctx_generic_free,
meth->priority);
if (idx < 0)
return 0;
ctx->dyn_indexes[static_index] = idx;
return 1;
}
void *ossl_lib_ctx_get_data(OSSL_LIB_CTX *ctx, int index,
const OSSL_LIB_CTX_METHOD *meth)
{
void *data = NULL;
int dynidx;
ctx = ossl_lib_ctx_get_concrete(ctx);
if (ctx == NULL)
return NULL;
if (!CRYPTO_THREAD_read_lock(ctx->lock))
return NULL;
dynidx = ctx->dyn_indexes[index];
CRYPTO_THREAD_unlock(ctx->lock);
if (dynidx != -1) {
if (!CRYPTO_THREAD_read_lock(ctx->index_locks[index]))
return NULL;
if (!CRYPTO_THREAD_read_lock(ctx->lock)) {
CRYPTO_THREAD_unlock(ctx->index_locks[index]);
return NULL;
}
data = CRYPTO_get_ex_data(&ctx->data, dynidx);
CRYPTO_THREAD_unlock(ctx->lock);
CRYPTO_THREAD_unlock(ctx->index_locks[index]);
return data;
}
if (!CRYPTO_THREAD_write_lock(ctx->index_locks[index]))
return NULL;
if (!CRYPTO_THREAD_write_lock(ctx->lock)) {
CRYPTO_THREAD_unlock(ctx->index_locks[index]);
return NULL;
}
dynidx = ctx->dyn_indexes[index];
if (dynidx != -1) {
data = CRYPTO_get_ex_data(&ctx->data, dynidx);
CRYPTO_THREAD_unlock(ctx->lock);
CRYPTO_THREAD_unlock(ctx->index_locks[index]);
return data;
}
if (!ossl_lib_ctx_init_index(ctx, index, meth)) {
CRYPTO_THREAD_unlock(ctx->lock);
CRYPTO_THREAD_unlock(ctx->index_locks[index]);
return NULL;
}
CRYPTO_THREAD_unlock(ctx->lock);
/*
* The alloc call ensures there's a value there. We release the ctx->lock
* for this, because the allocation itself may recursively call
* ossl_lib_ctx_get_data for other indexes (never this one). The allocation
* will itself aquire the ctx->lock when it actually comes to store the
* allocated data (see ossl_lib_ctx_generic_new() above). We call
* ossl_crypto_alloc_ex_data_intern() here instead of CRYPTO_alloc_ex_data().
* They do the same thing except that the latter calls CRYPTO_get_ex_data()
* as well - which we must not do without holding the ctx->lock.
*/
if (ossl_crypto_alloc_ex_data_intern(CRYPTO_EX_INDEX_OSSL_LIB_CTX, NULL,
&ctx->data, ctx->dyn_indexes[index])) {
if (!CRYPTO_THREAD_read_lock(ctx->lock))
goto end;
data = CRYPTO_get_ex_data(&ctx->data, ctx->dyn_indexes[index]);
CRYPTO_THREAD_unlock(ctx->lock);
}
end:
CRYPTO_THREAD_unlock(ctx->index_locks[index]);
return data;
}
OSSL_EX_DATA_GLOBAL *ossl_lib_ctx_get_ex_data_global(OSSL_LIB_CTX *ctx)
{
ctx = ossl_lib_ctx_get_concrete(ctx);
if (ctx == NULL)
return NULL;
return &ctx->global;
}
int ossl_lib_ctx_run_once(OSSL_LIB_CTX *ctx, unsigned int idx,
ossl_lib_ctx_run_once_fn run_once_fn)
{
int done = 0, ret = 0;
ctx = ossl_lib_ctx_get_concrete(ctx);
if (ctx == NULL)
return 0;
if (!CRYPTO_THREAD_read_lock(ctx->oncelock))
return 0;
done = ctx->run_once_done[idx];
if (done)
ret = ctx->run_once_ret[idx];
CRYPTO_THREAD_unlock(ctx->oncelock);
if (done)
return ret;
if (!CRYPTO_THREAD_write_lock(ctx->oncelock))
return 0;
if (ctx->run_once_done[idx]) {
ret = ctx->run_once_ret[idx];
CRYPTO_THREAD_unlock(ctx->oncelock);
return ret;
}
ret = run_once_fn(ctx);
ctx->run_once_done[idx] = 1;
ctx->run_once_ret[idx] = ret;
CRYPTO_THREAD_unlock(ctx->oncelock);
return ret;
}
int ossl_lib_ctx_onfree(OSSL_LIB_CTX *ctx, ossl_lib_ctx_onfree_fn onfreefn)
{
struct ossl_lib_ctx_onfree_list_st *newonfree
= OPENSSL_malloc(sizeof(*newonfree));
if (newonfree == NULL)
return 0;
newonfree->fn = onfreefn;
newonfree->next = ctx->onfreelist;
ctx->onfreelist = newonfree;
return 1;
}
const char *ossl_lib_ctx_get_descriptor(OSSL_LIB_CTX *libctx)
{
#ifdef FIPS_MODULE
return "FIPS internal library context";
#else
if (ossl_lib_ctx_is_global_default(libctx))
return "Global default library context";
if (ossl_lib_ctx_is_default(libctx))
return "Thread-local default library context";
return "Non-default library context";
#endif
}
diff --git a/crypto/openssl/crypto/ec/ecdsa_ossl.c b/crypto/openssl/crypto/ec/ecdsa_ossl.c
index 4b54a30cf9bc..775b7ec911be 100644
--- a/crypto/openssl/crypto/ec/ecdsa_ossl.c
+++ b/crypto/openssl/crypto/ec/ecdsa_ossl.c
@@ -1,486 +1,494 @@
/*
* 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);
+
+ if ((order = EC_GROUP_get0_order(group)) == NULL) {
+ ERR_raise(ERR_LIB_EC, ERR_R_EC_LIB);
+ goto err;
+ }
/* 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 (!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 (!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 (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);
+ if ((order = EC_GROUP_get0_order(group)) == NULL) {
+ ERR_raise(ERR_LIB_EC, ERR_R_EC_LIB);
+ goto err;
+ }
+
i = BN_num_bits(order);
/*
* Need to truncate digest if it is too long: first truncate whole bytes.
*/
if (8 * dgst_len > i)
dgst_len = (i + 7) / 8;
if (!BN_bin2bn(dgst, dgst_len, m)) {
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/engine/eng_table.c b/crypto/openssl/crypto/engine/eng_table.c
index 9dc3144bbfd7..6280965cc026 100644
--- a/crypto/openssl/crypto/engine/eng_table.c
+++ b/crypto/openssl/crypto/engine/eng_table.c
@@ -1,314 +1,316 @@
/*
- * 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
*/
#include "internal/cryptlib.h"
#include <openssl/evp.h>
#include <openssl/lhash.h>
#include <openssl/trace.h>
#include "eng_local.h"
/* The type of the items in the table */
struct st_engine_pile {
/* The 'nid' of this algorithm/mode */
int nid;
/* ENGINEs that implement this algorithm/mode. */
STACK_OF(ENGINE) *sk;
/* The default ENGINE to perform this algorithm/mode. */
ENGINE *funct;
/*
* Zero if 'sk' is newer than the cached 'funct', non-zero otherwise
*/
int uptodate;
};
/* The type exposed in eng_local.h */
struct st_engine_table {
LHASH_OF(ENGINE_PILE) piles;
}; /* ENGINE_TABLE */
typedef struct st_engine_pile_doall {
engine_table_doall_cb *cb;
void *arg;
} ENGINE_PILE_DOALL;
/* Global flags (ENGINE_TABLE_FLAG_***). */
static unsigned int table_flags = 0;
/* API function manipulating 'table_flags' */
unsigned int ENGINE_get_table_flags(void)
{
return table_flags;
}
void ENGINE_set_table_flags(unsigned int flags)
{
table_flags = flags;
}
/* Internal functions for the "piles" hash table */
static unsigned long engine_pile_hash(const ENGINE_PILE *c)
{
return c->nid;
}
static int engine_pile_cmp(const ENGINE_PILE *a, const ENGINE_PILE *b)
{
return a->nid - b->nid;
}
static int int_table_check(ENGINE_TABLE **t, int create)
{
LHASH_OF(ENGINE_PILE) *lh;
if (*t)
return 1;
if (!create)
return 0;
if ((lh = lh_ENGINE_PILE_new(engine_pile_hash, engine_pile_cmp)) == NULL)
return 0;
*t = (ENGINE_TABLE *)lh;
return 1;
}
/*
* Privately exposed (via eng_local.h) functions for adding and/or removing
* ENGINEs from the implementation table
*/
int engine_table_register(ENGINE_TABLE **table, ENGINE_CLEANUP_CB *cleanup,
ENGINE *e, const int *nids, int num_nids,
int setdefault)
{
int ret = 0, added = 0;
ENGINE_PILE tmplate, *fnd;
if (!CRYPTO_THREAD_write_lock(global_engine_lock))
return 0;
if (!(*table))
added = 1;
if (!int_table_check(table, 1))
goto end;
/* The cleanup callback needs to be added */
if (added && !engine_cleanup_add_first(cleanup)) {
lh_ENGINE_PILE_free(&(*table)->piles);
*table = NULL;
goto end;
}
while (num_nids--) {
tmplate.nid = *nids;
fnd = lh_ENGINE_PILE_retrieve(&(*table)->piles, &tmplate);
if (!fnd) {
fnd = OPENSSL_malloc(sizeof(*fnd));
if (fnd == NULL)
goto end;
fnd->uptodate = 1;
fnd->nid = *nids;
fnd->sk = sk_ENGINE_new_null();
if (!fnd->sk) {
OPENSSL_free(fnd);
goto end;
}
fnd->funct = NULL;
(void)lh_ENGINE_PILE_insert(&(*table)->piles, fnd);
if (lh_ENGINE_PILE_retrieve(&(*table)->piles, &tmplate) != fnd) {
sk_ENGINE_free(fnd->sk);
OPENSSL_free(fnd);
goto end;
}
}
/* A registration shouldn't add duplicate entries */
(void)sk_ENGINE_delete_ptr(fnd->sk, e);
/*
* if 'setdefault', this ENGINE goes to the head of the list
*/
if (!sk_ENGINE_push(fnd->sk, e))
goto end;
/* "touch" this ENGINE_PILE */
fnd->uptodate = 0;
if (setdefault) {
if (!engine_unlocked_init(e)) {
ERR_raise(ERR_LIB_ENGINE, ENGINE_R_INIT_FAILED);
goto end;
}
if (fnd->funct)
engine_unlocked_finish(fnd->funct, 0);
fnd->funct = e;
fnd->uptodate = 1;
}
nids++;
}
ret = 1;
end:
CRYPTO_THREAD_unlock(global_engine_lock);
return ret;
}
static void int_unregister_cb(ENGINE_PILE *pile, ENGINE *e)
{
int n;
/* Iterate the 'c->sk' stack removing any occurrence of 'e' */
while ((n = sk_ENGINE_find(pile->sk, e)) >= 0) {
(void)sk_ENGINE_delete(pile->sk, n);
pile->uptodate = 0;
}
if (pile->funct == e) {
engine_unlocked_finish(e, 0);
pile->funct = NULL;
}
}
IMPLEMENT_LHASH_DOALL_ARG(ENGINE_PILE, ENGINE);
void engine_table_unregister(ENGINE_TABLE **table, ENGINE *e)
{
if (!CRYPTO_THREAD_write_lock(global_engine_lock))
/* Can't return a value. :( */
return;
if (int_table_check(table, 0))
lh_ENGINE_PILE_doall_ENGINE(&(*table)->piles, int_unregister_cb, e);
CRYPTO_THREAD_unlock(global_engine_lock);
}
static void int_cleanup_cb_doall(ENGINE_PILE *p)
{
if (p == NULL)
return;
sk_ENGINE_free(p->sk);
if (p->funct)
engine_unlocked_finish(p->funct, 0);
OPENSSL_free(p);
}
void engine_table_cleanup(ENGINE_TABLE **table)
{
if (!CRYPTO_THREAD_write_lock(global_engine_lock))
return;
if (*table) {
lh_ENGINE_PILE_doall(&(*table)->piles, int_cleanup_cb_doall);
lh_ENGINE_PILE_free(&(*table)->piles);
*table = NULL;
}
CRYPTO_THREAD_unlock(global_engine_lock);
}
/* return a functional reference for a given 'nid' */
ENGINE *ossl_engine_table_select(ENGINE_TABLE **table, int nid,
const char *f, int l)
{
ENGINE *ret = NULL;
ENGINE_PILE tmplate, *fnd = NULL;
int initres, loop = 0;
#ifndef OPENSSL_NO_AUTOLOAD_CONFIG
/* Load the config before trying to check if engines are available */
OPENSSL_init_crypto(OPENSSL_INIT_LOAD_CONFIG, NULL);
#endif
if (!(*table)) {
OSSL_TRACE3(ENGINE_TABLE,
"%s:%d, nid=%d, nothing registered!\n",
f, l, nid);
return NULL;
}
- ERR_set_mark();
+
if (!CRYPTO_THREAD_write_lock(global_engine_lock))
- goto end;
+ return NULL;
+
+ ERR_set_mark();
/*
* Check again inside the lock otherwise we could race against cleanup
* operations. But don't worry about a debug printout
*/
if (!int_table_check(table, 0))
goto end;
tmplate.nid = nid;
fnd = lh_ENGINE_PILE_retrieve(&(*table)->piles, &tmplate);
if (!fnd)
goto end;
if (fnd->funct && engine_unlocked_init(fnd->funct)) {
OSSL_TRACE4(ENGINE_TABLE,
"%s:%d, nid=%d, using ENGINE '%s' cached\n",
f, l, nid, fnd->funct->id);
ret = fnd->funct;
goto end;
}
if (fnd->uptodate) {
ret = fnd->funct;
goto end;
}
trynext:
ret = sk_ENGINE_value(fnd->sk, loop++);
if (!ret) {
OSSL_TRACE3(ENGINE_TABLE,
"%s:%d, nid=%d, "
"no registered implementations would initialise\n",
f, l, nid);
goto end;
}
/* Try to initialise the ENGINE? */
if ((ret->funct_ref > 0) || !(table_flags & ENGINE_TABLE_FLAG_NOINIT))
initres = engine_unlocked_init(ret);
else
initres = 0;
if (initres) {
/* Update 'funct' */
if ((fnd->funct != ret) && engine_unlocked_init(ret)) {
/* If there was a previous default we release it. */
if (fnd->funct)
engine_unlocked_finish(fnd->funct, 0);
fnd->funct = ret;
OSSL_TRACE4(ENGINE_TABLE,
"%s:%d, nid=%d, setting default to '%s'\n",
f, l, nid, ret->id);
}
OSSL_TRACE4(ENGINE_TABLE,
"%s:%d, nid=%d, using newly initialised '%s'\n",
f, l, nid, ret->id);
goto end;
}
goto trynext;
end:
/*
* If it failed, it is unlikely to succeed again until some future
* registrations have taken place. In all cases, we cache.
*/
if (fnd)
fnd->uptodate = 1;
if (ret)
OSSL_TRACE4(ENGINE_TABLE,
"%s:%d, nid=%d, caching ENGINE '%s'\n",
f, l, nid, ret->id);
else
OSSL_TRACE3(ENGINE_TABLE,
"%s:%d, nid=%d, caching 'no matching ENGINE'\n",
f, l, nid);
CRYPTO_THREAD_unlock(global_engine_lock);
/*
* Whatever happened, any failed init()s are not failures in this
* context, so clear our error state.
*/
ERR_pop_to_mark();
return ret;
}
/* Table enumeration */
static void int_dall(const ENGINE_PILE *pile, ENGINE_PILE_DOALL *dall)
{
dall->cb(pile->nid, pile->sk, pile->funct, dall->arg);
}
IMPLEMENT_LHASH_DOALL_ARG_CONST(ENGINE_PILE, ENGINE_PILE_DOALL);
void engine_table_doall(ENGINE_TABLE *table, engine_table_doall_cb *cb,
void *arg)
{
ENGINE_PILE_DOALL dall;
dall.cb = cb;
dall.arg = arg;
if (table)
lh_ENGINE_PILE_doall_ENGINE_PILE_DOALL(&table->piles, int_dall, &dall);
}
diff --git a/crypto/openssl/crypto/evp/ctrl_params_translate.c b/crypto/openssl/crypto/evp/ctrl_params_translate.c
index dcd53b43f92b..de6c215e205a 100644
--- a/crypto/openssl/crypto/evp/ctrl_params_translate.c
+++ b/crypto/openssl/crypto/evp/ctrl_params_translate.c
@@ -1,2875 +1,2874 @@
/*
- * 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
* https://www.openssl.org/source/license.html
*/
/*
* Some ctrls depend on deprecated functionality. We trust that this is
* functionality that remains internally even when 'no-deprecated' is
* configured. When we drop #legacy EVP_PKEYs, this source should be
* possible to drop as well.
*/
#include "internal/deprecated.h"
#include <string.h>
/* The following includes get us all the EVP_PKEY_CTRL macros */
#include <openssl/dh.h>
#include <openssl/dsa.h>
#include <openssl/ec.h>
#include <openssl/rsa.h>
#include <openssl/kdf.h>
/* This include gets us all the OSSL_PARAM key string macros */
#include <openssl/core_names.h>
#include <openssl/err.h>
#include <openssl/evperr.h>
#include <openssl/params.h>
#include "internal/nelem.h"
#include "internal/cryptlib.h"
#include "internal/ffc.h"
#include "crypto/evp.h"
#include "crypto/dh.h"
#include "crypto/ec.h"
struct translation_ctx_st; /* Forwarding */
struct translation_st; /* Forwarding */
/*
* The fixup_args functions are called with the following parameters:
*
* |state| The state we're called in, explained further at the
* end of this comment.
* |translation| The translation item, to be pilfered for data as
* necessary.
* |ctx| The translation context, which contains copies of
* the following arguments, applicable according to
* the caller. All of the attributes in this context
* may be freely modified by the fixup_args function.
* For cleanup, call cleanup_translation_ctx().
*
* The |state| tells the fixup_args function something about the caller and
* what they may expect:
*
* PKEY The fixup_args function has been called
* from an EVP_PKEY payload getter / setter,
* and is fully responsible for getting or
* setting the requested data. With this
* state, the fixup_args function is expected
* to use or modify |*params|, depending on
* |action_type|.
*
* PRE_CTRL_TO_PARAMS The fixup_args function has been called
* POST_CTRL_TO_PARAMS from EVP_PKEY_CTX_ctrl(), to help with
* translating the ctrl data to an OSSL_PARAM
* element or back. The calling sequence is
* as follows:
*
* 1. fixup_args(PRE_CTRL_TO_PARAMS, ...)
* 2. EVP_PKEY_CTX_set_params() or
* EVP_PKEY_CTX_get_params()
* 3. fixup_args(POST_CTRL_TO_PARAMS, ...)
*
* With the PRE_CTRL_TO_PARAMS state, the
* fixup_args function is expected to modify
* the passed |*params| in whatever way
* necessary, when |action_type == SET|.
* With the POST_CTRL_TO_PARAMS state, the
* fixup_args function is expected to modify
* the passed |p2| in whatever way necessary,
* when |action_type == GET|.
*
* The return value from the fixup_args call
* with the POST_CTRL_TO_PARAMS state becomes
* the return value back to EVP_PKEY_CTX_ctrl().
*
* CLEANUP_CTRL_TO_PARAMS The cleanup_args functions has been called
* from EVP_PKEY_CTX_ctrl(), to clean up what
* the fixup_args function has done, if needed.
*
*
* PRE_CTRL_STR_TO_PARAMS The fixup_args function has been called
* POST_CTRL_STR_TO_PARAMS from EVP_PKEY_CTX_ctrl_str(), to help with
* translating the ctrl_str data to an
* OSSL_PARAM element or back. The calling
* sequence is as follows:
*
* 1. fixup_args(PRE_CTRL_STR_TO_PARAMS, ...)
* 2. EVP_PKEY_CTX_set_params() or
* EVP_PKEY_CTX_get_params()
* 3. fixup_args(POST_CTRL_STR_TO_PARAMS, ...)
*
* With the PRE_CTRL_STR_TO_PARAMS state,
* the fixup_args function is expected to
* modify the passed |*params| in whatever
* way necessary, when |action_type == SET|.
* With the POST_CTRL_STR_TO_PARAMS state,
* the fixup_args function is only expected
* to return a value.
*
* CLEANUP_CTRL_STR_TO_PARAMS The cleanup_args functions has been called
* from EVP_PKEY_CTX_ctrl_str(), to clean up
* what the fixup_args function has done, if
* needed.
*
* PRE_PARAMS_TO_CTRL The fixup_args function has been called
* POST_PARAMS_TO_CTRL from EVP_PKEY_CTX_get_params() or
* EVP_PKEY_CTX_set_params(), to help with
* translating the OSSL_PARAM data to the
* corresponding EVP_PKEY_CTX_ctrl() arguments
* or the other way around. The calling
* sequence is as follows:
*
* 1. fixup_args(PRE_PARAMS_TO_CTRL, ...)
* 2. EVP_PKEY_CTX_ctrl()
* 3. fixup_args(POST_PARAMS_TO_CTRL, ...)
*
* With the PRE_PARAMS_TO_CTRL state, the
* fixup_args function is expected to modify
* the passed |p1| and |p2| in whatever way
* necessary, when |action_type == SET|.
* With the POST_PARAMS_TO_CTRL state, the
* fixup_args function is expected to
* modify the passed |*params| in whatever
* way necessary, when |action_type == GET|.
*
* CLEANUP_PARAMS_TO_CTRL The cleanup_args functions has been called
* from EVP_PKEY_CTX_get_params() or
* EVP_PKEY_CTX_set_params(), to clean up what
* the fixup_args function has done, if needed.
*/
enum state {
PKEY,
PRE_CTRL_TO_PARAMS, POST_CTRL_TO_PARAMS, CLEANUP_CTRL_TO_PARAMS,
PRE_CTRL_STR_TO_PARAMS, POST_CTRL_STR_TO_PARAMS, CLEANUP_CTRL_STR_TO_PARAMS,
PRE_PARAMS_TO_CTRL, POST_PARAMS_TO_CTRL, CLEANUP_PARAMS_TO_CTRL
};
enum action {
NONE = 0, GET = 1, SET = 2
};
typedef int fixup_args_fn(enum state state,
const struct translation_st *translation,
struct translation_ctx_st *ctx);
typedef int cleanup_args_fn(enum state state,
const struct translation_st *translation,
struct translation_ctx_st *ctx);
struct translation_ctx_st {
/*
* The EVP_PKEY_CTX, for calls on that structure, to be pilfered for data
* as necessary.
*/
EVP_PKEY_CTX *pctx;
/*
* The action type (GET or SET). This may be 0 in some cases, and should
* be modified by the fixup_args function in the PRE states. It should
* otherwise remain untouched once set.
*/
enum action action_type;
/*
* For ctrl to params translation, the actual ctrl command number used.
* For params to ctrl translation, 0.
*/
int ctrl_cmd;
/*
* For ctrl_str to params translation, the actual ctrl command string
* used. In this case, the (string) value is always passed as |p2|.
* For params to ctrl translation, this is NULL. Along with it is also
* and indicator whether it matched |ctrl_str| or |ctrl_hexstr| in the
* translation item.
*/
const char *ctrl_str;
int ishex;
/* the ctrl-style int argument. */
int p1;
/* the ctrl-style void* argument. */
void *p2;
/* a size, for passing back the |p2| size where applicable */
size_t sz;
/* pointer to the OSSL_PARAM-style params array. */
OSSL_PARAM *params;
/*-
* The following are used entirely internally by the fixup_args functions
* and should not be touched by the callers, at all.
*/
/*
* Copy of the ctrl-style void* argument, if the fixup_args function
* needs to manipulate |p2| but wants to remember original.
*/
void *orig_p2;
/* Diverse types of storage for the needy. */
char name_buf[OSSL_MAX_NAME_SIZE];
void *allocated_buf;
void *bufp;
size_t buflen;
};
struct translation_st {
/*-
* What this table item does.
*
* If the item has this set to 0, it means that both GET and SET are
* supported, and |fixup_args| will determine which it is. This is to
* support translations of ctrls where the action type depends on the
* value of |p1| or |p2| (ctrls are really bi-directional, but are
* seldom used that way).
*
* This can be also used in the lookup template when it looks up by
* OSSL_PARAM key, to indicate if a setter or a getter called.
*/
enum action action_type;
/*-
* Conditions, for params->ctrl translations.
*
* In table item, |keytype1| and |keytype2| can be set to -1 to indicate
* that this item supports all key types (or rather, that |fixup_args|
* will check and return an error if it's not supported).
* Any of these may be set to 0 to indicate that they are unset.
*/
int keytype1; /* The EVP_PKEY_XXX type, i.e. NIDs. #legacy */
int keytype2; /* Another EVP_PKEY_XXX type, used for aliases */
int optype; /* The operation type */
/*
* Lookup and translation attributes
*
* |ctrl_num|, |ctrl_str|, |ctrl_hexstr| and |param_key| are lookup
* attributes.
*
* |ctrl_num| may be 0 or that |param_key| may be NULL in the table item,
* but not at the same time. If they are, they are simply not used for
* lookup.
* When |ctrl_num| == 0, no ctrl will be called. Likewise, when
* |param_key| == NULL, no OSSL_PARAM setter/getter will be called.
* In that case the treatment of the translation item relies entirely on
* |fixup_args|, which is then assumed to have side effects.
*
* As a special case, it's possible to set |ctrl_hexstr| and assign NULL
* to |ctrl_str|. That will signal to default_fixup_args() that the
* value must always be interpreted as hex.
*/
int ctrl_num; /* EVP_PKEY_CTRL_xxx */
const char *ctrl_str; /* The corresponding ctrl string */
const char *ctrl_hexstr; /* The alternative "hex{str}" ctrl string */
const char *param_key; /* The corresponding OSSL_PARAM key */
/*
* The appropriate OSSL_PARAM data type. This may be 0 to indicate that
* this OSSL_PARAM may have more than one data type, depending on input
* material. In this case, |fixup_args| is expected to check and handle
* it.
*/
unsigned int param_data_type;
/*
* Fixer functions
*
* |fixup_args| is always called before (for SET) or after (for GET)
* the actual ctrl / OSSL_PARAM function.
*/
fixup_args_fn *fixup_args;
};
/*-
* Fixer function implementations
* ==============================
*/
/*
* default_check isn't a fixer per se, but rather a helper function to
* perform certain standard checks.
*/
static int default_check(enum state state,
const struct translation_st *translation,
const struct translation_ctx_st *ctx)
{
switch (state) {
default:
break;
case PRE_CTRL_TO_PARAMS:
if (!ossl_assert(translation != NULL)) {
ERR_raise(ERR_LIB_EVP, EVP_R_COMMAND_NOT_SUPPORTED);
return -2;
}
if (!ossl_assert(translation->param_key != 0)
|| !ossl_assert(translation->param_data_type != 0)) {
ERR_raise(ERR_LIB_EVP, ERR_R_INTERNAL_ERROR);
return -1;
}
break;
case PRE_CTRL_STR_TO_PARAMS:
/*
* For ctrl_str to params translation, we allow direct use of
* OSSL_PARAM keys as ctrl_str keys. Therefore, it's possible that
* we end up with |translation == NULL|, which is fine. The fixup
* function will have to deal with it carefully.
*/
if (translation != NULL) {
if (!ossl_assert(translation->action_type != GET)) {
ERR_raise(ERR_LIB_EVP, EVP_R_COMMAND_NOT_SUPPORTED);
return -2;
}
if (!ossl_assert(translation->param_key != NULL)
|| !ossl_assert(translation->param_data_type != 0)) {
ERR_raise(ERR_LIB_EVP, ERR_R_INTERNAL_ERROR);
return 0;
}
}
break;
case PRE_PARAMS_TO_CTRL:
case POST_PARAMS_TO_CTRL:
if (!ossl_assert(translation != NULL)) {
ERR_raise(ERR_LIB_EVP, EVP_R_COMMAND_NOT_SUPPORTED);
return -2;
}
if (!ossl_assert(translation->ctrl_num != 0)
|| !ossl_assert(translation->param_data_type != 0)) {
ERR_raise(ERR_LIB_EVP, ERR_R_INTERNAL_ERROR);
return -1;
}
}
/* Nothing else to check */
return 1;
}
/*-
* default_fixup_args fixes up all sorts of arguments, governed by the
* diverse attributes in the translation item. It covers all "standard"
* base ctrl functionality, meaning it can handle basic conversion of
* data between p1+p2 (SET) or return value+p2 (GET) as long as the values
* don't have extra semantics (such as NIDs, OIDs, that sort of stuff).
* Extra semantics must be handled via specific fixup_args functions.
*
* The following states and action type combinations have standard handling
* done in this function:
*
* PRE_CTRL_TO_PARAMS, 0 - ERROR. action type must be
* determined by a fixup function.
* PRE_CTRL_TO_PARAMS, SET | GET - |p1| and |p2| are converted to an
* OSSL_PARAM according to the data
* type given in |translattion|.
* For OSSL_PARAM_UNSIGNED_INTEGER,
* a BIGNUM passed as |p2| is accepted.
* POST_CTRL_TO_PARAMS, GET - If the OSSL_PARAM data type is a
* STRING or PTR type, |p1| is set
* to the OSSL_PARAM return size, and
* |p2| is set to the string.
* PRE_CTRL_STR_TO_PARAMS, !SET - ERROR. That combination is not
* supported.
* PRE_CTRL_STR_TO_PARAMS, SET - |p2| is taken as a string, and is
* converted to an OSSL_PARAM in a
* standard manner, guided by the
* param key and data type from
* |translation|.
* PRE_PARAMS_TO_CTRL, SET - the OSSL_PARAM is converted to
* |p1| and |p2| according to the
* data type given in |translation|
* For OSSL_PARAM_UNSIGNED_INTEGER,
* if |p2| is non-NULL, then |*p2|
* is assigned a BIGNUM, otherwise
* |p1| is assigned an unsigned int.
* POST_PARAMS_TO_CTRL, GET - |p1| and |p2| are converted to
* an OSSL_PARAM, in the same manner
* as for the combination of
* PRE_CTRL_TO_PARAMS, SET.
*/
static int default_fixup_args(enum state state,
const struct translation_st *translation,
struct translation_ctx_st *ctx)
{
int ret;
if ((ret = default_check(state, translation, ctx)) <= 0)
return ret;
switch (state) {
default:
/* For states this function should never have been called with */
ERR_raise_data(ERR_LIB_EVP, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED,
"[action:%d, state:%d]", ctx->action_type, state);
return 0;
/*
* PRE_CTRL_TO_PARAMS and POST_CTRL_TO_PARAMS handle ctrl to params
* translations. PRE_CTRL_TO_PARAMS is responsible for preparing
* |*params|, and POST_CTRL_TO_PARAMS is responsible for bringing the
* result back to |*p2| and the return value.
*/
case PRE_CTRL_TO_PARAMS:
/* This is ctrl to params translation, so we need an OSSL_PARAM key */
if (ctx->action_type == NONE) {
/*
* No action type is an error here. That's a case for a
* special fixup function.
*/
ERR_raise_data(ERR_LIB_EVP, ERR_R_UNSUPPORTED,
"[action:%d, state:%d]", ctx->action_type, state);
return 0;
}
if (translation->optype != 0) {
if ((EVP_PKEY_CTX_IS_SIGNATURE_OP(ctx->pctx)
&& ctx->pctx->op.sig.algctx == NULL)
|| (EVP_PKEY_CTX_IS_DERIVE_OP(ctx->pctx)
&& ctx->pctx->op.kex.algctx == NULL)
|| (EVP_PKEY_CTX_IS_ASYM_CIPHER_OP(ctx->pctx)
&& ctx->pctx->op.ciph.algctx == NULL)
|| (EVP_PKEY_CTX_IS_KEM_OP(ctx->pctx)
&& ctx->pctx->op.encap.algctx == NULL)
/*
* The following may be unnecessary, but we have them
* for good measure...
*/
|| (EVP_PKEY_CTX_IS_GEN_OP(ctx->pctx)
&& ctx->pctx->op.keymgmt.genctx == NULL)
|| (EVP_PKEY_CTX_IS_FROMDATA_OP(ctx->pctx)
&& ctx->pctx->op.keymgmt.genctx == NULL)) {
ERR_raise(ERR_LIB_EVP, EVP_R_COMMAND_NOT_SUPPORTED);
/* Uses the same return values as EVP_PKEY_CTX_ctrl */
return -2;
}
}
/*
* OSSL_PARAM_construct_TYPE() works equally well for both SET and GET.
*/
switch (translation->param_data_type) {
case OSSL_PARAM_INTEGER:
*ctx->params = OSSL_PARAM_construct_int(translation->param_key,
&ctx->p1);
break;
case OSSL_PARAM_UNSIGNED_INTEGER:
/*
* BIGNUMs are passed via |p2|. For all ctrl's that just want
* to pass a simple integer via |p1|, |p2| is expected to be
* NULL.
*
* Note that this allocates a buffer, which the cleanup function
* must deallocate.
*/
if (ctx->p2 != NULL) {
if (ctx->action_type == SET) {
ctx->buflen = BN_num_bytes(ctx->p2);
if ((ctx->allocated_buf =
OPENSSL_malloc(ctx->buflen)) == NULL) {
ERR_raise(ERR_LIB_EVP, ERR_R_MALLOC_FAILURE);
return 0;
}
if (BN_bn2nativepad(ctx->p2,
ctx->allocated_buf, ctx->buflen) < 0) {
OPENSSL_free(ctx->allocated_buf);
ctx->allocated_buf = NULL;
return 0;
}
*ctx->params =
OSSL_PARAM_construct_BN(translation->param_key,
ctx->allocated_buf,
ctx->buflen);
} else {
/*
* No support for getting a BIGNUM by ctrl, this needs
* fixup_args function support.
*/
ERR_raise_data(ERR_LIB_EVP, ERR_R_UNSUPPORTED,
"[action:%d, state:%d] trying to get a "
"BIGNUM via ctrl call",
ctx->action_type, state);
return 0;
}
} else {
*ctx->params =
OSSL_PARAM_construct_uint(translation->param_key,
(unsigned int *)&ctx->p1);
}
break;
case OSSL_PARAM_UTF8_STRING:
*ctx->params =
OSSL_PARAM_construct_utf8_string(translation->param_key,
ctx->p2, (size_t)ctx->p1);
break;
case OSSL_PARAM_UTF8_PTR:
*ctx->params =
OSSL_PARAM_construct_utf8_ptr(translation->param_key,
ctx->p2, (size_t)ctx->p1);
break;
case OSSL_PARAM_OCTET_STRING:
*ctx->params =
OSSL_PARAM_construct_octet_string(translation->param_key,
ctx->p2, (size_t)ctx->p1);
break;
case OSSL_PARAM_OCTET_PTR:
*ctx->params =
OSSL_PARAM_construct_octet_ptr(translation->param_key,
ctx->p2, (size_t)ctx->p1);
break;
}
break;
case POST_CTRL_TO_PARAMS:
/*
* Because EVP_PKEY_CTX_ctrl() returns the length of certain objects
* as its return value, we need to ensure that we do it here as well,
* for the OSSL_PARAM data types where this makes sense.
*/
if (ctx->action_type == GET) {
switch (translation->param_data_type) {
case OSSL_PARAM_UTF8_STRING:
case OSSL_PARAM_UTF8_PTR:
case OSSL_PARAM_OCTET_STRING:
case OSSL_PARAM_OCTET_PTR:
ctx->p1 = (int)ctx->params[0].return_size;
break;
}
}
break;
/*
* PRE_CTRL_STR_TO_PARAMS and POST_CTRL_STR_TO_PARAMS handle ctrl_str to
* params translations. PRE_CTRL_TO_PARAMS is responsible for preparing
* |*params|, and POST_CTRL_TO_PARAMS currently has nothing to do, since
* there's no support for getting data via ctrl_str calls.
*/
case PRE_CTRL_STR_TO_PARAMS:
{
/* This is ctrl_str to params translation */
const char *tmp_ctrl_str = ctx->ctrl_str;
const char *orig_ctrl_str = ctx->ctrl_str;
const char *orig_value = ctx->p2;
const OSSL_PARAM *settable = NULL;
int exists = 0;
/* Only setting is supported here */
if (ctx->action_type != SET) {
ERR_raise_data(ERR_LIB_EVP, EVP_R_COMMAND_NOT_SUPPORTED,
"[action:%d, state:%d] only setting allowed",
ctx->action_type, state);
return 0;
}
/*
* If no translation exists, we simply pass the control string
* unmodified.
*/
if (translation != NULL) {
tmp_ctrl_str = ctx->ctrl_str = translation->param_key;
if (ctx->ishex) {
strcpy(ctx->name_buf, "hex");
if (OPENSSL_strlcat(ctx->name_buf, tmp_ctrl_str,
sizeof(ctx->name_buf)) <= 3) {
ERR_raise(ERR_LIB_EVP, ERR_R_INTERNAL_ERROR);
return -1;
}
tmp_ctrl_str = ctx->name_buf;
}
}
settable = EVP_PKEY_CTX_settable_params(ctx->pctx);
if (!OSSL_PARAM_allocate_from_text(ctx->params, settable,
tmp_ctrl_str,
ctx->p2, strlen(ctx->p2),
&exists)) {
if (!exists) {
ERR_raise_data(ERR_LIB_EVP, EVP_R_COMMAND_NOT_SUPPORTED,
"[action:%d, state:%d] name=%s, value=%s",
ctx->action_type, state,
orig_ctrl_str, orig_value);
return -2;
}
return 0;
}
ctx->allocated_buf = ctx->params->data;
ctx->buflen = ctx->params->data_size;
}
break;
case POST_CTRL_STR_TO_PARAMS:
/* Nothing to be done */
break;
/*
* PRE_PARAMS_TO_CTRL and POST_PARAMS_TO_CTRL handle params to ctrl
* translations. PRE_PARAMS_TO_CTRL is responsible for preparing
* |p1| and |p2|, and POST_PARAMS_TO_CTRL is responsible for bringing
* the EVP_PKEY_CTX_ctrl() return value (passed as |p1|) and |p2| back
* to |*params|.
*
* PKEY is treated just like POST_PARAMS_TO_CTRL, making it easy
* for the related fixup_args functions to just set |p1| and |p2|
* appropriately and leave it to this section of code to fix up
* |ctx->params| accordingly.
*/
case PKEY:
case POST_PARAMS_TO_CTRL:
ret = ctx->p1;
/* FALLTHRU */
case PRE_PARAMS_TO_CTRL:
{
/* This is params to ctrl translation */
if (state == PRE_PARAMS_TO_CTRL && ctx->action_type == SET) {
/* For the PRE state, only setting needs some work to be done */
/* When setting, we populate |p1| and |p2| from |*params| */
switch (translation->param_data_type) {
case OSSL_PARAM_INTEGER:
return OSSL_PARAM_get_int(ctx->params, &ctx->p1);
case OSSL_PARAM_UNSIGNED_INTEGER:
if (ctx->p2 != NULL) {
/* BIGNUM passed down with p2 */
if (!OSSL_PARAM_get_BN(ctx->params, ctx->p2))
return 0;
} else {
/* Normal C unsigned int passed down */
if (!OSSL_PARAM_get_uint(ctx->params,
(unsigned int *)&ctx->p1))
return 0;
}
return 1;
case OSSL_PARAM_UTF8_STRING:
return OSSL_PARAM_get_utf8_string(ctx->params,
ctx->p2, ctx->sz);
case OSSL_PARAM_OCTET_STRING:
return OSSL_PARAM_get_octet_string(ctx->params,
&ctx->p2, ctx->sz,
(size_t *)&ctx->p1);
case OSSL_PARAM_OCTET_PTR:
return OSSL_PARAM_get_octet_ptr(ctx->params,
ctx->p2, &ctx->sz);
default:
ERR_raise_data(ERR_LIB_EVP, ERR_R_UNSUPPORTED,
"[action:%d, state:%d] "
"unknown OSSL_PARAM data type %d",
ctx->action_type, state,
translation->param_data_type);
return 0;
}
} else if ((state == POST_PARAMS_TO_CTRL || state == PKEY)
&& ctx->action_type == GET) {
/* For the POST state, only getting needs some work to be done */
unsigned int param_data_type = translation->param_data_type;
size_t size = (size_t)ctx->p1;
if (state == PKEY)
size = ctx->sz;
if (param_data_type == 0) {
/* we must have a fixup_args function to work */
if (!ossl_assert(translation->fixup_args != NULL)) {
ERR_raise(ERR_LIB_EVP, ERR_R_INTERNAL_ERROR);
return 0;
}
param_data_type = ctx->params->data_type;
}
/* When getting, we populate |*params| from |p1| and |p2| */
switch (param_data_type) {
case OSSL_PARAM_INTEGER:
return OSSL_PARAM_set_int(ctx->params, ctx->p1);
case OSSL_PARAM_UNSIGNED_INTEGER:
if (ctx->p2 != NULL) {
/* BIGNUM passed back */
return OSSL_PARAM_set_BN(ctx->params, ctx->p2);
} else {
/* Normal C unsigned int passed back */
return OSSL_PARAM_set_uint(ctx->params,
(unsigned int)ctx->p1);
}
return 0;
case OSSL_PARAM_UTF8_STRING:
return OSSL_PARAM_set_utf8_string(ctx->params, ctx->p2);
case OSSL_PARAM_OCTET_STRING:
return OSSL_PARAM_set_octet_string(ctx->params, ctx->p2,
size);
case OSSL_PARAM_OCTET_PTR:
return OSSL_PARAM_set_octet_ptr(ctx->params, *(void **)ctx->p2,
size);
default:
ERR_raise_data(ERR_LIB_EVP, ERR_R_UNSUPPORTED,
"[action:%d, state:%d] "
"unsupported OSSL_PARAM data type %d",
ctx->action_type, state,
translation->param_data_type);
return 0;
}
} else if (state == PRE_PARAMS_TO_CTRL && ctx->action_type == GET) {
if (translation->param_data_type == OSSL_PARAM_OCTET_PTR)
ctx->p2 = &ctx->bufp;
}
}
/* Any other combination is simply pass-through */
break;
}
return ret;
}
static int
cleanup_translation_ctx(enum state state,
const struct translation_st *translation,
struct translation_ctx_st *ctx)
{
if (ctx->allocated_buf != NULL)
OPENSSL_free(ctx->allocated_buf);
ctx->allocated_buf = NULL;
return 1;
}
/*
* fix_cipher_md fixes up an EVP_CIPHER / EVP_MD to its name on SET,
* and cipher / md name to EVP_MD on GET.
*/
static const char *get_cipher_name(void *cipher)
{
return EVP_CIPHER_get0_name(cipher);
}
static const char *get_md_name(void *md)
{
return EVP_MD_get0_name(md);
}
static const void *get_cipher_by_name(OSSL_LIB_CTX *libctx, const char *name)
{
return evp_get_cipherbyname_ex(libctx, name);
}
static const void *get_md_by_name(OSSL_LIB_CTX *libctx, const char *name)
{
return evp_get_digestbyname_ex(libctx, name);
}
static int fix_cipher_md(enum state state,
const struct translation_st *translation,
struct translation_ctx_st *ctx,
const char *(*get_name)(void *algo),
const void *(*get_algo_by_name)(OSSL_LIB_CTX *libctx,
const char *name))
{
int ret = 1;
if ((ret = default_check(state, translation, ctx)) <= 0)
return ret;
if (state == PRE_CTRL_TO_PARAMS && ctx->action_type == GET) {
/*
* |ctx->p2| contains the address to an EVP_CIPHER or EVP_MD pointer
* to be filled in. We need to remember it, then make |ctx->p2|
* point at a buffer to be filled in with the name, and |ctx->p1|
* with its size. default_fixup_args() will take care of the rest
* for us.
*/
ctx->orig_p2 = ctx->p2;
ctx->p2 = ctx->name_buf;
ctx->p1 = sizeof(ctx->name_buf);
} else if (state == PRE_CTRL_TO_PARAMS && ctx->action_type == SET) {
/*
* In different parts of OpenSSL, this ctrl command is used
* differently. Some calls pass a NID as p1, others pass an
* EVP_CIPHER pointer as p2...
*/
ctx->p2 = (char *)(ctx->p2 == NULL
? OBJ_nid2sn(ctx->p1)
: get_name(ctx->p2));
ctx->p1 = strlen(ctx->p2);
} else if (state == POST_PARAMS_TO_CTRL && ctx->action_type == GET) {
ctx->p2 = (ctx->p2 == NULL ? "" : (char *)get_name(ctx->p2));
ctx->p1 = strlen(ctx->p2);
}
if ((ret = default_fixup_args(state, translation, ctx)) <= 0)
return ret;
if (state == POST_CTRL_TO_PARAMS && ctx->action_type == GET) {
/*
* Here's how we re-use |ctx->orig_p2| that was set in the
* PRE_CTRL_TO_PARAMS state above.
*/
*(void **)ctx->orig_p2 =
(void *)get_algo_by_name(ctx->pctx->libctx, ctx->p2);
ctx->p1 = 1;
} else if (state == PRE_PARAMS_TO_CTRL && ctx->action_type == SET) {
ctx->p2 = (void *)get_algo_by_name(ctx->pctx->libctx, ctx->p2);
ctx->p1 = 0;
}
return ret;
}
static int fix_cipher(enum state state,
const struct translation_st *translation,
struct translation_ctx_st *ctx)
{
return fix_cipher_md(state, translation, ctx,
get_cipher_name, get_cipher_by_name);
}
static int fix_md(enum state state,
const struct translation_st *translation,
struct translation_ctx_st *ctx)
{
return fix_cipher_md(state, translation, ctx,
get_md_name, get_md_by_name);
}
static int fix_distid_len(enum state state,
const struct translation_st *translation,
struct translation_ctx_st *ctx)
{
int ret = default_fixup_args(state, translation, ctx);
if (ret > 0) {
ret = 0;
if ((state == POST_CTRL_TO_PARAMS
|| state == POST_CTRL_STR_TO_PARAMS) && ctx->action_type == GET) {
*(size_t *)ctx->p2 = ctx->sz;
ret = 1;
}
}
return ret;
}
struct kdf_type_map_st {
int kdf_type_num;
const char *kdf_type_str;
};
static int fix_kdf_type(enum state state,
const struct translation_st *translation,
struct translation_ctx_st *ctx,
const struct kdf_type_map_st *kdf_type_map)
{
/*
* The EVP_PKEY_CTRL_DH_KDF_TYPE ctrl command is a bit special, in
* that it's used both for setting a value, and for getting it, all
* depending on the value if |p1|; if |p1| is -2, the backend is
* supposed to place the current kdf type in |p2|, and if not, |p1|
* is interpreted as the new kdf type.
*/
int ret = 0;
if ((ret = default_check(state, translation, ctx)) <= 0)
return ret;
if (state == PRE_CTRL_TO_PARAMS) {
/*
* In |translations|, the initial value for |ctx->action_type| must
* be NONE.
*/
if (!ossl_assert(ctx->action_type == NONE))
return 0;
/* The action type depends on the value of *p1 */
if (ctx->p1 == -2) {
/*
* The OSSL_PARAMS getter needs space to store a copy of the kdf
* type string. We use |ctx->name_buf|, which has enough space
* allocated.
*
* (this wouldn't be needed if the OSSL_xxx_PARAM_KDF_TYPE
* had the data type OSSL_PARAM_UTF8_PTR)
*/
ctx->p2 = ctx->name_buf;
ctx->p1 = sizeof(ctx->name_buf);
ctx->action_type = GET;
} else {
ctx->action_type = SET;
}
}
if ((ret = default_check(state, translation, ctx)) <= 0)
return ret;
if ((state == PRE_CTRL_TO_PARAMS && ctx->action_type == SET)
|| (state == POST_PARAMS_TO_CTRL && ctx->action_type == GET)) {
ret = -2;
/* Convert KDF type numbers to strings */
for (; kdf_type_map->kdf_type_str != NULL; kdf_type_map++)
if (ctx->p1 == kdf_type_map->kdf_type_num) {
ctx->p2 = (char *)kdf_type_map->kdf_type_str;
ret = 1;
break;
}
if (ret <= 0)
goto end;
ctx->p1 = strlen(ctx->p2);
}
if ((ret = default_fixup_args(state, translation, ctx)) <= 0)
return ret;
if ((state == POST_CTRL_TO_PARAMS && ctx->action_type == GET)
|| (state == PRE_PARAMS_TO_CTRL && ctx->action_type == SET)) {
ctx->p1 = ret = -1;
/* Convert KDF type strings to numbers */
for (; kdf_type_map->kdf_type_str != NULL; kdf_type_map++)
if (OPENSSL_strcasecmp(ctx->p2, kdf_type_map->kdf_type_str) == 0) {
ctx->p1 = kdf_type_map->kdf_type_num;
ret = 1;
break;
}
ctx->p2 = NULL;
} else if (state == PRE_PARAMS_TO_CTRL && ctx->action_type == GET) {
ctx->p1 = -2;
}
end:
return ret;
}
/* EVP_PKEY_CTRL_DH_KDF_TYPE */
static int fix_dh_kdf_type(enum state state,
const struct translation_st *translation,
struct translation_ctx_st *ctx)
{
static const struct kdf_type_map_st kdf_type_map[] = {
{ EVP_PKEY_DH_KDF_NONE, "" },
{ EVP_PKEY_DH_KDF_X9_42, OSSL_KDF_NAME_X942KDF_ASN1 },
{ 0, NULL }
};
return fix_kdf_type(state, translation, ctx, kdf_type_map);
}
/* EVP_PKEY_CTRL_EC_KDF_TYPE */
static int fix_ec_kdf_type(enum state state,
const struct translation_st *translation,
struct translation_ctx_st *ctx)
{
static const struct kdf_type_map_st kdf_type_map[] = {
{ EVP_PKEY_ECDH_KDF_NONE, "" },
{ EVP_PKEY_ECDH_KDF_X9_63, OSSL_KDF_NAME_X963KDF },
{ 0, NULL }
};
return fix_kdf_type(state, translation, ctx, kdf_type_map);
}
/* EVP_PKEY_CTRL_DH_KDF_OID, EVP_PKEY_CTRL_GET_DH_KDF_OID, ...??? */
static int fix_oid(enum state state,
const struct translation_st *translation,
struct translation_ctx_st *ctx)
{
int ret;
if ((ret = default_check(state, translation, ctx)) <= 0)
return ret;
if ((state == PRE_CTRL_TO_PARAMS && ctx->action_type == SET)
|| (state == POST_PARAMS_TO_CTRL && ctx->action_type == GET)) {
/*
* We're translating from ctrl to params and setting the OID, or
* we're translating from params to ctrl and getting the OID.
* Either way, |ctx->p2| points at an ASN1_OBJECT, and needs to have
* that replaced with the corresponding name.
* default_fixup_args() will then be able to convert that to the
* corresponding OSSL_PARAM.
*/
OBJ_obj2txt(ctx->name_buf, sizeof(ctx->name_buf), ctx->p2, 0);
ctx->p2 = (char *)ctx->name_buf;
ctx->p1 = 0; /* let default_fixup_args() figure out the length */
}
if ((ret = default_fixup_args(state, translation, ctx)) <= 0)
return ret;
if ((state == PRE_PARAMS_TO_CTRL && ctx->action_type == SET)
|| (state == POST_CTRL_TO_PARAMS && ctx->action_type == GET)) {
/*
* We're translating from ctrl to params and setting the OID name,
* or we're translating from params to ctrl and getting the OID
* name. Either way, default_fixup_args() has placed the OID name
* in |ctx->p2|, all we need to do now is to replace that with the
* corresponding ASN1_OBJECT.
*/
ctx->p2 = (ASN1_OBJECT *)OBJ_txt2obj(ctx->p2, 0);
}
return ret;
}
/* EVP_PKEY_CTRL_DH_NID */
static int fix_dh_nid(enum state state,
const struct translation_st *translation,
struct translation_ctx_st *ctx)
{
int ret;
if ((ret = default_check(state, translation, ctx)) <= 0)
return ret;
/* This is only settable */
if (ctx->action_type != SET)
return 0;
if (state == PRE_CTRL_TO_PARAMS) {
if ((ctx->p2 = (char *)ossl_ffc_named_group_get_name
(ossl_ffc_uid_to_dh_named_group(ctx->p1))) == NULL) {
ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_VALUE);
return 0;
}
ctx->p1 = 0;
}
return default_fixup_args(state, translation, ctx);
}
/* EVP_PKEY_CTRL_DH_RFC5114 */
static int fix_dh_nid5114(enum state state,
const struct translation_st *translation,
struct translation_ctx_st *ctx)
{
int ret;
if ((ret = default_check(state, translation, ctx)) <= 0)
return ret;
/* This is only settable */
if (ctx->action_type != SET)
return 0;
switch (state) {
case PRE_CTRL_TO_PARAMS:
if ((ctx->p2 = (char *)ossl_ffc_named_group_get_name
(ossl_ffc_uid_to_dh_named_group(ctx->p1))) == NULL) {
ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_VALUE);
return 0;
}
ctx->p1 = 0;
break;
case PRE_CTRL_STR_TO_PARAMS:
if (ctx->p2 == NULL)
return 0;
if ((ctx->p2 = (char *)ossl_ffc_named_group_get_name
(ossl_ffc_uid_to_dh_named_group(atoi(ctx->p2)))) == NULL) {
ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_VALUE);
return 0;
}
ctx->p1 = 0;
break;
default:
break;
}
return default_fixup_args(state, translation, ctx);
}
/* EVP_PKEY_CTRL_DH_PARAMGEN_TYPE */
static int fix_dh_paramgen_type(enum state state,
const struct translation_st *translation,
struct translation_ctx_st *ctx)
{
int ret;
if ((ret = default_check(state, translation, ctx)) <= 0)
return ret;
/* This is only settable */
if (ctx->action_type != SET)
return 0;
if (state == PRE_CTRL_STR_TO_PARAMS) {
if ((ctx->p2 = (char *)ossl_dh_gen_type_id2name(atoi(ctx->p2)))
== NULL) {
ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_VALUE);
return 0;
}
ctx->p1 = strlen(ctx->p2);
}
return default_fixup_args(state, translation, ctx);
}
/* EVP_PKEY_CTRL_EC_PARAM_ENC */
static int fix_ec_param_enc(enum state state,
const struct translation_st *translation,
struct translation_ctx_st *ctx)
{
int ret;
if ((ret = default_check(state, translation, ctx)) <= 0)
return ret;
/* This is currently only settable */
if (ctx->action_type != SET)
return 0;
if (state == PRE_CTRL_TO_PARAMS) {
switch (ctx->p1) {
case OPENSSL_EC_EXPLICIT_CURVE:
ctx->p2 = OSSL_PKEY_EC_ENCODING_EXPLICIT;
break;
case OPENSSL_EC_NAMED_CURVE:
ctx->p2 = OSSL_PKEY_EC_ENCODING_GROUP;
break;
default:
ret = -2;
goto end;
}
ctx->p1 = 0;
}
if ((ret = default_fixup_args(state, translation, ctx)) <= 0)
return ret;
if (state == PRE_PARAMS_TO_CTRL) {
if (strcmp(ctx->p2, OSSL_PKEY_EC_ENCODING_EXPLICIT) == 0)
ctx->p1 = OPENSSL_EC_EXPLICIT_CURVE;
else if (strcmp(ctx->p2, OSSL_PKEY_EC_ENCODING_GROUP) == 0)
ctx->p1 = OPENSSL_EC_NAMED_CURVE;
else
ctx->p1 = ret = -2;
ctx->p2 = NULL;
}
end:
if (ret == -2)
ERR_raise(ERR_LIB_EVP, EVP_R_COMMAND_NOT_SUPPORTED);
return ret;
}
/* EVP_PKEY_CTRL_EC_PARAMGEN_CURVE_NID */
static int fix_ec_paramgen_curve_nid(enum state state,
const struct translation_st *translation,
struct translation_ctx_st *ctx)
{
char *p2 = NULL;
int ret;
if ((ret = default_check(state, translation, ctx)) <= 0)
return ret;
/* This is currently only settable */
if (ctx->action_type != SET)
return 0;
if (state == PRE_CTRL_TO_PARAMS) {
ctx->p2 = (char *)OBJ_nid2sn(ctx->p1);
ctx->p1 = 0;
} else if (state == PRE_PARAMS_TO_CTRL) {
/*
* We're translating from params to ctrl and setting the curve name.
* The ctrl function needs it to be a NID, but meanwhile, we need
* space to get the curve name from the param. |ctx->name_buf| is
* sufficient for that.
* The double indirection is necessary for default_fixup_args()'s
* call of OSSL_PARAM_get_utf8_string() to be done correctly.
*/
p2 = ctx->name_buf;
ctx->p2 = &p2;
ctx->sz = sizeof(ctx->name_buf);
}
if ((ret = default_fixup_args(state, translation, ctx)) <= 0)
return ret;
if (state == PRE_PARAMS_TO_CTRL) {
ctx->p1 = OBJ_sn2nid(p2);
ctx->p2 = NULL;
}
return ret;
}
/* EVP_PKEY_CTRL_EC_ECDH_COFACTOR */
static int fix_ecdh_cofactor(enum state state,
const struct translation_st *translation,
struct translation_ctx_st *ctx)
{
/*
* The EVP_PKEY_CTRL_EC_ECDH_COFACTOR ctrl command is a bit special, in
* that it's used both for setting a value, and for getting it, all
* depending on the value if |ctx->p1|; if |ctx->p1| is -2, the backend is
* supposed to place the current cofactor mode in |ctx->p2|, and if not,
* |ctx->p1| is interpreted as the new cofactor mode.
*/
int ret = 0;
if (state == PRE_CTRL_TO_PARAMS) {
/*
* The initial value for |ctx->action_type| must be zero.
* evp_pkey_ctrl_to_params() takes it from the translation item.
*/
if (!ossl_assert(ctx->action_type == NONE))
return 0;
/* The action type depends on the value of ctx->p1 */
if (ctx->p1 == -2)
ctx->action_type = GET;
else
ctx->action_type = SET;
} else if (state == PRE_CTRL_STR_TO_PARAMS) {
ctx->action_type = SET;
} else if (state == PRE_PARAMS_TO_CTRL) {
/* The initial value for |ctx->action_type| must not be zero. */
if (!ossl_assert(ctx->action_type != NONE))
return 0;
}
if ((ret = default_check(state, translation, ctx)) <= 0)
return ret;
if (state == PRE_CTRL_TO_PARAMS && ctx->action_type == SET) {
if (ctx->p1 < -1 || ctx->p1 > 1) {
/* Uses the same return value of pkey_ec_ctrl() */
return -2;
}
}
if ((ret = default_fixup_args(state, translation, ctx)) <= 0)
return ret;
if (state == POST_CTRL_TO_PARAMS && ctx->action_type == GET) {
if (ctx->p1 < 0 || ctx->p1 > 1) {
/*
* The provider should return either 0 or 1, any other value is a
* provider error.
*/
ctx->p1 = ret = -1;
}
} else if (state == PRE_PARAMS_TO_CTRL && ctx->action_type == GET) {
ctx->p1 = -2;
}
return ret;
}
/* EVP_PKEY_CTRL_RSA_PADDING, EVP_PKEY_CTRL_GET_RSA_PADDING */
static int fix_rsa_padding_mode(enum state state,
const struct translation_st *translation,
struct translation_ctx_st *ctx)
{
static const OSSL_ITEM str_value_map[] = {
{ RSA_PKCS1_PADDING, "pkcs1" },
{ RSA_NO_PADDING, "none" },
{ RSA_PKCS1_OAEP_PADDING, "oaep" },
{ RSA_PKCS1_OAEP_PADDING, "oeap" },
{ RSA_X931_PADDING, "x931" },
{ RSA_PKCS1_PSS_PADDING, "pss" },
/* Special case, will pass directly as an integer */
{ RSA_PKCS1_WITH_TLS_PADDING, NULL }
};
int ret;
if ((ret = default_check(state, translation, ctx)) <= 0)
return ret;
if (state == PRE_CTRL_TO_PARAMS && ctx->action_type == GET) {
/*
* EVP_PKEY_CTRL_GET_RSA_PADDING returns the padding mode in the
* weirdest way for a ctrl. Instead of doing like all other ctrls
* that return a simple, i.e. just have that as a return value,
* this particular ctrl treats p2 as the address for the int to be
* returned. We must therefore remember |ctx->p2|, then make
* |ctx->p2| point at a buffer to be filled in with the name, and
* |ctx->p1| with its size. default_fixup_args() will take care
* of the rest for us, along with the POST_CTRL_TO_PARAMS && GET
* code section further down.
*/
ctx->orig_p2 = ctx->p2;
ctx->p2 = ctx->name_buf;
ctx->p1 = sizeof(ctx->name_buf);
} else if (state == PRE_CTRL_TO_PARAMS && ctx->action_type == SET) {
/*
* Ideally, we should use utf8 strings for the diverse padding modes.
* We only came here because someone called EVP_PKEY_CTX_ctrl(),
* though, and since that can reasonably be seen as legacy code
* that uses the diverse RSA macros for the padding mode, and we
* know that at least our providers can handle the numeric modes,
* we take the cheap route for now.
*
* The other solution would be to match |ctx->p1| against entries
* in str_value_map and pass the corresponding string. However,
* since we don't have a string for RSA_PKCS1_WITH_TLS_PADDING,
* we have to do this same hack at least for that one.
*
* Since the "official" data type for the RSA padding mode is utf8
* string, we cannot count on default_fixup_args(). Instead, we
* build the OSSL_PARAM item ourselves and return immediately.
*/
ctx->params[0] = OSSL_PARAM_construct_int(translation->param_key,
&ctx->p1);
return 1;
} else if (state == POST_PARAMS_TO_CTRL && ctx->action_type == GET) {
size_t i;
/*
* The EVP_PKEY_CTX_get_params() caller may have asked for a utf8
* string, or may have asked for an integer of some sort. If they
* ask for an integer, we respond directly. If not, we translate
* the response from the ctrl function into a string.
*/
switch (ctx->params->data_type) {
case OSSL_PARAM_INTEGER:
return OSSL_PARAM_get_int(ctx->params, &ctx->p1);
case OSSL_PARAM_UNSIGNED_INTEGER:
return OSSL_PARAM_get_uint(ctx->params, (unsigned int *)&ctx->p1);
default:
break;
}
for (i = 0; i < OSSL_NELEM(str_value_map); i++) {
if (ctx->p1 == (int)str_value_map[i].id)
break;
}
if (i == OSSL_NELEM(str_value_map)) {
ERR_raise_data(ERR_LIB_RSA, RSA_R_UNKNOWN_PADDING_TYPE,
"[action:%d, state:%d] padding number %d",
ctx->action_type, state, ctx->p1);
return -2;
}
/*
* If we don't have a string, we can't do anything. The caller
* should have asked for a number...
*/
if (str_value_map[i].ptr == NULL) {
ERR_raise(ERR_LIB_EVP, EVP_R_COMMAND_NOT_SUPPORTED);
return -2;
}
ctx->p2 = str_value_map[i].ptr;
ctx->p1 = strlen(ctx->p2);
}
if ((ret = default_fixup_args(state, translation, ctx)) <= 0)
return ret;
if ((ctx->action_type == SET && state == PRE_PARAMS_TO_CTRL)
|| (ctx->action_type == GET && state == POST_CTRL_TO_PARAMS)) {
size_t i;
for (i = 0; i < OSSL_NELEM(str_value_map); i++) {
if (strcmp(ctx->p2, str_value_map[i].ptr) == 0)
break;
}
if (i == OSSL_NELEM(str_value_map)) {
ERR_raise_data(ERR_LIB_RSA, RSA_R_UNKNOWN_PADDING_TYPE,
"[action:%d, state:%d] padding name %s",
ctx->action_type, state, ctx->p1);
ctx->p1 = ret = -2;
} else if (state == POST_CTRL_TO_PARAMS) {
/* EVP_PKEY_CTRL_GET_RSA_PADDING weirdness explained further up */
*(int *)ctx->orig_p2 = str_value_map[i].id;
} else {
ctx->p1 = str_value_map[i].id;
}
ctx->p2 = NULL;
}
return ret;
}
/* EVP_PKEY_CTRL_RSA_PSS_SALTLEN, EVP_PKEY_CTRL_GET_RSA_PSS_SALTLEN */
static int fix_rsa_pss_saltlen(enum state state,
const struct translation_st *translation,
struct translation_ctx_st *ctx)
{
static const OSSL_ITEM str_value_map[] = {
{ (unsigned int)RSA_PSS_SALTLEN_DIGEST, "digest" },
{ (unsigned int)RSA_PSS_SALTLEN_MAX, "max" },
{ (unsigned int)RSA_PSS_SALTLEN_AUTO, "auto" }
};
int ret;
if ((ret = default_check(state, translation, ctx)) <= 0)
return ret;
if (state == PRE_CTRL_TO_PARAMS && ctx->action_type == GET) {
/*
* EVP_PKEY_CTRL_GET_RSA_PSS_SALTLEN returns the saltlen by filling
* in the int pointed at by p2. This is potentially as weird as
* the way EVP_PKEY_CTRL_GET_RSA_PADDING works, except that saltlen
* might be a negative value, so it wouldn't work as a legitimate
* return value.
* In any case, we must therefore remember |ctx->p2|, then make
* |ctx->p2| point at a buffer to be filled in with the name, and
* |ctx->p1| with its size. default_fixup_args() will take care
* of the rest for us, along with the POST_CTRL_TO_PARAMS && GET
* code section further down.
*/
ctx->orig_p2 = ctx->p2;
ctx->p2 = ctx->name_buf;
ctx->p1 = sizeof(ctx->name_buf);
} else if ((ctx->action_type == SET && state == PRE_CTRL_TO_PARAMS)
|| (ctx->action_type == GET && state == POST_PARAMS_TO_CTRL)) {
size_t i;
for (i = 0; i < OSSL_NELEM(str_value_map); i++) {
if (ctx->p1 == (int)str_value_map[i].id)
break;
}
if (i == OSSL_NELEM(str_value_map)) {
BIO_snprintf(ctx->name_buf, sizeof(ctx->name_buf), "%d", ctx->p1);
} else {
/* This won't truncate but it will quiet static analysers */
strncpy(ctx->name_buf, str_value_map[i].ptr, sizeof(ctx->name_buf) - 1);
ctx->name_buf[sizeof(ctx->name_buf) - 1] = '\0';
}
ctx->p2 = ctx->name_buf;
ctx->p1 = strlen(ctx->p2);
}
if ((ret = default_fixup_args(state, translation, ctx)) <= 0)
return ret;
if ((ctx->action_type == SET && state == PRE_PARAMS_TO_CTRL)
|| (ctx->action_type == GET && state == POST_CTRL_TO_PARAMS)) {
size_t i;
int val;
for (i = 0; i < OSSL_NELEM(str_value_map); i++) {
if (strcmp(ctx->p2, str_value_map[i].ptr) == 0)
break;
}
val = i == OSSL_NELEM(str_value_map) ? atoi(ctx->p2)
: (int)str_value_map[i].id;
if (state == POST_CTRL_TO_PARAMS) {
/*
* EVP_PKEY_CTRL_GET_RSA_PSS_SALTLEN weirdness explained further
* up
*/
*(int *)ctx->orig_p2 = val;
} else {
ctx->p1 = val;
}
ctx->p2 = NULL;
}
return ret;
}
/* EVP_PKEY_CTRL_HKDF_MODE */
static int fix_hkdf_mode(enum state state,
const struct translation_st *translation,
struct translation_ctx_st *ctx)
{
static const OSSL_ITEM str_value_map[] = {
{ EVP_KDF_HKDF_MODE_EXTRACT_AND_EXPAND, "EXTRACT_AND_EXPAND" },
{ EVP_KDF_HKDF_MODE_EXTRACT_ONLY, "EXTRACT_ONLY" },
{ EVP_KDF_HKDF_MODE_EXPAND_ONLY, "EXPAND_ONLY" }
};
int ret;
if ((ret = default_check(state, translation, ctx)) <= 0)
return ret;
if ((ctx->action_type == SET && state == PRE_CTRL_TO_PARAMS)
|| (ctx->action_type == GET && state == POST_PARAMS_TO_CTRL)) {
size_t i;
for (i = 0; i < OSSL_NELEM(str_value_map); i++) {
if (ctx->p1 == (int)str_value_map[i].id)
break;
}
if (i == OSSL_NELEM(str_value_map))
return 0;
ctx->p2 = str_value_map[i].ptr;
ctx->p1 = strlen(ctx->p2);
}
if ((ret = default_fixup_args(state, translation, ctx)) <= 0)
return ret;
if ((ctx->action_type == SET && state == PRE_PARAMS_TO_CTRL)
|| (ctx->action_type == GET && state == POST_CTRL_TO_PARAMS)) {
size_t i;
for (i = 0; i < OSSL_NELEM(str_value_map); i++) {
if (strcmp(ctx->p2, str_value_map[i].ptr) == 0)
break;
}
if (i == OSSL_NELEM(str_value_map))
return 0;
if (state == POST_CTRL_TO_PARAMS)
ret = str_value_map[i].id;
else
ctx->p1 = str_value_map[i].id;
ctx->p2 = NULL;
}
return 1;
}
/*-
* Payload getters
* ===============
*
* These all get the data they want, then call default_fixup_args() as
* a post-ctrl GET fixup. They all get NULL ctx, ctrl_cmd, ctrl_str,
* p1, sz
*/
/* Pilfering DH, DSA and EC_KEY */
static int get_payload_group_name(enum state state,
const struct translation_st *translation,
struct translation_ctx_st *ctx)
{
EVP_PKEY *pkey = ctx->p2;
ctx->p2 = NULL;
switch (EVP_PKEY_get_base_id(pkey)) {
#ifndef OPENSSL_NO_DH
case EVP_PKEY_DH:
{
const DH *dh = EVP_PKEY_get0_DH(pkey);
int uid = DH_get_nid(dh);
if (uid != NID_undef) {
const DH_NAMED_GROUP *dh_group =
ossl_ffc_uid_to_dh_named_group(uid);
ctx->p2 = (char *)ossl_ffc_named_group_get_name(dh_group);
}
}
break;
#endif
#ifndef OPENSSL_NO_EC
case EVP_PKEY_EC:
{
const EC_GROUP *grp =
EC_KEY_get0_group(EVP_PKEY_get0_EC_KEY(pkey));
int nid = NID_undef;
if (grp != NULL)
nid = EC_GROUP_get_curve_name(grp);
if (nid != NID_undef)
ctx->p2 = (char *)OSSL_EC_curve_nid2name(nid);
}
break;
#endif
default:
ERR_raise(ERR_LIB_EVP, EVP_R_UNSUPPORTED_KEY_TYPE);
return 0;
}
/*
* Quietly ignoring unknown groups matches the behaviour on the provider
* side.
*/
if (ctx->p2 == NULL)
return 1;
ctx->p1 = strlen(ctx->p2);
return default_fixup_args(state, translation, ctx);
}
static int get_payload_private_key(enum state state,
const struct translation_st *translation,
struct translation_ctx_st *ctx)
{
EVP_PKEY *pkey = ctx->p2;
ctx->p2 = NULL;
if (ctx->params->data_type != OSSL_PARAM_UNSIGNED_INTEGER)
return 0;
switch (EVP_PKEY_get_base_id(pkey)) {
#ifndef OPENSSL_NO_DH
case EVP_PKEY_DH:
{
const DH *dh = EVP_PKEY_get0_DH(pkey);
ctx->p2 = (BIGNUM *)DH_get0_priv_key(dh);
}
break;
#endif
#ifndef OPENSSL_NO_EC
case EVP_PKEY_EC:
{
const EC_KEY *ec = EVP_PKEY_get0_EC_KEY(pkey);
ctx->p2 = (BIGNUM *)EC_KEY_get0_private_key(ec);
}
break;
#endif
default:
ERR_raise(ERR_LIB_EVP, EVP_R_UNSUPPORTED_KEY_TYPE);
return 0;
}
return default_fixup_args(state, translation, ctx);
}
static int get_payload_public_key(enum state state,
const struct translation_st *translation,
struct translation_ctx_st *ctx)
{
EVP_PKEY *pkey = ctx->p2;
unsigned char *buf = NULL;
int ret;
ctx->p2 = NULL;
switch (EVP_PKEY_get_base_id(pkey)) {
#ifndef OPENSSL_NO_DH
case EVP_PKEY_DHX:
case EVP_PKEY_DH:
switch (ctx->params->data_type) {
case OSSL_PARAM_OCTET_STRING:
ctx->sz = ossl_dh_key2buf(EVP_PKEY_get0_DH(pkey), &buf, 0, 1);
ctx->p2 = buf;
break;
case OSSL_PARAM_UNSIGNED_INTEGER:
ctx->p2 = (void *)DH_get0_pub_key(EVP_PKEY_get0_DH(pkey));
break;
default:
return 0;
}
break;
#endif
#ifndef OPENSSL_NO_DSA
case EVP_PKEY_DSA:
if (ctx->params->data_type == OSSL_PARAM_UNSIGNED_INTEGER) {
ctx->p2 = (void *)DSA_get0_pub_key(EVP_PKEY_get0_DSA(pkey));
break;
}
return 0;
#endif
#ifndef OPENSSL_NO_EC
case EVP_PKEY_EC:
if (ctx->params->data_type == OSSL_PARAM_OCTET_STRING) {
const EC_KEY *eckey = EVP_PKEY_get0_EC_KEY(pkey);
BN_CTX *bnctx = BN_CTX_new_ex(ossl_ec_key_get_libctx(eckey));
const EC_GROUP *ecg = EC_KEY_get0_group(eckey);
const EC_POINT *point = EC_KEY_get0_public_key(eckey);
if (bnctx == NULL)
return 0;
ctx->sz = EC_POINT_point2buf(ecg, point,
POINT_CONVERSION_COMPRESSED,
&buf, bnctx);
ctx->p2 = buf;
BN_CTX_free(bnctx);
break;
}
return 0;
#endif
default:
ERR_raise(ERR_LIB_EVP, EVP_R_UNSUPPORTED_KEY_TYPE);
return 0;
}
ret = default_fixup_args(state, translation, ctx);
OPENSSL_free(buf);
return ret;
}
static int get_payload_bn(enum state state,
const struct translation_st *translation,
struct translation_ctx_st *ctx, const BIGNUM *bn)
{
if (bn == NULL)
return 0;
if (ctx->params->data_type != OSSL_PARAM_UNSIGNED_INTEGER)
return 0;
ctx->p2 = (BIGNUM *)bn;
return default_fixup_args(state, translation, ctx);
}
static int get_dh_dsa_payload_p(enum state state,
const struct translation_st *translation,
struct translation_ctx_st *ctx)
{
const BIGNUM *bn = NULL;
EVP_PKEY *pkey = ctx->p2;
switch (EVP_PKEY_get_base_id(pkey)) {
#ifndef OPENSSL_NO_DH
case EVP_PKEY_DH:
bn = DH_get0_p(EVP_PKEY_get0_DH(pkey));
break;
#endif
#ifndef OPENSSL_NO_DSA
case EVP_PKEY_DSA:
bn = DSA_get0_p(EVP_PKEY_get0_DSA(pkey));
break;
#endif
default:
ERR_raise(ERR_LIB_EVP, EVP_R_UNSUPPORTED_KEY_TYPE);
}
return get_payload_bn(state, translation, ctx, bn);
}
static int get_dh_dsa_payload_q(enum state state,
const struct translation_st *translation,
struct translation_ctx_st *ctx)
{
const BIGNUM *bn = NULL;
switch (EVP_PKEY_get_base_id(ctx->p2)) {
#ifndef OPENSSL_NO_DH
case EVP_PKEY_DH:
bn = DH_get0_q(EVP_PKEY_get0_DH(ctx->p2));
break;
#endif
#ifndef OPENSSL_NO_DSA
case EVP_PKEY_DSA:
bn = DSA_get0_q(EVP_PKEY_get0_DSA(ctx->p2));
break;
#endif
}
return get_payload_bn(state, translation, ctx, bn);
}
static int get_dh_dsa_payload_g(enum state state,
const struct translation_st *translation,
struct translation_ctx_st *ctx)
{
const BIGNUM *bn = NULL;
switch (EVP_PKEY_get_base_id(ctx->p2)) {
#ifndef OPENSSL_NO_DH
case EVP_PKEY_DH:
bn = DH_get0_g(EVP_PKEY_get0_DH(ctx->p2));
break;
#endif
#ifndef OPENSSL_NO_DSA
case EVP_PKEY_DSA:
bn = DSA_get0_g(EVP_PKEY_get0_DSA(ctx->p2));
break;
#endif
}
return get_payload_bn(state, translation, ctx, bn);
}
static int get_payload_int(enum state state,
const struct translation_st *translation,
struct translation_ctx_st *ctx,
const int val)
{
if (ctx->params->data_type != OSSL_PARAM_INTEGER)
return 0;
ctx->p1 = val;
ctx->p2 = NULL;
return default_fixup_args(state, translation, ctx);
}
static int get_ec_decoded_from_explicit_params(enum state state,
const struct translation_st *translation,
struct translation_ctx_st *ctx)
{
int val = 0;
EVP_PKEY *pkey = ctx->p2;
switch (EVP_PKEY_base_id(pkey)) {
#ifndef OPENSSL_NO_EC
case EVP_PKEY_EC:
val = EC_KEY_decoded_from_explicit_params(EVP_PKEY_get0_EC_KEY(pkey));
if (val < 0) {
ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_KEY);
return 0;
}
break;
#endif
default:
ERR_raise(ERR_LIB_EVP, EVP_R_UNSUPPORTED_KEY_TYPE);
return 0;
}
return get_payload_int(state, translation, ctx, val);
}
static int get_rsa_payload_n(enum state state,
const struct translation_st *translation,
struct translation_ctx_st *ctx)
{
const BIGNUM *bn = NULL;
if (EVP_PKEY_get_base_id(ctx->p2) != EVP_PKEY_RSA
&& EVP_PKEY_get_base_id(ctx->p2) != EVP_PKEY_RSA_PSS)
return 0;
bn = RSA_get0_n(EVP_PKEY_get0_RSA(ctx->p2));
return get_payload_bn(state, translation, ctx, bn);
}
static int get_rsa_payload_e(enum state state,
const struct translation_st *translation,
struct translation_ctx_st *ctx)
{
const BIGNUM *bn = NULL;
if (EVP_PKEY_get_base_id(ctx->p2) != EVP_PKEY_RSA
&& EVP_PKEY_get_base_id(ctx->p2) != EVP_PKEY_RSA_PSS)
return 0;
bn = RSA_get0_e(EVP_PKEY_get0_RSA(ctx->p2));
return get_payload_bn(state, translation, ctx, bn);
}
static int get_rsa_payload_d(enum state state,
const struct translation_st *translation,
struct translation_ctx_st *ctx)
{
const BIGNUM *bn = NULL;
if (EVP_PKEY_get_base_id(ctx->p2) != EVP_PKEY_RSA
&& EVP_PKEY_get_base_id(ctx->p2) != EVP_PKEY_RSA_PSS)
return 0;
bn = RSA_get0_d(EVP_PKEY_get0_RSA(ctx->p2));
return get_payload_bn(state, translation, ctx, bn);
}
static int get_rsa_payload_factor(enum state state,
const struct translation_st *translation,
struct translation_ctx_st *ctx,
size_t factornum)
{
const RSA *r = EVP_PKEY_get0_RSA(ctx->p2);
const BIGNUM *bn = NULL;
switch (factornum) {
case 0:
bn = RSA_get0_p(r);
break;
case 1:
bn = RSA_get0_q(r);
break;
default:
{
size_t pnum = RSA_get_multi_prime_extra_count(r);
const BIGNUM *factors[10];
if (factornum - 2 < pnum
&& RSA_get0_multi_prime_factors(r, factors))
bn = factors[factornum - 2];
}
break;
}
return get_payload_bn(state, translation, ctx, bn);
}
static int get_rsa_payload_exponent(enum state state,
const struct translation_st *translation,
struct translation_ctx_st *ctx,
size_t exponentnum)
{
const RSA *r = EVP_PKEY_get0_RSA(ctx->p2);
const BIGNUM *bn = NULL;
switch (exponentnum) {
case 0:
bn = RSA_get0_dmp1(r);
break;
case 1:
bn = RSA_get0_dmq1(r);
break;
default:
{
size_t pnum = RSA_get_multi_prime_extra_count(r);
const BIGNUM *exps[10], *coeffs[10];
if (exponentnum - 2 < pnum
&& RSA_get0_multi_prime_crt_params(r, exps, coeffs))
bn = exps[exponentnum - 2];
}
break;
}
return get_payload_bn(state, translation, ctx, bn);
}
static int get_rsa_payload_coefficient(enum state state,
const struct translation_st *translation,
struct translation_ctx_st *ctx,
size_t coefficientnum)
{
const RSA *r = EVP_PKEY_get0_RSA(ctx->p2);
const BIGNUM *bn = NULL;
switch (coefficientnum) {
case 0:
bn = RSA_get0_iqmp(r);
break;
default:
{
size_t pnum = RSA_get_multi_prime_extra_count(r);
const BIGNUM *exps[10], *coeffs[10];
if (coefficientnum - 1 < pnum
&& RSA_get0_multi_prime_crt_params(r, exps, coeffs))
bn = coeffs[coefficientnum - 1];
}
break;
}
return get_payload_bn(state, translation, ctx, bn);
}
#define IMPL_GET_RSA_PAYLOAD_FACTOR(n) \
static int \
get_rsa_payload_f##n(enum state state, \
const struct translation_st *translation, \
struct translation_ctx_st *ctx) \
{ \
if (EVP_PKEY_get_base_id(ctx->p2) != EVP_PKEY_RSA \
&& EVP_PKEY_get_base_id(ctx->p2) != EVP_PKEY_RSA_PSS) \
return 0; \
return get_rsa_payload_factor(state, translation, ctx, n - 1); \
}
#define IMPL_GET_RSA_PAYLOAD_EXPONENT(n) \
static int \
get_rsa_payload_e##n(enum state state, \
const struct translation_st *translation, \
struct translation_ctx_st *ctx) \
{ \
if (EVP_PKEY_get_base_id(ctx->p2) != EVP_PKEY_RSA \
&& EVP_PKEY_get_base_id(ctx->p2) != EVP_PKEY_RSA_PSS) \
return 0; \
return get_rsa_payload_exponent(state, translation, ctx, \
n - 1); \
}
#define IMPL_GET_RSA_PAYLOAD_COEFFICIENT(n) \
static int \
get_rsa_payload_c##n(enum state state, \
const struct translation_st *translation, \
struct translation_ctx_st *ctx) \
{ \
if (EVP_PKEY_get_base_id(ctx->p2) != EVP_PKEY_RSA \
&& EVP_PKEY_get_base_id(ctx->p2) != EVP_PKEY_RSA_PSS) \
return 0; \
return get_rsa_payload_coefficient(state, translation, ctx, \
n - 1); \
}
IMPL_GET_RSA_PAYLOAD_FACTOR(1)
IMPL_GET_RSA_PAYLOAD_FACTOR(2)
IMPL_GET_RSA_PAYLOAD_FACTOR(3)
IMPL_GET_RSA_PAYLOAD_FACTOR(4)
IMPL_GET_RSA_PAYLOAD_FACTOR(5)
IMPL_GET_RSA_PAYLOAD_FACTOR(6)
IMPL_GET_RSA_PAYLOAD_FACTOR(7)
IMPL_GET_RSA_PAYLOAD_FACTOR(8)
IMPL_GET_RSA_PAYLOAD_FACTOR(9)
IMPL_GET_RSA_PAYLOAD_FACTOR(10)
IMPL_GET_RSA_PAYLOAD_EXPONENT(1)
IMPL_GET_RSA_PAYLOAD_EXPONENT(2)
IMPL_GET_RSA_PAYLOAD_EXPONENT(3)
IMPL_GET_RSA_PAYLOAD_EXPONENT(4)
IMPL_GET_RSA_PAYLOAD_EXPONENT(5)
IMPL_GET_RSA_PAYLOAD_EXPONENT(6)
IMPL_GET_RSA_PAYLOAD_EXPONENT(7)
IMPL_GET_RSA_PAYLOAD_EXPONENT(8)
IMPL_GET_RSA_PAYLOAD_EXPONENT(9)
IMPL_GET_RSA_PAYLOAD_EXPONENT(10)
IMPL_GET_RSA_PAYLOAD_COEFFICIENT(1)
IMPL_GET_RSA_PAYLOAD_COEFFICIENT(2)
IMPL_GET_RSA_PAYLOAD_COEFFICIENT(3)
IMPL_GET_RSA_PAYLOAD_COEFFICIENT(4)
IMPL_GET_RSA_PAYLOAD_COEFFICIENT(5)
IMPL_GET_RSA_PAYLOAD_COEFFICIENT(6)
IMPL_GET_RSA_PAYLOAD_COEFFICIENT(7)
IMPL_GET_RSA_PAYLOAD_COEFFICIENT(8)
IMPL_GET_RSA_PAYLOAD_COEFFICIENT(9)
static int fix_group_ecx(enum state state,
const struct translation_st *translation,
struct translation_ctx_st *ctx)
{
const char *value = NULL;
switch (state) {
case PRE_PARAMS_TO_CTRL:
if (!EVP_PKEY_CTX_IS_GEN_OP(ctx->pctx))
return 0;
ctx->action_type = NONE;
return 1;
case POST_PARAMS_TO_CTRL:
if (OSSL_PARAM_get_utf8_string_ptr(ctx->params, &value) == 0 ||
OPENSSL_strcasecmp(ctx->pctx->keytype, value) != 0) {
ERR_raise(ERR_LIB_EVP, ERR_R_PASSED_INVALID_ARGUMENT);
ctx->p1 = 0;
return 0;
}
ctx->p1 = 1;
return 1;
default:
return 0;
}
}
/*-
* The translation table itself
* ============================
*/
static const struct translation_st evp_pkey_ctx_translations[] = {
/*
* DistID: we pass it to the backend as an octet string,
* but get it back as a pointer to an octet string.
*
* Note that the EVP_PKEY_CTRL_GET1_ID_LEN is purely for legacy purposes
* that has no separate counterpart in OSSL_PARAM terms, since we get
* the length of the DistID automatically when getting the DistID itself.
*/
{ SET, -1, -1, EVP_PKEY_OP_TYPE_SIG,
EVP_PKEY_CTRL_SET1_ID, "distid", "hexdistid",
OSSL_PKEY_PARAM_DIST_ID, OSSL_PARAM_OCTET_STRING, NULL },
{ GET, -1, -1, -1,
EVP_PKEY_CTRL_GET1_ID, "distid", "hexdistid",
OSSL_PKEY_PARAM_DIST_ID, OSSL_PARAM_OCTET_PTR, NULL },
{ GET, -1, -1, -1,
EVP_PKEY_CTRL_GET1_ID_LEN, NULL, NULL,
OSSL_PKEY_PARAM_DIST_ID, OSSL_PARAM_OCTET_PTR, fix_distid_len },
/*-
* DH & DHX
* ========
*/
/*
* EVP_PKEY_CTRL_DH_KDF_TYPE is used both for setting and getting. The
* fixup function has to handle this...
*/
{ NONE, EVP_PKEY_DHX, 0, EVP_PKEY_OP_DERIVE,
EVP_PKEY_CTRL_DH_KDF_TYPE, NULL, NULL,
OSSL_EXCHANGE_PARAM_KDF_TYPE, OSSL_PARAM_UTF8_STRING,
fix_dh_kdf_type },
{ SET, EVP_PKEY_DHX, 0, EVP_PKEY_OP_DERIVE,
EVP_PKEY_CTRL_DH_KDF_MD, NULL, NULL,
OSSL_EXCHANGE_PARAM_KDF_DIGEST, OSSL_PARAM_UTF8_STRING, fix_md },
{ GET, EVP_PKEY_DHX, 0, EVP_PKEY_OP_DERIVE,
EVP_PKEY_CTRL_GET_DH_KDF_MD, NULL, NULL,
OSSL_EXCHANGE_PARAM_KDF_DIGEST, OSSL_PARAM_UTF8_STRING, fix_md },
{ SET, EVP_PKEY_DHX, 0, EVP_PKEY_OP_DERIVE,
EVP_PKEY_CTRL_DH_KDF_OUTLEN, NULL, NULL,
OSSL_EXCHANGE_PARAM_KDF_OUTLEN, OSSL_PARAM_UNSIGNED_INTEGER, NULL },
{ GET, EVP_PKEY_DHX, 0, EVP_PKEY_OP_DERIVE,
EVP_PKEY_CTRL_GET_DH_KDF_OUTLEN, NULL, NULL,
OSSL_EXCHANGE_PARAM_KDF_OUTLEN, OSSL_PARAM_UNSIGNED_INTEGER, NULL },
{ SET, EVP_PKEY_DHX, 0, EVP_PKEY_OP_DERIVE,
EVP_PKEY_CTRL_DH_KDF_UKM, NULL, NULL,
OSSL_EXCHANGE_PARAM_KDF_UKM, OSSL_PARAM_OCTET_STRING, NULL },
{ GET, EVP_PKEY_DHX, 0, EVP_PKEY_OP_DERIVE,
EVP_PKEY_CTRL_GET_DH_KDF_UKM, NULL, NULL,
OSSL_EXCHANGE_PARAM_KDF_UKM, OSSL_PARAM_OCTET_PTR, NULL },
{ SET, EVP_PKEY_DHX, 0, EVP_PKEY_OP_DERIVE,
EVP_PKEY_CTRL_DH_KDF_OID, NULL, NULL,
OSSL_KDF_PARAM_CEK_ALG, OSSL_PARAM_UTF8_STRING, fix_oid },
{ GET, EVP_PKEY_DHX, 0, EVP_PKEY_OP_DERIVE,
EVP_PKEY_CTRL_GET_DH_KDF_OID, NULL, NULL,
OSSL_KDF_PARAM_CEK_ALG, OSSL_PARAM_UTF8_STRING, fix_oid },
/* DHX Keygen Parameters that are shared with DH */
{ SET, EVP_PKEY_DHX, 0, EVP_PKEY_OP_PARAMGEN,
EVP_PKEY_CTRL_DH_PARAMGEN_TYPE, "dh_paramgen_type", NULL,
OSSL_PKEY_PARAM_FFC_TYPE, OSSL_PARAM_UTF8_STRING, fix_dh_paramgen_type },
{ SET, EVP_PKEY_DHX, 0, EVP_PKEY_OP_PARAMGEN,
EVP_PKEY_CTRL_DH_PARAMGEN_PRIME_LEN, "dh_paramgen_prime_len", NULL,
OSSL_PKEY_PARAM_FFC_PBITS, OSSL_PARAM_UNSIGNED_INTEGER, NULL },
{ SET, EVP_PKEY_DHX, 0, EVP_PKEY_OP_PARAMGEN | EVP_PKEY_OP_KEYGEN,
EVP_PKEY_CTRL_DH_NID, "dh_param", NULL,
OSSL_PKEY_PARAM_GROUP_NAME, OSSL_PARAM_UTF8_STRING, NULL },
{ SET, EVP_PKEY_DHX, 0, EVP_PKEY_OP_PARAMGEN | EVP_PKEY_OP_KEYGEN,
EVP_PKEY_CTRL_DH_RFC5114, "dh_rfc5114", NULL,
OSSL_PKEY_PARAM_GROUP_NAME, OSSL_PARAM_UTF8_STRING, fix_dh_nid5114 },
/* DH Keygen Parameters that are shared with DHX */
{ SET, EVP_PKEY_DH, 0, EVP_PKEY_OP_PARAMGEN,
EVP_PKEY_CTRL_DH_PARAMGEN_TYPE, "dh_paramgen_type", NULL,
OSSL_PKEY_PARAM_FFC_TYPE, OSSL_PARAM_UTF8_STRING, fix_dh_paramgen_type },
{ SET, EVP_PKEY_DH, 0, EVP_PKEY_OP_PARAMGEN,
EVP_PKEY_CTRL_DH_PARAMGEN_PRIME_LEN, "dh_paramgen_prime_len", NULL,
OSSL_PKEY_PARAM_FFC_PBITS, OSSL_PARAM_UNSIGNED_INTEGER, NULL },
{ SET, EVP_PKEY_DH, 0, EVP_PKEY_OP_PARAMGEN | EVP_PKEY_OP_KEYGEN,
EVP_PKEY_CTRL_DH_NID, "dh_param", NULL,
OSSL_PKEY_PARAM_GROUP_NAME, OSSL_PARAM_UTF8_STRING, fix_dh_nid },
{ SET, EVP_PKEY_DH, 0, EVP_PKEY_OP_PARAMGEN | EVP_PKEY_OP_KEYGEN,
EVP_PKEY_CTRL_DH_RFC5114, "dh_rfc5114", NULL,
OSSL_PKEY_PARAM_GROUP_NAME, OSSL_PARAM_UTF8_STRING, fix_dh_nid5114 },
/* DH specific Keygen Parameters */
{ SET, EVP_PKEY_DH, 0, EVP_PKEY_OP_PARAMGEN,
EVP_PKEY_CTRL_DH_PARAMGEN_GENERATOR, "dh_paramgen_generator", NULL,
OSSL_PKEY_PARAM_DH_GENERATOR, OSSL_PARAM_INTEGER, NULL },
/* DHX specific Keygen Parameters */
{ SET, EVP_PKEY_DHX, 0, EVP_PKEY_OP_PARAMGEN,
EVP_PKEY_CTRL_DH_PARAMGEN_SUBPRIME_LEN, "dh_paramgen_subprime_len", NULL,
OSSL_PKEY_PARAM_FFC_QBITS, OSSL_PARAM_UNSIGNED_INTEGER, NULL },
{ SET, EVP_PKEY_DH, 0, EVP_PKEY_OP_DERIVE,
EVP_PKEY_CTRL_DH_PAD, "dh_pad", NULL,
OSSL_EXCHANGE_PARAM_PAD, OSSL_PARAM_UNSIGNED_INTEGER, NULL },
/*-
* DSA
* ===
*/
{ SET, EVP_PKEY_DSA, 0, EVP_PKEY_OP_PARAMGEN,
EVP_PKEY_CTRL_DSA_PARAMGEN_BITS, "dsa_paramgen_bits", NULL,
OSSL_PKEY_PARAM_FFC_PBITS, OSSL_PARAM_UNSIGNED_INTEGER, NULL },
{ SET, EVP_PKEY_DSA, 0, EVP_PKEY_OP_PARAMGEN,
EVP_PKEY_CTRL_DSA_PARAMGEN_Q_BITS, "dsa_paramgen_q_bits", NULL,
OSSL_PKEY_PARAM_FFC_QBITS, OSSL_PARAM_UNSIGNED_INTEGER, NULL },
{ SET, EVP_PKEY_DSA, 0, EVP_PKEY_OP_PARAMGEN,
EVP_PKEY_CTRL_DSA_PARAMGEN_MD, "dsa_paramgen_md", NULL,
OSSL_PKEY_PARAM_FFC_DIGEST, OSSL_PARAM_UTF8_STRING, fix_md },
/*-
* EC
* ==
*/
{ SET, EVP_PKEY_EC, 0, EVP_PKEY_OP_PARAMGEN | EVP_PKEY_OP_KEYGEN,
EVP_PKEY_CTRL_EC_PARAM_ENC, "ec_param_enc", NULL,
OSSL_PKEY_PARAM_EC_ENCODING, OSSL_PARAM_UTF8_STRING, fix_ec_param_enc },
{ SET, EVP_PKEY_EC, 0, EVP_PKEY_OP_PARAMGEN | EVP_PKEY_OP_KEYGEN,
EVP_PKEY_CTRL_EC_PARAMGEN_CURVE_NID, "ec_paramgen_curve", NULL,
OSSL_PKEY_PARAM_GROUP_NAME, OSSL_PARAM_UTF8_STRING,
fix_ec_paramgen_curve_nid },
/*
* EVP_PKEY_CTRL_EC_ECDH_COFACTOR and EVP_PKEY_CTRL_EC_KDF_TYPE are used
* both for setting and getting. The fixup function has to handle this...
*/
{ NONE, EVP_PKEY_EC, 0, EVP_PKEY_OP_DERIVE,
EVP_PKEY_CTRL_EC_ECDH_COFACTOR, "ecdh_cofactor_mode", NULL,
OSSL_EXCHANGE_PARAM_EC_ECDH_COFACTOR_MODE, OSSL_PARAM_INTEGER,
fix_ecdh_cofactor },
{ NONE, EVP_PKEY_EC, 0, EVP_PKEY_OP_DERIVE,
EVP_PKEY_CTRL_EC_KDF_TYPE, NULL, NULL,
OSSL_EXCHANGE_PARAM_KDF_TYPE, OSSL_PARAM_UTF8_STRING, fix_ec_kdf_type },
{ SET, EVP_PKEY_EC, 0, EVP_PKEY_OP_DERIVE,
EVP_PKEY_CTRL_EC_KDF_MD, "ecdh_kdf_md", NULL,
OSSL_EXCHANGE_PARAM_KDF_DIGEST, OSSL_PARAM_UTF8_STRING, fix_md },
{ GET, EVP_PKEY_EC, 0, EVP_PKEY_OP_DERIVE,
EVP_PKEY_CTRL_GET_EC_KDF_MD, NULL, NULL,
OSSL_EXCHANGE_PARAM_KDF_DIGEST, OSSL_PARAM_UTF8_STRING, fix_md },
{ SET, EVP_PKEY_EC, 0, EVP_PKEY_OP_DERIVE,
EVP_PKEY_CTRL_EC_KDF_OUTLEN, NULL, NULL,
OSSL_EXCHANGE_PARAM_KDF_OUTLEN, OSSL_PARAM_UNSIGNED_INTEGER, NULL },
{ GET, EVP_PKEY_EC, 0, EVP_PKEY_OP_DERIVE,
EVP_PKEY_CTRL_GET_EC_KDF_OUTLEN, NULL, NULL,
OSSL_EXCHANGE_PARAM_KDF_OUTLEN, OSSL_PARAM_UNSIGNED_INTEGER, NULL },
{ SET, EVP_PKEY_EC, 0, EVP_PKEY_OP_DERIVE,
EVP_PKEY_CTRL_EC_KDF_UKM, NULL, NULL,
OSSL_EXCHANGE_PARAM_KDF_UKM, OSSL_PARAM_OCTET_STRING, NULL },
{ GET, EVP_PKEY_EC, 0, EVP_PKEY_OP_DERIVE,
EVP_PKEY_CTRL_GET_EC_KDF_UKM, NULL, NULL,
OSSL_EXCHANGE_PARAM_KDF_UKM, OSSL_PARAM_OCTET_PTR, NULL },
/*-
* SM2
* ==
*/
{ SET, EVP_PKEY_SM2, 0, EVP_PKEY_OP_PARAMGEN | EVP_PKEY_OP_KEYGEN,
EVP_PKEY_CTRL_EC_PARAM_ENC, "ec_param_enc", NULL,
OSSL_PKEY_PARAM_EC_ENCODING, OSSL_PARAM_UTF8_STRING, fix_ec_param_enc },
{ SET, EVP_PKEY_SM2, 0, EVP_PKEY_OP_PARAMGEN | EVP_PKEY_OP_KEYGEN,
EVP_PKEY_CTRL_EC_PARAMGEN_CURVE_NID, "ec_paramgen_curve", NULL,
OSSL_PKEY_PARAM_GROUP_NAME, OSSL_PARAM_UTF8_STRING,
fix_ec_paramgen_curve_nid },
/*
* EVP_PKEY_CTRL_EC_ECDH_COFACTOR and EVP_PKEY_CTRL_EC_KDF_TYPE are used
* both for setting and getting. The fixup function has to handle this...
*/
{ NONE, EVP_PKEY_SM2, 0, EVP_PKEY_OP_DERIVE,
EVP_PKEY_CTRL_EC_ECDH_COFACTOR, "ecdh_cofactor_mode", NULL,
OSSL_EXCHANGE_PARAM_EC_ECDH_COFACTOR_MODE, OSSL_PARAM_INTEGER,
fix_ecdh_cofactor },
{ NONE, EVP_PKEY_SM2, 0, EVP_PKEY_OP_DERIVE,
EVP_PKEY_CTRL_EC_KDF_TYPE, NULL, NULL,
OSSL_EXCHANGE_PARAM_KDF_TYPE, OSSL_PARAM_UTF8_STRING, fix_ec_kdf_type },
{ SET, EVP_PKEY_SM2, 0, EVP_PKEY_OP_DERIVE,
EVP_PKEY_CTRL_EC_KDF_MD, "ecdh_kdf_md", NULL,
OSSL_EXCHANGE_PARAM_KDF_DIGEST, OSSL_PARAM_UTF8_STRING, fix_md },
{ GET, EVP_PKEY_SM2, 0, EVP_PKEY_OP_DERIVE,
EVP_PKEY_CTRL_GET_EC_KDF_MD, NULL, NULL,
OSSL_EXCHANGE_PARAM_KDF_DIGEST, OSSL_PARAM_UTF8_STRING, fix_md },
{ SET, EVP_PKEY_SM2, 0, EVP_PKEY_OP_DERIVE,
EVP_PKEY_CTRL_EC_KDF_OUTLEN, NULL, NULL,
OSSL_EXCHANGE_PARAM_KDF_OUTLEN, OSSL_PARAM_UNSIGNED_INTEGER, NULL },
{ GET, EVP_PKEY_SM2, 0, EVP_PKEY_OP_DERIVE,
EVP_PKEY_CTRL_GET_EC_KDF_OUTLEN, NULL, NULL,
OSSL_EXCHANGE_PARAM_KDF_OUTLEN, OSSL_PARAM_UNSIGNED_INTEGER, NULL },
{ SET, EVP_PKEY_SM2, 0, EVP_PKEY_OP_DERIVE,
EVP_PKEY_CTRL_EC_KDF_UKM, NULL, NULL,
OSSL_EXCHANGE_PARAM_KDF_UKM, OSSL_PARAM_OCTET_STRING, NULL },
{ GET, EVP_PKEY_SM2, 0, EVP_PKEY_OP_DERIVE,
EVP_PKEY_CTRL_GET_EC_KDF_UKM, NULL, NULL,
OSSL_EXCHANGE_PARAM_KDF_UKM, OSSL_PARAM_OCTET_PTR, NULL },
/*-
* RSA
* ===
*/
/*
* RSA padding modes are numeric with ctrls, strings with ctrl_strs,
* and can be both with OSSL_PARAM. We standardise on strings here,
* fix_rsa_padding_mode() does the work when the caller has a different
* idea.
*/
{ SET, EVP_PKEY_RSA, EVP_PKEY_RSA_PSS,
EVP_PKEY_OP_TYPE_CRYPT | EVP_PKEY_OP_TYPE_SIG,
EVP_PKEY_CTRL_RSA_PADDING, "rsa_padding_mode", NULL,
OSSL_PKEY_PARAM_PAD_MODE, OSSL_PARAM_UTF8_STRING, fix_rsa_padding_mode },
{ GET, EVP_PKEY_RSA, EVP_PKEY_RSA_PSS,
EVP_PKEY_OP_TYPE_CRYPT | EVP_PKEY_OP_TYPE_SIG,
EVP_PKEY_CTRL_GET_RSA_PADDING, NULL, NULL,
OSSL_PKEY_PARAM_PAD_MODE, OSSL_PARAM_UTF8_STRING, fix_rsa_padding_mode },
{ SET, EVP_PKEY_RSA, EVP_PKEY_RSA_PSS,
EVP_PKEY_OP_TYPE_CRYPT | EVP_PKEY_OP_TYPE_SIG,
EVP_PKEY_CTRL_RSA_MGF1_MD, "rsa_mgf1_md", NULL,
OSSL_PKEY_PARAM_MGF1_DIGEST, OSSL_PARAM_UTF8_STRING, fix_md },
{ GET, EVP_PKEY_RSA, EVP_PKEY_RSA_PSS,
EVP_PKEY_OP_TYPE_CRYPT | EVP_PKEY_OP_TYPE_SIG,
EVP_PKEY_CTRL_GET_RSA_MGF1_MD, NULL, NULL,
OSSL_PKEY_PARAM_MGF1_DIGEST, OSSL_PARAM_UTF8_STRING, fix_md },
/*
* RSA-PSS saltlen is essentially numeric, but certain values can be
* expressed as keywords (strings) with ctrl_str. The corresponding
* OSSL_PARAM allows both forms.
* fix_rsa_pss_saltlen() takes care of the distinction.
*/
{ SET, EVP_PKEY_RSA, EVP_PKEY_RSA_PSS, EVP_PKEY_OP_TYPE_SIG,
EVP_PKEY_CTRL_RSA_PSS_SALTLEN, "rsa_pss_saltlen", NULL,
OSSL_PKEY_PARAM_RSA_PSS_SALTLEN, OSSL_PARAM_UTF8_STRING,
fix_rsa_pss_saltlen },
{ GET, EVP_PKEY_RSA, EVP_PKEY_RSA_PSS, EVP_PKEY_OP_TYPE_SIG,
EVP_PKEY_CTRL_GET_RSA_PSS_SALTLEN, NULL, NULL,
OSSL_PKEY_PARAM_RSA_PSS_SALTLEN, OSSL_PARAM_UTF8_STRING,
fix_rsa_pss_saltlen },
{ SET, EVP_PKEY_RSA, 0, EVP_PKEY_OP_TYPE_CRYPT,
EVP_PKEY_CTRL_RSA_OAEP_MD, "rsa_oaep_md", NULL,
OSSL_ASYM_CIPHER_PARAM_OAEP_DIGEST, OSSL_PARAM_UTF8_STRING, fix_md },
{ GET, EVP_PKEY_RSA, 0, EVP_PKEY_OP_TYPE_CRYPT,
EVP_PKEY_CTRL_GET_RSA_OAEP_MD, NULL, NULL,
OSSL_ASYM_CIPHER_PARAM_OAEP_DIGEST, OSSL_PARAM_UTF8_STRING, fix_md },
/*
* The "rsa_oaep_label" ctrl_str expects the value to always be hex.
* This is accomodated by default_fixup_args() above, which mimics that
* expectation for any translation item where |ctrl_str| is NULL and
* |ctrl_hexstr| is non-NULL.
*/
{ SET, EVP_PKEY_RSA, 0, EVP_PKEY_OP_TYPE_CRYPT,
EVP_PKEY_CTRL_RSA_OAEP_LABEL, NULL, "rsa_oaep_label",
OSSL_ASYM_CIPHER_PARAM_OAEP_LABEL, OSSL_PARAM_OCTET_STRING, NULL },
{ GET, EVP_PKEY_RSA, 0, EVP_PKEY_OP_TYPE_CRYPT,
EVP_PKEY_CTRL_GET_RSA_OAEP_LABEL, NULL, NULL,
OSSL_ASYM_CIPHER_PARAM_OAEP_LABEL, OSSL_PARAM_OCTET_PTR, NULL },
{ SET, EVP_PKEY_RSA_PSS, 0, EVP_PKEY_OP_TYPE_GEN,
EVP_PKEY_CTRL_MD, "rsa_pss_keygen_md", NULL,
OSSL_ALG_PARAM_DIGEST, OSSL_PARAM_UTF8_STRING, fix_md },
{ SET, EVP_PKEY_RSA_PSS, 0, EVP_PKEY_OP_TYPE_GEN,
EVP_PKEY_CTRL_RSA_MGF1_MD, "rsa_pss_keygen_mgf1_md", NULL,
OSSL_PKEY_PARAM_MGF1_DIGEST, OSSL_PARAM_UTF8_STRING, fix_md },
{ SET, EVP_PKEY_RSA_PSS, 0, EVP_PKEY_OP_TYPE_GEN,
EVP_PKEY_CTRL_RSA_PSS_SALTLEN, "rsa_pss_keygen_saltlen", NULL,
OSSL_SIGNATURE_PARAM_PSS_SALTLEN, OSSL_PARAM_INTEGER, NULL },
{ SET, EVP_PKEY_RSA, EVP_PKEY_RSA_PSS, EVP_PKEY_OP_KEYGEN,
EVP_PKEY_CTRL_RSA_KEYGEN_BITS, "rsa_keygen_bits", NULL,
OSSL_PKEY_PARAM_RSA_BITS, OSSL_PARAM_UNSIGNED_INTEGER, NULL },
{ SET, EVP_PKEY_RSA, EVP_PKEY_RSA_PSS, EVP_PKEY_OP_KEYGEN,
EVP_PKEY_CTRL_RSA_KEYGEN_PUBEXP, "rsa_keygen_pubexp", NULL,
OSSL_PKEY_PARAM_RSA_E, OSSL_PARAM_UNSIGNED_INTEGER, NULL },
{ SET, EVP_PKEY_RSA, EVP_PKEY_RSA_PSS, EVP_PKEY_OP_KEYGEN,
EVP_PKEY_CTRL_RSA_KEYGEN_PRIMES, "rsa_keygen_primes", NULL,
OSSL_PKEY_PARAM_RSA_PRIMES, OSSL_PARAM_UNSIGNED_INTEGER, NULL },
/*-
* SipHash
* ======
*/
{ SET, -1, -1, EVP_PKEY_OP_TYPE_SIG,
EVP_PKEY_CTRL_SET_DIGEST_SIZE, "digestsize", NULL,
OSSL_MAC_PARAM_SIZE, OSSL_PARAM_UNSIGNED_INTEGER, NULL },
/*-
* TLS1-PRF
* ========
*/
{ SET, -1, -1, EVP_PKEY_OP_DERIVE,
EVP_PKEY_CTRL_TLS_MD, "md", NULL,
OSSL_KDF_PARAM_DIGEST, OSSL_PARAM_UTF8_STRING, fix_md },
{ SET, -1, -1, EVP_PKEY_OP_DERIVE,
EVP_PKEY_CTRL_TLS_SECRET, "secret", "hexsecret",
OSSL_KDF_PARAM_SECRET, OSSL_PARAM_OCTET_STRING, NULL },
{ SET, -1, -1, EVP_PKEY_OP_DERIVE,
EVP_PKEY_CTRL_TLS_SEED, "seed", "hexseed",
OSSL_KDF_PARAM_SEED, OSSL_PARAM_OCTET_STRING, NULL },
/*-
* HKDF
* ====
*/
{ SET, -1, -1, EVP_PKEY_OP_DERIVE,
EVP_PKEY_CTRL_HKDF_MD, "md", NULL,
OSSL_KDF_PARAM_DIGEST, OSSL_PARAM_UTF8_STRING, fix_md },
{ SET, -1, -1, EVP_PKEY_OP_DERIVE,
EVP_PKEY_CTRL_HKDF_SALT, "salt", "hexsalt",
OSSL_KDF_PARAM_SALT, OSSL_PARAM_OCTET_STRING, NULL },
{ SET, -1, -1, EVP_PKEY_OP_DERIVE,
EVP_PKEY_CTRL_HKDF_KEY, "key", "hexkey",
OSSL_KDF_PARAM_KEY, OSSL_PARAM_OCTET_STRING, NULL },
{ SET, -1, -1, EVP_PKEY_OP_DERIVE,
EVP_PKEY_CTRL_HKDF_INFO, "info", "hexinfo",
OSSL_KDF_PARAM_INFO, OSSL_PARAM_OCTET_STRING, NULL },
{ SET, -1, -1, EVP_PKEY_OP_DERIVE,
EVP_PKEY_CTRL_HKDF_MODE, "mode", NULL,
OSSL_KDF_PARAM_MODE, OSSL_PARAM_INTEGER, fix_hkdf_mode },
/*-
* Scrypt
* ======
*/
{ SET, -1, -1, EVP_PKEY_OP_DERIVE,
EVP_PKEY_CTRL_PASS, "pass", "hexpass",
OSSL_KDF_PARAM_PASSWORD, OSSL_PARAM_OCTET_STRING, NULL },
{ SET, -1, -1, EVP_PKEY_OP_DERIVE,
EVP_PKEY_CTRL_SCRYPT_SALT, "salt", "hexsalt",
OSSL_KDF_PARAM_SALT, OSSL_PARAM_OCTET_STRING, NULL },
{ SET, -1, -1, EVP_PKEY_OP_DERIVE,
EVP_PKEY_CTRL_SCRYPT_N, "N", NULL,
OSSL_KDF_PARAM_SCRYPT_N, OSSL_PARAM_UNSIGNED_INTEGER, NULL },
{ SET, -1, -1, EVP_PKEY_OP_DERIVE,
EVP_PKEY_CTRL_SCRYPT_R, "r", NULL,
OSSL_KDF_PARAM_SCRYPT_R, OSSL_PARAM_UNSIGNED_INTEGER, NULL },
{ SET, -1, -1, EVP_PKEY_OP_DERIVE,
EVP_PKEY_CTRL_SCRYPT_P, "p", NULL,
OSSL_KDF_PARAM_SCRYPT_P, OSSL_PARAM_UNSIGNED_INTEGER, NULL },
{ SET, -1, -1, EVP_PKEY_OP_DERIVE,
EVP_PKEY_CTRL_SCRYPT_MAXMEM_BYTES, "maxmem_bytes", NULL,
OSSL_KDF_PARAM_SCRYPT_MAXMEM, OSSL_PARAM_UNSIGNED_INTEGER, NULL },
{ SET, -1, -1, EVP_PKEY_OP_KEYGEN | EVP_PKEY_OP_TYPE_CRYPT,
EVP_PKEY_CTRL_CIPHER, NULL, NULL,
OSSL_PKEY_PARAM_CIPHER, OSSL_PARAM_UTF8_STRING, fix_cipher },
{ SET, -1, -1, EVP_PKEY_OP_KEYGEN,
EVP_PKEY_CTRL_SET_MAC_KEY, "key", "hexkey",
OSSL_PKEY_PARAM_PRIV_KEY, OSSL_PARAM_OCTET_STRING, NULL },
{ SET, -1, -1, EVP_PKEY_OP_TYPE_SIG,
EVP_PKEY_CTRL_MD, NULL, NULL,
OSSL_SIGNATURE_PARAM_DIGEST, OSSL_PARAM_UTF8_STRING, fix_md },
{ GET, -1, -1, EVP_PKEY_OP_TYPE_SIG,
EVP_PKEY_CTRL_GET_MD, NULL, NULL,
OSSL_SIGNATURE_PARAM_DIGEST, OSSL_PARAM_UTF8_STRING, fix_md },
/*-
* ECX
* ===
*/
{ SET, EVP_PKEY_X25519, EVP_PKEY_X25519, EVP_PKEY_OP_KEYGEN, -1, NULL, NULL,
OSSL_PKEY_PARAM_GROUP_NAME, OSSL_PARAM_UTF8_STRING, fix_group_ecx },
{ SET, EVP_PKEY_X25519, EVP_PKEY_X25519, EVP_PKEY_OP_PARAMGEN, -1, NULL, NULL,
OSSL_PKEY_PARAM_GROUP_NAME, OSSL_PARAM_UTF8_STRING, fix_group_ecx },
{ SET, EVP_PKEY_X448, EVP_PKEY_X448, EVP_PKEY_OP_KEYGEN, -1, NULL, NULL,
OSSL_PKEY_PARAM_GROUP_NAME, OSSL_PARAM_UTF8_STRING, fix_group_ecx },
{ SET, EVP_PKEY_X448, EVP_PKEY_X448, EVP_PKEY_OP_PARAMGEN, -1, NULL, NULL,
OSSL_PKEY_PARAM_GROUP_NAME, OSSL_PARAM_UTF8_STRING, fix_group_ecx },
};
static const struct translation_st evp_pkey_translations[] = {
/*
* The following contain no ctrls, they are exclusively here to extract
* key payloads from legacy keys, using OSSL_PARAMs, and rely entirely
* on |fixup_args| to pass the actual data. The |fixup_args| should
* expect to get the EVP_PKEY pointer through |ctx->p2|.
*/
/* DH, DSA & EC */
{ GET, -1, -1, -1, 0, NULL, NULL,
OSSL_PKEY_PARAM_GROUP_NAME, OSSL_PARAM_UTF8_STRING,
get_payload_group_name },
{ GET, -1, -1, -1, 0, NULL, NULL,
OSSL_PKEY_PARAM_PRIV_KEY, OSSL_PARAM_UNSIGNED_INTEGER,
get_payload_private_key },
{ GET, -1, -1, -1, 0, NULL, NULL,
OSSL_PKEY_PARAM_PUB_KEY,
0 /* no data type, let get_payload_public_key() handle that */,
get_payload_public_key },
/* DH and DSA */
{ GET, -1, -1, -1, 0, NULL, NULL,
OSSL_PKEY_PARAM_FFC_P, OSSL_PARAM_UNSIGNED_INTEGER,
get_dh_dsa_payload_p },
{ GET, -1, -1, -1, 0, NULL, NULL,
OSSL_PKEY_PARAM_FFC_G, OSSL_PARAM_UNSIGNED_INTEGER,
get_dh_dsa_payload_g },
{ GET, -1, -1, -1, 0, NULL, NULL,
OSSL_PKEY_PARAM_FFC_Q, OSSL_PARAM_UNSIGNED_INTEGER,
get_dh_dsa_payload_q },
/* RSA */
{ GET, -1, -1, -1, 0, NULL, NULL,
OSSL_PKEY_PARAM_RSA_N, OSSL_PARAM_UNSIGNED_INTEGER,
get_rsa_payload_n },
{ GET, -1, -1, -1, 0, NULL, NULL,
OSSL_PKEY_PARAM_RSA_E, OSSL_PARAM_UNSIGNED_INTEGER,
get_rsa_payload_e },
{ GET, -1, -1, -1, 0, NULL, NULL,
OSSL_PKEY_PARAM_RSA_D, OSSL_PARAM_UNSIGNED_INTEGER,
get_rsa_payload_d },
{ GET, -1, -1, -1, 0, NULL, NULL,
OSSL_PKEY_PARAM_RSA_FACTOR1, OSSL_PARAM_UNSIGNED_INTEGER,
get_rsa_payload_f1 },
{ GET, -1, -1, -1, 0, NULL, NULL,
OSSL_PKEY_PARAM_RSA_FACTOR2, OSSL_PARAM_UNSIGNED_INTEGER,
get_rsa_payload_f2 },
{ GET, -1, -1, -1, 0, NULL, NULL,
OSSL_PKEY_PARAM_RSA_FACTOR3, OSSL_PARAM_UNSIGNED_INTEGER,
get_rsa_payload_f3 },
{ GET, -1, -1, -1, 0, NULL, NULL,
OSSL_PKEY_PARAM_RSA_FACTOR4, OSSL_PARAM_UNSIGNED_INTEGER,
get_rsa_payload_f4 },
{ GET, -1, -1, -1, 0, NULL, NULL,
OSSL_PKEY_PARAM_RSA_FACTOR5, OSSL_PARAM_UNSIGNED_INTEGER,
get_rsa_payload_f5 },
{ GET, -1, -1, -1, 0, NULL, NULL,
OSSL_PKEY_PARAM_RSA_FACTOR6, OSSL_PARAM_UNSIGNED_INTEGER,
get_rsa_payload_f6 },
{ GET, -1, -1, -1, 0, NULL, NULL,
OSSL_PKEY_PARAM_RSA_FACTOR7, OSSL_PARAM_UNSIGNED_INTEGER,
get_rsa_payload_f7 },
{ GET, -1, -1, -1, 0, NULL, NULL,
OSSL_PKEY_PARAM_RSA_FACTOR8, OSSL_PARAM_UNSIGNED_INTEGER,
get_rsa_payload_f8 },
{ GET, -1, -1, -1, 0, NULL, NULL,
OSSL_PKEY_PARAM_RSA_FACTOR9, OSSL_PARAM_UNSIGNED_INTEGER,
get_rsa_payload_f9 },
{ GET, -1, -1, -1, 0, NULL, NULL,
OSSL_PKEY_PARAM_RSA_FACTOR10, OSSL_PARAM_UNSIGNED_INTEGER,
get_rsa_payload_f10 },
{ GET, -1, -1, -1, 0, NULL, NULL,
OSSL_PKEY_PARAM_RSA_EXPONENT1, OSSL_PARAM_UNSIGNED_INTEGER,
get_rsa_payload_e1 },
{ GET, -1, -1, -1, 0, NULL, NULL,
OSSL_PKEY_PARAM_RSA_EXPONENT2, OSSL_PARAM_UNSIGNED_INTEGER,
get_rsa_payload_e2 },
{ GET, -1, -1, -1, 0, NULL, NULL,
OSSL_PKEY_PARAM_RSA_EXPONENT3, OSSL_PARAM_UNSIGNED_INTEGER,
get_rsa_payload_e3 },
{ GET, -1, -1, -1, 0, NULL, NULL,
OSSL_PKEY_PARAM_RSA_EXPONENT4, OSSL_PARAM_UNSIGNED_INTEGER,
get_rsa_payload_e4 },
{ GET, -1, -1, -1, 0, NULL, NULL,
OSSL_PKEY_PARAM_RSA_EXPONENT5, OSSL_PARAM_UNSIGNED_INTEGER,
get_rsa_payload_e5 },
{ GET, -1, -1, -1, 0, NULL, NULL,
OSSL_PKEY_PARAM_RSA_EXPONENT6, OSSL_PARAM_UNSIGNED_INTEGER,
get_rsa_payload_e6 },
{ GET, -1, -1, -1, 0, NULL, NULL,
OSSL_PKEY_PARAM_RSA_EXPONENT7, OSSL_PARAM_UNSIGNED_INTEGER,
get_rsa_payload_e7 },
{ GET, -1, -1, -1, 0, NULL, NULL,
OSSL_PKEY_PARAM_RSA_EXPONENT8, OSSL_PARAM_UNSIGNED_INTEGER,
get_rsa_payload_e8 },
{ GET, -1, -1, -1, 0, NULL, NULL,
OSSL_PKEY_PARAM_RSA_EXPONENT9, OSSL_PARAM_UNSIGNED_INTEGER,
get_rsa_payload_e9 },
{ GET, -1, -1, -1, 0, NULL, NULL,
OSSL_PKEY_PARAM_RSA_EXPONENT10, OSSL_PARAM_UNSIGNED_INTEGER,
get_rsa_payload_e10 },
{ GET, -1, -1, -1, 0, NULL, NULL,
OSSL_PKEY_PARAM_RSA_COEFFICIENT1, OSSL_PARAM_UNSIGNED_INTEGER,
get_rsa_payload_c1 },
{ GET, -1, -1, -1, 0, NULL, NULL,
OSSL_PKEY_PARAM_RSA_COEFFICIENT2, OSSL_PARAM_UNSIGNED_INTEGER,
get_rsa_payload_c2 },
{ GET, -1, -1, -1, 0, NULL, NULL,
OSSL_PKEY_PARAM_RSA_COEFFICIENT3, OSSL_PARAM_UNSIGNED_INTEGER,
get_rsa_payload_c3 },
{ GET, -1, -1, -1, 0, NULL, NULL,
OSSL_PKEY_PARAM_RSA_COEFFICIENT4, OSSL_PARAM_UNSIGNED_INTEGER,
get_rsa_payload_c4 },
{ GET, -1, -1, -1, 0, NULL, NULL,
OSSL_PKEY_PARAM_RSA_COEFFICIENT5, OSSL_PARAM_UNSIGNED_INTEGER,
get_rsa_payload_c5 },
{ GET, -1, -1, -1, 0, NULL, NULL,
OSSL_PKEY_PARAM_RSA_COEFFICIENT6, OSSL_PARAM_UNSIGNED_INTEGER,
get_rsa_payload_c6 },
{ GET, -1, -1, -1, 0, NULL, NULL,
OSSL_PKEY_PARAM_RSA_COEFFICIENT7, OSSL_PARAM_UNSIGNED_INTEGER,
get_rsa_payload_c7 },
{ GET, -1, -1, -1, 0, NULL, NULL,
OSSL_PKEY_PARAM_RSA_COEFFICIENT8, OSSL_PARAM_UNSIGNED_INTEGER,
get_rsa_payload_c8 },
{ GET, -1, -1, -1, 0, NULL, NULL,
OSSL_PKEY_PARAM_RSA_COEFFICIENT9, OSSL_PARAM_UNSIGNED_INTEGER,
get_rsa_payload_c9 },
/* EC */
{ GET, -1, -1, -1, 0, NULL, NULL,
OSSL_PKEY_PARAM_EC_DECODED_FROM_EXPLICIT_PARAMS, OSSL_PARAM_INTEGER,
get_ec_decoded_from_explicit_params },
};
static const struct translation_st *
lookup_translation(struct translation_st *tmpl,
const struct translation_st *translations,
size_t translations_num)
{
size_t i;
for (i = 0; i < translations_num; i++) {
const struct translation_st *item = &translations[i];
/*
* Sanity check the translation table item.
*
* 1. Either both keytypes are -1, or neither of them are.
* 2. TBA...
*/
if (!ossl_assert((item->keytype1 == -1) == (item->keytype2 == -1)))
continue;
/*
* Base search criteria: check that the optype and keytypes match,
* if relevant. All callers must synthesise these bits somehow.
*/
if (item->optype != -1 && (tmpl->optype & item->optype) == 0)
continue;
/*
* This expression is stunningly simple thanks to the sanity check
* above.
*/
if (item->keytype1 != -1
&& tmpl->keytype1 != item->keytype1
&& tmpl->keytype2 != item->keytype2)
continue;
/*
* Done with the base search criteria, now we check the criteria for
* the individual types of translations:
* ctrl->params, ctrl_str->params, and params->ctrl
*/
if (tmpl->ctrl_num != 0) {
if (tmpl->ctrl_num != item->ctrl_num)
continue;
} else if (tmpl->ctrl_str != NULL) {
const char *ctrl_str = NULL;
const char *ctrl_hexstr = NULL;
/*
* Search criteria that originates from a ctrl_str is only used
* for setting, never for getting. Therefore, we only look at
* the setter items.
*/
if (item->action_type != NONE
&& item->action_type != SET)
continue;
/*
* At least one of the ctrl cmd names must be match the ctrl
* cmd name in the template.
*/
if (item->ctrl_str != NULL
&& OPENSSL_strcasecmp(tmpl->ctrl_str, item->ctrl_str) == 0)
ctrl_str = tmpl->ctrl_str;
else if (item->ctrl_hexstr != NULL
&& OPENSSL_strcasecmp(tmpl->ctrl_hexstr,
item->ctrl_hexstr) == 0)
ctrl_hexstr = tmpl->ctrl_hexstr;
else
continue;
/* Modify the template to signal which string matched */
tmpl->ctrl_str = ctrl_str;
tmpl->ctrl_hexstr = ctrl_hexstr;
} else if (tmpl->param_key != NULL) {
/*
* Search criteria that originates from a OSSL_PARAM setter or
* getter.
*
* Ctrls were fundamentally bidirectional, with only the ctrl
* command macro name implying direction (if you're lucky).
* A few ctrl commands were even taking advantage of the
* bidirectional nature, making the direction depend in the
* value of the numeric argument.
*
* OSSL_PARAM functions are fundamentally different, in that
* setters and getters are separated, so the data direction is
* implied by the function that's used. The same OSSL_PARAM
* key name can therefore be used in both directions. We must
* therefore take the action type into account in this case.
*/
if ((item->action_type != NONE
&& tmpl->action_type != item->action_type)
|| (item->param_key != NULL
&& OPENSSL_strcasecmp(tmpl->param_key,
item->param_key) != 0))
continue;
} else {
return NULL;
}
return item;
}
return NULL;
}
static const struct translation_st *
lookup_evp_pkey_ctx_translation(struct translation_st *tmpl)
{
return lookup_translation(tmpl, evp_pkey_ctx_translations,
OSSL_NELEM(evp_pkey_ctx_translations));
}
static const struct translation_st *
lookup_evp_pkey_translation(struct translation_st *tmpl)
{
return lookup_translation(tmpl, evp_pkey_translations,
OSSL_NELEM(evp_pkey_translations));
}
/* This must ONLY be called for provider side operations */
int evp_pkey_ctx_ctrl_to_param(EVP_PKEY_CTX *pctx,
int keytype, int optype,
int cmd, int p1, void *p2)
{
struct translation_ctx_st ctx = { 0, };
struct translation_st tmpl = { 0, };
const struct translation_st *translation = NULL;
OSSL_PARAM params[2] = { OSSL_PARAM_END, OSSL_PARAM_END };
int ret;
fixup_args_fn *fixup = default_fixup_args;
if (keytype == -1)
keytype = pctx->legacy_keytype;
tmpl.ctrl_num = cmd;
tmpl.keytype1 = tmpl.keytype2 = keytype;
tmpl.optype = optype;
translation = lookup_evp_pkey_ctx_translation(&tmpl);
if (translation == NULL) {
ERR_raise(ERR_LIB_EVP, EVP_R_COMMAND_NOT_SUPPORTED);
return -2;
}
if (pctx->pmeth != NULL
&& pctx->pmeth->pkey_id != translation->keytype1
&& pctx->pmeth->pkey_id != translation->keytype2)
return -1;
if (translation->fixup_args != NULL)
fixup = translation->fixup_args;
ctx.action_type = translation->action_type;
ctx.ctrl_cmd = cmd;
ctx.p1 = p1;
ctx.p2 = p2;
ctx.pctx = pctx;
ctx.params = params;
ret = fixup(PRE_CTRL_TO_PARAMS, translation, &ctx);
if (ret > 0) {
switch (ctx.action_type) {
default:
/* fixup_args is expected to make sure this is dead code */
break;
case GET:
ret = evp_pkey_ctx_get_params_strict(pctx, ctx.params);
break;
case SET:
ret = evp_pkey_ctx_set_params_strict(pctx, ctx.params);
break;
}
}
/*
* In POST, we pass the return value as p1, allowing the fixup_args
* function to affect it by changing its value.
*/
if (ret > 0) {
ctx.p1 = ret;
fixup(POST_CTRL_TO_PARAMS, translation, &ctx);
ret = ctx.p1;
}
cleanup_translation_ctx(POST_CTRL_TO_PARAMS, translation, &ctx);
return ret;
}
/* This must ONLY be called for provider side operations */
int evp_pkey_ctx_ctrl_str_to_param(EVP_PKEY_CTX *pctx,
const char *name, const char *value)
{
struct translation_ctx_st ctx = { 0, };
struct translation_st tmpl = { 0, };
const struct translation_st *translation = NULL;
OSSL_PARAM params[2] = { OSSL_PARAM_END, OSSL_PARAM_END };
int keytype = pctx->legacy_keytype;
int optype = pctx->operation == 0 ? -1 : pctx->operation;
int ret;
fixup_args_fn *fixup = default_fixup_args;
tmpl.action_type = SET;
tmpl.keytype1 = tmpl.keytype2 = keytype;
tmpl.optype = optype;
tmpl.ctrl_str = name;
tmpl.ctrl_hexstr = name;
translation = lookup_evp_pkey_ctx_translation(&tmpl);
if (translation != NULL) {
if (translation->fixup_args != NULL)
fixup = translation->fixup_args;
ctx.action_type = translation->action_type;
ctx.ishex = (tmpl.ctrl_hexstr != NULL);
} else {
/* String controls really only support setting */
ctx.action_type = SET;
}
ctx.ctrl_str = name;
ctx.p1 = (int)strlen(value);
ctx.p2 = (char *)value;
ctx.pctx = pctx;
ctx.params = params;
ret = fixup(PRE_CTRL_STR_TO_PARAMS, translation, &ctx);
if (ret > 0) {
switch (ctx.action_type) {
default:
/* fixup_args is expected to make sure this is dead code */
break;
case GET:
/*
* this is dead code, but must be present, or some compilers
* will complain
*/
break;
case SET:
ret = evp_pkey_ctx_set_params_strict(pctx, ctx.params);
break;
}
}
if (ret > 0)
ret = fixup(POST_CTRL_STR_TO_PARAMS, translation, &ctx);
cleanup_translation_ctx(CLEANUP_CTRL_STR_TO_PARAMS, translation, &ctx);
return ret;
}
/* This must ONLY be called for legacy operations */
static int evp_pkey_ctx_setget_params_to_ctrl(EVP_PKEY_CTX *pctx,
enum action action_type,
OSSL_PARAM *params)
{
int keytype = pctx->legacy_keytype;
int optype = pctx->operation == 0 ? -1 : pctx->operation;
for (; params != NULL && params->key != NULL; params++) {
struct translation_ctx_st ctx = { 0, };
struct translation_st tmpl = { 0, };
const struct translation_st *translation = NULL;
fixup_args_fn *fixup = default_fixup_args;
int ret;
- tmpl.action_type = action_type;
+ ctx.action_type = tmpl.action_type = action_type;
tmpl.keytype1 = tmpl.keytype2 = keytype;
tmpl.optype = optype;
tmpl.param_key = params->key;
translation = lookup_evp_pkey_ctx_translation(&tmpl);
if (translation != NULL) {
if (translation->fixup_args != NULL)
fixup = translation->fixup_args;
- ctx.action_type = translation->action_type;
ctx.ctrl_cmd = translation->ctrl_num;
}
ctx.pctx = pctx;
ctx.params = params;
ret = fixup(PRE_PARAMS_TO_CTRL, translation, &ctx);
if (ret > 0 && ctx.action_type != NONE)
ret = EVP_PKEY_CTX_ctrl(pctx, keytype, optype,
ctx.ctrl_cmd, ctx.p1, ctx.p2);
/*
* In POST, we pass the return value as p1, allowing the fixup_args
* function to put it to good use, or maybe affect it.
*/
if (ret > 0) {
ctx.p1 = ret;
fixup(POST_PARAMS_TO_CTRL, translation, &ctx);
ret = ctx.p1;
}
cleanup_translation_ctx(CLEANUP_PARAMS_TO_CTRL, translation, &ctx);
if (ret <= 0)
return 0;
}
return 1;
}
int evp_pkey_ctx_set_params_to_ctrl(EVP_PKEY_CTX *ctx, const OSSL_PARAM *params)
{
return evp_pkey_ctx_setget_params_to_ctrl(ctx, SET, (OSSL_PARAM *)params);
}
int evp_pkey_ctx_get_params_to_ctrl(EVP_PKEY_CTX *ctx, OSSL_PARAM *params)
{
return evp_pkey_ctx_setget_params_to_ctrl(ctx, GET, params);
}
/* This must ONLY be called for legacy EVP_PKEYs */
static int evp_pkey_setget_params_to_ctrl(const EVP_PKEY *pkey,
enum action action_type,
OSSL_PARAM *params)
{
int ret = 1;
for (; params != NULL && params->key != NULL; params++) {
struct translation_ctx_st ctx = { 0, };
struct translation_st tmpl = { 0, };
const struct translation_st *translation = NULL;
fixup_args_fn *fixup = default_fixup_args;
tmpl.action_type = action_type;
tmpl.param_key = params->key;
translation = lookup_evp_pkey_translation(&tmpl);
if (translation != NULL) {
if (translation->fixup_args != NULL)
fixup = translation->fixup_args;
ctx.action_type = translation->action_type;
}
ctx.p2 = (void *)pkey;
ctx.params = params;
/*
* EVP_PKEY doesn't have any ctrl function, so we rely completely
* on fixup_args to do the whole work. Also, we currently only
* support getting.
*/
if (!ossl_assert(translation != NULL)
|| !ossl_assert(translation->action_type == GET)
|| !ossl_assert(translation->fixup_args != NULL)) {
return -2;
}
ret = fixup(PKEY, translation, &ctx);
cleanup_translation_ctx(PKEY, translation, &ctx);
}
return ret;
}
int evp_pkey_get_params_to_ctrl(const EVP_PKEY *pkey, OSSL_PARAM *params)
{
return evp_pkey_setget_params_to_ctrl(pkey, GET, params);
}
diff --git a/crypto/openssl/crypto/evp/digest.c b/crypto/openssl/crypto/evp/digest.c
index eefed523ec12..aca05186ec10 100644
--- a/crypto/openssl/crypto/evp/digest.c
+++ b/crypto/openssl/crypto/evp/digest.c
@@ -1,1108 +1,1108 @@
/*
- * 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
*/
/* We need to use some engine deprecated APIs */
#define OPENSSL_SUPPRESS_DEPRECATED
#include <stdio.h>
#include <openssl/objects.h>
#include <openssl/evp.h>
#include <openssl/ec.h>
#ifndef FIPS_MODULE
# include <openssl/engine.h>
#endif
#include <openssl/params.h>
#include <openssl/core_names.h>
#include "internal/cryptlib.h"
#include "internal/provider.h"
#include "internal/core.h"
#include "crypto/evp.h"
#include "evp_local.h"
static void cleanup_old_md_data(EVP_MD_CTX *ctx, int force)
{
if (ctx->digest != NULL) {
if (ctx->digest->cleanup != NULL
&& !EVP_MD_CTX_test_flags(ctx, EVP_MD_CTX_FLAG_CLEANED))
ctx->digest->cleanup(ctx);
if (ctx->md_data != NULL && ctx->digest->ctx_size > 0
&& (!EVP_MD_CTX_test_flags(ctx, EVP_MD_CTX_FLAG_REUSE)
|| force)) {
OPENSSL_clear_free(ctx->md_data, ctx->digest->ctx_size);
ctx->md_data = NULL;
}
}
}
void evp_md_ctx_clear_digest(EVP_MD_CTX *ctx, int force, int keep_fetched)
{
if (ctx->algctx != NULL) {
if (ctx->digest != NULL && ctx->digest->freectx != NULL)
ctx->digest->freectx(ctx->algctx);
ctx->algctx = NULL;
EVP_MD_CTX_set_flags(ctx, EVP_MD_CTX_FLAG_CLEANED);
}
/* Code below to be removed when legacy support is dropped. */
/*
* Don't assume ctx->md_data was cleaned in EVP_Digest_Final, because
* sometimes only copies of the context are ever finalised.
*/
cleanup_old_md_data(ctx, force);
if (force)
ctx->digest = NULL;
#if !defined(FIPS_MODULE) && !defined(OPENSSL_NO_ENGINE)
ENGINE_finish(ctx->engine);
ctx->engine = NULL;
#endif
/* Non legacy code, this has to be later than the ctx->digest cleaning */
if (!keep_fetched) {
EVP_MD_free(ctx->fetched_digest);
ctx->fetched_digest = NULL;
ctx->reqdigest = NULL;
}
}
static int evp_md_ctx_reset_ex(EVP_MD_CTX *ctx, int keep_fetched)
{
if (ctx == NULL)
return 1;
#ifndef FIPS_MODULE
/*
* pctx should be freed by the user of EVP_MD_CTX
* if EVP_MD_CTX_FLAG_KEEP_PKEY_CTX is set
*/
if (!EVP_MD_CTX_test_flags(ctx, EVP_MD_CTX_FLAG_KEEP_PKEY_CTX)) {
EVP_PKEY_CTX_free(ctx->pctx);
ctx->pctx = NULL;
}
#endif
evp_md_ctx_clear_digest(ctx, 0, keep_fetched);
if (!keep_fetched)
OPENSSL_cleanse(ctx, sizeof(*ctx));
return 1;
}
/* This call frees resources associated with the context */
int EVP_MD_CTX_reset(EVP_MD_CTX *ctx)
{
return evp_md_ctx_reset_ex(ctx, 0);
}
#ifndef FIPS_MODULE
EVP_MD_CTX *evp_md_ctx_new_ex(EVP_PKEY *pkey, const ASN1_OCTET_STRING *id,
OSSL_LIB_CTX *libctx, const char *propq)
{
EVP_MD_CTX *ctx;
EVP_PKEY_CTX *pctx = NULL;
if ((ctx = EVP_MD_CTX_new()) == NULL
|| (pctx = EVP_PKEY_CTX_new_from_pkey(libctx, pkey, propq)) == NULL) {
ERR_raise(ERR_LIB_ASN1, ERR_R_MALLOC_FAILURE);
goto err;
}
if (id != NULL && EVP_PKEY_CTX_set1_id(pctx, id->data, id->length) <= 0)
goto err;
EVP_MD_CTX_set_pkey_ctx(ctx, pctx);
return ctx;
err:
EVP_PKEY_CTX_free(pctx);
EVP_MD_CTX_free(ctx);
return NULL;
}
#endif
EVP_MD_CTX *EVP_MD_CTX_new(void)
{
return OPENSSL_zalloc(sizeof(EVP_MD_CTX));
}
void EVP_MD_CTX_free(EVP_MD_CTX *ctx)
{
if (ctx == NULL)
return;
EVP_MD_CTX_reset(ctx);
OPENSSL_free(ctx);
}
static int evp_md_init_internal(EVP_MD_CTX *ctx, const EVP_MD *type,
const OSSL_PARAM params[], ENGINE *impl)
{
#if !defined(OPENSSL_NO_ENGINE) && !defined(FIPS_MODULE)
ENGINE *tmpimpl = NULL;
#endif
#if !defined(FIPS_MODULE)
if (ctx->pctx != NULL
&& EVP_PKEY_CTX_IS_SIGNATURE_OP(ctx->pctx)
&& ctx->pctx->op.sig.algctx != NULL) {
/*
* Prior to OpenSSL 3.0 calling EVP_DigestInit_ex() on an mdctx
* previously initialised with EVP_DigestSignInit() would retain
* information about the key, and re-initialise for another sign
* operation. So in that case we redirect to EVP_DigestSignInit()
*/
if (ctx->pctx->operation == EVP_PKEY_OP_SIGNCTX)
return EVP_DigestSignInit(ctx, NULL, type, impl, NULL);
if (ctx->pctx->operation == EVP_PKEY_OP_VERIFYCTX)
return EVP_DigestVerifyInit(ctx, NULL, type, impl, NULL);
ERR_raise(ERR_LIB_EVP, EVP_R_UPDATE_ERROR);
return 0;
}
#endif
EVP_MD_CTX_clear_flags(ctx, EVP_MD_CTX_FLAG_CLEANED);
if (ctx->algctx != NULL) {
if (!ossl_assert(ctx->digest != NULL)) {
ERR_raise(ERR_LIB_EVP, EVP_R_INITIALIZATION_ERROR);
return 0;
}
if (ctx->digest->freectx != NULL)
ctx->digest->freectx(ctx->algctx);
ctx->algctx = NULL;
}
if (type != NULL) {
ctx->reqdigest = type;
} else {
if (ctx->digest == NULL) {
ERR_raise(ERR_LIB_EVP, EVP_R_NO_DIGEST_SET);
return 0;
}
type = ctx->digest;
}
/* Code below to be removed when legacy support is dropped. */
#if !defined(OPENSSL_NO_ENGINE) && !defined(FIPS_MODULE)
/*
* Whether it's nice or not, "Inits" can be used on "Final"'d contexts so
* this context may already have an ENGINE! Try to avoid releasing the
* previous handle, re-querying for an ENGINE, and having a
* reinitialisation, when it may all be unnecessary.
*/
if (ctx->engine && ctx->digest &&
(type == NULL || (type->type == ctx->digest->type)))
goto skip_to_init;
if (type != NULL) {
/*
* Ensure an ENGINE left lying around from last time is cleared (the
* previous check attempted to avoid this if the same ENGINE and
* EVP_MD could be used).
*/
ENGINE_finish(ctx->engine);
ctx->engine = NULL;
}
if (type != NULL && impl == NULL)
tmpimpl = ENGINE_get_digest_engine(type->type);
#endif
/*
* If there are engines involved or EVP_MD_CTX_FLAG_NO_INIT is set then we
* should use legacy handling for now.
*/
if (ctx->engine != NULL
|| impl != NULL
#if !defined(OPENSSL_NO_ENGINE) && !defined(FIPS_MODULE)
|| tmpimpl != NULL
#endif
|| (ctx->flags & EVP_MD_CTX_FLAG_NO_INIT) != 0
|| (type != NULL && type->origin == EVP_ORIG_METH)
|| (type == NULL && ctx->digest != NULL
&& ctx->digest->origin == EVP_ORIG_METH)) {
if (ctx->digest == ctx->fetched_digest)
ctx->digest = NULL;
EVP_MD_free(ctx->fetched_digest);
ctx->fetched_digest = NULL;
goto legacy;
}
cleanup_old_md_data(ctx, 1);
/* Start of non-legacy code below */
if (type->prov == NULL) {
#ifdef FIPS_MODULE
/* We only do explicit fetches inside the FIPS module */
ERR_raise(ERR_LIB_EVP, EVP_R_INITIALIZATION_ERROR);
return 0;
#else
/* The NULL digest is a special case */
EVP_MD *provmd = EVP_MD_fetch(NULL,
type->type != NID_undef ? OBJ_nid2sn(type->type)
: "NULL", "");
if (provmd == NULL) {
ERR_raise(ERR_LIB_EVP, EVP_R_INITIALIZATION_ERROR);
return 0;
}
type = provmd;
EVP_MD_free(ctx->fetched_digest);
ctx->fetched_digest = provmd;
#endif
}
if (ctx->algctx != NULL && ctx->digest != NULL && ctx->digest != type) {
if (ctx->digest->freectx != NULL)
ctx->digest->freectx(ctx->algctx);
ctx->algctx = NULL;
}
if (type->prov != NULL && ctx->fetched_digest != type) {
if (!EVP_MD_up_ref((EVP_MD *)type)) {
ERR_raise(ERR_LIB_EVP, EVP_R_INITIALIZATION_ERROR);
return 0;
}
EVP_MD_free(ctx->fetched_digest);
ctx->fetched_digest = (EVP_MD *)type;
}
ctx->digest = type;
if (ctx->algctx == NULL) {
ctx->algctx = ctx->digest->newctx(ossl_provider_ctx(type->prov));
if (ctx->algctx == NULL) {
ERR_raise(ERR_LIB_EVP, EVP_R_INITIALIZATION_ERROR);
return 0;
}
}
if (ctx->digest->dinit == NULL) {
ERR_raise(ERR_LIB_EVP, EVP_R_INITIALIZATION_ERROR);
return 0;
}
return ctx->digest->dinit(ctx->algctx, params);
/* Code below to be removed when legacy support is dropped. */
legacy:
#if !defined(OPENSSL_NO_ENGINE) && !defined(FIPS_MODULE)
if (type) {
if (impl != NULL) {
if (!ENGINE_init(impl)) {
ERR_raise(ERR_LIB_EVP, EVP_R_INITIALIZATION_ERROR);
return 0;
}
} else {
/* Ask if an ENGINE is reserved for this job */
impl = tmpimpl;
}
if (impl != NULL) {
/* There's an ENGINE for this job ... (apparently) */
const EVP_MD *d = ENGINE_get_digest(impl, type->type);
if (d == NULL) {
ERR_raise(ERR_LIB_EVP, EVP_R_INITIALIZATION_ERROR);
ENGINE_finish(impl);
return 0;
}
/* We'll use the ENGINE's private digest definition */
type = d;
/*
* Store the ENGINE functional reference so we know 'type' came
* from an ENGINE and we need to release it when done.
*/
ctx->engine = impl;
} else
ctx->engine = NULL;
}
#endif
if (ctx->digest != type) {
cleanup_old_md_data(ctx, 1);
ctx->digest = type;
if (!(ctx->flags & EVP_MD_CTX_FLAG_NO_INIT) && type->ctx_size) {
ctx->update = type->update;
ctx->md_data = OPENSSL_zalloc(type->ctx_size);
if (ctx->md_data == NULL) {
ERR_raise(ERR_LIB_EVP, ERR_R_MALLOC_FAILURE);
return 0;
}
}
}
#if !defined(OPENSSL_NO_ENGINE) && !defined(FIPS_MODULE)
skip_to_init:
#endif
#ifndef FIPS_MODULE
if (ctx->pctx != NULL
&& (!EVP_PKEY_CTX_IS_SIGNATURE_OP(ctx->pctx)
|| ctx->pctx->op.sig.signature == NULL)) {
int r;
r = EVP_PKEY_CTX_ctrl(ctx->pctx, -1, EVP_PKEY_OP_TYPE_SIG,
EVP_PKEY_CTRL_DIGESTINIT, 0, ctx);
if (r <= 0 && (r != -2))
return 0;
}
#endif
if (ctx->flags & EVP_MD_CTX_FLAG_NO_INIT)
return 1;
return ctx->digest->init(ctx);
}
int EVP_DigestInit_ex2(EVP_MD_CTX *ctx, const EVP_MD *type,
const OSSL_PARAM params[])
{
return evp_md_init_internal(ctx, type, params, NULL);
}
int EVP_DigestInit(EVP_MD_CTX *ctx, const EVP_MD *type)
{
EVP_MD_CTX_reset(ctx);
return evp_md_init_internal(ctx, type, NULL, NULL);
}
int EVP_DigestInit_ex(EVP_MD_CTX *ctx, const EVP_MD *type, ENGINE *impl)
{
return evp_md_init_internal(ctx, type, NULL, impl);
}
int EVP_DigestUpdate(EVP_MD_CTX *ctx, const void *data, size_t count)
{
if (count == 0)
return 1;
if (ctx->pctx != NULL
&& EVP_PKEY_CTX_IS_SIGNATURE_OP(ctx->pctx)
&& ctx->pctx->op.sig.algctx != NULL) {
/*
* Prior to OpenSSL 3.0 EVP_DigestSignUpdate() and
* EVP_DigestVerifyUpdate() were just macros for EVP_DigestUpdate().
* Some code calls EVP_DigestUpdate() directly even when initialised
* with EVP_DigestSignInit_ex() or
* EVP_DigestVerifyInit_ex(), so we detect that and redirect to
* the correct EVP_Digest*Update() function
*/
if (ctx->pctx->operation == EVP_PKEY_OP_SIGNCTX)
return EVP_DigestSignUpdate(ctx, data, count);
if (ctx->pctx->operation == EVP_PKEY_OP_VERIFYCTX)
return EVP_DigestVerifyUpdate(ctx, data, count);
ERR_raise(ERR_LIB_EVP, EVP_R_UPDATE_ERROR);
return 0;
}
if (ctx->digest == NULL
|| ctx->digest->prov == NULL
|| (ctx->flags & EVP_MD_CTX_FLAG_NO_INIT) != 0)
goto legacy;
if (ctx->digest->dupdate == NULL) {
ERR_raise(ERR_LIB_EVP, EVP_R_UPDATE_ERROR);
return 0;
}
return ctx->digest->dupdate(ctx->algctx, data, count);
/* Code below to be removed when legacy support is dropped. */
legacy:
- return ctx->update(ctx, data, count);
+ return ctx->update != NULL ? ctx->update(ctx, data, count) : 0;
}
/* The caller can assume that this removes any secret data from the context */
int EVP_DigestFinal(EVP_MD_CTX *ctx, unsigned char *md, unsigned int *size)
{
int ret;
ret = EVP_DigestFinal_ex(ctx, md, size);
EVP_MD_CTX_reset(ctx);
return ret;
}
/* The caller can assume that this removes any secret data from the context */
int EVP_DigestFinal_ex(EVP_MD_CTX *ctx, unsigned char *md, unsigned int *isize)
{
int ret, sz;
size_t size = 0;
size_t mdsize = 0;
if (ctx->digest == NULL)
return 0;
sz = EVP_MD_get_size(ctx->digest);
if (sz < 0)
return 0;
mdsize = sz;
if (ctx->digest->prov == NULL)
goto legacy;
if (ctx->digest->dfinal == NULL) {
ERR_raise(ERR_LIB_EVP, EVP_R_FINAL_ERROR);
return 0;
}
ret = ctx->digest->dfinal(ctx->algctx, md, &size, mdsize);
if (isize != NULL) {
if (size <= UINT_MAX) {
*isize = (unsigned int)size;
} else {
ERR_raise(ERR_LIB_EVP, EVP_R_FINAL_ERROR);
ret = 0;
}
}
return ret;
/* Code below to be removed when legacy support is dropped. */
legacy:
OPENSSL_assert(mdsize <= EVP_MAX_MD_SIZE);
ret = ctx->digest->final(ctx, md);
if (isize != NULL)
*isize = mdsize;
if (ctx->digest->cleanup) {
ctx->digest->cleanup(ctx);
EVP_MD_CTX_set_flags(ctx, EVP_MD_CTX_FLAG_CLEANED);
}
OPENSSL_cleanse(ctx->md_data, ctx->digest->ctx_size);
return ret;
}
int EVP_DigestFinalXOF(EVP_MD_CTX *ctx, unsigned char *md, size_t size)
{
int ret = 0;
OSSL_PARAM params[2];
size_t i = 0;
if (ctx->digest == NULL) {
ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_NULL_ALGORITHM);
return 0;
}
if (ctx->digest->prov == NULL)
goto legacy;
if (ctx->digest->dfinal == NULL) {
ERR_raise(ERR_LIB_EVP, EVP_R_FINAL_ERROR);
return 0;
}
params[i++] = OSSL_PARAM_construct_size_t(OSSL_DIGEST_PARAM_XOFLEN, &size);
params[i++] = OSSL_PARAM_construct_end();
if (EVP_MD_CTX_set_params(ctx, params) > 0)
ret = ctx->digest->dfinal(ctx->algctx, md, &size, size);
return ret;
legacy:
if (ctx->digest->flags & EVP_MD_FLAG_XOF
&& size <= INT_MAX
&& ctx->digest->md_ctrl(ctx, EVP_MD_CTRL_XOF_LEN, (int)size, NULL)) {
ret = ctx->digest->final(ctx, md);
if (ctx->digest->cleanup != NULL) {
ctx->digest->cleanup(ctx);
EVP_MD_CTX_set_flags(ctx, EVP_MD_CTX_FLAG_CLEANED);
}
OPENSSL_cleanse(ctx->md_data, ctx->digest->ctx_size);
} else {
ERR_raise(ERR_LIB_EVP, EVP_R_NOT_XOF_OR_INVALID_LENGTH);
}
return ret;
}
int EVP_MD_CTX_copy(EVP_MD_CTX *out, const EVP_MD_CTX *in)
{
EVP_MD_CTX_reset(out);
return EVP_MD_CTX_copy_ex(out, in);
}
int EVP_MD_CTX_copy_ex(EVP_MD_CTX *out, const EVP_MD_CTX *in)
{
int digest_change = 0;
unsigned char *tmp_buf;
if (in == NULL) {
ERR_raise(ERR_LIB_EVP, ERR_R_PASSED_NULL_PARAMETER);
return 0;
}
if (in->digest == NULL) {
/* copying uninitialized digest context */
EVP_MD_CTX_reset(out);
if (out->fetched_digest != NULL)
EVP_MD_free(out->fetched_digest);
*out = *in;
goto clone_pkey;
}
if (in->digest->prov == NULL
|| (in->flags & EVP_MD_CTX_FLAG_NO_INIT) != 0)
goto legacy;
if (in->digest->dupctx == NULL) {
ERR_raise(ERR_LIB_EVP, EVP_R_NOT_ABLE_TO_COPY_CTX);
return 0;
}
evp_md_ctx_reset_ex(out, 1);
digest_change = (out->fetched_digest != in->fetched_digest);
if (digest_change && out->fetched_digest != NULL)
EVP_MD_free(out->fetched_digest);
*out = *in;
/* NULL out pointers in case of error */
out->pctx = NULL;
out->algctx = NULL;
if (digest_change && in->fetched_digest != NULL)
EVP_MD_up_ref(in->fetched_digest);
if (in->algctx != NULL) {
out->algctx = in->digest->dupctx(in->algctx);
if (out->algctx == NULL) {
ERR_raise(ERR_LIB_EVP, EVP_R_NOT_ABLE_TO_COPY_CTX);
return 0;
}
}
clone_pkey:
/* copied EVP_MD_CTX should free the copied EVP_PKEY_CTX */
EVP_MD_CTX_clear_flags(out, EVP_MD_CTX_FLAG_KEEP_PKEY_CTX);
#ifndef FIPS_MODULE
if (in->pctx != NULL) {
out->pctx = EVP_PKEY_CTX_dup(in->pctx);
if (out->pctx == NULL) {
ERR_raise(ERR_LIB_EVP, EVP_R_NOT_ABLE_TO_COPY_CTX);
EVP_MD_CTX_reset(out);
return 0;
}
}
#endif
return 1;
/* Code below to be removed when legacy support is dropped. */
legacy:
#if !defined(OPENSSL_NO_ENGINE) && !defined(FIPS_MODULE)
/* Make sure it's safe to copy a digest context using an ENGINE */
if (in->engine && !ENGINE_init(in->engine)) {
ERR_raise(ERR_LIB_EVP, ERR_R_ENGINE_LIB);
return 0;
}
#endif
if (out->digest == in->digest) {
tmp_buf = out->md_data;
EVP_MD_CTX_set_flags(out, EVP_MD_CTX_FLAG_REUSE);
} else
tmp_buf = NULL;
EVP_MD_CTX_reset(out);
memcpy(out, in, sizeof(*out));
/* copied EVP_MD_CTX should free the copied EVP_PKEY_CTX */
EVP_MD_CTX_clear_flags(out, EVP_MD_CTX_FLAG_KEEP_PKEY_CTX);
/* Null these variables, since they are getting fixed up
* properly below. Anything else may cause a memleak and/or
* double free if any of the memory allocations below fail
*/
out->md_data = NULL;
out->pctx = NULL;
if (in->md_data && out->digest->ctx_size) {
if (tmp_buf)
out->md_data = tmp_buf;
else {
out->md_data = OPENSSL_malloc(out->digest->ctx_size);
if (out->md_data == NULL) {
ERR_raise(ERR_LIB_EVP, ERR_R_MALLOC_FAILURE);
return 0;
}
}
memcpy(out->md_data, in->md_data, out->digest->ctx_size);
}
out->update = in->update;
#ifndef FIPS_MODULE
if (in->pctx) {
out->pctx = EVP_PKEY_CTX_dup(in->pctx);
if (!out->pctx) {
EVP_MD_CTX_reset(out);
return 0;
}
}
#endif
if (out->digest->copy)
return out->digest->copy(out, in);
return 1;
}
int EVP_Digest(const void *data, size_t count,
unsigned char *md, unsigned int *size, const EVP_MD *type,
ENGINE *impl)
{
EVP_MD_CTX *ctx = EVP_MD_CTX_new();
int ret;
if (ctx == NULL)
return 0;
EVP_MD_CTX_set_flags(ctx, EVP_MD_CTX_FLAG_ONESHOT);
ret = EVP_DigestInit_ex(ctx, type, impl)
&& EVP_DigestUpdate(ctx, data, count)
&& EVP_DigestFinal_ex(ctx, md, size);
EVP_MD_CTX_free(ctx);
return ret;
}
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)
{
EVP_MD *digest = EVP_MD_fetch(libctx, name, propq);
unsigned int temp = 0;
int ret = 0;
if (digest != NULL) {
ret = EVP_Digest(data, datalen, md, &temp, digest, NULL);
EVP_MD_free(digest);
}
if (mdlen != NULL)
*mdlen = temp;
return ret;
}
int EVP_MD_get_params(const EVP_MD *digest, OSSL_PARAM params[])
{
if (digest != NULL && digest->get_params != NULL)
return digest->get_params(params);
return 0;
}
const OSSL_PARAM *EVP_MD_gettable_params(const EVP_MD *digest)
{
if (digest != NULL && digest->gettable_params != NULL)
return digest->gettable_params(
ossl_provider_ctx(EVP_MD_get0_provider(digest)));
return NULL;
}
int EVP_MD_CTX_set_params(EVP_MD_CTX *ctx, const OSSL_PARAM params[])
{
EVP_PKEY_CTX *pctx = ctx->pctx;
/* If we have a pctx then we should try that first */
if (pctx != NULL
&& (pctx->operation == EVP_PKEY_OP_VERIFYCTX
|| pctx->operation == EVP_PKEY_OP_SIGNCTX)
&& pctx->op.sig.algctx != NULL
&& pctx->op.sig.signature->set_ctx_md_params != NULL)
return pctx->op.sig.signature->set_ctx_md_params(pctx->op.sig.algctx,
params);
if (ctx->digest != NULL && ctx->digest->set_ctx_params != NULL)
return ctx->digest->set_ctx_params(ctx->algctx, params);
return 0;
}
const OSSL_PARAM *EVP_MD_settable_ctx_params(const EVP_MD *md)
{
void *provctx;
if (md != NULL && md->settable_ctx_params != NULL) {
provctx = ossl_provider_ctx(EVP_MD_get0_provider(md));
return md->settable_ctx_params(NULL, provctx);
}
return NULL;
}
const OSSL_PARAM *EVP_MD_CTX_settable_params(EVP_MD_CTX *ctx)
{
EVP_PKEY_CTX *pctx;
void *alg;
if (ctx == NULL)
return NULL;
/* If we have a pctx then we should try that first */
pctx = ctx->pctx;
if (pctx != NULL
&& (pctx->operation == EVP_PKEY_OP_VERIFYCTX
|| pctx->operation == EVP_PKEY_OP_SIGNCTX)
&& pctx->op.sig.algctx != NULL
&& pctx->op.sig.signature->settable_ctx_md_params != NULL)
return pctx->op.sig.signature->settable_ctx_md_params(
pctx->op.sig.algctx);
if (ctx->digest != NULL && ctx->digest->settable_ctx_params != NULL) {
alg = ossl_provider_ctx(EVP_MD_get0_provider(ctx->digest));
return ctx->digest->settable_ctx_params(ctx->algctx, alg);
}
return NULL;
}
int EVP_MD_CTX_get_params(EVP_MD_CTX *ctx, OSSL_PARAM params[])
{
EVP_PKEY_CTX *pctx = ctx->pctx;
/* If we have a pctx then we should try that first */
if (pctx != NULL
&& (pctx->operation == EVP_PKEY_OP_VERIFYCTX
|| pctx->operation == EVP_PKEY_OP_SIGNCTX)
&& pctx->op.sig.algctx != NULL
&& pctx->op.sig.signature->get_ctx_md_params != NULL)
return pctx->op.sig.signature->get_ctx_md_params(pctx->op.sig.algctx,
params);
if (ctx->digest != NULL && ctx->digest->get_ctx_params != NULL)
return ctx->digest->get_ctx_params(ctx->algctx, params);
return 0;
}
const OSSL_PARAM *EVP_MD_gettable_ctx_params(const EVP_MD *md)
{
void *provctx;
if (md != NULL && md->gettable_ctx_params != NULL) {
provctx = ossl_provider_ctx(EVP_MD_get0_provider(md));
return md->gettable_ctx_params(NULL, provctx);
}
return NULL;
}
const OSSL_PARAM *EVP_MD_CTX_gettable_params(EVP_MD_CTX *ctx)
{
EVP_PKEY_CTX *pctx;
void *provctx;
if (ctx == NULL)
return NULL;
/* If we have a pctx then we should try that first */
pctx = ctx->pctx;
if (pctx != NULL
&& (pctx->operation == EVP_PKEY_OP_VERIFYCTX
|| pctx->operation == EVP_PKEY_OP_SIGNCTX)
&& pctx->op.sig.algctx != NULL
&& pctx->op.sig.signature->gettable_ctx_md_params != NULL)
return pctx->op.sig.signature->gettable_ctx_md_params(
pctx->op.sig.algctx);
if (ctx->digest != NULL && ctx->digest->gettable_ctx_params != NULL) {
provctx = ossl_provider_ctx(EVP_MD_get0_provider(ctx->digest));
return ctx->digest->gettable_ctx_params(ctx->algctx, provctx);
}
return NULL;
}
int EVP_MD_CTX_ctrl(EVP_MD_CTX *ctx, int cmd, int p1, void *p2)
{
int ret = EVP_CTRL_RET_UNSUPPORTED;
int set_params = 1;
size_t sz;
OSSL_PARAM params[2] = { OSSL_PARAM_END, OSSL_PARAM_END };
if (ctx == NULL) {
ERR_raise(ERR_LIB_EVP, ERR_R_PASSED_NULL_PARAMETER);
return 0;
}
if (ctx->digest != NULL && ctx->digest->prov == NULL)
goto legacy;
switch (cmd) {
case EVP_MD_CTRL_XOF_LEN:
sz = (size_t)p1;
params[0] = OSSL_PARAM_construct_size_t(OSSL_DIGEST_PARAM_XOFLEN, &sz);
break;
case EVP_MD_CTRL_MICALG:
set_params = 0;
params[0] = OSSL_PARAM_construct_utf8_string(OSSL_DIGEST_PARAM_MICALG,
p2, p1 ? p1 : 9999);
break;
case EVP_CTRL_SSL3_MASTER_SECRET:
params[0] = OSSL_PARAM_construct_octet_string(OSSL_DIGEST_PARAM_SSL3_MS,
p2, p1);
break;
default:
goto conclude;
}
if (set_params)
ret = EVP_MD_CTX_set_params(ctx, params);
else
ret = EVP_MD_CTX_get_params(ctx, params);
goto conclude;
/* Code below to be removed when legacy support is dropped. */
legacy:
if (ctx->digest->md_ctrl == NULL) {
ERR_raise(ERR_LIB_EVP, EVP_R_CTRL_NOT_IMPLEMENTED);
return 0;
}
ret = ctx->digest->md_ctrl(ctx, cmd, p1, p2);
conclude:
if (ret <= 0)
return 0;
return ret;
}
EVP_MD *evp_md_new(void)
{
EVP_MD *md = OPENSSL_zalloc(sizeof(*md));
if (md != NULL) {
md->lock = CRYPTO_THREAD_lock_new();
if (md->lock == NULL) {
OPENSSL_free(md);
return NULL;
}
md->refcnt = 1;
}
return md;
}
/*
* FIPS module note: since internal fetches will be entirely
* provider based, we know that none of its code depends on legacy
* NIDs or any functionality that use them.
*/
#ifndef FIPS_MODULE
static void set_legacy_nid(const char *name, void *vlegacy_nid)
{
int nid;
int *legacy_nid = vlegacy_nid;
/*
* We use lowest level function to get the associated method, because
* higher level functions such as EVP_get_digestbyname() have changed
* to look at providers too.
*/
const void *legacy_method = OBJ_NAME_get(name, OBJ_NAME_TYPE_MD_METH);
if (*legacy_nid == -1) /* We found a clash already */
return;
if (legacy_method == NULL)
return;
nid = EVP_MD_nid(legacy_method);
if (*legacy_nid != NID_undef && *legacy_nid != nid) {
*legacy_nid = -1;
return;
}
*legacy_nid = nid;
}
#endif
static int evp_md_cache_constants(EVP_MD *md)
{
int ok, xof = 0, algid_absent = 0;
size_t blksz = 0;
size_t mdsize = 0;
OSSL_PARAM params[5];
params[0] = OSSL_PARAM_construct_size_t(OSSL_DIGEST_PARAM_BLOCK_SIZE, &blksz);
params[1] = OSSL_PARAM_construct_size_t(OSSL_DIGEST_PARAM_SIZE, &mdsize);
params[2] = OSSL_PARAM_construct_int(OSSL_DIGEST_PARAM_XOF, &xof);
params[3] = OSSL_PARAM_construct_int(OSSL_DIGEST_PARAM_ALGID_ABSENT,
&algid_absent);
params[4] = OSSL_PARAM_construct_end();
ok = evp_do_md_getparams(md, params) > 0;
if (mdsize > INT_MAX || blksz > INT_MAX)
ok = 0;
if (ok) {
md->block_size = (int)blksz;
md->md_size = (int)mdsize;
if (xof)
md->flags |= EVP_MD_FLAG_XOF;
if (algid_absent)
md->flags |= EVP_MD_FLAG_DIGALGID_ABSENT;
}
return ok;
}
static void *evp_md_from_algorithm(int name_id,
const OSSL_ALGORITHM *algodef,
OSSL_PROVIDER *prov)
{
const OSSL_DISPATCH *fns = algodef->implementation;
EVP_MD *md = NULL;
int fncnt = 0;
/* EVP_MD_fetch() will set the legacy NID if available */
if ((md = evp_md_new()) == NULL) {
ERR_raise(ERR_LIB_EVP, ERR_R_MALLOC_FAILURE);
return NULL;
}
#ifndef FIPS_MODULE
md->type = NID_undef;
if (!evp_names_do_all(prov, name_id, set_legacy_nid, &md->type)
|| md->type == -1) {
ERR_raise(ERR_LIB_EVP, ERR_R_INTERNAL_ERROR);
EVP_MD_free(md);
return NULL;
}
#endif
md->name_id = name_id;
if ((md->type_name = ossl_algorithm_get1_first_name(algodef)) == NULL) {
EVP_MD_free(md);
return NULL;
}
md->description = algodef->algorithm_description;
for (; fns->function_id != 0; fns++) {
switch (fns->function_id) {
case OSSL_FUNC_DIGEST_NEWCTX:
if (md->newctx == NULL) {
md->newctx = OSSL_FUNC_digest_newctx(fns);
fncnt++;
}
break;
case OSSL_FUNC_DIGEST_INIT:
if (md->dinit == NULL) {
md->dinit = OSSL_FUNC_digest_init(fns);
fncnt++;
}
break;
case OSSL_FUNC_DIGEST_UPDATE:
if (md->dupdate == NULL) {
md->dupdate = OSSL_FUNC_digest_update(fns);
fncnt++;
}
break;
case OSSL_FUNC_DIGEST_FINAL:
if (md->dfinal == NULL) {
md->dfinal = OSSL_FUNC_digest_final(fns);
fncnt++;
}
break;
case OSSL_FUNC_DIGEST_DIGEST:
if (md->digest == NULL)
md->digest = OSSL_FUNC_digest_digest(fns);
/* We don't increment fnct for this as it is stand alone */
break;
case OSSL_FUNC_DIGEST_FREECTX:
if (md->freectx == NULL) {
md->freectx = OSSL_FUNC_digest_freectx(fns);
fncnt++;
}
break;
case OSSL_FUNC_DIGEST_DUPCTX:
if (md->dupctx == NULL)
md->dupctx = OSSL_FUNC_digest_dupctx(fns);
break;
case OSSL_FUNC_DIGEST_GET_PARAMS:
if (md->get_params == NULL)
md->get_params = OSSL_FUNC_digest_get_params(fns);
break;
case OSSL_FUNC_DIGEST_SET_CTX_PARAMS:
if (md->set_ctx_params == NULL)
md->set_ctx_params = OSSL_FUNC_digest_set_ctx_params(fns);
break;
case OSSL_FUNC_DIGEST_GET_CTX_PARAMS:
if (md->get_ctx_params == NULL)
md->get_ctx_params = OSSL_FUNC_digest_get_ctx_params(fns);
break;
case OSSL_FUNC_DIGEST_GETTABLE_PARAMS:
if (md->gettable_params == NULL)
md->gettable_params = OSSL_FUNC_digest_gettable_params(fns);
break;
case OSSL_FUNC_DIGEST_SETTABLE_CTX_PARAMS:
if (md->settable_ctx_params == NULL)
md->settable_ctx_params =
OSSL_FUNC_digest_settable_ctx_params(fns);
break;
case OSSL_FUNC_DIGEST_GETTABLE_CTX_PARAMS:
if (md->gettable_ctx_params == NULL)
md->gettable_ctx_params =
OSSL_FUNC_digest_gettable_ctx_params(fns);
break;
}
}
if ((fncnt != 0 && fncnt != 5)
|| (fncnt == 0 && md->digest == NULL)) {
/*
* In order to be a consistent set of functions we either need the
* whole set of init/update/final etc functions or none of them.
* The "digest" function can standalone. We at least need one way to
* generate digests.
*/
EVP_MD_free(md);
ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_PROVIDER_FUNCTIONS);
return NULL;
}
md->prov = prov;
if (prov != NULL)
ossl_provider_up_ref(prov);
if (!evp_md_cache_constants(md)) {
EVP_MD_free(md);
ERR_raise(ERR_LIB_EVP, EVP_R_CACHE_CONSTANTS_FAILED);
md = NULL;
}
return md;
}
static int evp_md_up_ref(void *md)
{
return EVP_MD_up_ref(md);
}
static void evp_md_free(void *md)
{
EVP_MD_free(md);
}
EVP_MD *EVP_MD_fetch(OSSL_LIB_CTX *ctx, const char *algorithm,
const char *properties)
{
EVP_MD *md =
evp_generic_fetch(ctx, OSSL_OP_DIGEST, algorithm, properties,
evp_md_from_algorithm, evp_md_up_ref, evp_md_free);
return md;
}
int EVP_MD_up_ref(EVP_MD *md)
{
int ref = 0;
if (md->origin == EVP_ORIG_DYNAMIC)
CRYPTO_UP_REF(&md->refcnt, &ref, md->lock);
return 1;
}
void EVP_MD_free(EVP_MD *md)
{
int i;
if (md == NULL || md->origin != EVP_ORIG_DYNAMIC)
return;
CRYPTO_DOWN_REF(&md->refcnt, &i, md->lock);
if (i > 0)
return;
evp_md_free_int(md);
}
void EVP_MD_do_all_provided(OSSL_LIB_CTX *libctx,
void (*fn)(EVP_MD *mac, void *arg),
void *arg)
{
evp_generic_do_all(libctx, OSSL_OP_DIGEST,
(void (*)(void *, void *))fn, arg,
evp_md_from_algorithm, evp_md_up_ref, evp_md_free);
}
diff --git a/crypto/openssl/crypto/evp/names.c b/crypto/openssl/crypto/evp/names.c
index 19c03a3085e8..7ff850f99753 100644
--- a/crypto/openssl/crypto/evp/names.c
+++ b/crypto/openssl/crypto/evp/names.c
@@ -1,254 +1,280 @@
/*
- * 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 <stdio.h>
#include <openssl/evp.h>
#include <openssl/kdf.h>
#include <openssl/x509.h>
#include "internal/cryptlib.h"
#include "internal/namemap.h"
#include "crypto/objects.h"
#include "crypto/evp.h"
int EVP_add_cipher(const EVP_CIPHER *c)
{
int r;
if (c == NULL)
return 0;
r = OBJ_NAME_add(OBJ_nid2sn(c->nid), OBJ_NAME_TYPE_CIPHER_METH,
(const char *)c);
if (r == 0)
return 0;
r = OBJ_NAME_add(OBJ_nid2ln(c->nid), OBJ_NAME_TYPE_CIPHER_METH,
(const char *)c);
return r;
}
int EVP_add_digest(const EVP_MD *md)
{
int r;
const char *name;
name = OBJ_nid2sn(md->type);
r = OBJ_NAME_add(name, OBJ_NAME_TYPE_MD_METH, (const char *)md);
if (r == 0)
return 0;
r = OBJ_NAME_add(OBJ_nid2ln(md->type), OBJ_NAME_TYPE_MD_METH,
(const char *)md);
if (r == 0)
return 0;
if (md->pkey_type && md->type != md->pkey_type) {
r = OBJ_NAME_add(OBJ_nid2sn(md->pkey_type),
OBJ_NAME_TYPE_MD_METH | OBJ_NAME_ALIAS, name);
if (r == 0)
return 0;
r = OBJ_NAME_add(OBJ_nid2ln(md->pkey_type),
OBJ_NAME_TYPE_MD_METH | OBJ_NAME_ALIAS, name);
}
return r;
}
static void cipher_from_name(const char *name, void *data)
{
const EVP_CIPHER **cipher = data;
if (*cipher != NULL)
return;
*cipher = (const EVP_CIPHER *)OBJ_NAME_get(name, OBJ_NAME_TYPE_CIPHER_METH);
}
const EVP_CIPHER *EVP_get_cipherbyname(const char *name)
{
return evp_get_cipherbyname_ex(NULL, name);
}
const EVP_CIPHER *evp_get_cipherbyname_ex(OSSL_LIB_CTX *libctx,
const char *name)
{
const EVP_CIPHER *cp;
OSSL_NAMEMAP *namemap;
int id;
+ int do_retry = 1;
if (!OPENSSL_init_crypto(OPENSSL_INIT_ADD_ALL_CIPHERS, NULL))
return NULL;
cp = (const EVP_CIPHER *)OBJ_NAME_get(name, OBJ_NAME_TYPE_CIPHER_METH);
if (cp != NULL)
return cp;
/*
* It's not in the method database, but it might be there under a different
* name. So we check for aliases in the EVP namemap and try all of those
* in turn.
*/
namemap = ossl_namemap_stored(libctx);
+ retry:
id = ossl_namemap_name2num(namemap, name);
- if (id == 0)
- return NULL;
+ if (id == 0) {
+ EVP_CIPHER *fetched_cipher;
+
+ /* Try to fetch it because the name might not be known yet. */
+ if (!do_retry)
+ return NULL;
+ do_retry = 0;
+ ERR_set_mark();
+ fetched_cipher = EVP_CIPHER_fetch(libctx, name, NULL);
+ EVP_CIPHER_free(fetched_cipher);
+ ERR_pop_to_mark();
+ goto retry;
+ }
if (!ossl_namemap_doall_names(namemap, id, cipher_from_name, &cp))
return NULL;
return cp;
}
static void digest_from_name(const char *name, void *data)
{
const EVP_MD **md = data;
if (*md != NULL)
return;
*md = (const EVP_MD *)OBJ_NAME_get(name, OBJ_NAME_TYPE_MD_METH);
}
const EVP_MD *EVP_get_digestbyname(const char *name)
{
return evp_get_digestbyname_ex(NULL, name);
}
const EVP_MD *evp_get_digestbyname_ex(OSSL_LIB_CTX *libctx, const char *name)
{
const EVP_MD *dp;
OSSL_NAMEMAP *namemap;
int id;
+ int do_retry = 1;
if (!OPENSSL_init_crypto(OPENSSL_INIT_ADD_ALL_DIGESTS, NULL))
return NULL;
dp = (const EVP_MD *)OBJ_NAME_get(name, OBJ_NAME_TYPE_MD_METH);
if (dp != NULL)
return dp;
/*
* It's not in the method database, but it might be there under a different
* name. So we check for aliases in the EVP namemap and try all of those
* in turn.
*/
namemap = ossl_namemap_stored(libctx);
+ retry:
id = ossl_namemap_name2num(namemap, name);
- if (id == 0)
- return NULL;
+ if (id == 0) {
+ EVP_MD *fetched_md;
+
+ /* Try to fetch it because the name might not be known yet. */
+ if (!do_retry)
+ return NULL;
+ do_retry = 0;
+ ERR_set_mark();
+ fetched_md = EVP_MD_fetch(libctx, name, NULL);
+ EVP_MD_free(fetched_md);
+ ERR_pop_to_mark();
+ goto retry;
+ }
if (!ossl_namemap_doall_names(namemap, id, digest_from_name, &dp))
return NULL;
return dp;
}
void evp_cleanup_int(void)
{
OBJ_NAME_cleanup(OBJ_NAME_TYPE_KDF_METH);
OBJ_NAME_cleanup(OBJ_NAME_TYPE_CIPHER_METH);
OBJ_NAME_cleanup(OBJ_NAME_TYPE_MD_METH);
/*
* The above calls will only clean out the contents of the name hash
* table, but not the hash table itself. The following line does that
* part. -- Richard Levitte
*/
OBJ_NAME_cleanup(-1);
EVP_PBE_cleanup();
OBJ_sigid_free();
evp_app_cleanup_int();
}
struct doall_cipher {
void *arg;
void (*fn) (const EVP_CIPHER *ciph,
const char *from, const char *to, void *arg);
};
static void do_all_cipher_fn(const OBJ_NAME *nm, void *arg)
{
struct doall_cipher *dc = arg;
if (nm->alias)
dc->fn(NULL, nm->name, nm->data, dc->arg);
else
dc->fn((const EVP_CIPHER *)nm->data, nm->name, NULL, dc->arg);
}
void EVP_CIPHER_do_all(void (*fn) (const EVP_CIPHER *ciph,
const char *from, const char *to, void *x),
void *arg)
{
struct doall_cipher dc;
/* Ignore errors */
OPENSSL_init_crypto(OPENSSL_INIT_ADD_ALL_CIPHERS, NULL);
dc.fn = fn;
dc.arg = arg;
OBJ_NAME_do_all(OBJ_NAME_TYPE_CIPHER_METH, do_all_cipher_fn, &dc);
}
void EVP_CIPHER_do_all_sorted(void (*fn) (const EVP_CIPHER *ciph,
const char *from, const char *to,
void *x), void *arg)
{
struct doall_cipher dc;
/* Ignore errors */
OPENSSL_init_crypto(OPENSSL_INIT_ADD_ALL_CIPHERS, NULL);
dc.fn = fn;
dc.arg = arg;
OBJ_NAME_do_all_sorted(OBJ_NAME_TYPE_CIPHER_METH, do_all_cipher_fn, &dc);
}
struct doall_md {
void *arg;
void (*fn) (const EVP_MD *ciph,
const char *from, const char *to, void *arg);
};
static void do_all_md_fn(const OBJ_NAME *nm, void *arg)
{
struct doall_md *dc = arg;
if (nm->alias)
dc->fn(NULL, nm->name, nm->data, dc->arg);
else
dc->fn((const EVP_MD *)nm->data, nm->name, NULL, dc->arg);
}
void EVP_MD_do_all(void (*fn) (const EVP_MD *md,
const char *from, const char *to, void *x),
void *arg)
{
struct doall_md dc;
/* Ignore errors */
OPENSSL_init_crypto(OPENSSL_INIT_ADD_ALL_DIGESTS, NULL);
dc.fn = fn;
dc.arg = arg;
OBJ_NAME_do_all(OBJ_NAME_TYPE_MD_METH, do_all_md_fn, &dc);
}
void EVP_MD_do_all_sorted(void (*fn) (const EVP_MD *md,
const char *from, const char *to,
void *x), void *arg)
{
struct doall_md dc;
OPENSSL_init_crypto(OPENSSL_INIT_ADD_ALL_DIGESTS, NULL);
dc.fn = fn;
dc.arg = arg;
OBJ_NAME_do_all_sorted(OBJ_NAME_TYPE_MD_METH, do_all_md_fn, &dc);
}
diff --git a/crypto/openssl/crypto/evp/pmeth_lib.c b/crypto/openssl/crypto/evp/pmeth_lib.c
index cffd88725c85..5cd0c4b27f6d 100644
--- a/crypto/openssl/crypto/evp/pmeth_lib.c
+++ b/crypto/openssl/crypto/evp/pmeth_lib.c
@@ -1,2134 +1,2141 @@
/*
* 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];
+ const OSSL_PARAM *gettables;
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;
}
+ /* Check for older provider that doesn't support getting this parameter */
+ gettables = EVP_PKEY_CTX_gettable_params(ctx);
+ if (gettables == NULL || OSSL_PARAM_locate_const(gettables, param) == NULL)
+ return evp_pkey_ctx_set1_octet_string(ctx, fallback, param, op, ctrl,
+ data, datalen);
+
/* 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 */
+ /* This should not happen but check to be sure. */
if (os_params[0].return_size == OSSL_PARAM_UNMODIFIED)
- return evp_pkey_ctx_set1_octet_string(ctx, fallback, param, op, ctrl, data, datalen);
+ return 0;
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_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/o_str.c b/crypto/openssl/crypto/o_str.c
index c631f8aff26a..a6598171535e 100644
--- a/crypto/openssl/crypto/o_str.c
+++ b/crypto/openssl/crypto/o_str.c
@@ -1,366 +1,368 @@
/*
* 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 (len == 0)
+ ++len;
if (strlength != NULL)
*strlength = len;
if (str == NULL)
return 1;
- if (str_n < (unsigned long)len) {
+ if (str_n < 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)
+ if (has_sep && buflen > 0)
--q;
*q = CH_ZERO;
#ifdef CHARSET_EBCDIC
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/pkcs12/p12_crt.c b/crypto/openssl/crypto/pkcs12/p12_crt.c
index 26a444f868b0..1a48e5c611da 100644
--- a/crypto/openssl/crypto/pkcs12/p12_crt.c
+++ b/crypto/openssl/crypto/pkcs12/p12_crt.c
@@ -1,359 +1,362 @@
/*
- * Copyright 1999-2023 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 <stdio.h>
#include "internal/cryptlib.h"
#include <openssl/pkcs12.h>
#include "p12_local.h"
static int pkcs12_add_bag(STACK_OF(PKCS12_SAFEBAG) **pbags,
PKCS12_SAFEBAG *bag);
static PKCS12_SAFEBAG *pkcs12_add_cert_bag(STACK_OF(PKCS12_SAFEBAG) **pbags,
X509 *cert,
const char *name,
int namelen,
unsigned char *keyid,
int keyidlen);
static int copy_bag_attr(PKCS12_SAFEBAG *bag, EVP_PKEY *pkey, int nid)
{
int idx;
X509_ATTRIBUTE *attr;
idx = EVP_PKEY_get_attr_by_NID(pkey, nid, -1);
if (idx < 0)
return 1;
attr = EVP_PKEY_get_attr(pkey, idx);
if (!X509at_add1_attr(&bag->attrib, attr))
return 0;
return 1;
}
PKCS12 *PKCS12_create_ex(const char *pass, const char *name, EVP_PKEY *pkey,
X509 *cert, STACK_OF(X509) *ca, int nid_key, int nid_cert,
int iter, int mac_iter, int keytype,
OSSL_LIB_CTX *ctx, const char *propq)
{
PKCS12 *p12 = NULL;
STACK_OF(PKCS7) *safes = NULL;
STACK_OF(PKCS12_SAFEBAG) *bags = NULL;
PKCS12_SAFEBAG *bag = NULL;
int i;
unsigned char keyid[EVP_MAX_MD_SIZE];
unsigned int keyidlen = 0;
int namelen = -1;
unsigned char *pkeyid = NULL;
int pkeyidlen = -1;
/* Set defaults */
if (nid_cert == NID_undef)
nid_cert = NID_aes_256_cbc;
if (nid_key == NID_undef)
nid_key = NID_aes_256_cbc;
if (!iter)
iter = PKCS12_DEFAULT_ITER;
if (!mac_iter)
mac_iter = PKCS12_DEFAULT_ITER;
if (pkey == NULL && cert == NULL && ca == NULL) {
ERR_raise(ERR_LIB_PKCS12, PKCS12_R_INVALID_NULL_ARGUMENT);
return NULL;
}
if (pkey && cert) {
if (!X509_check_private_key(cert, pkey))
return NULL;
if (!X509_digest(cert, EVP_sha1(), keyid, &keyidlen))
return NULL;
}
if (cert) {
if (name == NULL)
name = (char *)X509_alias_get0(cert, &namelen);
if (keyidlen > 0) {
pkeyid = keyid;
pkeyidlen = keyidlen;
} else {
pkeyid = X509_keyid_get0(cert, &pkeyidlen);
}
bag = pkcs12_add_cert_bag(&bags, cert, name, namelen, pkeyid, pkeyidlen);
}
/* Add all other certificates */
for (i = 0; i < sk_X509_num(ca); i++) {
if (!PKCS12_add_cert(&bags, sk_X509_value(ca, i)))
goto err;
}
if (bags && !PKCS12_add_safe_ex(&safes, bags, nid_cert, iter, pass,
ctx, propq))
goto err;
sk_PKCS12_SAFEBAG_pop_free(bags, PKCS12_SAFEBAG_free);
bags = NULL;
if (pkey) {
bag = PKCS12_add_key_ex(&bags, pkey, keytype, iter, nid_key, pass,
ctx, propq);
if (!bag)
goto err;
if (!copy_bag_attr(bag, pkey, NID_ms_csp_name))
goto err;
if (!copy_bag_attr(bag, pkey, NID_LocalKeySet))
goto err;
if (name && !PKCS12_add_friendlyname(bag, name, -1))
goto err;
if (keyidlen && !PKCS12_add_localkeyid(bag, keyid, keyidlen))
goto err;
}
if (bags && !PKCS12_add_safe(&safes, bags, -1, 0, NULL))
goto err;
sk_PKCS12_SAFEBAG_pop_free(bags, PKCS12_SAFEBAG_free);
bags = NULL;
p12 = PKCS12_add_safes_ex(safes, 0, ctx, propq);
if (p12 == NULL)
goto err;
sk_PKCS7_pop_free(safes, PKCS7_free);
safes = NULL;
if ((mac_iter != -1) &&
!PKCS12_set_mac(p12, pass, -1, NULL, 0, mac_iter, NULL))
goto err;
return p12;
err:
PKCS12_free(p12);
sk_PKCS7_pop_free(safes, PKCS7_free);
sk_PKCS12_SAFEBAG_pop_free(bags, PKCS12_SAFEBAG_free);
return NULL;
}
PKCS12 *PKCS12_create(const char *pass, const char *name, EVP_PKEY *pkey, X509 *cert,
STACK_OF(X509) *ca, int nid_key, int nid_cert, int iter,
int mac_iter, int keytype)
{
return PKCS12_create_ex(pass, name, pkey, cert, ca, nid_key, nid_cert,
iter, mac_iter, keytype, NULL, NULL);
}
static PKCS12_SAFEBAG *pkcs12_add_cert_bag(STACK_OF(PKCS12_SAFEBAG) **pbags,
X509 *cert,
const char *name,
int namelen,
unsigned char *keyid,
int keyidlen)
{
PKCS12_SAFEBAG *bag = NULL;
/* Add user certificate */
if ((bag = PKCS12_SAFEBAG_create_cert(cert)) == NULL)
goto err;
if (name != NULL && !PKCS12_add_friendlyname(bag, name, namelen))
goto err;
if (keyid != NULL && !PKCS12_add_localkeyid(bag, keyid, keyidlen))
goto err;
if (!pkcs12_add_bag(pbags, bag))
goto err;
return bag;
err:
PKCS12_SAFEBAG_free(bag);
return NULL;
}
PKCS12_SAFEBAG *PKCS12_add_cert(STACK_OF(PKCS12_SAFEBAG) **pbags, X509 *cert)
{
char *name = NULL;
int namelen = -1;
unsigned char *keyid = NULL;
int keyidlen = -1;
/*
* Use friendlyName and localKeyID in certificate. (if present)
*/
name = (char *)X509_alias_get0(cert, &namelen);
keyid = X509_keyid_get0(cert, &keyidlen);
return pkcs12_add_cert_bag(pbags, cert, name, namelen, keyid, keyidlen);
}
PKCS12_SAFEBAG *PKCS12_add_key_ex(STACK_OF(PKCS12_SAFEBAG) **pbags,
EVP_PKEY *key, int key_usage, int iter,
int nid_key, const char *pass,
OSSL_LIB_CTX *ctx, const char *propq)
{
PKCS12_SAFEBAG *bag = NULL;
PKCS8_PRIV_KEY_INFO *p8 = NULL;
/* Make a PKCS#8 structure */
if ((p8 = EVP_PKEY2PKCS8(key)) == NULL)
goto err;
if (key_usage && !PKCS8_add_keyusage(p8, key_usage))
goto err;
if (nid_key != -1) {
+ /* This call does not take ownership of p8 */
bag = PKCS12_SAFEBAG_create_pkcs8_encrypt_ex(nid_key, pass, -1, NULL, 0,
iter, p8, ctx, propq);
- PKCS8_PRIV_KEY_INFO_free(p8);
- } else
+ } else {
bag = PKCS12_SAFEBAG_create0_p8inf(p8);
+ if (bag != NULL)
+ p8 = NULL; /* bag takes ownership of p8 */
+ }
+ /* This does not need to be in the error path */
+ if (p8 != NULL)
+ PKCS8_PRIV_KEY_INFO_free(p8);
- if (!bag)
- goto err;
-
- if (!pkcs12_add_bag(pbags, bag))
+ if (bag == NULL || !pkcs12_add_bag(pbags, bag))
goto err;
return bag;
err:
PKCS12_SAFEBAG_free(bag);
return NULL;
}
PKCS12_SAFEBAG *PKCS12_add_key(STACK_OF(PKCS12_SAFEBAG) **pbags,
EVP_PKEY *key, int key_usage, int iter,
int nid_key, const char *pass)
{
return PKCS12_add_key_ex(pbags, key, key_usage, iter, nid_key, pass,
NULL, NULL);
}
PKCS12_SAFEBAG *PKCS12_add_secret(STACK_OF(PKCS12_SAFEBAG) **pbags,
int nid_type, const unsigned char *value, int len)
{
PKCS12_SAFEBAG *bag = NULL;
/* Add secret, storing the value as an octet string */
if ((bag = PKCS12_SAFEBAG_create_secret(nid_type, V_ASN1_OCTET_STRING, value, len)) == NULL)
goto err;
if (!pkcs12_add_bag(pbags, bag))
goto err;
return bag;
err:
PKCS12_SAFEBAG_free(bag);
return NULL;
}
int PKCS12_add_safe_ex(STACK_OF(PKCS7) **psafes, STACK_OF(PKCS12_SAFEBAG) *bags,
int nid_safe, int iter, const char *pass,
OSSL_LIB_CTX *ctx, const char *propq)
{
PKCS7 *p7 = NULL;
int free_safes = 0;
if (*psafes == NULL) {
*psafes = sk_PKCS7_new_null();
if (*psafes == NULL)
return 0;
free_safes = 1;
}
if (nid_safe == 0)
#ifdef OPENSSL_NO_RC2
nid_safe = NID_pbe_WithSHA1And3_Key_TripleDES_CBC;
#else
nid_safe = NID_pbe_WithSHA1And40BitRC2_CBC;
#endif
if (nid_safe == -1)
p7 = PKCS12_pack_p7data(bags);
else
p7 = PKCS12_pack_p7encdata_ex(nid_safe, pass, -1, NULL, 0, iter, bags, ctx, propq);
if (p7 == NULL)
goto err;
if (!sk_PKCS7_push(*psafes, p7))
goto err;
return 1;
err:
if (free_safes) {
sk_PKCS7_free(*psafes);
*psafes = NULL;
}
PKCS7_free(p7);
return 0;
}
int PKCS12_add_safe(STACK_OF(PKCS7) **psafes, STACK_OF(PKCS12_SAFEBAG) *bags,
int nid_safe, int iter, const char *pass)
{
return PKCS12_add_safe_ex(psafes, bags, nid_safe, iter, pass, NULL, NULL);
}
static int pkcs12_add_bag(STACK_OF(PKCS12_SAFEBAG) **pbags,
PKCS12_SAFEBAG *bag)
{
int free_bags = 0;
if (pbags == NULL)
return 1;
if (*pbags == NULL) {
*pbags = sk_PKCS12_SAFEBAG_new_null();
if (*pbags == NULL)
return 0;
free_bags = 1;
}
if (!sk_PKCS12_SAFEBAG_push(*pbags, bag)) {
if (free_bags) {
sk_PKCS12_SAFEBAG_free(*pbags);
*pbags = NULL;
}
return 0;
}
return 1;
}
PKCS12 *PKCS12_add_safes_ex(STACK_OF(PKCS7) *safes, int nid_p7,
OSSL_LIB_CTX *ctx, const char *propq)
{
PKCS12 *p12;
if (nid_p7 <= 0)
nid_p7 = NID_pkcs7_data;
p12 = PKCS12_init_ex(nid_p7, ctx, propq);
if (p12 == NULL)
return NULL;
if (!PKCS12_pack_authsafes(p12, safes)) {
PKCS12_free(p12);
return NULL;
}
return p12;
}
PKCS12 *PKCS12_add_safes(STACK_OF(PKCS7) *safes, int nid_p7)
{
return PKCS12_add_safes_ex(safes, nid_p7, NULL, NULL);
}
diff --git a/crypto/openssl/crypto/pkcs7/pk7_doit.c b/crypto/openssl/crypto/pkcs7/pk7_doit.c
index 1cef67b211af..d7791e5c4f47 100644
--- a/crypto/openssl/crypto/pkcs7/pk7_doit.c
+++ b/crypto/openssl/crypto/pkcs7/pk7_doit.c
@@ -1,1274 +1,1267 @@
/*
- * 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 <openssl/rand.h>
#include <openssl/objects.h>
#include <openssl/x509.h>
#include <openssl/x509v3.h>
#include <openssl/err.h>
#include "internal/cryptlib.h"
#include "internal/sizes.h"
#include "pk7_local.h"
static int add_attribute(STACK_OF(X509_ATTRIBUTE) **sk, int nid, int atrtype,
void *value);
static ASN1_TYPE *get_attribute(const STACK_OF(X509_ATTRIBUTE) *sk, int nid);
int PKCS7_type_is_other(PKCS7 *p7)
{
int isOther = 1;
int nid = OBJ_obj2nid(p7->type);
switch (nid) {
case NID_pkcs7_data:
case NID_pkcs7_signed:
case NID_pkcs7_enveloped:
case NID_pkcs7_signedAndEnveloped:
case NID_pkcs7_digest:
case NID_pkcs7_encrypted:
isOther = 0;
break;
default:
isOther = 1;
}
return isOther;
}
ASN1_OCTET_STRING *PKCS7_get_octet_string(PKCS7 *p7)
{
if (PKCS7_type_is_data(p7))
return p7->d.data;
if (PKCS7_type_is_other(p7) && p7->d.other
&& (p7->d.other->type == V_ASN1_OCTET_STRING))
return p7->d.other->value.octet_string;
return NULL;
}
static int pkcs7_bio_add_digest(BIO **pbio, X509_ALGOR *alg,
const PKCS7_CTX *ctx)
{
BIO *btmp;
char name[OSSL_MAX_NAME_SIZE];
EVP_MD *fetched = NULL;
const EVP_MD *md;
if ((btmp = BIO_new(BIO_f_md())) == NULL) {
ERR_raise(ERR_LIB_PKCS7, ERR_R_BIO_LIB);
goto err;
}
OBJ_obj2txt(name, sizeof(name), alg->algorithm, 0);
(void)ERR_set_mark();
fetched = EVP_MD_fetch(ossl_pkcs7_ctx_get0_libctx(ctx), name,
ossl_pkcs7_ctx_get0_propq(ctx));
if (fetched != NULL)
md = fetched;
else
md = EVP_get_digestbyname(name);
if (md == NULL) {
(void)ERR_clear_last_mark();
ERR_raise(ERR_LIB_PKCS7, PKCS7_R_UNKNOWN_DIGEST_TYPE);
goto err;
}
(void)ERR_pop_to_mark();
if (BIO_set_md(btmp, md) <= 0) {
ERR_raise(ERR_LIB_PKCS7, ERR_R_BIO_LIB);
EVP_MD_free(fetched);
goto err;
}
EVP_MD_free(fetched);
if (*pbio == NULL)
*pbio = btmp;
else if (!BIO_push(*pbio, btmp)) {
ERR_raise(ERR_LIB_PKCS7, ERR_R_BIO_LIB);
goto err;
}
btmp = NULL;
return 1;
err:
BIO_free(btmp);
return 0;
}
static int pkcs7_encode_rinfo(PKCS7_RECIP_INFO *ri,
unsigned char *key, int keylen)
{
EVP_PKEY_CTX *pctx = NULL;
EVP_PKEY *pkey = NULL;
unsigned char *ek = NULL;
int ret = 0;
size_t eklen;
const PKCS7_CTX *ctx = ri->ctx;
pkey = X509_get0_pubkey(ri->cert);
if (pkey == NULL)
return 0;
pctx = EVP_PKEY_CTX_new_from_pkey(ossl_pkcs7_ctx_get0_libctx(ctx), pkey,
ossl_pkcs7_ctx_get0_propq(ctx));
if (pctx == NULL)
return 0;
if (EVP_PKEY_encrypt_init(pctx) <= 0)
goto err;
if (EVP_PKEY_encrypt(pctx, NULL, &eklen, key, keylen) <= 0)
goto err;
ek = OPENSSL_malloc(eklen);
if (ek == NULL) {
ERR_raise(ERR_LIB_PKCS7, ERR_R_MALLOC_FAILURE);
goto err;
}
if (EVP_PKEY_encrypt(pctx, ek, &eklen, key, keylen) <= 0)
goto err;
ASN1_STRING_set0(ri->enc_key, ek, eklen);
ek = NULL;
ret = 1;
err:
EVP_PKEY_CTX_free(pctx);
OPENSSL_free(ek);
return ret;
}
static int pkcs7_decrypt_rinfo(unsigned char **pek, int *peklen,
PKCS7_RECIP_INFO *ri, EVP_PKEY *pkey,
size_t fixlen)
{
EVP_PKEY_CTX *pctx = NULL;
unsigned char *ek = NULL;
size_t eklen;
int ret = -1;
const PKCS7_CTX *ctx = ri->ctx;
pctx = EVP_PKEY_CTX_new_from_pkey(ossl_pkcs7_ctx_get0_libctx(ctx), pkey,
ossl_pkcs7_ctx_get0_propq(ctx));
if (pctx == NULL)
return -1;
if (EVP_PKEY_decrypt_init(pctx) <= 0)
goto err;
if (EVP_PKEY_decrypt(pctx, NULL, &eklen,
ri->enc_key->data, ri->enc_key->length) <= 0)
goto err;
ek = OPENSSL_malloc(eklen);
if (ek == NULL) {
ERR_raise(ERR_LIB_PKCS7, ERR_R_MALLOC_FAILURE);
goto err;
}
if (EVP_PKEY_decrypt(pctx, ek, &eklen,
ri->enc_key->data, ri->enc_key->length) <= 0
|| eklen == 0
|| (fixlen != 0 && eklen != fixlen)) {
ret = 0;
ERR_raise(ERR_LIB_PKCS7, ERR_R_EVP_LIB);
goto err;
}
ret = 1;
OPENSSL_clear_free(*pek, *peklen);
*pek = ek;
*peklen = eklen;
err:
EVP_PKEY_CTX_free(pctx);
if (!ret)
OPENSSL_free(ek);
return ret;
}
BIO *PKCS7_dataInit(PKCS7 *p7, BIO *bio)
{
int i;
BIO *out = NULL, *btmp = NULL;
X509_ALGOR *xa = NULL;
EVP_CIPHER *fetched_cipher = NULL;
const EVP_CIPHER *cipher;
const EVP_CIPHER *evp_cipher = NULL;
STACK_OF(X509_ALGOR) *md_sk = NULL;
STACK_OF(PKCS7_RECIP_INFO) *rsk = NULL;
X509_ALGOR *xalg = NULL;
PKCS7_RECIP_INFO *ri = NULL;
ASN1_OCTET_STRING *os = NULL;
const PKCS7_CTX *p7_ctx;
OSSL_LIB_CTX *libctx;
const char *propq;
if (p7 == NULL) {
ERR_raise(ERR_LIB_PKCS7, PKCS7_R_INVALID_NULL_POINTER);
return NULL;
}
p7_ctx = ossl_pkcs7_get0_ctx(p7);
libctx = ossl_pkcs7_ctx_get0_libctx(p7_ctx);
propq = ossl_pkcs7_ctx_get0_propq(p7_ctx);
/*
* The content field in the PKCS7 ContentInfo is optional, but that really
* only applies to inner content (precisely, detached signatures).
*
* When reading content, missing outer content is therefore treated as an
* error.
*
* When creating content, PKCS7_content_new() must be called before
* calling this method, so a NULL p7->d is always an error.
*/
if (p7->d.ptr == NULL) {
ERR_raise(ERR_LIB_PKCS7, PKCS7_R_NO_CONTENT);
return NULL;
}
i = OBJ_obj2nid(p7->type);
p7->state = PKCS7_S_HEADER;
switch (i) {
case NID_pkcs7_signed:
md_sk = p7->d.sign->md_algs;
os = PKCS7_get_octet_string(p7->d.sign->contents);
break;
case NID_pkcs7_signedAndEnveloped:
rsk = p7->d.signed_and_enveloped->recipientinfo;
md_sk = p7->d.signed_and_enveloped->md_algs;
xalg = p7->d.signed_and_enveloped->enc_data->algorithm;
evp_cipher = p7->d.signed_and_enveloped->enc_data->cipher;
if (evp_cipher == NULL) {
ERR_raise(ERR_LIB_PKCS7, PKCS7_R_CIPHER_NOT_INITIALIZED);
goto err;
}
break;
case NID_pkcs7_enveloped:
rsk = p7->d.enveloped->recipientinfo;
xalg = p7->d.enveloped->enc_data->algorithm;
evp_cipher = p7->d.enveloped->enc_data->cipher;
if (evp_cipher == NULL) {
ERR_raise(ERR_LIB_PKCS7, PKCS7_R_CIPHER_NOT_INITIALIZED);
goto err;
}
break;
case NID_pkcs7_digest:
xa = p7->d.digest->md;
os = PKCS7_get_octet_string(p7->d.digest->contents);
break;
case NID_pkcs7_data:
break;
default:
ERR_raise(ERR_LIB_PKCS7, PKCS7_R_UNSUPPORTED_CONTENT_TYPE);
goto err;
}
for (i = 0; i < sk_X509_ALGOR_num(md_sk); i++)
if (!pkcs7_bio_add_digest(&out, sk_X509_ALGOR_value(md_sk, i), p7_ctx))
goto err;
if (xa && !pkcs7_bio_add_digest(&out, xa, p7_ctx))
goto err;
if (evp_cipher != NULL) {
unsigned char key[EVP_MAX_KEY_LENGTH];
unsigned char iv[EVP_MAX_IV_LENGTH];
int keylen, ivlen;
EVP_CIPHER_CTX *ctx;
if ((btmp = BIO_new(BIO_f_cipher())) == NULL) {
ERR_raise(ERR_LIB_PKCS7, ERR_R_BIO_LIB);
goto err;
}
BIO_get_cipher_ctx(btmp, &ctx);
keylen = EVP_CIPHER_get_key_length(evp_cipher);
ivlen = EVP_CIPHER_get_iv_length(evp_cipher);
xalg->algorithm = OBJ_nid2obj(EVP_CIPHER_get_type(evp_cipher));
if (ivlen > 0)
if (RAND_bytes_ex(libctx, iv, ivlen, 0) <= 0)
goto err;
(void)ERR_set_mark();
fetched_cipher = EVP_CIPHER_fetch(libctx,
EVP_CIPHER_get0_name(evp_cipher),
propq);
(void)ERR_pop_to_mark();
if (fetched_cipher != NULL)
cipher = fetched_cipher;
else
cipher = evp_cipher;
if (EVP_CipherInit_ex(ctx, cipher, NULL, NULL, NULL, 1) <= 0)
goto err;
EVP_CIPHER_free(fetched_cipher);
fetched_cipher = NULL;
if (EVP_CIPHER_CTX_rand_key(ctx, key) <= 0)
goto err;
if (EVP_CipherInit_ex(ctx, NULL, NULL, key, iv, 1) <= 0)
goto err;
if (ivlen > 0) {
if (xalg->parameter == NULL) {
xalg->parameter = ASN1_TYPE_new();
if (xalg->parameter == NULL)
goto err;
}
if (EVP_CIPHER_param_to_asn1(ctx, xalg->parameter) <= 0)
goto err;
}
/* Lets do the pub key stuff :-) */
for (i = 0; i < sk_PKCS7_RECIP_INFO_num(rsk); i++) {
ri = sk_PKCS7_RECIP_INFO_value(rsk, i);
if (pkcs7_encode_rinfo(ri, key, keylen) <= 0)
goto err;
}
OPENSSL_cleanse(key, keylen);
if (out == NULL)
out = btmp;
else
BIO_push(out, btmp);
btmp = NULL;
}
if (bio == NULL) {
if (PKCS7_is_detached(p7)) {
bio = BIO_new(BIO_s_null());
} else if (os && os->length > 0) {
bio = BIO_new_mem_buf(os->data, os->length);
} else {
bio = BIO_new(BIO_s_mem());
if (bio == NULL)
goto err;
BIO_set_mem_eof_return(bio, 0);
}
if (bio == NULL)
goto err;
}
if (out)
BIO_push(out, bio);
else
out = bio;
return out;
err:
EVP_CIPHER_free(fetched_cipher);
BIO_free_all(out);
BIO_free_all(btmp);
return NULL;
}
static int pkcs7_cmp_ri(PKCS7_RECIP_INFO *ri, X509 *pcert)
{
int ret;
ret = X509_NAME_cmp(ri->issuer_and_serial->issuer,
X509_get_issuer_name(pcert));
if (ret)
return ret;
return ASN1_INTEGER_cmp(X509_get0_serialNumber(pcert),
ri->issuer_and_serial->serial);
}
/* int */
BIO *PKCS7_dataDecode(PKCS7 *p7, EVP_PKEY *pkey, BIO *in_bio, X509 *pcert)
{
int i, len;
BIO *out = NULL, *btmp = NULL, *etmp = NULL, *bio = NULL;
X509_ALGOR *xa;
ASN1_OCTET_STRING *data_body = NULL;
EVP_MD *evp_md = NULL;
const EVP_MD *md;
EVP_CIPHER *evp_cipher = NULL;
const EVP_CIPHER *cipher = NULL;
EVP_CIPHER_CTX *evp_ctx = NULL;
X509_ALGOR *enc_alg = NULL;
STACK_OF(X509_ALGOR) *md_sk = NULL;
STACK_OF(PKCS7_RECIP_INFO) *rsk = NULL;
PKCS7_RECIP_INFO *ri = NULL;
unsigned char *ek = NULL, *tkey = NULL;
int eklen = 0, tkeylen = 0;
char name[OSSL_MAX_NAME_SIZE];
const PKCS7_CTX *p7_ctx;
OSSL_LIB_CTX *libctx;
const char *propq;
if (p7 == NULL) {
ERR_raise(ERR_LIB_PKCS7, PKCS7_R_INVALID_NULL_POINTER);
return NULL;
}
p7_ctx = ossl_pkcs7_get0_ctx(p7);
libctx = ossl_pkcs7_ctx_get0_libctx(p7_ctx);
propq = ossl_pkcs7_ctx_get0_propq(p7_ctx);
if (p7->d.ptr == NULL) {
ERR_raise(ERR_LIB_PKCS7, PKCS7_R_NO_CONTENT);
return NULL;
}
i = OBJ_obj2nid(p7->type);
p7->state = PKCS7_S_HEADER;
switch (i) {
case NID_pkcs7_signed:
/*
* p7->d.sign->contents is a PKCS7 structure consisting of a contentType
* field and optional content.
* data_body is NULL if that structure has no (=detached) content
* or if the contentType is wrong (i.e., not "data").
*/
data_body = PKCS7_get_octet_string(p7->d.sign->contents);
if (!PKCS7_is_detached(p7) && data_body == NULL) {
ERR_raise(ERR_LIB_PKCS7, PKCS7_R_INVALID_SIGNED_DATA_TYPE);
goto err;
}
md_sk = p7->d.sign->md_algs;
break;
case NID_pkcs7_signedAndEnveloped:
rsk = p7->d.signed_and_enveloped->recipientinfo;
md_sk = p7->d.signed_and_enveloped->md_algs;
/* data_body is NULL if the optional EncryptedContent is missing. */
data_body = p7->d.signed_and_enveloped->enc_data->enc_data;
enc_alg = p7->d.signed_and_enveloped->enc_data->algorithm;
OBJ_obj2txt(name, sizeof(name), enc_alg->algorithm, 0);
(void)ERR_set_mark();
evp_cipher = EVP_CIPHER_fetch(libctx, name, propq);
if (evp_cipher != NULL)
cipher = evp_cipher;
else
cipher = EVP_get_cipherbyname(name);
if (cipher == NULL) {
(void)ERR_clear_last_mark();
ERR_raise(ERR_LIB_PKCS7, PKCS7_R_UNSUPPORTED_CIPHER_TYPE);
goto err;
}
(void)ERR_pop_to_mark();
break;
case NID_pkcs7_enveloped:
rsk = p7->d.enveloped->recipientinfo;
enc_alg = p7->d.enveloped->enc_data->algorithm;
/* data_body is NULL if the optional EncryptedContent is missing. */
data_body = p7->d.enveloped->enc_data->enc_data;
OBJ_obj2txt(name, sizeof(name), enc_alg->algorithm, 0);
(void)ERR_set_mark();
evp_cipher = EVP_CIPHER_fetch(libctx, name, propq);
if (evp_cipher != NULL)
cipher = evp_cipher;
else
cipher = EVP_get_cipherbyname(name);
if (cipher == NULL) {
(void)ERR_clear_last_mark();
ERR_raise(ERR_LIB_PKCS7, PKCS7_R_UNSUPPORTED_CIPHER_TYPE);
goto err;
}
(void)ERR_pop_to_mark();
break;
default:
ERR_raise(ERR_LIB_PKCS7, PKCS7_R_UNSUPPORTED_CONTENT_TYPE);
goto err;
}
/* Detached content must be supplied via in_bio instead. */
if (data_body == NULL && in_bio == NULL) {
ERR_raise(ERR_LIB_PKCS7, PKCS7_R_NO_CONTENT);
goto err;
}
/* We will be checking the signature */
if (md_sk != NULL) {
for (i = 0; i < sk_X509_ALGOR_num(md_sk); i++) {
xa = sk_X509_ALGOR_value(md_sk, i);
if ((btmp = BIO_new(BIO_f_md())) == NULL) {
ERR_raise(ERR_LIB_PKCS7, ERR_R_BIO_LIB);
goto err;
}
OBJ_obj2txt(name, sizeof(name), xa->algorithm, 0);
(void)ERR_set_mark();
evp_md = EVP_MD_fetch(libctx, name, propq);
if (evp_md != NULL)
md = evp_md;
else
md = EVP_get_digestbyname(name);
if (md == NULL) {
(void)ERR_clear_last_mark();
ERR_raise(ERR_LIB_PKCS7, PKCS7_R_UNKNOWN_DIGEST_TYPE);
goto err;
}
(void)ERR_pop_to_mark();
if (BIO_set_md(btmp, md) <= 0) {
EVP_MD_free(evp_md);
ERR_raise(ERR_LIB_PKCS7, ERR_R_BIO_LIB);
goto err;
}
EVP_MD_free(evp_md);
if (out == NULL)
out = btmp;
else
BIO_push(out, btmp);
btmp = NULL;
}
}
if (cipher != NULL) {
if ((etmp = BIO_new(BIO_f_cipher())) == NULL) {
ERR_raise(ERR_LIB_PKCS7, ERR_R_BIO_LIB);
goto err;
}
/*
* It was encrypted, we need to decrypt the secret key with the
* private key
*/
/*
* Find the recipientInfo which matches the passed certificate (if
* any)
*/
if (pcert) {
for (i = 0; i < sk_PKCS7_RECIP_INFO_num(rsk); i++) {
ri = sk_PKCS7_RECIP_INFO_value(rsk, i);
if (!pkcs7_cmp_ri(ri, pcert))
break;
ri = NULL;
}
if (ri == NULL) {
ERR_raise(ERR_LIB_PKCS7,
PKCS7_R_NO_RECIPIENT_MATCHES_CERTIFICATE);
goto err;
}
}
/* If we haven't got a certificate try each ri in turn */
if (pcert == NULL) {
/*
* Always attempt to decrypt all rinfo even after success as a
* defence against MMA timing attacks.
*/
for (i = 0; i < sk_PKCS7_RECIP_INFO_num(rsk); i++) {
ri = sk_PKCS7_RECIP_INFO_value(rsk, i);
ri->ctx = p7_ctx;
if (pkcs7_decrypt_rinfo(&ek, &eklen, ri, pkey,
EVP_CIPHER_get_key_length(cipher)) < 0)
goto err;
ERR_clear_error();
}
} else {
ri->ctx = p7_ctx;
/* Only exit on fatal errors, not decrypt failure */
if (pkcs7_decrypt_rinfo(&ek, &eklen, ri, pkey, 0) < 0)
goto err;
ERR_clear_error();
}
evp_ctx = NULL;
BIO_get_cipher_ctx(etmp, &evp_ctx);
if (EVP_CipherInit_ex(evp_ctx, cipher, NULL, NULL, NULL, 0) <= 0)
goto err;
if (EVP_CIPHER_asn1_to_param(evp_ctx, enc_alg->parameter) <= 0)
goto err;
/* Generate random key as MMA defence */
len = EVP_CIPHER_CTX_get_key_length(evp_ctx);
if (len <= 0)
goto err;
tkeylen = (size_t)len;
tkey = OPENSSL_malloc(tkeylen);
if (tkey == NULL)
goto err;
if (EVP_CIPHER_CTX_rand_key(evp_ctx, tkey) <= 0)
goto err;
if (ek == NULL) {
ek = tkey;
eklen = tkeylen;
tkey = NULL;
}
if (eklen != EVP_CIPHER_CTX_get_key_length(evp_ctx)) {
/*
* Some S/MIME clients don't use the same key and effective key
* length. The key length is determined by the size of the
* decrypted RSA key.
*/
if (EVP_CIPHER_CTX_set_key_length(evp_ctx, eklen) <= 0) {
/* Use random key as MMA defence */
OPENSSL_clear_free(ek, eklen);
ek = tkey;
eklen = tkeylen;
tkey = NULL;
}
}
/* Clear errors so we don't leak information useful in MMA */
ERR_clear_error();
if (EVP_CipherInit_ex(evp_ctx, NULL, NULL, ek, NULL, 0) <= 0)
goto err;
OPENSSL_clear_free(ek, eklen);
ek = NULL;
OPENSSL_clear_free(tkey, tkeylen);
tkey = NULL;
if (out == NULL)
out = etmp;
else
BIO_push(out, etmp);
etmp = NULL;
}
if (in_bio != NULL) {
bio = in_bio;
} else {
if (data_body->length > 0)
bio = BIO_new_mem_buf(data_body->data, data_body->length);
else {
bio = BIO_new(BIO_s_mem());
if (bio == NULL)
goto err;
BIO_set_mem_eof_return(bio, 0);
}
if (bio == NULL)
goto err;
}
BIO_push(out, bio);
bio = NULL;
EVP_CIPHER_free(evp_cipher);
return out;
err:
EVP_CIPHER_free(evp_cipher);
OPENSSL_clear_free(ek, eklen);
OPENSSL_clear_free(tkey, tkeylen);
BIO_free_all(out);
BIO_free_all(btmp);
BIO_free_all(etmp);
BIO_free_all(bio);
return NULL;
}
static BIO *PKCS7_find_digest(EVP_MD_CTX **pmd, BIO *bio, int nid)
{
for (;;) {
bio = BIO_find_type(bio, BIO_TYPE_MD);
if (bio == NULL) {
ERR_raise(ERR_LIB_PKCS7, PKCS7_R_UNABLE_TO_FIND_MESSAGE_DIGEST);
return NULL;
}
BIO_get_md_ctx(bio, pmd);
if (*pmd == NULL) {
ERR_raise(ERR_LIB_PKCS7, ERR_R_INTERNAL_ERROR);
return NULL;
}
if (EVP_MD_CTX_get_type(*pmd) == nid)
return bio;
bio = BIO_next(bio);
}
return NULL;
}
static int do_pkcs7_signed_attrib(PKCS7_SIGNER_INFO *si, EVP_MD_CTX *mctx)
{
unsigned char md_data[EVP_MAX_MD_SIZE];
unsigned int md_len;
/* Add signing time if not already present */
if (!PKCS7_get_signed_attribute(si, NID_pkcs9_signingTime)) {
if (!PKCS7_add0_attrib_signing_time(si, NULL)) {
ERR_raise(ERR_LIB_PKCS7, ERR_R_MALLOC_FAILURE);
return 0;
}
}
/* Add digest */
if (!EVP_DigestFinal_ex(mctx, md_data, &md_len)) {
ERR_raise(ERR_LIB_PKCS7, ERR_R_EVP_LIB);
return 0;
}
if (!PKCS7_add1_attrib_digest(si, md_data, md_len)) {
ERR_raise(ERR_LIB_PKCS7, ERR_R_MALLOC_FAILURE);
return 0;
}
/* Now sign the attributes */
if (!PKCS7_SIGNER_INFO_sign(si))
return 0;
return 1;
}
int PKCS7_dataFinal(PKCS7 *p7, BIO *bio)
{
int ret = 0;
int i, j;
BIO *btmp;
PKCS7_SIGNER_INFO *si;
EVP_MD_CTX *mdc, *ctx_tmp;
STACK_OF(X509_ATTRIBUTE) *sk;
STACK_OF(PKCS7_SIGNER_INFO) *si_sk = NULL;
ASN1_OCTET_STRING *os = NULL;
const PKCS7_CTX *p7_ctx;
if (p7 == NULL) {
ERR_raise(ERR_LIB_PKCS7, PKCS7_R_INVALID_NULL_POINTER);
return 0;
}
p7_ctx = ossl_pkcs7_get0_ctx(p7);
if (p7->d.ptr == NULL) {
ERR_raise(ERR_LIB_PKCS7, PKCS7_R_NO_CONTENT);
return 0;
}
ctx_tmp = EVP_MD_CTX_new();
if (ctx_tmp == NULL) {
ERR_raise(ERR_LIB_PKCS7, ERR_R_MALLOC_FAILURE);
return 0;
}
i = OBJ_obj2nid(p7->type);
p7->state = PKCS7_S_HEADER;
switch (i) {
case NID_pkcs7_data:
os = p7->d.data;
break;
case NID_pkcs7_signedAndEnveloped:
/* XXXXXXXXXXXXXXXX */
si_sk = p7->d.signed_and_enveloped->signer_info;
os = p7->d.signed_and_enveloped->enc_data->enc_data;
if (os == NULL) {
os = ASN1_OCTET_STRING_new();
if (os == NULL) {
ERR_raise(ERR_LIB_PKCS7, ERR_R_MALLOC_FAILURE);
goto err;
}
p7->d.signed_and_enveloped->enc_data->enc_data = os;
}
break;
case NID_pkcs7_enveloped:
/* XXXXXXXXXXXXXXXX */
os = p7->d.enveloped->enc_data->enc_data;
if (os == NULL) {
os = ASN1_OCTET_STRING_new();
if (os == NULL) {
ERR_raise(ERR_LIB_PKCS7, ERR_R_MALLOC_FAILURE);
goto err;
}
p7->d.enveloped->enc_data->enc_data = os;
}
break;
case NID_pkcs7_signed:
si_sk = p7->d.sign->signer_info;
os = PKCS7_get_octet_string(p7->d.sign->contents);
/* If detached data then the content is excluded */
if (PKCS7_type_is_data(p7->d.sign->contents) && p7->detached) {
ASN1_OCTET_STRING_free(os);
os = NULL;
p7->d.sign->contents->d.data = NULL;
}
break;
case NID_pkcs7_digest:
os = PKCS7_get_octet_string(p7->d.digest->contents);
/* If detached data then the content is excluded */
if (PKCS7_type_is_data(p7->d.digest->contents) && p7->detached) {
ASN1_OCTET_STRING_free(os);
os = NULL;
p7->d.digest->contents->d.data = NULL;
}
break;
default:
ERR_raise(ERR_LIB_PKCS7, PKCS7_R_UNSUPPORTED_CONTENT_TYPE);
goto err;
}
if (si_sk != NULL) {
for (i = 0; i < sk_PKCS7_SIGNER_INFO_num(si_sk); i++) {
si = sk_PKCS7_SIGNER_INFO_value(si_sk, i);
if (si->pkey == NULL)
continue;
j = OBJ_obj2nid(si->digest_alg->algorithm);
btmp = bio;
btmp = PKCS7_find_digest(&mdc, btmp, j);
if (btmp == NULL)
goto err;
/*
* We now have the EVP_MD_CTX, lets do the signing.
*/
if (!EVP_MD_CTX_copy_ex(ctx_tmp, mdc))
goto err;
sk = si->auth_attr;
/*
* If there are attributes, we add the digest attribute and only
* sign the attributes
*/
if (sk_X509_ATTRIBUTE_num(sk) > 0) {
if (!do_pkcs7_signed_attrib(si, ctx_tmp))
goto err;
} else {
unsigned char *abuf = NULL;
unsigned int abuflen;
abuflen = EVP_PKEY_get_size(si->pkey);
abuf = OPENSSL_malloc(abuflen);
if (abuf == NULL)
goto err;
if (!EVP_SignFinal_ex(ctx_tmp, abuf, &abuflen, si->pkey,
ossl_pkcs7_ctx_get0_libctx(p7_ctx),
ossl_pkcs7_ctx_get0_propq(p7_ctx))) {
OPENSSL_free(abuf);
ERR_raise(ERR_LIB_PKCS7, ERR_R_EVP_LIB);
goto err;
}
ASN1_STRING_set0(si->enc_digest, abuf, abuflen);
}
}
} else if (i == NID_pkcs7_digest) {
unsigned char md_data[EVP_MAX_MD_SIZE];
unsigned int md_len;
if (!PKCS7_find_digest(&mdc, bio,
OBJ_obj2nid(p7->d.digest->md->algorithm)))
goto err;
if (!EVP_DigestFinal_ex(mdc, md_data, &md_len))
goto err;
if (!ASN1_OCTET_STRING_set(p7->d.digest->digest, md_data, md_len))
goto err;
}
if (!PKCS7_is_detached(p7)) {
/*
* NOTE(emilia): I think we only reach os == NULL here because detached
* digested data support is broken.
*/
if (os == NULL)
goto err;
if (!(os->flags & ASN1_STRING_FLAG_NDEF)) {
char *cont;
long contlen;
btmp = BIO_find_type(bio, BIO_TYPE_MEM);
if (btmp == NULL) {
ERR_raise(ERR_LIB_PKCS7, PKCS7_R_UNABLE_TO_FIND_MEM_BIO);
goto err;
}
contlen = BIO_get_mem_data(btmp, &cont);
/*
* Mark the BIO read only then we can use its copy of the data
* instead of making an extra copy.
*/
BIO_set_flags(btmp, BIO_FLAGS_MEM_RDONLY);
BIO_set_mem_eof_return(btmp, 0);
ASN1_STRING_set0(os, (unsigned char *)cont, contlen);
}
}
ret = 1;
err:
EVP_MD_CTX_free(ctx_tmp);
return ret;
}
int PKCS7_SIGNER_INFO_sign(PKCS7_SIGNER_INFO *si)
{
EVP_MD_CTX *mctx;
EVP_PKEY_CTX *pctx = NULL;
unsigned char *abuf = NULL;
int alen;
size_t siglen;
const EVP_MD *md = NULL;
const PKCS7_CTX *ctx = si->ctx;
md = EVP_get_digestbyobj(si->digest_alg->algorithm);
if (md == NULL)
return 0;
mctx = EVP_MD_CTX_new();
if (mctx == NULL) {
ERR_raise(ERR_LIB_PKCS7, ERR_R_MALLOC_FAILURE);
goto err;
}
if (EVP_DigestSignInit_ex(mctx, &pctx, EVP_MD_get0_name(md),
ossl_pkcs7_ctx_get0_libctx(ctx),
ossl_pkcs7_ctx_get0_propq(ctx), si->pkey,
NULL) <= 0)
goto err;
alen = ASN1_item_i2d((ASN1_VALUE *)si->auth_attr, &abuf,
ASN1_ITEM_rptr(PKCS7_ATTR_SIGN));
if (!abuf)
goto err;
if (EVP_DigestSignUpdate(mctx, abuf, alen) <= 0)
goto err;
OPENSSL_free(abuf);
abuf = NULL;
if (EVP_DigestSignFinal(mctx, NULL, &siglen) <= 0)
goto err;
abuf = OPENSSL_malloc(siglen);
if (abuf == NULL)
goto err;
if (EVP_DigestSignFinal(mctx, abuf, &siglen) <= 0)
goto err;
EVP_MD_CTX_free(mctx);
ASN1_STRING_set0(si->enc_digest, abuf, siglen);
return 1;
err:
OPENSSL_free(abuf);
EVP_MD_CTX_free(mctx);
return 0;
}
int PKCS7_dataVerify(X509_STORE *cert_store, X509_STORE_CTX *ctx, BIO *bio,
PKCS7 *p7, PKCS7_SIGNER_INFO *si)
{
PKCS7_ISSUER_AND_SERIAL *ias;
int ret = 0, i;
STACK_OF(X509) *cert;
X509 *x509;
if (p7 == NULL) {
ERR_raise(ERR_LIB_PKCS7, PKCS7_R_INVALID_NULL_POINTER);
return 0;
}
if (p7->d.ptr == NULL) {
ERR_raise(ERR_LIB_PKCS7, PKCS7_R_NO_CONTENT);
return 0;
}
if (PKCS7_type_is_signed(p7)) {
cert = p7->d.sign->cert;
} else if (PKCS7_type_is_signedAndEnveloped(p7)) {
cert = p7->d.signed_and_enveloped->cert;
} else {
ERR_raise(ERR_LIB_PKCS7, PKCS7_R_WRONG_PKCS7_TYPE);
goto err;
}
/* XXXXXXXXXXXXXXXXXXXXXXX */
ias = si->issuer_and_serial;
x509 = X509_find_by_issuer_and_serial(cert, ias->issuer, ias->serial);
/* were we able to find the cert in passed to us */
if (x509 == NULL) {
ERR_raise(ERR_LIB_PKCS7, PKCS7_R_UNABLE_TO_FIND_CERTIFICATE);
goto err;
}
/* Lets verify */
if (!X509_STORE_CTX_init(ctx, cert_store, x509, cert)) {
ERR_raise(ERR_LIB_PKCS7, ERR_R_X509_LIB);
goto err;
}
X509_STORE_CTX_set_purpose(ctx, X509_PURPOSE_SMIME_SIGN);
i = X509_verify_cert(ctx);
if (i <= 0) {
ERR_raise(ERR_LIB_PKCS7, ERR_R_X509_LIB);
goto err;
}
return PKCS7_signatureVerify(bio, p7, si, x509);
err:
return ret;
}
int PKCS7_signatureVerify(BIO *bio, PKCS7 *p7, PKCS7_SIGNER_INFO *si,
X509 *x509)
{
ASN1_OCTET_STRING *os;
EVP_MD_CTX *mdc_tmp, *mdc;
const EVP_MD *md;
EVP_MD *fetched_md = NULL;
int ret = 0, i;
int md_type;
STACK_OF(X509_ATTRIBUTE) *sk;
BIO *btmp;
EVP_PKEY *pkey;
const PKCS7_CTX *ctx = ossl_pkcs7_get0_ctx(p7);
OSSL_LIB_CTX *libctx = ossl_pkcs7_ctx_get0_libctx(ctx);
const char *propq = ossl_pkcs7_ctx_get0_propq(ctx);
mdc_tmp = EVP_MD_CTX_new();
if (mdc_tmp == NULL) {
ERR_raise(ERR_LIB_PKCS7, ERR_R_MALLOC_FAILURE);
goto err;
}
if (!PKCS7_type_is_signed(p7) && !PKCS7_type_is_signedAndEnveloped(p7)) {
ERR_raise(ERR_LIB_PKCS7, PKCS7_R_WRONG_PKCS7_TYPE);
goto err;
}
md_type = OBJ_obj2nid(si->digest_alg->algorithm);
btmp = bio;
for (;;) {
if ((btmp == NULL) ||
((btmp = BIO_find_type(btmp, BIO_TYPE_MD)) == NULL)) {
ERR_raise(ERR_LIB_PKCS7, PKCS7_R_UNABLE_TO_FIND_MESSAGE_DIGEST);
goto err;
}
BIO_get_md_ctx(btmp, &mdc);
if (mdc == NULL) {
ERR_raise(ERR_LIB_PKCS7, ERR_R_INTERNAL_ERROR);
goto err;
}
if (EVP_MD_CTX_get_type(mdc) == md_type)
break;
/*
* Workaround for some broken clients that put the signature OID
* instead of the digest OID in digest_alg->algorithm
*/
if (EVP_MD_get_pkey_type(EVP_MD_CTX_get0_md(mdc)) == md_type)
break;
btmp = BIO_next(btmp);
}
/*
* mdc is the digest ctx that we want, unless there are attributes, in
* which case the digest is the signed attributes
*/
if (!EVP_MD_CTX_copy_ex(mdc_tmp, mdc))
goto err;
sk = si->auth_attr;
if ((sk != NULL) && (sk_X509_ATTRIBUTE_num(sk) != 0)) {
unsigned char md_dat[EVP_MAX_MD_SIZE], *abuf = NULL;
unsigned int md_len;
int alen;
ASN1_OCTET_STRING *message_digest;
if (!EVP_DigestFinal_ex(mdc_tmp, md_dat, &md_len))
goto err;
message_digest = PKCS7_digest_from_attributes(sk);
if (!message_digest) {
ERR_raise(ERR_LIB_PKCS7, PKCS7_R_UNABLE_TO_FIND_MESSAGE_DIGEST);
goto err;
}
if ((message_digest->length != (int)md_len) ||
(memcmp(message_digest->data, md_dat, md_len))) {
ERR_raise(ERR_LIB_PKCS7, PKCS7_R_DIGEST_FAILURE);
ret = -1;
goto err;
}
(void)ERR_set_mark();
fetched_md = EVP_MD_fetch(libctx, OBJ_nid2sn(md_type), propq);
if (fetched_md != NULL)
md = fetched_md;
else
md = EVP_get_digestbynid(md_type);
if (md == NULL || !EVP_VerifyInit_ex(mdc_tmp, md, NULL)) {
(void)ERR_clear_last_mark();
goto err;
}
(void)ERR_pop_to_mark();
alen = ASN1_item_i2d((ASN1_VALUE *)sk, &abuf,
ASN1_ITEM_rptr(PKCS7_ATTR_VERIFY));
if (alen <= 0) {
ERR_raise(ERR_LIB_PKCS7, ERR_R_ASN1_LIB);
ret = -1;
goto err;
}
if (!EVP_VerifyUpdate(mdc_tmp, abuf, alen))
goto err;
OPENSSL_free(abuf);
}
os = si->enc_digest;
pkey = X509_get0_pubkey(x509);
if (pkey == NULL) {
ret = -1;
goto err;
}
i = EVP_VerifyFinal_ex(mdc_tmp, os->data, os->length, pkey, libctx, propq);
if (i <= 0) {
ERR_raise(ERR_LIB_PKCS7, PKCS7_R_SIGNATURE_FAILURE);
ret = -1;
goto err;
}
ret = 1;
err:
EVP_MD_CTX_free(mdc_tmp);
EVP_MD_free(fetched_md);
return ret;
}
PKCS7_ISSUER_AND_SERIAL *PKCS7_get_issuer_and_serial(PKCS7 *p7, int idx)
{
STACK_OF(PKCS7_RECIP_INFO) *rsk;
PKCS7_RECIP_INFO *ri;
int i;
i = OBJ_obj2nid(p7->type);
if (i != NID_pkcs7_signedAndEnveloped)
return NULL;
if (p7->d.signed_and_enveloped == NULL)
return NULL;
rsk = p7->d.signed_and_enveloped->recipientinfo;
if (rsk == NULL)
return NULL;
if (sk_PKCS7_RECIP_INFO_num(rsk) <= idx)
return NULL;
ri = sk_PKCS7_RECIP_INFO_value(rsk, idx);
return ri->issuer_and_serial;
}
ASN1_TYPE *PKCS7_get_signed_attribute(const PKCS7_SIGNER_INFO *si, int nid)
{
return get_attribute(si->auth_attr, nid);
}
ASN1_TYPE *PKCS7_get_attribute(const PKCS7_SIGNER_INFO *si, int nid)
{
return get_attribute(si->unauth_attr, nid);
}
static ASN1_TYPE *get_attribute(const STACK_OF(X509_ATTRIBUTE) *sk, int nid)
{
int idx;
X509_ATTRIBUTE *xa;
idx = X509at_get_attr_by_NID(sk, nid, -1);
xa = X509at_get_attr(sk, idx);
return X509_ATTRIBUTE_get0_type(xa, 0);
}
ASN1_OCTET_STRING *PKCS7_digest_from_attributes(STACK_OF(X509_ATTRIBUTE) *sk)
{
ASN1_TYPE *astype;
if ((astype = get_attribute(sk, NID_pkcs9_messageDigest)) == NULL)
return NULL;
return astype->value.octet_string;
}
int PKCS7_set_signed_attributes(PKCS7_SIGNER_INFO *p7si,
STACK_OF(X509_ATTRIBUTE) *sk)
{
int i;
sk_X509_ATTRIBUTE_pop_free(p7si->auth_attr, X509_ATTRIBUTE_free);
p7si->auth_attr = sk_X509_ATTRIBUTE_dup(sk);
if (p7si->auth_attr == NULL)
return 0;
for (i = 0; i < sk_X509_ATTRIBUTE_num(sk); i++) {
if ((sk_X509_ATTRIBUTE_set(p7si->auth_attr, i,
X509_ATTRIBUTE_dup(sk_X509_ATTRIBUTE_value
(sk, i))))
== NULL)
return 0;
}
return 1;
}
int PKCS7_set_attributes(PKCS7_SIGNER_INFO *p7si,
STACK_OF(X509_ATTRIBUTE) *sk)
{
int i;
sk_X509_ATTRIBUTE_pop_free(p7si->unauth_attr, X509_ATTRIBUTE_free);
p7si->unauth_attr = sk_X509_ATTRIBUTE_dup(sk);
if (p7si->unauth_attr == NULL)
return 0;
for (i = 0; i < sk_X509_ATTRIBUTE_num(sk); i++) {
if ((sk_X509_ATTRIBUTE_set(p7si->unauth_attr, i,
X509_ATTRIBUTE_dup(sk_X509_ATTRIBUTE_value
(sk, i))))
== NULL)
return 0;
}
return 1;
}
int PKCS7_add_signed_attribute(PKCS7_SIGNER_INFO *p7si, int nid, int atrtype,
void *value)
{
return add_attribute(&(p7si->auth_attr), nid, atrtype, value);
}
int PKCS7_add_attribute(PKCS7_SIGNER_INFO *p7si, int nid, int atrtype,
void *value)
{
return add_attribute(&(p7si->unauth_attr), nid, atrtype, value);
}
static int add_attribute(STACK_OF(X509_ATTRIBUTE) **sk, int nid, int atrtype,
void *value)
{
X509_ATTRIBUTE *attr = NULL;
+ int i, n;
if (*sk == NULL) {
if ((*sk = sk_X509_ATTRIBUTE_new_null()) == NULL)
return 0;
- new_attrib:
- if ((attr = X509_ATTRIBUTE_create(nid, atrtype, value)) == NULL)
- return 0;
- if (!sk_X509_ATTRIBUTE_push(*sk, attr)) {
- X509_ATTRIBUTE_free(attr);
- return 0;
- }
- } else {
- int i;
-
- for (i = 0; i < sk_X509_ATTRIBUTE_num(*sk); i++) {
- attr = sk_X509_ATTRIBUTE_value(*sk, i);
- if (OBJ_obj2nid(X509_ATTRIBUTE_get0_object(attr)) == nid) {
- X509_ATTRIBUTE_free(attr);
- attr = X509_ATTRIBUTE_create(nid, atrtype, value);
- if (attr == NULL)
- return 0;
- if (!sk_X509_ATTRIBUTE_set(*sk, i, attr)) {
- X509_ATTRIBUTE_free(attr);
- return 0;
- }
- goto end;
- }
- }
- goto new_attrib;
}
+ n = sk_X509_ATTRIBUTE_num(*sk);
+ for (i = 0; i < n; i++) {
+ attr = sk_X509_ATTRIBUTE_value(*sk, i);
+ if (OBJ_obj2nid(X509_ATTRIBUTE_get0_object(attr)) == nid)
+ goto end;
+ }
+ if (!sk_X509_ATTRIBUTE_push(*sk, NULL))
+ return 0;
+
end:
+ attr = X509_ATTRIBUTE_create(nid, atrtype, value);
+ if (attr == NULL) {
+ if (i == n)
+ sk_X509_ATTRIBUTE_pop(*sk);
+ return 0;
+ }
+ X509_ATTRIBUTE_free(sk_X509_ATTRIBUTE_value(*sk, i));
+ (void) sk_X509_ATTRIBUTE_set(*sk, i, attr);
return 1;
}
diff --git a/crypto/openssl/crypto/property/property.c b/crypto/openssl/crypto/property/property.c
index 602db0f3ff54..75615d39af36 100644
--- a/crypto/openssl/crypto/property/property.c
+++ b/crypto/openssl/crypto/property/property.c
@@ -1,770 +1,787 @@
/*
- * 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/crypto.h>
#include "internal/core.h"
#include "internal/property.h"
#include "internal/provider.h"
#include "internal/tsan_assist.h"
#include "crypto/ctype.h"
#include <openssl/lhash.h>
#include <openssl/rand.h>
#include "internal/thread_once.h"
#include "crypto/lhash.h"
#include "crypto/sparse_array.h"
#include "property_local.h"
/*
* The number of elements in the query cache before we initiate a flush.
* If reducing this, also ensure the stochastic test in test/property_test.c
* isn't likely to fail.
*/
#define IMPL_CACHE_FLUSH_THRESHOLD 500
typedef struct {
void *method;
int (*up_ref)(void *);
void (*free)(void *);
} METHOD;
typedef struct {
const OSSL_PROVIDER *provider;
OSSL_PROPERTY_LIST *properties;
METHOD method;
} IMPLEMENTATION;
DEFINE_STACK_OF(IMPLEMENTATION)
typedef struct {
const OSSL_PROVIDER *provider;
const char *query;
METHOD method;
char body[1];
} QUERY;
DEFINE_LHASH_OF(QUERY);
typedef struct {
int nid;
STACK_OF(IMPLEMENTATION) *impls;
LHASH_OF(QUERY) *cache;
} ALGORITHM;
struct ossl_method_store_st {
OSSL_LIB_CTX *ctx;
SPARSE_ARRAY_OF(ALGORITHM) *algs;
/*
* Lock to protect the |algs| array from concurrent writing, when
* individual implementations or queries are inserted. This is used
* by the appropriate functions here.
*/
CRYPTO_RWLOCK *lock;
/*
* Lock to reserve the whole store. This is used when fetching a set
* of algorithms, via these functions, found in crypto/core_fetch.c:
* ossl_method_construct_reserve_store()
* ossl_method_construct_unreserve_store()
*/
CRYPTO_RWLOCK *biglock;
/* query cache specific values */
/* Count of the query cache entries for all algs */
size_t cache_nelem;
/* Flag: 1 if query cache entries for all algs need flushing */
int cache_need_flush;
};
typedef struct {
LHASH_OF(QUERY) *cache;
size_t nelem;
uint32_t seed;
unsigned char using_global_seed;
} IMPL_CACHE_FLUSH;
DEFINE_SPARSE_ARRAY_OF(ALGORITHM);
+DEFINE_STACK_OF(ALGORITHM)
+
typedef struct ossl_global_properties_st {
OSSL_PROPERTY_LIST *list;
#ifndef FIPS_MODULE
unsigned int no_mirrored : 1;
#endif
} OSSL_GLOBAL_PROPERTIES;
static void ossl_method_cache_flush_alg(OSSL_METHOD_STORE *store,
ALGORITHM *alg);
static void ossl_method_cache_flush(OSSL_METHOD_STORE *store, int nid);
/* Global properties are stored per library context */
static void ossl_ctx_global_properties_free(void *vglobp)
{
OSSL_GLOBAL_PROPERTIES *globp = vglobp;
if (globp != NULL) {
ossl_property_free(globp->list);
OPENSSL_free(globp);
}
}
static void *ossl_ctx_global_properties_new(OSSL_LIB_CTX *ctx)
{
return OPENSSL_zalloc(sizeof(OSSL_GLOBAL_PROPERTIES));
}
static const OSSL_LIB_CTX_METHOD ossl_ctx_global_properties_method = {
OSSL_LIB_CTX_METHOD_DEFAULT_PRIORITY,
ossl_ctx_global_properties_new,
ossl_ctx_global_properties_free,
};
OSSL_PROPERTY_LIST **ossl_ctx_global_properties(OSSL_LIB_CTX *libctx,
ossl_unused int loadconfig)
{
OSSL_GLOBAL_PROPERTIES *globp;
#if !defined(FIPS_MODULE) && !defined(OPENSSL_NO_AUTOLOAD_CONFIG)
if (loadconfig && !OPENSSL_init_crypto(OPENSSL_INIT_LOAD_CONFIG, NULL))
return NULL;
#endif
globp = ossl_lib_ctx_get_data(libctx, OSSL_LIB_CTX_GLOBAL_PROPERTIES,
&ossl_ctx_global_properties_method);
return globp != NULL ? &globp->list : NULL;
}
#ifndef FIPS_MODULE
int ossl_global_properties_no_mirrored(OSSL_LIB_CTX *libctx)
{
OSSL_GLOBAL_PROPERTIES *globp
= ossl_lib_ctx_get_data(libctx, OSSL_LIB_CTX_GLOBAL_PROPERTIES,
&ossl_ctx_global_properties_method);
return globp != NULL && globp->no_mirrored ? 1 : 0;
}
void ossl_global_properties_stop_mirroring(OSSL_LIB_CTX *libctx)
{
OSSL_GLOBAL_PROPERTIES *globp
= ossl_lib_ctx_get_data(libctx, OSSL_LIB_CTX_GLOBAL_PROPERTIES,
&ossl_ctx_global_properties_method);
if (globp != NULL)
globp->no_mirrored = 1;
}
#endif
static int ossl_method_up_ref(METHOD *method)
{
return (*method->up_ref)(method->method);
}
static void ossl_method_free(METHOD *method)
{
(*method->free)(method->method);
}
static __owur int ossl_property_read_lock(OSSL_METHOD_STORE *p)
{
return p != NULL ? CRYPTO_THREAD_read_lock(p->lock) : 0;
}
static __owur int ossl_property_write_lock(OSSL_METHOD_STORE *p)
{
return p != NULL ? CRYPTO_THREAD_write_lock(p->lock) : 0;
}
static int ossl_property_unlock(OSSL_METHOD_STORE *p)
{
return p != 0 ? CRYPTO_THREAD_unlock(p->lock) : 0;
}
static unsigned long query_hash(const QUERY *a)
{
return OPENSSL_LH_strhash(a->query);
}
static int query_cmp(const QUERY *a, const QUERY *b)
{
int res = strcmp(a->query, b->query);
if (res == 0 && a->provider != NULL && b->provider != NULL)
res = b->provider > a->provider ? 1
: b->provider < a->provider ? -1
: 0;
return res;
}
static void impl_free(IMPLEMENTATION *impl)
{
if (impl != NULL) {
ossl_method_free(&impl->method);
OPENSSL_free(impl);
}
}
static void impl_cache_free(QUERY *elem)
{
if (elem != NULL) {
ossl_method_free(&elem->method);
OPENSSL_free(elem);
}
}
static void impl_cache_flush_alg(ossl_uintmax_t idx, ALGORITHM *alg)
{
lh_QUERY_doall(alg->cache, &impl_cache_free);
lh_QUERY_flush(alg->cache);
}
static void alg_cleanup(ossl_uintmax_t idx, ALGORITHM *a, void *arg)
{
OSSL_METHOD_STORE *store = arg;
if (a != NULL) {
sk_IMPLEMENTATION_pop_free(a->impls, &impl_free);
lh_QUERY_doall(a->cache, &impl_cache_free);
lh_QUERY_free(a->cache);
OPENSSL_free(a);
}
if (store != NULL)
ossl_sa_ALGORITHM_set(store->algs, idx, NULL);
}
/*
* The OSSL_LIB_CTX param here allows access to underlying property data needed
* for computation
*/
OSSL_METHOD_STORE *ossl_method_store_new(OSSL_LIB_CTX *ctx)
{
OSSL_METHOD_STORE *res;
res = OPENSSL_zalloc(sizeof(*res));
if (res != NULL) {
res->ctx = ctx;
if ((res->algs = ossl_sa_ALGORITHM_new()) == NULL
|| (res->lock = CRYPTO_THREAD_lock_new()) == NULL
|| (res->biglock = CRYPTO_THREAD_lock_new()) == NULL) {
ossl_method_store_free(res);
return NULL;
}
}
return res;
}
void ossl_method_store_free(OSSL_METHOD_STORE *store)
{
if (store != NULL) {
if (store->algs != NULL)
ossl_sa_ALGORITHM_doall_arg(store->algs, &alg_cleanup, store);
ossl_sa_ALGORITHM_free(store->algs);
CRYPTO_THREAD_lock_free(store->lock);
CRYPTO_THREAD_lock_free(store->biglock);
OPENSSL_free(store);
}
}
int ossl_method_lock_store(OSSL_METHOD_STORE *store)
{
return store != NULL ? CRYPTO_THREAD_write_lock(store->biglock) : 0;
}
int ossl_method_unlock_store(OSSL_METHOD_STORE *store)
{
return store != NULL ? CRYPTO_THREAD_unlock(store->biglock) : 0;
}
static ALGORITHM *ossl_method_store_retrieve(OSSL_METHOD_STORE *store, int nid)
{
return ossl_sa_ALGORITHM_get(store->algs, nid);
}
static int ossl_method_store_insert(OSSL_METHOD_STORE *store, ALGORITHM *alg)
{
return ossl_sa_ALGORITHM_set(store->algs, alg->nid, alg);
}
int ossl_method_store_add(OSSL_METHOD_STORE *store, const OSSL_PROVIDER *prov,
int nid, const char *properties, void *method,
int (*method_up_ref)(void *),
void (*method_destruct)(void *))
{
ALGORITHM *alg = NULL;
IMPLEMENTATION *impl;
int ret = 0;
int i;
if (nid <= 0 || method == NULL || store == NULL)
return 0;
if (properties == NULL)
properties = "";
if (!ossl_assert(prov != NULL))
return 0;
/* Create new entry */
impl = OPENSSL_malloc(sizeof(*impl));
if (impl == NULL)
return 0;
impl->method.method = method;
impl->method.up_ref = method_up_ref;
impl->method.free = method_destruct;
if (!ossl_method_up_ref(&impl->method)) {
OPENSSL_free(impl);
return 0;
}
impl->provider = prov;
/* Insert into the hash table if required */
if (!ossl_property_write_lock(store)) {
OPENSSL_free(impl);
return 0;
}
ossl_method_cache_flush(store, nid);
if ((impl->properties = ossl_prop_defn_get(store->ctx, properties)) == NULL) {
impl->properties = ossl_parse_property(store->ctx, properties);
if (impl->properties == NULL)
goto err;
if (!ossl_prop_defn_set(store->ctx, properties, &impl->properties)) {
ossl_property_free(impl->properties);
impl->properties = NULL;
goto err;
}
}
alg = ossl_method_store_retrieve(store, nid);
if (alg == NULL) {
if ((alg = OPENSSL_zalloc(sizeof(*alg))) == NULL
|| (alg->impls = sk_IMPLEMENTATION_new_null()) == NULL
|| (alg->cache = lh_QUERY_new(&query_hash, &query_cmp)) == NULL)
goto err;
alg->nid = nid;
if (!ossl_method_store_insert(store, alg))
goto err;
}
/* Push onto stack if there isn't one there already */
for (i = 0; i < sk_IMPLEMENTATION_num(alg->impls); i++) {
const IMPLEMENTATION *tmpimpl = sk_IMPLEMENTATION_value(alg->impls, i);
if (tmpimpl->provider == impl->provider
&& tmpimpl->properties == impl->properties)
break;
}
if (i == sk_IMPLEMENTATION_num(alg->impls)
&& sk_IMPLEMENTATION_push(alg->impls, impl))
ret = 1;
ossl_property_unlock(store);
if (ret == 0)
impl_free(impl);
return ret;
err:
ossl_property_unlock(store);
alg_cleanup(0, alg, NULL);
impl_free(impl);
return 0;
}
int ossl_method_store_remove(OSSL_METHOD_STORE *store, int nid,
const void *method)
{
ALGORITHM *alg = NULL;
int i;
if (nid <= 0 || method == NULL || store == NULL)
return 0;
if (!ossl_property_write_lock(store))
return 0;
ossl_method_cache_flush(store, nid);
alg = ossl_method_store_retrieve(store, nid);
if (alg == NULL) {
ossl_property_unlock(store);
return 0;
}
/*
* A sorting find then a delete could be faster but these stacks should be
* relatively small, so we avoid the overhead. Sorting could also surprise
* users when result orderings change (even though they are not guaranteed).
*/
for (i = 0; i < sk_IMPLEMENTATION_num(alg->impls); i++) {
IMPLEMENTATION *impl = sk_IMPLEMENTATION_value(alg->impls, i);
if (impl->method.method == method) {
impl_free(impl);
(void)sk_IMPLEMENTATION_delete(alg->impls, i);
ossl_property_unlock(store);
return 1;
}
}
ossl_property_unlock(store);
return 0;
}
struct alg_cleanup_by_provider_data_st {
OSSL_METHOD_STORE *store;
const OSSL_PROVIDER *prov;
};
static void
alg_cleanup_by_provider(ossl_uintmax_t idx, ALGORITHM *alg, void *arg)
{
struct alg_cleanup_by_provider_data_st *data = arg;
int i, count;
/*
* We walk the stack backwards, to avoid having to deal with stack shifts
* caused by deletion
*/
for (count = 0, i = sk_IMPLEMENTATION_num(alg->impls); i-- > 0;) {
IMPLEMENTATION *impl = sk_IMPLEMENTATION_value(alg->impls, i);
if (impl->provider == data->prov) {
impl_free(impl);
(void)sk_IMPLEMENTATION_delete(alg->impls, i);
count++;
}
}
/*
* If we removed any implementation, we also clear the whole associated
* cache, 'cause that's the sensible thing to do.
* There's no point flushing the cache entries where we didn't remove
* any implementation, though.
*/
if (count > 0)
ossl_method_cache_flush_alg(data->store, alg);
}
int ossl_method_store_remove_all_provided(OSSL_METHOD_STORE *store,
const OSSL_PROVIDER *prov)
{
struct alg_cleanup_by_provider_data_st data;
if (!ossl_property_write_lock(store))
return 0;
data.prov = prov;
data.store = store;
ossl_sa_ALGORITHM_doall_arg(store->algs, &alg_cleanup_by_provider, &data);
ossl_property_unlock(store);
return 1;
}
static void alg_do_one(ALGORITHM *alg, IMPLEMENTATION *impl,
void (*fn)(int id, void *method, void *fnarg),
void *fnarg)
{
fn(alg->nid, impl->method.method, fnarg);
}
-struct alg_do_each_data_st {
- void (*fn)(int id, void *method, void *fnarg);
- void *fnarg;
-};
-
-static void alg_do_each(ossl_uintmax_t idx, ALGORITHM *alg, void *arg)
+static void alg_copy(ossl_uintmax_t idx, ALGORITHM *alg, void *arg)
{
- struct alg_do_each_data_st *data = arg;
- int i, end = sk_IMPLEMENTATION_num(alg->impls);
-
- for (i = 0; i < end; i++) {
- IMPLEMENTATION *impl = sk_IMPLEMENTATION_value(alg->impls, i);
+ STACK_OF(ALGORITHM) *newalg = arg;
- alg_do_one(alg, impl, data->fn, data->fnarg);
- }
+ (void)sk_ALGORITHM_push(newalg, alg);
}
void ossl_method_store_do_all(OSSL_METHOD_STORE *store,
void (*fn)(int id, void *method, void *fnarg),
void *fnarg)
{
- struct alg_do_each_data_st data;
+ int i, j;
+ int numalgs, numimps;
+ STACK_OF(ALGORITHM) *tmpalgs;
+ ALGORITHM *alg;
- data.fn = fn;
- data.fnarg = fnarg;
- if (store != NULL)
- ossl_sa_ALGORITHM_doall_arg(store->algs, alg_do_each, &data);
+ if (store != NULL) {
+
+ if (!ossl_property_read_lock(store))
+ return;
+
+ tmpalgs = sk_ALGORITHM_new_reserve(NULL,
+ ossl_sa_ALGORITHM_num(store->algs));
+ if (tmpalgs == NULL) {
+ ossl_property_unlock(store);
+ return;
+ }
+
+ ossl_sa_ALGORITHM_doall_arg(store->algs, alg_copy, tmpalgs);
+ ossl_property_unlock(store);
+ numalgs = sk_ALGORITHM_num(tmpalgs);
+ for (i = 0; i < numalgs; i++) {
+ alg = sk_ALGORITHM_value(tmpalgs, i);
+ numimps = sk_IMPLEMENTATION_num(alg->impls);
+ for (j = 0; j < numimps; j++)
+ alg_do_one(alg, sk_IMPLEMENTATION_value(alg->impls, j), fn, fnarg);
+ }
+ sk_ALGORITHM_free(tmpalgs);
+ }
}
int ossl_method_store_fetch(OSSL_METHOD_STORE *store,
int nid, const char *prop_query,
const OSSL_PROVIDER **prov_rw, void **method)
{
OSSL_PROPERTY_LIST **plp;
ALGORITHM *alg;
IMPLEMENTATION *impl, *best_impl = NULL;
OSSL_PROPERTY_LIST *pq = NULL, *p2 = NULL;
const OSSL_PROVIDER *prov = prov_rw != NULL ? *prov_rw : NULL;
int ret = 0;
int j, best = -1, score, optional;
if (nid <= 0 || method == NULL || store == NULL)
return 0;
#if !defined(FIPS_MODULE) && !defined(OPENSSL_NO_AUTOLOAD_CONFIG)
if (ossl_lib_ctx_is_default(store->ctx)
&& !OPENSSL_init_crypto(OPENSSL_INIT_LOAD_CONFIG, NULL))
return 0;
#endif
/* This only needs to be a read lock, because the query won't create anything */
if (!ossl_property_read_lock(store))
return 0;
alg = ossl_method_store_retrieve(store, nid);
if (alg == NULL) {
ossl_property_unlock(store);
return 0;
}
if (prop_query != NULL)
p2 = pq = ossl_parse_query(store->ctx, prop_query, 0);
plp = ossl_ctx_global_properties(store->ctx, 0);
if (plp != NULL && *plp != NULL) {
if (pq == NULL) {
pq = *plp;
} else {
p2 = ossl_property_merge(pq, *plp);
ossl_property_free(pq);
if (p2 == NULL)
goto fin;
pq = p2;
}
}
if (pq == NULL) {
for (j = 0; j < sk_IMPLEMENTATION_num(alg->impls); j++) {
if ((impl = sk_IMPLEMENTATION_value(alg->impls, j)) != NULL
&& (prov == NULL || impl->provider == prov)) {
best_impl = impl;
ret = 1;
break;
}
}
goto fin;
}
optional = ossl_property_has_optional(pq);
for (j = 0; j < sk_IMPLEMENTATION_num(alg->impls); j++) {
if ((impl = sk_IMPLEMENTATION_value(alg->impls, j)) != NULL
&& (prov == NULL || impl->provider == prov)) {
score = ossl_property_match_count(pq, impl->properties);
if (score > best) {
best_impl = impl;
best = score;
ret = 1;
if (!optional)
goto fin;
}
}
}
fin:
if (ret && ossl_method_up_ref(&best_impl->method)) {
*method = best_impl->method.method;
if (prov_rw != NULL)
*prov_rw = best_impl->provider;
} else {
ret = 0;
}
ossl_property_unlock(store);
ossl_property_free(p2);
return ret;
}
static void ossl_method_cache_flush_alg(OSSL_METHOD_STORE *store,
ALGORITHM *alg)
{
store->cache_nelem -= lh_QUERY_num_items(alg->cache);
impl_cache_flush_alg(0, alg);
}
static void ossl_method_cache_flush(OSSL_METHOD_STORE *store, int nid)
{
ALGORITHM *alg = ossl_method_store_retrieve(store, nid);
if (alg != NULL)
ossl_method_cache_flush_alg(store, alg);
}
int ossl_method_store_cache_flush_all(OSSL_METHOD_STORE *store)
{
if (!ossl_property_write_lock(store))
return 0;
ossl_sa_ALGORITHM_doall(store->algs, &impl_cache_flush_alg);
store->cache_nelem = 0;
ossl_property_unlock(store);
return 1;
}
IMPLEMENT_LHASH_DOALL_ARG(QUERY, IMPL_CACHE_FLUSH);
/*
* Flush an element from the query cache (perhaps).
*
* In order to avoid taking a write lock or using atomic operations
* to keep accurate least recently used (LRU) or least frequently used
* (LFU) information, the procedure used here is to stochastically
* flush approximately half the cache.
*
* This procedure isn't ideal, LRU or LFU would be better. However,
* in normal operation, reaching a full cache would be unexpected.
* It means that no steady state of algorithm queries has been reached.
* That is, it is most likely an attack of some form. A suboptimal clearance
* strategy that doesn't degrade performance of the normal case is
* preferable to a more refined approach that imposes a performance
* impact.
*/
static void impl_cache_flush_cache(QUERY *c, IMPL_CACHE_FLUSH *state)
{
uint32_t n;
/*
* Implement the 32 bit xorshift as suggested by George Marsaglia in:
* https://doi.org/10.18637/jss.v008.i14
*
* This is a very fast PRNG so there is no need to extract bits one at a
* time and use the entire value each time.
*/
n = state->seed;
n ^= n << 13;
n ^= n >> 17;
n ^= n << 5;
state->seed = n;
if ((n & 1) != 0)
impl_cache_free(lh_QUERY_delete(state->cache, c));
else
state->nelem++;
}
static void impl_cache_flush_one_alg(ossl_uintmax_t idx, ALGORITHM *alg,
void *v)
{
IMPL_CACHE_FLUSH *state = (IMPL_CACHE_FLUSH *)v;
+ unsigned long orig_down_load = lh_QUERY_get_down_load(alg->cache);
state->cache = alg->cache;
+ lh_QUERY_set_down_load(alg->cache, 0);
lh_QUERY_doall_IMPL_CACHE_FLUSH(state->cache, &impl_cache_flush_cache,
state);
+ lh_QUERY_set_down_load(alg->cache, orig_down_load);
}
static void ossl_method_cache_flush_some(OSSL_METHOD_STORE *store)
{
IMPL_CACHE_FLUSH state;
static TSAN_QUALIFIER uint32_t global_seed = 1;
state.nelem = 0;
state.using_global_seed = 0;
if ((state.seed = OPENSSL_rdtsc()) == 0) {
/* If there is no timer available, seed another way */
state.using_global_seed = 1;
state.seed = tsan_load(&global_seed);
}
store->cache_need_flush = 0;
ossl_sa_ALGORITHM_doall_arg(store->algs, &impl_cache_flush_one_alg, &state);
store->cache_nelem = state.nelem;
/* Without a timer, update the global seed */
if (state.using_global_seed)
tsan_store(&global_seed, state.seed);
}
int ossl_method_store_cache_get(OSSL_METHOD_STORE *store, OSSL_PROVIDER *prov,
int nid, const char *prop_query, void **method)
{
ALGORITHM *alg;
QUERY elem, *r;
int res = 0;
if (nid <= 0 || store == NULL || prop_query == NULL)
return 0;
if (!ossl_property_read_lock(store))
return 0;
alg = ossl_method_store_retrieve(store, nid);
if (alg == NULL)
goto err;
elem.query = prop_query;
elem.provider = prov;
r = lh_QUERY_retrieve(alg->cache, &elem);
if (r == NULL)
goto err;
if (ossl_method_up_ref(&r->method)) {
*method = r->method.method;
res = 1;
}
err:
ossl_property_unlock(store);
return res;
}
int ossl_method_store_cache_set(OSSL_METHOD_STORE *store, OSSL_PROVIDER *prov,
int nid, const char *prop_query, void *method,
int (*method_up_ref)(void *),
void (*method_destruct)(void *))
{
QUERY elem, *old, *p = NULL;
ALGORITHM *alg;
size_t len;
int res = 1;
if (nid <= 0 || store == NULL || prop_query == NULL)
return 0;
if (!ossl_assert(prov != NULL))
return 0;
if (!ossl_property_write_lock(store))
return 0;
if (store->cache_need_flush)
ossl_method_cache_flush_some(store);
alg = ossl_method_store_retrieve(store, nid);
if (alg == NULL)
goto err;
if (method == NULL) {
elem.query = prop_query;
elem.provider = prov;
if ((old = lh_QUERY_delete(alg->cache, &elem)) != NULL) {
impl_cache_free(old);
store->cache_nelem--;
}
goto end;
}
p = OPENSSL_malloc(sizeof(*p) + (len = strlen(prop_query)));
if (p != NULL) {
p->query = p->body;
p->provider = prov;
p->method.method = method;
p->method.up_ref = method_up_ref;
p->method.free = method_destruct;
if (!ossl_method_up_ref(&p->method))
goto err;
memcpy((char *)p->query, prop_query, len + 1);
if ((old = lh_QUERY_insert(alg->cache, p)) != NULL) {
impl_cache_free(old);
goto end;
}
if (!lh_QUERY_error(alg->cache)) {
if (++store->cache_nelem >= IMPL_CACHE_FLUSH_THRESHOLD)
store->cache_need_flush = 1;
goto end;
}
ossl_method_free(&p->method);
}
err:
res = 0;
OPENSSL_free(p);
end:
ossl_property_unlock(store);
return res;
}
diff --git a/crypto/openssl/crypto/rand/randfile.c b/crypto/openssl/crypto/rand/randfile.c
index 82f41637387b..b4854a4c4eab 100644
--- a/crypto/openssl/crypto/rand/randfile.c
+++ b/crypto/openssl/crypto/rand/randfile.c
@@ -1,321 +1,330 @@
/*
- * 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
*/
#if defined (__TANDEM) && defined (_SPT_MODEL_)
/*
* These definitions have to come first in SPT due to scoping of the
* declarations in c99 associated with SPT use of stat.
*/
# include <sys/types.h>
# include <sys/stat.h>
#endif
+#include "e_os.h"
#include "internal/cryptlib.h"
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/crypto.h>
#include <openssl/rand.h>
#include <openssl/buffer.h>
#ifdef OPENSSL_SYS_VMS
# include <unixio.h>
#endif
#include <sys/types.h>
#ifndef OPENSSL_NO_POSIX_IO
# include <sys/stat.h>
# include <fcntl.h>
# if defined(_WIN32) && !defined(_WIN32_WCE)
# include <windows.h>
# include <io.h>
# define stat _stat
# define chmod _chmod
# define open _open
# define fdopen _fdopen
# define fstat _fstat
# define fileno _fileno
# endif
#endif
/*
* Following should not be needed, and we could have been stricter
* and demand S_IS*. But some systems just don't comply... Formally
* below macros are "anatomically incorrect", because normally they
* would look like ((m) & MASK == TYPE), but since MASK availability
* is as questionable, we settle for this poor-man fallback...
*/
# if !defined(S_ISREG)
# define S_ISREG(m) ((m) & S_IFREG)
# endif
#define RAND_BUF_SIZE 1024
#define RFILE ".rnd"
#ifdef OPENSSL_SYS_VMS
/*
* __FILE_ptr32 is a type provided by DEC C headers (types.h specifically)
* to make sure the FILE* is a 32-bit pointer no matter what. We know that
* stdio functions return this type (a study of stdio.h proves it).
*
* This declaration is a nasty hack to get around vms' extension to fopen for
* passing in sharing options being disabled by /STANDARD=ANSI89
*/
static __FILE_ptr32 (*const vms_fopen)(const char *, const char *, ...) =
(__FILE_ptr32 (*)(const char *, const char *, ...))fopen;
# define VMS_OPEN_ATTRS \
"shr=get,put,upd,del","ctx=bin,stm","rfm=stm","rat=none","mrs=0"
# define openssl_fopen(fname, mode) vms_fopen((fname), (mode), VMS_OPEN_ATTRS)
#endif
/*
* Note that these functions are intended for seed files only. Entropy
* devices and EGD sockets are handled in rand_unix.c If |bytes| is
* -1 read the complete file; otherwise read the specified amount.
*/
int RAND_load_file(const char *file, long bytes)
{
/*
* The load buffer size exceeds the chunk size by the comfortable amount
* of 'RAND_DRBG_STRENGTH' bytes (not bits!). This is done on purpose
* to avoid calling RAND_add() with a small final chunk. Instead, such
* a small final chunk will be added together with the previous chunk
* (unless it's the only one).
*/
#define RAND_LOAD_BUF_SIZE (RAND_BUF_SIZE + RAND_DRBG_STRENGTH)
unsigned char buf[RAND_LOAD_BUF_SIZE];
#ifndef OPENSSL_NO_POSIX_IO
struct stat sb;
#endif
int i, n, ret = 0;
FILE *in;
if (bytes == 0)
return 0;
if ((in = openssl_fopen(file, "rb")) == NULL) {
ERR_raise_data(ERR_LIB_RAND, RAND_R_CANNOT_OPEN_FILE,
"Filename=%s", file);
return -1;
}
#ifndef OPENSSL_NO_POSIX_IO
if (fstat(fileno(in), &sb) < 0) {
ERR_raise_data(ERR_LIB_RAND, RAND_R_INTERNAL_ERROR,
"Filename=%s", file);
fclose(in);
return -1;
}
if (bytes < 0) {
if (S_ISREG(sb.st_mode))
bytes = sb.st_size;
else
bytes = RAND_DRBG_STRENGTH;
}
#endif
/*
* On VMS, setbuf() will only take 32-bit pointers, and a compilation
* with /POINTER_SIZE=64 will give off a MAYLOSEDATA2 warning here.
* However, we trust that the C RTL will never give us a FILE pointer
* above the first 4 GB of memory, so we simply turn off the warning
* temporarily.
*/
#if defined(OPENSSL_SYS_VMS) && defined(__DECC)
# pragma environment save
# pragma message disable maylosedata2
#endif
/*
* Don't buffer, because even if |file| is regular file, we have
* no control over the buffer, so why would we want a copy of its
* contents lying around?
*/
setbuf(in, NULL);
#if defined(OPENSSL_SYS_VMS) && defined(__DECC)
# pragma environment restore
#endif
for ( ; ; ) {
if (bytes > 0)
n = (bytes <= RAND_LOAD_BUF_SIZE) ? (int)bytes : RAND_BUF_SIZE;
else
n = RAND_LOAD_BUF_SIZE;
i = fread(buf, 1, n, in);
#ifdef EINTR
if (ferror(in) && errno == EINTR){
clearerr(in);
if (i == 0)
continue;
}
#endif
if (i == 0)
break;
RAND_add(buf, i, (double)i);
ret += i;
/* If given a bytecount, and we did it, break. */
if (bytes > 0 && (bytes -= i) <= 0)
break;
}
OPENSSL_cleanse(buf, sizeof(buf));
fclose(in);
if (!RAND_status()) {
ERR_raise_data(ERR_LIB_RAND, RAND_R_RESEED_ERROR, "Filename=%s", file);
return -1;
}
return ret;
}
int RAND_write_file(const char *file)
{
unsigned char buf[RAND_BUF_SIZE];
int ret = -1;
FILE *out = NULL;
#ifndef OPENSSL_NO_POSIX_IO
struct stat sb;
if (stat(file, &sb) >= 0 && !S_ISREG(sb.st_mode)) {
ERR_raise_data(ERR_LIB_RAND, RAND_R_NOT_A_REGULAR_FILE,
"Filename=%s", file);
return -1;
}
#endif
/* Collect enough random data. */
if (RAND_priv_bytes(buf, (int)sizeof(buf)) != 1)
return -1;
#if defined(O_CREAT) && !defined(OPENSSL_NO_POSIX_IO) && \
!defined(OPENSSL_SYS_VMS) && !defined(OPENSSL_SYS_WINDOWS)
{
# ifndef O_BINARY
# define O_BINARY 0
# endif
/*
* chmod(..., 0600) is too late to protect the file, permissions
* should be restrictive from the start
*/
int fd = open(file, O_WRONLY | O_CREAT | O_BINARY, 0600);
- if (fd != -1)
+
+ if (fd != -1) {
out = fdopen(fd, "wb");
+ if (out == NULL) {
+ close(fd);
+ ERR_raise_data(ERR_LIB_RAND, RAND_R_CANNOT_OPEN_FILE,
+ "Filename=%s", file);
+ return -1;
+ }
+ }
}
#endif
#ifdef OPENSSL_SYS_VMS
/*
* VMS NOTE: Prior versions of this routine created a _new_ version of
* the rand file for each call into this routine, then deleted all
* existing versions named ;-1, and finally renamed the current version
* as ';1'. Under concurrent usage, this resulted in an RMS race
* condition in rename() which could orphan files (see vms message help
* for RMS$_REENT). With the fopen() calls below, openssl/VMS now shares
* the top-level version of the rand file. Note that there may still be
* conditions where the top-level rand file is locked. If so, this code
* will then create a new version of the rand file. Without the delete
* and rename code, this can result in ascending file versions that stop
* at version 32767, and this routine will then return an error. The
* remedy for this is to recode the calling application to avoid
* concurrent use of the rand file, or synchronize usage at the
* application level. Also consider whether or not you NEED a persistent
* rand file in a concurrent use situation.
*/
out = openssl_fopen(file, "rb+");
#endif
if (out == NULL)
out = openssl_fopen(file, "wb");
if (out == NULL) {
ERR_raise_data(ERR_LIB_RAND, RAND_R_CANNOT_OPEN_FILE,
"Filename=%s", file);
return -1;
}
#if !defined(NO_CHMOD) && !defined(OPENSSL_NO_POSIX_IO)
/*
* Yes it's late to do this (see above comment), but better than nothing.
*/
chmod(file, 0600);
#endif
ret = fwrite(buf, 1, RAND_BUF_SIZE, out);
fclose(out);
OPENSSL_cleanse(buf, RAND_BUF_SIZE);
return ret;
}
const char *RAND_file_name(char *buf, size_t size)
{
char *s = NULL;
size_t len;
int use_randfile = 1;
#if defined(_WIN32) && defined(CP_UTF8) && !defined(_WIN32_WCE)
DWORD envlen;
WCHAR *var;
/* Look up various environment variables. */
if ((envlen = GetEnvironmentVariableW(var = L"RANDFILE", NULL, 0)) == 0) {
use_randfile = 0;
if ((envlen = GetEnvironmentVariableW(var = L"HOME", NULL, 0)) == 0
&& (envlen = GetEnvironmentVariableW(var = L"USERPROFILE",
NULL, 0)) == 0)
envlen = GetEnvironmentVariableW(var = L"SYSTEMROOT", NULL, 0);
}
/* If we got a value, allocate space to hold it and then get it. */
if (envlen != 0) {
int sz;
WCHAR *val = _alloca(envlen * sizeof(WCHAR));
if (GetEnvironmentVariableW(var, val, envlen) < envlen
&& (sz = WideCharToMultiByte(CP_UTF8, 0, val, -1, NULL, 0,
NULL, NULL)) != 0) {
s = _alloca(sz);
if (WideCharToMultiByte(CP_UTF8, 0, val, -1, s, sz,
NULL, NULL) == 0)
s = NULL;
}
}
#else
if ((s = ossl_safe_getenv("RANDFILE")) == NULL || *s == '\0') {
use_randfile = 0;
s = ossl_safe_getenv("HOME");
}
#endif
#ifdef DEFAULT_HOME
if (!use_randfile && s == NULL)
s = DEFAULT_HOME;
#endif
if (s == NULL || *s == '\0')
return NULL;
len = strlen(s);
if (use_randfile) {
if (len + 1 >= size)
return NULL;
strcpy(buf, s);
} else {
if (len + 1 + strlen(RFILE) + 1 >= size)
return NULL;
strcpy(buf, s);
#ifndef OPENSSL_SYS_VMS
strcat(buf, "/");
#endif
strcat(buf, RFILE);
}
return buf;
}
diff --git a/crypto/openssl/crypto/rsa/rsa_oaep.c b/crypto/openssl/crypto/rsa/rsa_oaep.c
index d9be1a4f98c7..ffe24edcb6ee 100644
--- a/crypto/openssl/crypto/rsa/rsa_oaep.c
+++ b/crypto/openssl/crypto/rsa/rsa_oaep.c
@@ -1,375 +1,375 @@
/*
- * Copyright 1999-2021 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
*/
/* EME-OAEP as defined in RFC 2437 (PKCS #1 v2.0) */
/*
* See Victor Shoup, "OAEP reconsidered," Nov. 2000, <URL:
* http://www.shoup.net/papers/oaep.ps.Z> for problems with the security
* proof for the original OAEP scheme, which EME-OAEP is based on. A new
* proof can be found in E. Fujisaki, T. Okamoto, D. Pointcheval, J. Stern,
* "RSA-OEAP is Still Alive!", Dec. 2000, <URL:
* http://eprint.iacr.org/2000/061/>. The new proof has stronger requirements
* for the underlying permutation: "partial-one-wayness" instead of
* one-wayness. For the RSA function, this is an equivalent notion.
*/
/*
* RSA low level APIs are deprecated for public use, but still ok for
* internal use.
*/
#include "internal/deprecated.h"
#include "internal/constant_time.h"
#include <stdio.h>
#include "internal/cryptlib.h"
#include <openssl/bn.h>
#include <openssl/evp.h>
#include <openssl/rand.h>
#include <openssl/sha.h>
#include "rsa_local.h"
int RSA_padding_add_PKCS1_OAEP(unsigned char *to, int tlen,
const unsigned char *from, int flen,
const unsigned char *param, int plen)
{
return ossl_rsa_padding_add_PKCS1_OAEP_mgf1_ex(NULL, to, tlen, from, flen,
param, plen, NULL, NULL);
}
/*
* Perform the padding as per NIST 800-56B 7.2.2.3
* from (K) is the key material.
* param (A) is the additional input.
* Step numbers are included here but not in the constant time inverse below
* to avoid complicating an already difficult enough function.
*/
int ossl_rsa_padding_add_PKCS1_OAEP_mgf1_ex(OSSL_LIB_CTX *libctx,
unsigned char *to, int tlen,
const unsigned char *from, int flen,
const unsigned char *param,
int plen, const EVP_MD *md,
const EVP_MD *mgf1md)
{
int rv = 0;
int i, emlen = tlen - 1;
unsigned char *db, *seed;
unsigned char *dbmask = NULL;
unsigned char seedmask[EVP_MAX_MD_SIZE];
int mdlen, dbmask_len = 0;
if (md == NULL) {
#ifndef FIPS_MODULE
md = EVP_sha1();
#else
ERR_raise(ERR_LIB_RSA, ERR_R_PASSED_NULL_PARAMETER);
return 0;
#endif
}
if (mgf1md == NULL)
mgf1md = md;
mdlen = EVP_MD_get_size(md);
if (mdlen <= 0) {
ERR_raise(ERR_LIB_RSA, RSA_R_INVALID_LENGTH);
return 0;
}
/* step 2b: check KLen > nLen - 2 HLen - 2 */
if (flen > emlen - 2 * mdlen - 1) {
ERR_raise(ERR_LIB_RSA, RSA_R_DATA_TOO_LARGE_FOR_KEY_SIZE);
return 0;
}
if (emlen < 2 * mdlen + 1) {
ERR_raise(ERR_LIB_RSA, RSA_R_KEY_SIZE_TOO_SMALL);
return 0;
}
/* step 3i: EM = 00000000 || maskedMGF || maskedDB */
to[0] = 0;
seed = to + 1;
db = to + mdlen + 1;
/* step 3a: hash the additional input */
if (!EVP_Digest((void *)param, plen, db, NULL, md, NULL))
goto err;
/* step 3b: zero bytes array of length nLen - KLen - 2 HLen -2 */
memset(db + mdlen, 0, emlen - flen - 2 * mdlen - 1);
/* step 3c: DB = HA || PS || 00000001 || K */
db[emlen - flen - mdlen - 1] = 0x01;
memcpy(db + emlen - flen - mdlen, from, (unsigned int)flen);
/* step 3d: generate random byte string */
if (RAND_bytes_ex(libctx, seed, mdlen, 0) <= 0)
goto err;
dbmask_len = emlen - mdlen;
dbmask = OPENSSL_malloc(dbmask_len);
if (dbmask == NULL) {
ERR_raise(ERR_LIB_RSA, ERR_R_MALLOC_FAILURE);
goto err;
}
/* step 3e: dbMask = MGF(mgfSeed, nLen - HLen - 1) */
if (PKCS1_MGF1(dbmask, dbmask_len, seed, mdlen, mgf1md) < 0)
goto err;
/* step 3f: maskedDB = DB XOR dbMask */
for (i = 0; i < dbmask_len; i++)
db[i] ^= dbmask[i];
/* step 3g: mgfSeed = MGF(maskedDB, HLen) */
if (PKCS1_MGF1(seedmask, mdlen, db, dbmask_len, mgf1md) < 0)
goto err;
/* stepo 3h: maskedMGFSeed = mgfSeed XOR mgfSeedMask */
for (i = 0; i < mdlen; i++)
seed[i] ^= seedmask[i];
rv = 1;
err:
OPENSSL_cleanse(seedmask, sizeof(seedmask));
OPENSSL_clear_free(dbmask, dbmask_len);
return rv;
}
int RSA_padding_add_PKCS1_OAEP_mgf1(unsigned char *to, int tlen,
const unsigned char *from, int flen,
const unsigned char *param, int plen,
const EVP_MD *md, const EVP_MD *mgf1md)
{
return ossl_rsa_padding_add_PKCS1_OAEP_mgf1_ex(NULL, to, tlen, from, flen,
param, plen, md, mgf1md);
}
int RSA_padding_check_PKCS1_OAEP(unsigned char *to, int tlen,
const unsigned char *from, int flen, int num,
const unsigned char *param, int plen)
{
return RSA_padding_check_PKCS1_OAEP_mgf1(to, tlen, from, flen, num,
param, plen, NULL, NULL);
}
int RSA_padding_check_PKCS1_OAEP_mgf1(unsigned char *to, int tlen,
const unsigned char *from, int flen,
int num, const unsigned char *param,
int plen, const EVP_MD *md,
const EVP_MD *mgf1md)
{
int i, dblen = 0, mlen = -1, one_index = 0, msg_index;
unsigned int good = 0, found_one_byte, mask;
const unsigned char *maskedseed, *maskeddb;
/*
* |em| is the encoded message, zero-padded to exactly |num| bytes: em =
* Y || maskedSeed || maskedDB
*/
unsigned char *db = NULL, *em = NULL, seed[EVP_MAX_MD_SIZE],
phash[EVP_MAX_MD_SIZE];
int mdlen;
if (md == NULL) {
#ifndef FIPS_MODULE
md = EVP_sha1();
#else
ERR_raise(ERR_LIB_RSA, ERR_R_PASSED_NULL_PARAMETER);
return -1;
#endif
}
if (mgf1md == NULL)
mgf1md = md;
mdlen = EVP_MD_get_size(md);
- if (tlen <= 0 || flen <= 0)
+ if (tlen <= 0 || flen <= 0 || mdlen <= 0)
return -1;
/*
* |num| is the length of the modulus; |flen| is the length of the
* encoded message. Therefore, for any |from| that was obtained by
* decrypting a ciphertext, we must have |flen| <= |num|. Similarly,
* |num| >= 2 * |mdlen| + 2 must hold for the modulus irrespective of
* the ciphertext, see PKCS #1 v2.2, section 7.1.2.
* This does not leak any side-channel information.
*/
if (num < flen || num < 2 * mdlen + 2) {
ERR_raise(ERR_LIB_RSA, RSA_R_OAEP_DECODING_ERROR);
return -1;
}
dblen = num - mdlen - 1;
db = OPENSSL_malloc(dblen);
if (db == NULL) {
ERR_raise(ERR_LIB_RSA, ERR_R_MALLOC_FAILURE);
goto cleanup;
}
em = OPENSSL_malloc(num);
if (em == NULL) {
ERR_raise(ERR_LIB_RSA, ERR_R_MALLOC_FAILURE);
goto cleanup;
}
/*
* Caller is encouraged to pass zero-padded message created with
* BN_bn2binpad. Trouble is that since we can't read out of |from|'s
* bounds, it's impossible to have an invariant memory access pattern
* in case |from| was not zero-padded in advance.
*/
for (from += flen, em += num, i = 0; i < num; i++) {
mask = ~constant_time_is_zero(flen);
flen -= 1 & mask;
from -= 1 & mask;
*--em = *from & mask;
}
/*
* The first byte must be zero, however we must not leak if this is
* true. See James H. Manger, "A Chosen Ciphertext Attack on RSA
* Optimal Asymmetric Encryption Padding (OAEP) [...]", CRYPTO 2001).
*/
good = constant_time_is_zero(em[0]);
maskedseed = em + 1;
maskeddb = em + 1 + mdlen;
if (PKCS1_MGF1(seed, mdlen, maskeddb, dblen, mgf1md))
goto cleanup;
for (i = 0; i < mdlen; i++)
seed[i] ^= maskedseed[i];
if (PKCS1_MGF1(db, dblen, seed, mdlen, mgf1md))
goto cleanup;
for (i = 0; i < dblen; i++)
db[i] ^= maskeddb[i];
if (!EVP_Digest((void *)param, plen, phash, NULL, md, NULL))
goto cleanup;
good &= constant_time_is_zero(CRYPTO_memcmp(db, phash, mdlen));
found_one_byte = 0;
for (i = mdlen; i < dblen; i++) {
/*
* Padding consists of a number of 0-bytes, followed by a 1.
*/
unsigned int equals1 = constant_time_eq(db[i], 1);
unsigned int equals0 = constant_time_is_zero(db[i]);
one_index = constant_time_select_int(~found_one_byte & equals1,
i, one_index);
found_one_byte |= equals1;
good &= (found_one_byte | equals0);
}
good &= found_one_byte;
/*
* At this point |good| is zero unless the plaintext was valid,
* so plaintext-awareness ensures timing side-channels are no longer a
* concern.
*/
msg_index = one_index + 1;
mlen = dblen - msg_index;
/*
* For good measure, do this check in constant time as well.
*/
good &= constant_time_ge(tlen, mlen);
/*
* Move the result in-place by |dblen|-|mdlen|-1-|mlen| bytes to the left.
* Then if |good| move |mlen| bytes from |db|+|mdlen|+1 to |to|.
* Otherwise leave |to| unchanged.
* Copy the memory back in a way that does not reveal the size of
* the data being copied via a timing side channel. This requires copying
* parts of the buffer multiple times based on the bits set in the real
* length. Clear bits do a non-copy with identical access pattern.
* The loop below has overall complexity of O(N*log(N)).
*/
tlen = constant_time_select_int(constant_time_lt(dblen - mdlen - 1, tlen),
dblen - mdlen - 1, tlen);
for (msg_index = 1; msg_index < dblen - mdlen - 1; msg_index <<= 1) {
mask = ~constant_time_eq(msg_index & (dblen - mdlen - 1 - mlen), 0);
for (i = mdlen + 1; i < dblen - msg_index; i++)
db[i] = constant_time_select_8(mask, db[i + msg_index], db[i]);
}
for (i = 0; i < tlen; i++) {
mask = good & constant_time_lt(i, mlen);
to[i] = constant_time_select_8(mask, db[i + mdlen + 1], to[i]);
}
#ifndef FIPS_MODULE
/*
* To avoid chosen ciphertext attacks, the error message should not
* reveal which kind of decoding error happened.
*
* This trick doesn't work in the FIPS provider because libcrypto manages
* the error stack. Instead we opt not to put an error on the stack at all
* in case of padding failure in the FIPS provider.
*/
ERR_raise(ERR_LIB_RSA, RSA_R_OAEP_DECODING_ERROR);
err_clear_last_constant_time(1 & good);
#endif
cleanup:
OPENSSL_cleanse(seed, sizeof(seed));
OPENSSL_clear_free(db, dblen);
OPENSSL_clear_free(em, num);
return constant_time_select_int(good, mlen, -1);
}
/*
* Mask Generation Function corresponding to section 7.2.2.2 of NIST SP 800-56B.
* The variables are named differently to NIST:
* mask (T) and len (maskLen)are the returned mask.
* seed (mgfSeed).
* The range checking steps inm the process are performed outside.
*/
int PKCS1_MGF1(unsigned char *mask, long len,
const unsigned char *seed, long seedlen, const EVP_MD *dgst)
{
long i, outlen = 0;
unsigned char cnt[4];
EVP_MD_CTX *c = EVP_MD_CTX_new();
unsigned char md[EVP_MAX_MD_SIZE];
int mdlen;
int rv = -1;
if (c == NULL)
goto err;
mdlen = EVP_MD_get_size(dgst);
if (mdlen < 0)
goto err;
/* step 4 */
for (i = 0; outlen < len; i++) {
/* step 4a: D = I2BS(counter, 4) */
cnt[0] = (unsigned char)((i >> 24) & 255);
cnt[1] = (unsigned char)((i >> 16) & 255);
cnt[2] = (unsigned char)((i >> 8)) & 255;
cnt[3] = (unsigned char)(i & 255);
/* step 4b: T =T || hash(mgfSeed || D) */
if (!EVP_DigestInit_ex(c, dgst, NULL)
|| !EVP_DigestUpdate(c, seed, seedlen)
|| !EVP_DigestUpdate(c, cnt, 4))
goto err;
if (outlen + mdlen <= len) {
if (!EVP_DigestFinal_ex(c, mask + outlen, NULL))
goto err;
outlen += mdlen;
} else {
if (!EVP_DigestFinal_ex(c, md, NULL))
goto err;
memcpy(mask + outlen, md, len - outlen);
outlen = len;
}
}
rv = 0;
err:
OPENSSL_cleanse(md, sizeof(md));
EVP_MD_CTX_free(c);
return rv;
}
diff --git a/crypto/openssl/crypto/x509/v3_utl.c b/crypto/openssl/crypto/x509/v3_utl.c
index 304463d572c6..56ee36d4521e 100644
--- a/crypto/openssl/crypto/x509/v3_utl.c
+++ b/crypto/openssl/crypto/x509/v3_utl.c
@@ -1,1386 +1,1386 @@
/*
- * 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
*/
/* X509 v3 extension utilities */
#include "e_os.h"
#include "internal/cryptlib.h"
#include <stdio.h>
#include <string.h>
#include "crypto/ctype.h"
#include <openssl/conf.h>
#include <openssl/crypto.h>
#include <openssl/x509v3.h>
#include "crypto/x509.h"
#include <openssl/bn.h>
#include "ext_dat.h"
#include "x509_local.h"
static char *strip_spaces(char *name);
static int sk_strcmp(const char *const *a, const char *const *b);
static STACK_OF(OPENSSL_STRING) *get_email(const X509_NAME *name,
GENERAL_NAMES *gens);
static void str_free(OPENSSL_STRING str);
static int append_ia5(STACK_OF(OPENSSL_STRING) **sk,
const ASN1_IA5STRING *email);
static int ipv4_from_asc(unsigned char *v4, const char *in);
static int ipv6_from_asc(unsigned char *v6, const char *in);
static int ipv6_cb(const char *elem, int len, void *usr);
static int ipv6_hex(unsigned char *out, const char *in, int inlen);
/* Add a CONF_VALUE name value pair to stack */
static int x509v3_add_len_value(const char *name, const char *value,
size_t vallen, STACK_OF(CONF_VALUE) **extlist)
{
CONF_VALUE *vtmp = NULL;
char *tname = NULL, *tvalue = NULL;
int sk_allocated = (*extlist == NULL);
if (name != NULL && (tname = OPENSSL_strdup(name)) == NULL)
goto err;
if (value != NULL) {
/* We don't allow embeded NUL characters */
if (memchr(value, 0, vallen) != NULL)
goto err;
tvalue = OPENSSL_strndup(value, vallen);
if (tvalue == NULL)
goto err;
}
if ((vtmp = OPENSSL_malloc(sizeof(*vtmp))) == NULL)
goto err;
if (sk_allocated && (*extlist = sk_CONF_VALUE_new_null()) == NULL)
goto err;
vtmp->section = NULL;
vtmp->name = tname;
vtmp->value = tvalue;
if (!sk_CONF_VALUE_push(*extlist, vtmp))
goto err;
return 1;
err:
ERR_raise(ERR_LIB_X509V3, ERR_R_MALLOC_FAILURE);
if (sk_allocated) {
sk_CONF_VALUE_free(*extlist);
*extlist = NULL;
}
OPENSSL_free(vtmp);
OPENSSL_free(tname);
OPENSSL_free(tvalue);
return 0;
}
int X509V3_add_value(const char *name, const char *value,
STACK_OF(CONF_VALUE) **extlist)
{
return x509v3_add_len_value(name, value,
value != NULL ? strlen((const char *)value) : 0,
extlist);
}
int X509V3_add_value_uchar(const char *name, const unsigned char *value,
STACK_OF(CONF_VALUE) **extlist)
{
return x509v3_add_len_value(name, (const char *)value,
value != NULL ? strlen((const char *)value) : 0,
extlist);
}
int x509v3_add_len_value_uchar(const char *name, const unsigned char *value,
size_t vallen, STACK_OF(CONF_VALUE) **extlist)
{
return x509v3_add_len_value(name, (const char *)value, vallen, extlist);
}
/* Free function for STACK_OF(CONF_VALUE) */
void X509V3_conf_free(CONF_VALUE *conf)
{
if (!conf)
return;
OPENSSL_free(conf->name);
OPENSSL_free(conf->value);
OPENSSL_free(conf->section);
OPENSSL_free(conf);
}
int X509V3_add_value_bool(const char *name, int asn1_bool,
STACK_OF(CONF_VALUE) **extlist)
{
if (asn1_bool)
return X509V3_add_value(name, "TRUE", extlist);
return X509V3_add_value(name, "FALSE", extlist);
}
int X509V3_add_value_bool_nf(const char *name, int asn1_bool,
STACK_OF(CONF_VALUE) **extlist)
{
if (asn1_bool)
return X509V3_add_value(name, "TRUE", extlist);
return 1;
}
static char *bignum_to_string(const BIGNUM *bn)
{
char *tmp, *ret;
size_t len;
/*
* Display large numbers in hex and small numbers in decimal. Converting to
* decimal takes quadratic time and is no more useful than hex for large
* numbers.
*/
if (BN_num_bits(bn) < 128)
return BN_bn2dec(bn);
tmp = BN_bn2hex(bn);
if (tmp == NULL)
return NULL;
len = strlen(tmp) + 3;
ret = OPENSSL_malloc(len);
if (ret == NULL) {
ERR_raise(ERR_LIB_X509V3, ERR_R_MALLOC_FAILURE);
OPENSSL_free(tmp);
return NULL;
}
/* Prepend "0x", but place it after the "-" if negative. */
if (tmp[0] == '-') {
OPENSSL_strlcpy(ret, "-0x", len);
OPENSSL_strlcat(ret, tmp + 1, len);
} else {
OPENSSL_strlcpy(ret, "0x", len);
OPENSSL_strlcat(ret, tmp, len);
}
OPENSSL_free(tmp);
return ret;
}
char *i2s_ASN1_ENUMERATED(X509V3_EXT_METHOD *method, const ASN1_ENUMERATED *a)
{
BIGNUM *bntmp = NULL;
char *strtmp = NULL;
if (!a)
return NULL;
if ((bntmp = ASN1_ENUMERATED_to_BN(a, NULL)) == NULL
|| (strtmp = bignum_to_string(bntmp)) == NULL)
ERR_raise(ERR_LIB_X509V3, ERR_R_MALLOC_FAILURE);
BN_free(bntmp);
return strtmp;
}
char *i2s_ASN1_INTEGER(X509V3_EXT_METHOD *method, const ASN1_INTEGER *a)
{
BIGNUM *bntmp = NULL;
char *strtmp = NULL;
if (!a)
return NULL;
if ((bntmp = ASN1_INTEGER_to_BN(a, NULL)) == NULL
|| (strtmp = bignum_to_string(bntmp)) == NULL)
ERR_raise(ERR_LIB_X509V3, ERR_R_MALLOC_FAILURE);
BN_free(bntmp);
return strtmp;
}
ASN1_INTEGER *s2i_ASN1_INTEGER(X509V3_EXT_METHOD *method, const char *value)
{
BIGNUM *bn = NULL;
ASN1_INTEGER *aint;
int isneg, ishex;
int ret;
if (value == NULL) {
ERR_raise(ERR_LIB_X509V3, X509V3_R_INVALID_NULL_VALUE);
return NULL;
}
bn = BN_new();
if (bn == NULL) {
ERR_raise(ERR_LIB_X509V3, ERR_R_MALLOC_FAILURE);
return NULL;
}
if (value[0] == '-') {
value++;
isneg = 1;
} else {
isneg = 0;
}
if (value[0] == '0' && ((value[1] == 'x') || (value[1] == 'X'))) {
value += 2;
ishex = 1;
} else {
ishex = 0;
}
if (ishex)
ret = BN_hex2bn(&bn, value);
else
ret = BN_dec2bn(&bn, value);
if (!ret || value[ret]) {
BN_free(bn);
ERR_raise(ERR_LIB_X509V3, X509V3_R_BN_DEC2BN_ERROR);
return NULL;
}
if (isneg && BN_is_zero(bn))
isneg = 0;
aint = BN_to_ASN1_INTEGER(bn, NULL);
BN_free(bn);
if (!aint) {
ERR_raise(ERR_LIB_X509V3, X509V3_R_BN_TO_ASN1_INTEGER_ERROR);
return NULL;
}
if (isneg)
aint->type |= V_ASN1_NEG;
return aint;
}
int X509V3_add_value_int(const char *name, const ASN1_INTEGER *aint,
STACK_OF(CONF_VALUE) **extlist)
{
char *strtmp;
int ret;
if (!aint)
return 1;
if ((strtmp = i2s_ASN1_INTEGER(NULL, aint)) == NULL)
return 0;
ret = X509V3_add_value(name, strtmp, extlist);
OPENSSL_free(strtmp);
return ret;
}
int X509V3_get_value_bool(const CONF_VALUE *value, int *asn1_bool)
{
const char *btmp;
if ((btmp = value->value) == NULL)
goto err;
if (strcmp(btmp, "TRUE") == 0
|| strcmp(btmp, "true") == 0
|| strcmp(btmp, "Y") == 0
|| strcmp(btmp, "y") == 0
|| strcmp(btmp, "YES") == 0
|| strcmp(btmp, "yes") == 0) {
*asn1_bool = 0xff;
return 1;
}
if (strcmp(btmp, "FALSE") == 0
|| strcmp(btmp, "false") == 0
|| strcmp(btmp, "N") == 0
|| strcmp(btmp, "n") == 0
|| strcmp(btmp, "NO") == 0
|| strcmp(btmp, "no") == 0) {
*asn1_bool = 0;
return 1;
}
err:
ERR_raise(ERR_LIB_X509V3, X509V3_R_INVALID_BOOLEAN_STRING);
X509V3_conf_add_error_name_value(value);
return 0;
}
int X509V3_get_value_int(const CONF_VALUE *value, ASN1_INTEGER **aint)
{
ASN1_INTEGER *itmp;
if ((itmp = s2i_ASN1_INTEGER(NULL, value->value)) == NULL) {
X509V3_conf_add_error_name_value(value);
return 0;
}
*aint = itmp;
return 1;
}
#define HDR_NAME 1
#define HDR_VALUE 2
/*
* #define DEBUG
*/
STACK_OF(CONF_VALUE) *X509V3_parse_list(const char *line)
{
char *p, *q, c;
char *ntmp, *vtmp;
STACK_OF(CONF_VALUE) *values = NULL;
char *linebuf;
int state;
/* We are going to modify the line so copy it first */
linebuf = OPENSSL_strdup(line);
if (linebuf == NULL) {
ERR_raise(ERR_LIB_X509V3, ERR_R_MALLOC_FAILURE);
goto err;
}
state = HDR_NAME;
ntmp = NULL;
/* Go through all characters */
for (p = linebuf, q = linebuf; (c = *p) && (c != '\r') && (c != '\n');
p++) {
switch (state) {
case HDR_NAME:
if (c == ':') {
state = HDR_VALUE;
*p = 0;
ntmp = strip_spaces(q);
if (!ntmp) {
ERR_raise(ERR_LIB_X509V3, X509V3_R_INVALID_EMPTY_NAME);
goto err;
}
q = p + 1;
} else if (c == ',') {
*p = 0;
ntmp = strip_spaces(q);
q = p + 1;
if (!ntmp) {
ERR_raise(ERR_LIB_X509V3, X509V3_R_INVALID_EMPTY_NAME);
goto err;
}
if (!X509V3_add_value(ntmp, NULL, &values)) {
goto err;
}
}
break;
case HDR_VALUE:
if (c == ',') {
state = HDR_NAME;
*p = 0;
vtmp = strip_spaces(q);
if (!vtmp) {
ERR_raise(ERR_LIB_X509V3, X509V3_R_INVALID_NULL_VALUE);
goto err;
}
if (!X509V3_add_value(ntmp, vtmp, &values)) {
goto err;
}
ntmp = NULL;
q = p + 1;
}
}
}
if (state == HDR_VALUE) {
vtmp = strip_spaces(q);
if (!vtmp) {
ERR_raise(ERR_LIB_X509V3, X509V3_R_INVALID_NULL_VALUE);
goto err;
}
if (!X509V3_add_value(ntmp, vtmp, &values)) {
goto err;
}
} else {
ntmp = strip_spaces(q);
if (!ntmp) {
ERR_raise(ERR_LIB_X509V3, X509V3_R_INVALID_EMPTY_NAME);
goto err;
}
if (!X509V3_add_value(ntmp, NULL, &values)) {
goto err;
}
}
OPENSSL_free(linebuf);
return values;
err:
OPENSSL_free(linebuf);
sk_CONF_VALUE_pop_free(values, X509V3_conf_free);
return NULL;
}
/* Delete leading and trailing spaces from a string */
static char *strip_spaces(char *name)
{
char *p, *q;
/* Skip over leading spaces */
p = name;
while (*p && ossl_isspace(*p))
p++;
if (*p == '\0')
return NULL;
q = p + strlen(p) - 1;
while ((q != p) && ossl_isspace(*q))
q--;
if (p != q)
q[1] = 0;
if (*p == '\0')
return NULL;
return p;
}
/*
* V2I name comparison function: returns zero if 'name' matches cmp or cmp.*
*/
int ossl_v3_name_cmp(const char *name, const char *cmp)
{
int len, ret;
char c;
len = strlen(cmp);
if ((ret = strncmp(name, cmp, len)))
return ret;
c = name[len];
if (!c || (c == '.'))
return 0;
return 1;
}
static int sk_strcmp(const char *const *a, const char *const *b)
{
return strcmp(*a, *b);
}
STACK_OF(OPENSSL_STRING) *X509_get1_email(X509 *x)
{
GENERAL_NAMES *gens;
STACK_OF(OPENSSL_STRING) *ret;
gens = X509_get_ext_d2i(x, NID_subject_alt_name, NULL, NULL);
ret = get_email(X509_get_subject_name(x), gens);
sk_GENERAL_NAME_pop_free(gens, GENERAL_NAME_free);
return ret;
}
STACK_OF(OPENSSL_STRING) *X509_get1_ocsp(X509 *x)
{
AUTHORITY_INFO_ACCESS *info;
STACK_OF(OPENSSL_STRING) *ret = NULL;
int i;
info = X509_get_ext_d2i(x, NID_info_access, NULL, NULL);
if (!info)
return NULL;
for (i = 0; i < sk_ACCESS_DESCRIPTION_num(info); i++) {
ACCESS_DESCRIPTION *ad = sk_ACCESS_DESCRIPTION_value(info, i);
if (OBJ_obj2nid(ad->method) == NID_ad_OCSP) {
if (ad->location->type == GEN_URI) {
if (!append_ia5
(&ret, ad->location->d.uniformResourceIdentifier))
break;
}
}
}
AUTHORITY_INFO_ACCESS_free(info);
return ret;
}
STACK_OF(OPENSSL_STRING) *X509_REQ_get1_email(X509_REQ *x)
{
GENERAL_NAMES *gens;
STACK_OF(X509_EXTENSION) *exts;
STACK_OF(OPENSSL_STRING) *ret;
exts = X509_REQ_get_extensions(x);
gens = X509V3_get_d2i(exts, NID_subject_alt_name, NULL, NULL);
ret = get_email(X509_REQ_get_subject_name(x), gens);
sk_GENERAL_NAME_pop_free(gens, GENERAL_NAME_free);
sk_X509_EXTENSION_pop_free(exts, X509_EXTENSION_free);
return ret;
}
static STACK_OF(OPENSSL_STRING) *get_email(const X509_NAME *name,
GENERAL_NAMES *gens)
{
STACK_OF(OPENSSL_STRING) *ret = NULL;
X509_NAME_ENTRY *ne;
const ASN1_IA5STRING *email;
GENERAL_NAME *gen;
int i = -1;
/* Now add any email address(es) to STACK */
/* First supplied X509_NAME */
while ((i = X509_NAME_get_index_by_NID(name,
NID_pkcs9_emailAddress, i)) >= 0) {
ne = X509_NAME_get_entry(name, i);
email = X509_NAME_ENTRY_get_data(ne);
if (!append_ia5(&ret, email))
return NULL;
}
for (i = 0; i < sk_GENERAL_NAME_num(gens); i++) {
gen = sk_GENERAL_NAME_value(gens, i);
if (gen->type != GEN_EMAIL)
continue;
if (!append_ia5(&ret, gen->d.ia5))
return NULL;
}
return ret;
}
static void str_free(OPENSSL_STRING str)
{
OPENSSL_free(str);
}
static int append_ia5(STACK_OF(OPENSSL_STRING) **sk,
const ASN1_IA5STRING *email)
{
char *emtmp;
/* First some sanity checks */
if (email->type != V_ASN1_IA5STRING)
return 1;
if (email->data == NULL || email->length == 0)
return 1;
if (memchr(email->data, 0, email->length) != NULL)
return 1;
if (*sk == NULL)
*sk = sk_OPENSSL_STRING_new(sk_strcmp);
if (*sk == NULL)
return 0;
emtmp = OPENSSL_strndup((char *)email->data, email->length);
if (emtmp == NULL) {
X509_email_free(*sk);
*sk = NULL;
return 0;
}
/* Don't add duplicates */
if (sk_OPENSSL_STRING_find(*sk, emtmp) != -1) {
OPENSSL_free(emtmp);
return 1;
}
if (!sk_OPENSSL_STRING_push(*sk, emtmp)) {
OPENSSL_free(emtmp); /* free on push failure */
X509_email_free(*sk);
*sk = NULL;
return 0;
}
return 1;
}
void X509_email_free(STACK_OF(OPENSSL_STRING) *sk)
{
sk_OPENSSL_STRING_pop_free(sk, str_free);
}
typedef int (*equal_fn) (const unsigned char *pattern, size_t pattern_len,
const unsigned char *subject, size_t subject_len,
unsigned int flags);
/* Skip pattern prefix to match "wildcard" subject */
static void skip_prefix(const unsigned char **p, size_t *plen,
size_t subject_len,
unsigned int flags)
{
const unsigned char *pattern = *p;
size_t pattern_len = *plen;
/*
* If subject starts with a leading '.' followed by more octets, and
* pattern is longer, compare just an equal-length suffix with the
* full subject (starting at the '.'), provided the prefix contains
* no NULs.
*/
if ((flags & _X509_CHECK_FLAG_DOT_SUBDOMAINS) == 0)
return;
while (pattern_len > subject_len && *pattern) {
if ((flags & X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS) &&
*pattern == '.')
break;
++pattern;
--pattern_len;
}
/* Skip if entire prefix acceptable */
if (pattern_len == subject_len) {
*p = pattern;
*plen = pattern_len;
}
}
/* Compare while ASCII ignoring case. */
static int equal_nocase(const unsigned char *pattern, size_t pattern_len,
const unsigned char *subject, size_t subject_len,
unsigned int flags)
{
skip_prefix(&pattern, &pattern_len, subject_len, flags);
if (pattern_len != subject_len)
return 0;
while (pattern_len != 0) {
unsigned char l = *pattern;
unsigned char r = *subject;
/* The pattern must not contain NUL characters. */
if (l == 0)
return 0;
if (l != r) {
if ('A' <= l && l <= 'Z')
l = (l - 'A') + 'a';
if ('A' <= r && r <= 'Z')
r = (r - 'A') + 'a';
if (l != r)
return 0;
}
++pattern;
++subject;
--pattern_len;
}
return 1;
}
/* Compare using memcmp. */
static int equal_case(const unsigned char *pattern, size_t pattern_len,
const unsigned char *subject, size_t subject_len,
unsigned int flags)
{
skip_prefix(&pattern, &pattern_len, subject_len, flags);
if (pattern_len != subject_len)
return 0;
return !memcmp(pattern, subject, pattern_len);
}
/*
* RFC 5280, section 7.5, requires that only the domain is compared in a
* case-insensitive manner.
*/
static int equal_email(const unsigned char *a, size_t a_len,
const unsigned char *b, size_t b_len,
unsigned int unused_flags)
{
size_t i = a_len;
if (a_len != b_len)
return 0;
/*
* We search backwards for the '@' character, so that we do not have to
* deal with quoted local-parts. The domain part is compared in a
* case-insensitive manner.
*/
while (i > 0) {
--i;
if (a[i] == '@' || b[i] == '@') {
if (!equal_nocase(a + i, a_len - i, b + i, a_len - i, 0))
return 0;
break;
}
}
if (i == 0)
i = a_len;
return equal_case(a, i, b, i, 0);
}
/*
* Compare the prefix and suffix with the subject, and check that the
* characters in-between are valid.
*/
static int wildcard_match(const unsigned char *prefix, size_t prefix_len,
const unsigned char *suffix, size_t suffix_len,
const unsigned char *subject, size_t subject_len,
unsigned int flags)
{
const unsigned char *wildcard_start;
const unsigned char *wildcard_end;
const unsigned char *p;
int allow_multi = 0;
int allow_idna = 0;
if (subject_len < prefix_len + suffix_len)
return 0;
if (!equal_nocase(prefix, prefix_len, subject, prefix_len, flags))
return 0;
wildcard_start = subject + prefix_len;
wildcard_end = subject + (subject_len - suffix_len);
if (!equal_nocase(wildcard_end, suffix_len, suffix, suffix_len, flags))
return 0;
/*
* If the wildcard makes up the entire first label, it must match at
* least one character.
*/
if (prefix_len == 0 && *suffix == '.') {
if (wildcard_start == wildcard_end)
return 0;
allow_idna = 1;
if (flags & X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS)
allow_multi = 1;
}
/* IDNA labels cannot match partial wildcards */
if (!allow_idna &&
subject_len >= 4 && OPENSSL_strncasecmp((char *)subject, "xn--", 4) == 0)
return 0;
/* The wildcard may match a literal '*' */
if (wildcard_end == wildcard_start + 1 && *wildcard_start == '*')
return 1;
/*
* Check that the part matched by the wildcard contains only
* permitted characters and only matches a single label unless
* allow_multi is set.
*/
for (p = wildcard_start; p != wildcard_end; ++p)
if (!(('0' <= *p && *p <= '9') ||
('A' <= *p && *p <= 'Z') ||
('a' <= *p && *p <= 'z') ||
*p == '-' || (allow_multi && *p == '.')))
return 0;
return 1;
}
#define LABEL_START (1 << 0)
#define LABEL_END (1 << 1)
#define LABEL_HYPHEN (1 << 2)
#define LABEL_IDNA (1 << 3)
static const unsigned char *valid_star(const unsigned char *p, size_t len,
unsigned int flags)
{
const unsigned char *star = 0;
size_t i;
int state = LABEL_START;
int dots = 0;
for (i = 0; i < len; ++i) {
/*
* Locate first and only legal wildcard, either at the start
* or end of a non-IDNA first and not final label.
*/
if (p[i] == '*') {
int atstart = (state & LABEL_START);
int atend = (i == len - 1 || p[i + 1] == '.');
/*-
* At most one wildcard per pattern.
* No wildcards in IDNA labels.
* No wildcards after the first label.
*/
if (star != NULL || (state & LABEL_IDNA) != 0 || dots)
return NULL;
/* Only full-label '*.example.com' wildcards? */
if ((flags & X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS)
&& (!atstart || !atend))
return NULL;
/* No 'foo*bar' wildcards */
if (!atstart && !atend)
return NULL;
star = &p[i];
state &= ~LABEL_START;
} else if (('a' <= p[i] && p[i] <= 'z')
|| ('A' <= p[i] && p[i] <= 'Z')
|| ('0' <= p[i] && p[i] <= '9')) {
if ((state & LABEL_START) != 0
&& len - i >= 4 && OPENSSL_strncasecmp((char *)&p[i], "xn--", 4) == 0)
state |= LABEL_IDNA;
state &= ~(LABEL_HYPHEN | LABEL_START);
} else if (p[i] == '.') {
if ((state & (LABEL_HYPHEN | LABEL_START)) != 0)
return NULL;
state = LABEL_START;
++dots;
} else if (p[i] == '-') {
/* no domain/subdomain starts with '-' */
if ((state & LABEL_START) != 0)
return NULL;
state |= LABEL_HYPHEN;
} else {
return NULL;
}
}
/*
* The final label must not end in a hyphen or ".", and
* there must be at least two dots after the star.
*/
if ((state & (LABEL_START | LABEL_HYPHEN)) != 0 || dots < 2)
return NULL;
return star;
}
/* Compare using wildcards. */
static int equal_wildcard(const unsigned char *pattern, size_t pattern_len,
const unsigned char *subject, size_t subject_len,
unsigned int flags)
{
const unsigned char *star = NULL;
/*
* Subject names starting with '.' can only match a wildcard pattern
* via a subject sub-domain pattern suffix match.
*/
if (!(subject_len > 1 && subject[0] == '.'))
star = valid_star(pattern, pattern_len, flags);
if (star == NULL)
return equal_nocase(pattern, pattern_len,
subject, subject_len, flags);
return wildcard_match(pattern, star - pattern,
star + 1, (pattern + pattern_len) - star - 1,
subject, subject_len, flags);
}
/*
* Compare an ASN1_STRING to a supplied string. If they match return 1. If
* cmp_type > 0 only compare if string matches the type, otherwise convert it
* to UTF8.
*/
static int do_check_string(const ASN1_STRING *a, int cmp_type, equal_fn equal,
unsigned int flags, const char *b, size_t blen,
char **peername)
{
int rv = 0;
if (!a->data || !a->length)
return 0;
if (cmp_type > 0) {
if (cmp_type != a->type)
return 0;
if (cmp_type == V_ASN1_IA5STRING)
rv = equal(a->data, a->length, (unsigned char *)b, blen, flags);
else if (a->length == (int)blen && !memcmp(a->data, b, blen))
rv = 1;
if (rv > 0 && peername != NULL) {
*peername = OPENSSL_strndup((char *)a->data, a->length);
if (*peername == NULL)
return -1;
}
} else {
int astrlen;
unsigned char *astr;
astrlen = ASN1_STRING_to_UTF8(&astr, a);
if (astrlen < 0) {
/*
* -1 could be an internal malloc failure or a decoding error from
* malformed input; we can't distinguish.
*/
return -1;
}
rv = equal(astr, astrlen, (unsigned char *)b, blen, flags);
if (rv > 0 && peername != NULL) {
*peername = OPENSSL_strndup((char *)astr, astrlen);
if (*peername == NULL) {
OPENSSL_free(astr);
return -1;
}
}
OPENSSL_free(astr);
}
return rv;
}
static int do_x509_check(X509 *x, const char *chk, size_t chklen,
unsigned int flags, int check_type, char **peername)
{
GENERAL_NAMES *gens = NULL;
const X509_NAME *name = NULL;
int i;
int cnid = NID_undef;
int alt_type;
int san_present = 0;
int rv = 0;
equal_fn equal;
/* See below, this flag is internal-only */
flags &= ~_X509_CHECK_FLAG_DOT_SUBDOMAINS;
if (check_type == GEN_EMAIL) {
cnid = NID_pkcs9_emailAddress;
alt_type = V_ASN1_IA5STRING;
equal = equal_email;
} else if (check_type == GEN_DNS) {
cnid = NID_commonName;
/* Implicit client-side DNS sub-domain pattern */
if (chklen > 1 && chk[0] == '.')
flags |= _X509_CHECK_FLAG_DOT_SUBDOMAINS;
alt_type = V_ASN1_IA5STRING;
if (flags & X509_CHECK_FLAG_NO_WILDCARDS)
equal = equal_nocase;
else
equal = equal_wildcard;
} else {
alt_type = V_ASN1_OCTET_STRING;
equal = equal_case;
}
if (chklen == 0)
chklen = strlen(chk);
gens = X509_get_ext_d2i(x, NID_subject_alt_name, NULL, NULL);
if (gens) {
for (i = 0; i < sk_GENERAL_NAME_num(gens); i++) {
GENERAL_NAME *gen;
ASN1_STRING *cstr;
gen = sk_GENERAL_NAME_value(gens, i);
switch (gen->type) {
default:
continue;
case GEN_OTHERNAME:
switch (OBJ_obj2nid(gen->d.otherName->type_id)) {
default:
continue;
case NID_id_on_SmtpUTF8Mailbox:
/*-
* https://datatracker.ietf.org/doc/html/rfc8398#section-3
*
* Due to name constraint compatibility reasons described
* in Section 6, SmtpUTF8Mailbox subjectAltName MUST NOT
* be used unless the local-part of the email address
* contains non-ASCII characters. When the local-part is
* ASCII, rfc822Name subjectAltName MUST be used instead
* of SmtpUTF8Mailbox. This is compatible with legacy
* software that supports only rfc822Name (and not
* SmtpUTF8Mailbox). [...]
*
* SmtpUTF8Mailbox is encoded as UTF8String.
*
* If it is not a UTF8String then that is unexpected, and
* we ignore the invalid SAN (neither set san_present nor
* consider it a candidate for equality). This does mean
* that the subject CN may be considered, as would be the
* case when the malformed SmtpUtf8Mailbox SAN is instead
* simply absent.
*
* When CN-ID matching is not desirable, applications can
* choose to turn it off, doing so is at this time a best
* practice.
*/
if (check_type != GEN_EMAIL
|| gen->d.otherName->value->type != V_ASN1_UTF8STRING)
continue;
alt_type = 0;
cstr = gen->d.otherName->value->value.utf8string;
break;
}
break;
case GEN_EMAIL:
if (check_type != GEN_EMAIL)
continue;
cstr = gen->d.rfc822Name;
break;
case GEN_DNS:
if (check_type != GEN_DNS)
continue;
cstr = gen->d.dNSName;
break;
case GEN_IPADD:
if (check_type != GEN_IPADD)
continue;
cstr = gen->d.iPAddress;
break;
}
san_present = 1;
/* Positive on success, negative on error! */
if ((rv = do_check_string(cstr, alt_type, equal, flags,
chk, chklen, peername)) != 0)
break;
}
GENERAL_NAMES_free(gens);
if (rv != 0)
return rv;
if (san_present && !(flags & X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT))
return 0;
}
/* We're done if CN-ID is not pertinent */
if (cnid == NID_undef || (flags & X509_CHECK_FLAG_NEVER_CHECK_SUBJECT))
return 0;
i = -1;
name = X509_get_subject_name(x);
while ((i = X509_NAME_get_index_by_NID(name, cnid, i)) >= 0) {
const X509_NAME_ENTRY *ne = X509_NAME_get_entry(name, i);
const ASN1_STRING *str = X509_NAME_ENTRY_get_data(ne);
/* Positive on success, negative on error! */
if ((rv = do_check_string(str, -1, equal, flags,
chk, chklen, peername)) != 0)
return rv;
}
return 0;
}
int X509_check_host(X509 *x, const char *chk, size_t chklen,
unsigned int flags, char **peername)
{
if (chk == NULL)
return -2;
/*
* Embedded NULs are disallowed, except as the last character of a
* string of length 2 or more (tolerate caller including terminating
* NUL in string length).
*/
if (chklen == 0)
chklen = strlen(chk);
else if (memchr(chk, '\0', chklen > 1 ? chklen - 1 : chklen))
return -2;
if (chklen > 1 && chk[chklen - 1] == '\0')
--chklen;
return do_x509_check(x, chk, chklen, flags, GEN_DNS, peername);
}
int X509_check_email(X509 *x, const char *chk, size_t chklen,
unsigned int flags)
{
if (chk == NULL)
return -2;
/*
* Embedded NULs are disallowed, except as the last character of a
* string of length 2 or more (tolerate caller including terminating
* NUL in string length).
*/
if (chklen == 0)
chklen = strlen((char *)chk);
else if (memchr(chk, '\0', chklen > 1 ? chklen - 1 : chklen))
return -2;
if (chklen > 1 && chk[chklen - 1] == '\0')
--chklen;
return do_x509_check(x, chk, chklen, flags, GEN_EMAIL, NULL);
}
int X509_check_ip(X509 *x, const unsigned char *chk, size_t chklen,
unsigned int flags)
{
if (chk == NULL)
return -2;
return do_x509_check(x, (char *)chk, chklen, flags, GEN_IPADD, NULL);
}
int X509_check_ip_asc(X509 *x, const char *ipasc, unsigned int flags)
{
unsigned char ipout[16];
size_t iplen;
if (ipasc == NULL)
return -2;
iplen = (size_t)ossl_a2i_ipadd(ipout, ipasc);
if (iplen == 0)
return -2;
return do_x509_check(x, (char *)ipout, iplen, flags, GEN_IPADD, NULL);
}
char *ossl_ipaddr_to_asc(unsigned char *p, int len)
{
/*
* 40 is enough space for the longest IPv6 address + nul terminator byte
* XXXX:XXXX:XXXX:XXXX:XXXX:XXXX:XXXX:XXXX\0
*/
char buf[40], *out;
int i = 0, remain = 0, bytes = 0;
switch (len) {
case 4: /* IPv4 */
BIO_snprintf(buf, sizeof(buf), "%d.%d.%d.%d", p[0], p[1], p[2], p[3]);
break;
case 16: /* IPv6 */
for (out = buf, i = 8, remain = sizeof(buf);
i-- > 0 && bytes >= 0;
remain -= bytes, out += bytes) {
const char *template = (i > 0 ? "%X:" : "%X");
bytes = BIO_snprintf(out, remain, template, p[0] << 8 | p[1]);
p += 2;
}
break;
default:
BIO_snprintf(buf, sizeof(buf), "<invalid length=%d>", len);
break;
}
return OPENSSL_strdup(buf);
}
/*
* Convert IP addresses both IPv4 and IPv6 into an OCTET STRING compatible
* with RFC3280.
*/
ASN1_OCTET_STRING *a2i_IPADDRESS(const char *ipasc)
{
unsigned char ipout[16];
ASN1_OCTET_STRING *ret;
int iplen;
/* If string contains a ':' assume IPv6 */
iplen = ossl_a2i_ipadd(ipout, ipasc);
if (!iplen)
return NULL;
ret = ASN1_OCTET_STRING_new();
if (ret == NULL)
return NULL;
if (!ASN1_OCTET_STRING_set(ret, ipout, iplen)) {
ASN1_OCTET_STRING_free(ret);
return NULL;
}
return ret;
}
ASN1_OCTET_STRING *a2i_IPADDRESS_NC(const char *ipasc)
{
ASN1_OCTET_STRING *ret = NULL;
unsigned char ipout[32];
char *iptmp = NULL, *p;
int iplen1, iplen2;
p = strchr(ipasc, '/');
if (p == NULL)
return NULL;
iptmp = OPENSSL_strdup(ipasc);
if (iptmp == NULL)
return NULL;
p = iptmp + (p - ipasc);
*p++ = 0;
iplen1 = ossl_a2i_ipadd(ipout, iptmp);
if (!iplen1)
goto err;
iplen2 = ossl_a2i_ipadd(ipout + iplen1, p);
OPENSSL_free(iptmp);
iptmp = NULL;
if (!iplen2 || (iplen1 != iplen2))
goto err;
ret = ASN1_OCTET_STRING_new();
if (ret == NULL)
goto err;
if (!ASN1_OCTET_STRING_set(ret, ipout, iplen1 + iplen2))
goto err;
return ret;
err:
OPENSSL_free(iptmp);
ASN1_OCTET_STRING_free(ret);
return NULL;
}
int ossl_a2i_ipadd(unsigned char *ipout, const char *ipasc)
{
/* If string contains a ':' assume IPv6 */
if (strchr(ipasc, ':')) {
if (!ipv6_from_asc(ipout, ipasc))
return 0;
return 16;
} else {
if (!ipv4_from_asc(ipout, ipasc))
return 0;
return 4;
}
}
static int ipv4_from_asc(unsigned char *v4, const char *in)
{
const char *p;
int a0, a1, a2, a3, n;
if (sscanf(in, "%d.%d.%d.%d%n", &a0, &a1, &a2, &a3, &n) != 4)
return 0;
if ((a0 < 0) || (a0 > 255) || (a1 < 0) || (a1 > 255)
|| (a2 < 0) || (a2 > 255) || (a3 < 0) || (a3 > 255))
return 0;
p = in + n;
if (!(*p == '\0' || ossl_isspace(*p)))
return 0;
v4[0] = a0;
v4[1] = a1;
v4[2] = a2;
v4[3] = a3;
return 1;
}
typedef struct {
/* Temporary store for IPV6 output */
unsigned char tmp[16];
/* Total number of bytes in tmp */
int total;
/* The position of a zero (corresponding to '::') */
int zero_pos;
/* Number of zeroes */
int zero_cnt;
} IPV6_STAT;
static int ipv6_from_asc(unsigned char *v6, const char *in)
{
IPV6_STAT v6stat;
v6stat.total = 0;
v6stat.zero_pos = -1;
v6stat.zero_cnt = 0;
/*
* Treat the IPv6 representation as a list of values separated by ':'.
* The presence of a '::' will parse as one, two or three zero length
* elements.
*/
if (!CONF_parse_list(in, ':', 0, ipv6_cb, &v6stat))
return 0;
/* Now for some sanity checks */
if (v6stat.zero_pos == -1) {
/* If no '::' must have exactly 16 bytes */
if (v6stat.total != 16)
return 0;
} else {
/* If '::' must have less than 16 bytes */
if (v6stat.total == 16)
return 0;
/* More than three zeroes is an error */
if (v6stat.zero_cnt > 3) {
return 0;
/* Can only have three zeroes if nothing else present */
} else if (v6stat.zero_cnt == 3) {
if (v6stat.total > 0)
return 0;
} else if (v6stat.zero_cnt == 2) {
/* Can only have two zeroes if at start or end */
if ((v6stat.zero_pos != 0)
&& (v6stat.zero_pos != v6stat.total))
return 0;
} else {
/* Can only have one zero if *not* start or end */
if ((v6stat.zero_pos == 0)
|| (v6stat.zero_pos == v6stat.total))
return 0;
}
}
/* Format result */
if (v6stat.zero_pos >= 0) {
/* Copy initial part */
memcpy(v6, v6stat.tmp, v6stat.zero_pos);
/* Zero middle */
memset(v6 + v6stat.zero_pos, 0, 16 - v6stat.total);
/* Copy final part */
if (v6stat.total != v6stat.zero_pos)
memcpy(v6 + v6stat.zero_pos + 16 - v6stat.total,
v6stat.tmp + v6stat.zero_pos,
v6stat.total - v6stat.zero_pos);
} else {
memcpy(v6, v6stat.tmp, 16);
}
return 1;
}
static int ipv6_cb(const char *elem, int len, void *usr)
{
IPV6_STAT *s = usr;
/* Error if 16 bytes written */
if (s->total == 16)
return 0;
if (len == 0) {
/* Zero length element, corresponds to '::' */
if (s->zero_pos == -1)
s->zero_pos = s->total;
/* If we've already got a :: its an error */
else if (s->zero_pos != s->total)
return 0;
s->zero_cnt++;
} else {
/* If more than 4 characters could be final a.b.c.d form */
if (len > 4) {
/* Need at least 4 bytes left */
if (s->total > 12)
return 0;
/* Must be end of string */
if (elem[len])
return 0;
if (!ipv4_from_asc(s->tmp + s->total, elem))
return 0;
s->total += 4;
} else {
if (!ipv6_hex(s->tmp + s->total, elem, len))
return 0;
s->total += 2;
}
}
return 1;
}
/*
* Convert a string of up to 4 hex digits into the corresponding IPv6 form.
*/
static int ipv6_hex(unsigned char *out, const char *in, int inlen)
{
unsigned char c;
unsigned int num = 0;
int x;
if (inlen > 4)
return 0;
while (inlen--) {
c = *in++;
num <<= 4;
x = OPENSSL_hexchar2int(c);
if (x < 0)
return 0;
num |= (char)x;
}
out[0] = num >> 8;
out[1] = num & 0xff;
return 1;
}
int X509V3_NAME_from_section(X509_NAME *nm, STACK_OF(CONF_VALUE) *dn_sk,
unsigned long chtype)
{
CONF_VALUE *v;
int i, mval, spec_char, plus_char;
char *p, *type;
if (!nm)
return 0;
for (i = 0; i < sk_CONF_VALUE_num(dn_sk); i++) {
v = sk_CONF_VALUE_value(dn_sk, i);
type = v->name;
/*
* Skip past any leading X. X: X, etc to allow for multiple instances
*/
for (p = type; *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) {
mval = -1;
type++;
} else {
mval = 0;
}
if (!X509_NAME_add_entry_by_txt(nm, type, chtype,
(unsigned char *)v->value, -1, -1,
mval))
return 0;
}
return 1;
}
diff --git a/crypto/openssl/crypto/x509/x_name.c b/crypto/openssl/crypto/x509/x_name.c
index 944eb9992486..eded80246df9 100644
--- a/crypto/openssl/crypto/x509/x_name.c
+++ b/crypto/openssl/crypto/x509/x_name.c
@@ -1,553 +1,553 @@
/*
- * 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 "crypto/ctype.h"
#include "internal/cryptlib.h"
#include <openssl/asn1t.h>
#include <openssl/x509.h>
#include "crypto/x509.h"
#include "crypto/asn1.h"
#include "x509_local.h"
/*
* Maximum length of X509_NAME: much larger than anything we should
* ever see in practice.
*/
#define X509_NAME_MAX (1024 * 1024)
static int x509_name_ex_d2i(ASN1_VALUE **val,
const unsigned char **in, long len,
const ASN1_ITEM *it,
int tag, int aclass, char opt, ASN1_TLC *ctx);
static int x509_name_ex_i2d(const ASN1_VALUE **val, unsigned char **out,
const ASN1_ITEM *it, int tag, int aclass);
static int x509_name_ex_new(ASN1_VALUE **val, const ASN1_ITEM *it);
static void x509_name_ex_free(ASN1_VALUE **val, const ASN1_ITEM *it);
static int x509_name_encode(X509_NAME *a);
static int x509_name_canon(X509_NAME *a);
static int asn1_string_canon(ASN1_STRING *out, const ASN1_STRING *in);
static int i2d_name_canon(const STACK_OF(STACK_OF_X509_NAME_ENTRY) * intname,
unsigned char **in);
static int x509_name_ex_print(BIO *out, const ASN1_VALUE **pval,
int indent,
const char *fname, const ASN1_PCTX *pctx);
ASN1_SEQUENCE(X509_NAME_ENTRY) = {
ASN1_SIMPLE(X509_NAME_ENTRY, object, ASN1_OBJECT),
ASN1_SIMPLE(X509_NAME_ENTRY, value, ASN1_PRINTABLE)
} ASN1_SEQUENCE_END(X509_NAME_ENTRY)
IMPLEMENT_ASN1_FUNCTIONS(X509_NAME_ENTRY)
IMPLEMENT_ASN1_DUP_FUNCTION(X509_NAME_ENTRY)
/*
* For the "Name" type we need a SEQUENCE OF { SET OF X509_NAME_ENTRY } so
* declare two template wrappers for this
*/
ASN1_ITEM_TEMPLATE(X509_NAME_ENTRIES) =
ASN1_EX_TEMPLATE_TYPE(ASN1_TFLG_SET_OF, 0, RDNS, X509_NAME_ENTRY)
static_ASN1_ITEM_TEMPLATE_END(X509_NAME_ENTRIES)
ASN1_ITEM_TEMPLATE(X509_NAME_INTERNAL) =
ASN1_EX_TEMPLATE_TYPE(ASN1_TFLG_SEQUENCE_OF, 0, Name, X509_NAME_ENTRIES)
static_ASN1_ITEM_TEMPLATE_END(X509_NAME_INTERNAL)
/*
* Normally that's where it would end: we'd have two nested STACK structures
* representing the ASN1. Unfortunately X509_NAME uses a completely different
* form and caches encodings so we have to process the internal form and
* convert to the external form.
*/
static const ASN1_EXTERN_FUNCS x509_name_ff = {
NULL,
x509_name_ex_new,
x509_name_ex_free,
0, /* Default clear behaviour is OK */
x509_name_ex_d2i,
x509_name_ex_i2d,
x509_name_ex_print
};
IMPLEMENT_EXTERN_ASN1(X509_NAME, V_ASN1_SEQUENCE, x509_name_ff)
IMPLEMENT_ASN1_FUNCTIONS(X509_NAME)
IMPLEMENT_ASN1_DUP_FUNCTION(X509_NAME)
static int x509_name_ex_new(ASN1_VALUE **val, const ASN1_ITEM *it)
{
X509_NAME *ret = OPENSSL_zalloc(sizeof(*ret));
if (ret == NULL)
goto memerr;
if ((ret->entries = sk_X509_NAME_ENTRY_new_null()) == NULL)
goto memerr;
if ((ret->bytes = BUF_MEM_new()) == NULL)
goto memerr;
ret->modified = 1;
*val = (ASN1_VALUE *)ret;
return 1;
memerr:
ERR_raise(ERR_LIB_ASN1, ERR_R_MALLOC_FAILURE);
if (ret) {
sk_X509_NAME_ENTRY_free(ret->entries);
OPENSSL_free(ret);
}
return 0;
}
static void x509_name_ex_free(ASN1_VALUE **pval, const ASN1_ITEM *it)
{
X509_NAME *a;
if (pval == NULL || *pval == NULL)
return;
a = (X509_NAME *)*pval;
BUF_MEM_free(a->bytes);
sk_X509_NAME_ENTRY_pop_free(a->entries, X509_NAME_ENTRY_free);
OPENSSL_free(a->canon_enc);
OPENSSL_free(a);
*pval = NULL;
}
static void local_sk_X509_NAME_ENTRY_free(STACK_OF(X509_NAME_ENTRY) *ne)
{
sk_X509_NAME_ENTRY_free(ne);
}
static void local_sk_X509_NAME_ENTRY_pop_free(STACK_OF(X509_NAME_ENTRY) *ne)
{
sk_X509_NAME_ENTRY_pop_free(ne, X509_NAME_ENTRY_free);
}
static int x509_name_ex_d2i(ASN1_VALUE **val,
const unsigned char **in, long len,
const ASN1_ITEM *it, int tag, int aclass,
char opt, ASN1_TLC *ctx)
{
const unsigned char *p = *in, *q;
union {
STACK_OF(STACK_OF_X509_NAME_ENTRY) *s;
ASN1_VALUE *a;
} intname = {
NULL
};
union {
X509_NAME *x;
ASN1_VALUE *a;
} nm = {
NULL
};
int i, j, ret;
STACK_OF(X509_NAME_ENTRY) *entries;
X509_NAME_ENTRY *entry;
if (len > X509_NAME_MAX)
len = X509_NAME_MAX;
q = p;
/* Get internal representation of Name */
ret = ASN1_item_ex_d2i(&intname.a,
&p, len, ASN1_ITEM_rptr(X509_NAME_INTERNAL),
tag, aclass, opt, ctx);
if (ret <= 0)
return ret;
if (*val)
x509_name_ex_free(val, NULL);
if (!x509_name_ex_new(&nm.a, NULL))
goto err;
/* We've decoded it: now cache encoding */
if (!BUF_MEM_grow(nm.x->bytes, p - q))
goto err;
memcpy(nm.x->bytes->data, q, p - q);
/* Convert internal representation to X509_NAME structure */
for (i = 0; i < sk_STACK_OF_X509_NAME_ENTRY_num(intname.s); i++) {
entries = sk_STACK_OF_X509_NAME_ENTRY_value(intname.s, i);
for (j = 0; j < sk_X509_NAME_ENTRY_num(entries); j++) {
entry = sk_X509_NAME_ENTRY_value(entries, j);
entry->set = i;
if (!sk_X509_NAME_ENTRY_push(nm.x->entries, entry))
goto err;
(void)sk_X509_NAME_ENTRY_set(entries, j, NULL);
}
}
ret = x509_name_canon(nm.x);
if (!ret)
goto err;
sk_STACK_OF_X509_NAME_ENTRY_pop_free(intname.s,
local_sk_X509_NAME_ENTRY_free);
nm.x->modified = 0;
*val = nm.a;
*in = p;
return ret;
err:
if (nm.x != NULL)
X509_NAME_free(nm.x);
sk_STACK_OF_X509_NAME_ENTRY_pop_free(intname.s,
local_sk_X509_NAME_ENTRY_pop_free);
ERR_raise(ERR_LIB_ASN1, ERR_R_NESTED_ASN1_ERROR);
return 0;
}
static int x509_name_ex_i2d(const ASN1_VALUE **val, unsigned char **out,
const ASN1_ITEM *it, int tag, int aclass)
{
int ret;
X509_NAME *a = (X509_NAME *)*val;
if (a->modified) {
ret = x509_name_encode(a);
if (ret < 0)
return ret;
ret = x509_name_canon(a);
if (!ret)
return -1;
}
ret = a->bytes->length;
if (out != NULL) {
memcpy(*out, a->bytes->data, ret);
*out += ret;
}
return ret;
}
static int x509_name_encode(X509_NAME *a)
{
union {
STACK_OF(STACK_OF_X509_NAME_ENTRY) *s;
const ASN1_VALUE *a;
} intname = {
NULL
};
int len;
unsigned char *p;
STACK_OF(X509_NAME_ENTRY) *entries = NULL;
X509_NAME_ENTRY *entry;
int i, set = -1;
intname.s = sk_STACK_OF_X509_NAME_ENTRY_new_null();
if (!intname.s)
goto memerr;
for (i = 0; i < sk_X509_NAME_ENTRY_num(a->entries); i++) {
entry = sk_X509_NAME_ENTRY_value(a->entries, i);
if (entry->set != set) {
entries = sk_X509_NAME_ENTRY_new_null();
if (!entries)
goto memerr;
if (!sk_STACK_OF_X509_NAME_ENTRY_push(intname.s, entries)) {
sk_X509_NAME_ENTRY_free(entries);
goto memerr;
}
set = entry->set;
}
if (!sk_X509_NAME_ENTRY_push(entries, entry))
goto memerr;
}
len = ASN1_item_ex_i2d(&intname.a, NULL,
ASN1_ITEM_rptr(X509_NAME_INTERNAL), -1, -1);
if (!BUF_MEM_grow(a->bytes, len))
goto memerr;
p = (unsigned char *)a->bytes->data;
ASN1_item_ex_i2d(&intname.a,
&p, ASN1_ITEM_rptr(X509_NAME_INTERNAL), -1, -1);
sk_STACK_OF_X509_NAME_ENTRY_pop_free(intname.s,
local_sk_X509_NAME_ENTRY_free);
a->modified = 0;
return len;
memerr:
sk_STACK_OF_X509_NAME_ENTRY_pop_free(intname.s,
local_sk_X509_NAME_ENTRY_free);
ERR_raise(ERR_LIB_ASN1, ERR_R_MALLOC_FAILURE);
return -1;
}
static int x509_name_ex_print(BIO *out, const ASN1_VALUE **pval,
int indent,
const char *fname, const ASN1_PCTX *pctx)
{
if (X509_NAME_print_ex(out, (const X509_NAME *)*pval,
indent, pctx->nm_flags) <= 0)
return 0;
return 2;
}
/*
* This function generates the canonical encoding of the Name structure. In
* it all strings are converted to UTF8, leading, trailing and multiple
* spaces collapsed, converted to lower case and the leading SEQUENCE header
* removed. In future we could also normalize the UTF8 too. By doing this
* comparison of Name structures can be rapidly performed by just using
* memcmp() of the canonical encoding. By omitting the leading SEQUENCE name
* constraints of type dirName can also be checked with a simple memcmp().
* NOTE: For empty X509_NAME (NULL-DN), canon_enclen == 0 && canon_enc == NULL
*/
static int x509_name_canon(X509_NAME *a)
{
unsigned char *p;
STACK_OF(STACK_OF_X509_NAME_ENTRY) *intname;
STACK_OF(X509_NAME_ENTRY) *entries = NULL;
X509_NAME_ENTRY *entry, *tmpentry = NULL;
int i, set = -1, ret = 0, len;
OPENSSL_free(a->canon_enc);
a->canon_enc = NULL;
/* Special case: empty X509_NAME => null encoding */
if (sk_X509_NAME_ENTRY_num(a->entries) == 0) {
a->canon_enclen = 0;
return 1;
}
intname = sk_STACK_OF_X509_NAME_ENTRY_new_null();
if (intname == NULL) {
ERR_raise(ERR_LIB_X509, ERR_R_MALLOC_FAILURE);
goto err;
}
for (i = 0; i < sk_X509_NAME_ENTRY_num(a->entries); i++) {
entry = sk_X509_NAME_ENTRY_value(a->entries, i);
if (entry->set != set) {
entries = sk_X509_NAME_ENTRY_new_null();
if (entries == NULL)
goto err;
if (!sk_STACK_OF_X509_NAME_ENTRY_push(intname, entries)) {
sk_X509_NAME_ENTRY_free(entries);
ERR_raise(ERR_LIB_X509, ERR_R_MALLOC_FAILURE);
goto err;
}
set = entry->set;
}
tmpentry = X509_NAME_ENTRY_new();
if (tmpentry == NULL) {
ERR_raise(ERR_LIB_X509, ERR_R_MALLOC_FAILURE);
goto err;
}
tmpentry->object = OBJ_dup(entry->object);
if (tmpentry->object == NULL) {
ERR_raise(ERR_LIB_X509, ERR_R_MALLOC_FAILURE);
goto err;
}
if (!asn1_string_canon(tmpentry->value, entry->value))
goto err;
if (!sk_X509_NAME_ENTRY_push(entries, tmpentry)) {
ERR_raise(ERR_LIB_X509, ERR_R_MALLOC_FAILURE);
goto err;
}
tmpentry = NULL;
}
/* Finally generate encoding */
len = i2d_name_canon(intname, NULL);
if (len < 0)
goto err;
a->canon_enclen = len;
p = OPENSSL_malloc(a->canon_enclen);
if (p == NULL) {
ERR_raise(ERR_LIB_X509, ERR_R_MALLOC_FAILURE);
goto err;
}
a->canon_enc = p;
i2d_name_canon(intname, &p);
ret = 1;
err:
X509_NAME_ENTRY_free(tmpentry);
sk_STACK_OF_X509_NAME_ENTRY_pop_free(intname,
local_sk_X509_NAME_ENTRY_pop_free);
return ret;
}
/* Bitmap of all the types of string that will be canonicalized. */
#define ASN1_MASK_CANON \
(B_ASN1_UTF8STRING | B_ASN1_BMPSTRING | B_ASN1_UNIVERSALSTRING \
| B_ASN1_PRINTABLESTRING | B_ASN1_T61STRING | B_ASN1_IA5STRING \
| B_ASN1_VISIBLESTRING)
static int asn1_string_canon(ASN1_STRING *out, const ASN1_STRING *in)
{
unsigned char *to, *from;
int len, i;
/* If type not in bitmask just copy string across */
if (!(ASN1_tag2bit(in->type) & ASN1_MASK_CANON)) {
if (!ASN1_STRING_copy(out, in))
return 0;
return 1;
}
out->type = V_ASN1_UTF8STRING;
out->length = ASN1_STRING_to_UTF8(&out->data, in);
if (out->length == -1)
return 0;
to = out->data;
from = to;
len = out->length;
/*
* Convert string in place to canonical form. Ultimately we may need to
* handle a wider range of characters but for now ignore anything with
* MSB set and rely on the ossl_isspace() to fail on bad characters without
* needing isascii or range checks as well.
*/
/* Ignore leading spaces */
while (len > 0 && ossl_isspace(*from)) {
from++;
len--;
}
to = from + len;
/* Ignore trailing spaces */
while (len > 0 && ossl_isspace(to[-1])) {
to--;
len--;
}
to = out->data;
i = 0;
while (i < len) {
/* If not ASCII set just copy across */
if (!ossl_isascii(*from)) {
*to++ = *from++;
i++;
}
/* Collapse multiple spaces */
else if (ossl_isspace(*from)) {
/* Copy one space across */
*to++ = ' ';
/*
* Ignore subsequent spaces. Note: don't need to check len here
* because we know the last character is a non-space so we can't
* overflow.
*/
do {
from++;
i++;
}
while (ossl_isspace(*from));
} else {
*to++ = ossl_tolower(*from);
from++;
i++;
}
}
out->length = to - out->data;
return 1;
}
static int i2d_name_canon(const STACK_OF(STACK_OF_X509_NAME_ENTRY) * _intname,
unsigned char **in)
{
int i, len, ltmp;
const ASN1_VALUE *v;
STACK_OF(ASN1_VALUE) *intname = (STACK_OF(ASN1_VALUE) *)_intname;
len = 0;
for (i = 0; i < sk_ASN1_VALUE_num(intname); i++) {
v = sk_ASN1_VALUE_value(intname, i);
ltmp = ASN1_item_ex_i2d(&v, in,
ASN1_ITEM_rptr(X509_NAME_ENTRIES), -1, -1);
- if (ltmp < 0)
- return ltmp;
+ if (ltmp < 0 || len > INT_MAX - ltmp)
+ return -1;
len += ltmp;
}
return len;
}
int X509_NAME_set(X509_NAME **xn, const X509_NAME *name)
{
X509_NAME *name_copy;
if (*xn == name)
return *xn != NULL;
if ((name_copy = X509_NAME_dup(name)) == NULL)
return 0;
X509_NAME_free(*xn);
*xn = name_copy;
return 1;
}
int X509_NAME_print(BIO *bp, const X509_NAME *name, int obase)
{
char *s, *c, *b;
int i;
b = X509_NAME_oneline(name, NULL, 0);
if (b == NULL)
return 0;
if (*b == '\0') {
OPENSSL_free(b);
return 1;
}
s = b + 1; /* skip the first slash */
c = s;
for (;;) {
if (((*s == '/') &&
(ossl_isupper(s[1]) && ((s[2] == '=') ||
(ossl_isupper(s[2]) && (s[3] == '='))
))) || (*s == '\0'))
{
i = s - c;
if (BIO_write(bp, c, i) != i)
goto err;
c = s + 1; /* skip following slash */
if (*s != '\0') {
if (BIO_write(bp, ", ", 2) != 2)
goto err;
}
}
if (*s == '\0')
break;
s++;
}
OPENSSL_free(b);
return 1;
err:
ERR_raise(ERR_LIB_X509, ERR_R_BUF_LIB);
OPENSSL_free(b);
return 0;
}
int X509_NAME_get0_der(const X509_NAME *nm, const unsigned char **pder,
size_t *pderlen)
{
/* Make sure encoding is valid */
if (i2d_X509_NAME(nm, NULL) <= 0)
return 0;
if (pder != NULL)
*pder = (unsigned char *)nm->bytes->data;
if (pderlen != NULL)
*pderlen = nm->bytes->length;
return 1;
}
diff --git a/crypto/openssl/doc/HOWTO/certificates.txt b/crypto/openssl/doc/HOWTO/certificates.txt
index 78ab97b41928..82ce502a1d3d 100644
--- a/crypto/openssl/doc/HOWTO/certificates.txt
+++ b/crypto/openssl/doc/HOWTO/certificates.txt
@@ -1,110 +1,110 @@
<DRAFT!>
HOWTO certificates
1. Introduction
How you handle certificates depends a great deal on what your role is.
Your role can be one or several of:
- User of some client application
- User of some server application
- Certificate authority
This file is for users who wish to get a certificate of their own.
Certificate authorities should read https://www.openssl.org/docs/apps/ca.html.
In all the cases shown below, the standard configuration file, as
compiled into openssl, will be used. You may find it in /etc/,
/usr/local/ssl/ or somewhere else. By default the file is named
openssl.cnf and is described at https://www.openssl.org/docs/apps/config.html.
You can specify a different configuration file using the
'-config {file}' argument with the commands shown below.
2. Relationship with keys
Certificates are related to public key cryptography by containing a
public key. To be useful, there must be a corresponding private key
somewhere. With OpenSSL, public keys are easily derived from private
keys, so before you create a certificate or a certificate request, you
need to create a private key.
Private keys are generated with 'openssl genrsa -out privkey.pem' if
you want an RSA private key, or if you want a DSA private key:
'openssl dsaparam -out dsaparam.pem 2048; openssl gendsa -out privkey.pem dsaparam.pem'.
The private keys created by these commands are not passphrase protected;
it might or might not be the desirable thing. Further information on how to
create private keys can be found at https://www.openssl.org/docs/HOWTO/keys.txt.
The rest of this text assumes you have a private key in the file privkey.pem.
3. Creating a certificate request
To create a certificate, you need to start with a certificate request
(or, as some certificate authorities like to put it, "certificate
signing request", since that's exactly what they do, they sign it and
give you the result back, thus making it authentic according to their
policies). A certificate request is sent to a certificate authority
to get it signed into a certificate. You can also sign the certificate
yourself if you have your own certificate authority or create a
self-signed certificate (typically for testing purpose).
The certificate request is created like this:
openssl req -new -key privkey.pem -out cert.csr
Now, cert.csr can be sent to the certificate authority, if they can
handle files in PEM format. If not, use the extra argument '-outform'
followed by the keyword for the format to use (see another HOWTO
<formats.txt?>). In some cases, -outform does not let you output the
certificate request in the right format and you will have to use one
of the various other commands that are exposed by openssl (or get
creative and use a combination of tools).
The certificate authority performs various checks (according to their
policies) and usually waits for payment from you. Once that is
complete, they send you your new certificate.
Section 5 will tell you more on how to handle the certificate you
received.
4. Creating a self-signed test certificate
You can create a self-signed certificate if you don't want to deal
with a certificate authority, or if you just want to create a test
certificate for yourself. This is similar to creating a certificate
request, but creates a certificate instead of a certificate request.
This is NOT the recommended way to create a CA certificate, see
https://www.openssl.org/docs/apps/ca.html.
openssl req -new -x509 -key privkey.pem -out cacert.pem -days 1095
5. What to do with the certificate
If you created everything yourself, or if the certificate authority
was kind enough, your certificate is a raw DER thing in PEM format.
Your key most definitely is if you have followed the examples above.
However, some (most?) certificate authorities will encode them with
things like PKCS7 or PKCS12, or something else. Depending on your
-applications, this may be perfectly OK, it all depends on what they
+applications, this may be perfectly OK. It all depends on what they
know how to decode. If not, there are a number of OpenSSL tools to
convert between some (most?) formats.
So, depending on your application, you may have to convert your
certificate and your key to various formats, most often also putting
them together into one file. The ways to do this is described in
another HOWTO <formats.txt?>, I will just mention the simplest case.
In the case of a raw DER thing in PEM format, and assuming that's all
right for your applications, simply concatenating the certificate and
the key into a new file and using that one should be enough. With
some applications, you don't even have to do that.
By now, you have your certificate and your private key and can start
using applications that depend on it.
--
Richard Levitte
diff --git a/crypto/openssl/doc/fingerprints.txt b/crypto/openssl/doc/fingerprints.txt
index 9613cbac9848..bdcad1472309 100644
--- a/crypto/openssl/doc/fingerprints.txt
+++ b/crypto/openssl/doc/fingerprints.txt
@@ -1,31 +1,28 @@
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/man1/openssl-enc.pod.in b/crypto/openssl/doc/man1/openssl-enc.pod.in
index e6d5103bd91a..a47e783e2d63 100644
--- a/crypto/openssl/doc/man1/openssl-enc.pod.in
+++ b/crypto/openssl/doc/man1/openssl-enc.pod.in
@@ -1,459 +1,468 @@
=pod
{- OpenSSL::safe::output_do_not_edit_headers(); -}
=head1 NAME
openssl-enc - symmetric cipher routines
=head1 SYNOPSIS
B<openssl> B<enc>|I<cipher>
[B<-I<cipher>>]
[B<-help>]
[B<-list>]
[B<-ciphers>]
[B<-in> I<filename>]
[B<-out> I<filename>]
[B<-pass> I<arg>]
[B<-e>]
[B<-d>]
[B<-a>]
[B<-base64>]
[B<-A>]
[B<-k> I<password>]
[B<-kfile> I<filename>]
[B<-K> I<key>]
[B<-iv> I<IV>]
[B<-S> I<salt>]
[B<-salt>]
[B<-nosalt>]
[B<-z>]
[B<-md> I<digest>]
[B<-iter> I<count>]
[B<-pbkdf2>]
[B<-p>]
[B<-P>]
[B<-bufsize> I<number>]
[B<-nopad>]
[B<-v>]
[B<-debug>]
[B<-none>]
{- $OpenSSL::safe::opt_engine_synopsis -}{- $OpenSSL::safe::opt_r_synopsis -}
{- $OpenSSL::safe::opt_provider_synopsis -}
B<openssl> I<cipher> [B<...>]
=head1 DESCRIPTION
The symmetric cipher commands allow data to be encrypted or decrypted
using various block and stream ciphers using keys based on passwords
or explicitly provided. Base64 encoding or decoding can also be performed
either by itself or in addition to the encryption or decryption.
=head1 OPTIONS
=over 4
=item B<-I<cipher>>
The cipher to use.
=item B<-help>
Print out a usage message.
=item B<-list>
List all supported ciphers.
=item B<-ciphers>
Alias of -list to display all supported ciphers.
=item B<-in> I<filename>
The input filename, standard input by default.
=item B<-out> I<filename>
The output filename, standard output by default.
=item B<-pass> I<arg>
The password source. For more information about the format of I<arg>
see L<openssl-passphrase-options(1)>.
=item B<-e>
Encrypt the input data: this is the default.
=item B<-d>
Decrypt the input data.
=item B<-a>
Base64 process the data. This means that if encryption is taking place
the data is base64 encoded after encryption. If decryption is set then
the input data is base64 decoded before being decrypted.
+When the B<-A> option not given,
+on encoding a newline is inserted after each 64 characters, and
+on decoding a newline is expected among the first 1024 bytes of input.
+
=item B<-base64>
Same as B<-a>
=item B<-A>
-If the B<-a> option is set then base64 process the data on one line.
+If the B<-a> option is set then base64 encoding produces output without any
+newline character, and base64 decoding does not require any newlines.
+Therefore it can be helpful to use the B<-A> option when decoding unknown input.
=item B<-k> I<password>
The password to derive the key from. This is for compatibility with previous
versions of OpenSSL. Superseded by the B<-pass> argument.
=item B<-kfile> I<filename>
Read the password to derive the key from the first line of I<filename>.
This is for compatibility with previous versions of OpenSSL. Superseded by
the B<-pass> argument.
=item B<-md> I<digest>
Use the specified digest to create the key from the passphrase.
The default algorithm is sha-256.
=item B<-iter> I<count>
Use a given number of iterations on the password in deriving the encryption key.
High values increase the time required to brute-force the resulting file.
This option enables the use of PBKDF2 algorithm to derive the key.
=item B<-pbkdf2>
Use PBKDF2 algorithm with a default iteration count of 10000
unless otherwise specified by the B<-iter> command line option.
=item B<-nosalt>
Don't use a salt in the key derivation routines. This option B<SHOULD NOT> be
used except for test purposes or compatibility with ancient versions of
OpenSSL.
=item B<-salt>
Use salt (randomly generated or provide with B<-S> option) when
encrypting, this is the default.
=item B<-S> I<salt>
The actual salt to use: this must be represented as a string of hex digits.
If this option is used while encrypting, the same exact value will be needed
again during decryption.
=item B<-K> I<key>
The actual key to use: this must be represented as a string comprised only
of hex digits. If only the key is specified, the IV must additionally specified
using the B<-iv> option. When both a key and a password are specified, the
key given with the B<-K> option will be used and the IV generated from the
password will be taken. It does not make much sense to specify both key
and password.
=item B<-iv> I<IV>
The actual IV to use: this must be represented as a string comprised only
of hex digits. When only the key is specified using the B<-K> option, the
IV must explicitly be defined. When a password is being specified using
one of the other options, the IV is generated from this password.
=item B<-p>
Print out the key and IV used.
=item B<-P>
Print out the key and IV used then immediately exit: don't do any encryption
or decryption.
=item B<-bufsize> I<number>
Set the buffer size for I/O.
=item B<-nopad>
Disable standard block padding.
=item B<-v>
Verbose print; display some statistics about I/O and buffer sizes.
=item B<-debug>
Debug the BIOs used for I/O.
=item B<-z>
Compress or decompress encrypted data using zlib after encryption or before
decryption. This option exists only if OpenSSL was compiled with the zlib
or zlib-dynamic option.
=item B<-none>
Use NULL cipher (no encryption or decryption of input).
{- $OpenSSL::safe::opt_r_item -}
{- $OpenSSL::safe::opt_provider_item -}
{- $OpenSSL::safe::opt_engine_item -}
=back
=head1 NOTES
The program can be called either as C<openssl I<cipher>> or
C<openssl enc -I<cipher>>. The first form doesn't work with
engine-provided ciphers, because this form is processed before the
configuration file is read and any ENGINEs loaded.
Use the L<openssl-list(1)> command to get a list of supported ciphers.
Engines which provide entirely new encryption algorithms (such as the ccgost
engine which provides gost89 algorithm) should be configured in the
configuration file. Engines specified on the command line using B<-engine>
option can only be used for hardware-assisted implementations of
ciphers which are supported by the OpenSSL core or another engine specified
in the configuration file.
When the enc command lists supported ciphers, ciphers provided by engines,
specified in the configuration files are listed too.
A password will be prompted for to derive the key and IV if necessary.
The B<-salt> option should B<ALWAYS> be used if the key is being derived
from a password unless you want compatibility with previous versions of
OpenSSL.
Without the B<-salt> option it is possible to perform efficient dictionary
attacks on the password and to attack stream cipher encrypted data. The reason
for this is that without the salt the same password always generates the same
encryption key.
When the salt is generated at random (that means when encrypting using a
passphrase without explicit salt given using B<-S> option), the first bytes
of the encrypted data are reserved to store the salt for later decrypting.
Some of the ciphers do not have large keys and others have security
implications if not used correctly. A beginner is advised to just use
a strong block cipher, such as AES, in CBC mode.
All the block ciphers normally use PKCS#5 padding, also known as standard
block padding. This allows a rudimentary integrity or password check to
be performed. However, since the chance of random data passing the test
is better than 1 in 256 it isn't a very good test.
If padding is disabled then the input data must be a multiple of the cipher
block length.
All RC2 ciphers have the same key and effective key length.
Blowfish and RC5 algorithms use a 128 bit key.
Please note that OpenSSL 3.0 changed the effect of the B<-S> option.
Any explicit salt value specified via this option is no longer prepended to the
ciphertext when encrypting, and must again be explicitly provided when decrypting.
Conversely, when the B<-S> option is used during decryption, the ciphertext
is expected to not have a prepended salt value.
When using OpenSSL 3.0 or later to decrypt data that was encrypted with an
explicit salt under OpenSSL 1.1.1 do not use the B<-S> option, the salt will
then be read from the ciphertext.
To generate ciphertext that can be decrypted with OpenSSL 1.1.1 do not use
the B<-S> option, the salt will be then be generated randomly and prepended
to the output.
=head1 SUPPORTED CIPHERS
Note that some of these ciphers can be disabled at compile time
and some are available only if an appropriate engine is configured
in the configuration file. The output when invoking this command
with the B<-list> option (that is C<openssl enc -list>) is
a list of ciphers, supported by your version of OpenSSL, including
ones provided by configured engines.
This command does not support authenticated encryption modes
like CCM and GCM, and will not support such modes in the future.
This is due to having to begin streaming output (e.g., to standard output
when B<-out> is not used) before the authentication tag could be validated.
When this command is used in a pipeline, the receiving end will not be
able to roll back upon authentication failure. The AEAD modes currently in
common use also suffer from catastrophic failure of confidentiality and/or
integrity upon reuse of key/iv/nonce, and since B<openssl enc> places the
entire burden of key/iv/nonce management upon the user, the risk of
exposing AEAD modes is too great to allow. These key/iv/nonce
management issues also affect other modes currently exposed in this command,
but the failure modes are less extreme in these cases, and the
functionality cannot be removed with a stable release branch.
For bulk encryption of data, whether using authenticated encryption
modes or other modes, L<openssl-cms(1)> is recommended, as it provides a
standard data format and performs the needed key/iv/nonce management.
base64 Base 64
bf-cbc Blowfish in CBC mode
bf Alias for bf-cbc
blowfish Alias for bf-cbc
bf-cfb Blowfish in CFB mode
bf-ecb Blowfish in ECB mode
bf-ofb Blowfish in OFB mode
cast-cbc CAST in CBC mode
cast Alias for cast-cbc
cast5-cbc CAST5 in CBC mode
cast5-cfb CAST5 in CFB mode
cast5-ecb CAST5 in ECB mode
cast5-ofb CAST5 in OFB mode
chacha20 ChaCha20 algorithm
des-cbc DES in CBC mode
des Alias for des-cbc
des-cfb DES in CFB mode
des-ofb DES in OFB mode
des-ecb DES in ECB mode
des-ede-cbc Two key triple DES EDE in CBC mode
des-ede Two key triple DES EDE in ECB mode
des-ede-cfb Two key triple DES EDE in CFB mode
des-ede-ofb Two key triple DES EDE in OFB mode
des-ede3-cbc Three key triple DES EDE in CBC mode
des-ede3 Three key triple DES EDE in ECB mode
des3 Alias for des-ede3-cbc
des-ede3-cfb Three key triple DES EDE CFB mode
des-ede3-ofb Three key triple DES EDE in OFB mode
desx DESX algorithm.
gost89 GOST 28147-89 in CFB mode (provided by ccgost engine)
gost89-cnt GOST 28147-89 in CNT mode (provided by ccgost engine)
idea-cbc IDEA algorithm in CBC mode
idea same as idea-cbc
idea-cfb IDEA in CFB mode
idea-ecb IDEA in ECB mode
idea-ofb IDEA in OFB mode
rc2-cbc 128 bit RC2 in CBC mode
rc2 Alias for rc2-cbc
rc2-cfb 128 bit RC2 in CFB mode
rc2-ecb 128 bit RC2 in ECB mode
rc2-ofb 128 bit RC2 in OFB mode
rc2-64-cbc 64 bit RC2 in CBC mode
rc2-40-cbc 40 bit RC2 in CBC mode
rc4 128 bit RC4
rc4-64 64 bit RC4
rc4-40 40 bit RC4
rc5-cbc RC5 cipher in CBC mode
rc5 Alias for rc5-cbc
rc5-cfb RC5 cipher in CFB mode
rc5-ecb RC5 cipher in ECB mode
rc5-ofb RC5 cipher in OFB mode
seed-cbc SEED cipher in CBC mode
seed Alias for seed-cbc
seed-cfb SEED cipher in CFB mode
seed-ecb SEED cipher in ECB mode
seed-ofb SEED cipher in OFB mode
sm4-cbc SM4 cipher in CBC mode
sm4 Alias for sm4-cbc
sm4-cfb SM4 cipher in CFB mode
sm4-ctr SM4 cipher in CTR mode
sm4-ecb SM4 cipher in ECB mode
sm4-ofb SM4 cipher in OFB mode
aes-[128|192|256]-cbc 128/192/256 bit AES in CBC mode
aes[128|192|256] Alias for aes-[128|192|256]-cbc
aes-[128|192|256]-cfb 128/192/256 bit AES in 128 bit CFB mode
aes-[128|192|256]-cfb1 128/192/256 bit AES in 1 bit CFB mode
aes-[128|192|256]-cfb8 128/192/256 bit AES in 8 bit CFB mode
aes-[128|192|256]-ctr 128/192/256 bit AES in CTR mode
aes-[128|192|256]-ecb 128/192/256 bit AES in ECB mode
aes-[128|192|256]-ofb 128/192/256 bit AES in OFB mode
aria-[128|192|256]-cbc 128/192/256 bit ARIA in CBC mode
aria[128|192|256] Alias for aria-[128|192|256]-cbc
aria-[128|192|256]-cfb 128/192/256 bit ARIA in 128 bit CFB mode
aria-[128|192|256]-cfb1 128/192/256 bit ARIA in 1 bit CFB mode
aria-[128|192|256]-cfb8 128/192/256 bit ARIA in 8 bit CFB mode
aria-[128|192|256]-ctr 128/192/256 bit ARIA in CTR mode
aria-[128|192|256]-ecb 128/192/256 bit ARIA in ECB mode
aria-[128|192|256]-ofb 128/192/256 bit ARIA in OFB mode
camellia-[128|192|256]-cbc 128/192/256 bit Camellia in CBC mode
camellia[128|192|256] Alias for camellia-[128|192|256]-cbc
camellia-[128|192|256]-cfb 128/192/256 bit Camellia in 128 bit CFB mode
camellia-[128|192|256]-cfb1 128/192/256 bit Camellia in 1 bit CFB mode
camellia-[128|192|256]-cfb8 128/192/256 bit Camellia in 8 bit CFB mode
camellia-[128|192|256]-ctr 128/192/256 bit Camellia in CTR mode
camellia-[128|192|256]-ecb 128/192/256 bit Camellia in ECB mode
camellia-[128|192|256]-ofb 128/192/256 bit Camellia in OFB mode
=head1 EXAMPLES
Just base64 encode a binary file:
openssl base64 -in file.bin -out file.b64
Decode the same file
openssl base64 -d -in file.b64 -out file.bin
Encrypt a file using AES-128 using a prompted password
and PBKDF2 key derivation:
openssl enc -aes128 -pbkdf2 -in file.txt -out file.aes128
Decrypt a file using a supplied password:
openssl enc -aes128 -pbkdf2 -d -in file.aes128 -out file.txt \
-pass pass:<password>
Encrypt a file then base64 encode it (so it can be sent via mail for example)
using AES-256 in CTR mode and PBKDF2 key derivation:
openssl enc -aes-256-ctr -pbkdf2 -a -in file.txt -out file.aes256
Base64 decode a file then decrypt it using a password supplied in a file:
openssl enc -aes-256-ctr -pbkdf2 -d -a -in file.aes256 -out file.txt \
-pass file:<passfile>
=head1 BUGS
The B<-A> option when used with large files doesn't work properly.
+On the other hand, when base64 decoding without the B<-A> option,
+if the first 1024 bytes of input do not include a newline character
+the first two lines of input are ignored.
The B<openssl enc> command only supports a fixed number of algorithms with
certain parameters. So if, for example, you want to use RC2 with a
76 bit key or RC4 with an 84 bit key you can't use this program.
=head1 HISTORY
The default digest was changed from MD5 to SHA256 in OpenSSL 1.1.0.
The B<-list> option was added in OpenSSL 1.1.1e.
The B<-ciphers> and B<-engine> options 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/man1/openssl-passphrase-options.pod b/crypto/openssl/doc/man1/openssl-passphrase-options.pod
index abc43fb41e6f..2260dce8a650 100644
--- a/crypto/openssl/doc/man1/openssl-passphrase-options.pod
+++ b/crypto/openssl/doc/man1/openssl-passphrase-options.pod
@@ -1,75 +1,81 @@
=pod
=head1 NAME
openssl-passphrase-options - Pass phrase options
=head1 SYNOPSIS
B<openssl>
I<command>
[ I<options> ... ]
[ I<parameters> ... ]
=head1 DESCRIPTION
Several OpenSSL commands accept password arguments, typically using B<-passin>
and B<-passout> for input and output passwords respectively. These allow
the password to be obtained from a variety of sources. Both of these
options take a single argument whose format is described below. If no
password argument is given and a password is required then the user is
prompted to enter one: this will typically be read from the current
terminal with echoing turned off.
Note that character encoding may be relevant, please see
L<passphrase-encoding(7)>.
=head1 OPTIONS
=head2 Pass Phrase Option Arguments
Pass phrase arguments can be formatted as follows.
=over 4
=item B<pass:>I<password>
The actual password is I<password>. Since the password is visible
to utilities (like 'ps' under Unix) this form should only be used
where security is not important.
=item B<env:>I<var>
Obtain the password from the environment variable I<var>. Since
the environment of other processes is visible on certain platforms
(e.g. ps under certain Unix OSes) this option should be used with caution.
=item B<file:>I<pathname>
-The first line of I<pathname> is the password. If the same I<pathname>
-argument is supplied to B<-passin> and B<-passout> arguments then the first
-line will be used for the input password and the next line for the output
-password. I<pathname> need not refer to a regular file: it could for example
-refer to a device or named pipe.
+Reads the password from the specified file I<pathname>, which can be a regular
+file, device, or named pipe. Only the first line, up to the newline character,
+is read from the stream.
+
+If the same I<pathname> argument is supplied to both B<-passin> and B<-passout>
+arguments, the first line will be used for the input password, and the next
+line will be used for the output password.
=item B<fd:>I<number>
-Read the password from the file descriptor I<number>. This can be used to
-send the data via a pipe for example.
+Reads the password from the file descriptor I<number>. This can be useful for
+sending data via a pipe, for example. The same line handling as described for
+B<file:> applies to passwords read from file descriptors.
+
+B<fd:> is not supported on Windows.
=item B<stdin>
-Read the password from standard input.
+Reads the password from standard input. The same line handling as described for
+B<file:> applies to passwords read from standard input.
=back
=head1 COPYRIGHT
-Copyright 2000-2020 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-s_client.pod.in b/crypto/openssl/doc/man1/openssl-s_client.pod.in
index 4b7b58b72d55..bd6171aa265c 100644
--- a/crypto/openssl/doc/man1/openssl-s_client.pod.in
+++ b/crypto/openssl/doc/man1/openssl-s_client.pod.in
@@ -1,920 +1,924 @@
=pod
{- OpenSSL::safe::output_do_not_edit_headers(); -}
=head1 NAME
openssl-s_client - SSL/TLS client program
=head1 SYNOPSIS
B<openssl> B<s_client>
[B<-help>]
[B<-ssl_config> I<section>]
[B<-connect> I<host:port>]
[B<-host> I<hostname>]
[B<-port> I<port>]
[B<-bind> I<host:port>]
[B<-proxy> I<host:port>]
[B<-proxy_user> I<userid>]
[B<-proxy_pass> I<arg>]
[B<-unix> I<path>]
[B<-4>]
[B<-6>]
[B<-servername> I<name>]
[B<-noservername>]
[B<-verify> I<depth>]
[B<-verify_return_error>]
[B<-verify_quiet>]
[B<-verifyCAfile> I<filename>]
[B<-verifyCApath> I<dir>]
[B<-verifyCAstore> I<uri>]
[B<-cert> I<filename>]
[B<-certform> B<DER>|B<PEM>|B<P12>]
[B<-cert_chain> I<filename>]
[B<-build_chain>]
[B<-CRL> I<filename>]
[B<-CRLform> B<DER>|B<PEM>]
[B<-crl_download>]
[B<-key> I<filename>|I<uri>]
[B<-keyform> B<DER>|B<PEM>|B<P12>|B<ENGINE>]
[B<-pass> I<arg>]
[B<-chainCAfile> I<filename>]
[B<-chainCApath> I<directory>]
[B<-chainCAstore> I<uri>]
[B<-requestCAfile> I<filename>]
[B<-dane_tlsa_domain> I<domain>]
[B<-dane_tlsa_rrdata> I<rrdata>]
[B<-dane_ee_no_namechecks>]
[B<-reconnect>]
[B<-showcerts>]
[B<-prexit>]
[B<-debug>]
[B<-trace>]
[B<-nocommands>]
[B<-security_debug>]
[B<-security_debug_verbose>]
[B<-msg>]
[B<-timeout>]
[B<-mtu> I<size>]
[B<-no_etm>]
[B<-keymatexport> I<label>]
[B<-keymatexportlen> I<len>]
[B<-msgfile> I<filename>]
[B<-nbio_test>]
[B<-state>]
[B<-nbio>]
[B<-crlf>]
[B<-ign_eof>]
[B<-no_ign_eof>]
[B<-psk_identity> I<identity>]
[B<-psk> I<key>]
[B<-psk_session> I<file>]
[B<-quiet>]
[B<-sctp>]
[B<-sctp_label_bug>]
[B<-fallback_scsv>]
[B<-async>]
[B<-maxfraglen> I<len>]
[B<-max_send_frag>]
[B<-split_send_frag>]
[B<-max_pipelines>]
[B<-read_buf>]
[B<-ignore_unexpected_eof>]
[B<-bugs>]
[B<-comp>]
[B<-no_comp>]
[B<-brief>]
[B<-legacy_server_connect>]
[B<-no_legacy_server_connect>]
[B<-allow_no_dhe_kex>]
[B<-sigalgs> I<sigalglist>]
[B<-curves> I<curvelist>]
[B<-cipher> I<cipherlist>]
[B<-ciphersuites> I<val>]
[B<-serverpref>]
[B<-starttls> I<protocol>]
[B<-name> I<hostname>]
[B<-xmpphost> I<hostname>]
[B<-name> I<hostname>]
[B<-tlsextdebug>]
[B<-no_ticket>]
[B<-sess_out> I<filename>]
[B<-serverinfo> I<types>]
[B<-sess_in> I<filename>]
[B<-serverinfo> I<types>]
[B<-status>]
[B<-alpn> I<protocols>]
[B<-nextprotoneg> I<protocols>]
[B<-ct>]
[B<-noct>]
[B<-ctlogfile>]
[B<-keylogfile> I<file>]
[B<-early_data> I<file>]
[B<-enable_pha>]
[B<-use_srtp> I<value>]
[B<-srpuser> I<value>]
[B<-srppass> I<value>]
[B<-srp_lateuser>]
[B<-srp_moregroups>]
[B<-srp_strength> I<number>]
{- $OpenSSL::safe::opt_name_synopsis -}
{- $OpenSSL::safe::opt_version_synopsis -}
{- $OpenSSL::safe::opt_x_synopsis -}
{- $OpenSSL::safe::opt_trust_synopsis -}
{- $OpenSSL::safe::opt_s_synopsis -}
{- $OpenSSL::safe::opt_r_synopsis -}
{- $OpenSSL::safe::opt_provider_synopsis -}
{- $OpenSSL::safe::opt_engine_synopsis -}[B<-ssl_client_engine> I<id>]
{- $OpenSSL::safe::opt_v_synopsis -}
[I<host>:I<port>]
=head1 DESCRIPTION
This command implements a generic SSL/TLS client which
connects to a remote host using SSL/TLS. It is a I<very> useful diagnostic
tool for SSL servers.
=head1 OPTIONS
In addition to the options below, this command also supports the
common and client only options documented
in the "Supported Command Line Commands" section of the L<SSL_CONF_cmd(3)>
manual page.
=over 4
=item B<-help>
Print out a usage message.
=item B<-ssl_config> I<section>
Use the specified section of the configuration file to configure the B<SSL_CTX> object.
=item B<-connect> I<host>:I<port>
This specifies the host and optional port to connect to. It is possible to
select the host and port using the optional target positional argument instead.
If neither this nor the target positional argument are specified then an attempt
is made to connect to the local host on port 4433.
=item B<-host> I<hostname>
Host to connect to; use B<-connect> instead.
=item B<-port> I<port>
Connect to the specified port; use B<-connect> instead.
=item B<-bind> I<host:port>
This specifies the host address and or port to bind as the source for the
connection. For Unix-domain sockets the port is ignored and the host is
used as the source socket address.
=item B<-proxy> I<host:port>
When used with the B<-connect> flag, the program uses the host and port
specified with this flag and issues an HTTP CONNECT command to connect
to the desired server.
=item B<-proxy_user> I<userid>
When used with the B<-proxy> flag, the program will attempt to authenticate
with the specified proxy using basic (base64) authentication.
NB: Basic authentication is insecure; the credentials are sent to the proxy
in easily reversible base64 encoding before any TLS/SSL session is established.
Therefore, these credentials are easily recovered by anyone able to sniff/trace
the network. Use with caution.
=item B<-proxy_pass> I<arg>
The proxy password source, used with the B<-proxy_user> flag.
For more information about the format of B<arg>
see L<openssl-passphrase-options(1)>.
=item B<-unix> I<path>
Connect over the specified Unix-domain socket.
=item B<-4>
Use IPv4 only.
=item B<-6>
Use IPv6 only.
=item B<-servername> I<name>
Set the TLS SNI (Server Name Indication) extension in the ClientHello message to
the given value.
If B<-servername> is not provided, the TLS SNI extension will be populated with
the name given to B<-connect> if it follows a DNS name format. If B<-connect> is
not provided either, the SNI is set to "localhost".
This is the default since OpenSSL 1.1.1.
Even though SNI should normally be a DNS name and not an IP address, if
B<-servername> is provided then that name will be sent, regardless of whether
it is a DNS name or not.
This option cannot be used in conjunction with B<-noservername>.
=item B<-noservername>
Suppresses sending of the SNI (Server Name Indication) extension in the
ClientHello message. Cannot be used in conjunction with the B<-servername> or
B<-dane_tlsa_domain> options.
=item B<-cert> I<filename>
The client certificate to use, if one is requested by the server.
The default is not to use a certificate.
The chain for the client certificate may be specified using B<-cert_chain>.
=item B<-certform> B<DER>|B<PEM>|B<P12>
The client certificate file format to use; unspecified by default.
See L<openssl-format-options(1)> for details.
=item B<-cert_chain>
A file or URI of untrusted certificates to use when attempting to build the
certificate chain related to the certificate specified via the B<-cert> option.
The input can be in PEM, DER, or PKCS#12 format.
=item B<-build_chain>
Specify whether the application should build the client certificate chain to be
provided to the server.
=item B<-CRL> I<filename>
CRL file to use to check the server's certificate.
=item B<-CRLform> B<DER>|B<PEM>
The CRL file format; unspecified by default.
See L<openssl-format-options(1)> for details.
=item B<-crl_download>
Download CRL from distribution points in the certificate.
=item B<-key> I<filename>|I<uri>
The client private key to use.
If not specified then the certificate file will be used to read also the key.
=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<-pass> I<arg>
the private key and certificate file password source.
For more information about the format of I<arg>
see L<openssl-passphrase-options(1)>.
=item B<-verify> I<depth>
The verify depth to use. This specifies the maximum length of the
server certificate chain and turns on server certificate verification.
Currently the verify operation continues after errors so all the problems
with a certificate chain can be seen. As a side effect the connection
will never fail due to a server certificate verify failure.
=item B<-verify_return_error>
Return verification errors instead of continuing. This will typically
abort the handshake with a fatal error.
=item B<-verify_quiet>
Limit verify output to only errors.
=item B<-verifyCAfile> I<filename>
A file in PEM format containing trusted certificates to use
for verifying the server's certificate.
=item B<-verifyCApath> I<dir>
A directory containing trusted certificates to use
for verifying the server's certificate.
This directory must be in "hash format",
see L<openssl-verify(1)> for more information.
=item B<-verifyCAstore> I<uri>
The URI of a store containing trusted certificates to use
for verifying the server's certificate.
=item B<-chainCAfile> I<file>
A file in PEM format containing trusted certificates to use
when attempting to build the client certificate chain.
=item B<-chainCApath> I<directory>
A directory containing trusted certificates to use
for building the client certificate chain provided to the server.
This directory must be in "hash format",
see L<openssl-verify(1)> for more information.
=item B<-chainCAstore> I<uri>
The URI of a store containing trusted certificates to use
when attempting to build the client certificate chain.
The URI may indicate a single certificate, as well as a collection of them.
With URIs in the C<file:> scheme, this acts as B<-chainCAfile> or
B<-chainCApath>, depending on if the URI indicates a directory or a
single file.
See L<ossl_store-file(7)> for more information on the C<file:> scheme.
=item B<-requestCAfile> I<file>
A file containing a list of certificates whose subject names will be sent
to the server in the B<certificate_authorities> extension. Only supported
for TLS 1.3
=item B<-dane_tlsa_domain> I<domain>
Enable RFC6698/RFC7671 DANE TLSA authentication and specify the
TLSA base domain which becomes the default SNI hint and the primary
reference identifier for hostname checks. This must be used in
combination with at least one instance of the B<-dane_tlsa_rrdata>
option below.
When DANE authentication succeeds, the diagnostic output will include
the lowest (closest to 0) depth at which a TLSA record authenticated
a chain certificate. When that TLSA record is a "2 1 0" trust
anchor public key that signed (rather than matched) the top-most
certificate of the chain, the result is reported as "TA public key
verified". Otherwise, either the TLSA record "matched TA certificate"
at a positive depth or else "matched EE certificate" at depth 0.
=item B<-dane_tlsa_rrdata> I<rrdata>
Use one or more times to specify the RRDATA fields of the DANE TLSA
RRset associated with the target service. The I<rrdata> value is
specified in "presentation form", that is four whitespace separated
fields that specify the usage, selector, matching type and associated
data, with the last of these encoded in hexadecimal. Optional
whitespace is ignored in the associated data field. For example:
$ openssl s_client -brief -starttls smtp \
-connect smtp.example.com:25 \
-dane_tlsa_domain smtp.example.com \
-dane_tlsa_rrdata "2 1 1
B111DD8A1C2091A89BD4FD60C57F0716CCE50FEEFF8137CDBEE0326E 02CF362B" \
-dane_tlsa_rrdata "2 1 1
60B87575447DCBA2A36B7D11AC09FB24A9DB406FEE12D2CC90180517 616E8A18"
...
Verification: OK
Verified peername: smtp.example.com
DANE TLSA 2 1 1 ...ee12d2cc90180517616e8a18 matched TA certificate at depth 1
...
=item B<-dane_ee_no_namechecks>
This disables server name checks when authenticating via DANE-EE(3) TLSA
records.
For some applications, primarily web browsers, it is not safe to disable name
checks due to "unknown key share" attacks, in which a malicious server can
convince a client that a connection to a victim server is instead a secure
connection to the malicious server.
The malicious server may then be able to violate cross-origin scripting
restrictions.
Thus, despite the text of RFC7671, name checks are by default enabled for
DANE-EE(3) TLSA records, and can be disabled in applications where it is safe
to do so.
In particular, SMTP and XMPP clients should set this option as SRV and MX
records already make it possible for a remote domain to redirect client
connections to any server of its choice, and in any case SMTP and XMPP clients
do not execute scripts downloaded from remote servers.
=item B<-reconnect>
Reconnects to the same server 5 times using the same session ID, this can
be used as a test that session caching is working.
=item B<-showcerts>
Displays the server certificate list as sent by the server: it only consists of
certificates the server has sent (in the order the server has sent them). It is
B<not> a verified chain.
=item B<-prexit>
Print session information when the program exits. This will always attempt
to print out information even if the connection fails. Normally information
will only be printed out once if the connection succeeds. This option is useful
because the cipher in use may be renegotiated or the connection may fail
because a client certificate is required or is requested only after an
attempt is made to access a certain URL. Note: the output produced by this
option is not always accurate because a connection might never have been
established.
=item B<-state>
Prints out the SSL session states.
=item B<-debug>
Print extensive debugging information including a hex dump of all traffic.
=item B<-nocommands>
Do not use interactive command letters.
=item B<-security_debug>
Enable security debug messages.
=item B<-security_debug_verbose>
Output more security debug output.
=item B<-msg>
Show protocol messages.
=item B<-timeout>
Enable send/receive timeout on DTLS connections.
=item B<-mtu> I<size>
Set MTU of the link layer to the specified size.
=item B<-no_etm>
Disable Encrypt-then-MAC negotiation.
=item B<-keymatexport> I<label>
Export keying material using the specified label.
=item B<-keymatexportlen> I<len>
Export the specified number of bytes of keying material; default is 20.
Show all protocol messages with hex dump.
=item B<-trace>
Show verbose trace output of protocol messages.
=item B<-msgfile> I<filename>
File to send output of B<-msg> or B<-trace> to, default standard output.
=item B<-nbio_test>
Tests nonblocking I/O
=item B<-nbio>
Turns on nonblocking I/O
=item B<-crlf>
This option translated a line feed from the terminal into CR+LF as required
by some servers.
=item B<-ign_eof>
Inhibit shutting down the connection when end of file is reached in the
input.
=item B<-quiet>
Inhibit printing of session and certificate information. This implicitly
turns on B<-ign_eof> as well.
=item B<-no_ign_eof>
Shut down the connection when end of file is reached in the input.
Can be used to override the implicit B<-ign_eof> after B<-quiet>.
=item B<-psk_identity> I<identity>
Use the PSK identity I<identity> when using a PSK cipher suite.
The default value is "Client_identity" (without the quotes).
=item B<-psk> I<key>
Use the PSK key I<key> when using a PSK cipher suite. The key is
given as a hexadecimal number without leading 0x, for example -psk
1a2b3c4d.
This option must be provided in order to use a PSK cipher.
=item B<-psk_session> I<file>
Use the pem encoded SSL_SESSION data stored in I<file> as the basis of a PSK.
Note that this will only work if TLSv1.3 is negotiated.
=item B<-sctp>
Use SCTP for the transport protocol instead of UDP in DTLS. Must be used in
conjunction with B<-dtls>, B<-dtls1> or B<-dtls1_2>. This option is only
available where OpenSSL has support for SCTP enabled.
=item B<-sctp_label_bug>
Use the incorrect behaviour of older OpenSSL implementations when computing
endpoint-pair shared secrets for DTLS/SCTP. This allows communication with
older broken implementations but breaks interoperability with correct
implementations. Must be used in conjunction with B<-sctp>. This option is only
available where OpenSSL has support for SCTP enabled.
=item B<-fallback_scsv>
Send TLS_FALLBACK_SCSV in the ClientHello.
=item B<-async>
Switch on asynchronous mode. Cryptographic operations will be performed
asynchronously. This will only have an effect if an asynchronous capable engine
is also used via the B<-engine> option. For test purposes the dummy async engine
(dasync) can be used (if available).
=item B<-maxfraglen> I<len>
Enable Maximum Fragment Length Negotiation; allowed values are
C<512>, C<1024>, C<2048>, and C<4096>.
=item B<-max_send_frag> I<int>
The maximum size of data fragment to send.
See L<SSL_CTX_set_max_send_fragment(3)> for further information.
=item B<-split_send_frag> I<int>
The size used to split data for encrypt pipelines. If more data is written in
one go than this value then it will be split into multiple pipelines, up to the
maximum number of pipelines defined by max_pipelines. This only has an effect if
a suitable cipher suite has been negotiated, an engine that supports pipelining
has been loaded, and max_pipelines is greater than 1. See
L<SSL_CTX_set_split_send_fragment(3)> for further information.
=item B<-max_pipelines> I<int>
The maximum number of encrypt/decrypt pipelines to be used. This will only have
an effect if an engine has been loaded that supports pipelining (e.g. the dasync
engine) and a suitable cipher suite has been negotiated. The default value is 1.
See L<SSL_CTX_set_max_pipelines(3)> for further information.
=item B<-read_buf> I<int>
The default read buffer size to be used for connections. This will only have an
effect if the buffer size is larger than the size that would otherwise be used
and pipelining is in use (see L<SSL_CTX_set_default_read_buffer_len(3)> for
further information).
=item B<-ignore_unexpected_eof>
Some TLS implementations do not send the mandatory close_notify alert on
shutdown. If the application tries to wait for the close_notify alert but the
peer closes the connection without sending it, an error is generated. When this
option is enabled the peer does not need to send the close_notify alert and a
closed connection will be treated as if the close_notify alert was received.
For more information on shutting down a connection, see L<SSL_shutdown(3)>.
=item B<-bugs>
There are several known bugs in SSL and TLS implementations. Adding this
option enables various workarounds.
=item B<-comp>
Enables support for SSL/TLS compression.
This option was introduced in OpenSSL 1.1.0.
TLS compression is not recommended and is off by default as of
OpenSSL 1.1.0.
=item B<-no_comp>
Disables support for SSL/TLS compression.
TLS compression is not recommended and is off by default as of
OpenSSL 1.1.0.
=item B<-brief>
Only provide a brief summary of connection parameters instead of the
normal verbose output.
=item B<-sigalgs> I<sigalglist>
Specifies the list of signature algorithms that are sent by the client.
The server selects one entry in the list based on its preferences.
For example strings, see L<SSL_CTX_set1_sigalgs(3)>
=item B<-curves> I<curvelist>
Specifies the list of supported curves to be sent by the client. The curve is
-ultimately selected by the server. For a list of all curves, use:
+ultimately selected by the server.
+
+The list of all supported groups includes named EC parameters as well as X25519
+and X448 or FFDHE groups, and may also include groups implemented in 3rd-party
+providers. For a list of named EC parameters, use:
$ openssl ecparam -list_curves
=item B<-cipher> I<cipherlist>
This allows the TLSv1.2 and below cipher list sent by the client to be modified.
This list will be combined with any TLSv1.3 ciphersuites that have been
configured. Although the server determines which ciphersuite is used it should
take the first supported cipher in the list sent by the client. See
L<openssl-ciphers(1)> for more information.
=item B<-ciphersuites> I<val>
This allows the TLSv1.3 ciphersuites sent by the client to be modified. This
list will be combined with any TLSv1.2 and below ciphersuites that have been
configured. Although the server determines which cipher suite is used it should
take the first supported cipher in the list sent by the client. See
L<openssl-ciphers(1)> for more information. The format for this list is a simple
colon (":") separated list of TLSv1.3 ciphersuite names.
=item B<-starttls> I<protocol>
Send the protocol-specific message(s) to switch to TLS for communication.
I<protocol> is a keyword for the intended protocol. Currently, the only
supported keywords are "smtp", "pop3", "imap", "ftp", "xmpp", "xmpp-server",
"irc", "postgres", "mysql", "lmtp", "nntp", "sieve" and "ldap".
=item B<-xmpphost> I<hostname>
This option, when used with "-starttls xmpp" or "-starttls xmpp-server",
specifies the host for the "to" attribute of the stream element.
If this option is not specified, then the host specified with "-connect"
will be used.
This option is an alias of the B<-name> option for "xmpp" and "xmpp-server".
=item B<-name> I<hostname>
This option is used to specify hostname information for various protocols
used with B<-starttls> option. Currently only "xmpp", "xmpp-server",
"smtp" and "lmtp" can utilize this B<-name> option.
If this option is used with "-starttls xmpp" or "-starttls xmpp-server",
if specifies the host for the "to" attribute of the stream element. If this
option is not specified, then the host specified with "-connect" will be used.
If this option is used with "-starttls lmtp" or "-starttls smtp", it specifies
the name to use in the "LMTP LHLO" or "SMTP EHLO" message, respectively. If
this option is not specified, then "mail.example.com" will be used.
=item B<-tlsextdebug>
Print out a hex dump of any TLS extensions received from the server.
=item B<-no_ticket>
Disable RFC4507bis session ticket support.
=item B<-sess_out> I<filename>
Output SSL session to I<filename>.
=item B<-sess_in> I<filename>
Load SSL session from I<filename>. The client will attempt to resume a
connection from this session.
=item B<-serverinfo> I<types>
A list of comma-separated TLS Extension Types (numbers between 0 and
65535). Each type will be sent as an empty ClientHello TLS Extension.
The server's response (if any) will be encoded and displayed as a PEM
file.
=item B<-status>
Sends a certificate status request to the server (OCSP stapling). The server
response (if any) is printed out.
=item B<-alpn> I<protocols>, B<-nextprotoneg> I<protocols>
These flags enable the Enable the Application-Layer Protocol Negotiation
or Next Protocol Negotiation (NPN) extension, respectively. ALPN is the
IETF standard and replaces NPN.
The I<protocols> list is a comma-separated list of protocol names that
the client should advertise support for. The list should contain the most
desirable protocols first. Protocol names are printable ASCII strings,
for example "http/1.1" or "spdy/3".
An empty list of protocols is treated specially and will cause the
client to advertise support for the TLS extension but disconnect just
after receiving ServerHello with a list of server supported protocols.
The flag B<-nextprotoneg> cannot be specified if B<-tls1_3> is used.
=item B<-ct>, B<-noct>
Use one of these two options to control whether Certificate Transparency (CT)
is enabled (B<-ct>) or disabled (B<-noct>).
If CT is enabled, signed certificate timestamps (SCTs) will be requested from
the server and reported at handshake completion.
Enabling CT also enables OCSP stapling, as this is one possible delivery method
for SCTs.
=item B<-ctlogfile>
A file containing a list of known Certificate Transparency logs. See
L<SSL_CTX_set_ctlog_list_file(3)> for the expected file format.
=item B<-keylogfile> I<file>
Appends TLS secrets to the specified keylog file such that external programs
(like Wireshark) can decrypt TLS connections.
=item B<-early_data> I<file>
Reads the contents of the specified file and attempts to send it as early data
to the server. This will only work with resumed sessions that support early
data and when the server accepts the early data.
=item B<-enable_pha>
For TLSv1.3 only, send the Post-Handshake Authentication extension. This will
happen whether or not a certificate has been provided via B<-cert>.
=item B<-use_srtp> I<value>
Offer SRTP key management, where B<value> is a colon-separated profile list.
=item B<-srpuser> I<value>
Set the SRP username to the specified value. This option is deprecated.
=item B<-srppass> I<value>
Set the SRP password to the specified value. This option is deprecated.
=item B<-srp_lateuser>
SRP username for the second ClientHello message. This option is deprecated.
=item B<-srp_moregroups> This option is deprecated.
Tolerate other than the known B<g> and B<N> values.
=item B<-srp_strength> I<number>
Set the minimal acceptable length, in bits, for B<N>. This option is
deprecated.
{- $OpenSSL::safe::opt_version_item -}
{- $OpenSSL::safe::opt_name_item -}
{- $OpenSSL::safe::opt_x_item -}
{- $OpenSSL::safe::opt_trust_item -}
{- $OpenSSL::safe::opt_s_item -}
{- $OpenSSL::safe::opt_r_item -}
{- $OpenSSL::safe::opt_provider_item -}
{- $OpenSSL::safe::opt_engine_item -}
{- output_off() if $disabled{"deprecated-3.0"}; "" -}
=item B<-ssl_client_engine> I<id>
Specify engine to be used for client certificate operations.
{- output_on() if $disabled{"deprecated-3.0"}; "" -}
{- $OpenSSL::safe::opt_v_item -}
Verification errors are displayed, for debugging, but the command will
proceed unless the B<-verify_return_error> option is used.
=item I<host>:I<port>
Rather than providing B<-connect>, the target hostname and optional port may
be provided as a single positional argument after all options. If neither this
nor B<-connect> are provided, falls back to attempting to connect to
I<localhost> on port I<4433>.
=back
=head1 CONNECTED COMMANDS
If a connection is established with an SSL server then any data received
from the server is displayed and any key presses will be sent to the
server. If end of file is reached then the connection will be closed down. When
used interactively (which means neither B<-quiet> nor B<-ign_eof> have been
given), then certain commands are also recognized which perform special
operations. These commands are a letter which must appear at the start of a
line. They are listed below.
=over 4
=item B<Q>
End the current SSL connection and exit.
=item B<R>
Renegotiate the SSL session (TLSv1.2 and below only).
=item B<k>
Send a key update message to the server (TLSv1.3 only)
=item B<K>
Send a key update message to the server and request one back (TLSv1.3 only)
=back
=head1 NOTES
This command can be used to debug SSL servers. To connect to an SSL HTTP
server the command:
openssl s_client -connect servername:443
would typically be used (https uses port 443). If the connection succeeds
then an HTTP command can be given such as "GET /" to retrieve a web page.
If the handshake fails then there are several possible causes, if it is
nothing obvious like no client certificate then the B<-bugs>,
B<-ssl3>, B<-tls1>, B<-no_ssl3>, B<-no_tls1> options can be tried
in case it is a buggy server. In particular you should play with these
options B<before> submitting a bug report to an OpenSSL mailing list.
A frequent problem when attempting to get client certificates working
is that a web client complains it has no certificates or gives an empty
list to choose from. This is normally because the server is not sending
the clients certificate authority in its "acceptable CA list" when it
requests a certificate. By using this command, the CA list can be viewed
and checked. However, some servers only request client authentication
after a specific URL is requested. To obtain the list in this case it
is necessary to use the B<-prexit> option and send an HTTP request
for an appropriate page.
If a certificate is specified on the command line using the B<-cert>
option it will not be used unless the server specifically requests
a client certificate. Therefore, merely including a client certificate
on the command line is no guarantee that the certificate works.
If there are problems verifying a server certificate then the
B<-showcerts> option can be used to show all the certificates sent by the
server.
This command is a test tool and is designed to continue the
handshake after any certificate verification errors. As a result it will
accept any certificate chain (trusted or not) sent by the peer. Non-test
applications should B<not> do this as it makes them vulnerable to a MITM
attack. This behaviour can be changed by with the B<-verify_return_error>
option: any verify errors are then returned aborting the handshake.
The B<-bind> option may be useful if the server or a firewall requires
connections to come from some particular address and or port.
=head1 BUGS
Because this program has a lot of options and also because some of the
techniques used are rather old, the C source for this command is rather
hard to read and not a model of how things should be done.
A typical SSL client program would be much simpler.
The B<-prexit> option is a bit of a hack. We should really report
information whenever a session is renegotiated.
=head1 SEE ALSO
L<openssl(1)>,
L<openssl-sess_id(1)>,
L<openssl-s_server(1)>,
L<openssl-ciphers(1)>,
L<SSL_CONF_cmd(3)>,
L<SSL_CTX_set_max_send_fragment(3)>,
L<SSL_CTX_set_split_send_fragment(3)>,
L<SSL_CTX_set_max_pipelines(3)>,
L<ossl_store-file(7)>
=head1 HISTORY
The B<-no_alt_chains> option was added in OpenSSL 1.1.0.
The B<-name> option was added in OpenSSL 1.1.1.
The B<-certform> option has become obsolete in OpenSSL 3.0.0 and has no effect.
The B<-engine> option was 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/man1/openssl-s_server.pod.in b/crypto/openssl/doc/man1/openssl-s_server.pod.in
index 319f1e342b48..99a252a82254 100644
--- a/crypto/openssl/doc/man1/openssl-s_server.pod.in
+++ b/crypto/openssl/doc/man1/openssl-s_server.pod.in
@@ -1,940 +1,943 @@
=pod
{- OpenSSL::safe::output_do_not_edit_headers(); -}
=head1 NAME
openssl-s_server - SSL/TLS server program
=head1 SYNOPSIS
B<openssl> B<s_server>
[B<-help>]
[B<-port> I<+int>]
[B<-accept> I<val>]
[B<-unix> I<val>]
[B<-4>]
[B<-6>]
[B<-unlink>]
[B<-context> I<val>]
[B<-verify> I<int>]
[B<-Verify> I<int>]
[B<-cert> I<infile>]
[B<-cert2> I<infile>]
[B<-certform> B<DER>|B<PEM>|B<P12>]
[B<-cert_chain> I<infile>]
[B<-build_chain>]
[B<-serverinfo> I<val>]
[B<-key> I<filename>|I<uri>]
[B<-key2> I<filename>|I<uri>]
[B<-keyform> B<DER>|B<PEM>|B<P12>|B<ENGINE>]
[B<-pass> I<val>]
[B<-dcert> I<infile>]
[B<-dcertform> B<DER>|B<PEM>|B<P12>]
[B<-dcert_chain> I<infile>]
[B<-dkey> I<filename>|I<uri>]
[B<-dkeyform> B<DER>|B<PEM>|B<P12>|B<ENGINE>]
[B<-dpass> I<val>]
[B<-nbio_test>]
[B<-crlf>]
[B<-debug>]
[B<-msg>]
[B<-msgfile> I<outfile>]
[B<-state>]
[B<-nocert>]
[B<-quiet>]
[B<-no_resume_ephemeral>]
[B<-www>]
[B<-WWW>]
[B<-http_server_binmode>]
[B<-no_ca_names>]
[B<-ignore_unexpected_eof>]
[B<-servername>]
[B<-servername_fatal>]
[B<-tlsextdebug>]
[B<-HTTP>]
[B<-id_prefix> I<val>]
[B<-keymatexport> I<val>]
[B<-keymatexportlen> I<+int>]
[B<-CRL> I<infile>]
[B<-CRLform> B<DER>|B<PEM>]
[B<-crl_download>]
[B<-chainCAfile> I<infile>]
[B<-chainCApath> I<dir>]
[B<-chainCAstore> I<uri>]
[B<-verifyCAfile> I<infile>]
[B<-verifyCApath> I<dir>]
[B<-verifyCAstore> I<uri>]
[B<-no_cache>]
[B<-ext_cache>]
[B<-verify_return_error>]
[B<-verify_quiet>]
[B<-ign_eof>]
[B<-no_ign_eof>]
[B<-no_etm>]
[B<-status>]
[B<-status_verbose>]
[B<-status_timeout> I<int>]
[B<-proxy> I<[http[s]://][userinfo@]host[:port][/path]>]
[B<-no_proxy> I<addresses>]
[B<-status_url> I<val>]
[B<-status_file> I<infile>]
[B<-ssl_config> I<val>]
[B<-trace>]
[B<-security_debug>]
[B<-security_debug_verbose>]
[B<-brief>]
[B<-rev>]
[B<-async>]
[B<-max_send_frag> I<+int>]
[B<-split_send_frag> I<+int>]
[B<-max_pipelines> I<+int>]
[B<-naccept> I<+int>]
[B<-read_buf> I<+int>]
[B<-bugs>]
[B<-no_comp>]
[B<-comp>]
[B<-no_ticket>]
[B<-serverpref>]
[B<-legacy_renegotiation>]
[B<-no_renegotiation>]
[B<-no_resumption_on_reneg>]
[B<-allow_no_dhe_kex>]
[B<-prioritize_chacha>]
[B<-strict>]
[B<-sigalgs> I<val>]
[B<-client_sigalgs> I<val>]
[B<-groups> I<val>]
[B<-curves> I<val>]
[B<-named_curve> I<val>]
[B<-cipher> I<val>]
[B<-ciphersuites> I<val>]
[B<-dhparam> I<infile>]
[B<-record_padding> I<val>]
[B<-debug_broken_protocol>]
[B<-nbio>]
[B<-psk_identity> I<val>]
[B<-psk_hint> I<val>]
[B<-psk> I<val>]
[B<-psk_session> I<file>]
[B<-srpvfile> I<infile>]
[B<-srpuserseed> I<val>]
[B<-timeout>]
[B<-mtu> I<+int>]
[B<-listen>]
[B<-sctp>]
[B<-sctp_label_bug>]
[B<-use_srtp> I<val>]
[B<-no_dhe>]
[B<-nextprotoneg> I<val>]
[B<-alpn> I<val>]
[B<-sendfile>]
[B<-keylogfile> I<outfile>]
[B<-recv_max_early_data> I<int>]
[B<-max_early_data> I<int>]
[B<-early_data>]
[B<-stateless>]
[B<-anti_replay>]
[B<-no_anti_replay>]
[B<-num_tickets>]
{- $OpenSSL::safe::opt_name_synopsis -}
{- $OpenSSL::safe::opt_version_synopsis -}
{- $OpenSSL::safe::opt_v_synopsis -}
{- $OpenSSL::safe::opt_s_synopsis -}
{- $OpenSSL::safe::opt_x_synopsis -}
{- $OpenSSL::safe::opt_trust_synopsis -}
{- $OpenSSL::safe::opt_r_synopsis -}
{- $OpenSSL::safe::opt_engine_synopsis -}{- $OpenSSL::safe::opt_provider_synopsis -}
=head1 DESCRIPTION
This command implements a generic SSL/TLS server which
listens for connections on a given port using SSL/TLS.
=head1 OPTIONS
In addition to the options below, this command also supports
the common and server only options documented
L<SSL_CONF_cmd(3)/Supported Command Line Commands>
=over 4
=item B<-help>
Print out a usage message.
=item B<-port> I<+int>
The TCP port to listen on for connections. If not specified 4433 is used.
=item B<-accept> I<val>
The optional TCP host and port to listen on for connections. If not specified, *:4433 is used.
=item B<-unix> I<val>
Unix domain socket to accept on.
=item B<-4>
Use IPv4 only.
=item B<-6>
Use IPv6 only.
=item B<-unlink>
For -unix, unlink any existing socket first.
=item B<-context> I<val>
Sets the SSL context id. It can be given any string value. If this option
is not present a default value will be used.
=item B<-verify> I<int>, B<-Verify> I<int>
The verify depth to use. This specifies the maximum length of the
client certificate chain and makes the server request a certificate from
the client. With the B<-verify> option a certificate is requested but the
client does not have to send one, with the B<-Verify> option the client
must supply a certificate or an error occurs.
If the cipher suite cannot request a client certificate (for example an
anonymous cipher suite or PSK) this option has no effect.
=item B<-cert> I<infile>
The certificate to use, most servers cipher suites require the use of a
certificate and some require a certificate with a certain public key type:
for example the DSS cipher suites require a certificate containing a DSS
(DSA) key. If not specified then the filename F<server.pem> will be used.
=item B<-cert2> I<infile>
The certificate file to use for servername; default is C<server2.pem>.
=item B<-certform> B<DER>|B<PEM>|B<P12>
The server certificate file format; unspecified by default.
See L<openssl-format-options(1)> for details.
=item B<-cert_chain>
A file or URI of untrusted certificates to use when attempting to build the
certificate chain related to the certificate specified via the B<-cert> option.
The input can be in PEM, DER, or PKCS#12 format.
=item B<-build_chain>
Specify whether the application should build the server certificate chain to be
provided to the client.
=item B<-serverinfo> I<val>
A file containing one or more blocks of PEM data. Each PEM block
must encode a TLS ServerHello extension (2 bytes type, 2 bytes length,
followed by "length" bytes of extension data). If the client sends
an empty TLS ClientHello extension matching the type, the corresponding
ServerHello extension will be returned.
=item B<-key> I<filename>|I<uri>
The private key to use. If not specified then the certificate file will
be used.
=item B<-key2> I<filename>|I<uri>
The private Key file to use for servername if not given via B<-cert2>.
=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<-pass> I<val>
The private key and certificate file password source.
For more information about the format of I<val>,
see L<openssl-passphrase-options(1)>.
=item B<-dcert> I<infile>, B<-dkey> I<filename>|I<uri>
Specify an additional certificate and private key, these behave in the
same manner as the B<-cert> and B<-key> options except there is no default
if they are not specified (no additional certificate and key is used). As
noted above some cipher suites require a certificate containing a key of
a certain type. Some cipher suites need a certificate carrying an RSA key
and some a DSS (DSA) key. By using RSA and DSS certificates and keys
a server can support clients which only support RSA or DSS cipher suites
by using an appropriate certificate.
=item B<-dcert_chain>
A file or URI of untrusted certificates to use when attempting to build the
server certificate chain when a certificate specified via the B<-dcert> option
is in use.
The input can be in PEM, DER, or PKCS#12 format.
=item B<-dcertform> B<DER>|B<PEM>|B<P12>
The format of the additional certificate file; unspecified by default.
See L<openssl-format-options(1)> for details.
=item B<-dkeyform> B<DER>|B<PEM>|B<P12>|B<ENGINE>
The format of the additional private key; unspecified by default.
See L<openssl-format-options(1)> for details.
=item B<-dpass> I<val>
The passphrase for the additional private key and certificate.
For more information about the format of I<val>,
see L<openssl-passphrase-options(1)>.
=item B<-nbio_test>
Tests non blocking I/O.
=item B<-crlf>
This option translated a line feed from the terminal into CR+LF.
=item B<-debug>
Print extensive debugging information including a hex dump of all traffic.
=item B<-security_debug>
Print output from SSL/TLS security framework.
=item B<-security_debug_verbose>
Print more output from SSL/TLS security framework
=item B<-msg>
Show all protocol messages with hex dump.
=item B<-msgfile> I<outfile>
File to send output of B<-msg> or B<-trace> to, default standard output.
=item B<-state>
Prints the SSL session states.
=item B<-CRL> I<infile>
The CRL file to use.
=item B<-CRLform> B<DER>|B<PEM>
The CRL file format; unspecified by default.
See L<openssl-format-options(1)> for details.
=item B<-crl_download>
Download CRLs from distribution points given in CDP extensions of certificates
=item B<-verifyCAfile> I<filename>
A file in PEM format CA containing trusted certificates to use
for verifying client certificates.
=item B<-verifyCApath> I<dir>
A directory containing trusted certificates to use
for verifying client certificates.
This directory must be in "hash format",
see L<openssl-verify(1)> for more information.
=item B<-verifyCAstore> I<uri>
The URI of a store containing trusted certificates to use
for verifying client certificates.
=item B<-chainCAfile> I<file>
A file in PEM format containing trusted certificates to use
when attempting to build the server certificate chain.
=item B<-chainCApath> I<dir>
A directory containing trusted certificates to use
for building the server certificate chain provided to the client.
This directory must be in "hash format",
see L<openssl-verify(1)> for more information.
=item B<-chainCAstore> I<uri>
The URI of a store containing trusted certificates to use
for building the server certificate chain provided to the client.
The URI may indicate a single certificate, as well as a collection of them.
With URIs in the C<file:> scheme, this acts as B<-chainCAfile> or
B<-chainCApath>, depending on if the URI indicates a directory or a
single file.
See L<ossl_store-file(7)> for more information on the C<file:> scheme.
=item B<-nocert>
If this option is set then no certificate is used. This restricts the
cipher suites available to the anonymous ones (currently just anonymous
DH).
=item B<-quiet>
Inhibit printing of session and certificate information.
=item B<-no_resume_ephemeral>
Disable caching and tickets if ephemeral (EC)DH is used.
=item B<-tlsextdebug>
Print a hex dump of any TLS extensions received from the server.
=item B<-www>
Sends a status message back to the client when it connects. This includes
information about the ciphers used and various session parameters.
The output is in HTML format so this option can be used with a web browser.
The special URL C</renegcert> turns on client cert validation, and C</reneg>
tells the server to request renegotiation.
The B<-early_data> option cannot be used with this option.
=item B<-WWW>, B<-HTTP>
Emulates a simple web server. Pages will be resolved relative to the
current directory, for example if the URL C<https://myhost/page.html> is
requested the file F<./page.html> will be sent.
If the B<-HTTP> flag is used, the files are sent directly, and should contain
any HTTP response headers (including status response line).
If the B<-WWW> option is used,
the response headers are generated by the server, and the file extension is
examined to determine the B<Content-Type> header.
Extensions of C<html>, C<htm>, and C<php> are C<text/html> and all others are
C<text/plain>.
In addition, the special URL C</stats> will return status
information like the B<-www> option.
Neither of these options can be used in conjunction with B<-early_data>.
=item B<-http_server_binmode>
When acting as web-server (using option B<-WWW> or B<-HTTP>) open files requested
by the client in binary mode.
=item B<-no_ca_names>
Disable TLS Extension CA Names. You may want to disable it for security reasons
or for compatibility with some Windows TLS implementations crashing when this
extension is larger than 1024 bytes.
=item B<-ignore_unexpected_eof>
Some TLS implementations do not send the mandatory close_notify alert on
shutdown. If the application tries to wait for the close_notify alert but the
peer closes the connection without sending it, an error is generated. When this
option is enabled the peer does not need to send the close_notify alert and a
closed connection will be treated as if the close_notify alert was received.
For more information on shutting down a connection, see L<SSL_shutdown(3)>.
=item B<-servername>
Servername for HostName TLS extension.
=item B<-servername_fatal>
On servername mismatch send fatal alert (default: warning alert).
=item B<-id_prefix> I<val>
Generate SSL/TLS session IDs prefixed by I<val>. This is mostly useful
for testing any SSL/TLS code (e.g. proxies) that wish to deal with multiple
servers, when each of which might be generating a unique range of session
IDs (e.g. with a certain prefix).
=item B<-keymatexport>
Export keying material using label.
=item B<-keymatexportlen>
Export the given number of bytes of keying material; default 20.
=item B<-no_cache>
Disable session cache.
=item B<-ext_cache>.
Disable internal cache, set up and use external cache.
=item B<-verify_return_error>
Verification errors normally just print a message but allow the
connection to continue, for debugging purposes.
If this option is used, then verification errors close the connection.
=item B<-verify_quiet>
No verify output except verify errors.
=item B<-ign_eof>
Ignore input EOF (default: when B<-quiet>).
=item B<-no_ign_eof>
Do not ignore input EOF.
=item B<-no_etm>
Disable Encrypt-then-MAC negotiation.
=item B<-status>
Enables certificate status request support (aka OCSP stapling).
=item B<-status_verbose>
Enables certificate status request support (aka OCSP stapling) and gives
a verbose printout of the OCSP response.
=item B<-status_timeout> I<int>
Sets the timeout for OCSP response to I<int> seconds.
=item B<-proxy> I<[http[s]://][userinfo@]host[:port][/path]>
The HTTP(S) proxy server to use for reaching the OCSP server unless B<-no_proxy>
applies, see below.
The proxy port defaults to 80 or 443 if the scheme is C<https>; apart from that
the optional C<http://> or C<https://> prefix is ignored,
as well as any userinfo and path components.
Defaults to the environment variable C<http_proxy> if set, else C<HTTP_PROXY>
in case no TLS is used, otherwise C<https_proxy> if set, else C<HTTPS_PROXY>.
=item B<-no_proxy> I<addresses>
List of IP addresses and/or DNS names of servers
not to use an HTTP(S) proxy for, separated by commas and/or whitespace
(where in the latter case the whole argument must be enclosed in "...").
Default is from the environment variable C<no_proxy> if set, else C<NO_PROXY>.
=item B<-status_url> I<val>
Sets a fallback responder URL to use if no responder URL is present in the
server certificate. Without this option an error is returned if the server
certificate does not contain a responder address.
The optional userinfo and fragment URL components are ignored.
Any given query component is handled as part of the path component.
=item B<-status_file> I<infile>
Overrides any OCSP responder URLs from the certificate and always provides the
OCSP Response stored in the file. The file must be in DER format.
=item B<-ssl_config> I<val>
Configure SSL_CTX using the given configuration value.
=item B<-trace>
Show verbose trace output of protocol messages.
=item B<-brief>
Provide a brief summary of connection parameters instead of the normal verbose
output.
=item B<-rev>
Simple echo server that sends back received text reversed. Also sets B<-brief>.
Cannot be used in conjunction with B<-early_data>.
=item B<-async>
Switch on asynchronous mode. Cryptographic operations will be performed
asynchronously. This will only have an effect if an asynchronous capable engine
is also used via the B<-engine> option. For test purposes the dummy async engine
(dasync) can be used (if available).
=item B<-max_send_frag> I<+int>
The maximum size of data fragment to send.
See L<SSL_CTX_set_max_send_fragment(3)> for further information.
=item B<-split_send_frag> I<+int>
The size used to split data for encrypt pipelines. If more data is written in
one go than this value then it will be split into multiple pipelines, up to the
maximum number of pipelines defined by max_pipelines. This only has an effect if
a suitable cipher suite has been negotiated, an engine that supports pipelining
has been loaded, and max_pipelines is greater than 1. See
L<SSL_CTX_set_split_send_fragment(3)> for further information.
=item B<-max_pipelines> I<+int>
The maximum number of encrypt/decrypt pipelines to be used. This will only have
an effect if an engine has been loaded that supports pipelining (e.g. the dasync
engine) and a suitable cipher suite has been negotiated. The default value is 1.
See L<SSL_CTX_set_max_pipelines(3)> for further information.
=item B<-naccept> I<+int>
The server will exit after receiving the specified number of connections,
default unlimited.
=item B<-read_buf> I<+int>
The default read buffer size to be used for connections. This will only have an
effect if the buffer size is larger than the size that would otherwise be used
and pipelining is in use (see L<SSL_CTX_set_default_read_buffer_len(3)> for
further information).
=item B<-bugs>
There are several known bugs in SSL and TLS implementations. Adding this
option enables various workarounds.
=item B<-no_comp>
Disable negotiation of TLS compression.
TLS compression is not recommended and is off by default as of
OpenSSL 1.1.0.
=item B<-comp>
Enable negotiation of TLS compression.
This option was introduced in OpenSSL 1.1.0.
TLS compression is not recommended and is off by default as of
OpenSSL 1.1.0.
=item B<-no_ticket>
Disable RFC4507bis session ticket support. This option has no effect if TLSv1.3
is negotiated. See B<-num_tickets>.
=item B<-num_tickets>
Control the number of tickets that will be sent to the client after a full
handshake in TLSv1.3. The default number of tickets is 2. This option does not
affect the number of tickets sent after a resumption handshake.
=item B<-serverpref>
Use the server's cipher preferences, rather than the client's preferences.
=item B<-prioritize_chacha>
Prioritize ChaCha ciphers when preferred by clients. Requires B<-serverpref>.
=item B<-no_resumption_on_reneg>
Set the B<SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION> option.
=item B<-client_sigalgs> I<val>
Signature algorithms to support for client certificate authentication
(colon-separated list).
=item B<-named_curve> I<val>
Specifies the elliptic curve to use. NOTE: this is single curve, not a list.
-For a list of all possible curves, use:
+
+The list of all supported groups includes named EC parameters as well as X25519
+and X448 or FFDHE groups, and may also include groups implemented in 3rd-party
+providers. For a list of named EC parameters, use:
$ openssl ecparam -list_curves
=item B<-cipher> I<val>
This allows the list of TLSv1.2 and below ciphersuites used by the server to be
modified. This list is combined with any TLSv1.3 ciphersuites that have been
configured. When the client sends a list of supported ciphers the first client
cipher also included in the server list is used. Because the client specifies
the preference order, the order of the server cipherlist is irrelevant. See
L<openssl-ciphers(1)> for more information.
=item B<-ciphersuites> I<val>
This allows the list of TLSv1.3 ciphersuites used by the server to be modified.
This list is combined with any TLSv1.2 and below ciphersuites that have been
configured. When the client sends a list of supported ciphers the first client
cipher also included in the server list is used. Because the client specifies
the preference order, the order of the server cipherlist is irrelevant. See
L<openssl-ciphers(1)> command for more information. The format for this list is
a simple colon (":") separated list of TLSv1.3 ciphersuite names.
=item B<-dhparam> I<infile>
The DH parameter file to use. The ephemeral DH cipher suites generate keys
using a set of DH parameters. If not specified then an attempt is made to
load the parameters from the server certificate file.
If this fails then a static set of parameters hard coded into this command
will be used.
=item B<-nbio>
Turns on non blocking I/O.
=item B<-timeout>
Enable timeouts.
=item B<-mtu>
Set link-layer MTU.
=item B<-psk_identity> I<val>
Expect the client to send PSK identity I<val> when using a PSK
cipher suite, and warn if they do not. By default, the expected PSK
identity is the string "Client_identity".
=item B<-psk_hint> I<val>
Use the PSK identity hint I<val> when using a PSK cipher suite.
=item B<-psk> I<val>
Use the PSK key I<val> when using a PSK cipher suite. The key is
given as a hexadecimal number without leading 0x, for example -psk
1a2b3c4d.
This option must be provided in order to use a PSK cipher.
=item B<-psk_session> I<file>
Use the pem encoded SSL_SESSION data stored in I<file> as the basis of a PSK.
Note that this will only work if TLSv1.3 is negotiated.
=item B<-srpvfile>
The verifier file for SRP.
This option is deprecated.
=item B<-srpuserseed>
A seed string for a default user salt.
This option is deprecated.
=item B<-listen>
This option can only be used in conjunction with one of the DTLS options above.
With this option, this command will listen on a UDP port for incoming
connections.
Any ClientHellos that arrive will be checked to see if they have a cookie in
them or not.
Any without a cookie will be responded to with a HelloVerifyRequest.
If a ClientHello with a cookie is received then this command will
connect to that peer and complete the handshake.
=item B<-sctp>
Use SCTP for the transport protocol instead of UDP in DTLS. Must be used in
conjunction with B<-dtls>, B<-dtls1> or B<-dtls1_2>. This option is only
available where OpenSSL has support for SCTP enabled.
=item B<-sctp_label_bug>
Use the incorrect behaviour of older OpenSSL implementations when computing
endpoint-pair shared secrets for DTLS/SCTP. This allows communication with
older broken implementations but breaks interoperability with correct
implementations. Must be used in conjunction with B<-sctp>. This option is only
available where OpenSSL has support for SCTP enabled.
=item B<-use_srtp>
Offer SRTP key management with a colon-separated profile list.
=item B<-no_dhe>
If this option is set then no DH parameters will be loaded effectively
disabling the ephemeral DH cipher suites.
=item B<-alpn> I<val>, B<-nextprotoneg> I<val>
These flags enable the Application-Layer Protocol Negotiation
or Next Protocol Negotiation (NPN) extension, respectively. ALPN is the
IETF standard and replaces NPN.
The I<val> list is a comma-separated list of supported protocol
names. The list should contain the most desirable protocols first.
Protocol names are printable ASCII strings, for example "http/1.1" or
"spdy/3".
The flag B<-nextprotoneg> cannot be specified if B<-tls1_3> is used.
=item B<-sendfile>
If this option is set and KTLS is enabled, SSL_sendfile() will be used
instead of BIO_write() to send the HTTP response requested by a client.
This option is only valid if B<-WWW> or B<-HTTP> is specified.
=item B<-keylogfile> I<outfile>
Appends TLS secrets to the specified keylog file such that external programs
(like Wireshark) can decrypt TLS connections.
=item B<-max_early_data> I<int>
Change the default maximum early data bytes that are specified for new sessions
and any incoming early data (when used in conjunction with the B<-early_data>
flag). The default value is approximately 16k. The argument must be an integer
greater than or equal to 0.
=item B<-recv_max_early_data> I<int>
Specify the hard limit on the maximum number of early data bytes that will
be accepted.
=item B<-early_data>
Accept early data where possible. Cannot be used in conjunction with B<-www>,
B<-WWW>, B<-HTTP> or B<-rev>.
=item B<-stateless>
Require TLSv1.3 cookies.
=item B<-anti_replay>, B<-no_anti_replay>
Switches replay protection on or off, respectively. Replay protection is on by
default unless overridden by a configuration file. When it is on, OpenSSL will
automatically detect if a session ticket has been used more than once, TLSv1.3
has been negotiated, and early data is enabled on the server. A full handshake
is forced if a session ticket is used a second or subsequent time. Any early
data that was sent will be rejected.
{- $OpenSSL::safe::opt_name_item -}
{- $OpenSSL::safe::opt_version_item -}
{- $OpenSSL::safe::opt_s_item -}
{- $OpenSSL::safe::opt_x_item -}
{- $OpenSSL::safe::opt_trust_item -}
{- $OpenSSL::safe::opt_r_item -}
{- $OpenSSL::safe::opt_engine_item -}
{- $OpenSSL::safe::opt_provider_item -}
{- $OpenSSL::safe::opt_v_item -}
If the server requests a client certificate, then
verification errors are displayed, for debugging, but the command will
proceed unless the B<-verify_return_error> option is used.
=back
=head1 CONNECTED COMMANDS
If a connection request is established with an SSL client and neither the
B<-www> nor the B<-WWW> option has been used then normally any data received
from the client is displayed and any key presses will be sent to the client.
Certain commands are also recognized which perform special operations. These
commands are a letter which must appear at the start of a line. They are listed
below.
=over 4
=item B<q>
End the current SSL connection but still accept new connections.
=item B<Q>
End the current SSL connection and exit.
=item B<r>
Renegotiate the SSL session (TLSv1.2 and below only).
=item B<R>
Renegotiate the SSL session and request a client certificate (TLSv1.2 and below
only).
=item B<P>
Send some plain text down the underlying TCP connection: this should
cause the client to disconnect due to a protocol violation.
=item B<S>
Print out some session cache status information.
=item B<k>
Send a key update message to the client (TLSv1.3 only)
=item B<K>
Send a key update message to the client and request one back (TLSv1.3 only)
=item B<c>
Send a certificate request to the client (TLSv1.3 only)
=back
=head1 NOTES
This command can be used to debug SSL clients. To accept connections
from a web browser the command:
openssl s_server -accept 443 -www
can be used for example.
Although specifying an empty list of CAs when requesting a client certificate
is strictly speaking a protocol violation, some SSL clients interpret this to
mean any CA is acceptable. This is useful for debugging purposes.
The session parameters can printed out using the L<openssl-sess_id(1)> command.
=head1 BUGS
Because this program has a lot of options and also because some of the
techniques used are rather old, the C source for this command is rather
hard to read and not a model of how things should be done.
A typical SSL server program would be much simpler.
The output of common ciphers is wrong: it just gives the list of ciphers that
OpenSSL recognizes and the client supports.
There should be a way for this command to print out details
of any unknown cipher suites a client says it supports.
=head1 SEE ALSO
L<openssl(1)>,
L<openssl-sess_id(1)>,
L<openssl-s_client(1)>,
L<openssl-ciphers(1)>,
L<SSL_CONF_cmd(3)>,
L<SSL_CTX_set_max_send_fragment(3)>,
L<SSL_CTX_set_split_send_fragment(3)>,
L<SSL_CTX_set_max_pipelines(3)>,
L<ossl_store-file(7)>
=head1 HISTORY
The -no_alt_chains option was added in OpenSSL 1.1.0.
The
-allow-no-dhe-kex and -prioritize_chacha options were added in OpenSSL 1.1.1.
The B<-srpvfile>, B<-srpuserseed>, and B<-engine>
option were deprecated in OpenSSL 3.0.
=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/man1/openssl-verification-options.pod b/crypto/openssl/doc/man1/openssl-verification-options.pod
index 4998e452b549..bf9ed9c1a62e 100644
--- a/crypto/openssl/doc/man1/openssl-verification-options.pod
+++ b/crypto/openssl/doc/man1/openssl-verification-options.pod
@@ -1,696 +1,696 @@
=pod
=head1 NAME
openssl-verification-options - generic X.509 certificate verification options
=head1 SYNOPSIS
B<openssl>
I<command>
[ I<options> ... ]
[ I<parameters> ... ]
=head1 DESCRIPTION
There are many situations where X.509 certificates are verified
within the OpenSSL libraries and in various OpenSSL commands.
Certificate verification is implemented by L<X509_verify_cert(3)>.
It is a complicated process consisting of a number of steps
and depending on numerous options.
The most important of them are detailed in the following sections.
In a nutshell, a valid chain of certificates needs to be built up and verified
starting from the I<target certificate> that is to be verified
and ending in a certificate that due to some policy is trusted.
Verification is done relative to the given I<purpose>, which is the intended use
of the target certificate, such as SSL server, or by default for any purpose.
The details of how each OpenSSL command handles errors
are documented on the specific command page.
DANE support is documented in L<openssl-s_client(1)>,
L<SSL_CTX_dane_enable(3)>, L<SSL_set1_host(3)>,
L<X509_VERIFY_PARAM_set_flags(3)>, and L<X509_check_host(3)>.
=head2 Trust Anchors
In general, according to RFC 4158 and RFC 5280, a I<trust anchor> is
any public key and related subject distinguished name (DN) that
for some reason is considered trusted
and thus is acceptable as the root of a chain of certificates.
In practice, trust anchors are given in the form of certificates,
where their essential fields are the public key and the subject DN.
In addition to the requirements in RFC 5280,
OpenSSL checks the validity period of such certificates
and makes use of some further fields.
In particular, the subject key identifier extension, if present,
is used for matching trust anchors during chain building.
In the most simple and common case, trust anchors are by default
all self-signed "root" CA certificates that are placed in the I<trust store>,
which is a collection of certificates that are trusted for certain uses.
This is akin to what is used in the trust stores of Mozilla Firefox,
or Apple's and Microsoft's certificate stores, ...
From the OpenSSL perspective, a trust anchor is a certificate
that should be augmented with an explicit designation for which
uses of a target certificate the certificate may serve as a trust anchor.
In PEM encoding, this is indicated by the C<TRUSTED CERTIFICATE> string.
Such a designation provides a set of positive trust attributes
explicitly stating trust for the listed purposes
and/or a set of negative trust attributes
explicitly rejecting the use for the listed purposes.
The purposes are encoded using the values defined for the extended key usages
(EKUs) that may be given in X.509 extensions of end-entity certificates.
See also the L</Extended Key Usage> section below.
The currently recognized uses are
B<clientAuth> (SSL client use), B<serverAuth> (SSL server use),
B<emailProtection> (S/MIME email use), B<codeSigning> (object signer use),
B<OCSPSigning> (OCSP responder use), B<OCSP> (OCSP request use),
B<timeStamping> (TSA server use), and B<anyExtendedKeyUsage>.
As of OpenSSL 1.1.0, the last of these blocks all uses when rejected or
enables all uses when trusted.
A certificate, which may be CA certificate or an end-entity certificate,
is considered a trust anchor for the given use
if and only if all the following conditions hold:
=over 4
=item *
It is an an element of the trust store.
=item *
It does not have a negative trust attribute rejecting the given use.
=item *
It has a positive trust attribute accepting the given use
or (by default) one of the following compatibility conditions apply:
It is self-signed or the B<-partial_chain> option is given
(which corresponds to the B<X509_V_FLAG_PARTIAL_CHAIN> flag being set).
=back
=head2 Certification Path Building
First, a certificate chain is built up starting from the target certificate
and ending in a trust anchor.
The chain is built up iteratively, looking up in turn
a certificate with suitable key usage that
matches as an issuer of the current "subject" certificate as described below.
If there is such a certificate, the first one found that is currently valid
is taken, otherwise the one that expired most recently of all such certificates.
For efficiency, no backtracking is performed, thus
any further candidate issuer certificates that would match equally are ignored.
When a self-signed certificate has been added, chain construction stops.
In this case it must fully match a trust anchor, otherwise chain building fails.
A candidate issuer certificate matches a subject certificate
if all of the following conditions hold:
=over 4
=item *
Its subject name matches the issuer name of the subject certificate.
=item *
If the subject certificate has an authority key identifier extension,
each of its sub-fields equals the corresponding subject key identifier, serial
number, and issuer field of the candidate issuer certificate,
as far as the respective fields are present in both certificates.
=item *
The certificate signature algorithm used to sign the subject certificate
is supported and
equals the public key algorithm of the candidate issuer certificate.
=back
The lookup first searches for issuer certificates in the trust store.
If it does not find a match there it consults
the list of untrusted ("intermediate" CA) certificates, if provided.
=head2 Certification Path Validation
When the certificate chain building process was successful
the chain components and their links are checked thoroughly.
The first step is to check that each certificate is well-formed.
Part of these checks are enabled only if the B<-x509_strict> option is given.
The second step is to check the extensions of every untrusted certificate
for consistency with the supplied purpose.
If the B<-purpose> option is not given then no such checks are done
except for SSL/TLS connection setup,
where by default C<sslserver> or C<sslclient>, are checked.
The target or "leaf" certificate, as well as any other untrusted certificates,
must have extensions compatible with the specified purpose.
All certificates except the target or "leaf" must also be valid CA certificates.
The precise extensions required are described in more detail in
L<openssl-x509(1)/CERTIFICATE EXTENSIONS>.
The third step is to check the trust settings on the last certificate
(which typically is a self-signed root CA certificate).
It must be trusted for the given use.
For compatibility with previous versions of OpenSSL, a self-signed certificate
with no trust attributes is considered to be valid for all uses.
The fourth, and final, step is to check the validity of the certificate chain.
For each element in the chain, including the root CA certificate,
the validity period as specified by the C<notBefore> and C<notAfter> fields
is checked against the current system time.
The B<-attime> flag may be used to use a reference time other than "now."
The certificate signature is checked as well
(except for the signature of the typically self-signed root CA certificate,
which is verified only if the B<-check_ss_sig> option is given).
When verifying a certificate signature
the keyUsage extension (if present) of the candidate issuer certificate
is checked to permit digitalSignature for signing proxy certificates
or to permit keyCertSign for signing other certificates, respectively.
If all operations complete successfully then certificate is considered
valid. If any operation fails then the certificate is not valid.
=head1 OPTIONS
=head2 Trusted Certificate Options
The following options specify how to supply the certificates
that can be used as trust anchors for certain uses.
As mentioned, a collection of such certificates is called a I<trust store>.
Note that OpenSSL does not provide a default set of trust anchors. Many
Linux distributions include a system default and configure OpenSSL to point
to that. Mozilla maintains an influential trust store that can be found at
L<https://www.mozilla.org/en-US/about/governance/policies/security-group/certs/>.
The certificates to add to the trust store
can be specified using following options.
=over 4
=item B<-CAfile> I<file>
Load the specified file which contains a certificate
or several of them in case the input is in PEM or PKCS#12 format.
PEM-encoded certificates may also have trust attributes set.
=item B<-no-CAfile>
Do not load the default file of trusted certificates.
=item B<-CApath> I<dir>
Use the specified directory as a collection of trusted certificates,
i.e., a trust store.
Files should be named with the hash value of the X.509 SubjectName of each
certificate. This is so that the library can extract the IssuerName,
hash it, and directly lookup the file to get the issuer certificate.
See L<openssl-rehash(1)> for information on creating this type of directory.
=item B<-no-CApath>
Do not use the default directory of trusted certificates.
=item B<-CAstore> I<uri>
Use I<uri> as a store of CA certificates.
The URI may indicate a single certificate, as well as a collection of them.
With URIs in the C<file:> scheme, this acts as B<-CAfile> or
B<-CApath>, depending on if the URI indicates a single file or
directory.
See L<ossl_store-file(7)> for more information on the C<file:> scheme.
These certificates are also used when building the server certificate
chain (for example with L<openssl-s_server(1)>) or client certificate
chain (for example with L<openssl-s_time(1)>).
=item B<-no-CAstore>
Do not use the default store of trusted CA certificates.
=back
=head2 Verification Options
The certificate verification can be fine-tuned with the following flags.
=over 4
=item B<-verbose>
Print extra information about the operations being performed.
=item B<-attime> I<timestamp>
Perform validation checks using time specified by I<timestamp> and not
current system time. I<timestamp> is the number of seconds since
January 1, 1970 (i.e., the Unix Epoch).
=item B<-no_check_time>
This option suppresses checking the validity period of certificates and CRLs
against the current time. If option B<-attime> is used to specify
a verification time, the check is not suppressed.
=item B<-x509_strict>
This disables non-compliant workarounds for broken certificates.
Thus errors are thrown on certificates not compliant with RFC 5280.
When this option is set,
among others, the following certificate well-formedness conditions are checked:
=over 4
=item *
The basicConstraints of CA certificates must be marked critical.
=item *
CA certificates must explicitly include the keyUsage extension.
=item *
If a pathlenConstraint is given the key usage keyCertSign must be allowed.
=item *
The pathlenConstraint must not be given for non-CA certificates.
=item *
The issuer name of any certificate must not be empty.
=item *
The subject name of CA certs, certs with keyUsage crlSign, and certs
without subjectAlternativeName must not be empty.
=item *
If a subjectAlternativeName extension is given it must not be empty.
=item *
The signatureAlgorithm field and the cert signature must be consistent.
=item *
Any given authorityKeyIdentifier and any given subjectKeyIdentifier
must not be marked critical.
=item *
The authorityKeyIdentifier must be given for X.509v3 certs unless they
are self-signed.
=item *
The subjectKeyIdentifier must be given for all X.509v3 CA certs.
=back
=item B<-ignore_critical>
Normally if an unhandled critical extension is present that is not
supported by OpenSSL the certificate is rejected (as required by RFC5280).
If this option is set critical extensions are ignored.
=item B<-issuer_checks>
Ignored.
=item B<-crl_check>
Checks end entity certificate validity by attempting to look up a valid CRL.
If a valid CRL cannot be found an error occurs.
=item B<-crl_check_all>
Checks the validity of B<all> certificates in the chain by attempting
to look up valid CRLs.
=item B<-use_deltas>
Enable support for delta CRLs.
=item B<-extended_crl>
Enable extended CRL features such as indirect CRLs and alternate CRL
signing keys.
=item B<-suiteB_128_only>, B<-suiteB_128>, B<-suiteB_192>
Enable the Suite B mode operation at 128 bit Level of Security, 128 bit or
192 bit, or only 192 bit Level of Security respectively.
See RFC6460 for details. In particular the supported signature algorithms are
reduced to support only ECDSA and SHA256 or SHA384 and only the elliptic curves
P-256 and P-384.
=item B<-auth_level> I<level>
Set the certificate chain authentication security level to I<level>.
The authentication security level determines the acceptable signature and
public key strength when verifying certificate chains. For a certificate
chain to validate, the public keys of all the certificates must meet the
specified security I<level>. The signature algorithm security level is
enforced for all the certificates in the chain except for the chain's
I<trust anchor>, which is either directly trusted or validated by means
other than its signature. See L<SSL_CTX_set_security_level(3)> for the
definitions of the available levels. The default security level is -1,
or "not set". At security level 0 or lower all algorithms are acceptable.
Security level 1 requires at least 80-bit-equivalent security and is broadly
interoperable, though it will, for example, reject MD5 signatures or RSA
keys shorter than 1024 bits.
=item B<-partial_chain>
Allow verification to succeed if an incomplete chain can be built.
That is, a chain ending in a certificate that normally would not be trusted
(because it has no matching positive trust attributes and is not self-signed)
but is an element of the trust store.
This certificate may be self-issued or belong to an intermediate CA.
=item B<-check_ss_sig>
Verify the signature of
the last certificate in a chain if the certificate is supposedly self-signed.
This is prohibited and will result in an error if it is a non-conforming CA
certificate with key usage restrictions not including the keyCertSign bit.
This verification is disabled by default because it doesn't add any security.
=item B<-allow_proxy_certs>
Allow the verification of proxy certificates.
=item B<-trusted_first>
As of OpenSSL 1.1.0 this option is on by default and cannot be disabled.
When constructing the certificate chain, the trusted certificates specified
via B<-CAfile>, B<-CApath>, B<-CAstore> or B<-trusted> are always used
before any certificates specified via B<-untrusted>.
=item B<-no_alt_chains>
As of OpenSSL 1.1.0, since B<-trusted_first> always on, this option has no
effect.
=item B<-trusted> I<file>
Parse I<file> as a set of one or more certificates.
Each of them qualifies as trusted if has a suitable positive trust attribute
or it is self-signed or the B<-partial_chain> option is specified.
This option implies the B<-no-CAfile>, B<-no-CApath>, and B<-no-CAstore> options
and it cannot be used with the B<-CAfile>, B<-CApath> or B<-CAstore> options, so
only certificates specified using the B<-trusted> option are trust anchors.
This option may be used multiple times.
=item B<-untrusted> I<file>
Parse I<file> as a set of one or more certificates.
All certificates (typically of intermediate CAs) are considered untrusted
and may be used to
construct a certificate chain from the target certificate to a trust anchor.
This option may be used multiple times.
=item B<-policy> I<arg>
Enable policy processing and add I<arg> to the user-initial-policy-set (see
-RFC5280). The policy I<arg> can be an object name an OID in numeric form.
+RFC5280). The policy I<arg> can be an object name or an OID in numeric form.
This argument can appear more than once.
=item B<-explicit_policy>
Set policy variable require-explicit-policy (see RFC5280).
=item B<-policy_check>
Enables certificate policy processing.
=item B<-policy_print>
Print out diagnostics related to policy processing.
=item B<-inhibit_any>
Set policy variable inhibit-any-policy (see RFC5280).
=item B<-inhibit_map>
Set policy variable inhibit-policy-mapping (see RFC5280).
=item B<-purpose> I<purpose>
The intended use for the certificate.
Currently defined purposes are C<sslclient>, C<sslserver>, C<nssslserver>,
C<smimesign>, C<smimeencrypt>, C<crlsign>, C<ocsphelper>, C<timestampsign>,
and C<any>.
If peer certificate verification is enabled, by default the TLS implementation
as well as the commands B<s_client> and B<s_server> check for consistency
with TLS server or TLS client use, respectively.
While IETF RFC 5280 says that B<id-kp-serverAuth> and B<id-kp-clientAuth>
are only for WWW use, in practice they are used for all kinds of TLS clients
and servers, and this is what OpenSSL assumes as well.
=item B<-verify_depth> I<num>
Limit the certificate chain to I<num> intermediate CA certificates.
A maximal depth chain can have up to I<num>+2 certificates, since neither the
end-entity certificate nor the trust-anchor certificate count against the
B<-verify_depth> limit.
=item B<-verify_email> I<email>
Verify if I<email> matches the email address in Subject Alternative Name or
the email in the subject Distinguished Name.
=item B<-verify_hostname> I<hostname>
Verify if I<hostname> matches DNS name in Subject Alternative Name or
Common Name in the subject certificate.
=item B<-verify_ip> I<ip>
Verify if I<ip> matches the IP address in Subject Alternative Name of
the subject certificate.
=item B<-verify_name> I<name>
Use default verification policies like trust model and required certificate
policies identified by I<name>.
The trust model determines which auxiliary trust or reject OIDs are applicable
to verifying the given certificate chain.
They can be given using the B<-addtrust> and B<-addreject> options
for L<openssl-x509(1)>.
Supported policy names include: B<default>, B<pkcs7>, B<smime_sign>,
B<ssl_client>, B<ssl_server>.
These mimics the combinations of purpose and trust settings used in SSL, CMS
and S/MIME.
As of OpenSSL 1.1.0, the trust model is inferred from the purpose when not
specified, so the B<-verify_name> options are functionally equivalent to the
corresponding B<-purpose> settings.
=back
=head2 Extended Verification Options
Sometimes there may be more than one certificate chain leading to an
end-entity certificate.
This usually happens when a root or intermediate CA signs a certificate
for another a CA in other organization.
Another reason is when a CA might have intermediates that use two different
signature formats, such as a SHA-1 and a SHA-256 digest.
The following options can be used to provide data that will allow the
OpenSSL command to generate an alternative chain.
=over 4
=item B<-xkey> I<infile>, B<-xcert> I<infile>, B<-xchain>
Specify an extra certificate, private key and certificate chain. These behave
in the same manner as the B<-cert>, B<-key> and B<-cert_chain> options. When
specified, the callback returning the first valid chain will be in use by the
client.
=item B<-xchain_build>
Specify whether the application should build the certificate chain to be
provided to the server for the extra certificates via the B<-xkey>,
B<-xcert>, and B<-xchain> options.
=item B<-xcertform> B<DER>|B<PEM>|B<P12>
The input format for the extra certificate.
This option has no effect and is retained for backward compatibility only.
=item B<-xkeyform> B<DER>|B<PEM>|B<P12>
The input format for the extra key.
This option has no effect and is retained for backward compatibility only.
=back
=head2 Certificate Extensions
Options like B<-purpose> lead to checking the certificate extensions,
which determine what the target certificate and intermediate CA certificates
can be used for.
=head3 Basic Constraints
The basicConstraints extension CA flag is used to determine whether the
certificate can be used as a CA. If the CA flag is true then it is a CA,
if the CA flag is false then it is not a CA. B<All> CAs should have the
CA flag set to true.
If the basicConstraints extension is absent,
which includes the case that it is an X.509v1 certificate,
then the certificate is considered to be a "possible CA" and
other extensions are checked according to the intended use of the certificate.
The treatment of certificates without basicConstraints as a CA
is presently supported, but this could change in the future.
=head3 Key Usage
If the keyUsage extension is present then additional restraints are
made on the uses of the certificate. A CA certificate B<must> have the
keyCertSign bit set if the keyUsage extension is present.
=head3 Extended Key Usage
The extKeyUsage (EKU) extension places additional restrictions on the
certificate uses. If this extension is present (whether critical or not)
the key can only be used for the purposes specified.
A complete description of each check is given below. The comments about
basicConstraints and keyUsage and X.509v1 certificates above apply to B<all>
CA certificates.
=over 4
=item B<SSL Client>
The extended key usage extension must be absent or include the "web client
authentication" OID. The keyUsage extension must be absent or it must have the
digitalSignature bit set. The Netscape certificate type must be absent
or it must have the SSL client bit set.
=item B<SSL Client CA>
The extended key usage extension must be absent or include the "web client
authentication" OID.
The Netscape certificate type must be absent or it must have the SSL CA bit set.
This is used as a work around if the basicConstraints extension is absent.
=item B<SSL Server>
The extended key usage extension must be absent or include the "web server
authentication" and/or one of the SGC OIDs. The keyUsage extension must be
absent or it
must have the digitalSignature, the keyEncipherment set or both bits set.
The Netscape certificate type must be absent or have the SSL server bit set.
=item B<SSL Server CA>
The extended key usage extension must be absent or include the "web server
authentication" and/or one of the SGC OIDs. The Netscape certificate type must
be absent or the SSL CA bit must be set.
This is used as a work around if the basicConstraints extension is absent.
=item B<Netscape SSL Server>
For Netscape SSL clients to connect to an SSL server it must have the
keyEncipherment bit set if the keyUsage extension is present. This isn't
always valid because some cipher suites use the key for digital signing.
Otherwise it is the same as a normal SSL server.
=item B<Common S/MIME Client Tests>
The extended key usage extension must be absent or include the "email
protection" OID. The Netscape certificate type must be absent or should have the
S/MIME bit set. If the S/MIME bit is not set in the Netscape certificate type
then the SSL client bit is tolerated as an alternative but a warning is shown.
This is because some Verisign certificates don't set the S/MIME bit.
=item B<S/MIME Signing>
In addition to the common S/MIME client tests the digitalSignature bit or
the nonRepudiation bit must be set if the keyUsage extension is present.
=item B<S/MIME Encryption>
In addition to the common S/MIME tests the keyEncipherment bit must be set
if the keyUsage extension is present.
=item B<S/MIME CA>
The extended key usage extension must be absent or include the "email
protection" OID. The Netscape certificate type must be absent or must have the
S/MIME CA bit set.
This is used as a work around if the basicConstraints extension is absent.
=item B<CRL Signing>
The keyUsage extension must be absent or it must have the CRL signing bit
set.
=item B<CRL Signing CA>
The normal CA tests apply. Except in this case the basicConstraints extension
must be present.
=back
=head1 BUGS
The issuer checks still suffer from limitations in the underlying X509_LOOKUP
API. One consequence of this is that trusted certificates with matching
subject name must appear in a file (as specified by the B<-CAfile> option),
a directory (as specified by B<-CApath>),
or a store (as specified by B<-CAstore>).
If there are multiple such matches, possibly in multiple locations,
only the first one (in the mentioned order of locations) is recognised.
=head1 SEE ALSO
L<X509_verify_cert(3)>,
L<openssl-verify(1)>,
L<openssl-ocsp(1)>,
L<openssl-ts(1)>,
L<openssl-s_client(1)>,
L<openssl-s_server(1)>,
L<openssl-smime(1)>,
L<openssl-cmp(1)>,
L<openssl-cms(1)>
=head1 HISTORY
The checks enabled by B<-x509_strict> have been extended 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/ASN1_INTEGER_new.pod b/crypto/openssl/doc/man3/ASN1_INTEGER_new.pod
index 4722f880c0b2..869ac754f4b7 100644
--- a/crypto/openssl/doc/man3/ASN1_INTEGER_new.pod
+++ b/crypto/openssl/doc/man3/ASN1_INTEGER_new.pod
@@ -1,44 +1,45 @@
=pod
=head1 NAME
ASN1_INTEGER_new, ASN1_INTEGER_free - ASN1_INTEGER allocation functions
=head1 SYNOPSIS
=for openssl generic
#include <openssl/asn1.h>
ASN1_INTEGER *ASN1_INTEGER_new(void);
void ASN1_INTEGER_free(ASN1_INTEGER *a);
=head1 DESCRIPTION
ASN1_INTEGER_new() returns an allocated B<ASN1_INTEGER> structure.
ASN1_INTEGER_free() frees up a single B<ASN1_INTEGER> object.
+If the argument is NULL, nothing is done.
B<ASN1_INTEGER> structure representing the ASN.1 INTEGER type
=head1 RETURN VALUES
ASN1_INTEGER_new() return a valid B<ASN1_INTEGER> structure or NULL
if an error occurred.
ASN1_INTEGER_free() does not return a value.
=head1 SEE ALSO
L<ERR_get_error(3)>
=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/man3/ASYNC_WAIT_CTX_new.pod b/crypto/openssl/doc/man3/ASYNC_WAIT_CTX_new.pod
index 7621a8b3a166..d85c51e5556d 100644
--- a/crypto/openssl/doc/man3/ASYNC_WAIT_CTX_new.pod
+++ b/crypto/openssl/doc/man3/ASYNC_WAIT_CTX_new.pod
@@ -1,226 +1,229 @@
=pod
=head1 NAME
ASYNC_WAIT_CTX_new, ASYNC_WAIT_CTX_free, ASYNC_WAIT_CTX_set_wait_fd,
ASYNC_WAIT_CTX_get_fd, ASYNC_WAIT_CTX_get_all_fds,
ASYNC_WAIT_CTX_get_changed_fds, ASYNC_WAIT_CTX_clear_fd,
ASYNC_WAIT_CTX_set_callback, ASYNC_WAIT_CTX_get_callback,
ASYNC_WAIT_CTX_set_status, ASYNC_WAIT_CTX_get_status, ASYNC_callback_fn,
ASYNC_STATUS_UNSUPPORTED, ASYNC_STATUS_ERR, ASYNC_STATUS_OK,
ASYNC_STATUS_EAGAIN
- functions to manage waiting for asynchronous jobs to complete
=head1 SYNOPSIS
#include <openssl/async.h>
#define ASYNC_STATUS_UNSUPPORTED 0
#define ASYNC_STATUS_ERR 1
#define ASYNC_STATUS_OK 2
#define ASYNC_STATUS_EAGAIN 3
typedef int (*ASYNC_callback_fn)(void *arg);
ASYNC_WAIT_CTX *ASYNC_WAIT_CTX_new(void);
void ASYNC_WAIT_CTX_free(ASYNC_WAIT_CTX *ctx);
int ASYNC_WAIT_CTX_set_wait_fd(ASYNC_WAIT_CTX *ctx, const void *key,
OSSL_ASYNC_FD fd,
void *custom_data,
void (*cleanup)(ASYNC_WAIT_CTX *, const void *,
OSSL_ASYNC_FD, void *));
int ASYNC_WAIT_CTX_get_fd(ASYNC_WAIT_CTX *ctx, const void *key,
OSSL_ASYNC_FD *fd, void **custom_data);
int ASYNC_WAIT_CTX_get_all_fds(ASYNC_WAIT_CTX *ctx, OSSL_ASYNC_FD *fd,
size_t *numfds);
int ASYNC_WAIT_CTX_get_changed_fds(ASYNC_WAIT_CTX *ctx, OSSL_ASYNC_FD *addfd,
size_t *numaddfds, OSSL_ASYNC_FD *delfd,
size_t *numdelfds);
int ASYNC_WAIT_CTX_clear_fd(ASYNC_WAIT_CTX *ctx, const void *key);
int ASYNC_WAIT_CTX_set_callback(ASYNC_WAIT_CTX *ctx,
ASYNC_callback_fn callback,
void *callback_arg);
int ASYNC_WAIT_CTX_get_callback(ASYNC_WAIT_CTX *ctx,
ASYNC_callback_fn *callback,
void **callback_arg);
int ASYNC_WAIT_CTX_set_status(ASYNC_WAIT_CTX *ctx, int status);
int ASYNC_WAIT_CTX_get_status(ASYNC_WAIT_CTX *ctx);
=head1 DESCRIPTION
For an overview of how asynchronous operations are implemented in OpenSSL see
L<ASYNC_start_job(3)>. An B<ASYNC_WAIT_CTX> object represents an asynchronous
"session", i.e. a related set of crypto operations. For example in SSL terms
this would have a one-to-one correspondence with an SSL connection.
Application code must create an B<ASYNC_WAIT_CTX> using the ASYNC_WAIT_CTX_new()
function prior to calling ASYNC_start_job() (see L<ASYNC_start_job(3)>). When
the job is started it is associated with the B<ASYNC_WAIT_CTX> for the duration
of that job. An B<ASYNC_WAIT_CTX> should only be used for one B<ASYNC_JOB> at
any one time, but can be reused after an B<ASYNC_JOB> has finished for a
subsequent B<ASYNC_JOB>. When the session is complete (e.g. the SSL connection
is closed), application code cleans up with ASYNC_WAIT_CTX_free().
B<ASYNC_WAIT_CTX>s can have "wait" file descriptors associated with them.
Calling ASYNC_WAIT_CTX_get_all_fds() and passing in a pointer to an
B<ASYNC_WAIT_CTX> in the I<ctx> parameter will return the wait file descriptors
associated with that job in I<*fd>. The number of file descriptors returned will
be stored in I<*numfds>. It is the caller's responsibility to ensure that
sufficient memory has been allocated in I<*fd> to receive all the file
descriptors. Calling ASYNC_WAIT_CTX_get_all_fds() with a NULL I<fd> value will
return no file descriptors but will still populate I<*numfds>. Therefore,
application code is typically expected to call this function twice: once to get
the number of fds, and then again when sufficient memory has been allocated. If
only one asynchronous engine is being used then normally this call will only
ever return one fd. If multiple asynchronous engines are being used then more
could be returned.
The function ASYNC_WAIT_CTX_get_changed_fds() can be used to detect if any fds
have changed since the last call time ASYNC_start_job() returned B<ASYNC_PAUSE>
(or since the B<ASYNC_WAIT_CTX> was created if no B<ASYNC_PAUSE> result has
been received). The I<numaddfds> and I<numdelfds> parameters will be populated
with the number of fds added or deleted respectively. I<*addfd> and I<*delfd>
will be populated with the list of added and deleted fds respectively. Similarly
to ASYNC_WAIT_CTX_get_all_fds() either of these can be NULL, but if they are not
NULL then the caller is responsible for ensuring sufficient memory is allocated.
Implementers of async aware code (e.g. engines) are encouraged to return a
stable fd for the lifetime of the B<ASYNC_WAIT_CTX> in order to reduce the
"churn" of regularly changing fds - although no guarantees of this are provided
to applications.
Applications can wait for the file descriptor to be ready for "read" using a
system function call such as select or poll (being ready for "read" indicates
that the job should be resumed). If no file descriptor is made available then an
application will have to periodically "poll" the job by attempting to restart it
to see if it is ready to continue.
Async aware code (e.g. engines) can get the current B<ASYNC_WAIT_CTX> from the
job via L<ASYNC_get_wait_ctx(3)> and provide a file descriptor to use for
waiting on by calling ASYNC_WAIT_CTX_set_wait_fd(). Typically this would be done
by an engine immediately prior to calling ASYNC_pause_job() and not by end user
code. An existing association with a file descriptor can be obtained using
ASYNC_WAIT_CTX_get_fd() and cleared using ASYNC_WAIT_CTX_clear_fd(). Both of
these functions requires a I<key> value which is unique to the async aware
code. This could be any unique value but a good candidate might be the
B<ENGINE *> for the engine. The I<custom_data> parameter can be any value, and
will be returned in a subsequent call to ASYNC_WAIT_CTX_get_fd(). The
ASYNC_WAIT_CTX_set_wait_fd() function also expects a pointer to a "cleanup"
routine. This can be NULL but if provided will automatically get called when
the B<ASYNC_WAIT_CTX> is freed, and gives the engine the opportunity to close
the fd or any other resources. Note: The "cleanup" routine does not get called
if the fd is cleared directly via a call to ASYNC_WAIT_CTX_clear_fd().
An example of typical usage might be an async capable engine. User code would
initiate cryptographic operations. The engine would initiate those operations
asynchronously and then call ASYNC_WAIT_CTX_set_wait_fd() followed by
ASYNC_pause_job() to return control to the user code. The user code can then
perform other tasks or wait for the job to be ready by calling "select" or other
similar function on the wait file descriptor. The engine can signal to the user
code that the job should be resumed by making the wait file descriptor
"readable". Once resumed the engine should clear the wake signal on the wait
file descriptor.
As well as a file descriptor, user code may also be notified via a callback. The
callback and data pointers are stored within the B<ASYNC_WAIT_CTX> along with an
additional status field that can be used for the notification of retries from an
engine. This additional method can be used when the user thinks that a file
descriptor is too costly in terms of CPU cycles or in some context where a file
descriptor is not appropriate.
ASYNC_WAIT_CTX_set_callback() sets the callback and the callback argument. The
callback will be called to notify user code when an engine completes a
cryptography operation. It is a requirement that the callback function is small
and nonblocking as it will be run in the context of a polling mechanism or an
interrupt.
ASYNC_WAIT_CTX_get_callback() returns the callback set in the B<ASYNC_WAIT_CTX>
structure.
ASYNC_WAIT_CTX_set_status() allows an engine to set the current engine status.
The possible status values are the following:
=over 4
=item B<ASYNC_STATUS_UNSUPPORTED>
The engine does not support the callback mechanism. This is the default value.
The engine must call ASYNC_WAIT_CTX_set_status() to set the status to some value
other than B<ASYNC_STATUS_UNSUPPORTED> if it intends to enable the callback
mechanism.
=item B<ASYNC_STATUS_ERR>
The engine has a fatal problem with this request. The user code should clean up
this session.
=item B<ASYNC_STATUS_OK>
The request has been successfully submitted.
=item B<ASYNC_STATUS_EAGAIN>
The engine has some problem which will be recovered soon, such as a buffer is
full, so user code should resume the job.
=back
ASYNC_WAIT_CTX_get_status() allows user code to obtain the current status value.
If the status is any value other than B<ASYNC_STATUS_OK> then the user code
should not expect to receive a callback from the engine even if one has been
set.
An example of the usage of the callback method might be the following. User
code would initiate cryptographic operations, and the engine code would dispatch
this operation to hardware, and if the dispatch is successful, then the engine
code would call ASYNC_pause_job() to return control to the user code. After
that, user code can perform other tasks. When the hardware completes the
operation, normally it is detected by a polling function or an interrupt, as the
user code set a callback by calling ASYNC_WAIT_CTX_set_callback() previously,
then the registered callback will be called.
+ASYNC_WAIT_CTX_free() frees up a single B<ASYNC_WAIT_CTX> object.
+If the argument is NULL, nothing is done.
+
=head1 RETURN VALUES
ASYNC_WAIT_CTX_new() returns a pointer to the newly allocated B<ASYNC_WAIT_CTX>
or NULL on error.
ASYNC_WAIT_CTX_set_wait_fd, ASYNC_WAIT_CTX_get_fd, ASYNC_WAIT_CTX_get_all_fds,
ASYNC_WAIT_CTX_get_changed_fds, ASYNC_WAIT_CTX_clear_fd,
ASYNC_WAIT_CTX_set_callback, ASYNC_WAIT_CTX_get_callback and
ASYNC_WAIT_CTX_set_status all return 1 on success or 0 on error.
ASYNC_WAIT_CTX_get_status() returns the engine status.
=head1 NOTES
On Windows platforms the F<< <openssl/async.h> >> header is dependent on some
of the types customarily made available by including F<< <windows.h> >>. The
application developer is likely to require control over when the latter
is included, commonly as one of the first included headers. Therefore,
it is defined as an application developer's responsibility to include
F<< <windows.h> >> prior to F<< <openssl/async.h> >>.
=head1 SEE ALSO
L<crypto(7)>, L<ASYNC_start_job(3)>
=head1 HISTORY
ASYNC_WAIT_CTX_new(), ASYNC_WAIT_CTX_free(), ASYNC_WAIT_CTX_set_wait_fd(),
ASYNC_WAIT_CTX_get_fd(), ASYNC_WAIT_CTX_get_all_fds(),
ASYNC_WAIT_CTX_get_changed_fds() and ASYNC_WAIT_CTX_clear_fd()
were added in OpenSSL 1.1.0.
ASYNC_WAIT_CTX_set_callback(), ASYNC_WAIT_CTX_get_callback(),
ASYNC_WAIT_CTX_set_status(), and ASYNC_WAIT_CTX_get_status()
were added 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/man3/BIO_ADDR.pod b/crypto/openssl/doc/man3/BIO_ADDR.pod
index 5ab88622cee0..12ec84d15ca0 100644
--- a/crypto/openssl/doc/man3/BIO_ADDR.pod
+++ b/crypto/openssl/doc/man3/BIO_ADDR.pod
@@ -1,125 +1,126 @@
=pod
=head1 NAME
BIO_ADDR, BIO_ADDR_new, BIO_ADDR_clear, BIO_ADDR_free, BIO_ADDR_rawmake,
BIO_ADDR_family, BIO_ADDR_rawaddress, BIO_ADDR_rawport,
BIO_ADDR_hostname_string, BIO_ADDR_service_string,
BIO_ADDR_path_string - BIO_ADDR routines
=head1 SYNOPSIS
#include <sys/types.h>
#include <openssl/bio.h>
typedef union bio_addr_st BIO_ADDR;
BIO_ADDR *BIO_ADDR_new(void);
void BIO_ADDR_free(BIO_ADDR *);
void BIO_ADDR_clear(BIO_ADDR *ap);
int BIO_ADDR_rawmake(BIO_ADDR *ap, int family,
const void *where, size_t wherelen, unsigned short port);
int BIO_ADDR_family(const BIO_ADDR *ap);
int BIO_ADDR_rawaddress(const BIO_ADDR *ap, void *p, size_t *l);
unsigned short BIO_ADDR_rawport(const BIO_ADDR *ap);
char *BIO_ADDR_hostname_string(const BIO_ADDR *ap, int numeric);
char *BIO_ADDR_service_string(const BIO_ADDR *ap, int numeric);
char *BIO_ADDR_path_string(const BIO_ADDR *ap);
=head1 DESCRIPTION
The B<BIO_ADDR> type is a wrapper around all types of socket
addresses that OpenSSL deals with, currently transparently
supporting AF_INET, AF_INET6 and AF_UNIX according to what's
available on the platform at hand.
BIO_ADDR_new() creates a new unfilled B<BIO_ADDR>, to be used
with routines that will fill it with information, such as
BIO_accept_ex().
BIO_ADDR_free() frees a B<BIO_ADDR> created with BIO_ADDR_new().
+If the argument is NULL, nothing is done.
BIO_ADDR_clear() clears any data held within the provided B<BIO_ADDR> and sets
it back to an uninitialised state.
BIO_ADDR_rawmake() takes a protocol B<family>, a byte array of
size B<wherelen> with an address in network byte order pointed at
by B<where> and a port number in network byte order in B<port> (except
for the B<AF_UNIX> protocol family, where B<port> is meaningless and
therefore ignored) and populates the given B<BIO_ADDR> with them.
In case this creates a B<AF_UNIX> B<BIO_ADDR>, B<wherelen> is expected
to be the length of the path string (not including the terminating
NUL, such as the result of a call to strlen()).
Read on about the addresses in L</RAW ADDRESSES> below.
BIO_ADDR_family() returns the protocol family of the given
B<BIO_ADDR>. The possible non-error results are one of the
constants AF_INET, AF_INET6 and AF_UNIX. It will also return AF_UNSPEC if the
BIO_ADDR has not been initialised.
BIO_ADDR_rawaddress() will write the raw address of the given
B<BIO_ADDR> in the area pointed at by B<p> if B<p> is non-NULL,
and will set B<*l> to be the amount of bytes the raw address
takes up if B<l> is non-NULL.
A technique to only find out the size of the address is a call
with B<p> set to B<NULL>. The raw address will be in network byte
order, most significant byte first.
In case this is a B<AF_UNIX> B<BIO_ADDR>, B<l> gets the length of the
path string (not including the terminating NUL, such as the result of
a call to strlen()).
Read on about the addresses in L</RAW ADDRESSES> below.
BIO_ADDR_rawport() returns the raw port of the given B<BIO_ADDR>.
The raw port will be in network byte order.
BIO_ADDR_hostname_string() returns a character string with the
hostname of the given B<BIO_ADDR>. If B<numeric> is 1, the string
will contain the numerical form of the address. This only works for
B<BIO_ADDR> of the protocol families AF_INET and AF_INET6. The
returned string has been allocated on the heap and must be freed
with OPENSSL_free().
BIO_ADDR_service_string() returns a character string with the
service name of the port of the given B<BIO_ADDR>. If B<numeric>
is 1, the string will contain the port number. This only works
for B<BIO_ADDR> of the protocol families AF_INET and AF_INET6. The
returned string has been allocated on the heap and must be freed
with OPENSSL_free().
BIO_ADDR_path_string() returns a character string with the path
of the given B<BIO_ADDR>. This only works for B<BIO_ADDR> of the
protocol family AF_UNIX. The returned string has been allocated
on the heap and must be freed with OPENSSL_free().
=head1 RAW ADDRESSES
Both BIO_ADDR_rawmake() and BIO_ADDR_rawaddress() take a pointer to a
network byte order address of a specific site. Internally, those are
treated as a pointer to B<struct in_addr> (for B<AF_INET>), B<struct
in6_addr> (for B<AF_INET6>) or B<char *> (for B<AF_UNIX>), all
depending on the protocol family the address is for.
=head1 RETURN VALUES
The string producing functions BIO_ADDR_hostname_string(),
BIO_ADDR_service_string() and BIO_ADDR_path_string() will
return B<NULL> on error and leave an error indication on the
OpenSSL error stack.
All other functions described here return 0 or B<NULL> when the
information they should return isn't available.
=head1 SEE ALSO
L<BIO_connect(3)>, L<BIO_s_connect(3)>
=head1 COPYRIGHT
-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 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/BIO_ADDRINFO.pod b/crypto/openssl/doc/man3/BIO_ADDRINFO.pod
index 626052e7f8b9..71a14ff4f0d7 100644
--- a/crypto/openssl/doc/man3/BIO_ADDRINFO.pod
+++ b/crypto/openssl/doc/man3/BIO_ADDRINFO.pod
@@ -1,113 +1,113 @@
=pod
=head1 NAME
BIO_lookup_type,
BIO_ADDRINFO, BIO_ADDRINFO_next, BIO_ADDRINFO_free,
BIO_ADDRINFO_family, BIO_ADDRINFO_socktype, BIO_ADDRINFO_protocol,
BIO_ADDRINFO_address,
BIO_lookup_ex,
BIO_lookup
- BIO_ADDRINFO type and routines
=head1 SYNOPSIS
#include <sys/types.h>
#include <openssl/bio.h>
typedef union bio_addrinfo_st BIO_ADDRINFO;
enum BIO_lookup_type {
BIO_LOOKUP_CLIENT, BIO_LOOKUP_SERVER
};
int BIO_lookup_ex(const char *host, const char *service, int lookup_type,
int family, int socktype, int protocol, BIO_ADDRINFO **res);
int BIO_lookup(const char *host, const char *service,
enum BIO_lookup_type lookup_type,
int family, int socktype, BIO_ADDRINFO **res);
const BIO_ADDRINFO *BIO_ADDRINFO_next(const BIO_ADDRINFO *bai);
int BIO_ADDRINFO_family(const BIO_ADDRINFO *bai);
int BIO_ADDRINFO_socktype(const BIO_ADDRINFO *bai);
int BIO_ADDRINFO_protocol(const BIO_ADDRINFO *bai);
const BIO_ADDR *BIO_ADDRINFO_address(const BIO_ADDRINFO *bai);
void BIO_ADDRINFO_free(BIO_ADDRINFO *bai);
=head1 DESCRIPTION
The B<BIO_ADDRINFO> type is a wrapper for address information
types provided on your platform.
B<BIO_ADDRINFO> normally forms a chain of several that can be
picked at one by one.
BIO_lookup_ex() looks up a specified B<host> and B<service>, and
uses B<lookup_type> to determine what the default address should
be if B<host> is B<NULL>. B<family>, B<socktype> and B<protocol> are used to
determine what protocol family, socket type and protocol should be used for
the lookup. B<family> can be any of AF_INET, AF_INET6, AF_UNIX and
AF_UNSPEC. B<socktype> can be SOCK_STREAM, SOCK_DGRAM or 0. Specifying 0
indicates that any type can be used. B<protocol> specifies a protocol such as
IPPROTO_TCP, IPPROTO_UDP or IPPORTO_SCTP. If set to 0 than any protocol can be
used. B<res> points at a pointer to hold the start of a B<BIO_ADDRINFO>
chain.
For the family B<AF_UNIX>, BIO_lookup_ex() will ignore the B<service>
parameter and expects the B<host> parameter to hold the path to the socket file.
BIO_lookup() does the same as BIO_lookup_ex() but does not provide the ability
to select based on the protocol (any protocol may be returned).
BIO_ADDRINFO_family() returns the family of the given
B<BIO_ADDRINFO>. The result will be one of the constants
AF_INET, AF_INET6 and AF_UNIX.
BIO_ADDRINFO_socktype() returns the socket type of the given
B<BIO_ADDRINFO>. The result will be one of the constants
SOCK_STREAM and SOCK_DGRAM.
BIO_ADDRINFO_protocol() returns the protocol id of the given
B<BIO_ADDRINFO>. The result will be one of the constants
IPPROTO_TCP and IPPROTO_UDP.
BIO_ADDRINFO_address() returns the underlying B<BIO_ADDR>
of the given B<BIO_ADDRINFO>.
BIO_ADDRINFO_next() returns the next B<BIO_ADDRINFO> in the chain
from the given one.
BIO_ADDRINFO_free() frees the chain of B<BIO_ADDRINFO> starting
-with the given one.
+with the given one. If the argument is NULL, nothing is done.
=head1 RETURN VALUES
BIO_lookup_ex() and BIO_lookup() return 1 on success and 0 when an error
occurred, and will leave an error indication on the OpenSSL error stack in that
case.
All other functions described here return 0 or B<NULL> when the
information they should return isn't available.
=head1 NOTES
The BIO_lookup_ex() implementation uses the platform provided getaddrinfo()
function. On Linux it is known that specifying 0 for the protocol will not
return any SCTP based addresses when calling getaddrinfo(). Therefore, if an SCTP
address is required then the B<protocol> parameter to BIO_lookup_ex() should be
explicitly set to IPPROTO_SCTP. The same may be true on other platforms.
=head1 HISTORY
The BIO_lookup_ex() function was added in OpenSSL 1.1.1.
=head1 COPYRIGHT
-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
L<https://www.openssl.org/source/license.html>.
=cut
diff --git a/crypto/openssl/doc/man3/BIO_f_base64.pod b/crypto/openssl/doc/man3/BIO_f_base64.pod
index c865f0a17ac1..c951d4926190 100644
--- a/crypto/openssl/doc/man3/BIO_f_base64.pod
+++ b/crypto/openssl/doc/man3/BIO_f_base64.pod
@@ -1,103 +1,105 @@
=pod
=head1 NAME
BIO_f_base64 - base64 BIO filter
=head1 SYNOPSIS
=for openssl multiple includes
#include <openssl/bio.h>
#include <openssl/evp.h>
const BIO_METHOD *BIO_f_base64(void);
=head1 DESCRIPTION
BIO_f_base64() returns the base64 BIO method. This is a filter
BIO that base64 encodes any data written through it and decodes
any data read through it.
Base64 BIOs do not support BIO_gets() or BIO_puts().
-For writing, output is by default divided to lines of length 64
-characters and there is always a newline at the end of output.
+For writing, by default output is divided to lines of length 64
+characters and there is a newline at the end of output.
+This behavior can be changed with B<BIO_FLAGS_BASE64_NO_NL> flag.
-For reading, first line should be at most 1024
-characters long. If it is longer then it is ignored completely.
-Other input lines can be of any length. There must be a newline
-at the end of input.
-
-This behavior can be changed with BIO_FLAGS_BASE64_NO_NL flag.
+For reading, first line should be at most 1024 bytes long including newline
+unless the flag B<BIO_FLAGS_BASE64_NO_NL> is set.
+Further input lines can be of any length (i.e., newlines may appear anywhere
+in the input) and a newline at the end of input is not needed.
BIO_flush() on a base64 BIO that is being written through is
used to signal that no more data is to be encoded: this is used
to flush the final block through the BIO.
-The flag BIO_FLAGS_BASE64_NO_NL can be set with BIO_set_flags().
+The flag B<BIO_FLAGS_BASE64_NO_NL> can be set with BIO_set_flags().
For writing, it causes all data to be written on one line without
newline at the end.
-For reading, it expects the data to be all on one line (with or
-without a trailing newline).
+For reading, it removes all expectations on newlines in the input data.
=head1 NOTES
Because of the format of base64 encoding the end of the encoded
block cannot always be reliably determined.
=head1 RETURN VALUES
BIO_f_base64() returns the base64 BIO method.
=head1 EXAMPLES
Base64 encode the string "Hello World\n" and write the result
to standard output:
BIO *bio, *b64;
char message[] = "Hello World \n";
b64 = BIO_new(BIO_f_base64());
bio = BIO_new_fp(stdout, BIO_NOCLOSE);
BIO_push(b64, bio);
BIO_write(b64, message, strlen(message));
BIO_flush(b64);
BIO_free_all(b64);
Read Base64 encoded data from standard input and write the decoded
data to standard output:
BIO *bio, *b64, *bio_out;
char inbuf[512];
int inlen;
b64 = BIO_new(BIO_f_base64());
bio = BIO_new_fp(stdin, BIO_NOCLOSE);
bio_out = BIO_new_fp(stdout, BIO_NOCLOSE);
BIO_push(b64, bio);
while ((inlen = BIO_read(b64, inbuf, 512)) > 0)
BIO_write(bio_out, inbuf, inlen);
BIO_flush(bio_out);
BIO_free_all(b64);
=head1 BUGS
+On decoding, if the flag B<BIO_FLAGS_BASE64_NO_NL> is not set and
+the first 1024 bytes of input do not include a newline character
+the first two lines of input are ignored.
+
The ambiguity of EOF in base64 encoded data can cause additional
data following the base64 encoded block to be misinterpreted.
There should be some way of specifying a test that the BIO can perform
to reliably determine EOF (for example a MIME boundary).
=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/BIO_meth_new.pod b/crypto/openssl/doc/man3/BIO_meth_new.pod
index 86301b97189f..d626277c03b1 100644
--- a/crypto/openssl/doc/man3/BIO_meth_new.pod
+++ b/crypto/openssl/doc/man3/BIO_meth_new.pod
@@ -1,167 +1,167 @@
=pod
=head1 NAME
BIO_get_new_index,
BIO_meth_new, BIO_meth_free, BIO_meth_get_read_ex, BIO_meth_set_read_ex,
BIO_meth_get_write_ex, BIO_meth_set_write_ex, BIO_meth_get_write,
BIO_meth_set_write, BIO_meth_get_read, BIO_meth_set_read, BIO_meth_get_puts,
BIO_meth_set_puts, BIO_meth_get_gets, BIO_meth_set_gets, BIO_meth_get_ctrl,
BIO_meth_set_ctrl, BIO_meth_get_create, BIO_meth_set_create,
BIO_meth_get_destroy, BIO_meth_set_destroy, BIO_meth_get_callback_ctrl,
BIO_meth_set_callback_ctrl - Routines to build up BIO methods
=head1 SYNOPSIS
#include <openssl/bio.h>
int BIO_get_new_index(void);
BIO_METHOD *BIO_meth_new(int type, const char *name);
void BIO_meth_free(BIO_METHOD *biom);
int (*BIO_meth_get_write_ex(const BIO_METHOD *biom))(BIO *, const char *, size_t,
size_t *);
int (*BIO_meth_get_write(const BIO_METHOD *biom))(BIO *, const char *, int);
int BIO_meth_set_write_ex(BIO_METHOD *biom,
int (*bwrite)(BIO *, const char *, size_t, size_t *));
int BIO_meth_set_write(BIO_METHOD *biom,
int (*write)(BIO *, const char *, int));
int (*BIO_meth_get_read_ex(const BIO_METHOD *biom))(BIO *, char *, size_t, size_t *);
int (*BIO_meth_get_read(const BIO_METHOD *biom))(BIO *, char *, int);
int BIO_meth_set_read_ex(BIO_METHOD *biom,
int (*bread)(BIO *, char *, size_t, size_t *));
int BIO_meth_set_read(BIO_METHOD *biom, int (*read)(BIO *, char *, int));
int (*BIO_meth_get_puts(const BIO_METHOD *biom))(BIO *, const char *);
int BIO_meth_set_puts(BIO_METHOD *biom, int (*puts)(BIO *, const char *));
int (*BIO_meth_get_gets(const BIO_METHOD *biom))(BIO *, char *, int);
int BIO_meth_set_gets(BIO_METHOD *biom,
int (*gets)(BIO *, char *, int));
long (*BIO_meth_get_ctrl(const BIO_METHOD *biom))(BIO *, int, long, void *);
int BIO_meth_set_ctrl(BIO_METHOD *biom,
long (*ctrl)(BIO *, int, long, void *));
int (*BIO_meth_get_create(const BIO_METHOD *bion))(BIO *);
int BIO_meth_set_create(BIO_METHOD *biom, int (*create)(BIO *));
int (*BIO_meth_get_destroy(const BIO_METHOD *biom))(BIO *);
int BIO_meth_set_destroy(BIO_METHOD *biom, int (*destroy)(BIO *));
long (*BIO_meth_get_callback_ctrl(const BIO_METHOD *biom))(BIO *, int, BIO_info_cb *);
int BIO_meth_set_callback_ctrl(BIO_METHOD *biom,
long (*callback_ctrl)(BIO *, int, BIO_info_cb *));
=head1 DESCRIPTION
The B<BIO_METHOD> type is a structure used for the implementation of new BIO
types. It provides a set of functions used by OpenSSL for the implementation
of the various BIO capabilities. See the L<bio(7)> page for more information.
BIO_meth_new() creates a new B<BIO_METHOD> structure. It should be given a
unique integer B<type> and a string that represents its B<name>.
Use BIO_get_new_index() to get the value for B<type>.
The set of
standard OpenSSL provided BIO types is provided in F<< <openssl/bio.h> >>.
Some examples include B<BIO_TYPE_BUFFER> and B<BIO_TYPE_CIPHER>. Filter BIOs
should have a type which have the "filter" bit set (B<BIO_TYPE_FILTER>).
Source/sink BIOs should have the "source/sink" bit set (B<BIO_TYPE_SOURCE_SINK>).
File descriptor based BIOs (e.g. socket, fd, connect, accept etc) should
additionally have the "descriptor" bit set (B<BIO_TYPE_DESCRIPTOR>). See the
L<BIO_find_type(3)> page for more information.
BIO_meth_free() destroys a B<BIO_METHOD> structure and frees up any memory
-associated with it.
+associated with it. If the argument is NULL, nothing is done.
BIO_meth_get_write_ex() and BIO_meth_set_write_ex() get and set the function
used for writing arbitrary length data to the BIO respectively. This function
will be called in response to the application calling BIO_write_ex() or
BIO_write(). The parameters for the function have the same meaning as for
BIO_write_ex(). Older code may call BIO_meth_get_write() and
BIO_meth_set_write() instead. Applications should not call both
BIO_meth_set_write_ex() and BIO_meth_set_write() or call BIO_meth_get_write()
when the function was set with BIO_meth_set_write_ex().
BIO_meth_get_read_ex() and BIO_meth_set_read_ex() get and set the function used
for reading arbitrary length data from the BIO respectively. This function will
be called in response to the application calling BIO_read_ex() or BIO_read().
The parameters for the function have the same meaning as for BIO_read_ex().
Older code may call BIO_meth_get_read() and BIO_meth_set_read() instead.
Applications should not call both BIO_meth_set_read_ex() and BIO_meth_set_read()
or call BIO_meth_get_read() when the function was set with
BIO_meth_set_read_ex().
BIO_meth_get_puts() and BIO_meth_set_puts() get and set the function used for
writing a NULL terminated string to the BIO respectively. This function will be
called in response to the application calling BIO_puts(). The parameters for
the function have the same meaning as for BIO_puts().
BIO_meth_get_gets() and BIO_meth_set_gets() get and set the function typically
used for reading a line of data from the BIO respectively (see the L<BIO_gets(3)>
page for more information). This function will be called in response to the
application calling BIO_gets(). The parameters for the function have the same
meaning as for BIO_gets().
BIO_meth_get_ctrl() and BIO_meth_set_ctrl() get and set the function used for
processing ctrl messages in the BIO respectively. See the L<BIO_ctrl(3)> page for
more information. This function will be called in response to the application
calling BIO_ctrl(). The parameters for the function have the same meaning as for
BIO_ctrl().
BIO_meth_get_create() and BIO_meth_set_create() get and set the function used
for creating a new instance of the BIO respectively. This function will be
called in response to the application calling BIO_new() and passing
in a pointer to the current BIO_METHOD. The BIO_new() function will allocate the
memory for the new BIO, and a pointer to this newly allocated structure will
be passed as a parameter to the function. If a create function is set,
BIO_new() will not mark the BIO as initialised on allocation.
L<BIO_set_init(3)> must then be called either by the create function, or later,
by a BIO ctrl function, once BIO initialisation is complete.
BIO_meth_get_destroy() and BIO_meth_set_destroy() get and set the function used
for destroying an instance of a BIO respectively. This function will be
called in response to the application calling BIO_free(). A pointer to the BIO
to be destroyed is passed as a parameter. The destroy function should be used
for BIO specific clean up. The memory for the BIO itself should not be freed by
this function.
BIO_meth_get_callback_ctrl() and BIO_meth_set_callback_ctrl() get and set the
function used for processing callback ctrl messages in the BIO respectively. See
the L<BIO_callback_ctrl(3)> page for more information. This function will be called
in response to the application calling BIO_callback_ctrl(). The parameters for
the function have the same meaning as for BIO_callback_ctrl().
=head1 RETURN VALUES
BIO_get_new_index() returns the new BIO type value or -1 if an error occurred.
BIO_meth_new(int type, const char *name) returns a valid B<BIO_METHOD> or NULL
if an error occurred.
The B<BIO_meth_set> functions return 1 on success or 0 on error.
The B<BIO_meth_get> functions return the corresponding function pointers.
=head1 SEE ALSO
L<bio(7)>, L<BIO_find_type(3)>, L<BIO_ctrl(3)>, L<BIO_read_ex(3)>, L<BIO_new(3)>
=head1 HISTORY
The functions described here were added in OpenSSL 1.1.0.
=head1 COPYRIGHT
-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
L<https://www.openssl.org/source/license.html>.
=cut
diff --git a/crypto/openssl/doc/man3/BN_add.pod b/crypto/openssl/doc/man3/BN_add.pod
index 35cfdd1495fd..46966d996379 100644
--- a/crypto/openssl/doc/man3/BN_add.pod
+++ b/crypto/openssl/doc/man3/BN_add.pod
@@ -1,145 +1,145 @@
=pod
=head1 NAME
BN_add, BN_sub, BN_mul, BN_sqr, BN_div, BN_mod, BN_nnmod, BN_mod_add,
BN_mod_sub, BN_mod_mul, BN_mod_sqr, BN_mod_sqrt, BN_exp, BN_mod_exp, BN_gcd -
arithmetic operations on BIGNUMs
=head1 SYNOPSIS
#include <openssl/bn.h>
int BN_add(BIGNUM *r, const BIGNUM *a, const BIGNUM *b);
int BN_sub(BIGNUM *r, const BIGNUM *a, const BIGNUM *b);
- int BN_mul(BIGNUM *r, BIGNUM *a, BIGNUM *b, BN_CTX *ctx);
+ int BN_mul(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, BN_CTX *ctx);
- int BN_sqr(BIGNUM *r, BIGNUM *a, BN_CTX *ctx);
+ int BN_sqr(BIGNUM *r, const BIGNUM *a, BN_CTX *ctx);
int BN_div(BIGNUM *dv, BIGNUM *rem, const BIGNUM *a, const BIGNUM *d,
BN_CTX *ctx);
int BN_mod(BIGNUM *rem, const BIGNUM *a, const BIGNUM *m, BN_CTX *ctx);
int BN_nnmod(BIGNUM *r, const BIGNUM *a, const BIGNUM *m, BN_CTX *ctx);
- int BN_mod_add(BIGNUM *r, BIGNUM *a, BIGNUM *b, const BIGNUM *m,
+ int BN_mod_add(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, const BIGNUM *m,
BN_CTX *ctx);
- int BN_mod_sub(BIGNUM *r, BIGNUM *a, BIGNUM *b, const BIGNUM *m,
+ int BN_mod_sub(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, const BIGNUM *m,
BN_CTX *ctx);
- int BN_mod_mul(BIGNUM *r, BIGNUM *a, BIGNUM *b, const BIGNUM *m,
+ int BN_mod_mul(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, const BIGNUM *m,
BN_CTX *ctx);
- int BN_mod_sqr(BIGNUM *r, BIGNUM *a, const BIGNUM *m, BN_CTX *ctx);
+ int BN_mod_sqr(BIGNUM *r, const BIGNUM *a, const BIGNUM *m, BN_CTX *ctx);
- BIGNUM *BN_mod_sqrt(BIGNUM *in, BIGNUM *a, const BIGNUM *p, BN_CTX *ctx);
+ BIGNUM *BN_mod_sqrt(BIGNUM *in, const BIGNUM *a, const BIGNUM *p, BN_CTX *ctx);
- int BN_exp(BIGNUM *r, BIGNUM *a, BIGNUM *p, BN_CTX *ctx);
+ int BN_exp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, BN_CTX *ctx);
- int BN_mod_exp(BIGNUM *r, BIGNUM *a, const BIGNUM *p,
+ int BN_mod_exp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p,
const BIGNUM *m, BN_CTX *ctx);
- int BN_gcd(BIGNUM *r, BIGNUM *a, BIGNUM *b, BN_CTX *ctx);
+ int BN_gcd(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, BN_CTX *ctx);
=head1 DESCRIPTION
BN_add() adds I<a> and I<b> and places the result in I<r> (C<r=a+b>).
I<r> may be the same B<BIGNUM> as I<a> or I<b>.
BN_sub() subtracts I<b> from I<a> and places the result in I<r> (C<r=a-b>).
I<r> may be the same B<BIGNUM> as I<a> or I<b>.
BN_mul() multiplies I<a> and I<b> and places the result in I<r> (C<r=a*b>).
I<r> may be the same B<BIGNUM> as I<a> or I<b>.
For multiplication by powers of 2, use L<BN_lshift(3)>.
BN_sqr() takes the square of I<a> and places the result in I<r>
(C<r=a^2>). I<r> and I<a> may be the same B<BIGNUM>.
This function is faster than BN_mul(r,a,a).
BN_div() divides I<a> by I<d> and places the result in I<dv> and the
remainder in I<rem> (C<dv=a/d, rem=a%d>). Either of I<dv> and I<rem> may
be B<NULL>, in which case the respective value is not returned.
The result is rounded towards zero; thus if I<a> is negative, the
remainder will be zero or negative.
For division by powers of 2, use BN_rshift(3).
BN_mod() corresponds to BN_div() with I<dv> set to B<NULL>.
BN_nnmod() reduces I<a> modulo I<m> and places the nonnegative
remainder in I<r>.
BN_mod_add() adds I<a> to I<b> modulo I<m> and places the nonnegative
result in I<r>.
BN_mod_sub() subtracts I<b> from I<a> modulo I<m> and places the
nonnegative result in I<r>.
BN_mod_mul() multiplies I<a> by I<b> and finds the nonnegative
remainder respective to modulus I<m> (C<r=(a*b) mod m>). I<r> may be
the same B<BIGNUM> as I<a> or I<b>. For more efficient algorithms for
repeated computations using the same modulus, see
L<BN_mod_mul_montgomery(3)> and
L<BN_mod_mul_reciprocal(3)>.
BN_mod_sqr() takes the square of I<a> modulo B<m> and places the
result in I<r>.
BN_mod_sqrt() returns the modular square root of I<a> such that
C<in^2 = a (mod p)>. The modulus I<p> must be a
prime, otherwise an error or an incorrect "result" will be returned.
The result is stored into I<in> which can be NULL. The result will be
newly allocated in that case.
BN_exp() raises I<a> to the I<p>-th power and places the result in I<r>
(C<r=a^p>). This function is faster than repeated applications of
BN_mul().
BN_mod_exp() computes I<a> to the I<p>-th power modulo I<m> (C<r=a^p %
m>). This function uses less time and space than BN_exp(). Do not call this
function when B<m> is even and any of the parameters have the
B<BN_FLG_CONSTTIME> flag set.
BN_gcd() computes the greatest common divisor of I<a> and I<b> and
places the result in I<r>. I<r> may be the same B<BIGNUM> as I<a> or
I<b>.
For all functions, I<ctx> is a previously allocated B<BN_CTX> used for
temporary variables; see L<BN_CTX_new(3)>.
Unless noted otherwise, the result B<BIGNUM> must be different from
the arguments.
=head1 NOTES
For modular operations such as BN_nnmod() or BN_mod_exp() it is an error
to use the same B<BIGNUM> object for the modulus as for the output.
=head1 RETURN VALUES
The BN_mod_sqrt() returns the result (possibly incorrect if I<p> is
not a prime), or NULL.
For all remaining functions, 1 is returned for success, 0 on error. The return
value should always be checked (e.g., C<if (!BN_add(r,a,b)) goto err;>).
The error codes can be obtained by L<ERR_get_error(3)>.
=head1 SEE ALSO
L<ERR_get_error(3)>, L<BN_CTX_new(3)>,
L<BN_add_word(3)>, L<BN_set_bit(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/BN_generate_prime.pod b/crypto/openssl/doc/man3/BN_generate_prime.pod
index b536bcb3b781..accc8a749f0c 100644
--- a/crypto/openssl/doc/man3/BN_generate_prime.pod
+++ b/crypto/openssl/doc/man3/BN_generate_prime.pod
@@ -1,255 +1,256 @@
=pod
=head1 NAME
BN_generate_prime_ex2, BN_generate_prime_ex, BN_is_prime_ex, BN_check_prime,
BN_is_prime_fasttest_ex, BN_GENCB_call, BN_GENCB_new, BN_GENCB_free,
BN_GENCB_set_old, BN_GENCB_set, BN_GENCB_get_arg, BN_generate_prime,
BN_is_prime, BN_is_prime_fasttest - generate primes and test for primality
=head1 SYNOPSIS
#include <openssl/bn.h>
int BN_generate_prime_ex2(BIGNUM *ret, int bits, int safe,
const BIGNUM *add, const BIGNUM *rem, BN_GENCB *cb,
BN_CTX *ctx);
int BN_generate_prime_ex(BIGNUM *ret, int bits, int safe, const BIGNUM *add,
const BIGNUM *rem, BN_GENCB *cb);
int BN_check_prime(const BIGNUM *p, BN_CTX *ctx, BN_GENCB *cb);
int BN_GENCB_call(BN_GENCB *cb, int a, int b);
BN_GENCB *BN_GENCB_new(void);
void BN_GENCB_free(BN_GENCB *cb);
void BN_GENCB_set_old(BN_GENCB *gencb,
void (*callback)(int, int, void *), void *cb_arg);
void BN_GENCB_set(BN_GENCB *gencb,
int (*callback)(int, int, BN_GENCB *), void *cb_arg);
void *BN_GENCB_get_arg(BN_GENCB *cb);
The following functions have been deprecated since OpenSSL 0.9.8, and can be
hidden entirely by defining B<OPENSSL_API_COMPAT> with a suitable version value,
see L<openssl_user_macros(7)>:
BIGNUM *BN_generate_prime(BIGNUM *ret, int num, int safe, BIGNUM *add,
BIGNUM *rem, void (*callback)(int, int, void *),
void *cb_arg);
int BN_is_prime(const BIGNUM *p, int nchecks,
void (*callback)(int, int, void *), BN_CTX *ctx, void *cb_arg);
int BN_is_prime_fasttest(const BIGNUM *p, int nchecks,
void (*callback)(int, int, void *), BN_CTX *ctx,
void *cb_arg, int do_trial_division);
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)>:
int BN_is_prime_ex(const BIGNUM *p, int nchecks, BN_CTX *ctx, BN_GENCB *cb);
int BN_is_prime_fasttest_ex(const BIGNUM *p, int nchecks, BN_CTX *ctx,
int do_trial_division, BN_GENCB *cb);
=head1 DESCRIPTION
BN_generate_prime_ex2() generates a pseudo-random prime number of
at least bit length B<bits> using the BN_CTX provided in B<ctx>. The value of
B<ctx> must not be NULL.
The returned number is probably prime with a negligible error.
The maximum error rate is 2^-128.
It's 2^-287 for a 512 bit prime, 2^-435 for a 1024 bit prime,
2^-648 for a 2048 bit prime, and lower than 2^-882 for primes larger
than 2048 bit.
If B<add> is B<NULL> the returned prime number will have exact bit
length B<bits> with the top most two bits set.
If B<ret> is not B<NULL>, it will be used to store the number.
If B<cb> is not B<NULL>, it is used as follows:
=over 2
=item *
B<BN_GENCB_call(cb, 0, i)> is called after generating the i-th
potential prime number.
=item *
While the number is being tested for primality,
B<BN_GENCB_call(cb, 1, j)> is called as described below.
=item *
When a prime has been found, B<BN_GENCB_call(cb, 2, i)> is called.
=item *
The callers of BN_generate_prime_ex() may call B<BN_GENCB_call(cb, i, j)> with
other values as described in their respective man pages; see L</SEE ALSO>.
=back
The prime may have to fulfill additional requirements for use in
Diffie-Hellman key exchange:
If B<add> is not B<NULL>, the prime will fulfill the condition p % B<add>
== B<rem> (p % B<add> == 1 if B<rem> == B<NULL>) in order to suit a given
generator.
If B<safe> is true, it will be a safe prime (i.e. a prime p so
that (p-1)/2 is also prime). If B<safe> is true, and B<rem> == B<NULL>
the condition will be p % B<add> == 3.
It is recommended that B<add> is a multiple of 4.
The random generator must be seeded prior to calling BN_generate_prime_ex().
If the automatic seeding or reseeding of the OpenSSL CSPRNG fails due to
external circumstances (see L<RAND(7)>), the operation will fail.
The random number generator configured for the OSSL_LIB_CTX associated with
B<ctx> will be used.
BN_generate_prime_ex() is the same as BN_generate_prime_ex2() except that no
B<ctx> parameter is passed.
In this case the random number generator associated with the default OSSL_LIB_CTX
will be used.
BN_check_prime(), BN_is_prime_ex(), BN_is_prime_fasttest_ex(), BN_is_prime()
and BN_is_prime_fasttest() test if the number B<p> is prime.
The functions tests until one of the tests shows that B<p> is composite,
or all the tests passed.
If B<p> passes all these tests, it is considered a probable prime.
The test performed on B<p> are trial division by a number of small primes
and rounds of the of the Miller-Rabin probabilistic primality test.
The functions do at least 64 rounds of the Miller-Rabin test giving a maximum
false positive rate of 2^-128.
If the size of B<p> is more than 2048 bits, they do at least 128 rounds
giving a maximum false positive rate of 2^-256.
If B<nchecks> is larger than the minimum above (64 or 128), B<nchecks>
rounds of the Miller-Rabin test will be done.
If B<do_trial_division> set to B<0>, the trial division will be skipped.
BN_is_prime_ex() and BN_is_prime() always skip the trial division.
BN_is_prime_ex(), BN_is_prime_fasttest_ex(), BN_is_prime()
and BN_is_prime_fasttest() are deprecated.
BN_is_prime_fasttest() and BN_is_prime() behave just like
BN_is_prime_fasttest_ex() and BN_is_prime_ex() respectively, but with the old
style call back.
B<ctx> is a preallocated B<BN_CTX> (to save the overhead of allocating and
freeing the structure in a loop), or B<NULL>.
If the trial division is done, and no divisors are found and B<cb>
is not B<NULL>, B<BN_GENCB_call(cb, 1, -1)> is called.
After each round of the Miller-Rabin probabilistic primality test,
if B<cb> is not B<NULL>, B<BN_GENCB_call(cb, 1, j)> is called
with B<j> the iteration (j = 0, 1, ...).
BN_GENCB_call() calls the callback function held in the B<BN_GENCB> structure
and passes the ints B<a> and B<b> as arguments. There are two types of
B<BN_GENCB> structure that are supported: "new" style and "old" style. New
programs should prefer the "new" style, whilst the "old" style is provided
for backwards compatibility purposes.
A B<BN_GENCB> structure should be created through a call to BN_GENCB_new(),
-and freed through a call to BN_GENCB_free().
+and freed through a call to BN_GENCB_free(). If the argument is NULL,
+nothing is done.
For "new" style callbacks a BN_GENCB structure should be initialised with a
call to BN_GENCB_set(), where B<gencb> is a B<BN_GENCB *>, B<callback> is of
type B<int (*callback)(int, int, BN_GENCB *)> and B<cb_arg> is a B<void *>.
"Old" style callbacks are the same except they are initialised with a call
to BN_GENCB_set_old() and B<callback> is of type
B<void (*callback)(int, int, void *)>.
A callback is invoked through a call to B<BN_GENCB_call>. This will check
the type of the callback and will invoke B<callback(a, b, gencb)> for new
style callbacks or B<callback(a, b, cb_arg)> for old style.
It is possible to obtain the argument associated with a BN_GENCB structure
(set via a call to BN_GENCB_set or BN_GENCB_set_old) using BN_GENCB_get_arg.
BN_generate_prime() (deprecated) works in the same way as
BN_generate_prime_ex() but expects an old-style callback function
directly in the B<callback> parameter, and an argument to pass to it in
the B<cb_arg>. BN_is_prime() and BN_is_prime_fasttest()
can similarly be compared to BN_is_prime_ex() and
BN_is_prime_fasttest_ex(), respectively.
=head1 RETURN VALUES
BN_generate_prime_ex() return 1 on success or 0 on error.
BN_is_prime_ex(), BN_is_prime_fasttest_ex(), BN_is_prime(),
BN_is_prime_fasttest() and BN_check_prime return 0 if the number is composite,
1 if it is prime with an error probability of less than 0.25^B<nchecks>, and
-1 on error.
BN_generate_prime() returns the prime number on success, B<NULL> otherwise.
BN_GENCB_new returns a pointer to a BN_GENCB structure on success, or B<NULL>
otherwise.
BN_GENCB_get_arg returns the argument previously associated with a BN_GENCB
structure.
Callback functions should return 1 on success or 0 on error.
The error codes can be obtained by L<ERR_get_error(3)>.
=head1 REMOVED FUNCTIONALITY
As of OpenSSL 1.1.0 it is no longer possible to create a BN_GENCB structure
directly, as in:
BN_GENCB callback;
Instead applications should create a BN_GENCB structure using BN_GENCB_new:
BN_GENCB *callback;
callback = BN_GENCB_new();
if (!callback)
/* error */
...
BN_GENCB_free(callback);
=head1 SEE ALSO
L<DH_generate_parameters(3)>, L<DSA_generate_parameters(3)>,
L<RSA_generate_key(3)>, L<ERR_get_error(3)>, L<RAND_bytes(3)>,
L<RAND(7)>
=head1 HISTORY
The BN_is_prime_ex() and BN_is_prime_fasttest_ex() functions were
deprecated in OpenSSL 3.0.
The BN_GENCB_new(), BN_GENCB_free(),
and BN_GENCB_get_arg() functions were added in OpenSSL 1.1.0.
BN_check_prime() was 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/man3/BN_set_bit.pod b/crypto/openssl/doc/man3/BN_set_bit.pod
index 349ef9e0562c..ddc27d0c407a 100644
--- a/crypto/openssl/doc/man3/BN_set_bit.pod
+++ b/crypto/openssl/doc/man3/BN_set_bit.pod
@@ -1,69 +1,72 @@
=pod
=head1 NAME
BN_set_bit, BN_clear_bit, BN_is_bit_set, BN_mask_bits, BN_lshift,
BN_lshift1, BN_rshift, BN_rshift1 - bit operations on BIGNUMs
=head1 SYNOPSIS
#include <openssl/bn.h>
int BN_set_bit(BIGNUM *a, int n);
int BN_clear_bit(BIGNUM *a, int n);
int BN_is_bit_set(const BIGNUM *a, int n);
int BN_mask_bits(BIGNUM *a, int n);
int BN_lshift(BIGNUM *r, const BIGNUM *a, int n);
int BN_lshift1(BIGNUM *r, BIGNUM *a);
int BN_rshift(BIGNUM *r, BIGNUM *a, int n);
int BN_rshift1(BIGNUM *r, BIGNUM *a);
=head1 DESCRIPTION
BN_set_bit() sets bit B<n> in B<a> to 1 (C<a|=(1E<lt>E<lt>n)>). The
number is expanded if necessary.
BN_clear_bit() sets bit B<n> in B<a> to 0 (C<a&=~(1E<lt>E<lt>n)>). An
error occurs if B<a> is shorter than B<n> bits.
BN_is_bit_set() tests if bit B<n> in B<a> is set.
BN_mask_bits() truncates B<a> to an B<n> bit number
-(C<a&=~((~0)E<lt>E<lt>n)>). An error occurs if B<a> already is
-shorter than B<n> bits.
+(C<a&=~((~0)E<lt>E<lt>n)>). An error occurs if B<n> is negative. An error is
+also returned if the internal representation of B<a> is already shorter than
+B<n> bits. The internal representation depends on the platform's word size, and
+this error can be safely ignored. Use L<BN_num_bits(3)> to determine the exact
+number of bits if needed.
BN_lshift() shifts B<a> left by B<n> bits and places the result in
B<r> (C<r=a*2^n>). Note that B<n> must be nonnegative. BN_lshift1() shifts
B<a> left by one and places the result in B<r> (C<r=2*a>).
BN_rshift() shifts B<a> right by B<n> bits and places the result in
B<r> (C<r=a/2^n>). Note that B<n> must be nonnegative. BN_rshift1() shifts
B<a> right by one and places the result in B<r> (C<r=a/2>).
For the shift functions, B<r> and B<a> may be the same variable.
=head1 RETURN VALUES
BN_is_bit_set() returns 1 if the bit is set, 0 otherwise.
All other functions return 1 for success, 0 on error. The error codes
can be obtained by L<ERR_get_error(3)>.
=head1 SEE ALSO
L<BN_num_bytes(3)>, L<BN_add(3)>
=head1 COPYRIGHT
-Copyright 2000-2020 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/BUF_MEM_new.pod b/crypto/openssl/doc/man3/BUF_MEM_new.pod
index 262e18f31bfe..79de43a1df9a 100644
--- a/crypto/openssl/doc/man3/BUF_MEM_new.pod
+++ b/crypto/openssl/doc/man3/BUF_MEM_new.pod
@@ -1,75 +1,76 @@
=pod
=head1 NAME
BUF_MEM_new, BUF_MEM_new_ex, BUF_MEM_free, BUF_MEM_grow,
BUF_MEM_grow_clean, BUF_reverse
- simple character array structure
=head1 SYNOPSIS
#include <openssl/buffer.h>
BUF_MEM *BUF_MEM_new(void);
BUF_MEM *BUF_MEM_new_ex(unsigned long flags);
void BUF_MEM_free(BUF_MEM *a);
int BUF_MEM_grow(BUF_MEM *str, int len);
size_t BUF_MEM_grow_clean(BUF_MEM *str, size_t len);
void BUF_reverse(unsigned char *out, const unsigned char *in, size_t size);
=head1 DESCRIPTION
The buffer library handles simple character arrays. Buffers are used for
various purposes in the library, most notably memory BIOs.
BUF_MEM_new() allocates a new buffer of zero size.
BUF_MEM_new_ex() allocates a buffer with the specified flags.
The flag B<BUF_MEM_FLAG_SECURE> specifies that the B<data> pointer
should be allocated on the secure heap; see L<CRYPTO_secure_malloc(3)>.
BUF_MEM_free() frees up an already existing buffer. The data is zeroed
before freeing up in case the buffer contains sensitive data.
+If the argument is NULL, nothing is done.
BUF_MEM_grow() changes the size of an already existing buffer to
B<len>. Any data already in the buffer is preserved if it increases in
size.
BUF_MEM_grow_clean() is similar to BUF_MEM_grow() but it sets any free'd
or additionally-allocated memory to zero.
BUF_reverse() reverses B<size> bytes at B<in> into B<out>. If B<in>
is NULL, the array is reversed in-place.
=head1 RETURN VALUES
BUF_MEM_new() returns the buffer or NULL on error.
BUF_MEM_free() has no return value.
BUF_MEM_grow() and BUF_MEM_grow_clean() return
zero on error or the new size (i.e., B<len>).
=head1 SEE ALSO
L<bio(7)>,
L<CRYPTO_secure_malloc(3)>.
=head1 HISTORY
The BUF_MEM_new_ex() function was added in OpenSSL 1.1.0.
=head1 COPYRIGHT
-Copyright 2000-2018 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/CRYPTO_THREAD_run_once.pod b/crypto/openssl/doc/man3/CRYPTO_THREAD_run_once.pod
index a51679b97edd..420ff7278b26 100644
--- a/crypto/openssl/doc/man3/CRYPTO_THREAD_run_once.pod
+++ b/crypto/openssl/doc/man3/CRYPTO_THREAD_run_once.pod
@@ -1,193 +1,197 @@
=pod
=head1 NAME
CRYPTO_THREAD_run_once,
CRYPTO_THREAD_lock_new, CRYPTO_THREAD_read_lock, CRYPTO_THREAD_write_lock,
CRYPTO_THREAD_unlock, CRYPTO_THREAD_lock_free,
CRYPTO_atomic_add, CRYPTO_atomic_or, CRYPTO_atomic_load - OpenSSL thread support
=head1 SYNOPSIS
#include <openssl/crypto.h>
CRYPTO_ONCE CRYPTO_ONCE_STATIC_INIT;
int CRYPTO_THREAD_run_once(CRYPTO_ONCE *once, void (*init)(void));
CRYPTO_RWLOCK *CRYPTO_THREAD_lock_new(void);
int CRYPTO_THREAD_read_lock(CRYPTO_RWLOCK *lock);
int CRYPTO_THREAD_write_lock(CRYPTO_RWLOCK *lock);
int CRYPTO_THREAD_unlock(CRYPTO_RWLOCK *lock);
void CRYPTO_THREAD_lock_free(CRYPTO_RWLOCK *lock);
int CRYPTO_atomic_add(int *val, int amount, int *ret, CRYPTO_RWLOCK *lock);
int CRYPTO_atomic_or(uint64_t *val, uint64_t op, uint64_t *ret,
CRYPTO_RWLOCK *lock);
int CRYPTO_atomic_load(uint64_t *val, uint64_t *ret, CRYPTO_RWLOCK *lock);
=head1 DESCRIPTION
OpenSSL can be safely used in multi-threaded applications provided that
support for the underlying OS threading API is built-in. Currently, OpenSSL
supports the pthread and Windows APIs. OpenSSL can also be built without
any multi-threading support, for example on platforms that don't provide
any threading support or that provide a threading API that is not yet
supported by OpenSSL.
The following multi-threading function are provided:
=over 2
=item *
CRYPTO_THREAD_run_once() can be used to perform one-time initialization.
The I<once> argument must be a pointer to a static object of type
B<CRYPTO_ONCE> that was statically initialized to the value
B<CRYPTO_ONCE_STATIC_INIT>.
The I<init> argument is a pointer to a function that performs the desired
exactly once initialization.
In particular, this can be used to allocate locks in a thread-safe manner,
which can then be used with the locking functions below.
=item *
CRYPTO_THREAD_lock_new() allocates, initializes and returns a new read/write
lock.
=item *
CRYPTO_THREAD_read_lock() locks the provided I<lock> for reading.
=item *
CRYPTO_THREAD_write_lock() locks the provided I<lock> for writing.
=item *
CRYPTO_THREAD_unlock() unlocks the previously locked I<lock>.
=item *
CRYPTO_THREAD_lock_free() frees the provided I<lock>.
+If the argument is NULL, nothing is done.
=item *
CRYPTO_atomic_add() atomically adds I<amount> to I<*val> and returns the
result of the operation in I<*ret>. I<lock> will be locked, unless atomic
operations are supported on the specific platform. Because of this, if a
variable is modified by CRYPTO_atomic_add() then CRYPTO_atomic_add() must
be the only way that the variable is modified. If atomic operations are not
supported and I<lock> is NULL, then the function will fail.
=item *
CRYPTO_atomic_or() performs an atomic bitwise or of I<op> and I<*val> and stores
the result back in I<*val>. It also returns the result of the operation in
I<*ret>. I<lock> will be locked, unless atomic operations are supported on the
specific platform. Because of this, if a variable is modified by
CRYPTO_atomic_or() or read by CRYPTO_atomic_load() then CRYPTO_atomic_or() must
be the only way that the variable is modified. If atomic operations are not
supported and I<lock> is NULL, then the function will fail.
=item *
CRYPTO_atomic_load() atomically loads the contents of I<*val> into I<*ret>.
I<lock> will be locked, unless atomic operations are supported on the specific
platform. Because of this, if a variable is modified by CRYPTO_atomic_or() or
read by CRYPTO_atomic_load() then CRYPTO_atomic_load() must be the only way that
the variable is read. If atomic operations are not supported and I<lock> is
NULL, then the function will fail.
=back
=head1 RETURN VALUES
CRYPTO_THREAD_run_once() returns 1 on success, or 0 on error.
CRYPTO_THREAD_lock_new() returns the allocated lock, or NULL on error.
CRYPTO_THREAD_lock_free() returns no value.
The other functions return 1 on success, or 0 on error.
=head1 NOTES
On Windows platforms the CRYPTO_THREAD_* types and functions in the
F<< <openssl/crypto.h> >> header are dependent on some of the types
customarily made available by including F<< <windows.h> >>. The application
developer is likely to require control over when the latter is included,
commonly as one of the first included headers. Therefore, it is defined as an
application developer's responsibility to include F<< <windows.h> >> prior to
F<< <openssl/crypto.h> >> where use of CRYPTO_THREAD_* types and functions is
required.
=head1 EXAMPLES
You can find out if OpenSSL was configured with thread support:
#include <openssl/opensslconf.h>
#if defined(OPENSSL_THREADS)
/* thread support enabled */
#else
/* no thread support */
#endif
This example safely initializes and uses a lock.
#ifdef _WIN32
# include <windows.h>
#endif
#include <openssl/crypto.h>
static CRYPTO_ONCE once = CRYPTO_ONCE_STATIC_INIT;
static CRYPTO_RWLOCK *lock;
static void myinit(void)
{
lock = CRYPTO_THREAD_lock_new();
}
static int mylock(void)
{
if (!CRYPTO_THREAD_run_once(&once, void init) || lock == NULL)
return 0;
return CRYPTO_THREAD_write_lock(lock);
}
static int myunlock(void)
{
return CRYPTO_THREAD_unlock(lock);
}
int serialized(void)
{
int ret = 0;
- if (mylock()) {
- /* Your code here, do not return without releasing the lock! */
- ret = ... ;
+ if (!mylock()) {
+ /* Do not unlock unless the lock was successfully acquired. */
+ return 0;
}
+
+ /* Your code here, do not return without releasing the lock! */
+ ret = ... ;
myunlock();
return ret;
}
Finalization of locks is an advanced topic, not covered in this example.
This can only be done at process exit or when a dynamically loaded library is
no longer in use and is unloaded.
The simplest solution is to just "leak" the lock in applications and not
repeatedly load/unload shared libraries that allocate locks.
=head1 SEE ALSO
L<crypto(7)>, L<openssl-threads(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/man3/CTLOG_STORE_new.pod b/crypto/openssl/doc/man3/CTLOG_STORE_new.pod
index 801b1447e155..361eda57b182 100644
--- a/crypto/openssl/doc/man3/CTLOG_STORE_new.pod
+++ b/crypto/openssl/doc/man3/CTLOG_STORE_new.pod
@@ -1,88 +1,88 @@
=pod
=head1 NAME
CTLOG_STORE_new_ex,
CTLOG_STORE_new, CTLOG_STORE_free,
CTLOG_STORE_load_default_file, CTLOG_STORE_load_file -
Create and populate a Certificate Transparency log list
=head1 SYNOPSIS
#include <openssl/ct.h>
CTLOG_STORE *CTLOG_STORE_new_ex(OSSL_LIB_CTX *libctx, const char *propq);
CTLOG_STORE *CTLOG_STORE_new(void);
void CTLOG_STORE_free(CTLOG_STORE *store);
int CTLOG_STORE_load_default_file(CTLOG_STORE *store);
int CTLOG_STORE_load_file(CTLOG_STORE *store, const char *file);
=head1 DESCRIPTION
A CTLOG_STORE is a container for a list of CTLOGs (Certificate Transparency
logs). The list can be loaded from one or more files and then searched by LogID
(see RFC 6962, Section 3.2, for the definition of a LogID).
CTLOG_STORE_new_ex() creates an empty list of CT logs associated with
the library context I<libctx> and the property query string I<propq>.
CTLOG_STORE_new() does the same thing as CTLOG_STORE_new_ex() but with
the default library context and property query string.
The CTLOG_STORE is then populated by CTLOG_STORE_load_default_file() or
CTLOG_STORE_load_file(). CTLOG_STORE_load_default_file() loads from the default
file, which is named F<ct_log_list.cnf> in OPENSSLDIR (see the output of
L<openssl-version(1)>). This can be overridden using an environment variable
named B<CTLOG_FILE>. CTLOG_STORE_load_file() loads from a caller-specified file
path instead. Both of these functions append any loaded CT logs to the
CTLOG_STORE.
The expected format of the file is:
enabled_logs=foo,bar
[foo]
description = Log 1
key = <base64-encoded DER SubjectPublicKeyInfo here>
[bar]
description = Log 2
key = <base64-encoded DER SubjectPublicKeyInfo here>
Once a CTLOG_STORE is no longer required, it should be passed to
CTLOG_STORE_free(). This will delete all of the CTLOGs stored within, along
-with the CTLOG_STORE itself.
+with the CTLOG_STORE itself. If the argument is NULL, nothing is done.
=head1 NOTES
If there are any invalid CT logs in a file, they are skipped and the remaining
valid logs will still be added to the CTLOG_STORE. A CT log will be considered
invalid if it is missing a "key" or "description" field.
=head1 RETURN VALUES
Both B<CTLOG_STORE_load_default_file> and B<CTLOG_STORE_load_file> return 1 if
all CT logs in the file are successfully parsed and loaded, 0 otherwise.
=head1 SEE ALSO
L<ct(7)>,
L<CTLOG_STORE_get0_log_by_id(3)>,
L<SSL_CTX_set_ctlog_list_file(3)>
=head1 HISTORY
CTLOG_STORE_new_ex was added in OpenSSL 3.0. All other functions were
added in OpenSSL 1.1.0.
=head1 COPYRIGHT
-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 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/CTLOG_new.pod b/crypto/openssl/doc/man3/CTLOG_new.pod
index 30b806824966..7a78a6c58dd3 100644
--- a/crypto/openssl/doc/man3/CTLOG_new.pod
+++ b/crypto/openssl/doc/man3/CTLOG_new.pod
@@ -1,90 +1,90 @@
=pod
=head1 NAME
CTLOG_new_ex, CTLOG_new, CTLOG_new_from_base64,
CTLOG_new_from_base64_ex, CTLOG_free,
CTLOG_get0_name, CTLOG_get0_log_id, CTLOG_get0_public_key -
encapsulates information about a Certificate Transparency log
=head1 SYNOPSIS
#include <openssl/ct.h>
CTLOG *CTLOG_new_ex(EVP_PKEY *public_key, const char *name,
OSSL_LIB_CTX *libctx, const char *propq);
CTLOG *CTLOG_new(EVP_PKEY *public_key, const char *name);
int CTLOG_new_from_base64_ex(CTLOG **ct_log, const char *pkey_base64,
const char *name, OSSL_LIB_CTX *libctx,
const char *propq);
int CTLOG_new_from_base64(CTLOG ** ct_log,
const char *pkey_base64, const char *name);
void CTLOG_free(CTLOG *log);
const char *CTLOG_get0_name(const CTLOG *log);
void CTLOG_get0_log_id(const CTLOG *log, const uint8_t **log_id,
size_t *log_id_len);
EVP_PKEY *CTLOG_get0_public_key(const CTLOG *log);
=head1 DESCRIPTION
CTLOG_new_ex() returns a new CTLOG that represents the Certificate
Transparency (CT) log with the given public key and associates it with the
library context I<libctx> and property query string I<propq>. A name must also
be provided that can be used to help users identify this log. Ownership of the
public key is transferred.
CTLOG_new() does the same thing as CTLOG_new_ex() but with the default
library context and the default property query string.
CTLOG_new_from_base64_ex() also creates a new CTLOG, but takes the
public key in base64-encoded DER form and sets the ct_log pointer to point to
the new CTLOG. The base64 will be decoded and the public key parsed. The CTLOG
will be associated with the given library context I<libctx> and property query
string I<propq>.
CTLOG_new_from_base64() does the same thing as
CTLOG_new_from_base64_ex() except that the default library context and
property query string are used.
Regardless of whether CTLOG_new() or CTLOG_new_from_base64() is used, it is the
caller's responsibility to pass the CTLOG to CTLOG_free() once it is no longer
needed. This will delete it and, if created by CTLOG_new(), the EVP_PKEY that
-was passed to it.
+was passed to it. If the argument to CTLOG_free() is NULL, nothing is done.
CTLOG_get0_name() returns the name of the log, as provided when the CTLOG was
created. Ownership of the string remains with the CTLOG.
CTLOG_get0_log_id() sets *log_id to point to a string containing that log's
LogID (see RFC 6962). It sets *log_id_len to the length of that LogID. For a
v1 CT log, the LogID will be a SHA-256 hash (i.e. 32 bytes long). Ownership of
the string remains with the CTLOG.
CTLOG_get0_public_key() returns the public key of the CT log. Ownership of the
EVP_PKEY remains with the CTLOG.
=head1 RETURN VALUES
CTLOG_new() will return NULL if an error occurs.
CTLOG_new_from_base64() will return 1 on success, 0 otherwise.
=head1 SEE ALSO
L<ct(7)>
=head1 HISTORY
The functions CTLOG_new_ex() and CTLOG_new_from_base64_ex()
were added in OpenSSL 3.0. All other functions were added in OpenSSL 1.1.0.
=head1 COPYRIGHT
-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 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/CT_POLICY_EVAL_CTX_new.pod b/crypto/openssl/doc/man3/CT_POLICY_EVAL_CTX_new.pod
index bba6778d2deb..3b79980c43c2 100644
--- a/crypto/openssl/doc/man3/CT_POLICY_EVAL_CTX_new.pod
+++ b/crypto/openssl/doc/man3/CT_POLICY_EVAL_CTX_new.pod
@@ -1,140 +1,141 @@
=pod
=head1 NAME
CT_POLICY_EVAL_CTX_new_ex,
CT_POLICY_EVAL_CTX_new, CT_POLICY_EVAL_CTX_free,
CT_POLICY_EVAL_CTX_get0_cert, CT_POLICY_EVAL_CTX_set1_cert,
CT_POLICY_EVAL_CTX_get0_issuer, CT_POLICY_EVAL_CTX_set1_issuer,
CT_POLICY_EVAL_CTX_get0_log_store, CT_POLICY_EVAL_CTX_set_shared_CTLOG_STORE,
CT_POLICY_EVAL_CTX_get_time, CT_POLICY_EVAL_CTX_set_time -
Encapsulates the data required to evaluate whether SCTs meet a Certificate Transparency policy
=head1 SYNOPSIS
#include <openssl/ct.h>
CT_POLICY_EVAL_CTX *CT_POLICY_EVAL_CTX_new_ex(OSSL_LIB_CTX *libctx,
const char *propq);
CT_POLICY_EVAL_CTX *CT_POLICY_EVAL_CTX_new(void);
void CT_POLICY_EVAL_CTX_free(CT_POLICY_EVAL_CTX *ctx);
X509* CT_POLICY_EVAL_CTX_get0_cert(const CT_POLICY_EVAL_CTX *ctx);
int CT_POLICY_EVAL_CTX_set1_cert(CT_POLICY_EVAL_CTX *ctx, X509 *cert);
X509* CT_POLICY_EVAL_CTX_get0_issuer(const CT_POLICY_EVAL_CTX *ctx);
int CT_POLICY_EVAL_CTX_set1_issuer(CT_POLICY_EVAL_CTX *ctx, X509 *issuer);
const CTLOG_STORE *CT_POLICY_EVAL_CTX_get0_log_store(const CT_POLICY_EVAL_CTX *ctx);
void CT_POLICY_EVAL_CTX_set_shared_CTLOG_STORE(CT_POLICY_EVAL_CTX *ctx,
CTLOG_STORE *log_store);
uint64_t CT_POLICY_EVAL_CTX_get_time(const CT_POLICY_EVAL_CTX *ctx);
void CT_POLICY_EVAL_CTX_set_time(CT_POLICY_EVAL_CTX *ctx, uint64_t time_in_ms);
=head1 DESCRIPTION
A B<CT_POLICY_EVAL_CTX> is used by functions that evaluate whether Signed
Certificate Timestamps (SCTs) fulfil a Certificate Transparency (CT) policy.
This policy may be, for example, that at least one valid SCT is available. To
determine this, an SCT's timestamp and signature must be verified.
This requires:
=over 2
=item *
the public key of the log that issued the SCT
=item *
the certificate that the SCT was issued for
=item *
the issuer certificate (if the SCT was issued for a pre-certificate)
=item *
the current time
=back
The above requirements are met using the setters described below.
CT_POLICY_EVAL_CTX_new_ex() creates an empty policy evaluation context
and associates it with the given library context I<libctx> and property query
string I<propq>.
CT_POLICY_EVAL_CTX_new() does the same thing as
CT_POLICY_EVAL_CTX_new_ex() except that it uses the default library
context and property query string.
The CT_POLICY_EVAL_CTX should then be populated using:
=over 2
=item *
CT_POLICY_EVAL_CTX_set1_cert() to provide the certificate the SCTs were issued for
Increments the reference count of the certificate.
=item *
CT_POLICY_EVAL_CTX_set1_issuer() to provide the issuer certificate
Increments the reference count of the certificate.
=item *
CT_POLICY_EVAL_CTX_set_shared_CTLOG_STORE() to provide a list of logs that are trusted as sources of SCTs
Holds a pointer to the CTLOG_STORE, so the CTLOG_STORE must outlive the
CT_POLICY_EVAL_CTX.
=item *
CT_POLICY_EVAL_CTX_set_time() to set the time SCTs should be compared with to determine if they are valid
The SCT timestamp will be compared to this time to check whether the SCT was
issued in the future. RFC6962 states that "TLS clients MUST reject SCTs whose
timestamp is in the future". By default, this will be set to 5 minutes in the
future (e.g. (time() + 300) * 1000), to allow for clock drift.
The time should be in milliseconds since the Unix Epoch.
=back
Each setter has a matching getter for accessing the current value.
When no longer required, the B<CT_POLICY_EVAL_CTX> should be passed to
-CT_POLICY_EVAL_CTX_free() to delete it.
+CT_POLICY_EVAL_CTX_free() to delete it. If the argument to
+CT_POLICY_EVAL_CTX_free() is NULL, nothing is done.
=head1 NOTES
The issuer certificate only needs to be provided if at least one of the SCTs
was issued for a pre-certificate. This will be the case for SCTs embedded in a
certificate (i.e. those in an X.509 extension), but may not be the case for SCTs
found in the TLS SCT extension or OCSP response.
=head1 RETURN VALUES
CT_POLICY_EVAL_CTX_new_ex() and CT_POLICY_EVAL_CTX_new() will return
NULL if malloc fails.
=head1 SEE ALSO
L<ct(7)>
=head1 HISTORY
CT_POLICY_EVAL_CTX_new_ex was added in OpenSSL 3.0. All other
functions were added in OpenSSL 1.1.0.
=head1 COPYRIGHT
-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 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/DH_meth_new.pod b/crypto/openssl/doc/man3/DH_meth_new.pod
index 43827f55ef8c..d5ba5eac565d 100644
--- a/crypto/openssl/doc/man3/DH_meth_new.pod
+++ b/crypto/openssl/doc/man3/DH_meth_new.pod
@@ -1,176 +1,176 @@
=pod
=head1 NAME
DH_meth_new, DH_meth_free, DH_meth_dup, DH_meth_get0_name, DH_meth_set1_name,
DH_meth_get_flags, DH_meth_set_flags, DH_meth_get0_app_data,
DH_meth_set0_app_data, DH_meth_get_generate_key, DH_meth_set_generate_key,
DH_meth_get_compute_key, DH_meth_set_compute_key, DH_meth_get_bn_mod_exp,
DH_meth_set_bn_mod_exp, DH_meth_get_init, DH_meth_set_init, DH_meth_get_finish,
DH_meth_set_finish, DH_meth_get_generate_params,
DH_meth_set_generate_params - Routines to build up DH methods
=head1 SYNOPSIS
#include <openssl/dh.h>
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)>:
DH_METHOD *DH_meth_new(const char *name, int flags);
void DH_meth_free(DH_METHOD *dhm);
DH_METHOD *DH_meth_dup(const DH_METHOD *dhm);
const char *DH_meth_get0_name(const DH_METHOD *dhm);
int DH_meth_set1_name(DH_METHOD *dhm, const char *name);
int DH_meth_get_flags(const DH_METHOD *dhm);
int DH_meth_set_flags(DH_METHOD *dhm, int flags);
void *DH_meth_get0_app_data(const DH_METHOD *dhm);
int DH_meth_set0_app_data(DH_METHOD *dhm, void *app_data);
int (*DH_meth_get_generate_key(const DH_METHOD *dhm))(DH *);
int DH_meth_set_generate_key(DH_METHOD *dhm, int (*generate_key)(DH *));
int (*DH_meth_get_compute_key(const DH_METHOD *dhm))
(unsigned char *key, const BIGNUM *pub_key, DH *dh);
int DH_meth_set_compute_key(DH_METHOD *dhm,
int (*compute_key)(unsigned char *key, const BIGNUM *pub_key, DH *dh));
int (*DH_meth_get_bn_mod_exp(const DH_METHOD *dhm))
(const DH *dh, BIGNUM *r, const BIGNUM *a, const BIGNUM *p,
const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *m_ctx);
int DH_meth_set_bn_mod_exp(DH_METHOD *dhm,
int (*bn_mod_exp)(const DH *dh, BIGNUM *r, const BIGNUM *a,
const BIGNUM *p, const BIGNUM *m, BN_CTX *ctx,
BN_MONT_CTX *m_ctx));
int (*DH_meth_get_init(const DH_METHOD *dhm))(DH *);
int DH_meth_set_init(DH_METHOD *dhm, int (*init)(DH *));
int (*DH_meth_get_finish(const DH_METHOD *dhm))(DH *);
int DH_meth_set_finish(DH_METHOD *dhm, int (*finish)(DH *));
int (*DH_meth_get_generate_params(const DH_METHOD *dhm))
(DH *, int, int, BN_GENCB *);
int DH_meth_set_generate_params(DH_METHOD *dhm,
int (*generate_params)(DH *, int, int, BN_GENCB *));
=head1 DESCRIPTION
All of the functions described on this page are deprecated.
Applications should instead use the provider APIs.
The B<DH_METHOD> type is a structure used for the provision of custom DH
implementations. It provides a set of functions used by OpenSSL for the
implementation of the various DH capabilities.
DH_meth_new() creates a new B<DH_METHOD> structure. It should be given a
unique B<name> and a set of B<flags>. The B<name> should be a NULL terminated
string, which will be duplicated and stored in the B<DH_METHOD> object. It is
the callers responsibility to free the original string. The flags will be used
during the construction of a new B<DH> object based on this B<DH_METHOD>. Any
new B<DH> object will have those flags set by default.
DH_meth_dup() creates a duplicate copy of the B<DH_METHOD> object passed as a
parameter. This might be useful for creating a new B<DH_METHOD> based on an
existing one, but with some differences.
DH_meth_free() destroys a B<DH_METHOD> structure and frees up any memory
-associated with it.
+associated with it. If the argument is NULL, nothing is done.
DH_meth_get0_name() will return a pointer to the name of this DH_METHOD. This
is a pointer to the internal name string and so should not be freed by the
caller. DH_meth_set1_name() sets the name of the DH_METHOD to B<name>. The
string is duplicated and the copy is stored in the DH_METHOD structure, so the
caller remains responsible for freeing the memory associated with the name.
DH_meth_get_flags() returns the current value of the flags associated with this
DH_METHOD. DH_meth_set_flags() provides the ability to set these flags.
The functions DH_meth_get0_app_data() and DH_meth_set0_app_data() provide the
ability to associate implementation specific data with the DH_METHOD. It is
the application's responsibility to free this data before the DH_METHOD is
freed via a call to DH_meth_free().
DH_meth_get_generate_key() and DH_meth_set_generate_key() get and set the
function used for generating a new DH key pair respectively. This function will
be called in response to the application calling DH_generate_key(). The
parameter for the function has the same meaning as for DH_generate_key().
DH_meth_get_compute_key() and DH_meth_set_compute_key() get and set the
function used for computing a new DH shared secret respectively. This function
will be called in response to the application calling DH_compute_key(). The
parameters for the function have the same meaning as for DH_compute_key().
DH_meth_get_bn_mod_exp() and DH_meth_set_bn_mod_exp() get and set the function
used for computing the following value:
r = a ^ p mod m
This function will be called by the default OpenSSL function for
DH_generate_key(). The result is stored in the B<r> parameter. This function
may be NULL unless using the default generate key function, in which case it
must be present.
DH_meth_get_init() and DH_meth_set_init() get and set the function used
for creating a new DH instance respectively. This function will be
called in response to the application calling DH_new() (if the current default
DH_METHOD is this one) or DH_new_method(). The DH_new() and DH_new_method()
functions will allocate the memory for the new DH object, and a pointer to this
newly allocated structure will be passed as a parameter to the function. This
function may be NULL.
DH_meth_get_finish() and DH_meth_set_finish() get and set the function used
for destroying an instance of a DH object respectively. This function will be
called in response to the application calling DH_free(). A pointer to the DH
to be destroyed is passed as a parameter. The destroy function should be used
for DH implementation specific clean up. The memory for the DH itself should
not be freed by this function. This function may be NULL.
DH_meth_get_generate_params() and DH_meth_set_generate_params() get and set the
function used for generating DH parameters respectively. This function will be
called in response to the application calling DH_generate_parameters_ex() (or
DH_generate_parameters()). The parameters for the function have the same
meaning as for DH_generate_parameters_ex(). This function may be NULL.
=head1 RETURN VALUES
DH_meth_new() and DH_meth_dup() return the newly allocated DH_METHOD object
or NULL on failure.
DH_meth_get0_name() and DH_meth_get_flags() return the name and flags
associated with the DH_METHOD respectively.
All other DH_meth_get_*() functions return the appropriate function pointer
that has been set in the DH_METHOD, or NULL if no such pointer has yet been
set.
DH_meth_set1_name() and all DH_meth_set_*() functions return 1 on success or
0 on failure.
=head1 SEE ALSO
L<DH_new(3)>, L<DH_new(3)>, L<DH_generate_parameters(3)>, L<DH_generate_key(3)>,
L<DH_set_method(3)>, L<DH_size(3)>, L<DH_get0_pqg(3)>
=head1 HISTORY
All of these functions were deprecated in OpenSSL 3.0.
The functions described here were added in OpenSSL 1.1.0.
=head1 COPYRIGHT
-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
L<https://www.openssl.org/source/license.html>.
=cut
diff --git a/crypto/openssl/doc/man3/DSA_SIG_new.pod b/crypto/openssl/doc/man3/DSA_SIG_new.pod
index 1f532d300065..158da2d7dd06 100644
--- a/crypto/openssl/doc/man3/DSA_SIG_new.pod
+++ b/crypto/openssl/doc/man3/DSA_SIG_new.pod
@@ -1,58 +1,59 @@
=pod
=head1 NAME
DSA_SIG_get0, DSA_SIG_set0,
DSA_SIG_new, DSA_SIG_free - allocate and free DSA signature objects
=head1 SYNOPSIS
#include <openssl/dsa.h>
DSA_SIG *DSA_SIG_new(void);
void DSA_SIG_free(DSA_SIG *a);
void DSA_SIG_get0(const DSA_SIG *sig, const BIGNUM **pr, const BIGNUM **ps);
int DSA_SIG_set0(DSA_SIG *sig, BIGNUM *r, BIGNUM *s);
=head1 DESCRIPTION
DSA_SIG_new() allocates an empty B<DSA_SIG> structure.
DSA_SIG_free() frees the B<DSA_SIG> structure and its components. The
values are erased before the memory is returned to the system.
+If the argument is NULL, nothing is done.
DSA_SIG_get0() returns internal pointers to the B<r> and B<s> values contained
in B<sig>.
The B<r> and B<s> values can be set by calling DSA_SIG_set0() and passing the
new values for B<r> and B<s> as parameters to the function. Calling this
function transfers the memory management of the values to the DSA_SIG object,
and therefore the values that have been passed in should not be freed directly
after this function has been called.
=head1 RETURN VALUES
If the allocation fails, DSA_SIG_new() returns B<NULL> and sets an
error code that can be obtained by
L<ERR_get_error(3)>. Otherwise it returns a pointer
to the newly allocated structure.
DSA_SIG_free() returns no value.
DSA_SIG_set0() returns 1 on success or 0 on failure.
=head1 SEE ALSO
L<EVP_PKEY_new(3)>, L<EVP_PKEY_free(3)>, L<EVP_PKEY_get_bn_param(3)>,
L<ERR_get_error(3)>
=head1 COPYRIGHT
-Copyright 2000-2016 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/DSA_meth_new.pod b/crypto/openssl/doc/man3/DSA_meth_new.pod
index c00747cfc448..534561c61046 100644
--- a/crypto/openssl/doc/man3/DSA_meth_new.pod
+++ b/crypto/openssl/doc/man3/DSA_meth_new.pod
@@ -1,224 +1,224 @@
=pod
=head1 NAME
DSA_meth_new, DSA_meth_free, DSA_meth_dup, DSA_meth_get0_name,
DSA_meth_set1_name, DSA_meth_get_flags, DSA_meth_set_flags,
DSA_meth_get0_app_data, DSA_meth_set0_app_data, DSA_meth_get_sign,
DSA_meth_set_sign, DSA_meth_get_sign_setup, DSA_meth_set_sign_setup,
DSA_meth_get_verify, DSA_meth_set_verify, DSA_meth_get_mod_exp,
DSA_meth_set_mod_exp, DSA_meth_get_bn_mod_exp, DSA_meth_set_bn_mod_exp,
DSA_meth_get_init, DSA_meth_set_init, DSA_meth_get_finish, DSA_meth_set_finish,
DSA_meth_get_paramgen, DSA_meth_set_paramgen, DSA_meth_get_keygen,
DSA_meth_set_keygen - Routines to build up DSA methods
=head1 SYNOPSIS
#include <openssl/dsa.h>
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)>:
DSA_METHOD *DSA_meth_new(const char *name, int flags);
void DSA_meth_free(DSA_METHOD *dsam);
DSA_METHOD *DSA_meth_dup(const DSA_METHOD *meth);
const char *DSA_meth_get0_name(const DSA_METHOD *dsam);
int DSA_meth_set1_name(DSA_METHOD *dsam, const char *name);
int DSA_meth_get_flags(const DSA_METHOD *dsam);
int DSA_meth_set_flags(DSA_METHOD *dsam, int flags);
void *DSA_meth_get0_app_data(const DSA_METHOD *dsam);
int DSA_meth_set0_app_data(DSA_METHOD *dsam, void *app_data);
DSA_SIG *(*DSA_meth_get_sign(const DSA_METHOD *dsam))(const unsigned char *,
int, DSA *);
int DSA_meth_set_sign(DSA_METHOD *dsam, DSA_SIG *(*sign)(const unsigned char *,
int, DSA *));
int (*DSA_meth_get_sign_setup(const DSA_METHOD *dsam))(DSA *, BN_CTX *,$
BIGNUM **, BIGNUM **);
int DSA_meth_set_sign_setup(DSA_METHOD *dsam, int (*sign_setup)(DSA *, BN_CTX *,
BIGNUM **, BIGNUM **));
int (*DSA_meth_get_verify(const DSA_METHOD *dsam))(const unsigned char *,
int, DSA_SIG *, DSA *);
int DSA_meth_set_verify(DSA_METHOD *dsam, int (*verify)(const unsigned char *,
int, DSA_SIG *, DSA *));
int (*DSA_meth_get_mod_exp(const DSA_METHOD *dsam))(DSA *dsa, BIGNUM *rr, BIGNUM *a1,
BIGNUM *p1, BIGNUM *a2, BIGNUM *p2,
BIGNUM *m, BN_CTX *ctx,
BN_MONT_CTX *in_mont);
int DSA_meth_set_mod_exp(DSA_METHOD *dsam, int (*mod_exp)(DSA *dsa, BIGNUM *rr,
BIGNUM *a1, BIGNUM *p1,
BIGNUM *a2, BIGNUM *p2,
BIGNUM *m, BN_CTX *ctx,
BN_MONT_CTX *mont));
int (*DSA_meth_get_bn_mod_exp(const DSA_METHOD *dsam))(DSA *dsa, BIGNUM *r, BIGNUM *a,
const BIGNUM *p, const BIGNUM *m,
BN_CTX *ctx, BN_MONT_CTX *mont);
int DSA_meth_set_bn_mod_exp(DSA_METHOD *dsam, int (*bn_mod_exp)(DSA *dsa,
BIGNUM *r,
BIGNUM *a,
const BIGNUM *p,
const BIGNUM *m,
BN_CTX *ctx,
BN_MONT_CTX *mont));
int (*DSA_meth_get_init(const DSA_METHOD *dsam))(DSA *);
int DSA_meth_set_init(DSA_METHOD *dsam, int (*init)(DSA *));
int (*DSA_meth_get_finish(const DSA_METHOD *dsam))(DSA *);
int DSA_meth_set_finish(DSA_METHOD *dsam, int (*finish)(DSA *));
int (*DSA_meth_get_paramgen(const DSA_METHOD *dsam))(DSA *, int,
const unsigned char *,
int, int *, unsigned long *,
BN_GENCB *);
int DSA_meth_set_paramgen(DSA_METHOD *dsam,
int (*paramgen)(DSA *, int, const unsigned char *,
int, int *, unsigned long *, BN_GENCB *));
int (*DSA_meth_get_keygen(const DSA_METHOD *dsam))(DSA *);
int DSA_meth_set_keygen(DSA_METHOD *dsam, int (*keygen)(DSA *));
=head1 DESCRIPTION
All of the functions described on this page are deprecated.
Applications and extension implementations should instead use the
OSSL_PROVIDER APIs.
The B<DSA_METHOD> type is a structure used for the provision of custom DSA
implementations. It provides a set of functions used by OpenSSL for the
implementation of the various DSA capabilities.
DSA_meth_new() creates a new B<DSA_METHOD> structure. It should be given a
unique B<name> and a set of B<flags>. The B<name> should be a NULL terminated
string, which will be duplicated and stored in the B<DSA_METHOD> object. It is
the callers responsibility to free the original string. The flags will be used
during the construction of a new B<DSA> object based on this B<DSA_METHOD>. Any
new B<DSA> object will have those flags set by default.
DSA_meth_dup() creates a duplicate copy of the B<DSA_METHOD> object passed as a
parameter. This might be useful for creating a new B<DSA_METHOD> based on an
existing one, but with some differences.
DSA_meth_free() destroys a B<DSA_METHOD> structure and frees up any memory
-associated with it.
+associated with it. If the argument is NULL, nothing is done.
DSA_meth_get0_name() will return a pointer to the name of this DSA_METHOD. This
is a pointer to the internal name string and so should not be freed by the
caller. DSA_meth_set1_name() sets the name of the DSA_METHOD to B<name>. The
string is duplicated and the copy is stored in the DSA_METHOD structure, so the
caller remains responsible for freeing the memory associated with the name.
DSA_meth_get_flags() returns the current value of the flags associated with this
DSA_METHOD. DSA_meth_set_flags() provides the ability to set these flags.
The functions DSA_meth_get0_app_data() and DSA_meth_set0_app_data() provide the
ability to associate implementation specific data with the DSA_METHOD. It is
the application's responsibility to free this data before the DSA_METHOD is
freed via a call to DSA_meth_free().
DSA_meth_get_sign() and DSA_meth_set_sign() get and set the function used for
creating a DSA signature respectively. This function will be
called in response to the application calling DSA_do_sign() (or DSA_sign()). The
parameters for the function have the same meaning as for DSA_do_sign().
DSA_meth_get_sign_setup() and DSA_meth_set_sign_setup() get and set the function
used for precalculating the DSA signature values B<k^-1> and B<r>. This function
will be called in response to the application calling DSA_sign_setup(). The
parameters for the function have the same meaning as for DSA_sign_setup().
DSA_meth_get_verify() and DSA_meth_set_verify() get and set the function used
for verifying a DSA signature respectively. This function will be called in
response to the application calling DSA_do_verify() (or DSA_verify()). The
parameters for the function have the same meaning as for DSA_do_verify().
DSA_meth_get_mod_exp() and DSA_meth_set_mod_exp() get and set the function used
for computing the following value:
rr = a1^p1 * a2^p2 mod m
This function will be called by the default OpenSSL method during verification
of a DSA signature. The result is stored in the B<rr> parameter. This function
may be NULL.
DSA_meth_get_bn_mod_exp() and DSA_meth_set_bn_mod_exp() get and set the function
used for computing the following value:
r = a ^ p mod m
This function will be called by the default OpenSSL function for
DSA_sign_setup(). The result is stored in the B<r> parameter. This function
may be NULL.
DSA_meth_get_init() and DSA_meth_set_init() get and set the function used
for creating a new DSA instance respectively. This function will be
called in response to the application calling DSA_new() (if the current default
DSA_METHOD is this one) or DSA_new_method(). The DSA_new() and DSA_new_method()
functions will allocate the memory for the new DSA object, and a pointer to this
newly allocated structure will be passed as a parameter to the function. This
function may be NULL.
DSA_meth_get_finish() and DSA_meth_set_finish() get and set the function used
for destroying an instance of a DSA object respectively. This function will be
called in response to the application calling DSA_free(). A pointer to the DSA
to be destroyed is passed as a parameter. The destroy function should be used
for DSA implementation specific clean up. The memory for the DSA itself should
not be freed by this function. This function may be NULL.
DSA_meth_get_paramgen() and DSA_meth_set_paramgen() get and set the function
used for generating DSA parameters respectively. This function will be called in
response to the application calling DSA_generate_parameters_ex() (or
DSA_generate_parameters()). The parameters for the function have the same
meaning as for DSA_generate_parameters_ex().
DSA_meth_get_keygen() and DSA_meth_set_keygen() get and set the function
used for generating a new DSA key pair respectively. This function will be
called in response to the application calling DSA_generate_key(). The parameter
for the function has the same meaning as for DSA_generate_key().
=head1 RETURN VALUES
DSA_meth_new() and DSA_meth_dup() return the newly allocated DSA_METHOD object
or NULL on failure.
DSA_meth_get0_name() and DSA_meth_get_flags() return the name and flags
associated with the DSA_METHOD respectively.
All other DSA_meth_get_*() functions return the appropriate function pointer
that has been set in the DSA_METHOD, or NULL if no such pointer has yet been
set.
DSA_meth_set1_name() and all DSA_meth_set_*() functions return 1 on success or
0 on failure.
=head1 SEE ALSO
L<DSA_new(3)>, L<DSA_new(3)>, L<DSA_generate_parameters(3)>, L<DSA_generate_key(3)>,
L<DSA_dup_DH(3)>, L<DSA_do_sign(3)>, L<DSA_set_method(3)>, L<DSA_SIG_new(3)>,
L<DSA_sign(3)>, L<DSA_size(3)>, L<DSA_get0_pqg(3)>
=head1 HISTORY
The functions described here were deprecated in OpenSSL 3.0.
The functions described here were added in OpenSSL 1.1.0.
=head1 COPYRIGHT
-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
L<https://www.openssl.org/source/license.html>.
=cut
diff --git a/crypto/openssl/doc/man3/ECDSA_SIG_new.pod b/crypto/openssl/doc/man3/ECDSA_SIG_new.pod
index 3266c43b550c..e56ec959edff 100644
--- a/crypto/openssl/doc/man3/ECDSA_SIG_new.pod
+++ b/crypto/openssl/doc/man3/ECDSA_SIG_new.pod
@@ -1,146 +1,147 @@
=pod
=head1 NAME
ECDSA_SIG_new, ECDSA_SIG_free,
ECDSA_SIG_get0, ECDSA_SIG_get0_r, ECDSA_SIG_get0_s, ECDSA_SIG_set0
- Functions for creating, destroying and manipulating ECDSA_SIG objects
=head1 SYNOPSIS
#include <openssl/ecdsa.h>
ECDSA_SIG *ECDSA_SIG_new(void);
void ECDSA_SIG_free(ECDSA_SIG *sig);
void ECDSA_SIG_get0(const ECDSA_SIG *sig, const BIGNUM **pr, const BIGNUM **ps);
const BIGNUM *ECDSA_SIG_get0_r(const ECDSA_SIG *sig);
const BIGNUM *ECDSA_SIG_get0_s(const ECDSA_SIG *sig);
int ECDSA_SIG_set0(ECDSA_SIG *sig, BIGNUM *r, BIGNUM *s);
=head1 DESCRIPTION
B<ECDSA_SIG> is an opaque structure consisting of two BIGNUMs for the
I<r> and I<s> value of an Elliptic Curve Digital Signature Algorithm (ECDSA) signature
(see FIPS186-4 or X9.62).
The B<ECDSA_SIG> object was mainly used by the deprecated low level functions described in
L<ECDSA_sign(3)>, it is still required in order to be able to set or get the values of
I<r> and I<s> into or from a signature. This is mainly used for testing purposes as shown
in the L</EXAMPLES>.
ECDSA_SIG_new() allocates an empty B<ECDSA_SIG> structure.
Note: before OpenSSL 1.1.0, the I<r> and I<s> components were initialised.
ECDSA_SIG_free() frees the B<ECDSA_SIG> structure I<sig>.
+If the argument is NULL, nothing is done.
ECDSA_SIG_get0() returns internal pointers the I<r> and I<s> values contained
in I<sig> and stores them in I<*pr> and I<*ps>, respectively.
The pointer I<pr> or I<ps> can be NULL, in which case the corresponding value
is not returned.
The values I<r>, I<s> can also be retrieved separately by the corresponding
function ECDSA_SIG_get0_r() and ECDSA_SIG_get0_s(), respectively.
Non-NULL I<r> and I<s> values can be set on the I<sig> by calling
ECDSA_SIG_set0(). Calling this function transfers the memory management of the
values to the B<ECDSA_SIG> object, and therefore the values that have been
passed in should not be freed by the caller.
See L<i2d_ECDSA_SIG(3)> and L<d2i_ECDSA_SIG(3)> for information about encoding
and decoding ECDSA signatures to/from DER.
=head1 RETURN VALUES
ECDSA_SIG_new() returns NULL if the allocation fails.
ECDSA_SIG_set0() returns 1 on success or 0 on failure.
ECDSA_SIG_get0_r() and ECDSA_SIG_get0_s() return the corresponding value,
or NULL if it is unset.
=head1 EXAMPLES
Extract signature I<r> and I<s> values from a ECDSA I<signature>
of size I<signaturelen>:
ECDSA_SIG *obj;
const BIGNUM *r, *s;
/* Load a signature into the ECDSA_SIG object */
obj = d2i_ECDSA_SIG(NULL, &signature, signaturelen);
if (obj == NULL)
/* error */
r = ECDSA_SIG_get0_r(obj);
s = ECDSA_SIG_get0_s(obj);
if (r == NULL || s == NULL)
/* error */
/* Use BN_bn2binpad() here to convert to r and s into byte arrays */
/*
* Do not try to access I<r> or I<s> after calling ECDSA_SIG_free(),
* as they are both freed by this call.
*/
ECDSA_SIG_free(obj);
Convert I<r> and I<s> byte arrays into an ECDSA_SIG I<signature> of
size I<signaturelen>:
ECDSA_SIG *obj = NULL;
unsigned char *signature = NULL;
size_t signaturelen;
BIGNUM *rbn = NULL, *sbn = NULL;
obj = ECDSA_SIG_new();
if (obj == NULL)
/* error */
rbn = BN_bin2bn(r, rlen, NULL);
sbn = BN_bin2bn(s, slen, NULL);
if (rbn == NULL || sbn == NULL)
/* error */
if (!ECDSA_SIG_set0(obj, rbn, sbn))
/* error */
/* Set these to NULL since they are now owned by obj */
rbn = sbn = NULL;
signaturelen = i2d_ECDSA_SIG(obj, &signature);
if (signaturelen <= 0)
/* error */
/*
* This signature could now be passed to L<EVP_DigestVerify(3)>
* or L<EVP_DigestVerifyFinal(3)>
*/
BN_free(rbn);
BN_free(sbn);
OPENSSL_free(signature);
ECDSA_SIG_free(obj);
=head1 CONFORMING TO
ANSI X9.62,
US Federal Information Processing Standard FIPS186-4
(Digital Signature Standard, DSS)
=head1 SEE ALSO
L<EC_KEY_new(3)>,
L<EVP_DigestSignInit(3)>,
L<EVP_DigestVerifyInit(3)>,
L<EVP_PKEY_sign(3)>
L<i2d_ECDSA_SIG(3)>,
L<d2i_ECDSA_SIG(3)>,
L<ECDSA_sign(3)>
=head1 COPYRIGHT
-Copyright 2004-2022 The OpenSSL Project Authors. All Rights Reserved.
+Copyright 2004-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/ENGINE_add.pod b/crypto/openssl/doc/man3/ENGINE_add.pod
index 55e5d76fcdb8..24c83c576476 100644
--- a/crypto/openssl/doc/man3/ENGINE_add.pod
+++ b/crypto/openssl/doc/man3/ENGINE_add.pod
@@ -1,675 +1,676 @@
=pod
=head1 NAME
ENGINE_get_DH, ENGINE_get_DSA,
ENGINE_by_id, ENGINE_get_cipher_engine, ENGINE_get_default_DH,
ENGINE_get_default_DSA,
ENGINE_get_default_RAND,
ENGINE_get_default_RSA, ENGINE_get_digest_engine, ENGINE_get_first,
ENGINE_get_last, ENGINE_get_next, ENGINE_get_prev, ENGINE_new,
ENGINE_get_ciphers, ENGINE_get_ctrl_function, ENGINE_get_digests,
ENGINE_get_destroy_function, ENGINE_get_finish_function,
ENGINE_get_init_function, ENGINE_get_load_privkey_function,
ENGINE_get_load_pubkey_function, ENGINE_load_private_key,
ENGINE_load_public_key, ENGINE_get_RAND, ENGINE_get_RSA, ENGINE_get_id,
ENGINE_get_name, ENGINE_get_cmd_defns, ENGINE_get_cipher,
ENGINE_get_digest, ENGINE_add, ENGINE_cmd_is_executable,
ENGINE_ctrl, ENGINE_ctrl_cmd, ENGINE_ctrl_cmd_string,
ENGINE_finish, ENGINE_free, ENGINE_get_flags, ENGINE_init,
ENGINE_register_DH, ENGINE_register_DSA,
ENGINE_register_RAND, ENGINE_register_RSA,
ENGINE_register_all_complete, ENGINE_register_ciphers,
ENGINE_register_complete, ENGINE_register_digests, ENGINE_remove,
ENGINE_set_DH, ENGINE_set_DSA,
ENGINE_set_RAND, ENGINE_set_RSA, ENGINE_set_ciphers,
ENGINE_set_cmd_defns, ENGINE_set_ctrl_function, ENGINE_set_default,
ENGINE_set_default_DH, ENGINE_set_default_DSA,
ENGINE_set_default_RAND, ENGINE_set_default_RSA,
ENGINE_set_default_ciphers, ENGINE_set_default_digests,
ENGINE_set_default_string, ENGINE_set_destroy_function,
ENGINE_set_digests, ENGINE_set_finish_function, ENGINE_set_flags,
ENGINE_set_id, ENGINE_set_init_function, ENGINE_set_load_privkey_function,
ENGINE_set_load_pubkey_function, ENGINE_set_name, ENGINE_up_ref,
ENGINE_get_table_flags, ENGINE_cleanup,
ENGINE_load_builtin_engines, ENGINE_register_all_DH,
ENGINE_register_all_DSA,
ENGINE_register_all_RAND,
ENGINE_register_all_RSA, ENGINE_register_all_ciphers,
ENGINE_register_all_digests, ENGINE_set_table_flags, ENGINE_unregister_DH,
ENGINE_unregister_DSA,
ENGINE_unregister_RAND, ENGINE_unregister_RSA, ENGINE_unregister_ciphers,
ENGINE_unregister_digests
- ENGINE cryptographic module support
=head1 SYNOPSIS
#include <openssl/engine.h>
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)>:
ENGINE *ENGINE_get_first(void);
ENGINE *ENGINE_get_last(void);
ENGINE *ENGINE_get_next(ENGINE *e);
ENGINE *ENGINE_get_prev(ENGINE *e);
int ENGINE_add(ENGINE *e);
int ENGINE_remove(ENGINE *e);
ENGINE *ENGINE_by_id(const char *id);
int ENGINE_init(ENGINE *e);
int ENGINE_finish(ENGINE *e);
void ENGINE_load_builtin_engines(void);
ENGINE *ENGINE_get_default_RSA(void);
ENGINE *ENGINE_get_default_DSA(void);
ENGINE *ENGINE_get_default_DH(void);
ENGINE *ENGINE_get_default_RAND(void);
ENGINE *ENGINE_get_cipher_engine(int nid);
ENGINE *ENGINE_get_digest_engine(int nid);
int ENGINE_set_default_RSA(ENGINE *e);
int ENGINE_set_default_DSA(ENGINE *e);
int ENGINE_set_default_DH(ENGINE *e);
int ENGINE_set_default_RAND(ENGINE *e);
int ENGINE_set_default_ciphers(ENGINE *e);
int ENGINE_set_default_digests(ENGINE *e);
int ENGINE_set_default_string(ENGINE *e, const char *list);
int ENGINE_set_default(ENGINE *e, unsigned int flags);
unsigned int ENGINE_get_table_flags(void);
void ENGINE_set_table_flags(unsigned int flags);
int ENGINE_register_RSA(ENGINE *e);
void ENGINE_unregister_RSA(ENGINE *e);
void ENGINE_register_all_RSA(void);
int ENGINE_register_DSA(ENGINE *e);
void ENGINE_unregister_DSA(ENGINE *e);
void ENGINE_register_all_DSA(void);
int ENGINE_register_DH(ENGINE *e);
void ENGINE_unregister_DH(ENGINE *e);
void ENGINE_register_all_DH(void);
int ENGINE_register_RAND(ENGINE *e);
void ENGINE_unregister_RAND(ENGINE *e);
void ENGINE_register_all_RAND(void);
int ENGINE_register_ciphers(ENGINE *e);
void ENGINE_unregister_ciphers(ENGINE *e);
void ENGINE_register_all_ciphers(void);
int ENGINE_register_digests(ENGINE *e);
void ENGINE_unregister_digests(ENGINE *e);
void ENGINE_register_all_digests(void);
int ENGINE_register_complete(ENGINE *e);
int ENGINE_register_all_complete(void);
int ENGINE_ctrl(ENGINE *e, int cmd, long i, void *p, void (*f)(void));
int ENGINE_cmd_is_executable(ENGINE *e, int cmd);
int ENGINE_ctrl_cmd(ENGINE *e, const char *cmd_name,
long i, void *p, void (*f)(void), int cmd_optional);
int ENGINE_ctrl_cmd_string(ENGINE *e, const char *cmd_name, const char *arg,
int cmd_optional);
ENGINE *ENGINE_new(void);
int ENGINE_free(ENGINE *e);
int ENGINE_up_ref(ENGINE *e);
int ENGINE_set_id(ENGINE *e, const char *id);
int ENGINE_set_name(ENGINE *e, const char *name);
int ENGINE_set_RSA(ENGINE *e, const RSA_METHOD *rsa_meth);
int ENGINE_set_DSA(ENGINE *e, const DSA_METHOD *dsa_meth);
int ENGINE_set_DH(ENGINE *e, const DH_METHOD *dh_meth);
int ENGINE_set_RAND(ENGINE *e, const RAND_METHOD *rand_meth);
int ENGINE_set_destroy_function(ENGINE *e, ENGINE_GEN_INT_FUNC_PTR destroy_f);
int ENGINE_set_init_function(ENGINE *e, ENGINE_GEN_INT_FUNC_PTR init_f);
int ENGINE_set_finish_function(ENGINE *e, ENGINE_GEN_INT_FUNC_PTR finish_f);
int ENGINE_set_ctrl_function(ENGINE *e, ENGINE_CTRL_FUNC_PTR ctrl_f);
int ENGINE_set_load_privkey_function(ENGINE *e, ENGINE_LOAD_KEY_PTR loadpriv_f);
int ENGINE_set_load_pubkey_function(ENGINE *e, ENGINE_LOAD_KEY_PTR loadpub_f);
int ENGINE_set_ciphers(ENGINE *e, ENGINE_CIPHERS_PTR f);
int ENGINE_set_digests(ENGINE *e, ENGINE_DIGESTS_PTR f);
int ENGINE_set_flags(ENGINE *e, int flags);
int ENGINE_set_cmd_defns(ENGINE *e, const ENGINE_CMD_DEFN *defns);
const char *ENGINE_get_id(const ENGINE *e);
const char *ENGINE_get_name(const ENGINE *e);
const RSA_METHOD *ENGINE_get_RSA(const ENGINE *e);
const DSA_METHOD *ENGINE_get_DSA(const ENGINE *e);
const DH_METHOD *ENGINE_get_DH(const ENGINE *e);
const RAND_METHOD *ENGINE_get_RAND(const ENGINE *e);
ENGINE_GEN_INT_FUNC_PTR ENGINE_get_destroy_function(const ENGINE *e);
ENGINE_GEN_INT_FUNC_PTR ENGINE_get_init_function(const ENGINE *e);
ENGINE_GEN_INT_FUNC_PTR ENGINE_get_finish_function(const ENGINE *e);
ENGINE_CTRL_FUNC_PTR ENGINE_get_ctrl_function(const ENGINE *e);
ENGINE_LOAD_KEY_PTR ENGINE_get_load_privkey_function(const ENGINE *e);
ENGINE_LOAD_KEY_PTR ENGINE_get_load_pubkey_function(const ENGINE *e);
ENGINE_CIPHERS_PTR ENGINE_get_ciphers(const ENGINE *e);
ENGINE_DIGESTS_PTR ENGINE_get_digests(const ENGINE *e);
const EVP_CIPHER *ENGINE_get_cipher(ENGINE *e, int nid);
const EVP_MD *ENGINE_get_digest(ENGINE *e, int nid);
int ENGINE_get_flags(const ENGINE *e);
const ENGINE_CMD_DEFN *ENGINE_get_cmd_defns(const ENGINE *e);
EVP_PKEY *ENGINE_load_private_key(ENGINE *e, const char *key_id,
UI_METHOD *ui_method, void *callback_data);
EVP_PKEY *ENGINE_load_public_key(ENGINE *e, const char *key_id,
UI_METHOD *ui_method, void *callback_data);
The following function has been deprecated since OpenSSL 1.1.0, and can be
hidden entirely by defining B<OPENSSL_API_COMPAT> with a suitable version value,
see L<openssl_user_macros(7)>:
void ENGINE_cleanup(void);
=head1 DESCRIPTION
All of the functions described on this page are deprecated.
Applications should instead use the provider APIs.
These functions create, manipulate, and use cryptographic modules in the
form of B<ENGINE> objects. These objects act as containers for
implementations of cryptographic algorithms, and support a
reference-counted mechanism to allow them to be dynamically loaded in and
out of the running application.
The cryptographic functionality that can be provided by an B<ENGINE>
implementation includes the following abstractions;
RSA_METHOD - for providing alternative RSA implementations
DSA_METHOD, DH_METHOD, RAND_METHOD, ECDH_METHOD, ECDSA_METHOD,
- similarly for other OpenSSL APIs
EVP_CIPHER - potentially multiple cipher algorithms (indexed by 'nid')
EVP_DIGEST - potentially multiple hash algorithms (indexed by 'nid')
key-loading - loading public and/or private EVP_PKEY keys
=head2 Reference counting and handles
Due to the modular nature of the ENGINE API, pointers to ENGINEs need to be
treated as handles - i.e. not only as pointers, but also as references to
the underlying ENGINE object. Ie. one should obtain a new reference when
making copies of an ENGINE pointer if the copies will be used (and
released) independently.
ENGINE objects have two levels of reference-counting to match the way in
which the objects are used. At the most basic level, each ENGINE pointer is
inherently a B<structural> reference - a structural reference is required
to use the pointer value at all, as this kind of reference is a guarantee
that the structure can not be deallocated until the reference is released.
However, a structural reference provides no guarantee that the ENGINE is
initialised and able to use any of its cryptographic
implementations. Indeed it's quite possible that most ENGINEs will not
initialise at all in typical environments, as ENGINEs are typically used to
support specialised hardware. To use an ENGINE's functionality, you need a
B<functional> reference. This kind of reference can be considered a
specialised form of structural reference, because each functional reference
implicitly contains a structural reference as well - however to avoid
difficult-to-find programming bugs, it is recommended to treat the two
kinds of reference independently. If you have a functional reference to an
ENGINE, you have a guarantee that the ENGINE has been initialised and
is ready to perform cryptographic operations, and will remain initialised
until after you have released your reference.
I<Structural references>
This basic type of reference is used for instantiating new ENGINEs,
iterating across OpenSSL's internal linked-list of loaded
ENGINEs, reading information about an ENGINE, etc. Essentially a structural
reference is sufficient if you only need to query or manipulate the data of
an ENGINE implementation rather than use its functionality.
The ENGINE_new() function returns a structural reference to a new (empty)
ENGINE object. There are other ENGINE API functions that return structural
references such as; ENGINE_by_id(), ENGINE_get_first(), ENGINE_get_last(),
ENGINE_get_next(), ENGINE_get_prev(). All structural references should be
released by a corresponding to call to the ENGINE_free() function - the
ENGINE object itself will only actually be cleaned up and deallocated when
-the last structural reference is released.
+the last structural reference is released. If the argument to ENGINE_free()
+is NULL, nothing is done.
It should also be noted that many ENGINE API function calls that accept a
structural reference will internally obtain another reference - typically
this happens whenever the supplied ENGINE will be needed by OpenSSL after
the function has returned. Eg. the function to add a new ENGINE to
OpenSSL's internal list is ENGINE_add() - if this function returns success,
then OpenSSL will have stored a new structural reference internally so the
caller is still responsible for freeing their own reference with
ENGINE_free() when they are finished with it. In a similar way, some
functions will automatically release the structural reference passed to it
if part of the function's job is to do so. Eg. the ENGINE_get_next() and
ENGINE_get_prev() functions are used for iterating across the internal
ENGINE list - they will return a new structural reference to the next (or
previous) ENGINE in the list or NULL if at the end (or beginning) of the
list, but in either case the structural reference passed to the function is
released on behalf of the caller.
To clarify a particular function's handling of references, one should
always consult that function's documentation "man" page, or failing that
the F<< <openssl/engine.h> >> header file includes some hints.
I<Functional references>
As mentioned, functional references exist when the cryptographic
functionality of an ENGINE is required to be available. A functional
reference can be obtained in one of two ways; from an existing structural
reference to the required ENGINE, or by asking OpenSSL for the default
operational ENGINE for a given cryptographic purpose.
To obtain a functional reference from an existing structural reference,
call the ENGINE_init() function. This returns zero if the ENGINE was not
already operational and couldn't be successfully initialised (e.g. lack of
system drivers, no special hardware attached, etc), otherwise it will
return nonzero to indicate that the ENGINE is now operational and will
have allocated a new B<functional> reference to the ENGINE. All functional
references are released by calling ENGINE_finish() (which removes the
implicit structural reference as well).
The second way to get a functional reference is by asking OpenSSL for a
default implementation for a given task, e.g. by ENGINE_get_default_RSA(),
ENGINE_get_default_cipher_engine(), etc. These are discussed in the next
section, though they are not usually required by application programmers as
they are used automatically when creating and using the relevant
algorithm-specific types in OpenSSL, such as RSA, DSA, EVP_CIPHER_CTX, etc.
=head2 Default implementations
For each supported abstraction, the ENGINE code maintains an internal table
of state to control which implementations are available for a given
abstraction and which should be used by default. These implementations are
registered in the tables and indexed by an 'nid' value, because
abstractions like EVP_CIPHER and EVP_DIGEST support many distinct
algorithms and modes, and ENGINEs can support arbitrarily many of them.
In the case of other abstractions like RSA, DSA, etc, there is only one
"algorithm" so all implementations implicitly register using the same 'nid'
index.
When a default ENGINE is requested for a given abstraction/algorithm/mode, (e.g.
when calling RSA_new_method(NULL)), a "get_default" call will be made to the
ENGINE subsystem to process the corresponding state table and return a
functional reference to an initialised ENGINE whose implementation should be
used. If no ENGINE should (or can) be used, it will return NULL and the caller
will operate with a NULL ENGINE handle - this usually equates to using the
conventional software implementation. In the latter case, OpenSSL will from
then on behave the way it used to before the ENGINE API existed.
Each state table has a flag to note whether it has processed this
"get_default" query since the table was last modified, because to process
this question it must iterate across all the registered ENGINEs in the
table trying to initialise each of them in turn, in case one of them is
operational. If it returns a functional reference to an ENGINE, it will
also cache another reference to speed up processing future queries (without
needing to iterate across the table). Likewise, it will cache a NULL
response if no ENGINE was available so that future queries won't repeat the
same iteration unless the state table changes. This behaviour can also be
changed; if the ENGINE_TABLE_FLAG_NOINIT flag is set (using
ENGINE_set_table_flags()), no attempted initialisations will take place,
instead the only way for the state table to return a non-NULL ENGINE to the
"get_default" query will be if one is expressly set in the table. Eg.
ENGINE_set_default_RSA() does the same job as ENGINE_register_RSA() except
that it also sets the state table's cached response for the "get_default"
query. In the case of abstractions like EVP_CIPHER, where implementations are
indexed by 'nid', these flags and cached-responses are distinct for each 'nid'
value.
=head2 Application requirements
This section will explain the basic things an application programmer should
support to make the most useful elements of the ENGINE functionality
available to the user. The first thing to consider is whether the
programmer wishes to make alternative ENGINE modules available to the
application and user. OpenSSL maintains an internal linked list of
"visible" ENGINEs from which it has to operate - at start-up, this list is
empty and in fact if an application does not call any ENGINE API calls and
it uses static linking against openssl, then the resulting application
binary will not contain any alternative ENGINE code at all. So the first
consideration is whether any/all available ENGINE implementations should be
made visible to OpenSSL - this is controlled by calling the various "load"
functions.
The fact that ENGINEs are made visible to OpenSSL (and thus are linked into
the program and loaded into memory at run-time) does not mean they are
"registered" or called into use by OpenSSL automatically - that behaviour
is something for the application to control. Some applications
will want to allow the user to specify exactly which ENGINE they want used
if any is to be used at all. Others may prefer to load all support and have
OpenSSL automatically use at run-time any ENGINE that is able to
successfully initialise - i.e. to assume that this corresponds to
acceleration hardware attached to the machine or some such thing. There are
probably numerous other ways in which applications may prefer to handle
things, so we will simply illustrate the consequences as they apply to a
couple of simple cases and leave developers to consider these and the
source code to openssl's built-in utilities as guides.
If no ENGINE API functions are called within an application, then OpenSSL
will not allocate any internal resources. Prior to OpenSSL 1.1.0, however,
if any ENGINEs are loaded, even if not registered or used, it was necessary to
call ENGINE_cleanup() before the program exits.
I<Using a specific ENGINE implementation>
Here we'll assume an application has been configured by its user or admin
to want to use the "ACME" ENGINE if it is available in the version of
OpenSSL the application was compiled with. If it is available, it should be
used by default for all RSA, DSA, and symmetric cipher operations, otherwise
OpenSSL should use its built-in software as per usual. The following code
illustrates how to approach this;
ENGINE *e;
const char *engine_id = "ACME";
ENGINE_load_builtin_engines();
e = ENGINE_by_id(engine_id);
if (!e)
/* the engine isn't available */
return;
if (!ENGINE_init(e)) {
/* the engine couldn't initialise, release 'e' */
ENGINE_free(e);
return;
}
if (!ENGINE_set_default_RSA(e))
/*
* This should only happen when 'e' can't initialise, but the previous
* statement suggests it did.
*/
abort();
ENGINE_set_default_DSA(e);
ENGINE_set_default_ciphers(e);
/* Release the functional reference from ENGINE_init() */
ENGINE_finish(e);
/* Release the structural reference from ENGINE_by_id() */
ENGINE_free(e);
I<Automatically using built-in ENGINE implementations>
Here we'll assume we want to load and register all ENGINE implementations
bundled with OpenSSL, such that for any cryptographic algorithm required by
OpenSSL - if there is an ENGINE that implements it and can be initialised,
it should be used. The following code illustrates how this can work;
/* Load all bundled ENGINEs into memory and make them visible */
ENGINE_load_builtin_engines();
/* Register all of them for every algorithm they collectively implement */
ENGINE_register_all_complete();
That's all that's required. Eg. the next time OpenSSL tries to set up an
RSA key, any bundled ENGINEs that implement RSA_METHOD will be passed to
ENGINE_init() and if any of those succeed, that ENGINE will be set as the
default for RSA use from then on.
=head2 Advanced configuration support
There is a mechanism supported by the ENGINE framework that allows each
ENGINE implementation to define an arbitrary set of configuration
"commands" and expose them to OpenSSL and any applications based on
OpenSSL. This mechanism is entirely based on the use of name-value pairs
and assumes ASCII input (no unicode or UTF for now!), so it is ideal if
applications want to provide a transparent way for users to provide
arbitrary configuration "directives" directly to such ENGINEs. It is also
possible for the application to dynamically interrogate the loaded ENGINE
implementations for the names, descriptions, and input flags of their
available "control commands", providing a more flexible configuration
scheme. However, if the user is expected to know which ENGINE device he/she
is using (in the case of specialised hardware, this goes without saying)
then applications may not need to concern themselves with discovering the
supported control commands and simply prefer to pass settings into ENGINEs
exactly as they are provided by the user.
Before illustrating how control commands work, it is worth mentioning what
they are typically used for. Broadly speaking there are two uses for
control commands; the first is to provide the necessary details to the
implementation (which may know nothing at all specific to the host system)
so that it can be initialised for use. This could include the path to any
driver or config files it needs to load, required network addresses,
smart-card identifiers, passwords to initialise protected devices,
logging information, etc etc. This class of commands typically needs to be
passed to an ENGINE B<before> attempting to initialise it, i.e. before
calling ENGINE_init(). The other class of commands consist of settings or
operations that tweak certain behaviour or cause certain operations to take
place, and these commands may work either before or after ENGINE_init(), or
in some cases both. ENGINE implementations should provide indications of
this in the descriptions attached to built-in control commands and/or in
external product documentation.
I<Issuing control commands to an ENGINE>
Let's illustrate by example; a function for which the caller supplies the
name of the ENGINE it wishes to use, a table of string-pairs for use before
initialisation, and another table for use after initialisation. Note that
the string-pairs used for control commands consist of a command "name"
followed by the command "parameter" - the parameter could be NULL in some
cases but the name can not. This function should initialise the ENGINE
(issuing the "pre" commands beforehand and the "post" commands afterwards)
and set it as the default for everything except RAND and then return a
boolean success or failure.
int generic_load_engine_fn(const char *engine_id,
const char **pre_cmds, int pre_num,
const char **post_cmds, int post_num)
{
ENGINE *e = ENGINE_by_id(engine_id);
if (!e) return 0;
while (pre_num--) {
if (!ENGINE_ctrl_cmd_string(e, pre_cmds[0], pre_cmds[1], 0)) {
fprintf(stderr, "Failed command (%s - %s:%s)\n", engine_id,
pre_cmds[0], pre_cmds[1] ? pre_cmds[1] : "(NULL)");
ENGINE_free(e);
return 0;
}
pre_cmds += 2;
}
if (!ENGINE_init(e)) {
fprintf(stderr, "Failed initialisation\n");
ENGINE_free(e);
return 0;
}
/*
* ENGINE_init() returned a functional reference, so free the structural
* reference from ENGINE_by_id().
*/
ENGINE_free(e);
while (post_num--) {
if (!ENGINE_ctrl_cmd_string(e, post_cmds[0], post_cmds[1], 0)) {
fprintf(stderr, "Failed command (%s - %s:%s)\n", engine_id,
post_cmds[0], post_cmds[1] ? post_cmds[1] : "(NULL)");
ENGINE_finish(e);
return 0;
}
post_cmds += 2;
}
ENGINE_set_default(e, ENGINE_METHOD_ALL & ~ENGINE_METHOD_RAND);
/* Success */
return 1;
}
Note that ENGINE_ctrl_cmd_string() accepts a boolean argument that can
relax the semantics of the function - if set nonzero it will only return
failure if the ENGINE supported the given command name but failed while
executing it, if the ENGINE doesn't support the command name it will simply
return success without doing anything. In this case we assume the user is
only supplying commands specific to the given ENGINE so we set this to
FALSE.
I<Discovering supported control commands>
It is possible to discover at run-time the names, numerical-ids, descriptions
and input parameters of the control commands supported by an ENGINE using a
structural reference. Note that some control commands are defined by OpenSSL
itself and it will intercept and handle these control commands on behalf of the
ENGINE, i.e. the ENGINE's ctrl() handler is not used for the control command.
F<< <openssl/engine.h> >> defines an index, ENGINE_CMD_BASE, that all control
commands implemented by ENGINEs should be numbered from. Any command value
lower than this symbol is considered a "generic" command is handled directly
by the OpenSSL core routines.
It is using these "core" control commands that one can discover the control
commands implemented by a given ENGINE, specifically the commands:
ENGINE_HAS_CTRL_FUNCTION
ENGINE_CTRL_GET_FIRST_CMD_TYPE
ENGINE_CTRL_GET_NEXT_CMD_TYPE
ENGINE_CTRL_GET_CMD_FROM_NAME
ENGINE_CTRL_GET_NAME_LEN_FROM_CMD
ENGINE_CTRL_GET_NAME_FROM_CMD
ENGINE_CTRL_GET_DESC_LEN_FROM_CMD
ENGINE_CTRL_GET_DESC_FROM_CMD
ENGINE_CTRL_GET_CMD_FLAGS
Whilst these commands are automatically processed by the OpenSSL framework code,
they use various properties exposed by each ENGINE to process these
queries. An ENGINE has 3 properties it exposes that can affect how this behaves;
it can supply a ctrl() handler, it can specify ENGINE_FLAGS_MANUAL_CMD_CTRL in
the ENGINE's flags, and it can expose an array of control command descriptions.
If an ENGINE specifies the ENGINE_FLAGS_MANUAL_CMD_CTRL flag, then it will
simply pass all these "core" control commands directly to the ENGINE's ctrl()
handler (and thus, it must have supplied one), so it is up to the ENGINE to
reply to these "discovery" commands itself. If that flag is not set, then the
OpenSSL framework code will work with the following rules:
if no ctrl() handler supplied;
ENGINE_HAS_CTRL_FUNCTION returns FALSE (zero),
all other commands fail.
if a ctrl() handler was supplied but no array of control commands;
ENGINE_HAS_CTRL_FUNCTION returns TRUE,
all other commands fail.
if a ctrl() handler and array of control commands was supplied;
ENGINE_HAS_CTRL_FUNCTION returns TRUE,
all other commands proceed processing ...
If the ENGINE's array of control commands is empty then all other commands will
fail, otherwise; ENGINE_CTRL_GET_FIRST_CMD_TYPE returns the identifier of
the first command supported by the ENGINE, ENGINE_GET_NEXT_CMD_TYPE takes the
identifier of a command supported by the ENGINE and returns the next command
identifier or fails if there are no more, ENGINE_CMD_FROM_NAME takes a string
name for a command and returns the corresponding identifier or fails if no such
command name exists, and the remaining commands take a command identifier and
return properties of the corresponding commands. All except
ENGINE_CTRL_GET_FLAGS return the string length of a command name or description,
or populate a supplied character buffer with a copy of the command name or
description. ENGINE_CTRL_GET_FLAGS returns a bitwise-OR'd mask of the following
possible values:
ENGINE_CMD_FLAG_NUMERIC
ENGINE_CMD_FLAG_STRING
ENGINE_CMD_FLAG_NO_INPUT
ENGINE_CMD_FLAG_INTERNAL
If the ENGINE_CMD_FLAG_INTERNAL flag is set, then any other flags are purely
informational to the caller - this flag will prevent the command being usable
for any higher-level ENGINE functions such as ENGINE_ctrl_cmd_string().
"INTERNAL" commands are not intended to be exposed to text-based configuration
by applications, administrations, users, etc. These can support arbitrary
operations via ENGINE_ctrl(), including passing to and/or from the control
commands data of any arbitrary type. These commands are supported in the
discovery mechanisms simply to allow applications to determine if an ENGINE
supports certain specific commands it might want to use (e.g. application "foo"
might query various ENGINEs to see if they implement "FOO_GET_VENDOR_LOGO_GIF" -
and ENGINE could therefore decide whether or not to support this "foo"-specific
extension).
=head1 ENVIRONMENT
=over 4
=item B<OPENSSL_ENGINES>
The path to the engines directory.
Ignored in set-user-ID and set-group-ID programs.
=back
=head1 RETURN VALUES
ENGINE_get_first(), ENGINE_get_last(), ENGINE_get_next() and ENGINE_get_prev()
return a valid B<ENGINE> structure or NULL if an error occurred.
ENGINE_add() and ENGINE_remove() return 1 on success or 0 on error.
ENGINE_by_id() returns a valid B<ENGINE> structure or NULL if an error occurred.
ENGINE_init() and ENGINE_finish() return 1 on success or 0 on error.
All ENGINE_get_default_TYPE() functions, ENGINE_get_cipher_engine() and
ENGINE_get_digest_engine() return a valid B<ENGINE> structure on success or NULL
if an error occurred.
All ENGINE_set_default_TYPE() functions return 1 on success or 0 on error.
ENGINE_set_default() returns 1 on success or 0 on error.
ENGINE_get_table_flags() returns an unsigned integer value representing the
global table flags which are used to control the registration behaviour of
B<ENGINE> implementations.
All ENGINE_register_TYPE() functions return 1 on success or 0 on error.
ENGINE_register_complete() and ENGINE_register_all_complete() always return 1.
ENGINE_ctrl() returns a positive value on success or others on error.
ENGINE_cmd_is_executable() returns 1 if B<cmd> is executable or 0 otherwise.
ENGINE_ctrl_cmd() and ENGINE_ctrl_cmd_string() return 1 on success or 0 on error.
ENGINE_new() returns a valid B<ENGINE> structure on success or NULL if an error
occurred.
ENGINE_free() always returns 1.
ENGINE_up_ref() returns 1 on success or 0 on error.
ENGINE_set_id() and ENGINE_set_name() return 1 on success or 0 on error.
All other B<ENGINE_set_*> functions return 1 on success or 0 on error.
ENGINE_get_id() and ENGINE_get_name() return a string representing the identifier
and the name of the ENGINE B<e> respectively.
ENGINE_get_RSA(), ENGINE_get_DSA(), ENGINE_get_DH() and ENGINE_get_RAND()
return corresponding method structures for each algorithms.
ENGINE_get_destroy_function(), ENGINE_get_init_function(),
ENGINE_get_finish_function(), ENGINE_get_ctrl_function(),
ENGINE_get_load_privkey_function(), ENGINE_get_load_pubkey_function(),
ENGINE_get_ciphers() and ENGINE_get_digests() return corresponding function
pointers of the callbacks.
ENGINE_get_cipher() returns a valid B<EVP_CIPHER> structure on success or NULL
if an error occurred.
ENGINE_get_digest() returns a valid B<EVP_MD> structure on success or NULL if an
error occurred.
ENGINE_get_flags() returns an integer representing the ENGINE flags which are
used to control various behaviours of an ENGINE.
ENGINE_get_cmd_defns() returns an B<ENGINE_CMD_DEFN> structure or NULL if it's
not set.
ENGINE_load_private_key() and ENGINE_load_public_key() return a valid B<EVP_PKEY>
structure on success or NULL if an error occurred.
=head1 SEE ALSO
L<OPENSSL_init_crypto(3)>, L<RSA_new_method(3)>, L<DSA_new(3)>, L<DH_new(3)>,
L<RAND_bytes(3)>, L<config(5)>
=head1 HISTORY
All of these functions were deprecated in OpenSSL 3.0.
ENGINE_cleanup() was deprecated in OpenSSL 1.1.0 by the automatic cleanup
done by OPENSSL_cleanup()
and should not be used.
=head1 COPYRIGHT
-Copyright 2002-2021 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
L<https://www.openssl.org/source/license.html>.
=cut
diff --git a/crypto/openssl/doc/man3/EVP_ASYM_CIPHER_free.pod b/crypto/openssl/doc/man3/EVP_ASYM_CIPHER_free.pod
index c158ec1ae74a..162ad7ed7687 100644
--- a/crypto/openssl/doc/man3/EVP_ASYM_CIPHER_free.pod
+++ b/crypto/openssl/doc/man3/EVP_ASYM_CIPHER_free.pod
@@ -1,112 +1,112 @@
=pod
=head1 NAME
EVP_ASYM_CIPHER_fetch, EVP_ASYM_CIPHER_free, EVP_ASYM_CIPHER_up_ref,
EVP_ASYM_CIPHER_is_a, EVP_ASYM_CIPHER_get0_provider,
EVP_ASYM_CIPHER_do_all_provided, EVP_ASYM_CIPHER_names_do_all,
EVP_ASYM_CIPHER_get0_name, EVP_ASYM_CIPHER_get0_description,
EVP_ASYM_CIPHER_gettable_ctx_params, EVP_ASYM_CIPHER_settable_ctx_params
- Functions to manage EVP_ASYM_CIPHER algorithm objects
=head1 SYNOPSIS
#include <openssl/evp.h>
EVP_ASYM_CIPHER *EVP_ASYM_CIPHER_fetch(OSSL_LIB_CTX *ctx, const char *algorithm,
const char *properties);
void EVP_ASYM_CIPHER_free(EVP_ASYM_CIPHER *cipher);
int EVP_ASYM_CIPHER_up_ref(EVP_ASYM_CIPHER *cipher);
const char *EVP_ASYM_CIPHER_get0_name(const EVP_ASYM_CIPHER *cipher);
int EVP_ASYM_CIPHER_is_a(const EVP_ASYM_CIPHER *cipher, const char *name);
OSSL_PROVIDER *EVP_ASYM_CIPHER_get0_provider(const EVP_ASYM_CIPHER *cipher);
void EVP_ASYM_CIPHER_do_all_provided(OSSL_LIB_CTX *libctx,
void (*fn)(EVP_ASYM_CIPHER *cipher,
void *arg),
void *arg);
int EVP_ASYM_CIPHER_names_do_all(const EVP_ASYM_CIPHER *cipher,
void (*fn)(const char *name, void *data),
void *data);
const char *EVP_ASYM_CIPHER_get0_description(const EVP_ASYM_CIPHER *cipher);
const OSSL_PARAM *EVP_ASYM_CIPHER_gettable_ctx_params(const EVP_ASYM_CIPHER *cip);
const OSSL_PARAM *EVP_ASYM_CIPHER_settable_ctx_params(const EVP_ASYM_CIPHER *cip);
=head1 DESCRIPTION
EVP_ASYM_CIPHER_fetch() fetches the implementation for the given
B<algorithm> from any provider offering it, within the criteria given
by the B<properties> and in the scope of the given library context B<ctx> (see
L<OSSL_LIB_CTX(3)>). The algorithm will be one offering functions for performing
asymmetric cipher related tasks such as asymmetric encryption and decryption.
See L<crypto(7)/ALGORITHM FETCHING> for further information.
The returned value must eventually be freed with EVP_ASYM_CIPHER_free().
EVP_ASYM_CIPHER_free() decrements the reference count for the B<EVP_ASYM_CIPHER>
structure. Typically this structure will have been obtained from an earlier call
to EVP_ASYM_CIPHER_fetch(). If the reference count drops to 0 then the
-structure is freed.
+structure is freed. If the argument is NULL, nothing is done.
EVP_ASYM_CIPHER_up_ref() increments the reference count for an
B<EVP_ASYM_CIPHER> structure.
EVP_ASYM_CIPHER_is_a() returns 1 if I<cipher> is an implementation of an
algorithm that's identifiable with I<name>, otherwise 0.
EVP_ASYM_CIPHER_get0_provider() returns the provider that I<cipher> was
fetched from.
EVP_ASYM_CIPHER_do_all_provided() traverses all EVP_ASYM_CIPHERs 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_ASYM_CIPHER_get0_name() returns the algorithm name from the provided
implementation for the given I<cipher>. Note that the I<cipher> may have
multiple synonyms associated with it. In this case the first name from the
algorithm definition is returned. Ownership of the returned string is retained
by the I<cipher> object and should not be freed by the caller.
EVP_ASYM_CIPHER_names_do_all() traverses all names for I<cipher>, and calls
I<fn> with each name and I<data>.
EVP_ASYM_CIPHER_get0_description() returns a description of the I<cipher>,
meant for display and human consumption. The description is at the
discretion of the I<cipher> implementation.
EVP_ASYM_CIPHER_gettable_ctx_params() and EVP_ASYM_CIPHER_settable_ctx_params()
return a constant L<OSSL_PARAM(3)> array that describes the names and types of key
parameters that can be retrieved or set by a key encryption algorithm using
L<EVP_PKEY_CTX_get_params(3)> and L<EVP_PKEY_CTX_set_params(3)>.
=head1 RETURN VALUES
EVP_ASYM_CIPHER_fetch() returns a pointer to an B<EVP_ASYM_CIPHER> for success
or B<NULL> for failure.
EVP_ASYM_CIPHER_up_ref() returns 1 for success or 0 otherwise.
EVP_ASYM_CIPHER_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.
EVP_ASYM_CIPHER_gettable_ctx_params() and EVP_ASYM_CIPHER_settable_ctx_params()
return a constant L<OSSL_PARAM(3)> array or NULL on error.
=head1 SEE ALSO
L<crypto(7)/ALGORITHM FETCHING>, L<OSSL_PROVIDER(3)>
=head1 HISTORY
The functions described here were added in 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/man3/EVP_CIPHER_meth_new.pod b/crypto/openssl/doc/man3/EVP_CIPHER_meth_new.pod
index 8b862d9d99c8..8638cd3009c7 100644
--- a/crypto/openssl/doc/man3/EVP_CIPHER_meth_new.pod
+++ b/crypto/openssl/doc/man3/EVP_CIPHER_meth_new.pod
@@ -1,259 +1,260 @@
=pod
=head1 NAME
EVP_CIPHER_meth_new, EVP_CIPHER_meth_dup, EVP_CIPHER_meth_free,
EVP_CIPHER_meth_set_iv_length, EVP_CIPHER_meth_set_flags,
EVP_CIPHER_meth_set_impl_ctx_size, EVP_CIPHER_meth_set_init,
EVP_CIPHER_meth_set_do_cipher, EVP_CIPHER_meth_set_cleanup,
EVP_CIPHER_meth_set_set_asn1_params, EVP_CIPHER_meth_set_get_asn1_params,
EVP_CIPHER_meth_set_ctrl, EVP_CIPHER_meth_get_init,
EVP_CIPHER_meth_get_do_cipher, EVP_CIPHER_meth_get_cleanup,
EVP_CIPHER_meth_get_set_asn1_params, EVP_CIPHER_meth_get_get_asn1_params,
EVP_CIPHER_meth_get_ctrl
- Routines to build up EVP_CIPHER methods
=head1 SYNOPSIS
#include <openssl/evp.h>
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)>:
EVP_CIPHER *EVP_CIPHER_meth_new(int cipher_type, int block_size, int key_len);
EVP_CIPHER *EVP_CIPHER_meth_dup(const EVP_CIPHER *cipher);
void EVP_CIPHER_meth_free(EVP_CIPHER *cipher);
int EVP_CIPHER_meth_set_iv_length(EVP_CIPHER *cipher, int iv_len);
int EVP_CIPHER_meth_set_flags(EVP_CIPHER *cipher, unsigned long flags);
int EVP_CIPHER_meth_set_impl_ctx_size(EVP_CIPHER *cipher, int ctx_size);
int EVP_CIPHER_meth_set_init(EVP_CIPHER *cipher,
int (*init)(EVP_CIPHER_CTX *ctx,
const unsigned char *key,
const unsigned char *iv,
int enc));
int EVP_CIPHER_meth_set_do_cipher(EVP_CIPHER *cipher,
int (*do_cipher)(EVP_CIPHER_CTX *ctx,
unsigned char *out,
const unsigned char *in,
size_t inl));
int EVP_CIPHER_meth_set_cleanup(EVP_CIPHER *cipher,
int (*cleanup)(EVP_CIPHER_CTX *));
int EVP_CIPHER_meth_set_set_asn1_params(EVP_CIPHER *cipher,
int (*set_asn1_parameters)(EVP_CIPHER_CTX *,
ASN1_TYPE *));
int EVP_CIPHER_meth_set_get_asn1_params(EVP_CIPHER *cipher,
int (*get_asn1_parameters)(EVP_CIPHER_CTX *,
ASN1_TYPE *));
int EVP_CIPHER_meth_set_ctrl(EVP_CIPHER *cipher,
int (*ctrl)(EVP_CIPHER_CTX *, int type,
int arg, void *ptr));
int (*EVP_CIPHER_meth_get_init(const EVP_CIPHER *cipher))(EVP_CIPHER_CTX *ctx,
const unsigned char *key,
const unsigned char *iv,
int enc);
int (*EVP_CIPHER_meth_get_do_cipher(const EVP_CIPHER *cipher))(EVP_CIPHER_CTX *ctx,
unsigned char *out,
const unsigned char *in,
size_t inl);
int (*EVP_CIPHER_meth_get_cleanup(const EVP_CIPHER *cipher))(EVP_CIPHER_CTX *);
int (*EVP_CIPHER_meth_get_set_asn1_params(const EVP_CIPHER *cipher))(EVP_CIPHER_CTX *,
ASN1_TYPE *);
int (*EVP_CIPHER_meth_get_get_asn1_params(const EVP_CIPHER *cipher))(EVP_CIPHER_CTX *,
ASN1_TYPE *);
int (*EVP_CIPHER_meth_get_ctrl(const EVP_CIPHER *cipher))(EVP_CIPHER_CTX *,
int type, int arg,
void *ptr);
=head1 DESCRIPTION
All of the functions described on this page are deprecated.
Applications should instead use the OSSL_PROVIDER APIs.
The B<EVP_CIPHER> type is a structure for symmetric cipher method
implementation.
EVP_CIPHER_meth_new() creates a new B<EVP_CIPHER> structure.
EVP_CIPHER_meth_dup() creates a copy of B<cipher>.
EVP_CIPHER_meth_free() destroys a B<EVP_CIPHER> structure.
+If the argument is NULL, nothing is done.
EVP_CIPHER_meth_set_iv_length() sets the length of the IV.
This is only needed when the implemented cipher mode requires it.
EVP_CIPHER_meth_set_flags() sets the flags to describe optional
behaviours in the particular B<cipher>.
With the exception of cipher modes, of which only one may be present,
several flags can be or'd together.
The available flags are:
=over 4
=item EVP_CIPH_STREAM_CIPHER, EVP_CIPH_ECB_MODE EVP_CIPH_CBC_MODE,
EVP_CIPH_CFB_MODE, EVP_CIPH_OFB_MODE, EVP_CIPH_CTR_MODE, EVP_CIPH_GCM_MODE,
EVP_CIPH_CCM_MODE, EVP_CIPH_XTS_MODE, EVP_CIPH_WRAP_MODE,
EVP_CIPH_OCB_MODE, EVP_CIPH_SIV_MODE
The cipher mode.
=item EVP_CIPH_VARIABLE_LENGTH
This cipher is of variable length.
=item EVP_CIPH_CUSTOM_IV
Storing and initialising the IV is left entirely to the
implementation.
=item EVP_CIPH_ALWAYS_CALL_INIT
Set this if the implementation's init() function should be called even
if B<key> is B<NULL>.
=item EVP_CIPH_CTRL_INIT
Set this to have the implementation's ctrl() function called with
command code B<EVP_CTRL_INIT> early in its setup.
=item EVP_CIPH_CUSTOM_KEY_LENGTH
Checking and setting the key length after creating the B<EVP_CIPHER>
is left to the implementation.
Whenever someone uses EVP_CIPHER_CTX_set_key_length() on a
B<EVP_CIPHER> with this flag set, the implementation's ctrl() function
will be called with the control code B<EVP_CTRL_SET_KEY_LENGTH> and
the key length in B<arg>.
=item EVP_CIPH_NO_PADDING
Don't use standard block padding.
=item EVP_CIPH_RAND_KEY
Making a key with random content is left to the implementation.
This is done by calling the implementation's ctrl() function with the
control code B<EVP_CTRL_RAND_KEY> and the pointer to the key memory
storage in B<ptr>.
=item EVP_CIPH_CUSTOM_COPY
Set this to have the implementation's ctrl() function called with
command code B<EVP_CTRL_COPY> at the end of EVP_CIPHER_CTX_copy().
The intended use is for further things to deal with after the
implementation specific data block has been copied.
The destination B<EVP_CIPHER_CTX> is passed to the control with the
B<ptr> parameter.
The implementation specific data block is reached with
EVP_CIPHER_CTX_get_cipher_data().
=item EVP_CIPH_FLAG_DEFAULT_ASN1
Use the default EVP routines to pass IV to and from ASN.1.
=item EVP_CIPH_FLAG_LENGTH_BITS
Signals that the length of the input buffer for encryption /
decryption is to be understood as the number of bits instead of
bytes for this implementation.
This is only useful for CFB1 ciphers.
=item EVP_CIPH_FLAG_CTS
Indicates that the cipher uses ciphertext stealing. This is currently
used to indicate that the cipher is a one shot that only allows a single call to
EVP_CipherUpdate().
=item EVP_CIPH_FLAG_CUSTOM_CIPHER
This indicates that the implementation takes care of everything,
including padding, buffering and finalization.
The EVP routines will simply give them control and do nothing more.
=item EVP_CIPH_FLAG_AEAD_CIPHER
This indicates that this is an AEAD cipher implementation.
=item EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK
Allow interleaving of crypto blocks, a particular optimization only applicable
to certain TLS ciphers.
=back
EVP_CIPHER_meth_set_impl_ctx_size() sets the size of the EVP_CIPHER's
implementation context so that it can be automatically allocated.
EVP_CIPHER_meth_set_init() sets the cipher init function for
B<cipher>.
The cipher init function is called by EVP_CipherInit(),
EVP_CipherInit_ex(), EVP_EncryptInit(), EVP_EncryptInit_ex(),
EVP_DecryptInit(), EVP_DecryptInit_ex().
EVP_CIPHER_meth_set_do_cipher() sets the cipher function for
B<cipher>.
The cipher function is called by EVP_CipherUpdate(),
EVP_EncryptUpdate(), EVP_DecryptUpdate(), EVP_CipherFinal(),
EVP_EncryptFinal(), EVP_EncryptFinal_ex(), EVP_DecryptFinal() and
EVP_DecryptFinal_ex().
EVP_CIPHER_meth_set_cleanup() sets the function for B<cipher> to do
extra cleanup before the method's private data structure is cleaned
out and freed.
Note that the cleanup function is passed a B<EVP_CIPHER_CTX *>, the
private data structure is then available with
EVP_CIPHER_CTX_get_cipher_data().
This cleanup function is called by EVP_CIPHER_CTX_reset() and
EVP_CIPHER_CTX_free().
EVP_CIPHER_meth_set_set_asn1_params() sets the function for B<cipher>
to set the AlgorithmIdentifier "parameter" based on the passed cipher.
This function is called by EVP_CIPHER_param_to_asn1().
EVP_CIPHER_meth_set_get_asn1_params() sets the function for B<cipher>
that sets the cipher parameters based on an ASN.1 AlgorithmIdentifier
"parameter".
Both these functions are needed when there is a need for custom data
(more or other than the cipher IV).
They are called by EVP_CIPHER_param_to_asn1() and
EVP_CIPHER_asn1_to_param() respectively if defined.
EVP_CIPHER_meth_set_ctrl() sets the control function for B<cipher>.
EVP_CIPHER_meth_get_init(), EVP_CIPHER_meth_get_do_cipher(),
EVP_CIPHER_meth_get_cleanup(), EVP_CIPHER_meth_get_set_asn1_params(),
EVP_CIPHER_meth_get_get_asn1_params() and EVP_CIPHER_meth_get_ctrl()
are all used to retrieve the method data given with the
EVP_CIPHER_meth_set_*() functions above.
=head1 RETURN VALUES
EVP_CIPHER_meth_new() and EVP_CIPHER_meth_dup() return a pointer to a
newly created B<EVP_CIPHER>, or NULL on failure.
All EVP_CIPHER_meth_set_*() functions return 1.
All EVP_CIPHER_meth_get_*() functions return pointers to their
respective B<cipher> function.
=head1 SEE ALSO
L<EVP_EncryptInit(3)>
=head1 HISTORY
All of these functions were deprecated in OpenSSL 3.0.
The functions described here were added in OpenSSL 1.1.0.
The B<EVP_CIPHER> structure created with these functions became reference
counted in OpenSSL 3.0.
=head1 COPYRIGHT
-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
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 d7202c538172..de30191b61ac 100644
--- a/crypto/openssl/doc/man3/EVP_DigestInit.pod
+++ b/crypto/openssl/doc/man3/EVP_DigestInit.pod
@@ -1,794 +1,800 @@
=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.
+If the argument is NULL, nothing is done.
=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.
+If the argument is NULL, nothing is done.
=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_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
+=item EVP_MD_CTX_FLAG_CLEANED
-=for comment EVP_MD_CTX_FLAG_REUSE is internal, don't mention it
+This flag is for internal use only and I<must not> be used in user code.
+
+=item EVP_MD_CTX_FLAG_REUSE
+
+This flag is for internal use only and I<must not> be used in user code.
=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-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_EncodeInit.pod b/crypto/openssl/doc/man3/EVP_EncodeInit.pod
index 2b9e02e02d79..03c6f4e60579 100644
--- a/crypto/openssl/doc/man3/EVP_EncodeInit.pod
+++ b/crypto/openssl/doc/man3/EVP_EncodeInit.pod
@@ -1,161 +1,161 @@
=pod
=head1 NAME
EVP_ENCODE_CTX_new, EVP_ENCODE_CTX_free, EVP_ENCODE_CTX_copy,
EVP_ENCODE_CTX_num, EVP_EncodeInit, EVP_EncodeUpdate, EVP_EncodeFinal,
EVP_EncodeBlock, EVP_DecodeInit, EVP_DecodeUpdate, EVP_DecodeFinal,
EVP_DecodeBlock - EVP base 64 encode/decode routines
=head1 SYNOPSIS
#include <openssl/evp.h>
EVP_ENCODE_CTX *EVP_ENCODE_CTX_new(void);
void EVP_ENCODE_CTX_free(EVP_ENCODE_CTX *ctx);
int EVP_ENCODE_CTX_copy(EVP_ENCODE_CTX *dctx, EVP_ENCODE_CTX *sctx);
int EVP_ENCODE_CTX_num(EVP_ENCODE_CTX *ctx);
void EVP_EncodeInit(EVP_ENCODE_CTX *ctx);
int EVP_EncodeUpdate(EVP_ENCODE_CTX *ctx, unsigned char *out, int *outl,
const unsigned char *in, int inl);
void EVP_EncodeFinal(EVP_ENCODE_CTX *ctx, unsigned char *out, int *outl);
int EVP_EncodeBlock(unsigned char *t, const unsigned char *f, int n);
void EVP_DecodeInit(EVP_ENCODE_CTX *ctx);
int EVP_DecodeUpdate(EVP_ENCODE_CTX *ctx, unsigned char *out, int *outl,
const unsigned char *in, int inl);
int EVP_DecodeFinal(EVP_ENCODE_CTX *ctx, unsigned char *out, int *outl);
int EVP_DecodeBlock(unsigned char *t, const unsigned char *f, int n);
=head1 DESCRIPTION
The EVP encode routines provide a high-level interface to base 64 encoding and
decoding. Base 64 encoding converts binary data into a printable form that uses
the characters A-Z, a-z, 0-9, "+" and "/" to represent the data. For every 3
bytes of binary data provided 4 bytes of base 64 encoded data will be produced
plus some occasional newlines (see below). If the input data length is not a
multiple of 3 then the output data will be padded at the end using the "="
character.
EVP_ENCODE_CTX_new() allocates, initializes and returns a context to be used for
the encode/decode functions.
EVP_ENCODE_CTX_free() cleans up an encode/decode context B<ctx> and frees up the
-space allocated to it.
+space allocated to it. If the argument is NULL, nothing is done.
Encoding of binary data is performed in blocks of 48 input bytes (or less for
the final block). For each 48 byte input block encoded 64 bytes of base 64 data
is output plus an additional newline character (i.e. 65 bytes in total). The
final block (which may be less than 48 bytes) will output 4 bytes for every 3
bytes of input. If the data length is not divisible by 3 then a full 4 bytes is
still output for the final 1 or 2 bytes of input. Similarly a newline character
will also be output.
EVP_EncodeInit() initialises B<ctx> for the start of a new encoding operation.
EVP_EncodeUpdate() encode B<inl> bytes of data found in the buffer pointed to by
B<in>. The output is stored in the buffer B<out> and the number of bytes output
is stored in B<*outl>. It is the caller's responsibility to ensure that the
buffer at B<out> is sufficiently large to accommodate the output data. Only full
blocks of data (48 bytes) will be immediately processed and output by this
function. Any remainder is held in the B<ctx> object and will be processed by a
subsequent call to EVP_EncodeUpdate() or EVP_EncodeFinal(). To calculate the
required size of the output buffer add together the value of B<inl> with the
amount of unprocessed data held in B<ctx> and divide the result by 48 (ignore
any remainder). This gives the number of blocks of data that will be processed.
Ensure the output buffer contains 65 bytes of storage for each block, plus an
additional byte for a NUL terminator. EVP_EncodeUpdate() may be called
repeatedly to process large amounts of input data. In the event of an error
EVP_EncodeUpdate() will set B<*outl> to 0 and return 0. On success 1 will be
returned.
EVP_EncodeFinal() must be called at the end of an encoding operation. It will
process any partial block of data remaining in the B<ctx> object. The output
data will be stored in B<out> and the length of the data written will be stored
in B<*outl>. It is the caller's responsibility to ensure that B<out> is
sufficiently large to accommodate the output data which will never be more than
65 bytes plus an additional NUL terminator (i.e. 66 bytes in total).
EVP_ENCODE_CTX_copy() can be used to copy a context B<sctx> to a context
B<dctx>. B<dctx> must be initialized before calling this function.
EVP_ENCODE_CTX_num() will return the number of as yet unprocessed bytes still to
be encoded or decoded that are pending in the B<ctx> object.
EVP_EncodeBlock() encodes a full block of input data in B<f> and of length
B<n> and stores it in B<t>. For every 3 bytes of input provided 4 bytes of
output data will be produced. If B<n> is not divisible by 3 then the block is
encoded as a final block of data and the output is padded such that it is always
divisible by 4. Additionally a NUL terminator character will be added. For
example if 16 bytes of input data is provided then 24 bytes of encoded data is
created plus 1 byte for a NUL terminator (i.e. 25 bytes in total). The length of
the data generated I<without> the NUL terminator is returned from the function.
EVP_DecodeInit() initialises B<ctx> for the start of a new decoding operation.
EVP_DecodeUpdate() decodes B<inl> characters of data found in the buffer pointed
to by B<in>. The output is stored in the buffer B<out> and the number of bytes
output is stored in B<*outl>. It is the caller's responsibility to ensure that
the buffer at B<out> is sufficiently large to accommodate the output data. This
function will attempt to decode as much data as possible in 4 byte chunks. Any
whitespace, newline or carriage return characters are ignored. Any partial chunk
of unprocessed data (1, 2 or 3 bytes) that remains at the end will be held in
the B<ctx> object and processed by a subsequent call to EVP_DecodeUpdate(). If
any illegal base 64 characters are encountered or if the base 64 padding
character "=" is encountered in the middle of the data then the function returns
-1 to indicate an error. A return value of 0 or 1 indicates successful
processing of the data. A return value of 0 additionally indicates that the last
input data characters processed included the base 64 padding character "=" and
therefore no more non-padding character data is expected to be processed. For
every 4 valid base 64 bytes processed (ignoring whitespace, carriage returns and
line feeds), 3 bytes of binary output data will be produced (or less at the end
of the data where the padding character "=" has been used).
EVP_DecodeFinal() must be called at the end of a decoding operation. If there
is any unprocessed data still in B<ctx> then the input data must not have been
a multiple of 4 and therefore an error has occurred. The function will return -1
in this case. Otherwise the function returns 1 on success.
EVP_DecodeBlock() will decode the block of B<n> characters of base 64 data
contained in B<f> and store the result in B<t>. Any leading whitespace will be
trimmed as will any trailing whitespace, newlines, carriage returns or EOF
characters. After such trimming the length of the data in B<f> must be divisible
by 4. For every 4 input bytes exactly 3 output bytes will be produced. The
output will be padded with 0 bits if necessary to ensure that the output is
always 3 bytes for every 4 input bytes. This function will return the length of
the data decoded or -1 on error.
=head1 RETURN VALUES
EVP_ENCODE_CTX_new() returns a pointer to the newly allocated EVP_ENCODE_CTX
object or NULL on error.
EVP_ENCODE_CTX_num() returns the number of bytes pending encoding or decoding in
B<ctx>.
EVP_EncodeUpdate() returns 0 on error or 1 on success.
EVP_EncodeBlock() returns the number of bytes encoded excluding the NUL
terminator.
EVP_DecodeUpdate() returns -1 on error and 0 or 1 on success. If 0 is returned
then no more non-padding base 64 characters are expected.
EVP_DecodeFinal() returns -1 on error or 1 on success.
EVP_DecodeBlock() returns the length of the data decoded or -1 on error.
=head1 SEE ALSO
L<evp(7)>
=head1 COPYRIGHT
-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 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_EncryptInit.pod b/crypto/openssl/doc/man3/EVP_EncryptInit.pod
index 12d7153d0fd4..f037d135c9da 100644
--- a/crypto/openssl/doc/man3/EVP_EncryptInit.pod
+++ b/crypto/openssl/doc/man3/EVP_EncryptInit.pod
@@ -1,1743 +1,1748 @@
=pod
=head1 NAME
EVP_CIPHER_fetch,
EVP_CIPHER_up_ref,
EVP_CIPHER_free,
EVP_CIPHER_CTX_new,
EVP_CIPHER_CTX_reset,
EVP_CIPHER_CTX_free,
EVP_EncryptInit_ex,
EVP_EncryptInit_ex2,
EVP_EncryptUpdate,
EVP_EncryptFinal_ex,
EVP_DecryptInit_ex,
EVP_DecryptInit_ex2,
EVP_DecryptUpdate,
EVP_DecryptFinal_ex,
EVP_CipherInit_ex,
EVP_CipherInit_ex2,
EVP_CipherUpdate,
EVP_CipherFinal_ex,
EVP_CIPHER_CTX_set_key_length,
EVP_CIPHER_CTX_ctrl,
EVP_EncryptInit,
EVP_EncryptFinal,
EVP_DecryptInit,
EVP_DecryptFinal,
EVP_CipherInit,
EVP_CipherFinal,
EVP_Cipher,
EVP_get_cipherbyname,
EVP_get_cipherbynid,
EVP_get_cipherbyobj,
EVP_CIPHER_is_a,
EVP_CIPHER_get0_name,
EVP_CIPHER_get0_description,
EVP_CIPHER_names_do_all,
EVP_CIPHER_get0_provider,
EVP_CIPHER_get_nid,
EVP_CIPHER_get_params,
EVP_CIPHER_gettable_params,
EVP_CIPHER_get_block_size,
EVP_CIPHER_get_key_length,
EVP_CIPHER_get_iv_length,
EVP_CIPHER_get_flags,
EVP_CIPHER_get_mode,
EVP_CIPHER_get_type,
EVP_CIPHER_CTX_cipher,
EVP_CIPHER_CTX_get0_cipher,
EVP_CIPHER_CTX_get1_cipher,
EVP_CIPHER_CTX_get0_name,
EVP_CIPHER_CTX_get_nid,
EVP_CIPHER_CTX_get_params,
EVP_CIPHER_gettable_ctx_params,
EVP_CIPHER_CTX_gettable_params,
EVP_CIPHER_CTX_set_params,
EVP_CIPHER_settable_ctx_params,
EVP_CIPHER_CTX_settable_params,
EVP_CIPHER_CTX_get_block_size,
EVP_CIPHER_CTX_get_key_length,
EVP_CIPHER_CTX_get_iv_length,
EVP_CIPHER_CTX_get_tag_length,
EVP_CIPHER_CTX_get_app_data,
EVP_CIPHER_CTX_set_app_data,
EVP_CIPHER_CTX_flags,
EVP_CIPHER_CTX_set_flags,
EVP_CIPHER_CTX_clear_flags,
EVP_CIPHER_CTX_test_flags,
EVP_CIPHER_CTX_get_type,
EVP_CIPHER_CTX_get_mode,
EVP_CIPHER_CTX_get_num,
EVP_CIPHER_CTX_set_num,
EVP_CIPHER_CTX_is_encrypting,
EVP_CIPHER_param_to_asn1,
EVP_CIPHER_asn1_to_param,
EVP_CIPHER_CTX_set_padding,
EVP_enc_null,
EVP_CIPHER_do_all_provided,
EVP_CIPHER_nid,
EVP_CIPHER_name,
EVP_CIPHER_block_size,
EVP_CIPHER_key_length,
EVP_CIPHER_iv_length,
EVP_CIPHER_flags,
EVP_CIPHER_mode,
EVP_CIPHER_type,
EVP_CIPHER_CTX_encrypting,
EVP_CIPHER_CTX_nid,
EVP_CIPHER_CTX_block_size,
EVP_CIPHER_CTX_key_length,
EVP_CIPHER_CTX_iv_length,
EVP_CIPHER_CTX_tag_length,
EVP_CIPHER_CTX_num,
EVP_CIPHER_CTX_type,
EVP_CIPHER_CTX_mode
- EVP cipher routines
=head1 SYNOPSIS
=for openssl generic
#include <openssl/evp.h>
EVP_CIPHER *EVP_CIPHER_fetch(OSSL_LIB_CTX *ctx, const char *algorithm,
const char *properties);
int EVP_CIPHER_up_ref(EVP_CIPHER *cipher);
void EVP_CIPHER_free(EVP_CIPHER *cipher);
EVP_CIPHER_CTX *EVP_CIPHER_CTX_new(void);
int EVP_CIPHER_CTX_reset(EVP_CIPHER_CTX *ctx);
void EVP_CIPHER_CTX_free(EVP_CIPHER_CTX *ctx);
int EVP_EncryptInit_ex(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *type,
ENGINE *impl, const unsigned char *key, const unsigned char *iv);
int EVP_EncryptInit_ex2(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *type,
const unsigned char *key, const unsigned char *iv,
const OSSL_PARAM params[]);
int EVP_EncryptUpdate(EVP_CIPHER_CTX *ctx, unsigned char *out,
int *outl, const unsigned char *in, int inl);
int EVP_EncryptFinal_ex(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl);
int EVP_DecryptInit_ex(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *type,
ENGINE *impl, const unsigned char *key, const unsigned char *iv);
int EVP_DecryptInit_ex2(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *type,
const unsigned char *key, const unsigned char *iv,
const OSSL_PARAM params[]);
int EVP_DecryptUpdate(EVP_CIPHER_CTX *ctx, unsigned char *out,
int *outl, const unsigned char *in, int inl);
int EVP_DecryptFinal_ex(EVP_CIPHER_CTX *ctx, unsigned char *outm, int *outl);
int EVP_CipherInit_ex(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *type,
ENGINE *impl, const unsigned char *key, const unsigned char *iv, int enc);
int EVP_CipherInit_ex2(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *type,
const unsigned char *key, const unsigned char *iv,
int enc, const OSSL_PARAM params[]);
int EVP_CipherUpdate(EVP_CIPHER_CTX *ctx, unsigned char *out,
int *outl, const unsigned char *in, int inl);
int EVP_CipherFinal_ex(EVP_CIPHER_CTX *ctx, unsigned char *outm, int *outl);
int EVP_EncryptInit(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *type,
const unsigned char *key, const unsigned char *iv);
int EVP_EncryptFinal(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl);
int EVP_DecryptInit(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *type,
const unsigned char *key, const unsigned char *iv);
int EVP_DecryptFinal(EVP_CIPHER_CTX *ctx, unsigned char *outm, int *outl);
int EVP_CipherInit(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *type,
const unsigned char *key, const unsigned char *iv, int enc);
int EVP_CipherFinal(EVP_CIPHER_CTX *ctx, unsigned char *outm, int *outl);
int EVP_Cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
const unsigned char *in, unsigned int inl);
int EVP_CIPHER_CTX_set_padding(EVP_CIPHER_CTX *x, int padding);
int EVP_CIPHER_CTX_set_key_length(EVP_CIPHER_CTX *x, int keylen);
int EVP_CIPHER_CTX_ctrl(EVP_CIPHER_CTX *ctx, int cmd, int p1, void *p2);
int EVP_CIPHER_CTX_rand_key(EVP_CIPHER_CTX *ctx, unsigned char *key);
void EVP_CIPHER_CTX_set_flags(EVP_CIPHER_CTX *ctx, int flags);
void EVP_CIPHER_CTX_clear_flags(EVP_CIPHER_CTX *ctx, int flags);
int EVP_CIPHER_CTX_test_flags(const EVP_CIPHER_CTX *ctx, int flags);
const EVP_CIPHER *EVP_get_cipherbyname(const char *name);
const EVP_CIPHER *EVP_get_cipherbynid(int nid);
const EVP_CIPHER *EVP_get_cipherbyobj(const ASN1_OBJECT *a);
int EVP_CIPHER_get_nid(const EVP_CIPHER *e);
int EVP_CIPHER_is_a(const EVP_CIPHER *cipher, const char *name);
int EVP_CIPHER_names_do_all(const EVP_CIPHER *cipher,
void (*fn)(const char *name, void *data),
void *data);
const char *EVP_CIPHER_get0_name(const EVP_CIPHER *cipher);
const char *EVP_CIPHER_get0_description(const EVP_CIPHER *cipher);
const OSSL_PROVIDER *EVP_CIPHER_get0_provider(const EVP_CIPHER *cipher);
int EVP_CIPHER_get_block_size(const EVP_CIPHER *e);
int EVP_CIPHER_get_key_length(const EVP_CIPHER *e);
int EVP_CIPHER_get_iv_length(const EVP_CIPHER *e);
unsigned long EVP_CIPHER_get_flags(const EVP_CIPHER *e);
unsigned long EVP_CIPHER_get_mode(const EVP_CIPHER *e);
int EVP_CIPHER_get_type(const EVP_CIPHER *cipher);
const EVP_CIPHER *EVP_CIPHER_CTX_get0_cipher(const EVP_CIPHER_CTX *ctx);
EVP_CIPHER *EVP_CIPHER_CTX_get1_cipher(const EVP_CIPHER_CTX *ctx);
int EVP_CIPHER_CTX_get_nid(const EVP_CIPHER_CTX *ctx);
const char *EVP_CIPHER_CTX_get0_name(const EVP_CIPHER_CTX *ctx);
int EVP_CIPHER_get_params(EVP_CIPHER *cipher, OSSL_PARAM params[]);
int EVP_CIPHER_CTX_set_params(EVP_CIPHER_CTX *ctx, const OSSL_PARAM params[]);
int EVP_CIPHER_CTX_get_params(EVP_CIPHER_CTX *ctx, OSSL_PARAM params[]);
const OSSL_PARAM *EVP_CIPHER_gettable_params(const EVP_CIPHER *cipher);
const OSSL_PARAM *EVP_CIPHER_settable_ctx_params(const EVP_CIPHER *cipher);
const OSSL_PARAM *EVP_CIPHER_gettable_ctx_params(const EVP_CIPHER *cipher);
const OSSL_PARAM *EVP_CIPHER_CTX_settable_params(EVP_CIPHER_CTX *ctx);
const OSSL_PARAM *EVP_CIPHER_CTX_gettable_params(EVP_CIPHER_CTX *ctx);
int EVP_CIPHER_CTX_get_block_size(const EVP_CIPHER_CTX *ctx);
int EVP_CIPHER_CTX_get_key_length(const EVP_CIPHER_CTX *ctx);
int EVP_CIPHER_CTX_get_iv_length(const EVP_CIPHER_CTX *ctx);
int EVP_CIPHER_CTX_get_tag_length(const EVP_CIPHER_CTX *ctx);
void *EVP_CIPHER_CTX_get_app_data(const EVP_CIPHER_CTX *ctx);
void EVP_CIPHER_CTX_set_app_data(const EVP_CIPHER_CTX *ctx, void *data);
int EVP_CIPHER_CTX_get_type(const EVP_CIPHER_CTX *ctx);
int EVP_CIPHER_CTX_get_mode(const EVP_CIPHER_CTX *ctx);
int EVP_CIPHER_CTX_get_num(const EVP_CIPHER_CTX *ctx);
int EVP_CIPHER_CTX_set_num(EVP_CIPHER_CTX *ctx, int num);
int EVP_CIPHER_CTX_is_encrypting(const EVP_CIPHER_CTX *ctx);
int EVP_CIPHER_param_to_asn1(EVP_CIPHER_CTX *c, ASN1_TYPE *type);
int EVP_CIPHER_asn1_to_param(EVP_CIPHER_CTX *c, ASN1_TYPE *type);
void EVP_CIPHER_do_all_provided(OSSL_LIB_CTX *libctx,
void (*fn)(EVP_CIPHER *cipher, void *arg),
void *arg);
#define EVP_CIPHER_nid EVP_CIPHER_get_nid
#define EVP_CIPHER_name EVP_CIPHER_get0_name
#define EVP_CIPHER_block_size EVP_CIPHER_get_block_size
#define EVP_CIPHER_key_length EVP_CIPHER_get_key_length
#define EVP_CIPHER_iv_length EVP_CIPHER_get_iv_length
#define EVP_CIPHER_flags EVP_CIPHER_get_flags
#define EVP_CIPHER_mode EVP_CIPHER_get_mode
#define EVP_CIPHER_type EVP_CIPHER_get_type
#define EVP_CIPHER_CTX_encrypting EVP_CIPHER_CTX_is_encrypting
#define EVP_CIPHER_CTX_nid EVP_CIPHER_CTX_get_nid
#define EVP_CIPHER_CTX_block_size EVP_CIPHER_CTX_get_block_size
#define EVP_CIPHER_CTX_key_length EVP_CIPHER_CTX_get_key_length
#define EVP_CIPHER_CTX_iv_length EVP_CIPHER_CTX_get_iv_length
#define EVP_CIPHER_CTX_tag_length EVP_CIPHER_CTX_get_tag_length
#define EVP_CIPHER_CTX_num EVP_CIPHER_CTX_get_num
#define EVP_CIPHER_CTX_type EVP_CIPHER_CTX_get_type
#define EVP_CIPHER_CTX_mode EVP_CIPHER_CTX_get_mode
The following function has 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_CIPHER *EVP_CIPHER_CTX_cipher(const EVP_CIPHER_CTX *ctx);
The following function has been deprecated since OpenSSL 1.1.0, and can be
hidden entirely by defining B<OPENSSL_API_COMPAT> with a suitable version value,
see L<openssl_user_macros(7)>:
int EVP_CIPHER_CTX_flags(const EVP_CIPHER_CTX *ctx);
=head1 DESCRIPTION
The EVP cipher routines are a high-level interface to certain
symmetric ciphers.
The B<EVP_CIPHER> type is a structure for cipher method implementation.
=over 4
=item EVP_CIPHER_fetch()
Fetches the cipher 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_CIPHER_free().
Fetched B<EVP_CIPHER> structures are reference counted.
=item EVP_CIPHER_up_ref()
Increments the reference count for an B<EVP_CIPHER> structure.
=item EVP_CIPHER_free()
Decrements the reference count for the fetched B<EVP_CIPHER> structure.
If the reference count drops to 0 then the structure is freed.
+If the argument is NULL, nothing is done.
=item EVP_CIPHER_CTX_new()
Allocates and returns a cipher context.
=item EVP_CIPHER_CTX_free()
Clears all information from a cipher context and frees any allocated memory
-associated with it, including I<ctx> itself. This function should be called after
-all operations using a cipher are complete so sensitive information does not
-remain in memory.
+associated with it, including I<ctx> itself. This function should be called
+after all operations using a cipher are complete so sensitive information does
+not remain in memory. If the argument is NULL, nothing is done.
=item EVP_CIPHER_CTX_ctrl()
I<This is a legacy method.> EVP_CIPHER_CTX_set_params() and
EVP_CIPHER_CTX_get_params() is the mechanism that should be used to set and get
parameters that are used by providers.
Performs cipher-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_CIPHER_CTX_ctrl() must be called after EVP_CipherInit_ex2(). Other restrictions
may apply depending on the control type and cipher implementation.
If this function happens to be used with a fetched B<EVP_CIPHER>, it will
translate the controls that are known to OpenSSL into L<OSSL_PARAM(3)>
parameters with keys defined by OpenSSL and call EVP_CIPHER_CTX_get_params() or
EVP_CIPHER_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_CIPHER_get_params()
Retrieves the requested list of algorithm I<params> from a CIPHER I<cipher>.
See L</PARAMETERS> below for more information.
=item EVP_CIPHER_CTX_get_params()
Retrieves the requested list of I<params> from CIPHER context I<ctx>.
See L</PARAMETERS> below for more information.
=item EVP_CIPHER_CTX_set_params()
Sets the list of I<params> into a CIPHER context I<ctx>.
See L</PARAMETERS> below for more information.
=item EVP_CIPHER_gettable_params()
Get a constant L<OSSL_PARAM(3)> array that describes the retrievable parameters
that can be used with EVP_CIPHER_get_params().
=item EVP_CIPHER_gettable_ctx_params() and EVP_CIPHER_CTX_gettable_params()
Get a constant L<OSSL_PARAM(3)> array that describes the retrievable parameters
that can be used with EVP_CIPHER_CTX_get_params().
EVP_CIPHER_gettable_ctx_params() returns the parameters that can be retrieved
from the algorithm, whereas EVP_CIPHER_CTX_gettable_params() returns the
parameters that can be retrieved in the context's current state.
=item EVP_CIPHER_settable_ctx_params() and EVP_CIPHER_CTX_settable_params()
Get a constant L<OSSL_PARAM(3)> array that describes the settable parameters
that can be used with EVP_CIPHER_CTX_set_params().
EVP_CIPHER_settable_ctx_params() returns the parameters that can be set from the
algorithm, whereas EVP_CIPHER_CTX_settable_params() returns the parameters that
can be set in the context's current state.
=item EVP_EncryptInit_ex2()
Sets up cipher context I<ctx> for encryption with cipher I<type>. I<type> is
typically supplied by calling EVP_CIPHER_fetch(). I<type> may also be set
using legacy functions such as EVP_aes_256_cbc(), but this is not recommended
for new applications. I<key> is the symmetric key to use and I<iv> is the IV to
use (if necessary), the actual number of bytes used for the key and IV depends
on the cipher. The parameters I<params> will be set on the context after
initialisation. It is possible to set all parameters to NULL except I<type> in
an initial call and supply the remaining parameters in subsequent calls, all of
which have I<type> set to NULL. This is done when the default cipher parameters
are not appropriate.
For B<EVP_CIPH_GCM_MODE> the IV will be generated internally if it is not
specified.
=item EVP_EncryptInit_ex()
This legacy function is similar to EVP_EncryptInit_ex2() when I<impl> is NULL.
The implementation of the I<type> from the I<impl> engine will be used if it
exists.
=item EVP_EncryptUpdate()
Encrypts I<inl> bytes from the buffer I<in> and writes the encrypted version to
I<out>. The pointers I<out> and I<in> may point to the same location, in which
-case the encryption will be done in-place. If I<out> and I<in> point to different
-locations, the two buffers must be disjoint, otherwise the operation might fail
-or the outcome might be undefined.
+case the encryption will be done in-place. However, in-place encryption is
+guaranteed to work only if the encryption context (I<ctx>) has processed data in
+multiples of the block size. If the context contains an incomplete data block
+from previous operations, in-place encryption will fail.
+
+If I<out> and I<in> point to different locations, the two buffers must be
+disjoint, otherwise the operation might fail or the outcome might be undefined.
This function can be called multiple times to encrypt successive blocks
of data. The amount of data written depends on the block alignment of the
encrypted data.
For most ciphers and modes, the amount of data written can be anything
from zero bytes to (inl + cipher_block_size - 1) bytes.
For wrap cipher modes, the amount of data written can be anything
from zero bytes to (inl + cipher_block_size) bytes.
For stream ciphers, the amount of data written can be anything from zero
bytes to inl bytes.
Thus, the buffer pointed to by I<out> must contain sufficient room for the
operation being performed.
The actual number of bytes written is placed in I<outl>.
If padding is enabled (the default) then EVP_EncryptFinal_ex() encrypts
the "final" data, that is any data that remains in a partial block.
It uses standard block padding (aka PKCS padding) as described in
the NOTES section, below. The encrypted
final data is written to I<out> which should have sufficient space for
one cipher block. The number of bytes written is placed in I<outl>. After
this function is called the encryption operation is finished and no further
calls to EVP_EncryptUpdate() should be made.
If padding is disabled then EVP_EncryptFinal_ex() will not encrypt any more
data and it will return an error if any data remains in a partial block:
that is if the total data length is not a multiple of the block size.
=item EVP_DecryptInit_ex2(), EVP_DecryptInit_ex(), EVP_DecryptUpdate()
and EVP_DecryptFinal_ex()
These functions are the corresponding decryption operations.
EVP_DecryptFinal() will return an error code if padding is enabled and the
final block is not correctly formatted. The parameters and restrictions are
identical to the encryption operations except that if padding is enabled the
decrypted data buffer I<out> passed to EVP_DecryptUpdate() should have
sufficient room for (I<inl> + cipher_block_size) bytes unless the cipher block
size is 1 in which case I<inl> bytes is sufficient.
=item EVP_CipherInit_ex2(), EVP_CipherInit_ex(), EVP_CipherUpdate() and
EVP_CipherFinal_ex()
These functions can be used for decryption or encryption. The operation
performed depends on the value of the I<enc> parameter. It should be set to 1
for encryption, 0 for decryption and -1 to leave the value unchanged
(the actual value of 'enc' being supplied in a previous call).
=item EVP_CIPHER_CTX_reset()
Clears all information from a cipher context and free up any allocated memory
associated with it, except the I<ctx> itself. This function should be called
anytime I<ctx> is reused by another
EVP_CipherInit() / EVP_CipherUpdate() / EVP_CipherFinal() series of calls.
=item EVP_EncryptInit(), EVP_DecryptInit() and EVP_CipherInit()
Behave in a similar way to EVP_EncryptInit_ex(), EVP_DecryptInit_ex() and
EVP_CipherInit_ex() except if the I<type> is not a fetched cipher they use the
default implementation of the I<type>.
=item EVP_EncryptFinal(), EVP_DecryptFinal() and EVP_CipherFinal()
Identical to EVP_EncryptFinal_ex(), EVP_DecryptFinal_ex() and
EVP_CipherFinal_ex(). In previous releases they also cleaned up
the I<ctx>, but this is no longer done and EVP_CIPHER_CTX_cleanup()
must be called to free any context resources.
=item EVP_Cipher()
Encrypts or decrypts a maximum I<inl> amount of bytes from I<in> and leaves the
result in I<out>.
For legacy ciphers - If the cipher doesn't have the flag
B<EVP_CIPH_FLAG_CUSTOM_CIPHER> set, then I<inl> must be a multiple of
EVP_CIPHER_get_block_size(). If it isn't, the result is undefined. If the cipher
has that flag set, then I<inl> can be any size.
Due to the constraints of the API contract of this function it shouldn't be used
in applications, please consider using EVP_CipherUpdate() and
EVP_CipherFinal_ex() instead.
=item EVP_get_cipherbyname(), EVP_get_cipherbynid() and EVP_get_cipherbyobj()
Returns an B<EVP_CIPHER> structure when passed a cipher name, a cipher B<NID> or
an B<ASN1_OBJECT> structure respectively.
EVP_get_cipherbyname() 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.
The EVP_get_cipherbyname() function is present for backwards compatibility with
OpenSSL prior to version 3 and is different to the EVP_CIPHER_fetch() function
since it does not attempt to "fetch" an implementation of the cipher.
Additionally, it only knows about ciphers that are built-in to OpenSSL and have
an associated NID. Similarly EVP_get_cipherbynid() and EVP_get_cipherbyobj()
also return objects without an associated implementation.
When the cipher objects returned by these functions are used (such as in a call
to EVP_EncryptInit_ex()) an implementation of the cipher will be implicitly
fetched from the loaded providers. This fetch could fail if no suitable
implementation is available. Use EVP_CIPHER_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 cipher objects returned from these functions do not need to be freed with
EVP_CIPHER_free().
=item EVP_CIPHER_get_nid() and EVP_CIPHER_CTX_get_nid()
Return the NID of a cipher when passed an B<EVP_CIPHER> or B<EVP_CIPHER_CTX>
structure. The actual NID value is an internal value which may not have a
corresponding OBJECT IDENTIFIER.
=item EVP_CIPHER_CTX_set_flags(), EVP_CIPHER_CTX_clear_flags() and EVP_CIPHER_CTX_test_flags()
Sets, clears and tests I<ctx> flags. See L</FLAGS> below for more information.
For provided ciphers EVP_CIPHER_CTX_set_flags() should be called only after the
fetched cipher has been assigned to the I<ctx>. It is recommended to use
L</PARAMETERS> instead.
=item EVP_CIPHER_CTX_set_padding()
Enables or disables padding. This function should be called after the context
is set up for encryption or decryption with EVP_EncryptInit_ex2(),
EVP_DecryptInit_ex2() or EVP_CipherInit_ex2(). By default encryption operations
are padded using standard block padding and the padding is checked and removed
when decrypting. If the I<pad> parameter is zero then no padding is
performed, the total amount of data encrypted or decrypted must then
be a multiple of the block size or an error will occur.
=item EVP_CIPHER_get_key_length() and EVP_CIPHER_CTX_get_key_length()
Return the key length of a cipher when passed an B<EVP_CIPHER> or
B<EVP_CIPHER_CTX> structure. The constant B<EVP_MAX_KEY_LENGTH> is the maximum
key length for all ciphers. Note: although EVP_CIPHER_get_key_length() is fixed for
a given cipher, the value of EVP_CIPHER_CTX_get_key_length() may be different for
variable key length ciphers.
=item EVP_CIPHER_CTX_set_key_length()
Sets the key length of the cipher context.
If the cipher is a fixed length cipher then attempting to set the key
length to any value other than the fixed value is an error.
=item EVP_CIPHER_get_iv_length() and EVP_CIPHER_CTX_get_iv_length()
Return the IV length of a cipher when passed an B<EVP_CIPHER> or
B<EVP_CIPHER_CTX>. It will return zero if the cipher does not use an IV.
The constant B<EVP_MAX_IV_LENGTH> is the maximum IV length for all ciphers.
=item EVP_CIPHER_CTX_get_tag_length()
Returns the tag length of an AEAD cipher when passed a B<EVP_CIPHER_CTX>. It will
return zero if the cipher does not support a tag. It returns a default value if
the tag length has not been set.
=item EVP_CIPHER_get_block_size() and EVP_CIPHER_CTX_get_block_size()
Return the block size of a cipher when passed an B<EVP_CIPHER> or
B<EVP_CIPHER_CTX> structure. The constant B<EVP_MAX_BLOCK_LENGTH> is also the
maximum block length for all ciphers.
=item EVP_CIPHER_get_type() and EVP_CIPHER_CTX_get_type()
Return the type of the passed cipher or context. This "type" is the actual NID
of the cipher OBJECT IDENTIFIER and as such it ignores the cipher parameters
(40 bit RC2 and 128 bit RC2 have the same NID). If the cipher does not have an
object identifier or does not have ASN1 support this function will return
B<NID_undef>.
=item EVP_CIPHER_is_a()
Returns 1 if I<cipher> is an implementation of an algorithm that's identifiable
with I<name>, otherwise 0. If I<cipher> is a legacy cipher (it's the return
value from the likes of EVP_aes128() rather than the result of an
EVP_CIPHER_fetch()), only cipher names registered with the default library
context (see L<OSSL_LIB_CTX(3)>) will be considered.
=item EVP_CIPHER_get0_name() and EVP_CIPHER_CTX_get0_name()
Return the name of the passed cipher or context. For fetched ciphers with
multiple names, only one of them is returned. See also EVP_CIPHER_names_do_all().
=item EVP_CIPHER_names_do_all()
Traverses all names for the I<cipher>, and calls I<fn> with each name and
I<data>. This is only useful with fetched B<EVP_CIPHER>s.
=item EVP_CIPHER_get0_description()
Returns a description of the cipher, meant for display and human consumption.
The description is at the discretion of the cipher implementation.
=item EVP_CIPHER_get0_provider()
Returns an B<OSSL_PROVIDER> pointer to the provider that implements the given
B<EVP_CIPHER>.
=item EVP_CIPHER_CTX_get0_cipher()
Returns the B<EVP_CIPHER> structure when passed an B<EVP_CIPHER_CTX> structure.
EVP_CIPHER_CTX_get1_cipher() is the same except the ownership is passed to
the caller.
=item EVP_CIPHER_get_mode() and EVP_CIPHER_CTX_get_mode()
Return the block cipher mode:
EVP_CIPH_ECB_MODE, EVP_CIPH_CBC_MODE, EVP_CIPH_CFB_MODE, EVP_CIPH_OFB_MODE,
EVP_CIPH_CTR_MODE, EVP_CIPH_GCM_MODE, EVP_CIPH_CCM_MODE, EVP_CIPH_XTS_MODE,
EVP_CIPH_WRAP_MODE, EVP_CIPH_OCB_MODE or EVP_CIPH_SIV_MODE.
If the cipher is a stream cipher then EVP_CIPH_STREAM_CIPHER is returned.
=item EVP_CIPHER_get_flags()
Returns any flags associated with the cipher. See L</FLAGS>
for a list of currently defined flags.
=item EVP_CIPHER_CTX_get_num() and EVP_CIPHER_CTX_set_num()
Gets or sets the cipher specific "num" parameter for the associated I<ctx>.
Built-in ciphers typically use this to track how much of the current underlying block
has been "used" already.
=item EVP_CIPHER_CTX_is_encrypting()
Reports whether the I<ctx> is being used for encryption or decryption.
=item EVP_CIPHER_CTX_flags()
A deprecated macro calling C<EVP_CIPHER_get_flags(EVP_CIPHER_CTX_get0_cipher(ctx))>.
Do not use.
=item EVP_CIPHER_param_to_asn1()
Sets the AlgorithmIdentifier "parameter" based on the passed cipher. This will
typically include any parameters and an IV. The cipher IV (if any) must be set
when this call is made. This call should be made before the cipher is actually
"used" (before any EVP_EncryptUpdate(), EVP_DecryptUpdate() calls for example).
This function may fail if the cipher does not have any ASN1 support.
=item EVP_CIPHER_asn1_to_param()
Sets the cipher parameters based on an ASN1 AlgorithmIdentifier "parameter".
The precise effect depends on the cipher. In the case of B<RC2>, for example,
it will set the IV and effective key length.
This function should be called after the base cipher type is set but before
the key is set. For example EVP_CipherInit() will be called with the IV and
key set to NULL, EVP_CIPHER_asn1_to_param() will be called and finally
EVP_CipherInit() again with all parameters except the key set to NULL. It is
possible for this function to fail if the cipher does not have any ASN1 support
or the parameters cannot be set (for example the RC2 effective key length
is not supported.
=item EVP_CIPHER_CTX_rand_key()
Generates a random key of the appropriate length based on the cipher context.
The B<EVP_CIPHER> can provide its own random key generation routine to support
keys of a specific form. I<key> must point to a buffer at least as big as the
value returned by EVP_CIPHER_CTX_get_key_length().
=item EVP_CIPHER_do_all_provided()
Traverses all ciphers 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.
=head2 Gettable EVP_CIPHER parameters
When EVP_CIPHER_fetch() is called it internally calls EVP_CIPHER_get_params()
and caches the results.
EVP_CIPHER_get_params() can be used with the following L<OSSL_PARAM(3)> keys:
=over 4
=item "mode" (B<OSSL_CIPHER_PARAM_MODE>) <unsigned integer>
Gets the mode for the associated cipher algorithm I<cipher>.
See L</EVP_CIPHER_get_mode() and EVP_CIPHER_CTX_get_mode()> for a list of valid modes.
Use EVP_CIPHER_get_mode() to retrieve the cached value.
=item "keylen" (B<OSSL_CIPHER_PARAM_KEYLEN>) <unsigned integer>
Gets the key length for the associated cipher algorithm I<cipher>.
Use EVP_CIPHER_get_key_length() to retrieve the cached value.
=item "ivlen" (B<OSSL_CIPHER_PARAM_IVLEN>) <unsigned integer>
Gets the IV length for the associated cipher algorithm I<cipher>.
Use EVP_CIPHER_get_iv_length() to retrieve the cached value.
=item "blocksize" (B<OSSL_CIPHER_PARAM_BLOCK_SIZE>) <unsigned integer>
Gets the block size for the associated cipher algorithm I<cipher>.
The block size should be 1 for stream ciphers.
Note that the block size for a cipher may be different to the block size for
the underlying encryption/decryption primitive.
For example AES in CTR mode has a block size of 1 (because it operates like a
stream cipher), even though AES has a block size of 16.
Use EVP_CIPHER_get_block_size() to retrieve the cached value.
=item "aead" (B<OSSL_CIPHER_PARAM_AEAD>) <integer>
Gets 1 if this is an AEAD cipher algorithm, otherwise it gets 0.
Use (EVP_CIPHER_get_flags(cipher) & EVP_CIPH_FLAG_AEAD_CIPHER) to retrieve the
cached value.
=item "custom-iv" (B<OSSL_CIPHER_PARAM_CUSTOM_IV>) <integer>
Gets 1 if the cipher algorithm I<cipher> has a custom IV, otherwise it gets 0.
Storing and initializing the IV is left entirely to the implementation, if a
custom IV is used.
Use (EVP_CIPHER_get_flags(cipher) & EVP_CIPH_CUSTOM_IV) to retrieve the
cached value.
=item "cts" (B<OSSL_CIPHER_PARAM_CTS>) <integer>
Gets 1 if the cipher algorithm I<cipher> uses ciphertext stealing,
otherwise it gets 0.
This is currently used to indicate that the cipher is a one shot that only
allows a single call to EVP_CipherUpdate().
Use (EVP_CIPHER_get_flags(cipher) & EVP_CIPH_FLAG_CTS) to retrieve the
cached value.
=item "tls-multi" (B<OSSL_CIPHER_PARAM_TLS1_MULTIBLOCK>) <integer>
Gets 1 if the cipher algorithm I<cipher> supports interleaving of crypto blocks,
otherwise it gets 0. The interleaving is an optimization only applicable to certain
TLS ciphers.
Use (EVP_CIPHER_get_flags(cipher) & EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK) to retrieve the
cached value.
=item "has-randkey" (B<OSSL_CIPHER_PARAM_HAS_RANDKEY>) <integer>
Gets 1 if the cipher algorithm I<cipher> supports the gettable EVP_CIPHER_CTX
parameter B<OSSL_CIPHER_PARAM_RANDOM_KEY>. Only DES and 3DES set this to 1,
all other OpenSSL ciphers return 0.
=back
=head2 Gettable and Settable EVP_CIPHER_CTX parameters
The following L<OSSL_PARAM(3)> keys can be used with both EVP_CIPHER_CTX_get_params()
and EVP_CIPHER_CTX_set_params().
=over 4
=item "padding" (B<OSSL_CIPHER_PARAM_PADDING>) <unsigned integer>
Gets or sets the padding mode for the cipher context I<ctx>.
Padding is enabled if the value is 1, and disabled if the value is 0.
See also EVP_CIPHER_CTX_set_padding().
=item "num" (B<OSSL_CIPHER_PARAM_NUM>) <unsigned integer>
Gets or sets the cipher specific "num" parameter for the cipher context I<ctx>.
Built-in ciphers typically use this to track how much of the current underlying
block has been "used" already.
See also EVP_CIPHER_CTX_get_num() and EVP_CIPHER_CTX_set_num().
=item "keylen" (B<OSSL_CIPHER_PARAM_KEYLEN>) <unsigned integer>
Gets or sets the key length for the cipher context I<ctx>.
The length of the "keylen" parameter should not exceed that of a B<size_t>.
See also EVP_CIPHER_CTX_get_key_length() and EVP_CIPHER_CTX_set_key_length().
=item "tag" (B<OSSL_CIPHER_PARAM_AEAD_TAG>) <octet string>
Gets or sets the AEAD tag for the associated cipher context I<ctx>.
See L<EVP_EncryptInit(3)/AEAD Interface>.
=item "keybits" (B<OSSL_CIPHER_PARAM_RC2_KEYBITS>) <unsigned integer>
Gets or sets the effective keybits used for a RC2 cipher.
The length of the "keybits" parameter should not exceed that of a B<size_t>.
=item "rounds" (B<OSSL_CIPHER_PARAM_ROUNDS>) <unsigned integer>
Gets or sets the number of rounds to be used for a cipher.
This is used by the RC5 cipher.
=item "alg_id_param" (B<OSSL_CIPHER_PARAM_ALGORITHM_ID_PARAMS>) <octet string>
Used to pass the DER encoded AlgorithmIdentifier parameter to or from
the cipher implementation. Functions like L<EVP_CIPHER_param_to_asn1(3)>
and L<EVP_CIPHER_asn1_to_param(3)> use this parameter for any implementation
that has the flag B<EVP_CIPH_FLAG_CUSTOM_ASN1> set.
=item "cts_mode" (B<OSSL_CIPHER_PARAM_CTS_MODE>) <UTF8 string>
Gets or sets the cipher text stealing mode. For all modes the output size is the
same as the input size. The input length must be greater than or equal to the
block size. (The block size for AES and CAMELLIA is 16 bytes).
Valid values for the mode are:
=over 4
=item "CS1"
The NIST variant of cipher text stealing.
For input lengths that are multiples of the block size it is equivalent to
using a "AES-XXX-CBC" or "CAMELLIA-XXX-CBC" cipher otherwise the second last
cipher text block is a partial block.
=item "CS2"
For input lengths that are multiples of the block size it is equivalent to
using a "AES-XXX-CBC" or "CAMELLIA-XXX-CBC" cipher, otherwise it is the same as
"CS3" mode.
=item "CS3"
The Kerberos5 variant of cipher text stealing which always swaps the last
cipher text block with the previous block (which may be a partial or full block
depending on the input length). If the input length is exactly one full block
then this is equivalent to using a "AES-XXX-CBC" or "CAMELLIA-XXX-CBC" cipher.
=back
The default is "CS1".
This is only supported for "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".
=item "tls1multi_interleave" (B<OSSL_CIPHER_PARAM_TLS1_MULTIBLOCK_INTERLEAVE>) <unsigned integer>
Sets or gets the number of records being sent in one go for a tls1 multiblock
cipher operation (either 4 or 8 records).
=back
=head2 Gettable EVP_CIPHER_CTX parameters
The following L<OSSL_PARAM(3)> keys can be used with EVP_CIPHER_CTX_get_params():
=over 4
=item "ivlen" (B<OSSL_CIPHER_PARAM_IVLEN> and <B<OSSL_CIPHER_PARAM_AEAD_IVLEN>) <unsigned integer>
Gets the IV length for the cipher context I<ctx>.
The length of the "ivlen" parameter should not exceed that of a B<size_t>.
See also EVP_CIPHER_CTX_get_iv_length().
=item "iv" (B<OSSL_CIPHER_PARAM_IV>) <octet string OR octet ptr>
Gets the IV used to initialize the associated cipher context I<ctx>.
See also EVP_CIPHER_CTX_get_original_iv().
=item "updated-iv" (B<OSSL_CIPHER_PARAM_UPDATED_IV>) <octet string OR octet ptr>
Gets the updated pseudo-IV state for the associated cipher context, e.g.,
the previous ciphertext block for CBC mode or the iteratively encrypted IV
value for OFB mode. Note that octet pointer access is deprecated and is
provided only for backwards compatibility with historical libcrypto APIs.
See also EVP_CIPHER_CTX_get_updated_iv().
=item "randkey" (B<OSSL_CIPHER_PARAM_RANDOM_KEY>) <octet string>
Gets an implementation specific randomly generated key for the associated
cipher context I<ctx>. This is currently only supported by DES and 3DES (which set
the key to odd parity).
=item "taglen" (B<OSSL_CIPHER_PARAM_AEAD_TAGLEN>) <unsigned integer>
Gets the tag length to be used for an AEAD cipher for the associated cipher
context I<ctx>. It gets a default value if it has not been set.
The length of the "taglen" parameter should not exceed that of a B<size_t>.
See also EVP_CIPHER_CTX_get_tag_length().
=item "tlsaadpad" (B<OSSL_CIPHER_PARAM_AEAD_TLS1_AAD_PAD>) <unsigned integer>
Gets the length of the tag that will be added to a TLS record for the AEAD
tag for the associated cipher context I<ctx>.
The length of the "tlsaadpad" parameter should not exceed that of a B<size_t>.
=item "tlsivgen" (B<OSSL_CIPHER_PARAM_AEAD_TLS1_GET_IV_GEN>) <octet string>
Gets the invocation field generated for encryption.
Can only be called after "tlsivfixed" is set.
This is only used for GCM mode.
=item "tls1multi_enclen" (B<OSSL_CIPHER_PARAM_TLS1_MULTIBLOCK_ENC_LEN>) <unsigned integer>
Get the total length of the record returned from the "tls1multi_enc" operation.
=item "tls1multi_maxbufsz" (B<OSSL_CIPHER_PARAM_TLS1_MULTIBLOCK_MAX_BUFSIZE>) <unsigned integer>
Gets the maximum record length for a TLS1 multiblock cipher operation.
The length of the "tls1multi_maxbufsz" parameter should not exceed that of a B<size_t>.
=item "tls1multi_aadpacklen" (B<OSSL_CIPHER_PARAM_TLS1_MULTIBLOCK_AAD_PACKLEN>) <unsigned integer>
Gets the result of running the "tls1multi_aad" operation.
=item "tls-mac" (B<OSSL_CIPHER_PARAM_TLS_MAC>) <octet ptr>
Used to pass the TLS MAC data.
=back
=head2 Settable EVP_CIPHER_CTX parameters
The following L<OSSL_PARAM(3)> keys can be used with EVP_CIPHER_CTX_set_params():
=over 4
=item "mackey" (B<OSSL_CIPHER_PARAM_AEAD_MAC_KEY>) <octet string>
Sets the MAC key used by composite AEAD ciphers such as AES-CBC-HMAC-SHA256.
=item "speed" (B<OSSL_CIPHER_PARAM_SPEED>) <unsigned integer>
Sets the speed option for the associated cipher context. This is only supported
by AES SIV ciphers which disallow multiple operations by default.
Setting "speed" to 1 allows another encrypt or decrypt operation to be
performed. This is used for performance testing.
=item "use-bits" (B<OSSL_CIPHER_PARAM_USE_BITS>) <unsigned integer>
Determines if the input length I<inl> passed to EVP_EncryptUpdate(),
EVP_DecryptUpdate() and EVP_CipherUpdate() is the number of bits or number of bytes.
Setting "use-bits" to 1 uses bits. The default is in bytes.
This is only used for B<CFB1> ciphers.
This can be set using EVP_CIPHER_CTX_set_flags(ctx, EVP_CIPH_FLAG_LENGTH_BITS).
=item "tls-version" (B<OSSL_CIPHER_PARAM_TLS_VERSION>) <integer>
Sets the TLS version.
=item "tls-mac-size" (B<OSSL_CIPHER_PARAM_TLS_MAC_SIZE>) <unsigned integer>
Set the TLS MAC size.
=item "tlsaad" (B<OSSL_CIPHER_PARAM_AEAD_TLS1_AAD>) <octet string>
Sets TLSv1.2 AAD information for the associated cipher context I<ctx>.
TLSv1.2 AAD information is always 13 bytes in length and is as defined for the
"additional_data" field described in section 6.2.3.3 of RFC5246.
=item "tlsivfixed" (B<OSSL_CIPHER_PARAM_AEAD_TLS1_IV_FIXED>) <octet string>
Sets the fixed portion of an IV for an AEAD cipher used in a TLS record
encryption/ decryption for the associated cipher context.
TLS record encryption/decryption always occurs "in place" so that the input and
output buffers are always the same memory location.
AEAD IVs in TLSv1.2 consist of an implicit "fixed" part and an explicit part
that varies with every record.
Setting a TLS fixed IV changes a cipher to encrypt/decrypt TLS records.
TLS records are encrypted/decrypted using a single OSSL_FUNC_cipher_cipher call per
record.
For a record decryption the first bytes of the input buffer will be the explicit
part of the IV and the final bytes of the input buffer will be the AEAD tag.
The length of the explicit part of the IV and the tag length will depend on the
cipher in use and will be defined in the RFC for the relevant ciphersuite.
In order to allow for "in place" decryption the plaintext output should be
written to the same location in the output buffer that the ciphertext payload
was read from, i.e. immediately after the explicit IV.
When encrypting a record the first bytes of the input buffer should be empty to
allow space for the explicit IV, as will the final bytes where the tag will
be written.
The length of the input buffer will include the length of the explicit IV, the
payload, and the tag bytes.
The cipher implementation should generate the explicit IV and write it to the
beginning of the output buffer, do "in place" encryption of the payload and
write that to the output buffer, and finally add the tag onto the end of the
output buffer.
Whether encrypting or decrypting the value written to I<*outl> in the
OSSL_FUNC_cipher_cipher call should be the length of the payload excluding the explicit
IV length and the tag length.
=item "tlsivinv" (B<OSSL_CIPHER_PARAM_AEAD_TLS1_SET_IV_INV>) <octet string>
Sets the invocation field used for decryption.
Can only be called after "tlsivfixed" is set.
This is only used for GCM mode.
=item "tls1multi_enc" (B<OSSL_CIPHER_PARAM_TLS1_MULTIBLOCK_ENC>) <octet string>
Triggers a multiblock TLS1 encrypt operation for a TLS1 aware cipher that
supports sending 4 or 8 records in one go.
The cipher performs both the MAC and encrypt stages and constructs the record
headers itself.
"tls1multi_enc" supplies the output buffer for the encrypt operation,
"tls1multi_encin" & "tls1multi_interleave" must also be set in order to supply
values to the encrypt operation.
=item "tls1multi_encin" (B<OSSL_CIPHER_PARAM_TLS1_MULTIBLOCK_ENC_IN>) <octet string>
Supplies the data to encrypt for a TLS1 multiblock cipher operation.
=item "tls1multi_maxsndfrag" (B<OSSL_CIPHER_PARAM_TLS1_MULTIBLOCK_MAX_SEND_FRAGMENT>) <unsigned integer>
Sets the maximum send fragment size for a TLS1 multiblock cipher operation.
It must be set before using "tls1multi_maxbufsz".
The length of the "tls1multi_maxsndfrag" parameter should not exceed that of a B<size_t>.
=item "tls1multi_aad" (B<OSSL_CIPHER_PARAM_TLS1_MULTIBLOCK_AAD>) <octet string>
Sets the authenticated additional data used by a TLS1 multiblock cipher operation.
The supplied data consists of 13 bytes of record data containing:
Bytes 0-7: The sequence number of the first record
Byte 8: The record type
Byte 9-10: The protocol version
Byte 11-12: Input length (Always 0)
"tls1multi_interleave" must also be set for this operation.
=back
=head1 CONTROLS
The Mappings from EVP_CIPHER_CTX_ctrl() identifiers to PARAMETERS are listed
in the following section. See the L</PARAMETERS> section for more details.
EVP_CIPHER_CTX_ctrl() can be used to send the following standard controls:
=over 4
=item EVP_CTRL_AEAD_SET_IVLEN and EVP_CTRL_GET_IVLEN
When used with a fetched B<EVP_CIPHER>, EVP_CIPHER_CTX_set_params() and
EVP_CIPHER_CTX_get_params() get called with an L<OSSL_PARAM(3)> item with the
key "ivlen" (B<OSSL_CIPHER_PARAM_IVLEN>).
=item EVP_CTRL_AEAD_SET_IV_FIXED
When used with a fetched B<EVP_CIPHER>, EVP_CIPHER_CTX_set_params() gets called
with an L<OSSL_PARAM(3)> item with the key "tlsivfixed"
(B<OSSL_CIPHER_PARAM_AEAD_TLS1_IV_FIXED>).
=item EVP_CTRL_AEAD_SET_MAC_KEY
When used with a fetched B<EVP_CIPHER>, EVP_CIPHER_CTX_set_params() gets called
with an L<OSSL_PARAM(3)> item with the key "mackey"
(B<OSSL_CIPHER_PARAM_AEAD_MAC_KEY>).
=item EVP_CTRL_AEAD_SET_TAG and EVP_CTRL_AEAD_GET_TAG
When used with a fetched B<EVP_CIPHER>, EVP_CIPHER_CTX_set_params() and
EVP_CIPHER_CTX_get_params() get called with an L<OSSL_PARAM(3)> item with the
key "tag" (B<OSSL_CIPHER_PARAM_AEAD_TAG>).
=item EVP_CTRL_CCM_SET_L
When used with a fetched B<EVP_CIPHER>, EVP_CIPHER_CTX_set_params() gets called
with an L<OSSL_PARAM(3)> item with the key "ivlen" (B<OSSL_CIPHER_PARAM_IVLEN>)
with a value of (15 - L)
=item EVP_CTRL_COPY
There is no OSSL_PARAM mapping for this. Use EVP_CIPHER_CTX_copy() instead.
=item EVP_CTRL_GCM_SET_IV_INV
When used with a fetched B<EVP_CIPHER>, EVP_CIPHER_CTX_set_params() gets called
with an L<OSSL_PARAM(3)> item with the key "tlsivinv"
(B<OSSL_CIPHER_PARAM_AEAD_TLS1_SET_IV_INV>).
=item EVP_CTRL_RAND_KEY
When used with a fetched B<EVP_CIPHER>, EVP_CIPHER_CTX_set_params() gets called
with an L<OSSL_PARAM(3)> item with the key "randkey"
(B<OSSL_CIPHER_PARAM_RANDOM_KEY>).
=item EVP_CTRL_SET_KEY_LENGTH
When used with a fetched B<EVP_CIPHER>, EVP_CIPHER_CTX_set_params() gets called
with an L<OSSL_PARAM(3)> item with the key "keylen" (B<OSSL_CIPHER_PARAM_KEYLEN>).
=item EVP_CTRL_SET_RC2_KEY_BITS and EVP_CTRL_GET_RC2_KEY_BITS
When used with a fetched B<EVP_CIPHER>, EVP_CIPHER_CTX_set_params() and
EVP_CIPHER_CTX_get_params() get called with an L<OSSL_PARAM(3)> item with the
key "keybits" (B<OSSL_CIPHER_PARAM_RC2_KEYBITS>).
=item EVP_CTRL_SET_RC5_ROUNDS and EVP_CTRL_GET_RC5_ROUNDS
When used with a fetched B<EVP_CIPHER>, EVP_CIPHER_CTX_set_params() and
EVP_CIPHER_CTX_get_params() get called with an L<OSSL_PARAM(3)> item with the
key "rounds" (B<OSSL_CIPHER_PARAM_ROUNDS>).
=item EVP_CTRL_SET_SPEED
When used with a fetched B<EVP_CIPHER>, EVP_CIPHER_CTX_set_params() gets called
with an L<OSSL_PARAM(3)> item with the key "speed" (B<OSSL_CIPHER_PARAM_SPEED>).
=item EVP_CTRL_GCM_IV_GEN
When used with a fetched B<EVP_CIPHER>, EVP_CIPHER_CTX_get_params() gets called
with an L<OSSL_PARAM(3)> item with the key
"tlsivgen" (B<OSSL_CIPHER_PARAM_AEAD_TLS1_GET_IV_GEN>).
=item EVP_CTRL_AEAD_TLS1_AAD
When used with a fetched B<EVP_CIPHER>, EVP_CIPHER_CTX_set_params() get called
with an L<OSSL_PARAM(3)> item with the key
"tlsaad" (B<OSSL_CIPHER_PARAM_AEAD_TLS1_AAD>)
followed by EVP_CIPHER_CTX_get_params() with a key of
"tlsaadpad" (B<OSSL_CIPHER_PARAM_AEAD_TLS1_AAD_PAD>).
=item EVP_CTRL_TLS1_1_MULTIBLOCK_MAX_BUFSIZE
When used with a fetched B<EVP_CIPHER>,
EVP_CIPHER_CTX_set_params() gets called with an L<OSSL_PARAM(3)> item with the
key OSSL_CIPHER_PARAM_TLS1_MULTIBLOCK_MAX_SEND_FRAGMENT
followed by EVP_CIPHER_CTX_get_params() with a key of
"tls1multi_maxbufsz" (B<OSSL_CIPHER_PARAM_TLS1_MULTIBLOCK_MAX_BUFSIZE>).
=item EVP_CTRL_TLS1_1_MULTIBLOCK_AAD
When used with a fetched B<EVP_CIPHER>, EVP_CIPHER_CTX_set_params() gets called
with L<OSSL_PARAM(3)> items with the keys
"tls1multi_aad" (B<OSSL_CIPHER_PARAM_TLS1_MULTIBLOCK_AAD>) and
"tls1multi_interleave" (B<OSSL_CIPHER_PARAM_TLS1_MULTIBLOCK_INTERLEAVE>)
followed by EVP_CIPHER_CTX_get_params() with keys of
"tls1multi_aadpacklen" (B<OSSL_CIPHER_PARAM_TLS1_MULTIBLOCK_AAD_PACKLEN>) and
"tls1multi_interleave" (B<OSSL_CIPHER_PARAM_TLS1_MULTIBLOCK_INTERLEAVE>).
=item EVP_CTRL_TLS1_1_MULTIBLOCK_ENCRYPT
When used with a fetched B<EVP_CIPHER>, EVP_CIPHER_CTX_set_params() gets called
with L<OSSL_PARAM(3)> items with the keys
"tls1multi_enc" (B<OSSL_CIPHER_PARAM_TLS1_MULTIBLOCK_ENC>),
"tls1multi_encin" (B<OSSL_CIPHER_PARAM_TLS1_MULTIBLOCK_ENC_IN>) and
"tls1multi_interleave" (B<OSSL_CIPHER_PARAM_TLS1_MULTIBLOCK_INTERLEAVE>),
followed by EVP_CIPHER_CTX_get_params() with a key of
"tls1multi_enclen" (B<OSSL_CIPHER_PARAM_TLS1_MULTIBLOCK_ENC_LEN>).
=back
=head1 FLAGS
EVP_CIPHER_CTX_set_flags(), EVP_CIPHER_CTX_clear_flags() and EVP_CIPHER_CTX_test_flags().
can be used to manipulate and test these B<EVP_CIPHER_CTX> flags:
=over 4
=item EVP_CIPH_NO_PADDING
Used by EVP_CIPHER_CTX_set_padding().
See also L</Gettable and Settable EVP_CIPHER_CTX parameters> "padding"
=item EVP_CIPH_FLAG_LENGTH_BITS
See L</Settable EVP_CIPHER_CTX parameters> "use-bits".
=item EVP_CIPHER_CTX_FLAG_WRAP_ALLOW
Used for Legacy purposes only. This flag needed to be set to indicate the
cipher handled wrapping.
=back
EVP_CIPHER_flags() uses the following flags that
have mappings to L</Gettable EVP_CIPHER parameters>:
=over 4
=item EVP_CIPH_FLAG_AEAD_CIPHER
See L</Gettable EVP_CIPHER parameters> "aead".
=item EVP_CIPH_CUSTOM_IV
See L</Gettable EVP_CIPHER parameters> "custom-iv".
=item EVP_CIPH_FLAG_CTS
See L</Gettable EVP_CIPHER parameters> "cts".
=item EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK;
See L</Gettable EVP_CIPHER parameters> "tls-multi".
=item EVP_CIPH_RAND_KEY
See L</Gettable EVP_CIPHER parameters> "has-randkey".
=back
EVP_CIPHER_flags() uses the following flags for legacy purposes only:
=over 4
=item EVP_CIPH_VARIABLE_LENGTH
=item EVP_CIPH_FLAG_CUSTOM_CIPHER
=item EVP_CIPH_ALWAYS_CALL_INIT
=item EVP_CIPH_CTRL_INIT
=item EVP_CIPH_CUSTOM_KEY_LENGTH
=item EVP_CIPH_CUSTOM_COPY
=item EVP_CIPH_FLAG_DEFAULT_ASN1
See L<EVP_CIPHER_meth_set_flags(3)> for further information related to the above
flags.
=back
=head1 RETURN VALUES
EVP_CIPHER_fetch() returns a pointer to a B<EVP_CIPHER> for success
and B<NULL> for failure.
EVP_CIPHER_up_ref() returns 1 for success or 0 otherwise.
EVP_CIPHER_CTX_new() returns a pointer to a newly created
B<EVP_CIPHER_CTX> for success and B<NULL> for failure.
EVP_EncryptInit_ex2(), EVP_EncryptUpdate() and EVP_EncryptFinal_ex()
return 1 for success and 0 for failure.
EVP_DecryptInit_ex2() and EVP_DecryptUpdate() return 1 for success and 0 for failure.
EVP_DecryptFinal_ex() returns 0 if the decrypt failed or 1 for success.
EVP_CipherInit_ex2() and EVP_CipherUpdate() return 1 for success and 0 for failure.
EVP_CipherFinal_ex() returns 0 for a decryption failure or 1 for success.
EVP_Cipher() returns 1 on success or 0 on failure, if the flag
B<EVP_CIPH_FLAG_CUSTOM_CIPHER> is not set for the cipher.
EVP_Cipher() returns the number of bytes written to I<out> for encryption / decryption, or
the number of bytes authenticated in a call specifying AAD for an AEAD cipher, if the flag
B<EVP_CIPH_FLAG_CUSTOM_CIPHER> is set for the cipher.
EVP_CIPHER_CTX_reset() returns 1 for success and 0 for failure.
EVP_get_cipherbyname(), EVP_get_cipherbynid() and EVP_get_cipherbyobj()
return an B<EVP_CIPHER> structure or NULL on error.
EVP_CIPHER_get_nid() and EVP_CIPHER_CTX_get_nid() return a NID.
EVP_CIPHER_get_block_size() and EVP_CIPHER_CTX_get_block_size() return the
block size.
EVP_CIPHER_get_key_length() and EVP_CIPHER_CTX_get_key_length() return the key
length.
EVP_CIPHER_CTX_set_padding() always returns 1.
EVP_CIPHER_get_iv_length() and EVP_CIPHER_CTX_get_iv_length() return the IV
length or zero if the cipher does not use an IV.
EVP_CIPHER_CTX_get_tag_length() return the tag length or zero if the cipher
does not use a tag.
EVP_CIPHER_get_type() and EVP_CIPHER_CTX_get_type() return the NID of the
cipher's OBJECT IDENTIFIER or NID_undef if it has no defined
OBJECT IDENTIFIER.
EVP_CIPHER_CTX_cipher() returns an B<EVP_CIPHER> structure.
EVP_CIPHER_CTX_get_num() returns a nonnegative num value or
B<EVP_CTRL_RET_UNSUPPORTED> if the implementation does not support the call
or on any other error.
EVP_CIPHER_CTX_set_num() returns 1 on success and 0 if the implementation
does not support the call or on any other error.
EVP_CIPHER_CTX_is_encrypting() returns 1 if the I<ctx> is set up for encryption
0 otherwise.
EVP_CIPHER_param_to_asn1() and EVP_CIPHER_asn1_to_param() return greater
than zero for success and zero or a negative number on failure.
EVP_CIPHER_CTX_rand_key() returns 1 for success and zero or a negative number
for failure.
EVP_CIPHER_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.
=head1 CIPHER LISTING
All algorithms have a fixed key length unless otherwise stated.
Refer to L</SEE ALSO> for the full list of ciphers available through the EVP
interface.
=over 4
=item EVP_enc_null()
Null cipher: does nothing.
=back
=head1 AEAD INTERFACE
The EVP interface for Authenticated Encryption with Associated Data (AEAD)
modes are subtly altered and several additional I<ctrl> operations are supported
depending on the mode specified.
To specify additional authenticated data (AAD), a call to EVP_CipherUpdate(),
EVP_EncryptUpdate() or EVP_DecryptUpdate() should be made with the output
parameter I<out> set to B<NULL>. In this case, on success, the parameter
I<outl> is set to the number of bytes authenticated.
When decrypting, the return value of EVP_DecryptFinal() or EVP_CipherFinal()
indicates whether the operation was successful. If it does not indicate success,
the authentication operation has failed and any output data B<MUST NOT> be used
as it is corrupted.
=head2 GCM and OCB Modes
The following I<ctrl>s are supported in GCM and OCB modes.
=over 4
=item EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_IVLEN, ivlen, NULL)
Sets the IV length. This call can only be made before specifying an IV. If
not called a default IV length is used.
For GCM AES and OCB AES the default is 12 (i.e. 96 bits). For OCB mode the
maximum is 15.
=item EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_GET_TAG, taglen, tag)
Writes C<taglen> bytes of the tag value to the buffer indicated by C<tag>.
This call can only be made when encrypting data and B<after> all data has been
processed (e.g. after an EVP_EncryptFinal() call).
For OCB, C<taglen> must either be 16 or the value previously set via
B<EVP_CTRL_AEAD_SET_TAG>.
=item EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_TAG, taglen, tag)
When decrypting, this call sets the expected tag to C<taglen> bytes from C<tag>.
C<taglen> must be between 1 and 16 inclusive.
The tag must be set prior to any call to EVP_DecryptFinal() or
EVP_DecryptFinal_ex().
For GCM, this call is only valid when decrypting data.
For OCB, this call is valid when decrypting data to set the expected tag,
and when encrypting to set the desired tag length.
In OCB mode, calling this when encrypting with C<tag> set to C<NULL> sets the
tag length. The tag length can only be set before specifying an IV. If this is
not called prior to setting the IV during encryption, then a default tag length
is used.
For OCB AES, the default tag length is 16 (i.e. 128 bits). It is also the
maximum tag length for OCB.
=back
=head2 CCM Mode
The EVP interface for CCM mode is similar to that of the GCM mode but with a
few additional requirements and different I<ctrl> values.
For CCM mode, the total plaintext or ciphertext length B<MUST> be passed to
EVP_CipherUpdate(), EVP_EncryptUpdate() or EVP_DecryptUpdate() with the output
and input parameters (I<in> and I<out>) set to B<NULL> and the length passed in
the I<inl> parameter.
The following I<ctrl>s are supported in CCM mode.
=over 4
=item EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_TAG, taglen, tag)
This call is made to set the expected B<CCM> tag value when decrypting or
the length of the tag (with the C<tag> parameter set to NULL) when encrypting.
The tag length is often referred to as B<M>. If not set a default value is
used (12 for AES). When decrypting, the tag needs to be set before passing
in data to be decrypted, but as in GCM and OCB mode, it can be set after
passing additional authenticated data (see L</AEAD INTERFACE>).
=item EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_CCM_SET_L, ivlen, NULL)
Sets the CCM B<L> value. If not set a default is used (8 for AES).
=item EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_IVLEN, ivlen, NULL)
Sets the CCM nonce (IV) length. This call can only be made before specifying a
nonce value. The nonce length is given by B<15 - L> so it is 7 by default for
AES.
=back
=head2 SIV Mode
For SIV mode ciphers the behaviour of the EVP interface is subtly
altered and several additional ctrl operations are supported.
To specify any additional authenticated data (AAD) and/or a Nonce, a call to
EVP_CipherUpdate(), EVP_EncryptUpdate() or EVP_DecryptUpdate() should be made
with the output parameter I<out> set to B<NULL>.
RFC5297 states that the Nonce is the last piece of AAD before the actual
encrypt/decrypt takes place. The API does not differentiate the Nonce from
other AAD.
When decrypting the return value of EVP_DecryptFinal() or EVP_CipherFinal()
indicates if the operation was successful. If it does not indicate success
the authentication operation has failed and any output data B<MUST NOT>
be used as it is corrupted.
The API does not store the the SIV (Synthetic Initialization Vector) in
the cipher text. Instead, it is stored as the tag within the EVP_CIPHER_CTX.
The SIV must be retrieved from the context after encryption, and set into
the context before decryption.
This differs from RFC5297 in that the cipher output from encryption, and
the cipher input to decryption, does not contain the SIV. This also means
that the plain text and cipher text lengths are identical.
The following ctrls are supported in SIV mode, and are used to get and set
the Synthetic Initialization Vector:
=over 4
=item EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_GET_TAG, taglen, tag);
Writes I<taglen> bytes of the tag value (the Synthetic Initialization Vector)
to the buffer indicated by I<tag>. This call can only be made when encrypting
data and B<after> all data has been processed (e.g. after an EVP_EncryptFinal()
call). For SIV mode the taglen must be 16.
=item EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_TAG, taglen, tag);
Sets the expected tag (the Synthetic Initialization Vector) to I<taglen>
bytes from I<tag>. This call is only legal when decrypting data and must be
made B<before> any data is processed (e.g. before any EVP_DecryptUpdate()
calls). For SIV mode the taglen must be 16.
=back
SIV mode makes two passes over the input data, thus, only one call to
EVP_CipherUpdate(), EVP_EncryptUpdate() or EVP_DecryptUpdate() should be made
with I<out> set to a non-B<NULL> value. A call to EVP_DecryptFinal() or
EVP_CipherFinal() is not required, but will indicate if the update
operation succeeded.
=head2 ChaCha20-Poly1305
The following I<ctrl>s are supported for the ChaCha20-Poly1305 AEAD algorithm.
=over 4
=item EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_IVLEN, ivlen, NULL)
Sets the nonce length. This call is now redundant since the only valid value
is the default length of 12 (i.e. 96 bits).
Prior to OpenSSL 3.0 a nonce of less than 12 bytes could be used to automatically
pad the iv with leading 0 bytes to make it 12 bytes in length.
=item EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_GET_TAG, taglen, tag)
Writes C<taglen> bytes of the tag value to the buffer indicated by C<tag>.
This call can only be made when encrypting data and B<after> all data has been
processed (e.g. after an EVP_EncryptFinal() call).
C<taglen> specified here must be 16 (B<POLY1305_BLOCK_SIZE>, i.e. 128-bits) or
less.
=item EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_TAG, taglen, tag)
Sets the expected tag to C<taglen> bytes from C<tag>.
The tag length can only be set before specifying an IV.
C<taglen> must be between 1 and 16 (B<POLY1305_BLOCK_SIZE>) inclusive.
This call is only valid when decrypting data.
=back
=head1 NOTES
Where possible the B<EVP> interface to symmetric ciphers should be used in
preference to the low-level interfaces. This is because the code then becomes
transparent to the cipher used and much more flexible. Additionally, the
B<EVP> interface will ensure the use of platform specific cryptographic
acceleration such as AES-NI (the low-level interfaces do not provide the
guarantee).
PKCS padding works by adding B<n> padding bytes of value B<n> to make the total
length of the encrypted data a multiple of the block size. Padding is always
added so if the data is already a multiple of the block size B<n> will equal
the block size. For example if the block size is 8 and 11 bytes are to be
encrypted then 5 padding bytes of value 5 will be added.
When decrypting the final block is checked to see if it has the correct form.
Although the decryption operation can produce an error if padding is enabled,
it is not a strong test that the input data or key is correct. A random block
has better than 1 in 256 chance of being of the correct format and problems with
the input data earlier on will not produce a final decrypt error.
If padding is disabled then the decryption operation will always succeed if
the total amount of data decrypted is a multiple of the block size.
The functions EVP_EncryptInit(), EVP_EncryptInit_ex(),
EVP_EncryptFinal(), EVP_DecryptInit(), EVP_DecryptInit_ex(),
EVP_CipherInit(), EVP_CipherInit_ex() and EVP_CipherFinal() are obsolete
but are retained for compatibility with existing code. New code should
use EVP_EncryptInit_ex2(), EVP_EncryptFinal_ex(), EVP_DecryptInit_ex2(),
EVP_DecryptFinal_ex(), EVP_CipherInit_ex2() and EVP_CipherFinal_ex()
because they can reuse an existing context without allocating and freeing
it up on each call.
There are some differences between functions EVP_CipherInit() and
EVP_CipherInit_ex(), significant in some circumstances. EVP_CipherInit() fills
the passed context object with zeros. As a consequence, EVP_CipherInit() does
not allow step-by-step initialization of the ctx when the I<key> and I<iv> are
passed in separate calls. It also means that the flags set for the CTX are
removed, and it is especially important for the
B<EVP_CIPHER_CTX_FLAG_WRAP_ALLOW> flag treated specially in
EVP_CipherInit_ex().
Ignoring failure returns of the B<EVP_CIPHER_CTX> initialization functions can
lead to subsequent undefined behavior when calling the functions that update or
finalize the context. The only valid calls on the B<EVP_CIPHER_CTX> when
initialization fails are calls that attempt another initialization of the
context or release the context.
EVP_get_cipherbynid(), and EVP_get_cipherbyobj() are implemented as macros.
=head1 BUGS
B<EVP_MAX_KEY_LENGTH> and B<EVP_MAX_IV_LENGTH> only refer to the internal
ciphers with default key lengths. If custom ciphers exceed these values the
results are unpredictable. This is because it has become standard practice to
define a generic key as a fixed unsigned char array containing
B<EVP_MAX_KEY_LENGTH> bytes.
The ASN1 code is incomplete (and sometimes inaccurate) it has only been tested
for certain common S/MIME ciphers (RC2, DES, triple DES) in CBC mode.
=head1 EXAMPLES
Encrypt a string using IDEA:
int do_crypt(char *outfile)
{
unsigned char outbuf[1024];
int outlen, tmplen;
/*
* Bogus key and IV: we'd normally set these from
* another source.
*/
unsigned char key[] = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};
unsigned char iv[] = {1,2,3,4,5,6,7,8};
char intext[] = "Some Crypto Text";
EVP_CIPHER_CTX *ctx;
FILE *out;
ctx = EVP_CIPHER_CTX_new();
if (!EVP_EncryptInit_ex2(ctx, EVP_idea_cbc(), key, iv, NULL)) {
/* Error */
EVP_CIPHER_CTX_free(ctx);
return 0;
}
if (!EVP_EncryptUpdate(ctx, outbuf, &outlen, intext, strlen(intext))) {
/* Error */
EVP_CIPHER_CTX_free(ctx);
return 0;
}
/*
* Buffer passed to EVP_EncryptFinal() must be after data just
* encrypted to avoid overwriting it.
*/
if (!EVP_EncryptFinal_ex(ctx, outbuf + outlen, &tmplen)) {
/* Error */
EVP_CIPHER_CTX_free(ctx);
return 0;
}
outlen += tmplen;
EVP_CIPHER_CTX_free(ctx);
/*
* Need binary mode for fopen because encrypted data is
* binary data. Also cannot use strlen() on it because
* it won't be NUL terminated and may contain embedded
* NULs.
*/
out = fopen(outfile, "wb");
if (out == NULL) {
/* Error */
return 0;
}
fwrite(outbuf, 1, outlen, out);
fclose(out);
return 1;
}
The ciphertext from the above example can be decrypted using the B<openssl>
utility with the command line (shown on two lines for clarity):
openssl idea -d \
-K 000102030405060708090A0B0C0D0E0F -iv 0102030405060708 <filename
General encryption and decryption function example using FILE I/O and AES128
with a 128-bit key:
int do_crypt(FILE *in, FILE *out, int do_encrypt)
{
/* Allow enough space in output buffer for additional block */
unsigned char inbuf[1024], outbuf[1024 + EVP_MAX_BLOCK_LENGTH];
int inlen, outlen;
EVP_CIPHER_CTX *ctx;
/*
* Bogus key and IV: we'd normally set these from
* another source.
*/
unsigned char key[] = "0123456789abcdeF";
unsigned char iv[] = "1234567887654321";
/* Don't set key or IV right away; we want to check lengths */
ctx = EVP_CIPHER_CTX_new();
if (!EVP_CipherInit_ex2(ctx, EVP_aes_128_cbc(), NULL, NULL,
do_encrypt, NULL)) {
/* Error */
EVP_CIPHER_CTX_free(ctx);
return 0;
}
OPENSSL_assert(EVP_CIPHER_CTX_get_key_length(ctx) == 16);
OPENSSL_assert(EVP_CIPHER_CTX_get_iv_length(ctx) == 16);
/* Now we can set key and IV */
if (!EVP_CipherInit_ex2(ctx, NULL, key, iv, do_encrypt, NULL)) {
/* Error */
EVP_CIPHER_CTX_free(ctx);
return 0;
}
for (;;) {
inlen = fread(inbuf, 1, 1024, in);
if (inlen <= 0)
break;
if (!EVP_CipherUpdate(ctx, outbuf, &outlen, inbuf, inlen)) {
/* Error */
EVP_CIPHER_CTX_free(ctx);
return 0;
}
fwrite(outbuf, 1, outlen, out);
}
if (!EVP_CipherFinal_ex(ctx, outbuf, &outlen)) {
/* Error */
EVP_CIPHER_CTX_free(ctx);
return 0;
}
fwrite(outbuf, 1, outlen, out);
EVP_CIPHER_CTX_free(ctx);
return 1;
}
Encryption using AES-CBC with a 256-bit key with "CS1" ciphertext stealing.
int encrypt(const unsigned char *key, const unsigned char *iv,
const unsigned char *msg, size_t msg_len, unsigned char *out)
{
/*
* This assumes that key size is 32 bytes and the iv is 16 bytes.
* For ciphertext stealing mode the length of the ciphertext "out" will be
* the same size as the plaintext size "msg_len".
* The "msg_len" can be any size >= 16.
*/
int ret = 0, encrypt = 1, outlen, len;
EVP_CIPHER_CTX *ctx = NULL;
EVP_CIPHER *cipher = NULL;
OSSL_PARAM params[2];
ctx = EVP_CIPHER_CTX_new();
cipher = EVP_CIPHER_fetch(NULL, "AES-256-CBC-CTS", NULL);
if (ctx == NULL || cipher == NULL)
goto err;
/*
* The default is "CS1" so this is not really needed,
* but would be needed to set either "CS2" or "CS3".
*/
params[0] = OSSL_PARAM_construct_utf8_string(OSSL_CIPHER_PARAM_CTS_MODE,
"CS1", 0);
params[1] = OSSL_PARAM_construct_end();
if (!EVP_CipherInit_ex2(ctx, cipher, key, iv, encrypt, params))
goto err;
/* NOTE: CTS mode does not support multiple calls to EVP_CipherUpdate() */
if (!EVP_CipherUpdate(ctx, out, &outlen, msg, msg_len))
goto err;
if (!EVP_CipherFinal_ex(ctx, out + outlen, &len))
goto err;
ret = 1;
err:
EVP_CIPHER_free(cipher);
EVP_CIPHER_CTX_free(ctx);
return ret;
}
=head1 SEE ALSO
L<evp(7)>,
L<property(7)>,
L<crypto(7)/ALGORITHM FETCHING>,
L<provider-cipher(7)>,
L<life_cycle-cipher(7)>
Supported ciphers are listed in:
L<EVP_aes_128_gcm(3)>,
L<EVP_aria_128_gcm(3)>,
L<EVP_bf_cbc(3)>,
L<EVP_camellia_128_ecb(3)>,
L<EVP_cast5_cbc(3)>,
L<EVP_chacha20(3)>,
L<EVP_des_cbc(3)>,
L<EVP_desx_cbc(3)>,
L<EVP_idea_cbc(3)>,
L<EVP_rc2_cbc(3)>,
L<EVP_rc4(3)>,
L<EVP_rc5_32_12_16_cbc(3)>,
L<EVP_seed_cbc(3)>,
L<EVP_sm4_cbc(3)>,
=head1 HISTORY
Support for OCB mode was added in OpenSSL 1.1.0.
B<EVP_CIPHER_CTX> was made opaque in OpenSSL 1.1.0. As a result,
EVP_CIPHER_CTX_reset() appeared and EVP_CIPHER_CTX_cleanup()
disappeared. EVP_CIPHER_CTX_init() remains as an alias for
EVP_CIPHER_CTX_reset().
The EVP_CIPHER_CTX_cipher() function was deprecated in OpenSSL 3.0; use
EVP_CIPHER_CTX_get0_cipher() instead.
The EVP_EncryptInit_ex2(), EVP_DecryptInit_ex2(), EVP_CipherInit_ex2(),
EVP_CIPHER_fetch(), EVP_CIPHER_free(), EVP_CIPHER_up_ref(),
EVP_CIPHER_CTX_get0_cipher(), EVP_CIPHER_CTX_get1_cipher(),
EVP_CIPHER_get_params(), EVP_CIPHER_CTX_set_params(),
EVP_CIPHER_CTX_get_params(), EVP_CIPHER_gettable_params(),
EVP_CIPHER_settable_ctx_params(), EVP_CIPHER_gettable_ctx_params(),
EVP_CIPHER_CTX_settable_params() and EVP_CIPHER_CTX_gettable_params()
functions were added in 3.0.
The EVP_CIPHER_nid(), EVP_CIPHER_name(), EVP_CIPHER_block_size(),
EVP_CIPHER_key_length(), EVP_CIPHER_iv_length(), EVP_CIPHER_flags(),
EVP_CIPHER_mode(), EVP_CIPHER_type(), EVP_CIPHER_CTX_nid(),
EVP_CIPHER_CTX_block_size(), EVP_CIPHER_CTX_key_length(),
EVP_CIPHER_CTX_iv_length(), EVP_CIPHER_CTX_tag_length(),
EVP_CIPHER_CTX_num(), EVP_CIPHER_CTX_type(), and EVP_CIPHER_CTX_mode()
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_CIPHER_CTX_encrypting() function was renamed to
EVP_CIPHER_CTX_is_encrypting() in OpenSSL 3.0. The old name is kept as
non-deprecated alias macro.
The EVP_CIPHER_CTX_flags() macro was deprecated in OpenSSL 1.1.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_KEM_free.pod b/crypto/openssl/doc/man3/EVP_KEM_free.pod
index 575abc5f5798..b0ef604757d7 100644
--- a/crypto/openssl/doc/man3/EVP_KEM_free.pod
+++ b/crypto/openssl/doc/man3/EVP_KEM_free.pod
@@ -1,105 +1,106 @@
=pod
=head1 NAME
EVP_KEM_fetch, EVP_KEM_free, EVP_KEM_up_ref,
EVP_KEM_get0_name, EVP_KEM_is_a, EVP_KEM_get0_provider,
EVP_KEM_do_all_provided, EVP_KEM_names_do_all, EVP_KEM_get0_description,
EVP_KEM_gettable_ctx_params, EVP_KEM_settable_ctx_params
- Functions to manage EVP_KEM algorithm objects
=head1 SYNOPSIS
#include <openssl/evp.h>
EVP_KEM *EVP_KEM_fetch(OSSL_LIB_CTX *ctx, const char *algorithm,
const char *properties);
void EVP_KEM_free(EVP_KEM *kem);
int EVP_KEM_up_ref(EVP_KEM *kem);
const char *EVP_KEM_get0_name(const EVP_KEM *kem);
int EVP_KEM_is_a(const EVP_KEM *kem, const char *name);
OSSL_PROVIDER *EVP_KEM_get0_provider(const EVP_KEM *kem);
void EVP_KEM_do_all_provided(OSSL_LIB_CTX *libctx,
void (*fn)(EVP_KEM *kem, void *arg), void *arg);
int EVP_KEM_names_do_all(const EVP_KEM *kem,
void (*fn)(const char *name, void *data), void *data);
const char *EVP_KEM_get0_description(const EVP_KEM *kem);
const OSSL_PARAM *EVP_KEM_gettable_ctx_params(const EVP_KEM *kem);
const OSSL_PARAM *EVP_KEM_settable_ctx_params(const EVP_KEM *kem);
=head1 DESCRIPTION
EVP_KEM_fetch() fetches the implementation for the given B<algorithm> from any
provider offering it, within the criteria given by the B<properties> and in the
scope of the given library context B<ctx> (see L<OSSL_LIB_CTX(3)>). The algorithm
will be one offering functions for performing asymmetric kem related tasks such
as key encapsulation and decapsulation.
See L<crypto(7)/ALGORITHM FETCHING> for further information.
The returned value must eventually be freed with EVP_KEM_free().
EVP_KEM_free() decrements the reference count for the B<EVP_KEM> structure.
Typically this structure will have been obtained from an earlier call to
EVP_KEM_fetch(). If the reference count drops to 0 then the structure is freed.
+If the argument is NULL, nothing is done.
EVP_KEM_up_ref() increments the reference count for an B<EVP_KEM> structure.
EVP_KEM_is_a() returns 1 if I<kem> is an implementation of an
algorithm that's identifiable with I<name>, otherwise 0.
EVP_KEM_get0_provider() returns the provider that I<kem> was fetched from.
EVP_KEM_do_all_provided() traverses all EVP_KEMs 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_KEM_get0_name() returns the algorithm name from the provided
implementation for the given I<kem>. Note that the I<kem> may have
multiple synonyms associated with it. In this case the first name from the
algorithm definition is returned. Ownership of the returned string is retained
by the I<kem> object and should not be freed by the caller.
EVP_KEM_names_do_all() traverses all names for I<kem>, and calls I<fn> with
each name and I<data>.
EVP_KEM_get0_description() returns a description of the I<kem>, meant for
display and human consumption. The description is at the discretion of
the I<kem> implementation.
EVP_KEM_gettable_ctx_params() and EVP_KEM_settable_ctx_params() return
a constant L<OSSL_PARAM(3)> array that describes the names and types of key
parameters that can be retrieved or set by a key encapsulation algorithm using
L<EVP_PKEY_CTX_get_params(3)> and L<EVP_PKEY_CTX_set_params(3)>.
=head1 RETURN VALUES
EVP_KEM_fetch() returns a pointer to an B<EVP_KEM> for success or B<NULL> for
failure.
EVP_KEM_up_ref() returns 1 for success or 0 otherwise.
EVP_KEM_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.
EVP_KEM_gettable_ctx_params() and EVP_KEM_settable_ctx_params() return
a constant L<OSSL_PARAM(3)> array or NULL on error.
=head1 SEE ALSO
L<crypto(7)/ALGORITHM FETCHING>, L<OSSL_PROVIDER(3)>
=head1 HISTORY
The functions described here 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_KEYEXCH_free.pod b/crypto/openssl/doc/man3/EVP_KEYEXCH_free.pod
index 272855ccb3dd..e08f44e60c73 100644
--- a/crypto/openssl/doc/man3/EVP_KEYEXCH_free.pod
+++ b/crypto/openssl/doc/man3/EVP_KEYEXCH_free.pod
@@ -1,111 +1,111 @@
=pod
=head1 NAME
EVP_KEYEXCH_fetch, EVP_KEYEXCH_free, EVP_KEYEXCH_up_ref,
EVP_KEYEXCH_get0_provider, EVP_KEYEXCH_is_a, EVP_KEYEXCH_do_all_provided,
EVP_KEYEXCH_names_do_all, EVP_KEYEXCH_get0_name, EVP_KEYEXCH_get0_description,
EVP_KEYEXCH_gettable_ctx_params, EVP_KEYEXCH_settable_ctx_params
- Functions to manage EVP_KEYEXCH algorithm objects
=head1 SYNOPSIS
#include <openssl/evp.h>
EVP_KEYEXCH *EVP_KEYEXCH_fetch(OSSL_LIB_CTX *ctx, const char *algorithm,
const char *properties);
void EVP_KEYEXCH_free(EVP_KEYEXCH *exchange);
int EVP_KEYEXCH_up_ref(EVP_KEYEXCH *exchange);
OSSL_PROVIDER *EVP_KEYEXCH_get0_provider(const EVP_KEYEXCH *exchange);
int EVP_KEYEXCH_is_a(const EVP_KEYEXCH *exchange, const char *name);
const char *EVP_KEYEXCH_get0_name(const EVP_KEYEXCH *exchange);
void EVP_KEYEXCH_do_all_provided(OSSL_LIB_CTX *libctx,
void (*fn)(EVP_KEYEXCH *exchange, void *arg),
void *arg);
int EVP_KEYEXCH_names_do_all(const EVP_KEYEXCH *exchange,
void (*fn)(const char *name, void *data),
void *data);
const char *EVP_KEYEXCH_get0_description(const EVP_KEYEXCH *keyexch);
const OSSL_PARAM *EVP_KEYEXCH_gettable_ctx_params(const EVP_KEYEXCH *keyexch);
const OSSL_PARAM *EVP_KEYEXCH_settable_ctx_params(const EVP_KEYEXCH *keyexch);
=head1 DESCRIPTION
EVP_KEYEXCH_fetch() fetches the key exchange 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_KEYEXCH_free().
EVP_KEYEXCH_free() decrements the reference count for the B<EVP_KEYEXCH>
structure. Typically this structure will have been obtained from an earlier call
to EVP_KEYEXCH_fetch(). If the reference count drops to 0 then the
-structure is freed.
+structure is freed. If the argument is NULL, nothing is done.
EVP_KEYEXCH_up_ref() increments the reference count for an B<EVP_KEYEXCH>
structure.
EVP_KEYEXCH_get0_provider() returns the provider that I<exchange> was
fetched from.
EVP_KEYEXCH_is_a() checks if I<exchange> is an implementation of an
algorithm that's identifiable with I<name>.
EVP_KEYEXCH_get0_name() returns the algorithm name from the provided
implementation for the given I<exchange>. Note that the I<exchange> may have
multiple synonyms associated with it. In this case the first name from the
algorithm definition is returned. Ownership of the returned string is retained
by the I<exchange> object and should not be freed by the caller.
EVP_KEYEXCH_names_do_all() traverses all names for the I<exchange>, and
calls I<fn> with each name and I<data>.
EVP_KEYEXCH_get0_description() returns a description of the I<keyexch>, meant
for display and human consumption. The description is at the discretion of
the I<keyexch> implementation.
EVP_KEYEXCH_do_all_provided() traverses all key exchange implementations by
all activated providers in the library context I<libctx>, and for each
of the implementations, calls I<fn> with the implementation method and
I<data> as arguments.
EVP_KEYEXCH_gettable_ctx_params() and EVP_KEYEXCH_settable_ctx_params() return
a constant L<OSSL_PARAM(3)> array that describes the names and types of key
parameters that can be retrieved or set by a key exchange algorithm using
L<EVP_PKEY_CTX_get_params(3)> and L<EVP_PKEY_CTX_set_params(3)>.
=head1 RETURN VALUES
EVP_KEYEXCH_fetch() returns a pointer to a B<EVP_KEYEXCH> for success
or NULL for failure.
EVP_KEYEXCH_up_ref() returns 1 for success or 0 otherwise.
EVP_KEYEXCH_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.
EVP_KEYEXCH_is_a() returns 1 of I<exchange> was identifiable,
otherwise 0.
EVP_KEYEXCH_gettable_ctx_params() and EVP_KEYEXCH_settable_ctx_params() return
a constant L<OSSL_PARAM(3)> array or NULL on error.
=head1 SEE ALSO
L<crypto(7)/ALGORITHM FETCHING>, L<OSSL_PROVIDER(3)>
=head1 HISTORY
The functions described here were added in 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/man3/EVP_KEYMGMT.pod b/crypto/openssl/doc/man3/EVP_KEYMGMT.pod
index 455ffadce5ec..4c0c3b776c64 100644
--- a/crypto/openssl/doc/man3/EVP_KEYMGMT.pod
+++ b/crypto/openssl/doc/man3/EVP_KEYMGMT.pod
@@ -1,150 +1,151 @@
=pod
=head1 NAME
EVP_KEYMGMT,
EVP_KEYMGMT_fetch,
EVP_KEYMGMT_up_ref,
EVP_KEYMGMT_free,
EVP_KEYMGMT_get0_provider,
EVP_KEYMGMT_is_a,
EVP_KEYMGMT_get0_description,
EVP_KEYMGMT_get0_name,
EVP_KEYMGMT_do_all_provided,
EVP_KEYMGMT_names_do_all,
EVP_KEYMGMT_gettable_params,
EVP_KEYMGMT_settable_params,
EVP_KEYMGMT_gen_settable_params
- EVP key management routines
=head1 SYNOPSIS
#include <openssl/evp.h>
typedef struct evp_keymgmt_st EVP_KEYMGMT;
EVP_KEYMGMT *EVP_KEYMGMT_fetch(OSSL_LIB_CTX *ctx, const char *algorithm,
const char *properties);
int EVP_KEYMGMT_up_ref(EVP_KEYMGMT *keymgmt);
void EVP_KEYMGMT_free(EVP_KEYMGMT *keymgmt);
const OSSL_PROVIDER *EVP_KEYMGMT_get0_provider(const EVP_KEYMGMT *keymgmt);
int EVP_KEYMGMT_is_a(const EVP_KEYMGMT *keymgmt, const char *name);
const char *EVP_KEYMGMT_get0_name(const EVP_KEYMGMT *keymgmt);
const char *EVP_KEYMGMT_get0_description(const EVP_KEYMGMT *keymgmt);
void EVP_KEYMGMT_do_all_provided(OSSL_LIB_CTX *libctx,
void (*fn)(EVP_KEYMGMT *keymgmt, void *arg),
void *arg);
int EVP_KEYMGMT_names_do_all(const EVP_KEYMGMT *keymgmt,
void (*fn)(const char *name, void *data),
void *data);
const OSSL_PARAM *EVP_KEYMGMT_gettable_params(const EVP_KEYMGMT *keymgmt);
const OSSL_PARAM *EVP_KEYMGMT_settable_params(const EVP_KEYMGMT *keymgmt);
const OSSL_PARAM *EVP_KEYMGMT_gen_settable_params(const EVP_KEYMGMT *keymgmt);
=head1 DESCRIPTION
B<EVP_KEYMGMT> is a method object that represents key management
implementations for different cryptographic algorithms.
This method object provides functionality to have providers import key
material from the outside, as well as export key material to the
outside.
Most of the functionality can only be used internally and has no
public interface, this object is simply passed into other functions
when needed.
EVP_KEYMGMT_fetch() looks for an algorithm within the provider that
has been loaded into the B<OSSL_LIB_CTX> given by I<ctx>, having the
name given by I<algorithm> and the properties given by I<properties>.
EVP_KEYMGMT_up_ref() increments the reference count for the given
B<EVP_KEYMGMT> I<keymgmt>.
EVP_KEYMGMT_free() decrements the reference count for the given
B<EVP_KEYMGMT> I<keymgmt>, and when the count reaches zero, frees it.
+If the argument is NULL, nothing is done.
EVP_KEYMGMT_get0_provider() returns the provider that has this particular
implementation.
EVP_KEYMGMT_is_a() checks if I<keymgmt> is an implementation of an
algorithm that's identifiable with I<name>.
EVP_KEYMGMT_get0_name() returns the algorithm name from the provided
implementation for the given I<keymgmt>. Note that the I<keymgmt> may have
multiple synonyms associated with it. In this case the first name from the
algorithm definition is returned. Ownership of the returned string is
retained by the I<keymgmt> object and should not be freed by the caller.
EVP_KEYMGMT_names_do_all() traverses all names for the I<keymgmt>, and
calls I<fn> with each name and I<data>.
EVP_KEYMGMT_get0_description() returns a description of the I<keymgmt>, meant
for display and human consumption. The description is at the discretion
of the I<keymgmt> implementation.
EVP_KEYMGMT_do_all_provided() traverses all key keymgmt implementations by
all activated providers in the library context I<libctx>, and for each
of the implementations, calls I<fn> with the implementation method and
I<data> as arguments.
EVP_KEYMGMT_gettable_params() and EVP_KEYMGMT_settable_params() return a
constant L<OSSL_PARAM(3)> array that describes the names and types of key
parameters that can be retrieved or set.
EVP_KEYMGMT_gettable_params() is used by L<EVP_PKEY_gettable_params(3)>.
EVP_KEYMGMT_gen_settable_params() returns a constant L<OSSL_PARAM(3)> array that
describes the names and types of key generation parameters that can be set via
L<EVP_PKEY_CTX_set_params(3)>.
=head1 NOTES
EVP_KEYMGMT_fetch() may be called implicitly by other fetching
functions, using the same library context and properties.
Any other API that uses keys will typically do this.
=head1 RETURN VALUES
EVP_KEYMGMT_fetch() returns a pointer to the key management
implementation represented by an EVP_KEYMGMT object, or NULL on
error.
EVP_KEYMGMT_up_ref() returns 1 on success, or 0 on error.
EVP_KEYMGMT_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.
EVP_KEYMGMT_free() doesn't return any value.
EVP_KEYMGMT_get0_provider() returns a pointer to a provider object, or NULL
on error.
EVP_KEYMGMT_is_a() returns 1 of I<keymgmt> was identifiable,
otherwise 0.
EVP_KEYMGMT_get0_name() returns the algorithm name, or NULL on error.
EVP_KEYMGMT_get0_description() returns a pointer to a description, or NULL if
there isn't one.
EVP_KEYMGMT_gettable_params(), EVP_KEYMGMT_settable_params() and
EVP_KEYMGMT_gen_settable_params() return a constant L<OSSL_PARAM(3)> array or
NULL on error.
=head1 SEE ALSO
L<EVP_MD_fetch(3)>, L<OSSL_LIB_CTX(3)>
=head1 HISTORY
The functions described here were 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_MD_meth_new.pod b/crypto/openssl/doc/man3/EVP_MD_meth_new.pod
index a553c378f3d7..349797332376 100644
--- a/crypto/openssl/doc/man3/EVP_MD_meth_new.pod
+++ b/crypto/openssl/doc/man3/EVP_MD_meth_new.pod
@@ -1,204 +1,205 @@
=pod
=head1 NAME
EVP_MD_meth_new, EVP_MD_meth_dup, EVP_MD_meth_free,
EVP_MD_meth_set_input_blocksize,
EVP_MD_meth_set_result_size, EVP_MD_meth_set_app_datasize,
EVP_MD_meth_set_flags, EVP_MD_meth_set_init, EVP_MD_meth_set_update,
EVP_MD_meth_set_final, EVP_MD_meth_set_copy, EVP_MD_meth_set_cleanup,
EVP_MD_meth_set_ctrl, EVP_MD_meth_get_input_blocksize,
EVP_MD_meth_get_result_size, EVP_MD_meth_get_app_datasize,
EVP_MD_meth_get_flags, EVP_MD_meth_get_init, EVP_MD_meth_get_update,
EVP_MD_meth_get_final, EVP_MD_meth_get_copy, EVP_MD_meth_get_cleanup,
EVP_MD_meth_get_ctrl
- Routines to build up legacy EVP_MD methods
=head1 SYNOPSIS
#include <openssl/evp.h>
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)>:
EVP_MD *EVP_MD_meth_new(int md_type, int pkey_type);
void EVP_MD_meth_free(EVP_MD *md);
EVP_MD *EVP_MD_meth_dup(const EVP_MD *md);
int EVP_MD_meth_set_input_blocksize(EVP_MD *md, int blocksize);
int EVP_MD_meth_set_result_size(EVP_MD *md, int resultsize);
int EVP_MD_meth_set_app_datasize(EVP_MD *md, int datasize);
int EVP_MD_meth_set_flags(EVP_MD *md, unsigned long flags);
int EVP_MD_meth_set_init(EVP_MD *md, int (*init)(EVP_MD_CTX *ctx));
int EVP_MD_meth_set_update(EVP_MD *md, int (*update)(EVP_MD_CTX *ctx,
const void *data,
size_t count));
int EVP_MD_meth_set_final(EVP_MD *md, int (*final)(EVP_MD_CTX *ctx,
unsigned char *md));
int EVP_MD_meth_set_copy(EVP_MD *md, int (*copy)(EVP_MD_CTX *to,
const EVP_MD_CTX *from));
int EVP_MD_meth_set_cleanup(EVP_MD *md, int (*cleanup)(EVP_MD_CTX *ctx));
int EVP_MD_meth_set_ctrl(EVP_MD *md, int (*ctrl)(EVP_MD_CTX *ctx, int cmd,
int p1, void *p2));
int EVP_MD_meth_get_input_blocksize(const EVP_MD *md);
int EVP_MD_meth_get_result_size(const EVP_MD *md);
int EVP_MD_meth_get_app_datasize(const EVP_MD *md);
unsigned long EVP_MD_meth_get_flags(const EVP_MD *md);
int (*EVP_MD_meth_get_init(const EVP_MD *md))(EVP_MD_CTX *ctx);
int (*EVP_MD_meth_get_update(const EVP_MD *md))(EVP_MD_CTX *ctx,
const void *data,
size_t count);
int (*EVP_MD_meth_get_final(const EVP_MD *md))(EVP_MD_CTX *ctx,
unsigned char *md);
int (*EVP_MD_meth_get_copy(const EVP_MD *md))(EVP_MD_CTX *to,
const EVP_MD_CTX *from);
int (*EVP_MD_meth_get_cleanup(const EVP_MD *md))(EVP_MD_CTX *ctx);
int (*EVP_MD_meth_get_ctrl(const EVP_MD *md))(EVP_MD_CTX *ctx, int cmd,
int p1, void *p2);
=head1 DESCRIPTION
All of the functions described on this page are deprecated.
Applications should instead use the OSSL_PROVIDER APIs.
The B<EVP_MD> type is a structure for digest method implementation.
It can also have associated public/private key signing and verifying
routines.
EVP_MD_meth_new() creates a new B<EVP_MD> structure.
These B<EVP_MD> structures are reference counted.
EVP_MD_meth_dup() creates a copy of B<md>.
EVP_MD_meth_free() decrements the reference count for the B<EVP_MD> structure.
If the reference count drops to 0 then the structure is freed.
+If the argument is NULL, nothing is done.
EVP_MD_meth_set_input_blocksize() sets the internal input block size
for the method B<md> to B<blocksize> bytes.
EVP_MD_meth_set_result_size() sets the size of the result that the
digest method in B<md> is expected to produce to B<resultsize> bytes.
The digest method may have its own private data, which OpenSSL will
allocate for it. EVP_MD_meth_set_app_datasize() should be used to
set the size for it to B<datasize>.
EVP_MD_meth_set_flags() sets the flags to describe optional
behaviours in the particular B<md>. Several flags can be or'd
together. The available flags are:
=over 4
=item EVP_MD_FLAG_ONESHOT
This digest method can only handle one block of input.
=item EVP_MD_FLAG_XOF
This digest method is an extensible-output function (XOF) and supports
the B<EVP_MD_CTRL_XOF_LEN> control.
=item EVP_MD_FLAG_DIGALGID_NULL
When setting up a DigestAlgorithmIdentifier, this flag will have the
parameter set to NULL by default. Use this for PKCS#1. I<Note: if
combined with EVP_MD_FLAG_DIGALGID_ABSENT, the latter will override.>
=item EVP_MD_FLAG_DIGALGID_ABSENT
When setting up a DigestAlgorithmIdentifier, this flag will have the
parameter be left absent by default. I<Note: if combined with
EVP_MD_FLAG_DIGALGID_NULL, the latter will be overridden.>
=item EVP_MD_FLAG_DIGALGID_CUSTOM
Custom DigestAlgorithmIdentifier handling via ctrl, with
B<EVP_MD_FLAG_DIGALGID_ABSENT> as default. I<Note: if combined with
EVP_MD_FLAG_DIGALGID_NULL, the latter will be overridden.>
Currently unused.
=item EVP_MD_FLAG_FIPS
This digest method is suitable for use in FIPS mode.
Currently unused.
=back
EVP_MD_meth_set_init() sets the digest init function for B<md>.
The digest init function is called by EVP_Digest(), EVP_DigestInit(),
EVP_DigestInit_ex(), EVP_SignInit, EVP_SignInit_ex(), EVP_VerifyInit()
and EVP_VerifyInit_ex().
EVP_MD_meth_set_update() sets the digest update function for B<md>.
The digest update function is called by EVP_Digest(), EVP_DigestUpdate() and
EVP_SignUpdate().
EVP_MD_meth_set_final() sets the digest final function for B<md>.
The digest final function is called by EVP_Digest(), EVP_DigestFinal(),
EVP_DigestFinal_ex(), EVP_SignFinal() and EVP_VerifyFinal().
EVP_MD_meth_set_copy() sets the function for B<md> to do extra
computations after the method's private data structure has been copied
from one B<EVP_MD_CTX> to another. If all that's needed is to copy
the data, there is no need for this copy function.
Note that the copy function is passed two B<EVP_MD_CTX *>, the private
data structure is then available with EVP_MD_CTX_get0_md_data().
This copy function is called by EVP_MD_CTX_copy() and
EVP_MD_CTX_copy_ex().
EVP_MD_meth_set_cleanup() sets the function for B<md> to do extra
cleanup before the method's private data structure is cleaned out and
freed.
Note that the cleanup function is passed a B<EVP_MD_CTX *>, the
private data structure is then available with EVP_MD_CTX_get0_md_data().
This cleanup function is called by EVP_MD_CTX_reset() and
EVP_MD_CTX_free().
EVP_MD_meth_set_ctrl() sets the control function for B<md>.
See L<EVP_MD_CTX_ctrl(3)> for the available controls.
EVP_MD_meth_get_input_blocksize(), EVP_MD_meth_get_result_size(),
EVP_MD_meth_get_app_datasize(), EVP_MD_meth_get_flags(),
EVP_MD_meth_get_init(), EVP_MD_meth_get_update(),
EVP_MD_meth_get_final(), EVP_MD_meth_get_copy(),
EVP_MD_meth_get_cleanup() and EVP_MD_meth_get_ctrl() are all used
to retrieve the method data given with the EVP_MD_meth_set_*()
functions above.
=head1 RETURN VALUES
EVP_MD_meth_new() and EVP_MD_meth_dup() return a pointer to a newly
created B<EVP_MD>, or NULL on failure.
All EVP_MD_meth_set_*() functions return 1.
EVP_MD_get_input_blocksize(), EVP_MD_meth_get_result_size(),
EVP_MD_meth_get_app_datasize() and EVP_MD_meth_get_flags() return the
indicated sizes or flags.
All other EVP_CIPHER_meth_get_*() functions return pointers to their
respective B<md> function.
=head1 SEE ALSO
L<EVP_DigestInit(3)>, L<EVP_SignInit(3)>, L<EVP_VerifyInit(3)>
=head1 HISTORY
All of these functions were deprecated in OpenSSL 3.0.
The B<EVP_MD> structure was openly available in OpenSSL before version
1.1.
The functions described here were added in OpenSSL 1.1.
The B<EVP_MD> structure created with these functions became reference
counted in OpenSSL 3.0.
=head1 COPYRIGHT
-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
L<https://www.openssl.org/source/license.html>.
=cut
diff --git a/crypto/openssl/doc/man3/EVP_PKEY_ASN1_METHOD.pod b/crypto/openssl/doc/man3/EVP_PKEY_ASN1_METHOD.pod
index cc50d363daf1..41f058fe54ee 100644
--- a/crypto/openssl/doc/man3/EVP_PKEY_ASN1_METHOD.pod
+++ b/crypto/openssl/doc/man3/EVP_PKEY_ASN1_METHOD.pod
@@ -1,449 +1,449 @@
=pod
=head1 NAME
EVP_PKEY_ASN1_METHOD,
EVP_PKEY_asn1_new,
EVP_PKEY_asn1_copy,
EVP_PKEY_asn1_free,
EVP_PKEY_asn1_add0,
EVP_PKEY_asn1_add_alias,
EVP_PKEY_asn1_set_public,
EVP_PKEY_asn1_set_private,
EVP_PKEY_asn1_set_param,
EVP_PKEY_asn1_set_free,
EVP_PKEY_asn1_set_ctrl,
EVP_PKEY_asn1_set_item,
EVP_PKEY_asn1_set_siginf,
EVP_PKEY_asn1_set_check,
EVP_PKEY_asn1_set_public_check,
EVP_PKEY_asn1_set_param_check,
EVP_PKEY_asn1_set_security_bits,
EVP_PKEY_asn1_set_set_priv_key,
EVP_PKEY_asn1_set_set_pub_key,
EVP_PKEY_asn1_set_get_priv_key,
EVP_PKEY_asn1_set_get_pub_key,
EVP_PKEY_get0_asn1
- manipulating and registering EVP_PKEY_ASN1_METHOD structure
=head1 SYNOPSIS
#include <openssl/evp.h>
typedef struct evp_pkey_asn1_method_st EVP_PKEY_ASN1_METHOD;
EVP_PKEY_ASN1_METHOD *EVP_PKEY_asn1_new(int id, int flags,
const char *pem_str,
const char *info);
void EVP_PKEY_asn1_copy(EVP_PKEY_ASN1_METHOD *dst,
const EVP_PKEY_ASN1_METHOD *src);
void EVP_PKEY_asn1_free(EVP_PKEY_ASN1_METHOD *ameth);
int EVP_PKEY_asn1_add0(const EVP_PKEY_ASN1_METHOD *ameth);
int EVP_PKEY_asn1_add_alias(int to, int from);
void EVP_PKEY_asn1_set_public(EVP_PKEY_ASN1_METHOD *ameth,
int (*pub_decode) (EVP_PKEY *pk,
const X509_PUBKEY *pub),
int (*pub_encode) (X509_PUBKEY *pub,
const EVP_PKEY *pk),
int (*pub_cmp) (const EVP_PKEY *a,
const EVP_PKEY *b),
int (*pub_print) (BIO *out,
const EVP_PKEY *pkey,
int indent, ASN1_PCTX *pctx),
int (*pkey_size) (const EVP_PKEY *pk),
int (*pkey_bits) (const EVP_PKEY *pk));
void EVP_PKEY_asn1_set_private(EVP_PKEY_ASN1_METHOD *ameth,
int (*priv_decode) (EVP_PKEY *pk,
const PKCS8_PRIV_KEY_INFO
*p8inf),
int (*priv_encode) (PKCS8_PRIV_KEY_INFO *p8,
const EVP_PKEY *pk),
int (*priv_print) (BIO *out,
const EVP_PKEY *pkey,
int indent,
ASN1_PCTX *pctx));
void EVP_PKEY_asn1_set_param(EVP_PKEY_ASN1_METHOD *ameth,
int (*param_decode) (EVP_PKEY *pkey,
const unsigned char **pder,
int derlen),
int (*param_encode) (const EVP_PKEY *pkey,
unsigned char **pder),
int (*param_missing) (const EVP_PKEY *pk),
int (*param_copy) (EVP_PKEY *to,
const EVP_PKEY *from),
int (*param_cmp) (const EVP_PKEY *a,
const EVP_PKEY *b),
int (*param_print) (BIO *out,
const EVP_PKEY *pkey,
int indent,
ASN1_PCTX *pctx));
void EVP_PKEY_asn1_set_free(EVP_PKEY_ASN1_METHOD *ameth,
void (*pkey_free) (EVP_PKEY *pkey));
void EVP_PKEY_asn1_set_ctrl(EVP_PKEY_ASN1_METHOD *ameth,
int (*pkey_ctrl) (EVP_PKEY *pkey, int op,
long arg1, void *arg2));
void EVP_PKEY_asn1_set_item(EVP_PKEY_ASN1_METHOD *ameth,
int (*item_verify) (EVP_MD_CTX *ctx,
const ASN1_ITEM *it,
void *asn,
X509_ALGOR *a,
ASN1_BIT_STRING *sig,
EVP_PKEY *pkey),
int (*item_sign) (EVP_MD_CTX *ctx,
const ASN1_ITEM *it,
void *asn,
X509_ALGOR *alg1,
X509_ALGOR *alg2,
ASN1_BIT_STRING *sig));
void EVP_PKEY_asn1_set_siginf(EVP_PKEY_ASN1_METHOD *ameth,
int (*siginf_set) (X509_SIG_INFO *siginf,
const X509_ALGOR *alg,
const ASN1_STRING *sig));
void EVP_PKEY_asn1_set_check(EVP_PKEY_ASN1_METHOD *ameth,
int (*pkey_check) (const EVP_PKEY *pk));
void EVP_PKEY_asn1_set_public_check(EVP_PKEY_ASN1_METHOD *ameth,
int (*pkey_pub_check) (const EVP_PKEY *pk));
void EVP_PKEY_asn1_set_param_check(EVP_PKEY_ASN1_METHOD *ameth,
int (*pkey_param_check) (const EVP_PKEY *pk));
void EVP_PKEY_asn1_set_security_bits(EVP_PKEY_ASN1_METHOD *ameth,
int (*pkey_security_bits) (const EVP_PKEY
*pk));
void EVP_PKEY_asn1_set_set_priv_key(EVP_PKEY_ASN1_METHOD *ameth,
int (*set_priv_key) (EVP_PKEY *pk,
const unsigned char
*priv,
size_t len));
void EVP_PKEY_asn1_set_set_pub_key(EVP_PKEY_ASN1_METHOD *ameth,
int (*set_pub_key) (EVP_PKEY *pk,
const unsigned char *pub,
size_t len));
void EVP_PKEY_asn1_set_get_priv_key(EVP_PKEY_ASN1_METHOD *ameth,
int (*get_priv_key) (const EVP_PKEY *pk,
unsigned char *priv,
size_t *len));
void EVP_PKEY_asn1_set_get_pub_key(EVP_PKEY_ASN1_METHOD *ameth,
int (*get_pub_key) (const EVP_PKEY *pk,
unsigned char *pub,
size_t *len));
const EVP_PKEY_ASN1_METHOD *EVP_PKEY_get0_asn1(const EVP_PKEY *pkey);
=head1 DESCRIPTION
B<EVP_PKEY_ASN1_METHOD> is a structure which holds a set of ASN.1
conversion, printing and information methods for a specific public key
algorithm.
There are two places where the B<EVP_PKEY_ASN1_METHOD> objects are
stored: one is a built-in array representing the standard methods for
different algorithms, and the other one is a stack of user-defined
application-specific methods, which can be manipulated by using
L<EVP_PKEY_asn1_add0(3)>.
=head2 Methods
The methods are the underlying implementations of a particular public
key algorithm present by the B<EVP_PKEY> object.
int (*pub_decode) (EVP_PKEY *pk, const X509_PUBKEY *pub);
int (*pub_encode) (X509_PUBKEY *pub, const EVP_PKEY *pk);
int (*pub_cmp) (const EVP_PKEY *a, const EVP_PKEY *b);
int (*pub_print) (BIO *out, const EVP_PKEY *pkey, int indent,
ASN1_PCTX *pctx);
The pub_decode() and pub_encode() methods are called to decode /
encode B<X509_PUBKEY> ASN.1 parameters to / from B<pk>.
They MUST return 0 on error, 1 on success.
They're called by L<X509_PUBKEY_get0(3)> and L<X509_PUBKEY_set(3)>.
The pub_cmp() method is called when two public keys are to be
compared.
It MUST return 1 when the keys are equal, 0 otherwise.
It's called by L<EVP_PKEY_eq(3)>.
The pub_print() method is called to print a public key in humanly
readable text to B<out>, indented B<indent> spaces.
It MUST return 0 on error, 1 on success.
It's called by L<EVP_PKEY_print_public(3)>.
int (*priv_decode) (EVP_PKEY *pk, const PKCS8_PRIV_KEY_INFO *p8inf);
int (*priv_encode) (PKCS8_PRIV_KEY_INFO *p8, const EVP_PKEY *pk);
int (*priv_print) (BIO *out, const EVP_PKEY *pkey, int indent,
ASN1_PCTX *pctx);
The priv_decode() and priv_encode() methods are called to decode /
encode B<PKCS8_PRIV_KEY_INFO> form private key to / from B<pk>.
They MUST return 0 on error, 1 on success.
They're called by L<EVP_PKCS82PKEY(3)> and L<EVP_PKEY2PKCS8(3)>.
The priv_print() method is called to print a private key in humanly
readable text to B<out>, indented B<indent> spaces.
It MUST return 0 on error, 1 on success.
It's called by L<EVP_PKEY_print_private(3)>.
int (*pkey_size) (const EVP_PKEY *pk);
int (*pkey_bits) (const EVP_PKEY *pk);
int (*pkey_security_bits) (const EVP_PKEY *pk);
The pkey_size() method returns the key size in bytes.
It's called by L<EVP_PKEY_get_size(3)>.
The pkey_bits() method returns the key size in bits.
It's called by L<EVP_PKEY_get_bits(3)>.
int (*param_decode) (EVP_PKEY *pkey,
const unsigned char **pder, int derlen);
int (*param_encode) (const EVP_PKEY *pkey, unsigned char **pder);
int (*param_missing) (const EVP_PKEY *pk);
int (*param_copy) (EVP_PKEY *to, const EVP_PKEY *from);
int (*param_cmp) (const EVP_PKEY *a, const EVP_PKEY *b);
int (*param_print) (BIO *out, const EVP_PKEY *pkey, int indent,
ASN1_PCTX *pctx);
The param_decode() and param_encode() methods are called to decode /
encode DER formatted parameters to / from B<pk>.
They MUST return 0 on error, 1 on success.
They're called by L<PEM_read_bio_Parameters(3)> and the B<file:>
L<OSSL_STORE_LOADER(3)>.
The param_missing() method returns 0 if a key parameter is missing,
otherwise 1.
It's called by L<EVP_PKEY_missing_parameters(3)>.
The param_copy() method copies key parameters from B<from> to B<to>.
It MUST return 0 on error, 1 on success.
It's called by L<EVP_PKEY_copy_parameters(3)>.
The param_cmp() method compares the parameters of keys B<a> and B<b>.
It MUST return 1 when the keys are equal, 0 when not equal, or a
negative number on error.
It's called by L<EVP_PKEY_parameters_eq(3)>.
The param_print() method prints the private key parameters in humanly
readable text to B<out>, indented B<indent> spaces.
It MUST return 0 on error, 1 on success.
It's called by L<EVP_PKEY_print_params(3)>.
int (*sig_print) (BIO *out,
const X509_ALGOR *sigalg, const ASN1_STRING *sig,
int indent, ASN1_PCTX *pctx);
The sig_print() method prints a signature in humanly readable text to
B<out>, indented B<indent> spaces.
B<sigalg> contains the exact signature algorithm.
If the signature in B<sig> doesn't correspond to what this method
expects, X509_signature_dump() must be used as a last resort.
It MUST return 0 on error, 1 on success.
It's called by L<X509_signature_print(3)>.
void (*pkey_free) (EVP_PKEY *pkey);
The pkey_free() method helps freeing the internals of B<pkey>.
It's called by L<EVP_PKEY_free(3)>, L<EVP_PKEY_set_type(3)>,
L<EVP_PKEY_set_type_str(3)>, and L<EVP_PKEY_assign(3)>.
int (*pkey_ctrl) (EVP_PKEY *pkey, int op, long arg1, void *arg2);
The pkey_ctrl() method adds extra algorithm specific control.
It's called by L<EVP_PKEY_get_default_digest_nid(3)>,
L<EVP_PKEY_set1_encoded_public_key(3)>,
L<EVP_PKEY_get1_encoded_public_key(3)>, L<PKCS7_SIGNER_INFO_set(3)>,
L<PKCS7_RECIP_INFO_set(3)>, ...
int (*old_priv_decode) (EVP_PKEY *pkey,
const unsigned char **pder, int derlen);
int (*old_priv_encode) (const EVP_PKEY *pkey, unsigned char **pder);
The old_priv_decode() and old_priv_encode() methods decode / encode
they private key B<pkey> from / to a DER formatted array.
These are exclusively used to help decoding / encoding older (pre
PKCS#8) PEM formatted encrypted private keys.
old_priv_decode() MUST return 0 on error, 1 on success.
old_priv_encode() MUST the return same kind of values as
i2d_PrivateKey().
They're called by L<d2i_PrivateKey(3)> and L<i2d_PrivateKey(3)>.
int (*item_verify) (EVP_MD_CTX *ctx, const ASN1_ITEM *it, void *asn,
X509_ALGOR *a, ASN1_BIT_STRING *sig, EVP_PKEY *pkey);
int (*item_sign) (EVP_MD_CTX *ctx, const ASN1_ITEM *it, void *asn,
X509_ALGOR *alg1, X509_ALGOR *alg2,
ASN1_BIT_STRING *sig);
The item_sign() and item_verify() methods make it possible to have
algorithm specific signatures and verification of them.
item_sign() MUST return one of:
=over 4
=item <=0
error
=item Z<>1
item_sign() did everything, OpenSSL internals just needs to pass the
signature length back.
=item Z<>2
item_sign() did nothing, OpenSSL internal standard routines are
expected to continue with the default signature production.
=item Z<>3
item_sign() set the algorithm identifier B<algor1> and B<algor2>,
OpenSSL internals should just sign using those algorithms.
=back
item_verify() MUST return one of:
=over 4
=item <=0
error
=item Z<>1
item_sign() did everything, OpenSSL internals just needs to pass the
signature length back.
=item Z<>2
item_sign() did nothing, OpenSSL internal standard routines are
expected to continue with the default signature production.
=back
item_verify() and item_sign() are called by L<ASN1_item_verify(3)> and
L<ASN1_item_sign(3)>, and by extension, L<X509_verify(3)>,
L<X509_REQ_verify(3)>, L<X509_sign(3)>, L<X509_REQ_sign(3)>, ...
int (*siginf_set) (X509_SIG_INFO *siginf, const X509_ALGOR *alg,
const ASN1_STRING *sig);
The siginf_set() method is used to set custom B<X509_SIG_INFO>
parameters.
It MUST return 0 on error, or 1 on success.
It's called as part of L<X509_check_purpose(3)>, L<X509_check_ca(3)>
and L<X509_check_issued(3)>.
int (*pkey_check) (const EVP_PKEY *pk);
int (*pkey_public_check) (const EVP_PKEY *pk);
int (*pkey_param_check) (const EVP_PKEY *pk);
The pkey_check(), pkey_public_check() and pkey_param_check() methods are used
to check the validity of B<pk> for key-pair, public component and parameters,
respectively.
They MUST return 0 for an invalid key, or 1 for a valid key.
They are called by L<EVP_PKEY_check(3)>, L<EVP_PKEY_public_check(3)> and
L<EVP_PKEY_param_check(3)> respectively.
int (*set_priv_key) (EVP_PKEY *pk, const unsigned char *priv, size_t len);
int (*set_pub_key) (EVP_PKEY *pk, const unsigned char *pub, size_t len);
The set_priv_key() and set_pub_key() methods are used to set the raw private and
public key data for an EVP_PKEY. They MUST return 0 on error, or 1 on success.
They are called by L<EVP_PKEY_new_raw_private_key(3)>, and
L<EVP_PKEY_new_raw_public_key(3)> respectively.
size_t (*dirty) (const EVP_PKEY *pk);
void *(*export_to) (const EVP_PKEY *pk, EVP_KEYMGMT *keymgmt);
dirty_cnt() returns the internal key's dirty count.
This can be used to synchronise different copies of the same keys.
The export_to() method exports the key material from the given key to
a provider, through the L<EVP_KEYMGMT(3)> interface, if that provider
supports importing key material.
=head2 Functions
EVP_PKEY_asn1_new() creates and returns a new B<EVP_PKEY_ASN1_METHOD>
object, and associates the given B<id>, B<flags>, B<pem_str> and
B<info>.
B<id> is a NID, B<pem_str> is the PEM type string, B<info> is a
descriptive string.
The following B<flags> are supported:
ASN1_PKEY_SIGPARAM_NULL
If B<ASN1_PKEY_SIGPARAM_NULL> is set, then the signature algorithm
parameters are given the type B<V_ASN1_NULL> by default, otherwise
they will be given the type B<V_ASN1_UNDEF> (i.e. the parameter is
omitted).
See L<X509_ALGOR_set0(3)> for more information.
EVP_PKEY_asn1_copy() copies an B<EVP_PKEY_ASN1_METHOD> object from
B<src> to B<dst>.
This function is not thread safe, it's recommended to only use this
when initializing the application.
EVP_PKEY_asn1_free() frees an existing B<EVP_PKEY_ASN1_METHOD> pointed
-by B<ameth>.
+by B<ameth>. If the argument is NULL, nothing is done.
EVP_PKEY_asn1_add0() adds B<ameth> to the user defined stack of
methods unless another B<EVP_PKEY_ASN1_METHOD> with the same NID is
already there.
This function is not thread safe, it's recommended to only use this
when initializing the application.
EVP_PKEY_asn1_add_alias() creates an alias with the NID B<to> for the
B<EVP_PKEY_ASN1_METHOD> with NID B<from> unless another
B<EVP_PKEY_ASN1_METHOD> with the same NID is already added.
This function is not thread safe, it's recommended to only use this
when initializing the application.
EVP_PKEY_asn1_set_public(), EVP_PKEY_asn1_set_private(),
EVP_PKEY_asn1_set_param(), EVP_PKEY_asn1_set_free(),
EVP_PKEY_asn1_set_ctrl(), EVP_PKEY_asn1_set_item(),
EVP_PKEY_asn1_set_siginf(), EVP_PKEY_asn1_set_check(),
EVP_PKEY_asn1_set_public_check(), EVP_PKEY_asn1_set_param_check(),
EVP_PKEY_asn1_set_security_bits(), EVP_PKEY_asn1_set_set_priv_key(),
EVP_PKEY_asn1_set_set_pub_key(), EVP_PKEY_asn1_set_get_priv_key() and
EVP_PKEY_asn1_set_get_pub_key() set the diverse methods of the given
B<EVP_PKEY_ASN1_METHOD> object.
EVP_PKEY_get0_asn1() finds the B<EVP_PKEY_ASN1_METHOD> associated
with the key B<pkey>.
=head1 RETURN VALUES
EVP_PKEY_asn1_new() returns NULL on error, or a pointer to an
B<EVP_PKEY_ASN1_METHOD> object otherwise.
EVP_PKEY_asn1_add0() and EVP_PKEY_asn1_add_alias() return 0 on error,
or 1 on success.
EVP_PKEY_get0_asn1() returns NULL on error, or a pointer to a constant
B<EVP_PKEY_ASN1_METHOD> object otherwise.
=head1 HISTORY
The signature of the I<pub_decode> functional argument of
EVP_PKEY_asn1_set_public() has changed in OpenSSL 3.0 so its I<pub>
parameter is now constified.
=head1 COPYRIGHT
-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
L<https://www.openssl.org/source/license.html>.
=cut
diff --git a/crypto/openssl/doc/man3/EVP_PKEY_meth_new.pod b/crypto/openssl/doc/man3/EVP_PKEY_meth_new.pod
index db0b09f855fc..1b0adb2913f8 100644
--- a/crypto/openssl/doc/man3/EVP_PKEY_meth_new.pod
+++ b/crypto/openssl/doc/man3/EVP_PKEY_meth_new.pod
@@ -1,466 +1,466 @@
=pod
=head1 NAME
EVP_PKEY_meth_new, EVP_PKEY_meth_free, EVP_PKEY_meth_copy, EVP_PKEY_meth_find,
EVP_PKEY_meth_add0, EVP_PKEY_METHOD,
EVP_PKEY_meth_set_init, EVP_PKEY_meth_set_copy, EVP_PKEY_meth_set_cleanup,
EVP_PKEY_meth_set_paramgen, EVP_PKEY_meth_set_keygen, EVP_PKEY_meth_set_sign,
EVP_PKEY_meth_set_verify, EVP_PKEY_meth_set_verify_recover, EVP_PKEY_meth_set_signctx,
EVP_PKEY_meth_set_verifyctx, EVP_PKEY_meth_set_encrypt, EVP_PKEY_meth_set_decrypt,
EVP_PKEY_meth_set_derive, EVP_PKEY_meth_set_ctrl,
EVP_PKEY_meth_set_digestsign, EVP_PKEY_meth_set_digestverify,
EVP_PKEY_meth_set_check,
EVP_PKEY_meth_set_public_check, EVP_PKEY_meth_set_param_check,
EVP_PKEY_meth_set_digest_custom,
EVP_PKEY_meth_get_init, EVP_PKEY_meth_get_copy, EVP_PKEY_meth_get_cleanup,
EVP_PKEY_meth_get_paramgen, EVP_PKEY_meth_get_keygen, EVP_PKEY_meth_get_sign,
EVP_PKEY_meth_get_verify, EVP_PKEY_meth_get_verify_recover, EVP_PKEY_meth_get_signctx,
EVP_PKEY_meth_get_verifyctx, EVP_PKEY_meth_get_encrypt, EVP_PKEY_meth_get_decrypt,
EVP_PKEY_meth_get_derive, EVP_PKEY_meth_get_ctrl,
EVP_PKEY_meth_get_digestsign, EVP_PKEY_meth_get_digestverify,
EVP_PKEY_meth_get_check,
EVP_PKEY_meth_get_public_check, EVP_PKEY_meth_get_param_check,
EVP_PKEY_meth_get_digest_custom,
EVP_PKEY_meth_remove
- manipulating EVP_PKEY_METHOD structure
=head1 SYNOPSIS
#include <openssl/evp.h>
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)>:
typedef struct evp_pkey_method_st EVP_PKEY_METHOD;
EVP_PKEY_METHOD *EVP_PKEY_meth_new(int id, int flags);
void EVP_PKEY_meth_free(EVP_PKEY_METHOD *pmeth);
void EVP_PKEY_meth_copy(EVP_PKEY_METHOD *dst, const EVP_PKEY_METHOD *src);
const EVP_PKEY_METHOD *EVP_PKEY_meth_find(int type);
int EVP_PKEY_meth_add0(const EVP_PKEY_METHOD *pmeth);
int EVP_PKEY_meth_remove(const EVP_PKEY_METHOD *pmeth);
void EVP_PKEY_meth_set_init(EVP_PKEY_METHOD *pmeth,
int (*init) (EVP_PKEY_CTX *ctx));
void EVP_PKEY_meth_set_copy(EVP_PKEY_METHOD *pmeth,
int (*copy) (EVP_PKEY_CTX *dst,
const EVP_PKEY_CTX *src));
void EVP_PKEY_meth_set_cleanup(EVP_PKEY_METHOD *pmeth,
void (*cleanup) (EVP_PKEY_CTX *ctx));
void EVP_PKEY_meth_set_paramgen(EVP_PKEY_METHOD *pmeth,
int (*paramgen_init) (EVP_PKEY_CTX *ctx),
int (*paramgen) (EVP_PKEY_CTX *ctx,
EVP_PKEY *pkey));
void EVP_PKEY_meth_set_keygen(EVP_PKEY_METHOD *pmeth,
int (*keygen_init) (EVP_PKEY_CTX *ctx),
int (*keygen) (EVP_PKEY_CTX *ctx,
EVP_PKEY *pkey));
void EVP_PKEY_meth_set_sign(EVP_PKEY_METHOD *pmeth,
int (*sign_init) (EVP_PKEY_CTX *ctx),
int (*sign) (EVP_PKEY_CTX *ctx,
unsigned char *sig, size_t *siglen,
const unsigned char *tbs,
size_t tbslen));
void EVP_PKEY_meth_set_verify(EVP_PKEY_METHOD *pmeth,
int (*verify_init) (EVP_PKEY_CTX *ctx),
int (*verify) (EVP_PKEY_CTX *ctx,
const unsigned char *sig,
size_t siglen,
const unsigned char *tbs,
size_t tbslen));
void EVP_PKEY_meth_set_verify_recover(EVP_PKEY_METHOD *pmeth,
int (*verify_recover_init) (EVP_PKEY_CTX
*ctx),
int (*verify_recover) (EVP_PKEY_CTX
*ctx,
unsigned char
*sig,
size_t *siglen,
const unsigned
char *tbs,
size_t tbslen));
void EVP_PKEY_meth_set_signctx(EVP_PKEY_METHOD *pmeth,
int (*signctx_init) (EVP_PKEY_CTX *ctx,
EVP_MD_CTX *mctx),
int (*signctx) (EVP_PKEY_CTX *ctx,
unsigned char *sig,
size_t *siglen,
EVP_MD_CTX *mctx));
void EVP_PKEY_meth_set_verifyctx(EVP_PKEY_METHOD *pmeth,
int (*verifyctx_init) (EVP_PKEY_CTX *ctx,
EVP_MD_CTX *mctx),
int (*verifyctx) (EVP_PKEY_CTX *ctx,
const unsigned char *sig,
int siglen,
EVP_MD_CTX *mctx));
void EVP_PKEY_meth_set_encrypt(EVP_PKEY_METHOD *pmeth,
int (*encrypt_init) (EVP_PKEY_CTX *ctx),
int (*encryptfn) (EVP_PKEY_CTX *ctx,
unsigned char *out,
size_t *outlen,
const unsigned char *in,
size_t inlen));
void EVP_PKEY_meth_set_decrypt(EVP_PKEY_METHOD *pmeth,
int (*decrypt_init) (EVP_PKEY_CTX *ctx),
int (*decrypt) (EVP_PKEY_CTX *ctx,
unsigned char *out,
size_t *outlen,
const unsigned char *in,
size_t inlen));
void EVP_PKEY_meth_set_derive(EVP_PKEY_METHOD *pmeth,
int (*derive_init) (EVP_PKEY_CTX *ctx),
int (*derive) (EVP_PKEY_CTX *ctx,
unsigned char *key,
size_t *keylen));
void EVP_PKEY_meth_set_ctrl(EVP_PKEY_METHOD *pmeth,
int (*ctrl) (EVP_PKEY_CTX *ctx, int type, int p1,
void *p2),
int (*ctrl_str) (EVP_PKEY_CTX *ctx,
const char *type,
const char *value));
void EVP_PKEY_meth_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));
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));
void EVP_PKEY_meth_set_check(EVP_PKEY_METHOD *pmeth,
int (*check) (EVP_PKEY *pkey));
void EVP_PKEY_meth_set_public_check(EVP_PKEY_METHOD *pmeth,
int (*check) (EVP_PKEY *pkey));
void EVP_PKEY_meth_set_param_check(EVP_PKEY_METHOD *pmeth,
int (*check) (EVP_PKEY *pkey));
void EVP_PKEY_meth_set_digest_custom(EVP_PKEY_METHOD *pmeth,
int (*digest_custom) (EVP_PKEY_CTX *ctx,
EVP_MD_CTX *mctx));
void EVP_PKEY_meth_get_init(const EVP_PKEY_METHOD *pmeth,
int (**pinit) (EVP_PKEY_CTX *ctx));
void EVP_PKEY_meth_get_copy(const EVP_PKEY_METHOD *pmeth,
int (**pcopy) (EVP_PKEY_CTX *dst,
EVP_PKEY_CTX *src));
void EVP_PKEY_meth_get_cleanup(const EVP_PKEY_METHOD *pmeth,
void (**pcleanup) (EVP_PKEY_CTX *ctx));
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));
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));
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));
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));
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));
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));
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));
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));
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));
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));
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));
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));
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));
void EVP_PKEY_meth_get_check(const EVP_PKEY_METHOD *pmeth,
int (**pcheck) (EVP_PKEY *pkey));
void EVP_PKEY_meth_get_public_check(const EVP_PKEY_METHOD *pmeth,
int (**pcheck) (EVP_PKEY *pkey));
void EVP_PKEY_meth_get_param_check(const EVP_PKEY_METHOD *pmeth,
int (**pcheck) (EVP_PKEY *pkey));
void EVP_PKEY_meth_get_digest_custom(const EVP_PKEY_METHOD *pmeth,
int (**pdigest_custom) (EVP_PKEY_CTX *ctx,
EVP_MD_CTX *mctx));
=head1 DESCRIPTION
All of the functions described on this page are deprecated.
Applications should instead use the OSSL_PROVIDER APIs.
B<EVP_PKEY_METHOD> is a structure which holds a set of methods for a
specific public key cryptographic algorithm. Those methods are usually
used to perform different jobs, such as generating a key, signing or
verifying, encrypting or decrypting, etc.
There are two places where the B<EVP_PKEY_METHOD> objects are stored: one
is a built-in static array representing the standard methods for different
algorithms, and the other one is a stack of user-defined application-specific
methods, which can be manipulated by using L<EVP_PKEY_meth_add0(3)>.
The B<EVP_PKEY_METHOD> objects are usually referenced by B<EVP_PKEY_CTX>
objects.
=head2 Methods
The methods are the underlying implementations of a particular public key
algorithm present by the B<EVP_PKEY_CTX> object.
int (*init) (EVP_PKEY_CTX *ctx);
int (*copy) (EVP_PKEY_CTX *dst, const EVP_PKEY_CTX *src);
void (*cleanup) (EVP_PKEY_CTX *ctx);
The init() method is called to initialize algorithm-specific data when a new
B<EVP_PKEY_CTX> is created. As opposed to init(), the cleanup() method is called
when an B<EVP_PKEY_CTX> is freed. The copy() method is called when an B<EVP_PKEY_CTX>
is being duplicated. Refer to L<EVP_PKEY_CTX_new(3)>, L<EVP_PKEY_CTX_new_id(3)>,
L<EVP_PKEY_CTX_free(3)> and L<EVP_PKEY_CTX_dup(3)>.
int (*paramgen_init) (EVP_PKEY_CTX *ctx);
int (*paramgen) (EVP_PKEY_CTX *ctx, EVP_PKEY *pkey);
The paramgen_init() and paramgen() methods deal with key parameter generation.
They are called by L<EVP_PKEY_paramgen_init(3)> and L<EVP_PKEY_paramgen(3)> to
handle the parameter generation process.
int (*keygen_init) (EVP_PKEY_CTX *ctx);
int (*keygen) (EVP_PKEY_CTX *ctx, EVP_PKEY *pkey);
The keygen_init() and keygen() methods are used to generate the actual key for
the specified algorithm. They are called by L<EVP_PKEY_keygen_init(3)> and
L<EVP_PKEY_keygen(3)>.
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);
The sign_init() and sign() methods are used to generate the signature of a
piece of data using a private key. They are called by L<EVP_PKEY_sign_init(3)>
and L<EVP_PKEY_sign(3)>.
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);
The verify_init() and verify() methods are used to verify whether a signature is
valid. They are called by L<EVP_PKEY_verify_init(3)> and L<EVP_PKEY_verify(3)>.
int (*verify_recover_init) (EVP_PKEY_CTX *ctx);
int (*verify_recover) (EVP_PKEY_CTX *ctx,
unsigned char *rout, size_t *routlen,
const unsigned char *sig, size_t siglen);
The verify_recover_init() and verify_recover() methods are used to verify a
signature and then recover the digest from the signature (for instance, a
signature that was generated by RSA signing algorithm). They are called by
L<EVP_PKEY_verify_recover_init(3)> and L<EVP_PKEY_verify_recover(3)>.
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);
The signctx_init() and signctx() methods are used to sign a digest present by
a B<EVP_MD_CTX> object. They are called by the EVP_DigestSign functions. See
L<EVP_DigestSignInit(3)> for details.
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);
The verifyctx_init() and verifyctx() methods are used to verify a signature
against the data in a B<EVP_MD_CTX> object. They are called by the various
EVP_DigestVerify functions. See L<EVP_DigestVerifyInit(3)> for details.
int (*encrypt_init) (EVP_PKEY_CTX *ctx);
int (*encrypt) (EVP_PKEY_CTX *ctx, unsigned char *out, size_t *outlen,
const unsigned char *in, size_t inlen);
The encrypt_init() and encrypt() methods are used to encrypt a piece of data.
They are called by L<EVP_PKEY_encrypt_init(3)> and L<EVP_PKEY_encrypt(3)>.
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);
The decrypt_init() and decrypt() methods are used to decrypt a piece of data.
They are called by L<EVP_PKEY_decrypt_init(3)> and L<EVP_PKEY_decrypt(3)>.
int (*derive_init) (EVP_PKEY_CTX *ctx);
int (*derive) (EVP_PKEY_CTX *ctx, unsigned char *key, size_t *keylen);
The derive_init() and derive() methods are used to derive the shared secret
from a public key algorithm (for instance, the DH algorithm). They are called by
L<EVP_PKEY_derive_init(3)> and L<EVP_PKEY_derive(3)>.
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);
The ctrl() and ctrl_str() methods are used to adjust algorithm-specific
settings. See L<EVP_PKEY_CTX_ctrl(3)> and related functions for details.
int (*digestsign) (EVP_MD_CTX *ctx, unsigned char *sig, size_t *siglen,
const unsigned char *tbs, size_t tbslen);
int (*digestverify) (EVP_MD_CTX *ctx, const unsigned char *sig,
size_t siglen, const unsigned char *tbs,
size_t tbslen);
The digestsign() and digestverify() methods are used to generate or verify
a signature in a one-shot mode. They could be called by L<EVP_DigestSign(3)>
and L<EVP_DigestVerify(3)>.
int (*check) (EVP_PKEY *pkey);
int (*public_check) (EVP_PKEY *pkey);
int (*param_check) (EVP_PKEY *pkey);
The check(), public_check() and param_check() methods are used to validate a
key-pair, the public component and parameters respectively for a given B<pkey>.
They could be called by L<EVP_PKEY_check(3)>, L<EVP_PKEY_public_check(3)> and
L<EVP_PKEY_param_check(3)> respectively.
int (*digest_custom) (EVP_PKEY_CTX *ctx, EVP_MD_CTX *mctx);
The digest_custom() method is used to generate customized digest content before
the real message is passed to functions like L<EVP_DigestSignUpdate(3)> or
L<EVP_DigestVerifyInit(3)>. This is usually required by some public key
signature algorithms like SM2 which requires a hashed prefix to the message to
be signed. The digest_custom() function will be called by L<EVP_DigestSignInit(3)>
and L<EVP_DigestVerifyInit(3)>.
=head2 Functions
EVP_PKEY_meth_new() creates and returns a new B<EVP_PKEY_METHOD> object,
and associates the given B<id> and B<flags>. The following flags are
supported:
EVP_PKEY_FLAG_AUTOARGLEN
EVP_PKEY_FLAG_SIGCTX_CUSTOM
If an B<EVP_PKEY_METHOD> is set with the B<EVP_PKEY_FLAG_AUTOARGLEN> flag, the
maximum size of the output buffer will be automatically calculated or checked
in corresponding EVP methods by the EVP framework. Thus the implementations of
these methods don't need to care about handling the case of returning output
buffer size by themselves. For details on the output buffer size, refer to
L<EVP_PKEY_sign(3)>.
The B<EVP_PKEY_FLAG_SIGCTX_CUSTOM> is used to indicate the signctx() method
of an B<EVP_PKEY_METHOD> is always called by the EVP framework while doing a
digest signing operation by calling L<EVP_DigestSignFinal(3)>.
EVP_PKEY_meth_free() frees an existing B<EVP_PKEY_METHOD> pointed by
-B<pmeth>.
+B<pmeth>. If the argument is NULL, nothing is done.
EVP_PKEY_meth_copy() copies an B<EVP_PKEY_METHOD> object from B<src>
to B<dst>.
EVP_PKEY_meth_find() finds an B<EVP_PKEY_METHOD> object with the B<id>.
This function first searches through the user-defined method objects and
then the built-in objects.
EVP_PKEY_meth_add0() adds B<pmeth> to the user defined stack of methods.
EVP_PKEY_meth_remove() removes an B<EVP_PKEY_METHOD> object added by
EVP_PKEY_meth_add0().
The EVP_PKEY_meth_set functions set the corresponding fields of
B<EVP_PKEY_METHOD> structure with the arguments passed.
The EVP_PKEY_meth_get functions get the corresponding fields of
B<EVP_PKEY_METHOD> structure to the arguments provided.
=head1 RETURN VALUES
EVP_PKEY_meth_new() returns a pointer to a new B<EVP_PKEY_METHOD>
object or returns NULL on error.
EVP_PKEY_meth_free() and EVP_PKEY_meth_copy() do not return values.
EVP_PKEY_meth_find() returns a pointer to the found B<EVP_PKEY_METHOD>
object or returns NULL if not found.
EVP_PKEY_meth_add0() returns 1 if method is added successfully or 0
if an error occurred.
EVP_PKEY_meth_remove() returns 1 if method is removed successfully or
0 if an error occurred.
All EVP_PKEY_meth_set and EVP_PKEY_meth_get functions have no return
values. For the 'get' functions, function pointers are returned by
arguments.
=head1 HISTORY
All of these functions were deprecated in OpenSSL 3.0.
The signature of the I<copy> functional argument of EVP_PKEY_meth_set_copy()
has changed in OpenSSL 3.0 so its I<src> parameter is now constified.
=head1 COPYRIGHT
-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
L<https://www.openssl.org/source/license.html>.
=cut
diff --git a/crypto/openssl/doc/man3/EVP_RAND.pod b/crypto/openssl/doc/man3/EVP_RAND.pod
index 11ea807cc330..e5f75010499c 100644
--- a/crypto/openssl/doc/man3/EVP_RAND.pod
+++ b/crypto/openssl/doc/man3/EVP_RAND.pod
@@ -1,416 +1,416 @@
=pod
=head1 NAME
EVP_RAND, EVP_RAND_fetch, EVP_RAND_free, EVP_RAND_up_ref, EVP_RAND_CTX,
EVP_RAND_CTX_new, EVP_RAND_CTX_free, EVP_RAND_instantiate,
EVP_RAND_uninstantiate, EVP_RAND_generate, EVP_RAND_reseed, EVP_RAND_nonce,
EVP_RAND_enable_locking, EVP_RAND_verify_zeroization, EVP_RAND_get_strength,
EVP_RAND_get_state,
EVP_RAND_get0_provider, EVP_RAND_CTX_get0_rand, EVP_RAND_is_a,
EVP_RAND_get0_name, EVP_RAND_names_do_all,
EVP_RAND_get0_description,
EVP_RAND_CTX_get_params,
EVP_RAND_CTX_set_params, EVP_RAND_do_all_provided, EVP_RAND_get_params,
EVP_RAND_gettable_ctx_params, EVP_RAND_settable_ctx_params,
EVP_RAND_CTX_gettable_params, EVP_RAND_CTX_settable_params,
EVP_RAND_gettable_params, EVP_RAND_STATE_UNINITIALISED, EVP_RAND_STATE_READY,
EVP_RAND_STATE_ERROR - EVP RAND routines
=head1 SYNOPSIS
#include <openssl/evp.h>
typedef struct evp_rand_st EVP_RAND;
typedef struct evp_rand_ctx_st EVP_RAND_CTX;
EVP_RAND *EVP_RAND_fetch(OSSL_LIB_CTX *libctx, const char *algorithm,
const char *properties);
int EVP_RAND_up_ref(EVP_RAND *rand);
void EVP_RAND_free(EVP_RAND *rand);
EVP_RAND_CTX *EVP_RAND_CTX_new(EVP_RAND *rand, EVP_RAND_CTX *parent);
void EVP_RAND_CTX_free(EVP_RAND_CTX *ctx);
EVP_RAND *EVP_RAND_CTX_get0_rand(EVP_RAND_CTX *ctx);
int EVP_RAND_get_params(EVP_RAND *rand, OSSL_PARAM params[]);
int EVP_RAND_CTX_get_params(EVP_RAND_CTX *ctx, OSSL_PARAM params[]);
int EVP_RAND_CTX_set_params(EVP_RAND_CTX *ctx, const OSSL_PARAM params[]);
const OSSL_PARAM *EVP_RAND_gettable_params(const EVP_RAND *rand);
const OSSL_PARAM *EVP_RAND_gettable_ctx_params(const EVP_RAND *rand);
const OSSL_PARAM *EVP_RAND_settable_ctx_params(const EVP_RAND *rand);
const OSSL_PARAM *EVP_RAND_CTX_gettable_params(EVP_RAND_CTX *ctx);
const OSSL_PARAM *EVP_RAND_CTX_settable_params(EVP_RAND_CTX *ctx);
const char *EVP_RAND_get0_name(const EVP_RAND *rand);
const char *EVP_RAND_get0_description(const EVP_RAND *rand);
int EVP_RAND_is_a(const EVP_RAND *rand, const char *name);
const OSSL_PROVIDER *EVP_RAND_get0_provider(const EVP_RAND *rand);
void EVP_RAND_do_all_provided(OSSL_LIB_CTX *libctx,
void (*fn)(EVP_RAND *rand, void *arg),
void *arg);
int EVP_RAND_names_do_all(const EVP_RAND *rand,
void (*fn)(const char *name, void *data),
void *data);
int EVP_RAND_instantiate(EVP_RAND_CTX *ctx, unsigned int strength,
int prediction_resistance,
const unsigned char *pstr, size_t pstr_len,
const OSSL_PARAM params[]);
int EVP_RAND_uninstantiate(EVP_RAND_CTX *ctx);
int EVP_RAND_generate(EVP_RAND_CTX *ctx, unsigned char *out, size_t outlen,
unsigned int strength, int prediction_resistance,
const unsigned char *addin, size_t addin_len);
int EVP_RAND_reseed(EVP_RAND_CTX *ctx, int prediction_resistance,
const unsigned char *ent, size_t ent_len,
const unsigned char *addin, size_t addin_len);
int EVP_RAND_nonce(EVP_RAND_CTX *ctx, unsigned char *out, size_t outlen);
int EVP_RAND_enable_locking(EVP_RAND_CTX *ctx);
int EVP_RAND_verify_zeroization(EVP_RAND_CTX *ctx);
unsigned int EVP_RAND_get_strength(EVP_RAND_CTX *ctx);
int EVP_RAND_get_state(EVP_RAND_CTX *ctx);
#define EVP_RAND_STATE_UNINITIALISED 0
#define EVP_RAND_STATE_READY 1
#define EVP_RAND_STATE_ERROR 2
=head1 DESCRIPTION
The EVP RAND routines are a high-level interface to random number generators
both deterministic and not.
If you just want to generate random bytes then you don't need to use
these functions: just call RAND_bytes() or RAND_priv_bytes().
If you want to do more, these calls should be used instead of the older
RAND and RAND_DRBG functions.
After creating a B<EVP_RAND_CTX> for the required algorithm using
EVP_RAND_CTX_new(), inputs to the algorithm are supplied either by
passing them as part of the EVP_RAND_instantiate() call or using calls to
EVP_RAND_CTX_set_params() before calling EVP_RAND_instantiate(). Finally,
call EVP_RAND_generate() to produce cryptographically secure random bytes.
=head2 Types
B<EVP_RAND> is a type that holds the implementation of a RAND.
B<EVP_RAND_CTX> is a context type that holds the algorithm inputs.
B<EVP_RAND_CTX> structures are reference counted.
=head2 Algorithm implementation fetching
EVP_RAND_fetch() fetches an implementation of a RAND I<algorithm>, given
a library context I<libctx> and a set of I<properties>.
See L<crypto(7)/ALGORITHM FETCHING> for further information.
The returned value must eventually be freed with
L<EVP_RAND_free(3)>.
EVP_RAND_up_ref() increments the reference count of an already fetched
RAND.
EVP_RAND_free() frees a fetched algorithm.
NULL is a valid parameter, for which this function is a no-op.
=head2 Context manipulation functions
EVP_RAND_CTX_new() creates a new context for the RAND implementation I<rand>.
If not NULL, I<parent> specifies the seed source for this implementation.
Not all random number generators need to have a seed source specified.
If a parent is required, a NULL I<parent> will utilise the operating
system entropy sources.
It is recommended to minimise the number of random number generators that
rely on the operating system for their randomness because this is often scarce.
EVP_RAND_CTX_free() frees up the context I<ctx>. If I<ctx> is NULL, nothing
is done.
EVP_RAND_CTX_get0_rand() returns the B<EVP_RAND> associated with the context
I<ctx>.
=head2 Random Number Generator Functions
EVP_RAND_instantiate() processes any parameters in I<params> and
then instantiates the RAND I<ctx> with a minimum security strength
of <strength> and personalisation string I<pstr> of length <pstr_len>.
If I<prediction_resistance> is specified, fresh entropy from a live source
will be sought. This call operates as per NIST SP 800-90A and SP 800-90C.
EVP_RAND_uninstantiate() uninstantiates the RAND I<ctx> as per
NIST SP 800-90A and SP 800-90C. Subsequent to this call, the RAND cannot
be used to generate bytes. It can only be freed or instantiated again.
EVP_RAND_generate() produces random bytes from the RAND I<ctx> with the
additional input I<addin> of length I<addin_len>. The bytes
produced will meet the security I<strength>.
If I<prediction_resistance> is specified, fresh entropy from a live source
will be sought. This call operates as per NIST SP 800-90A and SP 800-90C.
EVP_RAND_reseed() reseeds the RAND with new entropy.
Entropy I<ent> of length I<ent_len> bytes can be supplied as can additional
input I<addin> of length I<addin_len> bytes. In the FIPS provider, both are
treated as additional input as per NIST SP-800-90Ar1, Sections 9.1 and 9.2.
Additional seed material is also drawn from the RAND's parent or the
operating system. If I<prediction_resistance> is specified, fresh entropy
from a live source will be sought. This call operates as per NIST SP 800-90A
and SP 800-90C.
EVP_RAND_nonce() creates a nonce in I<out> of maximum length I<outlen>
bytes from the RAND I<ctx>. The function returns the length of the generated
nonce. If I<out> is NULL, the length is still returned but no generation
takes place. This allows a caller to dynamically allocate a buffer of the
appropriate size.
EVP_RAND_enable_locking() enables locking for the RAND I<ctx> and all of
its parents. After this I<ctx> will operate in a thread safe manner, albeit
more slowly. This function is not itself thread safe if called with the same
I<ctx> from multiple threads. Typically locking should be enabled before a
I<ctx> is shared across multiple threads.
EVP_RAND_get_params() retrieves details about the implementation
I<rand>.
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_RAND_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_RAND_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_RAND_gettable_params() returns an L<OSSL_PARAM(3)> array that describes
the retrievable and settable parameters. EVP_RAND_gettable_params() returns
parameters that can be used with EVP_RAND_get_params().
EVP_RAND_gettable_ctx_params() and EVP_RAND_CTX_gettable_params() return
constant L<OSSL_PARAM(3)> arrays that describe the retrievable parameters that
can be used with EVP_RAND_CTX_get_params(). EVP_RAND_gettable_ctx_params()
returns the parameters that can be retrieved from the algorithm, whereas
EVP_RAND_CTX_gettable_params() returns the parameters that can be retrieved
in the context's current state.
EVP_RAND_settable_ctx_params() and EVP_RAND_CTX_settable_params() return
constant L<OSSL_PARAM(3)> arrays that describe the settable parameters that
can be used with EVP_RAND_CTX_set_params(). EVP_RAND_settable_ctx_params()
returns the parameters that can be retrieved from the algorithm, whereas
EVP_RAND_CTX_settable_params() returns the parameters that can be retrieved
in the context's current state.
=head2 Information functions
EVP_RAND_get_strength() returns the security strength of the RAND I<ctx>.
EVP_RAND_get_state() returns the current state of the RAND I<ctx>.
States defined by the OpenSSL RNGs are:
=over 4
=item *
EVP_RAND_STATE_UNINITIALISED: this RNG is currently uninitialised.
The instantiate call will change this to the ready state.
=item *
EVP_RAND_STATE_READY: this RNG is currently ready to generate output.
=item *
EVP_RAND_STATE_ERROR: this RNG is in an error state.
=back
EVP_RAND_is_a() returns 1 if I<rand> is an implementation of an
algorithm that's identifiable with I<name>, otherwise 0.
EVP_RAND_get0_provider() returns the provider that holds the implementation
of the given I<rand>.
EVP_RAND_do_all_provided() traverses all RAND 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_RAND_get0_name() returns the canonical name of I<rand>.
EVP_RAND_names_do_all() traverses all names for I<rand>, and calls
I<fn> with each name and I<data>.
EVP_RAND_get0_description() returns a description of the rand, meant for
display and human consumption. The description is at the discretion of
the rand implementation.
EVP_RAND_verify_zeroization() confirms if the internal DRBG state is
currently zeroed. This is used by the FIPS provider to support the mandatory
self tests.
=head1 PARAMETERS
The standard parameter names are:
=over 4
=item "state" (B<OSSL_RAND_PARAM_STATE>) <integer>
Returns the state of the random number generator.
=item "strength" (B<OSSL_RAND_PARAM_STRENGTH>) <unsigned integer>
Returns the bit strength of the random number generator.
=back
For rands that are also deterministic random bit generators (DRBGs), these
additional parameters are recognised. Not all
parameters are relevant to, or are understood by all DRBG rands:
=over 4
=item "reseed_requests" (B<OSSL_DRBG_PARAM_RESEED_REQUESTS>) <unsigned integer>
Reads or set the number of generate requests before reseeding the
associated RAND ctx.
=item "reseed_time_interval" (B<OSSL_DRBG_PARAM_RESEED_TIME_INTERVAL>) <integer>
Reads or set the number of elapsed seconds before reseeding the
associated RAND ctx.
-=item "max_request" (B<OSSL_DRBG_PARAM_RESEED_REQUESTS>) <unsigned integer>
+=item "max_request" (B<OSSL_RAND_PARAM_MAX_REQUEST>) <unsigned integer>
Specifies the maximum number of bytes that can be generated in a single
call to OSSL_FUNC_rand_generate.
=item "min_entropylen" (B<OSSL_DRBG_PARAM_MIN_ENTROPYLEN>) <unsigned integer>
=item "max_entropylen" (B<OSSL_DRBG_PARAM_MAX_ENTROPYLEN>) <unsigned integer>
Specify the minimum and maximum number of bytes of random material that
can be used to seed the DRBG.
=item "min_noncelen" (B<OSSL_DRBG_PARAM_MIN_NONCELEN>) <unsigned integer>
=item "max_noncelen" (B<OSSL_DRBG_PARAM_MAX_NONCELEN>) <unsigned integer>
Specify the minimum and maximum number of bytes of nonce that can be used to
seed the DRBG.
=item "max_perslen" (B<OSSL_DRBG_PARAM_MAX_PERSLEN>) <unsigned integer>
=item "max_adinlen" (B<OSSL_DRBG_PARAM_MAX_ADINLEN>) <unsigned integer>
Specify the minimum and maximum number of bytes of personalisation string
that can be used with the DRBG.
=item "reseed_counter" (B<OSSL_DRBG_PARAM_RESEED_COUNTER>) <unsigned integer>
Specifies the number of times the DRBG has been seeded or reseeded.
=item "properties" (B<OSSL_RAND_PARAM_PROPERTIES>) <UTF8 string>
=item "mac" (B<OSSL_RAND_PARAM_MAC>) <UTF8 string>
=item "digest" (B<OSSL_RAND_PARAM_DIGEST>) <UTF8 string>
=item "cipher" (B<OSSL_RAND_PARAM_CIPHER>) <UTF8 string>
For RAND 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 in the case of B<OSSL_RAND_PARAM_PROPERTIES>.
=back
=head1 NOTES
The use of a nonzero value for the I<prediction_resistance> argument to
EVP_RAND_instantiate(), EVP_RAND_generate() or EVP_RAND_reseed() should
be used sparingly. In the default setup, this will cause all public and
private DRBGs to be reseeded on next use. Since, by default, public and
private DRBGs are allocated on a per thread basis, this can result in
significant overhead for highly multi-threaded applications. For normal
use-cases, the default "reseed_requests" and "reseed_time_interval"
thresholds ensure sufficient prediction resistance over time and you
can reduce those values if you think they are too high. Explicitly
requesting prediction resistance is intended for more special use-cases
like generating long-term secrets.
An B<EVP_RAND_CTX> needs to have locking enabled if it acts as the parent of
more than one child and the children can be accessed concurrently. This must
be done by explicitly calling EVP_RAND_enable_locking().
The RAND life-cycle is described in L<life_cycle-rand(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 RETURN VALUES
EVP_RAND_fetch() returns a pointer to a newly fetched B<EVP_RAND>, or
NULL if allocation failed.
EVP_RAND_get0_provider() returns a pointer to the provider for the RAND, or
NULL on error.
EVP_RAND_CTX_get0_rand() returns a pointer to the B<EVP_RAND> associated
with the context.
EVP_RAND_get0_name() returns the name of the random number generation
algorithm.
EVP_RAND_up_ref() returns 1 on success, 0 on error.
EVP_RAND_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.
EVP_RAND_CTX_new() returns either the newly allocated
B<EVP_RAND_CTX> structure or NULL if an error occurred.
EVP_RAND_CTX_free() does not return a value.
EVP_RAND_nonce() returns the length of the nonce.
EVP_RAND_get_strength() returns the strength of the random number generator
in bits.
EVP_RAND_gettable_params(), EVP_RAND_gettable_ctx_params() and
EVP_RAND_settable_ctx_params() return an array of OSSL_PARAMs.
EVP_RAND_verify_zeroization() returns 1 if the internal DRBG state is
currently zeroed, and 0 if not.
The remaining functions return 1 for success and 0 or a negative value for
failure.
=head1 SEE ALSO
L<RAND_bytes(3)>,
L<EVP_RAND-CTR-DRBG(7)>,
L<EVP_RAND-HASH-DRBG(7)>,
L<EVP_RAND-HMAC-DRBG(7)>,
L<EVP_RAND-TEST-RAND(7)>,
L<provider-rand(7)>,
L<life_cycle-rand(7)>
=head1 HISTORY
This functionality was added to OpenSSL 3.0.
=head1 COPYRIGHT
-Copyright 2020-2023 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_SIGNATURE.pod b/crypto/openssl/doc/man3/EVP_SIGNATURE.pod
index 1f534ef33810..cf476d145315 100644
--- a/crypto/openssl/doc/man3/EVP_SIGNATURE.pod
+++ b/crypto/openssl/doc/man3/EVP_SIGNATURE.pod
@@ -1,116 +1,116 @@
=pod
=head1 NAME
EVP_SIGNATURE,
EVP_SIGNATURE_fetch, EVP_SIGNATURE_free, EVP_SIGNATURE_up_ref,
EVP_SIGNATURE_is_a, EVP_SIGNATURE_get0_provider,
EVP_SIGNATURE_do_all_provided, EVP_SIGNATURE_names_do_all,
EVP_SIGNATURE_get0_name, EVP_SIGNATURE_get0_description,
EVP_SIGNATURE_gettable_ctx_params, EVP_SIGNATURE_settable_ctx_params
- Functions to manage EVP_SIGNATURE algorithm objects
=head1 SYNOPSIS
#include <openssl/evp.h>
typedef struct evp_signature_st EVP_SIGNATURE;
EVP_SIGNATURE *EVP_SIGNATURE_fetch(OSSL_LIB_CTX *ctx, const char *algorithm,
const char *properties);
void EVP_SIGNATURE_free(EVP_SIGNATURE *signature);
int EVP_SIGNATURE_up_ref(EVP_SIGNATURE *signature);
const char *EVP_SIGNATURE_get0_name(const EVP_SIGNATURE *signature);
int EVP_SIGNATURE_is_a(const EVP_SIGNATURE *signature, const char *name);
OSSL_PROVIDER *EVP_SIGNATURE_get0_provider(const EVP_SIGNATURE *signature);
void EVP_SIGNATURE_do_all_provided(OSSL_LIB_CTX *libctx,
void (*fn)(EVP_SIGNATURE *signature,
void *arg),
void *arg);
int EVP_SIGNATURE_names_do_all(const EVP_SIGNATURE *signature,
void (*fn)(const char *name, void *data),
void *data);
const char *EVP_SIGNATURE_get0_name(const EVP_SIGNATURE *signature);
const char *EVP_SIGNATURE_get0_description(const EVP_SIGNATURE *signature);
const OSSL_PARAM *EVP_SIGNATURE_gettable_ctx_params(const EVP_SIGNATURE *sig);
const OSSL_PARAM *EVP_SIGNATURE_settable_ctx_params(const EVP_SIGNATURE *sig);
=head1 DESCRIPTION
EVP_SIGNATURE_fetch() fetches the implementation for the given
B<algorithm> from any provider offering it, within the criteria given
by the B<properties>.
The algorithm will be one offering functions for performing signature related
tasks such as signing and verifying.
See L<crypto(7)/ALGORITHM FETCHING> for further information.
The returned value must eventually be freed with EVP_SIGNATURE_free().
EVP_SIGNATURE_free() decrements the reference count for the B<EVP_SIGNATURE>
structure. Typically this structure will have been obtained from an earlier call
to EVP_SIGNATURE_fetch(). If the reference count drops to 0 then the
-structure is freed.
+structure is freed. If the argument is NULL, nothing is done.
EVP_SIGNATURE_up_ref() increments the reference count for an B<EVP_SIGNATURE>
structure.
EVP_SIGNATURE_is_a() returns 1 if I<signature> is an implementation of an
algorithm that's identifiable with I<name>, otherwise 0.
EVP_SIGNATURE_get0_provider() returns the provider that I<signature> was
fetched from.
EVP_SIGNATURE_do_all_provided() traverses all SIGNATURE 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_SIGNATURE_get0_name() returns the algorithm name from the provided
implementation for the given I<signature>. Note that the I<signature> may have
multiple synonyms associated with it. In this case the first name from the
algorithm definition is returned. Ownership of the returned string is retained
by the I<signature> object and should not be freed by the caller.
EVP_SIGNATURE_names_do_all() traverses all names for I<signature>, and calls
I<fn> with each name and I<data>.
EVP_SIGNATURE_get0_description() returns a description of the I<signature>,
meant for display and human consumption. The description is at the
discretion of the I<signature> implementation.
EVP_SIGNATURE_gettable_ctx_params() and EVP_SIGNATURE_settable_ctx_params()
return a constant L<OSSL_PARAM(3)> array that describes the names and types of key
parameters that can be retrieved or set by a signature algorithm using
L<EVP_PKEY_CTX_get_params(3)> and L<EVP_PKEY_CTX_set_params(3)>.
=head1 RETURN VALUES
EVP_SIGNATURE_fetch() returns a pointer to an B<EVP_SIGNATURE> for success
or B<NULL> for failure.
EVP_SIGNATURE_up_ref() returns 1 for success or 0 otherwise.
EVP_SIGNATURE_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.
EVP_SIGNATURE_gettable_ctx_params() and EVP_SIGNATURE_settable_ctx_params()
return a constant L<OSSL_PARAM(3)> array or NULL on error.
=head1 SEE ALSO
L<crypto(7)/ALGORITHM FETCHING>, L<OSSL_PROVIDER(3)>
=head1 HISTORY
The functions described here were 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/HMAC.pod b/crypto/openssl/doc/man3/HMAC.pod
index 87a567242f60..ebe69d2db9d3 100644
--- a/crypto/openssl/doc/man3/HMAC.pod
+++ b/crypto/openssl/doc/man3/HMAC.pod
@@ -1,173 +1,173 @@
=pod
=head1 NAME
HMAC,
HMAC_CTX_new,
HMAC_CTX_reset,
HMAC_CTX_free,
HMAC_Init,
HMAC_Init_ex,
HMAC_Update,
HMAC_Final,
HMAC_CTX_copy,
HMAC_CTX_set_flags,
HMAC_CTX_get_md,
HMAC_size
- HMAC message authentication code
=head1 SYNOPSIS
#include <openssl/hmac.h>
unsigned char *HMAC(const EVP_MD *evp_md, const void *key, int key_len,
const unsigned char *data, size_t data_len,
unsigned char *md, unsigned int *md_len);
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)>:
HMAC_CTX *HMAC_CTX_new(void);
int HMAC_CTX_reset(HMAC_CTX *ctx);
int HMAC_Init_ex(HMAC_CTX *ctx, const void *key, int key_len,
const EVP_MD *md, ENGINE *impl);
int HMAC_Update(HMAC_CTX *ctx, const unsigned char *data, size_t len);
int HMAC_Final(HMAC_CTX *ctx, unsigned char *md, unsigned int *len);
void HMAC_CTX_free(HMAC_CTX *ctx);
int HMAC_CTX_copy(HMAC_CTX *dctx, HMAC_CTX *sctx);
void HMAC_CTX_set_flags(HMAC_CTX *ctx, unsigned long flags);
const EVP_MD *HMAC_CTX_get_md(const HMAC_CTX *ctx);
size_t HMAC_size(const HMAC_CTX *e);
The following function has been deprecated since OpenSSL 1.1.0, and can be
hidden entirely by defining B<OPENSSL_API_COMPAT> with a suitable version value,
see L<openssl_user_macros(7)>:
int HMAC_Init(HMAC_CTX *ctx, const void *key, int key_len,
const EVP_MD *md);
=head1 DESCRIPTION
HMAC is a MAC (message authentication code), i.e. a keyed hash
function used for message authentication, which is based on a hash
function.
HMAC() computes the message authentication code of the I<data_len> bytes at
I<data> using the hash function I<evp_md> and the key I<key> which is
I<key_len> bytes long. The I<key> may also be NULL with I<key_len> being 0.
It places the result in I<md> (which must have space for the output of
the hash function, which is no more than B<EVP_MAX_MD_SIZE> bytes).
If I<md> is NULL, the digest is placed in a static array. The size of
the output is placed in I<md_len>, unless it is NULL. Note: passing a NULL
value for I<md> to use the static array is not thread safe.
I<evp_md> is a message digest such as EVP_sha1(), EVP_ripemd160() etc.
HMAC does not support variable output length digests such as EVP_shake128() and
EVP_shake256().
HMAC() uses the default B<OSSL_LIB_CTX>.
Use L<EVP_Q_mac(3)> instead if a library context is required.
All of the functions described below are deprecated.
Applications should instead use 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 'quick' single-shot MAC function L<EVP_Q_mac(3)>.
HMAC_CTX_new() creates a new HMAC_CTX in heap memory.
HMAC_CTX_reset() clears an existing B<HMAC_CTX> and associated
resources, making it suitable for new computations as if it was newly
created with HMAC_CTX_new().
HMAC_CTX_free() erases the key and other data from the B<HMAC_CTX>,
releases any associated resources and finally frees the B<HMAC_CTX>
-itself.
+itself. If the argument is NULL, nothing is done.
The following functions may be used if the message is not completely
stored in memory:
HMAC_Init_ex() initializes or reuses a B<HMAC_CTX> structure to use the hash
function I<evp_md> and key I<key>. If both are NULL, or if I<key> is NULL
and I<evp_md> is the same as the previous call, then the
existing key is
reused. I<ctx> must have been created with HMAC_CTX_new() before the first use
of an B<HMAC_CTX> in this function.
If HMAC_Init_ex() is called with I<key> NULL and I<evp_md> is not the
same as the previous digest used by I<ctx> then an error is returned
because reuse of an existing key with a different digest is not supported.
HMAC_Init() initializes a B<HMAC_CTX> structure to use the hash
function I<evp_md> and the key I<key> which is I<key_len> bytes
long.
HMAC_Update() can be called repeatedly with chunks of the message to
be authenticated (I<len> bytes at I<data>).
HMAC_Final() places the message authentication code in I<md>, which
must have space for the hash function output.
HMAC_CTX_copy() copies all of the internal state from I<sctx> into I<dctx>.
HMAC_CTX_set_flags() applies the specified flags to the internal EVP_MD_CTXs.
These flags have the same meaning as for L<EVP_MD_CTX_set_flags(3)>.
HMAC_CTX_get_md() returns the EVP_MD that has previously been set for the
supplied HMAC_CTX.
HMAC_size() returns the length in bytes of the underlying hash function output.
=head1 RETURN VALUES
HMAC() returns a pointer to the message authentication code or NULL if
an error occurred.
HMAC_CTX_new() returns a pointer to a new B<HMAC_CTX> on success or
NULL if an error occurred.
HMAC_CTX_reset(), HMAC_Init_ex(), HMAC_Update(), HMAC_Final() and
HMAC_CTX_copy() return 1 for success or 0 if an error occurred.
HMAC_CTX_get_md() return the EVP_MD previously set for the supplied HMAC_CTX or
NULL if no EVP_MD has been set.
HMAC_size() returns the length in bytes of the underlying hash function output
or zero on error.
=head1 CONFORMING TO
RFC 2104
=head1 SEE ALSO
L<SHA1(3)>, EVP_Q_mac(3), L<evp(7)>
=head1 HISTORY
All functions except for HMAC() were deprecated in OpenSSL 3.0.
HMAC_CTX_init() was replaced with HMAC_CTX_reset() in OpenSSL 1.1.0.
HMAC_CTX_cleanup() existed in OpenSSL before version 1.1.0.
HMAC_CTX_new(), HMAC_CTX_free() and HMAC_CTX_get_md() are new in OpenSSL 1.1.0.
HMAC_Init_ex(), HMAC_Update() and HMAC_Final() did not return values in
OpenSSL before version 1.0.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/man3/MD5.pod b/crypto/openssl/doc/man3/MD5.pod
index 2e01fe8193dd..99bf82116015 100644
--- a/crypto/openssl/doc/man3/MD5.pod
+++ b/crypto/openssl/doc/man3/MD5.pod
@@ -1,115 +1,114 @@
=pod
=head1 NAME
MD2, MD4, MD5, MD2_Init, MD2_Update, MD2_Final, MD4_Init, MD4_Update,
MD4_Final, MD5_Init, MD5_Update, MD5_Final - MD2, MD4, and MD5 hash functions
=head1 SYNOPSIS
- #include <openssl/md2.h>
-
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)>:
+ #include <openssl/md2.h>
+
unsigned char *MD2(const unsigned char *d, unsigned long n, unsigned char *md);
int MD2_Init(MD2_CTX *c);
int MD2_Update(MD2_CTX *c, const unsigned char *data, unsigned long len);
int MD2_Final(unsigned char *md, MD2_CTX *c);
- #include <openssl/md4.h>
-
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)>:
+ #include <openssl/md4.h>
+
unsigned char *MD4(const unsigned char *d, unsigned long n, unsigned char *md);
int MD4_Init(MD4_CTX *c);
int MD4_Update(MD4_CTX *c, const void *data, unsigned long len);
int MD4_Final(unsigned char *md, MD4_CTX *c);
-
- #include <openssl/md5.h>
-
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)>:
+ #include <openssl/md5.h>
+
unsigned char *MD5(const unsigned char *d, unsigned long n, unsigned char *md);
int MD5_Init(MD5_CTX *c);
int MD5_Update(MD5_CTX *c, const void *data, unsigned long len);
int MD5_Final(unsigned char *md, MD5_CTX *c);
=head1 DESCRIPTION
All of the functions described on this page are deprecated.
Applications should instead use L<EVP_DigestInit_ex(3)>, L<EVP_DigestUpdate(3)>
and L<EVP_DigestFinal_ex(3)>.
MD2, MD4, and MD5 are cryptographic hash functions with a 128 bit output.
MD2(), MD4(), and MD5() compute the MD2, MD4, and MD5 message digest
of the B<n> bytes at B<d> and place it in B<md> (which must have space
for MD2_DIGEST_LENGTH == MD4_DIGEST_LENGTH == MD5_DIGEST_LENGTH == 16
bytes of output). If B<md> is NULL, the digest is placed in a static
array.
The following functions may be used if the message is not completely
stored in memory:
MD2_Init() initializes a B<MD2_CTX> structure.
MD2_Update() can be called repeatedly with chunks of the message to
be hashed (B<len> bytes at B<data>).
MD2_Final() places the message digest in B<md>, which must have space
for MD2_DIGEST_LENGTH == 16 bytes of output, and erases the B<MD2_CTX>.
MD4_Init(), MD4_Update(), MD4_Final(), MD5_Init(), MD5_Update(), and
MD5_Final() are analogous using an B<MD4_CTX> and B<MD5_CTX> structure.
Applications should use the higher level functions
L<EVP_DigestInit(3)>
etc. instead of calling the hash functions directly.
=head1 NOTE
MD2, MD4, and MD5 are recommended only for compatibility with existing
applications. In new applications, hashes from the SHA-2 or SHA-3 family
should be preferred.
=head1 RETURN VALUES
MD2(), MD4(), and MD5() return pointers to the hash value.
MD2_Init(), MD2_Update(), MD2_Final(), MD4_Init(), MD4_Update(),
MD4_Final(), MD5_Init(), MD5_Update(), and MD5_Final() return 1 for
success, 0 otherwise.
=head1 CONFORMING TO
RFC 1319, RFC 1320, RFC 1321
=head1 SEE ALSO
L<EVP_DigestInit(3)>, L<EVP_MD-SHA2(7)>, L<EVP_MD-SHA3(7)>
=head1 HISTORY
All of these functions 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/NCONF_new_ex.pod b/crypto/openssl/doc/man3/NCONF_new_ex.pod
index 6861fb198c10..d088ab2fed29 100644
--- a/crypto/openssl/doc/man3/NCONF_new_ex.pod
+++ b/crypto/openssl/doc/man3/NCONF_new_ex.pod
@@ -1,84 +1,84 @@
=pod
=head1 NAME
NCONF_new_ex, NCONF_new, NCONF_free, NCONF_default, NCONF_load,
NCONF_get0_libctx, NCONF_get_section, NCONF_get_section_names
- functionality to Load and parse configuration files manually
=head1 SYNOPSIS
#include <openssl/conf.h>
typedef struct {
char *section;
char *name;
char *value;
} CONF_VALUE;
CONF *NCONF_new_ex(OSSL_LIB_CTX *libctx, CONF_METHOD *meth);
CONF *NCONF_new(CONF_METHOD *meth);
void NCONF_free(CONF *conf);
CONF_METHOD *NCONF_default(void);
int NCONF_load(CONF *conf, const char *file, long *eline);
OSSL_LIB_CTX *NCONF_get0_libctx(const CONF *conf);
STACK_OF(CONF_VALUE) *NCONF_get_section(const CONF *conf, const char *name);
STACK_OF(OPENSSL_CSTRING) *NCONF_get_section_names(const CONF *conf);
=head1 DESCRIPTION
NCONF_new_ex() creates a new CONF object in heap memory and assigns to
it a context I<libctx> that can be used during loading. If the method table
I<meth> is set to NULL then the default value of NCONF_default() is used.
NCONF_new() is similar to NCONF_new_ex() but sets the I<libctx> to NULL.
NCONF_free() frees the data associated with I<conf> and then frees the I<conf>
-object.
+object. If the argument is NULL, nothing is done.
NCONF_load() parses the file named I<filename> and adds the values found to
I<conf>. If an error occurs I<file> and I<eline> list the file and line that
the load failed on if they are not NULL.
NCONF_default() gets the default method table for processing a configuration file.
NCONF_get0_libctx() gets the library context associated with the I<conf>
parameter.
NCONF_get_section_names() gets the names of the sections associated with
the I<conf> as B<STACK_OF(OPENSSL_CSTRING)> strings. The individual strings
are associated with the I<conf> and will be invalid after I<conf> is
freed. The returned stack must be freed with sk_OPENSSL_CSTRING_free().
NCONF_get_section() gets the config values associated with the I<conf> from
the config section I<name> as B<STACK_OF(CONF_VALUE)> structures. The returned
stack is associated with the I<conf> and will be invalid after I<conf>
is freed. It must not be freed by the caller.
=head1 RETURN VALUES
NCONF_load() returns 1 on success or 0 on error.
NCONF_new_ex() and NCONF_new() return a newly created I<CONF> object
or NULL if an error occurs.
=head1 SEE ALSO
L<CONF_modules_load_file(3)>,
=head1 HISTORY
NCONF_new_ex(), NCONF_get0_libctx(), and NCONF_get_section_names() 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/OCSP_REQUEST_new.pod b/crypto/openssl/doc/man3/OCSP_REQUEST_new.pod
index e34e591fe01b..3f171e822971 100644
--- a/crypto/openssl/doc/man3/OCSP_REQUEST_new.pod
+++ b/crypto/openssl/doc/man3/OCSP_REQUEST_new.pod
@@ -1,118 +1,119 @@
=pod
=head1 NAME
OCSP_REQUEST_new, OCSP_REQUEST_free, OCSP_request_add0_id, OCSP_request_sign,
OCSP_request_add1_cert, OCSP_request_onereq_count,
OCSP_request_onereq_get0 - OCSP request functions
=head1 SYNOPSIS
#include <openssl/ocsp.h>
OCSP_REQUEST *OCSP_REQUEST_new(void);
void OCSP_REQUEST_free(OCSP_REQUEST *req);
OCSP_ONEREQ *OCSP_request_add0_id(OCSP_REQUEST *req, OCSP_CERTID *cid);
int OCSP_request_sign(OCSP_REQUEST *req,
X509 *signer, EVP_PKEY *key, const EVP_MD *dgst,
STACK_OF(X509) *certs, unsigned long flags);
int OCSP_request_add1_cert(OCSP_REQUEST *req, X509 *cert);
int OCSP_request_onereq_count(OCSP_REQUEST *req);
OCSP_ONEREQ *OCSP_request_onereq_get0(OCSP_REQUEST *req, int i);
=head1 DESCRIPTION
OCSP_REQUEST_new() allocates and returns an empty B<OCSP_REQUEST> structure.
OCSP_REQUEST_free() frees up the request structure B<req>.
+If the argument is NULL, nothing is done.
OCSP_request_add0_id() adds certificate ID B<cid> to B<req>. It returns
the B<OCSP_ONEREQ> structure added so an application can add additional
extensions to the request. The B<id> parameter B<MUST NOT> be freed up after
the operation.
OCSP_request_sign() signs OCSP request B<req> using certificate
B<signer>, private key B<key>, digest B<dgst> and additional certificates
B<certs>. If the B<flags> option B<OCSP_NOCERTS> is set then no certificates
will be included in the request.
OCSP_request_add1_cert() adds certificate B<cert> to request B<req>. The
application is responsible for freeing up B<cert> after use.
OCSP_request_onereq_count() returns the total number of B<OCSP_ONEREQ>
structures in B<req>.
OCSP_request_onereq_get0() returns an internal pointer to the B<OCSP_ONEREQ>
contained in B<req> of index B<i>. The index value B<i> runs from 0 to
OCSP_request_onereq_count(req) - 1.
=head1 RETURN VALUES
OCSP_REQUEST_new() returns an empty B<OCSP_REQUEST> structure or B<NULL> if
an error occurred.
OCSP_request_add0_id() returns the B<OCSP_ONEREQ> structure containing B<cid>
or B<NULL> if an error occurred.
OCSP_request_sign() and OCSP_request_add1_cert() return 1 for success and 0
for failure.
OCSP_request_onereq_count() returns the total number of B<OCSP_ONEREQ>
structures in B<req> and -1 on error.
OCSP_request_onereq_get0() returns a pointer to an B<OCSP_ONEREQ> structure
or B<NULL> if the index value is out or range.
=head1 NOTES
An OCSP request structure contains one or more B<OCSP_ONEREQ> structures
corresponding to each certificate.
OCSP_request_onereq_count() and OCSP_request_onereq_get0() are mainly used by
OCSP responders.
=head1 EXAMPLES
Create an B<OCSP_REQUEST> structure for certificate B<cert> with issuer
B<issuer>:
OCSP_REQUEST *req;
OCSP_ID *cid;
req = OCSP_REQUEST_new();
if (req == NULL)
/* error */
cid = OCSP_cert_to_id(EVP_sha1(), cert, issuer);
if (cid == NULL)
/* error */
if (OCSP_REQUEST_add0_id(req, cid) == NULL)
/* error */
/* Do something with req, e.g. query responder */
OCSP_REQUEST_free(req);
=head1 SEE ALSO
L<crypto(7)>,
L<OCSP_cert_to_id(3)>,
L<OCSP_request_add1_nonce(3)>,
L<OCSP_resp_find_status(3)>,
L<OCSP_response_status(3)>,
L<OCSP_sendreq_new(3)>
=head1 COPYRIGHT
-Copyright 2015-2016 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
L<https://www.openssl.org/source/license.html>.
=cut
diff --git a/crypto/openssl/doc/man3/OCSP_cert_to_id.pod b/crypto/openssl/doc/man3/OCSP_cert_to_id.pod
index 298527f6bb25..e0fbdfa9eacb 100644
--- a/crypto/openssl/doc/man3/OCSP_cert_to_id.pod
+++ b/crypto/openssl/doc/man3/OCSP_cert_to_id.pod
@@ -1,89 +1,90 @@
=pod
=head1 NAME
OCSP_cert_to_id, OCSP_cert_id_new, OCSP_CERTID_free, OCSP_id_issuer_cmp,
OCSP_id_cmp, OCSP_id_get0_info - OCSP certificate ID utility functions
=head1 SYNOPSIS
#include <openssl/ocsp.h>
OCSP_CERTID *OCSP_cert_to_id(const EVP_MD *dgst,
X509 *subject, X509 *issuer);
OCSP_CERTID *OCSP_cert_id_new(const EVP_MD *dgst,
X509_NAME *issuerName,
ASN1_BIT_STRING *issuerKey,
ASN1_INTEGER *serialNumber);
void OCSP_CERTID_free(OCSP_CERTID *id);
int OCSP_id_issuer_cmp(const OCSP_CERTID *a, const OCSP_CERTID *b);
int OCSP_id_cmp(const OCSP_CERTID *a, const OCSP_CERTID *b);
int OCSP_id_get0_info(ASN1_OCTET_STRING **piNameHash, ASN1_OBJECT **pmd,
ASN1_OCTET_STRING **pikeyHash,
ASN1_INTEGER **pserial, OCSP_CERTID *cid);
=head1 DESCRIPTION
OCSP_cert_to_id() creates and returns a new B<OCSP_CERTID> structure using
message digest B<dgst> for certificate B<subject> with issuer B<issuer>. If
B<dgst> is B<NULL> then SHA1 is used.
OCSP_cert_id_new() creates and returns a new B<OCSP_CERTID> using B<dgst> and
issuer name B<issuerName>, issuer key hash B<issuerKey> and serial number
B<serialNumber>.
OCSP_CERTID_free() frees up B<id>.
+If the argument is NULL, nothing is done.
OCSP_id_cmp() compares B<OCSP_CERTID> B<a> and B<b>.
OCSP_id_issuer_cmp() compares only the issuer name of B<OCSP_CERTID> B<a> and B<b>.
OCSP_id_get0_info() returns the issuer name hash, hash OID, issuer key hash and
serial number contained in B<cid>. If any of the values are not required the
corresponding parameter can be set to B<NULL>.
=head1 RETURN VALUES
OCSP_cert_to_id() and OCSP_cert_id_new() return either a pointer to a valid
B<OCSP_CERTID> structure or B<NULL> if an error occurred.
OCSP_id_cmp() and OCSP_id_issuer_cmp() returns zero for a match and nonzero
otherwise.
OCSP_CERTID_free() does not return a value.
OCSP_id_get0_info() returns 1 for success and 0 for failure.
=head1 NOTES
OCSP clients will typically only use OCSP_cert_to_id() or OCSP_cert_id_new():
the other functions are used by responder applications.
The values returned by OCSP_id_get0_info() are internal pointers and B<MUST
NOT> be freed up by an application: they will be freed when the corresponding
B<OCSP_CERTID> structure is freed.
=head1 SEE ALSO
L<crypto(7)>,
L<OCSP_request_add1_nonce(3)>,
L<OCSP_REQUEST_new(3)>,
L<OCSP_resp_find_status(3)>,
L<OCSP_response_status(3)>,
L<OCSP_sendreq_new(3)>
=head1 COPYRIGHT
-Copyright 2015-2016 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
L<https://www.openssl.org/source/license.html>.
=cut
diff --git a/crypto/openssl/doc/man3/OCSP_response_status.pod b/crypto/openssl/doc/man3/OCSP_response_status.pod
index 7ff74923a53f..0902ae8a31bc 100644
--- a/crypto/openssl/doc/man3/OCSP_response_status.pod
+++ b/crypto/openssl/doc/man3/OCSP_response_status.pod
@@ -1,133 +1,134 @@
=pod
=head1 NAME
OCSP_response_status, OCSP_response_get1_basic, OCSP_response_create,
OCSP_RESPONSE_free, OCSP_RESPID_set_by_name,
OCSP_RESPID_set_by_key_ex, OCSP_RESPID_set_by_key, OCSP_RESPID_match_ex,
OCSP_RESPID_match, OCSP_basic_sign, OCSP_basic_sign_ctx
- OCSP response functions
=head1 SYNOPSIS
#include <openssl/ocsp.h>
int OCSP_response_status(OCSP_RESPONSE *resp);
OCSP_BASICRESP *OCSP_response_get1_basic(OCSP_RESPONSE *resp);
OCSP_RESPONSE *OCSP_response_create(int status, OCSP_BASICRESP *bs);
void OCSP_RESPONSE_free(OCSP_RESPONSE *resp);
int OCSP_RESPID_set_by_name(OCSP_RESPID *respid, X509 *cert);
int OCSP_RESPID_set_by_key_ex(OCSP_RESPID *respid, X509 *cert,
OSSL_LIB_CTX *libctx, const char *propq);
int OCSP_RESPID_set_by_key(OCSP_RESPID *respid, X509 *cert);
int OCSP_RESPID_match_ex(OCSP_RESPID *respid, X509 *cert, OSSL_LIB_CTX *libctx,
const char *propq);
int OCSP_RESPID_match(OCSP_RESPID *respid, X509 *cert);
int OCSP_basic_sign(OCSP_BASICRESP *brsp, X509 *signer, EVP_PKEY *key,
const EVP_MD *dgst, STACK_OF(X509) *certs,
unsigned long flags);
int OCSP_basic_sign_ctx(OCSP_BASICRESP *brsp, X509 *signer, EVP_MD_CTX *ctx,
STACK_OF(X509) *certs, unsigned long flags);
=head1 DESCRIPTION
OCSP_response_status() returns the OCSP response status of I<resp>. It returns
one of the values: I<OCSP_RESPONSE_STATUS_SUCCESSFUL>,
I<OCSP_RESPONSE_STATUS_MALFORMEDREQUEST>,
I<OCSP_RESPONSE_STATUS_INTERNALERROR>, I<OCSP_RESPONSE_STATUS_TRYLATER>
I<OCSP_RESPONSE_STATUS_SIGREQUIRED>, or I<OCSP_RESPONSE_STATUS_UNAUTHORIZED>.
OCSP_response_get1_basic() decodes and returns the I<OCSP_BASICRESP> structure
contained in I<resp>.
OCSP_response_create() creates and returns an I<OCSP_RESPONSE> structure for
I<status> and optionally including basic response I<bs>.
OCSP_RESPONSE_free() frees up OCSP response I<resp>.
+If the argument is NULL, nothing is done.
OCSP_RESPID_set_by_name() sets the name of the OCSP_RESPID to be the same as the
subject name in the supplied X509 certificate I<cert> for the OCSP responder.
OCSP_RESPID_set_by_key_ex() sets the key of the OCSP_RESPID to be the same as the
key in the supplied X509 certificate I<cert> for the OCSP responder. The key is
stored as a SHA1 hash. To calculate the hash the SHA1 algorithm is fetched using
the library ctx I<libctx> and the property query string I<propq> (see
L<crypto(7)/ALGORITHM FETCHING> for further information).
OCSP_RESPID_set_by_key() does the same as OCSP_RESPID_set_by_key_ex() except
that the default library context is used with an empty property query string.
Note that an OCSP_RESPID can only have one of the name, or the key set. Calling
OCSP_RESPID_set_by_name() or OCSP_RESPID_set_by_key() will clear any existing
setting.
OCSP_RESPID_match_ex() tests whether the OCSP_RESPID given in I<respid> matches
with the X509 certificate I<cert> based on the SHA1 hash. To calculate the hash
the SHA1 algorithm is fetched using the library ctx I<libctx> and the property
query string I<propq> (see L<crypto(7)/ALGORITHM FETCHING> for further
information).
OCSP_RESPID_match() does the same as OCSP_RESPID_match_ex() except that the
default library context is used with an empty property query string.
OCSP_basic_sign() signs OCSP response I<brsp> using certificate I<signer>, private key
I<key>, digest I<dgst> and additional certificates I<certs>. If the I<flags> option
I<OCSP_NOCERTS> is set then no certificates will be included in the response. If the
I<flags> option I<OCSP_RESPID_KEY> is set then the responder is identified by key ID
rather than by name. OCSP_basic_sign_ctx() also signs OCSP response I<brsp> but
uses the parameters contained in digest context I<ctx>.
=head1 RETURN VALUES
OCSP_RESPONSE_status() returns a status value.
OCSP_response_get1_basic() returns an I<OCSP_BASICRESP> structure pointer or
I<NULL> if an error occurred.
OCSP_response_create() returns an I<OCSP_RESPONSE> structure pointer or I<NULL>
if an error occurred.
OCSP_RESPONSE_free() does not return a value.
OCSP_RESPID_set_by_name(), OCSP_RESPID_set_by_key(), OCSP_basic_sign(), and
OCSP_basic_sign_ctx() return 1 on success or 0
on failure.
OCSP_RESPID_match() returns 1 if the OCSP_RESPID and the X509 certificate match
or 0 otherwise.
=head1 NOTES
OCSP_response_get1_basic() is only called if the status of a response is
I<OCSP_RESPONSE_STATUS_SUCCESSFUL>.
=head1 SEE ALSO
L<crypto(7)>
L<OCSP_cert_to_id(3)>
L<OCSP_request_add1_nonce(3)>
L<OCSP_REQUEST_new(3)>
L<OCSP_resp_find_status(3)>
L<OCSP_sendreq_new(3)>
L<OCSP_RESPID_new(3)>
L<OCSP_RESPID_free(3)>
=head1 HISTORY
The OCSP_RESPID_set_by_name(), OCSP_RESPID_set_by_key() and OCSP_RESPID_match()
functions were added in OpenSSL 1.1.0a.
The OCSP_basic_sign_ctx() function was added in OpenSSL 1.1.1.
=head1 COPYRIGHT
-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
L<https://www.openssl.org/source/license.html>.
=cut
diff --git a/crypto/openssl/doc/man3/OPENSSL_LH_COMPFUNC.pod b/crypto/openssl/doc/man3/OPENSSL_LH_COMPFUNC.pod
index 688ef0edcb91..f62c57172cb7 100644
--- a/crypto/openssl/doc/man3/OPENSSL_LH_COMPFUNC.pod
+++ b/crypto/openssl/doc/man3/OPENSSL_LH_COMPFUNC.pod
@@ -1,309 +1,309 @@
=pod
=head1 NAME
LHASH, DECLARE_LHASH_OF,
OPENSSL_LH_COMPFUNC, OPENSSL_LH_HASHFUNC, OPENSSL_LH_DOALL_FUNC,
LHASH_DOALL_ARG_FN_TYPE,
IMPLEMENT_LHASH_HASH_FN, IMPLEMENT_LHASH_COMP_FN,
lh_TYPE_new, lh_TYPE_free, lh_TYPE_flush,
lh_TYPE_insert, lh_TYPE_delete, lh_TYPE_retrieve,
lh_TYPE_doall, lh_TYPE_doall_arg, lh_TYPE_num_items, lh_TYPE_get_down_load,
lh_TYPE_set_down_load, lh_TYPE_error,
OPENSSL_LH_new, OPENSSL_LH_free, OPENSSL_LH_flush,
OPENSSL_LH_insert, OPENSSL_LH_delete, OPENSSL_LH_retrieve,
OPENSSL_LH_doall, OPENSSL_LH_doall_arg, OPENSSL_LH_num_items,
OPENSSL_LH_get_down_load, OPENSSL_LH_set_down_load, OPENSSL_LH_error
- dynamic hash table
=head1 SYNOPSIS
=for openssl generic
#include <openssl/lhash.h>
DECLARE_LHASH_OF(TYPE);
LHASH_OF(TYPE) *lh_TYPE_new(OPENSSL_LH_HASHFUNC hash, OPENSSL_LH_COMPFUNC compare);
void lh_TYPE_free(LHASH_OF(TYPE) *table);
void lh_TYPE_flush(LHASH_OF(TYPE) *table);
TYPE *lh_TYPE_insert(LHASH_OF(TYPE) *table, TYPE *data);
TYPE *lh_TYPE_delete(LHASH_OF(TYPE) *table, TYPE *data);
TYPE *lh_TYPE_retrieve(LHASH_OF(TYPE) *table, TYPE *data);
void lh_TYPE_doall(LHASH_OF(TYPE) *table, OPENSSL_LH_DOALL_FUNC func);
void lh_TYPE_doall_arg(LHASH_OF(TYPE) *table, OPENSSL_LH_DOALL_FUNCARG func,
TYPE *arg);
unsigned long lh_TYPE_num_items(OPENSSL_LHASH *lh);
unsigned long lh_TYPE_get_down_load(OPENSSL_LHASH *lh);
void lh_TYPE_set_down_load(OPENSSL_LHASH *lh, unsigned long dl);
int lh_TYPE_error(LHASH_OF(TYPE) *table);
typedef int (*OPENSSL_LH_COMPFUNC)(const void *, const void *);
typedef unsigned long (*OPENSSL_LH_HASHFUNC)(const void *);
typedef void (*OPENSSL_LH_DOALL_FUNC)(const void *);
typedef void (*LHASH_DOALL_ARG_FN_TYPE)(const void *, const void *);
OPENSSL_LHASH *OPENSSL_LH_new(OPENSSL_LH_HASHFUNC h, OPENSSL_LH_COMPFUNC c);
void OPENSSL_LH_free(OPENSSL_LHASH *lh);
void OPENSSL_LH_flush(OPENSSL_LHASH *lh);
void *OPENSSL_LH_insert(OPENSSL_LHASH *lh, void *data);
void *OPENSSL_LH_delete(OPENSSL_LHASH *lh, const void *data);
void *OPENSSL_LH_retrieve(OPENSSL_LHASH *lh, const void *data);
void OPENSSL_LH_doall(OPENSSL_LHASH *lh, OPENSSL_LH_DOALL_FUNC func);
void OPENSSL_LH_doall_arg(OPENSSL_LHASH *lh, OPENSSL_LH_DOALL_FUNCARG func, void *arg);
unsigned long OPENSSL_LH_num_items(OPENSSL_LHASH *lh);
unsigned long OPENSSL_LH_get_down_load(OPENSSL_LHASH *lh);
void OPENSSL_LH_set_down_load(OPENSSL_LHASH *lh, unsigned long dl);
int OPENSSL_LH_error(OPENSSL_LHASH *lh);
#define LH_LOAD_MULT /* integer constant */
=head1 DESCRIPTION
This library implements type-checked dynamic hash tables. The hash
table entries can be arbitrary structures. Usually they consist of key
and value fields. In the description here, B<I<TYPE>> is used a placeholder
for any of the OpenSSL datatypes, such as I<SSL_SESSION>.
B<lh_I<TYPE>_new>() creates a new B<LHASH_OF>(B<I<TYPE>>) structure to store
arbitrary data entries, and specifies the 'hash' and 'compare'
callbacks to be used in organising the table's entries. The I<hash>
callback takes a pointer to a table entry as its argument and returns
an unsigned long hash value for its key field. The hash value is
normally truncated to a power of 2, so make sure that your hash
function returns well mixed low order bits. The I<compare> callback
takes two arguments (pointers to two hash table entries), and returns
0 if their keys are equal, nonzero otherwise.
If your hash table
will contain items of some particular type and the I<hash> and
I<compare> callbacks hash/compare these types, then the
B<IMPLEMENT_LHASH_HASH_FN> and B<IMPLEMENT_LHASH_COMP_FN> macros can be
used to create callback wrappers of the prototypes required by
B<lh_I<TYPE>_new>() as shown in this example:
/*
* Implement the hash and compare functions; "stuff" can be any word.
*/
static unsigned long stuff_hash(const TYPE *a)
{
...
}
static int stuff_cmp(const TYPE *a, const TYPE *b)
{
...
}
/*
* Implement the wrapper functions.
*/
static IMPLEMENT_LHASH_HASH_FN(stuff, TYPE)
static IMPLEMENT_LHASH_COMP_FN(stuff, TYPE)
If the type is going to be used in several places, the following macros
can be used in a common header file to declare the function wrappers:
DECLARE_LHASH_HASH_FN(stuff, TYPE)
DECLARE_LHASH_COMP_FN(stuff, TYPE)
Then a hash table of B<I<TYPE>> objects can be created using this:
LHASH_OF(TYPE) *htable;
htable = B<lh_I<TYPE>_new>(LHASH_HASH_FN(stuff), LHASH_COMP_FN(stuff));
B<lh_I<TYPE>_free>() frees the B<LHASH_OF>(B<I<TYPE>>) structure
I<table>. Allocated hash table entries will not be freed; consider
using B<lh_I<TYPE>_doall>() to deallocate any remaining entries in the
-hash table (see below).
+hash table (see below). If the argument is NULL, nothing is done.
B<lh_I<TYPE>_flush>() empties the B<LHASH_OF>(B<I<TYPE>>) structure I<table>. New
entries can be added to the flushed table. Allocated hash table entries
will not be freed; consider using B<lh_I<TYPE>_doall>() to deallocate any
remaining entries in the hash table (see below).
B<lh_I<TYPE>_insert>() inserts the structure pointed to by I<data> into
I<table>. If there already is an entry with the same key, the old
value is replaced. Note that B<lh_I<TYPE>_insert>() stores pointers, the
data are not copied.
B<lh_I<TYPE>_delete>() deletes an entry from I<table>.
B<lh_I<TYPE>_retrieve>() looks up an entry in I<table>. Normally, I<data>
is a structure with the key field(s) set; the function will return a
pointer to a fully populated structure.
B<lh_I<TYPE>_doall>() will, for every entry in the hash table, call
I<func> with the data item as its parameter.
For example:
/* Cleans up resources belonging to 'a' (this is implemented elsewhere) */
void TYPE_cleanup_doall(TYPE *a);
/* Implement a prototype-compatible wrapper for "TYPE_cleanup" */
IMPLEMENT_LHASH_DOALL_FN(TYPE_cleanup, TYPE)
/* Call "TYPE_cleanup" against all items in a hash table. */
lh_TYPE_doall(hashtable, LHASH_DOALL_FN(TYPE_cleanup));
/* Then the hash table itself can be deallocated */
lh_TYPE_free(hashtable);
B<lh_I<TYPE>_doall_arg>() is the same as B<lh_I<TYPE>_doall>() except that
I<func> will be called with I<arg> as the second argument and I<func>
should be of type B<LHASH_DOALL_ARG_FN>(B<I<TYPE>>) (a callback prototype
that is passed both the table entry and an extra argument). As with
lh_doall(), you can instead choose to declare your callback with a
prototype matching the types you are dealing with and use the
declare/implement macros to create compatible wrappers that cast
variables before calling your type-specific callbacks. An example of
this is demonstrated here (printing all hash table entries to a BIO
that is provided by the caller):
/* Prints item 'a' to 'output_bio' (this is implemented elsewhere) */
void TYPE_print_doall_arg(const TYPE *a, BIO *output_bio);
/* Implement a prototype-compatible wrapper for "TYPE_print" */
static IMPLEMENT_LHASH_DOALL_ARG_FN(TYPE, const TYPE, BIO)
/* Print out the entire hashtable to a particular BIO */
lh_TYPE_doall_arg(hashtable, LHASH_DOALL_ARG_FN(TYPE_print), BIO,
logging_bio);
Note that it is by default B<not> safe to use B<lh_I<TYPE>_delete>() inside a
callback passed to B<lh_I<TYPE>_doall>() or B<lh_I<TYPE>_doall_arg>(). The
reason for this is that deleting an item from the hash table may result in the
hash table being contracted to a smaller size and rehashed.
B<lh_I<TYPE>_doall>() and B<lh_I<TYPE>_doall_arg>() are unsafe and will exhibit
undefined behaviour under these conditions, as these functions assume the hash
table size and bucket pointers do not change during the call.
If it is desired to use B<lh_I<TYPE>_doall>() or B<lh_I<TYPE>_doall_arg>() with
B<lh_I<TYPE>_delete>(), it is essential that you call
B<lh_I<TYPE>_set_down_load>() with a I<down_load> argument of 0 first. This
disables hash table contraction and guarantees that it will be safe to delete
items from a hash table during a call to B<lh_I<TYPE>_doall>() or
B<lh_I<TYPE>_doall_arg>().
It is never safe to call B<lh_I<TYPE>_insert>() during a call to
B<lh_I<TYPE>_doall>() or B<lh_I<TYPE>_doall_arg>().
B<lh_I<TYPE>_error>() can be used to determine if an error occurred in the last
operation.
B<lh_I<TYPE>_num_items>() returns the number of items in the hash table.
B<lh_I<TYPE>_get_down_load>() and B<lh_I<TYPE>_set_down_load>() get and set the
factor used to determine when the hash table is contracted. The factor is the
load factor at or below which hash table contraction will occur, multiplied by
B<LH_LOAD_MULT>, where the load factor is the number of items divided by the
number of nodes. Setting this value to 0 disables hash table contraction.
OPENSSL_LH_new() is the same as the B<lh_I<TYPE>_new>() except that it is not
type specific. So instead of returning an B<LHASH_OF(I<TYPE>)> value it returns
a B<void *>. In the same way the functions OPENSSL_LH_free(),
OPENSSL_LH_flush(), OPENSSL_LH_insert(), OPENSSL_LH_delete(),
OPENSSL_LH_retrieve(), OPENSSL_LH_doall(), OPENSSL_LH_doall_arg(),
OPENSSL_LH_num_items(), OPENSSL_LH_get_down_load(), OPENSSL_LH_set_down_load()
and OPENSSL_LH_error() are equivalent to the similarly named B<lh_I<TYPE>>
functions except that they return or use a B<void *> where the equivalent
B<lh_I<TYPE>> function returns or uses a B<I<TYPE> *> or B<LHASH_OF(I<TYPE>) *>.
B<lh_I<TYPE>> functions are implemented as type checked wrappers around the
B<OPENSSL_LH> functions. Most applications should not call the B<OPENSSL_LH>
functions directly.
=head1 RETURN VALUES
B<lh_I<TYPE>_new>() and OPENSSL_LH_new() return NULL on error, otherwise a
pointer to the new B<LHASH> structure.
When a hash table entry is replaced, B<lh_I<TYPE>_insert>() or
OPENSSL_LH_insert() return the value being replaced. NULL is returned on normal
operation and on error.
B<lh_I<TYPE>_delete>() and OPENSSL_LH_delete() return the entry being deleted.
NULL is returned if there is no such value in the hash table.
B<lh_I<TYPE>_retrieve>() and OPENSSL_LH_retrieve() return the hash table entry
if it has been found, NULL otherwise.
B<lh_I<TYPE>_error>() and OPENSSL_LH_error() return 1 if an error occurred in
the last operation, 0 otherwise. It's meaningful only after non-retrieve
operations.
B<lh_I<TYPE>_free>(), OPENSSL_LH_free(), B<lh_I<TYPE>_flush>(),
OPENSSL_LH_flush(), B<lh_I<TYPE>_doall>() OPENSSL_LH_doall(),
B<lh_I<TYPE>_doall_arg>() and OPENSSL_LH_doall_arg() return no values.
=head1 NOTE
The LHASH code is not thread safe. All updating operations, as well as
B<lh_I<TYPE>_error>() or OPENSSL_LH_error() calls must be performed under
a write lock. All retrieve operations should be performed under a read lock,
I<unless> accurate usage statistics are desired. In which case, a write lock
should be used for retrieve operations as well. For output of the usage
statistics, using the functions from L<OPENSSL_LH_stats(3)>, a read lock
suffices.
The LHASH code regards table entries as constant data. As such, it
internally represents lh_insert()'d items with a "const void *"
pointer type. This is why callbacks such as those used by lh_doall()
and lh_doall_arg() declare their prototypes with "const", even for the
parameters that pass back the table items' data pointers - for
consistency, user-provided data is "const" at all times as far as the
LHASH code is concerned. However, as callers are themselves providing
these pointers, they can choose whether they too should be treating
all such parameters as constant.
As an example, a hash table may be maintained by code that, for
reasons of encapsulation, has only "const" access to the data being
indexed in the hash table (i.e. it is returned as "const" from
elsewhere in their code) - in this case the LHASH prototypes are
appropriate as-is. Conversely, if the caller is responsible for the
life-time of the data in question, then they may well wish to make
modifications to table item passed back in the lh_doall() or
lh_doall_arg() callbacks (see the "TYPE_cleanup" example above). If
so, the caller can either cast the "const" away (if they're providing
the raw callbacks themselves) or use the macros to declare/implement
the wrapper functions without "const" types.
Callers that only have "const" access to data they're indexing in a
table, yet declare callbacks without constant types (or cast the
"const" away themselves), are therefore creating their own risks/bugs
without being encouraged to do so by the API. On a related note,
those auditing code should pay special attention to any instances of
DECLARE/IMPLEMENT_LHASH_DOALL_[ARG_]_FN macros that provide types
without any "const" qualifiers.
=head1 BUGS
B<lh_I<TYPE>_insert>() and OPENSSL_LH_insert() return NULL both for success
and error.
=head1 SEE ALSO
L<OPENSSL_LH_stats(3)>
=head1 HISTORY
In OpenSSL 1.0.0, the lhash interface was revamped for better
type checking.
=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/OPENSSL_init_crypto.pod b/crypto/openssl/doc/man3/OPENSSL_init_crypto.pod
index c3e72d274423..1363693c779b 100644
--- a/crypto/openssl/doc/man3/OPENSSL_init_crypto.pod
+++ b/crypto/openssl/doc/man3/OPENSSL_init_crypto.pod
@@ -1,299 +1,300 @@
=pod
=head1 NAME
OPENSSL_INIT_new, OPENSSL_INIT_set_config_filename,
OPENSSL_INIT_set_config_appname, OPENSSL_INIT_set_config_file_flags,
OPENSSL_INIT_free, OPENSSL_init_crypto, OPENSSL_cleanup, OPENSSL_atexit,
OPENSSL_thread_stop_ex, OPENSSL_thread_stop - OpenSSL initialisation
and deinitialisation functions
=head1 SYNOPSIS
#include <openssl/crypto.h>
void OPENSSL_cleanup(void);
int OPENSSL_init_crypto(uint64_t opts, const OPENSSL_INIT_SETTINGS *settings);
int OPENSSL_atexit(void (*handler)(void));
void OPENSSL_thread_stop_ex(OSSL_LIB_CTX *ctx);
void OPENSSL_thread_stop(void);
OPENSSL_INIT_SETTINGS *OPENSSL_INIT_new(void);
int OPENSSL_INIT_set_config_filename(OPENSSL_INIT_SETTINGS *init,
const char* filename);
int OPENSSL_INIT_set_config_file_flags(OPENSSL_INIT_SETTINGS *init,
unsigned long flags);
int OPENSSL_INIT_set_config_appname(OPENSSL_INIT_SETTINGS *init,
const char* name);
void OPENSSL_INIT_free(OPENSSL_INIT_SETTINGS *init);
=head1 DESCRIPTION
During normal operation OpenSSL (libcrypto) will allocate various resources at
start up that must, subsequently, be freed on close down of the library.
Additionally some resources are allocated on a per thread basis (if the
application is multi-threaded), and these resources must be freed prior to the
thread closing.
As of version 1.1.0 OpenSSL will automatically allocate all resources that it
needs so no explicit initialisation is required. Similarly it will also
automatically deinitialise as required.
However, there may be situations when explicit initialisation is desirable or
needed, for example when some nondefault initialisation is required. The
function OPENSSL_init_crypto() can be used for this purpose for
libcrypto (see also L<OPENSSL_init_ssl(3)> for the libssl
equivalent).
Numerous internal OpenSSL functions call OPENSSL_init_crypto().
Therefore, in order to perform nondefault initialisation,
OPENSSL_init_crypto() MUST be called by application code prior to
any other OpenSSL function calls.
The B<opts> parameter specifies which aspects of libcrypto should be
initialised. Valid options are:
=over 4
=item OPENSSL_INIT_NO_LOAD_CRYPTO_STRINGS
Suppress automatic loading of the libcrypto error strings. This option is
not a default option. Once selected subsequent calls to
OPENSSL_init_crypto() with the option
B<OPENSSL_INIT_LOAD_CRYPTO_STRINGS> will be ignored.
=item OPENSSL_INIT_LOAD_CRYPTO_STRINGS
Automatic loading of the libcrypto error strings. With this option the
library will automatically load the libcrypto error strings.
This option is a default option. Once selected subsequent calls to
OPENSSL_init_crypto() with the option
B<OPENSSL_INIT_NO_LOAD_CRYPTO_STRINGS> will be ignored.
=item OPENSSL_INIT_ADD_ALL_CIPHERS
With this option the library will automatically load and make available all
libcrypto ciphers. This option is a default option. Once selected subsequent
calls to OPENSSL_init_crypto() with the option
B<OPENSSL_INIT_NO_ADD_ALL_CIPHERS> will be ignored.
=item OPENSSL_INIT_ADD_ALL_DIGESTS
With this option the library will automatically load and make available all
libcrypto digests. This option is a default option. Once selected subsequent
calls to OPENSSL_init_crypto() with the option
B<OPENSSL_INIT_NO_ADD_ALL_DIGESTS> will be ignored.
=item OPENSSL_INIT_NO_ADD_ALL_CIPHERS
With this option the library will suppress automatic loading of libcrypto
ciphers. This option is not a default option. Once selected subsequent
calls to OPENSSL_init_crypto() with the option
B<OPENSSL_INIT_ADD_ALL_CIPHERS> will be ignored.
=item OPENSSL_INIT_NO_ADD_ALL_DIGESTS
With this option the library will suppress automatic loading of libcrypto
digests. This option is not a default option. Once selected subsequent
calls to OPENSSL_init_crypto() with the option
B<OPENSSL_INIT_ADD_ALL_DIGESTS> will be ignored.
=item OPENSSL_INIT_LOAD_CONFIG
With this option an OpenSSL configuration file will be automatically loaded and
used by calling OPENSSL_config(). This is a default option.
Note that in OpenSSL 1.1.1 this was the default for libssl but not for
libcrypto (see L<OPENSSL_init_ssl(3)> for further details about libssl
initialisation).
In OpenSSL 1.1.0 this was a nondefault option for both libssl and libcrypto.
See the description of OPENSSL_INIT_new(), below.
=item OPENSSL_INIT_NO_LOAD_CONFIG
With this option the loading of OpenSSL configuration files will be suppressed.
It is the equivalent of calling OPENSSL_no_config(). This is not a default
option.
=item OPENSSL_INIT_ASYNC
With this option the library with automatically initialise the libcrypto async
sub-library (see L<ASYNC_start_job(3)>). This is a default option.
=item OPENSSL_INIT_ENGINE_RDRAND
With this option the library will automatically load and initialise the
RDRAND engine (if available). This not a default option and is deprecated
in OpenSSL 3.0.
=item OPENSSL_INIT_ENGINE_DYNAMIC
With this option the library will automatically load and initialise the
dynamic engine. This not a default option and is deprecated
in OpenSSL 3.0.
=item OPENSSL_INIT_ENGINE_OPENSSL
With this option the library will automatically load and initialise the
openssl engine. This not a default option and is deprecated
in OpenSSL 3.0.
=item OPENSSL_INIT_ENGINE_CRYPTODEV
With this option the library will automatically load and initialise the
cryptodev engine (if available). This not a default option and is deprecated
in OpenSSL 3.0.
=item OPENSSL_INIT_ENGINE_CAPI
With this option the library will automatically load and initialise the
CAPI engine (if available). This not a default option and is deprecated
in OpenSSL 3.0.
=item OPENSSL_INIT_ENGINE_PADLOCK
With this option the library will automatically load and initialise the
padlock engine (if available). This not a default option and is deprecated
in OpenSSL 3.0.
=item OPENSSL_INIT_ENGINE_AFALG
With this option the library will automatically load and initialise the
AFALG engine. This not a default option and is deprecated
in OpenSSL 3.0.
=item OPENSSL_INIT_ENGINE_ALL_BUILTIN
With this option the library will automatically load and initialise all the
built in engines listed above with the exception of the openssl and afalg
engines. This not a default option and is deprecated
in OpenSSL 3.0.
=item OPENSSL_INIT_ATFORK
With this option the library will register its fork handlers.
See OPENSSL_fork_prepare(3) for details.
=item OPENSSL_INIT_NO_ATEXIT
By default OpenSSL will attempt to clean itself up when the process exits via an
"atexit" handler. Using this option suppresses that behaviour. This means that
the application will have to clean up OpenSSL explicitly using
OPENSSL_cleanup().
=back
Multiple options may be combined together in a single call to
OPENSSL_init_crypto(). For example:
OPENSSL_init_crypto(OPENSSL_INIT_NO_ADD_ALL_CIPHERS
| OPENSSL_INIT_NO_ADD_ALL_DIGESTS, NULL);
The OPENSSL_cleanup() function deinitialises OpenSSL (both libcrypto
and libssl). All resources allocated by OpenSSL are freed. Typically there
should be no need to call this function directly as it is initiated
automatically on application exit. This is done via the standard C library
atexit() function. In the event that the application will close in a manner
that will not call the registered atexit() handlers then the application should
call OPENSSL_cleanup() directly. Developers of libraries using OpenSSL
are discouraged from calling this function and should instead, typically, rely
on auto-deinitialisation. This is to avoid error conditions where both an
application and a library it depends on both use OpenSSL, and the library
deinitialises it before the application has finished using it.
Once OPENSSL_cleanup() has been called the library cannot be reinitialised.
Attempts to call OPENSSL_init_crypto() will fail and an ERR_R_INIT_FAIL error
will be added to the error stack. Note that because initialisation has failed
OpenSSL error strings will not be available, only an error code. This code can
be put through the openssl errstr command line application to produce a human
readable error (see L<openssl-errstr(1)>).
The OPENSSL_atexit() function enables the registration of a
function to be called during OPENSSL_cleanup(). Stop handlers are
called after deinitialisation of resources local to a thread, but before other
process wide resources are freed. In the event that multiple stop handlers are
registered, no guarantees are made about the order of execution.
The OPENSSL_thread_stop_ex() function deallocates resources associated
with the current thread for the given OSSL_LIB_CTX B<ctx>. The B<ctx> parameter
can be NULL in which case the default OSSL_LIB_CTX is used.
Typically, this function will be called automatically by the library when
the thread exits as long as the OSSL_LIB_CTX has not been freed before the thread
exits. If OSSL_LIB_CTX_free() is called OPENSSL_thread_stop_ex will be called
automatically for the current thread (but not any other threads that may have
used this OSSL_LIB_CTX).
OPENSSL_thread_stop_ex should be called on all threads that will exit after the
OSSL_LIB_CTX is freed.
Typically this is not necessary for the default OSSL_LIB_CTX (because all
resources are cleaned up on library exit) except if thread local resources
should be freed before library exit, or under the circumstances described in
the NOTES section below.
OPENSSL_thread_stop() is the same as OPENSSL_thread_stop_ex() except that the
default OSSL_LIB_CTX is always used.
The B<OPENSSL_INIT_LOAD_CONFIG> flag will load a configuration file, as with
L<CONF_modules_load_file(3)> with NULL filename and application name and the
B<CONF_MFLAGS_IGNORE_MISSING_FILE>, B<CONF_MFLAGS_IGNORE_RETURN_CODES> and
B<CONF_MFLAGS_DEFAULT_SECTION> flags.
The filename, application name, and flags can be customized by providing a
non-null B<OPENSSL_INIT_SETTINGS> object.
The object can be allocated via B<OPENSSL_INIT_new()>.
The B<OPENSSL_INIT_set_config_filename()> function can be used to specify a
nondefault filename, which is copied and need not refer to persistent storage.
Similarly, OPENSSL_INIT_set_config_appname() can be used to specify a
nondefault application name.
Finally, OPENSSL_INIT_set_file_flags can be used to specify nondefault flags.
If the B<CONF_MFLAGS_IGNORE_RETURN_CODES> flag is not included, any errors in
the configuration file will cause an error return from B<OPENSSL_init_crypto>
or indirectly L<OPENSSL_init_ssl(3)>.
The object can be released with OPENSSL_INIT_free() when done.
+If the argument to OPENSSL_INIT_free() is NULL, nothing is done.
=head1 NOTES
Resources local to a thread are deallocated automatically when the thread exits
(e.g. in a pthreads environment, when pthread_exit() is called). On Windows
platforms this is done in response to a DLL_THREAD_DETACH message being sent to
the libcrypto32.dll entry point. Some windows functions may cause threads to exit
without sending this message (for example ExitProcess()). If the application
uses such functions, then the application must free up OpenSSL resources
directly via a call to OPENSSL_thread_stop() on each thread. Similarly this
message will also not be sent if OpenSSL is linked statically, and therefore
applications using static linking should also call OPENSSL_thread_stop() on each
thread. Additionally if OpenSSL is loaded dynamically via LoadLibrary() and the
threads are not destroyed until after FreeLibrary() is called then each thread
should call OPENSSL_thread_stop() prior to the FreeLibrary() call.
On Linux/Unix where OpenSSL has been loaded via dlopen() and the application is
multi-threaded and if dlclose() is subsequently called prior to the threads
being destroyed then OpenSSL will not be able to deallocate resources associated
with those threads. The application should either call OPENSSL_thread_stop() on
each thread prior to the dlclose() call, or alternatively the original dlopen()
call should use the RTLD_NODELETE flag (where available on the platform).
=head1 RETURN VALUES
The functions OPENSSL_init_crypto, OPENSSL_atexit() and
OPENSSL_INIT_set_config_appname() return 1 on success or 0 on error.
=head1 SEE ALSO
L<OPENSSL_init_ssl(3)>
=head1 HISTORY
The OPENSSL_init_crypto(), OPENSSL_cleanup(), OPENSSL_atexit(),
OPENSSL_thread_stop(), OPENSSL_INIT_new(), OPENSSL_INIT_set_config_appname()
and OPENSSL_INIT_free() functions were added in OpenSSL 1.1.0.
=head1 COPYRIGHT
-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
L<https://www.openssl.org/source/license.html>.
=cut
diff --git a/crypto/openssl/doc/man3/OPENSSL_malloc.pod b/crypto/openssl/doc/man3/OPENSSL_malloc.pod
index 76751012bde5..20441e76ac65 100644
--- a/crypto/openssl/doc/man3/OPENSSL_malloc.pod
+++ b/crypto/openssl/doc/man3/OPENSSL_malloc.pod
@@ -1,208 +1,209 @@
=pod
=head1 NAME
OPENSSL_malloc_init,
OPENSSL_malloc, OPENSSL_zalloc, OPENSSL_realloc, OPENSSL_free,
OPENSSL_clear_realloc, OPENSSL_clear_free, OPENSSL_cleanse,
CRYPTO_malloc, CRYPTO_zalloc, CRYPTO_realloc, CRYPTO_free,
OPENSSL_strdup, OPENSSL_strndup,
OPENSSL_memdup, OPENSSL_strlcpy, OPENSSL_strlcat,
CRYPTO_strdup, CRYPTO_strndup,
OPENSSL_mem_debug_push, OPENSSL_mem_debug_pop,
CRYPTO_mem_debug_push, CRYPTO_mem_debug_pop,
CRYPTO_clear_realloc, CRYPTO_clear_free,
CRYPTO_malloc_fn, CRYPTO_realloc_fn, CRYPTO_free_fn,
CRYPTO_get_mem_functions, CRYPTO_set_mem_functions,
CRYPTO_get_alloc_counts,
CRYPTO_set_mem_debug, CRYPTO_mem_ctrl,
CRYPTO_mem_leaks, CRYPTO_mem_leaks_fp, CRYPTO_mem_leaks_cb,
OPENSSL_MALLOC_FAILURES,
OPENSSL_MALLOC_FD
- Memory allocation functions
=head1 SYNOPSIS
#include <openssl/crypto.h>
int OPENSSL_malloc_init(void);
void *OPENSSL_malloc(size_t num);
void *OPENSSL_zalloc(size_t num);
void *OPENSSL_realloc(void *addr, size_t num);
void OPENSSL_free(void *addr);
char *OPENSSL_strdup(const char *str);
char *OPENSSL_strndup(const char *str, size_t s);
size_t OPENSSL_strlcat(char *dst, const char *src, size_t size);
size_t OPENSSL_strlcpy(char *dst, const char *src, size_t size);
void *OPENSSL_memdup(void *data, size_t s);
void *OPENSSL_clear_realloc(void *p, size_t old_len, size_t num);
void OPENSSL_clear_free(void *str, size_t num);
void OPENSSL_cleanse(void *ptr, size_t len);
void *CRYPTO_malloc(size_t num, const char *file, int line);
void *CRYPTO_zalloc(size_t num, const char *file, int line);
void *CRYPTO_realloc(void *p, size_t num, const char *file, int line);
void CRYPTO_free(void *str, const char *, int);
char *CRYPTO_strdup(const char *p, const char *file, int line);
char *CRYPTO_strndup(const char *p, size_t num, const char *file, int line);
void *CRYPTO_clear_realloc(void *p, size_t old_len, size_t num,
const char *file, int line);
void CRYPTO_clear_free(void *str, size_t num, const char *, int);
typedef void *(*CRYPTO_malloc_fn)(size_t num, const char *file, int line);
typedef void *(*CRYPTO_realloc_fn)(void *addr, size_t num, const char *file,
int line);
typedef void (*CRYPTO_free_fn)(void *addr, const char *file, int line);
void CRYPTO_get_mem_functions(CRYPTO_malloc_fn *malloc_fn,
CRYPTO_realloc_fn *realloc_fn,
CRYPTO_free_fn *free_fn);
int CRYPTO_set_mem_functions(CRYPTO_malloc_fn malloc_fn,
CRYPTO_realloc_fn realloc_fn,
CRYPTO_free_fn free_fn);
void CRYPTO_get_alloc_counts(int *mcount, int *rcount, int *fcount);
env OPENSSL_MALLOC_FAILURES=... <application>
env OPENSSL_MALLOC_FD=... <application>
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)>:
int CRYPTO_mem_leaks(BIO *b);
int CRYPTO_mem_leaks_fp(FILE *fp);
int CRYPTO_mem_leaks_cb(int (*cb)(const char *str, size_t len, void *u),
void *u);
int CRYPTO_set_mem_debug(int onoff);
int CRYPTO_mem_ctrl(int mode);
int OPENSSL_mem_debug_push(const char *info);
int OPENSSL_mem_debug_pop(void);
int CRYPTO_mem_debug_push(const char *info, const char *file, int line);
int CRYPTO_mem_debug_pop(void);
=head1 DESCRIPTION
OpenSSL memory allocation is handled by the B<OPENSSL_xxx> API. These are
generally macro's that add the standard C B<__FILE__> and B<__LINE__>
parameters and call a lower-level B<CRYPTO_xxx> API.
Some functions do not add those parameters, but exist for consistency.
OPENSSL_malloc_init() does nothing and does not need to be called. It is
included for compatibility with older versions of OpenSSL.
OPENSSL_malloc(), OPENSSL_realloc(), and OPENSSL_free() are like the
C malloc(), realloc(), and free() functions.
OPENSSL_zalloc() calls memset() to zero the memory before returning.
OPENSSL_clear_realloc() and OPENSSL_clear_free() should be used
when the buffer at B<addr> holds sensitive information.
The old buffer is filled with zero's by calling OPENSSL_cleanse()
-before ultimately calling OPENSSL_free().
+before ultimately calling OPENSSL_free(). If the argument to OPENSSL_free() is
+NULL, nothing is done.
OPENSSL_cleanse() fills B<ptr> of size B<len> with a string of 0's.
Use OPENSSL_cleanse() with care if the memory is a mapping of a file.
If the storage controller uses write compression, then it's possible
that sensitive tail bytes will survive zeroization because the block of
zeros will be compressed. If the storage controller uses wear leveling,
then the old sensitive data will not be overwritten; rather, a block of
0's will be written at a new physical location.
OPENSSL_strdup(), OPENSSL_strndup() and OPENSSL_memdup() are like the
equivalent C functions, except that memory is allocated by calling the
OPENSSL_malloc() and should be released by calling OPENSSL_free().
OPENSSL_strlcpy(),
OPENSSL_strlcat() and OPENSSL_strnlen() are equivalents of the common C
library functions and are provided for portability.
If no allocations have been done, it is possible to "swap out" the default
implementations for OPENSSL_malloc(), OPENSSL_realloc() and OPENSSL_free()
and replace them with alternate versions.
CRYPTO_get_mem_functions() function fills in the given arguments with the
function pointers for the current implementations.
With CRYPTO_set_mem_functions(), you can specify a different set of functions.
If any of B<malloc_fn>, B<realloc_fn>, or B<free_fn> are NULL, then
the function is not changed.
While it's permitted to swap out only a few and not all the functions
with CRYPTO_set_mem_functions(), it's recommended to swap them all out
at once.
If the library is built with the C<crypto-mdebug> option, then one
function, CRYPTO_get_alloc_counts(), and two additional environment
variables, B<OPENSSL_MALLOC_FAILURES> and B<OPENSSL_MALLOC_FD>,
are available.
The function CRYPTO_get_alloc_counts() fills in the number of times
each of CRYPTO_malloc(), CRYPTO_realloc(), and CRYPTO_free() have been
called, into the values pointed to by B<mcount>, B<rcount>, and B<fcount>,
respectively. If a pointer is NULL, then the corresponding count is not stored.
The variable
B<OPENSSL_MALLOC_FAILURES> controls how often allocations should fail.
It is a set of fields separated by semicolons, which each field is a count
(defaulting to zero) and an optional atsign and percentage (defaulting
to 100). If the count is zero, then it lasts forever. For example,
C<100;@25> or C<100@0;0@25> means the first 100 allocations pass, then all
other allocations (until the program exits or crashes) have a 25% chance of
failing.
If the variable B<OPENSSL_MALLOC_FD> is parsed as a positive integer, then
it is taken as an open file descriptor. This is used in conjunction with
B<OPENSSL_MALLOC_FAILURES> described above. For every allocation it will log
details about how many allocations there have been so far, what percentage
chance there is for this allocation failing, and whether it has actually failed.
The following example in classic shell syntax shows how to use this (will not
work on all platforms):
OPENSSL_MALLOC_FAILURES='200;@10'
export OPENSSL_MALLOC_FAILURES
OPENSSL_MALLOC_FD=3
export OPENSSL_MALLOC_FD
...app invocation... 3>/tmp/log$$
=head1 RETURN VALUES
OPENSSL_malloc_init(), OPENSSL_free(), OPENSSL_clear_free()
CRYPTO_free(), CRYPTO_clear_free() and CRYPTO_get_mem_functions()
return no value.
OPENSSL_malloc(), OPENSSL_zalloc(), OPENSSL_realloc(),
OPENSSL_clear_realloc(),
CRYPTO_malloc(), CRYPTO_zalloc(), CRYPTO_realloc(),
CRYPTO_clear_realloc(),
OPENSSL_strdup(), and OPENSSL_strndup()
return a pointer to allocated memory or NULL on error.
CRYPTO_set_mem_functions() returns 1 on success or 0 on failure (almost
always because allocations have already happened).
CRYPTO_mem_leaks(), CRYPTO_mem_leaks_fp(), CRYPTO_mem_leaks_cb(),
CRYPTO_set_mem_debug(), and CRYPTO_mem_ctrl() are deprecated and are no-ops that
always return -1.
OPENSSL_mem_debug_push(), OPENSSL_mem_debug_pop(),
CRYPTO_mem_debug_push(), and CRYPTO_mem_debug_pop()
are deprecated and are no-ops that always return 0.
=head1 HISTORY
OPENSSL_mem_debug_push(), OPENSSL_mem_debug_pop(),
CRYPTO_mem_debug_push(), CRYPTO_mem_debug_pop(),
CRYPTO_mem_leaks(), CRYPTO_mem_leaks_fp(),
CRYPTO_mem_leaks_cb(), CRYPTO_set_mem_debug(), CRYPTO_mem_ctrl()
were deprecated in OpenSSL 3.0.
The memory-leak checking has been deprecated in OpenSSL 3.0 in favor of
clang's memory and leak sanitizer.
=head1 COPYRIGHT
-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
L<https://www.openssl.org/source/license.html>.
=cut
diff --git a/crypto/openssl/doc/man3/OPENSSL_secure_malloc.pod b/crypto/openssl/doc/man3/OPENSSL_secure_malloc.pod
index c5d4bb2dbbb8..1bddd7737069 100644
--- a/crypto/openssl/doc/man3/OPENSSL_secure_malloc.pod
+++ b/crypto/openssl/doc/man3/OPENSSL_secure_malloc.pod
@@ -1,143 +1,145 @@
=pod
=head1 NAME
CRYPTO_secure_malloc_init, CRYPTO_secure_malloc_initialized,
CRYPTO_secure_malloc_done, OPENSSL_secure_malloc, CRYPTO_secure_malloc,
OPENSSL_secure_zalloc, CRYPTO_secure_zalloc, OPENSSL_secure_free,
CRYPTO_secure_free, OPENSSL_secure_clear_free,
CRYPTO_secure_clear_free, OPENSSL_secure_actual_size,
CRYPTO_secure_allocated,
CRYPTO_secure_used - secure heap storage
=head1 SYNOPSIS
#include <openssl/crypto.h>
int CRYPTO_secure_malloc_init(size_t size, size_t minsize);
int CRYPTO_secure_malloc_initialized();
int CRYPTO_secure_malloc_done();
void *OPENSSL_secure_malloc(size_t num);
void *CRYPTO_secure_malloc(size_t num, const char *file, int line);
void *OPENSSL_secure_zalloc(size_t num);
void *CRYPTO_secure_zalloc(size_t num, const char *file, int line);
void OPENSSL_secure_free(void* ptr);
void CRYPTO_secure_free(void *ptr, const char *, int);
void OPENSSL_secure_clear_free(void* ptr, size_t num);
void CRYPTO_secure_clear_free(void *ptr, size_t num, const char *, int);
size_t OPENSSL_secure_actual_size(const void *ptr);
int CRYPTO_secure_allocated(const void *ptr);
size_t CRYPTO_secure_used();
=head1 DESCRIPTION
In order to help protect applications (particularly long-running servers)
from pointer overruns or underruns that could return arbitrary data from
the program's dynamic memory area, where keys and other sensitive
information might be stored, OpenSSL supports the concept of a "secure heap."
The level and type of security guarantees depend on the operating system.
It is a good idea to review the code and see if it addresses your
threat model and concerns.
If a secure heap is used, then private key B<BIGNUM> values are stored there.
This protects long-term storage of private keys, but will not necessarily
put all intermediate values and computations there.
CRYPTO_secure_malloc_init() creates the secure heap, with the specified
C<size> in bytes. The C<minsize> parameter is the minimum size to
allocate from the heap or zero to use a reasonable default value.
Both C<size> and, if specified, C<minsize> must be a power of two and
C<minsize> should generally be small, for example 16 or 32.
C<minsize> must be less than a quarter of C<size> in any case.
CRYPTO_secure_malloc_initialized() indicates whether or not the secure
heap as been initialized and is available.
CRYPTO_secure_malloc_done() releases the heap and makes the memory unavailable
to the process if all secure memory has been freed.
It can take noticeably long to complete.
OPENSSL_secure_malloc() allocates C<num> bytes from the heap.
If CRYPTO_secure_malloc_init() is not called, this is equivalent to
calling OPENSSL_malloc().
It is a macro that expands to
CRYPTO_secure_malloc() and adds the C<__FILE__> and C<__LINE__> parameters.
OPENSSL_secure_zalloc() and CRYPTO_secure_zalloc() are like
OPENSSL_secure_malloc() and CRYPTO_secure_malloc(), respectively,
except that they call memset() to zero the memory before returning.
OPENSSL_secure_free() releases the memory at C<ptr> back to the heap.
It must be called with a value previously obtained from
OPENSSL_secure_malloc().
If CRYPTO_secure_malloc_init() is not called, this is equivalent to
calling OPENSSL_free().
It exists for consistency with OPENSSL_secure_malloc() , and
is a macro that expands to CRYPTO_secure_free() and adds the C<__FILE__>
-and C<__LINE__> parameters..
+and C<__LINE__> parameters.. If the argument to OPENSSL_secure_free()
+is NULL, nothing is done.
OPENSSL_secure_clear_free() is similar to OPENSSL_secure_free() except
that it has an additional C<num> parameter which is used to clear
the memory if it was not allocated from the secure heap.
If CRYPTO_secure_malloc_init() is not called, this is equivalent to
-calling OPENSSL_clear_free().
+calling OPENSSL_clear_free(). If the argument to OPENSSL_secure_clear_free()
+is NULL, nothing is done.
OPENSSL_secure_actual_size() tells the actual size allocated to the
pointer; implementations may allocate more space than initially
requested, in order to "round up" and reduce secure heap fragmentation.
OPENSSL_secure_allocated() tells if a pointer is allocated in the secure heap.
CRYPTO_secure_used() returns the number of bytes allocated in the
secure heap.
=head1 RETURN VALUES
CRYPTO_secure_malloc_init() returns 0 on failure, 1 if successful,
and 2 if successful but the heap could not be protected by memory
mapping.
CRYPTO_secure_malloc_initialized() returns 1 if the secure heap is
available (that is, if CRYPTO_secure_malloc_init() has been called,
but CRYPTO_secure_malloc_done() has not been called or failed) or 0 if not.
OPENSSL_secure_malloc() and OPENSSL_secure_zalloc() return a pointer into
the secure heap of the requested size, or C<NULL> if memory could not be
allocated.
CRYPTO_secure_allocated() returns 1 if the pointer is in the secure heap, or 0 if not.
CRYPTO_secure_malloc_done() returns 1 if the secure memory area is released, or 0 if not.
OPENSSL_secure_free() and OPENSSL_secure_clear_free() return no values.
=head1 SEE ALSO
L<OPENSSL_malloc(3)>,
L<BN_new(3)>
=head1 HISTORY
The OPENSSL_secure_clear_free() function was added in OpenSSL 1.1.0g.
The second argument to CRYPTO_secure_malloc_init() was changed from an B<int> to
a B<size_t> in OpenSSL 3.0.
=head1 COPYRIGHT
-Copyright 2015-2020 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
L<https://www.openssl.org/source/license.html>.
=cut
diff --git a/crypto/openssl/doc/man3/OSSL_CMP_CTX_new.pod b/crypto/openssl/doc/man3/OSSL_CMP_CTX_new.pod
index ce7db8f2f086..cab88ae88c91 100644
--- a/crypto/openssl/doc/man3/OSSL_CMP_CTX_new.pod
+++ b/crypto/openssl/doc/man3/OSSL_CMP_CTX_new.pod
@@ -1,806 +1,812 @@
=pod
=head1 NAME
OSSL_CMP_CTX_new,
OSSL_CMP_CTX_free,
OSSL_CMP_CTX_reinit,
OSSL_CMP_CTX_set_option,
OSSL_CMP_CTX_get_option,
OSSL_CMP_CTX_set_log_cb,
OSSL_CMP_CTX_set_log_verbosity,
OSSL_CMP_CTX_print_errors,
OSSL_CMP_CTX_set1_serverPath,
OSSL_CMP_CTX_set1_server,
OSSL_CMP_CTX_set_serverPort,
OSSL_CMP_CTX_set1_proxy,
OSSL_CMP_CTX_set1_no_proxy,
OSSL_CMP_CTX_set_http_cb,
OSSL_CMP_CTX_set_http_cb_arg,
OSSL_CMP_CTX_get_http_cb_arg,
OSSL_CMP_transfer_cb_t,
OSSL_CMP_CTX_set_transfer_cb,
OSSL_CMP_CTX_set_transfer_cb_arg,
OSSL_CMP_CTX_get_transfer_cb_arg,
OSSL_CMP_CTX_set1_srvCert,
OSSL_CMP_CTX_set1_expected_sender,
OSSL_CMP_CTX_set0_trustedStore,
OSSL_CMP_CTX_get0_trustedStore,
OSSL_CMP_CTX_set1_untrusted,
OSSL_CMP_CTX_get0_untrusted,
OSSL_CMP_CTX_set1_cert,
OSSL_CMP_CTX_build_cert_chain,
OSSL_CMP_CTX_set1_pkey,
OSSL_CMP_CTX_set1_referenceValue,
OSSL_CMP_CTX_set1_secretValue,
OSSL_CMP_CTX_set1_recipient,
OSSL_CMP_CTX_push0_geninfo_ITAV,
OSSL_CMP_CTX_reset_geninfo_ITAVs,
OSSL_CMP_CTX_set1_extraCertsOut,
OSSL_CMP_CTX_set0_newPkey,
OSSL_CMP_CTX_get0_newPkey,
OSSL_CMP_CTX_set1_issuer,
OSSL_CMP_CTX_set1_subjectName,
OSSL_CMP_CTX_push1_subjectAltName,
OSSL_CMP_CTX_set0_reqExtensions,
OSSL_CMP_CTX_reqExtensions_have_SAN,
OSSL_CMP_CTX_push0_policy,
OSSL_CMP_CTX_set1_oldCert,
OSSL_CMP_CTX_set1_p10CSR,
OSSL_CMP_CTX_push0_genm_ITAV,
OSSL_CMP_certConf_cb_t,
OSSL_CMP_certConf_cb,
OSSL_CMP_CTX_set_certConf_cb,
OSSL_CMP_CTX_set_certConf_cb_arg,
OSSL_CMP_CTX_get_certConf_cb_arg,
OSSL_CMP_CTX_get_status,
OSSL_CMP_CTX_get0_statusString,
OSSL_CMP_CTX_get_failInfoCode,
OSSL_CMP_CTX_get0_newCert,
OSSL_CMP_CTX_get1_newChain,
OSSL_CMP_CTX_get1_caPubs,
OSSL_CMP_CTX_get1_extraCertsIn,
OSSL_CMP_CTX_set1_transactionID,
OSSL_CMP_CTX_set1_senderNonce
- functions for managing the CMP client context data structure
=head1 SYNOPSIS
#include <openssl/cmp.h>
OSSL_CMP_CTX *OSSL_CMP_CTX_new(OSSL_LIB_CTX *libctx, const char *propq);
void OSSL_CMP_CTX_free(OSSL_CMP_CTX *ctx);
int OSSL_CMP_CTX_reinit(OSSL_CMP_CTX *ctx);
int OSSL_CMP_CTX_set_option(OSSL_CMP_CTX *ctx, int opt, int val);
int OSSL_CMP_CTX_get_option(const OSSL_CMP_CTX *ctx, int opt);
/* logging and error reporting: */
int OSSL_CMP_CTX_set_log_cb(OSSL_CMP_CTX *ctx, OSSL_CMP_log_cb_t cb);
#define OSSL_CMP_CTX_set_log_verbosity(ctx, level)
void OSSL_CMP_CTX_print_errors(const OSSL_CMP_CTX *ctx);
/* message transfer: */
int OSSL_CMP_CTX_set1_serverPath(OSSL_CMP_CTX *ctx, const char *path);
int OSSL_CMP_CTX_set1_server(OSSL_CMP_CTX *ctx, const char *address);
int OSSL_CMP_CTX_set_serverPort(OSSL_CMP_CTX *ctx, int port);
int OSSL_CMP_CTX_set1_proxy(OSSL_CMP_CTX *ctx, const char *name);
int OSSL_CMP_CTX_set1_no_proxy(OSSL_CMP_CTX *ctx, const char *names);
int OSSL_CMP_CTX_set_http_cb(OSSL_CMP_CTX *ctx, HTTP_bio_cb_t cb);
int OSSL_CMP_CTX_set_http_cb_arg(OSSL_CMP_CTX *ctx, void *arg);
void *OSSL_CMP_CTX_get_http_cb_arg(const OSSL_CMP_CTX *ctx);
typedef OSSL_CMP_MSG *(*OSSL_CMP_transfer_cb_t)(OSSL_CMP_CTX *ctx,
const OSSL_CMP_MSG *req);
int OSSL_CMP_CTX_set_transfer_cb(OSSL_CMP_CTX *ctx,
OSSL_CMP_transfer_cb_t cb);
int OSSL_CMP_CTX_set_transfer_cb_arg(OSSL_CMP_CTX *ctx, void *arg);
void *OSSL_CMP_CTX_get_transfer_cb_arg(const OSSL_CMP_CTX *ctx);
/* server authentication: */
int OSSL_CMP_CTX_set1_srvCert(OSSL_CMP_CTX *ctx, X509 *cert);
int OSSL_CMP_CTX_set1_expected_sender(OSSL_CMP_CTX *ctx,
const X509_NAME *name);
int OSSL_CMP_CTX_set0_trustedStore(OSSL_CMP_CTX *ctx, X509_STORE *store);
X509_STORE *OSSL_CMP_CTX_get0_trustedStore(const OSSL_CMP_CTX *ctx);
int OSSL_CMP_CTX_set1_untrusted(OSSL_CMP_CTX *ctx, STACK_OF(X509) *certs);
STACK_OF(X509) *OSSL_CMP_CTX_get0_untrusted(const OSSL_CMP_CTX *ctx);
/* client authentication: */
int OSSL_CMP_CTX_set1_cert(OSSL_CMP_CTX *ctx, X509 *cert);
int OSSL_CMP_CTX_build_cert_chain(OSSL_CMP_CTX *ctx, X509_STORE *own_trusted,
STACK_OF(X509) *candidates);
int OSSL_CMP_CTX_set1_pkey(OSSL_CMP_CTX *ctx, EVP_PKEY *pkey);
int OSSL_CMP_CTX_set1_referenceValue(OSSL_CMP_CTX *ctx,
const unsigned char *ref, int len);
int OSSL_CMP_CTX_set1_secretValue(OSSL_CMP_CTX *ctx,
const unsigned char *sec, int len);
/* CMP message header and extra certificates: */
int OSSL_CMP_CTX_set1_recipient(OSSL_CMP_CTX *ctx, const X509_NAME *name);
int OSSL_CMP_CTX_push0_geninfo_ITAV(OSSL_CMP_CTX *ctx, OSSL_CMP_ITAV *itav);
int OSSL_CMP_CTX_reset_geninfo_ITAVs(OSSL_CMP_CTX *ctx);
int OSSL_CMP_CTX_set1_extraCertsOut(OSSL_CMP_CTX *ctx,
STACK_OF(X509) *extraCertsOut);
/* certificate template: */
int OSSL_CMP_CTX_set0_newPkey(OSSL_CMP_CTX *ctx, int priv, EVP_PKEY *pkey);
EVP_PKEY *OSSL_CMP_CTX_get0_newPkey(const OSSL_CMP_CTX *ctx, int priv);
int OSSL_CMP_CTX_set1_issuer(OSSL_CMP_CTX *ctx, const X509_NAME *name);
int OSSL_CMP_CTX_set1_subjectName(OSSL_CMP_CTX *ctx, const X509_NAME *name);
int OSSL_CMP_CTX_push1_subjectAltName(OSSL_CMP_CTX *ctx,
const GENERAL_NAME *name);
int OSSL_CMP_CTX_set0_reqExtensions(OSSL_CMP_CTX *ctx, X509_EXTENSIONS *exts);
int OSSL_CMP_CTX_reqExtensions_have_SAN(OSSL_CMP_CTX *ctx);
int OSSL_CMP_CTX_push0_policy(OSSL_CMP_CTX *ctx, POLICYINFO *pinfo);
int OSSL_CMP_CTX_set1_oldCert(OSSL_CMP_CTX *ctx, X509 *cert);
int OSSL_CMP_CTX_set1_p10CSR(OSSL_CMP_CTX *ctx, const X509_REQ *csr);
/* misc body contents: */
int OSSL_CMP_CTX_push0_genm_ITAV(OSSL_CMP_CTX *ctx, OSSL_CMP_ITAV *itav);
/* certificate confirmation: */
typedef int (*OSSL_CMP_certConf_cb_t)(OSSL_CMP_CTX *ctx, X509 *cert,
int fail_info, const char **txt);
int OSSL_CMP_certConf_cb(OSSL_CMP_CTX *ctx, X509 *cert, int fail_info,
const char **text);
int OSSL_CMP_CTX_set_certConf_cb(OSSL_CMP_CTX *ctx, OSSL_CMP_certConf_cb_t cb);
int OSSL_CMP_CTX_set_certConf_cb_arg(OSSL_CMP_CTX *ctx, void *arg);
void *OSSL_CMP_CTX_get_certConf_cb_arg(const OSSL_CMP_CTX *ctx);
/* result fetching: */
int OSSL_CMP_CTX_get_status(const OSSL_CMP_CTX *ctx);
OSSL_CMP_PKIFREETEXT *OSSL_CMP_CTX_get0_statusString(const OSSL_CMP_CTX *ctx);
int OSSL_CMP_CTX_get_failInfoCode(const OSSL_CMP_CTX *ctx);
X509 *OSSL_CMP_CTX_get0_newCert(const OSSL_CMP_CTX *ctx);
STACK_OF(X509) *OSSL_CMP_CTX_get1_newChain(const OSSL_CMP_CTX *ctx);
STACK_OF(X509) *OSSL_CMP_CTX_get1_caPubs(const OSSL_CMP_CTX *ctx);
STACK_OF(X509) *OSSL_CMP_CTX_get1_extraCertsIn(const OSSL_CMP_CTX *ctx);
/* for testing and debugging purposes: */
int OSSL_CMP_CTX_set1_transactionID(OSSL_CMP_CTX *ctx,
const ASN1_OCTET_STRING *id);
int OSSL_CMP_CTX_set1_senderNonce(OSSL_CMP_CTX *ctx,
const ASN1_OCTET_STRING *nonce);
=head1 DESCRIPTION
This is the context API for using CMP (Certificate Management Protocol) with
OpenSSL.
OSSL_CMP_CTX_new() allocates an B<OSSL_CMP_CTX> structure associated with
the library context I<libctx> and property query string I<propq>,
both of which may be NULL to select the defaults.
It initializes the remaining fields to their default values - for instance,
the logging verbosity is set to OSSL_CMP_LOG_INFO,
the message timeout is set to 120 seconds,
and the proof-of-possession method is set to OSSL_CRMF_POPO_SIGNATURE.
OSSL_CMP_CTX_free() deallocates an OSSL_CMP_CTX structure.
+If the argument is NULL, nothing is done.
OSSL_CMP_CTX_reinit() prepares the given I<ctx> for a further transaction by
clearing the internal CMP transaction (aka session) status, PKIStatusInfo,
and any previous results (newCert, newChain, caPubs, and extraCertsIn)
from the last executed transaction.
It also clears any ITAVs that were added by OSSL_CMP_CTX_push0_genm_ITAV().
All other field values (i.e., CMP options) are retained for potential reuse.
OSSL_CMP_CTX_set_option() sets the given value for the given option
(e.g., OSSL_CMP_OPT_IMPLICIT_CONFIRM) in the given OSSL_CMP_CTX structure.
The following options can be set:
=over 4
=item B<OSSL_CMP_OPT_LOG_VERBOSITY>
The level of severity needed for actually outputting log messages
due to errors, warnings, general info, debugging, etc.
Default is OSSL_CMP_LOG_INFO. See also L<OSSL_CMP_log_open(3)>.
=item B<OSSL_CMP_OPT_KEEP_ALIVE>
If the given value is 0 then HTTP connections are not kept open
after receiving a response, which is the default behavior for HTTP 1.0.
If the value is 1 or 2 then persistent connections are requested.
If the value is 2 then persistent connections are required,
i.e., in case the server does not grant them an error occurs.
The default value is 1: prefer to keep the connection open.
=item B<OSSL_CMP_OPT_MSG_TIMEOUT>
Number of seconds a CMP request-response message round trip
is allowed to take before a timeout error is returned.
A value <= 0 means no limitation (waiting indefinitely).
Default is to use the B<OSSL_CMP_OPT_TOTAL_TIMEOUT> setting.
=item B<OSSL_CMP_OPT_TOTAL_TIMEOUT>
Maximum total number of seconds a transaction may take,
including polling etc.
A value <= 0 means no limitation (waiting indefinitely).
Default is 0.
=item B<OSSL_CMP_OPT_VALIDITY_DAYS>
Number of days new certificates are asked to be valid for.
=item B<OSSL_CMP_OPT_SUBJECTALTNAME_NODEFAULT>
Do not take default Subject Alternative Names
from the reference certificate.
=item B<OSSL_CMP_OPT_SUBJECTALTNAME_CRITICAL>
Demand that the given Subject Alternative Names are flagged as critical.
=item B<OSSL_CMP_OPT_POLICIES_CRITICAL>
Demand that the given policies are flagged as critical.
=item B<OSSL_CMP_OPT_POPO_METHOD>
Select the proof of possession method to use. Possible values are:
OSSL_CRMF_POPO_NONE - ProofOfPossession field omitted
OSSL_CRMF_POPO_RAVERIFIED - assert that the RA has already
verified the PoPo
OSSL_CRMF_POPO_SIGNATURE - sign a value with private key,
which is the default.
OSSL_CRMF_POPO_KEYENC - decrypt the encrypted certificate
("indirect method")
Note that a signature-based POPO can only be produced if a private key
is provided as the newPkey or client's pkey component of the CMP context.
=item B<OSSL_CMP_OPT_DIGEST_ALGNID>
The NID of the digest algorithm to be used in RFC 4210's MSG_SIG_ALG
for signature-based message protection and Proof-of-Possession (POPO).
Default is SHA256.
=item B<OSSL_CMP_OPT_OWF_ALGNID>
The NID of the digest algorithm to be used as one-way function (OWF)
for MAC-based message protection with password-based MAC (PBM).
See RFC 4210 section 5.1.3.1 for details.
Default is SHA256.
=item B<OSSL_CMP_OPT_MAC_ALGNID>
The NID of the MAC algorithm to be used for message protection with PBM.
Default is HMAC-SHA1 as per RFC 4210.
=item B<OSSL_CMP_OPT_REVOCATION_REASON>
The reason code to be included in a Revocation Request (RR);
values: 0..10 (RFC 5210, 5.3.1) or -1 for none, which is the default.
=item B<OSSL_CMP_OPT_IMPLICIT_CONFIRM>
Request server to enable implicit confirm mode, where the client
does not need to send confirmation upon receiving the
certificate. If the server does not enable implicit confirmation
in the return message, then confirmation is sent anyway.
=item B<OSSL_CMP_OPT_DISABLE_CONFIRM>
Do not confirm enrolled certificates, to cope with broken servers
not supporting implicit confirmation correctly.
B<WARNING:> This setting leads to unspecified behavior and it is meant
exclusively to allow interoperability with server implementations violating
RFC 4210.
=item B<OSSL_CMP_OPT_UNPROTECTED_SEND>
Send request or response messages without CMP-level protection.
=item B<OSSL_CMP_OPT_UNPROTECTED_ERRORS>
Accept unprotected error responses which are either explicitly
unprotected or where protection verification failed. Applies to regular
error messages as well as certificate responses (IP/CP/KUP) and
revocation responses (RP) with rejection.
B<WARNING:> This setting leads to unspecified behavior and it is meant
exclusively to allow interoperability with server implementations violating
RFC 4210.
=item B<OSSL_CMP_OPT_IGNORE_KEYUSAGE>
Ignore key usage restrictions in the signer's certificate when
validating signature-based protection in received CMP messages.
Else, 'digitalSignature' must be allowed by CMP signer certificates.
=item B<OSSL_CMP_OPT_PERMIT_TA_IN_EXTRACERTS_FOR_IR>
Allow retrieving a trust anchor from extraCerts and using that
to validate the certificate chain of an IP message.
+ This is a quirk option added to support 3GPP TS 33.310.
+
+ Note that using this option is dangerous as the certificate obtained
+ this way has not been authenticated (at least not at CMP level).
+ Taking it over as a trust anchor implements trust-on-first-use (TOFU).
=back
OSSL_CMP_CTX_get_option() reads the current value of the given option
(e.g., OSSL_CMP_OPT_IMPLICIT_CONFIRM) from the given OSSL_CMP_CTX structure.
OSSL_CMP_CTX_set_log_cb() sets in I<ctx> the callback function I<cb>
for handling error queue entries and logging messages.
When I<cb> is NULL errors are printed to STDERR (if available, else ignored)
any log messages are ignored.
Alternatively, L<OSSL_CMP_log_open(3)> may be used to direct logging to STDOUT.
OSSL_CMP_CTX_set_log_verbosity() is a macro setting the
OSSL_CMP_OPT_LOG_VERBOSITY context option to the given level.
OSSL_CMP_CTX_print_errors() outputs any entries in the OpenSSL error queue. It
is similar to L<ERR_print_errors_cb(3)> but uses the CMP log callback function
if set in the I<ctx> for uniformity with CMP logging if given. Otherwise it uses
L<ERR_print_errors(3)> to print to STDERR (unless OPENSSL_NO_STDIO is defined).
OSSL_CMP_CTX_set1_serverPath() sets the HTTP path of the CMP server on the host,
also known as "CMP alias".
The default is C</>.
OSSL_CMP_CTX_set1_server() sets the given server I<address>
(which may be a hostname or IP address or NULL) in the given I<ctx>.
OSSL_CMP_CTX_set_serverPort() sets the port of the CMP server to connect to.
If not used or the I<port> argument is 0
the default port applies, which is 80 for HTTP and 443 for HTTPS.
OSSL_CMP_CTX_set1_proxy() sets the HTTP proxy to be used for connecting to
the given CMP server unless overruled by any "no_proxy" settings (see below).
If TLS is not used this defaults to the value of
the environment variable C<http_proxy> if set, else C<HTTP_PROXY>.
Otherwise defaults to the value of C<https_proxy> if set, else C<HTTPS_PROXY>.
An empty proxy string specifies not to use a proxy.
Else the format is C<[http[s]://]address[:port][/path]>,
where any path given is ignored.
The default port number is 80, or 443 in case C<https:> is given.
OSSL_CMP_CTX_set1_no_proxy() sets the list of server hostnames not to use
an HTTP proxy for. The names may be separated by commas and/or whitespace.
Defaults to the environment variable C<no_proxy> if set, else C<NO_PROXY>.
OSSL_CMP_CTX_set_http_cb() sets the optional BIO connect/disconnect callback
function, which has the prototype
typedef BIO *(*HTTP_bio_cb_t) (BIO *bio, void *ctx, int connect, int detail);
The callback may modify the I<bio> provided by L<OSSL_CMP_MSG_http_perform(3)>,
whereby it may make use of a custom defined argument I<ctx>
stored in the OSSL_CMP_CTX by means of OSSL_CMP_CTX_set_http_cb_arg().
During connection establishment, just after calling BIO_do_connect_retry(),
the function is invoked with the I<connect> argument being 1 and the I<detail>
argument being 1 if HTTPS is requested, i.e., SSL/TLS should be enabled. On
disconnect I<connect> is 0 and I<detail> is 1 in case no error occurred, else 0.
For instance, on connect the function may prepend a TLS BIO to implement HTTPS;
after disconnect it may do some diagnostic output and/or specific cleanup.
The function should return NULL to indicate failure.
After disconnect the modified BIO will be deallocated using BIO_free_all().
OSSL_CMP_CTX_set_http_cb_arg() sets an argument, respectively a pointer to
a structure containing arguments,
optionally to be used by the http connect/disconnect callback function.
I<arg> is not consumed, and it must therefore explicitly be freed when not
needed any more. I<arg> may be NULL to clear the entry.
OSSL_CMP_CTX_get_http_cb_arg() gets the argument, respectively the pointer to a
structure containing arguments, previously set by
OSSL_CMP_CTX_set_http_cb_arg() or NULL if unset.
OSSL_CMP_CTX_set_transfer_cb() sets the message transfer callback function,
which has the type
typedef OSSL_CMP_MSG *(*OSSL_CMP_transfer_cb_t) (OSSL_CMP_CTX *ctx,
const OSSL_CMP_MSG *req);
Returns 1 on success, 0 on error.
Default is NULL, which implies the use of L<OSSL_CMP_MSG_http_perform(3)>.
The callback should send the CMP request message it obtains via the I<req>
parameter and on success return the response, else it must return NULL.
The transfer callback may make use of a custom defined argument stored in
the ctx by means of OSSL_CMP_CTX_set_transfer_cb_arg(), which may be retrieved
again through OSSL_CMP_CTX_get_transfer_cb_arg().
OSSL_CMP_CTX_set_transfer_cb_arg() sets an argument, respectively a pointer to a
structure containing arguments, optionally to be used by the transfer callback.
I<arg> is not consumed, and it must therefore explicitly be freed when not
needed any more. I<arg> may be NULL to clear the entry.
OSSL_CMP_CTX_get_transfer_cb_arg() gets the argument, respectively the pointer
to a structure containing arguments, previously set by
OSSL_CMP_CTX_set_transfer_cb_arg() or NULL if unset.
OSSL_CMP_CTX_set1_srvCert() sets the expected server cert in I<ctx> and trusts
it directly (even if it is expired) when verifying signed response messages.
This pins the accepted CMP server and
results in ignoring whatever may be set using OSSL_CMP_CTX_set0_trustedStore().
Any previously set value is freed.
The I<cert> argument may be NULL to clear the entry.
If set, the subject of the certificate is also used
as default value for the recipient of CMP requests
and as default value for the expected sender of CMP responses.
OSSL_CMP_CTX_set1_expected_sender() sets the Distinguished Name (DN)
expected in the sender field of incoming CMP messages.
Defaults to the subject of the pinned server certificate, if any.
This can be used to make sure that only a particular entity is accepted as
CMP message signer, and attackers are not able to use arbitrary certificates
of a trusted PKI hierarchy to fraudulently pose as CMP server.
Note that this gives slightly more freedom than OSSL_CMP_CTX_set1_srvCert(),
which pins the server to the holder of a particular certificate, while the
expected sender name will continue to match after updates of the server cert.
OSSL_CMP_CTX_set0_trustedStore()
sets in the CMP context I<ctx> the certificate store of type X509_STORE
containing trusted certificates, typically of root CAs.
This is ignored when a certificate is pinned using OSSL_CMP_CTX_set1_srvCert().
The store may also hold CRLs and a certificate verification callback function
used for signature-based peer authentication.
Any store entry already set before is freed.
When given a NULL parameter the entry is cleared.
OSSL_CMP_CTX_get0_trustedStore()
extracts from the CMP context I<ctx> the pointer to the currently set
certificate store containing trust anchors etc., or an empty store if unset.
OSSL_CMP_CTX_set1_untrusted() sets up a list of non-trusted certificates
of intermediate CAs that may be useful for path construction for the own CMP
signer certificate, for the own TLS certificate (if any), when verifying peer
CMP protection certificates, and when verifying newly enrolled certificates.
The reference counts of those certificates handled successfully are increased.
OSSL_CMP_CTX_get0_untrusted(OSSL_CMP_CTX *ctx) returns a pointer to the
list of untrusted certs, which may be empty if unset.
OSSL_CMP_CTX_set1_cert() sets the CMP signer certificate, also called protection
certificate, related to the private key for signature-based message protection.
Therefore the public key of this I<cert> must correspond to
the private key set before or thereafter via OSSL_CMP_CTX_set1_pkey().
When using signature-based protection of CMP request messages
this CMP signer certificate will be included first in the extraCerts field.
It serves as fallback reference certificate, see OSSL_CMP_CTX_set1_oldCert().
The subject of this I<cert> will be used as the sender field of outgoing
messages, while the subject of any cert set via OSSL_CMP_CTX_set1_oldCert()
and any value set via OSSL_CMP_CTX_set1_subjectName() are used as fallback.
The I<cert> argument may be NULL to clear the entry.
OSSL_CMP_CTX_build_cert_chain() builds a certificate chain for the CMP signer
certificate previously set in the I<ctx>. It adds the optional I<candidates>,
a list of intermediate CA certs that may already constitute the targeted chain,
to the untrusted certs that may already exist in the I<ctx>.
Then the function uses this augmented set of certs for chain construction.
If I<own_trusted> is NULL it builds the chain as far down as possible and
ignores any verification errors. Else the CMP signer certificate must be
verifiable where the chain reaches a trust anchor contained in I<own_trusted>.
On success the function stores the resulting chain in I<ctx>
for inclusion in the extraCerts field of signature-protected messages.
Calling this function is optional; by default a chain construction
is performed on demand that is equivalent to calling this function
with the I<candidates> and I<own_trusted> arguments being NULL.
OSSL_CMP_CTX_set1_pkey() sets the client's private key corresponding to the
CMP signer certificate set via OSSL_CMP_CTX_set1_cert().
This key is used create signature-based protection (protectionAlg = MSG_SIG_ALG)
of outgoing messages
unless a symmetric secret has been set via OSSL_CMP_CTX_set1_secretValue().
The I<pkey> argument may be NULL to clear the entry.
OSSL_CMP_CTX_set1_secretValue() sets in I<ctx> the byte string I<sec> of length
I<len> to use as pre-shared secret, or clears it if the I<sec> argument is NULL.
If present, this secret is used to create MAC-based authentication and integrity
protection (rather than applying signature-based protection)
of outgoing messages and to verify authenticity and integrity of incoming
messages that have MAC-based protection (protectionAlg = C<MSG_MAC_ALG>).
OSSL_CMP_CTX_set1_referenceValue() sets the given referenceValue I<ref> with
length I<len> in the given I<ctx> or clears it if the I<ref> argument is NULL.
According to RFC 4210 section 5.1.1, if no value for the sender field in
CMP message headers can be determined (i.e., no CMP signer certificate
and no subject DN is set via OSSL_CMP_CTX_set1_subjectName()
then the sender field will contain the NULL-DN
and the senderKID field of the CMP message header must be set.
When signature-based protection is used the senderKID will be set to
the subjectKeyIdentifier of the CMP signer certificate as far as present.
If not present or when MAC-based protection is used
the I<ref> value is taken as the fallback value for the senderKID.
OSSL_CMP_CTX_set1_recipient() sets the recipient name that will be used in the
PKIHeader of CMP request messages, i.e. the X509 name of the (CA) server.
The recipient field in the header of a CMP message is mandatory.
If not given explicitly the recipient is determined in the following order:
the subject of the CMP server certificate set using OSSL_CMP_CTX_set1_srvCert(),
the value set using OSSL_CMP_CTX_set1_issuer(),
the issuer of the certificate set using OSSL_CMP_CTX_set1_oldCert(),
the issuer of the CMP signer certificate,
as far as any of those is present, else the NULL-DN as last resort.
OSSL_CMP_CTX_push0_geninfo_ITAV() adds I<itav> to the stack in the I<ctx> to be
added to the GeneralInfo field of the CMP PKIMessage header of a request
message sent with this context.
OSSL_CMP_CTX_reset_geninfo_ITAVs()
clears any ITAVs that were added by OSSL_CMP_CTX_push0_geninfo_ITAV().
OSSL_CMP_CTX_set1_extraCertsOut() sets the stack of extraCerts that will be
sent to remote.
OSSL_CMP_CTX_set0_newPkey() can be used to explicitly set the given EVP_PKEY
structure as the private or public key to be certified in the CMP context.
The I<priv> parameter must be 0 if and only if the given key is a public key.
OSSL_CMP_CTX_get0_newPkey() gives the key to use for certificate enrollment
dependent on fields of the CMP context structure:
the newPkey (which may be a private or public key) if present,
else the public key in the p10CSR if present, else the client's private key.
If the I<priv> parameter is not 0 and the selected key does not have a
private component then NULL is returned.
OSSL_CMP_CTX_set1_issuer() sets the name of the intended issuer that
will be set in the CertTemplate, i.e., the X509 name of the CA server.
OSSL_CMP_CTX_set1_subjectName() sets the subject DN that will be used in
the CertTemplate structure when requesting a new cert. For Key Update Requests
(KUR), it defaults to the subject DN of the reference certificate,
see OSSL_CMP_CTX_set1_oldCert(). This default is used for Initialization
Requests (IR) and Certification Requests (CR) only if no SANs are set.
The I<subjectName> is also used as fallback for the sender field
of outgoing CMP messages if no reference certificate is available.
OSSL_CMP_CTX_push1_subjectAltName() adds the given X509 name to the list of
alternate names on the certificate template request. This cannot be used if
any Subject Alternative Name extension is set via
OSSL_CMP_CTX_set0_reqExtensions().
By default, unless B<OSSL_CMP_OPT_SUBJECTALTNAME_NODEFAULT> has been set,
the Subject Alternative Names are copied from the reference certificate,
see OSSL_CMP_CTX_set1_oldCert().
If set and the subject DN is not set with OSSL_CMP_CTX_set1_subjectName() then
the certificate template of an IR and CR will not be filled with the default
subject DN from the reference certificate.
If a subject DN is desired it needs to be set explicitly with
OSSL_CMP_CTX_set1_subjectName().
OSSL_CMP_CTX_set0_reqExtensions() sets the X.509v3 extensions to be used in
IR/CR/KUR.
OSSL_CMP_CTX_reqExtensions_have_SAN() returns 1 if the context contains
a Subject Alternative Name extension, else 0 or -1 on error.
OSSL_CMP_CTX_push0_policy() adds the certificate policy info object
to the X509_EXTENSIONS of the requested certificate template.
OSSL_CMP_CTX_set1_oldCert() sets the old certificate to be updated in
Key Update Requests (KUR) or to be revoked in Revocation Requests (RR).
It must be given for RR, else it defaults to the CMP signer certificate.
The I<reference certificate> determined in this way, if any, is also used for
deriving default subject DN, public key, Subject Alternative Names, and the
default issuer entry in the requested certificate template of IR/CR/KUR.
The subject of the reference certificate is used as the sender field value
in CMP message headers.
Its issuer is used as default recipient in CMP message headers.
OSSL_CMP_CTX_set1_p10CSR() sets the PKCS#10 CSR to use in P10CR messages.
If such a CSR is provided, its subject, public key, and extension fields are
also used as fallback values for the certificate template of IR/CR/KUR messages.
OSSL_CMP_CTX_push0_genm_ITAV() adds I<itav> to the stack in the I<ctx> which
will be the body of a General Message sent with this context.
OSSL_CMP_certConf_cb() is the default certificate confirmation callback function.
If the callback argument is not NULL it must point to a trust store.
In this case the function checks that the newly enrolled certificate can be
verified using this trust store and untrusted certificates from the I<ctx>,
which have been augmented by the list of extraCerts received.
During this verification, any certificate status checking is disabled.
If the callback argument is NULL the function tries building an approximate
chain as far as possible using the same untrusted certificates from the I<ctx>,
and if this fails it takes the received extraCerts as fallback.
The resulting cert chain can be retrieved using OSSL_CMP_CTX_get1_newChain().
OSSL_CMP_CTX_set_certConf_cb() sets the callback used for evaluating the newly
enrolled certificate before the library sends, depending on its result,
a positive or negative certConf message to the server. The callback has type
typedef int (*OSSL_CMP_certConf_cb_t) (OSSL_CMP_CTX *ctx, X509 *cert,
int fail_info, const char **txt);
and should inspect the certificate it obtains via the I<cert> parameter and may
overrule the pre-decision given in the I<fail_info> and I<*txt> parameters.
If it accepts the certificate it must return 0, indicating success. Else it must
return a bit field reflecting PKIFailureInfo with at least one failure bit and
may set the I<*txt> output parameter to point to a string constant with more
detail. The transfer callback may make use of a custom defined argument stored
in the I<ctx> by means of OSSL_CMP_CTX_set_certConf_cb_arg(), which may be
retrieved again through OSSL_CMP_CTX_get_certConf_cb_arg().
Typically, the callback will check at least that the certificate can be verified
using a set of trusted certificates.
It also could compare the subject DN and other fields of the newly
enrolled certificate with the certificate template of the request.
OSSL_CMP_CTX_set_certConf_cb_arg() sets an argument, respectively a pointer to a
structure containing arguments, optionally to be used by the certConf callback.
I<arg> is not consumed, and it must therefore explicitly be freed when not
needed any more. I<arg> may be NULL to clear the entry.
OSSL_CMP_CTX_get_certConf_cb_arg() gets the argument, respectively the pointer
to a structure containing arguments, previously set by
OSSL_CMP_CTX_set_certConf_cb_arg(), or NULL if unset.
OSSL_CMP_CTX_get_status() returns for client contexts the PKIstatus from
the last received CertRepMessage or Revocation Response or error message:
=item B<OSSL_CMP_PKISTATUS_accepted> on successful receipt of a GENP message:
=over 4
=item B<OSSL_CMP_PKISTATUS_request>
if an IR/CR/KUR/RR/GENM request message could not be produced,
=item B<OSSL_CMP_PKISTATUS_trans>
on a transmission error or transaction error for this type of request, and
=item B<OSSL_CMP_PKISTATUS_unspecified>
if no such request was attempted or OSSL_CMP_CTX_reinit() has been called.
=back
For server contexts it returns
B<OSSL_CMP_PKISTATUS_trans> if a transaction is open,
otherwise B<OSSL_CMP_PKISTATUS_unspecified>.
OSSL_CMP_CTX_get0_statusString() returns the statusString from the last received
CertRepMessage or Revocation Response or error message, or NULL if unset.
OSSL_CMP_CTX_get_failInfoCode() returns the error code from the failInfo field
of the last received CertRepMessage or Revocation Response or error message,
or -1 if no such response was received or OSSL_CMP_CTX_reinit() has been called.
This is a bit field and the flags for it are specified in the header file
F<< <openssl/cmp.h> >>.
The flags start with OSSL_CMP_CTX_FAILINFO, for example:
OSSL_CMP_CTX_FAILINFO_badAlg. Returns -1 if the failInfoCode field is unset.
OSSL_CMP_CTX_get0_newCert() returns the pointer to the newly obtained
certificate in case it is available, else NULL.
OSSL_CMP_CTX_get1_newChain() returns a pointer to a duplicate of the stack of
X.509 certificates computed by OSSL_CMP_certConf_cb() (if this function has
been called) on the last received certificate response message IP/CP/KUP.
OSSL_CMP_CTX_get1_caPubs() returns a pointer to a duplicate of the list of
X.509 certificates in the caPubs field of the last received certificate
response message (of type IP, CP, or KUP),
or an empty stack if no caPubs have been received in the current transaction.
OSSL_CMP_CTX_get1_extraCertsIn() returns a pointer to a duplicate of the list
of X.509 certificates contained in the extraCerts field of the last received
response message (except for pollRep and PKIConf), or
an empty stack if no extraCerts have been received in the current transaction.
OSSL_CMP_CTX_set1_transactionID() sets the given transaction ID in the given
OSSL_CMP_CTX structure.
OSSL_CMP_CTX_set1_senderNonce() stores the last sent sender I<nonce> in
the I<ctx>. This will be used to validate the recipNonce in incoming messages.
=head1 NOTES
CMP is defined in RFC 4210 (and CRMF in RFC 4211).
=head1 RETURN VALUES
OSSL_CMP_CTX_free() and OSSL_CMP_CTX_print_errors() do not return anything.
OSSL_CMP_CTX_new(),
OSSL_CMP_CTX_get_http_cb_arg(),
OSSL_CMP_CTX_get_transfer_cb_arg(),
OSSL_CMP_CTX_get0_trustedStore(),
OSSL_CMP_CTX_get0_untrusted(),
OSSL_CMP_CTX_get0_newPkey(),
OSSL_CMP_CTX_get_certConf_cb_arg(),
OSSL_CMP_CTX_get0_statusString(),
OSSL_CMP_CTX_get0_newCert(),
OSSL_CMP_CTX_get0_newChain(),
OSSL_CMP_CTX_get1_caPubs(), and
OSSL_CMP_CTX_get1_extraCertsIn()
return the intended pointer value as described above or NULL on error.
OSSL_CMP_CTX_get_option(),
OSSL_CMP_CTX_reqExtensions_have_SAN(),
OSSL_CMP_CTX_get_status(), and
OSSL_CMP_CTX_get_failInfoCode()
return the intended value as described above or -1 on error.
OSSL_CMP_certConf_cb() returns I<fail_info> if it is not equal to 0,
else 0 on successful validation,
or else a bit field with the B<OSSL_CMP_PKIFAILUREINFO_incorrectData> bit set.
All other functions, including OSSL_CMP_CTX_reinit()
and OSSL_CMP_CTX_reset_geninfo_ITAVs(),
return 1 on success, 0 on error.
=head1 EXAMPLES
The following code omits error handling.
Set up a CMP client context for sending requests and verifying responses:
cmp_ctx = OSSL_CMP_CTX_new();
OSSL_CMP_CTX_set1_server(cmp_ctx, name_or_address);
OSSL_CMP_CTX_set1_serverPort(cmp_ctx, port_string);
OSSL_CMP_CTX_set1_serverPath(cmp_ctx, path_or_alias);
OSSL_CMP_CTX_set0_trustedStore(cmp_ctx, ts);
Set up symmetric credentials for MAC-based message protection such as PBM:
OSSL_CMP_CTX_set1_referenceValue(cmp_ctx, ref, ref_len);
OSSL_CMP_CTX_set1_secretValue(cmp_ctx, sec, sec_len);
Set up the details for certificate requests:
OSSL_CMP_CTX_set1_subjectName(cmp_ctx, name);
OSSL_CMP_CTX_set0_newPkey(cmp_ctx, 1, initialKey);
Perform an Initialization Request transaction:
initialCert = OSSL_CMP_exec_IR_ses(cmp_ctx);
Reset the transaction state of the CMP context and the credentials:
OSSL_CMP_CTX_reinit(cmp_ctx);
OSSL_CMP_CTX_set1_referenceValue(cmp_ctx, NULL, 0);
OSSL_CMP_CTX_set1_secretValue(cmp_ctx, NULL, 0);
Perform a Certification Request transaction, making use of the new credentials:
OSSL_CMP_CTX_set1_cert(cmp_ctx, initialCert);
OSSL_CMP_CTX_set1_pkey(cmp_ctx, initialKey);
OSSL_CMP_CTX_set0_newPkey(cmp_ctx, 1, curentKey);
currentCert = OSSL_CMP_exec_CR_ses(cmp_ctx);
Perform a Key Update Request, signed using the cert (and key) to be updated:
OSSL_CMP_CTX_reinit(cmp_ctx);
OSSL_CMP_CTX_set1_cert(cmp_ctx, currentCert);
OSSL_CMP_CTX_set1_pkey(cmp_ctx, currentKey);
OSSL_CMP_CTX_set0_newPkey(cmp_ctx, 1, updatedKey);
currentCert = OSSL_CMP_exec_KUR_ses(cmp_ctx);
currentKey = updatedKey;
Perform a General Message transaction including, as an example,
the id-it-signKeyPairTypes OID and prints info on the General Response contents:
OSSL_CMP_CTX_reinit(cmp_ctx);
ASN1_OBJECT *type = OBJ_txt2obj("1.3.6.1.5.5.7.4.2", 1);
OSSL_CMP_ITAV *itav = OSSL_CMP_ITAV_create(type, NULL);
OSSL_CMP_CTX_push0_genm_ITAV(cmp_ctx, itav);
STACK_OF(OSSL_CMP_ITAV) *itavs;
itavs = OSSL_CMP_exec_GENM_ses(cmp_ctx);
print_itavs(itavs);
sk_OSSL_CMP_ITAV_pop_free(itavs, OSSL_CMP_ITAV_free);
=head1 SEE ALSO
L<OSSL_CMP_exec_IR_ses(3)>, L<OSSL_CMP_exec_CR_ses(3)>,
L<OSSL_CMP_exec_KUR_ses(3)>, L<OSSL_CMP_exec_GENM_ses(3)>,
L<OSSL_CMP_exec_certreq(3)>, L<OSSL_CMP_MSG_http_perform(3)>,
L<ERR_print_errors_cb(3)>
=head1 HISTORY
The OpenSSL CMP support was added in OpenSSL 3.0.
OSSL_CMP_CTX_reset_geninfo_ITAVs() was added in OpenSSL 3.0.8.
=head1 COPYRIGHT
-Copyright 2007-2023 The OpenSSL Project Authors. All Rights Reserved.
+Copyright 2007-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/OSSL_CMP_SRV_CTX_new.pod b/crypto/openssl/doc/man3/OSSL_CMP_SRV_CTX_new.pod
index d7f1a2e4dba7..12b1bfa88a1d 100644
--- a/crypto/openssl/doc/man3/OSSL_CMP_SRV_CTX_new.pod
+++ b/crypto/openssl/doc/man3/OSSL_CMP_SRV_CTX_new.pod
@@ -1,168 +1,169 @@
=pod
=head1 NAME
OSSL_CMP_SRV_process_request,
OSSL_CMP_CTX_server_perform,
OSSL_CMP_SRV_CTX_new,
OSSL_CMP_SRV_CTX_free,
OSSL_CMP_SRV_cert_request_cb_t,
OSSL_CMP_SRV_rr_cb_t,
OSSL_CMP_SRV_certConf_cb_t,
OSSL_CMP_SRV_genm_cb_t,
OSSL_CMP_SRV_error_cb_t,
OSSL_CMP_SRV_pollReq_cb_t,
OSSL_CMP_SRV_CTX_init,
OSSL_CMP_SRV_CTX_get0_cmp_ctx,
OSSL_CMP_SRV_CTX_get0_custom_ctx,
OSSL_CMP_SRV_CTX_set_send_unprotected_errors,
OSSL_CMP_SRV_CTX_set_accept_unprotected,
OSSL_CMP_SRV_CTX_set_accept_raverified,
OSSL_CMP_SRV_CTX_set_grant_implicit_confirm
- generic functions to set up and control a CMP server
=head1 SYNOPSIS
#include <openssl/cmp.h>
OSSL_CMP_MSG *OSSL_CMP_SRV_process_request(OSSL_CMP_SRV_CTX *srv_ctx,
const OSSL_CMP_MSG *req);
OSSL_CMP_MSG *OSSL_CMP_CTX_server_perform(OSSL_CMP_CTX *client_ctx,
const OSSL_CMP_MSG *req);
OSSL_CMP_SRV_CTX *OSSL_CMP_SRV_CTX_new(OSSL_LIB_CTX *libctx, const char *propq);
void OSSL_CMP_SRV_CTX_free(OSSL_CMP_SRV_CTX *srv_ctx);
typedef OSSL_CMP_PKISI *(*OSSL_CMP_SRV_cert_request_cb_t)(
OSSL_CMP_SRV_CTX *srv_ctx,
const OSSL_CMP_MSG *req,
int certReqId,
const OSSL_CRMF_MSG *crm,
const X509_REQ *p10cr,
X509 **certOut,
STACK_OF(X509) **chainOut,
STACK_OF(X509) **caPubs);
typedef OSSL_CMP_PKISI *(*OSSL_CMP_SRV_rr_cb_t)(OSSL_CMP_SRV_CTX *srv_ctx,
const OSSL_CMP_MSG *req,
const X509_NAME *issuer,
const ASN1_INTEGER *serial);
typedef int (*OSSL_CMP_SRV_genm_cb_t)(OSSL_CMP_SRV_CTX *srv_ctx,
const OSSL_CMP_MSG *req,
STACK_OF(OSSL_CMP_ITAV) *in,
STACK_OF(OSSL_CMP_ITAV) **out);
typedef void (*OSSL_CMP_SRV_error_cb_t)(OSSL_CMP_SRV_CTX *srv_ctx,
const OSSL_CMP_MSG *req,
const OSSL_CMP_PKISI *statusInfo,
const ASN1_INTEGER *errorCode,
const OSSL_CMP_PKIFREETEXT *errorDetails);
typedef int (*OSSL_CMP_SRV_certConf_cb_t)(OSSL_CMP_SRV_CTX *srv_ctx,
const OSSL_CMP_MSG *req,
int certReqId,
const ASN1_OCTET_STRING *certHash,
const OSSL_CMP_PKISI *si);
typedef int (*OSSL_CMP_SRV_pollReq_cb_t)(OSSL_CMP_SRV_CTX *srv_ctx,
const OSSL_CMP_MSG *req,
int certReqId,
OSSL_CMP_MSG **certReq,
int64_t *check_after);
int OSSL_CMP_SRV_CTX_init(OSSL_CMP_SRV_CTX *srv_ctx, void *custom_ctx,
OSSL_CMP_SRV_cert_request_cb_t process_cert_request,
OSSL_CMP_SRV_rr_cb_t process_rr,
OSSL_CMP_SRV_genm_cb_t process_genm,
OSSL_CMP_SRV_error_cb_t process_error,
OSSL_CMP_SRV_certConf_cb_t process_certConf,
OSSL_CMP_SRV_pollReq_cb_t process_pollReq);
OSSL_CMP_CTX *OSSL_CMP_SRV_CTX_get0_cmp_ctx(const OSSL_CMP_SRV_CTX *srv_ctx);
void *OSSL_CMP_SRV_CTX_get0_custom_ctx(const OSSL_CMP_SRV_CTX *srv_ctx);
int OSSL_CMP_SRV_CTX_set_send_unprotected_errors(OSSL_CMP_SRV_CTX *srv_ctx,
int val);
int OSSL_CMP_SRV_CTX_set_accept_unprotected(OSSL_CMP_SRV_CTX *srv_ctx, int val);
int OSSL_CMP_SRV_CTX_set_accept_raverified(OSSL_CMP_SRV_CTX *srv_ctx, int val);
int OSSL_CMP_SRV_CTX_set_grant_implicit_confirm(OSSL_CMP_SRV_CTX *srv_ctx,
int val);
=head1 DESCRIPTION
OSSL_CMP_SRV_process_request() implements the generic aspects of a CMP server.
Its arguments are the B<OSSL_CMP_SRV_CTX> I<srv_ctx> and the CMP request message
I<req>. It does the typical generic checks on I<req>, calls
the respective callback function (if present) for more specific processing,
and then assembles a result message, which may be a CMP error message.
If after return of the function the expression
I<OSSL_CMP_CTX_get_status(OSSL_CMP_SRV_CTX_get0_cmp_ctx(srv_ctx))> yields -1
then the function has closed the current transaction,
which may be due to normal successful end of the transaction or due to an error.
OSSL_CMP_CTX_server_perform() is an interface to
OSSL_CMP_SRV_process_request() that can be used by a CMP client
in the same way as L<OSSL_CMP_MSG_http_perform(3)>.
The B<OSSL_CMP_SRV_CTX> must be set as I<transfer_cb_arg> of I<client_ctx>.
OSSL_CMP_SRV_CTX_new() creates and initializes an B<OSSL_CMP_SRV_CTX> structure
associated with the library context I<libctx> and property query string
I<propq>, both of which may be NULL to select the defaults.
OSSL_CMP_SRV_CTX_free() deletes the given I<srv_ctx>.
+If the argument is NULL, nothing is done.
OSSL_CMP_SRV_CTX_init() sets in the given I<srv_ctx> a custom server context
pointer as well as callback functions performing the specific processing of CMP
certificate requests, revocation requests, certificate confirmation requests,
general messages, error messages, and poll requests.
All arguments except I<srv_ctx> may be NULL.
If a callback for some message type is not given this means that the respective
type of CMP message is not supported by the server.
OSSL_CMP_SRV_CTX_get0_cmp_ctx() returns the B<OSSL_CMP_CTX> from the I<srv_ctx>.
OSSL_CMP_SRV_CTX_get0_custom_ctx() returns the custom server context from
I<srv_ctx> that has been set using OSSL_CMP_SRV_CTX_init().
OSSL_CMP_SRV_CTX_set_send_unprotected_errors() enables sending error messages
and other forms of negative responses unprotected.
OSSL_CMP_SRV_CTX_set_accept_unprotected() enables acceptance of requests
without protection of with invalid protection.
OSSL_CMP_SRV_CTX_set_accept_raverified() enables acceptance of ir/cr/kur
messages with POPO 'RAVerified'.
OSSL_CMP_SRV_CTX_set_grant_implicit_confirm() enables granting implicit
confirmation of newly enrolled certificates if requested.
=head1 NOTES
CMP is defined in RFC 4210 (and CRMF in RFC 4211).
So far the CMP server implementation is limited to one request per CMP message
(and consequently to at most one response component per CMP message).
=head1 RETURN VALUES
OSSL_CMP_SRV_CTX_new() returns a B<OSSL_CMP_SRV_CTX> structure on success,
NULL on error.
OSSL_CMP_SRV_CTX_free() does not return a value.
OSSL_CMP_SRV_CTX_get0_cmp_ctx() returns a B<OSSL_CMP_CTX> structure on success,
NULL on error.
OSSL_CMP_SRV_CTX_get0_custom_ctx() returns the custom server context
that has been set using OSSL_CMP_SRV_CTX_init().
All other functions return 1 on success, 0 on error.
=head1 HISTORY
The OpenSSL CMP support was added in OpenSSL 3.0.
=head1 COPYRIGHT
-Copyright 2007-2021 The OpenSSL Project Authors. All Rights Reserved.
+Copyright 2007-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/OSSL_CMP_validate_msg.pod b/crypto/openssl/doc/man3/OSSL_CMP_validate_msg.pod
index 44c901210feb..555624a40358 100644
--- a/crypto/openssl/doc/man3/OSSL_CMP_validate_msg.pod
+++ b/crypto/openssl/doc/man3/OSSL_CMP_validate_msg.pod
@@ -1,84 +1,87 @@
=pod
=head1 NAME
OSSL_CMP_validate_msg,
OSSL_CMP_validate_cert_path
- functions for verifying CMP message protection
=head1 SYNOPSIS
#include <openssl/cmp.h>
int OSSL_CMP_validate_msg(OSSL_CMP_CTX *ctx, OSSL_CMP_MSG *msg);
int OSSL_CMP_validate_cert_path(const OSSL_CMP_CTX *ctx,
X509_STORE *trusted_store, X509 *cert);
=head1 DESCRIPTION
This is the API for validating the protection of CMP messages,
which includes validating CMP message sender certificates and their paths
while optionally checking the revocation status of the certificates(s).
OSSL_CMP_validate_msg() validates the protection of the given I<msg>,
which must be signature-based or using password-based MAC (PBM).
In the former case a suitable trust anchor must be given in the CMP context
I<ctx>, and in the latter case the matching secret must have been set there
using L<OSSL_CMP_CTX_set1_secretValue(3)>.
In case of signature algorithm, the certificate to use for the signature check
is preferably the one provided by a call to L<OSSL_CMP_CTX_set1_srvCert(3)>.
If no such sender cert has been pinned then candidate sender certificates are
taken from the list of certificates received in the I<msg> extraCerts, then any
certificates provided before via L<OSSL_CMP_CTX_set1_untrusted(3)>, and
then all trusted certificates provided via L<OSSL_CMP_CTX_set0_trustedStore(3)>,
where a candidate is acceptable only if has not expired, its subject DN matches
the I<msg> sender DN (as far as present), and its subject key identifier
is present and matches the senderKID (as far as the latter present).
Each acceptable cert is tried in the given order to see if the message
signature check succeeds and the cert and its path can be verified
using any trust store set via L<OSSL_CMP_CTX_set0_trustedStore(3)>.
If the option OSSL_CMP_OPT_PERMIT_TA_IN_EXTRACERTS_FOR_IR was set by calling
L<OSSL_CMP_CTX_set_option(3)>, for an Initialization Response (IP) message
-any self-issued certificate from the I<msg> extraCerts field may also be used
-as trust anchor for the path verification of an acceptable cert if it can be
+any self-issued certificate from the I<msg> extraCerts field may be used
+as a trust anchor for the path verification of an 'acceptable' cert if it can be
used also to validate the issued certificate returned in the IP message. This is
according to TS 33.310 [Network Domain Security (NDS); Authentication Framework
(AF)] document specified by the The 3rd Generation Partnership Project (3GPP).
+Note that using this option is dangerous as the certificate obtained this way
+has not been authenticated (at least not at CMP level).
+Taking it over as a trust anchor implements trust-on-first-use (TOFU).
Any cert that has been found as described above is cached and tried first when
validating the signatures of subsequent messages in the same transaction.
OSSL_CMP_validate_cert_path() attempts to validate the given certificate and its
path using the given store of trusted certs (possibly including CRLs and a cert
verification callback) and non-trusted intermediate certs from the I<ctx>.
=head1 NOTES
CMP is defined in RFC 4210 (and CRMF in RFC 4211).
=head1 RETURN VALUES
OSSL_CMP_validate_msg() and OSSL_CMP_validate_cert_path()
return 1 on success, 0 on error or validation failed.
=head1 SEE ALSO
L<OSSL_CMP_CTX_new(3)>, L<OSSL_CMP_exec_certreq(3)>,
L<OSSL_CMP_CTX_set1_secretValue(3)>, L<OSSL_CMP_CTX_set1_srvCert(3)>,
L<OSSL_CMP_CTX_set1_untrusted(3)>, L<OSSL_CMP_CTX_set0_trustedStore(3)>
=head1 HISTORY
The OpenSSL CMP support was added in OpenSSL 3.0.
=head1 COPYRIGHT
-Copyright 2007-2021 The OpenSSL Project Authors. All Rights Reserved.
+Copyright 2007-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/OSSL_DECODER.pod b/crypto/openssl/doc/man3/OSSL_DECODER.pod
index dcfd72bf9738..633aa07f8fff 100644
--- a/crypto/openssl/doc/man3/OSSL_DECODER.pod
+++ b/crypto/openssl/doc/man3/OSSL_DECODER.pod
@@ -1,190 +1,191 @@
=pod
=head1 NAME
OSSL_DECODER,
OSSL_DECODER_fetch,
OSSL_DECODER_up_ref,
OSSL_DECODER_free,
OSSL_DECODER_get0_provider,
OSSL_DECODER_get0_properties,
OSSL_DECODER_is_a,
OSSL_DECODER_get0_name,
OSSL_DECODER_get0_description,
OSSL_DECODER_do_all_provided,
OSSL_DECODER_names_do_all,
OSSL_DECODER_gettable_params,
OSSL_DECODER_get_params
- Decoder method routines
=head1 SYNOPSIS
#include <openssl/decoder.h>
typedef struct ossl_decoder_st OSSL_DECODER;
OSSL_DECODER *OSSL_DECODER_fetch(OSSL_LIB_CTX *ctx, const char *name,
const char *properties);
int OSSL_DECODER_up_ref(OSSL_DECODER *decoder);
void OSSL_DECODER_free(OSSL_DECODER *decoder);
const OSSL_PROVIDER *OSSL_DECODER_get0_provider(const OSSL_DECODER *decoder);
const char *OSSL_DECODER_get0_properties(const OSSL_DECODER *decoder);
int OSSL_DECODER_is_a(const OSSL_DECODER *decoder, const char *name);
const char *OSSL_DECODER_get0_name(const OSSL_DECODER *decoder);
const char *OSSL_DECODER_get0_description(const OSSL_DECODER *decoder);
void OSSL_DECODER_do_all_provided(OSSL_LIB_CTX *libctx,
void (*fn)(OSSL_DECODER *decoder, void *arg),
void *arg);
int OSSL_DECODER_names_do_all(const OSSL_DECODER *decoder,
void (*fn)(const char *name, void *data),
void *data);
const OSSL_PARAM *OSSL_DECODER_gettable_params(OSSL_DECODER *decoder);
int OSSL_DECODER_get_params(OSSL_DECODER_CTX *ctx, const OSSL_PARAM params[]);
=head1 DESCRIPTION
B<OSSL_DECODER> is a method for decoders, which know how to
decode encoded data into an object of some type that the rest
of OpenSSL knows how to handle.
OSSL_DECODER_fetch() looks for an algorithm within the provider that
has been loaded into the B<OSSL_LIB_CTX> given by I<ctx>, having the
name given by I<name> and the properties given by I<properties>.
The I<name> determines what type of object the fetched decoder
method is expected to be able to decode, and the properties are
used to determine the expected output type.
For known properties and the values they may have, please have a look
in L<provider-encoder(7)/Names and properties>.
OSSL_DECODER_up_ref() increments the reference count for the given
I<decoder>.
OSSL_DECODER_free() decrements the reference count for the given
I<decoder>, and when the count reaches zero, frees it.
+If the argument is NULL, nothing is done.
OSSL_DECODER_get0_provider() returns the provider of the given
I<decoder>.
OSSL_DECODER_get0_properties() returns the property definition associated
with the given I<decoder>.
OSSL_DECODER_is_a() checks if I<decoder> is an implementation
of an algorithm that's identifiable with I<name>.
OSSL_DECODER_get0_name() returns the name used to fetch the given I<decoder>.
OSSL_DECODER_get0_description() returns a description of the I<decoder>, meant
for display and human consumption. The description is at the discretion
of the I<decoder> implementation.
OSSL_DECODER_names_do_all() traverses all names for the given
I<decoder>, and calls I<fn> with each name and I<data> as arguments.
OSSL_DECODER_do_all_provided() traverses all decoder
implementations by all activated providers in the library context
I<libctx>, and for each of the implementations, calls I<fn> with the
implementation method and I<arg> as arguments.
OSSL_DECODER_gettable_params() returns an L<OSSL_PARAM(3)>
array of parameter descriptors.
OSSL_DECODER_get_params() attempts to get parameters specified
with an L<OSSL_PARAM(3)> array I<params>. Parameters that the
implementation doesn't recognise should be ignored.
=head1 RETURN VALUES
OSSL_DECODER_fetch() returns a pointer to an OSSL_DECODER object,
or NULL on error.
OSSL_DECODER_up_ref() returns 1 on success, or 0 on error.
OSSL_DECODER_free() doesn't return any value.
OSSL_DECODER_get0_provider() returns a pointer to a provider object, or
NULL on error.
OSSL_DECODER_get0_properties() returns a pointer to a property
definition string, or NULL on error.
OSSL_DECODER_is_a() returns 1 if I<decoder> was identifiable,
otherwise 0.
OSSL_DECODER_get0_name() returns the algorithm name from the provided
implementation for the given I<decoder>. Note that the I<decoder> may have
multiple synonyms associated with it. In this case the first name from the
algorithm definition is returned. Ownership of the returned string is retained
by the I<decoder> object and should not be freed by the caller.
OSSL_DECODER_get0_description() returns a pointer to a description, or NULL if
there isn't one.
OSSL_DECODER_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.
=head1 NOTES
OSSL_DECODER_fetch() may be called implicitly by other fetching
functions, using the same library context and properties.
Any other API that uses keys will typically do this.
=head1 EXAMPLES
To list all decoders in a provider to a bio_out:
static void collect_decoders(OSSL_DECODER *decoder, void *stack)
{
STACK_OF(OSSL_DECODER) *decoder_stack = stack;
sk_OSSL_DECODER_push(decoder_stack, decoder);
OSSL_DECODER_up_ref(decoder);
}
void print_name(const char *name, void *vdata)
{
BIO *bio = vdata;
BIO_printf(bio, "%s ", name);
}
STACK_OF(OSSL_DECODER) *decoders;
int i;
decoders = sk_OSSL_DECODER_new_null();
BIO_printf(bio_out, "DECODERs provided by %s:\n", provider);
OSSL_DECODER_do_all_provided(NULL, collect_decoders,
decoders);
for (i = 0; i < sk_OSSL_DECODER_num(decoders); i++) {
OSSL_DECODER *decoder = sk_OSSL_DECODER_value(decoders, i);
if (strcmp(OSSL_PROVIDER_get0_name(OSSL_DECODER_get0_provider(decoder)),
provider) != 0)
continue;
if (OSSL_DECODER_names_do_all(decoder, print_name, bio_out))
BIO_printf(bio_out, "\n");
}
sk_OSSL_DECODER_pop_free(decoders, OSSL_DECODER_free);
=head1 SEE ALSO
L<provider(7)>, L<OSSL_DECODER_CTX(3)>, L<OSSL_DECODER_from_bio(3)>,
L<OSSL_DECODER_CTX_new_for_pkey(3)>, L<OSSL_LIB_CTX(3)>
=head1 HISTORY
The functions described here were added in OpenSSL 3.0.
=head1 COPYRIGHT
-Copyright 2020-2023 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/OSSL_DECODER_CTX.pod b/crypto/openssl/doc/man3/OSSL_DECODER_CTX.pod
index 3ffd794cf0fb..bace3ee0cfed 100644
--- a/crypto/openssl/doc/man3/OSSL_DECODER_CTX.pod
+++ b/crypto/openssl/doc/man3/OSSL_DECODER_CTX.pod
@@ -1,259 +1,260 @@
=pod
=head1 NAME
OSSL_DECODER_CTX,
OSSL_DECODER_CTX_new,
OSSL_DECODER_settable_ctx_params,
OSSL_DECODER_CTX_set_params,
OSSL_DECODER_CTX_free,
OSSL_DECODER_CTX_set_selection,
OSSL_DECODER_CTX_set_input_type,
OSSL_DECODER_CTX_set_input_structure,
OSSL_DECODER_CTX_add_decoder,
OSSL_DECODER_CTX_add_extra,
OSSL_DECODER_CTX_get_num_decoders,
OSSL_DECODER_INSTANCE,
OSSL_DECODER_CONSTRUCT,
OSSL_DECODER_CLEANUP,
OSSL_DECODER_CTX_set_construct,
OSSL_DECODER_CTX_set_construct_data,
OSSL_DECODER_CTX_set_cleanup,
OSSL_DECODER_CTX_get_construct,
OSSL_DECODER_CTX_get_construct_data,
OSSL_DECODER_CTX_get_cleanup,
OSSL_DECODER_export,
OSSL_DECODER_INSTANCE_get_decoder,
OSSL_DECODER_INSTANCE_get_decoder_ctx,
OSSL_DECODER_INSTANCE_get_input_type,
OSSL_DECODER_INSTANCE_get_input_structure
- Decoder context routines
=head1 SYNOPSIS
#include <openssl/decoder.h>
typedef struct ossl_decoder_ctx_st OSSL_DECODER_CTX;
OSSL_DECODER_CTX *OSSL_DECODER_CTX_new(void);
const OSSL_PARAM *OSSL_DECODER_settable_ctx_params(OSSL_DECODER *decoder);
int OSSL_DECODER_CTX_set_params(OSSL_DECODER_CTX *ctx,
const OSSL_PARAM params[]);
void OSSL_DECODER_CTX_free(OSSL_DECODER_CTX *ctx);
int OSSL_DECODER_CTX_set_selection(OSSL_DECODER_CTX *ctx, int selection);
int OSSL_DECODER_CTX_set_input_type(OSSL_DECODER_CTX *ctx,
const char *input_type);
int OSSL_DECODER_CTX_set_input_structure(OSSL_DECODER_CTX *ctx,
const char *input_structure);
int OSSL_DECODER_CTX_add_decoder(OSSL_DECODER_CTX *ctx, OSSL_DECODER *decoder);
int OSSL_DECODER_CTX_add_extra(OSSL_DECODER_CTX *ctx,
OSSL_LIB_CTX *libctx,
const char *propq);
int OSSL_DECODER_CTX_get_num_decoders(OSSL_DECODER_CTX *ctx);
typedef struct ossl_decoder_instance_st OSSL_DECODER_INSTANCE;
OSSL_DECODER *
OSSL_DECODER_INSTANCE_get_decoder(OSSL_DECODER_INSTANCE *decoder_inst);
void *
OSSL_DECODER_INSTANCE_get_decoder_ctx(OSSL_DECODER_INSTANCE *decoder_inst);
const char *
OSSL_DECODER_INSTANCE_get_input_type(OSSL_DECODER_INSTANCE *decoder_inst);
OSSL_DECODER_INSTANCE_get_input_structure(OSSL_DECODER_INSTANCE *decoder_inst,
int *was_set);
typedef int OSSL_DECODER_CONSTRUCT(OSSL_DECODER_INSTANCE *decoder_inst,
const OSSL_PARAM *object,
void *construct_data);
typedef void OSSL_DECODER_CLEANUP(void *construct_data);
int OSSL_DECODER_CTX_set_construct(OSSL_DECODER_CTX *ctx,
OSSL_DECODER_CONSTRUCT *construct);
int OSSL_DECODER_CTX_set_construct_data(OSSL_DECODER_CTX *ctx,
void *construct_data);
int OSSL_DECODER_CTX_set_cleanup(OSSL_DECODER_CTX *ctx,
OSSL_DECODER_CLEANUP *cleanup);
OSSL_DECODER_CONSTRUCT *OSSL_DECODER_CTX_get_construct(OSSL_DECODER_CTX *ctx);
void *OSSL_DECODER_CTX_get_construct_data(OSSL_DECODER_CTX *ctx);
OSSL_DECODER_CLEANUP *OSSL_DECODER_CTX_get_cleanup(OSSL_DECODER_CTX *ctx);
int OSSL_DECODER_export(OSSL_DECODER_INSTANCE *decoder_inst,
void *reference, size_t reference_sz,
OSSL_CALLBACK *export_cb, void *export_cbarg);
=head1 DESCRIPTION
The B<OSSL_DECODER_CTX> holds data about multiple decoders, as needed to
figure out what the input data is and to attempt to unpack it into one of
several possible related results. This also includes chaining decoders, so
the output from one can become the input for another. This allows having
generic format decoders such as PEM to DER, as well as more specialized
decoders like DER to RSA.
The chains may be limited by specifying an input type, which is considered a
starting point. This is both considered by OSSL_DECODER_CTX_add_extra(),
which will stop adding one more decoder implementations when it has already
added those that take the specified input type, and functions like
L<OSSL_DECODER_from_bio(3)>, which will only start the decoding process with
the decoder implementations that take that input type. For example, if the
input type is set to C<DER>, a PEM to DER decoder will be ignored.
The input type can also be NULL, which means that the caller doesn't know
what type of input they have. In this case, OSSL_DECODER_from_bio() will
simply try with one decoder implementation after the other, and thereby
discover what kind of input the caller gave it.
For every decoding done, even an intermediary one, a constructor provided by
the caller is called to attempt to construct an appropriate type / structure
that the caller knows how to handle from the current decoding result.
The constructor is set with OSSL_DECODER_CTX_set_construct().
B<OSSL_DECODER_INSTANCE> is an opaque structure that contains data about the
decoder that was just used, and that may be useful for the constructor.
There are some functions to extract data from this type, described further
down.
=head2 Functions
OSSL_DECODER_CTX_new() creates a new empty B<OSSL_DECODER_CTX>.
OSSL_DECODER_settable_ctx_params() returns an L<OSSL_PARAM(3)> array of
parameter descriptors.
OSSL_DECODER_CTX_set_params() attempts to set parameters specified with an
L<OSSL_PARAM(3)> array I<params>. These parameters are passed to all
decoders that have been added to the I<ctx> so far. Parameters that an
implementation doesn't recognise should be ignored by it.
OSSL_DECODER_CTX_free() frees the given context I<ctx>.
+If the argument is NULL, nothing is done.
OSSL_DECODER_CTX_add_decoder() populates the B<OSSL_DECODER_CTX> I<ctx> with
a decoder, to be used to attempt to decode some encoded input.
OSSL_DECODER_CTX_add_extra() finds decoders that generate input for already
added decoders, and adds them as well. This is used to build decoder
chains.
OSSL_DECODER_CTX_set_input_type() sets the starting input type. This limits
the decoder chains to be considered, as explained in the general description
above.
OSSL_DECODER_CTX_set_input_structure() sets the name of the structure that
the input is expected to have. This may be used to determines what decoder
implementations may be used. NULL is a valid input structure, when it's not
relevant, or when the decoder implementations are expected to figure it out.
OSSL_DECODER_CTX_get_num_decoders() gets the number of decoders currently
added to the context I<ctx>.
OSSL_DECODER_CTX_set_construct() sets the constructor I<construct>.
OSSL_DECODER_CTX_set_construct_data() sets the constructor data that is
passed to the constructor every time it's called.
OSSL_DECODER_CTX_set_cleanup() sets the constructor data I<cleanup>
function. This is called by L<OSSL_DECODER_CTX_free(3)>.
OSSL_DECODER_CTX_get_construct(), OSSL_DECODER_CTX_get_construct_data() and
OSSL_DECODER_CTX_get_cleanup() return the values that have been set by
OSSL_DECODER_CTX_set_construct(), OSSL_DECODER_CTX_set_construct_data() and
OSSL_DECODER_CTX_set_cleanup() respectively.
OSSL_DECODER_export() is a fallback function for constructors that cannot
use the data they get directly for diverse reasons. It takes the same
decode instance I<decoder_inst> that the constructor got and an object
I<reference>, unpacks the object which it refers to, and exports it by
creating an L<OSSL_PARAM(3)> array that it then passes to I<export_cb>,
along with I<export_arg>.
=head2 Constructor
A B<OSSL_DECODER_CONSTRUCT> gets the following arguments:
=over 4
=item I<decoder_inst>
The B<OSSL_DECODER_INSTANCE> for the decoder from which the constructor gets
its data.
=item I<object>
A provider-native object abstraction produced by the decoder. Further
information on the provider-native object abstraction can be found in
L<provider-object(7)>.
=item I<construct_data>
The pointer that was set with OSSL_DECODE_CTX_set_construct_data().
=back
The constructor is expected to return 1 when the data it receives can be
constructed, otherwise 0.
These utility functions may be used by a constructor:
OSSL_DECODER_INSTANCE_get_decoder() can be used to get the decoder
implementation from a decoder instance I<decoder_inst>.
OSSL_DECODER_INSTANCE_get_decoder_ctx() can be used to get the decoder
implementation's provider context from a decoder instance I<decoder_inst>.
OSSL_DECODER_INSTANCE_get_input_type() can be used to get the decoder
implementation's input type from a decoder instance I<decoder_inst>.
OSSL_DECODER_INSTANCE_get_input_structure() can be used to get the input
structure for the decoder implementation from a decoder instance
I<decoder_inst>.
This may be NULL.
=head1 RETURN VALUES
OSSL_DECODER_CTX_new() returns a pointer to a B<OSSL_DECODER_CTX>, or NULL
if the context structure couldn't be allocated.
OSSL_DECODER_settable_ctx_params() returns an L<OSSL_PARAM(3)> array, or
NULL if none is available.
OSSL_DECODER_CTX_set_params() returns 1 if all recognised parameters were
valid, or 0 if one of them was invalid or caused some other failure in the
implementation.
OSSL_DECODER_CTX_add_decoder(), OSSL_DECODER_CTX_add_extra(),
OSSL_DECODER_CTX_set_construct(), OSSL_DECODER_CTX_set_construct_data() and
OSSL_DECODER_CTX_set_cleanup() return 1 on success, or 0 on failure.
OSSL_DECODER_CTX_get_construct(), OSSL_DECODER_CTX_get_construct_data() and
OSSL_DECODER_CTX_get_cleanup() return the current pointers to the
constructor, the constructor data and the cleanup functions, respectively.
OSSL_DECODER_CTX_num_decoders() returns the current number of decoders. It
returns 0 if I<ctx> is NULL.
OSSL_DECODER_export() returns 1 on success, or 0 on failure.
OSSL_DECODER_INSTANCE_decoder() returns an B<OSSL_DECODER> pointer on
success, or NULL on failure.
OSSL_DECODER_INSTANCE_decoder_ctx() returns a provider context pointer on
success, or NULL on failure.
=head1 SEE ALSO
L<provider(7)>, L<OSSL_DECODER(3)>, L<OSSL_DECODER_from_bio(3)>
=head1 HISTORY
The functions described here 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/OSSL_DECODER_CTX_new_for_pkey.pod b/crypto/openssl/doc/man3/OSSL_DECODER_CTX_new_for_pkey.pod
index acb04bc37623..e55212ad554b 100644
--- a/crypto/openssl/doc/man3/OSSL_DECODER_CTX_new_for_pkey.pod
+++ b/crypto/openssl/doc/man3/OSSL_DECODER_CTX_new_for_pkey.pod
@@ -1,145 +1,145 @@
=pod
=head1 NAME
OSSL_DECODER_CTX_new_for_pkey,
OSSL_DECODER_CTX_set_passphrase,
OSSL_DECODER_CTX_set_pem_password_cb,
OSSL_DECODER_CTX_set_passphrase_ui,
OSSL_DECODER_CTX_set_passphrase_cb
- Decoder routines to decode EVP_PKEYs
=head1 SYNOPSIS
#include <openssl/decoder.h>
OSSL_DECODER_CTX *
OSSL_DECODER_CTX_new_for_pkey(EVP_PKEY **pkey,
const char *input_type,
const char *input_struct,
const char *keytype, int selection,
OSSL_LIB_CTX *libctx, const char *propquery);
int OSSL_DECODER_CTX_set_passphrase(OSSL_DECODER_CTX *ctx,
const unsigned char *kstr,
size_t klen);
int OSSL_DECODER_CTX_set_pem_password_cb(OSSL_DECODER_CTX *ctx,
pem_password_cb *cb,
void *cbarg);
int OSSL_DECODER_CTX_set_passphrase_ui(OSSL_DECODER_CTX *ctx,
const UI_METHOD *ui_method,
void *ui_data);
int OSSL_DECODER_CTX_set_passphrase_cb(OSSL_DECODER_CTX *ctx,
OSSL_PASSPHRASE_CALLBACK *cb,
void *cbarg);
=head1 DESCRIPTION
OSSL_DECODER_CTX_new_for_pkey() is a utility function that creates a
B<OSSL_DECODER_CTX>, finds all applicable decoder implementations and sets
them up, so all the caller has to do next is call functions like
L<OSSL_DECODER_from_bio(3)>. The caller may use the optional I<input_type>,
I<input_struct>, I<keytype> and I<selection> to specify what the input is
expected to contain. The I<pkey> must reference an B<EVP_PKEY *> variable
that will be set to the newly created B<EVP_PKEY> on successful decoding.
The referenced variable must be initialized to NULL before calling the
function.
Internally OSSL_DECODER_CTX_new_for_pkey() searches for all available
L<EVP_KEYMGMT(3)> implementations, and then builds a list of all potential
decoder implementations that may be able to process the encoded input into
data suitable for B<EVP_PKEY>s. All these implementations are implicitly
fetched using I<libctx> and I<propquery>.
The search of decoder implementations can be limited with I<input_type> and
I<input_struct> which specifies a starting input type and input structure.
NULL is valid for both of them and signifies that the decoder implementations
will find out the input type on their own.
They are set with L<OSSL_DECODER_CTX_set_input_type(3)> and
L<OSSL_DECODER_CTX_set_input_structure(3)>.
See L</Input Types> and L</Input Structures> below for further information.
The search of decoder implementations can also be limited with I<keytype>
and I<selection>, which specifies the expected resulting keytype and contents.
NULL and zero are valid and signify that the decoder implementations will
find out the keytype and key contents on their own from the input they get.
If no suitable decoder implementation is found,
OSSL_DECODER_CTX_new_for_pkey() still creates a B<OSSL_DECODER_CTX>, but
with no associated decoder (L<OSSL_DECODER_CTX_get_num_decoders(3)> returns
zero). This helps the caller to distinguish between an error when creating
the B<OSSL_ENCODER_CTX> and missing encoder implementation, and allows it to
act accordingly.
OSSL_DECODER_CTX_set_passphrase() gives the implementation a pass phrase to
use when decrypting the encoded private key. Alternatively, a pass phrase
callback may be specified with the following functions.
OSSL_DECODER_CTX_set_pem_password_cb(), OSSL_DECODER_CTX_set_passphrase_ui()
and OSSL_DECODER_CTX_set_passphrase_cb() set up a callback method that the
implementation can use to prompt for a pass phrase, giving the caller the
choice of preferred pass phrase callback form. These are called indirectly,
through an internal L<OSSL_PASSPHRASE_CALLBACK(3)> function.
The internal L<OSSL_PASSPHRASE_CALLBACK(3)> function caches the pass phrase, to
-be re-used in all decodings that are performed in the same decoding run (for
+be reused in all decodings that are performed in the same decoding run (for
example, within one L<OSSL_DECODER_from_bio(3)> call).
=head2 Input Types
Available input types depend on the implementations that available providers
offer, and provider documentation should have the details.
Among the known input types that OpenSSL decoder implementations offer
for B<EVP_PKEY>s are C<DER>, C<PEM>, C<MSBLOB> and C<PVK>.
See L<openssl-glossary(7)> for further information on what these input
types mean.
=head2 Input Structures
Available input structures depend on the implementations that available
providers offer, and provider documentation should have the details.
Among the known input structures that OpenSSL decoder implementations
offer for B<EVP_PKEY>s are C<pkcs8> and C<SubjectPublicKeyInfo>.
OpenSSL decoder implementations also support the input structure
C<type-specific>. This is the structure used for keys encoded
according to key type specific specifications. For example, RSA keys
encoded according to PKCS#1.
=head2 Selections
I<selection> can be any one of the values described in
L<EVP_PKEY_fromdata(3)/Selections>.
Additionally I<selection> can also be set to B<0> to indicate that the code will
auto detect the selection.
=head1 RETURN VALUES
OSSL_DECODER_CTX_new_for_pkey() returns a pointer to a
B<OSSL_DECODER_CTX>, or NULL if it couldn't be created.
OSSL_DECODER_CTX_set_passphrase(), OSSL_DECODER_CTX_set_pem_password_cb(),
OSSL_DECODER_CTX_set_passphrase_ui() and
OSSL_DECODER_CTX_set_passphrase_cb() all return 1 on success, or 0 on
failure.
=head1 SEE ALSO
L<provider(7)>, L<OSSL_DECODER(3)>, L<OSSL_DECODER_CTX(3)>
=head1 HISTORY
The functions described here were added in OpenSSL 3.0.
=head1 COPYRIGHT
-Copyright 2020-2023 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/OSSL_ENCODER.pod b/crypto/openssl/doc/man3/OSSL_ENCODER.pod
index 06d8f80f8812..bbf64b0b47bf 100644
--- a/crypto/openssl/doc/man3/OSSL_ENCODER.pod
+++ b/crypto/openssl/doc/man3/OSSL_ENCODER.pod
@@ -1,144 +1,145 @@
=pod
=head1 NAME
OSSL_ENCODER,
OSSL_ENCODER_fetch,
OSSL_ENCODER_up_ref,
OSSL_ENCODER_free,
OSSL_ENCODER_get0_provider,
OSSL_ENCODER_get0_properties,
OSSL_ENCODER_is_a,
OSSL_ENCODER_get0_name,
OSSL_ENCODER_get0_description,
OSSL_ENCODER_do_all_provided,
OSSL_ENCODER_names_do_all,
OSSL_ENCODER_gettable_params,
OSSL_ENCODER_get_params
- Encoder method routines
=head1 SYNOPSIS
#include <openssl/encoder.h>
typedef struct ossl_encoder_st OSSL_ENCODER;
OSSL_ENCODER *OSSL_ENCODER_fetch(OSSL_LIB_CTX *ctx, const char *name,
const char *properties);
int OSSL_ENCODER_up_ref(OSSL_ENCODER *encoder);
void OSSL_ENCODER_free(OSSL_ENCODER *encoder);
const OSSL_PROVIDER *OSSL_ENCODER_get0_provider(const OSSL_ENCODER *encoder);
const char *OSSL_ENCODER_get0_properties(const OSSL_ENCODER *encoder);
int OSSL_ENCODER_is_a(const OSSL_ENCODER *encoder, const char *name);
const char *OSSL_ENCODER_get0_name(const OSSL_ENCODER *encoder);
const char *OSSL_ENCODER_get0_description(const OSSL_ENCODER *encoder);
void OSSL_ENCODER_do_all_provided(OSSL_LIB_CTX *libctx,
void (*fn)(OSSL_ENCODER *encoder, void *arg),
void *arg);
int OSSL_ENCODER_names_do_all(const OSSL_ENCODER *encoder,
void (*fn)(const char *name, void *data),
void *data);
const OSSL_PARAM *OSSL_ENCODER_gettable_params(OSSL_ENCODER *encoder);
int OSSL_ENCODER_get_params(OSSL_ENCODER_CTX *ctx, const OSSL_PARAM params[]);
=head1 DESCRIPTION
B<OSSL_ENCODER> is a method for encoders, which know how to
encode an object of some kind to a encoded form, such as PEM,
DER, or even human readable text.
OSSL_ENCODER_fetch() looks for an algorithm within the provider that
has been loaded into the B<OSSL_LIB_CTX> given by I<ctx>, having the
name given by I<name> and the properties given by I<properties>.
The I<name> determines what type of object the fetched encoder
method is expected to be able to encode, and the properties are
used to determine the expected output type.
For known properties and the values they may have, please have a look
in L<provider-encoder(7)/Names and properties>.
OSSL_ENCODER_up_ref() increments the reference count for the given
I<encoder>.
OSSL_ENCODER_free() decrements the reference count for the given
I<encoder>, and when the count reaches zero, frees it.
+If the argument is NULL, nothing is done.
OSSL_ENCODER_get0_provider() returns the provider of the given
I<encoder>.
OSSL_ENCODER_get0_properties() returns the property definition associated
with the given I<encoder>.
OSSL_ENCODER_is_a() checks if I<encoder> is an implementation of an
algorithm that's identifiable with I<name>.
OSSL_ENCODER_get0_name() returns the name used to fetch the given I<encoder>.
OSSL_ENCODER_get0_description() returns a description of the I<loader>, meant
for display and human consumption. The description is at the discretion of the
I<loader> implementation.
OSSL_ENCODER_names_do_all() traverses all names for the given
I<encoder>, and calls I<fn> with each name and I<data> as arguments.
OSSL_ENCODER_do_all_provided() traverses all encoder
implementations by all activated providers in the library context
I<libctx>, and for each of the implementations, calls I<fn> with the
implementation method and I<arg> as arguments.
OSSL_ENCODER_gettable_params() returns an L<OSSL_PARAM(3)>
array of parameter descriptors.
OSSL_ENCODER_get_params() attempts to get parameters specified
with an L<OSSL_PARAM(3)> array I<params>. Parameters that the
implementation doesn't recognise should be ignored.
=head1 RETURN VALUES
OSSL_ENCODER_fetch() returns a pointer to the key management
implementation represented by an OSSL_ENCODER object, or NULL on
error.
OSSL_ENCODER_up_ref() returns 1 on success, or 0 on error.
OSSL_ENCODER_free() doesn't return any value.
OSSL_ENCODER_get0_provider() returns a pointer to a provider object, or
NULL on error.
OSSL_ENCODER_get0_properties() returns a pointer to a property
definition string, or NULL on error.
OSSL_ENCODER_is_a() returns 1 of I<encoder> was identifiable,
otherwise 0.
OSSL_ENCODER_get0_name() returns the algorithm name from the provided
implementation for the given I<encoder>. Note that the I<encoder> may have
multiple synonyms associated with it. In this case the first name from the
algorithm definition is returned. Ownership of the returned string is retained
by the I<encoder> object and should not be freed by the caller.
OSSL_ENCODER_get0_description() returns a pointer to a description, or NULL if
there isn't one.
OSSL_ENCODER_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.
=head1 SEE ALSO
L<provider(7)>, L<OSSL_ENCODER_CTX(3)>, L<OSSL_ENCODER_to_bio(3)>,
L<OSSL_ENCODER_CTX_new_for_pkey(3)>, L<OSSL_LIB_CTX(3)>
=head1 HISTORY
The functions described here were 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/OSSL_ENCODER_CTX.pod b/crypto/openssl/doc/man3/OSSL_ENCODER_CTX.pod
index 7f3915fda882..e9248c356a05 100644
--- a/crypto/openssl/doc/man3/OSSL_ENCODER_CTX.pod
+++ b/crypto/openssl/doc/man3/OSSL_ENCODER_CTX.pod
@@ -1,221 +1,222 @@
=pod
=head1 NAME
OSSL_ENCODER_CTX,
OSSL_ENCODER_CTX_new,
OSSL_ENCODER_settable_ctx_params,
OSSL_ENCODER_CTX_set_params,
OSSL_ENCODER_CTX_free,
OSSL_ENCODER_CTX_set_selection,
OSSL_ENCODER_CTX_set_output_type,
OSSL_ENCODER_CTX_set_output_structure,
OSSL_ENCODER_CTX_add_encoder,
OSSL_ENCODER_CTX_add_extra,
OSSL_ENCODER_CTX_get_num_encoders,
OSSL_ENCODER_INSTANCE,
OSSL_ENCODER_INSTANCE_get_encoder,
OSSL_ENCODER_INSTANCE_get_encoder_ctx,
OSSL_ENCODER_INSTANCE_get_output_type,
OSSL_ENCODER_INSTANCE_get_output_structure,
OSSL_ENCODER_CONSTRUCT,
OSSL_ENCODER_CLEANUP,
OSSL_ENCODER_CTX_set_construct,
OSSL_ENCODER_CTX_set_construct_data,
OSSL_ENCODER_CTX_set_cleanup
- Encoder context routines
=head1 SYNOPSIS
#include <openssl/encoder.h>
typedef struct ossl_encoder_ctx_st OSSL_ENCODER_CTX;
OSSL_ENCODER_CTX *OSSL_ENCODER_CTX_new();
const OSSL_PARAM *OSSL_ENCODER_settable_ctx_params(OSSL_ENCODER *encoder);
int OSSL_ENCODER_CTX_set_params(OSSL_ENCODER_CTX *ctx,
const OSSL_PARAM params[]);
void OSSL_ENCODER_CTX_free(OSSL_ENCODER_CTX *ctx);
int OSSL_ENCODER_CTX_set_selection(OSSL_ENCODER_CTX *ctx, int selection);
int OSSL_ENCODER_CTX_set_output_type(OSSL_ENCODER_CTX *ctx,
const char *output_type);
int OSSL_ENCODER_CTX_set_output_structure(OSSL_ENCODER_CTX *ctx,
const char *output_structure);
int OSSL_ENCODER_CTX_add_encoder(OSSL_ENCODER_CTX *ctx, OSSL_ENCODER *encoder);
int OSSL_ENCODER_CTX_add_extra(OSSL_ENCODER_CTX *ctx,
OSSL_LIB_CTX *libctx, const char *propq);
int OSSL_ENCODER_CTX_get_num_encoders(OSSL_ENCODER_CTX *ctx);
typedef struct ossl_encoder_instance_st OSSL_ENCODER_INSTANCE;
OSSL_ENCODER *
OSSL_ENCODER_INSTANCE_get_encoder(OSSL_ENCODER_INSTANCE *encoder_inst);
void *
OSSL_ENCODER_INSTANCE_get_encoder_ctx(OSSL_ENCODER_INSTANCE *encoder_inst);
const char *
OSSL_ENCODER_INSTANCE_get_output_type(OSSL_ENCODER_INSTANCE *encoder_inst);
const char *
OSSL_ENCODER_INSTANCE_get_output_structure(OSSL_ENCODER_INSTANCE *encoder_inst);
typedef const void *OSSL_ENCODER_CONSTRUCT(OSSL_ENCODER_INSTANCE *encoder_inst,
void *construct_data);
typedef void OSSL_ENCODER_CLEANUP(void *construct_data);
int OSSL_ENCODER_CTX_set_construct(OSSL_ENCODER_CTX *ctx,
OSSL_ENCODER_CONSTRUCT *construct);
int OSSL_ENCODER_CTX_set_construct_data(OSSL_ENCODER_CTX *ctx,
void *construct_data);
int OSSL_ENCODER_CTX_set_cleanup(OSSL_ENCODER_CTX *ctx,
OSSL_ENCODER_CLEANUP *cleanup);
=head1 DESCRIPTION
Encoding an input object to the desired encoding may be done with a chain of
encoder implementations, which means that the output from one encoder may be
the input for the next in the chain. The B<OSSL_ENCODER_CTX> holds all the
data about these encoders. This allows having generic format encoders such
as DER to PEM, as well as more specialized encoders like RSA to DER.
The final output type must be given, and a chain of encoders must end with
an implementation that produces that output type.
At the beginning of the encoding process, a constructor provided by the
caller is called to ensure that there is an appropriate provider-side object
to start with.
The constructor is set with OSSL_ENCODER_CTX_set_construct().
B<OSSL_ENCODER_INSTANCE> is an opaque structure that contains data about the
encoder that is going to be used, and that may be useful for the
constructor. There are some functions to extract data from this type,
described in L</Constructor> below.
=head2 Functions
OSSL_ENCODER_CTX_new() creates a B<OSSL_ENCODER_CTX>.
OSSL_ENCODER_settable_ctx_params() returns an L<OSSL_PARAM(3)>
array of parameter descriptors.
OSSL_ENCODER_CTX_set_params() attempts to set parameters specified
with an L<OSSL_PARAM(3)> array I<params>. Parameters that the
implementation doesn't recognise should be ignored.
OSSL_ENCODER_CTX_free() frees the given context I<ctx>.
+If the argument is NULL, nothing is done.
OSSL_ENCODER_CTX_add_encoder() populates the B<OSSL_ENCODER_CTX>
I<ctx> with a encoder, to be used to encode an input object.
OSSL_ENCODER_CTX_add_extra() finds encoders that further encodes output
from already added encoders, and adds them as well. This is used to build
encoder chains.
OSSL_ENCODER_CTX_set_output_type() sets the ending output type. This must
be specified, and determines if a complete encoder chain is available.
OSSL_ENCODER_CTX_set_output_structure() sets the desired output structure.
This may be used to determines what encoder implementations may be used.
Depending on the type of object being encoded, the output structure may
not be relevant.
OSSL_ENCODER_CTX_get_num_encoders() gets the number of encoders currently
added to the context I<ctx>.
OSSL_ENCODER_CTX_set_construct() sets the constructor I<construct>.
OSSL_ENCODER_CTX_set_construct_data() sets the constructor data that is
passed to the constructor every time it's called.
OSSL_ENCODER_CTX_set_cleanup() sets the constructor data I<cleanup>
function. This is called by L<OSSL_ENCODER_CTX_free(3)>.
=head2 Constructor
A B<OSSL_ENCODER_CONSTRUCT> gets the following arguments:
=over 4
=item I<encoder_inst>
The B<OSSL_ENCODER_INSTANCE> for the encoder from which the constructor gets
its data.
=item I<construct_data>
The pointer that was set with OSSL_ENCODE_CTX_set_construct_data().
=back
The constructor is expected to return a valid (non-NULL) pointer to a
provider-native object that can be used as first input of an encoding chain,
or NULL to indicate that an error has occurred.
These utility functions may be used by a constructor:
OSSL_ENCODER_INSTANCE_get_encoder() can be used to get the encoder
implementation of the encoder instance I<encoder_inst>.
OSSL_ENCODER_INSTANCE_get_encoder_ctx() can be used to get the encoder
implementation's provider context of the encoder instance I<encoder_inst>.
OSSL_ENCODER_INSTANCE_get_output_type() can be used to get the output type
for the encoder implementation of the encoder instance I<encoder_inst>.
This will never be NULL.
OSSL_ENCODER_INSTANCE_get_output_structure() can be used to get the output
structure for the encoder implementation of the encoder instance
I<encoder_inst>.
This may be NULL.
=head1 RETURN VALUES
OSSL_ENCODER_CTX_new() returns a pointer to a B<OSSL_ENCODER_CTX>, or NULL
if the context structure couldn't be allocated.
OSSL_ENCODER_settable_ctx_params() returns an L<OSSL_PARAM(3)> array, or
NULL if none is available.
OSSL_ENCODER_CTX_set_params() returns 1 if all recognised parameters were
valid, or 0 if one of them was invalid or caused some other failure in the
implementation.
OSSL_ENCODER_CTX_add_encoder(), OSSL_ENCODER_CTX_add_extra(),
OSSL_ENCODER_CTX_set_construct(), OSSL_ENCODER_CTX_set_construct_data() and
OSSL_ENCODER_CTX_set_cleanup() return 1 on success, or 0 on failure.
OSSL_ENCODER_CTX_get_num_encoders() returns the current number of encoders.
It returns 0 if I<ctx> is NULL.
OSSL_ENCODER_INSTANCE_get_encoder() returns an B<OSSL_ENCODER> pointer on
success, or NULL on failure.
OSSL_ENCODER_INSTANCE_get_encoder_ctx() returns a provider context pointer on
success, or NULL on failure.
OSSL_ENCODER_INSTANCE_get_output_type() returns a string with the name of the
input type, if relevant. NULL is a valid returned value.
OSSL_ENCODER_INSTANCE_get_output_type() returns a string with the name of the
output type.
OSSL_ENCODER_INSTANCE_get_output_structure() returns a string with the name
of the output structure.
=head1 SEE ALSO
L<provider(7)>, L<OSSL_ENCODER(3)>
=head1 HISTORY
The functions described here were 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/OSSL_HTTP_REQ_CTX.pod b/crypto/openssl/doc/man3/OSSL_HTTP_REQ_CTX.pod
index 6216420e4ffe..d6c4cdfa0ca7 100644
--- a/crypto/openssl/doc/man3/OSSL_HTTP_REQ_CTX.pod
+++ b/crypto/openssl/doc/man3/OSSL_HTTP_REQ_CTX.pod
@@ -1,270 +1,271 @@
=pod
=head1 NAME
OSSL_HTTP_REQ_CTX,
OSSL_HTTP_REQ_CTX_new,
OSSL_HTTP_REQ_CTX_free,
OSSL_HTTP_REQ_CTX_set_request_line,
OSSL_HTTP_REQ_CTX_add1_header,
OSSL_HTTP_REQ_CTX_set_expected,
OSSL_HTTP_REQ_CTX_set1_req,
OSSL_HTTP_REQ_CTX_nbio,
OSSL_HTTP_REQ_CTX_nbio_d2i,
OSSL_HTTP_REQ_CTX_exchange,
OSSL_HTTP_REQ_CTX_get0_mem_bio,
OSSL_HTTP_REQ_CTX_get_resp_len,
OSSL_HTTP_REQ_CTX_set_max_response_length,
OSSL_HTTP_is_alive
- HTTP client low-level functions
=head1 SYNOPSIS
#include <openssl/http.h>
typedef struct ossl_http_req_ctx_st OSSL_HTTP_REQ_CTX;
OSSL_HTTP_REQ_CTX *OSSL_HTTP_REQ_CTX_new(BIO *wbio, BIO *rbio, int buf_size);
void OSSL_HTTP_REQ_CTX_free(OSSL_HTTP_REQ_CTX *rctx);
int OSSL_HTTP_REQ_CTX_set_request_line(OSSL_HTTP_REQ_CTX *rctx, int method_POST,
const char *server, const char *port,
const char *path);
int OSSL_HTTP_REQ_CTX_add1_header(OSSL_HTTP_REQ_CTX *rctx,
const char *name, const char *value);
int OSSL_HTTP_REQ_CTX_set_expected(OSSL_HTTP_REQ_CTX *rctx,
const char *content_type, int asn1,
int timeout, int keep_alive);
int OSSL_HTTP_REQ_CTX_set1_req(OSSL_HTTP_REQ_CTX *rctx, const char *content_type,
const ASN1_ITEM *it, const ASN1_VALUE *req);
int OSSL_HTTP_REQ_CTX_nbio(OSSL_HTTP_REQ_CTX *rctx);
int OSSL_HTTP_REQ_CTX_nbio_d2i(OSSL_HTTP_REQ_CTX *rctx,
ASN1_VALUE **pval, const ASN1_ITEM *it);
BIO *OSSL_HTTP_REQ_CTX_exchange(OSSL_HTTP_REQ_CTX *rctx);
BIO *OSSL_HTTP_REQ_CTX_get0_mem_bio(const OSSL_HTTP_REQ_CTX *rctx);
size_t OSSL_HTTP_REQ_CTX_get_resp_len(const OSSL_HTTP_REQ_CTX *rctx);
void OSSL_HTTP_REQ_CTX_set_max_response_length(OSSL_HTTP_REQ_CTX *rctx,
unsigned long len);
int OSSL_HTTP_is_alive(const OSSL_HTTP_REQ_CTX *rctx);
=head1 DESCRIPTION
B<OSSL_HTTP_REQ_CTX> is a context structure for an HTTP request and response,
used to collect all the necessary data to perform that request.
This file documents low-level HTTP functions rarely used directly. High-level
HTTP client functions like L<OSSL_HTTP_get(3)> and L<OSSL_HTTP_transfer(3)>
should be preferred.
OSSL_HTTP_REQ_CTX_new() allocates a new HTTP request context structure,
which gets populated with the B<BIO> to write/send the request to (I<wbio>),
the B<BIO> to read/receive the response from (I<rbio>, which may be equal to
I<wbio>), and the maximum expected response header line length I<buf_size>.
A value <= 0 indicates that
the B<OSSL_HTTP_DEFAULT_MAX_LINE_LEN> of 4KiB should be used.
I<buf_size> is also used as the number of content bytes that are read at a time.
The allocated context structure includes an internal memory B<BIO>,
which collects the HTTP request header lines.
OSSL_HTTP_REQ_CTX_free() frees up the HTTP request context I<rctx>.
The I<rbio> is not free'd, I<wbio> will be free'd if I<free_wbio> is set.
+If the argument is NULL, nothing is done.
OSSL_HTTP_REQ_CTX_set_request_line() adds the 1st HTTP request line to I<rctx>.
The HTTP method is determined by I<method_POST>,
which should be 1 to indicate C<POST> or 0 to indicate C<GET>.
I<server> and I<port> may be set to give the server and the optional port that
an HTTP proxy shall forward the request to, otherwise they must be left NULL.
I<path> provides the HTTP request path; if left NULL, C</> is used.
For backward compatibility, I<path> may begin with C<http://> and thus convey
an absoluteURI. In this case it indicates HTTP proxy use and provides also the
server (and optionally the port) that the proxy shall forward the request to.
In this case the I<server> and I<port> arguments must be NULL.
OSSL_HTTP_REQ_CTX_add1_header() adds header I<name> with value I<value> to the
context I<rctx>. It can be called more than once to add multiple header lines.
For example, to add a C<Host> header for C<example.com> you would call:
OSSL_HTTP_REQ_CTX_add1_header(ctx, "Host", "example.com");
OSSL_HTTP_REQ_CTX_set_expected() optionally sets in I<rctx> some expectations
of the HTTP client on the response.
Due to the structure of an HTTP request, if the I<keep_alive> argument is
nonzero the function must be used before calling OSSL_HTTP_REQ_CTX_set1_req().
If the I<content_type> parameter
is not NULL then the client will check that the given content type string
is included in the HTTP header of the response and return an error if not.
If the I<asn1> parameter is nonzero a structure in ASN.1 encoding will be
expected as the response content and input streaming is disabled. This means
that an ASN.1 sequence header is required, its length field is checked, and
OSSL_HTTP_REQ_CTX_get0_mem_bio() should be used to get the buffered response.
Otherwise (by default) any input format is allowed without length checks.
In this case the BIO given as I<rbio> argument to OSSL_HTTP_REQ_CTX_new() should
be used directly to read the response contents, which may support streaming.
If the I<timeout> parameter is > 0 this indicates the maximum number of seconds
the subsequent HTTP transfer (sending the request and receiving a response)
is allowed to take.
I<timeout> == 0 enables waiting indefinitely, i.e., no timeout can occur.
This is the default.
I<timeout> < 0 takes over any value set via the I<overall_timeout> argument of
L<OSSL_HTTP_open(3)> with the default being 0, which means no timeout.
If the I<keep_alive> parameter is 0, which is the default, the connection is not
kept open after receiving a response. This is the default behavior for HTTP 1.0.
If the value is 1 or 2 then a persistent connection is requested.
If the value is 2 then a persistent connection is required,
i.e., an error occurs in case the server does not grant it.
OSSL_HTTP_REQ_CTX_set1_req() finalizes the HTTP request context.
It is needed if the I<method_POST> parameter in the
OSSL_HTTP_REQ_CTX_set_request_line() call was 1
and an ASN.1-encoded request should be sent.
It must also be used when requesting "keep-alive",
even if a GET request is going to be sent, in which case I<req> must be NULL.
Unless I<req> is NULL, the function adds the DER encoding of I<req> using
the ASN.1 template I<it> to do the encoding (which does not support streaming).
The HTTP header C<Content-Length> is filled out with the length of the request.
I<content_type> must be NULL if I<req> is NULL.
If I<content_type> isn't NULL,
the HTTP header C<Content-Type> is also added with the given string value.
The header lines are added to the internal memory B<BIO> for the request header.
OSSL_HTTP_REQ_CTX_nbio() attempts to send the request prepared in I<rctx>
and to gather the response via HTTP, using the I<wbio> and I<rbio>
that were given when calling OSSL_HTTP_REQ_CTX_new().
The function may need to be called again if its result is -1, which indicates
L<BIO_should_retry(3)>. In such a case it is advisable to sleep a little in
between, using L<BIO_wait(3)> on the read BIO to prevent a busy loop.
OSSL_HTTP_REQ_CTX_nbio_d2i() is like OSSL_HTTP_REQ_CTX_nbio() but on success
in addition parses the response, which must be a DER-encoded ASN.1 structure,
using the ASN.1 template I<it> and places the result in I<*pval>.
OSSL_HTTP_REQ_CTX_exchange() calls OSSL_HTTP_REQ_CTX_nbio() as often as needed
in order to exchange a request and response or until a timeout is reached.
On success it returns a pointer to the BIO that can be used to read the result.
If an ASN.1-encoded response was expected, this is the BIO
returned by OSSL_HTTP_REQ_CTX_get0_mem_bio() when called after the exchange.
This memory BIO does not support streaming.
Otherwise the returned BIO is the I<rbio> given to OSSL_HTTP_REQ_CTX_new(),
which may support streaming.
When this BIO is returned, it has been read past the end of the response header,
such that the actual response body can be read from it.
The returned BIO pointer MUST NOT be freed by the caller.
OSSL_HTTP_REQ_CTX_get0_mem_bio() returns the internal memory B<BIO>.
Before the HTTP request is sent, this could be used to adapt its header lines.
I<Use with caution!>
After receiving a response via HTTP, the BIO represents the current state of
reading the response header. If the response was expected to be ASN.1 encoded,
its contents can be read via this BIO, which does not support streaming.
The returned BIO pointer must not be freed by the caller.
OSSL_HTTP_REQ_CTX_get_resp_len() returns the size of the response contents
in I<rctx> if provided by the server as <Content-Length> header field, else 0.
OSSL_HTTP_REQ_CTX_set_max_response_length() sets the maximum allowed
response content length for I<rctx> to I<len>. If not set or I<len> is 0
then the B<OSSL_HTTP_DEFAULT_MAX_RESP_LEN> is used, which currently is 100 KiB.
If the C<Content-Length> header is present and exceeds this value or
the content is an ASN.1 encoded structure with a length exceeding this value
or both length indications are present but disagree then an error occurs.
OSSL_HTTP_is_alive() can be used to query if the HTTP connection
given by I<rctx> is still alive, i.e., has not been closed.
It returns 0 if I<rctx> is NULL.
If the client application requested or required a persistent connection
and this was granted by the server, it can keep I<rctx> as long as it wants
to send further requests and OSSL_HTTP_is_alive() returns nonzero,
else it should call I<OSSL_HTTP_REQ_CTX_free(rctx)> or L<OSSL_HTTP_close(3)>.
In case the client application keeps I<rctx> but the connection then dies
for any reason at the server side, it will notice this obtaining an
I/O error when trying to send the next request via I<rctx>.
=head1 WARNINGS
The server's response may be unexpected if the hostname that was used to
create the I<wbio>, any C<Host> header, and the host specified in the
request URL do not match.
Many of these functions must be called in a certain order.
First, the HTTP request context must be allocated:
OSSL_HTTP_REQ_CTX_new().
Then, the HTTP request must be prepared with request data:
=over 4
=item 1.
Calling OSSL_HTTP_REQ_CTX_set_request_line().
=item 2.
Adding extra header lines with OSSL_HTTP_REQ_CTX_add1_header().
This is optional and may be done multiple times with different names.
=item 3.
Finalize the request using OSSL_HTTP_REQ_CTX_set1_req().
This may be omitted if the GET method is used and "keep-alive" is not requested.
=back
When the request context is fully prepared, the HTTP exchange may be performed
with OSSL_HTTP_REQ_CTX_nbio() or OSSL_HTTP_REQ_CTX_exchange().
=head1 RETURN VALUES
OSSL_HTTP_REQ_CTX_new() returns a pointer to a B<OSSL_HTTP_REQ_CTX>, or NULL
on error.
OSSL_HTTP_REQ_CTX_free() and OSSL_HTTP_REQ_CTX_set_max_response_length()
do not return values.
OSSL_HTTP_REQ_CTX_set_request_line(), OSSL_HTTP_REQ_CTX_add1_header(),
OSSL_HTTP_REQ_CTX_set1_req(), and OSSL_HTTP_REQ_CTX_set_expected()
return 1 for success and 0 for failure.
OSSL_HTTP_REQ_CTX_nbio() and OSSL_HTTP_REQ_CTX_nbio_d2i()
return 1 for success, 0 on error or redirection, -1 if retry is needed.
OSSL_HTTP_REQ_CTX_exchange() and OSSL_HTTP_REQ_CTX_get0_mem_bio()
return a pointer to a B<BIO> on success as described above or NULL on failure.
The returned BIO must not be freed by the caller.
OSSL_HTTP_REQ_CTX_get_resp_len() returns the size of the response contents
or 0 if not available or an error occurred.
OSSL_HTTP_is_alive() returns 1 if its argument is non-NULL
and the client requested a persistent connection
and the server did not disagree on keeping the connection open, else 0.
=head1 SEE ALSO
L<BIO_should_retry(3)>,
L<BIO_wait(3)>,
L<ASN1_item_d2i_bio(3)>,
L<ASN1_item_i2d_mem_bio(3)>,
L<OSSL_HTTP_open(3)>,
L<OSSL_HTTP_get(3)>,
L<OSSL_HTTP_transfer(3)>,
L<OSSL_HTTP_close(3)>
=head1 HISTORY
The functions described here were added in OpenSSL 3.0.
=head1 COPYRIGHT
-Copyright 2015-2023 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
L<https://www.openssl.org/source/license.html>.
=cut
diff --git a/crypto/openssl/doc/man3/OSSL_LIB_CTX.pod b/crypto/openssl/doc/man3/OSSL_LIB_CTX.pod
index 45fdd8f39a6a..ad203299e986 100644
--- a/crypto/openssl/doc/man3/OSSL_LIB_CTX.pod
+++ b/crypto/openssl/doc/man3/OSSL_LIB_CTX.pod
@@ -1,136 +1,136 @@
=pod
=head1 NAME
OSSL_LIB_CTX, OSSL_LIB_CTX_new, OSSL_LIB_CTX_new_from_dispatch,
OSSL_LIB_CTX_new_child, OSSL_LIB_CTX_free, OSSL_LIB_CTX_load_config,
OSSL_LIB_CTX_get0_global_default, OSSL_LIB_CTX_set0_default
- OpenSSL library context
=head1 SYNOPSIS
#include <openssl/crypto.h>
typedef struct ossl_lib_ctx_st OSSL_LIB_CTX;
OSSL_LIB_CTX *OSSL_LIB_CTX_new(void);
OSSL_LIB_CTX *OSSL_LIB_CTX_new_from_dispatch(const OSSL_CORE_HANDLE *handle,
const OSSL_DISPATCH *in);
OSSL_LIB_CTX *OSSL_LIB_CTX_new_child(const OSSL_CORE_HANDLE *handle,
const OSSL_DISPATCH *in);
int OSSL_LIB_CTX_load_config(OSSL_LIB_CTX *ctx, const char *config_file);
void OSSL_LIB_CTX_free(OSSL_LIB_CTX *ctx);
OSSL_LIB_CTX *OSSL_LIB_CTX_get0_global_default(void);
OSSL_LIB_CTX *OSSL_LIB_CTX_set0_default(OSSL_LIB_CTX *ctx);
=head1 DESCRIPTION
B<OSSL_LIB_CTX> is an internal OpenSSL library context type.
Applications may allocate their own, but may also use NULL to use
a default context with functions that take an B<OSSL_LIB_CTX>
argument.
When a non default library context is in use care should be taken with
multi-threaded applications to properly clean up thread local resources before
the OSSL_LIB_CTX is freed.
See L<OPENSSL_thread_stop_ex(3)> for more information.
OSSL_LIB_CTX_new() creates a new OpenSSL library context.
OSSL_LIB_CTX_new_from_dispatch() creates a new OpenSSL library context
initialised to use callbacks from the OSSL_DISPATCH structure. This is primarily
useful for provider authors. The I<handle> and dispatch structure arguments
passed should be the same ones as passed to a provider's
OSSL_provider_init function. Some OpenSSL functions, such as
L<BIO_new_from_core_bio(3)>, require the library context to be created in this
way in order to work.
OSSL_LIB_CTX_new_child() is only useful to provider authors and does the same
thing as OSSL_LIB_CTX_new_from_dispatch() except that it additionally links the
new library context to the application library context. The new library context
is a full library context in its own right, but will have all the same providers
available to it that are available in the application library context (without
having to reload them). If the application loads or unloads providers from the
application library context then this will be automatically mirrored in the
child library context.
In addition providers that are not loaded in the parent library context can be
explicitly loaded into the child library context independently from the parent
library context. Providers loaded independently in this way will not be mirrored
in the parent library context and will not be affected if the parent library
context subsequently loads the same provider.
A provider may call the function L<OSSL_PROVIDER_load(3)> with the child library
context as required. If the provider already exists due to it being mirrored
from the parent library context then it will remain available and its reference
count will be increased. If L<OSSL_PROVIDER_load(3)> is called in this way then
L<OSSL_PROVIDER_unload(3)> should be subsequently called to decrement the
reference count. L<OSSL_PROVIDER_unload(3)> must not be called for a provider in
the child library context that did not have an earlier L<OSSL_PROVIDER_load(3)>
call for that provider in that child library context.
In addition to providers, a child library context will also mirror the default
properties (set via L<EVP_set_default_properties(3)>) from the parent library
context. If L<EVP_set_default_properties(3)> is called directly on a child
library context then the new properties will override anything from the parent
library context and mirroring of the properties will stop.
When OSSL_LIB_CTX_new_child() is called from within the scope of a provider's
B<OSSL_provider_init> function the currently initialising provider is not yet
available in the application's library context and therefore will similarly not
yet be available in the newly constructed child library context. As soon as the
B<OSSL_provider_init> function returns then the new provider is available in the
application's library context and will be similarly mirrored in the child
library context.
OSSL_LIB_CTX_load_config() loads a configuration file using the given I<ctx>.
This can be used to associate a library context with providers that are loaded
from a configuration.
OSSL_LIB_CTX_free() frees the given I<ctx>, unless it happens to be the
-default OpenSSL library context.
+default OpenSSL library context. If the argument is NULL, nothing is done.
OSSL_LIB_CTX_get0_global_default() returns a concrete (non NULL) reference to
the global default library context.
OSSL_LIB_CTX_set0_default() sets the default OpenSSL library context to be
I<ctx> in the current thread. The previous default library context is
returned. Care should be taken by the caller to restore the previous
default library context with a subsequent call of this function. If I<ctx> is
NULL then no change is made to the default library context, but a pointer to
the current library context is still returned. On a successful call of this
function the returned value will always be a concrete (non NULL) library
context.
Care should be taken when changing the default library context and starting
async jobs (see L<ASYNC_start_job(3)>), as the default library context when
the job is started will be used throughout the lifetime of an async job, no
matter how the calling thread makes further default library context changes
in the mean time. This means that the calling thread must not free the
library context that was the default at the start of the async job before
that job has finished.
=head1 RETURN VALUES
OSSL_LIB_CTX_new(), OSSL_LIB_CTX_get0_global_default() and
OSSL_LIB_CTX_set0_default() return a library context pointer on success, or NULL
on error.
OSSL_LIB_CTX_free() doesn't return any value.
OSSL_LIB_CTX_load_config() returns 1 on success, 0 on error.
=head1 HISTORY
All of the functions described on this page were 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/man3/OSSL_PARAM_BLD.pod b/crypto/openssl/doc/man3/OSSL_PARAM_BLD.pod
index 455761c20d32..8598ed0626e0 100644
--- a/crypto/openssl/doc/man3/OSSL_PARAM_BLD.pod
+++ b/crypto/openssl/doc/man3/OSSL_PARAM_BLD.pod
@@ -1,203 +1,204 @@
=pod
=head1 NAME
OSSL_PARAM_BLD, OSSL_PARAM_BLD_new, OSSL_PARAM_BLD_to_param,
OSSL_PARAM_BLD_free, OSSL_PARAM_BLD_push_int,
OSSL_PARAM_BLD_push_uint, OSSL_PARAM_BLD_push_long,
OSSL_PARAM_BLD_push_ulong, OSSL_PARAM_BLD_push_int32,
OSSL_PARAM_BLD_push_uint32, OSSL_PARAM_BLD_push_int64,
OSSL_PARAM_BLD_push_uint64, OSSL_PARAM_BLD_push_size_t,
OSSL_PARAM_BLD_push_time_t, OSSL_PARAM_BLD_push_double,
OSSL_PARAM_BLD_push_BN, OSSL_PARAM_BLD_push_BN_pad,
OSSL_PARAM_BLD_push_utf8_string, OSSL_PARAM_BLD_push_utf8_ptr,
OSSL_PARAM_BLD_push_octet_string, OSSL_PARAM_BLD_push_octet_ptr
- functions to assist in the creation of OSSL_PARAM arrays
=head1 SYNOPSIS
=for openssl generic
#include <openssl/param_build.h>
typedef struct OSSL_PARAM_BLD;
OSSL_PARAM_BLD *OSSL_PARAM_BLD_new(void);
OSSL_PARAM *OSSL_PARAM_BLD_to_param(OSSL_PARAM_BLD *bld);
void OSSL_PARAM_BLD_free(OSSL_PARAM_BLD *bld);
int OSSL_PARAM_BLD_push_TYPE(OSSL_PARAM_BLD *bld, const char *key, TYPE val);
int OSSL_PARAM_BLD_push_BN(OSSL_PARAM_BLD *bld, const char *key,
const BIGNUM *bn);
int OSSL_PARAM_BLD_push_BN_pad(OSSL_PARAM_BLD *bld, const char *key,
const BIGNUM *bn, size_t sz);
int OSSL_PARAM_BLD_push_utf8_string(OSSL_PARAM_BLD *bld, const char *key,
const char *buf, size_t bsize);
int OSSL_PARAM_BLD_push_utf8_ptr(OSSL_PARAM_BLD *bld, const char *key,
char *buf, size_t bsize);
int OSSL_PARAM_BLD_push_octet_string(OSSL_PARAM_BLD *bld, const char *key,
const void *buf, size_t bsize);
int OSSL_PARAM_BLD_push_octet_ptr(OSSL_PARAM_BLD *bld, const char *key,
void *buf, size_t bsize);
=head1 DESCRIPTION
A collection of utility functions that simplify the creation of OSSL_PARAM
arrays. The B<I<TYPE>> names are as per L<OSSL_PARAM_int(3)>.
OSSL_PARAM_BLD_new() allocates and initialises a new OSSL_PARAM_BLD structure
so that values can be added.
Any existing values are cleared.
OSSL_PARAM_BLD_free() deallocates the memory allocates by OSSL_PARAM_BLD_new().
+If the argument is NULL, nothing is done.
OSSL_PARAM_BLD_to_param() converts a built up OSSL_PARAM_BLD structure
I<bld> into an allocated OSSL_PARAM array.
The OSSL_PARAM array and all associated storage must be freed by calling
OSSL_PARAM_free() with the functions return value.
OSSL_PARAM_BLD_free() can safely be called any time after this function is.
=begin comment
POD is pretty good at recognising function names and making them appropriately
bold... however, when part of the function name is variable, we have to help
the processor along
=end comment
B<OSSL_PARAM_BLD_push_I<TYPE>>() are a series of functions which will create
OSSL_PARAM objects of the specified size and correct type for the I<val>
argument.
I<val> is stored by value and an expression or auto variable can be used.
OSSL_PARAM_BLD_push_BN() is a function that will create an OSSL_PARAM object
that holds the specified BIGNUM I<bn>.
If I<bn> is marked as being securely allocated, its OSSL_PARAM representation
will also be securely allocated.
The I<bn> argument is stored by reference and the underlying BIGNUM object
must exist until after OSSL_PARAM_BLD_to_param() has been called.
OSSL_PARAM_BLD_push_BN_pad() is a function that will create an OSSL_PARAM object
that holds the specified BIGNUM I<bn>.
The object will be padded to occupy exactly I<sz> bytes, if insufficient space
is specified an error results.
If I<bn> is marked as being securely allocated, its OSSL_PARAM representation
will also be securely allocated.
The I<bn> argument is stored by reference and the underlying BIGNUM object
must exist until after OSSL_PARAM_BLD_to_param() has been called.
OSSL_PARAM_BLD_push_utf8_string() is a function that will create an OSSL_PARAM
object that references the UTF8 string specified by I<buf>.
The length of the string I<bsize> should not include the terminating NUL byte.
If it is zero then it will be calculated.
The string that I<buf> points to is stored by reference and must remain in
scope until after OSSL_PARAM_BLD_to_param() has been called.
OSSL_PARAM_BLD_push_octet_string() is a function that will create an OSSL_PARAM
object that references the octet string specified by I<buf> and <bsize>.
The memory that I<buf> points to is stored by reference and must remain in
scope until after OSSL_PARAM_BLD_to_param() has been called.
OSSL_PARAM_BLD_push_utf8_ptr() is a function that will create an OSSL_PARAM
object that references the UTF8 string specified by I<buf>.
The length of the string I<bsize> should not include the terminating NUL byte.
If it is zero then it will be calculated.
The string I<buf> points to is stored by reference and must remain in
scope until the OSSL_PARAM array is freed.
OSSL_PARAM_BLD_push_octet_ptr() is a function that will create an OSSL_PARAM
object that references the octet string specified by I<buf>.
The memory I<buf> points to is stored by reference and must remain in
scope until the OSSL_PARAM array is freed.
=head1 RETURN VALUES
OSSL_PARAM_BLD_new() returns the allocated OSSL_PARAM_BLD structure, or NULL
on error.
OSSL_PARAM_BLD_to_param() returns the allocated OSSL_PARAM array, or NULL
on error.
All of the OSSL_PARAM_BLD_push_TYPE functions return 1 on success and 0
on error.
=head1 NOTES
OSSL_PARAM_BLD_push_BN() and OSSL_PARAM_BLD_push_BN_pad() currently only
support nonnegative B<BIGNUM>s. They return an error on negative B<BIGNUM>s.
=head1 EXAMPLES
Both examples creating an OSSL_PARAM array that contains an RSA key.
For both, the predefined key variables are:
BIGNUM *n; /* modulus */
unsigned int e; /* public exponent */
BIGNUM *d; /* private exponent */
BIGNUM *p, *q; /* first two prime factors */
BIGNUM *dmp1, *dmq1; /* first two CRT exponents */
BIGNUM *iqmp; /* first CRT coefficient */
=head2 Example 1
This example shows how to create an OSSL_PARAM array that contains an RSA
private key.
OSSL_PARAM_BLD *bld = OSSL_PARAM_BLD_new();
OSSL_PARAM *params = NULL;
if (bld == NULL
|| !OSSL_PARAM_BLD_push_BN(bld, "n", n)
|| !OSSL_PARAM_BLD_push_uint(bld, "e", e)
|| !OSSL_PARAM_BLD_push_BN(bld, "d", d)
|| !OSSL_PARAM_BLD_push_BN(bld, "rsa-factor1", p)
|| !OSSL_PARAM_BLD_push_BN(bld, "rsa-factor2", q)
|| !OSSL_PARAM_BLD_push_BN(bld, "rsa-exponent1", dmp1)
|| !OSSL_PARAM_BLD_push_BN(bld, "rsa-exponent2", dmq1)
|| !OSSL_PARAM_BLD_push_BN(bld, "rsa-coefficient1", iqmp)
|| (params = OSSL_PARAM_BLD_to_param(bld)) == NULL)
goto err;
OSSL_PARAM_BLD_free(bld);
/* Use params */
...
OSSL_PARAM_free(params);
=head2 Example 2
This example shows how to create an OSSL_PARAM array that contains an RSA
public key.
OSSL_PARAM_BLD *bld = OSSL_PARAM_BLD_new();
OSSL_PARAM *params = NULL;
if (nld == NULL
|| !OSSL_PARAM_BLD_push_BN(bld, "n", n)
|| !OSSL_PARAM_BLD_push_uint(bld, "e", e)
|| (params = OSSL_PARAM_BLD_to_param(bld)) == NULL)
goto err;
OSSL_PARAM_BLD_free(bld);
/* Use params */
...
OSSL_PARAM_free(params);
=head1 SEE ALSO
L<OSSL_PARAM_int(3)>, L<OSSL_PARAM(3)>, L<OSSL_PARAM_free(3)>
=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/man3/OSSL_PARAM_dup.pod b/crypto/openssl/doc/man3/OSSL_PARAM_dup.pod
index 4ae33faf1e4e..c8d109a22782 100644
--- a/crypto/openssl/doc/man3/OSSL_PARAM_dup.pod
+++ b/crypto/openssl/doc/man3/OSSL_PARAM_dup.pod
@@ -1,59 +1,60 @@
=pod
=head1 NAME
OSSL_PARAM_dup, OSSL_PARAM_merge, OSSL_PARAM_free
- OSSL_PARAM array copy functions
=head1 SYNOPSIS
#include <openssl/params.h>
OSSL_PARAM *OSSL_PARAM_dup(const OSSL_PARAM *params);
OSSL_PARAM *OSSL_PARAM_merge(const OSSL_PARAM *params, const OSSL_PARAM *params1);
void OSSL_PARAM_free(OSSL_PARAM *params);
=head1 DESCRIPTION
Algorithm parameters can be exported/imported from/to providers using arrays of
L<OSSL_PARAM(3)>. The following utility functions allow the parameters to be
duplicated and merged with other L<OSSL_PARAM(3)> to assist in this process.
OSSL_PARAM_dup() duplicates the parameter array I<params>. This function does a
deep copy of the data.
OSSL_PARAM_merge() merges the parameter arrays I<params> and I<params1> into a
new parameter array. If I<params> and I<params1> contain values with the same
'key' then the value from I<params1> will replace the I<param> value. This
function does a shallow copy of the parameters. Either I<params> or I<params1>
may be NULL. The behaviour of the merge is unpredictable if I<params> and
I<params1> contain the same key, and there are multiple entries within either
array that have the same key.
OSSL_PARAM_free() frees the parameter array I<params> that was created using
OSSL_PARAM_dup(), OSSL_PARAM_merge() or OSSL_PARAM_BLD_to_param().
+If the argument to OSSL_PARAM_free() is NULL, nothing is done.
=head1 RETURN VALUES
The functions OSSL_PARAM_dup() and OSSL_PARAM_merge() return a newly allocated
L<OSSL_PARAM(3)> array, or NULL if there was an error. If both parameters are NULL
then NULL is returned.
=head1 SEE ALSO
L<OSSL_PARAM(3)>, L<OSSL_PARAM_BLD(3)>
=head1 HISTORY
The functions were added in OpenSSL 3.0.
=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/man3/OSSL_SELF_TEST_new.pod b/crypto/openssl/doc/man3/OSSL_SELF_TEST_new.pod
index 4c4b10fca96a..c46becd1ad9b 100644
--- a/crypto/openssl/doc/man3/OSSL_SELF_TEST_new.pod
+++ b/crypto/openssl/doc/man3/OSSL_SELF_TEST_new.pod
@@ -1,175 +1,176 @@
=pod
=head1 NAME
OSSL_SELF_TEST_new,
OSSL_SELF_TEST_free,
OSSL_SELF_TEST_onbegin,
OSSL_SELF_TEST_oncorrupt_byte,
OSSL_SELF_TEST_onend - functionality to trigger a callback during a self test
=head1 SYNOPSIS
#include <openssl/self_test.h>
OSSL_SELF_TEST *OSSL_SELF_TEST_new(OSSL_CALLBACK *cb, void *cbarg);
void OSSL_SELF_TEST_free(OSSL_SELF_TEST *st);
void OSSL_SELF_TEST_onbegin(OSSL_SELF_TEST *st, const char *type,
const char *desc);
int OSSL_SELF_TEST_oncorrupt_byte(OSSL_SELF_TEST *st, unsigned char *bytes);
void OSSL_SELF_TEST_onend(OSSL_SELF_TEST *st, int ret);
=head1 DESCRIPTION
These methods are intended for use by provider implementers, to display
diagnostic information during self testing.
OSSL_SELF_TEST_new() allocates an opaque B<OSSL_SELF_TEST> object that has a
callback and callback argument associated with it.
The callback I<cb> may be triggered multiple times by a self test to indicate
different phases.
OSSL_SELF_TEST_free() frees the space allocated by OSSL_SELF_TEST_new().
+If the argument is NULL, nothing is done.
OSSL_SELF_TEST_onbegin() may be inserted at the start of a block of self test
code. It can be used for diagnostic purposes.
If this method is called the callback I<cb> will receive the following
L<OSSL_PARAM(3)> object.
=over 4
=item "st-phase" (B<OSSL_PROV_PARAM_SELF_TEST_PHASE>) <UTF8 string>
The value is the string "Start"
=back
OSSL_SELF_TEST_oncorrupt_byte() may be inserted just after the known answer is
calculated, but before the self test compares the result. The first byte in the
passed in array of I<bytes> will be corrupted if the callback returns 0,
otherwise it leaves the array unaltered. It can be used for failure testing.
The I<type> and I<desc> can be used to identify an individual self test to
target for failure testing.
If this method is called the callback I<cb> will receive the following
L<OSSL_PARAM(3)> object.
=over 4
=item "st-phase" (B<OSSL_PROV_PARAM_SELF_TEST_PHASE>) <UTF8 string>
The value is the string "Corrupt"
=back
OSSL_SELF_TEST_onend() may be inserted at the end of a block of self test code
just before cleanup to indicate if the test passed or failed. It can be used for
diagnostic purposes.
If this method is called the callback I<cb> will receive the following
L<OSSL_PARAM(3)> object.
=over 4
=item "st-phase" (B<OSSL_PROV_PARAM_SELF_TEST_PHASE>) <UTF8 string>
The value of the string is "Pass" if I<ret> is non zero, otherwise it has the
value "Fail".
=back
After the callback I<cb> has been called the values that were set by
OSSL_SELF_TEST_onbegin() for I<type> and I<desc> are set to the value "None".
If OSSL_SELF_TEST_onbegin(), OSSL_SELF_TEST_oncorrupt_byte() or
OSSL_SELF_TEST_onend() is called the following additional L<OSSL_PARAM(3)> are
passed to the callback.
=over 4
=item "st-type" (B<OSSL_PROV_PARAM_SELF_TEST_TYPE>) <UTF8 string>
The value is setup by the I<type> passed to OSSL_SELF_TEST_onbegin().
This allows the callback to identify the type of test being run.
=item "st-desc" (B<OSSL_PROV_PARAM_SELF_TEST_DESC>) <UTF8 string>
The value is setup by the I<type> passed to OSSL_SELF_TEST_onbegin().
This allows the callback to identify the sub category of the test being run.
=back
=head1 RETURN VALUES
OSSL_SELF_TEST_new() returns the allocated B<OSSL_SELF_TEST> object, or NULL if
it fails.
OSSL_SELF_TEST_oncorrupt_byte() returns 1 if corruption occurs, otherwise it
returns 0.
=head1 EXAMPLES
A single self test could be set up in the following way:
OSSL_SELF_TEST *st = NULL;
OSSL_CALLBACK *cb;
void *cbarg;
int ok = 0;
unsigned char out[EVP_MAX_MD_SIZE];
unsigned int out_len = 0;
EVP_MD_CTX *ctx = EVP_MD_CTX_new();
EVP_MD *md = EVP_MD_fetch(libctx, t->algorithm, NULL);
/*
* Retrieve the callback - will be NULL if not set by the application via
* OSSL_SELF_TEST_set_callback().
*/
OSSL_SELF_TEST_get_callback(libctx, &cb, &cbarg);
st = OSSL_SELF_TEST_new(cb, cb_arg);
/* Trigger the optional callback */
OSSL_SELF_TEST_onbegin(st, OSSL_SELF_TEST_TYPE_KAT_DIGEST,
OSSL_SELF_TEST_DESC_MD_SHA2);
if (!EVP_DigestInit_ex(ctx, md, NULL)
|| !EVP_DigestUpdate(ctx, pt, pt_len)
|| !EVP_DigestFinal(ctx, out, &out_len))
goto err;
/* Optional corruption - If the application callback returns 0 */
OSSL_SELF_TEST_oncorrupt_byte(st, out);
if (out_len != t->expected_len
|| memcmp(out, t->expected, out_len) != 0)
goto err;
ok = 1;
err:
OSSL_SELF_TEST_onend(st, ok);
EVP_MD_free(md);
EVP_MD_CTX_free(ctx);
Multiple self test's can be set up in a similar way by repeating the pattern of
OSSL_SELF_TEST_onbegin(), OSSL_SELF_TEST_oncorrupt_byte(), OSSL_SELF_TEST_onend()
for each test.
=head1 SEE ALSO
L<OSSL_SELF_TEST_set_callback(3)>,
L<openssl-core.h(7)>,
L<OSSL_PROVIDER-FIPS(7)>
=head1 HISTORY
The functions described here were added in OpenSSL 3.0.
=head1 COPYRIGHT
-Copyright 2020-2023 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/OSSL_STORE_INFO.pod b/crypto/openssl/doc/man3/OSSL_STORE_INFO.pod
index 39bb93fbf5f2..b8332855d4d0 100644
--- a/crypto/openssl/doc/man3/OSSL_STORE_INFO.pod
+++ b/crypto/openssl/doc/man3/OSSL_STORE_INFO.pod
@@ -1,231 +1,232 @@
=pod
=head1 NAME
OSSL_STORE_INFO, OSSL_STORE_INFO_get_type, OSSL_STORE_INFO_get0_NAME,
OSSL_STORE_INFO_get0_NAME_description,
OSSL_STORE_INFO_get0_PARAMS, OSSL_STORE_INFO_get0_PUBKEY,
OSSL_STORE_INFO_get0_PKEY, OSSL_STORE_INFO_get0_CERT, OSSL_STORE_INFO_get0_CRL,
OSSL_STORE_INFO_get1_NAME, OSSL_STORE_INFO_get1_NAME_description,
OSSL_STORE_INFO_get1_PARAMS, OSSL_STORE_INFO_get1_PUBKEY,
OSSL_STORE_INFO_get1_PKEY, OSSL_STORE_INFO_get1_CERT, OSSL_STORE_INFO_get1_CRL,
OSSL_STORE_INFO_type_string, OSSL_STORE_INFO_free,
OSSL_STORE_INFO_new_NAME, OSSL_STORE_INFO_set0_NAME_description,
OSSL_STORE_INFO_new_PARAMS, OSSL_STORE_INFO_new_PUBKEY,
OSSL_STORE_INFO_new_PKEY, OSSL_STORE_INFO_new_CERT, OSSL_STORE_INFO_new_CRL,
OSSL_STORE_INFO_new, OSSL_STORE_INFO_get0_data
- Functions to manipulate OSSL_STORE_INFO objects
=head1 SYNOPSIS
#include <openssl/store.h>
typedef struct ossl_store_info_st OSSL_STORE_INFO;
int OSSL_STORE_INFO_get_type(const OSSL_STORE_INFO *store_info);
const char *OSSL_STORE_INFO_get0_NAME(const OSSL_STORE_INFO *store_info);
char *OSSL_STORE_INFO_get1_NAME(const OSSL_STORE_INFO *store_info);
const char *OSSL_STORE_INFO_get0_NAME_description(const OSSL_STORE_INFO
*store_info);
char *OSSL_STORE_INFO_get1_NAME_description(const OSSL_STORE_INFO *store_info);
EVP_PKEY *OSSL_STORE_INFO_get0_PARAMS(const OSSL_STORE_INFO *store_info);
EVP_PKEY *OSSL_STORE_INFO_get1_PARAMS(const OSSL_STORE_INFO *store_info);
EVP_PKEY *OSSL_STORE_INFO_get0_PUBKEY(const OSSL_STORE_INFO *info);
EVP_PKEY *OSSL_STORE_INFO_get1_PUBKEY(const OSSL_STORE_INFO *info);
EVP_PKEY *OSSL_STORE_INFO_get0_PKEY(const OSSL_STORE_INFO *store_info);
EVP_PKEY *OSSL_STORE_INFO_get1_PKEY(const OSSL_STORE_INFO *store_info);
X509 *OSSL_STORE_INFO_get0_CERT(const OSSL_STORE_INFO *store_info);
X509 *OSSL_STORE_INFO_get1_CERT(const OSSL_STORE_INFO *store_info);
X509_CRL *OSSL_STORE_INFO_get0_CRL(const OSSL_STORE_INFO *store_info);
X509_CRL *OSSL_STORE_INFO_get1_CRL(const OSSL_STORE_INFO *store_info);
const char *OSSL_STORE_INFO_type_string(int type);
void OSSL_STORE_INFO_free(OSSL_STORE_INFO *store_info);
OSSL_STORE_INFO *OSSL_STORE_INFO_new_NAME(char *name);
int OSSL_STORE_INFO_set0_NAME_description(OSSL_STORE_INFO *info, char *desc);
OSSL_STORE_INFO *OSSL_STORE_INFO_new_PARAMS(DSA *dsa_params);
OSSL_STORE_INFO *OSSL_STORE_INFO_new_PUBKEY(EVP_PKEY *pubkey);
OSSL_STORE_INFO *OSSL_STORE_INFO_new_PKEY(EVP_PKEY *pkey);
OSSL_STORE_INFO *OSSL_STORE_INFO_new_CERT(X509 *x509);
OSSL_STORE_INFO *OSSL_STORE_INFO_new_CRL(X509_CRL *crl);
OSSL_STORE_INFO *OSSL_STORE_INFO_new(int type, void *data);
void *OSSL_STORE_INFO_get0_data(int type, const OSSL_STORE_INFO *info);
=head1 DESCRIPTION
These functions are primarily useful for applications to retrieve
supported objects from B<OSSL_STORE_INFO> objects and for scheme specific
loaders to create B<OSSL_STORE_INFO> holders.
=head2 Types
B<OSSL_STORE_INFO> is an opaque type that's just an intermediary holder for
the objects that have been retrieved by OSSL_STORE_load() and similar functions.
Supported OpenSSL type object can be extracted using one of
STORE_INFO_get0_<TYPE>() where <TYPE> can be NAME, PARAMS, PKEY, CERT, or CRL.
The life time of this extracted object is as long as the life time of
the B<OSSL_STORE_INFO> it was extracted from, so care should be taken not
to free the latter too early.
As an alternative, STORE_INFO_get1_<TYPE>() extracts a duplicate (or the
same object with its reference count increased), which can be used
after the containing B<OSSL_STORE_INFO> has been freed.
The object returned by STORE_INFO_get1_<TYPE>() must be freed separately
by the caller.
See L</SUPPORTED OBJECTS> for more information on the types that are supported.
=head2 Functions
OSSL_STORE_INFO_get_type() takes a B<OSSL_STORE_INFO> and returns the STORE
type number for the object inside.
STORE_INFO_get_type_string() takes a STORE type number and returns a
short string describing it.
OSSL_STORE_INFO_get0_NAME(), OSSL_STORE_INFO_get0_NAME_description(),
OSSL_STORE_INFO_get0_PARAMS(), OSSL_STORE_INFO_get0_PUBKEY(),
OSSL_STORE_INFO_get0_PKEY(), OSSL_STORE_INFO_get0_CERT(),
OSSL_STORE_INFO_get0_CRL()
all take a B<OSSL_STORE_INFO> and return the object it holds if the
B<OSSL_STORE_INFO> type (as returned by OSSL_STORE_INFO_get_type())
matches the function, otherwise NULL.
OSSL_STORE_INFO_get1_NAME(), OSSL_STORE_INFO_get1_NAME_description(),
OSSL_STORE_INFO_get1_PARAMS(), OSSL_STORE_INFO_get1_PUBKEY(),
OSSL_STORE_INFO_get1_PKEY(), OSSL_STORE_INFO_get1_CERT() and
OSSL_STORE_INFO_get1_CRL()
all take a B<OSSL_STORE_INFO> and return a duplicate the object it
holds if the B<OSSL_STORE_INFO> type (as returned by
OSSL_STORE_INFO_get_type()) matches the function, otherwise NULL.
OSSL_STORE_INFO_free() frees a B<OSSL_STORE_INFO> and its contained type.
+If the argument is NULL, nothing is done.
OSSL_STORE_INFO_new_NAME() , OSSL_STORE_INFO_new_PARAMS(),
, OSSL_STORE_INFO_new_PUBKEY(), OSSL_STORE_INFO_new_PKEY(),
OSSL_STORE_INFO_new_CERT() and OSSL_STORE_INFO_new_CRL()
create a B<OSSL_STORE_INFO> object to hold the given input object.
On success the input object is consumed.
Additionally, for B<OSSL_STORE_INFO_NAME> objects,
OSSL_STORE_INFO_set0_NAME_description() can be used to add an extra
description.
This description is meant to be human readable and should be used for
information printout.
OSSL_STORE_INFO_new() creates a B<OSSL_STORE_INFO> with an arbitrary I<type>
number and I<data> structure. It's the responsibility of the caller to
define type numbers other than the ones defined by F<< <openssl/store.h> >>,
and to handle freeing the associated data structure on their own.
I<Using type numbers that are defined by F<< <openssl/store.h> >> may cause
undefined behaviours, including crashes>.
OSSL_STORE_INFO_get0_data() returns the data pointer that was passed to
OSSL_STORE_INFO_new() if I<type> matches the type number in I<info>.
OSSL_STORE_INFO_new() and OSSL_STORE_INFO_get0_data() may be useful for
applications that define their own STORE data, but must be used with care.
=head1 SUPPORTED OBJECTS
Currently supported object types are:
=over 4
=item OSSL_STORE_INFO_NAME
A name is exactly that, a name.
It's like a name in a directory, but formatted as a complete URI.
For example, the path in URI C<file:/foo/bar/> could include a file
named C<cookie.pem>, and in that case, the returned B<OSSL_STORE_INFO_NAME>
object would have the URI C<file:/foo/bar/cookie.pem>, which can be
used by the application to get the objects in that file.
This can be applied to all schemes that can somehow support a listing
of object URIs.
For C<file:> URIs that are used without the explicit scheme, the
returned name will be the path of each object, so if C</foo/bar> was
given and that path has the file C<cookie.pem>, the name
C</foo/bar/cookie.pem> will be returned.
The returned URI is considered canonical and must be unique and permanent
for the storage where the object (or collection of objects) resides.
Each loader is responsible for ensuring that it only returns canonical
URIs.
However, it's possible that certain schemes allow an object (or collection
thereof) to be reached with alternative URIs; just because one URI is
canonical doesn't mean that other variants can't be used.
At the discretion of the loader that was used to get these names, an
extra description may be attached as well.
=item OSSL_STORE_INFO_PARAMS
Key parameters.
=item OSSL_STORE_INFO_PKEY
A keypair or just a private key (possibly with key parameters).
=item OSSL_STORE_INFO_PUBKEY
A public key (possibly with key parameters).
=item OSSL_STORE_INFO_CERT
An X.509 certificate.
=item OSSL_STORE_INFO_CRL
A X.509 certificate revocation list.
=back
=head1 RETURN VALUES
OSSL_STORE_INFO_get_type() returns the STORE type number of the given
B<OSSL_STORE_INFO>.
There is no error value.
OSSL_STORE_INFO_get0_NAME(), OSSL_STORE_INFO_get0_NAME_description(),
OSSL_STORE_INFO_get0_PARAMS(), OSSL_STORE_INFO_get0_PKEY(),
OSSL_STORE_INFO_get0_CERT() and OSSL_STORE_INFO_get0_CRL() all return
a pointer to the OpenSSL object on success, NULL otherwise.
OSSL_STORE_INFO_get1_NAME(), OSSL_STORE_INFO_get1_NAME_description(),
OSSL_STORE_INFO_get1_PARAMS(), OSSL_STORE_INFO_get1_PKEY(),
OSSL_STORE_INFO_get1_CERT() and OSSL_STORE_INFO_get1_CRL() all return
a pointer to a duplicate of the OpenSSL object on success, NULL otherwise.
OSSL_STORE_INFO_type_string() returns a string on success, or NULL on
failure.
OSSL_STORE_INFO_new_NAME(), OSSL_STORE_INFO_new_PARAMS(),
OSSL_STORE_INFO_new_PKEY(), OSSL_STORE_INFO_new_CERT() and
OSSL_STORE_INFO_new_CRL() return a B<OSSL_STORE_INFO>
pointer on success, or NULL on failure.
OSSL_STORE_INFO_set0_NAME_description() returns 1 on success, or 0 on
failure.
=head1 SEE ALSO
L<ossl_store(7)>, L<OSSL_STORE_open(3)>, L<OSSL_STORE_register_loader(3)>
=head1 HISTORY
The OSSL_STORE API was added in OpenSSL 1.1.1.
The OSSL_STORE_INFO_PUBKEY object type was added in OpenSSL 3.0.
=head1 COPYRIGHT
-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
L<https://www.openssl.org/source/license.html>.
=cut
diff --git a/crypto/openssl/doc/man3/OSSL_STORE_LOADER.pod b/crypto/openssl/doc/man3/OSSL_STORE_LOADER.pod
index 9cd016be158a..b4fcc7efe935 100644
--- a/crypto/openssl/doc/man3/OSSL_STORE_LOADER.pod
+++ b/crypto/openssl/doc/man3/OSSL_STORE_LOADER.pod
@@ -1,390 +1,395 @@
=pod
=head1 NAME
OSSL_STORE_LOADER,
OSSL_STORE_LOADER_fetch,
OSSL_STORE_LOADER_up_ref,
OSSL_STORE_LOADER_free,
OSSL_STORE_LOADER_get0_provider,
OSSL_STORE_LOADER_get0_properties,
OSSL_STORE_LOADER_is_a,
OSSL_STORE_LOADER_get0_description,
OSSL_STORE_LOADER_do_all_provided,
OSSL_STORE_LOADER_names_do_all,
OSSL_STORE_LOADER_CTX, OSSL_STORE_LOADER_new,
OSSL_STORE_LOADER_get0_engine, OSSL_STORE_LOADER_get0_scheme,
OSSL_STORE_LOADER_set_open, OSSL_STORE_LOADER_set_open_ex,
OSSL_STORE_LOADER_set_attach, OSSL_STORE_LOADER_set_ctrl,
OSSL_STORE_LOADER_set_expect, OSSL_STORE_LOADER_set_find,
OSSL_STORE_LOADER_set_load, OSSL_STORE_LOADER_set_eof,
OSSL_STORE_LOADER_set_error, OSSL_STORE_LOADER_set_close,
OSSL_STORE_register_loader, OSSL_STORE_unregister_loader,
OSSL_STORE_open_fn, OSSL_STORE_open_ex_fn,
OSSL_STORE_attach_fn, OSSL_STORE_ctrl_fn,
OSSL_STORE_expect_fn, OSSL_STORE_find_fn,
OSSL_STORE_load_fn, OSSL_STORE_eof_fn, OSSL_STORE_error_fn,
OSSL_STORE_close_fn - Types and functions to manipulate, register and
unregister STORE loaders for different URI schemes
=head1 SYNOPSIS
#include <openssl/store.h>
typedef struct ossl_store_loader_st OSSL_STORE_LOADER;
OSSL_STORE_LOADER *OSSL_STORE_LOADER_fetch(OSSL_LIB_CTX *libctx,
const char *scheme,
const char *properties);
int OSSL_STORE_LOADER_up_ref(OSSL_STORE_LOADER *loader);
void OSSL_STORE_LOADER_free(OSSL_STORE_LOADER *loader);
const OSSL_PROVIDER *OSSL_STORE_LOADER_get0_provider(const OSSL_STORE_LOADER *
loader);
const char *OSSL_STORE_LOADER_get0_properties(const OSSL_STORE_LOADER *loader);
const char *OSSL_STORE_LOADER_get0_description(const OSSL_STORE_LOADER *loader);
int OSSL_STORE_LOADER_is_a(const OSSL_STORE_LOADER *loader,
const char *scheme);
void OSSL_STORE_LOADER_do_all_provided(OSSL_LIB_CTX *libctx,
void (*user_fn)(OSSL_STORE_LOADER *loader,
void *arg),
void *user_arg);
int OSSL_STORE_LOADER_names_do_all(const OSSL_STORE_LOADER *loader,
void (*fn)(const char *name, void *data),
void *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)>:
OSSL_STORE_LOADER *OSSL_STORE_LOADER_new(ENGINE *e, const char *scheme);
const ENGINE *OSSL_STORE_LOADER_get0_engine(const OSSL_STORE_LOADER
*store_loader);
const char *OSSL_STORE_LOADER_get0_scheme(const OSSL_STORE_LOADER
*store_loader);
/* struct ossl_store_loader_ctx_st is defined differently by each loader */
typedef struct ossl_store_loader_ctx_st OSSL_STORE_LOADER_CTX;
typedef OSSL_STORE_LOADER_CTX *(*OSSL_STORE_open_fn)(
const char *uri, const UI_METHOD *ui_method, void *ui_data);
int OSSL_STORE_LOADER_set_open(OSSL_STORE_LOADER *store_loader,
OSSL_STORE_open_fn store_open_function);
typedef OSSL_STORE_LOADER_CTX *(*OSSL_STORE_open_ex_fn)(
const char *uri, const UI_METHOD *ui_method, void *ui_data);
int OSSL_STORE_LOADER_set_open_ex
(OSSL_STORE_LOADER *store_loader,
OSSL_STORE_open_ex_fn store_open_ex_function);
typedef OSSL_STORE_LOADER_CTX *(*OSSL_STORE_attach_fn)
(const OSSL_STORE_LOADER *loader, BIO *bio,
OSSL_LIB_CTX *libctx, const char *propq,
const UI_METHOD *ui_method, void *ui_data);
int OSSL_STORE_LOADER_set_attach(OSSL_STORE_LOADER *loader,
OSSL_STORE_attach_fn attach_function);
typedef int (*OSSL_STORE_ctrl_fn)(OSSL_STORE_LOADER_CTX *ctx, int cmd,
va_list args);
int OSSL_STORE_LOADER_set_ctrl(OSSL_STORE_LOADER *store_loader,
OSSL_STORE_ctrl_fn store_ctrl_function);
typedef int (*OSSL_STORE_expect_fn)(OSSL_STORE_LOADER_CTX *ctx, int expected);
int OSSL_STORE_LOADER_set_expect(OSSL_STORE_LOADER *loader,
OSSL_STORE_expect_fn expect_function);
typedef int (*OSSL_STORE_find_fn)(OSSL_STORE_LOADER_CTX *ctx,
OSSL_STORE_SEARCH *criteria);
int OSSL_STORE_LOADER_set_find(OSSL_STORE_LOADER *loader,
OSSL_STORE_find_fn find_function);
typedef OSSL_STORE_INFO *(*OSSL_STORE_load_fn)(OSSL_STORE_LOADER_CTX *ctx,
UI_METHOD *ui_method,
void *ui_data);
int OSSL_STORE_LOADER_set_load(OSSL_STORE_LOADER *store_loader,
OSSL_STORE_load_fn store_load_function);
typedef int (*OSSL_STORE_eof_fn)(OSSL_STORE_LOADER_CTX *ctx);
int OSSL_STORE_LOADER_set_eof(OSSL_STORE_LOADER *store_loader,
OSSL_STORE_eof_fn store_eof_function);
typedef int (*OSSL_STORE_error_fn)(OSSL_STORE_LOADER_CTX *ctx);
int OSSL_STORE_LOADER_set_error(OSSL_STORE_LOADER *store_loader,
OSSL_STORE_error_fn store_error_function);
typedef int (*OSSL_STORE_close_fn)(OSSL_STORE_LOADER_CTX *ctx);
int OSSL_STORE_LOADER_set_close(OSSL_STORE_LOADER *store_loader,
OSSL_STORE_close_fn store_close_function);
- void OSSL_STORE_LOADER_free(OSSL_STORE_LOADER *store_loader);
int OSSL_STORE_register_loader(OSSL_STORE_LOADER *loader);
OSSL_STORE_LOADER *OSSL_STORE_unregister_loader(const char *scheme);
=head1 DESCRIPTION
B<OSSL_STORE_LOADER> is a method for OSSL_STORE loaders, which implement
OSSL_STORE_open(), OSSL_STORE_open_ex(), OSSL_STORE_load(),
OSSL_STORE_eof(), OSSL_STORE_error() and OSSL_STORE_close() for specific
storage schemes.
OSSL_STORE_LOADER_fetch() looks for an implementation for a storage
I<scheme> within the providers that has been loaded into the B<OSSL_LIB_CTX>
given by I<libctx>, and with the properties given by I<properties>.
OSSL_STORE_LOADER_up_ref() increments the reference count for the given
I<loader>.
OSSL_STORE_LOADER_free() decrements the reference count for the given
I<loader>, and when the count reaches zero, frees it.
+If the argument is NULL, nothing is done.
OSSL_STORE_LOADER_get0_provider() returns the provider of the given
I<loader>.
OSSL_STORE_LOADER_get0_properties() returns the property definition associated
with the given I<loader>.
OSSL_STORE_LOADER_is_a() checks if I<loader> is an implementation
of an algorithm that's identifiable with I<scheme>.
OSSL_STORE_LOADER_get0_description() returns a description of the I<loader>, meant
for display and human consumption. The description is at the discretion of the
I<loader> implementation.
OSSL_STORE_LOADER_do_all_provided() traverses all store implementations
by all activated providers in the library context I<libctx>, and for each
of the implementations, calls I<user_fn> with the implementation method and
I<user_arg> as arguments.
OSSL_STORE_LOADER_names_do_all() traverses all names for the given
I<loader>, and calls I<fn> with each name and I<data>.
=head2 Legacy Types and Functions (deprecated)
These functions help applications and engines to create loaders for
schemes they support. These are all deprecated and discouraged in favour of
provider implementations, see L<provider-storemgmt(7)>.
B<OSSL_STORE_LOADER_CTX> is a type template, to be defined by each loader
using C<struct ossl_store_loader_ctx_st { ... }>.
B<OSSL_STORE_open_fn>, B<OSSL_STORE_open_ex_fn>,
B<OSSL_STORE_ctrl_fn>, B<OSSL_STORE_expect_fn>, B<OSSL_STORE_find_fn>,
B<OSSL_STORE_load_fn>, B<OSSL_STORE_eof_fn>, and B<OSSL_STORE_close_fn>
are the function pointer types used within a STORE loader.
The functions pointed at define the functionality of the given loader.
=over 4
=item B<OSSL_STORE_open_fn> and B<OSSL_STORE_open_ex_fn>
B<OSSL_STORE_open_ex_fn> takes a URI and is expected to
interpret it in the best manner possible according to the scheme the
loader implements. It also takes a B<UI_METHOD> and associated data,
to be used any time something needs to be prompted for, as well as a
library context I<libctx> with an associated property query I<propq>,
to be used when fetching necessary algorithms to perform the loads.
Furthermore, this function is expected to initialize what needs to be
initialized, to create a private data store (B<OSSL_STORE_LOADER_CTX>,
see above), and to return it.
If something goes wrong, this function is expected to return NULL.
B<OSSL_STORE_open_fn> does the same thing as
B<OSSL_STORE_open_ex_fn> but uses NULL for the library
context I<libctx> and property query I<propq>.
=item B<OSSL_STORE_attach_fn>
This function takes a B<BIO>, otherwise works like
B<OSSL_STORE_open_ex_fn>.
=item B<OSSL_STORE_ctrl_fn>
This function takes a B<OSSL_STORE_LOADER_CTX> pointer, a command number
I<cmd> and a B<va_list> I<args> and is used to manipulate loader
specific parameters.
=begin comment
Globally known command numbers are documented in L<OSSL_STORE_ctrl(3)>,
along with what I<args> are expected with each of them.
=end comment
Loader specific command numbers must begin at B<OSSL_STORE_C_CUSTOM_START>.
Any number below that is reserved for future globally known command
numbers.
This function is expected to return 1 on success, 0 on error.
=item B<OSSL_STORE_expect_fn>
This function takes a B<OSSL_STORE_LOADER_CTX> pointer and a B<OSSL_STORE_INFO>
identity I<expected>, and is used to tell the loader what object type is
expected.
I<expected> may be zero to signify that no specific object type is expected.
This function is expected to return 1 on success, 0 on error.
=item B<OSSL_STORE_find_fn>
This function takes a B<OSSL_STORE_LOADER_CTX> pointer and a
B<OSSL_STORE_SEARCH> search criterion, and is used to tell the loader what
to search for.
When called with the loader context being NULL, this function is expected
to return 1 if the loader supports the criterion, otherwise 0.
When called with the loader context being something other than NULL, this
function is expected to return 1 on success, 0 on error.
=item B<OSSL_STORE_load_fn>
This function takes a B<OSSL_STORE_LOADER_CTX> pointer and a B<UI_METHOD>
with associated data.
It's expected to load the next available data, mold it into a data
structure that can be wrapped in a B<OSSL_STORE_INFO> using one of the
L<OSSL_STORE_INFO(3)> functions.
If no more data is available or an error occurs, this function is
expected to return NULL.
The B<OSSL_STORE_eof_fn> and B<OSSL_STORE_error_fn> functions must indicate if
it was in fact the end of data or if an error occurred.
Note that this function retrieves I<one> data item only.
=item B<OSSL_STORE_eof_fn>
This function takes a B<OSSL_STORE_LOADER_CTX> pointer and is expected to
return 1 to indicate that the end of available data has been reached.
It is otherwise expected to return 0.
=item B<OSSL_STORE_error_fn>
This function takes a B<OSSL_STORE_LOADER_CTX> pointer and is expected to
return 1 to indicate that an error occurred in a previous call to the
B<OSSL_STORE_load_fn> function.
It is otherwise expected to return 0.
=item B<OSSL_STORE_close_fn>
This function takes a B<OSSL_STORE_LOADER_CTX> pointer and is expected to
close or shut down what needs to be closed, and finally free the
contents of the B<OSSL_STORE_LOADER_CTX> pointer.
It returns 1 on success and 0 on error.
=back
OSSL_STORE_LOADER_new() creates a new B<OSSL_STORE_LOADER>.
It takes an B<ENGINE> I<e> and a string I<scheme>.
I<scheme> must I<always> be set.
Both I<e> and I<scheme> are used as is and must therefore be alive as
long as the created loader is.
OSSL_STORE_LOADER_get0_engine() returns the engine of the I<store_loader>.
OSSL_STORE_LOADER_get0_scheme() returns the scheme of the I<store_loader>.
OSSL_STORE_LOADER_set_open() sets the opener function for the
I<store_loader>.
OSSL_STORE_LOADER_set_open_ex() sets the opener with library context
function for the I<store_loader>.
OSSL_STORE_LOADER_set_attach() sets the attacher function for the
I<store_loader>.
OSSL_STORE_LOADER_set_ctrl() sets the control function for the
I<store_loader>.
OSSL_STORE_LOADER_set_expect() sets the expect function for the
I<store_loader>.
OSSL_STORE_LOADER_set_load() sets the loader function for the
I<store_loader>.
OSSL_STORE_LOADER_set_eof() sets the end of file checker function for the
I<store_loader>.
OSSL_STORE_LOADER_set_close() sets the closing function for the
I<store_loader>.
OSSL_STORE_LOADER_free() frees the given I<store_loader>.
+If the argument is NULL, nothing is done.
OSSL_STORE_register_loader() register the given I<store_loader> and
thereby makes it available for use with OSSL_STORE_open(),
OSSL_STORE_open_ex(), OSSL_STORE_load(), OSSL_STORE_eof()
and OSSL_STORE_close().
OSSL_STORE_unregister_loader() unregister the store loader for the given
I<scheme>.
=head1 RETURN VALUES
OSSL_STORE_LOADER_fetch() returns a pointer to an OSSL_STORE_LOADER object,
or NULL on error.
OSSL_STORE_LOADER_up_ref() returns 1 on success, or 0 on error.
OSSL_STORE_LOADER_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.
OSSL_STORE_LOADER_free() doesn't return any value.
OSSL_STORE_LOADER_get0_provider() returns a pointer to a provider object, or
NULL on error.
OSSL_STORE_LOADER_get0_properties() returns a pointer to a property
definition string, or NULL on error.
OSSL_STORE_LOADER_is_a() returns 1 if I<loader> was identifiable,
otherwise 0.
OSSL_STORE_LOADER_get0_description() returns a pointer to a description, or NULL if
there isn't one.
The functions with the types B<OSSL_STORE_open_fn>,
B<OSSL_STORE_open_ex_fn>, B<OSSL_STORE_ctrl_fn>,
B<OSSL_STORE_expect_fn>, B<OSSL_STORE_load_fn>, B<OSSL_STORE_eof_fn>
and B<OSSL_STORE_close_fn> have the same return values as OSSL_STORE_open(),
OSSL_STORE_open_ex(), OSSL_STORE_ctrl(), OSSL_STORE_expect(),
OSSL_STORE_load(), OSSL_STORE_eof() and OSSL_STORE_close(), respectively.
OSSL_STORE_LOADER_new() returns a pointer to a B<OSSL_STORE_LOADER> on success,
or NULL on failure.
OSSL_STORE_LOADER_set_open(), OSSL_STORE_LOADER_set_open_ex(),
OSSL_STORE_LOADER_set_ctrl(), OSSL_STORE_LOADER_set_load(),
OSSL_STORE_LOADER_set_eof() and OSSL_STORE_LOADER_set_close() return 1
on success, or 0 on failure.
OSSL_STORE_register_loader() returns 1 on success, or 0 on failure.
OSSL_STORE_unregister_loader() returns the unregistered loader on success,
or NULL on failure.
=head1 SEE ALSO
L<ossl_store(7)>, L<OSSL_STORE_open(3)>, L<OSSL_LIB_CTX(3)>,
L<provider-storemgmt(7)>
=head1 HISTORY
OSSL_STORE_LOADER_fetch(), OSSL_STORE_LOADER_up_ref(),
-OSSL_STORE_LOADER_free(), OSSL_STORE_LOADER_get0_provider(),
-OSSL_STORE_LOADER_get0_properties(), OSSL_STORE_LOADER_is_a(),
-OSSL_STORE_LOADER_do_all_provided() and
-OSSL_STORE_LOADER_names_do_all() were added in OpenSSL 3.0.
+OSSL_STORE_LOADER_get0_provider(), OSSL_STORE_LOADER_get0_properties(),
+OSSL_STORE_LOADER_get0_description(), OSSL_STORE_LOADER_is_a(),
+OSSL_STORE_LOADER_do_all_provided() and OSSL_STORE_LOADER_names_do_all()
+were added in OpenSSL 3.0.
-OSSL_STORE_open_ex_fn() was added in OpenSSL 3.0.
+B<OSSL_STORE_LOADER> and OSSL_STORE_LOADER_free() were added in OpenSSL
+1.1.1.
-B<OSSL_STORE_LOADER>, B<OSSL_STORE_LOADER_CTX>, OSSL_STORE_LOADER_new(),
+OSSL_STORE_LOADER_set_open_ex() and OSSL_STORE_open_ex_fn() were added in
+OpenSSL 3.0, and are deprecated.
+
+B<OSSL_STORE_LOADER_CTX>, OSSL_STORE_LOADER_new(),
OSSL_STORE_LOADER_set0_scheme(), OSSL_STORE_LOADER_get0_scheme(),
OSSL_STORE_LOADER_get0_engine(), OSSL_STORE_LOADER_set_expect(),
OSSL_STORE_LOADER_set_find(), OSSL_STORE_LOADER_set_attach(),
OSSL_STORE_LOADER_set_open_ex(), OSSL_STORE_LOADER_set_open(),
OSSL_STORE_LOADER_set_ctrl(),
OSSL_STORE_LOADER_set_load(), OSSL_STORE_LOADER_set_eof(),
-OSSL_STORE_LOADER_set_close(), OSSL_STORE_LOADER_free(),
+OSSL_STORE_LOADER_set_close(),
OSSL_STORE_register_loader(), OSSL_STORE_LOADER_set_error(),
OSSL_STORE_unregister_loader(), OSSL_STORE_open_fn(), OSSL_STORE_ctrl_fn(),
OSSL_STORE_load_fn(), OSSL_STORE_eof_fn() and OSSL_STORE_close_fn()
were added in OpenSSL 1.1.1, and became 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/man3/OSSL_STORE_SEARCH.pod b/crypto/openssl/doc/man3/OSSL_STORE_SEARCH.pod
index 79186b08997e..bd512890c607 100644
--- a/crypto/openssl/doc/man3/OSSL_STORE_SEARCH.pod
+++ b/crypto/openssl/doc/man3/OSSL_STORE_SEARCH.pod
@@ -1,193 +1,194 @@
=pod
=head1 NAME
OSSL_STORE_SEARCH,
OSSL_STORE_SEARCH_by_name,
OSSL_STORE_SEARCH_by_issuer_serial,
OSSL_STORE_SEARCH_by_key_fingerprint,
OSSL_STORE_SEARCH_by_alias,
OSSL_STORE_SEARCH_free,
OSSL_STORE_SEARCH_get_type,
OSSL_STORE_SEARCH_get0_name,
OSSL_STORE_SEARCH_get0_serial,
OSSL_STORE_SEARCH_get0_bytes,
OSSL_STORE_SEARCH_get0_string,
OSSL_STORE_SEARCH_get0_digest
- Type and functions to create OSSL_STORE search criteria
=head1 SYNOPSIS
#include <openssl/store.h>
typedef struct ossl_store_search_st OSSL_STORE_SEARCH;
OSSL_STORE_SEARCH *OSSL_STORE_SEARCH_by_name(X509_NAME *name);
OSSL_STORE_SEARCH *OSSL_STORE_SEARCH_by_issuer_serial(X509_NAME *name,
const ASN1_INTEGER
*serial);
OSSL_STORE_SEARCH *OSSL_STORE_SEARCH_by_key_fingerprint(const EVP_MD *digest,
const unsigned char
*bytes, int len);
OSSL_STORE_SEARCH *OSSL_STORE_SEARCH_by_alias(const char *alias);
void OSSL_STORE_SEARCH_free(OSSL_STORE_SEARCH *search);
int OSSL_STORE_SEARCH_get_type(const OSSL_STORE_SEARCH *criterion);
X509_NAME *OSSL_STORE_SEARCH_get0_name(OSSL_STORE_SEARCH *criterion);
const ASN1_INTEGER *OSSL_STORE_SEARCH_get0_serial(const OSSL_STORE_SEARCH
*criterion);
const unsigned char *OSSL_STORE_SEARCH_get0_bytes(const OSSL_STORE_SEARCH
*criterion, size_t *length);
const char *OSSL_STORE_SEARCH_get0_string(const OSSL_STORE_SEARCH *criterion);
const EVP_MD *OSSL_STORE_SEARCH_get0_digest(const OSSL_STORE_SEARCH
*criterion);
=head1 DESCRIPTION
These functions are used to specify search criteria to help search for specific
objects through other names than just the URI that's given to OSSL_STORE_open().
For example, this can be useful for an application that has received a URI
and then wants to add on search criteria in a uniform and supported manner.
=head2 Types
B<OSSL_STORE_SEARCH> is an opaque type that holds the constructed search
criterion, and that can be given to an OSSL_STORE context with
OSSL_STORE_find().
The calling application owns the allocation of an B<OSSL_STORE_SEARCH> at all
times, and should therefore be careful not to deallocate it before
OSSL_STORE_close() has been called for the OSSL_STORE context it was given
to.
=head2 Application Functions
OSSL_STORE_SEARCH_by_name(),
OSSL_STORE_SEARCH_by_issuer_serial(),
OSSL_STORE_SEARCH_by_key_fingerprint(),
and OSSL_STORE_SEARCH_by_alias()
are used to create an B<OSSL_STORE_SEARCH> from a subject name, an issuer name
and serial number pair, a key fingerprint, and an alias (for example a friendly
name).
The parameters that are provided are not copied, only referred to in a
criterion, so they must have at least the same life time as the created
B<OSSL_STORE_SEARCH>.
OSSL_STORE_SEARCH_free() is used to free the B<OSSL_STORE_SEARCH>.
+If the argument is NULL, nothing is done.
=head2 Loader Functions
OSSL_STORE_SEARCH_get_type() returns the criterion type for the given
B<OSSL_STORE_SEARCH>.
OSSL_STORE_SEARCH_get0_name(), OSSL_STORE_SEARCH_get0_serial(),
OSSL_STORE_SEARCH_get0_bytes(), OSSL_STORE_SEARCH_get0_string(),
and OSSL_STORE_SEARCH_get0_digest()
are used to retrieve different data from a B<OSSL_STORE_SEARCH>, as
available for each type.
For more information, see L</SUPPORTED CRITERION TYPES> below.
=head1 SUPPORTED CRITERION TYPES
Currently supported criterion types are:
=over 4
=item OSSL_STORE_SEARCH_BY_NAME
This criterion supports a search by exact match of subject name.
The subject name itself is a B<X509_NAME> pointer.
A criterion of this type is created with OSSL_STORE_SEARCH_by_name(),
and the actual subject name is retrieved with OSSL_STORE_SEARCH_get0_name().
=item OSSL_STORE_SEARCH_BY_ISSUER_SERIAL
This criterion supports a search by exact match of both issuer name and serial
number.
The issuer name itself is a B<X509_NAME> pointer, and the serial number is
a B<ASN1_INTEGER> pointer.
A criterion of this type is created with OSSL_STORE_SEARCH_by_issuer_serial()
and the actual issuer name and serial number are retrieved with
OSSL_STORE_SEARCH_get0_name() and OSSL_STORE_SEARCH_get0_serial().
=item OSSL_STORE_SEARCH_BY_KEY_FINGERPRINT
This criterion supports a search by exact match of key fingerprint.
The key fingerprint in itself is a string of bytes and its length, as
well as the algorithm that was used to compute the fingerprint.
The digest may be left unspecified (NULL), and in that case, the
loader has to decide on a default digest and compare fingerprints
accordingly.
A criterion of this type is created with OSSL_STORE_SEARCH_by_key_fingerprint()
and the actual fingerprint and its length can be retrieved with
OSSL_STORE_SEARCH_get0_bytes().
The digest can be retrieved with OSSL_STORE_SEARCH_get0_digest().
=item OSSL_STORE_SEARCH_BY_ALIAS
This criterion supports a search by match of an alias of some kind.
The alias in itself is a simple C string.
A criterion of this type is created with OSSL_STORE_SEARCH_by_alias()
and the actual alias is retrieved with OSSL_STORE_SEARCH_get0_string().
=back
=head1 RETURN VALUES
OSSL_STORE_SEARCH_by_name(),
OSSL_STORE_SEARCH_by_issuer_serial(),
OSSL_STORE_SEARCH_by_key_fingerprint(),
and OSSL_STORE_SEARCH_by_alias()
return a B<OSSL_STORE_SEARCH> pointer on success, or NULL on failure.
OSSL_STORE_SEARCH_get_type() returns the criterion type of the given
B<OSSL_STORE_SEARCH>.
There is no error value.
OSSL_STORE_SEARCH_get0_name() returns a B<X509_NAME> pointer on success,
or NULL when the given B<OSSL_STORE_SEARCH> was of a different type.
OSSL_STORE_SEARCH_get0_serial() returns a B<ASN1_INTEGER> pointer on success,
or NULL when the given B<OSSL_STORE_SEARCH> was of a different type.
OSSL_STORE_SEARCH_get0_bytes() returns a B<const unsigned char> pointer and
sets I<*length> to the strings length on success, or NULL when the given
B<OSSL_STORE_SEARCH> was of a different type.
OSSL_STORE_SEARCH_get0_string() returns a B<const char> pointer on success,
or NULL when the given B<OSSL_STORE_SEARCH> was of a different type.
OSSL_STORE_SEARCH_get0_digest() returns a B<const EVP_MD> pointer.
NULL is a valid value and means that the store loader default will
be used when applicable.
=head1 SEE ALSO
L<ossl_store(7)>, L<OSSL_STORE_supports_search(3)>, L<OSSL_STORE_find(3)>
=head1 HISTORY
B<OSSL_STORE_SEARCH>,
OSSL_STORE_SEARCH_by_name(),
OSSL_STORE_SEARCH_by_issuer_serial(),
OSSL_STORE_SEARCH_by_key_fingerprint(),
OSSL_STORE_SEARCH_by_alias(),
OSSL_STORE_SEARCH_free(),
OSSL_STORE_SEARCH_get_type(),
OSSL_STORE_SEARCH_get0_name(),
OSSL_STORE_SEARCH_get0_serial(),
OSSL_STORE_SEARCH_get0_bytes(),
and OSSL_STORE_SEARCH_get0_string()
were added in OpenSSL 1.1.1.
=head1 COPYRIGHT
-Copyright 2018-2020 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/man3/PEM_read_bio_PrivateKey.pod b/crypto/openssl/doc/man3/PEM_read_bio_PrivateKey.pod
index ac93920addec..f1635b89808a 100644
--- a/crypto/openssl/doc/man3/PEM_read_bio_PrivateKey.pod
+++ b/crypto/openssl/doc/man3/PEM_read_bio_PrivateKey.pod
@@ -1,584 +1,586 @@
=pod
=head1 NAME
pem_password_cb,
PEM_read_bio_PrivateKey_ex, PEM_read_bio_PrivateKey,
PEM_read_PrivateKey_ex, PEM_read_PrivateKey,
PEM_write_bio_PrivateKey_ex, PEM_write_bio_PrivateKey,
PEM_write_bio_PrivateKey_traditional,
PEM_write_PrivateKey_ex, PEM_write_PrivateKey,
PEM_write_bio_PKCS8PrivateKey, PEM_write_PKCS8PrivateKey,
PEM_write_bio_PKCS8PrivateKey_nid, PEM_write_PKCS8PrivateKey_nid,
PEM_read_bio_PUBKEY_ex, PEM_read_bio_PUBKEY,
PEM_read_PUBKEY_ex, PEM_read_PUBKEY,
PEM_write_bio_PUBKEY_ex, PEM_write_bio_PUBKEY,
PEM_write_PUBKEY_ex, PEM_write_PUBKEY,
PEM_read_bio_RSAPrivateKey, PEM_read_RSAPrivateKey,
PEM_write_bio_RSAPrivateKey, PEM_write_RSAPrivateKey,
PEM_read_bio_RSAPublicKey, PEM_read_RSAPublicKey, PEM_write_bio_RSAPublicKey,
PEM_write_RSAPublicKey, PEM_read_bio_RSA_PUBKEY, PEM_read_RSA_PUBKEY,
PEM_write_bio_RSA_PUBKEY, PEM_write_RSA_PUBKEY, PEM_read_bio_DSAPrivateKey,
PEM_read_DSAPrivateKey, PEM_write_bio_DSAPrivateKey, PEM_write_DSAPrivateKey,
PEM_read_bio_DSA_PUBKEY, PEM_read_DSA_PUBKEY, PEM_write_bio_DSA_PUBKEY,
PEM_write_DSA_PUBKEY, PEM_read_bio_Parameters_ex, PEM_read_bio_Parameters,
PEM_write_bio_Parameters, PEM_read_bio_DSAparams, PEM_read_DSAparams,
PEM_write_bio_DSAparams, PEM_write_DSAparams, PEM_read_bio_DHparams,
PEM_read_DHparams, PEM_write_bio_DHparams, PEM_write_DHparams,
PEM_read_bio_X509, PEM_read_X509, PEM_write_bio_X509, PEM_write_X509,
PEM_read_bio_X509_AUX, PEM_read_X509_AUX, PEM_write_bio_X509_AUX,
PEM_write_X509_AUX, PEM_read_bio_X509_REQ, PEM_read_X509_REQ,
PEM_write_bio_X509_REQ, PEM_write_X509_REQ, PEM_write_bio_X509_REQ_NEW,
PEM_write_X509_REQ_NEW, PEM_read_bio_X509_CRL, PEM_read_X509_CRL,
PEM_write_bio_X509_CRL, PEM_write_X509_CRL, PEM_read_bio_PKCS7, PEM_read_PKCS7,
PEM_write_bio_PKCS7, PEM_write_PKCS7 - PEM routines
=head1 SYNOPSIS
#include <openssl/pem.h>
typedef int pem_password_cb(char *buf, int size, int rwflag, void *u);
EVP_PKEY *PEM_read_bio_PrivateKey_ex(BIO *bp, EVP_PKEY **x,
pem_password_cb *cb, void *u,
OSSL_LIB_CTX *libctx, const char *propq);
EVP_PKEY *PEM_read_bio_PrivateKey(BIO *bp, EVP_PKEY **x,
pem_password_cb *cb, void *u);
EVP_PKEY *PEM_read_PrivateKey_ex(FILE *fp, EVP_PKEY **x, pem_password_cb *cb,
void *u, OSSL_LIB_CTX *libctx,
const char *propq);
EVP_PKEY *PEM_read_PrivateKey(FILE *fp, EVP_PKEY **x,
pem_password_cb *cb, void *u);
int PEM_write_bio_PrivateKey_ex(BIO *bp, const EVP_PKEY *x,
const EVP_CIPHER *enc,
unsigned char *kstr, int klen,
pem_password_cb *cb, void *u,
OSSL_LIB_CTX *libctx, const char *propq);
int PEM_write_bio_PrivateKey(BIO *bp, const EVP_PKEY *x, const EVP_CIPHER *enc,
unsigned char *kstr, int klen,
pem_password_cb *cb, void *u);
int PEM_write_bio_PrivateKey_traditional(BIO *bp, EVP_PKEY *x,
const EVP_CIPHER *enc,
unsigned char *kstr, int klen,
pem_password_cb *cb, void *u);
int PEM_write_PrivateKey_ex(FILE *fp, EVP_PKEY *x, const EVP_CIPHER *enc,
unsigned char *kstr, int klen,
pem_password_cb *cb, void *u,
OSSL_LIB_CTX *libctx, const char *propq);
int PEM_write_PrivateKey(FILE *fp, EVP_PKEY *x, const EVP_CIPHER *enc,
unsigned char *kstr, int klen,
pem_password_cb *cb, void *u);
int PEM_write_bio_PKCS8PrivateKey(BIO *bp, EVP_PKEY *x, const EVP_CIPHER *enc,
char *kstr, int klen,
pem_password_cb *cb, void *u);
int PEM_write_PKCS8PrivateKey(FILE *fp, EVP_PKEY *x, const EVP_CIPHER *enc,
char *kstr, int klen,
pem_password_cb *cb, void *u);
int PEM_write_bio_PKCS8PrivateKey_nid(BIO *bp, const EVP_PKEY *x, int nid,
char *kstr, int klen,
pem_password_cb *cb, void *u);
int PEM_write_PKCS8PrivateKey_nid(FILE *fp, const EVP_PKEY *x, int nid,
char *kstr, int klen,
pem_password_cb *cb, void *u);
EVP_PKEY *PEM_read_bio_PUBKEY_ex(BIO *bp, EVP_PKEY **x,
pem_password_cb *cb, void *u,
OSSL_LIB_CTX *libctx, const char *propq);
EVP_PKEY *PEM_read_bio_PUBKEY(BIO *bp, EVP_PKEY **x,
pem_password_cb *cb, void *u);
EVP_PKEY *PEM_read_PUBKEY_ex(FILE *fp, EVP_PKEY **x,
pem_password_cb *cb, void *u,
OSSL_LIB_CTX *libctx, const char *propq);
EVP_PKEY *PEM_read_PUBKEY(FILE *fp, EVP_PKEY **x,
pem_password_cb *cb, void *u);
int PEM_write_bio_PUBKEY_ex(BIO *bp, EVP_PKEY *x,
OSSL_LIB_CTX *libctx, const char *propq);
int PEM_write_bio_PUBKEY(BIO *bp, EVP_PKEY *x);
int PEM_write_PUBKEY_ex(FILE *fp, EVP_PKEY *x,
OSSL_LIB_CTX *libctx, const char *propq);
int PEM_write_PUBKEY(FILE *fp, EVP_PKEY *x);
EVP_PKEY *PEM_read_bio_Parameters_ex(BIO *bp, EVP_PKEY **x,
OSSL_LIB_CTX *libctx, const char *propq);
EVP_PKEY *PEM_read_bio_Parameters(BIO *bp, EVP_PKEY **x);
int PEM_write_bio_Parameters(BIO *bp, const EVP_PKEY *x);
X509 *PEM_read_bio_X509(BIO *bp, X509 **x, pem_password_cb *cb, void *u);
X509 *PEM_read_X509(FILE *fp, X509 **x, pem_password_cb *cb, void *u);
int PEM_write_bio_X509(BIO *bp, X509 *x);
int PEM_write_X509(FILE *fp, X509 *x);
X509 *PEM_read_bio_X509_AUX(BIO *bp, X509 **x, pem_password_cb *cb, void *u);
X509 *PEM_read_X509_AUX(FILE *fp, X509 **x, pem_password_cb *cb, void *u);
int PEM_write_bio_X509_AUX(BIO *bp, X509 *x);
int PEM_write_X509_AUX(FILE *fp, X509 *x);
X509_REQ *PEM_read_bio_X509_REQ(BIO *bp, X509_REQ **x,
pem_password_cb *cb, void *u);
X509_REQ *PEM_read_X509_REQ(FILE *fp, X509_REQ **x,
pem_password_cb *cb, void *u);
int PEM_write_bio_X509_REQ(BIO *bp, X509_REQ *x);
int PEM_write_X509_REQ(FILE *fp, X509_REQ *x);
int PEM_write_bio_X509_REQ_NEW(BIO *bp, X509_REQ *x);
int PEM_write_X509_REQ_NEW(FILE *fp, X509_REQ *x);
X509_CRL *PEM_read_bio_X509_CRL(BIO *bp, X509_CRL **x,
pem_password_cb *cb, void *u);
X509_CRL *PEM_read_X509_CRL(FILE *fp, X509_CRL **x,
pem_password_cb *cb, void *u);
int PEM_write_bio_X509_CRL(BIO *bp, X509_CRL *x);
int PEM_write_X509_CRL(FILE *fp, X509_CRL *x);
PKCS7 *PEM_read_bio_PKCS7(BIO *bp, PKCS7 **x, pem_password_cb *cb, void *u);
PKCS7 *PEM_read_PKCS7(FILE *fp, PKCS7 **x, pem_password_cb *cb, void *u);
int PEM_write_bio_PKCS7(BIO *bp, PKCS7 *x);
int PEM_write_PKCS7(FILE *fp, PKCS7 *x);
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)>:
RSA *PEM_read_bio_RSAPrivateKey(BIO *bp, RSA **x,
pem_password_cb *cb, void *u);
RSA *PEM_read_RSAPrivateKey(FILE *fp, RSA **x,
pem_password_cb *cb, void *u);
int PEM_write_bio_RSAPrivateKey(BIO *bp, RSA *x, const EVP_CIPHER *enc,
unsigned char *kstr, int klen,
pem_password_cb *cb, void *u);
int PEM_write_RSAPrivateKey(FILE *fp, RSA *x, const EVP_CIPHER *enc,
unsigned char *kstr, int klen,
pem_password_cb *cb, void *u);
RSA *PEM_read_bio_RSAPublicKey(BIO *bp, RSA **x,
pem_password_cb *cb, void *u);
RSA *PEM_read_RSAPublicKey(FILE *fp, RSA **x,
pem_password_cb *cb, void *u);
int PEM_write_bio_RSAPublicKey(BIO *bp, RSA *x);
int PEM_write_RSAPublicKey(FILE *fp, RSA *x);
RSA *PEM_read_bio_RSA_PUBKEY(BIO *bp, RSA **x,
pem_password_cb *cb, void *u);
RSA *PEM_read_RSA_PUBKEY(FILE *fp, RSA **x,
pem_password_cb *cb, void *u);
int PEM_write_bio_RSA_PUBKEY(BIO *bp, RSA *x);
int PEM_write_RSA_PUBKEY(FILE *fp, RSA *x);
DSA *PEM_read_bio_DSAPrivateKey(BIO *bp, DSA **x,
pem_password_cb *cb, void *u);
DSA *PEM_read_DSAPrivateKey(FILE *fp, DSA **x,
pem_password_cb *cb, void *u);
int PEM_write_bio_DSAPrivateKey(BIO *bp, DSA *x, const EVP_CIPHER *enc,
unsigned char *kstr, int klen,
pem_password_cb *cb, void *u);
int PEM_write_DSAPrivateKey(FILE *fp, DSA *x, const EVP_CIPHER *enc,
unsigned char *kstr, int klen,
pem_password_cb *cb, void *u);
DSA *PEM_read_bio_DSA_PUBKEY(BIO *bp, DSA **x,
pem_password_cb *cb, void *u);
DSA *PEM_read_DSA_PUBKEY(FILE *fp, DSA **x,
pem_password_cb *cb, void *u);
int PEM_write_bio_DSA_PUBKEY(BIO *bp, DSA *x);
int PEM_write_DSA_PUBKEY(FILE *fp, DSA *x);
DSA *PEM_read_bio_DSAparams(BIO *bp, DSA **x, pem_password_cb *cb, void *u);
DSA *PEM_read_DSAparams(FILE *fp, DSA **x, pem_password_cb *cb, void *u);
int PEM_write_bio_DSAparams(BIO *bp, DSA *x);
int PEM_write_DSAparams(FILE *fp, DSA *x);
DH *PEM_read_bio_DHparams(BIO *bp, DH **x, pem_password_cb *cb, void *u);
DH *PEM_read_DHparams(FILE *fp, DH **x, pem_password_cb *cb, void *u);
int PEM_write_bio_DHparams(BIO *bp, DH *x);
int PEM_write_DHparams(FILE *fp, DH *x);
=head1 DESCRIPTION
All of the functions described on this page that have a I<TYPE> of B<DH>, B<DSA>
and B<RSA> are deprecated. Applications should use L<OSSL_ENCODER_to_bio(3)> and
L<OSSL_DECODER_from_bio(3)> instead.
The PEM functions read or write structures in PEM format. In
this sense PEM format is simply base64 encoded data surrounded
by header lines.
For more details about the meaning of arguments see the
B<PEM FUNCTION ARGUMENTS> section.
Each operation has four functions associated with it. For
brevity the term "B<I<TYPE>> functions" will be used below to collectively
refer to the B<PEM_read_bio_I<TYPE>>(), B<PEM_read_I<TYPE>>(),
B<PEM_write_bio_I<TYPE>>(), and B<PEM_write_I<TYPE>>() functions.
Some operations have additional variants that take a library context I<libctx>
and a property query string I<propq>. The B<X509>, B<X509_REQ> and B<X509_CRL>
objects may have an associated library context or property query string but
there are no variants of these functions that take a library context or property
query string parameter. In this case it is possible to set the appropriate
library context or property query string by creating an empty B<X509>,
B<X509_REQ> or B<X509_CRL> object using L<X509_new_ex(3)>, L<X509_REQ_new_ex(3)>
or L<X509_CRL_new_ex(3)> respectively. Then pass the empty object as a parameter
to the relevant PEM function. See the L</EXAMPLES> section below.
The B<PrivateKey> functions read or write a private key in PEM format using
an EVP_PKEY structure. The write routines use PKCS#8 private key format and are
equivalent to PEM_write_bio_PKCS8PrivateKey(). The read functions transparently
handle traditional and PKCS#8 format encrypted and unencrypted keys.
PEM_write_bio_PrivateKey_traditional() writes out a private key in the
"traditional" format with a simple private key marker and should only
be used for compatibility with legacy programs.
PEM_write_bio_PKCS8PrivateKey() and PEM_write_PKCS8PrivateKey() write a private
key in an EVP_PKEY structure in PKCS#8 EncryptedPrivateKeyInfo format using
PKCS#5 v2.0 password based encryption algorithms. The I<cipher> argument
specifies the encryption algorithm to use: unlike some other PEM routines the
encryption is applied at the PKCS#8 level and not in the PEM headers. If
I<cipher> is NULL then no encryption is used and a PKCS#8 PrivateKeyInfo
structure is used instead.
PEM_write_bio_PKCS8PrivateKey_nid() and PEM_write_PKCS8PrivateKey_nid()
also write out a private key as a PKCS#8 EncryptedPrivateKeyInfo however
it uses PKCS#5 v1.5 or PKCS#12 encryption algorithms instead. The algorithm
to use is specified in the I<nid> parameter and should be the NID of the
corresponding OBJECT IDENTIFIER (see NOTES section).
The B<PUBKEY> functions process a public key using an EVP_PKEY
structure. The public key is encoded as a SubjectPublicKeyInfo
structure.
The B<RSAPrivateKey> functions process an RSA private key using an
RSA structure. The write routines uses traditional format. The read
routines handles the same formats as the B<PrivateKey>
functions but an error occurs if the private key is not RSA.
The B<RSAPublicKey> functions process an RSA public key using an
RSA structure. The public key is encoded using a PKCS#1 RSAPublicKey
structure.
The B<RSA_PUBKEY> functions also process an RSA public key using
an RSA structure. However, the public key is encoded using a
SubjectPublicKeyInfo structure and an error occurs if the public
key is not RSA.
The B<DSAPrivateKey> functions process a DSA private key using a
DSA structure. The write routines uses traditional format. The read
routines handles the same formats as the B<PrivateKey>
functions but an error occurs if the private key is not DSA.
The B<DSA_PUBKEY> functions process a DSA public key using
a DSA structure. The public key is encoded using a
SubjectPublicKeyInfo structure and an error occurs if the public
key is not DSA.
The B<Parameters> functions read or write key parameters in PEM format using
an EVP_PKEY structure. The encoding depends on the type of key; for DSA key
parameters, it will be a Dss-Parms structure as defined in RFC2459, and for DH
key parameters, it will be a PKCS#3 DHparameter structure. I<These functions
only exist for the B<BIO> type>.
The B<DSAparams> functions process DSA parameters using a DSA
structure. The parameters are encoded using a Dss-Parms structure
as defined in RFC2459.
The B<DHparams> functions process DH parameters using a DH
structure. The parameters are encoded using a PKCS#3 DHparameter
structure.
The B<X509> functions process an X509 certificate using an X509
structure. They will also process a trusted X509 certificate but
any trust settings are discarded.
The B<X509_AUX> functions process a trusted X509 certificate using
an X509 structure.
The B<X509_REQ> and B<X509_REQ_NEW> functions process a PKCS#10
certificate request using an X509_REQ structure. The B<X509_REQ>
write functions use B<CERTIFICATE REQUEST> in the header whereas
the B<X509_REQ_NEW> functions use B<NEW CERTIFICATE REQUEST>
(as required by some CAs). The B<X509_REQ> read functions will
handle either form so there are no B<X509_REQ_NEW> read functions.
The B<X509_CRL> functions process an X509 CRL using an X509_CRL
structure.
The B<PKCS7> functions process a PKCS#7 ContentInfo using a PKCS7
structure.
=head1 PEM FUNCTION ARGUMENTS
The PEM functions have many common arguments.
The I<bp> BIO parameter (if present) specifies the BIO to read from
or write to.
The I<fp> FILE parameter (if present) specifies the FILE pointer to
read from or write to.
The PEM read functions all take an argument I<B<TYPE> **x> and return
a I<B<TYPE> *> pointer. Where I<B<TYPE>> is whatever structure the function
uses. If I<x> is NULL then the parameter is ignored. If I<x> is not
NULL but I<*x> is NULL then the structure returned will be written
to I<*x>. If neither I<x> nor I<*x> is NULL then an attempt is made
to reuse the structure at I<*x> (but see BUGS and EXAMPLES sections).
Irrespective of the value of I<x> a pointer to the structure is always
-returned (or NULL if an error occurred).
+returned (or NULL if an error occurred). The caller retains ownership of the
+returned object and needs to free it when it is no longer needed, e.g.
+using X509_free() for X509 objects or EVP_PKEY_free() for EVP_PKEY objects.
The PEM functions which write private keys take an I<enc> parameter
which specifies the encryption algorithm to use, encryption is done
at the PEM level. If this parameter is set to NULL then the private
key is written in unencrypted form.
The I<cb> argument is the callback to use when querying for the pass
phrase used for encrypted PEM structures (normally only private keys).
For the PEM write routines if the I<kstr> parameter is not NULL then
I<klen> bytes at I<kstr> are used as the passphrase and I<cb> is
ignored.
If the I<cb> parameters is set to NULL and the I<u> parameter is not
NULL then the I<u> parameter is interpreted as a NUL terminated string
to use as the passphrase. If both I<cb> and I<u> are NULL then the
default callback routine is used which will typically prompt for the
passphrase on the current terminal with echoing turned off.
The default passphrase callback is sometimes inappropriate (for example
in a GUI application) so an alternative can be supplied. The callback
routine has the following form:
int cb(char *buf, int size, int rwflag, void *u);
I<buf> is the buffer to write the passphrase to. I<size> is the maximum
length of the passphrase (i.e. the size of buf). I<rwflag> is a flag
which is set to 0 when reading and 1 when writing. A typical routine
will ask the user to verify the passphrase (for example by prompting
for it twice) if I<rwflag> is 1. The I<u> parameter has the same
value as the I<u> parameter passed to the PEM routine. It allows
arbitrary data to be passed to the callback by the application
(for example a window handle in a GUI application). The callback
I<must> return the number of characters in the passphrase or -1 if
an error occurred. The passphrase can be arbitrary data; in the case where it
is a string, it is not NUL terminated. See the L</EXAMPLES> section below.
Some implementations may need to use cryptographic algorithms during their
operation. If this is the case and I<libctx> and I<propq> parameters have been
passed then any algorithm fetches will use that library context and property
query string. Otherwise the default library context and property query string
will be used.
=head1 NOTES
The PEM reading functions will skip any extraneous content or PEM data of
a different type than they expect. This allows for example having a certificate
(or multiple certificates) and a key in the PEM format in a single file.
The old B<PrivateKey> write routines are retained for compatibility.
New applications should write private keys using the
PEM_write_bio_PKCS8PrivateKey() or PEM_write_PKCS8PrivateKey() routines
because they are more secure (they use an iteration count of 2048 whereas
the traditional routines use a count of 1) unless compatibility with older
versions of OpenSSL is important.
The B<PrivateKey> read routines can be used in all applications because
they handle all formats transparently.
A frequent cause of problems is attempting to use the PEM routines like
this:
X509 *x;
PEM_read_bio_X509(bp, &x, 0, NULL);
this is a bug because an attempt will be made to reuse the data at I<x>
which is an uninitialised pointer.
These functions make no assumption regarding the pass phrase received from the
password callback.
It will simply be treated as a byte sequence.
=head1 PEM ENCRYPTION FORMAT
These old B<PrivateKey> routines use a non standard technique for encryption.
The private key (or other data) takes the following form:
-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: DES-EDE3-CBC,3F17F5316E2BAC89
...base64 encoded data...
-----END RSA PRIVATE KEY-----
The line beginning with I<Proc-Type> contains the version and the
protection on the encapsulated data. The line beginning I<DEK-Info>
contains two comma separated values: the encryption algorithm name as
used by EVP_get_cipherbyname() and an initialization vector used by the
cipher encoded as a set of hexadecimal digits. After those two lines is
the base64-encoded encrypted data.
The encryption key is derived using EVP_BytesToKey(). The cipher's
initialization vector is passed to EVP_BytesToKey() as the I<salt>
parameter. Internally, B<PKCS5_SALT_LEN> bytes of the salt are used
(regardless of the size of the initialization vector). The user's
password is passed to EVP_BytesToKey() using the I<data> and I<datal>
parameters. Finally, the library uses an iteration count of 1 for
EVP_BytesToKey().
The I<key> derived by EVP_BytesToKey() along with the original initialization
vector is then used to decrypt the encrypted data. The I<iv> produced by
EVP_BytesToKey() is not utilized or needed, and NULL should be passed to
the function.
The pseudo code to derive the key would look similar to:
EVP_CIPHER* cipher = EVP_des_ede3_cbc();
EVP_MD* md = EVP_md5();
unsigned int nkey = EVP_CIPHER_get_key_length(cipher);
unsigned int niv = EVP_CIPHER_get_iv_length(cipher);
unsigned char key[nkey];
unsigned char iv[niv];
memcpy(iv, HexToBin("3F17F5316E2BAC89"), niv);
rc = EVP_BytesToKey(cipher, md, iv /*salt*/, pword, plen, 1, key, NULL /*iv*/);
if (rc != nkey)
/* Error */
/* On success, use key and iv to initialize the cipher */
=head1 BUGS
The PEM read routines in some versions of OpenSSL will not correctly reuse
an existing structure. Therefore, the following:
PEM_read_bio_X509(bp, &x, 0, NULL);
where I<x> already contains a valid certificate, may not work, whereas:
X509_free(x);
x = PEM_read_bio_X509(bp, NULL, 0, NULL);
is guaranteed to work. It is always acceptable for I<x> to contain a newly
allocated, empty B<X509> object (for example allocated via L<X509_new_ex(3)>).
=head1 RETURN VALUES
The read routines return either a pointer to the structure read or NULL
if an error occurred.
The write routines return 1 for success or 0 for failure.
=head1 EXAMPLES
Although the PEM routines take several arguments in almost all applications
most of them are set to 0 or NULL.
To read a certificate with a library context in PEM format from a BIO:
X509 *x = X509_new_ex(libctx, NULL);
if (x == NULL)
/* Error */
if (PEM_read_bio_X509(bp, &x, 0, NULL) == NULL)
/* Error */
Read a certificate in PEM format from a BIO:
X509 *x;
x = PEM_read_bio_X509(bp, NULL, 0, NULL);
if (x == NULL)
/* Error */
Alternative method:
X509 *x = NULL;
if (!PEM_read_bio_X509(bp, &x, 0, NULL))
/* Error */
Write a certificate to a BIO:
if (!PEM_write_bio_X509(bp, x))
/* Error */
Write a private key (using traditional format) to a BIO using
triple DES encryption, the pass phrase is prompted for:
if (!PEM_write_bio_PrivateKey(bp, key, EVP_des_ede3_cbc(), NULL, 0, 0, NULL))
/* Error */
Write a private key (using PKCS#8 format) to a BIO using triple
DES encryption, using the pass phrase "hello":
if (!PEM_write_bio_PKCS8PrivateKey(bp, key, EVP_des_ede3_cbc(),
NULL, 0, 0, "hello"))
/* Error */
Read a private key from a BIO using a pass phrase callback:
key = PEM_read_bio_PrivateKey(bp, NULL, pass_cb, "My Private Key");
if (key == NULL)
/* Error */
Skeleton pass phrase callback:
int pass_cb(char *buf, int size, int rwflag, void *u)
{
/* We'd probably do something else if 'rwflag' is 1 */
printf("Enter pass phrase for \"%s\"\n", (char *)u);
/* get pass phrase, length 'len' into 'tmp' */
char *tmp = "hello";
if (tmp == NULL) /* An error occurred */
return -1;
size_t len = strlen(tmp);
if (len > size)
len = size;
memcpy(buf, tmp, len);
return len;
}
=head1 SEE ALSO
L<EVP_EncryptInit(3)>, L<EVP_BytesToKey(3)>,
L<passphrase-encoding(7)>
=head1 HISTORY
The old Netscape certificate sequences were no longer documented
in OpenSSL 1.1.0; applications should use the PKCS7 standard instead
as they will be formally deprecated in a future releases.
PEM_read_bio_PrivateKey_ex(), PEM_read_PrivateKey_ex(),
PEM_read_bio_PUBKEY_ex(), PEM_read_PUBKEY_ex() and
PEM_read_bio_Parameters_ex() were introduced in OpenSSL 3.0.
The functions PEM_read_bio_RSAPrivateKey(), PEM_read_RSAPrivateKey(),
PEM_write_bio_RSAPrivateKey(), PEM_write_RSAPrivateKey(),
PEM_read_bio_RSAPublicKey(), PEM_read_RSAPublicKey(),
PEM_write_bio_RSAPublicKey(), PEM_write_RSAPublicKey(),
PEM_read_bio_RSA_PUBKEY(), PEM_read_RSA_PUBKEY(),
PEM_write_bio_RSA_PUBKEY(), PEM_write_RSA_PUBKEY(),
PEM_read_bio_DSAPrivateKey(), PEM_read_DSAPrivateKey(),
PEM_write_bio_DSAPrivateKey(), PEM_write_DSAPrivateKey(),
PEM_read_bio_DSA_PUBKEY(), PEM_read_DSA_PUBKEY(),
PEM_write_bio_DSA_PUBKEY(), PEM_write_DSA_PUBKEY();
PEM_read_bio_DSAparams(), PEM_read_DSAparams(),
PEM_write_bio_DSAparams(), PEM_write_DSAparams(),
PEM_read_bio_DHparams(), PEM_read_DHparams(),
PEM_write_bio_DHparams() and PEM_write_DHparams() were deprecated in 3.0.
=head1 COPYRIGHT
-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
L<https://www.openssl.org/source/license.html>.
=cut
diff --git a/crypto/openssl/doc/man3/RAND_set_DRBG_type.pod b/crypto/openssl/doc/man3/RAND_set_DRBG_type.pod
index f78c15ff45f3..423ebfad656f 100644
--- a/crypto/openssl/doc/man3/RAND_set_DRBG_type.pod
+++ b/crypto/openssl/doc/man3/RAND_set_DRBG_type.pod
@@ -1,64 +1,64 @@
=pod
=head1 NAME
RAND_set_DRBG_type,
RAND_set_seed_source_type
- specify the global random number generator types
=head1 SYNOPSIS
#include <openssl/rand.h>
int RAND_set_DRBG_type(OSSL_LIB_CTX *ctx, const char *drbg, const char *propq,
const char *cipher, const char *digest);
int RAND_set_seed_source_type(OSSL_LIB_CTX *ctx, const char *seed,
const char *propq);
=head1 DESCRIPTION
RAND_set_DRBG_type() specifies the random bit generator that will be
used within the library context I<ctx>. A generator of name I<drbg>
with properties I<propq> will be fetched. It will be instantiated with
either I<cipher> or I<digest> as its underlying cryptographic algorithm.
This specifies the type that will be used for the primary, public and
private random instances.
RAND_set_seed_source_type() specifies the seed source that will be used
within the library context I<ctx>. The seed source of name I<seed>
with properties I<propq> will be fetched and used to seed the primary
-random big generator.
+random bit generator.
=head1 RETURN VALUES
These function return 1 on success and 0 on failure.
=head1 NOTES
These functions must be called before the random bit generators are first
created in the library context. They will return an error if the call
is made too late.
The default DRBG is "CTR-DRBG" using the "AES-256-CTR" cipher.
The default seed source is "SEED-SRC".
=head1 SEE ALSO
L<EVP_RAND(3)>,
L<RAND_get0_primary(3)>
=head1 HISTORY
These functions were added in OpenSSL 3.0.
=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/man3/RSA_meth_new.pod b/crypto/openssl/doc/man3/RSA_meth_new.pod
index 29ea4161b0b5..40f9bc4e8281 100644
--- a/crypto/openssl/doc/man3/RSA_meth_new.pod
+++ b/crypto/openssl/doc/man3/RSA_meth_new.pod
@@ -1,270 +1,270 @@
=pod
=head1 NAME
RSA_meth_get0_app_data, RSA_meth_set0_app_data,
RSA_meth_new, RSA_meth_free, RSA_meth_dup, RSA_meth_get0_name,
RSA_meth_set1_name, RSA_meth_get_flags, RSA_meth_set_flags,
RSA_meth_get_pub_enc,
RSA_meth_set_pub_enc, RSA_meth_get_pub_dec, RSA_meth_set_pub_dec,
RSA_meth_get_priv_enc, RSA_meth_set_priv_enc, RSA_meth_get_priv_dec,
RSA_meth_set_priv_dec, RSA_meth_get_mod_exp, RSA_meth_set_mod_exp,
RSA_meth_get_bn_mod_exp, RSA_meth_set_bn_mod_exp, RSA_meth_get_init,
RSA_meth_set_init, RSA_meth_get_finish, RSA_meth_set_finish,
RSA_meth_get_sign, RSA_meth_set_sign, RSA_meth_get_verify,
RSA_meth_set_verify, RSA_meth_get_keygen, RSA_meth_set_keygen,
RSA_meth_get_multi_prime_keygen, RSA_meth_set_multi_prime_keygen
- Routines to build up RSA methods
=head1 SYNOPSIS
#include <openssl/rsa.h>
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)>:
RSA_METHOD *RSA_meth_new(const char *name, int flags);
void RSA_meth_free(RSA_METHOD *meth);
RSA_METHOD *RSA_meth_dup(const RSA_METHOD *meth);
const char *RSA_meth_get0_name(const RSA_METHOD *meth);
int RSA_meth_set1_name(RSA_METHOD *meth, const char *name);
int RSA_meth_get_flags(const RSA_METHOD *meth);
int RSA_meth_set_flags(RSA_METHOD *meth, int flags);
void *RSA_meth_get0_app_data(const RSA_METHOD *meth);
int RSA_meth_set0_app_data(RSA_METHOD *meth, void *app_data);
int (*RSA_meth_get_pub_enc(const RSA_METHOD *meth))(int flen, const unsigned char *from,
unsigned char *to, RSA *rsa, int padding);
int RSA_meth_set_pub_enc(RSA_METHOD *rsa,
int (*pub_enc)(int flen, const unsigned char *from,
unsigned char *to, RSA *rsa,
int padding));
int (*RSA_meth_get_pub_dec(const RSA_METHOD *meth))
(int flen, const unsigned char *from,
unsigned char *to, RSA *rsa, int padding);
int RSA_meth_set_pub_dec(RSA_METHOD *rsa,
int (*pub_dec)(int flen, const unsigned char *from,
unsigned char *to, RSA *rsa,
int padding));
int (*RSA_meth_get_priv_enc(const RSA_METHOD *meth))(int flen, const unsigned char *from,
unsigned char *to, RSA *rsa,
int padding);
int RSA_meth_set_priv_enc(RSA_METHOD *rsa,
int (*priv_enc)(int flen, const unsigned char *from,
unsigned char *to, RSA *rsa, int padding));
int (*RSA_meth_get_priv_dec(const RSA_METHOD *meth))(int flen, const unsigned char *from,
unsigned char *to, RSA *rsa,
int padding);
int RSA_meth_set_priv_dec(RSA_METHOD *rsa,
int (*priv_dec)(int flen, const unsigned char *from,
unsigned char *to, RSA *rsa, int padding));
/* Can be null */
int (*RSA_meth_get_mod_exp(const RSA_METHOD *meth))(BIGNUM *r0, const BIGNUM *i,
RSA *rsa, BN_CTX *ctx);
int RSA_meth_set_mod_exp(RSA_METHOD *rsa,
int (*mod_exp)(BIGNUM *r0, const BIGNUM *i, RSA *rsa,
BN_CTX *ctx));
/* Can be null */
int (*RSA_meth_get_bn_mod_exp(const RSA_METHOD *meth))(BIGNUM *r, const BIGNUM *a,
const BIGNUM *p, const BIGNUM *m,
BN_CTX *ctx, BN_MONT_CTX *m_ctx);
int RSA_meth_set_bn_mod_exp(RSA_METHOD *rsa,
int (*bn_mod_exp)(BIGNUM *r, const BIGNUM *a,
const BIGNUM *p, const BIGNUM *m,
BN_CTX *ctx, BN_MONT_CTX *m_ctx));
/* called at new */
int (*RSA_meth_get_init(const RSA_METHOD *meth) (RSA *rsa);
int RSA_meth_set_init(RSA_METHOD *rsa, int (*init (RSA *rsa));
/* called at free */
int (*RSA_meth_get_finish(const RSA_METHOD *meth))(RSA *rsa);
int RSA_meth_set_finish(RSA_METHOD *rsa, int (*finish)(RSA *rsa));
int (*RSA_meth_get_sign(const RSA_METHOD *meth))(int type, const unsigned char *m,
unsigned int m_length,
unsigned char *sigret,
unsigned int *siglen, const RSA *rsa);
int RSA_meth_set_sign(RSA_METHOD *rsa,
int (*sign)(int type, const unsigned char *m,
unsigned int m_length, unsigned char *sigret,
unsigned int *siglen, const RSA *rsa));
int (*RSA_meth_get_verify(const RSA_METHOD *meth))(int dtype, const unsigned char *m,
unsigned int m_length,
const unsigned char *sigbuf,
unsigned int siglen, const RSA *rsa);
int RSA_meth_set_verify(RSA_METHOD *rsa,
int (*verify)(int dtype, const unsigned char *m,
unsigned int m_length,
const unsigned char *sigbuf,
unsigned int siglen, const RSA *rsa));
int (*RSA_meth_get_keygen(const RSA_METHOD *meth))(RSA *rsa, int bits, BIGNUM *e,
BN_GENCB *cb);
int RSA_meth_set_keygen(RSA_METHOD *rsa,
int (*keygen)(RSA *rsa, int bits, BIGNUM *e,
BN_GENCB *cb));
int (*RSA_meth_get_multi_prime_keygen(const RSA_METHOD *meth))(RSA *rsa, int bits,
int primes, BIGNUM *e,
BN_GENCB *cb);
int RSA_meth_set_multi_prime_keygen(RSA_METHOD *meth,
int (*keygen) (RSA *rsa, int bits,
int primes, BIGNUM *e,
BN_GENCB *cb));
=head1 DESCRIPTION
All of the functions described on this page are deprecated.
Applications should instead use the OSSL_PROVIDER APIs.
The B<RSA_METHOD> type is a structure used for the provision of custom
RSA implementations. It provides a set of functions used by OpenSSL
for the implementation of the various RSA capabilities.
RSA_meth_new() creates a new B<RSA_METHOD> structure. It should be
given a unique B<name> and a set of B<flags>. The B<name> should be a
NULL terminated string, which will be duplicated and stored in the
B<RSA_METHOD> object. It is the callers responsibility to free the
original string. The flags will be used during the construction of a
new B<RSA> object based on this B<RSA_METHOD>. Any new B<RSA> object
will have those flags set by default.
RSA_meth_dup() creates a duplicate copy of the B<RSA_METHOD> object
passed as a parameter. This might be useful for creating a new
B<RSA_METHOD> based on an existing one, but with some differences.
RSA_meth_free() destroys an B<RSA_METHOD> structure and frees up any
-memory associated with it.
+memory associated with it. If the argument is NULL, nothing is done.
RSA_meth_get0_name() will return a pointer to the name of this
RSA_METHOD. This is a pointer to the internal name string and so
should not be freed by the caller. RSA_meth_set1_name() sets the name
of the RSA_METHOD to B<name>. The string is duplicated and the copy is
stored in the RSA_METHOD structure, so the caller remains responsible
for freeing the memory associated with the name.
RSA_meth_get_flags() returns the current value of the flags associated
with this RSA_METHOD. RSA_meth_set_flags() provides the ability to set
these flags.
The functions RSA_meth_get0_app_data() and RSA_meth_set0_app_data()
provide the ability to associate implementation specific data with the
RSA_METHOD. It is the application's responsibility to free this data
before the RSA_METHOD is freed via a call to RSA_meth_free().
RSA_meth_get_sign() and RSA_meth_set_sign() get and set the function
used for creating an RSA signature respectively. This function will be
called in response to the application calling RSA_sign(). The
parameters for the function have the same meaning as for RSA_sign().
RSA_meth_get_verify() and RSA_meth_set_verify() get and set the
function used for verifying an RSA signature respectively. This
function will be called in response to the application calling
RSA_verify(). The parameters for the function have the same meaning as
for RSA_verify().
RSA_meth_get_mod_exp() and RSA_meth_set_mod_exp() get and set the
function used for CRT computations.
RSA_meth_get_bn_mod_exp() and RSA_meth_set_bn_mod_exp() get and set
the function used for CRT computations, specifically the following
value:
r = a ^ p mod m
Both the mod_exp() and bn_mod_exp() functions are called by the
default OpenSSL method during encryption, decryption, signing and
verification.
RSA_meth_get_init() and RSA_meth_set_init() get and set the function
used for creating a new RSA instance respectively. This function will
be called in response to the application calling RSA_new() (if the
current default RSA_METHOD is this one) or RSA_new_method(). The
RSA_new() and RSA_new_method() functions will allocate the memory for
the new RSA object, and a pointer to this newly allocated structure
will be passed as a parameter to the function. This function may be
NULL.
RSA_meth_get_finish() and RSA_meth_set_finish() get and set the
function used for destroying an instance of an RSA object respectively.
This function will be called in response to the application calling
RSA_free(). A pointer to the RSA to be destroyed is passed as a
parameter. The destroy function should be used for RSA implementation
specific clean up. The memory for the RSA itself should not be freed
by this function. This function may be NULL.
RSA_meth_get_keygen() and RSA_meth_set_keygen() get and set the
function used for generating a new RSA key pair respectively. This
function will be called in response to the application calling
RSA_generate_key_ex(). The parameter for the function has the same
meaning as for RSA_generate_key_ex().
RSA_meth_get_multi_prime_keygen() and RSA_meth_set_multi_prime_keygen() get
and set the function used for generating a new multi-prime RSA key pair
respectively. This function will be called in response to the application calling
RSA_generate_multi_prime_key(). The parameter for the function has the same
meaning as for RSA_generate_multi_prime_key().
RSA_meth_get_pub_enc(), RSA_meth_set_pub_enc(),
RSA_meth_get_pub_dec(), RSA_meth_set_pub_dec(),
RSA_meth_get_priv_enc(), RSA_meth_set_priv_enc(),
RSA_meth_get_priv_dec(), RSA_meth_set_priv_dec() get and set the
functions used for public and private key encryption and decryption.
These functions will be called in response to the application calling
RSA_public_encrypt(), RSA_private_decrypt(), RSA_private_encrypt() and
RSA_public_decrypt() and take the same parameters as those.
=head1 RETURN VALUES
RSA_meth_new() and RSA_meth_dup() return the newly allocated
RSA_METHOD object or NULL on failure.
RSA_meth_get0_name() and RSA_meth_get_flags() return the name and
flags associated with the RSA_METHOD respectively.
All other RSA_meth_get_*() functions return the appropriate function
pointer that has been set in the RSA_METHOD, or NULL if no such
pointer has yet been set.
RSA_meth_set1_name and all RSA_meth_set_*() functions return 1 on
success or 0 on failure.
=head1 SEE ALSO
L<RSA_new(3)>, L<RSA_generate_key_ex(3)>, L<RSA_sign(3)>,
L<RSA_set_method(3)>, L<RSA_size(3)>, L<RSA_get0_key(3)>,
L<RSA_generate_multi_prime_key(3)>
=head1 HISTORY
All of these functions were deprecated in OpenSSL 3.0.
RSA_meth_get_multi_prime_keygen() and RSA_meth_set_multi_prime_keygen() were
added in OpenSSL 1.1.1.
Other functions described here were added in OpenSSL 1.1.0.
=head1 COPYRIGHT
-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
L<https://www.openssl.org/source/license.html>.
=cut
diff --git a/crypto/openssl/doc/man3/SCT_new.pod b/crypto/openssl/doc/man3/SCT_new.pod
index 235762721992..a20affd38a84 100644
--- a/crypto/openssl/doc/man3/SCT_new.pod
+++ b/crypto/openssl/doc/man3/SCT_new.pod
@@ -1,220 +1,226 @@
=pod
=head1 NAME
SCT_new, SCT_new_from_base64, SCT_free, SCT_LIST_free,
SCT_get_version, SCT_set_version,
SCT_get_log_entry_type, SCT_set_log_entry_type,
SCT_get0_log_id, SCT_set0_log_id, SCT_set1_log_id,
SCT_get_timestamp, SCT_set_timestamp,
SCT_get_signature_nid, SCT_set_signature_nid,
SCT_get0_signature, SCT_set0_signature, SCT_set1_signature,
SCT_get0_extensions, SCT_set0_extensions, SCT_set1_extensions,
SCT_get_source, SCT_set_source
- A Certificate Transparency Signed Certificate Timestamp
=head1 SYNOPSIS
#include <openssl/ct.h>
typedef enum {
CT_LOG_ENTRY_TYPE_NOT_SET = -1,
CT_LOG_ENTRY_TYPE_X509 = 0,
CT_LOG_ENTRY_TYPE_PRECERT = 1
} ct_log_entry_type_t;
typedef enum {
SCT_VERSION_NOT_SET = -1,
SCT_VERSION_V1 = 0
} sct_version_t;
typedef enum {
SCT_SOURCE_UNKNOWN,
SCT_SOURCE_TLS_EXTENSION,
SCT_SOURCE_X509V3_EXTENSION,
SCT_SOURCE_OCSP_STAPLED_RESPONSE
} sct_source_t;
SCT *SCT_new(void);
SCT *SCT_new_from_base64(unsigned char version,
const char *logid_base64,
ct_log_entry_type_t entry_type,
uint64_t timestamp,
const char *extensions_base64,
const char *signature_base64);
void SCT_free(SCT *sct);
void SCT_LIST_free(STACK_OF(SCT) *a);
sct_version_t SCT_get_version(const SCT *sct);
int SCT_set_version(SCT *sct, sct_version_t version);
ct_log_entry_type_t SCT_get_log_entry_type(const SCT *sct);
int SCT_set_log_entry_type(SCT *sct, ct_log_entry_type_t entry_type);
size_t SCT_get0_log_id(const SCT *sct, unsigned char **log_id);
int SCT_set0_log_id(SCT *sct, unsigned char *log_id, size_t log_id_len);
int SCT_set1_log_id(SCT *sct, const unsigned char *log_id, size_t log_id_len);
uint64_t SCT_get_timestamp(const SCT *sct);
void SCT_set_timestamp(SCT *sct, uint64_t timestamp);
int SCT_get_signature_nid(const SCT *sct);
int SCT_set_signature_nid(SCT *sct, int nid);
size_t SCT_get0_signature(const SCT *sct, unsigned char **sig);
void SCT_set0_signature(SCT *sct, unsigned char *sig, size_t sig_len);
int SCT_set1_signature(SCT *sct, const unsigned char *sig, size_t sig_len);
size_t SCT_get0_extensions(const SCT *sct, unsigned char **ext);
void SCT_set0_extensions(SCT *sct, unsigned char *ext, size_t ext_len);
int SCT_set1_extensions(SCT *sct, const unsigned char *ext, size_t ext_len);
sct_source_t SCT_get_source(const SCT *sct);
int SCT_set_source(SCT *sct, sct_source_t source);
=head1 DESCRIPTION
Signed Certificate Timestamps (SCTs) are defined by RFC 6962, Section 3.2.
They constitute a promise by a Certificate Transparency (CT) log to publicly
record a certificate. By cryptographically verifying that a log did indeed issue
an SCT, some confidence can be gained that the certificate is publicly known.
An internal representation of an SCT can be created in one of two ways.
The first option is to create a blank SCT, using SCT_new(), and then populate
it using:
=over 2
=item *
SCT_set_version() to set the SCT version.
Only SCT_VERSION_V1 is currently supported.
=item *
SCT_set_log_entry_type() to set the type of certificate the SCT was issued for:
B<CT_LOG_ENTRY_TYPE_X509> for a normal certificate.
B<CT_LOG_ENTRY_TYPE_PRECERT> for a pre-certificate.
=item *
SCT_set0_log_id() or SCT_set1_log_id() to set the LogID of the CT log that the SCT came from.
The former takes ownership, whereas the latter makes a copy.
See RFC 6962, Section 3.2 for the definition of LogID.
=item *
SCT_set_timestamp() to set the time the SCT was issued (time in milliseconds
since the Unix Epoch).
=item *
SCT_set_signature_nid() to set the NID of the signature.
=item *
SCT_set0_signature() or SCT_set1_signature() to set the raw signature value.
The former takes ownership, whereas the latter makes a copy.
=item *
SCT_set0_extensions() or B<SCT_set1_extensions> to provide SCT extensions.
The former takes ownership, whereas the latter makes a copy.
=back
Alternatively, the SCT can be pre-populated from the following data using
SCT_new_from_base64():
=over 2
=item *
The SCT version (only SCT_VERSION_V1 is currently supported).
=item *
The LogID (see RFC 6962, Section 3.2), base64 encoded.
=item *
The type of certificate the SCT was issued for:
B<CT_LOG_ENTRY_TYPE_X509> for a normal certificate.
B<CT_LOG_ENTRY_TYPE_PRECERT> for a pre-certificate.
=item *
The time that the SCT was issued (time in milliseconds since the Unix Epoch).
=item *
The SCT extensions, base64 encoded.
=item *
The SCT signature, base64 encoded.
=back
SCT_set_source() can be used to record where the SCT was found
(TLS extension, X.509 certificate extension or OCSP response). This is not
required for verifying the SCT.
+SCT_free() frees the specified SCT.
+If the argument is NULL, nothing is done.
+
+SCT_LIST_free() frees the specified stack of SCTs.
+If the argument is NULL, nothing is done.
+
=head1 NOTES
Some of the setters return int, instead of void. These will all return 1 on
success, 0 on failure. They will not make changes on failure.
All of the setters will reset the validation status of the SCT to
SCT_VALIDATION_STATUS_NOT_SET (see L<SCT_validate(3)>).
SCT_set_source() will call SCT_set_log_entry_type() if the type of
certificate the SCT was issued for can be inferred from where the SCT was found.
For example, an SCT found in an X.509 extension must have been issued for a pre-
certificate.
SCT_set_source() will not refuse unknown values.
=head1 RETURN VALUES
SCT_set_version() returns 1 if the specified version is supported, 0 otherwise.
SCT_set_log_entry_type() returns 1 if the specified log entry type is supported, 0 otherwise.
SCT_set0_log_id() and B<SCT_set1_log_id> return 1 if the specified LogID is a
valid SHA-256 hash, 0 otherwise. Additionally, B<SCT_set1_log_id> returns 0 if
malloc fails.
B<SCT_set_signature_nid> returns 1 if the specified NID is supported, 0 otherwise.
B<SCT_set1_extensions> and B<SCT_set1_signature> return 1 if the supplied buffer
is copied successfully, 0 otherwise (i.e. if malloc fails).
B<SCT_set_source> returns 1 on success, 0 otherwise.
=head1 SEE ALSO
L<ct(7)>,
L<SCT_validate(3)>,
L<OBJ_nid2obj(3)>
=head1 HISTORY
These functions were added in OpenSSL 1.1.0.
=head1 COPYRIGHT
-Copyright 2016-2017 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/man3/SSL_CTX_set_alpn_select_cb.pod b/crypto/openssl/doc/man3/SSL_CTX_set_alpn_select_cb.pod
index 102e6578512c..2997a9955756 100644
--- a/crypto/openssl/doc/man3/SSL_CTX_set_alpn_select_cb.pod
+++ b/crypto/openssl/doc/man3/SSL_CTX_set_alpn_select_cb.pod
@@ -1,197 +1,207 @@
=pod
=head1 NAME
SSL_CTX_set_alpn_protos, SSL_set_alpn_protos, SSL_CTX_set_alpn_select_cb,
SSL_CTX_set_next_proto_select_cb, SSL_CTX_set_next_protos_advertised_cb,
SSL_select_next_proto, SSL_get0_alpn_selected, SSL_get0_next_proto_negotiated
- handle application layer protocol negotiation (ALPN)
=head1 SYNOPSIS
#include <openssl/ssl.h>
int SSL_CTX_set_alpn_protos(SSL_CTX *ctx, const unsigned char *protos,
unsigned int protos_len);
int SSL_set_alpn_protos(SSL *ssl, const unsigned char *protos,
unsigned int protos_len);
void SSL_CTX_set_alpn_select_cb(SSL_CTX *ctx,
int (*cb) (SSL *ssl,
const unsigned char **out,
unsigned char *outlen,
const unsigned char *in,
unsigned int inlen,
void *arg), void *arg);
void SSL_get0_alpn_selected(const SSL *ssl, const unsigned char **data,
unsigned int *len);
void SSL_CTX_set_next_protos_advertised_cb(SSL_CTX *ctx,
int (*cb)(SSL *ssl,
const unsigned char **out,
unsigned int *outlen,
void *arg),
void *arg);
void SSL_CTX_set_next_proto_select_cb(SSL_CTX *ctx,
int (*cb)(SSL *s,
unsigned char **out,
unsigned char *outlen,
const unsigned char *in,
unsigned int inlen,
void *arg),
void *arg);
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);
void SSL_get0_next_proto_negotiated(const SSL *s, const unsigned char **data,
unsigned *len);
=head1 DESCRIPTION
SSL_CTX_set_alpn_protos() and SSL_set_alpn_protos() are used by the client to
set the list of protocols available to be negotiated. The B<protos> must be in
protocol-list format, described below. The length of B<protos> is specified in
-B<protos_len>.
+B<protos_len>. Setting B<protos_len> to 0 clears any existing list of ALPN
+protocols and no ALPN extension will be sent to the server.
SSL_CTX_set_alpn_select_cb() sets the application callback B<cb> used by a
server to select which protocol to use for the incoming connection. When B<cb>
is NULL, ALPN is not used. The B<arg> value is a pointer which is passed to
the application callback.
B<cb> is the application defined callback. The B<in>, B<inlen> parameters are a
vector in protocol-list format. The value of the B<out>, B<outlen> vector
should be set to the value of a single protocol selected from the B<in>,
B<inlen> vector. The B<out> buffer may point directly into B<in>, or to a
buffer that outlives the handshake. The B<arg> parameter is the pointer set via
SSL_CTX_set_alpn_select_cb().
SSL_select_next_proto() is a helper function used to select protocols. It
implements the standard protocol selection. It is expected that this function
is called from the application callback B<cb>. The protocol data in B<server>,
B<server_len> and B<client>, B<client_len> must be in the protocol-list format
described below. The first item in the B<server>, B<server_len> list that
matches an item in the B<client>, B<client_len> list is selected, and returned
in B<out>, B<outlen>. The B<out> value will point into either B<server> or
-B<client>, so it should be copied immediately. If no match is found, the first
-item in B<client>, B<client_len> is returned in B<out>, B<outlen>. This
-function can also be used in the NPN callback.
+B<client>, so it should be copied immediately. The client list must include at
+least one valid (nonempty) protocol entry in the list.
+
+The SSL_select_next_proto() helper function can be useful from either the ALPN
+callback or the NPN callback (described below). If no match is found, the first
+item in B<client>, B<client_len> is returned in B<out>, B<outlen> and
+B<OPENSSL_NPN_NO_OVERLAP> is returned. This can be useful when implementing
+the NPN callback. In the ALPN case, the value returned in B<out> and B<outlen>
+must be ignored if B<OPENSSL_NPN_NO_OVERLAP> has been returned from
+SSL_select_next_proto().
SSL_CTX_set_next_proto_select_cb() sets a callback B<cb> that is called when a
client needs to select a protocol from the server's provided list, and a
user-defined pointer argument B<arg> which will be passed to this callback.
For the callback itself, B<out>
must be set to point to the selected protocol (which may be within B<in>).
The length of the protocol name must be written into B<outlen>. The
server's advertised protocols are provided in B<in> and B<inlen>. The
callback can assume that B<in> is syntactically valid. The client must
-select a protocol. It is fatal to the connection if this callback returns
-a value other than B<SSL_TLSEXT_ERR_OK>. The B<arg> parameter is the pointer
-set via SSL_CTX_set_next_proto_select_cb().
+select a protocol (although it may be an empty, zero length protocol). It is
+fatal to the connection if this callback returns a value other than
+B<SSL_TLSEXT_ERR_OK> or if the zero length protocol is selected. The B<arg>
+parameter is the pointer set via SSL_CTX_set_next_proto_select_cb().
SSL_CTX_set_next_protos_advertised_cb() sets a callback B<cb> that is called
when a TLS server needs a list of supported protocols for Next Protocol
Negotiation. The returned list must be in protocol-list format, described
below. The list is
returned by setting B<out> to point to it and B<outlen> to its length. This
memory will not be modified, but the B<SSL> does keep a
reference to it. The callback should return B<SSL_TLSEXT_ERR_OK> if it
wishes to advertise. Otherwise, no such extension will be included in the
ServerHello.
SSL_get0_alpn_selected() returns a pointer to the selected protocol in B<data>
with length B<len>. It is not NUL-terminated. B<data> is set to NULL and B<len>
is set to 0 if no protocol has been selected. B<data> must not be freed.
SSL_get0_next_proto_negotiated() sets B<data> and B<len> to point to the
client's requested protocol for this connection. If the client did not
request any protocol or NPN is not enabled, then B<data> is set to NULL and
B<len> to 0. 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.
=head1 NOTES
The protocol-lists must be in wire-format, which is defined as a vector of
nonempty, 8-bit length-prefixed, byte strings. The length-prefix byte is not
included in the length. Each string is limited to 255 bytes. A byte-string
length of 0 is invalid. A truncated byte-string is invalid. The length of the
vector is not in the vector itself, but in a separate variable.
Example:
unsigned char vector[] = {
6, 's', 'p', 'd', 'y', '/', '1',
8, 'h', 't', 't', 'p', '/', '1', '.', '1'
};
unsigned int length = sizeof(vector);
The ALPN callback is executed after the servername callback; as that servername
callback may update the SSL_CTX, and subsequently, the ALPN callback.
If there is no ALPN proposed in the ClientHello, the ALPN callback is not
invoked.
=head1 RETURN VALUES
SSL_CTX_set_alpn_protos() and SSL_set_alpn_protos() return 0 on success, and
non-0 on failure. WARNING: these functions reverse the return value convention.
SSL_select_next_proto() returns one of the following:
=over 4
=item OPENSSL_NPN_NEGOTIATED
A match was found and is returned in B<out>, B<outlen>.
=item OPENSSL_NPN_NO_OVERLAP
No match was found. The first item in B<client>, B<client_len> is returned in
-B<out>, B<outlen>.
+B<out>, B<outlen> (or B<NULL> and 0 in the case where the first entry in
+B<client> is invalid).
=back
The ALPN select callback B<cb>, must return one of the following:
=over 4
=item SSL_TLSEXT_ERR_OK
ALPN protocol selected.
=item SSL_TLSEXT_ERR_ALERT_FATAL
There was no overlap between the client's supplied list and the server
configuration.
=item SSL_TLSEXT_ERR_NOACK
ALPN protocol not selected, e.g., because no ALPN protocols are configured for
this connection.
=back
The callback set using SSL_CTX_set_next_proto_select_cb() should return
B<SSL_TLSEXT_ERR_OK> if successful. Any other value is fatal to the connection.
The callback set using SSL_CTX_set_next_protos_advertised_cb() should return
B<SSL_TLSEXT_ERR_OK> if it wishes to advertise. Otherwise, no such extension
will be included in the ServerHello.
=head1 SEE ALSO
L<ssl(7)>, L<SSL_CTX_set_tlsext_servername_callback(3)>,
L<SSL_CTX_set_tlsext_servername_arg(3)>
=head1 COPYRIGHT
-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 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_cipher_list.pod b/crypto/openssl/doc/man3/SSL_CTX_set_cipher_list.pod
index 71f399400c2a..08d7693f420e 100644
--- a/crypto/openssl/doc/man3/SSL_CTX_set_cipher_list.pod
+++ b/crypto/openssl/doc/man3/SSL_CTX_set_cipher_list.pod
@@ -1,129 +1,129 @@
=pod
=head1 NAME
SSL_CTX_set_cipher_list,
SSL_set_cipher_list,
SSL_CTX_set_ciphersuites,
SSL_set_ciphersuites,
OSSL_default_cipher_list,
OSSL_default_ciphersuites
- choose list of available SSL_CIPHERs
=head1 SYNOPSIS
#include <openssl/ssl.h>
int SSL_CTX_set_cipher_list(SSL_CTX *ctx, const char *str);
int SSL_set_cipher_list(SSL *ssl, const char *str);
int SSL_CTX_set_ciphersuites(SSL_CTX *ctx, const char *str);
int SSL_set_ciphersuites(SSL *s, const char *str);
const char *OSSL_default_cipher_list(void);
const char *OSSL_default_ciphersuites(void);
=head1 DESCRIPTION
SSL_CTX_set_cipher_list() sets the list of available ciphers (TLSv1.2 and below)
for B<ctx> using the control string B<str>. The format of the string is described
in L<openssl-ciphers(1)>. The list of ciphers is inherited by all
B<ssl> objects created from B<ctx>. This function does not impact TLSv1.3
ciphersuites. Use SSL_CTX_set_ciphersuites() to configure those.
SSL_set_cipher_list() sets the list of ciphers (TLSv1.2 and below) only for
B<ssl>.
SSL_CTX_set_ciphersuites() is used to configure the available TLSv1.3
ciphersuites for B<ctx>. This is a simple colon (":") separated list of TLSv1.3
ciphersuite names in order of preference. Valid TLSv1.3 ciphersuite names are:
=over 4
=item TLS_AES_128_GCM_SHA256
=item TLS_AES_256_GCM_SHA384
=item TLS_CHACHA20_POLY1305_SHA256
=item TLS_AES_128_CCM_SHA256
=item TLS_AES_128_CCM_8_SHA256
=back
-An empty list is permissible. The default value for the this setting is:
+An empty list is permissible. The default value for this setting is:
"TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_SHA256:TLS_AES_128_GCM_SHA256"
SSL_set_ciphersuites() is the same as SSL_CTX_set_ciphersuites() except it
configures the ciphersuites for B<ssl>.
OSSL_default_cipher_list() returns the default cipher string for TLSv1.2
(and earlier) ciphers. OSSL_default_ciphersuites() returns the default
cipher string for TLSv1.3 ciphersuites.
=head1 NOTES
The control string B<str> for SSL_CTX_set_cipher_list(), SSL_set_cipher_list(),
SSL_CTX_set_ciphersuites() and SSL_set_ciphersuites() should be universally
usable and not depend on details of the library configuration (ciphers compiled
in). Thus no syntax checking takes place. Items that are not recognized, because
the corresponding ciphers are not compiled in or because they are mistyped,
are simply ignored. Failure is only flagged if no ciphers could be collected
at all.
It should be noted, that inclusion of a cipher to be used into the list is
a necessary condition. On the client side, the inclusion into the list is
also sufficient unless the security level excludes it. On the server side,
additional restrictions apply. All ciphers have additional requirements.
ADH ciphers don't need a certificate, but DH-parameters must have been set.
All other ciphers need a corresponding certificate and key.
An RSA cipher can only be chosen, when an RSA certificate is available.
RSA ciphers using DHE need a certificate and key and additional DH-parameters
(see L<SSL_CTX_set_tmp_dh_callback(3)>).
A DSA cipher can only be chosen, when a DSA certificate is available.
DSA ciphers always use DH key exchange and therefore need DH-parameters
(see L<SSL_CTX_set_tmp_dh_callback(3)>).
When these conditions are not met for any cipher in the list (e.g. a
client only supports export RSA ciphers with an asymmetric key length
of 512 bits and the server is not configured to use temporary RSA
keys), the "no shared cipher" (SSL_R_NO_SHARED_CIPHER) error is generated
and the handshake will fail.
OSSL_default_cipher_list() and OSSL_default_ciphersuites() replace
SSL_DEFAULT_CIPHER_LIST and TLS_DEFAULT_CIPHERSUITES, respectively. The
cipher list defines are deprecated as of 3.0.
=head1 RETURN VALUES
SSL_CTX_set_cipher_list() and SSL_set_cipher_list() return 1 if any cipher
could be selected and 0 on complete failure.
SSL_CTX_set_ciphersuites() and SSL_set_ciphersuites() return 1 if the requested
ciphersuite list was configured, and 0 otherwise.
=head1 SEE ALSO
L<ssl(7)>, L<SSL_get_ciphers(3)>,
L<SSL_CTX_use_certificate(3)>,
L<SSL_CTX_set_tmp_dh_callback(3)>,
L<openssl-ciphers(1)>
=head1 HISTORY
OSSL_default_cipher_list() and OSSL_default_ciphersites() are new in 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/man3/SSL_CTX_set_tlsext_ticket_key_cb.pod b/crypto/openssl/doc/man3/SSL_CTX_set_tlsext_ticket_key_cb.pod
index f289383c7815..e4871590f719 100644
--- a/crypto/openssl/doc/man3/SSL_CTX_set_tlsext_ticket_key_cb.pod
+++ b/crypto/openssl/doc/man3/SSL_CTX_set_tlsext_ticket_key_cb.pod
@@ -1,251 +1,251 @@
=pod
=head1 NAME
SSL_CTX_set_tlsext_ticket_key_evp_cb,
SSL_CTX_set_tlsext_ticket_key_cb
- set a callback for session ticket processing
=head1 SYNOPSIS
#include <openssl/tls1.h>
int SSL_CTX_set_tlsext_ticket_key_evp_cb(SSL_CTX sslctx,
int (*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));
The following function has 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)>:
int SSL_CTX_set_tlsext_ticket_key_cb(SSL_CTX sslctx,
int (*cb)(SSL *s, unsigned char key_name[16],
unsigned char iv[EVP_MAX_IV_LENGTH],
EVP_CIPHER_CTX *ctx, HMAC_CTX *hctx, int enc));
=head1 DESCRIPTION
SSL_CTX_set_tlsext_ticket_key_evp_cb() sets a callback function I<cb> for handling
session tickets for the ssl context I<sslctx>. Session tickets, defined in
RFC5077 provide an enhanced session resumption capability where the server
implementation is not required to maintain per session state. It only applies
to TLS and there is no SSLv3 implementation.
The callback function I<cb> will be called for every client instigated TLS
session when session ticket extension is presented in the TLS hello
message. It is the responsibility of this function to create or retrieve the
cryptographic parameters and to maintain their state.
The OpenSSL library uses your callback function to help implement a common TLS
ticket construction state according to RFC5077 Section 4 such that per session
state is unnecessary and a small set of cryptographic variables needs to be
maintained by the callback function implementation.
In order to reuse a session, a TLS client must send the session ticket
extension to the server. The client must send exactly one session ticket.
The server, through the callback function, either agrees to reuse the session
ticket information or it starts a full TLS handshake to create a new session
ticket.
Before the callback function is started I<ctx> and I<hctx> have been
initialised with L<EVP_CIPHER_CTX_reset(3)> and L<EVP_MAC_CTX_new(3)>
respectively.
For new sessions tickets, when the client doesn't present a session ticket, or
an attempted retrieval of the ticket failed, or a renew option was indicated,
the callback function will be called with I<enc> equal to 1. The OpenSSL
library expects that the function will set an arbitrary I<name>, initialize
I<iv>, and set the cipher context I<ctx> and the hash context I<hctx>.
The I<name> is 16 characters long and is used as a key identifier.
The I<iv> length is the length of the IV of the corresponding cipher. The
maximum IV length is B<EVP_MAX_IV_LENGTH> bytes defined in F<< <openssl/evp.h> >>.
The initialization vector I<iv> should be a random value. The cipher context
I<ctx> should use the initialisation vector I<iv>. The cipher context can be
set using L<EVP_EncryptInit_ex(3)>. The hmac context and digest can be set using
L<EVP_MAC_CTX_set_params(3)> with the B<OSSL_MAC_PARAM_KEY> and
B<OSSL_MAC_PARAM_DIGEST> parameters respectively.
When the client presents a session ticket, the callback function with be called
with I<enc> set to 0 indicating that the I<cb> function should retrieve a set
of parameters. In this case I<name> and I<iv> have already been parsed out of
the session ticket. The OpenSSL library expects that the I<name> will be used
to retrieve a cryptographic parameters and that the cryptographic context
I<ctx> will be set with the retrieved parameters and the initialization vector
I<iv>. using a function like L<EVP_DecryptInit_ex(3)>. The key material and
digest for I<hctx> need to be set using L<EVP_MAC_CTX_set_params(3)> with the
B<OSSL_MAC_PARAM_KEY> and B<OSSL_MAC_PARAM_DIGEST> parameters respectively.
If the I<name> is still valid but a renewal of the ticket is required the
callback function should return 2. The library will call the callback again
with an argument of enc equal to 1 to set the new ticket.
The return value of the I<cb> function is used by OpenSSL to determine what
further processing will occur. The following return values have meaning:
=over 4
=item Z<>2
This indicates that the I<ctx> and I<hctx> have been set and the session can
continue on those parameters. Additionally it indicates that the session
ticket is in a renewal period and should be replaced. The OpenSSL library will
call I<cb> again with an enc argument of 1 to set the new ticket (see RFC5077
3.3 paragraph 2).
=item Z<>1
This indicates that the I<ctx> and I<hctx> have been set and the session can
continue on those parameters.
=item Z<>0
This indicates that it was not possible to set/retrieve a session ticket and
the SSL/TLS session will continue by negotiating a set of cryptographic
parameters or using the alternate SSL/TLS resumption mechanism, session ids.
If called with enc equal to 0 the library will call the I<cb> again to get
a new set of parameters.
=item less than 0
This indicates an error.
=back
The SSL_CTX_set_tlsext_ticket_key_cb() function is identical to
SSL_CTX_set_tlsext_ticket_key_evp_cb() except that it takes a deprecated
HMAC_CTX pointer instead of an EVP_MAC_CTX one.
Before this callback function is started I<hctx> will have been
initialised with L<EVP_MAC_CTX_new(3)> and the digest set with
L<EVP_MAC_CTX_set_params(3)>.
The I<hctx> key material can be set using L<HMAC_Init_ex(3)>.
=head1 NOTES
-Session resumption shortcuts the TLS so that the client certificate
-negotiation don't occur. It makes up for this by storing client certificate
-an all other negotiated state information encrypted within the ticket. In a
+Session resumption shortcuts the TLS handshake so that the client certificate
+negotiation doesn't occur. It makes up for this by storing the client certificate
+and all other negotiated state information encrypted within the ticket. In a
resumed session the applications will have all this state information available
exactly as if a full negotiation had occurred.
If an attacker can obtain the key used to encrypt a session ticket, they can
obtain the master secret for any ticket using that key and decrypt any traffic
using that session: even if the cipher suite supports forward secrecy. As
a result applications may wish to use multiple keys and avoid using long term
keys stored in files.
Applications can use longer keys to maintain a consistent level of security.
For example if a cipher suite uses 256 bit ciphers but only a 128 bit ticket key
the overall security is only 128 bits because breaking the ticket key will
enable an attacker to obtain the session keys.
=head1 RETURN VALUES
Returns 1 to indicate the callback function was set and 0 otherwise.
=head1 EXAMPLES
Reference Implementation:
SSL_CTX_set_tlsext_ticket_key_evp_cb(SSL, ssl_tlsext_ticket_key_cb);
...
static int ssl_tlsext_ticket_key_cb(SSL *s, unsigned char key_name[16],
unsigned char *iv, EVP_CIPHER_CTX *ctx,
EVP_MAC_CTX *hctx, int enc)
{
OSSL_PARAM params[3];
your_type_t *key; /* something that you need to implement */
if (enc) { /* create new session */
if (RAND_bytes(iv, EVP_MAX_IV_LENGTH) <= 0)
return -1; /* insufficient random */
key = currentkey(); /* something that you need to implement */
if (key == NULL) {
/* current key doesn't exist or isn't valid */
key = createkey(); /*
* Something that you need to implement.
* createkey needs to initialise a name,
* an aes_key, a hmac_key and optionally
* an expire time.
*/
if (key == NULL) /* key couldn't be created */
return 0;
}
memcpy(key_name, key->name, 16);
if (EVP_EncryptInit_ex(&ctx, EVP_aes_256_cbc(), NULL, key->aes_key,
iv) == 0)
return -1; /* error in cipher initialisation */
params[0] = OSSL_PARAM_construct_octet_string(OSSL_MAC_PARAM_KEY,
key->hmac_key, 32);
params[1] = OSSL_PARAM_construct_utf8_string(OSSL_MAC_PARAM_DIGEST,
"sha256", 0);
params[2] = OSSL_PARAM_construct_end();
if (EVP_MAC_CTX_set_params(hctx, params) == 0)
return -1; /* error in mac initialisation */
return 1;
} else { /* retrieve session */
time_t t = time(NULL);
key = findkey(key_name); /* something that you need to implement */
if (key == NULL || key->expire < t)
return 0;
params[0] = OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_KEY,
key->hmac_key, 32);
params[1] = OSSL_PARAM_construct_utf8_string(OSSL_MAC_PARAM_DIGEST,
"sha256", 0);
params[2] = OSSL_PARAM_construct_end();
if (EVP_MAC_CTX_set_params(hctx, params) == 0)
return -1; /* error in mac initialisation */
if (EVP_DecryptInit_ex(&ctx, EVP_aes_256_cbc(), NULL, key->aes_key,
iv) == 0)
return -1; /* error in cipher initialisation */
if (key->expire < t - RENEW_TIME) { /* RENEW_TIME: implement */
/*
* return 2 - This session will get a new ticket even though the
* current one is still valid.
*/
return 2;
}
return 1;
}
}
=head1 SEE ALSO
L<ssl(7)>, L<SSL_set_session(3)>,
L<SSL_session_reused(3)>,
L<SSL_CTX_add_session(3)>,
L<SSL_CTX_sess_number(3)>,
L<SSL_CTX_sess_set_get_cb(3)>,
L<SSL_CTX_set_session_id_context(3)>,
=head1 HISTORY
The SSL_CTX_set_tlsext_ticket_key_cb() function was deprecated in OpenSSL 3.0.
The SSL_CTX_set_tlsext_ticket_key_evp_cb() function was introduced in
OpenSSL 3.0.
=head1 COPYRIGHT
-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
L<https://www.openssl.org/source/license.html>.
=cut
diff --git a/crypto/openssl/doc/man3/TS_RESP_CTX_new.pod b/crypto/openssl/doc/man3/TS_RESP_CTX_new.pod
index 725a1921d133..01fd23a10eb4 100644
--- a/crypto/openssl/doc/man3/TS_RESP_CTX_new.pod
+++ b/crypto/openssl/doc/man3/TS_RESP_CTX_new.pod
@@ -1,49 +1,50 @@
=pod
=head1 NAME
TS_RESP_CTX_new_ex, TS_RESP_CTX_new,
TS_RESP_CTX_free - Timestamp response context object creation
=head1 SYNOPSIS
#include <openssl/ts.h>
TS_RESP_CTX *TS_RESP_CTX_new_ex(OSSL_LIB_CTX *libctx, const char *propq);
TS_RESP_CTX *TS_RESP_CTX_new(void);
void TS_RESP_CTX_free(TS_RESP_CTX *ctx);
=head1 DESCRIPTION
Creates a response context that can be used for generating responses.
TS_RESP_CTX_new_ex() allocates and initializes a TS_RESP_CTX structure with a
library context of I<libctx> and a property query of I<propq>.
The library context and property query can be used to select which providers
supply the fetched algorithms.
TS_RESP_CTX_new() is similar to TS_RESP_CTX_new_ex() but sets the library context
and property query to NULL. This results in the default (NULL) library context
being used for any operations requiring algorithm fetches.
TS_RESP_CTX_free() frees the B<TS_RESP_CTX> object I<ctx>.
+If the argument is NULL, nothing is done.
=head1 RETURN VALUES
If the allocation fails, TS_RESP_CTX_new_ex() and TS_RESP_CTX_new() return NULL,
otherwise it returns a pointer to the newly allocated structure.
=head1 HISTORY
The function TS_RESP_CTX_new_ex() was added in OpenSSL 3.0.
=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/man3/X509V3_get_d2i.pod b/crypto/openssl/doc/man3/X509V3_get_d2i.pod
index 4a2e81b0dbdf..88294ff710f2 100644
--- a/crypto/openssl/doc/man3/X509V3_get_d2i.pod
+++ b/crypto/openssl/doc/man3/X509V3_get_d2i.pod
@@ -1,246 +1,247 @@
=pod
=head1 NAME
X509V3_get_d2i, X509V3_add1_i2d, X509V3_EXT_d2i, X509V3_EXT_i2d,
X509_get_ext_d2i, X509_add1_ext_i2d,
X509_CRL_get_ext_d2i, X509_CRL_add1_ext_i2d,
X509_REVOKED_get_ext_d2i, X509_REVOKED_add1_ext_i2d,
X509_get0_extensions, X509_CRL_get0_extensions,
X509_REVOKED_get0_extensions - X509 extension decode and encode functions
=head1 SYNOPSIS
#include <openssl/x509v3.h>
void *X509V3_get_d2i(const STACK_OF(X509_EXTENSION) *x, int nid, int *crit,
int *idx);
int X509V3_add1_i2d(STACK_OF(X509_EXTENSION) **x, int nid, void *value,
int crit, unsigned long flags);
void *X509V3_EXT_d2i(X509_EXTENSION *ext);
X509_EXTENSION *X509V3_EXT_i2d(int ext_nid, int crit, void *ext_struc);
void *X509_get_ext_d2i(const X509 *x, int nid, int *crit, int *idx);
int X509_add1_ext_i2d(X509 *x, int nid, void *value, int crit,
unsigned long flags);
void *X509_CRL_get_ext_d2i(const X509_CRL *crl, int nid, int *crit, int *idx);
int X509_CRL_add1_ext_i2d(X509_CRL *crl, int nid, void *value, int crit,
unsigned long flags);
void *X509_REVOKED_get_ext_d2i(const X509_REVOKED *r, int nid, int *crit, int *idx);
int X509_REVOKED_add1_ext_i2d(X509_REVOKED *r, int nid, void *value, int crit,
unsigned long flags);
const STACK_OF(X509_EXTENSION) *X509_get0_extensions(const X509 *x);
const STACK_OF(X509_EXTENSION) *X509_CRL_get0_extensions(const X509_CRL *crl);
const STACK_OF(X509_EXTENSION) *X509_REVOKED_get0_extensions(const X509_REVOKED *r);
=head1 DESCRIPTION
X509V3_get_d2i() looks for an extension with OID I<nid> in the extensions
I<x> and, if found, decodes it. If I<idx> is NULL then only one
occurrence of an extension is permissible, otherwise the first extension after
index I<*idx> is returned and I<*idx> updated to the location of the extension.
If I<crit> is not NULL then I<*crit> is set to a status value: -2 if the
extension occurs multiple times (this is only returned if I<idx> is NULL),
-1 if the extension could not be found, 0 if the extension is found and is
not critical and 1 if critical. A pointer to an extension specific structure
or NULL is returned.
X509V3_add1_i2d() adds extension I<value> to STACK I<*x> (allocating a new
STACK if necessary) using OID I<nid> and criticality I<crit> according
to I<flags>.
X509V3_EXT_d2i() attempts to decode the ASN.1 data contained in extension
I<ext> and returns a pointer to an extension specific structure or NULL
if the extension could not be decoded (invalid syntax or not supported).
X509V3_EXT_i2d() encodes the extension specific structure I<ext_struc>
with OID I<ext_nid> and criticality I<crit>.
X509_get_ext_d2i() and X509_add1_ext_i2d() operate on the extensions of
certificate I<x>. They are otherwise identical to X509V3_get_d2i() and
X509V3_add1_i2d().
X509_CRL_get_ext_d2i() and X509_CRL_add1_ext_i2d() operate on the extensions
of CRL I<crl>. They are otherwise identical to X509V3_get_d2i() and
X509V3_add1_i2d().
X509_REVOKED_get_ext_d2i() and X509_REVOKED_add1_ext_i2d() operate on the
extensions of B<X509_REVOKED> structure I<r> (i.e for CRL entry extensions).
They are otherwise identical to X509V3_get_d2i() and X509V3_add1_i2d().
X509_get0_extensions(), X509_CRL_get0_extensions() and
X509_REVOKED_get0_extensions() return a STACK of all the extensions
of a certificate, a CRL or a CRL entry respectively.
=head1 NOTES
In almost all cases an extension can occur at most once and multiple
occurrences is an error. Therefore, the I<idx> parameter is usually NULL.
The I<flags> parameter may be one of the following values.
B<X509V3_ADD_DEFAULT> appends a new extension only if the extension does
not exist. An error is returned if the extension exists.
B<X509V3_ADD_APPEND> appends a new extension, ignoring whether the extension
exists.
B<X509V3_ADD_REPLACE> replaces an existing extension. If the extension does
not exist, appends a new extension.
B<X509V3_ADD_REPLACE_EXISTING> replaces an existing extension. If the
extension does not exist, returns an error.
B<X509V3_ADD_KEEP_EXISTING> appends a new extension only if the extension does
not exist. An error is B<not> returned if the extension exists.
B<X509V3_ADD_DELETE> deletes and frees an existing extension. If the extension
does not exist, returns an error. No new extension is added.
If B<X509V3_ADD_SILENT> is bitwise ORed with I<flags>: any error returned
will not be added to the error queue.
The function X509V3_get_d2i() and its variants
will return NULL if the extension is not
found, occurs multiple times or cannot be decoded. It is possible to
determine the precise reason by checking the value of I<*crit>.
+The returned pointer must be explicitly freed.
The function X509V3_add1_i2d() and its variants allocate B<X509_EXTENSION>
objects on STACK I<*x> depending on I<flags>. The B<X509_EXTENSION> objects
must be explicitly freed using X509_EXTENSION_free().
=head1 SUPPORTED EXTENSIONS
The following sections contain a list of all supported extensions
including their name and NID.
=head2 PKIX Certificate Extensions
The following certificate extensions are defined in PKIX standards such as
RFC5280.
Basic Constraints NID_basic_constraints
Key Usage NID_key_usage
Extended Key Usage NID_ext_key_usage
Subject Key Identifier NID_subject_key_identifier
Authority Key Identifier NID_authority_key_identifier
Private Key Usage Period NID_private_key_usage_period
Subject Alternative Name NID_subject_alt_name
Issuer Alternative Name NID_issuer_alt_name
Authority Information Access NID_info_access
Subject Information Access NID_sinfo_access
Name Constraints NID_name_constraints
Certificate Policies NID_certificate_policies
Policy Mappings NID_policy_mappings
Policy Constraints NID_policy_constraints
Inhibit Any Policy NID_inhibit_any_policy
TLS Feature NID_tlsfeature
=head2 Netscape Certificate Extensions
The following are (largely obsolete) Netscape certificate extensions.
Netscape Cert Type NID_netscape_cert_type
Netscape Base Url NID_netscape_base_url
Netscape Revocation Url NID_netscape_revocation_url
Netscape CA Revocation Url NID_netscape_ca_revocation_url
Netscape Renewal Url NID_netscape_renewal_url
Netscape CA Policy Url NID_netscape_ca_policy_url
Netscape SSL Server Name NID_netscape_ssl_server_name
Netscape Comment NID_netscape_comment
=head2 Miscellaneous Certificate Extensions
Strong Extranet ID NID_sxnet
Proxy Certificate Information NID_proxyCertInfo
=head2 PKIX CRL Extensions
The following are CRL extensions from PKIX standards such as RFC5280.
CRL Number NID_crl_number
CRL Distribution Points NID_crl_distribution_points
Delta CRL Indicator NID_delta_crl
Freshest CRL NID_freshest_crl
Invalidity Date NID_invalidity_date
Issuing Distribution Point NID_issuing_distribution_point
The following are CRL entry extensions from PKIX standards such as RFC5280.
CRL Reason Code NID_crl_reason
Certificate Issuer NID_certificate_issuer
=head2 OCSP Extensions
OCSP Nonce NID_id_pkix_OCSP_Nonce
OCSP CRL ID NID_id_pkix_OCSP_CrlID
Acceptable OCSP Responses NID_id_pkix_OCSP_acceptableResponses
OCSP No Check NID_id_pkix_OCSP_noCheck
OCSP Archive Cutoff NID_id_pkix_OCSP_archiveCutoff
OCSP Service Locator NID_id_pkix_OCSP_serviceLocator
Hold Instruction Code NID_hold_instruction_code
=head2 Certificate Transparency Extensions
The following extensions are used by certificate transparency, RFC6962
CT Precertificate SCTs NID_ct_precert_scts
CT Certificate SCTs NID_ct_cert_scts
=head1 RETURN VALUES
X509V3_get_d2i(), its variants, and X509V3_EXT_d2i() return
a pointer to an extension specific structure or NULL if an error occurs.
X509V3_add1_i2d() and its variants return 1 if the operation is successful
and 0 if it fails due to a non-fatal error (extension not found, already exists,
cannot be encoded) or -1 due to a fatal error such as a memory allocation
failure.
X509V3_EXT_i2d() returns a pointer to an B<X509_EXTENSION> structure
or NULL if an error occurs.
X509_get0_extensions(), X509_CRL_get0_extensions() and
X509_REVOKED_get0_extensions() return a stack of extensions. They return
NULL if no extensions are present.
=head1 SEE ALSO
L<d2i_X509(3)>,
L<ERR_get_error(3)>,
L<X509_CRL_get0_by_serial(3)>,
L<X509_get0_signature(3)>,
L<X509_get_ext_d2i(3)>,
L<X509_get_extension_flags(3)>,
L<X509_get_pubkey(3)>,
L<X509_get_subject_name(3)>,
L<X509_get_version(3)>,
L<X509_NAME_add_entry_by_txt(3)>,
L<X509_NAME_ENTRY_get_object(3)>,
L<X509_NAME_get_index_by_NID(3)>,
L<X509_NAME_print_ex(3)>,
L<X509_new(3)>,
L<X509_sign(3)>,
L<X509_verify_cert(3)>
=head1 COPYRIGHT
-Copyright 2015-2022 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
L<https://www.openssl.org/source/license.html>.
=cut
diff --git a/crypto/openssl/doc/man3/X509_LOOKUP.pod b/crypto/openssl/doc/man3/X509_LOOKUP.pod
index 4d2fe38f25ab..8f0240de2d13 100644
--- a/crypto/openssl/doc/man3/X509_LOOKUP.pod
+++ b/crypto/openssl/doc/man3/X509_LOOKUP.pod
@@ -1,238 +1,239 @@
=pod
=head1 NAME
X509_LOOKUP, X509_LOOKUP_TYPE,
X509_LOOKUP_new, X509_LOOKUP_free, X509_LOOKUP_init,
X509_LOOKUP_shutdown,
X509_LOOKUP_set_method_data, X509_LOOKUP_get_method_data,
X509_LOOKUP_ctrl_ex, X509_LOOKUP_ctrl,
X509_LOOKUP_load_file_ex, X509_LOOKUP_load_file,
X509_LOOKUP_add_dir,
X509_LOOKUP_add_store_ex, X509_LOOKUP_add_store,
X509_LOOKUP_load_store_ex, X509_LOOKUP_load_store,
X509_LOOKUP_get_store,
X509_LOOKUP_by_subject_ex, X509_LOOKUP_by_subject,
X509_LOOKUP_by_issuer_serial, X509_LOOKUP_by_fingerprint,
X509_LOOKUP_by_alias
- OpenSSL certificate lookup mechanisms
=head1 SYNOPSIS
#include <openssl/x509_vfy.h>
typedef x509_lookup_st X509_LOOKUP;
typedef enum X509_LOOKUP_TYPE;
X509_LOOKUP *X509_LOOKUP_new(X509_LOOKUP_METHOD *method);
int X509_LOOKUP_init(X509_LOOKUP *ctx);
int X509_LOOKUP_shutdown(X509_LOOKUP *ctx);
void X509_LOOKUP_free(X509_LOOKUP *ctx);
int X509_LOOKUP_set_method_data(X509_LOOKUP *ctx, void *data);
void *X509_LOOKUP_get_method_data(const X509_LOOKUP *ctx);
int X509_LOOKUP_ctrl_ex(X509_LOOKUP *ctx, int cmd, const char *argc, long argl,
char **ret, OSSL_LIB_CTX *libctx, const char *propq);
int X509_LOOKUP_ctrl(X509_LOOKUP *ctx, int cmd, const char *argc,
long argl, char **ret);
int X509_LOOKUP_load_file_ex(X509_LOOKUP *ctx, char *name, long type,
OSSL_LIB_CTX *libctx, const char *propq);
int X509_LOOKUP_load_file(X509_LOOKUP *ctx, char *name, long type);
int X509_LOOKUP_load_file_ex(X509_LOOKUP *ctx, char *name, long type,
OSSL_LIB_CTX *libctx, const char *propq);
int X509_LOOKUP_add_dir(X509_LOOKUP *ctx, char *name, long type);
int X509_LOOKUP_add_store_ex(X509_LOOKUP *ctx, char *uri, OSSL_LIB_CTX *libctx,
const char *propq);
int X509_LOOKUP_add_store(X509_LOOKUP *ctx, char *uri);
int X509_LOOKUP_load_store_ex(X509_LOOKUP *ctx, char *uri, OSSL_LIB_CTX *libctx,
const char *propq);
int X509_LOOKUP_load_store(X509_LOOKUP *ctx, char *uri);
X509_STORE *X509_LOOKUP_get_store(const X509_LOOKUP *ctx);
int X509_LOOKUP_by_subject_ex(X509_LOOKUP *ctx, X509_LOOKUP_TYPE type,
const X509_NAME *name, X509_OBJECT *ret,
OSSL_LIB_CTX *libctx, const char *propq);
int X509_LOOKUP_by_subject(X509_LOOKUP *ctx, X509_LOOKUP_TYPE type,
const X509_NAME *name, X509_OBJECT *ret);
int X509_LOOKUP_by_issuer_serial(X509_LOOKUP *ctx, X509_LOOKUP_TYPE type,
const X509_NAME *name,
const ASN1_INTEGER *serial, X509_OBJECT *ret);
int X509_LOOKUP_by_fingerprint(X509_LOOKUP *ctx, X509_LOOKUP_TYPE type,
const unsigned char *bytes, int len,
X509_OBJECT *ret);
int X509_LOOKUP_by_alias(X509_LOOKUP *ctx, X509_LOOKUP_TYPE type,
const char *str, int len, X509_OBJECT *ret);
=head1 DESCRIPTION
The B<X509_LOOKUP> structure holds the information needed to look up
certificates and CRLs according to an associated L<X509_LOOKUP_METHOD(3)>.
Multiple B<X509_LOOKUP> instances can be added to an L<X509_STORE(3)>
to enable lookup in that store.
X509_LOOKUP_new() creates a new B<X509_LOOKUP> using the given lookup
I<method>.
It can also be created by calling L<X509_STORE_add_lookup(3)>, which
will associate a B<X509_STORE> with the lookup mechanism.
X509_LOOKUP_init() initializes the internal state and resources as
needed by the given B<X509_LOOKUP> to do its work.
X509_LOOKUP_shutdown() tears down the internal state and resources of
the given B<X509_LOOKUP>.
X509_LOOKUP_free() destructs the given B<X509_LOOKUP>.
+If the argument is NULL, nothing is done.
X509_LOOKUP_set_method_data() and X509_LOOKUP_get_method_data()
associates and retrieves a pointer to application data to and from the
given B<X509_LOOKUP>, respectively.
X509_LOOKUP_ctrl_ex() is used to set or get additional data to or from
a B<X509_LOOKUP> structure or its associated L<X509_LOOKUP_METHOD(3)>.
The arguments of the control command are passed via I<argc> and I<argl>,
its return value via I<*ret>. The library context I<libctx> and property
query I<propq> are used when fetching algorithms from providers.
The meaning of the arguments depends on the I<cmd> number of the
control command. In general, this function is not called directly, but
wrapped by a macro call, see below.
The control I<cmd>s known to OpenSSL are discussed in more depth
in L</Control Commands>.
X509_LOOKUP_ctrl() is similar to X509_LOOKUP_ctrl_ex() but
uses NULL for the library context I<libctx> and property query I<propq>.
X509_LOOKUP_load_file_ex() passes a filename to be loaded immediately
into the associated B<X509_STORE>. The library context I<libctx> and property
query I<propq> are used when fetching algorithms from providers.
I<type> indicates what type of object is expected.
This can only be used with a lookup using the implementation
L<X509_LOOKUP_file(3)>.
X509_LOOKUP_load_file() is similar to X509_LOOKUP_load_file_ex() but
uses NULL for the library context I<libctx> and property query I<propq>.
X509_LOOKUP_add_dir() passes a directory specification from which
certificates and CRLs are loaded on demand into the associated
B<X509_STORE>.
I<type> indicates what type of object is expected.
This can only be used with a lookup using the implementation
L<X509_LOOKUP_hash_dir(3)>.
X509_LOOKUP_add_store_ex() passes a URI for a directory-like structure
from which containers with certificates and CRLs are loaded on demand
into the associated B<X509_STORE>. The library context I<libctx> and property
query I<propq> are used when fetching algorithms from providers.
X509_LOOKUP_add_store() is similar to X509_LOOKUP_add_store_ex() but
uses NULL for the library context I<libctx> and property query I<propq>.
X509_LOOKUP_load_store_ex() passes a URI for a single container from
which certificates and CRLs are immediately loaded into the associated
B<X509_STORE>. The library context I<libctx> and property query I<propq> are used
when fetching algorithms from providers.
These functions can only be used with a lookup using the
implementation L<X509_LOOKUP_store(3)>.
X509_LOOKUP_load_store() is similar to X509_LOOKUP_load_store_ex() but
uses NULL for the library context I<libctx> and property query I<propq>.
X509_LOOKUP_load_file_ex(), X509_LOOKUP_load_file(),
X509_LOOKUP_add_dir(),
X509_LOOKUP_add_store_ex() X509_LOOKUP_add_store(),
X509_LOOKUP_load_store_ex() and X509_LOOKUP_load_store() are
implemented as macros that use X509_LOOKUP_ctrl().
X509_LOOKUP_by_subject_ex(), X509_LOOKUP_by_subject(),
X509_LOOKUP_by_issuer_serial(), X509_LOOKUP_by_fingerprint(), and
X509_LOOKUP_by_alias() look up certificates and CRLs in the L<X509_STORE(3)>
associated with the B<X509_LOOKUP> using different criteria, where the looked up
object is stored in I<ret>.
Some of the underlying B<X509_LOOKUP_METHOD>s will also cache objects
matching the criteria in the associated B<X509_STORE>, which makes it
possible to handle cases where the criteria have more than one hit.
=head2 Control Commands
The B<X509_LOOKUP_METHOD>s built into OpenSSL recognize the following
X509_LOOKUP_ctrl() I<cmd>s:
=over 4
=item B<X509_L_FILE_LOAD>
This is the command that X509_LOOKUP_load_file_ex() and
X509_LOOKUP_load_file() use.
The filename is passed in I<argc>, and the type in I<argl>.
=item B<X509_L_ADD_DIR>
This is the command that X509_LOOKUP_add_dir() uses.
The directory specification is passed in I<argc>, and the type in
I<argl>.
=item B<X509_L_ADD_STORE>
This is the command that X509_LOOKUP_add_store_ex() and
X509_LOOKUP_add_store() use.
The URI is passed in I<argc>.
=item B<X509_L_LOAD_STORE>
This is the command that X509_LOOKUP_load_store_ex() and
X509_LOOKUP_load_store() use.
The URI is passed in I<argc>.
=back
=head1 RETURN VALUES
X509_LOOKUP_new() returns a B<X509_LOOKUP> pointer when successful,
or NULL on error.
X509_LOOKUP_init() and X509_LOOKUP_shutdown() return 1 on success, or
0 on error.
X509_LOOKUP_ctrl() returns -1 if the B<X509_LOOKUP> doesn't have an
associated B<X509_LOOKUP_METHOD>, or 1 if the X<509_LOOKUP_METHOD>
doesn't have a control function.
Otherwise, it returns what the control function in the
B<X509_LOOKUP_METHOD> returns, which is usually 1 on success and 0 in
error.
X509_LOOKUP_get_store() returns a B<X509_STORE> pointer if there is
one, otherwise NULL.
X509_LOOKUP_by_subject_ex(), X509_LOOKUP_by_subject(),
X509_LOOKUP_by_issuer_serial(), X509_LOOKUP_by_fingerprint(), and
X509_LOOKUP_by_alias() all return 0 if there is no B<X509_LOOKUP_METHOD> or that
method doesn't implement the corresponding function.
Otherwise, it returns what the corresponding function in the
B<X509_LOOKUP_METHOD> returns, which is usually 1 on success and 0 in
error.
=head1 SEE ALSO
L<X509_LOOKUP_METHOD(3)>, L<X509_STORE(3)>
=head1 HISTORY
The functions X509_LOOKUP_by_subject_ex() and
X509_LOOKUP_ctrl_ex() were added in OpenSSL 3.0.
The macros X509_LOOKUP_load_file_ex(),
X509_LOOKUP_load_store_ex() and 509_LOOKUP_add_store_ex() 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/X509_LOOKUP_meth_new.pod b/crypto/openssl/doc/man3/X509_LOOKUP_meth_new.pod
index 202174993563..ef2c3cdd500a 100644
--- a/crypto/openssl/doc/man3/X509_LOOKUP_meth_new.pod
+++ b/crypto/openssl/doc/man3/X509_LOOKUP_meth_new.pod
@@ -1,196 +1,197 @@
=pod
=head1 NAME
X509_LOOKUP_METHOD,
X509_LOOKUP_meth_new, X509_LOOKUP_meth_free, X509_LOOKUP_meth_set_new_item,
X509_LOOKUP_meth_get_new_item, X509_LOOKUP_meth_set_free,
X509_LOOKUP_meth_get_free, X509_LOOKUP_meth_set_init,
X509_LOOKUP_meth_get_init, X509_LOOKUP_meth_set_shutdown,
X509_LOOKUP_meth_get_shutdown,
X509_LOOKUP_ctrl_fn, X509_LOOKUP_meth_set_ctrl, X509_LOOKUP_meth_get_ctrl,
X509_LOOKUP_get_by_subject_fn, X509_LOOKUP_meth_set_get_by_subject,
X509_LOOKUP_meth_get_get_by_subject,
X509_LOOKUP_get_by_issuer_serial_fn, X509_LOOKUP_meth_set_get_by_issuer_serial,
X509_LOOKUP_meth_get_get_by_issuer_serial,
X509_LOOKUP_get_by_fingerprint_fn, X509_LOOKUP_meth_set_get_by_fingerprint,
X509_LOOKUP_meth_get_get_by_fingerprint,
X509_LOOKUP_get_by_alias_fn, X509_LOOKUP_meth_set_get_by_alias,
X509_LOOKUP_meth_get_get_by_alias,
X509_OBJECT_set1_X509, X509_OBJECT_set1_X509_CRL
- Routines to build up X509_LOOKUP methods
=head1 SYNOPSIS
#include <openssl/x509_vfy.h>
typedef x509_lookup_method_st X509_LOOKUP_METHOD;
X509_LOOKUP_METHOD *X509_LOOKUP_meth_new(const char *name);
void X509_LOOKUP_meth_free(X509_LOOKUP_METHOD *method);
int X509_LOOKUP_meth_set_new_item(X509_LOOKUP_METHOD *method,
int (*new_item) (X509_LOOKUP *ctx));
int (*X509_LOOKUP_meth_get_new_item(const X509_LOOKUP_METHOD* method))
(X509_LOOKUP *ctx);
int X509_LOOKUP_meth_set_free(X509_LOOKUP_METHOD *method,
void (*free) (X509_LOOKUP *ctx));
void (*X509_LOOKUP_meth_get_free(const X509_LOOKUP_METHOD* method))
(X509_LOOKUP *ctx);
int X509_LOOKUP_meth_set_init(X509_LOOKUP_METHOD *method,
int (*init) (X509_LOOKUP *ctx));
int (*X509_LOOKUP_meth_get_init(const X509_LOOKUP_METHOD* method))
(X509_LOOKUP *ctx);
int X509_LOOKUP_meth_set_shutdown(X509_LOOKUP_METHOD *method,
int (*shutdown) (X509_LOOKUP *ctx));
int (*X509_LOOKUP_meth_get_shutdown(const X509_LOOKUP_METHOD* method))
(X509_LOOKUP *ctx);
typedef int (*X509_LOOKUP_ctrl_fn)(X509_LOOKUP *ctx, int cmd, const char *argc,
long argl, char **ret);
int X509_LOOKUP_meth_set_ctrl(X509_LOOKUP_METHOD *method,
X509_LOOKUP_ctrl_fn ctrl_fn);
X509_LOOKUP_ctrl_fn X509_LOOKUP_meth_get_ctrl(const X509_LOOKUP_METHOD *method);
typedef int (*X509_LOOKUP_get_by_subject_fn)(X509_LOOKUP *ctx,
X509_LOOKUP_TYPE type,
const X509_NAME *name,
X509_OBJECT *ret);
int X509_LOOKUP_meth_set_get_by_subject(X509_LOOKUP_METHOD *method,
X509_LOOKUP_get_by_subject_fn fn);
X509_LOOKUP_get_by_subject_fn X509_LOOKUP_meth_get_get_by_subject(
const X509_LOOKUP_METHOD *method);
typedef int (*X509_LOOKUP_get_by_issuer_serial_fn)(X509_LOOKUP *ctx,
X509_LOOKUP_TYPE type,
const X509_NAME *name,
const ASN1_INTEGER *serial,
X509_OBJECT *ret);
int X509_LOOKUP_meth_set_get_by_issuer_serial(
X509_LOOKUP_METHOD *method, X509_LOOKUP_get_by_issuer_serial_fn fn);
X509_LOOKUP_get_by_issuer_serial_fn X509_LOOKUP_meth_get_get_by_issuer_serial(
const X509_LOOKUP_METHOD *method);
typedef int (*X509_LOOKUP_get_by_fingerprint_fn)(X509_LOOKUP *ctx,
X509_LOOKUP_TYPE type,
const unsigned char* bytes,
int len,
X509_OBJECT *ret);
int X509_LOOKUP_meth_set_get_by_fingerprint(X509_LOOKUP_METHOD *method,
X509_LOOKUP_get_by_fingerprint_fn fn);
X509_LOOKUP_get_by_fingerprint_fn X509_LOOKUP_meth_get_get_by_fingerprint(
const X509_LOOKUP_METHOD *method);
typedef int (*X509_LOOKUP_get_by_alias_fn)(X509_LOOKUP *ctx,
X509_LOOKUP_TYPE type,
const char *str,
int len,
X509_OBJECT *ret);
int X509_LOOKUP_meth_set_get_by_alias(X509_LOOKUP_METHOD *method,
X509_LOOKUP_get_by_alias_fn fn);
X509_LOOKUP_get_by_alias_fn X509_LOOKUP_meth_get_get_by_alias(
const X509_LOOKUP_METHOD *method);
int X509_OBJECT_set1_X509(X509_OBJECT *a, X509 *obj);
int X509_OBJECT_set1_X509_CRL(X509_OBJECT *a, X509_CRL *obj);
=head1 DESCRIPTION
The B<X509_LOOKUP_METHOD> type is a structure used for the implementation of new
X509_LOOKUP types. It provides a set of functions used by OpenSSL for the
implementation of various X509 and X509_CRL lookup capabilities. One instance
of an X509_LOOKUP_METHOD can be associated to many instantiations of an
B<X509_LOOKUP> structure.
X509_LOOKUP_meth_new() creates a new B<X509_LOOKUP_METHOD> structure. It should
be given a human-readable string containing a brief description of the lookup
method.
X509_LOOKUP_meth_free() destroys a B<X509_LOOKUP_METHOD> structure.
+If the argument is NULL, nothing is done.
X509_LOOKUP_get_new_item() and X509_LOOKUP_set_new_item() get and set the
function that is called when an B<X509_LOOKUP> object is created with
X509_LOOKUP_new(). If an X509_LOOKUP_METHOD requires any per-X509_LOOKUP
specific data, the supplied new_item function should allocate this data and
invoke L<X509_LOOKUP_set_method_data(3)>.
X509_LOOKUP_get_free() and X509_LOOKUP_set_free() get and set the function
that is used to free any method data that was allocated and set from within
new_item function.
X509_LOOKUP_meth_get_init() and X509_LOOKUP_meth_set_init() get and set the
function that is used to initialize the method data that was set with
L<X509_LOOKUP_set_method_data(3)> as part of the new_item routine.
X509_LOOKUP_meth_get_shutdown() and X509_LOOKUP_meth_set_shutdown() get and set
the function that is used to shut down the method data whose state was
previously initialized in the init function.
X509_LOOKUP_meth_get_ctrl() and X509_LOOKUP_meth_set_ctrl() get and set a
function to be used to handle arbitrary control commands issued by
X509_LOOKUP_ctrl(). The control function is given the X509_LOOKUP
B<ctx>, along with the arguments passed by X509_LOOKUP_ctrl. B<cmd> is
an arbitrary integer that defines some operation. B<argc> is a pointer
to an array of characters. B<argl> is an integer. B<ret>, if set,
points to a location where any return data should be written to. How
B<argc> and B<argl> are used depends entirely on the control function.
X509_LOOKUP_set_get_by_subject(), X509_LOOKUP_set_get_by_issuer_serial(),
X509_LOOKUP_set_get_by_fingerprint(), X509_LOOKUP_set_get_by_alias() set
the functions used to retrieve an X509 or X509_CRL object by the object's
subject, issuer, fingerprint, and alias respectively. These functions are given
the X509_LOOKUP context, the type of the X509_OBJECT being requested, parameters
related to the lookup, and an X509_OBJECT that will receive the requested
object.
Implementations must add objects they find to the B<X509_STORE> object
using X509_STORE_add_cert() or X509_STORE_add_crl(). This increments
its reference count. However, the X509_STORE_CTX_get_by_subject()
function also increases the reference count which leads to one too
many references being held. Therefore, applications should
additionally call X509_free() or X509_CRL_free() to decrement the
reference count again.
Implementations should also use either X509_OBJECT_set1_X509() or
X509_OBJECT_set1_X509_CRL() to set the result. Note that this also
increments the result's reference count.
Any method data that was created as a result of the new_item function
set by X509_LOOKUP_meth_set_new_item() can be accessed with
L<X509_LOOKUP_get_method_data(3)>. The B<X509_STORE> object that owns the
X509_LOOKUP may be accessed with L<X509_LOOKUP_get_store(3)>. Successful
lookups should return 1, and unsuccessful lookups should return 0.
X509_LOOKUP_get_get_by_subject(), X509_LOOKUP_get_get_by_issuer_serial(),
X509_LOOKUP_get_get_by_fingerprint(), X509_LOOKUP_get_get_by_alias() retrieve
the function set by the corresponding setter.
=head1 RETURN VALUES
The B<X509_LOOKUP_meth_set> functions return 1 on success or 0 on error.
The B<X509_LOOKUP_meth_get> functions return the corresponding function
pointers.
=head1 SEE ALSO
L<X509_STORE_new(3)>, L<SSL_CTX_set_cert_store(3)>
=head1 HISTORY
The functions described here were added in OpenSSL 1.1.0i.
=head1 COPYRIGHT
-Copyright 2018-2020 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/man3/X509_STORE_new.pod b/crypto/openssl/doc/man3/X509_STORE_new.pod
index 31d466faa42a..5b3dadb243d7 100644
--- a/crypto/openssl/doc/man3/X509_STORE_new.pod
+++ b/crypto/openssl/doc/man3/X509_STORE_new.pod
@@ -1,59 +1,60 @@
=pod
=head1 NAME
X509_STORE_new, X509_STORE_up_ref, X509_STORE_free,
X509_STORE_lock,X509_STORE_unlock
- X509_STORE allocation, freeing and locking functions
=head1 SYNOPSIS
#include <openssl/x509_vfy.h>
X509_STORE *X509_STORE_new(void);
void X509_STORE_free(X509_STORE *v);
int X509_STORE_lock(X509_STORE *v);
int X509_STORE_unlock(X509_STORE *v);
int X509_STORE_up_ref(X509_STORE *v);
=head1 DESCRIPTION
The X509_STORE_new() function returns a new X509_STORE.
X509_STORE_up_ref() increments the reference count associated with the
X509_STORE object.
X509_STORE_lock() locks the store from modification by other threads,
X509_STORE_unlock() unlocks it.
X509_STORE_free() frees up a single X509_STORE object.
+If the argument is NULL, nothing is done.
=head1 RETURN VALUES
X509_STORE_new() returns a newly created X509_STORE or NULL if the call fails.
X509_STORE_up_ref(), X509_STORE_lock() and X509_STORE_unlock() return
1 for success and 0 for failure.
X509_STORE_free() does not return values.
=head1 SEE ALSO
L<X509_STORE_set_verify_cb_func(3)>
L<X509_STORE_get0_param(3)>
=head1 HISTORY
The X509_STORE_up_ref(), X509_STORE_lock() and X509_STORE_unlock()
functions were added in OpenSSL 1.1.0.
=head1 COPYRIGHT
-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 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/X509_dup.pod b/crypto/openssl/doc/man3/X509_dup.pod
index 849364e2aae7..c8dd79ff71b7 100644
--- a/crypto/openssl/doc/man3/X509_dup.pod
+++ b/crypto/openssl/doc/man3/X509_dup.pod
@@ -1,406 +1,406 @@
=pod
=head1 NAME
DECLARE_ASN1_FUNCTIONS,
IMPLEMENT_ASN1_FUNCTIONS,
ASN1_ITEM,
ACCESS_DESCRIPTION_free,
ACCESS_DESCRIPTION_new,
ADMISSIONS_free,
ADMISSIONS_new,
ADMISSION_SYNTAX_free,
ADMISSION_SYNTAX_new,
ASIdOrRange_free,
ASIdOrRange_new,
ASIdentifierChoice_free,
ASIdentifierChoice_new,
ASIdentifiers_free,
ASIdentifiers_new,
ASRange_free,
ASRange_new,
AUTHORITY_INFO_ACCESS_free,
AUTHORITY_INFO_ACCESS_new,
AUTHORITY_KEYID_free,
AUTHORITY_KEYID_new,
BASIC_CONSTRAINTS_free,
BASIC_CONSTRAINTS_new,
CERTIFICATEPOLICIES_free,
CERTIFICATEPOLICIES_new,
CMS_ContentInfo_free,
CMS_ContentInfo_new,
CMS_ContentInfo_new_ex,
CMS_ContentInfo_print_ctx,
CMS_ReceiptRequest_free,
CMS_ReceiptRequest_new,
CRL_DIST_POINTS_free,
CRL_DIST_POINTS_new,
DIRECTORYSTRING_free,
DIRECTORYSTRING_new,
DISPLAYTEXT_free,
DISPLAYTEXT_new,
DIST_POINT_NAME_free,
DIST_POINT_NAME_new,
DIST_POINT_free,
DIST_POINT_new,
DSAparams_dup,
ECPARAMETERS_free,
ECPARAMETERS_new,
ECPKPARAMETERS_free,
ECPKPARAMETERS_new,
EDIPARTYNAME_free,
EDIPARTYNAME_new,
ESS_CERT_ID_dup,
ESS_CERT_ID_free,
ESS_CERT_ID_new,
ESS_CERT_ID_V2_dup,
ESS_CERT_ID_V2_free,
ESS_CERT_ID_V2_new,
ESS_ISSUER_SERIAL_dup,
ESS_ISSUER_SERIAL_free,
ESS_ISSUER_SERIAL_new,
ESS_SIGNING_CERT_dup,
ESS_SIGNING_CERT_free,
ESS_SIGNING_CERT_it,
ESS_SIGNING_CERT_new,
ESS_SIGNING_CERT_V2_dup,
ESS_SIGNING_CERT_V2_free,
ESS_SIGNING_CERT_V2_it,
ESS_SIGNING_CERT_V2_new,
EXTENDED_KEY_USAGE_free,
EXTENDED_KEY_USAGE_new,
GENERAL_NAMES_free,
GENERAL_NAMES_new,
GENERAL_NAME_dup,
GENERAL_NAME_free,
GENERAL_NAME_new,
GENERAL_SUBTREE_free,
GENERAL_SUBTREE_new,
IPAddressChoice_free,
IPAddressChoice_new,
IPAddressFamily_free,
IPAddressFamily_new,
IPAddressOrRange_free,
IPAddressOrRange_new,
IPAddressRange_free,
IPAddressRange_new,
ISSUER_SIGN_TOOL_free,
ISSUER_SIGN_TOOL_it,
ISSUER_SIGN_TOOL_new,
ISSUING_DIST_POINT_free,
ISSUING_DIST_POINT_it,
ISSUING_DIST_POINT_new,
NAME_CONSTRAINTS_free,
NAME_CONSTRAINTS_new,
NAMING_AUTHORITY_free,
NAMING_AUTHORITY_new,
NETSCAPE_CERT_SEQUENCE_free,
NETSCAPE_CERT_SEQUENCE_new,
NETSCAPE_SPKAC_free,
NETSCAPE_SPKAC_new,
NETSCAPE_SPKI_free,
NETSCAPE_SPKI_new,
NOTICEREF_free,
NOTICEREF_new,
OCSP_BASICRESP_free,
OCSP_BASICRESP_new,
OCSP_CERTID_dup,
OCSP_CERTID_new,
OCSP_CERTSTATUS_free,
OCSP_CERTSTATUS_new,
OCSP_CRLID_free,
OCSP_CRLID_new,
OCSP_ONEREQ_free,
OCSP_ONEREQ_new,
OCSP_REQINFO_free,
OCSP_REQINFO_new,
OCSP_RESPBYTES_free,
OCSP_RESPBYTES_new,
OCSP_RESPDATA_free,
OCSP_RESPDATA_new,
OCSP_RESPID_free,
OCSP_RESPID_new,
OCSP_RESPONSE_new,
OCSP_REVOKEDINFO_free,
OCSP_REVOKEDINFO_new,
OCSP_SERVICELOC_free,
OCSP_SERVICELOC_new,
OCSP_SIGNATURE_free,
OCSP_SIGNATURE_new,
OCSP_SINGLERESP_free,
OCSP_SINGLERESP_new,
OSSL_CMP_ITAV_dup,
OSSL_CMP_ITAV_free,
OSSL_CMP_MSG_dup,
OSSL_CMP_MSG_it,
OSSL_CMP_MSG_free,
OSSL_CMP_PKIHEADER_free,
OSSL_CMP_PKIHEADER_it,
OSSL_CMP_PKIHEADER_new,
OSSL_CMP_PKISI_dup,
OSSL_CMP_PKISI_free,
OSSL_CMP_PKISI_it,
OSSL_CMP_PKISI_new,
OSSL_CMP_PKISTATUS_it,
OSSL_CRMF_CERTID_dup,
OSSL_CRMF_CERTID_free,
OSSL_CRMF_CERTID_it,
OSSL_CRMF_CERTID_new,
OSSL_CRMF_CERTTEMPLATE_free,
OSSL_CRMF_CERTTEMPLATE_it,
OSSL_CRMF_CERTTEMPLATE_new,
OSSL_CRMF_ENCRYPTEDVALUE_free,
OSSL_CRMF_ENCRYPTEDVALUE_it,
OSSL_CRMF_ENCRYPTEDVALUE_new,
OSSL_CRMF_MSGS_free,
OSSL_CRMF_MSGS_it,
OSSL_CRMF_MSGS_new,
OSSL_CRMF_MSG_dup,
OSSL_CRMF_MSG_free,
OSSL_CRMF_MSG_it,
OSSL_CRMF_MSG_new,
OSSL_CRMF_PBMPARAMETER_free,
OSSL_CRMF_PBMPARAMETER_it,
OSSL_CRMF_PBMPARAMETER_new,
OSSL_CRMF_PKIPUBLICATIONINFO_free,
OSSL_CRMF_PKIPUBLICATIONINFO_it,
OSSL_CRMF_PKIPUBLICATIONINFO_new,
OSSL_CRMF_SINGLEPUBINFO_free,
OSSL_CRMF_SINGLEPUBINFO_it,
OSSL_CRMF_SINGLEPUBINFO_new,
OTHERNAME_free,
OTHERNAME_new,
PBE2PARAM_free,
PBE2PARAM_new,
PBEPARAM_free,
PBEPARAM_new,
PBKDF2PARAM_free,
PBKDF2PARAM_new,
PKCS12_BAGS_free,
PKCS12_BAGS_new,
PKCS12_MAC_DATA_free,
PKCS12_MAC_DATA_new,
PKCS12_SAFEBAG_free,
PKCS12_SAFEBAG_new,
PKCS12_free,
PKCS12_new,
PKCS7_DIGEST_free,
PKCS7_DIGEST_new,
PKCS7_ENCRYPT_free,
PKCS7_ENCRYPT_new,
PKCS7_ENC_CONTENT_free,
PKCS7_ENC_CONTENT_new,
PKCS7_ENVELOPE_free,
PKCS7_ENVELOPE_new,
PKCS7_ISSUER_AND_SERIAL_free,
PKCS7_ISSUER_AND_SERIAL_new,
PKCS7_RECIP_INFO_free,
PKCS7_RECIP_INFO_new,
PKCS7_SIGNED_free,
PKCS7_SIGNED_new,
PKCS7_SIGNER_INFO_free,
PKCS7_SIGNER_INFO_new,
PKCS7_SIGN_ENVELOPE_free,
PKCS7_SIGN_ENVELOPE_new,
PKCS7_dup,
PKCS7_free,
PKCS7_new_ex,
PKCS7_new,
PKCS7_print_ctx,
PKCS8_PRIV_KEY_INFO_free,
PKCS8_PRIV_KEY_INFO_new,
PKEY_USAGE_PERIOD_free,
PKEY_USAGE_PERIOD_new,
POLICYINFO_free,
POLICYINFO_new,
POLICYQUALINFO_free,
POLICYQUALINFO_new,
POLICY_CONSTRAINTS_free,
POLICY_CONSTRAINTS_new,
POLICY_MAPPING_free,
POLICY_MAPPING_new,
PROFESSION_INFOS_free,
PROFESSION_INFOS_new,
PROFESSION_INFO_free,
PROFESSION_INFO_new,
PROXY_CERT_INFO_EXTENSION_free,
PROXY_CERT_INFO_EXTENSION_new,
PROXY_POLICY_free,
PROXY_POLICY_new,
RSAPrivateKey_dup,
RSAPublicKey_dup,
RSA_OAEP_PARAMS_free,
RSA_OAEP_PARAMS_new,
RSA_PSS_PARAMS_free,
RSA_PSS_PARAMS_new,
RSA_PSS_PARAMS_dup,
SCRYPT_PARAMS_free,
SCRYPT_PARAMS_new,
SXNETID_free,
SXNETID_new,
SXNET_free,
SXNET_new,
TLS_FEATURE_free,
TLS_FEATURE_new,
TS_ACCURACY_dup,
TS_ACCURACY_free,
TS_ACCURACY_new,
TS_MSG_IMPRINT_dup,
TS_MSG_IMPRINT_free,
TS_MSG_IMPRINT_new,
TS_REQ_dup,
TS_REQ_free,
TS_REQ_new,
TS_RESP_dup,
TS_RESP_free,
TS_RESP_new,
TS_STATUS_INFO_dup,
TS_STATUS_INFO_free,
TS_STATUS_INFO_new,
TS_TST_INFO_dup,
TS_TST_INFO_free,
TS_TST_INFO_new,
USERNOTICE_free,
USERNOTICE_new,
X509_ALGOR_free,
X509_ALGOR_it,
X509_ALGOR_new,
X509_ATTRIBUTE_dup,
X509_ATTRIBUTE_free,
X509_ATTRIBUTE_new,
X509_CERT_AUX_free,
X509_CERT_AUX_new,
X509_CINF_free,
X509_CINF_new,
X509_CRL_INFO_free,
X509_CRL_INFO_new,
X509_CRL_dup,
X509_CRL_free,
X509_CRL_new_ex,
X509_CRL_new,
X509_EXTENSION_dup,
X509_EXTENSION_free,
X509_EXTENSION_new,
X509_NAME_ENTRY_dup,
X509_NAME_ENTRY_free,
X509_NAME_ENTRY_new,
X509_NAME_dup,
X509_NAME_free,
X509_NAME_new,
X509_REQ_INFO_free,
X509_REQ_INFO_new,
X509_REQ_dup,
X509_REQ_free,
X509_REQ_new,
X509_REQ_new_ex,
X509_REVOKED_dup,
X509_REVOKED_free,
X509_REVOKED_new,
X509_SIG_free,
X509_SIG_new,
X509_VAL_free,
X509_VAL_new,
X509_dup,
- ASN1 object utilities
=head1 SYNOPSIS
=for openssl generic
#include <openssl/asn1t.h>
DECLARE_ASN1_FUNCTIONS(type)
IMPLEMENT_ASN1_FUNCTIONS(stname)
typedef struct ASN1_ITEM_st ASN1_ITEM;
extern const ASN1_ITEM TYPE_it;
TYPE *TYPE_new(void);
TYPE *TYPE_dup(const TYPE *a);
void TYPE_free(TYPE *a);
int TYPE_print_ctx(BIO *out, TYPE *a, int indent, const ASN1_PCTX *pctx);
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)>:
DSA *DSAparams_dup(const DSA *dsa);
RSA *RSAPrivateKey_dup(const RSA *rsa);
RSA *RSAPublicKey_dup(const RSA *rsa);
=head1 DESCRIPTION
In the description below, B<I<TYPE>> is used
as a placeholder for any of the OpenSSL datatypes, such as B<X509>.
The OpenSSL ASN1 parsing library templates are like a data-driven bytecode
interpreter.
Every ASN1 object as a global variable, TYPE_it, that describes the item
such as its fields. (On systems which cannot export variables from shared
libraries, the global is instead a function which returns a pointer to a
static variable.
The macro DECLARE_ASN1_FUNCTIONS() is typically used in header files
to generate the function declarations.
The macro IMPLEMENT_ASN1_FUNCTIONS() is used once in a source file
to generate the function bodies.
B<I<TYPE>_new>() allocates an empty object of the indicated type.
The object returned must be released by calling B<I<TYPE>_free>().
B<I<TYPE>_new_ex>() is similar to B<I<TYPE>_new>() but also passes the
library context I<libctx> and the property query I<propq> to use when retrieving
algorithms from providers. This created object can then be used when loading
binary data using B<d2i_I<TYPE>>().
B<I<TYPE>_dup>() copies an existing object, leaving it untouched.
Note, however, that the internal representation of the object
may contain (besides the ASN.1 structure) further data, which is not copied.
For instance, an B<X509> object usually is augmented by cached information
on X.509v3 extensions, etc., and losing it can lead to wrong validation results.
To avoid such situations, better use B<I<TYPE>_up_ref>() if available.
For the case of B<X509> objects, an alternative to using L<X509_up_ref(3)>
may be to still call B<I<TYPE>_dup>(), e.g., I<copied_cert = X509_dup(cert)>,
followed by I<X509_check_purpose(copied_cert, -1, 0)>,
which re-builds the cached data.
B<I<TYPE>_free>() releases the object and all pointers and sub-objects
-within it.
+within it. If the argument is NULL, nothing is done.
B<I<TYPE>_print_ctx>() prints the object I<a> on the specified BIO I<out>.
Each line will be prefixed with I<indent> spaces.
The I<pctx> specifies the printing context and is for internal
use; use NULL to get the default behavior. If a print function is
user-defined, then pass in any I<pctx> down to any nested calls.
=head1 RETURN VALUES
B<I<TYPE>_new>(), B<I<TYPE>_new_ex>() and B<I<TYPE>_dup>() return a pointer to
the object or NULL on failure.
B<I<TYPE>_print_ctx>() returns 1 on success or zero on failure.
=head1 SEE ALSO
L<X509_up_ref(3)>
=head1 HISTORY
The functions X509_REQ_new_ex(), X509_CRL_new_ex(), PKCS7_new_ex() and
CMS_ContentInfo_new_ex() were added in OpenSSL 3.0.
The functions DSAparams_dup(), RSAPrivateKey_dup() and RSAPublicKey_dup() were
deprecated in 3.0.
=head1 COPYRIGHT
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/man3/X509_new.pod b/crypto/openssl/doc/man3/X509_new.pod
index ea2b3a2cc9b0..4b52972554de 100644
--- a/crypto/openssl/doc/man3/X509_new.pod
+++ b/crypto/openssl/doc/man3/X509_new.pod
@@ -1,96 +1,97 @@
=pod
=head1 NAME
X509_new, X509_new_ex,
X509_free, X509_up_ref,
X509_chain_up_ref - X509 certificate ASN1 allocation functions
=head1 SYNOPSIS
#include <openssl/x509.h>
X509 *X509_new(void);
X509 *X509_new_ex(OSSL_LIB_CTX *libctx, const char *propq);
void X509_free(X509 *a);
int X509_up_ref(X509 *a);
STACK_OF(X509) *X509_chain_up_ref(STACK_OF(X509) *x);
=head1 DESCRIPTION
-The X509 ASN1 allocation routines, allocate and free an
+The X509 ASN1 allocation routines allocate and free an
X509 structure, which represents an X509 certificate.
X509_new_ex() allocates and initializes a X509 structure with a
library context of I<libctx>, property query of I<propq> and a reference
count of B<1>. Many X509 functions such as X509_check_purpose(), and
X509_verify() use this library context to select which providers supply the
fetched algorithms (SHA1 is used internally). This created X509 object can then
be used when loading binary data using d2i_X509().
X509_new() is similar to X509_new_ex() but sets the library context
and property query to NULL. This results in the default (NULL) library context
being used for any X509 operations requiring algorithm fetches.
X509_free() decrements the reference count of B<X509> structure B<a> and
-frees it up if the reference count is zero. If B<a> is NULL nothing is done.
+frees it up if the reference count is zero. If the argument is NULL,
+nothing is done.
X509_up_ref() increments the reference count of B<a>.
X509_chain_up_ref() increases the reference count of all certificates in
chain B<x> and returns a copy of the stack, or an empty stack if B<a> is NULL.
=head1 NOTES
The function X509_up_ref() if useful if a certificate structure is being
used by several different operations each of which will free it up after
use: this avoids the need to duplicate the entire certificate structure.
The function X509_chain_up_ref() doesn't just up the reference count of
each certificate. It also returns a copy of the stack, using sk_X509_dup(),
but it serves a similar purpose: the returned chain persists after the
original has been freed.
=head1 RETURN VALUES
If the allocation fails, X509_new() returns NULL and sets an error
code that can be obtained by L<ERR_get_error(3)>.
Otherwise it returns a pointer to the newly allocated structure.
X509_up_ref() returns 1 for success and 0 for failure.
X509_chain_up_ref() returns a copy of the stack or NULL if an error occurred.
=head1 SEE ALSO
L<d2i_X509(3)>,
L<ERR_get_error(3)>,
L<X509_CRL_get0_by_serial(3)>,
L<X509_get0_signature(3)>,
L<X509_get_ext_d2i(3)>,
L<X509_get_extension_flags(3)>,
L<X509_get_pubkey(3)>,
L<X509_get_subject_name(3)>,
L<X509_get_version(3)>,
L<X509_NAME_add_entry_by_txt(3)>,
L<X509_NAME_ENTRY_get_object(3)>,
L<X509_NAME_get_index_by_NID(3)>,
L<X509_NAME_print_ex(3)>,
L<X509_sign(3)>,
L<X509V3_get_d2i(3)>,
L<X509_verify_cert(3)>
=head1 HISTORY
The function X509_new_ex() was added in OpenSSL 3.0.
=head1 COPYRIGHT
-Copyright 2002-2021 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
L<https://www.openssl.org/source/license.html>.
=cut
diff --git a/crypto/openssl/doc/man3/d2i_X509.pod b/crypto/openssl/doc/man3/d2i_X509.pod
index 00efb6035816..c4b589dd8957 100644
--- a/crypto/openssl/doc/man3/d2i_X509.pod
+++ b/crypto/openssl/doc/man3/d2i_X509.pod
@@ -1,625 +1,627 @@
=pod
=begin comment
Any keypair function here that gets deprecated should be moved to
d2i_RSAPrivateKey.pod.
=end comment
=head1 NAME
d2i_ACCESS_DESCRIPTION,
d2i_ADMISSIONS,
d2i_ADMISSION_SYNTAX,
d2i_ASIdOrRange,
d2i_ASIdentifierChoice,
d2i_ASIdentifiers,
d2i_ASN1_BIT_STRING,
d2i_ASN1_BMPSTRING,
d2i_ASN1_ENUMERATED,
d2i_ASN1_GENERALIZEDTIME,
d2i_ASN1_GENERALSTRING,
d2i_ASN1_IA5STRING,
d2i_ASN1_INTEGER,
d2i_ASN1_NULL,
d2i_ASN1_OBJECT,
d2i_ASN1_OCTET_STRING,
d2i_ASN1_PRINTABLE,
d2i_ASN1_PRINTABLESTRING,
d2i_ASN1_SEQUENCE_ANY,
d2i_ASN1_SET_ANY,
d2i_ASN1_T61STRING,
d2i_ASN1_TIME,
d2i_ASN1_TYPE,
d2i_ASN1_UINTEGER,
d2i_ASN1_UNIVERSALSTRING,
d2i_ASN1_UTCTIME,
d2i_ASN1_UTF8STRING,
d2i_ASN1_VISIBLESTRING,
d2i_ASRange,
d2i_AUTHORITY_INFO_ACCESS,
d2i_AUTHORITY_KEYID,
d2i_BASIC_CONSTRAINTS,
d2i_CERTIFICATEPOLICIES,
d2i_CMS_ContentInfo,
d2i_CMS_ReceiptRequest,
d2i_CMS_bio,
d2i_CRL_DIST_POINTS,
d2i_DHxparams,
d2i_DIRECTORYSTRING,
d2i_DISPLAYTEXT,
d2i_DIST_POINT,
d2i_DIST_POINT_NAME,
d2i_DSA_SIG,
d2i_ECDSA_SIG,
d2i_ECPKParameters,
d2i_EDIPARTYNAME,
d2i_ESS_CERT_ID,
d2i_ESS_CERT_ID_V2,
d2i_ESS_ISSUER_SERIAL,
d2i_ESS_SIGNING_CERT,
d2i_ESS_SIGNING_CERT_V2,
d2i_EXTENDED_KEY_USAGE,
d2i_GENERAL_NAME,
d2i_GENERAL_NAMES,
d2i_IPAddressChoice,
d2i_IPAddressFamily,
d2i_IPAddressOrRange,
d2i_IPAddressRange,
d2i_ISSUER_SIGN_TOOL,
d2i_ISSUING_DIST_POINT,
d2i_NAMING_AUTHORITY,
d2i_NETSCAPE_CERT_SEQUENCE,
d2i_NETSCAPE_SPKAC,
d2i_NETSCAPE_SPKI,
d2i_NOTICEREF,
d2i_OCSP_BASICRESP,
d2i_OCSP_CERTID,
d2i_OCSP_CERTSTATUS,
d2i_OCSP_CRLID,
d2i_OCSP_ONEREQ,
d2i_OCSP_REQINFO,
d2i_OCSP_REQUEST,
d2i_OCSP_RESPBYTES,
d2i_OCSP_RESPDATA,
d2i_OCSP_RESPID,
d2i_OCSP_RESPONSE,
d2i_OCSP_REVOKEDINFO,
d2i_OCSP_SERVICELOC,
d2i_OCSP_SIGNATURE,
d2i_OCSP_SINGLERESP,
d2i_OSSL_CMP_MSG,
d2i_OSSL_CMP_PKIHEADER,
d2i_OSSL_CMP_PKISI,
d2i_OSSL_CRMF_CERTID,
d2i_OSSL_CRMF_CERTTEMPLATE,
d2i_OSSL_CRMF_ENCRYPTEDVALUE,
d2i_OSSL_CRMF_MSG,
d2i_OSSL_CRMF_MSGS,
d2i_OSSL_CRMF_PBMPARAMETER,
d2i_OSSL_CRMF_PKIPUBLICATIONINFO,
d2i_OSSL_CRMF_SINGLEPUBINFO,
d2i_OTHERNAME,
d2i_PBE2PARAM,
d2i_PBEPARAM,
d2i_PBKDF2PARAM,
d2i_PKCS12,
d2i_PKCS12_BAGS,
d2i_PKCS12_MAC_DATA,
d2i_PKCS12_SAFEBAG,
d2i_PKCS12_bio,
d2i_PKCS12_fp,
d2i_PKCS7,
d2i_PKCS7_DIGEST,
d2i_PKCS7_ENCRYPT,
d2i_PKCS7_ENC_CONTENT,
d2i_PKCS7_ENVELOPE,
d2i_PKCS7_ISSUER_AND_SERIAL,
d2i_PKCS7_RECIP_INFO,
d2i_PKCS7_SIGNED,
d2i_PKCS7_SIGNER_INFO,
d2i_PKCS7_SIGN_ENVELOPE,
d2i_PKCS7_bio,
d2i_PKCS7_fp,
d2i_PKCS8_PRIV_KEY_INFO,
d2i_PKCS8_PRIV_KEY_INFO_bio,
d2i_PKCS8_PRIV_KEY_INFO_fp,
d2i_PKCS8_bio,
d2i_PKCS8_fp,
d2i_PKEY_USAGE_PERIOD,
d2i_POLICYINFO,
d2i_POLICYQUALINFO,
d2i_PROFESSION_INFO,
d2i_PROXY_CERT_INFO_EXTENSION,
d2i_PROXY_POLICY,
d2i_RSA_OAEP_PARAMS,
d2i_RSA_PSS_PARAMS,
d2i_SCRYPT_PARAMS,
d2i_SCT_LIST,
d2i_SXNET,
d2i_SXNETID,
d2i_TS_ACCURACY,
d2i_TS_MSG_IMPRINT,
d2i_TS_MSG_IMPRINT_bio,
d2i_TS_MSG_IMPRINT_fp,
d2i_TS_REQ,
d2i_TS_REQ_bio,
d2i_TS_REQ_fp,
d2i_TS_RESP,
d2i_TS_RESP_bio,
d2i_TS_RESP_fp,
d2i_TS_STATUS_INFO,
d2i_TS_TST_INFO,
d2i_TS_TST_INFO_bio,
d2i_TS_TST_INFO_fp,
d2i_USERNOTICE,
d2i_X509,
d2i_X509_bio,
d2i_X509_fp,
d2i_X509_ALGOR,
d2i_X509_ALGORS,
d2i_X509_ATTRIBUTE,
d2i_X509_CERT_AUX,
d2i_X509_CINF,
d2i_X509_CRL,
d2i_X509_CRL_INFO,
d2i_X509_CRL_bio,
d2i_X509_CRL_fp,
d2i_X509_EXTENSION,
d2i_X509_EXTENSIONS,
d2i_X509_NAME,
d2i_X509_NAME_ENTRY,
d2i_X509_PUBKEY,
d2i_X509_PUBKEY_bio,
d2i_X509_PUBKEY_fp,
d2i_X509_REQ,
d2i_X509_REQ_INFO,
d2i_X509_REQ_bio,
d2i_X509_REQ_fp,
d2i_X509_REVOKED,
d2i_X509_SIG,
d2i_X509_VAL,
i2d_ACCESS_DESCRIPTION,
i2d_ADMISSIONS,
i2d_ADMISSION_SYNTAX,
i2d_ASIdOrRange,
i2d_ASIdentifierChoice,
i2d_ASIdentifiers,
i2d_ASN1_BIT_STRING,
i2d_ASN1_BMPSTRING,
i2d_ASN1_ENUMERATED,
i2d_ASN1_GENERALIZEDTIME,
i2d_ASN1_GENERALSTRING,
i2d_ASN1_IA5STRING,
i2d_ASN1_INTEGER,
i2d_ASN1_NULL,
i2d_ASN1_OBJECT,
i2d_ASN1_OCTET_STRING,
i2d_ASN1_PRINTABLE,
i2d_ASN1_PRINTABLESTRING,
i2d_ASN1_SEQUENCE_ANY,
i2d_ASN1_SET_ANY,
i2d_ASN1_T61STRING,
i2d_ASN1_TIME,
i2d_ASN1_TYPE,
i2d_ASN1_UNIVERSALSTRING,
i2d_ASN1_UTCTIME,
i2d_ASN1_UTF8STRING,
i2d_ASN1_VISIBLESTRING,
i2d_ASN1_bio_stream,
i2d_ASRange,
i2d_AUTHORITY_INFO_ACCESS,
i2d_AUTHORITY_KEYID,
i2d_BASIC_CONSTRAINTS,
i2d_CERTIFICATEPOLICIES,
i2d_CMS_ContentInfo,
i2d_CMS_ReceiptRequest,
i2d_CMS_bio,
i2d_CRL_DIST_POINTS,
i2d_DHxparams,
i2d_DIRECTORYSTRING,
i2d_DISPLAYTEXT,
i2d_DIST_POINT,
i2d_DIST_POINT_NAME,
i2d_DSA_SIG,
i2d_ECDSA_SIG,
i2d_ECPKParameters,
i2d_EDIPARTYNAME,
i2d_ESS_CERT_ID,
i2d_ESS_CERT_ID_V2,
i2d_ESS_ISSUER_SERIAL,
i2d_ESS_SIGNING_CERT,
i2d_ESS_SIGNING_CERT_V2,
i2d_EXTENDED_KEY_USAGE,
i2d_GENERAL_NAME,
i2d_GENERAL_NAMES,
i2d_IPAddressChoice,
i2d_IPAddressFamily,
i2d_IPAddressOrRange,
i2d_IPAddressRange,
i2d_ISSUER_SIGN_TOOL,
i2d_ISSUING_DIST_POINT,
i2d_NAMING_AUTHORITY,
i2d_NETSCAPE_CERT_SEQUENCE,
i2d_NETSCAPE_SPKAC,
i2d_NETSCAPE_SPKI,
i2d_NOTICEREF,
i2d_OCSP_BASICRESP,
i2d_OCSP_CERTID,
i2d_OCSP_CERTSTATUS,
i2d_OCSP_CRLID,
i2d_OCSP_ONEREQ,
i2d_OCSP_REQINFO,
i2d_OCSP_REQUEST,
i2d_OCSP_RESPBYTES,
i2d_OCSP_RESPDATA,
i2d_OCSP_RESPID,
i2d_OCSP_RESPONSE,
i2d_OCSP_REVOKEDINFO,
i2d_OCSP_SERVICELOC,
i2d_OCSP_SIGNATURE,
i2d_OCSP_SINGLERESP,
i2d_OSSL_CMP_MSG,
i2d_OSSL_CMP_PKIHEADER,
i2d_OSSL_CMP_PKISI,
i2d_OSSL_CRMF_CERTID,
i2d_OSSL_CRMF_CERTTEMPLATE,
i2d_OSSL_CRMF_ENCRYPTEDVALUE,
i2d_OSSL_CRMF_MSG,
i2d_OSSL_CRMF_MSGS,
i2d_OSSL_CRMF_PBMPARAMETER,
i2d_OSSL_CRMF_PKIPUBLICATIONINFO,
i2d_OSSL_CRMF_SINGLEPUBINFO,
i2d_OTHERNAME,
i2d_PBE2PARAM,
i2d_PBEPARAM,
i2d_PBKDF2PARAM,
i2d_PKCS12,
i2d_PKCS12_BAGS,
i2d_PKCS12_MAC_DATA,
i2d_PKCS12_SAFEBAG,
i2d_PKCS12_bio,
i2d_PKCS12_fp,
i2d_PKCS7,
i2d_PKCS7_DIGEST,
i2d_PKCS7_ENCRYPT,
i2d_PKCS7_ENC_CONTENT,
i2d_PKCS7_ENVELOPE,
i2d_PKCS7_ISSUER_AND_SERIAL,
i2d_PKCS7_NDEF,
i2d_PKCS7_RECIP_INFO,
i2d_PKCS7_SIGNED,
i2d_PKCS7_SIGNER_INFO,
i2d_PKCS7_SIGN_ENVELOPE,
i2d_PKCS7_bio,
i2d_PKCS7_fp,
i2d_PKCS8PrivateKeyInfo_bio,
i2d_PKCS8PrivateKeyInfo_fp,
i2d_PKCS8_PRIV_KEY_INFO,
i2d_PKCS8_PRIV_KEY_INFO_bio,
i2d_PKCS8_PRIV_KEY_INFO_fp,
i2d_PKCS8_bio,
i2d_PKCS8_fp,
i2d_PKEY_USAGE_PERIOD,
i2d_POLICYINFO,
i2d_POLICYQUALINFO,
i2d_PROFESSION_INFO,
i2d_PROXY_CERT_INFO_EXTENSION,
i2d_PROXY_POLICY,
i2d_RSA_OAEP_PARAMS,
i2d_RSA_PSS_PARAMS,
i2d_SCRYPT_PARAMS,
i2d_SCT_LIST,
i2d_SXNET,
i2d_SXNETID,
i2d_TS_ACCURACY,
i2d_TS_MSG_IMPRINT,
i2d_TS_MSG_IMPRINT_bio,
i2d_TS_MSG_IMPRINT_fp,
i2d_TS_REQ,
i2d_TS_REQ_bio,
i2d_TS_REQ_fp,
i2d_TS_RESP,
i2d_TS_RESP_bio,
i2d_TS_RESP_fp,
i2d_TS_STATUS_INFO,
i2d_TS_TST_INFO,
i2d_TS_TST_INFO_bio,
i2d_TS_TST_INFO_fp,
i2d_USERNOTICE,
i2d_X509,
i2d_X509_bio,
i2d_X509_fp,
i2d_X509_ALGOR,
i2d_X509_ALGORS,
i2d_X509_ATTRIBUTE,
i2d_X509_CERT_AUX,
i2d_X509_CINF,
i2d_X509_CRL,
i2d_X509_CRL_INFO,
i2d_X509_CRL_bio,
i2d_X509_CRL_fp,
i2d_X509_EXTENSION,
i2d_X509_EXTENSIONS,
i2d_X509_NAME,
i2d_X509_NAME_ENTRY,
i2d_X509_PUBKEY,
i2d_X509_PUBKEY_bio,
i2d_X509_PUBKEY_fp,
i2d_X509_REQ,
i2d_X509_REQ_INFO,
i2d_X509_REQ_bio,
i2d_X509_REQ_fp,
i2d_X509_REVOKED,
i2d_X509_SIG,
i2d_X509_VAL,
- convert objects from/to ASN.1/DER representation
=head1 SYNOPSIS
=for openssl generic
TYPE *d2i_TYPE(TYPE **a, const unsigned char **ppin, long length);
TYPE *d2i_TYPE_bio(BIO *bp, TYPE **a);
TYPE *d2i_TYPE_fp(FILE *fp, TYPE **a);
int i2d_TYPE(const TYPE *a, unsigned char **ppout);
int i2d_TYPE(TYPE *a, unsigned char **ppout);
int i2d_TYPE_fp(FILE *fp, const TYPE *a);
int i2d_TYPE_fp(FILE *fp, TYPE *a);
int i2d_TYPE_bio(BIO *bp, const TYPE *a);
int i2d_TYPE_bio(BIO *bp, TYPE *a);
=head1 DESCRIPTION
In the description here, B<I<TYPE>> is used a placeholder
for any of the OpenSSL datatypes, such as B<X509_CRL>.
The function parameters I<ppin> and I<ppout> are generally
either both named I<pp> in the headers, or I<in> and I<out>.
These functions convert OpenSSL objects to and from their ASN.1/DER
encoding. Unlike the C structures which can have pointers to sub-objects
within, the DER is a serialized encoding, suitable for sending over the
network, writing to a file, and so on.
B<d2i_I<TYPE>>() attempts to decode I<len> bytes at I<*ppin>. If successful a
pointer to the B<I<TYPE>> structure is returned and I<*ppin> is incremented to
the byte following the parsed data. If I<a> is not NULL then a pointer
to the returned structure is also written to I<*a>. If an error occurred
-then NULL is returned.
+then NULL is returned. The caller retains ownership of the
+returned object and needs to free it when it is no longer needed, e.g.
+using X509_free() for X509 objects or DSA_SIG_free() for DSA_SIG objects.
On a successful return, if I<*a> is not NULL then it is assumed that I<*a>
contains a valid B<I<TYPE>> structure and an attempt is made to reuse it.
For B<I<TYPE>> structures where it matters it is possible to set up a library
context on the decoded structure this way (see the B<EXAMPLES> section).
However using the "reuse" capability for other purposes is B<strongly
discouraged> (see B<BUGS> below, and the discussion in the B<RETURN VALUES>
section).
B<d2i_I<TYPE>_bio>() is similar to B<d2i_I<TYPE>>() except it attempts
to parse data from BIO I<bp>.
B<d2i_I<TYPE>_fp>() is similar to B<d2i_I<TYPE>>() except it attempts
to parse data from FILE pointer I<fp>.
B<i2d_I<TYPE>>() encodes the structure pointed to by I<a> into DER format.
If I<ppout> is not NULL, it writes the DER encoded data to the buffer
at I<*ppout>, and increments it to point after the data just written.
If the return value is negative an error occurred, otherwise it
returns the length of the encoded data.
If I<*ppout> is NULL memory will be allocated for a buffer and the encoded
data written to it. In this case I<*ppout> is not incremented and it points
to the start of the data just written.
B<i2d_I<TYPE>_bio>() is similar to B<i2d_I<TYPE>>() except it writes
the encoding of the structure I<a> to BIO I<bp> and it
returns 1 for success and 0 for failure.
B<i2d_I<TYPE>_fp>() is similar to B<i2d_I<TYPE>>() except it writes
the encoding of the structure I<a> to FILE pointer I<fp> and it
returns 1 for success and 0 for failure.
These routines do not encrypt private keys and therefore offer no
security; use L<PEM_write_PrivateKey(3)> or similar for writing to files.
=head1 NOTES
The letters B<i> and B<d> in B<i2d_I<TYPE>>() stand for
"internal" (that is, an internal C structure) and "DER" respectively.
So B<i2d_I<TYPE>>() converts from internal to DER.
The functions can also understand B<BER> forms.
The actual TYPE structure passed to B<i2d_I<TYPE>>() must be a valid
populated B<I<TYPE>> structure -- it B<cannot> simply be fed with an
empty structure such as that returned by TYPE_new().
The encoded data is in binary form and may contain embedded zeros.
Therefore, any FILE pointers or BIOs should be opened in binary mode.
Functions such as strlen() will B<not> return the correct length
of the encoded structure.
The ways that I<*ppin> and I<*ppout> are incremented after the operation
can trap the unwary. See the B<WARNINGS> section for some common
errors.
The reason for this-auto increment behaviour is to reflect a typical
usage of ASN1 functions: after one structure is encoded or decoded
another will be processed after it.
The following points about the data types might be useful:
=over 4
=item B<ASN1_OBJECT>
Represents an ASN1 OBJECT IDENTIFIER.
=item B<DHparams>
Represents a PKCS#3 DH parameters structure.
=item B<DHxparams>
Represents an ANSI X9.42 DH parameters structure.
=item B<ECDSA_SIG>
Represents an ECDSA signature.
=item B<X509_ALGOR>
Represents an B<AlgorithmIdentifier> structure as used in IETF RFC 6960 and
elsewhere.
=item B<X509_NAME>
Represents a B<Name> type as used for subject and issuer names in
IETF RFC 6960 and elsewhere.
=item B<X509_REQ>
Represents a PKCS#10 certificate request.
=item B<X509_SIG>
Represents the B<DigestInfo> structure defined in PKCS#1 and PKCS#7.
=back
=head1 RETURN VALUES
B<d2i_I<TYPE>>(), B<d2i_I<TYPE>_bio>() and B<d2i_I<TYPE>_fp>() return a valid
B<I<TYPE>> structure or NULL if an error occurs. If the "reuse" capability has
been used with a valid structure being passed in via I<a>, then the object is
freed in the event of error and I<*a> is set to NULL.
B<i2d_I<TYPE>>() returns the number of bytes successfully encoded or a negative
value if an error occurs.
B<i2d_I<TYPE>_bio>() and B<i2d_I<TYPE>_fp>() return 1 for success and 0 if an
error occurs.
=head1 EXAMPLES
Allocate and encode the DER encoding of an X509 structure:
int len;
unsigned char *buf;
buf = NULL;
len = i2d_X509(x, &buf);
if (len < 0)
/* error */
Attempt to decode a buffer:
X509 *x;
unsigned char *buf;
const unsigned char *p;
int len;
/* Set up buf and len to point to the input buffer. */
p = buf;
x = d2i_X509(NULL, &p, len);
if (x == NULL)
/* error */
Alternative technique:
X509 *x;
unsigned char *buf;
const unsigned char *p;
int len;
/* Set up buf and len to point to the input buffer. */
p = buf;
x = NULL;
if (d2i_X509(&x, &p, len) == NULL)
/* error */
Setting up a library context and property query:
X509 *x;
unsigned char *buf;
const unsigned char *p;
int len;
OSSL_LIB_CTX *libctx = ....;
const char *propq = ....;
/* Set up buf and len to point to the input buffer. */
p = buf;
x = X509_new_ex(libctx, propq);
if (d2i_X509(&x, &p, len) == NULL)
/* error, x was freed and NULL assigned to it (see RETURN VALUES) */
=head1 WARNINGS
Using a temporary variable is mandatory. A common
mistake is to attempt to use a buffer directly as follows:
int len;
unsigned char *buf;
len = i2d_X509(x, NULL);
buf = OPENSSL_malloc(len);
...
i2d_X509(x, &buf);
...
OPENSSL_free(buf);
This code will result in I<buf> apparently containing garbage because
it was incremented after the call to point after the data just written.
Also I<buf> will no longer contain the pointer allocated by OPENSSL_malloc()
and the subsequent call to OPENSSL_free() is likely to crash.
Another trap to avoid is misuse of the I<a> argument to B<d2i_I<TYPE>>():
X509 *x;
if (d2i_X509(&x, &p, len) == NULL)
/* error */
This will probably crash somewhere in d2i_X509(). The reason for this
is that the variable I<x> is uninitialized and an attempt will be made to
interpret its (invalid) value as an B<X509> structure, typically causing
a segmentation violation. If I<x> is set to NULL first then this will not
happen.
=head1 BUGS
In some versions of OpenSSL the "reuse" behaviour of B<d2i_I<TYPE>>() when
I<*a> is valid is broken and some parts of the reused structure may
persist if they are not present in the new one. Additionally, in versions of
OpenSSL prior to 1.1.0, when the "reuse" behaviour is used and an error occurs
the behaviour is inconsistent. Some functions behaved as described here, while
some did not free I<*a> on error and did not set I<*a> to NULL.
As a result of the above issues the "reuse" behaviour is strongly discouraged.
B<i2d_I<TYPE>>() will not return an error in many versions of OpenSSL,
if mandatory fields are not initialized due to a programming error
then the encoded structure may contain invalid data or omit the
fields entirely and will not be parsed by B<d2i_I<TYPE>>(). This may be
fixed in future so code should not assume that B<i2d_I<TYPE>>() will
always succeed.
Any function which encodes a structure (B<i2d_I<TYPE>>(),
B<i2d_I<TYPE>_bio>() or B<i2d_I<TYPE>_fp>()) may return a stale encoding if the
structure has been modified after deserialization or previous
serialization. This is because some objects cache the encoding for
efficiency reasons.
=head1 COPYRIGHT
-Copyright 1998-2023 The OpenSSL Project Authors. All Rights Reserved.
+Copyright 1998-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_KEYEXCH-DH.pod b/crypto/openssl/doc/man7/EVP_KEYEXCH-DH.pod
index a6927afefb24..eaec67775ddb 100644
--- a/crypto/openssl/doc/man7/EVP_KEYEXCH-DH.pod
+++ b/crypto/openssl/doc/man7/EVP_KEYEXCH-DH.pod
@@ -1,132 +1,137 @@
=pod
=head1 NAME
EVP_KEYEXCH-DH
- DH Key Exchange algorithm support
=head1 DESCRIPTION
-Key exchange support for the B<DH> key type.
+Key exchange support for the B<DH> and B<DHX> key types.
-=head2 DH key exchange parameters
+Please note that although both key types support the same key exchange
+operations, they cannot be used together in a single key exchange. It
+is not possible to use a private key of the B<DH> type in key exchange
+with the public key of B<DHX> type and vice versa.
+
+=head2 DH and DHX key exchange parameters
=over 4
=item "pad" (B<OSSL_EXCHANGE_PARAM_PAD>) <unsigned integer>
Sets the padding mode for the associated key exchange ctx.
Setting a value of 1 will turn padding on.
Setting a value of 0 will turn padding off.
If padding is off then the derived shared secret may be smaller than the
largest possible secret size.
If padding is on then the derived shared secret will have its first bytes
filled with zeros where necessary to make the shared secret the same size as
the largest possible secret size.
The padding mode parameter is ignored (and padding implicitly enabled) when
the KDF type is set to "X942KDF-ASN1" (B<OSSL_KDF_NAME_X942KDF_ASN1>).
=item "kdf-type" (B<OSSL_EXCHANGE_PARAM_KDF_TYPE>) <UTF8 string>
See L<provider-keyexch(7)/Common Key Exchange parameters>.
=item "kdf-digest" (B<OSSL_EXCHANGE_PARAM_KDF_DIGEST>) <UTF8 string>
See L<provider-keyexch(7)/Common Key Exchange parameters>.
=item "kdf-digest-props" (B<OSSL_EXCHANGE_PARAM_KDF_DIGEST_PROPS>) <UTF8 string>
See L<provider-keyexch(7)/Common Key Exchange parameters>.
=item "kdf-outlen" (B<OSSL_EXCHANGE_PARAM_KDF_OUTLEN>) <unsigned integer>
See L<provider-keyexch(7)/Common Key Exchange parameters>.
=item "kdf-ukm" (B<OSSL_EXCHANGE_PARAM_KDF_UKM>) <octet string>
See L<provider-keyexch(7)/Common Key Exchange parameters>.
=item "cekalg" (B<OSSL_KDF_PARAM_CEK_ALG>) <octet string ptr>
See L<provider-kdf(7)/KDF Parameters>.
=back
=head1 EXAMPLES
The examples assume a host and peer both generate keys using the same
named group (or domain parameters). See L<EVP_PKEY-DH(7)/Examples>.
Both the host and peer transfer their public key to each other.
To convert the peer's generated key pair to a public key in DER format in order
to transfer to the host:
EVP_PKEY *peer_key; /* It is assumed this contains the peers generated key */
unsigned char *peer_pub_der = NULL;
int peer_pub_der_len;
peer_pub_der_len = i2d_PUBKEY(peer_key, &peer_pub_der);
...
OPENSSL_free(peer_pub_der);
To convert the received peer's public key from DER format on the host:
const unsigned char *pd = peer_pub_der;
EVP_PKEY *peer_pub_key = d2i_PUBKEY(NULL, &pd, peer_pub_der_len);
...
EVP_PKEY_free(peer_pub_key);
To derive a shared secret on the host using the host's key and the peer's public
key:
/* It is assumed that the host_key and peer_pub_key are set up */
void derive_secret(EVP_KEY *host_key, EVP_PKEY *peer_pub_key)
{
unsigned int pad = 1;
OSSL_PARAM params[2];
unsigned char *secret = NULL;
size_t secret_len = 0;
EVP_PKEY_CTX *dctx = EVP_PKEY_CTX_new_from_pkey(NULL, host_key, NULL);
EVP_PKEY_derive_init(dctx);
/* Optionally set the padding */
params[0] = OSSL_PARAM_construct_uint(OSSL_EXCHANGE_PARAM_PAD, &pad);
params[1] = OSSL_PARAM_construct_end();
EVP_PKEY_CTX_set_params(dctx, params);
EVP_PKEY_derive_set_peer(dctx, peer_pub_key);
/* Get the size by passing NULL as the buffer */
EVP_PKEY_derive(dctx, NULL, &secret_len);
secret = OPENSSL_zalloc(secret_len);
EVP_PKEY_derive(dctx, secret, &secret_len);
...
OPENSSL_clear_free(secret, secret_len);
EVP_PKEY_CTX_free(dctx);
}
Very similar code can be used by the peer to derive the same shared secret
using the host's public key and the peer's generated key pair.
=head1 SEE ALSO
L<EVP_PKEY-DH(7)>,
L<EVP_PKEY-FFC(7)>,
L<EVP_PKEY(3)>,
L<provider-keyexch(7)>,
L<provider-keymgmt(7)>,
L<OSSL_PROVIDER-default(7)>,
L<OSSL_PROVIDER-FIPS(7)>,
=head1 COPYRIGHT
-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
L<https://www.openssl.org/source/license.html>.
=cut
diff --git a/crypto/openssl/doc/man7/EVP_PKEY-DH.pod b/crypto/openssl/doc/man7/EVP_PKEY-DH.pod
index 1dfc9c734544..1232730c3364 100644
--- a/crypto/openssl/doc/man7/EVP_PKEY-DH.pod
+++ b/crypto/openssl/doc/man7/EVP_PKEY-DH.pod
@@ -1,337 +1,339 @@
=pod
=head1 NAME
EVP_PKEY-DH, EVP_PKEY-DHX, EVP_KEYMGMT-DH, EVP_KEYMGMT-DHX
- EVP_PKEY DH and DHX keytype and algorithm support
=head1 DESCRIPTION
-For B<DH> FFC key agreement, two classes of domain parameters can be used:
-"safe" domain parameters that are associated with approved named safe-prime
-groups, and a class of "FIPS186-type" domain parameters. FIPS186-type domain
-parameters should only be used for backward compatibility with existing
-applications that cannot be upgraded to use the approved safe-prime groups.
+For finite field Diffie-Hellman key agreement, two classes of domain
+parameters can be used: "safe" domain parameters that are associated with
+approved named safe-prime groups, and a class of "FIPS186-type" domain
+parameters. FIPS186-type domain parameters should only be used for backward
+compatibility with existing applications that cannot be upgraded to use the
+approved safe-prime groups.
See L<EVP_PKEY-FFC(7)> for more information about FFC keys.
The B<DH> key type uses PKCS#3 format which saves I<p> and I<g>, but not the
I<q> value.
The B<DHX> key type uses X9.42 format which saves the value of I<q> and this
must be used for FIPS186-4. If key validation is required, users should be aware
of the nuances associated with FIPS186-4 style parameters as discussed in
-L</DH key validation>.
+L</DH and DHX key validation>.
=head2 DH and DHX domain parameters
-In addition to the common FCC parameters that all FFC keytypes should support
+In addition to the common FFC parameters that all FFC keytypes should support
(see L<EVP_PKEY-FFC(7)/FFC parameters>) the B<DHX> and B<DH> keytype
implementations support the following:
=over 4
=item "group" (B<OSSL_PKEY_PARAM_GROUP_NAME>) <UTF8 string>
Sets or gets a string that associates a B<DH> or B<DHX> named safe prime group
with known values for I<p>, I<q> and I<g>.
The following values can be used by the OpenSSL's default and FIPS providers:
"ffdhe2048", "ffdhe3072", "ffdhe4096", "ffdhe6144", "ffdhe8192",
"modp_2048", "modp_3072", "modp_4096", "modp_6144", "modp_8192".
The following additional values can also be used by OpenSSL's default provider:
"modp_1536", "dh_1024_160", "dh_2048_224", "dh_2048_256".
DH/DHX named groups can be easily validated since the parameters are well known.
For protocols that only transfer I<p> and I<g> the value of I<q> can also be
retrieved.
=back
=head2 DH and DHX additional parameters
=over 4
=item "encoded-pub-key" (B<OSSL_PKEY_PARAM_ENCODED_PUBLIC_KEY>) <octet string>
Used for getting and setting the encoding of the DH public key used in a key
exchange message for the TLS protocol.
See EVP_PKEY_set1_encoded_public_key() and EVP_PKEY_get1_encoded_public_key().
=back
=head2 DH additional domain parameters
=over 4
=item "safeprime-generator" (B<OSSL_PKEY_PARAM_DH_GENERATOR>) <integer>
Used for DH generation of safe primes using the old safe prime generator code.
The default value is 2.
It is recommended to use a named safe prime group instead, if domain parameter
validation is required.
Randomly generated safe primes are not allowed by FIPS, so setting this value
for the OpenSSL FIPS provider will instead choose a named safe prime group
based on the size of I<p>.
=back
=head2 DH and DHX domain parameter / key generation parameters
In addition to the common FFC key generation parameters that all FFC key types
should support (see L<EVP_PKEY-FFC(7)/FFC key generation parameters>) the
B<DH> and B<DHX> keytype implementation supports the following:
=over 4
=item "type" (B<OSSL_PKEY_PARAM_FFC_TYPE>) <UTF8 string>
Sets the type of parameter generation. For B<DH> valid values are:
=over 4
=item "fips186_4"
=item "default"
=item "fips186_2"
These are described in L<EVP_PKEY-FFC(7)/FFC key generation parameters>
=item "group"
This specifies that a named safe prime name will be chosen using the "pbits"
type.
=item "generator"
A safe prime generator. See the "safeprime-generator" type above.
This is only valid for B<DH> keys.
=back
=item "pbits" (B<OSSL_PKEY_PARAM_FFC_PBITS>) <unsigned integer>
Sets the size (in bits) of the prime 'p'.
For "fips186_4" this must be 2048.
For "fips186_2" this must be 1024.
For "group" this can be any one of 2048, 3072, 4096, 6144 or 8192.
=item "priv_len" (B<OSSL_PKEY_PARAM_DH_PRIV_LEN>) <integer>
An optional value to set the maximum length of the generated private key.
The default value used if this is not set is the maximum value of
BN_num_bits(I<q>)). The minimum value that this can be set to is 2 * s.
Where s is the security strength of the key which has values of
112, 128, 152, 176 and 200 for key sizes of 2048, 3072, 4096, 6144 and 8192.
=back
-=head2 DH key validation
+=head2 DH and DHX key validation
-For B<DHX> that is not a named group the FIPS186-4 standard specifies that the
+For keys that are not a named group the FIPS186-4 standard specifies that the
values used for FFC parameter generation are also required for parameter
validation. This means that optional FFC domain parameter values for
I<seed>, I<pcounter> and I<gindex> or I<hindex> may need to be stored for
validation purposes.
For B<DHX> the I<seed> and I<pcounter> can be stored in ASN1 data
(but the I<gindex> or I<hindex> cannot be stored). It is recommended to use a
-named safe prime group instead.
+B<DH> parameters with named safe prime group instead.
-For DH keys, L<EVP_PKEY_param_check(3)> behaves in the following way:
-The OpenSSL FIPS provider tests if the parameters are either an approved safe
-prime group OR that the FFC parameters conform to FIPS186-4 as defined in
-SP800-56Ar3 I<Assurances of Domain-Parameter Validity>.
-The OpenSSL default provider uses simpler checks that allows there to be no I<q>
-value for backwards compatibility.
+With the OpenSSL FIPS provider, L<EVP_PKEY_param_check(3)> and
+L<EVP_PKEY_param_check_quick(3)> behave in the following way: the parameters
+are tested if they are either an approved safe prime group OR that the FFC
+parameters conform to FIPS186-4 as defined in SP800-56Ar3 I<Assurances of
+Domain-Parameter Validity>.
-For DH keys, L<EVP_PKEY_param_check_quick(3)> is equivalent to
-L<EVP_PKEY_param_check(3)>.
+The OpenSSL default provider uses simpler checks that allows there to be no I<q>
+value for backwards compatibility, however the L<EVP_PKEY_param_check(3)> will
+test the I<p> value for being a prime (and a safe prime if I<q> is missing)
+which can take significant time. The L<EVP_PKEY_param_check_quick(3)> avoids
+the prime tests.
-For DH keys, L<EVP_PKEY_public_check(3)> conforms to
-SP800-56Ar3 I<FFC Full Public-Key Validation>.
+L<EVP_PKEY_public_check(3)> conforms to SP800-56Ar3
+I<FFC Full Public-Key Validation>.
-For DH keys, L<EVP_PKEY_public_check_quick(3)> conforms to
-SP800-56Ar3 I<FFC Partial Public-Key Validation> when the
-DH key is an approved named safe prime group, otherwise it is the same as
-L<EVP_PKEY_public_check(3)>.
+L<EVP_PKEY_public_check_quick(3)> conforms to SP800-56Ar3
+I<FFC Partial Public-Key Validation> when the key is an approved named safe
+prime group, otherwise it is the same as L<EVP_PKEY_public_check(3)>.
-For DH Keys, L<EVP_PKEY_private_check(3)> tests that the private key is in the
-correct range according to SP800-56Ar3. The OpenSSL FIPS provider requires the
-value of I<q> to be set (note that this is set for named safe prime groups).
+L<EVP_PKEY_private_check(3)> tests that the private key is in the correct range
+according to SP800-56Ar3. The OpenSSL FIPS provider requires the value of I<q>
+to be set (note that this is implicitly set for named safe prime groups).
For backwards compatibility the OpenSSL default provider only requires I<p> to
be set.
-For DH keys, L<EVP_PKEY_pairwise_check(3)> conforms to
-SP800-56Ar3 I<Owner Assurance of Pair-wise Consistency>.
+L<EVP_PKEY_pairwise_check(3)> conforms to SP800-56Ar3
+I<Owner Assurance of Pair-wise Consistency>.
=head1 EXAMPLES
An B<EVP_PKEY> context can be obtained by calling:
EVP_PKEY_CTX *pctx = EVP_PKEY_CTX_new_from_name(NULL, "DH", NULL);
A B<DH> key can be generated with a named safe prime group by calling:
int priv_len = 2 * 112;
OSSL_PARAM params[3];
EVP_PKEY *pkey = NULL;
EVP_PKEY_CTX *pctx = EVP_PKEY_CTX_new_from_name(NULL, "DH", NULL);
params[0] = OSSL_PARAM_construct_utf8_string("group", "ffdhe2048", 0);
/* "priv_len" is optional */
params[1] = OSSL_PARAM_construct_int("priv_len", &priv_len);
params[2] = OSSL_PARAM_construct_end();
EVP_PKEY_keygen_init(pctx);
EVP_PKEY_CTX_set_params(pctx, params);
EVP_PKEY_generate(pctx, &pkey);
...
EVP_PKEY_free(pkey);
EVP_PKEY_CTX_free(pctx);
B<DHX> domain parameters can be generated according to B<FIPS186-4> by calling:
int gindex = 2;
unsigned int pbits = 2048;
unsigned int qbits = 256;
OSSL_PARAM params[6];
EVP_PKEY *param_key = NULL;
EVP_PKEY_CTX *pctx = NULL;
pctx = EVP_PKEY_CTX_new_from_name(NULL, "DHX", NULL);
EVP_PKEY_paramgen_init(pctx);
params[0] = OSSL_PARAM_construct_uint("pbits", &pbits);
params[1] = OSSL_PARAM_construct_uint("qbits", &qbits);
params[2] = OSSL_PARAM_construct_int("gindex", &gindex);
params[3] = OSSL_PARAM_construct_utf8_string("type", "fips186_4", 0);
params[4] = OSSL_PARAM_construct_utf8_string("digest", "SHA256", 0);
params[5] = OSSL_PARAM_construct_end();
EVP_PKEY_CTX_set_params(pctx, params);
EVP_PKEY_generate(pctx, &param_key);
EVP_PKEY_print_params(bio_out, param_key, 0, NULL);
...
EVP_PKEY_free(param_key);
EVP_PKEY_CTX_free(pctx);
A B<DH> key can be generated using domain parameters by calling:
EVP_PKEY *key = NULL;
EVP_PKEY_CTX *gctx = EVP_PKEY_CTX_new_from_pkey(NULL, param_key, NULL);
EVP_PKEY_keygen_init(gctx);
EVP_PKEY_generate(gctx, &key);
EVP_PKEY_print_private(bio_out, key, 0, NULL);
...
EVP_PKEY_free(key);
EVP_PKEY_CTX_free(gctx);
To validate B<FIPS186-4> B<DHX> domain parameters decoded from B<PEM> or
B<DER> data, additional values used during generation may be required to
be set into the key.
EVP_PKEY_todata(), OSSL_PARAM_merge(), and EVP_PKEY_fromdata() are useful
to add these parameters to the original key or domain parameters before
the actual validation. In production code the return values should be checked.
EVP_PKEY *received_domp = ...; /* parameters received and decoded */
unsigned char *seed = ...; /* and additional parameters received */
size_t seedlen = ...; /* by other means, required */
int gindex = ...; /* for the validation */
int pcounter = ...;
int hindex = ...;
OSSL_PARAM extra_params[4];
OSSL_PARAM *domain_params = NULL;
OSSL_PARAM *merged_params = NULL;
EVP_PKEY_CTX *ctx = NULL, *validate_ctx = NULL;
EVP_PKEY *complete_domp = NULL;
EVP_PKEY_todata(received_domp, OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS,
&domain_params);
extra_params[0] = OSSL_PARAM_construct_octet_string("seed", seed, seedlen);
/*
* NOTE: For unverifiable g use "hindex" instead of "gindex"
* extra_params[1] = OSSL_PARAM_construct_int("hindex", &hindex);
*/
extra_params[1] = OSSL_PARAM_construct_int("gindex", &gindex);
extra_params[2] = OSSL_PARAM_construct_int("pcounter", &pcounter);
extra_params[3] = OSSL_PARAM_construct_end();
merged_params = OSSL_PARAM_merge(domain_params, extra_params);
ctx = EVP_PKEY_CTX_new_from_name(NULL, "DHX", NULL);
EVP_PKEY_fromdata_init(ctx);
EVP_PKEY_fromdata(ctx, &complete_domp, OSSL_KEYMGMT_SELECT_ALL,
merged_params);
validate_ctx = EVP_PKEY_CTX_new_from_pkey(NULL, complete_domp, NULL);
if (EVP_PKEY_param_check(validate_ctx) > 0)
/* validation_passed(); */
else
/* validation_failed(); */
OSSL_PARAM_free(domain_params);
OSSL_PARAM_free(merged_params);
EVP_PKEY_CTX_free(ctx);
EVP_PKEY_CTX_free(validate_ctx);
EVP_PKEY_free(complete_domp);
=head1 CONFORMING TO
=over 4
=item RFC 7919 (TLS ffdhe named safe prime groups)
=item RFC 3526 (IKE modp named safe prime groups)
=item RFC 5114 (Additional DH named groups for dh_1024_160", "dh_2048_224"
and "dh_2048_256").
=back
The following sections of SP800-56Ar3:
=over 4
=item 5.5.1.1 FFC Domain Parameter Selection/Generation
=item Appendix D: FFC Safe-prime Groups
=back
The following sections of FIPS186-4:
=over 4
=item A.1.1.2 Generation of Probable Primes p and q Using an Approved Hash Function.
=item A.2.3 Generation of canonical generator g.
=item A.2.1 Unverifiable Generation of the Generator g.
=back
=head1 SEE ALSO
L<EVP_PKEY-FFC(7)>,
L<EVP_KEYEXCH-DH(7)>
L<EVP_PKEY(3)>,
L<provider-keymgmt(7)>,
L<EVP_KEYMGMT(3)>,
L<OSSL_PROVIDER-default(7)>,
L<OSSL_PROVIDER-FIPS(7)>
=head1 COPYRIGHT
-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
L<https://www.openssl.org/source/license.html>.
=cut
diff --git a/crypto/openssl/doc/man7/ossl_store.pod b/crypto/openssl/doc/man7/ossl_store.pod
index 3152cff10424..d6fdae8f22b0 100644
--- a/crypto/openssl/doc/man7/ossl_store.pod
+++ b/crypto/openssl/doc/man7/ossl_store.pod
@@ -1,87 +1,92 @@
=pod
=head1 NAME
ossl_store - Store retrieval functions
=head1 SYNOPSIS
=for openssl generic
#include <openssl/store.h>
=head1 DESCRIPTION
=head2 General
A STORE is a layer of functionality to retrieve a number of supported
objects from a repository of any kind, addressable as a filename or
as a URI.
The functionality supports the pattern "open a channel to the
repository", "loop and retrieve one object at a time", and "finish up
by closing the channel".
The retrieved objects are returned as a wrapper type B<OSSL_STORE_INFO>,
from which an OpenSSL type can be retrieved.
=head2 URI schemes and loaders
Support for a URI scheme is called a STORE "loader", and can be added
dynamically from the calling application or from a loadable engine.
Support for the 'file' scheme is built into C<libcrypto>.
See L<ossl_store-file(7)> for more information.
=head2 UI_METHOD and pass phrases
The B<OSS_STORE> API does nothing to enforce any specific format or
encoding on the pass phrase that the B<UI_METHOD> provides. However,
the pass phrase is expected to be UTF-8 encoded. The result of any
other encoding is undefined.
=head1 EXAMPLES
=head2 A generic call
- OSSL_STORE_CTX *ctx = OSSL_STORE_open("file:/foo/bar/data.pem");
+ #include <openssl/ui.h> /* for UI_get_default_method */
+ #include <openssl/store.h>
+
+ OSSL_STORE_CTX *ctx = OSSL_STORE_open("file:/foo/bar/data.pem",
+ UI_get_default_method(), NULL, NULL, NULL);
/*
* OSSL_STORE_eof() simulates file semantics for any repository to signal
* that no more data can be expected
*/
while (!OSSL_STORE_eof(ctx)) {
OSSL_STORE_INFO *info = OSSL_STORE_load(ctx);
/*
* Do whatever is necessary with the OSSL_STORE_INFO,
* here just one example
*/
switch (OSSL_STORE_INFO_get_type(info)) {
case OSSL_STORE_INFO_CERT:
/* Print the X.509 certificate text */
X509_print_fp(stdout, OSSL_STORE_INFO_get0_CERT(info));
/* Print the X.509 certificate PEM output */
PEM_write_X509(stdout, OSSL_STORE_INFO_get0_CERT(info));
break;
}
+ OSSL_STORE_INFO_free(info);
}
OSSL_STORE_close(ctx);
=head1 SEE ALSO
L<OSSL_STORE_INFO(3)>, L<OSSL_STORE_LOADER(3)>,
L<OSSL_STORE_open(3)>, L<OSSL_STORE_expect(3)>,
L<OSSL_STORE_SEARCH(3)>
=head1 COPYRIGHT
-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
L<https://www.openssl.org/source/license.html>.
=cut
diff --git a/crypto/openssl/fuzz/bignum.c b/crypto/openssl/fuzz/bignum.c
index d7c3716aacb4..08da6fb197f5 100644
--- a/crypto/openssl/fuzz/bignum.c
+++ b/crypto/openssl/fuzz/bignum.c
@@ -1,109 +1,110 @@
/*
- * Copyright 2016 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.
*/
/*
* Confirm that a^b mod c agrees when calculated cleverly vs naively, for
* random a, b and c.
*/
#include <stdio.h>
#include <openssl/bn.h>
#include <openssl/err.h>
#include "fuzzer.h"
int FuzzerInitialize(int *argc, char ***argv)
{
OPENSSL_init_crypto(OPENSSL_INIT_LOAD_CRYPTO_STRINGS, NULL);
ERR_clear_error();
return 1;
}
int FuzzerTestOneInput(const uint8_t *buf, size_t len)
{
int success = 0;
size_t l1 = 0, l2 = 0, l3 = 0;
int s1 = 0, s3 = 0;
BN_CTX *ctx;
BIGNUM *b1;
BIGNUM *b2;
BIGNUM *b3;
BIGNUM *b4;
BIGNUM *b5;
b1 = BN_new();
b2 = BN_new();
b3 = BN_new();
b4 = BN_new();
b5 = BN_new();
ctx = BN_CTX_new();
/* Divide the input into three parts, using the values of the first two
* bytes to choose lengths, which generate b1, b2 and b3. Use three bits
* of the third byte to choose signs for the three numbers.
*/
if (len > 2) {
len -= 3;
- l1 = (buf[0] * len) / 255;
+ /* limit l1, l2, and l3 to be no more than 512 bytes */
+ l1 = ((buf[0] * len) / 255) % 512;
++buf;
- l2 = (buf[0] * (len - l1)) / 255;
+ l2 = ((buf[0] * (len - l1)) / 255) % 512;
++buf;
- l3 = len - l1 - l2;
+ l3 = (len - l1 - l2) % 512;
s1 = buf[0] & 1;
s3 = buf[0] & 4;
++buf;
}
OPENSSL_assert(BN_bin2bn(buf, l1, b1) == b1);
BN_set_negative(b1, s1);
OPENSSL_assert(BN_bin2bn(buf + l1, l2, b2) == b2);
OPENSSL_assert(BN_bin2bn(buf + l1 + l2, l3, b3) == b3);
BN_set_negative(b3, s3);
/* mod 0 is undefined */
if (BN_is_zero(b3)) {
success = 1;
goto done;
}
OPENSSL_assert(BN_mod_exp(b4, b1, b2, b3, ctx));
OPENSSL_assert(BN_mod_exp_simple(b5, b1, b2, b3, ctx));
success = BN_cmp(b4, b5) == 0;
if (!success) {
BN_print_fp(stdout, b1);
putchar('\n');
BN_print_fp(stdout, b2);
putchar('\n');
BN_print_fp(stdout, b3);
putchar('\n');
BN_print_fp(stdout, b4);
putchar('\n');
BN_print_fp(stdout, b5);
putchar('\n');
}
done:
OPENSSL_assert(success);
BN_free(b1);
BN_free(b2);
BN_free(b3);
BN_free(b4);
BN_free(b5);
BN_CTX_free(ctx);
ERR_clear_error();
return 0;
}
void FuzzerCleanup(void)
{
}
diff --git a/crypto/openssl/include/crypto/aes_platform.h b/crypto/openssl/include/crypto/aes_platform.h
index e95ad5aa5de6..30c968b62c6c 100644
--- a/crypto/openssl/include/crypto/aes_platform.h
+++ b/crypto/openssl/include/crypto/aes_platform.h
@@ -1,450 +1,452 @@
/*
- * 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
*/
#ifndef OSSL_AES_PLATFORM_H
# define OSSL_AES_PLATFORM_H
# pragma once
# include <openssl/aes.h>
# ifdef VPAES_ASM
int vpaes_set_encrypt_key(const unsigned char *userKey, int bits,
AES_KEY *key);
int vpaes_set_decrypt_key(const unsigned char *userKey, int bits,
AES_KEY *key);
void vpaes_encrypt(const unsigned char *in, unsigned char *out,
const AES_KEY *key);
void vpaes_decrypt(const unsigned char *in, unsigned char *out,
const AES_KEY *key);
void vpaes_cbc_encrypt(const unsigned char *in,
unsigned char *out,
size_t length,
const AES_KEY *key, unsigned char *ivec, int enc);
# endif /* VPAES_ASM */
# ifdef BSAES_ASM
void ossl_bsaes_cbc_encrypt(const unsigned char *in, unsigned char *out,
size_t length, const AES_KEY *key,
unsigned char ivec[16], int enc);
void ossl_bsaes_ctr32_encrypt_blocks(const unsigned char *in,
unsigned char *out, size_t len,
const AES_KEY *key,
const unsigned char ivec[16]);
void ossl_bsaes_xts_encrypt(const unsigned char *inp, unsigned char *out,
size_t len, const AES_KEY *key1,
const AES_KEY *key2, const unsigned char iv[16]);
void ossl_bsaes_xts_decrypt(const unsigned char *inp, unsigned char *out,
size_t len, const AES_KEY *key1,
const AES_KEY *key2, const unsigned char iv[16]);
# endif /* BSAES_ASM */
# ifdef AES_CTR_ASM
void AES_ctr32_encrypt(const unsigned char *in, unsigned char *out,
size_t blocks, const AES_KEY *key,
const unsigned char ivec[AES_BLOCK_SIZE]);
# endif /* AES_CTR_ASM */
# ifdef AES_XTS_ASM
void AES_xts_encrypt(const unsigned char *inp, unsigned char *out, size_t len,
const AES_KEY *key1, const AES_KEY *key2,
const unsigned char iv[16]);
void AES_xts_decrypt(const unsigned char *inp, unsigned char *out, size_t len,
const AES_KEY *key1, const AES_KEY *key2,
const unsigned char iv[16]);
# endif /* AES_XTS_ASM */
# if defined(OPENSSL_CPUID_OBJ)
# if (defined(__powerpc__) || defined(__ppc__) || defined(_ARCH_PPC))
# include "crypto/ppc_arch.h"
# ifdef VPAES_ASM
# define VPAES_CAPABLE (OPENSSL_ppccap_P & PPC_ALTIVEC)
# endif
+# if !defined(OPENSSL_SYS_MACOSX)
# define HWAES_CAPABLE (OPENSSL_ppccap_P & PPC_CRYPTO207)
# define HWAES_set_encrypt_key aes_p8_set_encrypt_key
# define HWAES_set_decrypt_key aes_p8_set_decrypt_key
# define HWAES_encrypt aes_p8_encrypt
# define HWAES_decrypt aes_p8_decrypt
# define HWAES_cbc_encrypt aes_p8_cbc_encrypt
# define HWAES_ctr32_encrypt_blocks aes_p8_ctr32_encrypt_blocks
# define HWAES_xts_encrypt aes_p8_xts_encrypt
# define HWAES_xts_decrypt aes_p8_xts_decrypt
+# endif /* OPENSSL_SYS_MACOSX */
# endif /* PPC */
# if (defined(__arm__) || defined(__arm) || defined(__aarch64__))
# include "arm_arch.h"
# if __ARM_MAX_ARCH__>=7
# if defined(BSAES_ASM)
# define BSAES_CAPABLE (OPENSSL_armcap_P & ARMV7_NEON)
# endif
# if defined(VPAES_ASM)
# define VPAES_CAPABLE (OPENSSL_armcap_P & ARMV7_NEON)
# endif
# define HWAES_CAPABLE (OPENSSL_armcap_P & ARMV8_AES)
# define HWAES_set_encrypt_key aes_v8_set_encrypt_key
# define HWAES_set_decrypt_key aes_v8_set_decrypt_key
# define HWAES_encrypt aes_v8_encrypt
# define HWAES_decrypt aes_v8_decrypt
# define HWAES_cbc_encrypt aes_v8_cbc_encrypt
# define HWAES_ecb_encrypt aes_v8_ecb_encrypt
# if __ARM_MAX_ARCH__>=8 && defined(__aarch64__)
# define HWAES_xts_encrypt aes_v8_xts_encrypt
# define HWAES_xts_decrypt aes_v8_xts_decrypt
# endif
# define HWAES_ctr32_encrypt_blocks aes_v8_ctr32_encrypt_blocks
# define AES_PMULL_CAPABLE ((OPENSSL_armcap_P & ARMV8_PMULL) && (OPENSSL_armcap_P & ARMV8_AES))
# define AES_GCM_ENC_BYTES 512
# define AES_GCM_DEC_BYTES 512
# if __ARM_MAX_ARCH__>=8 && defined(__aarch64__)
# define AES_gcm_encrypt armv8_aes_gcm_encrypt
# define AES_gcm_decrypt armv8_aes_gcm_decrypt
# define AES_GCM_ASM(gctx) ((gctx)->ctr==aes_v8_ctr32_encrypt_blocks && \
(gctx)->gcm.ghash==gcm_ghash_v8)
size_t aes_gcm_enc_128_kernel(const uint8_t * plaintext, uint64_t plaintext_length, uint8_t * ciphertext,
uint64_t *Xi, unsigned char ivec[16], const void *key);
size_t aes_gcm_enc_192_kernel(const uint8_t * plaintext, uint64_t plaintext_length, uint8_t * ciphertext,
uint64_t *Xi, unsigned char ivec[16], const void *key);
size_t aes_gcm_enc_256_kernel(const uint8_t * plaintext, uint64_t plaintext_length, uint8_t * ciphertext,
uint64_t *Xi, unsigned char ivec[16], const void *key);
size_t aes_gcm_dec_128_kernel(const uint8_t * ciphertext, uint64_t plaintext_length, uint8_t * plaintext,
uint64_t *Xi, unsigned char ivec[16], const void *key);
size_t aes_gcm_dec_192_kernel(const uint8_t * ciphertext, uint64_t plaintext_length, uint8_t * plaintext,
uint64_t *Xi, unsigned char ivec[16], const void *key);
size_t aes_gcm_dec_256_kernel(const uint8_t * ciphertext, uint64_t plaintext_length, uint8_t * plaintext,
uint64_t *Xi, unsigned char ivec[16], const void *key);
size_t armv8_aes_gcm_encrypt(const unsigned char *in, unsigned char *out, size_t len, const void *key,
unsigned char ivec[16], u64 *Xi);
size_t armv8_aes_gcm_decrypt(const unsigned char *in, unsigned char *out, size_t len, const void *key,
unsigned char ivec[16], u64 *Xi);
void gcm_ghash_v8(u64 Xi[2],const u128 Htable[16],const u8 *inp, size_t len);
# endif
# endif
# endif
# endif /* OPENSSL_CPUID_OBJ */
# if defined(AES_ASM) && ( \
defined(__x86_64) || defined(__x86_64__) || \
defined(_M_AMD64) || defined(_M_X64) )
# define AES_CBC_HMAC_SHA_CAPABLE 1
# define AESNI_CBC_HMAC_SHA_CAPABLE (OPENSSL_ia32cap_P[1]&(1<<(57-32)))
# endif
# if defined(AES_ASM) && !defined(I386_ONLY) && ( \
((defined(__i386) || defined(__i386__) || \
defined(_M_IX86)) && defined(OPENSSL_IA32_SSE2))|| \
defined(__x86_64) || defined(__x86_64__) || \
defined(_M_AMD64) || defined(_M_X64) )
/* AES-NI section */
# define AESNI_CAPABLE (OPENSSL_ia32cap_P[1]&(1<<(57-32)))
# ifdef VPAES_ASM
# define VPAES_CAPABLE (OPENSSL_ia32cap_P[1]&(1<<(41-32)))
# endif
# ifdef BSAES_ASM
# define BSAES_CAPABLE (OPENSSL_ia32cap_P[1]&(1<<(41-32)))
# endif
# define AES_GCM_ENC_BYTES 32
# define AES_GCM_DEC_BYTES 16
int aesni_set_encrypt_key(const unsigned char *userKey, int bits,
AES_KEY *key);
int aesni_set_decrypt_key(const unsigned char *userKey, int bits,
AES_KEY *key);
void aesni_encrypt(const unsigned char *in, unsigned char *out,
const AES_KEY *key);
void aesni_decrypt(const unsigned char *in, unsigned char *out,
const AES_KEY *key);
void aesni_ecb_encrypt(const unsigned char *in,
unsigned char *out,
size_t length, const AES_KEY *key, int enc);
void aesni_cbc_encrypt(const unsigned char *in,
unsigned char *out,
size_t length,
const AES_KEY *key, unsigned char *ivec, int enc);
# ifndef OPENSSL_NO_OCB
void aesni_ocb_encrypt(const unsigned char *in, unsigned char *out,
size_t blocks, const void *key,
size_t start_block_num,
unsigned char offset_i[16],
const unsigned char L_[][16],
unsigned char checksum[16]);
void aesni_ocb_decrypt(const unsigned char *in, unsigned char *out,
size_t blocks, const void *key,
size_t start_block_num,
unsigned char offset_i[16],
const unsigned char L_[][16],
unsigned char checksum[16]);
# endif /* OPENSSL_NO_OCB */
void aesni_ctr32_encrypt_blocks(const unsigned char *in,
unsigned char *out,
size_t blocks,
const void *key, const unsigned char *ivec);
void aesni_xts_encrypt(const unsigned char *in,
unsigned char *out,
size_t length,
const AES_KEY *key1, const AES_KEY *key2,
const unsigned char iv[16]);
void aesni_xts_decrypt(const unsigned char *in,
unsigned char *out,
size_t length,
const AES_KEY *key1, const AES_KEY *key2,
const unsigned char iv[16]);
void aesni_ccm64_encrypt_blocks(const unsigned char *in,
unsigned char *out,
size_t blocks,
const void *key,
const unsigned char ivec[16],
unsigned char cmac[16]);
void aesni_ccm64_decrypt_blocks(const unsigned char *in,
unsigned char *out,
size_t blocks,
const void *key,
const unsigned char ivec[16],
unsigned char cmac[16]);
# if defined(__x86_64) || defined(__x86_64__) || defined(_M_AMD64) || defined(_M_X64)
size_t aesni_gcm_encrypt(const unsigned char *in, unsigned char *out, size_t len,
const void *key, unsigned char ivec[16], u64 *Xi);
size_t aesni_gcm_decrypt(const unsigned char *in, unsigned char *out, size_t len,
const void *key, unsigned char ivec[16], u64 *Xi);
void gcm_ghash_avx(u64 Xi[2], const u128 Htable[16], const u8 *in, size_t len);
# define AES_gcm_encrypt aesni_gcm_encrypt
# define AES_gcm_decrypt aesni_gcm_decrypt
# define AES_GCM_ASM(ctx) (ctx->ctr == aesni_ctr32_encrypt_blocks && \
ctx->gcm.ghash == gcm_ghash_avx)
# endif
# elif defined(AES_ASM) && (defined(__sparc) || defined(__sparc__))
/* Fujitsu SPARC64 X support */
# include "crypto/sparc_arch.h"
# define SPARC_AES_CAPABLE (OPENSSL_sparcv9cap_P[1] & CFR_AES)
# define HWAES_CAPABLE (OPENSSL_sparcv9cap_P[0] & SPARCV9_FJAESX)
# define HWAES_set_encrypt_key aes_fx_set_encrypt_key
# define HWAES_set_decrypt_key aes_fx_set_decrypt_key
# define HWAES_encrypt aes_fx_encrypt
# define HWAES_decrypt aes_fx_decrypt
# define HWAES_cbc_encrypt aes_fx_cbc_encrypt
# define HWAES_ctr32_encrypt_blocks aes_fx_ctr32_encrypt_blocks
void aes_t4_set_encrypt_key(const unsigned char *key, int bits, AES_KEY *ks);
void aes_t4_set_decrypt_key(const unsigned char *key, int bits, AES_KEY *ks);
void aes_t4_encrypt(const unsigned char *in, unsigned char *out,
const AES_KEY *key);
void aes_t4_decrypt(const unsigned char *in, unsigned char *out,
const AES_KEY *key);
/*
* Key-length specific subroutines were chosen for following reason.
* Each SPARC T4 core can execute up to 8 threads which share core's
* resources. Loading as much key material to registers allows to
* minimize references to shared memory interface, as well as amount
* of instructions in inner loops [much needed on T4]. But then having
* non-key-length specific routines would require conditional branches
* either in inner loops or on subroutines' entries. Former is hardly
* acceptable, while latter means code size increase to size occupied
* by multiple key-length specific subroutines, so why fight?
*/
void aes128_t4_cbc_encrypt(const unsigned char *in, unsigned char *out,
size_t len, const AES_KEY *key,
unsigned char *ivec, int /*unused*/);
void aes128_t4_cbc_decrypt(const unsigned char *in, unsigned char *out,
size_t len, const AES_KEY *key,
unsigned char *ivec, int /*unused*/);
void aes192_t4_cbc_encrypt(const unsigned char *in, unsigned char *out,
size_t len, const AES_KEY *key,
unsigned char *ivec, int /*unused*/);
void aes192_t4_cbc_decrypt(const unsigned char *in, unsigned char *out,
size_t len, const AES_KEY *key,
unsigned char *ivec, int /*unused*/);
void aes256_t4_cbc_encrypt(const unsigned char *in, unsigned char *out,
size_t len, const AES_KEY *key,
unsigned char *ivec, int /*unused*/);
void aes256_t4_cbc_decrypt(const unsigned char *in, unsigned char *out,
size_t len, const AES_KEY *key,
unsigned char *ivec, int /*unused*/);
void aes128_t4_ctr32_encrypt(const unsigned char *in, unsigned char *out,
size_t blocks, const AES_KEY *key,
unsigned char *ivec);
void aes192_t4_ctr32_encrypt(const unsigned char *in, unsigned char *out,
size_t blocks, const AES_KEY *key,
unsigned char *ivec);
void aes256_t4_ctr32_encrypt(const unsigned char *in, unsigned char *out,
size_t blocks, const AES_KEY *key,
unsigned char *ivec);
void aes128_t4_xts_encrypt(const unsigned char *in, unsigned char *out,
size_t blocks, const AES_KEY *key1,
const AES_KEY *key2, const unsigned char *ivec);
void aes128_t4_xts_decrypt(const unsigned char *in, unsigned char *out,
size_t blocks, const AES_KEY *key1,
const AES_KEY *key2, const unsigned char *ivec);
void aes256_t4_xts_encrypt(const unsigned char *in, unsigned char *out,
size_t blocks, const AES_KEY *key1,
const AES_KEY *key2, const unsigned char *ivec);
void aes256_t4_xts_decrypt(const unsigned char *in, unsigned char *out,
size_t blocks, const AES_KEY *key1,
const AES_KEY *key2, const unsigned char *ivec);
# elif defined(OPENSSL_CPUID_OBJ) && defined(__s390__)
/* IBM S390X support */
# include "s390x_arch.h"
/* Convert key size to function code: [16,24,32] -> [18,19,20]. */
# define S390X_AES_FC(keylen) (S390X_AES_128 + ((((keylen) << 3) - 128) >> 6))
/* Most modes of operation need km for partial block processing. */
# define S390X_aes_128_CAPABLE (OPENSSL_s390xcap_P.km[0] & \
S390X_CAPBIT(S390X_AES_128))
# define S390X_aes_192_CAPABLE (OPENSSL_s390xcap_P.km[0] & \
S390X_CAPBIT(S390X_AES_192))
# define S390X_aes_256_CAPABLE (OPENSSL_s390xcap_P.km[0] & \
S390X_CAPBIT(S390X_AES_256))
# define S390X_aes_128_cbc_CAPABLE 1 /* checked by callee */
# define S390X_aes_192_cbc_CAPABLE 1
# define S390X_aes_256_cbc_CAPABLE 1
# define S390X_aes_128_ecb_CAPABLE S390X_aes_128_CAPABLE
# define S390X_aes_192_ecb_CAPABLE S390X_aes_192_CAPABLE
# define S390X_aes_256_ecb_CAPABLE S390X_aes_256_CAPABLE
# define S390X_aes_128_ofb_CAPABLE (S390X_aes_128_CAPABLE && \
(OPENSSL_s390xcap_P.kmo[0] & \
S390X_CAPBIT(S390X_AES_128)))
# define S390X_aes_192_ofb_CAPABLE (S390X_aes_192_CAPABLE && \
(OPENSSL_s390xcap_P.kmo[0] & \
S390X_CAPBIT(S390X_AES_192)))
# define S390X_aes_256_ofb_CAPABLE (S390X_aes_256_CAPABLE && \
(OPENSSL_s390xcap_P.kmo[0] & \
S390X_CAPBIT(S390X_AES_256)))
# define S390X_aes_128_cfb_CAPABLE (S390X_aes_128_CAPABLE && \
(OPENSSL_s390xcap_P.kmf[0] & \
S390X_CAPBIT(S390X_AES_128)))
# define S390X_aes_192_cfb_CAPABLE (S390X_aes_192_CAPABLE && \
(OPENSSL_s390xcap_P.kmf[0] & \
S390X_CAPBIT(S390X_AES_192)))
# define S390X_aes_256_cfb_CAPABLE (S390X_aes_256_CAPABLE && \
(OPENSSL_s390xcap_P.kmf[0] & \
S390X_CAPBIT(S390X_AES_256)))
# define S390X_aes_128_cfb8_CAPABLE (OPENSSL_s390xcap_P.kmf[0] & \
S390X_CAPBIT(S390X_AES_128))
# define S390X_aes_192_cfb8_CAPABLE (OPENSSL_s390xcap_P.kmf[0] & \
S390X_CAPBIT(S390X_AES_192))
# define S390X_aes_256_cfb8_CAPABLE (OPENSSL_s390xcap_P.kmf[0] & \
S390X_CAPBIT(S390X_AES_256))
# define S390X_aes_128_cfb1_CAPABLE 0
# define S390X_aes_192_cfb1_CAPABLE 0
# define S390X_aes_256_cfb1_CAPABLE 0
# define S390X_aes_128_ctr_CAPABLE 1 /* checked by callee */
# define S390X_aes_192_ctr_CAPABLE 1
# define S390X_aes_256_ctr_CAPABLE 1
# define S390X_aes_128_xts_CAPABLE 1 /* checked by callee */
# define S390X_aes_256_xts_CAPABLE 1
# define S390X_aes_128_gcm_CAPABLE (S390X_aes_128_CAPABLE && \
(OPENSSL_s390xcap_P.kma[0] & \
S390X_CAPBIT(S390X_AES_128)))
# define S390X_aes_192_gcm_CAPABLE (S390X_aes_192_CAPABLE && \
(OPENSSL_s390xcap_P.kma[0] & \
S390X_CAPBIT(S390X_AES_192)))
# define S390X_aes_256_gcm_CAPABLE (S390X_aes_256_CAPABLE && \
(OPENSSL_s390xcap_P.kma[0] & \
S390X_CAPBIT(S390X_AES_256)))
# define S390X_aes_128_ccm_CAPABLE (S390X_aes_128_CAPABLE && \
(OPENSSL_s390xcap_P.kmac[0] & \
S390X_CAPBIT(S390X_AES_128)))
# define S390X_aes_192_ccm_CAPABLE (S390X_aes_192_CAPABLE && \
(OPENSSL_s390xcap_P.kmac[0] & \
S390X_CAPBIT(S390X_AES_192)))
# define S390X_aes_256_ccm_CAPABLE (S390X_aes_256_CAPABLE && \
(OPENSSL_s390xcap_P.kmac[0] & \
S390X_CAPBIT(S390X_AES_256)))
# define S390X_CCM_AAD_FLAG 0x40
# ifndef OPENSSL_NO_OCB
# define S390X_aes_128_ocb_CAPABLE 0
# define S390X_aes_192_ocb_CAPABLE 0
# define S390X_aes_256_ocb_CAPABLE 0
# endif /* OPENSSL_NO_OCB */
# ifndef OPENSSL_NO_SIV
# define S390X_aes_128_siv_CAPABLE 0
# define S390X_aes_192_siv_CAPABLE 0
# define S390X_aes_256_siv_CAPABLE 0
# endif /* OPENSSL_NO_SIV */
/* Convert key size to function code: [16,24,32] -> [18,19,20]. */
# define S390X_AES_FC(keylen) (S390X_AES_128 + ((((keylen) << 3) - 128) >> 6))
# endif
# if defined(HWAES_CAPABLE)
int HWAES_set_encrypt_key(const unsigned char *userKey, const int bits,
AES_KEY *key);
int HWAES_set_decrypt_key(const unsigned char *userKey, const int bits,
AES_KEY *key);
void HWAES_encrypt(const unsigned char *in, unsigned char *out,
const AES_KEY *key);
void HWAES_decrypt(const unsigned char *in, unsigned char *out,
const AES_KEY *key);
void HWAES_cbc_encrypt(const unsigned char *in, unsigned char *out,
size_t length, const AES_KEY *key,
unsigned char *ivec, const int enc);
void HWAES_ecb_encrypt(const unsigned char *in, unsigned char *out,
size_t length, const AES_KEY *key,
const int enc);
void HWAES_ctr32_encrypt_blocks(const unsigned char *in, unsigned char *out,
size_t len, const void *key,
const unsigned char ivec[16]);
void HWAES_xts_encrypt(const unsigned char *inp, unsigned char *out,
size_t len, const AES_KEY *key1,
const AES_KEY *key2, const unsigned char iv[16]);
void HWAES_xts_decrypt(const unsigned char *inp, unsigned char *out,
size_t len, const AES_KEY *key1,
const AES_KEY *key2, const unsigned char iv[16]);
# ifndef OPENSSL_NO_OCB
# ifdef HWAES_ocb_encrypt
void HWAES_ocb_encrypt(const unsigned char *in, unsigned char *out,
size_t blocks, const void *key,
size_t start_block_num,
unsigned char offset_i[16],
const unsigned char L_[][16],
unsigned char checksum[16]);
# else
# define HWAES_ocb_encrypt ((ocb128_f)NULL)
# endif
# ifdef HWAES_ocb_decrypt
void HWAES_ocb_decrypt(const unsigned char *in, unsigned char *out,
size_t blocks, const void *key,
size_t start_block_num,
unsigned char offset_i[16],
const unsigned char L_[][16],
unsigned char checksum[16]);
# else
# define HWAES_ocb_decrypt ((ocb128_f)NULL)
# endif
# endif /* OPENSSL_NO_OCB */
# endif /* HWAES_CAPABLE */
#endif /* OSSL_AES_PLATFORM_H */
diff --git a/crypto/openssl/include/crypto/bn.h b/crypto/openssl/include/crypto/bn.h
index 4cc23bd146fe..c5f328156d3a 100644
--- a/crypto/openssl/include/crypto/bn.h
+++ b/crypto/openssl/include/crypto/bn.h
@@ -1,125 +1,125 @@
/*
* 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_is_word_fixed_top(const BIGNUM *a, const 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/openssl/tls1.h b/crypto/openssl/include/openssl/tls1.h
index d6e9331fa1e9..91558fa8d1a5 100644
--- a/crypto/openssl/include/openssl/tls1.h
+++ b/crypto/openssl/include/openssl/tls1.h
@@ -1,1223 +1,1225 @@
/*
- * Copyright 1995-2021 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
*/
#ifndef OPENSSL_TLS1_H
# define OPENSSL_TLS1_H
# pragma once
# include <openssl/macros.h>
# ifndef OPENSSL_NO_DEPRECATED_3_0
# define HEADER_TLS1_H
# endif
# include <openssl/buffer.h>
# include <openssl/x509.h>
# include <openssl/prov_ssl.h>
#ifdef __cplusplus
extern "C" {
#endif
/* Default security level if not overridden at config time */
# ifndef OPENSSL_TLS_SECURITY_LEVEL
# define OPENSSL_TLS_SECURITY_LEVEL 1
# endif
/* TLS*_VERSION constants are defined in prov_ssl.h */
# ifndef OPENSSL_NO_DEPRECATED_3_0
# define TLS_MAX_VERSION TLS1_3_VERSION
# endif
/* Special value for method supporting multiple versions */
# define TLS_ANY_VERSION 0x10000
# define TLS1_VERSION_MAJOR 0x03
# define TLS1_VERSION_MINOR 0x01
# define TLS1_1_VERSION_MAJOR 0x03
# define TLS1_1_VERSION_MINOR 0x02
# define TLS1_2_VERSION_MAJOR 0x03
# define TLS1_2_VERSION_MINOR 0x03
# define TLS1_get_version(s) \
((SSL_version(s) >> 8) == TLS1_VERSION_MAJOR ? SSL_version(s) : 0)
# define TLS1_get_client_version(s) \
((SSL_client_version(s) >> 8) == TLS1_VERSION_MAJOR ? SSL_client_version(s) : 0)
# define TLS1_AD_DECRYPTION_FAILED 21
# define TLS1_AD_RECORD_OVERFLOW 22
# define TLS1_AD_UNKNOWN_CA 48/* fatal */
# define TLS1_AD_ACCESS_DENIED 49/* fatal */
# define TLS1_AD_DECODE_ERROR 50/* fatal */
# define TLS1_AD_DECRYPT_ERROR 51
# define TLS1_AD_EXPORT_RESTRICTION 60/* fatal */
# define TLS1_AD_PROTOCOL_VERSION 70/* fatal */
# define TLS1_AD_INSUFFICIENT_SECURITY 71/* fatal */
# define TLS1_AD_INTERNAL_ERROR 80/* fatal */
# define TLS1_AD_INAPPROPRIATE_FALLBACK 86/* fatal */
# define TLS1_AD_USER_CANCELLED 90
# define TLS1_AD_NO_RENEGOTIATION 100
/* TLSv1.3 alerts */
# define TLS13_AD_MISSING_EXTENSION 109 /* fatal */
# define TLS13_AD_CERTIFICATE_REQUIRED 116 /* fatal */
/* codes 110-114 are from RFC3546 */
# define TLS1_AD_UNSUPPORTED_EXTENSION 110
# define TLS1_AD_CERTIFICATE_UNOBTAINABLE 111
# define TLS1_AD_UNRECOGNIZED_NAME 112
# define TLS1_AD_BAD_CERTIFICATE_STATUS_RESPONSE 113
# define TLS1_AD_BAD_CERTIFICATE_HASH_VALUE 114
# define TLS1_AD_UNKNOWN_PSK_IDENTITY 115/* fatal */
# define TLS1_AD_NO_APPLICATION_PROTOCOL 120 /* fatal */
/* ExtensionType values from RFC3546 / RFC4366 / RFC6066 */
# define TLSEXT_TYPE_server_name 0
# define TLSEXT_TYPE_max_fragment_length 1
# define TLSEXT_TYPE_client_certificate_url 2
# define TLSEXT_TYPE_trusted_ca_keys 3
# define TLSEXT_TYPE_truncated_hmac 4
# define TLSEXT_TYPE_status_request 5
/* ExtensionType values from RFC4681 */
# define TLSEXT_TYPE_user_mapping 6
/* ExtensionType values from RFC5878 */
# define TLSEXT_TYPE_client_authz 7
# define TLSEXT_TYPE_server_authz 8
/* ExtensionType values from RFC6091 */
# define TLSEXT_TYPE_cert_type 9
/* ExtensionType values from RFC4492 */
/*
* Prior to TLSv1.3 the supported_groups extension was known as
* elliptic_curves
*/
# define TLSEXT_TYPE_supported_groups 10
# define TLSEXT_TYPE_elliptic_curves TLSEXT_TYPE_supported_groups
# define TLSEXT_TYPE_ec_point_formats 11
/* ExtensionType value from RFC5054 */
# define TLSEXT_TYPE_srp 12
/* ExtensionType values from RFC5246 */
# define TLSEXT_TYPE_signature_algorithms 13
/* ExtensionType value from RFC5764 */
# define TLSEXT_TYPE_use_srtp 14
/* ExtensionType value from RFC7301 */
# define TLSEXT_TYPE_application_layer_protocol_negotiation 16
/*
* Extension type for Certificate Transparency
* https://tools.ietf.org/html/rfc6962#section-3.3.1
*/
# define TLSEXT_TYPE_signed_certificate_timestamp 18
/*
* ExtensionType value for TLS padding extension.
* http://tools.ietf.org/html/draft-agl-tls-padding
*/
# define TLSEXT_TYPE_padding 21
/* ExtensionType value from RFC7366 */
# define TLSEXT_TYPE_encrypt_then_mac 22
/* ExtensionType value from RFC7627 */
# define TLSEXT_TYPE_extended_master_secret 23
/* ExtensionType value from RFC4507 */
# define TLSEXT_TYPE_session_ticket 35
/* As defined for TLS1.3 */
# define TLSEXT_TYPE_psk 41
# define TLSEXT_TYPE_early_data 42
# define TLSEXT_TYPE_supported_versions 43
# define TLSEXT_TYPE_cookie 44
# define TLSEXT_TYPE_psk_kex_modes 45
# define TLSEXT_TYPE_certificate_authorities 47
# define TLSEXT_TYPE_post_handshake_auth 49
# define TLSEXT_TYPE_signature_algorithms_cert 50
# define TLSEXT_TYPE_key_share 51
/* Temporary extension type */
# define TLSEXT_TYPE_renegotiate 0xff01
# ifndef OPENSSL_NO_NEXTPROTONEG
/* This is not an IANA defined extension number */
# define TLSEXT_TYPE_next_proto_neg 13172
# endif
/* NameType value from RFC3546 */
# define TLSEXT_NAMETYPE_host_name 0
/* status request value from RFC3546 */
# define TLSEXT_STATUSTYPE_ocsp 1
/* ECPointFormat values from RFC4492 */
# define TLSEXT_ECPOINTFORMAT_first 0
# define TLSEXT_ECPOINTFORMAT_uncompressed 0
# define TLSEXT_ECPOINTFORMAT_ansiX962_compressed_prime 1
# define TLSEXT_ECPOINTFORMAT_ansiX962_compressed_char2 2
# define TLSEXT_ECPOINTFORMAT_last 2
/* Signature and hash algorithms from RFC5246 */
# define TLSEXT_signature_anonymous 0
# define TLSEXT_signature_rsa 1
# define TLSEXT_signature_dsa 2
# define TLSEXT_signature_ecdsa 3
# define TLSEXT_signature_gostr34102001 237
# define TLSEXT_signature_gostr34102012_256 238
# define TLSEXT_signature_gostr34102012_512 239
/* Total number of different signature algorithms */
# define TLSEXT_signature_num 7
# define TLSEXT_hash_none 0
# define TLSEXT_hash_md5 1
# define TLSEXT_hash_sha1 2
# define TLSEXT_hash_sha224 3
# define TLSEXT_hash_sha256 4
# define TLSEXT_hash_sha384 5
# define TLSEXT_hash_sha512 6
# define TLSEXT_hash_gostr3411 237
# define TLSEXT_hash_gostr34112012_256 238
# define TLSEXT_hash_gostr34112012_512 239
/* Total number of different digest algorithms */
# define TLSEXT_hash_num 10
/* Flag set for unrecognised algorithms */
# define TLSEXT_nid_unknown 0x1000000
/* ECC curves */
# define TLSEXT_curve_P_256 23
# define TLSEXT_curve_P_384 24
/* OpenSSL value to disable maximum fragment length extension */
# define TLSEXT_max_fragment_length_DISABLED 0
/* Allowed values for max fragment length extension */
# define TLSEXT_max_fragment_length_512 1
# define TLSEXT_max_fragment_length_1024 2
# define TLSEXT_max_fragment_length_2048 3
# define TLSEXT_max_fragment_length_4096 4
+/* OpenSSL value for unset maximum fragment length extension */
+# define TLSEXT_max_fragment_length_UNSPECIFIED 255
int SSL_CTX_set_tlsext_max_fragment_length(SSL_CTX *ctx, uint8_t mode);
int SSL_set_tlsext_max_fragment_length(SSL *ssl, uint8_t mode);
# define TLSEXT_MAXLEN_host_name 255
__owur const char *SSL_get_servername(const SSL *s, const int type);
__owur int SSL_get_servername_type(const SSL *s);
/*
* SSL_export_keying_material exports a value derived from the master secret,
* as specified in RFC 5705. It writes |olen| bytes to |out| given a label and
* optional context. (Since a zero length context is allowed, the |use_context|
* flag controls whether a context is included.) It returns 1 on success and
* 0 or -1 otherwise.
*/
__owur 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);
/*
* SSL_export_keying_material_early exports a value derived from the
* early exporter master secret, as specified in
* https://tools.ietf.org/html/draft-ietf-tls-tls13-23. It writes
* |olen| bytes to |out| given a label and optional context. It
* returns 1 on success and 0 otherwise.
*/
__owur 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);
int SSL_get_peer_signature_type_nid(const SSL *s, int *pnid);
int SSL_get_signature_type_nid(const SSL *s, int *pnid);
int SSL_get_sigalgs(SSL *s, int idx,
int *psign, int *phash, int *psignandhash,
unsigned char *rsig, unsigned char *rhash);
int SSL_get_shared_sigalgs(SSL *s, int idx,
int *psign, int *phash, int *psignandhash,
unsigned char *rsig, unsigned char *rhash);
__owur int SSL_check_chain(SSL *s, X509 *x, EVP_PKEY *pk, STACK_OF(X509) *chain);
# define SSL_set_tlsext_host_name(s,name) \
SSL_ctrl(s,SSL_CTRL_SET_TLSEXT_HOSTNAME,TLSEXT_NAMETYPE_host_name,\
(void *)name)
# define SSL_set_tlsext_debug_callback(ssl, cb) \
SSL_callback_ctrl(ssl,SSL_CTRL_SET_TLSEXT_DEBUG_CB,\
(void (*)(void))cb)
# define SSL_set_tlsext_debug_arg(ssl, arg) \
SSL_ctrl(ssl,SSL_CTRL_SET_TLSEXT_DEBUG_ARG,0,arg)
# define SSL_get_tlsext_status_type(ssl) \
SSL_ctrl(ssl,SSL_CTRL_GET_TLSEXT_STATUS_REQ_TYPE,0,NULL)
# define SSL_set_tlsext_status_type(ssl, type) \
SSL_ctrl(ssl,SSL_CTRL_SET_TLSEXT_STATUS_REQ_TYPE,type,NULL)
# define SSL_get_tlsext_status_exts(ssl, arg) \
SSL_ctrl(ssl,SSL_CTRL_GET_TLSEXT_STATUS_REQ_EXTS,0,arg)
# define SSL_set_tlsext_status_exts(ssl, arg) \
SSL_ctrl(ssl,SSL_CTRL_SET_TLSEXT_STATUS_REQ_EXTS,0,arg)
# define SSL_get_tlsext_status_ids(ssl, arg) \
SSL_ctrl(ssl,SSL_CTRL_GET_TLSEXT_STATUS_REQ_IDS,0,arg)
# define SSL_set_tlsext_status_ids(ssl, arg) \
SSL_ctrl(ssl,SSL_CTRL_SET_TLSEXT_STATUS_REQ_IDS,0,arg)
# define SSL_get_tlsext_status_ocsp_resp(ssl, arg) \
SSL_ctrl(ssl,SSL_CTRL_GET_TLSEXT_STATUS_REQ_OCSP_RESP,0,arg)
# define SSL_set_tlsext_status_ocsp_resp(ssl, arg, arglen) \
SSL_ctrl(ssl,SSL_CTRL_SET_TLSEXT_STATUS_REQ_OCSP_RESP,arglen,arg)
# define SSL_CTX_set_tlsext_servername_callback(ctx, cb) \
SSL_CTX_callback_ctrl(ctx,SSL_CTRL_SET_TLSEXT_SERVERNAME_CB,\
(void (*)(void))cb)
# define SSL_TLSEXT_ERR_OK 0
# define SSL_TLSEXT_ERR_ALERT_WARNING 1
# define SSL_TLSEXT_ERR_ALERT_FATAL 2
# define SSL_TLSEXT_ERR_NOACK 3
# define SSL_CTX_set_tlsext_servername_arg(ctx, arg) \
SSL_CTX_ctrl(ctx,SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG,0,arg)
# define SSL_CTX_get_tlsext_ticket_keys(ctx, keys, keylen) \
SSL_CTX_ctrl(ctx,SSL_CTRL_GET_TLSEXT_TICKET_KEYS,keylen,keys)
# define SSL_CTX_set_tlsext_ticket_keys(ctx, keys, keylen) \
SSL_CTX_ctrl(ctx,SSL_CTRL_SET_TLSEXT_TICKET_KEYS,keylen,keys)
# define SSL_CTX_get_tlsext_status_cb(ssl, cb) \
SSL_CTX_ctrl(ssl,SSL_CTRL_GET_TLSEXT_STATUS_REQ_CB,0,(void *)cb)
# define SSL_CTX_set_tlsext_status_cb(ssl, cb) \
SSL_CTX_callback_ctrl(ssl,SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB,\
(void (*)(void))cb)
# define SSL_CTX_get_tlsext_status_arg(ssl, arg) \
SSL_CTX_ctrl(ssl,SSL_CTRL_GET_TLSEXT_STATUS_REQ_CB_ARG,0,arg)
# define SSL_CTX_set_tlsext_status_arg(ssl, arg) \
SSL_CTX_ctrl(ssl,SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB_ARG,0,arg)
# define SSL_CTX_set_tlsext_status_type(ssl, type) \
SSL_CTX_ctrl(ssl,SSL_CTRL_SET_TLSEXT_STATUS_REQ_TYPE,type,NULL)
# define SSL_CTX_get_tlsext_status_type(ssl) \
SSL_CTX_ctrl(ssl,SSL_CTRL_GET_TLSEXT_STATUS_REQ_TYPE,0,NULL)
# ifndef OPENSSL_NO_DEPRECATED_3_0
# define SSL_CTX_set_tlsext_ticket_key_cb(ssl, cb) \
SSL_CTX_callback_ctrl(ssl,SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB,\
(void (*)(void))cb)
# endif
int SSL_CTX_set_tlsext_ticket_key_evp_cb
(SSL_CTX *ctx, int (*fp)(SSL *, unsigned char *, unsigned char *,
EVP_CIPHER_CTX *, EVP_MAC_CTX *, int));
/* PSK ciphersuites from 4279 */
# define TLS1_CK_PSK_WITH_RC4_128_SHA 0x0300008A
# define TLS1_CK_PSK_WITH_3DES_EDE_CBC_SHA 0x0300008B
# define TLS1_CK_PSK_WITH_AES_128_CBC_SHA 0x0300008C
# define TLS1_CK_PSK_WITH_AES_256_CBC_SHA 0x0300008D
# define TLS1_CK_DHE_PSK_WITH_RC4_128_SHA 0x0300008E
# define TLS1_CK_DHE_PSK_WITH_3DES_EDE_CBC_SHA 0x0300008F
# define TLS1_CK_DHE_PSK_WITH_AES_128_CBC_SHA 0x03000090
# define TLS1_CK_DHE_PSK_WITH_AES_256_CBC_SHA 0x03000091
# define TLS1_CK_RSA_PSK_WITH_RC4_128_SHA 0x03000092
# define TLS1_CK_RSA_PSK_WITH_3DES_EDE_CBC_SHA 0x03000093
# define TLS1_CK_RSA_PSK_WITH_AES_128_CBC_SHA 0x03000094
# define TLS1_CK_RSA_PSK_WITH_AES_256_CBC_SHA 0x03000095
/* PSK ciphersuites from 5487 */
# define TLS1_CK_PSK_WITH_AES_128_GCM_SHA256 0x030000A8
# define TLS1_CK_PSK_WITH_AES_256_GCM_SHA384 0x030000A9
# define TLS1_CK_DHE_PSK_WITH_AES_128_GCM_SHA256 0x030000AA
# define TLS1_CK_DHE_PSK_WITH_AES_256_GCM_SHA384 0x030000AB
# define TLS1_CK_RSA_PSK_WITH_AES_128_GCM_SHA256 0x030000AC
# define TLS1_CK_RSA_PSK_WITH_AES_256_GCM_SHA384 0x030000AD
# define TLS1_CK_PSK_WITH_AES_128_CBC_SHA256 0x030000AE
# define TLS1_CK_PSK_WITH_AES_256_CBC_SHA384 0x030000AF
# define TLS1_CK_PSK_WITH_NULL_SHA256 0x030000B0
# define TLS1_CK_PSK_WITH_NULL_SHA384 0x030000B1
# define TLS1_CK_DHE_PSK_WITH_AES_128_CBC_SHA256 0x030000B2
# define TLS1_CK_DHE_PSK_WITH_AES_256_CBC_SHA384 0x030000B3
# define TLS1_CK_DHE_PSK_WITH_NULL_SHA256 0x030000B4
# define TLS1_CK_DHE_PSK_WITH_NULL_SHA384 0x030000B5
# define TLS1_CK_RSA_PSK_WITH_AES_128_CBC_SHA256 0x030000B6
# define TLS1_CK_RSA_PSK_WITH_AES_256_CBC_SHA384 0x030000B7
# define TLS1_CK_RSA_PSK_WITH_NULL_SHA256 0x030000B8
# define TLS1_CK_RSA_PSK_WITH_NULL_SHA384 0x030000B9
/* NULL PSK ciphersuites from RFC4785 */
# define TLS1_CK_PSK_WITH_NULL_SHA 0x0300002C
# define TLS1_CK_DHE_PSK_WITH_NULL_SHA 0x0300002D
# define TLS1_CK_RSA_PSK_WITH_NULL_SHA 0x0300002E
/* AES ciphersuites from RFC3268 */
# define TLS1_CK_RSA_WITH_AES_128_SHA 0x0300002F
# define TLS1_CK_DH_DSS_WITH_AES_128_SHA 0x03000030
# define TLS1_CK_DH_RSA_WITH_AES_128_SHA 0x03000031
# define TLS1_CK_DHE_DSS_WITH_AES_128_SHA 0x03000032
# define TLS1_CK_DHE_RSA_WITH_AES_128_SHA 0x03000033
# define TLS1_CK_ADH_WITH_AES_128_SHA 0x03000034
# define TLS1_CK_RSA_WITH_AES_256_SHA 0x03000035
# define TLS1_CK_DH_DSS_WITH_AES_256_SHA 0x03000036
# define TLS1_CK_DH_RSA_WITH_AES_256_SHA 0x03000037
# define TLS1_CK_DHE_DSS_WITH_AES_256_SHA 0x03000038
# define TLS1_CK_DHE_RSA_WITH_AES_256_SHA 0x03000039
# define TLS1_CK_ADH_WITH_AES_256_SHA 0x0300003A
/* TLS v1.2 ciphersuites */
# define TLS1_CK_RSA_WITH_NULL_SHA256 0x0300003B
# define TLS1_CK_RSA_WITH_AES_128_SHA256 0x0300003C
# define TLS1_CK_RSA_WITH_AES_256_SHA256 0x0300003D
# define TLS1_CK_DH_DSS_WITH_AES_128_SHA256 0x0300003E
# define TLS1_CK_DH_RSA_WITH_AES_128_SHA256 0x0300003F
# define TLS1_CK_DHE_DSS_WITH_AES_128_SHA256 0x03000040
/* Camellia ciphersuites from RFC4132 */
# define TLS1_CK_RSA_WITH_CAMELLIA_128_CBC_SHA 0x03000041
# define TLS1_CK_DH_DSS_WITH_CAMELLIA_128_CBC_SHA 0x03000042
# define TLS1_CK_DH_RSA_WITH_CAMELLIA_128_CBC_SHA 0x03000043
# define TLS1_CK_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA 0x03000044
# define TLS1_CK_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA 0x03000045
# define TLS1_CK_ADH_WITH_CAMELLIA_128_CBC_SHA 0x03000046
/* TLS v1.2 ciphersuites */
# define TLS1_CK_DHE_RSA_WITH_AES_128_SHA256 0x03000067
# define TLS1_CK_DH_DSS_WITH_AES_256_SHA256 0x03000068
# define TLS1_CK_DH_RSA_WITH_AES_256_SHA256 0x03000069
# define TLS1_CK_DHE_DSS_WITH_AES_256_SHA256 0x0300006A
# define TLS1_CK_DHE_RSA_WITH_AES_256_SHA256 0x0300006B
# define TLS1_CK_ADH_WITH_AES_128_SHA256 0x0300006C
# define TLS1_CK_ADH_WITH_AES_256_SHA256 0x0300006D
/* Camellia ciphersuites from RFC4132 */
# define TLS1_CK_RSA_WITH_CAMELLIA_256_CBC_SHA 0x03000084
# define TLS1_CK_DH_DSS_WITH_CAMELLIA_256_CBC_SHA 0x03000085
# define TLS1_CK_DH_RSA_WITH_CAMELLIA_256_CBC_SHA 0x03000086
# define TLS1_CK_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA 0x03000087
# define TLS1_CK_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA 0x03000088
# define TLS1_CK_ADH_WITH_CAMELLIA_256_CBC_SHA 0x03000089
/* SEED ciphersuites from RFC4162 */
# define TLS1_CK_RSA_WITH_SEED_SHA 0x03000096
# define TLS1_CK_DH_DSS_WITH_SEED_SHA 0x03000097
# define TLS1_CK_DH_RSA_WITH_SEED_SHA 0x03000098
# define TLS1_CK_DHE_DSS_WITH_SEED_SHA 0x03000099
# define TLS1_CK_DHE_RSA_WITH_SEED_SHA 0x0300009A
# define TLS1_CK_ADH_WITH_SEED_SHA 0x0300009B
/* TLS v1.2 GCM ciphersuites from RFC5288 */
# define TLS1_CK_RSA_WITH_AES_128_GCM_SHA256 0x0300009C
# define TLS1_CK_RSA_WITH_AES_256_GCM_SHA384 0x0300009D
# define TLS1_CK_DHE_RSA_WITH_AES_128_GCM_SHA256 0x0300009E
# define TLS1_CK_DHE_RSA_WITH_AES_256_GCM_SHA384 0x0300009F
# define TLS1_CK_DH_RSA_WITH_AES_128_GCM_SHA256 0x030000A0
# define TLS1_CK_DH_RSA_WITH_AES_256_GCM_SHA384 0x030000A1
# define TLS1_CK_DHE_DSS_WITH_AES_128_GCM_SHA256 0x030000A2
# define TLS1_CK_DHE_DSS_WITH_AES_256_GCM_SHA384 0x030000A3
# define TLS1_CK_DH_DSS_WITH_AES_128_GCM_SHA256 0x030000A4
# define TLS1_CK_DH_DSS_WITH_AES_256_GCM_SHA384 0x030000A5
# define TLS1_CK_ADH_WITH_AES_128_GCM_SHA256 0x030000A6
# define TLS1_CK_ADH_WITH_AES_256_GCM_SHA384 0x030000A7
/* CCM ciphersuites from RFC6655 */
# define TLS1_CK_RSA_WITH_AES_128_CCM 0x0300C09C
# define TLS1_CK_RSA_WITH_AES_256_CCM 0x0300C09D
# define TLS1_CK_DHE_RSA_WITH_AES_128_CCM 0x0300C09E
# define TLS1_CK_DHE_RSA_WITH_AES_256_CCM 0x0300C09F
# define TLS1_CK_RSA_WITH_AES_128_CCM_8 0x0300C0A0
# define TLS1_CK_RSA_WITH_AES_256_CCM_8 0x0300C0A1
# define TLS1_CK_DHE_RSA_WITH_AES_128_CCM_8 0x0300C0A2
# define TLS1_CK_DHE_RSA_WITH_AES_256_CCM_8 0x0300C0A3
# define TLS1_CK_PSK_WITH_AES_128_CCM 0x0300C0A4
# define TLS1_CK_PSK_WITH_AES_256_CCM 0x0300C0A5
# define TLS1_CK_DHE_PSK_WITH_AES_128_CCM 0x0300C0A6
# define TLS1_CK_DHE_PSK_WITH_AES_256_CCM 0x0300C0A7
# define TLS1_CK_PSK_WITH_AES_128_CCM_8 0x0300C0A8
# define TLS1_CK_PSK_WITH_AES_256_CCM_8 0x0300C0A9
# define TLS1_CK_DHE_PSK_WITH_AES_128_CCM_8 0x0300C0AA
# define TLS1_CK_DHE_PSK_WITH_AES_256_CCM_8 0x0300C0AB
/* CCM ciphersuites from RFC7251 */
# define TLS1_CK_ECDHE_ECDSA_WITH_AES_128_CCM 0x0300C0AC
# define TLS1_CK_ECDHE_ECDSA_WITH_AES_256_CCM 0x0300C0AD
# define TLS1_CK_ECDHE_ECDSA_WITH_AES_128_CCM_8 0x0300C0AE
# define TLS1_CK_ECDHE_ECDSA_WITH_AES_256_CCM_8 0x0300C0AF
/* TLS 1.2 Camellia SHA-256 ciphersuites from RFC5932 */
# define TLS1_CK_RSA_WITH_CAMELLIA_128_CBC_SHA256 0x030000BA
# define TLS1_CK_DH_DSS_WITH_CAMELLIA_128_CBC_SHA256 0x030000BB
# define TLS1_CK_DH_RSA_WITH_CAMELLIA_128_CBC_SHA256 0x030000BC
# define TLS1_CK_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA256 0x030000BD
# define TLS1_CK_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256 0x030000BE
# define TLS1_CK_ADH_WITH_CAMELLIA_128_CBC_SHA256 0x030000BF
# define TLS1_CK_RSA_WITH_CAMELLIA_256_CBC_SHA256 0x030000C0
# define TLS1_CK_DH_DSS_WITH_CAMELLIA_256_CBC_SHA256 0x030000C1
# define TLS1_CK_DH_RSA_WITH_CAMELLIA_256_CBC_SHA256 0x030000C2
# define TLS1_CK_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA256 0x030000C3
# define TLS1_CK_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256 0x030000C4
# define TLS1_CK_ADH_WITH_CAMELLIA_256_CBC_SHA256 0x030000C5
/* ECC ciphersuites from RFC4492 */
# define TLS1_CK_ECDH_ECDSA_WITH_NULL_SHA 0x0300C001
# define TLS1_CK_ECDH_ECDSA_WITH_RC4_128_SHA 0x0300C002
# define TLS1_CK_ECDH_ECDSA_WITH_DES_192_CBC3_SHA 0x0300C003
# define TLS1_CK_ECDH_ECDSA_WITH_AES_128_CBC_SHA 0x0300C004
# define TLS1_CK_ECDH_ECDSA_WITH_AES_256_CBC_SHA 0x0300C005
# define TLS1_CK_ECDHE_ECDSA_WITH_NULL_SHA 0x0300C006
# define TLS1_CK_ECDHE_ECDSA_WITH_RC4_128_SHA 0x0300C007
# define TLS1_CK_ECDHE_ECDSA_WITH_DES_192_CBC3_SHA 0x0300C008
# define TLS1_CK_ECDHE_ECDSA_WITH_AES_128_CBC_SHA 0x0300C009
# define TLS1_CK_ECDHE_ECDSA_WITH_AES_256_CBC_SHA 0x0300C00A
# define TLS1_CK_ECDH_RSA_WITH_NULL_SHA 0x0300C00B
# define TLS1_CK_ECDH_RSA_WITH_RC4_128_SHA 0x0300C00C
# define TLS1_CK_ECDH_RSA_WITH_DES_192_CBC3_SHA 0x0300C00D
# define TLS1_CK_ECDH_RSA_WITH_AES_128_CBC_SHA 0x0300C00E
# define TLS1_CK_ECDH_RSA_WITH_AES_256_CBC_SHA 0x0300C00F
# define TLS1_CK_ECDHE_RSA_WITH_NULL_SHA 0x0300C010
# define TLS1_CK_ECDHE_RSA_WITH_RC4_128_SHA 0x0300C011
# define TLS1_CK_ECDHE_RSA_WITH_DES_192_CBC3_SHA 0x0300C012
# define TLS1_CK_ECDHE_RSA_WITH_AES_128_CBC_SHA 0x0300C013
# define TLS1_CK_ECDHE_RSA_WITH_AES_256_CBC_SHA 0x0300C014
# define TLS1_CK_ECDH_anon_WITH_NULL_SHA 0x0300C015
# define TLS1_CK_ECDH_anon_WITH_RC4_128_SHA 0x0300C016
# define TLS1_CK_ECDH_anon_WITH_DES_192_CBC3_SHA 0x0300C017
# define TLS1_CK_ECDH_anon_WITH_AES_128_CBC_SHA 0x0300C018
# define TLS1_CK_ECDH_anon_WITH_AES_256_CBC_SHA 0x0300C019
/* SRP ciphersuites from RFC 5054 */
# define TLS1_CK_SRP_SHA_WITH_3DES_EDE_CBC_SHA 0x0300C01A
# define TLS1_CK_SRP_SHA_RSA_WITH_3DES_EDE_CBC_SHA 0x0300C01B
# define TLS1_CK_SRP_SHA_DSS_WITH_3DES_EDE_CBC_SHA 0x0300C01C
# define TLS1_CK_SRP_SHA_WITH_AES_128_CBC_SHA 0x0300C01D
# define TLS1_CK_SRP_SHA_RSA_WITH_AES_128_CBC_SHA 0x0300C01E
# define TLS1_CK_SRP_SHA_DSS_WITH_AES_128_CBC_SHA 0x0300C01F
# define TLS1_CK_SRP_SHA_WITH_AES_256_CBC_SHA 0x0300C020
# define TLS1_CK_SRP_SHA_RSA_WITH_AES_256_CBC_SHA 0x0300C021
# define TLS1_CK_SRP_SHA_DSS_WITH_AES_256_CBC_SHA 0x0300C022
/* ECDH HMAC based ciphersuites from RFC5289 */
# define TLS1_CK_ECDHE_ECDSA_WITH_AES_128_SHA256 0x0300C023
# define TLS1_CK_ECDHE_ECDSA_WITH_AES_256_SHA384 0x0300C024
# define TLS1_CK_ECDH_ECDSA_WITH_AES_128_SHA256 0x0300C025
# define TLS1_CK_ECDH_ECDSA_WITH_AES_256_SHA384 0x0300C026
# define TLS1_CK_ECDHE_RSA_WITH_AES_128_SHA256 0x0300C027
# define TLS1_CK_ECDHE_RSA_WITH_AES_256_SHA384 0x0300C028
# define TLS1_CK_ECDH_RSA_WITH_AES_128_SHA256 0x0300C029
# define TLS1_CK_ECDH_RSA_WITH_AES_256_SHA384 0x0300C02A
/* ECDH GCM based ciphersuites from RFC5289 */
# define TLS1_CK_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 0x0300C02B
# define TLS1_CK_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 0x0300C02C
# define TLS1_CK_ECDH_ECDSA_WITH_AES_128_GCM_SHA256 0x0300C02D
# define TLS1_CK_ECDH_ECDSA_WITH_AES_256_GCM_SHA384 0x0300C02E
# define TLS1_CK_ECDHE_RSA_WITH_AES_128_GCM_SHA256 0x0300C02F
# define TLS1_CK_ECDHE_RSA_WITH_AES_256_GCM_SHA384 0x0300C030
# define TLS1_CK_ECDH_RSA_WITH_AES_128_GCM_SHA256 0x0300C031
# define TLS1_CK_ECDH_RSA_WITH_AES_256_GCM_SHA384 0x0300C032
/* ECDHE PSK ciphersuites from RFC5489 */
# define TLS1_CK_ECDHE_PSK_WITH_RC4_128_SHA 0x0300C033
# define TLS1_CK_ECDHE_PSK_WITH_3DES_EDE_CBC_SHA 0x0300C034
# define TLS1_CK_ECDHE_PSK_WITH_AES_128_CBC_SHA 0x0300C035
# define TLS1_CK_ECDHE_PSK_WITH_AES_256_CBC_SHA 0x0300C036
# define TLS1_CK_ECDHE_PSK_WITH_AES_128_CBC_SHA256 0x0300C037
# define TLS1_CK_ECDHE_PSK_WITH_AES_256_CBC_SHA384 0x0300C038
/* NULL PSK ciphersuites from RFC4785 */
# define TLS1_CK_ECDHE_PSK_WITH_NULL_SHA 0x0300C039
# define TLS1_CK_ECDHE_PSK_WITH_NULL_SHA256 0x0300C03A
# define TLS1_CK_ECDHE_PSK_WITH_NULL_SHA384 0x0300C03B
/* Camellia-CBC ciphersuites from RFC6367 */
# define TLS1_CK_ECDHE_ECDSA_WITH_CAMELLIA_128_CBC_SHA256 0x0300C072
# define TLS1_CK_ECDHE_ECDSA_WITH_CAMELLIA_256_CBC_SHA384 0x0300C073
# define TLS1_CK_ECDH_ECDSA_WITH_CAMELLIA_128_CBC_SHA256 0x0300C074
# define TLS1_CK_ECDH_ECDSA_WITH_CAMELLIA_256_CBC_SHA384 0x0300C075
# define TLS1_CK_ECDHE_RSA_WITH_CAMELLIA_128_CBC_SHA256 0x0300C076
# define TLS1_CK_ECDHE_RSA_WITH_CAMELLIA_256_CBC_SHA384 0x0300C077
# define TLS1_CK_ECDH_RSA_WITH_CAMELLIA_128_CBC_SHA256 0x0300C078
# define TLS1_CK_ECDH_RSA_WITH_CAMELLIA_256_CBC_SHA384 0x0300C079
# define TLS1_CK_PSK_WITH_CAMELLIA_128_CBC_SHA256 0x0300C094
# define TLS1_CK_PSK_WITH_CAMELLIA_256_CBC_SHA384 0x0300C095
# define TLS1_CK_DHE_PSK_WITH_CAMELLIA_128_CBC_SHA256 0x0300C096
# define TLS1_CK_DHE_PSK_WITH_CAMELLIA_256_CBC_SHA384 0x0300C097
# define TLS1_CK_RSA_PSK_WITH_CAMELLIA_128_CBC_SHA256 0x0300C098
# define TLS1_CK_RSA_PSK_WITH_CAMELLIA_256_CBC_SHA384 0x0300C099
# define TLS1_CK_ECDHE_PSK_WITH_CAMELLIA_128_CBC_SHA256 0x0300C09A
# define TLS1_CK_ECDHE_PSK_WITH_CAMELLIA_256_CBC_SHA384 0x0300C09B
/* draft-ietf-tls-chacha20-poly1305-03 */
# define TLS1_CK_ECDHE_RSA_WITH_CHACHA20_POLY1305 0x0300CCA8
# define TLS1_CK_ECDHE_ECDSA_WITH_CHACHA20_POLY1305 0x0300CCA9
# define TLS1_CK_DHE_RSA_WITH_CHACHA20_POLY1305 0x0300CCAA
# define TLS1_CK_PSK_WITH_CHACHA20_POLY1305 0x0300CCAB
# define TLS1_CK_ECDHE_PSK_WITH_CHACHA20_POLY1305 0x0300CCAC
# define TLS1_CK_DHE_PSK_WITH_CHACHA20_POLY1305 0x0300CCAD
# define TLS1_CK_RSA_PSK_WITH_CHACHA20_POLY1305 0x0300CCAE
/* TLS v1.3 ciphersuites */
# define TLS1_3_CK_AES_128_GCM_SHA256 0x03001301
# define TLS1_3_CK_AES_256_GCM_SHA384 0x03001302
# define TLS1_3_CK_CHACHA20_POLY1305_SHA256 0x03001303
# define TLS1_3_CK_AES_128_CCM_SHA256 0x03001304
# define TLS1_3_CK_AES_128_CCM_8_SHA256 0x03001305
/* Aria ciphersuites from RFC6209 */
# define TLS1_CK_RSA_WITH_ARIA_128_GCM_SHA256 0x0300C050
# define TLS1_CK_RSA_WITH_ARIA_256_GCM_SHA384 0x0300C051
# define TLS1_CK_DHE_RSA_WITH_ARIA_128_GCM_SHA256 0x0300C052
# define TLS1_CK_DHE_RSA_WITH_ARIA_256_GCM_SHA384 0x0300C053
# define TLS1_CK_DH_RSA_WITH_ARIA_128_GCM_SHA256 0x0300C054
# define TLS1_CK_DH_RSA_WITH_ARIA_256_GCM_SHA384 0x0300C055
# define TLS1_CK_DHE_DSS_WITH_ARIA_128_GCM_SHA256 0x0300C056
# define TLS1_CK_DHE_DSS_WITH_ARIA_256_GCM_SHA384 0x0300C057
# define TLS1_CK_DH_DSS_WITH_ARIA_128_GCM_SHA256 0x0300C058
# define TLS1_CK_DH_DSS_WITH_ARIA_256_GCM_SHA384 0x0300C059
# define TLS1_CK_DH_anon_WITH_ARIA_128_GCM_SHA256 0x0300C05A
# define TLS1_CK_DH_anon_WITH_ARIA_256_GCM_SHA384 0x0300C05B
# define TLS1_CK_ECDHE_ECDSA_WITH_ARIA_128_GCM_SHA256 0x0300C05C
# define TLS1_CK_ECDHE_ECDSA_WITH_ARIA_256_GCM_SHA384 0x0300C05D
# define TLS1_CK_ECDH_ECDSA_WITH_ARIA_128_GCM_SHA256 0x0300C05E
# define TLS1_CK_ECDH_ECDSA_WITH_ARIA_256_GCM_SHA384 0x0300C05F
# define TLS1_CK_ECDHE_RSA_WITH_ARIA_128_GCM_SHA256 0x0300C060
# define TLS1_CK_ECDHE_RSA_WITH_ARIA_256_GCM_SHA384 0x0300C061
# define TLS1_CK_ECDH_RSA_WITH_ARIA_128_GCM_SHA256 0x0300C062
# define TLS1_CK_ECDH_RSA_WITH_ARIA_256_GCM_SHA384 0x0300C063
# define TLS1_CK_PSK_WITH_ARIA_128_GCM_SHA256 0x0300C06A
# define TLS1_CK_PSK_WITH_ARIA_256_GCM_SHA384 0x0300C06B
# define TLS1_CK_DHE_PSK_WITH_ARIA_128_GCM_SHA256 0x0300C06C
# define TLS1_CK_DHE_PSK_WITH_ARIA_256_GCM_SHA384 0x0300C06D
# define TLS1_CK_RSA_PSK_WITH_ARIA_128_GCM_SHA256 0x0300C06E
# define TLS1_CK_RSA_PSK_WITH_ARIA_256_GCM_SHA384 0x0300C06F
/* a bundle of RFC standard cipher names, generated from ssl3_ciphers[] */
# define TLS1_RFC_RSA_WITH_AES_128_SHA "TLS_RSA_WITH_AES_128_CBC_SHA"
# define TLS1_RFC_DHE_DSS_WITH_AES_128_SHA "TLS_DHE_DSS_WITH_AES_128_CBC_SHA"
# define TLS1_RFC_DHE_RSA_WITH_AES_128_SHA "TLS_DHE_RSA_WITH_AES_128_CBC_SHA"
# define TLS1_RFC_ADH_WITH_AES_128_SHA "TLS_DH_anon_WITH_AES_128_CBC_SHA"
# define TLS1_RFC_RSA_WITH_AES_256_SHA "TLS_RSA_WITH_AES_256_CBC_SHA"
# define TLS1_RFC_DHE_DSS_WITH_AES_256_SHA "TLS_DHE_DSS_WITH_AES_256_CBC_SHA"
# define TLS1_RFC_DHE_RSA_WITH_AES_256_SHA "TLS_DHE_RSA_WITH_AES_256_CBC_SHA"
# define TLS1_RFC_ADH_WITH_AES_256_SHA "TLS_DH_anon_WITH_AES_256_CBC_SHA"
# define TLS1_RFC_RSA_WITH_NULL_SHA256 "TLS_RSA_WITH_NULL_SHA256"
# define TLS1_RFC_RSA_WITH_AES_128_SHA256 "TLS_RSA_WITH_AES_128_CBC_SHA256"
# define TLS1_RFC_RSA_WITH_AES_256_SHA256 "TLS_RSA_WITH_AES_256_CBC_SHA256"
# define TLS1_RFC_DHE_DSS_WITH_AES_128_SHA256 "TLS_DHE_DSS_WITH_AES_128_CBC_SHA256"
# define TLS1_RFC_DHE_RSA_WITH_AES_128_SHA256 "TLS_DHE_RSA_WITH_AES_128_CBC_SHA256"
# define TLS1_RFC_DHE_DSS_WITH_AES_256_SHA256 "TLS_DHE_DSS_WITH_AES_256_CBC_SHA256"
# define TLS1_RFC_DHE_RSA_WITH_AES_256_SHA256 "TLS_DHE_RSA_WITH_AES_256_CBC_SHA256"
# define TLS1_RFC_ADH_WITH_AES_128_SHA256 "TLS_DH_anon_WITH_AES_128_CBC_SHA256"
# define TLS1_RFC_ADH_WITH_AES_256_SHA256 "TLS_DH_anon_WITH_AES_256_CBC_SHA256"
# define TLS1_RFC_RSA_WITH_AES_128_GCM_SHA256 "TLS_RSA_WITH_AES_128_GCM_SHA256"
# define TLS1_RFC_RSA_WITH_AES_256_GCM_SHA384 "TLS_RSA_WITH_AES_256_GCM_SHA384"
# define TLS1_RFC_DHE_RSA_WITH_AES_128_GCM_SHA256 "TLS_DHE_RSA_WITH_AES_128_GCM_SHA256"
# define TLS1_RFC_DHE_RSA_WITH_AES_256_GCM_SHA384 "TLS_DHE_RSA_WITH_AES_256_GCM_SHA384"
# define TLS1_RFC_DHE_DSS_WITH_AES_128_GCM_SHA256 "TLS_DHE_DSS_WITH_AES_128_GCM_SHA256"
# define TLS1_RFC_DHE_DSS_WITH_AES_256_GCM_SHA384 "TLS_DHE_DSS_WITH_AES_256_GCM_SHA384"
# define TLS1_RFC_ADH_WITH_AES_128_GCM_SHA256 "TLS_DH_anon_WITH_AES_128_GCM_SHA256"
# define TLS1_RFC_ADH_WITH_AES_256_GCM_SHA384 "TLS_DH_anon_WITH_AES_256_GCM_SHA384"
# define TLS1_RFC_RSA_WITH_AES_128_CCM "TLS_RSA_WITH_AES_128_CCM"
# define TLS1_RFC_RSA_WITH_AES_256_CCM "TLS_RSA_WITH_AES_256_CCM"
# define TLS1_RFC_DHE_RSA_WITH_AES_128_CCM "TLS_DHE_RSA_WITH_AES_128_CCM"
# define TLS1_RFC_DHE_RSA_WITH_AES_256_CCM "TLS_DHE_RSA_WITH_AES_256_CCM"
# define TLS1_RFC_RSA_WITH_AES_128_CCM_8 "TLS_RSA_WITH_AES_128_CCM_8"
# define TLS1_RFC_RSA_WITH_AES_256_CCM_8 "TLS_RSA_WITH_AES_256_CCM_8"
# define TLS1_RFC_DHE_RSA_WITH_AES_128_CCM_8 "TLS_DHE_RSA_WITH_AES_128_CCM_8"
# define TLS1_RFC_DHE_RSA_WITH_AES_256_CCM_8 "TLS_DHE_RSA_WITH_AES_256_CCM_8"
# define TLS1_RFC_PSK_WITH_AES_128_CCM "TLS_PSK_WITH_AES_128_CCM"
# define TLS1_RFC_PSK_WITH_AES_256_CCM "TLS_PSK_WITH_AES_256_CCM"
# define TLS1_RFC_DHE_PSK_WITH_AES_128_CCM "TLS_DHE_PSK_WITH_AES_128_CCM"
# define TLS1_RFC_DHE_PSK_WITH_AES_256_CCM "TLS_DHE_PSK_WITH_AES_256_CCM"
# define TLS1_RFC_PSK_WITH_AES_128_CCM_8 "TLS_PSK_WITH_AES_128_CCM_8"
# define TLS1_RFC_PSK_WITH_AES_256_CCM_8 "TLS_PSK_WITH_AES_256_CCM_8"
# define TLS1_RFC_DHE_PSK_WITH_AES_128_CCM_8 "TLS_PSK_DHE_WITH_AES_128_CCM_8"
# define TLS1_RFC_DHE_PSK_WITH_AES_256_CCM_8 "TLS_PSK_DHE_WITH_AES_256_CCM_8"
# define TLS1_RFC_ECDHE_ECDSA_WITH_AES_128_CCM "TLS_ECDHE_ECDSA_WITH_AES_128_CCM"
# define TLS1_RFC_ECDHE_ECDSA_WITH_AES_256_CCM "TLS_ECDHE_ECDSA_WITH_AES_256_CCM"
# define TLS1_RFC_ECDHE_ECDSA_WITH_AES_128_CCM_8 "TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8"
# define TLS1_RFC_ECDHE_ECDSA_WITH_AES_256_CCM_8 "TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8"
# define TLS1_3_RFC_AES_128_GCM_SHA256 "TLS_AES_128_GCM_SHA256"
# define TLS1_3_RFC_AES_256_GCM_SHA384 "TLS_AES_256_GCM_SHA384"
# define TLS1_3_RFC_CHACHA20_POLY1305_SHA256 "TLS_CHACHA20_POLY1305_SHA256"
# define TLS1_3_RFC_AES_128_CCM_SHA256 "TLS_AES_128_CCM_SHA256"
# define TLS1_3_RFC_AES_128_CCM_8_SHA256 "TLS_AES_128_CCM_8_SHA256"
# define TLS1_RFC_ECDHE_ECDSA_WITH_NULL_SHA "TLS_ECDHE_ECDSA_WITH_NULL_SHA"
# define TLS1_RFC_ECDHE_ECDSA_WITH_DES_192_CBC3_SHA "TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA"
# define TLS1_RFC_ECDHE_ECDSA_WITH_AES_128_CBC_SHA "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA"
# define TLS1_RFC_ECDHE_ECDSA_WITH_AES_256_CBC_SHA "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA"
# define TLS1_RFC_ECDHE_RSA_WITH_NULL_SHA "TLS_ECDHE_RSA_WITH_NULL_SHA"
# define TLS1_RFC_ECDHE_RSA_WITH_DES_192_CBC3_SHA "TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA"
# define TLS1_RFC_ECDHE_RSA_WITH_AES_128_CBC_SHA "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA"
# define TLS1_RFC_ECDHE_RSA_WITH_AES_256_CBC_SHA "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA"
# define TLS1_RFC_ECDH_anon_WITH_NULL_SHA "TLS_ECDH_anon_WITH_NULL_SHA"
# define TLS1_RFC_ECDH_anon_WITH_DES_192_CBC3_SHA "TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA"
# define TLS1_RFC_ECDH_anon_WITH_AES_128_CBC_SHA "TLS_ECDH_anon_WITH_AES_128_CBC_SHA"
# define TLS1_RFC_ECDH_anon_WITH_AES_256_CBC_SHA "TLS_ECDH_anon_WITH_AES_256_CBC_SHA"
# define TLS1_RFC_ECDHE_ECDSA_WITH_AES_128_SHA256 "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256"
# define TLS1_RFC_ECDHE_ECDSA_WITH_AES_256_SHA384 "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384"
# define TLS1_RFC_ECDHE_RSA_WITH_AES_128_SHA256 "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256"
# define TLS1_RFC_ECDHE_RSA_WITH_AES_256_SHA384 "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384"
# define TLS1_RFC_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256"
# define TLS1_RFC_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384"
# define TLS1_RFC_ECDHE_RSA_WITH_AES_128_GCM_SHA256 "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256"
# define TLS1_RFC_ECDHE_RSA_WITH_AES_256_GCM_SHA384 "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384"
# define TLS1_RFC_PSK_WITH_NULL_SHA "TLS_PSK_WITH_NULL_SHA"
# define TLS1_RFC_DHE_PSK_WITH_NULL_SHA "TLS_DHE_PSK_WITH_NULL_SHA"
# define TLS1_RFC_RSA_PSK_WITH_NULL_SHA "TLS_RSA_PSK_WITH_NULL_SHA"
# define TLS1_RFC_PSK_WITH_3DES_EDE_CBC_SHA "TLS_PSK_WITH_3DES_EDE_CBC_SHA"
# define TLS1_RFC_PSK_WITH_AES_128_CBC_SHA "TLS_PSK_WITH_AES_128_CBC_SHA"
# define TLS1_RFC_PSK_WITH_AES_256_CBC_SHA "TLS_PSK_WITH_AES_256_CBC_SHA"
# define TLS1_RFC_DHE_PSK_WITH_3DES_EDE_CBC_SHA "TLS_DHE_PSK_WITH_3DES_EDE_CBC_SHA"
# define TLS1_RFC_DHE_PSK_WITH_AES_128_CBC_SHA "TLS_DHE_PSK_WITH_AES_128_CBC_SHA"
# define TLS1_RFC_DHE_PSK_WITH_AES_256_CBC_SHA "TLS_DHE_PSK_WITH_AES_256_CBC_SHA"
# define TLS1_RFC_RSA_PSK_WITH_3DES_EDE_CBC_SHA "TLS_RSA_PSK_WITH_3DES_EDE_CBC_SHA"
# define TLS1_RFC_RSA_PSK_WITH_AES_128_CBC_SHA "TLS_RSA_PSK_WITH_AES_128_CBC_SHA"
# define TLS1_RFC_RSA_PSK_WITH_AES_256_CBC_SHA "TLS_RSA_PSK_WITH_AES_256_CBC_SHA"
# define TLS1_RFC_PSK_WITH_AES_128_GCM_SHA256 "TLS_PSK_WITH_AES_128_GCM_SHA256"
# define TLS1_RFC_PSK_WITH_AES_256_GCM_SHA384 "TLS_PSK_WITH_AES_256_GCM_SHA384"
# define TLS1_RFC_DHE_PSK_WITH_AES_128_GCM_SHA256 "TLS_DHE_PSK_WITH_AES_128_GCM_SHA256"
# define TLS1_RFC_DHE_PSK_WITH_AES_256_GCM_SHA384 "TLS_DHE_PSK_WITH_AES_256_GCM_SHA384"
# define TLS1_RFC_RSA_PSK_WITH_AES_128_GCM_SHA256 "TLS_RSA_PSK_WITH_AES_128_GCM_SHA256"
# define TLS1_RFC_RSA_PSK_WITH_AES_256_GCM_SHA384 "TLS_RSA_PSK_WITH_AES_256_GCM_SHA384"
# define TLS1_RFC_PSK_WITH_AES_128_CBC_SHA256 "TLS_PSK_WITH_AES_128_CBC_SHA256"
# define TLS1_RFC_PSK_WITH_AES_256_CBC_SHA384 "TLS_PSK_WITH_AES_256_CBC_SHA384"
# define TLS1_RFC_PSK_WITH_NULL_SHA256 "TLS_PSK_WITH_NULL_SHA256"
# define TLS1_RFC_PSK_WITH_NULL_SHA384 "TLS_PSK_WITH_NULL_SHA384"
# define TLS1_RFC_DHE_PSK_WITH_AES_128_CBC_SHA256 "TLS_DHE_PSK_WITH_AES_128_CBC_SHA256"
# define TLS1_RFC_DHE_PSK_WITH_AES_256_CBC_SHA384 "TLS_DHE_PSK_WITH_AES_256_CBC_SHA384"
# define TLS1_RFC_DHE_PSK_WITH_NULL_SHA256 "TLS_DHE_PSK_WITH_NULL_SHA256"
# define TLS1_RFC_DHE_PSK_WITH_NULL_SHA384 "TLS_DHE_PSK_WITH_NULL_SHA384"
# define TLS1_RFC_RSA_PSK_WITH_AES_128_CBC_SHA256 "TLS_RSA_PSK_WITH_AES_128_CBC_SHA256"
# define TLS1_RFC_RSA_PSK_WITH_AES_256_CBC_SHA384 "TLS_RSA_PSK_WITH_AES_256_CBC_SHA384"
# define TLS1_RFC_RSA_PSK_WITH_NULL_SHA256 "TLS_RSA_PSK_WITH_NULL_SHA256"
# define TLS1_RFC_RSA_PSK_WITH_NULL_SHA384 "TLS_RSA_PSK_WITH_NULL_SHA384"
# define TLS1_RFC_ECDHE_PSK_WITH_3DES_EDE_CBC_SHA "TLS_ECDHE_PSK_WITH_3DES_EDE_CBC_SHA"
# define TLS1_RFC_ECDHE_PSK_WITH_AES_128_CBC_SHA "TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA"
# define TLS1_RFC_ECDHE_PSK_WITH_AES_256_CBC_SHA "TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA"
# define TLS1_RFC_ECDHE_PSK_WITH_AES_128_CBC_SHA256 "TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256"
# define TLS1_RFC_ECDHE_PSK_WITH_AES_256_CBC_SHA384 "TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA384"
# define TLS1_RFC_ECDHE_PSK_WITH_NULL_SHA "TLS_ECDHE_PSK_WITH_NULL_SHA"
# define TLS1_RFC_ECDHE_PSK_WITH_NULL_SHA256 "TLS_ECDHE_PSK_WITH_NULL_SHA256"
# define TLS1_RFC_ECDHE_PSK_WITH_NULL_SHA384 "TLS_ECDHE_PSK_WITH_NULL_SHA384"
# define TLS1_RFC_SRP_SHA_WITH_3DES_EDE_CBC_SHA "TLS_SRP_SHA_WITH_3DES_EDE_CBC_SHA"
# define TLS1_RFC_SRP_SHA_RSA_WITH_3DES_EDE_CBC_SHA "TLS_SRP_SHA_RSA_WITH_3DES_EDE_CBC_SHA"
# define TLS1_RFC_SRP_SHA_DSS_WITH_3DES_EDE_CBC_SHA "TLS_SRP_SHA_DSS_WITH_3DES_EDE_CBC_SHA"
# define TLS1_RFC_SRP_SHA_WITH_AES_128_CBC_SHA "TLS_SRP_SHA_WITH_AES_128_CBC_SHA"
# define TLS1_RFC_SRP_SHA_RSA_WITH_AES_128_CBC_SHA "TLS_SRP_SHA_RSA_WITH_AES_128_CBC_SHA"
# define TLS1_RFC_SRP_SHA_DSS_WITH_AES_128_CBC_SHA "TLS_SRP_SHA_DSS_WITH_AES_128_CBC_SHA"
# define TLS1_RFC_SRP_SHA_WITH_AES_256_CBC_SHA "TLS_SRP_SHA_WITH_AES_256_CBC_SHA"
# define TLS1_RFC_SRP_SHA_RSA_WITH_AES_256_CBC_SHA "TLS_SRP_SHA_RSA_WITH_AES_256_CBC_SHA"
# define TLS1_RFC_SRP_SHA_DSS_WITH_AES_256_CBC_SHA "TLS_SRP_SHA_DSS_WITH_AES_256_CBC_SHA"
# define TLS1_RFC_DHE_RSA_WITH_CHACHA20_POLY1305 "TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256"
# define TLS1_RFC_ECDHE_RSA_WITH_CHACHA20_POLY1305 "TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256"
# define TLS1_RFC_ECDHE_ECDSA_WITH_CHACHA20_POLY1305 "TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256"
# define TLS1_RFC_PSK_WITH_CHACHA20_POLY1305 "TLS_PSK_WITH_CHACHA20_POLY1305_SHA256"
# define TLS1_RFC_ECDHE_PSK_WITH_CHACHA20_POLY1305 "TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256"
# define TLS1_RFC_DHE_PSK_WITH_CHACHA20_POLY1305 "TLS_DHE_PSK_WITH_CHACHA20_POLY1305_SHA256"
# define TLS1_RFC_RSA_PSK_WITH_CHACHA20_POLY1305 "TLS_RSA_PSK_WITH_CHACHA20_POLY1305_SHA256"
# define TLS1_RFC_RSA_WITH_CAMELLIA_128_CBC_SHA256 "TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256"
# define TLS1_RFC_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA256 "TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA256"
# define TLS1_RFC_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256 "TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256"
# define TLS1_RFC_ADH_WITH_CAMELLIA_128_CBC_SHA256 "TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA256"
# define TLS1_RFC_RSA_WITH_CAMELLIA_256_CBC_SHA256 "TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256"
# define TLS1_RFC_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA256 "TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA256"
# define TLS1_RFC_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256 "TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256"
# define TLS1_RFC_ADH_WITH_CAMELLIA_256_CBC_SHA256 "TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA256"
# define TLS1_RFC_RSA_WITH_CAMELLIA_256_CBC_SHA "TLS_RSA_WITH_CAMELLIA_256_CBC_SHA"
# define TLS1_RFC_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA "TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA"
# define TLS1_RFC_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA "TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA"
# define TLS1_RFC_ADH_WITH_CAMELLIA_256_CBC_SHA "TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA"
# define TLS1_RFC_RSA_WITH_CAMELLIA_128_CBC_SHA "TLS_RSA_WITH_CAMELLIA_128_CBC_SHA"
# define TLS1_RFC_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA "TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA"
# define TLS1_RFC_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA "TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA"
# define TLS1_RFC_ADH_WITH_CAMELLIA_128_CBC_SHA "TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA"
# define TLS1_RFC_ECDHE_ECDSA_WITH_CAMELLIA_128_CBC_SHA256 "TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_CBC_SHA256"
# define TLS1_RFC_ECDHE_ECDSA_WITH_CAMELLIA_256_CBC_SHA384 "TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_CBC_SHA384"
# define TLS1_RFC_ECDHE_RSA_WITH_CAMELLIA_128_CBC_SHA256 "TLS_ECDHE_RSA_WITH_CAMELLIA_128_CBC_SHA256"
# define TLS1_RFC_ECDHE_RSA_WITH_CAMELLIA_256_CBC_SHA384 "TLS_ECDHE_RSA_WITH_CAMELLIA_256_CBC_SHA384"
# define TLS1_RFC_PSK_WITH_CAMELLIA_128_CBC_SHA256 "TLS_PSK_WITH_CAMELLIA_128_CBC_SHA256"
# define TLS1_RFC_PSK_WITH_CAMELLIA_256_CBC_SHA384 "TLS_PSK_WITH_CAMELLIA_256_CBC_SHA384"
# define TLS1_RFC_DHE_PSK_WITH_CAMELLIA_128_CBC_SHA256 "TLS_DHE_PSK_WITH_CAMELLIA_128_CBC_SHA256"
# define TLS1_RFC_DHE_PSK_WITH_CAMELLIA_256_CBC_SHA384 "TLS_DHE_PSK_WITH_CAMELLIA_256_CBC_SHA384"
# define TLS1_RFC_RSA_PSK_WITH_CAMELLIA_128_CBC_SHA256 "TLS_RSA_PSK_WITH_CAMELLIA_128_CBC_SHA256"
# define TLS1_RFC_RSA_PSK_WITH_CAMELLIA_256_CBC_SHA384 "TLS_RSA_PSK_WITH_CAMELLIA_256_CBC_SHA384"
# define TLS1_RFC_ECDHE_PSK_WITH_CAMELLIA_128_CBC_SHA256 "TLS_ECDHE_PSK_WITH_CAMELLIA_128_CBC_SHA256"
# define TLS1_RFC_ECDHE_PSK_WITH_CAMELLIA_256_CBC_SHA384 "TLS_ECDHE_PSK_WITH_CAMELLIA_256_CBC_SHA384"
# define TLS1_RFC_RSA_WITH_SEED_SHA "TLS_RSA_WITH_SEED_CBC_SHA"
# define TLS1_RFC_DHE_DSS_WITH_SEED_SHA "TLS_DHE_DSS_WITH_SEED_CBC_SHA"
# define TLS1_RFC_DHE_RSA_WITH_SEED_SHA "TLS_DHE_RSA_WITH_SEED_CBC_SHA"
# define TLS1_RFC_ADH_WITH_SEED_SHA "TLS_DH_anon_WITH_SEED_CBC_SHA"
# define TLS1_RFC_ECDHE_PSK_WITH_RC4_128_SHA "TLS_ECDHE_PSK_WITH_RC4_128_SHA"
# define TLS1_RFC_ECDH_anon_WITH_RC4_128_SHA "TLS_ECDH_anon_WITH_RC4_128_SHA"
# define TLS1_RFC_ECDHE_ECDSA_WITH_RC4_128_SHA "TLS_ECDHE_ECDSA_WITH_RC4_128_SHA"
# define TLS1_RFC_ECDHE_RSA_WITH_RC4_128_SHA "TLS_ECDHE_RSA_WITH_RC4_128_SHA"
# define TLS1_RFC_PSK_WITH_RC4_128_SHA "TLS_PSK_WITH_RC4_128_SHA"
# define TLS1_RFC_RSA_PSK_WITH_RC4_128_SHA "TLS_RSA_PSK_WITH_RC4_128_SHA"
# define TLS1_RFC_DHE_PSK_WITH_RC4_128_SHA "TLS_DHE_PSK_WITH_RC4_128_SHA"
# define TLS1_RFC_RSA_WITH_ARIA_128_GCM_SHA256 "TLS_RSA_WITH_ARIA_128_GCM_SHA256"
# define TLS1_RFC_RSA_WITH_ARIA_256_GCM_SHA384 "TLS_RSA_WITH_ARIA_256_GCM_SHA384"
# define TLS1_RFC_DHE_RSA_WITH_ARIA_128_GCM_SHA256 "TLS_DHE_RSA_WITH_ARIA_128_GCM_SHA256"
# define TLS1_RFC_DHE_RSA_WITH_ARIA_256_GCM_SHA384 "TLS_DHE_RSA_WITH_ARIA_256_GCM_SHA384"
# define TLS1_RFC_DH_RSA_WITH_ARIA_128_GCM_SHA256 "TLS_DH_RSA_WITH_ARIA_128_GCM_SHA256"
# define TLS1_RFC_DH_RSA_WITH_ARIA_256_GCM_SHA384 "TLS_DH_RSA_WITH_ARIA_256_GCM_SHA384"
# define TLS1_RFC_DHE_DSS_WITH_ARIA_128_GCM_SHA256 "TLS_DHE_DSS_WITH_ARIA_128_GCM_SHA256"
# define TLS1_RFC_DHE_DSS_WITH_ARIA_256_GCM_SHA384 "TLS_DHE_DSS_WITH_ARIA_256_GCM_SHA384"
# define TLS1_RFC_DH_DSS_WITH_ARIA_128_GCM_SHA256 "TLS_DH_DSS_WITH_ARIA_128_GCM_SHA256"
# define TLS1_RFC_DH_DSS_WITH_ARIA_256_GCM_SHA384 "TLS_DH_DSS_WITH_ARIA_256_GCM_SHA384"
# define TLS1_RFC_DH_anon_WITH_ARIA_128_GCM_SHA256 "TLS_DH_anon_WITH_ARIA_128_GCM_SHA256"
# define TLS1_RFC_DH_anon_WITH_ARIA_256_GCM_SHA384 "TLS_DH_anon_WITH_ARIA_256_GCM_SHA384"
# define TLS1_RFC_ECDHE_ECDSA_WITH_ARIA_128_GCM_SHA256 "TLS_ECDHE_ECDSA_WITH_ARIA_128_GCM_SHA256"
# define TLS1_RFC_ECDHE_ECDSA_WITH_ARIA_256_GCM_SHA384 "TLS_ECDHE_ECDSA_WITH_ARIA_256_GCM_SHA384"
# define TLS1_RFC_ECDH_ECDSA_WITH_ARIA_128_GCM_SHA256 "TLS_ECDH_ECDSA_WITH_ARIA_128_GCM_SHA256"
# define TLS1_RFC_ECDH_ECDSA_WITH_ARIA_256_GCM_SHA384 "TLS_ECDH_ECDSA_WITH_ARIA_256_GCM_SHA384"
# define TLS1_RFC_ECDHE_RSA_WITH_ARIA_128_GCM_SHA256 "TLS_ECDHE_RSA_WITH_ARIA_128_GCM_SHA256"
# define TLS1_RFC_ECDHE_RSA_WITH_ARIA_256_GCM_SHA384 "TLS_ECDHE_RSA_WITH_ARIA_256_GCM_SHA384"
# define TLS1_RFC_ECDH_RSA_WITH_ARIA_128_GCM_SHA256 "TLS_ECDH_RSA_WITH_ARIA_128_GCM_SHA256"
# define TLS1_RFC_ECDH_RSA_WITH_ARIA_256_GCM_SHA384 "TLS_ECDH_RSA_WITH_ARIA_256_GCM_SHA384"
# define TLS1_RFC_PSK_WITH_ARIA_128_GCM_SHA256 "TLS_PSK_WITH_ARIA_128_GCM_SHA256"
# define TLS1_RFC_PSK_WITH_ARIA_256_GCM_SHA384 "TLS_PSK_WITH_ARIA_256_GCM_SHA384"
# define TLS1_RFC_DHE_PSK_WITH_ARIA_128_GCM_SHA256 "TLS_DHE_PSK_WITH_ARIA_128_GCM_SHA256"
# define TLS1_RFC_DHE_PSK_WITH_ARIA_256_GCM_SHA384 "TLS_DHE_PSK_WITH_ARIA_256_GCM_SHA384"
# define TLS1_RFC_RSA_PSK_WITH_ARIA_128_GCM_SHA256 "TLS_RSA_PSK_WITH_ARIA_128_GCM_SHA256"
# define TLS1_RFC_RSA_PSK_WITH_ARIA_256_GCM_SHA384 "TLS_RSA_PSK_WITH_ARIA_256_GCM_SHA384"
/*
* XXX Backward compatibility alert: Older versions of OpenSSL gave some DHE
* ciphers names with "EDH" instead of "DHE". Going forward, we should be
* using DHE everywhere, though we may indefinitely maintain aliases for
* users or configurations that used "EDH"
*/
# define TLS1_TXT_DHE_DSS_WITH_RC4_128_SHA "DHE-DSS-RC4-SHA"
# define TLS1_TXT_PSK_WITH_NULL_SHA "PSK-NULL-SHA"
# define TLS1_TXT_DHE_PSK_WITH_NULL_SHA "DHE-PSK-NULL-SHA"
# define TLS1_TXT_RSA_PSK_WITH_NULL_SHA "RSA-PSK-NULL-SHA"
/* AES ciphersuites from RFC3268 */
# define TLS1_TXT_RSA_WITH_AES_128_SHA "AES128-SHA"
# define TLS1_TXT_DH_DSS_WITH_AES_128_SHA "DH-DSS-AES128-SHA"
# define TLS1_TXT_DH_RSA_WITH_AES_128_SHA "DH-RSA-AES128-SHA"
# define TLS1_TXT_DHE_DSS_WITH_AES_128_SHA "DHE-DSS-AES128-SHA"
# define TLS1_TXT_DHE_RSA_WITH_AES_128_SHA "DHE-RSA-AES128-SHA"
# define TLS1_TXT_ADH_WITH_AES_128_SHA "ADH-AES128-SHA"
# define TLS1_TXT_RSA_WITH_AES_256_SHA "AES256-SHA"
# define TLS1_TXT_DH_DSS_WITH_AES_256_SHA "DH-DSS-AES256-SHA"
# define TLS1_TXT_DH_RSA_WITH_AES_256_SHA "DH-RSA-AES256-SHA"
# define TLS1_TXT_DHE_DSS_WITH_AES_256_SHA "DHE-DSS-AES256-SHA"
# define TLS1_TXT_DHE_RSA_WITH_AES_256_SHA "DHE-RSA-AES256-SHA"
# define TLS1_TXT_ADH_WITH_AES_256_SHA "ADH-AES256-SHA"
/* ECC ciphersuites from RFC4492 */
# define TLS1_TXT_ECDH_ECDSA_WITH_NULL_SHA "ECDH-ECDSA-NULL-SHA"
# define TLS1_TXT_ECDH_ECDSA_WITH_RC4_128_SHA "ECDH-ECDSA-RC4-SHA"
# define TLS1_TXT_ECDH_ECDSA_WITH_DES_192_CBC3_SHA "ECDH-ECDSA-DES-CBC3-SHA"
# define TLS1_TXT_ECDH_ECDSA_WITH_AES_128_CBC_SHA "ECDH-ECDSA-AES128-SHA"
# define TLS1_TXT_ECDH_ECDSA_WITH_AES_256_CBC_SHA "ECDH-ECDSA-AES256-SHA"
# define TLS1_TXT_ECDHE_ECDSA_WITH_NULL_SHA "ECDHE-ECDSA-NULL-SHA"
# define TLS1_TXT_ECDHE_ECDSA_WITH_RC4_128_SHA "ECDHE-ECDSA-RC4-SHA"
# define TLS1_TXT_ECDHE_ECDSA_WITH_DES_192_CBC3_SHA "ECDHE-ECDSA-DES-CBC3-SHA"
# define TLS1_TXT_ECDHE_ECDSA_WITH_AES_128_CBC_SHA "ECDHE-ECDSA-AES128-SHA"
# define TLS1_TXT_ECDHE_ECDSA_WITH_AES_256_CBC_SHA "ECDHE-ECDSA-AES256-SHA"
# define TLS1_TXT_ECDH_RSA_WITH_NULL_SHA "ECDH-RSA-NULL-SHA"
# define TLS1_TXT_ECDH_RSA_WITH_RC4_128_SHA "ECDH-RSA-RC4-SHA"
# define TLS1_TXT_ECDH_RSA_WITH_DES_192_CBC3_SHA "ECDH-RSA-DES-CBC3-SHA"
# define TLS1_TXT_ECDH_RSA_WITH_AES_128_CBC_SHA "ECDH-RSA-AES128-SHA"
# define TLS1_TXT_ECDH_RSA_WITH_AES_256_CBC_SHA "ECDH-RSA-AES256-SHA"
# define TLS1_TXT_ECDHE_RSA_WITH_NULL_SHA "ECDHE-RSA-NULL-SHA"
# define TLS1_TXT_ECDHE_RSA_WITH_RC4_128_SHA "ECDHE-RSA-RC4-SHA"
# define TLS1_TXT_ECDHE_RSA_WITH_DES_192_CBC3_SHA "ECDHE-RSA-DES-CBC3-SHA"
# define TLS1_TXT_ECDHE_RSA_WITH_AES_128_CBC_SHA "ECDHE-RSA-AES128-SHA"
# define TLS1_TXT_ECDHE_RSA_WITH_AES_256_CBC_SHA "ECDHE-RSA-AES256-SHA"
# define TLS1_TXT_ECDH_anon_WITH_NULL_SHA "AECDH-NULL-SHA"
# define TLS1_TXT_ECDH_anon_WITH_RC4_128_SHA "AECDH-RC4-SHA"
# define TLS1_TXT_ECDH_anon_WITH_DES_192_CBC3_SHA "AECDH-DES-CBC3-SHA"
# define TLS1_TXT_ECDH_anon_WITH_AES_128_CBC_SHA "AECDH-AES128-SHA"
# define TLS1_TXT_ECDH_anon_WITH_AES_256_CBC_SHA "AECDH-AES256-SHA"
/* PSK ciphersuites from RFC 4279 */
# define TLS1_TXT_PSK_WITH_RC4_128_SHA "PSK-RC4-SHA"
# define TLS1_TXT_PSK_WITH_3DES_EDE_CBC_SHA "PSK-3DES-EDE-CBC-SHA"
# define TLS1_TXT_PSK_WITH_AES_128_CBC_SHA "PSK-AES128-CBC-SHA"
# define TLS1_TXT_PSK_WITH_AES_256_CBC_SHA "PSK-AES256-CBC-SHA"
# define TLS1_TXT_DHE_PSK_WITH_RC4_128_SHA "DHE-PSK-RC4-SHA"
# define TLS1_TXT_DHE_PSK_WITH_3DES_EDE_CBC_SHA "DHE-PSK-3DES-EDE-CBC-SHA"
# define TLS1_TXT_DHE_PSK_WITH_AES_128_CBC_SHA "DHE-PSK-AES128-CBC-SHA"
# define TLS1_TXT_DHE_PSK_WITH_AES_256_CBC_SHA "DHE-PSK-AES256-CBC-SHA"
# define TLS1_TXT_RSA_PSK_WITH_RC4_128_SHA "RSA-PSK-RC4-SHA"
# define TLS1_TXT_RSA_PSK_WITH_3DES_EDE_CBC_SHA "RSA-PSK-3DES-EDE-CBC-SHA"
# define TLS1_TXT_RSA_PSK_WITH_AES_128_CBC_SHA "RSA-PSK-AES128-CBC-SHA"
# define TLS1_TXT_RSA_PSK_WITH_AES_256_CBC_SHA "RSA-PSK-AES256-CBC-SHA"
/* PSK ciphersuites from RFC 5487 */
# define TLS1_TXT_PSK_WITH_AES_128_GCM_SHA256 "PSK-AES128-GCM-SHA256"
# define TLS1_TXT_PSK_WITH_AES_256_GCM_SHA384 "PSK-AES256-GCM-SHA384"
# define TLS1_TXT_DHE_PSK_WITH_AES_128_GCM_SHA256 "DHE-PSK-AES128-GCM-SHA256"
# define TLS1_TXT_DHE_PSK_WITH_AES_256_GCM_SHA384 "DHE-PSK-AES256-GCM-SHA384"
# define TLS1_TXT_RSA_PSK_WITH_AES_128_GCM_SHA256 "RSA-PSK-AES128-GCM-SHA256"
# define TLS1_TXT_RSA_PSK_WITH_AES_256_GCM_SHA384 "RSA-PSK-AES256-GCM-SHA384"
# define TLS1_TXT_PSK_WITH_AES_128_CBC_SHA256 "PSK-AES128-CBC-SHA256"
# define TLS1_TXT_PSK_WITH_AES_256_CBC_SHA384 "PSK-AES256-CBC-SHA384"
# define TLS1_TXT_PSK_WITH_NULL_SHA256 "PSK-NULL-SHA256"
# define TLS1_TXT_PSK_WITH_NULL_SHA384 "PSK-NULL-SHA384"
# define TLS1_TXT_DHE_PSK_WITH_AES_128_CBC_SHA256 "DHE-PSK-AES128-CBC-SHA256"
# define TLS1_TXT_DHE_PSK_WITH_AES_256_CBC_SHA384 "DHE-PSK-AES256-CBC-SHA384"
# define TLS1_TXT_DHE_PSK_WITH_NULL_SHA256 "DHE-PSK-NULL-SHA256"
# define TLS1_TXT_DHE_PSK_WITH_NULL_SHA384 "DHE-PSK-NULL-SHA384"
# define TLS1_TXT_RSA_PSK_WITH_AES_128_CBC_SHA256 "RSA-PSK-AES128-CBC-SHA256"
# define TLS1_TXT_RSA_PSK_WITH_AES_256_CBC_SHA384 "RSA-PSK-AES256-CBC-SHA384"
# define TLS1_TXT_RSA_PSK_WITH_NULL_SHA256 "RSA-PSK-NULL-SHA256"
# define TLS1_TXT_RSA_PSK_WITH_NULL_SHA384 "RSA-PSK-NULL-SHA384"
/* SRP ciphersuite from RFC 5054 */
# define TLS1_TXT_SRP_SHA_WITH_3DES_EDE_CBC_SHA "SRP-3DES-EDE-CBC-SHA"
# define TLS1_TXT_SRP_SHA_RSA_WITH_3DES_EDE_CBC_SHA "SRP-RSA-3DES-EDE-CBC-SHA"
# define TLS1_TXT_SRP_SHA_DSS_WITH_3DES_EDE_CBC_SHA "SRP-DSS-3DES-EDE-CBC-SHA"
# define TLS1_TXT_SRP_SHA_WITH_AES_128_CBC_SHA "SRP-AES-128-CBC-SHA"
# define TLS1_TXT_SRP_SHA_RSA_WITH_AES_128_CBC_SHA "SRP-RSA-AES-128-CBC-SHA"
# define TLS1_TXT_SRP_SHA_DSS_WITH_AES_128_CBC_SHA "SRP-DSS-AES-128-CBC-SHA"
# define TLS1_TXT_SRP_SHA_WITH_AES_256_CBC_SHA "SRP-AES-256-CBC-SHA"
# define TLS1_TXT_SRP_SHA_RSA_WITH_AES_256_CBC_SHA "SRP-RSA-AES-256-CBC-SHA"
# define TLS1_TXT_SRP_SHA_DSS_WITH_AES_256_CBC_SHA "SRP-DSS-AES-256-CBC-SHA"
/* Camellia ciphersuites from RFC4132 */
# define TLS1_TXT_RSA_WITH_CAMELLIA_128_CBC_SHA "CAMELLIA128-SHA"
# define TLS1_TXT_DH_DSS_WITH_CAMELLIA_128_CBC_SHA "DH-DSS-CAMELLIA128-SHA"
# define TLS1_TXT_DH_RSA_WITH_CAMELLIA_128_CBC_SHA "DH-RSA-CAMELLIA128-SHA"
# define TLS1_TXT_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA "DHE-DSS-CAMELLIA128-SHA"
# define TLS1_TXT_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA "DHE-RSA-CAMELLIA128-SHA"
# define TLS1_TXT_ADH_WITH_CAMELLIA_128_CBC_SHA "ADH-CAMELLIA128-SHA"
# define TLS1_TXT_RSA_WITH_CAMELLIA_256_CBC_SHA "CAMELLIA256-SHA"
# define TLS1_TXT_DH_DSS_WITH_CAMELLIA_256_CBC_SHA "DH-DSS-CAMELLIA256-SHA"
# define TLS1_TXT_DH_RSA_WITH_CAMELLIA_256_CBC_SHA "DH-RSA-CAMELLIA256-SHA"
# define TLS1_TXT_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA "DHE-DSS-CAMELLIA256-SHA"
# define TLS1_TXT_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA "DHE-RSA-CAMELLIA256-SHA"
# define TLS1_TXT_ADH_WITH_CAMELLIA_256_CBC_SHA "ADH-CAMELLIA256-SHA"
/* TLS 1.2 Camellia SHA-256 ciphersuites from RFC5932 */
# define TLS1_TXT_RSA_WITH_CAMELLIA_128_CBC_SHA256 "CAMELLIA128-SHA256"
# define TLS1_TXT_DH_DSS_WITH_CAMELLIA_128_CBC_SHA256 "DH-DSS-CAMELLIA128-SHA256"
# define TLS1_TXT_DH_RSA_WITH_CAMELLIA_128_CBC_SHA256 "DH-RSA-CAMELLIA128-SHA256"
# define TLS1_TXT_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA256 "DHE-DSS-CAMELLIA128-SHA256"
# define TLS1_TXT_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256 "DHE-RSA-CAMELLIA128-SHA256"
# define TLS1_TXT_ADH_WITH_CAMELLIA_128_CBC_SHA256 "ADH-CAMELLIA128-SHA256"
# define TLS1_TXT_RSA_WITH_CAMELLIA_256_CBC_SHA256 "CAMELLIA256-SHA256"
# define TLS1_TXT_DH_DSS_WITH_CAMELLIA_256_CBC_SHA256 "DH-DSS-CAMELLIA256-SHA256"
# define TLS1_TXT_DH_RSA_WITH_CAMELLIA_256_CBC_SHA256 "DH-RSA-CAMELLIA256-SHA256"
# define TLS1_TXT_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA256 "DHE-DSS-CAMELLIA256-SHA256"
# define TLS1_TXT_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256 "DHE-RSA-CAMELLIA256-SHA256"
# define TLS1_TXT_ADH_WITH_CAMELLIA_256_CBC_SHA256 "ADH-CAMELLIA256-SHA256"
# define TLS1_TXT_PSK_WITH_CAMELLIA_128_CBC_SHA256 "PSK-CAMELLIA128-SHA256"
# define TLS1_TXT_PSK_WITH_CAMELLIA_256_CBC_SHA384 "PSK-CAMELLIA256-SHA384"
# define TLS1_TXT_DHE_PSK_WITH_CAMELLIA_128_CBC_SHA256 "DHE-PSK-CAMELLIA128-SHA256"
# define TLS1_TXT_DHE_PSK_WITH_CAMELLIA_256_CBC_SHA384 "DHE-PSK-CAMELLIA256-SHA384"
# define TLS1_TXT_RSA_PSK_WITH_CAMELLIA_128_CBC_SHA256 "RSA-PSK-CAMELLIA128-SHA256"
# define TLS1_TXT_RSA_PSK_WITH_CAMELLIA_256_CBC_SHA384 "RSA-PSK-CAMELLIA256-SHA384"
# define TLS1_TXT_ECDHE_PSK_WITH_CAMELLIA_128_CBC_SHA256 "ECDHE-PSK-CAMELLIA128-SHA256"
# define TLS1_TXT_ECDHE_PSK_WITH_CAMELLIA_256_CBC_SHA384 "ECDHE-PSK-CAMELLIA256-SHA384"
/* SEED ciphersuites from RFC4162 */
# define TLS1_TXT_RSA_WITH_SEED_SHA "SEED-SHA"
# define TLS1_TXT_DH_DSS_WITH_SEED_SHA "DH-DSS-SEED-SHA"
# define TLS1_TXT_DH_RSA_WITH_SEED_SHA "DH-RSA-SEED-SHA"
# define TLS1_TXT_DHE_DSS_WITH_SEED_SHA "DHE-DSS-SEED-SHA"
# define TLS1_TXT_DHE_RSA_WITH_SEED_SHA "DHE-RSA-SEED-SHA"
# define TLS1_TXT_ADH_WITH_SEED_SHA "ADH-SEED-SHA"
/* TLS v1.2 ciphersuites */
# define TLS1_TXT_RSA_WITH_NULL_SHA256 "NULL-SHA256"
# define TLS1_TXT_RSA_WITH_AES_128_SHA256 "AES128-SHA256"
# define TLS1_TXT_RSA_WITH_AES_256_SHA256 "AES256-SHA256"
# define TLS1_TXT_DH_DSS_WITH_AES_128_SHA256 "DH-DSS-AES128-SHA256"
# define TLS1_TXT_DH_RSA_WITH_AES_128_SHA256 "DH-RSA-AES128-SHA256"
# define TLS1_TXT_DHE_DSS_WITH_AES_128_SHA256 "DHE-DSS-AES128-SHA256"
# define TLS1_TXT_DHE_RSA_WITH_AES_128_SHA256 "DHE-RSA-AES128-SHA256"
# define TLS1_TXT_DH_DSS_WITH_AES_256_SHA256 "DH-DSS-AES256-SHA256"
# define TLS1_TXT_DH_RSA_WITH_AES_256_SHA256 "DH-RSA-AES256-SHA256"
# define TLS1_TXT_DHE_DSS_WITH_AES_256_SHA256 "DHE-DSS-AES256-SHA256"
# define TLS1_TXT_DHE_RSA_WITH_AES_256_SHA256 "DHE-RSA-AES256-SHA256"
# define TLS1_TXT_ADH_WITH_AES_128_SHA256 "ADH-AES128-SHA256"
# define TLS1_TXT_ADH_WITH_AES_256_SHA256 "ADH-AES256-SHA256"
/* TLS v1.2 GCM ciphersuites from RFC5288 */
# define TLS1_TXT_RSA_WITH_AES_128_GCM_SHA256 "AES128-GCM-SHA256"
# define TLS1_TXT_RSA_WITH_AES_256_GCM_SHA384 "AES256-GCM-SHA384"
# define TLS1_TXT_DHE_RSA_WITH_AES_128_GCM_SHA256 "DHE-RSA-AES128-GCM-SHA256"
# define TLS1_TXT_DHE_RSA_WITH_AES_256_GCM_SHA384 "DHE-RSA-AES256-GCM-SHA384"
# define TLS1_TXT_DH_RSA_WITH_AES_128_GCM_SHA256 "DH-RSA-AES128-GCM-SHA256"
# define TLS1_TXT_DH_RSA_WITH_AES_256_GCM_SHA384 "DH-RSA-AES256-GCM-SHA384"
# define TLS1_TXT_DHE_DSS_WITH_AES_128_GCM_SHA256 "DHE-DSS-AES128-GCM-SHA256"
# define TLS1_TXT_DHE_DSS_WITH_AES_256_GCM_SHA384 "DHE-DSS-AES256-GCM-SHA384"
# define TLS1_TXT_DH_DSS_WITH_AES_128_GCM_SHA256 "DH-DSS-AES128-GCM-SHA256"
# define TLS1_TXT_DH_DSS_WITH_AES_256_GCM_SHA384 "DH-DSS-AES256-GCM-SHA384"
# define TLS1_TXT_ADH_WITH_AES_128_GCM_SHA256 "ADH-AES128-GCM-SHA256"
# define TLS1_TXT_ADH_WITH_AES_256_GCM_SHA384 "ADH-AES256-GCM-SHA384"
/* CCM ciphersuites from RFC6655 */
# define TLS1_TXT_RSA_WITH_AES_128_CCM "AES128-CCM"
# define TLS1_TXT_RSA_WITH_AES_256_CCM "AES256-CCM"
# define TLS1_TXT_DHE_RSA_WITH_AES_128_CCM "DHE-RSA-AES128-CCM"
# define TLS1_TXT_DHE_RSA_WITH_AES_256_CCM "DHE-RSA-AES256-CCM"
# define TLS1_TXT_RSA_WITH_AES_128_CCM_8 "AES128-CCM8"
# define TLS1_TXT_RSA_WITH_AES_256_CCM_8 "AES256-CCM8"
# define TLS1_TXT_DHE_RSA_WITH_AES_128_CCM_8 "DHE-RSA-AES128-CCM8"
# define TLS1_TXT_DHE_RSA_WITH_AES_256_CCM_8 "DHE-RSA-AES256-CCM8"
# define TLS1_TXT_PSK_WITH_AES_128_CCM "PSK-AES128-CCM"
# define TLS1_TXT_PSK_WITH_AES_256_CCM "PSK-AES256-CCM"
# define TLS1_TXT_DHE_PSK_WITH_AES_128_CCM "DHE-PSK-AES128-CCM"
# define TLS1_TXT_DHE_PSK_WITH_AES_256_CCM "DHE-PSK-AES256-CCM"
# define TLS1_TXT_PSK_WITH_AES_128_CCM_8 "PSK-AES128-CCM8"
# define TLS1_TXT_PSK_WITH_AES_256_CCM_8 "PSK-AES256-CCM8"
# define TLS1_TXT_DHE_PSK_WITH_AES_128_CCM_8 "DHE-PSK-AES128-CCM8"
# define TLS1_TXT_DHE_PSK_WITH_AES_256_CCM_8 "DHE-PSK-AES256-CCM8"
/* CCM ciphersuites from RFC7251 */
# define TLS1_TXT_ECDHE_ECDSA_WITH_AES_128_CCM "ECDHE-ECDSA-AES128-CCM"
# define TLS1_TXT_ECDHE_ECDSA_WITH_AES_256_CCM "ECDHE-ECDSA-AES256-CCM"
# define TLS1_TXT_ECDHE_ECDSA_WITH_AES_128_CCM_8 "ECDHE-ECDSA-AES128-CCM8"
# define TLS1_TXT_ECDHE_ECDSA_WITH_AES_256_CCM_8 "ECDHE-ECDSA-AES256-CCM8"
/* ECDH HMAC based ciphersuites from RFC5289 */
# define TLS1_TXT_ECDHE_ECDSA_WITH_AES_128_SHA256 "ECDHE-ECDSA-AES128-SHA256"
# define TLS1_TXT_ECDHE_ECDSA_WITH_AES_256_SHA384 "ECDHE-ECDSA-AES256-SHA384"
# define TLS1_TXT_ECDH_ECDSA_WITH_AES_128_SHA256 "ECDH-ECDSA-AES128-SHA256"
# define TLS1_TXT_ECDH_ECDSA_WITH_AES_256_SHA384 "ECDH-ECDSA-AES256-SHA384"
# define TLS1_TXT_ECDHE_RSA_WITH_AES_128_SHA256 "ECDHE-RSA-AES128-SHA256"
# define TLS1_TXT_ECDHE_RSA_WITH_AES_256_SHA384 "ECDHE-RSA-AES256-SHA384"
# define TLS1_TXT_ECDH_RSA_WITH_AES_128_SHA256 "ECDH-RSA-AES128-SHA256"
# define TLS1_TXT_ECDH_RSA_WITH_AES_256_SHA384 "ECDH-RSA-AES256-SHA384"
/* ECDH GCM based ciphersuites from RFC5289 */
# define TLS1_TXT_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 "ECDHE-ECDSA-AES128-GCM-SHA256"
# define TLS1_TXT_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 "ECDHE-ECDSA-AES256-GCM-SHA384"
# define TLS1_TXT_ECDH_ECDSA_WITH_AES_128_GCM_SHA256 "ECDH-ECDSA-AES128-GCM-SHA256"
# define TLS1_TXT_ECDH_ECDSA_WITH_AES_256_GCM_SHA384 "ECDH-ECDSA-AES256-GCM-SHA384"
# define TLS1_TXT_ECDHE_RSA_WITH_AES_128_GCM_SHA256 "ECDHE-RSA-AES128-GCM-SHA256"
# define TLS1_TXT_ECDHE_RSA_WITH_AES_256_GCM_SHA384 "ECDHE-RSA-AES256-GCM-SHA384"
# define TLS1_TXT_ECDH_RSA_WITH_AES_128_GCM_SHA256 "ECDH-RSA-AES128-GCM-SHA256"
# define TLS1_TXT_ECDH_RSA_WITH_AES_256_GCM_SHA384 "ECDH-RSA-AES256-GCM-SHA384"
/* TLS v1.2 PSK GCM ciphersuites from RFC5487 */
# define TLS1_TXT_PSK_WITH_AES_128_GCM_SHA256 "PSK-AES128-GCM-SHA256"
# define TLS1_TXT_PSK_WITH_AES_256_GCM_SHA384 "PSK-AES256-GCM-SHA384"
/* ECDHE PSK ciphersuites from RFC 5489 */
# define TLS1_TXT_ECDHE_PSK_WITH_RC4_128_SHA "ECDHE-PSK-RC4-SHA"
# define TLS1_TXT_ECDHE_PSK_WITH_3DES_EDE_CBC_SHA "ECDHE-PSK-3DES-EDE-CBC-SHA"
# define TLS1_TXT_ECDHE_PSK_WITH_AES_128_CBC_SHA "ECDHE-PSK-AES128-CBC-SHA"
# define TLS1_TXT_ECDHE_PSK_WITH_AES_256_CBC_SHA "ECDHE-PSK-AES256-CBC-SHA"
# define TLS1_TXT_ECDHE_PSK_WITH_AES_128_CBC_SHA256 "ECDHE-PSK-AES128-CBC-SHA256"
# define TLS1_TXT_ECDHE_PSK_WITH_AES_256_CBC_SHA384 "ECDHE-PSK-AES256-CBC-SHA384"
# define TLS1_TXT_ECDHE_PSK_WITH_NULL_SHA "ECDHE-PSK-NULL-SHA"
# define TLS1_TXT_ECDHE_PSK_WITH_NULL_SHA256 "ECDHE-PSK-NULL-SHA256"
# define TLS1_TXT_ECDHE_PSK_WITH_NULL_SHA384 "ECDHE-PSK-NULL-SHA384"
/* Camellia-CBC ciphersuites from RFC6367 */
# define TLS1_TXT_ECDHE_ECDSA_WITH_CAMELLIA_128_CBC_SHA256 "ECDHE-ECDSA-CAMELLIA128-SHA256"
# define TLS1_TXT_ECDHE_ECDSA_WITH_CAMELLIA_256_CBC_SHA384 "ECDHE-ECDSA-CAMELLIA256-SHA384"
# define TLS1_TXT_ECDH_ECDSA_WITH_CAMELLIA_128_CBC_SHA256 "ECDH-ECDSA-CAMELLIA128-SHA256"
# define TLS1_TXT_ECDH_ECDSA_WITH_CAMELLIA_256_CBC_SHA384 "ECDH-ECDSA-CAMELLIA256-SHA384"
# define TLS1_TXT_ECDHE_RSA_WITH_CAMELLIA_128_CBC_SHA256 "ECDHE-RSA-CAMELLIA128-SHA256"
# define TLS1_TXT_ECDHE_RSA_WITH_CAMELLIA_256_CBC_SHA384 "ECDHE-RSA-CAMELLIA256-SHA384"
# define TLS1_TXT_ECDH_RSA_WITH_CAMELLIA_128_CBC_SHA256 "ECDH-RSA-CAMELLIA128-SHA256"
# define TLS1_TXT_ECDH_RSA_WITH_CAMELLIA_256_CBC_SHA384 "ECDH-RSA-CAMELLIA256-SHA384"
/* draft-ietf-tls-chacha20-poly1305-03 */
# define TLS1_TXT_ECDHE_RSA_WITH_CHACHA20_POLY1305 "ECDHE-RSA-CHACHA20-POLY1305"
# define TLS1_TXT_ECDHE_ECDSA_WITH_CHACHA20_POLY1305 "ECDHE-ECDSA-CHACHA20-POLY1305"
# define TLS1_TXT_DHE_RSA_WITH_CHACHA20_POLY1305 "DHE-RSA-CHACHA20-POLY1305"
# define TLS1_TXT_PSK_WITH_CHACHA20_POLY1305 "PSK-CHACHA20-POLY1305"
# define TLS1_TXT_ECDHE_PSK_WITH_CHACHA20_POLY1305 "ECDHE-PSK-CHACHA20-POLY1305"
# define TLS1_TXT_DHE_PSK_WITH_CHACHA20_POLY1305 "DHE-PSK-CHACHA20-POLY1305"
# define TLS1_TXT_RSA_PSK_WITH_CHACHA20_POLY1305 "RSA-PSK-CHACHA20-POLY1305"
/* Aria ciphersuites from RFC6209 */
# define TLS1_TXT_RSA_WITH_ARIA_128_GCM_SHA256 "ARIA128-GCM-SHA256"
# define TLS1_TXT_RSA_WITH_ARIA_256_GCM_SHA384 "ARIA256-GCM-SHA384"
# define TLS1_TXT_DHE_RSA_WITH_ARIA_128_GCM_SHA256 "DHE-RSA-ARIA128-GCM-SHA256"
# define TLS1_TXT_DHE_RSA_WITH_ARIA_256_GCM_SHA384 "DHE-RSA-ARIA256-GCM-SHA384"
# define TLS1_TXT_DH_RSA_WITH_ARIA_128_GCM_SHA256 "DH-RSA-ARIA128-GCM-SHA256"
# define TLS1_TXT_DH_RSA_WITH_ARIA_256_GCM_SHA384 "DH-RSA-ARIA256-GCM-SHA384"
# define TLS1_TXT_DHE_DSS_WITH_ARIA_128_GCM_SHA256 "DHE-DSS-ARIA128-GCM-SHA256"
# define TLS1_TXT_DHE_DSS_WITH_ARIA_256_GCM_SHA384 "DHE-DSS-ARIA256-GCM-SHA384"
# define TLS1_TXT_DH_DSS_WITH_ARIA_128_GCM_SHA256 "DH-DSS-ARIA128-GCM-SHA256"
# define TLS1_TXT_DH_DSS_WITH_ARIA_256_GCM_SHA384 "DH-DSS-ARIA256-GCM-SHA384"
# define TLS1_TXT_DH_anon_WITH_ARIA_128_GCM_SHA256 "ADH-ARIA128-GCM-SHA256"
# define TLS1_TXT_DH_anon_WITH_ARIA_256_GCM_SHA384 "ADH-ARIA256-GCM-SHA384"
# define TLS1_TXT_ECDHE_ECDSA_WITH_ARIA_128_GCM_SHA256 "ECDHE-ECDSA-ARIA128-GCM-SHA256"
# define TLS1_TXT_ECDHE_ECDSA_WITH_ARIA_256_GCM_SHA384 "ECDHE-ECDSA-ARIA256-GCM-SHA384"
# define TLS1_TXT_ECDH_ECDSA_WITH_ARIA_128_GCM_SHA256 "ECDH-ECDSA-ARIA128-GCM-SHA256"
# define TLS1_TXT_ECDH_ECDSA_WITH_ARIA_256_GCM_SHA384 "ECDH-ECDSA-ARIA256-GCM-SHA384"
# define TLS1_TXT_ECDHE_RSA_WITH_ARIA_128_GCM_SHA256 "ECDHE-ARIA128-GCM-SHA256"
# define TLS1_TXT_ECDHE_RSA_WITH_ARIA_256_GCM_SHA384 "ECDHE-ARIA256-GCM-SHA384"
# define TLS1_TXT_ECDH_RSA_WITH_ARIA_128_GCM_SHA256 "ECDH-ARIA128-GCM-SHA256"
# define TLS1_TXT_ECDH_RSA_WITH_ARIA_256_GCM_SHA384 "ECDH-ARIA256-GCM-SHA384"
# define TLS1_TXT_PSK_WITH_ARIA_128_GCM_SHA256 "PSK-ARIA128-GCM-SHA256"
# define TLS1_TXT_PSK_WITH_ARIA_256_GCM_SHA384 "PSK-ARIA256-GCM-SHA384"
# define TLS1_TXT_DHE_PSK_WITH_ARIA_128_GCM_SHA256 "DHE-PSK-ARIA128-GCM-SHA256"
# define TLS1_TXT_DHE_PSK_WITH_ARIA_256_GCM_SHA384 "DHE-PSK-ARIA256-GCM-SHA384"
# define TLS1_TXT_RSA_PSK_WITH_ARIA_128_GCM_SHA256 "RSA-PSK-ARIA128-GCM-SHA256"
# define TLS1_TXT_RSA_PSK_WITH_ARIA_256_GCM_SHA384 "RSA-PSK-ARIA256-GCM-SHA384"
# define TLS_CT_RSA_SIGN 1
# define TLS_CT_DSS_SIGN 2
# define TLS_CT_RSA_FIXED_DH 3
# define TLS_CT_DSS_FIXED_DH 4
# define TLS_CT_ECDSA_SIGN 64
# define TLS_CT_RSA_FIXED_ECDH 65
# define TLS_CT_ECDSA_FIXED_ECDH 66
# define TLS_CT_GOST01_SIGN 22
# define TLS_CT_GOST12_IANA_SIGN 67
# define TLS_CT_GOST12_IANA_512_SIGN 68
# define TLS_CT_GOST12_LEGACY_SIGN 238
# define TLS_CT_GOST12_LEGACY_512_SIGN 239
# ifndef OPENSSL_NO_DEPRECATED_3_0
# define TLS_CT_GOST12_SIGN TLS_CT_GOST12_LEGACY_SIGN
# define TLS_CT_GOST12_512_SIGN TLS_CT_GOST12_LEGACY_512_SIGN
# endif
/*
* when correcting this number, correct also SSL3_CT_NUMBER in ssl3.h (see
* comment there)
*/
# define TLS_CT_NUMBER 12
# if defined(SSL3_CT_NUMBER)
# if TLS_CT_NUMBER != SSL3_CT_NUMBER
# error "SSL/TLS CT_NUMBER values do not match"
# endif
# endif
# define TLS1_FINISH_MAC_LENGTH 12
# define TLS_MD_MAX_CONST_SIZE 22
# define TLS_MD_CLIENT_FINISH_CONST "client finished"
# define TLS_MD_CLIENT_FINISH_CONST_SIZE 15
# define TLS_MD_SERVER_FINISH_CONST "server finished"
# define TLS_MD_SERVER_FINISH_CONST_SIZE 15
# define TLS_MD_KEY_EXPANSION_CONST "key expansion"
# define TLS_MD_KEY_EXPANSION_CONST_SIZE 13
# define TLS_MD_CLIENT_WRITE_KEY_CONST "client write key"
# define TLS_MD_CLIENT_WRITE_KEY_CONST_SIZE 16
# define TLS_MD_SERVER_WRITE_KEY_CONST "server write key"
# define TLS_MD_SERVER_WRITE_KEY_CONST_SIZE 16
# define TLS_MD_IV_BLOCK_CONST "IV block"
# define TLS_MD_IV_BLOCK_CONST_SIZE 8
# define TLS_MD_MASTER_SECRET_CONST "master secret"
# define TLS_MD_MASTER_SECRET_CONST_SIZE 13
# define TLS_MD_EXTENDED_MASTER_SECRET_CONST "extended master secret"
# define TLS_MD_EXTENDED_MASTER_SECRET_CONST_SIZE 22
# ifdef CHARSET_EBCDIC
# undef TLS_MD_CLIENT_FINISH_CONST
/*
* client finished
*/
# define TLS_MD_CLIENT_FINISH_CONST "\x63\x6c\x69\x65\x6e\x74\x20\x66\x69\x6e\x69\x73\x68\x65\x64"
# undef TLS_MD_SERVER_FINISH_CONST
/*
* server finished
*/
# define TLS_MD_SERVER_FINISH_CONST "\x73\x65\x72\x76\x65\x72\x20\x66\x69\x6e\x69\x73\x68\x65\x64"
# undef TLS_MD_SERVER_WRITE_KEY_CONST
/*
* server write key
*/
# define TLS_MD_SERVER_WRITE_KEY_CONST "\x73\x65\x72\x76\x65\x72\x20\x77\x72\x69\x74\x65\x20\x6b\x65\x79"
# undef TLS_MD_KEY_EXPANSION_CONST
/*
* key expansion
*/
# define TLS_MD_KEY_EXPANSION_CONST "\x6b\x65\x79\x20\x65\x78\x70\x61\x6e\x73\x69\x6f\x6e"
# undef TLS_MD_CLIENT_WRITE_KEY_CONST
/*
* client write key
*/
# define TLS_MD_CLIENT_WRITE_KEY_CONST "\x63\x6c\x69\x65\x6e\x74\x20\x77\x72\x69\x74\x65\x20\x6b\x65\x79"
# undef TLS_MD_SERVER_WRITE_KEY_CONST
/*
* server write key
*/
# define TLS_MD_SERVER_WRITE_KEY_CONST "\x73\x65\x72\x76\x65\x72\x20\x77\x72\x69\x74\x65\x20\x6b\x65\x79"
# undef TLS_MD_IV_BLOCK_CONST
/*
* IV block
*/
# define TLS_MD_IV_BLOCK_CONST "\x49\x56\x20\x62\x6c\x6f\x63\x6b"
# undef TLS_MD_MASTER_SECRET_CONST
/*
* master secret
*/
# define TLS_MD_MASTER_SECRET_CONST "\x6d\x61\x73\x74\x65\x72\x20\x73\x65\x63\x72\x65\x74"
# undef TLS_MD_EXTENDED_MASTER_SECRET_CONST
/*
* extended master secret
*/
# define TLS_MD_EXTENDED_MASTER_SECRET_CONST "\x65\x78\x74\x65\x6e\x64\x65\x64\x20\x6d\x61\x73\x74\x65\x72\x20\x73\x65\x63\x72\x65\x74"
# endif
/* TLS Session Ticket extension struct */
struct tls_session_ticket_ext_st {
unsigned short length;
void *data;
};
#ifdef __cplusplus
}
#endif
#endif
diff --git a/crypto/openssl/providers/fips-sources.checksums b/crypto/openssl/providers/fips-sources.checksums
index 1a6e37329763..2075eca274d6 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
2eef5f20f1410b48bdaaafa24ded24f56f34c4ca79db1d38fa6bf1b3b19535bf crypto/aes/asm/aes-armv4.pl
38c2cf8ed3910efd89d8721e1b0763a8fde073b91f6529d251165a0496ef9555 crypto/aes/asm/aes-c64xplus.pl
00196f01f5218ad731e6a058d406078f7228a9756d9d73f51c0d0c2a68f885af crypto/aes/asm/aes-ia64.S
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
30103cfe3b29d06b34feff48a927e0fa649e9109d35a3db64b09cfeb15426fa2 crypto/aes/asm/aesni-x86_64.pl
-67c73dbf78b5f3c8a436800dc43bf122cd1f0c4fefab357359edaae4fbb27e8e crypto/aes/asm/aesp8-ppc.pl
+f3490c936a80e012c49e577ec6e1d4d36df324dfef6264e788e6225e20b5fd52 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
47bedbe6a04254eede121e71f11a657b1f1940aee1916bbfc04fa9fb8454f9b8 crypto/aes/asm/vpaes-x86_64.pl
1c9a2a0e8cee4a1283c74b2e306f46f79890f6d236394de2a80d1994fd411d1d crypto/alphacpuid.pl
7a37cadacdbecb50304228dfcb087ad7fbb6e31f6ab69c52dd161e79afb2f9ca crypto/arm64cpuid.pl
e0daf54f72dd8fd1bc537d93f34e2a6a887a9ed6027bb33e15a327ef5ff37a42 crypto/armcap.c
24cc7611225df0e20e414c14e80516c36d48bf99659946e85a876d8757356686 crypto/armv4cpuid.pl
16739d54200fb81ca7835b5814f965022a2ab41589c7787e2697e3ea72d4fafa crypto/asn1_dsa.c
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
10fb73a6cc1bc064ebdcf6d7fe3c7407ea1c28b0d65ad0123046f8b1518fa75a crypto/bn/asm/c64xplus-gf2m.pl
c86664fb974362ee52a454c83c2c4b23fd5b7d64b3c9e23ef1e0dfd130a46ee5 crypto/bn/asm/co-586.pl
b88190d748056e6a64988bf1a3d19efc4c292e3d338a65f4505cf769a2041077 crypto/bn/asm/ia64-mont.pl
a511aafbf76647a0c83705d4491c898a5584d300aa449fa6166c8803372946eb crypto/bn/asm/ia64.S
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
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
87d49e83a7df467097fdfc577aa206be9ee622c40fcbbbe5133b35d9783b7816 crypto/bn/asm/sparct4-mont.pl
ca21a9ccbc54e19fb7c2e6cdf286ce7cb08b0fba960c777c6edce5c57ccc2101 crypto/bn/asm/sparcv8.S
fbc93c8dbbecefe66086f58fe9719ed87b13b2cdc61454a10e841228296fecef crypto/bn/asm/sparcv8plus.S
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
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
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
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
71186d5bd40d467a919e6449d8aa23d13df88e0c85765d1a165f3eeec6bd33a7 crypto/bn/bn_rand.c
4df8f204c8a06de2b4395be613ca0b9943613c523586e2005876d5c7bb891c75 crypto/bn/bn_recp.c
a5c5c9f99961a5a7f22a3dcdce964c8a330f822be17f08652223a20fed747d0a crypto/bn/bn_rsa_fips186_4.c
6889866bca4673bccb8adf870859a867757ccd3c8ad4652675615afff710add3 crypto/bn/bn_shift.c
622e90766b29e0d25f46474429aebda8eba2246835b9e85dc26da7cdbd49334f crypto/bn/bn_sqr.c
42c8ce944c889abcfcf089d0ad2744b7587696d8d7785efa91b3f7ec53dc062a crypto/bn/bn_sqrt.c
24e62baa56e02f2db6454e10168b7c7fa7638db9221b9acda1803d43f38f36e0 crypto/bn/bn_word.c
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
d2bfdfd96b182741d2d51f91478ffcc48491b0da44662bc1c32bc506b3eef1ba crypto/c64xpluscpuid.pl
0e1a41a2d81b5765bca3df448f60bf1fad91e485fe89dd65a7300ffc419e316d crypto/cmac/cmac.c
-ff9be205d6d7ff00b0e64508f0eb8d9ec0415fbabc0948d26e308212b3f7b2d8 crypto/context.c
+5113d8d12d884f845cad3d35d92f0a1ee20ebafd7a169273642f4e8178711de9 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
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
196dc024873e413d92672c3a9b6c062ed6269250b0da6d41c0da1c03cfec9ef8 crypto/dsa/dsa_ossl.c
9f501a59c09fc3cb3caafaff25abd44397a94d1062950a4d62e855d2c8986b5a crypto/dsa/dsa_sign.c
53fa10cc87ac63e35df661882852dc46ae68e6fee83b842f1aeefe00b8900ee1 crypto/dsa/dsa_vrf.c
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
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
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
-031f99c746ac746c1d4f243dd71c8246b502ff00c1d7ca29f7ca024f0e37e14a crypto/ec/ecdsa_ossl.c
+2e00c2e0e6f6d58b81fc23fe500f59e98793dc828ca87d64eba10cc0fddd0dc1 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
+8f9e9da65ab1d0fb3feae5abd6b5c3649d3a4d03e936bb7624a431080de181ae 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
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
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
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
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
-fecd75b0e1646fb18eeb6b1f528015296157a9bcf97191d0f32b9619aa4f0ffb crypto/o_str.c
+abba788a11469f5c01c766fdac64eccd4fb598b2d4d9a12efb086ae87009acb8 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
826a78afb376cbf1e87f12a2a67eef2ee47059a0fd3f9cba7ce7f035e34f8052 crypto/ppccpuid.pl
b4d34272a0bd1fbe6562022bf7ea6259b6a5a021a48222d415be47ef5ef2a905 crypto/property/defn_cache.c
-3c4ade2fed4605e374d85ec1134a98da34e7124f89f44b81a754e8cfe81f14ba crypto/property/property.c
+c3709986fd2ab18f3c6136d8dd7705a4538986aa789ceafe770c3a376db3c569 crypto/property/property.c
66da4f28d408133fb544b14aeb9ad4913e7c5c67e2826e53f0dc5bf4d8fada26 crypto/property/property_local.h
b0b382ce829192d2537561cfb0fb5c7afb04305f321f7b3c91441b4ba99b9c92 crypto/property/property_parse.c
a7cefda6a117550e2c76e0f307565ce1e11640b11ba10c80e469a837fd1212a3 crypto/property/property_query.c
065698c8d88a5facc0cbc02a3bd0c642c94687a8c5dd79901c942138b406067d crypto/property/property_string.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
+f733d03a7f633514bfb33862cd0fa46ac952a86f84000f109c0d37937bac9a1e 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
370d98549d4d98e04b60677b319b85904259359bd9401dd5385aa728278e6626 crypto/s390xcpuid.pl
5fa59240ca885cbc0c1cd026934b226d44fc9c3fdf0c2e7e3a7bd7f4963ca2e5 crypto/self_test_core.c
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
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
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
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
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
af0af59fe2cb8668a96751f343232d7faa3e7a937beb2bda09ed74fe60b9cb5f crypto/x86_64cpuid.pl
bbec287bb9bf35379885f8f8998b7fd9e8fc22efee9e1b299109af0f33a7ee16 crypto/x86cpuid.pl
acbb841170d4d3eb91d969be1c0e4973b1babfd5fcd76440b0628f509f82fd76 e_os.h
-6f353dc7c8c4d8f24f7ffbf920668ccb224ebb5810805a7c80d96770cd858005 include/crypto/aes_platform.h
+249a0e58e9692920eddc1ada2ac772a0cfd749cfbf618f2f5da08280df545d8f include/crypto/aes_platform.h
8c6f308c1ca774e6127e325c3b80511dbcdc99631f032694d8db53a5c02364ee include/crypto/asn1_dsa.h
-f6b01cff254311e973361190011cb6aa4d24b3a8c92f54e5191b7e2f669b8745 include/crypto/bn.h
+2e8c284672c4e8e395b3da56a3abf3e65bb4346313fb6f7358e925d077a2e1e2 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
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
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
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
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
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 7b84d2271d3a..cbd9c0951179 100644
--- a/crypto/openssl/providers/fips.checksum
+++ b/crypto/openssl/providers/fips.checksum
@@ -1 +1 @@
-4e1960f3d68410e8daf1893c9133ba9840912974ec65f885054c46b6bbeff5cd providers/fips-sources.checksums
+101807560af8f62c064ad796dfa1e4c269d45aaf5303b47ad0b25fdd6cc92466 providers/fips-sources.checksums
diff --git a/crypto/openssl/providers/implementations/encode_decode/decode_der2key.c b/crypto/openssl/providers/implementations/encode_decode/decode_der2key.c
index d598f7eba1ac..f2d9d8255648 100644
--- a/crypto/openssl/providers/implementations/encode_decode/decode_der2key.c
+++ b/crypto/openssl/providers/implementations/encode_decode/decode_der2key.c
@@ -1,797 +1,816 @@
/*
- * Copyright 2020-2023 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
*/
/*
* low level APIs are deprecated for public use, but still ok for
* internal use.
*/
#include "internal/deprecated.h"
#include <openssl/core_dispatch.h>
#include <openssl/core_names.h>
#include <openssl/core_object.h>
#include <openssl/crypto.h>
#include <openssl/err.h>
#include <openssl/params.h>
#include <openssl/pem.h> /* PEM_BUFSIZE and public PEM functions */
#include <openssl/pkcs12.h>
#include <openssl/x509.h>
#include <openssl/proverr.h>
#include "internal/cryptlib.h" /* ossl_assert() */
#include "internal/asn1.h"
#include "crypto/dh.h"
#include "crypto/dsa.h"
#include "crypto/ec.h"
#include "crypto/evp.h"
#include "crypto/ecx.h"
#include "crypto/rsa.h"
#include "crypto/x509.h"
+#include "openssl/obj_mac.h"
#include "prov/bio.h"
#include "prov/implementations.h"
#include "endecoder_local.h"
struct der2key_ctx_st; /* Forward declaration */
typedef int check_key_fn(void *, struct der2key_ctx_st *ctx);
typedef void adjust_key_fn(void *, struct der2key_ctx_st *ctx);
typedef void free_key_fn(void *);
typedef void *d2i_PKCS8_fn(void **, const unsigned char **, long,
struct der2key_ctx_st *);
struct keytype_desc_st {
const char *keytype_name;
const OSSL_DISPATCH *fns; /* Keymgmt (to pilfer functions from) */
/* The input structure name */
const char *structure_name;
/*
* The EVP_PKEY_xxx type macro. Should be zero for type specific
* structures, non-zero when the outermost structure is PKCS#8 or
* SubjectPublicKeyInfo. This determines which of the function
* pointers below will be used.
*/
int evp_type;
/* The selection mask for OSSL_FUNC_decoder_does_selection() */
int selection_mask;
/* For type specific decoders, we use the corresponding d2i */
d2i_of_void *d2i_private_key; /* From type-specific DER */
d2i_of_void *d2i_public_key; /* From type-specific DER */
d2i_of_void *d2i_key_params; /* From type-specific DER */
d2i_PKCS8_fn *d2i_PKCS8; /* Wrapped in a PrivateKeyInfo */
d2i_of_void *d2i_PUBKEY; /* Wrapped in a SubjectPublicKeyInfo */
/*
* For any key, we may need to check that the key meets expectations.
* This is useful when the same functions can decode several variants
* of a key.
*/
check_key_fn *check_key;
/*
* For any key, we may need to make provider specific adjustments, such
* as ensure the key carries the correct library context.
*/
adjust_key_fn *adjust_key;
/* {type}_free() */
free_key_fn *free_key;
};
/*
* Context used for DER to key decoding.
*/
struct der2key_ctx_st {
PROV_CTX *provctx;
const struct keytype_desc_st *desc;
/* The selection that is passed to der2key_decode() */
int selection;
/* Flag used to signal that a failure is fatal */
unsigned int flag_fatal : 1;
};
typedef void *key_from_pkcs8_t(const PKCS8_PRIV_KEY_INFO *p8inf,
OSSL_LIB_CTX *libctx, const char *propq);
static void *der2key_decode_p8(const unsigned char **input_der,
long input_der_len, struct der2key_ctx_st *ctx,
key_from_pkcs8_t *key_from_pkcs8)
{
PKCS8_PRIV_KEY_INFO *p8inf = NULL;
const X509_ALGOR *alg = NULL;
void *key = NULL;
if ((p8inf = d2i_PKCS8_PRIV_KEY_INFO(NULL, input_der, input_der_len)) != NULL
&& PKCS8_pkey_get0(NULL, NULL, NULL, &alg, p8inf)
- && OBJ_obj2nid(alg->algorithm) == ctx->desc->evp_type)
+ && (OBJ_obj2nid(alg->algorithm) == ctx->desc->evp_type
+ /* Allow decoding sm2 private key with id_ecPublicKey */
+ || (OBJ_obj2nid(alg->algorithm) == NID_X9_62_id_ecPublicKey
+ && ctx->desc->evp_type == NID_sm2)))
key = key_from_pkcs8(p8inf, PROV_LIBCTX_OF(ctx->provctx), NULL);
PKCS8_PRIV_KEY_INFO_free(p8inf);
return key;
}
/* ---------------------------------------------------------------------- */
static OSSL_FUNC_decoder_freectx_fn der2key_freectx;
static OSSL_FUNC_decoder_decode_fn der2key_decode;
static OSSL_FUNC_decoder_export_object_fn der2key_export_object;
static struct der2key_ctx_st *
der2key_newctx(void *provctx, const struct keytype_desc_st *desc)
{
struct der2key_ctx_st *ctx = OPENSSL_zalloc(sizeof(*ctx));
if (ctx != NULL) {
ctx->provctx = provctx;
ctx->desc = desc;
}
return ctx;
}
static void der2key_freectx(void *vctx)
{
struct der2key_ctx_st *ctx = vctx;
OPENSSL_free(ctx);
}
static int der2key_check_selection(int selection,
const struct keytype_desc_st *desc)
{
/*
* The selections are kinda sorta "levels", i.e. each selection given
* here is assumed to include those following.
*/
int checks[] = {
OSSL_KEYMGMT_SELECT_PRIVATE_KEY,
OSSL_KEYMGMT_SELECT_PUBLIC_KEY,
OSSL_KEYMGMT_SELECT_ALL_PARAMETERS
};
size_t i;
/* The decoder implementations made here support guessing */
if (selection == 0)
return 1;
for (i = 0; i < OSSL_NELEM(checks); i++) {
int check1 = (selection & checks[i]) != 0;
int check2 = (desc->selection_mask & checks[i]) != 0;
/*
* If the caller asked for the currently checked bit(s), return
* whether the decoder description says it's supported.
*/
if (check1)
return check2;
}
/* This should be dead code, but just to be safe... */
return 0;
}
static int der2key_decode(void *vctx, OSSL_CORE_BIO *cin, int selection,
OSSL_CALLBACK *data_cb, void *data_cbarg,
OSSL_PASSPHRASE_CALLBACK *pw_cb, void *pw_cbarg)
{
struct der2key_ctx_st *ctx = vctx;
unsigned char *der = NULL;
const unsigned char *derp;
long der_len = 0;
void *key = NULL;
int ok = 0;
ctx->selection = selection;
/*
* The caller is allowed to specify 0 as a selection mark, to have the
* structure and key type guessed. For type-specific structures, this
* is not recommended, as some structures are very similar.
* Note that 0 isn't the same as OSSL_KEYMGMT_SELECT_ALL, as the latter
* signifies a private key structure, where everything else is assumed
* to be present as well.
*/
if (selection == 0)
selection = ctx->desc->selection_mask;
if ((selection & ctx->desc->selection_mask) == 0) {
ERR_raise(ERR_LIB_PROV, ERR_R_PASSED_INVALID_ARGUMENT);
return 0;
}
ok = ossl_read_der(ctx->provctx, cin, &der, &der_len);
if (!ok)
goto next;
ok = 0; /* Assume that we fail */
ERR_set_mark();
if ((selection & OSSL_KEYMGMT_SELECT_PRIVATE_KEY) != 0) {
derp = der;
if (ctx->desc->d2i_PKCS8 != NULL) {
key = ctx->desc->d2i_PKCS8(NULL, &derp, der_len, ctx);
if (ctx->flag_fatal) {
ERR_clear_last_mark();
goto end;
}
} else if (ctx->desc->d2i_private_key != NULL) {
key = ctx->desc->d2i_private_key(NULL, &derp, der_len);
}
if (key == NULL && ctx->selection != 0) {
ERR_clear_last_mark();
goto next;
}
}
if (key == NULL && (selection & OSSL_KEYMGMT_SELECT_PUBLIC_KEY) != 0) {
derp = der;
if (ctx->desc->d2i_PUBKEY != NULL)
key = ctx->desc->d2i_PUBKEY(NULL, &derp, der_len);
else if (ctx->desc->d2i_public_key != NULL)
key = ctx->desc->d2i_public_key(NULL, &derp, der_len);
if (key == NULL && ctx->selection != 0) {
ERR_clear_last_mark();
goto next;
}
}
if (key == NULL && (selection & OSSL_KEYMGMT_SELECT_ALL_PARAMETERS) != 0) {
derp = der;
if (ctx->desc->d2i_key_params != NULL)
key = ctx->desc->d2i_key_params(NULL, &derp, der_len);
if (key == NULL && ctx->selection != 0) {
ERR_clear_last_mark();
goto next;
}
}
if (key == NULL)
ERR_clear_last_mark();
else
ERR_pop_to_mark();
/*
* Last minute check to see if this was the correct type of key. This
* should never lead to a fatal error, i.e. the decoding itself was
* correct, it was just an unexpected key type. This is generally for
* classes of key types that have subtle variants, like RSA-PSS keys as
* opposed to plain RSA keys.
*/
if (key != NULL
&& ctx->desc->check_key != NULL
&& !ctx->desc->check_key(key, ctx)) {
ctx->desc->free_key(key);
key = NULL;
}
if (key != NULL && ctx->desc->adjust_key != NULL)
ctx->desc->adjust_key(key, ctx);
next:
/*
* Indicated that we successfully decoded something, or not at all.
* Ending up "empty handed" is not an error.
*/
ok = 1;
/*
* We free memory here so it's not held up during the callback, because
* we know the process is recursive and the allocated chunks of memory
* add up.
*/
OPENSSL_free(der);
der = NULL;
if (key != NULL) {
OSSL_PARAM params[4];
int object_type = OSSL_OBJECT_PKEY;
params[0] =
OSSL_PARAM_construct_int(OSSL_OBJECT_PARAM_TYPE, &object_type);
- params[1] =
- OSSL_PARAM_construct_utf8_string(OSSL_OBJECT_PARAM_DATA_TYPE,
- (char *)ctx->desc->keytype_name,
- 0);
+
+#ifndef OPENSSL_NO_SM2
+ if (strcmp(ctx->desc->keytype_name, "EC") == 0
+ && (EC_KEY_get_flags(key) & EC_FLAG_SM2_RANGE) != 0)
+ params[1] =
+ OSSL_PARAM_construct_utf8_string(OSSL_OBJECT_PARAM_DATA_TYPE,
+ "SM2", 0);
+ else
+#endif
+ params[1] =
+ OSSL_PARAM_construct_utf8_string(OSSL_OBJECT_PARAM_DATA_TYPE,
+ (char *)ctx->desc->keytype_name,
+ 0);
/* The address of the key becomes the octet string */
params[2] =
OSSL_PARAM_construct_octet_string(OSSL_OBJECT_PARAM_REFERENCE,
&key, sizeof(key));
params[3] = OSSL_PARAM_construct_end();
ok = data_cb(params, data_cbarg);
}
end:
ctx->desc->free_key(key);
OPENSSL_free(der);
return ok;
}
static int der2key_export_object(void *vctx,
const void *reference, size_t reference_sz,
OSSL_CALLBACK *export_cb, void *export_cbarg)
{
struct der2key_ctx_st *ctx = vctx;
OSSL_FUNC_keymgmt_export_fn *export =
ossl_prov_get_keymgmt_export(ctx->desc->fns);
void *keydata;
if (reference_sz == sizeof(keydata) && export != NULL) {
int selection = ctx->selection;
if (selection == 0)
selection = OSSL_KEYMGMT_SELECT_ALL;
/* The contents of the reference is the address to our object */
keydata = *(void **)reference;
return export(keydata, selection, export_cb, export_cbarg);
}
return 0;
}
/* ---------------------------------------------------------------------- */
#ifndef OPENSSL_NO_DH
# define dh_evp_type EVP_PKEY_DH
# define dh_d2i_private_key NULL
# define dh_d2i_public_key NULL
# define dh_d2i_key_params (d2i_of_void *)d2i_DHparams
static void *dh_d2i_PKCS8(void **key, const unsigned char **der, long der_len,
struct der2key_ctx_st *ctx)
{
return der2key_decode_p8(der, der_len, ctx,
(key_from_pkcs8_t *)ossl_dh_key_from_pkcs8);
}
# define dh_d2i_PUBKEY (d2i_of_void *)ossl_d2i_DH_PUBKEY
# define dh_free (free_key_fn *)DH_free
# define dh_check NULL
static void dh_adjust(void *key, struct der2key_ctx_st *ctx)
{
ossl_dh_set0_libctx(key, PROV_LIBCTX_OF(ctx->provctx));
}
# define dhx_evp_type EVP_PKEY_DHX
# define dhx_d2i_private_key NULL
# define dhx_d2i_public_key NULL
# define dhx_d2i_key_params (d2i_of_void *)d2i_DHxparams
# define dhx_d2i_PKCS8 dh_d2i_PKCS8
# define dhx_d2i_PUBKEY (d2i_of_void *)ossl_d2i_DHx_PUBKEY
# define dhx_free (free_key_fn *)DH_free
# define dhx_check NULL
# define dhx_adjust dh_adjust
#endif
/* ---------------------------------------------------------------------- */
#ifndef OPENSSL_NO_DSA
# define dsa_evp_type EVP_PKEY_DSA
# define dsa_d2i_private_key (d2i_of_void *)d2i_DSAPrivateKey
# define dsa_d2i_public_key (d2i_of_void *)d2i_DSAPublicKey
# define dsa_d2i_key_params (d2i_of_void *)d2i_DSAparams
static void *dsa_d2i_PKCS8(void **key, const unsigned char **der, long der_len,
struct der2key_ctx_st *ctx)
{
return der2key_decode_p8(der, der_len, ctx,
(key_from_pkcs8_t *)ossl_dsa_key_from_pkcs8);
}
# define dsa_d2i_PUBKEY (d2i_of_void *)ossl_d2i_DSA_PUBKEY
# define dsa_free (free_key_fn *)DSA_free
# define dsa_check NULL
static void dsa_adjust(void *key, struct der2key_ctx_st *ctx)
{
ossl_dsa_set0_libctx(key, PROV_LIBCTX_OF(ctx->provctx));
}
#endif
/* ---------------------------------------------------------------------- */
#ifndef OPENSSL_NO_EC
# define ec_evp_type EVP_PKEY_EC
# define ec_d2i_private_key (d2i_of_void *)d2i_ECPrivateKey
# define ec_d2i_public_key NULL
# define ec_d2i_key_params (d2i_of_void *)d2i_ECParameters
static void *ec_d2i_PKCS8(void **key, const unsigned char **der, long der_len,
struct der2key_ctx_st *ctx)
{
return der2key_decode_p8(der, der_len, ctx,
(key_from_pkcs8_t *)ossl_ec_key_from_pkcs8);
}
# define ec_d2i_PUBKEY (d2i_of_void *)d2i_EC_PUBKEY
# define ec_free (free_key_fn *)EC_KEY_free
static int ec_check(void *key, struct der2key_ctx_st *ctx)
{
/* We're trying to be clever by comparing two truths */
-
+ int ret = 0;
int sm2 = (EC_KEY_get_flags(key) & EC_FLAG_SM2_RANGE) != 0;
- return sm2 == (ctx->desc->evp_type == EVP_PKEY_SM2);
+ if (sm2)
+ ret = ctx->desc->evp_type == EVP_PKEY_SM2
+ || ctx->desc->evp_type == NID_X9_62_id_ecPublicKey;
+ else
+ ret = ctx->desc->evp_type != EVP_PKEY_SM2;
+
+ return ret;
}
static void ec_adjust(void *key, struct der2key_ctx_st *ctx)
{
ossl_ec_key_set0_libctx(key, PROV_LIBCTX_OF(ctx->provctx));
}
/*
* ED25519, ED448, X25519, X448 only implement PKCS#8 and SubjectPublicKeyInfo,
* so no d2i functions to be had.
*/
static void *ecx_d2i_PKCS8(void **key, const unsigned char **der, long der_len,
struct der2key_ctx_st *ctx)
{
return der2key_decode_p8(der, der_len, ctx,
(key_from_pkcs8_t *)ossl_ecx_key_from_pkcs8);
}
static void ecx_key_adjust(void *key, struct der2key_ctx_st *ctx)
{
ossl_ecx_key_set0_libctx(key, PROV_LIBCTX_OF(ctx->provctx));
}
# define ed25519_evp_type EVP_PKEY_ED25519
# define ed25519_d2i_private_key NULL
# define ed25519_d2i_public_key NULL
# define ed25519_d2i_key_params NULL
# define ed25519_d2i_PKCS8 ecx_d2i_PKCS8
# define ed25519_d2i_PUBKEY (d2i_of_void *)ossl_d2i_ED25519_PUBKEY
# define ed25519_free (free_key_fn *)ossl_ecx_key_free
# define ed25519_check NULL
# define ed25519_adjust ecx_key_adjust
# define ed448_evp_type EVP_PKEY_ED448
# define ed448_d2i_private_key NULL
# define ed448_d2i_public_key NULL
# define ed448_d2i_key_params NULL
# define ed448_d2i_PKCS8 ecx_d2i_PKCS8
# define ed448_d2i_PUBKEY (d2i_of_void *)ossl_d2i_ED448_PUBKEY
# define ed448_free (free_key_fn *)ossl_ecx_key_free
# define ed448_check NULL
# define ed448_adjust ecx_key_adjust
# define x25519_evp_type EVP_PKEY_X25519
# define x25519_d2i_private_key NULL
# define x25519_d2i_public_key NULL
# define x25519_d2i_key_params NULL
# define x25519_d2i_PKCS8 ecx_d2i_PKCS8
# define x25519_d2i_PUBKEY (d2i_of_void *)ossl_d2i_X25519_PUBKEY
# define x25519_free (free_key_fn *)ossl_ecx_key_free
# define x25519_check NULL
# define x25519_adjust ecx_key_adjust
# define x448_evp_type EVP_PKEY_X448
# define x448_d2i_private_key NULL
# define x448_d2i_public_key NULL
# define x448_d2i_key_params NULL
# define x448_d2i_PKCS8 ecx_d2i_PKCS8
# define x448_d2i_PUBKEY (d2i_of_void *)ossl_d2i_X448_PUBKEY
# define x448_free (free_key_fn *)ossl_ecx_key_free
# define x448_check NULL
# define x448_adjust ecx_key_adjust
# ifndef OPENSSL_NO_SM2
# define sm2_evp_type EVP_PKEY_SM2
# define sm2_d2i_private_key (d2i_of_void *)d2i_ECPrivateKey
# define sm2_d2i_public_key NULL
# define sm2_d2i_key_params (d2i_of_void *)d2i_ECParameters
static void *sm2_d2i_PKCS8(void **key, const unsigned char **der, long der_len,
struct der2key_ctx_st *ctx)
{
return der2key_decode_p8(der, der_len, ctx,
(key_from_pkcs8_t *)ossl_ec_key_from_pkcs8);
}
# define sm2_d2i_PUBKEY (d2i_of_void *)d2i_EC_PUBKEY
# define sm2_free (free_key_fn *)EC_KEY_free
# define sm2_check ec_check
# define sm2_adjust ec_adjust
# endif
#endif
/* ---------------------------------------------------------------------- */
#define rsa_evp_type EVP_PKEY_RSA
#define rsa_d2i_private_key (d2i_of_void *)d2i_RSAPrivateKey
#define rsa_d2i_public_key (d2i_of_void *)d2i_RSAPublicKey
#define rsa_d2i_key_params NULL
static void *rsa_d2i_PKCS8(void **key, const unsigned char **der, long der_len,
struct der2key_ctx_st *ctx)
{
return der2key_decode_p8(der, der_len, ctx,
(key_from_pkcs8_t *)ossl_rsa_key_from_pkcs8);
}
#define rsa_d2i_PUBKEY (d2i_of_void *)d2i_RSA_PUBKEY
#define rsa_free (free_key_fn *)RSA_free
static int rsa_check(void *key, struct der2key_ctx_st *ctx)
{
switch (RSA_test_flags(key, RSA_FLAG_TYPE_MASK)) {
case RSA_FLAG_TYPE_RSA:
return ctx->desc->evp_type == EVP_PKEY_RSA;
case RSA_FLAG_TYPE_RSASSAPSS:
return ctx->desc->evp_type == EVP_PKEY_RSA_PSS;
}
/* Currently unsupported RSA key type */
return 0;
}
static void rsa_adjust(void *key, struct der2key_ctx_st *ctx)
{
ossl_rsa_set0_libctx(key, PROV_LIBCTX_OF(ctx->provctx));
}
#define rsapss_evp_type EVP_PKEY_RSA_PSS
#define rsapss_d2i_private_key (d2i_of_void *)d2i_RSAPrivateKey
#define rsapss_d2i_public_key (d2i_of_void *)d2i_RSAPublicKey
#define rsapss_d2i_key_params NULL
#define rsapss_d2i_PKCS8 rsa_d2i_PKCS8
#define rsapss_d2i_PUBKEY (d2i_of_void *)d2i_RSA_PUBKEY
#define rsapss_free (free_key_fn *)RSA_free
#define rsapss_check rsa_check
#define rsapss_adjust rsa_adjust
/* ---------------------------------------------------------------------- */
/*
* The DO_ macros help define the selection mask and the method functions
* for each kind of object we want to decode.
*/
#define DO_type_specific_keypair(keytype) \
"type-specific", keytype##_evp_type, \
( OSSL_KEYMGMT_SELECT_KEYPAIR ), \
keytype##_d2i_private_key, \
keytype##_d2i_public_key, \
NULL, \
NULL, \
NULL, \
keytype##_check, \
keytype##_adjust, \
keytype##_free
#define DO_type_specific_pub(keytype) \
"type-specific", keytype##_evp_type, \
( OSSL_KEYMGMT_SELECT_PUBLIC_KEY ), \
NULL, \
keytype##_d2i_public_key, \
NULL, \
NULL, \
NULL, \
keytype##_check, \
keytype##_adjust, \
keytype##_free
#define DO_type_specific_priv(keytype) \
"type-specific", keytype##_evp_type, \
( OSSL_KEYMGMT_SELECT_PRIVATE_KEY ), \
keytype##_d2i_private_key, \
NULL, \
NULL, \
NULL, \
NULL, \
keytype##_check, \
keytype##_adjust, \
keytype##_free
#define DO_type_specific_params(keytype) \
"type-specific", keytype##_evp_type, \
( OSSL_KEYMGMT_SELECT_ALL_PARAMETERS ), \
NULL, \
NULL, \
keytype##_d2i_key_params, \
NULL, \
NULL, \
keytype##_check, \
keytype##_adjust, \
keytype##_free
#define DO_type_specific(keytype) \
"type-specific", keytype##_evp_type, \
( OSSL_KEYMGMT_SELECT_ALL ), \
keytype##_d2i_private_key, \
keytype##_d2i_public_key, \
keytype##_d2i_key_params, \
NULL, \
NULL, \
keytype##_check, \
keytype##_adjust, \
keytype##_free
#define DO_type_specific_no_pub(keytype) \
"type-specific", keytype##_evp_type, \
( OSSL_KEYMGMT_SELECT_PRIVATE_KEY \
| OSSL_KEYMGMT_SELECT_ALL_PARAMETERS ), \
keytype##_d2i_private_key, \
NULL, \
keytype##_d2i_key_params, \
NULL, \
NULL, \
keytype##_check, \
keytype##_adjust, \
keytype##_free
#define DO_PrivateKeyInfo(keytype) \
"PrivateKeyInfo", keytype##_evp_type, \
( OSSL_KEYMGMT_SELECT_PRIVATE_KEY ), \
NULL, \
NULL, \
NULL, \
keytype##_d2i_PKCS8, \
NULL, \
keytype##_check, \
keytype##_adjust, \
keytype##_free
#define DO_SubjectPublicKeyInfo(keytype) \
"SubjectPublicKeyInfo", keytype##_evp_type, \
( OSSL_KEYMGMT_SELECT_PUBLIC_KEY ), \
NULL, \
NULL, \
NULL, \
NULL, \
keytype##_d2i_PUBKEY, \
keytype##_check, \
keytype##_adjust, \
keytype##_free
#define DO_DH(keytype) \
"DH", keytype##_evp_type, \
( OSSL_KEYMGMT_SELECT_ALL_PARAMETERS ), \
NULL, \
NULL, \
keytype##_d2i_key_params, \
NULL, \
NULL, \
keytype##_check, \
keytype##_adjust, \
keytype##_free
#define DO_DHX(keytype) \
"DHX", keytype##_evp_type, \
( OSSL_KEYMGMT_SELECT_ALL_PARAMETERS ), \
NULL, \
NULL, \
keytype##_d2i_key_params, \
NULL, \
NULL, \
keytype##_check, \
keytype##_adjust, \
keytype##_free
#define DO_DSA(keytype) \
"DSA", keytype##_evp_type, \
( OSSL_KEYMGMT_SELECT_ALL ), \
keytype##_d2i_private_key, \
keytype##_d2i_public_key, \
keytype##_d2i_key_params, \
NULL, \
NULL, \
keytype##_check, \
keytype##_adjust, \
keytype##_free
#define DO_EC(keytype) \
"EC", keytype##_evp_type, \
( OSSL_KEYMGMT_SELECT_PRIVATE_KEY \
| OSSL_KEYMGMT_SELECT_ALL_PARAMETERS ), \
keytype##_d2i_private_key, \
NULL, \
keytype##_d2i_key_params, \
NULL, \
NULL, \
keytype##_check, \
keytype##_adjust, \
keytype##_free
#define DO_RSA(keytype) \
"RSA", keytype##_evp_type, \
( OSSL_KEYMGMT_SELECT_KEYPAIR ), \
keytype##_d2i_private_key, \
keytype##_d2i_public_key, \
NULL, \
NULL, \
NULL, \
keytype##_check, \
keytype##_adjust, \
keytype##_free
/*
* MAKE_DECODER is the single driver for creating OSSL_DISPATCH tables.
* It takes the following arguments:
*
* keytype_name The implementation key type as a string.
* keytype The implementation key type. This must correspond exactly
* to our existing keymgmt keytype names... in other words,
* there must exist an ossl_##keytype##_keymgmt_functions.
* type The type name for the set of functions that implement the
* decoder for the key type. This isn't necessarily the same
* as keytype. For example, the key types ed25519, ed448,
* x25519 and x448 are all handled by the same functions with
* the common type name ecx.
* kind The kind of support to implement. This translates into
* the DO_##kind macros above, to populate the keytype_desc_st
* structure.
*/
#define MAKE_DECODER(keytype_name, keytype, type, kind) \
static const struct keytype_desc_st kind##_##keytype##_desc = \
{ keytype_name, ossl_##keytype##_keymgmt_functions, \
DO_##kind(keytype) }; \
\
static OSSL_FUNC_decoder_newctx_fn kind##_der2##keytype##_newctx; \
\
static void *kind##_der2##keytype##_newctx(void *provctx) \
{ \
return der2key_newctx(provctx, &kind##_##keytype##_desc); \
} \
static int kind##_der2##keytype##_does_selection(void *provctx, \
int selection) \
{ \
return der2key_check_selection(selection, \
&kind##_##keytype##_desc); \
} \
const OSSL_DISPATCH \
ossl_##kind##_der_to_##keytype##_decoder_functions[] = { \
{ OSSL_FUNC_DECODER_NEWCTX, \
(void (*)(void))kind##_der2##keytype##_newctx }, \
{ OSSL_FUNC_DECODER_FREECTX, \
(void (*)(void))der2key_freectx }, \
{ OSSL_FUNC_DECODER_DOES_SELECTION, \
(void (*)(void))kind##_der2##keytype##_does_selection }, \
{ OSSL_FUNC_DECODER_DECODE, \
(void (*)(void))der2key_decode }, \
{ OSSL_FUNC_DECODER_EXPORT_OBJECT, \
(void (*)(void))der2key_export_object }, \
{ 0, NULL } \
}
#ifndef OPENSSL_NO_DH
MAKE_DECODER("DH", dh, dh, PrivateKeyInfo);
MAKE_DECODER("DH", dh, dh, SubjectPublicKeyInfo);
MAKE_DECODER("DH", dh, dh, type_specific_params);
MAKE_DECODER("DH", dh, dh, DH);
MAKE_DECODER("DHX", dhx, dhx, PrivateKeyInfo);
MAKE_DECODER("DHX", dhx, dhx, SubjectPublicKeyInfo);
MAKE_DECODER("DHX", dhx, dhx, type_specific_params);
MAKE_DECODER("DHX", dhx, dhx, DHX);
#endif
#ifndef OPENSSL_NO_DSA
MAKE_DECODER("DSA", dsa, dsa, PrivateKeyInfo);
MAKE_DECODER("DSA", dsa, dsa, SubjectPublicKeyInfo);
MAKE_DECODER("DSA", dsa, dsa, type_specific);
MAKE_DECODER("DSA", dsa, dsa, DSA);
#endif
#ifndef OPENSSL_NO_EC
MAKE_DECODER("EC", ec, ec, PrivateKeyInfo);
MAKE_DECODER("EC", ec, ec, SubjectPublicKeyInfo);
MAKE_DECODER("EC", ec, ec, type_specific_no_pub);
MAKE_DECODER("EC", ec, ec, EC);
MAKE_DECODER("X25519", x25519, ecx, PrivateKeyInfo);
MAKE_DECODER("X25519", x25519, ecx, SubjectPublicKeyInfo);
MAKE_DECODER("X448", x448, ecx, PrivateKeyInfo);
MAKE_DECODER("X448", x448, ecx, SubjectPublicKeyInfo);
MAKE_DECODER("ED25519", ed25519, ecx, PrivateKeyInfo);
MAKE_DECODER("ED25519", ed25519, ecx, SubjectPublicKeyInfo);
MAKE_DECODER("ED448", ed448, ecx, PrivateKeyInfo);
MAKE_DECODER("ED448", ed448, ecx, SubjectPublicKeyInfo);
# ifndef OPENSSL_NO_SM2
MAKE_DECODER("SM2", sm2, ec, PrivateKeyInfo);
MAKE_DECODER("SM2", sm2, ec, SubjectPublicKeyInfo);
# endif
#endif
MAKE_DECODER("RSA", rsa, rsa, PrivateKeyInfo);
MAKE_DECODER("RSA", rsa, rsa, SubjectPublicKeyInfo);
MAKE_DECODER("RSA", rsa, rsa, type_specific_keypair);
MAKE_DECODER("RSA", rsa, rsa, RSA);
MAKE_DECODER("RSA-PSS", rsapss, rsapss, PrivateKeyInfo);
MAKE_DECODER("RSA-PSS", rsapss, rsapss, SubjectPublicKeyInfo);
diff --git a/crypto/openssl/providers/implementations/rands/drbg.c b/crypto/openssl/providers/implementations/rands/drbg.c
index 41ff2a8e33f6..9ab18af900bc 100644
--- a/crypto/openssl/providers/implementations/rands/drbg.c
+++ b/crypto/openssl/providers/implementations/rands/drbg.c
@@ -1,935 +1,940 @@
/*
* 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
+ /*
+ * In normal use (i.e. OpenSSL's own uses), this is never called.
+ * Outside of the FIPS provider, OpenSSL sets its DRBGs up so that
+ * they always have a parent. This remains purely for legacy reasons.
+ */
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:
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/ssl/bio_ssl.c b/crypto/openssl/ssl/bio_ssl.c
index 401178f0c2e4..be3159b32a9f 100644
--- a/crypto/openssl/ssl/bio_ssl.c
+++ b/crypto/openssl/ssl/bio_ssl.c
@@ -1,506 +1,506 @@
/*
- * 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 <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <openssl/crypto.h>
#include "internal/bio.h"
#include <openssl/err.h>
#include "ssl_local.h"
static int ssl_write(BIO *h, const char *buf, size_t size, size_t *written);
static int ssl_read(BIO *b, char *buf, size_t size, size_t *readbytes);
static int ssl_puts(BIO *h, const char *str);
static long ssl_ctrl(BIO *h, int cmd, long arg1, void *arg2);
static int ssl_new(BIO *h);
static int ssl_free(BIO *data);
static long ssl_callback_ctrl(BIO *h, int cmd, BIO_info_cb *fp);
typedef struct bio_ssl_st {
SSL *ssl; /* The ssl handle :-) */
/* re-negotiate every time the total number of bytes is this size */
int num_renegotiates;
unsigned long renegotiate_count;
size_t byte_count;
unsigned long renegotiate_timeout;
unsigned long last_time;
} BIO_SSL;
static const BIO_METHOD methods_sslp = {
BIO_TYPE_SSL,
"ssl",
ssl_write,
NULL, /* ssl_write_old, */
ssl_read,
NULL, /* ssl_read_old, */
ssl_puts,
NULL, /* ssl_gets, */
ssl_ctrl,
ssl_new,
ssl_free,
ssl_callback_ctrl,
};
const BIO_METHOD *BIO_f_ssl(void)
{
return &methods_sslp;
}
static int ssl_new(BIO *bi)
{
BIO_SSL *bs = OPENSSL_zalloc(sizeof(*bs));
if (bs == NULL) {
ERR_raise(ERR_LIB_BIO, ERR_R_MALLOC_FAILURE);
return 0;
}
BIO_set_init(bi, 0);
BIO_set_data(bi, bs);
/* Clear all flags */
BIO_clear_flags(bi, ~0);
return 1;
}
static int ssl_free(BIO *a)
{
BIO_SSL *bs;
if (a == NULL)
return 0;
bs = BIO_get_data(a);
if (BIO_get_shutdown(a)) {
- if (bs->ssl != NULL)
+ if (bs->ssl != NULL && !SSL_in_init(bs->ssl))
SSL_shutdown(bs->ssl);
if (BIO_get_init(a))
SSL_free(bs->ssl);
BIO_clear_flags(a, ~0); /* Clear all flags */
BIO_set_init(a, 0);
}
OPENSSL_free(bs);
return 1;
}
static int ssl_read(BIO *b, char *buf, size_t size, size_t *readbytes)
{
int ret = 1;
BIO_SSL *sb;
SSL *ssl;
int retry_reason = 0;
int r = 0;
if (buf == NULL)
return 0;
sb = BIO_get_data(b);
ssl = sb->ssl;
BIO_clear_retry_flags(b);
ret = ssl_read_internal(ssl, buf, size, readbytes);
switch (SSL_get_error(ssl, ret)) {
case SSL_ERROR_NONE:
if (sb->renegotiate_count > 0) {
sb->byte_count += *readbytes;
if (sb->byte_count > sb->renegotiate_count) {
sb->byte_count = 0;
sb->num_renegotiates++;
SSL_renegotiate(ssl);
r = 1;
}
}
if ((sb->renegotiate_timeout > 0) && (!r)) {
unsigned long tm;
tm = (unsigned long)time(NULL);
if (tm > sb->last_time + sb->renegotiate_timeout) {
sb->last_time = tm;
sb->num_renegotiates++;
SSL_renegotiate(ssl);
}
}
break;
case SSL_ERROR_WANT_READ:
BIO_set_retry_read(b);
break;
case SSL_ERROR_WANT_WRITE:
BIO_set_retry_write(b);
break;
case SSL_ERROR_WANT_X509_LOOKUP:
BIO_set_retry_special(b);
retry_reason = BIO_RR_SSL_X509_LOOKUP;
break;
case SSL_ERROR_WANT_ACCEPT:
BIO_set_retry_special(b);
retry_reason = BIO_RR_ACCEPT;
break;
case SSL_ERROR_WANT_CONNECT:
BIO_set_retry_special(b);
retry_reason = BIO_RR_CONNECT;
break;
case SSL_ERROR_SYSCALL:
case SSL_ERROR_SSL:
case SSL_ERROR_ZERO_RETURN:
default:
break;
}
BIO_set_retry_reason(b, retry_reason);
return ret;
}
static int ssl_write(BIO *b, const char *buf, size_t size, size_t *written)
{
int ret, r = 0;
int retry_reason = 0;
SSL *ssl;
BIO_SSL *bs;
if (buf == NULL)
return 0;
bs = BIO_get_data(b);
ssl = bs->ssl;
BIO_clear_retry_flags(b);
ret = ssl_write_internal(ssl, buf, size, written);
switch (SSL_get_error(ssl, ret)) {
case SSL_ERROR_NONE:
if (bs->renegotiate_count > 0) {
bs->byte_count += *written;
if (bs->byte_count > bs->renegotiate_count) {
bs->byte_count = 0;
bs->num_renegotiates++;
SSL_renegotiate(ssl);
r = 1;
}
}
if ((bs->renegotiate_timeout > 0) && (!r)) {
unsigned long tm;
tm = (unsigned long)time(NULL);
if (tm > bs->last_time + bs->renegotiate_timeout) {
bs->last_time = tm;
bs->num_renegotiates++;
SSL_renegotiate(ssl);
}
}
break;
case SSL_ERROR_WANT_WRITE:
BIO_set_retry_write(b);
break;
case SSL_ERROR_WANT_READ:
BIO_set_retry_read(b);
break;
case SSL_ERROR_WANT_X509_LOOKUP:
BIO_set_retry_special(b);
retry_reason = BIO_RR_SSL_X509_LOOKUP;
break;
case SSL_ERROR_WANT_CONNECT:
BIO_set_retry_special(b);
retry_reason = BIO_RR_CONNECT;
case SSL_ERROR_SYSCALL:
case SSL_ERROR_SSL:
default:
break;
}
BIO_set_retry_reason(b, retry_reason);
return ret;
}
static long ssl_ctrl(BIO *b, int cmd, long num, void *ptr)
{
SSL **sslp, *ssl;
BIO_SSL *bs, *dbs;
BIO *dbio, *bio;
long ret = 1;
BIO *next;
bs = BIO_get_data(b);
next = BIO_next(b);
ssl = bs->ssl;
if ((ssl == NULL) && (cmd != BIO_C_SET_SSL))
return 0;
switch (cmd) {
case BIO_CTRL_RESET:
SSL_shutdown(ssl);
if (ssl->handshake_func == ssl->method->ssl_connect)
SSL_set_connect_state(ssl);
else if (ssl->handshake_func == ssl->method->ssl_accept)
SSL_set_accept_state(ssl);
if (!SSL_clear(ssl)) {
ret = 0;
break;
}
if (next != NULL)
ret = BIO_ctrl(next, cmd, num, ptr);
else if (ssl->rbio != NULL)
ret = BIO_ctrl(ssl->rbio, cmd, num, ptr);
else
ret = 1;
break;
case BIO_CTRL_INFO:
ret = 0;
break;
case BIO_C_SSL_MODE:
if (num) /* client mode */
SSL_set_connect_state(ssl);
else
SSL_set_accept_state(ssl);
break;
case BIO_C_SET_SSL_RENEGOTIATE_TIMEOUT:
ret = bs->renegotiate_timeout;
if (num < 60)
num = 5;
bs->renegotiate_timeout = (unsigned long)num;
bs->last_time = (unsigned long)time(NULL);
break;
case BIO_C_SET_SSL_RENEGOTIATE_BYTES:
ret = bs->renegotiate_count;
if ((long)num >= 512)
bs->renegotiate_count = (unsigned long)num;
break;
case BIO_C_GET_SSL_NUM_RENEGOTIATES:
ret = bs->num_renegotiates;
break;
case BIO_C_SET_SSL:
if (ssl != NULL) {
ssl_free(b);
if (!ssl_new(b))
return 0;
bs = BIO_get_data(b);
}
BIO_set_shutdown(b, num);
ssl = (SSL *)ptr;
bs->ssl = ssl;
bio = SSL_get_rbio(ssl);
if (bio != NULL) {
if (next != NULL)
BIO_push(bio, next);
BIO_set_next(b, bio);
BIO_up_ref(bio);
}
BIO_set_init(b, 1);
break;
case BIO_C_GET_SSL:
if (ptr != NULL) {
sslp = (SSL **)ptr;
*sslp = ssl;
} else
ret = 0;
break;
case BIO_CTRL_GET_CLOSE:
ret = BIO_get_shutdown(b);
break;
case BIO_CTRL_SET_CLOSE:
BIO_set_shutdown(b, (int)num);
break;
case BIO_CTRL_WPENDING:
ret = BIO_ctrl(ssl->wbio, cmd, num, ptr);
break;
case BIO_CTRL_PENDING:
ret = SSL_pending(ssl);
if (ret == 0)
ret = BIO_pending(ssl->rbio);
break;
case BIO_CTRL_FLUSH:
BIO_clear_retry_flags(b);
ret = BIO_ctrl(ssl->wbio, cmd, num, ptr);
BIO_copy_next_retry(b);
break;
case BIO_CTRL_PUSH:
if ((next != NULL) && (next != ssl->rbio)) {
/*
* We are going to pass ownership of next to the SSL object...but
* we don't own a reference to pass yet - so up ref
*/
BIO_up_ref(next);
SSL_set_bio(ssl, next, next);
}
break;
case BIO_CTRL_POP:
/* Only detach if we are the BIO explicitly being popped */
if (b == ptr) {
/* This will clear the reference we obtained during push */
SSL_set_bio(ssl, NULL, NULL);
}
break;
case BIO_C_DO_STATE_MACHINE:
BIO_clear_retry_flags(b);
BIO_set_retry_reason(b, 0);
ret = (int)SSL_do_handshake(ssl);
switch (SSL_get_error(ssl, (int)ret)) {
case SSL_ERROR_WANT_READ:
BIO_set_flags(b, BIO_FLAGS_READ | BIO_FLAGS_SHOULD_RETRY);
break;
case SSL_ERROR_WANT_WRITE:
BIO_set_flags(b, BIO_FLAGS_WRITE | BIO_FLAGS_SHOULD_RETRY);
break;
case SSL_ERROR_WANT_CONNECT:
BIO_set_flags(b, BIO_FLAGS_IO_SPECIAL | BIO_FLAGS_SHOULD_RETRY);
BIO_set_retry_reason(b, BIO_get_retry_reason(next));
break;
case SSL_ERROR_WANT_X509_LOOKUP:
BIO_set_retry_special(b);
BIO_set_retry_reason(b, BIO_RR_SSL_X509_LOOKUP);
break;
default:
break;
}
break;
case BIO_CTRL_DUP:
dbio = (BIO *)ptr;
dbs = BIO_get_data(dbio);
SSL_free(dbs->ssl);
dbs->ssl = SSL_dup(ssl);
dbs->num_renegotiates = bs->num_renegotiates;
dbs->renegotiate_count = bs->renegotiate_count;
dbs->byte_count = bs->byte_count;
dbs->renegotiate_timeout = bs->renegotiate_timeout;
dbs->last_time = bs->last_time;
ret = (dbs->ssl != NULL);
break;
case BIO_C_GET_FD:
ret = BIO_ctrl(ssl->rbio, cmd, num, ptr);
break;
case BIO_CTRL_SET_CALLBACK:
ret = 0; /* use callback ctrl */
break;
default:
ret = BIO_ctrl(ssl->rbio, cmd, num, ptr);
break;
}
return ret;
}
static long ssl_callback_ctrl(BIO *b, int cmd, BIO_info_cb *fp)
{
SSL *ssl;
BIO_SSL *bs;
long ret = 1;
bs = BIO_get_data(b);
ssl = bs->ssl;
switch (cmd) {
case BIO_CTRL_SET_CALLBACK:
ret = BIO_callback_ctrl(ssl->rbio, cmd, fp);
break;
default:
ret = 0;
break;
}
return ret;
}
static int ssl_puts(BIO *bp, const char *str)
{
int n, ret;
n = strlen(str);
ret = BIO_write(bp, str, n);
return ret;
}
BIO *BIO_new_buffer_ssl_connect(SSL_CTX *ctx)
{
#ifndef OPENSSL_NO_SOCK
BIO *ret = NULL, *buf = NULL, *ssl = NULL;
if ((buf = BIO_new(BIO_f_buffer())) == NULL)
return NULL;
if ((ssl = BIO_new_ssl_connect(ctx)) == NULL)
goto err;
if ((ret = BIO_push(buf, ssl)) == NULL)
goto err;
return ret;
err:
BIO_free(buf);
BIO_free(ssl);
#endif
return NULL;
}
BIO *BIO_new_ssl_connect(SSL_CTX *ctx)
{
#ifndef OPENSSL_NO_SOCK
BIO *ret = NULL, *con = NULL, *ssl = NULL;
if ((con = BIO_new(BIO_s_connect())) == NULL)
return NULL;
if ((ssl = BIO_new_ssl(ctx, 1)) == NULL)
goto err;
if ((ret = BIO_push(ssl, con)) == NULL)
goto err;
return ret;
err:
BIO_free(ssl);
BIO_free(con);
#endif
return NULL;
}
BIO *BIO_new_ssl(SSL_CTX *ctx, int client)
{
BIO *ret;
SSL *ssl;
if ((ret = BIO_new(BIO_f_ssl())) == NULL)
return NULL;
if ((ssl = SSL_new(ctx)) == NULL) {
BIO_free(ret);
return NULL;
}
if (client)
SSL_set_connect_state(ssl);
else
SSL_set_accept_state(ssl);
BIO_set_ssl(ret, ssl, BIO_CLOSE);
return ret;
}
int BIO_ssl_copy_session_id(BIO *t, BIO *f)
{
BIO_SSL *tdata, *fdata;
t = BIO_find_type(t, BIO_TYPE_SSL);
f = BIO_find_type(f, BIO_TYPE_SSL);
if ((t == NULL) || (f == NULL))
return 0;
tdata = BIO_get_data(t);
fdata = BIO_get_data(f);
if ((tdata->ssl == NULL) || (fdata->ssl == NULL))
return 0;
if (!SSL_copy_session_id(tdata->ssl, (fdata->ssl)))
return 0;
return 1;
}
void BIO_ssl_shutdown(BIO *b)
{
BIO_SSL *bdata;
for (; b != NULL; b = BIO_next(b)) {
if (BIO_method_type(b) != BIO_TYPE_SSL)
continue;
bdata = BIO_get_data(b);
if (bdata != NULL && bdata->ssl != NULL)
SSL_shutdown(bdata->ssl);
}
}
diff --git a/crypto/openssl/ssl/ssl_lib.c b/crypto/openssl/ssl/ssl_lib.c
index cb4e006ea7a3..e628140dfae9 100644
--- a/crypto/openssl/ssl/ssl_lib.c
+++ b/crypto/openssl/ssl/ssl_lib.c
@@ -1,6061 +1,6078 @@
/*
* 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;
+ PACKET cpkt, csubpkt, spkt, ssubpkt;
+
+ if (!PACKET_buf_init(&cpkt, client, client_len)
+ || !PACKET_get_length_prefixed_1(&cpkt, &csubpkt)
+ || PACKET_remaining(&csubpkt) == 0) {
+ *out = NULL;
+ *outlen = 0;
+ return OPENSSL_NPN_NO_OVERLAP;
+ }
+
+ /*
+ * Set the default opportunistic protocol. Will be overwritten if we find
+ * a match.
+ */
+ *out = (unsigned char *)PACKET_data(&csubpkt);
+ *outlen = (unsigned char)PACKET_remaining(&csubpkt);
/*
* 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;
+ if (PACKET_buf_init(&spkt, server, server_len)) {
+ while (PACKET_get_length_prefixed_1(&spkt, &ssubpkt)) {
+ if (PACKET_remaining(&ssubpkt) == 0)
+ continue; /* Invalid - ignore it */
+ if (PACKET_buf_init(&cpkt, client, client_len)) {
+ while (PACKET_get_length_prefixed_1(&cpkt, &csubpkt)) {
+ if (PACKET_equal(&csubpkt, PACKET_data(&ssubpkt),
+ PACKET_remaining(&ssubpkt))) {
+ /* We found a match */
+ *out = (unsigned char *)PACKET_data(&ssubpkt);
+ *outlen = (unsigned char)PACKET_remaining(&ssubpkt);
+ return OPENSSL_NPN_NEGOTIATED;
+ }
+ }
+ /* Ignore spurious trailing bytes in the client list */
+ } else {
+ /* This should never happen */
+ return OPENSSL_NPN_NO_OVERLAP;
}
- j += client[j];
- j++;
}
- i += server[i];
- i++;
+ /* Ignore spurious trailing bytes in the server list */
}
- /* 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;
+ /*
+ * There's no overlap between our protocols and the server's list. We use
+ * the default opportunistic protocol selected earlier
+ */
+ return OPENSSL_NPN_NO_OVERLAP;
}
#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 :-). 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 || 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 56854fc89023..ec937a321c30 100644
--- a/crypto/openssl/ssl/ssl_sess.c
+++ b/crypto/openssl/ssl/ssl_sess.c
@@ -1,1420 +1,1436 @@
/*
* 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;
}
+#ifdef __DJGPP__ /* time_t is unsigned on djgpp, it's signed anywhere else */
+# define TMAX(_type_) ((time_t)-1)
+#else
+# define TMAX(_type_) ((time_t)(((_type_)-1) >> 1))
+#endif
+
+#define CALCULATE_TIMEOUT(_ss_, _type_) do { \
+ _type_ overflow; \
+ time_t tmax = TMAX(_type_); \
+ overflow = (_type_)tmax - (_type_)(_ss_)->time; \
+ if ((_ss_)->timeout > (time_t)overflow) { \
+ (_ss_)->timeout_ovf = 1; \
+ (_ss_)->calc_timeout = (_ss_)->timeout - (time_t)overflow; \
+ } else { \
+ (_ss_)->timeout_ovf = 0; \
+ (_ss_)->calc_timeout = (_ss_)->time + (_ss_)->timeout; \
+ } \
+ } while (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;
+
+ if (sizeof(time_t) == 8)
+ CALCULATE_TIMEOUT(ss, uint64_t);
+ else
+ CALCULATE_TIMEOUT(ss, uint32_t);
+
/*
* 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->ext.max_fragment_len_mode = TLSEXT_max_fragment_length_UNSPECIFIED;
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;
}
/*
* 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.
*/
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/extensions.c b/crypto/openssl/ssl/statem/extensions.c
index 1518ca7f4e72..f8157389b7f1 100644
--- a/crypto/openssl/ssl/statem/extensions.c
+++ b/crypto/openssl/ssl/statem/extensions.c
@@ -1,1730 +1,1724 @@
/*
- * 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
*/
#if defined(__TANDEM) && defined(_SPT_MODEL_)
# include <spthread.h>
# include <spt_extensions.h> /* timeval */
#endif
#include <string.h>
#include "internal/nelem.h"
#include "internal/cryptlib.h"
#include "../ssl_local.h"
#include "statem_local.h"
#include "internal/cryptlib.h"
static int final_renegotiate(SSL *s, unsigned int context, int sent);
static int init_server_name(SSL *s, unsigned int context);
static int final_server_name(SSL *s, unsigned int context, int sent);
static int final_ec_pt_formats(SSL *s, unsigned int context, int sent);
static int init_session_ticket(SSL *s, unsigned int context);
#ifndef OPENSSL_NO_OCSP
static int init_status_request(SSL *s, unsigned int context);
#endif
#ifndef OPENSSL_NO_NEXTPROTONEG
static int init_npn(SSL *s, unsigned int context);
#endif
static int init_alpn(SSL *s, unsigned int context);
static int final_alpn(SSL *s, unsigned int context, int sent);
static int init_sig_algs_cert(SSL *s, unsigned int context);
static int init_sig_algs(SSL *s, unsigned int context);
static int init_certificate_authorities(SSL *s, unsigned int context);
static EXT_RETURN tls_construct_certificate_authorities(SSL *s, WPACKET *pkt,
unsigned int context,
X509 *x,
size_t chainidx);
static int tls_parse_certificate_authorities(SSL *s, PACKET *pkt,
unsigned int context, X509 *x,
size_t chainidx);
#ifndef OPENSSL_NO_SRP
static int init_srp(SSL *s, unsigned int context);
#endif
static int init_ec_point_formats(SSL *s, unsigned int context);
static int init_etm(SSL *s, unsigned int context);
static int init_ems(SSL *s, unsigned int context);
static int final_ems(SSL *s, unsigned int context, int sent);
static int init_psk_kex_modes(SSL *s, unsigned int context);
static int final_key_share(SSL *s, unsigned int context, int sent);
#ifndef OPENSSL_NO_SRTP
static int init_srtp(SSL *s, unsigned int context);
#endif
static int final_sig_algs(SSL *s, unsigned int context, int sent);
static int final_early_data(SSL *s, unsigned int context, int sent);
static int final_maxfragmentlen(SSL *s, unsigned int context, int sent);
static int init_post_handshake_auth(SSL *s, unsigned int context);
static int final_psk(SSL *s, unsigned int context, int sent);
/* Structure to define a built-in extension */
typedef struct extensions_definition_st {
/* The defined type for the extension */
unsigned int type;
/*
* The context that this extension applies to, e.g. what messages and
* protocol versions
*/
unsigned int context;
/*
* Initialise extension before parsing. Always called for relevant contexts
* even if extension not present
*/
int (*init)(SSL *s, unsigned int context);
/* Parse extension sent from client to server */
int (*parse_ctos)(SSL *s, PACKET *pkt, unsigned int context, X509 *x,
size_t chainidx);
/* Parse extension send from server to client */
int (*parse_stoc)(SSL *s, PACKET *pkt, unsigned int context, X509 *x,
size_t chainidx);
/* Construct extension sent from server to client */
EXT_RETURN (*construct_stoc)(SSL *s, WPACKET *pkt, unsigned int context,
X509 *x, size_t chainidx);
/* Construct extension sent from client to server */
EXT_RETURN (*construct_ctos)(SSL *s, WPACKET *pkt, unsigned int context,
X509 *x, size_t chainidx);
/*
* Finalise extension after parsing. Always called where an extensions was
* initialised even if the extension was not present. |sent| is set to 1 if
* the extension was seen, or 0 otherwise.
*/
int (*final)(SSL *s, unsigned int context, int sent);
} EXTENSION_DEFINITION;
/*
* Definitions of all built-in extensions. NOTE: Changes in the number or order
* of these extensions should be mirrored with equivalent changes to the
* indexes ( TLSEXT_IDX_* ) defined in ssl_local.h.
* Extensions should be added to test/ext_internal_test.c as well, as that
* tests the ordering of the extensions.
*
* Each extension has an initialiser, a client and
* server side parser and a finaliser. The initialiser is called (if the
* extension is relevant to the given context) even if we did not see the
* extension in the message that we received. The parser functions are only
* called if we see the extension in the message. The finalisers are always
* called if the initialiser was called.
* There are also server and client side constructor functions which are always
* called during message construction if the extension is relevant for the
* given context.
* The initialisation, parsing, finalisation and construction functions are
* always called in the order defined in this list. Some extensions may depend
* on others having been processed first, so the order of this list is
* significant.
* The extension context is defined by a series of flags which specify which
* messages the extension is relevant to. These flags also specify whether the
* extension is relevant to a particular protocol or protocol version.
*
* NOTE: WebSphere Application Server 7+ cannot handle empty extensions at
* the end, keep these extensions before signature_algorithm.
*/
#define INVALID_EXTENSION { TLSEXT_TYPE_invalid, 0, NULL, NULL, NULL, NULL, NULL, NULL }
static const EXTENSION_DEFINITION ext_defs[] = {
{
TLSEXT_TYPE_renegotiate,
SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_2_SERVER_HELLO
| SSL_EXT_SSL3_ALLOWED | SSL_EXT_TLS1_2_AND_BELOW_ONLY,
NULL, tls_parse_ctos_renegotiate, tls_parse_stoc_renegotiate,
tls_construct_stoc_renegotiate, tls_construct_ctos_renegotiate,
final_renegotiate
},
{
TLSEXT_TYPE_server_name,
SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_2_SERVER_HELLO
| SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS,
init_server_name,
tls_parse_ctos_server_name, tls_parse_stoc_server_name,
tls_construct_stoc_server_name, tls_construct_ctos_server_name,
final_server_name
},
{
TLSEXT_TYPE_max_fragment_length,
SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_2_SERVER_HELLO
| SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS,
NULL, tls_parse_ctos_maxfragmentlen, tls_parse_stoc_maxfragmentlen,
tls_construct_stoc_maxfragmentlen, tls_construct_ctos_maxfragmentlen,
final_maxfragmentlen
},
#ifndef OPENSSL_NO_SRP
{
TLSEXT_TYPE_srp,
SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_2_AND_BELOW_ONLY,
init_srp, tls_parse_ctos_srp, NULL, NULL, tls_construct_ctos_srp, NULL
},
#else
INVALID_EXTENSION,
#endif
{
TLSEXT_TYPE_ec_point_formats,
SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_2_SERVER_HELLO
| SSL_EXT_TLS1_2_AND_BELOW_ONLY,
init_ec_point_formats, tls_parse_ctos_ec_pt_formats, tls_parse_stoc_ec_pt_formats,
tls_construct_stoc_ec_pt_formats, tls_construct_ctos_ec_pt_formats,
final_ec_pt_formats
},
{
/*
* "supported_groups" is spread across several specifications.
* It was originally specified as "elliptic_curves" in RFC 4492,
* and broadened to include named FFDH groups by RFC 7919.
* Both RFCs 4492 and 7919 do not include a provision for the server
* to indicate to the client the complete list of groups supported
* by the server, with the server instead just indicating the
* selected group for this connection in the ServerKeyExchange
* message. TLS 1.3 adds a scheme for the server to indicate
* to the client its list of supported groups in the
* EncryptedExtensions message, but none of the relevant
* specifications permit sending supported_groups in the ServerHello.
* Nonetheless (possibly due to the close proximity to the
* "ec_point_formats" extension, which is allowed in the ServerHello),
* there are several servers that send this extension in the
* ServerHello anyway. Up to and including the 1.1.0 release,
* we did not check for the presence of nonpermitted extensions,
* so to avoid a regression, we must permit this extension in the
* TLS 1.2 ServerHello as well.
*
* Note that there is no tls_parse_stoc_supported_groups function,
* so we do not perform any additional parsing, validation, or
* processing on the server's group list -- this is just a minimal
* change to preserve compatibility with these misbehaving servers.
*/
TLSEXT_TYPE_supported_groups,
SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS
| SSL_EXT_TLS1_2_SERVER_HELLO,
NULL, tls_parse_ctos_supported_groups, NULL,
tls_construct_stoc_supported_groups,
tls_construct_ctos_supported_groups, NULL
},
{
TLSEXT_TYPE_session_ticket,
SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_2_SERVER_HELLO
| SSL_EXT_TLS1_2_AND_BELOW_ONLY,
init_session_ticket, tls_parse_ctos_session_ticket,
tls_parse_stoc_session_ticket, tls_construct_stoc_session_ticket,
tls_construct_ctos_session_ticket, NULL
},
#ifndef OPENSSL_NO_OCSP
{
TLSEXT_TYPE_status_request,
SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_2_SERVER_HELLO
| SSL_EXT_TLS1_3_CERTIFICATE | SSL_EXT_TLS1_3_CERTIFICATE_REQUEST,
init_status_request, tls_parse_ctos_status_request,
tls_parse_stoc_status_request, tls_construct_stoc_status_request,
tls_construct_ctos_status_request, NULL
},
#else
INVALID_EXTENSION,
#endif
#ifndef OPENSSL_NO_NEXTPROTONEG
{
TLSEXT_TYPE_next_proto_neg,
SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_2_SERVER_HELLO
| SSL_EXT_TLS1_2_AND_BELOW_ONLY,
init_npn, tls_parse_ctos_npn, tls_parse_stoc_npn,
tls_construct_stoc_next_proto_neg, tls_construct_ctos_npn, NULL
},
#else
INVALID_EXTENSION,
#endif
{
/*
* Must appear in this list after server_name so that finalisation
* happens after server_name callbacks
*/
TLSEXT_TYPE_application_layer_protocol_negotiation,
SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_2_SERVER_HELLO
| SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS,
init_alpn, tls_parse_ctos_alpn, tls_parse_stoc_alpn,
tls_construct_stoc_alpn, tls_construct_ctos_alpn, final_alpn
},
#ifndef OPENSSL_NO_SRTP
{
TLSEXT_TYPE_use_srtp,
SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_2_SERVER_HELLO
| SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS | SSL_EXT_DTLS_ONLY,
init_srtp, tls_parse_ctos_use_srtp, tls_parse_stoc_use_srtp,
tls_construct_stoc_use_srtp, tls_construct_ctos_use_srtp, NULL
},
#else
INVALID_EXTENSION,
#endif
{
TLSEXT_TYPE_encrypt_then_mac,
SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_2_SERVER_HELLO
| SSL_EXT_TLS1_2_AND_BELOW_ONLY,
init_etm, tls_parse_ctos_etm, tls_parse_stoc_etm,
tls_construct_stoc_etm, tls_construct_ctos_etm, NULL
},
#ifndef OPENSSL_NO_CT
{
TLSEXT_TYPE_signed_certificate_timestamp,
SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_2_SERVER_HELLO
| SSL_EXT_TLS1_3_CERTIFICATE | SSL_EXT_TLS1_3_CERTIFICATE_REQUEST,
NULL,
/*
* No server side support for this, but can be provided by a custom
* extension. This is an exception to the rule that custom extensions
* cannot override built in ones.
*/
NULL, tls_parse_stoc_sct, NULL, tls_construct_ctos_sct, NULL
},
#else
INVALID_EXTENSION,
#endif
{
TLSEXT_TYPE_extended_master_secret,
SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_2_SERVER_HELLO
| SSL_EXT_TLS1_2_AND_BELOW_ONLY,
init_ems, tls_parse_ctos_ems, tls_parse_stoc_ems,
tls_construct_stoc_ems, tls_construct_ctos_ems, final_ems
},
{
TLSEXT_TYPE_signature_algorithms_cert,
SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_3_CERTIFICATE_REQUEST,
init_sig_algs_cert, tls_parse_ctos_sig_algs_cert,
tls_parse_ctos_sig_algs_cert,
/* We do not generate signature_algorithms_cert at present. */
NULL, NULL, NULL
},
{
TLSEXT_TYPE_post_handshake_auth,
SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_3_ONLY,
init_post_handshake_auth,
tls_parse_ctos_post_handshake_auth, NULL,
NULL, tls_construct_ctos_post_handshake_auth,
NULL,
},
{
TLSEXT_TYPE_signature_algorithms,
SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_3_CERTIFICATE_REQUEST,
init_sig_algs, tls_parse_ctos_sig_algs,
tls_parse_ctos_sig_algs, tls_construct_ctos_sig_algs,
tls_construct_ctos_sig_algs, final_sig_algs
},
{
TLSEXT_TYPE_supported_versions,
SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_3_SERVER_HELLO
| SSL_EXT_TLS1_3_HELLO_RETRY_REQUEST | SSL_EXT_TLS_IMPLEMENTATION_ONLY,
NULL,
/* Processed inline as part of version selection */
NULL, tls_parse_stoc_supported_versions,
tls_construct_stoc_supported_versions,
tls_construct_ctos_supported_versions, NULL
},
{
TLSEXT_TYPE_psk_kex_modes,
SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS_IMPLEMENTATION_ONLY
| SSL_EXT_TLS1_3_ONLY,
init_psk_kex_modes, tls_parse_ctos_psk_kex_modes, NULL, NULL,
tls_construct_ctos_psk_kex_modes, NULL
},
{
/*
* Must be in this list after supported_groups. We need that to have
* been parsed before we do this one.
*/
TLSEXT_TYPE_key_share,
SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_3_SERVER_HELLO
| SSL_EXT_TLS1_3_HELLO_RETRY_REQUEST | SSL_EXT_TLS_IMPLEMENTATION_ONLY
| SSL_EXT_TLS1_3_ONLY,
NULL, tls_parse_ctos_key_share, tls_parse_stoc_key_share,
tls_construct_stoc_key_share, tls_construct_ctos_key_share,
final_key_share
},
{
/* Must be after key_share */
TLSEXT_TYPE_cookie,
SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_3_HELLO_RETRY_REQUEST
| SSL_EXT_TLS_IMPLEMENTATION_ONLY | SSL_EXT_TLS1_3_ONLY,
NULL, tls_parse_ctos_cookie, tls_parse_stoc_cookie,
tls_construct_stoc_cookie, tls_construct_ctos_cookie, NULL
},
{
/*
* Special unsolicited ServerHello extension only used when
* SSL_OP_CRYPTOPRO_TLSEXT_BUG is set. We allow it in a ClientHello but
* ignore it.
*/
TLSEXT_TYPE_cryptopro_bug,
SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_2_SERVER_HELLO
| SSL_EXT_TLS1_2_AND_BELOW_ONLY,
NULL, NULL, NULL, tls_construct_stoc_cryptopro_bug, NULL, NULL
},
{
TLSEXT_TYPE_early_data,
SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS
| SSL_EXT_TLS1_3_NEW_SESSION_TICKET | SSL_EXT_TLS1_3_ONLY,
NULL, tls_parse_ctos_early_data, tls_parse_stoc_early_data,
tls_construct_stoc_early_data, tls_construct_ctos_early_data,
final_early_data
},
{
TLSEXT_TYPE_certificate_authorities,
SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_3_CERTIFICATE_REQUEST
| SSL_EXT_TLS1_3_ONLY,
init_certificate_authorities,
tls_parse_certificate_authorities, tls_parse_certificate_authorities,
tls_construct_certificate_authorities,
tls_construct_certificate_authorities, NULL,
},
{
/* Must be immediately before pre_shared_key */
TLSEXT_TYPE_padding,
SSL_EXT_CLIENT_HELLO,
NULL,
/* We send this, but don't read it */
NULL, NULL, NULL, tls_construct_ctos_padding, NULL
},
{
/* Required by the TLSv1.3 spec to always be the last extension */
TLSEXT_TYPE_psk,
SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_3_SERVER_HELLO
| SSL_EXT_TLS_IMPLEMENTATION_ONLY | SSL_EXT_TLS1_3_ONLY,
NULL, tls_parse_ctos_psk, tls_parse_stoc_psk, tls_construct_stoc_psk,
tls_construct_ctos_psk, final_psk
}
};
/* Returns a TLSEXT_TYPE for the given index */
unsigned int ossl_get_extension_type(size_t idx)
{
size_t num_exts = OSSL_NELEM(ext_defs);
if (idx >= num_exts)
return TLSEXT_TYPE_out_of_range;
return ext_defs[idx].type;
}
/* Check whether an extension's context matches the current context */
static int validate_context(SSL *s, unsigned int extctx, unsigned int thisctx)
{
/* Check we're allowed to use this extension in this context */
if ((thisctx & extctx) == 0)
return 0;
if (SSL_IS_DTLS(s)) {
if ((extctx & SSL_EXT_TLS_ONLY) != 0)
return 0;
} else if ((extctx & SSL_EXT_DTLS_ONLY) != 0) {
return 0;
}
return 1;
}
int tls_validate_all_contexts(SSL *s, unsigned int thisctx, RAW_EXTENSION *exts)
{
size_t i, num_exts, builtin_num = OSSL_NELEM(ext_defs), offset;
RAW_EXTENSION *thisext;
unsigned int context;
ENDPOINT role = ENDPOINT_BOTH;
if ((thisctx & SSL_EXT_CLIENT_HELLO) != 0)
role = ENDPOINT_SERVER;
else if ((thisctx & SSL_EXT_TLS1_2_SERVER_HELLO) != 0)
role = ENDPOINT_CLIENT;
/* Calculate the number of extensions in the extensions list */
num_exts = builtin_num + s->cert->custext.meths_count;
for (thisext = exts, i = 0; i < num_exts; i++, thisext++) {
if (!thisext->present)
continue;
if (i < builtin_num) {
context = ext_defs[i].context;
} else {
custom_ext_method *meth = NULL;
meth = custom_ext_find(&s->cert->custext, role, thisext->type,
&offset);
if (!ossl_assert(meth != NULL))
return 0;
context = meth->context;
}
if (!validate_context(s, context, thisctx))
return 0;
}
return 1;
}
/*
* Verify whether we are allowed to use the extension |type| in the current
* |context|. Returns 1 to indicate the extension is allowed or unknown or 0 to
* indicate the extension is not allowed. If returning 1 then |*found| is set to
* the definition for the extension we found.
*/
static int verify_extension(SSL *s, unsigned int context, unsigned int type,
custom_ext_methods *meths, RAW_EXTENSION *rawexlist,
RAW_EXTENSION **found)
{
size_t i;
size_t builtin_num = OSSL_NELEM(ext_defs);
const EXTENSION_DEFINITION *thisext;
for (i = 0, thisext = ext_defs; i < builtin_num; i++, thisext++) {
if (type == thisext->type) {
if (!validate_context(s, thisext->context, context))
return 0;
*found = &rawexlist[i];
return 1;
}
}
/* Check the custom extensions */
if (meths != NULL) {
size_t offset = 0;
ENDPOINT role = ENDPOINT_BOTH;
custom_ext_method *meth = NULL;
if ((context & SSL_EXT_CLIENT_HELLO) != 0)
role = ENDPOINT_SERVER;
else if ((context & SSL_EXT_TLS1_2_SERVER_HELLO) != 0)
role = ENDPOINT_CLIENT;
meth = custom_ext_find(meths, role, type, &offset);
if (meth != NULL) {
if (!validate_context(s, meth->context, context))
return 0;
*found = &rawexlist[offset + builtin_num];
return 1;
}
}
/* Unknown extension. We allow it */
*found = NULL;
return 1;
}
/*
* Check whether the context defined for an extension |extctx| means whether
* the extension is relevant for the current context |thisctx| or not. Returns
* 1 if the extension is relevant for this context, and 0 otherwise
*/
int extension_is_relevant(SSL *s, unsigned int extctx, unsigned int thisctx)
{
int is_tls13;
/*
* For HRR we haven't selected the version yet but we know it will be
* TLSv1.3
*/
if ((thisctx & SSL_EXT_TLS1_3_HELLO_RETRY_REQUEST) != 0)
is_tls13 = 1;
else
is_tls13 = SSL_IS_TLS13(s);
if ((SSL_IS_DTLS(s)
&& (extctx & SSL_EXT_TLS_IMPLEMENTATION_ONLY) != 0)
|| (s->version == SSL3_VERSION
&& (extctx & SSL_EXT_SSL3_ALLOWED) == 0)
/*
* Note that SSL_IS_TLS13() means "TLS 1.3 has been negotiated",
* which is never true when generating the ClientHello.
* However, version negotiation *has* occurred by the time the
* ClientHello extensions are being parsed.
* Be careful to allow TLS 1.3-only extensions when generating
* the ClientHello.
*/
|| (is_tls13 && (extctx & SSL_EXT_TLS1_2_AND_BELOW_ONLY) != 0)
|| (!is_tls13 && (extctx & SSL_EXT_TLS1_3_ONLY) != 0
&& (thisctx & SSL_EXT_CLIENT_HELLO) == 0)
|| (s->server && !is_tls13 && (extctx & SSL_EXT_TLS1_3_ONLY) != 0)
|| (s->hit && (extctx & SSL_EXT_IGNORE_ON_RESUMPTION) != 0))
return 0;
return 1;
}
/*
* Gather a list of all the extensions from the data in |packet]. |context|
* tells us which message this extension is for. The raw extension data is
* stored in |*res| on success. We don't actually process the content of the
* extensions yet, except to check their types. This function also runs the
* initialiser functions for all known extensions if |init| is nonzero (whether
* we have collected them or not). If successful the caller is responsible for
* freeing the contents of |*res|.
*
* Per http://tools.ietf.org/html/rfc5246#section-7.4.1.4, there may not be
* more than one extension of the same type in a ClientHello or ServerHello.
* This function returns 1 if all extensions are unique and we have parsed their
* types, and 0 if the extensions contain duplicates, could not be successfully
* found, or an internal error occurred. We only check duplicates for
* extensions that we know about. We ignore others.
*/
int tls_collect_extensions(SSL *s, PACKET *packet, unsigned int context,
RAW_EXTENSION **res, size_t *len, int init)
{
PACKET extensions = *packet;
size_t i = 0;
size_t num_exts;
custom_ext_methods *exts = &s->cert->custext;
RAW_EXTENSION *raw_extensions = NULL;
const EXTENSION_DEFINITION *thisexd;
*res = NULL;
/*
* Initialise server side custom extensions. Client side is done during
* construction of extensions for the ClientHello.
*/
if ((context & SSL_EXT_CLIENT_HELLO) != 0)
custom_ext_init(&s->cert->custext);
num_exts = OSSL_NELEM(ext_defs) + (exts != NULL ? exts->meths_count : 0);
raw_extensions = OPENSSL_zalloc(num_exts * sizeof(*raw_extensions));
if (raw_extensions == NULL) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_MALLOC_FAILURE);
return 0;
}
i = 0;
while (PACKET_remaining(&extensions) > 0) {
unsigned int type, idx;
PACKET extension;
RAW_EXTENSION *thisex;
if (!PACKET_get_net_2(&extensions, &type) ||
!PACKET_get_length_prefixed_2(&extensions, &extension)) {
SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_EXTENSION);
goto err;
}
/*
* Verify this extension is allowed. We only check duplicates for
* extensions that we recognise. We also have a special case for the
* PSK extension, which must be the last one in the ClientHello.
*/
if (!verify_extension(s, context, type, exts, raw_extensions, &thisex)
|| (thisex != NULL && thisex->present == 1)
|| (type == TLSEXT_TYPE_psk
&& (context & SSL_EXT_CLIENT_HELLO) != 0
&& PACKET_remaining(&extensions) != 0)) {
SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_BAD_EXTENSION);
goto err;
}
idx = thisex - raw_extensions;
/*-
* Check that we requested this extension (if appropriate). Requests can
* be sent in the ClientHello and CertificateRequest. Unsolicited
* extensions can be sent in the NewSessionTicket. We only do this for
* the built-in extensions. Custom extensions have a different but
* similar check elsewhere.
* Special cases:
* - The HRR cookie extension is unsolicited
* - The renegotiate extension is unsolicited (the client signals
* support via an SCSV)
* - The signed_certificate_timestamp extension can be provided by a
* custom extension or by the built-in version. We let the extension
* itself handle unsolicited response checks.
*/
if (idx < OSSL_NELEM(ext_defs)
&& (context & (SSL_EXT_CLIENT_HELLO
| SSL_EXT_TLS1_3_CERTIFICATE_REQUEST
| SSL_EXT_TLS1_3_NEW_SESSION_TICKET)) == 0
&& type != TLSEXT_TYPE_cookie
&& type != TLSEXT_TYPE_renegotiate
&& type != TLSEXT_TYPE_signed_certificate_timestamp
&& (s->ext.extflags[idx] & SSL_EXT_FLAG_SENT) == 0
#ifndef OPENSSL_NO_GOST
&& !((context & SSL_EXT_TLS1_2_SERVER_HELLO) != 0
&& type == TLSEXT_TYPE_cryptopro_bug)
#endif
) {
SSLfatal(s, SSL_AD_UNSUPPORTED_EXTENSION,
SSL_R_UNSOLICITED_EXTENSION);
goto err;
}
if (thisex != NULL) {
thisex->data = extension;
thisex->present = 1;
thisex->type = type;
thisex->received_order = i++;
if (s->ext.debug_cb)
s->ext.debug_cb(s, !s->server, thisex->type,
PACKET_data(&thisex->data),
PACKET_remaining(&thisex->data),
s->ext.debug_arg);
}
}
if (init) {
/*
* Initialise all known extensions relevant to this context,
* whether we have found them or not
*/
for (thisexd = ext_defs, i = 0; i < OSSL_NELEM(ext_defs);
i++, thisexd++) {
if (thisexd->init != NULL && (thisexd->context & context) != 0
&& extension_is_relevant(s, thisexd->context, context)
&& !thisexd->init(s, context)) {
/* SSLfatal() already called */
goto err;
}
}
}
*res = raw_extensions;
if (len != NULL)
*len = num_exts;
return 1;
err:
OPENSSL_free(raw_extensions);
return 0;
}
/*
* Runs the parser for a given extension with index |idx|. |exts| contains the
* list of all parsed extensions previously collected by
* tls_collect_extensions(). The parser is only run if it is applicable for the
* given |context| and the parser has not already been run. If this is for a
* Certificate message, then we also provide the parser with the relevant
* Certificate |x| and its position in the |chainidx| with 0 being the first
* Certificate. Returns 1 on success or 0 on failure. If an extension is not
* present this counted as success.
*/
int tls_parse_extension(SSL *s, TLSEXT_INDEX idx, int context,
RAW_EXTENSION *exts, X509 *x, size_t chainidx)
{
RAW_EXTENSION *currext = &exts[idx];
int (*parser)(SSL *s, PACKET *pkt, unsigned int context, X509 *x,
size_t chainidx) = NULL;
/* Skip if the extension is not present */
if (!currext->present)
return 1;
/* Skip if we've already parsed this extension */
if (currext->parsed)
return 1;
currext->parsed = 1;
if (idx < OSSL_NELEM(ext_defs)) {
/* We are handling a built-in extension */
const EXTENSION_DEFINITION *extdef = &ext_defs[idx];
/* Check if extension is defined for our protocol. If not, skip */
if (!extension_is_relevant(s, extdef->context, context))
return 1;
parser = s->server ? extdef->parse_ctos : extdef->parse_stoc;
if (parser != NULL)
return parser(s, &currext->data, context, x, chainidx);
/*
* If the parser is NULL we fall through to the custom extension
* processing
*/
}
/* Parse custom extensions */
return custom_ext_parse(s, context, currext->type,
PACKET_data(&currext->data),
PACKET_remaining(&currext->data),
x, chainidx);
}
/*
* Parse all remaining extensions that have not yet been parsed. Also calls the
* finalisation for all extensions at the end if |fin| is nonzero, whether we
* collected them or not. Returns 1 for success or 0 for failure. If we are
* working on a Certificate message then we also pass the Certificate |x| and
* its position in the |chainidx|, with 0 being the first certificate.
*/
int tls_parse_all_extensions(SSL *s, int context, RAW_EXTENSION *exts, X509 *x,
size_t chainidx, int fin)
{
size_t i, numexts = OSSL_NELEM(ext_defs);
const EXTENSION_DEFINITION *thisexd;
/* Calculate the number of extensions in the extensions list */
numexts += s->cert->custext.meths_count;
/* Parse each extension in turn */
for (i = 0; i < numexts; i++) {
if (!tls_parse_extension(s, i, context, exts, x, chainidx)) {
/* SSLfatal() already called */
return 0;
}
}
if (fin) {
/*
* Finalise all known extensions relevant to this context,
* whether we have found them or not
*/
for (i = 0, thisexd = ext_defs; i < OSSL_NELEM(ext_defs);
i++, thisexd++) {
if (thisexd->final != NULL && (thisexd->context & context) != 0
&& !thisexd->final(s, context, exts[i].present)) {
/* SSLfatal() already called */
return 0;
}
}
}
return 1;
}
int should_add_extension(SSL *s, unsigned int extctx, unsigned int thisctx,
int max_version)
{
/* Skip if not relevant for our context */
if ((extctx & thisctx) == 0)
return 0;
/* Check if this extension is defined for our protocol. If not, skip */
if (!extension_is_relevant(s, extctx, thisctx)
|| ((extctx & SSL_EXT_TLS1_3_ONLY) != 0
&& (thisctx & SSL_EXT_CLIENT_HELLO) != 0
&& (SSL_IS_DTLS(s) || max_version < TLS1_3_VERSION)))
return 0;
return 1;
}
/*
* Construct all the extensions relevant to the current |context| and write
* them to |pkt|. If this is an extension for a Certificate in a Certificate
* message, then |x| will be set to the Certificate we are handling, and
* |chainidx| will indicate the position in the chainidx we are processing (with
* 0 being the first in the chain). Returns 1 on success or 0 on failure. On a
* failure construction stops at the first extension to fail to construct.
*/
int tls_construct_extensions(SSL *s, WPACKET *pkt, unsigned int context,
X509 *x, size_t chainidx)
{
size_t i;
int min_version, max_version = 0, reason;
const EXTENSION_DEFINITION *thisexd;
if (!WPACKET_start_sub_packet_u16(pkt)
/*
* If extensions are of zero length then we don't even add the
* extensions length bytes to a ClientHello/ServerHello
* (for non-TLSv1.3).
*/
|| ((context &
(SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_2_SERVER_HELLO)) != 0
&& !WPACKET_set_flags(pkt,
WPACKET_FLAGS_ABANDON_ON_ZERO_LENGTH))) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return 0;
}
if ((context & SSL_EXT_CLIENT_HELLO) != 0) {
reason = ssl_get_min_max_version(s, &min_version, &max_version, NULL);
if (reason != 0) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, reason);
return 0;
}
}
/* Add custom extensions first */
if ((context & SSL_EXT_CLIENT_HELLO) != 0) {
/* On the server side with initialise during ClientHello parsing */
custom_ext_init(&s->cert->custext);
}
if (!custom_ext_add(s, context, pkt, x, chainidx, max_version)) {
/* SSLfatal() already called */
return 0;
}
for (i = 0, thisexd = ext_defs; i < OSSL_NELEM(ext_defs); i++, thisexd++) {
EXT_RETURN (*construct)(SSL *s, WPACKET *pkt, unsigned int context,
X509 *x, size_t chainidx);
EXT_RETURN ret;
/* Skip if not relevant for our context */
if (!should_add_extension(s, thisexd->context, context, max_version))
continue;
construct = s->server ? thisexd->construct_stoc
: thisexd->construct_ctos;
if (construct == NULL)
continue;
ret = construct(s, pkt, context, x, chainidx);
if (ret == EXT_RETURN_FAIL) {
/* SSLfatal() already called */
return 0;
}
if (ret == EXT_RETURN_SENT
&& (context & (SSL_EXT_CLIENT_HELLO
| SSL_EXT_TLS1_3_CERTIFICATE_REQUEST
| SSL_EXT_TLS1_3_NEW_SESSION_TICKET)) != 0)
s->ext.extflags[i] |= SSL_EXT_FLAG_SENT;
}
if (!WPACKET_close(pkt)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return 0;
}
return 1;
}
/*
* Built in extension finalisation and initialisation functions. All initialise
* or finalise the associated extension type for the given |context|. For
* finalisers |sent| is set to 1 if we saw the extension during parsing, and 0
* otherwise. These functions return 1 on success or 0 on failure.
*/
static int final_renegotiate(SSL *s, unsigned int context, int sent)
{
if (!s->server) {
/*
* Check if we can connect to a server that doesn't support safe
* renegotiation
*/
if (!(s->options & SSL_OP_LEGACY_SERVER_CONNECT)
&& !(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)
&& !sent) {
SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
return 0;
}
return 1;
}
/* Need RI if renegotiating */
if (s->renegotiate
&& !(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)
&& !sent) {
SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
return 0;
}
return 1;
}
static ossl_inline void ssl_tsan_decr(const SSL_CTX *ctx,
TSAN_QUALIFIER int *stat)
{
if (ssl_tsan_lock(ctx)) {
tsan_decr(stat);
ssl_tsan_unlock(ctx);
}
}
static int init_server_name(SSL *s, unsigned int context)
{
if (s->server) {
s->servername_done = 0;
OPENSSL_free(s->ext.hostname);
s->ext.hostname = NULL;
}
return 1;
}
static int final_server_name(SSL *s, unsigned int context, int sent)
{
int ret = SSL_TLSEXT_ERR_NOACK;
int altmp = SSL_AD_UNRECOGNIZED_NAME;
int was_ticket = (SSL_get_options(s) & SSL_OP_NO_TICKET) == 0;
if (!ossl_assert(s->ctx != NULL) || !ossl_assert(s->session_ctx != NULL)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return 0;
}
if (s->ctx->ext.servername_cb != NULL)
ret = s->ctx->ext.servername_cb(s, &altmp,
s->ctx->ext.servername_arg);
else if (s->session_ctx->ext.servername_cb != NULL)
ret = s->session_ctx->ext.servername_cb(s, &altmp,
s->session_ctx->ext.servername_arg);
/*
* For servers, propagate the SNI hostname from the temporary
* storage in the SSL to the persistent SSL_SESSION, now that we
* know we accepted it.
* Clients make this copy when parsing the server's response to
* the extension, which is when they find out that the negotiation
* was successful.
*/
if (s->server) {
if (sent && ret == SSL_TLSEXT_ERR_OK && !s->hit) {
/* Only store the hostname in the session if we accepted it. */
OPENSSL_free(s->session->ext.hostname);
s->session->ext.hostname = OPENSSL_strdup(s->ext.hostname);
if (s->session->ext.hostname == NULL && s->ext.hostname != NULL) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
}
}
}
/*
* If we switched contexts (whether here or in the client_hello callback),
* move the sess_accept increment from the session_ctx to the new
* context, to avoid the confusing situation of having sess_accept_good
* exceed sess_accept (zero) for the new context.
*/
if (SSL_IS_FIRST_HANDSHAKE(s) && s->ctx != s->session_ctx
&& s->hello_retry_request == SSL_HRR_NONE) {
ssl_tsan_counter(s->ctx, &s->ctx->stats.sess_accept);
ssl_tsan_decr(s->session_ctx, &s->session_ctx->stats.sess_accept);
}
/*
* If we're expecting to send a ticket, and tickets were previously enabled,
* and now tickets are disabled, then turn off expected ticket.
* Also, if this is not a resumption, create a new session ID
*/
if (ret == SSL_TLSEXT_ERR_OK && s->ext.ticket_expected
&& was_ticket && (SSL_get_options(s) & SSL_OP_NO_TICKET) != 0) {
s->ext.ticket_expected = 0;
if (!s->hit) {
SSL_SESSION* ss = SSL_get_session(s);
if (ss != NULL) {
OPENSSL_free(ss->ext.tick);
ss->ext.tick = NULL;
ss->ext.ticklen = 0;
ss->ext.tick_lifetime_hint = 0;
ss->ext.tick_age_add = 0;
if (!ssl_generate_session_id(s, ss)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return 0;
}
} else {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return 0;
}
}
}
switch (ret) {
case SSL_TLSEXT_ERR_ALERT_FATAL:
SSLfatal(s, altmp, SSL_R_CALLBACK_FAILED);
return 0;
case SSL_TLSEXT_ERR_ALERT_WARNING:
/* TLSv1.3 doesn't have warning alerts so we suppress this */
if (!SSL_IS_TLS13(s))
ssl3_send_alert(s, SSL3_AL_WARNING, altmp);
s->servername_done = 0;
return 1;
case SSL_TLSEXT_ERR_NOACK:
s->servername_done = 0;
return 1;
default:
return 1;
}
}
static int final_ec_pt_formats(SSL *s, unsigned int context, int sent)
{
unsigned long alg_k, alg_a;
if (s->server)
return 1;
alg_k = s->s3.tmp.new_cipher->algorithm_mkey;
alg_a = s->s3.tmp.new_cipher->algorithm_auth;
/*
* If we are client and using an elliptic curve cryptography cipher
* suite, then if server returns an EC point formats lists extension it
* must contain uncompressed.
*/
if (s->ext.ecpointformats != NULL
&& s->ext.ecpointformats_len > 0
&& s->ext.peer_ecpointformats != NULL
&& s->ext.peer_ecpointformats_len > 0
&& ((alg_k & SSL_kECDHE) || (alg_a & SSL_aECDSA))) {
/* we are using an ECC cipher */
size_t i;
unsigned char *list = s->ext.peer_ecpointformats;
for (i = 0; i < s->ext.peer_ecpointformats_len; i++) {
if (*list++ == TLSEXT_ECPOINTFORMAT_uncompressed)
break;
}
if (i == s->ext.peer_ecpointformats_len) {
SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
SSL_R_TLS_INVALID_ECPOINTFORMAT_LIST);
return 0;
}
}
return 1;
}
static int init_session_ticket(SSL *s, unsigned int context)
{
if (!s->server)
s->ext.ticket_expected = 0;
return 1;
}
#ifndef OPENSSL_NO_OCSP
static int init_status_request(SSL *s, unsigned int context)
{
if (s->server) {
s->ext.status_type = TLSEXT_STATUSTYPE_nothing;
} else {
/*
* Ensure we get sensible values passed to tlsext_status_cb in the event
* that we don't receive a status message
*/
OPENSSL_free(s->ext.ocsp.resp);
s->ext.ocsp.resp = NULL;
s->ext.ocsp.resp_len = 0;
}
return 1;
}
#endif
#ifndef OPENSSL_NO_NEXTPROTONEG
static int init_npn(SSL *s, unsigned int context)
{
s->s3.npn_seen = 0;
return 1;
}
#endif
static int init_alpn(SSL *s, unsigned int context)
{
OPENSSL_free(s->s3.alpn_selected);
s->s3.alpn_selected = NULL;
s->s3.alpn_selected_len = 0;
if (s->server) {
OPENSSL_free(s->s3.alpn_proposed);
s->s3.alpn_proposed = NULL;
s->s3.alpn_proposed_len = 0;
}
return 1;
}
static int final_alpn(SSL *s, unsigned int context, int sent)
{
if (!s->server && !sent && s->session->ext.alpn_selected != NULL)
s->ext.early_data_ok = 0;
if (!s->server || !SSL_IS_TLS13(s))
return 1;
/*
* Call alpn_select callback if needed. Has to be done after SNI and
* cipher negotiation (HTTP/2 restricts permitted ciphers). In TLSv1.3
* we also have to do this before we decide whether to accept early_data.
* In TLSv1.3 we've already negotiated our cipher so we do this call now.
* For < TLSv1.3 we defer it until after cipher negotiation.
*
* On failure SSLfatal() already called.
*/
return tls_handle_alpn(s);
}
static int init_sig_algs(SSL *s, unsigned int context)
{
/* Clear any signature algorithms extension received */
OPENSSL_free(s->s3.tmp.peer_sigalgs);
s->s3.tmp.peer_sigalgs = NULL;
s->s3.tmp.peer_sigalgslen = 0;
return 1;
}
static int init_sig_algs_cert(SSL *s, ossl_unused unsigned int context)
{
/* Clear any signature algorithms extension received */
OPENSSL_free(s->s3.tmp.peer_cert_sigalgs);
s->s3.tmp.peer_cert_sigalgs = NULL;
s->s3.tmp.peer_cert_sigalgslen = 0;
return 1;
}
#ifndef OPENSSL_NO_SRP
static int init_srp(SSL *s, unsigned int context)
{
OPENSSL_free(s->srp_ctx.login);
s->srp_ctx.login = NULL;
return 1;
}
#endif
static int init_ec_point_formats(SSL *s, unsigned int context)
{
OPENSSL_free(s->ext.peer_ecpointformats);
s->ext.peer_ecpointformats = NULL;
s->ext.peer_ecpointformats_len = 0;
return 1;
}
static int init_etm(SSL *s, unsigned int context)
{
s->ext.use_etm = 0;
return 1;
}
static int init_ems(SSL *s, unsigned int context)
{
if (s->s3.flags & TLS1_FLAGS_RECEIVED_EXTMS) {
s->s3.flags &= ~TLS1_FLAGS_RECEIVED_EXTMS;
s->s3.flags |= TLS1_FLAGS_REQUIRED_EXTMS;
}
return 1;
}
static int final_ems(SSL *s, unsigned int context, int sent)
{
/*
* Check extended master secret extension is not dropped on
* renegotiation.
*/
if (!(s->s3.flags & TLS1_FLAGS_RECEIVED_EXTMS)
&& (s->s3.flags & TLS1_FLAGS_REQUIRED_EXTMS)) {
SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_INCONSISTENT_EXTMS);
return 0;
}
if (!s->server && s->hit) {
/*
* Check extended master secret extension is consistent with
* original session.
*/
if (!(s->s3.flags & TLS1_FLAGS_RECEIVED_EXTMS) !=
!(s->session->flags & SSL_SESS_FLAG_EXTMS)) {
SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_INCONSISTENT_EXTMS);
return 0;
}
}
return 1;
}
static int init_certificate_authorities(SSL *s, unsigned int context)
{
sk_X509_NAME_pop_free(s->s3.tmp.peer_ca_names, X509_NAME_free);
s->s3.tmp.peer_ca_names = NULL;
return 1;
}
static EXT_RETURN tls_construct_certificate_authorities(SSL *s, WPACKET *pkt,
unsigned int context,
X509 *x,
size_t chainidx)
{
const STACK_OF(X509_NAME) *ca_sk = get_ca_names(s);
if (ca_sk == NULL || sk_X509_NAME_num(ca_sk) == 0)
return EXT_RETURN_NOT_SENT;
if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_certificate_authorities)
|| !WPACKET_start_sub_packet_u16(pkt)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return EXT_RETURN_FAIL;
}
if (!construct_ca_names(s, ca_sk, pkt)) {
/* SSLfatal() already called */
return EXT_RETURN_FAIL;
}
if (!WPACKET_close(pkt)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return EXT_RETURN_FAIL;
}
return EXT_RETURN_SENT;
}
static int tls_parse_certificate_authorities(SSL *s, PACKET *pkt,
unsigned int context, X509 *x,
size_t chainidx)
{
if (!parse_ca_names(s, pkt))
return 0;
if (PACKET_remaining(pkt) != 0) {
SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_EXTENSION);
return 0;
}
return 1;
}
#ifndef OPENSSL_NO_SRTP
static int init_srtp(SSL *s, unsigned int context)
{
if (s->server)
s->srtp_profile = NULL;
return 1;
}
#endif
static int final_sig_algs(SSL *s, unsigned int context, int sent)
{
if (!sent && SSL_IS_TLS13(s) && !s->hit) {
SSLfatal(s, TLS13_AD_MISSING_EXTENSION,
SSL_R_MISSING_SIGALGS_EXTENSION);
return 0;
}
return 1;
}
static int final_key_share(SSL *s, unsigned int context, int sent)
{
#if !defined(OPENSSL_NO_TLS1_3)
if (!SSL_IS_TLS13(s))
return 1;
/* Nothing to do for key_share in an HRR */
if ((context & SSL_EXT_TLS1_3_HELLO_RETRY_REQUEST) != 0)
return 1;
/*
* If
* we are a client
* AND
* we have no key_share
* AND
* (we are not resuming
* OR the kex_mode doesn't allow non key_share resumes)
* THEN
* fail;
*/
if (!s->server
&& !sent
&& (!s->hit
|| (s->ext.psk_kex_mode & TLSEXT_KEX_MODE_FLAG_KE) == 0)) {
/* Nothing left we can do - just fail */
SSLfatal(s, SSL_AD_MISSING_EXTENSION, SSL_R_NO_SUITABLE_KEY_SHARE);
return 0;
}
/*
* IF
* we are a server
* THEN
* IF
* we have a suitable key_share
* THEN
* IF
* we are stateless AND we have no cookie
* THEN
* send a HelloRetryRequest
* ELSE
* IF
* we didn't already send a HelloRetryRequest
* AND
* the client sent a key_share extension
* AND
* (we are not resuming
* OR the kex_mode allows key_share resumes)
* AND
* a shared group exists
* THEN
* send a HelloRetryRequest
* ELSE IF
* we are not resuming
* OR
* the kex_mode doesn't allow non key_share resumes
* THEN
* fail
* ELSE IF
* we are stateless AND we have no cookie
* THEN
* send a HelloRetryRequest
*/
if (s->server) {
if (s->s3.peer_tmp != NULL) {
/* We have a suitable key_share */
if ((s->s3.flags & TLS1_FLAGS_STATELESS) != 0
&& !s->ext.cookieok) {
if (!ossl_assert(s->hello_retry_request == SSL_HRR_NONE)) {
/*
* If we are stateless then we wouldn't know about any
* previously sent HRR - so how can this be anything other
* than 0?
*/
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return 0;
}
s->hello_retry_request = SSL_HRR_PENDING;
return 1;
}
} else {
/* No suitable key_share */
if (s->hello_retry_request == SSL_HRR_NONE && sent
&& (!s->hit
|| (s->ext.psk_kex_mode & TLSEXT_KEX_MODE_FLAG_KE_DHE)
!= 0)) {
const uint16_t *pgroups, *clntgroups;
size_t num_groups, clnt_num_groups, i;
unsigned int group_id = 0;
/* Check if a shared group exists */
/* Get the clients list of supported groups. */
tls1_get_peer_groups(s, &clntgroups, &clnt_num_groups);
tls1_get_supported_groups(s, &pgroups, &num_groups);
/*
* Find the first group we allow that is also in client's list
*/
for (i = 0; i < num_groups; i++) {
group_id = pgroups[i];
if (check_in_list(s, group_id, clntgroups, clnt_num_groups,
1)
&& tls_group_allowed(s, group_id,
SSL_SECOP_CURVE_SUPPORTED)
&& tls_valid_group(s, group_id, TLS1_3_VERSION,
TLS1_3_VERSION, 0, NULL))
break;
}
if (i < num_groups) {
/* A shared group exists so send a HelloRetryRequest */
s->s3.group_id = group_id;
s->hello_retry_request = SSL_HRR_PENDING;
return 1;
}
}
if (!s->hit
|| (s->ext.psk_kex_mode & TLSEXT_KEX_MODE_FLAG_KE) == 0) {
/* Nothing left we can do - just fail */
SSLfatal(s, sent ? SSL_AD_HANDSHAKE_FAILURE
: SSL_AD_MISSING_EXTENSION,
SSL_R_NO_SUITABLE_KEY_SHARE);
return 0;
}
if ((s->s3.flags & TLS1_FLAGS_STATELESS) != 0
&& !s->ext.cookieok) {
if (!ossl_assert(s->hello_retry_request == SSL_HRR_NONE)) {
/*
* If we are stateless then we wouldn't know about any
* previously sent HRR - so how can this be anything other
* than 0?
*/
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return 0;
}
s->hello_retry_request = SSL_HRR_PENDING;
return 1;
}
}
/*
* We have a key_share so don't send any more HelloRetryRequest
* messages
*/
if (s->hello_retry_request == SSL_HRR_PENDING)
s->hello_retry_request = SSL_HRR_COMPLETE;
} else {
/*
* For a client side resumption with no key_share we need to generate
* the handshake secret (otherwise this is done during key_share
* processing).
*/
if (!sent && !tls13_generate_handshake_secret(s, NULL, 0)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return 0;
}
}
#endif /* !defined(OPENSSL_NO_TLS1_3) */
return 1;
}
static int init_psk_kex_modes(SSL *s, unsigned int context)
{
s->ext.psk_kex_mode = TLSEXT_KEX_MODE_FLAG_NONE;
return 1;
}
int tls_psk_do_binder(SSL *s, const EVP_MD *md, const unsigned char *msgstart,
size_t binderoffset, const unsigned char *binderin,
unsigned char *binderout, SSL_SESSION *sess, int sign,
int external)
{
EVP_PKEY *mackey = NULL;
EVP_MD_CTX *mctx = NULL;
unsigned char hash[EVP_MAX_MD_SIZE], binderkey[EVP_MAX_MD_SIZE];
unsigned char finishedkey[EVP_MAX_MD_SIZE], tmpbinder[EVP_MAX_MD_SIZE];
unsigned char *early_secret;
#ifdef CHARSET_EBCDIC
static const unsigned char resumption_label[] = { 0x72, 0x65, 0x73, 0x20, 0x62, 0x69, 0x6E, 0x64, 0x65, 0x72, 0x00 };
static const unsigned char external_label[] = { 0x65, 0x78, 0x74, 0x20, 0x62, 0x69, 0x6E, 0x64, 0x65, 0x72, 0x00 };
#else
static const unsigned char resumption_label[] = "res binder";
static const unsigned char external_label[] = "ext binder";
#endif
const unsigned char *label;
size_t bindersize, labelsize, hashsize;
int hashsizei = EVP_MD_get_size(md);
int ret = -1;
int usepskfored = 0;
/* Ensure cast to size_t is safe */
if (!ossl_assert(hashsizei >= 0)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
goto err;
}
hashsize = (size_t)hashsizei;
if (external
&& s->early_data_state == SSL_EARLY_DATA_CONNECTING
&& s->session->ext.max_early_data == 0
&& sess->ext.max_early_data > 0)
usepskfored = 1;
if (external) {
label = external_label;
labelsize = sizeof(external_label) - 1;
} else {
label = resumption_label;
labelsize = sizeof(resumption_label) - 1;
}
/*
* Generate the early_secret. On the server side we've selected a PSK to
* resume with (internal or external) so we always do this. On the client
* side we do this for a non-external (i.e. resumption) PSK or external PSK
* that will be used for early_data so that it is in place for sending early
* data. For client side external PSK not being used for early_data we
* generate it but store it away for later use.
*/
if (s->server || !external || usepskfored)
early_secret = (unsigned char *)s->early_secret;
else
early_secret = (unsigned char *)sess->early_secret;
if (!tls13_generate_secret(s, md, NULL, sess->master_key,
sess->master_key_length, early_secret)) {
/* SSLfatal() already called */
goto err;
}
/*
* Create the handshake hash for the binder key...the messages so far are
* empty!
*/
mctx = EVP_MD_CTX_new();
if (mctx == NULL
|| EVP_DigestInit_ex(mctx, md, NULL) <= 0
|| EVP_DigestFinal_ex(mctx, hash, NULL) <= 0) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
goto err;
}
/* Generate the binder key */
if (!tls13_hkdf_expand(s, md, early_secret, label, labelsize, hash,
hashsize, binderkey, hashsize, 1)) {
/* SSLfatal() already called */
goto err;
}
/* Generate the finished key */
if (!tls13_derive_finishedkey(s, md, binderkey, finishedkey, hashsize)) {
/* SSLfatal() already called */
goto err;
}
if (EVP_DigestInit_ex(mctx, md, NULL) <= 0) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
goto err;
}
/*
* Get a hash of the ClientHello up to the start of the binders. If we are
* following a HelloRetryRequest then this includes the hash of the first
* ClientHello and the HelloRetryRequest itself.
*/
if (s->hello_retry_request == SSL_HRR_PENDING) {
size_t hdatalen;
long hdatalen_l;
void *hdata;
hdatalen = hdatalen_l =
BIO_get_mem_data(s->s3.handshake_buffer, &hdata);
if (hdatalen_l <= 0) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_BAD_HANDSHAKE_LENGTH);
goto err;
}
/*
* For servers the handshake buffer data will include the second
* ClientHello - which we don't want - so we need to take that bit off.
*/
if (s->server) {
PACKET hashprefix, msg;
/* Find how many bytes are left after the first two messages */
if (!PACKET_buf_init(&hashprefix, hdata, hdatalen)
|| !PACKET_forward(&hashprefix, 1)
|| !PACKET_get_length_prefixed_3(&hashprefix, &msg)
|| !PACKET_forward(&hashprefix, 1)
|| !PACKET_get_length_prefixed_3(&hashprefix, &msg)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
goto err;
}
hdatalen -= PACKET_remaining(&hashprefix);
}
if (EVP_DigestUpdate(mctx, hdata, hdatalen) <= 0) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
goto err;
}
}
if (EVP_DigestUpdate(mctx, msgstart, binderoffset) <= 0
|| EVP_DigestFinal_ex(mctx, hash, NULL) <= 0) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
goto err;
}
mackey = EVP_PKEY_new_raw_private_key_ex(s->ctx->libctx, "HMAC",
s->ctx->propq, finishedkey,
hashsize);
if (mackey == NULL) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
goto err;
}
if (!sign)
binderout = tmpbinder;
bindersize = hashsize;
if (EVP_DigestSignInit_ex(mctx, NULL, EVP_MD_get0_name(md), s->ctx->libctx,
s->ctx->propq, mackey, NULL) <= 0
|| EVP_DigestSignUpdate(mctx, hash, hashsize) <= 0
|| EVP_DigestSignFinal(mctx, binderout, &bindersize) <= 0
|| bindersize != hashsize) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
goto err;
}
if (sign) {
ret = 1;
} else {
/* HMAC keys can't do EVP_DigestVerify* - use CRYPTO_memcmp instead */
ret = (CRYPTO_memcmp(binderin, binderout, hashsize) == 0);
if (!ret)
SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_BINDER_DOES_NOT_VERIFY);
}
err:
OPENSSL_cleanse(binderkey, sizeof(binderkey));
OPENSSL_cleanse(finishedkey, sizeof(finishedkey));
EVP_PKEY_free(mackey);
EVP_MD_CTX_free(mctx);
return ret;
}
static int final_early_data(SSL *s, unsigned int context, int sent)
{
if (!sent)
return 1;
if (!s->server) {
if (context == SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS
&& sent
&& !s->ext.early_data_ok) {
/*
* If we get here then the server accepted our early_data but we
* later realised that it shouldn't have done (e.g. inconsistent
* ALPN)
*/
SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_BAD_EARLY_DATA);
return 0;
}
return 1;
}
if (s->max_early_data == 0
|| !s->hit
|| s->early_data_state != SSL_EARLY_DATA_ACCEPTING
|| !s->ext.early_data_ok
|| s->hello_retry_request != SSL_HRR_NONE
|| (s->allow_early_data_cb != NULL
&& !s->allow_early_data_cb(s,
s->allow_early_data_cb_data))) {
s->ext.early_data = SSL_EARLY_DATA_REJECTED;
} else {
s->ext.early_data = SSL_EARLY_DATA_ACCEPTED;
if (!tls13_change_cipher_state(s,
SSL3_CC_EARLY | SSL3_CHANGE_CIPHER_SERVER_READ)) {
/* SSLfatal() already called */
return 0;
}
}
return 1;
}
static int final_maxfragmentlen(SSL *s, unsigned int context, int sent)
{
- /*
- * Session resumption on server-side with MFL extension active
- * BUT MFL extension packet was not resent (i.e. sent == 0)
- */
- if (s->server && s->hit && USE_MAX_FRAGMENT_LENGTH_EXT(s->session)
- && !sent ) {
- SSLfatal(s, SSL_AD_MISSING_EXTENSION, SSL_R_BAD_EXTENSION);
- return 0;
- }
+ /* MaxFragmentLength defaults to disabled */
+ if (s->session->ext.max_fragment_len_mode == TLSEXT_max_fragment_length_UNSPECIFIED)
+ s->session->ext.max_fragment_len_mode = TLSEXT_max_fragment_length_DISABLED;
/* Current SSL buffer is lower than requested MFL */
if (s->session && USE_MAX_FRAGMENT_LENGTH_EXT(s->session)
&& s->max_send_fragment < GET_MAX_FRAGMENT_LENGTH(s->session))
/* trigger a larger buffer reallocation */
if (!ssl3_setup_buffers(s)) {
/* SSLfatal() already called */
return 0;
}
return 1;
}
static int init_post_handshake_auth(SSL *s, ossl_unused unsigned int context)
{
s->post_handshake_auth = SSL_PHA_NONE;
return 1;
}
/*
* If clients offer "pre_shared_key" without a "psk_key_exchange_modes"
* extension, servers MUST abort the handshake.
*/
static int final_psk(SSL *s, unsigned int context, int sent)
{
if (s->server && sent && s->clienthello != NULL
&& !s->clienthello->pre_proc_exts[TLSEXT_IDX_psk_kex_modes].present) {
SSLfatal(s, TLS13_AD_MISSING_EXTENSION,
SSL_R_MISSING_PSK_KEX_MODES_EXTENSION);
return 0;
}
return 1;
}
diff --git a/crypto/openssl/ssl/statem/extensions_clnt.c b/crypto/openssl/ssl/statem/extensions_clnt.c
index 842be0722bd0..ced88f77ba3c 100644
--- a/crypto/openssl/ssl/statem/extensions_clnt.c
+++ b/crypto/openssl/ssl/statem/extensions_clnt.c
@@ -1,1983 +1,2008 @@
/*
- * 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 <openssl/ocsp.h>
#include "../ssl_local.h"
#include "internal/cryptlib.h"
#include "statem_local.h"
EXT_RETURN tls_construct_ctos_renegotiate(SSL *s, WPACKET *pkt,
unsigned int context, X509 *x,
size_t chainidx)
{
/* Add RI if renegotiating */
if (!s->renegotiate)
return EXT_RETURN_NOT_SENT;
if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_renegotiate)
|| !WPACKET_start_sub_packet_u16(pkt)
|| !WPACKET_sub_memcpy_u8(pkt, s->s3.previous_client_finished,
s->s3.previous_client_finished_len)
|| !WPACKET_close(pkt)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return EXT_RETURN_FAIL;
}
return EXT_RETURN_SENT;
}
EXT_RETURN tls_construct_ctos_server_name(SSL *s, WPACKET *pkt,
unsigned int context, X509 *x,
size_t chainidx)
{
if (s->ext.hostname == NULL)
return EXT_RETURN_NOT_SENT;
/* Add TLS extension servername to the Client Hello message */
if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_server_name)
/* Sub-packet for server_name extension */
|| !WPACKET_start_sub_packet_u16(pkt)
/* Sub-packet for servername list (always 1 hostname)*/
|| !WPACKET_start_sub_packet_u16(pkt)
|| !WPACKET_put_bytes_u8(pkt, TLSEXT_NAMETYPE_host_name)
|| !WPACKET_sub_memcpy_u16(pkt, s->ext.hostname,
strlen(s->ext.hostname))
|| !WPACKET_close(pkt)
|| !WPACKET_close(pkt)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return EXT_RETURN_FAIL;
}
return EXT_RETURN_SENT;
}
/* Push a Max Fragment Len extension into ClientHello */
EXT_RETURN tls_construct_ctos_maxfragmentlen(SSL *s, WPACKET *pkt,
unsigned int context, X509 *x,
size_t chainidx)
{
if (s->ext.max_fragment_len_mode == TLSEXT_max_fragment_length_DISABLED)
return EXT_RETURN_NOT_SENT;
/* Add Max Fragment Length extension if client enabled it. */
/*-
* 4 bytes for this extension type and extension length
* 1 byte for the Max Fragment Length code value.
*/
if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_max_fragment_length)
/* Sub-packet for Max Fragment Length extension (1 byte) */
|| !WPACKET_start_sub_packet_u16(pkt)
|| !WPACKET_put_bytes_u8(pkt, s->ext.max_fragment_len_mode)
|| !WPACKET_close(pkt)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return EXT_RETURN_FAIL;
}
return EXT_RETURN_SENT;
}
#ifndef OPENSSL_NO_SRP
EXT_RETURN tls_construct_ctos_srp(SSL *s, WPACKET *pkt, unsigned int context,
X509 *x, size_t chainidx)
{
/* Add SRP username if there is one */
if (s->srp_ctx.login == NULL)
return EXT_RETURN_NOT_SENT;
if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_srp)
/* Sub-packet for SRP extension */
|| !WPACKET_start_sub_packet_u16(pkt)
|| !WPACKET_start_sub_packet_u8(pkt)
/* login must not be zero...internal error if so */
|| !WPACKET_set_flags(pkt, WPACKET_FLAGS_NON_ZERO_LENGTH)
|| !WPACKET_memcpy(pkt, s->srp_ctx.login,
strlen(s->srp_ctx.login))
|| !WPACKET_close(pkt)
|| !WPACKET_close(pkt)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return EXT_RETURN_FAIL;
}
return EXT_RETURN_SENT;
}
#endif
static int use_ecc(SSL *s, int min_version, int max_version)
{
int i, end, ret = 0;
unsigned long alg_k, alg_a;
STACK_OF(SSL_CIPHER) *cipher_stack = NULL;
const uint16_t *pgroups = NULL;
size_t num_groups, j;
/* See if we support any ECC ciphersuites */
if (s->version == SSL3_VERSION)
return 0;
cipher_stack = SSL_get1_supported_ciphers(s);
end = sk_SSL_CIPHER_num(cipher_stack);
for (i = 0; i < end; i++) {
const SSL_CIPHER *c = sk_SSL_CIPHER_value(cipher_stack, i);
alg_k = c->algorithm_mkey;
alg_a = c->algorithm_auth;
if ((alg_k & (SSL_kECDHE | SSL_kECDHEPSK))
|| (alg_a & SSL_aECDSA)
|| c->min_tls >= TLS1_3_VERSION) {
ret = 1;
break;
}
}
sk_SSL_CIPHER_free(cipher_stack);
if (!ret)
return 0;
/* Check we have at least one EC supported group */
tls1_get_supported_groups(s, &pgroups, &num_groups);
for (j = 0; j < num_groups; j++) {
uint16_t ctmp = pgroups[j];
if (tls_valid_group(s, ctmp, min_version, max_version, 1, NULL)
&& tls_group_allowed(s, ctmp, SSL_SECOP_CURVE_SUPPORTED))
return 1;
}
return 0;
}
EXT_RETURN tls_construct_ctos_ec_pt_formats(SSL *s, WPACKET *pkt,
unsigned int context, X509 *x,
size_t chainidx)
{
const unsigned char *pformats;
size_t num_formats;
int reason, min_version, max_version;
reason = ssl_get_min_max_version(s, &min_version, &max_version, NULL);
if (reason != 0) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, reason);
return EXT_RETURN_FAIL;
}
if (!use_ecc(s, min_version, max_version))
return EXT_RETURN_NOT_SENT;
/* Add TLS extension ECPointFormats to the ClientHello message */
tls1_get_formatlist(s, &pformats, &num_formats);
if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_ec_point_formats)
/* Sub-packet for formats extension */
|| !WPACKET_start_sub_packet_u16(pkt)
|| !WPACKET_sub_memcpy_u8(pkt, pformats, num_formats)
|| !WPACKET_close(pkt)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return EXT_RETURN_FAIL;
}
return EXT_RETURN_SENT;
}
EXT_RETURN tls_construct_ctos_supported_groups(SSL *s, WPACKET *pkt,
unsigned int context, X509 *x,
size_t chainidx)
{
const uint16_t *pgroups = NULL;
size_t num_groups = 0, i, tls13added = 0, added = 0;
int min_version, max_version, reason;
reason = ssl_get_min_max_version(s, &min_version, &max_version, NULL);
if (reason != 0) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, reason);
return EXT_RETURN_FAIL;
}
/*
* We only support EC groups in TLSv1.2 or below, and in DTLS. Therefore
* if we don't have EC support then we don't send this extension.
*/
if (!use_ecc(s, min_version, max_version)
&& (SSL_IS_DTLS(s) || max_version < TLS1_3_VERSION))
return EXT_RETURN_NOT_SENT;
/*
* Add TLS extension supported_groups to the ClientHello message
*/
tls1_get_supported_groups(s, &pgroups, &num_groups);
if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_supported_groups)
/* Sub-packet for supported_groups extension */
|| !WPACKET_start_sub_packet_u16(pkt)
|| !WPACKET_start_sub_packet_u16(pkt)
|| !WPACKET_set_flags(pkt, WPACKET_FLAGS_NON_ZERO_LENGTH)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return EXT_RETURN_FAIL;
}
/* Copy group ID if supported */
for (i = 0; i < num_groups; i++) {
uint16_t ctmp = pgroups[i];
int okfortls13;
if (tls_valid_group(s, ctmp, min_version, max_version, 0, &okfortls13)
&& tls_group_allowed(s, ctmp, SSL_SECOP_CURVE_SUPPORTED)) {
if (!WPACKET_put_bytes_u16(pkt, ctmp)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return EXT_RETURN_FAIL;
}
if (okfortls13 && max_version == TLS1_3_VERSION)
tls13added++;
added++;
}
}
if (!WPACKET_close(pkt) || !WPACKET_close(pkt)) {
if (added == 0)
SSLfatal_data(s, SSL_AD_INTERNAL_ERROR, SSL_R_NO_SUITABLE_GROUPS,
"No groups enabled for max supported SSL/TLS version");
else
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return EXT_RETURN_FAIL;
}
if (tls13added == 0 && max_version == TLS1_3_VERSION) {
SSLfatal_data(s, SSL_AD_INTERNAL_ERROR, SSL_R_NO_SUITABLE_GROUPS,
"No groups enabled for max supported SSL/TLS version");
return EXT_RETURN_FAIL;
}
return EXT_RETURN_SENT;
}
EXT_RETURN tls_construct_ctos_session_ticket(SSL *s, WPACKET *pkt,
unsigned int context, X509 *x,
size_t chainidx)
{
size_t ticklen;
if (!tls_use_ticket(s))
return EXT_RETURN_NOT_SENT;
if (!s->new_session && s->session != NULL
&& s->session->ext.tick != NULL
&& s->session->ssl_version != TLS1_3_VERSION) {
ticklen = s->session->ext.ticklen;
} else if (s->session && s->ext.session_ticket != NULL
&& s->ext.session_ticket->data != NULL) {
ticklen = s->ext.session_ticket->length;
s->session->ext.tick = OPENSSL_malloc(ticklen);
if (s->session->ext.tick == NULL) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return EXT_RETURN_FAIL;
}
memcpy(s->session->ext.tick,
s->ext.session_ticket->data, ticklen);
s->session->ext.ticklen = ticklen;
} else {
ticklen = 0;
}
if (ticklen == 0 && s->ext.session_ticket != NULL &&
s->ext.session_ticket->data == NULL)
return EXT_RETURN_NOT_SENT;
if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_session_ticket)
|| !WPACKET_sub_memcpy_u16(pkt, s->session->ext.tick, ticklen)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return EXT_RETURN_FAIL;
}
return EXT_RETURN_SENT;
}
EXT_RETURN tls_construct_ctos_sig_algs(SSL *s, WPACKET *pkt,
unsigned int context, X509 *x,
size_t chainidx)
{
size_t salglen;
const uint16_t *salg;
if (!SSL_CLIENT_USE_SIGALGS(s))
return EXT_RETURN_NOT_SENT;
salglen = tls12_get_psigalgs(s, 1, &salg);
if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_signature_algorithms)
/* Sub-packet for sig-algs extension */
|| !WPACKET_start_sub_packet_u16(pkt)
/* Sub-packet for the actual list */
|| !WPACKET_start_sub_packet_u16(pkt)
|| !tls12_copy_sigalgs(s, pkt, salg, salglen)
|| !WPACKET_close(pkt)
|| !WPACKET_close(pkt)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return EXT_RETURN_FAIL;
}
return EXT_RETURN_SENT;
}
#ifndef OPENSSL_NO_OCSP
EXT_RETURN tls_construct_ctos_status_request(SSL *s, WPACKET *pkt,
unsigned int context, X509 *x,
size_t chainidx)
{
int i;
/* This extension isn't defined for client Certificates */
if (x != NULL)
return EXT_RETURN_NOT_SENT;
if (s->ext.status_type != TLSEXT_STATUSTYPE_ocsp)
return EXT_RETURN_NOT_SENT;
if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_status_request)
/* Sub-packet for status request extension */
|| !WPACKET_start_sub_packet_u16(pkt)
|| !WPACKET_put_bytes_u8(pkt, TLSEXT_STATUSTYPE_ocsp)
/* Sub-packet for the ids */
|| !WPACKET_start_sub_packet_u16(pkt)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return EXT_RETURN_FAIL;
}
for (i = 0; i < sk_OCSP_RESPID_num(s->ext.ocsp.ids); i++) {
unsigned char *idbytes;
OCSP_RESPID *id = sk_OCSP_RESPID_value(s->ext.ocsp.ids, i);
int idlen = i2d_OCSP_RESPID(id, NULL);
if (idlen <= 0
/* Sub-packet for an individual id */
|| !WPACKET_sub_allocate_bytes_u16(pkt, idlen, &idbytes)
|| i2d_OCSP_RESPID(id, &idbytes) != idlen) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return EXT_RETURN_FAIL;
}
}
if (!WPACKET_close(pkt)
|| !WPACKET_start_sub_packet_u16(pkt)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return EXT_RETURN_FAIL;
}
if (s->ext.ocsp.exts) {
unsigned char *extbytes;
int extlen = i2d_X509_EXTENSIONS(s->ext.ocsp.exts, NULL);
if (extlen < 0) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return EXT_RETURN_FAIL;
}
if (!WPACKET_allocate_bytes(pkt, extlen, &extbytes)
|| i2d_X509_EXTENSIONS(s->ext.ocsp.exts, &extbytes)
!= extlen) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return EXT_RETURN_FAIL;
}
}
if (!WPACKET_close(pkt) || !WPACKET_close(pkt)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return EXT_RETURN_FAIL;
}
return EXT_RETURN_SENT;
}
#endif
#ifndef OPENSSL_NO_NEXTPROTONEG
EXT_RETURN tls_construct_ctos_npn(SSL *s, WPACKET *pkt, unsigned int context,
X509 *x, size_t chainidx)
{
if (s->ctx->ext.npn_select_cb == NULL || !SSL_IS_FIRST_HANDSHAKE(s))
return EXT_RETURN_NOT_SENT;
/*
* The client advertises an empty extension to indicate its support
* for Next Protocol Negotiation
*/
if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_next_proto_neg)
|| !WPACKET_put_bytes_u16(pkt, 0)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return EXT_RETURN_FAIL;
}
return EXT_RETURN_SENT;
}
#endif
EXT_RETURN tls_construct_ctos_alpn(SSL *s, WPACKET *pkt, unsigned int context,
X509 *x, size_t chainidx)
{
s->s3.alpn_sent = 0;
if (s->ext.alpn == NULL || !SSL_IS_FIRST_HANDSHAKE(s))
return EXT_RETURN_NOT_SENT;
if (!WPACKET_put_bytes_u16(pkt,
TLSEXT_TYPE_application_layer_protocol_negotiation)
/* Sub-packet ALPN extension */
|| !WPACKET_start_sub_packet_u16(pkt)
|| !WPACKET_sub_memcpy_u16(pkt, s->ext.alpn, s->ext.alpn_len)
|| !WPACKET_close(pkt)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return EXT_RETURN_FAIL;
}
s->s3.alpn_sent = 1;
return EXT_RETURN_SENT;
}
#ifndef OPENSSL_NO_SRTP
EXT_RETURN tls_construct_ctos_use_srtp(SSL *s, WPACKET *pkt,
unsigned int context, X509 *x,
size_t chainidx)
{
STACK_OF(SRTP_PROTECTION_PROFILE) *clnt = SSL_get_srtp_profiles(s);
int i, end;
if (clnt == NULL)
return EXT_RETURN_NOT_SENT;
if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_use_srtp)
/* Sub-packet for SRTP extension */
|| !WPACKET_start_sub_packet_u16(pkt)
/* Sub-packet for the protection profile list */
|| !WPACKET_start_sub_packet_u16(pkt)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return EXT_RETURN_FAIL;
}
end = sk_SRTP_PROTECTION_PROFILE_num(clnt);
for (i = 0; i < end; i++) {
const SRTP_PROTECTION_PROFILE *prof =
sk_SRTP_PROTECTION_PROFILE_value(clnt, i);
if (prof == NULL || !WPACKET_put_bytes_u16(pkt, prof->id)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return EXT_RETURN_FAIL;
}
}
if (!WPACKET_close(pkt)
/* Add an empty use_mki value */
|| !WPACKET_put_bytes_u8(pkt, 0)
|| !WPACKET_close(pkt)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return EXT_RETURN_FAIL;
}
return EXT_RETURN_SENT;
}
#endif
EXT_RETURN tls_construct_ctos_etm(SSL *s, WPACKET *pkt, unsigned int context,
X509 *x, size_t chainidx)
{
if (s->options & SSL_OP_NO_ENCRYPT_THEN_MAC)
return EXT_RETURN_NOT_SENT;
if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_encrypt_then_mac)
|| !WPACKET_put_bytes_u16(pkt, 0)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return EXT_RETURN_FAIL;
}
return EXT_RETURN_SENT;
}
#ifndef OPENSSL_NO_CT
EXT_RETURN tls_construct_ctos_sct(SSL *s, WPACKET *pkt, unsigned int context,
X509 *x, size_t chainidx)
{
if (s->ct_validation_callback == NULL)
return EXT_RETURN_NOT_SENT;
/* Not defined for client Certificates */
if (x != NULL)
return EXT_RETURN_NOT_SENT;
if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_signed_certificate_timestamp)
|| !WPACKET_put_bytes_u16(pkt, 0)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return EXT_RETURN_FAIL;
}
return EXT_RETURN_SENT;
}
#endif
EXT_RETURN tls_construct_ctos_ems(SSL *s, WPACKET *pkt, unsigned int context,
X509 *x, size_t chainidx)
{
if (s->options & SSL_OP_NO_EXTENDED_MASTER_SECRET)
return EXT_RETURN_NOT_SENT;
if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_extended_master_secret)
|| !WPACKET_put_bytes_u16(pkt, 0)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return EXT_RETURN_FAIL;
}
return EXT_RETURN_SENT;
}
EXT_RETURN tls_construct_ctos_supported_versions(SSL *s, WPACKET *pkt,
unsigned int context, X509 *x,
size_t chainidx)
{
int currv, min_version, max_version, reason;
reason = ssl_get_min_max_version(s, &min_version, &max_version, NULL);
if (reason != 0) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, reason);
return EXT_RETURN_FAIL;
}
/*
* Don't include this if we can't negotiate TLSv1.3. We can do a straight
* comparison here because we will never be called in DTLS.
*/
if (max_version < TLS1_3_VERSION)
return EXT_RETURN_NOT_SENT;
if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_supported_versions)
|| !WPACKET_start_sub_packet_u16(pkt)
|| !WPACKET_start_sub_packet_u8(pkt)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return EXT_RETURN_FAIL;
}
for (currv = max_version; currv >= min_version; currv--) {
if (!WPACKET_put_bytes_u16(pkt, currv)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return EXT_RETURN_FAIL;
}
}
if (!WPACKET_close(pkt) || !WPACKET_close(pkt)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return EXT_RETURN_FAIL;
}
return EXT_RETURN_SENT;
}
/*
* Construct a psk_kex_modes extension.
*/
EXT_RETURN tls_construct_ctos_psk_kex_modes(SSL *s, WPACKET *pkt,
unsigned int context, X509 *x,
size_t chainidx)
{
#ifndef OPENSSL_NO_TLS1_3
int nodhe = s->options & SSL_OP_ALLOW_NO_DHE_KEX;
if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_psk_kex_modes)
|| !WPACKET_start_sub_packet_u16(pkt)
|| !WPACKET_start_sub_packet_u8(pkt)
|| !WPACKET_put_bytes_u8(pkt, TLSEXT_KEX_MODE_KE_DHE)
|| (nodhe && !WPACKET_put_bytes_u8(pkt, TLSEXT_KEX_MODE_KE))
|| !WPACKET_close(pkt)
|| !WPACKET_close(pkt)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return EXT_RETURN_FAIL;
}
s->ext.psk_kex_mode = TLSEXT_KEX_MODE_FLAG_KE_DHE;
if (nodhe)
s->ext.psk_kex_mode |= TLSEXT_KEX_MODE_FLAG_KE;
#endif
return EXT_RETURN_SENT;
}
#ifndef OPENSSL_NO_TLS1_3
static int add_key_share(SSL *s, WPACKET *pkt, unsigned int curve_id)
{
unsigned char *encoded_point = NULL;
EVP_PKEY *key_share_key = NULL;
size_t encodedlen;
if (s->s3.tmp.pkey != NULL) {
if (!ossl_assert(s->hello_retry_request == SSL_HRR_PENDING)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return 0;
}
/*
* Could happen if we got an HRR that wasn't requesting a new key_share
*/
key_share_key = s->s3.tmp.pkey;
} else {
key_share_key = ssl_generate_pkey_group(s, curve_id);
if (key_share_key == NULL) {
/* SSLfatal() already called */
return 0;
}
}
/* Encode the public key. */
encodedlen = EVP_PKEY_get1_encoded_public_key(key_share_key,
&encoded_point);
if (encodedlen == 0) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EC_LIB);
goto err;
}
/* Create KeyShareEntry */
if (!WPACKET_put_bytes_u16(pkt, curve_id)
|| !WPACKET_sub_memcpy_u16(pkt, encoded_point, encodedlen)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
goto err;
}
/*
* When changing to send more than one key_share we're
* going to need to be able to save more than one EVP_PKEY. For now
* we reuse the existing tmp.pkey
*/
s->s3.tmp.pkey = key_share_key;
s->s3.group_id = curve_id;
OPENSSL_free(encoded_point);
return 1;
err:
if (s->s3.tmp.pkey == NULL)
EVP_PKEY_free(key_share_key);
OPENSSL_free(encoded_point);
return 0;
}
#endif
EXT_RETURN tls_construct_ctos_key_share(SSL *s, WPACKET *pkt,
unsigned int context, X509 *x,
size_t chainidx)
{
#ifndef OPENSSL_NO_TLS1_3
size_t i, num_groups = 0;
const uint16_t *pgroups = NULL;
uint16_t curve_id = 0;
/* key_share extension */
if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_key_share)
/* Extension data sub-packet */
|| !WPACKET_start_sub_packet_u16(pkt)
/* KeyShare list sub-packet */
|| !WPACKET_start_sub_packet_u16(pkt)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return EXT_RETURN_FAIL;
}
tls1_get_supported_groups(s, &pgroups, &num_groups);
/*
* Make the number of key_shares sent configurable. For
* now, we just send one
*/
if (s->s3.group_id != 0) {
curve_id = s->s3.group_id;
} else {
for (i = 0; i < num_groups; i++) {
if (!tls_group_allowed(s, pgroups[i], SSL_SECOP_CURVE_SUPPORTED))
continue;
if (!tls_valid_group(s, pgroups[i], TLS1_3_VERSION, TLS1_3_VERSION,
0, NULL))
continue;
curve_id = pgroups[i];
break;
}
}
if (curve_id == 0) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_NO_SUITABLE_KEY_SHARE);
return EXT_RETURN_FAIL;
}
if (!add_key_share(s, pkt, curve_id)) {
/* SSLfatal() already called */
return EXT_RETURN_FAIL;
}
if (!WPACKET_close(pkt) || !WPACKET_close(pkt)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return EXT_RETURN_FAIL;
}
return EXT_RETURN_SENT;
#else
return EXT_RETURN_NOT_SENT;
#endif
}
EXT_RETURN tls_construct_ctos_cookie(SSL *s, WPACKET *pkt, unsigned int context,
X509 *x, size_t chainidx)
{
EXT_RETURN ret = EXT_RETURN_FAIL;
/* Should only be set if we've had an HRR */
if (s->ext.tls13_cookie_len == 0)
return EXT_RETURN_NOT_SENT;
if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_cookie)
/* Extension data sub-packet */
|| !WPACKET_start_sub_packet_u16(pkt)
|| !WPACKET_sub_memcpy_u16(pkt, s->ext.tls13_cookie,
s->ext.tls13_cookie_len)
|| !WPACKET_close(pkt)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
goto end;
}
ret = EXT_RETURN_SENT;
end:
OPENSSL_free(s->ext.tls13_cookie);
s->ext.tls13_cookie = NULL;
s->ext.tls13_cookie_len = 0;
return ret;
}
EXT_RETURN tls_construct_ctos_early_data(SSL *s, WPACKET *pkt,
unsigned int context, X509 *x,
size_t chainidx)
{
#ifndef OPENSSL_NO_PSK
char identity[PSK_MAX_IDENTITY_LEN + 1];
#endif /* OPENSSL_NO_PSK */
const unsigned char *id = NULL;
size_t idlen = 0;
SSL_SESSION *psksess = NULL;
SSL_SESSION *edsess = NULL;
const EVP_MD *handmd = NULL;
if (s->hello_retry_request == SSL_HRR_PENDING)
handmd = ssl_handshake_md(s);
if (s->psk_use_session_cb != NULL
&& (!s->psk_use_session_cb(s, handmd, &id, &idlen, &psksess)
|| (psksess != NULL
&& psksess->ssl_version != TLS1_3_VERSION))) {
SSL_SESSION_free(psksess);
SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_BAD_PSK);
return EXT_RETURN_FAIL;
}
#ifndef OPENSSL_NO_PSK
if (psksess == NULL && s->psk_client_callback != NULL) {
unsigned char psk[PSK_MAX_PSK_LEN];
size_t psklen = 0;
memset(identity, 0, sizeof(identity));
psklen = s->psk_client_callback(s, NULL, identity, sizeof(identity) - 1,
psk, sizeof(psk));
if (psklen > PSK_MAX_PSK_LEN) {
SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, ERR_R_INTERNAL_ERROR);
return EXT_RETURN_FAIL;
} else if (psklen > 0) {
const unsigned char tls13_aes128gcmsha256_id[] = { 0x13, 0x01 };
const SSL_CIPHER *cipher;
idlen = strlen(identity);
if (idlen > PSK_MAX_IDENTITY_LEN) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return EXT_RETURN_FAIL;
}
id = (unsigned char *)identity;
/*
* We found a PSK using an old style callback. We don't know
* the digest so we default to SHA256 as per the TLSv1.3 spec
*/
cipher = SSL_CIPHER_find(s, tls13_aes128gcmsha256_id);
if (cipher == NULL) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return EXT_RETURN_FAIL;
}
psksess = SSL_SESSION_new();
if (psksess == NULL
|| !SSL_SESSION_set1_master_key(psksess, psk, psklen)
|| !SSL_SESSION_set_cipher(psksess, cipher)
|| !SSL_SESSION_set_protocol_version(psksess, TLS1_3_VERSION)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
OPENSSL_cleanse(psk, psklen);
return EXT_RETURN_FAIL;
}
OPENSSL_cleanse(psk, psklen);
}
}
#endif /* OPENSSL_NO_PSK */
SSL_SESSION_free(s->psksession);
s->psksession = psksess;
if (psksess != NULL) {
OPENSSL_free(s->psksession_id);
s->psksession_id = OPENSSL_memdup(id, idlen);
if (s->psksession_id == NULL) {
s->psksession_id_len = 0;
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return EXT_RETURN_FAIL;
}
s->psksession_id_len = idlen;
}
if (s->early_data_state != SSL_EARLY_DATA_CONNECTING
|| (s->session->ext.max_early_data == 0
&& (psksess == NULL || psksess->ext.max_early_data == 0))) {
s->max_early_data = 0;
return EXT_RETURN_NOT_SENT;
}
edsess = s->session->ext.max_early_data != 0 ? s->session : psksess;
s->max_early_data = edsess->ext.max_early_data;
if (edsess->ext.hostname != NULL) {
if (s->ext.hostname == NULL
|| (s->ext.hostname != NULL
&& strcmp(s->ext.hostname, edsess->ext.hostname) != 0)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR,
SSL_R_INCONSISTENT_EARLY_DATA_SNI);
return EXT_RETURN_FAIL;
}
}
if ((s->ext.alpn == NULL && edsess->ext.alpn_selected != NULL)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_INCONSISTENT_EARLY_DATA_ALPN);
return EXT_RETURN_FAIL;
}
/*
* Verify that we are offering an ALPN protocol consistent with the early
* data.
*/
if (edsess->ext.alpn_selected != NULL) {
PACKET prots, alpnpkt;
int found = 0;
if (!PACKET_buf_init(&prots, s->ext.alpn, s->ext.alpn_len)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return EXT_RETURN_FAIL;
}
while (PACKET_get_length_prefixed_1(&prots, &alpnpkt)) {
if (PACKET_equal(&alpnpkt, edsess->ext.alpn_selected,
edsess->ext.alpn_selected_len)) {
found = 1;
break;
}
}
if (!found) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR,
SSL_R_INCONSISTENT_EARLY_DATA_ALPN);
return EXT_RETURN_FAIL;
}
}
if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_early_data)
|| !WPACKET_start_sub_packet_u16(pkt)
|| !WPACKET_close(pkt)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return EXT_RETURN_FAIL;
}
/*
* We set this to rejected here. Later, if the server acknowledges the
* extension, we set it to accepted.
*/
s->ext.early_data = SSL_EARLY_DATA_REJECTED;
s->ext.early_data_ok = 1;
return EXT_RETURN_SENT;
}
#define F5_WORKAROUND_MIN_MSG_LEN 0xff
#define F5_WORKAROUND_MAX_MSG_LEN 0x200
/*
* PSK pre binder overhead =
* 2 bytes for TLSEXT_TYPE_psk
* 2 bytes for extension length
* 2 bytes for identities list length
* 2 bytes for identity length
* 4 bytes for obfuscated_ticket_age
* 2 bytes for binder list length
* 1 byte for binder length
* The above excludes the number of bytes for the identity itself and the
* subsequent binder bytes
*/
#define PSK_PRE_BINDER_OVERHEAD (2 + 2 + 2 + 2 + 4 + 2 + 1)
EXT_RETURN tls_construct_ctos_padding(SSL *s, WPACKET *pkt,
unsigned int context, X509 *x,
size_t chainidx)
{
unsigned char *padbytes;
size_t hlen;
if ((s->options & SSL_OP_TLSEXT_PADDING) == 0)
return EXT_RETURN_NOT_SENT;
/*
* Add padding to workaround bugs in F5 terminators. See RFC7685.
* This code calculates the length of all extensions added so far but
* excludes the PSK extension (because that MUST be written last). Therefore
* this extension MUST always appear second to last.
*/
if (!WPACKET_get_total_written(pkt, &hlen)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return EXT_RETURN_FAIL;
}
/*
* If we're going to send a PSK then that will be written out after this
* extension, so we need to calculate how long it is going to be.
*/
if (s->session->ssl_version == TLS1_3_VERSION
&& s->session->ext.ticklen != 0
&& s->session->cipher != NULL) {
const EVP_MD *md = ssl_md(s->ctx, s->session->cipher->algorithm2);
if (md != NULL) {
/*
* Add the fixed PSK overhead, the identity length and the binder
* length.
*/
hlen += PSK_PRE_BINDER_OVERHEAD + s->session->ext.ticklen
+ EVP_MD_get_size(md);
}
}
if (hlen > F5_WORKAROUND_MIN_MSG_LEN && hlen < F5_WORKAROUND_MAX_MSG_LEN) {
/* Calculate the amount of padding we need to add */
hlen = F5_WORKAROUND_MAX_MSG_LEN - hlen;
/*
* Take off the size of extension header itself (2 bytes for type and
* 2 bytes for length bytes), but ensure that the extension is at least
* 1 byte long so as not to have an empty extension last (WebSphere 7.x,
* 8.x are intolerant of that condition)
*/
if (hlen > 4)
hlen -= 4;
else
hlen = 1;
if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_padding)
|| !WPACKET_sub_allocate_bytes_u16(pkt, hlen, &padbytes)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return EXT_RETURN_FAIL;
}
memset(padbytes, 0, hlen);
}
return EXT_RETURN_SENT;
}
/*
* Construct the pre_shared_key extension
*/
EXT_RETURN tls_construct_ctos_psk(SSL *s, WPACKET *pkt, unsigned int context,
X509 *x, size_t chainidx)
{
#ifndef OPENSSL_NO_TLS1_3
uint32_t agesec, agems = 0;
size_t reshashsize = 0, pskhashsize = 0, binderoffset, msglen;
unsigned char *resbinder = NULL, *pskbinder = NULL, *msgstart = NULL;
const EVP_MD *handmd = NULL, *mdres = NULL, *mdpsk = NULL;
int dores = 0;
s->ext.tick_identity = 0;
/*
* Note: At this stage of the code we only support adding a single
* resumption PSK. If we add support for multiple PSKs then the length
* calculations in the padding extension will need to be adjusted.
*/
/*
* If this is an incompatible or new session then we have nothing to resume
* so don't add this extension.
*/
if (s->session->ssl_version != TLS1_3_VERSION
|| (s->session->ext.ticklen == 0 && s->psksession == NULL))
return EXT_RETURN_NOT_SENT;
if (s->hello_retry_request == SSL_HRR_PENDING)
handmd = ssl_handshake_md(s);
if (s->session->ext.ticklen != 0) {
/* Get the digest associated with the ciphersuite in the session */
if (s->session->cipher == NULL) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return EXT_RETURN_FAIL;
}
mdres = ssl_md(s->ctx, s->session->cipher->algorithm2);
if (mdres == NULL) {
/*
* Don't recognize this cipher so we can't use the session.
* Ignore it
*/
goto dopsksess;
}
if (s->hello_retry_request == SSL_HRR_PENDING && mdres != handmd) {
/*
* Selected ciphersuite hash does not match the hash for the session
* so we can't use it.
*/
goto dopsksess;
}
/*
* Technically the C standard just says time() returns a time_t and says
* nothing about the encoding of that type. In practice most
* implementations follow POSIX which holds it as an integral type in
* seconds since epoch. We've already made the assumption that we can do
* this in multiple places in the code, so portability shouldn't be an
* issue.
*/
agesec = (uint32_t)(time(NULL) - s->session->time);
/*
* We calculate the age in seconds but the server may work in ms. Due to
* rounding errors we could overestimate the age by up to 1s. It is
* better to underestimate it. Otherwise, if the RTT is very short, when
* the server calculates the age reported by the client it could be
* bigger than the age calculated on the server - which should never
* happen.
*/
if (agesec > 0)
agesec--;
if (s->session->ext.tick_lifetime_hint < agesec) {
/* Ticket is too old. Ignore it. */
goto dopsksess;
}
/*
* Calculate age in ms. We're just doing it to nearest second. Should be
* good enough.
*/
agems = agesec * (uint32_t)1000;
if (agesec != 0 && agems / (uint32_t)1000 != agesec) {
/*
* Overflow. Shouldn't happen unless this is a *really* old session.
* If so we just ignore it.
*/
goto dopsksess;
}
/*
* Obfuscate the age. Overflow here is fine, this addition is supposed
* to be mod 2^32.
*/
agems += s->session->ext.tick_age_add;
reshashsize = EVP_MD_get_size(mdres);
s->ext.tick_identity++;
dores = 1;
}
dopsksess:
if (!dores && s->psksession == NULL)
return EXT_RETURN_NOT_SENT;
if (s->psksession != NULL) {
mdpsk = ssl_md(s->ctx, s->psksession->cipher->algorithm2);
if (mdpsk == NULL) {
/*
* Don't recognize this cipher so we can't use the session.
* If this happens it's an application bug.
*/
SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_BAD_PSK);
return EXT_RETURN_FAIL;
}
if (s->hello_retry_request == SSL_HRR_PENDING && mdpsk != handmd) {
/*
* Selected ciphersuite hash does not match the hash for the PSK
* session. This is an application bug.
*/
SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_BAD_PSK);
return EXT_RETURN_FAIL;
}
pskhashsize = EVP_MD_get_size(mdpsk);
}
/* Create the extension, but skip over the binder for now */
if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_psk)
|| !WPACKET_start_sub_packet_u16(pkt)
|| !WPACKET_start_sub_packet_u16(pkt)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return EXT_RETURN_FAIL;
}
if (dores) {
if (!WPACKET_sub_memcpy_u16(pkt, s->session->ext.tick,
s->session->ext.ticklen)
|| !WPACKET_put_bytes_u32(pkt, agems)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return EXT_RETURN_FAIL;
}
}
if (s->psksession != NULL) {
if (!WPACKET_sub_memcpy_u16(pkt, s->psksession_id,
s->psksession_id_len)
|| !WPACKET_put_bytes_u32(pkt, 0)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return EXT_RETURN_FAIL;
}
s->ext.tick_identity++;
}
if (!WPACKET_close(pkt)
|| !WPACKET_get_total_written(pkt, &binderoffset)
|| !WPACKET_start_sub_packet_u16(pkt)
|| (dores
&& !WPACKET_sub_allocate_bytes_u8(pkt, reshashsize, &resbinder))
|| (s->psksession != NULL
&& !WPACKET_sub_allocate_bytes_u8(pkt, pskhashsize, &pskbinder))
|| !WPACKET_close(pkt)
|| !WPACKET_close(pkt)
|| !WPACKET_get_total_written(pkt, &msglen)
/*
* We need to fill in all the sub-packet lengths now so we can
* calculate the HMAC of the message up to the binders
*/
|| !WPACKET_fill_lengths(pkt)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return EXT_RETURN_FAIL;
}
msgstart = WPACKET_get_curr(pkt) - msglen;
if (dores
&& tls_psk_do_binder(s, mdres, msgstart, binderoffset, NULL,
resbinder, s->session, 1, 0) != 1) {
/* SSLfatal() already called */
return EXT_RETURN_FAIL;
}
if (s->psksession != NULL
&& tls_psk_do_binder(s, mdpsk, msgstart, binderoffset, NULL,
pskbinder, s->psksession, 1, 1) != 1) {
/* SSLfatal() already called */
return EXT_RETURN_FAIL;
}
return EXT_RETURN_SENT;
#else
return EXT_RETURN_NOT_SENT;
#endif
}
EXT_RETURN tls_construct_ctos_post_handshake_auth(SSL *s, WPACKET *pkt,
ossl_unused unsigned int context,
ossl_unused X509 *x,
ossl_unused size_t chainidx)
{
#ifndef OPENSSL_NO_TLS1_3
if (!s->pha_enabled)
return EXT_RETURN_NOT_SENT;
/* construct extension - 0 length, no contents */
if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_post_handshake_auth)
|| !WPACKET_start_sub_packet_u16(pkt)
|| !WPACKET_close(pkt)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return EXT_RETURN_FAIL;
}
s->post_handshake_auth = SSL_PHA_EXT_SENT;
return EXT_RETURN_SENT;
#else
return EXT_RETURN_NOT_SENT;
#endif
}
/*
* Parse the server's renegotiation binding and abort if it's not right
*/
int tls_parse_stoc_renegotiate(SSL *s, PACKET *pkt, unsigned int context,
X509 *x, size_t chainidx)
{
size_t expected_len = s->s3.previous_client_finished_len
+ s->s3.previous_server_finished_len;
size_t ilen;
const unsigned char *data;
/* Check for logic errors */
if (!ossl_assert(expected_len == 0
|| s->s3.previous_client_finished_len != 0)
|| !ossl_assert(expected_len == 0
|| s->s3.previous_server_finished_len != 0)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return 0;
}
/* Parse the length byte */
if (!PACKET_get_1_len(pkt, &ilen)) {
SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_RENEGOTIATION_ENCODING_ERR);
return 0;
}
/* Consistency check */
if (PACKET_remaining(pkt) != ilen) {
SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_RENEGOTIATION_ENCODING_ERR);
return 0;
}
/* Check that the extension matches */
if (ilen != expected_len) {
SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_RENEGOTIATION_MISMATCH);
return 0;
}
if (!PACKET_get_bytes(pkt, &data, s->s3.previous_client_finished_len)
|| memcmp(data, s->s3.previous_client_finished,
s->s3.previous_client_finished_len) != 0) {
SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_RENEGOTIATION_MISMATCH);
return 0;
}
if (!PACKET_get_bytes(pkt, &data, s->s3.previous_server_finished_len)
|| memcmp(data, s->s3.previous_server_finished,
s->s3.previous_server_finished_len) != 0) {
SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_RENEGOTIATION_MISMATCH);
return 0;
}
s->s3.send_connection_binding = 1;
return 1;
}
/* Parse the server's max fragment len extension packet */
int tls_parse_stoc_maxfragmentlen(SSL *s, PACKET *pkt, unsigned int context,
X509 *x, size_t chainidx)
{
unsigned int value;
if (PACKET_remaining(pkt) != 1 || !PACKET_get_1(pkt, &value)) {
SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_EXTENSION);
return 0;
}
/* |value| should contains a valid max-fragment-length code. */
if (!IS_MAX_FRAGMENT_LENGTH_EXT_VALID(value)) {
SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
SSL_R_SSL3_EXT_INVALID_MAX_FRAGMENT_LENGTH);
return 0;
}
/* Must be the same value as client-configured one who was sent to server */
/*-
* RFC 6066: if a client receives a maximum fragment length negotiation
* response that differs from the length it requested, ...
* It must abort with SSL_AD_ILLEGAL_PARAMETER alert
*/
if (value != s->ext.max_fragment_len_mode) {
SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
SSL_R_SSL3_EXT_INVALID_MAX_FRAGMENT_LENGTH);
return 0;
}
/*
* Maximum Fragment Length Negotiation succeeded.
* The negotiated Maximum Fragment Length is binding now.
*/
s->session->ext.max_fragment_len_mode = value;
return 1;
}
int tls_parse_stoc_server_name(SSL *s, PACKET *pkt, unsigned int context,
X509 *x, size_t chainidx)
{
if (s->ext.hostname == NULL) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return 0;
}
if (PACKET_remaining(pkt) > 0) {
SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_EXTENSION);
return 0;
}
if (!s->hit) {
if (s->session->ext.hostname != NULL) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return 0;
}
s->session->ext.hostname = OPENSSL_strdup(s->ext.hostname);
if (s->session->ext.hostname == NULL) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return 0;
}
}
return 1;
}
int tls_parse_stoc_ec_pt_formats(SSL *s, PACKET *pkt, unsigned int context,
X509 *x, size_t chainidx)
{
size_t ecpointformats_len;
PACKET ecptformatlist;
if (!PACKET_as_length_prefixed_1(pkt, &ecptformatlist)) {
SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_EXTENSION);
return 0;
}
if (!s->hit) {
ecpointformats_len = PACKET_remaining(&ecptformatlist);
if (ecpointformats_len == 0) {
SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_LENGTH);
return 0;
}
s->ext.peer_ecpointformats_len = 0;
OPENSSL_free(s->ext.peer_ecpointformats);
s->ext.peer_ecpointformats = OPENSSL_malloc(ecpointformats_len);
if (s->ext.peer_ecpointformats == NULL) {
s->ext.peer_ecpointformats_len = 0;
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return 0;
}
s->ext.peer_ecpointformats_len = ecpointformats_len;
if (!PACKET_copy_bytes(&ecptformatlist,
s->ext.peer_ecpointformats,
ecpointformats_len)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return 0;
}
}
return 1;
}
int tls_parse_stoc_session_ticket(SSL *s, PACKET *pkt, unsigned int context,
X509 *x, size_t chainidx)
{
if (s->ext.session_ticket_cb != NULL &&
!s->ext.session_ticket_cb(s, PACKET_data(pkt),
PACKET_remaining(pkt),
s->ext.session_ticket_cb_arg)) {
SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_BAD_EXTENSION);
return 0;
}
if (!tls_use_ticket(s)) {
SSLfatal(s, SSL_AD_UNSUPPORTED_EXTENSION, SSL_R_BAD_EXTENSION);
return 0;
}
if (PACKET_remaining(pkt) > 0) {
SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_EXTENSION);
return 0;
}
s->ext.ticket_expected = 1;
return 1;
}
#ifndef OPENSSL_NO_OCSP
int tls_parse_stoc_status_request(SSL *s, PACKET *pkt, unsigned int context,
X509 *x, size_t chainidx)
{
if (context == SSL_EXT_TLS1_3_CERTIFICATE_REQUEST) {
/* We ignore this if the server sends a CertificateRequest */
return 1;
}
/*
* MUST only be sent if we've requested a status
* request message. In TLS <= 1.2 it must also be empty.
*/
if (s->ext.status_type != TLSEXT_STATUSTYPE_ocsp) {
SSLfatal(s, SSL_AD_UNSUPPORTED_EXTENSION, SSL_R_BAD_EXTENSION);
return 0;
}
if (!SSL_IS_TLS13(s) && PACKET_remaining(pkt) > 0) {
SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_EXTENSION);
return 0;
}
if (SSL_IS_TLS13(s)) {
/* We only know how to handle this if it's for the first Certificate in
* the chain. We ignore any other responses.
*/
if (chainidx != 0)
return 1;
/* SSLfatal() already called */
return tls_process_cert_status_body(s, pkt);
}
/* Set flag to expect CertificateStatus message */
s->ext.status_expected = 1;
return 1;
}
#endif
#ifndef OPENSSL_NO_CT
int tls_parse_stoc_sct(SSL *s, PACKET *pkt, unsigned int context, X509 *x,
size_t chainidx)
{
if (context == SSL_EXT_TLS1_3_CERTIFICATE_REQUEST) {
/* We ignore this if the server sends it in a CertificateRequest */
return 1;
}
/*
* Only take it if we asked for it - i.e if there is no CT validation
* callback set, then a custom extension MAY be processing it, so we
* need to let control continue to flow to that.
*/
if (s->ct_validation_callback != NULL) {
size_t size = PACKET_remaining(pkt);
/* Simply copy it off for later processing */
OPENSSL_free(s->ext.scts);
s->ext.scts = NULL;
s->ext.scts_len = (uint16_t)size;
if (size > 0) {
s->ext.scts = OPENSSL_malloc(size);
if (s->ext.scts == NULL) {
s->ext.scts_len = 0;
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_MALLOC_FAILURE);
return 0;
}
if (!PACKET_copy_bytes(pkt, s->ext.scts, size)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return 0;
}
}
} else {
ENDPOINT role = (context & SSL_EXT_TLS1_2_SERVER_HELLO) != 0
? ENDPOINT_CLIENT : ENDPOINT_BOTH;
/*
* If we didn't ask for it then there must be a custom extension,
* otherwise this is unsolicited.
*/
if (custom_ext_find(&s->cert->custext, role,
TLSEXT_TYPE_signed_certificate_timestamp,
NULL) == NULL) {
SSLfatal(s, TLS1_AD_UNSUPPORTED_EXTENSION, SSL_R_BAD_EXTENSION);
return 0;
}
if (!custom_ext_parse(s, context,
TLSEXT_TYPE_signed_certificate_timestamp,
PACKET_data(pkt), PACKET_remaining(pkt),
x, chainidx)) {
/* SSLfatal already called */
return 0;
}
}
return 1;
}
#endif
#ifndef OPENSSL_NO_NEXTPROTONEG
/*
* ssl_next_proto_validate validates a Next Protocol Negotiation block. No
* elements of zero length are allowed and the set of elements must exactly
* fill the length of the block. Returns 1 on success or 0 on failure.
*/
static int ssl_next_proto_validate(SSL *s, PACKET *pkt)
{
PACKET tmp_protocol;
while (PACKET_remaining(pkt)) {
if (!PACKET_get_length_prefixed_1(pkt, &tmp_protocol)
|| PACKET_remaining(&tmp_protocol) == 0) {
SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_EXTENSION);
return 0;
}
}
return 1;
}
int tls_parse_stoc_npn(SSL *s, PACKET *pkt, unsigned int context, X509 *x,
size_t chainidx)
{
unsigned char *selected;
unsigned char selected_len;
PACKET tmppkt;
/* Check if we are in a renegotiation. If so ignore this extension */
if (!SSL_IS_FIRST_HANDSHAKE(s))
return 1;
/* We must have requested it. */
if (s->ctx->ext.npn_select_cb == NULL) {
SSLfatal(s, SSL_AD_UNSUPPORTED_EXTENSION, SSL_R_BAD_EXTENSION);
return 0;
}
/* The data must be valid */
tmppkt = *pkt;
if (!ssl_next_proto_validate(s, &tmppkt)) {
/* SSLfatal() already called */
return 0;
}
if (s->ctx->ext.npn_select_cb(s, &selected, &selected_len,
PACKET_data(pkt),
PACKET_remaining(pkt),
s->ctx->ext.npn_select_cb_arg) !=
- SSL_TLSEXT_ERR_OK) {
+ SSL_TLSEXT_ERR_OK
+ || selected_len == 0) {
SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_BAD_EXTENSION);
return 0;
}
/*
* Could be non-NULL if server has sent multiple NPN extensions in
* a single Serverhello
*/
OPENSSL_free(s->ext.npn);
s->ext.npn = OPENSSL_malloc(selected_len);
if (s->ext.npn == NULL) {
s->ext.npn_len = 0;
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return 0;
}
memcpy(s->ext.npn, selected, selected_len);
s->ext.npn_len = selected_len;
s->s3.npn_seen = 1;
return 1;
}
#endif
int tls_parse_stoc_alpn(SSL *s, PACKET *pkt, unsigned int context, X509 *x,
size_t chainidx)
{
size_t len;
+ PACKET confpkt, protpkt;
+ int valid = 0;
/* We must have requested it. */
if (!s->s3.alpn_sent) {
SSLfatal(s, SSL_AD_UNSUPPORTED_EXTENSION, SSL_R_BAD_EXTENSION);
return 0;
}
/*-
* The extension data consists of:
* uint16 list_length
* uint8 proto_length;
* uint8 proto[proto_length];
*/
if (!PACKET_get_net_2_len(pkt, &len)
|| PACKET_remaining(pkt) != len || !PACKET_get_1_len(pkt, &len)
|| PACKET_remaining(pkt) != len) {
SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_EXTENSION);
return 0;
}
+
+ /* It must be a protocol that we sent */
+ if (!PACKET_buf_init(&confpkt, s->ext.alpn, s->ext.alpn_len)) {
+ SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
+ return 0;
+ }
+ while (PACKET_get_length_prefixed_1(&confpkt, &protpkt)) {
+ if (PACKET_remaining(&protpkt) != len)
+ continue;
+ if (memcmp(PACKET_data(pkt), PACKET_data(&protpkt), len) == 0) {
+ /* Valid protocol found */
+ valid = 1;
+ break;
+ }
+ }
+
+ if (!valid) {
+ /* The protocol sent from the server does not match one we advertised */
+ SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_EXTENSION);
+ return 0;
+ }
+
OPENSSL_free(s->s3.alpn_selected);
s->s3.alpn_selected = OPENSSL_malloc(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;
}
if (!PACKET_copy_bytes(pkt, s->s3.alpn_selected, len)) {
SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_EXTENSION);
return 0;
}
s->s3.alpn_selected_len = len;
if (s->session->ext.alpn_selected == NULL
|| s->session->ext.alpn_selected_len != len
|| memcmp(s->session->ext.alpn_selected, s->s3.alpn_selected, len)
!= 0) {
/* ALPN not consistent with the old session so cannot use 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(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_INTERNAL_ERROR);
return 0;
}
s->session->ext.alpn_selected_len = s->s3.alpn_selected_len;
}
return 1;
}
#ifndef OPENSSL_NO_SRTP
int tls_parse_stoc_use_srtp(SSL *s, PACKET *pkt, unsigned int context, X509 *x,
size_t chainidx)
{
unsigned int id, ct, mki;
int i;
STACK_OF(SRTP_PROTECTION_PROFILE) *clnt;
SRTP_PROTECTION_PROFILE *prof;
if (!PACKET_get_net_2(pkt, &ct) || ct != 2
|| !PACKET_get_net_2(pkt, &id)
|| !PACKET_get_1(pkt, &mki)
|| PACKET_remaining(pkt) != 0) {
SSLfatal(s, SSL_AD_DECODE_ERROR,
SSL_R_BAD_SRTP_PROTECTION_PROFILE_LIST);
return 0;
}
if (mki != 0) {
/* Must be no MKI, since we never offer one */
SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_BAD_SRTP_MKI_VALUE);
return 0;
}
/* Throw an error if the server gave us an unsolicited extension */
clnt = SSL_get_srtp_profiles(s);
if (clnt == NULL) {
SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_NO_SRTP_PROFILES);
return 0;
}
/*
* Check to see if the server gave us something we support (and
* presumably offered)
*/
for (i = 0; i < sk_SRTP_PROTECTION_PROFILE_num(clnt); i++) {
prof = sk_SRTP_PROTECTION_PROFILE_value(clnt, i);
if (prof->id == id) {
s->srtp_profile = prof;
return 1;
}
}
SSLfatal(s, SSL_AD_DECODE_ERROR,
SSL_R_BAD_SRTP_PROTECTION_PROFILE_LIST);
return 0;
}
#endif
int tls_parse_stoc_etm(SSL *s, PACKET *pkt, unsigned int context, X509 *x,
size_t chainidx)
{
/* Ignore if inappropriate ciphersuite */
if (!(s->options & SSL_OP_NO_ENCRYPT_THEN_MAC)
&& s->s3.tmp.new_cipher->algorithm_mac != SSL_AEAD
&& s->s3.tmp.new_cipher->algorithm_enc != SSL_RC4
&& s->s3.tmp.new_cipher->algorithm_enc != SSL_eGOST2814789CNT
&& s->s3.tmp.new_cipher->algorithm_enc != SSL_eGOST2814789CNT12
&& s->s3.tmp.new_cipher->algorithm_enc != SSL_MAGMA
&& s->s3.tmp.new_cipher->algorithm_enc != SSL_KUZNYECHIK)
s->ext.use_etm = 1;
return 1;
}
int tls_parse_stoc_ems(SSL *s, PACKET *pkt, unsigned int context, X509 *x,
size_t chainidx)
{
if (s->options & SSL_OP_NO_EXTENDED_MASTER_SECRET)
return 1;
s->s3.flags |= TLS1_FLAGS_RECEIVED_EXTMS;
if (!s->hit)
s->session->flags |= SSL_SESS_FLAG_EXTMS;
return 1;
}
int tls_parse_stoc_supported_versions(SSL *s, PACKET *pkt, unsigned int context,
X509 *x, size_t chainidx)
{
unsigned int version;
if (!PACKET_get_net_2(pkt, &version)
|| PACKET_remaining(pkt) != 0) {
SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
return 0;
}
/*
* The only protocol version we support which is valid in this extension in
* a ServerHello is TLSv1.3 therefore we shouldn't be getting anything else.
*/
if (version != TLS1_3_VERSION) {
SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
SSL_R_BAD_PROTOCOL_VERSION_NUMBER);
return 0;
}
/* We ignore this extension for HRRs except to sanity check it */
if (context == SSL_EXT_TLS1_3_HELLO_RETRY_REQUEST)
return 1;
/* We just set it here. We validate it in ssl_choose_client_version */
s->version = version;
return 1;
}
int tls_parse_stoc_key_share(SSL *s, PACKET *pkt, unsigned int context, X509 *x,
size_t chainidx)
{
#ifndef OPENSSL_NO_TLS1_3
unsigned int group_id;
PACKET encoded_pt;
EVP_PKEY *ckey = s->s3.tmp.pkey, *skey = NULL;
const TLS_GROUP_INFO *ginf = NULL;
/* Sanity check */
if (ckey == NULL || s->s3.peer_tmp != NULL) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return 0;
}
if (!PACKET_get_net_2(pkt, &group_id)) {
SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
return 0;
}
if ((context & SSL_EXT_TLS1_3_HELLO_RETRY_REQUEST) != 0) {
const uint16_t *pgroups = NULL;
size_t i, num_groups;
if (PACKET_remaining(pkt) != 0) {
SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
return 0;
}
/*
* It is an error if the HelloRetryRequest wants a key_share that we
* already sent in the first ClientHello
*/
if (group_id == s->s3.group_id) {
SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_BAD_KEY_SHARE);
return 0;
}
/* Validate the selected group is one we support */
tls1_get_supported_groups(s, &pgroups, &num_groups);
for (i = 0; i < num_groups; i++) {
if (group_id == pgroups[i])
break;
}
if (i >= num_groups
|| !tls_group_allowed(s, group_id, SSL_SECOP_CURVE_SUPPORTED)
|| !tls_valid_group(s, group_id, TLS1_3_VERSION, TLS1_3_VERSION,
0, NULL)) {
SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_BAD_KEY_SHARE);
return 0;
}
s->s3.group_id = group_id;
EVP_PKEY_free(s->s3.tmp.pkey);
s->s3.tmp.pkey = NULL;
return 1;
}
if (group_id != s->s3.group_id) {
/*
* This isn't for the group that we sent in the original
* key_share!
*/
SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_BAD_KEY_SHARE);
return 0;
}
/* Retain this group in the SSL_SESSION */
if (!s->hit) {
s->session->kex_group = group_id;
} else if (group_id != s->session->kex_group) {
/*
* If this is a resumption but changed what group was used, we need
* to record the new group in the session, but the session is not
* a new session and could be in use by other threads. So, make
* a copy of the session to record the new information so that it's
* useful for any sessions resumed from tickets issued on this
* connection.
*/
SSL_SESSION *new_sess;
if ((new_sess = ssl_session_dup(s->session, 0)) == NULL) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_MALLOC_FAILURE);
return 0;
}
SSL_SESSION_free(s->session);
s->session = new_sess;
s->session->kex_group = group_id;
}
if ((ginf = tls1_group_id_lookup(s->ctx, group_id)) == NULL) {
SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_BAD_KEY_SHARE);
return 0;
}
if (!PACKET_as_length_prefixed_2(pkt, &encoded_pt)
|| PACKET_remaining(&encoded_pt) == 0) {
SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
return 0;
}
if (!ginf->is_kem) {
/* Regular KEX */
skey = EVP_PKEY_new();
if (skey == NULL || EVP_PKEY_copy_parameters(skey, ckey) <= 0) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_COPY_PARAMETERS_FAILED);
EVP_PKEY_free(skey);
return 0;
}
if (tls13_set_encoded_pub_key(skey, PACKET_data(&encoded_pt),
PACKET_remaining(&encoded_pt)) <= 0) {
SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_BAD_ECPOINT);
EVP_PKEY_free(skey);
return 0;
}
if (ssl_derive(s, ckey, skey, 1) == 0) {
/* SSLfatal() already called */
EVP_PKEY_free(skey);
return 0;
}
s->s3.peer_tmp = skey;
} else {
/* KEM Mode */
const unsigned char *ct = PACKET_data(&encoded_pt);
size_t ctlen = PACKET_remaining(&encoded_pt);
if (ssl_decapsulate(s, ckey, ct, ctlen, 1) == 0) {
/* SSLfatal() already called */
return 0;
}
}
s->s3.did_kex = 1;
#endif
return 1;
}
int tls_parse_stoc_cookie(SSL *s, PACKET *pkt, unsigned int context, X509 *x,
size_t chainidx)
{
PACKET cookie;
if (!PACKET_as_length_prefixed_2(pkt, &cookie)
|| !PACKET_memdup(&cookie, &s->ext.tls13_cookie,
&s->ext.tls13_cookie_len)) {
SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
return 0;
}
return 1;
}
int tls_parse_stoc_early_data(SSL *s, PACKET *pkt, unsigned int context,
X509 *x, size_t chainidx)
{
if (context == SSL_EXT_TLS1_3_NEW_SESSION_TICKET) {
unsigned long max_early_data;
if (!PACKET_get_net_4(pkt, &max_early_data)
|| PACKET_remaining(pkt) != 0) {
SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_INVALID_MAX_EARLY_DATA);
return 0;
}
s->session->ext.max_early_data = max_early_data;
return 1;
}
if (PACKET_remaining(pkt) != 0) {
SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_EXTENSION);
return 0;
}
if (!s->ext.early_data_ok
|| !s->hit) {
/*
* If we get here then we didn't send early data, or we didn't resume
* using the first identity, or the SNI/ALPN is not consistent so the
* server should not be accepting it.
*/
SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_BAD_EXTENSION);
return 0;
}
s->ext.early_data = SSL_EARLY_DATA_ACCEPTED;
return 1;
}
int tls_parse_stoc_psk(SSL *s, PACKET *pkt, unsigned int context, X509 *x,
size_t chainidx)
{
#ifndef OPENSSL_NO_TLS1_3
unsigned int identity;
if (!PACKET_get_net_2(pkt, &identity) || PACKET_remaining(pkt) != 0) {
SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
return 0;
}
if (identity >= (unsigned int)s->ext.tick_identity) {
SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_BAD_PSK_IDENTITY);
return 0;
}
/*
* Session resumption tickets are always sent before PSK tickets. If the
* ticket index is 0 then it must be for a session resumption ticket if we
* sent two tickets, or if we didn't send a PSK ticket.
*/
if (identity == 0 && (s->psksession == NULL || s->ext.tick_identity == 2)) {
s->hit = 1;
SSL_SESSION_free(s->psksession);
s->psksession = NULL;
return 1;
}
if (s->psksession == NULL) {
/* Should never happen */
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return 0;
}
/*
* If we used the external PSK for sending early_data then s->early_secret
* is already set up, so don't overwrite it. Otherwise we copy the
* early_secret across that we generated earlier.
*/
if ((s->early_data_state != SSL_EARLY_DATA_WRITE_RETRY
&& s->early_data_state != SSL_EARLY_DATA_FINISHED_WRITING)
|| s->session->ext.max_early_data > 0
|| s->psksession->ext.max_early_data == 0)
memcpy(s->early_secret, s->psksession->early_secret, EVP_MAX_MD_SIZE);
SSL_SESSION_free(s->session);
s->session = s->psksession;
s->psksession = NULL;
s->hit = 1;
/* Early data is only allowed if we used the first ticket */
if (identity != 0)
s->ext.early_data_ok = 0;
#endif
return 1;
}
diff --git a/crypto/openssl/ssl/statem/extensions_srvr.c b/crypto/openssl/ssl/statem/extensions_srvr.c
index 1fab5a3d1295..91ff14ce98f2 100644
--- a/crypto/openssl/ssl/statem/extensions_srvr.c
+++ b/crypto/openssl/ssl/statem/extensions_srvr.c
@@ -1,1916 +1,1922 @@
/*
- * 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
*/
#include <openssl/ocsp.h>
#include "../ssl_local.h"
#include "statem_local.h"
#include "internal/cryptlib.h"
#define COOKIE_STATE_FORMAT_VERSION 1
/*
* 2 bytes for packet length, 2 bytes for format version, 2 bytes for
* protocol version, 2 bytes for group id, 2 bytes for cipher id, 1 byte for
* key_share present flag, 8 bytes for timestamp, 2 bytes for the hashlen,
* EVP_MAX_MD_SIZE for transcript hash, 1 byte for app cookie length, app cookie
* length bytes, SHA256_DIGEST_LENGTH bytes for the HMAC of the whole thing.
*/
#define MAX_COOKIE_SIZE (2 + 2 + 2 + 2 + 2 + 1 + 8 + 2 + EVP_MAX_MD_SIZE + 1 \
+ SSL_COOKIE_LENGTH + SHA256_DIGEST_LENGTH)
/*
* Message header + 2 bytes for protocol version + number of random bytes +
* + 1 byte for legacy session id length + number of bytes in legacy session id
* + 2 bytes for ciphersuite + 1 byte for legacy compression
* + 2 bytes for extension block length + 6 bytes for key_share extension
* + 4 bytes for cookie extension header + the number of bytes in the cookie
*/
#define MAX_HRR_SIZE (SSL3_HM_HEADER_LENGTH + 2 + SSL3_RANDOM_SIZE + 1 \
+ SSL_MAX_SSL_SESSION_ID_LENGTH + 2 + 1 + 2 + 6 + 4 \
+ MAX_COOKIE_SIZE)
/*
* Parse the client's renegotiation binding and abort if it's not right
*/
int tls_parse_ctos_renegotiate(SSL *s, PACKET *pkt, unsigned int context,
X509 *x, size_t chainidx)
{
unsigned int ilen;
const unsigned char *data;
/* Parse the length byte */
if (!PACKET_get_1(pkt, &ilen)
|| !PACKET_get_bytes(pkt, &data, ilen)) {
SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_RENEGOTIATION_ENCODING_ERR);
return 0;
}
/* Check that the extension matches */
if (ilen != s->s3.previous_client_finished_len) {
SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_RENEGOTIATION_MISMATCH);
return 0;
}
if (memcmp(data, s->s3.previous_client_finished,
s->s3.previous_client_finished_len)) {
SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_RENEGOTIATION_MISMATCH);
return 0;
}
s->s3.send_connection_binding = 1;
return 1;
}
/*-
* The servername extension is treated as follows:
*
* - Only the hostname type is supported with a maximum length of 255.
* - The servername is rejected if too long or if it contains zeros,
* in which case an fatal alert is generated.
* - The servername field is maintained together with the session cache.
* - When a session is resumed, the servername call back invoked in order
* to allow the application to position itself to the right context.
* - The servername is acknowledged if it is new for a session or when
* it is identical to a previously used for the same session.
* Applications can control the behaviour. They can at any time
* set a 'desirable' servername for a new SSL object. This can be the
* case for example with HTTPS when a Host: header field is received and
* a renegotiation is requested. In this case, a possible servername
* presented in the new client hello is only acknowledged if it matches
* the value of the Host: field.
* - Applications must use SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION
* if they provide for changing an explicit servername context for the
* session, i.e. when the session has been established with a servername
* extension.
* - On session reconnect, the servername extension may be absent.
*/
int tls_parse_ctos_server_name(SSL *s, PACKET *pkt, unsigned int context,
X509 *x, size_t chainidx)
{
unsigned int servname_type;
PACKET sni, hostname;
if (!PACKET_as_length_prefixed_2(pkt, &sni)
/* ServerNameList must be at least 1 byte long. */
|| PACKET_remaining(&sni) == 0) {
SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_EXTENSION);
return 0;
}
/*
* Although the intent was for server_name to be extensible, RFC 4366
* was not clear about it; and so OpenSSL among other implementations,
* always and only allows a 'host_name' name types.
* RFC 6066 corrected the mistake but adding new name types
* is nevertheless no longer feasible, so act as if no other
* SNI types can exist, to simplify parsing.
*
* Also note that the RFC permits only one SNI value per type,
* i.e., we can only have a single hostname.
*/
if (!PACKET_get_1(&sni, &servname_type)
|| servname_type != TLSEXT_NAMETYPE_host_name
|| !PACKET_as_length_prefixed_2(&sni, &hostname)) {
SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_EXTENSION);
return 0;
}
/*
* In TLSv1.2 and below the SNI is associated with the session. In TLSv1.3
* we always use the SNI value from the handshake.
*/
if (!s->hit || SSL_IS_TLS13(s)) {
if (PACKET_remaining(&hostname) > TLSEXT_MAXLEN_host_name) {
SSLfatal(s, SSL_AD_UNRECOGNIZED_NAME, SSL_R_BAD_EXTENSION);
return 0;
}
if (PACKET_contains_zero_byte(&hostname)) {
SSLfatal(s, SSL_AD_UNRECOGNIZED_NAME, SSL_R_BAD_EXTENSION);
return 0;
}
/*
* Store the requested SNI in the SSL as temporary storage.
* If we accept it, it will get stored in the SSL_SESSION as well.
*/
OPENSSL_free(s->ext.hostname);
s->ext.hostname = NULL;
if (!PACKET_strndup(&hostname, &s->ext.hostname)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return 0;
}
s->servername_done = 1;
} else {
/*
* In TLSv1.2 and below we should check if the SNI is consistent between
* the initial handshake and the resumption. In TLSv1.3 SNI is not
* associated with the session.
*/
s->servername_done = (s->session->ext.hostname != NULL)
&& PACKET_equal(&hostname, s->session->ext.hostname,
strlen(s->session->ext.hostname));
}
return 1;
}
int tls_parse_ctos_maxfragmentlen(SSL *s, PACKET *pkt, unsigned int context,
X509 *x, size_t chainidx)
{
unsigned int value;
if (PACKET_remaining(pkt) != 1 || !PACKET_get_1(pkt, &value)) {
SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_EXTENSION);
return 0;
}
/* Received |value| should be a valid max-fragment-length code. */
if (!IS_MAX_FRAGMENT_LENGTH_EXT_VALID(value)) {
SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
SSL_R_SSL3_EXT_INVALID_MAX_FRAGMENT_LENGTH);
return 0;
}
/*
- * RFC 6066: The negotiated length applies for the duration of the session
+ * When doing a full handshake or a renegotiation max_fragment_len_mode will
+ * be TLSEXT_max_fragment_length_UNSPECIFIED
+ *
+ * In case of a resumption max_fragment_len_mode will be one of
+ * TLSEXT_max_fragment_length_DISABLED, TLSEXT_max_fragment_length_512,
+ * TLSEXT_max_fragment_length_1024, TLSEXT_max_fragment_length_2048.
+ * TLSEXT_max_fragment_length_4096
+ *
+ * RFC 6066: The negotiated length applies for the duration of the session
* including session resumptions.
- * We should receive the same code as in resumed session !
+ *
+ * So we only set the value in case it is unspecified.
*/
- if (s->hit && s->session->ext.max_fragment_len_mode != value) {
- SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
- SSL_R_SSL3_EXT_INVALID_MAX_FRAGMENT_LENGTH);
- return 0;
- }
+ if (s->session->ext.max_fragment_len_mode == TLSEXT_max_fragment_length_UNSPECIFIED)
+ /*
+ * Store it in session, so it'll become binding for us
+ * and we'll include it in a next Server Hello.
+ */
+ s->session->ext.max_fragment_len_mode = value;
- /*
- * Store it in session, so it'll become binding for us
- * and we'll include it in a next Server Hello.
- */
- s->session->ext.max_fragment_len_mode = value;
return 1;
}
#ifndef OPENSSL_NO_SRP
int tls_parse_ctos_srp(SSL *s, PACKET *pkt, unsigned int context, X509 *x,
size_t chainidx)
{
PACKET srp_I;
if (!PACKET_as_length_prefixed_1(pkt, &srp_I)
|| PACKET_contains_zero_byte(&srp_I)) {
SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_EXTENSION);
return 0;
}
if (!PACKET_strndup(&srp_I, &s->srp_ctx.login)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return 0;
}
return 1;
}
#endif
int tls_parse_ctos_ec_pt_formats(SSL *s, PACKET *pkt, unsigned int context,
X509 *x, size_t chainidx)
{
PACKET ec_point_format_list;
if (!PACKET_as_length_prefixed_1(pkt, &ec_point_format_list)
|| PACKET_remaining(&ec_point_format_list) == 0) {
SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_EXTENSION);
return 0;
}
if (!s->hit) {
if (!PACKET_memdup(&ec_point_format_list,
&s->ext.peer_ecpointformats,
&s->ext.peer_ecpointformats_len)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return 0;
}
}
return 1;
}
int tls_parse_ctos_session_ticket(SSL *s, PACKET *pkt, unsigned int context,
X509 *x, size_t chainidx)
{
if (s->ext.session_ticket_cb &&
!s->ext.session_ticket_cb(s, PACKET_data(pkt),
PACKET_remaining(pkt),
s->ext.session_ticket_cb_arg)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return 0;
}
return 1;
}
int tls_parse_ctos_sig_algs_cert(SSL *s, PACKET *pkt,
ossl_unused unsigned int context,
ossl_unused X509 *x,
ossl_unused size_t chainidx)
{
PACKET supported_sig_algs;
if (!PACKET_as_length_prefixed_2(pkt, &supported_sig_algs)
|| PACKET_remaining(&supported_sig_algs) == 0) {
SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_EXTENSION);
return 0;
}
if (!s->hit && !tls1_save_sigalgs(s, &supported_sig_algs, 1)) {
SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_EXTENSION);
return 0;
}
return 1;
}
int tls_parse_ctos_sig_algs(SSL *s, PACKET *pkt, unsigned int context, X509 *x,
size_t chainidx)
{
PACKET supported_sig_algs;
if (!PACKET_as_length_prefixed_2(pkt, &supported_sig_algs)
|| PACKET_remaining(&supported_sig_algs) == 0) {
SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_EXTENSION);
return 0;
}
if (!s->hit && !tls1_save_sigalgs(s, &supported_sig_algs, 0)) {
SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_EXTENSION);
return 0;
}
return 1;
}
#ifndef OPENSSL_NO_OCSP
int tls_parse_ctos_status_request(SSL *s, PACKET *pkt, unsigned int context,
X509 *x, size_t chainidx)
{
PACKET responder_id_list, exts;
/* We ignore this in a resumption handshake */
if (s->hit)
return 1;
/* Not defined if we get one of these in a client Certificate */
if (x != NULL)
return 1;
if (!PACKET_get_1(pkt, (unsigned int *)&s->ext.status_type)) {
SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_EXTENSION);
return 0;
}
if (s->ext.status_type != TLSEXT_STATUSTYPE_ocsp) {
/*
* We don't know what to do with any other type so ignore it.
*/
s->ext.status_type = TLSEXT_STATUSTYPE_nothing;
return 1;
}
if (!PACKET_get_length_prefixed_2 (pkt, &responder_id_list)) {
SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_EXTENSION);
return 0;
}
/*
* We remove any OCSP_RESPIDs from a previous handshake
* to prevent unbounded memory growth - CVE-2016-6304
*/
sk_OCSP_RESPID_pop_free(s->ext.ocsp.ids, OCSP_RESPID_free);
if (PACKET_remaining(&responder_id_list) > 0) {
s->ext.ocsp.ids = sk_OCSP_RESPID_new_null();
if (s->ext.ocsp.ids == NULL) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_MALLOC_FAILURE);
return 0;
}
} else {
s->ext.ocsp.ids = NULL;
}
while (PACKET_remaining(&responder_id_list) > 0) {
OCSP_RESPID *id;
PACKET responder_id;
const unsigned char *id_data;
if (!PACKET_get_length_prefixed_2(&responder_id_list, &responder_id)
|| PACKET_remaining(&responder_id) == 0) {
SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_EXTENSION);
return 0;
}
id_data = PACKET_data(&responder_id);
id = d2i_OCSP_RESPID(NULL, &id_data,
(int)PACKET_remaining(&responder_id));
if (id == NULL) {
SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_EXTENSION);
return 0;
}
if (id_data != PACKET_end(&responder_id)) {
OCSP_RESPID_free(id);
SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_EXTENSION);
return 0;
}
if (!sk_OCSP_RESPID_push(s->ext.ocsp.ids, id)) {
OCSP_RESPID_free(id);
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return 0;
}
}
/* Read in request_extensions */
if (!PACKET_as_length_prefixed_2(pkt, &exts)) {
SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_EXTENSION);
return 0;
}
if (PACKET_remaining(&exts) > 0) {
const unsigned char *ext_data = PACKET_data(&exts);
sk_X509_EXTENSION_pop_free(s->ext.ocsp.exts,
X509_EXTENSION_free);
s->ext.ocsp.exts =
d2i_X509_EXTENSIONS(NULL, &ext_data, (int)PACKET_remaining(&exts));
if (s->ext.ocsp.exts == NULL || ext_data != PACKET_end(&exts)) {
SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_EXTENSION);
return 0;
}
}
return 1;
}
#endif
#ifndef OPENSSL_NO_NEXTPROTONEG
int tls_parse_ctos_npn(SSL *s, PACKET *pkt, unsigned int context, X509 *x,
size_t chainidx)
{
/*
* We shouldn't accept this extension on a
* renegotiation.
*/
if (SSL_IS_FIRST_HANDSHAKE(s))
s->s3.npn_seen = 1;
return 1;
}
#endif
/*
* Save the ALPN extension in a ClientHello.|pkt| holds the contents of the ALPN
* extension, not including type and length. Returns: 1 on success, 0 on error.
*/
int tls_parse_ctos_alpn(SSL *s, PACKET *pkt, unsigned int context, X509 *x,
size_t chainidx)
{
PACKET protocol_list, save_protocol_list, protocol;
if (!SSL_IS_FIRST_HANDSHAKE(s))
return 1;
if (!PACKET_as_length_prefixed_2(pkt, &protocol_list)
|| PACKET_remaining(&protocol_list) < 2) {
SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_EXTENSION);
return 0;
}
save_protocol_list = protocol_list;
do {
/* Protocol names can't be empty. */
if (!PACKET_get_length_prefixed_1(&protocol_list, &protocol)
|| PACKET_remaining(&protocol) == 0) {
SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_EXTENSION);
return 0;
}
} while (PACKET_remaining(&protocol_list) != 0);
OPENSSL_free(s->s3.alpn_proposed);
s->s3.alpn_proposed = NULL;
s->s3.alpn_proposed_len = 0;
if (!PACKET_memdup(&save_protocol_list,
&s->s3.alpn_proposed, &s->s3.alpn_proposed_len)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return 0;
}
return 1;
}
#ifndef OPENSSL_NO_SRTP
int tls_parse_ctos_use_srtp(SSL *s, PACKET *pkt, unsigned int context, X509 *x,
size_t chainidx)
{
STACK_OF(SRTP_PROTECTION_PROFILE) *srvr;
unsigned int ct, mki_len, id;
int i, srtp_pref;
PACKET subpkt;
/* Ignore this if we have no SRTP profiles */
if (SSL_get_srtp_profiles(s) == NULL)
return 1;
/* Pull off the length of the cipher suite list and check it is even */
if (!PACKET_get_net_2(pkt, &ct) || (ct & 1) != 0
|| !PACKET_get_sub_packet(pkt, &subpkt, ct)) {
SSLfatal(s, SSL_AD_DECODE_ERROR,
SSL_R_BAD_SRTP_PROTECTION_PROFILE_LIST);
return 0;
}
srvr = SSL_get_srtp_profiles(s);
s->srtp_profile = NULL;
/* Search all profiles for a match initially */
srtp_pref = sk_SRTP_PROTECTION_PROFILE_num(srvr);
while (PACKET_remaining(&subpkt)) {
if (!PACKET_get_net_2(&subpkt, &id)) {
SSLfatal(s, SSL_AD_DECODE_ERROR,
SSL_R_BAD_SRTP_PROTECTION_PROFILE_LIST);
return 0;
}
/*
* Only look for match in profiles of higher preference than
* current match.
* If no profiles have been have been configured then this
* does nothing.
*/
for (i = 0; i < srtp_pref; i++) {
SRTP_PROTECTION_PROFILE *sprof =
sk_SRTP_PROTECTION_PROFILE_value(srvr, i);
if (sprof->id == id) {
s->srtp_profile = sprof;
srtp_pref = i;
break;
}
}
}
/* Now extract the MKI value as a sanity check, but discard it for now */
if (!PACKET_get_1(pkt, &mki_len)) {
SSLfatal(s, SSL_AD_DECODE_ERROR,
SSL_R_BAD_SRTP_PROTECTION_PROFILE_LIST);
return 0;
}
if (!PACKET_forward(pkt, mki_len)
|| PACKET_remaining(pkt)) {
SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_SRTP_MKI_VALUE);
return 0;
}
return 1;
}
#endif
int tls_parse_ctos_etm(SSL *s, PACKET *pkt, unsigned int context, X509 *x,
size_t chainidx)
{
if (!(s->options & SSL_OP_NO_ENCRYPT_THEN_MAC))
s->ext.use_etm = 1;
return 1;
}
/*
* Process a psk_kex_modes extension received in the ClientHello. |pkt| contains
* the raw PACKET data for the extension. Returns 1 on success or 0 on failure.
*/
int tls_parse_ctos_psk_kex_modes(SSL *s, PACKET *pkt, unsigned int context,
X509 *x, size_t chainidx)
{
#ifndef OPENSSL_NO_TLS1_3
PACKET psk_kex_modes;
unsigned int mode;
if (!PACKET_as_length_prefixed_1(pkt, &psk_kex_modes)
|| PACKET_remaining(&psk_kex_modes) == 0) {
SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_EXTENSION);
return 0;
}
while (PACKET_get_1(&psk_kex_modes, &mode)) {
if (mode == TLSEXT_KEX_MODE_KE_DHE)
s->ext.psk_kex_mode |= TLSEXT_KEX_MODE_FLAG_KE_DHE;
else if (mode == TLSEXT_KEX_MODE_KE
&& (s->options & SSL_OP_ALLOW_NO_DHE_KEX) != 0)
s->ext.psk_kex_mode |= TLSEXT_KEX_MODE_FLAG_KE;
}
#endif
return 1;
}
/*
* Process a key_share extension received in the ClientHello. |pkt| contains
* the raw PACKET data for the extension. Returns 1 on success or 0 on failure.
*/
int tls_parse_ctos_key_share(SSL *s, PACKET *pkt, unsigned int context, X509 *x,
size_t chainidx)
{
#ifndef OPENSSL_NO_TLS1_3
unsigned int group_id;
PACKET key_share_list, encoded_pt;
const uint16_t *clntgroups, *srvrgroups;
size_t clnt_num_groups, srvr_num_groups;
int found = 0;
if (s->hit && (s->ext.psk_kex_mode & TLSEXT_KEX_MODE_FLAG_KE_DHE) == 0)
return 1;
/* Sanity check */
if (s->s3.peer_tmp != NULL) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return 0;
}
if (!PACKET_as_length_prefixed_2(pkt, &key_share_list)) {
SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
return 0;
}
/* Get our list of supported groups */
tls1_get_supported_groups(s, &srvrgroups, &srvr_num_groups);
/* Get the clients list of supported groups. */
tls1_get_peer_groups(s, &clntgroups, &clnt_num_groups);
if (clnt_num_groups == 0) {
/*
* This can only happen if the supported_groups extension was not sent,
* because we verify that the length is non-zero when we process that
* extension.
*/
SSLfatal(s, SSL_AD_MISSING_EXTENSION,
SSL_R_MISSING_SUPPORTED_GROUPS_EXTENSION);
return 0;
}
if (s->s3.group_id != 0 && PACKET_remaining(&key_share_list) == 0) {
/*
* If we set a group_id already, then we must have sent an HRR
* requesting a new key_share. If we haven't got one then that is an
* error
*/
SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_BAD_KEY_SHARE);
return 0;
}
while (PACKET_remaining(&key_share_list) > 0) {
if (!PACKET_get_net_2(&key_share_list, &group_id)
|| !PACKET_get_length_prefixed_2(&key_share_list, &encoded_pt)
|| PACKET_remaining(&encoded_pt) == 0) {
SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
return 0;
}
/*
* If we already found a suitable key_share we loop through the
* rest to verify the structure, but don't process them.
*/
if (found)
continue;
/*
* If we sent an HRR then the key_share sent back MUST be for the group
* we requested, and must be the only key_share sent.
*/
if (s->s3.group_id != 0
&& (group_id != s->s3.group_id
|| PACKET_remaining(&key_share_list) != 0)) {
SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_BAD_KEY_SHARE);
return 0;
}
/* Check if this share is in supported_groups sent from client */
if (!check_in_list(s, group_id, clntgroups, clnt_num_groups, 0)) {
SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_BAD_KEY_SHARE);
return 0;
}
/* Check if this share is for a group we can use */
if (!check_in_list(s, group_id, srvrgroups, srvr_num_groups, 1)
|| !tls_group_allowed(s, group_id, SSL_SECOP_CURVE_SUPPORTED)
/*
* We tolerate but ignore a group id that we don't think is
* suitable for TLSv1.3
*/
|| !tls_valid_group(s, group_id, TLS1_3_VERSION, TLS1_3_VERSION,
0, NULL)) {
/* Share not suitable */
continue;
}
if ((s->s3.peer_tmp = ssl_generate_param_group(s, group_id)) == NULL) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR,
SSL_R_UNABLE_TO_FIND_ECDH_PARAMETERS);
return 0;
}
s->s3.group_id = group_id;
/* Cache the selected group ID in the SSL_SESSION */
s->session->kex_group = group_id;
if (tls13_set_encoded_pub_key(s->s3.peer_tmp,
PACKET_data(&encoded_pt),
PACKET_remaining(&encoded_pt)) <= 0) {
SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_BAD_ECPOINT);
return 0;
}
found = 1;
}
#endif
return 1;
}
int tls_parse_ctos_cookie(SSL *s, PACKET *pkt, unsigned int context, X509 *x,
size_t chainidx)
{
#ifndef OPENSSL_NO_TLS1_3
unsigned int format, version, key_share, group_id;
EVP_MD_CTX *hctx;
EVP_PKEY *pkey;
PACKET cookie, raw, chhash, appcookie;
WPACKET hrrpkt;
const unsigned char *data, *mdin, *ciphdata;
unsigned char hmac[SHA256_DIGEST_LENGTH];
unsigned char hrr[MAX_HRR_SIZE];
size_t rawlen, hmaclen, hrrlen, ciphlen;
uint64_t tm, now;
/* Ignore any cookie if we're not set up to verify it */
if (s->ctx->verify_stateless_cookie_cb == NULL
|| (s->s3.flags & TLS1_FLAGS_STATELESS) == 0)
return 1;
if (!PACKET_as_length_prefixed_2(pkt, &cookie)) {
SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
return 0;
}
raw = cookie;
data = PACKET_data(&raw);
rawlen = PACKET_remaining(&raw);
if (rawlen < SHA256_DIGEST_LENGTH
|| !PACKET_forward(&raw, rawlen - SHA256_DIGEST_LENGTH)) {
SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
return 0;
}
mdin = PACKET_data(&raw);
/* Verify the HMAC of the cookie */
hctx = EVP_MD_CTX_create();
pkey = EVP_PKEY_new_raw_private_key_ex(s->ctx->libctx, "HMAC",
s->ctx->propq,
s->session_ctx->ext.cookie_hmac_key,
sizeof(s->session_ctx->ext.cookie_hmac_key));
if (hctx == NULL || pkey == NULL) {
EVP_MD_CTX_free(hctx);
EVP_PKEY_free(pkey);
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_MALLOC_FAILURE);
return 0;
}
hmaclen = SHA256_DIGEST_LENGTH;
if (EVP_DigestSignInit_ex(hctx, NULL, "SHA2-256", s->ctx->libctx,
s->ctx->propq, pkey, NULL) <= 0
|| EVP_DigestSign(hctx, hmac, &hmaclen, data,
rawlen - SHA256_DIGEST_LENGTH) <= 0
|| hmaclen != SHA256_DIGEST_LENGTH) {
EVP_MD_CTX_free(hctx);
EVP_PKEY_free(pkey);
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return 0;
}
EVP_MD_CTX_free(hctx);
EVP_PKEY_free(pkey);
if (CRYPTO_memcmp(hmac, mdin, SHA256_DIGEST_LENGTH) != 0) {
SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_COOKIE_MISMATCH);
return 0;
}
if (!PACKET_get_net_2(&cookie, &format)) {
SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
return 0;
}
/* Check the cookie format is something we recognise. Ignore it if not */
if (format != COOKIE_STATE_FORMAT_VERSION)
return 1;
/*
* The rest of these checks really shouldn't fail since we have verified the
* HMAC above.
*/
/* Check the version number is sane */
if (!PACKET_get_net_2(&cookie, &version)) {
SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
return 0;
}
if (version != TLS1_3_VERSION) {
SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
SSL_R_BAD_PROTOCOL_VERSION_NUMBER);
return 0;
}
if (!PACKET_get_net_2(&cookie, &group_id)) {
SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
return 0;
}
ciphdata = PACKET_data(&cookie);
if (!PACKET_forward(&cookie, 2)) {
SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
return 0;
}
if (group_id != s->s3.group_id
|| s->s3.tmp.new_cipher
!= ssl_get_cipher_by_char(s, ciphdata, 0)) {
/*
* We chose a different cipher or group id this time around to what is
* in the cookie. Something must have changed.
*/
SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_BAD_CIPHER);
return 0;
}
if (!PACKET_get_1(&cookie, &key_share)
|| !PACKET_get_net_8(&cookie, &tm)
|| !PACKET_get_length_prefixed_2(&cookie, &chhash)
|| !PACKET_get_length_prefixed_1(&cookie, &appcookie)
|| PACKET_remaining(&cookie) != SHA256_DIGEST_LENGTH) {
SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
return 0;
}
/* We tolerate a cookie age of up to 10 minutes (= 60 * 10 seconds) */
now = time(NULL);
if (tm > now || (now - tm) > 600) {
/* Cookie is stale. Ignore it */
return 1;
}
/* Verify the app cookie */
if (s->ctx->verify_stateless_cookie_cb(s, PACKET_data(&appcookie),
PACKET_remaining(&appcookie)) == 0) {
SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_COOKIE_MISMATCH);
return 0;
}
/*
* Reconstruct the HRR that we would have sent in response to the original
* ClientHello so we can add it to the transcript hash.
* Note: This won't work with custom HRR extensions
*/
if (!WPACKET_init_static_len(&hrrpkt, hrr, sizeof(hrr), 0)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return 0;
}
if (!WPACKET_put_bytes_u8(&hrrpkt, SSL3_MT_SERVER_HELLO)
|| !WPACKET_start_sub_packet_u24(&hrrpkt)
|| !WPACKET_put_bytes_u16(&hrrpkt, TLS1_2_VERSION)
|| !WPACKET_memcpy(&hrrpkt, hrrrandom, SSL3_RANDOM_SIZE)
|| !WPACKET_sub_memcpy_u8(&hrrpkt, s->tmp_session_id,
s->tmp_session_id_len)
|| !s->method->put_cipher_by_char(s->s3.tmp.new_cipher, &hrrpkt,
&ciphlen)
|| !WPACKET_put_bytes_u8(&hrrpkt, 0)
|| !WPACKET_start_sub_packet_u16(&hrrpkt)) {
WPACKET_cleanup(&hrrpkt);
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return 0;
}
if (!WPACKET_put_bytes_u16(&hrrpkt, TLSEXT_TYPE_supported_versions)
|| !WPACKET_start_sub_packet_u16(&hrrpkt)
|| !WPACKET_put_bytes_u16(&hrrpkt, s->version)
|| !WPACKET_close(&hrrpkt)) {
WPACKET_cleanup(&hrrpkt);
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return 0;
}
if (key_share) {
if (!WPACKET_put_bytes_u16(&hrrpkt, TLSEXT_TYPE_key_share)
|| !WPACKET_start_sub_packet_u16(&hrrpkt)
|| !WPACKET_put_bytes_u16(&hrrpkt, s->s3.group_id)
|| !WPACKET_close(&hrrpkt)) {
WPACKET_cleanup(&hrrpkt);
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return 0;
}
}
if (!WPACKET_put_bytes_u16(&hrrpkt, TLSEXT_TYPE_cookie)
|| !WPACKET_start_sub_packet_u16(&hrrpkt)
|| !WPACKET_sub_memcpy_u16(&hrrpkt, data, rawlen)
|| !WPACKET_close(&hrrpkt) /* cookie extension */
|| !WPACKET_close(&hrrpkt) /* extension block */
|| !WPACKET_close(&hrrpkt) /* message */
|| !WPACKET_get_total_written(&hrrpkt, &hrrlen)
|| !WPACKET_finish(&hrrpkt)) {
WPACKET_cleanup(&hrrpkt);
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return 0;
}
/* Reconstruct the transcript hash */
if (!create_synthetic_message_hash(s, PACKET_data(&chhash),
PACKET_remaining(&chhash), hrr,
hrrlen)) {
/* SSLfatal() already called */
return 0;
}
/* Act as if this ClientHello came after a HelloRetryRequest */
s->hello_retry_request = SSL_HRR_PENDING;
s->ext.cookieok = 1;
#endif
return 1;
}
int tls_parse_ctos_supported_groups(SSL *s, PACKET *pkt, unsigned int context,
X509 *x, size_t chainidx)
{
PACKET supported_groups_list;
/* Each group is 2 bytes and we must have at least 1. */
if (!PACKET_as_length_prefixed_2(pkt, &supported_groups_list)
|| PACKET_remaining(&supported_groups_list) == 0
|| (PACKET_remaining(&supported_groups_list) % 2) != 0) {
SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_EXTENSION);
return 0;
}
if (!s->hit || SSL_IS_TLS13(s)) {
OPENSSL_free(s->ext.peer_supportedgroups);
s->ext.peer_supportedgroups = NULL;
s->ext.peer_supportedgroups_len = 0;
if (!tls1_save_u16(&supported_groups_list,
&s->ext.peer_supportedgroups,
&s->ext.peer_supportedgroups_len)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return 0;
}
}
return 1;
}
int tls_parse_ctos_ems(SSL *s, PACKET *pkt, unsigned int context, X509 *x,
size_t chainidx)
{
/* The extension must always be empty */
if (PACKET_remaining(pkt) != 0) {
SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_EXTENSION);
return 0;
}
if (s->options & SSL_OP_NO_EXTENDED_MASTER_SECRET)
return 1;
s->s3.flags |= TLS1_FLAGS_RECEIVED_EXTMS;
return 1;
}
int tls_parse_ctos_early_data(SSL *s, PACKET *pkt, unsigned int context,
X509 *x, size_t chainidx)
{
if (PACKET_remaining(pkt) != 0) {
SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_EXTENSION);
return 0;
}
if (s->hello_retry_request != SSL_HRR_NONE) {
SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_BAD_EXTENSION);
return 0;
}
return 1;
}
static SSL_TICKET_STATUS tls_get_stateful_ticket(SSL *s, PACKET *tick,
SSL_SESSION **sess)
{
SSL_SESSION *tmpsess = NULL;
s->ext.ticket_expected = 1;
switch (PACKET_remaining(tick)) {
case 0:
return SSL_TICKET_EMPTY;
case SSL_MAX_SSL_SESSION_ID_LENGTH:
break;
default:
return SSL_TICKET_NO_DECRYPT;
}
tmpsess = lookup_sess_in_cache(s, PACKET_data(tick),
SSL_MAX_SSL_SESSION_ID_LENGTH);
if (tmpsess == NULL)
return SSL_TICKET_NO_DECRYPT;
*sess = tmpsess;
return SSL_TICKET_SUCCESS;
}
int tls_parse_ctos_psk(SSL *s, PACKET *pkt, unsigned int context, X509 *x,
size_t chainidx)
{
PACKET identities, binders, binder;
size_t binderoffset, hashsize;
SSL_SESSION *sess = NULL;
unsigned int id, i, ext = 0;
const EVP_MD *md = NULL;
/*
* If we have no PSK kex mode that we recognise then we can't resume so
* ignore this extension
*/
if ((s->ext.psk_kex_mode
& (TLSEXT_KEX_MODE_FLAG_KE | TLSEXT_KEX_MODE_FLAG_KE_DHE)) == 0)
return 1;
if (!PACKET_get_length_prefixed_2(pkt, &identities)) {
SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_EXTENSION);
return 0;
}
s->ext.ticket_expected = 0;
for (id = 0; PACKET_remaining(&identities) != 0; id++) {
PACKET identity;
unsigned long ticket_agel;
size_t idlen;
if (!PACKET_get_length_prefixed_2(&identities, &identity)
|| !PACKET_get_net_4(&identities, &ticket_agel)) {
SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_EXTENSION);
return 0;
}
idlen = PACKET_remaining(&identity);
if (s->psk_find_session_cb != NULL
&& !s->psk_find_session_cb(s, PACKET_data(&identity), idlen,
&sess)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_BAD_EXTENSION);
return 0;
}
#ifndef OPENSSL_NO_PSK
if(sess == NULL
&& s->psk_server_callback != NULL
&& idlen <= PSK_MAX_IDENTITY_LEN) {
char *pskid = NULL;
unsigned char pskdata[PSK_MAX_PSK_LEN];
unsigned int pskdatalen;
if (!PACKET_strndup(&identity, &pskid)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return 0;
}
pskdatalen = s->psk_server_callback(s, pskid, pskdata,
sizeof(pskdata));
OPENSSL_free(pskid);
if (pskdatalen > PSK_MAX_PSK_LEN) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return 0;
} else if (pskdatalen > 0) {
const SSL_CIPHER *cipher;
const unsigned char tls13_aes128gcmsha256_id[] = { 0x13, 0x01 };
/*
* We found a PSK using an old style callback. We don't know
* the digest so we default to SHA256 as per the TLSv1.3 spec
*/
cipher = SSL_CIPHER_find(s, tls13_aes128gcmsha256_id);
if (cipher == NULL) {
OPENSSL_cleanse(pskdata, pskdatalen);
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return 0;
}
sess = SSL_SESSION_new();
if (sess == NULL
|| !SSL_SESSION_set1_master_key(sess, pskdata,
pskdatalen)
|| !SSL_SESSION_set_cipher(sess, cipher)
|| !SSL_SESSION_set_protocol_version(sess,
TLS1_3_VERSION)) {
OPENSSL_cleanse(pskdata, pskdatalen);
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
goto err;
}
OPENSSL_cleanse(pskdata, pskdatalen);
}
}
#endif /* OPENSSL_NO_PSK */
if (sess != NULL) {
/* We found a PSK */
SSL_SESSION *sesstmp = ssl_session_dup(sess, 0);
if (sesstmp == NULL) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return 0;
}
SSL_SESSION_free(sess);
sess = sesstmp;
/*
* We've just been told to use this session for this context so
* make sure the sid_ctx matches up.
*/
memcpy(sess->sid_ctx, s->sid_ctx, s->sid_ctx_length);
sess->sid_ctx_length = s->sid_ctx_length;
ext = 1;
if (id == 0)
s->ext.early_data_ok = 1;
s->ext.ticket_expected = 1;
} else {
uint32_t ticket_age = 0, agesec, agems;
int ret;
/*
* 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 ((s->options & SSL_OP_NO_TICKET) != 0
|| (s->max_early_data > 0
&& (s->options & SSL_OP_NO_ANTI_REPLAY) == 0))
ret = tls_get_stateful_ticket(s, &identity, &sess);
else
ret = tls_decrypt_ticket(s, PACKET_data(&identity),
PACKET_remaining(&identity), NULL, 0,
&sess);
if (ret == SSL_TICKET_EMPTY) {
SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_EXTENSION);
return 0;
}
if (ret == SSL_TICKET_FATAL_ERR_MALLOC
|| ret == SSL_TICKET_FATAL_ERR_OTHER) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return 0;
}
if (ret == SSL_TICKET_NONE || ret == SSL_TICKET_NO_DECRYPT)
continue;
/* Check for replay */
if (s->max_early_data > 0
&& (s->options & SSL_OP_NO_ANTI_REPLAY) == 0
&& !SSL_CTX_remove_session(s->session_ctx, sess)) {
SSL_SESSION_free(sess);
sess = NULL;
continue;
}
ticket_age = (uint32_t)ticket_agel;
agesec = (uint32_t)(time(NULL) - sess->time);
agems = agesec * (uint32_t)1000;
ticket_age -= sess->ext.tick_age_add;
/*
* For simplicity we do our age calculations in seconds. If the
* client does it in ms then it could appear that their ticket age
* is longer than ours (our ticket age calculation should always be
* slightly longer than the client's due to the network latency).
* Therefore we add 1000ms to our age calculation to adjust for
* rounding errors.
*/
if (id == 0
&& sess->timeout >= (long)agesec
&& agems / (uint32_t)1000 == agesec
&& ticket_age <= agems + 1000
&& ticket_age + TICKET_AGE_ALLOWANCE >= agems + 1000) {
/*
* Ticket age is within tolerance and not expired. We allow it
* for early data
*/
s->ext.early_data_ok = 1;
}
}
md = ssl_md(s->ctx, sess->cipher->algorithm2);
if (md == NULL) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
goto err;
}
if (!EVP_MD_is_a(md,
EVP_MD_get0_name(ssl_md(s->ctx,
s->s3.tmp.new_cipher->algorithm2)))) {
/* The ciphersuite is not compatible with this session. */
SSL_SESSION_free(sess);
sess = NULL;
s->ext.early_data_ok = 0;
s->ext.ticket_expected = 0;
continue;
}
break;
}
if (sess == NULL)
return 1;
binderoffset = PACKET_data(pkt) - (const unsigned char *)s->init_buf->data;
hashsize = EVP_MD_get_size(md);
if (!PACKET_get_length_prefixed_2(pkt, &binders)) {
SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_EXTENSION);
goto err;
}
for (i = 0; i <= id; i++) {
if (!PACKET_get_length_prefixed_1(&binders, &binder)) {
SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_EXTENSION);
goto err;
}
}
if (PACKET_remaining(&binder) != hashsize) {
SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_EXTENSION);
goto err;
}
if (tls_psk_do_binder(s, md, (const unsigned char *)s->init_buf->data,
binderoffset, PACKET_data(&binder), NULL, sess, 0,
ext) != 1) {
/* SSLfatal() already called */
goto err;
}
s->ext.tick_identity = id;
SSL_SESSION_free(s->session);
s->session = sess;
return 1;
err:
SSL_SESSION_free(sess);
return 0;
}
int tls_parse_ctos_post_handshake_auth(SSL *s, PACKET *pkt,
ossl_unused unsigned int context,
ossl_unused X509 *x,
ossl_unused size_t chainidx)
{
if (PACKET_remaining(pkt) != 0) {
SSLfatal(s, SSL_AD_DECODE_ERROR,
SSL_R_POST_HANDSHAKE_AUTH_ENCODING_ERR);
return 0;
}
s->post_handshake_auth = SSL_PHA_EXT_RECEIVED;
return 1;
}
/*
* Add the server's renegotiation binding
*/
EXT_RETURN tls_construct_stoc_renegotiate(SSL *s, WPACKET *pkt,
unsigned int context, X509 *x,
size_t chainidx)
{
if (!s->s3.send_connection_binding)
return EXT_RETURN_NOT_SENT;
/* Still add this even if SSL_OP_NO_RENEGOTIATION is set */
if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_renegotiate)
|| !WPACKET_start_sub_packet_u16(pkt)
|| !WPACKET_start_sub_packet_u8(pkt)
|| !WPACKET_memcpy(pkt, s->s3.previous_client_finished,
s->s3.previous_client_finished_len)
|| !WPACKET_memcpy(pkt, s->s3.previous_server_finished,
s->s3.previous_server_finished_len)
|| !WPACKET_close(pkt)
|| !WPACKET_close(pkt)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return EXT_RETURN_FAIL;
}
return EXT_RETURN_SENT;
}
EXT_RETURN tls_construct_stoc_server_name(SSL *s, WPACKET *pkt,
unsigned int context, X509 *x,
size_t chainidx)
{
if (s->servername_done != 1)
return EXT_RETURN_NOT_SENT;
/*
* Prior to TLSv1.3 we ignore any SNI in the current handshake if resuming.
* We just use the servername from the initial handshake.
*/
if (s->hit && !SSL_IS_TLS13(s))
return EXT_RETURN_NOT_SENT;
if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_server_name)
|| !WPACKET_put_bytes_u16(pkt, 0)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return EXT_RETURN_FAIL;
}
return EXT_RETURN_SENT;
}
/* Add/include the server's max fragment len extension into ServerHello */
EXT_RETURN tls_construct_stoc_maxfragmentlen(SSL *s, WPACKET *pkt,
unsigned int context, X509 *x,
size_t chainidx)
{
if (!USE_MAX_FRAGMENT_LENGTH_EXT(s->session))
return EXT_RETURN_NOT_SENT;
/*-
* 4 bytes for this extension type and extension length
* 1 byte for the Max Fragment Length code value.
*/
if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_max_fragment_length)
|| !WPACKET_start_sub_packet_u16(pkt)
|| !WPACKET_put_bytes_u8(pkt, s->session->ext.max_fragment_len_mode)
|| !WPACKET_close(pkt)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return EXT_RETURN_FAIL;
}
return EXT_RETURN_SENT;
}
EXT_RETURN tls_construct_stoc_ec_pt_formats(SSL *s, WPACKET *pkt,
unsigned int context, X509 *x,
size_t chainidx)
{
unsigned long alg_k = s->s3.tmp.new_cipher->algorithm_mkey;
unsigned long alg_a = s->s3.tmp.new_cipher->algorithm_auth;
int using_ecc = ((alg_k & SSL_kECDHE) || (alg_a & SSL_aECDSA))
&& (s->ext.peer_ecpointformats != NULL);
const unsigned char *plist;
size_t plistlen;
if (!using_ecc)
return EXT_RETURN_NOT_SENT;
tls1_get_formatlist(s, &plist, &plistlen);
if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_ec_point_formats)
|| !WPACKET_start_sub_packet_u16(pkt)
|| !WPACKET_sub_memcpy_u8(pkt, plist, plistlen)
|| !WPACKET_close(pkt)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return EXT_RETURN_FAIL;
}
return EXT_RETURN_SENT;
}
EXT_RETURN tls_construct_stoc_supported_groups(SSL *s, WPACKET *pkt,
unsigned int context, X509 *x,
size_t chainidx)
{
const uint16_t *groups;
size_t numgroups, i, first = 1;
int version;
/* s->s3.group_id is non zero if we accepted a key_share */
if (s->s3.group_id == 0)
return EXT_RETURN_NOT_SENT;
/* Get our list of supported groups */
tls1_get_supported_groups(s, &groups, &numgroups);
if (numgroups == 0) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return EXT_RETURN_FAIL;
}
/* Copy group ID if supported */
version = SSL_version(s);
for (i = 0; i < numgroups; i++) {
uint16_t group = groups[i];
if (tls_valid_group(s, group, version, version, 0, NULL)
&& tls_group_allowed(s, group, SSL_SECOP_CURVE_SUPPORTED)) {
if (first) {
/*
* Check if the client is already using our preferred group. If
* so we don't need to add this extension
*/
if (s->s3.group_id == group)
return EXT_RETURN_NOT_SENT;
/* Add extension header */
if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_supported_groups)
/* Sub-packet for supported_groups extension */
|| !WPACKET_start_sub_packet_u16(pkt)
|| !WPACKET_start_sub_packet_u16(pkt)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return EXT_RETURN_FAIL;
}
first = 0;
}
if (!WPACKET_put_bytes_u16(pkt, group)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return EXT_RETURN_FAIL;
}
}
}
if (!WPACKET_close(pkt) || !WPACKET_close(pkt)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return EXT_RETURN_FAIL;
}
return EXT_RETURN_SENT;
}
EXT_RETURN tls_construct_stoc_session_ticket(SSL *s, WPACKET *pkt,
unsigned int context, X509 *x,
size_t chainidx)
{
if (!s->ext.ticket_expected || !tls_use_ticket(s)) {
s->ext.ticket_expected = 0;
return EXT_RETURN_NOT_SENT;
}
if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_session_ticket)
|| !WPACKET_put_bytes_u16(pkt, 0)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return EXT_RETURN_FAIL;
}
return EXT_RETURN_SENT;
}
#ifndef OPENSSL_NO_OCSP
EXT_RETURN tls_construct_stoc_status_request(SSL *s, WPACKET *pkt,
unsigned int context, X509 *x,
size_t chainidx)
{
/* We don't currently support this extension inside a CertificateRequest */
if (context == SSL_EXT_TLS1_3_CERTIFICATE_REQUEST)
return EXT_RETURN_NOT_SENT;
if (!s->ext.status_expected)
return EXT_RETURN_NOT_SENT;
if (SSL_IS_TLS13(s) && chainidx != 0)
return EXT_RETURN_NOT_SENT;
if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_status_request)
|| !WPACKET_start_sub_packet_u16(pkt)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return EXT_RETURN_FAIL;
}
/*
* In TLSv1.3 we include the certificate status itself. In <= TLSv1.2 we
* send back an empty extension, with the certificate status appearing as a
* separate message
*/
if (SSL_IS_TLS13(s) && !tls_construct_cert_status_body(s, pkt)) {
/* SSLfatal() already called */
return EXT_RETURN_FAIL;
}
if (!WPACKET_close(pkt)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return EXT_RETURN_FAIL;
}
return EXT_RETURN_SENT;
}
#endif
#ifndef OPENSSL_NO_NEXTPROTONEG
EXT_RETURN tls_construct_stoc_next_proto_neg(SSL *s, WPACKET *pkt,
unsigned int context, X509 *x,
size_t chainidx)
{
const unsigned char *npa;
unsigned int npalen;
int ret;
int npn_seen = s->s3.npn_seen;
s->s3.npn_seen = 0;
if (!npn_seen || s->ctx->ext.npn_advertised_cb == NULL)
return EXT_RETURN_NOT_SENT;
ret = s->ctx->ext.npn_advertised_cb(s, &npa, &npalen,
s->ctx->ext.npn_advertised_cb_arg);
if (ret == SSL_TLSEXT_ERR_OK) {
if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_next_proto_neg)
|| !WPACKET_sub_memcpy_u16(pkt, npa, npalen)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return EXT_RETURN_FAIL;
}
s->s3.npn_seen = 1;
+ return EXT_RETURN_SENT;
}
- return EXT_RETURN_SENT;
+ return EXT_RETURN_NOT_SENT;
}
#endif
EXT_RETURN tls_construct_stoc_alpn(SSL *s, WPACKET *pkt, unsigned int context,
X509 *x, size_t chainidx)
{
if (s->s3.alpn_selected == NULL)
return EXT_RETURN_NOT_SENT;
if (!WPACKET_put_bytes_u16(pkt,
TLSEXT_TYPE_application_layer_protocol_negotiation)
|| !WPACKET_start_sub_packet_u16(pkt)
|| !WPACKET_start_sub_packet_u16(pkt)
|| !WPACKET_sub_memcpy_u8(pkt, s->s3.alpn_selected,
s->s3.alpn_selected_len)
|| !WPACKET_close(pkt)
|| !WPACKET_close(pkt)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return EXT_RETURN_FAIL;
}
return EXT_RETURN_SENT;
}
#ifndef OPENSSL_NO_SRTP
EXT_RETURN tls_construct_stoc_use_srtp(SSL *s, WPACKET *pkt,
unsigned int context, X509 *x,
size_t chainidx)
{
if (s->srtp_profile == NULL)
return EXT_RETURN_NOT_SENT;
if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_use_srtp)
|| !WPACKET_start_sub_packet_u16(pkt)
|| !WPACKET_put_bytes_u16(pkt, 2)
|| !WPACKET_put_bytes_u16(pkt, s->srtp_profile->id)
|| !WPACKET_put_bytes_u8(pkt, 0)
|| !WPACKET_close(pkt)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return EXT_RETURN_FAIL;
}
return EXT_RETURN_SENT;
}
#endif
EXT_RETURN tls_construct_stoc_etm(SSL *s, WPACKET *pkt, unsigned int context,
X509 *x, size_t chainidx)
{
if (!s->ext.use_etm)
return EXT_RETURN_NOT_SENT;
/*
* Don't use encrypt_then_mac if AEAD or RC4 might want to disable
* for other cases too.
*/
if (s->s3.tmp.new_cipher->algorithm_mac == SSL_AEAD
|| s->s3.tmp.new_cipher->algorithm_enc == SSL_RC4
|| s->s3.tmp.new_cipher->algorithm_enc == SSL_eGOST2814789CNT
|| s->s3.tmp.new_cipher->algorithm_enc == SSL_eGOST2814789CNT12
|| s->s3.tmp.new_cipher->algorithm_enc == SSL_MAGMA
|| s->s3.tmp.new_cipher->algorithm_enc == SSL_KUZNYECHIK) {
s->ext.use_etm = 0;
return EXT_RETURN_NOT_SENT;
}
if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_encrypt_then_mac)
|| !WPACKET_put_bytes_u16(pkt, 0)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return EXT_RETURN_FAIL;
}
return EXT_RETURN_SENT;
}
EXT_RETURN tls_construct_stoc_ems(SSL *s, WPACKET *pkt, unsigned int context,
X509 *x, size_t chainidx)
{
if ((s->s3.flags & TLS1_FLAGS_RECEIVED_EXTMS) == 0)
return EXT_RETURN_NOT_SENT;
if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_extended_master_secret)
|| !WPACKET_put_bytes_u16(pkt, 0)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return EXT_RETURN_FAIL;
}
return EXT_RETURN_SENT;
}
EXT_RETURN tls_construct_stoc_supported_versions(SSL *s, WPACKET *pkt,
unsigned int context, X509 *x,
size_t chainidx)
{
if (!ossl_assert(SSL_IS_TLS13(s))) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return EXT_RETURN_FAIL;
}
if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_supported_versions)
|| !WPACKET_start_sub_packet_u16(pkt)
|| !WPACKET_put_bytes_u16(pkt, s->version)
|| !WPACKET_close(pkt)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return EXT_RETURN_FAIL;
}
return EXT_RETURN_SENT;
}
EXT_RETURN tls_construct_stoc_key_share(SSL *s, WPACKET *pkt,
unsigned int context, X509 *x,
size_t chainidx)
{
#ifndef OPENSSL_NO_TLS1_3
unsigned char *encodedPoint;
size_t encoded_pt_len = 0;
EVP_PKEY *ckey = s->s3.peer_tmp, *skey = NULL;
const TLS_GROUP_INFO *ginf = NULL;
if (s->hello_retry_request == SSL_HRR_PENDING) {
if (ckey != NULL) {
/* Original key_share was acceptable so don't ask for another one */
return EXT_RETURN_NOT_SENT;
}
if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_key_share)
|| !WPACKET_start_sub_packet_u16(pkt)
|| !WPACKET_put_bytes_u16(pkt, s->s3.group_id)
|| !WPACKET_close(pkt)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return EXT_RETURN_FAIL;
}
return EXT_RETURN_SENT;
}
if (ckey == NULL) {
/* No key_share received from client - must be resuming */
if (!s->hit || !tls13_generate_handshake_secret(s, NULL, 0)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return EXT_RETURN_FAIL;
}
return EXT_RETURN_NOT_SENT;
}
if (s->hit && (s->ext.psk_kex_mode & TLSEXT_KEX_MODE_FLAG_KE_DHE) == 0) {
/*
* PSK ('hit') and explicitly not doing DHE (if the client sent the
* DHE option we always take it); don't send key share.
*/
return EXT_RETURN_NOT_SENT;
}
if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_key_share)
|| !WPACKET_start_sub_packet_u16(pkt)
|| !WPACKET_put_bytes_u16(pkt, s->s3.group_id)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return EXT_RETURN_FAIL;
}
if ((ginf = tls1_group_id_lookup(s->ctx, s->s3.group_id)) == NULL) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return EXT_RETURN_FAIL;
}
if (!ginf->is_kem) {
/* Regular KEX */
skey = ssl_generate_pkey(s, ckey);
if (skey == NULL) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_MALLOC_FAILURE);
return EXT_RETURN_FAIL;
}
/* Generate encoding of server key */
encoded_pt_len = EVP_PKEY_get1_encoded_public_key(skey, &encodedPoint);
if (encoded_pt_len == 0) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EC_LIB);
EVP_PKEY_free(skey);
return EXT_RETURN_FAIL;
}
if (!WPACKET_sub_memcpy_u16(pkt, encodedPoint, encoded_pt_len)
|| !WPACKET_close(pkt)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
EVP_PKEY_free(skey);
OPENSSL_free(encodedPoint);
return EXT_RETURN_FAIL;
}
OPENSSL_free(encodedPoint);
/*
* This causes the crypto state to be updated based on the derived keys
*/
s->s3.tmp.pkey = skey;
if (ssl_derive(s, skey, ckey, 1) == 0) {
/* SSLfatal() already called */
return EXT_RETURN_FAIL;
}
} else {
/* KEM mode */
unsigned char *ct = NULL;
size_t ctlen = 0;
/*
* This does not update the crypto state.
*
* The generated pms is stored in `s->s3.tmp.pms` to be later used via
* ssl_gensecret().
*/
if (ssl_encapsulate(s, ckey, &ct, &ctlen, 0) == 0) {
/* SSLfatal() already called */
return EXT_RETURN_FAIL;
}
if (ctlen == 0) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
OPENSSL_free(ct);
return EXT_RETURN_FAIL;
}
if (!WPACKET_sub_memcpy_u16(pkt, ct, ctlen)
|| !WPACKET_close(pkt)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
OPENSSL_free(ct);
return EXT_RETURN_FAIL;
}
OPENSSL_free(ct);
/*
* This causes the crypto state to be updated based on the generated pms
*/
if (ssl_gensecret(s, s->s3.tmp.pms, s->s3.tmp.pmslen) == 0) {
/* SSLfatal() already called */
return EXT_RETURN_FAIL;
}
}
s->s3.did_kex = 1;
return EXT_RETURN_SENT;
#else
return EXT_RETURN_FAIL;
#endif
}
EXT_RETURN tls_construct_stoc_cookie(SSL *s, WPACKET *pkt, unsigned int context,
X509 *x, size_t chainidx)
{
#ifndef OPENSSL_NO_TLS1_3
unsigned char *hashval1, *hashval2, *appcookie1, *appcookie2, *cookie;
unsigned char *hmac, *hmac2;
size_t startlen, ciphlen, totcookielen, hashlen, hmaclen, appcookielen;
EVP_MD_CTX *hctx;
EVP_PKEY *pkey;
int ret = EXT_RETURN_FAIL;
if ((s->s3.flags & TLS1_FLAGS_STATELESS) == 0)
return EXT_RETURN_NOT_SENT;
if (s->ctx->gen_stateless_cookie_cb == NULL) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_NO_COOKIE_CALLBACK_SET);
return EXT_RETURN_FAIL;
}
if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_cookie)
|| !WPACKET_start_sub_packet_u16(pkt)
|| !WPACKET_start_sub_packet_u16(pkt)
|| !WPACKET_get_total_written(pkt, &startlen)
|| !WPACKET_reserve_bytes(pkt, MAX_COOKIE_SIZE, &cookie)
|| !WPACKET_put_bytes_u16(pkt, COOKIE_STATE_FORMAT_VERSION)
|| !WPACKET_put_bytes_u16(pkt, TLS1_3_VERSION)
|| !WPACKET_put_bytes_u16(pkt, s->s3.group_id)
|| !s->method->put_cipher_by_char(s->s3.tmp.new_cipher, pkt,
&ciphlen)
/* Is there a key_share extension present in this HRR? */
|| !WPACKET_put_bytes_u8(pkt, s->s3.peer_tmp == NULL)
|| !WPACKET_put_bytes_u64(pkt, time(NULL))
|| !WPACKET_start_sub_packet_u16(pkt)
|| !WPACKET_reserve_bytes(pkt, EVP_MAX_MD_SIZE, &hashval1)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return EXT_RETURN_FAIL;
}
/*
* Get the hash of the initial ClientHello. ssl_handshake_hash() operates
* on raw buffers, so we first reserve sufficient bytes (above) and then
* subsequently allocate them (below)
*/
if (!ssl3_digest_cached_records(s, 0)
|| !ssl_handshake_hash(s, hashval1, EVP_MAX_MD_SIZE, &hashlen)) {
/* SSLfatal() already called */
return EXT_RETURN_FAIL;
}
if (!WPACKET_allocate_bytes(pkt, hashlen, &hashval2)
|| !ossl_assert(hashval1 == hashval2)
|| !WPACKET_close(pkt)
|| !WPACKET_start_sub_packet_u8(pkt)
|| !WPACKET_reserve_bytes(pkt, SSL_COOKIE_LENGTH, &appcookie1)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return EXT_RETURN_FAIL;
}
/* Generate the application cookie */
if (s->ctx->gen_stateless_cookie_cb(s, appcookie1, &appcookielen) == 0) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_COOKIE_GEN_CALLBACK_FAILURE);
return EXT_RETURN_FAIL;
}
if (!WPACKET_allocate_bytes(pkt, appcookielen, &appcookie2)
|| !ossl_assert(appcookie1 == appcookie2)
|| !WPACKET_close(pkt)
|| !WPACKET_get_total_written(pkt, &totcookielen)
|| !WPACKET_reserve_bytes(pkt, SHA256_DIGEST_LENGTH, &hmac)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return EXT_RETURN_FAIL;
}
hmaclen = SHA256_DIGEST_LENGTH;
totcookielen -= startlen;
if (!ossl_assert(totcookielen <= MAX_COOKIE_SIZE - SHA256_DIGEST_LENGTH)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return EXT_RETURN_FAIL;
}
/* HMAC the cookie */
hctx = EVP_MD_CTX_create();
pkey = EVP_PKEY_new_raw_private_key_ex(s->ctx->libctx, "HMAC",
s->ctx->propq,
s->session_ctx->ext.cookie_hmac_key,
sizeof(s->session_ctx->ext.cookie_hmac_key));
if (hctx == NULL || pkey == NULL) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_MALLOC_FAILURE);
goto err;
}
if (EVP_DigestSignInit_ex(hctx, NULL, "SHA2-256", s->ctx->libctx,
s->ctx->propq, pkey, NULL) <= 0
|| EVP_DigestSign(hctx, hmac, &hmaclen, cookie,
totcookielen) <= 0) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
goto err;
}
if (!ossl_assert(totcookielen + hmaclen <= MAX_COOKIE_SIZE)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
goto err;
}
if (!WPACKET_allocate_bytes(pkt, hmaclen, &hmac2)
|| !ossl_assert(hmac == hmac2)
|| !ossl_assert(cookie == hmac - totcookielen)
|| !WPACKET_close(pkt)
|| !WPACKET_close(pkt)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
goto err;
}
ret = EXT_RETURN_SENT;
err:
EVP_MD_CTX_free(hctx);
EVP_PKEY_free(pkey);
return ret;
#else
return EXT_RETURN_FAIL;
#endif
}
EXT_RETURN tls_construct_stoc_cryptopro_bug(SSL *s, WPACKET *pkt,
unsigned int context, X509 *x,
size_t chainidx)
{
const unsigned char cryptopro_ext[36] = {
0xfd, 0xe8, /* 65000 */
0x00, 0x20, /* 32 bytes length */
0x30, 0x1e, 0x30, 0x08, 0x06, 0x06, 0x2a, 0x85,
0x03, 0x02, 0x02, 0x09, 0x30, 0x08, 0x06, 0x06,
0x2a, 0x85, 0x03, 0x02, 0x02, 0x16, 0x30, 0x08,
0x06, 0x06, 0x2a, 0x85, 0x03, 0x02, 0x02, 0x17
};
if (((s->s3.tmp.new_cipher->id & 0xFFFF) != 0x80
&& (s->s3.tmp.new_cipher->id & 0xFFFF) != 0x81)
|| (SSL_get_options(s) & SSL_OP_CRYPTOPRO_TLSEXT_BUG) == 0)
return EXT_RETURN_NOT_SENT;
if (!WPACKET_memcpy(pkt, cryptopro_ext, sizeof(cryptopro_ext))) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return EXT_RETURN_FAIL;
}
return EXT_RETURN_SENT;
}
EXT_RETURN tls_construct_stoc_early_data(SSL *s, WPACKET *pkt,
unsigned int context, X509 *x,
size_t chainidx)
{
if (context == SSL_EXT_TLS1_3_NEW_SESSION_TICKET) {
if (s->max_early_data == 0)
return EXT_RETURN_NOT_SENT;
if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_early_data)
|| !WPACKET_start_sub_packet_u16(pkt)
|| !WPACKET_put_bytes_u32(pkt, s->max_early_data)
|| !WPACKET_close(pkt)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return EXT_RETURN_FAIL;
}
return EXT_RETURN_SENT;
}
if (s->ext.early_data != SSL_EARLY_DATA_ACCEPTED)
return EXT_RETURN_NOT_SENT;
if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_early_data)
|| !WPACKET_start_sub_packet_u16(pkt)
|| !WPACKET_close(pkt)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return EXT_RETURN_FAIL;
}
return EXT_RETURN_SENT;
}
EXT_RETURN tls_construct_stoc_psk(SSL *s, WPACKET *pkt, unsigned int context,
X509 *x, size_t chainidx)
{
if (!s->hit)
return EXT_RETURN_NOT_SENT;
if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_psk)
|| !WPACKET_start_sub_packet_u16(pkt)
|| !WPACKET_put_bytes_u16(pkt, s->ext.tick_identity)
|| !WPACKET_close(pkt)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return EXT_RETURN_FAIL;
}
return EXT_RETURN_SENT;
}
diff --git a/crypto/openssl/ssl/statem/statem_lib.c b/crypto/openssl/ssl/statem/statem_lib.c
index b1ee38b9e5bc..6f0eaa5d6c0d 100644
--- a/crypto/openssl/ssl/statem/statem_lib.c
+++ b/crypto/openssl/ssl/statem/statem_lib.c
@@ -1,2412 +1,2416 @@
/*
- * 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
*/
#include <limits.h>
#include <string.h>
#include <stdio.h>
#include "../ssl_local.h"
#include "statem_local.h"
#include "internal/cryptlib.h"
#include <openssl/buffer.h>
#include <openssl/objects.h>
#include <openssl/evp.h>
#include <openssl/rsa.h>
#include <openssl/x509.h>
#include <openssl/trace.h>
/*
* Map error codes to TLS/SSL alart types.
*/
typedef struct x509err2alert_st {
int x509err;
int alert;
} X509ERR2ALERT;
/* Fixed value used in the ServerHello random field to identify an HRR */
const unsigned char hrrrandom[] = {
0xcf, 0x21, 0xad, 0x74, 0xe5, 0x9a, 0x61, 0x11, 0xbe, 0x1d, 0x8c, 0x02,
0x1e, 0x65, 0xb8, 0x91, 0xc2, 0xa2, 0x11, 0x16, 0x7a, 0xbb, 0x8c, 0x5e,
0x07, 0x9e, 0x09, 0xe2, 0xc8, 0xa8, 0x33, 0x9c
};
/*
* send s->init_buf in records of type 'type' (SSL3_RT_HANDSHAKE or
* SSL3_RT_CHANGE_CIPHER_SPEC)
*/
int ssl3_do_write(SSL *s, int type)
{
int ret;
size_t written = 0;
ret = ssl3_write_bytes(s, type, &s->init_buf->data[s->init_off],
s->init_num, &written);
if (ret <= 0)
return -1;
if (type == SSL3_RT_HANDSHAKE)
/*
* should not be done for 'Hello Request's, but in that case we'll
* ignore the result anyway
* TLS1.3 KeyUpdate and NewSessionTicket do not need to be added
*/
if (!SSL_IS_TLS13(s) || (s->statem.hand_state != TLS_ST_SW_SESSION_TICKET
&& s->statem.hand_state != TLS_ST_CW_KEY_UPDATE
&& s->statem.hand_state != TLS_ST_SW_KEY_UPDATE))
if (!ssl3_finish_mac(s,
(unsigned char *)&s->init_buf->data[s->init_off],
written))
return -1;
if (written == s->init_num) {
if (s->msg_callback)
s->msg_callback(1, s->version, type, s->init_buf->data,
(size_t)(s->init_off + s->init_num), s,
s->msg_callback_arg);
return 1;
}
s->init_off += written;
s->init_num -= written;
return 0;
}
int tls_close_construct_packet(SSL *s, WPACKET *pkt, int htype)
{
size_t msglen;
if ((htype != SSL3_MT_CHANGE_CIPHER_SPEC && !WPACKET_close(pkt))
|| !WPACKET_get_length(pkt, &msglen)
|| msglen > INT_MAX)
return 0;
s->init_num = (int)msglen;
s->init_off = 0;
return 1;
}
int tls_setup_handshake(SSL *s)
{
int ver_min, ver_max, ok;
if (!ssl3_init_finished_mac(s)) {
/* SSLfatal() already called */
return 0;
}
/* Reset any extension flags */
memset(s->ext.extflags, 0, sizeof(s->ext.extflags));
if (ssl_get_min_max_version(s, &ver_min, &ver_max, NULL) != 0) {
SSLfatal(s, SSL_AD_PROTOCOL_VERSION, SSL_R_NO_PROTOCOLS_AVAILABLE);
return 0;
}
/* Sanity check that we have MD5-SHA1 if we need it */
if (s->ctx->ssl_digest_methods[SSL_MD_MD5_SHA1_IDX] == NULL) {
int md5sha1_needed = 0;
/* We don't have MD5-SHA1 - do we need it? */
if (SSL_IS_DTLS(s)) {
if (DTLS_VERSION_LE(ver_max, DTLS1_VERSION))
md5sha1_needed = 1;
} else {
if (ver_max <= TLS1_1_VERSION)
md5sha1_needed = 1;
}
if (md5sha1_needed) {
SSLfatal_data(s, SSL_AD_HANDSHAKE_FAILURE,
SSL_R_NO_SUITABLE_DIGEST_ALGORITHM,
"The max supported SSL/TLS version needs the"
" MD5-SHA1 digest but it is not available"
" in the loaded providers. Use (D)TLSv1.2 or"
" above, or load different providers");
return 0;
}
ok = 1;
/* Don't allow TLSv1.1 or below to be negotiated */
if (SSL_IS_DTLS(s)) {
if (DTLS_VERSION_LT(ver_min, DTLS1_2_VERSION))
ok = SSL_set_min_proto_version(s, DTLS1_2_VERSION);
} else {
if (ver_min < TLS1_2_VERSION)
ok = SSL_set_min_proto_version(s, TLS1_2_VERSION);
}
if (!ok) {
/* Shouldn't happen */
SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, ERR_R_INTERNAL_ERROR);
return 0;
}
}
ok = 0;
if (s->server) {
STACK_OF(SSL_CIPHER) *ciphers = SSL_get_ciphers(s);
int i;
/*
* Sanity check that the maximum version we accept has ciphers
* enabled. For clients we do this check during construction of the
* ClientHello.
*/
for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
const SSL_CIPHER *c = sk_SSL_CIPHER_value(ciphers, i);
if (SSL_IS_DTLS(s)) {
if (DTLS_VERSION_GE(ver_max, c->min_dtls) &&
DTLS_VERSION_LE(ver_max, c->max_dtls))
ok = 1;
} else if (ver_max >= c->min_tls && ver_max <= c->max_tls) {
ok = 1;
}
if (ok)
break;
}
if (!ok) {
SSLfatal_data(s, SSL_AD_HANDSHAKE_FAILURE,
SSL_R_NO_CIPHERS_AVAILABLE,
"No ciphers enabled for max supported "
"SSL/TLS version");
return 0;
}
if (SSL_IS_FIRST_HANDSHAKE(s)) {
/* N.B. s->session_ctx == s->ctx here */
ssl_tsan_counter(s->session_ctx, &s->session_ctx->stats.sess_accept);
} else {
/* N.B. s->ctx may not equal s->session_ctx */
ssl_tsan_counter(s->ctx, &s->ctx->stats.sess_accept_renegotiate);
s->s3.tmp.cert_request = 0;
}
} else {
if (SSL_IS_FIRST_HANDSHAKE(s))
ssl_tsan_counter(s->session_ctx, &s->session_ctx->stats.sess_connect);
else
ssl_tsan_counter(s->session_ctx,
&s->session_ctx->stats.sess_connect_renegotiate);
/* mark client_random uninitialized */
memset(s->s3.client_random, 0, sizeof(s->s3.client_random));
s->hit = 0;
s->s3.tmp.cert_req = 0;
if (SSL_IS_DTLS(s))
s->statem.use_timer = 1;
}
return 1;
}
/*
* Size of the to-be-signed TLS13 data, without the hash size itself:
* 64 bytes of value 32, 33 context bytes, 1 byte separator
*/
#define TLS13_TBS_START_SIZE 64
#define TLS13_TBS_PREAMBLE_SIZE (TLS13_TBS_START_SIZE + 33 + 1)
static int get_cert_verify_tbs_data(SSL *s, unsigned char *tls13tbs,
void **hdata, size_t *hdatalen)
{
#ifdef CHARSET_EBCDIC
static const char servercontext[] = { 0x54, 0x4c, 0x53, 0x20, 0x31, 0x2e,
0x33, 0x2c, 0x20, 0x73, 0x65, 0x72, 0x76, 0x65, 0x72, 0x20, 0x43, 0x65,
0x72, 0x74, 0x69, 0x66, 0x69, 0x63, 0x61, 0x74, 0x65, 0x56, 0x65, 0x72,
0x69, 0x66, 0x79, 0x00 };
static const char clientcontext[] = { 0x54, 0x4c, 0x53, 0x20, 0x31, 0x2e,
0x33, 0x2c, 0x20, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x20, 0x43, 0x65,
0x72, 0x74, 0x69, 0x66, 0x69, 0x63, 0x61, 0x74, 0x65, 0x56, 0x65, 0x72,
0x69, 0x66, 0x79, 0x00 };
#else
static const char servercontext[] = "TLS 1.3, server CertificateVerify";
static const char clientcontext[] = "TLS 1.3, client CertificateVerify";
#endif
if (SSL_IS_TLS13(s)) {
size_t hashlen;
/* Set the first 64 bytes of to-be-signed data to octet 32 */
memset(tls13tbs, 32, TLS13_TBS_START_SIZE);
/* This copies the 33 bytes of context plus the 0 separator byte */
if (s->statem.hand_state == TLS_ST_CR_CERT_VRFY
|| s->statem.hand_state == TLS_ST_SW_CERT_VRFY)
strcpy((char *)tls13tbs + TLS13_TBS_START_SIZE, servercontext);
else
strcpy((char *)tls13tbs + TLS13_TBS_START_SIZE, clientcontext);
/*
* If we're currently reading then we need to use the saved handshake
* hash value. We can't use the current handshake hash state because
* that includes the CertVerify itself.
*/
if (s->statem.hand_state == TLS_ST_CR_CERT_VRFY
|| s->statem.hand_state == TLS_ST_SR_CERT_VRFY) {
memcpy(tls13tbs + TLS13_TBS_PREAMBLE_SIZE, s->cert_verify_hash,
s->cert_verify_hash_len);
hashlen = s->cert_verify_hash_len;
} else if (!ssl_handshake_hash(s, tls13tbs + TLS13_TBS_PREAMBLE_SIZE,
EVP_MAX_MD_SIZE, &hashlen)) {
/* SSLfatal() already called */
return 0;
}
*hdata = tls13tbs;
*hdatalen = TLS13_TBS_PREAMBLE_SIZE + hashlen;
} else {
size_t retlen;
long retlen_l;
retlen = retlen_l = BIO_get_mem_data(s->s3.handshake_buffer, hdata);
if (retlen_l <= 0) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return 0;
}
*hdatalen = retlen;
}
return 1;
}
int tls_construct_cert_verify(SSL *s, WPACKET *pkt)
{
EVP_PKEY *pkey = NULL;
const EVP_MD *md = NULL;
EVP_MD_CTX *mctx = NULL;
EVP_PKEY_CTX *pctx = NULL;
size_t hdatalen = 0, siglen = 0;
void *hdata;
unsigned char *sig = NULL;
unsigned char tls13tbs[TLS13_TBS_PREAMBLE_SIZE + EVP_MAX_MD_SIZE];
const SIGALG_LOOKUP *lu = s->s3.tmp.sigalg;
if (lu == NULL || s->s3.tmp.cert == NULL) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
goto err;
}
pkey = s->s3.tmp.cert->privatekey;
if (pkey == NULL || !tls1_lookup_md(s->ctx, lu, &md)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
goto err;
}
mctx = EVP_MD_CTX_new();
if (mctx == NULL) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_MALLOC_FAILURE);
goto err;
}
/* Get the data to be signed */
if (!get_cert_verify_tbs_data(s, tls13tbs, &hdata, &hdatalen)) {
/* SSLfatal() already called */
goto err;
}
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(mctx, &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_EVP_LIB);
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;
}
}
if (s->version == SSL3_VERSION) {
/*
* Here we use EVP_DigestSignUpdate followed by EVP_DigestSignFinal
* in order to add the EVP_CTRL_SSL3_MASTER_SECRET call between them.
*/
if (EVP_DigestSignUpdate(mctx, hdata, hdatalen) <= 0
|| EVP_MD_CTX_ctrl(mctx, EVP_CTRL_SSL3_MASTER_SECRET,
(int)s->session->master_key_length,
s->session->master_key) <= 0
|| EVP_DigestSignFinal(mctx, NULL, &siglen) <= 0) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
goto err;
}
sig = OPENSSL_malloc(siglen);
if (sig == NULL
|| EVP_DigestSignFinal(mctx, sig, &siglen) <= 0) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
goto err;
}
} else {
/*
* Here we *must* use EVP_DigestSign() because Ed25519/Ed448 does not
* support streaming via EVP_DigestSignUpdate/EVP_DigestSignFinal
*/
if (EVP_DigestSign(mctx, NULL, &siglen, hdata, hdatalen) <= 0) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
goto err;
}
sig = OPENSSL_malloc(siglen);
if (sig == NULL
|| EVP_DigestSign(mctx, sig, &siglen, hdata, hdatalen) <= 0) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
goto err;
}
}
#ifndef OPENSSL_NO_GOST
{
int pktype = lu->sig;
if (pktype == NID_id_GostR3410_2001
|| pktype == NID_id_GostR3410_2012_256
|| pktype == NID_id_GostR3410_2012_512)
BUF_reverse(sig, NULL, siglen);
}
#endif
if (!WPACKET_sub_memcpy_u16(pkt, sig, siglen)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
goto err;
}
/* Digest cached records and discard handshake buffer */
if (!ssl3_digest_cached_records(s, 0)) {
/* SSLfatal() already called */
goto err;
}
OPENSSL_free(sig);
EVP_MD_CTX_free(mctx);
return 1;
err:
OPENSSL_free(sig);
EVP_MD_CTX_free(mctx);
return 0;
}
MSG_PROCESS_RETURN tls_process_cert_verify(SSL *s, PACKET *pkt)
{
EVP_PKEY *pkey = NULL;
const unsigned char *data;
#ifndef OPENSSL_NO_GOST
unsigned char *gost_data = NULL;
#endif
MSG_PROCESS_RETURN ret = MSG_PROCESS_ERROR;
int j;
unsigned int len;
X509 *peer;
const EVP_MD *md = NULL;
size_t hdatalen = 0;
void *hdata;
unsigned char tls13tbs[TLS13_TBS_PREAMBLE_SIZE + EVP_MAX_MD_SIZE];
EVP_MD_CTX *mctx = EVP_MD_CTX_new();
EVP_PKEY_CTX *pctx = NULL;
if (mctx == NULL) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_MALLOC_FAILURE);
goto err;
}
peer = s->session->peer;
pkey = X509_get0_pubkey(peer);
if (pkey == NULL) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
goto err;
}
if (ssl_cert_lookup_by_pkey(pkey, NULL) == NULL) {
SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
SSL_R_SIGNATURE_FOR_NON_SIGNING_CERTIFICATE);
goto err;
}
if (SSL_USE_SIGALGS(s)) {
unsigned int sigalg;
if (!PACKET_get_net_2(pkt, &sigalg)) {
SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_PACKET);
goto err;
}
if (tls12_check_peer_sigalg(s, sigalg, pkey) <= 0) {
/* SSLfatal() already called */
goto err;
}
} else if (!tls1_set_peer_legacy_sigalg(s, pkey)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR,
SSL_R_LEGACY_SIGALG_DISALLOWED_OR_UNSUPPORTED);
goto err;
}
if (!tls1_lookup_md(s->ctx, s->s3.tmp.peer_sigalg, &md)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
goto err;
}
if (SSL_USE_SIGALGS(s))
OSSL_TRACE1(TLS, "USING TLSv1.2 HASH %s\n",
md == NULL ? "n/a" : EVP_MD_get0_name(md));
/* Check for broken implementations of GOST ciphersuites */
/*
* If key is GOST and len is exactly 64 or 128, it is signature without
* length field (CryptoPro implementations at least till TLS 1.2)
*/
#ifndef OPENSSL_NO_GOST
if (!SSL_USE_SIGALGS(s)
&& ((PACKET_remaining(pkt) == 64
&& (EVP_PKEY_get_id(pkey) == NID_id_GostR3410_2001
|| EVP_PKEY_get_id(pkey) == NID_id_GostR3410_2012_256))
|| (PACKET_remaining(pkt) == 128
&& EVP_PKEY_get_id(pkey) == NID_id_GostR3410_2012_512))) {
len = PACKET_remaining(pkt);
} else
#endif
if (!PACKET_get_net_2(pkt, &len)) {
SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
goto err;
}
if (!PACKET_get_bytes(pkt, &data, len)) {
SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
goto err;
}
+ if (PACKET_remaining(pkt) != 0) {
+ SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
+ goto err;
+ }
if (!get_cert_verify_tbs_data(s, tls13tbs, &hdata, &hdatalen)) {
/* SSLfatal() already called */
goto err;
}
OSSL_TRACE1(TLS, "Using client verify alg %s\n",
md == NULL ? "n/a" : EVP_MD_get0_name(md));
if (EVP_DigestVerifyInit_ex(mctx, &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_EVP_LIB);
goto err;
}
#ifndef OPENSSL_NO_GOST
{
int pktype = EVP_PKEY_get_id(pkey);
if (pktype == NID_id_GostR3410_2001
|| pktype == NID_id_GostR3410_2012_256
|| pktype == NID_id_GostR3410_2012_512) {
if ((gost_data = OPENSSL_malloc(len)) == NULL) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_MALLOC_FAILURE);
goto err;
}
BUF_reverse(gost_data, data, len);
data = gost_data;
}
}
#endif
if (SSL_USE_PSS(s)) {
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;
}
}
if (s->version == SSL3_VERSION) {
if (EVP_DigestVerifyUpdate(mctx, hdata, hdatalen) <= 0
|| EVP_MD_CTX_ctrl(mctx, EVP_CTRL_SSL3_MASTER_SECRET,
(int)s->session->master_key_length,
s->session->master_key) <= 0) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
goto err;
}
if (EVP_DigestVerifyFinal(mctx, data, len) <= 0) {
SSLfatal(s, SSL_AD_DECRYPT_ERROR, SSL_R_BAD_SIGNATURE);
goto err;
}
} else {
j = EVP_DigestVerify(mctx, data, len, hdata, hdatalen);
if (j <= 0) {
SSLfatal(s, SSL_AD_DECRYPT_ERROR, SSL_R_BAD_SIGNATURE);
goto err;
}
}
/*
* In TLSv1.3 on the client side we make sure we prepare the client
* certificate after the CertVerify instead of when we get the
* CertificateRequest. This is because in TLSv1.3 the CertificateRequest
* comes *before* the Certificate message. In TLSv1.2 it comes after. We
* want to make sure that SSL_get1_peer_certificate() will return the actual
* server certificate from the client_cert_cb callback.
*/
if (!s->server && SSL_IS_TLS13(s) && s->s3.tmp.cert_req == 1)
ret = MSG_PROCESS_CONTINUE_PROCESSING;
else
ret = MSG_PROCESS_CONTINUE_READING;
err:
BIO_free(s->s3.handshake_buffer);
s->s3.handshake_buffer = NULL;
EVP_MD_CTX_free(mctx);
#ifndef OPENSSL_NO_GOST
OPENSSL_free(gost_data);
#endif
return ret;
}
int tls_construct_finished(SSL *s, WPACKET *pkt)
{
size_t finish_md_len;
const char *sender;
size_t slen;
/* This is a real handshake so make sure we clean it up at the end */
if (!s->server && s->post_handshake_auth != SSL_PHA_REQUESTED)
s->statem.cleanuphand = 1;
/*
* We only change the keys if we didn't already do this when we sent the
* client certificate
*/
if (SSL_IS_TLS13(s)
&& !s->server
&& s->s3.tmp.cert_req == 0
&& (!s->method->ssl3_enc->change_cipher_state(s,
SSL3_CC_HANDSHAKE | SSL3_CHANGE_CIPHER_CLIENT_WRITE))) {;
/* SSLfatal() already called */
return 0;
}
if (s->server) {
sender = s->method->ssl3_enc->server_finished_label;
slen = s->method->ssl3_enc->server_finished_label_len;
} else {
sender = s->method->ssl3_enc->client_finished_label;
slen = s->method->ssl3_enc->client_finished_label_len;
}
finish_md_len = s->method->ssl3_enc->final_finish_mac(s,
sender, slen,
s->s3.tmp.finish_md);
if (finish_md_len == 0) {
/* SSLfatal() already called */
return 0;
}
s->s3.tmp.finish_md_len = finish_md_len;
if (!WPACKET_memcpy(pkt, s->s3.tmp.finish_md, finish_md_len)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return 0;
}
/*
* Log the master secret, if logging is enabled. We don't log it for
* TLSv1.3: there's a different key schedule for that.
*/
if (!SSL_IS_TLS13(s) && !ssl_log_secret(s, MASTER_SECRET_LABEL,
s->session->master_key,
s->session->master_key_length)) {
/* SSLfatal() already called */
return 0;
}
/*
* Copy the finished so we can use it for renegotiation checks
*/
if (!ossl_assert(finish_md_len <= EVP_MAX_MD_SIZE)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return 0;
}
if (!s->server) {
memcpy(s->s3.previous_client_finished, s->s3.tmp.finish_md,
finish_md_len);
s->s3.previous_client_finished_len = finish_md_len;
} else {
memcpy(s->s3.previous_server_finished, s->s3.tmp.finish_md,
finish_md_len);
s->s3.previous_server_finished_len = finish_md_len;
}
return 1;
}
int tls_construct_key_update(SSL *s, WPACKET *pkt)
{
if (!WPACKET_put_bytes_u8(pkt, s->key_update)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return 0;
}
s->key_update = SSL_KEY_UPDATE_NONE;
return 1;
}
MSG_PROCESS_RETURN tls_process_key_update(SSL *s, PACKET *pkt)
{
unsigned int updatetype;
/*
* A KeyUpdate message 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;
}
if (!PACKET_get_1(pkt, &updatetype)
|| PACKET_remaining(pkt) != 0) {
SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_KEY_UPDATE);
return MSG_PROCESS_ERROR;
}
/*
* There are only two defined key update types. Fail if we get a value we
* didn't recognise.
*/
if (updatetype != SSL_KEY_UPDATE_NOT_REQUESTED
&& updatetype != SSL_KEY_UPDATE_REQUESTED) {
SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_BAD_KEY_UPDATE);
return MSG_PROCESS_ERROR;
}
/*
* If we get a request for us to update our sending keys too then, we need
* to additionally send a KeyUpdate message. However that message should
* not also request an update (otherwise we get into an infinite loop).
*/
if (updatetype == SSL_KEY_UPDATE_REQUESTED)
s->key_update = SSL_KEY_UPDATE_NOT_REQUESTED;
if (!tls13_update_key(s, 0)) {
/* SSLfatal() already called */
return MSG_PROCESS_ERROR;
}
return MSG_PROCESS_FINISHED_READING;
}
/*
* ssl3_take_mac calculates the Finished MAC for the handshakes messages seen
* to far.
*/
int ssl3_take_mac(SSL *s)
{
const char *sender;
size_t slen;
if (!s->server) {
sender = s->method->ssl3_enc->server_finished_label;
slen = s->method->ssl3_enc->server_finished_label_len;
} else {
sender = s->method->ssl3_enc->client_finished_label;
slen = s->method->ssl3_enc->client_finished_label_len;
}
s->s3.tmp.peer_finish_md_len =
s->method->ssl3_enc->final_finish_mac(s, sender, slen,
s->s3.tmp.peer_finish_md);
if (s->s3.tmp.peer_finish_md_len == 0) {
/* SSLfatal() already called */
return 0;
}
return 1;
}
MSG_PROCESS_RETURN tls_process_change_cipher_spec(SSL *s, PACKET *pkt)
{
size_t remain;
remain = PACKET_remaining(pkt);
/*
* 'Change Cipher Spec' is just a single byte, which should already have
* been consumed by ssl_get_message() so there should be no bytes left,
* unless we're using DTLS1_BAD_VER, which has an extra 2 bytes
*/
if (SSL_IS_DTLS(s)) {
if ((s->version == DTLS1_BAD_VER
&& remain != DTLS1_CCS_HEADER_LENGTH + 1)
|| (s->version != DTLS1_BAD_VER
&& remain != DTLS1_CCS_HEADER_LENGTH - 1)) {
SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_CHANGE_CIPHER_SPEC);
return MSG_PROCESS_ERROR;
}
} else {
if (remain != 0) {
SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_CHANGE_CIPHER_SPEC);
return MSG_PROCESS_ERROR;
}
}
/* Check we have a cipher to change to */
if (s->s3.tmp.new_cipher == NULL) {
SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_CCS_RECEIVED_EARLY);
return MSG_PROCESS_ERROR;
}
s->s3.change_cipher_spec = 1;
if (!ssl3_do_change_cipher_spec(s)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return MSG_PROCESS_ERROR;
}
if (SSL_IS_DTLS(s)) {
dtls1_reset_seq_numbers(s, SSL3_CC_READ);
if (s->version == DTLS1_BAD_VER)
s->d1->handshake_read_seq++;
#ifndef OPENSSL_NO_SCTP
/*
* Remember that a CCS has been received, so that an old key of
* SCTP-Auth can be deleted when a CCS is sent. Will be ignored if no
* SCTP is used
*/
BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_AUTH_CCS_RCVD, 1, NULL);
#endif
}
return MSG_PROCESS_CONTINUE_READING;
}
MSG_PROCESS_RETURN tls_process_finished(SSL *s, PACKET *pkt)
{
size_t md_len;
/* This is a real handshake so make sure we clean it up at the end */
if (s->server) {
/*
* 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 (s->post_handshake_auth != SSL_PHA_REQUESTED)
s->statem.cleanuphand = 1;
if (SSL_IS_TLS13(s) && !tls13_save_handshake_digest_for_pha(s)) {
/* SSLfatal() already called */
return MSG_PROCESS_ERROR;
}
}
/*
* In TLSv1.3 a Finished message signals a key change so the end of the
* message must be 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);
return MSG_PROCESS_ERROR;
}
/* If this occurs, we have missed a message */
if (!SSL_IS_TLS13(s) && !s->s3.change_cipher_spec) {
SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_GOT_A_FIN_BEFORE_A_CCS);
return MSG_PROCESS_ERROR;
}
s->s3.change_cipher_spec = 0;
md_len = s->s3.tmp.peer_finish_md_len;
if (md_len != PACKET_remaining(pkt)) {
SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_DIGEST_LENGTH);
return MSG_PROCESS_ERROR;
}
if (CRYPTO_memcmp(PACKET_data(pkt), s->s3.tmp.peer_finish_md,
md_len) != 0) {
SSLfatal(s, SSL_AD_DECRYPT_ERROR, SSL_R_DIGEST_CHECK_FAILED);
return MSG_PROCESS_ERROR;
}
/*
* Copy the finished so we can use it for renegotiation checks
*/
if (!ossl_assert(md_len <= EVP_MAX_MD_SIZE)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return MSG_PROCESS_ERROR;
}
if (s->server) {
memcpy(s->s3.previous_client_finished, s->s3.tmp.peer_finish_md,
md_len);
s->s3.previous_client_finished_len = md_len;
} else {
memcpy(s->s3.previous_server_finished, s->s3.tmp.peer_finish_md,
md_len);
s->s3.previous_server_finished_len = md_len;
}
/*
* In TLS1.3 we also have to change cipher state and do any final processing
* of the initial server flight (if we are a client)
*/
if (SSL_IS_TLS13(s)) {
if (s->server) {
if (s->post_handshake_auth != SSL_PHA_REQUESTED &&
!s->method->ssl3_enc->change_cipher_state(s,
SSL3_CC_APPLICATION | SSL3_CHANGE_CIPHER_SERVER_READ)) {
/* SSLfatal() already called */
return MSG_PROCESS_ERROR;
}
} else {
/* 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)) {
/* SSLfatal() already called */
return MSG_PROCESS_ERROR;
}
if (!s->method->ssl3_enc->change_cipher_state(s,
SSL3_CC_APPLICATION | SSL3_CHANGE_CIPHER_CLIENT_READ)) {
/* SSLfatal() already called */
return MSG_PROCESS_ERROR;
}
if (!tls_process_initial_server_flight(s)) {
/* SSLfatal() already called */
return MSG_PROCESS_ERROR;
}
}
}
return MSG_PROCESS_FINISHED_READING;
}
int tls_construct_change_cipher_spec(SSL *s, WPACKET *pkt)
{
if (!WPACKET_put_bytes_u8(pkt, SSL3_MT_CCS)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return 0;
}
return 1;
}
/* Add a certificate to the WPACKET */
static int ssl_add_cert_to_wpacket(SSL *s, WPACKET *pkt, X509 *x, int chain)
{
int len;
unsigned char *outbytes;
len = i2d_X509(x, NULL);
if (len < 0) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_BUF_LIB);
return 0;
}
if (!WPACKET_sub_allocate_bytes_u24(pkt, len, &outbytes)
|| i2d_X509(x, &outbytes) != len) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return 0;
}
if (SSL_IS_TLS13(s)
&& !tls_construct_extensions(s, pkt, SSL_EXT_TLS1_3_CERTIFICATE, x,
chain)) {
/* SSLfatal() already called */
return 0;
}
return 1;
}
/* Add certificate chain to provided WPACKET */
static int ssl_add_cert_chain(SSL *s, WPACKET *pkt, CERT_PKEY *cpk)
{
int i, chain_count;
X509 *x;
STACK_OF(X509) *extra_certs;
STACK_OF(X509) *chain = NULL;
X509_STORE *chain_store;
if (cpk == NULL || cpk->x509 == NULL)
return 1;
x = cpk->x509;
/*
* If we have a certificate specific chain use it, else use parent ctx.
*/
if (cpk->chain != NULL)
extra_certs = cpk->chain;
else
extra_certs = s->ctx->extra_certs;
if ((s->mode & SSL_MODE_NO_AUTO_CHAIN) || extra_certs)
chain_store = NULL;
else if (s->cert->chain_store)
chain_store = s->cert->chain_store;
else
chain_store = s->ctx->cert_store;
if (chain_store != NULL) {
X509_STORE_CTX *xs_ctx = X509_STORE_CTX_new_ex(s->ctx->libctx,
s->ctx->propq);
if (xs_ctx == NULL) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_MALLOC_FAILURE);
return 0;
}
if (!X509_STORE_CTX_init(xs_ctx, chain_store, x, NULL)) {
X509_STORE_CTX_free(xs_ctx);
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_X509_LIB);
return 0;
}
/*
* It is valid for the chain not to be complete (because normally we
* don't include the root cert in the chain). Therefore we deliberately
* ignore the error return from this call. We're not actually verifying
* the cert - we're just building as much of the chain as we can
*/
(void)X509_verify_cert(xs_ctx);
/* Don't leave errors in the queue */
ERR_clear_error();
chain = X509_STORE_CTX_get0_chain(xs_ctx);
i = ssl_security_cert_chain(s, chain, NULL, 0);
if (i != 1) {
#if 0
/* Dummy error calls so mkerr generates them */
ERR_raise(ERR_LIB_SSL, SSL_R_EE_KEY_TOO_SMALL);
ERR_raise(ERR_LIB_SSL, SSL_R_CA_KEY_TOO_SMALL);
ERR_raise(ERR_LIB_SSL, SSL_R_CA_MD_TOO_WEAK);
#endif
X509_STORE_CTX_free(xs_ctx);
SSLfatal(s, SSL_AD_INTERNAL_ERROR, i);
return 0;
}
chain_count = sk_X509_num(chain);
for (i = 0; i < chain_count; i++) {
x = sk_X509_value(chain, i);
if (!ssl_add_cert_to_wpacket(s, pkt, x, i)) {
/* SSLfatal() already called */
X509_STORE_CTX_free(xs_ctx);
return 0;
}
}
X509_STORE_CTX_free(xs_ctx);
} else {
i = ssl_security_cert_chain(s, extra_certs, x, 0);
if (i != 1) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, i);
return 0;
}
if (!ssl_add_cert_to_wpacket(s, pkt, x, 0)) {
/* SSLfatal() already called */
return 0;
}
for (i = 0; i < sk_X509_num(extra_certs); i++) {
x = sk_X509_value(extra_certs, i);
if (!ssl_add_cert_to_wpacket(s, pkt, x, i + 1)) {
/* SSLfatal() already called */
return 0;
}
}
}
return 1;
}
unsigned long ssl3_output_cert_chain(SSL *s, WPACKET *pkt, CERT_PKEY *cpk)
{
if (!WPACKET_start_sub_packet_u24(pkt)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return 0;
}
if (!ssl_add_cert_chain(s, pkt, cpk))
return 0;
if (!WPACKET_close(pkt)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return 0;
}
return 1;
}
/*
* Tidy up after the end of a handshake. In the case of SCTP this may result
* in NBIO events. If |clearbufs| is set then init_buf and the wbio buffer is
* freed up as well.
*/
WORK_STATE tls_finish_handshake(SSL *s, ossl_unused WORK_STATE wst,
int clearbufs, int stop)
{
void (*cb) (const SSL *ssl, int type, int val) = NULL;
int cleanuphand = s->statem.cleanuphand;
if (clearbufs) {
if (!SSL_IS_DTLS(s)
#ifndef OPENSSL_NO_SCTP
/*
* RFC6083: SCTP provides a reliable and in-sequence transport service for DTLS
* messages that require it. Therefore, DTLS procedures for retransmissions
* MUST NOT be used.
* Hence the init_buf can be cleared when DTLS over SCTP as transport is used.
*/
|| BIO_dgram_is_sctp(SSL_get_wbio(s))
#endif
) {
/*
* We don't do this in DTLS over UDP because we may still need the init_buf
* in case there are any unexpected retransmits
*/
BUF_MEM_free(s->init_buf);
s->init_buf = NULL;
}
if (!ssl_free_wbio_buffer(s)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return WORK_ERROR;
}
s->init_num = 0;
}
if (SSL_IS_TLS13(s) && !s->server
&& s->post_handshake_auth == SSL_PHA_REQUESTED)
s->post_handshake_auth = SSL_PHA_EXT_SENT;
/*
* Only set if there was a Finished message and this isn't after a TLSv1.3
* post handshake exchange
*/
if (cleanuphand) {
/* skipped if we just sent a HelloRequest */
s->renegotiate = 0;
s->new_session = 0;
s->statem.cleanuphand = 0;
s->ext.ticket_expected = 0;
ssl3_cleanup_key_block(s);
if (s->server) {
/*
* In TLSv1.3 we update the cache as part of constructing the
* NewSessionTicket
*/
if (!SSL_IS_TLS13(s))
ssl_update_cache(s, SSL_SESS_CACHE_SERVER);
/* N.B. s->ctx may not equal s->session_ctx */
ssl_tsan_counter(s->ctx, &s->ctx->stats.sess_accept_good);
s->handshake_func = ossl_statem_accept;
} else {
if (SSL_IS_TLS13(s)) {
/*
* We encourage applications to only use TLSv1.3 tickets once,
* so we remove this one from the cache.
*/
if ((s->session_ctx->session_cache_mode
& SSL_SESS_CACHE_CLIENT) != 0)
SSL_CTX_remove_session(s->session_ctx, s->session);
} else {
/*
* In TLSv1.3 we update the cache as part of processing the
* NewSessionTicket
*/
ssl_update_cache(s, SSL_SESS_CACHE_CLIENT);
}
if (s->hit)
ssl_tsan_counter(s->session_ctx,
&s->session_ctx->stats.sess_hit);
s->handshake_func = ossl_statem_connect;
ssl_tsan_counter(s->session_ctx,
&s->session_ctx->stats.sess_connect_good);
}
if (SSL_IS_DTLS(s)) {
/* done with handshaking */
s->d1->handshake_read_seq = 0;
s->d1->handshake_write_seq = 0;
s->d1->next_handshake_write_seq = 0;
dtls1_clear_received_buffer(s);
}
}
if (s->info_callback != NULL)
cb = s->info_callback;
else if (s->ctx->info_callback != NULL)
cb = s->ctx->info_callback;
/* The callback may expect us to not be in init at handshake done */
ossl_statem_set_in_init(s, 0);
if (cb != NULL) {
if (cleanuphand
|| !SSL_IS_TLS13(s)
|| SSL_IS_FIRST_HANDSHAKE(s))
cb(s, SSL_CB_HANDSHAKE_DONE, 1);
}
if (!stop) {
/* If we've got more work to do we go back into init */
ossl_statem_set_in_init(s, 1);
return WORK_FINISHED_CONTINUE;
}
return WORK_FINISHED_STOP;
}
int tls_get_message_header(SSL *s, int *mt)
{
/* s->init_num < SSL3_HM_HEADER_LENGTH */
int skip_message, i, recvd_type;
unsigned char *p;
size_t l, readbytes;
p = (unsigned char *)s->init_buf->data;
do {
while (s->init_num < SSL3_HM_HEADER_LENGTH) {
i = s->method->ssl_read_bytes(s, SSL3_RT_HANDSHAKE, &recvd_type,
&p[s->init_num],
SSL3_HM_HEADER_LENGTH - s->init_num,
0, &readbytes);
if (i <= 0) {
s->rwstate = SSL_READING;
return 0;
}
if (recvd_type == SSL3_RT_CHANGE_CIPHER_SPEC) {
/*
* A ChangeCipherSpec must be a single byte and may not occur
* in the middle of a handshake message.
*/
if (s->init_num != 0 || readbytes != 1 || p[0] != SSL3_MT_CCS) {
SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
SSL_R_BAD_CHANGE_CIPHER_SPEC);
return 0;
}
if (s->statem.hand_state == TLS_ST_BEFORE
&& (s->s3.flags & TLS1_FLAGS_STATELESS) != 0) {
/*
* We are stateless and we received a CCS. Probably this is
* from a client between the first and second ClientHellos.
* We should ignore this, but return an error because we do
* not return success until we see the second ClientHello
* with a valid cookie.
*/
return 0;
}
s->s3.tmp.message_type = *mt = SSL3_MT_CHANGE_CIPHER_SPEC;
s->init_num = readbytes - 1;
s->init_msg = s->init_buf->data;
s->s3.tmp.message_size = readbytes;
return 1;
} else if (recvd_type != SSL3_RT_HANDSHAKE) {
SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
SSL_R_CCS_RECEIVED_EARLY);
return 0;
}
s->init_num += readbytes;
}
skip_message = 0;
if (!s->server)
if (s->statem.hand_state != TLS_ST_OK
&& p[0] == SSL3_MT_HELLO_REQUEST)
/*
* The server may always send 'Hello Request' messages --
* we are doing a handshake anyway now, so ignore them if
* their format is correct. Does not count for 'Finished'
* MAC.
*/
if (p[1] == 0 && p[2] == 0 && p[3] == 0) {
s->init_num = 0;
skip_message = 1;
if (s->msg_callback)
s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE,
p, SSL3_HM_HEADER_LENGTH, s,
s->msg_callback_arg);
}
} while (skip_message);
/* s->init_num == SSL3_HM_HEADER_LENGTH */
*mt = *p;
s->s3.tmp.message_type = *(p++);
if (RECORD_LAYER_is_sslv2_record(&s->rlayer)) {
/*
* Only happens with SSLv3+ in an SSLv2 backward compatible
* ClientHello
*
* Total message size is the remaining record bytes to read
* plus the SSL3_HM_HEADER_LENGTH bytes that we already read
*/
l = RECORD_LAYER_get_rrec_length(&s->rlayer)
+ SSL3_HM_HEADER_LENGTH;
s->s3.tmp.message_size = l;
s->init_msg = s->init_buf->data;
s->init_num = SSL3_HM_HEADER_LENGTH;
} else {
n2l3(p, l);
/* BUF_MEM_grow takes an 'int' parameter */
if (l > (INT_MAX - SSL3_HM_HEADER_LENGTH)) {
SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
SSL_R_EXCESSIVE_MESSAGE_SIZE);
return 0;
}
s->s3.tmp.message_size = l;
s->init_msg = s->init_buf->data + SSL3_HM_HEADER_LENGTH;
s->init_num = 0;
}
return 1;
}
int tls_get_message_body(SSL *s, size_t *len)
{
size_t n, readbytes;
unsigned char *p;
int i;
if (s->s3.tmp.message_type == SSL3_MT_CHANGE_CIPHER_SPEC) {
/* We've already read everything in */
*len = (unsigned long)s->init_num;
return 1;
}
p = s->init_msg;
n = s->s3.tmp.message_size - s->init_num;
while (n > 0) {
i = s->method->ssl_read_bytes(s, SSL3_RT_HANDSHAKE, NULL,
&p[s->init_num], n, 0, &readbytes);
if (i <= 0) {
s->rwstate = SSL_READING;
*len = 0;
return 0;
}
s->init_num += readbytes;
n -= readbytes;
}
/*
* If receiving Finished, record MAC of prior handshake messages for
* Finished verification.
*/
if (*(s->init_buf->data) == SSL3_MT_FINISHED && !ssl3_take_mac(s)) {
/* SSLfatal() already called */
*len = 0;
return 0;
}
/* Feed this message into MAC computation. */
if (RECORD_LAYER_is_sslv2_record(&s->rlayer)) {
if (!ssl3_finish_mac(s, (unsigned char *)s->init_buf->data,
s->init_num)) {
/* SSLfatal() already called */
*len = 0;
return 0;
}
if (s->msg_callback)
s->msg_callback(0, SSL2_VERSION, 0, s->init_buf->data,
(size_t)s->init_num, s, s->msg_callback_arg);
} else {
/*
* We defer feeding in the HRR until later. We'll do it as part of
* processing the message
* The TLsv1.3 handshake transcript stops at the ClientFinished
* message.
*/
#define SERVER_HELLO_RANDOM_OFFSET (SSL3_HM_HEADER_LENGTH + 2)
/* KeyUpdate and NewSessionTicket do not need to be added */
if (!SSL_IS_TLS13(s) || (s->s3.tmp.message_type != SSL3_MT_NEWSESSION_TICKET
&& s->s3.tmp.message_type != SSL3_MT_KEY_UPDATE)) {
if (s->s3.tmp.message_type != SSL3_MT_SERVER_HELLO
|| s->init_num < SERVER_HELLO_RANDOM_OFFSET + SSL3_RANDOM_SIZE
|| memcmp(hrrrandom,
s->init_buf->data + SERVER_HELLO_RANDOM_OFFSET,
SSL3_RANDOM_SIZE) != 0) {
if (!ssl3_finish_mac(s, (unsigned char *)s->init_buf->data,
s->init_num + SSL3_HM_HEADER_LENGTH)) {
/* SSLfatal() already called */
*len = 0;
return 0;
}
}
}
if (s->msg_callback)
s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE, s->init_buf->data,
(size_t)s->init_num + SSL3_HM_HEADER_LENGTH, s,
s->msg_callback_arg);
}
*len = s->init_num;
return 1;
}
static const X509ERR2ALERT x509table[] = {
{X509_V_ERR_APPLICATION_VERIFICATION, SSL_AD_HANDSHAKE_FAILURE},
{X509_V_ERR_CA_KEY_TOO_SMALL, SSL_AD_BAD_CERTIFICATE},
{X509_V_ERR_EC_KEY_EXPLICIT_PARAMS, SSL_AD_BAD_CERTIFICATE},
{X509_V_ERR_CA_MD_TOO_WEAK, SSL_AD_BAD_CERTIFICATE},
{X509_V_ERR_CERT_CHAIN_TOO_LONG, SSL_AD_UNKNOWN_CA},
{X509_V_ERR_CERT_HAS_EXPIRED, SSL_AD_CERTIFICATE_EXPIRED},
{X509_V_ERR_CERT_NOT_YET_VALID, SSL_AD_BAD_CERTIFICATE},
{X509_V_ERR_CERT_REJECTED, SSL_AD_BAD_CERTIFICATE},
{X509_V_ERR_CERT_REVOKED, SSL_AD_CERTIFICATE_REVOKED},
{X509_V_ERR_CERT_SIGNATURE_FAILURE, SSL_AD_DECRYPT_ERROR},
{X509_V_ERR_CERT_UNTRUSTED, SSL_AD_BAD_CERTIFICATE},
{X509_V_ERR_CRL_HAS_EXPIRED, SSL_AD_CERTIFICATE_EXPIRED},
{X509_V_ERR_CRL_NOT_YET_VALID, SSL_AD_BAD_CERTIFICATE},
{X509_V_ERR_CRL_SIGNATURE_FAILURE, SSL_AD_DECRYPT_ERROR},
{X509_V_ERR_DANE_NO_MATCH, SSL_AD_BAD_CERTIFICATE},
{X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT, SSL_AD_UNKNOWN_CA},
{X509_V_ERR_EE_KEY_TOO_SMALL, SSL_AD_BAD_CERTIFICATE},
{X509_V_ERR_EMAIL_MISMATCH, SSL_AD_BAD_CERTIFICATE},
{X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD, SSL_AD_BAD_CERTIFICATE},
{X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD, SSL_AD_BAD_CERTIFICATE},
{X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD, SSL_AD_BAD_CERTIFICATE},
{X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD, SSL_AD_BAD_CERTIFICATE},
{X509_V_ERR_HOSTNAME_MISMATCH, SSL_AD_BAD_CERTIFICATE},
{X509_V_ERR_INVALID_CA, SSL_AD_UNKNOWN_CA},
{X509_V_ERR_INVALID_CALL, SSL_AD_INTERNAL_ERROR},
{X509_V_ERR_INVALID_PURPOSE, SSL_AD_UNSUPPORTED_CERTIFICATE},
{X509_V_ERR_IP_ADDRESS_MISMATCH, SSL_AD_BAD_CERTIFICATE},
{X509_V_ERR_OUT_OF_MEM, SSL_AD_INTERNAL_ERROR},
{X509_V_ERR_PATH_LENGTH_EXCEEDED, SSL_AD_UNKNOWN_CA},
{X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN, SSL_AD_UNKNOWN_CA},
{X509_V_ERR_STORE_LOOKUP, SSL_AD_INTERNAL_ERROR},
{X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY, SSL_AD_BAD_CERTIFICATE},
{X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE, SSL_AD_BAD_CERTIFICATE},
{X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE, SSL_AD_BAD_CERTIFICATE},
{X509_V_ERR_UNABLE_TO_GET_CRL, SSL_AD_UNKNOWN_CA},
{X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER, SSL_AD_UNKNOWN_CA},
{X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT, SSL_AD_UNKNOWN_CA},
{X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY, SSL_AD_UNKNOWN_CA},
{X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE, SSL_AD_UNKNOWN_CA},
{X509_V_ERR_UNSPECIFIED, SSL_AD_INTERNAL_ERROR},
/* Last entry; return this if we don't find the value above. */
{X509_V_OK, SSL_AD_CERTIFICATE_UNKNOWN}
};
int ssl_x509err2alert(int x509err)
{
const X509ERR2ALERT *tp;
for (tp = x509table; tp->x509err != X509_V_OK; ++tp)
if (tp->x509err == x509err)
break;
return tp->alert;
}
int ssl_allow_compression(SSL *s)
{
if (s->options & SSL_OP_NO_COMPRESSION)
return 0;
return ssl_security(s, SSL_SECOP_COMPRESSION, 0, 0, NULL);
}
static int version_cmp(const SSL *s, int a, int b)
{
int dtls = SSL_IS_DTLS(s);
if (a == b)
return 0;
if (!dtls)
return a < b ? -1 : 1;
return DTLS_VERSION_LT(a, b) ? -1 : 1;
}
typedef struct {
int version;
const SSL_METHOD *(*cmeth) (void);
const SSL_METHOD *(*smeth) (void);
} version_info;
#if TLS_MAX_VERSION_INTERNAL != TLS1_3_VERSION
# error Code needs update for TLS_method() support beyond TLS1_3_VERSION.
#endif
/* Must be in order high to low */
static const version_info tls_version_table[] = {
#ifndef OPENSSL_NO_TLS1_3
{TLS1_3_VERSION, tlsv1_3_client_method, tlsv1_3_server_method},
#else
{TLS1_3_VERSION, NULL, NULL},
#endif
#ifndef OPENSSL_NO_TLS1_2
{TLS1_2_VERSION, tlsv1_2_client_method, tlsv1_2_server_method},
#else
{TLS1_2_VERSION, NULL, NULL},
#endif
#ifndef OPENSSL_NO_TLS1_1
{TLS1_1_VERSION, tlsv1_1_client_method, tlsv1_1_server_method},
#else
{TLS1_1_VERSION, NULL, NULL},
#endif
#ifndef OPENSSL_NO_TLS1
{TLS1_VERSION, tlsv1_client_method, tlsv1_server_method},
#else
{TLS1_VERSION, NULL, NULL},
#endif
#ifndef OPENSSL_NO_SSL3
{SSL3_VERSION, sslv3_client_method, sslv3_server_method},
#else
{SSL3_VERSION, NULL, NULL},
#endif
{0, NULL, NULL},
};
#if DTLS_MAX_VERSION_INTERNAL != DTLS1_2_VERSION
# error Code needs update for DTLS_method() support beyond DTLS1_2_VERSION.
#endif
/* Must be in order high to low */
static const version_info dtls_version_table[] = {
#ifndef OPENSSL_NO_DTLS1_2
{DTLS1_2_VERSION, dtlsv1_2_client_method, dtlsv1_2_server_method},
#else
{DTLS1_2_VERSION, NULL, NULL},
#endif
#ifndef OPENSSL_NO_DTLS1
{DTLS1_VERSION, dtlsv1_client_method, dtlsv1_server_method},
{DTLS1_BAD_VER, dtls_bad_ver_client_method, NULL},
#else
{DTLS1_VERSION, NULL, NULL},
{DTLS1_BAD_VER, NULL, NULL},
#endif
{0, NULL, NULL},
};
/*
* ssl_method_error - Check whether an SSL_METHOD is enabled.
*
* @s: The SSL handle for the candidate method
* @method: the intended method.
*
* Returns 0 on success, or an SSL error reason on failure.
*/
static int ssl_method_error(const SSL *s, const SSL_METHOD *method)
{
int version = method->version;
if ((s->min_proto_version != 0 &&
version_cmp(s, version, s->min_proto_version) < 0) ||
ssl_security(s, SSL_SECOP_VERSION, 0, version, NULL) == 0)
return SSL_R_VERSION_TOO_LOW;
if (s->max_proto_version != 0 &&
version_cmp(s, version, s->max_proto_version) > 0)
return SSL_R_VERSION_TOO_HIGH;
if ((s->options & method->mask) != 0)
return SSL_R_UNSUPPORTED_PROTOCOL;
if ((method->flags & SSL_METHOD_NO_SUITEB) != 0 && tls1_suiteb(s))
return SSL_R_AT_LEAST_TLS_1_2_NEEDED_IN_SUITEB_MODE;
return 0;
}
/*
* Only called by servers. Returns 1 if the server has a TLSv1.3 capable
* certificate type, or has PSK or a certificate callback configured, or has
* a servername callback configure. Otherwise returns 0.
*/
static int is_tls13_capable(const SSL *s)
{
int i;
int curve;
if (!ossl_assert(s->ctx != NULL) || !ossl_assert(s->session_ctx != NULL))
return 0;
/*
* A servername callback can change the available certs, so if a servername
* cb is set then we just assume TLSv1.3 will be ok
*/
if (s->ctx->ext.servername_cb != NULL
|| s->session_ctx->ext.servername_cb != NULL)
return 1;
#ifndef OPENSSL_NO_PSK
if (s->psk_server_callback != NULL)
return 1;
#endif
if (s->psk_find_session_cb != NULL || s->cert->cert_cb != NULL)
return 1;
for (i = 0; i < SSL_PKEY_NUM; i++) {
/* Skip over certs disallowed for TLSv1.3 */
switch (i) {
case SSL_PKEY_DSA_SIGN:
case SSL_PKEY_GOST01:
case SSL_PKEY_GOST12_256:
case SSL_PKEY_GOST12_512:
continue;
default:
break;
}
if (!ssl_has_cert(s, i))
continue;
if (i != SSL_PKEY_ECC)
return 1;
/*
* Prior to TLSv1.3 sig algs allowed any curve to be used. TLSv1.3 is
* more restrictive so check that our sig algs are consistent with this
* EC cert. See section 4.2.3 of RFC8446.
*/
curve = ssl_get_EC_curve_nid(s->cert->pkeys[SSL_PKEY_ECC].privatekey);
if (tls_check_sigalg_curve(s, curve))
return 1;
}
return 0;
}
/*
* ssl_version_supported - Check that the specified `version` is supported by
* `SSL *` instance
*
* @s: The SSL handle for the candidate method
* @version: Protocol version to test against
*
* Returns 1 when supported, otherwise 0
*/
int ssl_version_supported(const SSL *s, int version, const SSL_METHOD **meth)
{
const version_info *vent;
const version_info *table;
switch (s->method->version) {
default:
/* Version should match method version for non-ANY method */
return version_cmp(s, version, s->version) == 0;
case TLS_ANY_VERSION:
table = tls_version_table;
break;
case DTLS_ANY_VERSION:
table = dtls_version_table;
break;
}
for (vent = table;
vent->version != 0 && version_cmp(s, version, vent->version) <= 0;
++vent) {
if (vent->cmeth != NULL
&& version_cmp(s, version, vent->version) == 0
&& ssl_method_error(s, vent->cmeth()) == 0
&& (!s->server
|| version != TLS1_3_VERSION
|| is_tls13_capable(s))) {
if (meth != NULL)
*meth = vent->cmeth();
return 1;
}
}
return 0;
}
/*
* ssl_check_version_downgrade - In response to RFC7507 SCSV version
* fallback indication from a client check whether we're using the highest
* supported protocol version.
*
* @s server SSL handle.
*
* Returns 1 when using the highest enabled version, 0 otherwise.
*/
int ssl_check_version_downgrade(SSL *s)
{
const version_info *vent;
const version_info *table;
/*
* Check that the current protocol is the highest enabled version
* (according to s->ctx->method, as version negotiation may have changed
* s->method).
*/
if (s->version == s->ctx->method->version)
return 1;
/*
* Apparently we're using a version-flexible SSL_METHOD (not at its
* highest protocol version).
*/
if (s->ctx->method->version == TLS_method()->version)
table = tls_version_table;
else if (s->ctx->method->version == DTLS_method()->version)
table = dtls_version_table;
else {
/* Unexpected state; fail closed. */
return 0;
}
for (vent = table; vent->version != 0; ++vent) {
if (vent->smeth != NULL && ssl_method_error(s, vent->smeth()) == 0)
return s->version == vent->version;
}
return 0;
}
/*
* ssl_set_version_bound - set an upper or lower bound on the supported (D)TLS
* protocols, provided the initial (D)TLS method is version-flexible. This
* function sanity-checks the proposed value and makes sure the method is
* version-flexible, then sets the limit if all is well.
*
* @method_version: The version of the current SSL_METHOD.
* @version: the intended limit.
* @bound: pointer to limit to be updated.
*
* Returns 1 on success, 0 on failure.
*/
int ssl_set_version_bound(int method_version, int version, int *bound)
{
int valid_tls;
int valid_dtls;
if (version == 0) {
*bound = version;
return 1;
}
valid_tls = version >= SSL3_VERSION && version <= TLS_MAX_VERSION_INTERNAL;
valid_dtls =
DTLS_VERSION_LE(version, DTLS_MAX_VERSION_INTERNAL) &&
DTLS_VERSION_GE(version, DTLS1_BAD_VER);
if (!valid_tls && !valid_dtls)
return 0;
/*-
* Restrict TLS methods to TLS protocol versions.
* Restrict DTLS methods to DTLS protocol versions.
* Note, DTLS version numbers are decreasing, use comparison macros.
*
* Note that for both lower-bounds we use explicit versions, not
* (D)TLS_MIN_VERSION. This is because we don't want to break user
* configurations. If the MIN (supported) version ever rises, the user's
* "floor" remains valid even if no longer available. We don't expect the
* MAX ceiling to ever get lower, so making that variable makes sense.
*
* We ignore attempts to set bounds on version-inflexible methods,
* returning success.
*/
switch (method_version) {
default:
break;
case TLS_ANY_VERSION:
if (valid_tls)
*bound = version;
break;
case DTLS_ANY_VERSION:
if (valid_dtls)
*bound = version;
break;
}
return 1;
}
static void check_for_downgrade(SSL *s, int vers, DOWNGRADE *dgrd)
{
if (vers == TLS1_2_VERSION
&& ssl_version_supported(s, TLS1_3_VERSION, NULL)) {
*dgrd = DOWNGRADE_TO_1_2;
} else if (!SSL_IS_DTLS(s)
&& vers < TLS1_2_VERSION
/*
* We need to ensure that a server that disables TLSv1.2
* (creating a hole between TLSv1.3 and TLSv1.1) can still
* complete handshakes with clients that support TLSv1.2 and
* below. Therefore we do not enable the sentinel if TLSv1.3 is
* enabled and TLSv1.2 is not.
*/
&& ssl_version_supported(s, TLS1_2_VERSION, NULL)) {
*dgrd = DOWNGRADE_TO_1_1;
} else {
*dgrd = DOWNGRADE_NONE;
}
}
/*
* ssl_choose_server_version - Choose server (D)TLS version. Called when the
* client HELLO is received to select the final server protocol version and
* the version specific method.
*
* @s: server SSL handle.
*
* Returns 0 on success or an SSL error reason number on failure.
*/
int ssl_choose_server_version(SSL *s, CLIENTHELLO_MSG *hello, DOWNGRADE *dgrd)
{
/*-
* With version-flexible methods we have an initial state with:
*
* s->method->version == (D)TLS_ANY_VERSION,
* s->version == (D)TLS_MAX_VERSION_INTERNAL.
*
* So we detect version-flexible methods via the method version, not the
* handle version.
*/
int server_version = s->method->version;
int client_version = hello->legacy_version;
const version_info *vent;
const version_info *table;
int disabled = 0;
RAW_EXTENSION *suppversions;
s->client_version = client_version;
switch (server_version) {
default:
if (!SSL_IS_TLS13(s)) {
if (version_cmp(s, client_version, s->version) < 0)
return SSL_R_WRONG_SSL_VERSION;
*dgrd = DOWNGRADE_NONE;
/*
* If this SSL handle is not from a version flexible method we don't
* (and never did) check min/max FIPS or Suite B constraints. Hope
* that's OK. It is up to the caller to not choose fixed protocol
* versions they don't want. If not, then easy to fix, just return
* ssl_method_error(s, s->method)
*/
return 0;
}
/*
* Fall through if we are TLSv1.3 already (this means we must be after
* a HelloRetryRequest
*/
/* fall thru */
case TLS_ANY_VERSION:
table = tls_version_table;
break;
case DTLS_ANY_VERSION:
table = dtls_version_table;
break;
}
suppversions = &hello->pre_proc_exts[TLSEXT_IDX_supported_versions];
/* If we did an HRR then supported versions is mandatory */
if (!suppversions->present && s->hello_retry_request != SSL_HRR_NONE)
return SSL_R_UNSUPPORTED_PROTOCOL;
if (suppversions->present && !SSL_IS_DTLS(s)) {
unsigned int candidate_vers = 0;
unsigned int best_vers = 0;
const SSL_METHOD *best_method = NULL;
PACKET versionslist;
suppversions->parsed = 1;
if (!PACKET_as_length_prefixed_1(&suppversions->data, &versionslist)) {
/* Trailing or invalid data? */
return SSL_R_LENGTH_MISMATCH;
}
/*
* The TLSv1.3 spec says the client MUST set this to TLS1_2_VERSION.
* The spec only requires servers to check that it isn't SSLv3:
* "Any endpoint receiving a Hello message with
* ClientHello.legacy_version or ServerHello.legacy_version set to
* 0x0300 MUST abort the handshake with a "protocol_version" alert."
* We are slightly stricter and require that it isn't SSLv3 or lower.
* We tolerate TLSv1 and TLSv1.1.
*/
if (client_version <= SSL3_VERSION)
return SSL_R_BAD_LEGACY_VERSION;
while (PACKET_get_net_2(&versionslist, &candidate_vers)) {
if (version_cmp(s, candidate_vers, best_vers) <= 0)
continue;
if (ssl_version_supported(s, candidate_vers, &best_method))
best_vers = candidate_vers;
}
if (PACKET_remaining(&versionslist) != 0) {
/* Trailing data? */
return SSL_R_LENGTH_MISMATCH;
}
if (best_vers > 0) {
if (s->hello_retry_request != SSL_HRR_NONE) {
/*
* This is after a HelloRetryRequest so we better check that we
* negotiated TLSv1.3
*/
if (best_vers != TLS1_3_VERSION)
return SSL_R_UNSUPPORTED_PROTOCOL;
return 0;
}
check_for_downgrade(s, best_vers, dgrd);
s->version = best_vers;
s->method = best_method;
return 0;
}
return SSL_R_UNSUPPORTED_PROTOCOL;
}
/*
* If the supported versions extension isn't present, then the highest
* version we can negotiate is TLSv1.2
*/
if (version_cmp(s, client_version, TLS1_3_VERSION) >= 0)
client_version = TLS1_2_VERSION;
/*
* No supported versions extension, so we just use the version supplied in
* the ClientHello.
*/
for (vent = table; vent->version != 0; ++vent) {
const SSL_METHOD *method;
if (vent->smeth == NULL ||
version_cmp(s, client_version, vent->version) < 0)
continue;
method = vent->smeth();
if (ssl_method_error(s, method) == 0) {
check_for_downgrade(s, vent->version, dgrd);
s->version = vent->version;
s->method = method;
return 0;
}
disabled = 1;
}
return disabled ? SSL_R_UNSUPPORTED_PROTOCOL : SSL_R_VERSION_TOO_LOW;
}
/*
* ssl_choose_client_version - Choose client (D)TLS version. Called when the
* server HELLO is received to select the final client protocol version and
* the version specific method.
*
* @s: client SSL handle.
* @version: The proposed version from the server's HELLO.
* @extensions: The extensions received
*
* Returns 1 on success or 0 on error.
*/
int ssl_choose_client_version(SSL *s, int version, RAW_EXTENSION *extensions)
{
const version_info *vent;
const version_info *table;
int ret, ver_min, ver_max, real_max, origv;
origv = s->version;
s->version = version;
/* This will overwrite s->version if the extension is present */
if (!tls_parse_extension(s, TLSEXT_IDX_supported_versions,
SSL_EXT_TLS1_2_SERVER_HELLO
| SSL_EXT_TLS1_3_SERVER_HELLO, extensions,
NULL, 0)) {
s->version = origv;
return 0;
}
if (s->hello_retry_request != SSL_HRR_NONE
&& s->version != TLS1_3_VERSION) {
s->version = origv;
SSLfatal(s, SSL_AD_PROTOCOL_VERSION, SSL_R_WRONG_SSL_VERSION);
return 0;
}
switch (s->method->version) {
default:
if (s->version != s->method->version) {
s->version = origv;
SSLfatal(s, SSL_AD_PROTOCOL_VERSION, SSL_R_WRONG_SSL_VERSION);
return 0;
}
/*
* If this SSL handle is not from a version flexible method we don't
* (and never did) check min/max, FIPS or Suite B constraints. Hope
* that's OK. It is up to the caller to not choose fixed protocol
* versions they don't want. If not, then easy to fix, just return
* ssl_method_error(s, s->method)
*/
return 1;
case TLS_ANY_VERSION:
table = tls_version_table;
break;
case DTLS_ANY_VERSION:
table = dtls_version_table;
break;
}
ret = ssl_get_min_max_version(s, &ver_min, &ver_max, &real_max);
if (ret != 0) {
s->version = origv;
SSLfatal(s, SSL_AD_PROTOCOL_VERSION, ret);
return 0;
}
if (SSL_IS_DTLS(s) ? DTLS_VERSION_LT(s->version, ver_min)
: s->version < ver_min) {
s->version = origv;
SSLfatal(s, SSL_AD_PROTOCOL_VERSION, SSL_R_UNSUPPORTED_PROTOCOL);
return 0;
} else if (SSL_IS_DTLS(s) ? DTLS_VERSION_GT(s->version, ver_max)
: s->version > ver_max) {
s->version = origv;
SSLfatal(s, SSL_AD_PROTOCOL_VERSION, SSL_R_UNSUPPORTED_PROTOCOL);
return 0;
}
if ((s->mode & SSL_MODE_SEND_FALLBACK_SCSV) == 0)
real_max = ver_max;
/* Check for downgrades */
if (s->version == TLS1_2_VERSION && real_max > s->version) {
if (memcmp(tls12downgrade,
s->s3.server_random + SSL3_RANDOM_SIZE
- sizeof(tls12downgrade),
sizeof(tls12downgrade)) == 0) {
s->version = origv;
SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
SSL_R_INAPPROPRIATE_FALLBACK);
return 0;
}
} else if (!SSL_IS_DTLS(s)
&& s->version < TLS1_2_VERSION
&& real_max > s->version) {
if (memcmp(tls11downgrade,
s->s3.server_random + SSL3_RANDOM_SIZE
- sizeof(tls11downgrade),
sizeof(tls11downgrade)) == 0) {
s->version = origv;
SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
SSL_R_INAPPROPRIATE_FALLBACK);
return 0;
}
}
for (vent = table; vent->version != 0; ++vent) {
if (vent->cmeth == NULL || s->version != vent->version)
continue;
s->method = vent->cmeth();
return 1;
}
s->version = origv;
SSLfatal(s, SSL_AD_PROTOCOL_VERSION, SSL_R_UNSUPPORTED_PROTOCOL);
return 0;
}
/*
* ssl_get_min_max_version - get minimum and maximum protocol version
* @s: The SSL connection
* @min_version: The minimum supported version
* @max_version: The maximum supported version
* @real_max: The highest version below the lowest compile time version hole
* where that hole lies above at least one run-time enabled
* protocol.
*
* Work out what version we should be using for the initial ClientHello if the
* version is initially (D)TLS_ANY_VERSION. We apply any explicit SSL_OP_NO_xxx
* options, the MinProtocol and MaxProtocol configuration commands, any Suite B
* constraints and any floor imposed by the security level here,
* so we don't advertise the wrong protocol version to only reject the outcome later.
*
* Computing the right floor matters. If, e.g., TLS 1.0 and 1.2 are enabled,
* TLS 1.1 is disabled, but the security level, Suite-B and/or MinProtocol
* only allow TLS 1.2, we want to advertise TLS1.2, *not* TLS1.
*
* Returns 0 on success or an SSL error reason number on failure. On failure
* min_version and max_version will also be set to 0.
*/
int ssl_get_min_max_version(const SSL *s, int *min_version, int *max_version,
int *real_max)
{
int version, tmp_real_max;
int hole;
const SSL_METHOD *single = NULL;
const SSL_METHOD *method;
const version_info *table;
const version_info *vent;
switch (s->method->version) {
default:
/*
* If this SSL handle is not from a version flexible method we don't
* (and never did) check min/max FIPS or Suite B constraints. Hope
* that's OK. It is up to the caller to not choose fixed protocol
* versions they don't want. If not, then easy to fix, just return
* ssl_method_error(s, s->method)
*/
*min_version = *max_version = s->version;
/*
* Providing a real_max only makes sense where we're using a version
* flexible method.
*/
if (!ossl_assert(real_max == NULL))
return ERR_R_INTERNAL_ERROR;
return 0;
case TLS_ANY_VERSION:
table = tls_version_table;
break;
case DTLS_ANY_VERSION:
table = dtls_version_table;
break;
}
/*
* SSL_OP_NO_X disables all protocols above X *if* there are some protocols
* below X enabled. This is required in order to maintain the "version
* capability" vector contiguous. Any versions with a NULL client method
* (protocol version client is disabled at compile-time) is also a "hole".
*
* Our initial state is hole == 1, version == 0. That is, versions above
* the first version in the method table are disabled (a "hole" above
* the valid protocol entries) and we don't have a selected version yet.
*
* Whenever "hole == 1", and we hit an enabled method, its version becomes
* the selected version, and the method becomes a candidate "single"
* method. We're no longer in a hole, so "hole" becomes 0.
*
* If "hole == 0" and we hit an enabled method, then "single" is cleared,
* as we support a contiguous range of at least two methods. If we hit
* a disabled method, then hole becomes true again, but nothing else
* changes yet, because all the remaining methods may be disabled too.
* If we again hit an enabled method after the new hole, it becomes
* selected, as we start from scratch.
*/
*min_version = version = 0;
hole = 1;
if (real_max != NULL)
*real_max = 0;
tmp_real_max = 0;
for (vent = table; vent->version != 0; ++vent) {
/*
* A table entry with a NULL client method is still a hole in the
* "version capability" vector.
*/
if (vent->cmeth == NULL) {
hole = 1;
tmp_real_max = 0;
continue;
}
method = vent->cmeth();
if (hole == 1 && tmp_real_max == 0)
tmp_real_max = vent->version;
if (ssl_method_error(s, method) != 0) {
hole = 1;
} else if (!hole) {
single = NULL;
*min_version = method->version;
} else {
if (real_max != NULL && tmp_real_max != 0)
*real_max = tmp_real_max;
version = (single = method)->version;
*min_version = version;
hole = 0;
}
}
*max_version = version;
/* Fail if everything is disabled */
if (version == 0)
return SSL_R_NO_PROTOCOLS_AVAILABLE;
return 0;
}
/*
* ssl_set_client_hello_version - Work out what version we should be using for
* the initial ClientHello.legacy_version field.
*
* @s: client SSL handle.
*
* Returns 0 on success or an SSL error reason number on failure.
*/
int ssl_set_client_hello_version(SSL *s)
{
int ver_min, ver_max, ret;
/*
* In a renegotiation we always send the same client_version that we sent
* last time, regardless of which version we eventually negotiated.
*/
if (!SSL_IS_FIRST_HANDSHAKE(s))
return 0;
ret = ssl_get_min_max_version(s, &ver_min, &ver_max, NULL);
if (ret != 0)
return ret;
s->version = ver_max;
/* TLS1.3 always uses TLS1.2 in the legacy_version field */
if (!SSL_IS_DTLS(s) && ver_max > TLS1_2_VERSION)
ver_max = TLS1_2_VERSION;
s->client_version = ver_max;
return 0;
}
/*
* Checks a list of |groups| to determine if the |group_id| is in it. If it is
* and |checkallow| is 1 then additionally check if the group is allowed to be
* used. Returns 1 if the group is in the list (and allowed if |checkallow| is
* 1) or 0 otherwise.
*/
int check_in_list(SSL *s, uint16_t group_id, const uint16_t *groups,
size_t num_groups, int checkallow)
{
size_t i;
if (groups == NULL || num_groups == 0)
return 0;
for (i = 0; i < num_groups; i++) {
uint16_t group = groups[i];
if (group_id == group
&& (!checkallow
|| tls_group_allowed(s, group, SSL_SECOP_CURVE_CHECK))) {
return 1;
}
}
return 0;
}
/* Replace ClientHello1 in the transcript hash with a synthetic message */
int create_synthetic_message_hash(SSL *s, const unsigned char *hashval,
size_t hashlen, const unsigned char *hrr,
size_t hrrlen)
{
unsigned char hashvaltmp[EVP_MAX_MD_SIZE];
unsigned char msghdr[SSL3_HM_HEADER_LENGTH];
memset(msghdr, 0, sizeof(msghdr));
if (hashval == NULL) {
hashval = hashvaltmp;
hashlen = 0;
/* Get the hash of the initial ClientHello */
if (!ssl3_digest_cached_records(s, 0)
|| !ssl_handshake_hash(s, hashvaltmp, sizeof(hashvaltmp),
&hashlen)) {
/* SSLfatal() already called */
return 0;
}
}
/* Reinitialise the transcript hash */
if (!ssl3_init_finished_mac(s)) {
/* SSLfatal() already called */
return 0;
}
/* Inject the synthetic message_hash message */
msghdr[0] = SSL3_MT_MESSAGE_HASH;
msghdr[SSL3_HM_HEADER_LENGTH - 1] = (unsigned char)hashlen;
if (!ssl3_finish_mac(s, msghdr, SSL3_HM_HEADER_LENGTH)
|| !ssl3_finish_mac(s, hashval, hashlen)) {
/* SSLfatal() already called */
return 0;
}
/*
* Now re-inject the HRR and current message if appropriate (we just deleted
* it when we reinitialised the transcript hash above). Only necessary after
* receiving a ClientHello2 with a cookie.
*/
if (hrr != NULL
&& (!ssl3_finish_mac(s, hrr, hrrlen)
|| !ssl3_finish_mac(s, (unsigned char *)s->init_buf->data,
s->s3.tmp.message_size
+ SSL3_HM_HEADER_LENGTH))) {
/* SSLfatal() already called */
return 0;
}
return 1;
}
static int ca_dn_cmp(const X509_NAME *const *a, const X509_NAME *const *b)
{
return X509_NAME_cmp(*a, *b);
}
int parse_ca_names(SSL *s, PACKET *pkt)
{
STACK_OF(X509_NAME) *ca_sk = sk_X509_NAME_new(ca_dn_cmp);
X509_NAME *xn = NULL;
PACKET cadns;
if (ca_sk == NULL) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_MALLOC_FAILURE);
goto err;
}
/* get the CA RDNs */
if (!PACKET_get_length_prefixed_2(pkt, &cadns)) {
SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
goto err;
}
while (PACKET_remaining(&cadns)) {
const unsigned char *namestart, *namebytes;
unsigned int name_len;
if (!PACKET_get_net_2(&cadns, &name_len)
|| !PACKET_get_bytes(&cadns, &namebytes, name_len)) {
SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
goto err;
}
namestart = namebytes;
if ((xn = d2i_X509_NAME(NULL, &namebytes, name_len)) == NULL) {
SSLfatal(s, SSL_AD_DECODE_ERROR, ERR_R_ASN1_LIB);
goto err;
}
if (namebytes != (namestart + name_len)) {
SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_CA_DN_LENGTH_MISMATCH);
goto err;
}
if (!sk_X509_NAME_push(ca_sk, xn)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_MALLOC_FAILURE);
goto err;
}
xn = NULL;
}
sk_X509_NAME_pop_free(s->s3.tmp.peer_ca_names, X509_NAME_free);
s->s3.tmp.peer_ca_names = ca_sk;
return 1;
err:
sk_X509_NAME_pop_free(ca_sk, X509_NAME_free);
X509_NAME_free(xn);
return 0;
}
const STACK_OF(X509_NAME) *get_ca_names(SSL *s)
{
const STACK_OF(X509_NAME) *ca_sk = NULL;;
if (s->server) {
ca_sk = SSL_get_client_CA_list(s);
if (ca_sk != NULL && sk_X509_NAME_num(ca_sk) == 0)
ca_sk = NULL;
}
if (ca_sk == NULL)
ca_sk = SSL_get0_CA_list(s);
return ca_sk;
}
int construct_ca_names(SSL *s, const STACK_OF(X509_NAME) *ca_sk, WPACKET *pkt)
{
/* Start sub-packet for client CA list */
if (!WPACKET_start_sub_packet_u16(pkt)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return 0;
}
if ((ca_sk != NULL) && !(s->options & SSL_OP_DISABLE_TLSEXT_CA_NAMES)) {
int i;
for (i = 0; i < sk_X509_NAME_num(ca_sk); i++) {
unsigned char *namebytes;
X509_NAME *name = sk_X509_NAME_value(ca_sk, i);
int namelen;
if (name == NULL
|| (namelen = i2d_X509_NAME(name, NULL)) < 0
|| !WPACKET_sub_allocate_bytes_u16(pkt, namelen,
&namebytes)
|| i2d_X509_NAME(name, &namebytes) != namelen) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return 0;
}
}
}
if (!WPACKET_close(pkt)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return 0;
}
return 1;
}
/* Create a buffer containing data to be signed for server key exchange */
size_t construct_key_exchange_tbs(SSL *s, unsigned char **ptbs,
const void *param, size_t paramlen)
{
size_t tbslen = 2 * SSL3_RANDOM_SIZE + paramlen;
unsigned char *tbs = OPENSSL_malloc(tbslen);
if (tbs == NULL) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_MALLOC_FAILURE);
return 0;
}
memcpy(tbs, s->s3.client_random, SSL3_RANDOM_SIZE);
memcpy(tbs + SSL3_RANDOM_SIZE, s->s3.server_random, SSL3_RANDOM_SIZE);
memcpy(tbs + SSL3_RANDOM_SIZE * 2, param, paramlen);
*ptbs = tbs;
return tbslen;
}
/*
* Saves the current handshake digest for Post-Handshake Auth,
* Done after ClientFinished is processed, done exactly once
*/
int tls13_save_handshake_digest_for_pha(SSL *s)
{
if (s->pha_dgst == NULL) {
if (!ssl3_digest_cached_records(s, 1))
/* SSLfatal() already called */
return 0;
s->pha_dgst = EVP_MD_CTX_new();
if (s->pha_dgst == NULL) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return 0;
}
if (!EVP_MD_CTX_copy_ex(s->pha_dgst,
s->s3.handshake_dgst)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
EVP_MD_CTX_free(s->pha_dgst);
s->pha_dgst = NULL;
return 0;
}
}
return 1;
}
/*
* Restores the Post-Handshake Auth handshake digest
* Done just before sending/processing the Cert Request
*/
int tls13_restore_handshake_digest_for_pha(SSL *s)
{
if (s->pha_dgst == NULL) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return 0;
}
if (!EVP_MD_CTX_copy_ex(s->s3.handshake_dgst,
s->pha_dgst)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return 0;
}
return 1;
}
diff --git a/crypto/openssl/ssl/t1_lib.c b/crypto/openssl/ssl/t1_lib.c
index 673e2f0f0248..bbb3b514d77f 100644
--- a/crypto/openssl/ssl/t1_lib.c
+++ b/crypto/openssl/ssl/t1_lib.c
@@ -1,3531 +1,3533 @@
/*
* 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) * 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)
{
+ if (session->ext.max_fragment_len_mode == TLSEXT_max_fragment_length_UNSPECIFIED)
+ return TLSEXT_max_fragment_length_DISABLED;
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/build.info b/crypto/openssl/test/build.info
index 25ab0430b731..76ff945ab8b3 100644
--- a/crypto/openssl/test/build.info
+++ b/crypto/openssl/test/build.info
@@ -1,977 +1,981 @@
# 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 \
+ v3nametest v3ext punycode_test evp_byname_test \
crltest danetest bad_dtls_test lhash_test sparse_array_test \
conf_include_test params_api_test params_conversion_test \
constant_time_test 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[evp_byname_test]=evp_byname_test.c
+ INCLUDE[evp_byname_test]=../include ../apps/include
+ DEPEND[evp_byname_test]=../libcrypto libtestutil.a
+
SOURCE[stack_test]=stack_test.c
INCLUDE[stack_test]=../include ../apps/include
DEPEND[stack_test]=../libcrypto libtestutil.a
SOURCE[lhash_test]=lhash_test.c
INCLUDE[lhash_test]=../include ../apps/include
DEPEND[lhash_test]=../libcrypto 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/crltest.c b/crypto/openssl/test/crltest.c
index d17fac43f82a..c96561c69bfa 100644
--- a/crypto/openssl/test/crltest.c
+++ b/crypto/openssl/test/crltest.c
@@ -1,413 +1,454 @@
/*
- * Copyright 2015-2022 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
*/
#include "internal/nelem.h"
#include <string.h>
#include <openssl/bio.h>
#include <openssl/crypto.h>
#include <openssl/err.h>
#include <openssl/pem.h>
#include <openssl/x509.h>
#include "testutil.h"
#define PARAM_TIME 1474934400 /* Sep 27th, 2016 */
static const char *kCRLTestRoot[] = {
"-----BEGIN CERTIFICATE-----\n",
"MIIDbzCCAlegAwIBAgIJAODri7v0dDUFMA0GCSqGSIb3DQEBCwUAME4xCzAJBgNV\n",
"BAYTAlVTMRMwEQYDVQQIDApDYWxpZm9ybmlhMRYwFAYDVQQHDA1Nb3VudGFpbiBW\n",
"aWV3MRIwEAYDVQQKDAlCb3JpbmdTU0wwHhcNMTYwOTI2MTUwNjI2WhcNMjYwOTI0\n",
"MTUwNjI2WjBOMQswCQYDVQQGEwJVUzETMBEGA1UECAwKQ2FsaWZvcm5pYTEWMBQG\n",
"A1UEBwwNTW91bnRhaW4gVmlldzESMBAGA1UECgwJQm9yaW5nU1NMMIIBIjANBgkq\n",
"hkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAo16WiLWZuaymsD8n5SKPmxV1y6jjgr3B\n",
"S/dUBpbrzd1aeFzNlI8l2jfAnzUyp+I21RQ+nh/MhqjGElkTtK9xMn1Y+S9GMRh+\n",
"5R/Du0iCb1tCZIPY07Tgrb0KMNWe0v2QKVVruuYSgxIWodBfxlKO64Z8AJ5IbnWp\n",
"uRqO6rctN9qUoMlTIAB6dL4G0tDJ/PGFWOJYwOMEIX54bly2wgyYJVBKiRRt4f7n\n",
"8H922qmvPNA9idmX9G1VAtgV6x97XXi7ULORIQvn9lVQF6nTYDBJhyuPB+mLThbL\n",
"P2o9orxGx7aCtnnBZUIxUvHNOI0FaSaZH7Fi0xsZ/GkG2HZe7ImPJwIDAQABo1Aw\n",
"TjAdBgNVHQ4EFgQUWPt3N5cZ/CRvubbrkqfBnAqhq94wHwYDVR0jBBgwFoAUWPt3\n",
"N5cZ/CRvubbrkqfBnAqhq94wDAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQsFAAOC\n",
"AQEAORu6M0MOwXy+3VEBwNilfTxyqDfruQsc1jA4PT8Oe8zora1WxE1JB4q2FJOz\n",
"EAuM3H/NXvEnBuN+ITvKZAJUfm4NKX97qmjMJwLKWe1gVv+VQTr63aR7mgWJReQN\n",
"XdMztlVeZs2dppV6uEg3ia1X0G7LARxGpA9ETbMyCpb39XxlYuTClcbA5ftDN99B\n",
"3Xg9KNdd++Ew22O3HWRDvdDpTO/JkzQfzi3sYwUtzMEonENhczJhGf7bQMmvL/w5\n",
"24Wxj4Z7KzzWIHsNqE/RIs6RV3fcW61j/mRgW2XyoWnMVeBzvcJr9NXp4VQYmFPw\n",
"amd8GKMZQvP0ufGnUn7D7uartA==\n",
"-----END CERTIFICATE-----\n",
NULL
};
static const char *kCRLTestLeaf[] = {
"-----BEGIN CERTIFICATE-----\n",
"MIIDkDCCAnigAwIBAgICEAAwDQYJKoZIhvcNAQELBQAwTjELMAkGA1UEBhMCVVMx\n",
"EzARBgNVBAgMCkNhbGlmb3JuaWExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxEjAQ\n",
"BgNVBAoMCUJvcmluZ1NTTDAeFw0xNjA5MjYxNTA4MzFaFw0xNzA5MjYxNTA4MzFa\n",
"MEsxCzAJBgNVBAYTAlVTMRMwEQYDVQQIDApDYWxpZm9ybmlhMRIwEAYDVQQKDAlC\n",
"b3JpbmdTU0wxEzARBgNVBAMMCmJvcmluZy5zc2wwggEiMA0GCSqGSIb3DQEBAQUA\n",
"A4IBDwAwggEKAoIBAQDc5v1S1M0W+QWM+raWfO0LH8uvqEwuJQgODqMaGnSlWUx9\n",
"8iQcnWfjyPja3lWg9K62hSOFDuSyEkysKHDxijz5R93CfLcfnVXjWQDJe7EJTTDP\n",
"ozEvxN6RjAeYv7CF000euYr3QT5iyBjg76+bon1p0jHZBJeNPP1KqGYgyxp+hzpx\n",
"e0gZmTlGAXd8JQK4v8kpdYwD6PPifFL/jpmQpqOtQmH/6zcLjY4ojmqpEdBqIKIX\n",
"+saA29hMq0+NK3K+wgg31RU+cVWxu3tLOIiesETkeDgArjWRS1Vkzbi4v9SJxtNu\n",
"OZuAxWiynRJw3JwH/OFHYZIvQqz68ZBoj96cepjPAgMBAAGjezB5MAkGA1UdEwQC\n",
"MAAwLAYJYIZIAYb4QgENBB8WHU9wZW5TU0wgR2VuZXJhdGVkIENlcnRpZmljYXRl\n",
"MB0GA1UdDgQWBBTGn0OVVh/aoYt0bvEKG+PIERqnDzAfBgNVHSMEGDAWgBRY+3c3\n",
"lxn8JG+5tuuSp8GcCqGr3jANBgkqhkiG9w0BAQsFAAOCAQEAd2nM8gCQN2Dc8QJw\n",
"XSZXyuI3DBGGCHcay/3iXu0JvTC3EiQo8J6Djv7WLI0N5KH8mkm40u89fJAB2lLZ\n",
"ShuHVtcC182bOKnePgwp9CNwQ21p0rDEu/P3X46ZvFgdxx82E9xLa0tBB8PiPDWh\n",
"lV16jbaKTgX5AZqjnsyjR5o9/mbZVupZJXx5Syq+XA8qiJfstSYJs4KyKK9UOjql\n",
"ICkJVKpi2ahDBqX4MOH4SLfzVk8pqSpviS6yaA1RXqjpkxiN45WWaXDldVHMSkhC\n",
"5CNXsXi4b1nAntu89crwSLA3rEwzCWeYj+BX7e1T9rr3oJdwOU/2KQtW1js1yQUG\n",
"tjJMFw==\n",
"-----END CERTIFICATE-----\n",
NULL
};
static const char *kBasicCRL[] = {
"-----BEGIN X509 CRL-----\n",
"MIIBpzCBkAIBATANBgkqhkiG9w0BAQsFADBOMQswCQYDVQQGEwJVUzETMBEGA1UE\n",
"CAwKQ2FsaWZvcm5pYTEWMBQGA1UEBwwNTW91bnRhaW4gVmlldzESMBAGA1UECgwJ\n",
"Qm9yaW5nU1NMFw0xNjA5MjYxNTEwNTVaFw0xNjEwMjYxNTEwNTVaoA4wDDAKBgNV\n",
"HRQEAwIBATANBgkqhkiG9w0BAQsFAAOCAQEAnrBKKgvd9x9zwK9rtUvVeFeJ7+LN\n",
"ZEAc+a5oxpPNEsJx6hXoApYEbzXMxuWBQoCs5iEBycSGudct21L+MVf27M38KrWo\n",
"eOkq0a2siqViQZO2Fb/SUFR0k9zb8xl86Zf65lgPplALun0bV/HT7MJcl04Tc4os\n",
"dsAReBs5nqTGNEd5AlC1iKHvQZkM//MD51DspKnDpsDiUVi54h9C1SpfZmX8H2Vv\n",
"diyu0fZ/bPAM3VAGawatf/SyWfBMyKpoPXEG39oAzmjjOj8en82psn7m474IGaho\n",
"/vBbhl1ms5qQiLYPjm4YELtnXQoFyC72tBjbdFd/ZE9k4CNKDbxFUXFbkw==\n",
"-----END X509 CRL-----\n",
NULL
};
static const char *kRevokedCRL[] = {
"-----BEGIN X509 CRL-----\n",
"MIIBvjCBpwIBATANBgkqhkiG9w0BAQsFADBOMQswCQYDVQQGEwJVUzETMBEGA1UE\n",
"CAwKQ2FsaWZvcm5pYTEWMBQGA1UEBwwNTW91bnRhaW4gVmlldzESMBAGA1UECgwJ\n",
"Qm9yaW5nU1NMFw0xNjA5MjYxNTEyNDRaFw0xNjEwMjYxNTEyNDRaMBUwEwICEAAX\n",
"DTE2MDkyNjE1MTIyNlqgDjAMMAoGA1UdFAQDAgECMA0GCSqGSIb3DQEBCwUAA4IB\n",
"AQCUGaM4DcWzlQKrcZvI8TMeR8BpsvQeo5BoI/XZu2a8h//PyRyMwYeaOM+3zl0d\n",
"sjgCT8b3C1FPgT+P2Lkowv7rJ+FHJRNQkogr+RuqCSPTq65ha4WKlRGWkMFybzVH\n",
"NloxC+aU3lgp/NlX9yUtfqYmJek1CDrOOGPrAEAwj1l/BUeYKNGqfBWYJQtPJu+5\n",
"OaSvIYGpETCZJscUWODmLEb/O3DM438vLvxonwGqXqS0KX37+CHpUlyhnSovxXxp\n",
"Pz4aF+L7OtczxL0GYtD2fR9B7TDMqsNmHXgQrixvvOY7MUdLGbd4RfJL3yA53hyO\n",
"xzfKY2TzxLiOmctG0hXFkH5J\n",
"-----END X509 CRL-----\n",
NULL
};
+static const char *kInvalidCRL[] = {
+ "-----BEGIN X509 CRL-----\n",
+ "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n",
+ "-----END X509 CRL-----\n",
+ NULL
+};
+
static const char *kBadIssuerCRL[] = {
"-----BEGIN X509 CRL-----\n",
"MIIBwjCBqwIBATANBgkqhkiG9w0BAQsFADBSMQswCQYDVQQGEwJVUzETMBEGA1UE\n",
"CAwKQ2FsaWZvcm5pYTEWMBQGA1UEBwwNTW91bnRhaW4gVmlldzEWMBQGA1UECgwN\n",
"Tm90IEJvcmluZ1NTTBcNMTYwOTI2MTUxMjQ0WhcNMTYxMDI2MTUxMjQ0WjAVMBMC\n",
"AhAAFw0xNjA5MjYxNTEyMjZaoA4wDDAKBgNVHRQEAwIBAjANBgkqhkiG9w0BAQsF\n",
"AAOCAQEAlBmjOA3Fs5UCq3GbyPEzHkfAabL0HqOQaCP12btmvIf/z8kcjMGHmjjP\n",
"t85dHbI4Ak/G9wtRT4E/j9i5KML+6yfhRyUTUJKIK/kbqgkj06uuYWuFipURlpDB\n",
"cm81RzZaMQvmlN5YKfzZV/clLX6mJiXpNQg6zjhj6wBAMI9ZfwVHmCjRqnwVmCUL\n",
"TybvuTmkryGBqREwmSbHFFjg5ixG/ztwzON/Ly78aJ8Bql6ktCl9+/gh6VJcoZ0q\n",
"L8V8aT8+Ghfi+zrXM8S9BmLQ9n0fQe0wzKrDZh14EK4sb7zmOzFHSxm3eEXyS98g\n",
"Od4cjsc3ymNk88S4jpnLRtIVxZB+SQ==\n",
"-----END X509 CRL-----\n",
NULL
};
/*
* This is kBasicCRL but with a critical issuing distribution point
* extension.
*/
static const char *kKnownCriticalCRL[] = {
"-----BEGIN X509 CRL-----\n",
"MIIBujCBowIBATANBgkqhkiG9w0BAQsFADBOMQswCQYDVQQGEwJVUzETMBEGA1UE\n",
"CAwKQ2FsaWZvcm5pYTEWMBQGA1UEBwwNTW91bnRhaW4gVmlldzESMBAGA1UECgwJ\n",
"Qm9yaW5nU1NMFw0xNjA5MjYxNTEwNTVaFw0xNjEwMjYxNTEwNTVaoCEwHzAKBgNV\n",
"HRQEAwIBATARBgNVHRwBAf8EBzAFoQMBAf8wDQYJKoZIhvcNAQELBQADggEBAA+3\n",
"i+5e5Ub8sccfgOBs6WVJFI9c8gvJjrJ8/dYfFIAuCyeocs7DFXn1n13CRZ+URR/Q\n",
"mVWgU28+xeusuSPYFpd9cyYTcVyNUGNTI3lwgcE/yVjPaOmzSZKdPakApRxtpKKQ\n",
"NN/56aQz3bnT/ZSHQNciRB8U6jiD9V30t0w+FDTpGaG+7bzzUH3UVF9xf9Ctp60A\n",
"3mfLe0scas7owSt4AEFuj2SPvcE7yvdOXbu+IEv21cEJUVExJAbhvIweHXh6yRW+\n",
"7VVeiNzdIjkZjyTmAzoXGha4+wbxXyBRbfH+XWcO/H+8nwyG8Gktdu2QB9S9nnIp\n",
"o/1TpfOMSGhMyMoyPrk=\n",
"-----END X509 CRL-----\n",
NULL
};
/*
* kUnknownCriticalCRL is kBasicCRL but with an unknown critical extension.
*/
static const char *kUnknownCriticalCRL[] = {
"-----BEGIN X509 CRL-----\n",
"MIIBvDCBpQIBATANBgkqhkiG9w0BAQsFADBOMQswCQYDVQQGEwJVUzETMBEGA1UE\n",
"CAwKQ2FsaWZvcm5pYTEWMBQGA1UEBwwNTW91bnRhaW4gVmlldzESMBAGA1UECgwJ\n",
"Qm9yaW5nU1NMFw0xNjA5MjYxNTEwNTVaFw0xNjEwMjYxNTEwNTVaoCMwITAKBgNV\n",
"HRQEAwIBATATBgwqhkiG9xIEAYS3CQABAf8EADANBgkqhkiG9w0BAQsFAAOCAQEA\n",
"GvBP0xqL509InMj/3493YVRV+ldTpBv5uTD6jewzf5XdaxEQ/VjTNe5zKnxbpAib\n",
"Kf7cwX0PMSkZjx7k7kKdDlEucwVvDoqC+O9aJcqVmM6GDyNb9xENxd0XCXja6MZC\n",
"yVgP4AwLauB2vSiEprYJyI1APph3iAEeDm60lTXX/wBM/tupQDDujKh2GPyvBRfJ\n",
"+wEDwGg3ICwvu4gO4zeC5qnFR+bpL9t5tOMAQnVZ0NWv+k7mkd2LbHdD44dxrfXC\n",
"nhtfERx99SDmC/jtUAJrGhtCO8acr7exCeYcduN7KKCm91OeCJKK6OzWst0Og1DB\n",
"kwzzU2rL3G65CrZ7H0SZsQ==\n",
"-----END X509 CRL-----\n",
NULL
};
/*
* kUnknownCriticalCRL2 is kBasicCRL but with a critical issuing distribution
* point extension followed by an unknown critical extension
*/
static const char *kUnknownCriticalCRL2[] = {
"-----BEGIN X509 CRL-----\n",
"MIIBzzCBuAIBATANBgkqhkiG9w0BAQsFADBOMQswCQYDVQQGEwJVUzETMBEGA1UE\n",
"CAwKQ2FsaWZvcm5pYTEWMBQGA1UEBwwNTW91bnRhaW4gVmlldzESMBAGA1UECgwJ\n",
"Qm9yaW5nU1NMFw0xNjA5MjYxNTEwNTVaFw0xNjEwMjYxNTEwNTVaoDYwNDAKBgNV\n",
"HRQEAwIBATARBgNVHRwBAf8EBzAFoQMBAf8wEwYMKoZIhvcSBAGEtwkAAQH/BAAw\n",
"DQYJKoZIhvcNAQELBQADggEBACTcpQC8jXL12JN5YzOcQ64ubQIe0XxRAd30p7qB\n",
"BTXGpgqBjrjxRfLms7EBYodEXB2oXMsDq3km0vT1MfYdsDD05S+SQ9CDsq/pUfaC\n",
"E2WNI5p8WircRnroYvbN2vkjlRbMd1+yNITohXYXCJwjEOAWOx3XIM10bwPYBv4R\n",
"rDobuLHoMgL3yHgMHmAkP7YpkBucNqeBV8cCdeAZLuhXFWi6yfr3r/X18yWbC/r2\n",
"2xXdkrSqXLFo7ToyP8YKTgiXpya4x6m53biEYwa2ULlas0igL6DK7wjYZX95Uy7H\n",
"GKljn9weIYiMPV/BzGymwfv2EW0preLwtyJNJPaxbdin6Jc=\n",
"-----END X509 CRL-----\n",
NULL
};
static const char **unknown_critical_crls[] = {
kUnknownCriticalCRL, kUnknownCriticalCRL2
};
static X509 *test_root = NULL;
static X509 *test_leaf = NULL;
/*
* Glue an array of strings together. Return a BIO and put the string
* into |*out| so we can free it.
*/
static BIO *glue2bio(const char **pem, char **out)
{
size_t s = 0;
*out = glue_strings(pem, &s);
return BIO_new_mem_buf(*out, s);
}
/*
* Create a CRL from an array of strings.
*/
static X509_CRL *CRL_from_strings(const char **pem)
{
X509_CRL *crl;
char *p;
BIO *b = glue2bio(pem, &p);
if (b == NULL) {
OPENSSL_free(p);
return NULL;
}
crl = PEM_read_bio_X509_CRL(b, NULL, NULL, NULL);
OPENSSL_free(p);
BIO_free(b);
return crl;
}
/*
* Create an X509 from an array of strings.
*/
static X509 *X509_from_strings(const char **pem)
{
X509 *x;
char *p;
BIO *b = glue2bio(pem, &p);
if (b == NULL) {
OPENSSL_free(p);
return NULL;
}
x = PEM_read_bio_X509(b, NULL, NULL, NULL);
OPENSSL_free(p);
BIO_free(b);
return x;
}
/*
* Verify |leaf| certificate (chained up to |root|). |crls| if
* not NULL, is a list of CRLs to include in the verification. It is
* also free'd before returning, which is kinda yucky but convenient.
* Returns a value from X509_V_ERR_xxx or X509_V_OK.
*/
static int verify(X509 *leaf, X509 *root, STACK_OF(X509_CRL) *crls,
unsigned long flags)
{
X509_STORE_CTX *ctx = X509_STORE_CTX_new();
X509_STORE *store = X509_STORE_new();
X509_VERIFY_PARAM *param = X509_VERIFY_PARAM_new();
STACK_OF(X509) *roots = sk_X509_new_null();
int status = X509_V_ERR_UNSPECIFIED;
if (!TEST_ptr(ctx)
|| !TEST_ptr(store)
|| !TEST_ptr(param)
|| !TEST_ptr(roots))
goto err;
/* Create a stack; upref the cert because we free it below. */
X509_up_ref(root);
if (!TEST_true(sk_X509_push(roots, root))
|| !TEST_true(X509_STORE_CTX_init(ctx, store, leaf, NULL)))
goto err;
X509_STORE_CTX_set0_trusted_stack(ctx, roots);
X509_STORE_CTX_set0_crls(ctx, crls);
X509_VERIFY_PARAM_set_time(param, PARAM_TIME);
if (!TEST_long_eq((long)X509_VERIFY_PARAM_get_time(param), PARAM_TIME))
goto err;
X509_VERIFY_PARAM_set_depth(param, 16);
if (flags)
X509_VERIFY_PARAM_set_flags(param, flags);
X509_STORE_CTX_set0_param(ctx, param);
param = NULL;
ERR_clear_error();
status = X509_verify_cert(ctx) == 1 ? X509_V_OK
: X509_STORE_CTX_get_error(ctx);
err:
sk_X509_pop_free(roots, X509_free);
sk_X509_CRL_pop_free(crls, X509_CRL_free);
X509_VERIFY_PARAM_free(param);
X509_STORE_CTX_free(ctx);
X509_STORE_free(store);
return status;
}
/*
* Create a stack of CRL's. Upref each one because we call pop_free on
* the stack and need to keep the CRL's around until the test exits.
* Yes this crashes on malloc failure; it forces us to debug.
*/
static STACK_OF(X509_CRL) *make_CRL_stack(X509_CRL *x1, X509_CRL *x2)
{
STACK_OF(X509_CRL) *sk = sk_X509_CRL_new_null();
sk_X509_CRL_push(sk, x1);
X509_CRL_up_ref(x1);
if (x2 != NULL) {
sk_X509_CRL_push(sk, x2);
X509_CRL_up_ref(x2);
}
return sk;
}
static int test_basic_crl(void)
{
X509_CRL *basic_crl = CRL_from_strings(kBasicCRL);
X509_CRL *revoked_crl = CRL_from_strings(kRevokedCRL);
int r;
r = TEST_ptr(basic_crl)
&& TEST_ptr(revoked_crl)
&& TEST_int_eq(verify(test_leaf, test_root,
make_CRL_stack(basic_crl, NULL),
X509_V_FLAG_CRL_CHECK), X509_V_OK)
&& TEST_int_eq(verify(test_leaf, test_root,
make_CRL_stack(basic_crl, revoked_crl),
X509_V_FLAG_CRL_CHECK), X509_V_ERR_CERT_REVOKED);
X509_CRL_free(basic_crl);
X509_CRL_free(revoked_crl);
return r;
}
static int test_no_crl(void)
{
return TEST_int_eq(verify(test_leaf, test_root, NULL,
X509_V_FLAG_CRL_CHECK),
X509_V_ERR_UNABLE_TO_GET_CRL);
}
static int test_bad_issuer_crl(void)
{
X509_CRL *bad_issuer_crl = CRL_from_strings(kBadIssuerCRL);
int r;
r = TEST_ptr(bad_issuer_crl)
&& TEST_int_eq(verify(test_leaf, test_root,
make_CRL_stack(bad_issuer_crl, NULL),
X509_V_FLAG_CRL_CHECK),
X509_V_ERR_UNABLE_TO_GET_CRL);
X509_CRL_free(bad_issuer_crl);
return r;
}
static int test_known_critical_crl(void)
{
X509_CRL *known_critical_crl = CRL_from_strings(kKnownCriticalCRL);
int r;
r = TEST_ptr(known_critical_crl)
&& TEST_int_eq(verify(test_leaf, test_root,
make_CRL_stack(known_critical_crl, NULL),
X509_V_FLAG_CRL_CHECK), X509_V_OK);
X509_CRL_free(known_critical_crl);
return r;
}
static int test_unknown_critical_crl(int n)
{
X509_CRL *unknown_critical_crl = CRL_from_strings(unknown_critical_crls[n]);
int r;
r = TEST_ptr(unknown_critical_crl)
&& TEST_int_eq(verify(test_leaf, test_root,
make_CRL_stack(unknown_critical_crl, NULL),
X509_V_FLAG_CRL_CHECK),
X509_V_ERR_UNHANDLED_CRITICAL_CRL_EXTENSION);
X509_CRL_free(unknown_critical_crl);
return r;
}
-static int test_reuse_crl(void)
+static int test_reuse_crl(int idx)
{
- X509_CRL *reused_crl = CRL_from_strings(kBasicCRL);
- char *p;
- BIO *b = glue2bio(kRevokedCRL, &p);
+ X509_CRL *result, *reused_crl = CRL_from_strings(kBasicCRL);
+ X509_CRL *addref_crl = NULL;
+ char *p = NULL;
+ BIO *b = NULL;
+ int r = 0;
- if (b == NULL) {
- OPENSSL_free(p);
- X509_CRL_free(reused_crl);
- return 0;
+ if (!TEST_ptr(reused_crl))
+ goto err;
+
+ if (idx & 1) {
+ if (!TEST_true(X509_CRL_up_ref(reused_crl)))
+ goto err;
+ addref_crl = reused_crl;
}
- reused_crl = PEM_read_bio_X509_CRL(b, &reused_crl, NULL, NULL);
+ idx >>= 1;
+ b = glue2bio(idx == 2 ? kRevokedCRL : kInvalidCRL + idx, &p);
+ if (!TEST_ptr(b))
+ goto err;
+
+ result = PEM_read_bio_X509_CRL(b, &reused_crl, NULL, NULL);
+
+ switch (idx) {
+ case 0: /* valid PEM + invalid DER */
+ if (!TEST_ptr_null(result)
+ || !TEST_ptr_null(reused_crl))
+ goto err;
+ break;
+ case 1: /* invalid PEM */
+ if (!TEST_ptr_null(result)
+ || !TEST_ptr(reused_crl))
+ goto err;
+ break;
+ case 2:
+ if (!TEST_ptr(result)
+ || !TEST_ptr(reused_crl)
+ || !TEST_ptr_eq(result, reused_crl))
+ goto err;
+ break;
+ }
+
+ r = 1;
+
+ err:
OPENSSL_free(p);
BIO_free(b);
X509_CRL_free(reused_crl);
- return 1;
+ X509_CRL_free(addref_crl);
+ return r;
}
int setup_tests(void)
{
if (!TEST_ptr(test_root = X509_from_strings(kCRLTestRoot))
|| !TEST_ptr(test_leaf = X509_from_strings(kCRLTestLeaf)))
return 0;
ADD_TEST(test_no_crl);
ADD_TEST(test_basic_crl);
ADD_TEST(test_bad_issuer_crl);
ADD_TEST(test_known_critical_crl);
ADD_ALL_TESTS(test_unknown_critical_crl, OSSL_NELEM(unknown_critical_crls));
- ADD_TEST(test_reuse_crl);
+ ADD_ALL_TESTS(test_reuse_crl, 6);
return 1;
}
void cleanup_tests(void)
{
X509_free(test_root);
X509_free(test_leaf);
}
diff --git a/crypto/openssl/test/endecode_test.c b/crypto/openssl/test/endecode_test.c
index 5158b39ee41f..0611d94216f0 100644
--- a/crypto/openssl/test/endecode_test.c
+++ b/crypto/openssl/test/endecode_test.c
@@ -1,1502 +1,1516 @@
/*
- * Copyright 2020-2023 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 <string.h>
#include <openssl/core_dispatch.h>
#include <openssl/evp.h>
#include <openssl/pem.h>
#include <openssl/rsa.h>
#include <openssl/x509.h>
#include <openssl/core_names.h>
#include <openssl/params.h>
#include <openssl/param_build.h>
#include <openssl/encoder.h>
#include <openssl/decoder.h>
#include "internal/cryptlib.h" /* ossl_assert */
#include "crypto/pem.h" /* For PVK and "blob" PEM headers */
#include "crypto/evp.h" /* For evp_pkey_is_provided() */
#include "helpers/predefined_dhparams.h"
#include "testutil.h"
/* Extended test macros to allow passing file & line number */
#define TEST_FL_ptr(a) test_ptr(file, line, #a, a)
#define TEST_FL_mem_eq(a, m, b, n) test_mem_eq(file, line, #a, #b, a, m, b, n)
#define TEST_FL_strn_eq(a, b, n) test_strn_eq(file, line, #a, #b, a, n, b, n)
#define TEST_FL_strn2_eq(a, m, b, n) test_strn_eq(file, line, #a, #b, a, m, b, n)
#define TEST_FL_int_eq(a, b) test_int_eq(file, line, #a, #b, a, b)
#define TEST_FL_int_ge(a, b) test_int_ge(file, line, #a, #b, a, b)
#define TEST_FL_int_gt(a, b) test_int_gt(file, line, #a, #b, a, b)
#define TEST_FL_long_gt(a, b) test_long_gt(file, line, #a, #b, a, b)
#define TEST_FL_true(a) test_true(file, line, #a, (a) != 0)
#if defined(OPENSSL_NO_DH) && defined(OPENSSL_NO_DSA) && defined(OPENSSL_NO_EC)
# define OPENSSL_NO_KEYPARAMS
#endif
static int default_libctx = 1;
static int is_fips = 0;
static int is_fips_3_0_0 = 0;
static OSSL_LIB_CTX *testctx = NULL;
static OSSL_LIB_CTX *keyctx = NULL;
static char *testpropq = NULL;
static OSSL_PROVIDER *nullprov = NULL;
static OSSL_PROVIDER *deflprov = NULL;
static OSSL_PROVIDER *keyprov = NULL;
#ifndef OPENSSL_NO_EC
static BN_CTX *bnctx = NULL;
static OSSL_PARAM_BLD *bld_prime_nc = NULL;
static OSSL_PARAM_BLD *bld_prime = NULL;
static OSSL_PARAM *ec_explicit_prime_params_nc = NULL;
static OSSL_PARAM *ec_explicit_prime_params_explicit = NULL;
# ifndef OPENSSL_NO_EC2M
static OSSL_PARAM_BLD *bld_tri_nc = NULL;
static OSSL_PARAM_BLD *bld_tri = NULL;
static OSSL_PARAM *ec_explicit_tri_params_nc = NULL;
static OSSL_PARAM *ec_explicit_tri_params_explicit = NULL;
# endif
#endif
#ifndef OPENSSL_NO_KEYPARAMS
static EVP_PKEY *make_template(const char *type, OSSL_PARAM *genparams)
{
EVP_PKEY *pkey = NULL;
EVP_PKEY_CTX *ctx = NULL;
# ifndef OPENSSL_NO_DH
/*
* Use 512-bit DH(X) keys with predetermined parameters for efficiency,
* for testing only. Use a minimum key size of 2048 for security purposes.
*/
if (strcmp(type, "DH") == 0)
return get_dh512(keyctx);
if (strcmp(type, "X9.42 DH") == 0)
return get_dhx512(keyctx);
# endif
/*
* No real need to check the errors other than for the cascade
* effect. |pkey| will simply remain NULL if something goes wrong.
*/
(void)((ctx = EVP_PKEY_CTX_new_from_name(keyctx, type, testpropq)) != NULL
&& EVP_PKEY_paramgen_init(ctx) > 0
&& (genparams == NULL
|| EVP_PKEY_CTX_set_params(ctx, genparams) > 0)
&& EVP_PKEY_generate(ctx, &pkey) > 0);
EVP_PKEY_CTX_free(ctx);
return pkey;
}
#endif
#if !defined(OPENSSL_NO_DH) || !defined(OPENSSL_NO_DSA) || !defined(OPENSSL_NO_EC)
static EVP_PKEY *make_key(const char *type, EVP_PKEY *template,
OSSL_PARAM *genparams)
{
EVP_PKEY *pkey = NULL;
EVP_PKEY_CTX *ctx =
template != NULL
? EVP_PKEY_CTX_new_from_pkey(keyctx, template, testpropq)
: EVP_PKEY_CTX_new_from_name(keyctx, type, testpropq);
/*
* No real need to check the errors other than for the cascade
* effect. |pkey| will simply remain NULL if something goes wrong.
*/
(void)(ctx != NULL
&& EVP_PKEY_keygen_init(ctx) > 0
&& (genparams == NULL
|| EVP_PKEY_CTX_set_params(ctx, genparams) > 0)
&& EVP_PKEY_keygen(ctx, &pkey) > 0);
EVP_PKEY_CTX_free(ctx);
return pkey;
}
#endif
/* Main test driver */
typedef int (encoder)(const char *file, const int line,
void **encoded, long *encoded_len,
void *object, int selection,
const char *output_type, const char *output_structure,
const char *pass, const char *pcipher);
typedef int (decoder)(const char *file, const int line,
void **object, void *encoded, long encoded_len,
const char *input_type, const char *structure_type,
const char *keytype, int selection, const char *pass);
typedef int (tester)(const char *file, const int line,
const void *data1, size_t data1_len,
const void *data2, size_t data2_len);
typedef int (checker)(const char *file, const int line,
const char *type, const void *data, size_t data_len);
typedef void (dumper)(const char *label, const void *data, size_t data_len);
#define FLAG_DECODE_WITH_TYPE 0x0001
#define FLAG_FAIL_IF_FIPS 0x0002
static int test_encode_decode(const char *file, const int line,
const char *type, EVP_PKEY *pkey,
int selection, const char *output_type,
const char *output_structure,
const char *pass, const char *pcipher,
encoder *encode_cb, decoder *decode_cb,
tester *test_cb, checker *check_cb,
dumper *dump_cb, int flags)
{
void *encoded = NULL;
long encoded_len = 0;
EVP_PKEY *pkey2 = NULL;
EVP_PKEY *pkey3 = NULL;
void *encoded2 = NULL;
long encoded2_len = 0;
int ok = 0;
/*
* Encode |pkey|, decode the result into |pkey2|, and finish off by
* encoding |pkey2| as well. That last encoding is for checking and
* dumping purposes.
*/
if (!TEST_true(encode_cb(file, line, &encoded, &encoded_len, pkey, selection,
output_type, output_structure, pass, pcipher)))
goto end;
if ((flags & FLAG_FAIL_IF_FIPS) != 0 && is_fips && !is_fips_3_0_0) {
if (TEST_false(decode_cb(file, line, (void **)&pkey2, encoded,
encoded_len, output_type, output_structure,
(flags & FLAG_DECODE_WITH_TYPE ? type : NULL),
selection, pass)))
ok = 1;
goto end;
}
if (!TEST_true(check_cb(file, line, type, encoded, encoded_len))
|| !TEST_true(decode_cb(file, line, (void **)&pkey2, encoded, encoded_len,
output_type, output_structure,
(flags & FLAG_DECODE_WITH_TYPE ? type : NULL),
selection, pass))
|| ((output_structure == NULL
|| strcmp(output_structure, "type-specific") != 0)
&& !TEST_true(decode_cb(file, line, (void **)&pkey3, encoded, encoded_len,
output_type, output_structure,
(flags & FLAG_DECODE_WITH_TYPE ? type : NULL),
0, pass)))
|| !TEST_true(encode_cb(file, line, &encoded2, &encoded2_len, pkey2, selection,
output_type, output_structure, pass, pcipher)))
goto end;
if (selection == OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS) {
if (!TEST_int_eq(EVP_PKEY_parameters_eq(pkey, pkey2), 1)
|| (pkey3 != NULL
&& !TEST_int_eq(EVP_PKEY_parameters_eq(pkey, pkey3), 1)))
goto end;
} else {
if (!TEST_int_eq(EVP_PKEY_eq(pkey, pkey2), 1)
|| (pkey3 != NULL
&& !TEST_int_eq(EVP_PKEY_eq(pkey, pkey3), 1)))
goto end;
}
/*
* Double check the encoding, but only for unprotected keys,
* as protected keys have a random component, which makes the output
* differ.
*/
if ((pass == NULL && pcipher == NULL)
&& !test_cb(file, line, encoded, encoded_len, encoded2, encoded2_len))
goto end;
ok = 1;
end:
if (!ok) {
if (encoded != NULL && encoded_len != 0)
dump_cb("|pkey| encoded", encoded, encoded_len);
if (encoded2 != NULL && encoded2_len != 0)
dump_cb("|pkey2| encoded", encoded2, encoded2_len);
}
OPENSSL_free(encoded);
OPENSSL_free(encoded2);
EVP_PKEY_free(pkey2);
EVP_PKEY_free(pkey3);
return ok;
}
/* Encoding and decoding methods */
static int encode_EVP_PKEY_prov(const char *file, const int line,
void **encoded, long *encoded_len,
void *object, int selection,
const char *output_type,
const char *output_structure,
const char *pass, const char *pcipher)
{
EVP_PKEY *pkey = object;
OSSL_ENCODER_CTX *ectx = NULL;
BIO *mem_ser = NULL;
BUF_MEM *mem_buf = NULL;
const unsigned char *upass = (const unsigned char *)pass;
int ok = 0;
if (!TEST_FL_ptr(ectx = OSSL_ENCODER_CTX_new_for_pkey(pkey, selection,
output_type,
output_structure,
testpropq))
|| !TEST_FL_int_gt(OSSL_ENCODER_CTX_get_num_encoders(ectx), 0)
|| (pass != NULL
&& !TEST_FL_true(OSSL_ENCODER_CTX_set_passphrase(ectx, upass,
strlen(pass))))
|| (pcipher != NULL
&& !TEST_FL_true(OSSL_ENCODER_CTX_set_cipher(ectx, pcipher, NULL)))
|| !TEST_FL_ptr(mem_ser = BIO_new(BIO_s_mem()))
|| !TEST_FL_true(OSSL_ENCODER_to_bio(ectx, mem_ser))
|| !TEST_FL_true(BIO_get_mem_ptr(mem_ser, &mem_buf) > 0)
|| !TEST_FL_ptr(*encoded = mem_buf->data)
|| !TEST_FL_long_gt(*encoded_len = mem_buf->length, 0))
goto end;
/* Detach the encoded output */
mem_buf->data = NULL;
mem_buf->length = 0;
ok = 1;
end:
BIO_free(mem_ser);
OSSL_ENCODER_CTX_free(ectx);
return ok;
}
static int decode_EVP_PKEY_prov(const char *file, const int line,
void **object, void *encoded, long encoded_len,
const char *input_type,
const char *structure_type,
const char *keytype, int selection,
const char *pass)
{
EVP_PKEY *pkey = NULL, *testpkey = NULL;
OSSL_DECODER_CTX *dctx = NULL;
BIO *encoded_bio = NULL;
const unsigned char *upass = (const unsigned char *)pass;
int ok = 0;
int i;
const char *badtype;
if (strcmp(input_type, "DER") == 0)
badtype = "PEM";
else
badtype = "DER";
if (!TEST_FL_ptr(encoded_bio = BIO_new_mem_buf(encoded, encoded_len)))
goto end;
/*
* We attempt the decode 3 times. The first time we provide the expected
* starting input type. The second time we provide NULL for the starting
* type. The third time we provide a bad starting input type.
* The bad starting input type should fail. The other two should succeed
* and produce the same result.
*/
for (i = 0; i < 3; i++) {
const char *testtype = (i == 0) ? input_type
: ((i == 1) ? NULL : badtype);
if (!TEST_FL_ptr(dctx = OSSL_DECODER_CTX_new_for_pkey(&testpkey,
testtype,
structure_type,
keytype,
selection,
testctx, testpropq))
|| (pass != NULL
&& !OSSL_DECODER_CTX_set_passphrase(dctx, upass, strlen(pass)))
|| !TEST_FL_int_gt(BIO_reset(encoded_bio), 0)
/* We expect to fail when using a bad input type */
|| !TEST_FL_int_eq(OSSL_DECODER_from_bio(dctx, encoded_bio),
(i == 2) ? 0 : 1))
goto end;
OSSL_DECODER_CTX_free(dctx);
dctx = NULL;
if (i == 0) {
pkey = testpkey;
testpkey = NULL;
} else if (i == 1) {
if (selection == OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS) {
if (!TEST_FL_int_eq(EVP_PKEY_parameters_eq(pkey, testpkey), 1))
goto end;
} else {
if (!TEST_FL_int_eq(EVP_PKEY_eq(pkey, testpkey), 1))
goto end;
}
}
}
ok = 1;
*object = pkey;
pkey = NULL;
end:
EVP_PKEY_free(pkey);
EVP_PKEY_free(testpkey);
BIO_free(encoded_bio);
OSSL_DECODER_CTX_free(dctx);
return ok;
}
static int encode_EVP_PKEY_legacy_PEM(const char *file, const int line,
void **encoded, long *encoded_len,
void *object, ossl_unused int selection,
ossl_unused const char *output_type,
ossl_unused const char *output_structure,
const char *pass, const char *pcipher)
{
EVP_PKEY *pkey = object;
EVP_CIPHER *cipher = NULL;
BIO *mem_ser = NULL;
BUF_MEM *mem_buf = NULL;
const unsigned char *upass = (const unsigned char *)pass;
size_t passlen = 0;
int ok = 0;
if (pcipher != NULL && pass != NULL) {
passlen = strlen(pass);
if (!TEST_FL_ptr(cipher = EVP_CIPHER_fetch(testctx, pcipher, testpropq)))
goto end;
}
if (!TEST_FL_ptr(mem_ser = BIO_new(BIO_s_mem()))
|| !TEST_FL_true(PEM_write_bio_PrivateKey_traditional(mem_ser, pkey,
cipher,
upass, passlen,
NULL, NULL))
|| !TEST_FL_true(BIO_get_mem_ptr(mem_ser, &mem_buf) > 0)
|| !TEST_FL_ptr(*encoded = mem_buf->data)
|| !TEST_FL_long_gt(*encoded_len = mem_buf->length, 0))
goto end;
/* Detach the encoded output */
mem_buf->data = NULL;
mem_buf->length = 0;
ok = 1;
end:
BIO_free(mem_ser);
EVP_CIPHER_free(cipher);
return ok;
}
static int encode_EVP_PKEY_MSBLOB(const char *file, const int line,
void **encoded, long *encoded_len,
void *object, int selection,
ossl_unused const char *output_type,
ossl_unused const char *output_structure,
ossl_unused const char *pass,
ossl_unused const char *pcipher)
{
EVP_PKEY *pkey = object;
BIO *mem_ser = NULL;
BUF_MEM *mem_buf = NULL;
int ok = 0;
if (!TEST_FL_ptr(mem_ser = BIO_new(BIO_s_mem())))
goto end;
if ((selection & OSSL_KEYMGMT_SELECT_PRIVATE_KEY) != 0) {
if (!TEST_FL_int_ge(i2b_PrivateKey_bio(mem_ser, pkey), 0))
goto end;
} else {
if (!TEST_FL_int_ge(i2b_PublicKey_bio(mem_ser, pkey), 0))
goto end;
}
if (!TEST_FL_true(BIO_get_mem_ptr(mem_ser, &mem_buf) > 0)
|| !TEST_FL_ptr(*encoded = mem_buf->data)
|| !TEST_FL_long_gt(*encoded_len = mem_buf->length, 0))
goto end;
/* Detach the encoded output */
mem_buf->data = NULL;
mem_buf->length = 0;
ok = 1;
end:
BIO_free(mem_ser);
return ok;
}
static pem_password_cb pass_pw;
static int pass_pw(char *buf, int size, int rwflag, void *userdata)
{
OPENSSL_strlcpy(buf, userdata, size);
return strlen(userdata);
}
static int encode_EVP_PKEY_PVK(const char *file, const int line,
void **encoded, long *encoded_len,
void *object, int selection,
ossl_unused const char *output_type,
ossl_unused const char *output_structure,
const char *pass,
ossl_unused const char *pcipher)
{
EVP_PKEY *pkey = object;
BIO *mem_ser = NULL;
BUF_MEM *mem_buf = NULL;
int enc = (pass != NULL);
int ok = 0;
if (!TEST_FL_true(ossl_assert((selection
& OSSL_KEYMGMT_SELECT_PRIVATE_KEY) != 0))
|| !TEST_FL_ptr(mem_ser = BIO_new(BIO_s_mem()))
|| !TEST_FL_int_ge(i2b_PVK_bio_ex(mem_ser, pkey, enc,
pass_pw, (void *)pass, testctx, testpropq), 0)
|| !TEST_FL_true(BIO_get_mem_ptr(mem_ser, &mem_buf) > 0)
|| !TEST_FL_ptr(*encoded = mem_buf->data)
|| !TEST_FL_long_gt(*encoded_len = mem_buf->length, 0))
goto end;
/* Detach the encoded output */
mem_buf->data = NULL;
mem_buf->length = 0;
ok = 1;
end:
BIO_free(mem_ser);
return ok;
}
static int test_text(const char *file, const int line,
const void *data1, size_t data1_len,
const void *data2, size_t data2_len)
{
return TEST_FL_strn2_eq(data1, data1_len, data2, data2_len);
}
static int test_mem(const char *file, const int line,
const void *data1, size_t data1_len,
const void *data2, size_t data2_len)
{
return TEST_FL_mem_eq(data1, data1_len, data2, data2_len);
}
/* Test cases and their dumpers / checkers */
static void collect_name(const char *name, void *arg)
{
char **namelist = arg;
char *new_namelist;
size_t space;
space = strlen(name);
if (*namelist != NULL)
space += strlen(*namelist) + 2 /* for comma and space */;
space++; /* for terminating null byte */
new_namelist = OPENSSL_realloc(*namelist, space);
if (new_namelist == NULL)
return;
if (*namelist != NULL) {
strcat(new_namelist, ", ");
strcat(new_namelist, name);
} else {
strcpy(new_namelist, name);
}
*namelist = new_namelist;
}
static void dump_der(const char *label, const void *data, size_t data_len)
{
test_output_memory(label, data, data_len);
}
static void dump_pem(const char *label, const void *data, size_t data_len)
{
test_output_string(label, data, data_len - 1);
}
static int check_unprotected_PKCS8_DER(const char *file, const int line,
const char *type,
const void *data, size_t data_len)
{
const unsigned char *datap = data;
PKCS8_PRIV_KEY_INFO *p8inf =
d2i_PKCS8_PRIV_KEY_INFO(NULL, &datap, data_len);
int ok = 0;
if (TEST_FL_ptr(p8inf)) {
EVP_PKEY *pkey = EVP_PKCS82PKEY_ex(p8inf, testctx, testpropq);
char *namelist = NULL;
if (TEST_FL_ptr(pkey)) {
if (!(ok = TEST_FL_true(EVP_PKEY_is_a(pkey, type)))) {
EVP_PKEY_type_names_do_all(pkey, collect_name, &namelist);
if (namelist != NULL)
TEST_note("%s isn't any of %s", type, namelist);
OPENSSL_free(namelist);
}
ok = ok && TEST_FL_true(evp_pkey_is_provided(pkey));
EVP_PKEY_free(pkey);
}
}
PKCS8_PRIV_KEY_INFO_free(p8inf);
return ok;
}
static int test_unprotected_via_DER(const char *type, EVP_PKEY *key, int fips)
{
return test_encode_decode(__FILE__, __LINE__, type, key,
OSSL_KEYMGMT_SELECT_KEYPAIR
| OSSL_KEYMGMT_SELECT_ALL_PARAMETERS,
"DER", "PrivateKeyInfo", NULL, NULL,
encode_EVP_PKEY_prov, decode_EVP_PKEY_prov,
test_mem, check_unprotected_PKCS8_DER,
dump_der, fips ? 0 : FLAG_FAIL_IF_FIPS);
}
static int check_unprotected_PKCS8_PEM(const char *file, const int line,
const char *type,
const void *data, size_t data_len)
{
static const char expected_pem_header[] =
"-----BEGIN " PEM_STRING_PKCS8INF "-----";
return TEST_FL_strn_eq(data, expected_pem_header,
sizeof(expected_pem_header) - 1);
}
static int test_unprotected_via_PEM(const char *type, EVP_PKEY *key, int fips)
{
return test_encode_decode(__FILE__, __LINE__, type, key,
OSSL_KEYMGMT_SELECT_KEYPAIR
| OSSL_KEYMGMT_SELECT_ALL_PARAMETERS,
"PEM", "PrivateKeyInfo", NULL, NULL,
encode_EVP_PKEY_prov, decode_EVP_PKEY_prov,
test_text, check_unprotected_PKCS8_PEM,
dump_pem, fips ? 0 : FLAG_FAIL_IF_FIPS);
}
#ifndef OPENSSL_NO_KEYPARAMS
static int check_params_DER(const char *file, const int line,
const char *type, const void *data, size_t data_len)
{
const unsigned char *datap = data;
int ok = 0;
int itype = NID_undef;
EVP_PKEY *pkey = NULL;
if (strcmp(type, "DH") == 0)
itype = EVP_PKEY_DH;
else if (strcmp(type, "X9.42 DH") == 0)
itype = EVP_PKEY_DHX;
else if (strcmp(type, "DSA") == 0)
itype = EVP_PKEY_DSA;
else if (strcmp(type, "EC") == 0)
itype = EVP_PKEY_EC;
if (itype != NID_undef) {
pkey = d2i_KeyParams(itype, NULL, &datap, data_len);
ok = (pkey != NULL);
EVP_PKEY_free(pkey);
}
return ok;
}
static int check_params_PEM(const char *file, const int line,
const char *type,
const void *data, size_t data_len)
{
static char expected_pem_header[80];
return
TEST_FL_int_gt(BIO_snprintf(expected_pem_header,
sizeof(expected_pem_header),
"-----BEGIN %s PARAMETERS-----", type), 0)
&& TEST_FL_strn_eq(data, expected_pem_header, strlen(expected_pem_header));
}
static int test_params_via_DER(const char *type, EVP_PKEY *key)
{
return test_encode_decode(__FILE__, __LINE__, type, key, OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS,
"DER", "type-specific", NULL, NULL,
encode_EVP_PKEY_prov, decode_EVP_PKEY_prov,
test_mem, check_params_DER,
dump_der, FLAG_DECODE_WITH_TYPE);
}
static int test_params_via_PEM(const char *type, EVP_PKEY *key)
{
return test_encode_decode(__FILE__, __LINE__, type, key, OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS,
"PEM", "type-specific", NULL, NULL,
encode_EVP_PKEY_prov, decode_EVP_PKEY_prov,
test_text, check_params_PEM,
dump_pem, 0);
}
#endif /* !OPENSSL_NO_KEYPARAMS */
static int check_unprotected_legacy_PEM(const char *file, const int line,
const char *type,
const void *data, size_t data_len)
{
static char expected_pem_header[80];
return
TEST_FL_int_gt(BIO_snprintf(expected_pem_header,
sizeof(expected_pem_header),
"-----BEGIN %s PRIVATE KEY-----", type), 0)
&& TEST_FL_strn_eq(data, expected_pem_header, strlen(expected_pem_header));
}
static int test_unprotected_via_legacy_PEM(const char *type, EVP_PKEY *key)
{
if (!default_libctx || is_fips)
return TEST_skip("Test not available if using a non-default library context or FIPS provider");
return test_encode_decode(__FILE__, __LINE__, type, key,
OSSL_KEYMGMT_SELECT_KEYPAIR
| OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS,
"PEM", "type-specific", NULL, NULL,
encode_EVP_PKEY_legacy_PEM, decode_EVP_PKEY_prov,
test_text, check_unprotected_legacy_PEM,
dump_pem, 0);
}
static int check_MSBLOB(const char *file, const int line,
const char *type, const void *data, size_t data_len)
{
const unsigned char *datap = data;
EVP_PKEY *pkey = b2i_PrivateKey(&datap, data_len);
int ok = TEST_FL_ptr(pkey);
EVP_PKEY_free(pkey);
return ok;
}
static int test_unprotected_via_MSBLOB(const char *type, EVP_PKEY *key)
{
return test_encode_decode(__FILE__, __LINE__, type, key,
OSSL_KEYMGMT_SELECT_KEYPAIR
| OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS,
"MSBLOB", NULL, NULL, NULL,
encode_EVP_PKEY_MSBLOB, decode_EVP_PKEY_prov,
test_mem, check_MSBLOB,
dump_der, 0);
}
static int check_PVK(const char *file, const int line,
const char *type, const void *data, size_t data_len)
{
const unsigned char *in = data;
unsigned int saltlen = 0, keylen = 0;
int ok = ossl_do_PVK_header(&in, data_len, 0, &saltlen, &keylen);
return ok;
}
static int test_unprotected_via_PVK(const char *type, EVP_PKEY *key)
{
return test_encode_decode(__FILE__, __LINE__, type, key,
OSSL_KEYMGMT_SELECT_KEYPAIR
| OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS,
"PVK", NULL, NULL, NULL,
encode_EVP_PKEY_PVK, decode_EVP_PKEY_prov,
test_mem, check_PVK,
dump_der, 0);
}
static const char *pass_cipher = "AES-256-CBC";
static const char *pass = "the holy handgrenade of antioch";
static int check_protected_PKCS8_DER(const char *file, const int line,
const char *type,
const void *data, size_t data_len)
{
const unsigned char *datap = data;
X509_SIG *p8 = d2i_X509_SIG(NULL, &datap, data_len);
int ok = TEST_FL_ptr(p8);
X509_SIG_free(p8);
return ok;
}
static int test_protected_via_DER(const char *type, EVP_PKEY *key, int fips)
{
return test_encode_decode(__FILE__, __LINE__, type, key,
OSSL_KEYMGMT_SELECT_KEYPAIR
| OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS,
"DER", "EncryptedPrivateKeyInfo",
pass, pass_cipher,
encode_EVP_PKEY_prov, decode_EVP_PKEY_prov,
test_mem, check_protected_PKCS8_DER,
dump_der, fips ? 0 : FLAG_FAIL_IF_FIPS);
}
static int check_protected_PKCS8_PEM(const char *file, const int line,
const char *type,
const void *data, size_t data_len)
{
static const char expected_pem_header[] =
"-----BEGIN " PEM_STRING_PKCS8 "-----";
return TEST_FL_strn_eq(data, expected_pem_header,
sizeof(expected_pem_header) - 1);
}
static int test_protected_via_PEM(const char *type, EVP_PKEY *key, int fips)
{
return test_encode_decode(__FILE__, __LINE__, type, key,
OSSL_KEYMGMT_SELECT_KEYPAIR
| OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS,
"PEM", "EncryptedPrivateKeyInfo",
pass, pass_cipher,
encode_EVP_PKEY_prov, decode_EVP_PKEY_prov,
test_text, check_protected_PKCS8_PEM,
dump_pem, fips ? 0 : FLAG_FAIL_IF_FIPS);
}
static int check_protected_legacy_PEM(const char *file, const int line,
const char *type,
const void *data, size_t data_len)
{
static char expected_pem_header[80];
return
TEST_FL_int_gt(BIO_snprintf(expected_pem_header,
sizeof(expected_pem_header),
"-----BEGIN %s PRIVATE KEY-----", type), 0)
&& TEST_FL_strn_eq(data, expected_pem_header, strlen(expected_pem_header))
&& TEST_FL_ptr(strstr(data, "\nDEK-Info: "));
}
static int test_protected_via_legacy_PEM(const char *type, EVP_PKEY *key)
{
if (!default_libctx || is_fips)
return TEST_skip("Test not available if using a non-default library context or FIPS provider");
return test_encode_decode(__FILE__, __LINE__, type, key,
OSSL_KEYMGMT_SELECT_KEYPAIR
| OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS,
"PEM", "type-specific", pass, pass_cipher,
encode_EVP_PKEY_legacy_PEM, decode_EVP_PKEY_prov,
test_text, check_protected_legacy_PEM,
dump_pem, 0);
}
#ifndef OPENSSL_NO_RC4
static int test_protected_via_PVK(const char *type, EVP_PKEY *key)
{
int ret = 0;
OSSL_PROVIDER *lgcyprov = OSSL_PROVIDER_load(testctx, "legacy");
if (lgcyprov == NULL)
return TEST_skip("Legacy provider not available");
ret = test_encode_decode(__FILE__, __LINE__, type, key,
OSSL_KEYMGMT_SELECT_KEYPAIR
| OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS,
"PVK", NULL, pass, NULL,
encode_EVP_PKEY_PVK, decode_EVP_PKEY_prov,
test_mem, check_PVK, dump_der, 0);
OSSL_PROVIDER_unload(lgcyprov);
return ret;
}
#endif
static int check_public_DER(const char *file, const int line,
const char *type, const void *data, size_t data_len)
{
const unsigned char *datap = data;
EVP_PKEY *pkey = d2i_PUBKEY_ex(NULL, &datap, data_len, testctx, testpropq);
int ok = (TEST_FL_ptr(pkey) && TEST_FL_true(EVP_PKEY_is_a(pkey, type)));
EVP_PKEY_free(pkey);
return ok;
}
static int test_public_via_DER(const char *type, EVP_PKEY *key, int fips)
{
return test_encode_decode(__FILE__, __LINE__, type, key,
OSSL_KEYMGMT_SELECT_PUBLIC_KEY
| OSSL_KEYMGMT_SELECT_ALL_PARAMETERS,
"DER", "SubjectPublicKeyInfo", NULL, NULL,
encode_EVP_PKEY_prov, decode_EVP_PKEY_prov,
test_mem, check_public_DER, dump_der,
fips ? 0 : FLAG_FAIL_IF_FIPS);
}
static int check_public_PEM(const char *file, const int line,
const char *type, const void *data, size_t data_len)
{
static const char expected_pem_header[] =
"-----BEGIN " PEM_STRING_PUBLIC "-----";
return
TEST_FL_strn_eq(data, expected_pem_header,
sizeof(expected_pem_header) - 1);
}
static int test_public_via_PEM(const char *type, EVP_PKEY *key, int fips)
{
return test_encode_decode(__FILE__, __LINE__, type, key,
OSSL_KEYMGMT_SELECT_PUBLIC_KEY
| OSSL_KEYMGMT_SELECT_ALL_PARAMETERS,
"PEM", "SubjectPublicKeyInfo", NULL, NULL,
encode_EVP_PKEY_prov, decode_EVP_PKEY_prov,
test_text, check_public_PEM, dump_pem,
fips ? 0 : FLAG_FAIL_IF_FIPS);
}
static int check_public_MSBLOB(const char *file, const int line,
const char *type,
const void *data, size_t data_len)
{
const unsigned char *datap = data;
EVP_PKEY *pkey = b2i_PublicKey(&datap, data_len);
int ok = TEST_FL_ptr(pkey);
EVP_PKEY_free(pkey);
return ok;
}
static int test_public_via_MSBLOB(const char *type, EVP_PKEY *key)
{
return test_encode_decode(__FILE__, __LINE__, type, key, OSSL_KEYMGMT_SELECT_PUBLIC_KEY
| OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS,
"MSBLOB", NULL, NULL, NULL,
encode_EVP_PKEY_MSBLOB, decode_EVP_PKEY_prov,
test_mem, check_public_MSBLOB, dump_der, 0);
}
#define KEYS(KEYTYPE) \
static EVP_PKEY *key_##KEYTYPE = NULL
#define MAKE_KEYS(KEYTYPE, KEYTYPEstr, params) \
ok = ok \
&& TEST_ptr(key_##KEYTYPE = make_key(KEYTYPEstr, NULL, params))
#define FREE_KEYS(KEYTYPE) \
EVP_PKEY_free(key_##KEYTYPE); \
#define DOMAIN_KEYS(KEYTYPE) \
static EVP_PKEY *template_##KEYTYPE = NULL; \
static EVP_PKEY *key_##KEYTYPE = NULL
#define MAKE_DOMAIN_KEYS(KEYTYPE, KEYTYPEstr, params) \
ok = ok \
&& TEST_ptr(template_##KEYTYPE = \
make_template(KEYTYPEstr, params)) \
&& TEST_ptr(key_##KEYTYPE = \
make_key(KEYTYPEstr, template_##KEYTYPE, NULL))
#define FREE_DOMAIN_KEYS(KEYTYPE) \
EVP_PKEY_free(template_##KEYTYPE); \
EVP_PKEY_free(key_##KEYTYPE)
#define IMPLEMENT_TEST_SUITE(KEYTYPE, KEYTYPEstr, fips) \
static int test_unprotected_##KEYTYPE##_via_DER(void) \
{ \
return test_unprotected_via_DER(KEYTYPEstr, key_##KEYTYPE, fips); \
} \
static int test_unprotected_##KEYTYPE##_via_PEM(void) \
{ \
return test_unprotected_via_PEM(KEYTYPEstr, key_##KEYTYPE, fips); \
} \
static int test_protected_##KEYTYPE##_via_DER(void) \
{ \
return test_protected_via_DER(KEYTYPEstr, key_##KEYTYPE, fips); \
} \
static int test_protected_##KEYTYPE##_via_PEM(void) \
{ \
return test_protected_via_PEM(KEYTYPEstr, key_##KEYTYPE, fips); \
} \
static int test_public_##KEYTYPE##_via_DER(void) \
{ \
return test_public_via_DER(KEYTYPEstr, key_##KEYTYPE, fips); \
} \
static int test_public_##KEYTYPE##_via_PEM(void) \
{ \
return test_public_via_PEM(KEYTYPEstr, key_##KEYTYPE, fips); \
}
#define ADD_TEST_SUITE(KEYTYPE) \
ADD_TEST(test_unprotected_##KEYTYPE##_via_DER); \
ADD_TEST(test_unprotected_##KEYTYPE##_via_PEM); \
ADD_TEST(test_protected_##KEYTYPE##_via_DER); \
ADD_TEST(test_protected_##KEYTYPE##_via_PEM); \
ADD_TEST(test_public_##KEYTYPE##_via_DER); \
ADD_TEST(test_public_##KEYTYPE##_via_PEM)
#define IMPLEMENT_TEST_SUITE_PARAMS(KEYTYPE, KEYTYPEstr) \
static int test_params_##KEYTYPE##_via_DER(void) \
{ \
return test_params_via_DER(KEYTYPEstr, key_##KEYTYPE); \
} \
static int test_params_##KEYTYPE##_via_PEM(void) \
{ \
return test_params_via_PEM(KEYTYPEstr, key_##KEYTYPE); \
}
#define ADD_TEST_SUITE_PARAMS(KEYTYPE) \
ADD_TEST(test_params_##KEYTYPE##_via_DER); \
ADD_TEST(test_params_##KEYTYPE##_via_PEM)
#define IMPLEMENT_TEST_SUITE_LEGACY(KEYTYPE, KEYTYPEstr) \
static int test_unprotected_##KEYTYPE##_via_legacy_PEM(void) \
{ \
return \
test_unprotected_via_legacy_PEM(KEYTYPEstr, key_##KEYTYPE); \
} \
static int test_protected_##KEYTYPE##_via_legacy_PEM(void) \
{ \
return \
test_protected_via_legacy_PEM(KEYTYPEstr, key_##KEYTYPE); \
}
#define ADD_TEST_SUITE_LEGACY(KEYTYPE) \
ADD_TEST(test_unprotected_##KEYTYPE##_via_legacy_PEM); \
ADD_TEST(test_protected_##KEYTYPE##_via_legacy_PEM)
#define IMPLEMENT_TEST_SUITE_MSBLOB(KEYTYPE, KEYTYPEstr) \
static int test_unprotected_##KEYTYPE##_via_MSBLOB(void) \
{ \
return test_unprotected_via_MSBLOB(KEYTYPEstr, key_##KEYTYPE); \
} \
static int test_public_##KEYTYPE##_via_MSBLOB(void) \
{ \
return test_public_via_MSBLOB(KEYTYPEstr, key_##KEYTYPE); \
}
#define ADD_TEST_SUITE_MSBLOB(KEYTYPE) \
ADD_TEST(test_unprotected_##KEYTYPE##_via_MSBLOB); \
ADD_TEST(test_public_##KEYTYPE##_via_MSBLOB)
#define IMPLEMENT_TEST_SUITE_UNPROTECTED_PVK(KEYTYPE, KEYTYPEstr) \
static int test_unprotected_##KEYTYPE##_via_PVK(void) \
{ \
return test_unprotected_via_PVK(KEYTYPEstr, key_##KEYTYPE); \
}
# define ADD_TEST_SUITE_UNPROTECTED_PVK(KEYTYPE) \
ADD_TEST(test_unprotected_##KEYTYPE##_via_PVK)
#ifndef OPENSSL_NO_RC4
# define IMPLEMENT_TEST_SUITE_PROTECTED_PVK(KEYTYPE, KEYTYPEstr) \
static int test_protected_##KEYTYPE##_via_PVK(void) \
{ \
return test_protected_via_PVK(KEYTYPEstr, key_##KEYTYPE); \
}
# define ADD_TEST_SUITE_PROTECTED_PVK(KEYTYPE) \
ADD_TEST(test_protected_##KEYTYPE##_via_PVK)
#endif
#ifndef OPENSSL_NO_DH
DOMAIN_KEYS(DH);
IMPLEMENT_TEST_SUITE(DH, "DH", 1)
IMPLEMENT_TEST_SUITE_PARAMS(DH, "DH")
DOMAIN_KEYS(DHX);
IMPLEMENT_TEST_SUITE(DHX, "X9.42 DH", 1)
IMPLEMENT_TEST_SUITE_PARAMS(DHX, "X9.42 DH")
/*
* DH has no support for PEM_write_bio_PrivateKey_traditional(),
* so no legacy tests.
*/
#endif
#ifndef OPENSSL_NO_DSA
DOMAIN_KEYS(DSA);
IMPLEMENT_TEST_SUITE(DSA, "DSA", 1)
IMPLEMENT_TEST_SUITE_PARAMS(DSA, "DSA")
IMPLEMENT_TEST_SUITE_LEGACY(DSA, "DSA")
IMPLEMENT_TEST_SUITE_MSBLOB(DSA, "DSA")
IMPLEMENT_TEST_SUITE_UNPROTECTED_PVK(DSA, "DSA")
# ifndef OPENSSL_NO_RC4
IMPLEMENT_TEST_SUITE_PROTECTED_PVK(DSA, "DSA")
# endif
#endif
#ifndef OPENSSL_NO_EC
DOMAIN_KEYS(EC);
IMPLEMENT_TEST_SUITE(EC, "EC", 1)
IMPLEMENT_TEST_SUITE_PARAMS(EC, "EC")
IMPLEMENT_TEST_SUITE_LEGACY(EC, "EC")
DOMAIN_KEYS(ECExplicitPrimeNamedCurve);
IMPLEMENT_TEST_SUITE(ECExplicitPrimeNamedCurve, "EC", 1)
IMPLEMENT_TEST_SUITE_LEGACY(ECExplicitPrimeNamedCurve, "EC")
DOMAIN_KEYS(ECExplicitPrime2G);
IMPLEMENT_TEST_SUITE(ECExplicitPrime2G, "EC", 0)
IMPLEMENT_TEST_SUITE_LEGACY(ECExplicitPrime2G, "EC")
# ifndef OPENSSL_NO_EC2M
DOMAIN_KEYS(ECExplicitTriNamedCurve);
IMPLEMENT_TEST_SUITE(ECExplicitTriNamedCurve, "EC", 1)
IMPLEMENT_TEST_SUITE_LEGACY(ECExplicitTriNamedCurve, "EC")
DOMAIN_KEYS(ECExplicitTri2G);
IMPLEMENT_TEST_SUITE(ECExplicitTri2G, "EC", 0)
IMPLEMENT_TEST_SUITE_LEGACY(ECExplicitTri2G, "EC")
# endif
+# ifndef OPENSSL_NO_SM2
+KEYS(SM2);
+IMPLEMENT_TEST_SUITE(SM2, "SM2", 0)
+# endif
KEYS(ED25519);
IMPLEMENT_TEST_SUITE(ED25519, "ED25519", 1)
KEYS(ED448);
IMPLEMENT_TEST_SUITE(ED448, "ED448", 1)
KEYS(X25519);
IMPLEMENT_TEST_SUITE(X25519, "X25519", 1)
KEYS(X448);
IMPLEMENT_TEST_SUITE(X448, "X448", 1)
/*
* ED25519, ED448, X25519 and X448 have no support for
* PEM_write_bio_PrivateKey_traditional(), so no legacy tests.
*/
#endif
KEYS(RSA);
IMPLEMENT_TEST_SUITE(RSA, "RSA", 1)
IMPLEMENT_TEST_SUITE_LEGACY(RSA, "RSA")
KEYS(RSA_PSS);
IMPLEMENT_TEST_SUITE(RSA_PSS, "RSA-PSS", 1)
/*
* RSA-PSS has no support for PEM_write_bio_PrivateKey_traditional(),
* so no legacy tests.
*/
IMPLEMENT_TEST_SUITE_MSBLOB(RSA, "RSA")
IMPLEMENT_TEST_SUITE_UNPROTECTED_PVK(RSA, "RSA")
#ifndef OPENSSL_NO_RC4
IMPLEMENT_TEST_SUITE_PROTECTED_PVK(RSA, "RSA")
#endif
#ifndef OPENSSL_NO_EC
/* Explicit parameters that match a named curve */
static int do_create_ec_explicit_prime_params(OSSL_PARAM_BLD *bld,
const unsigned char *gen,
size_t gen_len)
{
BIGNUM *a, *b, *prime, *order;
/* Curve prime256v1 */
static const unsigned char prime_data[] = {
0x00, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00,
0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff
};
static const unsigned char a_data[] = {
0x00, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00,
0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xfc
};
static const unsigned char b_data[] = {
0x5a, 0xc6, 0x35, 0xd8, 0xaa, 0x3a, 0x93, 0xe7,
0xb3, 0xeb, 0xbd, 0x55, 0x76, 0x98, 0x86, 0xbc,
0x65, 0x1d, 0x06, 0xb0, 0xcc, 0x53, 0xb0, 0xf6,
0x3b, 0xce, 0x3c, 0x3e, 0x27, 0xd2, 0x60, 0x4b
};
static const unsigned char seed[] = {
0xc4, 0x9d, 0x36, 0x08, 0x86, 0xe7, 0x04, 0x93,
0x6a, 0x66, 0x78, 0xe1, 0x13, 0x9d, 0x26, 0xb7,
0x81, 0x9f, 0x7e, 0x90
};
static const unsigned char order_data[] = {
0x00, 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
};
return TEST_ptr(a = BN_CTX_get(bnctx))
&& TEST_ptr(b = BN_CTX_get(bnctx))
&& TEST_ptr(prime = BN_CTX_get(bnctx))
&& TEST_ptr(order = BN_CTX_get(bnctx))
&& TEST_ptr(BN_bin2bn(prime_data, sizeof(prime_data), prime))
&& TEST_ptr(BN_bin2bn(a_data, sizeof(a_data), a))
&& TEST_ptr(BN_bin2bn(b_data, sizeof(b_data), b))
&& TEST_ptr(BN_bin2bn(order_data, sizeof(order_data), order))
&& TEST_true(OSSL_PARAM_BLD_push_utf8_string(bld,
OSSL_PKEY_PARAM_EC_FIELD_TYPE, SN_X9_62_prime_field,
0))
&& TEST_true(OSSL_PARAM_BLD_push_BN(bld, OSSL_PKEY_PARAM_EC_P, prime))
&& TEST_true(OSSL_PARAM_BLD_push_BN(bld, OSSL_PKEY_PARAM_EC_A, a))
&& TEST_true(OSSL_PARAM_BLD_push_BN(bld, OSSL_PKEY_PARAM_EC_B, b))
&& TEST_true(OSSL_PARAM_BLD_push_BN(bld,
OSSL_PKEY_PARAM_EC_ORDER, order))
&& TEST_true(OSSL_PARAM_BLD_push_octet_string(bld,
OSSL_PKEY_PARAM_EC_GENERATOR, gen, gen_len))
&& TEST_true(OSSL_PARAM_BLD_push_octet_string(bld,
OSSL_PKEY_PARAM_EC_SEED, seed, sizeof(seed)))
&& TEST_true(OSSL_PARAM_BLD_push_BN(bld, OSSL_PKEY_PARAM_EC_COFACTOR,
BN_value_one()));
}
static int create_ec_explicit_prime_params_namedcurve(OSSL_PARAM_BLD *bld)
{
static const unsigned char prime256v1_gen[] = {
0x04,
0x6b, 0x17, 0xd1, 0xf2, 0xe1, 0x2c, 0x42, 0x47,
0xf8, 0xbc, 0xe6, 0xe5, 0x63, 0xa4, 0x40, 0xf2,
0x77, 0x03, 0x7d, 0x81, 0x2d, 0xeb, 0x33, 0xa0,
0xf4, 0xa1, 0x39, 0x45, 0xd8, 0x98, 0xc2, 0x96,
0x4f, 0xe3, 0x42, 0xe2, 0xfe, 0x1a, 0x7f, 0x9b,
0x8e, 0xe7, 0xeb, 0x4a, 0x7c, 0x0f, 0x9e, 0x16,
0x2b, 0xce, 0x33, 0x57, 0x6b, 0x31, 0x5e, 0xce,
0xcb, 0xb6, 0x40, 0x68, 0x37, 0xbf, 0x51, 0xf5
};
return do_create_ec_explicit_prime_params(bld, prime256v1_gen,
sizeof(prime256v1_gen));
}
static int create_ec_explicit_prime_params(OSSL_PARAM_BLD *bld)
{
/* 2G */
static const unsigned char prime256v1_gen2[] = {
0x04,
0xe4, 0x97, 0x08, 0xbe, 0x7d, 0xfa, 0xa2, 0x9a,
0xa3, 0x12, 0x6f, 0xe4, 0xe7, 0xd0, 0x25, 0xe3,
0x4a, 0xc1, 0x03, 0x15, 0x8c, 0xd9, 0x33, 0xc6,
0x97, 0x42, 0xf5, 0xdc, 0x97, 0xb9, 0xd7, 0x31,
0xe9, 0x7d, 0x74, 0x3d, 0x67, 0x6a, 0x3b, 0x21,
0x08, 0x9c, 0x31, 0x73, 0xf8, 0xc1, 0x27, 0xc9,
0xd2, 0xa0, 0xa0, 0x83, 0x66, 0xe0, 0xc9, 0xda,
0xa8, 0xc6, 0x56, 0x2b, 0x94, 0xb1, 0xae, 0x55
};
return do_create_ec_explicit_prime_params(bld, prime256v1_gen2,
sizeof(prime256v1_gen2));
}
# ifndef OPENSSL_NO_EC2M
static int do_create_ec_explicit_trinomial_params(OSSL_PARAM_BLD *bld,
const unsigned char *gen,
size_t gen_len)
{
BIGNUM *a, *b, *poly, *order, *cofactor;
/* sect233k1 characteristic-two-field tpBasis */
static const unsigned char poly_data[] = {
0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x01,
};
static const unsigned char a_data[] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};
static const unsigned char b_data[] = {
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, 0x01
};
static const unsigned char order_data[] = {
0x00, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x06, 0x9D, 0x5B, 0xB9, 0x15, 0xBC, 0xD4, 0x6E, 0xFB,
0x1A, 0xD5, 0xF1, 0x73, 0xAB, 0xDF
};
static const unsigned char cofactor_data[]= {
0x4
};
return TEST_ptr(a = BN_CTX_get(bnctx))
&& TEST_ptr(b = BN_CTX_get(bnctx))
&& TEST_ptr(poly = BN_CTX_get(bnctx))
&& TEST_ptr(order = BN_CTX_get(bnctx))
&& TEST_ptr(cofactor = BN_CTX_get(bnctx))
&& TEST_ptr(BN_bin2bn(poly_data, sizeof(poly_data), poly))
&& TEST_ptr(BN_bin2bn(a_data, sizeof(a_data), a))
&& TEST_ptr(BN_bin2bn(b_data, sizeof(b_data), b))
&& TEST_ptr(BN_bin2bn(order_data, sizeof(order_data), order))
&& TEST_ptr(BN_bin2bn(cofactor_data, sizeof(cofactor_data), cofactor))
&& TEST_true(OSSL_PARAM_BLD_push_utf8_string(bld,
OSSL_PKEY_PARAM_EC_FIELD_TYPE,
SN_X9_62_characteristic_two_field, 0))
&& TEST_true(OSSL_PARAM_BLD_push_BN(bld, OSSL_PKEY_PARAM_EC_P, poly))
&& TEST_true(OSSL_PARAM_BLD_push_BN(bld, OSSL_PKEY_PARAM_EC_A, a))
&& TEST_true(OSSL_PARAM_BLD_push_BN(bld, OSSL_PKEY_PARAM_EC_B, b))
&& TEST_true(OSSL_PARAM_BLD_push_BN(bld,
OSSL_PKEY_PARAM_EC_ORDER, order))
&& TEST_true(OSSL_PARAM_BLD_push_octet_string(bld,
OSSL_PKEY_PARAM_EC_GENERATOR, gen, gen_len))
&& TEST_true(OSSL_PARAM_BLD_push_BN(bld, OSSL_PKEY_PARAM_EC_COFACTOR,
cofactor));
}
static int create_ec_explicit_trinomial_params_namedcurve(OSSL_PARAM_BLD *bld)
{
static const unsigned char gen[] = {
0x04,
0x01, 0x72, 0x32, 0xBA, 0x85, 0x3A, 0x7E, 0x73, 0x1A, 0xF1, 0x29, 0xF2,
0x2F, 0xF4, 0x14, 0x95, 0x63, 0xA4, 0x19, 0xC2, 0x6B, 0xF5, 0x0A, 0x4C,
0x9D, 0x6E, 0xEF, 0xAD, 0x61, 0x26,
0x01, 0xDB, 0x53, 0x7D, 0xEC, 0xE8, 0x19, 0xB7, 0xF7, 0x0F, 0x55, 0x5A,
0x67, 0xC4, 0x27, 0xA8, 0xCD, 0x9B, 0xF1, 0x8A, 0xEB, 0x9B, 0x56, 0xE0,
0xC1, 0x10, 0x56, 0xFA, 0xE6, 0xA3
};
return do_create_ec_explicit_trinomial_params(bld, gen, sizeof(gen));
}
static int create_ec_explicit_trinomial_params(OSSL_PARAM_BLD *bld)
{
static const unsigned char gen2[] = {
0x04,
0x00, 0xd7, 0xba, 0xd0, 0x26, 0x6c, 0x31, 0x6a, 0x78, 0x76, 0x01, 0xd1,
0x32, 0x4b, 0x8f, 0x30, 0x29, 0x2d, 0x78, 0x30, 0xca, 0x43, 0xaa, 0xf0,
0xa2, 0x5a, 0xd4, 0x0f, 0xb3, 0xf4,
0x00, 0x85, 0x4b, 0x1b, 0x8d, 0x50, 0x10, 0xa5, 0x1c, 0x80, 0xf7, 0x86,
0x40, 0x62, 0x4c, 0x87, 0xd1, 0x26, 0x7a, 0x9c, 0x5c, 0xe9, 0x82, 0x29,
0xd1, 0x67, 0x70, 0x41, 0xea, 0xcb
};
return do_create_ec_explicit_trinomial_params(bld, gen2, sizeof(gen2));
}
# endif /* OPENSSL_NO_EC2M */
#endif /* OPENSSL_NO_EC */
typedef enum OPTION_choice {
OPT_ERR = -1,
OPT_EOF = 0,
OPT_CONTEXT,
OPT_RSA_FILE,
OPT_RSA_PSS_FILE,
OPT_CONFIG_FILE,
OPT_PROVIDER_NAME,
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" },
{ "rsa", OPT_RSA_FILE, '<',
"PEM format RSA key file to encode/decode" },
{ "pss", OPT_RSA_PSS_FILE, '<',
"PEM format RSA-PSS key file to encode/decode" },
{ "config", OPT_CONFIG_FILE, '<',
"The configuration file to use for the library context" },
{ "provider", OPT_PROVIDER_NAME, 's',
"The provider to load (The default value is 'default')" },
{ NULL }
};
return options;
}
int setup_tests(void)
{
const char *rsa_file = NULL;
const char *rsa_pss_file = NULL;
const char *prov_name = "default";
char *config_file = NULL;
int ok = 1;
#ifndef OPENSSL_NO_DSA
static size_t qbits = 160; /* PVK only tolerates 160 Q bits */
static size_t pbits = 1024; /* With 160 Q bits, we MUST use 1024 P bits */
OSSL_PARAM DSA_params[] = {
OSSL_PARAM_size_t("pbits", &pbits),
OSSL_PARAM_size_t("qbits", &qbits),
OSSL_PARAM_END
};
#endif
#ifndef OPENSSL_NO_EC
static char groupname[] = "prime256v1";
OSSL_PARAM EC_params[] = {
OSSL_PARAM_utf8_string("group", groupname, sizeof(groupname) - 1),
OSSL_PARAM_END
};
#endif
OPTION_CHOICE o;
while ((o = opt_next()) != OPT_EOF) {
switch (o) {
case OPT_CONTEXT:
default_libctx = 0;
break;
case OPT_PROVIDER_NAME:
prov_name = opt_arg();
break;
case OPT_CONFIG_FILE:
config_file = opt_arg();
break;
case OPT_RSA_FILE:
rsa_file = opt_arg();
break;
case OPT_RSA_PSS_FILE:
rsa_pss_file = opt_arg();
break;
case OPT_TEST_CASES:
break;
default:
return 0;
}
}
if (strcmp(prov_name, "fips") == 0)
is_fips = 1;
if (default_libctx) {
if (!test_get_libctx(NULL, NULL, config_file, &deflprov, prov_name))
return 0;
} else {
if (!test_get_libctx(&testctx, &nullprov, config_file, &deflprov, prov_name))
return 0;
}
/* FIPS(3.0.0): provider imports explicit params but they won't work #17998 */
- is_fips_3_0_0 = fips_provider_version_eq(testctx, 3, 0, 0);
- if (is_fips_3_0_0 < 0)
- return 0;
+ is_fips_3_0_0 = is_fips && fips_provider_version_eq(testctx, 3, 0, 0);
/* Separate provider/ctx for generating the test data */
if (!TEST_ptr(keyctx = OSSL_LIB_CTX_new()))
return 0;
if (!TEST_ptr(keyprov = OSSL_PROVIDER_load(keyctx, "default")))
return 0;
#ifndef OPENSSL_NO_EC
if (!TEST_ptr(bnctx = BN_CTX_new_ex(testctx))
|| !TEST_ptr(bld_prime_nc = OSSL_PARAM_BLD_new())
|| !TEST_ptr(bld_prime = OSSL_PARAM_BLD_new())
|| !create_ec_explicit_prime_params_namedcurve(bld_prime_nc)
|| !create_ec_explicit_prime_params(bld_prime)
|| !TEST_ptr(ec_explicit_prime_params_nc = OSSL_PARAM_BLD_to_param(bld_prime_nc))
|| !TEST_ptr(ec_explicit_prime_params_explicit = OSSL_PARAM_BLD_to_param(bld_prime))
# ifndef OPENSSL_NO_EC2M
|| !TEST_ptr(bld_tri_nc = OSSL_PARAM_BLD_new())
|| !TEST_ptr(bld_tri = OSSL_PARAM_BLD_new())
|| !create_ec_explicit_trinomial_params_namedcurve(bld_tri_nc)
|| !create_ec_explicit_trinomial_params(bld_tri)
|| !TEST_ptr(ec_explicit_tri_params_nc = OSSL_PARAM_BLD_to_param(bld_tri_nc))
|| !TEST_ptr(ec_explicit_tri_params_explicit = OSSL_PARAM_BLD_to_param(bld_tri))
# endif
)
return 0;
#endif
TEST_info("Generating keys...");
#ifndef OPENSSL_NO_DH
TEST_info("Generating DH keys...");
MAKE_DOMAIN_KEYS(DH, "DH", NULL);
MAKE_DOMAIN_KEYS(DHX, "X9.42 DH", NULL);
#endif
#ifndef OPENSSL_NO_DSA
TEST_info("Generating DSA keys...");
MAKE_DOMAIN_KEYS(DSA, "DSA", DSA_params);
#endif
#ifndef OPENSSL_NO_EC
TEST_info("Generating EC keys...");
MAKE_DOMAIN_KEYS(EC, "EC", EC_params);
MAKE_DOMAIN_KEYS(ECExplicitPrimeNamedCurve, "EC", ec_explicit_prime_params_nc);
MAKE_DOMAIN_KEYS(ECExplicitPrime2G, "EC", ec_explicit_prime_params_explicit);
# ifndef OPENSSL_NO_EC2M
MAKE_DOMAIN_KEYS(ECExplicitTriNamedCurve, "EC", ec_explicit_tri_params_nc);
MAKE_DOMAIN_KEYS(ECExplicitTri2G, "EC", ec_explicit_tri_params_explicit);
+# endif
+# ifndef OPENSSL_NO_SM2
+ MAKE_KEYS(SM2, "SM2", NULL);
# endif
MAKE_KEYS(ED25519, "ED25519", NULL);
MAKE_KEYS(ED448, "ED448", NULL);
MAKE_KEYS(X25519, "X25519", NULL);
MAKE_KEYS(X448, "X448", NULL);
#endif
TEST_info("Loading RSA key...");
ok = ok && TEST_ptr(key_RSA = load_pkey_pem(rsa_file, keyctx));
TEST_info("Loading RSA_PSS key...");
ok = ok && TEST_ptr(key_RSA_PSS = load_pkey_pem(rsa_pss_file, keyctx));
TEST_info("Generating keys done");
if (ok) {
#ifndef OPENSSL_NO_DH
ADD_TEST_SUITE(DH);
ADD_TEST_SUITE_PARAMS(DH);
ADD_TEST_SUITE(DHX);
ADD_TEST_SUITE_PARAMS(DHX);
/*
* DH has no support for PEM_write_bio_PrivateKey_traditional(),
* so no legacy tests.
*/
#endif
#ifndef OPENSSL_NO_DSA
ADD_TEST_SUITE(DSA);
ADD_TEST_SUITE_PARAMS(DSA);
ADD_TEST_SUITE_LEGACY(DSA);
ADD_TEST_SUITE_MSBLOB(DSA);
ADD_TEST_SUITE_UNPROTECTED_PVK(DSA);
# ifndef OPENSSL_NO_RC4
ADD_TEST_SUITE_PROTECTED_PVK(DSA);
# endif
#endif
#ifndef OPENSSL_NO_EC
ADD_TEST_SUITE(EC);
ADD_TEST_SUITE_PARAMS(EC);
ADD_TEST_SUITE_LEGACY(EC);
ADD_TEST_SUITE(ECExplicitPrimeNamedCurve);
ADD_TEST_SUITE_LEGACY(ECExplicitPrimeNamedCurve);
ADD_TEST_SUITE(ECExplicitPrime2G);
ADD_TEST_SUITE_LEGACY(ECExplicitPrime2G);
# ifndef OPENSSL_NO_EC2M
ADD_TEST_SUITE(ECExplicitTriNamedCurve);
ADD_TEST_SUITE_LEGACY(ECExplicitTriNamedCurve);
ADD_TEST_SUITE(ECExplicitTri2G);
ADD_TEST_SUITE_LEGACY(ECExplicitTri2G);
+# endif
+# ifndef OPENSSL_NO_SM2
+ if (!is_fips_3_0_0) {
+ /* 3.0.0 FIPS provider imports explicit EC params and then fails. */
+ ADD_TEST_SUITE(SM2);
+ }
# endif
ADD_TEST_SUITE(ED25519);
ADD_TEST_SUITE(ED448);
ADD_TEST_SUITE(X25519);
ADD_TEST_SUITE(X448);
/*
* ED25519, ED448, X25519 and X448 have no support for
* PEM_write_bio_PrivateKey_traditional(), so no legacy tests.
*/
#endif
ADD_TEST_SUITE(RSA);
ADD_TEST_SUITE_LEGACY(RSA);
ADD_TEST_SUITE(RSA_PSS);
/*
* RSA-PSS has no support for PEM_write_bio_PrivateKey_traditional(),
* so no legacy tests.
*/
ADD_TEST_SUITE_MSBLOB(RSA);
ADD_TEST_SUITE_UNPROTECTED_PVK(RSA);
# ifndef OPENSSL_NO_RC4
ADD_TEST_SUITE_PROTECTED_PVK(RSA);
# endif
}
return 1;
}
void cleanup_tests(void)
{
#ifndef OPENSSL_NO_EC
OSSL_PARAM_free(ec_explicit_prime_params_nc);
OSSL_PARAM_free(ec_explicit_prime_params_explicit);
OSSL_PARAM_BLD_free(bld_prime_nc);
OSSL_PARAM_BLD_free(bld_prime);
# ifndef OPENSSL_NO_EC2M
OSSL_PARAM_free(ec_explicit_tri_params_nc);
OSSL_PARAM_free(ec_explicit_tri_params_explicit);
OSSL_PARAM_BLD_free(bld_tri_nc);
OSSL_PARAM_BLD_free(bld_tri);
# endif
BN_CTX_free(bnctx);
#endif /* OPENSSL_NO_EC */
#ifndef OPENSSL_NO_DH
FREE_DOMAIN_KEYS(DH);
FREE_DOMAIN_KEYS(DHX);
#endif
#ifndef OPENSSL_NO_DSA
FREE_DOMAIN_KEYS(DSA);
#endif
#ifndef OPENSSL_NO_EC
FREE_DOMAIN_KEYS(EC);
FREE_DOMAIN_KEYS(ECExplicitPrimeNamedCurve);
FREE_DOMAIN_KEYS(ECExplicitPrime2G);
# ifndef OPENSSL_NO_EC2M
FREE_DOMAIN_KEYS(ECExplicitTriNamedCurve);
FREE_DOMAIN_KEYS(ECExplicitTri2G);
+# endif
+# ifndef OPENSSL_NO_SM2
+ FREE_KEYS(SM2);
# endif
FREE_KEYS(ED25519);
FREE_KEYS(ED448);
FREE_KEYS(X25519);
FREE_KEYS(X448);
#endif
FREE_KEYS(RSA);
FREE_KEYS(RSA_PSS);
OSSL_PROVIDER_unload(nullprov);
OSSL_PROVIDER_unload(deflprov);
OSSL_PROVIDER_unload(keyprov);
OSSL_LIB_CTX_free(testctx);
OSSL_LIB_CTX_free(keyctx);
}
diff --git a/crypto/openssl/test/evp_byname_test.c b/crypto/openssl/test/evp_byname_test.c
new file mode 100644
index 000000000000..e16e27a3a5ec
--- /dev/null
+++ b/crypto/openssl/test/evp_byname_test.c
@@ -0,0 +1,40 @@
+/*
+ * Copyright 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 <string.h>
+
+#include <openssl/evp.h>
+#include "testutil.h"
+
+static int test_evp_get_digestbyname(void)
+{
+ const EVP_MD *md;
+
+ if (!TEST_ptr(md = EVP_get_digestbyname("SHA2-256")))
+ return 0;
+ return 1;
+}
+
+static int test_evp_get_cipherbyname(void)
+{
+ const EVP_CIPHER *cipher;
+
+ if (!TEST_ptr(cipher = EVP_get_cipherbyname("AES-256-WRAP")))
+ return 0;
+ return 1;
+}
+
+int setup_tests(void)
+{
+ ADD_TEST(test_evp_get_digestbyname);
+ ADD_TEST(test_evp_get_cipherbyname);
+ return 1;
+}
diff --git a/crypto/openssl/test/evp_extra_test.c b/crypto/openssl/test/evp_extra_test.c
index 7e97e2d34d5d..c5fbbf8a8309 100644
--- a/crypto/openssl/test/evp_extra_test.c
+++ b/crypto/openssl/test/evp_extra_test.c
@@ -1,5526 +1,5547 @@
/*
* 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;
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
+static int test_invalid_ctx_for_digest(void)
+{
+ int ret;
+ EVP_MD_CTX *mdctx;
+
+ mdctx = EVP_MD_CTX_new();
+ if (!TEST_ptr(mdctx))
+ return 0;
+
+ if (!TEST_int_eq(EVP_DigestUpdate(mdctx, "test", sizeof("test") - 1), 0))
+ ret = 0;
+ else
+ ret = 1;
+
+ EVP_MD_CTX_free(mdctx);
+
+ return ret;
+}
+
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
+ ADD_TEST(test_invalid_ctx_for_digest);
+
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/helpers/handshake.c b/crypto/openssl/test/helpers/handshake.c
index 285391bc03b6..5744c6a54ee5 100644
--- a/crypto/openssl/test/helpers/handshake.c
+++ b/crypto/openssl/test/helpers/handshake.c
@@ -1,1750 +1,1756 @@
/*
- * 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 <string.h>
#include <openssl/bio.h>
#include <openssl/x509_vfy.h>
#include <openssl/ssl.h>
#include <openssl/core_names.h>
#include "../../ssl/ssl_local.h"
#include "internal/sockets.h"
#include "internal/nelem.h"
#include "handshake.h"
#include "../testutil.h"
#if !defined(OPENSSL_NO_SCTP) && !defined(OPENSSL_NO_SOCK)
#include <netinet/sctp.h>
#endif
HANDSHAKE_RESULT *HANDSHAKE_RESULT_new(void)
{
HANDSHAKE_RESULT *ret;
TEST_ptr(ret = OPENSSL_zalloc(sizeof(*ret)));
return ret;
}
void HANDSHAKE_RESULT_free(HANDSHAKE_RESULT *result)
{
if (result == NULL)
return;
OPENSSL_free(result->client_npn_negotiated);
OPENSSL_free(result->server_npn_negotiated);
OPENSSL_free(result->client_alpn_negotiated);
OPENSSL_free(result->server_alpn_negotiated);
OPENSSL_free(result->result_session_ticket_app_data);
sk_X509_NAME_pop_free(result->server_ca_names, X509_NAME_free);
sk_X509_NAME_pop_free(result->client_ca_names, X509_NAME_free);
OPENSSL_free(result->cipher);
OPENSSL_free(result);
}
/*
* Since there appears to be no way to extract the sent/received alert
* from the SSL object directly, we use the info callback and stash
* the result in ex_data.
*/
typedef struct handshake_ex_data_st {
int alert_sent;
int num_fatal_alerts_sent;
int alert_received;
int session_ticket_do_not_call;
ssl_servername_t servername;
} HANDSHAKE_EX_DATA;
/* |ctx_data| itself is stack-allocated. */
static void ctx_data_free_data(CTX_DATA *ctx_data)
{
OPENSSL_free(ctx_data->npn_protocols);
ctx_data->npn_protocols = NULL;
OPENSSL_free(ctx_data->alpn_protocols);
ctx_data->alpn_protocols = NULL;
OPENSSL_free(ctx_data->srp_user);
ctx_data->srp_user = NULL;
OPENSSL_free(ctx_data->srp_password);
ctx_data->srp_password = NULL;
OPENSSL_free(ctx_data->session_ticket_app_data);
ctx_data->session_ticket_app_data = NULL;
}
static int ex_data_idx;
static void info_cb(const SSL *s, int where, int ret)
{
if (where & SSL_CB_ALERT) {
HANDSHAKE_EX_DATA *ex_data =
(HANDSHAKE_EX_DATA*)(SSL_get_ex_data(s, ex_data_idx));
if (where & SSL_CB_WRITE) {
ex_data->alert_sent = ret;
if (strcmp(SSL_alert_type_string(ret), "F") == 0
|| strcmp(SSL_alert_desc_string(ret), "CN") == 0)
ex_data->num_fatal_alerts_sent++;
} else {
ex_data->alert_received = ret;
}
}
}
/* Select the appropriate server CTX.
* Returns SSL_TLSEXT_ERR_OK if a match was found.
* If |ignore| is 1, returns SSL_TLSEXT_ERR_NOACK on mismatch.
* Otherwise, returns SSL_TLSEXT_ERR_ALERT_FATAL on mismatch.
* An empty SNI extension also returns SSL_TSLEXT_ERR_NOACK.
*/
static int select_server_ctx(SSL *s, void *arg, int ignore)
{
const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
HANDSHAKE_EX_DATA *ex_data =
(HANDSHAKE_EX_DATA*)(SSL_get_ex_data(s, ex_data_idx));
if (servername == NULL) {
ex_data->servername = SSL_TEST_SERVERNAME_SERVER1;
return SSL_TLSEXT_ERR_NOACK;
}
if (strcmp(servername, "server2") == 0) {
SSL_CTX *new_ctx = (SSL_CTX*)arg;
SSL_set_SSL_CTX(s, new_ctx);
/*
* Copy over all the SSL_CTX options - reasonable behavior
* allows testing of cases where the options between two
* contexts differ/conflict
*/
SSL_clear_options(s, 0xFFFFFFFFL);
SSL_set_options(s, SSL_CTX_get_options(new_ctx));
ex_data->servername = SSL_TEST_SERVERNAME_SERVER2;
return SSL_TLSEXT_ERR_OK;
} else if (strcmp(servername, "server1") == 0) {
ex_data->servername = SSL_TEST_SERVERNAME_SERVER1;
return SSL_TLSEXT_ERR_OK;
} else if (ignore) {
ex_data->servername = SSL_TEST_SERVERNAME_SERVER1;
return SSL_TLSEXT_ERR_NOACK;
} else {
/* Don't set an explicit alert, to test library defaults. */
return SSL_TLSEXT_ERR_ALERT_FATAL;
}
}
static int client_hello_select_server_ctx(SSL *s, void *arg, int ignore)
{
const char *servername;
const unsigned char *p;
size_t len, remaining;
HANDSHAKE_EX_DATA *ex_data =
(HANDSHAKE_EX_DATA*)(SSL_get_ex_data(s, ex_data_idx));
/*
* The server_name extension was given too much extensibility when it
* was written, so parsing the normal case is a bit complex.
*/
if (!SSL_client_hello_get0_ext(s, TLSEXT_TYPE_server_name, &p,
&remaining) ||
remaining <= 2)
return 0;
/* Extract the length of the supplied list of names. */
len = (*(p++) << 8);
len += *(p++);
if (len + 2 != remaining)
return 0;
remaining = len;
/*
* The list in practice only has a single element, so we only consider
* the first one.
*/
if (remaining == 0 || *p++ != TLSEXT_NAMETYPE_host_name)
return 0;
remaining--;
/* Now we can finally pull out the byte array with the actual hostname. */
if (remaining <= 2)
return 0;
len = (*(p++) << 8);
len += *(p++);
if (len + 2 > remaining)
return 0;
remaining = len;
servername = (const char *)p;
if (len == strlen("server2") && strncmp(servername, "server2", len) == 0) {
SSL_CTX *new_ctx = arg;
SSL_set_SSL_CTX(s, new_ctx);
/*
* Copy over all the SSL_CTX options - reasonable behavior
* allows testing of cases where the options between two
* contexts differ/conflict
*/
SSL_clear_options(s, 0xFFFFFFFFL);
SSL_set_options(s, SSL_CTX_get_options(new_ctx));
ex_data->servername = SSL_TEST_SERVERNAME_SERVER2;
return 1;
} else if (len == strlen("server1") &&
strncmp(servername, "server1", len) == 0) {
ex_data->servername = SSL_TEST_SERVERNAME_SERVER1;
return 1;
} else if (ignore) {
ex_data->servername = SSL_TEST_SERVERNAME_SERVER1;
return 1;
}
return 0;
}
/*
* (RFC 6066):
* If the server understood the ClientHello extension but
* does not recognize the server name, the server SHOULD take one of two
* actions: either abort the handshake by sending a fatal-level
* unrecognized_name(112) alert or continue the handshake.
*
* This behaviour is up to the application to configure; we test both
* configurations to ensure the state machine propagates the result
* correctly.
*/
static int servername_ignore_cb(SSL *s, int *ad, void *arg)
{
return select_server_ctx(s, arg, 1);
}
static int servername_reject_cb(SSL *s, int *ad, void *arg)
{
return select_server_ctx(s, arg, 0);
}
static int client_hello_ignore_cb(SSL *s, int *al, void *arg)
{
if (!client_hello_select_server_ctx(s, arg, 1)) {
*al = SSL_AD_UNRECOGNIZED_NAME;
return SSL_CLIENT_HELLO_ERROR;
}
return SSL_CLIENT_HELLO_SUCCESS;
}
static int client_hello_reject_cb(SSL *s, int *al, void *arg)
{
if (!client_hello_select_server_ctx(s, arg, 0)) {
*al = SSL_AD_UNRECOGNIZED_NAME;
return SSL_CLIENT_HELLO_ERROR;
}
return SSL_CLIENT_HELLO_SUCCESS;
}
static int client_hello_nov12_cb(SSL *s, int *al, void *arg)
{
int ret;
unsigned int v;
const unsigned char *p;
v = SSL_client_hello_get0_legacy_version(s);
if (v > TLS1_2_VERSION || v < SSL3_VERSION) {
*al = SSL_AD_PROTOCOL_VERSION;
return SSL_CLIENT_HELLO_ERROR;
}
(void)SSL_client_hello_get0_session_id(s, &p);
if (p == NULL ||
SSL_client_hello_get0_random(s, &p) == 0 ||
SSL_client_hello_get0_ciphers(s, &p) == 0 ||
SSL_client_hello_get0_compression_methods(s, &p) == 0) {
*al = SSL_AD_INTERNAL_ERROR;
return SSL_CLIENT_HELLO_ERROR;
}
ret = client_hello_select_server_ctx(s, arg, 0);
SSL_set_max_proto_version(s, TLS1_1_VERSION);
if (!ret) {
*al = SSL_AD_UNRECOGNIZED_NAME;
return SSL_CLIENT_HELLO_ERROR;
}
return SSL_CLIENT_HELLO_SUCCESS;
}
static unsigned char dummy_ocsp_resp_good_val = 0xff;
static unsigned char dummy_ocsp_resp_bad_val = 0xfe;
static int server_ocsp_cb(SSL *s, void *arg)
{
unsigned char *resp;
resp = OPENSSL_malloc(1);
if (resp == NULL)
return SSL_TLSEXT_ERR_ALERT_FATAL;
/*
* For the purposes of testing we just send back a dummy OCSP response
*/
*resp = *(unsigned char *)arg;
if (!SSL_set_tlsext_status_ocsp_resp(s, resp, 1)) {
OPENSSL_free(resp);
return SSL_TLSEXT_ERR_ALERT_FATAL;
}
return SSL_TLSEXT_ERR_OK;
}
static int client_ocsp_cb(SSL *s, void *arg)
{
const unsigned char *resp;
int len;
len = SSL_get_tlsext_status_ocsp_resp(s, &resp);
if (len != 1 || *resp != dummy_ocsp_resp_good_val)
return 0;
return 1;
}
static int verify_reject_cb(X509_STORE_CTX *ctx, void *arg) {
X509_STORE_CTX_set_error(ctx, X509_V_ERR_APPLICATION_VERIFICATION);
return 0;
}
static int n_retries = 0;
static int verify_retry_cb(X509_STORE_CTX *ctx, void *arg) {
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 (--n_retries < 0)
return 1;
return SSL_set_retry_verify(ssl);
}
static int verify_accept_cb(X509_STORE_CTX *ctx, void *arg) {
return 1;
}
static int broken_session_ticket_cb(SSL *s, unsigned char *key_name,
unsigned char *iv, EVP_CIPHER_CTX *ctx,
EVP_MAC_CTX *hctx, int enc)
{
return 0;
}
static int do_not_call_session_ticket_cb(SSL *s, unsigned char *key_name,
unsigned char *iv,
EVP_CIPHER_CTX *ctx,
EVP_MAC_CTX *hctx, int enc)
{
HANDSHAKE_EX_DATA *ex_data =
(HANDSHAKE_EX_DATA*)(SSL_get_ex_data(s, ex_data_idx));
ex_data->session_ticket_do_not_call = 1;
return 0;
}
/* Parse the comma-separated list into TLS format. */
static int parse_protos(const char *protos, unsigned char **out, size_t *outlen)
{
size_t len, i, prefix;
len = strlen(protos);
+ if (len == 0) {
+ *out = NULL;
+ *outlen = 0;
+ return 1;
+ }
+
/* Should never have reuse. */
if (!TEST_ptr_null(*out)
/* Test values are small, so we omit length limit checks. */
|| !TEST_ptr(*out = OPENSSL_malloc(len + 1)))
return 0;
*outlen = len + 1;
/*
* foo => '3', 'f', 'o', 'o'
* foo,bar => '3', 'f', 'o', 'o', '3', 'b', 'a', 'r'
*/
memcpy(*out + 1, protos, len);
prefix = 0;
i = prefix + 1;
while (i <= len) {
if ((*out)[i] == ',') {
if (!TEST_int_gt(i - 1, prefix))
goto err;
(*out)[prefix] = (unsigned char)(i - 1 - prefix);
prefix = i;
}
i++;
}
if (!TEST_int_gt(len, prefix))
goto err;
(*out)[prefix] = (unsigned char)(len - prefix);
return 1;
err:
OPENSSL_free(*out);
*out = NULL;
return 0;
}
#ifndef OPENSSL_NO_NEXTPROTONEG
/*
* The client SHOULD select the first protocol advertised by the server that it
* also supports. In the event that the client doesn't support any of server's
* protocols, or the server doesn't advertise any, it SHOULD select the first
* protocol that it supports.
*/
static int client_npn_cb(SSL *s, unsigned char **out, unsigned char *outlen,
const unsigned char *in, unsigned int inlen,
void *arg)
{
CTX_DATA *ctx_data = (CTX_DATA*)(arg);
int ret;
ret = SSL_select_next_proto(out, outlen, in, inlen,
ctx_data->npn_protocols,
ctx_data->npn_protocols_len);
/* Accept both OPENSSL_NPN_NEGOTIATED and OPENSSL_NPN_NO_OVERLAP. */
return TEST_true(ret == OPENSSL_NPN_NEGOTIATED || ret == OPENSSL_NPN_NO_OVERLAP)
? SSL_TLSEXT_ERR_OK : SSL_TLSEXT_ERR_ALERT_FATAL;
}
static int server_npn_cb(SSL *s, const unsigned char **data,
unsigned int *len, void *arg)
{
CTX_DATA *ctx_data = (CTX_DATA*)(arg);
*data = ctx_data->npn_protocols;
*len = ctx_data->npn_protocols_len;
return SSL_TLSEXT_ERR_OK;
}
#endif
/*
* The server SHOULD select the most highly preferred protocol that it supports
* and that is also advertised by the client. In the event that the server
* supports no protocols that the client advertises, then the server SHALL
* respond with a fatal "no_application_protocol" alert.
*/
static int server_alpn_cb(SSL *s, const unsigned char **out,
unsigned char *outlen, const unsigned char *in,
unsigned int inlen, void *arg)
{
CTX_DATA *ctx_data = (CTX_DATA*)(arg);
int ret;
/* SSL_select_next_proto isn't const-correct... */
unsigned char *tmp_out;
/*
* The result points either to |in| or to |ctx_data->alpn_protocols|.
* The callback is allowed to point to |in| or to a long-lived buffer,
* so we can return directly without storing a copy.
*/
ret = SSL_select_next_proto(&tmp_out, outlen,
ctx_data->alpn_protocols,
ctx_data->alpn_protocols_len, in, inlen);
*out = tmp_out;
/* Unlike NPN, we don't tolerate a mismatch. */
return ret == OPENSSL_NPN_NEGOTIATED ? SSL_TLSEXT_ERR_OK
: SSL_TLSEXT_ERR_ALERT_FATAL;
}
static int generate_session_ticket_cb(SSL *s, void *arg)
{
CTX_DATA *server_ctx_data = arg;
SSL_SESSION *ss = SSL_get_session(s);
char *app_data = server_ctx_data->session_ticket_app_data;
if (ss == NULL || app_data == NULL)
return 0;
return SSL_SESSION_set1_ticket_appdata(ss, app_data, strlen(app_data));
}
static int decrypt_session_ticket_cb(SSL *s, SSL_SESSION *ss,
const unsigned char *keyname,
size_t keyname_len,
SSL_TICKET_STATUS status,
void *arg)
{
switch (status) {
case SSL_TICKET_EMPTY:
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:
break;
}
return SSL_TICKET_RETURN_ABORT;
}
/*
* Configure callbacks and other properties that can't be set directly
* in the server/client CONF.
*/
static int configure_handshake_ctx(SSL_CTX *server_ctx, SSL_CTX *server2_ctx,
SSL_CTX *client_ctx,
const SSL_TEST_CTX *test,
const SSL_TEST_EXTRA_CONF *extra,
CTX_DATA *server_ctx_data,
CTX_DATA *server2_ctx_data,
CTX_DATA *client_ctx_data)
{
unsigned char *ticket_keys;
size_t ticket_key_len;
if (!TEST_int_eq(SSL_CTX_set_max_send_fragment(server_ctx,
test->max_fragment_size), 1))
goto err;
if (server2_ctx != NULL) {
if (!TEST_int_eq(SSL_CTX_set_max_send_fragment(server2_ctx,
test->max_fragment_size),
1))
goto err;
}
if (!TEST_int_eq(SSL_CTX_set_max_send_fragment(client_ctx,
test->max_fragment_size), 1))
goto err;
switch (extra->client.verify_callback) {
case SSL_TEST_VERIFY_ACCEPT_ALL:
SSL_CTX_set_cert_verify_callback(client_ctx, &verify_accept_cb, NULL);
break;
case SSL_TEST_VERIFY_RETRY_ONCE:
n_retries = 1;
SSL_CTX_set_cert_verify_callback(client_ctx, &verify_retry_cb, NULL);
break;
case SSL_TEST_VERIFY_REJECT_ALL:
SSL_CTX_set_cert_verify_callback(client_ctx, &verify_reject_cb, NULL);
break;
case SSL_TEST_VERIFY_NONE:
break;
}
switch (extra->client.max_fragment_len_mode) {
case TLSEXT_max_fragment_length_512:
case TLSEXT_max_fragment_length_1024:
case TLSEXT_max_fragment_length_2048:
case TLSEXT_max_fragment_length_4096:
case TLSEXT_max_fragment_length_DISABLED:
SSL_CTX_set_tlsext_max_fragment_length(
client_ctx, extra->client.max_fragment_len_mode);
break;
}
/*
* Link the two contexts for SNI purposes.
* Also do ClientHello callbacks here, as setting both ClientHello and SNI
* is bad.
*/
switch (extra->server.servername_callback) {
case SSL_TEST_SERVERNAME_IGNORE_MISMATCH:
SSL_CTX_set_tlsext_servername_callback(server_ctx, servername_ignore_cb);
SSL_CTX_set_tlsext_servername_arg(server_ctx, server2_ctx);
break;
case SSL_TEST_SERVERNAME_REJECT_MISMATCH:
SSL_CTX_set_tlsext_servername_callback(server_ctx, servername_reject_cb);
SSL_CTX_set_tlsext_servername_arg(server_ctx, server2_ctx);
break;
case SSL_TEST_SERVERNAME_CB_NONE:
break;
case SSL_TEST_SERVERNAME_CLIENT_HELLO_IGNORE_MISMATCH:
SSL_CTX_set_client_hello_cb(server_ctx, client_hello_ignore_cb, server2_ctx);
break;
case SSL_TEST_SERVERNAME_CLIENT_HELLO_REJECT_MISMATCH:
SSL_CTX_set_client_hello_cb(server_ctx, client_hello_reject_cb, server2_ctx);
break;
case SSL_TEST_SERVERNAME_CLIENT_HELLO_NO_V12:
SSL_CTX_set_client_hello_cb(server_ctx, client_hello_nov12_cb, server2_ctx);
}
if (extra->server.cert_status != SSL_TEST_CERT_STATUS_NONE) {
SSL_CTX_set_tlsext_status_type(client_ctx, TLSEXT_STATUSTYPE_ocsp);
SSL_CTX_set_tlsext_status_cb(client_ctx, client_ocsp_cb);
SSL_CTX_set_tlsext_status_arg(client_ctx, NULL);
SSL_CTX_set_tlsext_status_cb(server_ctx, server_ocsp_cb);
SSL_CTX_set_tlsext_status_arg(server_ctx,
((extra->server.cert_status == SSL_TEST_CERT_STATUS_GOOD_RESPONSE)
? &dummy_ocsp_resp_good_val : &dummy_ocsp_resp_bad_val));
}
/*
* The initial_ctx/session_ctx always handles the encrypt/decrypt of the
* session ticket. This ticket_key callback is assigned to the second
* session (assigned via SNI), and should never be invoked
*/
if (server2_ctx != NULL)
SSL_CTX_set_tlsext_ticket_key_evp_cb(server2_ctx,
do_not_call_session_ticket_cb);
if (extra->server.broken_session_ticket) {
SSL_CTX_set_tlsext_ticket_key_evp_cb(server_ctx,
broken_session_ticket_cb);
}
#ifndef OPENSSL_NO_NEXTPROTONEG
if (extra->server.npn_protocols != NULL) {
if (!TEST_true(parse_protos(extra->server.npn_protocols,
&server_ctx_data->npn_protocols,
&server_ctx_data->npn_protocols_len)))
goto err;
SSL_CTX_set_npn_advertised_cb(server_ctx, server_npn_cb,
server_ctx_data);
}
if (extra->server2.npn_protocols != NULL) {
if (!TEST_true(parse_protos(extra->server2.npn_protocols,
&server2_ctx_data->npn_protocols,
&server2_ctx_data->npn_protocols_len))
|| !TEST_ptr(server2_ctx))
goto err;
SSL_CTX_set_npn_advertised_cb(server2_ctx, server_npn_cb,
server2_ctx_data);
}
if (extra->client.npn_protocols != NULL) {
if (!TEST_true(parse_protos(extra->client.npn_protocols,
&client_ctx_data->npn_protocols,
&client_ctx_data->npn_protocols_len)))
goto err;
SSL_CTX_set_next_proto_select_cb(client_ctx, client_npn_cb,
client_ctx_data);
}
#endif
if (extra->server.alpn_protocols != NULL) {
if (!TEST_true(parse_protos(extra->server.alpn_protocols,
&server_ctx_data->alpn_protocols,
&server_ctx_data->alpn_protocols_len)))
goto err;
SSL_CTX_set_alpn_select_cb(server_ctx, server_alpn_cb, server_ctx_data);
}
if (extra->server2.alpn_protocols != NULL) {
if (!TEST_ptr(server2_ctx)
|| !TEST_true(parse_protos(extra->server2.alpn_protocols,
&server2_ctx_data->alpn_protocols,
&server2_ctx_data->alpn_protocols_len
)))
goto err;
SSL_CTX_set_alpn_select_cb(server2_ctx, server_alpn_cb,
server2_ctx_data);
}
if (extra->client.alpn_protocols != NULL) {
unsigned char *alpn_protos = NULL;
size_t alpn_protos_len = 0;
if (!TEST_true(parse_protos(extra->client.alpn_protocols,
&alpn_protos, &alpn_protos_len))
/* Reversed return value convention... */
|| !TEST_int_eq(SSL_CTX_set_alpn_protos(client_ctx, alpn_protos,
alpn_protos_len), 0))
goto err;
OPENSSL_free(alpn_protos);
}
if (extra->server.session_ticket_app_data != NULL) {
server_ctx_data->session_ticket_app_data =
OPENSSL_strdup(extra->server.session_ticket_app_data);
SSL_CTX_set_session_ticket_cb(server_ctx, generate_session_ticket_cb,
decrypt_session_ticket_cb, server_ctx_data);
}
if (extra->server2.session_ticket_app_data != NULL) {
if (!TEST_ptr(server2_ctx))
goto err;
server2_ctx_data->session_ticket_app_data =
OPENSSL_strdup(extra->server2.session_ticket_app_data);
SSL_CTX_set_session_ticket_cb(server2_ctx, NULL,
decrypt_session_ticket_cb, server2_ctx_data);
}
/*
* Use fixed session ticket keys so that we can decrypt a ticket created with
* one CTX in another CTX. Don't address server2 for the moment.
*/
ticket_key_len = SSL_CTX_set_tlsext_ticket_keys(server_ctx, NULL, 0);
if (!TEST_ptr(ticket_keys = OPENSSL_zalloc(ticket_key_len))
|| !TEST_int_eq(SSL_CTX_set_tlsext_ticket_keys(server_ctx,
ticket_keys,
ticket_key_len), 1)) {
OPENSSL_free(ticket_keys);
goto err;
}
OPENSSL_free(ticket_keys);
/* The default log list includes EC keys, so CT can't work without EC. */
#if !defined(OPENSSL_NO_CT) && !defined(OPENSSL_NO_EC)
if (!TEST_true(SSL_CTX_set_default_ctlog_list_file(client_ctx)))
goto err;
switch (extra->client.ct_validation) {
case SSL_TEST_CT_VALIDATION_PERMISSIVE:
if (!TEST_true(SSL_CTX_enable_ct(client_ctx,
SSL_CT_VALIDATION_PERMISSIVE)))
goto err;
break;
case SSL_TEST_CT_VALIDATION_STRICT:
if (!TEST_true(SSL_CTX_enable_ct(client_ctx, SSL_CT_VALIDATION_STRICT)))
goto err;
break;
case SSL_TEST_CT_VALIDATION_NONE:
break;
}
#endif
#ifndef OPENSSL_NO_SRP
if (!configure_handshake_ctx_for_srp(server_ctx, server2_ctx, client_ctx,
extra, server_ctx_data,
server2_ctx_data, client_ctx_data))
goto err;
#endif /* !OPENSSL_NO_SRP */
return 1;
err:
return 0;
}
/* Configure per-SSL callbacks and other properties. */
static void configure_handshake_ssl(SSL *server, SSL *client,
const SSL_TEST_EXTRA_CONF *extra)
{
if (extra->client.servername != SSL_TEST_SERVERNAME_NONE)
SSL_set_tlsext_host_name(client,
ssl_servername_name(extra->client.servername));
if (extra->client.enable_pha)
SSL_set_post_handshake_auth(client, 1);
}
/* The status for each connection phase. */
typedef enum {
PEER_SUCCESS,
PEER_RETRY,
PEER_ERROR,
PEER_WAITING,
PEER_TEST_FAILURE
} peer_status_t;
/* An SSL object and associated read-write buffers. */
typedef struct peer_st {
SSL *ssl;
/* Buffer lengths are int to match the SSL read/write API. */
unsigned char *write_buf;
int write_buf_len;
unsigned char *read_buf;
int read_buf_len;
int bytes_to_write;
int bytes_to_read;
peer_status_t status;
} PEER;
static int create_peer(PEER *peer, SSL_CTX *ctx)
{
static const int peer_buffer_size = 64 * 1024;
SSL *ssl = NULL;
unsigned char *read_buf = NULL, *write_buf = NULL;
if (!TEST_ptr(ssl = SSL_new(ctx))
|| !TEST_ptr(write_buf = OPENSSL_zalloc(peer_buffer_size))
|| !TEST_ptr(read_buf = OPENSSL_zalloc(peer_buffer_size)))
goto err;
peer->ssl = ssl;
peer->write_buf = write_buf;
peer->read_buf = read_buf;
peer->write_buf_len = peer->read_buf_len = peer_buffer_size;
return 1;
err:
SSL_free(ssl);
OPENSSL_free(write_buf);
OPENSSL_free(read_buf);
return 0;
}
static void peer_free_data(PEER *peer)
{
SSL_free(peer->ssl);
OPENSSL_free(peer->write_buf);
OPENSSL_free(peer->read_buf);
}
/*
* Note that we could do the handshake transparently under an SSL_write,
* but separating the steps is more helpful for debugging test failures.
*/
static void do_handshake_step(PEER *peer)
{
if (!TEST_int_eq(peer->status, PEER_RETRY)) {
peer->status = PEER_TEST_FAILURE;
} else {
int ret = SSL_do_handshake(peer->ssl);
if (ret == 1) {
peer->status = PEER_SUCCESS;
} else if (ret == 0) {
peer->status = PEER_ERROR;
} else {
int error = SSL_get_error(peer->ssl, ret);
/* Memory bios should never block with SSL_ERROR_WANT_WRITE. */
if (error != SSL_ERROR_WANT_READ
&& error != SSL_ERROR_WANT_RETRY_VERIFY)
peer->status = PEER_ERROR;
}
}
}
/*-
* Send/receive some application data. The read-write sequence is
* Peer A: (R) W - first read will yield no data
* Peer B: R W
* ...
* Peer A: R W
* Peer B: R W
* Peer A: R
*/
static void do_app_data_step(PEER *peer)
{
int ret = 1, write_bytes;
if (!TEST_int_eq(peer->status, PEER_RETRY)) {
peer->status = PEER_TEST_FAILURE;
return;
}
/* We read everything available... */
while (ret > 0 && peer->bytes_to_read) {
ret = SSL_read(peer->ssl, peer->read_buf, peer->read_buf_len);
if (ret > 0) {
if (!TEST_int_le(ret, peer->bytes_to_read)) {
peer->status = PEER_TEST_FAILURE;
return;
}
peer->bytes_to_read -= ret;
} else if (ret == 0) {
peer->status = PEER_ERROR;
return;
} else {
int error = SSL_get_error(peer->ssl, ret);
if (error != SSL_ERROR_WANT_READ) {
peer->status = PEER_ERROR;
return;
} /* Else continue with write. */
}
}
/* ... but we only write one write-buffer-full of data. */
write_bytes = peer->bytes_to_write < peer->write_buf_len ? peer->bytes_to_write :
peer->write_buf_len;
if (write_bytes) {
ret = SSL_write(peer->ssl, peer->write_buf, write_bytes);
if (ret > 0) {
/* SSL_write will only succeed with a complete write. */
if (!TEST_int_eq(ret, write_bytes)) {
peer->status = PEER_TEST_FAILURE;
return;
}
peer->bytes_to_write -= ret;
} else {
/*
* We should perhaps check for SSL_ERROR_WANT_READ/WRITE here
* but this doesn't yet occur with current app data sizes.
*/
peer->status = PEER_ERROR;
return;
}
}
/*
* We could simply finish when there was nothing to read, and we have
* nothing left to write. But keeping track of the expected number of bytes
* to read gives us somewhat better guarantees that all data sent is in fact
* received.
*/
if (peer->bytes_to_write == 0 && peer->bytes_to_read == 0) {
peer->status = PEER_SUCCESS;
}
}
static void do_reneg_setup_step(const SSL_TEST_CTX *test_ctx, PEER *peer)
{
int ret;
char buf;
if (peer->status == PEER_SUCCESS) {
/*
* We are a client that succeeded this step previously, but the server
* wanted to retry. Probably there is a no_renegotiation warning alert
* waiting for us. Attempt to continue the handshake.
*/
peer->status = PEER_RETRY;
do_handshake_step(peer);
return;
}
if (!TEST_int_eq(peer->status, PEER_RETRY)
|| !TEST_true(test_ctx->handshake_mode
== SSL_TEST_HANDSHAKE_RENEG_SERVER
|| test_ctx->handshake_mode
== SSL_TEST_HANDSHAKE_RENEG_CLIENT
|| test_ctx->handshake_mode
== SSL_TEST_HANDSHAKE_KEY_UPDATE_SERVER
|| test_ctx->handshake_mode
== SSL_TEST_HANDSHAKE_KEY_UPDATE_CLIENT
|| test_ctx->handshake_mode
== SSL_TEST_HANDSHAKE_POST_HANDSHAKE_AUTH)) {
peer->status = PEER_TEST_FAILURE;
return;
}
/* Reset the count of the amount of app data we need to read/write */
peer->bytes_to_write = peer->bytes_to_read = test_ctx->app_data_size;
/* Check if we are the peer that is going to initiate */
if ((test_ctx->handshake_mode == SSL_TEST_HANDSHAKE_RENEG_SERVER
&& SSL_is_server(peer->ssl))
|| (test_ctx->handshake_mode == SSL_TEST_HANDSHAKE_RENEG_CLIENT
&& !SSL_is_server(peer->ssl))) {
/*
* If we already asked for a renegotiation then fall through to the
* SSL_read() below.
*/
if (!SSL_renegotiate_pending(peer->ssl)) {
/*
* If we are the client we will always attempt to resume the
* session. The server may or may not resume dependent on the
* setting of SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION
*/
if (SSL_is_server(peer->ssl)) {
ret = SSL_renegotiate(peer->ssl);
} else {
int full_reneg = 0;
if (test_ctx->extra.client.no_extms_on_reneg) {
SSL_set_options(peer->ssl, SSL_OP_NO_EXTENDED_MASTER_SECRET);
full_reneg = 1;
}
if (test_ctx->extra.client.reneg_ciphers != NULL) {
if (!SSL_set_cipher_list(peer->ssl,
test_ctx->extra.client.reneg_ciphers)) {
peer->status = PEER_ERROR;
return;
}
full_reneg = 1;
}
if (full_reneg)
ret = SSL_renegotiate(peer->ssl);
else
ret = SSL_renegotiate_abbreviated(peer->ssl);
}
if (!ret) {
peer->status = PEER_ERROR;
return;
}
do_handshake_step(peer);
/*
* If status is PEER_RETRY it means we're waiting on the peer to
* continue the handshake. As far as setting up the renegotiation is
* concerned that is a success. The next step will continue the
* handshake to its conclusion.
*
* If status is PEER_SUCCESS then we are the server and we have
* successfully sent the HelloRequest. We need to continue to wait
* until the handshake arrives from the client.
*/
if (peer->status == PEER_RETRY)
peer->status = PEER_SUCCESS;
else if (peer->status == PEER_SUCCESS)
peer->status = PEER_RETRY;
return;
}
} else if (test_ctx->handshake_mode == SSL_TEST_HANDSHAKE_KEY_UPDATE_SERVER
|| test_ctx->handshake_mode
== SSL_TEST_HANDSHAKE_KEY_UPDATE_CLIENT) {
if (SSL_is_server(peer->ssl)
!= (test_ctx->handshake_mode
== SSL_TEST_HANDSHAKE_KEY_UPDATE_SERVER)) {
peer->status = PEER_SUCCESS;
return;
}
ret = SSL_key_update(peer->ssl, test_ctx->key_update_type);
if (!ret) {
peer->status = PEER_ERROR;
return;
}
do_handshake_step(peer);
/*
* This is a one step handshake. We shouldn't get anything other than
* PEER_SUCCESS
*/
if (peer->status != PEER_SUCCESS)
peer->status = PEER_ERROR;
return;
} else if (test_ctx->handshake_mode == SSL_TEST_HANDSHAKE_POST_HANDSHAKE_AUTH) {
if (SSL_is_server(peer->ssl)) {
/* Make the server believe it's received the extension */
if (test_ctx->extra.server.force_pha)
peer->ssl->post_handshake_auth = SSL_PHA_EXT_RECEIVED;
ret = SSL_verify_client_post_handshake(peer->ssl);
if (!ret) {
peer->status = PEER_ERROR;
return;
}
}
do_handshake_step(peer);
/*
* This is a one step handshake. We shouldn't get anything other than
* PEER_SUCCESS
*/
if (peer->status != PEER_SUCCESS)
peer->status = PEER_ERROR;
return;
}
/*
* The SSL object is still expecting app data, even though it's going to
* get a handshake message. We try to read, and it should fail - after which
* we should be in a handshake
*/
ret = SSL_read(peer->ssl, &buf, sizeof(buf));
if (ret >= 0) {
/*
* We're not actually expecting data - we're expecting a reneg to
* start
*/
peer->status = PEER_ERROR;
return;
} else {
int error = SSL_get_error(peer->ssl, ret);
if (error != SSL_ERROR_WANT_READ) {
peer->status = PEER_ERROR;
return;
}
/* If we're not in init yet then we're not done with setup yet */
if (!SSL_in_init(peer->ssl))
return;
}
peer->status = PEER_SUCCESS;
}
/*
* RFC 5246 says:
*
* Note that as of TLS 1.1,
* failure to properly close a connection no longer requires that a
* session not be resumed. This is a change from TLS 1.0 to conform
* with widespread implementation practice.
*
* However,
* (a) OpenSSL requires that a connection be shutdown for all protocol versions.
* (b) We test lower versions, too.
* So we just implement shutdown. We do a full bidirectional shutdown so that we
* can compare sent and received close_notify alerts and get some test coverage
* for SSL_shutdown as a bonus.
*/
static void do_shutdown_step(PEER *peer)
{
int ret;
if (!TEST_int_eq(peer->status, PEER_RETRY)) {
peer->status = PEER_TEST_FAILURE;
return;
}
ret = SSL_shutdown(peer->ssl);
if (ret == 1) {
peer->status = PEER_SUCCESS;
} else if (ret < 0) { /* On 0, we retry. */
int error = SSL_get_error(peer->ssl, ret);
if (error != SSL_ERROR_WANT_READ && error != SSL_ERROR_WANT_WRITE)
peer->status = PEER_ERROR;
}
}
typedef enum {
HANDSHAKE,
RENEG_APPLICATION_DATA,
RENEG_SETUP,
RENEG_HANDSHAKE,
APPLICATION_DATA,
SHUTDOWN,
CONNECTION_DONE
} connect_phase_t;
static int renegotiate_op(const SSL_TEST_CTX *test_ctx)
{
switch (test_ctx->handshake_mode) {
case SSL_TEST_HANDSHAKE_RENEG_SERVER:
case SSL_TEST_HANDSHAKE_RENEG_CLIENT:
return 1;
default:
return 0;
}
}
static int post_handshake_op(const SSL_TEST_CTX *test_ctx)
{
switch (test_ctx->handshake_mode) {
case SSL_TEST_HANDSHAKE_KEY_UPDATE_CLIENT:
case SSL_TEST_HANDSHAKE_KEY_UPDATE_SERVER:
case SSL_TEST_HANDSHAKE_POST_HANDSHAKE_AUTH:
return 1;
default:
return 0;
}
}
static connect_phase_t next_phase(const SSL_TEST_CTX *test_ctx,
connect_phase_t phase)
{
switch (phase) {
case HANDSHAKE:
if (renegotiate_op(test_ctx) || post_handshake_op(test_ctx))
return RENEG_APPLICATION_DATA;
return APPLICATION_DATA;
case RENEG_APPLICATION_DATA:
return RENEG_SETUP;
case RENEG_SETUP:
if (post_handshake_op(test_ctx))
return APPLICATION_DATA;
return RENEG_HANDSHAKE;
case RENEG_HANDSHAKE:
return APPLICATION_DATA;
case APPLICATION_DATA:
return SHUTDOWN;
case SHUTDOWN:
return CONNECTION_DONE;
case CONNECTION_DONE:
TEST_error("Trying to progress after connection done");
break;
}
return -1;
}
static void do_connect_step(const SSL_TEST_CTX *test_ctx, PEER *peer,
connect_phase_t phase)
{
switch (phase) {
case HANDSHAKE:
do_handshake_step(peer);
break;
case RENEG_APPLICATION_DATA:
do_app_data_step(peer);
break;
case RENEG_SETUP:
do_reneg_setup_step(test_ctx, peer);
break;
case RENEG_HANDSHAKE:
do_handshake_step(peer);
break;
case APPLICATION_DATA:
do_app_data_step(peer);
break;
case SHUTDOWN:
do_shutdown_step(peer);
break;
case CONNECTION_DONE:
TEST_error("Action after connection done");
break;
}
}
typedef enum {
/* Both parties succeeded. */
HANDSHAKE_SUCCESS,
/* Client errored. */
CLIENT_ERROR,
/* Server errored. */
SERVER_ERROR,
/* Peers are in inconsistent state. */
INTERNAL_ERROR,
/* One or both peers not done. */
HANDSHAKE_RETRY
} handshake_status_t;
/*
* Determine the handshake outcome.
* last_status: the status of the peer to have acted last.
* previous_status: the status of the peer that didn't act last.
* client_spoke_last: 1 if the client went last.
*/
static handshake_status_t handshake_status(peer_status_t last_status,
peer_status_t previous_status,
int client_spoke_last)
{
switch (last_status) {
case PEER_TEST_FAILURE:
return INTERNAL_ERROR;
case PEER_WAITING:
/* Shouldn't ever happen */
return INTERNAL_ERROR;
case PEER_SUCCESS:
switch (previous_status) {
case PEER_TEST_FAILURE:
return INTERNAL_ERROR;
case PEER_SUCCESS:
/* Both succeeded. */
return HANDSHAKE_SUCCESS;
case PEER_WAITING:
case PEER_RETRY:
/* Let the first peer finish. */
return HANDSHAKE_RETRY;
case PEER_ERROR:
/*
* Second peer succeeded despite the fact that the first peer
* already errored. This shouldn't happen.
*/
return INTERNAL_ERROR;
}
break;
case PEER_RETRY:
return HANDSHAKE_RETRY;
case PEER_ERROR:
switch (previous_status) {
case PEER_TEST_FAILURE:
return INTERNAL_ERROR;
case PEER_WAITING:
/* The client failed immediately before sending the ClientHello */
return client_spoke_last ? CLIENT_ERROR : INTERNAL_ERROR;
case PEER_SUCCESS:
/* First peer succeeded but second peer errored. */
return client_spoke_last ? CLIENT_ERROR : SERVER_ERROR;
case PEER_RETRY:
/* We errored; let the peer finish. */
return HANDSHAKE_RETRY;
case PEER_ERROR:
/* Both peers errored. Return the one that errored first. */
return client_spoke_last ? SERVER_ERROR : CLIENT_ERROR;
}
}
/* Control should never reach here. */
return INTERNAL_ERROR;
}
/* Convert unsigned char buf's that shouldn't contain any NUL-bytes to char. */
static char *dup_str(const unsigned char *in, size_t len)
{
char *ret = NULL;
if (len == 0)
return NULL;
/* Assert that the string does not contain NUL-bytes. */
if (TEST_size_t_eq(OPENSSL_strnlen((const char*)(in), len), len))
TEST_ptr(ret = OPENSSL_strndup((const char*)(in), len));
return ret;
}
static int pkey_type(EVP_PKEY *pkey)
{
if (EVP_PKEY_is_a(pkey, "EC")) {
char name[80];
size_t name_len;
if (!EVP_PKEY_get_group_name(pkey, name, sizeof(name), &name_len))
return NID_undef;
return OBJ_txt2nid(name);
}
return EVP_PKEY_get_id(pkey);
}
static int peer_pkey_type(SSL *s)
{
X509 *x = SSL_get0_peer_certificate(s);
if (x != NULL)
return pkey_type(X509_get0_pubkey(x));
return NID_undef;
}
#if !defined(OPENSSL_NO_SCTP) && !defined(OPENSSL_NO_SOCK)
static int set_sock_as_sctp(int sock)
{
struct sctp_assocparams assocparams;
struct sctp_rtoinfo rto_info;
BIO *tmpbio;
/*
* To allow tests to fail fast (within a second or so), reduce the
* retransmission timeouts and the number of retransmissions.
*/
memset(&rto_info, 0, sizeof(struct sctp_rtoinfo));
rto_info.srto_initial = 100;
rto_info.srto_max = 200;
rto_info.srto_min = 50;
(void)setsockopt(sock, IPPROTO_SCTP, SCTP_RTOINFO,
(const void *)&rto_info, sizeof(struct sctp_rtoinfo));
memset(&assocparams, 0, sizeof(struct sctp_assocparams));
assocparams.sasoc_asocmaxrxt = 2;
(void)setsockopt(sock, IPPROTO_SCTP, SCTP_ASSOCINFO,
(const void *)&assocparams,
sizeof(struct sctp_assocparams));
/*
* For SCTP we have to set various options on the socket prior to
* connecting. This is done automatically by BIO_new_dgram_sctp().
* We don't actually need the created BIO though so we free it again
* immediately.
*/
tmpbio = BIO_new_dgram_sctp(sock, BIO_NOCLOSE);
if (tmpbio == NULL)
return 0;
BIO_free(tmpbio);
return 1;
}
static int create_sctp_socks(int *ssock, int *csock)
{
BIO_ADDRINFO *res = NULL;
const BIO_ADDRINFO *ai = NULL;
int lsock = INVALID_SOCKET, asock = INVALID_SOCKET;
int consock = INVALID_SOCKET;
int ret = 0;
int family = 0;
if (BIO_sock_init() != 1)
return 0;
/*
* Port is 4463. It could be anything. It will fail if it's already being
* used for some other SCTP service. It seems unlikely though so we don't
* worry about it here.
*/
if (!BIO_lookup_ex(NULL, "4463", BIO_LOOKUP_SERVER, family, SOCK_STREAM,
IPPROTO_SCTP, &res))
return 0;
for (ai = res; ai != NULL; ai = BIO_ADDRINFO_next(ai)) {
family = BIO_ADDRINFO_family(ai);
lsock = BIO_socket(family, SOCK_STREAM, IPPROTO_SCTP, 0);
if (lsock == INVALID_SOCKET) {
/* Maybe the kernel doesn't support the socket family, even if
* BIO_lookup() added it in the returned result...
*/
continue;
}
if (!set_sock_as_sctp(lsock)
|| !BIO_listen(lsock, BIO_ADDRINFO_address(ai),
BIO_SOCK_REUSEADDR)) {
BIO_closesocket(lsock);
lsock = INVALID_SOCKET;
continue;
}
/* Success, don't try any more addresses */
break;
}
if (lsock == INVALID_SOCKET)
goto err;
BIO_ADDRINFO_free(res);
res = NULL;
if (!BIO_lookup_ex(NULL, "4463", BIO_LOOKUP_CLIENT, family, SOCK_STREAM,
IPPROTO_SCTP, &res))
goto err;
consock = BIO_socket(family, SOCK_STREAM, IPPROTO_SCTP, 0);
if (consock == INVALID_SOCKET)
goto err;
if (!set_sock_as_sctp(consock)
|| !BIO_connect(consock, BIO_ADDRINFO_address(res), 0)
|| !BIO_socket_nbio(consock, 1))
goto err;
asock = BIO_accept_ex(lsock, NULL, BIO_SOCK_NONBLOCK);
if (asock == INVALID_SOCKET)
goto err;
*csock = consock;
*ssock = asock;
consock = asock = INVALID_SOCKET;
ret = 1;
err:
BIO_ADDRINFO_free(res);
if (consock != INVALID_SOCKET)
BIO_closesocket(consock);
if (lsock != INVALID_SOCKET)
BIO_closesocket(lsock);
if (asock != INVALID_SOCKET)
BIO_closesocket(asock);
return ret;
}
#endif
/*
* Note that |extra| points to the correct client/server configuration
* within |test_ctx|. When configuring the handshake, general mode settings
* are taken from |test_ctx|, and client/server-specific settings should be
* taken from |extra|.
*
* The configuration code should never reach into |test_ctx->extra| or
* |test_ctx->resume_extra| directly.
*
* (We could refactor test mode settings into a substructure. This would result
* in cleaner argument passing but would complicate the test configuration
* parsing.)
*/
static HANDSHAKE_RESULT *do_handshake_internal(
SSL_CTX *server_ctx, SSL_CTX *server2_ctx, SSL_CTX *client_ctx,
const SSL_TEST_CTX *test_ctx, const SSL_TEST_EXTRA_CONF *extra,
SSL_SESSION *session_in, SSL_SESSION *serv_sess_in,
SSL_SESSION **session_out, SSL_SESSION **serv_sess_out)
{
PEER server, client;
BIO *client_to_server = NULL, *server_to_client = NULL;
HANDSHAKE_EX_DATA server_ex_data, client_ex_data;
CTX_DATA client_ctx_data, server_ctx_data, server2_ctx_data;
HANDSHAKE_RESULT *ret = HANDSHAKE_RESULT_new();
int client_turn = 1, client_turn_count = 0, client_wait_count = 0;
connect_phase_t phase = HANDSHAKE;
handshake_status_t status = HANDSHAKE_RETRY;
const unsigned char* tick = NULL;
size_t tick_len = 0;
const unsigned char* sess_id = NULL;
unsigned int sess_id_len = 0;
SSL_SESSION* sess = NULL;
const unsigned char *proto = NULL;
/* API dictates unsigned int rather than size_t. */
unsigned int proto_len = 0;
EVP_PKEY *tmp_key;
const STACK_OF(X509_NAME) *names;
time_t start;
const char* cipher;
if (ret == NULL)
return NULL;
memset(&server_ctx_data, 0, sizeof(server_ctx_data));
memset(&server2_ctx_data, 0, sizeof(server2_ctx_data));
memset(&client_ctx_data, 0, sizeof(client_ctx_data));
memset(&server, 0, sizeof(server));
memset(&client, 0, sizeof(client));
memset(&server_ex_data, 0, sizeof(server_ex_data));
memset(&client_ex_data, 0, sizeof(client_ex_data));
if (!configure_handshake_ctx(server_ctx, server2_ctx, client_ctx,
test_ctx, extra, &server_ctx_data,
&server2_ctx_data, &client_ctx_data)) {
TEST_note("configure_handshake_ctx");
HANDSHAKE_RESULT_free(ret);
return NULL;
}
#if !defined(OPENSSL_NO_SCTP) && !defined(OPENSSL_NO_SOCK)
if (test_ctx->enable_client_sctp_label_bug)
SSL_CTX_set_mode(client_ctx, SSL_MODE_DTLS_SCTP_LABEL_LENGTH_BUG);
if (test_ctx->enable_server_sctp_label_bug)
SSL_CTX_set_mode(server_ctx, SSL_MODE_DTLS_SCTP_LABEL_LENGTH_BUG);
#endif
/* Setup SSL and buffers; additional configuration happens below. */
if (!create_peer(&server, server_ctx)) {
TEST_note("creating server context");
goto err;
}
if (!create_peer(&client, client_ctx)) {
TEST_note("creating client context");
goto err;
}
server.bytes_to_write = client.bytes_to_read = test_ctx->app_data_size;
client.bytes_to_write = server.bytes_to_read = test_ctx->app_data_size;
configure_handshake_ssl(server.ssl, client.ssl, extra);
if (session_in != NULL) {
SSL_SESSION_get_id(serv_sess_in, &sess_id_len);
/* In case we're testing resumption without tickets. */
if ((sess_id_len > 0
&& !TEST_true(SSL_CTX_add_session(server_ctx,
serv_sess_in)))
|| !TEST_true(SSL_set_session(client.ssl, session_in)))
goto err;
sess_id_len = 0;
}
ret->result = SSL_TEST_INTERNAL_ERROR;
if (test_ctx->use_sctp) {
#if !defined(OPENSSL_NO_SCTP) && !defined(OPENSSL_NO_SOCK)
int csock, ssock;
if (create_sctp_socks(&ssock, &csock)) {
client_to_server = BIO_new_dgram_sctp(csock, BIO_CLOSE);
server_to_client = BIO_new_dgram_sctp(ssock, BIO_CLOSE);
}
#endif
} else {
client_to_server = BIO_new(BIO_s_mem());
server_to_client = BIO_new(BIO_s_mem());
}
if (!TEST_ptr(client_to_server)
|| !TEST_ptr(server_to_client))
goto err;
/* Non-blocking bio. */
BIO_set_nbio(client_to_server, 1);
BIO_set_nbio(server_to_client, 1);
SSL_set_connect_state(client.ssl);
SSL_set_accept_state(server.ssl);
/* The bios are now owned by the SSL object. */
if (test_ctx->use_sctp) {
SSL_set_bio(client.ssl, client_to_server, client_to_server);
SSL_set_bio(server.ssl, server_to_client, server_to_client);
} else {
SSL_set_bio(client.ssl, server_to_client, client_to_server);
if (!TEST_int_gt(BIO_up_ref(server_to_client), 0)
|| !TEST_int_gt(BIO_up_ref(client_to_server), 0))
goto err;
SSL_set_bio(server.ssl, client_to_server, server_to_client);
}
ex_data_idx = SSL_get_ex_new_index(0, "ex data", NULL, NULL, NULL);
if (!TEST_int_ge(ex_data_idx, 0)
|| !TEST_int_eq(SSL_set_ex_data(server.ssl, ex_data_idx, &server_ex_data), 1)
|| !TEST_int_eq(SSL_set_ex_data(client.ssl, ex_data_idx, &client_ex_data), 1))
goto err;
SSL_set_info_callback(server.ssl, &info_cb);
SSL_set_info_callback(client.ssl, &info_cb);
client.status = PEER_RETRY;
server.status = PEER_WAITING;
start = time(NULL);
/*
* Half-duplex handshake loop.
* Client and server speak to each other synchronously in the same process.
* We use non-blocking BIOs, so whenever one peer blocks for read, it
* returns PEER_RETRY to indicate that it's the other peer's turn to write.
* The handshake succeeds once both peers have succeeded. If one peer
* errors out, we also let the other peer retry (and presumably fail).
*/
for(;;) {
if (client_turn) {
do_connect_step(test_ctx, &client, phase);
status = handshake_status(client.status, server.status,
1 /* client went last */);
if (server.status == PEER_WAITING)
server.status = PEER_RETRY;
} else {
do_connect_step(test_ctx, &server, phase);
status = handshake_status(server.status, client.status,
0 /* server went last */);
}
switch (status) {
case HANDSHAKE_SUCCESS:
client_turn_count = 0;
phase = next_phase(test_ctx, phase);
if (phase == CONNECTION_DONE) {
ret->result = SSL_TEST_SUCCESS;
goto err;
} else {
client.status = server.status = PEER_RETRY;
/*
* For now, client starts each phase. Since each phase is
* started separately, we can later control this more
* precisely, for example, to test client-initiated and
* server-initiated shutdown.
*/
client_turn = 1;
break;
}
case CLIENT_ERROR:
ret->result = SSL_TEST_CLIENT_FAIL;
goto err;
case SERVER_ERROR:
ret->result = SSL_TEST_SERVER_FAIL;
goto err;
case INTERNAL_ERROR:
ret->result = SSL_TEST_INTERNAL_ERROR;
goto err;
case HANDSHAKE_RETRY:
if (test_ctx->use_sctp) {
if (time(NULL) - start > 3) {
/*
* We've waited for too long. Give up.
*/
ret->result = SSL_TEST_INTERNAL_ERROR;
goto err;
}
/*
* With "real" sockets we only swap to processing the peer
* if they are expecting to retry. Otherwise we just retry the
* same endpoint again.
*/
if ((client_turn && server.status == PEER_RETRY)
|| (!client_turn && client.status == PEER_RETRY))
client_turn ^= 1;
} else {
if (client_turn_count++ >= 2000) {
/*
* At this point, there's been so many PEER_RETRY in a row
* that it's likely both sides are stuck waiting for a read.
* It's time to give up.
*/
ret->result = SSL_TEST_INTERNAL_ERROR;
goto err;
}
if (client_turn && server.status == PEER_SUCCESS) {
/*
* The server may finish before the client because the
* client spends some turns processing NewSessionTickets.
*/
if (client_wait_count++ >= 2) {
ret->result = SSL_TEST_INTERNAL_ERROR;
goto err;
}
} else {
/* Continue. */
client_turn ^= 1;
}
}
break;
}
}
err:
ret->server_alert_sent = server_ex_data.alert_sent;
ret->server_num_fatal_alerts_sent = server_ex_data.num_fatal_alerts_sent;
ret->server_alert_received = client_ex_data.alert_received;
ret->client_alert_sent = client_ex_data.alert_sent;
ret->client_num_fatal_alerts_sent = client_ex_data.num_fatal_alerts_sent;
ret->client_alert_received = server_ex_data.alert_received;
ret->server_protocol = SSL_version(server.ssl);
ret->client_protocol = SSL_version(client.ssl);
ret->servername = server_ex_data.servername;
if ((sess = SSL_get0_session(client.ssl)) != NULL) {
SSL_SESSION_get0_ticket(sess, &tick, &tick_len);
sess_id = SSL_SESSION_get_id(sess, &sess_id_len);
}
if (tick == NULL || tick_len == 0)
ret->session_ticket = SSL_TEST_SESSION_TICKET_NO;
else
ret->session_ticket = SSL_TEST_SESSION_TICKET_YES;
ret->compression = (SSL_get_current_compression(client.ssl) == NULL)
? SSL_TEST_COMPRESSION_NO
: SSL_TEST_COMPRESSION_YES;
if (sess_id == NULL || sess_id_len == 0)
ret->session_id = SSL_TEST_SESSION_ID_NO;
else
ret->session_id = SSL_TEST_SESSION_ID_YES;
ret->session_ticket_do_not_call = server_ex_data.session_ticket_do_not_call;
if (extra->client.verify_callback == SSL_TEST_VERIFY_RETRY_ONCE
&& n_retries != -1)
ret->result = SSL_TEST_SERVER_FAIL;
#ifndef OPENSSL_NO_NEXTPROTONEG
SSL_get0_next_proto_negotiated(client.ssl, &proto, &proto_len);
ret->client_npn_negotiated = dup_str(proto, proto_len);
SSL_get0_next_proto_negotiated(server.ssl, &proto, &proto_len);
ret->server_npn_negotiated = dup_str(proto, proto_len);
#endif
SSL_get0_alpn_selected(client.ssl, &proto, &proto_len);
ret->client_alpn_negotiated = dup_str(proto, proto_len);
SSL_get0_alpn_selected(server.ssl, &proto, &proto_len);
ret->server_alpn_negotiated = dup_str(proto, proto_len);
if ((sess = SSL_get0_session(server.ssl)) != NULL) {
SSL_SESSION_get0_ticket_appdata(sess, (void**)&tick, &tick_len);
ret->result_session_ticket_app_data = OPENSSL_strndup((const char*)tick, tick_len);
}
ret->client_resumed = SSL_session_reused(client.ssl);
ret->server_resumed = SSL_session_reused(server.ssl);
cipher = SSL_CIPHER_get_name(SSL_get_current_cipher(client.ssl));
ret->cipher = dup_str((const unsigned char*)cipher, strlen(cipher));
if (session_out != NULL)
*session_out = SSL_get1_session(client.ssl);
if (serv_sess_out != NULL) {
SSL_SESSION *tmp = SSL_get_session(server.ssl);
/*
* We create a fresh copy that is not in the server session ctx linked
* list.
*/
if (tmp != NULL)
*serv_sess_out = SSL_SESSION_dup(tmp);
}
if (SSL_get_peer_tmp_key(client.ssl, &tmp_key)) {
ret->tmp_key_type = pkey_type(tmp_key);
EVP_PKEY_free(tmp_key);
}
SSL_get_peer_signature_nid(client.ssl, &ret->server_sign_hash);
SSL_get_peer_signature_nid(server.ssl, &ret->client_sign_hash);
SSL_get_peer_signature_type_nid(client.ssl, &ret->server_sign_type);
SSL_get_peer_signature_type_nid(server.ssl, &ret->client_sign_type);
names = SSL_get0_peer_CA_list(client.ssl);
if (names == NULL)
ret->client_ca_names = NULL;
else
ret->client_ca_names = SSL_dup_CA_list(names);
names = SSL_get0_peer_CA_list(server.ssl);
if (names == NULL)
ret->server_ca_names = NULL;
else
ret->server_ca_names = SSL_dup_CA_list(names);
ret->server_cert_type = peer_pkey_type(client.ssl);
ret->client_cert_type = peer_pkey_type(server.ssl);
ctx_data_free_data(&server_ctx_data);
ctx_data_free_data(&server2_ctx_data);
ctx_data_free_data(&client_ctx_data);
peer_free_data(&server);
peer_free_data(&client);
return ret;
}
HANDSHAKE_RESULT *do_handshake(SSL_CTX *server_ctx, SSL_CTX *server2_ctx,
SSL_CTX *client_ctx, SSL_CTX *resume_server_ctx,
SSL_CTX *resume_client_ctx,
const SSL_TEST_CTX *test_ctx)
{
HANDSHAKE_RESULT *result;
SSL_SESSION *session = NULL, *serv_sess = NULL;
result = do_handshake_internal(server_ctx, server2_ctx, client_ctx,
test_ctx, &test_ctx->extra,
NULL, NULL, &session, &serv_sess);
if (result == NULL
|| test_ctx->handshake_mode != SSL_TEST_HANDSHAKE_RESUME
|| result->result == SSL_TEST_INTERNAL_ERROR)
goto end;
if (result->result != SSL_TEST_SUCCESS) {
result->result = SSL_TEST_FIRST_HANDSHAKE_FAILED;
goto end;
}
HANDSHAKE_RESULT_free(result);
/* We don't support SNI on second handshake yet, so server2_ctx is NULL. */
result = do_handshake_internal(resume_server_ctx, NULL, resume_client_ctx,
test_ctx, &test_ctx->resume_extra,
session, serv_sess, NULL, NULL);
end:
SSL_SESSION_free(session);
SSL_SESSION_free(serv_sess);
return result;
}
diff --git a/crypto/openssl/test/hexstr_test.c b/crypto/openssl/test/hexstr_test.c
index 5a9684e0e697..566615ed6d68 100644
--- a/crypto/openssl/test/hexstr_test.c
+++ b/crypto/openssl/test/hexstr_test.c
@@ -1,134 +1,139 @@
/*
- * 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 may obtain a copy of the License at
* https://www.openssl.org/source/license.html
* or in the file LICENSE in the source distribution.
*/
/*
* This program tests the use of OSSL_PARAM, currently in raw form.
*/
#include "internal/nelem.h"
#include "internal/cryptlib.h"
#include "testutil.h"
struct testdata
{
const char *in;
const unsigned char *expected;
size_t expected_len;
const char sep;
};
static const unsigned char test_1[] = { 0xAB, 0xCD, 0xEF, 0xF1 };
static const unsigned char test_2[] = { 0xAB, 0xCD, 0xEF, 0x76, 0x00 };
static struct testdata tbl_testdata[] = {
{
"AB:CD:EF:F1",
test_1, sizeof(test_1),
':',
},
{
"AB:CD:EF:76:00",
test_2, sizeof(test_2),
':',
},
{
"AB_CD_EF_F1",
test_1, sizeof(test_1),
'_',
},
{
"AB_CD_EF_76_00",
test_2, sizeof(test_2),
'_',
},
{
"ABCDEFF1",
test_1, sizeof(test_1),
'\0',
},
{
"ABCDEF7600",
test_2, sizeof(test_2),
'\0',
},
};
static int test_hexstr_sep_to_from(int test_index)
{
int ret = 0;
long len = 0;
unsigned char *buf = NULL;
char *out = NULL;
struct testdata *test = &tbl_testdata[test_index];
if (!TEST_ptr(buf = ossl_hexstr2buf_sep(test->in, &len, test->sep))
|| !TEST_mem_eq(buf, len, test->expected, test->expected_len)
|| !TEST_ptr(out = ossl_buf2hexstr_sep(buf, len, test->sep))
|| !TEST_str_eq(out, test->in))
goto err;
ret = 1;
err:
OPENSSL_free(buf);
OPENSSL_free(out);
return ret;
}
static int test_hexstr_to_from(int test_index)
{
int ret = 0;
long len = 0;
unsigned char *buf = NULL;
char *out = NULL;
struct testdata *test = &tbl_testdata[test_index];
if (test->sep != '_') {
if (!TEST_ptr(buf = OPENSSL_hexstr2buf(test->in, &len))
|| !TEST_mem_eq(buf, len, test->expected, test->expected_len)
|| !TEST_ptr(out = OPENSSL_buf2hexstr(buf, len)))
goto err;
if (test->sep == ':') {
if (!TEST_str_eq(out, test->in))
goto err;
} else if (!TEST_str_ne(out, test->in)) {
goto err;
}
} else {
if (!TEST_ptr_null(buf = OPENSSL_hexstr2buf(test->in, &len)))
goto err;
}
ret = 1;
err:
OPENSSL_free(buf);
OPENSSL_free(out);
return ret;
}
static int test_hexstr_ex_to_from(int test_index)
{
size_t len = 0;
char out[64];
unsigned char buf[64];
struct testdata *test = &tbl_testdata[test_index];
return TEST_true(OPENSSL_hexstr2buf_ex(buf, sizeof(buf), &len, test->in, ':'))
&& TEST_mem_eq(buf, len, test->expected, test->expected_len)
+ && TEST_false(OPENSSL_buf2hexstr_ex(out, 3 * len - 1, NULL, buf, len,
+ ':'))
&& TEST_true(OPENSSL_buf2hexstr_ex(out, sizeof(out), NULL, buf, len,
- ':'))
- && TEST_str_eq(out, test->in);
+ ':'))
+ && TEST_str_eq(out, test->in)
+ && TEST_true(OPENSSL_buf2hexstr_ex(out, sizeof(out), NULL, buf, 0,
+ ':'))
+ && TEST_size_t_eq(strlen(out), 0);
}
int setup_tests(void)
{
ADD_ALL_TESTS(test_hexstr_sep_to_from, OSSL_NELEM(tbl_testdata));
ADD_ALL_TESTS(test_hexstr_to_from, OSSL_NELEM(tbl_testdata));
ADD_ALL_TESTS(test_hexstr_ex_to_from, 2);
return 1;
}
diff --git a/crypto/openssl/test/prov_config_test.c b/crypto/openssl/test/prov_config_test.c
index f93d8d62be6a..2fd913deadf4 100644
--- a/crypto/openssl/test/prov_config_test.c
+++ b/crypto/openssl/test/prov_config_test.c
@@ -1,145 +1,140 @@
/*
* 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;
+ goto err;
if (!TEST_true(OSSL_LIB_CTX_load_config(ctx, configfile)))
- return 0;
+ goto err;
/* 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/provider_fallback_test.c b/crypto/openssl/test/provider_fallback_test.c
index 5902f57c85e7..26ba9ea1dcb0 100644
--- a/crypto/openssl/test/provider_fallback_test.c
+++ b/crypto/openssl/test/provider_fallback_test.c
@@ -1,57 +1,63 @@
/*
- * 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
* https://www.openssl.org/source/license.html
*/
#include <stddef.h>
#include <openssl/provider.h>
#include <openssl/evp.h>
#include "testutil.h"
static int test_provider(OSSL_LIB_CTX *ctx)
{
EVP_KEYMGMT *rsameth = NULL;
const OSSL_PROVIDER *prov = NULL;
int ok;
ok = TEST_true(OSSL_PROVIDER_available(ctx, "default"))
&& TEST_ptr(rsameth = EVP_KEYMGMT_fetch(ctx, "RSA", NULL))
&& TEST_ptr(prov = EVP_KEYMGMT_get0_provider(rsameth))
&& TEST_str_eq(OSSL_PROVIDER_get0_name(prov), "default");
EVP_KEYMGMT_free(rsameth);
return ok;
}
static int test_fallback_provider(void)
{
return test_provider(NULL);
}
static int test_explicit_provider(void)
{
OSSL_LIB_CTX *ctx = NULL;
OSSL_PROVIDER *prov = NULL;
int ok;
ok = TEST_ptr(ctx = OSSL_LIB_CTX_new())
- && TEST_ptr(prov = OSSL_PROVIDER_load(ctx, "default"))
- && test_provider(ctx)
- && TEST_true(OSSL_PROVIDER_unload(prov));
+ && TEST_ptr(prov = OSSL_PROVIDER_load(ctx, "default"));
+
+ if (ok) {
+ ok = test_provider(ctx);
+ if (ok)
+ ok = TEST_true(OSSL_PROVIDER_unload(prov));
+ else
+ OSSL_PROVIDER_unload(prov);
+ }
OSSL_LIB_CTX_free(ctx);
return ok;
}
int setup_tests(void)
{
ADD_TEST(test_fallback_provider);
ADD_TEST(test_explicit_provider);
return 1;
}
diff --git a/crypto/openssl/test/provider_internal_test.c b/crypto/openssl/test/provider_internal_test.c
index 1fe8fb0cc5c4..e42af73b1746 100644
--- a/crypto/openssl/test/provider_internal_test.c
+++ b/crypto/openssl/test/provider_internal_test.c
@@ -1,151 +1,151 @@
/*
- * 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 <stddef.h>
#include <openssl/crypto.h>
#include "internal/provider.h"
#include "testutil.h"
extern OSSL_provider_init_fn PROVIDER_INIT_FUNCTION_NAME;
static char buf[256];
static OSSL_PARAM greeting_request[] = {
{ "greeting", OSSL_PARAM_UTF8_STRING, buf, sizeof(buf), 0 },
{ NULL, 0, NULL, 0, 0 }
};
static int test_provider(OSSL_PROVIDER *prov, const char *expected_greeting)
{
- const char *greeting = NULL;
+ const char *greeting = "no greeting received";
int ret = 0;
ret =
TEST_true(ossl_provider_activate(prov, 1, 0))
&& TEST_true(ossl_provider_get_params(prov, greeting_request))
&& TEST_ptr(greeting = greeting_request[0].data)
&& TEST_size_t_gt(greeting_request[0].data_size, 0)
&& TEST_str_eq(greeting, expected_greeting)
&& TEST_true(ossl_provider_deactivate(prov, 1));
TEST_info("Got this greeting: %s\n", greeting);
ossl_provider_free(prov);
return ret;
}
static const char *expected_greeting1(const char *name)
{
static char expected_greeting[256] = "";
BIO_snprintf(expected_greeting, sizeof(expected_greeting),
"Hello OpenSSL %.20s, greetings from %s!",
OPENSSL_VERSION_STR, name);
return expected_greeting;
}
static int test_builtin_provider(void)
{
const char *name = "p_test_builtin";
OSSL_PROVIDER *prov = NULL;
int ret;
/*
* We set properties that we know the providers we are using don't have.
* This should mean that the p_test provider will fail any fetches - which
* is something we test inside the provider.
*/
EVP_set_default_properties(NULL, "fips=yes");
ret =
TEST_ptr(prov =
ossl_provider_new(NULL, name, PROVIDER_INIT_FUNCTION_NAME, 0))
&& test_provider(prov, expected_greeting1(name));
EVP_set_default_properties(NULL, "");
return ret;
}
#ifndef NO_PROVIDER_MODULE
static int test_loaded_provider(void)
{
const char *name = "p_test";
OSSL_PROVIDER *prov = NULL;
return
TEST_ptr(prov = ossl_provider_new(NULL, name, NULL, 0))
&& test_provider(prov, expected_greeting1(name));
}
# ifndef OPENSSL_NO_AUTOLOAD_CONFIG
static int test_configured_provider(void)
{
const char *name = "p_test_configured";
OSSL_PROVIDER *prov = NULL;
/* This MUST match the config file */
const char *expected_greeting =
"Hello OpenSSL, greetings from Test Provider";
return
TEST_ptr(prov = ossl_provider_find(NULL, name, 0))
&& test_provider(prov, expected_greeting);
}
# endif
#endif
static int test_cache_flushes(void)
{
OSSL_LIB_CTX *ctx;
OSSL_PROVIDER *prov = NULL;
EVP_MD *md = NULL;
int ret = 0;
if (!TEST_ptr(ctx = OSSL_LIB_CTX_new())
|| !TEST_ptr(prov = OSSL_PROVIDER_load(ctx, "default"))
|| !TEST_true(OSSL_PROVIDER_available(ctx, "default"))
|| !TEST_ptr(md = EVP_MD_fetch(ctx, "SHA256", NULL)))
goto err;
EVP_MD_free(md);
md = NULL;
OSSL_PROVIDER_unload(prov);
prov = NULL;
if (!TEST_false(OSSL_PROVIDER_available(ctx, "default")))
goto err;
if (!TEST_ptr_null(md = EVP_MD_fetch(ctx, "SHA256", NULL))) {
const char *provname = OSSL_PROVIDER_get0_name(EVP_MD_get0_provider(md));
if (OSSL_PROVIDER_available(NULL, provname))
TEST_info("%s provider is available\n", provname);
else
TEST_info("%s provider is not available\n", provname);
}
ret = 1;
err:
OSSL_PROVIDER_unload(prov);
EVP_MD_free(md);
OSSL_LIB_CTX_free(ctx);
return ret;
}
int setup_tests(void)
{
ADD_TEST(test_builtin_provider);
#ifndef NO_PROVIDER_MODULE
ADD_TEST(test_loaded_provider);
# ifndef OPENSSL_NO_AUTOLOAD_CONFIG
ADD_TEST(test_configured_provider);
# endif
#endif
ADD_TEST(test_cache_flushes);
return 1;
}
diff --git a/crypto/openssl/test/provider_test.c b/crypto/openssl/test/provider_test.c
index b2e0a5da716f..762c2ee16eff 100644
--- a/crypto/openssl/test/provider_test.c
+++ b/crypto/openssl/test/provider_test.c
@@ -1,270 +1,271 @@
/*
- * 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 <stddef.h>
#include <openssl/provider.h>
#include "testutil.h"
extern OSSL_provider_init_fn PROVIDER_INIT_FUNCTION_NAME;
static char buf[256];
static OSSL_PARAM greeting_request[] = {
{ "greeting", OSSL_PARAM_UTF8_STRING, buf, sizeof(buf) },
{ NULL, 0, NULL, 0, 0 }
};
static unsigned int digestsuccess = 0;
static OSSL_PARAM digest_check[] = {
{ "digest-check", OSSL_PARAM_UNSIGNED_INTEGER, &digestsuccess,
sizeof(digestsuccess) },
{ NULL, 0, NULL, 0, 0 }
};
static unsigned int stopsuccess = 0;
static OSSL_PARAM stop_property_mirror[] = {
{ "stop-property-mirror", OSSL_PARAM_UNSIGNED_INTEGER, &stopsuccess,
sizeof(stopsuccess) },
{ NULL, 0, NULL, 0, 0 }
};
static int test_provider(OSSL_LIB_CTX **libctx, const char *name,
OSSL_PROVIDER *legacy)
{
OSSL_PROVIDER *prov = NULL;
const char *greeting = NULL;
char expected_greeting[256];
int ok = 0;
long err;
int dolegacycheck = (legacy != NULL);
OSSL_PROVIDER *deflt = NULL, *base = NULL;
BIO_snprintf(expected_greeting, sizeof(expected_greeting),
"Hello OpenSSL %.20s, greetings from %s!",
OPENSSL_VERSION_STR, name);
/*
* We set properties that we know the providers we are using don't have.
* This should mean that the p_test provider will fail any fetches - which
* is something we test inside the provider.
*/
EVP_set_default_properties(*libctx, "fips=yes");
/*
* Check that it is possible to have a built-in provider mirrored in
* a child lib ctx.
*/
if (!TEST_ptr(base = OSSL_PROVIDER_load(*libctx, "base")))
goto err;
if (!TEST_ptr(prov = OSSL_PROVIDER_load(*libctx, name)))
goto err;
/*
* Once the provider is loaded we clear the default properties and fetches
* should start working again.
*/
EVP_set_default_properties(*libctx, "");
if (dolegacycheck) {
if (!TEST_true(OSSL_PROVIDER_get_params(prov, digest_check))
|| !TEST_true(digestsuccess))
goto err;
/*
* Check that a provider can prevent property mirroring if it sets its
* own properties explicitly
*/
if (!TEST_true(OSSL_PROVIDER_get_params(prov, stop_property_mirror))
|| !TEST_true(stopsuccess))
goto err;
EVP_set_default_properties(*libctx, "fips=yes");
if (!TEST_true(OSSL_PROVIDER_get_params(prov, digest_check))
|| !TEST_true(digestsuccess))
goto err;
EVP_set_default_properties(*libctx, "");
}
if (!TEST_true(OSSL_PROVIDER_get_params(prov, greeting_request))
|| !TEST_ptr(greeting = greeting_request[0].data)
|| !TEST_size_t_gt(greeting_request[0].data_size, 0)
|| !TEST_str_eq(greeting, expected_greeting))
goto err;
/* Make sure we got the error we were expecting */
err = ERR_peek_last_error();
if (!TEST_int_gt(err, 0)
|| !TEST_int_eq(ERR_GET_REASON(err), 1))
goto err;
OSSL_PROVIDER_unload(legacy);
legacy = NULL;
if (dolegacycheck) {
/* Legacy provider should also be unloaded from child libctx */
if (!TEST_true(OSSL_PROVIDER_get_params(prov, digest_check))
|| !TEST_false(digestsuccess))
goto err;
/*
* Loading the legacy provider again should make it available again in
* the child libctx. Loading and unloading the default provider should
* have no impact on the child because the child loads it explicitly
* before this point.
*/
legacy = OSSL_PROVIDER_load(*libctx, "legacy");
deflt = OSSL_PROVIDER_load(*libctx, "default");
if (!TEST_ptr(deflt)
|| !TEST_true(OSSL_PROVIDER_available(*libctx, "default")))
goto err;
OSSL_PROVIDER_unload(deflt);
deflt = NULL;
if (!TEST_ptr(legacy)
|| !TEST_false(OSSL_PROVIDER_available(*libctx, "default"))
|| !TEST_true(OSSL_PROVIDER_get_params(prov, digest_check))
|| !TEST_true(digestsuccess))
goto err;
OSSL_PROVIDER_unload(legacy);
legacy = NULL;
}
if (!TEST_true(OSSL_PROVIDER_unload(base)))
goto err;
base = NULL;
if (!TEST_true(OSSL_PROVIDER_unload(prov)))
goto err;
prov = NULL;
/*
* We must free the libctx to force the provider to really be unloaded from
* memory
*/
OSSL_LIB_CTX_free(*libctx);
*libctx = NULL;
/* We print out all the data to make sure it can still be accessed */
ERR_print_errors_fp(stderr);
ok = 1;
err:
OSSL_PROVIDER_unload(base);
OSSL_PROVIDER_unload(deflt);
OSSL_PROVIDER_unload(legacy);
legacy = NULL;
OSSL_PROVIDER_unload(prov);
OSSL_LIB_CTX_free(*libctx);
*libctx = NULL;
return ok;
}
static int test_builtin_provider(void)
{
OSSL_LIB_CTX *libctx = OSSL_LIB_CTX_new();
const char *name = "p_test_builtin";
int ok;
ok =
TEST_ptr(libctx)
&& TEST_true(OSSL_PROVIDER_add_builtin(libctx, name,
PROVIDER_INIT_FUNCTION_NAME))
&& test_provider(&libctx, name, NULL);
OSSL_LIB_CTX_free(libctx);
return ok;
}
/* Test relies on fetching the MD4 digest from the legacy provider */
#ifndef OPENSSL_NO_MD4
static int test_builtin_provider_with_child(void)
{
OSSL_LIB_CTX *libctx = OSSL_LIB_CTX_new();
const char *name = "p_test";
OSSL_PROVIDER *legacy;
if (!TEST_ptr(libctx))
return 0;
legacy = OSSL_PROVIDER_load(libctx, "legacy");
if (legacy == NULL) {
/*
* In this case we assume we've been built with "no-legacy" and skip
* this test (there is no OPENSSL_NO_LEGACY)
*/
OSSL_LIB_CTX_free(libctx);
return 1;
}
if (!TEST_true(OSSL_PROVIDER_add_builtin(libctx, name,
PROVIDER_INIT_FUNCTION_NAME))) {
+ OSSL_PROVIDER_unload(legacy);
OSSL_LIB_CTX_free(libctx);
return 0;
}
/* test_provider will free libctx and unload legacy as part of the test */
return test_provider(&libctx, name, legacy);
}
#endif
#ifndef NO_PROVIDER_MODULE
static int test_loaded_provider(void)
{
OSSL_LIB_CTX *libctx = OSSL_LIB_CTX_new();
const char *name = "p_test";
if (!TEST_ptr(libctx))
return 0;
/* test_provider will free libctx as part of the test */
return test_provider(&libctx, name, NULL);
}
#endif
typedef enum OPTION_choice {
OPT_ERR = -1,
OPT_EOF = 0,
OPT_LOADED,
OPT_TEST_ENUM
} OPTION_CHOICE;
const OPTIONS *test_get_options(void)
{
static const OPTIONS test_options[] = {
OPT_TEST_OPTIONS_DEFAULT_USAGE,
{ "loaded", OPT_LOADED, '-', "Run test with a loaded provider" },
{ NULL }
};
return test_options;
}
int setup_tests(void)
{
OPTION_CHOICE o;
int loaded = 0;
while ((o = opt_next()) != OPT_EOF) {
switch (o) {
case OPT_TEST_CASES:
break;
case OPT_LOADED:
loaded = 1;
break;
default:
return 0;
}
}
if (!loaded) {
ADD_TEST(test_builtin_provider);
#ifndef OPENSSL_NO_MD4
ADD_TEST(test_builtin_provider_with_child);
#endif
}
#ifndef NO_PROVIDER_MODULE
else {
ADD_TEST(test_loaded_provider);
}
#endif
return 1;
}
diff --git a/crypto/openssl/test/recipes/03-test_fipsinstall.t b/crypto/openssl/test/recipes/03-test_fipsinstall.t
index c39b2cee09ec..5f514e231b59 100644
--- a/crypto/openssl/test/recipes/03-test_fipsinstall.t
+++ b/crypto/openssl/test/recipes/03-test_fipsinstall.t
@@ -1,310 +1,316 @@
#! /usr/bin/env perl
-# 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
use strict;
use warnings;
use File::Spec::Functions qw(:DEFAULT abs2rel);
use File::Copy;
use OpenSSL::Glob;
use OpenSSL::Test qw/:DEFAULT srctop_dir srctop_file bldtop_dir bldtop_file/;
use OpenSSL::Test::Utils;
BEGIN {
setup("test_fipsinstall");
}
use lib srctop_dir('Configurations');
use lib bldtop_dir('.');
use platform;
plan skip_all => "Test only supported in a fips build" if disabled("fips");
plan tests => 29;
my $infile = bldtop_file('providers', platform->dso('fips'));
my $fipskey = $ENV{FIPSKEY} // config('FIPSKEY') // '00';
my $provconf = srctop_file("test", "fips-and-base.cnf");
+run(test(["fips_version_test", "-config", $provconf, "<3.4.0"]),
+ capture => 1, statusvar => \my $indicatorpost);
+
# Read in a text $infile and replace the regular expression in $srch with the
# value in $repl and output to a new file $outfile.
sub replace_line_file_internal {
my ($infile, $srch, $repl, $outfile) = @_;
my $msg;
open(my $in, "<", $infile) or return 0;
read($in, $msg, 1024);
close $in;
$msg =~ s/$srch/$repl/;
open(my $fh, ">", $outfile) or return 0;
print $fh $msg;
close $fh;
return 1;
}
# Read in the text input file 'fips.cnf'
# and replace a single Key = Value line with a new value in $value.
# OR remove the Key = Value line if the passed in $value is empty.
# and then output a new file $outfile.
# $key is the Key to find
sub replace_line_file {
my ($key, $value, $outfile) = @_;
my $srch = qr/$key\s*=\s*\S*\n/;
my $rep;
if ($value eq "") {
$rep = "";
} else {
$rep = "$key = $value\n";
}
return replace_line_file_internal('fips.cnf', $srch, $rep, $outfile);
}
# Read in the text input file 'test/fips.cnf'
# and replace the .cnf file used in
# .include fipsmodule.cnf with a new value in $value.
# and then output a new file $outfile.
# $key is the Key to find
sub replace_parent_line_file {
my ($value, $outfile) = @_;
my $srch = qr/fipsmodule.cnf/;
my $rep = "$value";
return replace_line_file_internal(srctop_file("test", 'fips.cnf'),
$srch, $rep, $outfile);
}
# fail if no module name
ok(!run(app(['openssl', 'fipsinstall', '-out', 'fips.cnf', '-module',
'-provider_name', 'fips',
'-macopt', 'digest:SHA256', '-macopt', "hexkey:$fipskey",
'-section_name', 'fips_sect'])),
"fipsinstall fail");
# fail to verify if the configuration file is missing
ok(!run(app(['openssl', 'fipsinstall', '-in', 'dummy.tmp', '-module', $infile,
'-provider_name', 'fips', '-mac_name', 'HMAC',
'-macopt', 'digest:SHA256', '-macopt', "hexkey:$fipskey",
'-section_name', 'fips_sect', '-verify'])),
"fipsinstall verify fail");
# output a fips.cnf file containing mac data
ok(run(app(['openssl', 'fipsinstall', '-out', 'fips.cnf', '-module', $infile,
'-provider_name', 'fips', '-mac_name', 'HMAC',
'-macopt', 'digest:SHA256', '-macopt', "hexkey:$fipskey",
'-section_name', 'fips_sect'])),
"fipsinstall");
# verify the fips.cnf file
ok(run(app(['openssl', 'fipsinstall', '-in', 'fips.cnf', '-module', $infile,
'-provider_name', 'fips', '-mac_name', 'HMAC',
'-macopt', 'digest:SHA256', '-macopt', "hexkey:$fipskey",
'-section_name', 'fips_sect', '-verify'])),
"fipsinstall verify");
ok(replace_line_file('module-mac', '', 'fips_no_module_mac.cnf')
&& !run(app(['openssl', 'fipsinstall',
'-in', 'fips_no_module_mac.cnf',
'-module', $infile,
'-provider_name', 'fips', '-mac_name', 'HMAC',
'-macopt', 'digest:SHA256', '-macopt', "hexkey:01",
'-section_name', 'fips_sect', '-verify'])),
"fipsinstall verify fail no module mac");
ok(replace_line_file('install-mac', '', 'fips_no_install_mac.cnf')
&& !run(app(['openssl', 'fipsinstall',
'-in', 'fips_no_install_mac.cnf',
'-module', $infile,
'-provider_name', 'fips', '-mac_name', 'HMAC',
'-macopt', 'digest:SHA256', '-macopt', "hexkey:01",
'-section_name', 'fips_sect', '-verify'])),
"fipsinstall verify fail no install indicator mac");
ok(replace_line_file('module-mac', '00:00:00:00:00:00',
'fips_bad_module_mac.cnf')
&& !run(app(['openssl', 'fipsinstall',
'-in', 'fips_bad_module_mac.cnf',
'-module', $infile,
'-provider_name', 'fips', '-mac_name', 'HMAC',
'-macopt', 'digest:SHA256', '-macopt', "hexkey:01",
'-section_name', 'fips_sect', '-verify'])),
"fipsinstall verify fail if invalid module integrity value");
ok(replace_line_file('install-mac', '00:00:00:00:00:00',
'fips_bad_install_mac.cnf')
&& !run(app(['openssl', 'fipsinstall',
'-in', 'fips_bad_install_mac.cnf',
'-module', $infile,
'-provider_name', 'fips', '-mac_name', 'HMAC',
'-macopt', 'digest:SHA256', '-macopt', "hexkey:01",
'-section_name', 'fips_sect', '-verify'])),
"fipsinstall verify fail if invalid install indicator integrity value");
ok(replace_line_file('install-status', 'INCORRECT_STATUS_STRING',
'fips_bad_indicator.cnf')
&& !run(app(['openssl', 'fipsinstall',
'-in', 'fips_bad_indicator.cnf',
'-module', $infile,
'-provider_name', 'fips', '-mac_name', 'HMAC',
'-macopt', 'digest:SHA256', '-macopt', "hexkey:01",
'-section_name', 'fips_sect', '-verify'])),
"fipsinstall verify fail if invalid install indicator status");
# fail to verify the fips.cnf file if a different key is used
ok(!run(app(['openssl', 'fipsinstall', '-in', 'fips.cnf', '-module', $infile,
'-provider_name', 'fips', '-mac_name', 'HMAC',
'-macopt', 'digest:SHA256', '-macopt', "hexkey:01",
'-section_name', 'fips_sect', '-verify'])),
"fipsinstall verify fail bad key");
# fail to verify the fips.cnf file if a different mac digest is used
ok(!run(app(['openssl', 'fipsinstall', '-in', 'fips.cnf', '-module', $infile,
'-provider_name', 'fips', '-mac_name', 'HMAC',
'-macopt', 'digest:SHA512', '-macopt', "hexkey:$fipskey",
'-section_name', 'fips_sect', '-verify'])),
"fipsinstall verify fail incorrect digest");
# corrupt the module hmac
ok(!run(app(['openssl', 'fipsinstall', '-out', 'fips.cnf', '-module', $infile,
'-provider_name', 'fips', '-mac_name', 'HMAC',
'-macopt', 'digest:SHA256', '-macopt', "hexkey:$fipskey",
'-section_name', 'fips_sect', '-corrupt_desc', 'HMAC'])),
"fipsinstall fails when the module integrity is corrupted");
# corrupt the first digest
ok(!run(app(['openssl', 'fipsinstall', '-out', 'fips_fail.cnf', '-module', $infile,
'-provider_name', 'fips', '-mac_name', 'HMAC',
'-macopt', 'digest:SHA256', '-macopt', "hexkey:$fipskey",
- '-section_name', 'fips_sect', '-corrupt_desc', 'SHA1'])),
+ '-section_name', 'fips_sect', '-corrupt_desc', 'SHA2'])),
"fipsinstall fails when the digest result is corrupted");
# corrupt another digest
ok(!run(app(['openssl', 'fipsinstall', '-out', 'fips_fail.cnf', '-module', $infile,
'-provider_name', 'fips', '-mac_name', 'HMAC',
'-macopt', 'digest:SHA256', '-macopt', "hexkey:$fipskey",
'-section_name', 'fips_sect', '-corrupt_desc', 'SHA3'])),
"fipsinstall fails when the digest result is corrupted");
# corrupt cipher encrypt test
ok(!run(app(['openssl', 'fipsinstall', '-out', 'fips_fail.cnf', '-module', $infile,
'-provider_name', 'fips', '-mac_name', 'HMAC',
'-macopt', 'digest:SHA256', '-macopt', "hexkey:$fipskey",
'-section_name', 'fips_sect', '-corrupt_desc', 'AES_GCM'])),
"fipsinstall fails when the AES_GCM result is corrupted");
# corrupt cipher decrypt test
ok(!run(app(['openssl', 'fipsinstall', '-out', 'fips_fail.cnf', '-module', $infile,
'-provider_name', 'fips', '-mac_name', 'HMAC',
'-macopt', 'digest:SHA256', '-macopt', "hexkey:$fipskey",
'-section_name', 'fips_sect', '-corrupt_desc', 'AES_ECB_Decrypt'])),
"fipsinstall fails when the AES_ECB result is corrupted");
# corrupt DRBG
ok(!run(app(['openssl', 'fipsinstall', '-out', 'fips_fail.cnf', '-module', $infile,
'-provider_name', 'fips', '-mac_name', 'HMAC',
'-macopt', 'digest:SHA256', '-macopt', "hexkey:$fipskey",
'-section_name', 'fips_sect', '-corrupt_desc', 'CTR'])),
"fipsinstall fails when the DRBG CTR result is corrupted");
# corrupt a KAS test
SKIP: {
skip "Skipping KAS DH corruption test because of no dh in this build", 1
if disabled("dh");
ok(!run(app(['openssl', 'fipsinstall', '-out', 'fips.cnf', '-module', $infile,
'-provider_name', 'fips', '-mac_name', 'HMAC',
'-macopt', 'digest:SHA256', '-macopt', "hexkey:$fipskey",
'-section_name', 'fips_sect',
'-corrupt_desc', 'DH',
'-corrupt_type', 'KAT_KA'])),
"fipsinstall fails when the kas result is corrupted");
}
# corrupt a Signature test
SKIP: {
skip "Skipping Signature DSA corruption test because of no dsa in this build", 1
if disabled("dsa");
run(test(["fips_version_test", "-config", $provconf, "<3.1.0"]),
capture => 1, statusvar => \my $exit);
skip "FIPS provider version is too new for PCT DSA signature test", 1
if !$exit;
ok(!run(app(['openssl', 'fipsinstall', '-out', 'fips.cnf', '-module', $infile,
'-provider_name', 'fips', '-mac_name', 'HMAC',
'-macopt', 'digest:SHA256', '-macopt', "hexkey:$fipskey",
'-section_name', 'fips_sect',
'-corrupt_desc', 'DSA',
'-corrupt_type', 'PCT_Signature'])),
"fipsinstall fails when the signature result is corrupted");
}
# corrupt an Asymmetric cipher test
SKIP: {
skip "Skipping Asymmetric RSA corruption test because of no rsa in this build", 1
if disabled("rsa");
ok(!run(app(['openssl', 'fipsinstall', '-out', 'fips.cnf', '-module', $infile,
'-corrupt_desc', 'RSA_Encrypt',
'-corrupt_type', 'KAT_AsymmetricCipher'])),
"fipsinstall fails when the asymmetric cipher result is corrupted");
}
# 'local' ensures that this change is only done in this file.
local $ENV{OPENSSL_CONF_INCLUDE} = abs2rel(curdir());
ok(replace_parent_line_file('fips.cnf', 'fips_parent.cnf')
&& run(app(['openssl', 'fipsinstall', '-config', 'fips_parent.cnf'])),
"verify fips provider loads from a configuration file");
ok(replace_parent_line_file('fips_no_module_mac.cnf',
'fips_parent_no_module_mac.cnf')
&& !run(app(['openssl', 'fipsinstall',
'-config', 'fips_parent_no_module_mac.cnf'])),
"verify load config fail no module mac");
-ok(replace_parent_line_file('fips_no_install_mac.cnf',
- 'fips_parent_no_install_mac.cnf')
- && !run(app(['openssl', 'fipsinstall',
- '-config', 'fips_parent_no_install_mac.cnf'])),
- "verify load config fail no install mac");
-
-ok(replace_parent_line_file('fips_bad_indicator.cnf',
- 'fips_parent_bad_indicator.cnf')
- && !run(app(['openssl', 'fipsinstall',
- '-config', 'fips_parent_bad_indicator.cnf'])),
- "verify load config fail bad indicator");
-
-ok(replace_parent_line_file('fips_bad_install_mac.cnf',
- 'fips_parent_bad_install_mac.cnf')
- && !run(app(['openssl', 'fipsinstall',
- '-config', 'fips_parent_bad_install_mac.cnf'])),
- "verify load config fail bad install mac");
+SKIP: {
+ skip "Newer FIPS provider version does not support this feature", 3
+ if !$indicatorpost;
+
+ ok(replace_parent_line_file('fips_no_install_mac.cnf',
+ 'fips_parent_no_install_mac.cnf')
+ && !run(app(['openssl', 'fipsinstall',
+ '-config', 'fips_parent_no_install_mac.cnf'])),
+ "verify load config fail no install mac");
+ ok(replace_parent_line_file('fips_bad_indicator.cnf',
+ 'fips_parent_bad_indicator.cnf')
+ && !run(app(['openssl', 'fipsinstall',
+ '-config', 'fips_parent_bad_indicator.cnf'])),
+ "verify load config fail bad indicator");
+ ok(replace_parent_line_file('fips_bad_install_mac.cnf',
+ 'fips_parent_bad_install_mac.cnf')
+ && !run(app(['openssl', 'fipsinstall',
+ '-config', 'fips_parent_bad_install_mac.cnf'])),
+ "verify load config fail bad install mac");
+}
ok(replace_parent_line_file('fips_bad_module_mac.cnf',
'fips_parent_bad_module_mac.cnf')
&& !run(app(['openssl', 'fipsinstall',
'-config', 'fips_parent_bad_module_mac.cnf'])),
"verify load config fail bad module mac");
my $stconf = "fipsmodule_selftest.cnf";
ok(run(app(['openssl', 'fipsinstall', '-out', $stconf,
'-module', $infile, '-self_test_onload'])),
"fipsinstall config saved without self test indicator");
ok(!run(app(['openssl', 'fipsinstall', '-in', $stconf,
'-module', $infile, '-verify'])),
"fipsinstall config verify fails without self test indicator");
ok(run(app(['openssl', 'fipsinstall', '-in', $stconf,
'-module', $infile, '-self_test_onload', '-verify'])),
"fipsinstall config verify passes when self test indicator is not present");
diff --git a/crypto/openssl/test/recipes/04-test_conf.t b/crypto/openssl/test/recipes/04-test_conf.t
index f987e43c8e94..574859e90e1c 100644
--- a/crypto/openssl/test/recipes/04-test_conf.t
+++ b/crypto/openssl/test/recipes/04-test_conf.t
@@ -1,46 +1,47 @@
#! /usr/bin/env perl
-# 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
use strict;
use warnings;
use OpenSSL::Test qw(:DEFAULT data_file);
use OpenSSL::Test::Utils;
use File::Compare qw(compare_text);
setup('test_conf');
my %input_result = (
'dollarid_on.cnf' => 'dollarid_on.txt',
'dollarid_off.cnf' => 'dollarid_off.txt',
+ 'oversized_line.cnf' => 'oversized_line.txt',
);
plan skip_all => 'This is unsupported for cross compiled configurations'
if config('CROSS_COMPILE');
plan tests => 2 * scalar(keys %input_result);
foreach (sort keys %input_result) {
SKIP: {
my $input_path = data_file($_);
my $expected_path = data_file($input_result{$_});
my $result_path = "test_conf-$_-stdout";
skip "Problem dumping $_", 1
unless ok(run(test([ 'confdump', $input_path ],
stdout => $result_path)),
"dumping $_");
is(compare_text($result_path, $expected_path, sub {
my $in1 = $_[0];
my $in2 = $_[1];
$in1 =~ s/\r\n/\n/g;
$in2 =~ s/\r\n/\n/g;
$in1 ne $in2}), 0,
"comparing the dump of $_ with $input_result{$_}");
}
}
diff --git a/crypto/openssl/test/recipes/04-test_conf_data/oversized_line.cnf b/crypto/openssl/test/recipes/04-test_conf_data/oversized_line.cnf
new file mode 100644
index 000000000000..08988a2e0f1d
--- /dev/null
+++ b/crypto/openssl/test/recipes/04-test_conf_data/oversized_line.cnf
@@ -0,0 +1,3 @@
+foo = a_line_longer_than_512_characters_\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"_end
+bar = a_line_longer_than_512_characters__\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"_end
+last = x
diff --git a/crypto/openssl/test/recipes/04-test_conf_data/oversized_line.txt b/crypto/openssl/test/recipes/04-test_conf_data/oversized_line.txt
new file mode 100644
index 000000000000..c15b654300c7
--- /dev/null
+++ b/crypto/openssl/test/recipes/04-test_conf_data/oversized_line.txt
@@ -0,0 +1,4 @@
+[ default ]
+foo = a_line_longer_than_512_characters_""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""_end
+bar = a_line_longer_than_512_characters__""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""_end
+last = x
diff --git a/crypto/openssl/test/recipes/25-test_eai_data.t b/crypto/openssl/test/recipes/25-test_eai_data.t
index e18735d89aad..63548d060293 100644
--- a/crypto/openssl/test/recipes/25-test_eai_data.t
+++ b/crypto/openssl/test/recipes/25-test_eai_data.t
@@ -1,82 +1,82 @@
#! /usr/bin/env perl
-# 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
use strict;
use warnings;
use File::Spec;
use OpenSSL::Test::Utils;
use OpenSSL::Test qw/:DEFAULT srctop_file with/;
setup("test_eai_data");
#./util/wrap.pl apps/openssl verify -nameopt utf8 -no_check_time -CAfile test/recipes/25-test_eai_data/ascii_chain.pem test/recipes/25-test_eai_data/ascii_leaf.pem
#./util/wrap.pl apps/openssl verify -nameopt utf8 -no_check_time -CAfile test/recipes/25-test_eai_data/utf8_chain.pem test/recipes/25-test_eai_data/utf8_leaf.pem
#./util/wrap.pl apps/openssl verify -nameopt utf8 -no_check_time -CAfile test/recipes/25-test_eai_data/utf8_chain.pem test/recipes/25-test_eai_data/ascii_leaf.pem
#./util/wrap.pl apps/openssl verify -nameopt utf8 -no_check_time -CAfile test/recipes/25-test_eai_data/ascii_chain.pem test/recipes/25-test_eai_data/utf8_leaf.pem
plan tests => 16;
require_ok(srctop_file('test','recipes','tconversion.pl'));
my $folder = "test/recipes/25-test_eai_data";
my $ascii_pem = srctop_file($folder, "ascii_leaf.pem");
my $utf8_pem = srctop_file($folder, "utf8_leaf.pem");
my $kdc_pem = srctop_file($folder, "kdc-cert.pem");
my $ascii_chain_pem = srctop_file($folder, "ascii_chain.pem");
my $utf8_chain_pem = srctop_file($folder, "utf8_chain.pem");
my $kdc_chain_pem = srctop_file($folder, "kdc-root-cert.pem");
my $out;
my $outcnt = 0;
sub outname {
$outcnt++;
return "sanout-$outcnt.tmp";
}
$out = outname();
ok(run(app(["openssl", "x509", "-ext", "subjectAltName", "-in", $ascii_pem, "-noout", "-out", $out])));
is(cmp_text($out, srctop_file($folder, "san.ascii")), 0, 'Comparing othername for ASCII domain');
$out = outname();
ok(run(app(["openssl", "x509", "-ext", "subjectAltName", "-in", $utf8_pem, "-noout", "-out", $out])));
is(cmp_text($out, srctop_file($folder, "san.utf8")), 0, 'Comparing othername for IDN domain');
SKIP: {
skip "Unicode tests disabled on MingW", 2 if $^O =~ /^msys$/;
ok(run(app(["openssl", "verify", "-nameopt", "utf8", "-no_check_time", "-verify_email", "学生\@elementary.school.example.com", "-CAfile", $ascii_chain_pem, $ascii_pem])));
ok(run(app(["openssl", "verify", "-nameopt", "utf8", "-no_check_time", "-verify_email", "医生\@大学.example.com", "-CAfile", $utf8_chain_pem, $utf8_pem])));
}
ok(run(app(["openssl", "verify", "-nameopt", "utf8", "-no_check_time", "-CAfile", $ascii_chain_pem, $ascii_pem])));
ok(run(app(["openssl", "verify", "-nameopt", "utf8", "-no_check_time", "-CAfile", $utf8_chain_pem, $utf8_pem])));
ok(run(app(["openssl", "verify", "-nameopt", "utf8", "-no_check_time", "-CAfile", $kdc_chain_pem, $kdc_pem])));
ok(!run(app(["openssl", "verify", "-nameopt", "utf8", "-no_check_time", "-CAfile", $ascii_chain_pem, $utf8_pem])));
ok(!run(app(["openssl", "verify", "-nameopt", "utf8", "-no_check_time", "-CAfile", $utf8_chain_pem, $ascii_pem])));
# Check an otherName does not get misparsed as an DNS name, (should trigger ASAN errors if violated).
ok(run(app(["openssl", "verify", "-nameopt", "utf8", "-no_check_time", "-verify_hostname", 'mx1.example.com', "-CAfile", $kdc_chain_pem, $kdc_pem])));
# Check an otherName does not get misparsed as an email address, (should trigger ASAN errors if violated).
ok(run(app(["openssl", "verify", "-nameopt", "utf8", "-no_check_time", "-verify_email", 'joe@example.com', "-CAfile", $kdc_chain_pem, $kdc_pem])));
# We expect SmtpUTF8Mailbox to be a UTF8 String, not an IA5String.
ok(!run(app(["openssl", "verify", "-nameopt", "utf8", "-no_check_time", "-verify_email", 'moe@example.com', "-CAfile", $kdc_chain_pem, $kdc_pem])));
#Check that we get the expected failure return code
with({ exit_checker => sub { return shift == 2; } },
sub {
ok(run(app(["openssl", "verify", "-CAfile",
srctop_file("test", "certs", "bad-othername-namec.pem"),
"-partial_chain", "-no_check_time", "-verify_email",
'foo@example.com',
srctop_file("test", "certs", "bad-othername-namec.pem")])));
});
diff --git a/crypto/openssl/test/recipes/30-test_evp_byname.t b/crypto/openssl/test/recipes/30-test_evp_byname.t
new file mode 100644
index 000000000000..d06e874fe927
--- /dev/null
+++ b/crypto/openssl/test/recipes/30-test_evp_byname.t
@@ -0,0 +1,16 @@
+#! /usr/bin/env perl
+# Copyright 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 OpenSSL::Test;
+use OpenSSL::Test::Simple;
+use OpenSSL::Test::Utils;
+
+setup("test_evp_byname");
+
+simple_test("test_evp_byname", "evp_byname_test");
diff --git a/crypto/openssl/test/recipes/30-test_evp_data/evppkey_dsa.txt b/crypto/openssl/test/recipes/30-test_evp_data/evppkey_dsa.txt
index debd62bca84c..39f9a01343bf 100644
--- a/crypto/openssl/test/recipes/30-test_evp_data/evppkey_dsa.txt
+++ b/crypto/openssl/test/recipes/30-test_evp_data/evppkey_dsa.txt
@@ -1,355 +1,359 @@
#
-# 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
# Tests start with one of these keywords
# Cipher Decrypt Derive Digest Encoding KDF MAC PBE
# PrivPubKeyPair Sign Verify VerifyRecover
# and continue until a blank line. Lines starting with a pound sign are ignored.
# Private keys used for PKEY operations.
# DSA key
PrivateKey=DSA-1024
-----BEGIN PRIVATE KEY-----
MIIBSwIBADCCASwGByqGSM44BAEwggEfAoGBAO0SwRpkAeM21qSM5ch4CLEHpFk4
19R5ve1UUr421y3HEUURsrVpxYKvyx8aOBQC/akz95cYxNN3y1JnJJMxPklhdJrJ
f/WDYPxjMk8BqNJmeZtLuCVLKGwQomuo7ZkG955WRyLHYEdQ6uC7K2QTPKpW6psF
YFaDYjAjSEKk2MFxAhUAykDkKLZdhPWzwM8/qYaE31VmWz0CgYEApNVF8oFK41ez
Qci9XbSZJHyPB+3jML1YQkHxiiInaIz6GEFtjUbIUEYA/ovY+6ECNI1aIDHTd7CH
woS0mp33oQYs43nt29B6UwbtMmbzCOQ9vGGwWVho+JtHyyPWrDuLmkvLtoQPaxYt
6PVa3gncr2v3njcVuH+EQ6DuFR93zksEFgIUbyv6pqH+UQurernJn/7sUm2U2i0=
-----END PRIVATE KEY-----
PublicKey=DSA-1024-PUBLIC
-----BEGIN PUBLIC KEY-----
MIIBtzCCASwGByqGSM44BAEwggEfAoGBAO0SwRpkAeM21qSM5ch4CLEHpFk419R5
ve1UUr421y3HEUURsrVpxYKvyx8aOBQC/akz95cYxNN3y1JnJJMxPklhdJrJf/WD
YPxjMk8BqNJmeZtLuCVLKGwQomuo7ZkG955WRyLHYEdQ6uC7K2QTPKpW6psFYFaD
YjAjSEKk2MFxAhUAykDkKLZdhPWzwM8/qYaE31VmWz0CgYEApNVF8oFK41ezQci9
XbSZJHyPB+3jML1YQkHxiiInaIz6GEFtjUbIUEYA/ovY+6ECNI1aIDHTd7CHwoS0
mp33oQYs43nt29B6UwbtMmbzCOQ9vGGwWVho+JtHyyPWrDuLmkvLtoQPaxYt6PVa
3gncr2v3njcVuH+EQ6DuFR93zksDgYQAAoGAVXFwJ5wTuF0rQ6AWfTitm3/zUeRW
SeKFo+Rg0GrBI+Wg2Tj+Yn6V8Xs+Xyjim1wsd2P6/BlJzCEr4nHjP9JcBICqM3vI
9zCaT/vYsLD7/T7rF9AF/jV+LnkGJCzLbDYF04IkhtLNHOQob+Uc8PWB78e/1Lc4
SzJw2oHciIOt+UU=
-----END PUBLIC KEY-----
PrivPubKeyPair = DSA-1024:DSA-1024-PUBLIC
Title = DSA tests
Verify = DSA-1024
Ctrl = digest:SHA1
Input = "0123456789ABCDEF1234"
Output = 302d021500942b8c5850e05b59e24495116b1e8559e51b610e0214237aedf272d91f2397f63c9fc8790e1a6cde5d87
Verify = DSA-1024-PUBLIC
Ctrl = digest:SHA1
Input = "0123456789ABCDEF1234"
Output = 302d021500942b8c5850e05b59e24495116b1e8559e51b610e0214237aedf272d91f2397f63c9fc8790e1a6cde5d87
# Modified signature
Verify = DSA-1024-PUBLIC
Ctrl = digest:SHA1
Input = "0123456789ABCDEF1234"
Output = 302d021500942b8c5850e05b59e24495116b1e8559e51b610e0214237aedf272d91f2397f63c9fc8790e1a6cde5d88
Result = VERIFY_ERROR
# Digest too short
Verify = DSA-1024-PUBLIC
Ctrl = digest:SHA1
Input = "0123456789ABCDEF123"
Output = 302d021500942b8c5850e05b59e24495116b1e8559e51b610e0214237aedf272d91f2397f63c9fc8790e1a6cde5d87
Result = VERIFY_ERROR
# Digest too long
Verify = DSA-1024-PUBLIC
Ctrl = digest:SHA1
Input = "0123456789ABCDEF12345"
Output = 302d021500942b8c5850e05b59e24495116b1e8559e51b610e0214237aedf272d91f2397f63c9fc8790e1a6cde5d87
Result = VERIFY_ERROR
# Garbage after signature
Verify = DSA-1024-PUBLIC
Input = "0123456789ABCDEF1234"
Output = 302d021500942b8c5850e05b59e24495116b1e8559e51b610e0214237aedf272d91f2397f63c9fc8790e1a6cde5d8700
Result = VERIFY_ERROR
# Invalid tag
Verify = DSA-1024-PUBLIC
Ctrl = digest:SHA1
Input = "0123456789ABCDEF1234"
Output = 312d021500942b8c5850e05b59e24495116b1e8559e51b610e0214237aedf272d91f2397f63c9fc8790e1a6cde5d87
Result = VERIFY_ERROR
# BER signature
Verify = DSA-1024-PUBLIC
Ctrl = digest:SHA1
Input = "0123456789ABCDEF1234"
Output = 3080021500942b8c5850e05b59e24495116b1e8559e51b610e0214237aedf272d91f2397f63c9fc8790e1a6cde5d870000
Result = VERIFY_ERROR
Title = Test keypair mismatches
PrivateKey = DSA-1024-BIS
-----BEGIN PRIVATE KEY-----
MIIBSwIBADCCASwGByqGSM44BAEwggEfAoGBAO0SwRpkAeM21qSM5ch4CLEHpFk419R5ve1UUr42
1y3HEUURsrVpxYKvyx8aOBQC/akz95cYxNN3y1JnJJMxPklhdJrJf/WDYPxjMk8BqNJmeZtLuCVL
KGwQomuo7ZkG955WRyLHYEdQ6uC7K2QTPKpW6psFYFaDYjAjSEKk2MFxAhUAykDkKLZdhPWzwM8/
qYaE31VmWz0CgYEApNVF8oFK41ezQci9XbSZJHyPB+3jML1YQkHxiiInaIz6GEFtjUbIUEYA/ovY
+6ECNI1aIDHTd7CHwoS0mp33oQYs43nt29B6UwbtMmbzCOQ9vGGwWVho+JtHyyPWrDuLmkvLtoQP
axYt6PVa3gncr2v3njcVuH+EQ6DuFR93zksEFgIUFQFshP0hj7i6ClXkSPYoFW6KrIY=
-----END PRIVATE KEY-----
PublicKey = DSA-1024-BIS-PUBLIC
-----BEGIN PUBLIC KEY-----
MIIBtzCCASwGByqGSM44BAEwggEfAoGBAO0SwRpkAeM21qSM5ch4CLEHpFk419R5
ve1UUr421y3HEUURsrVpxYKvyx8aOBQC/akz95cYxNN3y1JnJJMxPklhdJrJf/WD
YPxjMk8BqNJmeZtLuCVLKGwQomuo7ZkG955WRyLHYEdQ6uC7K2QTPKpW6psFYFaD
YjAjSEKk2MFxAhUAykDkKLZdhPWzwM8/qYaE31VmWz0CgYEApNVF8oFK41ezQci9
XbSZJHyPB+3jML1YQkHxiiInaIz6GEFtjUbIUEYA/ovY+6ECNI1aIDHTd7CHwoS0
mp33oQYs43nt29B6UwbtMmbzCOQ9vGGwWVho+JtHyyPWrDuLmkvLtoQPaxYt6PVa
3gncr2v3njcVuH+EQ6DuFR93zksDgYQAAoGAdZCPYZ9WvtKW7dFvbEjl0HHBxLNX
8kV1/FAxsDrQd+c8mWdruNzcmwsZJklJuTK9czKnXgLmkRHR20I4oNrJ/bptV8lV
iDvJBJlmZ1aGh6yLIHzYBbgbgia3lBrFlO5qUxNmbNeiC+HIqUvlVBmQOLN6+Xjn
Q4A0wDK8dmF2dFI=
-----END PUBLIC KEY-----
PrivPubKeyPair = DSA-1024-BIS:DSA-1024-BIS-PUBLIC
PrivPubKeyPair = DSA-1024:DSA-1024-BIS-PUBLIC
Result = KEYPAIR_MISMATCH
PrivPubKeyPair = DSA-1024-BIS:DSA-1024-PUBLIC
Result = KEYPAIR_MISMATCH
PrivateKey = DSA-1024-FIPS186-2
-----BEGIN PRIVATE KEY-----
MIIBWgIBADCCATMGByqGSM44BAEwggEmAoGBALRSnNcjMPIl4tekT5D3AgqsK042
Ar1dGKeJCmWrSngAELtSH0yZCwsbl7wLEgG2lfusbn5sdtbpFioKInohZruRhzwC
59GRXjAFD0QPhVE/qy6Oto+8WIHAa/RiEIkxRfTiAe9Ach56k9lZYONDUHDqH38u
UIfjoUN+jlzoJcWbAh0A6TfgjmB+CxvxG/2pz8OAXXfNP8/JLfYvolE/fwKBgH7l
jLeoOofKc+rwO2Fha8nuFddXRSePZKzC7mRQsPXwfvX5V6msU2xizjdPIsqVu7qA
Bcc1YMd7/5C3vaKuS21DxBOs7nAHbO9ZZtGlpUAnJwM/P09nMb3yG6tR9LF3AQmu
Kr2KShQB0FlSgvcCDTX7g8eJ/UuIWo6wX4hSdHDhBB4CHAdVVg1m5ikOICUBo37Y
/TqkTaCFsMDwcDc20Jg=
-----END PRIVATE KEY-----
PrivateKey = DSA-2048-160
-----BEGIN PRIVATE KEY-----
MIICTAIBADCCAi0GByqGSM44BAEwggIgAoIBAQCOypCJyAO7uNZSPSNGalSkyjQC
xdFVIGfMJKjEXzJnH4g3ts0UqUyO8126REDJEXDeMi22841xsSvzz0ZJeT5YvMLW
t1BtSTiYg2QOar1qEGJunHgjsWKJbVzIqWNw60ZP7pNKmlR7PKa3WDaPhdeVP8zJ
PEMeUHOSprO5Jk/Hjr8jxV0znIIixb9L9PgJAwxiM7rkRHS2Oz1FCYDmNmuFhQDh
Cb3wY9t1AcAHZ05uZ4PtNjdRPwFLPeVdckPj0ntApvOrH18xPWBmwcVeHAH1SV2k
7LPK7wILHVzcKm74ubX/s1wKysyyXyKM+oCgG9jvfh09VQJcHTHaVS643ohZAhUA
uQMLDZqMQbh9TYlm9xYCEBaeVs0CggEAcum3PgEQIRfukytMQ7gKMyfxHqhMmJ6t
RolRhgMrSfl99dmMoqJV+sdSjYvZSkwl71N1Y4Al8GcJB1SzTSb8qGRzM+43pa4k
SyQZ62WA8w5gaIQJ85JUrWiT8C6SgwAbruS5BVHRbQD6FxZwro9+s8uPnLesMTQX
p4maNSQaqYX7tqGl6Z7Wo0PsEwuDRvBlI6sl97gl4q3FQPByCq/64UW/eF6Illo1
dpfbiWCszsp8oczXCEuP+2Y67WUIj3LjFA7WM/R8K4SfdMQ/VXY/cyRhlUqQl8Qe
ndBVKe0IeSdqvMcLNoUip7DGcOXW2ogZl+wgeP4xL3pdo8uS025kjwQWAhRfutAE
r/MlbdGMvcA7l0XmzzY85w==
-----END PRIVATE KEY-----
PrivateKey = DSA-2048-224
-----BEGIN PRIVATE KEY-----
MIICXAIBADCCAjUGByqGSM44BAEwggIoAoIBAQDVjuiHR3XA9yAjToNQOmdg2rN9
0A4mIEV3XGy1nqaKZXdavdXcsAGLmttZ/gfiHi0JNh3rxj4dbvcaN+K0IWXq6hAY
6ZOvDZ0FH5DRH63Ecd8fWY/BMDr178sOINkPG8hLRmYcrAp/4woMBPxkEtQBfl4R
POus+OYS4sJpl8wEgfy0HhLXkkN4YQhBf57NvQ7+LcwaErDcNLRguI3TRzflhNEh
ieBfYtIIgISIi0yMsxOINopuHeAmcANLjyUqkQ44xcJ0kM+OoAKFq/XukkTj++iP
9Okh+bmNEo23RtM4qqScZyUIX4bPyynbkMdu01ZG+q8PEhyoxGpHkMT6kYHBAh0A
/rbeX9L8STLoLIsLUMbdPVLWvnLyLooSygawvwKCAQAhscCNIY/bPZ6DRULS8i4G
0f+9chMR+C5tNykaTzCUxRjObOWKu0z1JyViiafcAoV8j1e64xRxA4a8g9RrKilK
KztCJfwIJCeHIjHi/dvIR0z1SDeNNVpFacAT+DF5G+sMqS8Mael0MnEcR2sNkw+1
MVIO5tinKWAFM087hsSmKs/uIvdVexH2ptKKehxTFjs8ySfAMiMfqhaC2JgPCFL1
jUpAIvs4oCx2yZKvq+TzJOq8LRHG3qSHa0BcNVPKfVkmVJRg4ETzza1/e14Re1BR
si7RL7EtHuFiFjYiWTGueT+e0jdBS8CoafD1V/I7NPqVmGc5NeaRv4n+ESpDSX+z
BB4CHBN2hfQxLXg+t/MNcza5M0WoAWna5JzQBAtDzIM=
-----END PRIVATE KEY-----
PrivateKey = DSA-2048-256
-----BEGIN PRIVATE KEY-----
MIICZQIBADCCAjoGByqGSM44BAEwggItAoIBAQDAuDj/d/t7n4013h18atbOYg4Q
oWZPLmA7MvFABqrlv9lfa0dRGhOHyXClHh2bsNMwk3txKjTaTwjM9v80xe47y2lv
34DPEKaWf+6HGcsu313kjIoAITO61HK0TJXjm0BV2uzZQFmvVHwEZmt7uGFcTc4t
Vl71Z+MjhlMqpOmXIL/OBJkMOE1CXF/b6oKyXJvyZRpE4oxS+8B1l7d/N0B1XhQl
EMToFwmvsKfeeK24wDfxasfbNbQ7Zih/5HylWtNXbvldnOf6cfPPPM6FO7HVI9R5
llQKxFWujVrX0IOXu89xT8t+/ICKJtLKD5HzmeH1Y6LO+Qnsu5tW8IhnDHKLAiEA
prlohsCeURHqsKcqtMElD7vg+Ati8OKgdo79/ktz9bMCggEBALC9Awm0lClgvefU
inwV6gQppvAQttX7fUGjnrmuAXjw/pm4MBuzkR1P7vm2IY51+SopK+ZvgXXXnWGQ
m8y3DCuoSnfE6Y+NpAfL9iJxy5W+ByvW75GW7/Lj5hR/igKKuYhfGYT/2eIGtdQ2
C2tcWTcV7Gfk60WSw9eLUtKCUjBHaoFHFMo3MWH64Fc0xVEQ1DLgEC5Y3TLmiLBx
VOGpp5ZFeAc52n/W4afbBcQ5ifGFPwgcS7+WdnUUs7awuCCldh74kz58kdTJAztZ
ZjjK728BYEE4P6itUNtr3jgNzhqwTBFvOwWCQA//a7vpyqtHMzDmpcVuDx6f4iP3
aghyxFAEIgIgK1Ct6iRtcq01mdt4EGRrkiAHBr5zTcAgbv5ZaU99pmQ=
-----END PRIVATE KEY-----
PrivateKey = DSA-3072-256
-----BEGIN PRIVATE KEY-----
MIIDZgIBADCCAzoGByqGSM44BAEwggMtAoIBgQCvf6pPUvu2J7j4aaGcpEkfjX7e
DvM5qlpuf2GDwbWFQpkxeRFtmd5EFbgNvRMsLyfTA3KWd4k2nFug2Uf5kFJ0rOcI
nToVcrPjg8onD43Rcknvmu5grsjDvCFMmWFu361LbWxZCgGCwSUv4P647kS5ccaD
k0o4f+a8YWLahop/HowqoN8/TvC/izdN0WvRYKeegJcBzaaBKWsBS8ucu0jEh5S3
PCAQRFoKNRPjUzjIhycIlpdmI5BG72SkvSSMef9wvGl72FN2t3v5dbWjl7QgghU5
0BB/RlueApJgrFhadE/0ZJKSukPMbL9a0L1xZl01iJYraa76rn5weVkU8sW7BN7C
oHTovusrls/AtEBKXKC47rNnfSc9VwfwdNBuvs33Ga872575bjOunQiXQRxuuqjq
u3MyixPygIy+MmjhjPhnpYnb+1sytpoN1UOTi9QMHWLp2ExYvurda6n4nCjbJBcB
DvWPyapslDP+yT/3aEH0ctqu/QMk3rPxBAzVytUCIQD/CwBYEWtyd6IoiqcWVMT5
4k1cKfg5ZbNu7mG3iS+iSwKCAYEAm1QNpGrOS2orCVUP80KQFTQwg37tlynJjXev
ORdBgDXpIjFcdEgsEx9cHzlOywBDQWxHLXRukvgQbx7dCq2RgEM6Fo6ngbhj87zw
dLFdXxj/TU0fJPhj3VIF2qu5vG1SZRu4zKNZ6uoJP7R4/7o/shHOoTyCOigRew4X
A2P9eIxpEv/KXRznxjG1IcAQJcPYBDwjE555WNHL0jzzKEyxyxmkm9ThEpleW7HU
ij78B5O45V/AHVF7oB/L+Aqmbc2dZy8EtShsMKqSMdFWjV0BnuzsPt9KmKT+rbj6
MpqgdaKPEsYVD4Nk6EWEyYbWmELtS9jKH5E4Z/pqFGeamsiD5Sn0ap7SGa81BtA+
s7FMG851b2jtRw0RB4+boGx0Lt43WbytfmW445i4h/NMB0nE/pzjIIjD3URdNoaS
2G2eZcW/aC9bKkOoAr2USSlgylPCkz2a/CAx7i925HOZ2dw9HJ940vkAoxP+nMQv
kMzKKeM5QVgAeRwjDqRk9uCWD7VyBCMCIQDxycQrIIL4PxAoPIM7//v8mL7A3YSW
o3mO5AXuBuEe2g==
-----END PRIVATE KEY-----
PrivateKey = DSA-3072-224
-----BEGIN PRIVATE KEY-----
MIIDXAIBADCCAzUGByqGSM44BAEwggMoAoIBgQDEY9anVQ8qwdz77IQx1bSmu5MI
mP7pf9IUXbH5fZFrCjlDu34w2WvsdDRrM2/isvKb/wj+sgg5dx5bWRn/+xolwu8l
upmD6KMJ07t9SSla155tkvS/8hU5AD8elH9vV+HlTPKRHNF1X3jFJRVay64O+vFX
WRe7t3yBFv/VqkhnYwm5aymMK6/TXR1znJzrMNgU1Ao3unhjaFnRsldHVHjXrA4y
rJRMsa4r5BCPQNK8iXKabAw19oiRbRvqs3YfzoR1HqZ3LGO1/p9ECoc/QW0uI1Za
LYQli1aNtNmtYhwKvy7O8IzjrbjkDRgl/TtDmtfpDnM6FkQebgU0OxQXTOwZgtEV
a7VY+EwG1q+Qab7uvuO2YJ7Mk2JKmu4u0Gz7tq5N+hEN4P5UMC/MUw6ftLCGN6l6
ycEJHMgGzDsAKEJW6NcXneY3vXpdaRGnuxyUKI86wQd3Qg1Mm3H1gqtkd48owIJm
RtE/u91T4OJOcwVm2FxDgmMsb0LwqAELL+I9RH8CHQDNAddLZ4ovSccoD+s06I+X
d+GzJ8cNcbn4H1TVAoIBgAmwgz0CjHaacOiXcQ4GLw0kN2IpXKAXYma1vDlDcesT
lY8dcGsX2UjuLnfegMRkb5FMGZ8TDjgDG4vLo2p1ybt7S7s0hn56bju5HZLSOmAp
nu5M15iZxDzgVvhRkB0EG/aw5i6iq22JUA5SUAGYLemcZIuukIDu6vhTeK2125qa
q+Uc0/kyPMOf0zABo+I2wWNmZgdq26F147Yrf06VY3ekxcER1vAUfVBHxeYPfdZR
N8ztdzYTPtCSxyIWATUxYvWxsaxqNckjXLZp5t9L72Zc8k5swsBDIAabhJTiQrRS
hkhD0UOCf2pUNFcHIxLqYskOycEjtmKrAYbrHZDRw5CzP5ABaDYwqgxi2ZSt/tv4
iYUhX4tRicGeAWLM7D3LxG+P/6q7dJ/Gjjx8gmbcBJKcjVDGp/b8xn1WY83gbNEJ
HOAqdXyxgnQL+E581jk13LixzoOboyrhryFqVoMarZOXEAQKToG24tj5DO7LmviW
8hzXTwJmVlKblGJxVmqDuQQeAhx6PjOtN4DxhxZdoX8+lU7C6CWYvyQbJOER0XVn
-----END PRIVATE KEY-----
PrivateKey = DSA-4096-256
-----BEGIN PRIVATE KEY-----
MIIEZQIBADCCBDoGByqGSM44BAEwggQtAoICAQD9m23nz0MOXi3GFvuv+Qpva9Ms
oZ/oPS1sYy/JtxvBtEjWv0b0wxtLAiASkBBhaqC1Qy+9O7dC7s5wze/0v/mAxFtF
X18KhMWSRtgiGOWzg6Nyog+Dus224Qa6wfYC1+lcGG/TmDLSmukBrVzd/71pSOkT
6O3v5hx1JOdJzzNPt1kjq31B1/2h9OXnARg1JDCLHP6fxRkWj2ThwU+FwlKTpo+d
MsC0Xl93t1lBOiS5VsHLSZIeqsInEj3bWBTT6C5q0huZKBQ9iT3SwAq/gG8KL9DV
MGSWQwAQdUpQWcv6JDwLb6h6QhHmzclDCF8JAGRzLA9kDWbmYPXQuVxj1//LuJba
fMe6tLWBuAMeQNFuB/pro2dszbo8GDOYEaOfogG86x9hfgBoPufU0oHlfhj3nhO8
cLYwvhRkN/ZZyTM5/1aHQNvp6S+sIGD1WFKPxMZuTH2k01I0s8ESGrlWpnPgwNQx
iwx+dlXLFZNdDOiS+Mb9JPSuJ/xDagHmQzG0gxYiLfWQKjAMol4niB6mGIm0gEYq
Rw9OEHE/ghzBMbr6M+BLDm7PDac5y1a3L6l9e0Yq9h+4bwqTqZIpNIsRS4A0lmXd
IXs54dQmTwF75cMWjOAOYwxua97I4Ci3nkJWiozBugoGrKTSkeNX21uMfVJKidjd
j79Vlz79qnMSB42sqwIhAPwv8XkIkZvnDKTTowvUy8L6V/SxF7KZFtvX5Mx4KJt7
AoICAQDdWpUSEpBLdFiu6MzqdWnRv9pt8BEu0sC9Z+xE3VrpDKqqnK2Rhtye0yIk
4fofLl9VF2J4P6hzDcCu8QEDj0K3dWQR+BU1WMBHMCTHrTM51XAqbjR1H3ZYWVxC
WgWrVGQkcD55TrM2RYBKH6Wa7K9HeFVJcdHrh0AZb4lXIBZHf0+71cOfZH8w1ufl
yKzYNMGY9+eoU3Pm0D5gBO/69uWDrK21SJMW3Fpqm4rgeHtNhR4oI6cagyo2+XfD
e+ivCk5XKCXgImKpKDMuKhJy0K4vZFjVHeIWl2mf1zyhmCxuAcGEf9dRVKtnQQGS
8uJGddKuda67J9vecN78H2nhsZcU9DRPzgjW+tUTwSX3ycW/hEA65kN5PUSpj8Ax
7gZN5Jn8bGNlCgLItHQMscGDo0L47+bN8G8JguZr+hpNFKmYMpbQ15yHaRU7DR36
Zx91SEQ1o8Kn8mNT37RBYk/vZij9P8QRnn3pen9Ha5CBNs6/8RERaUJ84kSCV0iL
4/ed3syr8bek8a2rN6qhLZSKfYwLdiu0VaBsmJrOoE7xNgJ+f0g7aTptO1NOiwtY
ftiDvljQGG1QhAv9i1uSmz6EPYn3VCJPadxX8mlPmpGCewk8ycOV1IFgCK86cdTl
bDfJavyQoCWW6EF260m2+rWtl6ILGhhWIbDN5KfXBhrOPvxvHQQiAiBZM1KxUjGw
h2C/91Z0b0Xg4QYNOtVUbfqQTJQAqEpaRg==
-----END PRIVATE KEY-----
Title = FIPS Tests (using different key sizes and digests)
# Test sign with a 2048 bit key with N == 160 is not allowed in fips mode
Availablein = fips
+FIPSversion = <3.4.0
DigestSign = SHA256
Key = DSA-2048-160
Input = "Hello"
Output = 00
Result = DIGESTSIGNINIT_ERROR
# Test sign with a 2048 bit key with N == 224 is allowed in fips mode
DigestSign = SHA256
Key = DSA-2048-224
Input = "Hello"
Output = 00
Result = SIGNATURE_MISMATCH
# Test sign with a 2048 bit key with N == 256 is allowed in fips mode
DigestSign = SHA256
Key = DSA-2048-256
Input = "Hello"
Result = SIGNATURE_MISMATCH
# Test sign with a 3072 bit key with N == 256 is allowed in fips mode
DigestSign = SHA256
Key = DSA-3072-256
Input = "Hello"
Result = SIGNATURE_MISMATCH
# Test sign with a 2048 bit SHA3 is allowed in fips mode
DigestSign = SHA3-224
Key = DSA-2048-256
Input = "Hello"
Result = SIGNATURE_MISMATCH
# Test verify with a 1024 bit key is allowed in fips mode
DigestVerify = SHA256
Key = DSA-1024
Input = "Hello "
Output = 302c02142e32c8a5b0bd19b2ba33fd9c78aad3729dcb1b9e02142c006f7726a9d6833d414865b95167ea5f4f7713
# Test verify with SHA1 is allowed in fips mode
DigestVerify = SHA1
Key = DSA-1024
Input = "Hello "
Output = 302c0214602d21ed37e46051bb3d06cc002adddeb4cdb3bd02144f39f75587b286588862d06366b2f29bddaf8cf6
# Test verify with a 2048/160 bit key is allowed in fips mode
FIPSversion = >3.1.1
DigestVerify = SHA256
Key = DSA-2048-160
Input = "Hello"
Output = 302e021500a51ca7f70ae206f221dc9b805bb04bfc07d6e448021500b16e45f9dac8aff04e115f96c00f4237d0fced41
Title = Fips Negative Tests (using different key sizes and digests)
# Test sign with a 1024 bit key is not allowed in fips mode
Availablein = fips
+FIPSversion = <3.4.0
DigestSign = SHA256
Securitycheck = 1
Key = DSA-1024-FIPS186-2
Input = "Hello"
Result = DIGESTSIGNINIT_ERROR
# Test sign with SHA1 is not allowed in fips mode
Availablein = fips
DigestSign = SHA1
Securitycheck = 1
Key = DSA-2048
Input = "Hello"
Result = DIGESTSIGNINIT_ERROR
# Test sign with a 3072 bit key with N == 224 is not allowed in fips mode
Availablein = fips
+FIPSversion = <3.4.0
DigestSign = SHA256
Securitycheck = 1
Key = DSA-3072-224
Input = "Hello"
Result = DIGESTSIGNINIT_ERROR
# Test sign with a 4096 bit key is not allowed in fips mode
Availablein = fips
+FIPSversion = <3.4.0
DigestSign = SHA256
Securitycheck = 1
Key = DSA-4096-256
Input = "Hello"
Result = DIGESTSIGNINIT_ERROR
diff --git a/crypto/openssl/test/recipes/30-test_evp_data/evppkey_ecdsa.txt b/crypto/openssl/test/recipes/30-test_evp_data/evppkey_ecdsa.txt
index ec3c032aba8d..1f9ce93cd166 100644
--- a/crypto/openssl/test/recipes/30-test_evp_data/evppkey_ecdsa.txt
+++ b/crypto/openssl/test/recipes/30-test_evp_data/evppkey_ecdsa.txt
@@ -1,230 +1,231 @@
#
-# 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
# Tests start with one of these keywords
# Cipher Decrypt Derive Digest Encoding KDF MAC PBE
# PrivPubKeyPair Sign Verify VerifyRecover
# and continue until a blank line. Lines starting with a pound sign are ignored.
# The keyword Availablein must appear before the test name if needed.
# Public key algorithm tests
# Private keys used for PKEY operations.
# EC P-256 key
PrivateKey=P-256
-----BEGIN PRIVATE KEY-----
MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgiocvtiiTxNH/xbnw
+RdYBp+DUuCPoFpJ+NuSbLVyhyWhRANCAAQsFQ9CnOcPIWwlLPXgYs4fY5zV0WXH
+JQkBywnGX14szuSDpXNtmTpkNzwz+oNlOKo5q+dDlgFbmUxBJJbn+bJ
-----END PRIVATE KEY-----
# EC public key for above
PublicKey=P-256-PUBLIC
-----BEGIN PUBLIC KEY-----
MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAELBUPQpznDyFsJSz14GLOH2Oc1dFl
x/iUJAcsJxl9eLM7kg6VzbZk6ZDc8M/qDZTiqOavnQ5YBW5lMQSSW5/myQ==
-----END PUBLIC KEY-----
PrivPubKeyPair = P-256:P-256-PUBLIC
Title = ECDSA tests
Verify = P-256
Ctrl = digest:SHA1
Input = "0123456789ABCDEF1234"
Output = 3045022100b1d1cb1a577035bccdd5a86c6148c2cc7c633cd42b7234139b593076d041e15202201898cdd52b41ca502098184b409cf83a21bc945006746e3b7cea52234e043ec8
# Digest too long
Verify = P-256
Ctrl = digest:SHA1
Input = "0123456789ABCDEF12345"
Output = 3045022100b1d1cb1a577035bccdd5a86c6148c2cc7c633cd42b7234139b593076d041e15202201898cdd52b41ca502098184b409cf83a21bc945006746e3b7cea52234e043ec8
Result = VERIFY_ERROR
# Digest too short
Verify = P-256
Ctrl = digest:SHA1
Input = "0123456789ABCDEF123"
Output = 3045022100b1d1cb1a577035bccdd5a86c6148c2cc7c633cd42b7234139b593076d041e15202201898cdd52b41ca502098184b409cf83a21bc945006746e3b7cea52234e043ec8
Result = VERIFY_ERROR
# Digest invalid
Verify = P-256
Ctrl = digest:SHA1
Input = "0123456789ABCDEF1235"
Output = 3045022100b1d1cb1a577035bccdd5a86c6148c2cc7c633cd42b7234139b593076d041e15202201898cdd52b41ca502098184b409cf83a21bc945006746e3b7cea52234e043ec8
Result = VERIFY_ERROR
# Invalid signature
Verify = P-256
Ctrl = digest:SHA1
Input = "0123456789ABCDEF1234"
Output = 3045022100b1d1cb1a577035bccdd5a86c6148c2cc7c633cd42b7234139b593076d041e15202201898cdd52b41ca502098184b409cf83a21bc945006746e3b7cea52234e043ec7
Result = VERIFY_ERROR
# Garbage after signature
Availablein = default
Verify = P-256
Ctrl = digest:SHA1
Input = "0123456789ABCDEF1234"
Output = 3045022100b1d1cb1a577035bccdd5a86c6148c2cc7c633cd42b7234139b593076d041e15202201898cdd52b41ca502098184b409cf83a21bc945006746e3b7cea52234e043ec800
Result = VERIFY_ERROR
# BER signature
Verify = P-256
Ctrl = digest:SHA1
Input = "0123456789ABCDEF1234"
Output = 3080022100b1d1cb1a577035bccdd5a86c6148c2cc7c633cd42b7234139b593076d041e15202201898cdd52b41ca502098184b409cf83a21bc945006746e3b7cea52234e043ec80000
Result = VERIFY_ERROR
Verify = P-256-PUBLIC
Ctrl = digest:SHA1
Input = "0123456789ABCDEF1234"
Output = 3045022100b1d1cb1a577035bccdd5a86c6148c2cc7c633cd42b7234139b593076d041e15202201898cdd52b41ca502098184b409cf83a21bc945006746e3b7cea52234e043ec8
Title = DigestSign and DigestVerify
DigestVerify = SHA256
Key = P-256-PUBLIC
Input = "Hello World"
Output = 3046022100e7515177ec3817b77a4a94066ab3070817b7aa9d44a8a09f040da250116e8972022100ba59b0f631258e59a9026be5d84f60685f4cf22b9165a0c2736d5c21c8ec1862
PublicKey=P-384-PUBLIC
-----BEGIN PUBLIC KEY-----
MHYwEAYHKoZIzj0CAQYFK4EEACIDYgAES/TlL5WEJ+u1kV+4yVlVUbTTo/2rZ7rd
nWwwk/QlukNjDfcfQvDrfOqpTZ9kSKhd0wMxWIJJ/S/cCzCex+2EgbwW8ngAwT19
twD8guGxyFRaoMDTtW47/nifwYqRaIfC
-----END PUBLIC KEY-----
DigestVerify = SHA384
Key = P-384-PUBLIC
Input = "123400"
Output = 304d0218389cb27e0bc8d21fa7e5f24cb74f58851313e696333ad68b023100ffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52970
# Oneshot tests
OneShotDigestVerify = SHA256
Key = P-256-PUBLIC
Input = "Hello World"
Output = 3046022100e7515177ec3817b77a4a94066ab3070817b7aa9d44a8a09f040da250116e8972022100ba59b0f631258e59a9026be5d84f60685f4cf22b9165a0c2736d5c21c8ec1862
# Test that mdsize != tbssize fails
Sign = P-256
Ctrl = digest:SHA256
Input = "0123456789ABCDEF1234"
Result = KEYOP_ERROR
PrivateKey = P-256_NAMED_CURVE_EXPLICIT
-----BEGIN PRIVATE KEY-----
MIIBeQIBADCCAQMGByqGSM49AgEwgfcCAQEwLAYHKoZIzj0BAQIhAP////8AAAAB
AAAAAAAAAAAAAAAA////////////////MFsEIP////8AAAABAAAAAAAAAAAAAAAA
///////////////8BCBaxjXYqjqT57PrvVV2mIa8ZR0GsMxTsPY7zjw+J9JgSwMV
AMSdNgiG5wSTamZ44ROdJreBn36QBEEEaxfR8uEsQkf4vOblY6RA8ncDfYEt6zOg
9KE5RdiYwpZP40Li/hp/m47n60p8D54WK84zV2sxXs7LtkBoN79R9QIhAP////8A
AAAA//////////+85vqtpxeehPO5ysL8YyVRAgEBBG0wawIBAQQgiUTxtr5vLVjj
0BOXUa/4r82DJ30QoupYS/wlilW4gWehRANCAATM0n3q2UaDyaQ7OxzJM3B6prhW
3ev1gTwRBduzqqlwd54AUSgI+pjttW8zrWNitO8H1sf59MPWOESKxNtZ1+Nl
-----END PRIVATE KEY-----
PrivateKey = EC_EXPLICIT
-----BEGIN PRIVATE KEY-----
MIIBeQIBADCCAQMGByqGSM49AgEwgfcCAQEwLAYHKoZIzj0BAQIhAP////8AAAAB
AAAAAAAAAAAAAAAA////////////////MFsEIP////8AAAABAAAAAAAAAAAAAAAA
///////////////8BCBaxjXYqjqT57PrvVV2mIa8ZR0GsMxTsPY7zjw+J9JgSwMV
AMSdNgiG5wSTamZ44ROdJreBn36QBEEE5JcIvn36opqjEm/k59Al40rBAxWM2TPG
l0L13Je51zHpfXQ9Z2o7IQicMXP4wSfJ0qCgg2bgydqoxlYrlLGuVQIhAP////8A
AAAA//////////+85vqtpxeehPO5ysL8YyVRAgEBBG0wawIBAQQgec92jwduadCk
OjoNRI+YT5Be5TkzZXzYCyTLkMOikDmhRANCAATtECEhQbLEaiUj/Wu0qjcr81lL
46dx5zYgArz/iaSNJ3W80oO+F7v04jlQ7wxQzg96R0bwKiMeq5CcW9ZFt6xg
-----END PRIVATE KEY-----
PrivateKey = B-163
-----BEGIN PRIVATE KEY-----
MGMCAQAwEAYHKoZIzj0CAQYFK4EEAA8ETDBKAgEBBBUDnQW0mLiHVha/jqFznX/K
DnVlDgChLgMsAAQB1qZ00fPIct+QN8skv1XIHtBNp3EGLytJV0tsAUTYtGhtrzRj
e3GzYyg=
-----END PRIVATE KEY-----
PrivateKey = secp256k1
-----BEGIN PRIVATE KEY-----
MIGEAgEAMBAGByqGSM49AgEGBSuBBAAKBG0wawIBAQQgsLpFV9joHc0bisyV53XL
mrG6/Gu6ZaHoXtKP/VFX44ehRANCAARLYWGgp5nP4N8guypLSbYGCVN6ZPCnWW4x
srYkcpdbxr4neRT3zC62keCKgPbJf5SIHkJ2Tcaw6hVSrBOUFtix
-----END PRIVATE KEY-----
Title = FIPS tests
# Test that a nist curve with < 112 bits is allowed in fips mode for verifying
DigestVerify = SHA256
Key = B-163
Input = "Hello World"
Output = 302e0215027bb891747468b4b59ca2a2bf8f42d29d08866cf5021502cc311b25e9a2168e42240b07a6071070f687eb3b
# Test that a nist curve with SHA3 is allowed in fips mode
# The sign will get a mismatch error since the output signature changes on each run
DigestSign = SHA3-512
Key = P-256
Input = "Hello World"
Result = SIGNATURE_MISMATCH
# Test that a explicit curve that is a named curve is allowed in fips mode
DigestVerify = SHA256
Key = P-256_NAMED_CURVE_EXPLICIT
Input = "Hello World"
Output = 30450220796fcf472882ed5779226dcd0217b9d2b9acfe4fa2fb0109c8ee63c63adc1033022100e306c69f7e31b9a5d54eb12ba813cddf4de4af933e4f6cea38a0817d9d831d91
Title = FIPS Negative tests (using different curves and digests)
# Test that a explicit curve is not allowed in fips mode
Availablein = fips
DigestVerify = SHA256
Securitycheck = 1
Key = EC_EXPLICIT
Input = "Hello World"
Result = DIGESTVERIFYINIT_ERROR
# Test that a curve with < 112 bits is not allowed in fips mode for signing
Availablein = fips
DigestSign = SHA3-512
Securitycheck = 1
Key = B-163
Input = "Hello World"
Result = DIGESTSIGNINIT_ERROR
# Test that a non nist curve is not allowed in fips mode
Availablein = fips
DigestSign = SHA3-512
Securitycheck = 1
Key = secp256k1
Input = "Hello World"
Result = DIGESTSIGNINIT_ERROR
# Test that SHA1 is not allowed in fips mode for signing
Availablein = fips
DigestSign = SHA1
Securitycheck = 1
Key = B-163
Input = "Hello World"
Result = DIGESTSIGNINIT_ERROR
# Test that SHA1 is not allowed in fips mode for signing
Availablein = fips
+FIPSversion = <3.4.0
Sign = P-256
Securitycheck = 1
Ctrl = digest:SHA1
Input = "0123456789ABCDEF1234"
Result = PKEY_CTRL_ERROR
# Invalid non-approved digest
Availablein = fips
DigestVerify = MD5
Securitycheck = 1
Key = P-256-PUBLIC
Result = DIGESTVERIFYINIT_ERROR
diff --git a/crypto/openssl/test/recipes/30-test_evp_data/evppkey_rsa_common.txt b/crypto/openssl/test/recipes/30-test_evp_data/evppkey_rsa_common.txt
index 24ec6a4f7705..5f3b396a6753 100644
--- a/crypto/openssl/test/recipes/30-test_evp_data/evppkey_rsa_common.txt
+++ b/crypto/openssl/test/recipes/30-test_evp_data/evppkey_rsa_common.txt
@@ -1,1375 +1,1376 @@
#
-# Copyright 2001-2021 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
# Tests start with one of these keywords
# Cipher Decrypt Derive Digest Encoding KDF MAC PBE
# PrivPubKeyPair Sign Verify VerifyRecover
# and continue until a blank line. Lines starting with a pound sign are ignored.
# The keyword Availablein must appear before the test name if needed.
# Private keys used for PKEY operations.
# RSA 2048 bit key.
PrivateKey = RSA-2048
-----BEGIN PRIVATE KEY-----
MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDNAIHqeyrh6gbV
n3xz2f+5SglhXC5Lp8Y2zvCN01M+wxhVJbAVx2m5mnfWclv5w1Mqm25fZifV+4UW
B2jT3anL01l0URcX3D0wnS/EfuQfl+Mq23+d2GShxHZ6Zm7NcbwarPXnUX9LOFlP
6psF5C1a2pkSAIAT5FMWpNm7jtCGuI0odYusr5ItRqhotIXSOcm66w4rZFknEPQr
LR6gpLSALAvsqzKPimiwBzvbVG/uqYCdKEmRKzkMFTK8finHZY+BdfrkbzQzL/h7
yrPkBkm5hXeGnaDqcYNT8HInVIhpE2SHYNEivmduD8SD3SD/wxvalqMZZsmqLnWt
A95H4cRPAgMBAAECggEAYCl6x5kbFnoG1rJHWLjL4gi+ubLZ7Jc4vYD5Ci41AF3X
ziktnim6iFvTFv7x8gkTvArJDWsICLJBTYIQREHYYkozzgIzyPeApIs3Wv8C12cS
IopwJITbP56+zM+77hcJ26GCgA2Unp5CFuC/81WDiPi9kNo3Oh2CdD7D+90UJ/0W
glplejFpEuhpU2URfKL4RckJQF/KxV+JX8FdIDhsJu54yemQdQKaF4psHkzwwgDo
qc+yfp0Vb4bmwq3CKxqEoc1cpbJ5CHXXlAfISzUjlcuBzD/tW7BDtp7eDAcgRVAC
XO6MX0QBcLYSC7SOD3R7zY9SIRCFDfBDxCjf0YcFMQKBgQD2+WG0fLwDXTrt68fe
hQqVa2Xs25z2B2QGPxWqSFU8WNly/mZ1BW413f3De/O58vYi7icTNyVoScm+8hdv
6PfD+LuRujdN1TuvPeyBTSvewQwf3IjN0Wh28mse36PwlBl+301C/x+ylxEDuJjK
hZxCcocIaoQqtBC7ac8tNa9r4wKBgQDUfnJKf/QQSLJwwlJKQQGHi3MVm7c9PbwY
eyIOY1s1NPluJDoYTZP4YLa/u2txwe2aHh9FhYMCPDAelqaSwaCLU9DsnKkQEA2A
RR47fcagG6xK7O+N95iEa8I1oIy7os9MBoBMwRIZ6VYIxxTj8UMNSR+tu6MqV1Gg
T5d0WDTJpQKBgCHyRSu5uV39AoyRS/eZ8cp36JqV1Q08FtOE+EVfi9evnrPfo9WR
2YQt7yNfdjCo5IwIj/ZkLhAXlFNakz4el2+oUJ/HKLLaDEoaCNf883q6rh/zABrK
HcG7sF2d/7qhoJ9/se7zgjfZ68zHIrkzhDbd5xGREnmMJoCcGo3sQyBhAoGAH3UQ
qmLC2N5KPFMoJ4H0HgLQ6LQCrnhDLkScSBEBYaEUA/AtAYgKjcyTgVLXlyGkcRpg
esRHHr+WSBD5W+R6ReYEmeKfTJdzyDdzQE9gZjdyjC0DUbsDwybIu3OnIef6VEDq
IXK7oUZfzDDcsNn4mTDoFaoff5cpqFfgDgM43VkCgYBNHw11b+d+AQmaZS9QqIt7
aF3FvwCYHV0jdv0Mb+Kc1bY4c0R5MFpzrTwVmdOerjuuA1+9b+0Hwo3nBZM4eaBu
SOamA2hu2OJWCl9q8fLCT69KqWDjghhvFe7c6aJJGucwaA3Uz3eLcPqoaCarMiNH
fMkTd7GabVourqIZdgvu1Q==
-----END PRIVATE KEY-----
# Corresponding public key
PublicKey = RSA-2048-PUBLIC
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAzQCB6nsq4eoG1Z98c9n/
uUoJYVwuS6fGNs7wjdNTPsMYVSWwFcdpuZp31nJb+cNTKptuX2Yn1fuFFgdo092p
y9NZdFEXF9w9MJ0vxH7kH5fjKtt/ndhkocR2emZuzXG8Gqz151F/SzhZT+qbBeQt
WtqZEgCAE+RTFqTZu47QhriNKHWLrK+SLUaoaLSF0jnJuusOK2RZJxD0Ky0eoKS0
gCwL7Ksyj4posAc721Rv7qmAnShJkSs5DBUyvH4px2WPgXX65G80My/4e8qz5AZJ
uYV3hp2g6nGDU/ByJ1SIaRNkh2DRIr5nbg/Eg90g/8Mb2pajGWbJqi51rQPeR+HE
TwIDAQAB
-----END PUBLIC KEY-----
PrivPubKeyPair = RSA-2048:RSA-2048-PUBLIC
# 1024 bit key
# generated using (openssl genpkey -algorithm RSA -pkeyopt bits:1024)
PrivateKey = RSA-1024
-----BEGIN PRIVATE KEY-----
MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAK02R0z9ehovubaQ
aSAj0UohCDkWB/bv/J+ra/bATuruD/Q/wm+4mp5+0btc+jNSC/eK+SEz1JVMtRUn
AfloXmsJXE3EDS65te1jphU3/MBXjs+YdlXVFNFmmLd4Nnum/I0z1Gvkimt0WQ2d
gn313vwqQDaSeho2Q2ZQgEbiwZ+3AgMBAAECgYEAn6tibMFY1lzaSEW08rCx1DDB
AMajTuoJKTL/UjYSSZRsVo6T8SLuPV7QfXQHHFnsuCN+5jF+LKbKYpZTxpKEPYid
4ghxoCQVg+2NrnRVUaw+Cv4iN9HlopaJg+Rc3XmbumoFE3JrkHZrZjkFWgdcijc7
YyWLlN1zQLMo8xOOujECQQDa1mPPqkYVkfLL6e60QtZtTFubjsiCCebWp2VZVSrF
vjQqEOl3jgNCrErODqSiheadaPk2SJRRoDpoDY9mTn4JAkEAyqBlP1yjlo+RpG2M
jsUltlfL3l9Xk1G/i/RpjwoOUcg8ZMqkuNDiWCBh9ND9KuT4VE9bw7Q37EoxH2OG
ORqfvwJAA7Fuicij2iVWZZ6TCrO+DqYlPaDRPXCRVroIedN4H1Iway1R41SgNXXW
5VdV6/A6jhmBaysaZa5AjhT8gIt+kQJAeJB1jfz+LXDhlPfGAZFWvieBW6BZSIQE
uC7GvGCcYpcFMGfPGVTYyN0DzBqp+OLiy6+oh0rtV4BRuD6Mt9+amwJBAIhG3Z6u
82FZ31EwRwj1TO80bEpsCa8cNLReJc+FyNytrYkjBddKwkGHciqeaXB65V+IDmlC
/0nh11NaBVUGqsQ=
-----END PRIVATE KEY-----
PrivateKey = RSA-512
-----BEGIN PRIVATE KEY-----
MIIBVAIBADANBgkqhkiG9w0BAQEFAASCAT4wggE6AgEAAkEA0aGpl/FjkDOqV8yF
Gw7IFXcLLVf0scal6HRJMJhLoB4iN0jq2XeVCDHNsIzTI7WmdYOV7FAdyOjCm74h
AFl+KQIDAQABAkAsWYBQte/zbQrHwmwSmmD4MZQ6xpXtGnK1KAzn7ABr4jHdV+OG
ic1+sY3aKj+C79GWF5WEd+NHnTrV+bSXPrXRAiEA+ahiTkZ9x0m1JmQ5/cJGm8zS
YOBdE0SlJZJrPskfGzUCIQDW9PkYpIddXU+vJoIIaTgoXmjMsETzcjcyjVkdK+LB
pQIgScvIIzMbAsl6znpZ2fSPQoZsuU4YtRVZa524LbrtgvECIQDFkRTdhGLx+hCC
ECeVqXe3CsbR0vUcuA5phSaxvCNHDQIgUaYqag90Gnxe9kST5K1DRRoKpksaIPbG
NDL6WCBbets=
-----END PRIVATE KEY-----
Title = RSA tests
Verify = RSA-2048
Ctrl = digest:SHA1
Input = "0123456789ABCDEF1234"
Output = c09d402423cbf233d26cae21f954547bc43fe80fd41360a0336cfdbe9aedad05bef6fd2eaee6cd60089a52482d4809a238149520df3bdde4cb9e23d9307b05c0a6f327052325a29adf2cc95b66523be7024e2a585c3d4db15dfbe146efe0ecdc0402e33fe5d40324ee96c5c3edd374a15cdc0f5d84aa243c0f07e188c6518fbfceae158a9943be398e31097da81b62074f626eff738be6160741d5a26957a482b3251fd85d8df78b98148459de10aa93305dbb4a5230aa1da291a9b0e481918f99b7638d72bb687f97661d304ae145d64a474437a4ef39d7b8059332ddeb07e92bf6e0e3acaf8afedc93795e4511737ec1e7aab6d5bc9466afc950c1c17b48ad
# Truncated digest
Sign = RSA-2048
Ctrl = digest:SHA512-224
Input = "0123456789ABCDEF123456789ABC"
Output = 5f720e9488139bb21e1c2f027fd5ce5993e6d31c5a8faaee833487b3a944d66891178868ace8070cad3ee2ffbe54aa4885a15fd1a7cc5166970fe1fd8c0423e72bd3e3b56fc4a53ed80aaaeca42497f0ec3c62113edc05cd006608f5eef7ce3ad4cba1069f68731dd28a524a1f93fcdc5547112d48d45586dd943ba0d443be9635720d8a61697c54c96627f0d85c5fbeaa3b4af86a65cf2fc3800dd5de34c046985f25d0efc0bb6edccc1d08b3a4fb9c8faffe181c7e68b31e374ad1440a4a664eec9ca0dc53a9d2f5bc7d9940d866f64201bcbc63612754df45727ea24b531d7de83d1bb707444859fa35521320c33bf6f4dbeb6fb56e653adbf7af15843f17
Verify = RSA-2048
Ctrl = digest:SHA512-224
Input = "0123456789ABCDEF123456789ABC"
Output = 5f720e9488139bb21e1c2f027fd5ce5993e6d31c5a8faaee833487b3a944d66891178868ace8070cad3ee2ffbe54aa4885a15fd1a7cc5166970fe1fd8c0423e72bd3e3b56fc4a53ed80aaaeca42497f0ec3c62113edc05cd006608f5eef7ce3ad4cba1069f68731dd28a524a1f93fcdc5547112d48d45586dd943ba0d443be9635720d8a61697c54c96627f0d85c5fbeaa3b4af86a65cf2fc3800dd5de34c046985f25d0efc0bb6edccc1d08b3a4fb9c8faffe181c7e68b31e374ad1440a4a664eec9ca0dc53a9d2f5bc7d9940d866f64201bcbc63612754df45727ea24b531d7de83d1bb707444859fa35521320c33bf6f4dbeb6fb56e653adbf7af15843f17
VerifyRecover = RSA-2048
Ctrl = digest:SHA1
Input = c09d402423cbf233d26cae21f954547bc43fe80fd41360a0336cfdbe9aedad05bef6fd2eaee6cd60089a52482d4809a238149520df3bdde4cb9e23d9307b05c0a6f327052325a29adf2cc95b66523be7024e2a585c3d4db15dfbe146efe0ecdc0402e33fe5d40324ee96c5c3edd374a15cdc0f5d84aa243c0f07e188c6518fbfceae158a9943be398e31097da81b62074f626eff738be6160741d5a26957a482b3251fd85d8df78b98148459de10aa93305dbb4a5230aa1da291a9b0e481918f99b7638d72bb687f97661d304ae145d64a474437a4ef39d7b8059332ddeb07e92bf6e0e3acaf8afedc93795e4511737ec1e7aab6d5bc9466afc950c1c17b48ad
Output = "0123456789ABCDEF1234"
# Leading zero in the signature
Verify = RSA-2048
Ctrl = digest:SHA1
Input = "0123456789ABCDEF1234"
Output = 00c09d402423cbf233d26cae21f954547bc43fe80fd41360a0336cfdbe9aedad05bef6fd2eaee6cd60089a52482d4809a238149520df3bdde4cb9e23d9307b05c0a6f327052325a29adf2cc95b66523be7024e2a585c3d4db15dfbe146efe0ecdc0402e33fe5d40324ee96c5c3edd374a15cdc0f5d84aa243c0f07e188c6518fbfceae158a9943be398e31097da81b62074f626eff738be6160741d5a26957a482b3251fd85d8df78b98148459de10aa93305dbb4a5230aa1da291a9b0e481918f99b7638d72bb687f97661d304ae145d64a474437a4ef39d7b8059332ddeb07e92bf6e0e3acaf8afedc93795e4511737ec1e7aab6d5bc9466afc950c1c17b48ad
Result = VERIFY_ERROR
VerifyRecover = RSA-2048
Ctrl = digest:SHA1
Input = 00c09d402423cbf233d26cae21f954547bc43fe80fd41360a0336cfdbe9aedad05bef6fd2eaee6cd60089a52482d4809a238149520df3bdde4cb9e23d9307b05c0a6f327052325a29adf2cc95b66523be7024e2a585c3d4db15dfbe146efe0ecdc0402e33fe5d40324ee96c5c3edd374a15cdc0f5d84aa243c0f07e188c6518fbfceae158a9943be398e31097da81b62074f626eff738be6160741d5a26957a482b3251fd85d8df78b98148459de10aa93305dbb4a5230aa1da291a9b0e481918f99b7638d72bb687f97661d304ae145d64a474437a4ef39d7b8059332ddeb07e92bf6e0e3acaf8afedc93795e4511737ec1e7aab6d5bc9466afc950c1c17b48ad
Result = KEYOP_ERROR
# Mismatched digest
Verify = RSA-2048
Ctrl = digest:SHA1
Input = "0123456789ABCDEF1233"
Output = c09d402423cbf233d26cae21f954547bc43fe80fd41360a0336cfdbe9aedad05bef6fd2eaee6cd60089a52482d4809a238149520df3bdde4cb9e23d9307b05c0a6f327052325a29adf2cc95b66523be7024e2a585c3d4db15dfbe146efe0ecdc0402e33fe5d40324ee96c5c3edd374a15cdc0f5d84aa243c0f07e188c6518fbfceae158a9943be398e31097da81b62074f626eff738be6160741d5a26957a482b3251fd85d8df78b98148459de10aa93305dbb4a5230aa1da291a9b0e481918f99b7638d72bb687f97661d304ae145d64a474437a4ef39d7b8059332ddeb07e92bf6e0e3acaf8afedc93795e4511737ec1e7aab6d5bc9466afc950c1c17b48ad
Result = VERIFY_ERROR
# Corrupted signature
Verify = RSA-2048
Ctrl = digest:SHA1
Input = "0123456789ABCDEF1233"
Output = c09d402423cbf233d26cae21f954547bc43fe80fd41360a0336cfdbe9aedad05bef6fd2eaee6cd60089a52482d4809a238149520df3bdde4cb9e23d9307b05c0a6f327052325a29adf2cc95b66523be7024e2a585c3d4db15dfbe146efe0ecdc0402e33fe5d40324ee96c5c3edd374a15cdc0f5d84aa243c0f07e188c6518fbfceae158a9943be398e31097da81b62074f626eff738be6160741d5a26957a482b3251fd85d8df78b98148459de10aa93305dbb4a5230aa1da291a9b0e481918f99b7638d72bb687f97661d304ae145d64a474437a4ef39d7b8059332ddeb07e92bf6e0e3acaf8afedc93795e4511737ec1e7aab6d5bc9466afc950c1c17b48ae
Result = VERIFY_ERROR
# parameter is not NULLt
Verify = RSA-2048
Ctrl = digest:sha1
Input = "0123456789ABCDEF1234"
Output = 3ec3fc29eb6e122bd7aa361cd09fe1bcbe85311096a7b9e4799cedfb2351ce0ab7fe4e75b4f6b37f67edd9c60c800f9ab941c0c157d7d880ca9de40c951d60fd293ae220d4bc510b1572d6e85a1bbbd8605b52e05f1c64fafdae59a1c2fbed214b7844d0134619de62851d5a0522e32e556e5950f3f97b8150e3f0dffee612c924201c27cd9bc8b423a71533380c276d3d59fcba35a2e80a1a192ec266a6c2255012cd86a349fe90a542b355fa3355b04da6cdf1df77f0e7bd44a90e880e1760266d233e465226f5db1c68857847d82072861ee266ddfc2e596845b77e1803274a579835ab5e4975d81d20b7df9cec7795489e4a2bdb8c1cf6a6b359945ac92c
Result = VERIFY_ERROR
# embedded digest too long
Verify = RSA-2048
Ctrl = digest:sha1
Input = "0123456789ABCDEF1234"
Output = afec9a0d5330a08f54283bb4a9d4e7e7e70fc1342336c4c766fba713f66970151c6e27413c48c33864ea45a0238787004f338ed3e21b53b0fe9c1151c42c388cbc7cba5a06b706c407a5b48324fbe994dc7afc3a19fb3d2841e66222596c14cd72a0f0a7455a019d8eb554f59c0183f9552b75aa96fee8bf935945e079ca283d2bd3534a86f11351f6d6181fbf433e5b01a6d1422145c7a72214d3aacdd5d3af12b2d6bf6438f9f9a64010d8aeed801c87f0859412b236150b86a545f7239be022f4a7ad246b59df87514294cb4a4c7c5a997ee53c66054d9f38ca4e76c1f7af83c30f737ef70f83a45aebe18238ddb95e1998814ca4fc72388f1533147c169d
Result = VERIFY_ERROR
VerifyRecover = RSA-2048
Ctrl = digest:sha1
Input = afec9a0d5330a08f54283bb4a9d4e7e7e70fc1342336c4c766fba713f66970151c6e27413c48c33864ea45a0238787004f338ed3e21b53b0fe9c1151c42c388cbc7cba5a06b706c407a5b48324fbe994dc7afc3a19fb3d2841e66222596c14cd72a0f0a7455a019d8eb554f59c0183f9552b75aa96fee8bf935945e079ca283d2bd3534a86f11351f6d6181fbf433e5b01a6d1422145c7a72214d3aacdd5d3af12b2d6bf6438f9f9a64010d8aeed801c87f0859412b236150b86a545f7239be022f4a7ad246b59df87514294cb4a4c7c5a997ee53c66054d9f38ca4e76c1f7af83c30f737ef70f83a45aebe18238ddb95e1998814ca4fc72388f1533147c169d
Result = KEYOP_ERROR
# embedded digest too short
Verify = RSA-2048
Ctrl = digest:sha1
Input = "0123456789ABCDEF1234"
Output = afec9a0d5330a08f54283bb4a9d4e7e7e70fc1342336c4c766fba713f66970151c6e27413c48c33864ea45a0238787004f338ed3e21b53b0fe9c1151c42c388cbc7cba5a06b706c407a5b48324fbe994dc7afc3a19fb3d2841e66222596c14cd72a0f0a7455a019d8eb554f59c0183f9552b75aa96fee8bf935945e079ca283d2bd3534a86f11351f6d6181fbf433e5b01a6d1422145c7a72214d3aacdd5d3af12b2d6bf6438f9f9a64010d8aeed801c87f0859412b236150b86a545f7239be022f4a7ad246b59df87514294cb4a4c7c5a997ee53c66054d9f38ca4e76c1f7af83c30f737ef70f83a45aebe18238ddb95e1998814ca4fc72388f1533147c169d
Result = VERIFY_ERROR
VerifyRecover = RSA-2048
Ctrl = digest:sha1
Input = afec9a0d5330a08f54283bb4a9d4e7e7e70fc1342336c4c766fba713f66970151c6e27413c48c33864ea45a0238787004f338ed3e21b53b0fe9c1151c42c388cbc7cba5a06b706c407a5b48324fbe994dc7afc3a19fb3d2841e66222596c14cd72a0f0a7455a019d8eb554f59c0183f9552b75aa96fee8bf935945e079ca283d2bd3534a86f11351f6d6181fbf433e5b01a6d1422145c7a72214d3aacdd5d3af12b2d6bf6438f9f9a64010d8aeed801c87f0859412b236150b86a545f7239be022f4a7ad246b59df87514294cb4a4c7c5a997ee53c66054d9f38ca4e76c1f7af83c30f737ef70f83a45aebe18238ddb95e1998814ca4fc72388f1533147c169d
Result = KEYOP_ERROR
# Garbage after DigestInfo
Verify = RSA-2048
Ctrl = digest:sha1
Input = "0123456789ABCDEF1234"
Output = 9ee34872d4271a7d8808af0a4052a145a6d6a8437d00da3ed14428c7f087cd39f4d43334c41af63e7fa1ba363fee7bcef401d9d36a662abbab55ce89a696e1be0dfa19a5d09ca617dd488787b6048baaefeb29bc8688b2fe3882de2b77c905b5a8b56cf9616041e5ec934ba6de863efe93acc4eef783fe7f72a00fa65d6093ed32bf98ce527e62ccb1d56317f4be18b7e0f55d7c36617d2d0678a306e3350956b662ac15df45215dd8f6b314babb9788e6c272fa461e4c9b512a11a4b92bc77c3a4c95c903fccb238794eca5c750477bf56ea6ee6a167367d881b485ae3889e7c489af8fdf38e0c0f2aed780831182e34abedd43c39281b290774bf35cc25274
Result = VERIFY_ERROR
VerifyRecover = RSA-2048
Ctrl = digest:sha1
Input = 9ee34872d4271a7d8808af0a4052a145a6d6a8437d00da3ed14428c7f087cd39f4d43334c41af63e7fa1ba363fee7bcef401d9d36a662abbab55ce89a696e1be0dfa19a5d09ca617dd488787b6048baaefeb29bc8688b2fe3882de2b77c905b5a8b56cf9616041e5ec934ba6de863efe93acc4eef783fe7f72a00fa65d6093ed32bf98ce527e62ccb1d56317f4be18b7e0f55d7c36617d2d0678a306e3350956b662ac15df45215dd8f6b314babb9788e6c272fa461e4c9b512a11a4b92bc77c3a4c95c903fccb238794eca5c750477bf56ea6ee6a167367d881b485ae3889e7c489af8fdf38e0c0f2aed780831182e34abedd43c39281b290774bf35cc25274
Result = KEYOP_ERROR
# invalid tag for parameter
Verify = RSA-2048
Ctrl = digest:sha1
Input = "0123456789ABCDEF1234"
Output = 49525db4d44c755e560cba980b1d85ea604b0e077fcadd4ba44072a3487bbddb835016200a7d8739cce2dc3223d9c20cbdd25059ab02277f1f21318efd18e21038ec89aa9d40680987129e8b41ba33bceb86518bdf47268b921cce2037acabca6575d832499538d6f40cdba0d40bd7f4d8ea6ca6e2eec87f294efc971407857f5d7db09f6a7b31e301f571c6d82a5e3d08d2bb3a36e673d28b910f5bec57f0fcc4d968fd7c94d0b9226dec17f5192ad8b42bcab6f26e1bea1fdc3b958199acb00f14ebcb2a352f3afcedd4c09000128a603bbeb9696dea13040445253972d46237a25c7845e3b464e6984c2348ea1f1210a9ff0b00d2d72b50db00c009bb39f9
Result = VERIFY_ERROR
# Verify using public key
Verify = RSA-2048-PUBLIC
Ctrl = digest:SHA1
Input = "0123456789ABCDEF1234"
Output = c09d402423cbf233d26cae21f954547bc43fe80fd41360a0336cfdbe9aedad05bef6fd2eaee6cd60089a52482d4809a238149520df3bdde4cb9e23d9307b05c0a6f327052325a29adf2cc95b66523be7024e2a585c3d4db15dfbe146efe0ecdc0402e33fe5d40324ee96c5c3edd374a15cdc0f5d84aa243c0f07e188c6518fbfceae158a9943be398e31097da81b62074f626eff738be6160741d5a26957a482b3251fd85d8df78b98148459de10aa93305dbb4a5230aa1da291a9b0e481918f99b7638d72bb687f97661d304ae145d64a474437a4ef39d7b8059332ddeb07e92bf6e0e3acaf8afedc93795e4511737ec1e7aab6d5bc9466afc950c1c17b48ad
# no padding
# Too small input
Sign = RSA-2048
Ctrl = rsa_padding_mode:none
Input = "0123456789ABCDEF123456789ABC"
Output = c09d402423cbf233d26cae21f954547bc43fe80fd41360a0336cfdbe9aedad05bef6fd2eaee6cd60089a52482d4809a238149520df3bdde4cb9e23d9307b05c0a6f327052325a29adf2cc95b66523be7024e2a585c3d4db15dfbe146efe0ecdc0402e33fe5d40324ee96c5c3edd374a15cdc0f5d84aa243c0f07e188c6518fbfceae158a9943be398e31097da81b62074f626eff738be6160741d5a26957a482b3251fd85d8df78b98148459de10aa93305dbb4a5230aa1da291a9b0e481918f99b7638d72bb687f97661d304ae145d64a474437a4ef39d7b8059332ddeb07e92bf6e0e3acaf8afedc93795e4511737ec1e7aab6d5bc9466afc950c1c17b48ad
Result = KEYOP_ERROR
# Digest set before padding
Sign = RSA-2048
Ctrl = digest:sha256
Ctrl = rsa_padding_mode:none
Input = 0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef
Output = 64b0e9f9892371110c40ba5739dc0974002aa6e6160b481447c6819947c2d3b537a6e3775a85ae8ef75e000ca5498d772e3e797012ac8e462d72e567eb4afae0d1df72ffc84b3117045c58eb13aabb427fd6591577089dfa36d8d07ebd0670e4473683659b53b050c32397752cdee7c08de667f8de0ec01db01d440e433986e57ead2f877356b7d4985daf6c7ba09e46c061fe2372baa90cbd77557ef1143f46e27abf65c276f165a753e1f09e3719d1bfd8b32efe4aed2e97b502aa96ce472d3d91a09fae47b1a5103c448039ada73a57d7a001542bfb0b58c8b4bcb705a108a643434bb7ff997b58ba8b76425d7510aeff3e60f17af82191500517653fa5f3
Result = PKEY_CTRL_ERROR
# Digest set after padding
Sign = RSA-2048
Ctrl = rsa_padding_mode:none
Ctrl = digest:sha256
Input = 0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef
Output = 64b0e9f9892371110c40ba5739dc0974002aa6e6160b481447c6819947c2d3b537a6e3775a85ae8ef75e000ca5498d772e3e797012ac8e462d72e567eb4afae0d1df72ffc84b3117045c58eb13aabb427fd6591577089dfa36d8d07ebd0670e4473683659b53b050c32397752cdee7c08de667f8de0ec01db01d440e433986e57ead2f877356b7d4985daf6c7ba09e46c061fe2372baa90cbd77557ef1143f46e27abf65c276f165a753e1f09e3719d1bfd8b32efe4aed2e97b502aa96ce472d3d91a09fae47b1a5103c448039ada73a57d7a001542bfb0b58c8b4bcb705a108a643434bb7ff997b58ba8b76425d7510aeff3e60f17af82191500517653fa5f3
Result = PKEY_CTRL_ERROR
Sign = RSA-2048
Ctrl = rsa_padding_mode:none
Input = 0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef
Output = 64b0e9f9892371110c40ba5739dc0974002aa6e6160b481447c6819947c2d3b537a6e3775a85ae8ef75e000ca5498d772e3e797012ac8e462d72e567eb4afae0d1df72ffc84b3117045c58eb13aabb427fd6591577089dfa36d8d07ebd0670e4473683659b53b050c32397752cdee7c08de667f8de0ec01db01d440e433986e57ead2f877356b7d4985daf6c7ba09e46c061fe2372baa90cbd77557ef1143f46e27abf65c276f165a753e1f09e3719d1bfd8b32efe4aed2e97b502aa96ce472d3d91a09fae47b1a5103c448039ada73a57d7a001542bfb0b58c8b4bcb705a108a643434bb7ff997b58ba8b76425d7510aeff3e60f17af82191500517653fa5f3
Verify = RSA-2048-PUBLIC
Ctrl = rsa_padding_mode:none
Input = 0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef
Output = 64b0e9f9892371110c40ba5739dc0974002aa6e6160b481447c6819947c2d3b537a6e3775a85ae8ef75e000ca5498d772e3e797012ac8e462d72e567eb4afae0d1df72ffc84b3117045c58eb13aabb427fd6591577089dfa36d8d07ebd0670e4473683659b53b050c32397752cdee7c08de667f8de0ec01db01d440e433986e57ead2f877356b7d4985daf6c7ba09e46c061fe2372baa90cbd77557ef1143f46e27abf65c276f165a753e1f09e3719d1bfd8b32efe4aed2e97b502aa96ce472d3d91a09fae47b1a5103c448039ada73a57d7a001542bfb0b58c8b4bcb705a108a643434bb7ff997b58ba8b76425d7510aeff3e60f17af82191500517653fa5f3
# Plaintext modified
Verify = RSA-2048-PUBLIC
Ctrl = rsa_padding_mode:none
Input = 0223456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef
Output = 64b0e9f9892371110c40ba5739dc0974002aa6e6160b481447c6819947c2d3b537a6e3775a85ae8ef75e000ca5498d772e3e797012ac8e462d72e567eb4afae0d1df72ffc84b3117045c58eb13aabb427fd6591577089dfa36d8d07ebd0670e4473683659b53b050c32397752cdee7c08de667f8de0ec01db01d440e433986e57ead2f877356b7d4985daf6c7ba09e46c061fe2372baa90cbd77557ef1143f46e27abf65c276f165a753e1f09e3719d1bfd8b32efe4aed2e97b502aa96ce472d3d91a09fae47b1a5103c448039ada73a57d7a001542bfb0b58c8b4bcb705a108a643434bb7ff997b58ba8b76425d7510aeff3e60f17af82191500517653fa5f3
Result = VERIFY_ERROR
VerifyRecover = RSA-2048-PUBLIC
Ctrl = rsa_padding_mode:none
Input = 64b0e9f9892371110c40ba5739dc0974002aa6e6160b481447c6819947c2d3b537a6e3775a85ae8ef75e000ca5498d772e3e797012ac8e462d72e567eb4afae0d1df72ffc84b3117045c58eb13aabb427fd6591577089dfa36d8d07ebd0670e4473683659b53b050c32397752cdee7c08de667f8de0ec01db01d440e433986e57ead2f877356b7d4985daf6c7ba09e46c061fe2372baa90cbd77557ef1143f46e27abf65c276f165a753e1f09e3719d1bfd8b32efe4aed2e97b502aa96ce472d3d91a09fae47b1a5103c448039ada73a57d7a001542bfb0b58c8b4bcb705a108a643434bb7ff997b58ba8b76425d7510aeff3e60f17af82191500517653fa5f3
Output = 0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef
# RSA decrypt
Decrypt = RSA-2048
Input = 550AF55A2904E7B9762352F8FB7FA235A9CB053AACB2D5FCB8CA48453CB2EE3619746C701ABF2D4CC67003471A187900B05AA812BD25ED05C675DFC8C97A24A7BF49BD6214992CAD766D05A9A2B57B74F26A737E0237B8B76C45F1F226A836D7CFBC75BA999BDBE48DBC09227AA46C88F21DCCBA7840141AD5A5D71FD122E6BD6AC3E564780DFE623FC1CA9B995A6037BF0BBD43B205A84AC5444F34202C05CE9113087176432476576DE6FFFF9A52EA57C08BE3EC2F49676CB8E12F762AC71FA3C321E00AC988910C85FF52F93825666CE0D40FFAA0592078919D4493F46D95CCF76364C6D57760DD0B64805F9AFC76A2365A5575CA301D5103F0EA76CB9A78
Output = "Hello World"
# Corrupted ciphertext
FIPSversion = <3.2.0
Decrypt = RSA-2048
Input = 550AF55A2904E7B9762352F8FB7FA235A9CB053AACB2D5FCB8CA48453CB2EE3619746C701ABF2D4CC67003471A187900B05AA812BD25ED05C675DFC8C97A24A7BF49BD6214992CAD766D05A9A2B57B74F26A737E0237B8B76C45F1F226A836D7CFBC75BA999BDBE48DBC09227AA46C88F21DCCBA7840141AD5A5D71FD122E6BD6AC3E564780DFE623FC1CA9B995A6037BF0BBD43B205A84AC5444F34202C05CE9113087176432476576DE6FFFF9A52EA57C08BE3EC2F49676CB8E12F762AC71FA3C321E00AC988910C85FF52F93825666CE0D40FFAA0592078919D4493F46D95CCF76364C6D57760DD0B64805F9AFC76A2365A5575CA301D5103F0EA76CB9A79
Output = "Hello World"
Result = KEYOP_ERROR
# OAEP padding
Decrypt = RSA-2048
Ctrl = rsa_padding_mode:oaep
Input = 458708DFBD42A1297CE7A9C86C7087AB80B1754810929B89C5107CA55368587686986FCE94D86CC1595B3FB736223A656EC0F34D18BA1CC5665593610F56C58E26B272D584F3D983A5C91085700755AEBD921FB280BBA3EDA7046EC07B43E7298E52D59EDC92BE4639A8CE08B2F85976ECF6D98CC469EEB9D5D8E2A32EA8A6626EDAFE1038B3DF455668A9F3C77CAD8B92FB872E00058C3D2A7EDE1A1F03FC5622084AE04D9D24F6BF0995C58D35B93B699B9763595E123F2AB0863CC9229EB290E2EDE7715C7A8F39E0B9A3E2E1B56EBB62F1CBFBB5986FB212EBD785B83D01D968B11D1756C7337F70C1F1A63BFF03608E24F3A2FD44E67F832A8701C5D5AF
Output = "Hello World"
# OAEP padding, corrupted ciphertext
Decrypt = RSA-2048
Ctrl = rsa_padding_mode:oaep
Input = 458708DFBD42A1297CE7A9C86C7087AB80B1754810929B89C5107CA55368587686986FCE94D86CC1595B3FB736223A656EC0F34D18BA1CC5665593610F56C58E26B272D584F3D983A5C91085700755AEBD921FB280BBA3EDA7046EC07B43E7298E52D59EDC92BE4639A8CE08B2F85976ECF6D98CC469EEB9D5D8E2A32EA8A6626EDAFE1038B3DF455668A9F3C77CAD8B92FB872E00058C3D2A7EDE1A1F03FC5622084AE04D9D24F6BF0995C58D35B93B699B9763595E123F2AB0863CC9229EB290E2EDE7715C7A8F39E0B9A3E2E1B56EBB62F1CBFBB5986FB212EBD785B83D01D968B11D1756C7337F70C1F1A63BFF03608E24F3A2FD44E67F832A8701C5D5AC
Output = "Hello World"
Result = KEYOP_ERROR
# Illegal RSA key derivation
Derive = RSA-2048
Result = KEYOP_INIT_ERROR
Reason = operation not supported for this keytype
# RSA PSS key tests
# PSS only key, no parameter restrictions
PrivateKey = RSA-PSS
-----BEGIN PRIVATE KEY-----
MIIEugIBADALBgkqhkiG9w0BAQoEggSmMIIEogIBAAKCAQEAzQCB6nsq4eoG1Z98
c9n/uUoJYVwuS6fGNs7wjdNTPsMYVSWwFcdpuZp31nJb+cNTKptuX2Yn1fuFFgdo
092py9NZdFEXF9w9MJ0vxH7kH5fjKtt/ndhkocR2emZuzXG8Gqz151F/SzhZT+qb
BeQtWtqZEgCAE+RTFqTZu47QhriNKHWLrK+SLUaoaLSF0jnJuusOK2RZJxD0Ky0e
oKS0gCwL7Ksyj4posAc721Rv7qmAnShJkSs5DBUyvH4px2WPgXX65G80My/4e8qz
5AZJuYV3hp2g6nGDU/ByJ1SIaRNkh2DRIr5nbg/Eg90g/8Mb2pajGWbJqi51rQPe
R+HETwIDAQABAoIBAGApeseZGxZ6BtayR1i4y+IIvrmy2eyXOL2A+QouNQBd184p
LZ4puohb0xb+8fIJE7wKyQ1rCAiyQU2CEERB2GJKM84CM8j3gKSLN1r/AtdnEiKK
cCSE2z+evszPu+4XCduhgoANlJ6eQhbgv/NVg4j4vZDaNzodgnQ+w/vdFCf9FoJa
ZXoxaRLoaVNlEXyi+EXJCUBfysVfiV/BXSA4bCbueMnpkHUCmheKbB5M8MIA6KnP
sn6dFW+G5sKtwisahKHNXKWyeQh115QHyEs1I5XLgcw/7VuwQ7ae3gwHIEVQAlzu
jF9EAXC2Egu0jg90e82PUiEQhQ3wQ8Qo39GHBTECgYEA9vlhtHy8A1067evH3oUK
lWtl7Nuc9gdkBj8VqkhVPFjZcv5mdQVuNd39w3vzufL2Iu4nEzclaEnJvvIXb+j3
w/i7kbo3TdU7rz3sgU0r3sEMH9yIzdFodvJrHt+j8JQZft9NQv8fspcRA7iYyoWc
QnKHCGqEKrQQu2nPLTWva+MCgYEA1H5ySn/0EEiycMJSSkEBh4tzFZu3PT28GHsi
DmNbNTT5biQ6GE2T+GC2v7trccHtmh4fRYWDAjwwHpamksGgi1PQ7JypEBANgEUe
O33GoBusSuzvjfeYhGvCNaCMu6LPTAaATMESGelWCMcU4/FDDUkfrbujKldRoE+X
dFg0yaUCgYAh8kUrubld/QKMkUv3mfHKd+ialdUNPBbThPhFX4vXr56z36PVkdmE
Le8jX3YwqOSMCI/2ZC4QF5RTWpM+HpdvqFCfxyiy2gxKGgjX/PN6uq4f8wAayh3B
u7Bdnf+6oaCff7Hu84I32evMxyK5M4Q23ecRkRJ5jCaAnBqN7EMgYQKBgB91EKpi
wtjeSjxTKCeB9B4C0Oi0Aq54Qy5EnEgRAWGhFAPwLQGICo3Mk4FS15chpHEaYHrE
Rx6/lkgQ+VvkekXmBJnin0yXc8g3c0BPYGY3cowtA1G7A8MmyLtzpyHn+lRA6iFy
u6FGX8ww3LDZ+Jkw6BWqH3+XKahX4A4DON1ZAoGATR8NdW/nfgEJmmUvUKiLe2hd
xb8AmB1dI3b9DG/inNW2OHNEeTBac608FZnTnq47rgNfvW/tB8KN5wWTOHmgbkjm
pgNobtjiVgpfavHywk+vSqlg44IYbxXu3OmiSRrnMGgN1M93i3D6qGgmqzIjR3zJ
E3exmm1aLq6iGXYL7tU=
-----END PRIVATE KEY-----
# PSS public key default parameters
PublicKey = RSA-PSS-DEFAULT
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQowAAOCAQ8AMIIBCgKCAQEAzQCB6nsq4eoG1Z98c9n/
uUoJYVwuS6fGNs7wjdNTPsMYVSWwFcdpuZp31nJb+cNTKptuX2Yn1fuFFgdo092p
y9NZdFEXF9w9MJ0vxH7kH5fjKtt/ndhkocR2emZuzXG8Gqz151F/SzhZT+qbBeQt
WtqZEgCAE+RTFqTZu47QhriNKHWLrK+SLUaoaLSF0jnJuusOK2RZJxD0Ky0eoKS0
gCwL7Ksyj4posAc721Rv7qmAnShJkSs5DBUyvH4px2WPgXX65G80My/4e8qz5AZJ
uYV3hp2g6nGDU/ByJ1SIaRNkh2DRIr5nbg/Eg90g/8Mb2pajGWbJqi51rQPeR+HE
TwIDAQAB
-----END PUBLIC KEY-----
PrivPubKeyPair = RSA-PSS:RSA-PSS-DEFAULT
# Key with invalid negative minimum salt length
PublicKey = RSA-PSS-BAD
-----BEGIN PUBLIC KEY-----
MIIBJzASBgkqhkiG9w0BAQowBaIDAgH/A4IBDwAwggEKAoIBAQDNAIHqeyrh6gbV
n3xz2f+5SglhXC5Lp8Y2zvCN01M+wxhVJbAVx2m5mnfWclv5w1Mqm25fZifV+4UW
B2jT3anL01l0URcX3D0wnS/EfuQfl+Mq23+d2GShxHZ6Zm7NcbwarPXnUX9LOFlP
6psF5C1a2pkSAIAT5FMWpNm7jtCGuI0odYusr5ItRqhotIXSOcm66w4rZFknEPQr
LR6gpLSALAvsqzKPimiwBzvbVG/uqYCdKEmRKzkMFTK8finHZY+BdfrkbzQzL/h7
yrPkBkm5hXeGnaDqcYNT8HInVIhpE2SHYNEivmduD8SD3SD/wxvalqMZZsmqLnWt
A95H4cRPAgMBAAE=
-----END PUBLIC KEY-----
PrivPubKeyPair = RSA-PSS:RSA-PSS-BAD
# Key with minimum salt length exceeding maximum permitted value
PublicKey = RSA-PSS-BAD2
-----BEGIN PUBLIC KEY-----
MIIBKDATBgkqhkiG9w0BAQowBqIEAgIBAAOCAQ8AMIIBCgKCAQEAzQCB6nsq4eoG
1Z98c9n/uUoJYVwuS6fGNs7wjdNTPsMYVSWwFcdpuZp31nJb+cNTKptuX2Yn1fuF
Fgdo092py9NZdFEXF9w9MJ0vxH7kH5fjKtt/ndhkocR2emZuzXG8Gqz151F/SzhZ
T+qbBeQtWtqZEgCAE+RTFqTZu47QhriNKHWLrK+SLUaoaLSF0jnJuusOK2RZJxD0
Ky0eoKS0gCwL7Ksyj4posAc721Rv7qmAnShJkSs5DBUyvH4px2WPgXX65G80My/4
e8qz5AZJuYV3hp2g6nGDU/ByJ1SIaRNkh2DRIr5nbg/Eg90g/8Mb2pajGWbJqi51
rQPeR+HETwIDAQAB
-----END PUBLIC KEY-----
PrivPubKeyPair = RSA-PSS:RSA-PSS-BAD2
# Zero salt length makes output deterministic
Sign = RSA-2048
Ctrl = digest:sha256
Ctrl = rsa_padding_mode:pss
Ctrl = rsa_pss_saltlen:0
Input="0123456789ABCDEF0123456789ABCDEF"
Output=4DE433D5844043EF08D354DA03CB29068780D52706D7D1E4D50EFB7D58C9D547D83A747DDD0635A96B28F854E50145518482CB49E963054621B53C60C498D07C16E9C2789C893CF38D4D86900DE71BDE463BD2761D1271E358C7480A1AC0BAB930DDF39602AD1BC165B5D7436B516B7A7858E8EB7AB1C420EEB482F4D207F0E462B1724959320A084E13848D11D10FB593E66BF680BF6D3F345FC3E9C3DE60ABBAC37E1C6EC80A268C8D9FC49626C679097AA690BC1AA662B95EB8DB70390861AA0898229F9349B4B5FDD030D4928C47084708A933144BE23BD3C6E661B85B2C0EF9ED36D498D5B7320E8194D363D4AD478C059BAE804181965E0B81B663158A
# Verify of above signature
Verify = RSA-2048-PUBLIC
Ctrl = rsa_padding_mode:pss
Ctrl = rsa_pss_saltlen:0
Ctrl = digest:sha256
Input="0123456789ABCDEF0123456789ABCDEF"
Output=4DE433D5844043EF08D354DA03CB29068780D52706D7D1E4D50EFB7D58C9D547D83A747DDD0635A96B28F854E50145518482CB49E963054621B53C60C498D07C16E9C2789C893CF38D4D86900DE71BDE463BD2761D1271E358C7480A1AC0BAB930DDF39602AD1BC165B5D7436B516B7A7858E8EB7AB1C420EEB482F4D207F0E462B1724959320A084E13848D11D10FB593E66BF680BF6D3F345FC3E9C3DE60ABBAC37E1C6EC80A268C8D9FC49626C679097AA690BC1AA662B95EB8DB70390861AA0898229F9349B4B5FDD030D4928C47084708A933144BE23BD3C6E661B85B2C0EF9ED36D498D5B7320E8194D363D4AD478C059BAE804181965E0B81B663158A
# Verify using salt length auto detect
Verify = RSA-2048-PUBLIC
Ctrl = rsa_padding_mode:pss
Ctrl = rsa_pss_saltlen:auto
Input="0123456789ABCDEF0123"
Output = 6BF7EDC63A0BA184EEEC7F3020FEC8F5EBF38C2B76481881F48BCCE5796E7AB294548BA9AE810457C7723CABD1BDE94CF59CF7C0FC7461B22760C8ED703DD98E97BFDD61FA8D1181C411F6DEE5FF159F4850746D78EDEE385A363DC28E2CB373D5CAD7953F3BD5E639BE345732C03A1BDEA268814DA036EB1891C82D4012F3B903D86636055F87B96FC98806AD1B217685A4D754046A5DE0B0D7870664BE07902153EC85BA457BE7D7F89D7FE0F626D02A9CBBB2BB479DDA1A5CAE75247FB7BF6BFB15C1D3FD9E6B1573CCDBC72011C3B97716058BB11C7EA2E4E56ADAFE1F5DE6A7FD405AC5890100F9C3408EFFB5C73BF73F48177FF743B4B819D0699D507B
# Digest too short
Verify = RSA-2048-PUBLIC
Ctrl = rsa_padding_mode:pss
Ctrl = rsa_pss_saltlen:0
Ctrl = digest:sha256
Input="0123456789ABCDEF0123456789ABCDE"
Output=4DE433D5844043EF08D354DA03CB29068780D52706D7D1E4D50EFB7D58C9D547D83A747DDD0635A96B28F854E50145518482CB49E963054621B53C60C498D07C16E9C2789C893CF38D4D86900DE71BDE463BD2761D1271E358C7480A1AC0BAB930DDF39602AD1BC165B5D7436B516B7A7858E8EB7AB1C420EEB482F4D207F0E462B1724959320A084E13848D11D10FB593E66BF680BF6D3F345FC3E9C3DE60ABBAC37E1C6EC80A268C8D9FC49626C679097AA690BC1AA662B95EB8DB70390861AA0898229F9349B4B5FDD030D4928C47084708A933144BE23BD3C6E661B85B2C0EF9ED36D498D5B7320E8194D363D4AD478C059BAE804181965E0B81B663158A
Result = VERIFY_ERROR
# Digest too long
Verify = RSA-2048-PUBLIC
Ctrl = rsa_padding_mode:pss
Ctrl = rsa_pss_saltlen:0
Ctrl = digest:sha256
Input="0123456789ABCDEF0123456789ABCDEF0"
Output=4DE433D5844043EF08D354DA03CB29068780D52706D7D1E4D50EFB7D58C9D547D83A747DDD0635A96B28F854E50145518482CB49E963054621B53C60C498D07C16E9C2789C893CF38D4D86900DE71BDE463BD2761D1271E358C7480A1AC0BAB930DDF39602AD1BC165B5D7436B516B7A7858E8EB7AB1C420EEB482F4D207F0E462B1724959320A084E13848D11D10FB593E66BF680BF6D3F345FC3E9C3DE60ABBAC37E1C6EC80A268C8D9FC49626C679097AA690BC1AA662B95EB8DB70390861AA0898229F9349B4B5FDD030D4928C47084708A933144BE23BD3C6E661B85B2C0EF9ED36D498D5B7320E8194D363D4AD478C059BAE804181965E0B81B663158A
Result = VERIFY_ERROR
# Wrong salt length
Verify = RSA-2048
Ctrl = rsa_padding_mode:pss
Ctrl = rsa_pss_saltlen:2
Ctrl = digest:sha256
Input="0123456789ABCDEF0123456789ABCDEF"
Output=4DE433D5844043EF08D354DA03CB29068780D52706D7D1E4D50EFB7D58C9D547D83A747DDD0635A96B28F854E50145518482CB49E963054621B53C60C498D07C16E9C2789C893CF38D4D86900DE71BDE463BD2761D1271E358C7480A1AC0BAB930DDF39602AD1BC165B5D7436B516B7A7858E8EB7AB1C420EEB482F4D207F0E462B1724959320A084E13848D11D10FB593E66BF680BF6D3F345FC3E9C3DE60ABBAC37E1C6EC80A268C8D9FC49626C679097AA690BC1AA662B95EB8DB70390861AA0898229F9349B4B5FDD030D4928C47084708A933144BE23BD3C6E661B85B2C0EF9ED36D498D5B7320E8194D363D4AD478C059BAE804181965E0B81B663158A
Result = VERIFY_ERROR
# Verify using default parameters, explicitly setting parameters
Verify = RSA-PSS-DEFAULT
Ctrl = rsa_padding_mode:pss
Ctrl = rsa_pss_saltlen:20
Ctrl = digest:sha1
Input="0123456789ABCDEF0123"
Output = 3EFE09D88509027D837BFA5F8471CF7B69E6DF395DD999BB9CA42021F15722D9AC76670507C6BCFB73F64FB2211B611B8F140E76EBDB064BD762FDBA89D019E304A0D6B274E1C2FE1DF50005598A0306AF805416094E2A5BA60BC72BDE38CE061E853ED40F14967A8B9CA4DC739B462F89558F12FDF2D8D19FBEF16AD66FE2DDDA8BEE983ECBD873064244849D8D94B5B33F45E076871A47ED653E73257A2BE2DB3C0878094B0D2B6B682C8007DFD989425FB39A1FEEC9EED5876414601A49176EC344F5E3EDEE81CA2DDD29B7364F4638112CB3A547E2BC170E28CB66BDABE863754BE8AD5BA230567B575266F4B6B4CF81F28310ABF05351CC9E2DB85D00BF
# Verify explicitly setting parameters "digest" salt length
Verify = RSA-PSS-DEFAULT
Ctrl = rsa_padding_mode:pss
Ctrl = rsa_pss_saltlen:digest
Ctrl = digest:sha1
Input="0123456789ABCDEF0123"
Output = 3EFE09D88509027D837BFA5F8471CF7B69E6DF395DD999BB9CA42021F15722D9AC76670507C6BCFB73F64FB2211B611B8F140E76EBDB064BD762FDBA89D019E304A0D6B274E1C2FE1DF50005598A0306AF805416094E2A5BA60BC72BDE38CE061E853ED40F14967A8B9CA4DC739B462F89558F12FDF2D8D19FBEF16AD66FE2DDDA8BEE983ECBD873064244849D8D94B5B33F45E076871A47ED653E73257A2BE2DB3C0878094B0D2B6B682C8007DFD989425FB39A1FEEC9EED5876414601A49176EC344F5E3EDEE81CA2DDD29B7364F4638112CB3A547E2BC170E28CB66BDABE863754BE8AD5BA230567B575266F4B6B4CF81F28310ABF05351CC9E2DB85D00BF
# Verify using salt length larger than minimum
Verify = RSA-PSS-DEFAULT
Ctrl = rsa_pss_saltlen:30
Input="0123456789ABCDEF0123"
Output = 6BF7EDC63A0BA184EEEC7F3020FEC8F5EBF38C2B76481881F48BCCE5796E7AB294548BA9AE810457C7723CABD1BDE94CF59CF7C0FC7461B22760C8ED703DD98E97BFDD61FA8D1181C411F6DEE5FF159F4850746D78EDEE385A363DC28E2CB373D5CAD7953F3BD5E639BE345732C03A1BDEA268814DA036EB1891C82D4012F3B903D86636055F87B96FC98806AD1B217685A4D754046A5DE0B0D7870664BE07902153EC85BA457BE7D7F89D7FE0F626D02A9CBBB2BB479DDA1A5CAE75247FB7BF6BFB15C1D3FD9E6B1573CCDBC72011C3B97716058BB11C7EA2E4E56ADAFE1F5DE6A7FD405AC5890100F9C3408EFFB5C73BF73F48177FF743B4B819D0699D507B
# Verify using maximum salt length
Verify = RSA-PSS-DEFAULT
Ctrl = rsa_pss_saltlen:max
Input="0123456789ABCDEF0123"
Output = 4470DCFE812DEE2E58E4301D4ED274AB348FE040B724B2CD1D8CD0914BFF375F0B86FCB32BFA8AEA9BD22BD7C4F1ADD4F3D215A5CFCC99055BAFECFC23800E9BECE19A08C66BEBC5802122D13A732E5958FC228DCC0B49B5B4B1154F032D8FA2F3564AA949C1310CC9266B0C47F86D449AC9D2E7678347E7266E2D7C888CCE1ADF44A109A293F8516AE2BD94CE220F26E137DB8E7A66BB9FCE052CDC1D0BE24D8CEBB20D10125F26B069F117044B9E1D16FDDAABCA5340AE1702F37D0E1C08A2E93801C0A41035C6C73DA02A0E32227EAFB0B85E79107B59650D0EE7DC32A6772CCCE90F06369B2880FE87ED76997BA61F5EA818091EE88F8B0D6F24D02A3FC6
# Attempt to change salt length below minimum
Verify = RSA-PSS-DEFAULT
Ctrl = rsa_pss_saltlen:0
Result = PKEY_CTRL_ERROR
# Attempt to change padding mode
# Note this used to return PKEY_CTRL_INVALID
# but it is limited because setparams only returns 0 or 1.
Verify = RSA-PSS-DEFAULT
Ctrl = rsa_padding_mode:pkcs1
Result = PKEY_CTRL_ERROR
# Attempt to change digest
Verify = RSA-PSS-DEFAULT
Ctrl = digest:sha256
Result = PKEY_CTRL_ERROR
# Invalid key: rejected when we try to init
Verify = RSA-PSS-BAD
Result = KEYOP_INIT_ERROR
Reason = invalid salt length
# Invalid key: rejected when we try to init
Verify = RSA-PSS-BAD2
Result = KEYOP_INIT_ERROR
Reason = invalid salt length
# Additional RSA-PSS and RSA-OAEP tests converted from
# ftp://ftp.rsasecurity.com/pub/pkcs/pkcs-1/pkcs-1v2-1-vec.zip
Title = RSA PSS/OAEP (from RSASecurity FTP)
# 1024 bit key
PublicKey=RSA-PSS-1
-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQClbkoOcBAXWJpRh9x+qEHRVvLs
DjatUqRN/rHmH3rZkdjFEFb/7bFitMDyg6EqiKOU3/Umq3KRy7MHzqv84LHf1c2V
CAltWyuLbfXWce9jd8CSHLI8Jwpw4lmOb/idGfEFrMLT8Ms18pKA4Thrb2TE7yLh
4fINDOjP+yJJvZohNwIDAQAB
-----END PUBLIC KEY-----
Verify=RSA-PSS-1
Ctrl = rsa_padding_mode:pss
Ctrl = rsa_mgf1_md:sha1
Input=cd8b6538cb8e8de566b68bd067569dbf1ee2718e
Output=9074308fb598e9701b2294388e52f971faac2b60a5145af185df5287b5ed2887e57ce7fd44dc8634e407c8e0e4360bc226f3ec227f9d9e54638e8d31f5051215df6ebb9c2f9579aa77598a38f914b5b9c1bd83c4e2f9f382a0d0aa3542ffee65984a601bc69eb28deb27dca12c82c2d4c3f66cd500f1ff2b994d8a4e30cbb33c
Verify=RSA-PSS-1
Ctrl = rsa_padding_mode:pss
Ctrl = rsa_mgf1_md:sha1
Input=e35befc17a1d160b9ce35fbd8eb16e7ee491d3fd
Output=3ef7f46e831bf92b32274142a585ffcefbdca7b32ae90d10fb0f0c729984f04ef29a9df0780775ce43739b97838390db0a5505e63de927028d9d29b219ca2c4517832558a55d694a6d25b9dab66003c4cccd907802193be5170d26147d37b93590241be51c25055f47ef62752cfbe21418fafe98c22c4d4d47724fdb5669e843
Verify=RSA-PSS-1
Ctrl = rsa_padding_mode:pss
Ctrl = rsa_mgf1_md:sha1
Input=0652ec67bcee30f9d2699122b91c19abdba89f91
Output=666026fba71bd3e7cf13157cc2c51a8e4aa684af9778f91849f34335d141c00154c4197621f9624a675b5abc22ee7d5baaffaae1c9baca2cc373b3f33e78e6143c395a91aa7faca664eb733afd14d8827259d99a7550faca501ef2b04e33c23aa51f4b9e8282efdb728cc0ab09405a91607c6369961bc8270d2d4f39fce612b1
Verify=RSA-PSS-1
Ctrl = rsa_padding_mode:pss
Ctrl = rsa_mgf1_md:sha1
Input=39c21c4cceda9c1adf839c744e1212a6437575ec
Output=4609793b23e9d09362dc21bb47da0b4f3a7622649a47d464019b9aeafe53359c178c91cd58ba6bcb78be0346a7bc637f4b873d4bab38ee661f199634c547a1ad8442e03da015b136e543f7ab07c0c13e4225b8de8cce25d4f6eb8400f81f7e1833b7ee6e334d370964ca79fdb872b4d75223b5eeb08101591fb532d155a6de87
Verify=RSA-PSS-1
Ctrl = rsa_padding_mode:pss
Ctrl = rsa_mgf1_md:sha1
Input=36dae913b77bd17cae6e7b09453d24544cebb33c
Output=1d2aad221ca4d31ddf13509239019398e3d14b32dc34dc5af4aeaea3c095af73479cf0a45e5629635a53a018377615b16cb9b13b3e09d671eb71e387b8545c5960da5a64776e768e82b2c93583bf104c3fdb23512b7b4e89f633dd0063a530db4524b01c3f384c09310e315a79dcd3d684022a7f31c865a664e316978b759fad
Verify=RSA-PSS-1
Ctrl = rsa_padding_mode:pss
Ctrl = rsa_mgf1_md:sha1
Input=45eef191f4f79c31fe5d2ede7e5098994e929d2d
Output=2a34f6125e1f6b0bf971e84fbd41c632be8f2c2ace7de8b6926e31ff93e9af987fbc06e51e9be14f5198f91f3f953bd67da60a9df59764c3dc0fe08e1cbef0b75f868d10ad3fba749fef59fb6dac46a0d6e504369331586f58e4628f39aa278982543bc0eeb537dc61958019b394fb273f215858a0a01ac4d650b955c67f4c58
PublicKey=RSA-PSS-9
-----BEGIN PUBLIC KEY-----
MIHfMA0GCSqGSIb3DQEBAQUAA4HNADCByQKBwQDmvWkqyWZFeQQD/dD1vri5v5Lt
EAB/w2UEZBndBsBcW1svSOz5ieTOJpEJl5y7QLSgrSTSJIPR7jFa1MyxU0JoNSaR
xST23Y5sKdIkzyRpc67IbFv2sUAahQ0bmtG7jLzsR7BvD4x/RdP8jzGSmcVDPdvC
swU7R97S7NSkyu/WFIM9yLtiLzF+0Ha4BX/o3j+ESArV6D5KYZBKTySPs5cCc1fh
0w5GMTmBXG/U/VrFuBcqRSMOy2MYoE8UVdhOWosCAwEAAQ==
-----END PUBLIC KEY-----
Verify=RSA-PSS-9
Ctrl = rsa_padding_mode:pss
Ctrl = rsa_mgf1_md:sha1
Input=2715a49b8b0012cd7aee84c116446e6dfe3faec0
Output=586107226c3ce013a7c8f04d1a6a2959bb4b8e205ba43a27b50f124111bc35ef589b039f5932187cb696d7d9a32c0c38300a5cdda4834b62d2eb240af33f79d13dfbf095bf599e0d9686948c1964747b67e89c9aba5cd85016236f566cc5802cb13ead51bc7ca6bef3b94dcbdbb1d570469771df0e00b1a8a06777472d2316279edae86474668d4e1efff95f1de61c6020da32ae92bbf16520fef3cf4d88f61121f24bbd9fe91b59caf1235b2a93ff81fc403addf4ebdea84934a9cdaf8e1a9e
Verify=RSA-PSS-9
Ctrl = rsa_padding_mode:pss
Ctrl = rsa_mgf1_md:sha1
Input=2dac956d53964748ac364d06595827c6b4f143cd
Output=80b6d643255209f0a456763897ac9ed259d459b49c2887e5882ecb4434cfd66dd7e1699375381e51cd7f554f2c271704b399d42b4be2540a0eca61951f55267f7c2878c122842dadb28b01bd5f8c025f7e228418a673c03d6bc0c736d0a29546bd67f786d9d692ccea778d71d98c2063b7a71092187a4d35af108111d83e83eae46c46aa34277e06044589903788f1d5e7cee25fb485e92949118814d6f2c3ee361489016f327fb5bc517eb50470bffa1afa5f4ce9aa0ce5b8ee19bf5501b958
Verify=RSA-PSS-9
Ctrl = rsa_padding_mode:pss
Ctrl = rsa_mgf1_md:sha1
Input=28d98c46cccafbd3bc04e72f967a54bd3ea12298
Output=484408f3898cd5f53483f80819efbf2708c34d27a8b2a6fae8b322f9240237f981817aca1846f1084daa6d7c0795f6e5bf1af59c38e1858437ce1f7ec419b98c8736adf6dd9a00b1806d2bd3ad0a73775e05f52dfef3a59ab4b08143f0df05cd1ad9d04bececa6daa4a2129803e200cbc77787caf4c1d0663a6c5987b605952019782caf2ec1426d68fb94ed1d4be816a7ed081b77e6ab330b3ffc073820fecde3727fcbe295ee61a050a343658637c3fd659cfb63736de32d9f90d3c2f63eca
Verify=RSA-PSS-9
Ctrl = rsa_padding_mode:pss
Ctrl = rsa_mgf1_md:sha1
Input=0866d2ff5a79f25ef668cd6f31b42dee421e4c0e
Output=84ebeb481be59845b46468bafb471c0112e02b235d84b5d911cbd1926ee5074ae0424495cb20e82308b8ebb65f419a03fb40e72b78981d88aad143053685172c97b29c8b7bf0ae73b5b2263c403da0ed2f80ff7450af7828eb8b86f0028bd2a8b176a4d228cccea18394f238b09ff758cc00bc04301152355742f282b54e663a919e709d8da24ade5500a7b9aa50226e0ca52923e6c2d860ec50ff480fa57477e82b0565f4379f79c772d5c2da80af9fbf325ece6fc20b00961614bee89a183e
Verify=RSA-PSS-9
Ctrl = rsa_padding_mode:pss
Ctrl = rsa_mgf1_md:sha1
Input=6a5b4be4cd36cc97dfde9995efbf8f097a4a991a
Output=82102df8cb91e7179919a04d26d335d64fbc2f872c44833943241de8454810274cdf3db5f42d423db152af7135f701420e39b494a67cbfd19f9119da233a23da5c6439b5ba0d2bc373eee3507001378d4a4073856b7fe2aba0b5ee93b27f4afec7d4d120921c83f606765b02c19e4d6a1a3b95fa4c422951be4f52131077ef17179729cddfbdb56950dbaceefe78cb16640a099ea56d24389eef10f8fecb31ba3ea3b227c0a86698bb89e3e9363905bf22777b2a3aa521b65b4cef76d83bde4c
Verify=RSA-PSS-9
Ctrl = rsa_padding_mode:pss
Ctrl = rsa_mgf1_md:sha1
Input=b9dfd1df76a461c51e6576c6c8ed0a923d1c50e7
Output=a7fdb0d259165ca2c88d00bbf1028a867d337699d061193b17a9648e14ccbbaadeacaacdec815e7571294ebb8a117af205fa078b47b0712c199e3ad05135c504c24b81705115740802487992ffd511d4afc6b854491eb3f0dd523139542ff15c3101ee85543517c6a3c79417c67e2dd9aa741e9a29b06dcb593c2336b3670ae3afbac7c3e76e215473e866e338ca244de00b62624d6b9426822ceae9f8cc460895f41250073fd45c5a1e7b425c204a423a699159f6903e710b37a7bb2bc8049f
PublicKey=RSA-PSS-10
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEApd2GesTLAvkLlFfUjBSn
cO+ZHFbDnA7GX9Ea+ok3zqV7m+esc7RcABdhW4LWIuMYdTtgJ8D9FXvhL4CQ/uKn
rc0O73WfiLpJl8ekLVjJqhLLma4AH+UhwTu1QxRFqNWuT15MfpSKwifTYEBx8g5X
fpBfvrFd+vBtHeWuYlPWOmohILMaXaXavJVQYA4g8n03OeJieSX+o8xQnyHf8E5u
6kVJxUDWgJ/5MH7t6R//WHM9g4WiN9bTcFoz45GQCZIHDfet8TV89+NwDONmfeg/
F7jfF3jbOB3OCctK0FilEQAac4GY7ifPVaE7dUU5kGWC7IsXS9WNXR89dnxhNyGu
BQIDAQAB
-----END PUBLIC KEY-----
Verify=RSA-PSS-10
Ctrl = rsa_padding_mode:pss
Ctrl = rsa_mgf1_md:sha1
Input=9596bb630cf6a8d4ea4600422b9eba8b13675dd4
Output=82c2b160093b8aa3c0f7522b19f87354066c77847abf2a9fce542d0e84e920c5afb49ffdfdace16560ee94a1369601148ebad7a0e151cf16331791a5727d05f21e74e7eb811440206935d744765a15e79f015cb66c532c87a6a05961c8bfad741a9a6657022894393e7223739796c02a77455d0f555b0ec01ddf259b6207fd0fd57614cef1a5573baaff4ec00069951659b85f24300a25160ca8522dc6e6727e57d019d7e63629b8fe5e89e25cc15beb3a647577559299280b9b28f79b0409000be25bbd96408ba3b43cc486184dd1c8e62553fa1af4040f60663de7f5e49c04388e257f1ce89c95dab48a315d9b66b1b7628233876ff2385230d070d07e1666
Verify=RSA-PSS-10
Ctrl = rsa_padding_mode:pss
Ctrl = rsa_mgf1_md:sha1
Input=b503319399277fd6c1c8f1033cbf04199ea21716
Output=14ae35d9dd06ba92f7f3b897978aed7cd4bf5ff0b585a40bd46ce1b42cd2703053bb9044d64e813d8f96db2dd7007d10118f6f8f8496097ad75e1ff692341b2892ad55a633a1c55e7f0a0ad59a0e203a5b8278aec54dd8622e2831d87174f8caff43ee6c46445345d84a59659bfb92ecd4c818668695f34706f66828a89959637f2bf3e3251c24bdba4d4b7649da0022218b119c84e79a6527ec5b8a5f861c159952e23ec05e1e717346faefe8b1686825bd2b262fb2531066c0de09acde2e4231690728b5d85e115a2f6b92b79c25abc9bd9399ff8bcf825a52ea1f56ea76dd26f43baafa18bfa92a504cbd35699e26d1dcc5a2887385f3c63232f06f3244c3
Verify=RSA-PSS-10
Ctrl = rsa_padding_mode:pss
Ctrl = rsa_mgf1_md:sha1
Input=50aaede8536b2c307208b275a67ae2df196c7628
Output=6e3e4d7b6b15d2fb46013b8900aa5bbb3939cf2c095717987042026ee62c74c54cffd5d7d57efbbf950a0f5c574fa09d3fc1c9f513b05b4ff50dd8df7edfa20102854c35e592180119a70ce5b085182aa02d9ea2aa90d1df03f2daae885ba2f5d05afdac97476f06b93b5bc94a1a80aa9116c4d615f333b098892b25fface266f5db5a5a3bcc10a824ed55aad35b727834fb8c07da28fcf416a5d9b2224f1f8b442b36f91e456fdea2d7cfe3367268de0307a4c74e924159ed33393d5e0655531c77327b89821bdedf880161c78cd4196b5419f7acc3f13e5ebf161b6e7c6724716ca33b85c2e25640192ac2859651d50bde7eb976e51cec828b98b6563b86bb
Verify=RSA-PSS-10
Ctrl = rsa_padding_mode:pss
Ctrl = rsa_mgf1_md:sha1
Input=aa0b72b8b371ddd10c8ae474425ccccf8842a294
Output=34047ff96c4dc0dc90b2d4ff59a1a361a4754b255d2ee0af7d8bf87c9bc9e7ddeede33934c63ca1c0e3d262cb145ef932a1f2c0a997aa6a34f8eaee7477d82ccf09095a6b8acad38d4eec9fb7eab7ad02da1d11d8e54c1825e55bf58c2a23234b902be124f9e9038a8f68fa45dab72f66e0945bf1d8bacc9044c6f07098c9fcec58a3aab100c805178155f030a124c450e5acbda47d0e4f10b80a23f803e774d023b0015c20b9f9bbe7c91296338d5ecb471cafb032007b67a60be5f69504a9f01abb3cb467b260e2bce860be8d95bf92c0c8e1496ed1e528593a4abb6df462dde8a0968dffe4683116857a232f5ebf6c85be238745ad0f38f767a5fdbf486fb
Verify=RSA-PSS-10
Ctrl = rsa_padding_mode:pss
Ctrl = rsa_mgf1_md:sha1
Input=fad3902c9750622a2bc672622c48270cc57d3ea8
Output=7e0935ea18f4d6c1d17ce82eb2b3836c55b384589ce19dfe743363ac9948d1f346b7bfddfe92efd78adb21faefc89ade42b10f374003fe122e67429a1cb8cbd1f8d9014564c44d120116f4990f1a6e38774c194bd1b8213286b077b0499d2e7b3f434ab12289c556684deed78131934bb3dd6537236f7c6f3dcb09d476be07721e37e1ceed9b2f7b406887bd53157305e1c8b4f84d733bc1e186fe06cc59b6edb8f4bd7ffefdf4f7ba9cfb9d570689b5a1a4109a746a690893db3799255a0cb9215d2d1cd490590e952e8c8786aa0011265252470c041dfbc3eec7c3cbf71c24869d115c0cb4a956f56d530b80ab589acfefc690751ddf36e8d383f83cedd2cc
Verify=RSA-PSS-10
Ctrl = rsa_padding_mode:pss
Ctrl = rsa_mgf1_md:sha1
Input=122196deb5d122bd8c6fc781ff6924d7c695aade
Output=6d3b5b87f67ea657af21f75441977d2180f91b2c5f692de82955696a686730d9b9778d970758ccb26071c2209ffbd6125be2e96ea81b67cb9b9308239fda17f7b2b64ecda096b6b935640a5a1cb42a9155b1c9ef7a633a02c59f0d6ee59b852c43b35029e73c940ff0410e8f114eed46bbd0fae165e42be2528a401c3b28fd818ef3232dca9f4d2a0f5166ec59c42396d6c11dbc1215a56fa17169db9575343ef34f9de32a49cdc3174922f229c23e18e45df9353119ec4319cedce7a17c64088c1f6f52be29634100b3919d38f3d1ed94e6891e66a73b8fb849f5874df59459e298c7bbce2eee782a195aa66fe2d0732b25e595f57d3e061b1fc3e4063bf98f
PrivateKey=RSA-OAEP-1
-----BEGIN PRIVATE KEY-----
MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAKizsoSvjrULOHA0
qGDxRsSRnzGHY81sVZjIrkgRoeCrxMfgsILWk6Xn/O1nXPRmhRJ3LAy8ZKdCxsYw
9TPIzHL2KugzxAvyWELphLt4vb+XwBB9Vb22YvXE4Pq5hFy1FI73OS3Tqv+Trh5r
Znuz1CR2FtT1uhDUz9Im3ojTnxb7AgMBAAECgYBTM5z9t5/IRmplXHMWrKhcVf2P
bdiY/a8RlRfvT1Lo/Y4ljfk/7hgPoOSrKWk82DsVKlU9SsTRgSuLn6WvDn9V/nME
30FXCSbzMR8VxNZacyxIMRbuPT0tCvNUmtm/fL+3itiE+E1b6wRyTcc2mzHe830M
9Tnpz83T3mU3KerV0QJBANMnN+cmf/4TQbLVwNFQqBtYb7MTK+0vjVJihkqcufMK
84vkSFmNQToXLvuALCGs8cEcUgwvJqRx3K0hLqx8o50CQQDMiFPR1U2mMPrABPRx
8oHHuJgtgiSkkO2+sz0+PVzJPEdlcD0d15FkLx8Rag3YUr4kGbKvcr/poDDoYLAo
i113AkAOEr8XGOnO9VmbocOIL+gEapCHTu/OjyzMIOTydB+wozo4SK7JyTBfvsvS
12gZln1GcazGQx5AN5aNs3h45pXBAkEAlSl7D5Wi+mfQBwfWCd/U/AXIna/C721u
pVvsdx6jM3NNklHnkILs2oZu/vE8RZ4aYxOGt+NUyJn18RLKhdcVgwJAT0VsUCST
vcDtKrdWo6btTWc1Kml9QhbpMhKxJ6Y9VBHOb6mNXb79cyY+NygUJ0OBgWbtfdY2
h90qjKHS9PvY4Q==
-----END PRIVATE KEY-----
Decrypt=RSA-OAEP-1
Ctrl = rsa_padding_mode:oaep
Ctrl = rsa_mgf1_md:sha1
Input=354fe67b4a126d5d35fe36c777791a3f7ba13def484e2d3908aff722fad468fb21696de95d0be911c2d3174f8afcc201035f7b6d8e69402de5451618c21a535fa9d7bfc5b8dd9fc243f8cf927db31322d6e881eaa91a996170e657a05a266426d98c88003f8477c1227094a0d9fa1e8c4024309ce1ecccb5210035d47ac72e8a
Output=6628194e12073db03ba94cda9ef9532397d50dba79b987004afefe34
Decrypt=RSA-OAEP-1
Ctrl = rsa_padding_mode:oaep
Ctrl = rsa_mgf1_md:sha1
Input=640db1acc58e0568fe5407e5f9b701dff8c3c91e716c536fc7fcec6cb5b71c1165988d4a279e1577d730fc7a29932e3f00c81515236d8d8e31017a7a09df4352d904cdeb79aa583adcc31ea698a4c05283daba9089be5491f67c1a4ee48dc74bbbe6643aef846679b4cb395a352d5ed115912df696ffe0702932946d71492b44
Output=750c4047f547e8e41411856523298ac9bae245efaf1397fbe56f9dd5
Decrypt=RSA-OAEP-1
Ctrl = rsa_padding_mode:oaep
Ctrl = rsa_mgf1_md:sha1
Input=423736ed035f6026af276c35c0b3741b365e5f76ca091b4e8c29e2f0befee603595aa8322d602d2e625e95eb81b2f1c9724e822eca76db8618cf09c5343503a4360835b5903bc637e3879fb05e0ef32685d5aec5067cd7cc96fe4b2670b6eac3066b1fcf5686b68589aafb7d629b02d8f8625ca3833624d4800fb081b1cf94eb
Output=d94ae0832e6445ce42331cb06d531a82b1db4baad30f746dc916df24d4e3c2451fff59a6423eb0e1d02d4fe646cf699dfd818c6e97b051
Decrypt=RSA-OAEP-1
Ctrl = rsa_padding_mode:oaep
Ctrl = rsa_mgf1_md:sha1
Input=45ead4ca551e662c9800f1aca8283b0525e6abae30be4b4aba762fa40fd3d38e22abefc69794f6ebbbc05ddbb11216247d2f412fd0fba87c6e3acd888813646fd0e48e785204f9c3f73d6d8239562722dddd8771fec48b83a31ee6f592c4cfd4bc88174f3b13a112aae3b9f7b80e0fc6f7255ba880dc7d8021e22ad6a85f0755
Output=52e650d98e7f2a048b4f86852153b97e01dd316f346a19f67a85
Decrypt=RSA-OAEP-1
Ctrl = rsa_padding_mode:oaep
Ctrl = rsa_mgf1_md:sha1
Input=36f6e34d94a8d34daacba33a2139d00ad85a9345a86051e73071620056b920e219005855a213a0f23897cdcd731b45257c777fe908202befdd0b58386b1244ea0cf539a05d5d10329da44e13030fd760dcd644cfef2094d1910d3f433e1c7c6dd18bc1f2df7f643d662fb9dd37ead9059190f4fa66ca39e869c4eb449cbdc439
Output=8da89fd9e5f974a29feffb462b49180f6cf9e802
Decrypt=RSA-OAEP-1
Ctrl = rsa_padding_mode:oaep
Ctrl = rsa_mgf1_md:sha1
Input=42cee2617b1ecea4db3f4829386fbd61dafbf038e180d837c96366df24c097b4ab0fac6bdf590d821c9f10642e681ad05b8d78b378c0f46ce2fad63f74e0ad3df06b075d7eb5f5636f8d403b9059ca761b5c62bb52aa45002ea70baace08ded243b9d8cbd62a68ade265832b56564e43a6fa42ed199a099769742df1539e8255
Output=26521050844271
PrivateKey=RSA-OAEP-2
-----BEGIN PRIVATE KEY-----
MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAZR8f86QQl9HJ55w
hR8l1eYjFv6KHfGTcePmKOJgVD5JAe9ggfaMC4FBGQ0q6Nq6fRJQ7G22NulE7Dci
h3x8HQpn8UsWlMXwN5RRpD5Joy3eg2cLc9qRocmbwjtDamAFXGEPC6+ZwaB5VluV
o/FSZjLR1Npg8g7aJeZTxPACdm9FAgMBAAECgYAII/IPrbXaiQiKnQCJPiH6ShsR
+8k8ZKO+C6rql/s7k8P/cTcEwZyWPB0Qeq6ZBUc5954C4Ybehvh6bd7+ptjM0dPI
Gke/pyVb4gYBpKSy8IoWe14nnXFbG0Vb3X6rJFlB2XaLms77PM2llS2jzuclJbRQ
FmOo7hXJ6ZLZJGL+OQJBAVnb3gSjPvBvtgi4CxkPTT4ivME6yOSggQM6v6QW7bCz
OKoItXMJ6lpSQOfcblQ3jGlBTDHZfdsfQG2zdpzEGkMCQQErZS8wQDs4tAmV/W/0
GhrMitpwNzI2tyAtObLuMM+0bbCVEfbzB8xhzCFgbBinW4pi+CLfAxug3w2v1VBv
VovXAkBDbvUI3nNlGcLaTFgNmMgst0UqP7XvrcO5x3iaG8ZYT3la3bvTJDnHRoZV
LstsLDB6TTr39TnuwVckjHsx8aJVAkEBKxWonz37KzkHPnPwK90MGns3ndQ18Fzd
4u/55GKUi3zsYu6QUNXggW4HhahWtJEI3LdfNoOHTRymMpoZATBm/wJAAnDbF9WR
SwGNdhGLJDiac1Dsg2sAY6IXISNv2O222JtR5+64e2EbcTLLfqc1bCMVHB53UVB8
eG2e4XlBcKjI6A==
-----END PRIVATE KEY-----
Decrypt=RSA-OAEP-2
Ctrl = rsa_padding_mode:oaep
Ctrl = rsa_mgf1_md:sha1
Input=0181af8922b9fcb4d79d92ebe19815992fc0c1439d8bcd491398a0f4ad3a329a5bd9385560db532683c8b7da04e4b12aed6aacdf471c34c9cda891addcc2df3456653aa6382e9ae59b54455257eb099d562bbe10453f2b6d13c59c02e10f1f8abb5da0d0570932dacf2d0901db729d0fefcc054e70968ea540c81b04bcaefe720e
Output=8ff00caa605c702830634d9a6c3d42c652b58cf1d92fec570beee7
Decrypt=RSA-OAEP-2
Ctrl = rsa_padding_mode:oaep
Ctrl = rsa_mgf1_md:sha1
Input=018759ff1df63b2792410562314416a8aeaf2ac634b46f940ab82d64dbf165eee33011da749d4bab6e2fcd18129c9e49277d8453112b429a222a8471b070993998e758861c4d3f6d749d91c4290d332c7a4ab3f7ea35ff3a07d497c955ff0ffc95006b62c6d296810d9bfab024196c7934012c2df978ef299aba239940cba10245
Output=2d
Decrypt=RSA-OAEP-2
Ctrl = rsa_padding_mode:oaep
Ctrl = rsa_mgf1_md:sha1
Input=018802bab04c60325e81c4962311f2be7c2adce93041a00719c88f957575f2c79f1b7bc8ced115c706b311c08a2d986ca3b6a9336b147c29c6f229409ddec651bd1fdd5a0b7f610c9937fdb4a3a762364b8b3206b4ea485fd098d08f63d4aa8bb2697d027b750c32d7f74eaf5180d2e9b66b17cb2fa55523bc280da10d14be2053
Output=74fc88c51bc90f77af9d5e9a4a70133d4b4e0b34da3c37c7ef8e
Decrypt=RSA-OAEP-2
Ctrl = rsa_padding_mode:oaep
Ctrl = rsa_mgf1_md:sha1
Input=00a4578cbc176318a638fba7d01df15746af44d4f6cd96d7e7c495cbf425b09c649d32bf886da48fbaf989a2117187cafb1fb580317690e3ccd446920b7af82b31db5804d87d01514acbfa9156e782f867f6bed9449e0e9a2c09bcecc6aa087636965e34b3ec766f2fe2e43018a2fddeb140616a0e9d82e5331024ee0652fc7641
Output=a7eb2a5036931d27d4e891326d99692ffadda9bf7efd3e34e622c4adc085f721dfe885072c78a203b151739be540fa8c153a10f00a
Decrypt=RSA-OAEP-2
Ctrl = rsa_padding_mode:oaep
Ctrl = rsa_mgf1_md:sha1
Input=00ebc5f5fda77cfdad3c83641a9025e77d72d8a6fb33a810f5950f8d74c73e8d931e8634d86ab1246256ae07b6005b71b7f2fb98351218331ce69b8ffbdc9da08bbc9c704f876deb9df9fc2ec065cad87f9090b07acc17aa7f997b27aca48806e897f771d95141fe4526d8a5301b678627efab707fd40fbebd6e792a25613e7aec
Output=2ef2b066f854c33f3bdcbb5994a435e73d6c6c
Decrypt=RSA-OAEP-2
Ctrl = rsa_padding_mode:oaep
Ctrl = rsa_mgf1_md:sha1
Input=010839ec20c27b9052e55befb9b77e6fc26e9075d7a54378c646abdf51e445bd5715de81789f56f1803d9170764a9e93cb78798694023ee7393ce04bc5d8f8c5a52c171d43837e3aca62f609eb0aa5ffb0960ef04198dd754f57f7fbe6abf765cf118b4ca443b23b5aab266f952326ac4581100644325f8b721acd5d04ff14ef3a
Output=8a7fb344c8b6cb2cf2ef1f643f9a3218f6e19bba89c0
PrivateKey=RSA-OAEP-3
-----BEGIN PRIVATE KEY-----
MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBArWP7AOahgcApNe2
Ri+T5s3UkRYd3XT06BC0DjwWUgBqXCd7J3TBEwWky6taeO+lfheobfej+jb8Sx0i
SfIux8LdakYyMqzOqQbWbr6AtXBLEHKdpvgzI0q7Xv3UopLL+tM7TTP6ehS4w5e1
bjrNISA0KLd836M6bacGs9iw/EPpAgMBAAECgYAVtIpbVoOpRnDiO1cY+BT6DhP4
UDj1BxEYLLphUQWB89IsfiMu+TfiLlUdaLhuL4yxqti+LkiPXffv0nnj9WjU6vNv
gM9xQazmD8yRE/tsSoQf1Qu8fFEv/L7/IUh6qBHrPKjGIAU0aobehr+h2KlI/T80
jCLqrfMzw85s4TII/QJBAb8B0hbXNZXPAnDCvreNQKDYRH0x2pGamD9+6ngbd9hf
43Gz6Tc+e2khfTFQoC2JWN5/rZ1VUWCVi0RUEn4Ofq8CQQGNM5llgWbbOCmBbXsp
VBZ1npyRmH9bLYrs1jsEtIvXsvzyKbt/im3Ii6E90uOa1VttGgYWBwj5cAvoC4/T
dEznAkAGwKJJ0gpvLudciLSU1T9qrpmqQnyIwosWOnaUReXzkM9AwnT9bqYymlzn
x84DohWDlu4qeEV4bgniiFqXKOTlAkEA0dJ8Kf7dkthsNI7dDMv6wU90bgUc4dGB
HfNdYfLuHJfUvygEgC9kJxh7qOkKivRCQ7QHmwNEXmAuKfpRk+ZP6QJBAIyy91a9
iUGx07dw5a0x7jc7KKzaaf+bb0D+V4ufGvuFg2+WJ9N6z/c8J3nmNLsmARwsj38z
Ya4qnqZe1onjY5o=
-----END PRIVATE KEY-----
Decrypt=RSA-OAEP-3
Ctrl = rsa_padding_mode:oaep
Ctrl = rsa_mgf1_md:sha1
Input=026a0485d96aebd96b4382085099b962e6a2bdec3d90c8db625e14372de85e2d5b7baab65c8faf91bb5504fb495afce5c988b3f6a52e20e1d6cbd3566c5cd1f2b8318bb542cc0ea25c4aab9932afa20760eaddec784396a07ea0ef24d4e6f4d37e5052a7a31e146aa480a111bbe926401307e00f410033842b6d82fe5ce4dfae80
Output=087820b569e8fa8d
Decrypt=RSA-OAEP-3
Ctrl = rsa_padding_mode:oaep
Ctrl = rsa_mgf1_md:sha1
Input=024db89c7802989be0783847863084941bf209d761987e38f97cb5f6f1bc88da72a50b73ebaf11c879c4f95df37b850b8f65d7622e25b1b889e80fe80baca2069d6e0e1d829953fc459069de98ea9798b451e557e99abf8fe3d9ccf9096ebbf3e5255d3b4e1c6d2ecadf067a359eea86405acd47d5e165517ccafd47d6dbee4bf5
Output=4653acaf171960b01f52a7be63a3ab21dc368ec43b50d82ec3781e04
Decrypt=RSA-OAEP-3
Ctrl = rsa_padding_mode:oaep
Ctrl = rsa_mgf1_md:sha1
Input=0239bce681032441528877d6d1c8bb28aa3bc97f1df584563618995797683844ca86664732f4bed7a0aab083aaabfb7238f582e30958c2024e44e57043b97950fd543da977c90cdde5337d618442f99e60d7783ab59ce6dd9d69c47ad1e962bec22d05895cff8d3f64ed5261d92b2678510393484990ba3f7f06818ae6ffce8a3a
Output=d94cd0e08fa404ed89
Decrypt=RSA-OAEP-3
Ctrl = rsa_padding_mode:oaep
Ctrl = rsa_mgf1_md:sha1
Input=02994c62afd76f498ba1fd2cf642857fca81f4373cb08f1cbaee6f025c3b512b42c3e8779113476648039dbe0493f9246292fac28950600e7c0f32edf9c81b9dec45c3bde0cc8d8847590169907b7dc5991ceb29bb0714d613d96df0f12ec5d8d3507c8ee7ae78dd83f216fa61de100363aca48a7e914ae9f42ddfbe943b09d9a0
Output=6cc641b6b61e6f963974dad23a9013284ef1
Decrypt=RSA-OAEP-3
Ctrl = rsa_padding_mode:oaep
Ctrl = rsa_mgf1_md:sha1
Input=0162042ff6969592a6167031811a239834ce638abf54fec8b99478122afe2ee67f8c5b18b0339805bfdbc5a4e6720b37c59cfba942464c597ff532a119821545fd2e59b114e61daf71820529f5029cf524954327c34ec5e6f5ba7efcc4de943ab8ad4ed787b1454329f70db798a3a8f4d92f8274e2b2948ade627ce8ee33e43c60
Output=df5151832b61f4f25891fb4172f328d2eddf8371ffcfdbe997939295f30eca6918017cfda1153bf7a6af87593223
Decrypt=RSA-OAEP-3
Ctrl = rsa_padding_mode:oaep
Ctrl = rsa_mgf1_md:sha1
Input=00112051e75d064943bc4478075e43482fd59cee0679de6893eec3a943daa490b9691c93dfc0464b6623b9f3dbd3e70083264f034b374f74164e1a00763725e574744ba0b9db83434f31df96f6e2a26f6d8eba348bd4686c2238ac07c37aac3785d1c7eea2f819fd91491798ed8e9cef5e43b781b0e0276e37c43ff9492d005730
Output=3c3bad893c544a6d520ab022319188c8d504b7a788b850903b85972eaa18552e1134a7ad6098826254ff7ab672b3d8eb3158fac6d4cbaef1
PrivateKey=RSA-OAEP-4
-----BEGIN PRIVATE KEY-----
MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBBRJAtswABPpI0BNG
ccB4x8jew7Pi8lvCVkRnM52ziFPQa4XupbLeNTv/QqwuRryX+uaslhjalTelyPVT
weNXYlmR1hCNzXiF+zolQT9T78rZSMs1zZua6cHGdibRE9V93kxb6na7W7felsAN
BzculoWm11z50jn6FI1wkxtfP7A5AgMBAAECgYAEEf/KO3yl6em+f+OKhRBeNTiW
2wXFeWrs0qclFh6zZRyGKam4YrkE17DHs3+MtaHCtUABAYoAoessr+TuTpSSw0i8
K+2rS5678GTo7/MiuQCfjuxlOQX0DfiKPNxJ1FZ/dWJ9QaymJBKbRqC3xpjl5l8r
e6ECx0mhATW2VA0EAQJBAnRYwZ7BY2kZ5zbJryXWCaUbj1YdGca/aUPdHuGriko/
IyEAvUC4jezGuiNVSLbveSoRyd6CPQp5IscJW266VwECQQIQ7pszq2FxbifSUb1G
X0s1oaIy4toAkBwpS/IjUM5JDQmfZCtTdWEttjuh8gOGSSvwTTSzwivOuQnRNEG1
O1E5AkA5+gKLgm6IwRIbdQqLJC+po1xbZr39H6Y308xIqEpPRXoZTncn5J97zG5a
WkEmV/xHDHMi68N0Fu9FjDB6jAkBAkEBXZmoQZWUOXn6nhviw8G2n0MvRv0D5H1b
77u/1rHRNx2D77Mwo+AglCsv7RFeXQK+JP2SyQGdHOzW3Uzx5UzImQJBAfC3AVFw
s/XkIiO6MDAcQabYfLtw4wy308Z9JUc9sfbL8D4/kSbj6XloJ5qGWywrQmUkz8Uq
aD0x7TDrmEvkEro=
-----END PRIVATE KEY-----
Decrypt=RSA-OAEP-4
Ctrl = rsa_padding_mode:oaep
Ctrl = rsa_mgf1_md:sha1
Input=04cce19614845e094152a3fe18e54e3330c44e5efbc64ae16886cb1869014cc5781b1f8f9e045384d0112a135ca0d12e9c88a8e4063416deaae3844f60d6e96fe155145f4525b9a34431ca3766180f70e15a5e5d8e8b1a516ff870609f13f896935ced188279a58ed13d07114277d75c6568607e0ab092fd803a223e4a8ee0b1a8
Output=4a86609534ee434a6cbca3f7e962e76d455e3264c19f605f6e5ff6137c65c56d7fb344cd52bc93374f3d166c9f0c6f9c506bad19330972d2
Decrypt=RSA-OAEP-4
Ctrl = rsa_padding_mode:oaep
Ctrl = rsa_mgf1_md:sha1
Input=0097b698c6165645b303486fbf5a2a4479c0ee85889b541a6f0b858d6b6597b13b854eb4f839af03399a80d79bda6578c841f90d645715b280d37143992dd186c80b949b775cae97370e4ec97443136c6da484e970ffdb1323a20847821d3b18381de13bb49aaea66530c4a4b8271f3eae172cd366e07e6636f1019d2a28aed15e
Output=b0adc4f3fe11da59ce992773d9059943c03046497ee9d9f9a06df1166db46d98f58d27ec074c02eee6cbe2449c8b9fc5080c5c3f4433092512ec46aa793743c8
Decrypt=RSA-OAEP-4
Ctrl = rsa_padding_mode:oaep
Ctrl = rsa_mgf1_md:sha1
Input=0301f935e9c47abcb48acbbe09895d9f5971af14839da4ff95417ee453d1fd77319072bb7297e1b55d7561cd9d1bb24c1a9a37c619864308242804879d86ebd001dce5183975e1506989b70e5a83434154d5cbfd6a24787e60eb0c658d2ac193302d1192c6e622d4a12ad4b53923bca246df31c6395e37702c6a78ae081fb9d065
Output=bf6d42e701707b1d0206b0c8b45a1c72641ff12889219a82bdea965b5e79a96b0d0163ed9d578ec9ada20f2fbcf1ea3c4089d83419ba81b0c60f3606da99
Decrypt=RSA-OAEP-4
Ctrl = rsa_padding_mode:oaep
Ctrl = rsa_mgf1_md:sha1
Input=02d110ad30afb727beb691dd0cf17d0af1a1e7fa0cc040ec1a4ba26a42c59d0a796a2e22c8f357ccc98b6519aceb682e945e62cb734614a529407cd452bee3e44fece8423cc19e55548b8b994b849c7ecde4933e76037e1d0ce44275b08710c68e430130b929730ed77e09b015642c5593f04e4ffb9410798102a8e96ffdfe11e4
Output=fb2ef112f5e766eb94019297934794f7be2f6fc1c58e
Decrypt=RSA-OAEP-4
Ctrl = rsa_padding_mode:oaep
Ctrl = rsa_mgf1_md:sha1
Input=00dbb8a7439d90efd919a377c54fae8fe11ec58c3b858362e23ad1b8a44310799066b99347aa525691d2adc58d9b06e34f288c170390c5f0e11c0aa3645959f18ee79e8f2be8d7ac5c23d061f18dd74b8c5f2a58fcb5eb0c54f99f01a83247568292536583340948d7a8c97c4acd1e98d1e29dc320e97a260532a8aa7a758a1ec2
Output=28ccd447bb9e85166dabb9e5b7d1adadc4b9d39f204e96d5e440ce9ad928bc1c2284
Decrypt=RSA-OAEP-4
Ctrl = rsa_padding_mode:oaep
Ctrl = rsa_mgf1_md:sha1
Input=00a5ffa4768c8bbecaee2db77e8f2eec99595933545520835e5ba7db9493d3e17cddefe6a5f567624471908db4e2d83a0fbee60608fc84049503b2234a07dc83b27b22847ad8920ff42f674ef79b76280b00233d2b51b8cb2703a9d42bfbc8250c96ec32c051e57f1b4ba528db89c37e4c54e27e6e64ac69635ae887d9541619a9
Output=f22242751ec6b1
PrivateKey=RSA-OAEP-5
-----BEGIN PRIVATE KEY-----
MIICeQIBADANBgkqhkiG9w0BAQEFAASCAmMwggJfAgEAAoGBCq3z+cEl5diR8xrE
SOmT3v5YD4ArRfnX8iulAh6cR1drWh5oAxup205tq+TZah1vPSZyaM/0CABfEY78
rbmYiNHCNEZxZrKiuEmgWoicBgrA2gxfrotV8wm6YucDdC+gMm8tELARAhSJ/0l3
cBkNiV/Tn1IpPDnv1zppi9q58Q7ZAgMBAAECgYECVutMunBn8tK+VA3N/0WCo2t9
MdHJCZuyFLeYSEZqJo+A9YpJrATA42SJNKAgbARTfBmyNmQ6YIJzIUTfdfohdYj3
lGgr6JFoJ23HJsXAy9uE0xu/JtCkOvSVcX99UorP7jQVYfb/PK4FxXj4Rw2WgvnA
0HL59gaLVtWID2gr4sUCQQOw05YvbRdUnL/KESlDSNzw5+OfjCvGgk8hZLYG1oeG
Da4eYyOTz+31EyKCKQaeL2DkrNfmM6Q2Bj+COF9ImTcHAkEC5MMuL1FyabcHIwnw
DA4xNl984osja4KRLfI5q/OVcs8O1gSwKYLlNWTFLWoFOX3lwFKi/dwUHvcYmDY0
auszHwJBAehLEZ0lFh+mewAlalvZtkXSsjLssFsBUYACmohiKtw/CbOurN5hYat8
3iLCrSbneX31TgcsvTsmc4ALPkM429UCQQDrkKoaQBNbTOoHGXztyIGb4efL/yVH
ZiEW9GWkqfSHqxLzuk/vE4IiZaZSl9mLe97ZNy4//oGjiz6WAP7QVXVPAkEBL3+B
OPlAQGLrhaQpJFILOPW7iGoBlvSLuNzqYP2SzAJ/GOeBWKNKXF1fhgoPbAQHGn0B
MSwGUGLx60i3nRyDyw==
-----END PRIVATE KEY-----
Decrypt=RSA-OAEP-5
Ctrl = rsa_padding_mode:oaep
Ctrl = rsa_mgf1_md:sha1
Input=036046a4a47d9ed3ba9a89139c105038eb7492b05a5d68bfd53accff4597f7a68651b47b4a4627d927e485eed7b4566420e8b409879e5d606eae251d22a5df799f7920bfc117b992572a53b1263146bcea03385cc5e853c9a101c8c3e1bda31a519807496c6cb5e5efb408823a352b8fa0661fb664efadd593deb99fff5ed000e5
Output=af71a901e3a61d3132f0fc1fdb474f9ea6579257ffc24d164170145b3dbde8
Decrypt=RSA-OAEP-5
Ctrl = rsa_padding_mode:oaep
Ctrl = rsa_mgf1_md:sha1
Input=03d6eb654edce615bc59f455265ed4e5a18223cbb9be4e4069b473804d5de96f54dcaaa603d049c5d94aa1470dfcd2254066b7c7b61ff1f6f6770e3215c51399fd4e34ec5082bc48f089840ad04354ae66dc0f1bd18e461a33cc1258b443a2837a6df26759aa2302334986f87380c9cc9d53be9f99605d2c9a97da7b0915a4a7ad
Output=a3b844a08239a8ac41605af17a6cfda4d350136585903a417a79268760519a4b4ac3303ec73f0f87cfb32399
Decrypt=RSA-OAEP-5
Ctrl = rsa_padding_mode:oaep
Ctrl = rsa_mgf1_md:sha1
Input=0770952181649f9f9f07ff626ff3a22c35c462443d905d456a9fd0bff43cac2ca7a9f554e9478b9acc3ac838b02040ffd3e1847de2e4253929f9dd9ee4044325a9b05cabb808b2ee840d34e15d105a3f1f7b27695a1a07a2d73fe08ecaaa3c9c9d4d5a89ff890d54727d7ae40c0ec1a8dd86165d8ee2c6368141016a48b55b6967
Output=308b0ecbd2c76cb77fc6f70c5edd233fd2f20929d629f026953bb62a8f4a3a314bde195de85b5f816da2aab074d26cb6acddf323ae3b9c678ac3cf12fbdde7
Decrypt=RSA-OAEP-5
Ctrl = rsa_padding_mode:oaep
Ctrl = rsa_mgf1_md:sha1
Input=0812b76768ebcb642d040258e5f4441a018521bd96687e6c5e899fcd6c17588ff59a82cc8ae03a4b45b31299af1788c329f7dcd285f8cf4ced82606b97612671a45bedca133442144d1617d114f802857f0f9d739751c57a3f9ee400912c61e2e6992be031a43dd48fa6ba14eef7c422b5edc4e7afa04fdd38f402d1c8bb719abf
Output=15c5b9ee1185
Decrypt=RSA-OAEP-5
Ctrl = rsa_padding_mode:oaep
Ctrl = rsa_mgf1_md:sha1
Input=07b60e14ec954bfd29e60d0047e789f51d57186c63589903306793ced3f68241c743529aba6a6374f92e19e0163efa33697e196f7661dfaaa47aac6bde5e51deb507c72c589a2ca1693d96b1460381249b2cdb9eac44769f2489c5d3d2f99f0ee3c7ee5bf64a5ac79c42bd433f149be8cb59548361640595513c97af7bc2509723
Output=21026e6800c7fa728fcaaba0d196ae28d7a2ac4ffd8abce794f0985f60c8a6737277365d3fea11db8923a2029a
Decrypt=RSA-OAEP-5
Ctrl = rsa_padding_mode:oaep
Ctrl = rsa_mgf1_md:sha1
Input=08c36d4dda33423b2ed6830d85f6411ba1dcf470a1fae0ebefee7c089f256cef74cb96ea69c38f60f39abee44129bcb4c92de7f797623b20074e3d9c2899701ed9071e1efa0bdd84d4c3e5130302d8f0240baba4b84a71cc032f2235a5ff0fae277c3e8f9112bef44c9ae20d175fc9a4058bfc930ba31b02e2e4f444483710f24a
Output=541e37b68b6c8872b84c02
PrivateKey=RSA-OAEP-6
-----BEGIN PRIVATE KEY-----
MIICeQIBADANBgkqhkiG9w0BAQEFAASCAmMwggJfAgEAAoGBErF/ba0uzRn/RtwT
94YPCeDgz7Z3s4pSWSMFzq8CLBZtuQ0ErCnjP33RLZ+vZuCBa7Y+rSZ8x9RsF8N7
4hS8oqItcjpk5EQHQ2tvyWVymu/CVU83bNXc6mgpN4CmK/OdAClIWhYLu55dwJct
IaUE9S5e4CiqQWMy9RCy6c/19yKvAgMBAAECgYECleyjVgYYNpVZzs0wOqnP2vwd
nwaVnfdf/vkpqolpYbzRkNxpl+2n9ZY+ck0HtNwR8wZeWul9loNREigLkIS7FPKi
Hr1OiJ1BucQTLsGVb8q4uy/tBXWISTZSLF/30zJhkEgk58re5OC7Ny0kV8944r0S
hiKP+D8QcxzmPJDP8/kCQQSmzotzWN+mm9z3QmFwBa+1OF9fOliiTvdKIqjAXLfM
OOvUzJ2anXiaYs0PYPDLlB00I8lpLvpP463/KQxHSaOLAkEEBMmoAzcf7bTFvjnz
wAsAnl4Ipjvh5AA1zaylARzHAc9+68uZ8P/hfP0KS/e+/S3VNqyUbbeX/bxKvo8p
NJuR7QJBA5Ycj3YKor1RVMeq/XciWzus0BOa57WUjqMxH8zYb7lcda+nZyhLmy3l
WVcvFdjQRMfrg6G+X63yzDd8DYR1KUsCQQIhl+BmdCGWqrwD+i/utOcLFct4fWF6
zTG7dce8I0rXBvfEjSGC0fD/nCKNz0GWe2wLptLArREKG4V4MewkXiyxAkEEAcTA
xT1F29tenZbQ/s9Cdd8JdLxKBza0p0wyaQU++2hqziQG4iyeBY3bSuVAYnri/bCC
Yejn5Ly8mU2q+jBcRQ==
-----END PRIVATE KEY-----
Decrypt=RSA-OAEP-6
Ctrl = rsa_padding_mode:oaep
Ctrl = rsa_mgf1_md:sha1
Input=0630eebcd2856c24f798806e41f9e67345eda9ceda386acc9facaea1eeed06ace583709718d9d169fadf414d5c76f92996833ef305b75b1e4b95f662a20faedc3bae0c4827a8bf8a88edbd57ec203a27a841f02e43a615bab1a8cac0701de34debdef62a088089b55ec36ea7522fd3ec8d06b6a073e6df833153bc0aefd93bd1a3
Output=4046ca8baa3347ca27f49e0d81f9cc1d71be9ba517d4
Decrypt=RSA-OAEP-6
Ctrl = rsa_padding_mode:oaep
Ctrl = rsa_mgf1_md:sha1
Input=0ebc37376173a4fd2f89cc55c2ca62b26b11d51c3c7ce49e8845f74e7607317c436bc8d23b9667dfeb9d087234b47bc6837175ae5c0559f6b81d7d22416d3e50f4ac533d8f0812f2db9e791fe9c775ac8b6ad0f535ad9ceb23a4a02014c58ab3f8d3161499a260f39348e714ae2a1d3443208fd8b722ccfdfb393e98011f99e63f
Output=5cc72c60231df03b3d40f9b57931bc31109f972527f28b19e7480c7288cb3c92b22512214e4be6c914792ddabdf57faa8aa7
Decrypt=RSA-OAEP-6
Ctrl = rsa_padding_mode:oaep
Ctrl = rsa_mgf1_md:sha1
Input=0a98bf1093619394436cf68d8f38e2f158fde8ea54f3435f239b8d06b8321844202476aeed96009492480ce3a8d705498c4c8c68f01501dc81db608f60087350c8c3b0bd2e9ef6a81458b7c801b89f2e4fe99d4900ba6a4b5e5a96d865dc676c7755928794130d6280a8160a190f2df3ea7cf9aa0271d88e9e6905ecf1c5152d65
Output=b20e651303092f4bccb43070c0f86d23049362ed96642fc5632c27db4a52e3d831f2ab068b23b149879c002f6bf3feee97591112562c
Decrypt=RSA-OAEP-6
Ctrl = rsa_padding_mode:oaep
Ctrl = rsa_mgf1_md:sha1
Input=008e7a67cacfb5c4e24bec7dee149117f19598ce8c45808fef88c608ff9cd6e695263b9a3c0ad4b8ba4c95238e96a8422b8535629c8d5382374479ad13fa39974b242f9a759eeaf9c83ad5a8ca18940a0162ba755876df263f4bd50c6525c56090267c1f0e09ce0899a0cf359e88120abd9bf893445b3cae77d3607359ae9a52f8
Output=684e3038c5c041f7
Decrypt=RSA-OAEP-6
Ctrl = rsa_padding_mode:oaep
Ctrl = rsa_mgf1_md:sha1
Input=00003474416c7b68bdf961c385737944d7f1f40cb395343c693cc0b4fe63b31fedf1eaeeac9ccc0678b31dc32e0977489514c4f09085f6298a9653f01aea4045ff582ee887be26ae575b73eef7f3774921e375a3d19adda0ca31aa1849887c1f42cac9677f7a2f4e923f6e5a868b38c084ef187594dc9f7f048fea2e02955384ab
Output=32488cb262d041d6e4dd35f987bf3ca696db1f06ac29a44693
Decrypt=RSA-OAEP-6
Ctrl = rsa_padding_mode:oaep
Ctrl = rsa_mgf1_md:sha1
Input=0a026dda5fc8785f7bd9bf75327b63e85e2c0fdee5dadb65ebdcac9ae1de95c92c672ab433aa7a8e69ce6a6d8897fac4ac4a54de841ae5e5bbce7687879d79634cea7a30684065c714d52409b928256bbf53eabcd5231eb7259504537399bd29164b726d33a46da701360a4168a091ccab72d44a62fed246c0ffea5b1348ab5470
Output=50ba14be8462720279c306ba
PrivateKey=RSA-OAEP-7
-----BEGIN PRIVATE KEY-----
MIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBMRF58Lz8m508oxXQ
DvMNe906LPrpkRv+3LlIs6R4LQcytqtEqkvwN0GmRNwBvsPmmwGgM+Z12KzXxJJc
axrsMRkFHf2Jdi0hXUVHX/y1n5CBSGI/NxdxVvauht16fF9D3B4fkIJUBYooSl8G
wAIXk6h/GsX+/33K7mnF5Ro3ieNzAgMBAAECgYEHDPz/L+uCduJ0MsRd/uSPSbeR
fWUw4fDKNGDzLgJ2F0SHxW4ipF0lANd3VJUhnX0WWpzzvZLDKvmpjY3JzCloAK3J
SgpU+0DzQpG/hO6OoStvEJNZxtNUKlD5x2f1z/8FpoHC5lb7d8qq20vpRo2KvNTf
mPWOhtIFP6E0n3SOIbECQQdJJiwRHNRw7CVm5rNzL8CTKUaaoZBx07nAGQZRTG8d
JrqhS+qwlxyLfmEaT3kAnW/qd2koyiUoWw3jZD0aP4xxAkEGvB5Q6WwCv2NunuqL
iZu+v3ZR3nfdR0w+m8I7rYGCthkEx9l9++v7HgAQiHi25n5BU5HWeULCsr+bRDX4
iwywIwJBA7x+p/CqsUOrxs6LlxGGNqMBcuTP4CyPoN2jt7qvkPgJKYKYVSX0iL38
tL1ybiJjmsZKMJKrf/y/HVM0z6ULW/ECQQJipqopwqPGfcU0bAY4Gv2YeqPMk8+/
7PVP3Z+deH1/WaUj05iXnaE3ovY4H+lIAffJTaIVGNw0y0CHDEaXmUrZAkBknUwX
tu4XIedy0DiaVZw9PN+VUNRXxGsDe3RkGx1SFmr4ohPIOWIGzfukQi8Y1vYdvLXS
FMlxv0gq65dqc3DC
-----END PRIVATE KEY-----
Decrypt=RSA-OAEP-7
Ctrl = rsa_padding_mode:oaep
Ctrl = rsa_mgf1_md:sha1
Input=1688e4ce7794bba6cb7014169ecd559cede2a30b56a52b68d9fe18cf1973ef97b2a03153951c755f6294aa49adbdb55845ab6875fb3986c93ecf927962840d282f9e54ce8b690f7c0cb8bbd73440d9571d1b16cd9260f9eab4783cc482e5223dc60973871783ec27b0ae0fd47732cbc286a173fc92b00fb4ba6824647cd93c85c1
Output=47aae909
Decrypt=RSA-OAEP-7
Ctrl = rsa_padding_mode:oaep
Ctrl = rsa_mgf1_md:sha1
Input=1052ed397b2e01e1d0ee1c50bf24363f95e504f4a03434a08fd822574ed6b9736edbb5f390db10321479a8a139350e2bd4977c3778ef331f3e78ae118b268451f20a2f01d471f5d53c566937171b2dbc2d4bde459a5799f0372d6574239b2323d245d0bb81c286b63c89a361017337e4902f88a467f4c7f244bfd5ab46437ff3b6
Output=1d9b2e2223d9bc13bfb9f162ce735db48ba7c68f6822a0a1a7b6ae165834e7
Decrypt=RSA-OAEP-7
Ctrl = rsa_padding_mode:oaep
Ctrl = rsa_mgf1_md:sha1
Input=2155cd843ff24a4ee8badb7694260028a490813ba8b369a4cbf106ec148e5298707f5965be7d101c1049ea8584c24cd63455ad9c104d686282d3fb803a4c11c1c2e9b91c7178801d1b6640f003f5728df007b8a4ccc92bce05e41a27278d7c85018c52414313a5077789001d4f01910b72aad05d220aa14a58733a7489bc54556b
Output=d976fc
Decrypt=RSA-OAEP-7
Ctrl = rsa_padding_mode:oaep
Ctrl = rsa_mgf1_md:sha1
Input=0ab14c373aeb7d4328d0aaad8c094d88b9eb098b95f21054a29082522be7c27a312878b637917e3d819e6c3c568db5d843802b06d51d9e98a2be0bf40c031423b00edfbff8320efb9171bd2044653a4cb9c5122f6c65e83cda2ec3c126027a9c1a56ba874d0fea23f380b82cf240b8cf540004758c4c77d934157a74f3fc12bfac
Output=d4738623df223aa43843df8467534c41d013e0c803c624e263666b239bde40a5f29aeb8de79e3daa61dd0370f49bd4b013834b98212aef6b1c5ee373b3cb
Decrypt=RSA-OAEP-7
Ctrl = rsa_padding_mode:oaep
Ctrl = rsa_mgf1_md:sha1
Input=028387a318277434798b4d97f460068df5298faba5041ba11761a1cb7316b24184114ec500257e2589ed3b607a1ebbe97a6cc2e02bf1b681f42312a33b7a77d8e7855c4a6de03e3c04643f786b91a264a0d6805e2cea91e68177eb7a64d9255e4f27e713b7ccec00dc200ebd21c2ea2bb890feae4942df941dc3f97890ed347478
Output=bb47231ca5ea1d3ad46c99345d9a8a61
Decrypt=RSA-OAEP-7
Ctrl = rsa_padding_mode:oaep
Ctrl = rsa_mgf1_md:sha1
Input=14c678a94ad60525ef39e959b2f3ba5c097a94ff912b67dbace80535c187abd47d075420b1872152bba08f7fc31f313bbf9273c912fc4c0149a9b0cfb79807e346eb332069611bec0ff9bcd168f1f7c33e77313cea454b94e2549eecf002e2acf7f6f2d2845d4fe0aab2e5a92ddf68c480ae11247935d1f62574842216ae674115
Output=2184827095d35c3f86f600e8e59754013296
PrivateKey=RSA-OAEP-8
-----BEGIN PRIVATE KEY-----
MIICeQIBADANBgkqhkiG9w0BAQEFAASCAmMwggJfAgEAAoGBW98OMNMh3aUUf4gk
CPppGVSA34+A0/bov1gYUE82QnypsfVUC5xlqPaXTPhEeiRNkoAgG7Sfy75jeNGU
TNIn4jD5bj0Q+Bnc7ydsZKALKktnAefQHeX6veOx6aDfgvRjE1nNImaWR/uxcXJG
E07XtJfP/73EK1nHOpbtkBZiEt/3AgMBAAECgYEPfR6eWqol/RPkoGY64UTg0V9c
0YvNsJ3yzH5k48XpFa1iZFMEFh0JjHFbt6uL0B0H6vP+18ftCK8qimLvRKsWsyDh
SvcqSPlq/iYqCuTPZeY16RB5DNTuXOp2iksmOffm9nez8Ltr4yt1dH2JCQNvAmT1
jUAc26ExcWFXp17PYzECQQoC74RI2frYu9DQBMjCqpdR75chwbDQMjalSw35R8uu
1aJV7p6OINSR6hcj/glHBKl2Loiv0W67WZRBLKlm3E+fAkEJLTYuftOgv9np/Q5s
AwG23ykVnPUMyDubDPTW7qcaYeACtG4K6fLeYtJbXXRS1Ji4HJrG/FhZPUw/tPXX
LfuwqQJBB8cUEK8QOWLbNnQE43roULqk6cKd2SFFgVKUpnx9HG3tJjqgMKm2M65Q
MD4UA10a8BQSPrpoeCAwjY68hbaVfX0CQQCuLHU4DALAFq0FiRszAd6IHyiuEXEY
K2ssg76nxRXsqcopjHscq1gXpZcGj8hQYN5NqKAWN4quQ8f5Z7zDeQS5AkEFmNEF
njraT2MgdSwJ2AX/fR8a4NAXru7pzvoNfdf/d15EtXgyL2QF1iEdoZUZZmqof9xM
2MiPa249Z+lh3Luj0A==
-----END PRIVATE KEY-----
Decrypt=RSA-OAEP-8
Ctrl = rsa_padding_mode:oaep
Ctrl = rsa_mgf1_md:sha1
Input=09b3683d8a2eb0fb295b62ed1fb9290b714457b7825319f4647872af889b30409472020ad12912bf19b11d4819f49614824ffd84d09c0a17e7d17309d12919790410aa2995699f6a86dbe3242b5acc23af45691080d6b1ae810fb3e3057087f0970092ce00be9562ff4053b6262ce0caa93e13723d2e3a5ba075d45f0d61b54b61
Output=050b755e5e6880f7b9e9d692a74c37aae449b31bfea6deff83747a897f6c2c825bb1adbf850a3c96994b5de5b33cbc7d4a17913a7967
Decrypt=RSA-OAEP-8
Ctrl = rsa_padding_mode:oaep
Ctrl = rsa_mgf1_md:sha1
Input=2ecf15c97c5a15b1476ae986b371b57a24284f4a162a8d0c8182e7905e792256f1812ba5f83f1f7a130e42dcc02232844edc14a31a68ee97ae564a383a3411656424c5f62ddb646093c367be1fcda426cf00a06d8acb7e57776fbbd855ac3df506fc16b1d7c3f2110f3d8068e91e186363831c8409680d8da9ecd8cf1fa20ee39d
Output=4eb68dcd93ca9b19df111bd43608f557026fe4aa1d5cfac227a3eb5ab9548c18a06dded23f81825986b2fcd71109ecef7eff88873f075c2aa0c469f69c92bc
Decrypt=RSA-OAEP-8
Ctrl = rsa_padding_mode:oaep
Ctrl = rsa_mgf1_md:sha1
Input=4bc89130a5b2dabb7c2fcf90eb5d0eaf9e681b7146a38f3173a3d9cfec52ea9e0a41932e648a9d69344c50da763f51a03c95762131e8052254dcd2248cba40fd31667786ce05a2b7b531ac9dac9ed584a59b677c1a8aed8c5d15d68c05569e2be780bf7db638fd2bfd2a85ab276860f3777338fca989ffd743d13ee08e0ca9893f
Output=8604ac56328c1ab5ad917861
Decrypt=RSA-OAEP-8
Ctrl = rsa_padding_mode:oaep
Ctrl = rsa_mgf1_md:sha1
Input=2e456847d8fc36ff0147d6993594b9397227d577752c79d0f904fcb039d4d812fea605a7b574dd82ca786f93752348438ee9f5b5454985d5f0e1699e3e7ad175a32e15f03deb042ab9fe1dd9db1bb86f8c089ccb45e7ef0c5ee7ca9b7290ca6b15bed47039788a8a93ff83e0e8d6244c71006362deef69b6f416fb3c684383fbd0
Output=fdda5fbf6ec361a9d9a4ac68af216a0686f438b1e0e5c36b955f74e107f39c0dddcc
Decrypt=RSA-OAEP-8
Ctrl = rsa_padding_mode:oaep
Ctrl = rsa_mgf1_md:sha1
Input=1fb9356fd5c4b1796db2ebf7d0d393cc810adf6145defc2fce714f79d93800d5e2ac211ea8bbecca4b654b94c3b18b30dd576ce34dc95436ef57a09415645923359a5d7b4171ef22c24670f1b229d3603e91f76671b7df97e7317c97734476d5f3d17d21cf82b5ba9f83df2e588d36984fd1b584468bd23b2e875f32f68953f7b2
Output=4a5f4914bee25de3c69341de07
Decrypt=RSA-OAEP-8
Ctrl = rsa_padding_mode:oaep
Ctrl = rsa_mgf1_md:sha1
Input=3afd9c6600147b21798d818c655a0f4c9212db26d0b0dfdc2a7594ccb3d22f5bf1d7c3e112cd73fc7d509c7a8bafdd3c274d1399009f9609ec4be6477e453f075aa33db382870c1c3409aef392d7386ae3a696b99a94b4da0589447e955d16c98b17602a59bd736279fcd8fb280c4462d590bfa9bf13fed570eafde97330a2c210
Output=8e07d66f7b880a72563abcd3f35092bc33409fb7f88f2472be
PrivateKey=RSA-OAEP-9
-----BEGIN PRIVATE KEY-----
MIIDlwIBADANBgkqhkiG9w0BAQEFAASCA4EwggN9AgEAAoHBAM8s1B40yjpyjqXL
iv9kw20nve9TZOM2/WjTEjxaGWqMKHAT6FPVFW1Y0VGVRSD7T217F6u2gXdlkJxX
YRllnZArGQbtiisQwVXCTRJFKNq57q43m+rGbkpBF4bcuP0AYuvAMN4SGaBMKowb
fdMTHk1rbK7i4xpe1BrBUJsu8e4qsYNkvlaMqUHCXsyE/51kO17Bqq4QKiDXP0eb
eA/W2pEHUhLZ6sA6BnTYmeui5DH0xEthW2uiIyvUszuu1z1iXQIDAQABAoHAGYwU
HiNxWpK8z2oRmlvBE4lGjSgR9UjXJ+F7SrDrmG1vIR77U7cffMvqh+5px17mFQCM
UzLetSvzkKvfv+N9cgU2gVmyY4wd4ybiHSIlHw+1hIs78VAF0qdDMPCv6RbuYszB
NE0dg6cJ5gZ2JzhA9/N3QkpeCk2nXwGzH/doGc+cv90hUkPDkXwD7zgZkxLlZ7O/
eu06tFfzce+KFCP0W2jG4oLsERu6KDO5h/1p+tg7wbjGE8Xh6hbBHtEl6n7BAmEA
/I1sBL7E65qBksp5AMvlNuLotRnezzOyRZeYxpCd9PF2230jGQ/HK4hlpxiviV8b
zZFFKYAnQjtgXnCkfPWDkKjD6I/IxI6LMuPaIQ374+iB6lZ0tqNIwh6T+eVepl79
AmEA0gDUXniKrOpgakAdBGD4fdXBAn4S3BoNdYbok52c94m0D1GsBEKWHefSHMIe
BcgxVcHyqpGTOHz9+VbLSNFTuicEBvm7ulN9SYfZ4vmULXoUy//+p0/s3ako0j4l
n17hAmEA2xaAL3mi8NRfNY1p/TPkS4H66ChiLpOlQlPpl9AbB0N1naDoErSqTmyL
6rIyjVQxlVpBimf/JqjFyAel2jVOBe8xzIz3WPRjcylQsD4mVyb7lOOdalcqJiRK
sI23V1KtAmEAoKMXz+ffFCP4em3uhFH04rSmflSX8ptPHk6DC5+t2UARZwJvVZbl
o5yXgX4PXxbifhnsmQLgHX6m+5qjx2Cv7h44G2neasnAdYWgatnEugC/dcitL6iY
pHnoCuKU/tKhAmALIfM1w1M0LrRMOqJERXgMLWVblAF0yuOMfIpOZJPAup/TA3SC
Z7CDuaemy2HkLbNiuMmJbbcGTgKtWuYVh9oVtGSckFlJCf6zfby2VL63Jo7IAeWo
tKo5Eb69iFQvBb4=
-----END PRIVATE KEY-----
Decrypt=RSA-OAEP-9
Ctrl = rsa_padding_mode:oaep
Ctrl = rsa_mgf1_md:sha1
Input=267bcd118acab1fc8ba81c85d73003cb8610fa55c1d97da8d48a7c7f06896a4db751aa284255b9d36ad65f37653d829f1b37f97b8001942545b2fc2c55a7376ca7a1be4b1760c8e05a33e5aa2526b8d98e317088e7834c755b2a59b12631a182c05d5d43ab1779264f8456f515ce57dfdf512d5493dab7b7338dc4b7d78db9c091ac3baf537a69fc7f549d979f0eff9a94fda4169bd4d1d19a69c99e33c3b55490d501b39b1edae118ff6793a153261584d3a5f39f6e682e3d17c8cd1261fa72
Output=f735fd55ba92592c3b52b8f9c4f69aaa1cbef8fe88add095595412467f9cf4ec0b896c59eda16210e7549c8abb10cdbc21a12ec9b6b5b8fd2f10399eb6
Decrypt=RSA-OAEP-9
Ctrl = rsa_padding_mode:oaep
Ctrl = rsa_mgf1_md:sha1
Input=93ac9f0671ec29acbb444effc1a5741351d60fdb0e393fbf754acf0de49761a14841df7772e9bc82773966a1584c4d72baea00118f83f35cca6e537cbd4d811f5583b29783d8a6d94cd31be70d6f526c10ff09c6fa7ce069795a3fcd0511fd5fcb564bcc80ea9c78f38b80012539d8a4ddf6fe81e9cddb7f50dbbbbcc7e5d86097ccf4ec49189fb8bf318be6d5a0715d516b49af191258cd32dc833ce6eb4673c03a19bbace88cc54895f636cc0c1ec89096d11ce235a265ca1764232a689ae8
Output=81b906605015a63aabe42ddf11e1978912f5404c7474b26dce3ed482bf961ecc818bf420c54659
Decrypt=RSA-OAEP-9
Ctrl = rsa_padding_mode:oaep
Ctrl = rsa_mgf1_md:sha1
Input=81ebdd95054b0c822ef9ad7693f5a87adfb4b4c4ce70df2df84ed49c04da58ba5fc20a19e1a6e8b7a3900b22796dc4e869ee6b42792d15a8eceb56c09c69914e813cea8f6931e4b8ed6f421af298d595c97f4789c7caa612c7ef360984c21b93edc5401068b5af4c78a8771b984d53b8ea8adf2f6a7d4a0ba76c75e1dd9f658f20ded4a46071d46d7791b56803d8fea7f0b0f8e41ae3f09383a6f9585fe7753eaaffd2bf94563108beecc207bbb535f5fcc705f0dde9f708c62f49a9c90371d3
Output=fd326429df9b890e09b54b18b8f34f1e24
Decrypt=RSA-OAEP-9
Ctrl = rsa_padding_mode:oaep
Ctrl = rsa_mgf1_md:sha1
Input=bcc35f94cde66cb1136625d625b94432a35b22f3d2fa11a613ff0fca5bd57f87b902ccdc1cd0aebcb0715ee869d1d1fe395f6793003f5eca465059c88660d446ff5f0818552022557e38c08a67ead991262254f10682975ec56397768537f4977af6d5f6aaceb7fb25dec5937230231fd8978af49119a29f29e424ab8272b47562792d5c94f774b8829d0b0d9f1a8c9eddf37574d5fa248eefa9c5271fc5ec2579c81bdd61b410fa61fe36e424221c113addb275664c801d34ca8c6351e4a858
Output=f1459b5f0c92f01a0f723a2e5662484d8f8c0a20fc29dad6acd43bb5f3effdf4e1b63e07fdfe6628d0d74ca19bf2d69e4a0abf86d293925a796772f8088e
Decrypt=RSA-OAEP-9
Ctrl = rsa_padding_mode:oaep
Ctrl = rsa_mgf1_md:sha1
Input=232afbc927fa08c2f6a27b87d4a5cb09c07dc26fae73d73a90558839f4fd66d281b87ec734bce237ba166698ed829106a7de6942cd6cdce78fed8d2e4d81428e66490d036264cef92af941d3e35055fe3981e14d29cbb9a4f67473063baec79a1179f5a17c9c1832f2838fd7d5e59bb9659d56dce8a019edef1bb3accc697cc6cc7a778f60a064c7f6f5d529c6210262e003de583e81e3167b89971fb8c0e15d44fffef89b53d8d64dd797d159b56d2b08ea5307ea12c241bd58d4ee278a1f2e
Output=53e6e8c729d6f9c319dd317e74b0db8e4ccca25f3c8305746e137ac63a63ef3739e7b595abb96e8d55e54f7bd41ab433378ffb911d
Decrypt=RSA-OAEP-9
Ctrl = rsa_padding_mode:oaep
Ctrl = rsa_mgf1_md:sha1
Input=438cc7dc08a68da249e42505f8573ba60e2c2773d5b290f4cf9dff718e842081c383e67024a0f29594ea987b9d25e4b738f285970d195abb3a8c8054e3d79d6b9c9a8327ba596f1259e27126674766907d8d582ff3a8476154929adb1e6d1235b2ccb4ec8f663ba9cc670a92bebd853c8dbf69c6436d016f61add836e94732450434207f9fd4c43dec2a12a958efa01efe2669899b5e604c255c55fb7166de5589e369597bb09168c06dd5db177e06a1740eb2d5c82faeca6d92fcee9931ba9f
Output=b6b28ea2198d0c1008bc64
PrivateKey=RSA-OAEP-10
-----BEGIN PRIVATE KEY-----
MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCuRe1WAc7GuMwF
+AOTXGdN2+DXXEwJ/XlR/GsMrsMTqN85lwxRi/+6XtaPPw1/IqQCnUE/GuB+Tr6e
QXfOI+f1QEtWnk7hvc88H7A+8ROALU+FXrm1E0tafICFrcrm+i+hQX7DdjvhcbDG
K3YO3iPBKtkrmAiExkH1qPrCa9rUoDOBoi/ht1SIUJTIJQbUAZpTWihq/rJxu5ul
kt4Y3PYAwq7q5W4C9895/BTPO9x82E/ru/lQypAwSyIZp6oGOu+iw8GYDlYM1kr+
d5WFthB2V7lXhX795gEJiKt95Bf8iNjzhMTm5yw/lD4MMcDEpcw2+HnYo6ydfVmG
Dqraa4O7AgMBAAECggEABWsEIW/l81SsdyUKS2sMhSWoXFmwvYDFZFCiLV9Djllq
MzqodeKR3UP0jLiLnV/A1Jn5/NHDl/mvwHDNnjmMjRnmHbfHQQprJnXfv100W4BN
IBrdUC1c4t/LCRzpmXu+vlcwbzg+TViBA/A29+hdGTTRUqMj5KjbRR1vSlsbDxAs
wVDgL+7iuI3qStTBusyyTYQHLRTh0kpncfdAjuMFZPuG1Dk6NLzwt4hQHRkzA/E6
IoSwAfD2Ser3kyjUrFxDCrRBSSCpRg7Rt7xA7GU+h20Jq8UJrkW1JRkBFqDCYQGE
gphQnBw786SD5ydAVOFelwdQNumJ9gkygHtSV3UeeQKBgQDs9a7NHlUV//rL11oo
Fsbr9JAYzftGOOGF1mpzlrb4CQ+AGMf9lcw0uFfcF/DMZRa7E0arTVgsra17QQM1
I4e3AzjQhAR8nZU5tkliBLPdbqRCSZIHvsAflkKH/2M2w5hGWDNoRvVuRoYYgcEC
M9IXa/FaXpbdx4C8hoqnfTznaQKBgQC8RsRk/GrEyng7DrCKPIQbdy9+my8our1Y
iuiF4aDGHkhYoPslrCmZkPNb6FFkwlm6EXXN1xknBxNRhJkrbCm3Rt0NLKvhQoNf
fRSMwWFSS0oJlG1IuChHPxzna2y2iGw0XAPgX0HVG1w6kKPyQHPH10pP4l2c8hx1
lg8/w4YxgwKBgQDHNWRXHQD7FdCKPemVelCRXXEm6UQtrPQryC6GLlZz/2oAjtTS
43RhffifF6FgtDt/2py2trdCGGCYFffUXKJjwVmqMtJy0Sf69LyMotdzeOiusZsK
19o8s94K5zFJgPYrbUsKh10d8DwbrjnM2DPvbNfi2VKL8ITR+WnnlOn2wQKBgCZY
s39t+cEDC+HbaBF/qdh+OeoraTt+bTovcJR0E+7GFC4Y+438tqxUXXyGoK1I+EVx
cPDvsmvEgSbFPv0dFpIBmNwqEQfcKC22qAzTBiNguj+hP3DkMS/xps1rj8TNnFw9
sXxtalchL3OuKfYZMnutWbFThYWFuk4otgpipF5JAoGAbzhSazklCFU07z5BWoNu
3ouGFYosfL/sywvYNDBP7Gg7qNT0ecQz1DQW5jJpYjzqEAd22Fr/QB0//2EO5lQR
zjsTY9Y6lwnu3kJkfOpWFJPVRXCoecGGgs2XcQuWIF7DERfXO182Ij+t1ui6kN18
DuYdROFjJR4gx/ZuswURfLg=
-----END PRIVATE KEY-----
Decrypt=RSA-OAEP-10
Ctrl = rsa_padding_mode:oaep
Ctrl = rsa_mgf1_md:sha1
Input=53ea5dc08cd260fb3b858567287fa91552c30b2febfba213f0ae87702d068d19bab07fe574523dfb42139d68c3c5afeee0bfe4cb7969cbf382b804d6e61396144e2d0e60741f8993c3014b58b9b1957a8babcd23af854f4c356fb1662aa72bfcc7e586559dc4280d160c126785a723ebeebeff71f11594440aaef87d10793a8774a239d4a04c87fe1467b9daf85208ec6c7255794a96cc29142f9a8bd418e3c1fd67344b0cd0829df3b2bec60253196293c6b34d3f75d32f213dd45c6273d505adf4cced1057cb758fc26aeefa441255ed4e64c199ee075e7f16646182fdb464739b68ab5daff0e63e9552016824f054bf4d3c8c90a97bb6b6553284eb429fcc
Output=8bba6bf82a6c0f86d5f1756e97956870b08953b06b4eb205bc1694ee
Decrypt=RSA-OAEP-10
Ctrl = rsa_padding_mode:oaep
Ctrl = rsa_mgf1_md:sha1
Input=a2b1a430a9d657e2fa1c2bb5ed43ffb25c05a308fe9093c01031795f5874400110828ae58fb9b581ce9dddd3e549ae04a0985459bde6c626594e7b05dc4278b2a1465c1368408823c85e96dc66c3a30983c639664fc4569a37fe21e5a195b5776eed2df8d8d361af686e750229bbd663f161868a50615e0c337bec0ca35fec0bb19c36eb2e0bbcc0582fa1d93aacdb061063f59f2ce1ee43605e5d89eca183d2acdfe9f81011022ad3b43a3dd417dac94b4e11ea81b192966e966b182082e71964607b4f8002f36299844a11f2ae0faeac2eae70f8f4f98088acdcd0ac556e9fccc511521908fad26f04c64201450305778758b0538bf8b5bb144a828e629795
Output=e6ad181f053b58a904f2457510373e57
Decrypt=RSA-OAEP-10
Ctrl = rsa_padding_mode:oaep
Ctrl = rsa_mgf1_md:sha1
Input=9886c3e6764a8b9a84e84148ebd8c3b1aa8050381a78f668714c16d9cfd2a6edc56979c535d9dee3b44b85c18be8928992371711472216d95dda98d2ee8347c9b14dffdff84aa48d25ac06f7d7e65398ac967b1ce90925f67dce049b7f812db0742997a74d44fe81dbe0e7a3feaf2e5c40af888d550ddbbe3bc20657a29543f8fc2913b9bd1a61b2ab2256ec409bbd7dc0d17717ea25c43f42ed27df8738bf4afc6766ff7aff0859555ee283920f4c8a63c4a7340cbafddc339ecdb4b0515002f96c932b5b79167af699c0ad3fccfdf0f44e85a70262bf2e18fe34b850589975e867ff969d48eabf212271546cdc05a69ecb526e52870c836f307bd798780ede
Output=510a2cf60e866fa2340553c94ea39fbc256311e83e94454b4124
Decrypt=RSA-OAEP-10
Ctrl = rsa_padding_mode:oaep
Ctrl = rsa_mgf1_md:sha1
Input=6318e9fb5c0d05e5307e1683436e903293ac4642358aaa223d7163013aba87e2dfda8e60c6860e29a1e92686163ea0b9175f329ca3b131a1edd3a77759a8b97bad6a4f8f4396f28cf6f39ca58112e48160d6e203daa5856f3aca5ffed577af499408e3dfd233e3e604dbe34a9c4c9082de65527cac6331d29dc80e0508a0fa7122e7f329f6cca5cfa34d4d1da417805457e008bec549e478ff9e12a763c477d15bbb78f5b69bd57830fc2c4ed686d79bc72a95d85f88134c6b0afe56a8ccfbc855828bb339bd17909cf1d70de3335ae07039093e606d655365de6550b872cd6de1d440ee031b61945f629ad8a353b0d40939e96a3c450d2a8d5eee9f678093c8
Output=bcdd190da3b7d300df9a06e22caae2a75f10c91ff667b7c16bde8b53064a2649a94045c9
Decrypt=RSA-OAEP-10
Ctrl = rsa_padding_mode:oaep
Ctrl = rsa_mgf1_md:sha1
Input=75290872ccfd4a4505660d651f56da6daa09ca1301d890632f6a992f3d565cee464afded40ed3b5be9356714ea5aa7655f4a1366c2f17c728f6f2c5a5d1f8e28429bc4e6f8f2cff8da8dc0e0a9808e45fd09ea2fa40cb2b6ce6ffff5c0e159d11b68d90a85f7b84e103b09e682666480c657505c0929259468a314786d74eab131573cf234bf57db7d9e66cc6748192e002dc0deea930585f0831fdcd9bc33d51f79ed2ffc16bcf4d59812fcebcaa3f9069b0e445686d644c25ccf63b456ee5fa6ffe96f19cdf751fed9eaf35957754dbf4bfea5216aa1844dc507cb2d080e722eba150308c2b5ff1193620f1766ecf4481bafb943bd292877f2136ca494aba0
Output=a7dd6c7dc24b46f9dd5f1e91ada4c3b3df947e877232a9
Decrypt=RSA-OAEP-10
Ctrl = rsa_padding_mode:oaep
Ctrl = rsa_mgf1_md:sha1
Input=2d207a73432a8fb4c03051b3f73b28a61764098dfa34c47a20995f8115aa6816679b557e82dbee584908c6e69782d7deb34dbd65af063d57fca76a5fd069492fd6068d9984d209350565a62e5c77f23038c12cb10c6634709b547c46f6b4a709bd85ca122d74465ef97762c29763e06dbc7a9e738c78bfca0102dc5e79d65b973f28240caab2e161a78b57d262457ed8195d53e3c7ae9da021883c6db7c24afdd2322eac972ad3c354c5fcef1e146c3a0290fb67adf007066e00428d2cec18ce58f9328698defef4b2eb5ec76918fde1c198cbb38b7afc67626a9aefec4322bfd90d2563481c9a221f78c8272c82d1b62ab914e1c69f6af6ef30ca5260db4a46
Output=eaf1a73a1b0c4609537de69cd9228bbcfb9a8ca8c6c3efaf056fe4a7f4634ed00b7c39ec6922d7b8ea2c04ebac
Title = RSA DigestSign and DigestVerify
DigestSign = SHA256
Key = RSA-2048
Input = "Hello World"
Output = ba8c24b86f18633767ed1778ef12d283a508d0bef32dd50b4a67cbd6b75df0f4ef6e69bfafbc809b01b93ab34aad9a33908644efca6eca04db1afda1016d1c1603183d2263597cf85ce5b7acd6a4872cbcc401b90b221d85aa0a2d0e1f159fc0843e0a55c47dc108c3f207d000e954605fabbb8c938050f280e29653aa1438109d02e53dfbdcb8cb9b46d372dd39ba7317a3f4c0020dba1ddd247b3d58addb1df7208785a62a8e3e4372c1fa6d24a17cd6413f7f5c046ba40a881c21875fde848b3b56fea7264430eca15b27c5c3b72fedcbcc124f8d939ffc11e6d3172c7eb491d378902093fcc3bf3a2835a1fcfabf457c13abf7b37f08595ed72332e27034
DigestSign = SHA256
Key = RSA-2048
Input = "Hello "
Input = "World"
Output = ba8c24b86f18633767ed1778ef12d283a508d0bef32dd50b4a67cbd6b75df0f4ef6e69bfafbc809b01b93ab34aad9a33908644efca6eca04db1afda1016d1c1603183d2263597cf85ce5b7acd6a4872cbcc401b90b221d85aa0a2d0e1f159fc0843e0a55c47dc108c3f207d000e954605fabbb8c938050f280e29653aa1438109d02e53dfbdcb8cb9b46d372dd39ba7317a3f4c0020dba1ddd247b3d58addb1df7208785a62a8e3e4372c1fa6d24a17cd6413f7f5c046ba40a881c21875fde848b3b56fea7264430eca15b27c5c3b72fedcbcc124f8d939ffc11e6d3172c7eb491d378902093fcc3bf3a2835a1fcfabf457c13abf7b37f08595ed72332e27034
DigestSign = SHA256
Key = RSA-2048
Input = "Hello "
Input = "World"
Ctrl = rsa_padding_mode:pss
Ctrl = rsa_pss_saltlen:0
Output = 4a35cc7623f176c997696213045024f1b1121a6ec4a5755d206c20fc4a7c5259566d19730f6f1a75ac00878c6290e6757510588d740da3633b09a1d899c7dfba2031cfcae6a490e995c87f4750ea88948009cbed6c80cebb9ebfab7d04805e7a2140373fb888b5e6151d1c4eb7f505c4e0a584c17c6ca71e552ba13e1f20101796fe0d1af0cde661fc47d904b5d3f127073471fe6dc7e78f5cd2a049d67e0c7c92184e2bf97f8e16b50b8385daa1f8882e8f6c8683720903454b35356058f2f0136cad7689105167bacbe0dbad466ff2a298e41e5a65caecac4cde08529b7ea8717258e19b0732c966b34f5d52e4ec3073da78757471086553a3ff6c5460bcda
DigestVerify = SHA256
Key = RSA-2048-PUBLIC
Input = "Hello "
Input = "World"
Output = ba8c24b86f18633767ed1778ef12d283a508d0bef32dd50b4a67cbd6b75df0f4ef6e69bfafbc809b01b93ab34aad9a33908644efca6eca04db1afda1016d1c1603183d2263597cf85ce5b7acd6a4872cbcc401b90b221d85aa0a2d0e1f159fc0843e0a55c47dc108c3f207d000e954605fabbb8c938050f280e29653aa1438109d02e53dfbdcb8cb9b46d372dd39ba7317a3f4c0020dba1ddd247b3d58addb1df7208785a62a8e3e4372c1fa6d24a17cd6413f7f5c046ba40a881c21875fde848b3b56fea7264430eca15b27c5c3b72fedcbcc124f8d939ffc11e6d3172c7eb491d378902093fcc3bf3a2835a1fcfabf457c13abf7b37f08595ed72332e27034
DigestVerify = SHA256
Key = RSA-2048-PUBLIC
Input = "Hello"
Input = "World"
Output = ba8c24b86f18633767ed1778ef12d283a508d0bef32dd50b4a67cbd6b75df0f4ef6e69bfafbc809b01b93ab34aad9a33908644efca6eca04db1afda1016d1c1603183d2263597cf85ce5b7acd6a4872cbcc401b90b221d85aa0a2d0e1f159fc0843e0a55c47dc108c3f207d000e954605fabbb8c938050f280e29653aa1438109d02e53dfbdcb8cb9b46d372dd39ba7317a3f4c0020dba1ddd247b3d58addb1df7208785a62a8e3e4372c1fa6d24a17cd6413f7f5c046ba40a881c21875fde848b3b56fea7264430eca15b27c5c3b72fedcbcc124f8d939ffc11e6d3172c7eb491d378902093fcc3bf3a2835a1fcfabf457c13abf7b37f08595ed72332e27034
Result = VERIFY_ERROR
DigestSign = SHA256
Key = RSA-2048
Input = "Hello "
Input = "World"
Output = ba8c24b86f18633767ed1778ef12d283a508d0bef32dd50b4a67cbd6b75df0f4ef6e69bfafbc809b01b93ab34aad9a33908644efca6eca04db1afda1016d1c1603183d2263597cf85ce5b7acd6a4872cbcc401b90b221d85aa0a2d0e1f159fc0843e0a55c47dc108c3f207d000e954605fabbb8c938050f280e29653aa1438109d02e53dfbdcb8cb9b46d372dd39ba7317a3f4c0020dba1ddd247b3d58addb1df7208785a62a8e3e4372c1fa6d24a17cd6413f7f5c046ba40a881c21875fde848b3b56fea7264430eca15b27c5c3b72fedcbcc124f8d939ffc11e6d3172c7eb491d378902093fcc3bf3a2835a1fcfabf457c13abf7b37f08595ed72332e27034
# As there dont seem to be test vectors for these - they were just generated
# to verify that all approved digests are supported.
Title = Test RSA with different digests
DigestSign = SHA224
Key = RSA-2048
Input = "Hello World"
Output = 4bae2cf892733233985102eb7117303e49994a8a97b3de64597c33f15a689502ba4dcea20f0ada460b262bd0c92db23dd090453f95debbfd7a835b51d1923ede76f4f66ba04d9ba0715b333a747c8d469283af653f286a307a3c46cd91f51ca2d597f9d3951fc068ff3ed45ba6b3540801159c7c890a252183de9e4aeb0512eb9ae681ac1d436c9efef9f265dcdf64ce67dce73d8a88bcb0008211bc6cd5493822818bfc208b8737ae38874184f834301de26e537694cfdc0abaccc2702820ee58cbba243aac685681329705999f4d77e596615293eb642ec450f149caabfab55092fc0315ec4157d322813ba9790c0f46c6805b8e1c0f21b6211c3529e6d7cc
DigestSign = SHA384
Key = RSA-2048
Input = "Hello World"
Output = 041348caa7ffaa7dce1ac67567c408967a1736dd44ff73076570a63c4c7128ff09f716918b81fdfaa160368bc8b85c23466f8c0d4172da880386b75065f541c0fb6c9355a1731532ebab9cf5026cafe03a790bc1698586fbdff5f6e8f1a7148b07f1f895a99d0f041b8b36d8ffdd5e77ba36e5177610e0825ba78594f95826dabdc95f682da04edf0d133c55e78fa386dea9dbc1cf748e768e9116976476e75a84b5510d869beac9a1a9ffc579a28629154b24ee9df8d51fee479f4dca5646a2032c27206ad30f4937fc096c41362562bee74562132a4f471bb4b4c76e774be0e9eca9412809665ab13951d3699b3a7ccb6714a0f070345f6f3e037bd0f8ae52
DigestSign = SHA512
Key = RSA-2048
Input = "Hello World"
Output = 32e1f87fcd81a9d5a9f988087cdb3931fe0b12197d501b9c958cc1614a236e71a00ee7c96f7d5b3ae5ae3f11e40df5d06b0a818ee2a573aa1459f7f14dc22ca0b0b0ad2d47f4ab9e479baa084973b69f74f691ee700af102aceaf788e513f0e942a862bc6884ef1efb993b11d2ebd95139c61c37f8eac3edd94a4d8a358842f17da6d2971b8141a70097a1de569751eb4533e27880206fb8f8e1ac995688ca6facc85ed116becea9d3c4d0e96b2cb4b422b21c81328a335441d897c7deebf0f605ef086cfc5d81d1ab30ac04f674993511b142ea7ad43a8d3b7b1d2d26ce4a93413b690afdb1718408379fbd002a3c569bf11f0c10ce7cb46e257ce6b62ef62b
DigestSign = SHA512-224
Key = RSA-2048
Input = "Hello World"
Output = 8f20f0f2389408cfb7f4b47c299ca610c34a2ad20664378530ecf977c3243ce5f01c71296d2101dc962853a27f64a228eea92fee05780be31cdd7fe648d39f136de1dd857609d0d54d0de52c5cdf09d95986d808d1c92dcb3e8e96848af788c959927196316fcc56b884d34711a2a947b7e806caf7a2b05314f0c726b5e083baa0b341ac6515529bf6b3a7098a635c865e8d4b05af68fb3e893feb12ac7c4d667e1233f2e39449c285d4ad2a809e687f68ef66daf710e7d21e97833372c251bc0b45bc79c8bfe4087f16662875c2fc91a02d11078556a2b3232617406fbd947b9d95c193742ac4bb1858934ed7288cd0327c678b5295c682a4d2ba91d8fafae7
DigestSign = SHA512-256
Key = RSA-2048
Input = "Hello World"
Output = 00904130234e4e1a51060f7747ab26ca766c64cff1df97e4d0f432169046da422305ddea16b96e0d8fcc5ab651ac247d1b65283f2f27e7e97538e9f6b77f9558c9885d5ddacaf4d6ca600ad61693766498fa815361cd1debe2d71a5af77da71f8bd72d2f5cf741aa177a2dc44107f5887d95b217c67dbc5a4874f9aa8de1fc8a5645815c561edcb348db6458018096a99a98f5d2e677f068c9093618e28f532a97e8d6161aec002d5273884ce8b46f077d37b1e158de682a927126952bdbb6b6dfdf47d7e34a7d9c9b1395315586a11ceadfb72c021b28e28b8397bc9086418a45cb8c1ad46ef47f1c2bedb14b50e50b58bd607992e1d19b895119c6a62471b4
DigestSign = SHA3-224
Key = RSA-2048
Input = "Hello World"
Output = 5b6f6834356ba08ef649d822592d7a3d889995283e3752760b0728ed99aa05af901298159485a690f8dab21c850946ef2376bedcc87f403288039e1eb18dfdf4ac1075753528c94b5a8b11f74513ef64eddc215f7df97d977e788fd93db4063529fd87f583c1c98d39cd79178330bae7980d9a846acdf3bdd77a864f85b77941b375c076ff86def44b8da19b5de6131bb8894c870d4deeb62361bd429faad97530abab33795912d63f2fb886b25f1a1d9583fae3b7cf6dd6a5addd1b28320ab88a4dac2d938fb50b6c9115c7a0a4edd6b7b3453e435605839703f0b0c6e58f7bb73ef0fb38cab4f2d9dc1fd8b8b77b36ae945dea7563eaa33608781ce5ac181b
DigestSign = SHA3-256
Key = RSA-2048
Input = "Hello World"
Output = c531d0db6635b7c58c7118641565796c3d61323e303246cfc39e4e697727fede52b029407f82aa07e25c4833d18ec6ef6b585f3f078ca1494ae80a696fec701e1c2386196100cc5879fb8ea77f07b7019185258e1ad632c28cc672a61296787bb16a0e4f259d6eac1960f7eaaee1f7ab7eea3cf2d9e11435859630f0c71c48c8655b1252e072f18831731b2bc8e788a722c77db57583c7456e9b7fd5273e6781e214616620084dfefffe506910a39087912c3a8586fce65d8a0b1e5803ffe59b53537119653d708a55ef17d2721b9c8c183fe6750991b0e77b79d8d208ad750b2bc3426fbeeebf9b090bfc19f6534e44bf6d7d2f2e1dc2594b38ceda420553c9
DigestSign = SHA3-384
Key = RSA-2048
Input = "Hello World"
Output = 78bc11342fd44b4c047a365cc6ef78476bf28547da4eafec09f6bdf68a5593e993716662801b313515d80ddd232dfcc414cf896349a0237976dd89a97a9c88a92cd86992996d9c2747bf4e5dff5acb2fc67aa51ceb27ed1b95edd952d8eab3055cdc576a860593308c426f7ea73e01bd05fb20a4fcb64b10945e1684da67a8367826535344ad25057b4840e138909668c2423669b51f2fec631fd7e919f6e8b82ee293878894cac6a58b21f2168ba6335197e39e587fd60076a369f0b8e779c045c507654fbb98f5ffc998f720ab48bdbfe6d397aa63c7209b45068e24b65371180ff6d775851b2aaceac393082920fffb9e8b6999c682875bd0eff231dfaadf
DigestSign = SHA3-512
Key = RSA-2048
Input = "Hello World"
Output = 4681312b0e27e4e5f2dd3165ea5bdc98210d4883709a842239cef72099d71855fc322c3d2f74a7e7357647de153c22e4c4f9a0e4f1ce9b7f993242df5ee778ca949e6e184551e87e0aac8440ae990ef76a14f6056a16181390ad3a150bfdbb985cfe4cca3255b5eb0871116654d59fc89f69adb46c307b927c51a5f34069a2f43c854fde8e2df0ded10f8e257d1d800aa44bf31981f93c062128cc551ad7f5f7ba68e9d7c917c8fc51bcda3ce9192680c1e5308bd5c571ac0a5ae7347a897e8698ea94059562cd3035e3ed5fcf6c4ca8c20f58a079dfcdb175242a5726237d1b92378ec7dc4f2db09a0fbd62d1ab6d1a3d0be7afd34ed9c3ecd1bc5a3d2c448c
Title = Test RSA keypair mismatches
PrivateKey = RSA-2048-BIS
-----BEGIN PRIVATE KEY-----
MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCytEHg4qzeBrqu
1haSf0xOttQeyburRKC4N4KJIbtQbooYS6M7C9mvXdz4vA7PtgXS6L4gDTH2Bpa5
qvbAYQ7CbmssmkciN/bqxMqecsuN49uMRF2Yy40UYCKv+wv6fGbCsrczDc5kfRu2
XzKHewAKF9EZYkKLNfLjT+jQAogdfmnShDQPWus7t+9RbuZPrg/iz/urQGfTEarW
8yFl6jJd88cjASrGCCxTCL2BLuimLrSauF/Na9K1Jmxst+lqXKhf4YYtf5ARgDBn
oOfZl24ts9twBXD6hjfhVh3wOPJL3+EKOORBclHixQ47Kx9ermb6hQDv0AyRoXyp
6Jy7gkLxAgMBAAECggEAeDWjXxh7+nqCV5ux4Wf6N7Tqqa9AK6xlhKXqjD6Bl1BU
WpV+vvhwvXOhcjxmpjimYEKpqjvWEM5L06d6htyDJi1KsN0y3oTQ9wnb1owX+2F8
TTWr1F2QkFU+4Cw62YuXQH8hlxlBbf1uh9Yv0kzeMOvmf3HGm4h104zsaghZ8aP4
Tmmeqnc+ty3iQkjDLIXEaHYIZ1AZ7fzc/rc6kbkWGkVAgCP1CDIm3q586OZDQz0E
hgLhWHgJQ5Z2m9Qw/hROJeesKHtq19GFafIBANDelB/yG8p+dCqPQsg6nm24jAHO
pT1EipOWwLnsTBsa9BlcCYeBpqNIPV4ST+X4Que59QKBgQDjublne/+/i7dQLpCT
01fzbkDEIV2s7jVpEz0imzT6HXIeHBpOmS7GHlurN7WLUcbB5QUEgzNxA08x80o1
oU9b/jUpFBJRudyIKX8aSBVSInOXw1eQNjkqBZdUVN1ADeS/HYRYnPhIB4w31XgJ
ujc9udPtn2GqWfKXrG5abfXfdwKBgQDI5GJ/8kh4nxtC7SvcJNfbRtC/03f0vJQj
600vCU8X+wkk1EMtnHU/A/oOhZey/zdc03h3UuwznOER8KWLB8/XidRZnT9NgMGb
sO7sNPyTfMep+jLcolv1SAThjQxAVxCkvl87GFGvGnBCTtLWMEWpazl8XH+aHgyn
1NU/VJqa1wKBgD5Nb6YaTKwRA4QSWUe4SJW3Ek0We9R2D3LB6rXvFJ1hNPl74s6i
JiPZ5mZ/hVGqe+BMUgUcCBThPOeDkkf97AJVGCI29ZQab3VpNPbxxbOE7W8V6Hzx
+M3AXdiapzWBF5YZ8z1zJJJATmJwKrkukzJ2Br86HbRHi5FngYGIF/6dAoGAE/32
d3krESX0VpK3vK7F9IJ1n8FxvJ9Ptsth4P5yKpbG8C1XiiB54o2Iww00bZHMdqZs
5KMR8oj4NQrXzqA2ZOLIiSqG9DWODupqvIMBZ8QRMq89hIt7z0sdgTzCLVz8wQhY
/c6LwntFFLQ3cy1WoWeUTvX9lN7Mr58UobrPr/0CgYEA31WYhr/TH7sBG5tlUvuK
1KYMRwh1HR3lMnuCzAFOEtIJhSG/GtWyPtlYzYWvYGEukBO5+QSoB9K+jNEm6tNw
mRsMet399ylSQMkmPIfXldQvDF/9AvXBCR+EttZDr2Dw0Haeu4PGwT3WgqGHDWz5
vOpxAsEe+k0AI8MnJvlO8uw=
-----END PRIVATE KEY-----
PublicKey = RSA-2048-BIS-PUBLIC
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsrRB4OKs3ga6rtYWkn9M
TrbUHsm7q0SguDeCiSG7UG6KGEujOwvZr13c+LwOz7YF0ui+IA0x9gaWuar2wGEO
wm5rLJpHIjf26sTKnnLLjePbjERdmMuNFGAir/sL+nxmwrK3Mw3OZH0btl8yh3sA
ChfRGWJCizXy40/o0AKIHX5p0oQ0D1rrO7fvUW7mT64P4s/7q0Bn0xGq1vMhZeoy
XfPHIwEqxggsUwi9gS7opi60mrhfzWvStSZsbLfpalyoX+GGLX+QEYAwZ6Dn2Zdu
LbPbcAVw+oY34VYd8DjyS9/hCjjkQXJR4sUOOysfXq5m+oUA79AMkaF8qeicu4JC
8QIDAQAB
-----END PUBLIC KEY-----
PrivPubKeyPair = RSA-2048-BIS:RSA-2048-BIS-PUBLIC
PrivPubKeyPair = RSA-2048-BIS:RSA-2048-PUBLIC
Result = KEYPAIR_MISMATCH
Title = Test RSA keygen
# Key generation tests
# RSA-PSS with restrictions, should succeed.
KeyGen = RSASSA-PSS
KeyName = tmppss
Ctrl = rsa_pss_keygen_md:sha256
Ctrl = rsa_pss_keygen_mgf1_md:sha512
# Check MGF1 restrictions
DigestVerify = SHA256
Key = tmppss
Ctrl = rsa_mgf1_md:sha256
Result = PKEY_CTRL_ERROR
# Test valid digest and MGF1 parameters. Verify will fail
DigestVerify = SHA256
Key = tmppss
Ctrl = rsa_mgf1_md:sha512
Input = ""
Output = ""
Result = VERIFY_ERROR
# Check caching of key MGF1 digest restriction
DigestVerify = SHA256
Key = tmppss
Ctrl = rsa_mgf1_md:sha1
Result = PKEY_CTRL_ERROR
Title = RSA FIPS tests
# FIPS tests
# Verifying with SHA1 is permitted in fips mode for older applications
DigestVerify = SHA1
Key = RSA-2048
Input = "Hello "
Output = 87ea0e2226ef35e5a2aec9ca1222fcbe39ba723f05b3203564f671dd3601271806ead3240e61d424359ee3b17bd3e32f54b82df83998a8ac4148410710361de0400f9ddf98278618fbc87747a0531972543e6e5f18ab2fdfbfda02952f6ac69690e43864690af271bf43d4be9705b303d4ff994ab3abd4d5851562b73e59be3edc01cec41a4cc13b68206329bad1a46c6608d3609e951faa321d0fdbc765d54e9a7c59248d2f67913c9903e932b769c9c8a45520cabea06e8c0b231dd3bcc7f7ec55b46b0157ccb5fc5011fa57353cd3df32edcbadcb8d168133cbd0acfb64444cb040e1298f621508a38f79e14ae8c2c5c857f90aa9d24ef5fc07d34bf23859
# Verifying with a 1024 bit key is permitted in fips mode for older applications
DigestVerify = SHA256
Key = RSA-1024
Input = "Hello"
Output = 80382819f51b197c42f9fc02a85198683d918059afc013ae155992442563dd2897008297fecb3a8d8cf9421d493a99bd427a628f17cc4a7c76d23dfad0619f4068403fa7351f6d5a92a631d670c04407f305a4b5cb492295754e73e9b7ad41459826d3619a61e90d4744bdaf0f24f2393ea9241e973600c2ed62b1a0a37c504e
# Signing with SHA1 is not allowed in fips mode
Availablein = fips
+FIPSversion = <3.4.0
DigestSign = SHA1
Securitycheck = 1
Key = RSA-2048
Input = "Hello"
Result = DIGESTSIGNINIT_ERROR
# Signing with a 1024 bit key is not allowed in fips mode
Availablein = fips
DigestSign = SHA256
Securitycheck = 1
Key = RSA-1024
Input = "Hello"
Result = DIGESTSIGNINIT_ERROR
# Verifying with a legacy digest in fips mode is not allowed
Availablein = fips
DigestVerify = MD5
Securitycheck = 1
Key = RSA-2048
Input = "Hello"
Result = DIGESTVERIFYINIT_ERROR
# Verifying with a key smaller than 1024 bits in fips mode is not allowed
Availablein = fips
DigestVerify = SHA256
Securitycheck = 1
Key = RSA-512
Input = "Hello"
Result = DIGESTVERIFYINIT_ERROR
diff --git a/crypto/openssl/test/recipes/70-test_npn.t b/crypto/openssl/test/recipes/70-test_npn.t
new file mode 100644
index 000000000000..f82e71af6aca
--- /dev/null
+++ b/crypto/openssl/test/recipes/70-test_npn.t
@@ -0,0 +1,73 @@
+#! /usr/bin/env perl
+# Copyright 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 OpenSSL::Test qw/:DEFAULT cmdstr srctop_file/;
+use OpenSSL::Test::Utils;
+
+use TLSProxy::Proxy;
+
+my $test_name = "test_npn";
+setup($test_name);
+
+plan skip_all => "TLSProxy isn't usable on $^O"
+ if $^O =~ /^(VMS)$/;
+
+plan skip_all => "$test_name needs the dynamic engine feature enabled"
+ if disabled("engine") || disabled("dynamic-engine");
+
+plan skip_all => "$test_name needs the sock feature enabled"
+ if disabled("sock");
+
+plan skip_all => "$test_name needs NPN enabled"
+ if disabled("nextprotoneg");
+
+plan skip_all => "$test_name needs TLSv1.2 enabled"
+ if disabled("tls1_2");
+
+my $proxy = TLSProxy::Proxy->new(
+ undef,
+ cmdstr(app(["openssl"]), display => 1),
+ srctop_file("apps", "server.pem"),
+ (!$ENV{HARNESS_ACTIVE} || $ENV{HARNESS_VERBOSE})
+);
+
+$proxy->start() or plan skip_all => "Unable to start up Proxy for tests";
+plan tests => 1;
+
+my $npnseen = 0;
+
+# Test 1: Check sending an empty NextProto message from the client works. This is
+# valid as per the spec, but OpenSSL does not allow you to send it.
+# Therefore we must be prepared to receive such a message but we cannot
+# generate it except via TLSProxy
+$proxy->clear();
+$proxy->filter(\&npn_filter);
+$proxy->clientflags("-nextprotoneg foo -no_tls1_3");
+$proxy->serverflags("-nextprotoneg foo");
+$proxy->start();
+ok($npnseen && TLSProxy::Message->success(), "Empty NPN message");
+
+sub npn_filter
+{
+ my $proxy = shift;
+ my $message;
+
+ # The NextProto message always appears in flight 2
+ return if $proxy->flight != 2;
+
+ foreach my $message (@{$proxy->message_list}) {
+ if ($message->mt == TLSProxy::Message::MT_NEXT_PROTO) {
+ # Our TLSproxy NextProto message support doesn't support parsing of
+ # the message. If we repack it just creates an empty NextProto
+ # message - which is exactly the scenario we want to test here.
+ $message->repack();
+ $npnseen = 1;
+ }
+ }
+}
diff --git a/crypto/openssl/test/ssl-tests/08-npn.cnf b/crypto/openssl/test/ssl-tests/08-npn.cnf
index f38b3f6975ce..1931d02de4ba 100644
--- a/crypto/openssl/test/ssl-tests/08-npn.cnf
+++ b/crypto/openssl/test/ssl-tests/08-npn.cnf
@@ -1,816 +1,883 @@
# Generated with generate_ssl_tests.pl
-num_tests = 20
+num_tests = 22
test-0 = 0-npn-simple
test-1 = 1-npn-client-finds-match
test-2 = 2-npn-client-honours-server-pref
test-3 = 3-npn-client-first-pref-on-mismatch
test-4 = 4-npn-no-server-support
test-5 = 5-npn-no-client-support
-test-6 = 6-npn-with-sni-no-context-switch
-test-7 = 7-npn-with-sni-context-switch
-test-8 = 8-npn-selected-sni-server-supports-npn
-test-9 = 9-npn-selected-sni-server-does-not-support-npn
-test-10 = 10-alpn-preferred-over-npn
-test-11 = 11-sni-npn-preferred-over-alpn
-test-12 = 12-npn-simple-resumption
-test-13 = 13-npn-server-switch-resumption
-test-14 = 14-npn-client-switch-resumption
-test-15 = 15-npn-client-first-pref-on-mismatch-resumption
-test-16 = 16-npn-no-server-support-resumption
-test-17 = 17-npn-no-client-support-resumption
-test-18 = 18-alpn-preferred-over-npn-resumption
-test-19 = 19-npn-used-if-alpn-not-supported-resumption
+test-6 = 6-npn-empty-client-list
+test-7 = 7-npn-empty-server-list
+test-8 = 8-npn-with-sni-no-context-switch
+test-9 = 9-npn-with-sni-context-switch
+test-10 = 10-npn-selected-sni-server-supports-npn
+test-11 = 11-npn-selected-sni-server-does-not-support-npn
+test-12 = 12-alpn-preferred-over-npn
+test-13 = 13-sni-npn-preferred-over-alpn
+test-14 = 14-npn-simple-resumption
+test-15 = 15-npn-server-switch-resumption
+test-16 = 16-npn-client-switch-resumption
+test-17 = 17-npn-client-first-pref-on-mismatch-resumption
+test-18 = 18-npn-no-server-support-resumption
+test-19 = 19-npn-no-client-support-resumption
+test-20 = 20-alpn-preferred-over-npn-resumption
+test-21 = 21-npn-used-if-alpn-not-supported-resumption
# ===========================================================
[0-npn-simple]
ssl_conf = 0-npn-simple-ssl
[0-npn-simple-ssl]
server = 0-npn-simple-server
client = 0-npn-simple-client
[0-npn-simple-server]
Certificate = ${ENV::TEST_CERTS_DIR}/servercert.pem
CipherString = DEFAULT
PrivateKey = ${ENV::TEST_CERTS_DIR}/serverkey.pem
[0-npn-simple-client]
CipherString = DEFAULT
MaxProtocol = TLSv1.2
VerifyCAFile = ${ENV::TEST_CERTS_DIR}/rootcert.pem
VerifyMode = Peer
[test-0]
ExpectedNPNProtocol = foo
server = 0-npn-simple-server-extra
client = 0-npn-simple-client-extra
[0-npn-simple-server-extra]
NPNProtocols = foo
[0-npn-simple-client-extra]
NPNProtocols = foo
# ===========================================================
[1-npn-client-finds-match]
ssl_conf = 1-npn-client-finds-match-ssl
[1-npn-client-finds-match-ssl]
server = 1-npn-client-finds-match-server
client = 1-npn-client-finds-match-client
[1-npn-client-finds-match-server]
Certificate = ${ENV::TEST_CERTS_DIR}/servercert.pem
CipherString = DEFAULT
PrivateKey = ${ENV::TEST_CERTS_DIR}/serverkey.pem
[1-npn-client-finds-match-client]
CipherString = DEFAULT
MaxProtocol = TLSv1.2
VerifyCAFile = ${ENV::TEST_CERTS_DIR}/rootcert.pem
VerifyMode = Peer
[test-1]
ExpectedNPNProtocol = bar
server = 1-npn-client-finds-match-server-extra
client = 1-npn-client-finds-match-client-extra
[1-npn-client-finds-match-server-extra]
NPNProtocols = baz,bar
[1-npn-client-finds-match-client-extra]
NPNProtocols = foo,bar
# ===========================================================
[2-npn-client-honours-server-pref]
ssl_conf = 2-npn-client-honours-server-pref-ssl
[2-npn-client-honours-server-pref-ssl]
server = 2-npn-client-honours-server-pref-server
client = 2-npn-client-honours-server-pref-client
[2-npn-client-honours-server-pref-server]
Certificate = ${ENV::TEST_CERTS_DIR}/servercert.pem
CipherString = DEFAULT
PrivateKey = ${ENV::TEST_CERTS_DIR}/serverkey.pem
[2-npn-client-honours-server-pref-client]
CipherString = DEFAULT
MaxProtocol = TLSv1.2
VerifyCAFile = ${ENV::TEST_CERTS_DIR}/rootcert.pem
VerifyMode = Peer
[test-2]
ExpectedNPNProtocol = bar
server = 2-npn-client-honours-server-pref-server-extra
client = 2-npn-client-honours-server-pref-client-extra
[2-npn-client-honours-server-pref-server-extra]
NPNProtocols = bar,foo
[2-npn-client-honours-server-pref-client-extra]
NPNProtocols = foo,bar
# ===========================================================
[3-npn-client-first-pref-on-mismatch]
ssl_conf = 3-npn-client-first-pref-on-mismatch-ssl
[3-npn-client-first-pref-on-mismatch-ssl]
server = 3-npn-client-first-pref-on-mismatch-server
client = 3-npn-client-first-pref-on-mismatch-client
[3-npn-client-first-pref-on-mismatch-server]
Certificate = ${ENV::TEST_CERTS_DIR}/servercert.pem
CipherString = DEFAULT
PrivateKey = ${ENV::TEST_CERTS_DIR}/serverkey.pem
[3-npn-client-first-pref-on-mismatch-client]
CipherString = DEFAULT
MaxProtocol = TLSv1.2
VerifyCAFile = ${ENV::TEST_CERTS_DIR}/rootcert.pem
VerifyMode = Peer
[test-3]
ExpectedNPNProtocol = foo
server = 3-npn-client-first-pref-on-mismatch-server-extra
client = 3-npn-client-first-pref-on-mismatch-client-extra
[3-npn-client-first-pref-on-mismatch-server-extra]
NPNProtocols = baz
[3-npn-client-first-pref-on-mismatch-client-extra]
NPNProtocols = foo,bar
# ===========================================================
[4-npn-no-server-support]
ssl_conf = 4-npn-no-server-support-ssl
[4-npn-no-server-support-ssl]
server = 4-npn-no-server-support-server
client = 4-npn-no-server-support-client
[4-npn-no-server-support-server]
Certificate = ${ENV::TEST_CERTS_DIR}/servercert.pem
CipherString = DEFAULT
PrivateKey = ${ENV::TEST_CERTS_DIR}/serverkey.pem
[4-npn-no-server-support-client]
CipherString = DEFAULT
MaxProtocol = TLSv1.2
VerifyCAFile = ${ENV::TEST_CERTS_DIR}/rootcert.pem
VerifyMode = Peer
[test-4]
client = 4-npn-no-server-support-client-extra
[4-npn-no-server-support-client-extra]
NPNProtocols = foo
# ===========================================================
[5-npn-no-client-support]
ssl_conf = 5-npn-no-client-support-ssl
[5-npn-no-client-support-ssl]
server = 5-npn-no-client-support-server
client = 5-npn-no-client-support-client
[5-npn-no-client-support-server]
Certificate = ${ENV::TEST_CERTS_DIR}/servercert.pem
CipherString = DEFAULT
PrivateKey = ${ENV::TEST_CERTS_DIR}/serverkey.pem
[5-npn-no-client-support-client]
CipherString = DEFAULT
MaxProtocol = TLSv1.2
VerifyCAFile = ${ENV::TEST_CERTS_DIR}/rootcert.pem
VerifyMode = Peer
[test-5]
server = 5-npn-no-client-support-server-extra
[5-npn-no-client-support-server-extra]
NPNProtocols = foo
# ===========================================================
-[6-npn-with-sni-no-context-switch]
-ssl_conf = 6-npn-with-sni-no-context-switch-ssl
+[6-npn-empty-client-list]
+ssl_conf = 6-npn-empty-client-list-ssl
-[6-npn-with-sni-no-context-switch-ssl]
-server = 6-npn-with-sni-no-context-switch-server
-client = 6-npn-with-sni-no-context-switch-client
-server2 = 6-npn-with-sni-no-context-switch-server2
+[6-npn-empty-client-list-ssl]
+server = 6-npn-empty-client-list-server
+client = 6-npn-empty-client-list-client
-[6-npn-with-sni-no-context-switch-server]
+[6-npn-empty-client-list-server]
Certificate = ${ENV::TEST_CERTS_DIR}/servercert.pem
CipherString = DEFAULT
PrivateKey = ${ENV::TEST_CERTS_DIR}/serverkey.pem
-[6-npn-with-sni-no-context-switch-server2]
+[6-npn-empty-client-list-client]
+CipherString = DEFAULT
+MaxProtocol = TLSv1.2
+VerifyCAFile = ${ENV::TEST_CERTS_DIR}/rootcert.pem
+VerifyMode = Peer
+
+[test-6]
+ExpectedClientAlert = HandshakeFailure
+ExpectedResult = ClientFail
+server = 6-npn-empty-client-list-server-extra
+client = 6-npn-empty-client-list-client-extra
+
+[6-npn-empty-client-list-server-extra]
+NPNProtocols = foo
+
+[6-npn-empty-client-list-client-extra]
+NPNProtocols =
+
+
+# ===========================================================
+
+[7-npn-empty-server-list]
+ssl_conf = 7-npn-empty-server-list-ssl
+
+[7-npn-empty-server-list-ssl]
+server = 7-npn-empty-server-list-server
+client = 7-npn-empty-server-list-client
+
+[7-npn-empty-server-list-server]
Certificate = ${ENV::TEST_CERTS_DIR}/servercert.pem
CipherString = DEFAULT
PrivateKey = ${ENV::TEST_CERTS_DIR}/serverkey.pem
-[6-npn-with-sni-no-context-switch-client]
+[7-npn-empty-server-list-client]
CipherString = DEFAULT
MaxProtocol = TLSv1.2
VerifyCAFile = ${ENV::TEST_CERTS_DIR}/rootcert.pem
VerifyMode = Peer
-[test-6]
+[test-7]
+ExpectedNPNProtocol = foo
+server = 7-npn-empty-server-list-server-extra
+client = 7-npn-empty-server-list-client-extra
+
+[7-npn-empty-server-list-server-extra]
+NPNProtocols =
+
+[7-npn-empty-server-list-client-extra]
+NPNProtocols = foo
+
+
+# ===========================================================
+
+[8-npn-with-sni-no-context-switch]
+ssl_conf = 8-npn-with-sni-no-context-switch-ssl
+
+[8-npn-with-sni-no-context-switch-ssl]
+server = 8-npn-with-sni-no-context-switch-server
+client = 8-npn-with-sni-no-context-switch-client
+server2 = 8-npn-with-sni-no-context-switch-server2
+
+[8-npn-with-sni-no-context-switch-server]
+Certificate = ${ENV::TEST_CERTS_DIR}/servercert.pem
+CipherString = DEFAULT
+PrivateKey = ${ENV::TEST_CERTS_DIR}/serverkey.pem
+
+[8-npn-with-sni-no-context-switch-server2]
+Certificate = ${ENV::TEST_CERTS_DIR}/servercert.pem
+CipherString = DEFAULT
+PrivateKey = ${ENV::TEST_CERTS_DIR}/serverkey.pem
+
+[8-npn-with-sni-no-context-switch-client]
+CipherString = DEFAULT
+MaxProtocol = TLSv1.2
+VerifyCAFile = ${ENV::TEST_CERTS_DIR}/rootcert.pem
+VerifyMode = Peer
+
+[test-8]
ExpectedNPNProtocol = foo
ExpectedServerName = server1
-server = 6-npn-with-sni-no-context-switch-server-extra
-server2 = 6-npn-with-sni-no-context-switch-server2-extra
-client = 6-npn-with-sni-no-context-switch-client-extra
+server = 8-npn-with-sni-no-context-switch-server-extra
+server2 = 8-npn-with-sni-no-context-switch-server2-extra
+client = 8-npn-with-sni-no-context-switch-client-extra
-[6-npn-with-sni-no-context-switch-server-extra]
+[8-npn-with-sni-no-context-switch-server-extra]
NPNProtocols = foo
ServerNameCallback = IgnoreMismatch
-[6-npn-with-sni-no-context-switch-server2-extra]
+[8-npn-with-sni-no-context-switch-server2-extra]
NPNProtocols = bar
-[6-npn-with-sni-no-context-switch-client-extra]
+[8-npn-with-sni-no-context-switch-client-extra]
NPNProtocols = foo,bar
ServerName = server1
# ===========================================================
-[7-npn-with-sni-context-switch]
-ssl_conf = 7-npn-with-sni-context-switch-ssl
+[9-npn-with-sni-context-switch]
+ssl_conf = 9-npn-with-sni-context-switch-ssl
-[7-npn-with-sni-context-switch-ssl]
-server = 7-npn-with-sni-context-switch-server
-client = 7-npn-with-sni-context-switch-client
-server2 = 7-npn-with-sni-context-switch-server2
+[9-npn-with-sni-context-switch-ssl]
+server = 9-npn-with-sni-context-switch-server
+client = 9-npn-with-sni-context-switch-client
+server2 = 9-npn-with-sni-context-switch-server2
-[7-npn-with-sni-context-switch-server]
+[9-npn-with-sni-context-switch-server]
Certificate = ${ENV::TEST_CERTS_DIR}/servercert.pem
CipherString = DEFAULT
PrivateKey = ${ENV::TEST_CERTS_DIR}/serverkey.pem
-[7-npn-with-sni-context-switch-server2]
+[9-npn-with-sni-context-switch-server2]
Certificate = ${ENV::TEST_CERTS_DIR}/servercert.pem
CipherString = DEFAULT
PrivateKey = ${ENV::TEST_CERTS_DIR}/serverkey.pem
-[7-npn-with-sni-context-switch-client]
+[9-npn-with-sni-context-switch-client]
CipherString = DEFAULT
MaxProtocol = TLSv1.2
VerifyCAFile = ${ENV::TEST_CERTS_DIR}/rootcert.pem
VerifyMode = Peer
-[test-7]
+[test-9]
ExpectedNPNProtocol = bar
ExpectedServerName = server2
-server = 7-npn-with-sni-context-switch-server-extra
-server2 = 7-npn-with-sni-context-switch-server2-extra
-client = 7-npn-with-sni-context-switch-client-extra
+server = 9-npn-with-sni-context-switch-server-extra
+server2 = 9-npn-with-sni-context-switch-server2-extra
+client = 9-npn-with-sni-context-switch-client-extra
-[7-npn-with-sni-context-switch-server-extra]
+[9-npn-with-sni-context-switch-server-extra]
NPNProtocols = foo
ServerNameCallback = IgnoreMismatch
-[7-npn-with-sni-context-switch-server2-extra]
+[9-npn-with-sni-context-switch-server2-extra]
NPNProtocols = bar
-[7-npn-with-sni-context-switch-client-extra]
+[9-npn-with-sni-context-switch-client-extra]
NPNProtocols = foo,bar
ServerName = server2
# ===========================================================
-[8-npn-selected-sni-server-supports-npn]
-ssl_conf = 8-npn-selected-sni-server-supports-npn-ssl
+[10-npn-selected-sni-server-supports-npn]
+ssl_conf = 10-npn-selected-sni-server-supports-npn-ssl
-[8-npn-selected-sni-server-supports-npn-ssl]
-server = 8-npn-selected-sni-server-supports-npn-server
-client = 8-npn-selected-sni-server-supports-npn-client
-server2 = 8-npn-selected-sni-server-supports-npn-server2
+[10-npn-selected-sni-server-supports-npn-ssl]
+server = 10-npn-selected-sni-server-supports-npn-server
+client = 10-npn-selected-sni-server-supports-npn-client
+server2 = 10-npn-selected-sni-server-supports-npn-server2
-[8-npn-selected-sni-server-supports-npn-server]
+[10-npn-selected-sni-server-supports-npn-server]
Certificate = ${ENV::TEST_CERTS_DIR}/servercert.pem
CipherString = DEFAULT
PrivateKey = ${ENV::TEST_CERTS_DIR}/serverkey.pem
-[8-npn-selected-sni-server-supports-npn-server2]
+[10-npn-selected-sni-server-supports-npn-server2]
Certificate = ${ENV::TEST_CERTS_DIR}/servercert.pem
CipherString = DEFAULT
PrivateKey = ${ENV::TEST_CERTS_DIR}/serverkey.pem
-[8-npn-selected-sni-server-supports-npn-client]
+[10-npn-selected-sni-server-supports-npn-client]
CipherString = DEFAULT
MaxProtocol = TLSv1.2
VerifyCAFile = ${ENV::TEST_CERTS_DIR}/rootcert.pem
VerifyMode = Peer
-[test-8]
+[test-10]
ExpectedNPNProtocol = bar
ExpectedServerName = server2
-server = 8-npn-selected-sni-server-supports-npn-server-extra
-server2 = 8-npn-selected-sni-server-supports-npn-server2-extra
-client = 8-npn-selected-sni-server-supports-npn-client-extra
+server = 10-npn-selected-sni-server-supports-npn-server-extra
+server2 = 10-npn-selected-sni-server-supports-npn-server2-extra
+client = 10-npn-selected-sni-server-supports-npn-client-extra
-[8-npn-selected-sni-server-supports-npn-server-extra]
+[10-npn-selected-sni-server-supports-npn-server-extra]
ServerNameCallback = IgnoreMismatch
-[8-npn-selected-sni-server-supports-npn-server2-extra]
+[10-npn-selected-sni-server-supports-npn-server2-extra]
NPNProtocols = bar
-[8-npn-selected-sni-server-supports-npn-client-extra]
+[10-npn-selected-sni-server-supports-npn-client-extra]
NPNProtocols = foo,bar
ServerName = server2
# ===========================================================
-[9-npn-selected-sni-server-does-not-support-npn]
-ssl_conf = 9-npn-selected-sni-server-does-not-support-npn-ssl
+[11-npn-selected-sni-server-does-not-support-npn]
+ssl_conf = 11-npn-selected-sni-server-does-not-support-npn-ssl
-[9-npn-selected-sni-server-does-not-support-npn-ssl]
-server = 9-npn-selected-sni-server-does-not-support-npn-server
-client = 9-npn-selected-sni-server-does-not-support-npn-client
-server2 = 9-npn-selected-sni-server-does-not-support-npn-server2
+[11-npn-selected-sni-server-does-not-support-npn-ssl]
+server = 11-npn-selected-sni-server-does-not-support-npn-server
+client = 11-npn-selected-sni-server-does-not-support-npn-client
+server2 = 11-npn-selected-sni-server-does-not-support-npn-server2
-[9-npn-selected-sni-server-does-not-support-npn-server]
+[11-npn-selected-sni-server-does-not-support-npn-server]
Certificate = ${ENV::TEST_CERTS_DIR}/servercert.pem
CipherString = DEFAULT
PrivateKey = ${ENV::TEST_CERTS_DIR}/serverkey.pem
-[9-npn-selected-sni-server-does-not-support-npn-server2]
+[11-npn-selected-sni-server-does-not-support-npn-server2]
Certificate = ${ENV::TEST_CERTS_DIR}/servercert.pem
CipherString = DEFAULT
PrivateKey = ${ENV::TEST_CERTS_DIR}/serverkey.pem
-[9-npn-selected-sni-server-does-not-support-npn-client]
+[11-npn-selected-sni-server-does-not-support-npn-client]
CipherString = DEFAULT
MaxProtocol = TLSv1.2
VerifyCAFile = ${ENV::TEST_CERTS_DIR}/rootcert.pem
VerifyMode = Peer
-[test-9]
+[test-11]
ExpectedServerName = server2
-server = 9-npn-selected-sni-server-does-not-support-npn-server-extra
-client = 9-npn-selected-sni-server-does-not-support-npn-client-extra
+server = 11-npn-selected-sni-server-does-not-support-npn-server-extra
+client = 11-npn-selected-sni-server-does-not-support-npn-client-extra
-[9-npn-selected-sni-server-does-not-support-npn-server-extra]
+[11-npn-selected-sni-server-does-not-support-npn-server-extra]
NPNProtocols = bar
ServerNameCallback = IgnoreMismatch
-[9-npn-selected-sni-server-does-not-support-npn-client-extra]
+[11-npn-selected-sni-server-does-not-support-npn-client-extra]
NPNProtocols = foo,bar
ServerName = server2
# ===========================================================
-[10-alpn-preferred-over-npn]
-ssl_conf = 10-alpn-preferred-over-npn-ssl
+[12-alpn-preferred-over-npn]
+ssl_conf = 12-alpn-preferred-over-npn-ssl
-[10-alpn-preferred-over-npn-ssl]
-server = 10-alpn-preferred-over-npn-server
-client = 10-alpn-preferred-over-npn-client
+[12-alpn-preferred-over-npn-ssl]
+server = 12-alpn-preferred-over-npn-server
+client = 12-alpn-preferred-over-npn-client
-[10-alpn-preferred-over-npn-server]
+[12-alpn-preferred-over-npn-server]
Certificate = ${ENV::TEST_CERTS_DIR}/servercert.pem
CipherString = DEFAULT
PrivateKey = ${ENV::TEST_CERTS_DIR}/serverkey.pem
-[10-alpn-preferred-over-npn-client]
+[12-alpn-preferred-over-npn-client]
CipherString = DEFAULT
MaxProtocol = TLSv1.2
VerifyCAFile = ${ENV::TEST_CERTS_DIR}/rootcert.pem
VerifyMode = Peer
-[test-10]
+[test-12]
ExpectedALPNProtocol = foo
-server = 10-alpn-preferred-over-npn-server-extra
-client = 10-alpn-preferred-over-npn-client-extra
+server = 12-alpn-preferred-over-npn-server-extra
+client = 12-alpn-preferred-over-npn-client-extra
-[10-alpn-preferred-over-npn-server-extra]
+[12-alpn-preferred-over-npn-server-extra]
ALPNProtocols = foo
NPNProtocols = bar
-[10-alpn-preferred-over-npn-client-extra]
+[12-alpn-preferred-over-npn-client-extra]
ALPNProtocols = foo
NPNProtocols = bar
# ===========================================================
-[11-sni-npn-preferred-over-alpn]
-ssl_conf = 11-sni-npn-preferred-over-alpn-ssl
+[13-sni-npn-preferred-over-alpn]
+ssl_conf = 13-sni-npn-preferred-over-alpn-ssl
-[11-sni-npn-preferred-over-alpn-ssl]
-server = 11-sni-npn-preferred-over-alpn-server
-client = 11-sni-npn-preferred-over-alpn-client
-server2 = 11-sni-npn-preferred-over-alpn-server2
+[13-sni-npn-preferred-over-alpn-ssl]
+server = 13-sni-npn-preferred-over-alpn-server
+client = 13-sni-npn-preferred-over-alpn-client
+server2 = 13-sni-npn-preferred-over-alpn-server2
-[11-sni-npn-preferred-over-alpn-server]
+[13-sni-npn-preferred-over-alpn-server]
Certificate = ${ENV::TEST_CERTS_DIR}/servercert.pem
CipherString = DEFAULT
PrivateKey = ${ENV::TEST_CERTS_DIR}/serverkey.pem
-[11-sni-npn-preferred-over-alpn-server2]
+[13-sni-npn-preferred-over-alpn-server2]
Certificate = ${ENV::TEST_CERTS_DIR}/servercert.pem
CipherString = DEFAULT
PrivateKey = ${ENV::TEST_CERTS_DIR}/serverkey.pem
-[11-sni-npn-preferred-over-alpn-client]
+[13-sni-npn-preferred-over-alpn-client]
CipherString = DEFAULT
MaxProtocol = TLSv1.2
VerifyCAFile = ${ENV::TEST_CERTS_DIR}/rootcert.pem
VerifyMode = Peer
-[test-11]
+[test-13]
ExpectedNPNProtocol = bar
ExpectedServerName = server2
-server = 11-sni-npn-preferred-over-alpn-server-extra
-server2 = 11-sni-npn-preferred-over-alpn-server2-extra
-client = 11-sni-npn-preferred-over-alpn-client-extra
+server = 13-sni-npn-preferred-over-alpn-server-extra
+server2 = 13-sni-npn-preferred-over-alpn-server2-extra
+client = 13-sni-npn-preferred-over-alpn-client-extra
-[11-sni-npn-preferred-over-alpn-server-extra]
+[13-sni-npn-preferred-over-alpn-server-extra]
ALPNProtocols = foo
ServerNameCallback = IgnoreMismatch
-[11-sni-npn-preferred-over-alpn-server2-extra]
+[13-sni-npn-preferred-over-alpn-server2-extra]
NPNProtocols = bar
-[11-sni-npn-preferred-over-alpn-client-extra]
+[13-sni-npn-preferred-over-alpn-client-extra]
ALPNProtocols = foo
NPNProtocols = bar
ServerName = server2
# ===========================================================
-[12-npn-simple-resumption]
-ssl_conf = 12-npn-simple-resumption-ssl
+[14-npn-simple-resumption]
+ssl_conf = 14-npn-simple-resumption-ssl
-[12-npn-simple-resumption-ssl]
-server = 12-npn-simple-resumption-server
-client = 12-npn-simple-resumption-client
-resume-server = 12-npn-simple-resumption-server
-resume-client = 12-npn-simple-resumption-client
+[14-npn-simple-resumption-ssl]
+server = 14-npn-simple-resumption-server
+client = 14-npn-simple-resumption-client
+resume-server = 14-npn-simple-resumption-server
+resume-client = 14-npn-simple-resumption-client
-[12-npn-simple-resumption-server]
+[14-npn-simple-resumption-server]
Certificate = ${ENV::TEST_CERTS_DIR}/servercert.pem
CipherString = DEFAULT
PrivateKey = ${ENV::TEST_CERTS_DIR}/serverkey.pem
-[12-npn-simple-resumption-client]
+[14-npn-simple-resumption-client]
CipherString = DEFAULT
MaxProtocol = TLSv1.2
VerifyCAFile = ${ENV::TEST_CERTS_DIR}/rootcert.pem
VerifyMode = Peer
-[test-12]
+[test-14]
ExpectedNPNProtocol = foo
HandshakeMode = Resume
ResumptionExpected = Yes
-server = 12-npn-simple-resumption-server-extra
-resume-server = 12-npn-simple-resumption-server-extra
-client = 12-npn-simple-resumption-client-extra
-resume-client = 12-npn-simple-resumption-client-extra
+server = 14-npn-simple-resumption-server-extra
+resume-server = 14-npn-simple-resumption-server-extra
+client = 14-npn-simple-resumption-client-extra
+resume-client = 14-npn-simple-resumption-client-extra
-[12-npn-simple-resumption-server-extra]
+[14-npn-simple-resumption-server-extra]
NPNProtocols = foo
-[12-npn-simple-resumption-client-extra]
+[14-npn-simple-resumption-client-extra]
NPNProtocols = foo
# ===========================================================
-[13-npn-server-switch-resumption]
-ssl_conf = 13-npn-server-switch-resumption-ssl
+[15-npn-server-switch-resumption]
+ssl_conf = 15-npn-server-switch-resumption-ssl
-[13-npn-server-switch-resumption-ssl]
-server = 13-npn-server-switch-resumption-server
-client = 13-npn-server-switch-resumption-client
-resume-server = 13-npn-server-switch-resumption-resume-server
-resume-client = 13-npn-server-switch-resumption-client
+[15-npn-server-switch-resumption-ssl]
+server = 15-npn-server-switch-resumption-server
+client = 15-npn-server-switch-resumption-client
+resume-server = 15-npn-server-switch-resumption-resume-server
+resume-client = 15-npn-server-switch-resumption-client
-[13-npn-server-switch-resumption-server]
+[15-npn-server-switch-resumption-server]
Certificate = ${ENV::TEST_CERTS_DIR}/servercert.pem
CipherString = DEFAULT
PrivateKey = ${ENV::TEST_CERTS_DIR}/serverkey.pem
-[13-npn-server-switch-resumption-resume-server]
+[15-npn-server-switch-resumption-resume-server]
Certificate = ${ENV::TEST_CERTS_DIR}/servercert.pem
CipherString = DEFAULT
PrivateKey = ${ENV::TEST_CERTS_DIR}/serverkey.pem
-[13-npn-server-switch-resumption-client]
+[15-npn-server-switch-resumption-client]
CipherString = DEFAULT
MaxProtocol = TLSv1.2
VerifyCAFile = ${ENV::TEST_CERTS_DIR}/rootcert.pem
VerifyMode = Peer
-[test-13]
+[test-15]
ExpectedNPNProtocol = baz
HandshakeMode = Resume
ResumptionExpected = Yes
-server = 13-npn-server-switch-resumption-server-extra
-resume-server = 13-npn-server-switch-resumption-resume-server-extra
-client = 13-npn-server-switch-resumption-client-extra
-resume-client = 13-npn-server-switch-resumption-client-extra
+server = 15-npn-server-switch-resumption-server-extra
+resume-server = 15-npn-server-switch-resumption-resume-server-extra
+client = 15-npn-server-switch-resumption-client-extra
+resume-client = 15-npn-server-switch-resumption-client-extra
-[13-npn-server-switch-resumption-server-extra]
+[15-npn-server-switch-resumption-server-extra]
NPNProtocols = bar,foo
-[13-npn-server-switch-resumption-resume-server-extra]
+[15-npn-server-switch-resumption-resume-server-extra]
NPNProtocols = baz,foo
-[13-npn-server-switch-resumption-client-extra]
+[15-npn-server-switch-resumption-client-extra]
NPNProtocols = foo,bar,baz
# ===========================================================
-[14-npn-client-switch-resumption]
-ssl_conf = 14-npn-client-switch-resumption-ssl
+[16-npn-client-switch-resumption]
+ssl_conf = 16-npn-client-switch-resumption-ssl
-[14-npn-client-switch-resumption-ssl]
-server = 14-npn-client-switch-resumption-server
-client = 14-npn-client-switch-resumption-client
-resume-server = 14-npn-client-switch-resumption-server
-resume-client = 14-npn-client-switch-resumption-resume-client
+[16-npn-client-switch-resumption-ssl]
+server = 16-npn-client-switch-resumption-server
+client = 16-npn-client-switch-resumption-client
+resume-server = 16-npn-client-switch-resumption-server
+resume-client = 16-npn-client-switch-resumption-resume-client
-[14-npn-client-switch-resumption-server]
+[16-npn-client-switch-resumption-server]
Certificate = ${ENV::TEST_CERTS_DIR}/servercert.pem
CipherString = DEFAULT
PrivateKey = ${ENV::TEST_CERTS_DIR}/serverkey.pem
-[14-npn-client-switch-resumption-client]
+[16-npn-client-switch-resumption-client]
CipherString = DEFAULT
MaxProtocol = TLSv1.2
VerifyCAFile = ${ENV::TEST_CERTS_DIR}/rootcert.pem
VerifyMode = Peer
-[14-npn-client-switch-resumption-resume-client]
+[16-npn-client-switch-resumption-resume-client]
CipherString = DEFAULT
MaxProtocol = TLSv1.2
VerifyCAFile = ${ENV::TEST_CERTS_DIR}/rootcert.pem
VerifyMode = Peer
-[test-14]
+[test-16]
ExpectedNPNProtocol = bar
HandshakeMode = Resume
ResumptionExpected = Yes
-server = 14-npn-client-switch-resumption-server-extra
-resume-server = 14-npn-client-switch-resumption-server-extra
-client = 14-npn-client-switch-resumption-client-extra
-resume-client = 14-npn-client-switch-resumption-resume-client-extra
+server = 16-npn-client-switch-resumption-server-extra
+resume-server = 16-npn-client-switch-resumption-server-extra
+client = 16-npn-client-switch-resumption-client-extra
+resume-client = 16-npn-client-switch-resumption-resume-client-extra
-[14-npn-client-switch-resumption-server-extra]
+[16-npn-client-switch-resumption-server-extra]
NPNProtocols = foo,bar,baz
-[14-npn-client-switch-resumption-client-extra]
+[16-npn-client-switch-resumption-client-extra]
NPNProtocols = foo,baz
-[14-npn-client-switch-resumption-resume-client-extra]
+[16-npn-client-switch-resumption-resume-client-extra]
NPNProtocols = bar,baz
# ===========================================================
-[15-npn-client-first-pref-on-mismatch-resumption]
-ssl_conf = 15-npn-client-first-pref-on-mismatch-resumption-ssl
+[17-npn-client-first-pref-on-mismatch-resumption]
+ssl_conf = 17-npn-client-first-pref-on-mismatch-resumption-ssl
-[15-npn-client-first-pref-on-mismatch-resumption-ssl]
-server = 15-npn-client-first-pref-on-mismatch-resumption-server
-client = 15-npn-client-first-pref-on-mismatch-resumption-client
-resume-server = 15-npn-client-first-pref-on-mismatch-resumption-resume-server
-resume-client = 15-npn-client-first-pref-on-mismatch-resumption-client
+[17-npn-client-first-pref-on-mismatch-resumption-ssl]
+server = 17-npn-client-first-pref-on-mismatch-resumption-server
+client = 17-npn-client-first-pref-on-mismatch-resumption-client
+resume-server = 17-npn-client-first-pref-on-mismatch-resumption-resume-server
+resume-client = 17-npn-client-first-pref-on-mismatch-resumption-client
-[15-npn-client-first-pref-on-mismatch-resumption-server]
+[17-npn-client-first-pref-on-mismatch-resumption-server]
Certificate = ${ENV::TEST_CERTS_DIR}/servercert.pem
CipherString = DEFAULT
PrivateKey = ${ENV::TEST_CERTS_DIR}/serverkey.pem
-[15-npn-client-first-pref-on-mismatch-resumption-resume-server]
+[17-npn-client-first-pref-on-mismatch-resumption-resume-server]
Certificate = ${ENV::TEST_CERTS_DIR}/servercert.pem
CipherString = DEFAULT
PrivateKey = ${ENV::TEST_CERTS_DIR}/serverkey.pem
-[15-npn-client-first-pref-on-mismatch-resumption-client]
+[17-npn-client-first-pref-on-mismatch-resumption-client]
CipherString = DEFAULT
MaxProtocol = TLSv1.2
VerifyCAFile = ${ENV::TEST_CERTS_DIR}/rootcert.pem
VerifyMode = Peer
-[test-15]
+[test-17]
ExpectedNPNProtocol = foo
HandshakeMode = Resume
ResumptionExpected = Yes
-server = 15-npn-client-first-pref-on-mismatch-resumption-server-extra
-resume-server = 15-npn-client-first-pref-on-mismatch-resumption-resume-server-extra
-client = 15-npn-client-first-pref-on-mismatch-resumption-client-extra
-resume-client = 15-npn-client-first-pref-on-mismatch-resumption-client-extra
+server = 17-npn-client-first-pref-on-mismatch-resumption-server-extra
+resume-server = 17-npn-client-first-pref-on-mismatch-resumption-resume-server-extra
+client = 17-npn-client-first-pref-on-mismatch-resumption-client-extra
+resume-client = 17-npn-client-first-pref-on-mismatch-resumption-client-extra
-[15-npn-client-first-pref-on-mismatch-resumption-server-extra]
+[17-npn-client-first-pref-on-mismatch-resumption-server-extra]
NPNProtocols = bar
-[15-npn-client-first-pref-on-mismatch-resumption-resume-server-extra]
+[17-npn-client-first-pref-on-mismatch-resumption-resume-server-extra]
NPNProtocols = baz
-[15-npn-client-first-pref-on-mismatch-resumption-client-extra]
+[17-npn-client-first-pref-on-mismatch-resumption-client-extra]
NPNProtocols = foo,bar
# ===========================================================
-[16-npn-no-server-support-resumption]
-ssl_conf = 16-npn-no-server-support-resumption-ssl
+[18-npn-no-server-support-resumption]
+ssl_conf = 18-npn-no-server-support-resumption-ssl
-[16-npn-no-server-support-resumption-ssl]
-server = 16-npn-no-server-support-resumption-server
-client = 16-npn-no-server-support-resumption-client
-resume-server = 16-npn-no-server-support-resumption-resume-server
-resume-client = 16-npn-no-server-support-resumption-client
+[18-npn-no-server-support-resumption-ssl]
+server = 18-npn-no-server-support-resumption-server
+client = 18-npn-no-server-support-resumption-client
+resume-server = 18-npn-no-server-support-resumption-resume-server
+resume-client = 18-npn-no-server-support-resumption-client
-[16-npn-no-server-support-resumption-server]
+[18-npn-no-server-support-resumption-server]
Certificate = ${ENV::TEST_CERTS_DIR}/servercert.pem
CipherString = DEFAULT
PrivateKey = ${ENV::TEST_CERTS_DIR}/serverkey.pem
-[16-npn-no-server-support-resumption-resume-server]
+[18-npn-no-server-support-resumption-resume-server]
Certificate = ${ENV::TEST_CERTS_DIR}/servercert.pem
CipherString = DEFAULT
PrivateKey = ${ENV::TEST_CERTS_DIR}/serverkey.pem
-[16-npn-no-server-support-resumption-client]
+[18-npn-no-server-support-resumption-client]
CipherString = DEFAULT
MaxProtocol = TLSv1.2
VerifyCAFile = ${ENV::TEST_CERTS_DIR}/rootcert.pem
VerifyMode = Peer
-[test-16]
+[test-18]
HandshakeMode = Resume
ResumptionExpected = Yes
-server = 16-npn-no-server-support-resumption-server-extra
-client = 16-npn-no-server-support-resumption-client-extra
-resume-client = 16-npn-no-server-support-resumption-client-extra
+server = 18-npn-no-server-support-resumption-server-extra
+client = 18-npn-no-server-support-resumption-client-extra
+resume-client = 18-npn-no-server-support-resumption-client-extra
-[16-npn-no-server-support-resumption-server-extra]
+[18-npn-no-server-support-resumption-server-extra]
NPNProtocols = foo
-[16-npn-no-server-support-resumption-client-extra]
+[18-npn-no-server-support-resumption-client-extra]
NPNProtocols = foo
# ===========================================================
-[17-npn-no-client-support-resumption]
-ssl_conf = 17-npn-no-client-support-resumption-ssl
+[19-npn-no-client-support-resumption]
+ssl_conf = 19-npn-no-client-support-resumption-ssl
-[17-npn-no-client-support-resumption-ssl]
-server = 17-npn-no-client-support-resumption-server
-client = 17-npn-no-client-support-resumption-client
-resume-server = 17-npn-no-client-support-resumption-server
-resume-client = 17-npn-no-client-support-resumption-resume-client
+[19-npn-no-client-support-resumption-ssl]
+server = 19-npn-no-client-support-resumption-server
+client = 19-npn-no-client-support-resumption-client
+resume-server = 19-npn-no-client-support-resumption-server
+resume-client = 19-npn-no-client-support-resumption-resume-client
-[17-npn-no-client-support-resumption-server]
+[19-npn-no-client-support-resumption-server]
Certificate = ${ENV::TEST_CERTS_DIR}/servercert.pem
CipherString = DEFAULT
PrivateKey = ${ENV::TEST_CERTS_DIR}/serverkey.pem
-[17-npn-no-client-support-resumption-client]
+[19-npn-no-client-support-resumption-client]
CipherString = DEFAULT
MaxProtocol = TLSv1.2
VerifyCAFile = ${ENV::TEST_CERTS_DIR}/rootcert.pem
VerifyMode = Peer
-[17-npn-no-client-support-resumption-resume-client]
+[19-npn-no-client-support-resumption-resume-client]
CipherString = DEFAULT
MaxProtocol = TLSv1.2
VerifyCAFile = ${ENV::TEST_CERTS_DIR}/rootcert.pem
VerifyMode = Peer
-[test-17]
+[test-19]
HandshakeMode = Resume
ResumptionExpected = Yes
-server = 17-npn-no-client-support-resumption-server-extra
-resume-server = 17-npn-no-client-support-resumption-server-extra
-client = 17-npn-no-client-support-resumption-client-extra
+server = 19-npn-no-client-support-resumption-server-extra
+resume-server = 19-npn-no-client-support-resumption-server-extra
+client = 19-npn-no-client-support-resumption-client-extra
-[17-npn-no-client-support-resumption-server-extra]
+[19-npn-no-client-support-resumption-server-extra]
NPNProtocols = foo
-[17-npn-no-client-support-resumption-client-extra]
+[19-npn-no-client-support-resumption-client-extra]
NPNProtocols = foo
# ===========================================================
-[18-alpn-preferred-over-npn-resumption]
-ssl_conf = 18-alpn-preferred-over-npn-resumption-ssl
+[20-alpn-preferred-over-npn-resumption]
+ssl_conf = 20-alpn-preferred-over-npn-resumption-ssl
-[18-alpn-preferred-over-npn-resumption-ssl]
-server = 18-alpn-preferred-over-npn-resumption-server
-client = 18-alpn-preferred-over-npn-resumption-client
-resume-server = 18-alpn-preferred-over-npn-resumption-resume-server
-resume-client = 18-alpn-preferred-over-npn-resumption-client
+[20-alpn-preferred-over-npn-resumption-ssl]
+server = 20-alpn-preferred-over-npn-resumption-server
+client = 20-alpn-preferred-over-npn-resumption-client
+resume-server = 20-alpn-preferred-over-npn-resumption-resume-server
+resume-client = 20-alpn-preferred-over-npn-resumption-client
-[18-alpn-preferred-over-npn-resumption-server]
+[20-alpn-preferred-over-npn-resumption-server]
Certificate = ${ENV::TEST_CERTS_DIR}/servercert.pem
CipherString = DEFAULT
PrivateKey = ${ENV::TEST_CERTS_DIR}/serverkey.pem
-[18-alpn-preferred-over-npn-resumption-resume-server]
+[20-alpn-preferred-over-npn-resumption-resume-server]
Certificate = ${ENV::TEST_CERTS_DIR}/servercert.pem
CipherString = DEFAULT
PrivateKey = ${ENV::TEST_CERTS_DIR}/serverkey.pem
-[18-alpn-preferred-over-npn-resumption-client]
+[20-alpn-preferred-over-npn-resumption-client]
CipherString = DEFAULT
MaxProtocol = TLSv1.2
VerifyCAFile = ${ENV::TEST_CERTS_DIR}/rootcert.pem
VerifyMode = Peer
-[test-18]
+[test-20]
ExpectedALPNProtocol = foo
HandshakeMode = Resume
ResumptionExpected = Yes
-server = 18-alpn-preferred-over-npn-resumption-server-extra
-resume-server = 18-alpn-preferred-over-npn-resumption-resume-server-extra
-client = 18-alpn-preferred-over-npn-resumption-client-extra
-resume-client = 18-alpn-preferred-over-npn-resumption-client-extra
+server = 20-alpn-preferred-over-npn-resumption-server-extra
+resume-server = 20-alpn-preferred-over-npn-resumption-resume-server-extra
+client = 20-alpn-preferred-over-npn-resumption-client-extra
+resume-client = 20-alpn-preferred-over-npn-resumption-client-extra
-[18-alpn-preferred-over-npn-resumption-server-extra]
+[20-alpn-preferred-over-npn-resumption-server-extra]
NPNProtocols = bar
-[18-alpn-preferred-over-npn-resumption-resume-server-extra]
+[20-alpn-preferred-over-npn-resumption-resume-server-extra]
ALPNProtocols = foo
NPNProtocols = baz
-[18-alpn-preferred-over-npn-resumption-client-extra]
+[20-alpn-preferred-over-npn-resumption-client-extra]
ALPNProtocols = foo
NPNProtocols = bar,baz
# ===========================================================
-[19-npn-used-if-alpn-not-supported-resumption]
-ssl_conf = 19-npn-used-if-alpn-not-supported-resumption-ssl
+[21-npn-used-if-alpn-not-supported-resumption]
+ssl_conf = 21-npn-used-if-alpn-not-supported-resumption-ssl
-[19-npn-used-if-alpn-not-supported-resumption-ssl]
-server = 19-npn-used-if-alpn-not-supported-resumption-server
-client = 19-npn-used-if-alpn-not-supported-resumption-client
-resume-server = 19-npn-used-if-alpn-not-supported-resumption-resume-server
-resume-client = 19-npn-used-if-alpn-not-supported-resumption-client
+[21-npn-used-if-alpn-not-supported-resumption-ssl]
+server = 21-npn-used-if-alpn-not-supported-resumption-server
+client = 21-npn-used-if-alpn-not-supported-resumption-client
+resume-server = 21-npn-used-if-alpn-not-supported-resumption-resume-server
+resume-client = 21-npn-used-if-alpn-not-supported-resumption-client
-[19-npn-used-if-alpn-not-supported-resumption-server]
+[21-npn-used-if-alpn-not-supported-resumption-server]
Certificate = ${ENV::TEST_CERTS_DIR}/servercert.pem
CipherString = DEFAULT
PrivateKey = ${ENV::TEST_CERTS_DIR}/serverkey.pem
-[19-npn-used-if-alpn-not-supported-resumption-resume-server]
+[21-npn-used-if-alpn-not-supported-resumption-resume-server]
Certificate = ${ENV::TEST_CERTS_DIR}/servercert.pem
CipherString = DEFAULT
PrivateKey = ${ENV::TEST_CERTS_DIR}/serverkey.pem
-[19-npn-used-if-alpn-not-supported-resumption-client]
+[21-npn-used-if-alpn-not-supported-resumption-client]
CipherString = DEFAULT
MaxProtocol = TLSv1.2
VerifyCAFile = ${ENV::TEST_CERTS_DIR}/rootcert.pem
VerifyMode = Peer
-[test-19]
+[test-21]
ExpectedNPNProtocol = baz
HandshakeMode = Resume
ResumptionExpected = Yes
-server = 19-npn-used-if-alpn-not-supported-resumption-server-extra
-resume-server = 19-npn-used-if-alpn-not-supported-resumption-resume-server-extra
-client = 19-npn-used-if-alpn-not-supported-resumption-client-extra
-resume-client = 19-npn-used-if-alpn-not-supported-resumption-client-extra
+server = 21-npn-used-if-alpn-not-supported-resumption-server-extra
+resume-server = 21-npn-used-if-alpn-not-supported-resumption-resume-server-extra
+client = 21-npn-used-if-alpn-not-supported-resumption-client-extra
+resume-client = 21-npn-used-if-alpn-not-supported-resumption-client-extra
-[19-npn-used-if-alpn-not-supported-resumption-server-extra]
+[21-npn-used-if-alpn-not-supported-resumption-server-extra]
ALPNProtocols = foo
NPNProtocols = bar
-[19-npn-used-if-alpn-not-supported-resumption-resume-server-extra]
+[21-npn-used-if-alpn-not-supported-resumption-resume-server-extra]
NPNProtocols = baz
-[19-npn-used-if-alpn-not-supported-resumption-client-extra]
+[21-npn-used-if-alpn-not-supported-resumption-client-extra]
ALPNProtocols = foo
NPNProtocols = bar,baz
diff --git a/crypto/openssl/test/ssl-tests/08-npn.cnf.in b/crypto/openssl/test/ssl-tests/08-npn.cnf.in
index 30783e45eb59..0caed2100ed4 100644
--- a/crypto/openssl/test/ssl-tests/08-npn.cnf.in
+++ b/crypto/openssl/test/ssl-tests/08-npn.cnf.in
@@ -1,443 +1,478 @@
# -*- mode: perl; -*-
-# 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 can obtain a copy
# in the file LICENSE in the source distribution or at
# https://www.openssl.org/source/license.html
## Test NPN. Note that NPN is only supported up to TLSv1.2
use strict;
use warnings;
package ssltests;
our @tests = (
{
name => "npn-simple",
server => {
extra => {
"NPNProtocols" => "foo",
},
},
client => {
extra => {
"NPNProtocols" => "foo",
},
"MaxProtocol" => "TLSv1.2"
},
test => {
"ExpectedNPNProtocol" => "foo",
},
},
{
name => "npn-client-finds-match",
server => {
extra => {
"NPNProtocols" => "baz,bar",
},
},
client => {
extra => {
"NPNProtocols" => "foo,bar",
},
"MaxProtocol" => "TLSv1.2"
},
test => {
"ExpectedNPNProtocol" => "bar",
},
},
{
name => "npn-client-honours-server-pref",
server => {
extra => {
"NPNProtocols" => "bar,foo",
},
},
client => {
extra => {
"NPNProtocols" => "foo,bar",
},
"MaxProtocol" => "TLSv1.2"
},
test => {
"ExpectedNPNProtocol" => "bar",
},
},
{
name => "npn-client-first-pref-on-mismatch",
server => {
extra => {
"NPNProtocols" => "baz",
},
},
client => {
extra => {
"NPNProtocols" => "foo,bar",
},
"MaxProtocol" => "TLSv1.2"
},
test => {
"ExpectedNPNProtocol" => "foo",
},
},
{
name => "npn-no-server-support",
server => {},
client => {
extra => {
"NPNProtocols" => "foo",
},
"MaxProtocol" => "TLSv1.2"
},
test => {
"ExpectedNPNProtocol" => undef,
},
},
{
name => "npn-no-client-support",
server => {
extra => {
"NPNProtocols" => "foo",
},
},
client => {
"MaxProtocol" => "TLSv1.2"
},
test => {
"ExpectedNPNProtocol" => undef,
},
},
+ {
+ name => "npn-empty-client-list",
+ server => {
+ extra => {
+ "NPNProtocols" => "foo",
+ },
+ },
+ client => {
+ extra => {
+ "NPNProtocols" => "",
+ },
+ "MaxProtocol" => "TLSv1.2"
+ },
+ test => {
+ "ExpectedResult" => "ClientFail",
+ "ExpectedClientAlert" => "HandshakeFailure"
+ },
+ },
+ {
+ name => "npn-empty-server-list",
+ server => {
+ extra => {
+ "NPNProtocols" => "",
+ },
+ },
+ client => {
+ extra => {
+ "NPNProtocols" => "foo",
+ },
+ "MaxProtocol" => "TLSv1.2"
+ },
+ test => {
+ "ExpectedNPNProtocol" => "foo"
+ },
+ },
{
name => "npn-with-sni-no-context-switch",
server => {
extra => {
"NPNProtocols" => "foo",
"ServerNameCallback" => "IgnoreMismatch",
},
},
server2 => {
extra => {
"NPNProtocols" => "bar",
},
},
client => {
extra => {
"NPNProtocols" => "foo,bar",
"ServerName" => "server1",
},
"MaxProtocol" => "TLSv1.2"
},
test => {
"ExpectedServerName" => "server1",
"ExpectedNPNProtocol" => "foo",
},
},
{
name => "npn-with-sni-context-switch",
server => {
extra => {
"NPNProtocols" => "foo",
"ServerNameCallback" => "IgnoreMismatch",
},
},
server2 => {
extra => {
"NPNProtocols" => "bar",
},
},
client => {
extra => {
"NPNProtocols" => "foo,bar",
"ServerName" => "server2",
},
"MaxProtocol" => "TLSv1.2"
},
test => {
"ExpectedServerName" => "server2",
"ExpectedNPNProtocol" => "bar",
},
},
{
name => "npn-selected-sni-server-supports-npn",
server => {
extra => {
"ServerNameCallback" => "IgnoreMismatch",
},
},
server2 => {
extra => {
"NPNProtocols" => "bar",
},
},
client => {
extra => {
"NPNProtocols" => "foo,bar",
"ServerName" => "server2",
},
"MaxProtocol" => "TLSv1.2"
},
test => {
"ExpectedServerName" => "server2",
"ExpectedNPNProtocol" => "bar",
},
},
{
name => "npn-selected-sni-server-does-not-support-npn",
server => {
extra => {
"NPNProtocols" => "bar",
"ServerNameCallback" => "IgnoreMismatch",
},
},
server2 => { },
client => {
extra => {
"NPNProtocols" => "foo,bar",
"ServerName" => "server2",
},
"MaxProtocol" => "TLSv1.2"
},
test => {
"ExpectedServerName" => "server2",
"ExpectedNPNProtocol" => undef,
},
},
{
name => "alpn-preferred-over-npn",
server => {
extra => {
"ALPNProtocols" => "foo",
"NPNProtocols" => "bar",
},
},
client => {
extra => {
"ALPNProtocols" => "foo",
"NPNProtocols" => "bar",
},
"MaxProtocol" => "TLSv1.2"
},
test => {
"ExpectedALPNProtocol" => "foo",
"ExpectedNPNProtocol" => undef,
},
},
{
name => "sni-npn-preferred-over-alpn",
server => {
extra => {
"ServerNameCallback" => "IgnoreMismatch",
"ALPNProtocols" => "foo",
},
},
server2 => {
extra => {
"NPNProtocols" => "bar",
},
},
client => {
extra => {
"ServerName" => "server2",
"ALPNProtocols" => "foo",
"NPNProtocols" => "bar",
},
"MaxProtocol" => "TLSv1.2"
},
test => {
"ExpectedALPNProtocol" => undef,
"ExpectedNPNProtocol" => "bar",
"ExpectedServerName" => "server2",
},
},
{
name => "npn-simple-resumption",
server => {
extra => {
"NPNProtocols" => "foo",
},
},
client => {
extra => {
"NPNProtocols" => "foo",
},
"MaxProtocol" => "TLSv1.2"
},
test => {
"HandshakeMode" => "Resume",
"ResumptionExpected" => "Yes",
"ExpectedNPNProtocol" => "foo",
},
},
{
name => "npn-server-switch-resumption",
server => {
extra => {
"NPNProtocols" => "bar,foo",
},
},
resume_server => {
extra => {
"NPNProtocols" => "baz,foo",
},
},
client => {
extra => {
"NPNProtocols" => "foo,bar,baz",
},
"MaxProtocol" => "TLSv1.2"
},
test => {
"HandshakeMode" => "Resume",
"ResumptionExpected" => "Yes",
"ExpectedNPNProtocol" => "baz",
},
},
{
name => "npn-client-switch-resumption",
server => {
extra => {
"NPNProtocols" => "foo,bar,baz",
},
},
client => {
extra => {
"NPNProtocols" => "foo,baz",
},
"MaxProtocol" => "TLSv1.2"
},
resume_client => {
extra => {
"NPNProtocols" => "bar,baz",
},
"MaxProtocol" => "TLSv1.2"
},
test => {
"HandshakeMode" => "Resume",
"ResumptionExpected" => "Yes",
"ExpectedNPNProtocol" => "bar",
},
},
{
name => "npn-client-first-pref-on-mismatch-resumption",
server => {
extra => {
"NPNProtocols" => "bar",
},
},
resume_server => {
extra => {
"NPNProtocols" => "baz",
},
},
client => {
extra => {
"NPNProtocols" => "foo,bar",
},
"MaxProtocol" => "TLSv1.2"
},
test => {
"HandshakeMode" => "Resume",
"ResumptionExpected" => "Yes",
"ExpectedNPNProtocol" => "foo",
},
},
{
name => "npn-no-server-support-resumption",
server => {
extra => {
"NPNProtocols" => "foo",
},
},
resume_server => { },
client => {
extra => {
"NPNProtocols" => "foo",
},
"MaxProtocol" => "TLSv1.2"
},
test => {
"HandshakeMode" => "Resume",
"ResumptionExpected" => "Yes",
"ExpectedNPNProtocol" => undef,
},
},
{
name => "npn-no-client-support-resumption",
server => {
extra => {
"NPNProtocols" => "foo",
},
},
client => {
extra => {
"NPNProtocols" => "foo",
},
"MaxProtocol" => "TLSv1.2"
},
resume_client => {
"MaxProtocol" => "TLSv1.2"
},
test => {
"HandshakeMode" => "Resume",
"ResumptionExpected" => "Yes",
"ExpectedNPNProtocol" => undef,
},
},
{
name => "alpn-preferred-over-npn-resumption",
server => {
extra => {
"NPNProtocols" => "bar",
},
},
resume_server => {
extra => {
"ALPNProtocols" => "foo",
"NPNProtocols" => "baz",
},
},
client => {
extra => {
"ALPNProtocols" => "foo",
"NPNProtocols" => "bar,baz",
},
"MaxProtocol" => "TLSv1.2"
},
test => {
"HandshakeMode" => "Resume",
"ResumptionExpected" => "Yes",
"ExpectedALPNProtocol" => "foo",
"ExpectedNPNProtocol" => undef,
},
},
{
name => "npn-used-if-alpn-not-supported-resumption",
server => {
extra => {
"ALPNProtocols" => "foo",
"NPNProtocols" => "bar",
},
},
resume_server => {
extra => {
"NPNProtocols" => "baz",
},
},
client => {
extra => {
"ALPNProtocols" => "foo",
"NPNProtocols" => "bar,baz",
},
"MaxProtocol" => "TLSv1.2"
},
test => {
"HandshakeMode" => "Resume",
"ResumptionExpected" => "Yes",
"ExpectedALPNProtocol" => undef,
"ExpectedNPNProtocol" => "baz",
},
},
);
diff --git a/crypto/openssl/test/ssl-tests/09-alpn.cnf b/crypto/openssl/test/ssl-tests/09-alpn.cnf
index e7e6cb95348b..dd668739ab9a 100644
--- a/crypto/openssl/test/ssl-tests/09-alpn.cnf
+++ b/crypto/openssl/test/ssl-tests/09-alpn.cnf
@@ -1,619 +1,683 @@
# Generated with generate_ssl_tests.pl
-num_tests = 16
+num_tests = 18
test-0 = 0-alpn-simple
test-1 = 1-alpn-server-finds-match
test-2 = 2-alpn-server-honours-server-pref
test-3 = 3-alpn-alert-on-mismatch
test-4 = 4-alpn-no-server-support
test-5 = 5-alpn-no-client-support
test-6 = 6-alpn-with-sni-no-context-switch
test-7 = 7-alpn-with-sni-context-switch
test-8 = 8-alpn-selected-sni-server-supports-alpn
test-9 = 9-alpn-selected-sni-server-does-not-support-alpn
test-10 = 10-alpn-simple-resumption
test-11 = 11-alpn-server-switch-resumption
test-12 = 12-alpn-client-switch-resumption
test-13 = 13-alpn-alert-on-mismatch-resumption
test-14 = 14-alpn-no-server-support-resumption
test-15 = 15-alpn-no-client-support-resumption
+test-16 = 16-alpn-empty-client-list
+test-17 = 17-alpn-empty-server-list
# ===========================================================
[0-alpn-simple]
ssl_conf = 0-alpn-simple-ssl
[0-alpn-simple-ssl]
server = 0-alpn-simple-server
client = 0-alpn-simple-client
[0-alpn-simple-server]
Certificate = ${ENV::TEST_CERTS_DIR}/servercert.pem
CipherString = DEFAULT
PrivateKey = ${ENV::TEST_CERTS_DIR}/serverkey.pem
[0-alpn-simple-client]
CipherString = DEFAULT
VerifyCAFile = ${ENV::TEST_CERTS_DIR}/rootcert.pem
VerifyMode = Peer
[test-0]
ExpectedALPNProtocol = foo
server = 0-alpn-simple-server-extra
client = 0-alpn-simple-client-extra
[0-alpn-simple-server-extra]
ALPNProtocols = foo
[0-alpn-simple-client-extra]
ALPNProtocols = foo
# ===========================================================
[1-alpn-server-finds-match]
ssl_conf = 1-alpn-server-finds-match-ssl
[1-alpn-server-finds-match-ssl]
server = 1-alpn-server-finds-match-server
client = 1-alpn-server-finds-match-client
[1-alpn-server-finds-match-server]
Certificate = ${ENV::TEST_CERTS_DIR}/servercert.pem
CipherString = DEFAULT
PrivateKey = ${ENV::TEST_CERTS_DIR}/serverkey.pem
[1-alpn-server-finds-match-client]
CipherString = DEFAULT
VerifyCAFile = ${ENV::TEST_CERTS_DIR}/rootcert.pem
VerifyMode = Peer
[test-1]
ExpectedALPNProtocol = bar
server = 1-alpn-server-finds-match-server-extra
client = 1-alpn-server-finds-match-client-extra
[1-alpn-server-finds-match-server-extra]
ALPNProtocols = baz,bar
[1-alpn-server-finds-match-client-extra]
ALPNProtocols = foo,bar
# ===========================================================
[2-alpn-server-honours-server-pref]
ssl_conf = 2-alpn-server-honours-server-pref-ssl
[2-alpn-server-honours-server-pref-ssl]
server = 2-alpn-server-honours-server-pref-server
client = 2-alpn-server-honours-server-pref-client
[2-alpn-server-honours-server-pref-server]
Certificate = ${ENV::TEST_CERTS_DIR}/servercert.pem
CipherString = DEFAULT
PrivateKey = ${ENV::TEST_CERTS_DIR}/serverkey.pem
[2-alpn-server-honours-server-pref-client]
CipherString = DEFAULT
VerifyCAFile = ${ENV::TEST_CERTS_DIR}/rootcert.pem
VerifyMode = Peer
[test-2]
ExpectedALPNProtocol = bar
server = 2-alpn-server-honours-server-pref-server-extra
client = 2-alpn-server-honours-server-pref-client-extra
[2-alpn-server-honours-server-pref-server-extra]
ALPNProtocols = bar,foo
[2-alpn-server-honours-server-pref-client-extra]
ALPNProtocols = foo,bar
# ===========================================================
[3-alpn-alert-on-mismatch]
ssl_conf = 3-alpn-alert-on-mismatch-ssl
[3-alpn-alert-on-mismatch-ssl]
server = 3-alpn-alert-on-mismatch-server
client = 3-alpn-alert-on-mismatch-client
[3-alpn-alert-on-mismatch-server]
Certificate = ${ENV::TEST_CERTS_DIR}/servercert.pem
CipherString = DEFAULT
PrivateKey = ${ENV::TEST_CERTS_DIR}/serverkey.pem
[3-alpn-alert-on-mismatch-client]
CipherString = DEFAULT
VerifyCAFile = ${ENV::TEST_CERTS_DIR}/rootcert.pem
VerifyMode = Peer
[test-3]
ExpectedResult = ServerFail
ExpectedServerAlert = NoApplicationProtocol
server = 3-alpn-alert-on-mismatch-server-extra
client = 3-alpn-alert-on-mismatch-client-extra
[3-alpn-alert-on-mismatch-server-extra]
ALPNProtocols = baz
[3-alpn-alert-on-mismatch-client-extra]
ALPNProtocols = foo,bar
# ===========================================================
[4-alpn-no-server-support]
ssl_conf = 4-alpn-no-server-support-ssl
[4-alpn-no-server-support-ssl]
server = 4-alpn-no-server-support-server
client = 4-alpn-no-server-support-client
[4-alpn-no-server-support-server]
Certificate = ${ENV::TEST_CERTS_DIR}/servercert.pem
CipherString = DEFAULT
PrivateKey = ${ENV::TEST_CERTS_DIR}/serverkey.pem
[4-alpn-no-server-support-client]
CipherString = DEFAULT
VerifyCAFile = ${ENV::TEST_CERTS_DIR}/rootcert.pem
VerifyMode = Peer
[test-4]
client = 4-alpn-no-server-support-client-extra
[4-alpn-no-server-support-client-extra]
ALPNProtocols = foo
# ===========================================================
[5-alpn-no-client-support]
ssl_conf = 5-alpn-no-client-support-ssl
[5-alpn-no-client-support-ssl]
server = 5-alpn-no-client-support-server
client = 5-alpn-no-client-support-client
[5-alpn-no-client-support-server]
Certificate = ${ENV::TEST_CERTS_DIR}/servercert.pem
CipherString = DEFAULT
PrivateKey = ${ENV::TEST_CERTS_DIR}/serverkey.pem
[5-alpn-no-client-support-client]
CipherString = DEFAULT
VerifyCAFile = ${ENV::TEST_CERTS_DIR}/rootcert.pem
VerifyMode = Peer
[test-5]
server = 5-alpn-no-client-support-server-extra
[5-alpn-no-client-support-server-extra]
ALPNProtocols = foo
# ===========================================================
[6-alpn-with-sni-no-context-switch]
ssl_conf = 6-alpn-with-sni-no-context-switch-ssl
[6-alpn-with-sni-no-context-switch-ssl]
server = 6-alpn-with-sni-no-context-switch-server
client = 6-alpn-with-sni-no-context-switch-client
server2 = 6-alpn-with-sni-no-context-switch-server2
[6-alpn-with-sni-no-context-switch-server]
Certificate = ${ENV::TEST_CERTS_DIR}/servercert.pem
CipherString = DEFAULT
PrivateKey = ${ENV::TEST_CERTS_DIR}/serverkey.pem
[6-alpn-with-sni-no-context-switch-server2]
Certificate = ${ENV::TEST_CERTS_DIR}/servercert.pem
CipherString = DEFAULT
PrivateKey = ${ENV::TEST_CERTS_DIR}/serverkey.pem
[6-alpn-with-sni-no-context-switch-client]
CipherString = DEFAULT
VerifyCAFile = ${ENV::TEST_CERTS_DIR}/rootcert.pem
VerifyMode = Peer
[test-6]
ExpectedALPNProtocol = foo
ExpectedServerName = server1
server = 6-alpn-with-sni-no-context-switch-server-extra
server2 = 6-alpn-with-sni-no-context-switch-server2-extra
client = 6-alpn-with-sni-no-context-switch-client-extra
[6-alpn-with-sni-no-context-switch-server-extra]
ALPNProtocols = foo
ServerNameCallback = IgnoreMismatch
[6-alpn-with-sni-no-context-switch-server2-extra]
ALPNProtocols = bar
[6-alpn-with-sni-no-context-switch-client-extra]
ALPNProtocols = foo,bar
ServerName = server1
# ===========================================================
[7-alpn-with-sni-context-switch]
ssl_conf = 7-alpn-with-sni-context-switch-ssl
[7-alpn-with-sni-context-switch-ssl]
server = 7-alpn-with-sni-context-switch-server
client = 7-alpn-with-sni-context-switch-client
server2 = 7-alpn-with-sni-context-switch-server2
[7-alpn-with-sni-context-switch-server]
Certificate = ${ENV::TEST_CERTS_DIR}/servercert.pem
CipherString = DEFAULT
PrivateKey = ${ENV::TEST_CERTS_DIR}/serverkey.pem
[7-alpn-with-sni-context-switch-server2]
Certificate = ${ENV::TEST_CERTS_DIR}/servercert.pem
CipherString = DEFAULT
PrivateKey = ${ENV::TEST_CERTS_DIR}/serverkey.pem
[7-alpn-with-sni-context-switch-client]
CipherString = DEFAULT
VerifyCAFile = ${ENV::TEST_CERTS_DIR}/rootcert.pem
VerifyMode = Peer
[test-7]
ExpectedALPNProtocol = bar
ExpectedServerName = server2
server = 7-alpn-with-sni-context-switch-server-extra
server2 = 7-alpn-with-sni-context-switch-server2-extra
client = 7-alpn-with-sni-context-switch-client-extra
[7-alpn-with-sni-context-switch-server-extra]
ALPNProtocols = foo
ServerNameCallback = IgnoreMismatch
[7-alpn-with-sni-context-switch-server2-extra]
ALPNProtocols = bar
[7-alpn-with-sni-context-switch-client-extra]
ALPNProtocols = foo,bar
ServerName = server2
# ===========================================================
[8-alpn-selected-sni-server-supports-alpn]
ssl_conf = 8-alpn-selected-sni-server-supports-alpn-ssl
[8-alpn-selected-sni-server-supports-alpn-ssl]
server = 8-alpn-selected-sni-server-supports-alpn-server
client = 8-alpn-selected-sni-server-supports-alpn-client
server2 = 8-alpn-selected-sni-server-supports-alpn-server2
[8-alpn-selected-sni-server-supports-alpn-server]
Certificate = ${ENV::TEST_CERTS_DIR}/servercert.pem
CipherString = DEFAULT
PrivateKey = ${ENV::TEST_CERTS_DIR}/serverkey.pem
[8-alpn-selected-sni-server-supports-alpn-server2]
Certificate = ${ENV::TEST_CERTS_DIR}/servercert.pem
CipherString = DEFAULT
PrivateKey = ${ENV::TEST_CERTS_DIR}/serverkey.pem
[8-alpn-selected-sni-server-supports-alpn-client]
CipherString = DEFAULT
VerifyCAFile = ${ENV::TEST_CERTS_DIR}/rootcert.pem
VerifyMode = Peer
[test-8]
ExpectedALPNProtocol = bar
ExpectedServerName = server2
server = 8-alpn-selected-sni-server-supports-alpn-server-extra
server2 = 8-alpn-selected-sni-server-supports-alpn-server2-extra
client = 8-alpn-selected-sni-server-supports-alpn-client-extra
[8-alpn-selected-sni-server-supports-alpn-server-extra]
ServerNameCallback = IgnoreMismatch
[8-alpn-selected-sni-server-supports-alpn-server2-extra]
ALPNProtocols = bar
[8-alpn-selected-sni-server-supports-alpn-client-extra]
ALPNProtocols = foo,bar
ServerName = server2
# ===========================================================
[9-alpn-selected-sni-server-does-not-support-alpn]
ssl_conf = 9-alpn-selected-sni-server-does-not-support-alpn-ssl
[9-alpn-selected-sni-server-does-not-support-alpn-ssl]
server = 9-alpn-selected-sni-server-does-not-support-alpn-server
client = 9-alpn-selected-sni-server-does-not-support-alpn-client
server2 = 9-alpn-selected-sni-server-does-not-support-alpn-server2
[9-alpn-selected-sni-server-does-not-support-alpn-server]
Certificate = ${ENV::TEST_CERTS_DIR}/servercert.pem
CipherString = DEFAULT
PrivateKey = ${ENV::TEST_CERTS_DIR}/serverkey.pem
[9-alpn-selected-sni-server-does-not-support-alpn-server2]
Certificate = ${ENV::TEST_CERTS_DIR}/servercert.pem
CipherString = DEFAULT
PrivateKey = ${ENV::TEST_CERTS_DIR}/serverkey.pem
[9-alpn-selected-sni-server-does-not-support-alpn-client]
CipherString = DEFAULT
VerifyCAFile = ${ENV::TEST_CERTS_DIR}/rootcert.pem
VerifyMode = Peer
[test-9]
ExpectedServerName = server2
server = 9-alpn-selected-sni-server-does-not-support-alpn-server-extra
client = 9-alpn-selected-sni-server-does-not-support-alpn-client-extra
[9-alpn-selected-sni-server-does-not-support-alpn-server-extra]
ALPNProtocols = bar
ServerNameCallback = IgnoreMismatch
[9-alpn-selected-sni-server-does-not-support-alpn-client-extra]
ALPNProtocols = foo,bar
ServerName = server2
# ===========================================================
[10-alpn-simple-resumption]
ssl_conf = 10-alpn-simple-resumption-ssl
[10-alpn-simple-resumption-ssl]
server = 10-alpn-simple-resumption-server
client = 10-alpn-simple-resumption-client
resume-server = 10-alpn-simple-resumption-server
resume-client = 10-alpn-simple-resumption-client
[10-alpn-simple-resumption-server]
Certificate = ${ENV::TEST_CERTS_DIR}/servercert.pem
CipherString = DEFAULT
PrivateKey = ${ENV::TEST_CERTS_DIR}/serverkey.pem
[10-alpn-simple-resumption-client]
CipherString = DEFAULT
VerifyCAFile = ${ENV::TEST_CERTS_DIR}/rootcert.pem
VerifyMode = Peer
[test-10]
ExpectedALPNProtocol = foo
HandshakeMode = Resume
ResumptionExpected = Yes
server = 10-alpn-simple-resumption-server-extra
resume-server = 10-alpn-simple-resumption-server-extra
client = 10-alpn-simple-resumption-client-extra
resume-client = 10-alpn-simple-resumption-client-extra
[10-alpn-simple-resumption-server-extra]
ALPNProtocols = foo
[10-alpn-simple-resumption-client-extra]
ALPNProtocols = foo
# ===========================================================
[11-alpn-server-switch-resumption]
ssl_conf = 11-alpn-server-switch-resumption-ssl
[11-alpn-server-switch-resumption-ssl]
server = 11-alpn-server-switch-resumption-server
client = 11-alpn-server-switch-resumption-client
resume-server = 11-alpn-server-switch-resumption-resume-server
resume-client = 11-alpn-server-switch-resumption-client
[11-alpn-server-switch-resumption-server]
Certificate = ${ENV::TEST_CERTS_DIR}/servercert.pem
CipherString = DEFAULT
PrivateKey = ${ENV::TEST_CERTS_DIR}/serverkey.pem
[11-alpn-server-switch-resumption-resume-server]
Certificate = ${ENV::TEST_CERTS_DIR}/servercert.pem
CipherString = DEFAULT
PrivateKey = ${ENV::TEST_CERTS_DIR}/serverkey.pem
[11-alpn-server-switch-resumption-client]
CipherString = DEFAULT
VerifyCAFile = ${ENV::TEST_CERTS_DIR}/rootcert.pem
VerifyMode = Peer
[test-11]
ExpectedALPNProtocol = baz
HandshakeMode = Resume
ResumptionExpected = Yes
server = 11-alpn-server-switch-resumption-server-extra
resume-server = 11-alpn-server-switch-resumption-resume-server-extra
client = 11-alpn-server-switch-resumption-client-extra
resume-client = 11-alpn-server-switch-resumption-client-extra
[11-alpn-server-switch-resumption-server-extra]
ALPNProtocols = bar,foo
[11-alpn-server-switch-resumption-resume-server-extra]
ALPNProtocols = baz,foo
[11-alpn-server-switch-resumption-client-extra]
ALPNProtocols = foo,bar,baz
# ===========================================================
[12-alpn-client-switch-resumption]
ssl_conf = 12-alpn-client-switch-resumption-ssl
[12-alpn-client-switch-resumption-ssl]
server = 12-alpn-client-switch-resumption-server
client = 12-alpn-client-switch-resumption-client
resume-server = 12-alpn-client-switch-resumption-server
resume-client = 12-alpn-client-switch-resumption-resume-client
[12-alpn-client-switch-resumption-server]
Certificate = ${ENV::TEST_CERTS_DIR}/servercert.pem
CipherString = DEFAULT
PrivateKey = ${ENV::TEST_CERTS_DIR}/serverkey.pem
[12-alpn-client-switch-resumption-client]
CipherString = DEFAULT
VerifyCAFile = ${ENV::TEST_CERTS_DIR}/rootcert.pem
VerifyMode = Peer
[12-alpn-client-switch-resumption-resume-client]
CipherString = DEFAULT
VerifyCAFile = ${ENV::TEST_CERTS_DIR}/rootcert.pem
VerifyMode = Peer
[test-12]
ExpectedALPNProtocol = bar
HandshakeMode = Resume
ResumptionExpected = Yes
server = 12-alpn-client-switch-resumption-server-extra
resume-server = 12-alpn-client-switch-resumption-server-extra
client = 12-alpn-client-switch-resumption-client-extra
resume-client = 12-alpn-client-switch-resumption-resume-client-extra
[12-alpn-client-switch-resumption-server-extra]
ALPNProtocols = foo,bar,baz
[12-alpn-client-switch-resumption-client-extra]
ALPNProtocols = foo,baz
[12-alpn-client-switch-resumption-resume-client-extra]
ALPNProtocols = bar,baz
# ===========================================================
[13-alpn-alert-on-mismatch-resumption]
ssl_conf = 13-alpn-alert-on-mismatch-resumption-ssl
[13-alpn-alert-on-mismatch-resumption-ssl]
server = 13-alpn-alert-on-mismatch-resumption-server
client = 13-alpn-alert-on-mismatch-resumption-client
resume-server = 13-alpn-alert-on-mismatch-resumption-resume-server
resume-client = 13-alpn-alert-on-mismatch-resumption-client
[13-alpn-alert-on-mismatch-resumption-server]
Certificate = ${ENV::TEST_CERTS_DIR}/servercert.pem
CipherString = DEFAULT
PrivateKey = ${ENV::TEST_CERTS_DIR}/serverkey.pem
[13-alpn-alert-on-mismatch-resumption-resume-server]
Certificate = ${ENV::TEST_CERTS_DIR}/servercert.pem
CipherString = DEFAULT
PrivateKey = ${ENV::TEST_CERTS_DIR}/serverkey.pem
[13-alpn-alert-on-mismatch-resumption-client]
CipherString = DEFAULT
VerifyCAFile = ${ENV::TEST_CERTS_DIR}/rootcert.pem
VerifyMode = Peer
[test-13]
ExpectedResult = ServerFail
ExpectedServerAlert = NoApplicationProtocol
HandshakeMode = Resume
server = 13-alpn-alert-on-mismatch-resumption-server-extra
resume-server = 13-alpn-alert-on-mismatch-resumption-resume-server-extra
client = 13-alpn-alert-on-mismatch-resumption-client-extra
resume-client = 13-alpn-alert-on-mismatch-resumption-client-extra
[13-alpn-alert-on-mismatch-resumption-server-extra]
ALPNProtocols = bar
[13-alpn-alert-on-mismatch-resumption-resume-server-extra]
ALPNProtocols = baz
[13-alpn-alert-on-mismatch-resumption-client-extra]
ALPNProtocols = foo,bar
# ===========================================================
[14-alpn-no-server-support-resumption]
ssl_conf = 14-alpn-no-server-support-resumption-ssl
[14-alpn-no-server-support-resumption-ssl]
server = 14-alpn-no-server-support-resumption-server
client = 14-alpn-no-server-support-resumption-client
resume-server = 14-alpn-no-server-support-resumption-resume-server
resume-client = 14-alpn-no-server-support-resumption-client
[14-alpn-no-server-support-resumption-server]
Certificate = ${ENV::TEST_CERTS_DIR}/servercert.pem
CipherString = DEFAULT
PrivateKey = ${ENV::TEST_CERTS_DIR}/serverkey.pem
[14-alpn-no-server-support-resumption-resume-server]
Certificate = ${ENV::TEST_CERTS_DIR}/servercert.pem
CipherString = DEFAULT
PrivateKey = ${ENV::TEST_CERTS_DIR}/serverkey.pem
[14-alpn-no-server-support-resumption-client]
CipherString = DEFAULT
VerifyCAFile = ${ENV::TEST_CERTS_DIR}/rootcert.pem
VerifyMode = Peer
[test-14]
HandshakeMode = Resume
ResumptionExpected = Yes
server = 14-alpn-no-server-support-resumption-server-extra
client = 14-alpn-no-server-support-resumption-client-extra
resume-client = 14-alpn-no-server-support-resumption-client-extra
[14-alpn-no-server-support-resumption-server-extra]
ALPNProtocols = foo
[14-alpn-no-server-support-resumption-client-extra]
ALPNProtocols = foo
# ===========================================================
[15-alpn-no-client-support-resumption]
ssl_conf = 15-alpn-no-client-support-resumption-ssl
[15-alpn-no-client-support-resumption-ssl]
server = 15-alpn-no-client-support-resumption-server
client = 15-alpn-no-client-support-resumption-client
resume-server = 15-alpn-no-client-support-resumption-server
resume-client = 15-alpn-no-client-support-resumption-resume-client
[15-alpn-no-client-support-resumption-server]
Certificate = ${ENV::TEST_CERTS_DIR}/servercert.pem
CipherString = DEFAULT
PrivateKey = ${ENV::TEST_CERTS_DIR}/serverkey.pem
[15-alpn-no-client-support-resumption-client]
CipherString = DEFAULT
VerifyCAFile = ${ENV::TEST_CERTS_DIR}/rootcert.pem
VerifyMode = Peer
[15-alpn-no-client-support-resumption-resume-client]
CipherString = DEFAULT
VerifyCAFile = ${ENV::TEST_CERTS_DIR}/rootcert.pem
VerifyMode = Peer
[test-15]
HandshakeMode = Resume
ResumptionExpected = Yes
server = 15-alpn-no-client-support-resumption-server-extra
resume-server = 15-alpn-no-client-support-resumption-server-extra
client = 15-alpn-no-client-support-resumption-client-extra
[15-alpn-no-client-support-resumption-server-extra]
ALPNProtocols = foo
[15-alpn-no-client-support-resumption-client-extra]
ALPNProtocols = foo
+# ===========================================================
+
+[16-alpn-empty-client-list]
+ssl_conf = 16-alpn-empty-client-list-ssl
+
+[16-alpn-empty-client-list-ssl]
+server = 16-alpn-empty-client-list-server
+client = 16-alpn-empty-client-list-client
+
+[16-alpn-empty-client-list-server]
+Certificate = ${ENV::TEST_CERTS_DIR}/servercert.pem
+CipherString = DEFAULT
+PrivateKey = ${ENV::TEST_CERTS_DIR}/serverkey.pem
+
+[16-alpn-empty-client-list-client]
+CipherString = DEFAULT
+VerifyCAFile = ${ENV::TEST_CERTS_DIR}/rootcert.pem
+VerifyMode = Peer
+
+[test-16]
+server = 16-alpn-empty-client-list-server-extra
+client = 16-alpn-empty-client-list-client-extra
+
+[16-alpn-empty-client-list-server-extra]
+ALPNProtocols = foo
+
+[16-alpn-empty-client-list-client-extra]
+ALPNProtocols =
+
+
+# ===========================================================
+
+[17-alpn-empty-server-list]
+ssl_conf = 17-alpn-empty-server-list-ssl
+
+[17-alpn-empty-server-list-ssl]
+server = 17-alpn-empty-server-list-server
+client = 17-alpn-empty-server-list-client
+
+[17-alpn-empty-server-list-server]
+Certificate = ${ENV::TEST_CERTS_DIR}/servercert.pem
+CipherString = DEFAULT
+PrivateKey = ${ENV::TEST_CERTS_DIR}/serverkey.pem
+
+[17-alpn-empty-server-list-client]
+CipherString = DEFAULT
+VerifyCAFile = ${ENV::TEST_CERTS_DIR}/rootcert.pem
+VerifyMode = Peer
+
+[test-17]
+ExpectedResult = ServerFail
+ExpectedServerAlert = NoApplicationProtocol
+server = 17-alpn-empty-server-list-server-extra
+client = 17-alpn-empty-server-list-client-extra
+
+[17-alpn-empty-server-list-server-extra]
+ALPNProtocols =
+
+[17-alpn-empty-server-list-client-extra]
+ALPNProtocols = foo
+
+
diff --git a/crypto/openssl/test/ssl-tests/09-alpn.cnf.in b/crypto/openssl/test/ssl-tests/09-alpn.cnf.in
index 81330756c62c..73e9cbabb053 100644
--- a/crypto/openssl/test/ssl-tests/09-alpn.cnf.in
+++ b/crypto/openssl/test/ssl-tests/09-alpn.cnf.in
@@ -1,325 +1,358 @@
# -*- mode: perl; -*-
-# 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 can obtain a copy
# in the file LICENSE in the source distribution or at
# https://www.openssl.org/source/license.html
## Test version negotiation
use strict;
use warnings;
package ssltests;
our @tests = (
{
name => "alpn-simple",
server => {
extra => {
"ALPNProtocols" => "foo",
},
},
client => {
extra => {
"ALPNProtocols" => "foo",
},
},
test => {
"ExpectedALPNProtocol" => "foo",
},
},
{
name => "alpn-server-finds-match",
server => {
extra => {
"ALPNProtocols" => "baz,bar",
},
},
client => {
extra => {
"ALPNProtocols" => "foo,bar",
},
},
test => {
"ExpectedALPNProtocol" => "bar",
},
},
{
name => "alpn-server-honours-server-pref",
server => {
extra => {
"ALPNProtocols" => "bar,foo",
},
},
client => {
extra => {
"ALPNProtocols" => "foo,bar",
},
},
test => {
"ExpectedALPNProtocol" => "bar",
},
},
{
name => "alpn-alert-on-mismatch",
server => {
extra => {
"ALPNProtocols" => "baz",
},
},
client => {
extra => {
"ALPNProtocols" => "foo,bar",
},
},
test => {
"ExpectedResult" => "ServerFail",
"ExpectedServerAlert" => "NoApplicationProtocol",
},
},
{
name => "alpn-no-server-support",
server => { },
client => {
extra => {
"ALPNProtocols" => "foo",
},
},
test => {
"ExpectedALPNProtocol" => undef,
},
},
{
name => "alpn-no-client-support",
server => {
extra => {
"ALPNProtocols" => "foo",
},
},
client => { },
test => {
"ExpectedALPNProtocol" => undef,
},
},
{
name => "alpn-with-sni-no-context-switch",
server => {
extra => {
"ALPNProtocols" => "foo",
"ServerNameCallback" => "IgnoreMismatch",
},
},
server2 => {
extra => {
"ALPNProtocols" => "bar",
},
},
client => {
extra => {
"ALPNProtocols" => "foo,bar",
"ServerName" => "server1",
},
},
test => {
"ExpectedServerName" => "server1",
"ExpectedALPNProtocol" => "foo",
},
},
{
name => "alpn-with-sni-context-switch",
server => {
extra => {
"ALPNProtocols" => "foo",
"ServerNameCallback" => "IgnoreMismatch",
},
},
server2 => {
extra => {
"ALPNProtocols" => "bar",
},
},
client => {
extra => {
"ALPNProtocols" => "foo,bar",
"ServerName" => "server2",
},
},
test => {
"ExpectedServerName" => "server2",
"ExpectedALPNProtocol" => "bar",
},
},
{
name => "alpn-selected-sni-server-supports-alpn",
server => {
extra => {
"ServerNameCallback" => "IgnoreMismatch",
},
},
server2 => {
extra => {
"ALPNProtocols" => "bar",
},
},
client => {
extra => {
"ALPNProtocols" => "foo,bar",
"ServerName" => "server2",
},
},
test => {
"ExpectedServerName" => "server2",
"ExpectedALPNProtocol" => "bar",
},
},
{
name => "alpn-selected-sni-server-does-not-support-alpn",
server => {
extra => {
"ALPNProtocols" => "bar",
"ServerNameCallback" => "IgnoreMismatch",
},
},
server2 => { },
client => {
extra => {
"ALPNProtocols" => "foo,bar",
"ServerName" => "server2",
},
},
test => {
"ExpectedServerName" => "server2",
"ExpectedALPNProtocol" => undef,
},
},
{
name => "alpn-simple-resumption",
server => {
extra => {
"ALPNProtocols" => "foo",
},
},
client => {
extra => {
"ALPNProtocols" => "foo",
},
},
test => {
"HandshakeMode" => "Resume",
"ResumptionExpected" => "Yes",
"ExpectedALPNProtocol" => "foo",
},
},
{
name => "alpn-server-switch-resumption",
server => {
extra => {
"ALPNProtocols" => "bar,foo",
},
},
resume_server => {
extra => {
"ALPNProtocols" => "baz,foo",
},
},
client => {
extra => {
"ALPNProtocols" => "foo,bar,baz",
},
},
test => {
"HandshakeMode" => "Resume",
"ResumptionExpected" => "Yes",
"ExpectedALPNProtocol" => "baz",
},
},
{
name => "alpn-client-switch-resumption",
server => {
extra => {
"ALPNProtocols" => "foo,bar,baz",
},
},
client => {
extra => {
"ALPNProtocols" => "foo,baz",
},
},
resume_client => {
extra => {
"ALPNProtocols" => "bar,baz",
},
},
test => {
"HandshakeMode" => "Resume",
"ResumptionExpected" => "Yes",
"ExpectedALPNProtocol" => "bar",
},
},
{
name => "alpn-alert-on-mismatch-resumption",
server => {
extra => {
"ALPNProtocols" => "bar",
},
},
resume_server => {
extra => {
"ALPNProtocols" => "baz",
},
},
client => {
extra => {
"ALPNProtocols" => "foo,bar",
},
},
test => {
"HandshakeMode" => "Resume",
"ExpectedResult" => "ServerFail",
"ExpectedServerAlert" => "NoApplicationProtocol",
},
},
{
name => "alpn-no-server-support-resumption",
server => {
extra => {
"ALPNProtocols" => "foo",
},
},
resume_server => { },
client => {
extra => {
"ALPNProtocols" => "foo",
},
},
test => {
"HandshakeMode" => "Resume",
"ResumptionExpected" => "Yes",
"ExpectedALPNProtocol" => undef,
},
},
{
name => "alpn-no-client-support-resumption",
server => {
extra => {
"ALPNProtocols" => "foo",
},
},
client => {
extra => {
"ALPNProtocols" => "foo",
},
},
resume_client => {
},
test => {
"HandshakeMode" => "Resume",
"ResumptionExpected" => "Yes",
"ExpectedALPNProtocol" => undef,
},
},
+ {
+ name => "alpn-empty-client-list",
+ server => {
+ extra => {
+ "ALPNProtocols" => "foo",
+ },
+ },
+ client => {
+ extra => {
+ "ALPNProtocols" => "",
+ },
+ },
+ test => {
+ "ExpectedALPNProtocol" => undef,
+ },
+ },
+ {
+ name => "alpn-empty-server-list",
+ server => {
+ extra => {
+ "ALPNProtocols" => "",
+ },
+ },
+ client => {
+ extra => {
+ "ALPNProtocols" => "foo",
+ },
+ },
+ test => {
+ "ExpectedResult" => "ServerFail",
+ "ExpectedServerAlert" => "NoApplicationProtocol",
+ },
+ },
);
diff --git a/crypto/openssl/test/sslapitest.c b/crypto/openssl/test/sslapitest.c
index 2b1c2fded322..97cf0f3ef092 100644
--- a/crypto/openssl/test/sslapitest.c
+++ b/crypto/openssl/test/sslapitest.c
@@ -1,11075 +1,11441 @@
/*
* 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)))
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)) {
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")))
+ if (!TEST_true(SSL_set1_groups_list(serverssl, "P-384")))
goto end;
#endif
} else if (idx == 2) {
/*
* We force early_data rejection by ensuring the PSK identity is
* unrecognised
*/
srvid = "Dummy Identity";
} else {
/*
* Deliberately corrupt the creation time. We take 20 seconds off the
* time. It could be any value as long as it is not within tolerance.
* This should mean the ticket is rejected.
*/
if (!TEST_true(SSL_SESSION_set_time(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)) {
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)) {
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")))
+ if (!TEST_true(SSL_set1_groups_list(serverssl, "P-384")))
goto end;
#endif
/*
* Check we can create a connection, the PSK is used and the callbacks are
* called twice.
*/
if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))
|| !TEST_true(SSL_session_reused(clientssl))
|| !TEST_true(SSL_session_reused(serverssl)))
goto end;
if (idx == 0 || idx == 1) {
if (!TEST_true(use_session_cb_cnt == 2)
|| !TEST_true(find_session_cb_cnt == 2)
|| !TEST_true(psk_client_cb_cnt == 0)
|| !TEST_true(psk_server_cb_cnt == 0))
goto end;
} else {
if (!TEST_true(use_session_cb_cnt == 0)
|| !TEST_true(find_session_cb_cnt == 0)
|| !TEST_true(psk_client_cb_cnt == 2)
|| !TEST_true(psk_server_cb_cnt == 2))
goto end;
}
shutdown_ssl_connection(serverssl, clientssl);
serverssl = clientssl = NULL;
use_session_cb_cnt = find_session_cb_cnt = 0;
psk_client_cb_cnt = psk_server_cb_cnt = 0;
if (idx != 3) {
/*
* Check that if the server rejects the PSK we can still connect, but with
* a full handshake
*/
srvid = "Dummy Identity";
if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
NULL, NULL))
|| !TEST_true(create_ssl_connection(serverssl, clientssl,
SSL_ERROR_NONE))
|| !TEST_false(SSL_session_reused(clientssl))
|| !TEST_false(SSL_session_reused(serverssl)))
goto end;
if (idx == 0 || idx == 1) {
if (!TEST_true(use_session_cb_cnt == 1)
|| !TEST_true(find_session_cb_cnt == 1)
|| !TEST_true(psk_client_cb_cnt == 0)
/*
* If no old style callback then below should be 0
* otherwise 1
*/
|| !TEST_true(psk_server_cb_cnt == idx))
goto end;
} else {
if (!TEST_true(use_session_cb_cnt == 0)
|| !TEST_true(find_session_cb_cnt == 0)
|| !TEST_true(psk_client_cb_cnt == 1)
|| !TEST_true(psk_server_cb_cnt == 1))
goto end;
}
shutdown_ssl_connection(serverssl, clientssl);
serverssl = clientssl = NULL;
}
testresult = 1;
end:
SSL_SESSION_free(clientpsk);
SSL_SESSION_free(serverpsk);
clientpsk = serverpsk = NULL;
SSL_free(serverssl);
SSL_free(clientssl);
SSL_CTX_free(sctx);
SSL_CTX_free(cctx);
return testresult;
}
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)))
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 ? "xorkemgroup" : "xorgroup";
if (!TEST_ptr(tlsprov))
goto end;
if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
TLS_client_method(),
TLS1_3_VERSION,
TLS1_3_VERSION,
&sctx, &cctx, cert, privkey))
|| !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
NULL, NULL)))
goto end;
/* ensure GROUPLIST_INCREMENT (=40) logic triggers: */
if (!TEST_true(SSL_set1_groups_list(serverssl, "xorgroup:xorkemgroup:dummy1:dummy2:dummy3:dummy4:dummy5:dummy6:dummy7:dummy8:dummy9:dummy10:dummy11:dummy12:dummy13:dummy14:dummy15:dummy16:dummy17:dummy18:dummy19:dummy20:dummy21:dummy22:dummy23:dummy24:dummy25:dummy26:dummy27:dummy28:dummy29:dummy30:dummy31:dummy32:dummy33:dummy34:dummy35:dummy36:dummy37:dummy38:dummy39:dummy40:dummy41:dummy42:dummy43"))
/* removing a single algorithm from the list makes the test pass */
|| !TEST_true(SSL_set1_groups_list(clientssl, group_name)))
goto end;
if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
goto end;
if (!TEST_str_eq(group_name,
SSL_group_to_name(serverssl, SSL_get_shared_group(serverssl, 0))))
goto end;
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)
/*
* 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;
}
+static struct next_proto_st {
+ int serverlen;
+ unsigned char server[40];
+ int clientlen;
+ unsigned char client[40];
+ int expected_ret;
+ size_t selectedlen;
+ unsigned char selected[40];
+} next_proto_tests[] = {
+ {
+ 4, { 3, 'a', 'b', 'c' },
+ 4, { 3, 'a', 'b', 'c' },
+ OPENSSL_NPN_NEGOTIATED,
+ 3, { 'a', 'b', 'c' }
+ },
+ {
+ 7, { 3, 'a', 'b', 'c', 2, 'a', 'b' },
+ 4, { 3, 'a', 'b', 'c' },
+ OPENSSL_NPN_NEGOTIATED,
+ 3, { 'a', 'b', 'c' }
+ },
+ {
+ 7, { 2, 'a', 'b', 3, 'a', 'b', 'c', },
+ 4, { 3, 'a', 'b', 'c' },
+ OPENSSL_NPN_NEGOTIATED,
+ 3, { 'a', 'b', 'c' }
+ },
+ {
+ 4, { 3, 'a', 'b', 'c' },
+ 7, { 3, 'a', 'b', 'c', 2, 'a', 'b', },
+ OPENSSL_NPN_NEGOTIATED,
+ 3, { 'a', 'b', 'c' }
+ },
+ {
+ 4, { 3, 'a', 'b', 'c' },
+ 7, { 2, 'a', 'b', 3, 'a', 'b', 'c'},
+ OPENSSL_NPN_NEGOTIATED,
+ 3, { 'a', 'b', 'c' }
+ },
+ {
+ 7, { 2, 'b', 'c', 3, 'a', 'b', 'c' },
+ 7, { 2, 'a', 'b', 3, 'a', 'b', 'c'},
+ OPENSSL_NPN_NEGOTIATED,
+ 3, { 'a', 'b', 'c' }
+ },
+ {
+ 10, { 2, 'b', 'c', 3, 'a', 'b', 'c', 2, 'a', 'b' },
+ 7, { 2, 'a', 'b', 3, 'a', 'b', 'c'},
+ OPENSSL_NPN_NEGOTIATED,
+ 3, { 'a', 'b', 'c' }
+ },
+ {
+ 4, { 3, 'b', 'c', 'd' },
+ 4, { 3, 'a', 'b', 'c' },
+ OPENSSL_NPN_NO_OVERLAP,
+ 3, { 'a', 'b', 'c' }
+ },
+ {
+ 0, { 0 },
+ 4, { 3, 'a', 'b', 'c' },
+ OPENSSL_NPN_NO_OVERLAP,
+ 3, { 'a', 'b', 'c' }
+ },
+ {
+ -1, { 0 },
+ 4, { 3, 'a', 'b', 'c' },
+ OPENSSL_NPN_NO_OVERLAP,
+ 3, { 'a', 'b', 'c' }
+ },
+ {
+ 4, { 3, 'a', 'b', 'c' },
+ 0, { 0 },
+ OPENSSL_NPN_NO_OVERLAP,
+ 0, { 0 }
+ },
+ {
+ 4, { 3, 'a', 'b', 'c' },
+ -1, { 0 },
+ OPENSSL_NPN_NO_OVERLAP,
+ 0, { 0 }
+ },
+ {
+ 3, { 3, 'a', 'b', 'c' },
+ 4, { 3, 'a', 'b', 'c' },
+ OPENSSL_NPN_NO_OVERLAP,
+ 3, { 'a', 'b', 'c' }
+ },
+ {
+ 4, { 3, 'a', 'b', 'c' },
+ 3, { 3, 'a', 'b', 'c' },
+ OPENSSL_NPN_NO_OVERLAP,
+ 0, { 0 }
+ }
+};
+
+static int test_select_next_proto(int idx)
+{
+ struct next_proto_st *np = &next_proto_tests[idx];
+ int ret = 0;
+ unsigned char *out, *client, *server;
+ unsigned char outlen;
+ unsigned int clientlen, serverlen;
+
+ if (np->clientlen == -1) {
+ client = NULL;
+ clientlen = 0;
+ } else {
+ client = np->client;
+ clientlen = (unsigned int)np->clientlen;
+ }
+ if (np->serverlen == -1) {
+ server = NULL;
+ serverlen = 0;
+ } else {
+ server = np->server;
+ serverlen = (unsigned int)np->serverlen;
+ }
+
+ if (!TEST_int_eq(SSL_select_next_proto(&out, &outlen, server, serverlen,
+ client, clientlen),
+ np->expected_ret))
+ goto err;
+
+ if (np->selectedlen == 0) {
+ if (!TEST_ptr_null(out) || !TEST_uchar_eq(outlen, 0))
+ goto err;
+ } else {
+ if (!TEST_mem_eq(out, outlen, np->selected, np->selectedlen))
+ goto err;
+ }
+
+ ret = 1;
+ err:
+ return ret;
+}
+
+static const unsigned char fooprot[] = {3, 'f', 'o', 'o' };
+static const unsigned char barprot[] = {3, 'b', 'a', 'r' };
+
+#if !defined(OPENSSL_NO_TLS1_2) && !defined(OPENSSL_NO_NEXTPROTONEG)
+static int npn_advert_cb(SSL *ssl, const unsigned char **out,
+ unsigned int *outlen, void *arg)
+{
+ int *idx = (int *)arg;
+
+ switch (*idx) {
+ default:
+ case 0:
+ *out = fooprot;
+ *outlen = sizeof(fooprot);
+ return SSL_TLSEXT_ERR_OK;
+
+ case 1:
+ *outlen = 0;
+ return SSL_TLSEXT_ERR_OK;
+
+ case 2:
+ return SSL_TLSEXT_ERR_NOACK;
+ }
+}
+
+static int npn_select_cb(SSL *s, unsigned char **out, unsigned char *outlen,
+ const unsigned char *in, unsigned int inlen, void *arg)
+{
+ int *idx = (int *)arg;
+
+ switch (*idx) {
+ case 0:
+ case 1:
+ *out = (unsigned char *)(fooprot + 1);
+ *outlen = *fooprot;
+ return SSL_TLSEXT_ERR_OK;
+
+ case 3:
+ *out = (unsigned char *)(barprot + 1);
+ *outlen = *barprot;
+ return SSL_TLSEXT_ERR_OK;
+
+ case 4:
+ *outlen = 0;
+ return SSL_TLSEXT_ERR_OK;
+
+ default:
+ case 2:
+ return SSL_TLSEXT_ERR_ALERT_FATAL;
+ }
+}
+
+/*
+ * Test the NPN callbacks
+ * Test 0: advert = foo, select = foo
+ * Test 1: advert = <empty>, select = foo
+ * Test 2: no advert
+ * Test 3: advert = foo, select = bar
+ * Test 4: advert = foo, select = <empty> (should fail)
+ */
+static int test_npn(int idx)
+{
+ SSL_CTX *sctx = NULL, *cctx = NULL;
+ SSL *serverssl = NULL, *clientssl = NULL;
+ int testresult = 0;
+
+ if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
+ TLS_client_method(), 0, TLS1_2_VERSION,
+ &sctx, &cctx, cert, privkey)))
+ goto end;
+
+ SSL_CTX_set_next_protos_advertised_cb(sctx, npn_advert_cb, &idx);
+ SSL_CTX_set_next_proto_select_cb(cctx, npn_select_cb, &idx);
+
+ if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL,
+ NULL)))
+ goto end;
+
+ if (idx == 4) {
+ /* We don't allow empty selection of NPN, so this should fail */
+ if (!TEST_false(create_ssl_connection(serverssl, clientssl,
+ SSL_ERROR_NONE)))
+ goto end;
+ } else {
+ const unsigned char *prot;
+ unsigned int protlen;
+
+ if (!TEST_true(create_ssl_connection(serverssl, clientssl,
+ SSL_ERROR_NONE)))
+ goto end;
+
+ SSL_get0_next_proto_negotiated(serverssl, &prot, &protlen);
+ switch (idx) {
+ case 0:
+ case 1:
+ if (!TEST_mem_eq(prot, protlen, fooprot + 1, *fooprot))
+ goto end;
+ break;
+ case 2:
+ if (!TEST_uint_eq(protlen, 0))
+ goto end;
+ break;
+ case 3:
+ if (!TEST_mem_eq(prot, protlen, barprot + 1, *barprot))
+ goto end;
+ break;
+ default:
+ TEST_error("Should not get here");
+ goto end;
+ }
+ }
+
+ testresult = 1;
+ end:
+ SSL_free(serverssl);
+ SSL_free(clientssl);
+ SSL_CTX_free(sctx);
+ SSL_CTX_free(cctx);
+
+ return testresult;
+}
+#endif /* !defined(OPENSSL_NO_TLS1_2) && !defined(OPENSSL_NO_NEXTPROTONEG) */
+
+static int alpn_select_cb2(SSL *ssl, const unsigned char **out,
+ unsigned char *outlen, const unsigned char *in,
+ unsigned int inlen, void *arg)
+{
+ int *idx = (int *)arg;
+
+ switch (*idx) {
+ case 0:
+ *out = (unsigned char *)(fooprot + 1);
+ *outlen = *fooprot;
+ return SSL_TLSEXT_ERR_OK;
+
+ case 2:
+ *out = (unsigned char *)(barprot + 1);
+ *outlen = *barprot;
+ return SSL_TLSEXT_ERR_OK;
+
+ case 3:
+ *outlen = 0;
+ return SSL_TLSEXT_ERR_OK;
+
+ default:
+ case 1:
+ return SSL_TLSEXT_ERR_ALERT_FATAL;
+ }
+ return 0;
+}
+
+/*
+ * Test the ALPN callbacks
+ * Test 0: client = foo, select = foo
+ * Test 1: client = <empty>, select = none
+ * Test 2: client = foo, select = bar (should fail)
+ * Test 3: client = foo, select = <empty> (should fail)
+ */
+static int test_alpn(int idx)
+{
+ SSL_CTX *sctx = NULL, *cctx = NULL;
+ SSL *serverssl = NULL, *clientssl = NULL;
+ int testresult = 0;
+ const unsigned char *prots = fooprot;
+ unsigned int protslen = sizeof(fooprot);
+
+ if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
+ TLS_client_method(), 0, 0,
+ &sctx, &cctx, cert, privkey)))
+ goto end;
+
+ SSL_CTX_set_alpn_select_cb(sctx, alpn_select_cb2, &idx);
+
+ if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL,
+ NULL)))
+ goto end;
+
+ if (idx == 1) {
+ prots = NULL;
+ protslen = 0;
+ }
+
+ /* SSL_set_alpn_protos returns 0 for success! */
+ if (!TEST_false(SSL_set_alpn_protos(clientssl, prots, protslen)))
+ goto end;
+
+ if (idx == 2 || idx == 3) {
+ /* We don't allow empty selection of NPN, so this should fail */
+ if (!TEST_false(create_ssl_connection(serverssl, clientssl,
+ SSL_ERROR_NONE)))
+ goto end;
+ } else {
+ const unsigned char *prot;
+ unsigned int protlen;
+
+ if (!TEST_true(create_ssl_connection(serverssl, clientssl,
+ SSL_ERROR_NONE)))
+ goto end;
+
+ SSL_get0_alpn_selected(clientssl, &prot, &protlen);
+ switch (idx) {
+ case 0:
+ if (!TEST_mem_eq(prot, protlen, fooprot + 1, *fooprot))
+ goto end;
+ break;
+ case 1:
+ if (!TEST_uint_eq(protlen, 0))
+ goto end;
+ break;
+ default:
+ TEST_error("Should not get here");
+ goto end;
+ }
+ }
+
+ testresult = 1;
+ end:
+ SSL_free(serverssl);
+ SSL_free(clientssl);
+ SSL_CTX_free(sctx);
+ SSL_CTX_free(cctx);
+
+ return testresult;
+}
+
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);
+ ADD_ALL_TESTS(test_select_next_proto, OSSL_NELEM(next_proto_tests));
+#if !defined(OPENSSL_NO_TLS1_2) && !defined(OPENSSL_NO_NEXTPROTONEG)
+ ADD_ALL_TESTS(test_npn, 5);
+#endif
+ ADD_ALL_TESTS(test_alpn, 4);
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/util/check-format-commit.sh b/crypto/openssl/util/check-format-commit.sh
new file mode 100755
index 000000000000..7e712dc48cf6
--- /dev/null
+++ b/crypto/openssl/util/check-format-commit.sh
@@ -0,0 +1,171 @@
+#!/bin/bash
+# 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
+#
+# This script is a wrapper around check-format.pl. It accepts a commit sha
+# value as input, and uses it to identify the files and ranges that were
+# changed in that commit, filtering check-format.pl output only to lines that
+# fall into the commits change ranges.
+#
+
+
+# List of Regexes to use when running check-format.pl.
+# Style checks don't apply to any of these
+EXCLUDED_FILE_REGEX=("\.pod" \
+ "\.pl" \
+ "\.pm" \
+ "\.t" \
+ "\.yml" \
+ "\.sh")
+
+# Exit code for the script
+EXIT_CODE=0
+
+# Global vars
+
+# TEMPDIR is used to hold any files this script creates
+# And is cleaned on EXIT with a trap function
+TEMPDIR=$(mktemp -d /tmp/checkformat.XXXXXX)
+
+# TOPDIR always points to the root of the git tree we are working in
+# used to locate the check-format.pl script
+TOPDIR=$(git rev-parse --show-toplevel)
+
+
+# cleanup handler function, returns us to the root of the git tree
+# and erases our temp directory
+cleanup() {
+ rm -rf $TEMPDIR
+ cd $TOPDIR
+}
+
+trap cleanup EXIT
+
+# Get the canonical sha256 sum for the commit we are checking
+# This lets us pass in symbolic ref names like master/etc and
+# resolve them to sha256 sums easily
+COMMIT=$(git rev-parse $1)
+
+# Fail gracefully if git rev-parse doesn't produce a valid
+# commit
+if [ $? -ne 0 ]
+then
+ echo "$1 is not a valid revision"
+ exit 1
+fi
+
+# Create a iteratable list of files to check for a
+# given commit. It produces output of the format
+# <commit id> <file name> <change start line>, <change line count>
+touch $TEMPDIR/ranges.txt
+git show $COMMIT | awk -v mycmt=$COMMIT '
+ BEGIN {myfile=""}
+ /+{3}/ {
+ gsub(/b\//,"",$2);
+ myfile=$2
+ }
+ /@@/ {
+ gsub(/+/,"",$3);
+ printf mycmt " " myfile " " $3 "\n"
+ }' >> $TEMPDIR/ranges.txt || true
+
+# filter out anything that matches on a filter regex
+for i in ${EXCLUDED_FILE_REGEX[@]}
+do
+ touch $TEMPDIR/ranges.filter
+ grep -v "$i" $TEMPDIR/ranges.txt >> $TEMPDIR/ranges.filter || true
+ REMAINING_FILES=$(wc -l $TEMPDIR/ranges.filter | awk '{print $1}')
+ if [ $REMAINING_FILES -eq 0 ]
+ then
+ echo "This commit has no files that require checking"
+ exit 0
+ fi
+ mv $TEMPDIR/ranges.filter $TEMPDIR/ranges.txt
+done
+
+# check out the files from the commit level.
+# For each file name in ranges, we show that file at the commit
+# level we are checking, and redirect it to the same path, relative
+# to $TEMPDIR/check-format. This give us the full file to run
+# check-format.pl on with line numbers matching the ranges in the
+# $TEMPDIR/ranges.txt file
+for j in $(grep $COMMIT $TEMPDIR/ranges.txt | awk '{print $2}')
+do
+ FDIR=$(dirname $j)
+ mkdir -p $TEMPDIR/check-format/$FDIR
+ git show $COMMIT:$j > $TEMPDIR/check-format/$j
+done
+
+# Now for each file in $TEMPDIR/check-format run check-format.pl
+# Note that we use the %P formatter in the find utilty. This strips
+# off the $TEMPDIR/check-format path prefix, leaving $j with the
+# path to the file relative to the root of the source dir, so that
+# output from check-format.pl looks correct, relative to the root
+# of the git tree.
+for j in $(find $TEMPDIR/check-format -type f -printf "%P\n")
+do
+ range_start=()
+ range_end=()
+
+ # Get the ranges for this file. Create 2 arrays. range_start contains
+ # the start lines for valid ranges from the commit. the range_end array
+ # contains the corresponding end line (note, since diff output gives us
+ # a line count for a change, the range_end[k] entry is actually
+ # range_start[k]+line count
+ for k in $(grep $COMMIT $TEMPDIR/ranges.txt | grep $j | awk '{print $3}')
+ do
+ RANGE=$k
+ RSTART=$(echo $RANGE | awk -F',' '{print $1}')
+ RLEN=$(echo $RANGE | awk -F',' '{print $2}')
+ let REND=$RSTART+$RLEN
+ range_start+=($RSTART)
+ range_end+=($REND)
+ done
+
+ # Go to our checked out tree
+ cd $TEMPDIR/check-format
+
+ # Actually run check-format.pl on the file, capturing the output
+ # in a temporary file. Note the format of check-patch.pl output is
+ # <file name>:<line number>:<error text>:<offending line contents>
+ $TOPDIR/util/check-format.pl $j > $TEMPDIR/format-results.txt
+
+ # Now we filter the check-format.pl output based on the changed lines
+ # captured in the range_start/end arrays
+ let maxidx=${#range_start[@]}-1
+ for k in $(seq 0 1 $maxidx)
+ do
+ RSTART=${range_start[$k]}
+ REND=${range_end[$k]}
+
+ # field 2 of check-format.pl output is the offending line number
+ # Check here if any line in that output falls between any of the
+ # start/end ranges defined in the range_start/range_end array.
+ # If it does fall in that range, print the entire line to stdout
+ # If anything is printed, have awk exit with a non-zero exit code
+ awk -v rstart=$RSTART -v rend=$REND -F':' '
+ BEGIN {rc=0}
+ /:/ {
+ if (($2 >= rstart) && ($2 <= rend)) {
+ print $0;
+ rc=1
+ }
+ }
+ END {exit rc;}
+ ' $TEMPDIR/format-results.txt
+
+ # If awk exited with a non-zero code, this script will also exit
+ # with a non-zero code
+ if [ $? -ne 0 ]
+ then
+ EXIT_CODE=1
+ fi
+ done
+done
+
+# Exit with the recorded exit code above
+exit $EXIT_CODE
diff --git a/crypto/openssl/util/check-format-test-negatives.c b/crypto/openssl/util/check-format-test-negatives.c
index b6c42a00a075..f6b1bfb31920 100644
--- a/crypto/openssl/util/check-format-test-negatives.c
+++ b/crypto/openssl/util/check-format-test-negatives.c
@@ -1,893 +1,892 @@
/*
- * Copyright 2007-2023 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2007-2024 The OpenSSL Project Authors. All Rights Reserved.
* Copyright Siemens AG 2015-2022
*
* 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
*/
/*
* A collection of test cases where check-format.pl should not report issues.
* There are some known false positives, though, which are marked below.
*/
#include <errno.h> /* should not report whitespace nits within <...> */
#define F \
void f() \
{ \
int i; \
int j; \
\
return; \
}
/* allow extra SPC in single-line comment */
/*
* allow extra SPC in regular multi-line comment
*/
/*-
* allow extra SPC in format-tagged multi-line comment
*/
/** allow extra '*' in comment opening */
/*! allow extra '!' in comment opening */
/*
** allow "**" as first non-space chars of a line within multi-line comment
*/
int f(void) /*
* trailing multi-line comment
*/
{
typedef int INT;
void v;
short b;
char c;
signed s;
unsigned u;
int i;
long l;
float f;
double d;
enum {} enu;
struct {} stru;
union {} un;
auto a;
extern e;
static int stat;
const int con;
volatile int vola;
register int reg;
OSSL_x y, *p = params;
int params[];
OSSL_PARAM * (* params []) [MAX + 1];
XY *(* fn)(int a, char b);
/*
* multi-line comment should not disturb detection of local decls
*/
BIO1 ***b;
/* intra-line comment should not disturb detection of local decls */
unsigned k;
/* intra-line comment should not disturb detection of end of local decls */
{
int x; /* just decls in block */
}
if (p != (unsigned char *)
&(ctx->tmp[0])) {
i -= (p - (unsigned char *) /* do not confuse with var decl */
&(ctx->tmp[0]));
}
{
ctx->buf_off = 0; /* do not confuse with var decl */
return 0;
}
{
ctx->buf_len = EVP_EncodeBlock((unsigned char *)ctx->buf,
(unsigned char *)ctx->tmp, /* no decl */
ctx->tmp_len);
}
{
EVP_EncodeFinal(ctx->base64,
(unsigned char *)ctx->buf, &(ctx->len)); /* no decl */
/* push out the bytes */
goto again;
}
{
f(1, (unsigned long)2); /* no decl */
x;
}
{
char *pass_str = get_passwd(opt_srv_secret, "x");
if (pass_str != NULL) {
cleanse(opt_srv_secret);
res = OSSL_CMP_CTX_set1_secretValue(ctx, (unsigned char *)pass_str,
strlen(pass_str));
clear_free(pass_str);
}
}
}
int g(void)
{
if (ctx == NULL) { /* non-leading end-of-line comment */
if (/* comment after '(' */ pem_name != NULL /* comment before ')' */)
/* entire-line comment indent usually like for the following line */
return NULL; /* hanging indent also for this line after comment */
/* leading comment has same indentation as normal code */ stmt;
/* entire-line comment may have same indent as normal code */
}
for (i = 0; i < n; i++)
for (; i < n; i++)
for (i = 0; ; i++)
for (i = 0;; i++)
for (i = 0; i < n; )
for (i = 0; i < n;)
;
for (i = 0; ; )
for (i = 0; ;)
for (i = 0;; )
for (i = 0;;)
for (; i < n; )
for (; j < n;)
for (; ; i++)
for (;; i++)
;
for (;;) /* the only variant allowed in case of "empty" for (...) */
;
for (;;) ; /* should not trigger: space before ';' */
lab: ; /* should not trigger: space before ';' */
#if X
if (1) /* bad style: just part of control structure depends on #if */
#else
if (2) /*@ resulting false positive */
#endif
c; /*@ resulting false positive */
if (1)
if (2)
c;
else
e;
else
f;
do
do
2;
while (1);
while (2);
if (1)
f(a, b);
do
1; while (2); /*@ more than one stmt just to construct case */
if (1)
f(a, b);
else
do
1;
while (2);
if (1)
f(a, b);
else do /*@ (non-brace) code before 'do' just to construct case */
1;
while (2);
f1234(a,
b); do /*@ (non-brace) code before 'do' just to construct case */
1;
while (2);
if (1)
f(a,
b); do /*@ (non-brace) code before 'do' just to construct case */
1;
while (2);
if (1)
f(a, b);
else
do f(c, c); /*@ (non-brace) code after 'do' just to construct case */
while (2);
if (1)
f(a, b);
else
return;
if (1)
f(a,
b); else /*@ (non-brace) code before 'else' just to construct case */
do
1;
while (2);
if (1)
{ /*@ brace after 'if' not on same line just to construct case */
c;
d;
}
/* this comment is correctly indented if it refers to the following line */
d;
if (1) {
2;
} else /*@ no brace after 'else' just to construct case */
3;
do {
} while (x);
if (1) {
2;
} else {
3;
}
if (4)
5;
else
6;
if (1) {
if (2) {
case MAC_TYPE_MAC:
{
EVP_MAC_CTX *new_mac_ctx;
if (ctx->pkey == NULL)
return 0;
}
break;
default:
/* This should be dead code */
return 0;
}
}
if (expr_line1
== expr_line2
&& expr_line3) {
c1;
} else {
c;
d;
}
if (expr_line1
== expr_line2
&& expr_line3)
hanging_stmt;
}
#define m \
do { /* should not be confused with function header followed by '{' */ \
} while (0)
/* should not trigger: constant on LHS of comparison or assignment operator */
X509 *x509 = NULL;
int y = a + 1 < b;
int ret, was_NULL = *certs == NULL;
/* should not trigger: missing space before ... */
float z = 1e-6 * (-1) * b[+6] * 1e+1 * (a)->f * (long)+1
- (tmstart.tv_sec + tmstart.tv_nsec * 1e-9);
struct st = {-1, 0};
int x = (y <<= 1) + (z <= 5.0);
const OPTIONS passwd_options[] = {
{"aixmd5", OPT_AIXMD5, '-', "AIX MD5-based password algorithm"},
#if !defined(OPENSSL_NO_DES) && !defined(OPENSSL_NO_DEPRECATED_3_0)
{"crypt", OPT_CRYPT, '-', "Standard Unix password algorithm (default)"},
#endif
OPT_R_OPTIONS,
{NULL}
};
typedef * d(int)
x;
typedef (int)
x;
typedef (int)*()
x;
typedef *int *
x;
typedef OSSL_CMP_MSG *(*cmp_srv_process_cb_t)
(OSSL_CMP_SRV_CTX *ctx, OSSL_CMP_MSG *msg)
xx;
#define IF(cond) if (cond)
_Pragma("GCC diagnostic push")
_Pragma("GCC diagnostic pop")
#define CB_ERR_IF(cond, ctx, cert, depth, err) \
if ((cond) && ((depth) < 0 || verify_cb_cert(ctx, cert, depth, err) == 0)) \
return err
static int verify_cb_crl(X509_STORE_CTX *ctx, int err)
{
ctx->error = err;
return ctx->verify_cb(0, ctx);
}
#ifdef CMP_FALLBACK_EST
# define CMP_FALLBACK_CERT_FILE "cert.pem"
#endif
#define X509_OBJECT_get0_X509(obj) \
((obj) == NULL || (obj)->type != X509_LU_X509 ? NULL : (obj)->data.x509)
#define X509_STORE_CTX_set_current_cert(ctx, x) { (ctx)->current_cert = (x); }
#define X509_STORE_set_ex_data(ctx, idx, data) \
CRYPTO_set_ex_data(&(ctx)->ex_data, (idx), (data))
typedef int (*X509_STORE_CTX_check_revocation_fn)(X509_STORE_CTX *ctx);
#define X509_STORE_CTX_set_error_depth(ctx, depth) \
{ (ctx)->error_depth = (depth); }
#define EVP_PKEY_up_ref(x) ((x)->references++)
/* should not report missing blank line: */
DECLARE_STACK_OF(OPENSSL_CSTRING)
bool UTIL_iterate_dir(int (*fn)(const char *file, void *arg), void *arg,
const char *path, bool recursive);
size_t UTIL_url_encode(
size_t *size_needed
);
size_t UTIL_url_encode(const char *source,
char *destination,
size_t destination_len,
size_t *size_needed);
#error well. oops.
int f()
{
c;
- if (1) {
+ if (1)
c;
- }
c;
if (1)
if (2)
{ /*@ brace after 'if' not on same line just to construct case */
c;
}
e;
const usign = {
0xDF,
{
dd
},
dd
};
const unsign = {
0xDF, {
dd
},
dd
};
}
const unsigned char trans_id[OSSL_CMP_TRANSACTIONID_LENGTH] = {
0xDF,
};
const unsigned char trans_id[OSSL_CMP_TRANSACTIONID_LENGTH] =
{
0xDF,
};
typedef
int
a;
typedef
struct
{
int a;
} b;
typedef enum {
w = 0
} e_type;
typedef struct {
enum {
w = 0
} e_type;
enum {
w = 0
} e_type;
} e;
struct s_type {
enum e_type {
w = 0
};
};
struct s_type
{
enum e_type {
w = 0
};
enum e2_type {
w = 0
};
};
#define X 1 + 1
#define Y /* .. */ 2 + 2
#define Z 3 + 3 * (*a++)
static varref cmp_vars[] = { /* comment. comment? comment! */
{&opt_config}, {&opt_section},
{&opt_server}, {&opt_proxy}, {&opt_path},
};
#define SWITCH(x) \
switch (x) { \
case 0: \
break; \
default: \
break; \
}
#define DEFINE_SET_GET_BASE_TEST(PREFIX, SETN, GETN, DUP, FIELD, TYPE, ERR, \
DEFAULT, NEW, FREE) \
static int execute_CTX_##SETN##_##GETN##_##FIELD( \
TEST_FIXTURE *fixture) \
{ \
CTX *ctx = fixture->ctx; \
int (*set_fn)(CTX *ctx, TYPE) = \
(int (*)(CTX *ctx, TYPE))PREFIX##_##SETN##_##FIELD; \
/* comment */ \
}
union un var; /* struct/union/enum in variable type */
struct provider_store_st *f() /* struct/union/enum in function return type */
{
}
static void f(struct pem_pass_data *data) /* struct/union/enum in arg list */
{
}
static void *fun(void)
{
if (pem_name != NULL)
/* comment */
return NULL;
label0:
label1: /* allow special indent 1 for label at outermost level in body */
do {
label2:
size_t available_len, data_len;
const char *curr = txt, *next = txt;
char *tmp;
{
label3:
}
} while (1);
char *intraline_string_with_comment_delimiters_and_dbl_space = "1 /*1";
char *multiline_string_with_comment_delimiters_and_dbl_space = "1 /*1\
2222222\'22222222222222222\"222222222" "33333 /*3333333333" "44 /*44444444444\
55555555555555\
6666";
}
ASN1_CHOICE(OSSL_CRMF_POPO) = {
ASN1_IMP(OSSL_CRMF_POPO, value.raVerified, ASN1_NULL, 0),
ASN1_EXP(OSSL_CRMF_POPO, value.keyAgreement, OSSL_CRMF_POPOPRIVKEY, 3)
} ASN1_CHOICE_END(OSSL_CRMF_POPO)
IMPLEMENT_ASN1_FUNCTIONS(OSSL_CRMF_POPO)
ASN1_ADB(OSSL_CRMF_ATTRIBUTETYPEANDVALUE) = {
ADB_ENTRY(NID_id_regCtrl_regToken,
ASN1_SIMPLE(OSSL_CRMF_ATTRIBUTETYPEANDVALUE,
value.regToken, ASN1_UTF8STRING)),
} ASN1_ADB_END(OSSL_CRMF_ATTRIBUTETYPEANDVALUE, 0, type, 0,
&attributetypeandvalue_default_tt, NULL);
ASN1_ITEM_TEMPLATE(OSSL_CRMF_MSGS) =
ASN1_EX_TEMPLATE_TYPE(ASN1_TFLG_SEQUENCE_OF, 0,
OSSL_CRMF_MSGS, OSSL_CRMF_MSG)
ASN1_ITEM_TEMPLATE_END(OSSL_CRMF_MSGS)
void f_looong_body_200()
{ /* function body length up to 200 lines accepted */
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
}
void f_looong_body_201()
{ /* function body length > 200 lines, but LONG BODY marker present */
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
}
diff --git a/crypto/openssl/util/check-format.pl b/crypto/openssl/util/check-format.pl
index e1a91bcc5815..ef2c1920e722 100755
--- a/crypto/openssl/util/check-format.pl
+++ b/crypto/openssl/util/check-format.pl
@@ -1,1272 +1,1275 @@
#! /usr/bin/env perl
#
-# Copyright 2020-2023 The OpenSSL Project Authors. All Rights Reserved.
+# Copyright 2020-2024 The OpenSSL Project Authors. All Rights Reserved.
# Copyright Siemens AG 2019-2022
#
# 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
#
# check-format.pl
# - check formatting of C source according to OpenSSL coding style
#
# usage:
# check-format.pl [-l|--sloppy-len] [-l|--sloppy-bodylen]
# [-s|--sloppy-space] [-c|--sloppy-comment]
# [-m|--sloppy-macro] [-h|--sloppy-hang]
# [-e|--eol-comment] [-1|--1-stmt]
# <files>
#
# run self-tests:
# util/check-format.pl util/check-format-test-positives.c
# util/check-format.pl util/check-format-test-negatives.c
#
# checks adherence to the formatting rules of the OpenSSL coding guidelines
# assuming that the input files contain syntactically correct C code.
# This pragmatic tool is incomplete and yields some false positives.
# Still it should be useful for detecting most typical glitches.
#
# options:
# -l | --sloppy-len increase accepted max line length from 80 to 84
# -l | --sloppy-bodylen do not report function body length > 200
# -s | --sloppy-space do not report whitespace nits
# -c | --sloppy-comment do not report indentation of comments
# Otherwise for each multi-line comment the indentation of
# its lines is checked for consistency. For each comment
# that does not begin to the right of normal code its
# indentation must be as for normal code, while in case it
# also has no normal code to its right it is considered to
# refer to the following line and may be indented equally.
# -m | --sloppy-macro allow missing extra indentation of macro bodies
# -h | --sloppy-hang when checking hanging indentation, do not report
# * same indentation as on line before
# * same indentation as non-hanging indent level
# * indentation moved left (not beyond non-hanging indent)
# just to fit contents within the line length limit
# -e | --eol-comment report needless intermediate multiple consecutive spaces also before end-of-line comments
# -1 | --1-stmt do more aggressive checks for { 1 stmt } - see below
#
# There are non-trivial false positives and negatives such as the following.
#
# * When a line contains several issues of the same kind only one is reported.
#
# * When a line contains more than one statement this is (correctly) reported
# but in some situations the indentation checks for subsequent lines go wrong.
#
# * There is the special OpenSSL rule not to unnecessarily use braces around
# single statements:
# {
# stmt;
# }
# except within if ... else constructs where some branch contains more than one
# statement. Since the exception is hard to recognize when such branches occur
# after the current position (such that false positives would be reported)
# the tool by checks for this rule by default only for do/while/for bodies.
# Yet with the --1-stmt option false positives are preferred over negatives.
# False negatives occur if the braces are more than two non-blank lines apart.
#
# * The presence of multiple consecutive spaces is regarded a coding style nit
# except when this is before end-of-line comments (unless the --eol-comment is given) and
# except when done in order to align certain columns over multiple lines, e.g.:
# # define AB 1
# # define CDE 22
# # define F 3333
# This pattern is recognized - and consequently extra space not reported -
# for a given line if in the non-blank line before or after (if existing)
# for each occurrence of " \S" (where \S means non-space) in the given line
# there is " \S" in the other line in the respective column position.
# This may lead to both false negatives (in case of coincidental " \S")
# and false positives (in case of more complex multi-column alignment).
#
# * When just part of control structures depend on #if(n)(def), which can be
# considered bad programming style, indentation false positives occur, e.g.:
# #if X
# if (1) /* bad style */
# #else
# if (2) /* bad style resulting in false positive */
# #endif
# c; /* resulting further false positive */
use strict;
# use List::Util qw[min max];
use POSIX;
use constant INDENT_LEVEL => 4;
use constant MAX_LINE_LENGTH => 80;
use constant MAX_BODY_LENGTH => 200;
# global variables @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
# command-line options
my $max_length = MAX_LINE_LENGTH;
my $sloppy_bodylen = 0;
my $sloppy_SPC = 0;
my $sloppy_hang = 0;
my $sloppy_cmt = 0;
my $sloppy_macro = 0;
my $eol_cmt = 0;
my $extended_1_stmt = 0;
while ($ARGV[0] =~ m/^-(\w|-[\w\-]+)$/) {
my $arg = $1; shift;
if ($arg =~ m/^(l|-sloppy-len)$/) {
$max_length += INDENT_LEVEL;
} elsif ($arg =~ m/^(b|-sloppy-bodylen)$/) {
$sloppy_bodylen = 1;
} elsif ($arg =~ m/^(s|-sloppy-space)$/) {
$sloppy_SPC= 1;
} elsif ($arg =~ m/^(c|-sloppy-comment)$/) {
$sloppy_cmt = 1;
} elsif ($arg =~ m/^(m|-sloppy-macro)$/) {
$sloppy_macro = 1;
} elsif ($arg =~ m/^(h|-sloppy-hang)$/) {
$sloppy_hang = 1;
} elsif ($arg =~ m/^(e|-eol-comment)$/) {
$eol_cmt = 1;
} elsif ($arg =~ m/^(1|-1-stmt)$/) {
$extended_1_stmt = 1;
} else {
die("unknown option: -$arg");
}
}
# state variables
my $self_test; # whether the current input file is regarded to contain (positive/negative) self-tests
my $in_comment; # number of lines so far within multi-line comment, 0 if no comment, < 0 when end is on current line
my $leading_comment; # multi-line comment has no code before its beginning delimiter, if $in_comment != 0
my $formatted_comment; # multi-line comment beginning with "/*-", which indicates/allows special formatting, if $in_comment != 0
my $comment_indent; # comment indent, if $in_comment != 0
my $ifdef__cplusplus; # line before contained '#ifdef __cplusplus' (used in header files)
my $preproc_if_nesting; # currently required indentation of preprocessor directive according to #if(n)(def)
my $in_preproc; # 0 or number of lines so far within preprocessor directive, e.g., macro definition
my $preproc_directive; # name of current preprocessor directive, if $in_preproc != 0
my $preproc_offset; # offset to $block_indent within multi-line preprocessor directive, else 0
my $in_macro_header; # number of open parentheses + 1 in (multi-line) header of #define, if $in_preproc != 0
my $line; # current line number
my $line_before; # number of previous not essentially blank line (containing at most whitespace and '\')
my $line_before2; # number of not essentially blank line before previous not essentially blank line
# indentation state
my $contents; # contents of current line (without blinding)
# $_ # current line, where comments etc. get blinded
my $code_contents_before; # contents of previous non-comment non-preprocessor-directive line (without blinding), initially ""
my $contents_before; # contents of $line_before (without blinding), if $line_before > 0
my $contents_before_; # contents of $line_before after blinding comments etc., if $line_before > 0
my $contents_before2; # contents of $line_before2 (without blinding), if $line_before2 > 0
my $contents_before_2; # contents of $line_before2 after blinding comments etc., if $line_before2 > 0
my $in_multiline_string; # line starts within multi-line string literal
my $count; # -1 or number of leading whitespace characters (except newline) in current line,
# which should be $block_indent + $hanging_offset + $local_offset or $expr_indent
my $count_before; # number of leading whitespace characters (except line ending chars) in $contents_before
my $has_label; # current line contains label
my $local_offset; # current extra indent due to label, switch case/default, or leading closing brace(s)
my $line_body_start; # number of line where last function body started, or 0
my $line_function_start; # number of line where last function definition started, used for $line_body_start
my $last_function_header; # header containing name of last function defined, used if $line_body_start != 0
-my $line_opening_brace; # number of previous line with opening brace after do/while/for, optionally for if/else
+my $line_opening_brace; # number of previous line with opening brace after if/do/while/for, optionally for 'else'
my $keyword_opening_brace; # name of previous keyword, used if $line_opening_brace != 0
my $block_indent; # currently required normal indentation at block/statement level
my $hanging_offset; # extra indent, which may be nested, for just one hanging statement or expr or typedef
my @in_do_hanging_offsets; # stack of hanging offsets for nested 'do' ... 'while'
my @in_if_hanging_offsets; # stack of hanging offsets for nested 'if' (but not its potential 'else' branch)
my $if_maybe_terminated; # 'if' ends and $hanging_offset should be reset unless the next line starts with 'else'
my @nested_block_indents; # stack of indentations at block/statement level, needed due to hanging statements
my @nested_hanging_offsets;# stack of nested $hanging_offset values, in parallel to @nested_block_indents
my @nested_in_typedecl; # stack of nested $in_typedecl values, partly in parallel to @nested_block_indents
my @nested_indents; # stack of hanging indents due to parentheses, braces, brackets, or conditionals
my @nested_symbols; # stack of hanging symbols '(', '{', '[', or '?', in parallel to @nested_indents
my @nested_conds_indents; # stack of hanging indents due to conditionals ('?' ... ':')
my $expr_indent; # resulting hanging indent within (multi-line) expressions including type exprs, else 0
my $hanging_symbol; # character ('(', '{', '[', not: '?') responsible for $expr_indent, if $expr_indent != 0
my $in_block_decls; # number of local declaration lines after block opening before normal statements, or -1 if no block opening
my $in_expr; # in expression after if/while/for/switch/return/enum/LHS of assignment
my $in_paren_expr; # in parenthesized if/while/for condition and switch expression, if $expr_indent != 0
my $in_typedecl; # nesting level of typedef/struct/union/enum
my $num_reports_line = 0; # number of issues found on current line
my $num_reports = 0; # total number of issues found
my $num_indent_reports = 0;# total number of indentation issues found
my $num_nesting_issues = 0;# total number of preprocessor #if nesting issues found
my $num_syntax_issues = 0; # total number of syntax issues found during sanity checks
my $num_SPC_reports = 0; # total number of whitespace issues found
my $num_length_reports = 0;# total number of line length issues found
sub reset_file_state {
$in_comment = 0;
$ifdef__cplusplus = 0;
$preproc_if_nesting = 0;
$in_preproc = 0;
$line = 0;
$line_before = 0;
$line_before2 = 0;
reset_indentation_state();
}
sub reset_indentation_state {
$code_contents_before = "";
@nested_block_indents = ();
@nested_hanging_offsets = ();
@nested_in_typedecl = ();
@nested_symbols = ();
@nested_indents = ();
@nested_conds_indents = ();
$expr_indent = 0;
$in_block_decls = -1;
$in_expr = 0;
$in_paren_expr = 0;
$hanging_offset = 0;
@in_do_hanging_offsets = ();
@in_if_hanging_offsets = ();
$if_maybe_terminated = 0;
$block_indent = 0;
$in_multiline_string = 0;
$line_body_start = 0;
$line_opening_brace = 0;
$in_typedecl = 0;
}
my $bak_line_before;
my $bak_line_before2;
my $bak_code_contents_before;
my @bak_nested_block_indents;
my @bak_nested_hanging_offsets;
my @bak_nested_in_typedecl;
my @bak_nested_symbols;
my @bak_nested_indents;
my @bak_nested_conds_indents;
my $bak_expr_indent;
my $bak_in_block_decls;
my $bak_in_expr;
my $bak_in_paren_expr;
my $bak_hanging_offset;
my @bak_in_do_hanging_offsets;
my @bak_in_if_hanging_offsets;
my $bak_if_maybe_terminated;
my $bak_block_indent;
my $bak_in_multiline_string;
my $bak_line_body_start;
my $bak_line_opening_brace;
my $bak_in_typedecl;
sub backup_indentation_state {
$bak_code_contents_before = $code_contents_before;
@bak_nested_block_indents = @nested_block_indents;
@bak_nested_hanging_offsets = @nested_hanging_offsets;
@bak_nested_in_typedecl = @nested_in_typedecl;
@bak_nested_symbols = @nested_symbols;
@bak_nested_indents = @nested_indents;
@bak_nested_conds_indents = @nested_conds_indents;
$bak_expr_indent = $expr_indent;
$bak_in_block_decls = $in_block_decls;
$bak_in_expr = $in_expr;
$bak_in_paren_expr = $in_paren_expr;
$bak_hanging_offset = $hanging_offset;
@bak_in_do_hanging_offsets = @in_do_hanging_offsets;
@bak_in_if_hanging_offsets = @in_if_hanging_offsets;
$bak_if_maybe_terminated = $if_maybe_terminated;
$bak_block_indent = $block_indent;
$bak_in_multiline_string = $in_multiline_string;
$bak_line_body_start = $line_body_start;
$bak_line_opening_brace = $line_opening_brace;
$bak_in_typedecl = $in_typedecl;
}
sub restore_indentation_state {
$code_contents_before = $bak_code_contents_before;
@nested_block_indents = @bak_nested_block_indents;
@nested_hanging_offsets = @bak_nested_hanging_offsets;
@nested_in_typedecl = @bak_nested_in_typedecl;
@nested_symbols = @bak_nested_symbols;
@nested_indents = @bak_nested_indents;
@nested_conds_indents = @bak_nested_conds_indents;
$expr_indent = $bak_expr_indent;
$in_block_decls = $bak_in_block_decls;
$in_expr = $bak_in_expr;
$in_paren_expr = $bak_in_paren_expr;
$hanging_offset = $bak_hanging_offset;
@in_do_hanging_offsets = @bak_in_do_hanging_offsets;
@in_if_hanging_offsets = @bak_in_if_hanging_offsets;
$if_maybe_terminated = $bak_if_maybe_terminated;
$block_indent = $bak_block_indent;
$in_multiline_string = $bak_in_multiline_string;
$line_body_start = $bak_line_body_start;
$line_opening_brace = $bak_line_opening_brace;
$in_typedecl = $bak_in_typedecl;
}
# auxiliary submodules @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
sub report_flexibly {
my $line = shift;
my $msg = shift;
my $contents = shift;
my $report_SPC = $msg =~ /space|blank/;
return if $report_SPC && $sloppy_SPC;
print "$ARGV:$line:$msg:$contents" unless $self_test;
$num_reports_line++;
$num_reports++;
$num_indent_reports++ if $msg =~ m/:indent /;
$num_nesting_issues++ if $msg =~ m/ nesting indent /;
$num_syntax_issues++ if $msg =~ m/unclosed|unexpected/;
$num_SPC_reports++ if $report_SPC;
$num_length_reports++ if $msg =~ m/length/;
}
sub report {
my $msg = shift;
report_flexibly($line, $msg, $contents);
}
sub parens_balance { # count balance of opening parentheses - closing parentheses
my $str = shift;
return $str =~ tr/\(// - $str =~ tr/\)//;
}
sub blind_nonspace { # blind non-space text of comment as @, preserving length and spaces
# the @ character is used because it cannot occur in normal program code so there is no confusion
# comment text is not blinded to whitespace in order to be able to check extra SPC also in comments
my $comment_text = shift;
$comment_text =~ s/([\.\?\!])\s\s/$1. /g; # in extra SPC checks allow one extra SPC after period '.', '?', or '!' in comments
return $comment_text =~ tr/ /@/cr;
}
# submodule for indentation checking/reporting @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
sub check_indent { # used for lines outside multi-line string literals
my $stmt_indent = $block_indent + $hanging_offset + $local_offset;
# print "DEBUG: expr_indent $expr_indent; stmt_indent $stmt_indent = block_indent $block_indent + hanging_offset $hanging_offset + local_offset $local_offset\n";
$stmt_indent = 0 if $stmt_indent < 0; # TODO maybe give warning/error
my $stmt_desc = $contents =~
m/^\s*\/\*/ ? "intra-line comment" :
$has_label ? "label" :
($hanging_offset != 0 ? "hanging " : "").
($hanging_offset != 0 ? "stmt/expr" : "stmt/decl"); # $in_typedecl is not fully to the point here
my ($ref_desc, $ref_indent) = $expr_indent == 0 ? ($stmt_desc, $stmt_indent)
: ("hanging '$hanging_symbol'", $expr_indent);
my ($alt_desc, $alt_indent) = ("", $ref_indent);
# allow indent 1 for labels - this cannot happen for leading ':'
($alt_desc, $alt_indent) = ("outermost position", 1) if $expr_indent == 0 && $has_label;
if (@nested_conds_indents != 0 && substr($_, $count, 1) eq ":") {
# leading ':' within stmt/expr/decl - this cannot happen for labels, leading '&&', or leading '||'
# allow special indent at level of corresponding "?"
($alt_desc, $alt_indent) = ("leading ':'", @nested_conds_indents[-1]);
}
# allow extra indent offset leading '&&' or '||' - this cannot happen for leading ":"
($alt_desc, $alt_indent) = ("leading '$1'", $ref_indent + INDENT_LEVEL) if $contents =~ m/^[\s@]*(\&\&|\|\|)/;
if ($expr_indent < 0) { # implies @nested_symbols != 0 && @nested_symbols[0] eq "{" && @nested_indents[-1] < 0
# allow normal stmt indentation level for hanging initializer/enum expressions after trailing '{'
# this cannot happen for labels and overrides special treatment of ':', '&&' and '||' for this line
($alt_desc, $alt_indent) = ("lines after '{'", $stmt_indent);
# decide depending on current actual indentation, preventing forth and back
@nested_indents[-1] = $count == $stmt_indent ? $stmt_indent : -@nested_indents[-1]; # allow $stmt_indent
$ref_indent = $expr_indent = @nested_indents[-1];
}
# check consistency of indentation within multi-line comment (i.e., between its first, inner, and last lines)
if ($in_comment != 0 && $in_comment != 1) { # in multi-line comment but not on its first line
if (!$sloppy_cmt) {
if ($in_comment > 0) { # not at its end
report("indent = $count != $comment_indent within multi-line comment")
if $count != $comment_indent;
} else {
my $tweak = $in_comment == -2 ? 1 : 0;
report("indent = ".($count + $tweak)." != $comment_indent at end of multi-line comment")
if $count + $tweak != $comment_indent;
}
}
# do not check indentation of last line of non-leading multi-line comment
if ($in_comment < 0 && !$leading_comment) {
s/^(\s*)@/$1*/; # blind first '@' as '*' to prevent below delayed check for the line before
return;
}
return if $in_comment > 0; # not on its last line
# $comment_indent will be checked by the below checks for end of multi-line comment
}
# else check indentation of entire-line comment or entire-line end of multi-line comment
# ... w.r.t. indent of the following line by delayed check for the line before
if (($in_comment == 0 || $in_comment == 1) # no comment, intra-line comment, or begin of multi-line comment
&& $line_before > 0 # there is a line before
&& $contents_before_ =~ m/^(\s*)@[\s@]*$/) { # line before begins with '@', no code follows (except '\')
report_flexibly($line_before, "entire-line comment indent = $count_before != $count (of following line)",
$contents_before) if !$sloppy_cmt && $count_before != -1 && $count_before != $count;
}
# ... but allow normal indentation for the current line, else above check will be done for the line before
if (($in_comment == 0 || $in_comment < 0) # (no comment,) intra-line comment or end of multi-line comment
&& m/^(\s*)@[\s@]*$/) { # line begins with '@', no code follows (except '\')
if ($count == $ref_indent) { # indentation is like for (normal) code in this line
s/^(\s*)@/$1*/; # blind first '@' as '*' to prevent above delayed check for the line before
return;
}
return if !eof; # defer check of entire-line comment to next line
}
# else check indentation of leading intra-line comment or end of multi-line comment
if (m/^(\s*)@/) { # line begins with '@', i.e., any (remaining type of) comment
if (!$sloppy_cmt && $count != $ref_indent) {
report("intra-line comment indent = $count != $ref_indent") if $in_comment == 0;
report("multi-line comment indent = $count != $ref_indent") if $in_comment < 0;
}
return;
}
if ($sloppy_hang && ($hanging_offset != 0 || $expr_indent != 0)) {
# do not report same indentation as on the line before (potentially due to same violations)
return if $line_before > 0 && $count == $count_before;
# do not report indentation at normal indentation level while hanging expression indent would be required
return if $expr_indent != 0 && $count == $stmt_indent;
# do not report if contents have been shifted left of nested expr indent (but not as far as stmt indent)
# apparently aligned to the right in order to fit within line length limit
return if $stmt_indent < $count && $count < $expr_indent &&
length($contents) == MAX_LINE_LENGTH + length("\n");
}
report("indent = $count != $ref_indent for $ref_desc".
($alt_desc eq ""
|| $alt_indent == $ref_indent # prevent showing alternative that happens to have equal value
? "" : " or $alt_indent for $alt_desc"))
if $count != $ref_indent && $count != $alt_indent;
}
# submodules handling indentation within expressions @@@@@@@@@@@@@@@@@@@@@@@@@@@
sub update_nested_indents { # may reset $in_paren_expr and in this case also resets $in_expr
my $str = shift;
my $start = shift; # defaults to 0
my $terminator_position = -1;
for (my $i = $start; $i < length($str); $i++) {
my $c;
my $curr = substr($str, $i);
if ($curr =~ m/^(.*?)([{}()?:;\[\]])(.*)$/) { # match from position $i the first {}()?:;[]
$c = $2;
} else {
last;
}
my ($head, $tail) = (substr($str, 0, $i).$1, $3);
$i += length($1) + length($2) - 1;
# stop at terminator outside 'for (..;..;..)', assuming that 'for' is followed by '('
return $i if $c eq ";" && (!$in_paren_expr || @nested_indents == 0);
my $in_stmt = $in_expr || @nested_symbols != 0; # not: || $in_typedecl != 0
if ($c =~ m/[{([?]/) { # $c is '{', '(', '[', or '?'
if ($c eq "{") { # '{' in any context
$in_block_decls = 0 if !$in_expr && $in_typedecl == 0;
# cancel newly hanging_offset if opening brace '{' is after non-whitespace non-comment:
$hanging_offset -= INDENT_LEVEL if $hanging_offset > 0 && $head =~ m/[^\s\@]/;
push @nested_block_indents, $block_indent;
push @nested_hanging_offsets, $in_expr ? $hanging_offset : 0;
push @nested_in_typedecl, $in_typedecl if $in_typedecl != 0;
$block_indent += INDENT_LEVEL + $hanging_offset;
$hanging_offset = 0;
}
if ($c ne "{" || $in_stmt) { # for '{' inside stmt/expr (not: decl), for '(', '[', or '?' anywhere
$tail =~ m/^([\s@]*)([^\s\@])/;
push @nested_indents, defined $2
? $i + 1 + length($1) # actual indentation of following non-space non-comment
: $c ne "{" ? +($i + 1) # just after '(' or '[' if only whitespace thereafter
: -($i + 1); # allow also $stmt_indent if '{' with only whitespace thereafter
push @nested_symbols, $c; # done also for '?' to be able to check correct nesting
push @nested_conds_indents, $i if $c eq "?"; # remember special alternative indent for ':'
}
} elsif ($c =~ m/[})\]:]/) { # $c is '}', ')', ']', or ':'
my $opening_c = ($c =~ tr/})]:/{([/r);
if (($c ne ":" || $in_stmt # ignore ':' outside stmt/expr/decl
# in the presence of ':', one could add this sanity check:
# && !(# ':' after initial label/case/default
# $head =~ m/^([\s@]*)(case\W.*$|\w+$)/ || # this matching would not work for
# # multi-line expr after 'case'
# # bitfield length within unsigned type decl
# $tail =~ m/^[\s@]*\d+/ # this matching would need improvement
# )
)) {
if ($c ne "}" || $in_stmt) { # for '}' inside stmt/expr/decl, ')', ']', or ':'
if (@nested_symbols != 0 &&
@nested_symbols[-1] == $opening_c) { # for $c there was a corresponding $opening_c
pop @nested_indents;
pop @nested_symbols;
pop @nested_conds_indents if $opening_c eq "?";
} else {
report("unexpected '$c' @ ".($in_paren_expr ? "(expr)" : "expr"));
next;
}
}
if ($c eq "}") { # '}' at block level but also inside stmt/expr/decl
if (@nested_block_indents == 0) {
report("unexpected '}'");
} else {
$block_indent = pop @nested_block_indents;
$hanging_offset = pop @nested_hanging_offsets;
$in_typedecl = pop @nested_in_typedecl if @nested_in_typedecl != 0;
}
}
if ($in_paren_expr && !grep(/\(/, @nested_symbols)) { # end of (expr)
check_nested_nonblock_indents("(expr)");
$in_paren_expr = $in_expr = 0;
report("code after (expr)")
if $tail =~ m/^([^{]*)/ && $1 =~ m/[^\s\@;]/; # non-space non-';' before any '{'
}
}
}
}
return -1;
}
sub check_nested_nonblock_indents {
my $position = shift;
while (@nested_symbols != 0) {
my $symbol = pop @nested_symbols;
report("unclosed '$symbol' in $position");
if ($symbol eq "{") { # repair stack of blocks
$block_indent = pop @nested_block_indents;
$hanging_offset = pop @nested_hanging_offsets;
$in_typedecl = pop @nested_in_typedecl if @nested_in_typedecl != 0;
}
}
@nested_indents = ();
@nested_conds_indents = ();
}
# start of main program @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
reset_file_state();
while (<>) { # loop over all lines of all input files
$self_test = $ARGV =~ m/check-format-test/;
$_ = "" if $self_test && m/ blank line within local decls /;
$line++;
s/\r$//; # strip any trailing CR '\r' (which are typical on Windows systems)
$contents = $_;
# check for illegal characters
if (m/(.*?)([\x00-\x09\x0B-\x1F\x7F-\xFF])/) {
my $col = length($1);
report(($2 eq "\x09" ? "TAB" : $2 eq "\x0D" ? "CR " : $2 =~ m/[\x00-\x1F]/ ? "non-printable"
: "non-7bit char") . " at column $col") ;
}
# check for whitespace at EOL
report("trailing whitespace at EOL") if m/\s\n$/;
# assign to $count the actual indentation level of the current line
chomp; # remove trailing NL '\n'
m/^(\s*)/;
$count = length($1); # actual indentation
$has_label = 0;
$local_offset = 0;
# character/string literals @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
s/\\["']/@@/g; # blind all '"' and "'" escaped by '\' (typically within character literals or string literals)
# handle multi-line string literals to avoid confusion on starting/ending '"' and trailing '\'
if ($in_multiline_string) {
if (s#^([^"]*)"#($1 =~ tr/"/@/cr).'@'#e) { # string literal terminated by '"'
# string contents and its terminating '"' have been blinded as '@'
$count = -1; # do not check indentation
} else {
report("multi-line string literal not terminated by '\"' and trailing '\' is missing")
unless s#^([^\\]*)\s*\\\s*$#$1#; # strip trailing '\' plus any whitespace around
goto LINE_FINISHED;
}
}
# blind contents of character and string literals as @, preserving length (but not spaces)
# this prevents confusing any of the matching below, e.g., of whitespace and comment delimiters
s#('[^']*')#$1 =~ tr/'/@/cr#eg; # handle all intra-line character literals
s#("[^"]*")#$1 =~ tr/"/@/cr#eg; # handle all intra-line string literals
$in_multiline_string = # handle trailing string literal terminated by '\'
s#^(([^"]*"[^"]*")*[^"]*)("[^"]*)\\(\s*)$#$1.($3 =~ tr/"/@/cr).'"'.$4#e;
# its contents have been blinded and the trailing '\' replaced by '"'
# strip any other trailing '\' along with any whitespace around it such that it does not interfere with various matching below
my $trailing_backslash = s#^(.*?)\s*\\\s*$#$1#; # trailing '\' possibly preceded or followed by whitespace
my $essentially_blank_line = m/^\s*$/; # just whitespace and maybe a '\'
# comments @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
# do/prepare checks within multi-line comments
my $self_test_exception = $self_test ? "@" : "";
if ($in_comment > 0) { # this still includes the last line of multi-line comment
my ($head, $any_symbol, $cmt_text) = m/^(\s*)(.?)(.*)$/;
if ($any_symbol eq "*") {
report("missing space or '*' after leading '*' in multi-line comment") if $cmt_text =~ m|^[^*\s/$self_test_exception]|;
} else {
report("missing leading '*' in multi-line comment");
}
$in_comment++;
}
# detect end of comment, must be within multi-line comment, check if it is preceded by non-whitespace text
if ((my ($head, $tail) = m|^(.*?)\*/(.*)$|) && $1 ne '/') { # ending comment: '*/'
report("missing space or '*' before '*/'") if $head =~ m/[^*\s]$/;
report("missing space (or ',', ';', ')', '}', ']') after '*/'") if $tail =~ m/^[^\s,;)}\]]/; # no space or ,;)}] after '*/'
if (!($head =~ m|/\*|)) { # not begin of comment '/*', which is is handled below
if ($in_comment == 0) {
report("unexpected '*/' outside comment");
$_ = "$head@@".$tail; # blind the "*/"
} else {
report("text before '*/' in multi-line comment") if ($head =~ m/[^*\s]/); # non-SPC before '*/'
$in_comment = -1; # indicate that multi-line comment ends on current line
if ($count > 0) {
# make indentation of end of multi-line comment appear like of leading intra-line comment
$head =~ s/^(\s*)\s/$1@/; # replace the last leading space by '@'
$count--;
$in_comment = -2; # indicate that multi-line comment ends on current line, with tweak
}
my $cmt_text = $head;
$_ = blind_nonspace($cmt_text)."@@".$tail;
}
}
}
# detect begin of comment, check if it is followed by non-space text
MATCH_COMMENT:
if (my ($head, $opt_minus, $tail) = m|^(.*?)/\*(-?)(.*)$|) { # begin of comment: '/*'
report("missing space before '/*'")
if $head =~ m/[^\s(\*]$/; # not space, '(', or or '*' (needed to allow '*/') before comment delimiter
report("missing space, '*', or '!' after '/*$opt_minus'") if $tail =~ m/^[^\s*!$self_test_exception]/;
my $cmt_text = $opt_minus.$tail; # preliminary
if ($in_comment > 0) {
report("unexpected '/*' inside multi-line comment");
} elsif ($tail =~ m|^(.*?)\*/(.*)$|) { # comment end: */ on same line
report("unexpected '/*' inside intra-line comment") if $1 =~ /\/\*/;
# blind comment text, preserving length and spaces
($cmt_text, my $rest) = ($opt_minus.$1, $2);
$_ = "$head@@".blind_nonspace($cmt_text)."@@".$rest;
goto MATCH_COMMENT;
} else { # begin of multi-line comment
my $self_test_exception = $self_test ? "(@\d?)?" : "";
report("text after '/*' in multi-line comment")
unless $tail =~ m/^$self_test_exception.?[*\s]*$/;
# tail not essentially blank, first char already checked
# adapt to actual indentation of first line
$comment_indent = length($head) + 1;
$_ = "$head@@".blind_nonspace($cmt_text);
$in_comment = 1;
$leading_comment = $head =~ m/^\s*$/; # there is code before beginning delimiter
$formatted_comment = $opt_minus eq "-";
}
} elsif (($head, $tail) = m|^\{-(.*)$|) { # begin of Perl pragma: '{-'
}
if ($in_comment > 1) { # still inside multi-line comment (not at its begin or end)
m/^(\s*)\*?(\s*)(.*)$/;
$_ = $1."@".$2.blind_nonspace($3);
}
# handle special case of line after '#ifdef __cplusplus' (which typically appears in header files)
if ($ifdef__cplusplus) {
$ifdef__cplusplus = 0;
$_ = "$1 $2" if $contents =~ m/^(\s*extern\s*"C"\s*)\{(\s*)$/; # ignore opening brace in 'extern "C" {'
goto LINE_FINISHED if m/^\s*\}\s*$/; # ignore closing brace '}'
}
# check for over-long lines,
# while allowing trailing (also multi-line) string literals to go past $max_length
my $len = length; # total line length (without trailing '\n')
if ($len > $max_length &&
!(m/^(.*)"[^"]*"\s*[\)\}\]]*[,;]?\s*$/ # string literal terminated by '"' (or '\'), then maybe )}],;
&& length($1) < $max_length)
# this allows over-long trailing string literals with beginning col before $max_length
) {
report("line length = $len > ".MAX_LINE_LENGTH);
}
# handle C++ / C99 - style end-of-line comments
if (my ($head, $cmt_text) = m|^(.*?)//(.*$)|) {
report("'//' end-of-line comment"); # the '//' comment style is not allowed for C90
# blind comment text, preserving length and spaces
$_ = "$head@@".blind_nonspace($cmt_text);
}
# at this point all non-space portions of any types of comments have been blinded as @
goto LINE_FINISHED if $essentially_blank_line;
# handle preprocessor directives @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
if (s/^(\s*#)(\s*)(\w+)//) { # line beginning with '#' and directive name;
# blank these portions to prevent confusion with C-level 'if', 'else', etc.
my ($lead, $space) = ($1, $2);
$preproc_directive = $3;
$_ = "$lead$space$preproc_directive$_" if $preproc_directive =~ m/^(define|include)$/; # yet do not blank #define or #include to prevent confusing the indentation or whitespace checks, resp.
$_ = blind_nonspace($_) if $preproc_directive eq "error"; # blind error message
if ($in_preproc != 0) {
report("preprocessor directive within multi-line directive");
reset_indentation_state();
}
$in_preproc++;
report("indent = $count != 0 for '#'") if $count != 0;
report("'#$preproc_directive' with constant condition")
if $preproc_directive =~ m/^(if|elif)$/ && m/^[\W0-9]+$/ && !$trailing_backslash;
$preproc_if_nesting-- if $preproc_directive =~ m/^(else|elif|endif)$/;
if ($preproc_if_nesting < 0) {
$preproc_if_nesting = 0;
report("unexpected '#$preproc_directive' according to '#if' nesting");
}
my $space_count = length($space); # maybe could also use indentation before '#'
report("'#if' nesting indent = $space_count != $preproc_if_nesting") if $space_count != $preproc_if_nesting;
$preproc_if_nesting++ if $preproc_directive =~ m/^(if|ifdef|ifndef|else|elif)$/;
$ifdef__cplusplus = $preproc_directive eq "ifdef" && m/\s+__cplusplus\s*$/;
# handle indentation of preprocessor directive independently of surrounding normal code
$count = -1; # do not check indentation of first line of preprocessor directive
backup_indentation_state();
reset_indentation_state();
}
# intra-line whitespace nits @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
my $in_multiline_comment = ($in_comment > 1 || $in_comment < 0); # $in_multiline_comment refers to line before
if (!$sloppy_SPC && !($in_multiline_comment && $formatted_comment)) {
sub extra_SPC {
my $intra_line = shift;
return "extra space".($intra_line =~ m/@\s\s/ ?
$in_comment != 0 ? " in multi-line comment"
: " in intra-line comment" : "");
}
sub split_line_head { # split line contents into header containing leading spaces and the first non-space char, and the rest of the line
my $comment_symbol =
$in_comment != 0 ? "@" : ""; # '@' will match the blinded leading '*' in multi-line comment
# $in_comment may pertain to the following line due to delayed check
# do not check for extra SPC in leading spaces including any '#' (or '*' within multi-line comment)
shift =~ m/^(\s*([#$comment_symbol]\s*)?)(.*?)\s*$/;
return ($1, $3);
}
my ($head , $intra_line ) = split_line_head($_);
my ($head1, $intra_line1) = split_line_head($contents_before_ ) if $line_before > 0;
my ($head2, $intra_line2) = split_line_head($contents_before_2) if $line_before2 > 0;
if ($line_before > 0) { # check with one line delay, such that at least $contents_before is available
sub column_alignments_only { # return 1 if the given line has multiple consecutive spaces only at columns that match the reference line
# all parameter strings are assumed to contain contents after blinding comments etc.
my $head = shift; # leading spaces and the first non-space char
my $intra = shift; # the rest of the line contents
my $contents = shift; # reference line
# check if all extra SPC in $intra is used only for multi-line column alignment with $contents
my $offset = length($head);
for (my $col = 0; $col < length($intra) - 2; $col++) {
my $substr = substr($intra, $col);
next unless $substr =~ m/^\s\s\S/; # extra SPC (but not in leading spaces of the line)
next if !$eol_cmt && $substr =~ m/^[@\s]+$/; # end-of-line comment
return 0 unless substr($contents, $col + $offset + 1, 2) =~ m/\s\S/; # reference line contents do not match
}
return 1;
}
report_flexibly($line_before, extra_SPC($intra_line1), $contents_before) if $intra_line1 =~ m/\s\s\S/ &&
!( column_alignments_only($head1, $intra_line1, $_ ) # compare with $line
|| ($line_before2 > 0 &&
column_alignments_only($head1, $intra_line1, $contents_before_2))); # compare w/ $line_before2
report(extra_SPC($intra_line)) if $intra_line =~ m/\s\s\S/ && eof
&& ! column_alignments_only($head , $intra_line , $contents_before_ ) ; # compare w/ $line_before
} elsif (eof) { # special case: just one line exists
report(extra_SPC($intra_line)) if $intra_line =~ m/\s\s\S/;
}
# ignore paths in #include
$intra_line =~ s/^(include\s*)(".*?"|<.*?>)/$1/e if $head =~ m/#/;
report("missing space before '$2'")
if $intra_line =~ m/(\S)((<<|>>)=)/ # '<<=' or >>=' without preceding space
|| ($intra_line =~ m/(\S)([\+\-\*\/\/%\&\|\^\!<>=]=)/
&& "$1$2" ne "<<=" && "$1$2" ne ">>=") # other <op>= or (in)equality without preceding space
|| ($intra_line =~ m/(\S)=/
&& !($1 =~ m/[\+\-\*\/\/%\&\|\^\!<>=]/)
&& $intra_line =~ m/(\S)(=)/); # otherwise, '=' without preceding space
# treat op= and comparison operators as simple '=', simplifying matching below
$intra_line =~ s/(<<|>>|[\+\-\*\/\/%\&\|\^\!<>=])=/=/g;
# treat (type) variables within macro, indicated by trailing '\', as 'int' simplifying matching below
$intra_line =~ s/[A-Z_]+/int/g if $trailing_backslash;
# treat double &&, ||, <<, and >> as single ones, simplifying matching below
$intra_line =~ s/(&&|\|\||<<|>>)/substr($1, 0, 1)/eg;
# remove blinded comments etc. directly after [{(
while ($intra_line =~ s/([\[\{\(])@+\s?/$1/e) {} # /g does not work here
# remove blinded comments etc. directly before ,;)}]
while ($intra_line =~ s/\s?@+([,;\)\}\]])/$1/e) {} # /g does not work here
# treat remaining blinded comments and string literal contents as (single) space during matching below
$intra_line =~ s/@+/ /g; # note that extra SPC has already been handled above
$intra_line =~ s/\s+$//; # strip any (resulting) space at EOL
# replace ';;' or '; ;' by ';' in "for(;;)" and in "for (...)" unless "..." contains just SPC and ';' characters:
$intra_line =~ s/((^|\W)for\s*\()([^;]*?)(\s*)(;\s?);(\s*)([^;]*)(\))/
"$1$3$4".("$3$4$5$6$7" eq ";" || $3 ne "" || $7 ne "" ? "" : $5).";$6$7$8"/eg;
# strip trailing ';' or '; ' in "for (...)" except in "for (;;)" or "for (;; )":
$intra_line =~ s/((^|\W)for\s*\()([^;]*(;[^;]*)?)(;\s?)(\))/
"$1$3".($3 eq ";" ? $5 : "")."$6"/eg;
$intra_line =~ s/(=\s*)\{ /"$1@ "/eg; # do not report {SPC in initializers such as ' = { 0, };'
$intra_line =~ s/, \};/, @;/g; # do not report SPC} in initializers such as ' = { 0, };'
report("space before '$1'") if $intra_line =~ m/[\w)\]]\s+(\+\+|--)/; # postfix ++/-- with preceding space
report("space after '$1'") if $intra_line =~ m/(\+\+|--)\s+[a-zA-Z_(]/; # prefix ++/-- with following space
$intra_line =~ s/\.\.\./@/g; # blind '...'
report("space before '$1'") if $intra_line =~ m/\s(\.|->)/; # '.' or '->' with preceding space
report("space after '$1'") if $intra_line =~ m/(\.|->)\s/; # '.' or '->' with following space
$intra_line =~ s/\-\>|\+\+|\-\-/@/g; # blind '->,', '++', and '--'
report("space before '$1'") if $intra_line =~ m/[^:)]\s+(;)/; # space before ';' but not after ':' or ')' # note that
# exceptions for "for (;; )" are handled above
report("space before '$1'") if $intra_line =~ m/\s([,)\]])/; # space before ,)]
report("space after '$1'") if $intra_line =~ m/([(\[~!])\s/; # space after ([~!
report("space after '$1'") if $intra_line =~ m/(defined)\s/; # space after 'defined'
report("missing space before '$1'") if $intra_line =~ m/\S([|\/%<>^\?])/; # |/%<>^? without preceding space
# TODO ternary ':' without preceding SPC, while allowing no SPC before ':' after 'case'
report("missing space before binary '$2'") if $intra_line =~ m/([^\s{()\[e])([+\-])/; # '+'/'-' without preceding space or {()[e
# ')' may be used for type casts or before "->", 'e' may be used for numerical literals such as "1e-6"
report("missing space before binary '$1'") if $intra_line =~ m/[^\s{()\[*!]([*])/; # '*' without preceding space or {()[*!
report("missing space before binary '$1'") if $intra_line =~ m/[^\s{()\[]([&])/; # '&' without preceding space or {()[
report("missing space after ternary '$1'") if $intra_line =~ m/(:)[^\s\d]/; # ':' without following space or digit
report("missing space after '$1'") if $intra_line =~ m/([,;=|\/%<>^\?])\S/; # ,;=|/%<>^? without following space
report("missing space after binary '$1'") if $intra_line=~m/[^{(\[]([*])[^\sa-zA-Z_(),*]/;# '*' w/o space or \w(),* after
# TODO unary '*' must not be followed by SPC
report("missing space after binary '$1'") if $intra_line=~m/([&])[^\sa-zA-Z_(]/; # '&' w/o following space or \w(
# TODO unary '&' must not be followed by SPC
report("missing space after binary '$1'") if $intra_line=~m/[^{(\[]([+\-])[^\s\d(]/; # +/- w/o following space or \d(
# TODO unary '+' and '-' must not be followed by SPC
report("missing space after '$2'") if $intra_line =~ m/(^|\W)(if|while|for|switch|case)[^\w\s]/; # kw w/o SPC
report("missing space after '$2'") if $intra_line =~ m/(^|\W)(return)[^\w\s;]/; # return w/o SPC or ';'
report("space after function/macro name")
if $intra_line =~ m/(\w+)\s+\(/ # fn/macro name with space before '('
&& !($1 =~ m/^(sizeof|if|else|while|do|for|switch|case|default|break|continue|goto|return|void|char|signed|unsigned|int|short|long|float|double|typedef|enum|struct|union|auto|extern|static|const|volatile|register)$/) # not keyword
&& !(m/^\s*#\s*define\s+\w+\s+\(/); # not a macro without parameters having a body that starts with '('
report("missing space before '{'") if $intra_line =~ m/[^\s{(\[]\{/; # '{' without preceding space or {([
report("missing space after '}'") if $intra_line =~ m/\}[^\s,;\])}]/; # '}' without following space or ,;])}
}
# adapt required indentation @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
s/(\w*ASN1_[A-Z_]+END\w*([^(]|\(.*?\)|$))/$1;/g; # treat *ASN1_*END*(..) macro calls as if followed by ';'
my $nested_indents_position = 0;
# update indents according to leading closing brace(s) '}' or label or switch case
my $in_stmt = $in_expr || @nested_symbols != 0 || $in_typedecl != 0;
if ($in_stmt) { # expr/stmt/type decl/var def/fn hdr, i.e., not at block level
if (m/^([\s@]*\})/) { # leading '}' within stmt, any preceding blinded comment must not be matched
$in_block_decls = -1;
my $head = $1;
update_nested_indents($head);
$nested_indents_position = length($head);
if (@nested_symbols >= 1) {
$hanging_symbol = @nested_symbols[-1];
$expr_indent = @nested_indents[-1];
} else { # typically end of initialiizer expr or enum
$expr_indent = 0;
}
} elsif (m/^([\s@]*)(static_)?ASN1_ITEM_TEMPLATE_END(\W|$)/) { # workaround for ASN1 macro indented as '}'
$local_offset = -INDENT_LEVEL;
$expr_indent = 0;
} elsif (m/;.*?\}/) { # expr ends with ';' before '}'
report("code before '}'");
}
}
if (@in_do_hanging_offsets != 0 && # note there is nothing like "unexpected 'while'"
m/^[\s@]*while(\W|$)/) { # leading 'while'
$hanging_offset = pop @in_do_hanging_offsets;
}
if ($if_maybe_terminated) {
if (m/(^|\W)else(\W|$)/) { # (not necessarily leading) 'else'
if (@in_if_hanging_offsets == 0) {
report("unexpected 'else'");
} else {
$hanging_offset = pop @in_if_hanging_offsets;
}
} else {
@in_if_hanging_offsets = (); # note there is nothing like "unclosed 'if'"
$hanging_offset = 0;
}
}
if (!$in_stmt) { # at block level, i.e., outside expr/stmt/type decl/var def/fn hdr
$if_maybe_terminated = 0;
if (my ($head, $before, $tail) = m/^([\s@]*([^{}]*)\})[\s@]*(.*)$/) { # leading closing '}', but possibly
# with non-whitespace non-'{' before
report("code after '}'") unless $tail eq "" || $tail =~ m/(else|while|OSSL_TRACE_END)(\W|$)/;
my $outermost_level = @nested_block_indents == 1 && @nested_block_indents[0] == 0;
if (!$sloppy_bodylen && $outermost_level && $line_body_start != 0) {
my $body_len = $line - $line_body_start - 1;
report_flexibly($line_function_start, "function body length = $body_len > ".MAX_BODY_LENGTH." lines",
$last_function_header) if $body_len > MAX_BODY_LENGTH;
$line_body_start = 0;
}
if ($before ne "") { # non-whitespace non-'{' before '}'
report("code before '}'");
} else { # leading '}' outside stmt, any preceding blinded comment must not be matched
$in_block_decls = -1;
$local_offset = $block_indent + $hanging_offset - INDENT_LEVEL;
update_nested_indents($head);
$nested_indents_position = length($head);
$local_offset -= ($block_indent + $hanging_offset);
# in effect $local_offset = -INDENT_LEVEL relative to $block_indent + $hanging_offset values before
}
}
# handle opening brace '{' after if/else/while/for/switch/do on line before
if ($hanging_offset > 0 && m/^[\s@]*{/ && # leading opening '{'
$line_before > 0 &&
$contents_before_ =~ m/(^|^.*\W)(if|else|while|for|switch|do)(\W.*$|$)/) {
$keyword_opening_brace = $1;
$hanging_offset -= INDENT_LEVEL; # cancel newly hanging_offset
}
if (m/^[\s@]*(case|default)(\W.*$|$)/) { # leading 'case' or 'default'
my $keyword = $1;
report("code after $keyword: ") if $2 =~ /:.*[^\s@].*$/;
$local_offset = -INDENT_LEVEL;
} else {
if (m/^([\s@]*)(\w+):/) { # (leading) label, cannot be "default"
$local_offset = -INDENT_LEVEL;
$has_label = 1;
}
}
}
# potential adaptations of indent in first line of macro body in multi-line macro definition
if ($in_preproc != 0 && $in_macro_header > 0) {
if ($in_macro_header > 1) { # still in macro definition header
$in_macro_header += parens_balance($_);
} else { # begin of macro body
$in_macro_header = 0;
if ($count == $block_indent - $preproc_offset # body began with same indentation as preceding code
&& $sloppy_macro) { # workaround for this situation is enabled
$block_indent -= $preproc_offset;
$preproc_offset = 0;
}
}
}
# check required indentation @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
check_indent() if $count >= 0; # not for start of preprocessor directive and not if multi-line string literal is continued
# check for blank lines within/after local decls @@@@@@@@@@@@@@@@@@@@@@@@@@@
if ($in_block_decls >= 0 &&
$in_comment == 0 && !m/^\s*\*?@/ && # not in a multi-line or intra-line comment
!$in_expr && $expr_indent == 0 && $in_typedecl == 0) {
my $blank_line_before = $line > 1 && $code_contents_before =~ m/^\s*(\\\s*)?$/;
# essentially blank line before: just whitespace and maybe a '\'
if (m/^[\s(]*(char|signed|unsigned|int|short|long|float|double|enum|struct|union|auto|extern|static|const|volatile|register)(\W|$)/ # clear start of local decl
|| (m/^(\s*(\w+|\[\]|[\*()]))+?\s+[\*\(]*\w+(\s*(\)|\[[^\]]*\]))*\s*[;,=]/ # weak check for decl involving user-defined type
&& !m/^\s*(\}|sizeof|if|else|while|do|for|switch|case|default|break|continue|goto|return)(\W|$)/)) {
$in_block_decls++;
report_flexibly($line - 1, "blank line within local decls, before", $contents) if $blank_line_before;
} else {
report_flexibly($line, "missing blank line after local decls", "\n$contents_before$contents")
if $in_block_decls > 0 && !$blank_line_before;
$in_block_decls = -1 unless
m/^\s*(\\\s*)?$/ # essentially blank line: just whitespace (and maybe a trailing '\')
|| $in_comment != 0 || m/^\s*\*?@/; # in multi-line comment or an intra-line comment
}
}
$in_comment = 0 if $in_comment < 0; # multi-line comment has ended
# do some further checks @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
my $outermost_level = $block_indent - $preproc_offset == 0;
report("more than one stmt") if !m/(^|\W)for(\W.*|$)/ && # no 'for' - TODO improve matching
m/;.*;/; # two or more terminators ';', so more than one statement
# check for code block containing a single line/statement
if ($line_before2 > 0 && !$outermost_level && # within function body
$in_typedecl == 0 && @nested_indents == 0 && # neither within type declaration nor inside stmt/expr
- m/^[\s@]*\}/) { # leading closing brace '}', any preceding blinded comment must not be matched
+ m/^[\s@]*\}\s*(\w*)/) { # leading closing brace '}', any preceding blinded comment must not be matched
# TODO extend detection from single-line to potentially multi-line statement
+ my $next_word = $1;
if ($line_opening_brace > 0 &&
+ ($keyword_opening_brace ne "if" ||
+ $extended_1_stmt || $next_word ne "else") &&
($line_opening_brace == $line_before2 ||
$line_opening_brace == $line_before)
&& $contents_before =~ m/;/) { # there is at least one terminator ';', so there is some stmt
# TODO do not report cases where a further else branch
# follows with a block containing more than one line/statement
report_flexibly($line_before, "'$keyword_opening_brace' { 1 stmt }", $contents_before);
}
}
report("single-letter name '$2'") if (m/(^|.*\W)([IO])(\W.*|$)/); # single-letter name 'I' or 'O' # maybe re-add 'l'?
# constant on LHS of comparison or assignment, e.g., NULL != x or 'a' < c, but not a + 1 == b
report("constant on LHS of '$3'")
if (m/(['"]|([\+\-\*\/\/%\&\|\^<>]\s*)?\W[0-9]+L?|\WNULL)\s*([\!<>=]=|[<=>])([<>]?)/ &&
$2 eq "" && (($3 ne "<" && $3 ne "='" && $3 ne ">") || $4 eq ""));
# TODO report needless use of parentheses, while
# macro parameters should always be in parens (except when passed on), e.g., '#define ID(x) (x)'
# adapt required indentation for following lines @@@@@@@@@@@@@@@@@@@@@@@@@@@
# set $in_expr, $in_paren_expr, and $hanging_offset for if/while/for/switch, return/enum, and assignment RHS
my $paren_expr_start = 0;
my $return_enum_start = 0;
my $assignment_start = 0;
my $tmp = $_;
$tmp =~ s/[\!<>=]=/@@/g; # blind (in-)equality symbols like '<=' as '@@' to prevent matching them as '=' below
if (m/^((^|.*\W)(if|while|for|switch))(\W.*|$)$/) { # (last) if/for/while/switch
$paren_expr_start = 1;
} elsif (m/^((^|.*\W)(return|enum))(\W.*|$)/ # (last) return/enum
&& !$in_expr && @nested_indents == 0 && parens_balance($1) == 0) { # not nested enum
$return_enum_start = 1;
} elsif ($tmp =~ m/^(([^=]*)(=))(.*)$/ # (last) '=', i.e., assignment
&& !$in_expr && @nested_indents == 0 && parens_balance($1) == 0) { # not nested assignment
$assignment_start = 1;
}
if ($paren_expr_start || $return_enum_start || $assignment_start)
{
my ($head, $mid, $tail) = ($1, $3, $4);
$keyword_opening_brace = $mid if $mid ne "=";
# to cope with multi-line expressions, do this also if !($tail =~ m/\{/)
push @in_if_hanging_offsets, $hanging_offset if $mid eq "if";
# already handle $head, i.e., anything before expression
update_nested_indents($head, $nested_indents_position);
$nested_indents_position = length($head);
# now can set $in_expr and $in_paren_expr
$in_expr = 1;
$in_paren_expr = 1 if $paren_expr_start;
if ($mid eq "while" && @in_do_hanging_offsets != 0) {
$hanging_offset = pop @in_do_hanging_offsets;
} else {
$hanging_offset += INDENT_LEVEL; # tentatively set hanging_offset, may be canceled by following '{'
}
}
# set $hanging_offset and $keyword_opening_brace for do/else
if (my ($head, $mid, $tail) = m/(^|^.*\W)(else|do)(\W.*|$)$/) { # last else/do, where 'do' is preferred, but not #else
my $code_before = $head =~ m/[^\s\@}]/; # leading non-whitespace non-comment non-'}'
report("code before '$mid'") if $code_before;
report("code after '$mid'" ) if $tail =~ m/[^\s\@{]/# trailing non-whitespace non-comment non-'{' (non-'\')
&& !($mid eq "else" && $tail =~ m/[\s@]*if(\W|$)/);
if ($mid eq "do") { # workarounds for code before 'do'
if ($head =~ m/(^|^.*\W)(else)(\W.*$|$)/) { # 'else' ... 'do'
$hanging_offset += INDENT_LEVEL; # tentatively set hanging_offset, may be canceled by following '{'
}
if ($head =~ m/;/) { # terminator ';' ... 'do'
@in_if_hanging_offsets = (); # note there is nothing like "unclosed 'if'"
$hanging_offset = 0;
}
}
push @in_do_hanging_offsets, $hanging_offset if $mid eq "do";
if ($code_before && $mid eq "do") {
$hanging_offset = length($head) - $block_indent;
}
if (!$in_paren_expr) {
$keyword_opening_brace = $mid if $tail =~ m/\{/;
$hanging_offset += INDENT_LEVEL;
}
}
# set $in_typedecl and potentially $hanging_offset for type declaration
if (!$in_expr && @nested_indents == 0 # not in expression
&& m/(^|^.*\W)(typedef|enum|struct|union)(\W.*|$)$/
&& parens_balance($1) == 0 # not in newly started expression or function arg list
&& ($2 eq "typedef" || !($3 =~ m/\s*\w++\s*(.)/ && $1 ne "{")) # 'struct'/'union'/'enum' <name> not followed by '{'
# not needed: && $keyword_opening_brace = $2 if $3 =~ m/\{/;
) {
$in_typedecl++;
$hanging_offset += INDENT_LEVEL if m/\*.*\(/; # '*' followed by '(' - seems consistent with Emacs C mode
}
my $local_in_expr = $in_expr;
my $terminator_position = update_nested_indents($_, $nested_indents_position);
if ($local_in_expr) {
# on end of non-if/while/for/switch (multi-line) expression (i.e., return/enum/assignment) and
# on end of statement/type declaration/variable definition/function header
if ($terminator_position >= 0 && ($in_typedecl == 0 || @nested_indents == 0)) {
check_nested_nonblock_indents("expr");
$in_expr = 0;
}
} else {
check_nested_nonblock_indents($in_typedecl == 0 ? "stmt" : "decl") if $terminator_position >= 0;
}
# on ';', which terminates the current statement/type declaration/variable definition/function declaration
if ($terminator_position >= 0) {
my $tail = substr($_, $terminator_position + 1);
if (@in_if_hanging_offsets != 0) {
if ($tail =~ m/\s*else(\W|$)/) {
pop @in_if_hanging_offsets;
$hanging_offset -= INDENT_LEVEL;
} elsif ($tail =~ m/[^\s@]/) { # code (not just comment) follows
@in_if_hanging_offsets = (); # note there is nothing like "unclosed 'if'"
$hanging_offset = 0;
} else {
$if_maybe_terminated = 1;
}
} elsif ($tail =~ m/^[\s@]*$/) { # ';' has been trailing, i.e. there is nothing but whitespace and comments
$hanging_offset = 0; # reset in case of terminated assignment ('=') etc.
}
$in_typedecl-- if $in_typedecl != 0 && @nested_in_typedecl == 0; # TODO handle multiple type decls per line
m/(;[^;]*)$/; # match last ';'
$terminator_position = length($_) - length($1) if $1;
# new $terminator_position value may be after the earlier one in case multiple terminators on current line
# TODO check treatment in case of multiple terminators on current line
update_nested_indents($_, $terminator_position + 1);
}
# set hanging expression indent according to nested indents - TODO maybe do better in update_nested_indents()
# also if $in_expr is 0: in statement/type declaration/variable definition/function header
$expr_indent = 0;
for (my $i = -1; $i >= -@nested_symbols; $i--) {
if (@nested_symbols[$i] ne "?") { # conditionals '?' ... ':' are treated specially in check_indent()
$hanging_symbol = @nested_symbols[$i];
$expr_indent = $nested_indents[$i];
# $expr_indent is guaranteed to be != 0 unless @nested_indents contains just outer conditionals
last;
}
}
# remember line number and header containing name of last function defined for reports w.r.t. MAX_BODY_LENGTH
if ($in_preproc == 0 && $outermost_level && m/(\w+)\s*\(/ && $1 ne "STACK_OF") {
$line_function_start = $line;
$last_function_header = $contents;
}
# special checks for last, typically trailing opening brace '{' in line
if (my ($head, $tail) = m/^(.*)\{(.*)$/) { # match last ... '{'
if (!$in_expr && $in_typedecl == 0) {
if ($outermost_level) {
if (!$assignment_start && !$local_in_expr) {
# at end of function definition header (or stmt or var definition)
report("'{' not at line start") if length($head) != $preproc_offset && $head =~ m/\)\s*/; # at end of function definition header
$line_body_start = $contents =~ m/LONG BODY/ ? 0 : $line if $line_function_start != 0;
}
} else {
- $line_opening_brace = $line if $keyword_opening_brace =~ m/do|while|for/;
+ $line_opening_brace = $line if $keyword_opening_brace =~ m/if|do|while|for/;
# using, not assigning, $keyword_opening_brace here because it could be on an earlier line
- $line_opening_brace = $line if $keyword_opening_brace =~ m/if|else/ && $extended_1_stmt &&
+ $line_opening_brace = $line if $keyword_opening_brace eq "else" && $extended_1_stmt &&
# TODO prevent false positives for if/else where braces around single-statement branches
# should be avoided but only if all branches have just single statements
# The following helps detecting the exception when handling multiple 'if ... else' branches:
!($keyword_opening_brace eq "else" && $line_opening_brace < $line_before2);
}
report("code after '{'") if $tail=~ m/[^\s\@]/ && # trailing non-whitespace non-comment (non-'\')
!($tail=~ m/\}/); # missing '}' after last '{'
}
}
# check for opening brace after if/while/for/switch/do not on same line
# note that "missing '{' on same line after '} else'" is handled further below
if (/^[\s@]*{/ && # leading '{'
$line_before > 0 && !($contents_before_ =~ m/^\s*#/) && # not preprocessor directive '#if
(my ($head, $mid, $tail) = ($contents_before_ =~ m/(^|^.*\W)(if|while|for|switch|do)(\W.*$|$)/))) {
my $brace_after = $tail =~ /^[\s@]*{/; # any whitespace or comments then '{'
report("'{' not on same line as preceding '$mid'") if !$brace_after;
}
# check for closing brace on line before 'else' not followed by leading '{'
elsif (my ($head, $tail) = m/(^|^.*\W)else(\W.*$|$)/) {
if (parens_balance($tail) == 0 && # avoid false positive due to unfinished expr on current line
!($tail =~ m/{/) && # after 'else' missing '{' on same line
!($head =~ m/}[\s@]*$/) && # not: '}' then any whitespace or comments before 'else'
$line_before > 0 && $contents_before_ =~ /}[\s@]*$/) { # trailing '}' on line before
report("missing '{' on same line after '} else'");
}
}
# check for closing brace before 'while' not on same line
if (my ($head, $tail) = m/(^|^.*\W)while(\W.*$|$)/) {
my $brace_before = $head =~ m/}[\s@]*$/; # '}' then any whitespace or comments
# possibly 'if (...)' (with potentially inner '(' and ')') then any whitespace or comments then '{'
if (!$brace_before &&
# does not work here: @in_do_hanging_offsets != 0 && #'while' terminates loop
parens_balance($tail) == 0 && # avoid false positive due to unfinished expr on current line
$tail =~ /;/ && # 'while' terminates loop (by ';')
$line_before > 0 &&
$contents_before_ =~ /}[\s@]*$/) { # on line before: '}' then any whitespace or comments
report("'while' not on same line as preceding '}'");
}
}
# check for missing brace on same line before or after 'else'
if (my ($head, $tail) = m/(^|^.*\W)else(\W.*$|$)/) {
my $brace_before = $head =~ /}[\s@]*$/; # '}' then any whitespace or comments
my $brace_after = $tail =~ /^[\s@]*if[\s@]*\(.*\)[\s@]*{|[\s@]*{/;
# possibly 'if (...)' (with potentially inner '(' and ')') then any whitespace or comments then '{'
if (!$brace_before) {
if ($line_before > 0 && $contents_before_ =~ /}[\s@]*$/) {
report("'else' not on same line as preceding '}'");
} elsif (parens_balance($tail) == 0) { # avoid false positive due to unfinished expr on current line
report("missing '}' on same line before 'else ... {'") if $brace_after;
}
} elsif (parens_balance($tail) == 0) { # avoid false positive due to unfinished expr on current line
report("missing '{' on same line after '} else'") if $brace_before && !$brace_after;
}
}
# on begin of multi-line preprocessor directive, adapt indent
if ($in_comment == 0 && $trailing_backslash) {
# trailing '\'typically used in preprocessor directive like '#define'
if ($in_preproc == 1) { # start of multi-line preprocessor directive
# note that backup+reset_indentation_state() has already been called
$in_macro_header = m/^\s*#\s*define(\W|$)?(.*)/ ? 1 + parens_balance($2) : 0; # '#define' is beginning
$preproc_offset = INDENT_LEVEL;
$block_indent = $preproc_offset;
}
$in_preproc += 1;
}
# post-processing at end of line @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
LINE_FINISHED:
$code_contents_before = $contents if
!m/^\s*#(\s*)(\w+)/ && # not single-line preprocessor directive
$in_comment == 0 && !m/^\s*\*?@/; # not in a multi-line comment nor in an intra-line comment
# on end of (possibly multi-line) preprocessor directive, adapt indent
if ($in_preproc != 0 && !$trailing_backslash) { # no trailing '\'
$in_preproc = 0;
$preproc_offset = 0;
restore_indentation_state();
}
if ($essentially_blank_line) {
report("leading ".($1 eq "" ? "blank" :"whitespace")." line") if $line == 1 && !$sloppy_SPC;
} else {
if ($line_before > 0) {
my $linediff = $line - $line_before - 1;
report("$linediff blank lines before") if $linediff > 1 && !$sloppy_SPC;
}
$line_before2 = $line_before;
$contents_before2 = $contents_before;
$contents_before_2 = $contents_before_;
$line_before = $line;
$contents_before = $contents;
$contents_before_ = $_;
$count_before = $count;
}
if ($self_test) { # debugging
my $should_report = $contents =~ m/\*@(\d)?/ ? 1 : 0;
$should_report = +$1 if $should_report != 0 && defined $1;
print("$ARGV:$line:$num_reports_line reports on:$contents")
if $num_reports_line != $should_report;
}
$num_reports_line = 0;
# post-processing at end of file @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
if (eof) {
# check for essentially blank line (which may include a '\') just before EOF
report(($1 eq "\n" ? "blank line" : $2 ne "" ? "'\\'" : "whitespace")." at EOF")
if $contents =~ m/^(\s*(\\?)\s*)$/ && !$sloppy_SPC;
# report unclosed expression-level nesting
check_nested_nonblock_indents("expr at EOF"); # also adapts @nested_block_indents
# sanity-check balance of block-level { ... } via final $block_indent at end of file
report_flexibly($line, +@nested_block_indents." unclosed '{'", "(EOF)\n") if @nested_block_indents != 0;
# sanity-check balance of #if ... #endif via final preprocessor directive indent at end of file
report_flexibly($line, "$preproc_if_nesting unclosed '#if'", "(EOF)\n") if $preproc_if_nesting != 0;
reset_file_state();
}
}
# final summary report @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
my $num_other_reports = $num_reports - $num_indent_reports - $num_nesting_issues
- $num_syntax_issues - $num_SPC_reports - $num_length_reports;
print "$num_reports ($num_indent_reports indentation, $num_nesting_issues '#if' nesting indent, ".
"$num_syntax_issues syntax, $num_SPC_reports whitespace, $num_length_reports length, $num_other_reports other)".
" issues have been found by $0\n" if $num_reports != 0 && !$self_test;
diff --git a/crypto/openssl/util/perl/OpenSSL/Test/Utils.pm b/crypto/openssl/util/perl/OpenSSL/Test/Utils.pm
index dcff6a5c9967..34eafc4659a5 100644
--- a/crypto/openssl/util/perl/OpenSSL/Test/Utils.pm
+++ b/crypto/openssl/util/perl/OpenSSL/Test/Utils.pm
@@ -1,241 +1,257 @@
-# Copyright 2016-2019 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
package OpenSSL::Test::Utils;
use strict;
use warnings;
use Exporter;
use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
$VERSION = "0.1";
@ISA = qw(Exporter);
@EXPORT = qw(alldisabled anydisabled disabled config available_protocols
have_IPv4 have_IPv6);
=head1 NAME
OpenSSL::Test::Utils - test utility functions
=head1 SYNOPSIS
use OpenSSL::Test::Utils;
my @tls = available_protocols("tls");
my @dtls = available_protocols("dtls");
alldisabled("dh", "dsa");
anydisabled("dh", "dsa");
config("fips");
have_IPv4();
have_IPv6();
=head1 DESCRIPTION
This module provides utility functions for the testing framework.
=cut
use OpenSSL::Test qw/:DEFAULT bldtop_file/;
=over 4
=item B<available_protocols STRING>
Returns a list of strings for all the available SSL/TLS versions if
STRING is "tls", or for all the available DTLS versions if STRING is
"dtls". Otherwise, it returns the empty list. The strings in the
returned list can be used with B<alldisabled> and B<anydisabled>.
=item B<alldisabled ARRAY>
=item B<anydisabled ARRAY>
In an array context returns an array with each element set to 1 if the
corresponding feature is disabled and 0 otherwise.
In a scalar context, alldisabled returns 1 if all of the features in
ARRAY are disabled, while anydisabled returns 1 if any of them are
disabled.
=item B<config STRING>
Returns an item from the %config hash in \$TOP/configdata.pm.
=item B<have_IPv4>
=item B<have_IPv6>
Return true if IPv4 / IPv6 is possible to use on the current system.
+Additionally, B<have_IPv6> also checks how OpenSSL was configured,
+i.e. if IPv6 was explicitly disabled with -DOPENSSL_USE_IPv6=0.
=back
=cut
our %available_protocols;
our %disabled;
our %config;
+our %target;
my $configdata_loaded = 0;
sub load_configdata {
# We eval it so it doesn't run at compile time of this file.
# The latter would have bldtop_file() complain that setup() hasn't
# been run yet.
my $configdata = bldtop_file("configdata.pm");
eval { require $configdata;
%available_protocols = %configdata::available_protocols;
%disabled = %configdata::disabled;
%config = %configdata::config;
+ %target = %configdata::target;
};
$configdata_loaded = 1;
}
# args
# list of 1s and 0s, coming from check_disabled()
sub anyof {
my $x = 0;
foreach (@_) { $x += $_ }
return $x > 0;
}
# args
# list of 1s and 0s, coming from check_disabled()
sub allof {
my $x = 1;
foreach (@_) { $x *= $_ }
return $x > 0;
}
# args
# list of strings, all of them should be names of features
# that can be disabled.
# returns a list of 1s (if the corresponding feature is disabled)
# and 0s (if it isn't)
sub check_disabled {
return map { exists $disabled{lc $_} ? 1 : 0 } @_;
}
# Exported functions #################################################
# args:
# list of features to check
sub anydisabled {
load_configdata() unless $configdata_loaded;
my @ret = check_disabled(@_);
return @ret if wantarray;
return anyof(@ret);
}
# args:
# list of features to check
sub alldisabled {
load_configdata() unless $configdata_loaded;
my @ret = check_disabled(@_);
return @ret if wantarray;
return allof(@ret);
}
# !!! Kept for backward compatibility
# args:
# single string
sub disabled {
anydisabled(@_);
}
sub available_protocols {
load_configdata() unless $configdata_loaded;
my $protocol_class = shift;
if (exists $available_protocols{lc $protocol_class}) {
return @{$available_protocols{lc $protocol_class}}
}
return ();
}
sub config {
load_configdata() unless $configdata_loaded;
return $config{$_[0]};
}
# IPv4 / IPv6 checker
my $have_IPv4 = -1;
my $have_IPv6 = -1;
my $IP_factory;
sub check_IP {
my $listenaddress = shift;
eval {
require IO::Socket::IP;
my $s = IO::Socket::IP->new(
LocalAddr => $listenaddress,
LocalPort => 0,
Listen=>1,
);
$s or die "\n";
$s->close();
};
if ($@ eq "") {
return 1;
}
eval {
require IO::Socket::INET6;
my $s = IO::Socket::INET6->new(
LocalAddr => $listenaddress,
LocalPort => 0,
Listen=>1,
);
$s or die "\n";
$s->close();
};
if ($@ eq "") {
return 1;
}
eval {
require IO::Socket::INET;
my $s = IO::Socket::INET->new(
LocalAddr => $listenaddress,
LocalPort => 0,
Listen=>1,
);
$s or die "\n";
$s->close();
};
if ($@ eq "") {
return 1;
}
return 0;
}
sub have_IPv4 {
if ($have_IPv4 < 0) {
$have_IPv4 = check_IP("127.0.0.1");
}
return $have_IPv4;
}
sub have_IPv6 {
+ if ($have_IPv6 < 0) {
+ load_configdata() unless $configdata_loaded;
+ # If OpenSSL is configured with IPv6 explicitly disabled, no IPv6
+ # related tests should be performed. In other words, pretend IPv6
+ # isn't present.
+ $have_IPv6 = 0
+ if grep { $_ eq 'OPENSSL_USE_IPV6=0' } @{$config{CPPDEFINES}};
+ # Similarly, if a config target has explicitly disabled IPv6, no
+ # IPv6 related tests should be performed.
+ $have_IPv6 = 0
+ if grep { $_ eq 'OPENSSL_USE_IPV6=0' } @{$target{defines}};
+ }
if ($have_IPv6 < 0) {
$have_IPv6 = check_IP("::1");
}
return $have_IPv6;
}
=head1 SEE ALSO
L<OpenSSL::Test>
=head1 AUTHORS
Stephen Henson E<lt>steve@openssl.orgE<gt> and
Richard Levitte E<lt>levitte@openssl.orgE<gt>
=cut
1;
diff --git a/crypto/openssl/util/perl/TLSProxy/Message.pm b/crypto/openssl/util/perl/TLSProxy/Message.pm
index 2c1bdb3837e2..193aa2554f19 100644
--- a/crypto/openssl/util/perl/TLSProxy/Message.pm
+++ b/crypto/openssl/util/perl/TLSProxy/Message.pm
@@ -1,629 +1,638 @@
-# 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 strict;
package TLSProxy::Message;
use TLSProxy::Alert;
use constant TLS_MESSAGE_HEADER_LENGTH => 4;
#Message types
use constant {
MT_HELLO_REQUEST => 0,
MT_CLIENT_HELLO => 1,
MT_SERVER_HELLO => 2,
MT_NEW_SESSION_TICKET => 4,
MT_ENCRYPTED_EXTENSIONS => 8,
MT_CERTIFICATE => 11,
MT_SERVER_KEY_EXCHANGE => 12,
MT_CERTIFICATE_REQUEST => 13,
MT_SERVER_HELLO_DONE => 14,
MT_CERTIFICATE_VERIFY => 15,
MT_CLIENT_KEY_EXCHANGE => 16,
MT_FINISHED => 20,
MT_CERTIFICATE_STATUS => 22,
MT_NEXT_PROTO => 67
};
#Alert levels
use constant {
AL_LEVEL_WARN => 1,
AL_LEVEL_FATAL => 2
};
#Alert descriptions
use constant {
AL_DESC_CLOSE_NOTIFY => 0,
AL_DESC_UNEXPECTED_MESSAGE => 10,
AL_DESC_ILLEGAL_PARAMETER => 47,
AL_DESC_NO_RENEGOTIATION => 100
};
my %message_type = (
MT_HELLO_REQUEST, "HelloRequest",
MT_CLIENT_HELLO, "ClientHello",
MT_SERVER_HELLO, "ServerHello",
MT_NEW_SESSION_TICKET, "NewSessionTicket",
MT_ENCRYPTED_EXTENSIONS, "EncryptedExtensions",
MT_CERTIFICATE, "Certificate",
MT_SERVER_KEY_EXCHANGE, "ServerKeyExchange",
MT_CERTIFICATE_REQUEST, "CertificateRequest",
MT_SERVER_HELLO_DONE, "ServerHelloDone",
MT_CERTIFICATE_VERIFY, "CertificateVerify",
MT_CLIENT_KEY_EXCHANGE, "ClientKeyExchange",
MT_FINISHED, "Finished",
MT_CERTIFICATE_STATUS, "CertificateStatus",
MT_NEXT_PROTO, "NextProto"
);
use constant {
EXT_SERVER_NAME => 0,
EXT_MAX_FRAGMENT_LENGTH => 1,
EXT_STATUS_REQUEST => 5,
EXT_SUPPORTED_GROUPS => 10,
EXT_EC_POINT_FORMATS => 11,
EXT_SRP => 12,
EXT_SIG_ALGS => 13,
EXT_USE_SRTP => 14,
EXT_ALPN => 16,
EXT_SCT => 18,
EXT_PADDING => 21,
EXT_ENCRYPT_THEN_MAC => 22,
EXT_EXTENDED_MASTER_SECRET => 23,
EXT_SESSION_TICKET => 35,
EXT_KEY_SHARE => 51,
EXT_PSK => 41,
EXT_SUPPORTED_VERSIONS => 43,
EXT_COOKIE => 44,
EXT_PSK_KEX_MODES => 45,
EXT_POST_HANDSHAKE_AUTH => 49,
EXT_SIG_ALGS_CERT => 50,
EXT_RENEGOTIATE => 65281,
EXT_NPN => 13172,
EXT_CRYPTOPRO_BUG_EXTENSION => 0xfde8,
EXT_UNKNOWN => 0xfffe,
#Unknown extension that should appear last
EXT_FORCE_LAST => 0xffff
};
# SignatureScheme of TLS 1.3 from:
# https://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml#tls-signaturescheme
# We have to manually grab the SHA224 equivalents from the old registry
use constant {
SIG_ALG_RSA_PKCS1_SHA256 => 0x0401,
SIG_ALG_RSA_PKCS1_SHA384 => 0x0501,
SIG_ALG_RSA_PKCS1_SHA512 => 0x0601,
SIG_ALG_ECDSA_SECP256R1_SHA256 => 0x0403,
SIG_ALG_ECDSA_SECP384R1_SHA384 => 0x0503,
SIG_ALG_ECDSA_SECP521R1_SHA512 => 0x0603,
SIG_ALG_RSA_PSS_RSAE_SHA256 => 0x0804,
SIG_ALG_RSA_PSS_RSAE_SHA384 => 0x0805,
SIG_ALG_RSA_PSS_RSAE_SHA512 => 0x0806,
SIG_ALG_ED25519 => 0x0807,
SIG_ALG_ED448 => 0x0808,
SIG_ALG_RSA_PSS_PSS_SHA256 => 0x0809,
SIG_ALG_RSA_PSS_PSS_SHA384 => 0x080a,
SIG_ALG_RSA_PSS_PSS_SHA512 => 0x080b,
SIG_ALG_RSA_PKCS1_SHA1 => 0x0201,
SIG_ALG_ECDSA_SHA1 => 0x0203,
SIG_ALG_DSA_SHA1 => 0x0202,
SIG_ALG_DSA_SHA256 => 0x0402,
SIG_ALG_DSA_SHA384 => 0x0502,
SIG_ALG_DSA_SHA512 => 0x0602,
OSSL_SIG_ALG_RSA_PKCS1_SHA224 => 0x0301,
OSSL_SIG_ALG_DSA_SHA224 => 0x0302,
OSSL_SIG_ALG_ECDSA_SHA224 => 0x0303
};
use constant {
CIPHER_RSA_WITH_AES_128_CBC_SHA => 0x002f,
CIPHER_DHE_RSA_AES_128_SHA => 0x0033,
CIPHER_ADH_AES_128_SHA => 0x0034,
CIPHER_TLS13_AES_128_GCM_SHA256 => 0x1301,
CIPHER_TLS13_AES_256_GCM_SHA384 => 0x1302
};
use constant {
CLIENT => 0,
SERVER => 1
};
my $payload = "";
my $messlen = -1;
my $mt;
my $startoffset = -1;
my $server = 0;
my $success = 0;
my $end = 0;
my @message_rec_list = ();
my @message_frag_lens = ();
my $ciphersuite = 0;
my $successondata = 0;
my $alert;
sub clear
{
$payload = "";
$messlen = -1;
$startoffset = -1;
$server = 0;
$success = 0;
$end = 0;
$successondata = 0;
@message_rec_list = ();
@message_frag_lens = ();
$alert = undef;
}
#Class method to extract messages from a record
sub get_messages
{
my $class = shift;
my $serverin = shift;
my $record = shift;
my @messages = ();
my $message;
@message_frag_lens = ();
if ($serverin != $server && length($payload) != 0) {
die "Changed peer, but we still have fragment data\n";
}
$server = $serverin;
if ($record->content_type == TLSProxy::Record::RT_CCS) {
if ($payload ne "") {
#We can't handle this yet
die "CCS received before message data complete\n";
}
if (!TLSProxy::Proxy->is_tls13()) {
if ($server) {
TLSProxy::Record->server_encrypting(1);
} else {
TLSProxy::Record->client_encrypting(1);
}
}
} elsif ($record->content_type == TLSProxy::Record::RT_HANDSHAKE) {
if ($record->len == 0 || $record->len_real == 0) {
print " Message truncated\n";
} else {
my $recoffset = 0;
if (length $payload > 0) {
#We are continuing processing a message started in a previous
#record. Add this record to the list associated with this
#message
push @message_rec_list, $record;
if ($messlen <= length($payload)) {
#Shouldn't happen
die "Internal error: invalid messlen: ".$messlen
." payload length:".length($payload)."\n";
}
if (length($payload) + $record->decrypt_len >= $messlen) {
#We can complete the message with this record
$recoffset = $messlen - length($payload);
$payload .= substr($record->decrypt_data, 0, $recoffset);
push @message_frag_lens, $recoffset;
$message = create_message($server, $mt, $payload,
$startoffset);
push @messages, $message;
$payload = "";
} else {
#This is just part of the total message
$payload .= $record->decrypt_data;
$recoffset = $record->decrypt_len;
push @message_frag_lens, $record->decrypt_len;
}
print " Partial message data read: ".$recoffset." bytes\n";
}
while ($record->decrypt_len > $recoffset) {
#We are at the start of a new message
if ($record->decrypt_len - $recoffset < 4) {
#Whilst technically probably valid we can't cope with this
die "End of record in the middle of a message header\n";
}
@message_rec_list = ($record);
my $lenhi;
my $lenlo;
($mt, $lenhi, $lenlo) = unpack('CnC',
substr($record->decrypt_data,
$recoffset));
$messlen = ($lenhi << 8) | $lenlo;
print " Message type: $message_type{$mt}\n";
print " Message Length: $messlen\n";
$startoffset = $recoffset;
$recoffset += 4;
$payload = "";
if ($recoffset <= $record->decrypt_len) {
#Some payload data is present in this record
if ($record->decrypt_len - $recoffset >= $messlen) {
#We can complete the message with this record
$payload .= substr($record->decrypt_data, $recoffset,
$messlen);
$recoffset += $messlen;
push @message_frag_lens, $messlen;
$message = create_message($server, $mt, $payload,
$startoffset);
push @messages, $message;
$payload = "";
} else {
#This is just part of the total message
$payload .= substr($record->decrypt_data, $recoffset,
$record->decrypt_len - $recoffset);
$recoffset = $record->decrypt_len;
push @message_frag_lens, $recoffset;
}
}
}
}
} elsif ($record->content_type == TLSProxy::Record::RT_APPLICATION_DATA) {
print " [ENCRYPTED APPLICATION DATA]\n";
print " [".$record->decrypt_data."]\n";
if ($successondata) {
$success = 1;
$end = 1;
}
} elsif ($record->content_type == TLSProxy::Record::RT_ALERT) {
my ($alertlev, $alertdesc) = unpack('CC', $record->decrypt_data);
print " [$alertlev, $alertdesc]\n";
#A CloseNotify from the client indicates we have finished successfully
#(we assume)
if (!$end && !$server && $alertlev == AL_LEVEL_WARN
&& $alertdesc == AL_DESC_CLOSE_NOTIFY) {
$success = 1;
}
#Fatal or close notify alerts end the test
if ($alertlev == AL_LEVEL_FATAL || $alertdesc == AL_DESC_CLOSE_NOTIFY) {
$end = 1;
}
$alert = TLSProxy::Alert->new(
$server,
$record->encrypted,
$alertlev,
$alertdesc);
}
return @messages;
}
#Function to work out which sub-class we need to create and then
#construct it
sub create_message
{
my ($server, $mt, $data, $startoffset) = @_;
my $message;
#We only support ClientHello in this version...needs to be extended for
#others
if ($mt == MT_CLIENT_HELLO) {
$message = TLSProxy::ClientHello->new(
$server,
$data,
[@message_rec_list],
$startoffset,
[@message_frag_lens]
);
$message->parse();
} elsif ($mt == MT_SERVER_HELLO) {
$message = TLSProxy::ServerHello->new(
$server,
$data,
[@message_rec_list],
$startoffset,
[@message_frag_lens]
);
$message->parse();
} elsif ($mt == MT_ENCRYPTED_EXTENSIONS) {
$message = TLSProxy::EncryptedExtensions->new(
$server,
$data,
[@message_rec_list],
$startoffset,
[@message_frag_lens]
);
$message->parse();
} elsif ($mt == MT_CERTIFICATE) {
$message = TLSProxy::Certificate->new(
$server,
$data,
[@message_rec_list],
$startoffset,
[@message_frag_lens]
);
$message->parse();
} elsif ($mt == MT_CERTIFICATE_REQUEST) {
$message = TLSProxy::CertificateRequest->new(
$server,
$data,
[@message_rec_list],
$startoffset,
[@message_frag_lens]
);
$message->parse();
} elsif ($mt == MT_CERTIFICATE_VERIFY) {
$message = TLSProxy::CertificateVerify->new(
$server,
$data,
[@message_rec_list],
$startoffset,
[@message_frag_lens]
);
$message->parse();
} elsif ($mt == MT_SERVER_KEY_EXCHANGE) {
$message = TLSProxy::ServerKeyExchange->new(
$server,
$data,
[@message_rec_list],
$startoffset,
[@message_frag_lens]
);
$message->parse();
} elsif ($mt == MT_NEW_SESSION_TICKET) {
$message = TLSProxy::NewSessionTicket->new(
$server,
$data,
[@message_rec_list],
$startoffset,
[@message_frag_lens]
);
$message->parse();
+ } elsif ($mt == MT_NEXT_PROTO) {
+ $message = TLSProxy::NextProto->new(
+ $server,
+ $data,
+ [@message_rec_list],
+ $startoffset,
+ [@message_frag_lens]
+ );
+ $message->parse();
} else {
#Unknown message type
$message = TLSProxy::Message->new(
$server,
$mt,
$data,
[@message_rec_list],
$startoffset,
[@message_frag_lens]
);
}
return $message;
}
sub end
{
my $class = shift;
return $end;
}
sub success
{
my $class = shift;
return $success;
}
sub fail
{
my $class = shift;
return !$success && $end;
}
sub alert
{
return $alert;
}
sub new
{
my $class = shift;
my ($server,
$mt,
$data,
$records,
$startoffset,
$message_frag_lens) = @_;
my $self = {
server => $server,
data => $data,
records => $records,
mt => $mt,
startoffset => $startoffset,
message_frag_lens => $message_frag_lens,
dupext => -1
};
return bless $self, $class;
}
sub ciphersuite
{
my $class = shift;
if (@_) {
$ciphersuite = shift;
}
return $ciphersuite;
}
#Update all the underlying records with the modified data from this message
#Note: Only supports TLSv1.3 and ETM encryption
sub repack
{
my $self = shift;
my $msgdata;
my $numrecs = $#{$self->records};
$self->set_message_contents();
my $lenhi;
my $lenlo;
$lenlo = length($self->data) & 0xff;
$lenhi = length($self->data) >> 8;
$msgdata = pack('CnC', $self->mt, $lenhi, $lenlo).$self->data;
if ($numrecs == 0) {
#The message is fully contained within one record
my ($rec) = @{$self->records};
my $recdata = $rec->decrypt_data;
my $old_length;
# We use empty message_frag_lens to indicates that pre-repacking,
# the message wasn't present. The first fragment length doesn't include
# the TLS header, so we need to check and compute the right length.
if (@{$self->message_frag_lens}) {
$old_length = ${$self->message_frag_lens}[0] +
TLS_MESSAGE_HEADER_LENGTH;
} else {
$old_length = 0;
}
my $prefix = substr($recdata, 0, $self->startoffset);
my $suffix = substr($recdata, $self->startoffset + $old_length);
$rec->decrypt_data($prefix.($msgdata).($suffix));
# TODO(openssl-team): don't keep explicit lengths.
# (If a length override is ever needed to construct invalid packets,
# use an explicit override field instead.)
$rec->decrypt_len(length($rec->decrypt_data));
# Only support re-encryption for TLSv1.3 and ETM.
if ($rec->encrypted()) {
if (TLSProxy::Proxy->is_tls13()) {
#Add content type (1 byte) and 16 tag bytes
$rec->data($rec->decrypt_data
.pack("C", TLSProxy::Record::RT_HANDSHAKE).("\0"x16));
} elsif ($rec->etm()) {
my $data = $rec->decrypt_data;
#Add padding
my $padval = length($data) % 16;
$padval = 15 - $padval;
for (0..$padval) {
$data .= pack("C", $padval);
}
#Add MAC. Assumed to be 20 bytes
foreach my $macval (0..19) {
$data .= pack("C", $macval);
}
if ($rec->version() >= TLSProxy::Record::VERS_TLS_1_1) {
#Explicit IV
$data = ("\0"x16).$data;
}
$rec->data($data);
} else {
die "Unsupported encryption: No ETM";
}
} else {
$rec->data($rec->decrypt_data);
}
$rec->len(length($rec->data));
#Update the fragment len in case we changed it above
${$self->message_frag_lens}[0] = length($msgdata)
- TLS_MESSAGE_HEADER_LENGTH;
return;
}
#Note we don't currently support changing a fragmented message length
my $recctr = 0;
my $datadone = 0;
foreach my $rec (@{$self->records}) {
my $recdata = $rec->decrypt_data;
if ($recctr == 0) {
#This is the first record
my $remainlen = length($recdata) - $self->startoffset;
$rec->data(substr($recdata, 0, $self->startoffset)
.substr(($msgdata), 0, $remainlen));
$datadone += $remainlen;
} elsif ($recctr + 1 == $numrecs) {
#This is the last record
$rec->data(substr($msgdata, $datadone));
} else {
#This is a middle record
$rec->data(substr($msgdata, $datadone, length($rec->data)));
$datadone += length($rec->data);
}
$recctr++;
}
}
#To be overridden by sub-classes
sub set_message_contents
{
}
#Read only accessors
sub server
{
my $self = shift;
return $self->{server};
}
#Read/write accessors
sub mt
{
my $self = shift;
if (@_) {
$self->{mt} = shift;
}
return $self->{mt};
}
sub data
{
my $self = shift;
if (@_) {
$self->{data} = shift;
}
return $self->{data};
}
sub records
{
my $self = shift;
if (@_) {
$self->{records} = shift;
}
return $self->{records};
}
sub startoffset
{
my $self = shift;
if (@_) {
$self->{startoffset} = shift;
}
return $self->{startoffset};
}
sub message_frag_lens
{
my $self = shift;
if (@_) {
$self->{message_frag_lens} = shift;
}
return $self->{message_frag_lens};
}
sub encoded_length
{
my $self = shift;
return TLS_MESSAGE_HEADER_LENGTH + length($self->data);
}
sub dupext
{
my $self = shift;
if (@_) {
$self->{dupext} = shift;
}
return $self->{dupext};
}
sub successondata
{
my $class = shift;
if (@_) {
$successondata = shift;
}
return $successondata;
}
1;
diff --git a/crypto/openssl/util/perl/TLSProxy/NextProto.pm b/crypto/openssl/util/perl/TLSProxy/NextProto.pm
new file mode 100644
index 000000000000..0e1834754667
--- /dev/null
+++ b/crypto/openssl/util/perl/TLSProxy/NextProto.pm
@@ -0,0 +1,54 @@
+# Copyright 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;
+
+package TLSProxy::NextProto;
+
+use vars '@ISA';
+push @ISA, 'TLSProxy::Message';
+
+sub new
+{
+ my $class = shift;
+ my ($server,
+ $data,
+ $records,
+ $startoffset,
+ $message_frag_lens) = @_;
+
+ my $self = $class->SUPER::new(
+ $server,
+ TLSProxy::Message::MT_NEXT_PROTO,
+ $data,
+ $records,
+ $startoffset,
+ $message_frag_lens);
+
+ return $self;
+}
+
+sub parse
+{
+ # We don't support parsing at the moment
+}
+
+# This is supposed to reconstruct the on-the-wire message data following changes.
+# For now though since we don't support parsing we just create an empty NextProto
+# message - this capability is used in test_npn
+sub set_message_contents
+{
+ my $self = shift;
+ my $data;
+
+ $data = pack("C32", 0x00, 0x1e, 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);
+ $self->data($data);
+}
+1;
diff --git a/crypto/openssl/util/perl/TLSProxy/Proxy.pm b/crypto/openssl/util/perl/TLSProxy/Proxy.pm
index 3de10eccb94e..7ad7c939ad52 100644
--- a/crypto/openssl/util/perl/TLSProxy/Proxy.pm
+++ b/crypto/openssl/util/perl/TLSProxy/Proxy.pm
@@ -1,729 +1,730 @@
-# Copyright 2016-2018 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 strict;
use POSIX ":sys_wait_h";
package TLSProxy::Proxy;
use File::Spec;
use IO::Socket;
use IO::Select;
use TLSProxy::Record;
use TLSProxy::Message;
use TLSProxy::ClientHello;
use TLSProxy::ServerHello;
use TLSProxy::EncryptedExtensions;
use TLSProxy::Certificate;
use TLSProxy::CertificateRequest;
use TLSProxy::CertificateVerify;
use TLSProxy::ServerKeyExchange;
use TLSProxy::NewSessionTicket;
+use TLSProxy::NextProto;
my $have_IPv6;
my $IP_factory;
BEGIN
{
# IO::Socket::IP is on the core module list, IO::Socket::INET6 isn't.
# However, IO::Socket::INET6 is older and is said to be more widely
# deployed for the moment, and may have less bugs, so we try the latter
# first, then fall back on the core modules. Worst case scenario, we
# fall back to IO::Socket::INET, only supports IPv4.
eval {
require IO::Socket::INET6;
my $s = IO::Socket::INET6->new(
LocalAddr => "::1",
LocalPort => 0,
Listen=>1,
);
$s or die "\n";
$s->close();
};
if ($@ eq "") {
$IP_factory = sub { IO::Socket::INET6->new(Domain => AF_INET6, @_); };
$have_IPv6 = 1;
} else {
eval {
require IO::Socket::IP;
my $s = IO::Socket::IP->new(
LocalAddr => "::1",
LocalPort => 0,
Listen=>1,
);
$s or die "\n";
$s->close();
};
if ($@ eq "") {
$IP_factory = sub { IO::Socket::IP->new(@_); };
$have_IPv6 = 1;
} else {
$IP_factory = sub { IO::Socket::INET->new(@_); };
$have_IPv6 = 0;
}
}
}
my $is_tls13 = 0;
my $ciphersuite = undef;
sub new
{
my $class = shift;
my ($filter,
$execute,
$cert,
$debug) = @_;
my $self = {
#Public read/write
proxy_addr => $have_IPv6 ? "[::1]" : "127.0.0.1",
filter => $filter,
serverflags => "",
clientflags => "",
serverconnects => 1,
reneg => 0,
sessionfile => undef,
#Public read
proxy_port => 0,
server_port => 0,
serverpid => 0,
clientpid => 0,
execute => $execute,
cert => $cert,
debug => $debug,
cipherc => "",
ciphersuitesc => "",
ciphers => "AES128-SHA",
ciphersuitess => "TLS_AES_128_GCM_SHA256",
flight => -1,
direction => -1,
partial => ["", ""],
record_list => [],
message_list => [],
};
# Create the Proxy socket
my $proxaddr = $self->{proxy_addr};
$proxaddr =~ s/[\[\]]//g; # Remove [ and ]
my @proxyargs = (
LocalHost => $proxaddr,
LocalPort => 0,
Proto => "tcp",
Listen => SOMAXCONN,
);
if (my $sock = $IP_factory->(@proxyargs)) {
$self->{proxy_sock} = $sock;
$self->{proxy_port} = $sock->sockport();
$self->{proxy_addr} = $sock->sockhost();
$self->{proxy_addr} =~ s/(.*:.*)/[$1]/;
print "Proxy started on port ",
"$self->{proxy_addr}:$self->{proxy_port}\n";
# use same address for s_server
$self->{server_addr} = $self->{proxy_addr};
} else {
warn "Failed creating proxy socket (".$proxaddr.",0): $!\n";
}
return bless $self, $class;
}
sub DESTROY
{
my $self = shift;
$self->{proxy_sock}->close() if $self->{proxy_sock};
}
sub clearClient
{
my $self = shift;
$self->{cipherc} = "";
$self->{ciphersuitec} = "";
$self->{flight} = -1;
$self->{direction} = -1;
$self->{partial} = ["", ""];
$self->{record_list} = [];
$self->{message_list} = [];
$self->{clientflags} = "";
$self->{sessionfile} = undef;
$self->{clientpid} = 0;
$is_tls13 = 0;
$ciphersuite = undef;
TLSProxy::Message->clear();
TLSProxy::Record->clear();
}
sub clear
{
my $self = shift;
$self->clearClient;
$self->{ciphers} = "AES128-SHA";
$self->{ciphersuitess} = "TLS_AES_128_GCM_SHA256";
$self->{serverflags} = "";
$self->{serverconnects} = 1;
$self->{serverpid} = 0;
$self->{reneg} = 0;
}
sub restart
{
my $self = shift;
$self->clear;
$self->start;
}
sub clientrestart
{
my $self = shift;
$self->clear;
$self->clientstart;
}
sub connect_to_server
{
my $self = shift;
my $servaddr = $self->{server_addr};
$servaddr =~ s/[\[\]]//g; # Remove [ and ]
my $sock = $IP_factory->(PeerAddr => $servaddr,
PeerPort => $self->{server_port},
Proto => 'tcp');
if (!defined($sock)) {
my $err = $!;
kill(3, $self->{real_serverpid});
die "unable to connect: $err\n";
}
$self->{server_sock} = $sock;
}
sub start
{
my ($self) = shift;
my $pid;
if ($self->{proxy_sock} == 0) {
return 0;
}
my $execcmd = $self->execute
." s_server -max_protocol TLSv1.3 -no_comp -rev -engine ossltest"
#In TLSv1.3 we issue two session tickets. The default session id
#callback gets confused because the ossltest engine causes the same
#session id to be created twice due to the changed random number
#generation. Using "-ext_cache" replaces the default callback with a
#different one that doesn't get confused.
." -ext_cache"
." -accept $self->{server_addr}:0"
." -cert ".$self->cert." -cert2 ".$self->cert
." -naccept ".$self->serverconnects;
if ($self->ciphers ne "") {
$execcmd .= " -cipher ".$self->ciphers;
}
if ($self->ciphersuitess ne "") {
$execcmd .= " -ciphersuites ".$self->ciphersuitess;
}
if ($self->serverflags ne "") {
$execcmd .= " ".$self->serverflags;
}
if ($self->debug) {
print STDERR "Server command: $execcmd\n";
}
open(my $savedin, "<&STDIN");
# Temporarily replace STDIN so that sink process can inherit it...
$pid = open(STDIN, "$execcmd 2>&1 |") or die "Failed to $execcmd: $!\n";
$self->{real_serverpid} = $pid;
# Process the output from s_server until we find the ACCEPT line, which
# tells us what the accepting address and port are.
while (<>) {
print;
s/\R$//; # Better chomp
next unless (/^ACCEPT\s.*:(\d+)$/);
$self->{server_port} = $1;
last;
}
if ($self->{server_port} == 0) {
# This actually means that s_server exited, because otherwise
# we would still searching for ACCEPT...
waitpid($pid, 0);
die "no ACCEPT detected in '$execcmd' output: $?\n";
}
# Just make sure everything else is simply printed [as separate lines].
# The sub process simply inherits our STD* and will keep consuming
# server's output and printing it as long as there is anything there,
# out of our way.
my $error;
$pid = undef;
if (eval { require Win32::Process; 1; }) {
if (Win32::Process::Create(my $h, $^X, "perl -ne print", 0, 0, ".")) {
$pid = $h->GetProcessID();
$self->{proc_handle} = $h; # hold handle till next round [or exit]
} else {
$error = Win32::FormatMessage(Win32::GetLastError());
}
} else {
if (defined($pid = fork)) {
$pid or exec("$^X -ne print") or exit($!);
} else {
$error = $!;
}
}
# Change back to original stdin
open(STDIN, "<&", $savedin);
close($savedin);
if (!defined($pid)) {
kill(3, $self->{real_serverpid});
die "Failed to capture s_server's output: $error\n";
}
$self->{serverpid} = $pid;
print STDERR "Server responds on ",
"$self->{server_addr}:$self->{server_port}\n";
# Connect right away...
$self->connect_to_server();
return $self->clientstart;
}
sub clientstart
{
my ($self) = shift;
if ($self->execute) {
my $pid;
my $execcmd = $self->execute
." s_client -max_protocol TLSv1.3 -engine ossltest"
." -connect $self->{proxy_addr}:$self->{proxy_port}";
if ($self->cipherc ne "") {
$execcmd .= " -cipher ".$self->cipherc;
}
if ($self->ciphersuitesc ne "") {
$execcmd .= " -ciphersuites ".$self->ciphersuitesc;
}
if ($self->clientflags ne "") {
$execcmd .= " ".$self->clientflags;
}
if ($self->clientflags !~ m/-(no)?servername/) {
$execcmd .= " -servername localhost";
}
if (defined $self->sessionfile) {
$execcmd .= " -ign_eof";
}
if ($self->debug) {
print STDERR "Client command: $execcmd\n";
}
open(my $savedout, ">&STDOUT");
# If we open pipe with new descriptor, attempt to close it,
# explicitly or implicitly, would incur waitpid and effectively
# dead-lock...
if (!($pid = open(STDOUT, "| $execcmd"))) {
my $err = $!;
kill(3, $self->{real_serverpid});
die "Failed to $execcmd: $err\n";
}
$self->{clientpid} = $pid;
# queue [magic] input
print $self->reneg ? "R" : "test";
# this closes client's stdin without waiting for its pid
open(STDOUT, ">&", $savedout);
close($savedout);
}
# Wait for incoming connection from client
my $fdset = IO::Select->new($self->{proxy_sock});
if (!$fdset->can_read(60)) {
kill(3, $self->{real_serverpid});
die "s_client didn't try to connect\n";
}
my $client_sock;
if(!($client_sock = $self->{proxy_sock}->accept())) {
warn "Failed accepting incoming connection: $!\n";
return 0;
}
print "Connection opened\n";
my $server_sock = $self->{server_sock};
my $indata;
#Wait for either the server socket or the client socket to become readable
$fdset = IO::Select->new($server_sock, $client_sock);
my @ready;
my $ctr = 0;
local $SIG{PIPE} = "IGNORE";
$self->{saw_session_ticket} = undef;
while($fdset->count && $ctr < 10) {
if (defined($self->{sessionfile})) {
# s_client got -ign_eof and won't be exiting voluntarily, so we
# look for data *and* session ticket...
last if TLSProxy::Message->success()
&& $self->{saw_session_ticket};
}
if (!(@ready = $fdset->can_read(1))) {
$ctr++;
next;
}
foreach my $hand (@ready) {
if ($hand == $server_sock) {
if ($server_sock->sysread($indata, 16384)) {
if ($indata = $self->process_packet(1, $indata)) {
$client_sock->syswrite($indata) or goto END;
}
$ctr = 0;
} else {
$fdset->remove($server_sock);
$client_sock->shutdown(SHUT_WR);
}
} elsif ($hand == $client_sock) {
if ($client_sock->sysread($indata, 16384)) {
if ($indata = $self->process_packet(0, $indata)) {
$server_sock->syswrite($indata) or goto END;
}
$ctr = 0;
} else {
$fdset->remove($client_sock);
$server_sock->shutdown(SHUT_WR);
}
} else {
kill(3, $self->{real_serverpid});
die "Unexpected handle";
}
}
}
if ($ctr >= 10) {
kill(3, $self->{real_serverpid});
die "No progress made";
}
END:
print "Connection closed\n";
if($server_sock) {
$server_sock->close();
$self->{server_sock} = undef;
}
if($client_sock) {
#Closing this also kills the child process
$client_sock->close();
}
my $pid;
if (--$self->{serverconnects} == 0) {
$pid = $self->{serverpid};
print "Waiting for 'perl -ne print' process to close: $pid...\n";
$pid = waitpid($pid, 0);
if ($pid > 0) {
die "exit code $? from 'perl -ne print' process\n" if $? != 0;
} elsif ($pid == 0) {
kill(3, $self->{real_serverpid});
die "lost control over $self->{serverpid}?";
}
$pid = $self->{real_serverpid};
print "Waiting for s_server process to close: $pid...\n";
# it's done already, just collect the exit code [and reap]...
waitpid($pid, 0);
die "exit code $? from s_server process\n" if $? != 0;
} else {
# It's a bit counter-intuitive spot to make next connection to
# the s_server. Rationale is that established connection works
# as synchronization point, in sense that this way we know that
# s_server is actually done with current session...
$self->connect_to_server();
}
$pid = $self->{clientpid};
print "Waiting for s_client process to close: $pid...\n";
waitpid($pid, 0);
return 1;
}
sub process_packet
{
my ($self, $server, $packet) = @_;
my $len_real;
my $decrypt_len;
my $data;
my $recnum;
if ($server) {
print "Received server packet\n";
} else {
print "Received client packet\n";
}
if ($self->{direction} != $server) {
$self->{flight} = $self->{flight} + 1;
$self->{direction} = $server;
}
print "Packet length = ".length($packet)."\n";
print "Processing flight ".$self->flight."\n";
#Return contains the list of record found in the packet followed by the
#list of messages in those records and any partial message
my @ret = TLSProxy::Record->get_records($server, $self->flight,
$self->{partial}[$server].$packet);
$self->{partial}[$server] = $ret[2];
push @{$self->{record_list}}, @{$ret[0]};
push @{$self->{message_list}}, @{$ret[1]};
print "\n";
if (scalar(@{$ret[0]}) == 0 or length($ret[2]) != 0) {
return "";
}
#Finished parsing. Call user provided filter here
if (defined $self->filter) {
$self->filter->($self);
}
#Take a note on NewSessionTicket
foreach my $message (reverse @{$self->{message_list}}) {
if ($message->{mt} == TLSProxy::Message::MT_NEW_SESSION_TICKET) {
$self->{saw_session_ticket} = 1;
last;
}
}
#Reconstruct the packet
$packet = "";
foreach my $record (@{$self->record_list}) {
$packet .= $record->reconstruct_record($server);
}
print "Forwarded packet length = ".length($packet)."\n\n";
return $packet;
}
#Read accessors
sub execute
{
my $self = shift;
return $self->{execute};
}
sub cert
{
my $self = shift;
return $self->{cert};
}
sub debug
{
my $self = shift;
return $self->{debug};
}
sub flight
{
my $self = shift;
return $self->{flight};
}
sub record_list
{
my $self = shift;
return $self->{record_list};
}
sub success
{
my $self = shift;
return $self->{success};
}
sub end
{
my $self = shift;
return $self->{end};
}
sub supports_IPv6
{
my $self = shift;
return $have_IPv6;
}
sub proxy_addr
{
my $self = shift;
return $self->{proxy_addr};
}
sub proxy_port
{
my $self = shift;
return $self->{proxy_port};
}
sub server_addr
{
my $self = shift;
return $self->{server_addr};
}
sub server_port
{
my $self = shift;
return $self->{server_port};
}
sub serverpid
{
my $self = shift;
return $self->{serverpid};
}
sub clientpid
{
my $self = shift;
return $self->{clientpid};
}
#Read/write accessors
sub filter
{
my $self = shift;
if (@_) {
$self->{filter} = shift;
}
return $self->{filter};
}
sub cipherc
{
my $self = shift;
if (@_) {
$self->{cipherc} = shift;
}
return $self->{cipherc};
}
sub ciphersuitesc
{
my $self = shift;
if (@_) {
$self->{ciphersuitesc} = shift;
}
return $self->{ciphersuitesc};
}
sub ciphers
{
my $self = shift;
if (@_) {
$self->{ciphers} = shift;
}
return $self->{ciphers};
}
sub ciphersuitess
{
my $self = shift;
if (@_) {
$self->{ciphersuitess} = shift;
}
return $self->{ciphersuitess};
}
sub serverflags
{
my $self = shift;
if (@_) {
$self->{serverflags} = shift;
}
return $self->{serverflags};
}
sub clientflags
{
my $self = shift;
if (@_) {
$self->{clientflags} = shift;
}
return $self->{clientflags};
}
sub serverconnects
{
my $self = shift;
if (@_) {
$self->{serverconnects} = shift;
}
return $self->{serverconnects};
}
# This is a bit ugly because the caller is responsible for keeping the records
# in sync with the updated message list; simply updating the message list isn't
# sufficient to get the proxy to forward the new message.
# But it does the trick for the one test (test_sslsessiontick) that needs it.
sub message_list
{
my $self = shift;
if (@_) {
$self->{message_list} = shift;
}
return $self->{message_list};
}
sub fill_known_data
{
my $length = shift;
my $ret = "";
for (my $i = 0; $i < $length; $i++) {
$ret .= chr($i);
}
return $ret;
}
sub is_tls13
{
my $class = shift;
if (@_) {
$is_tls13 = shift;
}
return $is_tls13;
}
sub reneg
{
my $self = shift;
if (@_) {
$self->{reneg} = shift;
}
return $self->{reneg};
}
#Setting a sessionfile means that the client will not close until the given
#file exists. This is useful in TLSv1.3 where otherwise s_client will close
#immediately at the end of the handshake, but before the session has been
#received from the server. A side effect of this is that s_client never sends
#a close_notify, so instead we consider success to be when it sends application
#data over the connection.
sub sessionfile
{
my $self = shift;
if (@_) {
$self->{sessionfile} = shift;
TLSProxy::Message->successondata(1);
}
return $self->{sessionfile};
}
sub ciphersuite
{
my $class = shift;
if (@_) {
$ciphersuite = shift;
}
return $ciphersuite;
}
1;

File Metadata

Mime Type
application/octet-stream
Expires
Mon, Oct 13, 7:06 AM (1 d, 23 h)
Storage Engine
chunks
Storage Format
Chunks
Storage Handle
EDsUM5igULaX
Default Alt Text
(4 MB)

Event Timeline