Page MenuHomeFreeBSD

No OneTemporary

This file is larger than 256 KB, so syntax highlighting was skipped.
This document is not UTF8. It was detected as ISO-8859-1 (Latin 1) and converted to UTF8 for display.
diff --git a/CHANGES b/CHANGES
index f2fc31a25c54..cc142508b9a4 100644
--- a/CHANGES
+++ b/CHANGES
@@ -1,11533 +1,11551 @@
OpenSSL CHANGES
_______________
This is a high-level summary of the most important changes.
For a full list of changes, see the git commit log; for example,
https://github.com/openssl/openssl/commits/ and pick the appropriate
release branch.
+ Changes between 1.0.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.
(CVE-2017-3735)
[Rich Salz]
Changes between 1.0.2k and 1.0.2l [25 May 2017]
*) Have 'config' recognise 64-bit mingw and choose 'mingw64' as the target
platform rather than 'mingw'.
[Richard Levitte]
Changes between 1.0.2j and 1.0.2k [26 Jan 2017]
*) Truncated packet could crash via OOB read
If one side of an SSL/TLS path is running on a 32-bit host and a specific
cipher is being used, then a truncated packet can cause that host to
perform an out-of-bounds read, usually resulting in a crash.
This issue was reported to OpenSSL by Robert Święcki of Google.
(CVE-2017-3731)
[Andy Polyakov]
*) BN_mod_exp may produce incorrect results on x86_64
There is a carry propagating bug in the x86_64 Montgomery squaring
procedure. No EC algorithms are affected. Analysis suggests that attacks
against RSA and DSA as a result of this defect would be very difficult to
perform and are not believed likely. Attacks against DH are considered just
feasible (although very difficult) because most of the work necessary to
deduce information about a private key may be performed offline. The amount
of resources required for such an attack would be very significant and
likely only accessible to a limited number of attackers. An attacker would
additionally need online access to an unpatched system using the target
private key in a scenario with persistent DH parameters and a private
key that is shared between multiple clients. For example this can occur by
default in OpenSSL DHE based SSL/TLS ciphersuites. Note: This issue is very
similar to CVE-2015-3193 but must be treated as a separate problem.
This issue was reported to OpenSSL by the OSS-Fuzz project.
(CVE-2017-3732)
[Andy Polyakov]
*) Montgomery multiplication may produce incorrect results
There is a carry propagating bug in the Broadwell-specific Montgomery
multiplication procedure that handles input lengths divisible by, but
longer than 256 bits. Analysis suggests that attacks against RSA, DSA
and DH private keys are impossible. This is because the subroutine in
question is not used in operations with the private key itself and an input
of the attacker's direct choice. Otherwise the bug can manifest itself as
transient authentication and key negotiation failures or reproducible
erroneous outcome of public-key operations with specially crafted input.
Among EC algorithms only Brainpool P-512 curves are affected and one
presumably can attack ECDH key negotiation. Impact was not analyzed in
detail, because pre-requisites for attack are considered unlikely. Namely
multiple clients have to choose the curve in question and the server has to
share the private key among them, neither of which is default behaviour.
Even then only clients that chose the curve will be affected.
This issue was publicly reported as transient failures and was not
initially recognized as a security issue. Thanks to Richard Morgan for
providing reproducible case.
(CVE-2016-7055)
[Andy Polyakov]
*) OpenSSL now fails if it receives an unrecognised record type in TLS1.0
or TLS1.1. Previously this only happened in SSLv3 and TLS1.2. This is to
prevent issues where no progress is being made and the peer continually
sends unrecognised record types, using up resources processing them.
[Matt Caswell]
Changes between 1.0.2i and 1.0.2j [26 Sep 2016]
*) Missing CRL sanity check
A bug fix which included a CRL sanity check was added to OpenSSL 1.1.0
but was omitted from OpenSSL 1.0.2i. As a result any attempt to use
CRLs in OpenSSL 1.0.2i will crash with a null pointer exception.
This issue only affects the OpenSSL 1.0.2i
(CVE-2016-7052)
[Matt Caswell]
Changes between 1.0.2h and 1.0.2i [22 Sep 2016]
*) OCSP Status Request extension unbounded memory growth
A malicious client can send an excessively large OCSP Status Request
extension. If that client continually requests renegotiation, sending a
large OCSP Status Request extension each time, then there will be unbounded
memory growth on the server. This will eventually lead to a Denial Of
Service attack through memory exhaustion. Servers with a default
configuration are vulnerable even if they do not support OCSP. Builds using
the "no-ocsp" build time option are not affected.
This issue was reported to OpenSSL by Shi Lei (Gear Team, Qihoo 360 Inc.)
(CVE-2016-6304)
[Matt Caswell]
*) In order to mitigate the SWEET32 attack, the DES ciphers were moved from
HIGH to MEDIUM.
This issue was reported to OpenSSL Karthikeyan Bhargavan and Gaetan
Leurent (INRIA)
(CVE-2016-2183)
[Rich Salz]
*) OOB write in MDC2_Update()
An overflow can occur in MDC2_Update() either if called directly or
through the EVP_DigestUpdate() function using MDC2. If an attacker
is able to supply very large amounts of input data after a previous
call to EVP_EncryptUpdate() with a partial block then a length check
can overflow resulting in a heap corruption.
The amount of data needed is comparable to SIZE_MAX which is impractical
on most platforms.
This issue was reported to OpenSSL by Shi Lei (Gear Team, Qihoo 360 Inc.)
(CVE-2016-6303)
[Stephen Henson]
*) Malformed SHA512 ticket DoS
If a server uses SHA512 for TLS session ticket HMAC it is vulnerable to a
DoS attack where a malformed ticket will result in an OOB read which will
ultimately crash.
The use of SHA512 in TLS session tickets is comparatively rare as it requires
a custom server callback and ticket lookup mechanism.
This issue was reported to OpenSSL by Shi Lei (Gear Team, Qihoo 360 Inc.)
(CVE-2016-6302)
[Stephen Henson]
*) OOB write in BN_bn2dec()
The function BN_bn2dec() does not check the return value of BN_div_word().
This can cause an OOB write if an application uses this function with an
overly large BIGNUM. This could be a problem if an overly large certificate
or CRL is printed out from an untrusted source. TLS is not affected because
record limits will reject an oversized certificate before it is parsed.
This issue was reported to OpenSSL by Shi Lei (Gear Team, Qihoo 360 Inc.)
(CVE-2016-2182)
[Stephen Henson]
*) OOB read in TS_OBJ_print_bio()
The function TS_OBJ_print_bio() misuses OBJ_obj2txt(): the return value is
the total length the OID text representation would use and not the amount
of data written. This will result in OOB reads when large OIDs are
presented.
This issue was reported to OpenSSL by Shi Lei (Gear Team, Qihoo 360 Inc.)
(CVE-2016-2180)
[Stephen Henson]
*) Pointer arithmetic undefined behaviour
Avoid some undefined pointer arithmetic
A common idiom in the codebase is to check limits in the following manner:
"p + len > limit"
Where "p" points to some malloc'd data of SIZE bytes and
limit == p + SIZE
"len" here could be from some externally supplied data (e.g. from a TLS
message).
The rules of C pointer arithmetic are such that "p + len" is only well
defined where len <= SIZE. Therefore the above idiom is actually
undefined behaviour.
For example this could cause problems if some malloc implementation
provides an address for "p" such that "p + len" actually overflows for
values of len that are too big and therefore p + len < limit.
This issue was reported to OpenSSL by Guido Vranken
(CVE-2016-2177)
[Matt Caswell]
*) Constant time flag not preserved in DSA signing
Operations in the DSA signing algorithm should run in constant time in
order to avoid side channel attacks. A flaw in the OpenSSL DSA
implementation means that a non-constant time codepath is followed for
certain operations. This has been demonstrated through a cache-timing
attack to be sufficient for an attacker to recover the private DSA key.
This issue was reported by César Pereida (Aalto University), Billy Brumley
(Tampere University of Technology), and Yuval Yarom (The University of
Adelaide and NICTA).
(CVE-2016-2178)
[César Pereida]
*) DTLS buffered message DoS
In a DTLS connection where handshake messages are delivered out-of-order
those messages that OpenSSL is not yet ready to process will be buffered
for later use. Under certain circumstances, a flaw in the logic means that
those messages do not get removed from the buffer even though the handshake
has been completed. An attacker could force up to approx. 15 messages to
remain in the buffer when they are no longer required. These messages will
be cleared when the DTLS connection is closed. The default maximum size for
a message is 100k. Therefore the attacker could force an additional 1500k
to be consumed per connection. By opening many simulataneous connections an
attacker could cause a DoS attack through memory exhaustion.
This issue was reported to OpenSSL by Quan Luo.
(CVE-2016-2179)
[Matt Caswell]
*) DTLS replay protection DoS
A flaw in the DTLS replay attack protection mechanism means that records
that arrive for future epochs update the replay protection "window" before
the MAC for the record has been validated. This could be exploited by an
attacker by sending a record for the next epoch (which does not have to
decrypt or have a valid MAC), with a very large sequence number. This means
that all subsequent legitimate packets are dropped causing a denial of
service for a specific DTLS connection.
This issue was reported to OpenSSL by the OCAP audit team.
(CVE-2016-2181)
[Matt Caswell]
*) Certificate message OOB reads
In OpenSSL 1.0.2 and earlier some missing message length checks can result
in OOB reads of up to 2 bytes beyond an allocated buffer. There is a
theoretical DoS risk but this has not been observed in practice on common
platforms.
The messages affected are client certificate, client certificate request
and server certificate. As a result the attack can only be performed
against a client or a server which enables client authentication.
This issue was reported to OpenSSL by Shi Lei (Gear Team, Qihoo 360 Inc.)
(CVE-2016-6306)
[Stephen Henson]
Changes between 1.0.2g and 1.0.2h [3 May 2016]
*) Prevent padding oracle in AES-NI CBC MAC check
A MITM attacker can use a padding oracle attack to decrypt traffic
when the connection uses an AES CBC cipher and the server support
AES-NI.
This issue was introduced as part of the fix for Lucky 13 padding
attack (CVE-2013-0169). The padding check was rewritten to be in
constant time by making sure that always the same bytes are read and
compared against either the MAC or padding bytes. But it no longer
checked that there was enough data to have both the MAC and padding
bytes.
This issue was reported by Juraj Somorovsky using TLS-Attacker.
(CVE-2016-2107)
[Kurt Roeckx]
*) Fix EVP_EncodeUpdate overflow
An overflow can occur in the EVP_EncodeUpdate() function which is used for
Base64 encoding of binary data. If an attacker is able to supply very large
amounts of input data then a length check can overflow resulting in a heap
corruption.
Internally to OpenSSL the EVP_EncodeUpdate() function is primarly used by
the PEM_write_bio* family of functions. These are mainly used within the
OpenSSL command line applications, so any application which processes data
from an untrusted source and outputs it as a PEM file should be considered
vulnerable to this issue. User applications that call these APIs directly
with large amounts of untrusted data may also be vulnerable.
This issue was reported by Guido Vranken.
(CVE-2016-2105)
[Matt Caswell]
*) Fix EVP_EncryptUpdate overflow
An overflow can occur in the EVP_EncryptUpdate() function. If an attacker
is able to supply very large amounts of input data after a previous call to
EVP_EncryptUpdate() with a partial block then a length check can overflow
resulting in a heap corruption. Following an analysis of all OpenSSL
internal usage of the EVP_EncryptUpdate() function all usage is one of two
forms. The first form is where the EVP_EncryptUpdate() call is known to be
the first called function after an EVP_EncryptInit(), and therefore that
specific call must be safe. The second form is where the length passed to
EVP_EncryptUpdate() can be seen from the code to be some small value and
therefore there is no possibility of an overflow. Since all instances are
one of these two forms, it is believed that there can be no overflows in
internal code due to this problem. It should be noted that
EVP_DecryptUpdate() can call EVP_EncryptUpdate() in certain code paths.
Also EVP_CipherUpdate() is a synonym for EVP_EncryptUpdate(). All instances
of these calls have also been analysed too and it is believed there are no
instances in internal usage where an overflow could occur.
This issue was reported by Guido Vranken.
(CVE-2016-2106)
[Matt Caswell]
*) Prevent ASN.1 BIO excessive memory allocation
When ASN.1 data is read from a BIO using functions such as d2i_CMS_bio()
a short invalid encoding can casuse allocation of large amounts of memory
potentially consuming excessive resources or exhausting memory.
Any application parsing untrusted data through d2i BIO functions is
affected. The memory based functions such as d2i_X509() are *not* affected.
Since the memory based functions are used by the TLS library, TLS
applications are not affected.
This issue was reported by Brian Carpenter.
(CVE-2016-2109)
[Stephen Henson]
*) EBCDIC overread
ASN1 Strings that are over 1024 bytes can cause an overread in applications
using the X509_NAME_oneline() function on EBCDIC systems. This could result
in arbitrary stack data being returned in the buffer.
This issue was reported by Guido Vranken.
(CVE-2016-2176)
[Matt Caswell]
*) Modify behavior of ALPN to invoke callback after SNI/servername
callback, such that updates to the SSL_CTX affect ALPN.
[Todd Short]
*) Remove LOW from the DEFAULT cipher list. This removes singles DES from the
default.
[Kurt Roeckx]
*) Only remove the SSLv2 methods with the no-ssl2-method option. When the
methods are enabled and ssl2 is disabled the methods return NULL.
[Kurt Roeckx]
Changes between 1.0.2f and 1.0.2g [1 Mar 2016]
* Disable weak ciphers in SSLv3 and up in default builds of OpenSSL.
Builds that are not configured with "enable-weak-ssl-ciphers" will not
provide any "EXPORT" or "LOW" strength ciphers.
[Viktor Dukhovni]
* Disable SSLv2 default build, default negotiation and weak ciphers. SSLv2
is by default disabled at build-time. Builds that are not configured with
"enable-ssl2" will not support SSLv2. Even if "enable-ssl2" is used,
users who want to negotiate SSLv2 via the version-flexible SSLv23_method()
will need to explicitly call either of:
SSL_CTX_clear_options(ctx, SSL_OP_NO_SSLv2);
or
SSL_clear_options(ssl, SSL_OP_NO_SSLv2);
as appropriate. Even if either of those is used, or the application
explicitly uses the version-specific SSLv2_method() or its client and
server variants, SSLv2 ciphers vulnerable to exhaustive search key
recovery have been removed. Specifically, the SSLv2 40-bit EXPORT
ciphers, and SSLv2 56-bit DES are no longer available.
(CVE-2016-0800)
[Viktor Dukhovni]
*) Fix a double-free in DSA code
A double free bug was discovered when OpenSSL parses malformed DSA private
keys and could lead to a DoS attack or memory corruption for applications
that receive DSA private keys from untrusted sources. This scenario is
considered rare.
This issue was reported to OpenSSL by Adam Langley(Google/BoringSSL) using
libFuzzer.
(CVE-2016-0705)
[Stephen Henson]
*) Disable SRP fake user seed to address a server memory leak.
Add a new method SRP_VBASE_get1_by_user that handles the seed properly.
SRP_VBASE_get_by_user had inconsistent memory management behaviour.
In order to fix an unavoidable memory leak, SRP_VBASE_get_by_user
was changed to ignore the "fake user" SRP seed, even if the seed
is configured.
Users should use SRP_VBASE_get1_by_user instead. Note that in
SRP_VBASE_get1_by_user, caller must free the returned value. Note
also that even though configuring the SRP seed attempts to hide
invalid usernames by continuing the handshake with fake
credentials, this behaviour is not constant time and no strong
guarantees are made that the handshake is indistinguishable from
that of a valid user.
(CVE-2016-0798)
[Emilia Käsper]
*) Fix BN_hex2bn/BN_dec2bn NULL pointer deref/heap corruption
In the BN_hex2bn function the number of hex digits is calculated using an
int value |i|. Later |bn_expand| is called with a value of |i * 4|. For
large values of |i| this can result in |bn_expand| not allocating any
memory because |i * 4| is negative. This can leave the internal BIGNUM data
field as NULL leading to a subsequent NULL ptr deref. For very large values
of |i|, the calculation |i * 4| could be a positive value smaller than |i|.
In this case memory is allocated to the internal BIGNUM data field, but it
is insufficiently sized leading to heap corruption. A similar issue exists
in BN_dec2bn. This could have security consequences if BN_hex2bn/BN_dec2bn
is ever called by user applications with very large untrusted hex/dec data.
This is anticipated to be a rare occurrence.
All OpenSSL internal usage of these functions use data that is not expected
to be untrusted, e.g. config file data or application command line
arguments. If user developed applications generate config file data based
on untrusted data then it is possible that this could also lead to security
consequences. This is also anticipated to be rare.
This issue was reported to OpenSSL by Guido Vranken.
(CVE-2016-0797)
[Matt Caswell]
*) Fix memory issues in BIO_*printf functions
The internal |fmtstr| function used in processing a "%s" format string in
the BIO_*printf functions could overflow while calculating the length of a
string and cause an OOB read when printing very long strings.
Additionally the internal |doapr_outch| function can attempt to write to an
OOB memory location (at an offset from the NULL pointer) in the event of a
memory allocation failure. In 1.0.2 and below this could be caused where
the size of a buffer to be allocated is greater than INT_MAX. E.g. this
could be in processing a very long "%s" format string. Memory leaks can
also occur.
The first issue may mask the second issue dependent on compiler behaviour.
These problems could enable attacks where large amounts of untrusted data
is passed to the BIO_*printf functions. If applications use these functions
in this way then they could be vulnerable. OpenSSL itself uses these
functions when printing out human-readable dumps of ASN.1 data. Therefore
applications that print this data could be vulnerable if the data is from
untrusted sources. OpenSSL command line applications could also be
vulnerable where they print out ASN.1 data, or if untrusted data is passed
as command line arguments.
Libssl is not considered directly vulnerable. Additionally certificates etc
received via remote connections via libssl are also unlikely to be able to
trigger these issues because of message size limits enforced within libssl.
This issue was reported to OpenSSL Guido Vranken.
(CVE-2016-0799)
[Matt Caswell]
*) Side channel attack on modular exponentiation
A side-channel attack was found which makes use of cache-bank conflicts on
the Intel Sandy-Bridge microarchitecture which could lead to the recovery
of RSA keys. The ability to exploit this issue is limited as it relies on
an attacker who has control of code in a thread running on the same
hyper-threaded core as the victim thread which is performing decryptions.
This issue was reported to OpenSSL by Yuval Yarom, The University of
Adelaide and NICTA, Daniel Genkin, Technion and Tel Aviv University, and
Nadia Heninger, University of Pennsylvania with more information at
http://cachebleed.info.
(CVE-2016-0702)
[Andy Polyakov]
*) Change the req app to generate a 2048-bit RSA/DSA key by default,
if no keysize is specified with default_bits. This fixes an
omission in an earlier change that changed all RSA/DSA key generation
apps to use 2048 bits by default.
[Emilia Käsper]
Changes between 1.0.2e and 1.0.2f [28 Jan 2016]
*) DH small subgroups
Historically OpenSSL only ever generated DH parameters based on "safe"
primes. More recently (in version 1.0.2) support was provided for
generating X9.42 style parameter files such as those required for RFC 5114
support. The primes used in such files may not be "safe". Where an
application is using DH configured with parameters based on primes that are
not "safe" then an attacker could use this fact to find a peer's private
DH exponent. This attack requires that the attacker complete multiple
handshakes in which the peer uses the same private DH exponent. For example
this could be used to discover a TLS server's private DH exponent if it's
reusing the private DH exponent or it's using a static DH ciphersuite.
OpenSSL provides the option SSL_OP_SINGLE_DH_USE for ephemeral DH (DHE) in
TLS. It is not on by default. If the option is not set then the server
reuses the same private DH exponent for the life of the server process and
would be vulnerable to this attack. It is believed that many popular
applications do set this option and would therefore not be at risk.
The fix for this issue adds an additional check where a "q" parameter is
available (as is the case in X9.42 based parameters). This detects the
only known attack, and is the only possible defense for static DH
ciphersuites. This could have some performance impact.
Additionally the SSL_OP_SINGLE_DH_USE option has been switched on by
default and cannot be disabled. This could have some performance impact.
This issue was reported to OpenSSL by Antonio Sanso (Adobe).
(CVE-2016-0701)
[Matt Caswell]
*) SSLv2 doesn't block disabled ciphers
A malicious client can negotiate SSLv2 ciphers that have been disabled on
the server and complete SSLv2 handshakes even if all SSLv2 ciphers have
been disabled, provided that the SSLv2 protocol was not also disabled via
SSL_OP_NO_SSLv2.
This issue was reported to OpenSSL on 26th December 2015 by Nimrod Aviram
and Sebastian Schinzel.
(CVE-2015-3197)
[Viktor Dukhovni]
*) Reject DH handshakes with parameters shorter than 1024 bits.
[Kurt Roeckx]
Changes between 1.0.2d and 1.0.2e [3 Dec 2015]
*) BN_mod_exp may produce incorrect results on x86_64
There is a carry propagating bug in the x86_64 Montgomery squaring
procedure. No EC algorithms are affected. Analysis suggests that attacks
against RSA and DSA as a result of this defect would be very difficult to
perform and are not believed likely. Attacks against DH are considered just
feasible (although very difficult) because most of the work necessary to
deduce information about a private key may be performed offline. The amount
of resources required for such an attack would be very significant and
likely only accessible to a limited number of attackers. An attacker would
additionally need online access to an unpatched system using the target
private key in a scenario with persistent DH parameters and a private
key that is shared between multiple clients. For example this can occur by
default in OpenSSL DHE based SSL/TLS ciphersuites.
This issue was reported to OpenSSL by Hanno Böck.
(CVE-2015-3193)
[Andy Polyakov]
*) Certificate verify crash with missing PSS parameter
The signature verification routines will crash with a NULL pointer
dereference if presented with an ASN.1 signature using the RSA PSS
algorithm and absent mask generation function parameter. Since these
routines are used to verify certificate signature algorithms this can be
used to crash any certificate verification operation and exploited in a
DoS attack. Any application which performs certificate verification is
vulnerable including OpenSSL clients and servers which enable client
authentication.
This issue was reported to OpenSSL by Loïc Jonas Etienne (Qnective AG).
(CVE-2015-3194)
[Stephen Henson]
*) X509_ATTRIBUTE memory leak
When presented with a malformed X509_ATTRIBUTE structure OpenSSL will leak
memory. This structure is used by the PKCS#7 and CMS routines so any
application which reads PKCS#7 or CMS data from untrusted sources is
affected. SSL/TLS is not affected.
This issue was reported to OpenSSL by Adam Langley (Google/BoringSSL) using
libFuzzer.
(CVE-2015-3195)
[Stephen Henson]
*) Rewrite EVP_DecodeUpdate (base64 decoding) to fix several bugs.
This changes the decoding behaviour for some invalid messages,
though the change is mostly in the more lenient direction, and
legacy behaviour is preserved as much as possible.
[Emilia Käsper]
*) In DSA_generate_parameters_ex, if the provided seed is too short,
use a random seed, as already documented.
[Rich Salz and Ismo Puustinen <ismo.puustinen@intel.com>]
Changes between 1.0.2c and 1.0.2d [9 Jul 2015]
*) Alternate chains certificate forgery
During certificate verfification, OpenSSL will attempt to find an
alternative certificate chain if the first attempt to build such a chain
fails. An error in the implementation of this logic can mean that an
attacker could cause certain checks on untrusted certificates to be
bypassed, such as the CA flag, enabling them to use a valid leaf
certificate to act as a CA and "issue" an invalid certificate.
This issue was reported to OpenSSL by Adam Langley/David Benjamin
(Google/BoringSSL).
(CVE-2015-1793)
[Matt Caswell]
*) Race condition handling PSK identify hint
If PSK identity hints are received by a multi-threaded client then
the values are wrongly updated in the parent SSL_CTX structure. This can
result in a race condition potentially leading to a double free of the
identify hint data.
(CVE-2015-3196)
[Stephen Henson]
Changes between 1.0.2b and 1.0.2c [12 Jun 2015]
*) Fix HMAC ABI incompatibility. The previous version introduced an ABI
incompatibility in the handling of HMAC. The previous ABI has now been
restored.
Changes between 1.0.2a and 1.0.2b [11 Jun 2015]
*) Malformed ECParameters causes infinite loop
When processing an ECParameters structure OpenSSL enters an infinite loop
if the curve specified is over a specially malformed binary polynomial
field.
This can be used to perform denial of service against any
system which processes public keys, certificate requests or
certificates. This includes TLS clients and TLS servers with
client authentication enabled.
This issue was reported to OpenSSL by Joseph Barr-Pixton.
(CVE-2015-1788)
[Andy Polyakov]
*) Exploitable out-of-bounds read in X509_cmp_time
X509_cmp_time does not properly check the length of the ASN1_TIME
string and can read a few bytes out of bounds. In addition,
X509_cmp_time accepts an arbitrary number of fractional seconds in the
time string.
An attacker can use this to craft malformed certificates and CRLs of
various sizes and potentially cause a segmentation fault, resulting in
a DoS on applications that verify certificates or CRLs. TLS clients
that verify CRLs are affected. TLS clients and servers with client
authentication enabled may be affected if they use custom verification
callbacks.
This issue was reported to OpenSSL by Robert Swiecki (Google), and
independently by Hanno Böck.
(CVE-2015-1789)
[Emilia Käsper]
*) PKCS7 crash with missing EnvelopedContent
The PKCS#7 parsing code does not handle missing inner EncryptedContent
correctly. An attacker can craft malformed ASN.1-encoded PKCS#7 blobs
with missing content and trigger a NULL pointer dereference on parsing.
Applications that decrypt PKCS#7 data or otherwise parse PKCS#7
structures from untrusted sources are affected. OpenSSL clients and
servers are not affected.
This issue was reported to OpenSSL by Michal Zalewski (Google).
(CVE-2015-1790)
[Emilia Käsper]
*) CMS verify infinite loop with unknown hash function
When verifying a signedData message the CMS code can enter an infinite loop
if presented with an unknown hash function OID. This can be used to perform
denial of service against any system which verifies signedData messages using
the CMS code.
This issue was reported to OpenSSL by Johannes Bauer.
(CVE-2015-1792)
[Stephen Henson]
*) Race condition handling NewSessionTicket
If a NewSessionTicket is received by a multi-threaded client when attempting to
reuse a previous ticket then a race condition can occur potentially leading to
a double free of the ticket data.
(CVE-2015-1791)
[Matt Caswell]
*) Removed support for the two export grade static DH ciphersuites
EXP-DH-RSA-DES-CBC-SHA and EXP-DH-DSS-DES-CBC-SHA. These two ciphersuites
were newly added (along with a number of other static DH ciphersuites) to
1.0.2. However the two export ones have *never* worked since they were
introduced. It seems strange in any case to be adding new export
ciphersuites, and given "logjam" it also does not seem correct to fix them.
[Matt Caswell]
*) Only support 256-bit or stronger elliptic curves with the
'ecdh_auto' setting (server) or by default (client). Of supported
curves, prefer P-256 (both).
[Emilia Kasper]
*) Reject DH handshakes with parameters shorter than 768 bits.
[Kurt Roeckx and Emilia Kasper]
Changes between 1.0.2 and 1.0.2a [19 Mar 2015]
*) ClientHello sigalgs DoS fix
If a client connects to an OpenSSL 1.0.2 server and renegotiates with an
invalid signature algorithms extension a NULL pointer dereference will
occur. This can be exploited in a DoS attack against the server.
This issue was was reported to OpenSSL by David Ramos of Stanford
University.
(CVE-2015-0291)
[Stephen Henson and Matt Caswell]
*) Multiblock corrupted pointer fix
OpenSSL 1.0.2 introduced the "multiblock" performance improvement. This
feature only applies on 64 bit x86 architecture platforms that support AES
NI instructions. A defect in the implementation of "multiblock" can cause
OpenSSL's internal write buffer to become incorrectly set to NULL when
using non-blocking IO. Typically, when the user application is using a
socket BIO for writing, this will only result in a failed connection.
However if some other BIO is used then it is likely that a segmentation
fault will be triggered, thus enabling a potential DoS attack.
This issue was reported to OpenSSL by Daniel Danner and Rainer Mueller.
(CVE-2015-0290)
[Matt Caswell]
*) Segmentation fault in DTLSv1_listen fix
The DTLSv1_listen function is intended to be stateless and processes the
initial ClientHello from many peers. It is common for user code to loop
over the call to DTLSv1_listen until a valid ClientHello is received with
an associated cookie. A defect in the implementation of DTLSv1_listen means
that state is preserved in the SSL object from one invocation to the next
that can lead to a segmentation fault. Errors processing the initial
ClientHello can trigger this scenario. An example of such an error could be
that a DTLS1.0 only client is attempting to connect to a DTLS1.2 only
server.
This issue was reported to OpenSSL by Per Allansson.
(CVE-2015-0207)
[Matt Caswell]
*) Segmentation fault in ASN1_TYPE_cmp fix
The function ASN1_TYPE_cmp will crash with an invalid read if an attempt is
made to compare ASN.1 boolean types. Since ASN1_TYPE_cmp is used to check
certificate signature algorithm consistency this can be used to crash any
certificate verification operation and exploited in a DoS attack. Any
application which performs certificate verification is vulnerable including
OpenSSL clients and servers which enable client authentication.
(CVE-2015-0286)
[Stephen Henson]
*) Segmentation fault for invalid PSS parameters fix
The signature verification routines will crash with a NULL pointer
dereference if presented with an ASN.1 signature using the RSA PSS
algorithm and invalid parameters. Since these routines are used to verify
certificate signature algorithms this can be used to crash any
certificate verification operation and exploited in a DoS attack. Any
application which performs certificate verification is vulnerable including
OpenSSL clients and servers which enable client authentication.
This issue was was reported to OpenSSL by Brian Carpenter.
(CVE-2015-0208)
[Stephen Henson]
*) ASN.1 structure reuse memory corruption fix
Reusing a structure in ASN.1 parsing may allow an attacker to cause
memory corruption via an invalid write. Such reuse is and has been
strongly discouraged and is believed to be rare.
Applications that parse structures containing CHOICE or ANY DEFINED BY
components may be affected. Certificate parsing (d2i_X509 and related
functions) are however not affected. OpenSSL clients and servers are
not affected.
(CVE-2015-0287)
[Stephen Henson]
*) PKCS7 NULL pointer dereferences fix
The PKCS#7 parsing code does not handle missing outer ContentInfo
correctly. An attacker can craft malformed ASN.1-encoded PKCS#7 blobs with
missing content and trigger a NULL pointer dereference on parsing.
Applications that verify PKCS#7 signatures, decrypt PKCS#7 data or
otherwise parse PKCS#7 structures from untrusted sources are
affected. OpenSSL clients and servers are not affected.
This issue was reported to OpenSSL by Michal Zalewski (Google).
(CVE-2015-0289)
[Emilia Käsper]
*) DoS via reachable assert in SSLv2 servers fix
A malicious client can trigger an OPENSSL_assert (i.e., an abort) in
servers that both support SSLv2 and enable export cipher suites by sending
a specially crafted SSLv2 CLIENT-MASTER-KEY message.
This issue was discovered by Sean Burford (Google) and Emilia Käsper
(OpenSSL development team).
(CVE-2015-0293)
[Emilia Käsper]
*) Empty CKE with client auth and DHE fix
If client auth is used then a server can seg fault in the event of a DHE
ciphersuite being selected and a zero length ClientKeyExchange message
being sent by the client. This could be exploited in a DoS attack.
(CVE-2015-1787)
[Matt Caswell]
*) Handshake with unseeded PRNG fix
Under certain conditions an OpenSSL 1.0.2 client can complete a handshake
with an unseeded PRNG. The conditions are:
- The client is on a platform where the PRNG has not been seeded
automatically, and the user has not seeded manually
- A protocol specific client method version has been used (i.e. not
SSL_client_methodv23)
- A ciphersuite is used that does not require additional random data from
the PRNG beyond the initial ClientHello client random (e.g. PSK-RC4-SHA).
If the handshake succeeds then the client random that has been used will
have been generated from a PRNG with insufficient entropy and therefore the
output may be predictable.
For example using the following command with an unseeded openssl will
succeed on an unpatched platform:
openssl s_client -psk 1a2b3c4d -tls1_2 -cipher PSK-RC4-SHA
(CVE-2015-0285)
[Matt Caswell]
*) Use After Free following d2i_ECPrivatekey error fix
A malformed EC private key file consumed via the d2i_ECPrivateKey function
could cause a use after free condition. This, in turn, could cause a double
free in several private key parsing functions (such as d2i_PrivateKey
or EVP_PKCS82PKEY) and could lead to a DoS attack or memory corruption
for applications that receive EC private keys from untrusted
sources. This scenario is considered rare.
This issue was discovered by the BoringSSL project and fixed in their
commit 517073cd4b.
(CVE-2015-0209)
[Matt Caswell]
*) X509_to_X509_REQ NULL pointer deref fix
The function X509_to_X509_REQ will crash with a NULL pointer dereference if
the certificate key is invalid. This function is rarely used in practice.
This issue was discovered by Brian Carpenter.
(CVE-2015-0288)
[Stephen Henson]
*) Removed the export ciphers from the DEFAULT ciphers
[Kurt Roeckx]
Changes between 1.0.1l and 1.0.2 [22 Jan 2015]
*) Change RSA and DH/DSA key generation apps to generate 2048-bit
keys by default.
[Kurt Roeckx]
*) Facilitate "universal" ARM builds targeting range of ARM ISAs, e.g.
ARMv5 through ARMv8, as opposite to "locking" it to single one.
So far those who have to target multiple plaforms would compromise
and argue that binary targeting say ARMv5 would still execute on
ARMv8. "Universal" build resolves this compromise by providing
near-optimal performance even on newer platforms.
[Andy Polyakov]
*) Accelerated NIST P-256 elliptic curve implementation for x86_64
(other platforms pending).
[Shay Gueron & Vlad Krasnov (Intel Corp), Andy Polyakov]
*) Add support for the SignedCertificateTimestampList certificate and
OCSP response extensions from RFC6962.
[Rob Stradling]
*) Fix ec_GFp_simple_points_make_affine (thus, EC_POINTs_mul etc.)
for corner cases. (Certain input points at infinity could lead to
bogus results, with non-infinity inputs mapped to infinity too.)
[Bodo Moeller]
*) Initial support for PowerISA 2.0.7, first implemented in POWER8.
This covers AES, SHA256/512 and GHASH. "Initial" means that most
common cases are optimized and there still is room for further
improvements. Vector Permutation AES for Altivec is also added.
[Andy Polyakov]
*) Add support for little-endian ppc64 Linux target.
[Marcelo Cerri (IBM)]
*) Initial support for AMRv8 ISA crypto extensions. This covers AES,
SHA1, SHA256 and GHASH. "Initial" means that most common cases
are optimized and there still is room for further improvements.
Both 32- and 64-bit modes are supported.
[Andy Polyakov, Ard Biesheuvel (Linaro)]
*) Improved ARMv7 NEON support.
[Andy Polyakov]
*) Support for SPARC Architecture 2011 crypto extensions, first
implemented in SPARC T4. This covers AES, DES, Camellia, SHA1,
SHA256/512, MD5, GHASH and modular exponentiation.
[Andy Polyakov, David Miller]
*) Accelerated modular exponentiation for Intel processors, a.k.a.
RSAZ.
[Shay Gueron & Vlad Krasnov (Intel Corp)]
*) Support for new and upcoming Intel processors, including AVX2,
BMI and SHA ISA extensions. This includes additional "stitched"
implementations, AESNI-SHA256 and GCM, and multi-buffer support
for TLS encrypt.
This work was sponsored by Intel Corp.
[Andy Polyakov]
*) Support for DTLS 1.2. This adds two sets of DTLS methods: DTLS_*_method()
supports both DTLS 1.2 and 1.0 and should use whatever version the peer
supports and DTLSv1_2_*_method() which supports DTLS 1.2 only.
[Steve Henson]
*) Use algorithm specific chains in SSL_CTX_use_certificate_chain_file():
this fixes a limiation in previous versions of OpenSSL.
[Steve Henson]
*) Extended RSA OAEP support via EVP_PKEY API. Options to specify digest,
MGF1 digest and OAEP label.
[Steve Henson]
*) Add EVP support for key wrapping algorithms, to avoid problems with
existing code the flag EVP_CIPHER_CTX_WRAP_ALLOW has to be set in
the EVP_CIPHER_CTX or an error is returned. Add AES and DES3 wrap
algorithms and include tests cases.
[Steve Henson]
*) Add functions to allocate and set the fields of an ECDSA_METHOD
structure.
[Douglas E. Engert, Steve Henson]
*) New functions OPENSSL_gmtime_diff and ASN1_TIME_diff to find the
difference in days and seconds between two tm or ASN1_TIME structures.
[Steve Henson]
*) Add -rev test option to s_server to just reverse order of characters
received by client and send back to server. Also prints an abbreviated
summary of the connection parameters.
[Steve Henson]
*) New option -brief for s_client and s_server to print out a brief summary
of connection parameters.
[Steve Henson]
*) Add callbacks for arbitrary TLS extensions.
[Trevor Perrin <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 distint stores for certificate chain
verification and chain building. New ctrl SSL_CTRL_BUILD_CERT_CHAIN
to build and store a certificate chain in CERT structure: returing
an error if the chain cannot be built: this will allow applications
to test if a chain is correctly configured.
Note: if the CERT based stores are not set then the parent SSL_CTX
store is used to retain compatibility with existing behaviour.
[Steve Henson]
*) New function ssl_set_client_disabled to set a ciphersuite disabled
mask based on the current session, check mask when sending client
hello and checking the requested ciphersuite.
[Steve Henson]
*) New ctrls to retrieve and set certificate types in a certificate
request message. Print out received values in s_client. If certificate
types is not set with custom values set sensible values based on
supported signature algorithms.
[Steve Henson]
*) Support for distinct client and server supported signature algorithms.
[Steve Henson]
*) Add certificate callback. If set this is called whenever a certificate
is required by client or server. An application can decide which
certificate chain to present based on arbitrary criteria: for example
supported signature algorithms. Add very simple example to s_server.
This fixes many of the problems and restrictions of the existing client
certificate callback: for example you can now clear an existing
certificate and specify the whole chain.
[Steve Henson]
*) Add new "valid_flags" field to CERT_PKEY structure which determines what
the certificate can be used for (if anything). Set valid_flags field
in new tls1_check_chain function. Simplify ssl_set_cert_masks which used
to have similar checks in it.
Add new "cert_flags" field to CERT structure and include a "strict mode".
This enforces some TLS certificate requirements (such as only permitting
certificate signature algorithms contained in the supported algorithms
extension) which some implementations ignore: this option should be used
with caution as it could cause interoperability issues.
[Steve Henson]
*) Update and tidy signature algorithm extension processing. Work out
shared signature algorithms based on preferences and peer algorithms
and print them out in s_client and s_server. Abort handshake if no
shared signature algorithms.
[Steve Henson]
*) Add new functions to allow customised supported signature algorithms
for SSL and SSL_CTX structures. Add options to s_client and s_server
to support them.
[Steve Henson]
*) New function SSL_certs_clear() to delete all references to certificates
from an SSL structure. Before this once a certificate had been added
it couldn't be removed.
[Steve Henson]
*) Integrate hostname, email address and IP address checking with certificate
verification. New verify options supporting checking in opensl utility.
[Steve Henson]
*) Fixes and wildcard matching support to hostname and email checking
functions. Add manual page.
[Florian Weimer (Red Hat Product Security Team)]
*) New functions to check a hostname email or IP address against a
certificate. Add options x509 utility to print results of checks against
a certificate.
[Steve Henson]
*) Fix OCSP checking.
[Rob Stradling <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 perfomance) FIPS implementations outside FIPS mode.
[Steve Henson]
*) Transparently support X9.42 DH parameters when calling
PEM_read_bio_DHparameters. This means existing applications can handle
the new parameter format automatically.
[Steve Henson]
*) Initial experimental support for X9.42 DH parameter format: mainly
to support use of 'q' parameter for RFC5114 parameters.
[Steve Henson]
*) Add DH parameters from RFC5114 including test data to dhtest.
[Steve Henson]
*) Support for automatic EC temporary key parameter selection. If enabled
the most preferred EC parameters are automatically used instead of
hardcoded fixed parameters. Now a server just has to call:
SSL_CTX_set_ecdh_auto(ctx, 1) and the server will automatically
support ECDH and use the most appropriate parameters.
[Steve Henson]
*) Enhance and tidy EC curve and point format TLS extension code. Use
static structures instead of allocation if default values are used.
New ctrls to set curves we wish to support and to retrieve shared curves.
Print out shared curves in s_server. New options to s_server and s_client
to set list of supported curves.
[Steve Henson]
*) New ctrls to retrieve supported signature algorithms and
supported curve values as an array of NIDs. Extend openssl utility
to print out received values.
[Steve Henson]
*) Add new APIs EC_curve_nist2nid and EC_curve_nid2nist which convert
between NIDs and the more common NIST names such as "P-256". Enhance
ecparam utility and ECC method to recognise the NIST names for curves.
[Steve Henson]
*) Enhance SSL/TLS certificate chain handling to support different
chains for each certificate instead of one chain in the parent SSL_CTX.
[Steve Henson]
*) Support for fixed DH ciphersuite client authentication: where both
server and client use DH certificates with common parameters.
[Steve Henson]
*) Support for fixed DH ciphersuites: those requiring DH server
certificates.
[Steve Henson]
*) New function i2d_re_X509_tbs for re-encoding the TBS portion of
the certificate.
Note: Related 1.0.2-beta specific macros X509_get_cert_info,
X509_CINF_set_modified, X509_CINF_get_issuer, X509_CINF_get_extensions and
X509_CINF_get_signature were reverted post internal team review.
Changes between 1.0.1k and 1.0.1l [15 Jan 2015]
*) Build fixes for the Windows and OpenVMS platforms
[Matt Caswell and Richard Levitte]
Changes between 1.0.1j and 1.0.1k [8 Jan 2015]
*) Fix DTLS segmentation fault in dtls1_get_record. A carefully crafted DTLS
message can cause a segmentation fault in OpenSSL due to a NULL pointer
dereference. This could lead to a Denial Of Service attack. Thanks to
Markus Stenberg of Cisco Systems, Inc. for reporting this issue.
(CVE-2014-3571)
[Steve Henson]
*) Fix DTLS memory leak in dtls1_buffer_record. A memory leak can occur in the
dtls1_buffer_record function under certain conditions. In particular this
could occur if an attacker sent repeated DTLS records with the same
sequence number but for the next epoch. The memory leak could be exploited
by an attacker in a Denial of Service attack through memory exhaustion.
Thanks to Chris Mueller for reporting this issue.
(CVE-2015-0206)
[Matt Caswell]
*) Fix issue where no-ssl3 configuration sets method to NULL. When openssl is
built with the no-ssl3 option and a SSL v3 ClientHello is received the ssl
method would be set to NULL which could later result in a NULL pointer
dereference. Thanks to Frank Schmirler for reporting this issue.
(CVE-2014-3569)
[Kurt Roeckx]
*) Abort handshake if server key exchange message is omitted for ephemeral
ECDH ciphersuites.
Thanks to Karthikeyan Bhargavan of the PROSECCO team at INRIA for
reporting this issue.
(CVE-2014-3572)
[Steve Henson]
*) Remove non-export ephemeral RSA code on client and server. This code
violated the TLS standard by allowing the use of temporary RSA keys in
non-export ciphersuites and could be used by a server to effectively
downgrade the RSA key length used to a value smaller than the server
certificate. Thanks for Karthikeyan Bhargavan of the PROSECCO team at
INRIA or reporting this issue.
(CVE-2015-0204)
[Steve Henson]
*) Fixed issue where DH client certificates are accepted without verification.
An OpenSSL server will accept a DH certificate for client authentication
without the certificate verify message. This effectively allows a client to
authenticate without the use of a private key. This only affects servers
which trust a client certificate authority which issues certificates
containing DH keys: these are extremely rare and hardly ever encountered.
Thanks for Karthikeyan Bhargavan of the PROSECCO team at INRIA or reporting
this issue.
(CVE-2015-0205)
[Steve Henson]
*) Ensure that the session ID context of an SSL is updated when its
SSL_CTX is updated via SSL_set_SSL_CTX.
The session ID context is typically set from the parent SSL_CTX,
and can vary with the CTX.
[Adam Langley]
*) Fix various certificate fingerprint issues.
By using non-DER or invalid encodings outside the signed portion of a
certificate the fingerprint can be changed without breaking the signature.
Although no details of the signed portion of the certificate can be changed
this can cause problems with some applications: e.g. those using the
certificate fingerprint for blacklists.
1. Reject signatures with non zero unused bits.
If the BIT STRING containing the signature has non zero unused bits reject
the signature. All current signature algorithms require zero unused bits.
2. Check certificate algorithm consistency.
Check the AlgorithmIdentifier inside TBS matches the one in the
certificate signature. NB: this will result in signature failure
errors for some broken certificates.
Thanks to Konrad Kraszewski from Google for reporting this issue.
3. Check DSA/ECDSA signatures use DER.
Reencode DSA/ECDSA signatures and compare with the original received
signature. Return an error if there is a mismatch.
This will reject various cases including garbage after signature
(thanks to Antti Karjalainen and Tuomo Untinen from the Codenomicon CROSS
program for discovering this case) and use of BER or invalid ASN.1 INTEGERs
(negative or with leading zeroes).
Further analysis was conducted and fixes were developed by Stephen Henson
of the OpenSSL core team.
(CVE-2014-8275)
[Steve Henson]
*) Correct Bignum squaring. Bignum squaring (BN_sqr) may produce incorrect
results on some platforms, including x86_64. This bug occurs at random
with a very low probability, and is not known to be exploitable in any
way, though its exact impact is difficult to determine. Thanks to Pieter
Wuille (Blockstream) who reported this issue and also suggested an initial
fix. Further analysis was conducted by the OpenSSL development team and
Adam Langley of Google. The final fix was developed by Andy Polyakov of
the OpenSSL core team.
(CVE-2014-3570)
[Andy Polyakov]
*) Do not resume sessions on the server if the negotiated protocol
version does not match the session's version. Resuming with a different
version, while not strictly forbidden by the RFC, is of questionable
sanity and breaks all known clients.
[David Benjamin, Emilia Käsper]
*) Tighten handling of the ChangeCipherSpec (CCS) message: reject
early CCS messages during renegotiation. (Note that because
renegotiation is encrypted, this early CCS was not exploitable.)
[Emilia Käsper]
*) Tighten client-side session ticket handling during renegotiation:
ensure that the client only accepts a session ticket if the server sends
the extension anew in the ServerHello. Previously, a TLS client would
reuse the old extension state and thus accept a session ticket if one was
announced in the initial ServerHello.
Similarly, ensure that the client requires a session ticket if one
was advertised in the ServerHello. Previously, a TLS client would
ignore a missing NewSessionTicket message.
[Emilia Käsper]
Changes between 1.0.1i and 1.0.1j [15 Oct 2014]
*) SRTP Memory Leak.
A flaw in the DTLS SRTP extension parsing code allows an attacker, who
sends a carefully crafted handshake message, to cause OpenSSL to fail
to free up to 64k of memory causing a memory leak. This could be
exploited in a Denial Of Service attack. This issue affects OpenSSL
1.0.1 server implementations for both SSL/TLS and DTLS regardless of
whether SRTP is used or configured. Implementations of OpenSSL that
have been compiled with OPENSSL_NO_SRTP defined are not affected.
The fix was developed by the OpenSSL team.
(CVE-2014-3513)
[OpenSSL team]
*) Session Ticket Memory Leak.
When an OpenSSL SSL/TLS/DTLS server receives a session ticket the
integrity of that ticket is first verified. In the event of a session
ticket integrity check failing, OpenSSL will fail to free memory
causing a memory leak. By sending a large number of invalid session
tickets an attacker could exploit this issue in a Denial Of Service
attack.
(CVE-2014-3567)
[Steve Henson]
*) Build option no-ssl3 is incomplete.
When OpenSSL is configured with "no-ssl3" as a build option, servers
could accept and complete a SSL 3.0 handshake, and clients could be
configured to send them.
(CVE-2014-3568)
[Akamai and the OpenSSL team]
*) Add support for TLS_FALLBACK_SCSV.
Client applications doing fallback retries should call
SSL_set_mode(s, SSL_MODE_SEND_FALLBACK_SCSV).
(CVE-2014-3566)
[Adam Langley, Bodo Moeller]
*) Add additional DigestInfo checks.
Reencode DigestInto in DER and check against the original when
verifying RSA signature: this will reject any improperly encoded
DigestInfo structures.
Note: this is a precautionary measure and no attacks are currently known.
[Steve Henson]
Changes between 1.0.1h and 1.0.1i [6 Aug 2014]
*) Fix SRP buffer overrun vulnerability. Invalid parameters passed to the
SRP code can be overrun an internal buffer. Add sanity check that
g, A, B < N to SRP code.
Thanks to Sean Devlin and Watson Ladd of Cryptography Services, NCC
Group for discovering this issue.
(CVE-2014-3512)
[Steve Henson]
*) A flaw in the OpenSSL SSL/TLS server code causes the server to negotiate
TLS 1.0 instead of higher protocol versions when the ClientHello message
is badly fragmented. This allows a man-in-the-middle attacker to force a
downgrade to TLS 1.0 even if both the server and the client support a
higher protocol version, by modifying the client's TLS records.
Thanks to David Benjamin and Adam Langley (Google) for discovering and
researching this issue.
(CVE-2014-3511)
[David Benjamin]
*) OpenSSL DTLS clients enabling anonymous (EC)DH ciphersuites are subject
to a denial of service attack. A malicious server can crash the client
with a null pointer dereference (read) by specifying an anonymous (EC)DH
ciphersuite and sending carefully crafted handshake messages.
Thanks to Felix Gröbert (Google) for discovering and researching this
issue.
(CVE-2014-3510)
[Emilia Käsper]
*) By sending carefully crafted DTLS packets an attacker could cause openssl
to leak memory. This can be exploited through a Denial of Service attack.
Thanks to Adam Langley for discovering and researching this issue.
(CVE-2014-3507)
[Adam Langley]
*) An attacker can force openssl to consume large amounts of memory whilst
processing DTLS handshake messages. This can be exploited through a
Denial of Service attack.
Thanks to Adam Langley for discovering and researching this issue.
(CVE-2014-3506)
[Adam Langley]
*) An attacker can force an error condition which causes openssl to crash
whilst processing DTLS packets due to memory being freed twice. This
can be exploited through a Denial of Service attack.
Thanks to Adam Langley and Wan-Teh Chang for discovering and researching
this issue.
(CVE-2014-3505)
[Adam Langley]
*) If a multithreaded client connects to a malicious server using a resumed
session and the server sends an ec point format extension it could write
up to 255 bytes to freed memory.
Thanks to Gabor Tyukasz (LogMeIn Inc) for discovering and researching this
issue.
(CVE-2014-3509)
[Gabor Tyukasz]
*) A malicious server can crash an OpenSSL client with a null pointer
dereference (read) by specifying an SRP ciphersuite even though it was not
properly negotiated with the client. This can be exploited through a
Denial of Service attack.
Thanks to Joonas Kuorilehto and Riku Hietamäki (Codenomicon) for
discovering and researching this issue.
(CVE-2014-5139)
[Steve Henson]
*) A flaw in OBJ_obj2txt may cause pretty printing functions such as
X509_name_oneline, X509_name_print_ex et al. to leak some information
from the stack. Applications may be affected if they echo pretty printing
output to the attacker.
Thanks to Ivan Fratric (Google) for discovering this issue.
(CVE-2014-3508)
[Emilia Käsper, and Steve Henson]
*) Fix ec_GFp_simple_points_make_affine (thus, EC_POINTs_mul etc.)
for corner cases. (Certain input points at infinity could lead to
bogus results, with non-infinity inputs mapped to infinity too.)
[Bodo Moeller]
Changes between 1.0.1g and 1.0.1h [5 Jun 2014]
*) Fix for SSL/TLS MITM flaw. An attacker using a carefully crafted
handshake can force the use of weak keying material in OpenSSL
SSL/TLS clients and servers.
Thanks to KIKUCHI Masashi (Lepidum Co. Ltd.) for discovering and
researching this issue. (CVE-2014-0224)
[KIKUCHI Masashi, Steve Henson]
*) Fix DTLS recursion flaw. By sending an invalid DTLS handshake to an
OpenSSL DTLS client the code can be made to recurse eventually crashing
in a DoS attack.
Thanks to Imre Rad (Search-Lab Ltd.) for discovering this issue.
(CVE-2014-0221)
[Imre Rad, Steve Henson]
*) Fix DTLS invalid fragment vulnerability. A buffer overrun attack can
be triggered by sending invalid DTLS fragments to an OpenSSL DTLS
client or server. This is potentially exploitable to run arbitrary
code on a vulnerable client or server.
Thanks to Jüri Aedla for reporting this issue. (CVE-2014-0195)
[Jüri Aedla, Steve Henson]
*) Fix bug in TLS code where clients enable anonymous ECDH ciphersuites
are subject to a denial of service attack.
Thanks to Felix Gröbert and Ivan Fratric at Google for discovering
this issue. (CVE-2014-3470)
[Felix Gröbert, Ivan Fratric, Steve Henson]
*) Harmonize version and its documentation. -f flag is used to display
compilation flags.
[mancha <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>]
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 disablng
TLS 1.1 also. Fix this by changing the value of SSL_OP_NO_TLSv1_1 to
0x10000000L Any application which was previously compiled against
OpenSSL 1.0.1 or 1.0.1a headers and which cares about SSL_OP_NO_TLSv1_1
will need to be recompiled as a result. Letting be results in
inability to disable specifically TLS 1.1 and in client context,
in unlike event, limit maximum offered version to TLS 1.0 [see below].
[Steve Henson]
*) In order to ensure interoperabilty SSL_OP_NO_protocolX does not
disable just protocol X, but all protocols above X *if* there are
protocols *below* X still enabled. In more practical terms it means
that if application wants to disable TLS1.0 in favor of TLS1.1 and
above, it's not sufficient to pass SSL_OP_NO_TLSv1, one has to pass
SSL_OP_NO_TLSv1|SSL_OP_NO_SSLv3|SSL_OP_NO_SSLv2. This applies to
client side.
[Andy Polyakov]
Changes between 1.0.1 and 1.0.1a [19 Apr 2012]
*) Check for potentially exploitable overflows in asn1_d2i_read_bio
BUF_mem_grow and BUF_mem_grow_clean. Refuse attempts to shrink buffer
in CRYPTO_realloc_clean.
Thanks to Tavis Ormandy, Google Security Team, for discovering this
issue and to Adam Langley <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 pemitted
client version in client hello, this should keep such servers happy
and still work with previous versions of OpenSSL.
[Steve Henson]
*) Add support for TLS/DTLS heartbeats.
[Robin Seggelmann <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 instad of ssize_t which isn't available on
all platforms. Move ssize_t definition from e_os.h to the public
header file e_os2.h as it now appears in public header file cms.h
[Steve Henson]
*) New -sigopt option to the ca, req and x509 utilities. Additional
signature parameters can be passed using this option and in
particular PSS.
[Steve Henson]
*) Add RSA PSS signing function. This will generate and set the
appropriate AlgorithmIdentifiers for PSS based on those in the
corresponding EVP_MD_CTX structure. No application support yet.
[Steve Henson]
*) Support for companion algorithm specific ASN1 signing routines.
New function ASN1_item_sign_ctx() signs a pre-initialised
EVP_MD_CTX structure and sets AlgorithmIdentifiers based on
the appropriate parameters.
[Steve Henson]
*) Add new algorithm specific ASN1 verification initialisation function
to EVP_PKEY_ASN1_METHOD: this is not in EVP_PKEY_METHOD since the ASN1
handling will be the same no matter what EVP_PKEY_METHOD is used.
Add a PSS handler to support verification of PSS signatures: checked
against a number of sample certificates.
[Steve Henson]
*) Add signature printing for PSS. Add PSS OIDs.
[Steve Henson, Martin Kaiser <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 inlclude GCM and
add a special AESGCM string for GCM only.
[Steve Henson]
*) Expand range of ctrls for AES GCM. Permit setting invocation
field on decrypt and retrieval of invocation field only on encrypt.
[Steve Henson]
*) Add HMAC ECC ciphersuites from RFC5289. Include SHA384 PRF support.
As required by RFC5289 these ciphersuites cannot be used if for
versions of TLS earlier than 1.2.
[Steve Henson]
*) For FIPS capable OpenSSL interpret a NULL default public key method
as unset and return the appopriate default but do *not* set the default.
This means we can return the appopriate method in applications that
swicth between FIPS and non-FIPS modes.
[Steve Henson]
*) Redirect HMAC and CMAC operations to FIPS module in FIPS mode. If an
ENGINE is used then we cannot handle that in the FIPS module so we
keep original code iff non-FIPS operations are allowed.
[Steve Henson]
*) Add -attime option to openssl utilities.
[Peter Eckersley <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]
- *) Add SRP support.
- [Tom Wu <tjw@cs.stanford.edu> and Ben Laurie]
+ *) 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]
Changes between 1.0.0g and 1.0.0h [12 Mar 2012]
*) Fix MMA (Bleichenbacher's attack on PKCS #1 v1.5 RSA padding) weakness
in CMS and PKCS7 code. When RSA decryption fails use a random key for
content decryption and always return the same error. Note: this attack
needs on average 2^20 messages so it only affects automated senders. The
old behaviour can be reenabled in the CMS code by setting the
CMS_DEBUG_DECRYPT flag: this is useful for debugging and testing where
an MMA defence is not necessary.
Thanks to Ivan Nestlerode <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 apps tidying load_certs() too. Add option
to verify utility to allow additional CRLs to be included.
[Steve Henson]
*) Update OCSP request code to permit adding custom headers to the request:
some responders need this.
[Steve Henson]
*) The function EVP_PKEY_sign() returns <=0 on error: check return code
correctly.
[Julia Lawall <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 wont
see this because it requires extended CRL support which is off by
default.
This work was sponsored by Google.
[Steve Henson]
*) Support for freshest CRL extension.
This work was sponsored by Google.
[Steve Henson]
*) Initial indirect CRL support. Currently only supported in the CRLs
passed directly and not via lookup. Process certificate issuer
CRL entry extension and lookup CRL entries by bother issuer name
and serial number. Check and process CRL issuer entry in IDP extension.
This work was sponsored by Google.
[Steve Henson]
*) Add support for distinct certificate and CRL paths. The CRL issuer
certificate is validated separately in this case. Only enabled if
an extended CRL support flag is set: this flag will enable additional
CRL functionality in future.
This work was sponsored by Google.
[Steve Henson]
*) Add support for policy mappings extension.
This work was sponsored by Google.
[Steve Henson]
*) Fixes to pathlength constraint, self issued certificate handling,
policy processing to align with RFC3280 and PKITS tests.
This work was sponsored by Google.
[Steve Henson]
*) Support for name constraints certificate extension. DN, email, DNS
and URI types are currently supported.
This work was sponsored by Google.
[Steve Henson]
*) To cater for systems that provide a pointer-based thread ID rather
than numeric, deprecate the current numeric thread ID mechanism and
replace it with a structure and associated callback type. This
mechanism allows a numeric "hash" to be extracted from a thread ID in
either case, and on platforms where pointers are larger than 'long',
mixing is done to help ensure the numeric 'hash' is usable even if it
can't be guaranteed unique. The default mechanism is to use "&errno"
as a pointer-based thread ID to distinguish between threads.
Applications that want to provide their own thread IDs should now use
CRYPTO_THREADID_set_callback() to register a callback that will call
either CRYPTO_THREADID_set_numeric() or CRYPTO_THREADID_set_pointer().
Note that ERR_remove_state() is now deprecated, because it is tied
to the assumption that thread IDs are numeric. ERR_remove_state(0)
to free the current thread's error state should be replaced by
ERR_remove_thread_state(NULL).
(This new approach replaces the functions CRYPTO_set_idptr_callback(),
CRYPTO_get_idptr_callback(), and CRYPTO_thread_idptr() that existed in
OpenSSL 0.9.9-dev between June 2006 and August 2008. Also, if an
application was previously providing a numeric thread callback that
was inappropriate for distinguishing threads, then uniqueness might
have been obtained with &errno that happened immediately in the
intermediate development versions of OpenSSL; this is no longer the
case, the numeric thread callback will now override the automatic use
of &errno.)
[Geoff Thorpe, with help from Bodo Moeller]
*) Initial support for different CRL issuing certificates. This covers a
simple case where the self issued certificates in the chain exist and
the real CRL issuer is higher in the existing chain.
This work was sponsored by Google.
[Steve Henson]
*) Removed effectively defunct crypto/store from the build.
[Ben Laurie]
*) Revamp of STACK to provide stronger type-checking. Still to come:
TXT_DB, bsearch(?), OBJ_bsearch, qsort, CRYPTO_EX_DATA, ASN1_VALUE,
ASN1_STRING, CONF_VALUE.
[Ben Laurie]
*) Add a new SSL_MODE_RELEASE_BUFFERS mode flag to release unused buffer
RAM on SSL connections. This option can save about 34k per idle SSL.
[Nick Mathewson]
*) Revamp of LHASH to provide stronger type-checking. Still to come:
STACK, TXT_DB, bsearch, qsort.
[Ben Laurie]
*) Initial support for Cryptographic Message Syntax (aka CMS) based
on RFC3850, RFC3851 and RFC3852. New cms directory and cms utility,
support for data, signedData, compressedData, digestedData and
encryptedData, envelopedData types included. Scripts to check against
RFC4134 examples draft and interop and consistency checks of many
content types and variants.
[Steve Henson]
*) Add options to enc utility to support use of zlib compression BIO.
[Steve Henson]
*) Extend mk1mf to support importing of options and assembly language
files from Configure script, currently only included in VC-WIN32.
The assembly language rules can now optionally generate the source
files from the associated perl scripts.
[Steve Henson]
*) Implement remaining functionality needed to support GOST ciphersuites.
Interop testing has been performed using CryptoPro implementations.
[Victor B. Wagner <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 interal copy of the length-'len' string at 'src', and will
return non-zero for success.
To get more control and flexibility, provide a callback function
by using
SSL_CTX_set_tlsext_opaque_prf_input_callback(ctx, cb)
SSL_CTX_set_tlsext_opaque_prf_input_callback_arg(ctx, arg)
where
int (*cb)(SSL *, void *peerinput, size_t len, void *arg);
void *arg;
Callback function 'cb' will be called in handshakes, and is
expected to use SSL_set_tlsext_opaque_prf_input() as appropriate.
Argument 'arg' is for application purposes (the value as given to
SSL_CTX_set_tlsext_opaque_prf_input_callback_arg() will directly
be provided to the callback function). The callback function
has to return non-zero to report success: usually 1 to use opaque
PRF input just if possible, or 2 to enforce use of the opaque PRF
input. In the latter case, the library will abort the handshake
if opaque PRF input is not successfully negotiated.
Arguments 'peerinput' and 'len' given to the callback function
will always be NULL and 0 in the case of a client. A server will
see the client's opaque PRF input through these variables if
available (NULL and 0 otherwise). Note that if the server
provides an opaque PRF input, the length must be the same as the
length of the client's opaque PRF input.
Note that the callback function will only be called when creating
a new session (session resumption can resume whatever was
previously negotiated), and will not be called in SSL 2.0
handshakes; thus, SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv2) or
SSL_set_options(ssl, SSL_OP_NO_SSLv2) is especially recommended
for applications that need to enforce opaque PRF input.
[Bodo Moeller]
*) Update ssl code to support digests other than SHA1+MD5 for handshake
MAC.
[Victor B. Wagner <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 paramaters such as X9.31 or PSS in the dgst
utility.
[Steve Henson]
*) Change ssl_cipher_apply_rule(), the internal function that does
the work each time a ciphersuite string requests enabling
("foo+bar"), moving ("+foo+bar"), disabling ("-foo+bar", or
removing ("!foo+bar") a class of ciphersuites: Now it maintains
the order of disabled ciphersuites such that those ciphersuites
that most recently went from enabled to disabled not only stay
in order with respect to each other, but also have higher priority
than other disabled ciphersuites the next time ciphersuites are
enabled again.
This means that you can now say, e.g., "PSK:-PSK:HIGH" to enable
the same ciphersuites as with "HIGH" alone, but in a specific
order where the PSK ciphersuites come first (since they are the
most recently disabled ciphersuites when "HIGH" is parsed).
Also, change ssl_create_cipher_list() (using this new
funcionality) such that between otherwise identical
cihpersuites, ephemeral ECDH is preferred over ephemeral DH in
the default order.
[Bodo Moeller]
*) Change ssl_create_cipher_list() so that it automatically
arranges the ciphersuites in reasonable order before starting
to process the rule string. Thus, the definition for "DEFAULT"
(SSL_DEFAULT_CIPHER_LIST) now is just "ALL:!aNULL:!eNULL", but
remains equivalent to "AES:ALL:!aNULL:!eNULL:+aECDH:+kRSA:+RC4:@STRENGTH".
This makes it much easier to arrive at a reasonable default order
in applications for which anonymous ciphers are OK (meaning
that you can't actually use DEFAULT).
[Bodo Moeller; suggested by Victor Duchovni]
*) Split the SSL/TLS algorithm mask (as used for ciphersuite string
processing) into multiple integers instead of setting
"SSL_MKEY_MASK" bits, "SSL_AUTH_MASK" bits, "SSL_ENC_MASK",
"SSL_MAC_MASK", and "SSL_SSL_MASK" bits all in a single integer.
(These masks as well as the individual bit definitions are hidden
away into the non-exported interface ssl/ssl_locl.h, so this
change to the definition of the SSL_CIPHER structure shouldn't
affect applications.) This give us more bits for each of these
categories, so there is no longer a need to coagulate AES128 and
AES256 into a single algorithm bit, and to coagulate Camellia128
and Camellia256 into a single algorithm bit, which has led to all
kinds of kludges.
Thus, among other things, the kludge introduced in 0.9.7m and
0.9.8e for masking out AES256 independently of AES128 or masking
out Camellia256 independently of AES256 is not needed here in 0.9.9.
With the change, we also introduce new ciphersuite aliases that
so far were missing: "AES128", "AES256", "CAMELLIA128", and
"CAMELLIA256".
[Bodo Moeller]
*) Add support for dsa-with-SHA224 and dsa-with-SHA256.
Use the leftmost N bytes of the signature input if the input is
larger than the prime q (with N being the size in bytes of q).
[Nils Larsch]
*) Very *very* experimental PKCS#7 streaming encoder support. Nothing uses
it yet and it is largely untested.
[Steve Henson]
*) Add support for the ecdsa-with-SHA224/256/384/512 signature types.
[Nils Larsch]
*) Initial incomplete changes to avoid need for function casts in OpenSSL
some compilers (gcc 4.2 and later) reject their use. Safestack is
reimplemented. Update ASN1 to avoid use of legacy functions.
[Steve Henson]
*) Win32/64 targets are linked with Winsock2.
[Andy Polyakov]
*) Add an X509_CRL_METHOD structure to allow CRL processing to be redirected
to external functions. This can be used to increase CRL handling
efficiency especially when CRLs are very large by (for example) storing
the CRL revoked certificates in a database.
[Steve Henson]
*) Overhaul of by_dir code. Add support for dynamic loading of CRLs so
new CRLs added to a directory can be used. New command line option
-verify_return_error to s_client and s_server. This causes real errors
to be returned by the verify callback instead of carrying on no matter
what. This reflects the way a "real world" verify callback would behave.
[Steve Henson]
*) GOST engine, supporting several GOST algorithms and public key formats.
Kindly donated by Cryptocom.
[Cryptocom]
*) Partial support for Issuing Distribution Point CRL extension. CRLs
partitioned by DP are handled but no indirect CRL or reason partitioning
(yet). Complete overhaul of CRL handling: now the most suitable CRL is
selected via a scoring technique which handles IDP and AKID in CRLs.
[Steve Henson]
*) New X509_STORE_CTX callbacks lookup_crls() and lookup_certs() which
will ultimately be used for all verify operations: this will remove the
X509_STORE dependency on certificate verification and allow alternative
lookup methods. X509_STORE based implementations of these two callbacks.
[Steve Henson]
*) Allow multiple CRLs to exist in an X509_STORE with matching issuer names.
Modify get_crl() to find a valid (unexpired) CRL if possible.
[Steve Henson]
*) New function X509_CRL_match() to check if two CRLs are identical. Normally
this would be called X509_CRL_cmp() but that name is already used by
a function that just compares CRL issuer names. Cache several CRL
extensions in X509_CRL structure and cache CRLDP in X509.
[Steve Henson]
*) Store a "canonical" representation of X509_NAME structure (ASN1 Name)
this maps equivalent X509_NAME structures into a consistent structure.
Name comparison can then be performed rapidly using memcmp().
[Steve Henson]
*) Non-blocking OCSP request processing. Add -timeout option to ocsp
utility.
[Steve Henson]
*) Allow digests to supply their own micalg string for S/MIME type using
the ctrl EVP_MD_CTRL_MICALG.
[Steve Henson]
*) During PKCS7 signing pass the PKCS7 SignerInfo structure to the
EVP_PKEY_METHOD before and after signing via the EVP_PKEY_CTRL_PKCS7_SIGN
ctrl. It can then customise the structure before and/or after signing
if necessary.
[Steve Henson]
*) New function OBJ_add_sigid() to allow application defined signature OIDs
to be added to OpenSSLs internal tables. New function OBJ_sigid_free()
to free up any added signature OIDs.
[Steve Henson]
*) New functions EVP_CIPHER_do_all(), EVP_CIPHER_do_all_sorted(),
EVP_MD_do_all() and EVP_MD_do_all_sorted() to enumerate internal
digest and cipher tables. New options added to openssl utility:
list-message-digest-algorithms and list-cipher-algorithms.
[Steve Henson]
*) Change the array representation of binary polynomials: the list
of degrees of non-zero coefficients is now terminated with -1.
Previously it was terminated with 0, which was also part of the
value; thus, the array representation was not applicable to
polynomials where t^0 has coefficient zero. This change makes
the array representation useful in a more general context.
[Douglas Stebila]
*) Various modifications and fixes to SSL/TLS cipher string
handling. For ECC, the code now distinguishes between fixed ECDH
with RSA certificates on the one hand and with ECDSA certificates
on the other hand, since these are separate ciphersuites. The
unused code for Fortezza ciphersuites has been removed.
For consistency with EDH, ephemeral ECDH is now called "EECDH"
(not "ECDHE"). For consistency with the code for DH
certificates, use of ECDH certificates is now considered ECDH
authentication, not RSA or ECDSA authentication (the latter is
merely the CA's signing algorithm and not actively used in the
protocol).
The temporary ciphersuite alias "ECCdraft" is no longer
available, and ECC ciphersuites are no longer excluded from "ALL"
and "DEFAULT". The following aliases now exist for RFC 4492
ciphersuites, most of these by analogy with the DH case:
kECDHr - ECDH cert, signed with RSA
kECDHe - ECDH cert, signed with ECDSA
kECDH - ECDH cert (signed with either RSA or ECDSA)
kEECDH - ephemeral ECDH
ECDH - ECDH cert or ephemeral ECDH
aECDH - ECDH cert
aECDSA - ECDSA cert
ECDSA - ECDSA cert
AECDH - anonymous ECDH
EECDH - non-anonymous ephemeral ECDH (equivalent to "kEECDH:-AECDH")
[Bodo Moeller]
*) Add additional S/MIME capabilities for AES and GOST ciphers if supported.
Use correct micalg parameters depending on digest(s) in signed message.
[Steve Henson]
*) Add engine support for EVP_PKEY_ASN1_METHOD. Add functions to process
an ENGINE asn1 method. Support ENGINE lookups in the ASN1 code.
[Steve Henson]
*) Initial engine support for EVP_PKEY_METHOD. New functions to permit
an engine to register a method. Add ENGINE lookups for methods and
functional reference processing.
[Steve Henson]
*) New functions EVP_Digest{Sign,Verify)*. These are enchance versions of
EVP_{Sign,Verify}* which allow an application to customise the signature
process.
[Steve Henson]
*) New -resign option to smime utility. This adds one or more signers
to an existing PKCS#7 signedData structure. Also -md option to use an
alternative message digest algorithm for signing.
[Steve Henson]
*) Tidy up PKCS#7 routines and add new functions to make it easier to
create PKCS7 structures containing multiple signers. Update smime
application to support multiple signers.
[Steve Henson]
*) New -macalg option to pkcs12 utility to allow setting of an alternative
digest MAC.
[Steve Henson]
*) Initial support for PKCS#5 v2.0 PRFs other than default SHA1 HMAC.
Reorganize PBE internals to lookup from a static table using NIDs,
add support for HMAC PBE OID translation. Add a EVP_CIPHER ctrl:
EVP_CTRL_PBE_PRF_NID this allows a cipher to specify an alternative
PRF which will be automatically used with PBES2.
[Steve Henson]
*) Replace the algorithm specific calls to generate keys in "req" with the
new API.
[Steve Henson]
*) Update PKCS#7 enveloped data routines to use new API. This is now
supported by any public key method supporting the encrypt operation. A
ctrl is added to allow the public key algorithm to examine or modify
the PKCS#7 RecipientInfo structure if it needs to: for RSA this is
a no op.
[Steve Henson]
*) Add a ctrl to asn1 method to allow a public key algorithm to express
a default digest type to use. In most cases this will be SHA1 but some
algorithms (such as GOST) need to specify an alternative digest. The
return value indicates how strong the prefernce is 1 means optional and
2 is mandatory (that is it is the only supported type). Modify
ASN1_item_sign() to accept a NULL digest argument to indicate it should
use the default md. Update openssl utilities to use the default digest
type for signing if it is not explicitly indicated.
[Steve Henson]
*) Use OID cross reference table in ASN1_sign() and ASN1_verify(). New
EVP_MD flag EVP_MD_FLAG_PKEY_METHOD_SIGNATURE. This uses the relevant
signing method from the key type. This effectively removes the link
between digests and public key types.
[Steve Henson]
*) Add an OID cross reference table and utility functions. Its purpose is to
translate between signature OIDs such as SHA1WithrsaEncryption and SHA1,
rsaEncryption. This will allow some of the algorithm specific hackery
needed to use the correct OID to be removed.
[Steve Henson]
*) Remove algorithm specific dependencies when setting PKCS7_SIGNER_INFO
structures for PKCS7_sign(). They are now set up by the relevant public
key ASN1 method.
[Steve Henson]
*) Add provisional EC pkey method with support for ECDSA and ECDH.
[Steve Henson]
*) Add support for key derivation (agreement) in the API, DH method and
pkeyutl.
[Steve Henson]
*) Add DSA pkey method and DH pkey methods, extend DH ASN1 method to support
public and private key formats. As a side effect these add additional
command line functionality not previously available: DSA signatures can be
generated and verified using pkeyutl and DH key support and generation in
pkey, genpkey.
[Steve Henson]
*) BeOS support.
[Oliver Tappe <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 analagous to "genrsa" etc except it can
generate keys for any algorithm. Extend and update EVP_PKEY_METHOD to
support key and parameter generation and add initial key generation
functionality for RSA.
[Steve Henson]
*) Add functions for main EVP_PKEY_method operations. The undocumented
functions EVP_PKEY_{encrypt,decrypt} have been renamed to
EVP_PKEY_{encrypt,decrypt}_old.
[Steve Henson]
*) Initial definitions for EVP_PKEY_METHOD. This will be a high level public
key API, doesn't do much yet.
[Steve Henson]
*) New function EVP_PKEY_asn1_get0_info() to retrieve information about
public key algorithms. New option to openssl utility:
"list-public-key-algorithms" to print out info.
[Steve Henson]
*) Implement the Supported Elliptic Curves Extension for
ECC ciphersuites from draft-ietf-tls-ecc-12.txt.
[Douglas Stebila]
*) Don't free up OIDs in OBJ_cleanup() if they are in use by EVP_MD or
EVP_CIPHER structures to avoid later problems in EVP_cleanup().
[Steve Henson]
*) New utilities pkey and pkeyparam. These are similar to algorithm specific
utilities such as rsa, dsa, dsaparam etc except they process any key
type.
[Steve Henson]
*) Transfer public key printing routines to EVP_PKEY_ASN1_METHOD. New
functions EVP_PKEY_print_public(), EVP_PKEY_print_private(),
EVP_PKEY_print_param() to print public key data from an EVP_PKEY
structure.
[Steve Henson]
*) Initial support for pluggable public key ASN1.
De-spaghettify the public key ASN1 handling. Move public and private
key ASN1 handling to a new EVP_PKEY_ASN1_METHOD structure. Relocate
algorithm specific handling to a single module within the relevant
algorithm directory. Add functions to allow (near) opaque processing
of public and private key structures.
[Steve Henson]
*) Implement the Supported Point Formats Extension for
ECC ciphersuites from draft-ietf-tls-ecc-12.txt.
[Douglas Stebila]
*) Add initial support for RFC 4279 PSK TLS ciphersuites. Add members
for the psk identity [hint] and the psk callback functions to the
SSL_SESSION, SSL and SSL_CTX structure.
New ciphersuites:
PSK-RC4-SHA, PSK-3DES-EDE-CBC-SHA, PSK-AES128-CBC-SHA,
PSK-AES256-CBC-SHA
New functions:
SSL_CTX_use_psk_identity_hint
SSL_get_psk_identity_hint
SSL_get_psk_identity
SSL_use_psk_identity_hint
[Mika Kousa and Pasi Eronen of Nokia Corporation]
*) Add RFC 3161 compliant time stamp request creation, response generation
and response verification functionality.
[Zoltán Glózik <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 unrecogninzed_name alert has to be sent, this by
default is a warning; it becomes fatal with the '-servername_fatal'
option.
[Peter Sylvester, Remy Allais, Christophe Renou]
*) Whirlpool hash implementation is added.
[Andy Polyakov]
*) BIGNUM code on 64-bit SPARCv9 targets is switched from bn(64,64) to
bn(64,32). Because of instruction set limitations it doesn't have
any negative impact on performance. This was done mostly in order
to make it possible to share assembler modules, such as bn_mul_mont
implementations, between 32- and 64-bit builds without hassle.
[Andy Polyakov]
*) Move code previously exiled into file crypto/ec/ec2_smpt.c
to ec2_smpl.c, and no longer require the OPENSSL_EC_BIN_PT_COMP
macro.
[Bodo Moeller]
*) New candidate for BIGNUM assembler implementation, bn_mul_mont,
dedicated Montgomery multiplication procedure, is introduced.
BN_MONT_CTX is modified to allow bn_mul_mont to reach for higher
"64-bit" performance on certain 32-bit targets.
[Andy Polyakov]
*) New option SSL_OP_NO_COMP to disable use of compression selectively
in SSL structures. New SSL ctrl to set maximum send fragment size.
Save memory by seeting the I/O buffer sizes dynamically instead of
using the maximum available value.
[Steve Henson]
*) New option -V for 'openssl ciphers'. This prints the ciphersuite code
in addition to the text details.
[Bodo Moeller]
*) Very, very preliminary EXPERIMENTAL support for printing of general
ASN1 structures. This currently produces rather ugly output and doesn't
handle several customised structures at all.
[Steve Henson]
*) Integrated support for PVK file format and some related formats such
as MS PUBLICKEYBLOB and PRIVATEKEYBLOB. Command line switches to support
these in the 'rsa' and 'dsa' utilities.
[Steve Henson]
*) Support for PKCS#1 RSAPublicKey format on rsa utility command line.
[Steve Henson]
*) Remove the ancient ASN1_METHOD code. This was only ever used in one
place for the (very old) "NETSCAPE" format certificates which are now
handled using new ASN1 code equivalents.
[Steve Henson]
*) Let the TLSv1_method() etc. functions return a 'const' SSL_METHOD
pointer and make the SSL_METHOD parameter in SSL_CTX_new,
SSL_CTX_set_ssl_version and SSL_set_ssl_method 'const'.
[Nils Larsch]
*) Modify CRL distribution points extension code to print out previously
unsupported fields. Enhance extension setting code to allow setting of
all fields.
[Steve Henson]
*) Add print and set support for Issuing Distribution Point CRL extension.
[Steve Henson]
*) Change 'Configure' script to enable Camellia by default.
[NTT]
Changes between 0.9.8m and 0.9.8n [24 Mar 2010]
*) When rejecting SSL/TLS records due to an incorrect version number, never
update s->server with a new major version number. As of
- OpenSSL 0.9.8m if 'short' is a 16-bit type,
- OpenSSL 0.9.8f if 'short' is longer than 16 bits,
the previous behavior could result in a read attempt at NULL when
receiving specific incorrect SSL/TLS records once record payload
protection is active. (CVE-2010-0740)
[Bodo Moeller, Adam Langley <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_wexpend() return values for failure. (CVE-2009-3245)
[Martin Olsson, Neel Mehta]
*) Fix X509_STORE locking: Every 'objs' access requires a lock (to
accommodate for stack sorting, always a write lock!).
[Bodo Moeller]
*) On some versions of WIN32 Heap32Next is very slow. This can cause
excessive delays in the RAND_poll(): over a minute. As a workaround
include a time check in the inner Heap32Next loop too.
[Steve Henson]
*) The code that handled flushing of data in SSL/TLS originally used the
BIO_CTRL_INFO ctrl to see if any data was pending first. This caused
the problem outlined in PR#1949. The fix suggested there however can
trigger problems with buggy BIO_CTRL_WPENDING (e.g. some versions
of Apache). So instead simplify the code to flush unconditionally.
This should be fine since flushing with no data to flush is a no op.
[Steve Henson]
*) Handle TLS versions 2.0 and later properly and correctly use the
highest version of TLS/SSL supported. Although TLS >= 2.0 is some way
off ancient servers have a habit of sticking around for a while...
[Steve Henson]
*) Modify compression code so it frees up structures without using the
ex_data callbacks. This works around a problem where some applications
call CRYPTO_cleanup_all_ex_data() before application exit (e.g. when
restarting) then use compression (e.g. SSL with compression) later.
This results in significant per-connection memory leaks and
has caused some security issues including CVE-2008-1678 and
CVE-2009-4355.
[Steve Henson]
*) Constify crypto/cast (i.e., <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 messege was buffered, even if the
sequence number made no sense and would be part of another handshake.
So only messages with sequence numbers less than 10 in advance will be
buffered. (CVE-2009-1378)
[Robin Seggelmann, discovered by Daniel Mentz]
*) Records are buffered if they arrive with a future epoch to be
processed after finishing the corresponding handshake. There is
currently no limitation to this buffer allowing an attacker to perform
a DOS attack with sending records with future epochs until there is no
memory left. This patch adds the pqueue_size() function to detemine
the size of a buffer and limits the record buffer to 100 entries.
(CVE-2009-1377)
[Robin Seggelmann, discovered by Daniel Mentz]
*) Keep a copy of frag->msg_header.frag_len so it can be used after the
parent structure is freed. (CVE-2009-1379)
[Daniel Mentz]
*) Handle non-blocking I/O properly in SSL_shutdown() call.
[Darryl Miles <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 transitition in s3_srvr.c and d1_srvr.c
(was using SSL3_ST_CW_CLNT_HELLO_B, should be ..._ST_SW_SRVR_...).
[Nagendra Modadugu]
*) The fix in 0.9.8c that supposedly got rid of unsafe
double-checked locking was incomplete for RSA blinding,
addressing just one layer of what turns out to have been
doubly unsafe triple-checked locking.
So now fix this for real by retiring the MONT_HELPER macro
in crypto/rsa/rsa_eay.c.
[Bodo Moeller; problem pointed out by Marius Schilder]
*) Various precautionary measures:
- Avoid size_t integer overflow in HASH_UPDATE (md32_common.h).
- Avoid a buffer overflow in d2i_SSL_SESSION() (ssl_asn1.c).
(NB: This would require knowledge of the secret session ticket key
to exploit, in which case you'd be SOL either way.)
- Change bn_nist.c so that it will properly handle input BIGNUMs
outside the expected range.
- Enforce the 'num' check in BN_div() (bn_div.c) for non-BN_DEBUG
builds.
[Neel Mehta, Bodo Moeller]
*) Allow engines to be "soft loaded" - i.e. optionally don't die if
the load fails. Useful for distros.
[Ben Laurie and the FreeBSD team]
*) Add support for Local Machine Keyset attribute in PKCS#12 files.
[Steve Henson]
*) Fix BN_GF2m_mod_arr() top-bit cleanup code.
[Huang Ying]
*) Expand ENGINE to support engine supplied SSL client certificate functions.
This work was sponsored by Logica.
[Steve Henson]
*) Add CryptoAPI ENGINE to support use of RSA and DSA keys held in Windows
keystores. Support for SSL/TLS client authentication too.
Not compiled unless enable-capieng specified to Configure.
This work was sponsored by Logica.
[Steve Henson]
*) Fix bug in X509_ATTRIBUTE creation: dont set attribute using
ASN1_TYPE_set1 if MBSTRING flag set. This bug would crash certain
attribute creation routines such as certifcate requests and PKCS#12
files.
[Steve Henson]
Changes between 0.9.8g and 0.9.8h [28 May 2008]
*) Fix flaw if 'Server Key exchange message' is omitted from a TLS
handshake which could lead to a cilent crash as found using the
Codenomicon TLS test suite (CVE-2008-1672)
[Steve Henson, Mark Cox]
*) Fix double free in TLS server name extensions which could lead to
a remote crash found by Codenomicon TLS test suite (CVE-2008-0891)
[Joe Orton]
*) Clear error queue in SSL_CTX_use_certificate_chain_file()
Clear the error queue to ensure that error entries left from
older function calls do not interfere with the correct operation.
[Lutz Jaenicke, Erik de Castro Lopo]
*) Remove root CA certificates of commercial CAs:
The OpenSSL project does not recommend any specific CA and does not
have any policy with respect to including or excluding any CA.
Therefore it does not make any sense to ship an arbitrary selection
of root CA certificates with the OpenSSL software.
[Lutz Jaenicke]
*) RSA OAEP patches to fix two separate invalid memory reads.
The first one involves inputs when 'lzero' is greater than
'SHA_DIGEST_LENGTH' (it would read about SHA_DIGEST_LENGTH bytes
before the beginning of from). The second one involves inputs where
the 'db' section contains nothing but zeroes (there is a one-byte
invalid read after the end of 'db').
[Ivan Nestlerode <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
implemention in the following ways:
Lack of EVP_PKEY_ASN1_METHOD means algorithm parameters have to be
hard coded.
Lack of BER streaming support means one pass streaming processing is
only supported if data is detached: setting the streaming flag is
ignored for embedded content.
CMS support is disabled by default and must be explicitly enabled
with the enable-cms configuration option.
[Steve Henson]
*) Update the GMP engine glue to do direct copies between BIGNUM and
mpz_t when openssl and GMP use the same limb size. Otherwise the
existing "conversion via a text string export" trick is still used.
[Paul Sheer <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 unrecogninzed_name alert has to be sent, this by
default is a warning; it becomes fatal with the '-servername_fatal'
option.
[Peter Sylvester, Remy Allais, Christophe Renou, Steve Henson]
*) Add AES and SSE2 assembly language support to VC++ build.
[Steve Henson]
*) Mitigate attack on final subtraction in Montgomery reduction.
[Andy Polyakov]
*) Fix crypto/ec/ec_mult.c to work properly with scalars of value 0
(which previously caused an internal error).
[Bodo Moeller]
*) Squeeze another 10% out of IGE mode when in != out.
[Ben Laurie]
*) AES IGE mode speedup.
[Dean Gaudet (Google)]
*) Add the Korean symmetric 128-bit cipher SEED (see
http://www.kisa.or.kr/kisa/seed/jsp/seed_eng.jsp) and
add SEED ciphersuites from RFC 4162:
TLS_RSA_WITH_SEED_CBC_SHA = "SEED-SHA"
TLS_DHE_DSS_WITH_SEED_CBC_SHA = "DHE-DSS-SEED-SHA"
TLS_DHE_RSA_WITH_SEED_CBC_SHA = "DHE-RSA-SEED-SHA"
TLS_DH_anon_WITH_SEED_CBC_SHA = "ADH-SEED-SHA"
To minimize changes between patchlevels in the OpenSSL 0.9.8
series, SEED remains excluded from compilation unless OpenSSL
is configured with 'enable-seed'.
[KISA, Bodo Moeller]
*) Mitigate branch prediction attacks, which can be practical if a
single processor is shared, allowing a spy process to extract
information. For detailed background information, see
http://eprint.iacr.org/2007/039 (O. Aciicmez, S. Gueron,
J.-P. Seifert, "New Branch Prediction Vulnerabilities in OpenSSL
and Necessary Software Countermeasures"). The core of the change
are new versions BN_div_no_branch() and
BN_mod_inverse_no_branch() of BN_div() and BN_mod_inverse(),
respectively, which are slower, but avoid the security-relevant
conditional branches. These are automatically called by BN_div()
and BN_mod_inverse() if the flag BN_FLG_CONSTTIME is set for one
of the input BIGNUMs. Also, BN_is_bit_set() has been changed to
remove a conditional branch.
BN_FLG_CONSTTIME is the new name for the previous
BN_FLG_EXP_CONSTTIME flag, since it now affects more than just
modular exponentiation. (Since OpenSSL 0.9.7h, setting this flag
in the exponent causes BN_mod_exp_mont() to use the alternative
implementation in BN_mod_exp_mont_consttime().) The old name
remains as a deprecated alias.
Similary, RSA_FLAG_NO_EXP_CONSTTIME is replaced by a more general
RSA_FLAG_NO_CONSTTIME flag since the RSA implementation now uses
constant-time implementations for more than just exponentiation.
Here too the old name is kept as a deprecated alias.
BN_BLINDING_new() will now use BN_dup() for the modulus so that
the BN_BLINDING structure gets an independent copy of the
modulus. This means that the previous "BIGNUM *m" argument to
BN_BLINDING_new() and to BN_BLINDING_create_param() now
essentially becomes "const BIGNUM *m", although we can't actually
change this in the header file before 0.9.9. It allows
RSA_setup_blinding() to use BN_with_flags() on the modulus to
enable BN_FLG_CONSTTIME.
[Matthew D Wood (Intel Corp)]
*) In the SSL/TLS server implementation, be strict about session ID
context matching (which matters if an application uses a single
external cache for different purposes). Previously,
out-of-context reuse was forbidden only if SSL_VERIFY_PEER was
set. This did ensure strict client verification, but meant that,
with applications using a single external cache for quite
different requirements, clients could circumvent ciphersuite
restrictions for a given session ID context by starting a session
in a different context.
[Bodo Moeller]
*) Include "!eNULL" in SSL_DEFAULT_CIPHER_LIST to make sure that
a ciphersuite string such as "DEFAULT:RSA" cannot enable
authentication-only ciphersuites.
[Bodo Moeller]
*) Update the SSL_get_shared_ciphers() fix CVE-2006-3738 which was
not complete and could lead to a possible single byte overflow
(CVE-2007-5135) [Ben Laurie]
Changes between 0.9.8d and 0.9.8e [23 Feb 2007]
*) Since AES128 and AES256 (and similarly Camellia128 and
Camellia256) share a single mask bit in the logic of
ssl/ssl_ciph.c, the code for masking out disabled ciphers needs a
kludge to work properly if AES128 is available and AES256 isn't
(or if Camellia128 is available and Camellia256 isn't).
[Victor Duchovni]
*) Fix the BIT STRING encoding generated by crypto/ec/ec_asn1.c
(within i2d_ECPrivateKey, i2d_ECPKParameters, i2d_ECParameters):
When a point or a seed is encoded in a BIT STRING, we need to
prevent the removal of trailing zero bits to get the proper DER
encoding. (By default, crypto/asn1/a_bitstr.c assumes the case
of a NamedBitList, for which trailing 0 bits need to be removed.)
[Bodo Moeller]
*) Have SSL/TLS server implementation tolerate "mismatched" record
protocol version while receiving ClientHello even if the
ClientHello is fragmented. (The server can't insist on the
particular protocol version it has chosen before the ServerHello
message has informed the client about his choice.)
[Bodo Moeller]
*) Add RFC 3779 support.
[Rob Austein for ARIN, Ben Laurie]
*) Load error codes if they are not already present instead of using a
static variable. This allows them to be cleanly unloaded and reloaded.
Improve header file function name parsing.
[Steve Henson]
*) extend SMTP and IMAP protocol emulation in s_client to use EHLO
or CAPABILITY handshake as required by RFCs.
[Goetz Babin-Ebell]
Changes between 0.9.8c and 0.9.8d [28 Sep 2006]
*) Introduce limits to prevent malicious keys being able to
cause a denial of service. (CVE-2006-2940)
[Steve Henson, Bodo Moeller]
*) Fix ASN.1 parsing of certain invalid structures that can result
in a denial of service. (CVE-2006-2937) [Steve Henson]
*) Fix buffer overflow in SSL_get_shared_ciphers() function.
(CVE-2006-3738) [Tavis Ormandy and Will Drewry, Google Security Team]
*) Fix SSL client code which could crash if connecting to a
malicious SSLv2 server. (CVE-2006-4343)
[Tavis Ormandy and Will Drewry, Google Security Team]
*) Since 0.9.8b, ciphersuite strings naming explicit ciphersuites
match only those. Before that, "AES256-SHA" would be interpreted
as a pattern and match "AES128-SHA" too (since AES128-SHA got
the same strength classification in 0.9.7h) as we currently only
have a single AES bit in the ciphersuite description bitmap.
That change, however, also applied to ciphersuite strings such as
"RC4-MD5" that intentionally matched multiple ciphersuites --
namely, SSL 2.0 ciphersuites in addition to the more common ones
from SSL 3.0/TLS 1.0.
So we change the selection algorithm again: Naming an explicit
ciphersuite selects this one ciphersuite, and any other similar
ciphersuite (same bitmap) from *other* protocol versions.
Thus, "RC4-MD5" again will properly select both the SSL 2.0
ciphersuite and the SSL 3.0/TLS 1.0 ciphersuite.
Since SSL 2.0 does not have any ciphersuites for which the
128/256 bit distinction would be relevant, this works for now.
The proper fix will be to use different bits for AES128 and
AES256, which would have avoided the problems from the beginning;
however, bits are scarce, so we can only do this in a new release
(not just a patchlevel) when we can change the SSL_CIPHER
definition to split the single 'unsigned long mask' bitmap into
multiple values to extend the available space.
[Bodo Moeller]
Changes between 0.9.8b and 0.9.8c [05 Sep 2006]
*) Avoid PKCS #1 v1.5 signature attack discovered by Daniel Bleichenbacher
(CVE-2006-4339) [Ben Laurie and Google Security Team]
*) Add AES IGE and biIGE modes.
[Ben Laurie]
*) Change the Unix randomness entropy gathering to use poll() when
possible instead of select(), since the latter has some
undesirable limitations.
[Darryl Miles via Richard Levitte and Bodo Moeller]
*) Disable "ECCdraft" ciphersuites more thoroughly. Now special
treatment in ssl/ssl_ciph.s makes sure that these ciphersuites
cannot be implicitly activated as part of, e.g., the "AES" alias.
However, please upgrade to OpenSSL 0.9.9[-dev] for
non-experimental use of the ECC ciphersuites to get TLS extension
support, which is required for curve and point format negotiation
to avoid potential handshake problems.
[Bodo Moeller]
*) Disable rogue ciphersuites:
- SSLv2 0x08 0x00 0x80 ("RC4-64-MD5")
- SSLv3/TLSv1 0x00 0x61 ("EXP1024-RC2-CBC-MD5")
- SSLv3/TLSv1 0x00 0x60 ("EXP1024-RC4-MD5")
The latter two were purportedly from
draft-ietf-tls-56-bit-ciphersuites-0[01].txt, but do not really
appear there.
Also deactivate the remaining ciphersuites from
draft-ietf-tls-56-bit-ciphersuites-01.txt. These are just as
unofficial, and the ID has long expired.
[Bodo Moeller]
*) Fix RSA blinding Heisenbug (problems sometimes occured on
dual-core machines) and other potential thread-safety issues.
[Bodo Moeller]
*) Add the symmetric cipher Camellia (128-bit, 192-bit, 256-bit key
versions), which is now available for royalty-free use
(see http://info.isl.ntt.co.jp/crypt/eng/info/chiteki.html).
Also, add Camellia TLS ciphersuites from RFC 4132.
To minimize changes between patchlevels in the OpenSSL 0.9.8
series, Camellia remains excluded from compilation unless OpenSSL
is configured with 'enable-camellia'.
[NTT]
*) Disable the padding bug check when compression is in use. The padding
bug check assumes the first packet is of even length, this is not
necessarily true if compresssion is enabled and can result in false
positives causing handshake failure. The actual bug test is ancient
code so it is hoped that implementations will either have fixed it by
now or any which still have the bug do not support compression.
[Steve Henson]
Changes between 0.9.8a and 0.9.8b [04 May 2006]
*) When applying a cipher rule check to see if string match is an explicit
cipher suite and only match that one cipher suite if it is.
[Steve Henson]
*) Link in manifests for VC++ if needed.
[Austin Ziegler <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 incompletet DH cert support from
ssl/ssl_rsa.c and ssl/s3_both.c
[Nils Larsch]
*) Use SHA-1 instead of MD5 as the default digest algorithm for
the apps/openssl applications.
[Nils Larsch]
*) Compile clean with "-Wall -Wmissing-prototypes
-Wstrict-prototypes -Wmissing-declarations -Werror". Currently
DEBUG_SAFESTACK must also be set.
[Ben Laurie]
*) Change ./Configure so that certain algorithms can be disabled by default.
The new counterpiece to "no-xxx" is "enable-xxx".
The patented RC5 and MDC2 algorithms will now be disabled unless
"enable-rc5" and "enable-mdc2", respectively, are specified.
(IDEA remains enabled despite being patented. This is because IDEA
is frequently required for interoperability, and there is no license
fee for non-commercial use. As before, "no-idea" can be used to
avoid this algorithm.)
[Bodo Moeller]
*) Add processing of proxy certificates (see RFC 3820). This work was
sponsored by KTH (The Royal Institute of Technology in Stockholm) and
EGEE (Enabling Grids for E-science in Europe).
[Richard Levitte]
*) RC4 performance overhaul on modern architectures/implementations, such
as Intel P4, IA-64 and AMD64.
[Andy Polyakov]
*) New utility extract-section.pl. This can be used specify an alternative
section number in a pod file instead of having to treat each file as
a separate case in Makefile. This can be done by adding two lines to the
pod file:
=for comment openssl_section:XXX
The blank line is mandatory.
[Steve Henson]
*) New arguments -certform, -keyform and -pass for s_client and s_server
to allow alternative format key and certificate files and passphrase
sources.
[Steve Henson]
*) New structure X509_VERIFY_PARAM which combines current verify parameters,
update associated structures and add various utility functions.
Add new policy related verify parameters, include policy checking in
standard verify code. Enhance 'smime' application with extra parameters
to support policy checking and print out.
[Steve Henson]
*) Add a new engine to support VIA PadLock ACE extensions in the VIA C3
Nehemiah processors. These extensions support AES encryption in hardware
as well as RNG (though RNG support is currently disabled).
[Michal Ludvig <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 interdepencies by declaring more opaque objects in
ossl_typ.h. As a consequence, including some headers (eg. engine.h) will
give fewer recursive includes, which could break lazy source code - so
this change is covered by the OPENSSL_NO_DEPRECATED symbol. As always,
developers should define this symbol when building and using openssl to
ensure they track the recommended behaviour, interfaces, [etc], but
backwards-compatible behaviour prevails when this isn't defined.
[Geoff Thorpe]
*) New function X509_POLICY_NODE_print() which prints out policy nodes.
[Steve Henson]
*) Add new EVP function EVP_CIPHER_CTX_rand_key and associated functionality.
This will generate a random key of the appropriate length based on the
cipher context. The EVP_CIPHER can provide its own random key generation
routine to support keys of a specific form. This is used in the des and
3des routines to generate a key of the correct parity. Update S/MIME
code to use new functions and hence generate correct parity DES keys.
Add EVP_CHECK_DES_KEY #define to return an error if the key is not
valid (weak or incorrect parity).
[Steve Henson]
*) Add a local set of CRLs that can be used by X509_verify_cert() as well
as looking them up. This is useful when the verified structure may contain
CRLs, for example PKCS#7 signedData. Modify PKCS7_verify() to use any CRLs
present unless the new PKCS7_NO_CRL flag is asserted.
[Steve Henson]
*) Extend ASN1 oid configuration module. It now additionally accepts the
syntax:
shortName = some long name, 1.2.3.4
[Steve Henson]
*) Reimplemented the BN_CTX implementation. There is now no more static
limitation on the number of variables it can handle nor the depth of the
"stack" handling for BN_CTX_start()/BN_CTX_end() pairs. The stack
information can now expand as required, and rather than having a single
static array of bignums, BN_CTX now uses a linked-list of such arrays
allowing it to expand on demand whilst maintaining the usefulness of
BN_CTX's "bundling".
[Geoff Thorpe]
*) Add a missing BN_CTX parameter to the 'rsa_mod_exp' callback in RSA_METHOD
to allow all RSA operations to function using a single BN_CTX.
[Geoff Thorpe]
*) Preliminary support for certificate policy evaluation and checking. This
is initially intended to pass the tests outlined in "Conformance Testing
of Relying Party Client Certificate Path Processing Logic" v1.07.
[Steve Henson]
*) bn_dup_expand() has been deprecated, it was introduced in 0.9.7 and
remained unused and not that useful. A variety of other little bignum
tweaks and fixes have also been made continuing on from the audit (see
below).
[Geoff Thorpe]
*) Constify all or almost all d2i, c2i, s2i and r2i functions, along with
associated ASN1, EVP and SSL functions and old ASN1 macros.
[Richard Levitte]
*) BN_zero() only needs to set 'top' and 'neg' to zero for correct results,
and this should never fail. So the return value from the use of
BN_set_word() (which can fail due to needless expansion) is now deprecated;
if OPENSSL_NO_DEPRECATED is defined, BN_zero() is a void macro.
[Geoff Thorpe]
*) BN_CTX_get() should return zero-valued bignums, providing the same
initialised value as BN_new().
[Geoff Thorpe, suggested by Ulf Möller]
*) Support for inhibitAnyPolicy certificate extension.
[Steve Henson]
*) An audit of the BIGNUM code is underway, for which debugging code is
enabled when BN_DEBUG is defined. This makes stricter enforcements on what
is considered valid when processing BIGNUMs, and causes execution to
assert() when a problem is discovered. If BN_DEBUG_RAND is defined,
further steps are taken to deliberately pollute unused data in BIGNUM
structures to try and expose faulty code further on. For now, openssl will
(in its default mode of operation) continue to tolerate the inconsistent
forms that it has tolerated in the past, but authors and packagers should
consider trying openssl and their own applications when compiled with
these debugging symbols defined. It will help highlight potential bugs in
their own code, and will improve the test coverage for OpenSSL itself. At
some point, these tighter rules will become openssl's default to improve
maintainability, though the assert()s and other overheads will remain only
in debugging configurations. See bn.h for more details.
[Geoff Thorpe, Nils Larsch, Ulf Möller]
*) BN_CTX_init() has been deprecated, as BN_CTX is an opaque structure
that can only be obtained through BN_CTX_new() (which implicitly
initialises it). The presence of this function only made it possible
to overwrite an existing structure (and cause memory leaks).
[Geoff Thorpe]
*) Because of the callback-based approach for implementing LHASH as a
template type, lh_insert() adds opaque objects to hash-tables and
lh_doall() or lh_doall_arg() are typically used with a destructor callback
to clean up those corresponding objects before destroying the hash table
(and losing the object pointers). So some over-zealous constifications in
LHASH have been relaxed so that lh_insert() does not take (nor store) the
objects as "const" and the lh_doall[_arg] callback wrappers are not
prototyped to have "const" restrictions on the object pointers they are
given (and so aren't required to cast them away any more).
[Geoff Thorpe]
*) The tmdiff.h API was so ugly and minimal that our own timing utility
(speed) prefers to use its own implementation. The two implementations
haven't been consolidated as yet (volunteers?) but the tmdiff API has had
its object type properly exposed (MS_TM) instead of casting to/from "char
*". This may still change yet if someone realises MS_TM and "ms_time_***"
aren't necessarily the greatest nomenclatures - but this is what was used
internally to the implementation so I've used that for now.
[Geoff Thorpe]
*) Ensure that deprecated functions do not get compiled when
OPENSSL_NO_DEPRECATED is defined. Some "openssl" subcommands and a few of
the self-tests were still using deprecated key-generation functions so
these have been updated also.
[Geoff Thorpe]
*) Reorganise PKCS#7 code to separate the digest location functionality
into PKCS7_find_digest(), digest addtion into PKCS7_bio_add_digest().
New function PKCS7_set_digest() to set the digest type for PKCS#7
digestedData type. Add additional code to correctly generate the
digestedData type and add support for this type in PKCS7 initialization
functions.
[Steve Henson]
*) New function PKCS7_set0_type_other() this initializes a PKCS7
structure of type "other".
[Steve Henson]
*) Fix prime generation loop in crypto/bn/bn_prime.pl by making
sure the loop does correctly stop and breaking ("division by zero")
modulus operations are not performed. The (pre-generated) prime
table crypto/bn/bn_prime.h was already correct, but it could not be
re-generated on some platforms because of the "division by zero"
situation in the script.
[Ralf S. Engelschall]
*) Update support for ECC-based TLS ciphersuites according to
draft-ietf-tls-ecc-03.txt: the KDF1 key derivation function with
SHA-1 now is only used for "small" curves (where the
representation of a field element takes up to 24 bytes); for
larger curves, the field element resulting from ECDH is directly
used as premaster secret.
[Douglas Stebila (Sun Microsystems Laboratories)]
*) Add code for kP+lQ timings to crypto/ec/ectest.c, and add SEC2
curve secp160r1 to the tests.
[Douglas Stebila (Sun Microsystems Laboratories)]
*) Add the possibility to load symbols globally with DSO.
[Götz Babin-Ebell <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 muti valued AVAs using '+' notation in config files for
req and dirName.
[Steve Henson]
*) Support for nameConstraints certificate extension.
[Steve Henson]
*) Support for policyConstraints certificate extension.
[Steve Henson]
*) Support for policyMappings certificate extension.
[Steve Henson]
*) Make sure the default DSA_METHOD implementation only uses its
dsa_mod_exp() and/or bn_mod_exp() handlers if they are non-NULL,
and change its own handlers to be NULL so as to remove unnecessary
indirection. This lets alternative implementations fallback to the
default implementation more easily.
[Geoff Thorpe]
*) Support for directoryName in GeneralName related extensions
in config files.
[Steve Henson]
*) Make it possible to link applications using Makefile.shared.
Make that possible even when linking against static libraries!
[Richard Levitte]
*) Support for single pass processing for S/MIME signing. This now
means that S/MIME signing can be done from a pipe, in addition
cleartext signing (multipart/signed type) is effectively streaming
and the signed data does not need to be all held in memory.
This is done with a new flag PKCS7_STREAM. When this flag is set
PKCS7_sign() only initializes the PKCS7 structure and the actual signing
is done after the data is output (and digests calculated) in
SMIME_write_PKCS7().
[Steve Henson]
*) Add full support for -rpath/-R, both in shared libraries and
applications, at least on the platforms where it's known how
to do it.
[Richard Levitte]
*) In crypto/ec/ec_mult.c, implement fast point multiplication with
precomputation, based on wNAF splitting: EC_GROUP_precompute_mult()
will now compute a table of multiples of the generator that
makes subsequent invocations of EC_POINTs_mul() or EC_POINT_mul()
faster (notably in the case of a single point multiplication,
scalar * generator).
[Nils Larsch, Bodo Moeller]
*) IPv6 support for certificate extensions. The various extensions
which use the IP:a.b.c.d can now take IPv6 addresses using the
formats of RFC1884 2.2 . IPv6 addresses are now also displayed
correctly.
[Steve Henson]
*) Added an ENGINE that implements RSA by performing private key
exponentiations with the GMP library. The conversions to and from
GMP's mpz_t format aren't optimised nor are any montgomery forms
cached, and on x86 it appears OpenSSL's own performance has caught up.
However there are likely to be other architectures where GMP could
provide a boost. This ENGINE is not built in by default, but it can be
specified at Configure time and should be accompanied by the necessary
linker additions, eg;
./config -DOPENSSL_USE_GMP -lgmp
[Geoff Thorpe]
*) "openssl engine" will not display ENGINE/DSO load failure errors when
testing availability of engines with "-t" - the old behaviour is
produced by increasing the feature's verbosity with "-tt".
[Geoff Thorpe]
*) ECDSA routines: under certain error conditions uninitialized BN objects
could be freed. Solution: make sure initialization is performed early
enough. (Reported and fix supplied by Nils Larsch <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 overriden by providing the appropriate method callbacks.
[Geoff Thorpe]
*) Change the "progress" mechanism used in key-generation and
primality testing to functions that take a new BN_GENCB pointer in
place of callback/argument pairs. The new API functions have "_ex"
postfixes and the older functions are reimplemented as wrappers for
the new ones. The OPENSSL_NO_DEPRECATED symbol can be used to hide
declarations of the old functions to help (graceful) attempts to
migrate to the new functions. Also, the new key-generation API
functions operate on a caller-supplied key-structure and return
success/failure rather than returning a key or NULL - this is to
help make "keygen" another member function of RSA_METHOD etc.
Example for using the new callback interface:
int (*my_callback)(int a, int b, BN_GENCB *cb) = ...;
void *my_arg = ...;
BN_GENCB my_cb;
BN_GENCB_set(&my_cb, my_callback, my_arg);
return BN_is_prime_ex(some_bignum, BN_prime_checks, NULL, &cb);
/* For the meaning of a, b in calls to my_callback(), see the
* documentation of the function that calls the callback.
* cb will point to my_cb; my_arg can be retrieved as cb->arg.
* my_callback should return 1 if it wants BN_is_prime_ex()
* to continue, or 0 to stop.
*/
[Geoff Thorpe]
*) Change the ZLIB compression method to be stateful, and make it
available to TLS with the number defined in
draft-ietf-tls-compression-04.txt.
[Richard Levitte]
*) Add the ASN.1 structures and functions for CertificatePair, which
is defined as follows (according to X.509_4thEditionDraftV6.pdf):
CertificatePair ::= SEQUENCE {
forward [0] Certificate OPTIONAL,
reverse [1] Certificate OPTIONAL,
-- at least one of the pair shall be present -- }
Also implement the PEM functions to read and write certificate
pairs, and defined the PEM tag as "CERTIFICATE PAIR".
This needed to be defined, mostly for the sake of the LDAP
attribute crossCertificatePair, but may prove useful elsewhere as
well.
[Richard Levitte]
*) Make it possible to inhibit symlinking of shared libraries in
Makefile.shared, for Cygwin's sake.
[Richard Levitte]
*) Extend the BIGNUM API by creating a function
void BN_set_negative(BIGNUM *a, int neg);
and a macro that behave like
int BN_is_negative(const BIGNUM *a);
to avoid the need to access 'a->neg' directly in applications.
[Nils Larsch]
*) Implement fast modular reduction for pseudo-Mersenne primes
used in NIST curves (crypto/bn/bn_nist.c, crypto/ec/ecp_nist.c).
EC_GROUP_new_curve_GFp() will now automatically use this
if applicable.
[Nils Larsch <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 overriden at configure time through
the usual use of --prefix and/or --openssldir, and at run
time with the environment variable OPENSSL_ENGINES.
[Geoff Thorpe and Richard Levitte]
*) Add Makefile.shared, a helper makefile to build shared
libraries. Addapt Makefile.org.
[Richard Levitte]
*) Add version info to Win32 DLLs.
[Peter 'Luna' Runestig" <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 deactive the remaining ciphersuites from
draft-ietf-tls-56-bit-ciphersuites-01.txt. These are just as
unofficial, and the ID has long expired.
[Bodo Moeller]
*) Fix RSA blinding Heisenbug (problems sometimes occured on
dual-core machines) and other potential thread-safety issues.
[Bodo Moeller]
Changes between 0.9.7i and 0.9.7j [04 May 2006]
*) Adapt fipsld and the build system to link against the validated FIPS
module in FIPS mode.
[Steve Henson]
*) Fixes for VC++ 2005 build under Windows.
[Steve Henson]
*) Add new Windows build target VC-32-GMAKE for VC++. This uses GNU make
from a Windows bash shell such as MSYS. It is autodetected from the
"config" script when run from a VC++ environment. Modify standard VC++
build to use fipscanister.o from the GNU make build.
[Steve Henson]
Changes between 0.9.7h and 0.9.7i [14 Oct 2005]
*) Wrapped the definition of EVP_MAX_MD_SIZE in a #ifdef OPENSSL_FIPS.
The value now differs depending on if you build for FIPS or not.
BEWARE! A program linked with a shared FIPSed libcrypto can't be
safely run with a non-FIPSed libcrypto, as it may crash because of
the difference induced by this change.
[Andy Polyakov]
Changes between 0.9.7g and 0.9.7h [11 Oct 2005]
*) Remove the functionality of SSL_OP_MSIE_SSLV2_RSA_PADDING
(part of SSL_OP_ALL). This option used to disable the
countermeasure against man-in-the-middle protocol-version
rollback in the SSL 2.0 server implementation, which is a bad
idea. (CVE-2005-2969)
[Bodo Moeller; problem pointed out by Yutaka Oiwa (Research Center
for Information Security, National Institute of Advanced Industrial
Science and Technology [AIST], Japan)]
*) Minimal support for X9.31 signatures and PSS padding modes. This is
mainly for FIPS compliance and not fully integrated at this stage.
[Steve Henson]
*) For DSA signing, unless DSA_FLAG_NO_EXP_CONSTTIME is set, perform
the exponentiation using a fixed-length exponent. (Otherwise,
the information leaked through timing could expose the secret key
after many signatures; cf. Bleichenbacher's attack on DSA with
biased k.)
[Bodo Moeller]
*) Make a new fixed-window mod_exp implementation the default for
RSA, DSA, and DH private-key operations so that the sequence of
squares and multiplies and the memory access pattern are
independent of the particular secret key. This will mitigate
cache-timing and potential related attacks.
BN_mod_exp_mont_consttime() is the new exponentiation implementation,
and this is automatically used by BN_mod_exp_mont() if the new flag
BN_FLG_EXP_CONSTTIME is set for the exponent. RSA, DSA, and DH
will use this BN flag for private exponents unless the flag
RSA_FLAG_NO_EXP_CONSTTIME, DSA_FLAG_NO_EXP_CONSTTIME, or
DH_FLAG_NO_EXP_CONSTTIME, respectively, is set.
[Matthew D Wood (Intel Corp), with some changes by Bodo Moeller]
*) Change the client implementation for SSLv23_method() and
SSLv23_client_method() so that is uses the SSL 3.0/TLS 1.0
Client Hello message format if the SSL_OP_NO_SSLv2 option is set.
(Previously, the SSL 2.0 backwards compatible Client Hello
message format would be used even with SSL_OP_NO_SSLv2.)
[Bodo Moeller]
*) Add support for smime-type MIME parameter in S/MIME messages which some
clients need.
[Steve Henson]
*) New function BN_MONT_CTX_set_locked() to set montgomery parameters in
a threadsafe manner. Modify rsa code to use new function and add calls
to dsa and dh code (which had race conditions before).
[Steve Henson]
*) Include the fixed error library code in the C error file definitions
instead of fixing them up at runtime. This keeps the error code
structures constant.
[Steve Henson]
Changes between 0.9.7f and 0.9.7g [11 Apr 2005]
[NB: OpenSSL 0.9.7h and later 0.9.7 patch levels were released after
OpenSSL 0.9.8.]
*) Fixes for newer kerberos headers. NB: the casts are needed because
the 'length' field is signed on one version and unsigned on another
with no (?) obvious way to tell the difference, without these VC++
complains. Also the "definition" of FAR (blank) is no longer included
nor is the error ENOMEM. KRB5_PRIVATE has to be set to 1 to pick up
some needed definitions.
[Steve Henson]
*) Undo Cygwin change.
[Ulf Möller]
*) Added support for proxy certificates according to RFC 3820.
Because they may be a security thread to unaware applications,
they must be explicitely allowed in run-time. See
docs/HOWTO/proxy_certificates.txt for further information.
[Richard Levitte]
Changes between 0.9.7e and 0.9.7f [22 Mar 2005]
*) Use (SSL_RANDOM_VALUE - 4) bytes of pseudo random data when generating
server and client random values. Previously
(SSL_RANDOM_VALUE - sizeof(time_t)) would be used which would result in
less random data when sizeof(time_t) > 4 (some 64 bit platforms).
This change has negligible security impact because:
1. Server and client random values still have 24 bytes of pseudo random
data.
2. Server and client random values are sent in the clear in the initial
handshake.
3. The master secret is derived using the premaster secret (48 bytes in
size for static RSA ciphersuites) as well as client server and random
values.
The OpenSSL team would like to thank the UK NISCC for bringing this issue
to our attention.
[Stephen Henson, reported by UK NISCC]
*) Use Windows randomness collection on Cygwin.
[Ulf Möller]
*) Fix hang in EGD/PRNGD query when communication socket is closed
prematurely by EGD/PRNGD.
[Darren Tucker <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 reencode DNs into UTF8Strings
(in violation of RFC3280) and can't or wont issue name rollover
certificates.
[Steve Henson]
*) Make an explicit check during certificate validation to see that
the CA setting in each certificate on the chain is correct. As a
side effect always do the following basic checks on extensions,
not just when there's an associated purpose to the check:
- if there is an unhandled critical extension (unless the user
has chosen to ignore this fault)
- if the path length has been exceeded (if one is set at all)
- that certain extensions fit the associated purpose (if one has
been given)
[Richard Levitte]
Changes between 0.9.7d and 0.9.7e [25 Oct 2004]
*) Avoid a race condition when CRLs are checked in a multi threaded
environment. This would happen due to the reordering of the revoked
entries during signature checking and serial number lookup. Now the
encoding is cached and the serial number sort performed under a lock.
Add new STACK function sk_is_sorted().
[Steve Henson]
*) Add Delta CRL to the extension code.
[Steve Henson]
*) Various fixes to s3_pkt.c so alerts are sent properly.
[David Holmes <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 incorrrect
block cipher padding has been found. This is a countermeasure
against active attacks where the attacker has to distinguish
between bad padding and a MAC verification error. (CVE-2003-0078)
[Bodo Moeller; problem pointed out by Brice Canvel (EPFL),
Alain Hiltgen (UBS), Serge Vaudenay (EPFL), and
Martin Vuagnoux (EPFL, Ilion)]
*) Make the no-err option work as intended. The intention with no-err
is not to have the whole error stack handling routines removed from
libcrypto, it's only intended to remove all the function name and
reason texts, thereby removing some of the footprint that may not
be interesting if those errors aren't displayed anyway.
NOTE: it's still possible for any application or module to have it's
own set of error texts inserted. The routines are there, just not
used by default when no-err is given.
[Richard Levitte]
*) Add support for FreeBSD on IA64.
[dirk.meyer@dinoex.sub.org via Richard Levitte, resolves #454]
*) Adjust DES_cbc_cksum() so it returns the same value as the MIT
Kerberos function mit_des_cbc_cksum(). Before this change,
the value returned by DES_cbc_cksum() was like the one from
mit_des_cbc_cksum(), except the bytes were swapped.
[Kevin Greaney <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 successfull, don't worry about it,
it probably means the source directory is very clean.
[Richard Levitte]
*) Make sure any ENGINE control commands make local copies of string
pointers passed to them whenever necessary. Otherwise it is possible
the caller may have overwritten (or deallocated) the original string
data when a later ENGINE operation tries to use the stored values.
[Götz Babin-Ebell <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 initailized at that point (ctrls before that point are run
on the uninitialized ENGINE and after on the initialized one). If
init=0 then the ENGINE will not be iniatialized at all.
[Steve Henson]
*) Fix the 'app_verify_callback' interface so that the user-defined
argument is actually passed to the callback: In the
SSL_CTX_set_cert_verify_callback() prototype, the callback
declaration has been changed from
int (*cb)()
into
int (*cb)(X509_STORE_CTX *,void *);
in ssl_verify_cert_chain (ssl/ssl_cert.c), the call
i=s->ctx->app_verify_callback(&ctx)
has been changed into
i=s->ctx->app_verify_callback(&ctx, s->ctx->app_verify_arg).
To update applications using SSL_CTX_set_cert_verify_callback(),
a dummy argument can be added to their callback functions.
[D. K. Smetters <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]
*) Prelminary ENGINE config module.
[Steve Henson]
*) New experimental application configuration code.
[Steve Henson]
*) Change the AES code to follow the same name structure as all other
symmetric ciphers, and behave the same way. Move everything to
the directory crypto/aes, thereby obsoleting crypto/rijndael.
[Stephen Sprunk <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 iterfaces. This change also introduces integrated
support for symmetric ciphers and digest implementations - so ENGINEs
can now accelerate these by providing EVP_CIPHER and EVP_MD
implementations of their own. This is detailed in crypto/engine/README
as it couldn't be adequately described here. However, there are a few
API changes worth noting - some RSA, DSA, DH, and RAND functions that
were changed in the original introduction of ENGINE code have now
reverted back - the hooking from this code to ENGINE is now a good
deal more passive and at run-time, operations deal directly with
RSA_METHODs, DSA_METHODs (etc) as they did before, rather than
dereferencing through an ENGINE pointer any more. Also, the ENGINE
functions dealing with BN_MOD_EXP[_CRT] handlers have been removed -
they were not being used by the framework as there is no concept of a
BIGNUM_METHOD and they could not be generalised to the new
'ENGINE_TABLE' mechanism that underlies the new code. Similarly,
ENGINE_cpy() has been removed as it cannot be consistently defined in
the new code.
[Geoff Thorpe]
*) Change ASN1_GENERALIZEDTIME_check() to allow fractional seconds.
[Steve Henson]
*) Change mkdef.pl to sort symbols that get the same entry number,
and make sure the automatically generated functions ERR_load_*
become part of libeay.num as well.
[Richard Levitte]
*) New function SSL_renegotiate_pending(). This returns true once
renegotiation has been requested (either SSL_renegotiate() call
or HelloRequest/ClientHello receveived from the peer) and becomes
false once a handshake has been completed.
(For servers, SSL_renegotiate() followed by SSL_do_handshake()
sends a HelloRequest, but does not ensure that a handshake takes
place. SSL_renegotiate_pending() is useful for checking if the
client has followed the request.)
[Bodo Moeller]
*) New SSL option SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION.
By default, clients may request session resumption even during
renegotiation (if session ID contexts permit); with this option,
session resumption is possible only in the first handshake.
SSL_OP_ALL is now 0x00000FFFL instead of 0x000FFFFFL. This makes
more bits available for options that should not be part of
SSL_OP_ALL (such as SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION).
[Bodo Moeller]
*) Add some demos for certificate and certificate request creation.
[Steve Henson]
*) Make maximum certificate chain size accepted from the peer application
settable (SSL*_get/set_max_cert_list()), as proposed by
"Douglas E. Engert" <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).
[Geoff Thorpe]
*) Add a "dynamic" ENGINE that provides a mechanism for binding ENGINE
implementations into applications that are completely implemented in
self-contained shared-libraries. The "dynamic" ENGINE exposes control
commands that can be used to configure what shared-library to load and
to control aspects of the way it is handled. Also, made an update to
the README.ENGINE file that brings its information up-to-date and
provides some information and instructions on the "dynamic" ENGINE
(ie. how to use it, how to build "dynamic"-loadable ENGINEs, etc).
[Geoff Thorpe]
*) Make it possible to unload ranges of ERR strings with a new
"ERR_unload_strings" function.
[Geoff Thorpe]
*) Add a copy() function to EVP_MD.
[Ben Laurie]
*) Make EVP_MD routines take a context pointer instead of just the
md_data void pointer.
[Ben Laurie]
*) Add flags to EVP_MD and EVP_MD_CTX. EVP_MD_FLAG_ONESHOT indicates
that the digest can only process a single chunk of data
(typically because it is provided by a piece of
hardware). EVP_MD_CTX_FLAG_ONESHOT indicates that the application
is only going to provide a single chunk of data, and hence the
framework needn't accumulate the data for oneshot drivers.
[Ben Laurie]
*) As with "ERR", make it possible to replace the underlying "ex_data"
functions. This change also alters the storage and management of global
ex_data state - it's now all inside ex_data.c and all "class" code (eg.
RSA, BIO, SSL_CTX, etc) no longer stores its own STACKS and per-class
index counters. The API functions that use this state have been changed
to take a "class_index" rather than pointers to the class's local STACK
and counter, and there is now an API function to dynamically create new
classes. This centralisation allows us to (a) plug a lot of the
thread-safety problems that existed, and (b) makes it possible to clean
up all allocated state using "CRYPTO_cleanup_all_ex_data()". W.r.t. (b)
such data would previously have always leaked in application code and
workarounds were in place to make the memory debugging turn a blind eye
to it. Application code that doesn't use this new function will still
leak as before, but their memory debugging output will announce it now
rather than letting it slide.
Besides the addition of CRYPTO_cleanup_all_ex_data(), another API change
induced by the "ex_data" overhaul is that X509_STORE_CTX_init() now
has a return value to indicate success or failure.
[Geoff Thorpe]
*) Make it possible to replace the underlying "ERR" functions such that the
global state (2 LHASH tables and 2 locks) is only used by the "default"
implementation. This change also adds two functions to "get" and "set"
the implementation prior to it being automatically set the first time
any other ERR function takes place. Ie. an application can call "get",
pass the return value to a module it has just loaded, and that module
can call its own "set" function using that value. This means the
module's "ERR" operations will use (and modify) the error state in the
application and not in its own statically linked copy of OpenSSL code.
[Geoff Thorpe]
*) Give DH, DSA, and RSA types their own "**_up_ref()" function to increment
reference counts. This performs normal REF_PRINT/REF_CHECK macros on
the operation, and provides a more encapsulated way for external code
(crypto/evp/ and ssl/) to do this. Also changed the evp and ssl code
to use these functions rather than manually incrementing the counts.
Also rename "DSO_up()" function to more descriptive "DSO_up_ref()".
[Geoff Thorpe]
*) Add EVP test program.
[Ben Laurie]
*) Add symmetric cipher support to ENGINE. Expect the API to change!
[Ben Laurie]
*) New CRL functions: X509_CRL_set_version(), X509_CRL_set_issuer_name()
X509_CRL_set_lastUpdate(), X509_CRL_set_nextUpdate(), X509_CRL_sort(),
X509_REVOKED_set_serialNumber(), and X509_REVOKED_set_revocationDate().
These allow a CRL to be built without having to access X509_CRL fields
directly. Modify 'ca' application to use new functions.
[Steve Henson]
*) Move SSL_OP_TLS_ROLLBACK_BUG out of the SSL_OP_ALL list of recommended
bug workarounds. Rollback attack detection is a security feature.
The problem will only arise on OpenSSL servers when TLSv1 is not
available (sslv3_server_method() or SSL_OP_NO_TLSv1).
Software authors not wanting to support TLSv1 will have special reasons
for their choice and can explicitly enable this option.
[Bodo Moeller, Lutz Jaenicke]
*) Rationalise EVP so it can be extended: don't include a union of
cipher/digest structures, add init/cleanup functions for EVP_MD_CTX
(similar to those existing for EVP_CIPHER_CTX).
Usage example:
EVP_MD_CTX md;
EVP_MD_CTX_init(&md); /* new function call */
EVP_DigestInit(&md, EVP_sha1());
EVP_DigestUpdate(&md, in, len);
EVP_DigestFinal(&md, out, NULL);
EVP_MD_CTX_cleanup(&md); /* new function call */
[Ben Laurie]
*) Make DES key schedule conform to the usual scheme, as well as
correcting its structure. This means that calls to DES functions
now have to pass a pointer to a des_key_schedule instead of a
plain des_key_schedule (which was actually always a pointer
anyway): E.g.,
des_key_schedule ks;
des_set_key_checked(..., &ks);
des_ncbc_encrypt(..., &ks, ...);
(Note that a later change renames 'des_...' into 'DES_...'.)
[Ben Laurie]
*) Initial reduction of linker bloat: the use of some functions, such as
PEM causes large amounts of unused functions to be linked in due to
poor organisation. For example pem_all.c contains every PEM function
which has a knock on effect of linking in large amounts of (unused)
ASN1 code. Grouping together similar functions and splitting unrelated
functions prevents this.
[Steve Henson]
*) Cleanup of EVP macros.
[Ben Laurie]
*) Change historical references to {NID,SN,LN}_des_ede and ede3 to add the
correct _ecb suffix.
[Ben Laurie]
*) Add initial OCSP responder support to ocsp application. The
revocation information is handled using the text based index
use by the ca application. The responder can either handle
requests generated internally, supplied in files (for example
via a CGI script) or using an internal minimal server.
[Steve Henson]
*) Add configuration choices to get zlib compression for TLS.
[Richard Levitte]
*) Changes to Kerberos SSL for RFC 2712 compliance:
1. Implemented real KerberosWrapper, instead of just using
KRB5 AP_REQ message. [Thanks to Simon Wilkinson <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:
encrypt
type 8 bytes 64 bytes 256 bytes 1024 bytes 8192 bytes
des-cbc 4408.85k 5560.51k 5778.46k 5862.20k 5825.16k
des-cbc 4389.55k 5571.17k 5792.23k 5846.91k 5832.11k
des-cbc 4394.32k 5575.92k 5807.44k 5848.37k 5841.30k
decrypt
des-cbc 3482.66k 5069.49k 5496.39k 5614.16k 5639.28k
des-cbc 3480.74k 5068.76k 5510.34k 5609.87k 5635.52k
des-cbc 3483.72k 5067.62k 5504.60k 5708.01k 5724.80k
After:
encrypt
des-cbc 4660.16k 5650.19k 5807.19k 5827.13k 5783.32k
decrypt
des-cbc 3624.96k 5258.21k 5530.91k 5624.30k 5628.26k
[Ben Laurie]
*) Added the OS2-EMX target.
["Brian Havard" <brianh@kheldar.apana.org.au> and Richard Levitte]
*) Rewrite apps to use NCONF routines instead of the old CONF. New functions
to support NCONF routines in extension code. New function CONF_set_nconf()
to allow functions which take an NCONF to also handle the old LHASH
structure: this means that the old CONF compatible routines can be
retained (in particular wrt extensions) without having to duplicate the
code. New function X509V3_add_ext_nconf_sk to add extensions to a stack.
[Steve Henson]
*) Enhance the general user interface with mechanisms for inner control
and with possibilities to have yes/no kind of prompts.
[Richard Levitte]
*) Change all calls to low level digest routines in the library and
applications to use EVP. Add missing calls to HMAC_cleanup() and
don't assume HMAC_CTX can be copied using memcpy().
[Verdon Walker <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;
wont compile. This is used by the any applications that need to
declare their own ASN1 modules. This was fixed by adding the option
EXPORT_VAR_AS_FN to all Win32 platforms, although this isn't strictly
needed for static libraries under Win32.
[Steve Henson]
*) New functions X509_PURPOSE_set() and X509_TRUST_set() to handle
setting of purpose and trust fields. New X509_STORE trust and
purpose functions and tidy up setting in other SSL functions.
[Steve Henson]
*) Add copies of X509_STORE_CTX fields and callbacks to X509_STORE
structure. These are inherited by X509_STORE_CTX when it is
initialised. This allows various defaults to be set in the
X509_STORE structure (such as flags for CRL checking and custom
purpose or trust settings) for functions which only use X509_STORE_CTX
internally such as S/MIME.
Modify X509_STORE_CTX_purpose_inherit() so it only sets purposes and
trust settings if they are not set in X509_STORE. This allows X509_STORE
purposes and trust (in S/MIME for example) to override any set by default.
Add command line options for CRL checking to smime, s_client and s_server
applications.
[Steve Henson]
*) Initial CRL based revocation checking. If the CRL checking flag(s)
are set then the CRL is looked up in the X509_STORE structure and
its validity and signature checked, then if the certificate is found
in the CRL the verify fails with a revoked error.
Various new CRL related callbacks added to X509_STORE_CTX structure.
Command line options added to 'verify' application to support this.
This needs some additional work, such as being able to handle multiple
CRLs with different times, extension based lookup (rather than just
by subject name) and ultimately more complete V2 CRL extension
handling.
[Steve Henson]
*) Add a general user interface API (crypto/ui/). This is designed
to replace things like des_read_password and friends (backward
compatibility functions using this new API are provided).
The purpose is to remove prompting functions from the DES code
section as well as provide for prompting through dialog boxes in
a window system and the like.
[Richard Levitte]
*) Add "ex_data" support to ENGINE so implementations can add state at a
per-structure level rather than having to store it globally.
[Geoff]
*) Make it possible for ENGINE structures to be copied when retrieved by
ENGINE_by_id() if the ENGINE specifies a new flag: ENGINE_FLAGS_BY_ID_COPY.
This causes the "original" ENGINE structure to act like a template,
analogous to the RSA vs. RSA_METHOD type of separation. Because of this
operational state can be localised to each ENGINE structure, despite the
fact they all share the same "methods". New ENGINE structures returned in
this case have no functional references and the return value is the single
structural reference. This matches the single structural reference returned
by ENGINE_by_id() normally, when it is incremented on the pre-existing
ENGINE structure.
[Geoff]
*) Fix ASN1 decoder when decoding type ANY and V_ASN1_OTHER: since this
needs to match any other type at all we need to manually clear the
tag cache.
[Steve Henson]
*) Changes to the "openssl engine" utility to include;
- verbosity levels ('-v', '-vv', and '-vvv') that provide information
about an ENGINE's available control commands.
- executing control commands from command line arguments using the
'-pre' and '-post' switches. '-post' is only used if '-t' is
specified and the ENGINE is successfully initialised. The syntax for
the individual commands are colon-separated, for example;
openssl engine chil -pre FORK_CHECK:0 -pre SO_PATH:/lib/test.so
[Geoff]
*) New dynamic control command support for ENGINEs. ENGINEs can now
declare their own commands (numbers), names (strings), descriptions,
and input types for run-time discovery by calling applications. A
subset of these commands are implicitly classed as "executable"
depending on their input type, and only these can be invoked through
the new string-based API function ENGINE_ctrl_cmd_string(). (Eg. this
can be based on user input, config files, etc). The distinction is
that "executable" commands cannot return anything other than a boolean
result and can only support numeric or string input, whereas some
discoverable commands may only be for direct use through
ENGINE_ctrl(), eg. supporting the exchange of binary data, function
pointers, or other custom uses. The "executable" commands are to
support parameterisations of ENGINE behaviour that can be
unambiguously defined by ENGINEs and used consistently across any
OpenSSL-based application. Commands have been added to all the
existing hardware-supporting ENGINEs, noticeably "SO_PATH" to allow
control over shared-library paths without source code alterations.
[Geoff]
*) Changed all ENGINE implementations to dynamically allocate their
ENGINEs rather than declaring them statically. Apart from this being
necessary with the removal of the ENGINE_FLAGS_MALLOCED distinction,
this also allows the implementations to compile without using the
internal engine_int.h header.
[Geoff]
*) Minor adjustment to "rand" code. RAND_get_rand_method() now returns a
'const' value. Any code that should be able to modify a RAND_METHOD
should already have non-const pointers to it (ie. they should only
modify their own ones).
[Geoff]
*) Made a variety of little tweaks to the ENGINE code.
- "atalla" and "ubsec" string definitions were moved from header files
to C code. "nuron" string definitions were placed in variables
rather than hard-coded - allowing parameterisation of these values
later on via ctrl() commands.
- Removed unused "#if 0"'d code.
- Fixed engine list iteration code so it uses ENGINE_free() to release
structural references.
- Constified the RAND_METHOD element of ENGINE structures.
- Constified various get/set functions as appropriate and added
missing functions (including a catch-all ENGINE_cpy that duplicates
all ENGINE values onto a new ENGINE except reference counts/state).
- Removed NULL parameter checks in get/set functions. Setting a method
or function to NULL is a way of cancelling out a previously set
value. Passing a NULL ENGINE parameter is just plain stupid anyway
and doesn't justify the extra error symbols and code.
- Deprecate the ENGINE_FLAGS_MALLOCED define and move the area for
flags from engine_int.h to engine.h.
- Changed prototypes for ENGINE handler functions (init(), finish(),
ctrl(), key-load functions, etc) to take an (ENGINE*) parameter.
[Geoff]
*) Implement binary inversion algorithm for BN_mod_inverse in addition
to the algorithm using long division. The binary algorithm can be
used only if the modulus is odd. On 32-bit systems, it is faster
only for relatively small moduli (roughly 20-30% for 128-bit moduli,
roughly 5-15% for 256-bit moduli), so we use it only for moduli
up to 450 bits. In 64-bit environments, the binary algorithm
appears to be advantageous for much longer moduli; here we use it
for moduli up to 2048 bits.
[Bodo Moeller]
*) Rewrite CHOICE field setting in ASN1_item_ex_d2i(). The old code
could not support the combine flag in choice fields.
[Steve Henson]
*) Add a 'copy_extensions' option to the 'ca' utility. This copies
extensions from a certificate request to the certificate.
[Steve Henson]
*) Allow multiple 'certopt' and 'nameopt' options to be separated
by commas. Add 'namopt' and 'certopt' options to the 'ca' config
file: this allows the display of the certificate about to be
signed to be customised, to allow certain fields to be included
or excluded and extension details. The old system didn't display
multicharacter strings properly, omitted fields not in the policy
and couldn't display additional details such as extensions.
[Steve Henson]
*) Function EC_POINTs_mul for multiple scalar multiplication
of an arbitrary number of elliptic curve points
\sum scalars[i]*points[i],
optionally including the generator defined for the EC_GROUP:
scalar*generator + \sum scalars[i]*points[i].
EC_POINT_mul is a simple wrapper function for the typical case
that the point list has just one item (besides the optional
generator).
[Bodo Moeller]
*) First EC_METHODs for curves over GF(p):
EC_GFp_simple_method() uses the basic BN_mod_mul and BN_mod_sqr
operations and provides various method functions that can also
operate with faster implementations of modular arithmetic.
EC_GFp_mont_method() reuses most functions that are part of
EC_GFp_simple_method, but uses Montgomery arithmetic.
[Bodo Moeller; point addition and point doubling
implementation directly derived from source code provided by
Lenka Fibikova <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, outputed or printed in text form. Not complete yet:
still needs to check the OCSP response validity.
[Steve Henson]
*) New subcommands for 'openssl ca':
'openssl ca -status <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, quering stops
when enough entropy was collected without querying more sockets.
[Lutz Jaenicke]
*) Change the Unix RAND_poll() variant to be able to poll several
random devices, as specified by DEVRANDOM, until a sufficient amount
of data has been collected. We spend at most 10 ms on each file
(select timeout) and read in non-blocking mode. DEVRANDOM now
defaults to the list "/dev/urandom", "/dev/random", "/dev/srandom"
(previously it was just the string "/dev/urandom"), so on typical
platforms the 10 ms delay will never occur.
Also separate out the Unix variant to its own file, rand_unix.c.
For VMS, there's a currently-empty rand_vms.c.
[Richard Levitte]
*) Move OCSP client related routines to ocsp_cl.c. These
provide utility functions which an application needing
to issue a request to an OCSP responder and analyse the
response will typically need: as opposed to those which an
OCSP responder itself would need which will be added later.
OCSP_request_sign() signs an OCSP request with an API similar
to PKCS7_sign(). OCSP_response_status() returns status of OCSP
response. OCSP_response_get1_basic() extracts basic response
from response. OCSP_resp_find_status(): finds and extracts status
information from an OCSP_CERTID structure (which will be created
when the request structure is built). These are built from lower
level functions which work on OCSP_SINGLERESP structures but
wont normally be used unless the application wishes to examine
extensions in the OCSP response for example.
Replace nonce routines with a pair of functions.
OCSP_request_add1_nonce() adds a nonce value and optionally
generates a random value. OCSP_check_nonce() checks the
validity of the nonce in an OCSP response.
[Steve Henson]
*) Change function OCSP_request_add() to OCSP_request_add0_id().
This doesn't copy the supplied OCSP_CERTID and avoids the
need to free up the newly created id. Change return type
to OCSP_ONEREQ to return the internal OCSP_ONEREQ structure.
This can then be used to add extensions to the request.
Deleted OCSP_request_new(), since most of its functionality
is now in OCSP_REQUEST_new() (and the case insensitive name
clash) apart from the ability to set the request name which
will be added elsewhere.
[Steve Henson]
*) Update OCSP API. Remove obsolete extensions argument from
various functions. Extensions are now handled using the new
OCSP extension code. New simple OCSP HTTP function which
can be used to send requests and parse the response.
[Steve Henson]
*) Fix the PKCS#7 (S/MIME) code to work with new ASN1. Two new
ASN1_ITEM structures help with sign and verify. PKCS7_ATTR_SIGN
uses the special reorder version of SET OF to sort the attributes
and reorder them to match the encoded order. This resolves a long
standing problem: a verify on a PKCS7 structure just after signing
it used to fail because the attribute order did not match the
encoded order. PKCS7_ATTR_VERIFY does not reorder the attributes:
it uses the received order. This is necessary to tolerate some broken
software that does not order SET OF. This is handled by encoding
as a SEQUENCE OF but using implicit tagging (with UNIVERSAL class)
to produce the required SET OF.
[Steve Henson]
*) Have mk1mf.pl generate the macros OPENSSL_BUILD_SHLIBCRYPTO and
OPENSSL_BUILD_SHLIBSSL and use them appropriately in the header
files to get correct declarations of the ASN.1 item variables.
[Richard Levitte]
*) Rewrite of PKCS#12 code to use new ASN1 functionality. Replace many
PKCS#12 macros with real functions. Fix two unrelated ASN1 bugs:
asn1_check_tlen() would sometimes attempt to use 'ctx' when it was
NULL and ASN1_TYPE was not dereferenced properly in asn1_ex_c2i().
New ASN1 macro: DECLARE_ASN1_ITEM() which just declares the relevant
ASN1_ITEM and no wrapper functions.
[Steve Henson]
*) New functions or ASN1_item_d2i_fp() and ASN1_item_d2i_bio(). These
replace the old function pointer based I/O routines. Change most of
the *_d2i_bio() and *_d2i_fp() functions to use these.
[Steve Henson]
*) Enhance mkdef.pl to be more accepting about spacing in C preprocessor
lines, recognice more "algorithms" that can be deselected, and make
it complain about algorithm deselection that isn't recognised.
[Richard Levitte]
*) New ASN1 functions to handle dup, sign, verify, digest, pack and
unpack operations in terms of ASN1_ITEM. Modify existing wrappers
to use new functions. Add NO_ASN1_OLD which can be set to remove
some old style ASN1 functions: this can be used to determine if old
code will still work when these eventually go away.
[Steve Henson]
*) New extension functions for OCSP structures, these follow the
same conventions as certificates and CRLs.
[Steve Henson]
*) New function X509V3_add1_i2d(). This automatically encodes and
adds an extension. Its behaviour can be customised with various
flags to append, replace or delete. Various wrappers added for
certifcates and CRLs.
[Steve Henson]
*) Fix to avoid calling the underlying ASN1 print routine when
an extension cannot be parsed. Correct a typo in the
OCSP_SERVICELOC extension. Tidy up print OCSP format.
[Steve Henson]
*) Make mkdef.pl parse some of the ASN1 macros and add apropriate
entries for variables.
[Steve Henson]
*) Add functionality to apps/openssl.c for detecting locking
problems: As the program is single-threaded, all we have
to do is register a locking callback using an array for
storing which locks are currently held by the program.
[Bodo Moeller]
*) Use a lock around the call to CRYPTO_get_ex_new_index() in
SSL_get_ex_data_X509_STORE_idx(), which is used in
ssl_verify_cert_chain() and thus can be called at any time
during TLS/SSL handshakes so that thread-safety is essential.
Unfortunately, the ex_data design is not at all suited
for multi-threaded use, so it probably should be abolished.
[Bodo Moeller]
*) Added Broadcom "ubsec" ENGINE to OpenSSL.
[Broadcom, tweaked and integrated by Geoff Thorpe]
*) Move common extension printing code to new function
X509V3_print_extensions(). Reorganise OCSP print routines and
implement some needed OCSP ASN1 functions. Add OCSP extensions.
[Steve Henson]
*) New function X509_signature_print() to remove duplication in some
print routines.
[Steve Henson]
*) Add a special meaning when SET OF and SEQUENCE OF flags are both
set (this was treated exactly the same as SET OF previously). This
is used to reorder the STACK representing the structure to match the
encoding. This will be used to get round a problem where a PKCS7
structure which was signed could not be verified because the STACK
order did not reflect the encoded order.
[Steve Henson]
*) Reimplement the OCSP ASN1 module using the new code.
[Steve Henson]
*) Update the X509V3 code to permit the use of an ASN1_ITEM structure
for its ASN1 operations. The old style function pointers still exist
for now but they will eventually go away.
[Steve Henson]
*) Merge in replacement ASN1 code from the ASN1 branch. This almost
completely replaces the old ASN1 functionality with a table driven
encoder and decoder which interprets an ASN1_ITEM structure describing
the ASN1 module. Compatibility with the existing ASN1 API (i2d,d2i) is
largely maintained. Almost all of the old asn1_mac.h macro based ASN1
has also been converted to the new form.
[Steve Henson]
*) Change BN_mod_exp_recp so that negative moduli are tolerated
(the sign is ignored). Similarly, ignore the sign in BN_MONT_CTX_set
so that BN_mod_exp_mont and BN_mod_exp_mont_word work
for negative moduli.
[Bodo Moeller]
*) Fix BN_uadd and BN_usub: Always return non-negative results instead
of not touching the result's sign bit.
[Bodo Moeller]
*) BN_div bugfix: If the result is 0, the sign (res->neg) must not be
set.
[Bodo Moeller]
*) Changed the LHASH code to use prototypes for callbacks, and created
macros to declare and implement thin (optionally static) functions
that provide type-safety and avoid function pointer casting for the
type-specific callbacks.
[Geoff Thorpe]
*) Added Kerberos Cipher Suites to be used with TLS, as written in
RFC 2712.
[Veers Staats <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]
#if 0
The following entry accidentily appeared in the CHANGES file
distributed with OpenSSL 0.9.7. The modifications described in
it do *not* apply to OpenSSL 0.9.7.
*) Remove a few calls to bn_wexpand() in BN_sqr() (the one in there
was actually never needed) and in BN_mul(). The removal in BN_mul()
required a small change in bn_mul_part_recursive() and the addition
of the functions bn_cmp_part_words(), bn_sub_part_words() and
bn_add_part_words(), which do the same thing as bn_cmp_words(),
bn_sub_words() and bn_add_words() except they take arrays with
differing sizes.
[Richard Levitte]
#endif
*) In 'openssl passwd', verify passwords read from the terminal
unless the '-salt' option is used (which usually means that
verification would just waste user's time since the resulting
hash is going to be compared with some given password hash)
or the new '-noverify' option is used.
This is an incompatible change, but it does not affect
non-interactive use of 'openssl passwd' (passwords on the command
line, '-stdin' option, '-in ...' option) and thus should not
cause any problems.
[Bodo Moeller]
*) Remove all references to RSAref, since there's no more need for it.
[Richard Levitte]
*) Make DSO load along a path given through an environment variable
(SHLIB_PATH) with shl_load().
[Richard Levitte]
*) Constify the ENGINE code as a result of BIGNUM constification.
Also constify the RSA code and most things related to it. In a
few places, most notable in the depth of the ASN.1 code, ugly
casts back to non-const were required (to be solved at a later
time)
[Richard Levitte]
*) Make it so the openssl application has all engines loaded by default.
[Richard Levitte]
*) Constify the BIGNUM routines a little more.
[Richard Levitte]
*) Add the following functions:
ENGINE_load_cswift()
ENGINE_load_chil()
ENGINE_load_atalla()
ENGINE_load_nuron()
ENGINE_load_builtin_engines()
That way, an application can itself choose if external engines that
are built-in in OpenSSL shall ever be used or not. The benefit is
that applications won't have to be linked with libdl or other dso
libraries unless it's really needed.
Changed 'openssl engine' to load all engines on demand.
Changed the engine header files to avoid the duplication of some
declarations (they differed!).
[Richard Levitte]
*) 'openssl engine' can now list capabilities.
[Richard Levitte]
*) Better error reporting in 'openssl engine'.
[Richard Levitte]
*) Never call load_dh_param(NULL) in s_server.
[Bodo Moeller]
*) Add engine application. It can currently list engines by name and
identity, and test if they are actually available.
[Richard Levitte]
*) Improve RPM specification file by forcing symbolic linking and making
sure the installed documentation is also owned by root.root.
[Damien Miller <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 incorrrect
block cipher padding has been found. This is a countermeasure
against active attacks where the attacker has to distinguish
between bad padding and a MAC verification error. (CVE-2003-0078)
[Bodo Moeller; problem pointed out by Brice Canvel (EPFL),
Alain Hiltgen (UBS), Serge Vaudenay (EPFL), and
Martin Vuagnoux (EPFL, Ilion)]
Changes between 0.9.6g and 0.9.6h [5 Dec 2002]
*) New function OPENSSL_cleanse(), which is used to cleanse a section of
memory from it's contents. This is done with a counter that will
place alternating values in each byte. This can be used to solve
two issues: 1) the removal of calls to memset() by highly optimizing
compilers, and 2) cleansing with other values than 0, since those can
be read through on certain media, for example a swap space on disk.
[Geoff Thorpe]
*) Bugfix: client side session caching did not work with external caching,
because the session->cipher setting was not restored when reloading
from the external cache. This problem was masked, when
SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG (part of SSL_OP_ALL) was set.
(Found by Steve Haslam <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 erronously be flagged, when the CRLF
was just at the end of a processed block. The bug was discovered when
processing data through a buffering memory BIO handing the data to a
BASE64-decoding BIO. Bug fund and patch submitted by Pavel Tsekov
<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 circuments various
cleanups done in state SSL_ST_OK. But session related stuff
must be disabled for SSL_ST_OK in the case that we just sent a
HelloRequest.
Also avoid some overhead by not calling ssl_init_wbio_buffer()
before just sending a HelloRequest.
[Bodo Moeller, Eric Rescorla <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 occured. (Neither SSLerr() codes nor alerts
are directly visible to potential attackers, but the information
may leak via logfiles.)
Similar changes are not required for the SSL 2.0 implementation
because the number of padding bytes is sent in clear for SSL 2.0,
and the extra bytes are just ignored. However ssl/s2_pkt.c
failed to verify that the purported number of padding bytes is in
the legal range.
[Bodo Moeller]
*) Add OpenUNIX-8 support including shared libraries
(Boyd Lynn Gerber <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
specificly for an SSL object with SSL_set_verify() is actually being
used. Before the change, a verify_callback set with this function was
ignored and the verify_callback() set in the SSL_CTX at the time of
the call was used. New function X509_STORE_CTX_set_verify_cb() introduced
to allow the necessary settings.
[Lutz Jaenicke]
*) Initialize static variable in crypto/dsa/dsa_lib.c and crypto/dh/dh_lib.c
explicitly to NULL, as at least on Solaris 8 this seems not always to be
done automatically (in contradiction to the requirements of the C
standard). This made problems when used from OpenSSH.
[Lutz Jaenicke]
*) In OpenSSL 0.9.6a and 0.9.6b, crypto/dh/dh_key.c ignored
dh->length and always used
BN_rand_range(priv_key, dh->p).
BN_rand_range() is not necessary for Diffie-Hellman, and this
specific range makes Diffie-Hellman unnecessarily inefficient if
dh->length (recommended exponent length) is much smaller than the
length of dh->p. We could use BN_rand_range() if the order of
the subgroup was stored in the DH structure, but we only have
dh->length.
So switch back to
BN_rand(priv_key, l, ...)
where 'l' is dh->length if this is defined, or BN_num_bits(dh->p)-1
otherwise.
[Bodo Moeller]
*) In
RSA_eay_public_encrypt
RSA_eay_private_decrypt
RSA_eay_private_encrypt (signing)
RSA_eay_public_decrypt (signature verification)
(default implementations for RSA_public_encrypt,
RSA_private_decrypt, RSA_private_encrypt, RSA_public_decrypt),
always reject numbers >= n.
[Bodo Moeller]
*) In crypto/rand/md_rand.c, use a new short-time lock CRYPTO_LOCK_RAND2
to synchronize access to 'locking_thread'. This is necessary on
systems where access to 'locking_thread' (an 'unsigned long'
variable) is not atomic.
[Bodo Moeller]
*) In crypto/rand/md_rand.c, set 'locking_thread' to current thread's ID
*before* setting the 'crypto_lock_rand' flag. The previous code had
a race condition if 0 is a valid thread ID.
[Travis Vitek <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 disableed algorithms no
matter what.
[Richard Levitte]
*) Added several new manual pages for SSL_* function.
[Lutz Jaenicke]
Changes between 0.9.5a and 0.9.6 [24 Sep 2000]
*) In ssl23_get_client_hello, generate an error message when faced
with an initial SSL 3.0/TLS record that is too small to contain the
first two bytes of the ClientHello message, i.e. client_version.
(Note that this is a pathologic case that probably has never happened
in real life.) The previous approach was to use the version number
from the record header as a substitute; but our protocol choice
should not depend on that one because it is not authenticated
by the Finished messages.
[Bodo Moeller]
*) More robust randomness gathering functions for Windows.
[Jeffrey Altman <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 presentig variables as well
as functions. This change means that there's n more need
to rebuild the .num files when some algorithms are excluded.
[Richard Levitte]
*) Allow the verify time to be set by an application,
rather than always using the current time.
[Steve Henson]
*) Phase 2 verify code reorganisation. The certificate
verify code now looks up an issuer certificate by a
number of criteria: subject name, authority key id
and key usage. It also verifies self signed certificates
by the same criteria. The main comparison function is
X509_check_issued() which performs these checks.
Lot of changes were necessary in order to support this
without completely rewriting the lookup code.
Authority and subject key identifier are now cached.
The LHASH 'certs' is X509_STORE has now been replaced
by a STACK_OF(X509_OBJECT). This is mainly because an
LHASH can't store or retrieve multiple objects with
the same hash value.
As a result various functions (which were all internal
use only) have changed to handle the new X509_STORE
structure. This will break anything that messed round
with X509_STORE internally.
The functions X509_STORE_add_cert() now checks for an
exact match, rather than just subject name.
The X509_STORE API doesn't directly support the retrieval
of multiple certificates matching a given criteria, however
this can be worked round by performing a lookup first
(which will fill the cache with candidate certificates)
and then examining the cache for matches. This is probably
the best we can do without throwing out X509_LOOKUP
entirely (maybe later...).
The X509_VERIFY_CTX structure has been enhanced considerably.
All certificate lookup operations now go via a get_issuer()
callback. Although this currently uses an X509_STORE it
can be replaced by custom lookups. This is a simple way
to bypass the X509_STORE hackery necessary to make this
work and makes it possible to use more efficient techniques
in future. A very simple version which uses a simple
STACK for its trusted certificate store is also provided
using X509_STORE_CTX_trusted_stack().
The verify_cb() and verify() callbacks now have equivalents
in the X509_STORE_CTX structure.
X509_STORE_CTX also has a 'flags' field which can be used
to customise the verify behaviour.
[Steve Henson]
*) Add new PKCS#7 signing option PKCS7_NOSMIMECAP which
excludes S/MIME capabilities.
[Steve Henson]
*) When a certificate request is read in keep a copy of the
original encoding of the signed data and use it when outputing
again. Signatures then use the original encoding rather than
a decoded, encoded version which may cause problems if the
request is improperly encoded.
[Steve Henson]
*) For consistency with other BIO_puts implementations, call
buffer_write(b, ...) directly in buffer_puts instead of calling
BIO_write(b, ...).
In BIO_puts, increment b->num_write as in BIO_write.
[Peter.Sylvester@EdelWeb.fr]
*) Fix BN_mul_word for the case where the word is 0. (We have to use
BN_zero, we may not return a BIGNUM with an array consisting of
words set to zero.)
[Bodo Moeller]
*) Avoid calling abort() from within the library when problems are
detected, except if preprocessor symbols have been defined
(such as REF_CHECK, BN_DEBUG etc.).
[Bodo Moeller]
*) New openssl application 'rsautl'. This utility can be
used for low level RSA operations. DER public key
BIO/fp routines also added.
[Steve Henson]
*) New Configure entry and patches for compiling on QNX 4.
[Andreas Schneider <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 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 objects.README.
- objects.pl is used to process obj_mac.num and create a new
obj_mac.h.
- obj_dat.pl is used to create a new obj_dat.h, using the data in
obj_mac.h.
This is currently kind of a hack, and the perl code in objects.pl
isn't very elegant, but it works as I intended. The simplest way
to check that it worked correctly is to look in obj_dat.h and
check the array nid_objs and make sure the objects haven't moved
around (this is important!). Additions are OK, as well as
consistent name changes.
[Richard Levitte]
*) Add BSD-style MD5-based passwords to 'openssl passwd' (option '-1').
[Bodo Moeller]
*) Addition of the command line parameter '-rand file' to 'openssl req'.
The given file adds to whatever has already been seeded into the
random pool through the RANDFILE configuration file option or
environment variable, or the default random state file.
[Richard Levitte]
*) mkstack.pl now sorts each macro group into lexical order.
Previously the output order depended on the order the files
appeared in the directory, resulting in needless rewriting
of safestack.h .
[Steve Henson]
*) Patches to make OpenSSL compile under Win32 again. Mostly
work arounds for the VC++ problem that it treats func() as
func(void). Also stripped out the parts of mkdef.pl that
added extra typesafe functions: these no longer exist.
[Steve Henson]
*) Reorganisation of the stack code. The macros are now all
collected in safestack.h . Each macro is defined in terms of
a "stack macro" of the form SKM_<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 insted. Added some
new functions i2d_RSA_NET(), d2i_RSA_NET() etc which are the same
as the old Netscape_RSA functions except they have an additional
'sgckey' parameter which uses the modified algorithm. Also added
an -sgckey command line option to the rsa utility. Thanks to
Adrian Peck <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 wth the exception of the
first that must be a `CONF *' instead of a `LHASH *'.
To make it easer to use the new classes with the old CONF_* functions,
the function CONF_set_default_method is provided.
[Richard Levitte]
*) Add '-tls1' option to 'openssl ciphers', which was already
mentioned in the documentation but had not been implemented.
(This option is not yet really useful because even the additional
experimental TLS 1.0 ciphers are currently treated as SSL 3.0 ciphers.)
[Bodo Moeller]
*) Initial DSO code added into libcrypto for letting OpenSSL (and
OpenSSL-based applications) load shared libraries and bind to
them in a portable way.
[Geoff Thorpe, with contributions from Richard Levitte]
Changes between 0.9.5 and 0.9.5a [1 Apr 2000]
*) Make sure _lrotl and _lrotr are only used with MSVC.
*) Use lock CRYPTO_LOCK_RAND correctly in ssleay_rand_status
(the default implementation of RAND_status).
*) Rename openssl x509 option '-crlext', which was added in 0.9.5,
to '-clrext' (= clear extensions), as intended and documented.
[Bodo Moeller; inconsistency pointed out by Michael Attili
<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, meanining
you effectivly got SSL_OP_SINGLE_DH_USE when using this macro.
[Bodo Moeller]
*) New s_client option -ign_eof: EOF at stdin is ignored, and
'Q' and 'R' lose their special meanings (quit/renegotiate).
This is part of what -quiet does; unlike -quiet, -ign_eof
does not suppress any output.
[Richard Levitte]
*) Add compatibility options to the purpose and trust code. The
purpose X509_PURPOSE_ANY is "any purpose" which automatically
accepts a certificate or CA, this was the previous behaviour,
with all the associated security issues.
X509_TRUST_COMPAT is the old trust behaviour: only and
automatically trust self signed roots in certificate store. A
new trust setting X509_TRUST_DEFAULT is used to specify that
a purpose has no associated trust setting and it should instead
use the value in the default purpose.
[Steve Henson]
*) Fix the PKCS#8 DSA private key code so it decodes keys again
and fix a memory leak.
[Steve Henson]
*) In util/mkerr.pl (which implements 'make errors'), preserve
reason strings from the previous version of the .c file, as
the default to have only downcase letters (and digits) in
automatically generated reasons codes is not always appropriate.
[Bodo Moeller]
*) In ERR_load_ERR_strings(), build an ERR_LIB_SYS error reason table
using strerror. Previously, ERR_reason_error_string() returned
library names as reason strings for SYSerr; but SYSerr is a special
case where small numbers are errno values, not library numbers.
[Bodo Moeller]
*) Add '-dsaparam' option to 'openssl dhparam' application. This
converts DSA parameters into DH parameters. (When creating parameters,
DSA_generate_parameters is used.)
[Bodo Moeller]
*) Include 'length' (recommended exponent length) in C code generated
by 'openssl dhparam -C'.
[Bodo Moeller]
*) The second argument to set_label in perlasm was already being used
so couldn't be used as a "file scope" flag. Moved to third argument
which was free.
[Steve Henson]
*) In PEM_ASN1_write_bio and some other functions, use RAND_pseudo_bytes
instead of RAND_bytes for encryption IVs and salts.
[Bodo Moeller]
*) Include RAND_status() into RAND_METHOD instead of implementing
it only for md_rand.c Otherwise replacing the PRNG by calling
RAND_set_rand_method would be impossible.
[Bodo Moeller]
*) Don't let DSA_generate_key() enter an infinite loop if the random
number generation fails.
[Bodo Moeller]
*) New 'rand' application for creating pseudo-random output.
[Bodo Moeller]
*) Added configuration support for Linux/IA64
[Rolf Haberrecker <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 divsor are
equal (it gave wrong results if (rem=(n1-q*d0)&BN_MASK2) < d0).
[Ulf Möller]
*) Add support for various broken PKCS#8 formats, and command line
options to produce them.
[Steve Henson]
*) New functions BN_CTX_start(), BN_CTX_get() and BT_CTX_end() to
get temporary BIGNUMs from a BN_CTX.
[Ulf Möller]
*) Correct return values in BN_mod_exp_mont() and BN_mod_exp2_mont()
for p == 0.
[Ulf Möller]
*) Change the SSLeay_add_all_*() functions to OpenSSL_add_all_*() and
include a #define from the old name to the new. The original intent
was that statically linked binaries could for example just call
SSLeay_add_all_ciphers() to just add ciphers to the table and not
link with digests. This never worked becayse SSLeay_add_all_digests()
and SSLeay_add_all_ciphers() were in the same source file so calling
one would link with the other. They are now in separate source files.
[Steve Henson]
*) Add a new -notext option to 'ca' and a -pubkey option to 'spkac'.
[Steve Henson]
*) Use a less unusual form of the Miller-Rabin primality test (it used
a binary algorithm for exponentiation integrated into the Miller-Rabin
loop, our standard modexp algorithms are faster).
[Bodo Moeller]
*) Support for the EBCDIC character set completed.
[Martin Kraemer <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 analagous way to the X509v3 functions:
they shouldn't be called directly but wrapper functions should be used
instead.
So we also now have some wrapper functions that call the X509at functions
when passed certificate requests. (TO DO: similar things can be done with
PKCS#7 signed and unsigned attributes, PKCS#12 attributes and a few other
things. Some of these need some d2i or i2d and print functionality
because they handle more complex structures.)
[Steve Henson]
*) Add missing #ifndefs that caused missing symbols when building libssl
as a shared library without RSA. Use #ifndef NO_SSL2 instead of
NO_RSA in ssl/s2*.c.
[Kris Kennaway <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 ANS1_tag2str() to convert an ASN1 tag to a descriptive
ASCII string. This was handled independently in various places before.
[Steve Henson]
*) New functions UTF8_getc() and UTF8_putc() that parse and generate
UTF8 strings a character at a time.
[Steve Henson]
*) Use client_version from client hello to select the protocol
(s23_srvr.c) and for RSA client key exchange verification
(s3_srvr.c), as required by the SSL 3.0/TLS 1.0 specifications.
[Bodo Moeller]
*) Add various utility functions to handle SPKACs, these were previously
handled by poking round in the structure internals. Added new function
NETSCAPE_SPKI_print() to print out SPKAC and a new utility 'spkac' to
print, verify and generate SPKACs. Based on an original idea from
Massimiliano Pala <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 occured while trying to read the rest.
[Bodo Moeller]
*) The PKCS7_ENC_CONTENT_new() function was setting the content type as
NID_pkcs7_encrypted by default: this was wrong since this should almost
always be NID_pkcs7_data. Also modified the PKCS7_set_type() to handle
the encrypted data type: this is a more sensible place to put it and it
allows the PKCS#12 code to be tidied up that duplicated this
functionality.
[Steve Henson]
*) Changed obj_dat.pl script so it takes its input and output files on
the command line. This should avoid shell escape redirection problems
under Win32.
[Steve Henson]
*) Initial support for certificate extension requests, these are included
in things like Xenroll certificate requests. Included functions to allow
extensions to be obtained and added.
[Steve Henson]
*) -crlf option to s_client and s_server for sending newlines as
CRLF (as required by many protocols).
[Bodo Moeller]
Changes between 0.9.3a and 0.9.4 [09 Aug 1999]
*) Install libRSAglue.a when OpenSSL is built with RSAref.
[Ralf S. Engelschall]
*) A few more ``#ifndef NO_FP_API / #endif'' pairs for consistency.
[Andrija Antonijevic <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 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]
#if 0
*) DES CBC did not update the IV. Weird.
[Ben Laurie]
#else
des_cbc_encrypt does not update the IV, but des_ncbc_encrypt does.
Changing the behaviour of the former might break existing programs --
where IV updating is needed, des_ncbc_encrypt can be used.
#endif
*) When bntest is run from "make test" it drives bc to check its
calculations, as well as internally checking them. If an internal check
fails, it needs to cause bc to give a non-zero result or make test carries
on without noticing the failure. Fixed.
[Ben Laurie]
*) DES library cleanups.
[Ulf Möller]
*) Add support for PKCS#5 v2.0 PBE algorithms. This will permit PKCS#8 to be
used with any cipher unlike PKCS#5 v1.5 which can at most handle 64 bit
ciphers. NOTE: although the key derivation function has been verified
against some published test vectors it has not been extensively tested
yet. Added a -v2 "cipher" option to pkcs8 application to allow the use
of v2.0.
[Steve Henson]
*) Instead of "mkdir -p", which is not fully portable, use new
Perl script "util/mkdir-p.pl".
[Bodo Moeller]
*) Rewrite the way password based encryption (PBE) is handled. It used to
assume that the ASN1 AlgorithmIdentifier parameter was a PBEParameter
structure. This was true for the PKCS#5 v1.5 and PKCS#12 PBE algorithms
but doesn't apply to PKCS#5 v2.0 where it can be something else. Now
the 'parameter' field of the AlgorithmIdentifier is passed to the
underlying key generation function so it must do its own ASN1 parsing.
This has also changed the EVP_PBE_CipherInit() function which now has a
'parameter' argument instead of literal salt and iteration count values
and the function EVP_PBE_ALGOR_CipherInit() has been deleted.
[Steve Henson]
*) Support for PKCS#5 v1.5 compatible password based encryption algorithms
and PKCS#8 functionality. New 'pkcs8' application linked to openssl.
Needed to change the PEM_STRING_EVP_PKEY value which was just "PRIVATE
KEY" because this clashed with PKCS#8 unencrypted string. Since this
value was just used as a "magic string" and not used directly its
value doesn't matter.
[Steve Henson]
*) Introduce some semblance of const correctness to BN. Shame C doesn't
support mutable.
[Ben Laurie]
*) "linux-sparc64" configuration (ultrapenguin).
[Ray Miller <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 imbedded
in a comment' is no longer necessary and it doesn't use .err files which
have now been deleted. Also the error code call doesn't have to appear all
on one line (which resulted in some large lines...).
[Steve Henson]
*) Change #include filenames from <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 cipers including rc5, which was forgotten until now.
In order to let the testing shell script know which algorithms
are available, a new (up to now undocumented) command
"openssl list-cipher-commands" is used.
[Bodo Moeller]
*) Bugfix: s_client occasionally would sleep in select() when
it should have checked SSL_pending() first.
[Bodo Moeller]
*) New functions DSA_do_sign and DSA_do_verify to provide access to
the raw DSA values prior to ASN.1 encoding.
[Ulf Möller]
*) Tweaks to Configure
[Niels Poppe <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 comparision
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 everytime: One now can use ``perl Configure
<id>:<details>'', i.e. platform ids are allowed to have details appended
to them (seperated by colons). This is treated as there would be a static
pre-configured entry in Configure's %table under key <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'.
Additonally cleaned up the `make links' target: Remove unnecessary
semicolons, subsequent redundant removes, inline point.sh into mklink.sh
to speed processing and no longer clutter the display with confusing
stuff. Instead only the actually done links are displayed.
[Ralf S. Engelschall]
*) Permit null encryption ciphersuites, used for authentication only. It used
to be necessary to set the preprocessor define SSL_ALLOW_ENULL to do this.
It is now necessary to set SSL_FORBID_ENULL to prevent the use of null
encryption.
[Ben Laurie]
*) Add a bunch of fixes to the PKCS#7 stuff. It used to sometimes reorder
signed attributes when verifying signatures (this would break them),
the detached data encoding was wrong and public keys obtained using
X509_get_pubkey() weren't freed.
[Steve Henson]
*) Add text documentation for the BUFFER functions. Also added a work around
to a Win95 console bug. This was triggered by the password read stuff: the
last character typed gets carried over to the next fread(). If you were
generating a new cert request using 'req' for example then the last
character of the passphrase would be CR which would then enter the first
field as blank.
[Steve Henson]
*) Added the new `Includes OpenSSL Cryptography Software' button as
doc/openssl_button.{gif,html} which is similar in style to the old SSLeay
button and can be used by applications based on OpenSSL to show the
relationship to the OpenSSL project.
[Ralf S. Engelschall]
*) Remove confusing variables in function signatures in files
ssl/ssl_lib.c and ssl/ssl.h.
[Lennart Bong <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's 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 apps. Fixed *lots* of memory
leaks in ssl/ relating to new X509_get_pubkey() behaviour. Also fixes
in apps/ and an unrelated leak in crypto/dsa/dsa_vrf.c
[Steve Henson]
*) Support for RAW extensions where an arbitrary extension can be
created by including its DER encoding. See apps/openssl.cnf for
an example.
[Steve Henson]
*) Make sure latest Perl versions don't interpret some generated C array
code as Perl array code in the crypto/err/err_genc.pl script.
[Lars Weber <3weber@informatik.uni-hamburg.de>]
*) Modify ms/do_ms.bat to not generate assembly language makefiles since
not many people have the assembler. Various Win32 compilation fixes and
update to the INSTALL.W32 file with (hopefully) more accurate Win32
build instructions.
[Steve Henson]
*) Modify configure script 'Configure' to automatically create crypto/date.h
file under Win32 and also build pem.h from pem.org. New script
util/mkfiles.pl to create the MINFO file on environments that can't do a
'make files': perl util/mkfiles.pl >MINFO should work.
[Steve Henson]
*) Major rework of DES function declarations, in the pursuit of correctness
and purity. As a result, many evil casts evaporated, and some weirdness,
too. You may find this causes warnings in your code. Zapping your evil
casts will probably fix them. Mostly.
[Ben Laurie]
*) Fix for a typo in asn1.h. Bug fix to object creation script
obj_dat.pl. It considered a zero in an object definition to mean
"end of object": none of the objects in objects.h have any zeros
so it wasn't spotted.
[Steve Henson, reported by Erwann ABALEA <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 (perl/*):
- ported BN stuff to OpenSSL's different BN library
- made the perl/ source tree CVS-aware
- renamed the package from SSLeay to OpenSSL (the files still contain
their history because I've copied them in the repository)
- removed obsolete files (the test scripts will be replaced
by better Test::Harness variants in the future)
[Ralf S. Engelschall]
*) First cut for a very conservative source tree cleanup:
1. merge various obsolete readme texts into doc/ssleay.txt
where we collect the old documents and readme texts.
2. remove the first part of files where I'm already sure that we no
longer need them because of three reasons: either they are just temporary
files which were left by Eric or they are preserved original files where
I've verified that the diff is also available in the CVS via "cvs diff
-rSSLeay_0_8_1b" or they were renamed (as it was definitely the case for
the crypto/md/ stuff).
[Ralf S. Engelschall]
*) More extension code. Incomplete support for subject and issuer alt
name, issuer and authority key id. Change the i2v function parameters
and add an extra 'crl' parameter in the X509V3_CTX structure: guess
what that's for :-) Fix to ASN1 macro which messed up
IMPLICIT tag and add f_enum.c which adds a2i, i2a for ENUMERATED.
[Steve Henson]
*) Preliminary support for ENUMERATED type. This is largely copied from the
INTEGER code.
[Steve Henson]
*) Add new function, EVP_MD_CTX_copy() to replace frequent use of memcpy.
[Eric A. Young, (from changes to C2Net SSLeay, integrated by Mark Cox)]
*) Make sure `make rehash' target really finds the `openssl' program.
[Ralf S. Engelschall, Matthias Loepfe <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 addding X509 V3 extension support code. Add
files in crypto/x509v3. Move original stuff to crypto/x509v3/old. All this
stuff is currently isolated and isn't even compiled yet.
[Steve Henson]
*) Continuing patches for GeneralizedTime. Fix up certificate and CRL
ASN1 to use ASN1_TIME and modify print routines to use ASN1_TIME_print.
Removed the versions check from X509 routines when loading extensions:
this allows certain broken certificates that don't set the version
properly to be processed.
[Steve Henson]
*) Deal with irritating shit to do with dependencies, in YAAHW (Yet Another
Ad Hoc Way) - Makefile.ssls now all contain local dependencies, which
can still be regenerated with "make depend".
[Ben Laurie]
*) Spelling mistake in C version of CAST-128.
[Ben Laurie, reported by Jeremy Hylton <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 program working (hopefully) and add it to app list. Remove
encryption from sample DSA keys (in case anyone is interested the password
was "1234").
[Steve Henson]
*) Make _all_ *_free functions accept a NULL pointer.
[Frans Heymans <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 construted
EXPLICIT tags. Some non standard certificates use these: they can now
be read in.
[Steve Henson]
*) Merged the various old/obsolete SSLeay documentation files (doc/xxx.doc)
into a single doc/ssleay.txt bundle. This way the information is still
preserved but no longer messes up this directory. Now it's new room for
the new set of documenation files.
[Ralf S. Engelschall]
*) SETs were incorrectly DER encoded. This was a major pain, because they
shared code with SEQUENCEs, which aren't coded the same. This means that
almost everything to do with SETs or SEQUENCEs has either changed name or
number of arguments.
[Ben Laurie, based on a partial fix by GP Jayan <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 a RSA-free SSLeay.
[Andrew Cooke / Interrader Ldt., Ralf S. Engelschall]
*) Fixed nasty rehash problem under `make -f Makefile.ssl links'
when "ssleay" is still not found.
[Ralf S. Engelschall]
*) Added more platforms to Configure: Cray T3E, HPUX 11,
[Ralf S. Engelschall, Beckmann <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>]
diff --git a/Configure b/Configure
index 60386d395987..744b493b96f6 100755
--- a/Configure
+++ b/Configure
@@ -1,2312 +1,2318 @@
:
eval 'exec perl -S $0 ${1+"$@"}'
if $running_under_some_shell;
##
## Configure -- OpenSSL source tree configuration script
##
require 5.000;
use strict;
use File::Compare;
# see INSTALL for instructions.
my $usage="Usage: Configure [no-<cipher> ...] [enable-<cipher> ...] [experimental-<cipher> ...] [-Dxxx] [-lxxx] [-Lxxx] [-fxxx] [-Kxxx] [no-hw-xxx|no-hw] [[no-]threads] [[no-]shared] [[no-]zlib|zlib-dynamic] [no-asm] [no-dso] [no-krb5] [sctp] [386] [--prefix=DIR] [--openssldir=OPENSSLDIR] [--with-xxx[=vvv]] [--test-sanity] os/compiler[:flags]\n";
# Options:
#
# --openssldir install OpenSSL in OPENSSLDIR (Default: DIR/ssl if the
# --prefix option is given; /usr/local/ssl otherwise)
# --prefix prefix for the OpenSSL include, lib and bin directories
# (Default: the OPENSSLDIR directory)
#
# --install_prefix Additional prefix for package builders (empty by
# default). This needn't be set in advance, you can
# just as well use "make INSTALL_PREFIX=/whatever install".
#
# --with-krb5-dir Declare where Kerberos 5 lives. The libraries are expected
# to live in the subdirectory lib/ and the header files in
# include/. A value is required.
# --with-krb5-lib Declare where the Kerberos 5 libraries live. A value is
# required.
# (Default: KRB5_DIR/lib)
# --with-krb5-include Declare where the Kerberos 5 header files live. A
# value is required.
# (Default: KRB5_DIR/include)
# --with-krb5-flavor Declare what flavor of Kerberos 5 is used. Currently
# supported values are "MIT" and "Heimdal". A value is required.
#
# --test-sanity Make a number of sanity checks on the data in this file.
# This is a debugging tool for OpenSSL developers.
#
# --cross-compile-prefix Add specified prefix to binutils components.
#
# 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-asm do not use assembler
# no-dso do not compile in any native shared-library methods. This
# will ensure that all methods just return NULL.
# no-krb5 do not compile in any KRB5 library or code.
# [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
# enable-weak-ssl-ciphers
# Enable EXPORT and LOW SSLv3 ciphers that are disabled by
# default. Note, weak SSLv2 ciphers are unconditionally
# disabled.
# 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 (rsa, idea, rc5, ...)
# -<xxx> +<xxx> compiler options are passed through
#
# DEBUG_SAFESTACK use type-safe stacks to enforce type-safety on stack items
# provided to stack calls. Generates unique stack functions for
# each possible stack type.
# DES_PTR use pointer lookup vs arrays in the DES in crypto/des/des_locl.h
# DES_RISC1 use different DES_ENCRYPT macro that helps reduce register
# dependancies but needs to more registers, good for RISC CPU's
# DES_RISC2 A different RISC variant.
# DES_UNROLL unroll the inner DES loop, sometimes helps, somtimes hinders.
# DES_INT use 'int' instead of 'long' for DES_LONG in crypto/des/des.h
# This is used on the DEC Alpha where long is 8 bytes
# and int is 4
# BN_LLONG use the type 'long long' in crypto/bn/bn.h
# MD2_CHAR use 'char' instead of 'int' for MD2_INT in crypto/md2/md2.h
# MD2_LONG use 'long' instead of 'int' for MD2_INT in crypto/md2/md2.h
# IDEA_SHORT use 'short' instead of 'int' for IDEA_INT in crypto/idea/idea.h
# IDEA_LONG use 'long' instead of 'int' for IDEA_INT in crypto/idea/idea.h
# RC2_SHORT use 'short' instead of 'int' for RC2_INT in crypto/rc2/rc2.h
# RC2_LONG use 'long' instead of 'int' for RC2_INT in crypto/rc2/rc2.h
# RC4_CHAR use 'char' instead of 'int' for RC4_INT in crypto/rc4/rc4.h
# RC4_LONG use 'long' instead of 'int' for RC4_INT in crypto/rc4/rc4.h
# RC4_INDEX define RC4_INDEX in crypto/rc4/rc4_locl.h. This turns on
# array lookups instead of pointer use.
# RC4_CHUNK enables code that handles data aligned at long (natural CPU
# word) boundary.
# RC4_CHUNK_LL enables code that handles data aligned at long long boundary
# (intended for 64-bit CPUs running 32-bit OS).
# BF_PTR use 'pointer arithmatic' for Blowfish (unsafe on Alpha).
# BF_PTR2 intel specific version (generic version is more efficient).
#
# Following are set automatically by this script
#
# MD5_ASM use some extra md5 assember,
# SHA1_ASM use some extra sha1 assember, must define L_ENDIAN for x86
# RMD160_ASM use some extra ripemd160 assember,
# SHA256_ASM sha256_block is implemented in assembler
# SHA512_ASM sha512_block is implemented in assembler
# AES_ASM ASE_[en|de]crypt is implemented in assembler
# Minimum warning options... any contributions to OpenSSL should at least get
# past these.
my $gcc_devteam_warn = "-Wall -pedantic -DPEDANTIC -Wno-long-long -Wsign-compare -Wmissing-prototypes -Wshadow -Wformat -Wundef -Werror -DCRYPTO_MDEBUG_ALL -DCRYPTO_MDEBUG_ABORT -DREF_CHECK -DOPENSSL_NO_DEPRECATED";
# TODO(openssl-team): fix problems and investigate if (at least) the following
# warnings can also be enabled:
# -Wconditional-uninitialized, -Wswitch-enum, -Wunused-macros,
# -Wmissing-field-initializers, -Wmissing-variable-declarations,
# -Wincompatible-pointer-types-discards-qualifiers, -Wcast-align,
# -Wunreachable-code -Wunused-parameter -Wlanguage-extension-token
# -Wextended-offsetof
my $clang_disabled_warnings = "-Wno-unused-parameter -Wno-missing-field-initializers -Wno-language-extension-token -Wno-extended-offsetof";
# 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: -Wconditional-uninitialized,
# -Wswitch-enum, -Wunused-macros, -Wmissing-field-initializers,
# -Wmissing-variable-declarations,
# -Wincompatible-pointer-types-discards-qualifiers, -Wcast-align,
# -Wunreachable-code -Wunused-parameter -Wlanguage-extension-token
# -Wextended-offsetof
my $clang_devteam_warn = "-Wno-unused-parameter -Wno-missing-field-initializers -Wno-language-extension-token -Wno-extended-offsetof -Qunused-arguments";
# Warn that "make depend" should be run?
my $warn_make_depend = 0;
my $strict_warnings = 0;
my $x86_gcc_des="DES_PTR DES_RISC1 DES_UNROLL";
# MD2_CHAR slags pentium pros
my $x86_gcc_opts="RC4_INDEX MD2_INT";
# MODIFY THESE PARAMETERS IF YOU ARE GOING TO USE THE 'util/speed.sh SCRIPT
# Don't worry about these normally
my $tcc="cc";
my $tflags="-fast -Xa";
my $tbn_mul="";
my $tlib="-lnsl -lsocket";
#$bits1="SIXTEEN_BIT ";
#$bits2="THIRTY_TWO_BIT ";
my $bits1="THIRTY_TWO_BIT ";
my $bits2="SIXTY_FOUR_BIT ";
my $x86_asm="x86cpuid.o:bn-586.o co-586.o x86-mont.o x86-gf2m.o::des-586.o crypt586.o:aes-586.o vpaes-x86.o aesni-x86.o:bf-586.o:md5-586.o:sha1-586.o sha256-586.o sha512-586.o:cast-586.o:rc4-586.o:rmd-586.o:rc5-586.o:wp_block.o wp-mmx.o:cmll-x86.o:ghash-x86.o:";
my $x86_elf_asm="$x86_asm:elf";
my $x86_64_asm="x86_64cpuid.o:x86_64-gcc.o x86_64-mont.o x86_64-mont5.o x86_64-gf2m.o rsaz_exp.o rsaz-x86_64.o rsaz-avx2.o:ecp_nistz256.o ecp_nistz256-x86_64.o::aes-x86_64.o vpaes-x86_64.o bsaes-x86_64.o aesni-x86_64.o aesni-sha1-x86_64.o aesni-sha256-x86_64.o aesni-mb-x86_64.o::md5-x86_64.o:sha1-x86_64.o sha256-x86_64.o sha512-x86_64.o sha1-mb-x86_64.o sha256-mb-x86_64.o::rc4-x86_64.o rc4-md5-x86_64.o:::wp-x86_64.o:cmll-x86_64.o cmll_misc.o:ghash-x86_64.o aesni-gcm-x86_64.o:";
my $ia64_asm="ia64cpuid.o:bn-ia64.o ia64-mont.o:::aes_core.o aes_cbc.o aes-ia64.o::md5-ia64.o:sha1-ia64.o sha256-ia64.o sha512-ia64.o::rc4-ia64.o rc4_skey.o:::::ghash-ia64.o::void";
my $sparcv9_asm="sparcv9cap.o sparccpuid.o:bn-sparcv9.o sparcv9-mont.o sparcv9a-mont.o vis3-mont.o sparct4-mont.o sparcv9-gf2m.o::des_enc-sparc.o fcrypt_b.o dest4-sparcv9.o:aes_core.o aes_cbc.o aes-sparcv9.o aest4-sparcv9.o::md5-sparcv9.o:sha1-sparcv9.o sha256-sparcv9.o sha512-sparcv9.o::::::camellia.o cmll_misc.o cmll_cbc.o cmllt4-sparcv9.o:ghash-sparcv9.o::void";
my $sparcv8_asm=":sparcv8.o::des_enc-sparc.o fcrypt_b.o:::::::::::::void";
my $alpha_asm="alphacpuid.o:bn_asm.o alpha-mont.o::::::sha1-alpha.o:::::::ghash-alpha.o::void";
my $mips64_asm=":bn-mips.o mips-mont.o:::aes_cbc.o aes-mips.o:::sha1-mips.o sha256-mips.o sha512-mips.o::::::::";
my $mips32_asm=$mips64_asm; $mips32_asm =~ s/\s*sha512\-mips\.o//;
my $s390x_asm="s390xcap.o s390xcpuid.o:bn-s390x.o s390x-mont.o s390x-gf2m.o:::aes-s390x.o aes-ctr.o aes-xts.o:::sha1-s390x.o sha256-s390x.o sha512-s390x.o::rc4-s390x.o:::::ghash-s390x.o:";
my $armv4_asm="armcap.o armv4cpuid.o:bn_asm.o armv4-mont.o armv4-gf2m.o:::aes_cbc.o aes-armv4.o bsaes-armv7.o aesv8-armx.o:::sha1-armv4-large.o sha256-armv4.o sha512-armv4.o:::::::ghash-armv4.o ghashv8-armx.o::void";
my $aarch64_asm="armcap.o arm64cpuid.o mem_clr.o::::aes_core.o aes_cbc.o aesv8-armx.o:::sha1-armv8.o sha256-armv8.o sha512-armv8.o:::::::ghashv8-armx.o:";
my $parisc11_asm="pariscid.o:bn_asm.o parisc-mont.o:::aes_core.o aes_cbc.o aes-parisc.o:::sha1-parisc.o sha256-parisc.o sha512-parisc.o::rc4-parisc.o:::::ghash-parisc.o::32";
my $parisc20_asm="pariscid.o:pa-risc2W.o parisc-mont.o:::aes_core.o aes_cbc.o aes-parisc.o:::sha1-parisc.o sha256-parisc.o sha512-parisc.o::rc4-parisc.o:::::ghash-parisc.o::64";
my $ppc64_asm="ppccpuid.o ppccap.o:bn-ppc.o ppc-mont.o ppc64-mont.o:::aes_core.o aes_cbc.o aes-ppc.o vpaes-ppc.o aesp8-ppc.o:::sha1-ppc.o sha256-ppc.o sha512-ppc.o sha256p8-ppc.o sha512p8-ppc.o:::::::ghashp8-ppc.o:";
my $ppc32_asm=$ppc64_asm;
my $no_asm="::::::::::::::::void";
# 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?
my $BSDthreads="-pthread -D_THREAD_SAFE -D_REENTRANT";
#config-string $cc : $cflags : $unistd : $thread_cflag : $sys_id : $lflags : $bn_ops : $cpuid_obj : $bn_obj : $ec_obj : $des_obj : $aes_obj : $bf_obj : $md5_obj : $sha1_obj : $cast_obj : $rc4_obj : $rmd160_obj : $rc5_obj : $wp_obj : $cmll_obj : $modes_obj : $engines_obj : $dso_scheme : $shared_target : $shared_cflag : $shared_ldflag : $shared_extension : $ranlib : $arflags : $multilib
my %table=(
# File 'TABLE' (created by 'make TABLE') contains the data from this list,
# formatted for better readability.
#"b", "${tcc}:${tflags}::${tlib}:${bits1}:${tbn_mul}::",
#"bl-4c-2c", "${tcc}:${tflags}::${tlib}:${bits1}BN_LLONG RC4_CHAR MD2_CHAR:${tbn_mul}::",
#"bl-4c-ri", "${tcc}:${tflags}::${tlib}:${bits1}BN_LLONG RC4_CHAR RC4_INDEX:${tbn_mul}::",
#"b2-is-ri-dp", "${tcc}:${tflags}::${tlib}:${bits2}IDEA_SHORT RC4_INDEX DES_PTR:${tbn_mul}::",
# Our development configs
"purify", "purify gcc:-g -DPURIFY -Wall::(unknown)::-lsocket -lnsl::::",
"debug", "gcc:-DBN_DEBUG -DREF_CHECK -DCONF_DEBUG -DBN_CTX_DEBUG -DCRYPTO_MDEBUG -DOPENSSL_NO_ASM -ggdb -g2 -Wformat -Wshadow -Wmissing-prototypes -Wmissing-declarations -Werror::(unknown)::-lefence::::",
"debug-ben", "gcc:$gcc_devteam_warn -DBN_DEBUG -DREF_CHECK -DCONF_DEBUG -DBN_CTX_DEBUG -DCRYPTO_MDEBUG -DDEBUG_SAFESTACK -O2 -pipe::(unknown):::::",
"debug-ben-openbsd","gcc:-DBN_DEBUG -DREF_CHECK -DCONF_DEBUG -DBN_CTX_DEBUG -DCRYPTO_MDEBUG -DPEDANTIC -DDEBUG_SAFESTACK -DOPENSSL_OPENBSD_DEV_CRYPTO -DOPENSSL_NO_ASM -O2 -pedantic -Wall -Wshadow -Werror -pipe::(unknown)::::",
"debug-ben-openbsd-debug","gcc:-DBN_DEBUG -DREF_CHECK -DCONF_DEBUG -DBN_CTX_DEBUG -DCRYPTO_MDEBUG -DPEDANTIC -DDEBUG_SAFESTACK -DOPENSSL_OPENBSD_DEV_CRYPTO -DOPENSSL_NO_ASM -g3 -O2 -pedantic -Wall -Wshadow -Werror -pipe::(unknown)::::",
"debug-ben-debug", "gcc44:$gcc_devteam_warn -DBN_DEBUG -DCONF_DEBUG -DDEBUG_SAFESTACK -DDEBUG_UNUSED -g3 -O2 -pipe::(unknown)::::::",
"debug-ben-debug-64", "gcc:$gcc_devteam_warn -Wno-error=overlength-strings -DBN_DEBUG -DCONF_DEBUG -DDEBUG_SAFESTACK -DDEBUG_UNUSED -g3 -O3 -pipe::${BSDthreads}:::SIXTY_FOUR_BIT_LONG RC4_CHUNK DES_INT DES_UNROLL:${x86_64_asm}:elf:dlfcn:bsd-gcc-shared:-fPIC::.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)",
"debug-ben-macos", "cc:$gcc_devteam_warn -arch i386 -DBN_DEBUG -DCONF_DEBUG -DDEBUG_SAFESTACK -DDEBUG_UNUSED -DOPENSSL_THREADS -D_REENTRANT -DDSO_DLFCN -DHAVE_DLFCN_H -O3 -DL_ENDIAN -g3 -pipe::(unknown)::-Wl,-search_paths_first::::",
"debug-ben-macos-gcc46", "gcc-mp-4.6:$gcc_devteam_warn -Wconversion -DBN_DEBUG -DCONF_DEBUG -DDEBUG_SAFESTACK -DDEBUG_UNUSED -DOPENSSL_THREADS -D_REENTRANT -DDSO_DLFCN -DHAVE_DLFCN_H -O3 -DL_ENDIAN -g3 -pipe::(unknown)::::::",
"debug-ben-darwin64","cc:$gcc_devteam_warn -g -Wno-language-extension-token -Wno-extended-offsetof -arch x86_64 -O3 -DL_ENDIAN -Wall::-D_REENTRANT:MACOSX:-Wl,-search_paths_first%:SIXTY_FOUR_BIT_LONG RC4_CHAR RC4_CHUNK DES_INT DES_UNROLL:".eval{my $asm=$x86_64_asm;$asm=~s/rc4\-[^:]+//;$asm}.":macosx:dlfcn:darwin-shared:-fPIC -fno-common:-arch x86_64 -dynamiclib:.\$(SHLIB_MAJOR).\$(SHLIB_MINOR).dylib",
"debug-ben-debug-64-clang", "clang:$gcc_devteam_warn -Wno-error=overlength-strings -Wno-error=extended-offsetof -Qunused-arguments -DBN_DEBUG -DCONF_DEBUG -DDEBUG_SAFESTACK -DDEBUG_UNUSED -g3 -O3 -pipe::${BSDthreads}:::SIXTY_FOUR_BIT_LONG RC4_CHUNK DES_INT DES_UNROLL:${x86_64_asm}:elf:dlfcn:bsd-gcc-shared:-fPIC::.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)",
"debug-ben-no-opt", "gcc: -Wall -Wmissing-prototypes -Wstrict-prototypes -Wmissing-declarations -DDEBUG_SAFESTACK -DCRYPTO_MDEBUG -Werror -DL_ENDIAN -DTERMIOS -Wall -g3::(unknown)::::::",
"debug-ben-strict", "gcc:-DBN_DEBUG -DREF_CHECK -DCONF_DEBUG -DBN_CTX_DEBUG -DCRYPTO_MDEBUG -DCONST_STRICT -O2 -Wall -Wshadow -Werror -Wpointer-arith -Wcast-qual -Wwrite-strings -pipe::(unknown)::::::",
"debug-rse","cc:-DTERMIOS -DL_ENDIAN -pipe -O -g -ggdb3 -Wall::(unknown):::BN_LLONG ${x86_gcc_des} ${x86_gcc_opts}:${x86_elf_asm}",
"debug-bodo", "gcc:$gcc_devteam_warn -Wno-error=overlength-strings -DBN_DEBUG -DBN_DEBUG_RAND -DCONF_DEBUG -DBIO_PAIR_DEBUG -m64 -DL_ENDIAN -DTERMIO -g -DMD32_REG_T=int::-D_REENTRANT::-ldl:SIXTY_FOUR_BIT_LONG RC4_CHUNK DES_INT DES_UNROLL:${x86_64_asm}:elf:dlfcn:linux-shared:-fPIC:-m64:.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR):::64",
"debug-steve64", "gcc:$gcc_devteam_warn -m64 -DL_ENDIAN -DTERMIO -DCONF_DEBUG -DDEBUG_SAFESTACK -Wno-overlength-strings -g::-D_REENTRANT::-ldl:SIXTY_FOUR_BIT_LONG RC4_CHUNK DES_INT DES_UNROLL:${x86_64_asm}:elf:dlfcn:linux-shared:-fPIC:-m64:.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)",
"debug-steve32", "gcc:$gcc_devteam_warn -m32 -DL_ENDIAN -DCONF_DEBUG -DDEBUG_SAFESTACK -Wno-overlength-strings -g -pipe::-D_REENTRANT::-rdynamic -ldl:BN_LLONG ${x86_gcc_des} ${x86_gcc_opts}:${x86_elf_asm}:dlfcn:linux-shared:-fPIC:-m32:.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)",
"debug-steve-opt", "gcc:$gcc_devteam_warn -m64 -O3 -DL_ENDIAN -DTERMIO -DCONF_DEBUG -DDEBUG_SAFESTACK -g::-D_REENTRANT::-ldl:SIXTY_FOUR_BIT_LONG RC4_CHUNK DES_INT DES_UNROLL:${x86_64_asm}:elf:dlfcn:linux-shared:-fPIC:-m64:.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)",
"debug-levitte-linux-elf","gcc:-DLEVITTE_DEBUG -DBN_DEBUG -DREF_CHECK -DCONF_DEBUG -DCRYPTO_MDEBUG -DL_ENDIAN -ggdb -g3 -Wall::-D_REENTRANT::-ldl:BN_LLONG ${x86_gcc_des} ${x86_gcc_opts}:${x86_elf_asm}:dlfcn:linux-shared:-fPIC::.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)",
"debug-levitte-linux-noasm","gcc:-DLEVITTE_DEBUG -DBN_DEBUG -DREF_CHECK -DCONF_DEBUG -DCRYPTO_MDEBUG -DOPENSSL_NO_ASM -DL_ENDIAN -ggdb -g3 -Wall::-D_REENTRANT::-ldl:BN_LLONG ${x86_gcc_des} ${x86_gcc_opts}:${no_asm}:dlfcn:linux-shared:-fPIC::.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)",
"debug-levitte-linux-elf-extreme","gcc:-DLEVITTE_DEBUG -DREF_CHECK -DCONF_DEBUG -DBN_DEBUG -DBN_DEBUG_RAND -DCRYPTO_MDEBUG -DENGINE_CONF_DEBUG -DL_ENDIAN -DPEDANTIC -ggdb -g3 -pedantic -ansi -Wall -W -Wundef -Wshadow -Wcast-align -Wstrict-prototypes -Wmissing-prototypes -Wno-long-long -Wundef -Wconversion -pipe::-D_REENTRANT::-ldl:BN_LLONG ${x86_gcc_des} ${x86_gcc_opts}:${x86_elf_asm}:dlfcn:linux-shared:-fPIC::.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)",
"debug-levitte-linux-noasm-extreme","gcc:-DLEVITTE_DEBUG -DREF_CHECK -DCONF_DEBUG -DBN_DEBUG -DBN_DEBUG_RAND -DCRYPTO_MDEBUG -DENGINE_CONF_DEBUG -DOPENSSL_NO_ASM -DL_ENDIAN -DPEDANTIC -ggdb -g3 -pedantic -ansi -Wall -W -Wundef -Wshadow -Wcast-align -Wstrict-prototypes -Wmissing-prototypes -Wno-long-long -Wundef -Wconversion -pipe::-D_REENTRANT::-ldl:BN_LLONG ${x86_gcc_des} ${x86_gcc_opts}:${no_asm}:dlfcn:linux-shared:-fPIC::.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)",
"debug-geoff32","gcc:-DBN_DEBUG -DBN_DEBUG_RAND -DBN_STRICT -DPURIFY -DOPENSSL_NO_DEPRECATED -DOPENSSL_NO_ASM -DOPENSSL_NO_INLINE_ASM -DL_ENDIAN -DTERMIO -DPEDANTIC -O1 -ggdb2 -Wall -Werror -Wundef -pedantic -Wshadow -Wpointer-arith -Wbad-function-cast -Wcast-align -Wsign-compare -Wmissing-prototypes -Wmissing-declarations -Wno-long-long::-D_REENTRANT::-ldl:BN_LLONG:${no_asm}:dlfcn:linux-shared:-fPIC::.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)",
"debug-geoff64","gcc:-DBN_DEBUG -DBN_DEBUG_RAND -DBN_STRICT -DPURIFY -DOPENSSL_NO_DEPRECATED -DOPENSSL_NO_ASM -DOPENSSL_NO_INLINE_ASM -DL_ENDIAN -DTERMIO -DPEDANTIC -O1 -ggdb2 -Wall -Werror -Wundef -pedantic -Wshadow -Wpointer-arith -Wbad-function-cast -Wcast-align -Wsign-compare -Wmissing-prototypes -Wmissing-declarations -Wno-long-long::-D_REENTRANT::-ldl:SIXTY_FOUR_BIT_LONG RC4_CHAR RC4_CHUNK DES_INT DES_UNROLL BF_PTR:${no_asm}:dlfcn:linux-shared:-fPIC::.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)",
"debug-linux-pentium","gcc:-DBN_DEBUG -DREF_CHECK -DCONF_DEBUG -DBN_CTX_DEBUG -DCRYPTO_MDEBUG -DL_ENDIAN -g -mcpu=pentium -Wall::-D_REENTRANT::-ldl:BN_LLONG ${x86_gcc_des} ${x86_gcc_opts}:${x86_elf_asm}:dlfcn",
"debug-linux-ppro","gcc:-DBN_DEBUG -DREF_CHECK -DCONF_DEBUG -DBN_CTX_DEBUG -DCRYPTO_MDEBUG -DL_ENDIAN -g -mcpu=pentiumpro -Wall::-D_REENTRANT::-ldl:BN_LLONG ${x86_gcc_des} ${x86_gcc_opts}:${x86_elf_asm}:dlfcn",
"debug-linux-elf","gcc:-DBN_DEBUG -DREF_CHECK -DCONF_DEBUG -DBN_CTX_DEBUG -DCRYPTO_MDEBUG -DL_ENDIAN -g -march=i486 -Wall::-D_REENTRANT::-lefence -ldl:BN_LLONG ${x86_gcc_des} ${x86_gcc_opts}:${x86_elf_asm}:dlfcn:linux-shared:-fPIC::.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)",
"debug-linux-elf-noefence","gcc:-DBN_DEBUG -DREF_CHECK -DCONF_DEBUG -DBN_CTX_DEBUG -DCRYPTO_MDEBUG -DL_ENDIAN -g -march=i486 -Wall::-D_REENTRANT::-ldl:BN_LLONG ${x86_gcc_des} ${x86_gcc_opts}:${x86_elf_asm}:dlfcn:linux-shared:-fPIC::.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)",
"debug-linux-ia32-aes", "gcc:-DAES_EXPERIMENTAL -DL_ENDIAN -O3 -fomit-frame-pointer -Wall::-D_REENTRANT::-ldl:BN_LLONG ${x86_gcc_des} ${x86_gcc_opts}:x86cpuid.o:bn-586.o co-586.o x86-mont.o::des-586.o crypt586.o:aes_x86core.o aes_cbc.o aesni-x86.o:bf-586.o:md5-586.o:sha1-586.o sha256-586.o sha512-586.o:cast-586.o:rc4-586.o:rmd-586.o:rc5-586.o:wp_block.o wp-mmx.o::ghash-x86.o::elf:dlfcn:linux-shared:-fPIC::.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)",
"debug-linux-generic32","gcc:-DBN_DEBUG -DREF_CHECK -DCONF_DEBUG -DCRYPTO_MDEBUG -g -Wall::-D_REENTRANT::-ldl:BN_LLONG RC4_CHAR RC4_CHUNK DES_INT DES_UNROLL BF_PTR:${no_asm}:dlfcn:linux-shared:-fPIC::.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)",
"debug-linux-generic64","gcc:-DBN_DEBUG -DREF_CHECK -DCONF_DEBUG -DCRYPTO_MDEBUG -DTERMIO -g -Wall::-D_REENTRANT::-ldl:SIXTY_FOUR_BIT_LONG RC4_CHAR RC4_CHUNK DES_INT DES_UNROLL BF_PTR:${no_asm}:dlfcn:linux-shared:-fPIC::.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)",
"debug-linux-x86_64","gcc:-DBN_DEBUG -DREF_CHECK -DCONF_DEBUG -DCRYPTO_MDEBUG -m64 -DL_ENDIAN -g -Wall::-D_REENTRANT::-ldl:SIXTY_FOUR_BIT_LONG RC4_CHUNK DES_INT DES_UNROLL:${x86_64_asm}:elf:dlfcn:linux-shared:-fPIC:-m64:.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR):::64",
"dist", "cc:-O::(unknown)::::::",
# Basic configs that should work on any (32 and less bit) box
"gcc", "gcc:-O3::(unknown):::BN_LLONG:::",
"cc", "cc:-O::(unknown)::::::",
####VOS Configurations
"vos-gcc","gcc:-O3 -Wall -DOPENSSL_SYSNAME_VOS -D_POSIX_C_SOURCE=200112L -D_BSD -D_VOS_EXTENDED_NAMES -DB_ENDIAN::(unknown):VOS:-Wl,-map:BN_LLONG:${no_asm}:::::.so:",
"debug-vos-gcc","gcc:-O0 -g -Wall -DOPENSSL_SYSNAME_VOS -D_POSIX_C_SOURCE=200112L -D_BSD -D_VOS_EXTENDED_NAMES -DB_ENDIAN -DBN_DEBUG -DREF_CHECK -DCONF_DEBUG -DCRYPTO_MDEBUG::(unknown):VOS:-Wl,-map:BN_LLONG:${no_asm}:::::.so:",
#### Solaris x86 with GNU C setups
# -DOPENSSL_NO_INLINE_ASM switches off inline assembler. We have to do it
# here because whenever GNU C instantiates an assembler template it
# surrounds it with #APP #NO_APP comment pair which (at least Solaris
# 7_x86) /usr/ccs/bin/as fails to assemble with "Illegal mnemonic"
# error message.
"solaris-x86-gcc","gcc:-O3 -fomit-frame-pointer -march=pentium -Wall -DL_ENDIAN -DOPENSSL_NO_INLINE_ASM::-D_REENTRANT::-lsocket -lnsl -ldl:BN_LLONG ${x86_gcc_des} ${x86_gcc_opts}:${x86_elf_asm}:dlfcn:solaris-shared:-fPIC:-shared:.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)",
# -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@fy.chalmers.se>
"solaris64-x86_64-gcc","gcc:-m64 -O3 -Wall -DL_ENDIAN::-D_REENTRANT::-lsocket -lnsl -ldl:SIXTY_FOUR_BIT_LONG RC4_CHUNK DES_INT DES_UNROLL:${x86_64_asm}:elf:dlfcn:solaris-shared:-fPIC:-m64 -shared -static-libgcc:.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR):::/64",
#### Solaris x86 with Sun C setups
"solaris-x86-cc","cc:-fast -xarch=generic -O -Xa::-D_REENTRANT::-lsocket -lnsl -ldl:BN_LLONG RC4_CHAR RC4_CHUNK DES_PTR DES_UNROLL BF_PTR:${no_asm}:dlfcn:solaris-shared:-KPIC:-G -dy -z text:.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)",
"solaris64-x86_64-cc","cc:-fast -xarch=amd64 -xstrconst -Xa -DL_ENDIAN::-D_REENTRANT::-lsocket -lnsl -ldl:SIXTY_FOUR_BIT_LONG RC4_CHUNK DES_INT DES_UNROLL:${x86_64_asm}:elf:dlfcn:solaris-shared:-KPIC:-xarch=amd64 -G -dy -z text:.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR):::/64",
#### SPARC Solaris with GNU C setups
"solaris-sparcv7-gcc","gcc:-O3 -fomit-frame-pointer -Wall -DB_ENDIAN -DBN_DIV2W::-D_REENTRANT::-lsocket -lnsl -ldl:BN_LLONG RC4_CHAR RC4_CHUNK DES_UNROLL BF_PTR:${no_asm}:dlfcn:solaris-shared:-fPIC:-shared:.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)",
"solaris-sparcv8-gcc","gcc:-mcpu=v8 -O3 -fomit-frame-pointer -Wall -DB_ENDIAN -DBN_DIV2W::-D_REENTRANT::-lsocket -lnsl -ldl:BN_LLONG RC4_CHAR RC4_CHUNK DES_UNROLL BF_PTR:${sparcv8_asm}:dlfcn:solaris-shared:-fPIC:-shared:.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)",
# -m32 should be safe to add as long as driver recognizes -mcpu=ultrasparc
"solaris-sparcv9-gcc","gcc:-m32 -mcpu=ultrasparc -O3 -fomit-frame-pointer -Wall -DB_ENDIAN -DBN_DIV2W::-D_REENTRANT:ULTRASPARC:-lsocket -lnsl -ldl:BN_LLONG RC4_CHAR RC4_CHUNK DES_UNROLL BF_PTR:${sparcv9_asm}:dlfcn:solaris-shared:-fPIC:-shared:.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)",
"solaris64-sparcv9-gcc","gcc:-m64 -mcpu=ultrasparc -O3 -Wall -DB_ENDIAN::-D_REENTRANT:ULTRASPARC:-lsocket -lnsl -ldl:BN_LLONG RC4_CHAR RC4_CHUNK DES_INT DES_PTR DES_RISC1 DES_UNROLL BF_PTR:${sparcv9_asm}:dlfcn:solaris-shared:-fPIC:-m64 -shared:.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR):::/64",
####
"debug-solaris-sparcv8-gcc","gcc:-DBN_DEBUG -DREF_CHECK -DCONF_DEBUG -DBN_CTX_DEBUG -DCRYPTO_MDEBUG_ALL -O -g -mcpu=v8 -Wall -DB_ENDIAN::-D_REENTRANT::-lsocket -lnsl -ldl:BN_LLONG RC4_CHAR RC4_CHUNK DES_UNROLL BF_PTR:${sparcv8_asm}:dlfcn:solaris-shared:-fPIC:-shared:.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)",
"debug-solaris-sparcv9-gcc","gcc:-DBN_DEBUG -DREF_CHECK -DCONF_DEBUG -DBN_CTX_DEBUG -DCRYPTO_MDEBUG_ALL -DPEDANTIC -O -g -mcpu=ultrasparc -pedantic -ansi -Wall -Wshadow -Wno-long-long -D__EXTENSIONS__ -DB_ENDIAN -DBN_DIV2W::-D_REENTRANT:ULTRASPARC:-lsocket -lnsl -ldl:BN_LLONG RC4_CHAR RC4_CHUNK DES_UNROLL BF_PTR:${sparcv9_asm}:dlfcn:solaris-shared:-fPIC:-shared:.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)",
#### 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","cc:-xO5 -xstrconst -xdepend -Xa -DB_ENDIAN -DBN_DIV2W::-D_REENTRANT::-lsocket -lnsl -ldl:BN_LLONG RC4_CHAR RC4_CHUNK DES_PTR DES_RISC1 DES_UNROLL BF_PTR:${no_asm}:dlfcn:solaris-shared:-KPIC:-G -dy -z text:.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)",
"solaris-sparcv8-cc","cc:-xarch=v8 -xO5 -xstrconst -xdepend -Xa -DB_ENDIAN -DBN_DIV2W::-D_REENTRANT::-lsocket -lnsl -ldl:BN_LLONG RC4_CHAR RC4_CHUNK DES_PTR DES_RISC1 DES_UNROLL BF_PTR:${sparcv8_asm}:dlfcn:solaris-shared:-KPIC:-G -dy -z text:.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)",
"solaris-sparcv9-cc","cc:-xtarget=ultra -xarch=v8plus -xO5 -xstrconst -xdepend -Xa -DB_ENDIAN -DBN_DIV2W::-D_REENTRANT:ULTRASPARC:-lsocket -lnsl -ldl:BN_LLONG RC4_CHAR RC4_CHUNK_LL DES_PTR DES_RISC1 DES_UNROLL BF_PTR:${sparcv9_asm}:dlfcn:solaris-shared:-KPIC:-G -dy -z text:.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)",
"solaris64-sparcv9-cc","cc:-xtarget=ultra -xarch=v9 -xO5 -xstrconst -xdepend -Xa -DB_ENDIAN::-D_REENTRANT:ULTRASPARC:-lsocket -lnsl -ldl:BN_LLONG RC4_CHAR RC4_CHUNK DES_INT DES_PTR DES_RISC1 DES_UNROLL BF_PTR:${sparcv9_asm}:dlfcn:solaris-shared:-KPIC:-xarch=v9 -G -dy -z text:.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR):::/64",
####
"debug-solaris-sparcv8-cc","cc:-DBN_DEBUG -DREF_CHECK -DCONF_DEBUG -DBN_CTX_DEBUG -DCRYPTO_MDEBUG_ALL -xarch=v8 -g -O -xstrconst -Xa -DB_ENDIAN -DBN_DIV2W::-D_REENTRANT::-lsocket -lnsl -ldl:BN_LLONG RC4_CHAR RC4_CHUNK DES_PTR DES_RISC1 DES_UNROLL BF_PTR:${sparcv8_asm}:dlfcn:solaris-shared:-KPIC:-G -dy -z text:.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)",
"debug-solaris-sparcv9-cc","cc:-DBN_DEBUG -DREF_CHECK -DCONF_DEBUG -DBN_CTX_DEBUG -DCRYPTO_MDEBUG_ALL -xtarget=ultra -xarch=v8plus -g -O -xstrconst -Xa -DB_ENDIAN -DBN_DIV2W::-D_REENTRANT:ULTRASPARC:-lsocket -lnsl -ldl:BN_LLONG RC4_CHAR RC4_CHUNK_LL DES_PTR DES_RISC1 DES_UNROLL BF_PTR:${sparcv9_asm}:dlfcn:solaris-shared:-KPIC:-G -dy -z text:.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)",
#### SunOS configs, assuming sparc for the gcc one.
#"sunos-cc", "cc:-O4 -DNOPROTO -DNOCONST::(unknown):SUNOS::DES_UNROLL:${no_asm}::",
"sunos-gcc","gcc:-O3 -mcpu=v8 -Dssize_t=int::(unknown):SUNOS::BN_LLONG RC4_CHAR RC4_CHUNK DES_UNROLL DES_PTR DES_RISC1:${no_asm}::",
#### IRIX 5.x configs
# -mips2 flag is added by ./config when appropriate.
"irix-gcc","gcc:-O3 -DB_ENDIAN::(unknown):::BN_LLONG MD2_CHAR RC4_INDEX RC4_CHAR RC4_CHUNK DES_UNROLL DES_RISC2 DES_PTR BF_PTR:${mips32_asm}:o32:dlfcn:irix-shared:::.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)",
"irix-cc", "cc:-O2 -use_readonly_const -DB_ENDIAN::(unknown):::BN_LLONG RC4_CHAR RC4_CHUNK DES_PTR DES_RISC2 DES_UNROLL BF_PTR:${mips32_asm}:o32:dlfcn:irix-shared:::.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)",
#### IRIX 6.x configs
# Only N32 and N64 ABIs are supported. If you need O32 ABI build, invoke
# './Configure irix-cc -o32' manually.
"irix-mips3-gcc","gcc:-mabi=n32 -O3 -DB_ENDIAN -DBN_DIV3W::-D_SGI_MP_SOURCE:::MD2_CHAR RC4_INDEX RC4_CHAR RC4_CHUNK_LL DES_UNROLL DES_RISC2 DES_PTR BF_PTR SIXTY_FOUR_BIT:${mips64_asm}:n32:dlfcn:irix-shared::-mabi=n32:.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR):::32",
"irix-mips3-cc", "cc:-n32 -mips3 -O2 -use_readonly_const -G0 -rdata_shared -DB_ENDIAN -DBN_DIV3W::-D_SGI_MP_SOURCE:::DES_PTR RC4_CHAR RC4_CHUNK_LL DES_RISC2 DES_UNROLL BF_PTR SIXTY_FOUR_BIT:${mips64_asm}:n32:dlfcn:irix-shared::-n32:.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR):::32",
# N64 ABI builds.
"irix64-mips4-gcc","gcc:-mabi=64 -mips4 -O3 -DB_ENDIAN -DBN_DIV3W::-D_SGI_MP_SOURCE:::RC4_CHAR RC4_CHUNK DES_RISC2 DES_UNROLL SIXTY_FOUR_BIT_LONG:${mips64_asm}:64:dlfcn:irix-shared::-mabi=64:.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR):::64",
"irix64-mips4-cc", "cc:-64 -mips4 -O2 -use_readonly_const -G0 -rdata_shared -DB_ENDIAN -DBN_DIV3W::-D_SGI_MP_SOURCE:::RC4_CHAR RC4_CHUNK DES_RISC2 DES_UNROLL SIXTY_FOUR_BIT_LONG:${mips64_asm}:64:dlfcn:irix-shared::-64:.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR):::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 ment to be used on various PA-RISC processors
# consider './config +DAportable'.
# - +DD64 is chosen in favour of +DA2.0W because it's meant to be
# compatible with *future* releases.
# - If you run ./Configure hpux-parisc-[g]cc manually don't forget to
# pass -D_REENTRANT on HP-UX 10 and later.
# - -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_lcl.h.
# <appro@fy.chalmers.se>
#
# Since there is mention of this in shlib/hpux10-cc.sh
"hpux-parisc-cc-o4","cc:-Ae +O4 +ESlit -z -DB_ENDIAN -DBN_DIV2W -DMD32_XARRAY::-D_REENTRANT::-ldld:BN_LLONG DES_PTR DES_UNROLL DES_RISC1:${no_asm}:dl:hpux-shared:+Z:-b:.sl.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)",
"hpux-parisc-gcc","gcc:-O3 -DB_ENDIAN -DBN_DIV2W::-D_REENTRANT::-Wl,+s -ldld:BN_LLONG DES_PTR DES_UNROLL DES_RISC1:${no_asm}:dl:hpux-shared:-fPIC:-shared:.sl.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)",
"hpux-parisc1_1-gcc","gcc:-O3 -DB_ENDIAN -DBN_DIV2W::-D_REENTRANT::-Wl,+s -ldld:BN_LLONG DES_PTR DES_UNROLL DES_RISC1:${parisc11_asm}:dl:hpux-shared:-fPIC:-shared:.sl.\$(SHLIB_MAJOR).\$(SHLIB_MINOR):::/pa1.1",
"hpux-parisc2-gcc","gcc:-march=2.0 -O3 -DB_ENDIAN -D_REENTRANT::::-Wl,+s -ldld:SIXTY_FOUR_BIT RC4_CHAR RC4_CHUNK DES_PTR DES_UNROLL DES_RISC1:".eval{my $asm=$parisc20_asm;$asm=~s/2W\./2\./;$asm=~s/:64/:32/;$asm}.":dl:hpux-shared:-fPIC:-shared:.sl.\$(SHLIB_MAJOR).\$(SHLIB_MINOR):::/pa20_32",
"hpux64-parisc2-gcc","gcc:-O3 -DB_ENDIAN -D_REENTRANT::::-ldl:SIXTY_FOUR_BIT_LONG MD2_CHAR RC4_INDEX RC4_CHAR DES_UNROLL DES_RISC1 DES_INT::pa-risc2W.o:::::::::::::::void:dlfcn:hpux-shared:-fpic:-shared:.sl.\$(SHLIB_MAJOR).\$(SHLIB_MINOR):::/pa20_64",
# More attempts at unified 10.X and 11.X targets for HP C compiler.
#
# Chris Ruemmler <ruemmler@cup.hp.com>
# Kevin Steves <ks@hp.se>
"hpux-parisc-cc","cc:+O3 +Optrs_strongly_typed -Ae +ESlit -DB_ENDIAN -DBN_DIV2W -DMD32_XARRAY::-D_REENTRANT::-Wl,+s -ldld:MD2_CHAR RC4_INDEX RC4_CHAR DES_UNROLL DES_RISC1 DES_INT:${no_asm}:dl:hpux-shared:+Z:-b:.sl.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)",
"hpux-parisc1_1-cc","cc:+DA1.1 +O3 +Optrs_strongly_typed -Ae +ESlit -DB_ENDIAN -DMD32_XARRAY::-D_REENTRANT::-Wl,+s -ldld:MD2_CHAR RC4_INDEX RC4_CHAR DES_UNROLL DES_RISC1 DES_INT:${parisc11_asm}:dl:hpux-shared:+Z:-b:.sl.\$(SHLIB_MAJOR).\$(SHLIB_MINOR):::/pa1.1",
"hpux-parisc2-cc","cc:+DA2.0 +DS2.0 +O3 +Optrs_strongly_typed -Ae +ESlit -DB_ENDIAN -DMD32_XARRAY -D_REENTRANT::::-Wl,+s -ldld:SIXTY_FOUR_BIT MD2_CHAR RC4_INDEX RC4_CHAR DES_UNROLL DES_RISC1 DES_INT:".eval{my $asm=$parisc20_asm;$asm=~s/2W\./2\./;$asm=~s/:64/:32/;$asm}.":dl:hpux-shared:+Z:-b:.sl.\$(SHLIB_MAJOR).\$(SHLIB_MINOR):::/pa20_32",
"hpux64-parisc2-cc","cc:+DD64 +O3 +Optrs_strongly_typed -Ae +ESlit -DB_ENDIAN -DMD32_XARRAY -D_REENTRANT::::-ldl:SIXTY_FOUR_BIT_LONG MD2_CHAR RC4_INDEX RC4_CHAR DES_UNROLL DES_RISC1 DES_INT:${parisc20_asm}:dlfcn:hpux-shared:+Z:+DD64 -b:.sl.\$(SHLIB_MAJOR).\$(SHLIB_MINOR):::/pa20_64",
# HP/UX IA-64 targets
"hpux-ia64-cc","cc:-Ae +DD32 +O2 +Olit=all -z -DB_ENDIAN -D_REENTRANT::::-ldl:SIXTY_FOUR_BIT MD2_CHAR RC4_INDEX DES_UNROLL DES_RISC1 DES_INT:${ia64_asm}:dlfcn:hpux-shared:+Z:+DD32 -b:.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR):::/hpux32",
# Frank Geurts <frank.geurts@nl.abnamro.com> has patiently assisted with
# with debugging of the following config.
"hpux64-ia64-cc","cc:-Ae +DD64 +O3 +Olit=all -z -DB_ENDIAN -D_REENTRANT::::-ldl:SIXTY_FOUR_BIT_LONG MD2_CHAR RC4_INDEX DES_UNROLL DES_RISC1 DES_INT:${ia64_asm}:dlfcn:hpux-shared:+Z:+DD64 -b:.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR):::/hpux64",
# GCC builds...
"hpux-ia64-gcc","gcc:-O3 -DB_ENDIAN -D_REENTRANT::::-ldl:SIXTY_FOUR_BIT MD2_CHAR RC4_INDEX DES_UNROLL DES_RISC1 DES_INT:${ia64_asm}:dlfcn:hpux-shared:-fpic:-shared:.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR):::/hpux32",
"hpux64-ia64-gcc","gcc:-mlp64 -O3 -DB_ENDIAN -D_REENTRANT::::-ldl:SIXTY_FOUR_BIT_LONG MD2_CHAR RC4_INDEX DES_UNROLL DES_RISC1 DES_INT:${ia64_asm}:dlfcn:hpux-shared:-fpic:-mlp64 -shared:.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR):::/hpux64",
# Legacy HPUX 9.X configs...
"hpux-cc", "cc:-DB_ENDIAN -DBN_DIV2W -DMD32_XARRAY -Ae +ESlit +O2 -z::(unknown)::-Wl,+s -ldld:DES_PTR DES_UNROLL DES_RISC1:${no_asm}:dl:hpux-shared:+Z:-b:.sl.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)",
"hpux-gcc", "gcc:-DB_ENDIAN -DBN_DIV2W -O3::(unknown)::-Wl,+s -ldld:DES_PTR DES_UNROLL DES_RISC1:${no_asm}:dl:hpux-shared:-fPIC:-shared:.sl.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)",
#### HP MPE/iX http://jazz.external.hp.com/src/openssl/
-"MPE/iX-gcc", "gcc:-D_ENDIAN -DBN_DIV2W -O3 -D_POSIX_SOURCE -D_SOCKET_SOURCE -I/SYSLOG/PUB::(unknown):MPE:-L/SYSLOG/PUB -lsyslog -lsocket -lcurses:BN_LLONG DES_PTR DES_UNROLL DES_RISC1:::",
+"MPE/iX-gcc", "gcc:-DBN_DIV2W -O3 -D_POSIX_SOURCE -D_SOCKET_SOURCE -I/SYSLOG/PUB::(unknown):MPE:-L/SYSLOG/PUB -lsyslog -lsocket -lcurses:BN_LLONG DES_PTR DES_UNROLL DES_RISC1:::",
# DEC Alpha OSF/1/Tru64 targets.
#
# "What's in a name? That which we call a rose
# By any other word would smell as sweet."
#
# - William Shakespeare, "Romeo & Juliet", Act II, scene II.
#
# For gcc, the following gave a %50 speedup on a 164 over the 'DES_INT' version
#
"osf1-alpha-gcc", "gcc:-O3::(unknown):::SIXTY_FOUR_BIT_LONG RC4_CHUNK DES_UNROLL DES_RISC1:${alpha_asm}:dlfcn:alpha-osf1-shared:::.so",
"osf1-alpha-cc", "cc:-std1 -tune host -O4 -readonly_strings::(unknown):::SIXTY_FOUR_BIT_LONG RC4_CHUNK:${alpha_asm}:dlfcn:alpha-osf1-shared:::.so",
"tru64-alpha-cc", "cc:-std1 -tune host -fast -readonly_strings::-pthread:::SIXTY_FOUR_BIT_LONG RC4_CHUNK:${alpha_asm}:dlfcn:alpha-osf1-shared::-msym:.so",
####
#### Variety of LINUX:-)
####
# *-generic* is endian-neutral target, but ./config is free to
# throw in -D[BL]_ENDIAN, whichever appropriate...
"linux-generic32","gcc:-O3 -fomit-frame-pointer -Wall::-D_REENTRANT::-ldl:BN_LLONG RC4_CHAR RC4_CHUNK DES_INT DES_UNROLL BF_PTR:${no_asm}:dlfcn:linux-shared:-fPIC::.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)",
"linux-ppc", "gcc:-DB_ENDIAN -O3 -Wall::-D_REENTRANT::-ldl:BN_LLONG RC4_CHAR RC4_CHUNK DES_RISC1 DES_UNROLL:${ppc32_asm}:linux32:dlfcn:linux-shared:-fPIC::.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)",
#######################################################################
# Note that -march is not among compiler options in below linux-armv4
# target line. 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
#
"linux-armv4", "gcc: -O3 -Wall::-D_REENTRANT::-ldl:BN_LLONG RC4_CHAR RC4_CHUNK DES_INT DES_UNROLL BF_PTR:${armv4_asm}:dlfcn:linux-shared:-fPIC::.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)",
"linux-aarch64","gcc: -O3 -Wall::-D_REENTRANT::-ldl:SIXTY_FOUR_BIT_LONG RC4_CHAR RC4_CHUNK DES_INT DES_UNROLL BF_PTR:${aarch64_asm}:linux64:dlfcn:linux-shared:-fPIC::.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)",
# Configure script adds minimally required -march for assembly support,
# if no -march was specified at command line. mips32 and mips64 below
# refer to contemporary MIPS Architecture specifications, MIPS32 and
# MIPS64, rather than to kernel bitness.
"linux-mips32", "gcc:-mabi=32 -O3 -Wall -DBN_DIV3W::-D_REENTRANT::-ldl:BN_LLONG RC4_CHAR RC4_CHUNK DES_INT DES_UNROLL BF_PTR:${mips32_asm}:o32:dlfcn:linux-shared:-fPIC::.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)",
"linux-mips64", "gcc:-mabi=n32 -O3 -Wall -DBN_DIV3W::-D_REENTRANT::-ldl:SIXTY_FOUR_BIT RC4_CHAR RC4_CHUNK DES_INT DES_UNROLL BF_PTR:${mips64_asm}:n32:dlfcn:linux-shared:-fPIC:-mabi=n32:.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR):::32",
"linux64-mips64", "gcc:-mabi=64 -O3 -Wall -DBN_DIV3W::-D_REENTRANT::-ldl:SIXTY_FOUR_BIT_LONG RC4_CHAR RC4_CHUNK DES_INT DES_UNROLL BF_PTR:${mips64_asm}:64:dlfcn:linux-shared:-fPIC:-mabi=64:.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR):::64",
#### IA-32 targets...
"linux-ia32-icc", "icc:-DL_ENDIAN -O2::-D_REENTRANT::-ldl -no_cpprt:BN_LLONG ${x86_gcc_des} ${x86_gcc_opts}:${x86_elf_asm}:dlfcn:linux-shared:-KPIC::.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)",
"linux-elf", "gcc:-DL_ENDIAN -O3 -fomit-frame-pointer -Wall::-D_REENTRANT::-ldl:BN_LLONG ${x86_gcc_des} ${x86_gcc_opts}:${x86_elf_asm}:dlfcn:linux-shared:-fPIC::.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)",
"linux-aout", "gcc:-DL_ENDIAN -O3 -fomit-frame-pointer -march=i486 -Wall::(unknown):::BN_LLONG ${x86_gcc_des} ${x86_gcc_opts}:${x86_asm}:a.out",
####
"linux-generic64","gcc:-O3 -Wall::-D_REENTRANT::-ldl:SIXTY_FOUR_BIT_LONG RC4_CHAR RC4_CHUNK DES_INT DES_UNROLL BF_PTR:${no_asm}:dlfcn:linux-shared:-fPIC::.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)",
"linux-ppc64", "gcc:-m64 -DB_ENDIAN -O3 -Wall::-D_REENTRANT::-ldl:SIXTY_FOUR_BIT_LONG RC4_CHAR RC4_CHUNK DES_RISC1 DES_UNROLL:${ppc64_asm}:linux64:dlfcn:linux-shared:-fPIC:-m64:.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR):::64",
"linux-ppc64le","gcc:-m64 -DL_ENDIAN -O3 -Wall::-D_REENTRANT::-ldl:SIXTY_FOUR_BIT_LONG RC4_CHAR RC4_CHUNK DES_RISC1 DES_UNROLL:$ppc64_asm:linux64le:dlfcn:linux-shared:-fPIC:-m64:.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR):::",
"linux-ia64", "gcc:-DL_ENDIAN -DTERMIO -O3 -Wall::-D_REENTRANT::-ldl:SIXTY_FOUR_BIT_LONG RC4_CHUNK DES_UNROLL DES_INT:${ia64_asm}:dlfcn:linux-shared:-fPIC::.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)",
"linux-ia64-icc","icc:-DL_ENDIAN -O2 -Wall::-D_REENTRANT::-ldl -no_cpprt:SIXTY_FOUR_BIT_LONG RC4_CHUNK DES_RISC1 DES_INT:${ia64_asm}:dlfcn:linux-shared:-fPIC::.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)",
"linux-x86_64", "gcc:-m64 -DL_ENDIAN -O3 -Wall::-D_REENTRANT::-ldl:SIXTY_FOUR_BIT_LONG RC4_CHUNK DES_INT DES_UNROLL:${x86_64_asm}:elf:dlfcn:linux-shared:-fPIC:-m64:.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR):::64",
"linux-x86_64-clang", "clang: -m64 -DL_ENDIAN -O3 -Wall -Wextra $clang_disabled_warnings -Qunused-arguments::-D_REENTRANT::-ldl:SIXTY_FOUR_BIT_LONG RC4_CHUNK DES_INT DES_UNROLL:${x86_64_asm}:elf:dlfcn:linux-shared:-fPIC:-m64:.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR):::64",
"debug-linux-x86_64-clang", "clang: -DBN_DEBUG -DREF_CHECK -DCONF_DEBUG -DCRYPTO_MDEBUG -m64 -DL_ENDIAN -g -Wall -Wextra $clang_disabled_warnings -Qunused-arguments::-D_REENTRANT::-ldl:SIXTY_FOUR_BIT_LONG RC4_CHUNK DES_INT DES_UNROLL:${x86_64_asm}:elf:dlfcn:linux-shared:-fPIC:-m64:.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR):::64",
"linux-x86_64-icc", "icc:-DL_ENDIAN -O2::-D_REENTRANT::-ldl -no_cpprt:SIXTY_FOUR_BIT_LONG RC4_CHUNK DES_INT DES_UNROLL:${x86_64_asm}:elf:dlfcn:linux-shared:-fPIC::.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR):::64",
"linux-x32", "gcc:-mx32 -DL_ENDIAN -O3 -Wall::-D_REENTRANT::-ldl:SIXTY_FOUR_BIT RC4_CHUNK_LL DES_INT DES_UNROLL:${x86_64_asm}:elf:dlfcn:linux-shared:-fPIC:-mx32:.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR):::x32",
"linux64-s390x", "gcc:-m64 -DB_ENDIAN -O3 -Wall::-D_REENTRANT::-ldl:SIXTY_FOUR_BIT_LONG RC4_CHAR RC4_CHUNK DES_INT DES_UNROLL:${s390x_asm}:64:dlfcn:linux-shared:-fPIC:-m64:.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR):::64",
#### 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...
"linux32-s390x", "gcc:-m31 -Wa,-mzarch -DB_ENDIAN -O3 -Wall::-D_REENTRANT::-ldl:BN_LLONG RC4_CHAR RC4_CHUNK DES_INT DES_UNROLL:".eval{my $asm=$s390x_asm;$asm=~s/bn\-s390x\.o/bn_asm.o/;$asm}.":31:dlfcn:linux-shared:-fPIC:-m31:.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR):::/highgprs",
#### SPARC Linux setups
# Ray Miller <ray.miller@computing-services.oxford.ac.uk> has patiently
# assisted with debugging of following two configs.
"linux-sparcv8","gcc:-mcpu=v8 -DB_ENDIAN -O3 -fomit-frame-pointer -Wall -DBN_DIV2W::-D_REENTRANT::-ldl:BN_LLONG RC4_CHAR RC4_CHUNK DES_UNROLL BF_PTR:${sparcv8_asm}:dlfcn:linux-shared:-fPIC::.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)",
# it's a real mess with -mcpu=ultrasparc option under Linux, but
# -Wa,-Av8plus should do the trick no matter what.
"linux-sparcv9","gcc:-m32 -mcpu=ultrasparc -DB_ENDIAN -O3 -fomit-frame-pointer -Wall -Wa,-Av8plus -DBN_DIV2W::-D_REENTRANT:ULTRASPARC:-ldl:BN_LLONG RC4_CHAR RC4_CHUNK DES_UNROLL BF_PTR:${sparcv9_asm}:dlfcn:linux-shared:-fPIC:-m32:.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)",
# GCC 3.1 is a requirement
"linux64-sparcv9","gcc:-m64 -mcpu=ultrasparc -DB_ENDIAN -O3 -fomit-frame-pointer -Wall::-D_REENTRANT:ULTRASPARC:-ldl:BN_LLONG RC4_CHAR RC4_CHUNK DES_INT DES_PTR DES_RISC1 DES_UNROLL BF_PTR:${sparcv9_asm}:dlfcn:linux-shared:-fPIC:-m64:.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR):::64",
#### Alpha Linux with GNU C and Compaq C setups
# Special notes:
# - linux-alpha+bwx-gcc is ment to be used from ./config only. If you
# ought to run './Configure linux-alpha+bwx-gcc' manually, do
# complement the command line with -mcpu=ev56, -mcpu=ev6 or whatever
# which is appropriate.
# - If you use ccc keep in mind that -fast implies -arch host and the
# compiler is free to issue instructions which gonna make elder CPU
# choke. If you wish to build "blended" toolkit, add -arch generic
# *after* -fast and invoke './Configure linux-alpha-ccc' manually.
#
# <appro@fy.chalmers.se>
#
"linux-alpha-gcc","gcc:-O3 -DL_ENDIAN::-D_REENTRANT::-ldl:SIXTY_FOUR_BIT_LONG RC4_CHUNK DES_RISC1 DES_UNROLL:${alpha_asm}:dlfcn:linux-shared:-fPIC::.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)",
"linux-alpha+bwx-gcc","gcc:-O3 -DL_ENDIAN::-D_REENTRANT::-ldl:SIXTY_FOUR_BIT_LONG RC4_CHAR RC4_CHUNK DES_RISC1 DES_UNROLL:${alpha_asm}:dlfcn:linux-shared:-fPIC::.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)",
"linux-alpha-ccc","ccc:-fast -readonly_strings -DL_ENDIAN::-D_REENTRANT:::SIXTY_FOUR_BIT_LONG RC4_CHUNK DES_INT DES_PTR DES_RISC1 DES_UNROLL:${alpha_asm}",
"linux-alpha+bwx-ccc","ccc:-fast -readonly_strings -DL_ENDIAN::-D_REENTRANT:::SIXTY_FOUR_BIT_LONG RC4_CHAR RC4_CHUNK DES_INT DES_PTR DES_RISC1 DES_UNROLL:${alpha_asm}",
# Android: linux-* but without pointers to headers and libs.
"android","gcc:-mandroid -I\$(ANDROID_DEV)/include -B\$(ANDROID_DEV)/lib -O3 -fomit-frame-pointer -Wall::-D_REENTRANT::-ldl:BN_LLONG RC4_CHAR RC4_CHUNK DES_INT DES_UNROLL BF_PTR:${no_asm}:dlfcn:linux-shared:-fPIC::.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)",
"android-x86","gcc:-mandroid -I\$(ANDROID_DEV)/include -B\$(ANDROID_DEV)/lib -O3 -fomit-frame-pointer -Wall::-D_REENTRANT::-ldl:BN_LLONG ${x86_gcc_des} ${x86_gcc_opts}:".eval{my $asm=${x86_elf_asm};$asm=~s/:elf/:android/;$asm}.":dlfcn:linux-shared:-fPIC::.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)",
"android-armv7","gcc:-march=armv7-a -mandroid -I\$(ANDROID_DEV)/include -B\$(ANDROID_DEV)/lib -O3 -fomit-frame-pointer -Wall::-D_REENTRANT::-ldl:BN_LLONG RC4_CHAR RC4_CHUNK DES_INT DES_UNROLL BF_PTR:${armv4_asm}:dlfcn:linux-shared:-fPIC::.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)",
"android-mips","gcc:-mandroid -I\$(ANDROID_DEV)/include -B\$(ANDROID_DEV)/lib -O3 -Wall::-D_REENTRANT::-ldl:BN_LLONG RC4_CHAR RC4_CHUNK DES_INT DES_UNROLL BF_PTR:${mips32_asm}:o32:dlfcn:linux-shared:-fPIC::.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)",
#### *BSD [do see comment about ${BSDthreads} above!]
"BSD-generic32","gcc:-O3 -fomit-frame-pointer -Wall::${BSDthreads}:::BN_LLONG RC2_CHAR RC4_INDEX DES_INT DES_UNROLL:${no_asm}:dlfcn:bsd-gcc-shared:-fPIC::.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)",
"BSD-x86", "gcc:-DL_ENDIAN -O3 -fomit-frame-pointer -Wall::${BSDthreads}:::BN_LLONG ${x86_gcc_des} ${x86_gcc_opts}:${x86_asm}:a.out:dlfcn:bsd-shared:-fPIC::.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)",
"BSD-x86-elf", "gcc:-DL_ENDIAN -O3 -fomit-frame-pointer -Wall::${BSDthreads}:::BN_LLONG ${x86_gcc_des} ${x86_gcc_opts}:${x86_elf_asm}:dlfcn:bsd-shared:-fPIC::.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)",
"debug-BSD-x86-elf", "gcc:-DL_ENDIAN -O3 -Wall -g::${BSDthreads}:::BN_LLONG ${x86_gcc_des} ${x86_gcc_opts}:${x86_elf_asm}:dlfcn:bsd-shared:-fPIC::.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)",
"BSD-sparcv8", "gcc:-DB_ENDIAN -O3 -mcpu=v8 -Wall::${BSDthreads}:::BN_LLONG RC2_CHAR RC4_INDEX DES_INT DES_UNROLL:${sparcv8_asm}:dlfcn:bsd-gcc-shared:-fPIC::.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)",
"BSD-generic64","gcc:-O3 -Wall::${BSDthreads}:::SIXTY_FOUR_BIT_LONG RC4_CHUNK DES_INT DES_UNROLL:${no_asm}:dlfcn:bsd-gcc-shared:-fPIC::.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)",
# -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.
"BSD-sparc64", "gcc:-DB_ENDIAN -O3 -DMD32_REG_T=int -Wall::${BSDthreads}:::BN_LLONG RC2_CHAR RC4_CHUNK DES_INT DES_PTR DES_RISC2 BF_PTR:${sparcv9_asm}:dlfcn:bsd-gcc-shared:-fPIC::.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)",
"BSD-ia64", "gcc:-DL_ENDIAN -O3 -Wall::${BSDthreads}:::SIXTY_FOUR_BIT_LONG RC4_CHUNK DES_UNROLL DES_INT:${ia64_asm}:dlfcn:bsd-gcc-shared:-fPIC::.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)",
"BSD-x86_64", "cc:-DL_ENDIAN -O3 -Wall::${BSDthreads}:::SIXTY_FOUR_BIT_LONG RC4_CHUNK DES_INT DES_UNROLL:${x86_64_asm}:elf:dlfcn:bsd-gcc-shared:-fPIC::.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)",
"bsdi-elf-gcc", "gcc:-DPERL5 -DL_ENDIAN -fomit-frame-pointer -O3 -march=i486 -Wall::(unknown)::-ldl:BN_LLONG ${x86_gcc_des} ${x86_gcc_opts}:${x86_elf_asm}:dlfcn:bsd-gcc-shared:-fPIC::.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)",
"nextstep", "cc:-O -Wall:<libc.h>:(unknown):::BN_LLONG ${x86_gcc_des} ${x86_gcc_opts}:::",
"nextstep3.3", "cc:-O3 -Wall:<libc.h>:(unknown):::BN_LLONG ${x86_gcc_des} ${x86_gcc_opts}:::",
# NCR MP-RAS UNIX ver 02.03.01
"ncr-scde","cc:-O6 -Xa -Hoff=BEHAVED -686 -Hwide -Hiw::(unknown)::-lsocket -lnsl -lc89:${x86_gcc_des} ${x86_gcc_opts}:::",
# QNX
"qnx4", "cc:-DL_ENDIAN -DTERMIO::(unknown):::${x86_gcc_des} ${x86_gcc_opts}:",
"QNX6", "gcc:::::-lsocket::${no_asm}:dlfcn:bsd-gcc-shared:-fPIC::.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)",
"QNX6-i386", "gcc:-DL_ENDIAN -O2 -Wall::::-lsocket:${x86_gcc_des} ${x86_gcc_opts}:${x86_elf_asm}:dlfcn:bsd-gcc-shared:-fPIC::.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)",
# BeOS
"beos-x86-r5", "gcc:-DL_ENDIAN -DTERMIOS -O3 -fomit-frame-pointer -mcpu=pentium -Wall::-D_REENTRANT:BEOS:-lbe -lnet:BN_LLONG ${x86_gcc_des} ${x86_gcc_opts}:${x86_elf_asm}:beos:beos-shared:-fPIC -DPIC:-shared:.so",
"beos-x86-bone", "gcc:-DL_ENDIAN -DTERMIOS -O3 -fomit-frame-pointer -mcpu=pentium -Wall::-D_REENTRANT:BEOS:-lbe -lbind -lsocket:BN_LLONG ${x86_gcc_des} ${x86_gcc_opts}:${x86_elf_asm}:beos:beos-shared:-fPIC:-shared:.so",
#### 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. Tim Rice <tim@multitalents.net> has
# patiently assisted to debug most of it.
#
# UnixWare 2.0x fails destest with -O.
"unixware-2.0","cc:-DFILIO_H -DNO_STRINGS_H::-Kthread::-lsocket -lnsl -lresolv -lx:${x86_gcc_des} ${x86_gcc_opts}:::",
"unixware-2.1","cc:-O -DFILIO_H::-Kthread::-lsocket -lnsl -lresolv -lx:${x86_gcc_des} ${x86_gcc_opts}:::",
"unixware-7","cc:-O -DFILIO_H -Kalloca::-Kthread::-lsocket -lnsl:BN_LLONG MD2_CHAR RC4_INDEX ${x86_gcc_des}:${x86_elf_asm}-1:dlfcn:svr5-shared:-Kpic::.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)",
"unixware-7-gcc","gcc:-DL_ENDIAN -DFILIO_H -O3 -fomit-frame-pointer -march=pentium -Wall::-D_REENTRANT::-lsocket -lnsl:BN_LLONG ${x86_gcc_des} ${x86_gcc_opts}:${x86_elf_asm}-1:dlfcn:gnu-shared:-fPIC::.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)",
# SCO 5 - Ben Laurie <ben@algroup.co.uk> says the -O breaks the SCO cc.
"sco5-cc", "cc:-belf::(unknown)::-lsocket -lnsl:${x86_gcc_des} ${x86_gcc_opts}:${x86_elf_asm}-1:dlfcn:svr3-shared:-Kpic::.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)",
"sco5-gcc", "gcc:-O3 -fomit-frame-pointer::(unknown)::-lsocket -lnsl:BN_LLONG ${x86_gcc_des} ${x86_gcc_opts}:${x86_elf_asm}-1:dlfcn:svr3-shared:-fPIC::.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)",
#### IBM's AIX.
"aix3-cc", "cc:-O -DB_ENDIAN -qmaxmem=16384::(unknown):AIX::BN_LLONG RC4_CHAR:::",
"aix-gcc", "gcc:-O -DB_ENDIAN::-pthread:AIX::BN_LLONG RC4_CHAR:${ppc32_asm}:aix32:dlfcn:aix-shared::-shared -Wl,-G:.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)::-X32",
"aix64-gcc","gcc:-maix64 -O -DB_ENDIAN::-pthread:AIX::SIXTY_FOUR_BIT_LONG RC4_CHAR:${ppc64_asm}:aix64:dlfcn:aix-shared::-maix64 -shared -Wl,-G:.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)::-X64",
# Below targets assume AIX 5. Idea is to effectively disregard $OBJECT_MODE
# at build time. $OBJECT_MODE is respected at ./config stage!
"aix-cc", "cc:-q32 -O -DB_ENDIAN -qmaxmem=16384 -qro -qroconst::-qthreaded -D_THREAD_SAFE:AIX::BN_LLONG RC4_CHAR:${ppc32_asm}:aix32:dlfcn:aix-shared::-q32 -G:.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)::-X 32",
"aix64-cc", "cc:-q64 -O -DB_ENDIAN -qmaxmem=16384 -qro -qroconst::-qthreaded -D_THREAD_SAFE:AIX::SIXTY_FOUR_BIT_LONG RC4_CHAR:${ppc64_asm}:aix64:dlfcn:aix-shared::-q64 -G:.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)::-X 64",
#
# Cray T90 and similar (SDSC)
# It's Big-endian, but the algorithms work properly when B_ENDIAN is NOT
# defined. The T90 ints and longs are 8 bytes long, and apparently the
# B_ENDIAN code assumes 4 byte ints. Fortunately, the non-B_ENDIAN and
# non L_ENDIAN code aligns the bytes in each word correctly.
#
# The BIT_FIELD_LIMITS define is to avoid two fatal compiler errors:
#'Taking the address of a bit field is not allowed. '
#'An expression with bit field exists as the operand of "sizeof" '
# (written by Wayne Schroeder <schroede@SDSC.EDU>)
#
# j90 is considered the base machine type for unicos machines,
# so this configuration is now called "cray-j90" ...
"cray-j90", "cc: -DBIT_FIELD_LIMITS -DTERMIOS::(unknown):CRAY::SIXTY_FOUR_BIT_LONG DES_INT:::",
#
# Cray T3E (Research Center Juelich, beckman@acl.lanl.gov)
#
# The BIT_FIELD_LIMITS define was written for the C90 (it seems). I added
# another use. Basically, the problem is that the T3E uses some bit fields
# for some st_addr stuff, and then sizeof and address-of fails
# I could not use the ams/alpha.o option because the Cray assembler, 'cam'
# did not like it.
"cray-t3e", "cc: -DBIT_FIELD_LIMITS -DTERMIOS::(unknown):CRAY::SIXTY_FOUR_BIT_LONG RC4_CHUNK DES_INT:::",
# DGUX, 88100.
"dgux-R3-gcc", "gcc:-O3 -fomit-frame-pointer::(unknown):::RC4_INDEX DES_UNROLL:::",
"dgux-R4-gcc", "gcc:-O3 -fomit-frame-pointer::(unknown)::-lnsl -lsocket:RC4_INDEX DES_UNROLL:::",
"dgux-R4-x86-gcc", "gcc:-O3 -fomit-frame-pointer -DL_ENDIAN::(unknown)::-lnsl -lsocket:BN_LLONG ${x86_gcc_des} ${x86_gcc_opts}:${x86_elf_asm}",
# Sinix/ReliantUNIX RM400
# NOTE: The CDS++ Compiler up to V2.0Bsomething has the IRIX_CC_BUG optimizer problem. Better use -g */
"ReliantUNIX","cc:-KPIC -g -DTERMIOS -DB_ENDIAN::-Kthread:SNI:-lsocket -lnsl -lc -L/usr/ucblib -lucb:BN_LLONG DES_PTR DES_RISC2 DES_UNROLL BF_PTR:${no_asm}:dlfcn:reliantunix-shared:::.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)",
"SINIX","cc:-O::(unknown):SNI:-lsocket -lnsl -lc -L/usr/ucblib -lucb:RC4_INDEX RC4_CHAR:::",
"SINIX-N","/usr/ucb/cc:-O2 -misaligned::(unknown)::-lucb:RC4_INDEX RC4_CHAR:::",
# SIEMENS BS2000/OSD: an EBCDIC-based mainframe
"BS2000-OSD","c89:-O -XLLML -XLLMK -XL -DB_ENDIAN -DCHARSET_EBCDIC::(unknown)::-lsocket -lnsl:THIRTY_TWO_BIT DES_PTR DES_UNROLL MD2_CHAR RC4_INDEX RC4_CHAR BF_PTR:::",
# OS/390 Unix an EBCDIC-based Unix system on IBM mainframe
# You need to compile using the c89.sh wrapper in the tools directory, because the
# IBM compiler does not like the -L switch after any object modules.
#
"OS390-Unix","c89.sh:-O -DB_ENDIAN -DCHARSET_EBCDIC -DNO_SYS_PARAM_H -D_ALL_SOURCE::(unknown):::THIRTY_TWO_BIT DES_PTR DES_UNROLL MD2_CHAR RC4_INDEX RC4_CHAR BF_PTR:::",
# Visual C targets
#
# Win64 targets, WIN64I denotes IA-64 and WIN64A - AMD64
"VC-WIN64I","cl:-W3 -Gs0 -Gy -nologo -DOPENSSL_SYSNAME_WIN32 -DWIN32_LEAN_AND_MEAN -DL_ENDIAN -DUNICODE -D_UNICODE -D_CRT_SECURE_NO_DEPRECATE:::WIN64I::SIXTY_FOUR_BIT RC4_CHUNK_LL DES_INT EXPORT_VAR_AS_FN:ia64cpuid.o:ia64.o ia64-mont.o:::aes_core.o aes_cbc.o aes-ia64.o::md5-ia64.o:sha1-ia64.o sha256-ia64.o sha512-ia64.o:::::::ghash-ia64.o::ias:win32",
"VC-WIN64A","cl:-W3 -Gs0 -Gy -nologo -DOPENSSL_SYSNAME_WIN32 -DWIN32_LEAN_AND_MEAN -DL_ENDIAN -DUNICODE -D_UNICODE -D_CRT_SECURE_NO_DEPRECATE:::WIN64A::SIXTY_FOUR_BIT RC4_CHUNK_LL DES_INT EXPORT_VAR_AS_FN:".eval{my $asm=$x86_64_asm;$asm=~s/x86_64-gcc\.o/bn_asm.o/;$asm}.":auto:win32",
"debug-VC-WIN64I","cl:-W3 -Gs0 -Gy -Zi -nologo -DOPENSSL_SYSNAME_WIN32 -DWIN32_LEAN_AND_MEAN -DL_ENDIAN -DUNICODE -D_UNICODE -D_CRT_SECURE_NO_DEPRECATE:::WIN64I::SIXTY_FOUR_BIT RC4_CHUNK_LL DES_INT EXPORT_VAR_AS_FN:ia64cpuid.o:ia64.o:::aes_core.o aes_cbc.o aes-ia64.o::md5-ia64.o:sha1-ia64.o sha256-ia64.o sha512-ia64.o:::::::ghash-ia64.o::ias:win32",
"debug-VC-WIN64A","cl:-W3 -Gs0 -Gy -Zi -nologo -DOPENSSL_SYSNAME_WIN32 -DWIN32_LEAN_AND_MEAN -DL_ENDIAN -DUNICODE -D_UNICODE -D_CRT_SECURE_NO_DEPRECATE:::WIN64A::SIXTY_FOUR_BIT RC4_CHUNK_LL DES_INT EXPORT_VAR_AS_FN:".eval{my $asm=$x86_64_asm;$asm=~s/x86_64-gcc\.o/bn_asm.o/;$asm}.":auto:win32",
# x86 Win32 target defaults to ANSI API, if you want UNICODE, complement
# 'perl Configure VC-WIN32' with '-DUNICODE -D_UNICODE'
"VC-WIN32","cl:-W3 -WX -Gs0 -GF -Gy -nologo -DOPENSSL_SYSNAME_WIN32 -DWIN32_LEAN_AND_MEAN -DL_ENDIAN -D_CRT_SECURE_NO_DEPRECATE -D_WINSOCK_DEPRECATED_NO_WARNINGS:::WIN32::BN_LLONG RC4_INDEX EXPORT_VAR_AS_FN ${x86_gcc_opts}:${x86_asm}:win32n:win32",
# Unified CE target
"debug-VC-WIN32","cl:-W3 -WX -Gs0 -GF -Gy -Zi -nologo -DOPENSSL_SYSNAME_WIN32 -DWIN32_LEAN_AND_MEAN -DL_ENDIAN -D_CRT_SECURE_NO_DEPRECATE -D_WINSOCK_DEPRECATED_NO_WARNINGS:::WIN32::BN_LLONG RC4_INDEX EXPORT_VAR_AS_FN ${x86_gcc_opts}:${x86_asm}:win32n:win32",
"VC-CE","cl::::WINCE::BN_LLONG RC4_INDEX EXPORT_VAR_AS_FN ${x86_gcc_opts}:${no_asm}:win32",
# Borland C++ 4.5
"BC-32","bcc32::::WIN32::BN_LLONG DES_PTR RC4_INDEX EXPORT_VAR_AS_FN:${no_asm}:win32",
# MinGW
"mingw", "gcc:-mno-cygwin -DL_ENDIAN -DWIN32_LEAN_AND_MEAN -fomit-frame-pointer -O3 -march=i486 -Wall::-D_MT:MINGW32:-lws2_32 -lgdi32 -lcrypt32:BN_LLONG ${x86_gcc_des} ${x86_gcc_opts} EXPORT_VAR_AS_FN:${x86_asm}:coff:win32:cygwin-shared:-D_WINDLL -DOPENSSL_USE_APPLINK:-mno-cygwin:.dll.a",
# As for OPENSSL_USE_APPLINK. 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 till 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.
"mingw64", "gcc:-mno-cygwin -DL_ENDIAN -O3 -Wall -DWIN32_LEAN_AND_MEAN -DUNICODE -D_UNICODE::-D_MT:MINGW64:-lws2_32 -lgdi32 -lcrypt32:SIXTY_FOUR_BIT RC4_CHUNK_LL DES_INT EXPORT_VAR_AS_FN:${x86_64_asm}:mingw64:win32:cygwin-shared:-D_WINDLL:-mno-cygwin:.dll.a",
# UWIN
"UWIN", "cc:-DTERMIOS -DL_ENDIAN -O -Wall:::UWIN::BN_LLONG ${x86_gcc_des} ${x86_gcc_opts}:${no_asm}:win32",
# Cygwin
"Cygwin", "gcc:-DTERMIOS -DL_ENDIAN -fomit-frame-pointer -O3 -march=i486 -Wall:::CYGWIN::BN_LLONG ${x86_gcc_des} ${x86_gcc_opts}:${x86_asm}:coff:dlfcn:cygwin-shared:-D_WINDLL:-shared:.dll.a",
"Cygwin-x86_64", "gcc:-DTERMIOS -DL_ENDIAN -O3 -Wall:::CYGWIN::SIXTY_FOUR_BIT_LONG RC4_CHUNK DES_INT DES_UNROLL:${x86_64_asm}:mingw64:dlfcn:cygwin-shared:-D_WINDLL:-shared:.dll.a",
# NetWare from David Ward (dsward@novell.com)
# requires either MetroWerks NLM development tools, or gcc / nlmconv
# NetWare defaults socket bio to WinSock sockets. However,
# the builds can be configured to use BSD sockets instead.
# netware-clib => legacy CLib c-runtime support
"netware-clib", "mwccnlm::::::${x86_gcc_opts}::",
"netware-clib-bsdsock", "mwccnlm::::::${x86_gcc_opts}::",
"netware-clib-gcc", "i586-netware-gcc:-nostdinc -I/ndk/nwsdk/include/nlm -I/ndk/ws295sdk/include -DL_ENDIAN -DNETWARE_CLIB -DOPENSSL_SYSNAME_NETWARE -O2 -Wall:::::${x86_gcc_opts}::",
"netware-clib-bsdsock-gcc", "i586-netware-gcc:-nostdinc -I/ndk/nwsdk/include/nlm -DNETWARE_BSDSOCK -DNETDB_USE_INTERNET -DL_ENDIAN -DNETWARE_CLIB -DOPENSSL_SYSNAME_NETWARE -O2 -Wall:::::${x86_gcc_opts}::",
# netware-libc => LibC/NKS support
"netware-libc", "mwccnlm::::::BN_LLONG ${x86_gcc_opts}::",
"netware-libc-bsdsock", "mwccnlm::::::BN_LLONG ${x86_gcc_opts}::",
"netware-libc-gcc", "i586-netware-gcc:-nostdinc -I/ndk/libc/include -I/ndk/libc/include/winsock -DL_ENDIAN -DNETWARE_LIBC -DOPENSSL_SYSNAME_NETWARE -DTERMIO -O2 -Wall:::::BN_LLONG ${x86_gcc_opts}::",
"netware-libc-bsdsock-gcc", "i586-netware-gcc:-nostdinc -I/ndk/libc/include -DNETWARE_BSDSOCK -DL_ENDIAN -DNETWARE_LIBC -DOPENSSL_SYSNAME_NETWARE -DTERMIO -O2 -Wall:::::BN_LLONG ${x86_gcc_opts}::",
# DJGPP
"DJGPP", "gcc:-I/dev/env/WATT_ROOT/inc -DTERMIO -DL_ENDIAN -fomit-frame-pointer -O2 -Wall:::MSDOS:-L/dev/env/WATT_ROOT/lib -lwatt:BN_LLONG ${x86_gcc_des} ${x86_gcc_opts}:${x86_asm}:a.out:",
# Ultrix from Bernhard Simon <simon@zid.tuwien.ac.at>
"ultrix-cc","cc:-std1 -O -Olimit 2500 -DL_ENDIAN::(unknown):::::::",
"ultrix-gcc","gcc:-O3 -DL_ENDIAN::(unknown):::BN_LLONG::::",
# K&R C is no longer supported; you need gcc on old Ultrix installations
##"ultrix","cc:-O2 -DNOPROTO -DNOCONST -DL_ENDIAN::(unknown):::::::",
##### MacOS X (a.k.a. Rhapsody or Darwin) setup
"rhapsody-ppc-cc","cc:-O3 -DB_ENDIAN::(unknown):MACOSX_RHAPSODY::BN_LLONG RC4_CHAR RC4_CHUNK DES_UNROLL BF_PTR:${no_asm}::",
"darwin-ppc-cc","cc:-arch ppc -O3 -DB_ENDIAN -Wa,-force_cpusubtype_ALL::-D_REENTRANT:MACOSX:-Wl,-search_paths_first%:BN_LLONG RC4_CHAR RC4_CHUNK DES_UNROLL BF_PTR:${ppc32_asm}:osx32:dlfcn:darwin-shared:-fPIC -fno-common:-arch ppc -dynamiclib:.\$(SHLIB_MAJOR).\$(SHLIB_MINOR).dylib",
"darwin64-ppc-cc","cc:-arch ppc64 -O3 -DB_ENDIAN::-D_REENTRANT:MACOSX:-Wl,-search_paths_first%:SIXTY_FOUR_BIT_LONG RC4_CHAR RC4_CHUNK DES_UNROLL BF_PTR:${ppc64_asm}:osx64:dlfcn:darwin-shared:-fPIC -fno-common:-arch ppc64 -dynamiclib:.\$(SHLIB_MAJOR).\$(SHLIB_MINOR).dylib",
"darwin-i386-cc","cc:-arch i386 -O3 -fomit-frame-pointer -DL_ENDIAN::-D_REENTRANT:MACOSX:-Wl,-search_paths_first%:BN_LLONG RC4_INT RC4_CHUNK DES_UNROLL BF_PTR:".eval{my $asm=$x86_asm;$asm=~s/cast\-586\.o//;$asm}.":macosx:dlfcn:darwin-shared:-fPIC -fno-common:-arch i386 -dynamiclib:.\$(SHLIB_MAJOR).\$(SHLIB_MINOR).dylib",
"debug-darwin-i386-cc","cc:-arch i386 -g3 -DL_ENDIAN::-D_REENTRANT:MACOSX:-Wl,-search_paths_first%:BN_LLONG RC4_INT RC4_CHUNK DES_UNROLL BF_PTR:${x86_asm}:macosx:dlfcn:darwin-shared:-fPIC -fno-common:-arch i386 -dynamiclib:.\$(SHLIB_MAJOR).\$(SHLIB_MINOR).dylib",
"darwin64-x86_64-cc","cc:-arch x86_64 -O3 -DL_ENDIAN -Wall::-D_REENTRANT:MACOSX:-Wl,-search_paths_first%:SIXTY_FOUR_BIT_LONG RC4_CHUNK DES_INT DES_UNROLL:".eval{my $asm=$x86_64_asm;$asm=~s/rc4\-[^:]+//;$asm}.":macosx:dlfcn:darwin-shared:-fPIC -fno-common:-arch x86_64 -dynamiclib:.\$(SHLIB_MAJOR).\$(SHLIB_MINOR).dylib",
"debug-darwin64-x86_64-cc","cc:-arch x86_64 -ggdb -g2 -O0 -DL_ENDIAN -Wall::-D_REENTRANT:MACOSX:-Wl,-search_paths_first%:SIXTY_FOUR_BIT_LONG RC4_CHUNK DES_INT DES_UNROLL:".eval{my $asm=$x86_64_asm;$asm=~s/rc4\-[^:]+//;$asm}.":macosx:dlfcn:darwin-shared:-fPIC -fno-common:-arch x86_64 -dynamiclib:.\$(SHLIB_MAJOR).\$(SHLIB_MINOR).dylib",
"debug-darwin-ppc-cc","cc:-DBN_DEBUG -DREF_CHECK -DCONF_DEBUG -DCRYPTO_MDEBUG -DB_ENDIAN -g -Wall -O::-D_REENTRANT:MACOSX::BN_LLONG RC4_CHAR RC4_CHUNK DES_UNROLL BF_PTR:${ppc32_asm}:osx32:dlfcn:darwin-shared:-fPIC:-dynamiclib:.\$(SHLIB_MAJOR).\$(SHLIB_MINOR).dylib",
# iPhoneOS/iOS
"iphoneos-cross","llvm-gcc:-O3 -isysroot \$(CROSS_TOP)/SDKs/\$(CROSS_SDK) -fomit-frame-pointer -fno-common::-D_REENTRANT:iOS:-Wl,-search_paths_first%:BN_LLONG RC4_CHAR RC4_CHUNK DES_UNROLL BF_PTR:${no_asm}:dlfcn:darwin-shared:-fPIC -fno-common:-dynamiclib:.\$(SHLIB_MAJOR).\$(SHLIB_MINOR).dylib",
##### A/UX
"aux3-gcc","gcc:-O2 -DTERMIO::(unknown):AUX:-lbsd:RC4_CHAR RC4_CHUNK DES_UNROLL BF_PTR:::",
##### Sony NEWS-OS 4.x
"newsos4-gcc","gcc:-O -DB_ENDIAN::(unknown):NEWS4:-lmld -liberty:BN_LLONG RC4_CHAR RC4_CHUNK DES_PTR DES_RISC1 DES_UNROLL BF_PTR::::",
##### GNU Hurd
"hurd-x86", "gcc:-DL_ENDIAN -O3 -fomit-frame-pointer -march=i486 -Wall::-D_REENTRANT::-ldl:BN_LLONG ${x86_gcc_des} ${x86_gcc_opts}:${x86_elf_asm}:dlfcn:linux-shared:-fPIC",
##### OS/2 EMX
"OS2-EMX", "gcc::::::::",
##### VxWorks for various targets
"vxworks-ppc60x","ccppc:-D_REENTRANT -mrtp -mhard-float -mstrict-align -fno-implicit-fp -DPPC32_fp60x -O2 -fstrength-reduce -fno-builtin -fno-strict-aliasing -Wall -DCPU=PPC32 -DTOOL_FAMILY=gnu -DTOOL=gnu -I\$(WIND_BASE)/target/usr/h -I\$(WIND_BASE)/target/usr/h/wrn/coreip:::VXWORKS:-Wl,--defsym,__wrs_rtp_base=0xe0000000 -L \$(WIND_BASE)/target/usr/lib/ppc/PPC32/common:::::",
"vxworks-ppcgen","ccppc:-D_REENTRANT -mrtp -msoft-float -mstrict-align -O1 -fno-builtin -fno-strict-aliasing -Wall -DCPU=PPC32 -DTOOL_FAMILY=gnu -DTOOL=gnu -I\$(WIND_BASE)/target/usr/h -I\$(WIND_BASE)/target/usr/h/wrn/coreip:::VXWORKS:-Wl,--defsym,__wrs_rtp_base=0xe0000000 -L \$(WIND_BASE)/target/usr/lib/ppc/PPC32/sfcommon:::::",
"vxworks-ppc405","ccppc:-g -msoft-float -mlongcall -DCPU=PPC405 -I\$(WIND_BASE)/target/h:::VXWORKS:-r:::::",
"vxworks-ppc750","ccppc:-ansi -nostdinc -DPPC750 -D_REENTRANT -fvolatile -fno-builtin -fno-for-scope -fsigned-char -Wall -msoft-float -mlongcall -DCPU=PPC604 -I\$(WIND_BASE)/target/h \$(DEBUG_FLAG):::VXWORKS:-r:::::",
"vxworks-ppc750-debug","ccppc:-ansi -nostdinc -DPPC750 -D_REENTRANT -fvolatile -fno-builtin -fno-for-scope -fsigned-char -Wall -msoft-float -mlongcall -DCPU=PPC604 -I\$(WIND_BASE)/target/h -DBN_DEBUG -DREF_CHECK -DCONF_DEBUG -DBN_CTX_DEBUG -DCRYPTO_MDEBUG -DPEDANTIC -DDEBUG_SAFESTACK -DDEBUG -g:::VXWORKS:-r:::::",
"vxworks-ppc860","ccppc:-nostdinc -msoft-float -DCPU=PPC860 -DNO_STRINGS_H -I\$(WIND_BASE)/target/h:::VXWORKS:-r:::::",
"vxworks-simlinux","ccpentium:-B\$(WIND_BASE)/host/\$(WIND_HOST_TYPE)/lib/gcc-lib/ -D_VSB_CONFIG_FILE=\"\$(WIND_BASE)/target/lib/h/config/vsbConfig.h\" -DL_ENDIAN -DCPU=SIMLINUX -DTOOL_FAMILY=gnu -DTOOL=gnu -fno-builtin -fno-defer-pop -DNO_STRINGS_H -I\$(WIND_BASE)/target/h -I\$(WIND_BASE)/target/h/wrn/coreip -DOPENSSL_NO_HW_PADLOCK:::VXWORKS:-r::${no_asm}::::::ranlibpentium:",
"vxworks-mips","ccmips:-mrtp -mips2 -O -G 0 -B\$(WIND_BASE)/host/\$(WIND_HOST_TYPE)/lib/gcc-lib/ -D_VSB_CONFIG_FILE=\"\$(WIND_BASE)/target/lib/h/config/vsbConfig.h\" -DCPU=MIPS32 -msoft-float -mno-branch-likely -DTOOL_FAMILY=gnu -DTOOL=gnu -fno-builtin -fno-defer-pop -DNO_STRINGS_H -I\$(WIND_BASE)/target/usr/h -I\$(WIND_BASE)/target/h/wrn/coreip::-D_REENTRANT:VXWORKS:-Wl,--defsym,__wrs_rtp_base=0xe0000000 -L \$(WIND_BASE)/target/usr/lib/mips/MIPSI32/sfcommon::${mips32_asm}:o32::::::ranlibmips:",
##### Compaq Non-Stop Kernel (Tandem)
"tandem-c89","c89:-Ww -D__TANDEM -D_XOPEN_SOURCE -D_XOPEN_SOURCE_EXTENDED=1 -D_TANDEM_SOURCE -DB_ENDIAN::(unknown):::THIRTY_TWO_BIT:::",
# uClinux
"uClinux-dist","$ENV{'CC'}:\$(CFLAGS)::-D_REENTRANT::\$(LDFLAGS) \$(LDLIBS):BN_LLONG:${no_asm}:$ENV{'LIBSSL_dlfcn'}:linux-shared:-fPIC:-shared:.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR):$ENV{'RANLIB'}::",
"uClinux-dist64","$ENV{'CC'}:\$(CFLAGS)::-D_REENTRANT::\$(LDFLAGS) \$(LDLIBS):SIXTY_FOUR_BIT_LONG:${no_asm}:$ENV{'LIBSSL_dlfcn'}:linux-shared:-fPIC:-shared:.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR):$ENV{'RANLIB'}::",
);
my @MK1MF_Builds=qw(VC-WIN64I VC-WIN64A
debug-VC-WIN64I debug-VC-WIN64A
VC-NT VC-CE VC-WIN32 debug-VC-WIN32
BC-32
netware-clib netware-clib-bsdsock
netware-libc netware-libc-bsdsock);
my $idx = 0;
my $idx_cc = $idx++;
my $idx_cflags = $idx++;
my $idx_unistd = $idx++;
my $idx_thread_cflag = $idx++;
my $idx_sys_id = $idx++;
my $idx_lflags = $idx++;
my $idx_bn_ops = $idx++;
my $idx_cpuid_obj = $idx++;
my $idx_bn_obj = $idx++;
my $idx_ec_obj = $idx++;
my $idx_des_obj = $idx++;
my $idx_aes_obj = $idx++;
my $idx_bf_obj = $idx++;
my $idx_md5_obj = $idx++;
my $idx_sha1_obj = $idx++;
my $idx_cast_obj = $idx++;
my $idx_rc4_obj = $idx++;
my $idx_rmd160_obj = $idx++;
my $idx_rc5_obj = $idx++;
my $idx_wp_obj = $idx++;
my $idx_cmll_obj = $idx++;
my $idx_modes_obj = $idx++;
my $idx_engines_obj = $idx++;
my $idx_perlasm_scheme = $idx++;
my $idx_dso_scheme = $idx++;
my $idx_shared_target = $idx++;
my $idx_shared_cflag = $idx++;
my $idx_shared_ldflag = $idx++;
my $idx_shared_extension = $idx++;
my $idx_ranlib = $idx++;
my $idx_arflags = $idx++;
my $idx_multilib = $idx++;
my $prefix="";
my $libdir="";
my $openssldir="";
my $exe_ext="";
my $install_prefix= "$ENV{'INSTALL_PREFIX'}";
my $cross_compile_prefix="";
my $fipsdir="/usr/local/ssl/fips-2.0";
my $fipslibdir="";
my $baseaddr="0xFB00000";
my $no_threads=0;
my $threads=0;
my $no_shared=0; # but "no-shared" is default
my $zlib=1; # but "no-zlib" is default
my $no_krb5=0; # but "no-krb5" is implied unless "--with-krb5-..." is used
my $no_rfc3779=1; # but "no-rfc3779" is default
my $no_asm=0;
my $no_dso=0;
my $no_gmp=0;
my @skip=();
my $Makefile="Makefile";
my $des_locl="crypto/des/des_locl.h";
my $des ="crypto/des/des.h";
my $bn ="crypto/bn/bn.h";
my $md2 ="crypto/md2/md2.h";
my $rc4 ="crypto/rc4/rc4.h";
my $rc4_locl="crypto/rc4/rc4_locl.h";
my $idea ="crypto/idea/idea.h";
my $rc2 ="crypto/rc2/rc2.h";
my $bf ="crypto/bf/bf_locl.h";
my $bn_asm ="bn_asm.o";
my $des_enc="des_enc.o fcrypt_b.o";
my $aes_enc="aes_core.o aes_cbc.o";
my $bf_enc ="bf_enc.o";
my $cast_enc="c_enc.o";
my $rc4_enc="rc4_enc.o rc4_skey.o";
my $rc5_enc="rc5_enc.o";
my $md5_obj="";
my $sha1_obj="";
my $rmd160_obj="";
my $cmll_enc="camellia.o cmll_misc.o cmll_cbc.o";
my $processor="";
my $default_ranlib;
my $perl;
my $fips=0;
if (exists $ENV{FIPSDIR})
{
$fipsdir = $ENV{FIPSDIR};
$fipsdir =~ s/\/$//;
}
# All of the following is disabled by default (RC5 was enabled before 0.9.8):
my %disabled = ( # "what" => "comment" [or special keyword "experimental"]
"ec_nistp_64_gcc_128" => "default",
"gmp" => "default",
"jpake" => "experimental",
"libunbound" => "experimental",
"md2" => "default",
"rc5" => "default",
"rfc3779" => "default",
"sctp" => "default",
"shared" => "default",
"ssl-trace" => "default",
"ssl2" => "default",
"store" => "experimental",
"unit-test" => "default",
"weak-ssl-ciphers" => "default",
"zlib" => "default",
"zlib-dynamic" => "default"
);
my @experimental = ();
# This is what $depflags will look like with the above defaults
# (we need this to see if we should advise the user to run "make depend"):
my $default_depflags = " -DOPENSSL_NO_EC_NISTP_64_GCC_128 -DOPENSSL_NO_GMP -DOPENSSL_NO_JPAKE -DOPENSSL_NO_LIBUNBOUND -DOPENSSL_NO_MD2 -DOPENSSL_NO_RC5 -DOPENSSL_NO_RFC3779 -DOPENSSL_NO_SCTP -DOPENSSL_NO_SSL_TRACE -DOPENSSL_NO_SSL2 -DOPENSSL_NO_STORE -DOPENSSL_NO_UNIT_TEST -DOPENSSL_NO_WEAK_SSL_CIPHERS";
# Explicit "no-..." options will be collected in %disabled along with the defaults.
# To remove something from %disabled, use "enable-foo" (unless it's experimental).
# For symmetry, "disable-foo" is a synonym for "no-foo".
# For features called "experimental" here, a more explicit "experimental-foo" is needed to enable.
# We will collect such requests in @experimental.
# To avoid accidental use of experimental features, applications will have to use -DOPENSSL_EXPERIMENTAL_FOO.
my $no_sse2=0;
&usage if ($#ARGV < 0);
my $flags;
my $depflags;
my $openssl_experimental_defines;
my $openssl_algorithm_defines;
my $openssl_thread_defines;
my $openssl_sys_defines="";
my $openssl_other_defines;
my $libs;
my $libkrb5="";
my $target;
my $options;
my $symlink;
my $make_depend=0;
my %withargs=();
my @argvcopy=@ARGV;
my $argvstring="";
my $argv_unprocessed=1;
while($argv_unprocessed)
{
$flags="";
$depflags="";
$openssl_experimental_defines="";
$openssl_algorithm_defines="";
$openssl_thread_defines="";
$openssl_sys_defines="";
$openssl_other_defines="";
$libs="";
$target="";
$options="";
$symlink=1;
$argv_unprocessed=0;
$argvstring=join(' ',@argvcopy);
PROCESS_ARGS:
foreach (@argvcopy)
{
s /^-no-/no-/; # some people just can't read the instructions
# 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/;
if (/^no-(.+)$/ || /^disable-(.+)$/)
{
if (!($disabled{$1} eq "experimental"))
{
if ($1 eq "ssl")
{
$disabled{"ssl2"} = "option(ssl)";
$disabled{"ssl3"} = "option(ssl)";
}
elsif ($1 eq "tls")
{
$disabled{"tls1"} = "option(tls)"
}
elsif ($1 eq "ssl3-method")
{
$disabled{"ssl3-method"} = "option(ssl)";
$disabled{"ssl3"} = "option(ssl)";
}
else
{
$disabled{$1} = "option";
}
}
}
elsif (/^enable-(.+)$/ || /^experimental-(.+)$/)
{
my $algo = $1;
if ($disabled{$algo} eq "experimental")
{
die "You are requesting an experimental feature; please say 'experimental-$algo' if you are sure\n"
unless (/^experimental-/);
push @experimental, $algo;
}
delete $disabled{$algo};
$threads = 1 if ($algo eq "threads");
}
elsif (/^--test-sanity$/)
{
exit(&test_sanity());
}
elsif (/^--strict-warnings/)
{
$strict_warnings = 1;
}
elsif (/^reconfigure/ || /^reconf/)
{
if (open(IN,"<$Makefile"))
{
while (<IN>)
{
chomp;
if (/^CONFIGURE_ARGS=(.*)/)
{
$argvstring=$1;
@argvcopy=split(' ',$argvstring);
die "Incorrect data to reconfigure, please do a normal configuration\n"
if (grep(/^reconf/,@argvcopy));
print "Reconfiguring with: $argvstring\n";
$argv_unprocessed=1;
close(IN);
last PROCESS_ARGS;
}
}
close(IN);
}
die "Insufficient data to reconfigure, please do a normal configuration\n";
}
elsif (/^386$/)
{ $processor=386; }
elsif (/^fips$/)
{
$fips=1;
}
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 (/^[-+]/)
{
if (/^--prefix=(.*)$/)
{
$prefix=$1;
}
elsif (/^--libdir=(.*)$/)
{
$libdir=$1;
}
elsif (/^--openssldir=(.*)$/)
{
$openssldir=$1;
}
elsif (/^--install.prefix=(.*)$/)
{
$install_prefix=$1;
}
elsif (/^--with-krb5-(dir|lib|include|flavor)=(.*)$/)
{
$withargs{"krb5-".$1}=$2;
}
elsif (/^--with-zlib-lib=(.*)$/)
{
$withargs{"zlib-lib"}=$1;
}
elsif (/^--with-zlib-include=(.*)$/)
{
$withargs{"zlib-include"}="-I$1";
}
elsif (/^--with-fipsdir=(.*)$/)
{
$fipsdir="$1";
}
elsif (/^--with-fipslibdir=(.*)$/)
{
$fipslibdir="$1";
}
elsif (/^--with-baseaddr=(.*)$/)
{
$baseaddr="$1";
}
elsif (/^--cross-compile-prefix=(.*)$/)
{
$cross_compile_prefix=$1;
}
elsif (/^-[lL](.*)$/ or /^-Wl,/)
{
$libs.=$_." ";
}
else # common if (/^[-+]/), just pass down...
{
$_ =~ s/%([0-9a-f]{1,2})/chr(hex($1))/gei;
$flags.=$_." ";
}
}
elsif ($_ =~ /^([^:]+):(.+)$/)
{
eval "\$table{\$1} = \"$2\""; # allow $xxx constructs in the string
$target=$1;
}
else
{
die "target already defined - $target (offending arg: $_)\n" if ($target ne "");
$target=$_;
}
unless ($_ eq $target || /^no-/ || /^disable-/)
{
# "no-..." follows later after implied disactivations
# have been derived. (Don't take this too seroiusly,
# we really only write OPTIONS to the Makefile out of
# nostalgia.)
if ($options eq "")
{ $options = $_; }
else
{ $options .= " ".$_; }
}
}
}
if ($processor eq "386")
{
$disabled{"sse2"} = "forced";
}
if (!defined($withargs{"krb5-flavor"}) || $withargs{"krb5-flavor"} eq "")
{
$disabled{"krb5"} = "krb5-flavor not specified";
}
if (!defined($disabled{"zlib-dynamic"}))
{
# "zlib-dynamic" was specifically enabled, so enable "zlib"
delete $disabled{"zlib"};
}
if (defined($disabled{"rijndael"}))
{
$disabled{"aes"} = "forced";
}
if (defined($disabled{"des"}))
{
$disabled{"mdc2"} = "forced";
}
if (defined($disabled{"ec"}))
{
$disabled{"ecdsa"} = "forced";
$disabled{"ecdh"} = "forced";
}
# SSL 2.0 requires MD5 and RSA
if (defined($disabled{"md5"}) || defined($disabled{"rsa"}))
{
$disabled{"ssl2"} = "forced";
}
if ($fips && $fipslibdir eq "")
{
$fipslibdir = $fipsdir . "/lib/";
}
# RSAX ENGINE sets default non-FIPS RSA method.
if ($fips)
{
$disabled{"rsax"} = "forced";
}
# SSL 3.0 and TLS requires MD5 and SHA and either RSA or DSA+DH
if (defined($disabled{"md5"}) || defined($disabled{"sha"})
|| (defined($disabled{"rsa"})
&& (defined($disabled{"dsa"}) || defined($disabled{"dh"}))))
{
$disabled{"ssl3"} = "forced";
$disabled{"tls1"} = "forced";
}
if (defined($disabled{"ec"}) || defined($disabled{"dsa"})
|| defined($disabled{"dh"}))
{
$disabled{"gost"} = "forced";
}
# SRP and HEARTBEATS require TLSEXT
if (defined($disabled{"tlsext"}))
{
$disabled{"srp"} = "forced";
$disabled{"heartbeats"} = "forced";
}
if ($target eq "TABLE") {
foreach $target (sort keys %table) {
print_table_entry($target);
}
exit 0;
}
if ($target eq "LIST") {
foreach (sort keys %table) {
print;
print "\n";
}
exit 0;
}
if ($target =~ m/^CygWin32(-.*)$/) {
$target = "Cygwin".$1;
}
print "Configuring for $target\n";
&usage if (!defined($table{$target}));
foreach (sort (keys %disabled))
{
$options .= " no-$_";
printf " no-%-12s %-10s", $_, "[$disabled{$_}]";
if (/^dso$/)
{ $no_dso = 1; }
elsif (/^threads$/)
{ $no_threads = 1; }
elsif (/^shared$/)
{ $no_shared = 1; }
elsif (/^zlib$/)
{ $zlib = 0; }
elsif (/^static-engine$/)
{ }
elsif (/^zlib-dynamic$/)
{ }
elsif (/^symlinks$/)
{ $symlink = 0; }
elsif (/^sse2$/)
{ $no_sse2 = 1; }
else
{
my ($ALGO, $algo);
($ALGO = $algo = $_) =~ tr/[\-a-z]/[_A-Z]/;
if (/^asm$/ || /^err$/ || /^hw$/ || /^hw-/)
{
$openssl_other_defines .= "#define OPENSSL_NO_$ALGO\n";
print " OPENSSL_NO_$ALGO";
if (/^err$/) { $flags .= "-DOPENSSL_NO_ERR "; }
elsif (/^asm$/) { $no_asm = 1; }
}
else
{
$openssl_algorithm_defines .= "#define OPENSSL_NO_$ALGO\n";
print " OPENSSL_NO_$ALGO";
if (/^krb5$/)
{ $no_krb5 = 1; }
else
{
push @skip, $algo;
# fix-up crypto/directory name(s)
@skip[$#skip]="whrlpool" if $algo eq "whirlpool";
print " (skip dir)";
$depflags .= " -DOPENSSL_NO_$ALGO";
}
}
}
print "\n";
}
my $exp_cflags = "";
foreach (sort @experimental)
{
my $ALGO;
($ALGO = $_) =~ tr/[a-z]/[A-Z]/;
# opensslconf.h will set OPENSSL_NO_... unless OPENSSL_EXPERIMENTAL_... is defined
$openssl_experimental_defines .= "#define OPENSSL_NO_$ALGO\n";
$exp_cflags .= " -DOPENSSL_EXPERIMENTAL_$ALGO";
}
my $IsMK1MF=scalar grep /^$target$/,@MK1MF_Builds;
$exe_ext=".exe" if ($target eq "Cygwin" || $target eq "DJGPP" || $target =~ /^mingw/);
$exe_ext=".nlm" if ($target =~ /netware/);
$exe_ext=".pm" if ($target =~ /vos/);
$openssldir="/usr/local/ssl" if ($openssldir eq "" and $prefix eq "");
$prefix=$openssldir if $prefix eq "";
$default_ranlib= &which("ranlib") or $default_ranlib="true";
$perl=$ENV{'PERL'} or $perl=&which("perl5") or $perl=&which("perl")
or $perl="perl";
my $make = $ENV{'MAKE'} || "make";
$cross_compile_prefix=$ENV{'CROSS_COMPILE'} if $cross_compile_prefix eq "";
chop $openssldir if $openssldir =~ /\/$/;
chop $prefix if $prefix =~ /.\/$/;
$openssldir=$prefix . "/ssl" if $openssldir eq "";
$openssldir=$prefix . "/" . $openssldir if $openssldir !~ /(^\/|^[a-zA-Z]:[\\\/])/;
print "IsMK1MF=$IsMK1MF\n";
my @fields = split(/\s*:\s*/,$table{$target} . ":" x 30 , -1);
my $cc = $fields[$idx_cc];
# Allow environment CC to override compiler...
if($ENV{CC}) {
$cc = $ENV{CC};
}
my $cflags = $fields[$idx_cflags];
my $unistd = $fields[$idx_unistd];
my $thread_cflag = $fields[$idx_thread_cflag];
my $sys_id = $fields[$idx_sys_id];
my $lflags = $fields[$idx_lflags];
my $bn_ops = $fields[$idx_bn_ops];
my $cpuid_obj = $fields[$idx_cpuid_obj];
my $bn_obj = $fields[$idx_bn_obj];
my $ec_obj = $fields[$idx_ec_obj];
my $des_obj = $fields[$idx_des_obj];
my $aes_obj = $fields[$idx_aes_obj];
my $bf_obj = $fields[$idx_bf_obj];
my $md5_obj = $fields[$idx_md5_obj];
my $sha1_obj = $fields[$idx_sha1_obj];
my $cast_obj = $fields[$idx_cast_obj];
my $rc4_obj = $fields[$idx_rc4_obj];
my $rmd160_obj = $fields[$idx_rmd160_obj];
my $rc5_obj = $fields[$idx_rc5_obj];
my $wp_obj = $fields[$idx_wp_obj];
my $cmll_obj = $fields[$idx_cmll_obj];
my $modes_obj = $fields[$idx_modes_obj];
my $engines_obj = $fields[$idx_engines_obj];
my $perlasm_scheme = $fields[$idx_perlasm_scheme];
my $dso_scheme = $fields[$idx_dso_scheme];
my $shared_target = $fields[$idx_shared_target];
my $shared_cflag = $fields[$idx_shared_cflag];
my $shared_ldflag = $fields[$idx_shared_ldflag];
my $shared_extension = $fields[$idx_shared_extension];
my $ranlib = $ENV{'RANLIB'} || $fields[$idx_ranlib];
my $ar = $ENV{'AR'} || "ar";
my $arflags = $fields[$idx_arflags];
my $windres = $ENV{'RC'} || $ENV{'WINDRES'} || "windres";
my $multilib = $fields[$idx_multilib];
# if $prefix/lib$multilib is not an existing directory, then
# assume that it's not searched by linker automatically, in
# which case adding $multilib suffix causes more grief than
# we're ready to tolerate, so don't...
$multilib="" if !-d "$prefix/lib$multilib";
$libdir="lib$multilib" if $libdir eq "";
$cflags = "$cflags$exp_cflags";
# '%' in $lflags is used to split flags to "pre-" and post-flags
my ($prelflags,$postlflags)=split('%',$lflags);
if (defined($postlflags)) { $lflags=$postlflags; }
else { $lflags=$prelflags; undef $prelflags; }
-if ($target =~ /^mingw/ && `$cc --target-help 2>&1` !~ m/\-mno\-cygwin/m)
+if ($target =~ /^mingw/ && `$cross_compile_prefix$cc --target-help 2>&1` !~ m/\-mno\-cygwin/m)
{
$cflags =~ s/\-mno\-cygwin\s*//;
$shared_ldflag =~ s/\-mno\-cygwin\s*//;
}
if ($target =~ /linux.*\-mips/ && !$no_asm && $flags !~ /\-m(ips|arch=)/) {
# minimally required architecture flags for assembly modules
$cflags="-mips2 $cflags" if ($target =~ /mips32/);
$cflags="-mips3 $cflags" if ($target =~ /mips64/);
}
my $no_shared_warn=0;
my $no_user_cflags=0;
if ($flags ne "") { $cflags="$flags$cflags"; }
else { $no_user_cflags=1; }
# Kerberos settings. The flavor must be provided from outside, either through
# the script "config" or manually.
if (!$no_krb5)
{
my ($lresolv, $lpath, $lext);
if ($withargs{"krb5-flavor"} =~ /^[Hh]eimdal$/)
{
die "Sorry, Heimdal is currently not supported\n";
}
##### HACK to force use of Heimdal.
##### WARNING: Since we don't really have adequate support for Heimdal,
##### using this will break the build. You'll have to make
##### changes to the source, and if you do, please send
##### patches to openssl-dev@openssl.org
if ($withargs{"krb5-flavor"} =~ /^force-[Hh]eimdal$/)
{
warn "Heimdal isn't really supported. Your build WILL break\n";
warn "If you fix the problems, please send a patch to openssl-dev\@openssl.org\n";
$withargs{"krb5-dir"} = "/usr/heimdal"
if $withargs{"krb5-dir"} eq "";
$withargs{"krb5-lib"} = "-L".$withargs{"krb5-dir"}.
"/lib -lgssapi -lkrb5 -lcom_err"
if $withargs{"krb5-lib"} eq "" && !$IsMK1MF;
$cflags="-DKRB5_HEIMDAL $cflags";
}
if ($withargs{"krb5-flavor"} =~ /^[Mm][Ii][Tt]/)
{
$withargs{"krb5-dir"} = "/usr/kerberos"
if $withargs{"krb5-dir"} eq "";
$withargs{"krb5-lib"} = "-L".$withargs{"krb5-dir"}.
"/lib -lgssapi_krb5 -lkrb5 -lcom_err -lk5crypto"
if $withargs{"krb5-lib"} eq "" && !$IsMK1MF;
$cflags="-DKRB5_MIT $cflags";
$withargs{"krb5-flavor"} =~ s/^[Mm][Ii][Tt][._-]*//;
if ($withargs{"krb5-flavor"} =~ /^1[._-]*[01]/)
{
$cflags="-DKRB5_MIT_OLD11 $cflags";
}
}
LRESOLV:
foreach $lpath ("/lib", "/usr/lib")
{
foreach $lext ("a", "so")
{
$lresolv = "$lpath/libresolv.$lext";
last LRESOLV if (-r "$lresolv");
$lresolv = "";
}
}
$withargs{"krb5-lib"} .= " -lresolv"
if ("$lresolv" ne "");
$withargs{"krb5-include"} = "-I".$withargs{"krb5-dir"}."/include"
if $withargs{"krb5-include"} eq "" &&
$withargs{"krb5-dir"} ne "";
}
# The DSO code currently always implements all functions so that no
# applications will have to worry about that from a compilation point
# of view. However, the "method"s may return zero unless that platform
# has support compiled in for them. Currently each method is enabled
# by a define "DSO_<name>" ... we translate the "dso_scheme" config
# string entry into using the following logic;
my $dso_cflags;
if (!$no_dso && $dso_scheme ne "")
{
$dso_scheme =~ tr/[a-z]/[A-Z]/;
if ($dso_scheme eq "DLFCN")
{
$dso_cflags = "-DDSO_DLFCN -DHAVE_DLFCN_H";
}
elsif ($dso_scheme eq "DLFCN_NO_H")
{
$dso_cflags = "-DDSO_DLFCN";
}
else
{
$dso_cflags = "-DDSO_$dso_scheme";
}
$cflags = "$dso_cflags $cflags";
}
my $thread_cflags;
my $thread_defines;
if ($thread_cflag ne "(unknown)" && !$no_threads)
{
# If we know how to do it, support threads by default.
$threads = 1;
}
if ($thread_cflag eq "(unknown)" && $threads)
{
# If the user asked for "threads", [s]he is also expected to
# provide any system-dependent compiler options that are
# necessary.
if ($no_user_cflags)
{
print "You asked for multi-threading support, but didn't\n";
print "provide any system-specific compiler options\n";
exit(1);
}
$thread_cflags="-DOPENSSL_THREADS $cflags" ;
$thread_defines .= "#define OPENSSL_THREADS\n";
}
else
{
$thread_cflags="-DOPENSSL_THREADS $thread_cflag $cflags";
$thread_defines .= "#define OPENSSL_THREADS\n";
# my $def;
# foreach $def (split ' ',$thread_cflag)
# {
# if ($def =~ s/^-D// && $def !~ /^_/)
# {
# $thread_defines .= "#define $def\n";
# }
# }
}
$lflags="$libs$lflags" if ($libs ne "");
if ($no_asm)
{
$cpuid_obj=$bn_obj=$ec_obj=
$des_obj=$aes_obj=$bf_obj=$cast_obj=$rc4_obj=$rc5_obj=$cmll_obj=
$modes_obj=$sha1_obj=$md5_obj=$rmd160_obj=$wp_obj=$engines_obj="";
}
if (!$no_shared)
{
$cast_obj=""; # CAST assembler is not PIC
}
if ($threads)
{
$cflags=$thread_cflags;
$openssl_thread_defines .= $thread_defines;
}
if ($zlib)
{
$cflags = "-DZLIB $cflags";
if (defined($disabled{"zlib-dynamic"}))
{
if (defined($withargs{"zlib-lib"}))
{
$lflags = "$lflags -L" . $withargs{"zlib-lib"} . " -lz";
}
else
{
$lflags = "$lflags -lz";
}
}
else
{
$cflags = "-DZLIB_SHARED $cflags";
}
}
# You will find shlib_mark1 and shlib_mark2 explained in Makefile.org
my $shared_mark = "";
if ($shared_target eq "")
{
$no_shared_warn = 1 if !$no_shared;
$no_shared = 1;
}
if (!$no_shared)
{
if ($shared_cflag ne "")
{
$cflags = "$shared_cflag -DOPENSSL_PIC $cflags";
}
}
if (!$IsMK1MF)
{
# add {no-}static-engine to options to allow mkdef.pl to work without extra arguments
if ($no_shared)
{
$openssl_other_defines.="#define OPENSSL_NO_DYNAMIC_ENGINE\n";
$options.=" static-engine";
}
else
{
$openssl_other_defines.="#define OPENSSL_NO_STATIC_ENGINE\n";
$options.=" no-static-engine";
}
}
$cpuid_obj.=" uplink.o uplink-x86.o" if ($cflags =~ /\-DOPENSSL_USE_APPLINK/);
#
# Platform fix-ups
#
if ($target =~ /\-icc$/) # Intel C compiler
{
my $iccver=0;
if (open(FD,"$cc -V 2>&1 |"))
{
while(<FD>) { $iccver=$1 if (/Version ([0-9]+)\./); }
close(FD);
}
if ($iccver>=8)
{
$cflags=~s/\-KPIC/-fPIC/;
# Eliminate unnecessary dependency from libirc.a. This is
# essential for shared library support, as otherwise
# apps/openssl can end up in endless loop upon startup...
$cflags.=" -Dmemcpy=__builtin_memcpy -Dmemset=__builtin_memset";
}
if ($iccver>=9)
{
$lflags.=" -i-static";
$lflags=~s/\-no_cpprt/-no-cpprt/;
}
if ($iccver>=10)
{
$lflags=~s/\-i\-static/-static-intel/;
}
if ($iccver>=11)
{
$cflags.=" -no-intel-extensions"; # disable Cilk
$lflags=~s/\-no\-cpprt/-no-cxxlib/;
}
}
# Unlike other OSes (like Solaris, Linux, Tru64, IRIX) BSD run-time
# linkers (tested OpenBSD, NetBSD and FreeBSD) "demand" RPATH set on
# .so objects. Apparently application RPATH is not global and does
# not apply to .so linked with other .so. Problem manifests itself
# when libssl.so fails to load libcrypto.so. One can argue that we
# should engrave this into Makefile.shared rules or into BSD-* config
# lines above. Meanwhile let's try to be cautious and pass -rpath to
# linker only when --prefix is not /usr.
if ($target =~ /^BSD\-/)
{
$shared_ldflag.=" -Wl,-rpath,\$\$(LIBRPATH)" if ($prefix !~ m|^/usr[/]*$|);
}
if ($sys_id ne "")
{
#$cflags="-DOPENSSL_SYSNAME_$sys_id $cflags";
$openssl_sys_defines="#define OPENSSL_SYSNAME_$sys_id\n";
}
if ($ranlib eq "")
{
$ranlib = $default_ranlib;
}
#my ($bn1)=split(/\s+/,$bn_obj);
#$bn1 = "" unless defined $bn1;
#$bn1=$bn_asm unless ($bn1 =~ /\.o$/);
#$bn_obj="$bn1";
$cpuid_obj="" if ($processor eq "386");
$bn_obj = $bn_asm unless $bn_obj ne "";
# bn-586 is the only one implementing bn_*_part_words
$cflags.=" -DOPENSSL_BN_ASM_PART_WORDS" if ($bn_obj =~ /bn-586/);
$cflags.=" -DOPENSSL_IA32_SSE2" if (!$no_sse2 && $bn_obj =~ /86/);
$cflags.=" -DOPENSSL_BN_ASM_MONT" if ($bn_obj =~ /-mont/);
$cflags.=" -DOPENSSL_BN_ASM_MONT5" if ($bn_obj =~ /-mont5/);
$cflags.=" -DOPENSSL_BN_ASM_GF2m" if ($bn_obj =~ /-gf2m/);
if ($fips)
{
$openssl_other_defines.="#define OPENSSL_FIPS\n";
$cflags .= " -I\$(FIPSDIR)/include";
}
$cpuid_obj="mem_clr.o" unless ($cpuid_obj =~ /\.o$/);
$des_obj=$des_enc unless ($des_obj =~ /\.o$/);
$bf_obj=$bf_enc unless ($bf_obj =~ /\.o$/);
$cast_obj=$cast_enc unless ($cast_obj =~ /\.o$/);
$rc5_obj=$rc5_enc unless ($rc5_obj =~ /\.o$/);
if ($rc4_obj =~ /\.o$/)
{
$cflags.=" -DRC4_ASM";
}
else
{
$rc4_obj=$rc4_enc;
}
if ($sha1_obj =~ /\.o$/)
{
# $sha1_obj=$sha1_enc;
$cflags.=" -DSHA1_ASM" if ($sha1_obj =~ /sx86/ || $sha1_obj =~ /sha1/);
$cflags.=" -DSHA256_ASM" if ($sha1_obj =~ /sha256/);
$cflags.=" -DSHA512_ASM" if ($sha1_obj =~ /sha512/);
if ($sha1_obj =~ /sse2/)
{ if ($no_sse2)
{ $sha1_obj =~ s/\S*sse2\S+//; }
elsif ($cflags !~ /OPENSSL_IA32_SSE2/)
{ $cflags.=" -DOPENSSL_IA32_SSE2"; }
}
}
if ($md5_obj =~ /\.o$/)
{
# $md5_obj=$md5_enc;
$cflags.=" -DMD5_ASM";
}
if ($rmd160_obj =~ /\.o$/)
{
# $rmd160_obj=$rmd160_enc;
$cflags.=" -DRMD160_ASM";
}
if ($aes_obj =~ /\.o$/)
{
$cflags.=" -DAES_ASM" if ($aes_obj =~ m/\baes\-/);;
# aes-ctr.o is not a real file, only indication that assembler
# module implements AES_ctr32_encrypt...
$cflags.=" -DAES_CTR_ASM" if ($aes_obj =~ s/\s*aes\-ctr\.o//);
# aes-xts.o indicates presense of AES_xts_[en|de]crypt...
$cflags.=" -DAES_XTS_ASM" if ($aes_obj =~ s/\s*aes\-xts\.o//);
$aes_obj =~ s/\s*(vpaes|aesni)\-x86\.o//g if ($no_sse2);
$cflags.=" -DVPAES_ASM" if ($aes_obj =~ m/vpaes/);
$cflags.=" -DBSAES_ASM" if ($aes_obj =~ m/bsaes/);
}
else {
$aes_obj=$aes_enc;
}
$wp_obj="" if ($wp_obj =~ /mmx/ && $processor eq "386");
if ($wp_obj =~ /\.o$/ && !$disabled{"whirlpool"})
{
$cflags.=" -DWHIRLPOOL_ASM";
}
else {
$wp_obj="wp_block.o";
}
$cmll_obj=$cmll_enc unless ($cmll_obj =~ /.o$/);
if ($modes_obj =~ /ghash\-/)
{
$cflags.=" -DGHASH_ASM";
}
if ($ec_obj =~ /ecp_nistz256/)
{
$cflags.=" -DECP_NISTZ256_ASM";
}
# "Stringify" the C flags string. This permits it to be made part of a string
# and works as well on command lines.
$cflags =~ s/([\\\"])/\\\1/g;
my $version = "unknown";
my $version_num = "unknown";
my $major = "unknown";
my $minor = "unknown";
my $shlib_version_number = "unknown";
my $shlib_version_history = "unknown";
my $shlib_major = "unknown";
my $shlib_minor = "unknown";
open(IN,'<crypto/opensslv.h') || die "unable to read opensslv.h:$!\n";
while (<IN>)
{
$version=$1 if /OPENSSL.VERSION.TEXT.*OpenSSL (\S+) /;
$version_num=$1 if /OPENSSL.VERSION.NUMBER.*0x(\S+)/;
$shlib_version_number=$1 if /SHLIB_VERSION_NUMBER *"([^"]+)"/;
$shlib_version_history=$1 if /SHLIB_VERSION_HISTORY *"([^"]*)"/;
}
close(IN);
if ($shlib_version_history ne "") { $shlib_version_history .= ":"; }
if ($version =~ /(^[0-9]*)\.([0-9\.]*)/)
{
$major=$1;
$minor=$2;
}
if ($shlib_version_number =~ /(^[0-9]*)\.([0-9\.]*)/)
{
$shlib_major=$1;
$shlib_minor=$2;
}
-my $ecc = $cc;
-$ecc = "clang" if `$cc --version 2>&1` =~ /clang/;
+my %predefined;
+
+# collect compiler pre-defines from gcc or gcc-alike...
+open(PIPE, "$cross_compile_prefix$cc -dM -E -x c /dev/null 2>&1 |");
+while (<PIPE>) {
+ m/^#define\s+(\w+(?:\(\w+\))?)(?:\s+(.+))?/ or last;
+ $predefined{$1} = defined($2) ? $2 : "";
+}
+close(PIPE);
if ($strict_warnings)
{
my $wopt;
- die "ERROR --strict-warnings requires gcc or clang" unless ($ecc =~ /gcc$/ or $ecc =~ /clang$/);
+ die "ERROR --strict-warnings requires gcc or clang" unless defined($predefined{__GNUC__});
foreach $wopt (split /\s+/, $gcc_devteam_warn)
{
$cflags .= " $wopt" unless ($cflags =~ /(^|\s)$wopt(\s|$)/)
}
- if ($ecc eq "clang")
+ if (defined($predefined{__clang__}))
{
foreach $wopt (split /\s+/, $clang_devteam_warn)
{
$cflags .= " $wopt" unless ($cflags =~ /(^|\s)$wopt(\s|$)/)
}
}
}
open(IN,'<Makefile.org') || die "unable to read Makefile.org:$!\n";
unlink("$Makefile.new") || die "unable to remove old $Makefile.new:$!\n" if -e "$Makefile.new";
open(OUT,">$Makefile.new") || die "unable to create $Makefile.new:$!\n";
print OUT "### Generated automatically from Makefile.org by Configure.\n\n";
my $sdirs=0;
while (<IN>)
{
chomp;
$sdirs = 1 if /^SDIRS=/;
if ($sdirs) {
my $dir;
foreach $dir (@skip) {
s/(\s)$dir /$1/;
s/\s$dir$//;
}
}
$sdirs = 0 unless /\\$/;
s/engines // if (/^DIRS=/ && $disabled{"engine"});
s/ccgost// if (/^ENGDIRS=/ && $disabled{"gost"});
s/^VERSION=.*/VERSION=$version/;
s/^MAJOR=.*/MAJOR=$major/;
s/^MINOR=.*/MINOR=$minor/;
s/^SHLIB_VERSION_NUMBER=.*/SHLIB_VERSION_NUMBER=$shlib_version_number/;
s/^SHLIB_VERSION_HISTORY=.*/SHLIB_VERSION_HISTORY=$shlib_version_history/;
s/^SHLIB_MAJOR=.*/SHLIB_MAJOR=$shlib_major/;
s/^SHLIB_MINOR=.*/SHLIB_MINOR=$shlib_minor/;
s/^SHLIB_EXT=.*/SHLIB_EXT=$shared_extension/;
s/^INSTALLTOP=.*$/INSTALLTOP=$prefix/;
s/^MULTILIB=.*$/MULTILIB=$multilib/;
s/^OPENSSLDIR=.*$/OPENSSLDIR=$openssldir/;
s/^LIBDIR=.*$/LIBDIR=$libdir/;
s/^INSTALL_PREFIX=.*$/INSTALL_PREFIX=$install_prefix/;
s/^PLATFORM=.*$/PLATFORM=$target/;
s/^OPTIONS=.*$/OPTIONS=$options/;
s/^CONFIGURE_ARGS=.*$/CONFIGURE_ARGS=$argvstring/;
if ($cross_compile_prefix)
{
s/^CC=.*$/CROSS_COMPILE= $cross_compile_prefix\nCC= \$\(CROSS_COMPILE\)$cc/;
s/^AR=\s*/AR= \$\(CROSS_COMPILE\)/;
s/^NM=\s*/NM= \$\(CROSS_COMPILE\)/;
s/^RANLIB=\s*/RANLIB= \$\(CROSS_COMPILE\)/;
s/^RC=\s*/RC= \$\(CROSS_COMPILE\)/;
- s/^MAKEDEPPROG=.*$/MAKEDEPPROG= \$\(CROSS_COMPILE\)$cc/ if $cc eq "gcc";
+ s/^MAKEDEPPROG=.*$/MAKEDEPPROG= \$\(CROSS_COMPILE\)$cc/ if $predefined{__GNUC__} >= 3;
}
else {
s/^CC=.*$/CC= $cc/;
s/^AR=\s*ar/AR= $ar/;
s/^RANLIB=.*/RANLIB= $ranlib/;
s/^RC=.*/RC= $windres/;
- s/^MAKEDEPPROG=.*$/MAKEDEPPROG= $cc/ if $cc eq "gcc";
- s/^MAKEDEPPROG=.*$/MAKEDEPPROG= $cc/ if $ecc eq "gcc" || $ecc eq "clang";
+ s/^MAKEDEPPROG=.*$/MAKEDEPPROG= $cc/ if $predefined{__GNUC__} >= 3;
}
s/^CFLAG=.*$/CFLAG= $cflags/;
s/^DEPFLAG=.*$/DEPFLAG=$depflags/;
s/^PEX_LIBS=.*$/PEX_LIBS= $prelflags/;
s/^EX_LIBS=.*$/EX_LIBS= $lflags/;
s/^EXE_EXT=.*$/EXE_EXT= $exe_ext/;
s/^CPUID_OBJ=.*$/CPUID_OBJ= $cpuid_obj/;
s/^BN_ASM=.*$/BN_ASM= $bn_obj/;
s/^EC_ASM=.*$/EC_ASM= $ec_obj/;
s/^DES_ENC=.*$/DES_ENC= $des_obj/;
s/^AES_ENC=.*$/AES_ENC= $aes_obj/;
s/^BF_ENC=.*$/BF_ENC= $bf_obj/;
s/^CAST_ENC=.*$/CAST_ENC= $cast_obj/;
s/^RC4_ENC=.*$/RC4_ENC= $rc4_obj/;
s/^RC5_ENC=.*$/RC5_ENC= $rc5_obj/;
s/^MD5_ASM_OBJ=.*$/MD5_ASM_OBJ= $md5_obj/;
s/^SHA1_ASM_OBJ=.*$/SHA1_ASM_OBJ= $sha1_obj/;
s/^RMD160_ASM_OBJ=.*$/RMD160_ASM_OBJ= $rmd160_obj/;
s/^WP_ASM_OBJ=.*$/WP_ASM_OBJ= $wp_obj/;
s/^CMLL_ENC=.*$/CMLL_ENC= $cmll_obj/;
s/^MODES_ASM_OBJ.=*$/MODES_ASM_OBJ= $modes_obj/;
s/^ENGINES_ASM_OBJ.=*$/ENGINES_ASM_OBJ= $engines_obj/;
s/^PERLASM_SCHEME=.*$/PERLASM_SCHEME= $perlasm_scheme/;
s/^PROCESSOR=.*/PROCESSOR= $processor/;
s/^ARFLAGS=.*/ARFLAGS= $arflags/;
s/^PERL=.*/PERL= $perl/;
s/^KRB5_INCLUDES=.*/KRB5_INCLUDES=$withargs{"krb5-include"}/;
s/^LIBKRB5=.*/LIBKRB5=$withargs{"krb5-lib"}/;
s/^LIBZLIB=.*/LIBZLIB=$withargs{"zlib-lib"}/;
s/^ZLIB_INCLUDE=.*/ZLIB_INCLUDE=$withargs{"zlib-include"}/;
s/^FIPSDIR=.*/FIPSDIR=$fipsdir/;
s/^FIPSLIBDIR=.*/FIPSLIBDIR=$fipslibdir/;
s/^FIPSCANLIB=.*/FIPSCANLIB=libcrypto/ if $fips;
s/^BASEADDR=.*/BASEADDR=$baseaddr/;
s/^SHLIB_TARGET=.*/SHLIB_TARGET=$shared_target/;
s/^SHLIB_MARK=.*/SHLIB_MARK=$shared_mark/;
s/^SHARED_LIBS=.*/SHARED_LIBS=\$(SHARED_CRYPTO) \$(SHARED_SSL)/ if (!$no_shared);
if ($shared_extension ne "" && $shared_extension =~ /^\.s([ol])\.[^\.]*$/)
{
my $sotmp = $1;
s/^SHARED_LIBS_LINK_EXTS=.*/SHARED_LIBS_LINK_EXTS=.s$sotmp/;
}
elsif ($shared_extension ne "" && $shared_extension =~ /^\.[^\.]*\.dylib$/)
{
s/^SHARED_LIBS_LINK_EXTS=.*/SHARED_LIBS_LINK_EXTS=.dylib/;
}
elsif ($shared_extension ne "" && $shared_extension =~ /^\.s([ol])\.[^\.]*\.[^\.]*$/)
{
my $sotmp = $1;
s/^SHARED_LIBS_LINK_EXTS=.*/SHARED_LIBS_LINK_EXTS=.s$sotmp.\$(SHLIB_MAJOR) .s$sotmp/;
}
elsif ($shared_extension ne "" && $shared_extension =~ /^\.[^\.]*\.[^\.]*\.dylib$/)
{
s/^SHARED_LIBS_LINK_EXTS=.*/SHARED_LIBS_LINK_EXTS=.\$(SHLIB_MAJOR).dylib .dylib/;
}
s/^SHARED_LDFLAGS=.*/SHARED_LDFLAGS=$shared_ldflag/;
print OUT $_."\n";
}
close(IN);
close(OUT);
if ((compare($Makefile, "$Makefile.new"))
or file_newer('Configure', $Makefile)
or file_newer('config', $Makefile)
or file_newer('Makefile.org', $Makefile))
{
rename($Makefile,"$Makefile.bak") || die "unable to rename $Makefile\n" if -e $Makefile;
rename("$Makefile.new",$Makefile) || die "unable to rename $Makefile.new\n";
}
else
{ unlink("$Makefile.new"); }
print "CC =$cc\n";
print "CFLAG =$cflags\n";
print "EX_LIBS =$lflags\n";
print "CPUID_OBJ =$cpuid_obj\n";
print "BN_ASM =$bn_obj\n";
print "EC_ASM =$ec_obj\n";
print "DES_ENC =$des_obj\n";
print "AES_ENC =$aes_obj\n";
print "BF_ENC =$bf_obj\n";
print "CAST_ENC =$cast_obj\n";
print "RC4_ENC =$rc4_obj\n";
print "RC5_ENC =$rc5_obj\n";
print "MD5_OBJ_ASM =$md5_obj\n";
print "SHA1_OBJ_ASM =$sha1_obj\n";
print "RMD160_OBJ_ASM=$rmd160_obj\n";
print "CMLL_ENC =$cmll_obj\n";
print "MODES_OBJ =$modes_obj\n";
print "ENGINES_OBJ =$engines_obj\n";
print "PROCESSOR =$processor\n";
print "RANLIB =$ranlib\n";
print "ARFLAGS =$arflags\n";
print "PERL =$perl\n";
print "KRB5_INCLUDES =",$withargs{"krb5-include"},"\n"
if $withargs{"krb5-include"} ne "";
my $des_ptr=0;
my $des_risc1=0;
my $des_risc2=0;
my $des_unroll=0;
my $bn_ll=0;
my $def_int=2;
my $rc4_int=$def_int;
my $md2_int=$def_int;
my $idea_int=$def_int;
my $rc2_int=$def_int;
my $rc4_idx=0;
my $rc4_chunk=0;
my $bf_ptr=0;
my @type=("char","short","int","long");
my ($b64l,$b64,$b32,$b16,$b8)=(0,0,1,0,0);
my $export_var_as_fn=0;
my $des_int;
foreach (sort split(/\s+/,$bn_ops))
{
$des_ptr=1 if /DES_PTR/;
$des_risc1=1 if /DES_RISC1/;
$des_risc2=1 if /DES_RISC2/;
$des_unroll=1 if /DES_UNROLL/;
$des_int=1 if /DES_INT/;
$bn_ll=1 if /BN_LLONG/;
$rc4_int=0 if /RC4_CHAR/;
$rc4_int=3 if /RC4_LONG/;
$rc4_idx=1 if /RC4_INDEX/;
$rc4_chunk=1 if /RC4_CHUNK/;
$rc4_chunk=2 if /RC4_CHUNK_LL/;
$md2_int=0 if /MD2_CHAR/;
$md2_int=3 if /MD2_LONG/;
$idea_int=1 if /IDEA_SHORT/;
$idea_int=3 if /IDEA_LONG/;
$rc2_int=1 if /RC2_SHORT/;
$rc2_int=3 if /RC2_LONG/;
$bf_ptr=1 if $_ eq "BF_PTR";
$bf_ptr=2 if $_ eq "BF_PTR2";
($b64l,$b64,$b32,$b16,$b8)=(0,1,0,0,0) if /SIXTY_FOUR_BIT/;
($b64l,$b64,$b32,$b16,$b8)=(1,0,0,0,0) if /SIXTY_FOUR_BIT_LONG/;
($b64l,$b64,$b32,$b16,$b8)=(0,0,1,0,0) if /THIRTY_TWO_BIT/;
($b64l,$b64,$b32,$b16,$b8)=(0,0,0,1,0) if /SIXTEEN_BIT/;
($b64l,$b64,$b32,$b16,$b8)=(0,0,0,0,1) if /EIGHT_BIT/;
$export_var_as_fn=1 if /EXPORT_VAR_AS_FN/;
}
open(IN,'<crypto/opensslconf.h.in') || die "unable to read crypto/opensslconf.h.in:$!\n";
unlink("crypto/opensslconf.h.new") || die "unable to remove old crypto/opensslconf.h.new:$!\n" if -e "crypto/opensslconf.h.new";
open(OUT,'>crypto/opensslconf.h.new') || die "unable to create crypto/opensslconf.h.new:$!\n";
print OUT "/* opensslconf.h */\n";
print OUT "/* WARNING: Generated automatically from opensslconf.h.in by Configure. */\n\n";
print OUT "#ifdef __cplusplus\n";
print OUT "extern \"C\" {\n";
print OUT "#endif\n";
print OUT "/* OpenSSL was configured with the following options: */\n";
my $openssl_algorithm_defines_trans = $openssl_algorithm_defines;
$openssl_experimental_defines =~ s/^\s*#\s*define\s+OPENSSL_NO_(.*)/#ifndef OPENSSL_EXPERIMENTAL_$1\n# ifndef OPENSSL_NO_$1\n# define OPENSSL_NO_$1\n# endif\n#endif/mg;
$openssl_algorithm_defines_trans =~ s/^\s*#\s*define\s+OPENSSL_(.*)/# if defined(OPENSSL_$1) \&\& !defined($1)\n# define $1\n# endif/mg;
$openssl_algorithm_defines =~ s/^\s*#\s*define\s+(.*)/#ifndef $1\n# define $1\n#endif/mg;
$openssl_algorithm_defines = " /* no ciphers excluded */\n" if $openssl_algorithm_defines eq "";
$openssl_thread_defines =~ s/^\s*#\s*define\s+(.*)/#ifndef $1\n# define $1\n#endif/mg;
$openssl_sys_defines =~ s/^\s*#\s*define\s+(.*)/#ifndef $1\n# define $1\n#endif/mg;
$openssl_other_defines =~ s/^\s*#\s*define\s+(.*)/#ifndef $1\n# define $1\n#endif/mg;
print OUT $openssl_sys_defines;
print OUT "#ifndef OPENSSL_DOING_MAKEDEPEND\n\n";
print OUT $openssl_experimental_defines;
print OUT "\n";
print OUT $openssl_algorithm_defines;
print OUT "\n#endif /* OPENSSL_DOING_MAKEDEPEND */\n\n";
print OUT $openssl_thread_defines;
print OUT $openssl_other_defines,"\n";
print OUT "/* The OPENSSL_NO_* macros are also defined as NO_* if the application\n";
print OUT " asks for it. This is a transient feature that is provided for those\n";
print OUT " who haven't had the time to do the appropriate changes in their\n";
print OUT " applications. */\n";
print OUT "#ifdef OPENSSL_ALGORITHM_DEFINES\n";
print OUT $openssl_algorithm_defines_trans;
print OUT "#endif\n\n";
print OUT "#define OPENSSL_CPUID_OBJ\n\n" if ($cpuid_obj ne "mem_clr.o");
while (<IN>)
{
if (/^#define\s+OPENSSLDIR/)
{
my $foo = $openssldir;
$foo =~ s/\\/\\\\/g;
print OUT "#define OPENSSLDIR \"$foo\"\n";
}
elsif (/^#define\s+ENGINESDIR/)
{
my $foo = "$prefix/$libdir/engines";
$foo =~ s/\\/\\\\/g;
print OUT "#define ENGINESDIR \"$foo\"\n";
}
elsif (/^#((define)|(undef))\s+OPENSSL_EXPORT_VAR_AS_FUNCTION/)
{ printf OUT "#undef OPENSSL_EXPORT_VAR_AS_FUNCTION\n"
if $export_var_as_fn;
printf OUT "#%s OPENSSL_EXPORT_VAR_AS_FUNCTION\n",
($export_var_as_fn)?"define":"undef"; }
elsif (/^#define\s+OPENSSL_UNISTD/)
{
$unistd = "<unistd.h>" if $unistd eq "";
print OUT "#define OPENSSL_UNISTD $unistd\n";
}
elsif (/^#((define)|(undef))\s+SIXTY_FOUR_BIT_LONG/)
{ printf OUT "#%s SIXTY_FOUR_BIT_LONG\n",($b64l)?"define":"undef"; }
elsif (/^#((define)|(undef))\s+SIXTY_FOUR_BIT/)
{ printf OUT "#%s SIXTY_FOUR_BIT\n",($b64)?"define":"undef"; }
elsif (/^#((define)|(undef))\s+THIRTY_TWO_BIT/)
{ printf OUT "#%s THIRTY_TWO_BIT\n",($b32)?"define":"undef"; }
elsif (/^#((define)|(undef))\s+SIXTEEN_BIT/)
{ printf OUT "#%s SIXTEEN_BIT\n",($b16)?"define":"undef"; }
elsif (/^#((define)|(undef))\s+EIGHT_BIT/)
{ printf OUT "#%s EIGHT_BIT\n",($b8)?"define":"undef"; }
elsif (/^#((define)|(undef))\s+BN_LLONG\s*$/)
{ printf OUT "#%s BN_LLONG\n",($bn_ll)?"define":"undef"; }
elsif (/^\#define\s+DES_LONG\s+.*/)
{ printf OUT "#define DES_LONG unsigned %s\n",
($des_int)?'int':'long'; }
elsif (/^\#(define|undef)\s+DES_PTR/)
{ printf OUT "#%s DES_PTR\n",($des_ptr)?'define':'undef'; }
elsif (/^\#(define|undef)\s+DES_RISC1/)
{ printf OUT "#%s DES_RISC1\n",($des_risc1)?'define':'undef'; }
elsif (/^\#(define|undef)\s+DES_RISC2/)
{ printf OUT "#%s DES_RISC2\n",($des_risc2)?'define':'undef'; }
elsif (/^\#(define|undef)\s+DES_UNROLL/)
{ printf OUT "#%s DES_UNROLL\n",($des_unroll)?'define':'undef'; }
elsif (/^#define\s+RC4_INT\s/)
{ printf OUT "#define RC4_INT unsigned %s\n",$type[$rc4_int]; }
elsif (/^#undef\s+RC4_CHUNK/)
{
printf OUT "#undef RC4_CHUNK\n" if $rc4_chunk==0;
printf OUT "#define RC4_CHUNK unsigned long\n" if $rc4_chunk==1;
printf OUT "#define RC4_CHUNK unsigned long long\n" if $rc4_chunk==2;
}
elsif (/^#((define)|(undef))\s+RC4_INDEX/)
{ printf OUT "#%s RC4_INDEX\n",($rc4_idx)?"define":"undef"; }
elsif (/^#(define|undef)\s+I386_ONLY/)
{ printf OUT "#%s I386_ONLY\n", ($processor eq "386")?
"define":"undef"; }
elsif (/^#define\s+MD2_INT\s/)
{ printf OUT "#define MD2_INT unsigned %s\n",$type[$md2_int]; }
elsif (/^#define\s+IDEA_INT\s/)
{printf OUT "#define IDEA_INT unsigned %s\n",$type[$idea_int];}
elsif (/^#define\s+RC2_INT\s/)
{printf OUT "#define RC2_INT unsigned %s\n",$type[$rc2_int];}
elsif (/^#(define|undef)\s+BF_PTR/)
{
printf OUT "#undef BF_PTR\n" if $bf_ptr == 0;
printf OUT "#define BF_PTR\n" if $bf_ptr == 1;
printf OUT "#define BF_PTR2\n" if $bf_ptr == 2;
}
else
{ print OUT $_; }
}
close(IN);
print OUT "#ifdef __cplusplus\n";
print OUT "}\n";
print OUT "#endif\n";
close(OUT);
if (compare("crypto/opensslconf.h.new","crypto/opensslconf.h"))
{
rename("crypto/opensslconf.h","crypto/opensslconf.h.bak") || die "unable to rename crypto/opensslconf.h\n" if -e "crypto/opensslconf.h";
rename("crypto/opensslconf.h.new","crypto/opensslconf.h") || die "unable to rename crypto/opensslconf.h.new\n";
}
else
{ unlink("crypto/opensslconf.h.new"); }
# Fix the date
print "SIXTY_FOUR_BIT_LONG mode\n" if $b64l;
print "SIXTY_FOUR_BIT mode\n" if $b64;
print "THIRTY_TWO_BIT mode\n" if $b32;
print "SIXTEEN_BIT mode\n" if $b16;
print "EIGHT_BIT mode\n" if $b8;
print "DES_PTR used\n" if $des_ptr;
print "DES_RISC1 used\n" if $des_risc1;
print "DES_RISC2 used\n" if $des_risc2;
print "DES_UNROLL used\n" if $des_unroll;
print "DES_INT used\n" if $des_int;
print "BN_LLONG mode\n" if $bn_ll;
print "RC4 uses u$type[$rc4_int]\n" if $rc4_int != $def_int;
print "RC4_INDEX mode\n" if $rc4_idx;
print "RC4_CHUNK is undefined\n" if $rc4_chunk==0;
print "RC4_CHUNK is unsigned long\n" if $rc4_chunk==1;
print "RC4_CHUNK is unsigned long long\n" if $rc4_chunk==2;
print "MD2 uses u$type[$md2_int]\n" if $md2_int != $def_int;
print "IDEA uses u$type[$idea_int]\n" if $idea_int != $def_int;
print "RC2 uses u$type[$rc2_int]\n" if $rc2_int != $def_int;
print "BF_PTR used\n" if $bf_ptr == 1;
print "BF_PTR2 used\n" if $bf_ptr == 2;
if($IsMK1MF) {
open (OUT,">crypto/buildinf.h") || die "Can't open buildinf.h";
printf OUT <<EOF;
#ifndef MK1MF_BUILD
/* auto-generated by Configure for crypto/cversion.c:
* for Unix builds, crypto/Makefile.ssl generates functional definitions;
* Windows builds (and other mk1mf builds) compile cversion.c with
* -DMK1MF_BUILD and use definitions added to this file by util/mk1mf.pl. */
#error "Windows builds (PLATFORM=$target) use mk1mf.pl-created Makefiles"
#endif
EOF
close(OUT);
} else {
my $make_command = "$make PERL=\'$perl\'";
my @make_targets = ();
push @make_targets, "links" if $symlink;
push @make_targets, "depend" if $depflags ne $default_depflags && $make_depend;
push @make_targets, "gentests" if $symlink;
foreach my $make_target (@make_targets) {
(system "$make_command $make_target") == 0 or exit $?;
}
if ( $perl =~ m@^/@) {
&dofile("tools/c_rehash",$perl,'^#!/', '#!%s','^my \$dir;$', 'my $dir = "' . $openssldir . '";', '^my \$prefix;$', 'my $prefix = "' . $prefix . '";');
&dofile("apps/CA.pl",$perl,'^#!/', '#!%s');
} else {
# No path for Perl known ...
&dofile("tools/c_rehash",'/usr/local/bin/perl','^#!/', '#!%s','^my \$dir;$', 'my $dir = "' . $openssldir . '";', '^my \$prefix;$', 'my $prefix = "' . $prefix . '";');
&dofile("apps/CA.pl",'/usr/local/bin/perl','^#!/', '#!%s');
}
if ($depflags ne $default_depflags && !$make_depend) {
$warn_make_depend++;
}
}
# create the ms/version32.rc file if needed
if ($IsMK1MF && ($target !~ /^netware/)) {
my ($v1, $v2, $v3, $v4);
if ($version_num =~ /(^[0-9a-f]{1})([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})/i) {
$v1=hex $1;
$v2=hex $2;
$v3=hex $3;
$v4=hex $4;
}
open (OUT,">ms/version32.rc") || die "Can't open ms/version32.rc";
print OUT <<EOF;
#include <winver.h>
LANGUAGE 0x09,0x01
1 VERSIONINFO
FILEVERSION $v1,$v2,$v3,$v4
PRODUCTVERSION $v1,$v2,$v3,$v4
FILEFLAGSMASK 0x3fL
#ifdef _DEBUG
FILEFLAGS 0x01L
#else
FILEFLAGS 0x00L
#endif
FILEOS VOS__WINDOWS32
FILETYPE VFT_DLL
FILESUBTYPE 0x0L
BEGIN
BLOCK "StringFileInfo"
BEGIN
BLOCK "040904b0"
BEGIN
// Required:
VALUE "CompanyName", "The OpenSSL Project, http://www.openssl.org/\\0"
VALUE "FileDescription", "OpenSSL Shared Library\\0"
VALUE "FileVersion", "$version\\0"
#if defined(CRYPTO)
VALUE "InternalName", "libeay32\\0"
VALUE "OriginalFilename", "libeay32.dll\\0"
#elif defined(SSL)
VALUE "InternalName", "ssleay32\\0"
VALUE "OriginalFilename", "ssleay32.dll\\0"
#endif
VALUE "ProductName", "The OpenSSL Toolkit\\0"
VALUE "ProductVersion", "$version\\0"
// Optional:
//VALUE "Comments", "\\0"
VALUE "LegalCopyright", "Copyright © 1998-2005 The OpenSSL Project. Copyright © 1995-1998 Eric A. Young, Tim J. Hudson. All rights reserved.\\0"
//VALUE "LegalTrademarks", "\\0"
//VALUE "PrivateBuild", "\\0"
//VALUE "SpecialBuild", "\\0"
END
END
BLOCK "VarFileInfo"
BEGIN
VALUE "Translation", 0x409, 0x4b0
END
END
EOF
close(OUT);
}
print <<EOF;
Configured for $target.
EOF
print <<\EOF if (!$no_threads && !$threads);
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 for details if you need multi-threading.
EOF
print <<\EOF if ($no_shared_warn);
You gave the option 'shared', which is not supported on this platform, so
we will pretend you gave the option 'no-shared'. If you know how to implement
shared libraries, please let us know (but please first make sure you have
tried with a current version of OpenSSL).
EOF
print <<EOF if ($warn_make_depend);
*** Because of configuration changes, you MUST do the following before
*** building:
make depend
EOF
exit(0);
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 $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 $i !~ /^debug/;
$k += length($i) + 1;
if ($k > 78)
{
print STDERR "\n";
$k=length($i);
}
print STDERR $i . " ";
}
print STDERR "\n\nNOTE: If in doubt, on Unix-ish systems use './config'.\n";
exit(1);
}
sub which
{
my($name)=@_;
my $path;
foreach $path (split /:/, $ENV{PATH})
{
if (-f "$path/$name$exe_ext" and -x _)
{
return "$path/$name$exe_ext" unless ($name eq "perl" and
system("$path/$name$exe_ext -e " . '\'exit($]<5.0);\''));
}
}
}
sub dofile
{
my $f; my $p; my %m; my @a; my $k; my $ff;
($f,$p,%m)=@_;
open(IN,"<$f.in") || open(IN,"<$f") || die "unable to open $f:$!\n";
@a=<IN>;
close(IN);
foreach $k (keys %m)
{
grep(/$k/ && ($_=sprintf($m{$k}."\n",$p)),@a);
}
open(OUT,">$f.new") || die "unable to open $f.new:$!\n";
print OUT @a;
close(OUT);
rename($f,"$f.bak") || die "unable to rename $f\n" if -e $f;
rename("$f.new",$f) || die "unable to rename $f.new\n";
}
sub print_table_entry
{
my $target = shift;
my ($cc, $cflags, $unistd, $thread_cflag, $sys_id, $lflags,
$bn_ops, $cpuid_obj, $bn_obj, $ec_obj, $des_obj, $aes_obj, $bf_obj,
$md5_obj, $sha1_obj, $cast_obj, $rc4_obj, $rmd160_obj,
$rc5_obj, $wp_obj, $cmll_obj, $modes_obj, $engines_obj,
$perlasm_scheme, $dso_scheme, $shared_target, $shared_cflag,
$shared_ldflag, $shared_extension, $ranlib, $arflags, $multilib)=
split(/\s*:\s*/,$table{$target} . ":" x 30 , -1);
print <<EOF
*** $target
\$cc = $cc
\$cflags = $cflags
\$unistd = $unistd
\$thread_cflag = $thread_cflag
\$sys_id = $sys_id
\$lflags = $lflags
\$bn_ops = $bn_ops
\$cpuid_obj = $cpuid_obj
\$bn_obj = $bn_obj
\$ec_obj = $ec_obj
\$des_obj = $des_obj
\$aes_obj = $aes_obj
\$bf_obj = $bf_obj
\$md5_obj = $md5_obj
\$sha1_obj = $sha1_obj
\$cast_obj = $cast_obj
\$rc4_obj = $rc4_obj
\$rmd160_obj = $rmd160_obj
\$rc5_obj = $rc5_obj
\$wp_obj = $wp_obj
\$cmll_obj = $cmll_obj
\$modes_obj = $modes_obj
\$engines_obj = $engines_obj
\$perlasm_scheme = $perlasm_scheme
\$dso_scheme = $dso_scheme
\$shared_target= $shared_target
\$shared_cflag = $shared_cflag
\$shared_ldflag = $shared_ldflag
\$shared_extension = $shared_extension
\$ranlib = $ranlib
\$arflags = $arflags
\$multilib = $multilib
EOF
}
sub test_sanity
{
my $errorcnt = 0;
print STDERR "=" x 70, "\n";
print STDERR "=== SANITY TESTING!\n";
print STDERR "=== No configuration will be done, all other arguments will be ignored!\n";
print STDERR "=" x 70, "\n";
foreach $target (sort keys %table)
{
@fields = split(/\s*:\s*/,$table{$target} . ":" x 30 , -1);
if ($fields[$idx_dso_scheme-1] =~ /^(beos|dl|dlfcn|win32|vms)$/)
{
$errorcnt++;
print STDERR "SANITY ERROR: '$target' has the dso_scheme [$idx_dso_scheme] values\n";
print STDERR " in the previous field\n";
}
elsif ($fields[$idx_dso_scheme+1] =~ /^(beos|dl|dlfcn|win32|vms)$/)
{
$errorcnt++;
print STDERR "SANITY ERROR: '$target' has the dso_scheme [$idx_dso_scheme] values\n";
print STDERR " in the following field\n";
}
elsif ($fields[$idx_dso_scheme] !~ /^(beos|dl|dlfcn|win32|vms|)$/)
{
$errorcnt++;
print STDERR "SANITY ERROR: '$target' has the dso_scheme [$idx_dso_scheme] field = ",$fields[$idx_dso_scheme],"\n";
print STDERR " valid values are 'beos', 'dl', 'dlfcn', 'win32' and 'vms'\n";
}
}
print STDERR "No sanity errors detected!\n" if $errorcnt == 0;
return $errorcnt;
}
sub file_newer
{
my ($file1, $file2) = @_;
return (stat($file1))[9] > (stat($file2))[9]
}
diff --git a/FREEBSD-upgrade b/FREEBSD-upgrade
index a9cd999dae3e..fb8fda8e0479 100644
--- a/FREEBSD-upgrade
+++ b/FREEBSD-upgrade
@@ -1,83 +1,83 @@
This contains various notes used to import a new OpenSSL version into
the FreeBSD base system. It is not expected to be complete but just to
contain some hints for imports. Note that this doesn't actually deal
with getting OpenSSL to compile...
XXX This file currently partly contain CVS and SVN instructions.
First, read http://wiki.freebsd.org/SubversionPrimer/VendorImports
# Xlist
setenv XLIST /FreeBSD/work/openssl/svn-FREEBSD-files/FREEBSD-Xlist
setenv FSVN "svn+ssh://repo.freebsd.org/base"
-setenv OSSLVER 1.0.2n
-# OSSLTAG format: v1_0_2n
+setenv OSSLVER 1.0.2o
+# OSSLTAG format: v1_0_2o
###setenv OSSLTAG v`echo ${OSSLVER} | tr . _`
cd /FreeBSD/work/openssl/merge
fetch http://www.openssl.org/source/openssl-${OSSLVER}.tar.gz \
http://www.openssl.org/source/openssl-${OSSLVER}.tar.gz.asc
gpg --verify openssl-${OSSLVER}.tar.gz.asc openssl-${OSSLVER}.tar.gz
svn co $FSVN/vendor-crypto/openssl/dist dist
tar -x -X $XLIST -f openssl-${OSSLVER}.tar.gz
cd dist
svn list -R | egrep -v -e '/$' -e '^FREEBSD-(Xlist|upgrade)$' | sort >../old
cd ../openssl-${OSSLVER}
find . -type f -or -type l | cut -c 3- | sort >../new
cd ..
# See that files to remove makes sense
comm -23 old new
# See that files to add makes sense
comm -13 old new
tar -cf - -C openssl-${OSSLVER} . | tar -xf - -C dist
cd dist
comm -23 ../old ../new | xargs svn rm
# Make sure to remove empty directories
comm -13 ../old ../new | xargs svn --parents add
svn stat
svn ci
svn cp ^/vendor-crypto/openssl/dist ^/vendor-crypto/openssl/$OSSLVER
# Merge to head
mkdir ../head
cd ../head
svn co $FSVN/head/crypto/openssl crypto/openssl
svn merge ^/vendor-crypto/openssl/dist crypto/openssl
# Resolve conflicts manually
svn co $FSVN/head/secure/lib/libcrypto secure/lib/libcrypto
svn co $FSVN/head/secure/lib/libssl secure/lib/libssl
svn co $FSVN/head/secure/usr.bin/openssl secure/usr.bin/openssl
cd secure/lib/libcrypto
# Update version number and release date in Makefile.inc
# Update all opensslconf-${MACHINE_CPUARCH}.h
# Regen assembly files if necessary
make -f Makefile.asm all
mv *.[Ss] ${MACHINE_CPUARCH}
make -f Makefile.asm clean
# Regen manual pages
make man-makefile-update && make man-update
cd ../libssl
make man-makefile-update && make man-update
cd ../../usr.bin/openssl
make man-makefile-update && make man-update
cd ../../..
# Commit!
svn ci crypto/openssl secure/lib/libcrypto secure/lib/libssl secure/usr.bin/openssl
-- simon@, jkim@
$FreeBSD$
diff --git a/LICENSE b/LICENSE
index bdfd985a691b..b1fa6f9fdb4d 100644
--- a/LICENSE
+++ b/LICENSE
@@ -1,127 +1,127 @@
LICENSE ISSUES
==============
The OpenSSL toolkit stays under a double license, i.e. both the conditions of
the OpenSSL License and the original SSLeay license apply to the toolkit.
See below for the actual license texts. Actually both licenses are BSD-style
Open Source licenses. In case of any license issues related to OpenSSL
please contact openssl-core@openssl.org.
OpenSSL License
---------------
/* ====================================================================
- * Copyright (c) 1998-2017 The OpenSSL Project. All rights reserved.
+ * Copyright (c) 1998-2018 The OpenSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* openssl-core@openssl.org.
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.openssl.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*
* This product includes cryptographic software written by Eric Young
* (eay@cryptsoft.com). This product includes software written by Tim
* Hudson (tjh@cryptsoft.com).
*
*/
Original SSLeay License
-----------------------
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
diff --git a/Makefile b/Makefile
index 9212c2885278..d28f6fac188f 100644
--- a/Makefile
+++ b/Makefile
@@ -1,692 +1,692 @@
### Generated automatically from Makefile.org by Configure.
##
## Makefile for OpenSSL
##
-VERSION=1.0.2n
+VERSION=1.0.2o
MAJOR=1
MINOR=0.2
SHLIB_VERSION_NUMBER=1.0.0
SHLIB_VERSION_HISTORY=
SHLIB_MAJOR=1
SHLIB_MINOR=0.0
SHLIB_EXT=
PLATFORM=dist
OPTIONS= no-ec_nistp_64_gcc_128 no-gmp no-jpake no-krb5 no-libunbound no-md2 no-rc5 no-rfc3779 no-sctp no-shared no-ssl-trace no-ssl2 no-store no-unit-test no-weak-ssl-ciphers no-zlib no-zlib-dynamic static-engine
CONFIGURE_ARGS=dist
SHLIB_TARGET=
# HERE indicates where this Makefile lives. This can be used to indicate
# where sub-Makefiles are expected to be. Currently has very limited usage,
# and should probably not be bothered with at all.
HERE=.
# INSTALL_PREFIX is for package builders so that they can configure
# for, say, /usr/ and yet have everything installed to /tmp/somedir/usr/.
# Normally it is left empty.
INSTALL_PREFIX=
INSTALLTOP=/usr/local/ssl
# Do not edit this manually. Use Configure --openssldir=DIR do change this!
OPENSSLDIR=/usr/local/ssl
# NO_IDEA - Define to build without the IDEA algorithm
# NO_RC4 - Define to build without the RC4 algorithm
# NO_RC2 - Define to build without the RC2 algorithm
# THREADS - Define when building with threads, you will probably also need any
# system defines as well, i.e. _REENTERANT for Solaris 2.[34]
# TERMIO - Define the termio terminal subsystem, needed if sgtty is missing.
# TERMIOS - Define the termios terminal subsystem, Silicon Graphics.
# LONGCRYPT - Define to use HPUX 10.x's long password modification to crypt(3).
# DEVRANDOM - Give this the value of the 'random device' if your OS supports
# one. 32 bytes will be read from this when the random
# number generator is initalised.
# SSL_FORBID_ENULL - define if you want the server to be not able to use the
# NULL encryption ciphers.
#
# LOCK_DEBUG - turns on lots of lock debug output :-)
# REF_CHECK - turn on some xyz_free() assertions.
# REF_PRINT - prints some stuff on structure free.
# CRYPTO_MDEBUG - turns on my 'memory leak' detecting stuff
# MFUNC - Make all Malloc/Free/Realloc calls call
# CRYPTO_malloc/CRYPTO_free/CRYPTO_realloc which can be setup to
# call application defined callbacks via CRYPTO_set_mem_functions()
# MD5_ASM needs to be defined to use the x86 assembler for MD5
# SHA1_ASM needs to be defined to use the x86 assembler for SHA1
# RMD160_ASM needs to be defined to use the x86 assembler for RIPEMD160
# Do not define B_ENDIAN or L_ENDIAN if 'unsigned long' == 8. It must
# equal 4.
# PKCS1_CHECK - pkcs1 tests.
CC= cc
CFLAG= -O
DEPFLAG= -DOPENSSL_NO_EC_NISTP_64_GCC_128 -DOPENSSL_NO_GMP -DOPENSSL_NO_JPAKE -DOPENSSL_NO_LIBUNBOUND -DOPENSSL_NO_MD2 -DOPENSSL_NO_RC5 -DOPENSSL_NO_RFC3779 -DOPENSSL_NO_SCTP -DOPENSSL_NO_SSL_TRACE -DOPENSSL_NO_SSL2 -DOPENSSL_NO_STORE -DOPENSSL_NO_UNIT_TEST -DOPENSSL_NO_WEAK_SSL_CIPHERS
PEX_LIBS=
EX_LIBS=
EXE_EXT=
ARFLAGS=
AR= ar $(ARFLAGS) r
RANLIB= /usr/bin/ranlib
RC= windres
NM= nm
PERL= /usr/bin/perl
TAR= tar
TARFLAGS= --no-recursion
-MAKEDEPPROG=makedepend
+MAKEDEPPROG= cc
LIBDIR=lib
# We let the C compiler driver to take care of .s files. This is done in
# order to be excused from maintaining a separate set of architecture
# dependent assembler flags. E.g. if you throw -mcpu=ultrasparc at SPARC
# gcc, then the driver will automatically translate it to -xarch=v8plus
# and pass it down to assembler.
AS=$(CC) -c
ASFLAG=$(CFLAG)
# For x86 assembler: Set PROCESSOR to 386 if you want to support
# the 80386.
PROCESSOR=
# CPUID module collects small commonly used assembler snippets
CPUID_OBJ= mem_clr.o
BN_ASM= bn_asm.o
EC_ASM=
DES_ENC= des_enc.o fcrypt_b.o
AES_ENC= aes_core.o aes_cbc.o
BF_ENC= bf_enc.o
CAST_ENC= c_enc.o
RC4_ENC= rc4_enc.o rc4_skey.o
RC5_ENC= rc5_enc.o
MD5_ASM_OBJ=
SHA1_ASM_OBJ=
RMD160_ASM_OBJ=
WP_ASM_OBJ= wp_block.o
CMLL_ENC= camellia.o cmll_misc.o cmll_cbc.o
MODES_ASM_OBJ=
ENGINES_ASM_OBJ=
PERLASM_SCHEME=
# KRB5 stuff
KRB5_INCLUDES=
LIBKRB5=
# Zlib stuff
ZLIB_INCLUDE=
LIBZLIB=
# TOP level FIPS install directory.
FIPSDIR=/usr/local/ssl/fips-2.0
# This is the location of fipscanister.o and friends.
# The FIPS module build will place it $(INSTALLTOP)/lib
# but since $(INSTALLTOP) can only take the default value
# when the module is built it will be in /usr/local/ssl/lib
# $(INSTALLTOP) for this build may be different so hard
# code the path.
FIPSLIBDIR=
# The location of the library which contains fipscanister.o
# normally it will be libcrypto unless fipsdso is set in which
# case it will be libfips. If not compiling in FIPS mode at all
# this is empty making it a useful test for a FIPS compile.
FIPSCANLIB=
# Shared library base address. Currently only used on Windows.
#
BASEADDR=0xFB00000
DIRS= crypto ssl engines apps test tools
ENGDIRS= ccgost
SHLIBDIRS= crypto ssl
# dirs in crypto to build
SDIRS= \
objects \
md4 md5 sha mdc2 hmac ripemd whrlpool \
des aes rc2 rc4 idea bf cast camellia seed modes \
bn ec rsa dsa ecdsa dh ecdh dso engine \
buffer bio stack lhash rand err \
evp asn1 pem x509 x509v3 conf txt_db pkcs7 pkcs12 comp ocsp ui krb5 \
cms pqueue ts srp cmac
# keep in mind that the above list is adjusted by ./Configure
# according to no-xxx arguments...
# tests to perform. "alltests" is a special word indicating that all tests
# should be performed.
TESTS = alltests
MAKEFILE= Makefile
MANDIR=$(OPENSSLDIR)/man
MAN1=1
MAN3=3
MANSUFFIX=
HTMLSUFFIX=html
HTMLDIR=$(OPENSSLDIR)/html
SHELL=/bin/sh
TOP= .
ONEDIRS=out tmp
EDIRS= times doc bugs util include certs ms shlib mt demos perl sf dep VMS
WDIRS= windows
LIBS= libcrypto.a libssl.a
SHARED_CRYPTO=libcrypto$(SHLIB_EXT)
SHARED_SSL=libssl$(SHLIB_EXT)
SHARED_LIBS=
SHARED_LIBS_LINK_EXTS=
SHARED_LDFLAGS=
GENERAL= Makefile
BASENAME= openssl
NAME= $(BASENAME)-$(VERSION)
TARFILE= ../$(NAME).tar
EXHEADER= e_os2.h
HEADER= e_os.h
all: Makefile build_all
# as we stick to -e, CLEARENV ensures that local variables in lower
# Makefiles remain local and variable. $${VAR+VAR} is tribute to Korn
# shell, which [annoyingly enough] terminates unset with error if VAR
# is not present:-( TOP= && unset TOP is tribute to HP-UX /bin/sh,
# which terminates unset with error if no variable was present:-(
CLEARENV= TOP= && unset TOP $${LIB+LIB} $${LIBS+LIBS} \
$${INCLUDE+INCLUDE} $${INCLUDES+INCLUDES} \
$${DIR+DIR} $${DIRS+DIRS} $${SRC+SRC} \
$${LIBSRC+LIBSRC} $${LIBOBJ+LIBOBJ} $${ALL+ALL} \
$${EXHEADER+EXHEADER} $${HEADER+HEADER} \
$${GENERAL+GENERAL} $${CFLAGS+CFLAGS} \
$${ASFLAGS+ASFLAGS} $${AFLAGS+AFLAGS} \
$${LDCMD+LDCMD} $${LDFLAGS+LDFLAGS} $${SCRIPTS+SCRIPTS} \
$${SHAREDCMD+SHAREDCMD} $${SHAREDFLAGS+SHAREDFLAGS} \
$${SHARED_LIB+SHARED_LIB} $${LIBEXTRAS+LIBEXTRAS} \
$${APPS+APPS}
# LC_ALL=C ensures that error [and other] messages are delivered in
# same language for uniform treatment.
BUILDENV= LC_ALL=C PLATFORM='$(PLATFORM)' PROCESSOR='$(PROCESSOR)'\
CC='$(CC)' CFLAG='$(CFLAG)' \
AS='$(CC)' ASFLAG='$(CFLAG) -c' \
AR='$(AR)' NM='$(NM)' RANLIB='$(RANLIB)' \
RC='$(RC)' \
CROSS_COMPILE='$(CROSS_COMPILE)' \
PERL='$(PERL)' ENGDIRS='$(ENGDIRS)' \
SDIRS='$(SDIRS)' LIBRPATH='$(INSTALLTOP)/$(LIBDIR)' \
INSTALL_PREFIX='$(INSTALL_PREFIX)' \
INSTALLTOP='$(INSTALLTOP)' OPENSSLDIR='$(OPENSSLDIR)' \
LIBDIR='$(LIBDIR)' \
MAKEDEPEND='$$$${TOP}/util/domd $$$${TOP} -MD $(MAKEDEPPROG)' \
DEPFLAG='-DOPENSSL_NO_DEPRECATED $(DEPFLAG)' \
MAKEDEPPROG='$(MAKEDEPPROG)' \
SHARED_LDFLAGS='$(SHARED_LDFLAGS)' \
KRB5_INCLUDES='$(KRB5_INCLUDES)' LIBKRB5='$(LIBKRB5)' \
ZLIB_INCLUDE='$(ZLIB_INCLUDE)' LIBZLIB='$(LIBZLIB)' \
EXE_EXT='$(EXE_EXT)' SHARED_LIBS='$(SHARED_LIBS)' \
SHLIB_EXT='$(SHLIB_EXT)' SHLIB_TARGET='$(SHLIB_TARGET)' \
PEX_LIBS='$(PEX_LIBS)' EX_LIBS='$(EX_LIBS)' \
CPUID_OBJ='$(CPUID_OBJ)' BN_ASM='$(BN_ASM)' \
EC_ASM='$(EC_ASM)' DES_ENC='$(DES_ENC)' \
AES_ENC='$(AES_ENC)' CMLL_ENC='$(CMLL_ENC)' \
BF_ENC='$(BF_ENC)' CAST_ENC='$(CAST_ENC)' \
RC4_ENC='$(RC4_ENC)' RC5_ENC='$(RC5_ENC)' \
SHA1_ASM_OBJ='$(SHA1_ASM_OBJ)' \
MD5_ASM_OBJ='$(MD5_ASM_OBJ)' \
RMD160_ASM_OBJ='$(RMD160_ASM_OBJ)' \
WP_ASM_OBJ='$(WP_ASM_OBJ)' \
MODES_ASM_OBJ='$(MODES_ASM_OBJ)' \
ENGINES_ASM_OBJ='$(ENGINES_ASM_OBJ)' \
PERLASM_SCHEME='$(PERLASM_SCHEME)' \
FIPSLIBDIR='${FIPSLIBDIR}' \
FIPSDIR='${FIPSDIR}' \
FIPSCANLIB="$${FIPSCANLIB:-$(FIPSCANLIB)}" \
THIS=$${THIS:-$@} MAKEFILE=Makefile MAKEOVERRIDES=
# MAKEOVERRIDES= effectively "equalizes" GNU-ish and SysV-ish make flavors,
# which in turn eliminates ambiguities in variable treatment with -e.
# BUILD_CMD is a generic macro to build a given target in a given
# subdirectory. The target must be given through the shell variable
# `target' and the subdirectory to build in must be given through `dir'.
# This macro shouldn't be used directly, use RECURSIVE_BUILD_CMD or
# BUILD_ONE_CMD instead.
#
# BUILD_ONE_CMD is a macro to build a given target in a given
# subdirectory if that subdirectory is part of $(DIRS). It requires
# exactly the same shell variables as BUILD_CMD.
#
# RECURSIVE_BUILD_CMD is a macro to build a given target in all
# subdirectories defined in $(DIRS). It requires that the target
# is given through the shell variable `target'.
BUILD_CMD= if [ -d "$$dir" ]; then \
( cd $$dir && echo "making $$target in $$dir..." && \
$(CLEARENV) && $(MAKE) -e $(BUILDENV) TOP=.. DIR=$$dir $$target \
) || exit 1; \
fi
RECURSIVE_BUILD_CMD=for dir in $(DIRS); do $(BUILD_CMD); done
BUILD_ONE_CMD=\
if expr " $(DIRS) " : ".* $$dir " >/dev/null 2>&1; then \
$(BUILD_CMD); \
fi
reflect:
@[ -n "$(THIS)" ] && $(CLEARENV) && $(MAKE) $(THIS) -e $(BUILDENV)
sub_all: build_all
build_all: build_libs build_apps build_tests build_tools
build_libs: build_libcrypto build_libssl openssl.pc
build_libcrypto: build_crypto build_engines libcrypto.pc
build_libssl: build_ssl libssl.pc
build_crypto:
@dir=crypto; target=all; $(BUILD_ONE_CMD)
build_ssl: build_crypto
@dir=ssl; target=all; $(BUILD_ONE_CMD)
build_engines: build_crypto
@dir=engines; target=all; $(BUILD_ONE_CMD)
build_apps: build_libs
@dir=apps; target=all; $(BUILD_ONE_CMD)
build_tests: build_libs
@dir=test; target=all; $(BUILD_ONE_CMD)
build_tools: build_libs
@dir=tools; target=all; $(BUILD_ONE_CMD)
all_testapps: build_libs build_testapps
build_testapps:
@dir=crypto; target=testapps; $(BUILD_ONE_CMD)
fips_premain_dso$(EXE_EXT): libcrypto.a
[ -z "$(FIPSCANLIB)" ] || $(CC) $(CFLAG) -Iinclude \
-DFINGERPRINT_PREMAIN_DSO_LOAD -o $@ \
$(FIPSLIBDIR)fips_premain.c $(FIPSLIBDIR)fipscanister.o \
libcrypto.a $(EX_LIBS)
libcrypto$(SHLIB_EXT): libcrypto.a fips_premain_dso$(EXE_EXT)
@if [ "$(SHLIB_TARGET)" != "" ]; then \
if [ "$(FIPSCANLIB)" = "libcrypto" ]; then \
FIPSLD_LIBCRYPTO=libcrypto.a ; \
FIPSLD_CC="$(CC)"; CC=$(FIPSDIR)/bin/fipsld; \
export CC FIPSLD_CC FIPSLD_LIBCRYPTO; \
fi; \
$(MAKE) -e SHLIBDIRS=crypto CC="$${CC:-$(CC)}" build-shared && \
(touch -c fips_premain_dso$(EXE_EXT) || :); \
else \
echo "There's no support for shared libraries on this platform" >&2; \
exit 1; \
fi
libssl$(SHLIB_EXT): libcrypto$(SHLIB_EXT) libssl.a
@if [ "$(SHLIB_TARGET)" != "" ]; then \
$(MAKE) SHLIBDIRS=ssl SHLIBDEPS='-lcrypto' build-shared; \
else \
echo "There's no support for shared libraries on this platform" >&2; \
exit 1; \
fi
clean-shared:
@set -e; for i in $(SHLIBDIRS); do \
if [ -n "$(SHARED_LIBS_LINK_EXTS)" ]; then \
tmp="$(SHARED_LIBS_LINK_EXTS)"; \
for j in $${tmp:-x}; do \
( set -x; rm -f lib$$i$$j ); \
done; \
fi; \
( set -x; rm -f lib$$i$(SHLIB_EXT) ); \
if expr "$(PLATFORM)" : "Cygwin" >/dev/null; then \
( set -x; rm -f cyg$$i$(SHLIB_EXT) lib$$i$(SHLIB_EXT).a ); \
fi; \
done
link-shared:
@ set -e; for i in $(SHLIBDIRS); do \
$(MAKE) -f $(HERE)/Makefile.shared -e $(BUILDENV) \
LIBNAME=$$i LIBVERSION=$(SHLIB_MAJOR).$(SHLIB_MINOR) \
LIBCOMPATVERSIONS=";$(SHLIB_VERSION_HISTORY)" \
symlink.$(SHLIB_TARGET); \
libs="$$libs -l$$i"; \
done
build-shared: do_$(SHLIB_TARGET) link-shared
do_$(SHLIB_TARGET):
@ set -e; libs='-L. $(SHLIBDEPS)'; for i in $(SHLIBDIRS); do \
if [ "$$i" = "ssl" -a -n "$(LIBKRB5)" ]; then \
libs="$(LIBKRB5) $$libs"; \
fi; \
$(CLEARENV) && $(MAKE) -f Makefile.shared -e $(BUILDENV) \
LIBNAME=$$i LIBVERSION=$(SHLIB_MAJOR).$(SHLIB_MINOR) \
LIBCOMPATVERSIONS=";$(SHLIB_VERSION_HISTORY)" \
LIBDEPS="$$libs $(EX_LIBS)" \
link_a.$(SHLIB_TARGET); \
libs="-l$$i $$libs"; \
done
libcrypto.pc: Makefile
@ ( echo 'prefix=$(INSTALLTOP)'; \
echo 'exec_prefix=$${prefix}'; \
echo 'libdir=$${exec_prefix}/$(LIBDIR)'; \
echo 'includedir=$${prefix}/include'; \
echo 'enginesdir=$${libdir}/engines'; \
echo ''; \
echo 'Name: OpenSSL-libcrypto'; \
echo 'Description: OpenSSL cryptography library'; \
echo 'Version: '$(VERSION); \
echo 'Requires: '; \
echo 'Libs: -L$${libdir} -lcrypto'; \
echo 'Libs.private: $(EX_LIBS)'; \
echo 'Cflags: -I$${includedir} $(KRB5_INCLUDES)' ) > libcrypto.pc
libssl.pc: Makefile
@ ( echo 'prefix=$(INSTALLTOP)'; \
echo 'exec_prefix=$${prefix}'; \
echo 'libdir=$${exec_prefix}/$(LIBDIR)'; \
echo 'includedir=$${prefix}/include'; \
echo ''; \
echo 'Name: OpenSSL-libssl'; \
echo 'Description: Secure Sockets Layer and cryptography libraries'; \
echo 'Version: '$(VERSION); \
echo 'Requires.private: libcrypto'; \
echo 'Libs: -L$${libdir} -lssl'; \
echo 'Libs.private: $(EX_LIBS)'; \
echo 'Cflags: -I$${includedir} $(KRB5_INCLUDES)' ) > libssl.pc
openssl.pc: Makefile
@ ( echo 'prefix=$(INSTALLTOP)'; \
echo 'exec_prefix=$${prefix}'; \
echo 'libdir=$${exec_prefix}/$(LIBDIR)'; \
echo 'includedir=$${prefix}/include'; \
echo ''; \
echo 'Name: OpenSSL'; \
echo 'Description: Secure Sockets Layer and cryptography libraries and tools'; \
echo 'Version: '$(VERSION); \
echo 'Requires: libssl libcrypto' ) > openssl.pc
Makefile: Makefile.org Configure config
@echo "Makefile is older than Makefile.org, Configure or config."
@echo "Reconfigure the source tree (via './config' or 'perl Configure'), please."
@false
libclean:
rm -f *.map *.so *.so.* *.dylib *.dll engines/*.so engines/*.dll engines/*.dylib *.a engines/*.a */lib */*/lib
clean: libclean
rm -f shlib/*.o *.o core a.out fluff rehash.time testlog make.log cctest cctest.c
@set -e; target=clean; $(RECURSIVE_BUILD_CMD)
rm -f $(LIBS)
rm -f openssl.pc libssl.pc libcrypto.pc
rm -f speed.* .pure
rm -f $(TARFILE)
@set -e; for i in $(ONEDIRS) ;\
do \
rm -fr $$i/*; \
done
distclean: clean
-$(RM) `find . -name .git -prune -o -type l -print`
$(RM) apps/CA.pl
$(RM) test/evptests.txt test/newkey.pem test/testkey.pem test/testreq.pem
$(RM) tools/c_rehash
$(RM) crypto/opensslconf.h
$(RM) Makefile Makefile.bak
makefile.one: files
$(PERL) util/mk1mf.pl >makefile.one; \
sh util/do_ms.sh
files:
$(PERL) $(TOP)/util/files.pl Makefile > $(TOP)/MINFO
@set -e; target=files; $(RECURSIVE_BUILD_CMD)
links:
@$(PERL) $(TOP)/util/mkdir-p.pl include/openssl
@$(PERL) $(TOP)/util/mklink.pl include/openssl $(EXHEADER)
@set -e; target=links; $(RECURSIVE_BUILD_CMD)
gentests:
@(cd test && echo "generating dummy tests (if needed)..." && \
$(CLEARENV) && $(MAKE) -e $(BUILDENV) TESTS='$(TESTS)' OPENSSL_DEBUG_MEMORY=on generate );
dclean:
rm -rf *.bak include/openssl certs/.0
@set -e; target=dclean; $(RECURSIVE_BUILD_CMD)
rehash: rehash.time
rehash.time: certs apps
@if [ -z "$(CROSS_COMPILE)" ]; then \
(OPENSSL="`pwd`/util/opensslwrap.sh"; \
[ -x "apps/openssl.exe" ] && OPENSSL="apps/openssl.exe" || :; \
OPENSSL_DEBUG_MEMORY=on; \
export OPENSSL OPENSSL_DEBUG_MEMORY; \
$(PERL) tools/c_rehash certs/demo) && \
touch rehash.time; \
else :; fi
test: tests
tests: rehash
@(cd test && echo "testing..." && \
$(CLEARENV) && $(MAKE) -e $(BUILDENV) TOP=.. TESTS='$(TESTS)' OPENSSL_DEBUG_MEMORY=on OPENSSL_CONF=../apps/openssl.cnf tests );
OPENSSL_CONF=apps/openssl.cnf util/opensslwrap.sh version -a
report:
@$(PERL) util/selftest.pl
update: errors stacks util/libeay.num util/ssleay.num TABLE
@set -e; target=update; $(RECURSIVE_BUILD_CMD)
depend:
@set -e; target=depend; $(RECURSIVE_BUILD_CMD)
lint:
@set -e; target=lint; $(RECURSIVE_BUILD_CMD)
tags:
rm -f TAGS
find . -name '[^.]*.[ch]' | xargs etags -a
errors:
$(PERL) util/ck_errf.pl -strict */*.c */*/*.c
$(PERL) util/mkerr.pl -recurse -write
(cd engines; $(MAKE) PERL=$(PERL) errors)
stacks:
$(PERL) util/mkstack.pl -write
util/libeay.num::
$(PERL) util/mkdef.pl crypto update
util/ssleay.num::
$(PERL) util/mkdef.pl ssl update
TABLE: Configure
(echo 'Output of `Configure TABLE'"':"; \
$(PERL) Configure TABLE) > TABLE
# Build distribution tar-file. As the list of files returned by "find" is
# pretty long, on several platforms a "too many arguments" error or similar
# would occur. Therefore the list of files is temporarily stored into a file
# and read directly, requiring GNU-Tar. Call "make TAR=gtar dist" if the normal
# tar does not support the --files-from option.
TAR_COMMAND=$(TAR) $(TARFLAGS) --files-from $(TARFILE).list \
--owner 0 --group 0 \
--transform 's|^|$(NAME)/|' \
-cvf -
$(TARFILE).list:
find * \! -name STATUS \! -name TABLE \! -name '*.o' \! -name '*.a' \
\! -name '*.so' \! -name '*.so.*' \! -name 'openssl' \
\( \! -name '*test' -o -name bctest -o -name pod2mantest \) \
\! -name '.#*' \! -name '*~' \! -type l \
| sort > $(TARFILE).list
tar: $(TARFILE).list
find . -type d -print | xargs chmod 755
find . -type f -print | xargs chmod a+r
find . -type f -perm -0100 -print | xargs chmod a+x
$(TAR_COMMAND) | gzip --best > $(TARFILE).gz
rm -f $(TARFILE).list
ls -l $(TARFILE).gz
tar-snap: $(TARFILE).list
$(TAR_COMMAND) > $(TARFILE)
rm -f $(TARFILE).list
ls -l $(TARFILE)
dist:
$(PERL) Configure dist
@$(MAKE) SDIRS='$(SDIRS)' clean
@$(MAKE) TAR='$(TAR)' TARFLAGS='$(TARFLAGS)' $(DISTTARVARS) tar
install: all install_docs install_sw
install_sw:
@$(PERL) $(TOP)/util/mkdir-p.pl $(INSTALL_PREFIX)$(INSTALLTOP)/bin \
$(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR) \
$(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR)/engines \
$(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR)/pkgconfig \
$(INSTALL_PREFIX)$(INSTALLTOP)/include/openssl \
$(INSTALL_PREFIX)$(OPENSSLDIR)/misc \
$(INSTALL_PREFIX)$(OPENSSLDIR)/certs \
$(INSTALL_PREFIX)$(OPENSSLDIR)/private
@set -e; headerlist="$(EXHEADER)"; for i in $$headerlist;\
do \
(cp $$i $(INSTALL_PREFIX)$(INSTALLTOP)/include/openssl/$$i; \
chmod 644 $(INSTALL_PREFIX)$(INSTALLTOP)/include/openssl/$$i ); \
done;
@set -e; target=install; $(RECURSIVE_BUILD_CMD)
@set -e; liblist="$(LIBS)"; for i in $$liblist ;\
do \
if [ -f "$$i" ]; then \
( echo installing $$i; \
cp $$i $(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR)/$$i.new; \
$(RANLIB) $(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR)/$$i.new; \
chmod 644 $(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR)/$$i.new; \
mv -f $(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR)/$$i.new $(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR)/$$i ); \
fi; \
done;
@set -e; if [ -n "$(SHARED_LIBS)" ]; then \
tmp="$(SHARED_LIBS)"; \
for i in $${tmp:-x}; \
do \
if [ -f "$$i" -o -f "$$i.a" ]; then \
( echo installing $$i; \
if expr "$(PLATFORM)" : "Cygwin" >/dev/null; then \
c=`echo $$i | sed 's/^lib\(.*\)\.dll\.a/cyg\1-$(SHLIB_VERSION_NUMBER).dll/'`; \
cp $$c $(INSTALL_PREFIX)$(INSTALLTOP)/bin/$$c.new; \
chmod 755 $(INSTALL_PREFIX)$(INSTALLTOP)/bin/$$c.new; \
mv -f $(INSTALL_PREFIX)$(INSTALLTOP)/bin/$$c.new $(INSTALL_PREFIX)$(INSTALLTOP)/bin/$$c; \
cp $$i $(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR)/$$i.new; \
chmod 644 $(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR)/$$i.new; \
mv -f $(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR)/$$i.new $(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR)/$$i; \
else \
cp $$i $(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR)/$$i.new; \
chmod 555 $(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR)/$$i.new; \
mv -f $(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR)/$$i.new $(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR)/$$i; \
fi ); \
if expr $(PLATFORM) : 'mingw' > /dev/null; then \
( case $$i in \
*crypto*) i=libeay32.dll;; \
*ssl*) i=ssleay32.dll;; \
esac; \
echo installing $$i; \
cp $$i $(INSTALL_PREFIX)$(INSTALLTOP)/bin/$$i.new; \
chmod 755 $(INSTALL_PREFIX)$(INSTALLTOP)/bin/$$i.new; \
mv -f $(INSTALL_PREFIX)$(INSTALLTOP)/bin/$$i.new $(INSTALL_PREFIX)$(INSTALLTOP)/bin/$$i ); \
fi; \
fi; \
done; \
( here="`pwd`"; \
cd $(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR); \
$(MAKE) -f $$here/Makefile HERE="$$here" link-shared ); \
if [ "$(INSTALLTOP)" != "/usr" ]; then \
echo 'OpenSSL shared libraries have been installed in:'; \
echo ' $(INSTALLTOP)'; \
echo ''; \
sed -e '1,/^$$/d' doc/openssl-shared.txt; \
fi; \
fi
cp libcrypto.pc $(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR)/pkgconfig
chmod 644 $(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR)/pkgconfig/libcrypto.pc
cp libssl.pc $(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR)/pkgconfig
chmod 644 $(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR)/pkgconfig/libssl.pc
cp openssl.pc $(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR)/pkgconfig
chmod 644 $(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR)/pkgconfig/openssl.pc
install_html_docs:
here="`pwd`"; \
filecase=; \
case "$(PLATFORM)" in DJGPP|Cygwin*|mingw*|darwin*-*-cc) \
filecase=-i; \
esac; \
for subdir in apps crypto ssl; do \
mkdir -p $(INSTALL_PREFIX)$(HTMLDIR)/$$subdir; \
for i in doc/$$subdir/*.pod; do \
fn=`basename $$i .pod`; \
echo "installing html/$$fn.$(HTMLSUFFIX)"; \
cat $$i \
| sed -r 's/L<([^)]*)(\([0-9]\))?\|([^)]*)(\([0-9]\))?>/L<\1|\3>/g' \
| pod2html --podroot=doc --htmlroot=.. --podpath=apps:crypto:ssl \
| sed -r 's/<!DOCTYPE.*//g' \
> $(INSTALL_PREFIX)$(HTMLDIR)/$$subdir/$$fn.$(HTMLSUFFIX); \
$(PERL) util/extract-names.pl < $$i | \
grep -v $$filecase "^$$fn\$$" | \
(cd $(INSTALL_PREFIX)$(HTMLDIR)/$$subdir; \
while read n; do \
PLATFORM=$(PLATFORM) $$here/util/point.sh $$fn.$(HTMLSUFFIX) "$$n".$(HTMLSUFFIX); \
done); \
done; \
done
install_docs:
@$(PERL) $(TOP)/util/mkdir-p.pl \
$(INSTALL_PREFIX)$(MANDIR)/man1 \
$(INSTALL_PREFIX)$(MANDIR)/man3 \
$(INSTALL_PREFIX)$(MANDIR)/man5 \
$(INSTALL_PREFIX)$(MANDIR)/man7
@pod2man="`cd ./util; ./pod2mantest $(PERL)`"; \
here="`pwd`"; \
filecase=; \
case "$(PLATFORM)" in DJGPP|Cygwin*|mingw*|darwin*-*-cc) \
filecase=-i; \
esac; \
set -e; for i in doc/apps/*.pod; do \
fn=`basename $$i .pod`; \
sec=`$(PERL) util/extract-section.pl 1 < $$i`; \
echo "installing man$$sec/$$fn.$${sec}$(MANSUFFIX)"; \
(cd `$(PERL) util/dirname.pl $$i`; \
sh -c "$$pod2man \
--section=$$sec --center=OpenSSL \
--release=$(VERSION) `basename $$i`") \
> $(INSTALL_PREFIX)$(MANDIR)/man$$sec/$$fn.$${sec}$(MANSUFFIX); \
$(PERL) util/extract-names.pl < $$i | \
(grep -v $$filecase "^$$fn\$$"; true) | \
(grep -v "[ ]"; true) | \
(cd $(INSTALL_PREFIX)$(MANDIR)/man$$sec/; \
while read n; do \
PLATFORM=$(PLATFORM) $$here/util/point.sh $$fn.$${sec}$(MANSUFFIX) "$$n".$${sec}$(MANSUFFIX); \
done); \
done; \
set -e; for i in doc/crypto/*.pod doc/ssl/*.pod; do \
fn=`basename $$i .pod`; \
sec=`$(PERL) util/extract-section.pl 3 < $$i`; \
echo "installing man$$sec/$$fn.$${sec}$(MANSUFFIX)"; \
(cd `$(PERL) util/dirname.pl $$i`; \
sh -c "$$pod2man \
--section=$$sec --center=OpenSSL \
--release=$(VERSION) `basename $$i`") \
> $(INSTALL_PREFIX)$(MANDIR)/man$$sec/$$fn.$${sec}$(MANSUFFIX); \
$(PERL) util/extract-names.pl < $$i | \
(grep -v $$filecase "^$$fn\$$"; true) | \
(grep -v "[ ]"; true) | \
(cd $(INSTALL_PREFIX)$(MANDIR)/man$$sec/; \
while read n; do \
PLATFORM=$(PLATFORM) $$here/util/point.sh $$fn.$${sec}$(MANSUFFIX) "$$n".$${sec}$(MANSUFFIX); \
done); \
done
# DO NOT DELETE THIS LINE -- make depend depends on it.
diff --git a/NEWS b/NEWS
index 6f0c5c47b654..5080f79a6cbf 100644
--- a/NEWS
+++ b/NEWS
@@ -1,813 +1,818 @@
NEWS
====
This file gives a brief overview of the major changes between each OpenSSL
release. For more details please read the CHANGES file.
+ Major changes between OpenSSL 1.0.2n and OpenSSL 1.0.2o [27 Mar 2018]
+
+ o 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]
o Read/write after SSL object in error state (CVE-2017-3737)
o 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]
o bn_sqrx8x_internal carry bug on x86_64 (CVE-2017-3736)
o Malformed X.509 IPAddressFamily could cause OOB read (CVE-2017-3735)
Major changes between OpenSSL 1.0.2k and OpenSSL 1.0.2l [25 May 2017]
o config now recognises 64-bit mingw and chooses mingw64 instead of mingw
Major changes between OpenSSL 1.0.2j and OpenSSL 1.0.2k [26 Jan 2017]
o Truncated packet could crash via OOB read (CVE-2017-3731)
o BN_mod_exp may produce incorrect results on x86_64 (CVE-2017-3732)
o Montgomery multiplication may produce incorrect results (CVE-2016-7055)
Major changes between OpenSSL 1.0.2i and OpenSSL 1.0.2j [26 Sep 2016]
o Missing CRL sanity check (CVE-2016-7052)
Major changes between OpenSSL 1.0.2h and OpenSSL 1.0.2i [22 Sep 2016]
o OCSP Status Request extension unbounded memory growth (CVE-2016-6304)
o SWEET32 Mitigation (CVE-2016-2183)
o OOB write in MDC2_Update() (CVE-2016-6303)
o Malformed SHA512 ticket DoS (CVE-2016-6302)
o OOB write in BN_bn2dec() (CVE-2016-2182)
o OOB read in TS_OBJ_print_bio() (CVE-2016-2180)
o Pointer arithmetic undefined behaviour (CVE-2016-2177)
o Constant time flag not preserved in DSA signing (CVE-2016-2178)
o DTLS buffered message DoS (CVE-2016-2179)
o DTLS replay protection DoS (CVE-2016-2181)
o Certificate message OOB reads (CVE-2016-6306)
Major changes between OpenSSL 1.0.2g and OpenSSL 1.0.2h [3 May 2016]
o Prevent padding oracle in AES-NI CBC MAC check (CVE-2016-2107)
o Fix EVP_EncodeUpdate overflow (CVE-2016-2105)
o Fix EVP_EncryptUpdate overflow (CVE-2016-2106)
o Prevent ASN.1 BIO excessive memory allocation (CVE-2016-2109)
o EBCDIC overread (CVE-2016-2176)
o Modify behavior of ALPN to invoke callback after SNI/servername
callback, such that updates to the SSL_CTX affect ALPN.
o Remove LOW from the DEFAULT cipher list. This removes singles DES from
the default.
o Only remove the SSLv2 methods with the no-ssl2-method option.
Major changes between OpenSSL 1.0.2f and OpenSSL 1.0.2g [1 Mar 2016]
o Disable weak ciphers in SSLv3 and up in default builds of OpenSSL.
o Disable SSLv2 default build, default negotiation and weak ciphers
(CVE-2016-0800)
o Fix a double-free in DSA code (CVE-2016-0705)
o Disable SRP fake user seed to address a server memory leak
(CVE-2016-0798)
o Fix BN_hex2bn/BN_dec2bn NULL pointer deref/heap corruption
(CVE-2016-0797)
o Fix memory issues in BIO_*printf functions (CVE-2016-0799)
o Fix side channel attack on modular exponentiation (CVE-2016-0702)
Major changes between OpenSSL 1.0.2e and OpenSSL 1.0.2f [28 Jan 2016]
o DH small subgroups (CVE-2016-0701)
o SSLv2 doesn't block disabled ciphers (CVE-2015-3197)
Major changes between OpenSSL 1.0.2d and OpenSSL 1.0.2e [3 Dec 2015]
o BN_mod_exp may produce incorrect results on x86_64 (CVE-2015-3193)
o Certificate verify crash with missing PSS parameter (CVE-2015-3194)
o X509_ATTRIBUTE memory leak (CVE-2015-3195)
o Rewrite EVP_DecodeUpdate (base64 decoding) to fix several bugs
o In DSA_generate_parameters_ex, if the provided seed is too short,
return an error
Major changes between OpenSSL 1.0.2c and OpenSSL 1.0.2d [9 Jul 2015]
o Alternate chains certificate forgery (CVE-2015-1793)
o Race condition handling PSK identify hint (CVE-2015-3196)
Major changes between OpenSSL 1.0.2b and OpenSSL 1.0.2c [12 Jun 2015]
o Fix HMAC ABI incompatibility
Major changes between OpenSSL 1.0.2a and OpenSSL 1.0.2b [11 Jun 2015]
o Malformed ECParameters causes infinite loop (CVE-2015-1788)
o Exploitable out-of-bounds read in X509_cmp_time (CVE-2015-1789)
o PKCS7 crash with missing EnvelopedContent (CVE-2015-1790)
o CMS verify infinite loop with unknown hash function (CVE-2015-1792)
o Race condition handling NewSessionTicket (CVE-2015-1791)
Major changes between OpenSSL 1.0.2 and OpenSSL 1.0.2a [19 Mar 2015]
o OpenSSL 1.0.2 ClientHello sigalgs DoS fix (CVE-2015-0291)
o Multiblock corrupted pointer fix (CVE-2015-0290)
o Segmentation fault in DTLSv1_listen fix (CVE-2015-0207)
o Segmentation fault in ASN1_TYPE_cmp fix (CVE-2015-0286)
o Segmentation fault for invalid PSS parameters fix (CVE-2015-0208)
o ASN.1 structure reuse memory corruption fix (CVE-2015-0287)
o PKCS7 NULL pointer dereferences fix (CVE-2015-0289)
o DoS via reachable assert in SSLv2 servers fix (CVE-2015-0293)
o Empty CKE with client auth and DHE fix (CVE-2015-1787)
o Handshake with unseeded PRNG fix (CVE-2015-0285)
o Use After Free following d2i_ECPrivatekey error fix (CVE-2015-0209)
o X509_to_X509_REQ NULL pointer deref fix (CVE-2015-0288)
o Removed the export ciphers from the DEFAULT ciphers
Major changes between OpenSSL 1.0.1l and OpenSSL 1.0.2 [22 Jan 2015]:
o Suite B support for TLS 1.2 and DTLS 1.2
o Support for DTLS 1.2
o TLS automatic EC curve selection.
o API to set TLS supported signature algorithms and curves
o SSL_CONF configuration API.
o TLS Brainpool support.
o ALPN support.
o CMS support for RSA-PSS, RSA-OAEP, ECDH and X9.42 DH.
Major changes between OpenSSL 1.0.1k and OpenSSL 1.0.1l [15 Jan 2015]
o Build fixes for the Windows and OpenVMS platforms
Major changes between OpenSSL 1.0.1j and OpenSSL 1.0.1k [8 Jan 2015]
o Fix for CVE-2014-3571
o Fix for CVE-2015-0206
o Fix for CVE-2014-3569
o Fix for CVE-2014-3572
o Fix for CVE-2015-0204
o Fix for CVE-2015-0205
o Fix for CVE-2014-8275
o Fix for CVE-2014-3570
Major changes between OpenSSL 1.0.1i and OpenSSL 1.0.1j [15 Oct 2014]
o Fix for CVE-2014-3513
o Fix for CVE-2014-3567
o Mitigation for CVE-2014-3566 (SSL protocol vulnerability)
o Fix for CVE-2014-3568
Major changes between OpenSSL 1.0.1h and OpenSSL 1.0.1i [6 Aug 2014]
o Fix for CVE-2014-3512
o Fix for CVE-2014-3511
o Fix for CVE-2014-3510
o Fix for CVE-2014-3507
o Fix for CVE-2014-3506
o Fix for CVE-2014-3505
o Fix for CVE-2014-3509
o Fix for CVE-2014-5139
o Fix for CVE-2014-3508
Major changes between OpenSSL 1.0.1g and OpenSSL 1.0.1h [5 Jun 2014]
o Fix for CVE-2014-0224
o Fix for CVE-2014-0221
o Fix for CVE-2014-0198
o Fix for CVE-2014-0195
o Fix for CVE-2014-3470
o Fix for CVE-2010-5298
Major changes between OpenSSL 1.0.1f and OpenSSL 1.0.1g [7 Apr 2014]
o Fix for CVE-2014-0160
o Add TLS padding extension workaround for broken servers.
o Fix for CVE-2014-0076
Major changes between OpenSSL 1.0.1e and OpenSSL 1.0.1f [6 Jan 2014]
o Don't include gmt_unix_time in TLS server and client random values
o Fix for TLS record tampering bug CVE-2013-4353
o Fix for TLS version checking bug CVE-2013-6449
o Fix for DTLS retransmission bug CVE-2013-6450
Major changes between OpenSSL 1.0.1d and OpenSSL 1.0.1e [11 Feb 2013]:
o Corrected fix for CVE-2013-0169
Major changes between OpenSSL 1.0.1c and OpenSSL 1.0.1d [4 Feb 2013]:
o Fix renegotiation in TLS 1.1, 1.2 by using the correct TLS version.
o Include the fips configuration module.
o Fix OCSP bad key DoS attack CVE-2013-0166
o Fix for SSL/TLS/DTLS CBC plaintext recovery attack CVE-2013-0169
o Fix for TLS AESNI record handling flaw CVE-2012-2686
Major changes between OpenSSL 1.0.1b and OpenSSL 1.0.1c [10 May 2012]:
o Fix TLS/DTLS record length checking bug CVE-2012-2333
o Don't attempt to use non-FIPS composite ciphers in FIPS mode.
Major changes between OpenSSL 1.0.1a and OpenSSL 1.0.1b [26 Apr 2012]:
o Fix compilation error on non-x86 platforms.
o Make FIPS capable OpenSSL ciphers work in non-FIPS mode.
o Fix SSL_OP_NO_TLSv1_1 clash with SSL_OP_ALL in OpenSSL 1.0.0
Major changes between OpenSSL 1.0.1 and OpenSSL 1.0.1a [19 Apr 2012]:
o Fix for ASN1 overflow bug CVE-2012-2110
o Workarounds for some servers that hang on long client hellos.
o Fix SEGV in AES code.
Major changes between OpenSSL 1.0.0h and OpenSSL 1.0.1 [14 Mar 2012]:
o TLS/DTLS heartbeat support.
o SCTP support.
o RFC 5705 TLS key material exporter.
o RFC 5764 DTLS-SRTP negotiation.
o Next Protocol Negotiation.
o PSS signatures in certificates, requests and CRLs.
o Support for password based recipient info for CMS.
o Support TLS v1.2 and TLS v1.1.
o Preliminary FIPS capability for unvalidated 2.0 FIPS module.
o SRP support.
Major changes between OpenSSL 1.0.0g and OpenSSL 1.0.0h [12 Mar 2012]:
o Fix for CMS/PKCS#7 MMA CVE-2012-0884
o Corrected fix for CVE-2011-4619
o Various DTLS fixes.
Major changes between OpenSSL 1.0.0f and OpenSSL 1.0.0g [18 Jan 2012]:
o Fix for DTLS DoS issue CVE-2012-0050
Major changes between OpenSSL 1.0.0e and OpenSSL 1.0.0f [4 Jan 2012]:
o Fix for DTLS plaintext recovery attack CVE-2011-4108
o Clear block padding bytes of SSL 3.0 records CVE-2011-4576
o Only allow one SGC handshake restart for SSL/TLS CVE-2011-4619
o Check parameters are not NULL in GOST ENGINE CVE-2012-0027
o Check for malformed RFC3779 data CVE-2011-4577
Major changes between OpenSSL 1.0.0d and OpenSSL 1.0.0e [6 Sep 2011]:
o Fix for CRL vulnerability issue CVE-2011-3207
o Fix for ECDH crashes CVE-2011-3210
o Protection against EC timing attacks.
o Support ECDH ciphersuites for certificates using SHA2 algorithms.
o Various DTLS fixes.
Major changes between OpenSSL 1.0.0c and OpenSSL 1.0.0d [8 Feb 2011]:
o Fix for security issue CVE-2011-0014
Major changes between OpenSSL 1.0.0b and OpenSSL 1.0.0c [2 Dec 2010]:
o Fix for security issue CVE-2010-4180
o Fix for CVE-2010-4252
o Fix mishandling of absent EC point format extension.
o Fix various platform compilation issues.
o Corrected fix for security issue CVE-2010-3864.
Major changes between OpenSSL 1.0.0a and OpenSSL 1.0.0b [16 Nov 2010]:
o Fix for security issue CVE-2010-3864.
o Fix for CVE-2010-2939
o Fix WIN32 build system for GOST ENGINE.
Major changes between OpenSSL 1.0.0 and OpenSSL 1.0.0a [1 Jun 2010]:
o Fix for security issue CVE-2010-1633.
o GOST MAC and CFB fixes.
Major changes between OpenSSL 0.9.8n and OpenSSL 1.0.0 [29 Mar 2010]:
o RFC3280 path validation: sufficient to process PKITS tests.
o Integrated support for PVK files and keyblobs.
o Change default private key format to PKCS#8.
o CMS support: able to process all examples in RFC4134
o Streaming ASN1 encode support for PKCS#7 and CMS.
o Multiple signer and signer add support for PKCS#7 and CMS.
o ASN1 printing support.
o Whirlpool hash algorithm added.
o RFC3161 time stamp support.
o New generalised public key API supporting ENGINE based algorithms.
o New generalised public key API utilities.
o New ENGINE supporting GOST algorithms.
o SSL/TLS GOST ciphersuite support.
o PKCS#7 and CMS GOST support.
o RFC4279 PSK ciphersuite support.
o Supported points format extension for ECC ciphersuites.
o ecdsa-with-SHA224/256/384/512 signature types.
o dsa-with-SHA224 and dsa-with-SHA256 signature types.
o Opaque PRF Input TLS extension support.
o Updated time routines to avoid OS limitations.
Major changes between OpenSSL 0.9.8m and OpenSSL 0.9.8n [24 Mar 2010]:
o CFB cipher definition fixes.
o Fix security issues CVE-2010-0740 and CVE-2010-0433.
Major changes between OpenSSL 0.9.8l and OpenSSL 0.9.8m [25 Feb 2010]:
o Cipher definition fixes.
o Workaround for slow RAND_poll() on some WIN32 versions.
o Remove MD2 from algorithm tables.
o SPKAC handling fixes.
o Support for RFC5746 TLS renegotiation extension.
o Compression memory leak fixed.
o Compression session resumption fixed.
o Ticket and SNI coexistence fixes.
o Many fixes to DTLS handling.
Major changes between OpenSSL 0.9.8k and OpenSSL 0.9.8l [5 Nov 2009]:
o Temporary work around for CVE-2009-3555: disable renegotiation.
Major changes between OpenSSL 0.9.8j and OpenSSL 0.9.8k [25 Mar 2009]:
o Fix various build issues.
o Fix security issues (CVE-2009-0590, CVE-2009-0591, CVE-2009-0789)
Major changes between OpenSSL 0.9.8i and OpenSSL 0.9.8j [7 Jan 2009]:
o Fix security issue (CVE-2008-5077)
o Merge FIPS 140-2 branch code.
Major changes between OpenSSL 0.9.8g and OpenSSL 0.9.8h [28 May 2008]:
o CryptoAPI ENGINE support.
o Various precautionary measures.
o Fix for bugs affecting certificate request creation.
o Support for local machine keyset attribute in PKCS#12 files.
Major changes between OpenSSL 0.9.8f and OpenSSL 0.9.8g [19 Oct 2007]:
o Backport of CMS functionality to 0.9.8.
o Fixes for bugs introduced with 0.9.8f.
Major changes between OpenSSL 0.9.8e and OpenSSL 0.9.8f [11 Oct 2007]:
o Add gcc 4.2 support.
o Add support for AES and SSE2 assembly lanugauge optimization
for VC++ build.
o Support for RFC4507bis and server name extensions if explicitly
selected at compile time.
o DTLS improvements.
o RFC4507bis support.
o TLS Extensions support.
Major changes between OpenSSL 0.9.8d and OpenSSL 0.9.8e [23 Feb 2007]:
o Various ciphersuite selection fixes.
o RFC3779 support.
Major changes between OpenSSL 0.9.8c and OpenSSL 0.9.8d [28 Sep 2006]:
o Introduce limits to prevent malicious key DoS (CVE-2006-2940)
o Fix security issues (CVE-2006-2937, CVE-2006-3737, CVE-2006-4343)
o Changes to ciphersuite selection algorithm
Major changes between OpenSSL 0.9.8b and OpenSSL 0.9.8c [5 Sep 2006]:
o Fix Daniel Bleichenbacher forged signature attack, CVE-2006-4339
o New cipher Camellia
Major changes between OpenSSL 0.9.8a and OpenSSL 0.9.8b [4 May 2006]:
o Cipher string fixes.
o Fixes for VC++ 2005.
o Updated ECC cipher suite support.
o New functions EVP_CIPHER_CTX_new() and EVP_CIPHER_CTX_free().
o Zlib compression usage fixes.
o Built in dynamic engine compilation support on Win32.
o Fixes auto dynamic engine loading in Win32.
Major changes between OpenSSL 0.9.8 and OpenSSL 0.9.8a [11 Oct 2005]:
o Fix potential SSL 2.0 rollback, CVE-2005-2969
o Extended Windows CE support
Major changes between OpenSSL 0.9.7g and OpenSSL 0.9.8 [5 Jul 2005]:
o Major work on the BIGNUM library for higher efficiency and to
make operations more streamlined and less contradictory. This
is the result of a major audit of the BIGNUM library.
o Addition of BIGNUM functions for fields GF(2^m) and NIST
curves, to support the Elliptic Crypto functions.
o Major work on Elliptic Crypto; ECDH and ECDSA added, including
the use through EVP, X509 and ENGINE.
o New ASN.1 mini-compiler that's usable through the OpenSSL
configuration file.
o Added support for ASN.1 indefinite length constructed encoding.
o New PKCS#12 'medium level' API to manipulate PKCS#12 files.
o Complete rework of shared library construction and linking
programs with shared or static libraries, through a separate
Makefile.shared.
o Rework of the passing of parameters from one Makefile to another.
o Changed ENGINE framework to load dynamic engine modules
automatically from specifically given directories.
o New structure and ASN.1 functions for CertificatePair.
o Changed the ZLIB compression method to be stateful.
o Changed the key-generation and primality testing "progress"
mechanism to take a structure that contains the ticker
function and an argument.
o New engine module: GMP (performs private key exponentiation).
o New engine module: VIA PadLOck ACE extension in VIA C3
Nehemiah processors.
o Added support for IPv6 addresses in certificate extensions.
See RFC 1884, section 2.2.
o Added support for certificate policy mappings, policy
constraints and name constraints.
o Added support for multi-valued AVAs in the OpenSSL
configuration file.
o Added support for multiple certificates with the same subject
in the 'openssl ca' index file.
o Make it possible to create self-signed certificates using
'openssl ca -selfsign'.
o Make it possible to generate a serial number file with
'openssl ca -create_serial'.
o New binary search functions with extended functionality.
o New BUF functions.
o New STORE structure and library to provide an interface to all
sorts of data repositories. Supports storage of public and
private keys, certificates, CRLs, numbers and arbitrary blobs.
This library is unfortunately unfinished and unused withing
OpenSSL.
o New control functions for the error stack.
o Changed the PKCS#7 library to support one-pass S/MIME
processing.
o Added the possibility to compile without old deprecated
functionality with the OPENSSL_NO_DEPRECATED macro or the
'no-deprecated' argument to the config and Configure scripts.
o Constification of all ASN.1 conversion functions, and other
affected functions.
o Improved platform support for PowerPC.
o New FIPS 180-2 algorithms (SHA-224, -256, -384 and -512).
o New X509_VERIFY_PARAM structure to support parametrisation
of X.509 path validation.
o Major overhaul of RC4 performance on Intel P4, IA-64 and
AMD64.
o Changed the Configure script to have some algorithms disabled
by default. Those can be explicitely enabled with the new
argument form 'enable-xxx'.
o Change the default digest in 'openssl' commands from MD5 to
SHA-1.
o Added support for DTLS.
o New BIGNUM blinding.
o Added support for the RSA-PSS encryption scheme
o Added support for the RSA X.931 padding.
o Added support for BSD sockets on NetWare.
o Added support for files larger than 2GB.
o Added initial support for Win64.
o Added alternate pkg-config files.
Major changes between OpenSSL 0.9.7l and OpenSSL 0.9.7m [23 Feb 2007]:
o FIPS 1.1.1 module linking.
o Various ciphersuite selection fixes.
Major changes between OpenSSL 0.9.7k and OpenSSL 0.9.7l [28 Sep 2006]:
o Introduce limits to prevent malicious key DoS (CVE-2006-2940)
o Fix security issues (CVE-2006-2937, CVE-2006-3737, CVE-2006-4343)
Major changes between OpenSSL 0.9.7j and OpenSSL 0.9.7k [5 Sep 2006]:
o Fix Daniel Bleichenbacher forged signature attack, CVE-2006-4339
Major changes between OpenSSL 0.9.7i and OpenSSL 0.9.7j [4 May 2006]:
o Visual C++ 2005 fixes.
o Update Windows build system for FIPS.
Major changes between OpenSSL 0.9.7h and OpenSSL 0.9.7i [14 Oct 2005]:
o Give EVP_MAX_MD_SIZE it's old value, except for a FIPS build.
Major changes between OpenSSL 0.9.7g and OpenSSL 0.9.7h [11 Oct 2005]:
o Fix SSL 2.0 Rollback, CVE-2005-2969
o Allow use of fixed-length exponent on DSA signing
o Default fixed-window RSA, DSA, DH private-key operations
Major changes between OpenSSL 0.9.7f and OpenSSL 0.9.7g [11 Apr 2005]:
o More compilation issues fixed.
o Adaptation to more modern Kerberos API.
o Enhanced or corrected configuration for Solaris64, Mingw and Cygwin.
o Enhanced x86_64 assembler BIGNUM module.
o More constification.
o Added processing of proxy certificates (RFC 3820).
Major changes between OpenSSL 0.9.7e and OpenSSL 0.9.7f [22 Mar 2005]:
o Several compilation issues fixed.
o Many memory allocation failure checks added.
o Improved comparison of X509 Name type.
o Mandatory basic checks on certificates.
o Performance improvements.
Major changes between OpenSSL 0.9.7d and OpenSSL 0.9.7e [25 Oct 2004]:
o Fix race condition in CRL checking code.
o Fixes to PKCS#7 (S/MIME) code.
Major changes between OpenSSL 0.9.7c and OpenSSL 0.9.7d [17 Mar 2004]:
o Security: Fix Kerberos ciphersuite SSL/TLS handshaking bug
o Security: Fix null-pointer assignment in do_change_cipher_spec()
o Allow multiple active certificates with same subject in CA index
o Multiple X509 verification fixes
o Speed up HMAC and other operations
Major changes between OpenSSL 0.9.7b and OpenSSL 0.9.7c [30 Sep 2003]:
o Security: fix various ASN1 parsing bugs.
o New -ignore_err option to OCSP utility.
o Various interop and bug fixes in S/MIME code.
o SSL/TLS protocol fix for unrequested client certificates.
Major changes between OpenSSL 0.9.7a and OpenSSL 0.9.7b [10 Apr 2003]:
o Security: counter the Klima-Pokorny-Rosa extension of
Bleichbacher's attack
o Security: make RSA blinding default.
o Configuration: Irix fixes, AIX fixes, better mingw support.
o Support for new platforms: linux-ia64-ecc.
o Build: shared library support fixes.
o ASN.1: treat domainComponent correctly.
o Documentation: fixes and additions.
Major changes between OpenSSL 0.9.7 and OpenSSL 0.9.7a [19 Feb 2003]:
o Security: Important security related bugfixes.
o Enhanced compatibility with MIT Kerberos.
o Can be built without the ENGINE framework.
o IA32 assembler enhancements.
o Support for new platforms: FreeBSD/IA64 and FreeBSD/Sparc64.
o Configuration: the no-err option now works properly.
o SSL/TLS: now handles manual certificate chain building.
o SSL/TLS: certain session ID malfunctions corrected.
Major changes between OpenSSL 0.9.6 and OpenSSL 0.9.7 [30 Dec 2002]:
o New library section OCSP.
o Complete rewrite of ASN1 code.
o CRL checking in verify code and openssl utility.
o Extension copying in 'ca' utility.
o Flexible display options in 'ca' utility.
o Provisional support for international characters with UTF8.
o Support for external crypto devices ('engine') is no longer
a separate distribution.
o New elliptic curve library section.
o New AES (Rijndael) library section.
o Support for new platforms: Windows CE, Tandem OSS, A/UX, AIX 64-bit,
Linux x86_64, Linux 64-bit on Sparc v9
o Extended support for some platforms: VxWorks
o Enhanced support for shared libraries.
o Now only builds PIC code when shared library support is requested.
o Support for pkg-config.
o Lots of new manuals.
o Makes symbolic links to or copies of manuals to cover all described
functions.
o Change DES API to clean up the namespace (some applications link also
against libdes providing similar functions having the same name).
Provide macros for backward compatibility (will be removed in the
future).
o Unify handling of cryptographic algorithms (software and engine)
to be available via EVP routines for asymmetric and symmetric ciphers.
o NCONF: new configuration handling routines.
o Change API to use more 'const' modifiers to improve error checking
and help optimizers.
o Finally remove references to RSAref.
o Reworked parts of the BIGNUM code.
o Support for new engines: Broadcom ubsec, Accelerated Encryption
Processing, IBM 4758.
o A few new engines added in the demos area.
o Extended and corrected OID (object identifier) table.
o PRNG: query at more locations for a random device, automatic query for
EGD style random sources at several locations.
o SSL/TLS: allow optional cipher choice according to server's preference.
o SSL/TLS: allow server to explicitly set new session ids.
o SSL/TLS: support Kerberos cipher suites (RFC2712).
Only supports MIT Kerberos for now.
o SSL/TLS: allow more precise control of renegotiations and sessions.
o SSL/TLS: add callback to retrieve SSL/TLS messages.
o SSL/TLS: support AES cipher suites (RFC3268).
Major changes between OpenSSL 0.9.6j and OpenSSL 0.9.6k [30 Sep 2003]:
o Security: fix various ASN1 parsing bugs.
o SSL/TLS protocol fix for unrequested client certificates.
Major changes between OpenSSL 0.9.6i and OpenSSL 0.9.6j [10 Apr 2003]:
o Security: counter the Klima-Pokorny-Rosa extension of
Bleichbacher's attack
o Security: make RSA blinding default.
o Build: shared library support fixes.
Major changes between OpenSSL 0.9.6h and OpenSSL 0.9.6i [19 Feb 2003]:
o Important security related bugfixes.
Major changes between OpenSSL 0.9.6g and OpenSSL 0.9.6h [5 Dec 2002]:
o New configuration targets for Tandem OSS and A/UX.
o New OIDs for Microsoft attributes.
o Better handling of SSL session caching.
o Better comparison of distinguished names.
o Better handling of shared libraries in a mixed GNU/non-GNU environment.
o Support assembler code with Borland C.
o Fixes for length problems.
o Fixes for uninitialised variables.
o Fixes for memory leaks, some unusual crashes and some race conditions.
o Fixes for smaller building problems.
o Updates of manuals, FAQ and other instructive documents.
Major changes between OpenSSL 0.9.6f and OpenSSL 0.9.6g [9 Aug 2002]:
o Important building fixes on Unix.
Major changes between OpenSSL 0.9.6e and OpenSSL 0.9.6f [8 Aug 2002]:
o Various important bugfixes.
Major changes between OpenSSL 0.9.6d and OpenSSL 0.9.6e [30 Jul 2002]:
o Important security related bugfixes.
o Various SSL/TLS library bugfixes.
Major changes between OpenSSL 0.9.6c and OpenSSL 0.9.6d [9 May 2002]:
o Various SSL/TLS library bugfixes.
o Fix DH parameter generation for 'non-standard' generators.
Major changes between OpenSSL 0.9.6b and OpenSSL 0.9.6c [21 Dec 2001]:
o Various SSL/TLS library bugfixes.
o BIGNUM library fixes.
o RSA OAEP and random number generation fixes.
o Object identifiers corrected and added.
o Add assembler BN routines for IA64.
o Add support for OS/390 Unix, UnixWare with gcc, OpenUNIX 8,
MIPS Linux; shared library support for Irix, HP-UX.
o Add crypto accelerator support for AEP, Baltimore SureWare,
Broadcom and Cryptographic Appliance's keyserver
[in 0.9.6c-engine release].
Major changes between OpenSSL 0.9.6a and OpenSSL 0.9.6b [9 Jul 2001]:
o Security fix: PRNG improvements.
o Security fix: RSA OAEP check.
o Security fix: Reinsert and fix countermeasure to Bleichbacher's
attack.
o MIPS bug fix in BIGNUM.
o Bug fix in "openssl enc".
o Bug fix in X.509 printing routine.
o Bug fix in DSA verification routine and DSA S/MIME verification.
o Bug fix to make PRNG thread-safe.
o Bug fix in RAND_file_name().
o Bug fix in compatibility mode trust settings.
o Bug fix in blowfish EVP.
o Increase default size for BIO buffering filter.
o Compatibility fixes in some scripts.
Major changes between OpenSSL 0.9.6 and OpenSSL 0.9.6a [5 Apr 2001]:
o Security fix: change behavior of OpenSSL to avoid using
environment variables when running as root.
o Security fix: check the result of RSA-CRT to reduce the
possibility of deducing the private key from an incorrectly
calculated signature.
o Security fix: prevent Bleichenbacher's DSA attack.
o Security fix: Zero the premaster secret after deriving the
master secret in DH ciphersuites.
o Reimplement SSL_peek(), which had various problems.
o Compatibility fix: the function des_encrypt() renamed to
des_encrypt1() to avoid clashes with some Unixen libc.
o Bug fixes for Win32, HP/UX and Irix.
o Bug fixes in BIGNUM, SSL, PKCS#7, PKCS#12, X.509, CONF and
memory checking routines.
o Bug fixes for RSA operations in threaded environments.
o Bug fixes in misc. openssl applications.
o Remove a few potential memory leaks.
o Add tighter checks of BIGNUM routines.
o Shared library support has been reworked for generality.
o More documentation.
o New function BN_rand_range().
o Add "-rand" option to openssl s_client and s_server.
Major changes between OpenSSL 0.9.5a and OpenSSL 0.9.6 [10 Oct 2000]:
o Some documentation for BIO and SSL libraries.
o Enhanced chain verification using key identifiers.
o New sign and verify options to 'dgst' application.
o Support for DER and PEM encoded messages in 'smime' application.
o New 'rsautl' application, low level RSA utility.
o MD4 now included.
o Bugfix for SSL rollback padding check.
o Support for external crypto devices [1].
o Enhanced EVP interface.
[1] The support for external crypto devices is currently a separate
distribution. See the file README.ENGINE.
Major changes between OpenSSL 0.9.5 and OpenSSL 0.9.5a [1 Apr 2000]:
o Bug fixes for Win32, SuSE Linux, NeXTSTEP and FreeBSD 2.2.8
o Shared library support for HPUX and Solaris-gcc
o Support of Linux/IA64
o Assembler support for Mingw32
o New 'rand' application
o New way to check for existence of algorithms from scripts
Major changes between OpenSSL 0.9.4 and OpenSSL 0.9.5 [25 May 2000]:
o S/MIME support in new 'smime' command
o Documentation for the OpenSSL command line application
o Automation of 'req' application
o Fixes to make s_client, s_server work under Windows
o Support for multiple fieldnames in SPKACs
o New SPKAC command line utilty and associated library functions
o Options to allow passwords to be obtained from various sources
o New public key PEM format and options to handle it
o Many other fixes and enhancements to command line utilities
o Usable certificate chain verification
o Certificate purpose checking
o Certificate trust settings
o Support of authority information access extension
o Extensions in certificate requests
o Simplified X509 name and attribute routines
o Initial (incomplete) support for international character sets
o New DH_METHOD, DSA_METHOD and enhanced RSA_METHOD
o Read only memory BIOs and simplified creation function
o TLS/SSL protocol bugfixes: Accept TLS 'client hello' in SSL 3.0
record; allow fragmentation and interleaving of handshake and other
data
o TLS/SSL code now "tolerates" MS SGC
o Work around for Netscape client certificate hang bug
o RSA_NULL option that removes RSA patent code but keeps other
RSA functionality
o Memory leak detection now allows applications to add extra information
via a per-thread stack
o PRNG robustness improved
o EGD support
o BIGNUM library bug fixes
o Faster DSA parameter generation
o Enhanced support for Alpha Linux
o Experimental MacOS support
Major changes between OpenSSL 0.9.3 and OpenSSL 0.9.4 [9 Aug 1999]:
o Transparent support for PKCS#8 format private keys: these are used
by several software packages and are more secure than the standard
form
o PKCS#5 v2.0 implementation
o Password callbacks have a new void * argument for application data
o Avoid various memory leaks
o New pipe-like BIO that allows using the SSL library when actual I/O
must be handled by the application (BIO pair)
Major changes between OpenSSL 0.9.2b and OpenSSL 0.9.3 [24 May 1999]:
o Lots of enhancements and cleanups to the Configuration mechanism
o RSA OEAP related fixes
o Added `openssl ca -revoke' option for revoking a certificate
o Source cleanups: const correctness, type-safe stacks and ASN.1 SETs
o Source tree cleanups: removed lots of obsolete files
o Thawte SXNet, certificate policies and CRL distribution points
extension support
o Preliminary (experimental) S/MIME support
o Support for ASN.1 UTF8String and VisibleString
o Full integration of PKCS#12 code
o Sparc assembler bignum implementation, optimized hash functions
o Option to disable selected ciphers
Major changes between OpenSSL 0.9.1c and OpenSSL 0.9.2b [22 Mar 1999]:
o Fixed a security hole related to session resumption
o Fixed RSA encryption routines for the p < q case
o "ALL" in cipher lists now means "everything except NULL ciphers"
o Support for Triple-DES CBCM cipher
o Support of Optimal Asymmetric Encryption Padding (OAEP) for RSA
o First support for new TLSv1 ciphers
o Added a few new BIOs (syslog BIO, reliable BIO)
o Extended support for DSA certificate/keys.
o Extended support for Certificate Signing Requests (CSR)
o Initial support for X.509v3 extensions
o Extended support for compression inside the SSL record layer
o Overhauled Win32 builds
o Cleanups and fixes to the Big Number (BN) library
o Support for ASN.1 GeneralizedTime
o Splitted ASN.1 SETs from SEQUENCEs
o ASN1 and PEM support for Netscape Certificate Sequences
o Overhauled Perl interface
o Lots of source tree cleanups.
o Lots of memory leak fixes.
o Lots of bug fixes.
Major changes between SSLeay 0.9.0b and OpenSSL 0.9.1c [23 Dec 1998]:
o Integration of the popular NO_RSA/NO_DSA patches
o Initial support for compression inside the SSL record layer
o Added BIO proxy and filtering functionality
o Extended Big Number (BN) library
o Added RIPE MD160 message digest
o Addeed support for RC2/64bit cipher
o Extended ASN.1 parser routines
o Adjustations of the source tree for CVS
o Support for various new platforms
diff --git a/README b/README
index 80de6886a766..a0fce3f5f974 100644
--- a/README
+++ b/README
@@ -1,101 +1,101 @@
- OpenSSL 1.0.2n 7 Dec 2017
+ OpenSSL 1.0.2o 27 Mar 2018
Copyright (c) 1998-2015 The OpenSSL Project
Copyright (c) 1995-1998 Eric A. Young, Tim J. Hudson
All rights reserved.
DESCRIPTION
-----------
The OpenSSL Project is a collaborative effort to develop a robust,
commercial-grade, fully featured, and Open Source toolkit implementing the
Secure Sockets Layer (SSLv3) and Transport Layer Security (TLS) protocols as
well as a full-strength general purpose cryptograpic library. The project is
managed by a worldwide community of volunteers that use the Internet to
communicate, plan, and develop the OpenSSL toolkit and its related
documentation.
OpenSSL is descended from the SSLeay library developed by Eric A. Young
and Tim J. Hudson. The OpenSSL toolkit is licensed under a dual-license (the
OpenSSL license plus the SSLeay license), which means that you are free to
get and use it for commercial and non-commercial purposes as long as you
fulfill the conditions of both licenses.
OVERVIEW
--------
The OpenSSL toolkit includes:
libssl.a:
Provides the client and server-side implementations for SSLv3 and TLS.
libcrypto.a:
Provides general cryptographic and X.509 support needed by SSL/TLS but
not logically part of it.
openssl:
A command line tool that can be used for:
Creation of key parameters
Creation of X.509 certificates, CSRs and CRLs
Calculation of message digests
Encryption and decryption
SSL/TLS client and server tests
Handling of S/MIME signed or encrypted mail
And more...
INSTALLATION
------------
See the appropriate file:
INSTALL Linux, Unix, etc.
INSTALL.DJGPP DOS platform with DJGPP
INSTALL.NW Netware
INSTALL.OS2 OS/2
INSTALL.VMS VMS
INSTALL.W32 Windows (32bit)
INSTALL.W64 Windows (64bit)
INSTALL.WCE Windows CE
SUPPORT
-------
See the OpenSSL website www.openssl.org for details on how to obtain
commercial technical support.
If you have any problems with OpenSSL then please take the following steps
first:
- Download the latest version from the repository
to see if the problem has already been addressed
- Configure with no-asm
- Remove compiler optimisation flags
If you wish to report a bug then please include the following information
and create an issue on GitHub:
- On Unix systems:
Self-test report generated by 'make report'
- On other systems:
OpenSSL version: output of 'openssl version -a'
OS Name, Version, Hardware platform
Compiler Details (name, version)
- Application Details (name, version)
- Problem Description (steps that will reproduce the problem, if known)
- Stack Traceback (if the application dumps core)
Just because something doesn't work the way you expect does not mean it
is necessarily a bug in OpenSSL.
HOW TO CONTRIBUTE TO OpenSSL
----------------------------
See CONTRIBUTING
LEGALITIES
----------
A number of nations restrict the use or export of cryptography. If you
are potentially subject to such restrictions you should seek competent
professional legal advice before attempting to develop or distribute
cryptographic code.
diff --git a/apps/app_rand.c b/apps/app_rand.c
index 7f40bba76468..0bbf342e7e1a 100644
--- a/apps/app_rand.c
+++ b/apps/app_rand.c
@@ -1,217 +1,217 @@
/* apps/app_rand.c */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
/* ====================================================================
* Copyright (c) 1998-2000 The OpenSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* openssl-core@openssl.org.
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.openssl.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*
* This product includes cryptographic software written by Eric Young
* (eay@cryptsoft.com). This product includes software written by Tim
* Hudson (tjh@cryptsoft.com).
*
*/
#define NON_MAIN
#include "apps.h"
#undef NON_MAIN
#include <openssl/bio.h>
#include <openssl/rand.h>
static int seeded = 0;
static int egdsocket = 0;
int app_RAND_load_file(const char *file, BIO *bio_e, int dont_warn)
{
int consider_randfile = (file == NULL);
char buffer[200];
#ifdef OPENSSL_SYS_WINDOWS
RAND_screen();
#endif
if (file == NULL)
- file = RAND_file_name(buffer, sizeof buffer);
+ file = RAND_file_name(buffer, sizeof(buffer));
else if (RAND_egd(file) > 0) {
/*
* we try if the given filename is an EGD socket. if it is, we don't
* write anything back to the file.
*/
egdsocket = 1;
return 1;
}
if (file == NULL || !RAND_load_file(file, -1)) {
if (RAND_status() == 0) {
if (!dont_warn) {
BIO_printf(bio_e, "unable to load 'random state'\n");
BIO_printf(bio_e,
"This means that the random number generator has not been seeded\n");
BIO_printf(bio_e, "with much random data.\n");
if (consider_randfile) { /* explanation does not apply when a
* file is explicitly named */
BIO_printf(bio_e,
"Consider setting the RANDFILE environment variable to point at a file that\n");
BIO_printf(bio_e,
"'random' data can be kept in (the file will be overwritten).\n");
}
}
return 0;
}
}
seeded = 1;
return 1;
}
long app_RAND_load_files(char *name)
{
char *p, *n;
int last;
long tot = 0;
int egd;
for (;;) {
last = 0;
for (p = name; ((*p != '\0') && (*p != LIST_SEPARATOR_CHAR)); p++) ;
if (*p == '\0')
last = 1;
*p = '\0';
n = name;
name = p + 1;
if (*n == '\0')
break;
egd = RAND_egd(n);
if (egd > 0)
tot += egd;
else
tot += RAND_load_file(n, -1);
if (last)
break;
}
if (tot > 512)
app_RAND_allow_write_file();
return (tot);
}
int app_RAND_write_file(const char *file, BIO *bio_e)
{
char buffer[200];
if (egdsocket || !seeded)
/*
* If we did not manage to read the seed file, we should not write a
* low-entropy seed file back -- it would suppress a crucial warning
* the next time we want to use it.
*/
return 0;
if (file == NULL)
- file = RAND_file_name(buffer, sizeof buffer);
+ file = RAND_file_name(buffer, sizeof(buffer));
if (file == NULL || !RAND_write_file(file)) {
BIO_printf(bio_e, "unable to write 'random state'\n");
return 0;
}
return 1;
}
void app_RAND_allow_write_file(void)
{
seeded = 1;
}
diff --git a/apps/apps.c b/apps/apps.c
index 29de1b75dd60..c5a515229556 100644
--- a/apps/apps.c
+++ b/apps/apps.c
@@ -1,3283 +1,3283 @@
/* apps/apps.c */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
/* ====================================================================
* Copyright (c) 1998-2001 The OpenSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* openssl-core@openssl.org.
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.openssl.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*
* This product includes cryptographic software written by Eric Young
* (eay@cryptsoft.com). This product includes software written by Tim
* Hudson (tjh@cryptsoft.com).
*
*/
#if !defined(_POSIX_C_SOURCE) && defined(OPENSSL_SYS_VMS)
/*
* On VMS, you need to define this to get the declaration of fileno(). The
* value 2 is to make sure no function defined in POSIX-2 is left undefined.
*/
# define _POSIX_C_SOURCE 2
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <ctype.h>
#include <errno.h>
#include <assert.h>
#include <openssl/err.h>
#include <openssl/x509.h>
#include <openssl/x509v3.h>
#include <openssl/pem.h>
#include <openssl/pkcs12.h>
#include <openssl/ui.h>
#include <openssl/safestack.h>
#ifndef OPENSSL_NO_ENGINE
# include <openssl/engine.h>
#endif
#ifndef OPENSSL_NO_RSA
# include <openssl/rsa.h>
#endif
#include <openssl/bn.h>
#ifndef OPENSSL_NO_JPAKE
# include <openssl/jpake.h>
#endif
#define NON_MAIN
#include "apps.h"
#undef NON_MAIN
#ifdef _WIN32
static int WIN32_rename(const char *from, const char *to);
# define rename(from,to) WIN32_rename((from),(to))
# ifdef fileno
# undef fileno
# endif
# define fileno(a) (int)_fileno(a)
#endif
typedef struct {
const char *name;
unsigned long flag;
unsigned long mask;
} NAME_EX_TBL;
static UI_METHOD *ui_method = NULL;
static int set_table_opts(unsigned long *flags, const char *arg,
const NAME_EX_TBL * in_tbl);
static int set_multi_opts(unsigned long *flags, const char *arg,
const NAME_EX_TBL * in_tbl);
#if !defined(OPENSSL_NO_RC4) && !defined(OPENSSL_NO_RSA)
/* Looks like this stuff is worth moving into separate function */
static EVP_PKEY *load_netscape_key(BIO *err, BIO *key, const char *file,
const char *key_descrip, int format);
#endif
int app_init(long mesgwin);
#ifdef undef /* never finished - probably never will be
* :-) */
int args_from_file(char *file, int *argc, char **argv[])
{
FILE *fp;
int num, i;
unsigned int len;
static char *buf = NULL;
static char **arg = NULL;
char *p;
fp = fopen(file, "r");
if (fp == NULL)
return (0);
if (fseek(fp, 0, SEEK_END) == 0)
len = ftell(fp), rewind(fp);
else
len = -1;
if (len <= 0) {
fclose(fp);
return (0);
}
*argc = 0;
*argv = NULL;
if (buf != NULL)
OPENSSL_free(buf);
buf = (char *)OPENSSL_malloc(len + 1);
if (buf == NULL)
return (0);
len = fread(buf, 1, len, fp);
if (len <= 1)
return (0);
buf[len] = '\0';
i = 0;
for (p = buf; *p; p++)
if (*p == '\n')
i++;
if (arg != NULL)
OPENSSL_free(arg);
arg = (char **)OPENSSL_malloc(sizeof(char *) * (i * 2));
if (arg == NULL)
return 0;
*argv = arg;
num = 0;
p = buf;
for (;;) {
if (!*p)
break;
if (*p == '#') { /* comment line */
while (*p && (*p != '\n'))
p++;
continue;
}
/* else we have a line */
*(arg++) = p;
num++;
while (*p && ((*p != ' ') && (*p != '\t') && (*p != '\n')))
p++;
if (!*p)
break;
if (*p == '\n') {
*(p++) = '\0';
continue;
}
/* else it is a tab or space */
p++;
while (*p && ((*p == ' ') || (*p == '\t') || (*p == '\n')))
p++;
if (!*p)
break;
if (*p == '\n') {
p++;
continue;
}
*(arg++) = p++;
num++;
while (*p && (*p != '\n'))
p++;
if (!*p)
break;
/* else *p == '\n' */
*(p++) = '\0';
}
*argc = num;
return (1);
}
#endif
int str2fmt(char *s)
{
if (s == NULL)
return FORMAT_UNDEF;
if ((*s == 'D') || (*s == 'd'))
return (FORMAT_ASN1);
else if ((*s == 'T') || (*s == 't'))
return (FORMAT_TEXT);
else if ((*s == 'N') || (*s == 'n'))
return (FORMAT_NETSCAPE);
else if ((*s == 'S') || (*s == 's'))
return (FORMAT_SMIME);
else if ((*s == 'M') || (*s == 'm'))
return (FORMAT_MSBLOB);
else if ((*s == '1')
|| (strcmp(s, "PKCS12") == 0) || (strcmp(s, "pkcs12") == 0)
|| (strcmp(s, "P12") == 0) || (strcmp(s, "p12") == 0))
return (FORMAT_PKCS12);
else if ((*s == 'E') || (*s == 'e'))
return (FORMAT_ENGINE);
else if ((*s == 'H') || (*s == 'h'))
return FORMAT_HTTP;
else if ((*s == 'P') || (*s == 'p')) {
if (s[1] == 'V' || s[1] == 'v')
return FORMAT_PVK;
else
return (FORMAT_PEM);
} else
return (FORMAT_UNDEF);
}
#if defined(OPENSSL_SYS_MSDOS) || defined(OPENSSL_SYS_WIN32) || defined(OPENSSL_SYS_WIN16) || defined(OPENSSL_SYS_NETWARE)
void program_name(char *in, char *out, int size)
{
int i, n;
char *p = NULL;
n = strlen(in);
/* find the last '/', '\' or ':' */
for (i = n - 1; i > 0; i--) {
if ((in[i] == '/') || (in[i] == '\\') || (in[i] == ':')) {
p = &(in[i + 1]);
break;
}
}
if (p == NULL)
p = in;
n = strlen(p);
# if defined(OPENSSL_SYS_NETWARE)
/* strip off trailing .nlm if present. */
if ((n > 4) && (p[n - 4] == '.') &&
((p[n - 3] == 'n') || (p[n - 3] == 'N')) &&
((p[n - 2] == 'l') || (p[n - 2] == 'L')) &&
((p[n - 1] == 'm') || (p[n - 1] == 'M')))
n -= 4;
# else
/* strip off trailing .exe if present. */
if ((n > 4) && (p[n - 4] == '.') &&
((p[n - 3] == 'e') || (p[n - 3] == 'E')) &&
((p[n - 2] == 'x') || (p[n - 2] == 'X')) &&
((p[n - 1] == 'e') || (p[n - 1] == 'E')))
n -= 4;
# endif
if (n > size - 1)
n = size - 1;
for (i = 0; i < n; i++) {
if ((p[i] >= 'A') && (p[i] <= 'Z'))
out[i] = p[i] - 'A' + 'a';
else
out[i] = p[i];
}
out[n] = '\0';
}
#else
# ifdef OPENSSL_SYS_VMS
void program_name(char *in, char *out, int size)
{
char *p = in, *q;
char *chars = ":]>";
while (*chars != '\0') {
q = strrchr(p, *chars);
if (q > p)
p = q + 1;
chars++;
}
q = strrchr(p, '.');
if (q == NULL)
q = p + strlen(p);
strncpy(out, p, size - 1);
if (q - p >= size) {
out[size - 1] = '\0';
} else {
out[q - p] = '\0';
}
}
# else
void program_name(char *in, char *out, int size)
{
char *p;
p = strrchr(in, '/');
if (p != NULL)
p++;
else
p = in;
BUF_strlcpy(out, p, size);
}
# endif
#endif
int chopup_args(ARGS *arg, char *buf, int *argc, char **argv[])
{
int num, i;
char *p;
*argc = 0;
*argv = NULL;
i = 0;
if (arg->count == 0) {
arg->count = 20;
arg->data = (char **)OPENSSL_malloc(sizeof(char *) * arg->count);
if (arg->data == NULL)
return 0;
}
for (i = 0; i < arg->count; i++)
arg->data[i] = NULL;
num = 0;
p = buf;
for (;;) {
/* first scan over white space */
if (!*p)
break;
while (*p && ((*p == ' ') || (*p == '\t') || (*p == '\n')))
p++;
if (!*p)
break;
/* The start of something good :-) */
if (num >= arg->count) {
char **tmp_p;
int tlen = arg->count + 20;
tmp_p = (char **)OPENSSL_realloc(arg->data,
sizeof(char *) * tlen);
if (tmp_p == NULL)
return 0;
arg->data = tmp_p;
arg->count = tlen;
/* initialize newly allocated data */
for (i = num; i < arg->count; i++)
arg->data[i] = NULL;
}
arg->data[num++] = p;
/* now look for the end of this */
if ((*p == '\'') || (*p == '\"')) { /* scan for closing quote */
i = *(p++);
arg->data[num - 1]++; /* jump over quote */
while (*p && (*p != i))
p++;
*p = '\0';
} else {
while (*p && ((*p != ' ') && (*p != '\t') && (*p != '\n')))
p++;
if (*p == '\0')
p--;
else
*p = '\0';
}
p++;
}
*argc = num;
*argv = arg->data;
return (1);
}
#ifndef APP_INIT
int app_init(long mesgwin)
{
return (1);
}
#endif
int dump_cert_text(BIO *out, X509 *x)
{
char *p;
p = X509_NAME_oneline(X509_get_subject_name(x), NULL, 0);
BIO_puts(out, "subject=");
BIO_puts(out, p);
OPENSSL_free(p);
p = X509_NAME_oneline(X509_get_issuer_name(x), NULL, 0);
BIO_puts(out, "\nissuer=");
BIO_puts(out, p);
BIO_puts(out, "\n");
OPENSSL_free(p);
return 0;
}
static int ui_open(UI *ui)
{
return UI_method_get_opener(UI_OpenSSL())(ui);
}
static int ui_read(UI *ui, UI_STRING *uis)
{
if (UI_get_input_flags(uis) & UI_INPUT_FLAG_DEFAULT_PWD
&& UI_get0_user_data(ui)) {
switch (UI_get_string_type(uis)) {
case UIT_PROMPT:
case UIT_VERIFY:
{
const char *password =
((PW_CB_DATA *)UI_get0_user_data(ui))->password;
if (password && password[0] != '\0') {
UI_set_result(ui, uis, password);
return 1;
}
}
default:
break;
}
}
return UI_method_get_reader(UI_OpenSSL())(ui, uis);
}
static int ui_write(UI *ui, UI_STRING *uis)
{
if (UI_get_input_flags(uis) & UI_INPUT_FLAG_DEFAULT_PWD
&& UI_get0_user_data(ui)) {
switch (UI_get_string_type(uis)) {
case UIT_PROMPT:
case UIT_VERIFY:
{
const char *password =
((PW_CB_DATA *)UI_get0_user_data(ui))->password;
if (password && password[0] != '\0')
return 1;
}
default:
break;
}
}
return UI_method_get_writer(UI_OpenSSL())(ui, uis);
}
static int ui_close(UI *ui)
{
return UI_method_get_closer(UI_OpenSSL())(ui);
}
int setup_ui_method(void)
{
ui_method = UI_create_method("OpenSSL application user interface");
UI_method_set_opener(ui_method, ui_open);
UI_method_set_reader(ui_method, ui_read);
UI_method_set_writer(ui_method, ui_write);
UI_method_set_closer(ui_method, ui_close);
return 0;
}
void destroy_ui_method(void)
{
if (ui_method) {
UI_destroy_method(ui_method);
ui_method = NULL;
}
}
int password_callback(char *buf, int bufsiz, int verify, PW_CB_DATA *cb_tmp)
{
UI *ui = NULL;
int res = 0;
const char *prompt_info = NULL;
const char *password = NULL;
PW_CB_DATA *cb_data = (PW_CB_DATA *)cb_tmp;
if (cb_data) {
if (cb_data->password)
password = cb_data->password;
if (cb_data->prompt_info)
prompt_info = cb_data->prompt_info;
}
if (password) {
res = strlen(password);
if (res > bufsiz)
res = bufsiz;
memcpy(buf, password, res);
return res;
}
ui = UI_new_method(ui_method);
if (ui) {
int ok = 0;
char *buff = NULL;
int ui_flags = 0;
char *prompt = NULL;
prompt = UI_construct_prompt(ui, "pass phrase", prompt_info);
if (!prompt) {
BIO_printf(bio_err, "Out of memory\n");
UI_free(ui);
return 0;
}
ui_flags |= UI_INPUT_FLAG_DEFAULT_PWD;
UI_ctrl(ui, UI_CTRL_PRINT_ERRORS, 1, 0, 0);
if (ok >= 0)
ok = UI_add_input_string(ui, prompt, ui_flags, buf,
PW_MIN_LENGTH, bufsiz - 1);
if (ok >= 0 && verify) {
buff = (char *)OPENSSL_malloc(bufsiz);
if (!buff) {
BIO_printf(bio_err, "Out of memory\n");
UI_free(ui);
OPENSSL_free(prompt);
return 0;
}
ok = UI_add_verify_string(ui, prompt, ui_flags, buff,
PW_MIN_LENGTH, bufsiz - 1, buf);
}
if (ok >= 0)
do {
ok = UI_process(ui);
}
while (ok < 0 && UI_ctrl(ui, UI_CTRL_IS_REDOABLE, 0, 0, 0));
if (buff) {
OPENSSL_cleanse(buff, (unsigned int)bufsiz);
OPENSSL_free(buff);
}
if (ok >= 0)
res = strlen(buf);
if (ok == -1) {
BIO_printf(bio_err, "User interface error\n");
ERR_print_errors(bio_err);
OPENSSL_cleanse(buf, (unsigned int)bufsiz);
res = 0;
}
if (ok == -2) {
BIO_printf(bio_err, "aborted!\n");
OPENSSL_cleanse(buf, (unsigned int)bufsiz);
res = 0;
}
UI_free(ui);
OPENSSL_free(prompt);
}
return res;
}
static char *app_get_pass(BIO *err, char *arg, int keepbio);
int app_passwd(BIO *err, char *arg1, char *arg2, char **pass1, char **pass2)
{
int same;
if (!arg2 || !arg1 || strcmp(arg1, arg2))
same = 0;
else
same = 1;
if (arg1) {
*pass1 = app_get_pass(err, arg1, same);
if (!*pass1)
return 0;
} else if (pass1)
*pass1 = NULL;
if (arg2) {
*pass2 = app_get_pass(err, arg2, same ? 2 : 0);
if (!*pass2)
return 0;
} else if (pass2)
*pass2 = NULL;
return 1;
}
static char *app_get_pass(BIO *err, char *arg, int keepbio)
{
char *tmp, tpass[APP_PASS_LEN];
static BIO *pwdbio = NULL;
int i;
if (!strncmp(arg, "pass:", 5))
return BUF_strdup(arg + 5);
if (!strncmp(arg, "env:", 4)) {
tmp = getenv(arg + 4);
if (!tmp) {
BIO_printf(err, "Can't read environment variable %s\n", arg + 4);
return NULL;
}
return BUF_strdup(tmp);
}
if (!keepbio || !pwdbio) {
if (!strncmp(arg, "file:", 5)) {
pwdbio = BIO_new_file(arg + 5, "r");
if (!pwdbio) {
BIO_printf(err, "Can't open file %s\n", arg + 5);
return NULL;
}
#if !defined(_WIN32)
/*
* Under _WIN32, which covers even Win64 and CE, file
* descriptors referenced by BIO_s_fd are not inherited
* by child process and therefore below is not an option.
* It could have been an option if bss_fd.c was operating
* on real Windows descriptors, such as those obtained
* with CreateFile.
*/
} else if (!strncmp(arg, "fd:", 3)) {
BIO *btmp;
i = atoi(arg + 3);
if (i >= 0)
pwdbio = BIO_new_fd(i, BIO_NOCLOSE);
if ((i < 0) || !pwdbio) {
BIO_printf(err, "Can't access file descriptor %s\n", arg + 3);
return NULL;
}
/*
* Can't do BIO_gets on an fd BIO so add a buffering BIO
*/
btmp = BIO_new(BIO_f_buffer());
pwdbio = BIO_push(btmp, pwdbio);
#endif
} else if (!strcmp(arg, "stdin")) {
pwdbio = BIO_new_fp(stdin, BIO_NOCLOSE);
if (!pwdbio) {
BIO_printf(err, "Can't open BIO for stdin\n");
return NULL;
}
} else {
BIO_printf(err, "Invalid password argument \"%s\"\n", arg);
return NULL;
}
}
i = BIO_gets(pwdbio, tpass, APP_PASS_LEN);
if (keepbio != 1) {
BIO_free_all(pwdbio);
pwdbio = NULL;
}
if (i <= 0) {
BIO_printf(err, "Error reading password from BIO\n");
return NULL;
}
tmp = strchr(tpass, '\n');
if (tmp)
*tmp = 0;
return BUF_strdup(tpass);
}
int add_oid_section(BIO *err, CONF *conf)
{
char *p;
STACK_OF(CONF_VALUE) *sktmp;
CONF_VALUE *cnf;
int i;
if (!(p = NCONF_get_string(conf, NULL, "oid_section"))) {
ERR_clear_error();
return 1;
}
if (!(sktmp = NCONF_get_section(conf, p))) {
BIO_printf(err, "problem loading oid section %s\n", p);
return 0;
}
for (i = 0; i < sk_CONF_VALUE_num(sktmp); i++) {
cnf = sk_CONF_VALUE_value(sktmp, i);
if (OBJ_create(cnf->value, cnf->name, cnf->name) == NID_undef) {
BIO_printf(err, "problem creating object %s=%s\n",
cnf->name, cnf->value);
return 0;
}
}
return 1;
}
static int load_pkcs12(BIO *err, BIO *in, const char *desc,
pem_password_cb *pem_cb, void *cb_data,
EVP_PKEY **pkey, X509 **cert, STACK_OF(X509) **ca)
{
const char *pass;
char tpass[PEM_BUFSIZE];
int len, ret = 0;
PKCS12 *p12;
p12 = d2i_PKCS12_bio(in, NULL);
if (p12 == NULL) {
BIO_printf(err, "Error loading PKCS12 file for %s\n", desc);
goto die;
}
/* See if an empty password will do */
if (PKCS12_verify_mac(p12, "", 0) || PKCS12_verify_mac(p12, NULL, 0))
pass = "";
else {
if (!pem_cb)
pem_cb = (pem_password_cb *)password_callback;
len = pem_cb(tpass, PEM_BUFSIZE, 0, cb_data);
if (len < 0) {
BIO_printf(err, "Passpharse callback error for %s\n", desc);
goto die;
}
if (len < PEM_BUFSIZE)
tpass[len] = 0;
if (!PKCS12_verify_mac(p12, tpass, len)) {
BIO_printf(err,
"Mac verify error (wrong password?) in PKCS12 file for %s\n",
desc);
goto die;
}
pass = tpass;
}
ret = PKCS12_parse(p12, pass, pkey, cert, ca);
die:
if (p12)
PKCS12_free(p12);
return ret;
}
int load_cert_crl_http(const char *url, BIO *err,
X509 **pcert, X509_CRL **pcrl)
{
char *host = NULL, *port = NULL, *path = NULL;
BIO *bio = NULL;
OCSP_REQ_CTX *rctx = NULL;
int use_ssl, rv = 0;
if (!OCSP_parse_url(url, &host, &port, &path, &use_ssl))
goto err;
if (use_ssl) {
if (err)
BIO_puts(err, "https not supported\n");
goto err;
}
bio = BIO_new_connect(host);
if (!bio || !BIO_set_conn_port(bio, port))
goto err;
rctx = OCSP_REQ_CTX_new(bio, 1024);
if (!rctx)
goto err;
if (!OCSP_REQ_CTX_http(rctx, "GET", path))
goto err;
if (!OCSP_REQ_CTX_add1_header(rctx, "Host", host))
goto err;
if (pcert) {
do {
rv = X509_http_nbio(rctx, pcert);
}
while (rv == -1);
} else {
do {
rv = X509_CRL_http_nbio(rctx, pcrl);
} while (rv == -1);
}
err:
if (host)
OPENSSL_free(host);
if (path)
OPENSSL_free(path);
if (port)
OPENSSL_free(port);
if (bio)
BIO_free_all(bio);
if (rctx)
OCSP_REQ_CTX_free(rctx);
if (rv != 1) {
if (bio && err)
BIO_printf(bio_err, "Error loading %s from %s\n",
pcert ? "certificate" : "CRL", url);
ERR_print_errors(bio_err);
}
return rv;
}
X509 *load_cert(BIO *err, const char *file, int format,
const char *pass, ENGINE *e, const char *cert_descrip)
{
X509 *x = NULL;
BIO *cert;
if (format == FORMAT_HTTP) {
load_cert_crl_http(file, err, &x, NULL);
return x;
}
if ((cert = BIO_new(BIO_s_file())) == NULL) {
ERR_print_errors(err);
goto end;
}
if (file == NULL) {
#ifdef _IONBF
# ifndef OPENSSL_NO_SETVBUF_IONBF
setvbuf(stdin, NULL, _IONBF, 0);
# endif /* ndef OPENSSL_NO_SETVBUF_IONBF */
#endif
BIO_set_fp(cert, stdin, BIO_NOCLOSE);
} else {
if (BIO_read_filename(cert, file) <= 0) {
BIO_printf(err, "Error opening %s %s\n", cert_descrip, file);
ERR_print_errors(err);
goto end;
}
}
if (format == FORMAT_ASN1)
x = d2i_X509_bio(cert, NULL);
else if (format == FORMAT_NETSCAPE) {
NETSCAPE_X509 *nx;
nx = ASN1_item_d2i_bio(ASN1_ITEM_rptr(NETSCAPE_X509), cert, NULL);
if (nx == NULL)
goto end;
if ((strncmp(NETSCAPE_CERT_HDR, (char *)nx->header->data,
nx->header->length) != 0)) {
NETSCAPE_X509_free(nx);
BIO_printf(err, "Error reading header on certificate\n");
goto end;
}
x = nx->cert;
nx->cert = NULL;
NETSCAPE_X509_free(nx);
} else if (format == FORMAT_PEM)
x = PEM_read_bio_X509_AUX(cert, NULL,
(pem_password_cb *)password_callback, NULL);
else if (format == FORMAT_PKCS12) {
if (!load_pkcs12(err, cert, cert_descrip, NULL, NULL, NULL, &x, NULL))
goto end;
} else {
BIO_printf(err, "bad input format specified for %s\n", cert_descrip);
goto end;
}
end:
if (x == NULL) {
BIO_printf(err, "unable to load certificate\n");
ERR_print_errors(err);
}
if (cert != NULL)
BIO_free(cert);
return (x);
}
X509_CRL *load_crl(const char *infile, int format)
{
X509_CRL *x = NULL;
BIO *in = NULL;
if (format == FORMAT_HTTP) {
load_cert_crl_http(infile, bio_err, NULL, &x);
return x;
}
in = BIO_new(BIO_s_file());
if (in == NULL) {
ERR_print_errors(bio_err);
goto end;
}
if (infile == NULL)
BIO_set_fp(in, stdin, BIO_NOCLOSE);
else {
if (BIO_read_filename(in, infile) <= 0) {
perror(infile);
goto end;
}
}
if (format == FORMAT_ASN1)
x = d2i_X509_CRL_bio(in, NULL);
else if (format == FORMAT_PEM)
x = PEM_read_bio_X509_CRL(in, NULL, NULL, NULL);
else {
BIO_printf(bio_err, "bad input format specified for input crl\n");
goto end;
}
if (x == NULL) {
BIO_printf(bio_err, "unable to load CRL\n");
ERR_print_errors(bio_err);
goto end;
}
end:
BIO_free(in);
return (x);
}
EVP_PKEY *load_key(BIO *err, const char *file, int format, int maybe_stdin,
const char *pass, ENGINE *e, const char *key_descrip)
{
BIO *key = NULL;
EVP_PKEY *pkey = NULL;
PW_CB_DATA cb_data;
cb_data.password = pass;
cb_data.prompt_info = file;
if (file == NULL && (!maybe_stdin || format == FORMAT_ENGINE)) {
BIO_printf(err, "no keyfile specified\n");
goto end;
}
#ifndef OPENSSL_NO_ENGINE
if (format == FORMAT_ENGINE) {
if (!e)
BIO_printf(err, "no engine specified\n");
else {
if (ENGINE_init(e)) {
pkey = ENGINE_load_private_key(e, file, ui_method, &cb_data);
ENGINE_finish(e);
}
if (!pkey) {
BIO_printf(err, "cannot load %s from engine\n", key_descrip);
ERR_print_errors(err);
}
}
goto end;
}
#endif
key = BIO_new(BIO_s_file());
if (key == NULL) {
ERR_print_errors(err);
goto end;
}
if (file == NULL && maybe_stdin) {
#ifdef _IONBF
# ifndef OPENSSL_NO_SETVBUF_IONBF
setvbuf(stdin, NULL, _IONBF, 0);
# endif /* ndef OPENSSL_NO_SETVBUF_IONBF */
#endif
BIO_set_fp(key, stdin, BIO_NOCLOSE);
} else if (BIO_read_filename(key, file) <= 0) {
BIO_printf(err, "Error opening %s %s\n", key_descrip, file);
ERR_print_errors(err);
goto end;
}
if (format == FORMAT_ASN1) {
pkey = d2i_PrivateKey_bio(key, NULL);
} else if (format == FORMAT_PEM) {
pkey = PEM_read_bio_PrivateKey(key, NULL,
(pem_password_cb *)password_callback,
&cb_data);
}
#if !defined(OPENSSL_NO_RC4) && !defined(OPENSSL_NO_RSA)
else if (format == FORMAT_NETSCAPE || format == FORMAT_IISSGC)
pkey = load_netscape_key(err, key, file, key_descrip, format);
#endif
else if (format == FORMAT_PKCS12) {
if (!load_pkcs12(err, key, key_descrip,
(pem_password_cb *)password_callback, &cb_data,
&pkey, NULL, NULL))
goto end;
}
#if !defined(OPENSSL_NO_RSA) && !defined(OPENSSL_NO_DSA) && !defined (OPENSSL_NO_RC4)
else if (format == FORMAT_MSBLOB)
pkey = b2i_PrivateKey_bio(key);
else if (format == FORMAT_PVK)
pkey = b2i_PVK_bio(key, (pem_password_cb *)password_callback,
&cb_data);
#endif
else {
BIO_printf(err, "bad input format specified for key file\n");
goto end;
}
end:
if (key != NULL)
BIO_free(key);
if (pkey == NULL) {
BIO_printf(err, "unable to load %s\n", key_descrip);
ERR_print_errors(err);
}
return (pkey);
}
EVP_PKEY *load_pubkey(BIO *err, const char *file, int format, int maybe_stdin,
const char *pass, ENGINE *e, const char *key_descrip)
{
BIO *key = NULL;
EVP_PKEY *pkey = NULL;
PW_CB_DATA cb_data;
cb_data.password = pass;
cb_data.prompt_info = file;
if (file == NULL && (!maybe_stdin || format == FORMAT_ENGINE)) {
BIO_printf(err, "no keyfile specified\n");
goto end;
}
#ifndef OPENSSL_NO_ENGINE
if (format == FORMAT_ENGINE) {
if (!e)
BIO_printf(bio_err, "no engine specified\n");
else
pkey = ENGINE_load_public_key(e, file, ui_method, &cb_data);
goto end;
}
#endif
key = BIO_new(BIO_s_file());
if (key == NULL) {
ERR_print_errors(err);
goto end;
}
if (file == NULL && maybe_stdin) {
#ifdef _IONBF
# ifndef OPENSSL_NO_SETVBUF_IONBF
setvbuf(stdin, NULL, _IONBF, 0);
# endif /* ndef OPENSSL_NO_SETVBUF_IONBF */
#endif
BIO_set_fp(key, stdin, BIO_NOCLOSE);
} else if (BIO_read_filename(key, file) <= 0) {
BIO_printf(err, "Error opening %s %s\n", key_descrip, file);
ERR_print_errors(err);
goto end;
}
if (format == FORMAT_ASN1) {
pkey = d2i_PUBKEY_bio(key, NULL);
}
#ifndef OPENSSL_NO_RSA
else if (format == FORMAT_ASN1RSA) {
RSA *rsa;
rsa = d2i_RSAPublicKey_bio(key, NULL);
if (rsa) {
pkey = EVP_PKEY_new();
if (pkey)
EVP_PKEY_set1_RSA(pkey, rsa);
RSA_free(rsa);
} else
pkey = NULL;
} else if (format == FORMAT_PEMRSA) {
RSA *rsa;
rsa = PEM_read_bio_RSAPublicKey(key, NULL,
(pem_password_cb *)password_callback,
&cb_data);
if (rsa) {
pkey = EVP_PKEY_new();
if (pkey)
EVP_PKEY_set1_RSA(pkey, rsa);
RSA_free(rsa);
} else
pkey = NULL;
}
#endif
else if (format == FORMAT_PEM) {
pkey = PEM_read_bio_PUBKEY(key, NULL,
(pem_password_cb *)password_callback,
&cb_data);
}
#if !defined(OPENSSL_NO_RC4) && !defined(OPENSSL_NO_RSA)
else if (format == FORMAT_NETSCAPE || format == FORMAT_IISSGC)
pkey = load_netscape_key(err, key, file, key_descrip, format);
#endif
#if !defined(OPENSSL_NO_RSA) && !defined(OPENSSL_NO_DSA)
else if (format == FORMAT_MSBLOB)
pkey = b2i_PublicKey_bio(key);
#endif
else {
BIO_printf(err, "bad input format specified for key file\n");
goto end;
}
end:
if (key != NULL)
BIO_free(key);
if (pkey == NULL)
BIO_printf(err, "unable to load %s\n", key_descrip);
return (pkey);
}
#if !defined(OPENSSL_NO_RC4) && !defined(OPENSSL_NO_RSA)
static EVP_PKEY *load_netscape_key(BIO *err, BIO *key, const char *file,
const char *key_descrip, int format)
{
EVP_PKEY *pkey;
BUF_MEM *buf;
RSA *rsa;
const unsigned char *p;
int size, i;
buf = BUF_MEM_new();
pkey = EVP_PKEY_new();
size = 0;
if (buf == NULL || pkey == NULL)
goto error;
for (;;) {
if (!BUF_MEM_grow_clean(buf, size + 1024 * 10))
goto error;
i = BIO_read(key, &(buf->data[size]), 1024 * 10);
size += i;
if (i == 0)
break;
if (i < 0) {
BIO_printf(err, "Error reading %s %s", key_descrip, file);
goto error;
}
}
p = (unsigned char *)buf->data;
rsa = d2i_RSA_NET(NULL, &p, (long)size, NULL,
(format == FORMAT_IISSGC ? 1 : 0));
if (rsa == NULL)
goto error;
BUF_MEM_free(buf);
EVP_PKEY_set1_RSA(pkey, rsa);
return pkey;
error:
BUF_MEM_free(buf);
EVP_PKEY_free(pkey);
return NULL;
}
#endif /* ndef OPENSSL_NO_RC4 */
static int load_certs_crls(BIO *err, const char *file, int format,
const char *pass, ENGINE *e, const char *desc,
STACK_OF(X509) **pcerts,
STACK_OF(X509_CRL) **pcrls)
{
int i;
BIO *bio;
STACK_OF(X509_INFO) *xis = NULL;
X509_INFO *xi;
PW_CB_DATA cb_data;
int rv = 0;
cb_data.password = pass;
cb_data.prompt_info = file;
if (format != FORMAT_PEM) {
BIO_printf(err, "bad input format specified for %s\n", desc);
return 0;
}
if (file == NULL)
bio = BIO_new_fp(stdin, BIO_NOCLOSE);
else
bio = BIO_new_file(file, "r");
if (bio == NULL) {
BIO_printf(err, "Error opening %s %s\n", desc, file ? file : "stdin");
ERR_print_errors(err);
return 0;
}
xis = PEM_X509_INFO_read_bio(bio, NULL,
(pem_password_cb *)password_callback,
&cb_data);
BIO_free(bio);
if (pcerts) {
*pcerts = sk_X509_new_null();
if (!*pcerts)
goto end;
}
if (pcrls) {
*pcrls = sk_X509_CRL_new_null();
if (!*pcrls)
goto end;
}
for (i = 0; i < sk_X509_INFO_num(xis); i++) {
xi = sk_X509_INFO_value(xis, i);
if (xi->x509 && pcerts) {
if (!sk_X509_push(*pcerts, xi->x509))
goto end;
xi->x509 = NULL;
}
if (xi->crl && pcrls) {
if (!sk_X509_CRL_push(*pcrls, xi->crl))
goto end;
xi->crl = NULL;
}
}
if (pcerts && sk_X509_num(*pcerts) > 0)
rv = 1;
if (pcrls && sk_X509_CRL_num(*pcrls) > 0)
rv = 1;
end:
if (xis)
sk_X509_INFO_pop_free(xis, X509_INFO_free);
if (rv == 0) {
if (pcerts) {
sk_X509_pop_free(*pcerts, X509_free);
*pcerts = NULL;
}
if (pcrls) {
sk_X509_CRL_pop_free(*pcrls, X509_CRL_free);
*pcrls = NULL;
}
BIO_printf(err, "unable to load %s\n",
pcerts ? "certificates" : "CRLs");
ERR_print_errors(err);
}
return rv;
}
STACK_OF(X509) *load_certs(BIO *err, const char *file, int format,
const char *pass, ENGINE *e, const char *desc)
{
STACK_OF(X509) *certs;
if (!load_certs_crls(err, file, format, pass, e, desc, &certs, NULL))
return NULL;
return certs;
}
STACK_OF(X509_CRL) *load_crls(BIO *err, const char *file, int format,
const char *pass, ENGINE *e, const char *desc)
{
STACK_OF(X509_CRL) *crls;
if (!load_certs_crls(err, file, format, pass, e, desc, NULL, &crls))
return NULL;
return crls;
}
#define X509V3_EXT_UNKNOWN_MASK (0xfL << 16)
/* Return error for unknown extensions */
#define X509V3_EXT_DEFAULT 0
/* Print error for unknown extensions */
#define X509V3_EXT_ERROR_UNKNOWN (1L << 16)
/* ASN1 parse unknown extensions */
#define X509V3_EXT_PARSE_UNKNOWN (2L << 16)
/* BIO_dump unknown extensions */
#define X509V3_EXT_DUMP_UNKNOWN (3L << 16)
#define X509_FLAG_CA (X509_FLAG_NO_ISSUER | X509_FLAG_NO_PUBKEY | \
X509_FLAG_NO_HEADER | X509_FLAG_NO_VERSION)
int set_cert_ex(unsigned long *flags, const char *arg)
{
static const NAME_EX_TBL cert_tbl[] = {
{"compatible", X509_FLAG_COMPAT, 0xffffffffl},
{"ca_default", X509_FLAG_CA, 0xffffffffl},
{"no_header", X509_FLAG_NO_HEADER, 0},
{"no_version", X509_FLAG_NO_VERSION, 0},
{"no_serial", X509_FLAG_NO_SERIAL, 0},
{"no_signame", X509_FLAG_NO_SIGNAME, 0},
{"no_validity", X509_FLAG_NO_VALIDITY, 0},
{"no_subject", X509_FLAG_NO_SUBJECT, 0},
{"no_issuer", X509_FLAG_NO_ISSUER, 0},
{"no_pubkey", X509_FLAG_NO_PUBKEY, 0},
{"no_extensions", X509_FLAG_NO_EXTENSIONS, 0},
{"no_sigdump", X509_FLAG_NO_SIGDUMP, 0},
{"no_aux", X509_FLAG_NO_AUX, 0},
{"no_attributes", X509_FLAG_NO_ATTRIBUTES, 0},
{"ext_default", X509V3_EXT_DEFAULT, X509V3_EXT_UNKNOWN_MASK},
{"ext_error", X509V3_EXT_ERROR_UNKNOWN, X509V3_EXT_UNKNOWN_MASK},
{"ext_parse", X509V3_EXT_PARSE_UNKNOWN, X509V3_EXT_UNKNOWN_MASK},
{"ext_dump", X509V3_EXT_DUMP_UNKNOWN, X509V3_EXT_UNKNOWN_MASK},
{NULL, 0, 0}
};
return set_multi_opts(flags, arg, cert_tbl);
}
int set_name_ex(unsigned long *flags, const char *arg)
{
static const NAME_EX_TBL ex_tbl[] = {
{"esc_2253", ASN1_STRFLGS_ESC_2253, 0},
{"esc_ctrl", ASN1_STRFLGS_ESC_CTRL, 0},
{"esc_msb", ASN1_STRFLGS_ESC_MSB, 0},
{"use_quote", ASN1_STRFLGS_ESC_QUOTE, 0},
{"utf8", ASN1_STRFLGS_UTF8_CONVERT, 0},
{"ignore_type", ASN1_STRFLGS_IGNORE_TYPE, 0},
{"show_type", ASN1_STRFLGS_SHOW_TYPE, 0},
{"dump_all", ASN1_STRFLGS_DUMP_ALL, 0},
{"dump_nostr", ASN1_STRFLGS_DUMP_UNKNOWN, 0},
{"dump_der", ASN1_STRFLGS_DUMP_DER, 0},
{"compat", XN_FLAG_COMPAT, 0xffffffffL},
{"sep_comma_plus", XN_FLAG_SEP_COMMA_PLUS, XN_FLAG_SEP_MASK},
{"sep_comma_plus_space", XN_FLAG_SEP_CPLUS_SPC, XN_FLAG_SEP_MASK},
{"sep_semi_plus_space", XN_FLAG_SEP_SPLUS_SPC, XN_FLAG_SEP_MASK},
{"sep_multiline", XN_FLAG_SEP_MULTILINE, XN_FLAG_SEP_MASK},
{"dn_rev", XN_FLAG_DN_REV, 0},
{"nofname", XN_FLAG_FN_NONE, XN_FLAG_FN_MASK},
{"sname", XN_FLAG_FN_SN, XN_FLAG_FN_MASK},
{"lname", XN_FLAG_FN_LN, XN_FLAG_FN_MASK},
{"align", XN_FLAG_FN_ALIGN, 0},
{"oid", XN_FLAG_FN_OID, XN_FLAG_FN_MASK},
{"space_eq", XN_FLAG_SPC_EQ, 0},
{"dump_unknown", XN_FLAG_DUMP_UNKNOWN_FIELDS, 0},
{"RFC2253", XN_FLAG_RFC2253, 0xffffffffL},
{"oneline", XN_FLAG_ONELINE, 0xffffffffL},
{"multiline", XN_FLAG_MULTILINE, 0xffffffffL},
{"ca_default", XN_FLAG_MULTILINE, 0xffffffffL},
{NULL, 0, 0}
};
if (set_multi_opts(flags, arg, ex_tbl) == 0)
return 0;
if ((*flags & XN_FLAG_SEP_MASK) == 0)
*flags |= XN_FLAG_SEP_CPLUS_SPC;
return 1;
}
int set_ext_copy(int *copy_type, const char *arg)
{
if (!strcasecmp(arg, "none"))
*copy_type = EXT_COPY_NONE;
else if (!strcasecmp(arg, "copy"))
*copy_type = EXT_COPY_ADD;
else if (!strcasecmp(arg, "copyall"))
*copy_type = EXT_COPY_ALL;
else
return 0;
return 1;
}
int copy_extensions(X509 *x, X509_REQ *req, int copy_type)
{
STACK_OF(X509_EXTENSION) *exts = NULL;
X509_EXTENSION *ext, *tmpext;
ASN1_OBJECT *obj;
int i, idx, ret = 0;
if (!x || !req || (copy_type == EXT_COPY_NONE))
return 1;
exts = X509_REQ_get_extensions(req);
for (i = 0; i < sk_X509_EXTENSION_num(exts); i++) {
ext = sk_X509_EXTENSION_value(exts, i);
obj = X509_EXTENSION_get_object(ext);
idx = X509_get_ext_by_OBJ(x, obj, -1);
/* Does extension exist? */
if (idx != -1) {
/* If normal copy don't override existing extension */
if (copy_type == EXT_COPY_ADD)
continue;
/* Delete all extensions of same type */
do {
tmpext = X509_get_ext(x, idx);
X509_delete_ext(x, idx);
X509_EXTENSION_free(tmpext);
idx = X509_get_ext_by_OBJ(x, obj, -1);
} while (idx != -1);
}
if (!X509_add_ext(x, ext, -1))
goto end;
}
ret = 1;
end:
sk_X509_EXTENSION_pop_free(exts, X509_EXTENSION_free);
return ret;
}
static int set_multi_opts(unsigned long *flags, const char *arg,
const NAME_EX_TBL * in_tbl)
{
STACK_OF(CONF_VALUE) *vals;
CONF_VALUE *val;
int i, ret = 1;
if (!arg)
return 0;
vals = X509V3_parse_list(arg);
for (i = 0; i < sk_CONF_VALUE_num(vals); i++) {
val = sk_CONF_VALUE_value(vals, i);
if (!set_table_opts(flags, val->name, in_tbl))
ret = 0;
}
sk_CONF_VALUE_pop_free(vals, X509V3_conf_free);
return ret;
}
static int set_table_opts(unsigned long *flags, const char *arg,
const NAME_EX_TBL * in_tbl)
{
char c;
const NAME_EX_TBL *ptbl;
c = arg[0];
if (c == '-') {
c = 0;
arg++;
} else if (c == '+') {
c = 1;
arg++;
} else
c = 1;
for (ptbl = in_tbl; ptbl->name; ptbl++) {
if (!strcasecmp(arg, ptbl->name)) {
*flags &= ~ptbl->mask;
if (c)
*flags |= ptbl->flag;
else
*flags &= ~ptbl->flag;
return 1;
}
}
return 0;
}
void print_name(BIO *out, const char *title, X509_NAME *nm,
unsigned long lflags)
{
char *buf;
char mline = 0;
int indent = 0;
if (title)
BIO_puts(out, title);
if ((lflags & XN_FLAG_SEP_MASK) == XN_FLAG_SEP_MULTILINE) {
mline = 1;
indent = 4;
}
if (lflags == XN_FLAG_COMPAT) {
buf = X509_NAME_oneline(nm, 0, 0);
BIO_puts(out, buf);
BIO_puts(out, "\n");
OPENSSL_free(buf);
} else {
if (mline)
BIO_puts(out, "\n");
X509_NAME_print_ex(out, nm, indent, lflags);
BIO_puts(out, "\n");
}
}
X509_STORE *setup_verify(BIO *bp, char *CAfile, char *CApath)
{
X509_STORE *store;
X509_LOOKUP *lookup;
if (!(store = X509_STORE_new()))
goto end;
lookup = X509_STORE_add_lookup(store, X509_LOOKUP_file());
if (lookup == NULL)
goto end;
if (CAfile) {
if (!X509_LOOKUP_load_file(lookup, CAfile, X509_FILETYPE_PEM)) {
BIO_printf(bp, "Error loading file %s\n", CAfile);
goto end;
}
} else
X509_LOOKUP_load_file(lookup, NULL, X509_FILETYPE_DEFAULT);
lookup = X509_STORE_add_lookup(store, X509_LOOKUP_hash_dir());
if (lookup == NULL)
goto end;
if (CApath) {
if (!X509_LOOKUP_add_dir(lookup, CApath, X509_FILETYPE_PEM)) {
BIO_printf(bp, "Error loading directory %s\n", CApath);
goto end;
}
} else
X509_LOOKUP_add_dir(lookup, NULL, X509_FILETYPE_DEFAULT);
ERR_clear_error();
return store;
end:
X509_STORE_free(store);
return NULL;
}
#ifndef OPENSSL_NO_ENGINE
/* Try to load an engine in a shareable library */
static ENGINE *try_load_engine(BIO *err, const char *engine, int debug)
{
ENGINE *e = ENGINE_by_id("dynamic");
if (e) {
if (!ENGINE_ctrl_cmd_string(e, "SO_PATH", engine, 0)
|| !ENGINE_ctrl_cmd_string(e, "LOAD", NULL, 0)) {
ENGINE_free(e);
e = NULL;
}
}
return e;
}
#endif
ENGINE *setup_engine(BIO *err, const char *engine, int debug)
{
ENGINE *e = NULL;
#ifndef OPENSSL_NO_ENGINE
if (engine) {
if (strcmp(engine, "auto") == 0) {
BIO_printf(err, "enabling auto ENGINE support\n");
ENGINE_register_all_complete();
return NULL;
}
if ((e = ENGINE_by_id(engine)) == NULL
&& (e = try_load_engine(err, engine, debug)) == NULL) {
BIO_printf(err, "invalid engine \"%s\"\n", engine);
ERR_print_errors(err);
return NULL;
}
if (debug) {
ENGINE_ctrl(e, ENGINE_CTRL_SET_LOGSTREAM, 0, err, 0);
}
ENGINE_ctrl_cmd(e, "SET_USER_INTERFACE", 0, ui_method, 0, 1);
if (!ENGINE_set_default(e, ENGINE_METHOD_ALL)) {
BIO_printf(err, "can't use that engine\n");
ERR_print_errors(err);
ENGINE_free(e);
return NULL;
}
BIO_printf(err, "engine \"%s\" set.\n", ENGINE_get_id(e));
}
#endif
return e;
}
void release_engine(ENGINE *e)
{
#ifndef OPENSSL_NO_ENGINE
if (e != NULL)
/* Free our "structural" reference. */
ENGINE_free(e);
#endif
}
int load_config(BIO *err, CONF *cnf)
{
static int load_config_called = 0;
if (load_config_called)
return 1;
load_config_called = 1;
if (!cnf)
cnf = config;
if (!cnf)
return 1;
OPENSSL_load_builtin_modules();
if (CONF_modules_load(cnf, NULL, 0) <= 0) {
BIO_printf(err, "Error configuring OpenSSL\n");
ERR_print_errors(err);
return 0;
}
return 1;
}
char *make_config_name()
{
const char *t = X509_get_default_cert_area();
size_t len;
char *p;
len = strlen(t) + strlen(OPENSSL_CONF) + 2;
p = OPENSSL_malloc(len);
if (p == NULL)
return NULL;
BUF_strlcpy(p, t, len);
#ifndef OPENSSL_SYS_VMS
BUF_strlcat(p, "/", len);
#endif
BUF_strlcat(p, OPENSSL_CONF, len);
return p;
}
static unsigned long index_serial_hash(const OPENSSL_CSTRING *a)
{
const char *n;
n = a[DB_serial];
while (*n == '0')
n++;
return (lh_strhash(n));
}
static int index_serial_cmp(const OPENSSL_CSTRING *a,
const OPENSSL_CSTRING *b)
{
const char *aa, *bb;
for (aa = a[DB_serial]; *aa == '0'; aa++) ;
for (bb = b[DB_serial]; *bb == '0'; bb++) ;
return (strcmp(aa, bb));
}
static int index_name_qual(char **a)
{
return (a[0][0] == 'V');
}
static unsigned long index_name_hash(const OPENSSL_CSTRING *a)
{
return (lh_strhash(a[DB_name]));
}
int index_name_cmp(const OPENSSL_CSTRING *a, const OPENSSL_CSTRING *b)
{
return (strcmp(a[DB_name], b[DB_name]));
}
static IMPLEMENT_LHASH_HASH_FN(index_serial, OPENSSL_CSTRING)
static IMPLEMENT_LHASH_COMP_FN(index_serial, OPENSSL_CSTRING)
static IMPLEMENT_LHASH_HASH_FN(index_name, OPENSSL_CSTRING)
static IMPLEMENT_LHASH_COMP_FN(index_name, OPENSSL_CSTRING)
#undef BSIZE
#define BSIZE 256
BIGNUM *load_serial(char *serialfile, int create, ASN1_INTEGER **retai)
{
BIO *in = NULL;
BIGNUM *ret = NULL;
MS_STATIC char buf[1024];
ASN1_INTEGER *ai = NULL;
ai = ASN1_INTEGER_new();
if (ai == NULL)
goto err;
if ((in = BIO_new(BIO_s_file())) == NULL) {
ERR_print_errors(bio_err);
goto err;
}
if (BIO_read_filename(in, serialfile) <= 0) {
if (!create) {
perror(serialfile);
goto err;
} else {
ret = BN_new();
if (ret == NULL || !rand_serial(ret, ai))
BIO_printf(bio_err, "Out of memory\n");
}
} else {
if (!a2i_ASN1_INTEGER(in, ai, buf, 1024)) {
BIO_printf(bio_err, "unable to load number from %s\n",
serialfile);
goto err;
}
ret = ASN1_INTEGER_to_BN(ai, NULL);
if (ret == NULL) {
BIO_printf(bio_err,
"error converting number from bin to BIGNUM\n");
goto err;
}
}
if (ret && retai) {
*retai = ai;
ai = NULL;
}
err:
if (in != NULL)
BIO_free(in);
if (ai != NULL)
ASN1_INTEGER_free(ai);
return (ret);
}
int save_serial(char *serialfile, char *suffix, BIGNUM *serial,
ASN1_INTEGER **retai)
{
char buf[1][BSIZE];
BIO *out = NULL;
int ret = 0;
ASN1_INTEGER *ai = NULL;
int j;
if (suffix == NULL)
j = strlen(serialfile);
else
j = strlen(serialfile) + strlen(suffix) + 1;
if (j >= BSIZE) {
BIO_printf(bio_err, "file name too long\n");
goto err;
}
if (suffix == NULL)
BUF_strlcpy(buf[0], serialfile, BSIZE);
else {
#ifndef OPENSSL_SYS_VMS
- j = BIO_snprintf(buf[0], sizeof buf[0], "%s.%s", serialfile, suffix);
+ j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s.%s", serialfile, suffix);
#else
- j = BIO_snprintf(buf[0], sizeof buf[0], "%s-%s", serialfile, suffix);
+ j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s-%s", serialfile, suffix);
#endif
}
#ifdef RL_DEBUG
BIO_printf(bio_err, "DEBUG: writing \"%s\"\n", buf[0]);
#endif
out = BIO_new(BIO_s_file());
if (out == NULL) {
ERR_print_errors(bio_err);
goto err;
}
if (BIO_write_filename(out, buf[0]) <= 0) {
perror(serialfile);
goto err;
}
if ((ai = BN_to_ASN1_INTEGER(serial, NULL)) == NULL) {
BIO_printf(bio_err, "error converting serial to ASN.1 format\n");
goto err;
}
i2a_ASN1_INTEGER(out, ai);
BIO_puts(out, "\n");
ret = 1;
if (retai) {
*retai = ai;
ai = NULL;
}
err:
if (out != NULL)
BIO_free_all(out);
if (ai != NULL)
ASN1_INTEGER_free(ai);
return (ret);
}
int rotate_serial(char *serialfile, char *new_suffix, char *old_suffix)
{
char buf[5][BSIZE];
int i, j;
i = strlen(serialfile) + strlen(old_suffix);
j = strlen(serialfile) + strlen(new_suffix);
if (i > j)
j = i;
if (j + 1 >= BSIZE) {
BIO_printf(bio_err, "file name too long\n");
goto err;
}
#ifndef OPENSSL_SYS_VMS
- j = BIO_snprintf(buf[0], sizeof buf[0], "%s.%s", serialfile, new_suffix);
+ j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s.%s", serialfile, new_suffix);
#else
- j = BIO_snprintf(buf[0], sizeof buf[0], "%s-%s", serialfile, new_suffix);
+ j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s-%s", serialfile, new_suffix);
#endif
#ifndef OPENSSL_SYS_VMS
- j = BIO_snprintf(buf[1], sizeof buf[1], "%s.%s", serialfile, old_suffix);
+ j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s.%s", serialfile, old_suffix);
#else
- j = BIO_snprintf(buf[1], sizeof buf[1], "%s-%s", serialfile, old_suffix);
+ j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s-%s", serialfile, old_suffix);
#endif
#ifdef RL_DEBUG
BIO_printf(bio_err, "DEBUG: renaming \"%s\" to \"%s\"\n",
serialfile, buf[1]);
#endif
if (rename(serialfile, buf[1]) < 0 && errno != ENOENT
#ifdef ENOTDIR
&& errno != ENOTDIR
#endif
) {
BIO_printf(bio_err,
"unable to rename %s to %s\n", serialfile, buf[1]);
perror("reason");
goto err;
}
#ifdef RL_DEBUG
BIO_printf(bio_err, "DEBUG: renaming \"%s\" to \"%s\"\n",
buf[0], serialfile);
#endif
if (rename(buf[0], serialfile) < 0) {
BIO_printf(bio_err,
"unable to rename %s to %s\n", buf[0], serialfile);
perror("reason");
rename(buf[1], serialfile);
goto err;
}
return 1;
err:
return 0;
}
int rand_serial(BIGNUM *b, ASN1_INTEGER *ai)
{
BIGNUM *btmp;
int ret = 0;
if (b)
btmp = b;
else
btmp = BN_new();
if (!btmp)
return 0;
if (!BN_pseudo_rand(btmp, SERIAL_RAND_BITS, 0, 0))
goto error;
if (ai && !BN_to_ASN1_INTEGER(btmp, ai))
goto error;
ret = 1;
error:
if (!b)
BN_free(btmp);
return ret;
}
CA_DB *load_index(char *dbfile, DB_ATTR *db_attr)
{
CA_DB *retdb = NULL;
TXT_DB *tmpdb = NULL;
BIO *in = BIO_new(BIO_s_file());
CONF *dbattr_conf = NULL;
char buf[1][BSIZE];
long errorline = -1;
if (in == NULL) {
ERR_print_errors(bio_err);
goto err;
}
if (BIO_read_filename(in, dbfile) <= 0) {
perror(dbfile);
BIO_printf(bio_err, "unable to open '%s'\n", dbfile);
goto err;
}
if ((tmpdb = TXT_DB_read(in, DB_NUMBER)) == NULL)
goto err;
#ifndef OPENSSL_SYS_VMS
- BIO_snprintf(buf[0], sizeof buf[0], "%s.attr", dbfile);
+ BIO_snprintf(buf[0], sizeof(buf[0]), "%s.attr", dbfile);
#else
- BIO_snprintf(buf[0], sizeof buf[0], "%s-attr", dbfile);
+ BIO_snprintf(buf[0], sizeof(buf[0]), "%s-attr", dbfile);
#endif
dbattr_conf = NCONF_new(NULL);
if (NCONF_load(dbattr_conf, buf[0], &errorline) <= 0) {
if (errorline > 0) {
BIO_printf(bio_err,
"error on line %ld of db attribute file '%s'\n",
errorline, buf[0]);
goto err;
} else {
NCONF_free(dbattr_conf);
dbattr_conf = NULL;
}
}
if ((retdb = OPENSSL_malloc(sizeof(CA_DB))) == NULL) {
fprintf(stderr, "Out of memory\n");
goto err;
}
retdb->db = tmpdb;
tmpdb = NULL;
if (db_attr)
retdb->attributes = *db_attr;
else {
retdb->attributes.unique_subject = 1;
}
if (dbattr_conf) {
char *p = NCONF_get_string(dbattr_conf, NULL, "unique_subject");
if (p) {
#ifdef RL_DEBUG
BIO_printf(bio_err,
"DEBUG[load_index]: unique_subject = \"%s\"\n", p);
#endif
retdb->attributes.unique_subject = parse_yesno(p, 1);
}
}
err:
if (dbattr_conf)
NCONF_free(dbattr_conf);
if (tmpdb)
TXT_DB_free(tmpdb);
if (in)
BIO_free_all(in);
return retdb;
}
int index_index(CA_DB *db)
{
if (!TXT_DB_create_index(db->db, DB_serial, NULL,
LHASH_HASH_FN(index_serial),
LHASH_COMP_FN(index_serial))) {
BIO_printf(bio_err,
"error creating serial number index:(%ld,%ld,%ld)\n",
db->db->error, db->db->arg1, db->db->arg2);
return 0;
}
if (db->attributes.unique_subject
&& !TXT_DB_create_index(db->db, DB_name, index_name_qual,
LHASH_HASH_FN(index_name),
LHASH_COMP_FN(index_name))) {
BIO_printf(bio_err, "error creating name index:(%ld,%ld,%ld)\n",
db->db->error, db->db->arg1, db->db->arg2);
return 0;
}
return 1;
}
int save_index(const char *dbfile, const char *suffix, CA_DB *db)
{
char buf[3][BSIZE];
BIO *out = BIO_new(BIO_s_file());
int j;
if (out == NULL) {
ERR_print_errors(bio_err);
goto err;
}
j = strlen(dbfile) + strlen(suffix);
if (j + 6 >= BSIZE) {
BIO_printf(bio_err, "file name too long\n");
goto err;
}
#ifndef OPENSSL_SYS_VMS
- j = BIO_snprintf(buf[2], sizeof buf[2], "%s.attr", dbfile);
+ j = BIO_snprintf(buf[2], sizeof(buf[2]), "%s.attr", dbfile);
#else
- j = BIO_snprintf(buf[2], sizeof buf[2], "%s-attr", dbfile);
+ j = BIO_snprintf(buf[2], sizeof(buf[2]), "%s-attr", dbfile);
#endif
#ifndef OPENSSL_SYS_VMS
- j = BIO_snprintf(buf[1], sizeof buf[1], "%s.attr.%s", dbfile, suffix);
+ j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s.attr.%s", dbfile, suffix);
#else
- j = BIO_snprintf(buf[1], sizeof buf[1], "%s-attr-%s", dbfile, suffix);
+ j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s-attr-%s", dbfile, suffix);
#endif
#ifndef OPENSSL_SYS_VMS
- j = BIO_snprintf(buf[0], sizeof buf[0], "%s.%s", dbfile, suffix);
+ j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s.%s", dbfile, suffix);
#else
- j = BIO_snprintf(buf[0], sizeof buf[0], "%s-%s", dbfile, suffix);
+ j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s-%s", dbfile, suffix);
#endif
#ifdef RL_DEBUG
BIO_printf(bio_err, "DEBUG: writing \"%s\"\n", buf[0]);
#endif
if (BIO_write_filename(out, buf[0]) <= 0) {
perror(dbfile);
BIO_printf(bio_err, "unable to open '%s'\n", dbfile);
goto err;
}
j = TXT_DB_write(out, db->db);
if (j <= 0)
goto err;
BIO_free(out);
out = BIO_new(BIO_s_file());
#ifdef RL_DEBUG
BIO_printf(bio_err, "DEBUG: writing \"%s\"\n", buf[1]);
#endif
if (BIO_write_filename(out, buf[1]) <= 0) {
perror(buf[2]);
BIO_printf(bio_err, "unable to open '%s'\n", buf[2]);
goto err;
}
BIO_printf(out, "unique_subject = %s\n",
db->attributes.unique_subject ? "yes" : "no");
BIO_free(out);
return 1;
err:
return 0;
}
int rotate_index(const char *dbfile, const char *new_suffix,
const char *old_suffix)
{
char buf[5][BSIZE];
int i, j;
i = strlen(dbfile) + strlen(old_suffix);
j = strlen(dbfile) + strlen(new_suffix);
if (i > j)
j = i;
if (j + 6 >= BSIZE) {
BIO_printf(bio_err, "file name too long\n");
goto err;
}
#ifndef OPENSSL_SYS_VMS
- j = BIO_snprintf(buf[4], sizeof buf[4], "%s.attr", dbfile);
+ j = BIO_snprintf(buf[4], sizeof(buf[4]), "%s.attr", dbfile);
#else
- j = BIO_snprintf(buf[4], sizeof buf[4], "%s-attr", dbfile);
+ j = BIO_snprintf(buf[4], sizeof(buf[4]), "%s-attr", dbfile);
#endif
#ifndef OPENSSL_SYS_VMS
- j = BIO_snprintf(buf[2], sizeof buf[2], "%s.attr.%s", dbfile, new_suffix);
+ j = BIO_snprintf(buf[2], sizeof(buf[2]), "%s.attr.%s", dbfile, new_suffix);
#else
- j = BIO_snprintf(buf[2], sizeof buf[2], "%s-attr-%s", dbfile, new_suffix);
+ j = BIO_snprintf(buf[2], sizeof(buf[2]), "%s-attr-%s", dbfile, new_suffix);
#endif
#ifndef OPENSSL_SYS_VMS
- j = BIO_snprintf(buf[0], sizeof buf[0], "%s.%s", dbfile, new_suffix);
+ j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s.%s", dbfile, new_suffix);
#else
- j = BIO_snprintf(buf[0], sizeof buf[0], "%s-%s", dbfile, new_suffix);
+ j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s-%s", dbfile, new_suffix);
#endif
#ifndef OPENSSL_SYS_VMS
- j = BIO_snprintf(buf[1], sizeof buf[1], "%s.%s", dbfile, old_suffix);
+ j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s.%s", dbfile, old_suffix);
#else
- j = BIO_snprintf(buf[1], sizeof buf[1], "%s-%s", dbfile, old_suffix);
+ j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s-%s", dbfile, old_suffix);
#endif
#ifndef OPENSSL_SYS_VMS
- j = BIO_snprintf(buf[3], sizeof buf[3], "%s.attr.%s", dbfile, old_suffix);
+ j = BIO_snprintf(buf[3], sizeof(buf[3]), "%s.attr.%s", dbfile, old_suffix);
#else
- j = BIO_snprintf(buf[3], sizeof buf[3], "%s-attr-%s", dbfile, old_suffix);
+ j = BIO_snprintf(buf[3], sizeof(buf[3]), "%s-attr-%s", dbfile, old_suffix);
#endif
#ifdef RL_DEBUG
BIO_printf(bio_err, "DEBUG: renaming \"%s\" to \"%s\"\n", dbfile, buf[1]);
#endif
if (rename(dbfile, buf[1]) < 0 && errno != ENOENT
#ifdef ENOTDIR
&& errno != ENOTDIR
#endif
) {
BIO_printf(bio_err, "unable to rename %s to %s\n", dbfile, buf[1]);
perror("reason");
goto err;
}
#ifdef RL_DEBUG
BIO_printf(bio_err, "DEBUG: renaming \"%s\" to \"%s\"\n", buf[0], dbfile);
#endif
if (rename(buf[0], dbfile) < 0) {
BIO_printf(bio_err, "unable to rename %s to %s\n", buf[0], dbfile);
perror("reason");
rename(buf[1], dbfile);
goto err;
}
#ifdef RL_DEBUG
BIO_printf(bio_err, "DEBUG: renaming \"%s\" to \"%s\"\n", buf[4], buf[3]);
#endif
if (rename(buf[4], buf[3]) < 0 && errno != ENOENT
#ifdef ENOTDIR
&& errno != ENOTDIR
#endif
) {
BIO_printf(bio_err, "unable to rename %s to %s\n", buf[4], buf[3]);
perror("reason");
rename(dbfile, buf[0]);
rename(buf[1], dbfile);
goto err;
}
#ifdef RL_DEBUG
BIO_printf(bio_err, "DEBUG: renaming \"%s\" to \"%s\"\n", buf[2], buf[4]);
#endif
if (rename(buf[2], buf[4]) < 0) {
BIO_printf(bio_err, "unable to rename %s to %s\n", buf[2], buf[4]);
perror("reason");
rename(buf[3], buf[4]);
rename(dbfile, buf[0]);
rename(buf[1], dbfile);
goto err;
}
return 1;
err:
return 0;
}
void free_index(CA_DB *db)
{
if (db) {
if (db->db)
TXT_DB_free(db->db);
OPENSSL_free(db);
}
}
int parse_yesno(const char *str, int def)
{
int ret = def;
if (str) {
switch (*str) {
case 'f': /* false */
case 'F': /* FALSE */
case 'n': /* no */
case 'N': /* NO */
case '0': /* 0 */
ret = 0;
break;
case 't': /* true */
case 'T': /* TRUE */
case 'y': /* yes */
case 'Y': /* YES */
case '1': /* 1 */
ret = 1;
break;
default:
ret = def;
break;
}
}
return ret;
}
/*
* subject is expected to be in the format /type0=value0/type1=value1/type2=...
* where characters may be escaped by \
*/
X509_NAME *parse_name(char *subject, long chtype, int multirdn)
{
size_t buflen = strlen(subject) + 1; /* to copy the types and values
* into. due to escaping, the copy
* can only become shorter */
char *buf = OPENSSL_malloc(buflen);
size_t max_ne = buflen / 2 + 1; /* maximum number of name elements */
char **ne_types = OPENSSL_malloc(max_ne * sizeof(char *));
char **ne_values = OPENSSL_malloc(max_ne * sizeof(char *));
int *mval = OPENSSL_malloc(max_ne * sizeof(int));
char *sp = subject, *bp = buf;
int i, ne_num = 0;
X509_NAME *n = NULL;
int nid;
if (!buf || !ne_types || !ne_values || !mval) {
BIO_printf(bio_err, "malloc error\n");
goto error;
}
if (*subject != '/') {
BIO_printf(bio_err, "Subject does not start with '/'.\n");
goto error;
}
sp++; /* skip leading / */
/* no multivalued RDN by default */
mval[ne_num] = 0;
while (*sp) {
/* collect type */
ne_types[ne_num] = bp;
while (*sp) {
if (*sp == '\\') { /* is there anything to escape in the
* type...? */
if (*++sp)
*bp++ = *sp++;
else {
BIO_printf(bio_err,
"escape character at end of string\n");
goto error;
}
} else if (*sp == '=') {
sp++;
*bp++ = '\0';
break;
} else
*bp++ = *sp++;
}
if (!*sp) {
BIO_printf(bio_err,
"end of string encountered while processing type of subject name element #%d\n",
ne_num);
goto error;
}
ne_values[ne_num] = bp;
while (*sp) {
if (*sp == '\\') {
if (*++sp)
*bp++ = *sp++;
else {
BIO_printf(bio_err,
"escape character at end of string\n");
goto error;
}
} else if (*sp == '/') {
sp++;
/* no multivalued RDN by default */
mval[ne_num + 1] = 0;
break;
} else if (*sp == '+' && multirdn) {
/*
* a not escaped + signals a mutlivalued RDN
*/
sp++;
mval[ne_num + 1] = -1;
break;
} else
*bp++ = *sp++;
}
*bp++ = '\0';
ne_num++;
}
if (!(n = X509_NAME_new()))
goto error;
for (i = 0; i < ne_num; i++) {
if ((nid = OBJ_txt2nid(ne_types[i])) == NID_undef) {
BIO_printf(bio_err,
"Subject Attribute %s has no known NID, skipped\n",
ne_types[i]);
continue;
}
if (!*ne_values[i]) {
BIO_printf(bio_err,
"No value provided for Subject Attribute %s, skipped\n",
ne_types[i]);
continue;
}
if (!X509_NAME_add_entry_by_NID
(n, nid, chtype, (unsigned char *)ne_values[i], -1, -1, mval[i]))
goto error;
}
OPENSSL_free(ne_values);
OPENSSL_free(ne_types);
OPENSSL_free(buf);
OPENSSL_free(mval);
return n;
error:
X509_NAME_free(n);
if (ne_values)
OPENSSL_free(ne_values);
if (ne_types)
OPENSSL_free(ne_types);
if (mval)
OPENSSL_free(mval);
if (buf)
OPENSSL_free(buf);
return NULL;
}
int args_verify(char ***pargs, int *pargc,
int *badarg, BIO *err, X509_VERIFY_PARAM **pm)
{
ASN1_OBJECT *otmp = NULL;
unsigned long flags = 0;
int i;
int purpose = 0, depth = -1;
char **oldargs = *pargs;
char *arg = **pargs, *argn = (*pargs)[1];
time_t at_time = 0;
char *hostname = NULL;
char *email = NULL;
char *ipasc = NULL;
if (!strcmp(arg, "-policy")) {
if (!argn)
*badarg = 1;
else {
otmp = OBJ_txt2obj(argn, 0);
if (!otmp) {
BIO_printf(err, "Invalid Policy \"%s\"\n", argn);
*badarg = 1;
}
}
(*pargs)++;
} else if (strcmp(arg, "-purpose") == 0) {
X509_PURPOSE *xptmp;
if (!argn)
*badarg = 1;
else {
i = X509_PURPOSE_get_by_sname(argn);
if (i < 0) {
BIO_printf(err, "unrecognized purpose\n");
*badarg = 1;
} else {
xptmp = X509_PURPOSE_get0(i);
purpose = X509_PURPOSE_get_id(xptmp);
}
}
(*pargs)++;
} else if (strcmp(arg, "-verify_depth") == 0) {
if (!argn)
*badarg = 1;
else {
depth = atoi(argn);
if (depth < 0) {
BIO_printf(err, "invalid depth\n");
*badarg = 1;
}
}
(*pargs)++;
} else if (strcmp(arg, "-attime") == 0) {
if (!argn)
*badarg = 1;
else {
long timestamp;
/*
* interpret the -attime argument as seconds since Epoch
*/
if (sscanf(argn, "%li", &timestamp) != 1) {
BIO_printf(bio_err, "Error parsing timestamp %s\n", argn);
*badarg = 1;
}
/* on some platforms time_t may be a float */
at_time = (time_t)timestamp;
}
(*pargs)++;
} else if (strcmp(arg, "-verify_hostname") == 0) {
if (!argn)
*badarg = 1;
hostname = argn;
(*pargs)++;
} else if (strcmp(arg, "-verify_email") == 0) {
if (!argn)
*badarg = 1;
email = argn;
(*pargs)++;
} else if (strcmp(arg, "-verify_ip") == 0) {
if (!argn)
*badarg = 1;
ipasc = argn;
(*pargs)++;
} else if (!strcmp(arg, "-ignore_critical"))
flags |= X509_V_FLAG_IGNORE_CRITICAL;
else if (!strcmp(arg, "-issuer_checks"))
flags |= X509_V_FLAG_CB_ISSUER_CHECK;
else if (!strcmp(arg, "-crl_check"))
flags |= X509_V_FLAG_CRL_CHECK;
else if (!strcmp(arg, "-crl_check_all"))
flags |= X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL;
else if (!strcmp(arg, "-policy_check"))
flags |= X509_V_FLAG_POLICY_CHECK;
else if (!strcmp(arg, "-explicit_policy"))
flags |= X509_V_FLAG_EXPLICIT_POLICY;
else if (!strcmp(arg, "-inhibit_any"))
flags |= X509_V_FLAG_INHIBIT_ANY;
else if (!strcmp(arg, "-inhibit_map"))
flags |= X509_V_FLAG_INHIBIT_MAP;
else if (!strcmp(arg, "-x509_strict"))
flags |= X509_V_FLAG_X509_STRICT;
else if (!strcmp(arg, "-extended_crl"))
flags |= X509_V_FLAG_EXTENDED_CRL_SUPPORT;
else if (!strcmp(arg, "-use_deltas"))
flags |= X509_V_FLAG_USE_DELTAS;
else if (!strcmp(arg, "-policy_print"))
flags |= X509_V_FLAG_NOTIFY_POLICY;
else if (!strcmp(arg, "-check_ss_sig"))
flags |= X509_V_FLAG_CHECK_SS_SIGNATURE;
else if (!strcmp(arg, "-trusted_first"))
flags |= X509_V_FLAG_TRUSTED_FIRST;
else if (!strcmp(arg, "-suiteB_128_only"))
flags |= X509_V_FLAG_SUITEB_128_LOS_ONLY;
else if (!strcmp(arg, "-suiteB_128"))
flags |= X509_V_FLAG_SUITEB_128_LOS;
else if (!strcmp(arg, "-suiteB_192"))
flags |= X509_V_FLAG_SUITEB_192_LOS;
else if (!strcmp(arg, "-partial_chain"))
flags |= X509_V_FLAG_PARTIAL_CHAIN;
else if (!strcmp(arg, "-no_alt_chains"))
flags |= X509_V_FLAG_NO_ALT_CHAINS;
else if (!strcmp(arg, "-allow_proxy_certs"))
flags |= X509_V_FLAG_ALLOW_PROXY_CERTS;
else
return 0;
if (*badarg) {
if (*pm)
X509_VERIFY_PARAM_free(*pm);
*pm = NULL;
goto end;
}
if (!*pm && !(*pm = X509_VERIFY_PARAM_new())) {
*badarg = 1;
goto end;
}
if (otmp)
X509_VERIFY_PARAM_add0_policy(*pm, otmp);
if (flags)
X509_VERIFY_PARAM_set_flags(*pm, flags);
if (purpose)
X509_VERIFY_PARAM_set_purpose(*pm, purpose);
if (depth >= 0)
X509_VERIFY_PARAM_set_depth(*pm, depth);
if (at_time)
X509_VERIFY_PARAM_set_time(*pm, at_time);
if (hostname && !X509_VERIFY_PARAM_set1_host(*pm, hostname, 0))
*badarg = 1;
if (email && !X509_VERIFY_PARAM_set1_email(*pm, email, 0))
*badarg = 1;
if (ipasc && !X509_VERIFY_PARAM_set1_ip_asc(*pm, ipasc))
*badarg = 1;
end:
(*pargs)++;
if (pargc)
*pargc -= *pargs - oldargs;
return 1;
}
/*
* Read whole contents of a BIO into an allocated memory buffer and return
* it.
*/
int bio_to_mem(unsigned char **out, int maxlen, BIO *in)
{
BIO *mem;
int len, ret;
unsigned char tbuf[1024];
mem = BIO_new(BIO_s_mem());
if (!mem)
return -1;
for (;;) {
if ((maxlen != -1) && maxlen < 1024)
len = maxlen;
else
len = 1024;
len = BIO_read(in, tbuf, len);
if (len < 0) {
BIO_free(mem);
return -1;
}
if (len == 0)
break;
if (BIO_write(mem, tbuf, len) != len) {
BIO_free(mem);
return -1;
}
maxlen -= len;
if (maxlen == 0)
break;
}
ret = BIO_get_mem_data(mem, (char **)out);
BIO_set_flags(mem, BIO_FLAGS_MEM_RDONLY);
BIO_free(mem);
return ret;
}
int pkey_ctrl_string(EVP_PKEY_CTX *ctx, const char *value)
{
int rv;
char *stmp, *vtmp = NULL;
stmp = BUF_strdup(value);
if (!stmp)
return -1;
vtmp = strchr(stmp, ':');
if (vtmp) {
*vtmp = 0;
vtmp++;
}
rv = EVP_PKEY_CTX_ctrl_str(ctx, stmp, vtmp);
OPENSSL_free(stmp);
return rv;
}
static void nodes_print(BIO *out, const char *name,
STACK_OF(X509_POLICY_NODE) *nodes)
{
X509_POLICY_NODE *node;
int i;
BIO_printf(out, "%s Policies:", name);
if (nodes) {
BIO_puts(out, "\n");
for (i = 0; i < sk_X509_POLICY_NODE_num(nodes); i++) {
node = sk_X509_POLICY_NODE_value(nodes, i);
X509_POLICY_NODE_print(out, node, 2);
}
} else
BIO_puts(out, " <empty>\n");
}
void policies_print(BIO *out, X509_STORE_CTX *ctx)
{
X509_POLICY_TREE *tree;
int explicit_policy;
int free_out = 0;
if (out == NULL) {
out = BIO_new_fp(stderr, BIO_NOCLOSE);
free_out = 1;
}
tree = X509_STORE_CTX_get0_policy_tree(ctx);
explicit_policy = X509_STORE_CTX_get_explicit_policy(ctx);
BIO_printf(out, "Require explicit Policy: %s\n",
explicit_policy ? "True" : "False");
nodes_print(out, "Authority", X509_policy_tree_get0_policies(tree));
nodes_print(out, "User", X509_policy_tree_get0_user_policies(tree));
if (free_out)
BIO_free(out);
}
#if !defined(OPENSSL_NO_JPAKE) && !defined(OPENSSL_NO_PSK)
static JPAKE_CTX *jpake_init(const char *us, const char *them,
const char *secret)
{
BIGNUM *p = NULL;
BIGNUM *g = NULL;
BIGNUM *q = NULL;
BIGNUM *bnsecret = BN_new();
JPAKE_CTX *ctx;
/* Use a safe prime for p (that we found earlier) */
BN_hex2bn(&p,
"F9E5B365665EA7A05A9C534502780FEE6F1AB5BD4F49947FD036DBD7E905269AF46EF28B0FC07487EE4F5D20FB3C0AF8E700F3A2FA3414970CBED44FEDFF80CE78D800F184BB82435D137AADA2C6C16523247930A63B85661D1FC817A51ACD96168E95898A1F83A79FFB529368AA7833ABD1B0C3AEDDB14D2E1A2F71D99F763F");
g = BN_new();
BN_set_word(g, 2);
q = BN_new();
BN_rshift1(q, p);
BN_bin2bn((const unsigned char *)secret, strlen(secret), bnsecret);
ctx = JPAKE_CTX_new(us, them, p, g, q, bnsecret);
BN_free(bnsecret);
BN_free(q);
BN_free(g);
BN_free(p);
return ctx;
}
static void jpake_send_part(BIO *conn, const JPAKE_STEP_PART *p)
{
BN_print(conn, p->gx);
BIO_puts(conn, "\n");
BN_print(conn, p->zkpx.gr);
BIO_puts(conn, "\n");
BN_print(conn, p->zkpx.b);
BIO_puts(conn, "\n");
}
static void jpake_send_step1(BIO *bconn, JPAKE_CTX *ctx)
{
JPAKE_STEP1 s1;
JPAKE_STEP1_init(&s1);
JPAKE_STEP1_generate(&s1, ctx);
jpake_send_part(bconn, &s1.p1);
jpake_send_part(bconn, &s1.p2);
(void)BIO_flush(bconn);
JPAKE_STEP1_release(&s1);
}
static void jpake_send_step2(BIO *bconn, JPAKE_CTX *ctx)
{
JPAKE_STEP2 s2;
JPAKE_STEP2_init(&s2);
JPAKE_STEP2_generate(&s2, ctx);
jpake_send_part(bconn, &s2);
(void)BIO_flush(bconn);
JPAKE_STEP2_release(&s2);
}
static void jpake_send_step3a(BIO *bconn, JPAKE_CTX *ctx)
{
JPAKE_STEP3A s3a;
JPAKE_STEP3A_init(&s3a);
JPAKE_STEP3A_generate(&s3a, ctx);
- BIO_write(bconn, s3a.hhk, sizeof s3a.hhk);
+ BIO_write(bconn, s3a.hhk, sizeof(s3a.hhk));
(void)BIO_flush(bconn);
JPAKE_STEP3A_release(&s3a);
}
static void jpake_send_step3b(BIO *bconn, JPAKE_CTX *ctx)
{
JPAKE_STEP3B s3b;
JPAKE_STEP3B_init(&s3b);
JPAKE_STEP3B_generate(&s3b, ctx);
- BIO_write(bconn, s3b.hk, sizeof s3b.hk);
+ BIO_write(bconn, s3b.hk, sizeof(s3b.hk));
(void)BIO_flush(bconn);
JPAKE_STEP3B_release(&s3b);
}
static void readbn(BIGNUM **bn, BIO *bconn)
{
char buf[10240];
int l;
- l = BIO_gets(bconn, buf, sizeof buf);
+ l = BIO_gets(bconn, buf, sizeof(buf));
assert(l > 0);
assert(buf[l - 1] == '\n');
buf[l - 1] = '\0';
BN_hex2bn(bn, buf);
}
static void jpake_receive_part(JPAKE_STEP_PART *p, BIO *bconn)
{
readbn(&p->gx, bconn);
readbn(&p->zkpx.gr, bconn);
readbn(&p->zkpx.b, bconn);
}
static void jpake_receive_step1(JPAKE_CTX *ctx, BIO *bconn)
{
JPAKE_STEP1 s1;
JPAKE_STEP1_init(&s1);
jpake_receive_part(&s1.p1, bconn);
jpake_receive_part(&s1.p2, bconn);
if (!JPAKE_STEP1_process(ctx, &s1)) {
ERR_print_errors(bio_err);
exit(1);
}
JPAKE_STEP1_release(&s1);
}
static void jpake_receive_step2(JPAKE_CTX *ctx, BIO *bconn)
{
JPAKE_STEP2 s2;
JPAKE_STEP2_init(&s2);
jpake_receive_part(&s2, bconn);
if (!JPAKE_STEP2_process(ctx, &s2)) {
ERR_print_errors(bio_err);
exit(1);
}
JPAKE_STEP2_release(&s2);
}
static void jpake_receive_step3a(JPAKE_CTX *ctx, BIO *bconn)
{
JPAKE_STEP3A s3a;
int l;
JPAKE_STEP3A_init(&s3a);
- l = BIO_read(bconn, s3a.hhk, sizeof s3a.hhk);
- assert(l == sizeof s3a.hhk);
+ l = BIO_read(bconn, s3a.hhk, sizeof(s3a.hhk));
+ assert(l == sizeof(s3a.hhk));
if (!JPAKE_STEP3A_process(ctx, &s3a)) {
ERR_print_errors(bio_err);
exit(1);
}
JPAKE_STEP3A_release(&s3a);
}
static void jpake_receive_step3b(JPAKE_CTX *ctx, BIO *bconn)
{
JPAKE_STEP3B s3b;
int l;
JPAKE_STEP3B_init(&s3b);
- l = BIO_read(bconn, s3b.hk, sizeof s3b.hk);
- assert(l == sizeof s3b.hk);
+ l = BIO_read(bconn, s3b.hk, sizeof(s3b.hk));
+ assert(l == sizeof(s3b.hk));
if (!JPAKE_STEP3B_process(ctx, &s3b)) {
ERR_print_errors(bio_err);
exit(1);
}
JPAKE_STEP3B_release(&s3b);
}
void jpake_client_auth(BIO *out, BIO *conn, const char *secret)
{
JPAKE_CTX *ctx;
BIO *bconn;
BIO_puts(out, "Authenticating with JPAKE\n");
ctx = jpake_init("client", "server", secret);
bconn = BIO_new(BIO_f_buffer());
BIO_push(bconn, conn);
jpake_send_step1(bconn, ctx);
jpake_receive_step1(ctx, bconn);
jpake_send_step2(bconn, ctx);
jpake_receive_step2(ctx, bconn);
jpake_send_step3a(bconn, ctx);
jpake_receive_step3b(ctx, bconn);
BIO_puts(out, "JPAKE authentication succeeded, setting PSK\n");
if (psk_key)
OPENSSL_free(psk_key);
psk_key = BN_bn2hex(JPAKE_get_shared_key(ctx));
BIO_pop(bconn);
BIO_free(bconn);
JPAKE_CTX_free(ctx);
}
void jpake_server_auth(BIO *out, BIO *conn, const char *secret)
{
JPAKE_CTX *ctx;
BIO *bconn;
BIO_puts(out, "Authenticating with JPAKE\n");
ctx = jpake_init("server", "client", secret);
bconn = BIO_new(BIO_f_buffer());
BIO_push(bconn, conn);
jpake_receive_step1(ctx, bconn);
jpake_send_step1(bconn, ctx);
jpake_receive_step2(ctx, bconn);
jpake_send_step2(bconn, ctx);
jpake_receive_step3a(ctx, bconn);
jpake_send_step3b(bconn, ctx);
BIO_puts(out, "JPAKE authentication succeeded, setting PSK\n");
if (psk_key)
OPENSSL_free(psk_key);
psk_key = BN_bn2hex(JPAKE_get_shared_key(ctx));
BIO_pop(bconn);
BIO_free(bconn);
JPAKE_CTX_free(ctx);
}
#endif
#ifndef OPENSSL_NO_TLSEXT
/*-
* next_protos_parse parses a comma separated list of strings into a string
* in a format suitable for passing to SSL_CTX_set_next_protos_advertised.
* outlen: (output) set to the length of the resulting buffer on success.
* err: (maybe NULL) on failure, an error message line is written to this BIO.
* in: a NUL termianted string like "abc,def,ghi"
*
* returns: a malloced buffer or NULL on failure.
*/
unsigned char *next_protos_parse(unsigned short *outlen, const char *in)
{
size_t len;
unsigned char *out;
size_t i, start = 0;
len = strlen(in);
if (len >= 65535)
return NULL;
out = OPENSSL_malloc(strlen(in) + 1);
if (!out)
return NULL;
for (i = 0; i <= len; ++i) {
if (i == len || in[i] == ',') {
if (i - start > 255) {
OPENSSL_free(out);
return NULL;
}
out[start] = (unsigned char)(i - start);
start = i + 1;
} else
out[i + 1] = in[i];
}
*outlen = (unsigned char)(len + 1);
return out;
}
#endif /* ndef OPENSSL_NO_TLSEXT */
void print_cert_checks(BIO *bio, X509 *x,
const char *checkhost,
const char *checkemail, const char *checkip)
{
if (x == NULL)
return;
if (checkhost) {
BIO_printf(bio, "Hostname %s does%s match certificate\n",
checkhost, X509_check_host(x, checkhost, 0, 0, NULL) == 1
? "" : " NOT");
}
if (checkemail) {
BIO_printf(bio, "Email %s does%s match certificate\n",
checkemail, X509_check_email(x, checkemail, 0,
0) ? "" : " NOT");
}
if (checkip) {
BIO_printf(bio, "IP %s does%s match certificate\n",
checkip, X509_check_ip_asc(x, checkip, 0) ? "" : " NOT");
}
}
/* Get first http URL from a DIST_POINT structure */
static const char *get_dp_url(DIST_POINT *dp)
{
GENERAL_NAMES *gens;
GENERAL_NAME *gen;
int i, gtype;
ASN1_STRING *uri;
if (!dp->distpoint || dp->distpoint->type != 0)
return NULL;
gens = dp->distpoint->name.fullname;
for (i = 0; i < sk_GENERAL_NAME_num(gens); i++) {
gen = sk_GENERAL_NAME_value(gens, i);
uri = GENERAL_NAME_get0_value(gen, &gtype);
if (gtype == GEN_URI && ASN1_STRING_length(uri) > 6) {
char *uptr = (char *)ASN1_STRING_data(uri);
if (!strncmp(uptr, "http://", 7))
return uptr;
}
}
return NULL;
}
/*
* Look through a CRLDP structure and attempt to find an http URL to
* downloads a CRL from.
*/
static X509_CRL *load_crl_crldp(STACK_OF(DIST_POINT) *crldp)
{
int i;
const char *urlptr = NULL;
for (i = 0; i < sk_DIST_POINT_num(crldp); i++) {
DIST_POINT *dp = sk_DIST_POINT_value(crldp, i);
urlptr = get_dp_url(dp);
if (urlptr)
return load_crl(urlptr, FORMAT_HTTP);
}
return NULL;
}
/*
* Example of downloading CRLs from CRLDP: not usable for real world as it
* always downloads, doesn't support non-blocking I/O and doesn't cache
* anything.
*/
static STACK_OF(X509_CRL) *crls_http_cb(X509_STORE_CTX *ctx, X509_NAME *nm)
{
X509 *x;
STACK_OF(X509_CRL) *crls = NULL;
X509_CRL *crl;
STACK_OF(DIST_POINT) *crldp;
x = X509_STORE_CTX_get_current_cert(ctx);
crldp = X509_get_ext_d2i(x, NID_crl_distribution_points, NULL, NULL);
crl = load_crl_crldp(crldp);
sk_DIST_POINT_pop_free(crldp, DIST_POINT_free);
if (!crl)
return NULL;
crls = sk_X509_CRL_new_null();
sk_X509_CRL_push(crls, crl);
/* Try to download delta CRL */
crldp = X509_get_ext_d2i(x, NID_freshest_crl, NULL, NULL);
crl = load_crl_crldp(crldp);
sk_DIST_POINT_pop_free(crldp, DIST_POINT_free);
if (crl)
sk_X509_CRL_push(crls, crl);
return crls;
}
void store_setup_crl_download(X509_STORE *st)
{
X509_STORE_set_lookup_crls_cb(st, crls_http_cb);
}
/*
* Platform-specific sections
*/
#if defined(_WIN32)
# ifdef fileno
# undef fileno
# define fileno(a) (int)_fileno(a)
# endif
# include <windows.h>
# include <tchar.h>
static int WIN32_rename(const char *from, const char *to)
{
TCHAR *tfrom = NULL, *tto;
DWORD err;
int ret = 0;
if (sizeof(TCHAR) == 1) {
tfrom = (TCHAR *)from;
tto = (TCHAR *)to;
} else { /* UNICODE path */
size_t i, flen = strlen(from) + 1, tlen = strlen(to) + 1;
tfrom = (TCHAR *)malloc(sizeof(TCHAR) * (flen + tlen));
if (tfrom == NULL)
goto err;
tto = tfrom + flen;
# if !defined(_WIN32_WCE) || _WIN32_WCE>=101
if (!MultiByteToWideChar(CP_ACP, 0, from, flen, (WCHAR *)tfrom, flen))
# endif
for (i = 0; i < flen; i++)
tfrom[i] = (TCHAR)from[i];
# if !defined(_WIN32_WCE) || _WIN32_WCE>=101
if (!MultiByteToWideChar(CP_ACP, 0, to, tlen, (WCHAR *)tto, tlen))
# endif
for (i = 0; i < tlen; i++)
tto[i] = (TCHAR)to[i];
}
if (MoveFile(tfrom, tto))
goto ok;
err = GetLastError();
if (err == ERROR_ALREADY_EXISTS || err == ERROR_FILE_EXISTS) {
if (DeleteFile(tto) && MoveFile(tfrom, tto))
goto ok;
err = GetLastError();
}
if (err == ERROR_FILE_NOT_FOUND || err == ERROR_PATH_NOT_FOUND)
errno = ENOENT;
else if (err == ERROR_ACCESS_DENIED)
errno = EACCES;
else
errno = EINVAL; /* we could map more codes... */
err:
ret = -1;
ok:
if (tfrom != NULL && tfrom != (TCHAR *)from)
free(tfrom);
return ret;
}
#endif
/* app_tminterval section */
#if defined(_WIN32)
double app_tminterval(int stop, int usertime)
{
FILETIME now;
double ret = 0;
static ULARGE_INTEGER tmstart;
static int warning = 1;
# ifdef _WIN32_WINNT
static HANDLE proc = NULL;
if (proc == NULL) {
if (check_winnt())
proc = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE,
GetCurrentProcessId());
if (proc == NULL)
proc = (HANDLE) - 1;
}
if (usertime && proc != (HANDLE) - 1) {
FILETIME junk;
GetProcessTimes(proc, &junk, &junk, &junk, &now);
} else
# endif
{
SYSTEMTIME systime;
if (usertime && warning) {
BIO_printf(bio_err, "To get meaningful results, run "
"this program on idle system.\n");
warning = 0;
}
GetSystemTime(&systime);
SystemTimeToFileTime(&systime, &now);
}
if (stop == TM_START) {
tmstart.u.LowPart = now.dwLowDateTime;
tmstart.u.HighPart = now.dwHighDateTime;
} else {
ULARGE_INTEGER tmstop;
tmstop.u.LowPart = now.dwLowDateTime;
tmstop.u.HighPart = now.dwHighDateTime;
ret = (__int64)(tmstop.QuadPart - tmstart.QuadPart) * 1e-7;
}
return (ret);
}
#elif defined(OPENSSL_SYS_NETWARE)
# include <time.h>
double app_tminterval(int stop, int usertime)
{
double ret = 0;
static clock_t tmstart;
static int warning = 1;
if (usertime && warning) {
BIO_printf(bio_err, "To get meaningful results, run "
"this program on idle system.\n");
warning = 0;
}
if (stop == TM_START)
tmstart = clock();
else
ret = (clock() - tmstart) / (double)CLOCKS_PER_SEC;
return (ret);
}
#elif defined(OPENSSL_SYSTEM_VXWORKS)
# include <time.h>
double app_tminterval(int stop, int usertime)
{
double ret = 0;
# ifdef CLOCK_REALTIME
static struct timespec tmstart;
struct timespec now;
# else
static unsigned long tmstart;
unsigned long now;
# endif
static int warning = 1;
if (usertime && warning) {
BIO_printf(bio_err, "To get meaningful results, run "
"this program on idle system.\n");
warning = 0;
}
# ifdef CLOCK_REALTIME
clock_gettime(CLOCK_REALTIME, &now);
if (stop == TM_START)
tmstart = now;
else
ret = ((now.tv_sec + now.tv_nsec * 1e-9)
- (tmstart.tv_sec + tmstart.tv_nsec * 1e-9));
# else
now = tickGet();
if (stop == TM_START)
tmstart = now;
else
ret = (now - tmstart) / (double)sysClkRateGet();
# endif
return (ret);
}
#elif defined(OPENSSL_SYSTEM_VMS)
# include <time.h>
# include <times.h>
double app_tminterval(int stop, int usertime)
{
static clock_t tmstart;
double ret = 0;
clock_t now;
# ifdef __TMS
struct tms rus;
now = times(&rus);
if (usertime)
now = rus.tms_utime;
# else
if (usertime)
now = clock(); /* sum of user and kernel times */
else {
struct timeval tv;
gettimeofday(&tv, NULL);
now = (clock_t)((unsigned long long)tv.tv_sec * CLK_TCK +
(unsigned long long)tv.tv_usec * (1000000 / CLK_TCK)
);
}
# endif
if (stop == TM_START)
tmstart = now;
else
ret = (now - tmstart) / (double)(CLK_TCK);
return (ret);
}
#elif defined(_SC_CLK_TCK) /* by means of unistd.h */
# include <sys/times.h>
double app_tminterval(int stop, int usertime)
{
double ret = 0;
struct tms rus;
clock_t now = times(&rus);
static clock_t tmstart;
if (usertime)
now = rus.tms_utime;
if (stop == TM_START)
tmstart = now;
else {
long int tck = sysconf(_SC_CLK_TCK);
ret = (now - tmstart) / (double)tck;
}
return (ret);
}
#else
# include <sys/time.h>
# include <sys/resource.h>
double app_tminterval(int stop, int usertime)
{
double ret = 0;
struct rusage rus;
struct timeval now;
static struct timeval tmstart;
if (usertime)
getrusage(RUSAGE_SELF, &rus), now = rus.ru_utime;
else
gettimeofday(&now, NULL);
if (stop == TM_START)
tmstart = now;
else
ret = ((now.tv_sec + now.tv_usec * 1e-6)
- (tmstart.tv_sec + tmstart.tv_usec * 1e-6));
return ret;
}
#endif
/* app_isdir section */
#ifdef _WIN32
int app_isdir(const char *name)
{
HANDLE hList;
WIN32_FIND_DATA FileData;
# if defined(UNICODE) || defined(_UNICODE)
size_t i, len_0 = strlen(name) + 1;
if (len_0 > sizeof(FileData.cFileName) / sizeof(FileData.cFileName[0]))
return -1;
# if !defined(_WIN32_WCE) || _WIN32_WCE>=101
if (!MultiByteToWideChar
(CP_ACP, 0, name, len_0, FileData.cFileName, len_0))
# endif
for (i = 0; i < len_0; i++)
FileData.cFileName[i] = (WCHAR)name[i];
hList = FindFirstFile(FileData.cFileName, &FileData);
# else
hList = FindFirstFile(name, &FileData);
# endif
if (hList == INVALID_HANDLE_VALUE)
return -1;
FindClose(hList);
return ((FileData.dwFileAttributes & 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 app_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
/* raw_read|write section */
#if defined(__VMS)
# include "vms_term_sock.h"
static int stdin_sock = -1;
static void close_stdin_sock(void)
{
TerminalSocket (TERM_SOCK_DELETE, &stdin_sock);
}
int fileno_stdin(void)
{
if (stdin_sock == -1) {
TerminalSocket(TERM_SOCK_CREATE, &stdin_sock);
atexit(close_stdin_sock);
}
return stdin_sock;
}
#else
int fileno_stdin(void)
{
return fileno(stdin);
}
#endif
int fileno_stdout(void)
{
return fileno(stdout);
}
#if defined(_WIN32) && defined(STD_INPUT_HANDLE)
int raw_read_stdin(void *buf, int siz)
{
DWORD n;
if (ReadFile(GetStdHandle(STD_INPUT_HANDLE), buf, siz, &n, NULL))
return (n);
else
return (-1);
}
#elif defined(__VMS)
#include <sys/socket.h>
int raw_read_stdin(void *buf, int siz)
{
return recv(fileno_stdin(), buf, siz, 0);
}
#else
int raw_read_stdin(void *buf, int siz)
{
return read(fileno_stdin(), buf, siz);
}
#endif
#if defined(_WIN32) && defined(STD_OUTPUT_HANDLE)
int raw_write_stdout(const void *buf, int siz)
{
DWORD n;
if (WriteFile(GetStdHandle(STD_OUTPUT_HANDLE), buf, siz, &n, NULL))
return (n);
else
return (-1);
}
#else
int raw_write_stdout(const void *buf, int siz)
{
return write(fileno_stdout(), buf, siz);
}
#endif
diff --git a/apps/ca.c b/apps/ca.c
index 9a839969a204..4f9de5492148 100644
--- a/apps/ca.c
+++ b/apps/ca.c
@@ -1,2923 +1,2938 @@
/* apps/ca.c */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
/* The PPKI stuff has been donated by Jeff Barber <jeffb@issl.atl.hp.com> */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <sys/types.h>
#include <openssl/conf.h>
#include <openssl/bio.h>
#include <openssl/err.h>
#include <openssl/bn.h>
#include <openssl/txt_db.h>
#include <openssl/evp.h>
#include <openssl/x509.h>
#include <openssl/x509v3.h>
#include <openssl/objects.h>
#include <openssl/ocsp.h>
#include <openssl/pem.h>
#ifndef W_OK
# ifdef OPENSSL_SYS_VMS
# if defined(__DECC)
# include <unistd.h>
# else
# include <unixlib.h>
# endif
# elif !defined(OPENSSL_SYS_VXWORKS) && !defined(OPENSSL_SYS_WINDOWS) && !defined(OPENSSL_SYS_NETWARE)
# include <sys/file.h>
# endif
#endif
#include "apps.h"
#ifndef W_OK
# define F_OK 0
# define X_OK 1
# define W_OK 2
# define R_OK 4
#endif
#undef PROG
#define PROG ca_main
#define BASE_SECTION "ca"
#define CONFIG_FILE "openssl.cnf"
#define ENV_DEFAULT_CA "default_ca"
#define STRING_MASK "string_mask"
#define UTF8_IN "utf8"
#define ENV_NEW_CERTS_DIR "new_certs_dir"
#define ENV_CERTIFICATE "certificate"
#define ENV_SERIAL "serial"
#define ENV_CRLNUMBER "crlnumber"
#define ENV_PRIVATE_KEY "private_key"
#define ENV_DEFAULT_DAYS "default_days"
#define ENV_DEFAULT_STARTDATE "default_startdate"
#define ENV_DEFAULT_ENDDATE "default_enddate"
#define ENV_DEFAULT_CRL_DAYS "default_crl_days"
#define ENV_DEFAULT_CRL_HOURS "default_crl_hours"
#define ENV_DEFAULT_MD "default_md"
#define ENV_DEFAULT_EMAIL_DN "email_in_dn"
#define ENV_PRESERVE "preserve"
#define ENV_POLICY "policy"
#define ENV_EXTENSIONS "x509_extensions"
#define ENV_CRLEXT "crl_extensions"
#define ENV_MSIE_HACK "msie_hack"
#define ENV_NAMEOPT "name_opt"
#define ENV_CERTOPT "cert_opt"
#define ENV_EXTCOPY "copy_extensions"
#define ENV_UNIQUE_SUBJECT "unique_subject"
#define ENV_DATABASE "database"
/* Additional revocation information types */
#define REV_NONE 0 /* No addditional information */
#define REV_CRL_REASON 1 /* Value is CRL reason code */
#define REV_HOLD 2 /* Value is hold instruction */
#define REV_KEY_COMPROMISE 3 /* Value is cert key compromise time */
#define REV_CA_COMPROMISE 4 /* Value is CA key compromise time */
static const char *ca_usage[] = {
"usage: ca args\n",
"\n",
" -verbose - Talk alot while doing things\n",
" -config file - A config file\n",
" -name arg - The particular CA definition to use\n",
" -gencrl - Generate a new CRL\n",
" -crldays days - Days is when the next CRL is due\n",
" -crlhours hours - Hours is when the next CRL is due\n",
" -startdate YYMMDDHHMMSSZ - certificate validity notBefore\n",
" -enddate YYMMDDHHMMSSZ - certificate validity notAfter (overrides -days)\n",
" -days arg - number of days to certify the certificate for\n",
" -md arg - md to use, one of md2, md5, sha or sha1\n",
" -policy arg - The CA 'policy' to support\n",
" -keyfile arg - private key file\n",
" -keyform arg - private key file format (PEM or ENGINE)\n",
" -key arg - key to decode the private key if it is encrypted\n",
" -cert file - The CA certificate\n",
" -selfsign - sign a certificate with the key associated with it\n",
" -in file - The input PEM encoded certificate request(s)\n",
" -out file - Where to put the output file(s)\n",
" -outdir dir - Where to put output certificates\n",
" -infiles .... - The last argument, requests to process\n",
" -spkac file - File contains DN and signed public key and challenge\n",
" -ss_cert file - File contains a self signed cert to sign\n",
" -preserveDN - Don't re-order the DN\n",
" -noemailDN - Don't add the EMAIL field into certificate' subject\n",
" -batch - Don't ask questions\n",
" -msie_hack - msie modifications to handle all those universal strings\n",
" -revoke file - Revoke a certificate (given in file)\n",
" -subj arg - Use arg instead of request's subject\n",
" -utf8 - input characters are UTF8 (default ASCII)\n",
" -multivalue-rdn - enable support for multivalued RDNs\n",
" -extensions .. - Extension section (override value in config file)\n",
" -extfile file - Configuration file with X509v3 extentions to add\n",
" -crlexts .. - CRL extension section (override value in config file)\n",
#ifndef OPENSSL_NO_ENGINE
" -engine e - use engine e, possibly a hardware device.\n",
#endif
" -status serial - Shows certificate status given the serial number\n",
" -updatedb - Updates db for expired certificates\n",
NULL
};
#ifdef EFENCE
extern int EF_PROTECT_FREE;
extern int EF_PROTECT_BELOW;
extern int EF_ALIGNMENT;
#endif
static void lookup_fail(const char *name, const char *tag);
static int certify(X509 **xret, char *infile, EVP_PKEY *pkey, X509 *x509,
const EVP_MD *dgst, STACK_OF(OPENSSL_STRING) *sigopts,
STACK_OF(CONF_VALUE) *policy, CA_DB *db,
BIGNUM *serial, char *subj, unsigned long chtype,
int multirdn, int email_dn, char *startdate, char *enddate,
long days, int batch, char *ext_sect, CONF *conf,
int verbose, unsigned long certopt, unsigned long nameopt,
int default_op, int ext_copy, int selfsign);
static int certify_cert(X509 **xret, char *infile, EVP_PKEY *pkey, X509 *x509,
const EVP_MD *dgst, STACK_OF(OPENSSL_STRING) *sigopts,
STACK_OF(CONF_VALUE) *policy, CA_DB *db,
BIGNUM *serial, char *subj, unsigned long chtype,
int multirdn, int email_dn, char *startdate,
char *enddate, long days, int batch, char *ext_sect,
CONF *conf, int verbose, unsigned long certopt,
unsigned long nameopt, int default_op, int ext_copy,
ENGINE *e);
static int certify_spkac(X509 **xret, char *infile, EVP_PKEY *pkey,
X509 *x509, const EVP_MD *dgst,
STACK_OF(OPENSSL_STRING) *sigopts,
STACK_OF(CONF_VALUE) *policy, CA_DB *db,
BIGNUM *serial, char *subj, unsigned long chtype,
int multirdn, int email_dn, char *startdate,
char *enddate, long days, char *ext_sect, CONF *conf,
int verbose, unsigned long certopt,
unsigned long nameopt, int default_op, int ext_copy);
static void write_new_certificate(BIO *bp, X509 *x, int output_der,
int notext);
static int do_body(X509 **xret, EVP_PKEY *pkey, X509 *x509,
const EVP_MD *dgst, STACK_OF(OPENSSL_STRING) *sigopts,
STACK_OF(CONF_VALUE) *policy, CA_DB *db, BIGNUM *serial,
char *subj, unsigned long chtype, int multirdn,
int email_dn, char *startdate, char *enddate, long days,
int batch, int verbose, X509_REQ *req, char *ext_sect,
CONF *conf, unsigned long certopt, unsigned long nameopt,
int default_op, int ext_copy, int selfsign);
static int do_revoke(X509 *x509, CA_DB *db, int ext, char *extval);
static int get_certificate_status(const char *ser_status, CA_DB *db);
static int do_updatedb(CA_DB *db);
static int check_time_format(const char *str);
char *make_revocation_str(int rev_type, char *rev_arg);
int make_revoked(X509_REVOKED *rev, const char *str);
int old_entry_print(BIO *bp, ASN1_OBJECT *obj, ASN1_STRING *str);
static CONF *conf = NULL;
static CONF *extconf = NULL;
static char *section = NULL;
static int preserve = 0;
static int msie_hack = 0;
int MAIN(int, char **);
int MAIN(int argc, char **argv)
{
ENGINE *e = NULL;
char *key = NULL, *passargin = NULL;
int create_ser = 0;
int free_key = 0;
int total = 0;
int total_done = 0;
int badops = 0;
int ret = 1;
int email_dn = 1;
int req = 0;
int verbose = 0;
int gencrl = 0;
int dorevoke = 0;
int doupdatedb = 0;
long crldays = 0;
long crlhours = 0;
long crlsec = 0;
long errorline = -1;
char *configfile = NULL;
char *md = NULL;
char *policy = NULL;
char *keyfile = NULL;
char *certfile = NULL;
int keyform = FORMAT_PEM;
char *infile = NULL;
char *spkac_file = NULL;
char *ss_cert_file = NULL;
char *ser_status = NULL;
EVP_PKEY *pkey = NULL;
int output_der = 0;
char *outfile = NULL;
char *outdir = NULL;
char *serialfile = NULL;
char *crlnumberfile = NULL;
char *extensions = NULL;
char *extfile = NULL;
char *subj = NULL;
unsigned long chtype = MBSTRING_ASC;
int multirdn = 0;
char *tmp_email_dn = NULL;
char *crl_ext = NULL;
int rev_type = REV_NONE;
char *rev_arg = NULL;
BIGNUM *serial = NULL;
BIGNUM *crlnumber = NULL;
char *startdate = NULL;
char *enddate = NULL;
long days = 0;
int batch = 0;
int notext = 0;
unsigned long nameopt = 0, certopt = 0;
int default_op = 1;
int ext_copy = EXT_COPY_NONE;
int selfsign = 0;
X509 *x509 = NULL, *x509p = NULL;
X509 *x = NULL;
BIO *in = NULL, *out = NULL, *Sout = NULL, *Cout = NULL;
char *dbfile = NULL;
CA_DB *db = NULL;
X509_CRL *crl = NULL;
X509_REVOKED *r = NULL;
ASN1_TIME *tmptm;
ASN1_INTEGER *tmpser;
char *f;
const char *p;
char *const *pp;
int i, j;
const EVP_MD *dgst = NULL;
STACK_OF(CONF_VALUE) *attribs = NULL;
STACK_OF(X509) *cert_sk = NULL;
STACK_OF(OPENSSL_STRING) *sigopts = NULL;
#undef BSIZE
#define BSIZE 256
MS_STATIC char buf[3][BSIZE];
char *randfile = NULL;
char *engine = NULL;
char *tofree = NULL;
DB_ATTR db_attr;
#ifdef EFENCE
EF_PROTECT_FREE = 1;
EF_PROTECT_BELOW = 1;
EF_ALIGNMENT = 0;
#endif
apps_startup();
conf = NULL;
key = NULL;
section = NULL;
preserve = 0;
msie_hack = 0;
if (bio_err == NULL)
if ((bio_err = BIO_new(BIO_s_file())) != NULL)
BIO_set_fp(bio_err, stderr, BIO_NOCLOSE | BIO_FP_TEXT);
argc--;
argv++;
while (argc >= 1) {
if (strcmp(*argv, "-verbose") == 0)
verbose = 1;
else if (strcmp(*argv, "-config") == 0) {
if (--argc < 1)
goto bad;
configfile = *(++argv);
} else if (strcmp(*argv, "-name") == 0) {
if (--argc < 1)
goto bad;
section = *(++argv);
} else if (strcmp(*argv, "-subj") == 0) {
if (--argc < 1)
goto bad;
subj = *(++argv);
/* preserve=1; */
} else if (strcmp(*argv, "-utf8") == 0)
chtype = MBSTRING_UTF8;
else if (strcmp(*argv, "-create_serial") == 0)
create_ser = 1;
else if (strcmp(*argv, "-multivalue-rdn") == 0)
multirdn = 1;
else if (strcmp(*argv, "-startdate") == 0) {
if (--argc < 1)
goto bad;
startdate = *(++argv);
} else if (strcmp(*argv, "-enddate") == 0) {
if (--argc < 1)
goto bad;
enddate = *(++argv);
} else if (strcmp(*argv, "-days") == 0) {
if (--argc < 1)
goto bad;
days = atoi(*(++argv));
} else if (strcmp(*argv, "-md") == 0) {
if (--argc < 1)
goto bad;
md = *(++argv);
} else if (strcmp(*argv, "-policy") == 0) {
if (--argc < 1)
goto bad;
policy = *(++argv);
} else if (strcmp(*argv, "-keyfile") == 0) {
if (--argc < 1)
goto bad;
keyfile = *(++argv);
} else if (strcmp(*argv, "-keyform") == 0) {
if (--argc < 1)
goto bad;
keyform = str2fmt(*(++argv));
} else if (strcmp(*argv, "-passin") == 0) {
if (--argc < 1)
goto bad;
passargin = *(++argv);
} else if (strcmp(*argv, "-key") == 0) {
if (--argc < 1)
goto bad;
key = *(++argv);
} else if (strcmp(*argv, "-cert") == 0) {
if (--argc < 1)
goto bad;
certfile = *(++argv);
} else if (strcmp(*argv, "-selfsign") == 0)
selfsign = 1;
else if (strcmp(*argv, "-in") == 0) {
if (--argc < 1)
goto bad;
infile = *(++argv);
req = 1;
} else if (strcmp(*argv, "-out") == 0) {
if (--argc < 1)
goto bad;
outfile = *(++argv);
} else if (strcmp(*argv, "-outdir") == 0) {
if (--argc < 1)
goto bad;
outdir = *(++argv);
} else if (strcmp(*argv, "-sigopt") == 0) {
if (--argc < 1)
goto bad;
if (!sigopts)
sigopts = sk_OPENSSL_STRING_new_null();
if (!sigopts || !sk_OPENSSL_STRING_push(sigopts, *(++argv)))
goto bad;
} else if (strcmp(*argv, "-notext") == 0)
notext = 1;
else if (strcmp(*argv, "-batch") == 0)
batch = 1;
else if (strcmp(*argv, "-preserveDN") == 0)
preserve = 1;
else if (strcmp(*argv, "-noemailDN") == 0)
email_dn = 0;
else if (strcmp(*argv, "-gencrl") == 0)
gencrl = 1;
else if (strcmp(*argv, "-msie_hack") == 0)
msie_hack = 1;
else if (strcmp(*argv, "-crldays") == 0) {
if (--argc < 1)
goto bad;
crldays = atol(*(++argv));
} else if (strcmp(*argv, "-crlhours") == 0) {
if (--argc < 1)
goto bad;
crlhours = atol(*(++argv));
} else if (strcmp(*argv, "-crlsec") == 0) {
if (--argc < 1)
goto bad;
crlsec = atol(*(++argv));
} else if (strcmp(*argv, "-infiles") == 0) {
argc--;
argv++;
req = 1;
break;
} else if (strcmp(*argv, "-ss_cert") == 0) {
if (--argc < 1)
goto bad;
ss_cert_file = *(++argv);
req = 1;
} else if (strcmp(*argv, "-spkac") == 0) {
if (--argc < 1)
goto bad;
spkac_file = *(++argv);
req = 1;
} else if (strcmp(*argv, "-revoke") == 0) {
if (--argc < 1)
goto bad;
infile = *(++argv);
dorevoke = 1;
} else if (strcmp(*argv, "-valid") == 0) {
if (--argc < 1)
goto bad;
infile = *(++argv);
dorevoke = 2;
} else if (strcmp(*argv, "-extensions") == 0) {
if (--argc < 1)
goto bad;
extensions = *(++argv);
} else if (strcmp(*argv, "-extfile") == 0) {
if (--argc < 1)
goto bad;
extfile = *(++argv);
} else if (strcmp(*argv, "-status") == 0) {
if (--argc < 1)
goto bad;
ser_status = *(++argv);
} else if (strcmp(*argv, "-updatedb") == 0) {
doupdatedb = 1;
} else if (strcmp(*argv, "-crlexts") == 0) {
if (--argc < 1)
goto bad;
crl_ext = *(++argv);
} else if (strcmp(*argv, "-crl_reason") == 0) {
if (--argc < 1)
goto bad;
rev_arg = *(++argv);
rev_type = REV_CRL_REASON;
} else if (strcmp(*argv, "-crl_hold") == 0) {
if (--argc < 1)
goto bad;
rev_arg = *(++argv);
rev_type = REV_HOLD;
} else if (strcmp(*argv, "-crl_compromise") == 0) {
if (--argc < 1)
goto bad;
rev_arg = *(++argv);
rev_type = REV_KEY_COMPROMISE;
} else if (strcmp(*argv, "-crl_CA_compromise") == 0) {
if (--argc < 1)
goto bad;
rev_arg = *(++argv);
rev_type = REV_CA_COMPROMISE;
}
#ifndef OPENSSL_NO_ENGINE
else if (strcmp(*argv, "-engine") == 0) {
if (--argc < 1)
goto bad;
engine = *(++argv);
}
#endif
else {
bad:
BIO_printf(bio_err, "unknown option %s\n", *argv);
badops = 1;
break;
}
argc--;
argv++;
}
if (badops) {
const char **pp2;
for (pp2 = ca_usage; (*pp2 != NULL); pp2++)
BIO_printf(bio_err, "%s", *pp2);
goto err;
}
ERR_load_crypto_strings();
/*****************************************************************/
tofree = NULL;
if (configfile == NULL)
configfile = getenv("OPENSSL_CONF");
if (configfile == NULL)
configfile = getenv("SSLEAY_CONF");
if (configfile == NULL) {
const char *s = X509_get_default_cert_area();
size_t len;
#ifdef OPENSSL_SYS_VMS
len = strlen(s) + sizeof(CONFIG_FILE);
tofree = OPENSSL_malloc(len);
if (!tofree) {
BIO_printf(bio_err, "Out of memory\n");
goto err;
}
strcpy(tofree, s);
#else
len = strlen(s) + sizeof(CONFIG_FILE) + 1;
tofree = OPENSSL_malloc(len);
if (!tofree) {
BIO_printf(bio_err, "Out of memory\n");
goto err;
}
BUF_strlcpy(tofree, s, len);
BUF_strlcat(tofree, "/", len);
#endif
BUF_strlcat(tofree, CONFIG_FILE, len);
configfile = tofree;
}
BIO_printf(bio_err, "Using configuration from %s\n", configfile);
conf = NCONF_new(NULL);
if (NCONF_load(conf, configfile, &errorline) <= 0) {
if (errorline <= 0)
BIO_printf(bio_err, "error loading the config file '%s'\n",
configfile);
else
BIO_printf(bio_err, "error on line %ld of config file '%s'\n",
errorline, configfile);
goto err;
}
if (tofree) {
OPENSSL_free(tofree);
tofree = NULL;
}
if (!load_config(bio_err, conf))
goto err;
e = setup_engine(bio_err, engine, 0);
/* Lets get the config section we are using */
if (section == NULL) {
section = NCONF_get_string(conf, BASE_SECTION, ENV_DEFAULT_CA);
if (section == NULL) {
lookup_fail(BASE_SECTION, ENV_DEFAULT_CA);
goto err;
}
}
if (conf != NULL) {
p = NCONF_get_string(conf, NULL, "oid_file");
if (p == NULL)
ERR_clear_error();
if (p != NULL) {
BIO *oid_bio;
oid_bio = BIO_new_file(p, "r");
if (oid_bio == NULL) {
/*-
BIO_printf(bio_err,"problems opening %s for extra oid's\n",p);
ERR_print_errors(bio_err);
*/
ERR_clear_error();
} else {
OBJ_create_objects(oid_bio);
BIO_free(oid_bio);
}
}
if (!add_oid_section(bio_err, conf)) {
ERR_print_errors(bio_err);
goto err;
}
}
randfile = NCONF_get_string(conf, BASE_SECTION, "RANDFILE");
if (randfile == NULL)
ERR_clear_error();
app_RAND_load_file(randfile, bio_err, 0);
f = NCONF_get_string(conf, section, STRING_MASK);
if (!f)
ERR_clear_error();
if (f && !ASN1_STRING_set_default_mask_asc(f)) {
BIO_printf(bio_err, "Invalid global string mask setting %s\n", f);
goto err;
}
if (chtype != MBSTRING_UTF8) {
f = NCONF_get_string(conf, section, UTF8_IN);
if (!f)
ERR_clear_error();
else if (!strcmp(f, "yes"))
chtype = MBSTRING_UTF8;
}
db_attr.unique_subject = 1;
p = NCONF_get_string(conf, section, ENV_UNIQUE_SUBJECT);
if (p) {
#ifdef RL_DEBUG
BIO_printf(bio_err, "DEBUG: unique_subject = \"%s\"\n", p);
#endif
db_attr.unique_subject = parse_yesno(p, 1);
} else
ERR_clear_error();
#ifdef RL_DEBUG
if (!p)
BIO_printf(bio_err, "DEBUG: unique_subject undefined\n");
#endif
#ifdef RL_DEBUG
BIO_printf(bio_err, "DEBUG: configured unique_subject is %d\n",
db_attr.unique_subject);
#endif
in = BIO_new(BIO_s_file());
out = BIO_new(BIO_s_file());
Sout = BIO_new(BIO_s_file());
Cout = BIO_new(BIO_s_file());
if ((in == NULL) || (out == NULL) || (Sout == NULL) || (Cout == NULL)) {
ERR_print_errors(bio_err);
goto err;
}
/*****************************************************************/
/* report status of cert with serial number given on command line */
if (ser_status) {
if ((dbfile = NCONF_get_string(conf, section, ENV_DATABASE)) == NULL) {
lookup_fail(section, ENV_DATABASE);
goto err;
}
db = load_index(dbfile, &db_attr);
if (db == NULL)
goto err;
if (!index_index(db))
goto err;
if (get_certificate_status(ser_status, db) != 1)
BIO_printf(bio_err, "Error verifying serial %s!\n", ser_status);
goto err;
}
/*****************************************************************/
/* we definitely need a private key, so let's get it */
if ((keyfile == NULL) && ((keyfile = NCONF_get_string(conf,
section,
ENV_PRIVATE_KEY)) ==
NULL)) {
lookup_fail(section, ENV_PRIVATE_KEY);
goto err;
}
if (!key) {
free_key = 1;
if (!app_passwd(bio_err, passargin, NULL, &key, NULL)) {
BIO_printf(bio_err, "Error getting password\n");
goto err;
}
}
pkey = load_key(bio_err, keyfile, keyform, 0, key, e, "CA private key");
if (key)
OPENSSL_cleanse(key, strlen(key));
if (pkey == NULL) {
/* load_key() has already printed an appropriate message */
goto err;
}
/*****************************************************************/
/* we need a certificate */
if (!selfsign || spkac_file || ss_cert_file || gencrl) {
if ((certfile == NULL)
&& ((certfile = NCONF_get_string(conf,
section,
ENV_CERTIFICATE)) == NULL)) {
lookup_fail(section, ENV_CERTIFICATE);
goto err;
}
x509 = load_cert(bio_err, certfile, FORMAT_PEM, NULL, e,
"CA certificate");
if (x509 == NULL)
goto err;
if (!X509_check_private_key(x509, pkey)) {
BIO_printf(bio_err,
"CA certificate and CA private key do not match\n");
goto err;
}
}
if (!selfsign)
x509p = x509;
f = NCONF_get_string(conf, BASE_SECTION, ENV_PRESERVE);
if (f == NULL)
ERR_clear_error();
if ((f != NULL) && ((*f == 'y') || (*f == 'Y')))
preserve = 1;
f = NCONF_get_string(conf, BASE_SECTION, ENV_MSIE_HACK);
if (f == NULL)
ERR_clear_error();
if ((f != NULL) && ((*f == 'y') || (*f == 'Y')))
msie_hack = 1;
f = NCONF_get_string(conf, section, ENV_NAMEOPT);
if (f) {
if (!set_name_ex(&nameopt, f)) {
BIO_printf(bio_err, "Invalid name options: \"%s\"\n", f);
goto err;
}
default_op = 0;
} else
ERR_clear_error();
f = NCONF_get_string(conf, section, ENV_CERTOPT);
if (f) {
if (!set_cert_ex(&certopt, f)) {
BIO_printf(bio_err, "Invalid certificate options: \"%s\"\n", f);
goto err;
}
default_op = 0;
} else
ERR_clear_error();
f = NCONF_get_string(conf, section, ENV_EXTCOPY);
if (f) {
if (!set_ext_copy(&ext_copy, f)) {
BIO_printf(bio_err, "Invalid extension copy option: \"%s\"\n", f);
goto err;
}
} else
ERR_clear_error();
/*****************************************************************/
/* lookup where to write new certificates */
if ((outdir == NULL) && (req)) {
if ((outdir = NCONF_get_string(conf, section, ENV_NEW_CERTS_DIR))
== NULL) {
BIO_printf(bio_err,
"there needs to be defined a directory for new certificate to be placed in\n");
goto err;
}
#ifndef OPENSSL_SYS_VMS
/*
* outdir is a directory spec, but access() for VMS demands a
* filename. In any case, stat(), below, will catch the problem if
* outdir is not a directory spec, and the fopen() or open() will
* catch an error if there is no write access.
*
* Presumably, this problem could also be solved by using the DEC C
* routines to convert the directory syntax to Unixly, and give that
* to access(). However, time's too short to do that just now.
*/
# ifndef _WIN32
if (access(outdir, R_OK | W_OK | X_OK) != 0)
# else
if (_access(outdir, R_OK | W_OK | X_OK) != 0)
# endif
{
BIO_printf(bio_err, "I am unable to access the %s directory\n",
outdir);
perror(outdir);
goto err;
}
if (app_isdir(outdir) <= 0) {
BIO_printf(bio_err, "%s need to be a directory\n", outdir);
perror(outdir);
goto err;
}
#endif
}
/*****************************************************************/
/* we need to load the database file */
if ((dbfile = NCONF_get_string(conf, section, ENV_DATABASE)) == NULL) {
lookup_fail(section, ENV_DATABASE);
goto err;
}
db = load_index(dbfile, &db_attr);
if (db == NULL)
goto err;
/* Lets check some fields */
for (i = 0; i < sk_OPENSSL_PSTRING_num(db->db->data); i++) {
pp = sk_OPENSSL_PSTRING_value(db->db->data, i);
if ((pp[DB_type][0] != DB_TYPE_REV) && (pp[DB_rev_date][0] != '\0')) {
BIO_printf(bio_err,
"entry %d: not revoked yet, but has a revocation date\n",
i + 1);
goto err;
}
if ((pp[DB_type][0] == DB_TYPE_REV) &&
!make_revoked(NULL, pp[DB_rev_date])) {
BIO_printf(bio_err, " in entry %d\n", i + 1);
goto err;
}
if (!check_time_format((char *)pp[DB_exp_date])) {
BIO_printf(bio_err, "entry %d: invalid expiry date\n", i + 1);
goto err;
}
p = pp[DB_serial];
j = strlen(p);
if (*p == '-') {
p++;
j--;
}
if ((j & 1) || (j < 2)) {
BIO_printf(bio_err, "entry %d: bad serial number length (%d)\n",
i + 1, j);
goto err;
}
while (*p) {
if (!(((*p >= '0') && (*p <= '9')) ||
((*p >= 'A') && (*p <= 'F')) ||
((*p >= 'a') && (*p <= 'f')))) {
BIO_printf(bio_err,
"entry %d: bad serial number characters, char pos %ld, char is '%c'\n",
i + 1, (long)(p - pp[DB_serial]), *p);
goto err;
}
p++;
}
}
if (verbose) {
BIO_set_fp(out, stdout, BIO_NOCLOSE | BIO_FP_TEXT); /* cannot fail */
#ifdef OPENSSL_SYS_VMS
{
BIO *tmpbio = BIO_new(BIO_f_linebuffer());
out = BIO_push(tmpbio, out);
}
#endif
TXT_DB_write(out, db->db);
BIO_printf(bio_err, "%d entries loaded from the database\n",
sk_OPENSSL_PSTRING_num(db->db->data));
BIO_printf(bio_err, "generating index\n");
}
if (!index_index(db))
goto err;
/*****************************************************************/
/* Update the db file for expired certificates */
if (doupdatedb) {
if (verbose)
BIO_printf(bio_err, "Updating %s ...\n", dbfile);
i = do_updatedb(db);
if (i == -1) {
BIO_printf(bio_err, "Malloc failure\n");
goto err;
} else if (i == 0) {
if (verbose)
BIO_printf(bio_err, "No entries found to mark expired\n");
} else {
if (!save_index(dbfile, "new", db))
goto err;
if (!rotate_index(dbfile, "new", "old"))
goto err;
if (verbose)
BIO_printf(bio_err,
"Done. %d entries marked as expired\n", i);
}
}
/*****************************************************************/
/* Read extentions config file */
if (extfile) {
extconf = NCONF_new(NULL);
if (NCONF_load(extconf, extfile, &errorline) <= 0) {
if (errorline <= 0)
BIO_printf(bio_err, "ERROR: loading the config file '%s'\n",
extfile);
else
BIO_printf(bio_err,
"ERROR: on line %ld of config file '%s'\n",
errorline, extfile);
ret = 1;
goto err;
}
if (verbose)
BIO_printf(bio_err, "Successfully loaded extensions file %s\n",
extfile);
/* We can have sections in the ext file */
if (!extensions
&& !(extensions =
NCONF_get_string(extconf, "default", "extensions")))
extensions = "default";
}
/*****************************************************************/
if (req || gencrl) {
if (outfile != NULL) {
if (BIO_write_filename(Sout, outfile) <= 0) {
perror(outfile);
goto err;
}
} else {
BIO_set_fp(Sout, stdout, BIO_NOCLOSE | BIO_FP_TEXT);
#ifdef OPENSSL_SYS_VMS
{
BIO *tmpbio = BIO_new(BIO_f_linebuffer());
Sout = BIO_push(tmpbio, Sout);
}
#endif
}
}
if ((md == NULL) && ((md = NCONF_get_string(conf,
section,
ENV_DEFAULT_MD)) == NULL)) {
lookup_fail(section, ENV_DEFAULT_MD);
goto err;
}
if (!strcmp(md, "default")) {
int def_nid;
if (EVP_PKEY_get_default_digest_nid(pkey, &def_nid) <= 0) {
BIO_puts(bio_err, "no default digest\n");
goto err;
}
md = (char *)OBJ_nid2sn(def_nid);
}
if ((dgst = EVP_get_digestbyname(md)) == NULL) {
BIO_printf(bio_err, "%s is an unsupported message digest type\n", md);
goto err;
}
if (req) {
if ((email_dn == 1) && ((tmp_email_dn = NCONF_get_string(conf,
section,
ENV_DEFAULT_EMAIL_DN))
!= NULL)) {
if (strcmp(tmp_email_dn, "no") == 0)
email_dn = 0;
}
if (verbose)
BIO_printf(bio_err, "message digest is %s\n",
OBJ_nid2ln(dgst->type));
if ((policy == NULL) && ((policy = NCONF_get_string(conf,
section,
ENV_POLICY)) ==
NULL)) {
lookup_fail(section, ENV_POLICY);
goto err;
}
if (verbose)
BIO_printf(bio_err, "policy is %s\n", policy);
if ((serialfile = NCONF_get_string(conf, section, ENV_SERIAL))
== NULL) {
lookup_fail(section, ENV_SERIAL);
goto err;
}
if (!extconf) {
/*
* no '-extfile' option, so we look for extensions in the main
* configuration file
*/
if (!extensions) {
extensions = NCONF_get_string(conf, section, ENV_EXTENSIONS);
if (!extensions)
ERR_clear_error();
}
if (extensions) {
/* Check syntax of file */
X509V3_CTX ctx;
X509V3_set_ctx_test(&ctx);
X509V3_set_nconf(&ctx, conf);
if (!X509V3_EXT_add_nconf(conf, &ctx, extensions, NULL)) {
BIO_printf(bio_err,
"Error Loading extension section %s\n",
extensions);
ret = 1;
goto err;
}
}
}
if (startdate == NULL) {
startdate = NCONF_get_string(conf, section,
ENV_DEFAULT_STARTDATE);
if (startdate == NULL)
ERR_clear_error();
}
if (startdate && !ASN1_TIME_set_string(NULL, startdate)) {
BIO_printf(bio_err,
"start date is invalid, it should be YYMMDDHHMMSSZ or YYYYMMDDHHMMSSZ\n");
goto err;
}
if (startdate == NULL)
startdate = "today";
if (enddate == NULL) {
enddate = NCONF_get_string(conf, section, ENV_DEFAULT_ENDDATE);
if (enddate == NULL)
ERR_clear_error();
}
if (enddate && !ASN1_TIME_set_string(NULL, enddate)) {
BIO_printf(bio_err,
"end date is invalid, it should be YYMMDDHHMMSSZ or YYYYMMDDHHMMSSZ\n");
goto err;
}
if (days == 0) {
if (!NCONF_get_number(conf, section, ENV_DEFAULT_DAYS, &days))
days = 0;
}
if (!enddate && (days == 0)) {
BIO_printf(bio_err,
"cannot lookup how many days to certify for\n");
goto err;
}
if ((serial = load_serial(serialfile, create_ser, NULL)) == NULL) {
BIO_printf(bio_err, "error while loading serial number\n");
goto err;
}
if (verbose) {
if (BN_is_zero(serial))
BIO_printf(bio_err, "next serial number is 00\n");
else {
if ((f = BN_bn2hex(serial)) == NULL)
goto err;
BIO_printf(bio_err, "next serial number is %s\n", f);
OPENSSL_free(f);
}
}
if ((attribs = NCONF_get_section(conf, policy)) == NULL) {
BIO_printf(bio_err, "unable to find 'section' for %s\n", policy);
goto err;
}
if ((cert_sk = sk_X509_new_null()) == NULL) {
BIO_printf(bio_err, "Memory allocation failure\n");
goto err;
}
if (spkac_file != NULL) {
total++;
j = certify_spkac(&x, spkac_file, pkey, x509, dgst, sigopts,
attribs, db, serial, subj, chtype, multirdn,
email_dn, startdate, enddate, days, extensions,
conf, verbose, certopt, nameopt, default_op,
ext_copy);
if (j < 0)
goto err;
if (j > 0) {
total_done++;
BIO_printf(bio_err, "\n");
if (!BN_add_word(serial, 1))
goto err;
if (!sk_X509_push(cert_sk, x)) {
BIO_printf(bio_err, "Memory allocation failure\n");
goto err;
}
if (outfile) {
output_der = 1;
batch = 1;
}
}
}
if (ss_cert_file != NULL) {
total++;
j = certify_cert(&x, ss_cert_file, pkey, x509, dgst, sigopts,
attribs,
db, serial, subj, chtype, multirdn, email_dn,
startdate, enddate, days, batch, extensions,
conf, verbose, certopt, nameopt, default_op,
ext_copy, e);
if (j < 0)
goto err;
if (j > 0) {
total_done++;
BIO_printf(bio_err, "\n");
if (!BN_add_word(serial, 1))
goto err;
if (!sk_X509_push(cert_sk, x)) {
BIO_printf(bio_err, "Memory allocation failure\n");
goto err;
}
}
}
if (infile != NULL) {
total++;
j = certify(&x, infile, pkey, x509p, dgst, sigopts, attribs, db,
serial, subj, chtype, multirdn, email_dn, startdate,
enddate, days, batch, extensions, conf, verbose,
certopt, nameopt, default_op, ext_copy, selfsign);
if (j < 0)
goto err;
if (j > 0) {
total_done++;
BIO_printf(bio_err, "\n");
if (!BN_add_word(serial, 1))
goto err;
if (!sk_X509_push(cert_sk, x)) {
BIO_printf(bio_err, "Memory allocation failure\n");
goto err;
}
}
}
for (i = 0; i < argc; i++) {
total++;
j = certify(&x, argv[i], pkey, x509p, dgst, sigopts, attribs, db,
serial, subj, chtype, multirdn, email_dn, startdate,
enddate, days, batch, extensions, conf, verbose,
certopt, nameopt, default_op, ext_copy, selfsign);
if (j < 0)
goto err;
if (j > 0) {
total_done++;
BIO_printf(bio_err, "\n");
if (!BN_add_word(serial, 1))
goto err;
if (!sk_X509_push(cert_sk, x)) {
BIO_printf(bio_err, "Memory allocation failure\n");
goto err;
}
}
}
/*
* we have a stack of newly certified certificates and a data base
* and serial number that need updating
*/
if (sk_X509_num(cert_sk) > 0) {
if (!batch) {
BIO_printf(bio_err,
"\n%d out of %d certificate requests certified, commit? [y/n]",
total_done, total);
(void)BIO_flush(bio_err);
buf[0][0] = '\0';
if (!fgets(buf[0], 10, stdin)) {
BIO_printf(bio_err,
"CERTIFICATION CANCELED: I/O error\n");
ret = 0;
goto err;
}
if ((buf[0][0] != 'y') && (buf[0][0] != 'Y')) {
BIO_printf(bio_err, "CERTIFICATION CANCELED\n");
ret = 0;
goto err;
}
}
BIO_printf(bio_err, "Write out database with %d new entries\n",
sk_X509_num(cert_sk));
if (!save_serial(serialfile, "new", serial, NULL))
goto err;
if (!save_index(dbfile, "new", db))
goto err;
}
if (verbose)
BIO_printf(bio_err, "writing new certificates\n");
for (i = 0; i < sk_X509_num(cert_sk); i++) {
int k;
char *n;
x = sk_X509_value(cert_sk, i);
j = x->cert_info->serialNumber->length;
p = (const char *)x->cert_info->serialNumber->data;
if (strlen(outdir) >= (size_t)(j ? BSIZE - j * 2 - 6 : BSIZE - 8)) {
BIO_printf(bio_err, "certificate file name too long\n");
goto err;
}
strcpy(buf[2], outdir);
#ifndef OPENSSL_SYS_VMS
BUF_strlcat(buf[2], "/", sizeof(buf[2]));
#endif
n = (char *)&(buf[2][strlen(buf[2])]);
if (j > 0) {
for (k = 0; k < j; k++) {
if (n >= &(buf[2][sizeof(buf[2])]))
break;
BIO_snprintf(n,
&buf[2][0] + sizeof(buf[2]) - n,
"%02X", (unsigned char)*(p++));
n += 2;
}
} else {
*(n++) = '0';
*(n++) = '0';
}
*(n++) = '.';
*(n++) = 'p';
*(n++) = 'e';
*(n++) = 'm';
*n = '\0';
if (verbose)
BIO_printf(bio_err, "writing %s\n", buf[2]);
if (BIO_write_filename(Cout, buf[2]) <= 0) {
perror(buf[2]);
goto err;
}
write_new_certificate(Cout, x, 0, notext);
write_new_certificate(Sout, x, output_der, notext);
}
if (sk_X509_num(cert_sk)) {
/* Rename the database and the serial file */
if (!rotate_serial(serialfile, "new", "old"))
goto err;
if (!rotate_index(dbfile, "new", "old"))
goto err;
BIO_printf(bio_err, "Data Base Updated\n");
}
}
/*****************************************************************/
if (gencrl) {
int crl_v2 = 0;
if (!crl_ext) {
crl_ext = NCONF_get_string(conf, section, ENV_CRLEXT);
if (!crl_ext)
ERR_clear_error();
}
if (crl_ext) {
/* Check syntax of file */
X509V3_CTX ctx;
X509V3_set_ctx_test(&ctx);
X509V3_set_nconf(&ctx, conf);
if (!X509V3_EXT_add_nconf(conf, &ctx, crl_ext, NULL)) {
BIO_printf(bio_err,
"Error Loading CRL extension section %s\n",
crl_ext);
ret = 1;
goto err;
}
}
if ((crlnumberfile = NCONF_get_string(conf, section, ENV_CRLNUMBER))
!= NULL)
if ((crlnumber = load_serial(crlnumberfile, 0, NULL)) == NULL) {
BIO_printf(bio_err, "error while loading CRL number\n");
goto err;
}
if (!crldays && !crlhours && !crlsec) {
if (!NCONF_get_number(conf, section,
ENV_DEFAULT_CRL_DAYS, &crldays))
crldays = 0;
if (!NCONF_get_number(conf, section,
ENV_DEFAULT_CRL_HOURS, &crlhours))
crlhours = 0;
ERR_clear_error();
}
if ((crldays == 0) && (crlhours == 0) && (crlsec == 0)) {
BIO_printf(bio_err,
"cannot lookup how long until the next CRL is issued\n");
goto err;
}
if (verbose)
BIO_printf(bio_err, "making CRL\n");
if ((crl = X509_CRL_new()) == NULL)
goto err;
if (!X509_CRL_set_issuer_name(crl, X509_get_subject_name(x509)))
goto err;
tmptm = ASN1_TIME_new();
if (!tmptm)
goto err;
X509_gmtime_adj(tmptm, 0);
X509_CRL_set_lastUpdate(crl, tmptm);
if (!X509_time_adj_ex(tmptm, crldays, crlhours * 60 * 60 + crlsec,
NULL)) {
BIO_puts(bio_err, "error setting CRL nextUpdate\n");
goto err;
}
X509_CRL_set_nextUpdate(crl, tmptm);
ASN1_TIME_free(tmptm);
for (i = 0; i < sk_OPENSSL_PSTRING_num(db->db->data); i++) {
pp = sk_OPENSSL_PSTRING_value(db->db->data, i);
if (pp[DB_type][0] == DB_TYPE_REV) {
if ((r = X509_REVOKED_new()) == NULL)
goto err;
j = make_revoked(r, pp[DB_rev_date]);
if (!j)
goto err;
if (j == 2)
crl_v2 = 1;
if (!BN_hex2bn(&serial, pp[DB_serial]))
goto err;
tmpser = BN_to_ASN1_INTEGER(serial, NULL);
BN_free(serial);
serial = NULL;
if (!tmpser)
goto err;
X509_REVOKED_set_serialNumber(r, tmpser);
ASN1_INTEGER_free(tmpser);
X509_CRL_add0_revoked(crl, r);
}
}
/*
* sort the data so it will be written in serial number order
*/
X509_CRL_sort(crl);
/* we now have a CRL */
if (verbose)
BIO_printf(bio_err, "signing CRL\n");
/* Add any extensions asked for */
if (crl_ext || crlnumberfile != NULL) {
X509V3_CTX crlctx;
X509V3_set_ctx(&crlctx, x509, NULL, NULL, crl, 0);
X509V3_set_nconf(&crlctx, conf);
if (crl_ext)
if (!X509V3_EXT_CRL_add_nconf(conf, &crlctx, crl_ext, crl))
goto err;
if (crlnumberfile != NULL) {
tmpser = BN_to_ASN1_INTEGER(crlnumber, NULL);
if (!tmpser)
goto err;
X509_CRL_add1_ext_i2d(crl, NID_crl_number, tmpser, 0, 0);
ASN1_INTEGER_free(tmpser);
crl_v2 = 1;
if (!BN_add_word(crlnumber, 1))
goto err;
}
}
if (crl_ext || crl_v2) {
if (!X509_CRL_set_version(crl, 1))
goto err; /* version 2 CRL */
}
/* we have a CRL number that need updating */
if (crlnumberfile != NULL)
if (!save_serial(crlnumberfile, "new", crlnumber, NULL))
goto err;
if (crlnumber) {
BN_free(crlnumber);
crlnumber = NULL;
}
if (!do_X509_CRL_sign(bio_err, crl, pkey, dgst, sigopts))
goto err;
PEM_write_bio_X509_CRL(Sout, crl);
if (crlnumberfile != NULL) /* Rename the crlnumber file */
if (!rotate_serial(crlnumberfile, "new", "old"))
goto err;
}
/*****************************************************************/
if (dorevoke) {
if (infile == NULL) {
BIO_printf(bio_err, "no input files\n");
goto err;
} else {
X509 *revcert;
revcert = load_cert(bio_err, infile, FORMAT_PEM, NULL, e, infile);
if (revcert == NULL)
goto err;
if (dorevoke == 2)
rev_type = -1;
j = do_revoke(revcert, db, rev_type, rev_arg);
if (j <= 0)
goto err;
X509_free(revcert);
if (!save_index(dbfile, "new", db))
goto err;
if (!rotate_index(dbfile, "new", "old"))
goto err;
BIO_printf(bio_err, "Data Base Updated\n");
}
}
/*****************************************************************/
ret = 0;
err:
if (tofree)
OPENSSL_free(tofree);
BIO_free_all(Cout);
BIO_free_all(Sout);
BIO_free_all(out);
BIO_free_all(in);
if (cert_sk)
sk_X509_pop_free(cert_sk, X509_free);
if (ret)
ERR_print_errors(bio_err);
app_RAND_write_file(randfile, bio_err);
if (free_key && key)
OPENSSL_free(key);
BN_free(serial);
BN_free(crlnumber);
free_index(db);
if (sigopts)
sk_OPENSSL_STRING_free(sigopts);
EVP_PKEY_free(pkey);
if (x509)
X509_free(x509);
X509_CRL_free(crl);
NCONF_free(conf);
NCONF_free(extconf);
release_engine(e);
OBJ_cleanup();
apps_shutdown();
OPENSSL_EXIT(ret);
}
static void lookup_fail(const char *name, const char *tag)
{
BIO_printf(bio_err, "variable lookup failed for %s::%s\n", name, tag);
}
static int certify(X509 **xret, char *infile, EVP_PKEY *pkey, X509 *x509,
const EVP_MD *dgst, STACK_OF(OPENSSL_STRING) *sigopts,
STACK_OF(CONF_VALUE) *policy, CA_DB *db,
BIGNUM *serial, char *subj, unsigned long chtype,
int multirdn, int email_dn, char *startdate, char *enddate,
long days, int batch, char *ext_sect, CONF *lconf,
int verbose, unsigned long certopt, unsigned long nameopt,
int default_op, int ext_copy, int selfsign)
{
X509_REQ *req = NULL;
BIO *in = NULL;
EVP_PKEY *pktmp = NULL;
int ok = -1, i;
in = BIO_new(BIO_s_file());
if (BIO_read_filename(in, infile) <= 0) {
perror(infile);
goto err;
}
if ((req = PEM_read_bio_X509_REQ(in, NULL, NULL, NULL)) == NULL) {
BIO_printf(bio_err, "Error reading certificate request in %s\n",
infile);
goto err;
}
if (verbose)
X509_REQ_print(bio_err, req);
BIO_printf(bio_err, "Check that the request matches the signature\n");
if (selfsign && !X509_REQ_check_private_key(req, pkey)) {
BIO_printf(bio_err,
"Certificate request and CA private key do not match\n");
ok = 0;
goto err;
}
if ((pktmp = X509_REQ_get_pubkey(req)) == NULL) {
BIO_printf(bio_err, "error unpacking public key\n");
goto err;
}
i = X509_REQ_verify(req, pktmp);
EVP_PKEY_free(pktmp);
if (i < 0) {
ok = 0;
BIO_printf(bio_err, "Signature verification problems....\n");
ERR_print_errors(bio_err);
goto err;
}
if (i == 0) {
ok = 0;
BIO_printf(bio_err,
"Signature did not match the certificate request\n");
ERR_print_errors(bio_err);
goto err;
} else
BIO_printf(bio_err, "Signature ok\n");
ok = do_body(xret, pkey, x509, dgst, sigopts, policy, db, serial, subj,
chtype, multirdn, email_dn, startdate, enddate, days, batch,
verbose, req, ext_sect, lconf, certopt, nameopt, default_op,
ext_copy, selfsign);
err:
if (req != NULL)
X509_REQ_free(req);
if (in != NULL)
BIO_free(in);
return (ok);
}
static int certify_cert(X509 **xret, char *infile, EVP_PKEY *pkey, X509 *x509,
const EVP_MD *dgst, STACK_OF(OPENSSL_STRING) *sigopts,
STACK_OF(CONF_VALUE) *policy, CA_DB *db,
BIGNUM *serial, char *subj, unsigned long chtype,
int multirdn, int email_dn, char *startdate,
char *enddate, long days, int batch, char *ext_sect,
CONF *lconf, int verbose, unsigned long certopt,
unsigned long nameopt, int default_op, int ext_copy,
ENGINE *e)
{
X509 *req = NULL;
X509_REQ *rreq = NULL;
EVP_PKEY *pktmp = NULL;
int ok = -1, i;
if ((req =
load_cert(bio_err, infile, FORMAT_PEM, NULL, e, infile)) == NULL)
goto err;
if (verbose)
X509_print(bio_err, req);
BIO_printf(bio_err, "Check that the request matches the signature\n");
if ((pktmp = X509_get_pubkey(req)) == NULL) {
BIO_printf(bio_err, "error unpacking public key\n");
goto err;
}
i = X509_verify(req, pktmp);
EVP_PKEY_free(pktmp);
if (i < 0) {
ok = 0;
BIO_printf(bio_err, "Signature verification problems....\n");
goto err;
}
if (i == 0) {
ok = 0;
BIO_printf(bio_err, "Signature did not match the certificate\n");
goto err;
} else
BIO_printf(bio_err, "Signature ok\n");
if ((rreq = X509_to_X509_REQ(req, NULL, EVP_md5())) == NULL)
goto err;
ok = do_body(xret, pkey, x509, dgst, sigopts, policy, db, serial, subj,
chtype, multirdn, email_dn, startdate, enddate, days, batch,
verbose, rreq, ext_sect, lconf, certopt, nameopt, default_op,
ext_copy, 0);
err:
if (rreq != NULL)
X509_REQ_free(rreq);
if (req != NULL)
X509_free(req);
return (ok);
}
static int do_body(X509 **xret, EVP_PKEY *pkey, X509 *x509,
const EVP_MD *dgst, STACK_OF(OPENSSL_STRING) *sigopts,
STACK_OF(CONF_VALUE) *policy, CA_DB *db, BIGNUM *serial,
char *subj, unsigned long chtype, int multirdn,
int email_dn, char *startdate, char *enddate, long days,
int batch, int verbose, X509_REQ *req, char *ext_sect,
CONF *lconf, unsigned long certopt, unsigned long nameopt,
int default_op, int ext_copy, int selfsign)
{
- X509_NAME *name = NULL, *CAname = NULL, *subject = NULL, *dn_subject =
- NULL;
+ X509_NAME *name = NULL, *CAname = NULL, *subject = NULL;
ASN1_UTCTIME *tm, *tmptm;
ASN1_STRING *str, *str2;
ASN1_OBJECT *obj;
X509 *ret = NULL;
X509_CINF *ci;
X509_NAME_ENTRY *ne;
X509_NAME_ENTRY *tne, *push;
EVP_PKEY *pktmp;
int ok = -1, i, j, last, nid;
const char *p;
CONF_VALUE *cv;
OPENSSL_STRING row[DB_NUMBER];
OPENSSL_STRING *irow = NULL;
OPENSSL_STRING *rrow = NULL;
char buf[25];
tmptm = ASN1_UTCTIME_new();
if (tmptm == NULL) {
BIO_printf(bio_err, "malloc error\n");
return (0);
}
for (i = 0; i < DB_NUMBER; i++)
row[i] = NULL;
if (subj) {
X509_NAME *n = parse_name(subj, chtype, multirdn);
if (!n) {
ERR_print_errors(bio_err);
goto err;
}
X509_REQ_set_subject_name(req, n);
req->req_info->enc.modified = 1;
X509_NAME_free(n);
}
if (default_op)
BIO_printf(bio_err,
"The Subject's Distinguished Name is as follows\n");
name = X509_REQ_get_subject_name(req);
for (i = 0; i < X509_NAME_entry_count(name); i++) {
ne = X509_NAME_get_entry(name, i);
str = X509_NAME_ENTRY_get_data(ne);
obj = X509_NAME_ENTRY_get_object(ne);
if (msie_hack) {
/* assume all type should be strings */
nid = OBJ_obj2nid(ne->object);
if (str->type == V_ASN1_UNIVERSALSTRING)
ASN1_UNIVERSALSTRING_to_string(str);
if ((str->type == V_ASN1_IA5STRING) &&
(nid != NID_pkcs9_emailAddress))
str->type = V_ASN1_T61STRING;
if ((nid == NID_pkcs9_emailAddress) &&
(str->type == V_ASN1_PRINTABLESTRING))
str->type = V_ASN1_IA5STRING;
}
/* If no EMAIL is wanted in the subject */
if ((OBJ_obj2nid(obj) == NID_pkcs9_emailAddress) && (!email_dn))
continue;
/* check some things */
if ((OBJ_obj2nid(obj) == NID_pkcs9_emailAddress) &&
(str->type != V_ASN1_IA5STRING)) {
BIO_printf(bio_err,
"\nemailAddress type needs to be of type IA5STRING\n");
goto err;
}
if ((str->type != V_ASN1_BMPSTRING)
&& (str->type != V_ASN1_UTF8STRING)) {
j = ASN1_PRINTABLE_type(str->data, str->length);
if (((j == V_ASN1_T61STRING) &&
(str->type != V_ASN1_T61STRING)) ||
((j == V_ASN1_IA5STRING) &&
(str->type == V_ASN1_PRINTABLESTRING))) {
BIO_printf(bio_err,
"\nThe string contains characters that are illegal for the ASN.1 type\n");
goto err;
}
}
if (default_op)
old_entry_print(bio_err, obj, str);
}
/* Ok, now we check the 'policy' stuff. */
if ((subject = X509_NAME_new()) == NULL) {
BIO_printf(bio_err, "Memory allocation failure\n");
goto err;
}
/* take a copy of the issuer name before we mess with it. */
if (selfsign)
CAname = X509_NAME_dup(name);
else
CAname = X509_NAME_dup(x509->cert_info->subject);
if (CAname == NULL)
goto err;
str = str2 = NULL;
for (i = 0; i < sk_CONF_VALUE_num(policy); i++) {
cv = sk_CONF_VALUE_value(policy, i); /* get the object id */
if ((j = OBJ_txt2nid(cv->name)) == NID_undef) {
BIO_printf(bio_err,
"%s:unknown object type in 'policy' configuration\n",
cv->name);
goto err;
}
obj = OBJ_nid2obj(j);
last = -1;
for (;;) {
/* lookup the object in the supplied name list */
j = X509_NAME_get_index_by_OBJ(name, obj, last);
if (j < 0) {
if (last != -1)
break;
tne = NULL;
} else {
tne = X509_NAME_get_entry(name, j);
}
last = j;
/* depending on the 'policy', decide what to do. */
push = NULL;
if (strcmp(cv->value, "optional") == 0) {
if (tne != NULL)
push = tne;
} else if (strcmp(cv->value, "supplied") == 0) {
if (tne == NULL) {
BIO_printf(bio_err,
"The %s field needed to be supplied and was missing\n",
cv->name);
goto err;
} else
push = tne;
} else if (strcmp(cv->value, "match") == 0) {
int last2;
if (tne == NULL) {
BIO_printf(bio_err,
"The mandatory %s field was missing\n",
cv->name);
goto err;
}
last2 = -1;
again2:
j = X509_NAME_get_index_by_OBJ(CAname, obj, last2);
if ((j < 0) && (last2 == -1)) {
BIO_printf(bio_err,
"The %s field does not exist in the CA certificate,\nthe 'policy' is misconfigured\n",
cv->name);
goto err;
}
if (j >= 0) {
push = X509_NAME_get_entry(CAname, j);
str = X509_NAME_ENTRY_get_data(tne);
str2 = X509_NAME_ENTRY_get_data(push);
last2 = j;
if (ASN1_STRING_cmp(str, str2) != 0)
goto again2;
}
if (j < 0) {
BIO_printf(bio_err,
"The %s field needed to be the same in the\nCA certificate (%s) and the request (%s)\n",
cv->name,
((str2 == NULL) ? "NULL" : (char *)str2->data),
((str == NULL) ? "NULL" : (char *)str->data));
goto err;
}
} else {
BIO_printf(bio_err,
"%s:invalid type in 'policy' configuration\n",
cv->value);
goto err;
}
if (push != NULL) {
if (!X509_NAME_add_entry(subject, push, -1, 0)) {
- if (push != NULL)
- X509_NAME_ENTRY_free(push);
BIO_printf(bio_err, "Memory allocation failure\n");
goto err;
}
}
if (j < 0)
break;
}
}
if (preserve) {
X509_NAME_free(subject);
/* subject=X509_NAME_dup(X509_REQ_get_subject_name(req)); */
subject = X509_NAME_dup(name);
if (subject == NULL)
goto err;
}
- if (verbose)
- BIO_printf(bio_err,
- "The subject name appears to be ok, checking data base for clashes\n");
-
- /* Build the correct Subject if no e-mail is wanted in the subject */
- /*
- * and add it later on because of the method extensions are added
- * (altName)
- */
-
- if (email_dn)
- dn_subject = subject;
- else {
- X509_NAME_ENTRY *tmpne;
- /*
- * Its best to dup the subject DN and then delete any email addresses
- * because this retains its structure.
- */
- if (!(dn_subject = X509_NAME_dup(subject))) {
- BIO_printf(bio_err, "Memory allocation failure\n");
- goto err;
- }
- while ((i = X509_NAME_get_index_by_NID(dn_subject,
- NID_pkcs9_emailAddress,
- -1)) >= 0) {
- tmpne = X509_NAME_get_entry(dn_subject, i);
- X509_NAME_delete_entry(dn_subject, i);
- X509_NAME_ENTRY_free(tmpne);
- }
- }
-
- if (BN_is_zero(serial))
- row[DB_serial] = BUF_strdup("00");
- else
- row[DB_serial] = BN_bn2hex(serial);
- if (row[DB_serial] == NULL) {
- BIO_printf(bio_err, "Memory allocation failure\n");
- goto err;
- }
-
- if (db->attributes.unique_subject) {
- OPENSSL_STRING *crow = row;
-
- rrow = TXT_DB_get_by_index(db->db, DB_name, crow);
- if (rrow != NULL) {
- BIO_printf(bio_err,
- "ERROR:There is already a certificate for %s\n",
- row[DB_name]);
- }
- }
- if (rrow == NULL) {
- rrow = TXT_DB_get_by_index(db->db, DB_serial, row);
- if (rrow != NULL) {
- BIO_printf(bio_err,
- "ERROR:Serial number %s has already been issued,\n",
- row[DB_serial]);
- BIO_printf(bio_err,
- " check the database/serial_file for corruption\n");
- }
- }
-
- if (rrow != NULL) {
- BIO_printf(bio_err, "The matching entry has the following details\n");
- if (rrow[DB_type][0] == 'E')
- p = "Expired";
- else if (rrow[DB_type][0] == 'R')
- p = "Revoked";
- else if (rrow[DB_type][0] == 'V')
- p = "Valid";
- else
- p = "\ninvalid type, Data base error\n";
- BIO_printf(bio_err, "Type :%s\n", p);;
- if (rrow[DB_type][0] == 'R') {
- p = rrow[DB_exp_date];
- if (p == NULL)
- p = "undef";
- BIO_printf(bio_err, "Was revoked on:%s\n", p);
- }
- p = rrow[DB_exp_date];
- if (p == NULL)
- p = "undef";
- BIO_printf(bio_err, "Expires on :%s\n", p);
- p = rrow[DB_serial];
- if (p == NULL)
- p = "undef";
- BIO_printf(bio_err, "Serial Number :%s\n", p);
- p = rrow[DB_file];
- if (p == NULL)
- p = "undef";
- BIO_printf(bio_err, "File name :%s\n", p);
- p = rrow[DB_name];
- if (p == NULL)
- p = "undef";
- BIO_printf(bio_err, "Subject Name :%s\n", p);
- ok = -1; /* This is now a 'bad' error. */
- goto err;
- }
-
/* We are now totally happy, lets make and sign the certificate */
if (verbose)
BIO_printf(bio_err,
"Everything appears to be ok, creating and signing the certificate\n");
if ((ret = X509_new()) == NULL)
goto err;
ci = ret->cert_info;
#ifdef X509_V3
/* Make it an X509 v3 certificate. */
if (!X509_set_version(ret, 2))
goto err;
#endif
if (BN_to_ASN1_INTEGER(serial, ci->serialNumber) == NULL)
goto err;
if (selfsign) {
if (!X509_set_issuer_name(ret, subject))
goto err;
} else {
if (!X509_set_issuer_name(ret, X509_get_subject_name(x509)))
goto err;
}
if (strcmp(startdate, "today") == 0)
X509_gmtime_adj(X509_get_notBefore(ret), 0);
else
ASN1_TIME_set_string(X509_get_notBefore(ret), startdate);
if (enddate == NULL)
X509_time_adj_ex(X509_get_notAfter(ret), days, 0, NULL);
else {
int tdays;
ASN1_TIME_set_string(X509_get_notAfter(ret), enddate);
ASN1_TIME_diff(&tdays, NULL, NULL, X509_get_notAfter(ret));
days = tdays;
}
if (!X509_set_subject_name(ret, subject))
goto err;
pktmp = X509_REQ_get_pubkey(req);
i = X509_set_pubkey(ret, pktmp);
EVP_PKEY_free(pktmp);
if (!i)
goto err;
/* Lets add the extensions, if there are any */
if (ext_sect) {
X509V3_CTX ctx;
/*
* Free the current entries if any, there should not be any I believe
*/
if (ci->extensions != NULL)
sk_X509_EXTENSION_pop_free(ci->extensions, X509_EXTENSION_free);
ci->extensions = NULL;
/* Initialize the context structure */
if (selfsign)
X509V3_set_ctx(&ctx, ret, ret, req, NULL, 0);
else
X509V3_set_ctx(&ctx, x509, ret, req, NULL, 0);
if (extconf) {
if (verbose)
BIO_printf(bio_err, "Extra configuration file found\n");
/* Use the extconf configuration db LHASH */
X509V3_set_nconf(&ctx, extconf);
/* Test the structure (needed?) */
/* X509V3_set_ctx_test(&ctx); */
/* Adds exts contained in the configuration file */
if (!X509V3_EXT_add_nconf(extconf, &ctx, ext_sect, ret)) {
BIO_printf(bio_err,
"ERROR: adding extensions in section %s\n",
ext_sect);
ERR_print_errors(bio_err);
goto err;
}
if (verbose)
BIO_printf(bio_err,
"Successfully added extensions from file.\n");
} else if (ext_sect) {
/* We found extensions to be set from config file */
X509V3_set_nconf(&ctx, lconf);
if (!X509V3_EXT_add_nconf(lconf, &ctx, ext_sect, ret)) {
BIO_printf(bio_err,
"ERROR: adding extensions in section %s\n",
ext_sect);
ERR_print_errors(bio_err);
goto err;
}
if (verbose)
BIO_printf(bio_err,
"Successfully added extensions from config\n");
}
}
/* Copy extensions from request (if any) */
if (!copy_extensions(ret, req, ext_copy)) {
BIO_printf(bio_err, "ERROR: adding extensions from request\n");
ERR_print_errors(bio_err);
goto err;
}
{
STACK_OF(X509_EXTENSION) *exts = ci->extensions;
if (exts != NULL && sk_X509_EXTENSION_num(exts) > 0)
/* Make it an X509 v3 certificate. */
if (!X509_set_version(ret, 2))
goto err;
}
- /* Set the right value for the noemailDN option */
- if (email_dn == 0) {
- if (!X509_set_subject_name(ret, dn_subject))
+ if (verbose)
+ BIO_printf(bio_err,
+ "The subject name appears to be ok, checking data base for clashes\n");
+
+ /* Build the correct Subject if no e-mail is wanted in the subject */
+
+ if (!email_dn) {
+ X509_NAME_ENTRY *tmpne;
+ X509_NAME *dn_subject;
+
+ /*
+ * Its best to dup the subject DN and then delete any email addresses
+ * because this retains its structure.
+ */
+ if (!(dn_subject = X509_NAME_dup(subject))) {
+ BIO_printf(bio_err, "Memory allocation failure\n");
+ goto err;
+ }
+ while ((i = X509_NAME_get_index_by_NID(dn_subject,
+ NID_pkcs9_emailAddress,
+ -1)) >= 0) {
+ tmpne = X509_NAME_get_entry(dn_subject, i);
+ X509_NAME_delete_entry(dn_subject, i);
+ X509_NAME_ENTRY_free(tmpne);
+ }
+
+ if (!X509_set_subject_name(ret, dn_subject)) {
+ X509_NAME_free(dn_subject);
+ goto err;
+ }
+ X509_NAME_free(dn_subject);
+ }
+
+ row[DB_name] = X509_NAME_oneline(X509_get_subject_name(ret), NULL, 0);
+ if (row[DB_name] == NULL) {
+ BIO_printf(bio_err, "Memory allocation failure\n");
+ goto err;
+ }
+
+ if (BN_is_zero(serial))
+ row[DB_serial] = BUF_strdup("00");
+ else
+ row[DB_serial] = BN_bn2hex(serial);
+ if (row[DB_serial] == NULL) {
+ BIO_printf(bio_err, "Memory allocation failure\n");
+ goto err;
+ }
+
+ if (row[DB_name][0] == '\0') {
+ /*
+ * An empty subject! We'll use the serial number instead. If
+ * unique_subject is in use then we don't want different entries with
+ * empty subjects matching each other.
+ */
+ OPENSSL_free(row[DB_name]);
+ row[DB_name] = OPENSSL_strdup(row[DB_serial]);
+ if (row[DB_name] == NULL) {
+ BIO_printf(bio_err, "Memory allocation failure\n");
goto err;
+ }
+ }
+
+ if (db->attributes.unique_subject) {
+ OPENSSL_STRING *crow = row;
+
+ rrow = TXT_DB_get_by_index(db->db, DB_name, crow);
+ if (rrow != NULL) {
+ BIO_printf(bio_err,
+ "ERROR:There is already a certificate for %s\n",
+ row[DB_name]);
+ }
+ }
+ if (rrow == NULL) {
+ rrow = TXT_DB_get_by_index(db->db, DB_serial, row);
+ if (rrow != NULL) {
+ BIO_printf(bio_err,
+ "ERROR:Serial number %s has already been issued,\n",
+ row[DB_serial]);
+ BIO_printf(bio_err,
+ " check the database/serial_file for corruption\n");
+ }
+ }
+
+ if (rrow != NULL) {
+ BIO_printf(bio_err, "The matching entry has the following details\n");
+ if (rrow[DB_type][0] == 'E')
+ p = "Expired";
+ else if (rrow[DB_type][0] == 'R')
+ p = "Revoked";
+ else if (rrow[DB_type][0] == 'V')
+ p = "Valid";
+ else
+ p = "\ninvalid type, Data base error\n";
+ BIO_printf(bio_err, "Type :%s\n", p);;
+ if (rrow[DB_type][0] == 'R') {
+ p = rrow[DB_exp_date];
+ if (p == NULL)
+ p = "undef";
+ BIO_printf(bio_err, "Was revoked on:%s\n", p);
+ }
+ p = rrow[DB_exp_date];
+ if (p == NULL)
+ p = "undef";
+ BIO_printf(bio_err, "Expires on :%s\n", p);
+ p = rrow[DB_serial];
+ if (p == NULL)
+ p = "undef";
+ BIO_printf(bio_err, "Serial Number :%s\n", p);
+ p = rrow[DB_file];
+ if (p == NULL)
+ p = "undef";
+ BIO_printf(bio_err, "File name :%s\n", p);
+ p = rrow[DB_name];
+ if (p == NULL)
+ p = "undef";
+ BIO_printf(bio_err, "Subject Name :%s\n", p);
+ ok = -1; /* This is now a 'bad' error. */
+ goto err;
}
if (!default_op) {
BIO_printf(bio_err, "Certificate Details:\n");
/*
* Never print signature details because signature not present
*/
certopt |= X509_FLAG_NO_SIGDUMP | X509_FLAG_NO_SIGNAME;
X509_print_ex(bio_err, ret, nameopt, certopt);
}
BIO_printf(bio_err, "Certificate is to be certified until ");
ASN1_TIME_print(bio_err, X509_get_notAfter(ret));
if (days)
BIO_printf(bio_err, " (%ld days)", days);
BIO_printf(bio_err, "\n");
if (!batch) {
BIO_printf(bio_err, "Sign the certificate? [y/n]:");
(void)BIO_flush(bio_err);
buf[0] = '\0';
if (!fgets(buf, sizeof(buf) - 1, stdin)) {
BIO_printf(bio_err,
"CERTIFICATE WILL NOT BE CERTIFIED: I/O error\n");
ok = 0;
goto err;
}
if (!((buf[0] == 'y') || (buf[0] == 'Y'))) {
BIO_printf(bio_err, "CERTIFICATE WILL NOT BE CERTIFIED\n");
ok = 0;
goto err;
}
}
pktmp = X509_get_pubkey(ret);
if (EVP_PKEY_missing_parameters(pktmp) &&
!EVP_PKEY_missing_parameters(pkey))
EVP_PKEY_copy_parameters(pktmp, pkey);
EVP_PKEY_free(pktmp);
if (!do_X509_sign(bio_err, ret, pkey, dgst, sigopts))
goto err;
/* We now just add it to the database */
tm = X509_get_notAfter(ret);
row[DB_type] = OPENSSL_malloc(2);
row[DB_exp_date] = OPENSSL_malloc(tm->length + 1);
row[DB_rev_date] = OPENSSL_malloc(1);
row[DB_file] = OPENSSL_malloc(8);
- row[DB_name] = X509_NAME_oneline(X509_get_subject_name(ret), NULL, 0);
if ((row[DB_type] == NULL) || (row[DB_exp_date] == NULL) ||
(row[DB_rev_date] == NULL) ||
- (row[DB_file] == NULL) || (row[DB_name] == NULL)) {
+ (row[DB_file] == NULL)) {
BIO_printf(bio_err, "Memory allocation failure\n");
goto err;
}
memcpy(row[DB_exp_date], tm->data, tm->length);
row[DB_exp_date][tm->length] = '\0';
row[DB_rev_date][0] = '\0';
strcpy(row[DB_file], "unknown");
row[DB_type][0] = 'V';
row[DB_type][1] = '\0';
if ((irow =
(char **)OPENSSL_malloc(sizeof(char *) * (DB_NUMBER + 1))) == NULL) {
BIO_printf(bio_err, "Memory allocation failure\n");
goto err;
}
for (i = 0; i < DB_NUMBER; i++)
irow[i] = row[i];
irow[DB_NUMBER] = NULL;
if (!TXT_DB_insert(db->db, irow)) {
BIO_printf(bio_err, "failed to update database\n");
BIO_printf(bio_err, "TXT_DB error number %ld\n", db->db->error);
goto err;
}
irow = NULL;
ok = 1;
err:
- if (irow != NULL) {
+ if (ok != 1) {
for (i = 0; i < DB_NUMBER; i++)
OPENSSL_free(row[i]);
- OPENSSL_free(irow);
}
+ OPENSSL_free(irow);
if (CAname != NULL)
X509_NAME_free(CAname);
if (subject != NULL)
X509_NAME_free(subject);
- if ((dn_subject != NULL) && !email_dn)
- X509_NAME_free(dn_subject);
if (tmptm != NULL)
ASN1_UTCTIME_free(tmptm);
if (ok <= 0) {
if (ret != NULL)
X509_free(ret);
ret = NULL;
} else
*xret = ret;
return (ok);
}
static void write_new_certificate(BIO *bp, X509 *x, int output_der,
int notext)
{
if (output_der) {
(void)i2d_X509_bio(bp, x);
return;
}
#if 0
/* ??? Not needed since X509_print prints all this stuff anyway */
f = X509_NAME_oneline(X509_get_issuer_name(x), buf, 256);
BIO_printf(bp, "issuer :%s\n", f);
f = X509_NAME_oneline(X509_get_subject_name(x), buf, 256);
BIO_printf(bp, "subject:%s\n", f);
BIO_puts(bp, "serial :");
i2a_ASN1_INTEGER(bp, x->cert_info->serialNumber);
BIO_puts(bp, "\n\n");
#endif
if (!notext)
X509_print(bp, x);
PEM_write_bio_X509(bp, x);
}
static int certify_spkac(X509 **xret, char *infile, EVP_PKEY *pkey,
X509 *x509, const EVP_MD *dgst,
STACK_OF(OPENSSL_STRING) *sigopts,
STACK_OF(CONF_VALUE) *policy, CA_DB *db,
BIGNUM *serial, char *subj, unsigned long chtype,
int multirdn, int email_dn, char *startdate,
char *enddate, long days, char *ext_sect,
CONF *lconf, int verbose, unsigned long certopt,
unsigned long nameopt, int default_op, int ext_copy)
{
STACK_OF(CONF_VALUE) *sk = NULL;
LHASH_OF(CONF_VALUE) *parms = NULL;
X509_REQ *req = NULL;
CONF_VALUE *cv = NULL;
NETSCAPE_SPKI *spki = NULL;
X509_REQ_INFO *ri;
char *type, *buf;
EVP_PKEY *pktmp = NULL;
X509_NAME *n = NULL;
X509_NAME_ENTRY *ne = NULL;
int ok = -1, i, j;
long errline;
int nid;
/*
* Load input file into a hash table. (This is just an easy
* way to read and parse the file, then put it into a convenient
* STACK format).
*/
parms = CONF_load(NULL, infile, &errline);
if (parms == NULL) {
BIO_printf(bio_err, "error on line %ld of %s\n", errline, infile);
ERR_print_errors(bio_err);
goto err;
}
sk = CONF_get_section(parms, "default");
if (sk_CONF_VALUE_num(sk) == 0) {
BIO_printf(bio_err, "no name/value pairs found in %s\n", infile);
goto err;
}
/*
* Now create a dummy X509 request structure. We don't actually
* have an X509 request, but we have many of the components
* (a public key, various DN components). The idea is that we
* put these components into the right X509 request structure
* and we can use the same code as if you had a real X509 request.
*/
req = X509_REQ_new();
if (req == NULL) {
ERR_print_errors(bio_err);
goto err;
}
/*
* Build up the subject name set.
*/
ri = req->req_info;
n = ri->subject;
for (i = 0;; i++) {
if (sk_CONF_VALUE_num(sk) <= i)
break;
cv = sk_CONF_VALUE_value(sk, i);
type = cv->name;
/*
* Skip past any leading X. X: X, etc to allow for multiple instances
*/
for (buf = cv->name; *buf; buf++)
if ((*buf == ':') || (*buf == ',') || (*buf == '.')) {
buf++;
if (*buf)
type = buf;
break;
}
buf = cv->value;
if ((nid = OBJ_txt2nid(type)) == NID_undef) {
if (strcmp(type, "SPKAC") == 0) {
spki = NETSCAPE_SPKI_b64_decode(cv->value, -1);
if (spki == NULL) {
BIO_printf(bio_err,
"unable to load Netscape SPKAC structure\n");
ERR_print_errors(bio_err);
goto err;
}
}
continue;
}
if (!X509_NAME_add_entry_by_NID(n, nid, chtype,
(unsigned char *)buf, -1, -1, 0))
goto err;
}
if (spki == NULL) {
BIO_printf(bio_err, "Netscape SPKAC structure not found in %s\n",
infile);
goto err;
}
/*
* Now extract the key from the SPKI structure.
*/
BIO_printf(bio_err,
"Check that the SPKAC request matches the signature\n");
if ((pktmp = NETSCAPE_SPKI_get_pubkey(spki)) == NULL) {
BIO_printf(bio_err, "error unpacking SPKAC public key\n");
goto err;
}
j = NETSCAPE_SPKI_verify(spki, pktmp);
if (j <= 0) {
EVP_PKEY_free(pktmp);
BIO_printf(bio_err,
"signature verification failed on SPKAC public key\n");
goto err;
}
BIO_printf(bio_err, "Signature ok\n");
X509_REQ_set_pubkey(req, pktmp);
EVP_PKEY_free(pktmp);
ok = do_body(xret, pkey, x509, dgst, sigopts, policy, db, serial, subj,
chtype, multirdn, email_dn, startdate, enddate, days, 1,
verbose, req, ext_sect, lconf, certopt, nameopt, default_op,
ext_copy, 0);
err:
if (req != NULL)
X509_REQ_free(req);
if (parms != NULL)
CONF_free(parms);
if (spki != NULL)
NETSCAPE_SPKI_free(spki);
if (ne != NULL)
X509_NAME_ENTRY_free(ne);
return (ok);
}
static int check_time_format(const char *str)
{
return ASN1_TIME_set_string(NULL, str);
}
static int do_revoke(X509 *x509, CA_DB *db, int type, char *value)
{
ASN1_UTCTIME *tm = NULL;
char *row[DB_NUMBER], **rrow, **irow;
char *rev_str = NULL;
BIGNUM *bn = NULL;
int ok = -1, i;
for (i = 0; i < DB_NUMBER; i++)
row[i] = NULL;
row[DB_name] = X509_NAME_oneline(X509_get_subject_name(x509), NULL, 0);
bn = ASN1_INTEGER_to_BN(X509_get_serialNumber(x509), NULL);
if (!bn)
goto err;
if (BN_is_zero(bn))
row[DB_serial] = BUF_strdup("00");
else
row[DB_serial] = BN_bn2hex(bn);
BN_free(bn);
+ if (row[DB_name] != NULL && row[DB_name][0] == '\0') {
+ /* Entries with empty Subjects actually use the serial number instead */
+ OPENSSL_free(row[DB_name]);
+ row[DB_name] = OPENSSL_strdup(row[DB_serial]);
+ }
if ((row[DB_name] == NULL) || (row[DB_serial] == NULL)) {
BIO_printf(bio_err, "Memory allocation failure\n");
goto err;
}
/*
* We have to lookup by serial number because name lookup skips revoked
* certs
*/
rrow = TXT_DB_get_by_index(db->db, DB_serial, row);
if (rrow == NULL) {
BIO_printf(bio_err,
"Adding Entry with serial number %s to DB for %s\n",
row[DB_serial], row[DB_name]);
/* We now just add it to the database */
row[DB_type] = (char *)OPENSSL_malloc(2);
tm = X509_get_notAfter(x509);
row[DB_exp_date] = (char *)OPENSSL_malloc(tm->length + 1);
memcpy(row[DB_exp_date], tm->data, tm->length);
row[DB_exp_date][tm->length] = '\0';
row[DB_rev_date] = NULL;
/* row[DB_serial] done already */
row[DB_file] = (char *)OPENSSL_malloc(8);
/* row[DB_name] done already */
if ((row[DB_type] == NULL) || (row[DB_exp_date] == NULL) ||
(row[DB_file] == NULL)) {
BIO_printf(bio_err, "Memory allocation failure\n");
goto err;
}
BUF_strlcpy(row[DB_file], "unknown", 8);
row[DB_type][0] = 'V';
row[DB_type][1] = '\0';
if ((irow =
(char **)OPENSSL_malloc(sizeof(char *) * (DB_NUMBER + 1))) ==
NULL) {
BIO_printf(bio_err, "Memory allocation failure\n");
goto err;
}
for (i = 0; i < DB_NUMBER; i++)
irow[i] = row[i];
irow[DB_NUMBER] = NULL;
if (!TXT_DB_insert(db->db, irow)) {
BIO_printf(bio_err, "failed to update database\n");
BIO_printf(bio_err, "TXT_DB error number %ld\n", db->db->error);
OPENSSL_free(irow);
goto err;
}
for (i = 0; i < DB_NUMBER; i++)
row[i] = NULL;
/* Revoke Certificate */
if (type == -1)
ok = 1;
else
ok = do_revoke(x509, db, type, value);
goto err;
} else if (index_name_cmp_noconst(row, rrow)) {
BIO_printf(bio_err, "ERROR:name does not match %s\n", row[DB_name]);
goto err;
} else if (type == -1) {
BIO_printf(bio_err, "ERROR:Already present, serial number %s\n",
row[DB_serial]);
goto err;
} else if (rrow[DB_type][0] == 'R') {
BIO_printf(bio_err, "ERROR:Already revoked, serial number %s\n",
row[DB_serial]);
goto err;
} else {
BIO_printf(bio_err, "Revoking Certificate %s.\n", rrow[DB_serial]);
rev_str = make_revocation_str(type, value);
if (!rev_str) {
BIO_printf(bio_err, "Error in revocation arguments\n");
goto err;
}
rrow[DB_type][0] = 'R';
rrow[DB_type][1] = '\0';
rrow[DB_rev_date] = rev_str;
}
ok = 1;
err:
for (i = 0; i < DB_NUMBER; i++) {
if (row[i] != NULL)
OPENSSL_free(row[i]);
}
return (ok);
}
static int get_certificate_status(const char *serial, CA_DB *db)
{
char *row[DB_NUMBER], **rrow;
int ok = -1, i;
/* Free Resources */
for (i = 0; i < DB_NUMBER; i++)
row[i] = NULL;
/* Malloc needed char spaces */
row[DB_serial] = OPENSSL_malloc(strlen(serial) + 2);
if (row[DB_serial] == NULL) {
BIO_printf(bio_err, "Malloc failure\n");
goto err;
}
if (strlen(serial) % 2) {
/*
* Set the first char to 0
*/ ;
row[DB_serial][0] = '0';
/* Copy String from serial to row[DB_serial] */
memcpy(row[DB_serial] + 1, serial, strlen(serial));
row[DB_serial][strlen(serial) + 1] = '\0';
} else {
/* Copy String from serial to row[DB_serial] */
memcpy(row[DB_serial], serial, strlen(serial));
row[DB_serial][strlen(serial)] = '\0';
}
/* Make it Upper Case */
for (i = 0; row[DB_serial][i] != '\0'; i++)
row[DB_serial][i] = toupper((unsigned char)row[DB_serial][i]);
ok = 1;
/* Search for the certificate */
rrow = TXT_DB_get_by_index(db->db, DB_serial, row);
if (rrow == NULL) {
BIO_printf(bio_err, "Serial %s not present in db.\n", row[DB_serial]);
ok = -1;
goto err;
} else if (rrow[DB_type][0] == 'V') {
BIO_printf(bio_err, "%s=Valid (%c)\n",
row[DB_serial], rrow[DB_type][0]);
goto err;
} else if (rrow[DB_type][0] == 'R') {
BIO_printf(bio_err, "%s=Revoked (%c)\n",
row[DB_serial], rrow[DB_type][0]);
goto err;
} else if (rrow[DB_type][0] == 'E') {
BIO_printf(bio_err, "%s=Expired (%c)\n",
row[DB_serial], rrow[DB_type][0]);
goto err;
} else if (rrow[DB_type][0] == 'S') {
BIO_printf(bio_err, "%s=Suspended (%c)\n",
row[DB_serial], rrow[DB_type][0]);
goto err;
} else {
BIO_printf(bio_err, "%s=Unknown (%c).\n",
row[DB_serial], rrow[DB_type][0]);
ok = -1;
}
err:
for (i = 0; i < DB_NUMBER; i++) {
if (row[i] != NULL)
OPENSSL_free(row[i]);
}
return (ok);
}
static int do_updatedb(CA_DB *db)
{
ASN1_UTCTIME *a_tm = NULL;
int i, cnt = 0;
int db_y2k, a_y2k; /* flags = 1 if y >= 2000 */
char **rrow, *a_tm_s;
a_tm = ASN1_UTCTIME_new();
if (a_tm == NULL)
return -1;
/* get actual time and make a string */
a_tm = X509_gmtime_adj(a_tm, 0);
a_tm_s = (char *)OPENSSL_malloc(a_tm->length + 1);
if (a_tm_s == NULL) {
cnt = -1;
goto err;
}
memcpy(a_tm_s, a_tm->data, a_tm->length);
a_tm_s[a_tm->length] = '\0';
if (strncmp(a_tm_s, "49", 2) <= 0)
a_y2k = 1;
else
a_y2k = 0;
for (i = 0; i < sk_OPENSSL_PSTRING_num(db->db->data); i++) {
rrow = sk_OPENSSL_PSTRING_value(db->db->data, i);
if (rrow[DB_type][0] == 'V') {
/* ignore entries that are not valid */
if (strncmp(rrow[DB_exp_date], "49", 2) <= 0)
db_y2k = 1;
else
db_y2k = 0;
if (db_y2k == a_y2k) {
/* all on the same y2k side */
if (strcmp(rrow[DB_exp_date], a_tm_s) <= 0) {
rrow[DB_type][0] = 'E';
rrow[DB_type][1] = '\0';
cnt++;
BIO_printf(bio_err, "%s=Expired\n", rrow[DB_serial]);
}
} else if (db_y2k < a_y2k) {
rrow[DB_type][0] = 'E';
rrow[DB_type][1] = '\0';
cnt++;
BIO_printf(bio_err, "%s=Expired\n", rrow[DB_serial]);
}
}
}
err:
ASN1_UTCTIME_free(a_tm);
OPENSSL_free(a_tm_s);
return (cnt);
}
static const char *crl_reasons[] = {
/* CRL reason strings */
"unspecified",
"keyCompromise",
"CACompromise",
"affiliationChanged",
"superseded",
"cessationOfOperation",
"certificateHold",
"removeFromCRL",
/* Additional pseudo reasons */
"holdInstruction",
"keyTime",
"CAkeyTime"
};
#define NUM_REASONS (sizeof(crl_reasons) / sizeof(char *))
/*
* Given revocation information convert to a DB string. The format of the
* string is: revtime[,reason,extra]. Where 'revtime' is the revocation time
* (the current time). 'reason' is the optional CRL reason and 'extra' is any
* additional argument
*/
char *make_revocation_str(int rev_type, char *rev_arg)
{
char *other = NULL, *str;
const char *reason = NULL;
ASN1_OBJECT *otmp;
ASN1_UTCTIME *revtm = NULL;
int i;
switch (rev_type) {
case REV_NONE:
break;
case REV_CRL_REASON:
for (i = 0; i < 8; i++) {
if (!strcasecmp(rev_arg, crl_reasons[i])) {
reason = crl_reasons[i];
break;
}
}
if (reason == NULL) {
BIO_printf(bio_err, "Unknown CRL reason %s\n", rev_arg);
return NULL;
}
break;
case REV_HOLD:
/* Argument is an OID */
otmp = OBJ_txt2obj(rev_arg, 0);
ASN1_OBJECT_free(otmp);
if (otmp == NULL) {
BIO_printf(bio_err, "Invalid object identifier %s\n", rev_arg);
return NULL;
}
reason = "holdInstruction";
other = rev_arg;
break;
case REV_KEY_COMPROMISE:
case REV_CA_COMPROMISE:
/* Argument is the key compromise time */
if (!ASN1_GENERALIZEDTIME_set_string(NULL, rev_arg)) {
BIO_printf(bio_err,
"Invalid time format %s. Need YYYYMMDDHHMMSSZ\n",
rev_arg);
return NULL;
}
other = rev_arg;
if (rev_type == REV_KEY_COMPROMISE)
reason = "keyTime";
else
reason = "CAkeyTime";
break;
}
revtm = X509_gmtime_adj(NULL, 0);
if (!revtm)
return NULL;
i = revtm->length + 1;
if (reason)
i += strlen(reason) + 1;
if (other)
i += strlen(other) + 1;
str = OPENSSL_malloc(i);
if (!str)
return NULL;
BUF_strlcpy(str, (char *)revtm->data, i);
if (reason) {
BUF_strlcat(str, ",", i);
BUF_strlcat(str, reason, i);
}
if (other) {
BUF_strlcat(str, ",", i);
BUF_strlcat(str, other, i);
}
ASN1_UTCTIME_free(revtm);
return str;
}
/*-
* Convert revocation field to X509_REVOKED entry
* return code:
* 0 error
* 1 OK
* 2 OK and some extensions added (i.e. V2 CRL)
*/
int make_revoked(X509_REVOKED *rev, const char *str)
{
char *tmp = NULL;
int reason_code = -1;
int i, ret = 0;
ASN1_OBJECT *hold = NULL;
ASN1_GENERALIZEDTIME *comp_time = NULL;
ASN1_ENUMERATED *rtmp = NULL;
ASN1_TIME *revDate = NULL;
i = unpack_revinfo(&revDate, &reason_code, &hold, &comp_time, str);
if (i == 0)
goto err;
if (rev && !X509_REVOKED_set_revocationDate(rev, revDate))
goto err;
if (rev && (reason_code != OCSP_REVOKED_STATUS_NOSTATUS)) {
rtmp = ASN1_ENUMERATED_new();
if (!rtmp || !ASN1_ENUMERATED_set(rtmp, reason_code))
goto err;
if (!X509_REVOKED_add1_ext_i2d(rev, NID_crl_reason, rtmp, 0, 0))
goto err;
}
if (rev && comp_time) {
if (!X509_REVOKED_add1_ext_i2d
(rev, NID_invalidity_date, comp_time, 0, 0))
goto err;
}
if (rev && hold) {
if (!X509_REVOKED_add1_ext_i2d
(rev, NID_hold_instruction_code, hold, 0, 0))
goto err;
}
if (reason_code != OCSP_REVOKED_STATUS_NOSTATUS)
ret = 2;
else
ret = 1;
err:
if (tmp)
OPENSSL_free(tmp);
ASN1_OBJECT_free(hold);
ASN1_GENERALIZEDTIME_free(comp_time);
ASN1_ENUMERATED_free(rtmp);
ASN1_TIME_free(revDate);
return ret;
}
int old_entry_print(BIO *bp, ASN1_OBJECT *obj, ASN1_STRING *str)
{
char buf[25], *pbuf, *p;
int j;
j = i2a_ASN1_OBJECT(bp, obj);
pbuf = buf;
for (j = 22 - j; j > 0; j--)
*(pbuf++) = ' ';
*(pbuf++) = ':';
*(pbuf++) = '\0';
BIO_puts(bp, buf);
if (str->type == V_ASN1_PRINTABLESTRING)
BIO_printf(bp, "PRINTABLE:'");
else if (str->type == V_ASN1_T61STRING)
BIO_printf(bp, "T61STRING:'");
else if (str->type == V_ASN1_IA5STRING)
BIO_printf(bp, "IA5STRING:'");
else if (str->type == V_ASN1_UNIVERSALSTRING)
BIO_printf(bp, "UNIVERSALSTRING:'");
else
BIO_printf(bp, "ASN.1 %2d:'", str->type);
p = (char *)str->data;
for (j = str->length; j > 0; j--) {
if ((*p >= ' ') && (*p <= '~'))
BIO_printf(bp, "%c", *p);
else if (*p & 0x80)
BIO_printf(bp, "\\0x%02X", *p);
else if ((unsigned char)*p == 0xf7)
BIO_printf(bp, "^?");
else
BIO_printf(bp, "^%c", *p + '@');
p++;
}
BIO_printf(bp, "'\n");
return 1;
}
int unpack_revinfo(ASN1_TIME **prevtm, int *preason, ASN1_OBJECT **phold,
ASN1_GENERALIZEDTIME **pinvtm, const char *str)
{
char *tmp = NULL;
char *rtime_str, *reason_str = NULL, *arg_str = NULL, *p;
int reason_code = -1;
int ret = 0;
unsigned int i;
ASN1_OBJECT *hold = NULL;
ASN1_GENERALIZEDTIME *comp_time = NULL;
tmp = BUF_strdup(str);
if (!tmp) {
BIO_printf(bio_err, "memory allocation failure\n");
goto err;
}
p = strchr(tmp, ',');
rtime_str = tmp;
if (p) {
*p = '\0';
p++;
reason_str = p;
p = strchr(p, ',');
if (p) {
*p = '\0';
arg_str = p + 1;
}
}
if (prevtm) {
*prevtm = ASN1_UTCTIME_new();
if (!*prevtm) {
BIO_printf(bio_err, "memory allocation failure\n");
goto err;
}
if (!ASN1_UTCTIME_set_string(*prevtm, rtime_str)) {
BIO_printf(bio_err, "invalid revocation date %s\n", rtime_str);
goto err;
}
}
if (reason_str) {
for (i = 0; i < NUM_REASONS; i++) {
if (!strcasecmp(reason_str, crl_reasons[i])) {
reason_code = i;
break;
}
}
if (reason_code == OCSP_REVOKED_STATUS_NOSTATUS) {
BIO_printf(bio_err, "invalid reason code %s\n", reason_str);
goto err;
}
if (reason_code == 7)
reason_code = OCSP_REVOKED_STATUS_REMOVEFROMCRL;
else if (reason_code == 8) { /* Hold instruction */
if (!arg_str) {
BIO_printf(bio_err, "missing hold instruction\n");
goto err;
}
reason_code = OCSP_REVOKED_STATUS_CERTIFICATEHOLD;
hold = OBJ_txt2obj(arg_str, 0);
if (!hold) {
BIO_printf(bio_err, "invalid object identifier %s\n",
arg_str);
goto err;
}
if (phold)
*phold = hold;
} else if ((reason_code == 9) || (reason_code == 10)) {
if (!arg_str) {
BIO_printf(bio_err, "missing compromised time\n");
goto err;
}
comp_time = ASN1_GENERALIZEDTIME_new();
if (!comp_time) {
BIO_printf(bio_err, "memory allocation failure\n");
goto err;
}
if (!ASN1_GENERALIZEDTIME_set_string(comp_time, arg_str)) {
BIO_printf(bio_err, "invalid compromised time %s\n", arg_str);
goto err;
}
if (reason_code == 9)
reason_code = OCSP_REVOKED_STATUS_KEYCOMPROMISE;
else
reason_code = OCSP_REVOKED_STATUS_CACOMPROMISE;
}
}
if (preason)
*preason = reason_code;
if (pinvtm)
*pinvtm = comp_time;
else
ASN1_GENERALIZEDTIME_free(comp_time);
ret = 1;
err:
if (tmp)
OPENSSL_free(tmp);
if (!phold)
ASN1_OBJECT_free(hold);
if (!pinvtm)
ASN1_GENERALIZEDTIME_free(comp_time);
return ret;
}
diff --git a/apps/ciphers.c b/apps/ciphers.c
index 66636d2dfd18..4856141f6f2b 100644
--- a/apps/ciphers.c
+++ b/apps/ciphers.c
@@ -1,239 +1,239 @@
/* apps/ciphers.c */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef OPENSSL_NO_STDIO
# define APPS_WIN16
#endif
#include "apps.h"
#include <openssl/err.h>
#include <openssl/ssl.h>
#undef PROG
#define PROG ciphers_main
static const char *ciphers_usage[] = {
"usage: ciphers args\n",
" -v - verbose mode, a textual listing of the SSL/TLS ciphers in OpenSSL\n",
" -V - even more verbose\n",
" -ssl2 - SSL2 mode\n",
" -ssl3 - SSL3 mode\n",
" -tls1 - TLS1 mode\n",
NULL
};
int MAIN(int, char **);
int MAIN(int argc, char **argv)
{
int ret = 1, i;
int verbose = 0, Verbose = 0;
#ifndef OPENSSL_NO_SSL_TRACE
int stdname = 0;
#endif
const char **pp;
const char *p;
int badops = 0;
SSL_CTX *ctx = NULL;
SSL *ssl = NULL;
char *ciphers = NULL;
const SSL_METHOD *meth = NULL;
STACK_OF(SSL_CIPHER) *sk;
char buf[512];
BIO *STDout = NULL;
meth = SSLv23_server_method();
apps_startup();
if (bio_err == NULL)
bio_err = BIO_new_fp(stderr, BIO_NOCLOSE);
STDout = BIO_new_fp(stdout, BIO_NOCLOSE);
#ifdef OPENSSL_SYS_VMS
{
BIO *tmpbio = BIO_new(BIO_f_linebuffer());
STDout = BIO_push(tmpbio, STDout);
}
#endif
if (!load_config(bio_err, NULL))
goto end;
argc--;
argv++;
while (argc >= 1) {
if (strcmp(*argv, "-v") == 0)
verbose = 1;
else if (strcmp(*argv, "-V") == 0)
verbose = Verbose = 1;
#ifndef OPENSSL_NO_SSL_TRACE
else if (strcmp(*argv, "-stdname") == 0)
stdname = verbose = 1;
#endif
#ifndef OPENSSL_NO_SSL2
else if (strcmp(*argv, "-ssl2") == 0)
meth = SSLv2_client_method();
#endif
#ifndef OPENSSL_NO_SSL3
else if (strcmp(*argv, "-ssl3") == 0)
meth = SSLv3_client_method();
#endif
#ifndef OPENSSL_NO_TLS1
else if (strcmp(*argv, "-tls1") == 0)
meth = TLSv1_client_method();
#endif
else if ((strncmp(*argv, "-h", 2) == 0) || (strcmp(*argv, "-?") == 0)) {
badops = 1;
break;
} else {
ciphers = *argv;
}
argc--;
argv++;
}
if (badops) {
for (pp = ciphers_usage; (*pp != NULL); pp++)
BIO_printf(bio_err, "%s", *pp);
goto end;
}
OpenSSL_add_ssl_algorithms();
ctx = SSL_CTX_new(meth);
if (ctx == NULL)
goto err;
if (ciphers != NULL) {
if (!SSL_CTX_set_cipher_list(ctx, ciphers)) {
BIO_printf(bio_err, "Error in cipher list\n");
goto err;
}
}
ssl = SSL_new(ctx);
if (ssl == NULL)
goto err;
if (!verbose) {
for (i = 0;; i++) {
p = SSL_get_cipher_list(ssl, i);
if (p == NULL)
break;
if (i != 0)
BIO_printf(STDout, ":");
BIO_printf(STDout, "%s", p);
}
BIO_printf(STDout, "\n");
} else { /* verbose */
sk = SSL_get_ciphers(ssl);
for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) {
SSL_CIPHER *c;
c = sk_SSL_CIPHER_value(sk, i);
if (Verbose) {
unsigned long id = SSL_CIPHER_get_id(c);
int id0 = (int)(id >> 24);
int id1 = (int)((id >> 16) & 0xffL);
int id2 = (int)((id >> 8) & 0xffL);
int id3 = (int)(id & 0xffL);
if ((id & 0xff000000L) == 0x02000000L) {
/* SSL2 cipher */
BIO_printf(STDout, " 0x%02X,0x%02X,0x%02X - ", id1,
id2, id3);
} else if ((id & 0xff000000L) == 0x03000000L) {
/* SSL3 cipher */
BIO_printf(STDout, " 0x%02X,0x%02X - ", id2,
id3);
} else {
/* whatever */
BIO_printf(STDout, "0x%02X,0x%02X,0x%02X,0x%02X - ", id0,
id1, id2, id3);
}
}
#ifndef OPENSSL_NO_SSL_TRACE
if (stdname) {
const char *nm = SSL_CIPHER_standard_name(c);
if (nm == NULL)
nm = "UNKNOWN";
BIO_printf(STDout, "%s - ", nm);
}
#endif
- BIO_puts(STDout, SSL_CIPHER_description(c, buf, sizeof buf));
+ BIO_puts(STDout, SSL_CIPHER_description(c, buf, sizeof(buf)));
}
}
ret = 0;
if (0) {
err:
SSL_load_error_strings();
ERR_print_errors(bio_err);
}
end:
if (ctx != NULL)
SSL_CTX_free(ctx);
if (ssl != NULL)
SSL_free(ssl);
if (STDout != NULL)
BIO_free_all(STDout);
apps_shutdown();
OPENSSL_EXIT(ret);
}
diff --git a/apps/cms.c b/apps/cms.c
index f9a63bc0d096..de4ba136e8fa 100644
--- a/apps/cms.c
+++ b/apps/cms.c
@@ -1,1354 +1,1358 @@
/* apps/cms.c */
/*
* Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL
* project.
*/
/* ====================================================================
- * Copyright (c) 2008 The OpenSSL Project. All rights reserved.
+ * Copyright (c) 2008-2018 The OpenSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* licensing@OpenSSL.org.
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*/
/* CMS utility function */
#include <stdio.h>
#include <string.h>
#include "apps.h"
#ifndef OPENSSL_NO_CMS
# 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>
# undef PROG
# define PROG cms_main
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(BIO *out, 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 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_CMSOUT (5 | SMIME_IP | SMIME_OP)
# define SMIME_RESIGN (6 | SMIME_IP | SMIME_OP | SMIME_SIGNERS)
# define SMIME_DATAOUT (7 | SMIME_IP)
# define SMIME_DATA_CREATE (8 | SMIME_OP)
# define SMIME_DIGEST_VERIFY (9 | SMIME_IP)
# define SMIME_DIGEST_CREATE (10 | SMIME_OP)
# define SMIME_UNCOMPRESS (11 | SMIME_IP)
# define SMIME_COMPRESS (12 | SMIME_OP)
# define SMIME_ENCRYPTED_DECRYPT (13 | SMIME_IP)
# define SMIME_ENCRYPTED_ENCRYPT (14 | SMIME_OP)
# define SMIME_SIGN_RECEIPT (15 | SMIME_IP | SMIME_OP)
# define SMIME_VERIFY_RECEIPT (16 | SMIME_IP)
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;
};
int MAIN(int, char **);
int MAIN(int argc, char **argv)
{
ENGINE *e = NULL;
int operation = 0;
int ret = 0;
char **args;
const char *inmode = "r", *outmode = "w";
char *infile = NULL, *outfile = NULL, *rctfile = NULL;
char *signerfile = NULL, *recipfile = NULL;
STACK_OF(OPENSSL_STRING) *sksigners = NULL, *skkeys = NULL;
char *certfile = NULL, *keyfile = NULL, *contfile = NULL;
char *certsoutfile = NULL;
const EVP_CIPHER *cipher = NULL, *wrap_cipher = NULL;
CMS_ContentInfo *cms = NULL, *rcms = NULL;
X509_STORE *store = NULL;
X509 *cert = NULL, *recip = NULL, *signer = NULL;
EVP_PKEY *key = NULL;
STACK_OF(X509) *encerts = NULL, *other = NULL;
BIO *in = NULL, *out = NULL, *indata = NULL, *rctin = NULL;
int badarg = 0;
int flags = CMS_DETACHED, noout = 0, print = 0;
int verify_retcode = 0;
int rr_print = 0, rr_allorfirst = -1;
STACK_OF(OPENSSL_STRING) *rr_to = NULL, *rr_from = NULL;
CMS_ReceiptRequest *rr = NULL;
char *to = NULL, *from = NULL, *subject = NULL;
char *CAfile = NULL, *CApath = NULL;
char *passargin = NULL, *passin = NULL;
char *inrand = NULL;
int need_rand = 0;
const EVP_MD *sign_md = NULL;
int informat = FORMAT_SMIME, outformat = FORMAT_SMIME;
int rctformat = FORMAT_SMIME, keyform = FORMAT_PEM;
char *engine = NULL;
unsigned char *secret_key = NULL, *secret_keyid = NULL;
unsigned char *pwri_pass = NULL, *pwri_tmp = NULL;
size_t secret_keylen = 0, secret_keyidlen = 0;
cms_key_param *key_first = NULL, *key_param = NULL;
ASN1_OBJECT *econtent_type = NULL;
X509_VERIFY_PARAM *vpm = NULL;
args = argv + 1;
ret = 1;
apps_startup();
if (bio_err == NULL) {
if ((bio_err = BIO_new(BIO_s_file())) != NULL)
BIO_set_fp(bio_err, stderr, BIO_NOCLOSE | BIO_FP_TEXT);
}
if (!load_config(bio_err, NULL))
goto end;
while (!badarg && *args && *args[0] == '-') {
if (!strcmp(*args, "-encrypt"))
operation = SMIME_ENCRYPT;
else if (!strcmp(*args, "-decrypt"))
operation = SMIME_DECRYPT;
else if (!strcmp(*args, "-sign"))
operation = SMIME_SIGN;
else if (!strcmp(*args, "-sign_receipt"))
operation = SMIME_SIGN_RECEIPT;
else if (!strcmp(*args, "-resign"))
operation = SMIME_RESIGN;
else if (!strcmp(*args, "-verify"))
operation = SMIME_VERIFY;
else if (!strcmp(*args, "-verify_retcode"))
verify_retcode = 1;
else if (!strcmp(*args, "-verify_receipt")) {
operation = SMIME_VERIFY_RECEIPT;
if (!args[1])
goto argerr;
args++;
rctfile = *args;
} else if (!strcmp(*args, "-cmsout"))
operation = SMIME_CMSOUT;
else if (!strcmp(*args, "-data_out"))
operation = SMIME_DATAOUT;
else if (!strcmp(*args, "-data_create"))
operation = SMIME_DATA_CREATE;
else if (!strcmp(*args, "-digest_verify"))
operation = SMIME_DIGEST_VERIFY;
else if (!strcmp(*args, "-digest_create"))
operation = SMIME_DIGEST_CREATE;
else if (!strcmp(*args, "-compress"))
operation = SMIME_COMPRESS;
else if (!strcmp(*args, "-uncompress"))
operation = SMIME_UNCOMPRESS;
else if (!strcmp(*args, "-EncryptedData_decrypt"))
operation = SMIME_ENCRYPTED_DECRYPT;
else if (!strcmp(*args, "-EncryptedData_encrypt"))
operation = SMIME_ENCRYPTED_ENCRYPT;
# ifndef OPENSSL_NO_DES
else if (!strcmp(*args, "-des3"))
cipher = EVP_des_ede3_cbc();
else if (!strcmp(*args, "-des"))
cipher = EVP_des_cbc();
else if (!strcmp(*args, "-des3-wrap"))
wrap_cipher = EVP_des_ede3_wrap();
# endif
# ifndef OPENSSL_NO_SEED
else if (!strcmp(*args, "-seed"))
cipher = EVP_seed_cbc();
# endif
# ifndef OPENSSL_NO_RC2
else if (!strcmp(*args, "-rc2-40"))
cipher = EVP_rc2_40_cbc();
else if (!strcmp(*args, "-rc2-128"))
cipher = EVP_rc2_cbc();
else if (!strcmp(*args, "-rc2-64"))
cipher = EVP_rc2_64_cbc();
# endif
# ifndef OPENSSL_NO_AES
else if (!strcmp(*args, "-aes128"))
cipher = EVP_aes_128_cbc();
else if (!strcmp(*args, "-aes192"))
cipher = EVP_aes_192_cbc();
else if (!strcmp(*args, "-aes256"))
cipher = EVP_aes_256_cbc();
else if (!strcmp(*args, "-aes128-wrap"))
wrap_cipher = EVP_aes_128_wrap();
else if (!strcmp(*args, "-aes192-wrap"))
wrap_cipher = EVP_aes_192_wrap();
else if (!strcmp(*args, "-aes256-wrap"))
wrap_cipher = EVP_aes_256_wrap();
# endif
# ifndef OPENSSL_NO_CAMELLIA
else if (!strcmp(*args, "-camellia128"))
cipher = EVP_camellia_128_cbc();
else if (!strcmp(*args, "-camellia192"))
cipher = EVP_camellia_192_cbc();
else if (!strcmp(*args, "-camellia256"))
cipher = EVP_camellia_256_cbc();
# endif
else if (!strcmp(*args, "-debug_decrypt"))
flags |= CMS_DEBUG_DECRYPT;
else if (!strcmp(*args, "-text"))
flags |= CMS_TEXT;
else if (!strcmp(*args, "-nointern"))
flags |= CMS_NOINTERN;
else if (!strcmp(*args, "-noverify")
|| !strcmp(*args, "-no_signer_cert_verify"))
flags |= CMS_NO_SIGNER_CERT_VERIFY;
else if (!strcmp(*args, "-nocerts"))
flags |= CMS_NOCERTS;
else if (!strcmp(*args, "-noattr"))
flags |= CMS_NOATTR;
else if (!strcmp(*args, "-nodetach"))
flags &= ~CMS_DETACHED;
else if (!strcmp(*args, "-nosmimecap"))
flags |= CMS_NOSMIMECAP;
else if (!strcmp(*args, "-binary"))
flags |= CMS_BINARY;
else if (!strcmp(*args, "-keyid"))
flags |= CMS_USE_KEYID;
else if (!strcmp(*args, "-nosigs"))
flags |= CMS_NOSIGS;
else if (!strcmp(*args, "-no_content_verify"))
flags |= CMS_NO_CONTENT_VERIFY;
else if (!strcmp(*args, "-no_attr_verify"))
flags |= CMS_NO_ATTR_VERIFY;
else if (!strcmp(*args, "-stream"))
flags |= CMS_STREAM;
else if (!strcmp(*args, "-indef"))
flags |= CMS_STREAM;
else if (!strcmp(*args, "-noindef"))
flags &= ~CMS_STREAM;
else if (!strcmp(*args, "-nooldmime"))
flags |= CMS_NOOLDMIMETYPE;
else if (!strcmp(*args, "-crlfeol"))
flags |= CMS_CRLFEOL;
else if (!strcmp(*args, "-noout"))
noout = 1;
else if (!strcmp(*args, "-receipt_request_print"))
rr_print = 1;
else if (!strcmp(*args, "-receipt_request_all"))
rr_allorfirst = 0;
else if (!strcmp(*args, "-receipt_request_first"))
rr_allorfirst = 1;
else if (!strcmp(*args, "-receipt_request_from")) {
if (!args[1])
goto argerr;
args++;
if (!rr_from)
rr_from = sk_OPENSSL_STRING_new_null();
sk_OPENSSL_STRING_push(rr_from, *args);
} else if (!strcmp(*args, "-receipt_request_to")) {
if (!args[1])
goto argerr;
args++;
if (!rr_to)
rr_to = sk_OPENSSL_STRING_new_null();
sk_OPENSSL_STRING_push(rr_to, *args);
} else if (!strcmp(*args, "-print")) {
noout = 1;
print = 1;
} else if (!strcmp(*args, "-secretkey")) {
long ltmp;
if (!args[1])
goto argerr;
args++;
secret_key = string_to_hex(*args, &ltmp);
if (!secret_key) {
BIO_printf(bio_err, "Invalid key %s\n", *args);
goto argerr;
}
secret_keylen = (size_t)ltmp;
} else if (!strcmp(*args, "-secretkeyid")) {
long ltmp;
if (!args[1])
goto argerr;
args++;
secret_keyid = string_to_hex(*args, &ltmp);
if (!secret_keyid) {
BIO_printf(bio_err, "Invalid id %s\n", *args);
goto argerr;
}
secret_keyidlen = (size_t)ltmp;
} else if (!strcmp(*args, "-pwri_password")) {
if (!args[1])
goto argerr;
args++;
pwri_pass = (unsigned char *)*args;
} else if (!strcmp(*args, "-econtent_type")) {
if (!args[1])
goto argerr;
args++;
econtent_type = OBJ_txt2obj(*args, 0);
if (!econtent_type) {
BIO_printf(bio_err, "Invalid OID %s\n", *args);
goto argerr;
}
} else if (!strcmp(*args, "-rand")) {
if (!args[1])
goto argerr;
args++;
inrand = *args;
need_rand = 1;
}
# ifndef OPENSSL_NO_ENGINE
else if (!strcmp(*args, "-engine")) {
if (!args[1])
goto argerr;
engine = *++args;
}
# endif
else if (!strcmp(*args, "-passin")) {
if (!args[1])
goto argerr;
passargin = *++args;
} else if (!strcmp(*args, "-to")) {
if (!args[1])
goto argerr;
to = *++args;
} else if (!strcmp(*args, "-from")) {
if (!args[1])
goto argerr;
from = *++args;
} else if (!strcmp(*args, "-subject")) {
if (!args[1])
goto argerr;
subject = *++args;
} else if (!strcmp(*args, "-signer")) {
if (!args[1])
goto argerr;
/* If previous -signer argument add signer to list */
if (signerfile) {
if (!sksigners)
sksigners = sk_OPENSSL_STRING_new_null();
sk_OPENSSL_STRING_push(sksigners, signerfile);
if (!keyfile)
keyfile = signerfile;
if (!skkeys)
skkeys = sk_OPENSSL_STRING_new_null();
sk_OPENSSL_STRING_push(skkeys, keyfile);
keyfile = NULL;
}
signerfile = *++args;
} else if (!strcmp(*args, "-recip")) {
if (!args[1])
goto argerr;
if (operation == SMIME_ENCRYPT) {
if (!encerts)
encerts = sk_X509_new_null();
cert = load_cert(bio_err, *++args, FORMAT_PEM,
NULL, e, "recipient certificate file");
if (!cert)
goto end;
sk_X509_push(encerts, cert);
cert = NULL;
} else
recipfile = *++args;
} else if (!strcmp(*args, "-certsout")) {
if (!args[1])
goto argerr;
certsoutfile = *++args;
} else if (!strcmp(*args, "-md")) {
if (!args[1])
goto argerr;
sign_md = EVP_get_digestbyname(*++args);
if (sign_md == NULL) {
BIO_printf(bio_err, "Unknown digest %s\n", *args);
goto argerr;
}
} else if (!strcmp(*args, "-inkey")) {
if (!args[1])
goto argerr;
/* If previous -inkey arument add signer to list */
if (keyfile) {
if (!signerfile) {
BIO_puts(bio_err, "Illegal -inkey without -signer\n");
goto argerr;
}
if (!sksigners)
sksigners = sk_OPENSSL_STRING_new_null();
sk_OPENSSL_STRING_push(sksigners, signerfile);
signerfile = NULL;
if (!skkeys)
skkeys = sk_OPENSSL_STRING_new_null();
sk_OPENSSL_STRING_push(skkeys, keyfile);
}
keyfile = *++args;
} else if (!strcmp(*args, "-keyform")) {
if (!args[1])
goto argerr;
keyform = str2fmt(*++args);
} else if (!strcmp(*args, "-keyopt")) {
int keyidx = -1;
if (!args[1])
goto argerr;
if (operation == SMIME_ENCRYPT) {
if (encerts)
keyidx += sk_X509_num(encerts);
} else {
if (keyfile || signerfile)
keyidx++;
if (skkeys)
keyidx += sk_OPENSSL_STRING_num(skkeys);
}
if (keyidx < 0) {
BIO_printf(bio_err, "No key specified\n");
goto argerr;
}
if (key_param == NULL || key_param->idx != keyidx) {
cms_key_param *nparam;
nparam = OPENSSL_malloc(sizeof(cms_key_param));
if (!nparam) {
BIO_printf(bio_err, "Out of memory\n");
goto argerr;
}
nparam->idx = keyidx;
nparam->param = sk_OPENSSL_STRING_new_null();
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, *++args);
} else if (!strcmp(*args, "-rctform")) {
if (!args[1])
goto argerr;
rctformat = str2fmt(*++args);
} else if (!strcmp(*args, "-certfile")) {
if (!args[1])
goto argerr;
certfile = *++args;
} else if (!strcmp(*args, "-CAfile")) {
if (!args[1])
goto argerr;
CAfile = *++args;
} else if (!strcmp(*args, "-CApath")) {
if (!args[1])
goto argerr;
CApath = *++args;
} else if (!strcmp(*args, "-in")) {
if (!args[1])
goto argerr;
infile = *++args;
} else if (!strcmp(*args, "-inform")) {
if (!args[1])
goto argerr;
informat = str2fmt(*++args);
} else if (!strcmp(*args, "-outform")) {
if (!args[1])
goto argerr;
outformat = str2fmt(*++args);
} else if (!strcmp(*args, "-out")) {
if (!args[1])
goto argerr;
outfile = *++args;
} else if (!strcmp(*args, "-content")) {
if (!args[1])
goto argerr;
contfile = *++args;
} else if (args_verify(&args, NULL, &badarg, bio_err, &vpm))
continue;
else if ((cipher = EVP_get_cipherbyname(*args + 1)) == NULL)
badarg = 1;
args++;
}
if (((rr_allorfirst != -1) || rr_from) && !rr_to) {
BIO_puts(bio_err, "No Signed Receipts Recipients\n");
goto argerr;
}
if (!(operation & SMIME_SIGNERS) && (rr_to || rr_from)) {
BIO_puts(bio_err, "Signed receipts only allowed with -sign\n");
goto argerr;
}
if (!(operation & SMIME_SIGNERS) && (skkeys || sksigners)) {
BIO_puts(bio_err, "Multiple signers or keys not allowed\n");
goto argerr;
}
if (operation & SMIME_SIGNERS) {
if (keyfile && !signerfile) {
BIO_puts(bio_err, "Illegal -inkey without -signer\n");
goto argerr;
}
/* Check to see if any final signer needs to be appended */
if (signerfile) {
if (!sksigners)
sksigners = sk_OPENSSL_STRING_new_null();
sk_OPENSSL_STRING_push(sksigners, signerfile);
if (!skkeys)
skkeys = sk_OPENSSL_STRING_new_null();
if (!keyfile)
keyfile = signerfile;
sk_OPENSSL_STRING_push(skkeys, keyfile);
}
if (!sksigners) {
BIO_printf(bio_err, "No signer certificate specified\n");
badarg = 1;
}
signerfile = NULL;
keyfile = NULL;
need_rand = 1;
}
else if (operation == SMIME_DECRYPT) {
if (!recipfile && !keyfile && !secret_key && !pwri_pass) {
BIO_printf(bio_err,
"No recipient certificate or key specified\n");
badarg = 1;
}
} else if (operation == SMIME_ENCRYPT) {
if (!*args && !secret_key && !pwri_pass && !encerts) {
BIO_printf(bio_err, "No recipient(s) certificate(s) specified\n");
badarg = 1;
}
need_rand = 1;
} else if (!operation)
badarg = 1;
if (badarg) {
argerr:
BIO_printf(bio_err, "Usage cms [options] cert.pem ...\n");
BIO_printf(bio_err, "where options are\n");
BIO_printf(bio_err, "-encrypt encrypt message\n");
BIO_printf(bio_err, "-decrypt decrypt encrypted message\n");
BIO_printf(bio_err, "-sign sign message\n");
BIO_printf(bio_err, "-verify verify signed message\n");
BIO_printf(bio_err, "-cmsout output CMS structure\n");
# ifndef OPENSSL_NO_DES
BIO_printf(bio_err, "-des3 encrypt with triple DES\n");
BIO_printf(bio_err, "-des encrypt with DES\n");
# endif
# ifndef OPENSSL_NO_SEED
BIO_printf(bio_err, "-seed encrypt with SEED\n");
# endif
# ifndef OPENSSL_NO_RC2
BIO_printf(bio_err, "-rc2-40 encrypt with RC2-40 (default)\n");
BIO_printf(bio_err, "-rc2-64 encrypt with RC2-64\n");
BIO_printf(bio_err, "-rc2-128 encrypt with RC2-128\n");
# endif
# ifndef OPENSSL_NO_AES
BIO_printf(bio_err, "-aes128, -aes192, -aes256\n");
BIO_printf(bio_err,
" encrypt PEM output with cbc aes\n");
# endif
# ifndef OPENSSL_NO_CAMELLIA
BIO_printf(bio_err, "-camellia128, -camellia192, -camellia256\n");
BIO_printf(bio_err,
" encrypt PEM output with cbc camellia\n");
# endif
BIO_printf(bio_err,
"-nointern don't search certificates in message for signer\n");
BIO_printf(bio_err,
"-nosigs don't verify message signature\n");
BIO_printf(bio_err,
"-noverify don't verify signers certificate\n");
BIO_printf(bio_err,
"-nocerts don't include signers certificate when signing\n");
BIO_printf(bio_err, "-nodetach use opaque signing\n");
BIO_printf(bio_err,
"-noattr don't include any signed attributes\n");
BIO_printf(bio_err,
"-binary don't translate message to text\n");
BIO_printf(bio_err, "-certfile file other certificates file\n");
BIO_printf(bio_err, "-certsout file certificate output file\n");
BIO_printf(bio_err, "-signer file signer certificate file\n");
BIO_printf(bio_err,
"-recip file recipient certificate file for decryption\n");
BIO_printf(bio_err, "-keyid use subject key identifier\n");
BIO_printf(bio_err, "-in file input file\n");
BIO_printf(bio_err,
"-inform arg input format SMIME (default), PEM or DER\n");
BIO_printf(bio_err,
"-inkey file input private key (if not signer or recipient)\n");
BIO_printf(bio_err,
"-keyform arg input private key format (PEM or ENGINE)\n");
BIO_printf(bio_err, "-keyopt nm:v set public key parameters\n");
BIO_printf(bio_err, "-out file output file\n");
BIO_printf(bio_err,
"-outform arg output format SMIME (default), PEM or DER\n");
BIO_printf(bio_err,
"-content file supply or override content for detached signature\n");
BIO_printf(bio_err, "-to addr to address\n");
BIO_printf(bio_err, "-from ad from address\n");
BIO_printf(bio_err, "-subject s subject\n");
BIO_printf(bio_err,
"-text include or delete text MIME headers\n");
BIO_printf(bio_err,
"-CApath dir trusted certificates directory\n");
BIO_printf(bio_err, "-CAfile file trusted certificates file\n");
BIO_printf(bio_err,
"-no_alt_chains only ever use the first certificate chain found\n");
BIO_printf(bio_err,
"-crl_check check revocation status of signer's certificate using CRLs\n");
BIO_printf(bio_err,
"-crl_check_all check revocation status of signer's certificate chain using CRLs\n");
# ifndef OPENSSL_NO_ENGINE
BIO_printf(bio_err,
"-engine e use engine e, possibly a hardware device.\n");
# endif
BIO_printf(bio_err, "-passin arg input file pass phrase source\n");
BIO_printf(bio_err, "-rand file%cfile%c...\n", LIST_SEPARATOR_CHAR,
LIST_SEPARATOR_CHAR);
BIO_printf(bio_err,
" load the file (or the files in the directory) into\n");
BIO_printf(bio_err, " the random number generator\n");
BIO_printf(bio_err,
"cert.pem recipient certificate(s) for encryption\n");
goto end;
}
e = setup_engine(bio_err, engine, 0);
if (!app_passwd(bio_err, passargin, NULL, &passin, NULL)) {
BIO_printf(bio_err, "Error getting password\n");
goto end;
}
if (need_rand) {
app_RAND_load_file(NULL, bio_err, (inrand != NULL));
if (inrand != NULL)
BIO_printf(bio_err, "%ld semi-random bytes loaded\n",
app_RAND_load_files(inrand));
}
ret = 2;
if (!(operation & SMIME_SIGNERS))
flags &= ~CMS_DETACHED;
if (operation & SMIME_OP) {
if (outformat == FORMAT_ASN1)
outmode = "wb";
} else {
if (flags & CMS_BINARY)
outmode = "wb";
}
if (operation & SMIME_IP) {
if (informat == FORMAT_ASN1)
inmode = "rb";
} else {
if (flags & CMS_BINARY)
inmode = "rb";
}
if (operation == SMIME_ENCRYPT) {
if (!cipher) {
# ifndef OPENSSL_NO_DES
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;
}
if (*args && !encerts)
encerts = sk_X509_new_null();
while (*args) {
if (!(cert = load_cert(bio_err, *args, FORMAT_PEM,
NULL, e, "recipient certificate file")))
goto end;
sk_X509_push(encerts, cert);
cert = NULL;
args++;
}
}
if (certfile) {
if (!(other = load_certs(bio_err, certfile, FORMAT_PEM, NULL,
e, "certificate file"))) {
ERR_print_errors(bio_err);
goto end;
}
}
if (recipfile && (operation == SMIME_DECRYPT)) {
if (!(recip = load_cert(bio_err, recipfile, FORMAT_PEM, NULL,
e, "recipient certificate file"))) {
ERR_print_errors(bio_err);
goto end;
}
}
if (operation == SMIME_SIGN_RECEIPT) {
if (!(signer = load_cert(bio_err, signerfile, FORMAT_PEM, NULL,
e, "receipt signer certificate file"))) {
ERR_print_errors(bio_err);
goto end;
}
}
if (operation == SMIME_DECRYPT) {
if (!keyfile)
keyfile = recipfile;
} else if ((operation == SMIME_SIGN) || (operation == SMIME_SIGN_RECEIPT)) {
if (!keyfile)
keyfile = signerfile;
} else
keyfile = NULL;
if (keyfile) {
key = load_key(bio_err, keyfile, keyform, 0, passin, e,
"signing key file");
if (!key)
goto end;
}
if (infile) {
if (!(in = BIO_new_file(infile, inmode))) {
BIO_printf(bio_err, "Can't open input file %s\n", infile);
goto end;
}
} else
in = BIO_new_fp(stdin, BIO_NOCLOSE);
if (operation & SMIME_IP) {
if (informat == FORMAT_SMIME)
cms = SMIME_read_CMS(in, &indata);
else if (informat == FORMAT_PEM)
cms = PEM_read_bio_CMS(in, NULL, NULL, NULL);
else if (informat == FORMAT_ASN1)
cms = d2i_CMS_bio(in, NULL);
else {
BIO_printf(bio_err, "Bad input format for CMS file\n");
goto end;
}
if (!cms) {
BIO_printf(bio_err, "Error reading S/MIME message\n");
goto end;
}
if (contfile) {
BIO_free(indata);
if (!(indata = BIO_new_file(contfile, "rb"))) {
BIO_printf(bio_err, "Can't read content file %s\n", contfile);
goto end;
}
}
if (certsoutfile) {
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) {
char *rctmode = (rctformat == FORMAT_ASN1) ? "rb" : "r";
if (!(rctin = BIO_new_file(rctfile, rctmode))) {
BIO_printf(bio_err, "Can't open receipt file %s\n", rctfile);
goto end;
}
if (rctformat == FORMAT_SMIME)
rcms = SMIME_read_CMS(rctin, NULL);
else if (rctformat == FORMAT_PEM)
rcms = PEM_read_bio_CMS(rctin, NULL, NULL, NULL);
else if (rctformat == FORMAT_ASN1)
rcms = d2i_CMS_bio(rctin, NULL);
else {
BIO_printf(bio_err, "Bad input format for receipt\n");
goto end;
}
if (!rcms) {
BIO_printf(bio_err, "Error reading receipt\n");
goto end;
}
}
if (outfile) {
if (!(out = BIO_new_file(outfile, outmode))) {
BIO_printf(bio_err, "Can't open output file %s\n", outfile);
goto end;
}
} else {
out = BIO_new_fp(stdout, BIO_NOCLOSE);
# ifdef OPENSSL_SYS_VMS
{
BIO *tmpbio = BIO_new(BIO_f_linebuffer());
out = BIO_push(tmpbio, out);
}
# endif
}
if ((operation == SMIME_VERIFY) || (operation == SMIME_VERIFY_RECEIPT)) {
if (!(store = setup_verify(bio_err, CAfile, CApath)))
goto end;
X509_STORE_set_verify_cb(store, cms_cb);
if (vpm)
X509_STORE_set1_param(store, vpm);
}
ret = 3;
if (operation == SMIME_DATA_CREATE) {
cms = CMS_data_create(in, flags);
} else if (operation == SMIME_DIGEST_CREATE) {
cms = CMS_digest_create(in, sign_md, flags);
} else if (operation == SMIME_COMPRESS) {
cms = CMS_compress(in, -1, flags);
} else if (operation == SMIME_ENCRYPT) {
int i;
flags |= CMS_PARTIAL;
cms = CMS_encrypt(NULL, in, cipher, flags);
if (!cms)
goto end;
for (i = 0; i < sk_X509_num(encerts); i++) {
CMS_RecipientInfo *ri;
cms_key_param *kparam;
int tflags = flags;
X509 *x = sk_X509_value(encerts, i);
for (kparam = key_first; kparam; kparam = kparam->next) {
if (kparam->idx == i) {
tflags |= CMS_KEY_PARAM;
break;
}
}
ri = CMS_add1_recipient_cert(cms, x, tflags);
if (!ri)
goto end;
if (kparam) {
EVP_PKEY_CTX *pctx;
pctx = CMS_RecipientInfo_get0_pkey_ctx(ri);
if (!cms_set_pkey_param(pctx, kparam->param))
goto end;
}
if (CMS_RecipientInfo_type(ri) == CMS_RECIPINFO_AGREE
&& wrap_cipher) {
EVP_CIPHER_CTX *wctx;
wctx = CMS_RecipientInfo_kari_get0_ctx(ri);
EVP_EncryptInit_ex(wctx, wrap_cipher, NULL, NULL, NULL);
}
}
if (secret_key) {
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) {
pwri_tmp = (unsigned char *)BUF_strdup((char *)pwri_pass);
if (!pwri_tmp)
goto end;
if (!CMS_add0_recipient_password(cms,
-1, NID_undef, NID_undef,
pwri_tmp, -1, 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(in, cipher,
secret_key, secret_keylen, flags);
} 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)
goto end;
si = sk_CMS_SignerInfo_value(sis, 0);
srcms = CMS_sign_receipt(si, signer, key, other, flags);
if (!srcms)
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(NULL, NULL, other, in, flags);
if (!cms)
goto end;
if (econtent_type)
CMS_set1_eContentType(cms, econtent_type);
if (rr_to) {
rr = make_receipt_request(rr_to, rr_allorfirst, rr_from);
if (!rr) {
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(bio_err, signerfile, FORMAT_PEM, NULL,
e, "signer certificate");
- if (!signer)
+ if (!signer) {
+ ret = 2;
goto end;
+ }
key = load_key(bio_err, keyfile, keyform, 0, passin, e,
"signing key file");
- if (!key)
+ if (!key) {
+ 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)
goto end;
if (kparam) {
EVP_PKEY_CTX *pctx;
pctx = CMS_SignerInfo_get0_pkey_ctx(si);
if (!cms_set_pkey_param(pctx, kparam->param))
goto end;
}
if (rr && !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) {
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) {
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) {
if (!CMS_decrypt_set1_pkey(cms, key, recip)) {
BIO_puts(bio_err, "Error decrypting CMS using private key\n");
goto end;
}
}
if (pwri_pass) {
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_DATAOUT) {
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, "Verification successful\n");
else {
BIO_printf(bio_err, "Verification failure\n");
if (verify_retcode)
ret = verify_err + 32;
goto end;
}
if (signerfile) {
STACK_OF(X509) *signers;
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(bio_err, 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)
CMS_ContentInfo_print_ctx(out, cms, 0, NULL);
} else if (outformat == FORMAT_SMIME) {
if (to)
BIO_printf(out, "To: %s\n", to);
if (from)
BIO_printf(out, "From: %s\n", from);
if (subject)
BIO_printf(out, "Subject: %s\n", subject);
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);
if (need_rand)
app_RAND_write_file(NULL, bio_err);
sk_X509_pop_free(encerts, X509_free);
sk_X509_pop_free(other, X509_free);
if (vpm)
X509_VERIFY_PARAM_free(vpm);
if (sksigners)
sk_OPENSSL_STRING_free(sksigners);
if (skkeys)
sk_OPENSSL_STRING_free(skkeys);
if (secret_key)
OPENSSL_free(secret_key);
if (secret_keyid)
OPENSSL_free(secret_keyid);
if (pwri_tmp)
OPENSSL_free(pwri_tmp);
if (econtent_type)
ASN1_OBJECT_free(econtent_type);
if (rr)
CMS_ReceiptRequest_free(rr);
if (rr_to)
sk_OPENSSL_STRING_free(rr_to);
if (rr_from)
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);
CMS_ContentInfo_free(cms);
CMS_ContentInfo_free(rcms);
release_engine(e);
BIO_free(rctin);
BIO_free(in);
BIO_free(indata);
BIO_free_all(out);
if (passin)
OPENSSL_free(passin);
return (ret);
}
static int save_certs(char *signerfile, STACK_OF(X509) *signers)
{
int i;
BIO *tmp;
if (!signerfile)
return 1;
tmp = BIO_new_file(signerfile, "w");
if (!tmp)
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(NULL, ctx);
return ok;
}
static void gnames_stack_print(BIO *out, 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(out, " ");
GENERAL_NAME_print(out, gen);
BIO_puts(out, "\n");
}
}
return;
}
static void receipt_request_print(BIO *out, 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 {
char *id;
int idlen;
CMS_ReceiptRequest_get0_values(rr, &scid, &allorfirst,
&rlist, &rto);
BIO_puts(out, " Signed Content ID:\n");
idlen = ASN1_STRING_length(scid);
id = (char *)ASN1_STRING_data(scid);
BIO_dump_indent(out, id, idlen, 4);
BIO_puts(out, " Receipts From");
if (rlist) {
BIO_puts(out, " List:\n");
gnames_stack_print(out, rlist);
} else if (allorfirst == 1)
BIO_puts(out, ": First Tier\n");
else if (allorfirst == 0)
BIO_puts(out, ": All\n");
else
BIO_printf(out, " Unknown (%d)\n", allorfirst);
BIO_puts(out, " Receipts To:\n");
gnames_stack_print(out, rto);
}
if (rr)
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)
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)
goto err;
gens = GENERAL_NAMES_new();
if (!gens)
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:
if (ret)
sk_GENERAL_NAMES_pop_free(ret, GENERAL_NAMES_free);
if (gens)
GENERAL_NAMES_free(gens);
if (gen)
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, *rct_from;
CMS_ReceiptRequest *rr;
rct_to = make_names_stack(rr_to);
if (!rct_to)
goto err;
if (rr_from) {
rct_from = make_names_stack(rr_from);
if (!rct_from)
goto err;
} else
rct_from = NULL;
rr = CMS_ReceiptRequest_create0(NULL, -1, rr_allorfirst, rct_from,
rct_to);
return rr;
err:
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;
}
#endif
diff --git a/apps/dgst.c b/apps/dgst.c
index bc2601e452ef..686fe344fbf5 100644
--- a/apps/dgst.c
+++ b/apps/dgst.c
@@ -1,620 +1,620 @@
/* apps/dgst.c */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "apps.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>
#undef BUFSIZE
#define BUFSIZE 1024*8
#undef PROG
#define PROG dgst_main
int do_fp(BIO *out, unsigned char *buf, BIO *bp, int sep, int binout,
EVP_PKEY *key, unsigned char *sigin, int siglen,
const char *sig_name, const char *md_name,
const char *file, BIO *bmd);
static void list_md_fn(const EVP_MD *m,
const char *from, const char *to, void *arg)
{
const char *mname;
/* Skip aliases */
if (!m)
return;
mname = OBJ_nid2ln(EVP_MD_type(m));
/* Skip shortnames */
if (strcmp(from, mname))
return;
/* Skip clones */
if (EVP_MD_flags(m) & EVP_MD_FLAG_PKEY_DIGEST)
return;
if (strchr(mname, ' '))
mname = EVP_MD_name(m);
BIO_printf(arg, "-%-14s to use the %s message digest algorithm\n",
mname, mname);
}
int MAIN(int, char **);
int MAIN(int argc, char **argv)
{
ENGINE *e = NULL, *impl = NULL;
unsigned char *buf = NULL;
int i, err = 1;
const EVP_MD *md = NULL, *m;
BIO *in = NULL, *inp;
BIO *bmd = NULL;
BIO *out = NULL;
#define PROG_NAME_SIZE 39
char pname[PROG_NAME_SIZE + 1];
int separator = 0;
int debug = 0;
int keyform = FORMAT_PEM;
const char *outfile = NULL, *keyfile = NULL;
const char *sigfile = NULL, *randfile = NULL;
int out_bin = -1, want_pub = 0, do_verify = 0;
EVP_PKEY *sigkey = NULL;
unsigned char *sigbuf = NULL;
int siglen = 0;
char *passargin = NULL, *passin = NULL;
#ifndef OPENSSL_NO_ENGINE
char *engine = NULL;
int engine_impl = 0;
#endif
char *hmac_key = NULL;
char *mac_name = NULL;
int non_fips_allow = 0;
STACK_OF(OPENSSL_STRING) *sigopts = NULL, *macopts = NULL;
apps_startup();
if ((buf = (unsigned char *)OPENSSL_malloc(BUFSIZE)) == NULL) {
BIO_printf(bio_err, "out of memory\n");
goto end;
}
if (bio_err == NULL)
if ((bio_err = BIO_new(BIO_s_file())) != NULL)
BIO_set_fp(bio_err, stderr, BIO_NOCLOSE | BIO_FP_TEXT);
if (!load_config(bio_err, NULL))
goto end;
/* first check the program name */
- program_name(argv[0], pname, sizeof pname);
+ program_name(argv[0], pname, sizeof(pname));
md = EVP_get_digestbyname(pname);
argc--;
argv++;
while (argc > 0) {
if ((*argv)[0] != '-')
break;
if (strcmp(*argv, "-c") == 0)
separator = 1;
else if (strcmp(*argv, "-r") == 0)
separator = 2;
else if (strcmp(*argv, "-rand") == 0) {
if (--argc < 1)
break;
randfile = *(++argv);
} else if (strcmp(*argv, "-out") == 0) {
if (--argc < 1)
break;
outfile = *(++argv);
} else if (strcmp(*argv, "-sign") == 0) {
if (--argc < 1)
break;
keyfile = *(++argv);
} else if (!strcmp(*argv, "-passin")) {
if (--argc < 1)
break;
passargin = *++argv;
} else if (strcmp(*argv, "-verify") == 0) {
if (--argc < 1)
break;
keyfile = *(++argv);
want_pub = 1;
do_verify = 1;
} else if (strcmp(*argv, "-prverify") == 0) {
if (--argc < 1)
break;
keyfile = *(++argv);
do_verify = 1;
} else if (strcmp(*argv, "-signature") == 0) {
if (--argc < 1)
break;
sigfile = *(++argv);
} else if (strcmp(*argv, "-keyform") == 0) {
if (--argc < 1)
break;
keyform = str2fmt(*(++argv));
}
#ifndef OPENSSL_NO_ENGINE
else if (strcmp(*argv, "-engine") == 0) {
if (--argc < 1)
break;
engine = *(++argv);
e = setup_engine(bio_err, engine, 0);
} else if (strcmp(*argv, "-engine_impl") == 0)
engine_impl = 1;
#endif
else if (strcmp(*argv, "-hex") == 0)
out_bin = 0;
else if (strcmp(*argv, "-binary") == 0)
out_bin = 1;
else if (strcmp(*argv, "-d") == 0)
debug = 1;
else if (!strcmp(*argv, "-fips-fingerprint"))
hmac_key = "etaonrishdlcupfm";
else if (strcmp(*argv, "-non-fips-allow") == 0)
non_fips_allow = 1;
else if (!strcmp(*argv, "-hmac")) {
if (--argc < 1)
break;
hmac_key = *++argv;
} else if (!strcmp(*argv, "-mac")) {
if (--argc < 1)
break;
mac_name = *++argv;
} else if (strcmp(*argv, "-sigopt") == 0) {
if (--argc < 1)
break;
if (!sigopts)
sigopts = sk_OPENSSL_STRING_new_null();
if (!sigopts || !sk_OPENSSL_STRING_push(sigopts, *(++argv)))
break;
} else if (strcmp(*argv, "-macopt") == 0) {
if (--argc < 1)
break;
if (!macopts)
macopts = sk_OPENSSL_STRING_new_null();
if (!macopts || !sk_OPENSSL_STRING_push(macopts, *(++argv)))
break;
} else if ((m = EVP_get_digestbyname(&((*argv)[1]))) != NULL)
md = m;
else
break;
argc--;
argv++;
}
if (keyfile != NULL && argc > 1) {
BIO_printf(bio_err, "Can only sign or verify one file\n");
goto end;
}
if (do_verify && !sigfile) {
BIO_printf(bio_err,
"No signature to verify: use the -signature option\n");
goto end;
}
if ((argc > 0) && (argv[0][0] == '-')) { /* bad option */
BIO_printf(bio_err, "unknown option '%s'\n", *argv);
BIO_printf(bio_err, "options are\n");
BIO_printf(bio_err,
"-c to output the digest with separating colons\n");
BIO_printf(bio_err,
"-r to output the digest in coreutils format\n");
BIO_printf(bio_err, "-d to output debug info\n");
BIO_printf(bio_err, "-hex output as hex dump\n");
BIO_printf(bio_err, "-binary output in binary form\n");
BIO_printf(bio_err, "-hmac arg set the HMAC key to arg\n");
BIO_printf(bio_err, "-non-fips-allow allow use of non FIPS digest\n");
BIO_printf(bio_err,
"-sign file sign digest using private key in file\n");
BIO_printf(bio_err,
"-verify file verify a signature using public key in file\n");
BIO_printf(bio_err,
"-prverify file verify a signature using private key in file\n");
BIO_printf(bio_err,
"-keyform arg key file format (PEM or ENGINE)\n");
BIO_printf(bio_err,
"-out filename output to filename rather than stdout\n");
BIO_printf(bio_err, "-signature file signature to verify\n");
BIO_printf(bio_err, "-sigopt nm:v signature parameter\n");
BIO_printf(bio_err, "-hmac key create hashed MAC with key\n");
BIO_printf(bio_err,
"-mac algorithm create MAC (not neccessarily HMAC)\n");
BIO_printf(bio_err,
"-macopt nm:v MAC algorithm parameters or key\n");
#ifndef OPENSSL_NO_ENGINE
BIO_printf(bio_err,
"-engine e use engine e, possibly a hardware device.\n");
#endif
EVP_MD_do_all_sorted(list_md_fn, bio_err);
goto end;
}
#ifndef OPENSSL_NO_ENGINE
if (engine_impl)
impl = e;
#endif
in = BIO_new(BIO_s_file());
bmd = BIO_new(BIO_f_md());
if ((in == NULL) || (bmd == NULL)) {
ERR_print_errors(bio_err);
goto end;
}
if (debug) {
BIO_set_callback(in, BIO_debug_callback);
/* needed for windows 3.1 */
BIO_set_callback_arg(in, (char *)bio_err);
}
if (!app_passwd(bio_err, passargin, NULL, &passin, NULL)) {
BIO_printf(bio_err, "Error getting password\n");
goto end;
}
if (out_bin == -1) {
if (keyfile)
out_bin = 1;
else
out_bin = 0;
}
if (randfile)
app_RAND_load_file(randfile, bio_err, 0);
if (outfile) {
if (out_bin)
out = BIO_new_file(outfile, "wb");
else
out = BIO_new_file(outfile, "w");
} else {
out = BIO_new_fp(stdout, BIO_NOCLOSE);
#ifdef OPENSSL_SYS_VMS
{
BIO *tmpbio = BIO_new(BIO_f_linebuffer());
out = BIO_push(tmpbio, out);
}
#endif
}
if (!out) {
BIO_printf(bio_err, "Error opening output file %s\n",
outfile ? outfile : "(stdout)");
ERR_print_errors(bio_err);
goto end;
}
if ((! !mac_name + ! !keyfile + ! !hmac_key) > 1) {
BIO_printf(bio_err, "MAC and Signing key cannot both be specified\n");
goto end;
}
if (keyfile) {
if (want_pub)
sigkey = load_pubkey(bio_err, keyfile, keyform, 0, NULL,
e, "key file");
else
sigkey = load_key(bio_err, keyfile, keyform, 0, passin,
e, "key file");
if (!sigkey) {
/*
* load_[pub]key() has already printed an appropriate message
*/
goto end;
}
}
if (mac_name) {
EVP_PKEY_CTX *mac_ctx = NULL;
int r = 0;
if (!init_gen_str(bio_err, &mac_ctx, mac_name, impl, 0))
goto mac_end;
if (macopts) {
char *macopt;
for (i = 0; i < sk_OPENSSL_STRING_num(macopts); i++) {
macopt = sk_OPENSSL_STRING_value(macopts, i);
if (pkey_ctrl_string(mac_ctx, macopt) <= 0) {
BIO_printf(bio_err,
"MAC parameter error \"%s\"\n", macopt);
ERR_print_errors(bio_err);
goto mac_end;
}
}
}
if (EVP_PKEY_keygen(mac_ctx, &sigkey) <= 0) {
BIO_puts(bio_err, "Error generating key\n");
ERR_print_errors(bio_err);
goto mac_end;
}
r = 1;
mac_end:
if (mac_ctx)
EVP_PKEY_CTX_free(mac_ctx);
if (r == 0)
goto end;
}
if (non_fips_allow) {
EVP_MD_CTX *md_ctx;
BIO_get_md_ctx(bmd, &md_ctx);
EVP_MD_CTX_set_flags(md_ctx, EVP_MD_CTX_FLAG_NON_FIPS_ALLOW);
}
if (hmac_key) {
sigkey = EVP_PKEY_new_mac_key(EVP_PKEY_HMAC, impl,
(unsigned char *)hmac_key, -1);
if (!sigkey)
goto end;
}
if (sigkey) {
EVP_MD_CTX *mctx = NULL;
EVP_PKEY_CTX *pctx = NULL;
int r;
if (!BIO_get_md_ctx(bmd, &mctx)) {
BIO_printf(bio_err, "Error getting context\n");
ERR_print_errors(bio_err);
goto end;
}
if (do_verify)
r = EVP_DigestVerifyInit(mctx, &pctx, md, impl, sigkey);
else
r = EVP_DigestSignInit(mctx, &pctx, md, impl, sigkey);
if (!r) {
BIO_printf(bio_err, "Error setting context\n");
ERR_print_errors(bio_err);
goto end;
}
if (sigopts) {
char *sigopt;
for (i = 0; i < sk_OPENSSL_STRING_num(sigopts); i++) {
sigopt = sk_OPENSSL_STRING_value(sigopts, i);
if (pkey_ctrl_string(pctx, sigopt) <= 0) {
BIO_printf(bio_err, "parameter error \"%s\"\n", sigopt);
ERR_print_errors(bio_err);
goto end;
}
}
}
}
/* we use md as a filter, reading from 'in' */
else {
EVP_MD_CTX *mctx = NULL;
if (!BIO_get_md_ctx(bmd, &mctx)) {
BIO_printf(bio_err, "Error getting context\n");
ERR_print_errors(bio_err);
goto end;
}
if (md == NULL)
md = EVP_md5();
if (!EVP_DigestInit_ex(mctx, md, impl)) {
BIO_printf(bio_err, "Error setting digest %s\n", pname);
ERR_print_errors(bio_err);
goto end;
}
}
if (sigfile && sigkey) {
BIO *sigbio;
sigbio = BIO_new_file(sigfile, "rb");
siglen = EVP_PKEY_size(sigkey);
sigbuf = OPENSSL_malloc(siglen);
if (!sigbio) {
BIO_printf(bio_err, "Error opening signature file %s\n", sigfile);
ERR_print_errors(bio_err);
goto end;
}
if (!sigbuf) {
BIO_printf(bio_err, "Out of memory\n");
ERR_print_errors(bio_err);
goto end;
}
siglen = BIO_read(sigbio, sigbuf, siglen);
BIO_free(sigbio);
if (siglen <= 0) {
BIO_printf(bio_err, "Error reading signature file %s\n", sigfile);
ERR_print_errors(bio_err);
goto end;
}
}
inp = BIO_push(bmd, in);
if (md == NULL) {
EVP_MD_CTX *tctx;
BIO_get_md_ctx(bmd, &tctx);
md = EVP_MD_CTX_md(tctx);
}
if (argc == 0) {
BIO_set_fp(in, stdin, BIO_NOCLOSE);
err = do_fp(out, buf, inp, separator, out_bin, sigkey, sigbuf,
siglen, NULL, NULL, "stdin", bmd);
} else {
const char *md_name = NULL, *sig_name = NULL;
if (!out_bin) {
if (sigkey) {
const EVP_PKEY_ASN1_METHOD *ameth;
ameth = EVP_PKEY_get0_asn1(sigkey);
if (ameth)
EVP_PKEY_asn1_get0_info(NULL, NULL,
NULL, NULL, &sig_name, ameth);
}
if (md)
md_name = EVP_MD_name(md);
}
err = 0;
for (i = 0; i < argc; i++) {
int r;
if (BIO_read_filename(in, argv[i]) <= 0) {
perror(argv[i]);
err++;
continue;
} else
r = do_fp(out, buf, inp, separator, out_bin, sigkey, sigbuf,
siglen, sig_name, md_name, argv[i], bmd);
if (r)
err = r;
(void)BIO_reset(bmd);
}
}
end:
if (buf != NULL) {
OPENSSL_cleanse(buf, BUFSIZE);
OPENSSL_free(buf);
}
if (in != NULL)
BIO_free(in);
if (passin)
OPENSSL_free(passin);
BIO_free_all(out);
EVP_PKEY_free(sigkey);
if (sigopts)
sk_OPENSSL_STRING_free(sigopts);
if (macopts)
sk_OPENSSL_STRING_free(macopts);
if (sigbuf)
OPENSSL_free(sigbuf);
if (bmd != NULL)
BIO_free(bmd);
release_engine(e);
apps_shutdown();
OPENSSL_EXIT(err);
}
int do_fp(BIO *out, unsigned char *buf, BIO *bp, int sep, int binout,
EVP_PKEY *key, unsigned char *sigin, int siglen,
const char *sig_name, const char *md_name,
const char *file, BIO *bmd)
{
size_t len;
int i;
for (;;) {
i = BIO_read(bp, (char *)buf, BUFSIZE);
if (i < 0) {
BIO_printf(bio_err, "Read Error in %s\n", file);
ERR_print_errors(bio_err);
return 1;
}
if (i == 0)
break;
}
if (sigin) {
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");
return 1;
} else {
BIO_printf(bio_err, "Error Verifying Data\n");
ERR_print_errors(bio_err);
return 1;
}
return 0;
}
if (key) {
EVP_MD_CTX *ctx;
BIO_get_md_ctx(bp, &ctx);
len = BUFSIZE;
if (!EVP_DigestSignFinal(ctx, buf, &len)) {
BIO_printf(bio_err, "Error Signing Data\n");
ERR_print_errors(bio_err);
return 1;
}
} else {
len = BIO_gets(bp, (char *)buf, BUFSIZE);
if ((int)len < 0) {
ERR_print_errors(bio_err);
return 1;
}
}
if (binout)
BIO_write(out, buf, len);
else if (sep == 2) {
for (i = 0; i < (int)len; i++)
BIO_printf(out, "%02x", buf[i]);
BIO_printf(out, " *%s\n", file);
} else {
if (sig_name) {
BIO_puts(out, sig_name);
if (md_name)
BIO_printf(out, "-%s", md_name);
BIO_printf(out, "(%s)= ", file);
} else if (md_name)
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");
}
return 0;
}
diff --git a/apps/dsaparam.c b/apps/dsaparam.c
index f2cf553db3ff..3a4a123846c4 100644
--- a/apps/dsaparam.c
+++ b/apps/dsaparam.c
@@ -1,467 +1,470 @@
/* apps/dsaparam.c */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
#include <openssl/opensslconf.h> /* for OPENSSL_NO_DSA */
/*
* Until the key-gen callbacks are modified to use newer prototypes, we allow
* deprecated functions for openssl-internal code
*/
#ifdef OPENSSL_NO_DEPRECATED
# undef OPENSSL_NO_DEPRECATED
#endif
#ifndef OPENSSL_NO_DSA
# include <assert.h>
# include <stdio.h>
# include <stdlib.h>
# include <time.h>
# include <string.h>
# include "apps.h"
# include <openssl/bio.h>
# include <openssl/err.h>
# include <openssl/bn.h>
# include <openssl/dsa.h>
# include <openssl/x509.h>
# include <openssl/pem.h>
# undef PROG
# define PROG dsaparam_main
/*-
* -inform arg - input format - default PEM (DER or PEM)
* -outform arg - output format - default PEM
* -in arg - input file - default stdin
* -out arg - output file - default stdout
* -noout
* -text
* -C
* -noout
* -genkey
* #ifdef GENCB_TEST
* -timebomb n - interrupt keygen after <n> seconds
* #endif
*/
# ifdef GENCB_TEST
static int stop_keygen_flag = 0;
static void timebomb_sigalarm(int foo)
{
stop_keygen_flag = 1;
}
# endif
static int MS_CALLBACK dsa_cb(int p, int n, BN_GENCB *cb);
int MAIN(int, char **);
int MAIN(int argc, char **argv)
{
DSA *dsa = NULL;
int i, badops = 0, text = 0;
BIO *in = NULL, *out = NULL;
int informat, outformat, noout = 0, C = 0, ret = 1;
char *infile, *outfile, *prog, *inrand = NULL;
int numbits = -1, num, genkey = 0;
int need_rand = 0;
char *engine = NULL;
ENGINE *e = NULL;
# ifdef GENCB_TEST
int timebomb = 0;
# endif
apps_startup();
if (bio_err == NULL)
if ((bio_err = BIO_new(BIO_s_file())) != NULL)
BIO_set_fp(bio_err, stderr, BIO_NOCLOSE | BIO_FP_TEXT);
if (!load_config(bio_err, NULL))
goto end;
infile = NULL;
outfile = NULL;
informat = FORMAT_PEM;
outformat = FORMAT_PEM;
prog = argv[0];
argc--;
argv++;
while (argc >= 1) {
if (strcmp(*argv, "-inform") == 0) {
if (--argc < 1)
goto bad;
informat = str2fmt(*(++argv));
} else if (strcmp(*argv, "-outform") == 0) {
if (--argc < 1)
goto bad;
outformat = str2fmt(*(++argv));
} else if (strcmp(*argv, "-in") == 0) {
if (--argc < 1)
goto bad;
infile = *(++argv);
} else if (strcmp(*argv, "-out") == 0) {
if (--argc < 1)
goto bad;
outfile = *(++argv);
}
# ifndef OPENSSL_NO_ENGINE
else if (strcmp(*argv, "-engine") == 0) {
if (--argc < 1)
goto bad;
engine = *(++argv);
}
# endif
# ifdef GENCB_TEST
else if (strcmp(*argv, "-timebomb") == 0) {
if (--argc < 1)
goto bad;
timebomb = atoi(*(++argv));
}
# endif
else if (strcmp(*argv, "-text") == 0)
text = 1;
else if (strcmp(*argv, "-C") == 0)
C = 1;
else if (strcmp(*argv, "-genkey") == 0) {
genkey = 1;
need_rand = 1;
} else if (strcmp(*argv, "-rand") == 0) {
if (--argc < 1)
goto bad;
inrand = *(++argv);
need_rand = 1;
} else if (strcmp(*argv, "-noout") == 0)
noout = 1;
else if (sscanf(*argv, "%d", &num) == 1) {
/* generate a key */
numbits = num;
need_rand = 1;
} else {
BIO_printf(bio_err, "unknown option %s\n", *argv);
badops = 1;
break;
}
argc--;
argv++;
}
if (badops) {
bad:
BIO_printf(bio_err, "%s [options] [bits] <infile >outfile\n", prog);
BIO_printf(bio_err, "where options are\n");
BIO_printf(bio_err, " -inform arg input format - DER or PEM\n");
BIO_printf(bio_err, " -outform arg output format - DER or PEM\n");
BIO_printf(bio_err, " -in arg input file\n");
BIO_printf(bio_err, " -out arg output file\n");
BIO_printf(bio_err, " -text print as text\n");
BIO_printf(bio_err, " -C Output C code\n");
BIO_printf(bio_err, " -noout no output\n");
BIO_printf(bio_err, " -genkey generate a DSA key\n");
BIO_printf(bio_err,
" -rand files to use for random number input\n");
# ifndef OPENSSL_NO_ENGINE
BIO_printf(bio_err,
" -engine e use engine e, possibly a hardware device.\n");
# endif
# ifdef GENCB_TEST
BIO_printf(bio_err,
" -timebomb n interrupt keygen after <n> seconds\n");
# endif
BIO_printf(bio_err,
" number number of bits to use for generating private key\n");
goto end;
}
ERR_load_crypto_strings();
in = BIO_new(BIO_s_file());
out = BIO_new(BIO_s_file());
if ((in == NULL) || (out == NULL)) {
ERR_print_errors(bio_err);
goto end;
}
if (infile == NULL)
BIO_set_fp(in, stdin, BIO_NOCLOSE);
else {
if (BIO_read_filename(in, infile) <= 0) {
perror(infile);
goto end;
}
}
if (outfile == NULL) {
BIO_set_fp(out, stdout, BIO_NOCLOSE);
# ifdef OPENSSL_SYS_VMS
{
BIO *tmpbio = BIO_new(BIO_f_linebuffer());
out = BIO_push(tmpbio, out);
}
# endif
} else {
if (BIO_write_filename(out, outfile) <= 0) {
perror(outfile);
goto end;
}
}
e = setup_engine(bio_err, engine, 0);
if (need_rand) {
app_RAND_load_file(NULL, bio_err, (inrand != NULL));
if (inrand != NULL)
BIO_printf(bio_err, "%ld semi-random bytes loaded\n",
app_RAND_load_files(inrand));
}
if (numbits > 0) {
BN_GENCB cb;
BN_GENCB_set(&cb, dsa_cb, bio_err);
assert(need_rand);
dsa = DSA_new();
if (!dsa) {
BIO_printf(bio_err, "Error allocating DSA object\n");
goto end;
}
BIO_printf(bio_err, "Generating DSA parameters, %d bit long prime\n",
num);
BIO_printf(bio_err, "This could take some time\n");
# ifdef GENCB_TEST
if (timebomb > 0) {
struct sigaction act;
act.sa_handler = timebomb_sigalarm;
act.sa_flags = 0;
BIO_printf(bio_err,
"(though I'll stop it if not done within %d secs)\n",
timebomb);
if (sigaction(SIGALRM, &act, NULL) != 0) {
BIO_printf(bio_err, "Error, couldn't set SIGALRM handler\n");
goto end;
}
alarm(timebomb);
}
# endif
if (!DSA_generate_parameters_ex(dsa, num, NULL, 0, NULL, NULL, &cb)) {
# ifdef GENCB_TEST
if (stop_keygen_flag) {
BIO_printf(bio_err, "DSA key generation time-stopped\n");
/* This is an asked-for behaviour! */
ret = 0;
goto end;
}
# endif
ERR_print_errors(bio_err);
BIO_printf(bio_err, "Error, DSA key generation failed\n");
goto end;
}
} else if (informat == FORMAT_ASN1)
dsa = d2i_DSAparams_bio(in, NULL);
else if (informat == FORMAT_PEM)
dsa = PEM_read_bio_DSAparams(in, NULL, NULL, NULL);
else {
BIO_printf(bio_err, "bad input format specified\n");
goto end;
}
if (dsa == NULL) {
BIO_printf(bio_err, "unable to load DSA parameters\n");
ERR_print_errors(bio_err);
goto end;
}
if (text) {
DSAparams_print(out, dsa);
}
if (C) {
unsigned char *data;
int l, len, bits_p;
len = BN_num_bytes(dsa->p);
bits_p = BN_num_bits(dsa->p);
data = (unsigned char *)OPENSSL_malloc(len + 20);
if (data == NULL) {
perror("OPENSSL_malloc");
goto end;
}
l = BN_bn2bin(dsa->p, data);
printf("static unsigned char dsa%d_p[]={", bits_p);
for (i = 0; i < l; i++) {
if ((i % 12) == 0)
printf("\n\t");
printf("0x%02X,", data[i]);
}
printf("\n\t};\n");
l = BN_bn2bin(dsa->q, data);
printf("static unsigned char dsa%d_q[]={", bits_p);
for (i = 0; i < l; i++) {
if ((i % 12) == 0)
printf("\n\t");
printf("0x%02X,", data[i]);
}
printf("\n\t};\n");
l = BN_bn2bin(dsa->g, data);
printf("static unsigned char dsa%d_g[]={", bits_p);
for (i = 0; i < l; i++) {
if ((i % 12) == 0)
printf("\n\t");
printf("0x%02X,", data[i]);
}
printf("\n\t};\n\n");
printf("DSA *get_dsa%d()\n\t{\n", bits_p);
printf("\tDSA *dsa;\n\n");
printf("\tif ((dsa=DSA_new()) == NULL) return(NULL);\n");
printf("\tdsa->p=BN_bin2bn(dsa%d_p,sizeof(dsa%d_p),NULL);\n",
bits_p, bits_p);
printf("\tdsa->q=BN_bin2bn(dsa%d_q,sizeof(dsa%d_q),NULL);\n",
bits_p, bits_p);
printf("\tdsa->g=BN_bin2bn(dsa%d_g,sizeof(dsa%d_g),NULL);\n",
bits_p, bits_p);
printf
("\tif ((dsa->p == NULL) || (dsa->q == NULL) || (dsa->g == NULL))\n");
printf("\t\t{ DSA_free(dsa); return(NULL); }\n");
printf("\treturn(dsa);\n\t}\n");
}
+ if (outformat == FORMAT_ASN1 && genkey)
+ noout = 1;
+
if (!noout) {
if (outformat == FORMAT_ASN1)
i = i2d_DSAparams_bio(out, dsa);
else if (outformat == FORMAT_PEM)
i = PEM_write_bio_DSAparams(out, dsa);
else {
BIO_printf(bio_err, "bad output format specified for outfile\n");
goto end;
}
if (!i) {
BIO_printf(bio_err, "unable to write DSA parameters\n");
ERR_print_errors(bio_err);
goto end;
}
}
if (genkey) {
DSA *dsakey;
assert(need_rand);
if ((dsakey = DSAparams_dup(dsa)) == NULL)
goto end;
if (!DSA_generate_key(dsakey)) {
ERR_print_errors(bio_err);
DSA_free(dsakey);
goto end;
}
if (outformat == FORMAT_ASN1)
i = i2d_DSAPrivateKey_bio(out, dsakey);
else if (outformat == FORMAT_PEM)
i = PEM_write_bio_DSAPrivateKey(out, dsakey, NULL, NULL, 0, NULL,
NULL);
else {
BIO_printf(bio_err, "bad output format specified for outfile\n");
DSA_free(dsakey);
goto end;
}
DSA_free(dsakey);
}
if (need_rand)
app_RAND_write_file(NULL, bio_err);
ret = 0;
end:
if (in != NULL)
BIO_free(in);
if (out != NULL)
BIO_free_all(out);
if (dsa != NULL)
DSA_free(dsa);
release_engine(e);
apps_shutdown();
OPENSSL_EXIT(ret);
}
static int MS_CALLBACK dsa_cb(int p, int n, BN_GENCB *cb)
{
char c = '*';
if (p == 0)
c = '.';
if (p == 1)
c = '+';
if (p == 2)
c = '*';
if (p == 3)
c = '\n';
BIO_write(cb->arg, &c, 1);
(void)BIO_flush(cb->arg);
# ifdef LINT
p = n;
# endif
# ifdef GENCB_TEST
if (stop_keygen_flag)
return 0;
# endif
return 1;
}
#else /* !OPENSSL_NO_DSA */
# if PEDANTIC
static void *dummy = &dummy;
# endif
#endif
diff --git a/apps/ecparam.c b/apps/ecparam.c
index a9bf489cdd4c..8d5b7044489c 100644
--- a/apps/ecparam.c
+++ b/apps/ecparam.c
@@ -1,661 +1,667 @@
/* apps/ecparam.c */
/*
* Written by Nils Larsch for the OpenSSL project.
*/
/* ====================================================================
- * Copyright (c) 1998-2005 The OpenSSL Project. All rights reserved.
+ * Copyright (c) 1998-2018 The OpenSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* openssl-core@openssl.org.
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.openssl.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*
* This product includes cryptographic software written by Eric Young
* (eay@cryptsoft.com). This product includes software written by Tim
* Hudson (tjh@cryptsoft.com).
*
*/
/* ====================================================================
* Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
*
* Portions of the attached software ("Contribution") are developed by
* SUN MICROSYSTEMS, INC., and are contributed to the OpenSSL project.
*
* The Contribution is licensed pursuant to the OpenSSL open source
* license provided above.
*
* The elliptic curve binary polynomial software is originally written by
* Sheueling Chang Shantz and Douglas Stebila of Sun Microsystems Laboratories.
*
*/
#include <openssl/opensslconf.h>
#ifndef OPENSSL_NO_EC
# include <assert.h>
# include <stdio.h>
# include <stdlib.h>
# include <time.h>
# include <string.h>
# include "apps.h"
# include <openssl/bio.h>
# include <openssl/err.h>
# include <openssl/bn.h>
# include <openssl/ec.h>
# include <openssl/x509.h>
# include <openssl/pem.h>
# undef PROG
# define PROG ecparam_main
/*-
* -inform arg - input format - default PEM (DER or PEM)
* -outform arg - output format - default PEM
* -in arg - input file - default stdin
* -out arg - output file - default stdout
* -noout - do not print the ec parameter
* -text - print the ec parameters in text form
* -check - validate the ec parameters
* -C - print a 'C' function creating the parameters
* -name arg - use the ec parameters with 'short name' name
* -list_curves - prints a list of all currently available curve 'short names'
* -conv_form arg - specifies the point conversion form
* - possible values: compressed
* uncompressed (default)
* hybrid
* -param_enc arg - specifies the way the ec parameters are encoded
* in the asn1 der encoding
* possible values: named_curve (default)
* explicit
* -no_seed - if 'explicit' parameters are chosen do not use the seed
* -genkey - generate ec key
* -rand file - files to use for random number input
* -engine e - use engine e, possibly a hardware device
*/
static int ecparam_print_var(BIO *, BIGNUM *, const char *, int,
unsigned char *);
int MAIN(int, char **);
int MAIN(int argc, char **argv)
{
EC_GROUP *group = NULL;
point_conversion_form_t form = POINT_CONVERSION_UNCOMPRESSED;
int new_form = 0;
int asn1_flag = OPENSSL_EC_NAMED_CURVE;
int new_asn1_flag = 0;
char *curve_name = NULL, *inrand = NULL;
int list_curves = 0, no_seed = 0, check = 0,
badops = 0, text = 0, i, need_rand = 0, genkey = 0;
char *infile = NULL, *outfile = NULL, *prog;
BIO *in = NULL, *out = NULL;
int informat, outformat, noout = 0, C = 0, ret = 1;
char *engine = NULL;
ENGINE *e = NULL;
BIGNUM *ec_p = NULL, *ec_a = NULL, *ec_b = NULL,
*ec_gen = NULL, *ec_order = NULL, *ec_cofactor = NULL;
unsigned char *buffer = NULL;
apps_startup();
if (bio_err == NULL)
if ((bio_err = BIO_new(BIO_s_file())) != NULL)
BIO_set_fp(bio_err, stderr, BIO_NOCLOSE | BIO_FP_TEXT);
if (!load_config(bio_err, NULL))
goto end;
informat = FORMAT_PEM;
outformat = FORMAT_PEM;
prog = argv[0];
argc--;
argv++;
while (argc >= 1) {
if (strcmp(*argv, "-inform") == 0) {
if (--argc < 1)
goto bad;
informat = str2fmt(*(++argv));
} else if (strcmp(*argv, "-outform") == 0) {
if (--argc < 1)
goto bad;
outformat = str2fmt(*(++argv));
} else if (strcmp(*argv, "-in") == 0) {
if (--argc < 1)
goto bad;
infile = *(++argv);
} else if (strcmp(*argv, "-out") == 0) {
if (--argc < 1)
goto bad;
outfile = *(++argv);
} else if (strcmp(*argv, "-text") == 0)
text = 1;
else if (strcmp(*argv, "-C") == 0)
C = 1;
else if (strcmp(*argv, "-check") == 0)
check = 1;
else if (strcmp(*argv, "-name") == 0) {
if (--argc < 1)
goto bad;
curve_name = *(++argv);
} else if (strcmp(*argv, "-list_curves") == 0)
list_curves = 1;
else if (strcmp(*argv, "-conv_form") == 0) {
if (--argc < 1)
goto bad;
++argv;
new_form = 1;
if (strcmp(*argv, "compressed") == 0)
form = POINT_CONVERSION_COMPRESSED;
else if (strcmp(*argv, "uncompressed") == 0)
form = POINT_CONVERSION_UNCOMPRESSED;
else if (strcmp(*argv, "hybrid") == 0)
form = POINT_CONVERSION_HYBRID;
else
goto bad;
} else if (strcmp(*argv, "-param_enc") == 0) {
if (--argc < 1)
goto bad;
++argv;
new_asn1_flag = 1;
if (strcmp(*argv, "named_curve") == 0)
asn1_flag = OPENSSL_EC_NAMED_CURVE;
else if (strcmp(*argv, "explicit") == 0)
asn1_flag = 0;
else
goto bad;
} else if (strcmp(*argv, "-no_seed") == 0)
no_seed = 1;
else if (strcmp(*argv, "-noout") == 0)
noout = 1;
else if (strcmp(*argv, "-genkey") == 0) {
genkey = 1;
need_rand = 1;
} else if (strcmp(*argv, "-rand") == 0) {
if (--argc < 1)
goto bad;
inrand = *(++argv);
need_rand = 1;
} else if (strcmp(*argv, "-engine") == 0) {
if (--argc < 1)
goto bad;
engine = *(++argv);
} else {
BIO_printf(bio_err, "unknown option %s\n", *argv);
badops = 1;
break;
}
argc--;
argv++;
}
if (badops) {
bad:
BIO_printf(bio_err, "%s [options] <infile >outfile\n", prog);
BIO_printf(bio_err, "where options are\n");
BIO_printf(bio_err, " -inform arg input format - "
"default PEM (DER or PEM)\n");
BIO_printf(bio_err, " -outform arg output format - "
"default PEM\n");
BIO_printf(bio_err, " -in arg input file - "
"default stdin\n");
BIO_printf(bio_err, " -out arg output file - "
"default stdout\n");
BIO_printf(bio_err, " -noout do not print the "
"ec parameter\n");
BIO_printf(bio_err, " -text print the ec "
"parameters in text form\n");
BIO_printf(bio_err, " -check validate the ec "
"parameters\n");
BIO_printf(bio_err, " -C print a 'C' "
"function creating the parameters\n");
BIO_printf(bio_err, " -name arg use the "
"ec parameters with 'short name' name\n");
BIO_printf(bio_err, " -list_curves prints a list of "
"all currently available curve 'short names'\n");
BIO_printf(bio_err, " -conv_form arg specifies the "
"point conversion form \n");
BIO_printf(bio_err, " possible values:"
" compressed\n");
BIO_printf(bio_err, " "
" uncompressed (default)\n");
BIO_printf(bio_err, " "
" hybrid\n");
BIO_printf(bio_err, " -param_enc arg specifies the way"
" the ec parameters are encoded\n");
BIO_printf(bio_err, " in the asn1 der "
"encoding\n");
BIO_printf(bio_err, " possible values:"
" named_curve (default)\n");
BIO_printf(bio_err, " "
" explicit\n");
BIO_printf(bio_err, " -no_seed if 'explicit'"
" parameters are chosen do not" " use the seed\n");
BIO_printf(bio_err, " -genkey generate ec" " key\n");
BIO_printf(bio_err, " -rand file files to use for"
" random number input\n");
BIO_printf(bio_err, " -engine e use engine e, "
"possibly a hardware device\n");
goto end;
}
ERR_load_crypto_strings();
in = BIO_new(BIO_s_file());
out = BIO_new(BIO_s_file());
if ((in == NULL) || (out == NULL)) {
ERR_print_errors(bio_err);
goto end;
}
if (infile == NULL)
BIO_set_fp(in, stdin, BIO_NOCLOSE);
else {
if (BIO_read_filename(in, infile) <= 0) {
perror(infile);
goto end;
}
}
if (outfile == NULL) {
BIO_set_fp(out, stdout, BIO_NOCLOSE);
# ifdef OPENSSL_SYS_VMS
{
BIO *tmpbio = BIO_new(BIO_f_linebuffer());
out = BIO_push(tmpbio, out);
}
# endif
} else {
if (BIO_write_filename(out, outfile) <= 0) {
perror(outfile);
goto end;
}
}
e = setup_engine(bio_err, engine, 0);
if (list_curves) {
EC_builtin_curve *curves = NULL;
size_t crv_len = 0;
size_t n = 0;
crv_len = EC_get_builtin_curves(NULL, 0);
curves = OPENSSL_malloc((int)(sizeof(EC_builtin_curve) * crv_len));
if (curves == NULL)
goto end;
if (!EC_get_builtin_curves(curves, crv_len)) {
OPENSSL_free(curves);
goto end;
}
for (n = 0; n < crv_len; n++) {
const char *comment;
const char *sname;
comment = curves[n].comment;
sname = OBJ_nid2sn(curves[n].nid);
if (comment == NULL)
comment = "CURVE DESCRIPTION NOT AVAILABLE";
if (sname == NULL)
sname = "";
BIO_printf(out, " %-10s: ", sname);
BIO_printf(out, "%s\n", comment);
}
OPENSSL_free(curves);
ret = 0;
goto end;
}
if (curve_name != NULL) {
int nid;
/*
* workaround for the SECG curve names secp192r1 and secp256r1 (which
* are the same as the curves prime192v1 and prime256v1 defined in
* X9.62)
*/
if (!strcmp(curve_name, "secp192r1")) {
BIO_printf(bio_err, "using curve name prime192v1 "
"instead of secp192r1\n");
nid = NID_X9_62_prime192v1;
} else if (!strcmp(curve_name, "secp256r1")) {
BIO_printf(bio_err, "using curve name prime256v1 "
"instead of secp256r1\n");
nid = NID_X9_62_prime256v1;
} else
nid = OBJ_sn2nid(curve_name);
if (nid == 0)
nid = EC_curve_nist2nid(curve_name);
if (nid == 0) {
BIO_printf(bio_err, "unknown curve name (%s)\n", curve_name);
goto end;
}
group = EC_GROUP_new_by_curve_name(nid);
if (group == NULL) {
BIO_printf(bio_err, "unable to create curve (%s)\n", curve_name);
goto end;
}
EC_GROUP_set_asn1_flag(group, asn1_flag);
EC_GROUP_set_point_conversion_form(group, form);
} else if (informat == FORMAT_ASN1) {
group = d2i_ECPKParameters_bio(in, NULL);
} else if (informat == FORMAT_PEM) {
group = PEM_read_bio_ECPKParameters(in, NULL, NULL, NULL);
} else {
BIO_printf(bio_err, "bad input format specified\n");
goto end;
}
if (group == NULL) {
BIO_printf(bio_err, "unable to load elliptic curve parameters\n");
ERR_print_errors(bio_err);
goto end;
}
if (new_form)
EC_GROUP_set_point_conversion_form(group, form);
if (new_asn1_flag)
EC_GROUP_set_asn1_flag(group, asn1_flag);
if (no_seed) {
EC_GROUP_set_seed(group, NULL, 0);
}
if (text) {
if (!ECPKParameters_print(out, group, 0))
goto end;
}
if (check) {
BIO_printf(bio_err, "checking elliptic curve parameters: ");
if (!EC_GROUP_check(group, NULL)) {
BIO_printf(bio_err, "failed\n");
ERR_print_errors(bio_err);
goto end;
}
BIO_printf(bio_err, "ok\n");
}
if (C) {
size_t buf_len = 0, tmp_len = 0;
const EC_POINT *point;
int is_prime, len = 0;
const EC_METHOD *meth = EC_GROUP_method_of(group);
if ((ec_p = BN_new()) == NULL || (ec_a = BN_new()) == NULL ||
(ec_b = BN_new()) == NULL || (ec_gen = BN_new()) == NULL ||
(ec_order = BN_new()) == NULL ||
(ec_cofactor = BN_new()) == NULL) {
perror("OPENSSL_malloc");
goto end;
}
is_prime = (EC_METHOD_get_field_type(meth) == NID_X9_62_prime_field);
if (is_prime) {
if (!EC_GROUP_get_curve_GFp(group, ec_p, ec_a, ec_b, NULL))
goto end;
} else {
/* TODO */
goto end;
}
if ((point = EC_GROUP_get0_generator(group)) == NULL)
goto end;
if (!EC_POINT_point2bn(group, point,
EC_GROUP_get_point_conversion_form(group),
ec_gen, NULL))
goto end;
if (!EC_GROUP_get_order(group, ec_order, NULL))
goto end;
if (!EC_GROUP_get_cofactor(group, ec_cofactor, NULL))
goto end;
if (!ec_p || !ec_a || !ec_b || !ec_gen || !ec_order || !ec_cofactor)
goto end;
len = BN_num_bits(ec_order);
if ((tmp_len = (size_t)BN_num_bytes(ec_p)) > buf_len)
buf_len = tmp_len;
if ((tmp_len = (size_t)BN_num_bytes(ec_a)) > buf_len)
buf_len = tmp_len;
if ((tmp_len = (size_t)BN_num_bytes(ec_b)) > buf_len)
buf_len = tmp_len;
if ((tmp_len = (size_t)BN_num_bytes(ec_gen)) > buf_len)
buf_len = tmp_len;
if ((tmp_len = (size_t)BN_num_bytes(ec_order)) > buf_len)
buf_len = tmp_len;
if ((tmp_len = (size_t)BN_num_bytes(ec_cofactor)) > buf_len)
buf_len = tmp_len;
buffer = (unsigned char *)OPENSSL_malloc(buf_len);
if (buffer == NULL) {
perror("OPENSSL_malloc");
goto end;
}
ecparam_print_var(out, ec_p, "ec_p", len, buffer);
ecparam_print_var(out, ec_a, "ec_a", len, buffer);
ecparam_print_var(out, ec_b, "ec_b", len, buffer);
ecparam_print_var(out, ec_gen, "ec_gen", len, buffer);
ecparam_print_var(out, ec_order, "ec_order", len, buffer);
ecparam_print_var(out, ec_cofactor, "ec_cofactor", len, buffer);
BIO_printf(out, "\n\n");
BIO_printf(out, "EC_GROUP *get_ec_group_%d(void)\n\t{\n", len);
BIO_printf(out, "\tint ok=0;\n");
BIO_printf(out, "\tEC_GROUP *group = NULL;\n");
BIO_printf(out, "\tEC_POINT *point = NULL;\n");
BIO_printf(out, "\tBIGNUM *tmp_1 = NULL, *tmp_2 = NULL, "
"*tmp_3 = NULL;\n\n");
BIO_printf(out, "\tif ((tmp_1 = BN_bin2bn(ec_p_%d, "
"sizeof(ec_p_%d), NULL)) == NULL)\n\t\t"
"goto err;\n", len, len);
BIO_printf(out, "\tif ((tmp_2 = BN_bin2bn(ec_a_%d, "
"sizeof(ec_a_%d), NULL)) == NULL)\n\t\t"
"goto err;\n", len, len);
BIO_printf(out, "\tif ((tmp_3 = BN_bin2bn(ec_b_%d, "
"sizeof(ec_b_%d), NULL)) == NULL)\n\t\t"
"goto err;\n", len, len);
if (is_prime) {
BIO_printf(out, "\tif ((group = EC_GROUP_new_curve_"
"GFp(tmp_1, tmp_2, tmp_3, NULL)) == NULL)"
"\n\t\tgoto err;\n\n");
} else {
/* TODO */
goto end;
}
BIO_printf(out, "\t/* build generator */\n");
BIO_printf(out, "\tif ((tmp_1 = BN_bin2bn(ec_gen_%d, "
"sizeof(ec_gen_%d), tmp_1)) == NULL)"
"\n\t\tgoto err;\n", len, len);
BIO_printf(out, "\tpoint = EC_POINT_bn2point(group, tmp_1, "
"NULL, NULL);\n");
BIO_printf(out, "\tif (point == NULL)\n\t\tgoto err;\n");
BIO_printf(out, "\tif ((tmp_2 = BN_bin2bn(ec_order_%d, "
"sizeof(ec_order_%d), tmp_2)) == NULL)"
"\n\t\tgoto err;\n", len, len);
BIO_printf(out, "\tif ((tmp_3 = BN_bin2bn(ec_cofactor_%d, "
"sizeof(ec_cofactor_%d), tmp_3)) == NULL)"
"\n\t\tgoto err;\n", len, len);
BIO_printf(out, "\tif (!EC_GROUP_set_generator(group, point,"
" tmp_2, tmp_3))\n\t\tgoto err;\n");
BIO_printf(out, "\n\tok=1;\n");
BIO_printf(out, "err:\n");
BIO_printf(out, "\tif (tmp_1)\n\t\tBN_free(tmp_1);\n");
BIO_printf(out, "\tif (tmp_2)\n\t\tBN_free(tmp_2);\n");
BIO_printf(out, "\tif (tmp_3)\n\t\tBN_free(tmp_3);\n");
BIO_printf(out, "\tif (point)\n\t\tEC_POINT_free(point);\n");
BIO_printf(out, "\tif (!ok)\n");
BIO_printf(out, "\t\t{\n");
BIO_printf(out, "\t\tEC_GROUP_free(group);\n");
BIO_printf(out, "\t\tgroup = NULL;\n");
BIO_printf(out, "\t\t}\n");
BIO_printf(out, "\treturn(group);\n\t}\n");
}
+ if (outformat == FORMAT_ASN1 && genkey)
+ noout = 1;
+
if (!noout) {
if (outformat == FORMAT_ASN1)
i = i2d_ECPKParameters_bio(out, group);
else if (outformat == FORMAT_PEM)
i = PEM_write_bio_ECPKParameters(out, group);
else {
BIO_printf(bio_err, "bad output format specified for"
" outfile\n");
goto end;
}
if (!i) {
BIO_printf(bio_err, "unable to write elliptic "
"curve parameters\n");
ERR_print_errors(bio_err);
goto end;
}
}
if (need_rand) {
app_RAND_load_file(NULL, bio_err, (inrand != NULL));
if (inrand != NULL)
BIO_printf(bio_err, "%ld semi-random bytes loaded\n",
app_RAND_load_files(inrand));
}
if (genkey) {
EC_KEY *eckey = EC_KEY_new();
if (eckey == NULL)
goto end;
assert(need_rand);
if (EC_KEY_set_group(eckey, group) == 0)
goto end;
+ if (new_form)
+ EC_KEY_set_conv_form(eckey, form);
+
if (!EC_KEY_generate_key(eckey)) {
EC_KEY_free(eckey);
goto end;
}
if (outformat == FORMAT_ASN1)
i = i2d_ECPrivateKey_bio(out, eckey);
else if (outformat == FORMAT_PEM)
i = PEM_write_bio_ECPrivateKey(out, eckey, NULL,
NULL, 0, NULL, NULL);
else {
BIO_printf(bio_err, "bad output format specified "
"for outfile\n");
EC_KEY_free(eckey);
goto end;
}
EC_KEY_free(eckey);
}
if (need_rand)
app_RAND_write_file(NULL, bio_err);
ret = 0;
end:
if (ec_p)
BN_free(ec_p);
if (ec_a)
BN_free(ec_a);
if (ec_b)
BN_free(ec_b);
if (ec_gen)
BN_free(ec_gen);
if (ec_order)
BN_free(ec_order);
if (ec_cofactor)
BN_free(ec_cofactor);
if (buffer)
OPENSSL_free(buffer);
if (group != NULL)
EC_GROUP_free(group);
release_engine(e);
if (in != NULL)
BIO_free(in);
if (out != NULL)
BIO_free_all(out);
apps_shutdown();
OPENSSL_EXIT(ret);
}
static int ecparam_print_var(BIO *out, BIGNUM *in, const char *var,
int len, unsigned char *buffer)
{
BIO_printf(out, "static unsigned char %s_%d[] = {", var, len);
if (BN_is_zero(in))
BIO_printf(out, "\n\t0x00");
else {
int i, l;
l = BN_bn2bin(in, buffer);
for (i = 0; i < l - 1; i++) {
if ((i % 12) == 0)
BIO_printf(out, "\n\t");
BIO_printf(out, "0x%02X,", buffer[i]);
}
if ((i % 12) == 0)
BIO_printf(out, "\n\t");
BIO_printf(out, "0x%02X", buffer[i]);
}
BIO_printf(out, "\n\t};\n\n");
return 1;
}
#else /* !OPENSSL_NO_EC */
# if PEDANTIC
static void *dummy = &dummy;
# endif
#endif
diff --git a/apps/enc.c b/apps/enc.c
index 66145b3be770..3b7e1eea3d83 100644
--- a/apps/enc.c
+++ b/apps/enc.c
@@ -1,728 +1,728 @@
/* apps/enc.c */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "apps.h"
#include <openssl/bio.h>
#include <openssl/err.h>
#include <openssl/evp.h>
#include <openssl/objects.h>
#include <openssl/x509.h>
#include <openssl/rand.h>
#include <openssl/pem.h>
#ifndef OPENSSL_NO_COMP
# include <openssl/comp.h>
#endif
#include <ctype.h>
int set_hex(char *in, unsigned char *out, int size);
#undef SIZE
#undef BSIZE
#undef PROG
#define SIZE (512)
#define BSIZE (8*1024)
#define PROG enc_main
struct doall_enc_ciphers {
BIO *bio;
int n;
};
static void show_ciphers(const OBJ_NAME *name, void *arg)
{
struct doall_enc_ciphers *dec = (struct doall_enc_ciphers *)arg;
const EVP_CIPHER *cipher;
if (!islower((unsigned char)*name->name))
return;
/* Filter out ciphers that we cannot use */
cipher = EVP_get_cipherbyname(name->name);
if (cipher == NULL ||
(EVP_CIPHER_flags(cipher) & EVP_CIPH_FLAG_AEAD_CIPHER) != 0 ||
EVP_CIPHER_mode(cipher) == EVP_CIPH_XTS_MODE)
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, " ");
}
int MAIN(int, char **);
int MAIN(int argc, char **argv)
{
static const char magic[] = "Salted__";
- char mbuf[sizeof magic - 1];
+ char mbuf[sizeof(magic) - 1];
char *strbuf = NULL;
unsigned char *buff = NULL, *bufsize = NULL;
int bsize = BSIZE, verbose = 0;
int ret = 1, inl;
int nopad = 0;
unsigned char key[EVP_MAX_KEY_LENGTH], iv[EVP_MAX_IV_LENGTH];
unsigned char salt[PKCS5_SALT_LEN];
char *str = NULL, *passarg = NULL, *pass = NULL;
char *hkey = NULL, *hiv = NULL, *hsalt = NULL;
char *md = NULL;
int enc = 1, printkey = 0, i, base64 = 0;
#ifdef ZLIB
int do_zlib = 0;
BIO *bzl = NULL;
#endif
int debug = 0, olb64 = 0, nosalt = 0;
const EVP_CIPHER *cipher = NULL, *c;
EVP_CIPHER_CTX *ctx = NULL;
char *inf = NULL, *outf = NULL;
BIO *in = NULL, *out = NULL, *b64 = NULL, *benc = NULL, *rbio =
NULL, *wbio = NULL;
#define PROG_NAME_SIZE 39
char pname[PROG_NAME_SIZE + 1];
char *engine = NULL;
ENGINE *e = NULL;
const EVP_MD *dgst = NULL;
int non_fips_allow = 0;
struct doall_enc_ciphers dec;
apps_startup();
if (bio_err == NULL)
if ((bio_err = BIO_new(BIO_s_file())) != NULL)
BIO_set_fp(bio_err, stderr, BIO_NOCLOSE | BIO_FP_TEXT);
if (!load_config(bio_err, NULL))
goto end;
/* first check the program name */
- program_name(argv[0], pname, sizeof pname);
+ program_name(argv[0], pname, sizeof(pname));
if (strcmp(pname, "base64") == 0)
base64 = 1;
#ifdef ZLIB
if (strcmp(pname, "zlib") == 0)
do_zlib = 1;
#endif
cipher = EVP_get_cipherbyname(pname);
#ifdef ZLIB
if (!do_zlib && !base64 && (cipher == NULL)
&& (strcmp(pname, "enc") != 0))
#else
if (!base64 && (cipher == NULL) && (strcmp(pname, "enc") != 0))
#endif
{
BIO_printf(bio_err, "%s is an unknown cipher\n", pname);
goto bad;
}
argc--;
argv++;
while (argc >= 1) {
if (strcmp(*argv, "-e") == 0)
enc = 1;
else if (strcmp(*argv, "-in") == 0) {
if (--argc < 1)
goto bad;
inf = *(++argv);
} else if (strcmp(*argv, "-out") == 0) {
if (--argc < 1)
goto bad;
outf = *(++argv);
} else if (strcmp(*argv, "-pass") == 0) {
if (--argc < 1)
goto bad;
passarg = *(++argv);
}
#ifndef OPENSSL_NO_ENGINE
else if (strcmp(*argv, "-engine") == 0) {
if (--argc < 1)
goto bad;
engine = *(++argv);
}
#endif
else if (strcmp(*argv, "-d") == 0)
enc = 0;
else if (strcmp(*argv, "-p") == 0)
printkey = 1;
else if (strcmp(*argv, "-v") == 0)
verbose = 1;
else if (strcmp(*argv, "-nopad") == 0)
nopad = 1;
else if (strcmp(*argv, "-salt") == 0)
nosalt = 0;
else if (strcmp(*argv, "-nosalt") == 0)
nosalt = 1;
else if (strcmp(*argv, "-debug") == 0)
debug = 1;
else if (strcmp(*argv, "-P") == 0)
printkey = 2;
else if (strcmp(*argv, "-A") == 0)
olb64 = 1;
else if (strcmp(*argv, "-a") == 0)
base64 = 1;
else if (strcmp(*argv, "-base64") == 0)
base64 = 1;
#ifdef ZLIB
else if (strcmp(*argv, "-z") == 0)
do_zlib = 1;
#endif
else if (strcmp(*argv, "-bufsize") == 0) {
if (--argc < 1)
goto bad;
bufsize = (unsigned char *)*(++argv);
} else if (strcmp(*argv, "-k") == 0) {
if (--argc < 1)
goto bad;
str = *(++argv);
} else if (strcmp(*argv, "-kfile") == 0) {
static char buf[128];
FILE *infile;
char *file;
if (--argc < 1)
goto bad;
file = *(++argv);
infile = fopen(file, "r");
if (infile == NULL) {
BIO_printf(bio_err, "unable to read key from '%s'\n", file);
goto bad;
}
buf[0] = '\0';
- if (!fgets(buf, sizeof buf, infile)) {
+ if (!fgets(buf, sizeof(buf), infile)) {
BIO_printf(bio_err, "unable to read key from '%s'\n", file);
goto bad;
}
fclose(infile);
i = strlen(buf);
if ((i > 0) && ((buf[i - 1] == '\n') || (buf[i - 1] == '\r')))
buf[--i] = '\0';
if ((i > 0) && ((buf[i - 1] == '\n') || (buf[i - 1] == '\r')))
buf[--i] = '\0';
if (i < 1) {
BIO_printf(bio_err, "zero length password\n");
goto bad;
}
str = buf;
} else if (strcmp(*argv, "-K") == 0) {
if (--argc < 1)
goto bad;
hkey = *(++argv);
} else if (strcmp(*argv, "-S") == 0) {
if (--argc < 1)
goto bad;
hsalt = *(++argv);
} else if (strcmp(*argv, "-iv") == 0) {
if (--argc < 1)
goto bad;
hiv = *(++argv);
} else if (strcmp(*argv, "-md") == 0) {
if (--argc < 1)
goto bad;
md = *(++argv);
} else if (strcmp(*argv, "-non-fips-allow") == 0)
non_fips_allow = 1;
else if ((argv[0][0] == '-') &&
((c = EVP_get_cipherbyname(&(argv[0][1]))) != NULL)) {
cipher = c;
} else if (strcmp(*argv, "-none") == 0)
cipher = NULL;
else {
BIO_printf(bio_err, "unknown option '%s'\n", *argv);
bad:
BIO_printf(bio_err, "options are\n");
BIO_printf(bio_err, "%-14s input file\n", "-in <file>");
BIO_printf(bio_err, "%-14s output file\n", "-out <file>");
BIO_printf(bio_err, "%-14s pass phrase source\n", "-pass <arg>");
BIO_printf(bio_err, "%-14s encrypt\n", "-e");
BIO_printf(bio_err, "%-14s decrypt\n", "-d");
BIO_printf(bio_err,
"%-14s base64 encode/decode, depending on encryption flag\n",
"-a/-base64");
BIO_printf(bio_err, "%-14s passphrase is the next argument\n",
"-k");
BIO_printf(bio_err,
"%-14s passphrase is the first line of the file argument\n",
"-kfile");
BIO_printf(bio_err,
"%-14s the next argument is the md to use to create a key\n",
"-md");
BIO_printf(bio_err,
"%-14s from a passphrase. One of md2, md5, sha or sha1\n",
"");
BIO_printf(bio_err, "%-14s salt in hex is the next argument\n",
"-S");
BIO_printf(bio_err, "%-14s key/iv in hex is the next argument\n",
"-K/-iv");
BIO_printf(bio_err, "%-14s print the iv/key (then exit if -P)\n",
"-[pP]");
BIO_printf(bio_err, "%-14s buffer size\n", "-bufsize <n>");
BIO_printf(bio_err, "%-14s disable standard block padding\n",
"-nopad");
#ifndef OPENSSL_NO_ENGINE
BIO_printf(bio_err,
"%-14s use engine e, possibly a hardware device.\n",
"-engine e");
#endif
BIO_printf(bio_err, "Cipher Types\n");
dec.n = 0;
dec.bio = bio_err;
OBJ_NAME_do_all_sorted(OBJ_NAME_TYPE_CIPHER_METH,
show_ciphers, &dec);
BIO_printf(bio_err, "\n");
goto end;
}
argc--;
argv++;
}
e = setup_engine(bio_err, engine, 0);
if (cipher && EVP_CIPHER_flags(cipher) & EVP_CIPH_FLAG_AEAD_CIPHER) {
BIO_printf(bio_err,
"AEAD ciphers not supported by the enc utility\n");
goto end;
}
if (cipher && (EVP_CIPHER_mode(cipher) == EVP_CIPH_XTS_MODE)) {
BIO_printf(bio_err,
"Ciphers in XTS mode are not supported by the enc utility\n");
goto end;
}
if (md && (dgst = EVP_get_digestbyname(md)) == NULL) {
BIO_printf(bio_err, "%s is an unsupported message digest type\n", md);
goto end;
}
if (dgst == NULL) {
dgst = EVP_md5();
}
if (bufsize != NULL) {
unsigned long n;
for (n = 0; *bufsize; bufsize++) {
i = *bufsize;
if ((i <= '9') && (i >= '0'))
n = n * 10 + i - '0';
else if (i == 'k') {
n *= 1024;
bufsize++;
break;
}
}
if (*bufsize != '\0') {
BIO_printf(bio_err, "invalid 'bufsize' specified.\n");
goto end;
}
/* It must be large enough for a base64 encoded line */
if (base64 && n < 80)
n = 80;
bsize = (int)n;
if (verbose)
BIO_printf(bio_err, "bufsize=%d\n", bsize);
}
strbuf = OPENSSL_malloc(SIZE);
buff = (unsigned char *)OPENSSL_malloc(EVP_ENCODE_LENGTH(bsize));
if ((buff == NULL) || (strbuf == NULL)) {
BIO_printf(bio_err, "OPENSSL_malloc failure %ld\n",
(long)EVP_ENCODE_LENGTH(bsize));
goto end;
}
in = BIO_new(BIO_s_file());
out = BIO_new(BIO_s_file());
if ((in == NULL) || (out == NULL)) {
ERR_print_errors(bio_err);
goto end;
}
if (debug) {
BIO_set_callback(in, BIO_debug_callback);
BIO_set_callback(out, BIO_debug_callback);
BIO_set_callback_arg(in, (char *)bio_err);
BIO_set_callback_arg(out, (char *)bio_err);
}
if (inf == NULL) {
#ifndef OPENSSL_NO_SETVBUF_IONBF
if (bufsize != NULL)
setvbuf(stdin, (char *)NULL, _IONBF, 0);
#endif /* ndef OPENSSL_NO_SETVBUF_IONBF */
BIO_set_fp(in, stdin, BIO_NOCLOSE);
} else {
if (BIO_read_filename(in, inf) <= 0) {
perror(inf);
goto end;
}
}
if (!str && passarg) {
if (!app_passwd(bio_err, passarg, NULL, &pass, NULL)) {
BIO_printf(bio_err, "Error getting password\n");
goto end;
}
str = pass;
}
if ((str == NULL) && (cipher != NULL) && (hkey == NULL)) {
for (;;) {
char buf[200];
- BIO_snprintf(buf, sizeof buf, "enter %s %s password:",
+ BIO_snprintf(buf, sizeof(buf), "enter %s %s password:",
OBJ_nid2ln(EVP_CIPHER_nid(cipher)),
(enc) ? "encryption" : "decryption");
strbuf[0] = '\0';
i = EVP_read_pw_string((char *)strbuf, SIZE, buf, enc);
if (i == 0) {
if (strbuf[0] == '\0') {
ret = 1;
goto end;
}
str = strbuf;
break;
}
if (i < 0) {
BIO_printf(bio_err, "bad password read\n");
goto end;
}
}
}
if (outf == NULL) {
BIO_set_fp(out, stdout, BIO_NOCLOSE);
#ifndef OPENSSL_NO_SETVBUF_IONBF
if (bufsize != NULL)
setvbuf(stdout, (char *)NULL, _IONBF, 0);
#endif /* ndef OPENSSL_NO_SETVBUF_IONBF */
#ifdef OPENSSL_SYS_VMS
{
BIO *tmpbio = BIO_new(BIO_f_linebuffer());
out = BIO_push(tmpbio, out);
}
#endif
} else {
if (BIO_write_filename(out, outf) <= 0) {
perror(outf);
goto end;
}
}
rbio = in;
wbio = out;
#ifdef ZLIB
if (do_zlib) {
if ((bzl = BIO_new(BIO_f_zlib())) == NULL)
goto end;
if (enc)
wbio = BIO_push(bzl, wbio);
else
rbio = BIO_push(bzl, rbio);
}
#endif
if (base64) {
if ((b64 = BIO_new(BIO_f_base64())) == NULL)
goto end;
if (debug) {
BIO_set_callback(b64, BIO_debug_callback);
BIO_set_callback_arg(b64, (char *)bio_err);
}
if (olb64)
BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
if (enc)
wbio = BIO_push(b64, wbio);
else
rbio = BIO_push(b64, rbio);
}
if (cipher != NULL) {
/*
* Note that str is NULL if a key was passed on the command line, so
* we get no salt in that case. Is this a bug?
*/
if (str != NULL) {
/*
* Salt handling: if encrypting generate a salt and write to
* output BIO. If decrypting read salt from input BIO.
*/
unsigned char *sptr;
if (nosalt)
sptr = NULL;
else {
if (enc) {
if (hsalt) {
- if (!set_hex(hsalt, salt, sizeof salt)) {
+ if (!set_hex(hsalt, salt, sizeof(salt))) {
BIO_printf(bio_err, "invalid hex salt value\n");
goto end;
}
- } else if (RAND_bytes(salt, sizeof salt) <= 0)
+ } else if (RAND_bytes(salt, sizeof(salt)) <= 0)
goto end;
/*
* If -P option then don't bother writing
*/
if ((printkey != 2)
&& (BIO_write(wbio, magic,
- sizeof magic - 1) != sizeof magic - 1
+ sizeof(magic) - 1) != sizeof(magic) - 1
|| BIO_write(wbio,
(char *)salt,
- sizeof salt) != sizeof salt)) {
+ sizeof(salt)) != sizeof(salt))) {
BIO_printf(bio_err, "error writing output file\n");
goto end;
}
- } else if (BIO_read(rbio, mbuf, sizeof mbuf) != sizeof mbuf
+ } else if (BIO_read(rbio, mbuf, sizeof(mbuf)) != sizeof(mbuf)
|| BIO_read(rbio,
(unsigned char *)salt,
- sizeof salt) != sizeof salt) {
+ sizeof(salt)) != sizeof(salt)) {
BIO_printf(bio_err, "error reading input file\n");
goto end;
- } else if (memcmp(mbuf, magic, sizeof magic - 1)) {
+ } else if (memcmp(mbuf, magic, sizeof(magic) - 1)) {
BIO_printf(bio_err, "bad magic number\n");
goto end;
}
sptr = salt;
}
EVP_BytesToKey(cipher, dgst, sptr,
(unsigned char *)str, strlen(str), 1, key, iv);
/*
* zero the complete buffer or the string passed from the command
* line bug picked up by Larry J. Hughes Jr. <hughes@indiana.edu>
*/
if (str == strbuf)
OPENSSL_cleanse(str, SIZE);
else
OPENSSL_cleanse(str, strlen(str));
}
if (hiv != NULL) {
int siz = EVP_CIPHER_iv_length(cipher);
if (siz == 0) {
BIO_printf(bio_err, "warning: iv not use by this cipher\n");
- } else if (!set_hex(hiv, iv, sizeof iv)) {
+ } else if (!set_hex(hiv, iv, sizeof(iv))) {
BIO_printf(bio_err, "invalid hex iv value\n");
goto end;
}
}
if ((hiv == NULL) && (str == NULL)
&& EVP_CIPHER_iv_length(cipher) != 0) {
/*
* No IV was explicitly set and no IV was generated during
* EVP_BytesToKey. Hence the IV is undefined, making correct
* decryption impossible.
*/
BIO_printf(bio_err, "iv undefined\n");
goto end;
}
if ((hkey != NULL) && !set_hex(hkey, key, EVP_CIPHER_key_length(cipher))) {
BIO_printf(bio_err, "invalid hex key value\n");
goto end;
}
if ((benc = BIO_new(BIO_f_cipher())) == NULL)
goto end;
/*
* Since we may be changing parameters work on the encryption context
* rather than calling BIO_set_cipher().
*/
BIO_get_cipher_ctx(benc, &ctx);
if (non_fips_allow)
EVP_CIPHER_CTX_set_flags(ctx, EVP_CIPH_FLAG_NON_FIPS_ALLOW);
if (!EVP_CipherInit_ex(ctx, cipher, NULL, NULL, NULL, enc)) {
BIO_printf(bio_err, "Error setting cipher %s\n",
EVP_CIPHER_name(cipher));
ERR_print_errors(bio_err);
goto end;
}
if (nopad)
EVP_CIPHER_CTX_set_padding(ctx, 0);
if (!EVP_CipherInit_ex(ctx, NULL, NULL, key, iv, enc)) {
BIO_printf(bio_err, "Error setting cipher %s\n",
EVP_CIPHER_name(cipher));
ERR_print_errors(bio_err);
goto end;
}
if (debug) {
BIO_set_callback(benc, BIO_debug_callback);
BIO_set_callback_arg(benc, (char *)bio_err);
}
if (printkey) {
if (!nosalt) {
printf("salt=");
for (i = 0; i < (int)sizeof(salt); i++)
printf("%02X", salt[i]);
printf("\n");
}
if (cipher->key_len > 0) {
printf("key=");
for (i = 0; i < cipher->key_len; i++)
printf("%02X", key[i]);
printf("\n");
}
if (cipher->iv_len > 0) {
printf("iv =");
for (i = 0; i < cipher->iv_len; i++)
printf("%02X", iv[i]);
printf("\n");
}
if (printkey == 2) {
ret = 0;
goto end;
}
}
}
/* Only encrypt/decrypt as we write the file */
if (benc != NULL)
wbio = BIO_push(benc, wbio);
for (;;) {
inl = BIO_read(rbio, (char *)buff, bsize);
if (inl <= 0)
break;
if (BIO_write(wbio, (char *)buff, inl) != inl) {
BIO_printf(bio_err, "error writing output file\n");
goto end;
}
}
if (!BIO_flush(wbio)) {
BIO_printf(bio_err, "bad decrypt\n");
goto end;
}
ret = 0;
if (verbose) {
BIO_printf(bio_err, "bytes read :%8ld\n", BIO_number_read(in));
BIO_printf(bio_err, "bytes written:%8ld\n", BIO_number_written(out));
}
end:
ERR_print_errors(bio_err);
if (strbuf != NULL)
OPENSSL_free(strbuf);
if (buff != NULL)
OPENSSL_free(buff);
if (in != NULL)
BIO_free(in);
if (out != NULL)
BIO_free_all(out);
if (benc != NULL)
BIO_free(benc);
if (b64 != NULL)
BIO_free(b64);
#ifdef ZLIB
if (bzl != NULL)
BIO_free(bzl);
#endif
release_engine(e);
if (pass)
OPENSSL_free(pass);
apps_shutdown();
OPENSSL_EXIT(ret);
}
int set_hex(char *in, unsigned char *out, int size)
{
int i, n;
unsigned char j;
n = strlen(in);
if (n > (size * 2)) {
BIO_printf(bio_err, "hex string is too long\n");
return (0);
}
memset(out, 0, size);
for (i = 0; i < n; i++) {
j = (unsigned char)*in;
*(in++) = '\0';
if (j == 0)
break;
if ((j >= '0') && (j <= '9'))
j -= '0';
else if ((j >= 'A') && (j <= 'F'))
j = j - 'A' + 10;
else if ((j >= 'a') && (j <= 'f'))
j = j - 'a' + 10;
else {
BIO_printf(bio_err, "non-hex digit\n");
return (0);
}
if (i & 1)
out[i / 2] |= j;
else
out[i / 2] = (j << 4);
}
return (1);
}
diff --git a/apps/errstr.c b/apps/errstr.c
index c2d4fdec35ad..c3fef610fc2d 100644
--- a/apps/errstr.c
+++ b/apps/errstr.c
@@ -1,121 +1,121 @@
/* apps/errstr.c */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "apps.h"
#include <openssl/bio.h>
#include <openssl/lhash.h>
#include <openssl/err.h>
#include <openssl/ssl.h>
#undef PROG
#define PROG errstr_main
int MAIN(int, char **);
int MAIN(int argc, char **argv)
{
int i, ret = 0;
char buf[256];
unsigned long l;
apps_startup();
if (bio_err == NULL)
if ((bio_err = BIO_new(BIO_s_file())) != NULL)
BIO_set_fp(bio_err, stderr, BIO_NOCLOSE | BIO_FP_TEXT);
SSL_load_error_strings();
if ((argc > 1) && (strcmp(argv[1], "-stats") == 0)) {
BIO *out = NULL;
out = BIO_new(BIO_s_file());
if ((out != NULL) && BIO_set_fp(out, stdout, BIO_NOCLOSE)) {
#ifdef OPENSSL_SYS_VMS
{
BIO *tmpbio = BIO_new(BIO_f_linebuffer());
out = BIO_push(tmpbio, out);
}
#endif
lh_ERR_STRING_DATA_node_stats_bio(ERR_get_string_table(), out);
lh_ERR_STRING_DATA_stats_bio(ERR_get_string_table(), out);
lh_ERR_STRING_DATA_node_usage_stats_bio(ERR_get_string_table(),
out);
}
if (out != NULL)
BIO_free_all(out);
argc--;
argv++;
}
for (i = 1; i < argc; i++) {
if (sscanf(argv[i], "%lx", &l)) {
- ERR_error_string_n(l, buf, sizeof buf);
+ ERR_error_string_n(l, buf, sizeof(buf));
printf("%s\n", buf);
} else {
printf("%s: bad error code\n", argv[i]);
printf("usage: errstr [-stats] <errno> ...\n");
ret++;
}
}
apps_shutdown();
OPENSSL_EXIT(ret);
}
diff --git a/apps/ocsp.c b/apps/ocsp.c
index 5da51df5148c..654eebcbfc15 100644
--- a/apps/ocsp.c
+++ b/apps/ocsp.c
@@ -1,1367 +1,1367 @@
/* ocsp.c */
/*
* Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL project
* 2000.
*/
/* ====================================================================
* Copyright (c) 1999 The OpenSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* licensing@OpenSSL.org.
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*
* This product includes cryptographic software written by Eric Young
* (eay@cryptsoft.com). This product includes software written by Tim
* Hudson (tjh@cryptsoft.com).
*
*/
#ifndef OPENSSL_NO_OCSP
# ifdef OPENSSL_SYS_VMS
# define _XOPEN_SOURCE_EXTENDED/* So fd_set and friends get properly defined
* on OpenVMS */
# endif
# define USE_SOCKETS
# include <stdio.h>
# include <stdlib.h>
# include <string.h>
# include <time.h>
# include "apps.h" /* needs to be included before the openssl
* headers! */
# include <openssl/e_os2.h>
# include <openssl/crypto.h>
# include <openssl/err.h>
# include <openssl/ssl.h>
# include <openssl/evp.h>
# include <openssl/bn.h>
# include <openssl/x509v3.h>
# if defined(NETWARE_CLIB)
# ifdef NETWARE_BSDSOCK
# include <sys/socket.h>
# include <sys/bsdskt.h>
# else
# include <novsock2.h>
# endif
# elif defined(NETWARE_LIBC)
# ifdef NETWARE_BSDSOCK
# include <sys/select.h>
# else
# include <novsock2.h>
# endif
# endif
/* Maximum leeway in validity period: default 5 minutes */
# define MAX_VALIDITY_PERIOD (5 * 60)
static int add_ocsp_cert(OCSP_REQUEST **req, X509 *cert,
const EVP_MD *cert_id_md, X509 *issuer,
STACK_OF(OCSP_CERTID) *ids);
static int add_ocsp_serial(OCSP_REQUEST **req, char *serial,
const EVP_MD *cert_id_md, X509 *issuer,
STACK_OF(OCSP_CERTID) *ids);
static int print_ocsp_summary(BIO *out, OCSP_BASICRESP *bs, OCSP_REQUEST *req,
STACK_OF(OPENSSL_STRING) *names,
STACK_OF(OCSP_CERTID) *ids, long nsec,
long maxage);
static int make_ocsp_response(OCSP_RESPONSE **resp, OCSP_REQUEST *req,
CA_DB *db, X509 *ca, X509 *rcert,
EVP_PKEY *rkey, const EVP_MD *md,
STACK_OF(X509) *rother, unsigned long flags,
int nmin, int ndays, int badsig);
static char **lookup_serial(CA_DB *db, ASN1_INTEGER *ser);
static BIO *init_responder(const char *port);
static int do_responder(OCSP_REQUEST **preq, BIO **pcbio, BIO *acbio,
const char *port);
static int send_ocsp_response(BIO *cbio, OCSP_RESPONSE *resp);
static OCSP_RESPONSE *query_responder(BIO *err, BIO *cbio, const char *path,
const STACK_OF(CONF_VALUE) *headers,
OCSP_REQUEST *req, int req_timeout);
# undef PROG
# define PROG ocsp_main
int MAIN(int, char **);
int MAIN(int argc, char **argv)
{
ENGINE *e = NULL;
char **args;
char *host = NULL, *port = NULL, *path = "/";
char *thost = NULL, *tport = NULL, *tpath = NULL;
char *reqin = NULL, *respin = NULL;
char *reqout = NULL, *respout = NULL;
char *signfile = NULL, *keyfile = NULL;
char *rsignfile = NULL, *rkeyfile = NULL;
char *outfile = NULL;
int add_nonce = 1, noverify = 0, use_ssl = -1;
STACK_OF(CONF_VALUE) *headers = NULL;
OCSP_REQUEST *req = NULL;
OCSP_RESPONSE *resp = NULL;
OCSP_BASICRESP *bs = NULL;
X509 *issuer = NULL, *cert = NULL;
X509 *signer = NULL, *rsigner = NULL;
EVP_PKEY *key = NULL, *rkey = NULL;
BIO *acbio = NULL, *cbio = NULL;
BIO *derbio = NULL;
BIO *out = NULL;
int req_timeout = -1;
int req_text = 0, resp_text = 0;
long nsec = MAX_VALIDITY_PERIOD, maxage = -1;
char *CAfile = NULL, *CApath = NULL;
X509_STORE *store = NULL;
X509_VERIFY_PARAM *vpm = NULL;
STACK_OF(X509) *sign_other = NULL, *verify_other = NULL, *rother = NULL;
char *sign_certfile = NULL, *verify_certfile = NULL, *rcertfile = NULL;
unsigned long sign_flags = 0, verify_flags = 0, rflags = 0;
int ret = 1;
int accept_count = -1;
int badarg = 0;
int badsig = 0;
int i;
int ignore_err = 0;
STACK_OF(OPENSSL_STRING) *reqnames = NULL;
STACK_OF(OCSP_CERTID) *ids = NULL;
X509 *rca_cert = NULL;
char *ridx_filename = NULL;
char *rca_filename = NULL;
CA_DB *rdb = NULL;
int nmin = 0, ndays = -1;
const EVP_MD *cert_id_md = NULL, *rsign_md = NULL;
if (bio_err == NULL)
bio_err = BIO_new_fp(stderr, BIO_NOCLOSE);
if (!load_config(bio_err, NULL))
goto end;
SSL_load_error_strings();
OpenSSL_add_ssl_algorithms();
args = argv + 1;
reqnames = sk_OPENSSL_STRING_new_null();
ids = sk_OCSP_CERTID_new_null();
while (!badarg && *args && *args[0] == '-') {
if (!strcmp(*args, "-out")) {
if (args[1]) {
args++;
outfile = *args;
} else
badarg = 1;
} else if (!strcmp(*args, "-timeout")) {
if (args[1]) {
args++;
req_timeout = atol(*args);
if (req_timeout < 0) {
BIO_printf(bio_err, "Illegal timeout value %s\n", *args);
badarg = 1;
}
} else
badarg = 1;
} else if (!strcmp(*args, "-url")) {
if (thost)
OPENSSL_free(thost);
if (tport)
OPENSSL_free(tport);
if (tpath)
OPENSSL_free(tpath);
thost = tport = tpath = NULL;
if (args[1]) {
args++;
if (!OCSP_parse_url(*args, &host, &port, &path, &use_ssl)) {
BIO_printf(bio_err, "Error parsing URL\n");
badarg = 1;
}
thost = host;
tport = port;
tpath = path;
} else
badarg = 1;
} else if (!strcmp(*args, "-host")) {
if (args[1]) {
args++;
host = *args;
} else
badarg = 1;
} else if (!strcmp(*args, "-port")) {
if (args[1]) {
args++;
port = *args;
} else
badarg = 1;
} else if (!strcmp(*args, "-header")) {
if (args[1] && args[2]) {
if (!X509V3_add_value(args[1], args[2], &headers))
goto end;
args += 2;
} else
badarg = 1;
} else if (!strcmp(*args, "-ignore_err"))
ignore_err = 1;
else if (!strcmp(*args, "-noverify"))
noverify = 1;
else if (!strcmp(*args, "-nonce"))
add_nonce = 2;
else if (!strcmp(*args, "-no_nonce"))
add_nonce = 0;
else if (!strcmp(*args, "-resp_no_certs"))
rflags |= OCSP_NOCERTS;
else if (!strcmp(*args, "-resp_key_id"))
rflags |= OCSP_RESPID_KEY;
else if (!strcmp(*args, "-no_certs"))
sign_flags |= OCSP_NOCERTS;
else if (!strcmp(*args, "-no_signature_verify"))
verify_flags |= OCSP_NOSIGS;
else if (!strcmp(*args, "-no_cert_verify"))
verify_flags |= OCSP_NOVERIFY;
else if (!strcmp(*args, "-no_chain"))
verify_flags |= OCSP_NOCHAIN;
else if (!strcmp(*args, "-no_cert_checks"))
verify_flags |= OCSP_NOCHECKS;
else if (!strcmp(*args, "-no_explicit"))
verify_flags |= OCSP_NOEXPLICIT;
else if (!strcmp(*args, "-trust_other"))
verify_flags |= OCSP_TRUSTOTHER;
else if (!strcmp(*args, "-no_intern"))
verify_flags |= OCSP_NOINTERN;
else if (!strcmp(*args, "-badsig"))
badsig = 1;
else if (!strcmp(*args, "-text")) {
req_text = 1;
resp_text = 1;
} else if (!strcmp(*args, "-req_text"))
req_text = 1;
else if (!strcmp(*args, "-resp_text"))
resp_text = 1;
else if (!strcmp(*args, "-reqin")) {
if (args[1]) {
args++;
reqin = *args;
} else
badarg = 1;
} else if (!strcmp(*args, "-respin")) {
if (args[1]) {
args++;
respin = *args;
} else
badarg = 1;
} else if (!strcmp(*args, "-signer")) {
if (args[1]) {
args++;
signfile = *args;
} else
badarg = 1;
} else if (!strcmp(*args, "-VAfile")) {
if (args[1]) {
args++;
verify_certfile = *args;
verify_flags |= OCSP_TRUSTOTHER;
} else
badarg = 1;
} else if (!strcmp(*args, "-sign_other")) {
if (args[1]) {
args++;
sign_certfile = *args;
} else
badarg = 1;
} else if (!strcmp(*args, "-verify_other")) {
if (args[1]) {
args++;
verify_certfile = *args;
} else
badarg = 1;
} else if (!strcmp(*args, "-CAfile")) {
if (args[1]) {
args++;
CAfile = *args;
} else
badarg = 1;
} else if (!strcmp(*args, "-CApath")) {
if (args[1]) {
args++;
CApath = *args;
} else
badarg = 1;
} else if (args_verify(&args, NULL, &badarg, bio_err, &vpm)) {
if (badarg)
goto end;
continue;
} else if (!strcmp(*args, "-validity_period")) {
if (args[1]) {
args++;
nsec = atol(*args);
if (nsec < 0) {
BIO_printf(bio_err,
"Illegal validity period %s\n", *args);
badarg = 1;
}
} else
badarg = 1;
} else if (!strcmp(*args, "-status_age")) {
if (args[1]) {
args++;
maxage = atol(*args);
if (maxage < 0) {
BIO_printf(bio_err, "Illegal validity age %s\n", *args);
badarg = 1;
}
} else
badarg = 1;
} else if (!strcmp(*args, "-signkey")) {
if (args[1]) {
args++;
keyfile = *args;
} else
badarg = 1;
} else if (!strcmp(*args, "-reqout")) {
if (args[1]) {
args++;
reqout = *args;
} else
badarg = 1;
} else if (!strcmp(*args, "-respout")) {
if (args[1]) {
args++;
respout = *args;
} else
badarg = 1;
} else if (!strcmp(*args, "-path")) {
if (args[1]) {
args++;
path = *args;
} else
badarg = 1;
} else if (!strcmp(*args, "-issuer")) {
if (args[1]) {
args++;
X509_free(issuer);
issuer = load_cert(bio_err, *args, FORMAT_PEM,
NULL, e, "issuer certificate");
if (!issuer)
goto end;
} else
badarg = 1;
} else if (!strcmp(*args, "-cert")) {
if (args[1]) {
args++;
X509_free(cert);
cert = load_cert(bio_err, *args, FORMAT_PEM,
NULL, e, "certificate");
if (!cert)
goto end;
if (!cert_id_md)
cert_id_md = EVP_sha1();
if (!add_ocsp_cert(&req, cert, cert_id_md, issuer, ids))
goto end;
if (!sk_OPENSSL_STRING_push(reqnames, *args))
goto end;
} else
badarg = 1;
} else if (!strcmp(*args, "-serial")) {
if (args[1]) {
args++;
if (!cert_id_md)
cert_id_md = EVP_sha1();
if (!add_ocsp_serial(&req, *args, cert_id_md, issuer, ids))
goto end;
if (!sk_OPENSSL_STRING_push(reqnames, *args))
goto end;
} else
badarg = 1;
} else if (!strcmp(*args, "-index")) {
if (args[1]) {
args++;
ridx_filename = *args;
} else
badarg = 1;
} else if (!strcmp(*args, "-CA")) {
if (args[1]) {
args++;
rca_filename = *args;
} else
badarg = 1;
} else if (!strcmp(*args, "-nmin")) {
if (args[1]) {
args++;
nmin = atol(*args);
if (nmin < 0) {
BIO_printf(bio_err, "Illegal update period %s\n", *args);
badarg = 1;
}
}
if (ndays == -1)
ndays = 0;
else
badarg = 1;
} else if (!strcmp(*args, "-nrequest")) {
if (args[1]) {
args++;
accept_count = atol(*args);
if (accept_count < 0) {
BIO_printf(bio_err, "Illegal accept count %s\n", *args);
badarg = 1;
}
} else
badarg = 1;
} else if (!strcmp(*args, "-ndays")) {
if (args[1]) {
args++;
ndays = atol(*args);
if (ndays < 0) {
BIO_printf(bio_err, "Illegal update period %s\n", *args);
badarg = 1;
}
} else
badarg = 1;
} else if (!strcmp(*args, "-rsigner")) {
if (args[1]) {
args++;
rsignfile = *args;
} else
badarg = 1;
} else if (!strcmp(*args, "-rkey")) {
if (args[1]) {
args++;
rkeyfile = *args;
} else
badarg = 1;
} else if (!strcmp(*args, "-rother")) {
if (args[1]) {
args++;
rcertfile = *args;
} else
badarg = 1;
} else if (!strcmp(*args, "-rmd")) {
if (args[1]) {
args++;
rsign_md = EVP_get_digestbyname(*args);
if (!rsign_md)
badarg = 1;
} else
badarg = 1;
} else if ((cert_id_md = EVP_get_digestbyname((*args) + 1)) == NULL) {
badarg = 1;
}
args++;
}
/* Have we anything to do? */
if (!req && !reqin && !respin && !(port && ridx_filename))
badarg = 1;
if (badarg) {
BIO_printf(bio_err, "OCSP utility\n");
BIO_printf(bio_err, "Usage ocsp [options]\n");
BIO_printf(bio_err, "where options are\n");
BIO_printf(bio_err, "-out file output filename\n");
BIO_printf(bio_err, "-issuer file issuer certificate\n");
BIO_printf(bio_err, "-cert file certificate to check\n");
BIO_printf(bio_err, "-serial n serial number to check\n");
BIO_printf(bio_err,
"-signer file certificate to sign OCSP request with\n");
BIO_printf(bio_err,
"-signkey file private key to sign OCSP request with\n");
BIO_printf(bio_err,
"-sign_other file additional certificates to include in signed request\n");
BIO_printf(bio_err,
"-no_certs don't include any certificates in signed request\n");
BIO_printf(bio_err,
"-req_text print text form of request\n");
BIO_printf(bio_err,
"-resp_text print text form of response\n");
BIO_printf(bio_err,
"-text print text form of request and response\n");
BIO_printf(bio_err,
"-reqout file write DER encoded OCSP request to \"file\"\n");
BIO_printf(bio_err,
"-respout file write DER encoded OCSP reponse to \"file\"\n");
BIO_printf(bio_err,
"-reqin file read DER encoded OCSP request from \"file\"\n");
BIO_printf(bio_err,
"-respin file read DER encoded OCSP reponse from \"file\"\n");
BIO_printf(bio_err,
"-nonce add OCSP nonce to request\n");
BIO_printf(bio_err,
"-no_nonce don't add OCSP nonce to request\n");
BIO_printf(bio_err, "-url URL OCSP responder URL\n");
BIO_printf(bio_err,
"-host host:n send OCSP request to host on port n\n");
BIO_printf(bio_err,
"-path path to use in OCSP request\n");
BIO_printf(bio_err,
"-CApath dir trusted certificates directory\n");
BIO_printf(bio_err,
"-CAfile file trusted certificates file\n");
BIO_printf(bio_err,
"-no_alt_chains only ever use the first certificate chain found\n");
BIO_printf(bio_err,
"-VAfile file validator certificates file\n");
BIO_printf(bio_err,
"-validity_period n maximum validity discrepancy in seconds\n");
BIO_printf(bio_err,
"-status_age n maximum status age in seconds\n");
BIO_printf(bio_err,
"-noverify don't verify response at all\n");
BIO_printf(bio_err,
"-verify_other file additional certificates to search for signer\n");
BIO_printf(bio_err,
"-trust_other don't verify additional certificates\n");
BIO_printf(bio_err,
"-no_intern don't search certificates contained in response for signer\n");
BIO_printf(bio_err,
"-no_signature_verify don't check signature on response\n");
BIO_printf(bio_err,
"-no_cert_verify don't check signing certificate\n");
BIO_printf(bio_err,
"-no_chain don't chain verify response\n");
BIO_printf(bio_err,
"-no_cert_checks don't do additional checks on signing certificate\n");
BIO_printf(bio_err,
"-port num port to run responder on\n");
BIO_printf(bio_err,
"-index file certificate status index file\n");
BIO_printf(bio_err, "-CA file CA certificate\n");
BIO_printf(bio_err,
"-rsigner file responder certificate to sign responses with\n");
BIO_printf(bio_err,
"-rkey file responder key to sign responses with\n");
BIO_printf(bio_err,
"-rother file other certificates to include in response\n");
BIO_printf(bio_err,
"-resp_no_certs don't include any certificates in response\n");
BIO_printf(bio_err,
"-nmin n number of minutes before next update\n");
BIO_printf(bio_err,
"-ndays n number of days before next update\n");
BIO_printf(bio_err,
"-resp_key_id identify reponse by signing certificate key ID\n");
BIO_printf(bio_err,
"-nrequest n number of requests to accept (default unlimited)\n");
BIO_printf(bio_err,
"-<dgst alg> use specified digest in the request\n");
BIO_printf(bio_err,
"-timeout n timeout connection to OCSP responder after n seconds\n");
goto end;
}
if (outfile)
out = BIO_new_file(outfile, "w");
else
out = BIO_new_fp(stdout, BIO_NOCLOSE);
if (!out) {
BIO_printf(bio_err, "Error opening output file\n");
goto end;
}
if (!req && (add_nonce != 2))
add_nonce = 0;
if (!req && reqin) {
if (!strcmp(reqin, "-"))
derbio = BIO_new_fp(stdin, BIO_NOCLOSE);
else
derbio = BIO_new_file(reqin, "rb");
if (!derbio) {
BIO_printf(bio_err, "Error Opening OCSP request file\n");
goto end;
}
req = d2i_OCSP_REQUEST_bio(derbio, NULL);
BIO_free(derbio);
if (!req) {
BIO_printf(bio_err, "Error reading OCSP request\n");
goto end;
}
}
if (!req && port) {
acbio = init_responder(port);
if (!acbio)
goto end;
}
if (rsignfile && !rdb) {
if (!rkeyfile)
rkeyfile = rsignfile;
rsigner = load_cert(bio_err, rsignfile, FORMAT_PEM,
NULL, e, "responder certificate");
if (!rsigner) {
BIO_printf(bio_err, "Error loading responder certificate\n");
goto end;
}
rca_cert = load_cert(bio_err, rca_filename, FORMAT_PEM,
NULL, e, "CA certificate");
if (rcertfile) {
rother = load_certs(bio_err, rcertfile, FORMAT_PEM,
NULL, e, "responder other certificates");
if (!rother)
goto end;
}
rkey = load_key(bio_err, rkeyfile, FORMAT_PEM, 0, NULL, NULL,
"responder private key");
if (!rkey)
goto end;
}
if (acbio)
BIO_printf(bio_err, "Waiting for OCSP client connections...\n");
redo_accept:
if (acbio) {
if (!do_responder(&req, &cbio, acbio, port))
goto end;
if (!req) {
resp =
OCSP_response_create(OCSP_RESPONSE_STATUS_MALFORMEDREQUEST,
NULL);
send_ocsp_response(cbio, resp);
goto done_resp;
}
}
if (!req && (signfile || reqout || host || add_nonce || ridx_filename)) {
BIO_printf(bio_err, "Need an OCSP request for this operation!\n");
goto end;
}
if (req && add_nonce)
OCSP_request_add1_nonce(req, NULL, -1);
if (signfile) {
if (!keyfile)
keyfile = signfile;
signer = load_cert(bio_err, signfile, FORMAT_PEM,
NULL, e, "signer certificate");
if (!signer) {
BIO_printf(bio_err, "Error loading signer certificate\n");
goto end;
}
if (sign_certfile) {
sign_other = load_certs(bio_err, sign_certfile, FORMAT_PEM,
NULL, e, "signer certificates");
if (!sign_other)
goto end;
}
key = load_key(bio_err, keyfile, FORMAT_PEM, 0, NULL, NULL,
"signer private key");
if (!key)
goto end;
if (!OCSP_request_sign
(req, signer, key, NULL, sign_other, sign_flags)) {
BIO_printf(bio_err, "Error signing OCSP request\n");
goto end;
}
}
if (req_text && req)
OCSP_REQUEST_print(out, req, 0);
if (reqout) {
if (!strcmp(reqout, "-"))
derbio = BIO_new_fp(stdout, BIO_NOCLOSE);
else
derbio = BIO_new_file(reqout, "wb");
if (!derbio) {
BIO_printf(bio_err, "Error opening file %s\n", reqout);
goto end;
}
i2d_OCSP_REQUEST_bio(derbio, req);
BIO_free(derbio);
}
if (ridx_filename && (!rkey || !rsigner || !rca_cert)) {
BIO_printf(bio_err,
"Need a responder certificate, key and CA for this operation!\n");
goto end;
}
if (ridx_filename && !rdb) {
rdb = load_index(ridx_filename, NULL);
if (!rdb)
goto end;
if (!index_index(rdb))
goto end;
}
if (rdb) {
i = make_ocsp_response(&resp, req, rdb, rca_cert, rsigner, rkey,
rsign_md, rother, rflags, nmin, ndays, badsig);
if (cbio)
send_ocsp_response(cbio, resp);
} else if (host) {
# ifndef OPENSSL_NO_SOCK
resp = process_responder(bio_err, req, host, path,
port, use_ssl, headers, req_timeout);
if (!resp)
goto end;
# else
BIO_printf(bio_err,
"Error creating connect BIO - sockets not supported.\n");
goto end;
# endif
} else if (respin) {
if (!strcmp(respin, "-"))
derbio = BIO_new_fp(stdin, BIO_NOCLOSE);
else
derbio = BIO_new_file(respin, "rb");
if (!derbio) {
BIO_printf(bio_err, "Error Opening OCSP response file\n");
goto end;
}
resp = d2i_OCSP_RESPONSE_bio(derbio, NULL);
BIO_free(derbio);
if (!resp) {
BIO_printf(bio_err, "Error reading OCSP response\n");
goto end;
}
} else {
ret = 0;
goto end;
}
done_resp:
if (respout) {
if (!strcmp(respout, "-"))
derbio = BIO_new_fp(stdout, BIO_NOCLOSE);
else
derbio = BIO_new_file(respout, "wb");
if (!derbio) {
BIO_printf(bio_err, "Error opening file %s\n", respout);
goto end;
}
i2d_OCSP_RESPONSE_bio(derbio, resp);
BIO_free(derbio);
}
i = OCSP_response_status(resp);
if (i != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
BIO_printf(out, "Responder Error: %s (%d)\n",
OCSP_response_status_str(i), i);
if (ignore_err)
goto redo_accept;
ret = 0;
goto end;
}
if (resp_text)
OCSP_RESPONSE_print(out, resp, 0);
/* If running as responder don't verify our own response */
if (cbio) {
if (accept_count > 0)
accept_count--;
/* Redo if more connections needed */
if (accept_count) {
BIO_free_all(cbio);
cbio = NULL;
OCSP_REQUEST_free(req);
req = NULL;
OCSP_RESPONSE_free(resp);
resp = NULL;
goto redo_accept;
}
ret = 0;
goto end;
} else if (ridx_filename) {
ret = 0;
goto end;
}
if (!store)
store = setup_verify(bio_err, CAfile, CApath);
if (!store)
goto end;
if (vpm)
X509_STORE_set1_param(store, vpm);
if (verify_certfile) {
verify_other = load_certs(bio_err, verify_certfile, FORMAT_PEM,
NULL, e, "validator certificate");
if (!verify_other)
goto end;
}
bs = OCSP_response_get1_basic(resp);
if (!bs) {
BIO_printf(bio_err, "Error parsing response\n");
goto end;
}
ret = 0;
if (!noverify) {
if (req && ((i = OCSP_check_nonce(req, bs)) <= 0)) {
if (i == -1)
BIO_printf(bio_err, "WARNING: no nonce in response\n");
else {
BIO_printf(bio_err, "Nonce Verify error\n");
ret = 1;
goto end;
}
}
i = OCSP_basic_verify(bs, verify_other, store, verify_flags);
if (i <= 0) {
BIO_printf(bio_err, "Response Verify Failure\n");
ERR_print_errors(bio_err);
ret = 1;
} else
BIO_printf(bio_err, "Response verify OK\n");
}
if (!print_ocsp_summary(out, bs, req, reqnames, ids, nsec, maxage))
ret = 1;
end:
ERR_print_errors(bio_err);
X509_free(signer);
X509_STORE_free(store);
if (vpm)
X509_VERIFY_PARAM_free(vpm);
EVP_PKEY_free(key);
EVP_PKEY_free(rkey);
X509_free(issuer);
X509_free(cert);
X509_free(rsigner);
X509_free(rca_cert);
free_index(rdb);
BIO_free_all(cbio);
BIO_free_all(acbio);
BIO_free(out);
OCSP_REQUEST_free(req);
OCSP_RESPONSE_free(resp);
OCSP_BASICRESP_free(bs);
sk_OPENSSL_STRING_free(reqnames);
sk_OCSP_CERTID_free(ids);
sk_X509_pop_free(sign_other, X509_free);
sk_X509_pop_free(verify_other, X509_free);
sk_CONF_VALUE_pop_free(headers, X509V3_conf_free);
if (thost)
OPENSSL_free(thost);
if (tport)
OPENSSL_free(tport);
if (tpath)
OPENSSL_free(tpath);
OPENSSL_EXIT(ret);
}
static int add_ocsp_cert(OCSP_REQUEST **req, X509 *cert,
const EVP_MD *cert_id_md, X509 *issuer,
STACK_OF(OCSP_CERTID) *ids)
{
OCSP_CERTID *id;
if (!issuer) {
BIO_printf(bio_err, "No issuer certificate specified\n");
return 0;
}
if (!*req)
*req = OCSP_REQUEST_new();
if (!*req)
goto err;
id = OCSP_cert_to_id(cert_id_md, cert, issuer);
if (!id || !sk_OCSP_CERTID_push(ids, id))
goto err;
if (!OCSP_request_add0_id(*req, id))
goto err;
return 1;
err:
BIO_printf(bio_err, "Error Creating OCSP request\n");
return 0;
}
static int add_ocsp_serial(OCSP_REQUEST **req, char *serial,
const EVP_MD *cert_id_md, X509 *issuer,
STACK_OF(OCSP_CERTID) *ids)
{
OCSP_CERTID *id;
X509_NAME *iname;
ASN1_BIT_STRING *ikey;
ASN1_INTEGER *sno;
if (!issuer) {
BIO_printf(bio_err, "No issuer certificate specified\n");
return 0;
}
if (!*req)
*req = OCSP_REQUEST_new();
if (!*req)
goto err;
iname = X509_get_subject_name(issuer);
ikey = X509_get0_pubkey_bitstr(issuer);
sno = s2i_ASN1_INTEGER(NULL, serial);
if (!sno) {
BIO_printf(bio_err, "Error converting serial number %s\n", serial);
return 0;
}
id = OCSP_cert_id_new(cert_id_md, iname, ikey, sno);
ASN1_INTEGER_free(sno);
if (!id || !sk_OCSP_CERTID_push(ids, id))
goto err;
if (!OCSP_request_add0_id(*req, id))
goto err;
return 1;
err:
BIO_printf(bio_err, "Error Creating OCSP request\n");
return 0;
}
static int print_ocsp_summary(BIO *out, OCSP_BASICRESP *bs, OCSP_REQUEST *req,
STACK_OF(OPENSSL_STRING) *names,
STACK_OF(OCSP_CERTID) *ids, long nsec,
long maxage)
{
OCSP_CERTID *id;
char *name;
int i;
int status, reason;
ASN1_GENERALIZEDTIME *rev, *thisupd, *nextupd;
if (!bs || !req || !sk_OPENSSL_STRING_num(names)
|| !sk_OCSP_CERTID_num(ids))
return 1;
for (i = 0; i < sk_OCSP_CERTID_num(ids); i++) {
id = sk_OCSP_CERTID_value(ids, i);
name = sk_OPENSSL_STRING_value(names, i);
BIO_printf(out, "%s: ", name);
if (!OCSP_resp_find_status(bs, id, &status, &reason,
&rev, &thisupd, &nextupd)) {
BIO_puts(out, "ERROR: No Status found.\n");
continue;
}
/*
* Check validity: if invalid write to output BIO so we know which
* response this refers to.
*/
if (!OCSP_check_validity(thisupd, nextupd, nsec, maxage)) {
BIO_puts(out, "WARNING: Status times invalid.\n");
ERR_print_errors(out);
}
BIO_printf(out, "%s\n", OCSP_cert_status_str(status));
BIO_puts(out, "\tThis Update: ");
ASN1_GENERALIZEDTIME_print(out, thisupd);
BIO_puts(out, "\n");
if (nextupd) {
BIO_puts(out, "\tNext Update: ");
ASN1_GENERALIZEDTIME_print(out, nextupd);
BIO_puts(out, "\n");
}
if (status != V_OCSP_CERTSTATUS_REVOKED)
continue;
if (reason != -1)
BIO_printf(out, "\tReason: %s\n", OCSP_crl_reason_str(reason));
BIO_puts(out, "\tRevocation Time: ");
ASN1_GENERALIZEDTIME_print(out, rev);
BIO_puts(out, "\n");
}
return 1;
}
static int make_ocsp_response(OCSP_RESPONSE **resp, OCSP_REQUEST *req,
CA_DB *db, X509 *ca, X509 *rcert,
EVP_PKEY *rkey, const EVP_MD *rmd,
STACK_OF(X509) *rother, unsigned long flags,
int nmin, int ndays, int badsig)
{
ASN1_TIME *thisupd = NULL, *nextupd = NULL;
OCSP_CERTID *cid, *ca_id = NULL;
OCSP_BASICRESP *bs = NULL;
int i, id_count, ret = 1;
id_count = OCSP_request_onereq_count(req);
if (id_count <= 0) {
*resp =
OCSP_response_create(OCSP_RESPONSE_STATUS_MALFORMEDREQUEST, NULL);
goto end;
}
bs = OCSP_BASICRESP_new();
thisupd = X509_gmtime_adj(NULL, 0);
if (ndays != -1)
nextupd = X509_time_adj_ex(NULL, ndays, nmin * 60, NULL);
/* Examine each certificate id in the request */
for (i = 0; i < id_count; i++) {
OCSP_ONEREQ *one;
ASN1_INTEGER *serial;
char **inf;
ASN1_OBJECT *cert_id_md_oid;
const EVP_MD *cert_id_md;
one = OCSP_request_onereq_get0(req, i);
cid = OCSP_onereq_get0_id(one);
OCSP_id_get0_info(NULL, &cert_id_md_oid, NULL, NULL, cid);
cert_id_md = EVP_get_digestbyobj(cert_id_md_oid);
if (!cert_id_md) {
*resp = OCSP_response_create(OCSP_RESPONSE_STATUS_INTERNALERROR,
NULL);
goto end;
}
if (ca_id)
OCSP_CERTID_free(ca_id);
ca_id = OCSP_cert_to_id(cert_id_md, NULL, ca);
/* Is this request about our CA? */
if (OCSP_id_issuer_cmp(ca_id, cid)) {
OCSP_basic_add1_status(bs, cid,
V_OCSP_CERTSTATUS_UNKNOWN,
0, NULL, thisupd, nextupd);
continue;
}
OCSP_id_get0_info(NULL, NULL, NULL, &serial, cid);
inf = lookup_serial(db, serial);
if (!inf)
OCSP_basic_add1_status(bs, cid,
V_OCSP_CERTSTATUS_UNKNOWN,
0, NULL, thisupd, nextupd);
else if (inf[DB_type][0] == DB_TYPE_VAL)
OCSP_basic_add1_status(bs, cid,
V_OCSP_CERTSTATUS_GOOD,
0, NULL, thisupd, nextupd);
else if (inf[DB_type][0] == DB_TYPE_REV) {
ASN1_OBJECT *inst = NULL;
ASN1_TIME *revtm = NULL;
ASN1_GENERALIZEDTIME *invtm = NULL;
OCSP_SINGLERESP *single;
int reason = -1;
unpack_revinfo(&revtm, &reason, &inst, &invtm, inf[DB_rev_date]);
single = OCSP_basic_add1_status(bs, cid,
V_OCSP_CERTSTATUS_REVOKED,
reason, revtm, thisupd, nextupd);
if (invtm)
OCSP_SINGLERESP_add1_ext_i2d(single, NID_invalidity_date,
invtm, 0, 0);
else if (inst)
OCSP_SINGLERESP_add1_ext_i2d(single,
NID_hold_instruction_code, inst,
0, 0);
ASN1_OBJECT_free(inst);
ASN1_TIME_free(revtm);
ASN1_GENERALIZEDTIME_free(invtm);
}
}
OCSP_copy_nonce(bs, req);
OCSP_basic_sign(bs, rcert, rkey, rmd, rother, flags);
if (badsig)
bs->signature->data[bs->signature->length - 1] ^= 0x1;
*resp = OCSP_response_create(OCSP_RESPONSE_STATUS_SUCCESSFUL, bs);
end:
ASN1_TIME_free(thisupd);
ASN1_TIME_free(nextupd);
OCSP_CERTID_free(ca_id);
OCSP_BASICRESP_free(bs);
return ret;
}
static char **lookup_serial(CA_DB *db, ASN1_INTEGER *ser)
{
int i;
BIGNUM *bn = NULL;
char *itmp, *row[DB_NUMBER], **rrow;
for (i = 0; i < DB_NUMBER; i++)
row[i] = NULL;
bn = ASN1_INTEGER_to_BN(ser, NULL);
OPENSSL_assert(bn); /* FIXME: should report an error at this
* point and abort */
if (BN_is_zero(bn))
itmp = BUF_strdup("00");
else
itmp = BN_bn2hex(bn);
row[DB_serial] = itmp;
BN_free(bn);
rrow = TXT_DB_get_by_index(db->db, DB_serial, row);
OPENSSL_free(itmp);
return rrow;
}
/* Quick and dirty OCSP server: read in and parse input request */
static BIO *init_responder(const char *port)
{
BIO *acbio = NULL, *bufbio = NULL;
bufbio = BIO_new(BIO_f_buffer());
if (!bufbio)
goto err;
# ifndef OPENSSL_NO_SOCK
acbio = BIO_new_accept(port);
# else
BIO_printf(bio_err,
"Error setting up accept BIO - sockets not supported.\n");
# endif
if (!acbio)
goto err;
BIO_set_accept_bios(acbio, bufbio);
bufbio = NULL;
if (BIO_do_accept(acbio) <= 0) {
BIO_printf(bio_err, "Error setting up accept BIO\n");
ERR_print_errors(bio_err);
goto err;
}
return acbio;
err:
BIO_free_all(acbio);
BIO_free(bufbio);
return NULL;
}
static int do_responder(OCSP_REQUEST **preq, BIO **pcbio, BIO *acbio,
const char *port)
{
int have_post = 0, len;
OCSP_REQUEST *req = NULL;
char inbuf[1024];
BIO *cbio = NULL;
if (BIO_do_accept(acbio) <= 0) {
BIO_printf(bio_err, "Error accepting connection\n");
ERR_print_errors(bio_err);
return 0;
}
cbio = BIO_pop(acbio);
*pcbio = cbio;
for (;;) {
- len = BIO_gets(cbio, inbuf, sizeof inbuf);
+ len = BIO_gets(cbio, inbuf, sizeof(inbuf));
if (len <= 0)
return 1;
/* Look for "POST" signalling start of query */
if (!have_post) {
if (strncmp(inbuf, "POST", 4)) {
BIO_printf(bio_err, "Invalid request\n");
return 1;
}
have_post = 1;
}
/* Look for end of headers */
if ((inbuf[0] == '\r') || (inbuf[0] == '\n'))
break;
}
/* Try to read OCSP request */
req = d2i_OCSP_REQUEST_bio(cbio, NULL);
if (!req) {
BIO_printf(bio_err, "Error parsing OCSP request\n");
ERR_print_errors(bio_err);
}
*preq = req;
return 1;
}
static int send_ocsp_response(BIO *cbio, OCSP_RESPONSE *resp)
{
char http_resp[] =
"HTTP/1.0 200 OK\r\nContent-type: application/ocsp-response\r\n"
"Content-Length: %d\r\n\r\n";
if (!cbio)
return 0;
BIO_printf(cbio, http_resp, i2d_OCSP_RESPONSE(resp, NULL));
i2d_OCSP_RESPONSE_bio(cbio, resp);
(void)BIO_flush(cbio);
return 1;
}
static OCSP_RESPONSE *query_responder(BIO *err, BIO *cbio, const char *path,
const STACK_OF(CONF_VALUE) *headers,
OCSP_REQUEST *req, int req_timeout)
{
int fd;
int rv;
int i;
OCSP_REQ_CTX *ctx = NULL;
OCSP_RESPONSE *rsp = NULL;
fd_set confds;
struct timeval tv;
if (req_timeout != -1)
BIO_set_nbio(cbio, 1);
rv = BIO_do_connect(cbio);
if ((rv <= 0) && ((req_timeout == -1) || !BIO_should_retry(cbio))) {
BIO_puts(err, "Error connecting BIO\n");
return NULL;
}
if (BIO_get_fd(cbio, &fd) < 0) {
BIO_puts(bio_err, "Can't get connection fd\n");
goto err;
}
if (req_timeout != -1 && rv <= 0) {
FD_ZERO(&confds);
openssl_fdset(fd, &confds);
tv.tv_usec = 0;
tv.tv_sec = req_timeout;
rv = select(fd + 1, NULL, (void *)&confds, NULL, &tv);
if (rv == 0) {
BIO_puts(err, "Timeout on connect\n");
return NULL;
}
}
ctx = OCSP_sendreq_new(cbio, path, NULL, -1);
if (!ctx)
return NULL;
for (i = 0; i < sk_CONF_VALUE_num(headers); i++) {
CONF_VALUE *hdr = sk_CONF_VALUE_value(headers, i);
if (!OCSP_REQ_CTX_add1_header(ctx, hdr->name, hdr->value))
goto err;
}
if (!OCSP_REQ_CTX_set1_req(ctx, req))
goto err;
for (;;) {
rv = OCSP_sendreq_nbio(&rsp, ctx);
if (rv != -1)
break;
if (req_timeout == -1)
continue;
FD_ZERO(&confds);
openssl_fdset(fd, &confds);
tv.tv_usec = 0;
tv.tv_sec = req_timeout;
if (BIO_should_read(cbio))
rv = select(fd + 1, (void *)&confds, NULL, NULL, &tv);
else if (BIO_should_write(cbio))
rv = select(fd + 1, NULL, (void *)&confds, NULL, &tv);
else {
BIO_puts(err, "Unexpected retry condition\n");
goto err;
}
if (rv == 0) {
BIO_puts(err, "Timeout on request\n");
break;
}
if (rv == -1) {
BIO_puts(err, "Select error\n");
break;
}
}
err:
if (ctx)
OCSP_REQ_CTX_free(ctx);
return rsp;
}
OCSP_RESPONSE *process_responder(BIO *err, OCSP_REQUEST *req,
const char *host, const char *path,
const char *port, int use_ssl,
const STACK_OF(CONF_VALUE) *headers,
int req_timeout)
{
BIO *cbio = NULL;
SSL_CTX *ctx = NULL;
OCSP_RESPONSE *resp = NULL;
cbio = BIO_new_connect(host);
if (!cbio) {
BIO_printf(err, "Error creating connect BIO\n");
goto end;
}
if (port)
BIO_set_conn_port(cbio, port);
if (use_ssl == 1) {
BIO *sbio;
ctx = SSL_CTX_new(SSLv23_client_method());
if (ctx == NULL) {
BIO_printf(err, "Error creating SSL context.\n");
goto end;
}
SSL_CTX_set_mode(ctx, SSL_MODE_AUTO_RETRY);
sbio = BIO_new_ssl(ctx, 1);
cbio = BIO_push(sbio, cbio);
}
resp = query_responder(err, cbio, path, headers, req, req_timeout);
if (!resp)
BIO_printf(bio_err, "Error querying OCSP responder\n");
end:
if (cbio)
BIO_free_all(cbio);
if (ctx)
SSL_CTX_free(ctx);
return resp;
}
#endif
diff --git a/apps/openssl.c b/apps/openssl.c
index 687314522319..c3da5d6cd0e9 100644
--- a/apps/openssl.c
+++ b/apps/openssl.c
@@ -1,696 +1,696 @@
/* apps/openssl.c */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
/* ====================================================================
* Copyright (c) 1998-2006 The OpenSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* openssl-core@openssl.org.
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.openssl.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*
* This product includes cryptographic software written by Eric Young
* (eay@cryptsoft.com). This product includes software written by Tim
* Hudson (tjh@cryptsoft.com).
*
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define OPENSSL_C /* tells apps.h to use complete
* apps_startup() */
#include "apps.h"
#include <openssl/bio.h>
#include <openssl/crypto.h>
#include <openssl/rand.h>
#include <openssl/lhash.h>
#include <openssl/conf.h>
#include <openssl/x509.h>
#include <openssl/pem.h>
#include <openssl/ssl.h>
#ifndef OPENSSL_NO_ENGINE
# include <openssl/engine.h>
#endif
#define USE_SOCKETS /* needed for the _O_BINARY defs in the MS
* world */
#include "progs.h"
#include "s_apps.h"
#include <openssl/err.h>
#ifdef OPENSSL_FIPS
# include <openssl/fips.h>
#endif
/*
* The LHASH callbacks ("hash" & "cmp") have been replaced by functions with
* the base prototypes (we cast each variable inside the function to the
* required type of "FUNCTION*"). This removes the necessity for
* macro-generated wrapper functions.
*/
static LHASH_OF(FUNCTION) *prog_init(void);
static int do_cmd(LHASH_OF(FUNCTION) *prog, int argc, char *argv[]);
static void list_pkey(BIO *out);
static void list_cipher(BIO *out);
static void list_md(BIO *out);
char *default_config_file = NULL;
/* Make sure there is only one when MONOLITH is defined */
#ifdef MONOLITH
CONF *config = NULL;
BIO *bio_err = NULL;
#endif
static void lock_dbg_cb(int mode, int type, const char *file, int line)
{
static int modes[CRYPTO_NUM_LOCKS]; /* = {0, 0, ... } */
const char *errstr = NULL;
int rw;
rw = mode & (CRYPTO_READ | CRYPTO_WRITE);
if (!((rw == CRYPTO_READ) || (rw == CRYPTO_WRITE))) {
errstr = "invalid mode";
goto err;
}
if (type < 0 || type >= CRYPTO_NUM_LOCKS) {
errstr = "type out of bounds";
goto err;
}
if (mode & CRYPTO_LOCK) {
if (modes[type]) {
errstr = "already locked";
/*
* must not happen in a single-threaded program (would deadlock)
*/
goto err;
}
modes[type] = rw;
} else if (mode & CRYPTO_UNLOCK) {
if (!modes[type]) {
errstr = "not locked";
goto err;
}
if (modes[type] != rw) {
errstr = (rw == CRYPTO_READ) ?
"CRYPTO_r_unlock on write lock" :
"CRYPTO_w_unlock on read lock";
}
modes[type] = 0;
} else {
errstr = "invalid mode";
goto err;
}
err:
if (errstr) {
/* we cannot use bio_err here */
fprintf(stderr,
"openssl (lock_dbg_cb): %s (mode=%d, type=%d) at %s:%d\n",
errstr, mode, type, file, line);
}
}
#if defined( OPENSSL_SYS_VMS) && (__INITIAL_POINTER_SIZE == 64)
# define ARGV _Argv
#else
# define ARGV Argv
#endif
int main(int Argc, char *ARGV[])
{
ARGS arg;
#define PROG_NAME_SIZE 39
char pname[PROG_NAME_SIZE + 1];
FUNCTION f, *fp;
MS_STATIC const char *prompt;
MS_STATIC char buf[1024];
char *to_free = NULL;
int n, i, ret = 0;
int argc;
char **argv, *p;
LHASH_OF(FUNCTION) *prog = NULL;
long errline;
#if defined( OPENSSL_SYS_VMS) && (__INITIAL_POINTER_SIZE == 64)
/*-
* 2011-03-22 SMS.
* If we have 32-bit pointers everywhere, then we're safe, and
* we bypass this mess, as on non-VMS systems. (See ARGV,
* above.)
* Problem 1: Compaq/HP C before V7.3 always used 32-bit
* pointers for argv[].
* Fix 1: For a 32-bit argv[], when we're using 64-bit pointers
* everywhere else, we always allocate and use a 64-bit
* duplicate of argv[].
* Problem 2: Compaq/HP C V7.3 (Alpha, IA64) before ECO1 failed
* to NULL-terminate a 64-bit argv[]. (As this was written, the
* compiler ECO was available only on IA64.)
* Fix 2: Unless advised not to (VMS_TRUST_ARGV), we test a
* 64-bit argv[argc] for NULL, and, if necessary, use a
* (properly) NULL-terminated (64-bit) duplicate of argv[].
* The same code is used in either case to duplicate argv[].
* Some of these decisions could be handled in preprocessing,
* but the code tends to get even uglier, and the penalty for
* deciding at compile- or run-time is tiny.
*/
char **Argv = NULL;
int free_Argv = 0;
if ((sizeof(_Argv) < 8) /* 32-bit argv[]. */
# if !defined( VMS_TRUST_ARGV)
|| (_Argv[Argc] != NULL) /* Untrusted argv[argc] not NULL. */
# endif
) {
int i;
Argv = OPENSSL_malloc((Argc + 1) * sizeof(char *));
if (Argv == NULL) {
ret = -1;
goto end;
}
for (i = 0; i < Argc; i++)
Argv[i] = _Argv[i];
Argv[Argc] = NULL; /* Certain NULL termination. */
free_Argv = 1;
} else {
/*
* Use the known-good 32-bit argv[] (which needs the type cast to
* satisfy the compiler), or the trusted or tested-good 64-bit argv[]
* as-is.
*/
Argv = (char **)_Argv;
}
#endif /* defined( OPENSSL_SYS_VMS) &&
* (__INITIAL_POINTER_SIZE == 64) */
arg.data = NULL;
arg.count = 0;
if (bio_err == NULL)
if ((bio_err = BIO_new(BIO_s_file())) != NULL)
BIO_set_fp(bio_err, stderr, BIO_NOCLOSE | BIO_FP_TEXT);
if (getenv("OPENSSL_DEBUG_MEMORY") != NULL) { /* if not defined, use
* compiled-in library
* defaults */
if (!(0 == strcmp(getenv("OPENSSL_DEBUG_MEMORY"), "off"))) {
CRYPTO_malloc_debug_init();
CRYPTO_set_mem_debug_options(V_CRYPTO_MDEBUG_ALL);
} else {
/* OPENSSL_DEBUG_MEMORY=off */
CRYPTO_set_mem_debug_functions(0, 0, 0, 0, 0);
}
}
CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON);
#if 0
if (getenv("OPENSSL_DEBUG_LOCKING") != NULL)
#endif
{
CRYPTO_set_locking_callback(lock_dbg_cb);
}
if (getenv("OPENSSL_FIPS")) {
#ifdef OPENSSL_FIPS
if (!FIPS_mode_set(1)) {
ERR_load_crypto_strings();
ERR_print_errors(BIO_new_fp(stderr, BIO_NOCLOSE));
EXIT(1);
}
#else
fprintf(stderr, "FIPS mode not supported.\n");
EXIT(1);
#endif
}
apps_startup();
/* Lets load up our environment a little */
p = getenv("OPENSSL_CONF");
if (p == NULL)
p = getenv("SSLEAY_CONF");
if (p == NULL)
p = to_free = make_config_name();
default_config_file = p;
config = NCONF_new(NULL);
i = NCONF_load(config, p, &errline);
if (i == 0) {
if (ERR_GET_REASON(ERR_peek_last_error())
== CONF_R_NO_SUCH_FILE) {
BIO_printf(bio_err, "WARNING: can't open config file: %s\n", p);
ERR_clear_error();
NCONF_free(config);
config = NULL;
} else {
ERR_print_errors(bio_err);
NCONF_free(config);
exit(1);
}
}
prog = prog_init();
/* first check the program name */
- program_name(Argv[0], pname, sizeof pname);
+ program_name(Argv[0], pname, sizeof(pname));
f.name = pname;
fp = lh_FUNCTION_retrieve(prog, &f);
if (fp != NULL) {
Argv[0] = pname;
ret = fp->func(Argc, Argv);
goto end;
}
/*
* ok, now check that there are not arguments, if there are, run with
* them, shifting the ssleay off the front
*/
if (Argc != 1) {
Argc--;
Argv++;
ret = do_cmd(prog, Argc, Argv);
if (ret < 0)
ret = 0;
goto end;
}
/* ok, lets enter the old 'OpenSSL>' mode */
for (;;) {
ret = 0;
p = buf;
- n = sizeof buf;
+ n = sizeof(buf);
i = 0;
for (;;) {
p[0] = '\0';
if (i++)
prompt = ">";
else
prompt = "OpenSSL> ";
fputs(prompt, stdout);
fflush(stdout);
if (!fgets(p, n, stdin))
goto end;
if (p[0] == '\0')
goto end;
i = strlen(p);
if (i <= 1)
break;
if (p[i - 2] != '\\')
break;
i -= 2;
p += i;
n -= i;
}
if (!chopup_args(&arg, buf, &argc, &argv))
break;
ret = do_cmd(prog, argc, argv);
if (ret < 0) {
ret = 0;
goto end;
}
if (ret != 0)
BIO_printf(bio_err, "error in %s\n", argv[0]);
(void)BIO_flush(bio_err);
}
BIO_printf(bio_err, "bad exit\n");
ret = 1;
end:
if (to_free)
OPENSSL_free(to_free);
if (config != NULL) {
NCONF_free(config);
config = NULL;
}
if (prog != NULL)
lh_FUNCTION_free(prog);
if (arg.data != NULL)
OPENSSL_free(arg.data);
#if defined( OPENSSL_SYS_VMS) && (__INITIAL_POINTER_SIZE == 64)
/* Free any duplicate Argv[] storage. */
if (free_Argv) {
OPENSSL_free(Argv);
}
#endif
apps_shutdown();
CRYPTO_mem_leaks(bio_err);
if (bio_err != NULL) {
BIO_free(bio_err);
bio_err = NULL;
}
OPENSSL_EXIT(ret);
}
#define LIST_STANDARD_COMMANDS "list-standard-commands"
#define LIST_MESSAGE_DIGEST_COMMANDS "list-message-digest-commands"
#define LIST_MESSAGE_DIGEST_ALGORITHMS "list-message-digest-algorithms"
#define LIST_CIPHER_COMMANDS "list-cipher-commands"
#define LIST_CIPHER_ALGORITHMS "list-cipher-algorithms"
#define LIST_PUBLIC_KEY_ALGORITHMS "list-public-key-algorithms"
static int do_cmd(LHASH_OF(FUNCTION) *prog, int argc, char *argv[])
{
FUNCTION f, *fp;
int i, ret = 1, tp, nl;
if ((argc <= 0) || (argv[0] == NULL)) {
ret = 0;
goto end;
}
f.name = argv[0];
fp = lh_FUNCTION_retrieve(prog, &f);
if (fp == NULL) {
if (EVP_get_digestbyname(argv[0])) {
f.type = FUNC_TYPE_MD;
f.func = dgst_main;
fp = &f;
} else if (EVP_get_cipherbyname(argv[0])) {
f.type = FUNC_TYPE_CIPHER;
f.func = enc_main;
fp = &f;
}
}
if (fp != NULL) {
ret = fp->func(argc, argv);
} else if ((strncmp(argv[0], "no-", 3)) == 0) {
BIO *bio_stdout = BIO_new_fp(stdout, BIO_NOCLOSE);
#ifdef OPENSSL_SYS_VMS
{
BIO *tmpbio = BIO_new(BIO_f_linebuffer());
bio_stdout = BIO_push(tmpbio, bio_stdout);
}
#endif
f.name = argv[0] + 3;
ret = (lh_FUNCTION_retrieve(prog, &f) != NULL);
if (!ret)
BIO_printf(bio_stdout, "%s\n", argv[0]);
else
BIO_printf(bio_stdout, "%s\n", argv[0] + 3);
BIO_free_all(bio_stdout);
goto end;
} else if ((strcmp(argv[0], "quit") == 0) ||
(strcmp(argv[0], "q") == 0) ||
(strcmp(argv[0], "exit") == 0) ||
(strcmp(argv[0], "bye") == 0)) {
ret = -1;
goto end;
} else if ((strcmp(argv[0], LIST_STANDARD_COMMANDS) == 0) ||
(strcmp(argv[0], LIST_MESSAGE_DIGEST_COMMANDS) == 0) ||
(strcmp(argv[0], LIST_MESSAGE_DIGEST_ALGORITHMS) == 0) ||
(strcmp(argv[0], LIST_CIPHER_COMMANDS) == 0) ||
(strcmp(argv[0], LIST_CIPHER_ALGORITHMS) == 0) ||
(strcmp(argv[0], LIST_PUBLIC_KEY_ALGORITHMS) == 0)) {
int list_type;
BIO *bio_stdout;
if (strcmp(argv[0], LIST_STANDARD_COMMANDS) == 0)
list_type = FUNC_TYPE_GENERAL;
else if (strcmp(argv[0], LIST_MESSAGE_DIGEST_COMMANDS) == 0)
list_type = FUNC_TYPE_MD;
else if (strcmp(argv[0], LIST_MESSAGE_DIGEST_ALGORITHMS) == 0)
list_type = FUNC_TYPE_MD_ALG;
else if (strcmp(argv[0], LIST_PUBLIC_KEY_ALGORITHMS) == 0)
list_type = FUNC_TYPE_PKEY;
else if (strcmp(argv[0], LIST_CIPHER_ALGORITHMS) == 0)
list_type = FUNC_TYPE_CIPHER_ALG;
else /* strcmp(argv[0],LIST_CIPHER_COMMANDS) == 0 */
list_type = FUNC_TYPE_CIPHER;
bio_stdout = BIO_new_fp(stdout, BIO_NOCLOSE);
#ifdef OPENSSL_SYS_VMS
{
BIO *tmpbio = BIO_new(BIO_f_linebuffer());
bio_stdout = BIO_push(tmpbio, bio_stdout);
}
#endif
if (!load_config(bio_err, NULL))
goto end;
if (list_type == FUNC_TYPE_PKEY)
list_pkey(bio_stdout);
if (list_type == FUNC_TYPE_MD_ALG)
list_md(bio_stdout);
if (list_type == FUNC_TYPE_CIPHER_ALG)
list_cipher(bio_stdout);
else {
for (fp = functions; fp->name != NULL; fp++)
if (fp->type == list_type)
BIO_printf(bio_stdout, "%s\n", fp->name);
}
BIO_free_all(bio_stdout);
ret = 0;
goto end;
} else {
BIO_printf(bio_err, "openssl:Error: '%s' is an invalid command.\n",
argv[0]);
BIO_printf(bio_err, "\nStandard commands");
i = 0;
tp = 0;
for (fp = functions; fp->name != NULL; fp++) {
nl = 0;
#ifdef OPENSSL_NO_CAMELLIA
if (((i++) % 5) == 0)
#else
if (((i++) % 4) == 0)
#endif
{
BIO_printf(bio_err, "\n");
nl = 1;
}
if (fp->type != tp) {
tp = fp->type;
if (!nl)
BIO_printf(bio_err, "\n");
if (tp == FUNC_TYPE_MD) {
i = 1;
BIO_printf(bio_err,
"\nMessage Digest commands (see the `dgst' command for more details)\n");
} else if (tp == FUNC_TYPE_CIPHER) {
i = 1;
BIO_printf(bio_err,
"\nCipher commands (see the `enc' command for more details)\n");
}
}
#ifdef OPENSSL_NO_CAMELLIA
BIO_printf(bio_err, "%-15s", fp->name);
#else
BIO_printf(bio_err, "%-18s", fp->name);
#endif
}
BIO_printf(bio_err, "\n\n");
ret = 0;
}
end:
return (ret);
}
static int SortFnByName(const void *_f1, const void *_f2)
{
const FUNCTION *f1 = _f1;
const FUNCTION *f2 = _f2;
if (f1->type != f2->type)
return f1->type - f2->type;
return strcmp(f1->name, f2->name);
}
static void list_pkey(BIO *out)
{
int i;
for (i = 0; i < EVP_PKEY_asn1_get_count(); i++) {
const EVP_PKEY_ASN1_METHOD *ameth;
int pkey_id, pkey_base_id, pkey_flags;
const char *pinfo, *pem_str;
ameth = EVP_PKEY_asn1_get0(i);
EVP_PKEY_asn1_get0_info(&pkey_id, &pkey_base_id, &pkey_flags,
&pinfo, &pem_str, ameth);
if (pkey_flags & ASN1_PKEY_ALIAS) {
BIO_printf(out, "Name: %s\n", OBJ_nid2ln(pkey_id));
BIO_printf(out, "\tType: Alias to %s\n",
OBJ_nid2ln(pkey_base_id));
} else {
BIO_printf(out, "Name: %s\n", pinfo);
BIO_printf(out, "\tType: %s Algorithm\n",
pkey_flags & ASN1_PKEY_DYNAMIC ?
"External" : "Builtin");
BIO_printf(out, "\tOID: %s\n", OBJ_nid2ln(pkey_id));
if (pem_str == NULL)
pem_str = "(none)";
BIO_printf(out, "\tPEM string: %s\n", pem_str);
}
}
}
static void list_cipher_fn(const EVP_CIPHER *c,
const char *from, const char *to, void *arg)
{
if (c)
BIO_printf(arg, "%s\n", EVP_CIPHER_name(c));
else {
if (!from)
from = "<undefined>";
if (!to)
to = "<undefined>";
BIO_printf(arg, "%s => %s\n", from, to);
}
}
static void list_cipher(BIO *out)
{
EVP_CIPHER_do_all_sorted(list_cipher_fn, out);
}
static void list_md_fn(const EVP_MD *m,
const char *from, const char *to, void *arg)
{
if (m)
BIO_printf(arg, "%s\n", EVP_MD_name(m));
else {
if (!from)
from = "<undefined>";
if (!to)
to = "<undefined>";
BIO_printf(arg, "%s => %s\n", from, to);
}
}
static void list_md(BIO *out)
{
EVP_MD_do_all_sorted(list_md_fn, out);
}
static int MS_CALLBACK function_cmp(const FUNCTION * a, const FUNCTION * b)
{
return strncmp(a->name, b->name, 8);
}
static IMPLEMENT_LHASH_COMP_FN(function, FUNCTION)
static unsigned long MS_CALLBACK function_hash(const FUNCTION * a)
{
return lh_strhash(a->name);
}
static IMPLEMENT_LHASH_HASH_FN(function, FUNCTION)
static LHASH_OF(FUNCTION) *prog_init(void)
{
LHASH_OF(FUNCTION) *ret;
FUNCTION *f;
size_t i;
/* Purely so it looks nice when the user hits ? */
for (i = 0, f = functions; f->name != NULL; ++f, ++i) ;
- qsort(functions, i, sizeof *functions, SortFnByName);
+ qsort(functions, i, sizeof(*functions), SortFnByName);
if ((ret = lh_FUNCTION_new()) == NULL)
return (NULL);
for (f = functions; f->name != NULL; f++)
(void)lh_FUNCTION_insert(ret, f);
return (ret);
}
diff --git a/apps/passwd.c b/apps/passwd.c
index 798a6d593616..56e10ad3d8f1 100644
--- a/apps/passwd.c
+++ b/apps/passwd.c
@@ -1,494 +1,494 @@
/* apps/passwd.c */
#if defined OPENSSL_NO_MD5 || defined CHARSET_EBCDIC
# define NO_MD5CRYPT_1
#endif
#if !defined(OPENSSL_NO_DES) || !defined(NO_MD5CRYPT_1)
# include <assert.h>
# include <string.h>
# include "apps.h"
# include <openssl/bio.h>
# include <openssl/err.h>
# include <openssl/evp.h>
# include <openssl/rand.h>
# ifndef OPENSSL_NO_DES
# include <openssl/des.h>
# endif
# ifndef NO_MD5CRYPT_1
# include <openssl/md5.h>
# endif
# undef PROG
# define PROG passwd_main
static unsigned const char cov_2char[64] = {
/* from crypto/des/fcrypt.c */
0x2E, 0x2F, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35,
0x36, 0x37, 0x38, 0x39, 0x41, 0x42, 0x43, 0x44,
0x45, 0x46, 0x47, 0x48, 0x49, 0x4A, 0x4B, 0x4C,
0x4D, 0x4E, 0x4F, 0x50, 0x51, 0x52, 0x53, 0x54,
0x55, 0x56, 0x57, 0x58, 0x59, 0x5A, 0x61, 0x62,
0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6A,
0x6B, 0x6C, 0x6D, 0x6E, 0x6F, 0x70, 0x71, 0x72,
0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7A
};
static int do_passwd(int passed_salt, char **salt_p, char **salt_malloc_p,
char *passwd, BIO *out, int quiet, int table,
int reverse, size_t pw_maxlen, int usecrypt, int use1,
int useapr1);
/*-
* -crypt - standard Unix password algorithm (default)
* -1 - MD5-based password algorithm
* -apr1 - MD5-based password algorithm, Apache variant
* -salt string - salt
* -in file - read passwords from file
* -stdin - read passwords from stdin
* -noverify - never verify when reading password from terminal
* -quiet - no warnings
* -table - format output as table
* -reverse - switch table columns
*/
int MAIN(int, char **);
int MAIN(int argc, char **argv)
{
int ret = 1;
char *infile = NULL;
int in_stdin = 0;
int in_noverify = 0;
char *salt = NULL, *passwd = NULL, **passwds = NULL;
char *salt_malloc = NULL, *passwd_malloc = NULL;
size_t passwd_malloc_size = 0;
int pw_source_defined = 0;
BIO *in = NULL, *out = NULL;
int i, badopt, opt_done;
int passed_salt = 0, quiet = 0, table = 0, reverse = 0;
int usecrypt = 0, use1 = 0, useapr1 = 0;
size_t pw_maxlen = 0;
apps_startup();
if (bio_err == NULL)
if ((bio_err = BIO_new(BIO_s_file())) != NULL)
BIO_set_fp(bio_err, stderr, BIO_NOCLOSE | BIO_FP_TEXT);
if (!load_config(bio_err, NULL))
goto err;
out = BIO_new(BIO_s_file());
if (out == NULL)
goto err;
BIO_set_fp(out, stdout, BIO_NOCLOSE | BIO_FP_TEXT);
# ifdef OPENSSL_SYS_VMS
{
BIO *tmpbio = BIO_new(BIO_f_linebuffer());
out = BIO_push(tmpbio, out);
}
# endif
badopt = 0, opt_done = 0;
i = 0;
while (!badopt && !opt_done && argv[++i] != NULL) {
if (strcmp(argv[i], "-crypt") == 0)
usecrypt = 1;
else if (strcmp(argv[i], "-1") == 0)
use1 = 1;
else if (strcmp(argv[i], "-apr1") == 0)
useapr1 = 1;
else if (strcmp(argv[i], "-salt") == 0) {
if ((argv[i + 1] != NULL) && (salt == NULL)) {
passed_salt = 1;
salt = argv[++i];
} else
badopt = 1;
} else if (strcmp(argv[i], "-in") == 0) {
if ((argv[i + 1] != NULL) && !pw_source_defined) {
pw_source_defined = 1;
infile = argv[++i];
} else
badopt = 1;
} else if (strcmp(argv[i], "-stdin") == 0) {
if (!pw_source_defined) {
pw_source_defined = 1;
in_stdin = 1;
} else
badopt = 1;
} else if (strcmp(argv[i], "-noverify") == 0)
in_noverify = 1;
else if (strcmp(argv[i], "-quiet") == 0)
quiet = 1;
else if (strcmp(argv[i], "-table") == 0)
table = 1;
else if (strcmp(argv[i], "-reverse") == 0)
reverse = 1;
else if (argv[i][0] == '-')
badopt = 1;
else if (!pw_source_defined)
/* non-option arguments, use as passwords */
{
pw_source_defined = 1;
passwds = &argv[i];
opt_done = 1;
} else
badopt = 1;
}
if (!usecrypt && !use1 && !useapr1) /* use default */
usecrypt = 1;
if (usecrypt + use1 + useapr1 > 1) /* conflict */
badopt = 1;
/* reject unsupported algorithms */
# ifdef OPENSSL_NO_DES
if (usecrypt)
badopt = 1;
# endif
# ifdef NO_MD5CRYPT_1
if (use1 || useapr1)
badopt = 1;
# endif
if (badopt) {
BIO_printf(bio_err, "Usage: passwd [options] [passwords]\n");
BIO_printf(bio_err, "where options are\n");
# ifndef OPENSSL_NO_DES
BIO_printf(bio_err,
"-crypt standard Unix password algorithm (default)\n");
# endif
# ifndef NO_MD5CRYPT_1
BIO_printf(bio_err,
"-1 MD5-based password algorithm\n");
BIO_printf(bio_err,
"-apr1 MD5-based password algorithm, Apache variant\n");
# endif
BIO_printf(bio_err, "-salt string use provided salt\n");
BIO_printf(bio_err, "-in file read passwords from file\n");
BIO_printf(bio_err, "-stdin read passwords from stdin\n");
BIO_printf(bio_err,
"-noverify never verify when reading password from terminal\n");
BIO_printf(bio_err, "-quiet no warnings\n");
BIO_printf(bio_err, "-table format output as table\n");
BIO_printf(bio_err, "-reverse switch table columns\n");
goto err;
}
if ((infile != NULL) || in_stdin) {
in = BIO_new(BIO_s_file());
if (in == NULL)
goto err;
if (infile != NULL) {
assert(in_stdin == 0);
if (BIO_read_filename(in, infile) <= 0)
goto err;
} else {
assert(in_stdin);
BIO_set_fp(in, stdin, BIO_NOCLOSE);
}
}
if (usecrypt)
pw_maxlen = 8;
else if (use1 || useapr1)
pw_maxlen = 256; /* arbitrary limit, should be enough for most
* passwords */
if (passwds == NULL) {
/* no passwords on the command line */
passwd_malloc_size = pw_maxlen + 2;
/*
* longer than necessary so that we can warn about truncation
*/
passwd = passwd_malloc = OPENSSL_malloc(passwd_malloc_size);
if (passwd_malloc == NULL)
goto err;
}
if ((in == NULL) && (passwds == NULL)) {
/* build a null-terminated list */
static char *passwds_static[2] = { NULL, NULL };
passwds = passwds_static;
if (in == NULL)
if (EVP_read_pw_string
(passwd_malloc, passwd_malloc_size, "Password: ",
!(passed_salt || in_noverify)) != 0)
goto err;
passwds[0] = passwd_malloc;
}
if (in == NULL) {
assert(passwds != NULL);
assert(*passwds != NULL);
do { /* loop over list of passwords */
passwd = *passwds++;
if (!do_passwd(passed_salt, &salt, &salt_malloc, passwd, out,
quiet, table, reverse, pw_maxlen, usecrypt, use1,
useapr1))
goto err;
}
while (*passwds != NULL);
} else
/* in != NULL */
{
int done;
assert(passwd != NULL);
do {
int r = BIO_gets(in, passwd, pw_maxlen + 1);
if (r > 0) {
char *c = (strchr(passwd, '\n'));
if (c != NULL)
*c = 0; /* truncate at newline */
else {
/* ignore rest of line */
char trash[BUFSIZ];
do
- r = BIO_gets(in, trash, sizeof trash);
+ r = BIO_gets(in, trash, sizeof(trash));
while ((r > 0) && (!strchr(trash, '\n')));
}
if (!do_passwd(passed_salt, &salt, &salt_malloc, passwd, out,
quiet, table, reverse, pw_maxlen, usecrypt,
use1, useapr1))
goto err;
}
done = (r <= 0);
}
while (!done);
}
ret = 0;
err:
ERR_print_errors(bio_err);
if (salt_malloc)
OPENSSL_free(salt_malloc);
if (passwd_malloc)
OPENSSL_free(passwd_malloc);
if (in)
BIO_free(in);
if (out)
BIO_free_all(out);
apps_shutdown();
OPENSSL_EXIT(ret);
}
# ifndef NO_MD5CRYPT_1
/*
* MD5-based password algorithm (should probably be available as a library
* function; then the static buffer would not be acceptable). For magic
* string "1", this should be compatible to the MD5-based BSD password
* algorithm. For 'magic' string "apr1", this is compatible to the MD5-based
* Apache password algorithm. (Apparently, the Apache password algorithm is
* identical except that the 'magic' string was changed -- the laziest
* application of the NIH principle I've ever encountered.)
*/
static char *md5crypt(const char *passwd, const char *magic, const char *salt)
{
/* "$apr1$..salt..$.......md5hash..........\0" */
static char out_buf[6 + 9 + 24 + 2];
unsigned char buf[MD5_DIGEST_LENGTH];
char *salt_out;
int n;
unsigned int i;
EVP_MD_CTX md, md2;
size_t passwd_len, salt_len;
passwd_len = strlen(passwd);
out_buf[0] = '$';
out_buf[1] = 0;
assert(strlen(magic) <= 4); /* "1" or "apr1" */
strncat(out_buf, magic, 4);
strncat(out_buf, "$", 1);
strncat(out_buf, salt, 8);
assert(strlen(out_buf) <= 6 + 8); /* "$apr1$..salt.." */
salt_out = out_buf + 2 + strlen(magic);
salt_len = strlen(salt_out);
assert(salt_len <= 8);
EVP_MD_CTX_init(&md);
EVP_DigestInit_ex(&md, EVP_md5(), NULL);
EVP_DigestUpdate(&md, passwd, passwd_len);
EVP_DigestUpdate(&md, "$", 1);
EVP_DigestUpdate(&md, magic, strlen(magic));
EVP_DigestUpdate(&md, "$", 1);
EVP_DigestUpdate(&md, salt_out, salt_len);
EVP_MD_CTX_init(&md2);
EVP_DigestInit_ex(&md2, EVP_md5(), NULL);
EVP_DigestUpdate(&md2, passwd, passwd_len);
EVP_DigestUpdate(&md2, salt_out, salt_len);
EVP_DigestUpdate(&md2, passwd, passwd_len);
EVP_DigestFinal_ex(&md2, buf, NULL);
- for (i = passwd_len; i > sizeof buf; i -= sizeof buf)
- EVP_DigestUpdate(&md, buf, sizeof buf);
+ for (i = passwd_len; i > sizeof(buf); i -= sizeof(buf))
+ EVP_DigestUpdate(&md, buf, sizeof(buf));
EVP_DigestUpdate(&md, buf, i);
n = passwd_len;
while (n) {
EVP_DigestUpdate(&md, (n & 1) ? "\0" : passwd, 1);
n >>= 1;
}
EVP_DigestFinal_ex(&md, buf, NULL);
for (i = 0; i < 1000; i++) {
EVP_DigestInit_ex(&md2, EVP_md5(), NULL);
EVP_DigestUpdate(&md2, (i & 1) ? (unsigned const char *)passwd : buf,
- (i & 1) ? passwd_len : sizeof buf);
+ (i & 1) ? passwd_len : sizeof(buf));
if (i % 3)
EVP_DigestUpdate(&md2, salt_out, salt_len);
if (i % 7)
EVP_DigestUpdate(&md2, passwd, passwd_len);
EVP_DigestUpdate(&md2, (i & 1) ? buf : (unsigned const char *)passwd,
- (i & 1) ? sizeof buf : passwd_len);
+ (i & 1) ? sizeof(buf) : passwd_len);
EVP_DigestFinal_ex(&md2, buf, NULL);
}
EVP_MD_CTX_cleanup(&md2);
{
/* transform buf into output string */
- unsigned char buf_perm[sizeof buf];
+ unsigned char buf_perm[sizeof(buf)];
int dest, source;
char *output;
/* silly output permutation */
for (dest = 0, source = 0; dest < 14;
dest++, source = (source + 6) % 17)
buf_perm[dest] = buf[source];
buf_perm[14] = buf[5];
buf_perm[15] = buf[11];
# ifndef PEDANTIC /* Unfortunately, this generates a "no
* effect" warning */
- assert(16 == sizeof buf_perm);
+ assert(16 == sizeof(buf_perm));
# endif
output = salt_out + salt_len;
assert(output == out_buf + strlen(out_buf));
*output++ = '$';
for (i = 0; i < 15; i += 3) {
*output++ = cov_2char[buf_perm[i + 2] & 0x3f];
*output++ = cov_2char[((buf_perm[i + 1] & 0xf) << 2) |
(buf_perm[i + 2] >> 6)];
*output++ = cov_2char[((buf_perm[i] & 3) << 4) |
(buf_perm[i + 1] >> 4)];
*output++ = cov_2char[buf_perm[i] >> 2];
}
assert(i == 15);
*output++ = cov_2char[buf_perm[i] & 0x3f];
*output++ = cov_2char[buf_perm[i] >> 6];
*output = 0;
assert(strlen(out_buf) < sizeof(out_buf));
}
EVP_MD_CTX_cleanup(&md);
return out_buf;
}
# endif
static int do_passwd(int passed_salt, char **salt_p, char **salt_malloc_p,
char *passwd, BIO *out, int quiet, int table,
int reverse, size_t pw_maxlen, int usecrypt, int use1,
int useapr1)
{
char *hash = NULL;
assert(salt_p != NULL);
assert(salt_malloc_p != NULL);
/* first make sure we have a salt */
if (!passed_salt) {
# ifndef OPENSSL_NO_DES
if (usecrypt) {
if (*salt_malloc_p == NULL) {
*salt_p = *salt_malloc_p = OPENSSL_malloc(3);
if (*salt_malloc_p == NULL)
goto err;
}
if (RAND_bytes((unsigned char *)*salt_p, 2) <= 0)
goto err;
(*salt_p)[0] = cov_2char[(*salt_p)[0] & 0x3f]; /* 6 bits */
(*salt_p)[1] = cov_2char[(*salt_p)[1] & 0x3f]; /* 6 bits */
(*salt_p)[2] = 0;
# ifdef CHARSET_EBCDIC
ascii2ebcdic(*salt_p, *salt_p, 2); /* des_crypt will convert back
* to ASCII */
# endif
}
# endif /* !OPENSSL_NO_DES */
# ifndef NO_MD5CRYPT_1
if (use1 || useapr1) {
int i;
if (*salt_malloc_p == NULL) {
*salt_p = *salt_malloc_p = OPENSSL_malloc(9);
if (*salt_malloc_p == NULL)
goto err;
}
if (RAND_bytes((unsigned char *)*salt_p, 8) <= 0)
goto err;
for (i = 0; i < 8; i++)
(*salt_p)[i] = cov_2char[(*salt_p)[i] & 0x3f]; /* 6 bits */
(*salt_p)[8] = 0;
}
# endif /* !NO_MD5CRYPT_1 */
}
assert(*salt_p != NULL);
/* truncate password if necessary */
if ((strlen(passwd) > pw_maxlen)) {
if (!quiet)
/*
* XXX: really we should know how to print a size_t, not cast it
*/
BIO_printf(bio_err,
"Warning: truncating password to %u characters\n",
(unsigned)pw_maxlen);
passwd[pw_maxlen] = 0;
}
assert(strlen(passwd) <= pw_maxlen);
/* now compute password hash */
# ifndef OPENSSL_NO_DES
if (usecrypt)
hash = DES_crypt(passwd, *salt_p);
# endif
# ifndef NO_MD5CRYPT_1
if (use1 || useapr1)
hash = md5crypt(passwd, (use1 ? "1" : "apr1"), *salt_p);
# endif
assert(hash != NULL);
if (table && !reverse)
BIO_printf(out, "%s\t%s\n", passwd, hash);
else if (table && reverse)
BIO_printf(out, "%s\t%s\n", hash, passwd);
else
BIO_printf(out, "%s\n", hash);
return 1;
err:
return 0;
}
#else
int MAIN(int argc, char **argv)
{
fputs("Program not available.\n", stderr)
OPENSSL_EXIT(1);
}
#endif
diff --git a/apps/pkcs12.c b/apps/pkcs12.c
index d0bd97af0eee..0ba4c9a8076a 100644
--- a/apps/pkcs12.c
+++ b/apps/pkcs12.c
@@ -1,1112 +1,1112 @@
/* pkcs12.c */
/*
* Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL
* project.
*/
/* ====================================================================
* Copyright (c) 1999-2006 The OpenSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* licensing@OpenSSL.org.
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*
* This product includes cryptographic software written by Eric Young
* (eay@cryptsoft.com). This product includes software written by Tim
* Hudson (tjh@cryptsoft.com).
*
*/
#include <openssl/opensslconf.h>
#if !defined(OPENSSL_NO_DES) && !defined(OPENSSL_NO_SHA1)
# include <stdio.h>
# include <stdlib.h>
# include <string.h>
# include "apps.h"
# include <openssl/crypto.h>
# include <openssl/err.h>
# include <openssl/pem.h>
# include <openssl/pkcs12.h>
# define PROG pkcs12_main
const EVP_CIPHER *enc;
# define NOKEYS 0x1
# define NOCERTS 0x2
# define INFO 0x4
# define CLCERTS 0x8
# define CACERTS 0x10
static int get_cert_chain(X509 *cert, X509_STORE *store,
STACK_OF(X509) **chain);
int dump_certs_keys_p12(BIO *out, PKCS12 *p12, char *pass, int passlen,
int options, char *pempass);
int dump_certs_pkeys_bags(BIO *out, STACK_OF(PKCS12_SAFEBAG) *bags,
char *pass, int passlen, int options,
char *pempass);
int dump_certs_pkeys_bag(BIO *out, PKCS12_SAFEBAG *bags, char *pass,
int passlen, int options, char *pempass);
int print_attribs(BIO *out, STACK_OF(X509_ATTRIBUTE) *attrlst,
const char *name);
void hex_prin(BIO *out, unsigned char *buf, int len);
int alg_print(BIO *x, X509_ALGOR *alg);
int cert_load(BIO *in, STACK_OF(X509) *sk);
static int set_pbe(BIO *err, int *ppbe, const char *str);
int MAIN(int, char **);
int MAIN(int argc, char **argv)
{
ENGINE *e = NULL;
char *infile = NULL, *outfile = NULL, *keyname = NULL;
char *certfile = NULL;
BIO *in = NULL, *out = NULL;
char **args;
char *name = NULL;
char *csp_name = NULL;
int add_lmk = 0;
PKCS12 *p12 = NULL;
char pass[50], macpass[50];
int export_cert = 0;
int options = 0;
int chain = 0;
int badarg = 0;
int iter = PKCS12_DEFAULT_ITER;
int maciter = PKCS12_DEFAULT_ITER;
int twopass = 0;
int keytype = 0;
int cert_pbe;
int key_pbe = NID_pbe_WithSHA1And3_Key_TripleDES_CBC;
int ret = 1;
int macver = 1;
int noprompt = 0;
STACK_OF(OPENSSL_STRING) *canames = NULL;
char *cpass = NULL, *mpass = NULL;
char *passargin = NULL, *passargout = NULL, *passarg = NULL;
char *passin = NULL, *passout = NULL;
char *inrand = NULL;
char *macalg = NULL;
char *CApath = NULL, *CAfile = NULL;
char *engine = NULL;
apps_startup();
enc = EVP_des_ede3_cbc();
if (bio_err == NULL)
bio_err = BIO_new_fp(stderr, BIO_NOCLOSE);
if (!load_config(bio_err, NULL))
goto end;
# ifdef OPENSSL_FIPS
if (FIPS_mode())
cert_pbe = NID_pbe_WithSHA1And3_Key_TripleDES_CBC;
else
# endif
cert_pbe = NID_pbe_WithSHA1And40BitRC2_CBC;
args = argv + 1;
while (*args) {
if (*args[0] == '-') {
if (!strcmp(*args, "-nokeys"))
options |= NOKEYS;
else if (!strcmp(*args, "-keyex"))
keytype = KEY_EX;
else if (!strcmp(*args, "-keysig"))
keytype = KEY_SIG;
else if (!strcmp(*args, "-nocerts"))
options |= NOCERTS;
else if (!strcmp(*args, "-clcerts"))
options |= CLCERTS;
else if (!strcmp(*args, "-cacerts"))
options |= CACERTS;
else if (!strcmp(*args, "-noout"))
options |= (NOKEYS | NOCERTS);
else if (!strcmp(*args, "-info"))
options |= INFO;
else if (!strcmp(*args, "-chain"))
chain = 1;
else if (!strcmp(*args, "-twopass"))
twopass = 1;
else if (!strcmp(*args, "-nomacver"))
macver = 0;
else if (!strcmp(*args, "-descert"))
cert_pbe = NID_pbe_WithSHA1And3_Key_TripleDES_CBC;
else if (!strcmp(*args, "-export"))
export_cert = 1;
else if (!strcmp(*args, "-des"))
enc = EVP_des_cbc();
else if (!strcmp(*args, "-des3"))
enc = EVP_des_ede3_cbc();
# ifndef OPENSSL_NO_IDEA
else if (!strcmp(*args, "-idea"))
enc = EVP_idea_cbc();
# endif
# ifndef OPENSSL_NO_SEED
else if (!strcmp(*args, "-seed"))
enc = EVP_seed_cbc();
# endif
# ifndef OPENSSL_NO_AES
else if (!strcmp(*args, "-aes128"))
enc = EVP_aes_128_cbc();
else if (!strcmp(*args, "-aes192"))
enc = EVP_aes_192_cbc();
else if (!strcmp(*args, "-aes256"))
enc = EVP_aes_256_cbc();
# endif
# ifndef OPENSSL_NO_CAMELLIA
else if (!strcmp(*args, "-camellia128"))
enc = EVP_camellia_128_cbc();
else if (!strcmp(*args, "-camellia192"))
enc = EVP_camellia_192_cbc();
else if (!strcmp(*args, "-camellia256"))
enc = EVP_camellia_256_cbc();
# endif
else if (!strcmp(*args, "-noiter"))
iter = 1;
else if (!strcmp(*args, "-maciter"))
maciter = PKCS12_DEFAULT_ITER;
else if (!strcmp(*args, "-nomaciter"))
maciter = 1;
else if (!strcmp(*args, "-nomac"))
maciter = -1;
else if (!strcmp(*args, "-macalg"))
if (args[1]) {
args++;
macalg = *args;
} else
badarg = 1;
else if (!strcmp(*args, "-nodes"))
enc = NULL;
else if (!strcmp(*args, "-certpbe")) {
if (!set_pbe(bio_err, &cert_pbe, *++args))
badarg = 1;
} else if (!strcmp(*args, "-keypbe")) {
if (!set_pbe(bio_err, &key_pbe, *++args))
badarg = 1;
} else if (!strcmp(*args, "-rand")) {
if (args[1]) {
args++;
inrand = *args;
} else
badarg = 1;
} else if (!strcmp(*args, "-inkey")) {
if (args[1]) {
args++;
keyname = *args;
} else
badarg = 1;
} else if (!strcmp(*args, "-certfile")) {
if (args[1]) {
args++;
certfile = *args;
} else
badarg = 1;
} else if (!strcmp(*args, "-name")) {
if (args[1]) {
args++;
name = *args;
} else
badarg = 1;
} else if (!strcmp(*args, "-LMK"))
add_lmk = 1;
else if (!strcmp(*args, "-CSP")) {
if (args[1]) {
args++;
csp_name = *args;
} else
badarg = 1;
} else if (!strcmp(*args, "-caname")) {
if (args[1]) {
args++;
if (!canames)
canames = sk_OPENSSL_STRING_new_null();
sk_OPENSSL_STRING_push(canames, *args);
} else
badarg = 1;
} else if (!strcmp(*args, "-in")) {
if (args[1]) {
args++;
infile = *args;
} else
badarg = 1;
} else if (!strcmp(*args, "-out")) {
if (args[1]) {
args++;
outfile = *args;
} else
badarg = 1;
} else if (!strcmp(*args, "-passin")) {
if (args[1]) {
args++;
passargin = *args;
} else
badarg = 1;
} else if (!strcmp(*args, "-passout")) {
if (args[1]) {
args++;
passargout = *args;
} else
badarg = 1;
} else if (!strcmp(*args, "-password")) {
if (args[1]) {
args++;
passarg = *args;
noprompt = 1;
} else
badarg = 1;
} else if (!strcmp(*args, "-CApath")) {
if (args[1]) {
args++;
CApath = *args;
} else
badarg = 1;
} else if (!strcmp(*args, "-CAfile")) {
if (args[1]) {
args++;
CAfile = *args;
} else
badarg = 1;
# ifndef OPENSSL_NO_ENGINE
} else if (!strcmp(*args, "-engine")) {
if (args[1]) {
args++;
engine = *args;
} else
badarg = 1;
# endif
} else
badarg = 1;
} else
badarg = 1;
args++;
}
if (badarg) {
BIO_printf(bio_err, "Usage: pkcs12 [options]\n");
BIO_printf(bio_err, "where options are\n");
BIO_printf(bio_err, "-export output PKCS12 file\n");
BIO_printf(bio_err, "-chain add certificate chain\n");
BIO_printf(bio_err, "-inkey file private key if not infile\n");
BIO_printf(bio_err, "-certfile f add all certs in f\n");
BIO_printf(bio_err, "-CApath arg - PEM format directory of CA's\n");
BIO_printf(bio_err, "-CAfile arg - PEM format file of CA's\n");
BIO_printf(bio_err, "-name \"name\" use name as friendly name\n");
BIO_printf(bio_err,
"-caname \"nm\" use nm as CA friendly name (can be used more than once).\n");
BIO_printf(bio_err, "-in infile input filename\n");
BIO_printf(bio_err, "-out outfile output filename\n");
BIO_printf(bio_err,
"-noout don't output anything, just verify.\n");
BIO_printf(bio_err, "-nomacver don't verify MAC.\n");
BIO_printf(bio_err, "-nocerts don't output certificates.\n");
BIO_printf(bio_err,
"-clcerts only output client certificates.\n");
BIO_printf(bio_err, "-cacerts only output CA certificates.\n");
BIO_printf(bio_err, "-nokeys don't output private keys.\n");
BIO_printf(bio_err,
"-info give info about PKCS#12 structure.\n");
BIO_printf(bio_err, "-des encrypt private keys with DES\n");
BIO_printf(bio_err,
"-des3 encrypt private keys with triple DES (default)\n");
# ifndef OPENSSL_NO_IDEA
BIO_printf(bio_err, "-idea encrypt private keys with idea\n");
# endif
# ifndef OPENSSL_NO_SEED
BIO_printf(bio_err, "-seed encrypt private keys with seed\n");
# endif
# ifndef OPENSSL_NO_AES
BIO_printf(bio_err, "-aes128, -aes192, -aes256\n");
BIO_printf(bio_err,
" encrypt PEM output with cbc aes\n");
# endif
# ifndef OPENSSL_NO_CAMELLIA
BIO_printf(bio_err, "-camellia128, -camellia192, -camellia256\n");
BIO_printf(bio_err,
" encrypt PEM output with cbc camellia\n");
# endif
BIO_printf(bio_err, "-nodes don't encrypt private keys\n");
BIO_printf(bio_err, "-noiter don't use encryption iteration\n");
BIO_printf(bio_err, "-nomaciter don't use MAC iteration\n");
BIO_printf(bio_err, "-maciter use MAC iteration\n");
BIO_printf(bio_err, "-nomac don't generate MAC\n");
BIO_printf(bio_err,
"-twopass separate MAC, encryption passwords\n");
BIO_printf(bio_err,
"-descert encrypt PKCS#12 certificates with triple DES (default RC2-40)\n");
BIO_printf(bio_err,
"-certpbe alg specify certificate PBE algorithm (default RC2-40)\n");
BIO_printf(bio_err,
"-keypbe alg specify private key PBE algorithm (default 3DES)\n");
BIO_printf(bio_err,
"-macalg alg digest algorithm used in MAC (default SHA1)\n");
BIO_printf(bio_err, "-keyex set MS key exchange type\n");
BIO_printf(bio_err, "-keysig set MS key signature type\n");
BIO_printf(bio_err,
"-password p set import/export password source\n");
BIO_printf(bio_err, "-passin p input file pass phrase source\n");
BIO_printf(bio_err, "-passout p output file pass phrase source\n");
# ifndef OPENSSL_NO_ENGINE
BIO_printf(bio_err,
"-engine e use engine e, possibly a hardware device.\n");
# endif
BIO_printf(bio_err, "-rand file%cfile%c...\n", LIST_SEPARATOR_CHAR,
LIST_SEPARATOR_CHAR);
BIO_printf(bio_err,
" load the file (or the files in the directory) into\n");
BIO_printf(bio_err, " the random number generator\n");
BIO_printf(bio_err, "-CSP name Microsoft CSP name\n");
BIO_printf(bio_err,
"-LMK Add local machine keyset attribute to private key\n");
goto end;
}
e = setup_engine(bio_err, engine, 0);
if (passarg) {
if (export_cert)
passargout = passarg;
else
passargin = passarg;
}
if (!app_passwd(bio_err, passargin, passargout, &passin, &passout)) {
BIO_printf(bio_err, "Error getting passwords\n");
goto end;
}
if (!cpass) {
if (export_cert)
cpass = passout;
else
cpass = passin;
}
if (cpass) {
mpass = cpass;
noprompt = 1;
} else {
cpass = pass;
mpass = macpass;
}
if (export_cert || inrand) {
app_RAND_load_file(NULL, bio_err, (inrand != NULL));
if (inrand != NULL)
BIO_printf(bio_err, "%ld semi-random bytes loaded\n",
app_RAND_load_files(inrand));
}
ERR_load_crypto_strings();
# ifdef CRYPTO_MDEBUG
CRYPTO_push_info("read files");
# endif
if (!infile)
in = BIO_new_fp(stdin, BIO_NOCLOSE);
else
in = BIO_new_file(infile, "rb");
if (!in) {
BIO_printf(bio_err, "Error opening input file %s\n",
infile ? infile : "<stdin>");
perror(infile);
goto end;
}
# ifdef CRYPTO_MDEBUG
CRYPTO_pop_info();
CRYPTO_push_info("write files");
# endif
if (!outfile) {
out = BIO_new_fp(stdout, BIO_NOCLOSE);
# ifdef OPENSSL_SYS_VMS
{
BIO *tmpbio = BIO_new(BIO_f_linebuffer());
out = BIO_push(tmpbio, out);
}
# endif
} else
out = BIO_new_file(outfile, "wb");
if (!out) {
BIO_printf(bio_err, "Error opening output file %s\n",
outfile ? outfile : "<stdout>");
perror(outfile);
goto end;
}
if (twopass) {
# ifdef CRYPTO_MDEBUG
CRYPTO_push_info("read MAC password");
# endif
if (EVP_read_pw_string
- (macpass, sizeof macpass, "Enter MAC Password:", export_cert)) {
+ (macpass, sizeof(macpass), "Enter MAC Password:", export_cert)) {
BIO_printf(bio_err, "Can't read Password\n");
goto end;
}
# ifdef CRYPTO_MDEBUG
CRYPTO_pop_info();
# endif
}
if (export_cert) {
EVP_PKEY *key = NULL;
X509 *ucert = NULL, *x = NULL;
STACK_OF(X509) *certs = NULL;
const EVP_MD *macmd = NULL;
unsigned char *catmp = NULL;
int i;
if ((options & (NOCERTS | NOKEYS)) == (NOCERTS | NOKEYS)) {
BIO_printf(bio_err, "Nothing to do!\n");
goto export_end;
}
if (options & NOCERTS)
chain = 0;
# ifdef CRYPTO_MDEBUG
CRYPTO_push_info("process -export_cert");
CRYPTO_push_info("reading private key");
# endif
if (!(options & NOKEYS)) {
key = load_key(bio_err, keyname ? keyname : infile,
FORMAT_PEM, 1, passin, e, "private key");
if (!key)
goto export_end;
}
# ifdef CRYPTO_MDEBUG
CRYPTO_pop_info();
CRYPTO_push_info("reading certs from input");
# endif
/* Load in all certs in input file */
if (!(options & NOCERTS)) {
certs = load_certs(bio_err, infile, FORMAT_PEM, NULL, e,
"certificates");
if (!certs)
goto export_end;
if (key) {
/* Look for matching private key */
for (i = 0; i < sk_X509_num(certs); i++) {
x = sk_X509_value(certs, i);
if (X509_check_private_key(x, key)) {
ucert = x;
/* Zero keyid and alias */
X509_keyid_set1(ucert, NULL, 0);
X509_alias_set1(ucert, NULL, 0);
/* Remove from list */
(void)sk_X509_delete(certs, i);
break;
}
}
if (!ucert) {
BIO_printf(bio_err,
"No certificate matches private key\n");
goto export_end;
}
}
}
# ifdef CRYPTO_MDEBUG
CRYPTO_pop_info();
CRYPTO_push_info("reading certs from input 2");
# endif
/* Add any more certificates asked for */
if (certfile) {
STACK_OF(X509) *morecerts = NULL;
if (!(morecerts = load_certs(bio_err, certfile, FORMAT_PEM,
NULL, e,
"certificates from certfile")))
goto export_end;
while (sk_X509_num(morecerts) > 0)
sk_X509_push(certs, sk_X509_shift(morecerts));
sk_X509_free(morecerts);
}
# ifdef CRYPTO_MDEBUG
CRYPTO_pop_info();
CRYPTO_push_info("reading certs from certfile");
# endif
# ifdef CRYPTO_MDEBUG
CRYPTO_pop_info();
CRYPTO_push_info("building chain");
# endif
/* If chaining get chain from user cert */
if (chain) {
int vret;
STACK_OF(X509) *chain2;
X509_STORE *store = X509_STORE_new();
if (!store) {
BIO_printf(bio_err, "Memory allocation error\n");
goto export_end;
}
if (!X509_STORE_load_locations(store, CAfile, CApath))
X509_STORE_set_default_paths(store);
vret = get_cert_chain(ucert, store, &chain2);
X509_STORE_free(store);
if (vret == X509_V_OK) {
/* Exclude verified certificate */
for (i = 1; i < sk_X509_num(chain2); i++)
sk_X509_push(certs, sk_X509_value(chain2, i));
/* Free first certificate */
X509_free(sk_X509_value(chain2, 0));
sk_X509_free(chain2);
} else {
if (vret != X509_V_ERR_UNSPECIFIED)
BIO_printf(bio_err, "Error %s getting chain.\n",
X509_verify_cert_error_string(vret));
else
ERR_print_errors(bio_err);
goto export_end;
}
}
/* Add any CA names */
for (i = 0; i < sk_OPENSSL_STRING_num(canames); i++) {
catmp = (unsigned char *)sk_OPENSSL_STRING_value(canames, i);
X509_alias_set1(sk_X509_value(certs, i), catmp, -1);
}
if (csp_name && key)
EVP_PKEY_add1_attr_by_NID(key, NID_ms_csp_name,
MBSTRING_ASC, (unsigned char *)csp_name,
-1);
if (add_lmk && key)
EVP_PKEY_add1_attr_by_NID(key, NID_LocalKeySet, 0, NULL, -1);
# ifdef CRYPTO_MDEBUG
CRYPTO_pop_info();
CRYPTO_push_info("reading password");
# endif
if (!noprompt &&
- EVP_read_pw_string(pass, sizeof pass, "Enter Export Password:",
+ EVP_read_pw_string(pass, sizeof(pass), "Enter Export Password:",
1)) {
BIO_printf(bio_err, "Can't read Password\n");
goto export_end;
}
if (!twopass)
- BUF_strlcpy(macpass, pass, sizeof macpass);
+ BUF_strlcpy(macpass, pass, sizeof(macpass));
# ifdef CRYPTO_MDEBUG
CRYPTO_pop_info();
CRYPTO_push_info("creating PKCS#12 structure");
# endif
p12 = PKCS12_create(cpass, name, key, ucert, certs,
key_pbe, cert_pbe, iter, -1, keytype);
if (!p12) {
ERR_print_errors(bio_err);
goto export_end;
}
if (macalg) {
macmd = EVP_get_digestbyname(macalg);
if (!macmd) {
BIO_printf(bio_err, "Unknown digest algorithm %s\n", macalg);
}
}
if (maciter != -1)
PKCS12_set_mac(p12, mpass, -1, NULL, 0, maciter, macmd);
# ifdef CRYPTO_MDEBUG
CRYPTO_pop_info();
CRYPTO_push_info("writing pkcs12");
# endif
i2d_PKCS12_bio(out, p12);
ret = 0;
export_end:
# ifdef CRYPTO_MDEBUG
CRYPTO_pop_info();
CRYPTO_pop_info();
CRYPTO_push_info("process -export_cert: freeing");
# endif
if (key)
EVP_PKEY_free(key);
if (certs)
sk_X509_pop_free(certs, X509_free);
if (ucert)
X509_free(ucert);
# ifdef CRYPTO_MDEBUG
CRYPTO_pop_info();
# endif
goto end;
}
if (!(p12 = d2i_PKCS12_bio(in, NULL))) {
ERR_print_errors(bio_err);
goto end;
}
# ifdef CRYPTO_MDEBUG
CRYPTO_push_info("read import password");
# endif
if (!noprompt
- && EVP_read_pw_string(pass, sizeof pass, "Enter Import Password:",
+ && EVP_read_pw_string(pass, sizeof(pass), "Enter Import Password:",
0)) {
BIO_printf(bio_err, "Can't read Password\n");
goto end;
}
# ifdef CRYPTO_MDEBUG
CRYPTO_pop_info();
# endif
if (!twopass)
- BUF_strlcpy(macpass, pass, sizeof macpass);
+ BUF_strlcpy(macpass, pass, sizeof(macpass));
if ((options & INFO) && p12->mac)
BIO_printf(bio_err, "MAC Iteration %ld\n",
p12->mac->iter ? ASN1_INTEGER_get(p12->mac->iter) : 1);
if (macver) {
# ifdef CRYPTO_MDEBUG
CRYPTO_push_info("verify MAC");
# endif
/* If we enter empty password try no password first */
if (!mpass[0] && PKCS12_verify_mac(p12, NULL, 0)) {
/* If mac and crypto pass the same set it to NULL too */
if (!twopass)
cpass = NULL;
} else if (!PKCS12_verify_mac(p12, mpass, -1)) {
BIO_printf(bio_err, "Mac verify error: invalid password?\n");
ERR_print_errors(bio_err);
goto end;
}
BIO_printf(bio_err, "MAC verified OK\n");
# ifdef CRYPTO_MDEBUG
CRYPTO_pop_info();
# endif
}
# ifdef CRYPTO_MDEBUG
CRYPTO_push_info("output keys and certificates");
# endif
if (!dump_certs_keys_p12(out, p12, cpass, -1, options, passout)) {
BIO_printf(bio_err, "Error outputting keys and certificates\n");
ERR_print_errors(bio_err);
goto end;
}
# ifdef CRYPTO_MDEBUG
CRYPTO_pop_info();
# endif
ret = 0;
end:
if (p12)
PKCS12_free(p12);
if (export_cert || inrand)
app_RAND_write_file(NULL, bio_err);
# ifdef CRYPTO_MDEBUG
CRYPTO_remove_all_info();
# endif
release_engine(e);
BIO_free(in);
BIO_free_all(out);
if (canames)
sk_OPENSSL_STRING_free(canames);
if (passin)
OPENSSL_free(passin);
if (passout)
OPENSSL_free(passout);
apps_shutdown();
OPENSSL_EXIT(ret);
}
int dump_certs_keys_p12(BIO *out, PKCS12 *p12, char *pass,
int passlen, int options, char *pempass)
{
STACK_OF(PKCS7) *asafes = NULL;
STACK_OF(PKCS12_SAFEBAG) *bags;
int i, bagnid;
int ret = 0;
PKCS7 *p7;
if (!(asafes = PKCS12_unpack_authsafes(p12)))
return 0;
for (i = 0; i < sk_PKCS7_num(asafes); i++) {
p7 = sk_PKCS7_value(asafes, i);
bagnid = OBJ_obj2nid(p7->type);
if (bagnid == NID_pkcs7_data) {
bags = PKCS12_unpack_p7data(p7);
if (options & INFO)
BIO_printf(bio_err, "PKCS7 Data\n");
} else if (bagnid == NID_pkcs7_encrypted) {
if (options & INFO) {
BIO_printf(bio_err, "PKCS7 Encrypted data: ");
alg_print(bio_err, p7->d.encrypted->enc_data->algorithm);
}
bags = PKCS12_unpack_p7encdata(p7, pass, passlen);
} else
continue;
if (!bags)
goto err;
if (!dump_certs_pkeys_bags(out, bags, pass, passlen,
options, pempass)) {
sk_PKCS12_SAFEBAG_pop_free(bags, PKCS12_SAFEBAG_free);
goto err;
}
sk_PKCS12_SAFEBAG_pop_free(bags, PKCS12_SAFEBAG_free);
bags = NULL;
}
ret = 1;
err:
if (asafes)
sk_PKCS7_pop_free(asafes, PKCS7_free);
return ret;
}
int dump_certs_pkeys_bags(BIO *out, STACK_OF(PKCS12_SAFEBAG) *bags,
char *pass, int passlen, int options, char *pempass)
{
int i;
for (i = 0; i < sk_PKCS12_SAFEBAG_num(bags); i++) {
if (!dump_certs_pkeys_bag(out,
sk_PKCS12_SAFEBAG_value(bags, i),
pass, passlen, options, pempass))
return 0;
}
return 1;
}
int dump_certs_pkeys_bag(BIO *out, PKCS12_SAFEBAG *bag, char *pass,
int passlen, int options, char *pempass)
{
EVP_PKEY *pkey;
PKCS8_PRIV_KEY_INFO *p8;
X509 *x509;
int ret = 0;
switch (M_PKCS12_bag_type(bag)) {
case NID_keyBag:
if (options & INFO)
BIO_printf(bio_err, "Key bag\n");
if (options & NOKEYS)
return 1;
print_attribs(out, bag->attrib, "Bag Attributes");
p8 = bag->value.keybag;
if (!(pkey = EVP_PKCS82PKEY(p8)))
return 0;
print_attribs(out, p8->attributes, "Key Attributes");
ret = PEM_write_bio_PrivateKey(out, pkey, enc, NULL, 0, NULL, pempass);
EVP_PKEY_free(pkey);
break;
case NID_pkcs8ShroudedKeyBag:
if (options & INFO) {
BIO_printf(bio_err, "Shrouded Keybag: ");
alg_print(bio_err, bag->value.shkeybag->algor);
}
if (options & NOKEYS)
return 1;
print_attribs(out, bag->attrib, "Bag Attributes");
if (!(p8 = PKCS12_decrypt_skey(bag, pass, passlen)))
return 0;
if (!(pkey = EVP_PKCS82PKEY(p8))) {
PKCS8_PRIV_KEY_INFO_free(p8);
return 0;
}
print_attribs(out, p8->attributes, "Key Attributes");
PKCS8_PRIV_KEY_INFO_free(p8);
ret = PEM_write_bio_PrivateKey(out, pkey, enc, NULL, 0, NULL, pempass);
EVP_PKEY_free(pkey);
break;
case NID_certBag:
if (options & INFO)
BIO_printf(bio_err, "Certificate bag\n");
if (options & NOCERTS)
return 1;
if (PKCS12_get_attr(bag, NID_localKeyID)) {
if (options & CACERTS)
return 1;
} else if (options & CLCERTS)
return 1;
print_attribs(out, bag->attrib, "Bag Attributes");
if (M_PKCS12_cert_bag_type(bag) != NID_x509Certificate)
return 1;
if (!(x509 = PKCS12_certbag2x509(bag)))
return 0;
dump_cert_text(out, x509);
ret = PEM_write_bio_X509(out, x509);
X509_free(x509);
break;
case NID_safeContentsBag:
if (options & INFO)
BIO_printf(bio_err, "Safe Contents bag\n");
print_attribs(out, bag->attrib, "Bag Attributes");
return dump_certs_pkeys_bags(out, bag->value.safes, pass,
passlen, options, pempass);
default:
BIO_printf(bio_err, "Warning unsupported bag type: ");
i2a_ASN1_OBJECT(bio_err, bag->type);
BIO_printf(bio_err, "\n");
return 1;
break;
}
return ret;
}
/* Given a single certificate return a verified chain or NULL if error */
static int get_cert_chain(X509 *cert, X509_STORE *store,
STACK_OF(X509) **chain)
{
X509_STORE_CTX store_ctx;
STACK_OF(X509) *chn = NULL;
int i = 0;
if (!X509_STORE_CTX_init(&store_ctx, store, cert, NULL)) {
*chain = NULL;
return X509_V_ERR_UNSPECIFIED;
}
if (X509_verify_cert(&store_ctx) > 0)
chn = X509_STORE_CTX_get1_chain(&store_ctx);
else if ((i = X509_STORE_CTX_get_error(&store_ctx)) == 0)
i = X509_V_ERR_UNSPECIFIED;
X509_STORE_CTX_cleanup(&store_ctx);
*chain = chn;
return i;
}
int alg_print(BIO *x, X509_ALGOR *alg)
{
int pbenid, aparamtype;
ASN1_OBJECT *aoid;
void *aparam;
PBEPARAM *pbe = NULL;
X509_ALGOR_get0(&aoid, &aparamtype, &aparam, alg);
pbenid = OBJ_obj2nid(aoid);
BIO_printf(x, "%s", OBJ_nid2ln(pbenid));
/*
* If PBE algorithm is PBES2 decode algorithm parameters
* for additional details.
*/
if (pbenid == NID_pbes2) {
PBE2PARAM *pbe2 = NULL;
int encnid;
if (aparamtype == V_ASN1_SEQUENCE)
pbe2 = ASN1_item_unpack(aparam, ASN1_ITEM_rptr(PBE2PARAM));
if (pbe2 == NULL) {
BIO_puts(x, "<unsupported parameters>");
goto done;
}
X509_ALGOR_get0(&aoid, &aparamtype, &aparam, pbe2->keyfunc);
pbenid = OBJ_obj2nid(aoid);
X509_ALGOR_get0(&aoid, NULL, NULL, pbe2->encryption);
encnid = OBJ_obj2nid(aoid);
BIO_printf(x, ", %s, %s", OBJ_nid2ln(pbenid),
OBJ_nid2sn(encnid));
/* If KDF is PBKDF2 decode parameters */
if (pbenid == NID_id_pbkdf2) {
PBKDF2PARAM *kdf = NULL;
int prfnid;
if (aparamtype == V_ASN1_SEQUENCE)
kdf = ASN1_item_unpack(aparam, ASN1_ITEM_rptr(PBKDF2PARAM));
if (kdf == NULL) {
BIO_puts(x, "<unsupported parameters>");
goto done;
}
if (kdf->prf == NULL) {
prfnid = NID_hmacWithSHA1;
} else {
X509_ALGOR_get0(&aoid, NULL, NULL, kdf->prf);
prfnid = OBJ_obj2nid(aoid);
}
BIO_printf(x, ", Iteration %ld, PRF %s",
ASN1_INTEGER_get(kdf->iter), OBJ_nid2sn(prfnid));
PBKDF2PARAM_free(kdf);
}
PBE2PARAM_free(pbe2);
} else {
if (aparamtype == V_ASN1_SEQUENCE)
pbe = ASN1_item_unpack(aparam, ASN1_ITEM_rptr(PBEPARAM));
if (pbe == NULL) {
BIO_puts(x, "<unsupported parameters>");
goto done;
}
BIO_printf(x, ", Iteration %ld", ASN1_INTEGER_get(pbe->iter));
PBEPARAM_free(pbe);
}
done:
BIO_puts(x, "\n");
return 1;
}
/* Load all certificates from a given file */
int cert_load(BIO *in, STACK_OF(X509) *sk)
{
int ret;
X509 *cert;
ret = 0;
# ifdef CRYPTO_MDEBUG
CRYPTO_push_info("cert_load(): reading one cert");
# endif
while ((cert = PEM_read_bio_X509(in, NULL, NULL, NULL))) {
# ifdef CRYPTO_MDEBUG
CRYPTO_pop_info();
# endif
ret = 1;
sk_X509_push(sk, cert);
# ifdef CRYPTO_MDEBUG
CRYPTO_push_info("cert_load(): reading one cert");
# endif
}
# ifdef CRYPTO_MDEBUG
CRYPTO_pop_info();
# endif
if (ret)
ERR_clear_error();
return ret;
}
/* Generalised attribute print: handle PKCS#8 and bag attributes */
int print_attribs(BIO *out, STACK_OF(X509_ATTRIBUTE) *attrlst,
const char *name)
{
X509_ATTRIBUTE *attr;
ASN1_TYPE *av;
char *value;
int i, attr_nid;
if (!attrlst) {
BIO_printf(out, "%s: <No Attributes>\n", name);
return 1;
}
if (!sk_X509_ATTRIBUTE_num(attrlst)) {
BIO_printf(out, "%s: <Empty Attributes>\n", name);
return 1;
}
BIO_printf(out, "%s\n", name);
for (i = 0; i < sk_X509_ATTRIBUTE_num(attrlst); i++) {
attr = sk_X509_ATTRIBUTE_value(attrlst, i);
attr_nid = OBJ_obj2nid(attr->object);
BIO_printf(out, " ");
if (attr_nid == NID_undef) {
i2a_ASN1_OBJECT(out, attr->object);
BIO_printf(out, ": ");
} else
BIO_printf(out, "%s: ", OBJ_nid2ln(attr_nid));
if (sk_ASN1_TYPE_num(attr->value.set)) {
av = sk_ASN1_TYPE_value(attr->value.set, 0);
switch (av->type) {
case V_ASN1_BMPSTRING:
value = OPENSSL_uni2asc(av->value.bmpstring->data,
av->value.bmpstring->length);
BIO_printf(out, "%s\n", value);
OPENSSL_free(value);
break;
case V_ASN1_OCTET_STRING:
hex_prin(out, av->value.octet_string->data,
av->value.octet_string->length);
BIO_printf(out, "\n");
break;
case V_ASN1_BIT_STRING:
hex_prin(out, av->value.bit_string->data,
av->value.bit_string->length);
BIO_printf(out, "\n");
break;
default:
BIO_printf(out, "<Unsupported tag %d>\n", av->type);
break;
}
} else
BIO_printf(out, "<No Values>\n");
}
return 1;
}
void hex_prin(BIO *out, unsigned char *buf, int len)
{
int i;
for (i = 0; i < len; i++)
BIO_printf(out, "%02X ", buf[i]);
}
static int set_pbe(BIO *err, int *ppbe, const char *str)
{
if (!str)
return 0;
if (!strcmp(str, "NONE")) {
*ppbe = -1;
return 1;
}
*ppbe = OBJ_txt2nid(str);
if (*ppbe == NID_undef) {
BIO_printf(bio_err, "Unknown PBE algorithm %s\n", str);
return 0;
}
return 1;
}
#else
static void *dummy = &dummy;
#endif
diff --git a/apps/pkcs8.c b/apps/pkcs8.c
index 71e31689df08..d7f0720ca128 100644
--- a/apps/pkcs8.c
+++ b/apps/pkcs8.c
@@ -1,399 +1,399 @@
/* pkcs8.c */
/*
* Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL project
* 1999-2004.
*/
/* ====================================================================
* Copyright (c) 1999 The OpenSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* licensing@OpenSSL.org.
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*
* This product includes cryptographic software written by Eric Young
* (eay@cryptsoft.com). This product includes software written by Tim
* Hudson (tjh@cryptsoft.com).
*
*/
#include <stdio.h>
#include <string.h>
#include "apps.h"
#include <openssl/pem.h>
#include <openssl/err.h>
#include <openssl/evp.h>
#include <openssl/pkcs12.h>
#define PROG pkcs8_main
int MAIN(int, char **);
int MAIN(int argc, char **argv)
{
ENGINE *e = NULL;
char **args, *infile = NULL, *outfile = NULL;
char *passargin = NULL, *passargout = NULL;
BIO *in = NULL, *out = NULL;
int topk8 = 0;
int pbe_nid = -1;
const EVP_CIPHER *cipher = NULL;
int iter = PKCS12_DEFAULT_ITER;
int informat, outformat;
int p8_broken = PKCS8_OK;
int nocrypt = 0;
X509_SIG *p8 = NULL;
PKCS8_PRIV_KEY_INFO *p8inf = NULL;
EVP_PKEY *pkey = NULL;
char pass[50], *passin = NULL, *passout = NULL, *p8pass = NULL;
int badarg = 0;
int ret = 1;
char *engine = NULL;
if (bio_err == NULL)
bio_err = BIO_new_fp(stderr, BIO_NOCLOSE);
if (!load_config(bio_err, NULL))
goto end;
informat = FORMAT_PEM;
outformat = FORMAT_PEM;
ERR_load_crypto_strings();
OpenSSL_add_all_algorithms();
args = argv + 1;
while (!badarg && *args && *args[0] == '-') {
if (!strcmp(*args, "-v2")) {
if (args[1]) {
args++;
cipher = EVP_get_cipherbyname(*args);
if (!cipher) {
BIO_printf(bio_err, "Unknown cipher %s\n", *args);
badarg = 1;
}
} else
badarg = 1;
} else if (!strcmp(*args, "-v1")) {
if (args[1]) {
args++;
pbe_nid = OBJ_txt2nid(*args);
if (pbe_nid == NID_undef) {
BIO_printf(bio_err, "Unknown PBE algorithm %s\n", *args);
badarg = 1;
}
} else
badarg = 1;
} else if (!strcmp(*args, "-v2prf")) {
if (args[1]) {
args++;
pbe_nid = OBJ_txt2nid(*args);
if (!EVP_PBE_find(EVP_PBE_TYPE_PRF, pbe_nid, NULL, NULL, 0)) {
BIO_printf(bio_err, "Unknown PRF algorithm %s\n", *args);
badarg = 1;
}
} else
badarg = 1;
} else if (!strcmp(*args, "-inform")) {
if (args[1]) {
args++;
informat = str2fmt(*args);
} else
badarg = 1;
} else if (!strcmp(*args, "-outform")) {
if (args[1]) {
args++;
outformat = str2fmt(*args);
} else
badarg = 1;
} else if (!strcmp(*args, "-topk8"))
topk8 = 1;
else if (!strcmp(*args, "-noiter"))
iter = 1;
else if (!strcmp(*args, "-nocrypt"))
nocrypt = 1;
else if (!strcmp(*args, "-nooct"))
p8_broken = PKCS8_NO_OCTET;
else if (!strcmp(*args, "-nsdb"))
p8_broken = PKCS8_NS_DB;
else if (!strcmp(*args, "-embed"))
p8_broken = PKCS8_EMBEDDED_PARAM;
else if (!strcmp(*args, "-passin")) {
if (!args[1])
goto bad;
passargin = *(++args);
} else if (!strcmp(*args, "-passout")) {
if (!args[1])
goto bad;
passargout = *(++args);
}
#ifndef OPENSSL_NO_ENGINE
else if (strcmp(*args, "-engine") == 0) {
if (!args[1])
goto bad;
engine = *(++args);
}
#endif
else if (!strcmp(*args, "-in")) {
if (args[1]) {
args++;
infile = *args;
} else
badarg = 1;
} else if (!strcmp(*args, "-out")) {
if (args[1]) {
args++;
outfile = *args;
} else
badarg = 1;
} else
badarg = 1;
args++;
}
if (badarg) {
bad:
BIO_printf(bio_err, "Usage pkcs8 [options]\n");
BIO_printf(bio_err, "where options are\n");
BIO_printf(bio_err, "-in file input file\n");
BIO_printf(bio_err, "-inform X input format (DER or PEM)\n");
BIO_printf(bio_err,
"-passin arg input file pass phrase source\n");
BIO_printf(bio_err, "-outform X output format (DER or PEM)\n");
BIO_printf(bio_err, "-out file output file\n");
BIO_printf(bio_err,
"-passout arg output file pass phrase source\n");
BIO_printf(bio_err, "-topk8 output PKCS8 file\n");
BIO_printf(bio_err,
"-nooct use (nonstandard) no octet format\n");
BIO_printf(bio_err,
"-embed use (nonstandard) embedded DSA parameters format\n");
BIO_printf(bio_err,
"-nsdb use (nonstandard) DSA Netscape DB format\n");
BIO_printf(bio_err, "-noiter use 1 as iteration count\n");
BIO_printf(bio_err,
"-nocrypt use or expect unencrypted private key\n");
BIO_printf(bio_err,
"-v2 alg use PKCS#5 v2.0 and cipher \"alg\"\n");
BIO_printf(bio_err,
"-v1 obj use PKCS#5 v1.5 and cipher \"alg\"\n");
#ifndef OPENSSL_NO_ENGINE
BIO_printf(bio_err,
" -engine e use engine e, possibly a hardware device.\n");
#endif
goto end;
}
e = setup_engine(bio_err, engine, 0);
if (!app_passwd(bio_err, passargin, passargout, &passin, &passout)) {
BIO_printf(bio_err, "Error getting passwords\n");
goto end;
}
if ((pbe_nid == -1) && !cipher)
pbe_nid = NID_pbeWithMD5AndDES_CBC;
if (infile) {
if (!(in = BIO_new_file(infile, "rb"))) {
BIO_printf(bio_err, "Can't open input file %s\n", infile);
goto end;
}
} else
in = BIO_new_fp(stdin, BIO_NOCLOSE);
if (outfile) {
if (!(out = BIO_new_file(outfile, "wb"))) {
BIO_printf(bio_err, "Can't open output file %s\n", outfile);
goto end;
}
} else {
out = BIO_new_fp(stdout, BIO_NOCLOSE);
#ifdef OPENSSL_SYS_VMS
{
BIO *tmpbio = BIO_new(BIO_f_linebuffer());
out = BIO_push(tmpbio, out);
}
#endif
}
if (topk8) {
pkey = load_key(bio_err, infile, informat, 1, passin, e, "key");
if (!pkey)
goto end;
if (!(p8inf = EVP_PKEY2PKCS8_broken(pkey, p8_broken))) {
BIO_printf(bio_err, "Error converting key\n");
ERR_print_errors(bio_err);
goto end;
}
if (nocrypt) {
if (outformat == FORMAT_PEM)
PEM_write_bio_PKCS8_PRIV_KEY_INFO(out, p8inf);
else if (outformat == FORMAT_ASN1)
i2d_PKCS8_PRIV_KEY_INFO_bio(out, p8inf);
else {
BIO_printf(bio_err, "Bad format specified for key\n");
goto end;
}
} else {
if (passout)
p8pass = passout;
else {
p8pass = pass;
if (EVP_read_pw_string
- (pass, sizeof pass, "Enter Encryption Password:", 1))
+ (pass, sizeof(pass), "Enter Encryption Password:", 1))
goto end;
}
app_RAND_load_file(NULL, bio_err, 0);
if (!(p8 = PKCS8_encrypt(pbe_nid, cipher,
p8pass, strlen(p8pass),
NULL, 0, iter, p8inf))) {
BIO_printf(bio_err, "Error encrypting key\n");
ERR_print_errors(bio_err);
goto end;
}
app_RAND_write_file(NULL, bio_err);
if (outformat == FORMAT_PEM)
PEM_write_bio_PKCS8(out, p8);
else if (outformat == FORMAT_ASN1)
i2d_PKCS8_bio(out, p8);
else {
BIO_printf(bio_err, "Bad format specified for key\n");
goto end;
}
}
ret = 0;
goto end;
}
if (nocrypt) {
if (informat == FORMAT_PEM)
p8inf = PEM_read_bio_PKCS8_PRIV_KEY_INFO(in, NULL, NULL, NULL);
else if (informat == FORMAT_ASN1)
p8inf = d2i_PKCS8_PRIV_KEY_INFO_bio(in, NULL);
else {
BIO_printf(bio_err, "Bad format specified for key\n");
goto end;
}
} else {
if (informat == FORMAT_PEM)
p8 = PEM_read_bio_PKCS8(in, NULL, NULL, NULL);
else if (informat == FORMAT_ASN1)
p8 = d2i_PKCS8_bio(in, NULL);
else {
BIO_printf(bio_err, "Bad format specified for key\n");
goto end;
}
if (!p8) {
BIO_printf(bio_err, "Error reading key\n");
ERR_print_errors(bio_err);
goto end;
}
if (passin)
p8pass = passin;
else {
p8pass = pass;
- EVP_read_pw_string(pass, sizeof pass, "Enter Password:", 0);
+ EVP_read_pw_string(pass, sizeof(pass), "Enter Password:", 0);
}
p8inf = PKCS8_decrypt(p8, p8pass, strlen(p8pass));
}
if (!p8inf) {
BIO_printf(bio_err, "Error decrypting key\n");
ERR_print_errors(bio_err);
goto end;
}
if (!(pkey = EVP_PKCS82PKEY(p8inf))) {
BIO_printf(bio_err, "Error converting key\n");
ERR_print_errors(bio_err);
goto end;
}
if (p8inf->broken) {
BIO_printf(bio_err, "Warning: broken key encoding: ");
switch (p8inf->broken) {
case PKCS8_NO_OCTET:
BIO_printf(bio_err, "No Octet String in PrivateKey\n");
break;
case PKCS8_EMBEDDED_PARAM:
BIO_printf(bio_err, "DSA parameters included in PrivateKey\n");
break;
case PKCS8_NS_DB:
BIO_printf(bio_err, "DSA public key include in PrivateKey\n");
break;
case PKCS8_NEG_PRIVKEY:
BIO_printf(bio_err, "DSA private key value is negative\n");
break;
default:
BIO_printf(bio_err, "Unknown broken type\n");
break;
}
}
if (outformat == FORMAT_PEM)
PEM_write_bio_PrivateKey(out, pkey, NULL, NULL, 0, NULL, passout);
else if (outformat == FORMAT_ASN1)
i2d_PrivateKey_bio(out, pkey);
else {
BIO_printf(bio_err, "Bad format specified for key\n");
goto end;
}
ret = 0;
end:
X509_SIG_free(p8);
PKCS8_PRIV_KEY_INFO_free(p8inf);
EVP_PKEY_free(pkey);
release_engine(e);
BIO_free_all(out);
BIO_free(in);
if (passin)
OPENSSL_free(passin);
if (passout)
OPENSSL_free(passout);
return ret;
}
diff --git a/apps/rand.c b/apps/rand.c
index 96dcb7273a4d..eddb8af8d70a 100644
--- a/apps/rand.c
+++ b/apps/rand.c
@@ -1,227 +1,227 @@
/* apps/rand.c */
/* ====================================================================
* Copyright (c) 1998-2001 The OpenSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* openssl-core@openssl.org.
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.openssl.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*
* This product includes cryptographic software written by Eric Young
* (eay@cryptsoft.com). This product includes software written by Tim
* Hudson (tjh@cryptsoft.com).
*
*/
#include "apps.h"
#include <ctype.h>
#include <stdio.h>
#include <string.h>
#include <openssl/bio.h>
#include <openssl/err.h>
#include <openssl/rand.h>
#undef PROG
#define PROG rand_main
/*-
* -out file - write to file
* -rand file:file - PRNG seed files
* -base64 - base64 encode output
* -hex - hex encode output
* num - write 'num' bytes
*/
int MAIN(int, char **);
int MAIN(int argc, char **argv)
{
int i, r, ret = 1;
int badopt;
char *outfile = NULL;
char *inrand = NULL;
int base64 = 0;
int hex = 0;
BIO *out = NULL;
int num = -1;
ENGINE *e = NULL;
char *engine = NULL;
apps_startup();
if (bio_err == NULL)
if ((bio_err = BIO_new(BIO_s_file())) != NULL)
BIO_set_fp(bio_err, stderr, BIO_NOCLOSE | BIO_FP_TEXT);
if (!load_config(bio_err, NULL))
goto err;
badopt = 0;
i = 0;
while (!badopt && argv[++i] != NULL) {
if (strcmp(argv[i], "-out") == 0) {
if ((argv[i + 1] != NULL) && (outfile == NULL))
outfile = argv[++i];
else
badopt = 1;
}
#ifndef OPENSSL_NO_ENGINE
else if (strcmp(argv[i], "-engine") == 0) {
if ((argv[i + 1] != NULL) && (engine == NULL))
engine = argv[++i];
else
badopt = 1;
}
#endif
else if (strcmp(argv[i], "-rand") == 0) {
if ((argv[i + 1] != NULL) && (inrand == NULL))
inrand = argv[++i];
else
badopt = 1;
} else if (strcmp(argv[i], "-base64") == 0) {
if (!base64)
base64 = 1;
else
badopt = 1;
} else if (strcmp(argv[i], "-hex") == 0) {
if (!hex)
hex = 1;
else
badopt = 1;
} else if (isdigit((unsigned char)argv[i][0])) {
if (num < 0) {
r = sscanf(argv[i], "%d", &num);
if (r == 0 || num < 0)
badopt = 1;
} else
badopt = 1;
} else
badopt = 1;
}
if (hex && base64)
badopt = 1;
if (num < 0)
badopt = 1;
if (badopt) {
BIO_printf(bio_err, "Usage: rand [options] num\n");
BIO_printf(bio_err, "where options are\n");
BIO_printf(bio_err, "-out file - write to file\n");
#ifndef OPENSSL_NO_ENGINE
BIO_printf(bio_err,
"-engine e - use engine e, possibly a hardware device.\n");
#endif
BIO_printf(bio_err, "-rand file%cfile%c... - seed PRNG from files\n",
LIST_SEPARATOR_CHAR, LIST_SEPARATOR_CHAR);
BIO_printf(bio_err, "-base64 - base64 encode output\n");
BIO_printf(bio_err, "-hex - hex encode output\n");
goto err;
}
e = setup_engine(bio_err, engine, 0);
app_RAND_load_file(NULL, bio_err, (inrand != NULL));
if (inrand != NULL)
BIO_printf(bio_err, "%ld semi-random bytes loaded\n",
app_RAND_load_files(inrand));
out = BIO_new(BIO_s_file());
if (out == NULL)
goto err;
if (outfile != NULL)
r = BIO_write_filename(out, outfile);
else {
r = BIO_set_fp(out, stdout, BIO_NOCLOSE | BIO_FP_TEXT);
#ifdef OPENSSL_SYS_VMS
{
BIO *tmpbio = BIO_new(BIO_f_linebuffer());
out = BIO_push(tmpbio, out);
}
#endif
}
if (r <= 0)
goto err;
if (base64) {
BIO *b64 = BIO_new(BIO_f_base64());
if (b64 == NULL)
goto err;
out = BIO_push(b64, out);
}
while (num > 0) {
unsigned char buf[4096];
int chunk;
chunk = num;
if (chunk > (int)sizeof(buf))
- chunk = sizeof buf;
+ chunk = sizeof(buf);
r = RAND_bytes(buf, chunk);
if (r <= 0)
goto err;
if (!hex)
BIO_write(out, buf, chunk);
else {
for (i = 0; i < chunk; i++)
BIO_printf(out, "%02x", buf[i]);
}
num -= chunk;
}
if (hex)
BIO_puts(out, "\n");
(void)BIO_flush(out);
app_RAND_write_file(NULL, bio_err);
ret = 0;
err:
ERR_print_errors(bio_err);
release_engine(e);
if (out)
BIO_free_all(out);
apps_shutdown();
OPENSSL_EXIT(ret);
}
diff --git a/apps/req.c b/apps/req.c
index ede1d32cae62..7fcab18cd1c9 100644
--- a/apps/req.c
+++ b/apps/req.c
@@ -1,1731 +1,1731 @@
/* apps/req.c */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
/*
* Until the key-gen callbacks are modified to use newer prototypes, we allow
* deprecated functions for openssl-internal code
*/
#ifdef OPENSSL_NO_DEPRECATED
# undef OPENSSL_NO_DEPRECATED
#endif
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#ifdef OPENSSL_NO_STDIO
# define APPS_WIN16
#endif
#include "apps.h"
#include <openssl/bio.h>
#include <openssl/evp.h>
#include <openssl/conf.h>
#include <openssl/err.h>
#include <openssl/asn1.h>
#include <openssl/x509.h>
#include <openssl/x509v3.h>
#include <openssl/objects.h>
#include <openssl/pem.h>
#include <openssl/bn.h>
#ifndef OPENSSL_NO_RSA
# include <openssl/rsa.h>
#endif
#ifndef OPENSSL_NO_DSA
# include <openssl/dsa.h>
#endif
#define SECTION "req"
#define BITS "default_bits"
#define KEYFILE "default_keyfile"
#define PROMPT "prompt"
#define DISTINGUISHED_NAME "distinguished_name"
#define ATTRIBUTES "attributes"
#define V3_EXTENSIONS "x509_extensions"
#define REQ_EXTENSIONS "req_extensions"
#define STRING_MASK "string_mask"
#define UTF8_IN "utf8"
#define DEFAULT_KEY_LENGTH 2048
#define MIN_KEY_LENGTH 512
#undef PROG
#define PROG req_main
/*-
* -inform arg - input format - default PEM (DER or PEM)
* -outform arg - output format - default PEM
* -in arg - input file - default stdin
* -out arg - output file - default stdout
* -verify - check request signature
* -noout - don't print stuff out.
* -text - print out human readable text.
* -nodes - no des encryption
* -config file - Load configuration file.
* -key file - make a request using key in file (or use it for verification).
* -keyform arg - key file format.
* -rand file(s) - load the file(s) into the PRNG.
* -newkey - make a key and a request.
* -modulus - print RSA modulus.
* -pubkey - output Public Key.
* -x509 - output a self signed X509 structure instead.
* -asn1-kludge - output new certificate request in a format that some CA's
* require. This format is wrong
*/
static int make_REQ(X509_REQ *req, EVP_PKEY *pkey, char *dn, int mutlirdn,
int attribs, unsigned long chtype);
static int build_subject(X509_REQ *req, char *subj, unsigned long chtype,
int multirdn);
static int prompt_info(X509_REQ *req,
STACK_OF(CONF_VALUE) *dn_sk, char *dn_sect,
STACK_OF(CONF_VALUE) *attr_sk, char *attr_sect,
int attribs, unsigned long chtype);
static int auto_info(X509_REQ *req, STACK_OF(CONF_VALUE) *sk,
STACK_OF(CONF_VALUE) *attr, int attribs,
unsigned long chtype);
static int add_attribute_object(X509_REQ *req, char *text, const char *def,
char *value, int nid, int n_min, int n_max,
unsigned long chtype);
static int add_DN_object(X509_NAME *n, char *text, const char *def,
char *value, int nid, int n_min, int n_max,
unsigned long chtype, int mval);
static int genpkey_cb(EVP_PKEY_CTX *ctx);
static int req_check_len(int len, int n_min, int n_max);
static int check_end(const char *str, const char *end);
static EVP_PKEY_CTX *set_keygen_ctx(BIO *err, const char *gstr,
int *pkey_type, long *pkeylen,
char **palgnam, ENGINE *keygen_engine);
#ifndef MONOLITH
static char *default_config_file = NULL;
#endif
static CONF *req_conf = NULL;
static int batch = 0;
int MAIN(int, char **);
int MAIN(int argc, char **argv)
{
ENGINE *e = NULL, *gen_eng = NULL;
unsigned long nmflag = 0, reqflag = 0;
int ex = 1, x509 = 0, days = 30;
X509 *x509ss = NULL;
X509_REQ *req = NULL;
EVP_PKEY_CTX *genctx = NULL;
const char *keyalg = NULL;
char *keyalgstr = NULL;
STACK_OF(OPENSSL_STRING) *pkeyopts = NULL, *sigopts = NULL;
EVP_PKEY *pkey = NULL;
int i = 0, badops = 0, newreq = 0, verbose = 0, pkey_type = -1;
long newkey = -1;
BIO *in = NULL, *out = NULL;
int informat, outformat, verify = 0, noout = 0, text = 0, keyform =
FORMAT_PEM;
int nodes = 0, kludge = 0, newhdr = 0, subject = 0, pubkey = 0;
char *infile, *outfile, *prog, *keyfile = NULL, *template =
NULL, *keyout = NULL;
char *engine = NULL;
char *extensions = NULL;
char *req_exts = NULL;
const EVP_CIPHER *cipher = NULL;
ASN1_INTEGER *serial = NULL;
int modulus = 0;
char *inrand = NULL;
char *passargin = NULL, *passargout = NULL;
char *passin = NULL, *passout = NULL;
char *p;
char *subj = NULL;
int multirdn = 0;
const EVP_MD *md_alg = NULL, *digest = NULL;
unsigned long chtype = MBSTRING_ASC;
#ifndef MONOLITH
char *to_free;
long errline;
#endif
req_conf = NULL;
#ifndef OPENSSL_NO_DES
cipher = EVP_des_ede3_cbc();
#endif
apps_startup();
if (bio_err == NULL)
if ((bio_err = BIO_new(BIO_s_file())) != NULL)
BIO_set_fp(bio_err, stderr, BIO_NOCLOSE | BIO_FP_TEXT);
infile = NULL;
outfile = NULL;
informat = FORMAT_PEM;
outformat = FORMAT_PEM;
prog = argv[0];
argc--;
argv++;
while (argc >= 1) {
if (strcmp(*argv, "-inform") == 0) {
if (--argc < 1)
goto bad;
informat = str2fmt(*(++argv));
} else if (strcmp(*argv, "-outform") == 0) {
if (--argc < 1)
goto bad;
outformat = str2fmt(*(++argv));
}
#ifndef OPENSSL_NO_ENGINE
else if (strcmp(*argv, "-engine") == 0) {
if (--argc < 1)
goto bad;
engine = *(++argv);
} else if (strcmp(*argv, "-keygen_engine") == 0) {
if (--argc < 1)
goto bad;
gen_eng = ENGINE_by_id(*(++argv));
if (gen_eng == NULL) {
BIO_printf(bio_err, "Can't find keygen engine %s\n", *argv);
goto end;
}
}
#endif
else if (strcmp(*argv, "-key") == 0) {
if (--argc < 1)
goto bad;
keyfile = *(++argv);
} else if (strcmp(*argv, "-pubkey") == 0) {
pubkey = 1;
} else if (strcmp(*argv, "-new") == 0) {
newreq = 1;
} else if (strcmp(*argv, "-config") == 0) {
if (--argc < 1)
goto bad;
template = *(++argv);
} else if (strcmp(*argv, "-keyform") == 0) {
if (--argc < 1)
goto bad;
keyform = str2fmt(*(++argv));
} else if (strcmp(*argv, "-in") == 0) {
if (--argc < 1)
goto bad;
infile = *(++argv);
} else if (strcmp(*argv, "-out") == 0) {
if (--argc < 1)
goto bad;
outfile = *(++argv);
} else if (strcmp(*argv, "-keyout") == 0) {
if (--argc < 1)
goto bad;
keyout = *(++argv);
} else if (strcmp(*argv, "-passin") == 0) {
if (--argc < 1)
goto bad;
passargin = *(++argv);
} else if (strcmp(*argv, "-passout") == 0) {
if (--argc < 1)
goto bad;
passargout = *(++argv);
} else if (strcmp(*argv, "-rand") == 0) {
if (--argc < 1)
goto bad;
inrand = *(++argv);
} else if (strcmp(*argv, "-newkey") == 0) {
if (--argc < 1)
goto bad;
keyalg = *(++argv);
newreq = 1;
} else if (strcmp(*argv, "-pkeyopt") == 0) {
if (--argc < 1)
goto bad;
if (!pkeyopts)
pkeyopts = sk_OPENSSL_STRING_new_null();
if (!pkeyopts || !sk_OPENSSL_STRING_push(pkeyopts, *(++argv)))
goto bad;
} else if (strcmp(*argv, "-sigopt") == 0) {
if (--argc < 1)
goto bad;
if (!sigopts)
sigopts = sk_OPENSSL_STRING_new_null();
if (!sigopts || !sk_OPENSSL_STRING_push(sigopts, *(++argv)))
goto bad;
} else if (strcmp(*argv, "-batch") == 0)
batch = 1;
else if (strcmp(*argv, "-newhdr") == 0)
newhdr = 1;
else if (strcmp(*argv, "-modulus") == 0)
modulus = 1;
else if (strcmp(*argv, "-verify") == 0)
verify = 1;
else if (strcmp(*argv, "-nodes") == 0)
nodes = 1;
else if (strcmp(*argv, "-noout") == 0)
noout = 1;
else if (strcmp(*argv, "-verbose") == 0)
verbose = 1;
else if (strcmp(*argv, "-utf8") == 0)
chtype = MBSTRING_UTF8;
else if (strcmp(*argv, "-nameopt") == 0) {
if (--argc < 1)
goto bad;
if (!set_name_ex(&nmflag, *(++argv)))
goto bad;
} else if (strcmp(*argv, "-reqopt") == 0) {
if (--argc < 1)
goto bad;
if (!set_cert_ex(&reqflag, *(++argv)))
goto bad;
} else if (strcmp(*argv, "-subject") == 0)
subject = 1;
else if (strcmp(*argv, "-text") == 0)
text = 1;
else if (strcmp(*argv, "-x509") == 0) {
x509 = 1;
} else if (strcmp(*argv, "-asn1-kludge") == 0)
kludge = 1;
else if (strcmp(*argv, "-no-asn1-kludge") == 0)
kludge = 0;
else if (strcmp(*argv, "-subj") == 0) {
if (--argc < 1)
goto bad;
subj = *(++argv);
} else if (strcmp(*argv, "-multivalue-rdn") == 0)
multirdn = 1;
else if (strcmp(*argv, "-days") == 0) {
if (--argc < 1)
goto bad;
days = atoi(*(++argv));
if (days == 0)
days = 30;
} else if (strcmp(*argv, "-set_serial") == 0) {
if (--argc < 1)
goto bad;
serial = s2i_ASN1_INTEGER(NULL, *(++argv));
if (!serial)
goto bad;
} else if (strcmp(*argv, "-extensions") == 0) {
if (--argc < 1)
goto bad;
extensions = *(++argv);
} else if (strcmp(*argv, "-reqexts") == 0) {
if (--argc < 1)
goto bad;
req_exts = *(++argv);
} else if ((md_alg = EVP_get_digestbyname(&((*argv)[1]))) != NULL) {
/* ok */
digest = md_alg;
} else {
BIO_printf(bio_err, "unknown option %s\n", *argv);
badops = 1;
break;
}
argc--;
argv++;
}
if (badops) {
bad:
BIO_printf(bio_err, "%s [options] <infile >outfile\n", prog);
BIO_printf(bio_err, "where options are\n");
BIO_printf(bio_err, " -inform arg input format - DER or PEM\n");
BIO_printf(bio_err, " -outform arg output format - DER or PEM\n");
BIO_printf(bio_err, " -in arg input file\n");
BIO_printf(bio_err, " -out arg output file\n");
BIO_printf(bio_err, " -text text form of request\n");
BIO_printf(bio_err, " -pubkey output public key\n");
BIO_printf(bio_err, " -noout do not output REQ\n");
BIO_printf(bio_err, " -verify verify signature on REQ\n");
BIO_printf(bio_err, " -modulus RSA modulus\n");
BIO_printf(bio_err, " -nodes don't encrypt the output key\n");
#ifndef OPENSSL_NO_ENGINE
BIO_printf(bio_err,
" -engine e use engine e, possibly a hardware device\n");
#endif
BIO_printf(bio_err, " -subject output the request's subject\n");
BIO_printf(bio_err, " -passin private key password source\n");
BIO_printf(bio_err,
" -key file use the private key contained in file\n");
BIO_printf(bio_err, " -keyform arg key file format\n");
BIO_printf(bio_err, " -keyout arg file to send the key to\n");
BIO_printf(bio_err, " -rand file%cfile%c...\n", LIST_SEPARATOR_CHAR,
LIST_SEPARATOR_CHAR);
BIO_printf(bio_err,
" load the file (or the files in the directory) into\n");
BIO_printf(bio_err, " the random number generator\n");
BIO_printf(bio_err,
" -newkey rsa:bits generate a new RSA key of 'bits' in size\n");
BIO_printf(bio_err,
" -newkey dsa:file generate a new DSA key, parameters taken from CA in 'file'\n");
#ifndef OPENSSL_NO_ECDSA
BIO_printf(bio_err,
" -newkey ec:file generate a new EC key, parameters taken from CA in 'file'\n");
#endif
BIO_printf(bio_err,
" -[digest] Digest to sign with (md5, sha1, md2, mdc2, md4)\n");
BIO_printf(bio_err, " -config file request template file.\n");
BIO_printf(bio_err,
" -subj arg set or modify request subject\n");
BIO_printf(bio_err,
" -multivalue-rdn enable support for multivalued RDNs\n");
BIO_printf(bio_err, " -new new request.\n");
BIO_printf(bio_err,
" -batch do not ask anything during request generation\n");
BIO_printf(bio_err,
" -x509 output a x509 structure instead of a cert. req.\n");
BIO_printf(bio_err,
" -days number of days a certificate generated by -x509 is valid for.\n");
BIO_printf(bio_err,
" -set_serial serial number to use for a certificate generated by -x509.\n");
BIO_printf(bio_err,
" -newhdr output \"NEW\" in the header lines\n");
BIO_printf(bio_err,
" -asn1-kludge Output the 'request' in a format that is wrong but some CA's\n");
BIO_printf(bio_err,
" have been reported as requiring\n");
BIO_printf(bio_err,
" -extensions .. specify certificate extension section (override value in config file)\n");
BIO_printf(bio_err,
" -reqexts .. specify request extension section (override value in config file)\n");
BIO_printf(bio_err,
" -utf8 input characters are UTF8 (default ASCII)\n");
BIO_printf(bio_err,
" -nameopt arg - various certificate name options\n");
BIO_printf(bio_err,
" -reqopt arg - various request text options\n\n");
goto end;
}
if (x509 && infile == NULL)
newreq = 1;
ERR_load_crypto_strings();
if (!app_passwd(bio_err, passargin, passargout, &passin, &passout)) {
BIO_printf(bio_err, "Error getting passwords\n");
goto end;
}
#ifndef MONOLITH /* else this has happened in openssl.c
* (global `config') */
/* Lets load up our environment a little */
p = getenv("OPENSSL_CONF");
if (p == NULL)
p = getenv("SSLEAY_CONF");
if (p == NULL)
p = to_free = make_config_name();
default_config_file = p;
config = NCONF_new(NULL);
i = NCONF_load(config, p, &errline);
#endif
if (template != NULL) {
long errline = -1;
if (verbose)
BIO_printf(bio_err, "Using configuration from %s\n", template);
req_conf = NCONF_new(NULL);
i = NCONF_load(req_conf, template, &errline);
if (i == 0) {
BIO_printf(bio_err, "error on line %ld of %s\n", errline,
template);
goto end;
}
} else {
req_conf = config;
if (req_conf == NULL) {
BIO_printf(bio_err, "Unable to load config info from %s\n",
default_config_file);
if (newreq)
goto end;
} else if (verbose)
BIO_printf(bio_err, "Using configuration from %s\n",
default_config_file);
}
if (req_conf != NULL) {
if (!load_config(bio_err, req_conf))
goto end;
p = NCONF_get_string(req_conf, NULL, "oid_file");
if (p == NULL)
ERR_clear_error();
if (p != NULL) {
BIO *oid_bio;
oid_bio = BIO_new_file(p, "r");
if (oid_bio == NULL) {
/*-
BIO_printf(bio_err,"problems opening %s for extra oid's\n",p);
ERR_print_errors(bio_err);
*/
} else {
OBJ_create_objects(oid_bio);
BIO_free(oid_bio);
}
}
}
if (!add_oid_section(bio_err, req_conf))
goto end;
if (md_alg == NULL) {
p = NCONF_get_string(req_conf, SECTION, "default_md");
if (p == NULL)
ERR_clear_error();
if (p != NULL) {
if ((md_alg = EVP_get_digestbyname(p)) != NULL)
digest = md_alg;
}
}
if (!extensions) {
extensions = NCONF_get_string(req_conf, SECTION, V3_EXTENSIONS);
if (!extensions)
ERR_clear_error();
}
if (extensions) {
/* Check syntax of file */
X509V3_CTX ctx;
X509V3_set_ctx_test(&ctx);
X509V3_set_nconf(&ctx, req_conf);
if (!X509V3_EXT_add_nconf(req_conf, &ctx, extensions, NULL)) {
BIO_printf(bio_err,
"Error Loading extension section %s\n", extensions);
goto end;
}
}
if (!passin) {
passin = NCONF_get_string(req_conf, SECTION, "input_password");
if (!passin)
ERR_clear_error();
}
if (!passout) {
passout = NCONF_get_string(req_conf, SECTION, "output_password");
if (!passout)
ERR_clear_error();
}
p = NCONF_get_string(req_conf, SECTION, STRING_MASK);
if (!p)
ERR_clear_error();
if (p && !ASN1_STRING_set_default_mask_asc(p)) {
BIO_printf(bio_err, "Invalid global string mask setting %s\n", p);
goto end;
}
if (chtype != MBSTRING_UTF8) {
p = NCONF_get_string(req_conf, SECTION, UTF8_IN);
if (!p)
ERR_clear_error();
else if (!strcmp(p, "yes"))
chtype = MBSTRING_UTF8;
}
if (!req_exts) {
req_exts = NCONF_get_string(req_conf, SECTION, REQ_EXTENSIONS);
if (!req_exts)
ERR_clear_error();
}
if (req_exts) {
/* Check syntax of file */
X509V3_CTX ctx;
X509V3_set_ctx_test(&ctx);
X509V3_set_nconf(&ctx, req_conf);
if (!X509V3_EXT_add_nconf(req_conf, &ctx, req_exts, NULL)) {
BIO_printf(bio_err,
"Error Loading request extension section %s\n",
req_exts);
goto end;
}
}
in = BIO_new(BIO_s_file());
out = BIO_new(BIO_s_file());
if ((in == NULL) || (out == NULL))
goto end;
e = setup_engine(bio_err, engine, 0);
if (keyfile != NULL) {
pkey = load_key(bio_err, keyfile, keyform, 0, passin, e,
"Private Key");
if (!pkey) {
/*
* load_key() has already printed an appropriate message
*/
goto end;
} else {
char *randfile = NCONF_get_string(req_conf, SECTION, "RANDFILE");
if (randfile == NULL)
ERR_clear_error();
app_RAND_load_file(randfile, bio_err, 0);
}
}
if (newreq && (pkey == NULL)) {
char *randfile = NCONF_get_string(req_conf, SECTION, "RANDFILE");
if (randfile == NULL)
ERR_clear_error();
app_RAND_load_file(randfile, bio_err, 0);
if (inrand)
app_RAND_load_files(inrand);
if (!NCONF_get_number(req_conf, SECTION, BITS, &newkey)) {
newkey = DEFAULT_KEY_LENGTH;
}
if (keyalg) {
genctx = set_keygen_ctx(bio_err, keyalg, &pkey_type, &newkey,
&keyalgstr, gen_eng);
if (!genctx)
goto end;
}
if (newkey < MIN_KEY_LENGTH
&& (pkey_type == EVP_PKEY_RSA || pkey_type == EVP_PKEY_DSA)) {
BIO_printf(bio_err, "private key length is too short,\n");
BIO_printf(bio_err, "it needs to be at least %d bits, not %ld\n",
MIN_KEY_LENGTH, newkey);
goto end;
}
if (!genctx) {
genctx = set_keygen_ctx(bio_err, NULL, &pkey_type, &newkey,
&keyalgstr, gen_eng);
if (!genctx)
goto end;
}
if (pkeyopts) {
char *genopt;
for (i = 0; i < sk_OPENSSL_STRING_num(pkeyopts); i++) {
genopt = sk_OPENSSL_STRING_value(pkeyopts, i);
if (pkey_ctrl_string(genctx, genopt) <= 0) {
BIO_printf(bio_err, "parameter error \"%s\"\n", genopt);
ERR_print_errors(bio_err);
goto end;
}
}
}
BIO_printf(bio_err, "Generating a %ld bit %s private key\n",
newkey, keyalgstr);
EVP_PKEY_CTX_set_cb(genctx, genpkey_cb);
EVP_PKEY_CTX_set_app_data(genctx, bio_err);
if (EVP_PKEY_keygen(genctx, &pkey) <= 0) {
BIO_puts(bio_err, "Error Generating Key\n");
goto end;
}
EVP_PKEY_CTX_free(genctx);
genctx = NULL;
app_RAND_write_file(randfile, bio_err);
if (keyout == NULL) {
keyout = NCONF_get_string(req_conf, SECTION, KEYFILE);
if (keyout == NULL)
ERR_clear_error();
}
if (keyout == NULL) {
BIO_printf(bio_err, "writing new private key to stdout\n");
BIO_set_fp(out, stdout, BIO_NOCLOSE);
#ifdef OPENSSL_SYS_VMS
{
BIO *tmpbio = BIO_new(BIO_f_linebuffer());
out = BIO_push(tmpbio, out);
}
#endif
} else {
BIO_printf(bio_err, "writing new private key to '%s'\n", keyout);
if (BIO_write_filename(out, keyout) <= 0) {
perror(keyout);
goto end;
}
}
p = NCONF_get_string(req_conf, SECTION, "encrypt_rsa_key");
if (p == NULL) {
ERR_clear_error();
p = NCONF_get_string(req_conf, SECTION, "encrypt_key");
if (p == NULL)
ERR_clear_error();
}
if ((p != NULL) && (strcmp(p, "no") == 0))
cipher = NULL;
if (nodes)
cipher = NULL;
i = 0;
loop:
if (!PEM_write_bio_PrivateKey(out, pkey, cipher,
NULL, 0, NULL, passout)) {
if ((ERR_GET_REASON(ERR_peek_error()) ==
PEM_R_PROBLEMS_GETTING_PASSWORD) && (i < 3)) {
ERR_clear_error();
i++;
goto loop;
}
goto end;
}
BIO_printf(bio_err, "-----\n");
}
if (!newreq) {
/*
* Since we are using a pre-existing certificate request, the kludge
* 'format' info should not be changed.
*/
kludge = -1;
if (infile == NULL)
BIO_set_fp(in, stdin, BIO_NOCLOSE);
else {
if (BIO_read_filename(in, infile) <= 0) {
perror(infile);
goto end;
}
}
if (informat == FORMAT_ASN1)
req = d2i_X509_REQ_bio(in, NULL);
else if (informat == FORMAT_PEM)
req = PEM_read_bio_X509_REQ(in, NULL, NULL, NULL);
else {
BIO_printf(bio_err,
"bad input format specified for X509 request\n");
goto end;
}
if (req == NULL) {
BIO_printf(bio_err, "unable to load X509 request\n");
goto end;
}
}
if (newreq || x509) {
if (pkey == NULL) {
BIO_printf(bio_err, "you need to specify a private key\n");
goto end;
}
if (req == NULL) {
req = X509_REQ_new();
if (req == NULL) {
goto end;
}
i = make_REQ(req, pkey, subj, multirdn, !x509, chtype);
subj = NULL; /* done processing '-subj' option */
if ((kludge > 0)
&& !sk_X509_ATTRIBUTE_num(req->req_info->attributes)) {
sk_X509_ATTRIBUTE_free(req->req_info->attributes);
req->req_info->attributes = NULL;
}
if (!i) {
BIO_printf(bio_err, "problems making Certificate Request\n");
goto end;
}
}
if (x509) {
EVP_PKEY *tmppkey;
X509V3_CTX ext_ctx;
if ((x509ss = X509_new()) == NULL)
goto end;
/* Set version to V3 */
if (extensions && !X509_set_version(x509ss, 2))
goto end;
if (serial) {
if (!X509_set_serialNumber(x509ss, serial))
goto end;
} else {
if (!rand_serial(NULL, X509_get_serialNumber(x509ss)))
goto end;
}
if (!X509_set_issuer_name(x509ss, X509_REQ_get_subject_name(req)))
goto end;
if (!X509_gmtime_adj(X509_get_notBefore(x509ss), 0))
goto end;
if (!X509_time_adj_ex(X509_get_notAfter(x509ss), days, 0, NULL))
goto end;
if (!X509_set_subject_name
(x509ss, X509_REQ_get_subject_name(req)))
goto end;
tmppkey = X509_REQ_get_pubkey(req);
if (!tmppkey || !X509_set_pubkey(x509ss, tmppkey))
goto end;
EVP_PKEY_free(tmppkey);
/* Set up V3 context struct */
X509V3_set_ctx(&ext_ctx, x509ss, x509ss, NULL, NULL, 0);
X509V3_set_nconf(&ext_ctx, req_conf);
/* Add extensions */
if (extensions && !X509V3_EXT_add_nconf(req_conf,
&ext_ctx, extensions,
x509ss)) {
BIO_printf(bio_err, "Error Loading extension section %s\n",
extensions);
goto end;
}
i = do_X509_sign(bio_err, x509ss, pkey, digest, sigopts);
if (!i) {
ERR_print_errors(bio_err);
goto end;
}
} else {
X509V3_CTX ext_ctx;
/* Set up V3 context struct */
X509V3_set_ctx(&ext_ctx, NULL, NULL, req, NULL, 0);
X509V3_set_nconf(&ext_ctx, req_conf);
/* Add extensions */
if (req_exts && !X509V3_EXT_REQ_add_nconf(req_conf,
&ext_ctx, req_exts,
req)) {
BIO_printf(bio_err, "Error Loading extension section %s\n",
req_exts);
goto end;
}
i = do_X509_REQ_sign(bio_err, req, pkey, digest, sigopts);
if (!i) {
ERR_print_errors(bio_err);
goto end;
}
}
}
if (subj && x509) {
BIO_printf(bio_err, "Cannot modifiy certificate subject\n");
goto end;
}
if (subj && !x509) {
if (verbose) {
BIO_printf(bio_err, "Modifying Request's Subject\n");
print_name(bio_err, "old subject=",
X509_REQ_get_subject_name(req), nmflag);
}
if (build_subject(req, subj, chtype, multirdn) == 0) {
BIO_printf(bio_err, "ERROR: cannot modify subject\n");
ex = 1;
goto end;
}
req->req_info->enc.modified = 1;
if (verbose) {
print_name(bio_err, "new subject=",
X509_REQ_get_subject_name(req), nmflag);
}
}
if (verify && !x509) {
int tmp = 0;
if (pkey == NULL) {
pkey = X509_REQ_get_pubkey(req);
tmp = 1;
if (pkey == NULL)
goto end;
}
i = X509_REQ_verify(req, pkey);
if (tmp) {
EVP_PKEY_free(pkey);
pkey = NULL;
}
if (i < 0) {
goto end;
} else if (i == 0) {
BIO_printf(bio_err, "verify failure\n");
ERR_print_errors(bio_err);
} else /* if (i > 0) */
BIO_printf(bio_err, "verify OK\n");
}
if (noout && !text && !modulus && !subject && !pubkey) {
ex = 0;
goto end;
}
if (outfile == NULL) {
BIO_set_fp(out, stdout, BIO_NOCLOSE);
#ifdef OPENSSL_SYS_VMS
{
BIO *tmpbio = BIO_new(BIO_f_linebuffer());
out = BIO_push(tmpbio, out);
}
#endif
} else {
if ((keyout != NULL) && (strcmp(outfile, keyout) == 0))
i = (int)BIO_append_filename(out, outfile);
else
i = (int)BIO_write_filename(out, outfile);
if (!i) {
perror(outfile);
goto end;
}
}
if (pubkey) {
EVP_PKEY *tpubkey;
tpubkey = X509_REQ_get_pubkey(req);
if (tpubkey == NULL) {
BIO_printf(bio_err, "Error getting public key\n");
ERR_print_errors(bio_err);
goto end;
}
PEM_write_bio_PUBKEY(out, tpubkey);
EVP_PKEY_free(tpubkey);
}
if (text) {
if (x509)
X509_print_ex(out, x509ss, nmflag, reqflag);
else
X509_REQ_print_ex(out, req, nmflag, reqflag);
}
if (subject) {
if (x509)
print_name(out, "subject=", X509_get_subject_name(x509ss),
nmflag);
else
print_name(out, "subject=", X509_REQ_get_subject_name(req),
nmflag);
}
if (modulus) {
EVP_PKEY *tpubkey;
if (x509)
tpubkey = X509_get_pubkey(x509ss);
else
tpubkey = X509_REQ_get_pubkey(req);
if (tpubkey == NULL) {
fprintf(stdout, "Modulus=unavailable\n");
goto end;
}
fprintf(stdout, "Modulus=");
#ifndef OPENSSL_NO_RSA
if (EVP_PKEY_base_id(tpubkey) == EVP_PKEY_RSA)
BN_print(out, tpubkey->pkey.rsa->n);
else
#endif
fprintf(stdout, "Wrong Algorithm type");
EVP_PKEY_free(tpubkey);
fprintf(stdout, "\n");
}
if (!noout && !x509) {
if (outformat == FORMAT_ASN1)
i = i2d_X509_REQ_bio(out, req);
else if (outformat == FORMAT_PEM) {
if (newhdr)
i = PEM_write_bio_X509_REQ_NEW(out, req);
else
i = PEM_write_bio_X509_REQ(out, req);
} else {
BIO_printf(bio_err, "bad output format specified for outfile\n");
goto end;
}
if (!i) {
BIO_printf(bio_err, "unable to write X509 request\n");
goto end;
}
}
if (!noout && x509 && (x509ss != NULL)) {
if (outformat == FORMAT_ASN1)
i = i2d_X509_bio(out, x509ss);
else if (outformat == FORMAT_PEM)
i = PEM_write_bio_X509(out, x509ss);
else {
BIO_printf(bio_err, "bad output format specified for outfile\n");
goto end;
}
if (!i) {
BIO_printf(bio_err, "unable to write X509 certificate\n");
goto end;
}
}
ex = 0;
end:
#ifndef MONOLITH
if (to_free)
OPENSSL_free(to_free);
#endif
if (ex) {
ERR_print_errors(bio_err);
}
if ((req_conf != NULL) && (req_conf != config))
NCONF_free(req_conf);
BIO_free(in);
BIO_free_all(out);
EVP_PKEY_free(pkey);
if (genctx)
EVP_PKEY_CTX_free(genctx);
if (pkeyopts)
sk_OPENSSL_STRING_free(pkeyopts);
if (sigopts)
sk_OPENSSL_STRING_free(sigopts);
#ifndef OPENSSL_NO_ENGINE
if (gen_eng)
ENGINE_free(gen_eng);
#endif
if (keyalgstr)
OPENSSL_free(keyalgstr);
X509_REQ_free(req);
X509_free(x509ss);
ASN1_INTEGER_free(serial);
release_engine(e);
if (passargin && passin)
OPENSSL_free(passin);
if (passargout && passout)
OPENSSL_free(passout);
OBJ_cleanup();
apps_shutdown();
OPENSSL_EXIT(ex);
}
static int make_REQ(X509_REQ *req, EVP_PKEY *pkey, char *subj, int multirdn,
int attribs, unsigned long chtype)
{
int ret = 0, i;
char no_prompt = 0;
STACK_OF(CONF_VALUE) *dn_sk, *attr_sk = NULL;
char *tmp, *dn_sect, *attr_sect;
tmp = NCONF_get_string(req_conf, SECTION, PROMPT);
if (tmp == NULL)
ERR_clear_error();
if ((tmp != NULL) && !strcmp(tmp, "no"))
no_prompt = 1;
dn_sect = NCONF_get_string(req_conf, SECTION, DISTINGUISHED_NAME);
if (dn_sect == NULL) {
BIO_printf(bio_err, "unable to find '%s' in config\n",
DISTINGUISHED_NAME);
goto err;
}
dn_sk = NCONF_get_section(req_conf, dn_sect);
if (dn_sk == NULL) {
BIO_printf(bio_err, "unable to get '%s' section\n", dn_sect);
goto err;
}
attr_sect = NCONF_get_string(req_conf, SECTION, ATTRIBUTES);
if (attr_sect == NULL) {
ERR_clear_error();
attr_sk = NULL;
} else {
attr_sk = NCONF_get_section(req_conf, attr_sect);
if (attr_sk == NULL) {
BIO_printf(bio_err, "unable to get '%s' section\n", attr_sect);
goto err;
}
}
/* setup version number */
if (!X509_REQ_set_version(req, 0L))
goto err; /* version 1 */
if (no_prompt)
i = auto_info(req, dn_sk, attr_sk, attribs, chtype);
else {
if (subj)
i = build_subject(req, subj, chtype, multirdn);
else
i = prompt_info(req, dn_sk, dn_sect, attr_sk, attr_sect, attribs,
chtype);
}
if (!i)
goto err;
if (!X509_REQ_set_pubkey(req, pkey))
goto err;
ret = 1;
err:
return (ret);
}
/*
* subject is expected to be in the format /type0=value0/type1=value1/type2=...
* where characters may be escaped by \
*/
static int build_subject(X509_REQ *req, char *subject, unsigned long chtype,
int multirdn)
{
X509_NAME *n;
if (!(n = parse_name(subject, chtype, multirdn)))
return 0;
if (!X509_REQ_set_subject_name(req, n)) {
X509_NAME_free(n);
return 0;
}
X509_NAME_free(n);
return 1;
}
static int prompt_info(X509_REQ *req,
STACK_OF(CONF_VALUE) *dn_sk, char *dn_sect,
STACK_OF(CONF_VALUE) *attr_sk, char *attr_sect,
int attribs, unsigned long chtype)
{
int i;
char *p, *q;
char buf[100];
int nid, mval;
long n_min, n_max;
char *type, *value;
const char *def;
CONF_VALUE *v;
X509_NAME *subj;
subj = X509_REQ_get_subject_name(req);
if (!batch) {
BIO_printf(bio_err,
"You are about to be asked to enter information that will be incorporated\n");
BIO_printf(bio_err, "into your certificate request.\n");
BIO_printf(bio_err,
"What you are about to enter is what is called a Distinguished Name or a DN.\n");
BIO_printf(bio_err,
"There are quite a few fields but you can leave some blank\n");
BIO_printf(bio_err,
"For some fields there will be a default value,\n");
BIO_printf(bio_err,
"If you enter '.', the field will be left blank.\n");
BIO_printf(bio_err, "-----\n");
}
if (sk_CONF_VALUE_num(dn_sk)) {
i = -1;
start:for (;;) {
i++;
if (sk_CONF_VALUE_num(dn_sk) <= i)
break;
v = sk_CONF_VALUE_value(dn_sk, i);
p = q = NULL;
type = v->name;
if (!check_end(type, "_min") || !check_end(type, "_max") ||
!check_end(type, "_default") || !check_end(type, "_value"))
continue;
/*
* Skip past any leading X. X: X, etc to allow for multiple
* instances
*/
for (p = v->name; *p; p++)
if ((*p == ':') || (*p == ',') || (*p == '.')) {
p++;
if (*p)
type = p;
break;
}
if (*type == '+') {
mval = -1;
type++;
} else
mval = 0;
/* If OBJ not recognised ignore it */
if ((nid = OBJ_txt2nid(type)) == NID_undef)
goto start;
- if (BIO_snprintf(buf, sizeof buf, "%s_default", v->name)
+ if (BIO_snprintf(buf, sizeof(buf), "%s_default", v->name)
>= (int)sizeof(buf)) {
BIO_printf(bio_err, "Name '%s' too long\n", v->name);
return 0;
}
if ((def = NCONF_get_string(req_conf, dn_sect, buf)) == NULL) {
ERR_clear_error();
def = "";
}
- BIO_snprintf(buf, sizeof buf, "%s_value", v->name);
+ BIO_snprintf(buf, sizeof(buf), "%s_value", v->name);
if ((value = NCONF_get_string(req_conf, dn_sect, buf)) == NULL) {
ERR_clear_error();
value = NULL;
}
- BIO_snprintf(buf, sizeof buf, "%s_min", v->name);
+ BIO_snprintf(buf, sizeof(buf), "%s_min", v->name);
if (!NCONF_get_number(req_conf, dn_sect, buf, &n_min)) {
ERR_clear_error();
n_min = -1;
}
- BIO_snprintf(buf, sizeof buf, "%s_max", v->name);
+ BIO_snprintf(buf, sizeof(buf), "%s_max", v->name);
if (!NCONF_get_number(req_conf, dn_sect, buf, &n_max)) {
ERR_clear_error();
n_max = -1;
}
if (!add_DN_object(subj, v->value, def, value, nid,
n_min, n_max, chtype, mval))
return 0;
}
if (X509_NAME_entry_count(subj) == 0) {
BIO_printf(bio_err,
"error, no objects specified in config file\n");
return 0;
}
if (attribs) {
if ((attr_sk != NULL) && (sk_CONF_VALUE_num(attr_sk) > 0)
&& (!batch)) {
BIO_printf(bio_err,
"\nPlease enter the following 'extra' attributes\n");
BIO_printf(bio_err,
"to be sent with your certificate request\n");
}
i = -1;
start2: for (;;) {
i++;
if ((attr_sk == NULL) || (sk_CONF_VALUE_num(attr_sk) <= i))
break;
v = sk_CONF_VALUE_value(attr_sk, i);
type = v->name;
if ((nid = OBJ_txt2nid(type)) == NID_undef)
goto start2;
- if (BIO_snprintf(buf, sizeof buf, "%s_default", type)
+ if (BIO_snprintf(buf, sizeof(buf), "%s_default", type)
>= (int)sizeof(buf)) {
BIO_printf(bio_err, "Name '%s' too long\n", v->name);
return 0;
}
if ((def = NCONF_get_string(req_conf, attr_sect, buf))
== NULL) {
ERR_clear_error();
def = "";
}
- BIO_snprintf(buf, sizeof buf, "%s_value", type);
+ BIO_snprintf(buf, sizeof(buf), "%s_value", type);
if ((value = NCONF_get_string(req_conf, attr_sect, buf))
== NULL) {
ERR_clear_error();
value = NULL;
}
- BIO_snprintf(buf, sizeof buf, "%s_min", type);
+ BIO_snprintf(buf, sizeof(buf), "%s_min", type);
if (!NCONF_get_number(req_conf, attr_sect, buf, &n_min)) {
ERR_clear_error();
n_min = -1;
}
- BIO_snprintf(buf, sizeof buf, "%s_max", type);
+ BIO_snprintf(buf, sizeof(buf), "%s_max", type);
if (!NCONF_get_number(req_conf, attr_sect, buf, &n_max)) {
ERR_clear_error();
n_max = -1;
}
if (!add_attribute_object(req,
v->value, def, value, nid, n_min,
n_max, chtype))
return 0;
}
}
} else {
BIO_printf(bio_err, "No template, please set one up.\n");
return 0;
}
return 1;
}
static int auto_info(X509_REQ *req, STACK_OF(CONF_VALUE) *dn_sk,
STACK_OF(CONF_VALUE) *attr_sk, int attribs,
unsigned long chtype)
{
int i;
char *p, *q;
char *type;
CONF_VALUE *v;
X509_NAME *subj;
subj = X509_REQ_get_subject_name(req);
for (i = 0; i < sk_CONF_VALUE_num(dn_sk); i++) {
int mval;
v = sk_CONF_VALUE_value(dn_sk, i);
p = q = NULL;
type = v->name;
/*
* Skip past any leading X. X: X, etc to allow for multiple instances
*/
for (p = v->name; *p; p++)
#ifndef CHARSET_EBCDIC
if ((*p == ':') || (*p == ',') || (*p == '.')) {
#else
if ((*p == os_toascii[':']) || (*p == os_toascii[','])
|| (*p == os_toascii['.'])) {
#endif
p++;
if (*p)
type = p;
break;
}
#ifndef CHARSET_EBCDIC
if (*type == '+') {
#else
if (*type == os_toascii['+']) {
#endif
type++;
mval = -1;
} else
mval = 0;
if (!X509_NAME_add_entry_by_txt(subj, type, chtype,
(unsigned char *)v->value, -1, -1,
mval))
return 0;
}
if (!X509_NAME_entry_count(subj)) {
BIO_printf(bio_err, "error, no objects specified in config file\n");
return 0;
}
if (attribs) {
for (i = 0; i < sk_CONF_VALUE_num(attr_sk); i++) {
v = sk_CONF_VALUE_value(attr_sk, i);
if (!X509_REQ_add1_attr_by_txt(req, v->name, chtype,
(unsigned char *)v->value, -1))
return 0;
}
}
return 1;
}
static int add_DN_object(X509_NAME *n, char *text, const char *def,
char *value, int nid, int n_min, int n_max,
unsigned long chtype, int mval)
{
int i, ret = 0;
MS_STATIC char buf[1024];
start:
if (!batch)
BIO_printf(bio_err, "%s [%s]:", text, def);
(void)BIO_flush(bio_err);
if (value != NULL) {
- BUF_strlcpy(buf, value, sizeof buf);
- BUF_strlcat(buf, "\n", sizeof buf);
+ BUF_strlcpy(buf, value, sizeof(buf));
+ BUF_strlcat(buf, "\n", sizeof(buf));
BIO_printf(bio_err, "%s\n", value);
} else {
buf[0] = '\0';
if (!batch) {
- if (!fgets(buf, sizeof buf, stdin))
+ if (!fgets(buf, sizeof(buf), stdin))
return 0;
} else {
buf[0] = '\n';
buf[1] = '\0';
}
}
if (buf[0] == '\0')
return (0);
else if (buf[0] == '\n') {
if ((def == NULL) || (def[0] == '\0'))
return (1);
- BUF_strlcpy(buf, def, sizeof buf);
- BUF_strlcat(buf, "\n", sizeof buf);
+ BUF_strlcpy(buf, def, sizeof(buf));
+ BUF_strlcat(buf, "\n", sizeof(buf));
} else if ((buf[0] == '.') && (buf[1] == '\n'))
return (1);
i = strlen(buf);
if (buf[i - 1] != '\n') {
BIO_printf(bio_err, "weird input :-(\n");
return (0);
}
buf[--i] = '\0';
#ifdef CHARSET_EBCDIC
ebcdic2ascii(buf, buf, i);
#endif
if (!req_check_len(i, n_min, n_max)) {
if (batch || value)
return 0;
goto start;
}
if (!X509_NAME_add_entry_by_NID(n, nid, chtype,
(unsigned char *)buf, -1, -1, mval))
goto err;
ret = 1;
err:
return (ret);
}
static int add_attribute_object(X509_REQ *req, char *text, const char *def,
char *value, int nid, int n_min,
int n_max, unsigned long chtype)
{
int i;
static char buf[1024];
start:
if (!batch)
BIO_printf(bio_err, "%s [%s]:", text, def);
(void)BIO_flush(bio_err);
if (value != NULL) {
- BUF_strlcpy(buf, value, sizeof buf);
- BUF_strlcat(buf, "\n", sizeof buf);
+ BUF_strlcpy(buf, value, sizeof(buf));
+ BUF_strlcat(buf, "\n", sizeof(buf));
BIO_printf(bio_err, "%s\n", value);
} else {
buf[0] = '\0';
if (!batch) {
- if (!fgets(buf, sizeof buf, stdin))
+ if (!fgets(buf, sizeof(buf), stdin))
return 0;
} else {
buf[0] = '\n';
buf[1] = '\0';
}
}
if (buf[0] == '\0')
return (0);
else if (buf[0] == '\n') {
if ((def == NULL) || (def[0] == '\0'))
return (1);
- BUF_strlcpy(buf, def, sizeof buf);
- BUF_strlcat(buf, "\n", sizeof buf);
+ BUF_strlcpy(buf, def, sizeof(buf));
+ BUF_strlcat(buf, "\n", sizeof(buf));
} else if ((buf[0] == '.') && (buf[1] == '\n'))
return (1);
i = strlen(buf);
if (buf[i - 1] != '\n') {
BIO_printf(bio_err, "weird input :-(\n");
return (0);
}
buf[--i] = '\0';
#ifdef CHARSET_EBCDIC
ebcdic2ascii(buf, buf, i);
#endif
if (!req_check_len(i, n_min, n_max)) {
if (batch || value)
return 0;
goto start;
}
if (!X509_REQ_add1_attr_by_NID(req, nid, chtype,
(unsigned char *)buf, -1)) {
BIO_printf(bio_err, "Error adding attribute\n");
ERR_print_errors(bio_err);
goto err;
}
return (1);
err:
return (0);
}
static int req_check_len(int len, int n_min, int n_max)
{
if ((n_min > 0) && (len < n_min)) {
BIO_printf(bio_err,
"string is too short, it needs to be at least %d bytes long\n",
n_min);
return (0);
}
if ((n_max >= 0) && (len > n_max)) {
BIO_printf(bio_err,
"string is too long, it needs to be less than %d bytes long\n",
n_max);
return (0);
}
return (1);
}
/* Check if the end of a string matches 'end' */
static int check_end(const char *str, const char *end)
{
int elen, slen;
const char *tmp;
elen = strlen(end);
slen = strlen(str);
if (elen > slen)
return 1;
tmp = str + slen - elen;
return strcmp(tmp, end);
}
static EVP_PKEY_CTX *set_keygen_ctx(BIO *err, const char *gstr,
int *pkey_type, long *pkeylen,
char **palgnam, ENGINE *keygen_engine)
{
EVP_PKEY_CTX *gctx = NULL;
EVP_PKEY *param = NULL;
long keylen = -1;
BIO *pbio = NULL;
const char *paramfile = NULL;
if (gstr == NULL) {
*pkey_type = EVP_PKEY_RSA;
keylen = *pkeylen;
} else if (gstr[0] >= '0' && gstr[0] <= '9') {
*pkey_type = EVP_PKEY_RSA;
keylen = atol(gstr);
*pkeylen = keylen;
} else if (!strncmp(gstr, "param:", 6))
paramfile = gstr + 6;
else {
const char *p = strchr(gstr, ':');
int len;
ENGINE *tmpeng;
const EVP_PKEY_ASN1_METHOD *ameth;
if (p)
len = p - gstr;
else
len = strlen(gstr);
/*
* The lookup of a the string will cover all engines so keep a note
* of the implementation.
*/
ameth = EVP_PKEY_asn1_find_str(&tmpeng, gstr, len);
if (!ameth) {
BIO_printf(err, "Unknown algorithm %.*s\n", len, gstr);
return NULL;
}
EVP_PKEY_asn1_get0_info(NULL, pkey_type, NULL, NULL, NULL, ameth);
#ifndef OPENSSL_NO_ENGINE
if (tmpeng)
ENGINE_finish(tmpeng);
#endif
if (*pkey_type == EVP_PKEY_RSA) {
if (p) {
keylen = atol(p + 1);
*pkeylen = keylen;
} else
keylen = *pkeylen;
} else if (p)
paramfile = p + 1;
}
if (paramfile) {
pbio = BIO_new_file(paramfile, "r");
if (!pbio) {
BIO_printf(err, "Can't open parameter file %s\n", paramfile);
return NULL;
}
param = PEM_read_bio_Parameters(pbio, NULL);
if (!param) {
X509 *x;
(void)BIO_reset(pbio);
x = PEM_read_bio_X509(pbio, NULL, NULL, NULL);
if (x) {
param = X509_get_pubkey(x);
X509_free(x);
}
}
BIO_free(pbio);
if (!param) {
BIO_printf(err, "Error reading parameter file %s\n", paramfile);
return NULL;
}
if (*pkey_type == -1)
*pkey_type = EVP_PKEY_id(param);
else if (*pkey_type != EVP_PKEY_base_id(param)) {
BIO_printf(err, "Key Type does not match parameters\n");
EVP_PKEY_free(param);
return NULL;
}
}
if (palgnam) {
const EVP_PKEY_ASN1_METHOD *ameth;
ENGINE *tmpeng;
const char *anam;
ameth = EVP_PKEY_asn1_find(&tmpeng, *pkey_type);
if (!ameth) {
BIO_puts(err, "Internal error: can't find key algorithm\n");
return NULL;
}
EVP_PKEY_asn1_get0_info(NULL, NULL, NULL, NULL, &anam, ameth);
*palgnam = BUF_strdup(anam);
#ifndef OPENSSL_NO_ENGINE
if (tmpeng)
ENGINE_finish(tmpeng);
#endif
}
if (param) {
gctx = EVP_PKEY_CTX_new(param, keygen_engine);
*pkeylen = EVP_PKEY_bits(param);
EVP_PKEY_free(param);
} else
gctx = EVP_PKEY_CTX_new_id(*pkey_type, keygen_engine);
if (!gctx) {
BIO_puts(err, "Error allocating keygen context\n");
ERR_print_errors(err);
return NULL;
}
if (EVP_PKEY_keygen_init(gctx) <= 0) {
BIO_puts(err, "Error initializing keygen context\n");
ERR_print_errors(err);
return NULL;
}
#ifndef OPENSSL_NO_RSA
if ((*pkey_type == EVP_PKEY_RSA) && (keylen != -1)) {
if (EVP_PKEY_CTX_set_rsa_keygen_bits(gctx, keylen) <= 0) {
BIO_puts(err, "Error setting RSA keysize\n");
ERR_print_errors(err);
EVP_PKEY_CTX_free(gctx);
return NULL;
}
}
#endif
return gctx;
}
static int genpkey_cb(EVP_PKEY_CTX *ctx)
{
char c = '*';
BIO *b = EVP_PKEY_CTX_get_app_data(ctx);
int p;
p = EVP_PKEY_CTX_get_keygen_info(ctx, 0);
if (p == 0)
c = '.';
if (p == 1)
c = '+';
if (p == 2)
c = '*';
if (p == 3)
c = '\n';
BIO_write(b, &c, 1);
(void)BIO_flush(b);
#ifdef LINT
p = n;
#endif
return 1;
}
static int do_sign_init(BIO *err, EVP_MD_CTX *ctx, EVP_PKEY *pkey,
const EVP_MD *md, STACK_OF(OPENSSL_STRING) *sigopts)
{
EVP_PKEY_CTX *pkctx = NULL;
int i;
EVP_MD_CTX_init(ctx);
if (!EVP_DigestSignInit(ctx, &pkctx, md, NULL, pkey))
return 0;
for (i = 0; i < sk_OPENSSL_STRING_num(sigopts); i++) {
char *sigopt = sk_OPENSSL_STRING_value(sigopts, i);
if (pkey_ctrl_string(pkctx, sigopt) <= 0) {
BIO_printf(err, "parameter error \"%s\"\n", sigopt);
ERR_print_errors(bio_err);
return 0;
}
}
return 1;
}
int do_X509_sign(BIO *err, X509 *x, EVP_PKEY *pkey, const EVP_MD *md,
STACK_OF(OPENSSL_STRING) *sigopts)
{
int rv;
EVP_MD_CTX mctx;
EVP_MD_CTX_init(&mctx);
rv = do_sign_init(err, &mctx, pkey, md, sigopts);
if (rv > 0)
rv = X509_sign_ctx(x, &mctx);
EVP_MD_CTX_cleanup(&mctx);
return rv > 0 ? 1 : 0;
}
int do_X509_REQ_sign(BIO *err, X509_REQ *x, EVP_PKEY *pkey, const EVP_MD *md,
STACK_OF(OPENSSL_STRING) *sigopts)
{
int rv;
EVP_MD_CTX mctx;
EVP_MD_CTX_init(&mctx);
rv = do_sign_init(err, &mctx, pkey, md, sigopts);
if (rv > 0)
rv = X509_REQ_sign_ctx(x, &mctx);
EVP_MD_CTX_cleanup(&mctx);
return rv > 0 ? 1 : 0;
}
int do_X509_CRL_sign(BIO *err, X509_CRL *x, EVP_PKEY *pkey, const EVP_MD *md,
STACK_OF(OPENSSL_STRING) *sigopts)
{
int rv;
EVP_MD_CTX mctx;
EVP_MD_CTX_init(&mctx);
rv = do_sign_init(err, &mctx, pkey, md, sigopts);
if (rv > 0)
rv = X509_CRL_sign_ctx(x, &mctx);
EVP_MD_CTX_cleanup(&mctx);
return rv > 0 ? 1 : 0;
}
diff --git a/apps/s_client.c b/apps/s_client.c
index 2a0ead7beffb..c85566855fef 100644
--- a/apps/s_client.c
+++ b/apps/s_client.c
@@ -1,2364 +1,2364 @@
/* apps/s_client.c */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
/* ====================================================================
* Copyright (c) 1998-2006 The OpenSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* openssl-core@openssl.org.
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.openssl.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*
* This product includes cryptographic software written by Eric Young
* (eay@cryptsoft.com). This product includes software written by Tim
* Hudson (tjh@cryptsoft.com).
*
*/
/* ====================================================================
* Copyright 2005 Nokia. All rights reserved.
*
* The portions of the attached software ("Contribution") is developed by
* Nokia Corporation and is licensed pursuant to the OpenSSL open source
* license.
*
* The Contribution, originally written by Mika Kousa and Pasi Eronen of
* Nokia Corporation, consists of the "PSK" (Pre-Shared Key) ciphersuites
* support (see RFC 4279) to OpenSSL.
*
* No patent licenses or other rights except those expressly stated in
* the OpenSSL open source license shall be deemed granted or received
* expressly, by implication, estoppel, or otherwise.
*
* No assurances are provided by Nokia that the Contribution does not
* infringe the patent or other intellectual property rights of any third
* party or that the license provides you with all the necessary rights
* to make use of the Contribution.
*
* THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. IN
* ADDITION TO THE DISCLAIMERS INCLUDED IN THE LICENSE, NOKIA
* SPECIFICALLY DISCLAIMS ANY LIABILITY FOR CLAIMS BROUGHT BY YOU OR ANY
* OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS OR
* OTHERWISE.
*/
#include <assert.h>
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/e_os2.h>
#ifdef OPENSSL_NO_STDIO
# define APPS_WIN16
#endif
/*
* With IPv6, it looks like Digital has mixed up the proper order of
* recursive header file inclusion, resulting in the compiler complaining
* that u_int isn't defined, but only if _POSIX_C_SOURCE is defined, which is
* needed to have fileno() declared correctly... So let's define u_int
*/
#if defined(OPENSSL_SYS_VMS_DECC) && !defined(__U_INT)
# define __U_INT
typedef unsigned int u_int;
#endif
#define USE_SOCKETS
#include "apps.h"
#include <openssl/x509.h>
#include <openssl/ssl.h>
#include <openssl/err.h>
#include <openssl/pem.h>
#include <openssl/rand.h>
#include <openssl/ocsp.h>
#include <openssl/bn.h>
#ifndef OPENSSL_NO_SRP
# include <openssl/srp.h>
#endif
#include "s_apps.h"
#include "timeouts.h"
#if (defined(OPENSSL_SYS_VMS) && __VMS_VER < 70000000)
/* FIONBIO used as a switch to enable ioctl, and that isn't in VMS < 7.0 */
# undef FIONBIO
#endif
#if defined(OPENSSL_SYS_BEOS_R5)
# include <fcntl.h>
#endif
#undef PROG
#define PROG s_client_main
/*
* #define SSL_HOST_NAME "www.netscape.com"
*/
/*
* #define SSL_HOST_NAME "193.118.187.102"
*/
#define SSL_HOST_NAME "localhost"
/* no default cert. */
/*
* #define TEST_CERT "client.pem"
*/
#undef BUFSIZZ
#define BUFSIZZ 1024*8
extern int verify_depth;
extern int verify_error;
extern int verify_return_error;
extern int verify_quiet;
#ifdef FIONBIO
static int c_nbio = 0;
#endif
static int c_Pause = 0;
static int c_debug = 0;
#ifndef OPENSSL_NO_TLSEXT
static int c_tlsextdebug = 0;
static int c_status_req = 0;
#endif
static int c_msg = 0;
static int c_showcerts = 0;
static char *keymatexportlabel = NULL;
static int keymatexportlen = 20;
static void sc_usage(void);
static void print_stuff(BIO *berr, SSL *con, int full);
#ifndef OPENSSL_NO_TLSEXT
static int ocsp_resp_cb(SSL *s, void *arg);
#endif
static BIO *bio_c_out = NULL;
static BIO *bio_c_msg = NULL;
static int c_quiet = 0;
static int c_ign_eof = 0;
static int c_brief = 0;
#ifndef OPENSSL_NO_PSK
/* Default PSK identity and key */
static char *psk_identity = "Client_identity";
/*
* char *psk_key=NULL; by default PSK is not used
*/
static unsigned int psk_client_cb(SSL *ssl, const char *hint, char *identity,
unsigned int max_identity_len,
unsigned char *psk,
unsigned int max_psk_len)
{
int ret;
long key_len;
unsigned char *key;
if (c_debug)
BIO_printf(bio_c_out, "psk_client_cb\n");
if (!hint) {
/* no ServerKeyExchange message */
if (c_debug)
BIO_printf(bio_c_out,
"NULL received PSK identity hint, continuing anyway\n");
} else if (c_debug)
BIO_printf(bio_c_out, "Received PSK identity hint '%s'\n", hint);
/*
* lookup PSK identity and PSK key based on the given identity hint here
*/
ret = BIO_snprintf(identity, max_identity_len, "%s", psk_identity);
if (ret < 0 || (unsigned int)ret > max_identity_len)
goto out_err;
if (c_debug)
BIO_printf(bio_c_out, "created identity '%s' len=%d\n", identity,
ret);
/* convert the PSK key to binary */
key = string_to_hex(psk_key, &key_len);
if (key == NULL) {
BIO_printf(bio_err, "Could not convert PSK key '%s' to buffer\n",
psk_key);
return 0;
}
if ((unsigned long)key_len > (unsigned long)max_psk_len) {
BIO_printf(bio_err,
"psk buffer of callback is too small (%d) for key (%ld)\n",
max_psk_len, key_len);
OPENSSL_free(key);
return 0;
}
memcpy(psk, key, key_len);
OPENSSL_free(key);
if (c_debug)
BIO_printf(bio_c_out, "created PSK len=%ld\n", key_len);
return key_len;
out_err:
if (c_debug)
BIO_printf(bio_err, "Error in PSK client callback\n");
return 0;
}
#endif
static void sc_usage(void)
{
BIO_printf(bio_err, "usage: s_client args\n");
BIO_printf(bio_err, "\n");
BIO_printf(bio_err, " -host host - use -connect instead\n");
BIO_printf(bio_err, " -port port - use -connect instead\n");
BIO_printf(bio_err,
" -connect host:port - who to connect to (default is %s:%s)\n",
SSL_HOST_NAME, PORT_STR);
BIO_printf(bio_err,
" -verify_hostname host - check peer certificate matches \"host\"\n");
BIO_printf(bio_err,
" -verify_email email - check peer certificate matches \"email\"\n");
BIO_printf(bio_err,
" -verify_ip ipaddr - check peer certificate matches \"ipaddr\"\n");
BIO_printf(bio_err,
" -verify arg - turn on peer certificate verification\n");
BIO_printf(bio_err,
" -verify_return_error - return verification errors\n");
BIO_printf(bio_err,
" -cert arg - certificate file to use, PEM format assumed\n");
BIO_printf(bio_err,
" -certform arg - certificate format (PEM or DER) PEM default\n");
BIO_printf(bio_err,
" -key arg - Private key file to use, in cert file if\n");
BIO_printf(bio_err, " not specified but cert file is.\n");
BIO_printf(bio_err,
" -keyform arg - key format (PEM or DER) PEM default\n");
BIO_printf(bio_err,
" -pass arg - private key file pass phrase source\n");
BIO_printf(bio_err, " -CApath arg - PEM format directory of CA's\n");
BIO_printf(bio_err, " -CAfile arg - PEM format file of CA's\n");
BIO_printf(bio_err,
" -no_alt_chains - only ever use the first certificate chain found\n");
BIO_printf(bio_err,
" -reconnect - Drop and re-make the connection with the same Session-ID\n");
BIO_printf(bio_err,
" -pause - sleep(1) after each read(2) and write(2) system call\n");
BIO_printf(bio_err,
" -prexit - print session information even on connection failure\n");
BIO_printf(bio_err,
" -showcerts - show all certificates in the chain\n");
BIO_printf(bio_err, " -debug - extra output\n");
#ifdef WATT32
BIO_printf(bio_err, " -wdebug - WATT-32 tcp debugging\n");
#endif
BIO_printf(bio_err, " -msg - Show protocol messages\n");
BIO_printf(bio_err, " -nbio_test - more ssl protocol testing\n");
BIO_printf(bio_err, " -state - print the 'ssl' states\n");
#ifdef FIONBIO
BIO_printf(bio_err, " -nbio - Run with non-blocking IO\n");
#endif
BIO_printf(bio_err,
" -crlf - convert LF from terminal into CRLF\n");
BIO_printf(bio_err, " -quiet - no s_client output\n");
BIO_printf(bio_err,
" -ign_eof - ignore input eof (default when -quiet)\n");
BIO_printf(bio_err, " -no_ign_eof - don't ignore input eof\n");
#ifndef OPENSSL_NO_PSK
BIO_printf(bio_err, " -psk_identity arg - PSK identity\n");
BIO_printf(bio_err, " -psk arg - PSK in hex (without 0x)\n");
# ifndef OPENSSL_NO_JPAKE
BIO_printf(bio_err, " -jpake arg - JPAKE secret to use\n");
# endif
#endif
#ifndef OPENSSL_NO_SRP
BIO_printf(bio_err,
" -srpuser user - SRP authentification for 'user'\n");
BIO_printf(bio_err, " -srppass arg - password for 'user'\n");
BIO_printf(bio_err,
" -srp_lateuser - SRP username into second ClientHello message\n");
BIO_printf(bio_err,
" -srp_moregroups - Tolerate other than the known g N values.\n");
BIO_printf(bio_err,
" -srp_strength int - minimal length in bits for N (default %d).\n",
SRP_MINIMAL_N);
#endif
BIO_printf(bio_err, " -ssl2 - just use SSLv2\n");
#ifndef OPENSSL_NO_SSL3_METHOD
BIO_printf(bio_err, " -ssl3 - just use SSLv3\n");
#endif
BIO_printf(bio_err, " -tls1_2 - just use TLSv1.2\n");
BIO_printf(bio_err, " -tls1_1 - just use TLSv1.1\n");
BIO_printf(bio_err, " -tls1 - just use TLSv1\n");
BIO_printf(bio_err, " -dtls1 - just use DTLSv1\n");
BIO_printf(bio_err, " -fallback_scsv - send TLS_FALLBACK_SCSV\n");
BIO_printf(bio_err, " -mtu - set the link layer MTU\n");
BIO_printf(bio_err,
" -no_tls1_2/-no_tls1_1/-no_tls1/-no_ssl3/-no_ssl2 - turn off that protocol\n");
BIO_printf(bio_err,
" -bugs - Switch on all SSL implementation bug workarounds\n");
BIO_printf(bio_err,
" -cipher - preferred cipher to use, use the 'openssl ciphers'\n");
BIO_printf(bio_err,
" command to see what is available\n");
BIO_printf(bio_err,
" -starttls prot - use the STARTTLS command before starting TLS\n");
BIO_printf(bio_err,
" for those protocols that support it, where\n");
BIO_printf(bio_err,
" 'prot' defines which one to assume. Currently,\n");
BIO_printf(bio_err,
" only \"smtp\", \"pop3\", \"imap\", \"ftp\" and \"xmpp\"\n");
BIO_printf(bio_err, " are supported.\n");
#ifndef OPENSSL_NO_ENGINE
BIO_printf(bio_err,
" -engine id - Initialise and use the specified engine\n");
#endif
BIO_printf(bio_err, " -rand file%cfile%c...\n", LIST_SEPARATOR_CHAR,
LIST_SEPARATOR_CHAR);
BIO_printf(bio_err, " -sess_out arg - file to write SSL session to\n");
BIO_printf(bio_err, " -sess_in arg - file to read SSL session from\n");
#ifndef OPENSSL_NO_TLSEXT
BIO_printf(bio_err,
" -servername host - Set TLS extension servername in ClientHello\n");
BIO_printf(bio_err,
" -tlsextdebug - hex dump of all TLS extensions received\n");
BIO_printf(bio_err,
" -status - request certificate status from server\n");
BIO_printf(bio_err,
" -no_ticket - disable use of RFC4507bis session tickets\n");
BIO_printf(bio_err,
" -serverinfo types - send empty ClientHello extensions (comma-separated numbers)\n");
BIO_printf(bio_err,
" -curves arg - Elliptic curves to advertise (colon-separated list)\n");
BIO_printf(bio_err,
" -sigalgs arg - Signature algorithms to support (colon-separated list)\n");
BIO_printf(bio_err,
" -client_sigalgs arg - Signature algorithms to support for client\n");
BIO_printf(bio_err,
" certificate authentication (colon-separated list)\n");
#endif
#ifndef OPENSSL_NO_NEXTPROTONEG
BIO_printf(bio_err,
" -nextprotoneg arg - enable NPN extension, considering named protocols supported (comma-separated list)\n");
#endif
BIO_printf(bio_err,
" -alpn arg - enable ALPN extension, considering named protocols supported (comma-separated list)\n");
BIO_printf(bio_err,
" -legacy_renegotiation - enable use of legacy renegotiation (dangerous)\n");
#ifndef OPENSSL_NO_SRTP
BIO_printf(bio_err,
" -use_srtp profiles - Offer SRTP key management with a colon-separated profile list\n");
#endif
BIO_printf(bio_err,
" -keymatexport label - Export keying material using label\n");
BIO_printf(bio_err,
" -keymatexportlen len - Export len bytes of keying material (default 20)\n");
}
#ifndef OPENSSL_NO_TLSEXT
/* This is a context that we pass to callbacks */
typedef struct tlsextctx_st {
BIO *biodebug;
int ack;
} tlsextctx;
static int MS_CALLBACK ssl_servername_cb(SSL *s, int *ad, void *arg)
{
tlsextctx *p = (tlsextctx *) arg;
const char *hn = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
if (SSL_get_servername_type(s) != -1)
p->ack = !SSL_session_reused(s) && hn != NULL;
else
BIO_printf(bio_err, "Can't use SSL_get_servername\n");
return SSL_TLSEXT_ERR_OK;
}
# ifndef OPENSSL_NO_SRP
/* This is a context that we pass to all callbacks */
typedef struct srp_arg_st {
char *srppassin;
char *srplogin;
int msg; /* copy from c_msg */
int debug; /* copy from c_debug */
int amp; /* allow more groups */
int strength /* minimal size for N */ ;
} SRP_ARG;
# define SRP_NUMBER_ITERATIONS_FOR_PRIME 64
static int srp_Verify_N_and_g(BIGNUM *N, BIGNUM *g)
{
BN_CTX *bn_ctx = BN_CTX_new();
BIGNUM *p = BN_new();
BIGNUM *r = BN_new();
int ret =
g != NULL && N != NULL && bn_ctx != NULL && BN_is_odd(N) &&
BN_is_prime_ex(N, SRP_NUMBER_ITERATIONS_FOR_PRIME, bn_ctx, NULL) &&
p != NULL && BN_rshift1(p, N) &&
/* p = (N-1)/2 */
BN_is_prime_ex(p, SRP_NUMBER_ITERATIONS_FOR_PRIME, bn_ctx, NULL) &&
r != NULL &&
/* verify g^((N-1)/2) == -1 (mod N) */
BN_mod_exp(r, g, p, N, bn_ctx) &&
BN_add_word(r, 1) && BN_cmp(r, N) == 0;
if (r)
BN_free(r);
if (p)
BN_free(p);
if (bn_ctx)
BN_CTX_free(bn_ctx);
return ret;
}
/*-
* This callback is used here for two purposes:
* - extended debugging
* - making some primality tests for unknown groups
* The callback is only called for a non default group.
*
* An application does not need the call back at all if
* only the stanard groups are used. In real life situations,
* client and server already share well known groups,
* thus there is no need to verify them.
* Furthermore, in case that a server actually proposes a group that
* is not one of those defined in RFC 5054, it is more appropriate
* to add the group to a static list and then compare since
* primality tests are rather cpu consuming.
*/
static int MS_CALLBACK ssl_srp_verify_param_cb(SSL *s, void *arg)
{
SRP_ARG *srp_arg = (SRP_ARG *)arg;
BIGNUM *N = NULL, *g = NULL;
if (!(N = SSL_get_srp_N(s)) || !(g = SSL_get_srp_g(s)))
return 0;
if (srp_arg->debug || srp_arg->msg || srp_arg->amp == 1) {
BIO_printf(bio_err, "SRP parameters:\n");
BIO_printf(bio_err, "\tN=");
BN_print(bio_err, N);
BIO_printf(bio_err, "\n\tg=");
BN_print(bio_err, g);
BIO_printf(bio_err, "\n");
}
if (SRP_check_known_gN_param(g, N))
return 1;
if (srp_arg->amp == 1) {
if (srp_arg->debug)
BIO_printf(bio_err,
"SRP param N and g are not known params, going to check deeper.\n");
/*
* The srp_moregroups is a real debugging feature. Implementors
* should rather add the value to the known ones. The minimal size
* has already been tested.
*/
if (BN_num_bits(g) <= BN_BITS && srp_Verify_N_and_g(N, g))
return 1;
}
BIO_printf(bio_err, "SRP param N and g rejected.\n");
return 0;
}
# define PWD_STRLEN 1024
static char *MS_CALLBACK ssl_give_srp_client_pwd_cb(SSL *s, void *arg)
{
SRP_ARG *srp_arg = (SRP_ARG *)arg;
char *pass = (char *)OPENSSL_malloc(PWD_STRLEN + 1);
PW_CB_DATA cb_tmp;
int l;
if (!pass) {
BIO_printf(bio_err, "Malloc failure\n");
return NULL;
}
cb_tmp.password = (char *)srp_arg->srppassin;
cb_tmp.prompt_info = "SRP user";
if ((l = password_callback(pass, PWD_STRLEN, 0, &cb_tmp)) < 0) {
BIO_printf(bio_err, "Can't read Password\n");
OPENSSL_free(pass);
return NULL;
}
*(pass + l) = '\0';
return pass;
}
# endif
# ifndef OPENSSL_NO_SRTP
char *srtp_profiles = NULL;
# endif
# ifndef OPENSSL_NO_NEXTPROTONEG
/* This the context that we pass to next_proto_cb */
typedef struct tlsextnextprotoctx_st {
unsigned char *data;
unsigned short len;
int status;
} tlsextnextprotoctx;
static tlsextnextprotoctx next_proto;
static int next_proto_cb(SSL *s, unsigned char **out, unsigned char *outlen,
const unsigned char *in, unsigned int inlen,
void *arg)
{
tlsextnextprotoctx *ctx = arg;
if (!c_quiet) {
/* We can assume that |in| is syntactically valid. */
unsigned i;
BIO_printf(bio_c_out, "Protocols advertised by server: ");
for (i = 0; i < inlen;) {
if (i)
BIO_write(bio_c_out, ", ", 2);
BIO_write(bio_c_out, &in[i + 1], in[i]);
i += in[i] + 1;
}
BIO_write(bio_c_out, "\n", 1);
}
ctx->status =
SSL_select_next_proto(out, outlen, in, inlen, ctx->data, ctx->len);
return SSL_TLSEXT_ERR_OK;
}
# endif /* ndef OPENSSL_NO_NEXTPROTONEG */
static int serverinfo_cli_parse_cb(SSL *s, unsigned int ext_type,
const unsigned char *in, size_t inlen,
int *al, void *arg)
{
char pem_name[100];
unsigned char ext_buf[4 + 65536];
/* Reconstruct the type/len fields prior to extension data */
inlen &= 0xffff; /* for formal memcpy correctness */
ext_buf[0] = (unsigned char)(ext_type >> 8);
ext_buf[1] = (unsigned char)(ext_type);
ext_buf[2] = (unsigned char)(inlen >> 8);
ext_buf[3] = (unsigned char)(inlen);
memcpy(ext_buf + 4, in, inlen);
BIO_snprintf(pem_name, sizeof(pem_name), "SERVERINFO FOR EXTENSION %d",
ext_type);
PEM_write_bio(bio_c_out, pem_name, "", ext_buf, 4 + inlen);
return 1;
}
#endif
enum {
PROTO_OFF = 0,
PROTO_SMTP,
PROTO_POP3,
PROTO_IMAP,
PROTO_FTP,
PROTO_XMPP
};
int MAIN(int, char **);
int MAIN(int argc, char **argv)
{
int build_chain = 0;
SSL *con = NULL;
#ifndef OPENSSL_NO_KRB5
KSSL_CTX *kctx;
#endif
int s, k, width, state = 0;
char *cbuf = NULL, *sbuf = NULL, *mbuf = NULL;
int cbuf_len, cbuf_off;
int sbuf_len, sbuf_off;
fd_set readfds, writefds;
short port = PORT;
int full_log = 1;
char *host = SSL_HOST_NAME;
char *cert_file = NULL, *key_file = NULL, *chain_file = NULL;
int cert_format = FORMAT_PEM, key_format = FORMAT_PEM;
char *passarg = NULL, *pass = NULL;
X509 *cert = NULL;
EVP_PKEY *key = NULL;
STACK_OF(X509) *chain = NULL;
char *CApath = NULL, *CAfile = NULL;
char *chCApath = NULL, *chCAfile = NULL;
char *vfyCApath = NULL, *vfyCAfile = NULL;
int reconnect = 0, badop = 0, verify = SSL_VERIFY_NONE;
int crlf = 0;
int write_tty, read_tty, write_ssl, read_ssl, tty_on, ssl_pending;
SSL_CTX *ctx = NULL;
int ret = 1, in_init = 1, i, nbio_test = 0;
int starttls_proto = PROTO_OFF;
int prexit = 0;
X509_VERIFY_PARAM *vpm = NULL;
int badarg = 0;
const SSL_METHOD *meth = NULL;
int socket_type = SOCK_STREAM;
BIO *sbio;
char *inrand = NULL;
int mbuf_len = 0;
struct timeval timeout, *timeoutp;
char *engine_id = NULL;
ENGINE *e = NULL;
#ifndef OPENSSL_NO_ENGINE
char *ssl_client_engine_id = NULL;
ENGINE *ssl_client_engine = NULL;
#endif
#if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS) || defined(OPENSSL_SYS_NETWARE) || defined(OPENSSL_SYS_BEOS_R5)
struct timeval tv;
# if defined(OPENSSL_SYS_BEOS_R5)
int stdin_set = 0;
# endif
#endif
#ifndef OPENSSL_NO_TLSEXT
char *servername = NULL;
tlsextctx tlsextcbp = { NULL, 0 };
# ifndef OPENSSL_NO_NEXTPROTONEG
const char *next_proto_neg_in = NULL;
# endif
const char *alpn_in = NULL;
# define MAX_SI_TYPES 100
unsigned short serverinfo_types[MAX_SI_TYPES];
int serverinfo_types_count = 0;
#endif
char *sess_in = NULL;
char *sess_out = NULL;
struct sockaddr peer;
int peerlen = sizeof(peer);
int fallback_scsv = 0;
int enable_timeouts = 0;
long socket_mtu = 0;
#ifndef OPENSSL_NO_JPAKE
static char *jpake_secret = NULL;
# define no_jpake !jpake_secret
#else
# define no_jpake 1
#endif
#ifndef OPENSSL_NO_SRP
char *srppass = NULL;
int srp_lateuser = 0;
SRP_ARG srp_arg = { NULL, NULL, 0, 0, 0, 1024 };
#endif
SSL_EXCERT *exc = NULL;
SSL_CONF_CTX *cctx = NULL;
STACK_OF(OPENSSL_STRING) *ssl_args = NULL;
char *crl_file = NULL;
int crl_format = FORMAT_PEM;
int crl_download = 0;
STACK_OF(X509_CRL) *crls = NULL;
int prot_opt = 0, no_prot_opt = 0;
meth = SSLv23_client_method();
apps_startup();
c_Pause = 0;
c_quiet = 0;
c_ign_eof = 0;
c_debug = 0;
c_msg = 0;
c_showcerts = 0;
if (bio_err == NULL)
bio_err = BIO_new_fp(stderr, BIO_NOCLOSE);
if (!load_config(bio_err, NULL))
goto end;
cctx = SSL_CONF_CTX_new();
if (!cctx)
goto end;
SSL_CONF_CTX_set_flags(cctx, SSL_CONF_FLAG_CLIENT);
SSL_CONF_CTX_set_flags(cctx, SSL_CONF_FLAG_CMDLINE);
if (((cbuf = OPENSSL_malloc(BUFSIZZ)) == NULL) ||
((sbuf = OPENSSL_malloc(BUFSIZZ)) == NULL) ||
((mbuf = OPENSSL_malloc(BUFSIZZ)) == NULL)) {
BIO_printf(bio_err, "out of memory\n");
goto end;
}
verify_depth = 0;
verify_error = X509_V_OK;
#ifdef FIONBIO
c_nbio = 0;
#endif
argc--;
argv++;
while (argc >= 1) {
if (strcmp(*argv, "-host") == 0) {
if (--argc < 1)
goto bad;
host = *(++argv);
} else if (strcmp(*argv, "-port") == 0) {
if (--argc < 1)
goto bad;
port = atoi(*(++argv));
if (port == 0)
goto bad;
} else if (strcmp(*argv, "-connect") == 0) {
if (--argc < 1)
goto bad;
if (!extract_host_port(*(++argv), &host, NULL, &port))
goto bad;
} else if (strcmp(*argv, "-verify") == 0) {
verify = SSL_VERIFY_PEER;
if (--argc < 1)
goto bad;
verify_depth = atoi(*(++argv));
if (!c_quiet)
BIO_printf(bio_err, "verify depth is %d\n", verify_depth);
} else if (strcmp(*argv, "-cert") == 0) {
if (--argc < 1)
goto bad;
cert_file = *(++argv);
} else if (strcmp(*argv, "-CRL") == 0) {
if (--argc < 1)
goto bad;
crl_file = *(++argv);
} else if (strcmp(*argv, "-crl_download") == 0)
crl_download = 1;
else if (strcmp(*argv, "-sess_out") == 0) {
if (--argc < 1)
goto bad;
sess_out = *(++argv);
} else if (strcmp(*argv, "-sess_in") == 0) {
if (--argc < 1)
goto bad;
sess_in = *(++argv);
} else if (strcmp(*argv, "-certform") == 0) {
if (--argc < 1)
goto bad;
cert_format = str2fmt(*(++argv));
} else if (strcmp(*argv, "-CRLform") == 0) {
if (--argc < 1)
goto bad;
crl_format = str2fmt(*(++argv));
} else if (args_verify(&argv, &argc, &badarg, bio_err, &vpm)) {
if (badarg)
goto bad;
continue;
} else if (strcmp(*argv, "-verify_return_error") == 0)
verify_return_error = 1;
else if (strcmp(*argv, "-verify_quiet") == 0)
verify_quiet = 1;
else if (strcmp(*argv, "-brief") == 0) {
c_brief = 1;
verify_quiet = 1;
c_quiet = 1;
} else if (args_excert(&argv, &argc, &badarg, bio_err, &exc)) {
if (badarg)
goto bad;
continue;
} else if (args_ssl(&argv, &argc, cctx, &badarg, bio_err, &ssl_args,
&no_prot_opt)) {
if (badarg)
goto bad;
continue;
} else if (strcmp(*argv, "-prexit") == 0)
prexit = 1;
else if (strcmp(*argv, "-crlf") == 0)
crlf = 1;
else if (strcmp(*argv, "-quiet") == 0) {
c_quiet = 1;
c_ign_eof = 1;
} else if (strcmp(*argv, "-ign_eof") == 0)
c_ign_eof = 1;
else if (strcmp(*argv, "-no_ign_eof") == 0)
c_ign_eof = 0;
else if (strcmp(*argv, "-pause") == 0)
c_Pause = 1;
else if (strcmp(*argv, "-debug") == 0)
c_debug = 1;
#ifndef OPENSSL_NO_TLSEXT
else if (strcmp(*argv, "-tlsextdebug") == 0)
c_tlsextdebug = 1;
else if (strcmp(*argv, "-status") == 0)
c_status_req = 1;
#endif
#ifdef WATT32
else if (strcmp(*argv, "-wdebug") == 0)
dbug_init();
#endif
else if (strcmp(*argv, "-msg") == 0)
c_msg = 1;
else if (strcmp(*argv, "-msgfile") == 0) {
if (--argc < 1)
goto bad;
bio_c_msg = BIO_new_file(*(++argv), "w");
}
#ifndef OPENSSL_NO_SSL_TRACE
else if (strcmp(*argv, "-trace") == 0)
c_msg = 2;
#endif
else if (strcmp(*argv, "-showcerts") == 0)
c_showcerts = 1;
else if (strcmp(*argv, "-nbio_test") == 0)
nbio_test = 1;
else if (strcmp(*argv, "-state") == 0)
state = 1;
#ifndef OPENSSL_NO_PSK
else if (strcmp(*argv, "-psk_identity") == 0) {
if (--argc < 1)
goto bad;
psk_identity = *(++argv);
} else if (strcmp(*argv, "-psk") == 0) {
size_t j;
if (--argc < 1)
goto bad;
psk_key = *(++argv);
for (j = 0; j < strlen(psk_key); j++) {
if (isxdigit((unsigned char)psk_key[j]))
continue;
BIO_printf(bio_err, "Not a hex number '%s'\n", *argv);
goto bad;
}
}
#endif
#ifndef OPENSSL_NO_SRP
else if (strcmp(*argv, "-srpuser") == 0) {
if (--argc < 1)
goto bad;
srp_arg.srplogin = *(++argv);
meth = TLSv1_client_method();
} else if (strcmp(*argv, "-srppass") == 0) {
if (--argc < 1)
goto bad;
srppass = *(++argv);
meth = TLSv1_client_method();
} else if (strcmp(*argv, "-srp_strength") == 0) {
if (--argc < 1)
goto bad;
srp_arg.strength = atoi(*(++argv));
BIO_printf(bio_err, "SRP minimal length for N is %d\n",
srp_arg.strength);
meth = TLSv1_client_method();
} else if (strcmp(*argv, "-srp_lateuser") == 0) {
srp_lateuser = 1;
meth = TLSv1_client_method();
} else if (strcmp(*argv, "-srp_moregroups") == 0) {
srp_arg.amp = 1;
meth = TLSv1_client_method();
}
#endif
#ifndef OPENSSL_NO_SSL2
else if (strcmp(*argv, "-ssl2") == 0) {
meth = SSLv2_client_method();
prot_opt++;
}
#endif
#ifndef OPENSSL_NO_SSL3_METHOD
else if (strcmp(*argv, "-ssl3") == 0) {
meth = SSLv3_client_method();
prot_opt++;
}
#endif
#ifndef OPENSSL_NO_TLS1
else if (strcmp(*argv, "-tls1_2") == 0) {
meth = TLSv1_2_client_method();
prot_opt++;
} else if (strcmp(*argv, "-tls1_1") == 0) {
meth = TLSv1_1_client_method();
prot_opt++;
} else if (strcmp(*argv, "-tls1") == 0) {
meth = TLSv1_client_method();
prot_opt++;
}
#endif
#ifndef OPENSSL_NO_DTLS1
else if (strcmp(*argv, "-dtls") == 0) {
meth = DTLS_client_method();
socket_type = SOCK_DGRAM;
prot_opt++;
} else if (strcmp(*argv, "-dtls1") == 0) {
meth = DTLSv1_client_method();
socket_type = SOCK_DGRAM;
prot_opt++;
} else if (strcmp(*argv, "-dtls1_2") == 0) {
meth = DTLSv1_2_client_method();
socket_type = SOCK_DGRAM;
prot_opt++;
} else if (strcmp(*argv, "-timeout") == 0)
enable_timeouts = 1;
else if (strcmp(*argv, "-mtu") == 0) {
if (--argc < 1)
goto bad;
socket_mtu = atol(*(++argv));
}
#endif
else if (strcmp(*argv, "-fallback_scsv") == 0) {
fallback_scsv = 1;
} else if (strcmp(*argv, "-keyform") == 0) {
if (--argc < 1)
goto bad;
key_format = str2fmt(*(++argv));
} else if (strcmp(*argv, "-pass") == 0) {
if (--argc < 1)
goto bad;
passarg = *(++argv);
} else if (strcmp(*argv, "-cert_chain") == 0) {
if (--argc < 1)
goto bad;
chain_file = *(++argv);
} else if (strcmp(*argv, "-key") == 0) {
if (--argc < 1)
goto bad;
key_file = *(++argv);
} else if (strcmp(*argv, "-reconnect") == 0) {
reconnect = 5;
} else if (strcmp(*argv, "-CApath") == 0) {
if (--argc < 1)
goto bad;
CApath = *(++argv);
} else if (strcmp(*argv, "-chainCApath") == 0) {
if (--argc < 1)
goto bad;
chCApath = *(++argv);
} else if (strcmp(*argv, "-verifyCApath") == 0) {
if (--argc < 1)
goto bad;
vfyCApath = *(++argv);
} else if (strcmp(*argv, "-build_chain") == 0)
build_chain = 1;
else if (strcmp(*argv, "-CAfile") == 0) {
if (--argc < 1)
goto bad;
CAfile = *(++argv);
} else if (strcmp(*argv, "-chainCAfile") == 0) {
if (--argc < 1)
goto bad;
chCAfile = *(++argv);
} else if (strcmp(*argv, "-verifyCAfile") == 0) {
if (--argc < 1)
goto bad;
vfyCAfile = *(++argv);
}
#ifndef OPENSSL_NO_TLSEXT
# ifndef OPENSSL_NO_NEXTPROTONEG
else if (strcmp(*argv, "-nextprotoneg") == 0) {
if (--argc < 1)
goto bad;
next_proto_neg_in = *(++argv);
}
# endif
else if (strcmp(*argv, "-alpn") == 0) {
if (--argc < 1)
goto bad;
alpn_in = *(++argv);
} else if (strcmp(*argv, "-serverinfo") == 0) {
char *c;
int start = 0;
int len;
if (--argc < 1)
goto bad;
c = *(++argv);
serverinfo_types_count = 0;
len = strlen(c);
for (i = 0; i <= len; ++i) {
if (i == len || c[i] == ',') {
serverinfo_types[serverinfo_types_count]
= atoi(c + start);
serverinfo_types_count++;
start = i + 1;
}
if (serverinfo_types_count == MAX_SI_TYPES)
break;
}
}
#endif
#ifdef FIONBIO
else if (strcmp(*argv, "-nbio") == 0) {
c_nbio = 1;
}
#endif
else if (strcmp(*argv, "-starttls") == 0) {
if (--argc < 1)
goto bad;
++argv;
if (strcmp(*argv, "smtp") == 0)
starttls_proto = PROTO_SMTP;
else if (strcmp(*argv, "pop3") == 0)
starttls_proto = PROTO_POP3;
else if (strcmp(*argv, "imap") == 0)
starttls_proto = PROTO_IMAP;
else if (strcmp(*argv, "ftp") == 0)
starttls_proto = PROTO_FTP;
else if (strcmp(*argv, "xmpp") == 0)
starttls_proto = PROTO_XMPP;
else
goto bad;
}
#ifndef OPENSSL_NO_ENGINE
else if (strcmp(*argv, "-engine") == 0) {
if (--argc < 1)
goto bad;
engine_id = *(++argv);
} else if (strcmp(*argv, "-ssl_client_engine") == 0) {
if (--argc < 1)
goto bad;
ssl_client_engine_id = *(++argv);
}
#endif
else if (strcmp(*argv, "-rand") == 0) {
if (--argc < 1)
goto bad;
inrand = *(++argv);
}
#ifndef OPENSSL_NO_TLSEXT
else if (strcmp(*argv, "-servername") == 0) {
if (--argc < 1)
goto bad;
servername = *(++argv);
/* meth=TLSv1_client_method(); */
}
#endif
#ifndef OPENSSL_NO_JPAKE
else if (strcmp(*argv, "-jpake") == 0) {
if (--argc < 1)
goto bad;
jpake_secret = *++argv;
}
#endif
#ifndef OPENSSL_NO_SRTP
else if (strcmp(*argv, "-use_srtp") == 0) {
if (--argc < 1)
goto bad;
srtp_profiles = *(++argv);
}
#endif
else if (strcmp(*argv, "-keymatexport") == 0) {
if (--argc < 1)
goto bad;
keymatexportlabel = *(++argv);
} else if (strcmp(*argv, "-keymatexportlen") == 0) {
if (--argc < 1)
goto bad;
keymatexportlen = atoi(*(++argv));
if (keymatexportlen == 0)
goto bad;
} else {
BIO_printf(bio_err, "unknown option %s\n", *argv);
badop = 1;
break;
}
argc--;
argv++;
}
if (badop) {
bad:
sc_usage();
goto end;
}
#if !defined(OPENSSL_NO_JPAKE) && !defined(OPENSSL_NO_PSK)
if (jpake_secret) {
if (psk_key) {
BIO_printf(bio_err, "Can't use JPAKE and PSK together\n");
goto end;
}
psk_identity = "JPAKE";
}
#endif
if (prot_opt > 1) {
BIO_printf(bio_err, "Cannot supply multiple protocol flags\n");
goto end;
}
if (prot_opt == 1 && no_prot_opt) {
BIO_printf(bio_err, "Cannot supply both a protocol flag and "
"\"-no_<prot>\"\n");
goto end;
}
OpenSSL_add_ssl_algorithms();
SSL_load_error_strings();
#if !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_NEXTPROTONEG)
next_proto.status = -1;
if (next_proto_neg_in) {
next_proto.data =
next_protos_parse(&next_proto.len, next_proto_neg_in);
if (next_proto.data == NULL) {
BIO_printf(bio_err, "Error parsing -nextprotoneg argument\n");
goto end;
}
} else
next_proto.data = NULL;
#endif
e = setup_engine(bio_err, engine_id, 1);
#ifndef OPENSSL_NO_ENGINE
if (ssl_client_engine_id) {
ssl_client_engine = ENGINE_by_id(ssl_client_engine_id);
if (!ssl_client_engine) {
BIO_printf(bio_err, "Error getting client auth engine\n");
goto end;
}
}
#endif
if (!app_passwd(bio_err, passarg, NULL, &pass, NULL)) {
BIO_printf(bio_err, "Error getting password\n");
goto end;
}
if (key_file == NULL)
key_file = cert_file;
if (key_file) {
key = load_key(bio_err, key_file, key_format, 0, pass, e,
"client certificate private key file");
if (!key) {
ERR_print_errors(bio_err);
goto end;
}
}
if (cert_file) {
cert = load_cert(bio_err, cert_file, cert_format,
NULL, e, "client certificate file");
if (!cert) {
ERR_print_errors(bio_err);
goto end;
}
}
if (chain_file) {
chain = load_certs(bio_err, chain_file, FORMAT_PEM,
NULL, e, "client certificate chain");
if (!chain)
goto end;
}
if (crl_file) {
X509_CRL *crl;
crl = load_crl(crl_file, crl_format);
if (!crl) {
BIO_puts(bio_err, "Error loading CRL\n");
ERR_print_errors(bio_err);
goto end;
}
crls = sk_X509_CRL_new_null();
if (!crls || !sk_X509_CRL_push(crls, crl)) {
BIO_puts(bio_err, "Error adding CRL\n");
ERR_print_errors(bio_err);
X509_CRL_free(crl);
goto end;
}
}
if (!load_excert(&exc, bio_err))
goto end;
if (!app_RAND_load_file(NULL, bio_err, 1) && inrand == NULL
&& !RAND_status()) {
BIO_printf(bio_err,
"warning, not much extra random data, consider using the -rand option\n");
}
if (inrand != NULL)
BIO_printf(bio_err, "%ld semi-random bytes loaded\n",
app_RAND_load_files(inrand));
if (bio_c_out == NULL) {
if (c_quiet && !c_debug) {
bio_c_out = BIO_new(BIO_s_null());
if (c_msg && !bio_c_msg)
bio_c_msg = BIO_new_fp(stdout, BIO_NOCLOSE);
} else {
if (bio_c_out == NULL)
bio_c_out = BIO_new_fp(stdout, BIO_NOCLOSE);
}
}
#ifndef OPENSSL_NO_SRP
if (!app_passwd(bio_err, srppass, NULL, &srp_arg.srppassin, NULL)) {
BIO_printf(bio_err, "Error getting password\n");
goto end;
}
#endif
ctx = SSL_CTX_new(meth);
if (ctx == NULL) {
ERR_print_errors(bio_err);
goto end;
}
if (vpm)
SSL_CTX_set1_param(ctx, vpm);
if (!args_ssl_call(ctx, bio_err, cctx, ssl_args, 1, no_jpake)) {
ERR_print_errors(bio_err);
goto end;
}
if (!ssl_load_stores(ctx, vfyCApath, vfyCAfile, chCApath, chCAfile,
crls, crl_download)) {
BIO_printf(bio_err, "Error loading store locations\n");
ERR_print_errors(bio_err);
goto end;
}
#ifndef OPENSSL_NO_ENGINE
if (ssl_client_engine) {
if (!SSL_CTX_set_client_cert_engine(ctx, ssl_client_engine)) {
BIO_puts(bio_err, "Error setting client auth engine\n");
ERR_print_errors(bio_err);
ENGINE_free(ssl_client_engine);
goto end;
}
ENGINE_free(ssl_client_engine);
}
#endif
#ifndef OPENSSL_NO_PSK
# ifdef OPENSSL_NO_JPAKE
if (psk_key != NULL)
# else
if (psk_key != NULL || jpake_secret)
# endif
{
if (c_debug)
BIO_printf(bio_c_out,
"PSK key given or JPAKE in use, setting client callback\n");
SSL_CTX_set_psk_client_callback(ctx, psk_client_cb);
}
#endif
#ifndef OPENSSL_NO_SRTP
if (srtp_profiles != NULL)
SSL_CTX_set_tlsext_use_srtp(ctx, srtp_profiles);
#endif
if (exc)
ssl_ctx_set_excert(ctx, exc);
#if !defined(OPENSSL_NO_TLSEXT)
# if !defined(OPENSSL_NO_NEXTPROTONEG)
if (next_proto.data)
SSL_CTX_set_next_proto_select_cb(ctx, next_proto_cb, &next_proto);
# endif
if (alpn_in) {
unsigned short alpn_len;
unsigned char *alpn = next_protos_parse(&alpn_len, alpn_in);
if (alpn == NULL) {
BIO_printf(bio_err, "Error parsing -alpn argument\n");
goto end;
}
SSL_CTX_set_alpn_protos(ctx, alpn, alpn_len);
OPENSSL_free(alpn);
}
#endif
#ifndef OPENSSL_NO_TLSEXT
for (i = 0; i < serverinfo_types_count; i++) {
SSL_CTX_add_client_custom_ext(ctx,
serverinfo_types[i],
NULL, NULL, NULL,
serverinfo_cli_parse_cb, NULL);
}
#endif
if (state)
SSL_CTX_set_info_callback(ctx, apps_ssl_info_callback);
#if 0
else
SSL_CTX_set_cipher_list(ctx, getenv("SSL_CIPHER"));
#endif
SSL_CTX_set_verify(ctx, verify, verify_callback);
if ((CAfile || CApath)
&& !SSL_CTX_load_verify_locations(ctx, CAfile, CApath)) {
ERR_print_errors(bio_err);
}
if (!SSL_CTX_set_default_verify_paths(ctx)) {
ERR_print_errors(bio_err);
}
ssl_ctx_add_crls(ctx, crls, crl_download);
if (!set_cert_key_stuff(ctx, cert, key, chain, build_chain))
goto end;
#ifndef OPENSSL_NO_TLSEXT
if (servername != NULL) {
tlsextcbp.biodebug = bio_err;
SSL_CTX_set_tlsext_servername_callback(ctx, ssl_servername_cb);
SSL_CTX_set_tlsext_servername_arg(ctx, &tlsextcbp);
}
# ifndef OPENSSL_NO_SRP
if (srp_arg.srplogin) {
if (!srp_lateuser && !SSL_CTX_set_srp_username(ctx, srp_arg.srplogin)) {
BIO_printf(bio_err, "Unable to set SRP username\n");
goto end;
}
srp_arg.msg = c_msg;
srp_arg.debug = c_debug;
SSL_CTX_set_srp_cb_arg(ctx, &srp_arg);
SSL_CTX_set_srp_client_pwd_callback(ctx, ssl_give_srp_client_pwd_cb);
SSL_CTX_set_srp_strength(ctx, srp_arg.strength);
if (c_msg || c_debug || srp_arg.amp == 0)
SSL_CTX_set_srp_verify_param_callback(ctx,
ssl_srp_verify_param_cb);
}
# endif
#endif
con = SSL_new(ctx);
if (sess_in) {
SSL_SESSION *sess;
BIO *stmp = BIO_new_file(sess_in, "r");
if (!stmp) {
BIO_printf(bio_err, "Can't open session file %s\n", sess_in);
ERR_print_errors(bio_err);
goto end;
}
sess = PEM_read_bio_SSL_SESSION(stmp, NULL, 0, NULL);
BIO_free(stmp);
if (!sess) {
BIO_printf(bio_err, "Can't open session file %s\n", sess_in);
ERR_print_errors(bio_err);
goto end;
}
SSL_set_session(con, sess);
SSL_SESSION_free(sess);
}
if (fallback_scsv)
SSL_set_mode(con, SSL_MODE_SEND_FALLBACK_SCSV);
#ifndef OPENSSL_NO_TLSEXT
if (servername != NULL) {
if (!SSL_set_tlsext_host_name(con, servername)) {
BIO_printf(bio_err, "Unable to set TLS servername extension.\n");
ERR_print_errors(bio_err);
goto end;
}
}
#endif
#ifndef OPENSSL_NO_KRB5
if (con && (kctx = kssl_ctx_new()) != NULL) {
SSL_set0_kssl_ctx(con, kctx);
kssl_ctx_setstring(kctx, KSSL_SERVER, host);
}
#endif /* OPENSSL_NO_KRB5 */
/* SSL_set_cipher_list(con,"RC4-MD5"); */
#if 0
# ifdef TLSEXT_TYPE_opaque_prf_input
SSL_set_tlsext_opaque_prf_input(con, "Test client", 11);
# endif
#endif
re_start:
if (init_client(&s, host, port, socket_type) == 0) {
BIO_printf(bio_err, "connect:errno=%d\n", get_last_socket_error());
SHUTDOWN(s);
goto end;
}
BIO_printf(bio_c_out, "CONNECTED(%08X)\n", s);
#ifdef FIONBIO
if (c_nbio) {
unsigned long l = 1;
BIO_printf(bio_c_out, "turning on non blocking io\n");
if (BIO_socket_ioctl(s, FIONBIO, &l) < 0) {
ERR_print_errors(bio_err);
goto end;
}
}
#endif
if (c_Pause & 0x01)
SSL_set_debug(con, 1);
if (socket_type == SOCK_DGRAM) {
sbio = BIO_new_dgram(s, BIO_NOCLOSE);
if (getsockname(s, &peer, (void *)&peerlen) < 0) {
BIO_printf(bio_err, "getsockname:errno=%d\n",
get_last_socket_error());
SHUTDOWN(s);
goto end;
}
(void)BIO_ctrl_set_connected(sbio, 1, &peer);
if (enable_timeouts) {
timeout.tv_sec = 0;
timeout.tv_usec = DGRAM_RCV_TIMEOUT;
BIO_ctrl(sbio, BIO_CTRL_DGRAM_SET_RECV_TIMEOUT, 0, &timeout);
timeout.tv_sec = 0;
timeout.tv_usec = DGRAM_SND_TIMEOUT;
BIO_ctrl(sbio, BIO_CTRL_DGRAM_SET_SEND_TIMEOUT, 0, &timeout);
}
if (socket_mtu) {
if (socket_mtu < DTLS_get_link_min_mtu(con)) {
BIO_printf(bio_err, "MTU too small. Must be at least %ld\n",
DTLS_get_link_min_mtu(con));
BIO_free(sbio);
goto shut;
}
SSL_set_options(con, SSL_OP_NO_QUERY_MTU);
if (!DTLS_set_link_mtu(con, socket_mtu)) {
BIO_printf(bio_err, "Failed to set MTU\n");
BIO_free(sbio);
goto shut;
}
} else
/* want to do MTU discovery */
BIO_ctrl(sbio, BIO_CTRL_DGRAM_MTU_DISCOVER, 0, NULL);
} else
sbio = BIO_new_socket(s, BIO_NOCLOSE);
if (nbio_test) {
BIO *test;
test = BIO_new(BIO_f_nbio_test());
sbio = BIO_push(test, sbio);
}
if (c_debug) {
SSL_set_debug(con, 1);
BIO_set_callback(sbio, bio_dump_callback);
BIO_set_callback_arg(sbio, (char *)bio_c_out);
}
if (c_msg) {
#ifndef OPENSSL_NO_SSL_TRACE
if (c_msg == 2)
SSL_set_msg_callback(con, SSL_trace);
else
#endif
SSL_set_msg_callback(con, msg_cb);
SSL_set_msg_callback_arg(con, bio_c_msg ? bio_c_msg : bio_c_out);
}
#ifndef OPENSSL_NO_TLSEXT
if (c_tlsextdebug) {
SSL_set_tlsext_debug_callback(con, tlsext_cb);
SSL_set_tlsext_debug_arg(con, bio_c_out);
}
if (c_status_req) {
SSL_set_tlsext_status_type(con, TLSEXT_STATUSTYPE_ocsp);
SSL_CTX_set_tlsext_status_cb(ctx, ocsp_resp_cb);
SSL_CTX_set_tlsext_status_arg(ctx, bio_c_out);
# if 0
{
STACK_OF(OCSP_RESPID) *ids = sk_OCSP_RESPID_new_null();
OCSP_RESPID *id = OCSP_RESPID_new();
id->value.byKey = ASN1_OCTET_STRING_new();
id->type = V_OCSP_RESPID_KEY;
ASN1_STRING_set(id->value.byKey, "Hello World", -1);
sk_OCSP_RESPID_push(ids, id);
SSL_set_tlsext_status_ids(con, ids);
}
# endif
}
#endif
#ifndef OPENSSL_NO_JPAKE
if (jpake_secret)
jpake_client_auth(bio_c_out, sbio, jpake_secret);
#endif
SSL_set_bio(con, sbio, sbio);
SSL_set_connect_state(con);
/* ok, lets connect */
if (fileno_stdin() > SSL_get_fd(con))
width = fileno_stdin() + 1;
else
width = SSL_get_fd(con) + 1;
read_tty = 1;
write_tty = 0;
tty_on = 0;
read_ssl = 1;
write_ssl = 1;
cbuf_len = 0;
cbuf_off = 0;
sbuf_len = 0;
sbuf_off = 0;
/* This is an ugly hack that does a lot of assumptions */
/*
* We do have to handle multi-line responses which may come in a single
* packet or not. We therefore have to use BIO_gets() which does need a
* buffering BIO. So during the initial chitchat we do push a buffering
* BIO into the chain that is removed again later on to not disturb the
* rest of the s_client operation.
*/
if (starttls_proto == PROTO_SMTP) {
int foundit = 0;
BIO *fbio = BIO_new(BIO_f_buffer());
BIO_push(fbio, sbio);
/* wait for multi-line response to end from SMTP */
do {
mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ);
}
while (mbuf_len > 3 && mbuf[3] == '-');
/* STARTTLS command requires EHLO... */
BIO_printf(fbio, "EHLO openssl.client.net\r\n");
(void)BIO_flush(fbio);
/* wait for multi-line response to end EHLO SMTP response */
do {
mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ);
if (strstr(mbuf, "STARTTLS"))
foundit = 1;
}
while (mbuf_len > 3 && mbuf[3] == '-');
(void)BIO_flush(fbio);
BIO_pop(fbio);
BIO_free(fbio);
if (!foundit)
BIO_printf(bio_err,
"didn't found starttls in server response,"
" try anyway...\n");
BIO_printf(sbio, "STARTTLS\r\n");
BIO_read(sbio, sbuf, BUFSIZZ);
} else if (starttls_proto == PROTO_POP3) {
BIO_read(sbio, mbuf, BUFSIZZ);
BIO_printf(sbio, "STLS\r\n");
BIO_read(sbio, sbuf, BUFSIZZ);
} else if (starttls_proto == PROTO_IMAP) {
int foundit = 0;
BIO *fbio = BIO_new(BIO_f_buffer());
BIO_push(fbio, sbio);
BIO_gets(fbio, mbuf, BUFSIZZ);
/* STARTTLS command requires CAPABILITY... */
BIO_printf(fbio, ". CAPABILITY\r\n");
(void)BIO_flush(fbio);
/* wait for multi-line CAPABILITY response */
do {
mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ);
if (strstr(mbuf, "STARTTLS"))
foundit = 1;
}
while (mbuf_len > 3 && mbuf[0] != '.');
(void)BIO_flush(fbio);
BIO_pop(fbio);
BIO_free(fbio);
if (!foundit)
BIO_printf(bio_err,
"didn't found STARTTLS in server response,"
" try anyway...\n");
BIO_printf(sbio, ". STARTTLS\r\n");
BIO_read(sbio, sbuf, BUFSIZZ);
} else if (starttls_proto == PROTO_FTP) {
BIO *fbio = BIO_new(BIO_f_buffer());
BIO_push(fbio, sbio);
/* wait for multi-line response to end from FTP */
do {
mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ);
}
while (mbuf_len > 3 && mbuf[3] == '-');
(void)BIO_flush(fbio);
BIO_pop(fbio);
BIO_free(fbio);
BIO_printf(sbio, "AUTH TLS\r\n");
BIO_read(sbio, sbuf, BUFSIZZ);
}
if (starttls_proto == PROTO_XMPP) {
int seen = 0;
BIO_printf(sbio, "<stream:stream "
"xmlns:stream='http://etherx.jabber.org/streams' "
"xmlns='jabber:client' to='%s' version='1.0'>", host);
seen = BIO_read(sbio, mbuf, BUFSIZZ);
mbuf[seen] = 0;
while (!strstr
(mbuf, "<starttls xmlns='urn:ietf:params:xml:ns:xmpp-tls'")) {
if (strstr(mbuf, "/stream:features>"))
goto shut;
seen = BIO_read(sbio, mbuf, BUFSIZZ);
if (seen <= 0)
goto shut;
mbuf[seen] = 0;
}
BIO_printf(sbio,
"<starttls xmlns='urn:ietf:params:xml:ns:xmpp-tls'/>");
seen = BIO_read(sbio, sbuf, BUFSIZZ);
sbuf[seen] = 0;
if (!strstr(sbuf, "<proceed"))
goto shut;
mbuf[0] = 0;
}
for (;;) {
FD_ZERO(&readfds);
FD_ZERO(&writefds);
if ((SSL_version(con) == DTLS1_VERSION) &&
DTLSv1_get_timeout(con, &timeout))
timeoutp = &timeout;
else
timeoutp = NULL;
if (SSL_in_init(con) && !SSL_total_renegotiations(con)) {
in_init = 1;
tty_on = 0;
} else {
tty_on = 1;
if (in_init) {
in_init = 0;
#if 0 /* This test doesn't really work as intended
* (needs to be fixed) */
# ifndef OPENSSL_NO_TLSEXT
if (servername != NULL && !SSL_session_reused(con)) {
BIO_printf(bio_c_out,
"Server did %sacknowledge servername extension.\n",
tlsextcbp.ack ? "" : "not ");
}
# endif
#endif
if (sess_out) {
BIO *stmp = BIO_new_file(sess_out, "w");
if (stmp) {
PEM_write_bio_SSL_SESSION(stmp, SSL_get_session(con));
BIO_free(stmp);
} else
BIO_printf(bio_err, "Error writing session file %s\n",
sess_out);
}
if (c_brief) {
BIO_puts(bio_err, "CONNECTION ESTABLISHED\n");
print_ssl_summary(bio_err, con);
}
print_stuff(bio_c_out, con, full_log);
if (full_log > 0)
full_log--;
if (starttls_proto) {
BIO_printf(bio_err, "%s", mbuf);
/* We don't need to know any more */
starttls_proto = PROTO_OFF;
}
if (reconnect) {
reconnect--;
BIO_printf(bio_c_out,
"drop connection and then reconnect\n");
SSL_shutdown(con);
SSL_set_connect_state(con);
SHUTDOWN(SSL_get_fd(con));
goto re_start;
}
}
}
ssl_pending = read_ssl && SSL_pending(con);
if (!ssl_pending) {
#if !defined(OPENSSL_SYS_WINDOWS) && !defined(OPENSSL_SYS_MSDOS) && !defined(OPENSSL_SYS_NETWARE) && !defined (OPENSSL_SYS_BEOS_R5)
if (tty_on) {
if (read_tty)
openssl_fdset(fileno_stdin(), &readfds);
#if !defined(OPENSSL_SYS_VMS)
if (write_tty)
openssl_fdset(fileno_stdout(), &writefds);
#endif
}
if (read_ssl)
openssl_fdset(SSL_get_fd(con), &readfds);
if (write_ssl)
openssl_fdset(SSL_get_fd(con), &writefds);
#else
if (!tty_on || !write_tty) {
if (read_ssl)
openssl_fdset(SSL_get_fd(con), &readfds);
if (write_ssl)
openssl_fdset(SSL_get_fd(con), &writefds);
}
#endif
/*- printf("mode tty(%d %d%d) ssl(%d%d)\n",
tty_on,read_tty,write_tty,read_ssl,write_ssl);*/
/*
* Note: under VMS with SOCKETSHR the second parameter is
* currently of type (int *) whereas under other systems it is
* (void *) if you don't have a cast it will choke the compiler:
* if you do have a cast then you can either go for (int *) or
* (void *).
*/
#if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS)
/*
* Under Windows/DOS we make the assumption that we can always
* write to the tty: therefore if we need to write to the tty we
* just fall through. Otherwise we timeout the select every
* second and see if there are any keypresses. Note: this is a
* hack, in a proper Windows application we wouldn't do this.
*/
i = 0;
if (!write_tty) {
if (read_tty) {
tv.tv_sec = 1;
tv.tv_usec = 0;
i = select(width, (void *)&readfds, (void *)&writefds,
NULL, &tv);
# if defined(OPENSSL_SYS_WINCE) || defined(OPENSSL_SYS_MSDOS)
if (!i && (!_kbhit() || !read_tty))
continue;
# else
if (!i && (!((_kbhit())
|| (WAIT_OBJECT_0 ==
WaitForSingleObject(GetStdHandle
(STD_INPUT_HANDLE),
0)))
|| !read_tty))
continue;
# endif
} else
i = select(width, (void *)&readfds, (void *)&writefds,
NULL, timeoutp);
}
#elif defined(OPENSSL_SYS_NETWARE)
if (!write_tty) {
if (read_tty) {
tv.tv_sec = 1;
tv.tv_usec = 0;
i = select(width, (void *)&readfds, (void *)&writefds,
NULL, &tv);
} else
i = select(width, (void *)&readfds, (void *)&writefds,
NULL, timeoutp);
}
#elif defined(OPENSSL_SYS_BEOS_R5)
/* Under BeOS-R5 the situation is similar to DOS */
i = 0;
stdin_set = 0;
(void)fcntl(fileno_stdin(), F_SETFL, O_NONBLOCK);
if (!write_tty) {
if (read_tty) {
tv.tv_sec = 1;
tv.tv_usec = 0;
i = select(width, (void *)&readfds, (void *)&writefds,
NULL, &tv);
if (read(fileno_stdin(), sbuf, 0) >= 0)
stdin_set = 1;
if (!i && (stdin_set != 1 || !read_tty))
continue;
} else
i = select(width, (void *)&readfds, (void *)&writefds,
NULL, timeoutp);
}
(void)fcntl(fileno_stdin(), F_SETFL, 0);
#else
i = select(width, (void *)&readfds, (void *)&writefds,
NULL, timeoutp);
#endif
if (i < 0) {
BIO_printf(bio_err, "bad select %d\n",
get_last_socket_error());
goto shut;
/* goto end; */
}
}
if ((SSL_version(con) == DTLS1_VERSION)
&& DTLSv1_handle_timeout(con) > 0) {
BIO_printf(bio_err, "TIMEOUT occured\n");
}
if (!ssl_pending && FD_ISSET(SSL_get_fd(con), &writefds)) {
k = SSL_write(con, &(cbuf[cbuf_off]), (unsigned int)cbuf_len);
switch (SSL_get_error(con, k)) {
case SSL_ERROR_NONE:
cbuf_off += k;
cbuf_len -= k;
if (k <= 0)
goto end;
/* we have done a write(con,NULL,0); */
if (cbuf_len <= 0) {
read_tty = 1;
write_ssl = 0;
} else { /* if (cbuf_len > 0) */
read_tty = 0;
write_ssl = 1;
}
break;
case SSL_ERROR_WANT_WRITE:
BIO_printf(bio_c_out, "write W BLOCK\n");
write_ssl = 1;
read_tty = 0;
break;
case SSL_ERROR_WANT_READ:
BIO_printf(bio_c_out, "write R BLOCK\n");
write_tty = 0;
read_ssl = 1;
write_ssl = 0;
break;
case SSL_ERROR_WANT_X509_LOOKUP:
BIO_printf(bio_c_out, "write X BLOCK\n");
break;
case SSL_ERROR_ZERO_RETURN:
if (cbuf_len != 0) {
BIO_printf(bio_c_out, "shutdown\n");
ret = 0;
goto shut;
} else {
read_tty = 1;
write_ssl = 0;
break;
}
case SSL_ERROR_SYSCALL:
if ((k != 0) || (cbuf_len != 0)) {
BIO_printf(bio_err, "write:errno=%d\n",
get_last_socket_error());
goto shut;
} else {
read_tty = 1;
write_ssl = 0;
}
break;
case SSL_ERROR_SSL:
ERR_print_errors(bio_err);
goto shut;
}
}
#if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS) || defined(OPENSSL_SYS_NETWARE) || defined(OPENSSL_SYS_BEOS_R5) || defined(OPENSSL_SYS_VMS)
/* Assume Windows/DOS/BeOS can always write */
else if (!ssl_pending && write_tty)
#else
else if (!ssl_pending && FD_ISSET(fileno_stdout(), &writefds))
#endif
{
#ifdef CHARSET_EBCDIC
ascii2ebcdic(&(sbuf[sbuf_off]), &(sbuf[sbuf_off]), sbuf_len);
#endif
i = raw_write_stdout(&(sbuf[sbuf_off]), sbuf_len);
if (i <= 0) {
BIO_printf(bio_c_out, "DONE\n");
ret = 0;
goto shut;
/* goto end; */
}
sbuf_len -= i;;
sbuf_off += i;
if (sbuf_len <= 0) {
read_ssl = 1;
write_tty = 0;
}
} else if (ssl_pending || FD_ISSET(SSL_get_fd(con), &readfds)) {
#ifdef RENEG
{
static int iiii;
if (++iiii == 52) {
SSL_renegotiate(con);
iiii = 0;
}
}
#endif
#if 1
k = SSL_read(con, sbuf, 1024 /* BUFSIZZ */ );
#else
/* Demo for pending and peek :-) */
k = SSL_read(con, sbuf, 16);
{
char zbuf[10240];
printf("read=%d pending=%d peek=%d\n", k, SSL_pending(con),
SSL_peek(con, zbuf, 10240));
}
#endif
switch (SSL_get_error(con, k)) {
case SSL_ERROR_NONE:
if (k <= 0)
goto end;
sbuf_off = 0;
sbuf_len = k;
read_ssl = 0;
write_tty = 1;
break;
case SSL_ERROR_WANT_WRITE:
BIO_printf(bio_c_out, "read W BLOCK\n");
write_ssl = 1;
read_tty = 0;
break;
case SSL_ERROR_WANT_READ:
BIO_printf(bio_c_out, "read R BLOCK\n");
write_tty = 0;
read_ssl = 1;
if ((read_tty == 0) && (write_ssl == 0))
write_ssl = 1;
break;
case SSL_ERROR_WANT_X509_LOOKUP:
BIO_printf(bio_c_out, "read X BLOCK\n");
break;
case SSL_ERROR_SYSCALL:
ret = get_last_socket_error();
if (c_brief)
BIO_puts(bio_err, "CONNECTION CLOSED BY SERVER\n");
else
BIO_printf(bio_err, "read:errno=%d\n", ret);
goto shut;
case SSL_ERROR_ZERO_RETURN:
BIO_printf(bio_c_out, "closed\n");
ret = 0;
goto shut;
case SSL_ERROR_SSL:
ERR_print_errors(bio_err);
goto shut;
/* break; */
}
}
#if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS)
# if defined(OPENSSL_SYS_WINCE) || defined(OPENSSL_SYS_MSDOS)
else if (_kbhit())
# else
else if ((_kbhit())
|| (WAIT_OBJECT_0 ==
WaitForSingleObject(GetStdHandle(STD_INPUT_HANDLE), 0)))
# endif
#elif defined (OPENSSL_SYS_NETWARE)
else if (_kbhit())
#elif defined(OPENSSL_SYS_BEOS_R5)
else if (stdin_set)
#else
else if (FD_ISSET(fileno_stdin(), &readfds))
#endif
{
if (crlf) {
int j, lf_num;
i = raw_read_stdin(cbuf, BUFSIZZ / 2);
lf_num = 0;
/* both loops are skipped when i <= 0 */
for (j = 0; j < i; j++)
if (cbuf[j] == '\n')
lf_num++;
for (j = i - 1; j >= 0; j--) {
cbuf[j + lf_num] = cbuf[j];
if (cbuf[j] == '\n') {
lf_num--;
i++;
cbuf[j + lf_num] = '\r';
}
}
assert(lf_num == 0);
} else
i = raw_read_stdin(cbuf, BUFSIZZ);
if ((!c_ign_eof) && ((i <= 0) || (cbuf[0] == 'Q'))) {
BIO_printf(bio_err, "DONE\n");
ret = 0;
goto shut;
}
if ((!c_ign_eof) && (cbuf[0] == 'R')) {
BIO_printf(bio_err, "RENEGOTIATING\n");
SSL_renegotiate(con);
cbuf_len = 0;
}
#ifndef OPENSSL_NO_HEARTBEATS
else if ((!c_ign_eof) && (cbuf[0] == 'B')) {
BIO_printf(bio_err, "HEARTBEATING\n");
SSL_heartbeat(con);
cbuf_len = 0;
}
#endif
else {
cbuf_len = i;
cbuf_off = 0;
#ifdef CHARSET_EBCDIC
ebcdic2ascii(cbuf, cbuf, i);
#endif
}
write_ssl = 1;
read_tty = 0;
}
}
ret = 0;
shut:
if (in_init)
print_stuff(bio_c_out, con, full_log);
SSL_shutdown(con);
SHUTDOWN(SSL_get_fd(con));
end:
if (con != NULL) {
if (prexit != 0)
print_stuff(bio_c_out, con, 1);
SSL_free(con);
}
#if !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_NEXTPROTONEG)
if (next_proto.data)
OPENSSL_free(next_proto.data);
#endif
if (ctx != NULL)
SSL_CTX_free(ctx);
if (cert)
X509_free(cert);
if (crls)
sk_X509_CRL_pop_free(crls, X509_CRL_free);
if (key)
EVP_PKEY_free(key);
if (chain)
sk_X509_pop_free(chain, X509_free);
if (pass)
OPENSSL_free(pass);
#ifndef OPENSSL_NO_SRP
OPENSSL_free(srp_arg.srppassin);
#endif
if (vpm)
X509_VERIFY_PARAM_free(vpm);
ssl_excert_free(exc);
if (ssl_args)
sk_OPENSSL_STRING_free(ssl_args);
if (cctx)
SSL_CONF_CTX_free(cctx);
#ifndef OPENSSL_NO_JPAKE
if (jpake_secret && psk_key)
OPENSSL_free(psk_key);
#endif
if (cbuf != NULL) {
OPENSSL_cleanse(cbuf, BUFSIZZ);
OPENSSL_free(cbuf);
}
if (sbuf != NULL) {
OPENSSL_cleanse(sbuf, BUFSIZZ);
OPENSSL_free(sbuf);
}
if (mbuf != NULL) {
OPENSSL_cleanse(mbuf, BUFSIZZ);
OPENSSL_free(mbuf);
}
release_engine(e);
if (bio_c_out != NULL) {
BIO_free(bio_c_out);
bio_c_out = NULL;
}
if (bio_c_msg != NULL) {
BIO_free(bio_c_msg);
bio_c_msg = NULL;
}
SSL_COMP_free_compression_methods();
apps_shutdown();
OPENSSL_EXIT(ret);
}
static void print_stuff(BIO *bio, SSL *s, int full)
{
X509 *peer = NULL;
char *p;
static const char *space = " ";
char buf[BUFSIZ];
STACK_OF(X509) *sk;
STACK_OF(X509_NAME) *sk2;
const SSL_CIPHER *c;
X509_NAME *xn;
int j, i;
#ifndef OPENSSL_NO_COMP
const COMP_METHOD *comp, *expansion;
#endif
unsigned char *exportedkeymat;
if (full) {
int got_a_chain = 0;
sk = SSL_get_peer_cert_chain(s);
if (sk != NULL) {
got_a_chain = 1; /* we don't have it for SSL2 (yet) */
BIO_printf(bio, "---\nCertificate chain\n");
for (i = 0; i < sk_X509_num(sk); i++) {
X509_NAME_oneline(X509_get_subject_name(sk_X509_value(sk, i)),
- buf, sizeof buf);
+ buf, sizeof(buf));
BIO_printf(bio, "%2d s:%s\n", i, buf);
X509_NAME_oneline(X509_get_issuer_name(sk_X509_value(sk, i)),
- buf, sizeof buf);
+ buf, sizeof(buf));
BIO_printf(bio, " i:%s\n", buf);
if (c_showcerts)
PEM_write_bio_X509(bio, sk_X509_value(sk, i));
}
}
BIO_printf(bio, "---\n");
peer = SSL_get_peer_certificate(s);
if (peer != NULL) {
BIO_printf(bio, "Server certificate\n");
/* Redundant if we showed the whole chain */
if (!(c_showcerts && got_a_chain))
PEM_write_bio_X509(bio, peer);
- X509_NAME_oneline(X509_get_subject_name(peer), buf, sizeof buf);
+ X509_NAME_oneline(X509_get_subject_name(peer), buf, sizeof(buf));
BIO_printf(bio, "subject=%s\n", buf);
- X509_NAME_oneline(X509_get_issuer_name(peer), buf, sizeof buf);
+ X509_NAME_oneline(X509_get_issuer_name(peer), buf, sizeof(buf));
BIO_printf(bio, "issuer=%s\n", buf);
} else
BIO_printf(bio, "no peer certificate available\n");
sk2 = SSL_get_client_CA_list(s);
if ((sk2 != NULL) && (sk_X509_NAME_num(sk2) > 0)) {
BIO_printf(bio, "---\nAcceptable client certificate CA names\n");
for (i = 0; i < sk_X509_NAME_num(sk2); i++) {
xn = sk_X509_NAME_value(sk2, i);
X509_NAME_oneline(xn, buf, sizeof(buf));
BIO_write(bio, buf, strlen(buf));
BIO_write(bio, "\n", 1);
}
} else {
BIO_printf(bio, "---\nNo client certificate CA names sent\n");
}
- p = SSL_get_shared_ciphers(s, buf, sizeof buf);
+ p = SSL_get_shared_ciphers(s, buf, sizeof(buf));
if (p != NULL) {
/*
* This works only for SSL 2. In later protocol versions, the
* client does not know what other ciphers (in addition to the
* one to be used in the current connection) the server supports.
*/
BIO_printf(bio,
"---\nCiphers common between both SSL endpoints:\n");
j = i = 0;
while (*p) {
if (*p == ':') {
BIO_write(bio, space, 15 - j % 25);
i++;
j = 0;
BIO_write(bio, ((i % 3) ? " " : "\n"), 1);
} else {
BIO_write(bio, p, 1);
j++;
}
p++;
}
BIO_write(bio, "\n", 1);
}
ssl_print_sigalgs(bio, s);
ssl_print_tmp_key(bio, s);
BIO_printf(bio,
"---\nSSL handshake has read %ld bytes and written %ld bytes\n",
BIO_number_read(SSL_get_rbio(s)),
BIO_number_written(SSL_get_wbio(s)));
}
BIO_printf(bio, (SSL_cache_hit(s) ? "---\nReused, " : "---\nNew, "));
c = SSL_get_current_cipher(s);
BIO_printf(bio, "%s, Cipher is %s\n",
SSL_CIPHER_get_version(c), SSL_CIPHER_get_name(c));
if (peer != NULL) {
EVP_PKEY *pktmp;
pktmp = X509_get_pubkey(peer);
BIO_printf(bio, "Server public key is %d bit\n",
EVP_PKEY_bits(pktmp));
EVP_PKEY_free(pktmp);
}
BIO_printf(bio, "Secure Renegotiation IS%s supported\n",
SSL_get_secure_renegotiation_support(s) ? "" : " NOT");
#ifndef OPENSSL_NO_COMP
comp = SSL_get_current_compression(s);
expansion = SSL_get_current_expansion(s);
BIO_printf(bio, "Compression: %s\n",
comp ? SSL_COMP_get_name(comp) : "NONE");
BIO_printf(bio, "Expansion: %s\n",
expansion ? SSL_COMP_get_name(expansion) : "NONE");
#endif
#ifdef SSL_DEBUG
{
/* Print out local port of connection: useful for debugging */
int sock;
struct sockaddr_in ladd;
socklen_t ladd_size = sizeof(ladd);
sock = SSL_get_fd(s);
getsockname(sock, (struct sockaddr *)&ladd, &ladd_size);
BIO_printf(bio_c_out, "LOCAL PORT is %u\n", ntohs(ladd.sin_port));
}
#endif
#if !defined(OPENSSL_NO_TLSEXT)
# if !defined(OPENSSL_NO_NEXTPROTONEG)
if (next_proto.status != -1) {
const unsigned char *proto;
unsigned int proto_len;
SSL_get0_next_proto_negotiated(s, &proto, &proto_len);
BIO_printf(bio, "Next protocol: (%d) ", next_proto.status);
BIO_write(bio, proto, proto_len);
BIO_write(bio, "\n", 1);
}
# endif
{
const unsigned char *proto;
unsigned int proto_len;
SSL_get0_alpn_selected(s, &proto, &proto_len);
if (proto_len > 0) {
BIO_printf(bio, "ALPN protocol: ");
BIO_write(bio, proto, proto_len);
BIO_write(bio, "\n", 1);
} else
BIO_printf(bio, "No ALPN negotiated\n");
}
#endif
#ifndef OPENSSL_NO_SRTP
{
SRTP_PROTECTION_PROFILE *srtp_profile =
SSL_get_selected_srtp_profile(s);
if (srtp_profile)
BIO_printf(bio, "SRTP Extension negotiated, profile=%s\n",
srtp_profile->name);
}
#endif
SSL_SESSION_print(bio, SSL_get_session(s));
if (keymatexportlabel != NULL) {
BIO_printf(bio, "Keying material exporter:\n");
BIO_printf(bio, " Label: '%s'\n", keymatexportlabel);
BIO_printf(bio, " Length: %i bytes\n", keymatexportlen);
exportedkeymat = OPENSSL_malloc(keymatexportlen);
if (exportedkeymat != NULL) {
if (!SSL_export_keying_material(s, exportedkeymat,
keymatexportlen,
keymatexportlabel,
strlen(keymatexportlabel),
NULL, 0, 0)) {
BIO_printf(bio, " Error\n");
} else {
BIO_printf(bio, " Keying material: ");
for (i = 0; i < keymatexportlen; i++)
BIO_printf(bio, "%02X", exportedkeymat[i]);
BIO_printf(bio, "\n");
}
OPENSSL_free(exportedkeymat);
}
}
BIO_printf(bio, "---\n");
if (peer != NULL)
X509_free(peer);
/* flush, or debugging output gets mixed with http response */
(void)BIO_flush(bio);
}
#ifndef OPENSSL_NO_TLSEXT
static int ocsp_resp_cb(SSL *s, void *arg)
{
const unsigned char *p;
int len;
OCSP_RESPONSE *rsp;
len = SSL_get_tlsext_status_ocsp_resp(s, &p);
BIO_puts(arg, "OCSP response: ");
if (!p) {
BIO_puts(arg, "no response sent\n");
return 1;
}
rsp = d2i_OCSP_RESPONSE(NULL, &p, len);
if (!rsp) {
BIO_puts(arg, "response parse error\n");
BIO_dump_indent(arg, (char *)p, len, 4);
return 0;
}
BIO_puts(arg, "\n======================================\n");
OCSP_RESPONSE_print(arg, rsp, 0);
BIO_puts(arg, "======================================\n");
OCSP_RESPONSE_free(rsp);
return 1;
}
#endif
diff --git a/apps/s_server.c b/apps/s_server.c
index 98ffc09314a3..83918fb6d39a 100644
--- a/apps/s_server.c
+++ b/apps/s_server.c
@@ -1,3519 +1,3519 @@
/* apps/s_server.c */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
/* ====================================================================
* Copyright (c) 1998-2006 The OpenSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* openssl-core@openssl.org.
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.openssl.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*
* This product includes cryptographic software written by Eric Young
* (eay@cryptsoft.com). This product includes software written by Tim
* Hudson (tjh@cryptsoft.com).
*
*/
/* ====================================================================
* Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
* ECC cipher suite support in OpenSSL originally developed by
* SUN MICROSYSTEMS, INC., and contributed to the OpenSSL project.
*/
/* ====================================================================
* Copyright 2005 Nokia. All rights reserved.
*
* The portions of the attached software ("Contribution") is developed by
* Nokia Corporation and is licensed pursuant to the OpenSSL open source
* license.
*
* The Contribution, originally written by Mika Kousa and Pasi Eronen of
* Nokia Corporation, consists of the "PSK" (Pre-Shared Key) ciphersuites
* support (see RFC 4279) to OpenSSL.
*
* No patent licenses or other rights except those expressly stated in
* the OpenSSL open source license shall be deemed granted or received
* expressly, by implication, estoppel, or otherwise.
*
* No assurances are provided by Nokia that the Contribution does not
* infringe the patent or other intellectual property rights of any third
* party or that the license provides you with all the necessary rights
* to make use of the Contribution.
*
* THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. IN
* ADDITION TO THE DISCLAIMERS INCLUDED IN THE LICENSE, NOKIA
* SPECIFICALLY DISCLAIMS ANY LIABILITY FOR CLAIMS BROUGHT BY YOU OR ANY
* OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS OR
* OTHERWISE.
*/
/*
* Until the key-gen callbacks are modified to use newer prototypes, we allow
* deprecated functions for openssl-internal code
*/
#ifdef OPENSSL_NO_DEPRECATED
# undef OPENSSL_NO_DEPRECATED
#endif
#include <assert.h>
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/e_os2.h>
#ifdef OPENSSL_NO_STDIO
# define APPS_WIN16
#endif
/* conflicts with winsock2 stuff on netware */
#if !defined(OPENSSL_SYS_NETWARE)
# include <sys/types.h>
#endif
/*
* With IPv6, it looks like Digital has mixed up the proper order of
* recursive header file inclusion, resulting in the compiler complaining
* that u_int isn't defined, but only if _POSIX_C_SOURCE is defined, which is
* needed to have fileno() declared correctly... So let's define u_int
*/
#if defined(OPENSSL_SYS_VMS_DECC) && !defined(__U_INT)
# define __U_INT
typedef unsigned int u_int;
#endif
#include <openssl/lhash.h>
#include <openssl/bn.h>
#define USE_SOCKETS
#include "apps.h"
#include <openssl/err.h>
#include <openssl/pem.h>
#include <openssl/x509.h>
#include <openssl/ssl.h>
#include <openssl/rand.h>
#include <openssl/ocsp.h>
#ifndef OPENSSL_NO_DH
# include <openssl/dh.h>
#endif
#ifndef OPENSSL_NO_RSA
# include <openssl/rsa.h>
#endif
#ifndef OPENSSL_NO_SRP
# include <openssl/srp.h>
#endif
#include "s_apps.h"
#include "timeouts.h"
#if (defined(OPENSSL_SYS_VMS) && __VMS_VER < 70000000)
/* FIONBIO used as a switch to enable ioctl, and that isn't in VMS < 7.0 */
# undef FIONBIO
#endif
#if defined(OPENSSL_SYS_BEOS_R5)
# include <fcntl.h>
#endif
#ifndef OPENSSL_NO_RSA
static RSA MS_CALLBACK *tmp_rsa_cb(SSL *s, int is_export, int keylength);
#endif
static int sv_body(char *hostname, int s, int stype, unsigned char *context);
static int www_body(char *hostname, int s, int stype, unsigned char *context);
static int rev_body(char *hostname, int s, int stype, unsigned char *context);
static void close_accept_socket(void);
static void sv_usage(void);
static int init_ssl_connection(SSL *s);
static void print_stats(BIO *bp, SSL_CTX *ctx);
static int generate_session_id(const SSL *ssl, unsigned char *id,
unsigned int *id_len);
static void init_session_cache_ctx(SSL_CTX *sctx);
static void free_sessions(void);
#ifndef OPENSSL_NO_DH
static DH *load_dh_param(const char *dhfile);
static DH *get_dh2048(void);
#endif
#ifdef MONOLITH
static void s_server_init(void);
#endif
#ifndef OPENSSL_NO_DH
static unsigned char dh2048_p[] = {
0xF6,0x42,0x57,0xB7,0x08,0x7F,0x08,0x17,0x72,0xA2,0xBA,0xD6,
0xA9,0x42,0xF3,0x05,0xE8,0xF9,0x53,0x11,0x39,0x4F,0xB6,0xF1,
0x6E,0xB9,0x4B,0x38,0x20,0xDA,0x01,0xA7,0x56,0xA3,0x14,0xE9,
0x8F,0x40,0x55,0xF3,0xD0,0x07,0xC6,0xCB,0x43,0xA9,0x94,0xAD,
0xF7,0x4C,0x64,0x86,0x49,0xF8,0x0C,0x83,0xBD,0x65,0xE9,0x17,
0xD4,0xA1,0xD3,0x50,0xF8,0xF5,0x59,0x5F,0xDC,0x76,0x52,0x4F,
0x3D,0x3D,0x8D,0xDB,0xCE,0x99,0xE1,0x57,0x92,0x59,0xCD,0xFD,
0xB8,0xAE,0x74,0x4F,0xC5,0xFC,0x76,0xBC,0x83,0xC5,0x47,0x30,
0x61,0xCE,0x7C,0xC9,0x66,0xFF,0x15,0xF9,0xBB,0xFD,0x91,0x5E,
0xC7,0x01,0xAA,0xD3,0x5B,0x9E,0x8D,0xA0,0xA5,0x72,0x3A,0xD4,
0x1A,0xF0,0xBF,0x46,0x00,0x58,0x2B,0xE5,0xF4,0x88,0xFD,0x58,
0x4E,0x49,0xDB,0xCD,0x20,0xB4,0x9D,0xE4,0x91,0x07,0x36,0x6B,
0x33,0x6C,0x38,0x0D,0x45,0x1D,0x0F,0x7C,0x88,0xB3,0x1C,0x7C,
0x5B,0x2D,0x8E,0xF6,0xF3,0xC9,0x23,0xC0,0x43,0xF0,0xA5,0x5B,
0x18,0x8D,0x8E,0xBB,0x55,0x8C,0xB8,0x5D,0x38,0xD3,0x34,0xFD,
0x7C,0x17,0x57,0x43,0xA3,0x1D,0x18,0x6C,0xDE,0x33,0x21,0x2C,
0xB5,0x2A,0xFF,0x3C,0xE1,0xB1,0x29,0x40,0x18,0x11,0x8D,0x7C,
0x84,0xA7,0x0A,0x72,0xD6,0x86,0xC4,0x03,0x19,0xC8,0x07,0x29,
0x7A,0xCA,0x95,0x0C,0xD9,0x96,0x9F,0xAB,0xD0,0x0A,0x50,0x9B,
0x02,0x46,0xD3,0x08,0x3D,0x66,0xA4,0x5D,0x41,0x9F,0x9C,0x7C,
0xBD,0x89,0x4B,0x22,0x19,0x26,0xBA,0xAB,0xA2,0x5E,0xC3,0x55,
0xE9,0x32,0x0B,0x3B,
};
static unsigned char dh2048_g[] = {
0x02,
};
DH *get_dh2048()
{
DH *dh;
if ((dh = DH_new()) == NULL)
return NULL;
dh->p=BN_bin2bn(dh2048_p, sizeof(dh2048_p), NULL);
dh->g=BN_bin2bn(dh2048_g, sizeof(dh2048_g), NULL);
if (dh->p == NULL || dh->g == NULL) {
DH_free(dh);
return NULL;
}
return dh;
}
#endif
/* static int load_CA(SSL_CTX *ctx, char *file);*/
#undef BUFSIZZ
#define BUFSIZZ 16*1024
static int bufsize = BUFSIZZ;
static int accept_socket = -1;
#define TEST_CERT "server.pem"
#ifndef OPENSSL_NO_TLSEXT
# define TEST_CERT2 "server2.pem"
#endif
#undef PROG
#define PROG s_server_main
extern int verify_depth, verify_return_error, verify_quiet;
static int s_server_verify = SSL_VERIFY_NONE;
static int s_server_session_id_context = 1; /* anything will do */
static const char *s_cert_file = TEST_CERT, *s_key_file =
NULL, *s_chain_file = NULL;
#ifndef OPENSSL_NO_TLSEXT
static const char *s_cert_file2 = TEST_CERT2, *s_key_file2 = NULL;
#endif
static char *s_dcert_file = NULL, *s_dkey_file = NULL, *s_dchain_file = NULL;
#ifdef FIONBIO
static int s_nbio = 0;
#endif
static int s_nbio_test = 0;
int s_crlf = 0;
static SSL_CTX *ctx = NULL;
#ifndef OPENSSL_NO_TLSEXT
static SSL_CTX *ctx2 = NULL;
#endif
static int www = 0;
static BIO *bio_s_out = NULL;
static BIO *bio_s_msg = NULL;
static int s_debug = 0;
#ifndef OPENSSL_NO_TLSEXT
static int s_tlsextdebug = 0;
static int s_tlsextstatus = 0;
static int cert_status_cb(SSL *s, void *arg);
#endif
static int no_resume_ephemeral = 0;
static int s_msg = 0;
static int s_quiet = 0;
static int s_ign_eof = 0;
static int s_brief = 0;
static char *keymatexportlabel = NULL;
static int keymatexportlen = 20;
static int hack = 0;
static char *engine_id = NULL;
static const char *session_id_prefix = NULL;
static int enable_timeouts = 0;
static long socket_mtu;
#ifndef OPENSSL_NO_DTLS1
static int cert_chain = 0;
#endif
#ifndef OPENSSL_NO_TLSEXT
static BIO *serverinfo_in = NULL;
static const char *s_serverinfo_file = NULL;
#endif
#ifndef OPENSSL_NO_PSK
static char *psk_identity = "Client_identity";
char *psk_key = NULL; /* by default PSK is not used */
static unsigned int psk_server_cb(SSL *ssl, const char *identity,
unsigned char *psk,
unsigned int max_psk_len)
{
long key_len = 0;
unsigned char *key;
if (s_debug)
BIO_printf(bio_s_out, "psk_server_cb\n");
if (!identity) {
BIO_printf(bio_err, "Error: client did not send PSK identity\n");
goto out_err;
}
if (s_debug)
BIO_printf(bio_s_out, "identity_len=%d identity=%s\n",
(int)strlen(identity), identity);
/* here we could lookup the given identity e.g. from a database */
if (strcmp(identity, psk_identity) != 0) {
BIO_printf(bio_s_out, "PSK error: client identity not found"
" (got '%s' expected '%s')\n", identity, psk_identity);
goto out_err;
}
if (s_debug)
BIO_printf(bio_s_out, "PSK client identity found\n");
/* convert the PSK key to binary */
key = string_to_hex(psk_key, &key_len);
if (key == NULL) {
BIO_printf(bio_err, "Could not convert PSK key '%s' to buffer\n",
psk_key);
return 0;
}
if (key_len > (int)max_psk_len) {
BIO_printf(bio_err,
"psk buffer of callback is too small (%d) for key (%ld)\n",
max_psk_len, key_len);
OPENSSL_free(key);
return 0;
}
memcpy(psk, key, key_len);
OPENSSL_free(key);
if (s_debug)
BIO_printf(bio_s_out, "fetched PSK len=%ld\n", key_len);
return key_len;
out_err:
if (s_debug)
BIO_printf(bio_err, "Error in PSK server callback\n");
return 0;
}
#endif
#ifndef OPENSSL_NO_SRP
/* This is a context that we pass to callbacks */
typedef struct srpsrvparm_st {
char *login;
SRP_VBASE *vb;
SRP_user_pwd *user;
} srpsrvparm;
/*
* This callback pretends to require some asynchronous logic in order to
* obtain a verifier. When the callback is called for a new connection we
* return with a negative value. This will provoke the accept etc to return
* with an LOOKUP_X509. The main logic of the reinvokes the suspended call
* (which would normally occur after a worker has finished) and we set the
* user parameters.
*/
static int MS_CALLBACK ssl_srp_server_param_cb(SSL *s, int *ad, void *arg)
{
srpsrvparm *p = (srpsrvparm *) arg;
int ret = SSL3_AL_FATAL;
if (p->login == NULL && p->user == NULL) {
p->login = SSL_get_srp_username(s);
BIO_printf(bio_err, "SRP username = \"%s\"\n", p->login);
return (-1);
}
if (p->user == NULL) {
BIO_printf(bio_err, "User %s doesn't exist\n", p->login);
goto err;
}
if (SSL_set_srp_server_param
(s, p->user->N, p->user->g, p->user->s, p->user->v,
p->user->info) < 0) {
*ad = SSL_AD_INTERNAL_ERROR;
goto err;
}
BIO_printf(bio_err,
"SRP parameters set: username = \"%s\" info=\"%s\" \n",
p->login, p->user->info);
ret = SSL_ERROR_NONE;
err:
SRP_user_pwd_free(p->user);
p->user = NULL;
p->login = NULL;
return ret;
}
#endif
#ifdef MONOLITH
static void s_server_init(void)
{
accept_socket = -1;
s_server_verify = SSL_VERIFY_NONE;
s_dcert_file = NULL;
s_dkey_file = NULL;
s_dchain_file = NULL;
s_cert_file = TEST_CERT;
s_key_file = NULL;
s_chain_file = NULL;
# ifndef OPENSSL_NO_TLSEXT
s_cert_file2 = TEST_CERT2;
s_key_file2 = NULL;
ctx2 = NULL;
# endif
# ifdef FIONBIO
s_nbio = 0;
# endif
s_nbio_test = 0;
ctx = NULL;
www = 0;
bio_s_out = NULL;
s_debug = 0;
s_msg = 0;
s_quiet = 0;
s_brief = 0;
hack = 0;
engine_id = NULL;
}
#endif
static void sv_usage(void)
{
BIO_printf(bio_err, "usage: s_server [args ...]\n");
BIO_printf(bio_err, "\n");
BIO_printf(bio_err,
" -accept arg - port to accept on (default is %d)\n", PORT);
BIO_printf(bio_err,
" -verify_hostname host - check peer certificate matches \"host\"\n");
BIO_printf(bio_err,
" -verify_email email - check peer certificate matches \"email\"\n");
BIO_printf(bio_err,
" -verify_ip ipaddr - check peer certificate matches \"ipaddr\"\n");
BIO_printf(bio_err, " -context arg - set session ID context\n");
BIO_printf(bio_err,
" -verify arg - turn on peer certificate verification\n");
BIO_printf(bio_err,
" -Verify arg - turn on peer certificate verification, must have a cert.\n");
BIO_printf(bio_err,
" -verify_return_error - return verification errors\n");
BIO_printf(bio_err, " -cert arg - certificate file to use\n");
BIO_printf(bio_err, " (default is %s)\n", TEST_CERT);
#ifndef OPENSSL_NO_TLSEXT
BIO_printf(bio_err,
" -serverinfo arg - PEM serverinfo file for certificate\n");
BIO_printf(bio_err,
" -auth - send and receive RFC 5878 TLS auth extensions and supplemental data\n");
BIO_printf(bio_err,
" -auth_require_reneg - Do not send TLS auth extensions until renegotiation\n");
#endif
BIO_printf(bio_err,
" -no_resumption_on_reneg - set SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION flag\n");
BIO_printf(bio_err,
" -crl_check - check the peer certificate has not been revoked by its CA.\n"
" The CRL(s) are appended to the certificate file\n");
BIO_printf(bio_err,
" -crl_check_all - check the peer certificate has not been revoked by its CA\n"
" or any other CRL in the CA chain. CRL(s) are appened to the\n"
" the certificate file.\n");
BIO_printf(bio_err,
" -certform arg - certificate format (PEM or DER) PEM default\n");
BIO_printf(bio_err,
" -key arg - Private Key file to use, in cert file if\n");
BIO_printf(bio_err, " not specified (default is %s)\n",
TEST_CERT);
BIO_printf(bio_err,
" -keyform arg - key format (PEM, DER or ENGINE) PEM default\n");
BIO_printf(bio_err,
" -pass arg - private key file pass phrase source\n");
BIO_printf(bio_err,
" -dcert arg - second certificate file to use (usually for DSA)\n");
BIO_printf(bio_err,
" -dcertform x - second certificate format (PEM or DER) PEM default\n");
BIO_printf(bio_err,
" -dkey arg - second private key file to use (usually for DSA)\n");
BIO_printf(bio_err,
" -dkeyform arg - second key format (PEM, DER or ENGINE) PEM default\n");
BIO_printf(bio_err,
" -dpass arg - second private key file pass phrase source\n");
BIO_printf(bio_err,
" -dhparam arg - DH parameter file to use, in cert file if not specified\n");
BIO_printf(bio_err,
" or a default set of parameters is used\n");
#ifndef OPENSSL_NO_ECDH
BIO_printf(bio_err,
" -named_curve arg - Elliptic curve name to use for ephemeral ECDH keys.\n"
" Use \"openssl ecparam -list_curves\" for all names\n"
" (default is nistp256).\n");
#endif
#ifdef FIONBIO
BIO_printf(bio_err, " -nbio - Run with non-blocking IO\n");
#endif
BIO_printf(bio_err,
" -nbio_test - test with the non-blocking test bio\n");
BIO_printf(bio_err,
" -crlf - convert LF from terminal into CRLF\n");
BIO_printf(bio_err, " -debug - Print more output\n");
BIO_printf(bio_err, " -msg - Show protocol messages\n");
BIO_printf(bio_err, " -state - Print the SSL states\n");
BIO_printf(bio_err, " -CApath arg - PEM format directory of CA's\n");
BIO_printf(bio_err, " -CAfile arg - PEM format file of CA's\n");
BIO_printf(bio_err,
" -no_alt_chains - only ever use the first certificate chain found\n");
BIO_printf(bio_err,
" -nocert - Don't use any certificates (Anon-DH)\n");
BIO_printf(bio_err,
" -cipher arg - play with 'openssl ciphers' to see what goes here\n");
BIO_printf(bio_err, " -serverpref - Use server's cipher preferences\n");
BIO_printf(bio_err, " -quiet - No server output\n");
BIO_printf(bio_err, " -no_tmp_rsa - Do not generate a tmp RSA key\n");
#ifndef OPENSSL_NO_PSK
BIO_printf(bio_err, " -psk_hint arg - PSK identity hint to use\n");
BIO_printf(bio_err, " -psk arg - PSK in hex (without 0x)\n");
# ifndef OPENSSL_NO_JPAKE
BIO_printf(bio_err, " -jpake arg - JPAKE secret to use\n");
# endif
#endif
#ifndef OPENSSL_NO_SRP
BIO_printf(bio_err, " -srpvfile file - The verifier file for SRP\n");
BIO_printf(bio_err,
" -srpuserseed string - A seed string for a default user salt.\n");
#endif
BIO_printf(bio_err, " -ssl2 - Just talk SSLv2\n");
#ifndef OPENSSL_NO_SSL3_METHOD
BIO_printf(bio_err, " -ssl3 - Just talk SSLv3\n");
#endif
BIO_printf(bio_err, " -tls1_2 - Just talk TLSv1.2\n");
BIO_printf(bio_err, " -tls1_1 - Just talk TLSv1.1\n");
BIO_printf(bio_err, " -tls1 - Just talk TLSv1\n");
BIO_printf(bio_err, " -dtls1 - Just talk DTLSv1\n");
BIO_printf(bio_err, " -dtls1_2 - Just talk DTLSv1.2\n");
BIO_printf(bio_err, " -timeout - Enable timeouts\n");
BIO_printf(bio_err, " -mtu - Set link layer MTU\n");
BIO_printf(bio_err, " -chain - Read a certificate chain\n");
BIO_printf(bio_err, " -no_ssl2 - Just disable SSLv2\n");
BIO_printf(bio_err, " -no_ssl3 - Just disable SSLv3\n");
BIO_printf(bio_err, " -no_tls1 - Just disable TLSv1\n");
BIO_printf(bio_err, " -no_tls1_1 - Just disable TLSv1.1\n");
BIO_printf(bio_err, " -no_tls1_2 - Just disable TLSv1.2\n");
#ifndef OPENSSL_NO_DH
BIO_printf(bio_err, " -no_dhe - Disable ephemeral DH\n");
#endif
#ifndef OPENSSL_NO_ECDH
BIO_printf(bio_err, " -no_ecdhe - Disable ephemeral ECDH\n");
#endif
BIO_printf(bio_err, " -bugs - Turn on SSL bug compatibility\n");
BIO_printf(bio_err,
" -hack - workaround for early Netscape code\n");
BIO_printf(bio_err,
" -www - Respond to a 'GET /' with a status page\n");
BIO_printf(bio_err,
" -WWW - Respond to a 'GET /<path> HTTP/1.0' with file ./<path>\n");
BIO_printf(bio_err,
" -HTTP - Respond to a 'GET /<path> HTTP/1.0' with file ./<path>\n");
BIO_printf(bio_err,
" with the assumption it contains a complete HTTP response.\n");
#ifndef OPENSSL_NO_ENGINE
BIO_printf(bio_err,
" -engine id - Initialise and use the specified engine\n");
#endif
BIO_printf(bio_err,
" -id_prefix arg - Generate SSL/TLS session IDs prefixed by 'arg'\n");
BIO_printf(bio_err, " -rand file%cfile%c...\n", LIST_SEPARATOR_CHAR,
LIST_SEPARATOR_CHAR);
#ifndef OPENSSL_NO_TLSEXT
BIO_printf(bio_err,
" -servername host - servername for HostName TLS extension\n");
BIO_printf(bio_err,
" -servername_fatal - on mismatch send fatal alert (default warning alert)\n");
BIO_printf(bio_err,
" -cert2 arg - certificate file to use for servername\n");
BIO_printf(bio_err, " (default is %s)\n", TEST_CERT2);
BIO_printf(bio_err,
" -key2 arg - Private Key file to use for servername, in cert file if\n");
BIO_printf(bio_err, " not specified (default is %s)\n",
TEST_CERT2);
BIO_printf(bio_err,
" -tlsextdebug - hex dump of all TLS extensions received\n");
BIO_printf(bio_err,
" -no_ticket - disable use of RFC4507bis session tickets\n");
BIO_printf(bio_err,
" -legacy_renegotiation - enable use of legacy renegotiation (dangerous)\n");
BIO_printf(bio_err,
" -sigalgs arg - Signature algorithms to support (colon-separated list)\n");
BIO_printf(bio_err,
" -client_sigalgs arg - Signature algorithms to support for client \n");
BIO_printf(bio_err,
" certificate authentication (colon-separated list)\n");
# ifndef OPENSSL_NO_NEXTPROTONEG
BIO_printf(bio_err,
" -nextprotoneg arg - set the advertised protocols for the NPN extension (comma-separated list)\n");
# endif
# ifndef OPENSSL_NO_SRTP
BIO_printf(bio_err,
" -use_srtp profiles - Offer SRTP key management with a colon-separated profile list\n");
# endif
BIO_printf(bio_err,
" -alpn arg - set the advertised protocols for the ALPN extension (comma-separated list)\n");
#endif
BIO_printf(bio_err,
" -keymatexport label - Export keying material using label\n");
BIO_printf(bio_err,
" -keymatexportlen len - Export len bytes of keying material (default 20)\n");
BIO_printf(bio_err,
" -status - respond to certificate status requests\n");
BIO_printf(bio_err,
" -status_verbose - enable status request verbose printout\n");
BIO_printf(bio_err,
" -status_timeout n - status request responder timeout\n");
BIO_printf(bio_err, " -status_url URL - status request fallback URL\n");
}
static int local_argc = 0;
static char **local_argv;
#ifdef CHARSET_EBCDIC
static int ebcdic_new(BIO *bi);
static int ebcdic_free(BIO *a);
static int ebcdic_read(BIO *b, char *out, int outl);
static int ebcdic_write(BIO *b, const char *in, int inl);
static long ebcdic_ctrl(BIO *b, int cmd, long num, void *ptr);
static int ebcdic_gets(BIO *bp, char *buf, int size);
static int ebcdic_puts(BIO *bp, const char *str);
# define BIO_TYPE_EBCDIC_FILTER (18|0x0200)
static BIO_METHOD methods_ebcdic = {
BIO_TYPE_EBCDIC_FILTER,
"EBCDIC/ASCII filter",
ebcdic_write,
ebcdic_read,
ebcdic_puts,
ebcdic_gets,
ebcdic_ctrl,
ebcdic_new,
ebcdic_free,
};
typedef struct {
size_t alloced;
char buff[1];
} EBCDIC_OUTBUFF;
BIO_METHOD *BIO_f_ebcdic_filter()
{
return (&methods_ebcdic);
}
static int ebcdic_new(BIO *bi)
{
EBCDIC_OUTBUFF *wbuf;
wbuf = (EBCDIC_OUTBUFF *) OPENSSL_malloc(sizeof(EBCDIC_OUTBUFF) + 1024);
if (!wbuf)
return 0;
wbuf->alloced = 1024;
wbuf->buff[0] = '\0';
bi->ptr = (char *)wbuf;
bi->init = 1;
bi->flags = 0;
return (1);
}
static int ebcdic_free(BIO *a)
{
if (a == NULL)
return (0);
if (a->ptr != NULL)
OPENSSL_free(a->ptr);
a->ptr = NULL;
a->init = 0;
a->flags = 0;
return (1);
}
static int ebcdic_read(BIO *b, char *out, int outl)
{
int ret = 0;
if (out == NULL || outl == 0)
return (0);
if (b->next_bio == NULL)
return (0);
ret = BIO_read(b->next_bio, out, outl);
if (ret > 0)
ascii2ebcdic(out, out, ret);
return (ret);
}
static int ebcdic_write(BIO *b, const char *in, int inl)
{
EBCDIC_OUTBUFF *wbuf;
int ret = 0;
int num;
unsigned char n;
if ((in == NULL) || (inl <= 0))
return (0);
if (b->next_bio == NULL)
return (0);
wbuf = (EBCDIC_OUTBUFF *) b->ptr;
if (inl > (num = wbuf->alloced)) {
num = num + num; /* double the size */
if (num < inl)
num = inl;
wbuf =
(EBCDIC_OUTBUFF *) OPENSSL_malloc(sizeof(EBCDIC_OUTBUFF) + num);
if (!wbuf)
return 0;
OPENSSL_free(b->ptr);
wbuf->alloced = num;
wbuf->buff[0] = '\0';
b->ptr = (char *)wbuf;
}
ebcdic2ascii(wbuf->buff, in, inl);
ret = BIO_write(b->next_bio, wbuf->buff, inl);
return (ret);
}
static long ebcdic_ctrl(BIO *b, int cmd, long num, void *ptr)
{
long ret;
if (b->next_bio == NULL)
return (0);
switch (cmd) {
case BIO_CTRL_DUP:
ret = 0L;
break;
default:
ret = BIO_ctrl(b->next_bio, cmd, num, ptr);
break;
}
return (ret);
}
static int ebcdic_gets(BIO *bp, char *buf, int size)
{
int i, ret = 0;
if (bp->next_bio == NULL)
return (0);
/* return(BIO_gets(bp->next_bio,buf,size));*/
for (i = 0; i < size - 1; ++i) {
ret = ebcdic_read(bp, &buf[i], 1);
if (ret <= 0)
break;
else if (buf[i] == '\n') {
++i;
break;
}
}
if (i < size)
buf[i] = '\0';
return (ret < 0 && i == 0) ? ret : i;
}
static int ebcdic_puts(BIO *bp, const char *str)
{
if (bp->next_bio == NULL)
return (0);
return ebcdic_write(bp, str, strlen(str));
}
#endif
#ifndef OPENSSL_NO_TLSEXT
/* This is a context that we pass to callbacks */
typedef struct tlsextctx_st {
char *servername;
BIO *biodebug;
int extension_error;
} tlsextctx;
static int MS_CALLBACK ssl_servername_cb(SSL *s, int *ad, void *arg)
{
tlsextctx *p = (tlsextctx *) arg;
const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
if (servername && p->biodebug)
BIO_printf(p->biodebug, "Hostname in TLS extension: \"%s\"\n",
servername);
if (!p->servername)
return SSL_TLSEXT_ERR_NOACK;
if (servername) {
if (strcasecmp(servername, p->servername))
return p->extension_error;
if (ctx2) {
BIO_printf(p->biodebug, "Switching server context.\n");
SSL_set_SSL_CTX(s, ctx2);
}
}
return SSL_TLSEXT_ERR_OK;
}
/* Structure passed to cert status callback */
typedef struct tlsextstatusctx_st {
/* Default responder to use */
char *host, *path, *port;
int use_ssl;
int timeout;
BIO *err;
int verbose;
} tlsextstatusctx;
static tlsextstatusctx tlscstatp = { NULL, NULL, NULL, 0, -1, NULL, 0 };
/*
* Certificate Status callback. This is called when a client includes a
* certificate status request extension. This is a simplified version. It
* examines certificates each time and makes one OCSP responder query for
* each request. A full version would store details such as the OCSP
* certificate IDs and minimise the number of OCSP responses by caching them
* until they were considered "expired".
*/
static int cert_status_cb(SSL *s, void *arg)
{
tlsextstatusctx *srctx = arg;
BIO *err = srctx->err;
char *host, *port, *path;
int use_ssl;
unsigned char *rspder = NULL;
int rspderlen;
STACK_OF(OPENSSL_STRING) *aia = NULL;
X509 *x = NULL;
X509_STORE_CTX inctx;
X509_OBJECT obj;
OCSP_REQUEST *req = NULL;
OCSP_RESPONSE *resp = NULL;
OCSP_CERTID *id = NULL;
STACK_OF(X509_EXTENSION) *exts;
int ret = SSL_TLSEXT_ERR_NOACK;
int i;
# if 0
STACK_OF(OCSP_RESPID) *ids;
SSL_get_tlsext_status_ids(s, &ids);
BIO_printf(err, "cert_status: received %d ids\n",
sk_OCSP_RESPID_num(ids));
# endif
if (srctx->verbose)
BIO_puts(err, "cert_status: callback called\n");
/* Build up OCSP query from server certificate */
x = SSL_get_certificate(s);
aia = X509_get1_ocsp(x);
if (aia) {
if (!OCSP_parse_url(sk_OPENSSL_STRING_value(aia, 0),
&host, &port, &path, &use_ssl)) {
BIO_puts(err, "cert_status: can't parse AIA URL\n");
goto err;
}
if (srctx->verbose)
BIO_printf(err, "cert_status: AIA URL: %s\n",
sk_OPENSSL_STRING_value(aia, 0));
} else {
if (!srctx->host) {
BIO_puts(srctx->err,
"cert_status: no AIA and no default responder URL\n");
goto done;
}
host = srctx->host;
path = srctx->path;
port = srctx->port;
use_ssl = srctx->use_ssl;
}
if (!X509_STORE_CTX_init(&inctx,
SSL_CTX_get_cert_store(SSL_get_SSL_CTX(s)),
NULL, NULL))
goto err;
if (X509_STORE_get_by_subject(&inctx, X509_LU_X509,
X509_get_issuer_name(x), &obj) <= 0) {
BIO_puts(err, "cert_status: Can't retrieve issuer certificate.\n");
X509_STORE_CTX_cleanup(&inctx);
goto done;
}
req = OCSP_REQUEST_new();
if (!req)
goto err;
id = OCSP_cert_to_id(NULL, x, obj.data.x509);
X509_free(obj.data.x509);
X509_STORE_CTX_cleanup(&inctx);
if (!id)
goto err;
if (!OCSP_request_add0_id(req, id))
goto err;
id = NULL;
/* Add any extensions to the request */
SSL_get_tlsext_status_exts(s, &exts);
for (i = 0; i < sk_X509_EXTENSION_num(exts); i++) {
X509_EXTENSION *ext = sk_X509_EXTENSION_value(exts, i);
if (!OCSP_REQUEST_add_ext(req, ext, -1))
goto err;
}
resp = process_responder(err, req, host, path, port, use_ssl, NULL,
srctx->timeout);
if (!resp) {
BIO_puts(err, "cert_status: error querying responder\n");
goto done;
}
rspderlen = i2d_OCSP_RESPONSE(resp, &rspder);
if (rspderlen <= 0)
goto err;
SSL_set_tlsext_status_ocsp_resp(s, rspder, rspderlen);
if (srctx->verbose) {
BIO_puts(err, "cert_status: ocsp response sent:\n");
OCSP_RESPONSE_print(err, resp, 2);
}
ret = SSL_TLSEXT_ERR_OK;
done:
if (ret != SSL_TLSEXT_ERR_OK)
ERR_print_errors(err);
if (aia) {
OPENSSL_free(host);
OPENSSL_free(path);
OPENSSL_free(port);
X509_email_free(aia);
}
if (id)
OCSP_CERTID_free(id);
if (req)
OCSP_REQUEST_free(req);
if (resp)
OCSP_RESPONSE_free(resp);
return ret;
err:
ret = SSL_TLSEXT_ERR_ALERT_FATAL;
goto done;
}
# ifndef OPENSSL_NO_NEXTPROTONEG
/* This is the context that we pass to next_proto_cb */
typedef struct tlsextnextprotoctx_st {
unsigned char *data;
unsigned int len;
} tlsextnextprotoctx;
static int next_proto_cb(SSL *s, const unsigned char **data,
unsigned int *len, void *arg)
{
tlsextnextprotoctx *next_proto = arg;
*data = next_proto->data;
*len = next_proto->len;
return SSL_TLSEXT_ERR_OK;
}
# endif /* ndef OPENSSL_NO_NEXTPROTONEG */
/* This the context that we pass to alpn_cb */
typedef struct tlsextalpnctx_st {
unsigned char *data;
unsigned short len;
} tlsextalpnctx;
static int alpn_cb(SSL *s, const unsigned char **out, unsigned char *outlen,
const unsigned char *in, unsigned int inlen, void *arg)
{
tlsextalpnctx *alpn_ctx = arg;
if (!s_quiet) {
/* We can assume that |in| is syntactically valid. */
unsigned i;
BIO_printf(bio_s_out, "ALPN protocols advertised by the client: ");
for (i = 0; i < inlen;) {
if (i)
BIO_write(bio_s_out, ", ", 2);
BIO_write(bio_s_out, &in[i + 1], in[i]);
i += in[i] + 1;
}
BIO_write(bio_s_out, "\n", 1);
}
if (SSL_select_next_proto
((unsigned char **)out, outlen, alpn_ctx->data, alpn_ctx->len, in,
inlen) != OPENSSL_NPN_NEGOTIATED) {
return SSL_TLSEXT_ERR_NOACK;
}
if (!s_quiet) {
BIO_printf(bio_s_out, "ALPN protocols selected: ");
BIO_write(bio_s_out, *out, *outlen);
BIO_write(bio_s_out, "\n", 1);
}
return SSL_TLSEXT_ERR_OK;
}
#endif /* ndef OPENSSL_NO_TLSEXT */
int MAIN(int, char **);
#ifndef OPENSSL_NO_JPAKE
static char *jpake_secret = NULL;
# define no_jpake !jpake_secret
#else
# define no_jpake 1
#endif
#ifndef OPENSSL_NO_SRP
static srpsrvparm srp_callback_parm;
#endif
#ifndef OPENSSL_NO_SRTP
static char *srtp_profiles = NULL;
#endif
int MAIN(int argc, char *argv[])
{
X509_VERIFY_PARAM *vpm = NULL;
int badarg = 0;
short port = PORT;
char *CApath = NULL, *CAfile = NULL;
char *chCApath = NULL, *chCAfile = NULL;
char *vfyCApath = NULL, *vfyCAfile = NULL;
unsigned char *context = NULL;
char *dhfile = NULL;
int badop = 0;
int ret = 1;
int build_chain = 0;
int no_tmp_rsa = 0, no_dhe = 0, no_ecdhe = 0, nocert = 0;
int state = 0;
const SSL_METHOD *meth = NULL;
int socket_type = SOCK_STREAM;
ENGINE *e = NULL;
char *inrand = NULL;
int s_cert_format = FORMAT_PEM, s_key_format = FORMAT_PEM;
char *passarg = NULL, *pass = NULL;
char *dpassarg = NULL, *dpass = NULL;
int s_dcert_format = FORMAT_PEM, s_dkey_format = FORMAT_PEM;
X509 *s_cert = NULL, *s_dcert = NULL;
STACK_OF(X509) *s_chain = NULL, *s_dchain = NULL;
EVP_PKEY *s_key = NULL, *s_dkey = NULL;
int no_cache = 0, ext_cache = 0;
int rev = 0, naccept = -1;
#ifndef OPENSSL_NO_TLSEXT
EVP_PKEY *s_key2 = NULL;
X509 *s_cert2 = NULL;
tlsextctx tlsextcbp = { NULL, NULL, SSL_TLSEXT_ERR_ALERT_WARNING };
# ifndef OPENSSL_NO_NEXTPROTONEG
const char *next_proto_neg_in = NULL;
tlsextnextprotoctx next_proto = { NULL, 0 };
# endif
const char *alpn_in = NULL;
tlsextalpnctx alpn_ctx = { NULL, 0 };
#endif
#ifndef OPENSSL_NO_PSK
/* by default do not send a PSK identity hint */
static char *psk_identity_hint = NULL;
#endif
#ifndef OPENSSL_NO_SRP
char *srpuserseed = NULL;
char *srp_verifier_file = NULL;
#endif
SSL_EXCERT *exc = NULL;
SSL_CONF_CTX *cctx = NULL;
STACK_OF(OPENSSL_STRING) *ssl_args = NULL;
char *crl_file = NULL;
int crl_format = FORMAT_PEM;
int crl_download = 0;
STACK_OF(X509_CRL) *crls = NULL;
int prot_opt = 0, no_prot_opt = 0;
meth = SSLv23_server_method();
local_argc = argc;
local_argv = argv;
apps_startup();
#ifdef MONOLITH
s_server_init();
#endif
if (bio_err == NULL)
bio_err = BIO_new_fp(stderr, BIO_NOCLOSE);
if (!load_config(bio_err, NULL))
goto end;
cctx = SSL_CONF_CTX_new();
if (!cctx)
goto end;
SSL_CONF_CTX_set_flags(cctx, SSL_CONF_FLAG_SERVER);
SSL_CONF_CTX_set_flags(cctx, SSL_CONF_FLAG_CMDLINE);
verify_depth = 0;
#ifdef FIONBIO
s_nbio = 0;
#endif
s_nbio_test = 0;
argc--;
argv++;
while (argc >= 1) {
if ((strcmp(*argv, "-port") == 0) || (strcmp(*argv, "-accept") == 0)) {
if (--argc < 1)
goto bad;
if (!extract_port(*(++argv), &port))
goto bad;
} else if (strcmp(*argv, "-naccept") == 0) {
if (--argc < 1)
goto bad;
naccept = atol(*(++argv));
if (naccept <= 0) {
BIO_printf(bio_err, "bad accept value %s\n", *argv);
goto bad;
}
} else if (strcmp(*argv, "-verify") == 0) {
s_server_verify = SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE;
if (--argc < 1)
goto bad;
verify_depth = atoi(*(++argv));
if (!s_quiet)
BIO_printf(bio_err, "verify depth is %d\n", verify_depth);
} else if (strcmp(*argv, "-Verify") == 0) {
s_server_verify =
SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT |
SSL_VERIFY_CLIENT_ONCE;
if (--argc < 1)
goto bad;
verify_depth = atoi(*(++argv));
if (!s_quiet)
BIO_printf(bio_err,
"verify depth is %d, must return a certificate\n",
verify_depth);
} else if (strcmp(*argv, "-context") == 0) {
if (--argc < 1)
goto bad;
context = (unsigned char *)*(++argv);
} else if (strcmp(*argv, "-cert") == 0) {
if (--argc < 1)
goto bad;
s_cert_file = *(++argv);
} else if (strcmp(*argv, "-CRL") == 0) {
if (--argc < 1)
goto bad;
crl_file = *(++argv);
} else if (strcmp(*argv, "-crl_download") == 0)
crl_download = 1;
#ifndef OPENSSL_NO_TLSEXT
else if (strcmp(*argv, "-serverinfo") == 0) {
if (--argc < 1)
goto bad;
s_serverinfo_file = *(++argv);
}
#endif
else if (strcmp(*argv, "-certform") == 0) {
if (--argc < 1)
goto bad;
s_cert_format = str2fmt(*(++argv));
} else if (strcmp(*argv, "-key") == 0) {
if (--argc < 1)
goto bad;
s_key_file = *(++argv);
} else if (strcmp(*argv, "-keyform") == 0) {
if (--argc < 1)
goto bad;
s_key_format = str2fmt(*(++argv));
} else if (strcmp(*argv, "-pass") == 0) {
if (--argc < 1)
goto bad;
passarg = *(++argv);
} else if (strcmp(*argv, "-cert_chain") == 0) {
if (--argc < 1)
goto bad;
s_chain_file = *(++argv);
} else if (strcmp(*argv, "-dhparam") == 0) {
if (--argc < 1)
goto bad;
dhfile = *(++argv);
} else if (strcmp(*argv, "-dcertform") == 0) {
if (--argc < 1)
goto bad;
s_dcert_format = str2fmt(*(++argv));
} else if (strcmp(*argv, "-dcert") == 0) {
if (--argc < 1)
goto bad;
s_dcert_file = *(++argv);
} else if (strcmp(*argv, "-dkeyform") == 0) {
if (--argc < 1)
goto bad;
s_dkey_format = str2fmt(*(++argv));
} else if (strcmp(*argv, "-dpass") == 0) {
if (--argc < 1)
goto bad;
dpassarg = *(++argv);
} else if (strcmp(*argv, "-dkey") == 0) {
if (--argc < 1)
goto bad;
s_dkey_file = *(++argv);
} else if (strcmp(*argv, "-dcert_chain") == 0) {
if (--argc < 1)
goto bad;
s_dchain_file = *(++argv);
} else if (strcmp(*argv, "-nocert") == 0) {
nocert = 1;
} else if (strcmp(*argv, "-CApath") == 0) {
if (--argc < 1)
goto bad;
CApath = *(++argv);
} else if (strcmp(*argv, "-chainCApath") == 0) {
if (--argc < 1)
goto bad;
chCApath = *(++argv);
} else if (strcmp(*argv, "-verifyCApath") == 0) {
if (--argc < 1)
goto bad;
vfyCApath = *(++argv);
} else if (strcmp(*argv, "-no_cache") == 0)
no_cache = 1;
else if (strcmp(*argv, "-ext_cache") == 0)
ext_cache = 1;
else if (strcmp(*argv, "-CRLform") == 0) {
if (--argc < 1)
goto bad;
crl_format = str2fmt(*(++argv));
} else if (args_verify(&argv, &argc, &badarg, bio_err, &vpm)) {
if (badarg)
goto bad;
continue;
} else if (args_excert(&argv, &argc, &badarg, bio_err, &exc)) {
if (badarg)
goto bad;
continue;
} else if (args_ssl(&argv, &argc, cctx, &badarg, bio_err, &ssl_args,
&no_prot_opt)) {
if (badarg)
goto bad;
continue;
} else if (strcmp(*argv, "-verify_return_error") == 0)
verify_return_error = 1;
else if (strcmp(*argv, "-verify_quiet") == 0)
verify_quiet = 1;
else if (strcmp(*argv, "-build_chain") == 0)
build_chain = 1;
else if (strcmp(*argv, "-CAfile") == 0) {
if (--argc < 1)
goto bad;
CAfile = *(++argv);
} else if (strcmp(*argv, "-chainCAfile") == 0) {
if (--argc < 1)
goto bad;
chCAfile = *(++argv);
} else if (strcmp(*argv, "-verifyCAfile") == 0) {
if (--argc < 1)
goto bad;
vfyCAfile = *(++argv);
}
#ifdef FIONBIO
else if (strcmp(*argv, "-nbio") == 0) {
s_nbio = 1;
}
#endif
else if (strcmp(*argv, "-nbio_test") == 0) {
#ifdef FIONBIO
s_nbio = 1;
#endif
s_nbio_test = 1;
} else if (strcmp(*argv, "-ign_eof") == 0)
s_ign_eof = 1;
else if (strcmp(*argv, "-no_ign_eof") == 0)
s_ign_eof = 0;
else if (strcmp(*argv, "-debug") == 0) {
s_debug = 1;
}
#ifndef OPENSSL_NO_TLSEXT
else if (strcmp(*argv, "-tlsextdebug") == 0)
s_tlsextdebug = 1;
else if (strcmp(*argv, "-status") == 0)
s_tlsextstatus = 1;
else if (strcmp(*argv, "-status_verbose") == 0) {
s_tlsextstatus = 1;
tlscstatp.verbose = 1;
} else if (!strcmp(*argv, "-status_timeout")) {
s_tlsextstatus = 1;
if (--argc < 1)
goto bad;
tlscstatp.timeout = atoi(*(++argv));
} else if (!strcmp(*argv, "-status_url")) {
s_tlsextstatus = 1;
if (--argc < 1)
goto bad;
if (!OCSP_parse_url(*(++argv),
&tlscstatp.host,
&tlscstatp.port,
&tlscstatp.path, &tlscstatp.use_ssl)) {
BIO_printf(bio_err, "Error parsing URL\n");
goto bad;
}
}
#endif
else if (strcmp(*argv, "-msg") == 0) {
s_msg = 1;
} else if (strcmp(*argv, "-msgfile") == 0) {
if (--argc < 1)
goto bad;
bio_s_msg = BIO_new_file(*(++argv), "w");
}
#ifndef OPENSSL_NO_SSL_TRACE
else if (strcmp(*argv, "-trace") == 0) {
s_msg = 2;
}
#endif
else if (strcmp(*argv, "-hack") == 0) {
hack = 1;
} else if (strcmp(*argv, "-state") == 0) {
state = 1;
} else if (strcmp(*argv, "-crlf") == 0) {
s_crlf = 1;
} else if (strcmp(*argv, "-quiet") == 0) {
s_quiet = 1;
} else if (strcmp(*argv, "-brief") == 0) {
s_quiet = 1;
s_brief = 1;
verify_quiet = 1;
} else if (strcmp(*argv, "-no_tmp_rsa") == 0) {
no_tmp_rsa = 1;
} else if (strcmp(*argv, "-no_dhe") == 0) {
no_dhe = 1;
} else if (strcmp(*argv, "-no_ecdhe") == 0) {
no_ecdhe = 1;
} else if (strcmp(*argv, "-no_resume_ephemeral") == 0) {
no_resume_ephemeral = 1;
}
#ifndef OPENSSL_NO_PSK
else if (strcmp(*argv, "-psk_hint") == 0) {
if (--argc < 1)
goto bad;
psk_identity_hint = *(++argv);
} else if (strcmp(*argv, "-psk") == 0) {
size_t i;
if (--argc < 1)
goto bad;
psk_key = *(++argv);
for (i = 0; i < strlen(psk_key); i++) {
if (isxdigit((unsigned char)psk_key[i]))
continue;
BIO_printf(bio_err, "Not a hex number '%s'\n", *argv);
goto bad;
}
}
#endif
#ifndef OPENSSL_NO_SRP
else if (strcmp(*argv, "-srpvfile") == 0) {
if (--argc < 1)
goto bad;
srp_verifier_file = *(++argv);
meth = TLSv1_server_method();
} else if (strcmp(*argv, "-srpuserseed") == 0) {
if (--argc < 1)
goto bad;
srpuserseed = *(++argv);
meth = TLSv1_server_method();
}
#endif
else if (strcmp(*argv, "-rev") == 0) {
rev = 1;
} else if (strcmp(*argv, "-www") == 0) {
www = 1;
} else if (strcmp(*argv, "-WWW") == 0) {
www = 2;
} else if (strcmp(*argv, "-HTTP") == 0) {
www = 3;
}
#ifndef OPENSSL_NO_SSL2
else if (strcmp(*argv, "-ssl2") == 0) {
no_ecdhe = 1;
meth = SSLv2_server_method();
prot_opt++;
}
#endif
#ifndef OPENSSL_NO_SSL3_METHOD
else if (strcmp(*argv, "-ssl3") == 0) {
meth = SSLv3_server_method();
prot_opt++;
}
#endif
#ifndef OPENSSL_NO_TLS1
else if (strcmp(*argv, "-tls1") == 0) {
meth = TLSv1_server_method();
prot_opt++;
} else if (strcmp(*argv, "-tls1_1") == 0) {
meth = TLSv1_1_server_method();
prot_opt++;
} else if (strcmp(*argv, "-tls1_2") == 0) {
meth = TLSv1_2_server_method();
prot_opt++;
}
#endif
#ifndef OPENSSL_NO_DTLS1
else if (strcmp(*argv, "-dtls") == 0) {
meth = DTLS_server_method();
socket_type = SOCK_DGRAM;
prot_opt++;
} else if (strcmp(*argv, "-dtls1") == 0) {
meth = DTLSv1_server_method();
socket_type = SOCK_DGRAM;
prot_opt++;
} else if (strcmp(*argv, "-dtls1_2") == 0) {
meth = DTLSv1_2_server_method();
socket_type = SOCK_DGRAM;
prot_opt++;
} else if (strcmp(*argv, "-timeout") == 0)
enable_timeouts = 1;
else if (strcmp(*argv, "-mtu") == 0) {
if (--argc < 1)
goto bad;
socket_mtu = atol(*(++argv));
} else if (strcmp(*argv, "-chain") == 0)
cert_chain = 1;
#endif
else if (strcmp(*argv, "-id_prefix") == 0) {
if (--argc < 1)
goto bad;
session_id_prefix = *(++argv);
}
#ifndef OPENSSL_NO_ENGINE
else if (strcmp(*argv, "-engine") == 0) {
if (--argc < 1)
goto bad;
engine_id = *(++argv);
}
#endif
else if (strcmp(*argv, "-rand") == 0) {
if (--argc < 1)
goto bad;
inrand = *(++argv);
}
#ifndef OPENSSL_NO_TLSEXT
else if (strcmp(*argv, "-servername") == 0) {
if (--argc < 1)
goto bad;
tlsextcbp.servername = *(++argv);
} else if (strcmp(*argv, "-servername_fatal") == 0) {
tlsextcbp.extension_error = SSL_TLSEXT_ERR_ALERT_FATAL;
} else if (strcmp(*argv, "-cert2") == 0) {
if (--argc < 1)
goto bad;
s_cert_file2 = *(++argv);
} else if (strcmp(*argv, "-key2") == 0) {
if (--argc < 1)
goto bad;
s_key_file2 = *(++argv);
}
# ifndef OPENSSL_NO_NEXTPROTONEG
else if (strcmp(*argv, "-nextprotoneg") == 0) {
if (--argc < 1)
goto bad;
next_proto_neg_in = *(++argv);
}
# endif
else if (strcmp(*argv, "-alpn") == 0) {
if (--argc < 1)
goto bad;
alpn_in = *(++argv);
}
#endif
#if !defined(OPENSSL_NO_JPAKE) && !defined(OPENSSL_NO_PSK)
else if (strcmp(*argv, "-jpake") == 0) {
if (--argc < 1)
goto bad;
jpake_secret = *(++argv);
}
#endif
#ifndef OPENSSL_NO_SRTP
else if (strcmp(*argv, "-use_srtp") == 0) {
if (--argc < 1)
goto bad;
srtp_profiles = *(++argv);
}
#endif
else if (strcmp(*argv, "-keymatexport") == 0) {
if (--argc < 1)
goto bad;
keymatexportlabel = *(++argv);
} else if (strcmp(*argv, "-keymatexportlen") == 0) {
if (--argc < 1)
goto bad;
keymatexportlen = atoi(*(++argv));
if (keymatexportlen == 0)
goto bad;
} else {
BIO_printf(bio_err, "unknown option %s\n", *argv);
badop = 1;
break;
}
argc--;
argv++;
}
if (badop) {
bad:
sv_usage();
goto end;
}
#ifndef OPENSSL_NO_DTLS1
if (www && socket_type == SOCK_DGRAM) {
BIO_printf(bio_err, "Can't use -HTTP, -www or -WWW with DTLS\n");
goto end;
}
#endif
#if !defined(OPENSSL_NO_JPAKE) && !defined(OPENSSL_NO_PSK)
if (jpake_secret) {
if (psk_key) {
BIO_printf(bio_err, "Can't use JPAKE and PSK together\n");
goto end;
}
psk_identity = "JPAKE";
}
#endif
if (prot_opt > 1) {
BIO_printf(bio_err, "Cannot supply multiple protocol flags\n");
goto end;
}
if (prot_opt == 1 && no_prot_opt) {
BIO_printf(bio_err, "Cannot supply both a protocol flag and "
"\"-no_<prot>\"\n");
goto end;
}
SSL_load_error_strings();
OpenSSL_add_ssl_algorithms();
e = setup_engine(bio_err, engine_id, 1);
if (!app_passwd(bio_err, passarg, dpassarg, &pass, &dpass)) {
BIO_printf(bio_err, "Error getting password\n");
goto end;
}
if (s_key_file == NULL)
s_key_file = s_cert_file;
#ifndef OPENSSL_NO_TLSEXT
if (s_key_file2 == NULL)
s_key_file2 = s_cert_file2;
#endif
if (!load_excert(&exc, bio_err))
goto end;
if (nocert == 0) {
s_key = load_key(bio_err, s_key_file, s_key_format, 0, pass, e,
"server certificate private key file");
if (!s_key) {
ERR_print_errors(bio_err);
goto end;
}
s_cert = load_cert(bio_err, s_cert_file, s_cert_format,
NULL, e, "server certificate file");
if (!s_cert) {
ERR_print_errors(bio_err);
goto end;
}
if (s_chain_file) {
s_chain = load_certs(bio_err, s_chain_file, FORMAT_PEM,
NULL, e, "server certificate chain");
if (!s_chain)
goto end;
}
#ifndef OPENSSL_NO_TLSEXT
if (tlsextcbp.servername) {
s_key2 = load_key(bio_err, s_key_file2, s_key_format, 0, pass, e,
"second server certificate private key file");
if (!s_key2) {
ERR_print_errors(bio_err);
goto end;
}
s_cert2 = load_cert(bio_err, s_cert_file2, s_cert_format,
NULL, e, "second server certificate file");
if (!s_cert2) {
ERR_print_errors(bio_err);
goto end;
}
}
#endif /* OPENSSL_NO_TLSEXT */
}
#if !defined(OPENSSL_NO_TLSEXT)
# if !defined(OPENSSL_NO_NEXTPROTONEG)
if (next_proto_neg_in) {
unsigned short len;
next_proto.data = next_protos_parse(&len, next_proto_neg_in);
if (next_proto.data == NULL)
goto end;
next_proto.len = len;
} else {
next_proto.data = NULL;
}
# endif
alpn_ctx.data = NULL;
if (alpn_in) {
unsigned short len;
alpn_ctx.data = next_protos_parse(&len, alpn_in);
if (alpn_ctx.data == NULL)
goto end;
alpn_ctx.len = len;
}
#endif
if (crl_file) {
X509_CRL *crl;
crl = load_crl(crl_file, crl_format);
if (!crl) {
BIO_puts(bio_err, "Error loading CRL\n");
ERR_print_errors(bio_err);
goto end;
}
crls = sk_X509_CRL_new_null();
if (!crls || !sk_X509_CRL_push(crls, crl)) {
BIO_puts(bio_err, "Error adding CRL\n");
ERR_print_errors(bio_err);
X509_CRL_free(crl);
goto end;
}
}
if (s_dcert_file) {
if (s_dkey_file == NULL)
s_dkey_file = s_dcert_file;
s_dkey = load_key(bio_err, s_dkey_file, s_dkey_format,
0, dpass, e, "second certificate private key file");
if (!s_dkey) {
ERR_print_errors(bio_err);
goto end;
}
s_dcert = load_cert(bio_err, s_dcert_file, s_dcert_format,
NULL, e, "second server certificate file");
if (!s_dcert) {
ERR_print_errors(bio_err);
goto end;
}
if (s_dchain_file) {
s_dchain = load_certs(bio_err, s_dchain_file, FORMAT_PEM,
NULL, e, "second server certificate chain");
if (!s_dchain)
goto end;
}
}
if (!app_RAND_load_file(NULL, bio_err, 1) && inrand == NULL
&& !RAND_status()) {
BIO_printf(bio_err,
"warning, not much extra random data, consider using the -rand option\n");
}
if (inrand != NULL)
BIO_printf(bio_err, "%ld semi-random bytes loaded\n",
app_RAND_load_files(inrand));
if (bio_s_out == NULL) {
if (s_quiet && !s_debug) {
bio_s_out = BIO_new(BIO_s_null());
if (s_msg && !bio_s_msg)
bio_s_msg = BIO_new_fp(stdout, BIO_NOCLOSE);
} else {
if (bio_s_out == NULL)
bio_s_out = BIO_new_fp(stdout, BIO_NOCLOSE);
}
}
#if !defined(OPENSSL_NO_RSA) || !defined(OPENSSL_NO_DSA) || !defined(OPENSSL_NO_ECDSA)
if (nocert)
#endif
{
s_cert_file = NULL;
s_key_file = NULL;
s_dcert_file = NULL;
s_dkey_file = NULL;
#ifndef OPENSSL_NO_TLSEXT
s_cert_file2 = NULL;
s_key_file2 = NULL;
#endif
}
ctx = SSL_CTX_new(meth);
if (ctx == NULL) {
ERR_print_errors(bio_err);
goto end;
}
if (session_id_prefix) {
if (strlen(session_id_prefix) >= 32)
BIO_printf(bio_err,
"warning: id_prefix is too long, only one new session will be possible\n");
else if (strlen(session_id_prefix) >= 16)
BIO_printf(bio_err,
"warning: id_prefix is too long if you use SSLv2\n");
if (!SSL_CTX_set_generate_session_id(ctx, generate_session_id)) {
BIO_printf(bio_err, "error setting 'id_prefix'\n");
ERR_print_errors(bio_err);
goto end;
}
BIO_printf(bio_err, "id_prefix '%s' set.\n", session_id_prefix);
}
SSL_CTX_set_quiet_shutdown(ctx, 1);
if (hack)
SSL_CTX_set_options(ctx, SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG);
if (exc)
ssl_ctx_set_excert(ctx, exc);
if (state)
SSL_CTX_set_info_callback(ctx, apps_ssl_info_callback);
if (no_cache)
SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
else if (ext_cache)
init_session_cache_ctx(ctx);
else
SSL_CTX_sess_set_cache_size(ctx, 128);
#ifndef OPENSSL_NO_SRTP
if (srtp_profiles != NULL)
SSL_CTX_set_tlsext_use_srtp(ctx, srtp_profiles);
#endif
#if 0
if (cipher == NULL)
cipher = getenv("SSL_CIPHER");
#endif
#if 0
if (s_cert_file == NULL) {
BIO_printf(bio_err,
"You must specify a certificate file for the server to use\n");
goto end;
}
#endif
if ((!SSL_CTX_load_verify_locations(ctx, CAfile, CApath)) ||
(!SSL_CTX_set_default_verify_paths(ctx))) {
/* BIO_printf(bio_err,"X509_load_verify_locations\n"); */
ERR_print_errors(bio_err);
/* goto end; */
}
if (vpm)
SSL_CTX_set1_param(ctx, vpm);
ssl_ctx_add_crls(ctx, crls, 0);
if (!args_ssl_call(ctx, bio_err, cctx, ssl_args, no_ecdhe, no_jpake))
goto end;
if (!ssl_load_stores(ctx, vfyCApath, vfyCAfile, chCApath, chCAfile,
crls, crl_download)) {
BIO_printf(bio_err, "Error loading store locations\n");
ERR_print_errors(bio_err);
goto end;
}
#ifndef OPENSSL_NO_TLSEXT
if (s_cert2) {
ctx2 = SSL_CTX_new(meth);
if (ctx2 == NULL) {
ERR_print_errors(bio_err);
goto end;
}
}
if (ctx2) {
BIO_printf(bio_s_out, "Setting secondary ctx parameters\n");
if (session_id_prefix) {
if (strlen(session_id_prefix) >= 32)
BIO_printf(bio_err,
"warning: id_prefix is too long, only one new session will be possible\n");
else if (strlen(session_id_prefix) >= 16)
BIO_printf(bio_err,
"warning: id_prefix is too long if you use SSLv2\n");
if (!SSL_CTX_set_generate_session_id(ctx2, generate_session_id)) {
BIO_printf(bio_err, "error setting 'id_prefix'\n");
ERR_print_errors(bio_err);
goto end;
}
BIO_printf(bio_err, "id_prefix '%s' set.\n", session_id_prefix);
}
SSL_CTX_set_quiet_shutdown(ctx2, 1);
if (hack)
SSL_CTX_set_options(ctx2, SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG);
if (exc)
ssl_ctx_set_excert(ctx2, exc);
if (state)
SSL_CTX_set_info_callback(ctx2, apps_ssl_info_callback);
if (no_cache)
SSL_CTX_set_session_cache_mode(ctx2, SSL_SESS_CACHE_OFF);
else if (ext_cache)
init_session_cache_ctx(ctx2);
else
SSL_CTX_sess_set_cache_size(ctx2, 128);
if ((!SSL_CTX_load_verify_locations(ctx2, CAfile, CApath)) ||
(!SSL_CTX_set_default_verify_paths(ctx2))) {
ERR_print_errors(bio_err);
}
if (vpm)
SSL_CTX_set1_param(ctx2, vpm);
ssl_ctx_add_crls(ctx2, crls, 0);
if (!args_ssl_call(ctx2, bio_err, cctx, ssl_args, no_ecdhe, no_jpake))
goto end;
}
# ifndef OPENSSL_NO_NEXTPROTONEG
if (next_proto.data)
SSL_CTX_set_next_protos_advertised_cb(ctx, next_proto_cb,
&next_proto);
# endif
if (alpn_ctx.data)
SSL_CTX_set_alpn_select_cb(ctx, alpn_cb, &alpn_ctx);
#endif
#ifndef OPENSSL_NO_DH
if (!no_dhe) {
DH *dh = NULL;
if (dhfile)
dh = load_dh_param(dhfile);
else if (s_cert_file)
dh = load_dh_param(s_cert_file);
if (dh != NULL) {
BIO_printf(bio_s_out, "Setting temp DH parameters\n");
} else {
BIO_printf(bio_s_out, "Using default temp DH parameters\n");
dh = get_dh2048();
if (dh == NULL) {
ERR_print_errors(bio_err);
goto end;
}
}
(void)BIO_flush(bio_s_out);
SSL_CTX_set_tmp_dh(ctx, dh);
# ifndef OPENSSL_NO_TLSEXT
if (ctx2) {
if (!dhfile) {
DH *dh2 = load_dh_param(s_cert_file2);
if (dh2 != NULL) {
BIO_printf(bio_s_out, "Setting temp DH parameters\n");
(void)BIO_flush(bio_s_out);
DH_free(dh);
dh = dh2;
}
}
SSL_CTX_set_tmp_dh(ctx2, dh);
}
# endif
DH_free(dh);
}
#endif
if (!set_cert_key_stuff(ctx, s_cert, s_key, s_chain, build_chain))
goto end;
#ifndef OPENSSL_NO_TLSEXT
if (s_serverinfo_file != NULL
&& !SSL_CTX_use_serverinfo_file(ctx, s_serverinfo_file)) {
ERR_print_errors(bio_err);
goto end;
}
#endif
#ifndef OPENSSL_NO_TLSEXT
if (ctx2 && !set_cert_key_stuff(ctx2, s_cert2, s_key2, NULL, build_chain))
goto end;
#endif
if (s_dcert != NULL) {
if (!set_cert_key_stuff(ctx, s_dcert, s_dkey, s_dchain, build_chain))
goto end;
}
#ifndef OPENSSL_NO_RSA
# if 1
if (!no_tmp_rsa) {
SSL_CTX_set_tmp_rsa_callback(ctx, tmp_rsa_cb);
# ifndef OPENSSL_NO_TLSEXT
if (ctx2)
SSL_CTX_set_tmp_rsa_callback(ctx2, tmp_rsa_cb);
# endif
}
# else
if (!no_tmp_rsa && SSL_CTX_need_tmp_RSA(ctx)) {
RSA *rsa;
BIO_printf(bio_s_out, "Generating temp (512 bit) RSA key...");
BIO_flush(bio_s_out);
rsa = RSA_generate_key(512, RSA_F4, NULL);
if (!SSL_CTX_set_tmp_rsa(ctx, rsa)) {
ERR_print_errors(bio_err);
goto end;
}
# ifndef OPENSSL_NO_TLSEXT
if (ctx2) {
if (!SSL_CTX_set_tmp_rsa(ctx2, rsa)) {
ERR_print_errors(bio_err);
goto end;
}
}
# endif
RSA_free(rsa);
BIO_printf(bio_s_out, "\n");
}
# endif
#endif
#ifndef OPENSSL_NO_PSK
# ifdef OPENSSL_NO_JPAKE
if (psk_key != NULL)
# else
if (psk_key != NULL || jpake_secret)
# endif
{
if (s_debug)
BIO_printf(bio_s_out,
"PSK key given or JPAKE in use, setting server callback\n");
SSL_CTX_set_psk_server_callback(ctx, psk_server_cb);
}
if (!SSL_CTX_use_psk_identity_hint(ctx, psk_identity_hint)) {
BIO_printf(bio_err, "error setting PSK identity hint to context\n");
ERR_print_errors(bio_err);
goto end;
}
#endif
SSL_CTX_set_verify(ctx, s_server_verify, verify_callback);
SSL_CTX_set_session_id_context(ctx, (void *)&s_server_session_id_context,
- sizeof s_server_session_id_context);
+ sizeof(s_server_session_id_context));
/* Set DTLS cookie generation and verification callbacks */
SSL_CTX_set_cookie_generate_cb(ctx, generate_cookie_callback);
SSL_CTX_set_cookie_verify_cb(ctx, verify_cookie_callback);
#ifndef OPENSSL_NO_TLSEXT
if (ctx2) {
SSL_CTX_set_verify(ctx2, s_server_verify, verify_callback);
SSL_CTX_set_session_id_context(ctx2,
(void *)&s_server_session_id_context,
- sizeof s_server_session_id_context);
+ sizeof(s_server_session_id_context));
tlsextcbp.biodebug = bio_s_out;
SSL_CTX_set_tlsext_servername_callback(ctx2, ssl_servername_cb);
SSL_CTX_set_tlsext_servername_arg(ctx2, &tlsextcbp);
SSL_CTX_set_tlsext_servername_callback(ctx, ssl_servername_cb);
SSL_CTX_set_tlsext_servername_arg(ctx, &tlsextcbp);
}
#endif
#ifndef OPENSSL_NO_SRP
if (srp_verifier_file != NULL) {
srp_callback_parm.vb = SRP_VBASE_new(srpuserseed);
srp_callback_parm.user = NULL;
srp_callback_parm.login = NULL;
if ((ret =
SRP_VBASE_init(srp_callback_parm.vb,
srp_verifier_file)) != SRP_NO_ERROR) {
BIO_printf(bio_err,
"Cannot initialize SRP verifier file \"%s\":ret=%d\n",
srp_verifier_file, ret);
goto end;
}
SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, verify_callback);
SSL_CTX_set_srp_cb_arg(ctx, &srp_callback_parm);
SSL_CTX_set_srp_username_callback(ctx, ssl_srp_server_param_cb);
} else
#endif
if (CAfile != NULL) {
SSL_CTX_set_client_CA_list(ctx, SSL_load_client_CA_file(CAfile));
#ifndef OPENSSL_NO_TLSEXT
if (ctx2)
SSL_CTX_set_client_CA_list(ctx2, SSL_load_client_CA_file(CAfile));
#endif
}
BIO_printf(bio_s_out, "ACCEPT\n");
(void)BIO_flush(bio_s_out);
if (rev)
do_server(port, socket_type, &accept_socket, rev_body, context,
naccept);
else if (www)
do_server(port, socket_type, &accept_socket, www_body, context,
naccept);
else
do_server(port, socket_type, &accept_socket, sv_body, context,
naccept);
print_stats(bio_s_out, ctx);
ret = 0;
end:
if (ctx != NULL)
SSL_CTX_free(ctx);
if (s_cert)
X509_free(s_cert);
if (crls)
sk_X509_CRL_pop_free(crls, X509_CRL_free);
if (s_dcert)
X509_free(s_dcert);
if (s_key)
EVP_PKEY_free(s_key);
if (s_dkey)
EVP_PKEY_free(s_dkey);
if (s_chain)
sk_X509_pop_free(s_chain, X509_free);
if (s_dchain)
sk_X509_pop_free(s_dchain, X509_free);
if (pass)
OPENSSL_free(pass);
if (dpass)
OPENSSL_free(dpass);
if (vpm)
X509_VERIFY_PARAM_free(vpm);
free_sessions();
#ifndef OPENSSL_NO_TLSEXT
if (tlscstatp.host)
OPENSSL_free(tlscstatp.host);
if (tlscstatp.port)
OPENSSL_free(tlscstatp.port);
if (tlscstatp.path)
OPENSSL_free(tlscstatp.path);
if (ctx2 != NULL)
SSL_CTX_free(ctx2);
if (s_cert2)
X509_free(s_cert2);
if (s_key2)
EVP_PKEY_free(s_key2);
if (serverinfo_in != NULL)
BIO_free(serverinfo_in);
# ifndef OPENSSL_NO_NEXTPROTONEG
if (next_proto.data)
OPENSSL_free(next_proto.data);
# endif
if (alpn_ctx.data)
OPENSSL_free(alpn_ctx.data);
#endif
ssl_excert_free(exc);
if (ssl_args)
sk_OPENSSL_STRING_free(ssl_args);
if (cctx)
SSL_CONF_CTX_free(cctx);
#ifndef OPENSSL_NO_JPAKE
if (jpake_secret && psk_key)
OPENSSL_free(psk_key);
#endif
release_engine(e);
if (bio_s_out != NULL) {
BIO_free(bio_s_out);
bio_s_out = NULL;
}
if (bio_s_msg != NULL) {
BIO_free(bio_s_msg);
bio_s_msg = NULL;
}
SSL_COMP_free_compression_methods();
apps_shutdown();
OPENSSL_EXIT(ret);
}
static void print_stats(BIO *bio, SSL_CTX *ssl_ctx)
{
BIO_printf(bio, "%4ld items in the session cache\n",
SSL_CTX_sess_number(ssl_ctx));
BIO_printf(bio, "%4ld client connects (SSL_connect())\n",
SSL_CTX_sess_connect(ssl_ctx));
BIO_printf(bio, "%4ld client renegotiates (SSL_connect())\n",
SSL_CTX_sess_connect_renegotiate(ssl_ctx));
BIO_printf(bio, "%4ld client connects that finished\n",
SSL_CTX_sess_connect_good(ssl_ctx));
BIO_printf(bio, "%4ld server accepts (SSL_accept())\n",
SSL_CTX_sess_accept(ssl_ctx));
BIO_printf(bio, "%4ld server renegotiates (SSL_accept())\n",
SSL_CTX_sess_accept_renegotiate(ssl_ctx));
BIO_printf(bio, "%4ld server accepts that finished\n",
SSL_CTX_sess_accept_good(ssl_ctx));
BIO_printf(bio, "%4ld session cache hits\n", SSL_CTX_sess_hits(ssl_ctx));
BIO_printf(bio, "%4ld session cache misses\n",
SSL_CTX_sess_misses(ssl_ctx));
BIO_printf(bio, "%4ld session cache timeouts\n",
SSL_CTX_sess_timeouts(ssl_ctx));
BIO_printf(bio, "%4ld callback cache hits\n",
SSL_CTX_sess_cb_hits(ssl_ctx));
BIO_printf(bio, "%4ld cache full overflows (%ld allowed)\n",
SSL_CTX_sess_cache_full(ssl_ctx),
SSL_CTX_sess_get_cache_size(ssl_ctx));
}
static int sv_body(char *hostname, int s, int stype, unsigned char *context)
{
char *buf = NULL;
fd_set readfds;
int ret = 1, width;
int k, i;
unsigned long l;
SSL *con = NULL;
BIO *sbio;
#ifndef OPENSSL_NO_KRB5
KSSL_CTX *kctx;
#endif
struct timeval timeout;
#if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS) || defined(OPENSSL_SYS_NETWARE) || defined(OPENSSL_SYS_BEOS_R5)
struct timeval tv;
#else
struct timeval *timeoutp;
#endif
if ((buf = OPENSSL_malloc(bufsize)) == NULL) {
BIO_printf(bio_err, "out of memory\n");
goto err;
}
#ifdef FIONBIO
if (s_nbio) {
unsigned long sl = 1;
if (!s_quiet)
BIO_printf(bio_err, "turning on non blocking io\n");
if (BIO_socket_ioctl(s, FIONBIO, &sl) < 0)
ERR_print_errors(bio_err);
}
#endif
if (con == NULL) {
con = SSL_new(ctx);
#ifndef OPENSSL_NO_TLSEXT
if (s_tlsextdebug) {
SSL_set_tlsext_debug_callback(con, tlsext_cb);
SSL_set_tlsext_debug_arg(con, bio_s_out);
}
if (s_tlsextstatus) {
SSL_CTX_set_tlsext_status_cb(ctx, cert_status_cb);
tlscstatp.err = bio_err;
SSL_CTX_set_tlsext_status_arg(ctx, &tlscstatp);
}
#endif
#ifndef OPENSSL_NO_KRB5
if ((kctx = kssl_ctx_new()) != NULL) {
SSL_set0_kssl_ctx(con, kctx);
kssl_ctx_setstring(kctx, KSSL_SERVICE, KRB5SVC);
kssl_ctx_setstring(kctx, KSSL_KEYTAB, KRB5KEYTAB);
}
#endif /* OPENSSL_NO_KRB5 */
if (context)
SSL_set_session_id_context(con, context, strlen((char *)context));
}
SSL_clear(con);
#if 0
# ifdef TLSEXT_TYPE_opaque_prf_input
SSL_set_tlsext_opaque_prf_input(con, "Test server", 11);
# endif
#endif
if (stype == SOCK_DGRAM) {
sbio = BIO_new_dgram(s, BIO_NOCLOSE);
if (enable_timeouts) {
timeout.tv_sec = 0;
timeout.tv_usec = DGRAM_RCV_TIMEOUT;
BIO_ctrl(sbio, BIO_CTRL_DGRAM_SET_RECV_TIMEOUT, 0, &timeout);
timeout.tv_sec = 0;
timeout.tv_usec = DGRAM_SND_TIMEOUT;
BIO_ctrl(sbio, BIO_CTRL_DGRAM_SET_SEND_TIMEOUT, 0, &timeout);
}
if (socket_mtu) {
if (socket_mtu < DTLS_get_link_min_mtu(con)) {
BIO_printf(bio_err, "MTU too small. Must be at least %ld\n",
DTLS_get_link_min_mtu(con));
ret = -1;
BIO_free(sbio);
goto err;
}
SSL_set_options(con, SSL_OP_NO_QUERY_MTU);
if (!DTLS_set_link_mtu(con, socket_mtu)) {
BIO_printf(bio_err, "Failed to set MTU\n");
ret = -1;
BIO_free(sbio);
goto err;
}
} else
/* want to do MTU discovery */
BIO_ctrl(sbio, BIO_CTRL_DGRAM_MTU_DISCOVER, 0, NULL);
/* turn on cookie exchange */
SSL_set_options(con, SSL_OP_COOKIE_EXCHANGE);
} else
sbio = BIO_new_socket(s, BIO_NOCLOSE);
if (s_nbio_test) {
BIO *test;
test = BIO_new(BIO_f_nbio_test());
sbio = BIO_push(test, sbio);
}
#ifndef OPENSSL_NO_JPAKE
if (jpake_secret)
jpake_server_auth(bio_s_out, sbio, jpake_secret);
#endif
SSL_set_bio(con, sbio, sbio);
SSL_set_accept_state(con);
/* SSL_set_fd(con,s); */
if (s_debug) {
SSL_set_debug(con, 1);
BIO_set_callback(SSL_get_rbio(con), bio_dump_callback);
BIO_set_callback_arg(SSL_get_rbio(con), (char *)bio_s_out);
}
if (s_msg) {
#ifndef OPENSSL_NO_SSL_TRACE
if (s_msg == 2)
SSL_set_msg_callback(con, SSL_trace);
else
#endif
SSL_set_msg_callback(con, msg_cb);
SSL_set_msg_callback_arg(con, bio_s_msg ? bio_s_msg : bio_s_out);
}
#ifndef OPENSSL_NO_TLSEXT
if (s_tlsextdebug) {
SSL_set_tlsext_debug_callback(con, tlsext_cb);
SSL_set_tlsext_debug_arg(con, bio_s_out);
}
#endif
if (fileno_stdin() > s)
width = fileno_stdin() + 1;
else
width = s + 1;
for (;;) {
int read_from_terminal;
int read_from_sslcon;
read_from_terminal = 0;
read_from_sslcon = SSL_pending(con);
if (!read_from_sslcon) {
FD_ZERO(&readfds);
#if !defined(OPENSSL_SYS_WINDOWS) && !defined(OPENSSL_SYS_MSDOS) && !defined(OPENSSL_SYS_NETWARE) && !defined(OPENSSL_SYS_BEOS_R5)
openssl_fdset(fileno_stdin(), &readfds);
#endif
openssl_fdset(s, &readfds);
/*
* Note: under VMS with SOCKETSHR the second parameter is
* currently of type (int *) whereas under other systems it is
* (void *) if you don't have a cast it will choke the compiler:
* if you do have a cast then you can either go for (int *) or
* (void *).
*/
#if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS) || defined(OPENSSL_SYS_NETWARE)
/*
* Under DOS (non-djgpp) and Windows we can't select on stdin:
* only on sockets. As a workaround we timeout the select every
* second and check for any keypress. In a proper Windows
* application we wouldn't do this because it is inefficient.
*/
tv.tv_sec = 1;
tv.tv_usec = 0;
i = select(width, (void *)&readfds, NULL, NULL, &tv);
if ((i < 0) || (!i && !_kbhit()))
continue;
if (_kbhit())
read_from_terminal = 1;
#elif defined(OPENSSL_SYS_BEOS_R5)
/* Under BeOS-R5 the situation is similar to DOS */
tv.tv_sec = 1;
tv.tv_usec = 0;
(void)fcntl(fileno_stdin(), F_SETFL, O_NONBLOCK);
i = select(width, (void *)&readfds, NULL, NULL, &tv);
if ((i < 0) || (!i && read(fileno_stdin(), buf, 0) < 0))
continue;
if (read(fileno_stdin(), buf, 0) >= 0)
read_from_terminal = 1;
(void)fcntl(fileno_stdin(), F_SETFL, 0);
#else
if ((SSL_version(con) == DTLS1_VERSION) &&
DTLSv1_get_timeout(con, &timeout))
timeoutp = &timeout;
else
timeoutp = NULL;
i = select(width, (void *)&readfds, NULL, NULL, timeoutp);
if ((SSL_version(con) == DTLS1_VERSION)
&& DTLSv1_handle_timeout(con) > 0) {
BIO_printf(bio_err, "TIMEOUT occured\n");
}
if (i <= 0)
continue;
if (FD_ISSET(fileno_stdin(), &readfds))
read_from_terminal = 1;
#endif
if (FD_ISSET(s, &readfds))
read_from_sslcon = 1;
}
if (read_from_terminal) {
if (s_crlf) {
int j, lf_num;
i = raw_read_stdin(buf, bufsize / 2);
lf_num = 0;
/* both loops are skipped when i <= 0 */
for (j = 0; j < i; j++)
if (buf[j] == '\n')
lf_num++;
for (j = i - 1; j >= 0; j--) {
buf[j + lf_num] = buf[j];
if (buf[j] == '\n') {
lf_num--;
i++;
buf[j + lf_num] = '\r';
}
}
assert(lf_num == 0);
} else
i = raw_read_stdin(buf, bufsize);
if (!s_quiet && !s_brief) {
if ((i <= 0) || (buf[0] == 'Q')) {
BIO_printf(bio_s_out, "DONE\n");
SHUTDOWN(s);
close_accept_socket();
ret = -11;
goto err;
}
if ((i <= 0) || (buf[0] == 'q')) {
BIO_printf(bio_s_out, "DONE\n");
if (SSL_version(con) != DTLS1_VERSION)
SHUTDOWN(s);
/*
* close_accept_socket(); ret= -11;
*/
goto err;
}
#ifndef OPENSSL_NO_HEARTBEATS
if ((buf[0] == 'B') && ((buf[1] == '\n') || (buf[1] == '\r'))) {
BIO_printf(bio_err, "HEARTBEATING\n");
SSL_heartbeat(con);
i = 0;
continue;
}
#endif
if ((buf[0] == 'r') && ((buf[1] == '\n') || (buf[1] == '\r'))) {
SSL_renegotiate(con);
i = SSL_do_handshake(con);
printf("SSL_do_handshake -> %d\n", i);
i = 0; /* 13; */
continue;
/*
* strcpy(buf,"server side RE-NEGOTIATE\n");
*/
}
if ((buf[0] == 'R') && ((buf[1] == '\n') || (buf[1] == '\r'))) {
SSL_set_verify(con,
SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE,
NULL);
SSL_renegotiate(con);
i = SSL_do_handshake(con);
printf("SSL_do_handshake -> %d\n", i);
i = 0; /* 13; */
continue;
/*
* strcpy(buf,"server side RE-NEGOTIATE asking for client
* cert\n");
*/
}
if (buf[0] == 'P') {
static const char *str = "Lets print some clear text\n";
BIO_write(SSL_get_wbio(con), str, strlen(str));
}
if (buf[0] == 'S') {
print_stats(bio_s_out, SSL_get_SSL_CTX(con));
}
}
#ifdef CHARSET_EBCDIC
ebcdic2ascii(buf, buf, i);
#endif
l = k = 0;
for (;;) {
/* should do a select for the write */
#ifdef RENEG
{
static count = 0;
if (++count == 100) {
count = 0;
SSL_renegotiate(con);
}
}
#endif
k = SSL_write(con, &(buf[l]), (unsigned int)i);
#ifndef OPENSSL_NO_SRP
while (SSL_get_error(con, k) == SSL_ERROR_WANT_X509_LOOKUP) {
BIO_printf(bio_s_out, "LOOKUP renego during write\n");
SRP_user_pwd_free(srp_callback_parm.user);
srp_callback_parm.user =
SRP_VBASE_get1_by_user(srp_callback_parm.vb,
srp_callback_parm.login);
if (srp_callback_parm.user)
BIO_printf(bio_s_out, "LOOKUP done %s\n",
srp_callback_parm.user->info);
else
BIO_printf(bio_s_out, "LOOKUP not successful\n");
k = SSL_write(con, &(buf[l]), (unsigned int)i);
}
#endif
switch (SSL_get_error(con, k)) {
case SSL_ERROR_NONE:
break;
case SSL_ERROR_WANT_WRITE:
case SSL_ERROR_WANT_READ:
case SSL_ERROR_WANT_X509_LOOKUP:
BIO_printf(bio_s_out, "Write BLOCK\n");
break;
case SSL_ERROR_SYSCALL:
case SSL_ERROR_SSL:
BIO_printf(bio_s_out, "ERROR\n");
ERR_print_errors(bio_err);
ret = 1;
goto err;
/* break; */
case SSL_ERROR_ZERO_RETURN:
BIO_printf(bio_s_out, "DONE\n");
ret = 1;
goto err;
}
if (k > 0) {
l += k;
i -= k;
}
if (i <= 0)
break;
}
}
if (read_from_sslcon) {
if (!SSL_is_init_finished(con)) {
i = init_ssl_connection(con);
if (i < 0) {
ret = 0;
goto err;
} else if (i == 0) {
ret = 1;
goto err;
}
} else {
again:
i = SSL_read(con, (char *)buf, bufsize);
#ifndef OPENSSL_NO_SRP
while (SSL_get_error(con, i) == SSL_ERROR_WANT_X509_LOOKUP) {
BIO_printf(bio_s_out, "LOOKUP renego during read\n");
SRP_user_pwd_free(srp_callback_parm.user);
srp_callback_parm.user =
SRP_VBASE_get1_by_user(srp_callback_parm.vb,
srp_callback_parm.login);
if (srp_callback_parm.user)
BIO_printf(bio_s_out, "LOOKUP done %s\n",
srp_callback_parm.user->info);
else
BIO_printf(bio_s_out, "LOOKUP not successful\n");
i = SSL_read(con, (char *)buf, bufsize);
}
#endif
switch (SSL_get_error(con, i)) {
case SSL_ERROR_NONE:
#ifdef CHARSET_EBCDIC
ascii2ebcdic(buf, buf, i);
#endif
raw_write_stdout(buf, (unsigned int)i);
if (SSL_pending(con))
goto again;
break;
case SSL_ERROR_WANT_WRITE:
case SSL_ERROR_WANT_READ:
BIO_printf(bio_s_out, "Read BLOCK\n");
break;
case SSL_ERROR_SYSCALL:
case SSL_ERROR_SSL:
BIO_printf(bio_s_out, "ERROR\n");
ERR_print_errors(bio_err);
ret = 1;
goto err;
case SSL_ERROR_ZERO_RETURN:
BIO_printf(bio_s_out, "DONE\n");
ret = 1;
goto err;
}
}
}
}
err:
if (con != NULL) {
BIO_printf(bio_s_out, "shutting down SSL\n");
#if 1
SSL_set_shutdown(con, SSL_SENT_SHUTDOWN | SSL_RECEIVED_SHUTDOWN);
#else
SSL_shutdown(con);
#endif
SSL_free(con);
}
BIO_printf(bio_s_out, "CONNECTION CLOSED\n");
if (buf != NULL) {
OPENSSL_cleanse(buf, bufsize);
OPENSSL_free(buf);
}
if (ret >= 0)
BIO_printf(bio_s_out, "ACCEPT\n");
return (ret);
}
static void close_accept_socket(void)
{
BIO_printf(bio_err, "shutdown accept socket\n");
if (accept_socket >= 0) {
SHUTDOWN2(accept_socket);
}
}
static int init_ssl_connection(SSL *con)
{
int i;
const char *str;
X509 *peer;
long verify_error;
MS_STATIC char buf[BUFSIZ];
#ifndef OPENSSL_NO_KRB5
char *client_princ;
#endif
#if !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_NEXTPROTONEG)
const unsigned char *next_proto_neg;
unsigned next_proto_neg_len;
#endif
unsigned char *exportedkeymat;
i = SSL_accept(con);
#ifdef CERT_CB_TEST_RETRY
{
while (i <= 0 && SSL_get_error(con, i) == SSL_ERROR_WANT_X509_LOOKUP
&& SSL_state(con) == SSL3_ST_SR_CLNT_HELLO_C) {
fprintf(stderr,
"LOOKUP from certificate callback during accept\n");
i = SSL_accept(con);
}
}
#endif
#ifndef OPENSSL_NO_SRP
while (i <= 0 && SSL_get_error(con, i) == SSL_ERROR_WANT_X509_LOOKUP) {
BIO_printf(bio_s_out, "LOOKUP during accept %s\n",
srp_callback_parm.login);
SRP_user_pwd_free(srp_callback_parm.user);
srp_callback_parm.user =
SRP_VBASE_get1_by_user(srp_callback_parm.vb,
srp_callback_parm.login);
if (srp_callback_parm.user)
BIO_printf(bio_s_out, "LOOKUP done %s\n",
srp_callback_parm.user->info);
else
BIO_printf(bio_s_out, "LOOKUP not successful\n");
i = SSL_accept(con);
}
#endif
if (i <= 0) {
if (BIO_sock_should_retry(i)) {
BIO_printf(bio_s_out, "DELAY\n");
return (1);
}
BIO_printf(bio_err, "ERROR\n");
verify_error = SSL_get_verify_result(con);
if (verify_error != X509_V_OK) {
BIO_printf(bio_err, "verify error:%s\n",
X509_verify_cert_error_string(verify_error));
}
/* Always print any error messages */
ERR_print_errors(bio_err);
return (0);
}
if (s_brief)
print_ssl_summary(bio_err, con);
PEM_write_bio_SSL_SESSION(bio_s_out, SSL_get_session(con));
peer = SSL_get_peer_certificate(con);
if (peer != NULL) {
BIO_printf(bio_s_out, "Client certificate\n");
PEM_write_bio_X509(bio_s_out, peer);
- X509_NAME_oneline(X509_get_subject_name(peer), buf, sizeof buf);
+ X509_NAME_oneline(X509_get_subject_name(peer), buf, sizeof(buf));
BIO_printf(bio_s_out, "subject=%s\n", buf);
- X509_NAME_oneline(X509_get_issuer_name(peer), buf, sizeof buf);
+ X509_NAME_oneline(X509_get_issuer_name(peer), buf, sizeof(buf));
BIO_printf(bio_s_out, "issuer=%s\n", buf);
X509_free(peer);
}
- if (SSL_get_shared_ciphers(con, buf, sizeof buf) != NULL)
+ if (SSL_get_shared_ciphers(con, buf, sizeof(buf)) != NULL)
BIO_printf(bio_s_out, "Shared ciphers:%s\n", buf);
str = SSL_CIPHER_get_name(SSL_get_current_cipher(con));
ssl_print_sigalgs(bio_s_out, con);
#ifndef OPENSSL_NO_EC
ssl_print_point_formats(bio_s_out, con);
ssl_print_curves(bio_s_out, con, 0);
#endif
BIO_printf(bio_s_out, "CIPHER is %s\n", (str != NULL) ? str : "(NONE)");
#if !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_NEXTPROTONEG)
SSL_get0_next_proto_negotiated(con, &next_proto_neg, &next_proto_neg_len);
if (next_proto_neg) {
BIO_printf(bio_s_out, "NEXTPROTO is ");
BIO_write(bio_s_out, next_proto_neg, next_proto_neg_len);
BIO_printf(bio_s_out, "\n");
}
#endif
#ifndef OPENSSL_NO_SRTP
{
SRTP_PROTECTION_PROFILE *srtp_profile
= SSL_get_selected_srtp_profile(con);
if (srtp_profile)
BIO_printf(bio_s_out, "SRTP Extension negotiated, profile=%s\n",
srtp_profile->name);
}
#endif
if (SSL_cache_hit(con))
BIO_printf(bio_s_out, "Reused session-id\n");
if (SSL_ctrl(con, SSL_CTRL_GET_FLAGS, 0, NULL) &
TLS1_FLAGS_TLS_PADDING_BUG)
BIO_printf(bio_s_out, "Peer has incorrect TLSv1 block padding\n");
#ifndef OPENSSL_NO_KRB5
client_princ = kssl_ctx_get0_client_princ(SSL_get0_kssl_ctx(con));
if (client_princ != NULL) {
BIO_printf(bio_s_out, "Kerberos peer principal is %s\n",
client_princ);
}
#endif /* OPENSSL_NO_KRB5 */
BIO_printf(bio_s_out, "Secure Renegotiation IS%s supported\n",
SSL_get_secure_renegotiation_support(con) ? "" : " NOT");
if (keymatexportlabel != NULL) {
BIO_printf(bio_s_out, "Keying material exporter:\n");
BIO_printf(bio_s_out, " Label: '%s'\n", keymatexportlabel);
BIO_printf(bio_s_out, " Length: %i bytes\n", keymatexportlen);
exportedkeymat = OPENSSL_malloc(keymatexportlen);
if (exportedkeymat != NULL) {
if (!SSL_export_keying_material(con, exportedkeymat,
keymatexportlen,
keymatexportlabel,
strlen(keymatexportlabel),
NULL, 0, 0)) {
BIO_printf(bio_s_out, " Error\n");
} else {
BIO_printf(bio_s_out, " Keying material: ");
for (i = 0; i < keymatexportlen; i++)
BIO_printf(bio_s_out, "%02X", exportedkeymat[i]);
BIO_printf(bio_s_out, "\n");
}
OPENSSL_free(exportedkeymat);
}
}
return (1);
}
#ifndef OPENSSL_NO_DH
static DH *load_dh_param(const char *dhfile)
{
DH *ret = NULL;
BIO *bio;
if ((bio = BIO_new_file(dhfile, "r")) == NULL)
goto err;
ret = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
err:
if (bio != NULL)
BIO_free(bio);
return (ret);
}
#endif
#ifndef OPENSSL_NO_KRB5
char *client_princ;
#endif
#if 0
static int load_CA(SSL_CTX *ctx, char *file)
{
FILE *in;
X509 *x = NULL;
if ((in = fopen(file, "r")) == NULL)
return (0);
for (;;) {
if (PEM_read_X509(in, &x, NULL) == NULL)
break;
SSL_CTX_add_client_CA(ctx, x);
}
if (x != NULL)
X509_free(x);
fclose(in);
return (1);
}
#endif
static int www_body(char *hostname, int s, int stype, unsigned char *context)
{
char *buf = NULL;
int ret = 1;
int i, j, k, dot;
SSL *con;
const SSL_CIPHER *c;
BIO *io, *ssl_bio, *sbio;
#ifndef OPENSSL_NO_KRB5
KSSL_CTX *kctx;
#endif
buf = OPENSSL_malloc(bufsize);
if (buf == NULL)
return (0);
io = BIO_new(BIO_f_buffer());
ssl_bio = BIO_new(BIO_f_ssl());
if ((io == NULL) || (ssl_bio == NULL))
goto err;
#ifdef FIONBIO
if (s_nbio) {
unsigned long sl = 1;
if (!s_quiet)
BIO_printf(bio_err, "turning on non blocking io\n");
if (BIO_socket_ioctl(s, FIONBIO, &sl) < 0)
ERR_print_errors(bio_err);
}
#endif
/* lets make the output buffer a reasonable size */
if (!BIO_set_write_buffer_size(io, bufsize))
goto err;
if ((con = SSL_new(ctx)) == NULL)
goto err;
#ifndef OPENSSL_NO_TLSEXT
if (s_tlsextdebug) {
SSL_set_tlsext_debug_callback(con, tlsext_cb);
SSL_set_tlsext_debug_arg(con, bio_s_out);
}
#endif
#ifndef OPENSSL_NO_KRB5
if ((kctx = kssl_ctx_new()) != NULL) {
kssl_ctx_setstring(kctx, KSSL_SERVICE, KRB5SVC);
kssl_ctx_setstring(kctx, KSSL_KEYTAB, KRB5KEYTAB);
}
#endif /* OPENSSL_NO_KRB5 */
if (context)
SSL_set_session_id_context(con, context, strlen((char *)context));
sbio = BIO_new_socket(s, BIO_NOCLOSE);
if (s_nbio_test) {
BIO *test;
test = BIO_new(BIO_f_nbio_test());
sbio = BIO_push(test, sbio);
}
SSL_set_bio(con, sbio, sbio);
SSL_set_accept_state(con);
/* SSL_set_fd(con,s); */
BIO_set_ssl(ssl_bio, con, BIO_CLOSE);
BIO_push(io, ssl_bio);
#ifdef CHARSET_EBCDIC
io = BIO_push(BIO_new(BIO_f_ebcdic_filter()), io);
#endif
if (s_debug) {
SSL_set_debug(con, 1);
BIO_set_callback(SSL_get_rbio(con), bio_dump_callback);
BIO_set_callback_arg(SSL_get_rbio(con), (char *)bio_s_out);
}
if (s_msg) {
#ifndef OPENSSL_NO_SSL_TRACE
if (s_msg == 2)
SSL_set_msg_callback(con, SSL_trace);
else
#endif
SSL_set_msg_callback(con, msg_cb);
SSL_set_msg_callback_arg(con, bio_s_msg ? bio_s_msg : bio_s_out);
}
for (;;) {
if (hack) {
i = SSL_accept(con);
#ifndef OPENSSL_NO_SRP
while (i <= 0
&& SSL_get_error(con, i) == SSL_ERROR_WANT_X509_LOOKUP) {
BIO_printf(bio_s_out, "LOOKUP during accept %s\n",
srp_callback_parm.login);
SRP_user_pwd_free(srp_callback_parm.user);
srp_callback_parm.user =
SRP_VBASE_get1_by_user(srp_callback_parm.vb,
srp_callback_parm.login);
if (srp_callback_parm.user)
BIO_printf(bio_s_out, "LOOKUP done %s\n",
srp_callback_parm.user->info);
else
BIO_printf(bio_s_out, "LOOKUP not successful\n");
i = SSL_accept(con);
}
#endif
switch (SSL_get_error(con, i)) {
case SSL_ERROR_NONE:
break;
case SSL_ERROR_WANT_WRITE:
case SSL_ERROR_WANT_READ:
case SSL_ERROR_WANT_X509_LOOKUP:
continue;
case SSL_ERROR_SYSCALL:
case SSL_ERROR_SSL:
case SSL_ERROR_ZERO_RETURN:
ret = 1;
goto err;
/* break; */
}
SSL_renegotiate(con);
SSL_write(con, NULL, 0);
}
i = BIO_gets(io, buf, bufsize - 1);
if (i < 0) { /* error */
if (!BIO_should_retry(io)) {
if (!s_quiet)
ERR_print_errors(bio_err);
goto err;
} else {
BIO_printf(bio_s_out, "read R BLOCK\n");
#ifndef OPENSSL_NO_SRP
if (BIO_should_io_special(io)
&& BIO_get_retry_reason(io) == BIO_RR_SSL_X509_LOOKUP) {
BIO_printf(bio_s_out, "LOOKUP renego during read\n");
SRP_user_pwd_free(srp_callback_parm.user);
srp_callback_parm.user =
SRP_VBASE_get1_by_user(srp_callback_parm.vb,
srp_callback_parm.login);
if (srp_callback_parm.user)
BIO_printf(bio_s_out, "LOOKUP done %s\n",
srp_callback_parm.user->info);
else
BIO_printf(bio_s_out, "LOOKUP not successful\n");
continue;
}
#endif
#if defined(OPENSSL_SYS_NETWARE)
delay(1000);
#elif !defined(OPENSSL_SYS_MSDOS) && !defined(__DJGPP__)
sleep(1);
#endif
continue;
}
} else if (i == 0) { /* end of input */
ret = 1;
goto end;
}
/* else we have data */
if (((www == 1) && (strncmp("GET ", buf, 4) == 0)) ||
((www == 2) && (strncmp("GET /stats ", buf, 11) == 0))) {
char *p;
X509 *peer;
STACK_OF(SSL_CIPHER) *sk;
static const char *space = " ";
BIO_puts(io,
"HTTP/1.0 200 ok\r\nContent-type: text/html\r\n\r\n");
BIO_puts(io, "<HTML><BODY BGCOLOR=\"#ffffff\">\n");
BIO_puts(io, "<pre>\n");
/* BIO_puts(io,SSLeay_version(SSLEAY_VERSION));*/
BIO_puts(io, "\n");
for (i = 0; i < local_argc; i++) {
BIO_puts(io, local_argv[i]);
BIO_write(io, " ", 1);
}
BIO_puts(io, "\n");
BIO_printf(io,
"Secure Renegotiation IS%s supported\n",
SSL_get_secure_renegotiation_support(con) ?
"" : " NOT");
/*
* The following is evil and should not really be done
*/
BIO_printf(io, "Ciphers supported in s_server binary\n");
sk = SSL_get_ciphers(con);
j = sk_SSL_CIPHER_num(sk);
for (i = 0; i < j; i++) {
c = sk_SSL_CIPHER_value(sk, i);
BIO_printf(io, "%-11s:%-25s",
SSL_CIPHER_get_version(c), SSL_CIPHER_get_name(c));
if ((((i + 1) % 2) == 0) && (i + 1 != j))
BIO_puts(io, "\n");
}
BIO_puts(io, "\n");
p = SSL_get_shared_ciphers(con, buf, bufsize);
if (p != NULL) {
BIO_printf(io,
"---\nCiphers common between both SSL end points:\n");
j = i = 0;
while (*p) {
if (*p == ':') {
BIO_write(io, space, 26 - j);
i++;
j = 0;
BIO_write(io, ((i % 3) ? " " : "\n"), 1);
} else {
BIO_write(io, p, 1);
j++;
}
p++;
}
BIO_puts(io, "\n");
}
ssl_print_sigalgs(io, con);
#ifndef OPENSSL_NO_EC
ssl_print_curves(io, con, 0);
#endif
BIO_printf(io, (SSL_cache_hit(con)
? "---\nReused, " : "---\nNew, "));
c = SSL_get_current_cipher(con);
BIO_printf(io, "%s, Cipher is %s\n",
SSL_CIPHER_get_version(c), SSL_CIPHER_get_name(c));
SSL_SESSION_print(io, SSL_get_session(con));
BIO_printf(io, "---\n");
print_stats(io, SSL_get_SSL_CTX(con));
BIO_printf(io, "---\n");
peer = SSL_get_peer_certificate(con);
if (peer != NULL) {
BIO_printf(io, "Client certificate\n");
X509_print(io, peer);
PEM_write_bio_X509(io, peer);
} else
BIO_puts(io, "no client certificate available\n");
BIO_puts(io, "</pre></BODY></HTML>\r\n\r\n");
break;
} else if ((www == 2 || www == 3)
&& (strncmp("GET /", buf, 5) == 0)) {
BIO *file;
char *p, *e;
static const char *text =
"HTTP/1.0 200 ok\r\nContent-type: text/plain\r\n\r\n";
/* skip the '/' */
p = &(buf[5]);
dot = 1;
for (e = p; *e != '\0'; e++) {
if (e[0] == ' ')
break;
switch (dot) {
case 1:
dot = (e[0] == '.') ? 2 : 0;
break;
case 2:
dot = (e[0] == '.') ? 3 : 0;
break;
case 3:
dot = (e[0] == '/') ? -1 : 0;
break;
}
if (dot == 0)
dot = (e[0] == '/') ? 1 : 0;
}
dot = (dot == 3) || (dot == -1); /* filename contains ".."
* component */
if (*e == '\0') {
BIO_puts(io, text);
BIO_printf(io, "'%s' is an invalid file name\r\n", p);
break;
}
*e = '\0';
if (dot) {
BIO_puts(io, text);
BIO_printf(io, "'%s' contains '..' reference\r\n", p);
break;
}
if (*p == '/') {
BIO_puts(io, text);
BIO_printf(io, "'%s' is an invalid path\r\n", p);
break;
}
#if 0
/* append if a directory lookup */
if (e[-1] == '/')
strcat(p, "index.html");
#endif
/* if a directory, do the index thang */
if (app_isdir(p) > 0) {
#if 0 /* must check buffer size */
strcat(p, "/index.html");
#else
BIO_puts(io, text);
BIO_printf(io, "'%s' is a directory\r\n", p);
break;
#endif
}
if ((file = BIO_new_file(p, "r")) == NULL) {
BIO_puts(io, text);
BIO_printf(io, "Error opening '%s'\r\n", p);
ERR_print_errors(io);
break;
}
if (!s_quiet)
BIO_printf(bio_err, "FILE:%s\n", p);
if (www == 2) {
i = strlen(p);
if (((i > 5) && (strcmp(&(p[i - 5]), ".html") == 0)) ||
((i > 4) && (strcmp(&(p[i - 4]), ".php") == 0)) ||
((i > 4) && (strcmp(&(p[i - 4]), ".htm") == 0)))
BIO_puts(io,
"HTTP/1.0 200 ok\r\nContent-type: text/html\r\n\r\n");
else
BIO_puts(io,
"HTTP/1.0 200 ok\r\nContent-type: text/plain\r\n\r\n");
}
/* send the file */
for (;;) {
i = BIO_read(file, buf, bufsize);
if (i <= 0)
break;
#ifdef RENEG
total_bytes += i;
fprintf(stderr, "%d\n", i);
if (total_bytes > 3 * 1024) {
total_bytes = 0;
fprintf(stderr, "RENEGOTIATE\n");
SSL_renegotiate(con);
}
#endif
for (j = 0; j < i;) {
#ifdef RENEG
{
static count = 0;
if (++count == 13) {
SSL_renegotiate(con);
}
}
#endif
k = BIO_write(io, &(buf[j]), i - j);
if (k <= 0) {
if (!BIO_should_retry(io))
goto write_error;
else {
BIO_printf(bio_s_out, "rwrite W BLOCK\n");
}
} else {
j += k;
}
}
}
write_error:
BIO_free(file);
break;
}
}
for (;;) {
i = (int)BIO_flush(io);
if (i <= 0) {
if (!BIO_should_retry(io))
break;
} else
break;
}
end:
#if 1
/* make sure we re-use sessions */
SSL_set_shutdown(con, SSL_SENT_SHUTDOWN | SSL_RECEIVED_SHUTDOWN);
#else
/* This kills performance */
/*
* SSL_shutdown(con); A shutdown gets sent in the BIO_free_all(io)
* procession
*/
#endif
err:
if (ret >= 0)
BIO_printf(bio_s_out, "ACCEPT\n");
if (buf != NULL)
OPENSSL_free(buf);
if (io != NULL)
BIO_free_all(io);
/* if (ssl_bio != NULL) BIO_free(ssl_bio);*/
return (ret);
}
static int rev_body(char *hostname, int s, int stype, unsigned char *context)
{
char *buf = NULL;
int i;
int ret = 1;
SSL *con;
BIO *io, *ssl_bio, *sbio;
#ifndef OPENSSL_NO_KRB5
KSSL_CTX *kctx;
#endif
buf = OPENSSL_malloc(bufsize);
if (buf == NULL)
return (0);
io = BIO_new(BIO_f_buffer());
ssl_bio = BIO_new(BIO_f_ssl());
if ((io == NULL) || (ssl_bio == NULL))
goto err;
/* lets make the output buffer a reasonable size */
if (!BIO_set_write_buffer_size(io, bufsize))
goto err;
if ((con = SSL_new(ctx)) == NULL)
goto err;
#ifndef OPENSSL_NO_TLSEXT
if (s_tlsextdebug) {
SSL_set_tlsext_debug_callback(con, tlsext_cb);
SSL_set_tlsext_debug_arg(con, bio_s_out);
}
#endif
#ifndef OPENSSL_NO_KRB5
if ((kctx = kssl_ctx_new()) != NULL) {
kssl_ctx_setstring(kctx, KSSL_SERVICE, KRB5SVC);
kssl_ctx_setstring(kctx, KSSL_KEYTAB, KRB5KEYTAB);
}
#endif /* OPENSSL_NO_KRB5 */
if (context)
SSL_set_session_id_context(con, context, strlen((char *)context));
sbio = BIO_new_socket(s, BIO_NOCLOSE);
SSL_set_bio(con, sbio, sbio);
SSL_set_accept_state(con);
BIO_set_ssl(ssl_bio, con, BIO_CLOSE);
BIO_push(io, ssl_bio);
#ifdef CHARSET_EBCDIC
io = BIO_push(BIO_new(BIO_f_ebcdic_filter()), io);
#endif
if (s_debug) {
SSL_set_debug(con, 1);
BIO_set_callback(SSL_get_rbio(con), bio_dump_callback);
BIO_set_callback_arg(SSL_get_rbio(con), (char *)bio_s_out);
}
if (s_msg) {
#ifndef OPENSSL_NO_SSL_TRACE
if (s_msg == 2)
SSL_set_msg_callback(con, SSL_trace);
else
#endif
SSL_set_msg_callback(con, msg_cb);
SSL_set_msg_callback_arg(con, bio_s_msg ? bio_s_msg : bio_s_out);
}
for (;;) {
i = BIO_do_handshake(io);
if (i > 0)
break;
if (!BIO_should_retry(io)) {
BIO_puts(bio_err, "CONNECTION FAILURE\n");
ERR_print_errors(bio_err);
goto end;
}
#ifndef OPENSSL_NO_SRP
if (BIO_should_io_special(io)
&& BIO_get_retry_reason(io) == BIO_RR_SSL_X509_LOOKUP) {
BIO_printf(bio_s_out, "LOOKUP renego during accept\n");
SRP_user_pwd_free(srp_callback_parm.user);
srp_callback_parm.user =
SRP_VBASE_get1_by_user(srp_callback_parm.vb,
srp_callback_parm.login);
if (srp_callback_parm.user)
BIO_printf(bio_s_out, "LOOKUP done %s\n",
srp_callback_parm.user->info);
else
BIO_printf(bio_s_out, "LOOKUP not successful\n");
continue;
}
#endif
}
BIO_printf(bio_err, "CONNECTION ESTABLISHED\n");
print_ssl_summary(bio_err, con);
for (;;) {
i = BIO_gets(io, buf, bufsize - 1);
if (i < 0) { /* error */
if (!BIO_should_retry(io)) {
if (!s_quiet)
ERR_print_errors(bio_err);
goto err;
} else {
BIO_printf(bio_s_out, "read R BLOCK\n");
#ifndef OPENSSL_NO_SRP
if (BIO_should_io_special(io)
&& BIO_get_retry_reason(io) == BIO_RR_SSL_X509_LOOKUP) {
BIO_printf(bio_s_out, "LOOKUP renego during read\n");
SRP_user_pwd_free(srp_callback_parm.user);
srp_callback_parm.user =
SRP_VBASE_get1_by_user(srp_callback_parm.vb,
srp_callback_parm.login);
if (srp_callback_parm.user)
BIO_printf(bio_s_out, "LOOKUP done %s\n",
srp_callback_parm.user->info);
else
BIO_printf(bio_s_out, "LOOKUP not successful\n");
continue;
}
#endif
#if defined(OPENSSL_SYS_NETWARE)
delay(1000);
#elif !defined(OPENSSL_SYS_MSDOS) && !defined(__DJGPP__)
sleep(1);
#endif
continue;
}
} else if (i == 0) { /* end of input */
ret = 1;
BIO_printf(bio_err, "CONNECTION CLOSED\n");
goto end;
} else {
char *p = buf + i - 1;
while (i && (*p == '\n' || *p == '\r')) {
p--;
i--;
}
if (!s_ign_eof && i == 5 && !strncmp(buf, "CLOSE", 5)) {
ret = 1;
BIO_printf(bio_err, "CONNECTION CLOSED\n");
goto end;
}
BUF_reverse((unsigned char *)buf, NULL, i);
buf[i] = '\n';
BIO_write(io, buf, i + 1);
for (;;) {
i = BIO_flush(io);
if (i > 0)
break;
if (!BIO_should_retry(io))
goto end;
}
}
}
end:
/* make sure we re-use sessions */
SSL_set_shutdown(con, SSL_SENT_SHUTDOWN | SSL_RECEIVED_SHUTDOWN);
err:
if (buf != NULL)
OPENSSL_free(buf);
if (io != NULL)
BIO_free_all(io);
return (ret);
}
#ifndef OPENSSL_NO_RSA
static RSA MS_CALLBACK *tmp_rsa_cb(SSL *s, int is_export, int keylength)
{
BIGNUM *bn = NULL;
static RSA *rsa_tmp = NULL;
if (!rsa_tmp && ((bn = BN_new()) == NULL))
BIO_printf(bio_err, "Allocation error in generating RSA key\n");
if (!rsa_tmp && bn) {
if (!s_quiet) {
BIO_printf(bio_err, "Generating temp (%d bit) RSA key...",
keylength);
(void)BIO_flush(bio_err);
}
if (!BN_set_word(bn, RSA_F4) || ((rsa_tmp = RSA_new()) == NULL) ||
!RSA_generate_key_ex(rsa_tmp, keylength, bn, NULL)) {
if (rsa_tmp)
RSA_free(rsa_tmp);
rsa_tmp = NULL;
}
if (!s_quiet) {
BIO_printf(bio_err, "\n");
(void)BIO_flush(bio_err);
}
BN_free(bn);
}
return (rsa_tmp);
}
#endif
#define MAX_SESSION_ID_ATTEMPTS 10
static int generate_session_id(const SSL *ssl, unsigned char *id,
unsigned int *id_len)
{
unsigned int count = 0;
do {
if (RAND_bytes(id, *id_len) <= 0)
return 0;
/*
* Prefix the session_id with the required prefix. NB: If our prefix
* is too long, clip it - but there will be worse effects anyway, eg.
* the server could only possibly create 1 session ID (ie. the
* prefix!) so all future session negotiations will fail due to
* conflicts.
*/
memcpy(id, session_id_prefix,
(strlen(session_id_prefix) < *id_len) ?
strlen(session_id_prefix) : *id_len);
}
while (SSL_has_matching_session_id(ssl, id, *id_len) &&
(++count < MAX_SESSION_ID_ATTEMPTS));
if (count >= MAX_SESSION_ID_ATTEMPTS)
return 0;
return 1;
}
/*
* By default s_server uses an in-memory cache which caches SSL_SESSION
* structures without any serialisation. This hides some bugs which only
* become apparent in deployed servers. By implementing a basic external
* session cache some issues can be debugged using s_server.
*/
typedef struct simple_ssl_session_st {
unsigned char *id;
unsigned int idlen;
unsigned char *der;
int derlen;
struct simple_ssl_session_st *next;
} simple_ssl_session;
static simple_ssl_session *first = NULL;
static int add_session(SSL *ssl, SSL_SESSION *session)
{
simple_ssl_session *sess;
unsigned char *p;
sess = OPENSSL_malloc(sizeof(simple_ssl_session));
if (!sess) {
BIO_printf(bio_err, "Out of memory adding session to external cache\n");
return 0;
}
SSL_SESSION_get_id(session, &sess->idlen);
sess->derlen = i2d_SSL_SESSION(session, NULL);
sess->id = BUF_memdup(SSL_SESSION_get_id(session, NULL), sess->idlen);
sess->der = OPENSSL_malloc(sess->derlen);
if (!sess->id || !sess->der) {
BIO_printf(bio_err, "Out of memory adding session to external cache\n");
if (sess->id)
OPENSSL_free(sess->id);
if (sess->der)
OPENSSL_free(sess->der);
OPENSSL_free(sess);
return 0;
}
p = sess->der;
i2d_SSL_SESSION(session, &p);
sess->next = first;
first = sess;
BIO_printf(bio_err, "New session added to external cache\n");
return 0;
}
static SSL_SESSION *get_session(SSL *ssl, unsigned char *id, int idlen,
int *do_copy)
{
simple_ssl_session *sess;
*do_copy = 0;
for (sess = first; sess; sess = sess->next) {
if (idlen == (int)sess->idlen && !memcmp(sess->id, id, idlen)) {
const unsigned char *p = sess->der;
BIO_printf(bio_err, "Lookup session: cache hit\n");
return d2i_SSL_SESSION(NULL, &p, sess->derlen);
}
}
BIO_printf(bio_err, "Lookup session: cache miss\n");
return NULL;
}
static void del_session(SSL_CTX *sctx, SSL_SESSION *session)
{
simple_ssl_session *sess, *prev = NULL;
const unsigned char *id;
unsigned int idlen;
id = SSL_SESSION_get_id(session, &idlen);
for (sess = first; sess; sess = sess->next) {
if (idlen == sess->idlen && !memcmp(sess->id, id, idlen)) {
if (prev)
prev->next = sess->next;
else
first = sess->next;
OPENSSL_free(sess->id);
OPENSSL_free(sess->der);
OPENSSL_free(sess);
return;
}
prev = sess;
}
}
static void init_session_cache_ctx(SSL_CTX *sctx)
{
SSL_CTX_set_session_cache_mode(sctx,
SSL_SESS_CACHE_NO_INTERNAL |
SSL_SESS_CACHE_SERVER);
SSL_CTX_sess_set_new_cb(sctx, add_session);
SSL_CTX_sess_set_get_cb(sctx, get_session);
SSL_CTX_sess_set_remove_cb(sctx, del_session);
}
static void free_sessions(void)
{
simple_ssl_session *sess, *tsess;
for (sess = first; sess;) {
OPENSSL_free(sess->id);
OPENSSL_free(sess->der);
tsess = sess;
sess = sess->next;
OPENSSL_free(tsess);
}
first = NULL;
}
diff --git a/apps/s_socket.c b/apps/s_socket.c
index 77a7688f8d0c..83624ca84f15 100644
--- a/apps/s_socket.c
+++ b/apps/s_socket.c
@@ -1,613 +1,613 @@
/*
* apps/s_socket.c - socket-related functions used by s_client and s_server
*/
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <signal.h>
#ifdef FLAT_INC
# include "e_os2.h"
#else
# include "../e_os2.h"
#endif
/*
* With IPv6, it looks like Digital has mixed up the proper order of
* recursive header file inclusion, resulting in the compiler complaining
* that u_int isn't defined, but only if _POSIX_C_SOURCE is defined, which is
* needed to have fileno() declared correctly... So let's define u_int
*/
#if defined(OPENSSL_SYS_VMS_DECC) && !defined(__U_INT)
# define __U_INT
typedef unsigned int u_int;
#endif
#define USE_SOCKETS
#define NON_MAIN
#include "apps.h"
#undef USE_SOCKETS
#undef NON_MAIN
#include "s_apps.h"
#include <openssl/ssl.h>
#ifdef FLAT_INC
# include "e_os.h"
#else
# include "../e_os.h"
#endif
#ifndef OPENSSL_NO_SOCK
# if defined(OPENSSL_SYS_NETWARE) && defined(NETWARE_BSDSOCK)
# include "netdb.h"
# endif
static struct hostent *GetHostByName(char *name);
# if defined(OPENSSL_SYS_WINDOWS) || (defined(OPENSSL_SYS_NETWARE) && !defined(NETWARE_BSDSOCK))
static void ssl_sock_cleanup(void);
# endif
static int ssl_sock_init(void);
static int init_client_ip(int *sock, unsigned char ip[4], int port, int type);
static int init_server(int *sock, int port, int type);
static int init_server_long(int *sock, int port, char *ip, int type);
static int do_accept(int acc_sock, int *sock, char **host);
static int host_ip(char *str, unsigned char ip[4]);
# ifdef OPENSSL_SYS_WIN16
# define SOCKET_PROTOCOL 0 /* more microsoft stupidity */
# else
# define SOCKET_PROTOCOL IPPROTO_TCP
# endif
# if defined(OPENSSL_SYS_NETWARE) && !defined(NETWARE_BSDSOCK)
static int wsa_init_done = 0;
# endif
# ifdef OPENSSL_SYS_WINDOWS
static struct WSAData wsa_state;
static int wsa_init_done = 0;
# ifdef OPENSSL_SYS_WIN16
static HWND topWnd = 0;
static FARPROC lpTopWndProc = NULL;
static FARPROC lpTopHookProc = NULL;
extern HINSTANCE _hInstance; /* nice global CRT provides */
static LONG FAR PASCAL topHookProc(HWND hwnd, UINT message, WPARAM wParam,
LPARAM lParam)
{
if (hwnd == topWnd) {
switch (message) {
case WM_DESTROY:
case WM_CLOSE:
SetWindowLong(topWnd, GWL_WNDPROC, (LONG) lpTopWndProc);
ssl_sock_cleanup();
break;
}
}
return CallWindowProc(lpTopWndProc, hwnd, message, wParam, lParam);
}
static BOOL CALLBACK enumproc(HWND hwnd, LPARAM lParam)
{
topWnd = hwnd;
return (FALSE);
}
# endif /* OPENSSL_SYS_WIN32 */
# endif /* OPENSSL_SYS_WINDOWS */
# ifdef OPENSSL_SYS_WINDOWS
static void ssl_sock_cleanup(void)
{
if (wsa_init_done) {
wsa_init_done = 0;
# ifndef OPENSSL_SYS_WINCE
WSACancelBlockingCall();
# endif
WSACleanup();
}
}
# elif defined(OPENSSL_SYS_NETWARE) && !defined(NETWARE_BSDSOCK)
static void sock_cleanup(void)
{
if (wsa_init_done) {
wsa_init_done = 0;
WSACleanup();
}
}
# endif
static int ssl_sock_init(void)
{
# ifdef WATT32
extern int _watt_do_exit;
_watt_do_exit = 0;
if (sock_init())
return (0);
# elif defined(OPENSSL_SYS_WINDOWS)
if (!wsa_init_done) {
int err;
# ifdef SIGINT
signal(SIGINT, (void (*)(int))ssl_sock_cleanup);
# endif
wsa_init_done = 1;
memset(&wsa_state, 0, sizeof(wsa_state));
if (WSAStartup(0x0101, &wsa_state) != 0) {
err = WSAGetLastError();
BIO_printf(bio_err, "unable to start WINSOCK, error code=%d\n",
err);
return (0);
}
# ifdef OPENSSL_SYS_WIN16
EnumTaskWindows(GetCurrentTask(), enumproc, 0L);
lpTopWndProc = (FARPROC) GetWindowLong(topWnd, GWL_WNDPROC);
lpTopHookProc = MakeProcInstance((FARPROC) topHookProc, _hInstance);
SetWindowLong(topWnd, GWL_WNDPROC, (LONG) lpTopHookProc);
# endif /* OPENSSL_SYS_WIN16 */
}
# elif defined(OPENSSL_SYS_NETWARE) && !defined(NETWARE_BSDSOCK)
WORD wVerReq;
WSADATA wsaData;
int err;
if (!wsa_init_done) {
# ifdef SIGINT
signal(SIGINT, (void (*)(int))sock_cleanup);
# endif
wsa_init_done = 1;
wVerReq = MAKEWORD(2, 0);
err = WSAStartup(wVerReq, &wsaData);
if (err != 0) {
BIO_printf(bio_err, "unable to start WINSOCK2, error code=%d\n",
err);
return (0);
}
}
# endif /* OPENSSL_SYS_WINDOWS */
return (1);
}
int init_client(int *sock, char *host, int port, int type)
{
unsigned char ip[4];
- memset(ip, '\0', sizeof ip);
+ memset(ip, '\0', sizeof(ip));
if (!host_ip(host, &(ip[0])))
return 0;
return init_client_ip(sock, ip, port, type);
}
static int init_client_ip(int *sock, unsigned char ip[4], int port, int type)
{
unsigned long addr;
struct sockaddr_in them;
int s, i;
if (!ssl_sock_init())
return (0);
memset((char *)&them, 0, sizeof(them));
them.sin_family = AF_INET;
them.sin_port = htons((unsigned short)port);
addr = (unsigned long)
((unsigned long)ip[0] << 24L) |
((unsigned long)ip[1] << 16L) |
((unsigned long)ip[2] << 8L) | ((unsigned long)ip[3]);
them.sin_addr.s_addr = htonl(addr);
if (type == SOCK_STREAM)
s = socket(AF_INET, SOCK_STREAM, SOCKET_PROTOCOL);
else /* ( type == SOCK_DGRAM) */
s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (s == INVALID_SOCKET) {
perror("socket");
return (0);
}
# if defined(SO_KEEPALIVE) && !defined(OPENSSL_SYS_MPE)
if (type == SOCK_STREAM) {
i = 0;
i = setsockopt(s, SOL_SOCKET, SO_KEEPALIVE, (char *)&i, sizeof(i));
if (i < 0) {
closesocket(s);
perror("keepalive");
return (0);
}
}
# endif
if (connect(s, (struct sockaddr *)&them, sizeof(them)) == -1) {
closesocket(s);
perror("connect");
return (0);
}
*sock = s;
return (1);
}
int do_server(int port, int type, int *ret,
int (*cb) (char *hostname, int s, int stype,
unsigned char *context), unsigned char *context,
int naccept)
{
int sock;
char *name = NULL;
int accept_socket = 0;
int i;
if (!init_server(&accept_socket, port, type))
return (0);
if (ret != NULL) {
*ret = accept_socket;
/* return(1); */
}
for (;;) {
if (type == SOCK_STREAM) {
if (do_accept(accept_socket, &sock, &name) == 0) {
SHUTDOWN(accept_socket);
return (0);
}
} else
sock = accept_socket;
i = (*cb) (name, sock, type, context);
if (name != NULL)
OPENSSL_free(name);
if (type == SOCK_STREAM)
SHUTDOWN2(sock);
if (naccept != -1)
naccept--;
if (i < 0 || naccept == 0) {
SHUTDOWN2(accept_socket);
return (i);
}
}
}
static int init_server_long(int *sock, int port, char *ip, int type)
{
int ret = 0;
struct sockaddr_in server;
int s = -1;
if (!ssl_sock_init())
return (0);
memset((char *)&server, 0, sizeof(server));
server.sin_family = AF_INET;
server.sin_port = htons((unsigned short)port);
if (ip == NULL)
server.sin_addr.s_addr = INADDR_ANY;
else
/* Added for T3E, address-of fails on bit field (beckman@acl.lanl.gov) */
# ifndef BIT_FIELD_LIMITS
memcpy(&server.sin_addr.s_addr, ip, 4);
# else
memcpy(&server.sin_addr, ip, 4);
# endif
if (type == SOCK_STREAM)
s = socket(AF_INET, SOCK_STREAM, SOCKET_PROTOCOL);
else /* type == SOCK_DGRAM */
s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (s == INVALID_SOCKET)
goto err;
# if defined SOL_SOCKET && defined SO_REUSEADDR
{
int j = 1;
- setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (void *)&j, sizeof j);
+ setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (void *)&j, sizeof(j));
}
# endif
if (bind(s, (struct sockaddr *)&server, sizeof(server)) == -1) {
# ifndef OPENSSL_SYS_WINDOWS
perror("bind");
# endif
goto err;
}
/* Make it 128 for linux */
if (type == SOCK_STREAM && listen(s, 128) == -1)
goto err;
*sock = s;
ret = 1;
err:
if ((ret == 0) && (s != -1)) {
SHUTDOWN(s);
}
return (ret);
}
static int init_server(int *sock, int port, int type)
{
return (init_server_long(sock, port, NULL, type));
}
static int do_accept(int acc_sock, int *sock, char **host)
{
int ret;
struct hostent *h1, *h2;
static struct sockaddr_in from;
int len;
/* struct linger ling; */
if (!ssl_sock_init())
return (0);
# ifndef OPENSSL_SYS_WINDOWS
redoit:
# endif
memset((char *)&from, 0, sizeof(from));
len = sizeof(from);
/*
* Note: under VMS with SOCKETSHR the fourth parameter is currently of
* type (int *) whereas under other systems it is (void *) if you don't
* have a cast it will choke the compiler: if you do have a cast then you
* can either go for (int *) or (void *).
*/
ret = accept(acc_sock, (struct sockaddr *)&from, (void *)&len);
if (ret == INVALID_SOCKET) {
# if defined(OPENSSL_SYS_WINDOWS) || (defined(OPENSSL_SYS_NETWARE) && !defined(NETWARE_BSDSOCK))
int i;
i = WSAGetLastError();
BIO_printf(bio_err, "accept error %d\n", i);
# else
if (errno == EINTR) {
/*
* check_timeout();
*/
goto redoit;
}
fprintf(stderr, "errno=%d ", errno);
perror("accept");
# endif
return (0);
}
/*-
ling.l_onoff=1;
ling.l_linger=0;
i=setsockopt(ret,SOL_SOCKET,SO_LINGER,(char *)&ling,sizeof(ling));
if (i < 0) { perror("linger"); return(0); }
i=0;
i=setsockopt(ret,SOL_SOCKET,SO_KEEPALIVE,(char *)&i,sizeof(i));
if (i < 0) { perror("keepalive"); return(0); }
*/
if (host == NULL)
goto end;
# ifndef BIT_FIELD_LIMITS
/* I should use WSAAsyncGetHostByName() under windows */
h1 = gethostbyaddr((char *)&from.sin_addr.s_addr,
sizeof(from.sin_addr.s_addr), AF_INET);
# else
h1 = gethostbyaddr((char *)&from.sin_addr,
sizeof(struct in_addr), AF_INET);
# endif
if (h1 == NULL) {
BIO_printf(bio_err, "bad gethostbyaddr\n");
*host = NULL;
/* return(0); */
} else {
if ((*host = (char *)OPENSSL_malloc(strlen(h1->h_name) + 1)) == NULL) {
perror("OPENSSL_malloc");
closesocket(ret);
return (0);
}
BUF_strlcpy(*host, h1->h_name, strlen(h1->h_name) + 1);
h2 = GetHostByName(*host);
if (h2 == NULL) {
BIO_printf(bio_err, "gethostbyname failure\n");
closesocket(ret);
return (0);
}
if (h2->h_addrtype != AF_INET) {
BIO_printf(bio_err, "gethostbyname addr is not AF_INET\n");
closesocket(ret);
return (0);
}
}
end:
*sock = ret;
return (1);
}
int extract_host_port(char *str, char **host_ptr, unsigned char *ip,
short *port_ptr)
{
char *h, *p;
h = str;
p = strchr(str, ':');
if (p == NULL) {
BIO_printf(bio_err, "no port defined\n");
return (0);
}
*(p++) = '\0';
if ((ip != NULL) && !host_ip(str, ip))
goto err;
if (host_ptr != NULL)
*host_ptr = h;
if (!extract_port(p, port_ptr))
goto err;
return (1);
err:
return (0);
}
static int host_ip(char *str, unsigned char ip[4])
{
unsigned int in[4];
int i;
if (sscanf(str, "%u.%u.%u.%u", &(in[0]), &(in[1]), &(in[2]), &(in[3])) ==
4) {
for (i = 0; i < 4; i++)
if (in[i] > 255) {
BIO_printf(bio_err, "invalid IP address\n");
goto err;
}
ip[0] = in[0];
ip[1] = in[1];
ip[2] = in[2];
ip[3] = in[3];
} else { /* do a gethostbyname */
struct hostent *he;
if (!ssl_sock_init())
return (0);
he = GetHostByName(str);
if (he == NULL) {
BIO_printf(bio_err, "gethostbyname failure\n");
goto err;
}
/* cast to short because of win16 winsock definition */
if ((short)he->h_addrtype != AF_INET) {
BIO_printf(bio_err, "gethostbyname addr is not AF_INET\n");
return (0);
}
ip[0] = he->h_addr_list[0][0];
ip[1] = he->h_addr_list[0][1];
ip[2] = he->h_addr_list[0][2];
ip[3] = he->h_addr_list[0][3];
}
return (1);
err:
return (0);
}
int extract_port(char *str, short *port_ptr)
{
int i;
struct servent *s;
i = atoi(str);
if (i != 0)
*port_ptr = (unsigned short)i;
else {
s = getservbyname(str, "tcp");
if (s == NULL) {
BIO_printf(bio_err, "getservbyname failure for %s\n", str);
return (0);
}
*port_ptr = ntohs((unsigned short)s->s_port);
}
return (1);
}
# define GHBN_NUM 4
static struct ghbn_cache_st {
char name[128];
struct hostent ent;
unsigned long order;
} ghbn_cache[GHBN_NUM];
static unsigned long ghbn_hits = 0L;
static unsigned long ghbn_miss = 0L;
static struct hostent *GetHostByName(char *name)
{
struct hostent *ret;
int i, lowi = 0;
unsigned long low = (unsigned long)-1;
for (i = 0; i < GHBN_NUM; i++) {
if (low > ghbn_cache[i].order) {
low = ghbn_cache[i].order;
lowi = i;
}
if (ghbn_cache[i].order > 0) {
if (strncmp(name, ghbn_cache[i].name, 128) == 0)
break;
}
}
if (i == GHBN_NUM) { /* no hit */
ghbn_miss++;
ret = gethostbyname(name);
if (ret == NULL)
return (NULL);
/* else add to cache */
- if (strlen(name) < sizeof ghbn_cache[0].name) {
+ if (strlen(name) < sizeof(ghbn_cache[0].name)) {
strcpy(ghbn_cache[lowi].name, name);
memcpy((char *)&(ghbn_cache[lowi].ent), ret,
sizeof(struct hostent));
ghbn_cache[lowi].order = ghbn_miss + ghbn_hits;
}
return (ret);
} else {
ghbn_hits++;
ret = &(ghbn_cache[i].ent);
ghbn_cache[i].order = ghbn_miss + ghbn_hits;
return (ret);
}
}
#endif
diff --git a/apps/s_time.c b/apps/s_time.c
index 38788f7130c7..0bb2f8cc2aa1 100644
--- a/apps/s_time.c
+++ b/apps/s_time.c
@@ -1,641 +1,641 @@
/* apps/s_time.c */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
#define NO_SHUTDOWN
/* ----------------------------------------
s_time - SSL client connection timer program
Written and donated by Larry Streepy <streepy@healthcare.com>
-----------------------------------------*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define USE_SOCKETS
#include "apps.h"
#ifdef OPENSSL_NO_STDIO
# define APPS_WIN16
#endif
#include <openssl/x509.h>
#include <openssl/ssl.h>
#include <openssl/pem.h>
#include "s_apps.h"
#include <openssl/err.h>
#ifdef WIN32_STUFF
# include "winmain.h"
# include "wintext.h"
#endif
#if !defined(OPENSSL_SYS_MSDOS)
# include OPENSSL_UNISTD
#endif
#undef PROG
#define PROG s_time_main
#undef ioctl
#define ioctl ioctlsocket
#define SSL_CONNECT_NAME "localhost:4433"
/* no default cert. */
/*
* #define TEST_CERT "client.pem"
*/
#undef BUFSIZZ
#define BUFSIZZ 1024*10
#define MYBUFSIZ 1024*8
#undef min
#undef max
#define min(a,b) (((a) < (b)) ? (a) : (b))
#define max(a,b) (((a) > (b)) ? (a) : (b))
#undef SECONDS
#define SECONDS 30
extern int verify_depth;
extern int verify_error;
static void s_time_usage(void);
static int parseArgs(int argc, char **argv);
static SSL *doConnection(SSL *scon);
static void s_time_init(void);
/***********************************************************************
* Static data declarations
*/
/* static char *port=PORT_STR;*/
static char *host = SSL_CONNECT_NAME;
static char *t_cert_file = NULL;
static char *t_key_file = NULL;
static char *CApath = NULL;
static char *CAfile = NULL;
static char *tm_cipher = NULL;
static int tm_verify = SSL_VERIFY_NONE;
static int maxTime = SECONDS;
static SSL_CTX *tm_ctx = NULL;
static const SSL_METHOD *s_time_meth = NULL;
static char *s_www_path = NULL;
static long bytes_read = 0;
static int st_bugs = 0;
static int perform = 0;
#ifdef FIONBIO
static int t_nbio = 0;
#endif
#ifdef OPENSSL_SYS_WIN32
static int exitNow = 0; /* Set when it's time to exit main */
#endif
static void s_time_init(void)
{
host = SSL_CONNECT_NAME;
t_cert_file = NULL;
t_key_file = NULL;
CApath = NULL;
CAfile = NULL;
tm_cipher = NULL;
tm_verify = SSL_VERIFY_NONE;
maxTime = SECONDS;
tm_ctx = NULL;
s_time_meth = NULL;
s_www_path = NULL;
bytes_read = 0;
st_bugs = 0;
perform = 0;
#ifdef FIONBIO
t_nbio = 0;
#endif
#ifdef OPENSSL_SYS_WIN32
exitNow = 0; /* Set when it's time to exit main */
#endif
}
/***********************************************************************
* usage - display usage message
*/
static void s_time_usage(void)
{
static char umsg[] = "\
-time arg - max number of seconds to collect data, default %d\n\
-verify arg - turn on peer certificate verification, arg == depth\n\
-cert arg - certificate file to use, PEM format assumed\n\
-key arg - RSA file to use, PEM format assumed, key is in cert file\n\
file if not specified by this option\n\
-CApath arg - PEM format directory of CA's\n\
-CAfile arg - PEM format file of CA's\n\
-cipher - preferred cipher to use, play with 'openssl ciphers'\n\n";
printf("usage: s_time <args>\n\n");
printf("-connect host:port - host:port to connect to (default is %s)\n",
SSL_CONNECT_NAME);
#ifdef FIONBIO
printf("-nbio - Run with non-blocking IO\n");
printf("-ssl2 - Just use SSLv2\n");
printf("-ssl3 - Just use SSLv3\n");
printf("-bugs - Turn on SSL bug compatibility\n");
printf("-new - Just time new connections\n");
printf("-reuse - Just time connection reuse\n");
printf("-www page - Retrieve 'page' from the site\n");
#endif
printf(umsg, SECONDS);
}
/***********************************************************************
* parseArgs - Parse command line arguments and initialize data
*
* Returns 0 if ok, -1 on bad args
*/
static int parseArgs(int argc, char **argv)
{
int badop = 0;
verify_depth = 0;
verify_error = X509_V_OK;
argc--;
argv++;
while (argc >= 1) {
if (strcmp(*argv, "-connect") == 0) {
if (--argc < 1)
goto bad;
host = *(++argv);
}
#if 0
else if (strcmp(*argv, "-host") == 0) {
if (--argc < 1)
goto bad;
host = *(++argv);
} else if (strcmp(*argv, "-port") == 0) {
if (--argc < 1)
goto bad;
port = *(++argv);
}
#endif
else if (strcmp(*argv, "-reuse") == 0)
perform = 2;
else if (strcmp(*argv, "-new") == 0)
perform = 1;
else if (strcmp(*argv, "-verify") == 0) {
tm_verify = SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE;
if (--argc < 1)
goto bad;
verify_depth = atoi(*(++argv));
BIO_printf(bio_err, "verify depth is %d\n", verify_depth);
} else if (strcmp(*argv, "-cert") == 0) {
if (--argc < 1)
goto bad;
t_cert_file = *(++argv);
} else if (strcmp(*argv, "-key") == 0) {
if (--argc < 1)
goto bad;
t_key_file = *(++argv);
} else if (strcmp(*argv, "-CApath") == 0) {
if (--argc < 1)
goto bad;
CApath = *(++argv);
} else if (strcmp(*argv, "-CAfile") == 0) {
if (--argc < 1)
goto bad;
CAfile = *(++argv);
} else if (strcmp(*argv, "-cipher") == 0) {
if (--argc < 1)
goto bad;
tm_cipher = *(++argv);
}
#ifdef FIONBIO
else if (strcmp(*argv, "-nbio") == 0) {
t_nbio = 1;
}
#endif
else if (strcmp(*argv, "-www") == 0) {
if (--argc < 1)
goto bad;
s_www_path = *(++argv);
if (strlen(s_www_path) > MYBUFSIZ - 100) {
BIO_printf(bio_err, "-www option too long\n");
badop = 1;
}
} else if (strcmp(*argv, "-bugs") == 0)
st_bugs = 1;
#ifndef OPENSSL_NO_SSL2
else if (strcmp(*argv, "-ssl2") == 0)
s_time_meth = SSLv2_client_method();
#endif
#ifndef OPENSSL_NO_SSL3
else if (strcmp(*argv, "-ssl3") == 0)
s_time_meth = SSLv3_client_method();
#endif
else if (strcmp(*argv, "-time") == 0) {
if (--argc < 1)
goto bad;
maxTime = atoi(*(++argv));
if (maxTime <= 0) {
BIO_printf(bio_err, "time must be > 0\n");
badop = 1;
}
} else {
BIO_printf(bio_err, "unknown option %s\n", *argv);
badop = 1;
break;
}
argc--;
argv++;
}
if (perform == 0)
perform = 3;
if (badop) {
bad:
s_time_usage();
return -1;
}
return 0; /* Valid args */
}
/***********************************************************************
* TIME - time functions
*/
#define START 0
#define STOP 1
static double tm_Time_F(int s)
{
return app_tminterval(s, 1);
}
/***********************************************************************
* MAIN - main processing area for client
* real name depends on MONOLITH
*/
int MAIN(int, char **);
int MAIN(int argc, char **argv)
{
double totalTime = 0.0;
int nConn = 0;
SSL *scon = NULL;
long finishtime = 0;
int ret = 1, i;
MS_STATIC char buf[1024 * 8];
int ver;
apps_startup();
s_time_init();
if (bio_err == NULL)
bio_err = BIO_new_fp(stderr, BIO_NOCLOSE);
s_time_meth = SSLv23_client_method();
/* parse the command line arguments */
if (parseArgs(argc, argv) < 0)
goto end;
OpenSSL_add_ssl_algorithms();
if ((tm_ctx = SSL_CTX_new(s_time_meth)) == NULL)
return (1);
SSL_CTX_set_quiet_shutdown(tm_ctx, 1);
if (st_bugs)
SSL_CTX_set_options(tm_ctx, SSL_OP_ALL);
SSL_CTX_set_cipher_list(tm_ctx, tm_cipher);
if (!set_cert_stuff(tm_ctx, t_cert_file, t_key_file))
goto end;
SSL_load_error_strings();
if ((!SSL_CTX_load_verify_locations(tm_ctx, CAfile, CApath)) ||
(!SSL_CTX_set_default_verify_paths(tm_ctx))) {
/*
* BIO_printf(bio_err,"error setting default verify locations\n");
*/
ERR_print_errors(bio_err);
/* goto end; */
}
if (tm_cipher == NULL)
tm_cipher = getenv("SSL_CIPHER");
if (tm_cipher == NULL) {
fprintf(stderr, "No CIPHER specified\n");
}
if (!(perform & 1))
goto next;
printf("Collecting connection statistics for %d seconds\n", maxTime);
/* Loop and time how long it takes to make connections */
bytes_read = 0;
finishtime = (long)time(NULL) + maxTime;
tm_Time_F(START);
for (;;) {
if (finishtime < (long)time(NULL))
break;
#ifdef WIN32_STUFF
if (flushWinMsgs(0) == -1)
goto end;
if (waitingToDie || exitNow) /* we're dead */
goto end;
#endif
if ((scon = doConnection(NULL)) == NULL)
goto end;
if (s_www_path != NULL) {
- BIO_snprintf(buf, sizeof buf, "GET %s HTTP/1.0\r\n\r\n",
+ BIO_snprintf(buf, sizeof(buf), "GET %s HTTP/1.0\r\n\r\n",
s_www_path);
SSL_write(scon, buf, strlen(buf));
while ((i = SSL_read(scon, buf, sizeof(buf))) > 0)
bytes_read += i;
}
#ifdef NO_SHUTDOWN
SSL_set_shutdown(scon, SSL_SENT_SHUTDOWN | SSL_RECEIVED_SHUTDOWN);
#else
SSL_shutdown(scon);
#endif
SHUTDOWN2(SSL_get_fd(scon));
nConn += 1;
if (SSL_session_reused(scon))
ver = 'r';
else {
ver = SSL_version(scon);
if (ver == TLS1_VERSION)
ver = 't';
else if (ver == SSL3_VERSION)
ver = '3';
else if (ver == SSL2_VERSION)
ver = '2';
else
ver = '*';
}
fputc(ver, stdout);
fflush(stdout);
SSL_free(scon);
scon = NULL;
}
totalTime += tm_Time_F(STOP); /* Add the time for this iteration */
i = (int)((long)time(NULL) - finishtime + maxTime);
printf
("\n\n%d connections in %.2fs; %.2f connections/user sec, bytes read %ld\n",
nConn, totalTime, ((double)nConn / totalTime), bytes_read);
printf
("%d connections in %ld real seconds, %ld bytes read per connection\n",
nConn, (long)time(NULL) - finishtime + maxTime, bytes_read / nConn);
/*
* Now loop and time connections using the same session id over and over
*/
next:
if (!(perform & 2))
goto end;
printf("\n\nNow timing with session id reuse.\n");
/* Get an SSL object so we can reuse the session id */
if ((scon = doConnection(NULL)) == NULL) {
fprintf(stderr, "Unable to get connection\n");
goto end;
}
if (s_www_path != NULL) {
- BIO_snprintf(buf, sizeof buf, "GET %s HTTP/1.0\r\n\r\n", s_www_path);
+ BIO_snprintf(buf, sizeof(buf), "GET %s HTTP/1.0\r\n\r\n", s_www_path);
SSL_write(scon, buf, strlen(buf));
while (SSL_read(scon, buf, sizeof(buf)) > 0) ;
}
#ifdef NO_SHUTDOWN
SSL_set_shutdown(scon, SSL_SENT_SHUTDOWN | SSL_RECEIVED_SHUTDOWN);
#else
SSL_shutdown(scon);
#endif
SHUTDOWN2(SSL_get_fd(scon));
nConn = 0;
totalTime = 0.0;
finishtime = (long)time(NULL) + maxTime;
printf("starting\n");
bytes_read = 0;
tm_Time_F(START);
for (;;) {
if (finishtime < (long)time(NULL))
break;
#ifdef WIN32_STUFF
if (flushWinMsgs(0) == -1)
goto end;
if (waitingToDie || exitNow) /* we're dead */
goto end;
#endif
if ((doConnection(scon)) == NULL)
goto end;
if (s_www_path) {
- BIO_snprintf(buf, sizeof buf, "GET %s HTTP/1.0\r\n\r\n",
+ BIO_snprintf(buf, sizeof(buf), "GET %s HTTP/1.0\r\n\r\n",
s_www_path);
SSL_write(scon, buf, strlen(buf));
while ((i = SSL_read(scon, buf, sizeof(buf))) > 0)
bytes_read += i;
}
#ifdef NO_SHUTDOWN
SSL_set_shutdown(scon, SSL_SENT_SHUTDOWN | SSL_RECEIVED_SHUTDOWN);
#else
SSL_shutdown(scon);
#endif
SHUTDOWN2(SSL_get_fd(scon));
nConn += 1;
if (SSL_session_reused(scon))
ver = 'r';
else {
ver = SSL_version(scon);
if (ver == TLS1_VERSION)
ver = 't';
else if (ver == SSL3_VERSION)
ver = '3';
else if (ver == SSL2_VERSION)
ver = '2';
else
ver = '*';
}
fputc(ver, stdout);
fflush(stdout);
}
totalTime += tm_Time_F(STOP); /* Add the time for this iteration */
printf
("\n\n%d connections in %.2fs; %.2f connections/user sec, bytes read %ld\n",
nConn, totalTime, ((double)nConn / totalTime), bytes_read);
printf
("%d connections in %ld real seconds, %ld bytes read per connection\n",
nConn, (long)time(NULL) - finishtime + maxTime,
bytes_read / (nConn?nConn:1));
ret = 0;
end:
if (scon != NULL)
SSL_free(scon);
if (tm_ctx != NULL) {
SSL_CTX_free(tm_ctx);
tm_ctx = NULL;
}
apps_shutdown();
OPENSSL_EXIT(ret);
}
/*-
* doConnection - make a connection
* Args:
* scon = earlier ssl connection for session id, or NULL
* Returns:
* SSL * = the connection pointer.
*/
static SSL *doConnection(SSL *scon)
{
BIO *conn;
SSL *serverCon;
int width, i;
fd_set readfds;
if ((conn = BIO_new(BIO_s_connect())) == NULL)
return (NULL);
/* BIO_set_conn_port(conn,port);*/
BIO_set_conn_hostname(conn, host);
if (scon == NULL)
serverCon = SSL_new(tm_ctx);
else {
serverCon = scon;
SSL_set_connect_state(serverCon);
}
SSL_set_bio(serverCon, conn, conn);
#if 0
if (scon != NULL)
SSL_set_session(serverCon, SSL_get_session(scon));
#endif
/* ok, lets connect */
for (;;) {
i = SSL_connect(serverCon);
if (BIO_sock_should_retry(i)) {
BIO_printf(bio_err, "DELAY\n");
i = SSL_get_fd(serverCon);
width = i + 1;
FD_ZERO(&readfds);
openssl_fdset(i, &readfds);
/*
* Note: under VMS with SOCKETSHR the 2nd parameter is currently
* of type (int *) whereas under other systems it is (void *) if
* you don't have a cast it will choke the compiler: if you do
* have a cast then you can either go for (int *) or (void *).
*/
select(width, (void *)&readfds, NULL, NULL, NULL);
continue;
}
break;
}
if (i <= 0) {
BIO_printf(bio_err, "ERROR\n");
if (verify_error != X509_V_OK)
BIO_printf(bio_err, "verify error:%s\n",
X509_verify_cert_error_string(verify_error));
else
ERR_print_errors(bio_err);
if (scon == NULL)
SSL_free(serverCon);
return NULL;
}
return serverCon;
}
diff --git a/apps/speed.c b/apps/speed.c
index 5383678b9864..aaa982ee1f74 100644
--- a/apps/speed.c
+++ b/apps/speed.c
@@ -1,2880 +1,2880 @@
/* apps/speed.c */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
/* ====================================================================
* Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
*
* Portions of the attached software ("Contribution") are developed by
* SUN MICROSYSTEMS, INC., and are contributed to the OpenSSL project.
*
* The Contribution is licensed pursuant to the OpenSSL open source
* license provided above.
*
* The ECDH and ECDSA speed test software is originally written by
* Sumit Gupta of Sun Microsystems Laboratories.
*
*/
/* most of this code has been pilfered from my libdes speed.c program */
#ifndef OPENSSL_NO_SPEED
# undef SECONDS
# define SECONDS 3
# define RSA_SECONDS 10
# define DSA_SECONDS 10
# define ECDSA_SECONDS 10
# define ECDH_SECONDS 10
/* 11-Sep-92 Andrew Daviel Support for Silicon Graphics IRIX added */
/* 06-Apr-92 Luke Brennan Support for VMS and add extra signal calls */
# undef PROG
# define PROG speed_main
# include <stdio.h>
# include <stdlib.h>
# include <string.h>
# include <math.h>
# include "apps.h"
# ifdef OPENSSL_NO_STDIO
# define APPS_WIN16
# endif
# include <openssl/crypto.h>
# include <openssl/rand.h>
# include <openssl/err.h>
# include <openssl/evp.h>
# include <openssl/objects.h>
# if !defined(OPENSSL_SYS_MSDOS)
# include OPENSSL_UNISTD
# endif
# ifndef OPENSSL_SYS_NETWARE
# include <signal.h>
# endif
# if defined(_WIN32) || defined(__CYGWIN__)
# include <windows.h>
# if defined(__CYGWIN__) && !defined(_WIN32)
/*
* <windows.h> should define _WIN32, which normally is mutually exclusive
* with __CYGWIN__, but if it didn't...
*/
# define _WIN32
/* this is done because Cygwin alarm() fails sometimes. */
# endif
# endif
# include <openssl/bn.h>
# ifndef OPENSSL_NO_DES
# include <openssl/des.h>
# endif
# ifndef OPENSSL_NO_AES
# include <openssl/aes.h>
# endif
# ifndef OPENSSL_NO_CAMELLIA
# include <openssl/camellia.h>
# endif
# ifndef OPENSSL_NO_MD2
# include <openssl/md2.h>
# endif
# ifndef OPENSSL_NO_MDC2
# include <openssl/mdc2.h>
# endif
# ifndef OPENSSL_NO_MD4
# include <openssl/md4.h>
# endif
# ifndef OPENSSL_NO_MD5
# include <openssl/md5.h>
# endif
# ifndef OPENSSL_NO_HMAC
# include <openssl/hmac.h>
# endif
# include <openssl/evp.h>
# ifndef OPENSSL_NO_SHA
# include <openssl/sha.h>
# endif
# ifndef OPENSSL_NO_RIPEMD
# include <openssl/ripemd.h>
# endif
# ifndef OPENSSL_NO_WHIRLPOOL
# include <openssl/whrlpool.h>
# endif
# ifndef OPENSSL_NO_RC4
# include <openssl/rc4.h>
# endif
# ifndef OPENSSL_NO_RC5
# include <openssl/rc5.h>
# endif
# ifndef OPENSSL_NO_RC2
# include <openssl/rc2.h>
# endif
# ifndef OPENSSL_NO_IDEA
# include <openssl/idea.h>
# endif
# ifndef OPENSSL_NO_SEED
# include <openssl/seed.h>
# endif
# ifndef OPENSSL_NO_BF
# include <openssl/blowfish.h>
# endif
# ifndef OPENSSL_NO_CAST
# include <openssl/cast.h>
# endif
# ifndef OPENSSL_NO_RSA
# include <openssl/rsa.h>
# include "./testrsa.h"
# endif
# include <openssl/x509.h>
# ifndef OPENSSL_NO_DSA
# include <openssl/dsa.h>
# include "./testdsa.h"
# endif
# ifndef OPENSSL_NO_ECDSA
# include <openssl/ecdsa.h>
# endif
# ifndef OPENSSL_NO_ECDH
# include <openssl/ecdh.h>
# endif
# include <openssl/modes.h>
# ifdef OPENSSL_FIPS
# ifdef OPENSSL_DOING_MAKEDEPEND
# undef AES_set_encrypt_key
# undef AES_set_decrypt_key
# undef DES_set_key_unchecked
# endif
# define BF_set_key private_BF_set_key
# define CAST_set_key private_CAST_set_key
# define idea_set_encrypt_key private_idea_set_encrypt_key
# define SEED_set_key private_SEED_set_key
# define RC2_set_key private_RC2_set_key
# define RC4_set_key private_RC4_set_key
# define DES_set_key_unchecked private_DES_set_key_unchecked
# define AES_set_encrypt_key private_AES_set_encrypt_key
# define AES_set_decrypt_key private_AES_set_decrypt_key
# define Camellia_set_key private_Camellia_set_key
# endif
# ifndef HAVE_FORK
# if defined(OPENSSL_SYS_VMS) || defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MACINTOSH_CLASSIC) || defined(OPENSSL_SYS_OS2) || defined(OPENSSL_SYS_NETWARE)
# define HAVE_FORK 0
# else
# define HAVE_FORK 1
# endif
# endif
# if HAVE_FORK
# undef NO_FORK
# else
# define NO_FORK
# endif
# undef BUFSIZE
# define BUFSIZE ((long)1024*8+1)
static volatile int run = 0;
static int mr = 0;
static int usertime = 1;
static double Time_F(int s);
static void print_message(const char *s, long num, int length);
static void pkey_print_message(const char *str, const char *str2,
long num, int bits, int sec);
static void print_result(int alg, int run_no, int count, double time_used);
# ifndef NO_FORK
static int do_multi(int multi);
# endif
# define ALGOR_NUM 30
# define SIZE_NUM 5
# define RSA_NUM 4
# define DSA_NUM 3
# define EC_NUM 16
# define MAX_ECDH_SIZE 256
static const char *names[ALGOR_NUM] = {
"md2", "mdc2", "md4", "md5", "hmac(md5)", "sha1", "rmd160", "rc4",
"des cbc", "des ede3", "idea cbc", "seed cbc",
"rc2 cbc", "rc5-32/12 cbc", "blowfish cbc", "cast cbc",
"aes-128 cbc", "aes-192 cbc", "aes-256 cbc",
"camellia-128 cbc", "camellia-192 cbc", "camellia-256 cbc",
"evp", "sha256", "sha512", "whirlpool",
"aes-128 ige", "aes-192 ige", "aes-256 ige", "ghash"
};
static double results[ALGOR_NUM][SIZE_NUM];
static int lengths[SIZE_NUM] = { 16, 64, 256, 1024, 8 * 1024 };
# ifndef OPENSSL_NO_RSA
static double rsa_results[RSA_NUM][2];
# endif
# ifndef OPENSSL_NO_DSA
static double dsa_results[DSA_NUM][2];
# endif
# ifndef OPENSSL_NO_ECDSA
static double ecdsa_results[EC_NUM][2];
# endif
# ifndef OPENSSL_NO_ECDH
static double ecdh_results[EC_NUM][1];
# endif
# if defined(OPENSSL_NO_DSA) && !(defined(OPENSSL_NO_ECDSA) && defined(OPENSSL_NO_ECDH))
static const char rnd_seed[] =
"string to make the random number generator think it has entropy";
static int rnd_fake = 0;
# endif
# ifdef SIGALRM
# if defined(__STDC__) || defined(sgi) || defined(_AIX)
# define SIGRETTYPE void
# else
# define SIGRETTYPE int
# endif
static SIGRETTYPE sig_done(int sig);
static SIGRETTYPE sig_done(int sig)
{
signal(SIGALRM, sig_done);
run = 0;
# ifdef LINT
sig = sig;
# endif
}
# endif
# define START 0
# define STOP 1
# if defined(_WIN32)
# if !defined(SIGALRM)
# define SIGALRM
# endif
static volatile unsigned int lapse;
static volatile unsigned int schlock;
static void alarm_win32(unsigned int secs)
{
lapse = secs * 1000;
}
# define alarm alarm_win32
static DWORD WINAPI sleepy(VOID * arg)
{
schlock = 1;
Sleep(lapse);
run = 0;
return 0;
}
static double Time_F(int s)
{
if (s == START) {
HANDLE thr;
schlock = 0;
thr = CreateThread(NULL, 4096, sleepy, NULL, 0, NULL);
if (thr == NULL) {
DWORD ret = GetLastError();
BIO_printf(bio_err, "unable to CreateThread (%d)", ret);
ExitProcess(ret);
}
CloseHandle(thr); /* detach the thread */
while (!schlock)
Sleep(0); /* scheduler spinlock */
}
return app_tminterval(s, usertime);
}
# else
static double Time_F(int s)
{
return app_tminterval(s, usertime);
}
# endif
# ifndef OPENSSL_NO_ECDH
static const int KDF1_SHA1_len = 20;
static void *KDF1_SHA1(const void *in, size_t inlen, void *out,
size_t *outlen)
{
# ifndef OPENSSL_NO_SHA
if (*outlen < SHA_DIGEST_LENGTH)
return NULL;
else
*outlen = SHA_DIGEST_LENGTH;
return SHA1(in, inlen, out);
# else
return NULL;
# endif /* OPENSSL_NO_SHA */
}
# endif /* OPENSSL_NO_ECDH */
static void multiblock_speed(const EVP_CIPHER *evp_cipher);
int MAIN(int, char **);
int MAIN(int argc, char **argv)
{
ENGINE *e = NULL;
unsigned char *buf = NULL, *buf2 = NULL;
int mret = 1;
long count = 0, save_count = 0;
int i, j, k;
# if !defined(OPENSSL_NO_RSA) || !defined(OPENSSL_NO_DSA)
long rsa_count;
# endif
# ifndef OPENSSL_NO_RSA
unsigned rsa_num;
# endif
unsigned char md[EVP_MAX_MD_SIZE];
# ifndef OPENSSL_NO_MD2
unsigned char md2[MD2_DIGEST_LENGTH];
# endif
# ifndef OPENSSL_NO_MDC2
unsigned char mdc2[MDC2_DIGEST_LENGTH];
# endif
# ifndef OPENSSL_NO_MD4
unsigned char md4[MD4_DIGEST_LENGTH];
# endif
# ifndef OPENSSL_NO_MD5
unsigned char md5[MD5_DIGEST_LENGTH];
unsigned char hmac[MD5_DIGEST_LENGTH];
# endif
# ifndef OPENSSL_NO_SHA
unsigned char sha[SHA_DIGEST_LENGTH];
# ifndef OPENSSL_NO_SHA256
unsigned char sha256[SHA256_DIGEST_LENGTH];
# endif
# ifndef OPENSSL_NO_SHA512
unsigned char sha512[SHA512_DIGEST_LENGTH];
# endif
# endif
# ifndef OPENSSL_NO_WHIRLPOOL
unsigned char whirlpool[WHIRLPOOL_DIGEST_LENGTH];
# endif
# ifndef OPENSSL_NO_RIPEMD
unsigned char rmd160[RIPEMD160_DIGEST_LENGTH];
# endif
# ifndef OPENSSL_NO_RC4
RC4_KEY rc4_ks;
# endif
# ifndef OPENSSL_NO_RC5
RC5_32_KEY rc5_ks;
# endif
# ifndef OPENSSL_NO_RC2
RC2_KEY rc2_ks;
# endif
# ifndef OPENSSL_NO_IDEA
IDEA_KEY_SCHEDULE idea_ks;
# endif
# ifndef OPENSSL_NO_SEED
SEED_KEY_SCHEDULE seed_ks;
# endif
# ifndef OPENSSL_NO_BF
BF_KEY bf_ks;
# endif
# ifndef OPENSSL_NO_CAST
CAST_KEY cast_ks;
# endif
static const unsigned char key16[16] = {
0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0,
0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12
};
# ifndef OPENSSL_NO_AES
static const unsigned char key24[24] = {
0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0,
0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12,
0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34
};
static const unsigned char key32[32] = {
0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0,
0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12,
0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34,
0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56
};
# endif
# ifndef OPENSSL_NO_CAMELLIA
static const unsigned char ckey24[24] = {
0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0,
0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12,
0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34
};
static const unsigned char ckey32[32] = {
0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0,
0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12,
0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34,
0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56
};
# endif
# ifndef OPENSSL_NO_AES
# define MAX_BLOCK_SIZE 128
# else
# define MAX_BLOCK_SIZE 64
# endif
unsigned char DES_iv[8];
unsigned char iv[2 * MAX_BLOCK_SIZE / 8];
# ifndef OPENSSL_NO_DES
static DES_cblock key =
{ 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0 };
static DES_cblock key2 =
{ 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12 };
static DES_cblock key3 =
{ 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34 };
DES_key_schedule sch;
DES_key_schedule sch2;
DES_key_schedule sch3;
# endif
# ifndef OPENSSL_NO_AES
AES_KEY aes_ks1, aes_ks2, aes_ks3;
# endif
# ifndef OPENSSL_NO_CAMELLIA
CAMELLIA_KEY camellia_ks1, camellia_ks2, camellia_ks3;
# endif
# define D_MD2 0
# define D_MDC2 1
# define D_MD4 2
# define D_MD5 3
# define D_HMAC 4
# define D_SHA1 5
# define D_RMD160 6
# define D_RC4 7
# define D_CBC_DES 8
# define D_EDE3_DES 9
# define D_CBC_IDEA 10
# define D_CBC_SEED 11
# define D_CBC_RC2 12
# define D_CBC_RC5 13
# define D_CBC_BF 14
# define D_CBC_CAST 15
# define D_CBC_128_AES 16
# define D_CBC_192_AES 17
# define D_CBC_256_AES 18
# define D_CBC_128_CML 19
# define D_CBC_192_CML 20
# define D_CBC_256_CML 21
# define D_EVP 22
# define D_SHA256 23
# define D_SHA512 24
# define D_WHIRLPOOL 25
# define D_IGE_128_AES 26
# define D_IGE_192_AES 27
# define D_IGE_256_AES 28
# define D_GHASH 29
double d = 0.0;
long c[ALGOR_NUM][SIZE_NUM];
# define R_DSA_512 0
# define R_DSA_1024 1
# define R_DSA_2048 2
# define R_RSA_512 0
# define R_RSA_1024 1
# define R_RSA_2048 2
# define R_RSA_4096 3
# define R_EC_P160 0
# define R_EC_P192 1
# define R_EC_P224 2
# define R_EC_P256 3
# define R_EC_P384 4
# define R_EC_P521 5
# define R_EC_K163 6
# define R_EC_K233 7
# define R_EC_K283 8
# define R_EC_K409 9
# define R_EC_K571 10
# define R_EC_B163 11
# define R_EC_B233 12
# define R_EC_B283 13
# define R_EC_B409 14
# define R_EC_B571 15
# ifndef OPENSSL_NO_RSA
RSA *rsa_key[RSA_NUM];
long rsa_c[RSA_NUM][2];
static unsigned int rsa_bits[RSA_NUM] = {
512, 1024, 2048, 4096
};
static unsigned char *rsa_data[RSA_NUM] = {
test512, test1024, test2048, test4096
};
static int rsa_data_length[RSA_NUM] = {
sizeof(test512), sizeof(test1024),
sizeof(test2048), sizeof(test4096)
};
# endif
# ifndef OPENSSL_NO_DSA
DSA *dsa_key[DSA_NUM];
long dsa_c[DSA_NUM][2];
static unsigned int dsa_bits[DSA_NUM] = { 512, 1024, 2048 };
# endif
# ifndef OPENSSL_NO_EC
/*
* We only test over the following curves as they are representative, To
* add tests over more curves, simply add the curve NID and curve name to
* the following arrays and increase the EC_NUM value accordingly.
*/
static unsigned int test_curves[EC_NUM] = {
/* Prime Curves */
NID_secp160r1,
NID_X9_62_prime192v1,
NID_secp224r1,
NID_X9_62_prime256v1,
NID_secp384r1,
NID_secp521r1,
/* Binary Curves */
NID_sect163k1,
NID_sect233k1,
NID_sect283k1,
NID_sect409k1,
NID_sect571k1,
NID_sect163r2,
NID_sect233r1,
NID_sect283r1,
NID_sect409r1,
NID_sect571r1
};
static const char *test_curves_names[EC_NUM] = {
/* Prime Curves */
"secp160r1",
"nistp192",
"nistp224",
"nistp256",
"nistp384",
"nistp521",
/* Binary Curves */
"nistk163",
"nistk233",
"nistk283",
"nistk409",
"nistk571",
"nistb163",
"nistb233",
"nistb283",
"nistb409",
"nistb571"
};
static int test_curves_bits[EC_NUM] = {
160, 192, 224, 256, 384, 521,
163, 233, 283, 409, 571,
163, 233, 283, 409, 571
};
# endif
# ifndef OPENSSL_NO_ECDSA
unsigned char ecdsasig[256];
unsigned int ecdsasiglen;
EC_KEY *ecdsa[EC_NUM];
long ecdsa_c[EC_NUM][2];
# endif
# ifndef OPENSSL_NO_ECDH
EC_KEY *ecdh_a[EC_NUM], *ecdh_b[EC_NUM];
unsigned char secret_a[MAX_ECDH_SIZE], secret_b[MAX_ECDH_SIZE];
int secret_size_a, secret_size_b;
int ecdh_checks = 0;
int secret_idx = 0;
long ecdh_c[EC_NUM][2];
# endif
int rsa_doit[RSA_NUM];
int dsa_doit[DSA_NUM];
# ifndef OPENSSL_NO_ECDSA
int ecdsa_doit[EC_NUM];
# endif
# ifndef OPENSSL_NO_ECDH
int ecdh_doit[EC_NUM];
# endif
int doit[ALGOR_NUM];
int pr_header = 0;
const EVP_CIPHER *evp_cipher = NULL;
const EVP_MD *evp_md = NULL;
int decrypt = 0;
# ifndef NO_FORK
int multi = 0;
# endif
int multiblock = 0;
# ifndef TIMES
usertime = -1;
# endif
apps_startup();
memset(results, 0, sizeof(results));
# ifndef OPENSSL_NO_DSA
memset(dsa_key, 0, sizeof(dsa_key));
# endif
# ifndef OPENSSL_NO_ECDSA
for (i = 0; i < EC_NUM; i++)
ecdsa[i] = NULL;
# endif
# ifndef OPENSSL_NO_ECDH
for (i = 0; i < EC_NUM; i++) {
ecdh_a[i] = NULL;
ecdh_b[i] = NULL;
}
# endif
# ifndef OPENSSL_NO_RSA
for (i = 0; i < RSA_NUM; i++)
rsa_key[i] = NULL;
# endif
if (bio_err == NULL)
if ((bio_err = BIO_new(BIO_s_file())) != NULL)
BIO_set_fp(bio_err, stderr, BIO_NOCLOSE | BIO_FP_TEXT);
if (!load_config(bio_err, NULL))
goto end;
if ((buf = (unsigned char *)OPENSSL_malloc((int)BUFSIZE)) == NULL) {
BIO_printf(bio_err, "out of memory\n");
goto end;
}
if ((buf2 = (unsigned char *)OPENSSL_malloc((int)BUFSIZE)) == NULL) {
BIO_printf(bio_err, "out of memory\n");
goto end;
}
memset(c, 0, sizeof(c));
memset(DES_iv, 0, sizeof(DES_iv));
memset(iv, 0, sizeof(iv));
for (i = 0; i < ALGOR_NUM; i++)
doit[i] = 0;
for (i = 0; i < RSA_NUM; i++)
rsa_doit[i] = 0;
for (i = 0; i < DSA_NUM; i++)
dsa_doit[i] = 0;
# ifndef OPENSSL_NO_ECDSA
for (i = 0; i < EC_NUM; i++)
ecdsa_doit[i] = 0;
# endif
# ifndef OPENSSL_NO_ECDH
for (i = 0; i < EC_NUM; i++)
ecdh_doit[i] = 0;
# endif
j = 0;
argc--;
argv++;
while (argc) {
if ((argc > 0) && (strcmp(*argv, "-elapsed") == 0)) {
usertime = 0;
j--; /* Otherwise, -elapsed gets confused with an
* algorithm. */
} else if ((argc > 0) && (strcmp(*argv, "-evp") == 0)) {
argc--;
argv++;
if (argc == 0) {
BIO_printf(bio_err, "no EVP given\n");
goto end;
}
evp_md = NULL;
evp_cipher = EVP_get_cipherbyname(*argv);
if (!evp_cipher) {
evp_md = EVP_get_digestbyname(*argv);
}
if (!evp_cipher && !evp_md) {
BIO_printf(bio_err, "%s is an unknown cipher or digest\n",
*argv);
goto end;
}
doit[D_EVP] = 1;
} else if (argc > 0 && !strcmp(*argv, "-decrypt")) {
decrypt = 1;
j--; /* Otherwise, -elapsed gets confused with an
* algorithm. */
}
# ifndef OPENSSL_NO_ENGINE
else if ((argc > 0) && (strcmp(*argv, "-engine") == 0)) {
argc--;
argv++;
if (argc == 0) {
BIO_printf(bio_err, "no engine given\n");
goto end;
}
e = setup_engine(bio_err, *argv, 0);
/*
* j will be increased again further down. We just don't want
* speed to confuse an engine with an algorithm, especially when
* none is given (which means all of them should be run)
*/
j--;
}
# endif
# ifndef NO_FORK
else if ((argc > 0) && (strcmp(*argv, "-multi") == 0)) {
argc--;
argv++;
if (argc == 0) {
BIO_printf(bio_err, "no multi count given\n");
goto end;
}
multi = atoi(argv[0]);
if (multi <= 0) {
BIO_printf(bio_err, "bad multi count\n");
goto end;
}
j--; /* Otherwise, -mr gets confused with an
* algorithm. */
}
# endif
else if (argc > 0 && !strcmp(*argv, "-mr")) {
mr = 1;
j--; /* Otherwise, -mr gets confused with an
* algorithm. */
} else if (argc > 0 && !strcmp(*argv, "-mb")) {
multiblock = 1;
j--;
} else
# ifndef OPENSSL_NO_MD2
if (strcmp(*argv, "md2") == 0)
doit[D_MD2] = 1;
else
# endif
# ifndef OPENSSL_NO_MDC2
if (strcmp(*argv, "mdc2") == 0)
doit[D_MDC2] = 1;
else
# endif
# ifndef OPENSSL_NO_MD4
if (strcmp(*argv, "md4") == 0)
doit[D_MD4] = 1;
else
# endif
# ifndef OPENSSL_NO_MD5
if (strcmp(*argv, "md5") == 0)
doit[D_MD5] = 1;
else
# endif
# ifndef OPENSSL_NO_MD5
if (strcmp(*argv, "hmac") == 0)
doit[D_HMAC] = 1;
else
# endif
# ifndef OPENSSL_NO_SHA
if (strcmp(*argv, "sha1") == 0)
doit[D_SHA1] = 1;
else if (strcmp(*argv, "sha") == 0)
doit[D_SHA1] = 1, doit[D_SHA256] = 1, doit[D_SHA512] = 1;
else
# ifndef OPENSSL_NO_SHA256
if (strcmp(*argv, "sha256") == 0)
doit[D_SHA256] = 1;
else
# endif
# ifndef OPENSSL_NO_SHA512
if (strcmp(*argv, "sha512") == 0)
doit[D_SHA512] = 1;
else
# endif
# endif
# ifndef OPENSSL_NO_WHIRLPOOL
if (strcmp(*argv, "whirlpool") == 0)
doit[D_WHIRLPOOL] = 1;
else
# endif
# ifndef OPENSSL_NO_RIPEMD
if (strcmp(*argv, "ripemd") == 0)
doit[D_RMD160] = 1;
else if (strcmp(*argv, "rmd160") == 0)
doit[D_RMD160] = 1;
else if (strcmp(*argv, "ripemd160") == 0)
doit[D_RMD160] = 1;
else
# endif
# ifndef OPENSSL_NO_RC4
if (strcmp(*argv, "rc4") == 0)
doit[D_RC4] = 1;
else
# endif
# ifndef OPENSSL_NO_DES
if (strcmp(*argv, "des-cbc") == 0)
doit[D_CBC_DES] = 1;
else if (strcmp(*argv, "des-ede3") == 0)
doit[D_EDE3_DES] = 1;
else
# endif
# ifndef OPENSSL_NO_AES
if (strcmp(*argv, "aes-128-cbc") == 0)
doit[D_CBC_128_AES] = 1;
else if (strcmp(*argv, "aes-192-cbc") == 0)
doit[D_CBC_192_AES] = 1;
else if (strcmp(*argv, "aes-256-cbc") == 0)
doit[D_CBC_256_AES] = 1;
else if (strcmp(*argv, "aes-128-ige") == 0)
doit[D_IGE_128_AES] = 1;
else if (strcmp(*argv, "aes-192-ige") == 0)
doit[D_IGE_192_AES] = 1;
else if (strcmp(*argv, "aes-256-ige") == 0)
doit[D_IGE_256_AES] = 1;
else
# endif
# ifndef OPENSSL_NO_CAMELLIA
if (strcmp(*argv, "camellia-128-cbc") == 0)
doit[D_CBC_128_CML] = 1;
else if (strcmp(*argv, "camellia-192-cbc") == 0)
doit[D_CBC_192_CML] = 1;
else if (strcmp(*argv, "camellia-256-cbc") == 0)
doit[D_CBC_256_CML] = 1;
else
# endif
# ifndef OPENSSL_NO_RSA
# if 0 /* was: #ifdef RSAref */
if (strcmp(*argv, "rsaref") == 0) {
RSA_set_default_openssl_method(RSA_PKCS1_RSAref());
j--;
} else
# endif
# ifndef RSA_NULL
if (strcmp(*argv, "openssl") == 0) {
RSA_set_default_method(RSA_PKCS1_SSLeay());
j--;
} else
# endif
# endif /* !OPENSSL_NO_RSA */
if (strcmp(*argv, "dsa512") == 0)
dsa_doit[R_DSA_512] = 2;
else if (strcmp(*argv, "dsa1024") == 0)
dsa_doit[R_DSA_1024] = 2;
else if (strcmp(*argv, "dsa2048") == 0)
dsa_doit[R_DSA_2048] = 2;
else if (strcmp(*argv, "rsa512") == 0)
rsa_doit[R_RSA_512] = 2;
else if (strcmp(*argv, "rsa1024") == 0)
rsa_doit[R_RSA_1024] = 2;
else if (strcmp(*argv, "rsa2048") == 0)
rsa_doit[R_RSA_2048] = 2;
else if (strcmp(*argv, "rsa4096") == 0)
rsa_doit[R_RSA_4096] = 2;
else
# ifndef OPENSSL_NO_RC2
if (strcmp(*argv, "rc2-cbc") == 0)
doit[D_CBC_RC2] = 1;
else if (strcmp(*argv, "rc2") == 0)
doit[D_CBC_RC2] = 1;
else
# endif
# ifndef OPENSSL_NO_RC5
if (strcmp(*argv, "rc5-cbc") == 0)
doit[D_CBC_RC5] = 1;
else if (strcmp(*argv, "rc5") == 0)
doit[D_CBC_RC5] = 1;
else
# endif
# ifndef OPENSSL_NO_IDEA
if (strcmp(*argv, "idea-cbc") == 0)
doit[D_CBC_IDEA] = 1;
else if (strcmp(*argv, "idea") == 0)
doit[D_CBC_IDEA] = 1;
else
# endif
# ifndef OPENSSL_NO_SEED
if (strcmp(*argv, "seed-cbc") == 0)
doit[D_CBC_SEED] = 1;
else if (strcmp(*argv, "seed") == 0)
doit[D_CBC_SEED] = 1;
else
# endif
# ifndef OPENSSL_NO_BF
if (strcmp(*argv, "bf-cbc") == 0)
doit[D_CBC_BF] = 1;
else if (strcmp(*argv, "blowfish") == 0)
doit[D_CBC_BF] = 1;
else if (strcmp(*argv, "bf") == 0)
doit[D_CBC_BF] = 1;
else
# endif
# ifndef OPENSSL_NO_CAST
if (strcmp(*argv, "cast-cbc") == 0)
doit[D_CBC_CAST] = 1;
else if (strcmp(*argv, "cast") == 0)
doit[D_CBC_CAST] = 1;
else if (strcmp(*argv, "cast5") == 0)
doit[D_CBC_CAST] = 1;
else
# endif
# ifndef OPENSSL_NO_DES
if (strcmp(*argv, "des") == 0) {
doit[D_CBC_DES] = 1;
doit[D_EDE3_DES] = 1;
} else
# endif
# ifndef OPENSSL_NO_AES
if (strcmp(*argv, "aes") == 0) {
doit[D_CBC_128_AES] = 1;
doit[D_CBC_192_AES] = 1;
doit[D_CBC_256_AES] = 1;
} else if (strcmp(*argv, "ghash") == 0) {
doit[D_GHASH] = 1;
} else
# endif
# ifndef OPENSSL_NO_CAMELLIA
if (strcmp(*argv, "camellia") == 0) {
doit[D_CBC_128_CML] = 1;
doit[D_CBC_192_CML] = 1;
doit[D_CBC_256_CML] = 1;
} else
# endif
# ifndef OPENSSL_NO_RSA
if (strcmp(*argv, "rsa") == 0) {
rsa_doit[R_RSA_512] = 1;
rsa_doit[R_RSA_1024] = 1;
rsa_doit[R_RSA_2048] = 1;
rsa_doit[R_RSA_4096] = 1;
} else
# endif
# ifndef OPENSSL_NO_DSA
if (strcmp(*argv, "dsa") == 0) {
dsa_doit[R_DSA_512] = 1;
dsa_doit[R_DSA_1024] = 1;
dsa_doit[R_DSA_2048] = 1;
} else
# endif
# ifndef OPENSSL_NO_ECDSA
if (strcmp(*argv, "ecdsap160") == 0)
ecdsa_doit[R_EC_P160] = 2;
else if (strcmp(*argv, "ecdsap192") == 0)
ecdsa_doit[R_EC_P192] = 2;
else if (strcmp(*argv, "ecdsap224") == 0)
ecdsa_doit[R_EC_P224] = 2;
else if (strcmp(*argv, "ecdsap256") == 0)
ecdsa_doit[R_EC_P256] = 2;
else if (strcmp(*argv, "ecdsap384") == 0)
ecdsa_doit[R_EC_P384] = 2;
else if (strcmp(*argv, "ecdsap521") == 0)
ecdsa_doit[R_EC_P521] = 2;
else if (strcmp(*argv, "ecdsak163") == 0)
ecdsa_doit[R_EC_K163] = 2;
else if (strcmp(*argv, "ecdsak233") == 0)
ecdsa_doit[R_EC_K233] = 2;
else if (strcmp(*argv, "ecdsak283") == 0)
ecdsa_doit[R_EC_K283] = 2;
else if (strcmp(*argv, "ecdsak409") == 0)
ecdsa_doit[R_EC_K409] = 2;
else if (strcmp(*argv, "ecdsak571") == 0)
ecdsa_doit[R_EC_K571] = 2;
else if (strcmp(*argv, "ecdsab163") == 0)
ecdsa_doit[R_EC_B163] = 2;
else if (strcmp(*argv, "ecdsab233") == 0)
ecdsa_doit[R_EC_B233] = 2;
else if (strcmp(*argv, "ecdsab283") == 0)
ecdsa_doit[R_EC_B283] = 2;
else if (strcmp(*argv, "ecdsab409") == 0)
ecdsa_doit[R_EC_B409] = 2;
else if (strcmp(*argv, "ecdsab571") == 0)
ecdsa_doit[R_EC_B571] = 2;
else if (strcmp(*argv, "ecdsa") == 0) {
for (i = 0; i < EC_NUM; i++)
ecdsa_doit[i] = 1;
} else
# endif
# ifndef OPENSSL_NO_ECDH
if (strcmp(*argv, "ecdhp160") == 0)
ecdh_doit[R_EC_P160] = 2;
else if (strcmp(*argv, "ecdhp192") == 0)
ecdh_doit[R_EC_P192] = 2;
else if (strcmp(*argv, "ecdhp224") == 0)
ecdh_doit[R_EC_P224] = 2;
else if (strcmp(*argv, "ecdhp256") == 0)
ecdh_doit[R_EC_P256] = 2;
else if (strcmp(*argv, "ecdhp384") == 0)
ecdh_doit[R_EC_P384] = 2;
else if (strcmp(*argv, "ecdhp521") == 0)
ecdh_doit[R_EC_P521] = 2;
else if (strcmp(*argv, "ecdhk163") == 0)
ecdh_doit[R_EC_K163] = 2;
else if (strcmp(*argv, "ecdhk233") == 0)
ecdh_doit[R_EC_K233] = 2;
else if (strcmp(*argv, "ecdhk283") == 0)
ecdh_doit[R_EC_K283] = 2;
else if (strcmp(*argv, "ecdhk409") == 0)
ecdh_doit[R_EC_K409] = 2;
else if (strcmp(*argv, "ecdhk571") == 0)
ecdh_doit[R_EC_K571] = 2;
else if (strcmp(*argv, "ecdhb163") == 0)
ecdh_doit[R_EC_B163] = 2;
else if (strcmp(*argv, "ecdhb233") == 0)
ecdh_doit[R_EC_B233] = 2;
else if (strcmp(*argv, "ecdhb283") == 0)
ecdh_doit[R_EC_B283] = 2;
else if (strcmp(*argv, "ecdhb409") == 0)
ecdh_doit[R_EC_B409] = 2;
else if (strcmp(*argv, "ecdhb571") == 0)
ecdh_doit[R_EC_B571] = 2;
else if (strcmp(*argv, "ecdh") == 0) {
for (i = 0; i < EC_NUM; i++)
ecdh_doit[i] = 1;
} else
# endif
{
BIO_printf(bio_err, "Error: bad option or value\n");
BIO_printf(bio_err, "\n");
BIO_printf(bio_err, "Available values:\n");
# ifndef OPENSSL_NO_MD2
BIO_printf(bio_err, "md2 ");
# endif
# ifndef OPENSSL_NO_MDC2
BIO_printf(bio_err, "mdc2 ");
# endif
# ifndef OPENSSL_NO_MD4
BIO_printf(bio_err, "md4 ");
# endif
# ifndef OPENSSL_NO_MD5
BIO_printf(bio_err, "md5 ");
# ifndef OPENSSL_NO_HMAC
BIO_printf(bio_err, "hmac ");
# endif
# endif
# ifndef OPENSSL_NO_SHA1
BIO_printf(bio_err, "sha1 ");
# endif
# ifndef OPENSSL_NO_SHA256
BIO_printf(bio_err, "sha256 ");
# endif
# ifndef OPENSSL_NO_SHA512
BIO_printf(bio_err, "sha512 ");
# endif
# ifndef OPENSSL_NO_WHIRLPOOL
BIO_printf(bio_err, "whirlpool");
# endif
# ifndef OPENSSL_NO_RIPEMD160
BIO_printf(bio_err, "rmd160");
# endif
# if !defined(OPENSSL_NO_MD2) || !defined(OPENSSL_NO_MDC2) || \
!defined(OPENSSL_NO_MD4) || !defined(OPENSSL_NO_MD5) || \
!defined(OPENSSL_NO_SHA1) || !defined(OPENSSL_NO_RIPEMD160) || \
!defined(OPENSSL_NO_WHIRLPOOL)
BIO_printf(bio_err, "\n");
# endif
# ifndef OPENSSL_NO_IDEA
BIO_printf(bio_err, "idea-cbc ");
# endif
# ifndef OPENSSL_NO_SEED
BIO_printf(bio_err, "seed-cbc ");
# endif
# ifndef OPENSSL_NO_RC2
BIO_printf(bio_err, "rc2-cbc ");
# endif
# ifndef OPENSSL_NO_RC5
BIO_printf(bio_err, "rc5-cbc ");
# endif
# ifndef OPENSSL_NO_BF
BIO_printf(bio_err, "bf-cbc");
# endif
# if !defined(OPENSSL_NO_IDEA) || !defined(OPENSSL_NO_SEED) || !defined(OPENSSL_NO_RC2) || \
!defined(OPENSSL_NO_BF) || !defined(OPENSSL_NO_RC5)
BIO_printf(bio_err, "\n");
# endif
# ifndef OPENSSL_NO_DES
BIO_printf(bio_err, "des-cbc des-ede3 ");
# endif
# ifndef OPENSSL_NO_AES
BIO_printf(bio_err, "aes-128-cbc aes-192-cbc aes-256-cbc ");
BIO_printf(bio_err, "aes-128-ige aes-192-ige aes-256-ige ");
# endif
# ifndef OPENSSL_NO_CAMELLIA
BIO_printf(bio_err, "\n");
BIO_printf(bio_err,
"camellia-128-cbc camellia-192-cbc camellia-256-cbc ");
# endif
# ifndef OPENSSL_NO_RC4
BIO_printf(bio_err, "rc4");
# endif
BIO_printf(bio_err, "\n");
# ifndef OPENSSL_NO_RSA
BIO_printf(bio_err, "rsa512 rsa1024 rsa2048 rsa4096\n");
# endif
# ifndef OPENSSL_NO_DSA
BIO_printf(bio_err, "dsa512 dsa1024 dsa2048\n");
# endif
# ifndef OPENSSL_NO_ECDSA
BIO_printf(bio_err, "ecdsap160 ecdsap192 ecdsap224 "
"ecdsap256 ecdsap384 ecdsap521\n");
BIO_printf(bio_err,
"ecdsak163 ecdsak233 ecdsak283 ecdsak409 ecdsak571\n");
BIO_printf(bio_err,
"ecdsab163 ecdsab233 ecdsab283 ecdsab409 ecdsab571\n");
BIO_printf(bio_err, "ecdsa\n");
# endif
# ifndef OPENSSL_NO_ECDH
BIO_printf(bio_err, "ecdhp160 ecdhp192 ecdhp224 "
"ecdhp256 ecdhp384 ecdhp521\n");
BIO_printf(bio_err,
"ecdhk163 ecdhk233 ecdhk283 ecdhk409 ecdhk571\n");
BIO_printf(bio_err,
"ecdhb163 ecdhb233 ecdhb283 ecdhb409 ecdhb571\n");
BIO_printf(bio_err, "ecdh\n");
# endif
# ifndef OPENSSL_NO_IDEA
BIO_printf(bio_err, "idea ");
# endif
# ifndef OPENSSL_NO_SEED
BIO_printf(bio_err, "seed ");
# endif
# ifndef OPENSSL_NO_RC2
BIO_printf(bio_err, "rc2 ");
# endif
# ifndef OPENSSL_NO_DES
BIO_printf(bio_err, "des ");
# endif
# ifndef OPENSSL_NO_AES
BIO_printf(bio_err, "aes ");
# endif
# ifndef OPENSSL_NO_CAMELLIA
BIO_printf(bio_err, "camellia ");
# endif
# ifndef OPENSSL_NO_RSA
BIO_printf(bio_err, "rsa ");
# endif
# ifndef OPENSSL_NO_BF
BIO_printf(bio_err, "blowfish");
# endif
# if !defined(OPENSSL_NO_IDEA) || !defined(OPENSSL_NO_SEED) || \
!defined(OPENSSL_NO_RC2) || !defined(OPENSSL_NO_DES) || \
!defined(OPENSSL_NO_RSA) || !defined(OPENSSL_NO_BF) || \
!defined(OPENSSL_NO_AES) || !defined(OPENSSL_NO_CAMELLIA)
BIO_printf(bio_err, "\n");
# endif
BIO_printf(bio_err, "\n");
BIO_printf(bio_err, "Available options:\n");
# if defined(TIMES) || defined(USE_TOD)
BIO_printf(bio_err, "-elapsed "
"measure time in real time instead of CPU user time.\n");
# endif
# ifndef OPENSSL_NO_ENGINE
BIO_printf(bio_err,
"-engine e "
"use engine e, possibly a hardware device.\n");
# endif
BIO_printf(bio_err, "-evp e " "use EVP e.\n");
BIO_printf(bio_err,
"-decrypt "
"time decryption instead of encryption (only EVP).\n");
BIO_printf(bio_err,
"-mr "
"produce machine readable output.\n");
# ifndef NO_FORK
BIO_printf(bio_err,
"-multi n " "run n benchmarks in parallel.\n");
# endif
goto end;
}
argc--;
argv++;
j++;
}
# ifndef NO_FORK
if (multi && do_multi(multi))
goto show_res;
# endif
if (j == 0) {
for (i = 0; i < ALGOR_NUM; i++) {
if (i != D_EVP)
doit[i] = 1;
}
for (i = 0; i < RSA_NUM; i++)
rsa_doit[i] = 1;
for (i = 0; i < DSA_NUM; i++)
dsa_doit[i] = 1;
# ifndef OPENSSL_NO_ECDSA
for (i = 0; i < EC_NUM; i++)
ecdsa_doit[i] = 1;
# endif
# ifndef OPENSSL_NO_ECDH
for (i = 0; i < EC_NUM; i++)
ecdh_doit[i] = 1;
# endif
}
for (i = 0; i < ALGOR_NUM; i++)
if (doit[i])
pr_header++;
if (usertime == 0 && !mr)
BIO_printf(bio_err,
"You have chosen to measure elapsed time "
"instead of user CPU time.\n");
# ifndef OPENSSL_NO_RSA
for (i = 0; i < RSA_NUM; i++) {
const unsigned char *p;
p = rsa_data[i];
rsa_key[i] = d2i_RSAPrivateKey(NULL, &p, rsa_data_length[i]);
if (rsa_key[i] == NULL) {
BIO_printf(bio_err, "internal error loading RSA key number %d\n",
i);
goto end;
}
# if 0
else {
BIO_printf(bio_err,
mr ? "+RK:%d:"
: "Loaded RSA key, %d bit modulus and e= 0x",
BN_num_bits(rsa_key[i]->n));
BN_print(bio_err, rsa_key[i]->e);
BIO_printf(bio_err, "\n");
}
# endif
}
# endif
# ifndef OPENSSL_NO_DSA
dsa_key[0] = get_dsa512();
dsa_key[1] = get_dsa1024();
dsa_key[2] = get_dsa2048();
# endif
# ifndef OPENSSL_NO_DES
DES_set_key_unchecked(&key, &sch);
DES_set_key_unchecked(&key2, &sch2);
DES_set_key_unchecked(&key3, &sch3);
# endif
# ifndef OPENSSL_NO_AES
AES_set_encrypt_key(key16, 128, &aes_ks1);
AES_set_encrypt_key(key24, 192, &aes_ks2);
AES_set_encrypt_key(key32, 256, &aes_ks3);
# endif
# ifndef OPENSSL_NO_CAMELLIA
Camellia_set_key(key16, 128, &camellia_ks1);
Camellia_set_key(ckey24, 192, &camellia_ks2);
Camellia_set_key(ckey32, 256, &camellia_ks3);
# endif
# ifndef OPENSSL_NO_IDEA
idea_set_encrypt_key(key16, &idea_ks);
# endif
# ifndef OPENSSL_NO_SEED
SEED_set_key(key16, &seed_ks);
# endif
# ifndef OPENSSL_NO_RC4
RC4_set_key(&rc4_ks, 16, key16);
# endif
# ifndef OPENSSL_NO_RC2
RC2_set_key(&rc2_ks, 16, key16, 128);
# endif
# ifndef OPENSSL_NO_RC5
RC5_32_set_key(&rc5_ks, 16, key16, 12);
# endif
# ifndef OPENSSL_NO_BF
BF_set_key(&bf_ks, 16, key16);
# endif
# ifndef OPENSSL_NO_CAST
CAST_set_key(&cast_ks, 16, key16);
# endif
# ifndef OPENSSL_NO_RSA
memset(rsa_c, 0, sizeof(rsa_c));
# endif
# ifndef SIGALRM
# ifndef OPENSSL_NO_DES
BIO_printf(bio_err, "First we calculate the approximate speed ...\n");
count = 10;
do {
long it;
count *= 2;
Time_F(START);
for (it = count; it; it--)
DES_ecb_encrypt((DES_cblock *)buf,
(DES_cblock *)buf, &sch, DES_ENCRYPT);
d = Time_F(STOP);
} while (d < 3);
save_count = count;
c[D_MD2][0] = count / 10;
c[D_MDC2][0] = count / 10;
c[D_MD4][0] = count;
c[D_MD5][0] = count;
c[D_HMAC][0] = count;
c[D_SHA1][0] = count;
c[D_RMD160][0] = count;
c[D_RC4][0] = count * 5;
c[D_CBC_DES][0] = count;
c[D_EDE3_DES][0] = count / 3;
c[D_CBC_IDEA][0] = count;
c[D_CBC_SEED][0] = count;
c[D_CBC_RC2][0] = count;
c[D_CBC_RC5][0] = count;
c[D_CBC_BF][0] = count;
c[D_CBC_CAST][0] = count;
c[D_CBC_128_AES][0] = count;
c[D_CBC_192_AES][0] = count;
c[D_CBC_256_AES][0] = count;
c[D_CBC_128_CML][0] = count;
c[D_CBC_192_CML][0] = count;
c[D_CBC_256_CML][0] = count;
c[D_SHA256][0] = count;
c[D_SHA512][0] = count;
c[D_WHIRLPOOL][0] = count;
c[D_IGE_128_AES][0] = count;
c[D_IGE_192_AES][0] = count;
c[D_IGE_256_AES][0] = count;
c[D_GHASH][0] = count;
for (i = 1; i < SIZE_NUM; i++) {
c[D_MD2][i] = c[D_MD2][0] * 4 * lengths[0] / lengths[i];
c[D_MDC2][i] = c[D_MDC2][0] * 4 * lengths[0] / lengths[i];
c[D_MD4][i] = c[D_MD4][0] * 4 * lengths[0] / lengths[i];
c[D_MD5][i] = c[D_MD5][0] * 4 * lengths[0] / lengths[i];
c[D_HMAC][i] = c[D_HMAC][0] * 4 * lengths[0] / lengths[i];
c[D_SHA1][i] = c[D_SHA1][0] * 4 * lengths[0] / lengths[i];
c[D_RMD160][i] = c[D_RMD160][0] * 4 * lengths[0] / lengths[i];
c[D_SHA256][i] = c[D_SHA256][0] * 4 * lengths[0] / lengths[i];
c[D_SHA512][i] = c[D_SHA512][0] * 4 * lengths[0] / lengths[i];
c[D_WHIRLPOOL][i] = c[D_WHIRLPOOL][0] * 4 * lengths[0] / lengths[i];
}
for (i = 1; i < SIZE_NUM; i++) {
long l0, l1;
l0 = (long)lengths[i - 1];
l1 = (long)lengths[i];
c[D_RC4][i] = c[D_RC4][i - 1] * l0 / l1;
c[D_CBC_DES][i] = c[D_CBC_DES][i - 1] * l0 / l1;
c[D_EDE3_DES][i] = c[D_EDE3_DES][i - 1] * l0 / l1;
c[D_CBC_IDEA][i] = c[D_CBC_IDEA][i - 1] * l0 / l1;
c[D_CBC_SEED][i] = c[D_CBC_SEED][i - 1] * l0 / l1;
c[D_CBC_RC2][i] = c[D_CBC_RC2][i - 1] * l0 / l1;
c[D_CBC_RC5][i] = c[D_CBC_RC5][i - 1] * l0 / l1;
c[D_CBC_BF][i] = c[D_CBC_BF][i - 1] * l0 / l1;
c[D_CBC_CAST][i] = c[D_CBC_CAST][i - 1] * l0 / l1;
c[D_CBC_128_AES][i] = c[D_CBC_128_AES][i - 1] * l0 / l1;
c[D_CBC_192_AES][i] = c[D_CBC_192_AES][i - 1] * l0 / l1;
c[D_CBC_256_AES][i] = c[D_CBC_256_AES][i - 1] * l0 / l1;
c[D_CBC_128_CML][i] = c[D_CBC_128_CML][i - 1] * l0 / l1;
c[D_CBC_192_CML][i] = c[D_CBC_192_CML][i - 1] * l0 / l1;
c[D_CBC_256_CML][i] = c[D_CBC_256_CML][i - 1] * l0 / l1;
c[D_IGE_128_AES][i] = c[D_IGE_128_AES][i - 1] * l0 / l1;
c[D_IGE_192_AES][i] = c[D_IGE_192_AES][i - 1] * l0 / l1;
c[D_IGE_256_AES][i] = c[D_IGE_256_AES][i - 1] * l0 / l1;
}
# ifndef OPENSSL_NO_RSA
rsa_c[R_RSA_512][0] = count / 2000;
rsa_c[R_RSA_512][1] = count / 400;
for (i = 1; i < RSA_NUM; i++) {
rsa_c[i][0] = rsa_c[i - 1][0] / 8;
rsa_c[i][1] = rsa_c[i - 1][1] / 4;
if ((rsa_doit[i] <= 1) && (rsa_c[i][0] == 0))
rsa_doit[i] = 0;
else {
if (rsa_c[i][0] == 0) {
rsa_c[i][0] = 1;
rsa_c[i][1] = 20;
}
}
}
# endif
# ifndef OPENSSL_NO_DSA
dsa_c[R_DSA_512][0] = count / 1000;
dsa_c[R_DSA_512][1] = count / 1000 / 2;
for (i = 1; i < DSA_NUM; i++) {
dsa_c[i][0] = dsa_c[i - 1][0] / 4;
dsa_c[i][1] = dsa_c[i - 1][1] / 4;
if ((dsa_doit[i] <= 1) && (dsa_c[i][0] == 0))
dsa_doit[i] = 0;
else {
if (dsa_c[i] == 0) {
dsa_c[i][0] = 1;
dsa_c[i][1] = 1;
}
}
}
# endif
# ifndef OPENSSL_NO_ECDSA
ecdsa_c[R_EC_P160][0] = count / 1000;
ecdsa_c[R_EC_P160][1] = count / 1000 / 2;
for (i = R_EC_P192; i <= R_EC_P521; i++) {
ecdsa_c[i][0] = ecdsa_c[i - 1][0] / 2;
ecdsa_c[i][1] = ecdsa_c[i - 1][1] / 2;
if ((ecdsa_doit[i] <= 1) && (ecdsa_c[i][0] == 0))
ecdsa_doit[i] = 0;
else {
if (ecdsa_c[i] == 0) {
ecdsa_c[i][0] = 1;
ecdsa_c[i][1] = 1;
}
}
}
ecdsa_c[R_EC_K163][0] = count / 1000;
ecdsa_c[R_EC_K163][1] = count / 1000 / 2;
for (i = R_EC_K233; i <= R_EC_K571; i++) {
ecdsa_c[i][0] = ecdsa_c[i - 1][0] / 2;
ecdsa_c[i][1] = ecdsa_c[i - 1][1] / 2;
if ((ecdsa_doit[i] <= 1) && (ecdsa_c[i][0] == 0))
ecdsa_doit[i] = 0;
else {
if (ecdsa_c[i] == 0) {
ecdsa_c[i][0] = 1;
ecdsa_c[i][1] = 1;
}
}
}
ecdsa_c[R_EC_B163][0] = count / 1000;
ecdsa_c[R_EC_B163][1] = count / 1000 / 2;
for (i = R_EC_B233; i <= R_EC_B571; i++) {
ecdsa_c[i][0] = ecdsa_c[i - 1][0] / 2;
ecdsa_c[i][1] = ecdsa_c[i - 1][1] / 2;
if ((ecdsa_doit[i] <= 1) && (ecdsa_c[i][0] == 0))
ecdsa_doit[i] = 0;
else {
if (ecdsa_c[i] == 0) {
ecdsa_c[i][0] = 1;
ecdsa_c[i][1] = 1;
}
}
}
# endif
# ifndef OPENSSL_NO_ECDH
ecdh_c[R_EC_P160][0] = count / 1000;
ecdh_c[R_EC_P160][1] = count / 1000;
for (i = R_EC_P192; i <= R_EC_P521; i++) {
ecdh_c[i][0] = ecdh_c[i - 1][0] / 2;
ecdh_c[i][1] = ecdh_c[i - 1][1] / 2;
if ((ecdh_doit[i] <= 1) && (ecdh_c[i][0] == 0))
ecdh_doit[i] = 0;
else {
if (ecdh_c[i] == 0) {
ecdh_c[i][0] = 1;
ecdh_c[i][1] = 1;
}
}
}
ecdh_c[R_EC_K163][0] = count / 1000;
ecdh_c[R_EC_K163][1] = count / 1000;
for (i = R_EC_K233; i <= R_EC_K571; i++) {
ecdh_c[i][0] = ecdh_c[i - 1][0] / 2;
ecdh_c[i][1] = ecdh_c[i - 1][1] / 2;
if ((ecdh_doit[i] <= 1) && (ecdh_c[i][0] == 0))
ecdh_doit[i] = 0;
else {
if (ecdh_c[i] == 0) {
ecdh_c[i][0] = 1;
ecdh_c[i][1] = 1;
}
}
}
ecdh_c[R_EC_B163][0] = count / 1000;
ecdh_c[R_EC_B163][1] = count / 1000;
for (i = R_EC_B233; i <= R_EC_B571; i++) {
ecdh_c[i][0] = ecdh_c[i - 1][0] / 2;
ecdh_c[i][1] = ecdh_c[i - 1][1] / 2;
if ((ecdh_doit[i] <= 1) && (ecdh_c[i][0] == 0))
ecdh_doit[i] = 0;
else {
if (ecdh_c[i] == 0) {
ecdh_c[i][0] = 1;
ecdh_c[i][1] = 1;
}
}
}
# endif
# define COND(d) (count < (d))
# define COUNT(d) (d)
# else
/* not worth fixing */
# error "You cannot disable DES on systems without SIGALRM."
# endif /* OPENSSL_NO_DES */
# else
# define COND(c) (run && count<0x7fffffff)
# define COUNT(d) (count)
# ifndef _WIN32
signal(SIGALRM, sig_done);
# endif
# endif /* SIGALRM */
# ifndef OPENSSL_NO_MD2
if (doit[D_MD2]) {
for (j = 0; j < SIZE_NUM; j++) {
print_message(names[D_MD2], c[D_MD2][j], lengths[j]);
Time_F(START);
for (count = 0, run = 1; COND(c[D_MD2][j]); count++)
EVP_Digest(buf, (unsigned long)lengths[j], &(md2[0]), NULL,
EVP_md2(), NULL);
d = Time_F(STOP);
print_result(D_MD2, j, count, d);
}
}
# endif
# ifndef OPENSSL_NO_MDC2
if (doit[D_MDC2]) {
for (j = 0; j < SIZE_NUM; j++) {
print_message(names[D_MDC2], c[D_MDC2][j], lengths[j]);
Time_F(START);
for (count = 0, run = 1; COND(c[D_MDC2][j]); count++)
EVP_Digest(buf, (unsigned long)lengths[j], &(mdc2[0]), NULL,
EVP_mdc2(), NULL);
d = Time_F(STOP);
print_result(D_MDC2, j, count, d);
}
}
# endif
# ifndef OPENSSL_NO_MD4
if (doit[D_MD4]) {
for (j = 0; j < SIZE_NUM; j++) {
print_message(names[D_MD4], c[D_MD4][j], lengths[j]);
Time_F(START);
for (count = 0, run = 1; COND(c[D_MD4][j]); count++)
EVP_Digest(&(buf[0]), (unsigned long)lengths[j], &(md4[0]),
NULL, EVP_md4(), NULL);
d = Time_F(STOP);
print_result(D_MD4, j, count, d);
}
}
# endif
# ifndef OPENSSL_NO_MD5
if (doit[D_MD5]) {
for (j = 0; j < SIZE_NUM; j++) {
print_message(names[D_MD5], c[D_MD5][j], lengths[j]);
Time_F(START);
for (count = 0, run = 1; COND(c[D_MD5][j]); count++)
EVP_Digest(&(buf[0]), (unsigned long)lengths[j], &(md5[0]),
NULL, EVP_get_digestbyname("md5"), NULL);
d = Time_F(STOP);
print_result(D_MD5, j, count, d);
}
}
# endif
# if !defined(OPENSSL_NO_MD5) && !defined(OPENSSL_NO_HMAC)
if (doit[D_HMAC]) {
HMAC_CTX hctx;
HMAC_CTX_init(&hctx);
HMAC_Init_ex(&hctx, (unsigned char *)"This is a key...",
16, EVP_md5(), NULL);
for (j = 0; j < SIZE_NUM; j++) {
print_message(names[D_HMAC], c[D_HMAC][j], lengths[j]);
Time_F(START);
for (count = 0, run = 1; COND(c[D_HMAC][j]); count++) {
HMAC_Init_ex(&hctx, NULL, 0, NULL, NULL);
HMAC_Update(&hctx, buf, lengths[j]);
HMAC_Final(&hctx, &(hmac[0]), NULL);
}
d = Time_F(STOP);
print_result(D_HMAC, j, count, d);
}
HMAC_CTX_cleanup(&hctx);
}
# endif
# ifndef OPENSSL_NO_SHA
if (doit[D_SHA1]) {
for (j = 0; j < SIZE_NUM; j++) {
print_message(names[D_SHA1], c[D_SHA1][j], lengths[j]);
Time_F(START);
for (count = 0, run = 1; COND(c[D_SHA1][j]); count++)
EVP_Digest(buf, (unsigned long)lengths[j], &(sha[0]), NULL,
EVP_sha1(), NULL);
d = Time_F(STOP);
print_result(D_SHA1, j, count, d);
}
}
# ifndef OPENSSL_NO_SHA256
if (doit[D_SHA256]) {
for (j = 0; j < SIZE_NUM; j++) {
print_message(names[D_SHA256], c[D_SHA256][j], lengths[j]);
Time_F(START);
for (count = 0, run = 1; COND(c[D_SHA256][j]); count++)
SHA256(buf, lengths[j], sha256);
d = Time_F(STOP);
print_result(D_SHA256, j, count, d);
}
}
# endif
# ifndef OPENSSL_NO_SHA512
if (doit[D_SHA512]) {
for (j = 0; j < SIZE_NUM; j++) {
print_message(names[D_SHA512], c[D_SHA512][j], lengths[j]);
Time_F(START);
for (count = 0, run = 1; COND(c[D_SHA512][j]); count++)
SHA512(buf, lengths[j], sha512);
d = Time_F(STOP);
print_result(D_SHA512, j, count, d);
}
}
# endif
# endif
# ifndef OPENSSL_NO_WHIRLPOOL
if (doit[D_WHIRLPOOL]) {
for (j = 0; j < SIZE_NUM; j++) {
print_message(names[D_WHIRLPOOL], c[D_WHIRLPOOL][j], lengths[j]);
Time_F(START);
for (count = 0, run = 1; COND(c[D_WHIRLPOOL][j]); count++)
WHIRLPOOL(buf, lengths[j], whirlpool);
d = Time_F(STOP);
print_result(D_WHIRLPOOL, j, count, d);
}
}
# endif
# ifndef OPENSSL_NO_RIPEMD
if (doit[D_RMD160]) {
for (j = 0; j < SIZE_NUM; j++) {
print_message(names[D_RMD160], c[D_RMD160][j], lengths[j]);
Time_F(START);
for (count = 0, run = 1; COND(c[D_RMD160][j]); count++)
EVP_Digest(buf, (unsigned long)lengths[j], &(rmd160[0]), NULL,
EVP_ripemd160(), NULL);
d = Time_F(STOP);
print_result(D_RMD160, j, count, d);
}
}
# endif
# ifndef OPENSSL_NO_RC4
if (doit[D_RC4]) {
for (j = 0; j < SIZE_NUM; j++) {
print_message(names[D_RC4], c[D_RC4][j], lengths[j]);
Time_F(START);
for (count = 0, run = 1; COND(c[D_RC4][j]); count++)
RC4(&rc4_ks, (unsigned int)lengths[j], buf, buf);
d = Time_F(STOP);
print_result(D_RC4, j, count, d);
}
}
# endif
# ifndef OPENSSL_NO_DES
if (doit[D_CBC_DES]) {
for (j = 0; j < SIZE_NUM; j++) {
print_message(names[D_CBC_DES], c[D_CBC_DES][j], lengths[j]);
Time_F(START);
for (count = 0, run = 1; COND(c[D_CBC_DES][j]); count++)
DES_ncbc_encrypt(buf, buf, lengths[j], &sch,
&DES_iv, DES_ENCRYPT);
d = Time_F(STOP);
print_result(D_CBC_DES, j, count, d);
}
}
if (doit[D_EDE3_DES]) {
for (j = 0; j < SIZE_NUM; j++) {
print_message(names[D_EDE3_DES], c[D_EDE3_DES][j], lengths[j]);
Time_F(START);
for (count = 0, run = 1; COND(c[D_EDE3_DES][j]); count++)
DES_ede3_cbc_encrypt(buf, buf, lengths[j],
&sch, &sch2, &sch3,
&DES_iv, DES_ENCRYPT);
d = Time_F(STOP);
print_result(D_EDE3_DES, j, count, d);
}
}
# endif
# ifndef OPENSSL_NO_AES
if (doit[D_CBC_128_AES]) {
for (j = 0; j < SIZE_NUM; j++) {
print_message(names[D_CBC_128_AES], c[D_CBC_128_AES][j],
lengths[j]);
Time_F(START);
for (count = 0, run = 1; COND(c[D_CBC_128_AES][j]); count++)
AES_cbc_encrypt(buf, buf,
(unsigned long)lengths[j], &aes_ks1,
iv, AES_ENCRYPT);
d = Time_F(STOP);
print_result(D_CBC_128_AES, j, count, d);
}
}
if (doit[D_CBC_192_AES]) {
for (j = 0; j < SIZE_NUM; j++) {
print_message(names[D_CBC_192_AES], c[D_CBC_192_AES][j],
lengths[j]);
Time_F(START);
for (count = 0, run = 1; COND(c[D_CBC_192_AES][j]); count++)
AES_cbc_encrypt(buf, buf,
(unsigned long)lengths[j], &aes_ks2,
iv, AES_ENCRYPT);
d = Time_F(STOP);
print_result(D_CBC_192_AES, j, count, d);
}
}
if (doit[D_CBC_256_AES]) {
for (j = 0; j < SIZE_NUM; j++) {
print_message(names[D_CBC_256_AES], c[D_CBC_256_AES][j],
lengths[j]);
Time_F(START);
for (count = 0, run = 1; COND(c[D_CBC_256_AES][j]); count++)
AES_cbc_encrypt(buf, buf,
(unsigned long)lengths[j], &aes_ks3,
iv, AES_ENCRYPT);
d = Time_F(STOP);
print_result(D_CBC_256_AES, j, count, d);
}
}
if (doit[D_IGE_128_AES]) {
for (j = 0; j < SIZE_NUM; j++) {
print_message(names[D_IGE_128_AES], c[D_IGE_128_AES][j],
lengths[j]);
Time_F(START);
for (count = 0, run = 1; COND(c[D_IGE_128_AES][j]); count++)
AES_ige_encrypt(buf, buf2,
(unsigned long)lengths[j], &aes_ks1,
iv, AES_ENCRYPT);
d = Time_F(STOP);
print_result(D_IGE_128_AES, j, count, d);
}
}
if (doit[D_IGE_192_AES]) {
for (j = 0; j < SIZE_NUM; j++) {
print_message(names[D_IGE_192_AES], c[D_IGE_192_AES][j],
lengths[j]);
Time_F(START);
for (count = 0, run = 1; COND(c[D_IGE_192_AES][j]); count++)
AES_ige_encrypt(buf, buf2,
(unsigned long)lengths[j], &aes_ks2,
iv, AES_ENCRYPT);
d = Time_F(STOP);
print_result(D_IGE_192_AES, j, count, d);
}
}
if (doit[D_IGE_256_AES]) {
for (j = 0; j < SIZE_NUM; j++) {
print_message(names[D_IGE_256_AES], c[D_IGE_256_AES][j],
lengths[j]);
Time_F(START);
for (count = 0, run = 1; COND(c[D_IGE_256_AES][j]); count++)
AES_ige_encrypt(buf, buf2,
(unsigned long)lengths[j], &aes_ks3,
iv, AES_ENCRYPT);
d = Time_F(STOP);
print_result(D_IGE_256_AES, j, count, d);
}
}
if (doit[D_GHASH]) {
GCM128_CONTEXT *ctx =
CRYPTO_gcm128_new(&aes_ks1, (block128_f) AES_encrypt);
CRYPTO_gcm128_setiv(ctx, (unsigned char *)"0123456789ab", 12);
for (j = 0; j < SIZE_NUM; j++) {
print_message(names[D_GHASH], c[D_GHASH][j], lengths[j]);
Time_F(START);
for (count = 0, run = 1; COND(c[D_GHASH][j]); count++)
CRYPTO_gcm128_aad(ctx, buf, lengths[j]);
d = Time_F(STOP);
print_result(D_GHASH, j, count, d);
}
CRYPTO_gcm128_release(ctx);
}
# endif
# ifndef OPENSSL_NO_CAMELLIA
if (doit[D_CBC_128_CML]) {
for (j = 0; j < SIZE_NUM; j++) {
print_message(names[D_CBC_128_CML], c[D_CBC_128_CML][j],
lengths[j]);
Time_F(START);
for (count = 0, run = 1; COND(c[D_CBC_128_CML][j]); count++)
Camellia_cbc_encrypt(buf, buf,
(unsigned long)lengths[j], &camellia_ks1,
iv, CAMELLIA_ENCRYPT);
d = Time_F(STOP);
print_result(D_CBC_128_CML, j, count, d);
}
}
if (doit[D_CBC_192_CML]) {
for (j = 0; j < SIZE_NUM; j++) {
print_message(names[D_CBC_192_CML], c[D_CBC_192_CML][j],
lengths[j]);
Time_F(START);
for (count = 0, run = 1; COND(c[D_CBC_192_CML][j]); count++)
Camellia_cbc_encrypt(buf, buf,
(unsigned long)lengths[j], &camellia_ks2,
iv, CAMELLIA_ENCRYPT);
d = Time_F(STOP);
print_result(D_CBC_192_CML, j, count, d);
}
}
if (doit[D_CBC_256_CML]) {
for (j = 0; j < SIZE_NUM; j++) {
print_message(names[D_CBC_256_CML], c[D_CBC_256_CML][j],
lengths[j]);
Time_F(START);
for (count = 0, run = 1; COND(c[D_CBC_256_CML][j]); count++)
Camellia_cbc_encrypt(buf, buf,
(unsigned long)lengths[j], &camellia_ks3,
iv, CAMELLIA_ENCRYPT);
d = Time_F(STOP);
print_result(D_CBC_256_CML, j, count, d);
}
}
# endif
# ifndef OPENSSL_NO_IDEA
if (doit[D_CBC_IDEA]) {
for (j = 0; j < SIZE_NUM; j++) {
print_message(names[D_CBC_IDEA], c[D_CBC_IDEA][j], lengths[j]);
Time_F(START);
for (count = 0, run = 1; COND(c[D_CBC_IDEA][j]); count++)
idea_cbc_encrypt(buf, buf,
(unsigned long)lengths[j], &idea_ks,
iv, IDEA_ENCRYPT);
d = Time_F(STOP);
print_result(D_CBC_IDEA, j, count, d);
}
}
# endif
# ifndef OPENSSL_NO_SEED
if (doit[D_CBC_SEED]) {
for (j = 0; j < SIZE_NUM; j++) {
print_message(names[D_CBC_SEED], c[D_CBC_SEED][j], lengths[j]);
Time_F(START);
for (count = 0, run = 1; COND(c[D_CBC_SEED][j]); count++)
SEED_cbc_encrypt(buf, buf,
(unsigned long)lengths[j], &seed_ks, iv, 1);
d = Time_F(STOP);
print_result(D_CBC_SEED, j, count, d);
}
}
# endif
# ifndef OPENSSL_NO_RC2
if (doit[D_CBC_RC2]) {
for (j = 0; j < SIZE_NUM; j++) {
print_message(names[D_CBC_RC2], c[D_CBC_RC2][j], lengths[j]);
Time_F(START);
for (count = 0, run = 1; COND(c[D_CBC_RC2][j]); count++)
RC2_cbc_encrypt(buf, buf,
(unsigned long)lengths[j], &rc2_ks,
iv, RC2_ENCRYPT);
d = Time_F(STOP);
print_result(D_CBC_RC2, j, count, d);
}
}
# endif
# ifndef OPENSSL_NO_RC5
if (doit[D_CBC_RC5]) {
for (j = 0; j < SIZE_NUM; j++) {
print_message(names[D_CBC_RC5], c[D_CBC_RC5][j], lengths[j]);
Time_F(START);
for (count = 0, run = 1; COND(c[D_CBC_RC5][j]); count++)
RC5_32_cbc_encrypt(buf, buf,
(unsigned long)lengths[j], &rc5_ks,
iv, RC5_ENCRYPT);
d = Time_F(STOP);
print_result(D_CBC_RC5, j, count, d);
}
}
# endif
# ifndef OPENSSL_NO_BF
if (doit[D_CBC_BF]) {
for (j = 0; j < SIZE_NUM; j++) {
print_message(names[D_CBC_BF], c[D_CBC_BF][j], lengths[j]);
Time_F(START);
for (count = 0, run = 1; COND(c[D_CBC_BF][j]); count++)
BF_cbc_encrypt(buf, buf,
(unsigned long)lengths[j], &bf_ks,
iv, BF_ENCRYPT);
d = Time_F(STOP);
print_result(D_CBC_BF, j, count, d);
}
}
# endif
# ifndef OPENSSL_NO_CAST
if (doit[D_CBC_CAST]) {
for (j = 0; j < SIZE_NUM; j++) {
print_message(names[D_CBC_CAST], c[D_CBC_CAST][j], lengths[j]);
Time_F(START);
for (count = 0, run = 1; COND(c[D_CBC_CAST][j]); count++)
CAST_cbc_encrypt(buf, buf,
(unsigned long)lengths[j], &cast_ks,
iv, CAST_ENCRYPT);
d = Time_F(STOP);
print_result(D_CBC_CAST, j, count, d);
}
}
# endif
if (doit[D_EVP]) {
# ifdef EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK
if (multiblock && evp_cipher) {
if (!
(EVP_CIPHER_flags(evp_cipher) &
EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK)) {
fprintf(stderr, "%s is not multi-block capable\n",
OBJ_nid2ln(evp_cipher->nid));
goto end;
}
multiblock_speed(evp_cipher);
mret = 0;
goto end;
}
# endif
for (j = 0; j < SIZE_NUM; j++) {
if (evp_cipher) {
EVP_CIPHER_CTX ctx;
int outl;
names[D_EVP] = OBJ_nid2ln(evp_cipher->nid);
/*
* -O3 -fschedule-insns messes up an optimization here!
* names[D_EVP] somehow becomes NULL
*/
print_message(names[D_EVP], save_count, lengths[j]);
EVP_CIPHER_CTX_init(&ctx);
if (decrypt)
EVP_DecryptInit_ex(&ctx, evp_cipher, NULL, key16, iv);
else
EVP_EncryptInit_ex(&ctx, evp_cipher, NULL, key16, iv);
EVP_CIPHER_CTX_set_padding(&ctx, 0);
Time_F(START);
if (decrypt)
for (count = 0, run = 1;
COND(save_count * 4 * lengths[0] / lengths[j]);
count++)
EVP_DecryptUpdate(&ctx, buf, &outl, buf, lengths[j]);
else
for (count = 0, run = 1;
COND(save_count * 4 * lengths[0] / lengths[j]);
count++)
EVP_EncryptUpdate(&ctx, buf, &outl, buf, lengths[j]);
if (decrypt)
EVP_DecryptFinal_ex(&ctx, buf, &outl);
else
EVP_EncryptFinal_ex(&ctx, buf, &outl);
d = Time_F(STOP);
EVP_CIPHER_CTX_cleanup(&ctx);
}
if (evp_md) {
names[D_EVP] = OBJ_nid2ln(evp_md->type);
print_message(names[D_EVP], save_count, lengths[j]);
Time_F(START);
for (count = 0, run = 1;
COND(save_count * 4 * lengths[0] / lengths[j]); count++)
EVP_Digest(buf, lengths[j], &(md[0]), NULL, evp_md, NULL);
d = Time_F(STOP);
}
print_result(D_EVP, j, count, d);
}
}
RAND_pseudo_bytes(buf, 36);
# ifndef OPENSSL_NO_RSA
for (j = 0; j < RSA_NUM; j++) {
int ret;
if (!rsa_doit[j])
continue;
ret = RSA_sign(NID_md5_sha1, buf, 36, buf2, &rsa_num, rsa_key[j]);
if (ret == 0) {
BIO_printf(bio_err,
"RSA sign failure. No RSA sign will be done.\n");
ERR_print_errors(bio_err);
rsa_count = 1;
} else {
pkey_print_message("private", "rsa",
rsa_c[j][0], rsa_bits[j], RSA_SECONDS);
/* RSA_blinding_on(rsa_key[j],NULL); */
Time_F(START);
for (count = 0, run = 1; COND(rsa_c[j][0]); count++) {
ret = RSA_sign(NID_md5_sha1, buf, 36, buf2,
&rsa_num, rsa_key[j]);
if (ret == 0) {
BIO_printf(bio_err, "RSA sign failure\n");
ERR_print_errors(bio_err);
count = 1;
break;
}
}
d = Time_F(STOP);
BIO_printf(bio_err,
mr ? "+R1:%ld:%d:%.2f\n"
: "%ld %d bit private RSA's in %.2fs\n",
count, rsa_bits[j], d);
rsa_results[j][0] = d / (double)count;
rsa_count = count;
}
# if 1
ret = RSA_verify(NID_md5_sha1, buf, 36, buf2, rsa_num, rsa_key[j]);
if (ret <= 0) {
BIO_printf(bio_err,
"RSA verify failure. No RSA verify will be done.\n");
ERR_print_errors(bio_err);
rsa_doit[j] = 0;
} else {
pkey_print_message("public", "rsa",
rsa_c[j][1], rsa_bits[j], RSA_SECONDS);
Time_F(START);
for (count = 0, run = 1; COND(rsa_c[j][1]); count++) {
ret = RSA_verify(NID_md5_sha1, buf, 36, buf2,
rsa_num, rsa_key[j]);
if (ret <= 0) {
BIO_printf(bio_err, "RSA verify failure\n");
ERR_print_errors(bio_err);
count = 1;
break;
}
}
d = Time_F(STOP);
BIO_printf(bio_err,
mr ? "+R2:%ld:%d:%.2f\n"
: "%ld %d bit public RSA's in %.2fs\n",
count, rsa_bits[j], d);
rsa_results[j][1] = d / (double)count;
}
# endif
if (rsa_count <= 1) {
/* if longer than 10s, don't do any more */
for (j++; j < RSA_NUM; j++)
rsa_doit[j] = 0;
}
}
# endif
RAND_pseudo_bytes(buf, 20);
# ifndef OPENSSL_NO_DSA
if (RAND_status() != 1) {
- RAND_seed(rnd_seed, sizeof rnd_seed);
+ RAND_seed(rnd_seed, sizeof(rnd_seed));
rnd_fake = 1;
}
for (j = 0; j < DSA_NUM; j++) {
unsigned int kk;
int ret;
if (!dsa_doit[j])
continue;
/* DSA_generate_key(dsa_key[j]); */
/* DSA_sign_setup(dsa_key[j],NULL); */
ret = DSA_sign(EVP_PKEY_DSA, buf, 20, buf2, &kk, dsa_key[j]);
if (ret == 0) {
BIO_printf(bio_err,
"DSA sign failure. No DSA sign will be done.\n");
ERR_print_errors(bio_err);
rsa_count = 1;
} else {
pkey_print_message("sign", "dsa",
dsa_c[j][0], dsa_bits[j], DSA_SECONDS);
Time_F(START);
for (count = 0, run = 1; COND(dsa_c[j][0]); count++) {
ret = DSA_sign(EVP_PKEY_DSA, buf, 20, buf2, &kk, dsa_key[j]);
if (ret == 0) {
BIO_printf(bio_err, "DSA sign failure\n");
ERR_print_errors(bio_err);
count = 1;
break;
}
}
d = Time_F(STOP);
BIO_printf(bio_err,
mr ? "+R3:%ld:%d:%.2f\n"
: "%ld %d bit DSA signs in %.2fs\n",
count, dsa_bits[j], d);
dsa_results[j][0] = d / (double)count;
rsa_count = count;
}
ret = DSA_verify(EVP_PKEY_DSA, buf, 20, buf2, kk, dsa_key[j]);
if (ret <= 0) {
BIO_printf(bio_err,
"DSA verify failure. No DSA verify will be done.\n");
ERR_print_errors(bio_err);
dsa_doit[j] = 0;
} else {
pkey_print_message("verify", "dsa",
dsa_c[j][1], dsa_bits[j], DSA_SECONDS);
Time_F(START);
for (count = 0, run = 1; COND(dsa_c[j][1]); count++) {
ret = DSA_verify(EVP_PKEY_DSA, buf, 20, buf2, kk, dsa_key[j]);
if (ret <= 0) {
BIO_printf(bio_err, "DSA verify failure\n");
ERR_print_errors(bio_err);
count = 1;
break;
}
}
d = Time_F(STOP);
BIO_printf(bio_err,
mr ? "+R4:%ld:%d:%.2f\n"
: "%ld %d bit DSA verify in %.2fs\n",
count, dsa_bits[j], d);
dsa_results[j][1] = d / (double)count;
}
if (rsa_count <= 1) {
/* if longer than 10s, don't do any more */
for (j++; j < DSA_NUM; j++)
dsa_doit[j] = 0;
}
}
if (rnd_fake)
RAND_cleanup();
# endif
# ifndef OPENSSL_NO_ECDSA
if (RAND_status() != 1) {
- RAND_seed(rnd_seed, sizeof rnd_seed);
+ RAND_seed(rnd_seed, sizeof(rnd_seed));
rnd_fake = 1;
}
for (j = 0; j < EC_NUM; j++) {
int ret;
if (!ecdsa_doit[j])
continue; /* Ignore Curve */
ecdsa[j] = EC_KEY_new_by_curve_name(test_curves[j]);
if (ecdsa[j] == NULL) {
BIO_printf(bio_err, "ECDSA failure.\n");
ERR_print_errors(bio_err);
rsa_count = 1;
} else {
# if 1
EC_KEY_precompute_mult(ecdsa[j], NULL);
# endif
/* Perform ECDSA signature test */
EC_KEY_generate_key(ecdsa[j]);
ret = ECDSA_sign(0, buf, 20, ecdsasig, &ecdsasiglen, ecdsa[j]);
if (ret == 0) {
BIO_printf(bio_err,
"ECDSA sign failure. No ECDSA sign will be done.\n");
ERR_print_errors(bio_err);
rsa_count = 1;
} else {
pkey_print_message("sign", "ecdsa",
ecdsa_c[j][0],
test_curves_bits[j], ECDSA_SECONDS);
Time_F(START);
for (count = 0, run = 1; COND(ecdsa_c[j][0]); count++) {
ret = ECDSA_sign(0, buf, 20,
ecdsasig, &ecdsasiglen, ecdsa[j]);
if (ret == 0) {
BIO_printf(bio_err, "ECDSA sign failure\n");
ERR_print_errors(bio_err);
count = 1;
break;
}
}
d = Time_F(STOP);
BIO_printf(bio_err,
mr ? "+R5:%ld:%d:%.2f\n" :
"%ld %d bit ECDSA signs in %.2fs \n",
count, test_curves_bits[j], d);
ecdsa_results[j][0] = d / (double)count;
rsa_count = count;
}
/* Perform ECDSA verification test */
ret = ECDSA_verify(0, buf, 20, ecdsasig, ecdsasiglen, ecdsa[j]);
if (ret != 1) {
BIO_printf(bio_err,
"ECDSA verify failure. No ECDSA verify will be done.\n");
ERR_print_errors(bio_err);
ecdsa_doit[j] = 0;
} else {
pkey_print_message("verify", "ecdsa",
ecdsa_c[j][1],
test_curves_bits[j], ECDSA_SECONDS);
Time_F(START);
for (count = 0, run = 1; COND(ecdsa_c[j][1]); count++) {
ret =
ECDSA_verify(0, buf, 20, ecdsasig, ecdsasiglen,
ecdsa[j]);
if (ret != 1) {
BIO_printf(bio_err, "ECDSA verify failure\n");
ERR_print_errors(bio_err);
count = 1;
break;
}
}
d = Time_F(STOP);
BIO_printf(bio_err,
mr ? "+R6:%ld:%d:%.2f\n"
: "%ld %d bit ECDSA verify in %.2fs\n",
count, test_curves_bits[j], d);
ecdsa_results[j][1] = d / (double)count;
}
if (rsa_count <= 1) {
/* if longer than 10s, don't do any more */
for (j++; j < EC_NUM; j++)
ecdsa_doit[j] = 0;
}
}
}
if (rnd_fake)
RAND_cleanup();
# endif
# ifndef OPENSSL_NO_ECDH
if (RAND_status() != 1) {
- RAND_seed(rnd_seed, sizeof rnd_seed);
+ RAND_seed(rnd_seed, sizeof(rnd_seed));
rnd_fake = 1;
}
for (j = 0; j < EC_NUM; j++) {
if (!ecdh_doit[j])
continue;
ecdh_a[j] = EC_KEY_new_by_curve_name(test_curves[j]);
ecdh_b[j] = EC_KEY_new_by_curve_name(test_curves[j]);
if ((ecdh_a[j] == NULL) || (ecdh_b[j] == NULL)) {
BIO_printf(bio_err, "ECDH failure.\n");
ERR_print_errors(bio_err);
rsa_count = 1;
} else {
/* generate two ECDH key pairs */
if (!EC_KEY_generate_key(ecdh_a[j]) ||
!EC_KEY_generate_key(ecdh_b[j])) {
BIO_printf(bio_err, "ECDH key generation failure.\n");
ERR_print_errors(bio_err);
rsa_count = 1;
} else {
/*
* If field size is not more than 24 octets, then use SHA-1
* hash of result; otherwise, use result (see section 4.8 of
* draft-ietf-tls-ecc-03.txt).
*/
int field_size, outlen;
void *(*kdf) (const void *in, size_t inlen, void *out,
size_t *xoutlen);
field_size =
EC_GROUP_get_degree(EC_KEY_get0_group(ecdh_a[j]));
if (field_size <= 24 * 8) {
outlen = KDF1_SHA1_len;
kdf = KDF1_SHA1;
} else {
outlen = (field_size + 7) / 8;
kdf = NULL;
}
secret_size_a =
ECDH_compute_key(secret_a, outlen,
EC_KEY_get0_public_key(ecdh_b[j]),
ecdh_a[j], kdf);
secret_size_b =
ECDH_compute_key(secret_b, outlen,
EC_KEY_get0_public_key(ecdh_a[j]),
ecdh_b[j], kdf);
if (secret_size_a != secret_size_b)
ecdh_checks = 0;
else
ecdh_checks = 1;
for (secret_idx = 0; (secret_idx < secret_size_a)
&& (ecdh_checks == 1); secret_idx++) {
if (secret_a[secret_idx] != secret_b[secret_idx])
ecdh_checks = 0;
}
if (ecdh_checks == 0) {
BIO_printf(bio_err, "ECDH computations don't match.\n");
ERR_print_errors(bio_err);
rsa_count = 1;
}
pkey_print_message("", "ecdh",
ecdh_c[j][0],
test_curves_bits[j], ECDH_SECONDS);
Time_F(START);
for (count = 0, run = 1; COND(ecdh_c[j][0]); count++) {
ECDH_compute_key(secret_a, outlen,
EC_KEY_get0_public_key(ecdh_b[j]),
ecdh_a[j], kdf);
}
d = Time_F(STOP);
BIO_printf(bio_err,
mr ? "+R7:%ld:%d:%.2f\n" :
"%ld %d-bit ECDH ops in %.2fs\n", count,
test_curves_bits[j], d);
ecdh_results[j][0] = d / (double)count;
rsa_count = count;
}
}
if (rsa_count <= 1) {
/* if longer than 10s, don't do any more */
for (j++; j < EC_NUM; j++)
ecdh_doit[j] = 0;
}
}
if (rnd_fake)
RAND_cleanup();
# endif
# ifndef NO_FORK
show_res:
# endif
if (!mr) {
fprintf(stdout, "%s\n", SSLeay_version(SSLEAY_VERSION));
fprintf(stdout, "%s\n", SSLeay_version(SSLEAY_BUILT_ON));
printf("options:");
printf("%s ", BN_options());
# ifndef OPENSSL_NO_MD2
printf("%s ", MD2_options());
# endif
# ifndef OPENSSL_NO_RC4
printf("%s ", RC4_options());
# endif
# ifndef OPENSSL_NO_DES
printf("%s ", DES_options());
# endif
# ifndef OPENSSL_NO_AES
printf("%s ", AES_options());
# endif
# ifndef OPENSSL_NO_IDEA
printf("%s ", idea_options());
# endif
# ifndef OPENSSL_NO_BF
printf("%s ", BF_options());
# endif
fprintf(stdout, "\n%s\n", SSLeay_version(SSLEAY_CFLAGS));
}
if (pr_header) {
if (mr)
fprintf(stdout, "+H");
else {
fprintf(stdout,
"The 'numbers' are in 1000s of bytes per second processed.\n");
fprintf(stdout, "type ");
}
for (j = 0; j < SIZE_NUM; j++)
fprintf(stdout, mr ? ":%d" : "%7d bytes", lengths[j]);
fprintf(stdout, "\n");
}
for (k = 0; k < ALGOR_NUM; k++) {
if (!doit[k])
continue;
if (mr)
fprintf(stdout, "+F:%d:%s", k, names[k]);
else
fprintf(stdout, "%-13s", names[k]);
for (j = 0; j < SIZE_NUM; j++) {
if (results[k][j] > 10000 && !mr)
fprintf(stdout, " %11.2fk", results[k][j] / 1e3);
else
fprintf(stdout, mr ? ":%.2f" : " %11.2f ", results[k][j]);
}
fprintf(stdout, "\n");
}
# ifndef OPENSSL_NO_RSA
j = 1;
for (k = 0; k < RSA_NUM; k++) {
if (!rsa_doit[k])
continue;
if (j && !mr) {
printf("%18ssign verify sign/s verify/s\n", " ");
j = 0;
}
if (mr)
fprintf(stdout, "+F2:%u:%u:%f:%f\n",
k, rsa_bits[k], rsa_results[k][0], rsa_results[k][1]);
else
fprintf(stdout, "rsa %4u bits %8.6fs %8.6fs %8.1f %8.1f\n",
rsa_bits[k], rsa_results[k][0], rsa_results[k][1],
1.0 / rsa_results[k][0], 1.0 / rsa_results[k][1]);
}
# endif
# ifndef OPENSSL_NO_DSA
j = 1;
for (k = 0; k < DSA_NUM; k++) {
if (!dsa_doit[k])
continue;
if (j && !mr) {
printf("%18ssign verify sign/s verify/s\n", " ");
j = 0;
}
if (mr)
fprintf(stdout, "+F3:%u:%u:%f:%f\n",
k, dsa_bits[k], dsa_results[k][0], dsa_results[k][1]);
else
fprintf(stdout, "dsa %4u bits %8.6fs %8.6fs %8.1f %8.1f\n",
dsa_bits[k], dsa_results[k][0], dsa_results[k][1],
1.0 / dsa_results[k][0], 1.0 / dsa_results[k][1]);
}
# endif
# ifndef OPENSSL_NO_ECDSA
j = 1;
for (k = 0; k < EC_NUM; k++) {
if (!ecdsa_doit[k])
continue;
if (j && !mr) {
printf("%30ssign verify sign/s verify/s\n", " ");
j = 0;
}
if (mr)
fprintf(stdout, "+F4:%u:%u:%f:%f\n",
k, test_curves_bits[k],
ecdsa_results[k][0], ecdsa_results[k][1]);
else
fprintf(stdout,
"%4u bit ecdsa (%s) %8.4fs %8.4fs %8.1f %8.1f\n",
test_curves_bits[k],
test_curves_names[k],
ecdsa_results[k][0], ecdsa_results[k][1],
1.0 / ecdsa_results[k][0], 1.0 / ecdsa_results[k][1]);
}
# endif
# ifndef OPENSSL_NO_ECDH
j = 1;
for (k = 0; k < EC_NUM; k++) {
if (!ecdh_doit[k])
continue;
if (j && !mr) {
printf("%30sop op/s\n", " ");
j = 0;
}
if (mr)
fprintf(stdout, "+F5:%u:%u:%f:%f\n",
k, test_curves_bits[k],
ecdh_results[k][0], 1.0 / ecdh_results[k][0]);
else
fprintf(stdout, "%4u bit ecdh (%s) %8.4fs %8.1f\n",
test_curves_bits[k],
test_curves_names[k],
ecdh_results[k][0], 1.0 / ecdh_results[k][0]);
}
# endif
mret = 0;
end:
ERR_print_errors(bio_err);
if (buf != NULL)
OPENSSL_free(buf);
if (buf2 != NULL)
OPENSSL_free(buf2);
# ifndef OPENSSL_NO_RSA
for (i = 0; i < RSA_NUM; i++)
if (rsa_key[i] != NULL)
RSA_free(rsa_key[i]);
# endif
# ifndef OPENSSL_NO_DSA
for (i = 0; i < DSA_NUM; i++)
if (dsa_key[i] != NULL)
DSA_free(dsa_key[i]);
# endif
# ifndef OPENSSL_NO_ECDSA
for (i = 0; i < EC_NUM; i++)
if (ecdsa[i] != NULL)
EC_KEY_free(ecdsa[i]);
# endif
# ifndef OPENSSL_NO_ECDH
for (i = 0; i < EC_NUM; i++) {
if (ecdh_a[i] != NULL)
EC_KEY_free(ecdh_a[i]);
if (ecdh_b[i] != NULL)
EC_KEY_free(ecdh_b[i]);
}
# endif
release_engine(e);
apps_shutdown();
OPENSSL_EXIT(mret);
}
static void print_message(const char *s, long num, int length)
{
# ifdef SIGALRM
BIO_printf(bio_err,
mr ? "+DT:%s:%d:%d\n"
: "Doing %s for %ds on %d size blocks: ", s, SECONDS, length);
(void)BIO_flush(bio_err);
alarm(SECONDS);
# else
BIO_printf(bio_err,
mr ? "+DN:%s:%ld:%d\n"
: "Doing %s %ld times on %d size blocks: ", s, num, length);
(void)BIO_flush(bio_err);
# endif
# ifdef LINT
num = num;
# endif
}
static void pkey_print_message(const char *str, const char *str2, long num,
int bits, int tm)
{
# ifdef SIGALRM
BIO_printf(bio_err,
mr ? "+DTP:%d:%s:%s:%d\n"
: "Doing %d bit %s %s's for %ds: ", bits, str, str2, tm);
(void)BIO_flush(bio_err);
alarm(tm);
# else
BIO_printf(bio_err,
mr ? "+DNP:%ld:%d:%s:%s\n"
: "Doing %ld %d bit %s %s's: ", num, bits, str, str2);
(void)BIO_flush(bio_err);
# endif
# ifdef LINT
num = num;
# endif
}
static void print_result(int alg, int run_no, int count, double time_used)
{
BIO_printf(bio_err,
mr ? "+R:%d:%s:%f\n"
: "%d %s's in %.2fs\n", count, names[alg], time_used);
results[alg][run_no] = ((double)count) / time_used * lengths[run_no];
}
# ifndef NO_FORK
static char *sstrsep(char **string, const char *delim)
{
char isdelim[256];
char *token = *string;
if (**string == 0)
return NULL;
- memset(isdelim, 0, sizeof isdelim);
+ memset(isdelim, 0, sizeof(isdelim));
isdelim[0] = 1;
while (*delim) {
isdelim[(unsigned char)(*delim)] = 1;
delim++;
}
while (!isdelim[(unsigned char)(**string)]) {
(*string)++;
}
if (**string) {
**string = 0;
(*string)++;
}
return token;
}
static int do_multi(int multi)
{
int n;
int fd[2];
int *fds;
static char sep[] = ":";
- fds = malloc(multi * sizeof *fds);
+ fds = malloc(multi * sizeof(*fds));
if (fds == NULL) {
fprintf(stderr, "Out of memory in speed (do_multi)\n");
exit(1);
}
for (n = 0; n < multi; ++n) {
if (pipe(fd) == -1) {
fprintf(stderr, "pipe failure\n");
exit(1);
}
fflush(stdout);
fflush(stderr);
if (fork()) {
close(fd[1]);
fds[n] = fd[0];
} else {
close(fd[0]);
close(1);
if (dup(fd[1]) == -1) {
fprintf(stderr, "dup failed\n");
exit(1);
}
close(fd[1]);
mr = 1;
usertime = 0;
free(fds);
return 0;
}
printf("Forked child %d\n", n);
}
/* for now, assume the pipe is long enough to take all the output */
for (n = 0; n < multi; ++n) {
FILE *f;
char buf[1024];
char *p;
f = fdopen(fds[n], "r");
- while (fgets(buf, sizeof buf, f)) {
+ while (fgets(buf, sizeof(buf), f)) {
p = strchr(buf, '\n');
if (p)
*p = '\0';
if (buf[0] != '+') {
fprintf(stderr, "Don't understand line '%s' from child %d\n",
buf, n);
continue;
}
printf("Got: %s from %d\n", buf, n);
if (!strncmp(buf, "+F:", 3)) {
int alg;
int j;
p = buf + 3;
alg = atoi(sstrsep(&p, sep));
sstrsep(&p, sep);
for (j = 0; j < SIZE_NUM; ++j)
results[alg][j] += atof(sstrsep(&p, sep));
} else if (!strncmp(buf, "+F2:", 4)) {
int k;
double d;
p = buf + 4;
k = atoi(sstrsep(&p, sep));
sstrsep(&p, sep);
d = atof(sstrsep(&p, sep));
if (n)
rsa_results[k][0] = 1 / (1 / rsa_results[k][0] + 1 / d);
else
rsa_results[k][0] = d;
d = atof(sstrsep(&p, sep));
if (n)
rsa_results[k][1] = 1 / (1 / rsa_results[k][1] + 1 / d);
else
rsa_results[k][1] = d;
}
# ifndef OPENSSL_NO_DSA
else if (!strncmp(buf, "+F3:", 4)) {
int k;
double d;
p = buf + 4;
k = atoi(sstrsep(&p, sep));
sstrsep(&p, sep);
d = atof(sstrsep(&p, sep));
if (n)
dsa_results[k][0] = 1 / (1 / dsa_results[k][0] + 1 / d);
else
dsa_results[k][0] = d;
d = atof(sstrsep(&p, sep));
if (n)
dsa_results[k][1] = 1 / (1 / dsa_results[k][1] + 1 / d);
else
dsa_results[k][1] = d;
}
# endif
# ifndef OPENSSL_NO_ECDSA
else if (!strncmp(buf, "+F4:", 4)) {
int k;
double d;
p = buf + 4;
k = atoi(sstrsep(&p, sep));
sstrsep(&p, sep);
d = atof(sstrsep(&p, sep));
if (n)
ecdsa_results[k][0] =
1 / (1 / ecdsa_results[k][0] + 1 / d);
else
ecdsa_results[k][0] = d;
d = atof(sstrsep(&p, sep));
if (n)
ecdsa_results[k][1] =
1 / (1 / ecdsa_results[k][1] + 1 / d);
else
ecdsa_results[k][1] = d;
}
# endif
# ifndef OPENSSL_NO_ECDH
else if (!strncmp(buf, "+F5:", 4)) {
int k;
double d;
p = buf + 4;
k = atoi(sstrsep(&p, sep));
sstrsep(&p, sep);
d = atof(sstrsep(&p, sep));
if (n)
ecdh_results[k][0] = 1 / (1 / ecdh_results[k][0] + 1 / d);
else
ecdh_results[k][0] = d;
}
# endif
else if (!strncmp(buf, "+H:", 3)) {
} else
fprintf(stderr, "Unknown type '%s' from child %d\n", buf, n);
}
fclose(f);
}
free(fds);
return 1;
}
# endif
static void multiblock_speed(const EVP_CIPHER *evp_cipher)
{
static int mblengths[] =
{ 8 * 1024, 2 * 8 * 1024, 4 * 8 * 1024, 8 * 8 * 1024, 8 * 16 * 1024 };
int j, count, num = sizeof(lengths) / sizeof(lengths[0]);
const char *alg_name;
unsigned char *inp, *out, no_key[32], no_iv[16];
EVP_CIPHER_CTX ctx;
double d = 0.0;
inp = OPENSSL_malloc(mblengths[num - 1]);
out = OPENSSL_malloc(mblengths[num - 1] + 1024);
if (!inp || !out) {
BIO_printf(bio_err,"Out of memory\n");
goto end;
}
EVP_CIPHER_CTX_init(&ctx);
EVP_EncryptInit_ex(&ctx, evp_cipher, NULL, no_key, no_iv);
EVP_CIPHER_CTX_ctrl(&ctx, EVP_CTRL_AEAD_SET_MAC_KEY, sizeof(no_key),
no_key);
alg_name = OBJ_nid2ln(evp_cipher->nid);
for (j = 0; j < num; j++) {
print_message(alg_name, 0, mblengths[j]);
Time_F(START);
for (count = 0, run = 1; run && count < 0x7fffffff; count++) {
unsigned char aad[EVP_AEAD_TLS1_AAD_LEN];
EVP_CTRL_TLS1_1_MULTIBLOCK_PARAM mb_param;
size_t len = mblengths[j];
int packlen;
memset(aad, 0, 8); /* avoid uninitialized values */
aad[8] = 23; /* SSL3_RT_APPLICATION_DATA */
aad[9] = 3; /* version */
aad[10] = 2;
aad[11] = 0; /* length */
aad[12] = 0;
mb_param.out = NULL;
mb_param.inp = aad;
mb_param.len = len;
mb_param.interleave = 8;
packlen = EVP_CIPHER_CTX_ctrl(&ctx,
EVP_CTRL_TLS1_1_MULTIBLOCK_AAD,
sizeof(mb_param), &mb_param);
if (packlen > 0) {
mb_param.out = out;
mb_param.inp = inp;
mb_param.len = len;
EVP_CIPHER_CTX_ctrl(&ctx,
EVP_CTRL_TLS1_1_MULTIBLOCK_ENCRYPT,
sizeof(mb_param), &mb_param);
} else {
int pad;
RAND_bytes(out, 16);
len += 16;
aad[11] = (unsigned char)(len >> 8);
aad[12] = (unsigned char)(len);
pad = EVP_CIPHER_CTX_ctrl(&ctx,
EVP_CTRL_AEAD_TLS1_AAD,
EVP_AEAD_TLS1_AAD_LEN, aad);
EVP_Cipher(&ctx, out, inp, len + pad);
}
}
d = Time_F(STOP);
BIO_printf(bio_err,
mr ? "+R:%d:%s:%f\n"
: "%d %s's in %.2fs\n", count, "evp", d);
results[D_EVP][j] = ((double)count) / d * mblengths[j];
}
if (mr) {
fprintf(stdout, "+H");
for (j = 0; j < num; j++)
fprintf(stdout, ":%d", mblengths[j]);
fprintf(stdout, "\n");
fprintf(stdout, "+F:%d:%s", D_EVP, alg_name);
for (j = 0; j < num; j++)
fprintf(stdout, ":%.2f", results[D_EVP][j]);
fprintf(stdout, "\n");
} else {
fprintf(stdout,
"The 'numbers' are in 1000s of bytes per second processed.\n");
fprintf(stdout, "type ");
for (j = 0; j < num; j++)
fprintf(stdout, "%7d bytes", mblengths[j]);
fprintf(stdout, "\n");
fprintf(stdout, "%-24s", alg_name);
for (j = 0; j < num; j++) {
if (results[D_EVP][j] > 10000)
fprintf(stdout, " %11.2fk", results[D_EVP][j] / 1e3);
else
fprintf(stdout, " %11.2f ", results[D_EVP][j]);
}
fprintf(stdout, "\n");
}
end:
if (inp)
OPENSSL_free(inp);
if (out)
OPENSSL_free(out);
}
#endif
diff --git a/apps/x509.c b/apps/x509.c
index ad9fc98edfb9..add74d556d68 100644
--- a/apps/x509.c
+++ b/apps/x509.c
@@ -1,1278 +1,1278 @@
/* apps/x509.c */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef OPENSSL_NO_STDIO
# define APPS_WIN16
#endif
#include "apps.h"
#include <openssl/bio.h>
#include <openssl/asn1.h>
#include <openssl/err.h>
#include <openssl/bn.h>
#include <openssl/evp.h>
#include <openssl/x509.h>
#include <openssl/x509v3.h>
#include <openssl/objects.h>
#include <openssl/pem.h>
#ifndef OPENSSL_NO_RSA
# include <openssl/rsa.h>
#endif
#ifndef OPENSSL_NO_DSA
# include <openssl/dsa.h>
#endif
#undef PROG
#define PROG x509_main
#undef POSTFIX
#define POSTFIX ".srl"
#define DEF_DAYS 30
static const char *x509_usage[] = {
"usage: x509 args\n",
" -inform arg - input format - default PEM (one of DER, NET or PEM)\n",
" -outform arg - output format - default PEM (one of DER, NET or PEM)\n",
" -keyform arg - private key format - default PEM\n",
" -CAform arg - CA format - default PEM\n",
" -CAkeyform arg - CA key format - default PEM\n",
" -in arg - input file - default stdin\n",
" -out arg - output file - default stdout\n",
" -passin arg - private key password source\n",
" -serial - print serial number value\n",
" -subject_hash - print subject hash value\n",
#ifndef OPENSSL_NO_MD5
" -subject_hash_old - print old-style (MD5) subject hash value\n",
#endif
" -issuer_hash - print issuer hash value\n",
#ifndef OPENSSL_NO_MD5
" -issuer_hash_old - print old-style (MD5) issuer hash value\n",
#endif
" -hash - synonym for -subject_hash\n",
" -subject - print subject DN\n",
" -issuer - print issuer DN\n",
" -email - print email address(es)\n",
" -startdate - notBefore field\n",
" -enddate - notAfter field\n",
" -purpose - print out certificate purposes\n",
" -dates - both Before and After dates\n",
" -modulus - print the RSA key modulus\n",
" -pubkey - output the public key\n",
" -fingerprint - print the certificate fingerprint\n",
" -alias - output certificate alias\n",
" -noout - no certificate output\n",
" -ocspid - print OCSP hash values for the subject name and public key\n",
" -ocsp_uri - print OCSP Responder URL(s)\n",
" -trustout - output a \"trusted\" certificate\n",
" -clrtrust - clear all trusted purposes\n",
" -clrreject - clear all rejected purposes\n",
" -addtrust arg - trust certificate for a given purpose\n",
" -addreject arg - reject certificate for a given purpose\n",
" -setalias arg - set certificate alias\n",
" -days arg - How long till expiry of a signed certificate - def 30 days\n",
" -checkend arg - check whether the cert expires in the next arg seconds\n",
" exit 1 if so, 0 if not\n",
" -signkey arg - self sign cert with arg\n",
" -x509toreq - output a certification request object\n",
" -req - input is a certificate request, sign and output.\n",
" -CA arg - set the CA certificate, must be PEM format.\n",
" -CAkey arg - set the CA key, must be PEM format\n",
" missing, it is assumed to be in the CA file.\n",
" -CAcreateserial - create serial number file if it does not exist\n",
" -CAserial arg - serial file\n",
" -set_serial - serial number to use\n",
" -text - print the certificate in text form\n",
" -C - print out C code forms\n",
" -md2/-md5/-sha1/-mdc2 - digest to use\n",
" -extfile - configuration file with X509V3 extensions to add\n",
" -extensions - section from config file with X509V3 extensions to add\n",
" -clrext - delete extensions before signing and input certificate\n",
" -nameopt arg - various certificate name options\n",
#ifndef OPENSSL_NO_ENGINE
" -engine e - use engine e, possibly a hardware device.\n",
#endif
" -certopt arg - various certificate text options\n",
" -checkhost host - check certificate matches \"host\"\n",
" -checkemail email - check certificate matches \"email\"\n",
" -checkip ipaddr - check certificate matches \"ipaddr\"\n",
NULL
};
static int MS_CALLBACK callb(int ok, X509_STORE_CTX *ctx);
static int sign(X509 *x, EVP_PKEY *pkey, int days, int clrext,
const EVP_MD *digest, CONF *conf, char *section);
static int x509_certify(X509_STORE *ctx, char *CAfile, const EVP_MD *digest,
X509 *x, X509 *xca, EVP_PKEY *pkey,
STACK_OF(OPENSSL_STRING) *sigopts, char *serial,
int create, int days, int clrext, CONF *conf,
char *section, ASN1_INTEGER *sno);
static int purpose_print(BIO *bio, X509 *cert, X509_PURPOSE *pt);
static int reqfile = 0;
#ifdef OPENSSL_SSL_DEBUG_BROKEN_PROTOCOL
static int force_version = 2;
#endif
int MAIN(int, char **);
int MAIN(int argc, char **argv)
{
ENGINE *e = NULL;
int ret = 1;
X509_REQ *req = NULL;
X509 *x = NULL, *xca = NULL;
ASN1_OBJECT *objtmp;
STACK_OF(OPENSSL_STRING) *sigopts = NULL;
EVP_PKEY *Upkey = NULL, *CApkey = NULL, *fkey = NULL;
ASN1_INTEGER *sno = NULL;
int i, num, badops = 0, badsig = 0;
BIO *out = NULL;
BIO *STDout = NULL;
STACK_OF(ASN1_OBJECT) *trust = NULL, *reject = NULL;
int informat, outformat, keyformat, CAformat, CAkeyformat;
char *infile = NULL, *outfile = NULL, *keyfile = NULL, *CAfile = NULL;
char *CAkeyfile = NULL, *CAserial = NULL;
char *fkeyfile = NULL;
char *alias = NULL;
int text = 0, serial = 0, subject = 0, issuer = 0, startdate =
0, enddate = 0;
int next_serial = 0;
int subject_hash = 0, issuer_hash = 0, ocspid = 0;
#ifndef OPENSSL_NO_MD5
int subject_hash_old = 0, issuer_hash_old = 0;
#endif
int noout = 0, sign_flag = 0, CA_flag = 0, CA_createserial = 0, email = 0;
int ocsp_uri = 0;
int trustout = 0, clrtrust = 0, clrreject = 0, aliasout = 0, clrext = 0;
int C = 0;
int x509req = 0, days = DEF_DAYS, modulus = 0, pubkey = 0;
int pprint = 0;
const char **pp;
X509_STORE *ctx = NULL;
X509_REQ *rq = NULL;
int fingerprint = 0;
char buf[256];
const EVP_MD *md_alg, *digest = NULL;
CONF *extconf = NULL;
char *extsect = NULL, *extfile = NULL, *passin = NULL, *passargin = NULL;
int need_rand = 0;
int checkend = 0, checkoffset = 0;
unsigned long nmflag = 0, certflag = 0;
char *checkhost = NULL;
char *checkemail = NULL;
char *checkip = NULL;
char *engine = NULL;
reqfile = 0;
apps_startup();
if (bio_err == NULL)
bio_err = BIO_new_fp(stderr, BIO_NOCLOSE);
if (!load_config(bio_err, NULL))
goto end;
STDout = BIO_new_fp(stdout, BIO_NOCLOSE);
#ifdef OPENSSL_SYS_VMS
{
BIO *tmpbio = BIO_new(BIO_f_linebuffer());
STDout = BIO_push(tmpbio, STDout);
}
#endif
informat = FORMAT_PEM;
outformat = FORMAT_PEM;
keyformat = FORMAT_PEM;
CAformat = FORMAT_PEM;
CAkeyformat = FORMAT_PEM;
ctx = X509_STORE_new();
if (ctx == NULL)
goto end;
X509_STORE_set_verify_cb(ctx, callb);
argc--;
argv++;
num = 0;
while (argc >= 1) {
if (strcmp(*argv, "-inform") == 0) {
if (--argc < 1)
goto bad;
informat = str2fmt(*(++argv));
} else if (strcmp(*argv, "-outform") == 0) {
if (--argc < 1)
goto bad;
outformat = str2fmt(*(++argv));
} else if (strcmp(*argv, "-keyform") == 0) {
if (--argc < 1)
goto bad;
keyformat = str2fmt(*(++argv));
} else if (strcmp(*argv, "-req") == 0) {
reqfile = 1;
need_rand = 1;
} else if (strcmp(*argv, "-CAform") == 0) {
if (--argc < 1)
goto bad;
CAformat = str2fmt(*(++argv));
} else if (strcmp(*argv, "-CAkeyform") == 0) {
if (--argc < 1)
goto bad;
CAkeyformat = str2fmt(*(++argv));
} else if (strcmp(*argv, "-sigopt") == 0) {
if (--argc < 1)
goto bad;
if (!sigopts)
sigopts = sk_OPENSSL_STRING_new_null();
if (!sigopts || !sk_OPENSSL_STRING_push(sigopts, *(++argv)))
goto bad;
}
#ifdef OPENSSL_SSL_DEBUG_BROKEN_PROTOCOL
else if (strcmp(*argv, "-force_version") == 0) {
if (--argc < 1)
goto bad;
force_version = atoi(*(++argv)) - 1;
}
#endif
else if (strcmp(*argv, "-days") == 0) {
if (--argc < 1)
goto bad;
days = atoi(*(++argv));
if (days == 0) {
BIO_printf(bio_err, "bad number of days\n");
goto bad;
}
} else if (strcmp(*argv, "-passin") == 0) {
if (--argc < 1)
goto bad;
passargin = *(++argv);
} else if (strcmp(*argv, "-extfile") == 0) {
if (--argc < 1)
goto bad;
extfile = *(++argv);
} else if (strcmp(*argv, "-extensions") == 0) {
if (--argc < 1)
goto bad;
extsect = *(++argv);
} else if (strcmp(*argv, "-in") == 0) {
if (--argc < 1)
goto bad;
infile = *(++argv);
} else if (strcmp(*argv, "-out") == 0) {
if (--argc < 1)
goto bad;
outfile = *(++argv);
} else if (strcmp(*argv, "-signkey") == 0) {
if (--argc < 1)
goto bad;
keyfile = *(++argv);
sign_flag = ++num;
need_rand = 1;
} else if (strcmp(*argv, "-CA") == 0) {
if (--argc < 1)
goto bad;
CAfile = *(++argv);
CA_flag = ++num;
need_rand = 1;
} else if (strcmp(*argv, "-CAkey") == 0) {
if (--argc < 1)
goto bad;
CAkeyfile = *(++argv);
} else if (strcmp(*argv, "-CAserial") == 0) {
if (--argc < 1)
goto bad;
CAserial = *(++argv);
} else if (strcmp(*argv, "-set_serial") == 0) {
if (--argc < 1)
goto bad;
if (!(sno = s2i_ASN1_INTEGER(NULL, *(++argv))))
goto bad;
} else if (strcmp(*argv, "-force_pubkey") == 0) {
if (--argc < 1)
goto bad;
fkeyfile = *(++argv);
} else if (strcmp(*argv, "-addtrust") == 0) {
if (--argc < 1)
goto bad;
if (!(objtmp = OBJ_txt2obj(*(++argv), 0))) {
BIO_printf(bio_err, "Invalid trust object value %s\n", *argv);
goto bad;
}
if (!trust)
trust = sk_ASN1_OBJECT_new_null();
sk_ASN1_OBJECT_push(trust, objtmp);
trustout = 1;
} else if (strcmp(*argv, "-addreject") == 0) {
if (--argc < 1)
goto bad;
if (!(objtmp = OBJ_txt2obj(*(++argv), 0))) {
BIO_printf(bio_err,
"Invalid reject object value %s\n", *argv);
goto bad;
}
if (!reject)
reject = sk_ASN1_OBJECT_new_null();
sk_ASN1_OBJECT_push(reject, objtmp);
trustout = 1;
} else if (strcmp(*argv, "-setalias") == 0) {
if (--argc < 1)
goto bad;
alias = *(++argv);
trustout = 1;
} else if (strcmp(*argv, "-certopt") == 0) {
if (--argc < 1)
goto bad;
if (!set_cert_ex(&certflag, *(++argv)))
goto bad;
} else if (strcmp(*argv, "-nameopt") == 0) {
if (--argc < 1)
goto bad;
if (!set_name_ex(&nmflag, *(++argv)))
goto bad;
}
#ifndef OPENSSL_NO_ENGINE
else if (strcmp(*argv, "-engine") == 0) {
if (--argc < 1)
goto bad;
engine = *(++argv);
}
#endif
else if (strcmp(*argv, "-C") == 0)
C = ++num;
else if (strcmp(*argv, "-email") == 0)
email = ++num;
else if (strcmp(*argv, "-ocsp_uri") == 0)
ocsp_uri = ++num;
else if (strcmp(*argv, "-serial") == 0)
serial = ++num;
else if (strcmp(*argv, "-next_serial") == 0)
next_serial = ++num;
else if (strcmp(*argv, "-modulus") == 0)
modulus = ++num;
else if (strcmp(*argv, "-pubkey") == 0)
pubkey = ++num;
else if (strcmp(*argv, "-x509toreq") == 0)
x509req = ++num;
else if (strcmp(*argv, "-text") == 0)
text = ++num;
else if (strcmp(*argv, "-hash") == 0
|| strcmp(*argv, "-subject_hash") == 0)
subject_hash = ++num;
#ifndef OPENSSL_NO_MD5
else if (strcmp(*argv, "-subject_hash_old") == 0)
subject_hash_old = ++num;
#endif
else if (strcmp(*argv, "-issuer_hash") == 0)
issuer_hash = ++num;
#ifndef OPENSSL_NO_MD5
else if (strcmp(*argv, "-issuer_hash_old") == 0)
issuer_hash_old = ++num;
#endif
else if (strcmp(*argv, "-subject") == 0)
subject = ++num;
else if (strcmp(*argv, "-issuer") == 0)
issuer = ++num;
else if (strcmp(*argv, "-fingerprint") == 0)
fingerprint = ++num;
else if (strcmp(*argv, "-dates") == 0) {
startdate = ++num;
enddate = ++num;
} else if (strcmp(*argv, "-purpose") == 0)
pprint = ++num;
else if (strcmp(*argv, "-startdate") == 0)
startdate = ++num;
else if (strcmp(*argv, "-enddate") == 0)
enddate = ++num;
else if (strcmp(*argv, "-checkend") == 0) {
if (--argc < 1)
goto bad;
checkoffset = atoi(*(++argv));
checkend = 1;
} else if (strcmp(*argv, "-checkhost") == 0) {
if (--argc < 1)
goto bad;
checkhost = *(++argv);
} else if (strcmp(*argv, "-checkemail") == 0) {
if (--argc < 1)
goto bad;
checkemail = *(++argv);
} else if (strcmp(*argv, "-checkip") == 0) {
if (--argc < 1)
goto bad;
checkip = *(++argv);
} else if (strcmp(*argv, "-noout") == 0)
noout = ++num;
else if (strcmp(*argv, "-trustout") == 0)
trustout = 1;
else if (strcmp(*argv, "-clrtrust") == 0)
clrtrust = ++num;
else if (strcmp(*argv, "-clrreject") == 0)
clrreject = ++num;
else if (strcmp(*argv, "-alias") == 0)
aliasout = ++num;
else if (strcmp(*argv, "-CAcreateserial") == 0)
CA_createserial = ++num;
else if (strcmp(*argv, "-clrext") == 0)
clrext = 1;
#if 1 /* stay backwards-compatible with 0.9.5; this
* should go away soon */
else if (strcmp(*argv, "-crlext") == 0) {
BIO_printf(bio_err, "use -clrext instead of -crlext\n");
clrext = 1;
}
#endif
else if (strcmp(*argv, "-ocspid") == 0)
ocspid = ++num;
else if (strcmp(*argv, "-badsig") == 0)
badsig = 1;
else if ((md_alg = EVP_get_digestbyname(*argv + 1))) {
/* ok */
digest = md_alg;
} else {
BIO_printf(bio_err, "unknown option %s\n", *argv);
badops = 1;
break;
}
argc--;
argv++;
}
if (badops) {
bad:
for (pp = x509_usage; (*pp != NULL); pp++)
BIO_printf(bio_err, "%s", *pp);
goto end;
}
e = setup_engine(bio_err, engine, 0);
if (need_rand)
app_RAND_load_file(NULL, bio_err, 0);
ERR_load_crypto_strings();
if (!app_passwd(bio_err, passargin, NULL, &passin, NULL)) {
BIO_printf(bio_err, "Error getting password\n");
goto end;
}
if (!X509_STORE_set_default_paths(ctx)) {
ERR_print_errors(bio_err);
goto end;
}
if (fkeyfile) {
fkey = load_pubkey(bio_err, fkeyfile, keyformat, 0,
NULL, e, "Forced key");
if (fkey == NULL)
goto end;
}
if ((CAkeyfile == NULL) && (CA_flag) && (CAformat == FORMAT_PEM)) {
CAkeyfile = CAfile;
} else if ((CA_flag) && (CAkeyfile == NULL)) {
BIO_printf(bio_err,
"need to specify a CAkey if using the CA command\n");
goto end;
}
if (extfile) {
long errorline = -1;
X509V3_CTX ctx2;
extconf = NCONF_new(NULL);
if (!NCONF_load(extconf, extfile, &errorline)) {
if (errorline <= 0)
BIO_printf(bio_err,
"error loading the config file '%s'\n", extfile);
else
BIO_printf(bio_err,
"error on line %ld of config file '%s'\n",
errorline, extfile);
goto end;
}
if (!extsect) {
extsect = NCONF_get_string(extconf, "default", "extensions");
if (!extsect) {
ERR_clear_error();
extsect = "default";
}
}
X509V3_set_ctx_test(&ctx2);
X509V3_set_nconf(&ctx2, extconf);
if (!X509V3_EXT_add_nconf(extconf, &ctx2, extsect, NULL)) {
BIO_printf(bio_err,
"Error Loading extension section %s\n", extsect);
ERR_print_errors(bio_err);
goto end;
}
}
if (reqfile) {
EVP_PKEY *pkey;
BIO *in;
if (!sign_flag && !CA_flag) {
BIO_printf(bio_err, "We need a private key to sign with\n");
goto end;
}
in = BIO_new(BIO_s_file());
if (in == NULL) {
ERR_print_errors(bio_err);
goto end;
}
if (infile == NULL)
BIO_set_fp(in, stdin, BIO_NOCLOSE | BIO_FP_TEXT);
else {
if (BIO_read_filename(in, infile) <= 0) {
perror(infile);
BIO_free(in);
goto end;
}
}
req = PEM_read_bio_X509_REQ(in, NULL, NULL, NULL);
BIO_free(in);
if (req == NULL) {
ERR_print_errors(bio_err);
goto end;
}
if ((req->req_info == NULL) ||
(req->req_info->pubkey == NULL) ||
(req->req_info->pubkey->public_key == NULL) ||
(req->req_info->pubkey->public_key->data == NULL)) {
BIO_printf(bio_err,
"The certificate request appears to corrupted\n");
BIO_printf(bio_err, "It does not contain a public key\n");
goto end;
}
if ((pkey = X509_REQ_get_pubkey(req)) == NULL) {
BIO_printf(bio_err, "error unpacking public key\n");
goto end;
}
i = X509_REQ_verify(req, pkey);
EVP_PKEY_free(pkey);
if (i < 0) {
BIO_printf(bio_err, "Signature verification error\n");
ERR_print_errors(bio_err);
goto end;
}
if (i == 0) {
BIO_printf(bio_err,
"Signature did not match the certificate request\n");
goto end;
} else
BIO_printf(bio_err, "Signature ok\n");
print_name(bio_err, "subject=", X509_REQ_get_subject_name(req),
nmflag);
if ((x = X509_new()) == NULL)
goto end;
if (sno == NULL) {
sno = ASN1_INTEGER_new();
if (!sno || !rand_serial(NULL, sno))
goto end;
if (!X509_set_serialNumber(x, sno))
goto end;
ASN1_INTEGER_free(sno);
sno = NULL;
} else if (!X509_set_serialNumber(x, sno))
goto end;
if (!X509_set_issuer_name(x, req->req_info->subject))
goto end;
if (!X509_set_subject_name(x, req->req_info->subject))
goto end;
X509_gmtime_adj(X509_get_notBefore(x), 0);
X509_time_adj_ex(X509_get_notAfter(x), days, 0, NULL);
if (fkey)
X509_set_pubkey(x, fkey);
else {
pkey = X509_REQ_get_pubkey(req);
X509_set_pubkey(x, pkey);
EVP_PKEY_free(pkey);
}
} else
x = load_cert(bio_err, infile, informat, NULL, e, "Certificate");
if (x == NULL)
goto end;
if (CA_flag) {
xca = load_cert(bio_err, CAfile, CAformat, NULL, e, "CA Certificate");
if (xca == NULL)
goto end;
}
if (!noout || text || next_serial) {
OBJ_create("2.99999.3", "SET.ex3", "SET x509v3 extension 3");
out = BIO_new(BIO_s_file());
if (out == NULL) {
ERR_print_errors(bio_err);
goto end;
}
if (outfile == NULL) {
BIO_set_fp(out, stdout, BIO_NOCLOSE);
#ifdef OPENSSL_SYS_VMS
{
BIO *tmpbio = BIO_new(BIO_f_linebuffer());
out = BIO_push(tmpbio, out);
}
#endif
} else {
if (BIO_write_filename(out, outfile) <= 0) {
perror(outfile);
goto end;
}
}
}
if (alias)
X509_alias_set1(x, (unsigned char *)alias, -1);
if (clrtrust)
X509_trust_clear(x);
if (clrreject)
X509_reject_clear(x);
if (trust) {
for (i = 0; i < sk_ASN1_OBJECT_num(trust); i++) {
objtmp = sk_ASN1_OBJECT_value(trust, i);
X509_add1_trust_object(x, objtmp);
}
}
if (reject) {
for (i = 0; i < sk_ASN1_OBJECT_num(reject); i++) {
objtmp = sk_ASN1_OBJECT_value(reject, i);
X509_add1_reject_object(x, objtmp);
}
}
if (num) {
for (i = 1; i <= num; i++) {
if (issuer == i) {
print_name(STDout, "issuer= ",
X509_get_issuer_name(x), nmflag);
} else if (subject == i) {
print_name(STDout, "subject= ",
X509_get_subject_name(x), nmflag);
} else if (serial == i) {
BIO_printf(STDout, "serial=");
i2a_ASN1_INTEGER(STDout, X509_get_serialNumber(x));
BIO_printf(STDout, "\n");
} else if (next_serial == i) {
BIGNUM *bnser;
ASN1_INTEGER *ser;
ser = X509_get_serialNumber(x);
bnser = ASN1_INTEGER_to_BN(ser, NULL);
if (!bnser)
goto end;
if (!BN_add_word(bnser, 1))
goto end;
ser = BN_to_ASN1_INTEGER(bnser, NULL);
if (!ser)
goto end;
BN_free(bnser);
i2a_ASN1_INTEGER(out, ser);
ASN1_INTEGER_free(ser);
BIO_puts(out, "\n");
} else if ((email == i) || (ocsp_uri == i)) {
int j;
STACK_OF(OPENSSL_STRING) *emlst;
if (email == i)
emlst = X509_get1_email(x);
else
emlst = X509_get1_ocsp(x);
for (j = 0; j < sk_OPENSSL_STRING_num(emlst); j++)
BIO_printf(STDout, "%s\n",
sk_OPENSSL_STRING_value(emlst, j));
X509_email_free(emlst);
} else if (aliasout == i) {
unsigned char *alstr;
alstr = X509_alias_get0(x, NULL);
if (alstr)
BIO_printf(STDout, "%s\n", alstr);
else
BIO_puts(STDout, "<No Alias>\n");
} else if (subject_hash == i) {
BIO_printf(STDout, "%08lx\n", X509_subject_name_hash(x));
}
#ifndef OPENSSL_NO_MD5
else if (subject_hash_old == i) {
BIO_printf(STDout, "%08lx\n", X509_subject_name_hash_old(x));
}
#endif
else if (issuer_hash == i) {
BIO_printf(STDout, "%08lx\n", X509_issuer_name_hash(x));
}
#ifndef OPENSSL_NO_MD5
else if (issuer_hash_old == i) {
BIO_printf(STDout, "%08lx\n", X509_issuer_name_hash_old(x));
}
#endif
else if (pprint == i) {
X509_PURPOSE *ptmp;
int j;
BIO_printf(STDout, "Certificate purposes:\n");
for (j = 0; j < X509_PURPOSE_get_count(); j++) {
ptmp = X509_PURPOSE_get0(j);
purpose_print(STDout, x, ptmp);
}
} else if (modulus == i) {
EVP_PKEY *pkey;
pkey = X509_get_pubkey(x);
if (pkey == NULL) {
BIO_printf(bio_err, "Modulus=unavailable\n");
ERR_print_errors(bio_err);
goto end;
}
BIO_printf(STDout, "Modulus=");
#ifndef OPENSSL_NO_RSA
if (pkey->type == EVP_PKEY_RSA)
BN_print(STDout, pkey->pkey.rsa->n);
else
#endif
#ifndef OPENSSL_NO_DSA
if (pkey->type == EVP_PKEY_DSA)
BN_print(STDout, pkey->pkey.dsa->pub_key);
else
#endif
BIO_printf(STDout, "Wrong Algorithm type");
BIO_printf(STDout, "\n");
EVP_PKEY_free(pkey);
} else if (pubkey == i) {
EVP_PKEY *pkey;
pkey = X509_get_pubkey(x);
if (pkey == NULL) {
BIO_printf(bio_err, "Error getting public key\n");
ERR_print_errors(bio_err);
goto end;
}
PEM_write_bio_PUBKEY(STDout, pkey);
EVP_PKEY_free(pkey);
} else if (C == i) {
unsigned char *d;
char *m;
int y, z;
- X509_NAME_oneline(X509_get_subject_name(x), buf, sizeof buf);
+ X509_NAME_oneline(X509_get_subject_name(x), buf, sizeof(buf));
BIO_printf(STDout, "/* subject:%s */\n", buf);
m = X509_NAME_oneline(X509_get_issuer_name(x), buf,
- sizeof buf);
+ sizeof(buf));
BIO_printf(STDout, "/* issuer :%s */\n", buf);
z = i2d_X509(x, NULL);
m = OPENSSL_malloc(z);
if (!m) {
BIO_printf(bio_err, "Out of memory\n");
ERR_print_errors(bio_err);
goto end;
}
d = (unsigned char *)m;
z = i2d_X509_NAME(X509_get_subject_name(x), &d);
BIO_printf(STDout, "unsigned char XXX_subject_name[%d]={\n",
z);
d = (unsigned char *)m;
for (y = 0; y < z; y++) {
BIO_printf(STDout, "0x%02X,", d[y]);
if ((y & 0x0f) == 0x0f)
BIO_printf(STDout, "\n");
}
if (y % 16 != 0)
BIO_printf(STDout, "\n");
BIO_printf(STDout, "};\n");
z = i2d_X509_PUBKEY(X509_get_X509_PUBKEY(x), &d);
BIO_printf(STDout, "unsigned char XXX_public_key[%d]={\n", z);
d = (unsigned char *)m;
for (y = 0; y < z; y++) {
BIO_printf(STDout, "0x%02X,", d[y]);
if ((y & 0x0f) == 0x0f)
BIO_printf(STDout, "\n");
}
if (y % 16 != 0)
BIO_printf(STDout, "\n");
BIO_printf(STDout, "};\n");
z = i2d_X509(x, &d);
BIO_printf(STDout, "unsigned char XXX_certificate[%d]={\n",
z);
d = (unsigned char *)m;
for (y = 0; y < z; y++) {
BIO_printf(STDout, "0x%02X,", d[y]);
if ((y & 0x0f) == 0x0f)
BIO_printf(STDout, "\n");
}
if (y % 16 != 0)
BIO_printf(STDout, "\n");
BIO_printf(STDout, "};\n");
OPENSSL_free(m);
} else if (text == i) {
X509_print_ex(STDout, x, nmflag, certflag);
} else if (startdate == i) {
BIO_puts(STDout, "notBefore=");
ASN1_TIME_print(STDout, X509_get_notBefore(x));
BIO_puts(STDout, "\n");
} else if (enddate == i) {
BIO_puts(STDout, "notAfter=");
ASN1_TIME_print(STDout, X509_get_notAfter(x));
BIO_puts(STDout, "\n");
} else if (fingerprint == i) {
int j;
unsigned int n;
unsigned char md[EVP_MAX_MD_SIZE];
const EVP_MD *fdig = digest;
if (!fdig)
fdig = EVP_sha1();
if (!X509_digest(x, fdig, md, &n)) {
BIO_printf(bio_err, "out of memory\n");
goto end;
}
BIO_printf(STDout, "%s Fingerprint=",
OBJ_nid2sn(EVP_MD_type(fdig)));
for (j = 0; j < (int)n; j++) {
BIO_printf(STDout, "%02X%c", md[j], (j + 1 == (int)n)
? '\n' : ':');
}
}
/* should be in the library */
else if ((sign_flag == i) && (x509req == 0)) {
BIO_printf(bio_err, "Getting Private key\n");
if (Upkey == NULL) {
Upkey = load_key(bio_err,
keyfile, keyformat, 0,
passin, e, "Private key");
if (Upkey == NULL)
goto end;
}
assert(need_rand);
if (!sign(x, Upkey, days, clrext, digest, extconf, extsect))
goto end;
} else if (CA_flag == i) {
BIO_printf(bio_err, "Getting CA Private Key\n");
if (CAkeyfile != NULL) {
CApkey = load_key(bio_err,
CAkeyfile, CAkeyformat,
0, passin, e, "CA Private Key");
if (CApkey == NULL)
goto end;
}
assert(need_rand);
if (!x509_certify(ctx, CAfile, digest, x, xca,
CApkey, sigopts,
CAserial, CA_createserial, days, clrext,
extconf, extsect, sno))
goto end;
} else if (x509req == i) {
EVP_PKEY *pk;
BIO_printf(bio_err, "Getting request Private Key\n");
if (keyfile == NULL) {
BIO_printf(bio_err, "no request key file specified\n");
goto end;
} else {
pk = load_key(bio_err,
keyfile, keyformat, 0,
passin, e, "request key");
if (pk == NULL)
goto end;
}
BIO_printf(bio_err, "Generating certificate request\n");
rq = X509_to_X509_REQ(x, pk, digest);
EVP_PKEY_free(pk);
if (rq == NULL) {
ERR_print_errors(bio_err);
goto end;
}
if (!noout) {
X509_REQ_print(out, rq);
PEM_write_bio_X509_REQ(out, rq);
}
noout = 1;
} else if (ocspid == i) {
X509_ocspid_print(out, x);
}
}
}
if (checkend) {
time_t tcheck = time(NULL) + checkoffset;
if (X509_cmp_time(X509_get_notAfter(x), &tcheck) < 0) {
BIO_printf(out, "Certificate will expire\n");
ret = 1;
} else {
BIO_printf(out, "Certificate will not expire\n");
ret = 0;
}
goto end;
}
print_cert_checks(STDout, x, checkhost, checkemail, checkip);
if (noout) {
ret = 0;
goto end;
}
if (badsig)
x->signature->data[x->signature->length - 1] ^= 0x1;
if (outformat == FORMAT_ASN1)
i = i2d_X509_bio(out, x);
else if (outformat == FORMAT_PEM) {
if (trustout)
i = PEM_write_bio_X509_AUX(out, x);
else
i = PEM_write_bio_X509(out, x);
} else if (outformat == FORMAT_NETSCAPE) {
NETSCAPE_X509 nx;
ASN1_OCTET_STRING hdr;
hdr.data = (unsigned char *)NETSCAPE_CERT_HDR;
hdr.length = strlen(NETSCAPE_CERT_HDR);
nx.header = &hdr;
nx.cert = x;
i = ASN1_item_i2d_bio(ASN1_ITEM_rptr(NETSCAPE_X509), out, &nx);
} else {
BIO_printf(bio_err, "bad output format specified for outfile\n");
goto end;
}
if (!i) {
BIO_printf(bio_err, "unable to write certificate\n");
ERR_print_errors(bio_err);
goto end;
}
ret = 0;
end:
if (need_rand)
app_RAND_write_file(NULL, bio_err);
OBJ_cleanup();
NCONF_free(extconf);
BIO_free_all(out);
BIO_free_all(STDout);
X509_STORE_free(ctx);
X509_REQ_free(req);
X509_free(x);
X509_free(xca);
EVP_PKEY_free(Upkey);
EVP_PKEY_free(CApkey);
EVP_PKEY_free(fkey);
if (sigopts)
sk_OPENSSL_STRING_free(sigopts);
X509_REQ_free(rq);
ASN1_INTEGER_free(sno);
sk_ASN1_OBJECT_pop_free(trust, ASN1_OBJECT_free);
sk_ASN1_OBJECT_pop_free(reject, ASN1_OBJECT_free);
release_engine(e);
if (passin)
OPENSSL_free(passin);
apps_shutdown();
OPENSSL_EXIT(ret);
}
static ASN1_INTEGER *x509_load_serial(char *CAfile, char *serialfile,
int create)
{
char *buf = NULL, *p;
ASN1_INTEGER *bs = NULL;
BIGNUM *serial = NULL;
size_t len;
len = ((serialfile == NULL)
? (strlen(CAfile) + strlen(POSTFIX) + 1)
: (strlen(serialfile))) + 1;
buf = OPENSSL_malloc(len);
if (buf == NULL) {
BIO_printf(bio_err, "out of mem\n");
goto end;
}
if (serialfile == NULL) {
BUF_strlcpy(buf, CAfile, len);
for (p = buf; *p; p++)
if (*p == '.') {
*p = '\0';
break;
}
BUF_strlcat(buf, POSTFIX, len);
} else
BUF_strlcpy(buf, serialfile, len);
serial = load_serial(buf, create, NULL);
if (serial == NULL)
goto end;
if (!BN_add_word(serial, 1)) {
BIO_printf(bio_err, "add_word failure\n");
goto end;
}
if (!save_serial(buf, NULL, serial, &bs))
goto end;
end:
if (buf)
OPENSSL_free(buf);
BN_free(serial);
return bs;
}
static int x509_certify(X509_STORE *ctx, char *CAfile, const EVP_MD *digest,
X509 *x, X509 *xca, EVP_PKEY *pkey,
STACK_OF(OPENSSL_STRING) *sigopts,
char *serialfile, int create,
int days, int clrext, CONF *conf, char *section,
ASN1_INTEGER *sno)
{
int ret = 0;
ASN1_INTEGER *bs = NULL;
X509_STORE_CTX xsc;
EVP_PKEY *upkey;
upkey = X509_get_pubkey(xca);
if (upkey == NULL) {
BIO_printf(bio_err, "Error obtaining CA X509 public key\n");
goto end;
}
EVP_PKEY_copy_parameters(upkey, pkey);
EVP_PKEY_free(upkey);
if (!X509_STORE_CTX_init(&xsc, ctx, x, NULL)) {
BIO_printf(bio_err, "Error initialising X509 store\n");
goto end;
}
if (sno)
bs = sno;
else if (!(bs = x509_load_serial(CAfile, serialfile, create)))
goto end;
/* if (!X509_STORE_add_cert(ctx,x)) goto end;*/
/*
* NOTE: this certificate can/should be self signed, unless it was a
* certificate request in which case it is not.
*/
X509_STORE_CTX_set_cert(&xsc, x);
X509_STORE_CTX_set_flags(&xsc, X509_V_FLAG_CHECK_SS_SIGNATURE);
if (!reqfile && X509_verify_cert(&xsc) <= 0)
goto end;
if (!X509_check_private_key(xca, pkey)) {
BIO_printf(bio_err,
"CA certificate and CA private key do not match\n");
goto end;
}
if (!X509_set_issuer_name(x, X509_get_subject_name(xca)))
goto end;
if (!X509_set_serialNumber(x, bs))
goto end;
if (X509_gmtime_adj(X509_get_notBefore(x), 0L) == NULL)
goto end;
/* hardwired expired */
if (X509_time_adj_ex(X509_get_notAfter(x), days, 0, NULL) == NULL)
goto end;
if (clrext) {
while (X509_get_ext_count(x) > 0)
X509_delete_ext(x, 0);
}
if (conf) {
X509V3_CTX ctx2;
#ifdef OPENSSL_SSL_DEBUG_BROKEN_PROTOCOL
X509_set_version(x, force_version);
#else
X509_set_version(x, 2); /* version 3 certificate */
#endif
X509V3_set_ctx(&ctx2, xca, x, NULL, NULL, 0);
X509V3_set_nconf(&ctx2, conf);
if (!X509V3_EXT_add_nconf(conf, &ctx2, section, x))
goto end;
}
if (!do_X509_sign(bio_err, x, pkey, digest, sigopts))
goto end;
ret = 1;
end:
X509_STORE_CTX_cleanup(&xsc);
if (!ret)
ERR_print_errors(bio_err);
if (!sno)
ASN1_INTEGER_free(bs);
return ret;
}
static int MS_CALLBACK callb(int ok, X509_STORE_CTX *ctx)
{
int err;
X509 *err_cert;
/*
* it is ok to use a self signed certificate This case will catch both
* the initial ok == 0 and the final ok == 1 calls to this function
*/
err = X509_STORE_CTX_get_error(ctx);
if (err == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT)
return 1;
/*
* BAD we should have gotten an error. Normally if everything worked
* X509_STORE_CTX_get_error(ctx) will still be set to
* DEPTH_ZERO_SELF_....
*/
if (ok) {
BIO_printf(bio_err,
"error with certificate to be certified - should be self signed\n");
return 0;
} else {
err_cert = X509_STORE_CTX_get_current_cert(ctx);
print_name(bio_err, NULL, X509_get_subject_name(err_cert), 0);
BIO_printf(bio_err,
"error with certificate - error %d at depth %d\n%s\n", err,
X509_STORE_CTX_get_error_depth(ctx),
X509_verify_cert_error_string(err));
return 1;
}
}
/* self sign */
static int sign(X509 *x, EVP_PKEY *pkey, int days, int clrext,
const EVP_MD *digest, CONF *conf, char *section)
{
EVP_PKEY *pktmp;
pktmp = X509_get_pubkey(x);
if (pktmp == NULL)
goto err;
EVP_PKEY_copy_parameters(pktmp, pkey);
EVP_PKEY_save_parameters(pktmp, 1);
EVP_PKEY_free(pktmp);
if (!X509_set_issuer_name(x, X509_get_subject_name(x)))
goto err;
if (X509_gmtime_adj(X509_get_notBefore(x), 0) == NULL)
goto err;
if (X509_time_adj_ex(X509_get_notAfter(x), days, 0, NULL) == NULL)
goto err;
if (!X509_set_pubkey(x, pkey))
goto err;
if (clrext) {
while (X509_get_ext_count(x) > 0)
X509_delete_ext(x, 0);
}
if (conf) {
X509V3_CTX ctx;
#ifdef OPENSSL_SSL_DEBUG_BROKEN_PROTOCOL
X509_set_version(x, force_version);
#else
X509_set_version(x, 2); /* version 3 certificate */
#endif
X509V3_set_ctx(&ctx, x, x, NULL, NULL, 0);
X509V3_set_nconf(&ctx, conf);
if (!X509V3_EXT_add_nconf(conf, &ctx, section, x))
goto err;
}
if (!X509_sign(x, pkey, digest))
goto err;
return 1;
err:
ERR_print_errors(bio_err);
return 0;
}
static int purpose_print(BIO *bio, X509 *cert, X509_PURPOSE *pt)
{
int id, i, idret;
char *pname;
id = X509_PURPOSE_get_id(pt);
pname = X509_PURPOSE_get0_name(pt);
for (i = 0; i < 2; i++) {
idret = X509_check_purpose(cert, id, i);
BIO_printf(bio, "%s%s : ", pname, i ? " CA" : "");
if (idret == 1)
BIO_printf(bio, "Yes\n");
else if (idret == 0)
BIO_printf(bio, "No\n");
else
BIO_printf(bio, "Yes (WARNING code=%d)\n", idret);
}
return 1;
}
diff --git a/crypto/asn1/a_gentm.c b/crypto/asn1/a_gentm.c
index 85118137859f..cb4481597064 100644
--- a/crypto/asn1/a_gentm.c
+++ b/crypto/asn1/a_gentm.c
@@ -1,312 +1,312 @@
/* crypto/asn1/a_gentm.c */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
/*
* GENERALIZEDTIME implementation, written by Steve Henson. Based on UTCTIME
*/
#include <stdio.h>
#include <time.h>
#include "cryptlib.h"
#include "o_time.h"
#include <openssl/asn1.h>
#include "asn1_locl.h"
#if 0
int i2d_ASN1_GENERALIZEDTIME(ASN1_GENERALIZEDTIME *a, unsigned char **pp)
{
# ifdef CHARSET_EBCDIC
/* KLUDGE! We convert to ascii before writing DER */
int len;
char tmp[24];
ASN1_STRING tmpstr = *(ASN1_STRING *)a;
len = tmpstr.length;
- ebcdic2ascii(tmp, tmpstr.data, (len >= sizeof tmp) ? sizeof tmp : len);
+ ebcdic2ascii(tmp, tmpstr.data, (len >= sizeof(tmp)) ? sizeof(tmp) : len);
tmpstr.data = tmp;
a = (ASN1_GENERALIZEDTIME *)&tmpstr;
# endif
return (i2d_ASN1_bytes((ASN1_STRING *)a, pp,
V_ASN1_GENERALIZEDTIME, V_ASN1_UNIVERSAL));
}
ASN1_GENERALIZEDTIME *d2i_ASN1_GENERALIZEDTIME(ASN1_GENERALIZEDTIME **a,
unsigned char **pp,
long length)
{
ASN1_GENERALIZEDTIME *ret = NULL;
ret =
(ASN1_GENERALIZEDTIME *)d2i_ASN1_bytes((ASN1_STRING **)a, pp, length,
V_ASN1_GENERALIZEDTIME,
V_ASN1_UNIVERSAL);
if (ret == NULL) {
ASN1err(ASN1_F_D2I_ASN1_GENERALIZEDTIME, ERR_R_NESTED_ASN1_ERROR);
return (NULL);
}
# ifdef CHARSET_EBCDIC
ascii2ebcdic(ret->data, ret->data, ret->length);
# endif
if (!ASN1_GENERALIZEDTIME_check(ret)) {
ASN1err(ASN1_F_D2I_ASN1_GENERALIZEDTIME, ASN1_R_INVALID_TIME_FORMAT);
goto err;
}
return (ret);
err:
if ((ret != NULL) && ((a == NULL) || (*a != ret)))
M_ASN1_GENERALIZEDTIME_free(ret);
return (NULL);
}
#endif
int asn1_generalizedtime_to_tm(struct tm *tm, const ASN1_GENERALIZEDTIME *d)
{
static const int min[9] = { 0, 0, 1, 1, 0, 0, 0, 0, 0 };
static const int max[9] = { 99, 99, 12, 31, 23, 59, 59, 12, 59 };
char *a;
int n, i, l, o;
if (d->type != V_ASN1_GENERALIZEDTIME)
return (0);
l = d->length;
a = (char *)d->data;
o = 0;
/*
* GENERALIZEDTIME is similar to UTCTIME except the year is represented
* as YYYY. This stuff treats everything as a two digit field so make
* first two fields 00 to 99
*/
if (l < 13)
goto err;
for (i = 0; i < 7; i++) {
if ((i == 6) && ((a[o] == 'Z') || (a[o] == '+') || (a[o] == '-'))) {
i++;
if (tm)
tm->tm_sec = 0;
break;
}
if ((a[o] < '0') || (a[o] > '9'))
goto err;
n = a[o] - '0';
if (++o > l)
goto err;
if ((a[o] < '0') || (a[o] > '9'))
goto err;
n = (n * 10) + a[o] - '0';
if (++o > l)
goto err;
if ((n < min[i]) || (n > max[i]))
goto err;
if (tm) {
switch (i) {
case 0:
tm->tm_year = n * 100 - 1900;
break;
case 1:
tm->tm_year += n;
break;
case 2:
tm->tm_mon = n - 1;
break;
case 3:
tm->tm_mday = n;
break;
case 4:
tm->tm_hour = n;
break;
case 5:
tm->tm_min = n;
break;
case 6:
tm->tm_sec = n;
break;
}
}
}
/*
* Optional fractional seconds: decimal point followed by one or more
* digits.
*/
if (a[o] == '.') {
if (++o > l)
goto err;
i = o;
while ((a[o] >= '0') && (a[o] <= '9') && (o <= l))
o++;
/* Must have at least one digit after decimal point */
if (i == o)
goto err;
}
if (a[o] == 'Z')
o++;
else if ((a[o] == '+') || (a[o] == '-')) {
int offsign = a[o] == '-' ? 1 : -1, offset = 0;
o++;
if (o + 4 > l)
goto err;
for (i = 7; i < 9; i++) {
if ((a[o] < '0') || (a[o] > '9'))
goto err;
n = a[o] - '0';
o++;
if ((a[o] < '0') || (a[o] > '9'))
goto err;
n = (n * 10) + a[o] - '0';
if ((n < min[i]) || (n > max[i]))
goto err;
if (tm) {
if (i == 7)
offset = n * 3600;
else if (i == 8)
offset += n * 60;
}
o++;
}
if (offset && !OPENSSL_gmtime_adj(tm, 0, offset * offsign))
return 0;
} else if (a[o]) {
/* Missing time zone information. */
goto err;
}
return (o == l);
err:
return (0);
}
int ASN1_GENERALIZEDTIME_check(const ASN1_GENERALIZEDTIME *d)
{
return asn1_generalizedtime_to_tm(NULL, d);
}
int ASN1_GENERALIZEDTIME_set_string(ASN1_GENERALIZEDTIME *s, const char *str)
{
ASN1_GENERALIZEDTIME t;
t.type = V_ASN1_GENERALIZEDTIME;
t.length = strlen(str);
t.data = (unsigned char *)str;
if (ASN1_GENERALIZEDTIME_check(&t)) {
if (s != NULL) {
if (!ASN1_STRING_set((ASN1_STRING *)s,
(unsigned char *)str, t.length))
return 0;
s->type = V_ASN1_GENERALIZEDTIME;
}
return (1);
} else
return (0);
}
ASN1_GENERALIZEDTIME *ASN1_GENERALIZEDTIME_set(ASN1_GENERALIZEDTIME *s,
time_t t)
{
return ASN1_GENERALIZEDTIME_adj(s, t, 0, 0);
}
ASN1_GENERALIZEDTIME *ASN1_GENERALIZEDTIME_adj(ASN1_GENERALIZEDTIME *s,
time_t t, int offset_day,
long offset_sec)
{
char *p;
struct tm *ts;
struct tm data;
size_t len = 20;
if (s == NULL)
s = M_ASN1_GENERALIZEDTIME_new();
if (s == NULL)
return (NULL);
ts = OPENSSL_gmtime(&t, &data);
if (ts == NULL)
return (NULL);
if (offset_day || offset_sec) {
if (!OPENSSL_gmtime_adj(ts, offset_day, offset_sec))
return NULL;
}
p = (char *)s->data;
if ((p == NULL) || ((size_t)s->length < len)) {
p = OPENSSL_malloc(len);
if (p == NULL) {
ASN1err(ASN1_F_ASN1_GENERALIZEDTIME_ADJ, ERR_R_MALLOC_FAILURE);
return (NULL);
}
if (s->data != NULL)
OPENSSL_free(s->data);
s->data = (unsigned char *)p;
}
BIO_snprintf(p, len, "%04d%02d%02d%02d%02d%02dZ", ts->tm_year + 1900,
ts->tm_mon + 1, ts->tm_mday, ts->tm_hour, ts->tm_min,
ts->tm_sec);
s->length = strlen(p);
s->type = V_ASN1_GENERALIZEDTIME;
#ifdef CHARSET_EBCDIC_not
ebcdic2ascii(s->data, s->data, s->length);
#endif
return (s);
}
diff --git a/crypto/asn1/a_mbstr.c b/crypto/asn1/a_mbstr.c
index 6935efe09fb5..5b8028aaa3a5 100644
--- a/crypto/asn1/a_mbstr.c
+++ b/crypto/asn1/a_mbstr.c
@@ -1,423 +1,423 @@
/* a_mbstr.c */
/*
* Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL project
* 1999.
*/
/* ====================================================================
* Copyright (c) 1999 The OpenSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* licensing@OpenSSL.org.
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*
* This product includes cryptographic software written by Eric Young
* (eay@cryptsoft.com). This product includes software written by Tim
* Hudson (tjh@cryptsoft.com).
*
*/
#include <stdio.h>
#include <ctype.h>
#include "cryptlib.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);
static int is_printable(unsigned long value);
/*
* 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 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;
char strbuf[32];
int (*cpyfunc) (unsigned long, void *) = NULL;
if (len == -1)
len = strlen((const char *)in);
if (!mask)
mask = DIRSTRING_TYPE;
/* First do a string check and work out the number of characters */
switch (inform) {
case MBSTRING_BMP:
if (len & 1) {
ASN1err(ASN1_F_ASN1_MBSTRING_NCOPY,
ASN1_R_INVALID_BMPSTRING_LENGTH);
return -1;
}
nchar = len >> 1;
break;
case MBSTRING_UNIV:
if (len & 3) {
ASN1err(ASN1_F_ASN1_MBSTRING_NCOPY,
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) {
ASN1err(ASN1_F_ASN1_MBSTRING_NCOPY, ASN1_R_INVALID_UTF8STRING);
return -1;
}
break;
case MBSTRING_ASC:
nchar = len;
break;
default:
ASN1err(ASN1_F_ASN1_MBSTRING_NCOPY, ASN1_R_UNKNOWN_FORMAT);
return -1;
}
if ((minsize > 0) && (nchar < minsize)) {
ASN1err(ASN1_F_ASN1_MBSTRING_NCOPY, ASN1_R_STRING_TOO_SHORT);
- BIO_snprintf(strbuf, sizeof strbuf, "%ld", minsize);
+ BIO_snprintf(strbuf, sizeof(strbuf), "%ld", minsize);
ERR_add_error_data(2, "minsize=", strbuf);
return -1;
}
if ((maxsize > 0) && (nchar > maxsize)) {
ASN1err(ASN1_F_ASN1_MBSTRING_NCOPY, ASN1_R_STRING_TOO_LONG);
- BIO_snprintf(strbuf, sizeof strbuf, "%ld", maxsize);
+ BIO_snprintf(strbuf, sizeof(strbuf), "%ld", maxsize);
ERR_add_error_data(2, "maxsize=", strbuf);
return -1;
}
/* Now work out minimal type (if any) */
if (traverse_string(in, len, inform, type_str, &mask) < 0) {
ASN1err(ASN1_F_ASN1_MBSTRING_NCOPY, ASN1_R_ILLEGAL_CHARACTERS);
return -1;
}
/* Now work out output format and string type */
outform = MBSTRING_ASC;
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;
if (dest->data) {
dest->length = 0;
OPENSSL_free(dest->data);
dest->data = NULL;
}
dest->type = str_type;
} else {
free_out = 1;
dest = ASN1_STRING_type_new(str_type);
if (!dest) {
ASN1err(ASN1_F_ASN1_MBSTRING_NCOPY, 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)) {
ASN1err(ASN1_F_ASN1_MBSTRING_NCOPY, 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))) {
if (free_out)
ASN1_STRING_free(dest);
ASN1err(ASN1_F_ASN1_MBSTRING_NCOPY, 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;
nchar = arg;
(*nchar)++;
return 1;
}
/* Determine size of output as a UTF8 String */
static int out_utf8(unsigned long value, void *arg)
{
int *outlen;
outlen = arg;
*outlen += UTF8_putc(NULL, -1, value);
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;
types = *((unsigned long *)arg);
if ((types & B_ASN1_PRINTABLESTRING) && !is_printable(value))
types &= ~B_ASN1_PRINTABLESTRING;
if ((types & B_ASN1_IA5STRING) && (value > 127))
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)
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;
}
/* Return 1 if the character is permitted in a PrintableString */
static int is_printable(unsigned long value)
{
int ch;
if (value > 0x7f)
return 0;
ch = (int)value;
/*
* Note: we can't use 'isalnum' because certain accented characters may
* count as alphanumeric in some environments.
*/
#ifndef CHARSET_EBCDIC
if ((ch >= 'a') && (ch <= 'z'))
return 1;
if ((ch >= 'A') && (ch <= 'Z'))
return 1;
if ((ch >= '0') && (ch <= '9'))
return 1;
if ((ch == ' ') || strchr("'()+,-./:=?", ch))
return 1;
#else /* CHARSET_EBCDIC */
if ((ch >= os_toascii['a']) && (ch <= os_toascii['z']))
return 1;
if ((ch >= os_toascii['A']) && (ch <= os_toascii['Z']))
return 1;
if ((ch >= os_toascii['0']) && (ch <= os_toascii['9']))
return 1;
if ((ch == os_toascii[' ']) || strchr("'()+,-./:=?", os_toebcdic[ch]))
return 1;
#endif /* CHARSET_EBCDIC */
return 0;
}
diff --git a/crypto/asn1/a_object.c b/crypto/asn1/a_object.c
index 229a40ffa344..ad6b12a53667 100644
--- a/crypto/asn1/a_object.c
+++ b/crypto/asn1/a_object.c
@@ -1,406 +1,406 @@
/* crypto/asn1/a_object.c */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
#include <stdio.h>
#include <limits.h>
#include "cryptlib.h"
#include <openssl/buffer.h>
#include <openssl/asn1.h>
#include <openssl/objects.h>
#include <openssl/bn.h>
int i2d_ASN1_OBJECT(ASN1_OBJECT *a, unsigned char **pp)
{
unsigned char *p;
int objsize;
if ((a == NULL) || (a->data == NULL))
return (0);
objsize = ASN1_object_size(0, a->length, V_ASN1_OBJECT);
if (pp == NULL || objsize == -1)
return objsize;
p = *pp;
ASN1_put_object(&p, 0, a->length, V_ASN1_OBJECT, V_ASN1_UNIVERSAL);
memcpy(p, a->data, a->length);
p += a->length;
*pp = p;
return (objsize);
}
int a2d_ASN1_OBJECT(unsigned char *out, int olen, const char *buf, int num)
{
int i, first, len = 0, c, use_bn;
char ftmp[24], *tmp = ftmp;
- int tmpsize = sizeof ftmp;
+ int tmpsize = sizeof(ftmp);
const char *p;
unsigned long l;
BIGNUM *bl = NULL;
if (num == 0)
return (0);
else if (num == -1)
num = strlen(buf);
p = buf;
c = *(p++);
num--;
if ((c >= '0') && (c <= '2')) {
first = c - '0';
} else {
ASN1err(ASN1_F_A2D_ASN1_OBJECT, ASN1_R_FIRST_NUM_TOO_LARGE);
goto err;
}
if (num <= 0) {
ASN1err(ASN1_F_A2D_ASN1_OBJECT, ASN1_R_MISSING_SECOND_NUMBER);
goto err;
}
c = *(p++);
num--;
for (;;) {
if (num <= 0)
break;
if ((c != '.') && (c != ' ')) {
ASN1err(ASN1_F_A2D_ASN1_OBJECT, ASN1_R_INVALID_SEPARATOR);
goto err;
}
l = 0;
use_bn = 0;
for (;;) {
if (num <= 0)
break;
num--;
c = *(p++);
if ((c == ' ') || (c == '.'))
break;
if ((c < '0') || (c > '9')) {
ASN1err(ASN1_F_A2D_ASN1_OBJECT, ASN1_R_INVALID_DIGIT);
goto err;
}
if (!use_bn && l >= ((ULONG_MAX - 80) / 10L)) {
use_bn = 1;
if (!bl)
bl = BN_new();
if (!bl || !BN_set_word(bl, l))
goto err;
}
if (use_bn) {
if (!BN_mul_word(bl, 10L)
|| !BN_add_word(bl, c - '0'))
goto err;
} else
l = l * 10L + (long)(c - '0');
}
if (len == 0) {
if ((first < 2) && (l >= 40)) {
ASN1err(ASN1_F_A2D_ASN1_OBJECT,
ASN1_R_SECOND_NUMBER_TOO_LARGE);
goto err;
}
if (use_bn) {
if (!BN_add_word(bl, first * 40))
goto err;
} else
l += (long)first *40;
}
i = 0;
if (use_bn) {
int blsize;
blsize = BN_num_bits(bl);
blsize = (blsize + 6) / 7;
if (blsize > tmpsize) {
if (tmp != ftmp)
OPENSSL_free(tmp);
tmpsize = blsize + 32;
tmp = OPENSSL_malloc(tmpsize);
if (!tmp)
goto err;
}
while (blsize--) {
BN_ULONG t = BN_div_word(bl, 0x80L);
if (t == (BN_ULONG)-1)
goto err;
tmp[i++] = (unsigned char)t;
}
} else {
for (;;) {
tmp[i++] = (unsigned char)l & 0x7f;
l >>= 7L;
if (l == 0L)
break;
}
}
if (out != NULL) {
if (len + i > olen) {
ASN1err(ASN1_F_A2D_ASN1_OBJECT, ASN1_R_BUFFER_TOO_SMALL);
goto err;
}
while (--i > 0)
out[len++] = tmp[i] | 0x80;
out[len++] = tmp[0];
} else
len += i;
}
if (tmp != ftmp)
OPENSSL_free(tmp);
if (bl)
BN_free(bl);
return (len);
err:
if (tmp != ftmp)
OPENSSL_free(tmp);
if (bl)
BN_free(bl);
return (0);
}
int i2t_ASN1_OBJECT(char *buf, int buf_len, ASN1_OBJECT *a)
{
return OBJ_obj2txt(buf, buf_len, a, 0);
}
int i2a_ASN1_OBJECT(BIO *bp, ASN1_OBJECT *a)
{
char buf[80], *p = buf;
int i;
if ((a == NULL) || (a->data == NULL))
return (BIO_write(bp, "NULL", 4));
- i = i2t_ASN1_OBJECT(buf, sizeof buf, a);
+ i = i2t_ASN1_OBJECT(buf, sizeof(buf), a);
if (i > (int)(sizeof(buf) - 1)) {
p = OPENSSL_malloc(i + 1);
if (!p)
return -1;
i2t_ASN1_OBJECT(p, i + 1, a);
}
if (i <= 0)
return BIO_write(bp, "<INVALID>", 9);
BIO_write(bp, p, i);
if (p != buf)
OPENSSL_free(p);
return (i);
}
ASN1_OBJECT *d2i_ASN1_OBJECT(ASN1_OBJECT **a, const unsigned char **pp,
long length)
{
const unsigned char *p;
long len;
int tag, xclass;
int inf, i;
ASN1_OBJECT *ret = NULL;
p = *pp;
inf = ASN1_get_object(&p, &len, &tag, &xclass, length);
if (inf & 0x80) {
i = ASN1_R_BAD_OBJECT_HEADER;
goto err;
}
if (tag != V_ASN1_OBJECT) {
i = ASN1_R_EXPECTING_AN_OBJECT;
goto err;
}
ret = c2i_ASN1_OBJECT(a, &p, len);
if (ret)
*pp = p;
return ret;
err:
ASN1err(ASN1_F_D2I_ASN1_OBJECT, i);
return (NULL);
}
ASN1_OBJECT *c2i_ASN1_OBJECT(ASN1_OBJECT **a, const unsigned char **pp,
long len)
{
ASN1_OBJECT *ret = NULL;
const unsigned char *p;
unsigned char *data;
int i, length;
/*
* Sanity check OID encoding. Need at least one content octet. MSB must
* be clear in the last octet. can't have leading 0x80 in subidentifiers,
* see: X.690 8.19.2
*/
if (len <= 0 || len > INT_MAX || pp == NULL || (p = *pp) == NULL ||
p[len - 1] & 0x80) {
ASN1err(ASN1_F_C2I_ASN1_OBJECT, ASN1_R_INVALID_OBJECT_ENCODING);
return NULL;
}
/* Now 0 < len <= INT_MAX, so the cast is safe. */
length = (int)len;
for (i = 0; i < length; i++, p++) {
if (*p == 0x80 && (!i || !(p[-1] & 0x80))) {
ASN1err(ASN1_F_C2I_ASN1_OBJECT, ASN1_R_INVALID_OBJECT_ENCODING);
return NULL;
}
}
/*
* only the ASN1_OBJECTs from the 'table' will have values for ->sn or
* ->ln
*/
if ((a == NULL) || ((*a) == NULL) ||
!((*a)->flags & ASN1_OBJECT_FLAG_DYNAMIC)) {
if ((ret = ASN1_OBJECT_new()) == NULL)
return (NULL);
} else
ret = (*a);
p = *pp;
/* detach data from object */
data = (unsigned char *)ret->data;
ret->data = NULL;
/* once detached we can change it */
if ((data == NULL) || (ret->length < length)) {
ret->length = 0;
if (data != NULL)
OPENSSL_free(data);
data = (unsigned char *)OPENSSL_malloc(length);
if (data == NULL) {
i = ERR_R_MALLOC_FAILURE;
goto err;
}
ret->flags |= ASN1_OBJECT_FLAG_DYNAMIC_DATA;
}
memcpy(data, p, length);
/* reattach data to object, after which it remains const */
ret->data = data;
ret->length = length;
ret->sn = NULL;
ret->ln = NULL;
/* ret->flags=ASN1_OBJECT_FLAG_DYNAMIC; we know it is dynamic */
p += length;
if (a != NULL)
(*a) = ret;
*pp = p;
return (ret);
err:
ASN1err(ASN1_F_C2I_ASN1_OBJECT, i);
if ((ret != NULL) && ((a == NULL) || (*a != ret)))
ASN1_OBJECT_free(ret);
return (NULL);
}
ASN1_OBJECT *ASN1_OBJECT_new(void)
{
ASN1_OBJECT *ret;
ret = (ASN1_OBJECT *)OPENSSL_malloc(sizeof(ASN1_OBJECT));
if (ret == NULL) {
ASN1err(ASN1_F_ASN1_OBJECT_NEW, ERR_R_MALLOC_FAILURE);
return (NULL);
}
ret->length = 0;
ret->data = NULL;
ret->nid = 0;
ret->sn = NULL;
ret->ln = NULL;
ret->flags = ASN1_OBJECT_FLAG_DYNAMIC;
return (ret);
}
void ASN1_OBJECT_free(ASN1_OBJECT *a)
{
if (a == NULL)
return;
if (a->flags & ASN1_OBJECT_FLAG_DYNAMIC_STRINGS) {
#ifndef CONST_STRICT /* disable purely for compile-time strict
* const checking. Doing this on a "real"
* compile will cause memory leaks */
if (a->sn != NULL)
OPENSSL_free((void *)a->sn);
if (a->ln != NULL)
OPENSSL_free((void *)a->ln);
#endif
a->sn = a->ln = NULL;
}
if (a->flags & ASN1_OBJECT_FLAG_DYNAMIC_DATA) {
if (a->data != NULL)
OPENSSL_free((void *)a->data);
a->data = NULL;
a->length = 0;
}
if (a->flags & ASN1_OBJECT_FLAG_DYNAMIC)
OPENSSL_free(a);
}
ASN1_OBJECT *ASN1_OBJECT_create(int nid, unsigned char *data, int len,
const char *sn, const char *ln)
{
ASN1_OBJECT o;
o.sn = sn;
o.ln = ln;
o.data = data;
o.nid = nid;
o.length = len;
o.flags = ASN1_OBJECT_FLAG_DYNAMIC | ASN1_OBJECT_FLAG_DYNAMIC_STRINGS |
ASN1_OBJECT_FLAG_DYNAMIC_DATA;
return (OBJ_dup(&o));
}
IMPLEMENT_STACK_OF(ASN1_OBJECT)
IMPLEMENT_ASN1_SET_OF(ASN1_OBJECT)
diff --git a/crypto/asn1/a_strex.c b/crypto/asn1/a_strex.c
index 2d562f93452f..95f041620735 100644
--- a/crypto/asn1/a_strex.c
+++ b/crypto/asn1/a_strex.c
@@ -1,649 +1,649 @@
/* a_strex.c */
/*
* Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL project
* 2000.
*/
/* ====================================================================
* Copyright (c) 2000 The OpenSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* licensing@OpenSSL.org.
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*
* This product includes cryptographic software written by Eric Young
* (eay@cryptsoft.com). This product includes software written by Tim
* Hudson (tjh@cryptsoft.com).
*
*/
#include <stdio.h>
#include <string.h>
#include "cryptlib.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_QUOTE | \
ASN1_STRFLGS_ESC_CTRL | \
ASN1_STRFLGS_ESC_MSB)
/*
* Three IO functions for sending data to memory, a BIO and and a FILE
* pointer.
*/
#if 0 /* never used */
static int send_mem_chars(void *arg, const void *buf, int len)
{
unsigned char **out = arg;
if (!out)
return 1;
memcpy(*out, buf, len);
*out += len;
return 1;
}
#endif
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;
}
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;
}
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 char flags, char *do_quotes,
char_io *io_ch, void *arg)
{
unsigned char chflgs, chtmp;
char tmphex[HEX_SIZE(long) + 3];
if (c > 0xffffffffL)
return -1;
if (c > 0xffff) {
- BIO_snprintf(tmphex, sizeof tmphex, "\\W%08lX", c);
+ 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);
+ 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)) {
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 char flags, char *quotes, char_io *io_ch,
void *arg)
{
int i, outlen, len;
unsigned char orflags, *p, *q;
unsigned long c;
p = buf;
q = buf + buflen;
outlen = 0;
while (p != q) {
if (p == buf && flags & ASN1_STRFLGS_ESC_2253)
orflags = CHARTYPE_FIRST_ESC_2253;
else
orflags = 0;
switch (type & BUF_TYPE_WIDTH_MASK) {
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 */
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);
+ 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], (unsigned char)(flags | orflags),
quotes, io_ch, arg);
if (len < 0)
return -1;
outlen += len;
}
} else {
len =
do_esc_char(c, (unsigned char)(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,
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);
der_buf = OPENSSL_malloc(der_len);
if (!der_buf)
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, 0, -1, /* 10-13 */
-1, -1, -1, -1, /* 15-17 */
1, 1, 1, /* 18-20 */
-1, 1, 1, 1, /* 21-24 */
-1, 1, -1, /* 25-27 */
4, -1, 2 /* 28-30 */
};
/*
* 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,
ASN1_STRING *str)
{
int outlen, len;
int type;
char quotes;
unsigned char flags;
quotes = 0;
/* Keep a copy of escape flags */
flags = (unsigned char)(lflags & ESC_FLAGS);
type = str->type;
outlen = 0;
if (lflags & ASN1_STRFLGS_SHOW_TYPE) {
const char *tagname;
tagname = ASN1_tag2str(type);
outlen += 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)
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)
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, X509_NAME *n,
int indent, unsigned long flags)
{
int i, prev = -1, orflags, cnt;
int fn_opt, fn_nid;
ASN1_OBJECT *fn;
ASN1_STRING *val;
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 == ent->set) {
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 = ent->set;
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);
+ 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, 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_FP_API
int X509_NAME_print_ex_fp(FILE *fp, 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, ASN1_STRING *str, unsigned long flags)
{
return do_print_ex(send_bio_chars, out, flags, str);
}
#ifndef OPENSSL_NO_FP_API
int ASN1_STRING_print_ex_fp(FILE *fp, 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, 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/asn1/a_time.c b/crypto/asn1/a_time.c
index 0eeb79cd428c..28831d6b843c 100644
--- a/crypto/asn1/a_time.c
+++ b/crypto/asn1/a_time.c
@@ -1,236 +1,236 @@
/* crypto/asn1/a_time.c */
/* ====================================================================
* Copyright (c) 1999 The OpenSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* licensing@OpenSSL.org.
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*
* This product includes cryptographic software written by Eric Young
* (eay@cryptsoft.com). This product includes software written by Tim
* Hudson (tjh@cryptsoft.com).
*
*/
/*-
* This is an implementation of the ASN1 Time structure which is:
* Time ::= CHOICE {
* utcTime UTCTime,
* generalTime GeneralizedTime }
* written by Steve Henson.
*/
#include <stdio.h>
#include <time.h>
#include "cryptlib.h"
#include "o_time.h"
#include <openssl/asn1t.h>
#include "asn1_locl.h"
IMPLEMENT_ASN1_MSTRING(ASN1_TIME, B_ASN1_TIME)
IMPLEMENT_ASN1_FUNCTIONS(ASN1_TIME)
#if 0
int i2d_ASN1_TIME(ASN1_TIME *a, unsigned char **pp)
{
# ifdef CHARSET_EBCDIC
/* KLUDGE! We convert to ascii before writing DER */
char tmp[24];
ASN1_STRING tmpstr;
if (a->type == V_ASN1_UTCTIME || a->type == V_ASN1_GENERALIZEDTIME) {
int len;
tmpstr = *(ASN1_STRING *)a;
len = tmpstr.length;
ebcdic2ascii(tmp, tmpstr.data,
- (len >= sizeof tmp) ? sizeof tmp : len);
+ (len >= sizeof(tmp)) ? sizeof(tmp) : len);
tmpstr.data = tmp;
a = (ASN1_GENERALIZEDTIME *)&tmpstr;
}
# endif
if (a->type == V_ASN1_UTCTIME || a->type == V_ASN1_GENERALIZEDTIME)
return (i2d_ASN1_bytes((ASN1_STRING *)a, pp,
a->type, V_ASN1_UNIVERSAL));
ASN1err(ASN1_F_I2D_ASN1_TIME, ASN1_R_EXPECTING_A_TIME);
return -1;
}
#endif
ASN1_TIME *ASN1_TIME_set(ASN1_TIME *s, time_t t)
{
return ASN1_TIME_adj(s, t, 0, 0);
}
ASN1_TIME *ASN1_TIME_adj(ASN1_TIME *s, time_t t,
int offset_day, long offset_sec)
{
struct tm *ts;
struct tm data;
ts = OPENSSL_gmtime(&t, &data);
if (ts == NULL) {
ASN1err(ASN1_F_ASN1_TIME_ADJ, ASN1_R_ERROR_GETTING_TIME);
return NULL;
}
if (offset_day || offset_sec) {
if (!OPENSSL_gmtime_adj(ts, offset_day, offset_sec))
return NULL;
}
if ((ts->tm_year >= 50) && (ts->tm_year < 150))
return ASN1_UTCTIME_adj(s, t, offset_day, offset_sec);
return ASN1_GENERALIZEDTIME_adj(s, t, offset_day, offset_sec);
}
int ASN1_TIME_check(ASN1_TIME *t)
{
if (t->type == V_ASN1_GENERALIZEDTIME)
return ASN1_GENERALIZEDTIME_check(t);
else if (t->type == V_ASN1_UTCTIME)
return ASN1_UTCTIME_check(t);
return 0;
}
/* Convert an ASN1_TIME structure to GeneralizedTime */
ASN1_GENERALIZEDTIME *ASN1_TIME_to_generalizedtime(ASN1_TIME *t,
ASN1_GENERALIZEDTIME **out)
{
ASN1_GENERALIZEDTIME *ret = NULL;
char *str;
int newlen;
if (!ASN1_TIME_check(t))
return NULL;
if (!out || !*out) {
if (!(ret = ASN1_GENERALIZEDTIME_new()))
goto err;
} else {
ret = *out;
}
/* If already GeneralizedTime just copy across */
if (t->type == V_ASN1_GENERALIZEDTIME) {
if (!ASN1_STRING_set(ret, t->data, t->length))
goto err;
goto done;
}
/* grow the string */
if (!ASN1_STRING_set(ret, NULL, t->length + 2))
goto err;
/* ASN1_STRING_set() allocated 'len + 1' bytes. */
newlen = t->length + 2 + 1;
str = (char *)ret->data;
/* Work out the century and prepend */
if (t->data[0] >= '5')
BUF_strlcpy(str, "19", newlen);
else
BUF_strlcpy(str, "20", newlen);
BUF_strlcat(str, (char *)t->data, newlen);
done:
if (out != NULL && *out == NULL)
*out = ret;
return ret;
err:
if (out == NULL || *out != ret)
ASN1_GENERALIZEDTIME_free(ret);
return NULL;
}
int ASN1_TIME_set_string(ASN1_TIME *s, const char *str)
{
ASN1_TIME t;
t.length = strlen(str);
t.data = (unsigned char *)str;
t.flags = 0;
t.type = V_ASN1_UTCTIME;
if (!ASN1_TIME_check(&t)) {
t.type = V_ASN1_GENERALIZEDTIME;
if (!ASN1_TIME_check(&t))
return 0;
}
if (s && !ASN1_STRING_copy((ASN1_STRING *)s, (ASN1_STRING *)&t))
return 0;
return 1;
}
static int asn1_time_to_tm(struct tm *tm, const ASN1_TIME *t)
{
if (t == NULL) {
time_t now_t;
time(&now_t);
if (OPENSSL_gmtime(&now_t, tm))
return 1;
return 0;
}
if (t->type == V_ASN1_UTCTIME)
return asn1_utctime_to_tm(tm, t);
else if (t->type == V_ASN1_GENERALIZEDTIME)
return asn1_generalizedtime_to_tm(tm, t);
return 0;
}
int ASN1_TIME_diff(int *pday, int *psec,
const ASN1_TIME *from, const ASN1_TIME *to)
{
struct tm tm_from, tm_to;
if (!asn1_time_to_tm(&tm_from, from))
return 0;
if (!asn1_time_to_tm(&tm_to, to))
return 0;
return OPENSSL_gmtime_diff(pday, psec, &tm_from, &tm_to);
}
diff --git a/crypto/asn1/a_utctm.c b/crypto/asn1/a_utctm.c
index 0344482cc247..9cbad7c5ee1a 100644
--- a/crypto/asn1/a_utctm.c
+++ b/crypto/asn1/a_utctm.c
@@ -1,352 +1,352 @@
/* crypto/asn1/a_utctm.c */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
#include <stdio.h>
#include <time.h>
#include "cryptlib.h"
#include "o_time.h"
#include <openssl/asn1.h>
#include "asn1_locl.h"
#if 0
int i2d_ASN1_UTCTIME(ASN1_UTCTIME *a, unsigned char **pp)
{
# ifndef CHARSET_EBCDIC
return (i2d_ASN1_bytes((ASN1_STRING *)a, pp,
V_ASN1_UTCTIME, V_ASN1_UNIVERSAL));
# else
/* KLUDGE! We convert to ascii before writing DER */
int len;
char tmp[24];
ASN1_STRING x = *(ASN1_STRING *)a;
len = x.length;
- ebcdic2ascii(tmp, x.data, (len >= sizeof tmp) ? sizeof tmp : len);
+ ebcdic2ascii(tmp, x.data, (len >= sizeof(tmp)) ? sizeof(tmp) : len);
x.data = tmp;
return i2d_ASN1_bytes(&x, pp, V_ASN1_UTCTIME, V_ASN1_UNIVERSAL);
# endif
}
ASN1_UTCTIME *d2i_ASN1_UTCTIME(ASN1_UTCTIME **a, unsigned char **pp,
long length)
{
ASN1_UTCTIME *ret = NULL;
ret = (ASN1_UTCTIME *)d2i_ASN1_bytes((ASN1_STRING **)a, pp, length,
V_ASN1_UTCTIME, V_ASN1_UNIVERSAL);
if (ret == NULL) {
ASN1err(ASN1_F_D2I_ASN1_UTCTIME, ERR_R_NESTED_ASN1_ERROR);
return (NULL);
}
# ifdef CHARSET_EBCDIC
ascii2ebcdic(ret->data, ret->data, ret->length);
# endif
if (!ASN1_UTCTIME_check(ret)) {
ASN1err(ASN1_F_D2I_ASN1_UTCTIME, ASN1_R_INVALID_TIME_FORMAT);
goto err;
}
return (ret);
err:
if ((ret != NULL) && ((a == NULL) || (*a != ret)))
M_ASN1_UTCTIME_free(ret);
return (NULL);
}
#endif
int asn1_utctime_to_tm(struct tm *tm, const ASN1_UTCTIME *d)
{
static const int min[8] = { 0, 1, 1, 0, 0, 0, 0, 0 };
static const int max[8] = { 99, 12, 31, 23, 59, 59, 12, 59 };
char *a;
int n, i, l, o;
if (d->type != V_ASN1_UTCTIME)
return (0);
l = d->length;
a = (char *)d->data;
o = 0;
if (l < 11)
goto err;
for (i = 0; i < 6; i++) {
if ((i == 5) && ((a[o] == 'Z') || (a[o] == '+') || (a[o] == '-'))) {
i++;
if (tm)
tm->tm_sec = 0;
break;
}
if ((a[o] < '0') || (a[o] > '9'))
goto err;
n = a[o] - '0';
if (++o > l)
goto err;
if ((a[o] < '0') || (a[o] > '9'))
goto err;
n = (n * 10) + a[o] - '0';
if (++o > l)
goto err;
if ((n < min[i]) || (n > max[i]))
goto err;
if (tm) {
switch (i) {
case 0:
tm->tm_year = n < 50 ? n + 100 : n;
break;
case 1:
tm->tm_mon = n - 1;
break;
case 2:
tm->tm_mday = n;
break;
case 3:
tm->tm_hour = n;
break;
case 4:
tm->tm_min = n;
break;
case 5:
tm->tm_sec = n;
break;
}
}
}
if (a[o] == 'Z')
o++;
else if ((a[o] == '+') || (a[o] == '-')) {
int offsign = a[o] == '-' ? 1 : -1, offset = 0;
o++;
if (o + 4 > l)
goto err;
for (i = 6; i < 8; i++) {
if ((a[o] < '0') || (a[o] > '9'))
goto err;
n = a[o] - '0';
o++;
if ((a[o] < '0') || (a[o] > '9'))
goto err;
n = (n * 10) + a[o] - '0';
if ((n < min[i]) || (n > max[i]))
goto err;
if (tm) {
if (i == 6)
offset = n * 3600;
else if (i == 7)
offset += n * 60;
}
o++;
}
if (offset && !OPENSSL_gmtime_adj(tm, 0, offset * offsign))
return 0;
}
return o == l;
err:
return 0;
}
int ASN1_UTCTIME_check(const ASN1_UTCTIME *d)
{
return asn1_utctime_to_tm(NULL, d);
}
int ASN1_UTCTIME_set_string(ASN1_UTCTIME *s, const char *str)
{
ASN1_UTCTIME t;
t.type = V_ASN1_UTCTIME;
t.length = strlen(str);
t.data = (unsigned char *)str;
if (ASN1_UTCTIME_check(&t)) {
if (s != NULL) {
if (!ASN1_STRING_set((ASN1_STRING *)s,
(unsigned char *)str, t.length))
return 0;
s->type = V_ASN1_UTCTIME;
}
return (1);
} else
return (0);
}
ASN1_UTCTIME *ASN1_UTCTIME_set(ASN1_UTCTIME *s, time_t t)
{
return ASN1_UTCTIME_adj(s, t, 0, 0);
}
ASN1_UTCTIME *ASN1_UTCTIME_adj(ASN1_UTCTIME *s, time_t t,
int offset_day, long offset_sec)
{
char *p;
struct tm *ts;
struct tm data;
size_t len = 20;
int free_s = 0;
if (s == NULL) {
free_s = 1;
s = M_ASN1_UTCTIME_new();
}
if (s == NULL)
goto err;
ts = OPENSSL_gmtime(&t, &data);
if (ts == NULL)
goto err;
if (offset_day || offset_sec) {
if (!OPENSSL_gmtime_adj(ts, offset_day, offset_sec))
goto err;
}
if ((ts->tm_year < 50) || (ts->tm_year >= 150))
goto err;
p = (char *)s->data;
if ((p == NULL) || ((size_t)s->length < len)) {
p = OPENSSL_malloc(len);
if (p == NULL) {
ASN1err(ASN1_F_ASN1_UTCTIME_ADJ, ERR_R_MALLOC_FAILURE);
goto err;
}
if (s->data != NULL)
OPENSSL_free(s->data);
s->data = (unsigned char *)p;
}
BIO_snprintf(p, len, "%02d%02d%02d%02d%02d%02dZ", ts->tm_year % 100,
ts->tm_mon + 1, ts->tm_mday, ts->tm_hour, ts->tm_min,
ts->tm_sec);
s->length = strlen(p);
s->type = V_ASN1_UTCTIME;
#ifdef CHARSET_EBCDIC_not
ebcdic2ascii(s->data, s->data, s->length);
#endif
return (s);
err:
if (free_s && s)
M_ASN1_UTCTIME_free(s);
return NULL;
}
int ASN1_UTCTIME_cmp_time_t(const ASN1_UTCTIME *s, time_t t)
{
struct tm stm, ttm;
int day, sec;
if (!asn1_utctime_to_tm(&stm, s))
return -2;
if (!OPENSSL_gmtime(&t, &ttm))
return -2;
if (!OPENSSL_gmtime_diff(&day, &sec, &ttm, &stm))
return -2;
if (day > 0)
return 1;
if (day < 0)
return -1;
if (sec > 0)
return 1;
if (sec < 0)
return -1;
return 0;
}
#if 0
time_t ASN1_UTCTIME_get(const ASN1_UTCTIME *s)
{
struct tm tm;
int offset;
- memset(&tm, '\0', sizeof tm);
+ memset(&tm, '\0', sizeof(tm));
# define g2(p) (((p)[0]-'0')*10+(p)[1]-'0')
tm.tm_year = g2(s->data);
if (tm.tm_year < 50)
tm.tm_year += 100;
tm.tm_mon = g2(s->data + 2) - 1;
tm.tm_mday = g2(s->data + 4);
tm.tm_hour = g2(s->data + 6);
tm.tm_min = g2(s->data + 8);
tm.tm_sec = g2(s->data + 10);
if (s->data[12] == 'Z')
offset = 0;
else {
offset = g2(s->data + 13) * 60 + g2(s->data + 15);
if (s->data[12] == '-')
offset = -offset;
}
# undef g2
/*
* FIXME: mktime assumes the current timezone
* instead of UTC, and unless we rewrite OpenSSL
* in Lisp we cannot locally change the timezone
* without possibly interfering with other parts
* of the program. timegm, which uses UTC, is
* non-standard.
* Also time_t is inappropriate for general
* UTC times because it may a 32 bit type.
*/
return mktime(&tm) - offset * 60;
}
#endif
diff --git a/crypto/asn1/asn1.h b/crypto/asn1/asn1.h
index 68e791fcdbe8..35a2b2aa0238 100644
--- a/crypto/asn1/asn1.h
+++ b/crypto/asn1/asn1.h
@@ -1,1419 +1,1420 @@
/* crypto/asn1/asn1.h */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
#ifndef HEADER_ASN1_H
# define HEADER_ASN1_H
# include <time.h>
# include <openssl/e_os2.h>
# ifndef OPENSSL_NO_BIO
# include <openssl/bio.h>
# endif
# include <openssl/stack.h>
# include <openssl/safestack.h>
# include <openssl/symhacks.h>
# include <openssl/ossl_typ.h>
# ifndef OPENSSL_NO_DEPRECATED
# include <openssl/bn.h>
# endif
# ifdef OPENSSL_BUILD_SHLIBCRYPTO
# undef OPENSSL_EXTERN
# define OPENSSL_EXTERN OPENSSL_EXPORT
# endif
#ifdef __cplusplus
extern "C" {
#endif
# define V_ASN1_UNIVERSAL 0x00
# define V_ASN1_APPLICATION 0x40
# define V_ASN1_CONTEXT_SPECIFIC 0x80
# define V_ASN1_PRIVATE 0xc0
# define V_ASN1_CONSTRUCTED 0x20
# define V_ASN1_PRIMITIVE_TAG 0x1f
# define V_ASN1_PRIMATIVE_TAG 0x1f
# define V_ASN1_APP_CHOOSE -2/* let the recipient choose */
# define V_ASN1_OTHER -3/* used in ASN1_TYPE */
# define V_ASN1_ANY -4/* used in ASN1 template code */
# define V_ASN1_NEG 0x100/* negative flag */
# define V_ASN1_UNDEF -1
# define V_ASN1_EOC 0
# define V_ASN1_BOOLEAN 1 /**/
# define V_ASN1_INTEGER 2
# define V_ASN1_NEG_INTEGER (2 | V_ASN1_NEG)
# define V_ASN1_BIT_STRING 3
# define V_ASN1_OCTET_STRING 4
# define V_ASN1_NULL 5
# define V_ASN1_OBJECT 6
# define V_ASN1_OBJECT_DESCRIPTOR 7
# define V_ASN1_EXTERNAL 8
# define V_ASN1_REAL 9
# define V_ASN1_ENUMERATED 10
# define V_ASN1_NEG_ENUMERATED (10 | V_ASN1_NEG)
# define V_ASN1_UTF8STRING 12
# define V_ASN1_SEQUENCE 16
# define V_ASN1_SET 17
# define V_ASN1_NUMERICSTRING 18 /**/
# define V_ASN1_PRINTABLESTRING 19
# define V_ASN1_T61STRING 20
# define V_ASN1_TELETEXSTRING 20/* alias */
# define V_ASN1_VIDEOTEXSTRING 21 /**/
# define V_ASN1_IA5STRING 22
# define V_ASN1_UTCTIME 23
# define V_ASN1_GENERALIZEDTIME 24 /**/
# define V_ASN1_GRAPHICSTRING 25 /**/
# define V_ASN1_ISO64STRING 26 /**/
# define V_ASN1_VISIBLESTRING 26/* alias */
# define V_ASN1_GENERALSTRING 27 /**/
# define V_ASN1_UNIVERSALSTRING 28 /**/
# define V_ASN1_BMPSTRING 30
/* For use with d2i_ASN1_type_bytes() */
# define B_ASN1_NUMERICSTRING 0x0001
# define B_ASN1_PRINTABLESTRING 0x0002
# define B_ASN1_T61STRING 0x0004
# define B_ASN1_TELETEXSTRING 0x0004
# define B_ASN1_VIDEOTEXSTRING 0x0008
# define B_ASN1_IA5STRING 0x0010
# define B_ASN1_GRAPHICSTRING 0x0020
# define B_ASN1_ISO64STRING 0x0040
# define B_ASN1_VISIBLESTRING 0x0040
# define B_ASN1_GENERALSTRING 0x0080
# define B_ASN1_UNIVERSALSTRING 0x0100
# define B_ASN1_OCTET_STRING 0x0200
# define B_ASN1_BIT_STRING 0x0400
# define B_ASN1_BMPSTRING 0x0800
# define B_ASN1_UNKNOWN 0x1000
# define B_ASN1_UTF8STRING 0x2000
# define B_ASN1_UTCTIME 0x4000
# define B_ASN1_GENERALIZEDTIME 0x8000
# define B_ASN1_SEQUENCE 0x10000
/* For use with ASN1_mbstring_copy() */
# define MBSTRING_FLAG 0x1000
# define MBSTRING_UTF8 (MBSTRING_FLAG)
# define MBSTRING_ASC (MBSTRING_FLAG|1)
# define MBSTRING_BMP (MBSTRING_FLAG|2)
# define MBSTRING_UNIV (MBSTRING_FLAG|4)
# define SMIME_OLDMIME 0x400
# define SMIME_CRLFEOL 0x800
# define SMIME_STREAM 0x1000
struct X509_algor_st;
DECLARE_STACK_OF(X509_ALGOR)
# define DECLARE_ASN1_SET_OF(type)/* filled in by mkstack.pl */
# define IMPLEMENT_ASN1_SET_OF(type)/* nothing, no longer needed */
/*
* We MUST make sure that, except for constness, asn1_ctx_st and
* asn1_const_ctx are exactly the same. Fortunately, as soon as the old ASN1
* parsing macros are gone, we can throw this away as well...
*/
typedef struct asn1_ctx_st {
unsigned char *p; /* work char pointer */
int eos; /* end of sequence read for indefinite
* encoding */
int error; /* error code to use when returning an error */
int inf; /* constructed if 0x20, indefinite is 0x21 */
int tag; /* tag from last 'get object' */
int xclass; /* class from last 'get object' */
long slen; /* length of last 'get object' */
unsigned char *max; /* largest value of p allowed */
unsigned char *q; /* temporary variable */
unsigned char **pp; /* variable */
int line; /* used in error processing */
} ASN1_CTX;
typedef struct asn1_const_ctx_st {
const unsigned char *p; /* work char pointer */
int eos; /* end of sequence read for indefinite
* encoding */
int error; /* error code to use when returning an error */
int inf; /* constructed if 0x20, indefinite is 0x21 */
int tag; /* tag from last 'get object' */
int xclass; /* class from last 'get object' */
long slen; /* length of last 'get object' */
const unsigned char *max; /* largest value of p allowed */
const unsigned char *q; /* temporary variable */
const unsigned char **pp; /* variable */
int line; /* used in error processing */
} ASN1_const_CTX;
/*
* These are used internally in the ASN1_OBJECT to keep track of whether the
* names and data need to be free()ed
*/
# define ASN1_OBJECT_FLAG_DYNAMIC 0x01/* internal use */
# define ASN1_OBJECT_FLAG_CRITICAL 0x02/* critical x509v3 object id */
# define ASN1_OBJECT_FLAG_DYNAMIC_STRINGS 0x04/* internal use */
# define ASN1_OBJECT_FLAG_DYNAMIC_DATA 0x08/* internal use */
struct asn1_object_st {
const char *sn, *ln;
int nid;
int length;
const unsigned char *data; /* data remains const after init */
int flags; /* Should we free this one */
};
# define ASN1_STRING_FLAG_BITS_LEFT 0x08/* Set if 0x07 has bits left value */
/*
* This indicates that the ASN1_STRING is not a real value but just a place
* holder for the location where indefinite length constructed data should be
* inserted in the memory buffer
*/
# define ASN1_STRING_FLAG_NDEF 0x010
/*
* This flag is used by the CMS code to indicate that a string is not
* complete and is a place holder for content when it had all been accessed.
* The flag will be reset when content has been written to it.
*/
# define ASN1_STRING_FLAG_CONT 0x020
/*
* This flag is used by ASN1 code to indicate an ASN1_STRING is an MSTRING
* type.
*/
# define ASN1_STRING_FLAG_MSTRING 0x040
/* This is the base type that holds just about everything :-) */
struct asn1_string_st {
int length;
int type;
unsigned char *data;
/*
* The value of the following field depends on the type being held. It
* is mostly being used for BIT_STRING so if the input data has a
* non-zero 'unused bits' value, it will be handled correctly
*/
long flags;
};
/*
* ASN1_ENCODING structure: this is used to save the received encoding of an
* ASN1 type. This is useful to get round problems with invalid encodings
* which can break signatures.
*/
typedef struct ASN1_ENCODING_st {
unsigned char *enc; /* DER encoding */
long len; /* Length of encoding */
int modified; /* set to 1 if 'enc' is invalid */
} ASN1_ENCODING;
/* Used with ASN1 LONG type: if a long is set to this it is omitted */
# define ASN1_LONG_UNDEF 0x7fffffffL
# define STABLE_FLAGS_MALLOC 0x01
# define STABLE_NO_MASK 0x02
# define DIRSTRING_TYPE \
(B_ASN1_PRINTABLESTRING|B_ASN1_T61STRING|B_ASN1_BMPSTRING|B_ASN1_UTF8STRING)
# define PKCS9STRING_TYPE (DIRSTRING_TYPE|B_ASN1_IA5STRING)
typedef struct asn1_string_table_st {
int nid;
long minsize;
long maxsize;
unsigned long mask;
unsigned long flags;
} ASN1_STRING_TABLE;
DECLARE_STACK_OF(ASN1_STRING_TABLE)
/* size limits: this stuff is taken straight from RFC2459 */
# define ub_name 32768
# define ub_common_name 64
# define ub_locality_name 128
# define ub_state_name 128
# define ub_organization_name 64
# define ub_organization_unit_name 64
# define ub_title 64
# define ub_email_address 128
/*
* Declarations for template structures: for full definitions see asn1t.h
*/
typedef struct ASN1_TEMPLATE_st ASN1_TEMPLATE;
typedef struct ASN1_TLC_st ASN1_TLC;
/* This is just an opaque pointer */
typedef struct ASN1_VALUE_st ASN1_VALUE;
/* Declare ASN1 functions: the implement macro in in asn1t.h */
# define DECLARE_ASN1_FUNCTIONS(type) DECLARE_ASN1_FUNCTIONS_name(type, type)
# define DECLARE_ASN1_ALLOC_FUNCTIONS(type) \
DECLARE_ASN1_ALLOC_FUNCTIONS_name(type, type)
# define DECLARE_ASN1_FUNCTIONS_name(type, name) \
DECLARE_ASN1_ALLOC_FUNCTIONS_name(type, name) \
DECLARE_ASN1_ENCODE_FUNCTIONS(type, name, name)
# define DECLARE_ASN1_FUNCTIONS_fname(type, itname, name) \
DECLARE_ASN1_ALLOC_FUNCTIONS_name(type, name) \
DECLARE_ASN1_ENCODE_FUNCTIONS(type, itname, name)
# define DECLARE_ASN1_ENCODE_FUNCTIONS(type, itname, name) \
type *d2i_##name(type **a, const unsigned char **in, long len); \
int i2d_##name(type *a, unsigned char **out); \
DECLARE_ASN1_ITEM(itname)
# define DECLARE_ASN1_ENCODE_FUNCTIONS_const(type, name) \
type *d2i_##name(type **a, const unsigned char **in, long len); \
int i2d_##name(const type *a, unsigned char **out); \
DECLARE_ASN1_ITEM(name)
# define DECLARE_ASN1_NDEF_FUNCTION(name) \
int i2d_##name##_NDEF(name *a, unsigned char **out);
# define DECLARE_ASN1_FUNCTIONS_const(name) \
DECLARE_ASN1_ALLOC_FUNCTIONS(name) \
DECLARE_ASN1_ENCODE_FUNCTIONS_const(name, name)
# define DECLARE_ASN1_ALLOC_FUNCTIONS_name(type, name) \
type *name##_new(void); \
void name##_free(type *a);
# define DECLARE_ASN1_PRINT_FUNCTION(stname) \
DECLARE_ASN1_PRINT_FUNCTION_fname(stname, stname)
# define DECLARE_ASN1_PRINT_FUNCTION_fname(stname, fname) \
int fname##_print_ctx(BIO *out, stname *x, int indent, \
const ASN1_PCTX *pctx);
# define D2I_OF(type) type *(*)(type **,const unsigned char **,long)
# define I2D_OF(type) int (*)(type *,unsigned char **)
# define I2D_OF_const(type) int (*)(const type *,unsigned char **)
# define CHECKED_D2I_OF(type, d2i) \
((d2i_of_void*) (1 ? d2i : ((D2I_OF(type))0)))
# define CHECKED_I2D_OF(type, i2d) \
((i2d_of_void*) (1 ? i2d : ((I2D_OF(type))0)))
# define CHECKED_NEW_OF(type, xnew) \
((void *(*)(void)) (1 ? xnew : ((type *(*)(void))0)))
# define CHECKED_PTR_OF(type, p) \
((void*) (1 ? p : (type*)0))
# define CHECKED_PPTR_OF(type, p) \
((void**) (1 ? p : (type**)0))
# define TYPEDEF_D2I_OF(type) typedef type *d2i_of_##type(type **,const unsigned char **,long)
# define TYPEDEF_I2D_OF(type) typedef int i2d_of_##type(type *,unsigned char **)
# define TYPEDEF_D2I2D_OF(type) TYPEDEF_D2I_OF(type); TYPEDEF_I2D_OF(type)
TYPEDEF_D2I2D_OF(void);
/*-
* The following macros and typedefs allow an ASN1_ITEM
* to be embedded in a structure and referenced. Since
* the ASN1_ITEM pointers need to be globally accessible
* (possibly from shared libraries) they may exist in
* different forms. On platforms that support it the
* ASN1_ITEM structure itself will be globally exported.
* Other platforms will export a function that returns
* an ASN1_ITEM pointer.
*
* To handle both cases transparently the macros below
* should be used instead of hard coding an ASN1_ITEM
* pointer in a structure.
*
* The structure will look like this:
*
* typedef struct SOMETHING_st {
* ...
* ASN1_ITEM_EXP *iptr;
* ...
* } SOMETHING;
*
* It would be initialised as e.g.:
*
* SOMETHING somevar = {...,ASN1_ITEM_ref(X509),...};
*
* and the actual pointer extracted with:
*
* const ASN1_ITEM *it = ASN1_ITEM_ptr(somevar.iptr);
*
* Finally an ASN1_ITEM pointer can be extracted from an
* appropriate reference with: ASN1_ITEM_rptr(X509). This
* would be used when a function takes an ASN1_ITEM * argument.
*
*/
# ifndef OPENSSL_EXPORT_VAR_AS_FUNCTION
/* ASN1_ITEM pointer exported type */
typedef const ASN1_ITEM ASN1_ITEM_EXP;
/* Macro to obtain ASN1_ITEM pointer from exported type */
# define ASN1_ITEM_ptr(iptr) (iptr)
/* Macro to include ASN1_ITEM pointer from base type */
# define ASN1_ITEM_ref(iptr) (&(iptr##_it))
# define ASN1_ITEM_rptr(ref) (&(ref##_it))
# define DECLARE_ASN1_ITEM(name) \
OPENSSL_EXTERN const ASN1_ITEM name##_it;
# else
/*
* Platforms that can't easily handle shared global variables are declared as
* functions returning ASN1_ITEM pointers.
*/
/* ASN1_ITEM pointer exported type */
typedef const ASN1_ITEM *ASN1_ITEM_EXP (void);
/* Macro to obtain ASN1_ITEM pointer from exported type */
# define ASN1_ITEM_ptr(iptr) (iptr())
/* Macro to include ASN1_ITEM pointer from base type */
# define ASN1_ITEM_ref(iptr) (iptr##_it)
# define ASN1_ITEM_rptr(ref) (ref##_it())
# define DECLARE_ASN1_ITEM(name) \
const ASN1_ITEM * name##_it(void);
# endif
/* Parameters used by ASN1_STRING_print_ex() */
/*
* These determine which characters to escape: RFC2253 special characters,
* control characters and MSB set characters
*/
# define ASN1_STRFLGS_ESC_2253 1
# define ASN1_STRFLGS_ESC_CTRL 2
# define ASN1_STRFLGS_ESC_MSB 4
/*
* This flag determines how we do escaping: normally RC2253 backslash only,
* set this to use backslash and quote.
*/
# define ASN1_STRFLGS_ESC_QUOTE 8
/* These three flags are internal use only. */
/* Character is a valid PrintableString character */
# define CHARTYPE_PRINTABLESTRING 0x10
/* Character needs escaping if it is the first character */
# define CHARTYPE_FIRST_ESC_2253 0x20
/* Character needs escaping if it is the last character */
# define CHARTYPE_LAST_ESC_2253 0x40
/*
* NB the internal flags are safely reused below by flags handled at the top
* level.
*/
/*
* If this is set we convert all character strings to UTF8 first
*/
# define ASN1_STRFLGS_UTF8_CONVERT 0x10
/*
* If this is set we don't attempt to interpret content: just assume all
* strings are 1 byte per character. This will produce some pretty odd
* looking output!
*/
# define ASN1_STRFLGS_IGNORE_TYPE 0x20
/* If this is set we include the string type in the output */
# define ASN1_STRFLGS_SHOW_TYPE 0x40
/*
* This determines which strings to display and which to 'dump' (hex dump of
* content octets or DER encoding). We can only dump non character strings or
* everything. If we don't dump 'unknown' they are interpreted as character
* strings with 1 octet per character and are subject to the usual escaping
* options.
*/
# define ASN1_STRFLGS_DUMP_ALL 0x80
# define ASN1_STRFLGS_DUMP_UNKNOWN 0x100
/*
* These determine what 'dumping' does, we can dump the content octets or the
* DER encoding: both use the RFC2253 #XXXXX notation.
*/
# define ASN1_STRFLGS_DUMP_DER 0x200
/*
* All the string flags consistent with RFC2253, escaping control characters
* isn't essential in RFC2253 but it is advisable anyway.
*/
# define ASN1_STRFLGS_RFC2253 (ASN1_STRFLGS_ESC_2253 | \
ASN1_STRFLGS_ESC_CTRL | \
ASN1_STRFLGS_ESC_MSB | \
ASN1_STRFLGS_UTF8_CONVERT | \
ASN1_STRFLGS_DUMP_UNKNOWN | \
ASN1_STRFLGS_DUMP_DER)
DECLARE_STACK_OF(ASN1_INTEGER)
DECLARE_ASN1_SET_OF(ASN1_INTEGER)
DECLARE_STACK_OF(ASN1_GENERALSTRING)
typedef struct asn1_type_st {
int type;
union {
char *ptr;
ASN1_BOOLEAN boolean;
ASN1_STRING *asn1_string;
ASN1_OBJECT *object;
ASN1_INTEGER *integer;
ASN1_ENUMERATED *enumerated;
ASN1_BIT_STRING *bit_string;
ASN1_OCTET_STRING *octet_string;
ASN1_PRINTABLESTRING *printablestring;
ASN1_T61STRING *t61string;
ASN1_IA5STRING *ia5string;
ASN1_GENERALSTRING *generalstring;
ASN1_BMPSTRING *bmpstring;
ASN1_UNIVERSALSTRING *universalstring;
ASN1_UTCTIME *utctime;
ASN1_GENERALIZEDTIME *generalizedtime;
ASN1_VISIBLESTRING *visiblestring;
ASN1_UTF8STRING *utf8string;
/*
* set and sequence are left complete and still contain the set or
* sequence bytes
*/
ASN1_STRING *set;
ASN1_STRING *sequence;
ASN1_VALUE *asn1_value;
} value;
} ASN1_TYPE;
DECLARE_STACK_OF(ASN1_TYPE)
DECLARE_ASN1_SET_OF(ASN1_TYPE)
typedef STACK_OF(ASN1_TYPE) ASN1_SEQUENCE_ANY;
DECLARE_ASN1_ENCODE_FUNCTIONS_const(ASN1_SEQUENCE_ANY, ASN1_SEQUENCE_ANY)
DECLARE_ASN1_ENCODE_FUNCTIONS_const(ASN1_SEQUENCE_ANY, ASN1_SET_ANY)
typedef struct NETSCAPE_X509_st {
ASN1_OCTET_STRING *header;
X509 *cert;
} NETSCAPE_X509;
/* This is used to contain a list of bit names */
typedef struct BIT_STRING_BITNAME_st {
int bitnum;
const char *lname;
const char *sname;
} BIT_STRING_BITNAME;
# define M_ASN1_STRING_length(x) ((x)->length)
# define M_ASN1_STRING_length_set(x, n) ((x)->length = (n))
# define M_ASN1_STRING_type(x) ((x)->type)
# define M_ASN1_STRING_data(x) ((x)->data)
/* Macros for string operations */
# define M_ASN1_BIT_STRING_new() (ASN1_BIT_STRING *)\
ASN1_STRING_type_new(V_ASN1_BIT_STRING)
# define M_ASN1_BIT_STRING_free(a) ASN1_STRING_free((ASN1_STRING *)a)
# define M_ASN1_BIT_STRING_dup(a) (ASN1_BIT_STRING *)\
ASN1_STRING_dup((const ASN1_STRING *)a)
# define M_ASN1_BIT_STRING_cmp(a,b) ASN1_STRING_cmp(\
(const ASN1_STRING *)a,(const ASN1_STRING *)b)
# define M_ASN1_BIT_STRING_set(a,b,c) ASN1_STRING_set((ASN1_STRING *)a,b,c)
# define M_ASN1_INTEGER_new() (ASN1_INTEGER *)\
ASN1_STRING_type_new(V_ASN1_INTEGER)
# define M_ASN1_INTEGER_free(a) ASN1_STRING_free((ASN1_STRING *)a)
# define M_ASN1_INTEGER_dup(a) (ASN1_INTEGER *)\
ASN1_STRING_dup((const ASN1_STRING *)a)
# define M_ASN1_INTEGER_cmp(a,b) ASN1_STRING_cmp(\
(const ASN1_STRING *)a,(const ASN1_STRING *)b)
# define M_ASN1_ENUMERATED_new() (ASN1_ENUMERATED *)\
ASN1_STRING_type_new(V_ASN1_ENUMERATED)
# define M_ASN1_ENUMERATED_free(a) ASN1_STRING_free((ASN1_STRING *)a)
# define M_ASN1_ENUMERATED_dup(a) (ASN1_ENUMERATED *)\
ASN1_STRING_dup((const ASN1_STRING *)a)
# define M_ASN1_ENUMERATED_cmp(a,b) ASN1_STRING_cmp(\
(const ASN1_STRING *)a,(const ASN1_STRING *)b)
# define M_ASN1_OCTET_STRING_new() (ASN1_OCTET_STRING *)\
ASN1_STRING_type_new(V_ASN1_OCTET_STRING)
# define M_ASN1_OCTET_STRING_free(a) ASN1_STRING_free((ASN1_STRING *)a)
# define M_ASN1_OCTET_STRING_dup(a) (ASN1_OCTET_STRING *)\
ASN1_STRING_dup((const ASN1_STRING *)a)
# define M_ASN1_OCTET_STRING_cmp(a,b) ASN1_STRING_cmp(\
(const ASN1_STRING *)a,(const ASN1_STRING *)b)
# define M_ASN1_OCTET_STRING_set(a,b,c) ASN1_STRING_set((ASN1_STRING *)a,b,c)
# define M_ASN1_OCTET_STRING_print(a,b) ASN1_STRING_print(a,(ASN1_STRING *)b)
# define M_i2d_ASN1_OCTET_STRING(a,pp) \
i2d_ASN1_bytes((ASN1_STRING *)a,pp,V_ASN1_OCTET_STRING,\
V_ASN1_UNIVERSAL)
# define B_ASN1_TIME \
B_ASN1_UTCTIME | \
B_ASN1_GENERALIZEDTIME
# define B_ASN1_PRINTABLE \
B_ASN1_NUMERICSTRING| \
B_ASN1_PRINTABLESTRING| \
B_ASN1_T61STRING| \
B_ASN1_IA5STRING| \
B_ASN1_BIT_STRING| \
B_ASN1_UNIVERSALSTRING|\
B_ASN1_BMPSTRING|\
B_ASN1_UTF8STRING|\
B_ASN1_SEQUENCE|\
B_ASN1_UNKNOWN
# define B_ASN1_DIRECTORYSTRING \
B_ASN1_PRINTABLESTRING| \
B_ASN1_TELETEXSTRING|\
B_ASN1_BMPSTRING|\
B_ASN1_UNIVERSALSTRING|\
B_ASN1_UTF8STRING
# define B_ASN1_DISPLAYTEXT \
B_ASN1_IA5STRING| \
B_ASN1_VISIBLESTRING| \
B_ASN1_BMPSTRING|\
B_ASN1_UTF8STRING
# define M_ASN1_PRINTABLE_new() ASN1_STRING_type_new(V_ASN1_T61STRING)
# define M_ASN1_PRINTABLE_free(a) ASN1_STRING_free((ASN1_STRING *)a)
# define M_i2d_ASN1_PRINTABLE(a,pp) i2d_ASN1_bytes((ASN1_STRING *)a,\
pp,a->type,V_ASN1_UNIVERSAL)
# define M_d2i_ASN1_PRINTABLE(a,pp,l) \
d2i_ASN1_type_bytes((ASN1_STRING **)a,pp,l, \
B_ASN1_PRINTABLE)
# define M_DIRECTORYSTRING_new() ASN1_STRING_type_new(V_ASN1_PRINTABLESTRING)
# define M_DIRECTORYSTRING_free(a) ASN1_STRING_free((ASN1_STRING *)a)
# define M_i2d_DIRECTORYSTRING(a,pp) i2d_ASN1_bytes((ASN1_STRING *)a,\
pp,a->type,V_ASN1_UNIVERSAL)
# define M_d2i_DIRECTORYSTRING(a,pp,l) \
d2i_ASN1_type_bytes((ASN1_STRING **)a,pp,l, \
B_ASN1_DIRECTORYSTRING)
# define M_DISPLAYTEXT_new() ASN1_STRING_type_new(V_ASN1_VISIBLESTRING)
# define M_DISPLAYTEXT_free(a) ASN1_STRING_free((ASN1_STRING *)a)
# define M_i2d_DISPLAYTEXT(a,pp) i2d_ASN1_bytes((ASN1_STRING *)a,\
pp,a->type,V_ASN1_UNIVERSAL)
# define M_d2i_DISPLAYTEXT(a,pp,l) \
d2i_ASN1_type_bytes((ASN1_STRING **)a,pp,l, \
B_ASN1_DISPLAYTEXT)
# define M_ASN1_PRINTABLESTRING_new() (ASN1_PRINTABLESTRING *)\
ASN1_STRING_type_new(V_ASN1_PRINTABLESTRING)
# define M_ASN1_PRINTABLESTRING_free(a) ASN1_STRING_free((ASN1_STRING *)a)
# define M_i2d_ASN1_PRINTABLESTRING(a,pp) \
i2d_ASN1_bytes((ASN1_STRING *)a,pp,V_ASN1_PRINTABLESTRING,\
V_ASN1_UNIVERSAL)
# define M_d2i_ASN1_PRINTABLESTRING(a,pp,l) \
(ASN1_PRINTABLESTRING *)d2i_ASN1_type_bytes\
((ASN1_STRING **)a,pp,l,B_ASN1_PRINTABLESTRING)
# define M_ASN1_T61STRING_new() (ASN1_T61STRING *)\
ASN1_STRING_type_new(V_ASN1_T61STRING)
# define M_ASN1_T61STRING_free(a) ASN1_STRING_free((ASN1_STRING *)a)
# define M_i2d_ASN1_T61STRING(a,pp) \
i2d_ASN1_bytes((ASN1_STRING *)a,pp,V_ASN1_T61STRING,\
V_ASN1_UNIVERSAL)
# define M_d2i_ASN1_T61STRING(a,pp,l) \
(ASN1_T61STRING *)d2i_ASN1_type_bytes\
((ASN1_STRING **)a,pp,l,B_ASN1_T61STRING)
# define M_ASN1_IA5STRING_new() (ASN1_IA5STRING *)\
ASN1_STRING_type_new(V_ASN1_IA5STRING)
# define M_ASN1_IA5STRING_free(a) ASN1_STRING_free((ASN1_STRING *)a)
# define M_ASN1_IA5STRING_dup(a) \
(ASN1_IA5STRING *)ASN1_STRING_dup((const ASN1_STRING *)a)
# define M_i2d_ASN1_IA5STRING(a,pp) \
i2d_ASN1_bytes((ASN1_STRING *)a,pp,V_ASN1_IA5STRING,\
V_ASN1_UNIVERSAL)
# define M_d2i_ASN1_IA5STRING(a,pp,l) \
(ASN1_IA5STRING *)d2i_ASN1_type_bytes((ASN1_STRING **)a,pp,l,\
B_ASN1_IA5STRING)
# define M_ASN1_UTCTIME_new() (ASN1_UTCTIME *)\
ASN1_STRING_type_new(V_ASN1_UTCTIME)
# define M_ASN1_UTCTIME_free(a) ASN1_STRING_free((ASN1_STRING *)a)
# define M_ASN1_UTCTIME_dup(a) (ASN1_UTCTIME *)\
ASN1_STRING_dup((const ASN1_STRING *)a)
# define M_ASN1_GENERALIZEDTIME_new() (ASN1_GENERALIZEDTIME *)\
ASN1_STRING_type_new(V_ASN1_GENERALIZEDTIME)
# define M_ASN1_GENERALIZEDTIME_free(a) ASN1_STRING_free((ASN1_STRING *)a)
# define M_ASN1_GENERALIZEDTIME_dup(a) (ASN1_GENERALIZEDTIME *)ASN1_STRING_dup(\
(const ASN1_STRING *)a)
# define M_ASN1_TIME_new() (ASN1_TIME *)\
ASN1_STRING_type_new(V_ASN1_UTCTIME)
# define M_ASN1_TIME_free(a) ASN1_STRING_free((ASN1_STRING *)a)
# define M_ASN1_TIME_dup(a) (ASN1_TIME *)\
ASN1_STRING_dup((const ASN1_STRING *)a)
# define M_ASN1_GENERALSTRING_new() (ASN1_GENERALSTRING *)\
ASN1_STRING_type_new(V_ASN1_GENERALSTRING)
# define M_ASN1_GENERALSTRING_free(a) ASN1_STRING_free((ASN1_STRING *)a)
# define M_i2d_ASN1_GENERALSTRING(a,pp) \
i2d_ASN1_bytes((ASN1_STRING *)a,pp,V_ASN1_GENERALSTRING,\
V_ASN1_UNIVERSAL)
# define M_d2i_ASN1_GENERALSTRING(a,pp,l) \
(ASN1_GENERALSTRING *)d2i_ASN1_type_bytes\
((ASN1_STRING **)a,pp,l,B_ASN1_GENERALSTRING)
# define M_ASN1_UNIVERSALSTRING_new() (ASN1_UNIVERSALSTRING *)\
ASN1_STRING_type_new(V_ASN1_UNIVERSALSTRING)
# define M_ASN1_UNIVERSALSTRING_free(a) ASN1_STRING_free((ASN1_STRING *)a)
# define M_i2d_ASN1_UNIVERSALSTRING(a,pp) \
i2d_ASN1_bytes((ASN1_STRING *)a,pp,V_ASN1_UNIVERSALSTRING,\
V_ASN1_UNIVERSAL)
# define M_d2i_ASN1_UNIVERSALSTRING(a,pp,l) \
(ASN1_UNIVERSALSTRING *)d2i_ASN1_type_bytes\
((ASN1_STRING **)a,pp,l,B_ASN1_UNIVERSALSTRING)
# define M_ASN1_BMPSTRING_new() (ASN1_BMPSTRING *)\
ASN1_STRING_type_new(V_ASN1_BMPSTRING)
# define M_ASN1_BMPSTRING_free(a) ASN1_STRING_free((ASN1_STRING *)a)
# define M_i2d_ASN1_BMPSTRING(a,pp) \
i2d_ASN1_bytes((ASN1_STRING *)a,pp,V_ASN1_BMPSTRING,\
V_ASN1_UNIVERSAL)
# define M_d2i_ASN1_BMPSTRING(a,pp,l) \
(ASN1_BMPSTRING *)d2i_ASN1_type_bytes\
((ASN1_STRING **)a,pp,l,B_ASN1_BMPSTRING)
# define M_ASN1_VISIBLESTRING_new() (ASN1_VISIBLESTRING *)\
ASN1_STRING_type_new(V_ASN1_VISIBLESTRING)
# define M_ASN1_VISIBLESTRING_free(a) ASN1_STRING_free((ASN1_STRING *)a)
# define M_i2d_ASN1_VISIBLESTRING(a,pp) \
i2d_ASN1_bytes((ASN1_STRING *)a,pp,V_ASN1_VISIBLESTRING,\
V_ASN1_UNIVERSAL)
# define M_d2i_ASN1_VISIBLESTRING(a,pp,l) \
(ASN1_VISIBLESTRING *)d2i_ASN1_type_bytes\
((ASN1_STRING **)a,pp,l,B_ASN1_VISIBLESTRING)
# define M_ASN1_UTF8STRING_new() (ASN1_UTF8STRING *)\
ASN1_STRING_type_new(V_ASN1_UTF8STRING)
# define M_ASN1_UTF8STRING_free(a) ASN1_STRING_free((ASN1_STRING *)a)
# define M_i2d_ASN1_UTF8STRING(a,pp) \
i2d_ASN1_bytes((ASN1_STRING *)a,pp,V_ASN1_UTF8STRING,\
V_ASN1_UNIVERSAL)
# define M_d2i_ASN1_UTF8STRING(a,pp,l) \
(ASN1_UTF8STRING *)d2i_ASN1_type_bytes\
((ASN1_STRING **)a,pp,l,B_ASN1_UTF8STRING)
/* for the is_set parameter to i2d_ASN1_SET */
# define IS_SEQUENCE 0
# define IS_SET 1
DECLARE_ASN1_FUNCTIONS_fname(ASN1_TYPE, ASN1_ANY, ASN1_TYPE)
int ASN1_TYPE_get(ASN1_TYPE *a);
void ASN1_TYPE_set(ASN1_TYPE *a, int type, void *value);
int ASN1_TYPE_set1(ASN1_TYPE *a, int type, const void *value);
int ASN1_TYPE_cmp(const ASN1_TYPE *a, const ASN1_TYPE *b);
ASN1_OBJECT *ASN1_OBJECT_new(void);
void ASN1_OBJECT_free(ASN1_OBJECT *a);
int i2d_ASN1_OBJECT(ASN1_OBJECT *a, unsigned char **pp);
ASN1_OBJECT *c2i_ASN1_OBJECT(ASN1_OBJECT **a, const unsigned char **pp,
long length);
ASN1_OBJECT *d2i_ASN1_OBJECT(ASN1_OBJECT **a, const unsigned char **pp,
long length);
DECLARE_ASN1_ITEM(ASN1_OBJECT)
DECLARE_STACK_OF(ASN1_OBJECT)
DECLARE_ASN1_SET_OF(ASN1_OBJECT)
ASN1_STRING *ASN1_STRING_new(void);
void ASN1_STRING_free(ASN1_STRING *a);
void ASN1_STRING_clear_free(ASN1_STRING *a);
int ASN1_STRING_copy(ASN1_STRING *dst, const ASN1_STRING *str);
ASN1_STRING *ASN1_STRING_dup(const ASN1_STRING *a);
ASN1_STRING *ASN1_STRING_type_new(int type);
int ASN1_STRING_cmp(const ASN1_STRING *a, const ASN1_STRING *b);
/*
* Since this is used to store all sorts of things, via macros, for now,
* make its data void *
*/
int ASN1_STRING_set(ASN1_STRING *str, const void *data, int len);
void ASN1_STRING_set0(ASN1_STRING *str, void *data, int len);
int ASN1_STRING_length(const ASN1_STRING *x);
void ASN1_STRING_length_set(ASN1_STRING *x, int n);
int ASN1_STRING_type(ASN1_STRING *x);
unsigned char *ASN1_STRING_data(ASN1_STRING *x);
DECLARE_ASN1_FUNCTIONS(ASN1_BIT_STRING)
int i2c_ASN1_BIT_STRING(ASN1_BIT_STRING *a, unsigned char **pp);
ASN1_BIT_STRING *c2i_ASN1_BIT_STRING(ASN1_BIT_STRING **a,
const unsigned char **pp, long length);
int ASN1_BIT_STRING_set(ASN1_BIT_STRING *a, unsigned char *d, int length);
int ASN1_BIT_STRING_set_bit(ASN1_BIT_STRING *a, int n, int value);
int ASN1_BIT_STRING_get_bit(ASN1_BIT_STRING *a, int n);
int ASN1_BIT_STRING_check(ASN1_BIT_STRING *a,
unsigned char *flags, int flags_len);
# ifndef OPENSSL_NO_BIO
int ASN1_BIT_STRING_name_print(BIO *out, ASN1_BIT_STRING *bs,
BIT_STRING_BITNAME *tbl, int indent);
# endif
int ASN1_BIT_STRING_num_asc(char *name, BIT_STRING_BITNAME *tbl);
int ASN1_BIT_STRING_set_asc(ASN1_BIT_STRING *bs, char *name, int value,
BIT_STRING_BITNAME *tbl);
int i2d_ASN1_BOOLEAN(int a, unsigned char **pp);
int d2i_ASN1_BOOLEAN(int *a, const unsigned char **pp, long length);
DECLARE_ASN1_FUNCTIONS(ASN1_INTEGER)
int i2c_ASN1_INTEGER(ASN1_INTEGER *a, unsigned char **pp);
ASN1_INTEGER *c2i_ASN1_INTEGER(ASN1_INTEGER **a, const unsigned char **pp,
long length);
ASN1_INTEGER *d2i_ASN1_UINTEGER(ASN1_INTEGER **a, const unsigned char **pp,
long length);
ASN1_INTEGER *ASN1_INTEGER_dup(const ASN1_INTEGER *x);
int ASN1_INTEGER_cmp(const ASN1_INTEGER *x, const ASN1_INTEGER *y);
DECLARE_ASN1_FUNCTIONS(ASN1_ENUMERATED)
int ASN1_UTCTIME_check(const ASN1_UTCTIME *a);
ASN1_UTCTIME *ASN1_UTCTIME_set(ASN1_UTCTIME *s, time_t t);
ASN1_UTCTIME *ASN1_UTCTIME_adj(ASN1_UTCTIME *s, time_t t,
int offset_day, long offset_sec);
int ASN1_UTCTIME_set_string(ASN1_UTCTIME *s, const char *str);
int ASN1_UTCTIME_cmp_time_t(const ASN1_UTCTIME *s, time_t t);
# if 0
time_t ASN1_UTCTIME_get(const ASN1_UTCTIME *s);
# endif
int ASN1_GENERALIZEDTIME_check(const ASN1_GENERALIZEDTIME *a);
ASN1_GENERALIZEDTIME *ASN1_GENERALIZEDTIME_set(ASN1_GENERALIZEDTIME *s,
time_t t);
ASN1_GENERALIZEDTIME *ASN1_GENERALIZEDTIME_adj(ASN1_GENERALIZEDTIME *s,
time_t t, int offset_day,
long offset_sec);
int ASN1_GENERALIZEDTIME_set_string(ASN1_GENERALIZEDTIME *s, const char *str);
int ASN1_TIME_diff(int *pday, int *psec,
const ASN1_TIME *from, const ASN1_TIME *to);
DECLARE_ASN1_FUNCTIONS(ASN1_OCTET_STRING)
ASN1_OCTET_STRING *ASN1_OCTET_STRING_dup(const ASN1_OCTET_STRING *a);
int ASN1_OCTET_STRING_cmp(const ASN1_OCTET_STRING *a,
const ASN1_OCTET_STRING *b);
int ASN1_OCTET_STRING_set(ASN1_OCTET_STRING *str, const unsigned char *data,
int len);
DECLARE_ASN1_FUNCTIONS(ASN1_VISIBLESTRING)
DECLARE_ASN1_FUNCTIONS(ASN1_UNIVERSALSTRING)
DECLARE_ASN1_FUNCTIONS(ASN1_UTF8STRING)
DECLARE_ASN1_FUNCTIONS(ASN1_NULL)
DECLARE_ASN1_FUNCTIONS(ASN1_BMPSTRING)
int UTF8_getc(const unsigned char *str, int len, unsigned long *val);
int UTF8_putc(unsigned char *str, int len, unsigned long value);
DECLARE_ASN1_FUNCTIONS_name(ASN1_STRING, ASN1_PRINTABLE)
DECLARE_ASN1_FUNCTIONS_name(ASN1_STRING, DIRECTORYSTRING)
DECLARE_ASN1_FUNCTIONS_name(ASN1_STRING, DISPLAYTEXT)
DECLARE_ASN1_FUNCTIONS(ASN1_PRINTABLESTRING)
DECLARE_ASN1_FUNCTIONS(ASN1_T61STRING)
DECLARE_ASN1_FUNCTIONS(ASN1_IA5STRING)
DECLARE_ASN1_FUNCTIONS(ASN1_GENERALSTRING)
DECLARE_ASN1_FUNCTIONS(ASN1_UTCTIME)
DECLARE_ASN1_FUNCTIONS(ASN1_GENERALIZEDTIME)
DECLARE_ASN1_FUNCTIONS(ASN1_TIME)
DECLARE_ASN1_ITEM(ASN1_OCTET_STRING_NDEF)
ASN1_TIME *ASN1_TIME_set(ASN1_TIME *s, time_t t);
ASN1_TIME *ASN1_TIME_adj(ASN1_TIME *s, time_t t,
int offset_day, long offset_sec);
int ASN1_TIME_check(ASN1_TIME *t);
ASN1_GENERALIZEDTIME *ASN1_TIME_to_generalizedtime(ASN1_TIME *t, ASN1_GENERALIZEDTIME
**out);
int ASN1_TIME_set_string(ASN1_TIME *s, const char *str);
int i2d_ASN1_SET(STACK_OF(OPENSSL_BLOCK) *a, unsigned char **pp,
i2d_of_void *i2d, int ex_tag, int ex_class, int is_set);
STACK_OF(OPENSSL_BLOCK) *d2i_ASN1_SET(STACK_OF(OPENSSL_BLOCK) **a,
const unsigned char **pp,
long length, d2i_of_void *d2i,
void (*free_func) (OPENSSL_BLOCK),
int ex_tag, int ex_class);
# ifndef OPENSSL_NO_BIO
int i2a_ASN1_INTEGER(BIO *bp, ASN1_INTEGER *a);
int a2i_ASN1_INTEGER(BIO *bp, ASN1_INTEGER *bs, char *buf, int size);
int i2a_ASN1_ENUMERATED(BIO *bp, ASN1_ENUMERATED *a);
int a2i_ASN1_ENUMERATED(BIO *bp, ASN1_ENUMERATED *bs, char *buf, int size);
int i2a_ASN1_OBJECT(BIO *bp, ASN1_OBJECT *a);
int a2i_ASN1_STRING(BIO *bp, ASN1_STRING *bs, char *buf, int size);
int i2a_ASN1_STRING(BIO *bp, ASN1_STRING *a, int type);
# endif
int i2t_ASN1_OBJECT(char *buf, int buf_len, ASN1_OBJECT *a);
int a2d_ASN1_OBJECT(unsigned char *out, int olen, const char *buf, int num);
ASN1_OBJECT *ASN1_OBJECT_create(int nid, unsigned char *data, int len,
const char *sn, const char *ln);
int ASN1_INTEGER_set(ASN1_INTEGER *a, long v);
long ASN1_INTEGER_get(const ASN1_INTEGER *a);
ASN1_INTEGER *BN_to_ASN1_INTEGER(const BIGNUM *bn, ASN1_INTEGER *ai);
BIGNUM *ASN1_INTEGER_to_BN(const ASN1_INTEGER *ai, BIGNUM *bn);
int ASN1_ENUMERATED_set(ASN1_ENUMERATED *a, long v);
long ASN1_ENUMERATED_get(ASN1_ENUMERATED *a);
ASN1_ENUMERATED *BN_to_ASN1_ENUMERATED(BIGNUM *bn, ASN1_ENUMERATED *ai);
BIGNUM *ASN1_ENUMERATED_to_BN(ASN1_ENUMERATED *ai, BIGNUM *bn);
/* General */
/* given a string, return the correct type, max is the maximum length */
int ASN1_PRINTABLE_type(const unsigned char *s, int max);
int i2d_ASN1_bytes(ASN1_STRING *a, unsigned char **pp, int tag, int xclass);
ASN1_STRING *d2i_ASN1_bytes(ASN1_STRING **a, const unsigned char **pp,
long length, int Ptag, int Pclass);
unsigned long ASN1_tag2bit(int tag);
/* type is one or more of the B_ASN1_ values. */
ASN1_STRING *d2i_ASN1_type_bytes(ASN1_STRING **a, const unsigned char **pp,
long length, int type);
/* PARSING */
int asn1_Finish(ASN1_CTX *c);
int asn1_const_Finish(ASN1_const_CTX *c);
/* SPECIALS */
int ASN1_get_object(const unsigned char **pp, long *plength, int *ptag,
int *pclass, long omax);
int ASN1_check_infinite_end(unsigned char **p, long len);
int ASN1_const_check_infinite_end(const unsigned char **p, long len);
void ASN1_put_object(unsigned char **pp, int constructed, int length,
int tag, int xclass);
int ASN1_put_eoc(unsigned char **pp);
int ASN1_object_size(int constructed, int length, int tag);
/* Used to implement other functions */
void *ASN1_dup(i2d_of_void *i2d, d2i_of_void *d2i, void *x);
# define ASN1_dup_of(type,i2d,d2i,x) \
((type*)ASN1_dup(CHECKED_I2D_OF(type, i2d), \
CHECKED_D2I_OF(type, d2i), \
CHECKED_PTR_OF(type, x)))
# define ASN1_dup_of_const(type,i2d,d2i,x) \
((type*)ASN1_dup(CHECKED_I2D_OF(const type, i2d), \
CHECKED_D2I_OF(type, d2i), \
CHECKED_PTR_OF(const type, x)))
void *ASN1_item_dup(const ASN1_ITEM *it, void *x);
/* ASN1 alloc/free macros for when a type is only used internally */
# define M_ASN1_new_of(type) (type *)ASN1_item_new(ASN1_ITEM_rptr(type))
# define M_ASN1_free_of(x, type) \
ASN1_item_free(CHECKED_PTR_OF(type, x), ASN1_ITEM_rptr(type))
# ifndef OPENSSL_NO_FP_API
void *ASN1_d2i_fp(void *(*xnew) (void), d2i_of_void *d2i, FILE *in, void **x);
# define ASN1_d2i_fp_of(type,xnew,d2i,in,x) \
((type*)ASN1_d2i_fp(CHECKED_NEW_OF(type, xnew), \
CHECKED_D2I_OF(type, d2i), \
in, \
CHECKED_PPTR_OF(type, x)))
void *ASN1_item_d2i_fp(const ASN1_ITEM *it, FILE *in, void *x);
int ASN1_i2d_fp(i2d_of_void *i2d, FILE *out, void *x);
# define ASN1_i2d_fp_of(type,i2d,out,x) \
(ASN1_i2d_fp(CHECKED_I2D_OF(type, i2d), \
out, \
CHECKED_PTR_OF(type, x)))
# define ASN1_i2d_fp_of_const(type,i2d,out,x) \
(ASN1_i2d_fp(CHECKED_I2D_OF(const type, i2d), \
out, \
CHECKED_PTR_OF(const type, x)))
int ASN1_item_i2d_fp(const ASN1_ITEM *it, FILE *out, void *x);
int ASN1_STRING_print_ex_fp(FILE *fp, ASN1_STRING *str, unsigned long flags);
# endif
int ASN1_STRING_to_UTF8(unsigned char **out, ASN1_STRING *in);
# ifndef OPENSSL_NO_BIO
void *ASN1_d2i_bio(void *(*xnew) (void), d2i_of_void *d2i, BIO *in, void **x);
# define ASN1_d2i_bio_of(type,xnew,d2i,in,x) \
((type*)ASN1_d2i_bio( CHECKED_NEW_OF(type, xnew), \
CHECKED_D2I_OF(type, d2i), \
in, \
CHECKED_PPTR_OF(type, x)))
void *ASN1_item_d2i_bio(const ASN1_ITEM *it, BIO *in, void *x);
int ASN1_i2d_bio(i2d_of_void *i2d, BIO *out, unsigned char *x);
# define ASN1_i2d_bio_of(type,i2d,out,x) \
(ASN1_i2d_bio(CHECKED_I2D_OF(type, i2d), \
out, \
CHECKED_PTR_OF(type, x)))
# define ASN1_i2d_bio_of_const(type,i2d,out,x) \
(ASN1_i2d_bio(CHECKED_I2D_OF(const type, i2d), \
out, \
CHECKED_PTR_OF(const type, x)))
int ASN1_item_i2d_bio(const ASN1_ITEM *it, BIO *out, void *x);
int ASN1_UTCTIME_print(BIO *fp, const ASN1_UTCTIME *a);
int ASN1_GENERALIZEDTIME_print(BIO *fp, const ASN1_GENERALIZEDTIME *a);
int ASN1_TIME_print(BIO *fp, const ASN1_TIME *a);
int ASN1_STRING_print(BIO *bp, const ASN1_STRING *v);
int ASN1_STRING_print_ex(BIO *out, ASN1_STRING *str, unsigned long flags);
int ASN1_bn_print(BIO *bp, const char *number, const BIGNUM *num,
unsigned char *buf, int off);
int ASN1_parse(BIO *bp, const unsigned char *pp, long len, int indent);
int ASN1_parse_dump(BIO *bp, const unsigned char *pp, long len, int indent,
int dump);
# endif
const char *ASN1_tag2str(int tag);
/* Used to load and write netscape format cert */
DECLARE_ASN1_FUNCTIONS(NETSCAPE_X509)
int ASN1_UNIVERSALSTRING_to_string(ASN1_UNIVERSALSTRING *s);
int ASN1_TYPE_set_octetstring(ASN1_TYPE *a, unsigned char *data, int len);
int ASN1_TYPE_get_octetstring(ASN1_TYPE *a, unsigned char *data, int max_len);
int ASN1_TYPE_set_int_octetstring(ASN1_TYPE *a, long num,
unsigned char *data, int len);
int ASN1_TYPE_get_int_octetstring(ASN1_TYPE *a, long *num,
unsigned char *data, int max_len);
STACK_OF(OPENSSL_BLOCK) *ASN1_seq_unpack(const unsigned char *buf, int len,
d2i_of_void *d2i,
void (*free_func) (OPENSSL_BLOCK));
unsigned char *ASN1_seq_pack(STACK_OF(OPENSSL_BLOCK) *safes, i2d_of_void *i2d,
unsigned char **buf, int *len);
void *ASN1_unpack_string(ASN1_STRING *oct, d2i_of_void *d2i);
void *ASN1_item_unpack(ASN1_STRING *oct, const ASN1_ITEM *it);
ASN1_STRING *ASN1_pack_string(void *obj, i2d_of_void *i2d,
ASN1_OCTET_STRING **oct);
# define ASN1_pack_string_of(type,obj,i2d,oct) \
(ASN1_pack_string(CHECKED_PTR_OF(type, obj), \
CHECKED_I2D_OF(type, i2d), \
oct))
ASN1_STRING *ASN1_item_pack(void *obj, const ASN1_ITEM *it,
ASN1_OCTET_STRING **oct);
void ASN1_STRING_set_default_mask(unsigned long mask);
int ASN1_STRING_set_default_mask_asc(const char *p);
unsigned long ASN1_STRING_get_default_mask(void);
int ASN1_mbstring_copy(ASN1_STRING **out, const unsigned char *in, int len,
int inform, unsigned long mask);
int ASN1_mbstring_ncopy(ASN1_STRING **out, const unsigned char *in, int len,
int inform, unsigned long mask,
long minsize, long maxsize);
ASN1_STRING *ASN1_STRING_set_by_NID(ASN1_STRING **out,
const unsigned char *in, int inlen,
int inform, int nid);
ASN1_STRING_TABLE *ASN1_STRING_TABLE_get(int nid);
int ASN1_STRING_TABLE_add(int, long, long, unsigned long, unsigned long);
void ASN1_STRING_TABLE_cleanup(void);
/* ASN1 template functions */
/* Old API compatible functions */
ASN1_VALUE *ASN1_item_new(const ASN1_ITEM *it);
void ASN1_item_free(ASN1_VALUE *val, const ASN1_ITEM *it);
ASN1_VALUE *ASN1_item_d2i(ASN1_VALUE **val, const unsigned char **in,
long len, const ASN1_ITEM *it);
int ASN1_item_i2d(ASN1_VALUE *val, unsigned char **out, const ASN1_ITEM *it);
int ASN1_item_ndef_i2d(ASN1_VALUE *val, unsigned char **out,
const ASN1_ITEM *it);
void ASN1_add_oid_module(void);
ASN1_TYPE *ASN1_generate_nconf(char *str, CONF *nconf);
ASN1_TYPE *ASN1_generate_v3(char *str, X509V3_CTX *cnf);
/* ASN1 Print flags */
/* Indicate missing OPTIONAL fields */
# define ASN1_PCTX_FLAGS_SHOW_ABSENT 0x001
/* Mark start and end of SEQUENCE */
# define ASN1_PCTX_FLAGS_SHOW_SEQUENCE 0x002
/* Mark start and end of SEQUENCE/SET OF */
# define ASN1_PCTX_FLAGS_SHOW_SSOF 0x004
/* Show the ASN1 type of primitives */
# define ASN1_PCTX_FLAGS_SHOW_TYPE 0x008
/* Don't show ASN1 type of ANY */
# define ASN1_PCTX_FLAGS_NO_ANY_TYPE 0x010
/* Don't show ASN1 type of MSTRINGs */
# define ASN1_PCTX_FLAGS_NO_MSTRING_TYPE 0x020
/* Don't show field names in SEQUENCE */
# define ASN1_PCTX_FLAGS_NO_FIELD_NAME 0x040
/* Show structure names of each SEQUENCE field */
# define ASN1_PCTX_FLAGS_SHOW_FIELD_STRUCT_NAME 0x080
/* Don't show structure name even at top level */
# define ASN1_PCTX_FLAGS_NO_STRUCT_NAME 0x100
int ASN1_item_print(BIO *out, ASN1_VALUE *ifld, int indent,
const ASN1_ITEM *it, const ASN1_PCTX *pctx);
ASN1_PCTX *ASN1_PCTX_new(void);
void ASN1_PCTX_free(ASN1_PCTX *p);
unsigned long ASN1_PCTX_get_flags(ASN1_PCTX *p);
void ASN1_PCTX_set_flags(ASN1_PCTX *p, unsigned long flags);
unsigned long ASN1_PCTX_get_nm_flags(ASN1_PCTX *p);
void ASN1_PCTX_set_nm_flags(ASN1_PCTX *p, unsigned long flags);
unsigned long ASN1_PCTX_get_cert_flags(ASN1_PCTX *p);
void ASN1_PCTX_set_cert_flags(ASN1_PCTX *p, unsigned long flags);
unsigned long ASN1_PCTX_get_oid_flags(ASN1_PCTX *p);
void ASN1_PCTX_set_oid_flags(ASN1_PCTX *p, unsigned long flags);
unsigned long ASN1_PCTX_get_str_flags(ASN1_PCTX *p);
void ASN1_PCTX_set_str_flags(ASN1_PCTX *p, unsigned long flags);
BIO_METHOD *BIO_f_asn1(void);
BIO *BIO_new_NDEF(BIO *out, ASN1_VALUE *val, const ASN1_ITEM *it);
int i2d_ASN1_bio_stream(BIO *out, ASN1_VALUE *val, BIO *in, int flags,
const ASN1_ITEM *it);
int PEM_write_bio_ASN1_stream(BIO *out, ASN1_VALUE *val, BIO *in, int flags,
const char *hdr, const ASN1_ITEM *it);
int SMIME_write_ASN1(BIO *bio, ASN1_VALUE *val, BIO *data, int flags,
int ctype_nid, int econt_nid,
STACK_OF(X509_ALGOR) *mdalgs, const ASN1_ITEM *it);
ASN1_VALUE *SMIME_read_ASN1(BIO *bio, BIO **bcont, const ASN1_ITEM *it);
int SMIME_crlf_copy(BIO *in, BIO *out, int flags);
int SMIME_text(BIO *in, BIO *out);
/* BEGIN ERROR CODES */
/*
* The following lines are auto generated by the script mkerr.pl. Any changes
* made after this point may be overwritten when the script is next run.
*/
void ERR_load_ASN1_strings(void);
/* Error codes for the ASN1 functions. */
/* Function codes. */
# define ASN1_F_A2D_ASN1_OBJECT 100
# define ASN1_F_A2I_ASN1_ENUMERATED 101
# define ASN1_F_A2I_ASN1_INTEGER 102
# define ASN1_F_A2I_ASN1_STRING 103
# define ASN1_F_APPEND_EXP 176
# define ASN1_F_ASN1_BIT_STRING_SET_BIT 183
# define ASN1_F_ASN1_CB 177
# define ASN1_F_ASN1_CHECK_TLEN 104
# define ASN1_F_ASN1_COLLATE_PRIMITIVE 105
# define ASN1_F_ASN1_COLLECT 106
# define ASN1_F_ASN1_D2I_EX_PRIMITIVE 108
# define ASN1_F_ASN1_D2I_FP 109
# define ASN1_F_ASN1_D2I_READ_BIO 107
# define ASN1_F_ASN1_DIGEST 184
# define ASN1_F_ASN1_DO_ADB 110
# define ASN1_F_ASN1_DUP 111
# define ASN1_F_ASN1_ENUMERATED_SET 112
# define ASN1_F_ASN1_ENUMERATED_TO_BN 113
# define ASN1_F_ASN1_EX_C2I 204
# define ASN1_F_ASN1_FIND_END 190
# define ASN1_F_ASN1_GENERALIZEDTIME_ADJ 216
# define ASN1_F_ASN1_GENERALIZEDTIME_SET 185
# define ASN1_F_ASN1_GENERATE_V3 178
# define ASN1_F_ASN1_GET_OBJECT 114
# define ASN1_F_ASN1_HEADER_NEW 115
# define ASN1_F_ASN1_I2D_BIO 116
# define ASN1_F_ASN1_I2D_FP 117
# define ASN1_F_ASN1_INTEGER_SET 118
# define ASN1_F_ASN1_INTEGER_TO_BN 119
# define ASN1_F_ASN1_ITEM_D2I_FP 206
# define ASN1_F_ASN1_ITEM_DUP 191
# define ASN1_F_ASN1_ITEM_EX_COMBINE_NEW 121
# define ASN1_F_ASN1_ITEM_EX_D2I 120
# define ASN1_F_ASN1_ITEM_I2D_BIO 192
# define ASN1_F_ASN1_ITEM_I2D_FP 193
# define ASN1_F_ASN1_ITEM_PACK 198
# define ASN1_F_ASN1_ITEM_SIGN 195
# define ASN1_F_ASN1_ITEM_SIGN_CTX 220
# define ASN1_F_ASN1_ITEM_UNPACK 199
# define ASN1_F_ASN1_ITEM_VERIFY 197
# define ASN1_F_ASN1_MBSTRING_NCOPY 122
# define ASN1_F_ASN1_OBJECT_NEW 123
# define ASN1_F_ASN1_OUTPUT_DATA 214
# define ASN1_F_ASN1_PACK_STRING 124
# define ASN1_F_ASN1_PCTX_NEW 205
# define ASN1_F_ASN1_PKCS5_PBE_SET 125
# define ASN1_F_ASN1_SEQ_PACK 126
# define ASN1_F_ASN1_SEQ_UNPACK 127
# define ASN1_F_ASN1_SIGN 128
# define ASN1_F_ASN1_STR2TYPE 179
# define ASN1_F_ASN1_STRING_SET 186
# define ASN1_F_ASN1_STRING_TABLE_ADD 129
# define ASN1_F_ASN1_STRING_TYPE_NEW 130
# define ASN1_F_ASN1_TEMPLATE_EX_D2I 132
# define ASN1_F_ASN1_TEMPLATE_NEW 133
# define ASN1_F_ASN1_TEMPLATE_NOEXP_D2I 131
# define ASN1_F_ASN1_TIME_ADJ 217
# define ASN1_F_ASN1_TIME_SET 175
# define ASN1_F_ASN1_TYPE_GET_INT_OCTETSTRING 134
# define ASN1_F_ASN1_TYPE_GET_OCTETSTRING 135
# define ASN1_F_ASN1_UNPACK_STRING 136
# define ASN1_F_ASN1_UTCTIME_ADJ 218
# define ASN1_F_ASN1_UTCTIME_SET 187
# define ASN1_F_ASN1_VERIFY 137
# define ASN1_F_B64_READ_ASN1 209
# define ASN1_F_B64_WRITE_ASN1 210
# define ASN1_F_BIO_NEW_NDEF 208
# define ASN1_F_BITSTR_CB 180
# define ASN1_F_BN_TO_ASN1_ENUMERATED 138
# define ASN1_F_BN_TO_ASN1_INTEGER 139
# define ASN1_F_C2I_ASN1_BIT_STRING 189
# define ASN1_F_C2I_ASN1_INTEGER 194
# define ASN1_F_C2I_ASN1_OBJECT 196
# define ASN1_F_COLLECT_DATA 140
# define ASN1_F_D2I_ASN1_BIT_STRING 141
# define ASN1_F_D2I_ASN1_BOOLEAN 142
# define ASN1_F_D2I_ASN1_BYTES 143
# define ASN1_F_D2I_ASN1_GENERALIZEDTIME 144
# define ASN1_F_D2I_ASN1_HEADER 145
# define ASN1_F_D2I_ASN1_INTEGER 146
# define ASN1_F_D2I_ASN1_OBJECT 147
# define ASN1_F_D2I_ASN1_SET 148
# define ASN1_F_D2I_ASN1_TYPE_BYTES 149
# define ASN1_F_D2I_ASN1_UINTEGER 150
# define ASN1_F_D2I_ASN1_UTCTIME 151
# define ASN1_F_D2I_AUTOPRIVATEKEY 207
# define ASN1_F_D2I_NETSCAPE_RSA 152
# define ASN1_F_D2I_NETSCAPE_RSA_2 153
# define ASN1_F_D2I_PRIVATEKEY 154
# define ASN1_F_D2I_PUBLICKEY 155
# define ASN1_F_D2I_RSA_NET 200
# define ASN1_F_D2I_RSA_NET_2 201
# define ASN1_F_D2I_X509 156
# define ASN1_F_D2I_X509_CINF 157
# define ASN1_F_D2I_X509_PKEY 159
# define ASN1_F_I2D_ASN1_BIO_STREAM 211
# define ASN1_F_I2D_ASN1_SET 188
# define ASN1_F_I2D_ASN1_TIME 160
# define ASN1_F_I2D_DSA_PUBKEY 161
# define ASN1_F_I2D_EC_PUBKEY 181
# define ASN1_F_I2D_PRIVATEKEY 163
# define ASN1_F_I2D_PUBLICKEY 164
# define ASN1_F_I2D_RSA_NET 162
# define ASN1_F_I2D_RSA_PUBKEY 165
# define ASN1_F_LONG_C2I 166
# define ASN1_F_OID_MODULE_INIT 174
# define ASN1_F_PARSE_TAGGING 182
# define ASN1_F_PKCS5_PBE2_SET_IV 167
# define ASN1_F_PKCS5_PBE_SET 202
# define ASN1_F_PKCS5_PBE_SET0_ALGOR 215
# define ASN1_F_PKCS5_PBKDF2_SET 219
# define ASN1_F_SMIME_READ_ASN1 212
# define ASN1_F_SMIME_TEXT 213
# define ASN1_F_X509_CINF_NEW 168
# define ASN1_F_X509_CRL_ADD0_REVOKED 169
# define ASN1_F_X509_INFO_NEW 170
# define ASN1_F_X509_NAME_ENCODE 203
# define ASN1_F_X509_NAME_EX_D2I 158
# define ASN1_F_X509_NAME_EX_NEW 171
# define ASN1_F_X509_NEW 172
# define ASN1_F_X509_PKEY_NEW 173
/* Reason codes. */
# define ASN1_R_ADDING_OBJECT 171
# define ASN1_R_ASN1_PARSE_ERROR 203
# define ASN1_R_ASN1_SIG_PARSE_ERROR 204
# define ASN1_R_AUX_ERROR 100
# define ASN1_R_BAD_CLASS 101
# define ASN1_R_BAD_OBJECT_HEADER 102
# define ASN1_R_BAD_PASSWORD_READ 103
# define ASN1_R_BAD_TAG 104
# define ASN1_R_BMPSTRING_IS_WRONG_LENGTH 214
# define ASN1_R_BN_LIB 105
# define ASN1_R_BOOLEAN_IS_WRONG_LENGTH 106
# define ASN1_R_BUFFER_TOO_SMALL 107
# define ASN1_R_CIPHER_HAS_NO_OBJECT_IDENTIFIER 108
# define ASN1_R_CONTEXT_NOT_INITIALISED 217
# define ASN1_R_DATA_IS_WRONG 109
# define ASN1_R_DECODE_ERROR 110
# define ASN1_R_DECODING_ERROR 111
# define ASN1_R_DEPTH_EXCEEDED 174
# define ASN1_R_DIGEST_AND_KEY_TYPE_NOT_SUPPORTED 198
# define ASN1_R_ENCODE_ERROR 112
# define ASN1_R_ERROR_GETTING_TIME 173
# define ASN1_R_ERROR_LOADING_SECTION 172
# define ASN1_R_ERROR_PARSING_SET_ELEMENT 113
# define ASN1_R_ERROR_SETTING_CIPHER_PARAMS 114
# define ASN1_R_EXPECTING_AN_INTEGER 115
# define ASN1_R_EXPECTING_AN_OBJECT 116
# define ASN1_R_EXPECTING_A_BOOLEAN 117
# define ASN1_R_EXPECTING_A_TIME 118
# define ASN1_R_EXPLICIT_LENGTH_MISMATCH 119
# define ASN1_R_EXPLICIT_TAG_NOT_CONSTRUCTED 120
# define ASN1_R_FIELD_MISSING 121
# define ASN1_R_FIRST_NUM_TOO_LARGE 122
# define ASN1_R_HEADER_TOO_LONG 123
# define ASN1_R_ILLEGAL_BITSTRING_FORMAT 175
# define ASN1_R_ILLEGAL_BOOLEAN 176
# define ASN1_R_ILLEGAL_CHARACTERS 124
# define ASN1_R_ILLEGAL_FORMAT 177
# define ASN1_R_ILLEGAL_HEX 178
# define ASN1_R_ILLEGAL_IMPLICIT_TAG 179
# define ASN1_R_ILLEGAL_INTEGER 180
# define ASN1_R_ILLEGAL_NESTED_TAGGING 181
# define ASN1_R_ILLEGAL_NULL 125
# define ASN1_R_ILLEGAL_NULL_VALUE 182
# define ASN1_R_ILLEGAL_OBJECT 183
# define ASN1_R_ILLEGAL_OPTIONAL_ANY 126
# define ASN1_R_ILLEGAL_OPTIONS_ON_ITEM_TEMPLATE 170
# define ASN1_R_ILLEGAL_TAGGED_ANY 127
# define ASN1_R_ILLEGAL_TIME_VALUE 184
# define ASN1_R_INTEGER_NOT_ASCII_FORMAT 185
# define ASN1_R_INTEGER_TOO_LARGE_FOR_LONG 128
# define ASN1_R_INVALID_BIT_STRING_BITS_LEFT 220
# define ASN1_R_INVALID_BMPSTRING_LENGTH 129
# define ASN1_R_INVALID_DIGIT 130
# define ASN1_R_INVALID_MIME_TYPE 205
# define ASN1_R_INVALID_MODIFIER 186
# define ASN1_R_INVALID_NUMBER 187
# define ASN1_R_INVALID_OBJECT_ENCODING 216
# define ASN1_R_INVALID_SEPARATOR 131
# define ASN1_R_INVALID_TIME_FORMAT 132
# define ASN1_R_INVALID_UNIVERSALSTRING_LENGTH 133
# define ASN1_R_INVALID_UTF8STRING 134
# define ASN1_R_IV_TOO_LARGE 135
# define ASN1_R_LENGTH_ERROR 136
# define ASN1_R_LIST_ERROR 188
# define ASN1_R_MIME_NO_CONTENT_TYPE 206
# define ASN1_R_MIME_PARSE_ERROR 207
# define ASN1_R_MIME_SIG_PARSE_ERROR 208
# define ASN1_R_MISSING_EOC 137
# define ASN1_R_MISSING_SECOND_NUMBER 138
# define ASN1_R_MISSING_VALUE 189
# define ASN1_R_MSTRING_NOT_UNIVERSAL 139
# define ASN1_R_MSTRING_WRONG_TAG 140
# define ASN1_R_NESTED_ASN1_STRING 197
+# define ASN1_R_NESTED_TOO_DEEP 219
# define ASN1_R_NON_HEX_CHARACTERS 141
# define ASN1_R_NOT_ASCII_FORMAT 190
# define ASN1_R_NOT_ENOUGH_DATA 142
# define ASN1_R_NO_CONTENT_TYPE 209
# define ASN1_R_NO_DEFAULT_DIGEST 201
# define ASN1_R_NO_MATCHING_CHOICE_TYPE 143
# define ASN1_R_NO_MULTIPART_BODY_FAILURE 210
# define ASN1_R_NO_MULTIPART_BOUNDARY 211
# define ASN1_R_NO_SIG_CONTENT_TYPE 212
# define ASN1_R_NULL_IS_WRONG_LENGTH 144
# define ASN1_R_OBJECT_NOT_ASCII_FORMAT 191
# define ASN1_R_ODD_NUMBER_OF_CHARS 145
# define ASN1_R_PRIVATE_KEY_HEADER_MISSING 146
# define ASN1_R_SECOND_NUMBER_TOO_LARGE 147
# define ASN1_R_SEQUENCE_LENGTH_MISMATCH 148
# define ASN1_R_SEQUENCE_NOT_CONSTRUCTED 149
# define ASN1_R_SEQUENCE_OR_SET_NEEDS_CONFIG 192
# define ASN1_R_SHORT_LINE 150
# define ASN1_R_SIG_INVALID_MIME_TYPE 213
# define ASN1_R_STREAMING_NOT_SUPPORTED 202
# define ASN1_R_STRING_TOO_LONG 151
# define ASN1_R_STRING_TOO_SHORT 152
# define ASN1_R_TAG_VALUE_TOO_HIGH 153
# define ASN1_R_THE_ASN1_OBJECT_IDENTIFIER_IS_NOT_KNOWN_FOR_THIS_MD 154
# define ASN1_R_TIME_NOT_ASCII_FORMAT 193
# define ASN1_R_TOO_LONG 155
# define ASN1_R_TYPE_NOT_CONSTRUCTED 156
# define ASN1_R_TYPE_NOT_PRIMITIVE 218
# define ASN1_R_UNABLE_TO_DECODE_RSA_KEY 157
# define ASN1_R_UNABLE_TO_DECODE_RSA_PRIVATE_KEY 158
# define ASN1_R_UNEXPECTED_EOC 159
# define ASN1_R_UNIVERSALSTRING_IS_WRONG_LENGTH 215
# define ASN1_R_UNKNOWN_FORMAT 160
# define ASN1_R_UNKNOWN_MESSAGE_DIGEST_ALGORITHM 161
# define ASN1_R_UNKNOWN_OBJECT_TYPE 162
# define ASN1_R_UNKNOWN_PUBLIC_KEY_TYPE 163
# define ASN1_R_UNKNOWN_SIGNATURE_ALGORITHM 199
# define ASN1_R_UNKNOWN_TAG 194
# define ASN1_R_UNKOWN_FORMAT 195
# define ASN1_R_UNSUPPORTED_ANY_DEFINED_BY_TYPE 164
# define ASN1_R_UNSUPPORTED_CIPHER 165
# define ASN1_R_UNSUPPORTED_ENCRYPTION_ALGORITHM 166
# define ASN1_R_UNSUPPORTED_PUBLIC_KEY_TYPE 167
# define ASN1_R_UNSUPPORTED_TYPE 196
# define ASN1_R_WRONG_PUBLIC_KEY_TYPE 200
# define ASN1_R_WRONG_TAG 168
# define ASN1_R_WRONG_TYPE 169
#ifdef __cplusplus
}
#endif
#endif
diff --git a/crypto/asn1/asn1_err.c b/crypto/asn1/asn1_err.c
index fd4ac8d9db80..cfc1512f9d07 100644
--- a/crypto/asn1/asn1_err.c
+++ b/crypto/asn1/asn1_err.c
@@ -1,354 +1,355 @@
/* crypto/asn1/asn1_err.c */
/* ====================================================================
- * Copyright (c) 1999-2014 The OpenSSL Project. All rights reserved.
+ * Copyright (c) 1999-2018 The OpenSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* openssl-core@OpenSSL.org.
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*
* This product includes cryptographic software written by Eric Young
* (eay@cryptsoft.com). This product includes software written by Tim
* Hudson (tjh@cryptsoft.com).
*
*/
/*
* NOTE: this file was auto generated by the mkerr.pl script: any changes
* made to it will be overwritten when the script next updates this file,
* only reason strings will be preserved.
*/
#include <stdio.h>
#include <openssl/err.h>
#include <openssl/asn1.h>
/* BEGIN ERROR CODES */
#ifndef OPENSSL_NO_ERR
# define ERR_FUNC(func) ERR_PACK(ERR_LIB_ASN1,func,0)
# define ERR_REASON(reason) ERR_PACK(ERR_LIB_ASN1,0,reason)
static ERR_STRING_DATA ASN1_str_functs[] = {
{ERR_FUNC(ASN1_F_A2D_ASN1_OBJECT), "a2d_ASN1_OBJECT"},
{ERR_FUNC(ASN1_F_A2I_ASN1_ENUMERATED), "a2i_ASN1_ENUMERATED"},
{ERR_FUNC(ASN1_F_A2I_ASN1_INTEGER), "a2i_ASN1_INTEGER"},
{ERR_FUNC(ASN1_F_A2I_ASN1_STRING), "a2i_ASN1_STRING"},
{ERR_FUNC(ASN1_F_APPEND_EXP), "APPEND_EXP"},
{ERR_FUNC(ASN1_F_ASN1_BIT_STRING_SET_BIT), "ASN1_BIT_STRING_set_bit"},
{ERR_FUNC(ASN1_F_ASN1_CB), "ASN1_CB"},
{ERR_FUNC(ASN1_F_ASN1_CHECK_TLEN), "ASN1_CHECK_TLEN"},
{ERR_FUNC(ASN1_F_ASN1_COLLATE_PRIMITIVE), "ASN1_COLLATE_PRIMITIVE"},
{ERR_FUNC(ASN1_F_ASN1_COLLECT), "ASN1_COLLECT"},
{ERR_FUNC(ASN1_F_ASN1_D2I_EX_PRIMITIVE), "ASN1_D2I_EX_PRIMITIVE"},
{ERR_FUNC(ASN1_F_ASN1_D2I_FP), "ASN1_d2i_fp"},
{ERR_FUNC(ASN1_F_ASN1_D2I_READ_BIO), "ASN1_D2I_READ_BIO"},
{ERR_FUNC(ASN1_F_ASN1_DIGEST), "ASN1_digest"},
{ERR_FUNC(ASN1_F_ASN1_DO_ADB), "ASN1_DO_ADB"},
{ERR_FUNC(ASN1_F_ASN1_DUP), "ASN1_dup"},
{ERR_FUNC(ASN1_F_ASN1_ENUMERATED_SET), "ASN1_ENUMERATED_set"},
{ERR_FUNC(ASN1_F_ASN1_ENUMERATED_TO_BN), "ASN1_ENUMERATED_to_BN"},
{ERR_FUNC(ASN1_F_ASN1_EX_C2I), "ASN1_EX_C2I"},
{ERR_FUNC(ASN1_F_ASN1_FIND_END), "ASN1_FIND_END"},
{ERR_FUNC(ASN1_F_ASN1_GENERALIZEDTIME_ADJ), "ASN1_GENERALIZEDTIME_adj"},
{ERR_FUNC(ASN1_F_ASN1_GENERALIZEDTIME_SET), "ASN1_GENERALIZEDTIME_set"},
{ERR_FUNC(ASN1_F_ASN1_GENERATE_V3), "ASN1_generate_v3"},
{ERR_FUNC(ASN1_F_ASN1_GET_OBJECT), "ASN1_get_object"},
{ERR_FUNC(ASN1_F_ASN1_HEADER_NEW), "ASN1_HEADER_NEW"},
{ERR_FUNC(ASN1_F_ASN1_I2D_BIO), "ASN1_i2d_bio"},
{ERR_FUNC(ASN1_F_ASN1_I2D_FP), "ASN1_i2d_fp"},
{ERR_FUNC(ASN1_F_ASN1_INTEGER_SET), "ASN1_INTEGER_set"},
{ERR_FUNC(ASN1_F_ASN1_INTEGER_TO_BN), "ASN1_INTEGER_to_BN"},
{ERR_FUNC(ASN1_F_ASN1_ITEM_D2I_FP), "ASN1_item_d2i_fp"},
{ERR_FUNC(ASN1_F_ASN1_ITEM_DUP), "ASN1_item_dup"},
{ERR_FUNC(ASN1_F_ASN1_ITEM_EX_COMBINE_NEW), "ASN1_ITEM_EX_COMBINE_NEW"},
{ERR_FUNC(ASN1_F_ASN1_ITEM_EX_D2I), "ASN1_ITEM_EX_D2I"},
{ERR_FUNC(ASN1_F_ASN1_ITEM_I2D_BIO), "ASN1_item_i2d_bio"},
{ERR_FUNC(ASN1_F_ASN1_ITEM_I2D_FP), "ASN1_item_i2d_fp"},
{ERR_FUNC(ASN1_F_ASN1_ITEM_PACK), "ASN1_item_pack"},
{ERR_FUNC(ASN1_F_ASN1_ITEM_SIGN), "ASN1_item_sign"},
{ERR_FUNC(ASN1_F_ASN1_ITEM_SIGN_CTX), "ASN1_item_sign_ctx"},
{ERR_FUNC(ASN1_F_ASN1_ITEM_UNPACK), "ASN1_item_unpack"},
{ERR_FUNC(ASN1_F_ASN1_ITEM_VERIFY), "ASN1_item_verify"},
{ERR_FUNC(ASN1_F_ASN1_MBSTRING_NCOPY), "ASN1_mbstring_ncopy"},
{ERR_FUNC(ASN1_F_ASN1_OBJECT_NEW), "ASN1_OBJECT_new"},
{ERR_FUNC(ASN1_F_ASN1_OUTPUT_DATA), "ASN1_OUTPUT_DATA"},
{ERR_FUNC(ASN1_F_ASN1_PACK_STRING), "ASN1_pack_string"},
{ERR_FUNC(ASN1_F_ASN1_PCTX_NEW), "ASN1_PCTX_new"},
{ERR_FUNC(ASN1_F_ASN1_PKCS5_PBE_SET), "ASN1_PKCS5_PBE_SET"},
{ERR_FUNC(ASN1_F_ASN1_SEQ_PACK), "ASN1_seq_pack"},
{ERR_FUNC(ASN1_F_ASN1_SEQ_UNPACK), "ASN1_seq_unpack"},
{ERR_FUNC(ASN1_F_ASN1_SIGN), "ASN1_sign"},
{ERR_FUNC(ASN1_F_ASN1_STR2TYPE), "ASN1_STR2TYPE"},
{ERR_FUNC(ASN1_F_ASN1_STRING_SET), "ASN1_STRING_set"},
{ERR_FUNC(ASN1_F_ASN1_STRING_TABLE_ADD), "ASN1_STRING_TABLE_add"},
{ERR_FUNC(ASN1_F_ASN1_STRING_TYPE_NEW), "ASN1_STRING_type_new"},
{ERR_FUNC(ASN1_F_ASN1_TEMPLATE_EX_D2I), "ASN1_TEMPLATE_EX_D2I"},
{ERR_FUNC(ASN1_F_ASN1_TEMPLATE_NEW), "ASN1_TEMPLATE_NEW"},
{ERR_FUNC(ASN1_F_ASN1_TEMPLATE_NOEXP_D2I), "ASN1_TEMPLATE_NOEXP_D2I"},
{ERR_FUNC(ASN1_F_ASN1_TIME_ADJ), "ASN1_TIME_adj"},
{ERR_FUNC(ASN1_F_ASN1_TIME_SET), "ASN1_TIME_set"},
{ERR_FUNC(ASN1_F_ASN1_TYPE_GET_INT_OCTETSTRING),
"ASN1_TYPE_get_int_octetstring"},
{ERR_FUNC(ASN1_F_ASN1_TYPE_GET_OCTETSTRING), "ASN1_TYPE_get_octetstring"},
{ERR_FUNC(ASN1_F_ASN1_UNPACK_STRING), "ASN1_unpack_string"},
{ERR_FUNC(ASN1_F_ASN1_UTCTIME_ADJ), "ASN1_UTCTIME_adj"},
{ERR_FUNC(ASN1_F_ASN1_UTCTIME_SET), "ASN1_UTCTIME_set"},
{ERR_FUNC(ASN1_F_ASN1_VERIFY), "ASN1_verify"},
{ERR_FUNC(ASN1_F_B64_READ_ASN1), "B64_READ_ASN1"},
{ERR_FUNC(ASN1_F_B64_WRITE_ASN1), "B64_WRITE_ASN1"},
{ERR_FUNC(ASN1_F_BIO_NEW_NDEF), "BIO_new_NDEF"},
{ERR_FUNC(ASN1_F_BITSTR_CB), "BITSTR_CB"},
{ERR_FUNC(ASN1_F_BN_TO_ASN1_ENUMERATED), "BN_to_ASN1_ENUMERATED"},
{ERR_FUNC(ASN1_F_BN_TO_ASN1_INTEGER), "BN_to_ASN1_INTEGER"},
{ERR_FUNC(ASN1_F_C2I_ASN1_BIT_STRING), "c2i_ASN1_BIT_STRING"},
{ERR_FUNC(ASN1_F_C2I_ASN1_INTEGER), "c2i_ASN1_INTEGER"},
{ERR_FUNC(ASN1_F_C2I_ASN1_OBJECT), "c2i_ASN1_OBJECT"},
{ERR_FUNC(ASN1_F_COLLECT_DATA), "COLLECT_DATA"},
{ERR_FUNC(ASN1_F_D2I_ASN1_BIT_STRING), "D2I_ASN1_BIT_STRING"},
{ERR_FUNC(ASN1_F_D2I_ASN1_BOOLEAN), "d2i_ASN1_BOOLEAN"},
{ERR_FUNC(ASN1_F_D2I_ASN1_BYTES), "d2i_ASN1_bytes"},
{ERR_FUNC(ASN1_F_D2I_ASN1_GENERALIZEDTIME), "D2I_ASN1_GENERALIZEDTIME"},
{ERR_FUNC(ASN1_F_D2I_ASN1_HEADER), "D2I_ASN1_HEADER"},
{ERR_FUNC(ASN1_F_D2I_ASN1_INTEGER), "D2I_ASN1_INTEGER"},
{ERR_FUNC(ASN1_F_D2I_ASN1_OBJECT), "d2i_ASN1_OBJECT"},
{ERR_FUNC(ASN1_F_D2I_ASN1_SET), "d2i_ASN1_SET"},
{ERR_FUNC(ASN1_F_D2I_ASN1_TYPE_BYTES), "d2i_ASN1_type_bytes"},
{ERR_FUNC(ASN1_F_D2I_ASN1_UINTEGER), "d2i_ASN1_UINTEGER"},
{ERR_FUNC(ASN1_F_D2I_ASN1_UTCTIME), "D2I_ASN1_UTCTIME"},
{ERR_FUNC(ASN1_F_D2I_AUTOPRIVATEKEY), "d2i_AutoPrivateKey"},
{ERR_FUNC(ASN1_F_D2I_NETSCAPE_RSA), "d2i_Netscape_RSA"},
{ERR_FUNC(ASN1_F_D2I_NETSCAPE_RSA_2), "D2I_NETSCAPE_RSA_2"},
{ERR_FUNC(ASN1_F_D2I_PRIVATEKEY), "d2i_PrivateKey"},
{ERR_FUNC(ASN1_F_D2I_PUBLICKEY), "d2i_PublicKey"},
{ERR_FUNC(ASN1_F_D2I_RSA_NET), "d2i_RSA_NET"},
{ERR_FUNC(ASN1_F_D2I_RSA_NET_2), "D2I_RSA_NET_2"},
{ERR_FUNC(ASN1_F_D2I_X509), "D2I_X509"},
{ERR_FUNC(ASN1_F_D2I_X509_CINF), "D2I_X509_CINF"},
{ERR_FUNC(ASN1_F_D2I_X509_PKEY), "d2i_X509_PKEY"},
{ERR_FUNC(ASN1_F_I2D_ASN1_BIO_STREAM), "i2d_ASN1_bio_stream"},
{ERR_FUNC(ASN1_F_I2D_ASN1_SET), "i2d_ASN1_SET"},
{ERR_FUNC(ASN1_F_I2D_ASN1_TIME), "I2D_ASN1_TIME"},
{ERR_FUNC(ASN1_F_I2D_DSA_PUBKEY), "i2d_DSA_PUBKEY"},
{ERR_FUNC(ASN1_F_I2D_EC_PUBKEY), "i2d_EC_PUBKEY"},
{ERR_FUNC(ASN1_F_I2D_PRIVATEKEY), "i2d_PrivateKey"},
{ERR_FUNC(ASN1_F_I2D_PUBLICKEY), "i2d_PublicKey"},
{ERR_FUNC(ASN1_F_I2D_RSA_NET), "i2d_RSA_NET"},
{ERR_FUNC(ASN1_F_I2D_RSA_PUBKEY), "i2d_RSA_PUBKEY"},
{ERR_FUNC(ASN1_F_LONG_C2I), "LONG_C2I"},
{ERR_FUNC(ASN1_F_OID_MODULE_INIT), "OID_MODULE_INIT"},
{ERR_FUNC(ASN1_F_PARSE_TAGGING), "PARSE_TAGGING"},
{ERR_FUNC(ASN1_F_PKCS5_PBE2_SET_IV), "PKCS5_pbe2_set_iv"},
{ERR_FUNC(ASN1_F_PKCS5_PBE_SET), "PKCS5_pbe_set"},
{ERR_FUNC(ASN1_F_PKCS5_PBE_SET0_ALGOR), "PKCS5_pbe_set0_algor"},
{ERR_FUNC(ASN1_F_PKCS5_PBKDF2_SET), "PKCS5_pbkdf2_set"},
{ERR_FUNC(ASN1_F_SMIME_READ_ASN1), "SMIME_read_ASN1"},
{ERR_FUNC(ASN1_F_SMIME_TEXT), "SMIME_text"},
{ERR_FUNC(ASN1_F_X509_CINF_NEW), "X509_CINF_NEW"},
{ERR_FUNC(ASN1_F_X509_CRL_ADD0_REVOKED), "X509_CRL_add0_revoked"},
{ERR_FUNC(ASN1_F_X509_INFO_NEW), "X509_INFO_new"},
{ERR_FUNC(ASN1_F_X509_NAME_ENCODE), "X509_NAME_ENCODE"},
{ERR_FUNC(ASN1_F_X509_NAME_EX_D2I), "X509_NAME_EX_D2I"},
{ERR_FUNC(ASN1_F_X509_NAME_EX_NEW), "X509_NAME_EX_NEW"},
{ERR_FUNC(ASN1_F_X509_NEW), "X509_NEW"},
{ERR_FUNC(ASN1_F_X509_PKEY_NEW), "X509_PKEY_new"},
{0, NULL}
};
static ERR_STRING_DATA ASN1_str_reasons[] = {
{ERR_REASON(ASN1_R_ADDING_OBJECT), "adding object"},
{ERR_REASON(ASN1_R_ASN1_PARSE_ERROR), "asn1 parse error"},
{ERR_REASON(ASN1_R_ASN1_SIG_PARSE_ERROR), "asn1 sig parse error"},
{ERR_REASON(ASN1_R_AUX_ERROR), "aux error"},
{ERR_REASON(ASN1_R_BAD_CLASS), "bad class"},
{ERR_REASON(ASN1_R_BAD_OBJECT_HEADER), "bad object header"},
{ERR_REASON(ASN1_R_BAD_PASSWORD_READ), "bad password read"},
{ERR_REASON(ASN1_R_BAD_TAG), "bad tag"},
{ERR_REASON(ASN1_R_BMPSTRING_IS_WRONG_LENGTH),
"bmpstring is wrong length"},
{ERR_REASON(ASN1_R_BN_LIB), "bn lib"},
{ERR_REASON(ASN1_R_BOOLEAN_IS_WRONG_LENGTH), "boolean is wrong length"},
{ERR_REASON(ASN1_R_BUFFER_TOO_SMALL), "buffer too small"},
{ERR_REASON(ASN1_R_CIPHER_HAS_NO_OBJECT_IDENTIFIER),
"cipher has no object identifier"},
{ERR_REASON(ASN1_R_CONTEXT_NOT_INITIALISED), "context not initialised"},
{ERR_REASON(ASN1_R_DATA_IS_WRONG), "data is wrong"},
{ERR_REASON(ASN1_R_DECODE_ERROR), "decode error"},
{ERR_REASON(ASN1_R_DECODING_ERROR), "decoding error"},
{ERR_REASON(ASN1_R_DEPTH_EXCEEDED), "depth exceeded"},
{ERR_REASON(ASN1_R_DIGEST_AND_KEY_TYPE_NOT_SUPPORTED),
"digest and key type not supported"},
{ERR_REASON(ASN1_R_ENCODE_ERROR), "encode error"},
{ERR_REASON(ASN1_R_ERROR_GETTING_TIME), "error getting time"},
{ERR_REASON(ASN1_R_ERROR_LOADING_SECTION), "error loading section"},
{ERR_REASON(ASN1_R_ERROR_PARSING_SET_ELEMENT),
"error parsing set element"},
{ERR_REASON(ASN1_R_ERROR_SETTING_CIPHER_PARAMS),
"error setting cipher params"},
{ERR_REASON(ASN1_R_EXPECTING_AN_INTEGER), "expecting an integer"},
{ERR_REASON(ASN1_R_EXPECTING_AN_OBJECT), "expecting an object"},
{ERR_REASON(ASN1_R_EXPECTING_A_BOOLEAN), "expecting a boolean"},
{ERR_REASON(ASN1_R_EXPECTING_A_TIME), "expecting a time"},
{ERR_REASON(ASN1_R_EXPLICIT_LENGTH_MISMATCH), "explicit length mismatch"},
{ERR_REASON(ASN1_R_EXPLICIT_TAG_NOT_CONSTRUCTED),
"explicit tag not constructed"},
{ERR_REASON(ASN1_R_FIELD_MISSING), "field missing"},
{ERR_REASON(ASN1_R_FIRST_NUM_TOO_LARGE), "first num too large"},
{ERR_REASON(ASN1_R_HEADER_TOO_LONG), "header too long"},
{ERR_REASON(ASN1_R_ILLEGAL_BITSTRING_FORMAT), "illegal bitstring format"},
{ERR_REASON(ASN1_R_ILLEGAL_BOOLEAN), "illegal boolean"},
{ERR_REASON(ASN1_R_ILLEGAL_CHARACTERS), "illegal characters"},
{ERR_REASON(ASN1_R_ILLEGAL_FORMAT), "illegal format"},
{ERR_REASON(ASN1_R_ILLEGAL_HEX), "illegal hex"},
{ERR_REASON(ASN1_R_ILLEGAL_IMPLICIT_TAG), "illegal implicit tag"},
{ERR_REASON(ASN1_R_ILLEGAL_INTEGER), "illegal integer"},
{ERR_REASON(ASN1_R_ILLEGAL_NESTED_TAGGING), "illegal nested tagging"},
{ERR_REASON(ASN1_R_ILLEGAL_NULL), "illegal null"},
{ERR_REASON(ASN1_R_ILLEGAL_NULL_VALUE), "illegal null value"},
{ERR_REASON(ASN1_R_ILLEGAL_OBJECT), "illegal object"},
{ERR_REASON(ASN1_R_ILLEGAL_OPTIONAL_ANY), "illegal optional any"},
{ERR_REASON(ASN1_R_ILLEGAL_OPTIONS_ON_ITEM_TEMPLATE),
"illegal options on item template"},
{ERR_REASON(ASN1_R_ILLEGAL_TAGGED_ANY), "illegal tagged any"},
{ERR_REASON(ASN1_R_ILLEGAL_TIME_VALUE), "illegal time value"},
{ERR_REASON(ASN1_R_INTEGER_NOT_ASCII_FORMAT), "integer not ascii format"},
{ERR_REASON(ASN1_R_INTEGER_TOO_LARGE_FOR_LONG),
"integer too large for long"},
{ERR_REASON(ASN1_R_INVALID_BIT_STRING_BITS_LEFT),
"invalid bit string bits left"},
{ERR_REASON(ASN1_R_INVALID_BMPSTRING_LENGTH), "invalid bmpstring length"},
{ERR_REASON(ASN1_R_INVALID_DIGIT), "invalid digit"},
{ERR_REASON(ASN1_R_INVALID_MIME_TYPE), "invalid mime type"},
{ERR_REASON(ASN1_R_INVALID_MODIFIER), "invalid modifier"},
{ERR_REASON(ASN1_R_INVALID_NUMBER), "invalid number"},
{ERR_REASON(ASN1_R_INVALID_OBJECT_ENCODING), "invalid object encoding"},
{ERR_REASON(ASN1_R_INVALID_SEPARATOR), "invalid separator"},
{ERR_REASON(ASN1_R_INVALID_TIME_FORMAT), "invalid time format"},
{ERR_REASON(ASN1_R_INVALID_UNIVERSALSTRING_LENGTH),
"invalid universalstring length"},
{ERR_REASON(ASN1_R_INVALID_UTF8STRING), "invalid utf8string"},
{ERR_REASON(ASN1_R_IV_TOO_LARGE), "iv too large"},
{ERR_REASON(ASN1_R_LENGTH_ERROR), "length error"},
{ERR_REASON(ASN1_R_LIST_ERROR), "list error"},
{ERR_REASON(ASN1_R_MIME_NO_CONTENT_TYPE), "mime no content type"},
{ERR_REASON(ASN1_R_MIME_PARSE_ERROR), "mime parse error"},
{ERR_REASON(ASN1_R_MIME_SIG_PARSE_ERROR), "mime sig parse error"},
{ERR_REASON(ASN1_R_MISSING_EOC), "missing eoc"},
{ERR_REASON(ASN1_R_MISSING_SECOND_NUMBER), "missing second number"},
{ERR_REASON(ASN1_R_MISSING_VALUE), "missing value"},
{ERR_REASON(ASN1_R_MSTRING_NOT_UNIVERSAL), "mstring not universal"},
{ERR_REASON(ASN1_R_MSTRING_WRONG_TAG), "mstring wrong tag"},
{ERR_REASON(ASN1_R_NESTED_ASN1_STRING), "nested asn1 string"},
+ {ERR_REASON(ASN1_R_NESTED_TOO_DEEP), "nested too deep"},
{ERR_REASON(ASN1_R_NON_HEX_CHARACTERS), "non hex characters"},
{ERR_REASON(ASN1_R_NOT_ASCII_FORMAT), "not ascii format"},
{ERR_REASON(ASN1_R_NOT_ENOUGH_DATA), "not enough data"},
{ERR_REASON(ASN1_R_NO_CONTENT_TYPE), "no content type"},
{ERR_REASON(ASN1_R_NO_DEFAULT_DIGEST), "no default digest"},
{ERR_REASON(ASN1_R_NO_MATCHING_CHOICE_TYPE), "no matching choice type"},
{ERR_REASON(ASN1_R_NO_MULTIPART_BODY_FAILURE),
"no multipart body failure"},
{ERR_REASON(ASN1_R_NO_MULTIPART_BOUNDARY), "no multipart boundary"},
{ERR_REASON(ASN1_R_NO_SIG_CONTENT_TYPE), "no sig content type"},
{ERR_REASON(ASN1_R_NULL_IS_WRONG_LENGTH), "null is wrong length"},
{ERR_REASON(ASN1_R_OBJECT_NOT_ASCII_FORMAT), "object not ascii format"},
{ERR_REASON(ASN1_R_ODD_NUMBER_OF_CHARS), "odd number of chars"},
{ERR_REASON(ASN1_R_PRIVATE_KEY_HEADER_MISSING),
"private key header missing"},
{ERR_REASON(ASN1_R_SECOND_NUMBER_TOO_LARGE), "second number too large"},
{ERR_REASON(ASN1_R_SEQUENCE_LENGTH_MISMATCH), "sequence length mismatch"},
{ERR_REASON(ASN1_R_SEQUENCE_NOT_CONSTRUCTED), "sequence not constructed"},
{ERR_REASON(ASN1_R_SEQUENCE_OR_SET_NEEDS_CONFIG),
"sequence or set needs config"},
{ERR_REASON(ASN1_R_SHORT_LINE), "short line"},
{ERR_REASON(ASN1_R_SIG_INVALID_MIME_TYPE), "sig invalid mime type"},
{ERR_REASON(ASN1_R_STREAMING_NOT_SUPPORTED), "streaming not supported"},
{ERR_REASON(ASN1_R_STRING_TOO_LONG), "string too long"},
{ERR_REASON(ASN1_R_STRING_TOO_SHORT), "string too short"},
{ERR_REASON(ASN1_R_TAG_VALUE_TOO_HIGH), "tag value too high"},
{ERR_REASON(ASN1_R_THE_ASN1_OBJECT_IDENTIFIER_IS_NOT_KNOWN_FOR_THIS_MD),
"the asn1 object identifier is not known for this md"},
{ERR_REASON(ASN1_R_TIME_NOT_ASCII_FORMAT), "time not ascii format"},
{ERR_REASON(ASN1_R_TOO_LONG), "too long"},
{ERR_REASON(ASN1_R_TYPE_NOT_CONSTRUCTED), "type not constructed"},
{ERR_REASON(ASN1_R_TYPE_NOT_PRIMITIVE), "type not primitive"},
{ERR_REASON(ASN1_R_UNABLE_TO_DECODE_RSA_KEY), "unable to decode rsa key"},
{ERR_REASON(ASN1_R_UNABLE_TO_DECODE_RSA_PRIVATE_KEY),
"unable to decode rsa private key"},
{ERR_REASON(ASN1_R_UNEXPECTED_EOC), "unexpected eoc"},
{ERR_REASON(ASN1_R_UNIVERSALSTRING_IS_WRONG_LENGTH),
"universalstring is wrong length"},
{ERR_REASON(ASN1_R_UNKNOWN_FORMAT), "unknown format"},
{ERR_REASON(ASN1_R_UNKNOWN_MESSAGE_DIGEST_ALGORITHM),
"unknown message digest algorithm"},
{ERR_REASON(ASN1_R_UNKNOWN_OBJECT_TYPE), "unknown object type"},
{ERR_REASON(ASN1_R_UNKNOWN_PUBLIC_KEY_TYPE), "unknown public key type"},
{ERR_REASON(ASN1_R_UNKNOWN_SIGNATURE_ALGORITHM),
"unknown signature algorithm"},
{ERR_REASON(ASN1_R_UNKNOWN_TAG), "unknown tag"},
{ERR_REASON(ASN1_R_UNKOWN_FORMAT), "unknown format"},
{ERR_REASON(ASN1_R_UNSUPPORTED_ANY_DEFINED_BY_TYPE),
"unsupported any defined by type"},
{ERR_REASON(ASN1_R_UNSUPPORTED_CIPHER), "unsupported cipher"},
{ERR_REASON(ASN1_R_UNSUPPORTED_ENCRYPTION_ALGORITHM),
"unsupported encryption algorithm"},
{ERR_REASON(ASN1_R_UNSUPPORTED_PUBLIC_KEY_TYPE),
"unsupported public key type"},
{ERR_REASON(ASN1_R_UNSUPPORTED_TYPE), "unsupported type"},
{ERR_REASON(ASN1_R_WRONG_PUBLIC_KEY_TYPE), "wrong public key type"},
{ERR_REASON(ASN1_R_WRONG_TAG), "wrong tag"},
{ERR_REASON(ASN1_R_WRONG_TYPE), "wrong type"},
{0, NULL}
};
#endif
void ERR_load_ASN1_strings(void)
{
#ifndef OPENSSL_NO_ERR
if (ERR_func_error_string(ASN1_str_functs[0].error) == NULL) {
ERR_load_strings(0, ASN1_str_functs);
ERR_load_strings(0, ASN1_str_reasons);
}
#endif
}
diff --git a/crypto/asn1/asn1_lib.c b/crypto/asn1/asn1_lib.c
index e63e82a8b476..b52c3e1264c7 100644
--- a/crypto/asn1/asn1_lib.c
+++ b/crypto/asn1/asn1_lib.c
@@ -1,483 +1,483 @@
/* crypto/asn1/asn1_lib.c */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
#include <stdio.h>
#include <limits.h>
#include "cryptlib.h"
#include <openssl/asn1.h>
#include <openssl/asn1_mac.h>
static int asn1_get_length(const unsigned char **pp, int *inf, long *rl,
long max);
static void asn1_put_length(unsigned char **pp, int length);
const char ASN1_version[] = "ASN.1" OPENSSL_VERSION_PTEXT;
static int _asn1_check_infinite_end(const unsigned char **p, long len)
{
/*
* If there is 0 or 1 byte left, the length check should pick things up
*/
if (len <= 0)
return (1);
else if ((len >= 2) && ((*p)[0] == 0) && ((*p)[1] == 0)) {
(*p) += 2;
return (1);
}
return (0);
}
int ASN1_check_infinite_end(unsigned char **p, long len)
{
return _asn1_check_infinite_end((const unsigned char **)p, len);
}
int ASN1_const_check_infinite_end(const unsigned char **p, long len)
{
return _asn1_check_infinite_end(p, len);
}
int ASN1_get_object(const unsigned char **pp, long *plength, int *ptag,
int *pclass, long omax)
{
int i, ret;
long l;
const unsigned char *p = *pp;
int tag, xclass, inf;
long max = omax;
if (!max)
goto err;
ret = (*p & V_ASN1_CONSTRUCTED);
xclass = (*p & V_ASN1_PRIVATE);
i = *p & V_ASN1_PRIMITIVE_TAG;
if (i == V_ASN1_PRIMITIVE_TAG) { /* high-tag */
p++;
if (--max == 0)
goto err;
l = 0;
while (*p & 0x80) {
l <<= 7L;
l |= *(p++) & 0x7f;
if (--max == 0)
goto err;
if (l > (INT_MAX >> 7L))
goto err;
}
l <<= 7L;
l |= *(p++) & 0x7f;
tag = (int)l;
if (--max == 0)
goto err;
} else {
tag = i;
p++;
if (--max == 0)
goto err;
}
*ptag = tag;
*pclass = xclass;
if (!asn1_get_length(&p, &inf, plength, max))
goto err;
if (inf && !(ret & V_ASN1_CONSTRUCTED))
goto err;
#if 0
fprintf(stderr, "p=%d + *plength=%ld > omax=%ld + *pp=%d (%d > %d)\n",
(int)p, *plength, omax, (int)*pp, (int)(p + *plength),
(int)(omax + *pp));
#endif
if (*plength > (omax - (p - *pp))) {
ASN1err(ASN1_F_ASN1_GET_OBJECT, ASN1_R_TOO_LONG);
/*
* Set this so that even if things are not long enough the values are
* set correctly
*/
ret |= 0x80;
}
*pp = p;
return (ret | inf);
err:
ASN1err(ASN1_F_ASN1_GET_OBJECT, ASN1_R_HEADER_TOO_LONG);
return (0x80);
}
static int asn1_get_length(const unsigned char **pp, int *inf, long *rl,
long max)
{
const unsigned char *p = *pp;
unsigned long ret = 0;
unsigned long i;
if (max-- < 1)
return 0;
if (*p == 0x80) {
*inf = 1;
ret = 0;
p++;
} else {
*inf = 0;
i = *p & 0x7f;
if (*(p++) & 0x80) {
if (i > sizeof(ret) || max < (long)i)
return 0;
while (i-- > 0) {
ret <<= 8L;
ret |= *(p++);
}
} else
ret = i;
}
if (ret > LONG_MAX)
return 0;
*pp = p;
*rl = (long)ret;
return 1;
}
/*
* class 0 is constructed constructed == 2 for indefinite length constructed
*/
void ASN1_put_object(unsigned char **pp, int constructed, int length, int tag,
int xclass)
{
unsigned char *p = *pp;
int i, ttag;
i = (constructed) ? V_ASN1_CONSTRUCTED : 0;
i |= (xclass & V_ASN1_PRIVATE);
if (tag < 31)
*(p++) = i | (tag & V_ASN1_PRIMITIVE_TAG);
else {
*(p++) = i | V_ASN1_PRIMITIVE_TAG;
for (i = 0, ttag = tag; ttag > 0; i++)
ttag >>= 7;
ttag = i;
while (i-- > 0) {
p[i] = tag & 0x7f;
if (i != (ttag - 1))
p[i] |= 0x80;
tag >>= 7;
}
p += ttag;
}
if (constructed == 2)
*(p++) = 0x80;
else
asn1_put_length(&p, length);
*pp = p;
}
int ASN1_put_eoc(unsigned char **pp)
{
unsigned char *p = *pp;
*p++ = 0;
*p++ = 0;
*pp = p;
return 2;
}
static void asn1_put_length(unsigned char **pp, int length)
{
unsigned char *p = *pp;
int i, l;
if (length <= 127)
*(p++) = (unsigned char)length;
else {
l = length;
for (i = 0; l > 0; i++)
l >>= 8;
*(p++) = i | 0x80;
l = i;
while (i-- > 0) {
p[i] = length & 0xff;
length >>= 8;
}
p += l;
}
*pp = p;
}
int ASN1_object_size(int constructed, int length, int tag)
{
int ret = 1;
if (length < 0)
return -1;
if (tag >= 31) {
while (tag > 0) {
tag >>= 7;
ret++;
}
}
if (constructed == 2) {
ret += 3;
} else {
ret++;
if (length > 127) {
int tmplen = length;
while (tmplen > 0) {
tmplen >>= 8;
ret++;
}
}
}
if (ret >= INT_MAX - length)
return -1;
return ret + length;
}
static int _asn1_Finish(ASN1_const_CTX *c)
{
if ((c->inf == (1 | V_ASN1_CONSTRUCTED)) && (!c->eos)) {
if (!ASN1_const_check_infinite_end(&c->p, c->slen)) {
c->error = ERR_R_MISSING_ASN1_EOS;
return (0);
}
}
if (((c->slen != 0) && !(c->inf & 1)) || ((c->slen < 0) && (c->inf & 1))) {
c->error = ERR_R_ASN1_LENGTH_MISMATCH;
return (0);
}
return (1);
}
int asn1_Finish(ASN1_CTX *c)
{
return _asn1_Finish((ASN1_const_CTX *)c);
}
int asn1_const_Finish(ASN1_const_CTX *c)
{
return _asn1_Finish(c);
}
int asn1_GetSequence(ASN1_const_CTX *c, long *length)
{
const unsigned char *q;
q = c->p;
c->inf = ASN1_get_object(&(c->p), &(c->slen), &(c->tag), &(c->xclass),
*length);
if (c->inf & 0x80) {
c->error = ERR_R_BAD_GET_ASN1_OBJECT_CALL;
return (0);
}
if (c->tag != V_ASN1_SEQUENCE) {
c->error = ERR_R_EXPECTING_AN_ASN1_SEQUENCE;
return (0);
}
(*length) -= (c->p - q);
if (c->max && (*length < 0)) {
c->error = ERR_R_ASN1_LENGTH_MISMATCH;
return (0);
}
if (c->inf == (1 | V_ASN1_CONSTRUCTED))
c->slen = *length;
c->eos = 0;
return (1);
}
int ASN1_STRING_copy(ASN1_STRING *dst, const ASN1_STRING *str)
{
if (str == NULL)
return 0;
dst->type = str->type;
if (!ASN1_STRING_set(dst, str->data, str->length))
return 0;
dst->flags = str->flags;
return 1;
}
ASN1_STRING *ASN1_STRING_dup(const ASN1_STRING *str)
{
ASN1_STRING *ret;
if (!str)
return NULL;
ret = ASN1_STRING_new();
if (!ret)
return NULL;
if (!ASN1_STRING_copy(ret, str)) {
ASN1_STRING_free(ret);
return NULL;
}
return ret;
}
int ASN1_STRING_set(ASN1_STRING *str, const void *_data, int len)
{
unsigned char *c;
const char *data = _data;
if (len < 0) {
if (data == NULL)
return (0);
else
len = strlen(data);
}
if ((str->length <= len) || (str->data == NULL)) {
c = str->data;
if (c == NULL)
str->data = OPENSSL_malloc(len + 1);
else
str->data = OPENSSL_realloc(c, len + 1);
if (str->data == NULL) {
ASN1err(ASN1_F_ASN1_STRING_SET, ERR_R_MALLOC_FAILURE);
str->data = c;
return (0);
}
}
str->length = len;
if (data != NULL) {
memcpy(str->data, data, len);
/* an allowance for strings :-) */
str->data[len] = '\0';
}
return (1);
}
void ASN1_STRING_set0(ASN1_STRING *str, void *data, int len)
{
if (str->data)
OPENSSL_free(str->data);
str->data = data;
str->length = len;
}
ASN1_STRING *ASN1_STRING_new(void)
{
return (ASN1_STRING_type_new(V_ASN1_OCTET_STRING));
}
ASN1_STRING *ASN1_STRING_type_new(int type)
{
ASN1_STRING *ret;
ret = (ASN1_STRING *)OPENSSL_malloc(sizeof(ASN1_STRING));
if (ret == NULL) {
ASN1err(ASN1_F_ASN1_STRING_TYPE_NEW, ERR_R_MALLOC_FAILURE);
return (NULL);
}
ret->length = 0;
ret->type = type;
ret->data = NULL;
ret->flags = 0;
return (ret);
}
void ASN1_STRING_free(ASN1_STRING *a)
{
if (a == NULL)
return;
if (a->data && !(a->flags & ASN1_STRING_FLAG_NDEF))
OPENSSL_free(a->data);
OPENSSL_free(a);
}
void ASN1_STRING_clear_free(ASN1_STRING *a)
{
if (a && a->data && !(a->flags & ASN1_STRING_FLAG_NDEF))
OPENSSL_cleanse(a->data, a->length);
ASN1_STRING_free(a);
}
int ASN1_STRING_cmp(const ASN1_STRING *a, const ASN1_STRING *b)
{
int i;
i = (a->length - b->length);
if (i == 0) {
i = memcmp(a->data, b->data, a->length);
if (i == 0)
return (a->type - b->type);
else
return (i);
} else
return (i);
}
void asn1_add_error(const unsigned char *address, int offset)
{
char buf1[DECIMAL_SIZE(address) + 1], buf2[DECIMAL_SIZE(offset) + 1];
- BIO_snprintf(buf1, sizeof buf1, "%lu", (unsigned long)address);
- BIO_snprintf(buf2, sizeof buf2, "%d", offset);
+ BIO_snprintf(buf1, sizeof(buf1), "%lu", (unsigned long)address);
+ BIO_snprintf(buf2, sizeof(buf2), "%d", offset);
ERR_add_error_data(4, "address=", buf1, " offset=", buf2);
}
int ASN1_STRING_length(const ASN1_STRING *x)
{
return M_ASN1_STRING_length(x);
}
void ASN1_STRING_length_set(ASN1_STRING *x, int len)
{
M_ASN1_STRING_length_set(x, len);
return;
}
int ASN1_STRING_type(ASN1_STRING *x)
{
return M_ASN1_STRING_type(x);
}
unsigned char *ASN1_STRING_data(ASN1_STRING *x)
{
return M_ASN1_STRING_data(x);
}
diff --git a/crypto/asn1/asn1_par.c b/crypto/asn1/asn1_par.c
index e85e3398b6bb..0b1a689d6831 100644
--- a/crypto/asn1/asn1_par.c
+++ b/crypto/asn1/asn1_par.c
@@ -1,424 +1,424 @@
/* crypto/asn1/asn1_par.c */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
#include <stdio.h>
#include "cryptlib.h"
#include <openssl/buffer.h>
#include <openssl/objects.h>
#include <openssl/asn1.h>
#ifndef ASN1_PARSE_MAXDEPTH
#define ASN1_PARSE_MAXDEPTH 128
#endif
static int asn1_print_info(BIO *bp, int tag, int xclass, int constructed,
int indent);
static int asn1_parse2(BIO *bp, const unsigned char **pp, long length,
int offset, int depth, int indent, int dump);
static int asn1_print_info(BIO *bp, int tag, int xclass, int constructed,
int indent)
{
static const char fmt[] = "%-18s";
char str[128];
const char *p;
if (constructed & V_ASN1_CONSTRUCTED)
p = "cons: ";
else
p = "prim: ";
if (BIO_write(bp, p, 6) < 6)
goto err;
BIO_indent(bp, indent, 128);
p = str;
if ((xclass & V_ASN1_PRIVATE) == V_ASN1_PRIVATE)
- BIO_snprintf(str, sizeof str, "priv [ %d ] ", tag);
+ BIO_snprintf(str, sizeof(str), "priv [ %d ] ", tag);
else if ((xclass & V_ASN1_CONTEXT_SPECIFIC) == V_ASN1_CONTEXT_SPECIFIC)
- BIO_snprintf(str, sizeof str, "cont [ %d ]", tag);
+ BIO_snprintf(str, sizeof(str), "cont [ %d ]", tag);
else if ((xclass & V_ASN1_APPLICATION) == V_ASN1_APPLICATION)
- BIO_snprintf(str, sizeof str, "appl [ %d ]", tag);
+ BIO_snprintf(str, sizeof(str), "appl [ %d ]", tag);
else if (tag > 30)
- BIO_snprintf(str, sizeof str, "<ASN1 %d>", tag);
+ BIO_snprintf(str, sizeof(str), "<ASN1 %d>", tag);
else
p = ASN1_tag2str(tag);
if (BIO_printf(bp, fmt, p) <= 0)
goto err;
return (1);
err:
return (0);
}
int ASN1_parse(BIO *bp, const unsigned char *pp, long len, int indent)
{
return (asn1_parse2(bp, &pp, len, 0, 0, indent, 0));
}
int ASN1_parse_dump(BIO *bp, const unsigned char *pp, long len, int indent,
int dump)
{
return (asn1_parse2(bp, &pp, len, 0, 0, indent, dump));
}
static int asn1_parse2(BIO *bp, const unsigned char **pp, long length,
int offset, int depth, int indent, int dump)
{
const unsigned char *p, *ep, *tot, *op, *opp;
long len;
int tag, xclass, ret = 0;
int nl, hl, j, r;
ASN1_OBJECT *o = NULL;
ASN1_OCTET_STRING *os = NULL;
/* ASN1_BMPSTRING *bmp=NULL; */
int dump_indent;
#if 0
dump_indent = indent;
#else
dump_indent = 6; /* Because we know BIO_dump_indent() */
#endif
if (depth > ASN1_PARSE_MAXDEPTH) {
BIO_puts(bp, "BAD RECURSION DEPTH\n");
return 0;
}
p = *pp;
tot = p + length;
op = p - 1;
while ((p < tot) && (op < p)) {
op = p;
j = ASN1_get_object(&p, &len, &tag, &xclass, length);
#ifdef LINT
j = j;
#endif
if (j & 0x80) {
if (BIO_write(bp, "Error in encoding\n", 18) <= 0)
goto end;
ret = 0;
goto end;
}
hl = (p - op);
length -= hl;
/*
* if j == 0x21 it is a constructed indefinite length object
*/
if (BIO_printf(bp, "%5ld:", (long)offset + (long)(op - *pp))
<= 0)
goto end;
if (j != (V_ASN1_CONSTRUCTED | 1)) {
if (BIO_printf(bp, "d=%-2d hl=%ld l=%4ld ",
depth, (long)hl, len) <= 0)
goto end;
} else {
if (BIO_printf(bp, "d=%-2d hl=%ld l=inf ", depth, (long)hl) <= 0)
goto end;
}
if (!asn1_print_info(bp, tag, xclass, j, (indent) ? depth : 0))
goto end;
if (j & V_ASN1_CONSTRUCTED) {
const unsigned char *sp;
ep = p + len;
if (BIO_write(bp, "\n", 1) <= 0)
goto end;
if (len > length) {
BIO_printf(bp, "length is greater than %ld\n", length);
ret = 0;
goto end;
}
if ((j == 0x21) && (len == 0)) {
sp = p;
for (;;) {
r = asn1_parse2(bp, &p, (long)(tot - p),
offset + (p - *pp), depth + 1,
indent, dump);
if (r == 0) {
ret = 0;
goto end;
}
if ((r == 2) || (p >= tot)) {
len = p - sp;
break;
}
}
} else {
long tmp = len;
while (p < ep) {
sp = p;
r = asn1_parse2(bp, &p, tmp, offset + (p - *pp), depth + 1,
indent, dump);
if (r == 0) {
ret = 0;
goto end;
}
tmp -= p - sp;
}
}
} else if (xclass != 0) {
p += len;
if (BIO_write(bp, "\n", 1) <= 0)
goto end;
} else {
nl = 0;
if ((tag == V_ASN1_PRINTABLESTRING) ||
(tag == V_ASN1_T61STRING) ||
(tag == V_ASN1_IA5STRING) ||
(tag == V_ASN1_VISIBLESTRING) ||
(tag == V_ASN1_NUMERICSTRING) ||
(tag == V_ASN1_UTF8STRING) ||
(tag == V_ASN1_UTCTIME) || (tag == V_ASN1_GENERALIZEDTIME)) {
if (BIO_write(bp, ":", 1) <= 0)
goto end;
if ((len > 0) && BIO_write(bp, (const char *)p, (int)len)
!= (int)len)
goto end;
} else if (tag == V_ASN1_OBJECT) {
opp = op;
if (d2i_ASN1_OBJECT(&o, &opp, len + hl) != NULL) {
if (BIO_write(bp, ":", 1) <= 0)
goto end;
i2a_ASN1_OBJECT(bp, o);
} else {
if (BIO_write(bp, ":BAD OBJECT", 11) <= 0)
goto end;
}
} else if (tag == V_ASN1_BOOLEAN) {
int ii;
opp = op;
ii = d2i_ASN1_BOOLEAN(NULL, &opp, len + hl);
if (ii < 0) {
if (BIO_write(bp, "Bad boolean\n", 12) <= 0)
goto end;
}
BIO_printf(bp, ":%d", ii);
} else if (tag == V_ASN1_BMPSTRING) {
/* do the BMP thang */
} else if (tag == V_ASN1_OCTET_STRING) {
int i, printable = 1;
opp = op;
os = d2i_ASN1_OCTET_STRING(NULL, &opp, len + hl);
if (os != NULL && os->length > 0) {
opp = os->data;
/*
* testing whether the octet string is printable
*/
for (i = 0; i < os->length; i++) {
if (((opp[i] < ' ') &&
(opp[i] != '\n') &&
(opp[i] != '\r') &&
(opp[i] != '\t')) || (opp[i] > '~')) {
printable = 0;
break;
}
}
if (printable)
/* printable string */
{
if (BIO_write(bp, ":", 1) <= 0)
goto end;
if (BIO_write(bp, (const char *)opp, os->length) <= 0)
goto end;
} else if (!dump)
/*
* not printable => print octet string as hex dump
*/
{
if (BIO_write(bp, "[HEX DUMP]:", 11) <= 0)
goto end;
for (i = 0; i < os->length; i++) {
if (BIO_printf(bp, "%02X", opp[i]) <= 0)
goto end;
}
} else
/* print the normal dump */
{
if (!nl) {
if (BIO_write(bp, "\n", 1) <= 0)
goto end;
}
if (BIO_dump_indent(bp,
(const char *)opp,
((dump == -1 || dump >
os->
length) ? os->length : dump),
dump_indent) <= 0)
goto end;
nl = 1;
}
}
if (os != NULL) {
M_ASN1_OCTET_STRING_free(os);
os = NULL;
}
} else if (tag == V_ASN1_INTEGER) {
ASN1_INTEGER *bs;
int i;
opp = op;
bs = d2i_ASN1_INTEGER(NULL, &opp, len + hl);
if (bs != NULL) {
if (BIO_write(bp, ":", 1) <= 0)
goto end;
if (bs->type == V_ASN1_NEG_INTEGER)
if (BIO_write(bp, "-", 1) <= 0)
goto end;
for (i = 0; i < bs->length; i++) {
if (BIO_printf(bp, "%02X", bs->data[i]) <= 0)
goto end;
}
if (bs->length == 0) {
if (BIO_write(bp, "00", 2) <= 0)
goto end;
}
} else {
if (BIO_write(bp, "BAD INTEGER", 11) <= 0)
goto end;
}
M_ASN1_INTEGER_free(bs);
} else if (tag == V_ASN1_ENUMERATED) {
ASN1_ENUMERATED *bs;
int i;
opp = op;
bs = d2i_ASN1_ENUMERATED(NULL, &opp, len + hl);
if (bs != NULL) {
if (BIO_write(bp, ":", 1) <= 0)
goto end;
if (bs->type == V_ASN1_NEG_ENUMERATED)
if (BIO_write(bp, "-", 1) <= 0)
goto end;
for (i = 0; i < bs->length; i++) {
if (BIO_printf(bp, "%02X", bs->data[i]) <= 0)
goto end;
}
if (bs->length == 0) {
if (BIO_write(bp, "00", 2) <= 0)
goto end;
}
} else {
if (BIO_write(bp, "BAD ENUMERATED", 14) <= 0)
goto end;
}
M_ASN1_ENUMERATED_free(bs);
} else if (len > 0 && dump) {
if (!nl) {
if (BIO_write(bp, "\n", 1) <= 0)
goto end;
}
if (BIO_dump_indent(bp, (const char *)p,
((dump == -1 || dump > len) ? len : dump),
dump_indent) <= 0)
goto end;
nl = 1;
}
if (!nl) {
if (BIO_write(bp, "\n", 1) <= 0)
goto end;
}
p += len;
if ((tag == V_ASN1_EOC) && (xclass == 0)) {
ret = 2; /* End of sequence */
goto end;
}
}
length -= len;
}
ret = 1;
end:
if (o != NULL)
ASN1_OBJECT_free(o);
if (os != NULL)
M_ASN1_OCTET_STRING_free(os);
*pp = p;
return (ret);
}
const char *ASN1_tag2str(int tag)
{
static const char *const tag2str[] = {
/* 0-4 */
"EOC", "BOOLEAN", "INTEGER", "BIT STRING", "OCTET STRING",
/* 5-9 */
"NULL", "OBJECT", "OBJECT DESCRIPTOR", "EXTERNAL", "REAL",
/* 10-13 */
"ENUMERATED", "<ASN1 11>", "UTF8STRING", "<ASN1 13>",
/* 15-17 */
"<ASN1 14>", "<ASN1 15>", "SEQUENCE", "SET",
/* 18-20 */
"NUMERICSTRING", "PRINTABLESTRING", "T61STRING",
/* 21-24 */
"VIDEOTEXSTRING", "IA5STRING", "UTCTIME", "GENERALIZEDTIME",
/* 25-27 */
"GRAPHICSTRING", "VISIBLESTRING", "GENERALSTRING",
/* 28-30 */
"UNIVERSALSTRING", "<ASN1 29>", "BMPSTRING"
};
if ((tag == V_ASN1_NEG_INTEGER) || (tag == V_ASN1_NEG_ENUMERATED))
tag &= ~0x100;
if (tag < 0 || tag > 30)
return "(unknown)";
return tag2str[tag];
}
diff --git a/crypto/asn1/asn_mime.c b/crypto/asn1/asn_mime.c
index 5170906c62da..02b7c9b7efc6 100644
--- a/crypto/asn1/asn_mime.c
+++ b/crypto/asn1/asn_mime.c
@@ -1,976 +1,977 @@
/* asn_mime.c */
/*
* Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL
* project.
*/
/* ====================================================================
- * Copyright (c) 1999-2008 The OpenSSL Project. All rights reserved.
+ * Copyright (c) 1999-2018 The OpenSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* licensing@OpenSSL.org.
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*
*/
#include <stdio.h>
#include <ctype.h>
#include "cryptlib.h"
#include <openssl/rand.h>
#include <openssl/x509.h>
#include <openssl/asn1.h>
#include <openssl/asn1t.h>
#include "asn1_locl.h"
/*
* Generalised MIME like utilities for streaming ASN1. Although many have a
* PKCS7/CMS like flavour others are more general purpose.
*/
/*
* MIME format structures Note that all are translated to lower case apart
* from parameter values. Quotes are stripped off
*/
typedef struct {
char *param_name; /* Param name e.g. "micalg" */
char *param_value; /* Param value e.g. "sha1" */
} MIME_PARAM;
DECLARE_STACK_OF(MIME_PARAM)
IMPLEMENT_STACK_OF(MIME_PARAM)
typedef struct {
char *name; /* Name of line e.g. "content-type" */
char *value; /* Value of line e.g. "text/plain" */
STACK_OF(MIME_PARAM) *params; /* Zero or more parameters */
} MIME_HEADER;
DECLARE_STACK_OF(MIME_HEADER)
IMPLEMENT_STACK_OF(MIME_HEADER)
static int asn1_output_data(BIO *out, BIO *data, ASN1_VALUE *val, int flags,
const ASN1_ITEM *it);
static char *strip_ends(char *name);
static char *strip_start(char *name);
static char *strip_end(char *name);
static MIME_HEADER *mime_hdr_new(char *name, char *value);
static int mime_hdr_addparam(MIME_HEADER *mhdr, char *name, char *value);
static STACK_OF(MIME_HEADER) *mime_parse_hdr(BIO *bio);
static int mime_hdr_cmp(const MIME_HEADER *const *a,
const MIME_HEADER *const *b);
static int mime_param_cmp(const MIME_PARAM *const *a,
const MIME_PARAM *const *b);
static void mime_param_free(MIME_PARAM *param);
static int mime_bound_check(char *line, int linelen, char *bound, int blen);
static int multi_split(BIO *bio, char *bound, STACK_OF(BIO) **ret);
static int strip_eol(char *linebuf, int *plen);
static MIME_HEADER *mime_hdr_find(STACK_OF(MIME_HEADER) *hdrs, char *name);
static MIME_PARAM *mime_param_find(MIME_HEADER *hdr, char *name);
static void mime_hdr_free(MIME_HEADER *hdr);
#define MAX_SMLEN 1024
#define mime_debug(x) /* x */
/* Output an ASN1 structure in BER format streaming if necessary */
int i2d_ASN1_bio_stream(BIO *out, ASN1_VALUE *val, BIO *in, int flags,
const ASN1_ITEM *it)
{
/* If streaming create stream BIO and copy all content through it */
if (flags & SMIME_STREAM) {
BIO *bio, *tbio;
bio = BIO_new_NDEF(out, val, it);
if (!bio) {
ASN1err(ASN1_F_I2D_ASN1_BIO_STREAM, ERR_R_MALLOC_FAILURE);
return 0;
}
SMIME_crlf_copy(in, bio, flags);
(void)BIO_flush(bio);
/* Free up successive BIOs until we hit the old output BIO */
do {
tbio = BIO_pop(bio);
BIO_free(bio);
bio = tbio;
} while (bio != out);
}
/*
* else just write out ASN1 structure which will have all content stored
* internally
*/
else
ASN1_item_i2d_bio(it, out, val);
return 1;
}
/* Base 64 read and write of ASN1 structure */
static int B64_write_ASN1(BIO *out, ASN1_VALUE *val, BIO *in, int flags,
const ASN1_ITEM *it)
{
BIO *b64;
int r;
b64 = BIO_new(BIO_f_base64());
if (!b64) {
ASN1err(ASN1_F_B64_WRITE_ASN1, ERR_R_MALLOC_FAILURE);
return 0;
}
/*
* prepend the b64 BIO so all data is base64 encoded.
*/
out = BIO_push(b64, out);
r = i2d_ASN1_bio_stream(out, val, in, flags, it);
(void)BIO_flush(out);
BIO_pop(out);
BIO_free(b64);
return r;
}
/* Streaming ASN1 PEM write */
int PEM_write_bio_ASN1_stream(BIO *out, ASN1_VALUE *val, BIO *in, int flags,
const char *hdr, const ASN1_ITEM *it)
{
int r;
BIO_printf(out, "-----BEGIN %s-----\n", hdr);
r = B64_write_ASN1(out, val, in, flags, it);
BIO_printf(out, "-----END %s-----\n", hdr);
return r;
}
static ASN1_VALUE *b64_read_asn1(BIO *bio, const ASN1_ITEM *it)
{
BIO *b64;
ASN1_VALUE *val;
if (!(b64 = BIO_new(BIO_f_base64()))) {
ASN1err(ASN1_F_B64_READ_ASN1, ERR_R_MALLOC_FAILURE);
return 0;
}
bio = BIO_push(b64, bio);
val = ASN1_item_d2i_bio(it, bio, NULL);
if (!val)
ASN1err(ASN1_F_B64_READ_ASN1, ASN1_R_DECODE_ERROR);
(void)BIO_flush(bio);
bio = BIO_pop(bio);
BIO_free(b64);
return val;
}
/* Generate the MIME "micalg" parameter from RFC3851, RFC4490 */
static int asn1_write_micalg(BIO *out, STACK_OF(X509_ALGOR) *mdalgs)
{
const EVP_MD *md;
int i, have_unknown = 0, write_comma, ret = 0, md_nid;
have_unknown = 0;
write_comma = 0;
for (i = 0; i < sk_X509_ALGOR_num(mdalgs); i++) {
if (write_comma)
BIO_write(out, ",", 1);
write_comma = 1;
md_nid = OBJ_obj2nid(sk_X509_ALGOR_value(mdalgs, i)->algorithm);
md = EVP_get_digestbynid(md_nid);
if (md && md->md_ctrl) {
int rv;
char *micstr;
rv = md->md_ctrl(NULL, EVP_MD_CTRL_MICALG, 0, &micstr);
if (rv > 0) {
BIO_puts(out, micstr);
OPENSSL_free(micstr);
continue;
}
if (rv != -2)
goto err;
}
switch (md_nid) {
case NID_sha1:
BIO_puts(out, "sha1");
break;
case NID_md5:
BIO_puts(out, "md5");
break;
case NID_sha256:
BIO_puts(out, "sha-256");
break;
case NID_sha384:
BIO_puts(out, "sha-384");
break;
case NID_sha512:
BIO_puts(out, "sha-512");
break;
case NID_id_GostR3411_94:
BIO_puts(out, "gostr3411-94");
goto err;
break;
default:
if (have_unknown)
write_comma = 0;
else {
BIO_puts(out, "unknown");
have_unknown = 1;
}
break;
}
}
ret = 1;
err:
return ret;
}
/* SMIME sender */
int SMIME_write_ASN1(BIO *bio, ASN1_VALUE *val, BIO *data, int flags,
int ctype_nid, int econt_nid,
STACK_OF(X509_ALGOR) *mdalgs, const ASN1_ITEM *it)
{
char bound[33], c;
int i;
const char *mime_prefix, *mime_eol, *cname = "smime.p7m";
const char *msg_type = NULL;
if (flags & SMIME_OLDMIME)
mime_prefix = "application/x-pkcs7-";
else
mime_prefix = "application/pkcs7-";
if (flags & SMIME_CRLFEOL)
mime_eol = "\r\n";
else
mime_eol = "\n";
if ((flags & SMIME_DETACHED) && data) {
/* We want multipart/signed */
/* Generate a random boundary */
if (RAND_bytes((unsigned char *)bound, 32) <= 0)
return 0;
for (i = 0; i < 32; i++) {
c = bound[i] & 0xf;
if (c < 10)
c += '0';
else
c += 'A' - 10;
bound[i] = c;
}
bound[32] = 0;
BIO_printf(bio, "MIME-Version: 1.0%s", mime_eol);
BIO_printf(bio, "Content-Type: multipart/signed;");
BIO_printf(bio, " protocol=\"%ssignature\";", mime_prefix);
BIO_puts(bio, " micalg=\"");
asn1_write_micalg(bio, mdalgs);
BIO_printf(bio, "\"; boundary=\"----%s\"%s%s",
bound, mime_eol, mime_eol);
BIO_printf(bio, "This is an S/MIME signed message%s%s",
mime_eol, mime_eol);
/* Now write out the first part */
BIO_printf(bio, "------%s%s", bound, mime_eol);
if (!asn1_output_data(bio, data, val, flags, it))
return 0;
BIO_printf(bio, "%s------%s%s", mime_eol, bound, mime_eol);
/* Headers for signature */
BIO_printf(bio, "Content-Type: %ssignature;", mime_prefix);
BIO_printf(bio, " name=\"smime.p7s\"%s", mime_eol);
BIO_printf(bio, "Content-Transfer-Encoding: base64%s", mime_eol);
BIO_printf(bio, "Content-Disposition: attachment;");
BIO_printf(bio, " filename=\"smime.p7s\"%s%s", mime_eol, mime_eol);
B64_write_ASN1(bio, val, NULL, 0, it);
BIO_printf(bio, "%s------%s--%s%s", mime_eol, bound,
mime_eol, mime_eol);
return 1;
}
/* Determine smime-type header */
if (ctype_nid == NID_pkcs7_enveloped)
msg_type = "enveloped-data";
else if (ctype_nid == NID_pkcs7_signed) {
if (econt_nid == NID_id_smime_ct_receipt)
msg_type = "signed-receipt";
else if (sk_X509_ALGOR_num(mdalgs) >= 0)
msg_type = "signed-data";
else
msg_type = "certs-only";
} else if (ctype_nid == NID_id_smime_ct_compressedData) {
msg_type = "compressed-data";
cname = "smime.p7z";
}
/* MIME headers */
BIO_printf(bio, "MIME-Version: 1.0%s", mime_eol);
BIO_printf(bio, "Content-Disposition: attachment;");
BIO_printf(bio, " filename=\"%s\"%s", cname, mime_eol);
BIO_printf(bio, "Content-Type: %smime;", mime_prefix);
if (msg_type)
BIO_printf(bio, " smime-type=%s;", msg_type);
BIO_printf(bio, " name=\"%s\"%s", cname, mime_eol);
BIO_printf(bio, "Content-Transfer-Encoding: base64%s%s",
mime_eol, mime_eol);
if (!B64_write_ASN1(bio, val, data, flags, it))
return 0;
BIO_printf(bio, "%s", mime_eol);
return 1;
}
/* Handle output of ASN1 data */
static int asn1_output_data(BIO *out, BIO *data, ASN1_VALUE *val, int flags,
const ASN1_ITEM *it)
{
BIO *tmpbio;
const ASN1_AUX *aux = it->funcs;
ASN1_STREAM_ARG sarg;
int rv = 1;
/*
* If data is not deteched or resigning then the output BIO is already
* set up to finalise when it is written through.
*/
if (!(flags & SMIME_DETACHED) || (flags & PKCS7_REUSE_DIGEST)) {
SMIME_crlf_copy(data, out, flags);
return 1;
}
if (!aux || !aux->asn1_cb) {
ASN1err(ASN1_F_ASN1_OUTPUT_DATA, ASN1_R_STREAMING_NOT_SUPPORTED);
return 0;
}
sarg.out = out;
sarg.ndef_bio = NULL;
sarg.boundary = NULL;
/* Let ASN1 code prepend any needed BIOs */
if (aux->asn1_cb(ASN1_OP_DETACHED_PRE, &val, it, &sarg) <= 0)
return 0;
/* Copy data across, passing through filter BIOs for processing */
SMIME_crlf_copy(data, sarg.ndef_bio, flags);
/* Finalize structure */
if (aux->asn1_cb(ASN1_OP_DETACHED_POST, &val, it, &sarg) <= 0)
rv = 0;
/* Now remove any digests prepended to the BIO */
while (sarg.ndef_bio != out) {
tmpbio = BIO_pop(sarg.ndef_bio);
BIO_free(sarg.ndef_bio);
sarg.ndef_bio = tmpbio;
}
return rv;
}
/*
* SMIME reader: handle multipart/signed and opaque signing. in multipart
* case the content is placed in a memory BIO pointed to by "bcont". In
* opaque this is set to NULL
*/
ASN1_VALUE *SMIME_read_ASN1(BIO *bio, BIO **bcont, const ASN1_ITEM *it)
{
BIO *asnin;
STACK_OF(MIME_HEADER) *headers = NULL;
STACK_OF(BIO) *parts = NULL;
MIME_HEADER *hdr;
MIME_PARAM *prm;
ASN1_VALUE *val;
int ret;
if (bcont)
*bcont = NULL;
if (!(headers = mime_parse_hdr(bio))) {
ASN1err(ASN1_F_SMIME_READ_ASN1, ASN1_R_MIME_PARSE_ERROR);
return NULL;
}
if (!(hdr = mime_hdr_find(headers, "content-type")) || !hdr->value) {
sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
ASN1err(ASN1_F_SMIME_READ_ASN1, ASN1_R_NO_CONTENT_TYPE);
return NULL;
}
/* Handle multipart/signed */
if (!strcmp(hdr->value, "multipart/signed")) {
/* Split into two parts */
prm = mime_param_find(hdr, "boundary");
if (!prm || !prm->param_value) {
sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
ASN1err(ASN1_F_SMIME_READ_ASN1, ASN1_R_NO_MULTIPART_BOUNDARY);
return NULL;
}
ret = multi_split(bio, prm->param_value, &parts);
sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
if (!ret || (sk_BIO_num(parts) != 2)) {
ASN1err(ASN1_F_SMIME_READ_ASN1, ASN1_R_NO_MULTIPART_BODY_FAILURE);
sk_BIO_pop_free(parts, BIO_vfree);
return NULL;
}
/* Parse the signature piece */
asnin = sk_BIO_value(parts, 1);
if (!(headers = mime_parse_hdr(asnin))) {
ASN1err(ASN1_F_SMIME_READ_ASN1, ASN1_R_MIME_SIG_PARSE_ERROR);
sk_BIO_pop_free(parts, BIO_vfree);
return NULL;
}
/* Get content type */
if (!(hdr = mime_hdr_find(headers, "content-type")) || !hdr->value) {
sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
ASN1err(ASN1_F_SMIME_READ_ASN1, ASN1_R_NO_SIG_CONTENT_TYPE);
+ sk_BIO_pop_free(parts, BIO_vfree);
return NULL;
}
if (strcmp(hdr->value, "application/x-pkcs7-signature") &&
strcmp(hdr->value, "application/pkcs7-signature")) {
ASN1err(ASN1_F_SMIME_READ_ASN1, ASN1_R_SIG_INVALID_MIME_TYPE);
ERR_add_error_data(2, "type: ", hdr->value);
sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
sk_BIO_pop_free(parts, BIO_vfree);
return NULL;
}
sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
/* Read in ASN1 */
if (!(val = b64_read_asn1(asnin, it))) {
ASN1err(ASN1_F_SMIME_READ_ASN1, ASN1_R_ASN1_SIG_PARSE_ERROR);
sk_BIO_pop_free(parts, BIO_vfree);
return NULL;
}
if (bcont) {
*bcont = sk_BIO_value(parts, 0);
BIO_free(asnin);
sk_BIO_free(parts);
} else
sk_BIO_pop_free(parts, BIO_vfree);
return val;
}
/* OK, if not multipart/signed try opaque signature */
if (strcmp(hdr->value, "application/x-pkcs7-mime") &&
strcmp(hdr->value, "application/pkcs7-mime")) {
ASN1err(ASN1_F_SMIME_READ_ASN1, ASN1_R_INVALID_MIME_TYPE);
ERR_add_error_data(2, "type: ", hdr->value);
sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
return NULL;
}
sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
if (!(val = b64_read_asn1(bio, it))) {
ASN1err(ASN1_F_SMIME_READ_ASN1, ASN1_R_ASN1_PARSE_ERROR);
return NULL;
}
return val;
}
/* Copy text from one BIO to another making the output CRLF at EOL */
int SMIME_crlf_copy(BIO *in, BIO *out, int flags)
{
BIO *bf;
char eol;
int len;
char linebuf[MAX_SMLEN];
/*
* Buffer output so we don't write one line at a time. This is useful
* when streaming as we don't end up with one OCTET STRING per line.
*/
bf = BIO_new(BIO_f_buffer());
if (!bf)
return 0;
out = BIO_push(bf, out);
if (flags & SMIME_BINARY) {
while ((len = BIO_read(in, linebuf, MAX_SMLEN)) > 0)
BIO_write(out, linebuf, len);
} else {
if (flags & SMIME_TEXT)
BIO_printf(out, "Content-Type: text/plain\r\n\r\n");
while ((len = BIO_gets(in, linebuf, MAX_SMLEN)) > 0) {
eol = strip_eol(linebuf, &len);
if (len)
BIO_write(out, linebuf, len);
if (eol)
BIO_write(out, "\r\n", 2);
}
}
(void)BIO_flush(out);
BIO_pop(out);
BIO_free(bf);
return 1;
}
/* Strip off headers if they are text/plain */
int SMIME_text(BIO *in, BIO *out)
{
char iobuf[4096];
int len;
STACK_OF(MIME_HEADER) *headers;
MIME_HEADER *hdr;
if (!(headers = mime_parse_hdr(in))) {
ASN1err(ASN1_F_SMIME_TEXT, ASN1_R_MIME_PARSE_ERROR);
return 0;
}
if (!(hdr = mime_hdr_find(headers, "content-type")) || !hdr->value) {
ASN1err(ASN1_F_SMIME_TEXT, ASN1_R_MIME_NO_CONTENT_TYPE);
sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
return 0;
}
if (strcmp(hdr->value, "text/plain")) {
ASN1err(ASN1_F_SMIME_TEXT, ASN1_R_INVALID_MIME_TYPE);
ERR_add_error_data(2, "type: ", hdr->value);
sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
return 0;
}
sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
while ((len = BIO_read(in, iobuf, sizeof(iobuf))) > 0)
BIO_write(out, iobuf, len);
if (len < 0)
return 0;
return 1;
}
/*
* Split a multipart/XXX message body into component parts: result is
* canonical parts in a STACK of bios
*/
static int multi_split(BIO *bio, char *bound, STACK_OF(BIO) **ret)
{
char linebuf[MAX_SMLEN];
int len, blen;
int eol = 0, next_eol = 0;
BIO *bpart = NULL;
STACK_OF(BIO) *parts;
char state, part, first;
blen = strlen(bound);
part = 0;
state = 0;
first = 1;
parts = sk_BIO_new_null();
*ret = parts;
while ((len = BIO_gets(bio, linebuf, MAX_SMLEN)) > 0) {
state = mime_bound_check(linebuf, len, bound, blen);
if (state == 1) {
first = 1;
part++;
} else if (state == 2) {
sk_BIO_push(parts, bpart);
return 1;
} else if (part) {
/* Strip CR+LF from linebuf */
next_eol = strip_eol(linebuf, &len);
if (first) {
first = 0;
if (bpart)
sk_BIO_push(parts, bpart);
bpart = BIO_new(BIO_s_mem());
if (bpart == NULL)
return 1;
BIO_set_mem_eof_return(bpart, 0);
} else if (eol)
BIO_write(bpart, "\r\n", 2);
eol = next_eol;
if (len)
BIO_write(bpart, linebuf, len);
}
}
return 0;
}
/* This is the big one: parse MIME header lines up to message body */
#define MIME_INVALID 0
#define MIME_START 1
#define MIME_TYPE 2
#define MIME_NAME 3
#define MIME_VALUE 4
#define MIME_QUOTE 5
#define MIME_COMMENT 6
static STACK_OF(MIME_HEADER) *mime_parse_hdr(BIO *bio)
{
char *p, *q, c;
char *ntmp;
char linebuf[MAX_SMLEN];
MIME_HEADER *mhdr = NULL;
STACK_OF(MIME_HEADER) *headers;
int len, state, save_state = 0;
headers = sk_MIME_HEADER_new(mime_hdr_cmp);
if (!headers)
return NULL;
while ((len = BIO_gets(bio, linebuf, MAX_SMLEN)) > 0) {
/* If whitespace at line start then continuation line */
if (mhdr && isspace((unsigned char)linebuf[0]))
state = MIME_NAME;
else
state = MIME_START;
ntmp = NULL;
/* Go through all characters */
for (p = linebuf, q = linebuf; (c = *p) && (c != '\r') && (c != '\n');
p++) {
/*
* State machine to handle MIME headers if this looks horrible
* that's because it *is*
*/
switch (state) {
case MIME_START:
if (c == ':') {
state = MIME_TYPE;
*p = 0;
ntmp = strip_ends(q);
q = p + 1;
}
break;
case MIME_TYPE:
if (c == ';') {
mime_debug("Found End Value\n");
*p = 0;
mhdr = mime_hdr_new(ntmp, strip_ends(q));
sk_MIME_HEADER_push(headers, mhdr);
ntmp = NULL;
q = p + 1;
state = MIME_NAME;
} else if (c == '(') {
save_state = state;
state = MIME_COMMENT;
}
break;
case MIME_COMMENT:
if (c == ')') {
state = save_state;
}
break;
case MIME_NAME:
if (c == '=') {
state = MIME_VALUE;
*p = 0;
ntmp = strip_ends(q);
q = p + 1;
}
break;
case MIME_VALUE:
if (c == ';') {
state = MIME_NAME;
*p = 0;
mime_hdr_addparam(mhdr, ntmp, strip_ends(q));
ntmp = NULL;
q = p + 1;
} else if (c == '"') {
mime_debug("Found Quote\n");
state = MIME_QUOTE;
} else if (c == '(') {
save_state = state;
state = MIME_COMMENT;
}
break;
case MIME_QUOTE:
if (c == '"') {
mime_debug("Found Match Quote\n");
state = MIME_VALUE;
}
break;
}
}
if (state == MIME_TYPE) {
mhdr = mime_hdr_new(ntmp, strip_ends(q));
sk_MIME_HEADER_push(headers, mhdr);
} else if (state == MIME_VALUE)
mime_hdr_addparam(mhdr, ntmp, strip_ends(q));
if (p == linebuf)
break; /* Blank line means end of headers */
}
return headers;
}
static char *strip_ends(char *name)
{
return strip_end(strip_start(name));
}
/* Strip a parameter of whitespace from start of param */
static char *strip_start(char *name)
{
char *p, c;
/* Look for first non white space or quote */
for (p = name; (c = *p); p++) {
if (c == '"') {
/* Next char is start of string if non null */
if (p[1])
return p + 1;
/* Else null string */
return NULL;
}
if (!isspace((unsigned char)c))
return p;
}
return NULL;
}
/* As above but strip from end of string : maybe should handle brackets? */
static char *strip_end(char *name)
{
char *p, c;
if (!name)
return NULL;
/* Look for first non white space or quote */
for (p = name + strlen(name) - 1; p >= name; p--) {
c = *p;
if (c == '"') {
if (p - 1 == name)
return NULL;
*p = 0;
return name;
}
if (isspace((unsigned char)c))
*p = 0;
else
return name;
}
return NULL;
}
static MIME_HEADER *mime_hdr_new(char *name, char *value)
{
MIME_HEADER *mhdr;
char *tmpname, *tmpval, *p;
int c;
if (name) {
if (!(tmpname = BUF_strdup(name)))
return NULL;
for (p = tmpname; *p; p++) {
c = (unsigned char)*p;
if (isupper(c)) {
c = tolower(c);
*p = c;
}
}
} else
tmpname = NULL;
if (value) {
if (!(tmpval = BUF_strdup(value)))
return NULL;
for (p = tmpval; *p; p++) {
c = (unsigned char)*p;
if (isupper(c)) {
c = tolower(c);
*p = c;
}
}
} else
tmpval = NULL;
mhdr = (MIME_HEADER *)OPENSSL_malloc(sizeof(MIME_HEADER));
if (!mhdr)
return NULL;
mhdr->name = tmpname;
mhdr->value = tmpval;
if (!(mhdr->params = sk_MIME_PARAM_new(mime_param_cmp)))
return NULL;
return mhdr;
}
static int mime_hdr_addparam(MIME_HEADER *mhdr, char *name, char *value)
{
char *tmpname, *tmpval, *p;
int c;
MIME_PARAM *mparam;
if (name) {
tmpname = BUF_strdup(name);
if (!tmpname)
return 0;
for (p = tmpname; *p; p++) {
c = (unsigned char)*p;
if (isupper(c)) {
c = tolower(c);
*p = c;
}
}
} else
tmpname = NULL;
if (value) {
tmpval = BUF_strdup(value);
if (!tmpval)
return 0;
} else
tmpval = NULL;
/* Parameter values are case sensitive so leave as is */
mparam = (MIME_PARAM *)OPENSSL_malloc(sizeof(MIME_PARAM));
if (!mparam)
return 0;
mparam->param_name = tmpname;
mparam->param_value = tmpval;
sk_MIME_PARAM_push(mhdr->params, mparam);
return 1;
}
static int mime_hdr_cmp(const MIME_HEADER *const *a,
const MIME_HEADER *const *b)
{
if (!(*a)->name || !(*b)->name)
return ! !(*a)->name - ! !(*b)->name;
return (strcmp((*a)->name, (*b)->name));
}
static int mime_param_cmp(const MIME_PARAM *const *a,
const MIME_PARAM *const *b)
{
if (!(*a)->param_name || !(*b)->param_name)
return ! !(*a)->param_name - ! !(*b)->param_name;
return (strcmp((*a)->param_name, (*b)->param_name));
}
/* Find a header with a given name (if possible) */
static MIME_HEADER *mime_hdr_find(STACK_OF(MIME_HEADER) *hdrs, char *name)
{
MIME_HEADER htmp;
int idx;
htmp.name = name;
idx = sk_MIME_HEADER_find(hdrs, &htmp);
if (idx < 0)
return NULL;
return sk_MIME_HEADER_value(hdrs, idx);
}
static MIME_PARAM *mime_param_find(MIME_HEADER *hdr, char *name)
{
MIME_PARAM param;
int idx;
param.param_name = name;
idx = sk_MIME_PARAM_find(hdr->params, &param);
if (idx < 0)
return NULL;
return sk_MIME_PARAM_value(hdr->params, idx);
}
static void mime_hdr_free(MIME_HEADER *hdr)
{
if (hdr->name)
OPENSSL_free(hdr->name);
if (hdr->value)
OPENSSL_free(hdr->value);
if (hdr->params)
sk_MIME_PARAM_pop_free(hdr->params, mime_param_free);
OPENSSL_free(hdr);
}
static void mime_param_free(MIME_PARAM *param)
{
if (param->param_name)
OPENSSL_free(param->param_name);
if (param->param_value)
OPENSSL_free(param->param_value);
OPENSSL_free(param);
}
/*-
* Check for a multipart boundary. Returns:
* 0 : no boundary
* 1 : part boundary
* 2 : final boundary
*/
static int mime_bound_check(char *line, int linelen, char *bound, int blen)
{
if (linelen == -1)
linelen = strlen(line);
if (blen == -1)
blen = strlen(bound);
/* Quickly eliminate if line length too short */
if (blen + 2 > linelen)
return 0;
/* Check for part boundary */
if (!strncmp(line, "--", 2) && !strncmp(line + 2, bound, blen)) {
if (!strncmp(line + blen + 2, "--", 2))
return 2;
else
return 1;
}
return 0;
}
static int strip_eol(char *linebuf, int *plen)
{
int len = *plen;
char *p, c;
int is_eol = 0;
p = linebuf + len - 1;
for (p = linebuf + len - 1; len > 0; len--, p--) {
c = *p;
if (c == '\n')
is_eol = 1;
else if (c != '\r')
break;
}
*plen = len;
return is_eol;
}
diff --git a/crypto/asn1/t_x509a.c b/crypto/asn1/t_x509a.c
index f4b8f94cb35a..d1b897a469fd 100644
--- a/crypto/asn1/t_x509a.c
+++ b/crypto/asn1/t_x509a.c
@@ -1,115 +1,115 @@
/* t_x509a.c */
/*
* Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL project
* 1999.
*/
/* ====================================================================
* Copyright (c) 1999 The OpenSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* licensing@OpenSSL.org.
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*
* This product includes cryptographic software written by Eric Young
* (eay@cryptsoft.com). This product includes software written by Tim
* Hudson (tjh@cryptsoft.com).
*
*/
#include <stdio.h>
#include "cryptlib.h"
#include <openssl/evp.h>
#include <openssl/asn1.h>
#include <openssl/x509.h>
/*
* X509_CERT_AUX and string set routines
*/
int X509_CERT_AUX_print(BIO *out, X509_CERT_AUX *aux, int indent)
{
char oidstr[80], first;
int i;
if (!aux)
return 1;
if (aux->trust) {
first = 1;
BIO_printf(out, "%*sTrusted Uses:\n%*s", indent, "", indent + 2, "");
for (i = 0; i < sk_ASN1_OBJECT_num(aux->trust); i++) {
if (!first)
BIO_puts(out, ", ");
else
first = 0;
- OBJ_obj2txt(oidstr, sizeof oidstr,
+ OBJ_obj2txt(oidstr, sizeof(oidstr),
sk_ASN1_OBJECT_value(aux->trust, i), 0);
BIO_puts(out, oidstr);
}
BIO_puts(out, "\n");
} else
BIO_printf(out, "%*sNo Trusted Uses.\n", indent, "");
if (aux->reject) {
first = 1;
BIO_printf(out, "%*sRejected Uses:\n%*s", indent, "", indent + 2, "");
for (i = 0; i < sk_ASN1_OBJECT_num(aux->reject); i++) {
if (!first)
BIO_puts(out, ", ");
else
first = 0;
- OBJ_obj2txt(oidstr, sizeof oidstr,
+ OBJ_obj2txt(oidstr, sizeof(oidstr),
sk_ASN1_OBJECT_value(aux->reject, i), 0);
BIO_puts(out, oidstr);
}
BIO_puts(out, "\n");
} else
BIO_printf(out, "%*sNo Rejected Uses.\n", indent, "");
if (aux->alias)
BIO_printf(out, "%*sAlias: %s\n", indent, "", aux->alias->data);
if (aux->keyid) {
BIO_printf(out, "%*sKey Id: ", indent, "");
for (i = 0; i < aux->keyid->length; i++)
BIO_printf(out, "%s%02X", i ? ":" : "", aux->keyid->data[i]);
BIO_write(out, "\n", 1);
}
return 1;
}
diff --git a/crypto/asn1/tasn_dec.c b/crypto/asn1/tasn_dec.c
index d49a5d5792a4..e657c36d8ab6 100644
--- a/crypto/asn1/tasn_dec.c
+++ b/crypto/asn1/tasn_dec.c
@@ -1,1230 +1,1250 @@
/* tasn_dec.c */
/*
* Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL project
* 2000.
*/
/* ====================================================================
- * Copyright (c) 2000-2005 The OpenSSL Project. All rights reserved.
+ * Copyright (c) 2000-2018 The OpenSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* licensing@OpenSSL.org.
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*
* This product includes cryptographic software written by Eric Young
* (eay@cryptsoft.com). This product includes software written by Tim
* Hudson (tjh@cryptsoft.com).
*
*/
#include <stddef.h>
#include <string.h>
#include <openssl/asn1.h>
#include <openssl/asn1t.h>
#include <openssl/objects.h>
#include <openssl/buffer.h>
#include <openssl/err.h>
+/*
+ * Constructed types with a recursive definition (such as can be found in PKCS7)
+ * could eventually exceed the stack given malicious input with excessive
+ * recursion. Therefore we limit the stack depth. This is the maximum number of
+ * recursive invocations of asn1_item_embed_d2i().
+ */
+#define ASN1_MAX_CONSTRUCTED_NEST 30
+
static int asn1_check_eoc(const unsigned char **in, long len);
static int asn1_find_end(const unsigned char **in, long len, char inf);
static int asn1_collect(BUF_MEM *buf, const unsigned char **in, long len,
char inf, int tag, int aclass, int depth);
static int collect_data(BUF_MEM *buf, const unsigned char **p, long plen);
static int asn1_check_tlen(long *olen, int *otag, unsigned char *oclass,
char *inf, char *cst,
const unsigned char **in, long len,
int exptag, int expclass, char opt, ASN1_TLC *ctx);
static int asn1_template_ex_d2i(ASN1_VALUE **pval,
const unsigned char **in, long len,
const ASN1_TEMPLATE *tt, char opt,
- ASN1_TLC *ctx);
+ ASN1_TLC *ctx, int depth);
static int asn1_template_noexp_d2i(ASN1_VALUE **val,
const unsigned char **in, long len,
const ASN1_TEMPLATE *tt, char opt,
- ASN1_TLC *ctx);
+ ASN1_TLC *ctx, int depth);
static int asn1_d2i_ex_primitive(ASN1_VALUE **pval,
const unsigned char **in, long len,
const ASN1_ITEM *it,
int tag, int aclass, char opt,
ASN1_TLC *ctx);
/* Table to convert tags to bit values, used for MSTRING type */
static const unsigned long tag2bit[32] = {
/* tags 0 - 3 */
0, 0, 0, B_ASN1_BIT_STRING,
/* tags 4- 7 */
B_ASN1_OCTET_STRING, 0, 0, B_ASN1_UNKNOWN,
/* tags 8-11 */
B_ASN1_UNKNOWN, B_ASN1_UNKNOWN, B_ASN1_UNKNOWN, B_ASN1_UNKNOWN,
/* tags 12-15 */
B_ASN1_UTF8STRING, B_ASN1_UNKNOWN, B_ASN1_UNKNOWN, B_ASN1_UNKNOWN,
/* tags 16-19 */
B_ASN1_SEQUENCE, 0, B_ASN1_NUMERICSTRING, B_ASN1_PRINTABLESTRING,
/* tags 20-22 */
B_ASN1_T61STRING, B_ASN1_VIDEOTEXSTRING, B_ASN1_IA5STRING,
/* tags 23-24 */
B_ASN1_UTCTIME, B_ASN1_GENERALIZEDTIME,
/* tags 25-27 */
B_ASN1_GRAPHICSTRING, B_ASN1_ISO64STRING, B_ASN1_GENERALSTRING,
/* tags 28-31 */
B_ASN1_UNIVERSALSTRING, B_ASN1_UNKNOWN, B_ASN1_BMPSTRING, B_ASN1_UNKNOWN,
};
unsigned long ASN1_tag2bit(int tag)
{
if ((tag < 0) || (tag > 30))
return 0;
return tag2bit[tag];
}
/* Macro to initialize and invalidate the cache */
#define asn1_tlc_clear(c) if (c) (c)->valid = 0
/* Version to avoid compiler warning about 'c' always non-NULL */
#define asn1_tlc_clear_nc(c) (c)->valid = 0
/*
* Decode an ASN1 item, this currently behaves just like a standard 'd2i'
* function. 'in' points to a buffer to read the data from, in future we
* will have more advanced versions that can input data a piece at a time and
* this will simply be a special case.
*/
ASN1_VALUE *ASN1_item_d2i(ASN1_VALUE **pval,
const unsigned char **in, long len,
const ASN1_ITEM *it)
{
ASN1_TLC c;
ASN1_VALUE *ptmpval = NULL;
if (!pval)
pval = &ptmpval;
asn1_tlc_clear_nc(&c);
if (ASN1_item_ex_d2i(pval, in, len, it, -1, 0, 0, &c) > 0)
return *pval;
return NULL;
}
int ASN1_template_d2i(ASN1_VALUE **pval,
const unsigned char **in, long len,
const ASN1_TEMPLATE *tt)
{
ASN1_TLC c;
asn1_tlc_clear_nc(&c);
- return asn1_template_ex_d2i(pval, in, len, tt, 0, &c);
+ return asn1_template_ex_d2i(pval, in, len, tt, 0, &c, 0);
}
/*
* Decode an item, taking care of IMPLICIT tagging, if any. If 'opt' set and
* tag mismatch return -1 to handle OPTIONAL
*/
-
-int ASN1_item_ex_d2i(ASN1_VALUE **pval, const unsigned char **in, long len,
- const ASN1_ITEM *it,
- int tag, int aclass, char opt, ASN1_TLC *ctx)
+static int asn1_item_ex_d2i(ASN1_VALUE **pval, const unsigned char **in,
+ long len, const ASN1_ITEM *it, int tag, int aclass,
+ char opt, ASN1_TLC *ctx, int depth)
{
const ASN1_TEMPLATE *tt, *errtt = NULL;
const ASN1_COMPAT_FUNCS *cf;
const ASN1_EXTERN_FUNCS *ef;
const ASN1_AUX *aux = it->funcs;
ASN1_aux_cb *asn1_cb;
const unsigned char *p = NULL, *q;
unsigned char *wp = NULL; /* BIG FAT WARNING! BREAKS CONST WHERE USED */
unsigned char imphack = 0, oclass;
char seq_eoc, seq_nolen, cst, isopt;
long tmplen;
int i;
int otag;
int ret = 0;
ASN1_VALUE **pchptr, *ptmpval;
int combine = aclass & ASN1_TFLG_COMBINE;
aclass &= ~ASN1_TFLG_COMBINE;
if (!pval)
return 0;
if (aux && aux->asn1_cb)
asn1_cb = aux->asn1_cb;
else
asn1_cb = 0;
+ if (++depth > ASN1_MAX_CONSTRUCTED_NEST) {
+ ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_NESTED_TOO_DEEP);
+ goto err;
+ }
+
switch (it->itype) {
case ASN1_ITYPE_PRIMITIVE:
if (it->templates) {
/*
* tagging or OPTIONAL is currently illegal on an item template
* because the flags can't get passed down. In practice this
* isn't a problem: we include the relevant flags from the item
* template in the template itself.
*/
if ((tag != -1) || opt) {
ASN1err(ASN1_F_ASN1_ITEM_EX_D2I,
ASN1_R_ILLEGAL_OPTIONS_ON_ITEM_TEMPLATE);
goto err;
}
return asn1_template_ex_d2i(pval, in, len,
- it->templates, opt, ctx);
+ it->templates, opt, ctx, depth);
}
return asn1_d2i_ex_primitive(pval, in, len, it,
tag, aclass, opt, ctx);
break;
case ASN1_ITYPE_MSTRING:
p = *in;
/* Just read in tag and class */
ret = asn1_check_tlen(NULL, &otag, &oclass, NULL, NULL,
&p, len, -1, 0, 1, ctx);
if (!ret) {
ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ERR_R_NESTED_ASN1_ERROR);
goto err;
}
/* Must be UNIVERSAL class */
if (oclass != V_ASN1_UNIVERSAL) {
/* If OPTIONAL, assume this is OK */
if (opt)
return -1;
ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_MSTRING_NOT_UNIVERSAL);
goto err;
}
/* Check tag matches bit map */
if (!(ASN1_tag2bit(otag) & it->utype)) {
/* If OPTIONAL, assume this is OK */
if (opt)
return -1;
ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_MSTRING_WRONG_TAG);
goto err;
}
return asn1_d2i_ex_primitive(pval, in, len, it, otag, 0, 0, ctx);
case ASN1_ITYPE_EXTERN:
/* Use new style d2i */
ef = it->funcs;
return ef->asn1_ex_d2i(pval, in, len, it, tag, aclass, opt, ctx);
case ASN1_ITYPE_COMPAT:
/* we must resort to old style evil hackery */
cf = it->funcs;
/* If OPTIONAL see if it is there */
if (opt) {
int exptag;
p = *in;
if (tag == -1)
exptag = it->utype;
else
exptag = tag;
/*
* Don't care about anything other than presence of expected tag
*/
ret = asn1_check_tlen(NULL, NULL, NULL, NULL, NULL,
&p, len, exptag, aclass, 1, ctx);
if (!ret) {
ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ERR_R_NESTED_ASN1_ERROR);
goto err;
}
if (ret == -1)
return -1;
}
/*
* This is the old style evil hack IMPLICIT handling: since the
* underlying code is expecting a tag and class other than the one
* present we change the buffer temporarily then change it back
* afterwards. This doesn't and never did work for tags > 30. Yes
* this is *horrible* but it is only needed for old style d2i which
* will hopefully not be around for much longer. FIXME: should copy
* the buffer then modify it so the input buffer can be const: we
* should *always* copy because the old style d2i might modify the
* buffer.
*/
if (tag != -1) {
wp = *(unsigned char **)in;
imphack = *wp;
if (p == NULL) {
ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ERR_R_NESTED_ASN1_ERROR);
goto err;
}
*wp = (unsigned char)((*p & V_ASN1_CONSTRUCTED)
| it->utype);
}
ptmpval = cf->asn1_d2i(pval, in, len);
if (tag != -1)
*wp = imphack;
if (ptmpval)
return 1;
ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ERR_R_NESTED_ASN1_ERROR);
goto err;
case ASN1_ITYPE_CHOICE:
if (asn1_cb && !asn1_cb(ASN1_OP_D2I_PRE, pval, it, NULL))
goto auxerr;
if (*pval) {
/* Free up and zero CHOICE value if initialised */
i = asn1_get_choice_selector(pval, it);
if ((i >= 0) && (i < it->tcount)) {
tt = it->templates + i;
pchptr = asn1_get_field_ptr(pval, tt);
ASN1_template_free(pchptr, tt);
asn1_set_choice_selector(pval, -1, it);
}
} else if (!ASN1_item_ex_new(pval, it)) {
ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ERR_R_NESTED_ASN1_ERROR);
goto err;
}
/* CHOICE type, try each possibility in turn */
p = *in;
for (i = 0, tt = it->templates; i < it->tcount; i++, tt++) {
pchptr = asn1_get_field_ptr(pval, tt);
/*
* We mark field as OPTIONAL so its absence can be recognised.
*/
- ret = asn1_template_ex_d2i(pchptr, &p, len, tt, 1, ctx);
+ ret = asn1_template_ex_d2i(pchptr, &p, len, tt, 1, ctx, depth);
/* If field not present, try the next one */
if (ret == -1)
continue;
/* If positive return, read OK, break loop */
if (ret > 0)
break;
/* Otherwise must be an ASN1 parsing error */
errtt = tt;
ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ERR_R_NESTED_ASN1_ERROR);
goto err;
}
/* Did we fall off the end without reading anything? */
if (i == it->tcount) {
/* If OPTIONAL, this is OK */
if (opt) {
/* Free and zero it */
ASN1_item_ex_free(pval, it);
return -1;
}
ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_NO_MATCHING_CHOICE_TYPE);
goto err;
}
asn1_set_choice_selector(pval, i, it);
if (asn1_cb && !asn1_cb(ASN1_OP_D2I_POST, pval, it, NULL))
goto auxerr;
*in = p;
return 1;
case ASN1_ITYPE_NDEF_SEQUENCE:
case ASN1_ITYPE_SEQUENCE:
p = *in;
tmplen = len;
/* If no IMPLICIT tagging set to SEQUENCE, UNIVERSAL */
if (tag == -1) {
tag = V_ASN1_SEQUENCE;
aclass = V_ASN1_UNIVERSAL;
}
/* Get SEQUENCE length and update len, p */
ret = asn1_check_tlen(&len, NULL, NULL, &seq_eoc, &cst,
&p, len, tag, aclass, opt, ctx);
if (!ret) {
ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ERR_R_NESTED_ASN1_ERROR);
goto err;
} else if (ret == -1)
return -1;
if (aux && (aux->flags & ASN1_AFLG_BROKEN)) {
len = tmplen - (p - *in);
seq_nolen = 1;
}
/* If indefinite we don't do a length check */
else
seq_nolen = seq_eoc;
if (!cst) {
ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_SEQUENCE_NOT_CONSTRUCTED);
goto err;
}
if (!*pval && !ASN1_item_ex_new(pval, it)) {
ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ERR_R_NESTED_ASN1_ERROR);
goto err;
}
if (asn1_cb && !asn1_cb(ASN1_OP_D2I_PRE, pval, it, NULL))
goto auxerr;
/* Free up and zero any ADB found */
for (i = 0, tt = it->templates; i < it->tcount; i++, tt++) {
if (tt->flags & ASN1_TFLG_ADB_MASK) {
const ASN1_TEMPLATE *seqtt;
ASN1_VALUE **pseqval;
seqtt = asn1_do_adb(pval, tt, 0);
if (seqtt == NULL)
continue;
pseqval = asn1_get_field_ptr(pval, seqtt);
ASN1_template_free(pseqval, seqtt);
}
}
/* Get each field entry */
for (i = 0, tt = it->templates; i < it->tcount; i++, tt++) {
const ASN1_TEMPLATE *seqtt;
ASN1_VALUE **pseqval;
seqtt = asn1_do_adb(pval, tt, 1);
if (seqtt == NULL)
goto err;
pseqval = asn1_get_field_ptr(pval, seqtt);
/* Have we ran out of data? */
if (!len)
break;
q = p;
if (asn1_check_eoc(&p, len)) {
if (!seq_eoc) {
ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_UNEXPECTED_EOC);
goto err;
}
len -= p - q;
seq_eoc = 0;
q = p;
break;
}
/*
* This determines the OPTIONAL flag value. The field cannot be
* omitted if it is the last of a SEQUENCE and there is still
* data to be read. This isn't strictly necessary but it
* increases efficiency in some cases.
*/
if (i == (it->tcount - 1))
isopt = 0;
else
isopt = (char)(seqtt->flags & ASN1_TFLG_OPTIONAL);
/*
* attempt to read in field, allowing each to be OPTIONAL
*/
- ret = asn1_template_ex_d2i(pseqval, &p, len, seqtt, isopt, ctx);
+ ret = asn1_template_ex_d2i(pseqval, &p, len, seqtt, isopt, ctx,
+ depth);
if (!ret) {
errtt = seqtt;
goto err;
} else if (ret == -1) {
/*
* OPTIONAL component absent. Free and zero the field.
*/
ASN1_template_free(pseqval, seqtt);
continue;
}
/* Update length */
len -= p - q;
}
/* Check for EOC if expecting one */
if (seq_eoc && !asn1_check_eoc(&p, len)) {
ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_MISSING_EOC);
goto err;
}
/* Check all data read */
if (!seq_nolen && len) {
ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_SEQUENCE_LENGTH_MISMATCH);
goto err;
}
/*
* If we get here we've got no more data in the SEQUENCE, however we
* may not have read all fields so check all remaining are OPTIONAL
* and clear any that are.
*/
for (; i < it->tcount; tt++, i++) {
const ASN1_TEMPLATE *seqtt;
seqtt = asn1_do_adb(pval, tt, 1);
if (seqtt == NULL)
goto err;
if (seqtt->flags & ASN1_TFLG_OPTIONAL) {
ASN1_VALUE **pseqval;
pseqval = asn1_get_field_ptr(pval, seqtt);
ASN1_template_free(pseqval, seqtt);
} else {
errtt = seqtt;
ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_FIELD_MISSING);
goto err;
}
}
/* Save encoding */
if (!asn1_enc_save(pval, *in, p - *in, it))
goto auxerr;
if (asn1_cb && !asn1_cb(ASN1_OP_D2I_POST, pval, it, NULL))
goto auxerr;
*in = p;
return 1;
default:
return 0;
}
auxerr:
ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_AUX_ERROR);
err:
if (combine == 0)
ASN1_item_ex_free(pval, it);
if (errtt)
ERR_add_error_data(4, "Field=", errtt->field_name,
", Type=", it->sname);
else
ERR_add_error_data(2, "Type=", it->sname);
return 0;
}
+int ASN1_item_ex_d2i(ASN1_VALUE **pval, const unsigned char **in, long len,
+ const ASN1_ITEM *it,
+ int tag, int aclass, char opt, ASN1_TLC *ctx)
+{
+ return asn1_item_ex_d2i(pval, in, len, it, tag, aclass, opt, ctx, 0);
+}
+
/*
* Templates are handled with two separate functions. One handles any
* EXPLICIT tag and the other handles the rest.
*/
static int asn1_template_ex_d2i(ASN1_VALUE **val,
const unsigned char **in, long inlen,
const ASN1_TEMPLATE *tt, char opt,
- ASN1_TLC *ctx)
+ ASN1_TLC *ctx, int depth)
{
int flags, aclass;
int ret;
long len;
const unsigned char *p, *q;
char exp_eoc;
if (!val)
return 0;
flags = tt->flags;
aclass = flags & ASN1_TFLG_TAG_CLASS;
p = *in;
/* Check if EXPLICIT tag expected */
if (flags & ASN1_TFLG_EXPTAG) {
char cst;
/*
* Need to work out amount of data available to the inner content and
* where it starts: so read in EXPLICIT header to get the info.
*/
ret = asn1_check_tlen(&len, NULL, NULL, &exp_eoc, &cst,
&p, inlen, tt->tag, aclass, opt, ctx);
q = p;
if (!ret) {
ASN1err(ASN1_F_ASN1_TEMPLATE_EX_D2I, ERR_R_NESTED_ASN1_ERROR);
return 0;
} else if (ret == -1)
return -1;
if (!cst) {
ASN1err(ASN1_F_ASN1_TEMPLATE_EX_D2I,
ASN1_R_EXPLICIT_TAG_NOT_CONSTRUCTED);
return 0;
}
/* We've found the field so it can't be OPTIONAL now */
- ret = asn1_template_noexp_d2i(val, &p, len, tt, 0, ctx);
+ ret = asn1_template_noexp_d2i(val, &p, len, tt, 0, ctx, depth);
if (!ret) {
ASN1err(ASN1_F_ASN1_TEMPLATE_EX_D2I, ERR_R_NESTED_ASN1_ERROR);
return 0;
}
/* We read the field in OK so update length */
len -= p - q;
if (exp_eoc) {
/* If NDEF we must have an EOC here */
if (!asn1_check_eoc(&p, len)) {
ASN1err(ASN1_F_ASN1_TEMPLATE_EX_D2I, ASN1_R_MISSING_EOC);
goto err;
}
} else {
/*
* Otherwise we must hit the EXPLICIT tag end or its an error
*/
if (len) {
ASN1err(ASN1_F_ASN1_TEMPLATE_EX_D2I,
ASN1_R_EXPLICIT_LENGTH_MISMATCH);
goto err;
}
}
} else
- return asn1_template_noexp_d2i(val, in, inlen, tt, opt, ctx);
+ return asn1_template_noexp_d2i(val, in, inlen, tt, opt, ctx, depth);
*in = p;
return 1;
err:
ASN1_template_free(val, tt);
return 0;
}
static int asn1_template_noexp_d2i(ASN1_VALUE **val,
const unsigned char **in, long len,
const ASN1_TEMPLATE *tt, char opt,
- ASN1_TLC *ctx)
+ ASN1_TLC *ctx, int depth)
{
int flags, aclass;
int ret;
const unsigned char *p, *q;
if (!val)
return 0;
flags = tt->flags;
aclass = flags & ASN1_TFLG_TAG_CLASS;
p = *in;
q = p;
if (flags & ASN1_TFLG_SK_MASK) {
/* SET OF, SEQUENCE OF */
int sktag, skaclass;
char sk_eoc;
/* First work out expected inner tag value */
if (flags & ASN1_TFLG_IMPTAG) {
sktag = tt->tag;
skaclass = aclass;
} else {
skaclass = V_ASN1_UNIVERSAL;
if (flags & ASN1_TFLG_SET_OF)
sktag = V_ASN1_SET;
else
sktag = V_ASN1_SEQUENCE;
}
/* Get the tag */
ret = asn1_check_tlen(&len, NULL, NULL, &sk_eoc, NULL,
&p, len, sktag, skaclass, opt, ctx);
if (!ret) {
ASN1err(ASN1_F_ASN1_TEMPLATE_NOEXP_D2I, ERR_R_NESTED_ASN1_ERROR);
return 0;
} else if (ret == -1)
return -1;
if (!*val)
*val = (ASN1_VALUE *)sk_new_null();
else {
/*
* We've got a valid STACK: free up any items present
*/
STACK_OF(ASN1_VALUE) *sktmp = (STACK_OF(ASN1_VALUE) *)*val;
ASN1_VALUE *vtmp;
while (sk_ASN1_VALUE_num(sktmp) > 0) {
vtmp = sk_ASN1_VALUE_pop(sktmp);
ASN1_item_ex_free(&vtmp, ASN1_ITEM_ptr(tt->item));
}
}
if (!*val) {
ASN1err(ASN1_F_ASN1_TEMPLATE_NOEXP_D2I, ERR_R_MALLOC_FAILURE);
goto err;
}
/* Read as many items as we can */
while (len > 0) {
ASN1_VALUE *skfield;
q = p;
/* See if EOC found */
if (asn1_check_eoc(&p, len)) {
if (!sk_eoc) {
ASN1err(ASN1_F_ASN1_TEMPLATE_NOEXP_D2I,
ASN1_R_UNEXPECTED_EOC);
goto err;
}
len -= p - q;
sk_eoc = 0;
break;
}
skfield = NULL;
- if (!ASN1_item_ex_d2i(&skfield, &p, len,
- ASN1_ITEM_ptr(tt->item), -1, 0, 0, ctx)) {
+ if (!asn1_item_ex_d2i(&skfield, &p, len, ASN1_ITEM_ptr(tt->item),
+ -1, 0, 0, ctx, depth)) {
ASN1err(ASN1_F_ASN1_TEMPLATE_NOEXP_D2I,
ERR_R_NESTED_ASN1_ERROR);
goto err;
}
len -= p - q;
if (!sk_ASN1_VALUE_push((STACK_OF(ASN1_VALUE) *)*val, skfield)) {
ASN1_item_ex_free(&skfield, ASN1_ITEM_ptr(tt->item));
ASN1err(ASN1_F_ASN1_TEMPLATE_NOEXP_D2I, ERR_R_MALLOC_FAILURE);
goto err;
}
}
if (sk_eoc) {
ASN1err(ASN1_F_ASN1_TEMPLATE_NOEXP_D2I, ASN1_R_MISSING_EOC);
goto err;
}
} else if (flags & ASN1_TFLG_IMPTAG) {
/* IMPLICIT tagging */
- ret = ASN1_item_ex_d2i(val, &p, len,
- ASN1_ITEM_ptr(tt->item), tt->tag, aclass, opt,
- ctx);
+ ret = asn1_item_ex_d2i(val, &p, len, ASN1_ITEM_ptr(tt->item), tt->tag,
+ aclass, opt, ctx, depth);
if (!ret) {
ASN1err(ASN1_F_ASN1_TEMPLATE_NOEXP_D2I, ERR_R_NESTED_ASN1_ERROR);
goto err;
} else if (ret == -1)
return -1;
} else {
/* Nothing special */
- ret = ASN1_item_ex_d2i(val, &p, len, ASN1_ITEM_ptr(tt->item),
- -1, tt->flags & ASN1_TFLG_COMBINE, opt, ctx);
+ ret = asn1_item_ex_d2i(val, &p, len, ASN1_ITEM_ptr(tt->item),
+ -1, tt->flags & ASN1_TFLG_COMBINE, opt, ctx,
+ depth);
if (!ret) {
ASN1err(ASN1_F_ASN1_TEMPLATE_NOEXP_D2I, ERR_R_NESTED_ASN1_ERROR);
goto err;
} else if (ret == -1)
return -1;
}
*in = p;
return 1;
err:
ASN1_template_free(val, tt);
return 0;
}
static int asn1_d2i_ex_primitive(ASN1_VALUE **pval,
const unsigned char **in, long inlen,
const ASN1_ITEM *it,
int tag, int aclass, char opt, ASN1_TLC *ctx)
{
int ret = 0, utype;
long plen;
char cst, inf, free_cont = 0;
const unsigned char *p;
BUF_MEM buf = { 0, NULL, 0 };
const unsigned char *cont = NULL;
long len;
if (!pval) {
ASN1err(ASN1_F_ASN1_D2I_EX_PRIMITIVE, ASN1_R_ILLEGAL_NULL);
return 0; /* Should never happen */
}
if (it->itype == ASN1_ITYPE_MSTRING) {
utype = tag;
tag = -1;
} else
utype = it->utype;
if (utype == V_ASN1_ANY) {
/* If type is ANY need to figure out type from tag */
unsigned char oclass;
if (tag >= 0) {
ASN1err(ASN1_F_ASN1_D2I_EX_PRIMITIVE, ASN1_R_ILLEGAL_TAGGED_ANY);
return 0;
}
if (opt) {
ASN1err(ASN1_F_ASN1_D2I_EX_PRIMITIVE,
ASN1_R_ILLEGAL_OPTIONAL_ANY);
return 0;
}
p = *in;
ret = asn1_check_tlen(NULL, &utype, &oclass, NULL, NULL,
&p, inlen, -1, 0, 0, ctx);
if (!ret) {
ASN1err(ASN1_F_ASN1_D2I_EX_PRIMITIVE, ERR_R_NESTED_ASN1_ERROR);
return 0;
}
if (oclass != V_ASN1_UNIVERSAL)
utype = V_ASN1_OTHER;
}
if (tag == -1) {
tag = utype;
aclass = V_ASN1_UNIVERSAL;
}
p = *in;
/* Check header */
ret = asn1_check_tlen(&plen, NULL, NULL, &inf, &cst,
&p, inlen, tag, aclass, opt, ctx);
if (!ret) {
ASN1err(ASN1_F_ASN1_D2I_EX_PRIMITIVE, ERR_R_NESTED_ASN1_ERROR);
return 0;
} else if (ret == -1)
return -1;
ret = 0;
/* SEQUENCE, SET and "OTHER" are left in encoded form */
if ((utype == V_ASN1_SEQUENCE)
|| (utype == V_ASN1_SET) || (utype == V_ASN1_OTHER)) {
/*
* Clear context cache for type OTHER because the auto clear when we
* have a exact match wont work
*/
if (utype == V_ASN1_OTHER) {
asn1_tlc_clear(ctx);
}
/* SEQUENCE and SET must be constructed */
else if (!cst) {
ASN1err(ASN1_F_ASN1_D2I_EX_PRIMITIVE,
ASN1_R_TYPE_NOT_CONSTRUCTED);
return 0;
}
cont = *in;
/* If indefinite length constructed find the real end */
if (inf) {
if (!asn1_find_end(&p, plen, inf))
goto err;
len = p - cont;
} else {
len = p - cont + plen;
p += plen;
}
} else if (cst) {
if (utype == V_ASN1_NULL || utype == V_ASN1_BOOLEAN
|| utype == V_ASN1_OBJECT || utype == V_ASN1_INTEGER
|| utype == V_ASN1_ENUMERATED) {
ASN1err(ASN1_F_ASN1_D2I_EX_PRIMITIVE, ASN1_R_TYPE_NOT_PRIMITIVE);
return 0;
}
/* Free any returned 'buf' content */
free_cont = 1;
/*
* Should really check the internal tags are correct but some things
* may get this wrong. The relevant specs say that constructed string
* types should be OCTET STRINGs internally irrespective of the type.
* So instead just check for UNIVERSAL class and ignore the tag.
*/
if (!asn1_collect(&buf, &p, plen, inf, -1, V_ASN1_UNIVERSAL, 0)) {
goto err;
}
len = buf.length;
/* Append a final null to string */
if (!BUF_MEM_grow_clean(&buf, len + 1)) {
ASN1err(ASN1_F_ASN1_D2I_EX_PRIMITIVE, ERR_R_MALLOC_FAILURE);
goto err;
}
buf.data[len] = 0;
cont = (const unsigned char *)buf.data;
} else {
cont = p;
len = plen;
p += plen;
}
/* We now have content length and type: translate into a structure */
/* asn1_ex_c2i may reuse allocated buffer, and so sets free_cont to 0 */
if (!asn1_ex_c2i(pval, cont, len, utype, &free_cont, it))
goto err;
*in = p;
ret = 1;
err:
if (free_cont && buf.data)
OPENSSL_free(buf.data);
return ret;
}
/* Translate ASN1 content octets into a structure */
int asn1_ex_c2i(ASN1_VALUE **pval, const unsigned char *cont, int len,
int utype, char *free_cont, const ASN1_ITEM *it)
{
ASN1_VALUE **opval = NULL;
ASN1_STRING *stmp;
ASN1_TYPE *typ = NULL;
int ret = 0;
const ASN1_PRIMITIVE_FUNCS *pf;
ASN1_INTEGER **tint;
pf = it->funcs;
if (pf && pf->prim_c2i)
return pf->prim_c2i(pval, cont, len, utype, free_cont, it);
/* If ANY type clear type and set pointer to internal value */
if (it->utype == V_ASN1_ANY) {
if (!*pval) {
typ = ASN1_TYPE_new();
if (typ == NULL)
goto err;
*pval = (ASN1_VALUE *)typ;
} else
typ = (ASN1_TYPE *)*pval;
if (utype != typ->type)
ASN1_TYPE_set(typ, utype, NULL);
opval = pval;
pval = &typ->value.asn1_value;
}
switch (utype) {
case V_ASN1_OBJECT:
if (!c2i_ASN1_OBJECT((ASN1_OBJECT **)pval, &cont, len))
goto err;
break;
case V_ASN1_NULL:
if (len) {
ASN1err(ASN1_F_ASN1_EX_C2I, ASN1_R_NULL_IS_WRONG_LENGTH);
goto err;
}
*pval = (ASN1_VALUE *)1;
break;
case V_ASN1_BOOLEAN:
if (len != 1) {
ASN1err(ASN1_F_ASN1_EX_C2I, ASN1_R_BOOLEAN_IS_WRONG_LENGTH);
goto err;
} else {
ASN1_BOOLEAN *tbool;
tbool = (ASN1_BOOLEAN *)pval;
*tbool = *cont;
}
break;
case V_ASN1_BIT_STRING:
if (!c2i_ASN1_BIT_STRING((ASN1_BIT_STRING **)pval, &cont, len))
goto err;
break;
case V_ASN1_INTEGER:
case V_ASN1_ENUMERATED:
tint = (ASN1_INTEGER **)pval;
if (!c2i_ASN1_INTEGER(tint, &cont, len))
goto err;
/* Fixup type to match the expected form */
(*tint)->type = utype | ((*tint)->type & V_ASN1_NEG);
break;
case V_ASN1_OCTET_STRING:
case V_ASN1_NUMERICSTRING:
case V_ASN1_PRINTABLESTRING:
case V_ASN1_T61STRING:
case V_ASN1_VIDEOTEXSTRING:
case V_ASN1_IA5STRING:
case V_ASN1_UTCTIME:
case V_ASN1_GENERALIZEDTIME:
case V_ASN1_GRAPHICSTRING:
case V_ASN1_VISIBLESTRING:
case V_ASN1_GENERALSTRING:
case V_ASN1_UNIVERSALSTRING:
case V_ASN1_BMPSTRING:
case V_ASN1_UTF8STRING:
case V_ASN1_OTHER:
case V_ASN1_SET:
case V_ASN1_SEQUENCE:
default:
if (utype == V_ASN1_BMPSTRING && (len & 1)) {
ASN1err(ASN1_F_ASN1_EX_C2I, ASN1_R_BMPSTRING_IS_WRONG_LENGTH);
goto err;
}
if (utype == V_ASN1_UNIVERSALSTRING && (len & 3)) {
ASN1err(ASN1_F_ASN1_EX_C2I,
ASN1_R_UNIVERSALSTRING_IS_WRONG_LENGTH);
goto err;
}
/* All based on ASN1_STRING and handled the same */
if (!*pval) {
stmp = ASN1_STRING_type_new(utype);
if (!stmp) {
ASN1err(ASN1_F_ASN1_EX_C2I, ERR_R_MALLOC_FAILURE);
goto err;
}
*pval = (ASN1_VALUE *)stmp;
} else {
stmp = (ASN1_STRING *)*pval;
stmp->type = utype;
}
/* If we've already allocated a buffer use it */
if (*free_cont) {
if (stmp->data)
OPENSSL_free(stmp->data);
stmp->data = (unsigned char *)cont; /* UGLY CAST! RL */
stmp->length = len;
*free_cont = 0;
} else {
if (!ASN1_STRING_set(stmp, cont, len)) {
ASN1err(ASN1_F_ASN1_EX_C2I, ERR_R_MALLOC_FAILURE);
ASN1_STRING_free(stmp);
*pval = NULL;
goto err;
}
}
break;
}
/* If ASN1_ANY and NULL type fix up value */
if (typ && (utype == V_ASN1_NULL))
typ->value.ptr = NULL;
ret = 1;
err:
if (!ret) {
ASN1_TYPE_free(typ);
if (opval)
*opval = NULL;
}
return ret;
}
/*
* This function finds the end of an ASN1 structure when passed its maximum
* length, whether it is indefinite length and a pointer to the content. This
* is more efficient than calling asn1_collect because it does not recurse on
* each indefinite length header.
*/
static int asn1_find_end(const unsigned char **in, long len, char inf)
{
int expected_eoc;
long plen;
const unsigned char *p = *in, *q;
/* If not indefinite length constructed just add length */
if (inf == 0) {
*in += len;
return 1;
}
expected_eoc = 1;
/*
* Indefinite length constructed form. Find the end when enough EOCs are
* found. If more indefinite length constructed headers are encountered
* increment the expected eoc count otherwise just skip to the end of the
* data.
*/
while (len > 0) {
if (asn1_check_eoc(&p, len)) {
expected_eoc--;
if (expected_eoc == 0)
break;
len -= 2;
continue;
}
q = p;
/* Just read in a header: only care about the length */
if (!asn1_check_tlen(&plen, NULL, NULL, &inf, NULL, &p, len,
-1, 0, 0, NULL)) {
ASN1err(ASN1_F_ASN1_FIND_END, ERR_R_NESTED_ASN1_ERROR);
return 0;
}
if (inf)
expected_eoc++;
else
p += plen;
len -= p - q;
}
if (expected_eoc) {
ASN1err(ASN1_F_ASN1_FIND_END, ASN1_R_MISSING_EOC);
return 0;
}
*in = p;
return 1;
}
/*
* This function collects the asn1 data from a constructred string type into
* a buffer. The values of 'in' and 'len' should refer to the contents of the
* constructed type and 'inf' should be set if it is indefinite length.
*/
#ifndef ASN1_MAX_STRING_NEST
/*
* This determines how many levels of recursion are permitted in ASN1 string
* types. If it is not limited stack overflows can occur. If set to zero no
* recursion is allowed at all. Although zero should be adequate examples
* exist that require a value of 1. So 5 should be more than enough.
*/
# define ASN1_MAX_STRING_NEST 5
#endif
static int asn1_collect(BUF_MEM *buf, const unsigned char **in, long len,
char inf, int tag, int aclass, int depth)
{
const unsigned char *p, *q;
long plen;
char cst, ininf;
p = *in;
inf &= 1;
/*
* If no buffer and not indefinite length constructed just pass over the
* encoded data
*/
if (!buf && !inf) {
*in += len;
return 1;
}
while (len > 0) {
q = p;
/* Check for EOC */
if (asn1_check_eoc(&p, len)) {
/*
* EOC is illegal outside indefinite length constructed form
*/
if (!inf) {
ASN1err(ASN1_F_ASN1_COLLECT, ASN1_R_UNEXPECTED_EOC);
return 0;
}
inf = 0;
break;
}
if (!asn1_check_tlen(&plen, NULL, NULL, &ininf, &cst, &p,
len, tag, aclass, 0, NULL)) {
ASN1err(ASN1_F_ASN1_COLLECT, ERR_R_NESTED_ASN1_ERROR);
return 0;
}
/* If indefinite length constructed update max length */
if (cst) {
if (depth >= ASN1_MAX_STRING_NEST) {
ASN1err(ASN1_F_ASN1_COLLECT, ASN1_R_NESTED_ASN1_STRING);
return 0;
}
if (!asn1_collect(buf, &p, plen, ininf, tag, aclass, depth + 1))
return 0;
} else if (plen && !collect_data(buf, &p, plen))
return 0;
len -= p - q;
}
if (inf) {
ASN1err(ASN1_F_ASN1_COLLECT, ASN1_R_MISSING_EOC);
return 0;
}
*in = p;
return 1;
}
static int collect_data(BUF_MEM *buf, const unsigned char **p, long plen)
{
int len;
if (buf) {
len = buf->length;
if (!BUF_MEM_grow_clean(buf, len + plen)) {
ASN1err(ASN1_F_COLLECT_DATA, ERR_R_MALLOC_FAILURE);
return 0;
}
memcpy(buf->data + len, *p, plen);
}
*p += plen;
return 1;
}
/* Check for ASN1 EOC and swallow it if found */
static int asn1_check_eoc(const unsigned char **in, long len)
{
const unsigned char *p;
if (len < 2)
return 0;
p = *in;
if (!p[0] && !p[1]) {
*in += 2;
return 1;
}
return 0;
}
/*
* Check an ASN1 tag and length: a bit like ASN1_get_object but it sets the
* length for indefinite length constructed form, we don't know the exact
* length but we can set an upper bound to the amount of data available minus
* the header length just read.
*/
static int asn1_check_tlen(long *olen, int *otag, unsigned char *oclass,
char *inf, char *cst,
const unsigned char **in, long len,
int exptag, int expclass, char opt, ASN1_TLC *ctx)
{
int i;
int ptag, pclass;
long plen;
const unsigned char *p, *q;
p = *in;
q = p;
if (ctx && ctx->valid) {
i = ctx->ret;
plen = ctx->plen;
pclass = ctx->pclass;
ptag = ctx->ptag;
p += ctx->hdrlen;
} else {
i = ASN1_get_object(&p, &plen, &ptag, &pclass, len);
if (ctx) {
ctx->ret = i;
ctx->plen = plen;
ctx->pclass = pclass;
ctx->ptag = ptag;
ctx->hdrlen = p - q;
ctx->valid = 1;
/*
* If definite length, and no error, length + header can't exceed
* total amount of data available.
*/
if (!(i & 0x81) && ((plen + ctx->hdrlen) > len)) {
ASN1err(ASN1_F_ASN1_CHECK_TLEN, ASN1_R_TOO_LONG);
asn1_tlc_clear(ctx);
return 0;
}
}
}
if (i & 0x80) {
ASN1err(ASN1_F_ASN1_CHECK_TLEN, ASN1_R_BAD_OBJECT_HEADER);
asn1_tlc_clear(ctx);
return 0;
}
if (exptag >= 0) {
if ((exptag != ptag) || (expclass != pclass)) {
/*
* If type is OPTIONAL, not an error: indicate missing type.
*/
if (opt)
return -1;
asn1_tlc_clear(ctx);
ASN1err(ASN1_F_ASN1_CHECK_TLEN, ASN1_R_WRONG_TAG);
return 0;
}
/*
* We have a tag and class match: assume we are going to do something
* with it
*/
asn1_tlc_clear(ctx);
}
if (i & 1)
plen = len - (p - q);
if (inf)
*inf = i & 1;
if (cst)
*cst = i & V_ASN1_CONSTRUCTED;
if (olen)
*olen = plen;
if (oclass)
*oclass = pclass;
if (otag)
*otag = ptag;
*in = p;
return 1;
}
diff --git a/crypto/asn1/tasn_prn.c b/crypto/asn1/tasn_prn.c
index f628caddbd05..e93fd11f4740 100644
--- a/crypto/asn1/tasn_prn.c
+++ b/crypto/asn1/tasn_prn.c
@@ -1,593 +1,593 @@
/* tasn_prn.c */
/*
* Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL project
* 2000.
*/
/* ====================================================================
* Copyright (c) 2000,2005 The OpenSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* licensing@OpenSSL.org.
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*
* This product includes cryptographic software written by Eric Young
* (eay@cryptsoft.com). This product includes software written by Tim
* Hudson (tjh@cryptsoft.com).
*
*/
#include <stddef.h>
#include "cryptlib.h"
#include <openssl/asn1.h>
#include <openssl/asn1t.h>
#include <openssl/objects.h>
#include <openssl/buffer.h>
#include <openssl/err.h>
#include <openssl/x509v3.h>
#include "asn1_locl.h"
/*
* Print routines.
*/
/* ASN1_PCTX routines */
ASN1_PCTX default_pctx = {
ASN1_PCTX_FLAGS_SHOW_ABSENT, /* flags */
0, /* nm_flags */
0, /* cert_flags */
0, /* oid_flags */
0 /* str_flags */
};
ASN1_PCTX *ASN1_PCTX_new(void)
{
ASN1_PCTX *ret;
ret = OPENSSL_malloc(sizeof(ASN1_PCTX));
if (ret == NULL) {
ASN1err(ASN1_F_ASN1_PCTX_NEW, ERR_R_MALLOC_FAILURE);
return NULL;
}
ret->flags = 0;
ret->nm_flags = 0;
ret->cert_flags = 0;
ret->oid_flags = 0;
ret->str_flags = 0;
return ret;
}
void ASN1_PCTX_free(ASN1_PCTX *p)
{
OPENSSL_free(p);
}
unsigned long ASN1_PCTX_get_flags(ASN1_PCTX *p)
{
return p->flags;
}
void ASN1_PCTX_set_flags(ASN1_PCTX *p, unsigned long flags)
{
p->flags = flags;
}
unsigned long ASN1_PCTX_get_nm_flags(ASN1_PCTX *p)
{
return p->nm_flags;
}
void ASN1_PCTX_set_nm_flags(ASN1_PCTX *p, unsigned long flags)
{
p->nm_flags = flags;
}
unsigned long ASN1_PCTX_get_cert_flags(ASN1_PCTX *p)
{
return p->cert_flags;
}
void ASN1_PCTX_set_cert_flags(ASN1_PCTX *p, unsigned long flags)
{
p->cert_flags = flags;
}
unsigned long ASN1_PCTX_get_oid_flags(ASN1_PCTX *p)
{
return p->oid_flags;
}
void ASN1_PCTX_set_oid_flags(ASN1_PCTX *p, unsigned long flags)
{
p->oid_flags = flags;
}
unsigned long ASN1_PCTX_get_str_flags(ASN1_PCTX *p)
{
return p->str_flags;
}
void ASN1_PCTX_set_str_flags(ASN1_PCTX *p, unsigned long flags)
{
p->str_flags = flags;
}
/* Main print routines */
static int asn1_item_print_ctx(BIO *out, ASN1_VALUE **fld, int indent,
const ASN1_ITEM *it,
const char *fname, const char *sname,
int nohdr, const ASN1_PCTX *pctx);
int asn1_template_print_ctx(BIO *out, ASN1_VALUE **fld, int indent,
const ASN1_TEMPLATE *tt, const ASN1_PCTX *pctx);
static int asn1_primitive_print(BIO *out, ASN1_VALUE **fld,
const ASN1_ITEM *it, int indent,
const char *fname, const char *sname,
const ASN1_PCTX *pctx);
static int asn1_print_fsname(BIO *out, int indent,
const char *fname, const char *sname,
const ASN1_PCTX *pctx);
int ASN1_item_print(BIO *out, ASN1_VALUE *ifld, int indent,
const ASN1_ITEM *it, const ASN1_PCTX *pctx)
{
const char *sname;
if (pctx == NULL)
pctx = &default_pctx;
if (pctx->flags & ASN1_PCTX_FLAGS_NO_STRUCT_NAME)
sname = NULL;
else
sname = it->sname;
return asn1_item_print_ctx(out, &ifld, indent, it, NULL, sname, 0, pctx);
}
static int asn1_item_print_ctx(BIO *out, ASN1_VALUE **fld, int indent,
const ASN1_ITEM *it,
const char *fname, const char *sname,
int nohdr, const ASN1_PCTX *pctx)
{
const ASN1_TEMPLATE *tt;
const ASN1_EXTERN_FUNCS *ef;
ASN1_VALUE **tmpfld;
const ASN1_AUX *aux = it->funcs;
ASN1_aux_cb *asn1_cb;
ASN1_PRINT_ARG parg;
int i;
if (aux && aux->asn1_cb) {
parg.out = out;
parg.indent = indent;
parg.pctx = pctx;
asn1_cb = aux->asn1_cb;
} else
asn1_cb = 0;
if (((it->itype != ASN1_ITYPE_PRIMITIVE)
|| (it->utype != V_ASN1_BOOLEAN)) && *fld == NULL) {
if (pctx->flags & ASN1_PCTX_FLAGS_SHOW_ABSENT) {
if (!nohdr && !asn1_print_fsname(out, indent, fname, sname, pctx))
return 0;
if (BIO_puts(out, "<ABSENT>\n") <= 0)
return 0;
}
return 1;
}
switch (it->itype) {
case ASN1_ITYPE_PRIMITIVE:
if (it->templates) {
if (!asn1_template_print_ctx(out, fld, indent,
it->templates, pctx))
return 0;
break;
}
/* fall thru */
case ASN1_ITYPE_MSTRING:
if (!asn1_primitive_print(out, fld, it, indent, fname, sname, pctx))
return 0;
break;
case ASN1_ITYPE_EXTERN:
if (!nohdr && !asn1_print_fsname(out, indent, fname, sname, pctx))
return 0;
/* Use new style print routine if possible */
ef = it->funcs;
if (ef && ef->asn1_ex_print) {
i = ef->asn1_ex_print(out, fld, indent, "", pctx);
if (!i)
return 0;
if ((i == 2) && (BIO_puts(out, "\n") <= 0))
return 0;
return 1;
} else if (sname &&
BIO_printf(out, ":EXTERNAL TYPE %s\n", sname) <= 0)
return 0;
break;
case ASN1_ITYPE_CHOICE:
#if 0
if (!nohdr && !asn1_print_fsname(out, indent, fname, sname, pctx))
return 0;
#endif
/* CHOICE type, get selector */
i = asn1_get_choice_selector(fld, it);
/* This should never happen... */
if ((i < 0) || (i >= it->tcount)) {
if (BIO_printf(out, "ERROR: selector [%d] invalid\n", i) <= 0)
return 0;
return 1;
}
tt = it->templates + i;
tmpfld = asn1_get_field_ptr(fld, tt);
if (!asn1_template_print_ctx(out, tmpfld, indent, tt, pctx))
return 0;
break;
case ASN1_ITYPE_SEQUENCE:
case ASN1_ITYPE_NDEF_SEQUENCE:
if (!nohdr && !asn1_print_fsname(out, indent, fname, sname, pctx))
return 0;
if (fname || sname) {
if (pctx->flags & ASN1_PCTX_FLAGS_SHOW_SEQUENCE) {
if (BIO_puts(out, " {\n") <= 0)
return 0;
} else {
if (BIO_puts(out, "\n") <= 0)
return 0;
}
}
if (asn1_cb) {
i = asn1_cb(ASN1_OP_PRINT_PRE, fld, it, &parg);
if (i == 0)
return 0;
if (i == 2)
return 1;
}
/* Print each field entry */
for (i = 0, tt = it->templates; i < it->tcount; i++, tt++) {
const ASN1_TEMPLATE *seqtt;
seqtt = asn1_do_adb(fld, tt, 1);
if (!seqtt)
return 0;
tmpfld = asn1_get_field_ptr(fld, seqtt);
if (!asn1_template_print_ctx(out, tmpfld,
indent + 2, seqtt, pctx))
return 0;
}
if (pctx->flags & ASN1_PCTX_FLAGS_SHOW_SEQUENCE) {
if (BIO_printf(out, "%*s}\n", indent, "") < 0)
return 0;
}
if (asn1_cb) {
i = asn1_cb(ASN1_OP_PRINT_POST, fld, it, &parg);
if (i == 0)
return 0;
}
break;
default:
BIO_printf(out, "Unprocessed type %d\n", it->itype);
return 0;
}
return 1;
}
int asn1_template_print_ctx(BIO *out, ASN1_VALUE **fld, int indent,
const ASN1_TEMPLATE *tt, const ASN1_PCTX *pctx)
{
int i, flags;
const char *sname, *fname;
flags = tt->flags;
if (pctx->flags & ASN1_PCTX_FLAGS_SHOW_FIELD_STRUCT_NAME)
sname = ASN1_ITEM_ptr(tt->item)->sname;
else
sname = NULL;
if (pctx->flags & ASN1_PCTX_FLAGS_NO_FIELD_NAME)
fname = NULL;
else
fname = tt->field_name;
if (flags & ASN1_TFLG_SK_MASK) {
char *tname;
ASN1_VALUE *skitem;
STACK_OF(ASN1_VALUE) *stack;
/* SET OF, SEQUENCE OF */
if (fname) {
if (pctx->flags & ASN1_PCTX_FLAGS_SHOW_SSOF) {
if (flags & ASN1_TFLG_SET_OF)
tname = "SET";
else
tname = "SEQUENCE";
if (BIO_printf(out, "%*s%s OF %s {\n",
indent, "", tname, tt->field_name) <= 0)
return 0;
} else if (BIO_printf(out, "%*s%s:\n", indent, "", fname) <= 0)
return 0;
}
stack = (STACK_OF(ASN1_VALUE) *)*fld;
for (i = 0; i < sk_ASN1_VALUE_num(stack); i++) {
if ((i > 0) && (BIO_puts(out, "\n") <= 0))
return 0;
skitem = sk_ASN1_VALUE_value(stack, i);
if (!asn1_item_print_ctx(out, &skitem, indent + 2,
ASN1_ITEM_ptr(tt->item), NULL, NULL, 1,
pctx))
return 0;
}
if (!i && BIO_printf(out, "%*s<EMPTY>\n", indent + 2, "") <= 0)
return 0;
if (pctx->flags & ASN1_PCTX_FLAGS_SHOW_SEQUENCE) {
if (BIO_printf(out, "%*s}\n", indent, "") <= 0)
return 0;
}
return 1;
}
return asn1_item_print_ctx(out, fld, indent, ASN1_ITEM_ptr(tt->item),
fname, sname, 0, pctx);
}
static int asn1_print_fsname(BIO *out, int indent,
const char *fname, const char *sname,
const ASN1_PCTX *pctx)
{
static char spaces[] = " ";
const int nspaces = sizeof(spaces) - 1;
#if 0
if (!sname && !fname)
return 1;
#endif
while (indent > nspaces) {
if (BIO_write(out, spaces, nspaces) != nspaces)
return 0;
indent -= nspaces;
}
if (BIO_write(out, spaces, indent) != indent)
return 0;
if (pctx->flags & ASN1_PCTX_FLAGS_NO_STRUCT_NAME)
sname = NULL;
if (pctx->flags & ASN1_PCTX_FLAGS_NO_FIELD_NAME)
fname = NULL;
if (!sname && !fname)
return 1;
if (fname) {
if (BIO_puts(out, fname) <= 0)
return 0;
}
if (sname) {
if (fname) {
if (BIO_printf(out, " (%s)", sname) <= 0)
return 0;
} else {
if (BIO_puts(out, sname) <= 0)
return 0;
}
}
if (BIO_write(out, ": ", 2) != 2)
return 0;
return 1;
}
static int asn1_print_boolean_ctx(BIO *out, int boolval,
const ASN1_PCTX *pctx)
{
const char *str;
switch (boolval) {
case -1:
str = "BOOL ABSENT";
break;
case 0:
str = "FALSE";
break;
default:
str = "TRUE";
break;
}
if (BIO_puts(out, str) <= 0)
return 0;
return 1;
}
static int asn1_print_integer_ctx(BIO *out, ASN1_INTEGER *str,
const ASN1_PCTX *pctx)
{
char *s;
int ret = 1;
s = i2s_ASN1_INTEGER(NULL, str);
if (s == NULL)
return 0;
if (BIO_puts(out, s) <= 0)
ret = 0;
OPENSSL_free(s);
return ret;
}
static int asn1_print_oid_ctx(BIO *out, const ASN1_OBJECT *oid,
const ASN1_PCTX *pctx)
{
char objbuf[80];
const char *ln;
ln = OBJ_nid2ln(OBJ_obj2nid(oid));
if (!ln)
ln = "";
- OBJ_obj2txt(objbuf, sizeof objbuf, oid, 1);
+ OBJ_obj2txt(objbuf, sizeof(objbuf), oid, 1);
if (BIO_printf(out, "%s (%s)", ln, objbuf) <= 0)
return 0;
return 1;
}
static int asn1_print_obstring_ctx(BIO *out, ASN1_STRING *str, int indent,
const ASN1_PCTX *pctx)
{
if (str->type == V_ASN1_BIT_STRING) {
if (BIO_printf(out, " (%ld unused bits)\n", str->flags & 0x7) <= 0)
return 0;
} else if (BIO_puts(out, "\n") <= 0)
return 0;
if ((str->length > 0)
&& BIO_dump_indent(out, (char *)str->data, str->length,
indent + 2) <= 0)
return 0;
return 1;
}
static int asn1_primitive_print(BIO *out, ASN1_VALUE **fld,
const ASN1_ITEM *it, int indent,
const char *fname, const char *sname,
const ASN1_PCTX *pctx)
{
long utype;
ASN1_STRING *str;
int ret = 1, needlf = 1;
const char *pname;
const ASN1_PRIMITIVE_FUNCS *pf;
pf = it->funcs;
if (!asn1_print_fsname(out, indent, fname, sname, pctx))
return 0;
if (pf && pf->prim_print)
return pf->prim_print(out, fld, it, indent, pctx);
if (it->itype == ASN1_ITYPE_MSTRING) {
str = (ASN1_STRING *)*fld;
utype = str->type & ~V_ASN1_NEG;
} else {
utype = it->utype;
if (utype == V_ASN1_BOOLEAN)
str = NULL;
else
str = (ASN1_STRING *)*fld;
}
if (utype == V_ASN1_ANY) {
ASN1_TYPE *atype = (ASN1_TYPE *)*fld;
utype = atype->type;
fld = &atype->value.asn1_value;
str = (ASN1_STRING *)*fld;
if (pctx->flags & ASN1_PCTX_FLAGS_NO_ANY_TYPE)
pname = NULL;
else
pname = ASN1_tag2str(utype);
} else {
if (pctx->flags & ASN1_PCTX_FLAGS_SHOW_TYPE)
pname = ASN1_tag2str(utype);
else
pname = NULL;
}
if (utype == V_ASN1_NULL) {
if (BIO_puts(out, "NULL\n") <= 0)
return 0;
return 1;
}
if (pname) {
if (BIO_puts(out, pname) <= 0)
return 0;
if (BIO_puts(out, ":") <= 0)
return 0;
}
switch (utype) {
case V_ASN1_BOOLEAN:
{
int boolval = *(int *)fld;
if (boolval == -1)
boolval = it->size;
ret = asn1_print_boolean_ctx(out, boolval, pctx);
}
break;
case V_ASN1_INTEGER:
case V_ASN1_ENUMERATED:
ret = asn1_print_integer_ctx(out, str, pctx);
break;
case V_ASN1_UTCTIME:
ret = ASN1_UTCTIME_print(out, str);
break;
case V_ASN1_GENERALIZEDTIME:
ret = ASN1_GENERALIZEDTIME_print(out, str);
break;
case V_ASN1_OBJECT:
ret = asn1_print_oid_ctx(out, (const ASN1_OBJECT *)*fld, pctx);
break;
case V_ASN1_OCTET_STRING:
case V_ASN1_BIT_STRING:
ret = asn1_print_obstring_ctx(out, str, indent, pctx);
needlf = 0;
break;
case V_ASN1_SEQUENCE:
case V_ASN1_SET:
case V_ASN1_OTHER:
if (BIO_puts(out, "\n") <= 0)
return 0;
if (ASN1_parse_dump(out, str->data, str->length, indent, 0) <= 0)
ret = 0;
needlf = 0;
break;
default:
ret = ASN1_STRING_print_ex(out, str, pctx->str_flags);
}
if (!ret)
return 0;
if (needlf && BIO_puts(out, "\n") <= 0)
return 0;
return 1;
}
diff --git a/crypto/bf/bftest.c b/crypto/bf/bftest.c
index 0b008f091cbf..bd20a8e2112e 100644
--- a/crypto/bf/bftest.c
+++ b/crypto/bf/bftest.c
@@ -1,538 +1,538 @@
/* crypto/bf/bftest.c */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
/*
* This has been a quickly hacked 'ideatest.c'. When I add tests for other
* RC2 modes, more of the code will be uncommented.
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <openssl/opensslconf.h> /* To see if OPENSSL_NO_BF is defined */
#include "../e_os.h"
#ifdef OPENSSL_NO_BF
int main(int argc, char *argv[])
{
printf("No BF support\n");
return (0);
}
#else
# include <openssl/blowfish.h>
# ifdef CHARSET_EBCDIC
# include <openssl/ebcdic.h>
# endif
static char *bf_key[2] = {
"abcdefghijklmnopqrstuvwxyz",
"Who is John Galt?"
};
/* big endian */
static BF_LONG bf_plain[2][2] = {
{0x424c4f57L, 0x46495348L},
{0xfedcba98L, 0x76543210L}
};
static BF_LONG bf_cipher[2][2] = {
{0x324ed0feL, 0xf413a203L},
{0xcc91732bL, 0x8022f684L}
};
/************/
/* Lets use the DES test vectors :-) */
# define NUM_TESTS 34
static unsigned char ecb_data[NUM_TESTS][8] = {
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF},
{0x30, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
{0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11},
{0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF},
{0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11},
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
{0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10},
{0x7C, 0xA1, 0x10, 0x45, 0x4A, 0x1A, 0x6E, 0x57},
{0x01, 0x31, 0xD9, 0x61, 0x9D, 0xC1, 0x37, 0x6E},
{0x07, 0xA1, 0x13, 0x3E, 0x4A, 0x0B, 0x26, 0x86},
{0x38, 0x49, 0x67, 0x4C, 0x26, 0x02, 0x31, 0x9E},
{0x04, 0xB9, 0x15, 0xBA, 0x43, 0xFE, 0xB5, 0xB6},
{0x01, 0x13, 0xB9, 0x70, 0xFD, 0x34, 0xF2, 0xCE},
{0x01, 0x70, 0xF1, 0x75, 0x46, 0x8F, 0xB5, 0xE6},
{0x43, 0x29, 0x7F, 0xAD, 0x38, 0xE3, 0x73, 0xFE},
{0x07, 0xA7, 0x13, 0x70, 0x45, 0xDA, 0x2A, 0x16},
{0x04, 0x68, 0x91, 0x04, 0xC2, 0xFD, 0x3B, 0x2F},
{0x37, 0xD0, 0x6B, 0xB5, 0x16, 0xCB, 0x75, 0x46},
{0x1F, 0x08, 0x26, 0x0D, 0x1A, 0xC2, 0x46, 0x5E},
{0x58, 0x40, 0x23, 0x64, 0x1A, 0xBA, 0x61, 0x76},
{0x02, 0x58, 0x16, 0x16, 0x46, 0x29, 0xB0, 0x07},
{0x49, 0x79, 0x3E, 0xBC, 0x79, 0xB3, 0x25, 0x8F},
{0x4F, 0xB0, 0x5E, 0x15, 0x15, 0xAB, 0x73, 0xA7},
{0x49, 0xE9, 0x5D, 0x6D, 0x4C, 0xA2, 0x29, 0xBF},
{0x01, 0x83, 0x10, 0xDC, 0x40, 0x9B, 0x26, 0xD6},
{0x1C, 0x58, 0x7F, 0x1C, 0x13, 0x92, 0x4F, 0xEF},
{0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01},
{0x1F, 0x1F, 0x1F, 0x1F, 0x0E, 0x0E, 0x0E, 0x0E},
{0xE0, 0xFE, 0xE0, 0xFE, 0xF1, 0xFE, 0xF1, 0xFE},
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF},
{0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF},
{0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10}
};
static unsigned char plain_data[NUM_TESTS][8] = {
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF},
{0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01},
{0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11},
{0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11},
{0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF},
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
{0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF},
{0x01, 0xA1, 0xD6, 0xD0, 0x39, 0x77, 0x67, 0x42},
{0x5C, 0xD5, 0x4C, 0xA8, 0x3D, 0xEF, 0x57, 0xDA},
{0x02, 0x48, 0xD4, 0x38, 0x06, 0xF6, 0x71, 0x72},
{0x51, 0x45, 0x4B, 0x58, 0x2D, 0xDF, 0x44, 0x0A},
{0x42, 0xFD, 0x44, 0x30, 0x59, 0x57, 0x7F, 0xA2},
{0x05, 0x9B, 0x5E, 0x08, 0x51, 0xCF, 0x14, 0x3A},
{0x07, 0x56, 0xD8, 0xE0, 0x77, 0x47, 0x61, 0xD2},
{0x76, 0x25, 0x14, 0xB8, 0x29, 0xBF, 0x48, 0x6A},
{0x3B, 0xDD, 0x11, 0x90, 0x49, 0x37, 0x28, 0x02},
{0x26, 0x95, 0x5F, 0x68, 0x35, 0xAF, 0x60, 0x9A},
{0x16, 0x4D, 0x5E, 0x40, 0x4F, 0x27, 0x52, 0x32},
{0x6B, 0x05, 0x6E, 0x18, 0x75, 0x9F, 0x5C, 0xCA},
{0x00, 0x4B, 0xD6, 0xEF, 0x09, 0x17, 0x60, 0x62},
{0x48, 0x0D, 0x39, 0x00, 0x6E, 0xE7, 0x62, 0xF2},
{0x43, 0x75, 0x40, 0xC8, 0x69, 0x8F, 0x3C, 0xFA},
{0x07, 0x2D, 0x43, 0xA0, 0x77, 0x07, 0x52, 0x92},
{0x02, 0xFE, 0x55, 0x77, 0x81, 0x17, 0xF1, 0x2A},
{0x1D, 0x9D, 0x5C, 0x50, 0x18, 0xF7, 0x28, 0xC2},
{0x30, 0x55, 0x32, 0x28, 0x6D, 0x6F, 0x29, 0x5A},
{0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF},
{0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF},
{0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF},
{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF},
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}
};
static unsigned char cipher_data[NUM_TESTS][8] = {
{0x4E, 0xF9, 0x97, 0x45, 0x61, 0x98, 0xDD, 0x78},
{0x51, 0x86, 0x6F, 0xD5, 0xB8, 0x5E, 0xCB, 0x8A},
{0x7D, 0x85, 0x6F, 0x9A, 0x61, 0x30, 0x63, 0xF2},
{0x24, 0x66, 0xDD, 0x87, 0x8B, 0x96, 0x3C, 0x9D},
{0x61, 0xF9, 0xC3, 0x80, 0x22, 0x81, 0xB0, 0x96},
{0x7D, 0x0C, 0xC6, 0x30, 0xAF, 0xDA, 0x1E, 0xC7},
{0x4E, 0xF9, 0x97, 0x45, 0x61, 0x98, 0xDD, 0x78},
{0x0A, 0xCE, 0xAB, 0x0F, 0xC6, 0xA0, 0xA2, 0x8D},
{0x59, 0xC6, 0x82, 0x45, 0xEB, 0x05, 0x28, 0x2B},
{0xB1, 0xB8, 0xCC, 0x0B, 0x25, 0x0F, 0x09, 0xA0},
{0x17, 0x30, 0xE5, 0x77, 0x8B, 0xEA, 0x1D, 0xA4},
{0xA2, 0x5E, 0x78, 0x56, 0xCF, 0x26, 0x51, 0xEB},
{0x35, 0x38, 0x82, 0xB1, 0x09, 0xCE, 0x8F, 0x1A},
{0x48, 0xF4, 0xD0, 0x88, 0x4C, 0x37, 0x99, 0x18},
{0x43, 0x21, 0x93, 0xB7, 0x89, 0x51, 0xFC, 0x98},
{0x13, 0xF0, 0x41, 0x54, 0xD6, 0x9D, 0x1A, 0xE5},
{0x2E, 0xED, 0xDA, 0x93, 0xFF, 0xD3, 0x9C, 0x79},
{0xD8, 0x87, 0xE0, 0x39, 0x3C, 0x2D, 0xA6, 0xE3},
{0x5F, 0x99, 0xD0, 0x4F, 0x5B, 0x16, 0x39, 0x69},
{0x4A, 0x05, 0x7A, 0x3B, 0x24, 0xD3, 0x97, 0x7B},
{0x45, 0x20, 0x31, 0xC1, 0xE4, 0xFA, 0xDA, 0x8E},
{0x75, 0x55, 0xAE, 0x39, 0xF5, 0x9B, 0x87, 0xBD},
{0x53, 0xC5, 0x5F, 0x9C, 0xB4, 0x9F, 0xC0, 0x19},
{0x7A, 0x8E, 0x7B, 0xFA, 0x93, 0x7E, 0x89, 0xA3},
{0xCF, 0x9C, 0x5D, 0x7A, 0x49, 0x86, 0xAD, 0xB5},
{0xD1, 0xAB, 0xB2, 0x90, 0x65, 0x8B, 0xC7, 0x78},
{0x55, 0xCB, 0x37, 0x74, 0xD1, 0x3E, 0xF2, 0x01},
{0xFA, 0x34, 0xEC, 0x48, 0x47, 0xB2, 0x68, 0xB2},
{0xA7, 0x90, 0x79, 0x51, 0x08, 0xEA, 0x3C, 0xAE},
{0xC3, 0x9E, 0x07, 0x2D, 0x9F, 0xAC, 0x63, 0x1D},
{0x01, 0x49, 0x33, 0xE0, 0xCD, 0xAF, 0xF6, 0xE4},
{0xF2, 0x1E, 0x9A, 0x77, 0xB7, 0x1C, 0x49, 0xBC},
{0x24, 0x59, 0x46, 0x88, 0x57, 0x54, 0x36, 0x9A},
{0x6B, 0x5C, 0x5A, 0x9C, 0x5D, 0x9E, 0x0A, 0x5A},
};
static unsigned char cbc_key[16] = {
0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef,
0xf0, 0xe1, 0xd2, 0xc3, 0xb4, 0xa5, 0x96, 0x87
};
static unsigned char cbc_iv[8] =
{ 0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54, 0x32, 0x10 };
static char cbc_data[40] = "7654321 Now is the time for ";
static unsigned char cbc_ok[32] = {
0x6B, 0x77, 0xB4, 0xD6, 0x30, 0x06, 0xDE, 0xE6,
0x05, 0xB1, 0x56, 0xE2, 0x74, 0x03, 0x97, 0x93,
0x58, 0xDE, 0xB9, 0xE7, 0x15, 0x46, 0x16, 0xD9,
0x59, 0xF1, 0x65, 0x2B, 0xD5, 0xFF, 0x92, 0xCC
};
static unsigned char cfb64_ok[] = {
0xE7, 0x32, 0x14, 0xA2, 0x82, 0x21, 0x39, 0xCA,
0xF2, 0x6E, 0xCF, 0x6D, 0x2E, 0xB9, 0xE7, 0x6E,
0x3D, 0xA3, 0xDE, 0x04, 0xD1, 0x51, 0x72, 0x00,
0x51, 0x9D, 0x57, 0xA6, 0xC3
};
static unsigned char ofb64_ok[] = {
0xE7, 0x32, 0x14, 0xA2, 0x82, 0x21, 0x39, 0xCA,
0x62, 0xB3, 0x43, 0xCC, 0x5B, 0x65, 0x58, 0x73,
0x10, 0xDD, 0x90, 0x8D, 0x0C, 0x24, 0x1B, 0x22,
0x63, 0xC2, 0xCF, 0x80, 0xDA
};
# define KEY_TEST_NUM 25
static unsigned char key_test[KEY_TEST_NUM] = {
0xf0, 0xe1, 0xd2, 0xc3, 0xb4, 0xa5, 0x96, 0x87,
0x78, 0x69, 0x5a, 0x4b, 0x3c, 0x2d, 0x1e, 0x0f,
0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77,
0x88
};
static unsigned char key_data[8] =
{ 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10 };
static unsigned char key_out[KEY_TEST_NUM][8] = {
{0xF9, 0xAD, 0x59, 0x7C, 0x49, 0xDB, 0x00, 0x5E},
{0xE9, 0x1D, 0x21, 0xC1, 0xD9, 0x61, 0xA6, 0xD6},
{0xE9, 0xC2, 0xB7, 0x0A, 0x1B, 0xC6, 0x5C, 0xF3},
{0xBE, 0x1E, 0x63, 0x94, 0x08, 0x64, 0x0F, 0x05},
{0xB3, 0x9E, 0x44, 0x48, 0x1B, 0xDB, 0x1E, 0x6E},
{0x94, 0x57, 0xAA, 0x83, 0xB1, 0x92, 0x8C, 0x0D},
{0x8B, 0xB7, 0x70, 0x32, 0xF9, 0x60, 0x62, 0x9D},
{0xE8, 0x7A, 0x24, 0x4E, 0x2C, 0xC8, 0x5E, 0x82},
{0x15, 0x75, 0x0E, 0x7A, 0x4F, 0x4E, 0xC5, 0x77},
{0x12, 0x2B, 0xA7, 0x0B, 0x3A, 0xB6, 0x4A, 0xE0},
{0x3A, 0x83, 0x3C, 0x9A, 0xFF, 0xC5, 0x37, 0xF6},
{0x94, 0x09, 0xDA, 0x87, 0xA9, 0x0F, 0x6B, 0xF2},
{0x88, 0x4F, 0x80, 0x62, 0x50, 0x60, 0xB8, 0xB4},
{0x1F, 0x85, 0x03, 0x1C, 0x19, 0xE1, 0x19, 0x68},
{0x79, 0xD9, 0x37, 0x3A, 0x71, 0x4C, 0xA3, 0x4F},
{0x93, 0x14, 0x28, 0x87, 0xEE, 0x3B, 0xE1, 0x5C},
{0x03, 0x42, 0x9E, 0x83, 0x8C, 0xE2, 0xD1, 0x4B},
{0xA4, 0x29, 0x9E, 0x27, 0x46, 0x9F, 0xF6, 0x7B},
{0xAF, 0xD5, 0xAE, 0xD1, 0xC1, 0xBC, 0x96, 0xA8},
{0x10, 0x85, 0x1C, 0x0E, 0x38, 0x58, 0xDA, 0x9F},
{0xE6, 0xF5, 0x1E, 0xD7, 0x9B, 0x9D, 0xB2, 0x1F},
{0x64, 0xA6, 0xE1, 0x4A, 0xFD, 0x36, 0xB4, 0x6F},
{0x80, 0xC7, 0xD7, 0xD4, 0x5A, 0x54, 0x79, 0xAD},
{0x05, 0x04, 0x4B, 0x62, 0xFA, 0x52, 0xD0, 0x80},
};
static int test(void);
static int print_test_data(void);
int main(int argc, char *argv[])
{
int ret;
if (argc > 1)
ret = print_test_data();
else
ret = test();
# ifdef OPENSSL_SYS_NETWARE
if (ret)
printf("ERROR: %d\n", ret);
# endif
EXIT(ret);
return (0);
}
static int print_test_data(void)
{
unsigned int i, j;
printf("ecb test data\n");
printf("key bytes\t\tclear bytes\t\tcipher bytes\n");
for (i = 0; i < NUM_TESTS; i++) {
for (j = 0; j < 8; j++)
printf("%02X", ecb_data[i][j]);
printf("\t");
for (j = 0; j < 8; j++)
printf("%02X", plain_data[i][j]);
printf("\t");
for (j = 0; j < 8; j++)
printf("%02X", cipher_data[i][j]);
printf("\n");
}
printf("set_key test data\n");
printf("data[8]= ");
for (j = 0; j < 8; j++)
printf("%02X", key_data[j]);
printf("\n");
for (i = 0; i < KEY_TEST_NUM - 1; i++) {
printf("c=");
for (j = 0; j < 8; j++)
printf("%02X", key_out[i][j]);
printf(" k[%2u]=", i + 1);
for (j = 0; j < i + 1; j++)
printf("%02X", key_test[j]);
printf("\n");
}
printf("\nchaining mode test data\n");
printf("key[16] = ");
for (j = 0; j < 16; j++)
printf("%02X", cbc_key[j]);
printf("\niv[8] = ");
for (j = 0; j < 8; j++)
printf("%02X", cbc_iv[j]);
printf("\ndata[%d] = '%s'", (int)strlen(cbc_data) + 1, cbc_data);
printf("\ndata[%d] = ", (int)strlen(cbc_data) + 1);
for (j = 0; j < strlen(cbc_data) + 1; j++)
printf("%02X", cbc_data[j]);
printf("\n");
printf("cbc cipher text\n");
printf("cipher[%d]= ", 32);
for (j = 0; j < 32; j++)
printf("%02X", cbc_ok[j]);
printf("\n");
printf("cfb64 cipher text\n");
printf("cipher[%d]= ", (int)strlen(cbc_data) + 1);
for (j = 0; j < strlen(cbc_data) + 1; j++)
printf("%02X", cfb64_ok[j]);
printf("\n");
printf("ofb64 cipher text\n");
printf("cipher[%d]= ", (int)strlen(cbc_data) + 1);
for (j = 0; j < strlen(cbc_data) + 1; j++)
printf("%02X", ofb64_ok[j]);
printf("\n");
return (0);
}
static int test(void)
{
unsigned char cbc_in[40], cbc_out[40], iv[8];
int i, n, err = 0;
BF_KEY key;
BF_LONG data[2];
unsigned char out[8];
BF_LONG len;
# ifdef CHARSET_EBCDIC
ebcdic2ascii(cbc_data, cbc_data, strlen(cbc_data));
# endif
printf("testing blowfish in raw ecb mode\n");
for (n = 0; n < 2; n++) {
# ifdef CHARSET_EBCDIC
ebcdic2ascii(bf_key[n], bf_key[n], strlen(bf_key[n]));
# endif
BF_set_key(&key, strlen(bf_key[n]), (unsigned char *)bf_key[n]);
data[0] = bf_plain[n][0];
data[1] = bf_plain[n][1];
BF_encrypt(data, &key);
if (memcmp(&(bf_cipher[n][0]), &(data[0]), 8) != 0) {
printf("BF_encrypt error encrypting\n");
printf("got :");
for (i = 0; i < 2; i++)
printf("%08lX ", (unsigned long)data[i]);
printf("\n");
printf("expected:");
for (i = 0; i < 2; i++)
printf("%08lX ", (unsigned long)bf_cipher[n][i]);
err = 1;
printf("\n");
}
BF_decrypt(&(data[0]), &key);
if (memcmp(&(bf_plain[n][0]), &(data[0]), 8) != 0) {
printf("BF_encrypt error decrypting\n");
printf("got :");
for (i = 0; i < 2; i++)
printf("%08lX ", (unsigned long)data[i]);
printf("\n");
printf("expected:");
for (i = 0; i < 2; i++)
printf("%08lX ", (unsigned long)bf_plain[n][i]);
printf("\n");
err = 1;
}
}
printf("testing blowfish in ecb mode\n");
for (n = 0; n < NUM_TESTS; n++) {
BF_set_key(&key, 8, ecb_data[n]);
BF_ecb_encrypt(&(plain_data[n][0]), out, &key, BF_ENCRYPT);
if (memcmp(&(cipher_data[n][0]), out, 8) != 0) {
printf("BF_ecb_encrypt blowfish error encrypting\n");
printf("got :");
for (i = 0; i < 8; i++)
printf("%02X ", out[i]);
printf("\n");
printf("expected:");
for (i = 0; i < 8; i++)
printf("%02X ", cipher_data[n][i]);
err = 1;
printf("\n");
}
BF_ecb_encrypt(out, out, &key, BF_DECRYPT);
if (memcmp(&(plain_data[n][0]), out, 8) != 0) {
printf("BF_ecb_encrypt error decrypting\n");
printf("got :");
for (i = 0; i < 8; i++)
printf("%02X ", out[i]);
printf("\n");
printf("expected:");
for (i = 0; i < 8; i++)
printf("%02X ", plain_data[n][i]);
printf("\n");
err = 1;
}
}
printf("testing blowfish set_key\n");
for (n = 1; n < KEY_TEST_NUM; n++) {
BF_set_key(&key, n, key_test);
BF_ecb_encrypt(key_data, out, &key, BF_ENCRYPT);
/* mips-sgi-irix6.5-gcc vv -mabi=64 bug workaround */
if (memcmp(out, &(key_out[i = n - 1][0]), 8) != 0) {
printf("blowfish setkey error\n");
err = 1;
}
}
printf("testing blowfish in cbc mode\n");
len = strlen(cbc_data) + 1;
BF_set_key(&key, 16, cbc_key);
- memset(cbc_in, 0, sizeof cbc_in);
- memset(cbc_out, 0, sizeof cbc_out);
- memcpy(iv, cbc_iv, sizeof iv);
+ memset(cbc_in, 0, sizeof(cbc_in));
+ memset(cbc_out, 0, sizeof(cbc_out));
+ memcpy(iv, cbc_iv, sizeof(iv));
BF_cbc_encrypt((unsigned char *)cbc_data, cbc_out, len,
&key, iv, BF_ENCRYPT);
if (memcmp(cbc_out, cbc_ok, 32) != 0) {
err = 1;
printf("BF_cbc_encrypt encrypt error\n");
for (i = 0; i < 32; i++)
printf("0x%02X,", cbc_out[i]);
}
memcpy(iv, cbc_iv, 8);
BF_cbc_encrypt(cbc_out, cbc_in, len, &key, iv, BF_DECRYPT);
if (memcmp(cbc_in, cbc_data, strlen(cbc_data) + 1) != 0) {
printf("BF_cbc_encrypt decrypt error\n");
err = 1;
}
printf("testing blowfish in cfb64 mode\n");
BF_set_key(&key, 16, cbc_key);
memset(cbc_in, 0, 40);
memset(cbc_out, 0, 40);
memcpy(iv, cbc_iv, 8);
n = 0;
BF_cfb64_encrypt((unsigned char *)cbc_data, cbc_out, (long)13,
&key, iv, &n, BF_ENCRYPT);
BF_cfb64_encrypt((unsigned char *)&(cbc_data[13]), &(cbc_out[13]),
len - 13, &key, iv, &n, BF_ENCRYPT);
if (memcmp(cbc_out, cfb64_ok, (int)len) != 0) {
err = 1;
printf("BF_cfb64_encrypt encrypt error\n");
for (i = 0; i < (int)len; i++)
printf("0x%02X,", cbc_out[i]);
}
n = 0;
memcpy(iv, cbc_iv, 8);
BF_cfb64_encrypt(cbc_out, cbc_in, 17, &key, iv, &n, BF_DECRYPT);
BF_cfb64_encrypt(&(cbc_out[17]), &(cbc_in[17]), len - 17,
&key, iv, &n, BF_DECRYPT);
if (memcmp(cbc_in, cbc_data, (int)len) != 0) {
printf("BF_cfb64_encrypt decrypt error\n");
err = 1;
}
printf("testing blowfish in ofb64\n");
BF_set_key(&key, 16, cbc_key);
memset(cbc_in, 0, 40);
memset(cbc_out, 0, 40);
memcpy(iv, cbc_iv, 8);
n = 0;
BF_ofb64_encrypt((unsigned char *)cbc_data, cbc_out, (long)13, &key, iv,
&n);
BF_ofb64_encrypt((unsigned char *)&(cbc_data[13]), &(cbc_out[13]),
len - 13, &key, iv, &n);
if (memcmp(cbc_out, ofb64_ok, (int)len) != 0) {
err = 1;
printf("BF_ofb64_encrypt encrypt error\n");
for (i = 0; i < (int)len; i++)
printf("0x%02X,", cbc_out[i]);
}
n = 0;
memcpy(iv, cbc_iv, 8);
BF_ofb64_encrypt(cbc_out, cbc_in, 17, &key, iv, &n);
BF_ofb64_encrypt(&(cbc_out[17]), &(cbc_in[17]), len - 17, &key, iv, &n);
if (memcmp(cbc_in, cbc_data, (int)len) != 0) {
printf("BF_ofb64_encrypt decrypt error\n");
err = 1;
}
return (err);
}
#endif
diff --git a/crypto/bio/b_dump.c b/crypto/bio/b_dump.c
index ccf0e287c4e8..fcfd6995953d 100644
--- a/crypto/bio/b_dump.c
+++ b/crypto/bio/b_dump.c
@@ -1,208 +1,193 @@
/* crypto/bio/b_dump.c */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
/*
* Stolen from tjh's ssl/ssl_trc.c stuff.
*/
#include <stdio.h>
#include "cryptlib.h"
#include "bio_lcl.h"
-#define TRUNCATE
#define DUMP_WIDTH 16
#define DUMP_WIDTH_LESS_INDENT(i) (DUMP_WIDTH-((i-(i>6?6:i)+3)/4))
int BIO_dump_cb(int (*cb) (const void *data, size_t len, void *u),
void *u, const char *s, int len)
{
return BIO_dump_indent_cb(cb, u, s, len, 0);
}
int BIO_dump_indent_cb(int (*cb) (const void *data, size_t len, void *u),
void *u, const char *s, int len, int indent)
{
int ret = 0;
char buf[288 + 1], tmp[20], str[128 + 1];
- int i, j, rows, trc;
+ int i, j, rows;
unsigned char ch;
int dump_width;
- trc = 0;
-
-#ifdef TRUNCATE
- for (; (len > 0) && ((s[len - 1] == ' ') || (s[len - 1] == '\0')); len--)
- trc++;
-#endif
-
if (indent < 0)
indent = 0;
if (indent) {
if (indent > 128)
indent = 128;
memset(str, ' ', indent);
}
str[indent] = '\0';
dump_width = DUMP_WIDTH_LESS_INDENT(indent);
rows = (len / dump_width);
if ((rows * dump_width) < len)
rows++;
for (i = 0; i < rows; i++) {
- BUF_strlcpy(buf, str, sizeof buf);
- BIO_snprintf(tmp, sizeof tmp, "%04x - ", i * dump_width);
- BUF_strlcat(buf, tmp, sizeof buf);
+ BUF_strlcpy(buf, str, sizeof(buf));
+ BIO_snprintf(tmp, sizeof(tmp), "%04x - ", i * dump_width);
+ BUF_strlcat(buf, tmp, sizeof(buf));
for (j = 0; j < dump_width; j++) {
if (((i * dump_width) + j) >= len) {
- BUF_strlcat(buf, " ", sizeof buf);
+ BUF_strlcat(buf, " ", sizeof(buf));
} else {
ch = ((unsigned char)*(s + i * dump_width + j)) & 0xff;
- BIO_snprintf(tmp, sizeof tmp, "%02x%c", ch,
+ BIO_snprintf(tmp, sizeof(tmp), "%02x%c", ch,
j == 7 ? '-' : ' ');
- BUF_strlcat(buf, tmp, sizeof buf);
+ BUF_strlcat(buf, tmp, sizeof(buf));
}
}
- BUF_strlcat(buf, " ", sizeof buf);
+ BUF_strlcat(buf, " ", sizeof(buf));
for (j = 0; j < dump_width; j++) {
if (((i * dump_width) + j) >= len)
break;
ch = ((unsigned char)*(s + i * dump_width + j)) & 0xff;
#ifndef CHARSET_EBCDIC
- BIO_snprintf(tmp, sizeof tmp, "%c",
+ BIO_snprintf(tmp, sizeof(tmp), "%c",
((ch >= ' ') && (ch <= '~')) ? ch : '.');
#else
- BIO_snprintf(tmp, sizeof tmp, "%c",
+ BIO_snprintf(tmp, sizeof(tmp), "%c",
((ch >= os_toascii[' ']) && (ch <= os_toascii['~']))
? os_toebcdic[ch]
: '.');
#endif
- BUF_strlcat(buf, tmp, sizeof buf);
+ BUF_strlcat(buf, tmp, sizeof(buf));
}
- BUF_strlcat(buf, "\n", sizeof buf);
+ BUF_strlcat(buf, "\n", sizeof(buf));
/*
* if this is the last call then update the ddt_dump thing so that we
* will move the selection point in the debug window
*/
ret += cb((void *)buf, strlen(buf), u);
}
-#ifdef TRUNCATE
- if (trc > 0) {
- BIO_snprintf(buf, sizeof buf, "%s%04x - <SPACES/NULS>\n", str,
- len + trc);
- ret += cb((void *)buf, strlen(buf), u);
- }
-#endif
- return (ret);
+ return ret;
}
#ifndef OPENSSL_NO_FP_API
static int write_fp(const void *data, size_t len, void *fp)
{
return UP_fwrite(data, len, 1, fp);
}
int BIO_dump_fp(FILE *fp, const char *s, int len)
{
return BIO_dump_cb(write_fp, fp, s, len);
}
int BIO_dump_indent_fp(FILE *fp, const char *s, int len, int indent)
{
return BIO_dump_indent_cb(write_fp, fp, s, len, indent);
}
#endif
static int write_bio(const void *data, size_t len, void *bp)
{
return BIO_write((BIO *)bp, (const char *)data, len);
}
int BIO_dump(BIO *bp, const char *s, int len)
{
return BIO_dump_cb(write_bio, bp, s, len);
}
int BIO_dump_indent(BIO *bp, const char *s, int len, int indent)
{
return BIO_dump_indent_cb(write_bio, bp, s, len, indent);
}
int BIO_hex_string(BIO *out, int indent, int width, unsigned char *data,
int datalen)
{
int i, j = 0;
if (datalen < 1)
return 1;
for (i = 0; i < datalen - 1; i++) {
if (i && !j)
BIO_printf(out, "%*s", indent, "");
BIO_printf(out, "%02X:", data[i]);
j = (j + 1) % width;
if (!j)
BIO_printf(out, "\n");
}
if (i && !j)
BIO_printf(out, "%*s", indent, "");
BIO_printf(out, "%02X", data[datalen - 1]);
return 1;
}
diff --git a/crypto/bio/b_print.c b/crypto/bio/b_print.c
index 1c82f53d5a07..47654f85b0b0 100644
--- a/crypto/bio/b_print.c
+++ b/crypto/bio/b_print.c
@@ -1,869 +1,869 @@
/* crypto/bio/b_print.c */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
/* disable assert() unless BIO_DEBUG has been defined */
#ifndef BIO_DEBUG
# ifndef NDEBUG
# define NDEBUG
# endif
#endif
/*
* Stolen from tjh's ssl/ssl_trc.c stuff.
*/
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <assert.h>
#include <limits.h>
#include "cryptlib.h"
#ifndef NO_SYS_TYPES_H
# include <sys/types.h>
#endif
#include <openssl/bn.h> /* To get BN_LLONG properly defined */
#include <openssl/bio.h>
#if defined(BN_LLONG) || defined(SIXTY_FOUR_BIT)
# ifndef HAVE_LONG_LONG
# define HAVE_LONG_LONG 1
# endif
#endif
/***************************************************************************/
/*
* Copyright Patrick Powell 1995
* This code is based on code written by Patrick Powell <papowell@astart.com>
* It may be used for any purpose as long as this notice remains intact
* on all source code distributions.
*/
/*-
* This code contains numerious changes and enhancements which were
* made by lots of contributors over the last years to Patrick Powell's
* original code:
*
* o Patrick Powell <papowell@astart.com> (1995)
* o Brandon Long <blong@fiction.net> (1996, for Mutt)
* o Thomas Roessler <roessler@guug.de> (1998, for Mutt)
* o Michael Elkins <me@cs.hmc.edu> (1998, for Mutt)
* o Andrew Tridgell <tridge@samba.org> (1998, for Samba)
* o Luke Mewburn <lukem@netbsd.org> (1999, for LukemFTP)
* o Ralf S. Engelschall <rse@engelschall.com> (1999, for Pth)
* o ... (for OpenSSL)
*/
#ifdef HAVE_LONG_DOUBLE
# define LDOUBLE long double
#else
# define LDOUBLE double
#endif
#ifdef HAVE_LONG_LONG
# if defined(_WIN32) && !defined(__GNUC__)
# define LLONG __int64
# else
# define LLONG long long
# endif
#else
# define LLONG long
#endif
static int fmtstr(char **, char **, size_t *, size_t *,
const char *, int, int, int);
static int fmtint(char **, char **, size_t *, size_t *,
LLONG, int, int, int, int);
static int fmtfp(char **, char **, size_t *, size_t *,
LDOUBLE, int, int, int);
static int doapr_outch(char **, char **, size_t *, size_t *, int);
static int _dopr(char **sbuffer, char **buffer,
size_t *maxlen, size_t *retlen, int *truncated,
const char *format, va_list args);
/* format read states */
#define DP_S_DEFAULT 0
#define DP_S_FLAGS 1
#define DP_S_MIN 2
#define DP_S_DOT 3
#define DP_S_MAX 4
#define DP_S_MOD 5
#define DP_S_CONV 6
#define DP_S_DONE 7
/* format flags - Bits */
#define DP_F_MINUS (1 << 0)
#define DP_F_PLUS (1 << 1)
#define DP_F_SPACE (1 << 2)
#define DP_F_NUM (1 << 3)
#define DP_F_ZERO (1 << 4)
#define DP_F_UP (1 << 5)
#define DP_F_UNSIGNED (1 << 6)
/* conversion flags */
#define DP_C_SHORT 1
#define DP_C_LONG 2
#define DP_C_LDOUBLE 3
#define DP_C_LLONG 4
/* some handy macros */
#define char_to_int(p) (p - '0')
#define OSSL_MAX(p,q) ((p >= q) ? p : q)
static int
_dopr(char **sbuffer,
char **buffer,
size_t *maxlen,
size_t *retlen, int *truncated, const char *format, va_list args)
{
char ch;
LLONG value;
LDOUBLE fvalue;
char *strvalue;
int min;
int max;
int state;
int flags;
int cflags;
size_t currlen;
state = DP_S_DEFAULT;
flags = currlen = cflags = min = 0;
max = -1;
ch = *format++;
while (state != DP_S_DONE) {
if (ch == '\0' || (buffer == NULL && currlen >= *maxlen))
state = DP_S_DONE;
switch (state) {
case DP_S_DEFAULT:
if (ch == '%')
state = DP_S_FLAGS;
else
if(!doapr_outch(sbuffer, buffer, &currlen, maxlen, ch))
return 0;
ch = *format++;
break;
case DP_S_FLAGS:
switch (ch) {
case '-':
flags |= DP_F_MINUS;
ch = *format++;
break;
case '+':
flags |= DP_F_PLUS;
ch = *format++;
break;
case ' ':
flags |= DP_F_SPACE;
ch = *format++;
break;
case '#':
flags |= DP_F_NUM;
ch = *format++;
break;
case '0':
flags |= DP_F_ZERO;
ch = *format++;
break;
default:
state = DP_S_MIN;
break;
}
break;
case DP_S_MIN:
if (isdigit((unsigned char)ch)) {
min = 10 * min + char_to_int(ch);
ch = *format++;
} else if (ch == '*') {
min = va_arg(args, int);
ch = *format++;
state = DP_S_DOT;
} else
state = DP_S_DOT;
break;
case DP_S_DOT:
if (ch == '.') {
state = DP_S_MAX;
ch = *format++;
} else
state = DP_S_MOD;
break;
case DP_S_MAX:
if (isdigit((unsigned char)ch)) {
if (max < 0)
max = 0;
max = 10 * max + char_to_int(ch);
ch = *format++;
} else if (ch == '*') {
max = va_arg(args, int);
ch = *format++;
state = DP_S_MOD;
} else
state = DP_S_MOD;
break;
case DP_S_MOD:
switch (ch) {
case 'h':
cflags = DP_C_SHORT;
ch = *format++;
break;
case 'l':
if (*format == 'l') {
cflags = DP_C_LLONG;
format++;
} else
cflags = DP_C_LONG;
ch = *format++;
break;
case 'q':
cflags = DP_C_LLONG;
ch = *format++;
break;
case 'L':
cflags = DP_C_LDOUBLE;
ch = *format++;
break;
default:
break;
}
state = DP_S_CONV;
break;
case DP_S_CONV:
switch (ch) {
case 'd':
case 'i':
switch (cflags) {
case DP_C_SHORT:
value = (short int)va_arg(args, int);
break;
case DP_C_LONG:
value = va_arg(args, long int);
break;
case DP_C_LLONG:
value = va_arg(args, LLONG);
break;
default:
value = va_arg(args, int);
break;
}
if (!fmtint(sbuffer, buffer, &currlen, maxlen, value, 10, min,
max, flags))
return 0;
break;
case 'X':
flags |= DP_F_UP;
/* FALLTHROUGH */
case 'x':
case 'o':
case 'u':
flags |= DP_F_UNSIGNED;
switch (cflags) {
case DP_C_SHORT:
value = (unsigned short int)va_arg(args, unsigned int);
break;
case DP_C_LONG:
value = (LLONG) va_arg(args, unsigned long int);
break;
case DP_C_LLONG:
value = va_arg(args, unsigned LLONG);
break;
default:
value = (LLONG) va_arg(args, unsigned int);
break;
}
if (!fmtint(sbuffer, buffer, &currlen, maxlen, value,
ch == 'o' ? 8 : (ch == 'u' ? 10 : 16),
min, max, flags))
return 0;
break;
case 'f':
if (cflags == DP_C_LDOUBLE)
fvalue = va_arg(args, LDOUBLE);
else
fvalue = va_arg(args, double);
if (!fmtfp(sbuffer, buffer, &currlen, maxlen, fvalue, min, max,
flags))
return 0;
break;
case 'E':
flags |= DP_F_UP;
case 'e':
if (cflags == DP_C_LDOUBLE)
fvalue = va_arg(args, LDOUBLE);
else
fvalue = va_arg(args, double);
break;
case 'G':
flags |= DP_F_UP;
case 'g':
if (cflags == DP_C_LDOUBLE)
fvalue = va_arg(args, LDOUBLE);
else
fvalue = va_arg(args, double);
break;
case 'c':
if(!doapr_outch(sbuffer, buffer, &currlen, maxlen,
va_arg(args, int)))
return 0;
break;
case 's':
strvalue = va_arg(args, char *);
if (max < 0) {
if (buffer)
max = INT_MAX;
else
max = *maxlen;
}
if (!fmtstr(sbuffer, buffer, &currlen, maxlen, strvalue,
flags, min, max))
return 0;
break;
case 'p':
value = (long)va_arg(args, void *);
if (!fmtint(sbuffer, buffer, &currlen, maxlen,
value, 16, min, max, flags | DP_F_NUM))
return 0;
break;
case 'n': /* XXX */
if (cflags == DP_C_SHORT) {
short int *num;
num = va_arg(args, short int *);
*num = (short int)currlen;
} else if (cflags == DP_C_LONG) { /* XXX */
long int *num;
num = va_arg(args, long int *);
*num = (long int)currlen;
} else if (cflags == DP_C_LLONG) { /* XXX */
LLONG *num;
num = va_arg(args, LLONG *);
*num = (LLONG) currlen;
} else {
int *num;
num = va_arg(args, int *);
*num = currlen;
}
break;
case '%':
if(!doapr_outch(sbuffer, buffer, &currlen, maxlen, ch))
return 0;
break;
case 'w':
/* not supported yet, treat as next char */
ch = *format++;
break;
default:
/* unknown, skip */
break;
}
ch = *format++;
state = DP_S_DEFAULT;
flags = cflags = min = 0;
max = -1;
break;
case DP_S_DONE:
break;
default:
break;
}
}
/*
* We have to truncate if there is no dynamic buffer and we have filled the
* static buffer.
*/
if (buffer == NULL) {
*truncated = (currlen > *maxlen - 1);
if (*truncated)
currlen = *maxlen - 1;
}
if(!doapr_outch(sbuffer, buffer, &currlen, maxlen, '\0'))
return 0;
*retlen = currlen - 1;
return 1;
}
static int
fmtstr(char **sbuffer,
char **buffer,
size_t *currlen,
size_t *maxlen, const char *value, int flags, int min, int max)
{
int padlen;
size_t strln;
int cnt = 0;
if (value == 0)
value = "<NULL>";
strln = strlen(value);
if (strln > INT_MAX)
strln = INT_MAX;
padlen = min - strln;
if (min < 0 || padlen < 0)
padlen = 0;
if (flags & DP_F_MINUS)
padlen = -padlen;
while ((padlen > 0) && (cnt < max)) {
if(!doapr_outch(sbuffer, buffer, currlen, maxlen, ' '))
return 0;
--padlen;
++cnt;
}
while (*value && (cnt < max)) {
if(!doapr_outch(sbuffer, buffer, currlen, maxlen, *value++))
return 0;
++cnt;
}
while ((padlen < 0) && (cnt < max)) {
if(!doapr_outch(sbuffer, buffer, currlen, maxlen, ' '))
return 0;
++padlen;
++cnt;
}
return 1;
}
static int
fmtint(char **sbuffer,
char **buffer,
size_t *currlen,
size_t *maxlen, LLONG value, int base, int min, int max, int flags)
{
int signvalue = 0;
const char *prefix = "";
unsigned LLONG uvalue;
char convert[DECIMAL_SIZE(value) + 3];
int place = 0;
int spadlen = 0;
int zpadlen = 0;
int caps = 0;
if (max < 0)
max = 0;
uvalue = value;
if (!(flags & DP_F_UNSIGNED)) {
if (value < 0) {
signvalue = '-';
uvalue = 0 - (unsigned LLONG)value;
} else if (flags & DP_F_PLUS)
signvalue = '+';
else if (flags & DP_F_SPACE)
signvalue = ' ';
}
if (flags & DP_F_NUM) {
if (base == 8)
prefix = "0";
if (base == 16)
prefix = "0x";
}
if (flags & DP_F_UP)
caps = 1;
do {
convert[place++] = (caps ? "0123456789ABCDEF" : "0123456789abcdef")
[uvalue % (unsigned)base];
uvalue = (uvalue / (unsigned)base);
} while (uvalue && (place < (int)sizeof(convert)));
if (place == sizeof(convert))
place--;
convert[place] = 0;
zpadlen = max - place;
spadlen =
min - OSSL_MAX(max, place) - (signvalue ? 1 : 0) - strlen(prefix);
if (zpadlen < 0)
zpadlen = 0;
if (spadlen < 0)
spadlen = 0;
if (flags & DP_F_ZERO) {
zpadlen = OSSL_MAX(zpadlen, spadlen);
spadlen = 0;
}
if (flags & DP_F_MINUS)
spadlen = -spadlen;
/* spaces */
while (spadlen > 0) {
if(!doapr_outch(sbuffer, buffer, currlen, maxlen, ' '))
return 0;
--spadlen;
}
/* sign */
if (signvalue)
if(!doapr_outch(sbuffer, buffer, currlen, maxlen, signvalue))
return 0;
/* prefix */
while (*prefix) {
if(!doapr_outch(sbuffer, buffer, currlen, maxlen, *prefix))
return 0;
prefix++;
}
/* zeros */
if (zpadlen > 0) {
while (zpadlen > 0) {
if(!doapr_outch(sbuffer, buffer, currlen, maxlen, '0'))
return 0;
--zpadlen;
}
}
/* digits */
while (place > 0) {
if (!doapr_outch(sbuffer, buffer, currlen, maxlen, convert[--place]))
return 0;
}
/* left justified spaces */
while (spadlen < 0) {
if (!doapr_outch(sbuffer, buffer, currlen, maxlen, ' '))
return 0;
++spadlen;
}
return 1;
}
static LDOUBLE abs_val(LDOUBLE value)
{
LDOUBLE result = value;
if (value < 0)
result = -value;
return result;
}
static LDOUBLE pow_10(int in_exp)
{
LDOUBLE result = 1;
while (in_exp) {
result *= 10;
in_exp--;
}
return result;
}
static long roundv(LDOUBLE value)
{
long intpart;
intpart = (long)value;
value = value - intpart;
if (value >= 0.5)
intpart++;
return intpart;
}
static int
fmtfp(char **sbuffer,
char **buffer,
size_t *currlen,
size_t *maxlen, LDOUBLE fvalue, int min, int max, int flags)
{
int signvalue = 0;
LDOUBLE ufvalue;
char iconvert[20];
char fconvert[20];
int iplace = 0;
int fplace = 0;
int padlen = 0;
int zpadlen = 0;
long intpart;
long fracpart;
long max10;
if (max < 0)
max = 6;
ufvalue = abs_val(fvalue);
if (fvalue < 0)
signvalue = '-';
else if (flags & DP_F_PLUS)
signvalue = '+';
else if (flags & DP_F_SPACE)
signvalue = ' ';
intpart = (long)ufvalue;
/*
* sorry, we only support 9 digits past the decimal because of our
* conversion method
*/
if (max > 9)
max = 9;
/*
* we "cheat" by converting the fractional part to integer by multiplying
* by a factor of 10
*/
max10 = roundv(pow_10(max));
fracpart = roundv(pow_10(max) * (ufvalue - intpart));
if (fracpart >= max10) {
intpart++;
fracpart -= max10;
}
/* convert integer part */
do {
iconvert[iplace++] = "0123456789"[intpart % 10];
intpart = (intpart / 10);
} while (intpart && (iplace < (int)sizeof(iconvert)));
- if (iplace == sizeof iconvert)
+ if (iplace == sizeof(iconvert))
iplace--;
iconvert[iplace] = 0;
/* convert fractional part */
do {
fconvert[fplace++] = "0123456789"[fracpart % 10];
fracpart = (fracpart / 10);
} while (fplace < max);
- if (fplace == sizeof fconvert)
+ if (fplace == sizeof(fconvert))
fplace--;
fconvert[fplace] = 0;
/* -1 for decimal point, another -1 if we are printing a sign */
padlen = min - iplace - max - 1 - ((signvalue) ? 1 : 0);
zpadlen = max - fplace;
if (zpadlen < 0)
zpadlen = 0;
if (padlen < 0)
padlen = 0;
if (flags & DP_F_MINUS)
padlen = -padlen;
if ((flags & DP_F_ZERO) && (padlen > 0)) {
if (signvalue) {
if (!doapr_outch(sbuffer, buffer, currlen, maxlen, signvalue))
return 0;
--padlen;
signvalue = 0;
}
while (padlen > 0) {
if (!doapr_outch(sbuffer, buffer, currlen, maxlen, '0'))
return 0;
--padlen;
}
}
while (padlen > 0) {
if (!doapr_outch(sbuffer, buffer, currlen, maxlen, ' '))
return 0;
--padlen;
}
if (signvalue && !doapr_outch(sbuffer, buffer, currlen, maxlen, signvalue))
return 0;
while (iplace > 0) {
if (!doapr_outch(sbuffer, buffer, currlen, maxlen, iconvert[--iplace]))
return 0;
}
/*
* Decimal point. This should probably use locale to find the correct
* char to print out.
*/
if (max > 0 || (flags & DP_F_NUM)) {
if (!doapr_outch(sbuffer, buffer, currlen, maxlen, '.'))
return 0;
while (fplace > 0) {
if(!doapr_outch(sbuffer, buffer, currlen, maxlen,
fconvert[--fplace]))
return 0;
}
}
while (zpadlen > 0) {
if (!doapr_outch(sbuffer, buffer, currlen, maxlen, '0'))
return 0;
--zpadlen;
}
while (padlen < 0) {
if (!doapr_outch(sbuffer, buffer, currlen, maxlen, ' '))
return 0;
++padlen;
}
return 1;
}
#define BUFFER_INC 1024
static int
doapr_outch(char **sbuffer,
char **buffer, size_t *currlen, size_t *maxlen, int c)
{
/* If we haven't at least one buffer, someone has doe a big booboo */
assert(*sbuffer != NULL || buffer != NULL);
/* |currlen| must always be <= |*maxlen| */
assert(*currlen <= *maxlen);
if (buffer && *currlen == *maxlen) {
if (*maxlen > INT_MAX - BUFFER_INC)
return 0;
*maxlen += BUFFER_INC;
if (*buffer == NULL) {
*buffer = OPENSSL_malloc(*maxlen);
if (*buffer == NULL)
return 0;
if (*currlen > 0) {
assert(*sbuffer != NULL);
memcpy(*buffer, *sbuffer, *currlen);
}
*sbuffer = NULL;
} else {
char *tmpbuf;
tmpbuf = OPENSSL_realloc(*buffer, *maxlen);
if (tmpbuf == NULL)
return 0;
*buffer = tmpbuf;
}
}
if (*currlen < *maxlen) {
if (*sbuffer)
(*sbuffer)[(*currlen)++] = (char)c;
else
(*buffer)[(*currlen)++] = (char)c;
}
return 1;
}
/***************************************************************************/
int BIO_printf(BIO *bio, const char *format, ...)
{
va_list args;
int ret;
va_start(args, format);
ret = BIO_vprintf(bio, format, args);
va_end(args);
return (ret);
}
int BIO_vprintf(BIO *bio, const char *format, va_list args)
{
int ret;
size_t retlen;
char hugebuf[1024 * 2]; /* Was previously 10k, which is unreasonable
* in small-stack environments, like threads
* or DOS programs. */
char *hugebufp = hugebuf;
size_t hugebufsize = sizeof(hugebuf);
char *dynbuf = NULL;
int ignored;
dynbuf = NULL;
CRYPTO_push_info("doapr()");
if (!_dopr(&hugebufp, &dynbuf, &hugebufsize, &retlen, &ignored, format,
args)) {
OPENSSL_free(dynbuf);
return -1;
}
if (dynbuf) {
ret = BIO_write(bio, dynbuf, (int)retlen);
OPENSSL_free(dynbuf);
} else {
ret = BIO_write(bio, hugebuf, (int)retlen);
}
CRYPTO_pop_info();
return (ret);
}
/*
* As snprintf is not available everywhere, we provide our own
* implementation. This function has nothing to do with BIOs, but it's
* closely related to BIO_printf, and we need *some* name prefix ... (XXX the
* function should be renamed, but to what?)
*/
int BIO_snprintf(char *buf, size_t n, const char *format, ...)
{
va_list args;
int ret;
va_start(args, format);
ret = BIO_vsnprintf(buf, n, format, args);
va_end(args);
return (ret);
}
int BIO_vsnprintf(char *buf, size_t n, const char *format, va_list args)
{
size_t retlen;
int truncated;
if(!_dopr(&buf, NULL, &n, &retlen, &truncated, format, args))
return -1;
if (truncated)
/*
* In case of truncation, return -1 like traditional snprintf.
* (Current drafts for ISO/IEC 9899 say snprintf should return the
* number of characters that would have been written, had the buffer
* been large enough.)
*/
return -1;
else
return (retlen <= INT_MAX) ? (int)retlen : -1;
}
diff --git a/crypto/bio/bio_cb.c b/crypto/bio/bio_cb.c
index f96294bb4304..2ff52636d2c3 100644
--- a/crypto/bio/bio_cb.c
+++ b/crypto/bio/bio_cb.c
@@ -1,148 +1,148 @@
/* crypto/bio/bio_cb.c */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "cryptlib.h"
#include <openssl/bio.h>
#include <openssl/err.h>
long MS_CALLBACK BIO_debug_callback(BIO *bio, int cmd, const char *argp,
int argi, long argl, long ret)
{
BIO *b;
MS_STATIC char buf[256];
char *p;
long r = 1;
int len;
size_t p_maxlen;
if (BIO_CB_RETURN & cmd)
r = ret;
- len = BIO_snprintf(buf,sizeof buf,"BIO[%p]: ",(void *)bio);
+ len = BIO_snprintf(buf,sizeof(buf),"BIO[%p]: ",(void *)bio);
/* Ignore errors and continue printing the other information. */
if (len < 0)
len = 0;
p = buf + len;
p_maxlen = sizeof(buf) - len;
switch (cmd) {
case BIO_CB_FREE:
BIO_snprintf(p, p_maxlen, "Free - %s\n", bio->method->name);
break;
case BIO_CB_READ:
if (bio->method->type & BIO_TYPE_DESCRIPTOR)
BIO_snprintf(p, p_maxlen, "read(%d,%lu) - %s fd=%d\n",
bio->num, (unsigned long)argi,
bio->method->name, bio->num);
else
BIO_snprintf(p, p_maxlen, "read(%d,%lu) - %s\n",
bio->num, (unsigned long)argi, bio->method->name);
break;
case BIO_CB_WRITE:
if (bio->method->type & BIO_TYPE_DESCRIPTOR)
BIO_snprintf(p, p_maxlen, "write(%d,%lu) - %s fd=%d\n",
bio->num, (unsigned long)argi,
bio->method->name, bio->num);
else
BIO_snprintf(p, p_maxlen, "write(%d,%lu) - %s\n",
bio->num, (unsigned long)argi, bio->method->name);
break;
case BIO_CB_PUTS:
BIO_snprintf(p, p_maxlen, "puts() - %s\n", bio->method->name);
break;
case BIO_CB_GETS:
BIO_snprintf(p, p_maxlen, "gets(%lu) - %s\n", (unsigned long)argi,
bio->method->name);
break;
case BIO_CB_CTRL:
BIO_snprintf(p, p_maxlen, "ctrl(%lu) - %s\n", (unsigned long)argi,
bio->method->name);
break;
case BIO_CB_RETURN | BIO_CB_READ:
BIO_snprintf(p, p_maxlen, "read return %ld\n", ret);
break;
case BIO_CB_RETURN | BIO_CB_WRITE:
BIO_snprintf(p, p_maxlen, "write return %ld\n", ret);
break;
case BIO_CB_RETURN | BIO_CB_GETS:
BIO_snprintf(p, p_maxlen, "gets return %ld\n", ret);
break;
case BIO_CB_RETURN | BIO_CB_PUTS:
BIO_snprintf(p, p_maxlen, "puts return %ld\n", ret);
break;
case BIO_CB_RETURN | BIO_CB_CTRL:
BIO_snprintf(p, p_maxlen, "ctrl return %ld\n", ret);
break;
default:
BIO_snprintf(p, p_maxlen, "bio callback - unknown type (%d)\n", cmd);
break;
}
b = (BIO *)bio->cb_arg;
if (b != NULL)
BIO_write(b, buf, strlen(buf));
#if !defined(OPENSSL_NO_STDIO) && !defined(OPENSSL_SYS_WIN16)
else
fputs(buf, stderr);
#endif
return (r);
}
diff --git a/crypto/bio/bss_bio.c b/crypto/bio/bss_bio.c
index 3dd818772942..096ea4156cd4 100644
--- a/crypto/bio/bss_bio.c
+++ b/crypto/bio/bss_bio.c
@@ -1,889 +1,889 @@
/* crypto/bio/bss_bio.c */
/* ====================================================================
* Copyright (c) 1998-2003 The OpenSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* openssl-core@openssl.org.
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.openssl.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*
* This product includes cryptographic software written by Eric Young
* (eay@cryptsoft.com). This product includes software written by Tim
* Hudson (tjh@cryptsoft.com).
*
*/
/*
* Special method for a BIO where the other endpoint is also a BIO of this
* kind, handled by the same thread (i.e. the "peer" is actually ourselves,
* wearing a different hat). Such "BIO pairs" are mainly for using the SSL
* library with I/O interfaces for which no specific BIO method is available.
* See ssl/ssltest.c for some hints on how this can be used.
*/
/* BIO_DEBUG implies BIO_PAIR_DEBUG */
#ifdef BIO_DEBUG
# ifndef BIO_PAIR_DEBUG
# define BIO_PAIR_DEBUG
# endif
#endif
/* disable assert() unless BIO_PAIR_DEBUG has been defined */
#ifndef BIO_PAIR_DEBUG
# ifndef NDEBUG
# define NDEBUG
# endif
#endif
#include <assert.h>
#include <limits.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/bio.h>
#include <openssl/err.h>
#include <openssl/crypto.h>
#include "e_os.h"
/* VxWorks defines SSIZE_MAX with an empty value causing compile errors */
#if defined(OPENSSL_SYS_VXWORKS)
# undef SSIZE_MAX
#endif
#ifndef SSIZE_MAX
# define SSIZE_MAX INT_MAX
#endif
static int bio_new(BIO *bio);
static int bio_free(BIO *bio);
static int bio_read(BIO *bio, char *buf, int size);
static int bio_write(BIO *bio, const char *buf, int num);
static long bio_ctrl(BIO *bio, int cmd, long num, void *ptr);
static int bio_puts(BIO *bio, const char *str);
static int bio_make_pair(BIO *bio1, BIO *bio2);
static void bio_destroy_pair(BIO *bio);
static BIO_METHOD methods_biop = {
BIO_TYPE_BIO,
"BIO pair",
bio_write,
bio_read,
bio_puts,
NULL /* no bio_gets */ ,
bio_ctrl,
bio_new,
bio_free,
NULL /* no bio_callback_ctrl */
};
BIO_METHOD *BIO_s_bio(void)
{
return &methods_biop;
}
struct bio_bio_st {
BIO *peer; /* NULL if buf == NULL. If peer != NULL, then
* peer->ptr is also a bio_bio_st, and its
* "peer" member points back to us. peer !=
* NULL iff init != 0 in the BIO. */
/* This is for what we write (i.e. reading uses peer's struct): */
int closed; /* valid iff peer != NULL */
size_t len; /* valid iff buf != NULL; 0 if peer == NULL */
size_t offset; /* valid iff buf != NULL; 0 if len == 0 */
size_t size;
char *buf; /* "size" elements (if != NULL) */
size_t request; /* valid iff peer != NULL; 0 if len != 0,
* otherwise set by peer to number of bytes
* it (unsuccessfully) tried to read, never
* more than buffer space (size-len)
* warrants. */
};
static int bio_new(BIO *bio)
{
struct bio_bio_st *b;
- b = OPENSSL_malloc(sizeof *b);
+ b = OPENSSL_malloc(sizeof(*b));
if (b == NULL)
return 0;
b->peer = NULL;
b->closed = 0;
b->len = 0;
b->offset = 0;
/* enough for one TLS record (just a default) */
b->size = 17 * 1024;
b->buf = NULL;
b->request = 0;
bio->ptr = b;
return 1;
}
static int bio_free(BIO *bio)
{
struct bio_bio_st *b;
if (bio == NULL)
return 0;
b = bio->ptr;
assert(b != NULL);
if (b->peer)
bio_destroy_pair(bio);
if (b->buf != NULL) {
OPENSSL_free(b->buf);
}
OPENSSL_free(b);
return 1;
}
static int bio_read(BIO *bio, char *buf, int size_)
{
size_t size = size_;
size_t rest;
struct bio_bio_st *b, *peer_b;
BIO_clear_retry_flags(bio);
if (!bio->init)
return 0;
b = bio->ptr;
assert(b != NULL);
assert(b->peer != NULL);
peer_b = b->peer->ptr;
assert(peer_b != NULL);
assert(peer_b->buf != NULL);
peer_b->request = 0; /* will be set in "retry_read" situation */
if (buf == NULL || size == 0)
return 0;
if (peer_b->len == 0) {
if (peer_b->closed)
return 0; /* writer has closed, and no data is left */
else {
BIO_set_retry_read(bio); /* buffer is empty */
if (size <= peer_b->size)
peer_b->request = size;
else
/*
* don't ask for more than the peer can deliver in one write
*/
peer_b->request = peer_b->size;
return -1;
}
}
/* we can read */
if (peer_b->len < size)
size = peer_b->len;
/* now read "size" bytes */
rest = size;
assert(rest > 0);
do { /* one or two iterations */
size_t chunk;
assert(rest <= peer_b->len);
if (peer_b->offset + rest <= peer_b->size)
chunk = rest;
else
/* wrap around ring buffer */
chunk = peer_b->size - peer_b->offset;
assert(peer_b->offset + chunk <= peer_b->size);
memcpy(buf, peer_b->buf + peer_b->offset, chunk);
peer_b->len -= chunk;
if (peer_b->len) {
peer_b->offset += chunk;
assert(peer_b->offset <= peer_b->size);
if (peer_b->offset == peer_b->size)
peer_b->offset = 0;
buf += chunk;
} else {
/* buffer now empty, no need to advance "buf" */
assert(chunk == rest);
peer_b->offset = 0;
}
rest -= chunk;
}
while (rest);
return size;
}
/*-
* non-copying interface: provide pointer to available data in buffer
* bio_nread0: return number of available bytes
* bio_nread: also advance index
* (example usage: bio_nread0(), read from buffer, bio_nread()
* or just bio_nread(), read from buffer)
*/
/*
* WARNING: The non-copying interface is largely untested as of yet and may
* contain bugs.
*/
static ossl_ssize_t bio_nread0(BIO *bio, char **buf)
{
struct bio_bio_st *b, *peer_b;
ossl_ssize_t num;
BIO_clear_retry_flags(bio);
if (!bio->init)
return 0;
b = bio->ptr;
assert(b != NULL);
assert(b->peer != NULL);
peer_b = b->peer->ptr;
assert(peer_b != NULL);
assert(peer_b->buf != NULL);
peer_b->request = 0;
if (peer_b->len == 0) {
char dummy;
/* avoid code duplication -- nothing available for reading */
return bio_read(bio, &dummy, 1); /* returns 0 or -1 */
}
num = peer_b->len;
if (peer_b->size < peer_b->offset + num)
/* no ring buffer wrap-around for non-copying interface */
num = peer_b->size - peer_b->offset;
assert(num > 0);
if (buf != NULL)
*buf = peer_b->buf + peer_b->offset;
return num;
}
static ossl_ssize_t bio_nread(BIO *bio, char **buf, size_t num_)
{
struct bio_bio_st *b, *peer_b;
ossl_ssize_t num, available;
if (num_ > SSIZE_MAX)
num = SSIZE_MAX;
else
num = (ossl_ssize_t) num_;
available = bio_nread0(bio, buf);
if (num > available)
num = available;
if (num <= 0)
return num;
b = bio->ptr;
peer_b = b->peer->ptr;
peer_b->len -= num;
if (peer_b->len) {
peer_b->offset += num;
assert(peer_b->offset <= peer_b->size);
if (peer_b->offset == peer_b->size)
peer_b->offset = 0;
} else
peer_b->offset = 0;
return num;
}
static int bio_write(BIO *bio, const char *buf, int num_)
{
size_t num = num_;
size_t rest;
struct bio_bio_st *b;
BIO_clear_retry_flags(bio);
if (!bio->init || buf == NULL || num == 0)
return 0;
b = bio->ptr;
assert(b != NULL);
assert(b->peer != NULL);
assert(b->buf != NULL);
b->request = 0;
if (b->closed) {
/* we already closed */
BIOerr(BIO_F_BIO_WRITE, BIO_R_BROKEN_PIPE);
return -1;
}
assert(b->len <= b->size);
if (b->len == b->size) {
BIO_set_retry_write(bio); /* buffer is full */
return -1;
}
/* we can write */
if (num > b->size - b->len)
num = b->size - b->len;
/* now write "num" bytes */
rest = num;
assert(rest > 0);
do { /* one or two iterations */
size_t write_offset;
size_t chunk;
assert(b->len + rest <= b->size);
write_offset = b->offset + b->len;
if (write_offset >= b->size)
write_offset -= b->size;
/* b->buf[write_offset] is the first byte we can write to. */
if (write_offset + rest <= b->size)
chunk = rest;
else
/* wrap around ring buffer */
chunk = b->size - write_offset;
memcpy(b->buf + write_offset, buf, chunk);
b->len += chunk;
assert(b->len <= b->size);
rest -= chunk;
buf += chunk;
}
while (rest);
return num;
}
/*-
* non-copying interface: provide pointer to region to write to
* bio_nwrite0: check how much space is available
* bio_nwrite: also increase length
* (example usage: bio_nwrite0(), write to buffer, bio_nwrite()
* or just bio_nwrite(), write to buffer)
*/
static ossl_ssize_t bio_nwrite0(BIO *bio, char **buf)
{
struct bio_bio_st *b;
size_t num;
size_t write_offset;
BIO_clear_retry_flags(bio);
if (!bio->init)
return 0;
b = bio->ptr;
assert(b != NULL);
assert(b->peer != NULL);
assert(b->buf != NULL);
b->request = 0;
if (b->closed) {
BIOerr(BIO_F_BIO_NWRITE0, BIO_R_BROKEN_PIPE);
return -1;
}
assert(b->len <= b->size);
if (b->len == b->size) {
BIO_set_retry_write(bio);
return -1;
}
num = b->size - b->len;
write_offset = b->offset + b->len;
if (write_offset >= b->size)
write_offset -= b->size;
if (write_offset + num > b->size)
/*
* no ring buffer wrap-around for non-copying interface (to fulfil
* the promise by BIO_ctrl_get_write_guarantee, BIO_nwrite may have
* to be called twice)
*/
num = b->size - write_offset;
if (buf != NULL)
*buf = b->buf + write_offset;
assert(write_offset + num <= b->size);
return num;
}
static ossl_ssize_t bio_nwrite(BIO *bio, char **buf, size_t num_)
{
struct bio_bio_st *b;
ossl_ssize_t num, space;
if (num_ > SSIZE_MAX)
num = SSIZE_MAX;
else
num = (ossl_ssize_t) num_;
space = bio_nwrite0(bio, buf);
if (num > space)
num = space;
if (num <= 0)
return num;
b = bio->ptr;
assert(b != NULL);
b->len += num;
assert(b->len <= b->size);
return num;
}
static long bio_ctrl(BIO *bio, int cmd, long num, void *ptr)
{
long ret;
struct bio_bio_st *b = bio->ptr;
assert(b != NULL);
switch (cmd) {
/* specific CTRL codes */
case BIO_C_SET_WRITE_BUF_SIZE:
if (b->peer) {
BIOerr(BIO_F_BIO_CTRL, BIO_R_IN_USE);
ret = 0;
} else if (num == 0) {
BIOerr(BIO_F_BIO_CTRL, BIO_R_INVALID_ARGUMENT);
ret = 0;
} else {
size_t new_size = num;
if (b->size != new_size) {
if (b->buf) {
OPENSSL_free(b->buf);
b->buf = NULL;
}
b->size = new_size;
}
ret = 1;
}
break;
case BIO_C_GET_WRITE_BUF_SIZE:
ret = (long)b->size;
break;
case BIO_C_MAKE_BIO_PAIR:
{
BIO *other_bio = ptr;
if (bio_make_pair(bio, other_bio))
ret = 1;
else
ret = 0;
}
break;
case BIO_C_DESTROY_BIO_PAIR:
/*
* Affects both BIOs in the pair -- call just once! Or let
* BIO_free(bio1); BIO_free(bio2); do the job.
*/
bio_destroy_pair(bio);
ret = 1;
break;
case BIO_C_GET_WRITE_GUARANTEE:
/*
* How many bytes can the caller feed to the next write without
* having to keep any?
*/
if (b->peer == NULL || b->closed)
ret = 0;
else
ret = (long)b->size - b->len;
break;
case BIO_C_GET_READ_REQUEST:
/*
* If the peer unsuccessfully tried to read, how many bytes were
* requested? (As with BIO_CTRL_PENDING, that number can usually be
* treated as boolean.)
*/
ret = (long)b->request;
break;
case BIO_C_RESET_READ_REQUEST:
/*
* Reset request. (Can be useful after read attempts at the other
* side that are meant to be non-blocking, e.g. when probing SSL_read
* to see if any data is available.)
*/
b->request = 0;
ret = 1;
break;
case BIO_C_SHUTDOWN_WR:
/* similar to shutdown(..., SHUT_WR) */
b->closed = 1;
ret = 1;
break;
case BIO_C_NREAD0:
/* prepare for non-copying read */
ret = (long)bio_nread0(bio, ptr);
break;
case BIO_C_NREAD:
/* non-copying read */
ret = (long)bio_nread(bio, ptr, (size_t)num);
break;
case BIO_C_NWRITE0:
/* prepare for non-copying write */
ret = (long)bio_nwrite0(bio, ptr);
break;
case BIO_C_NWRITE:
/* non-copying write */
ret = (long)bio_nwrite(bio, ptr, (size_t)num);
break;
/* standard CTRL codes follow */
case BIO_CTRL_RESET:
if (b->buf != NULL) {
b->len = 0;
b->offset = 0;
}
ret = 0;
break;
case BIO_CTRL_GET_CLOSE:
ret = bio->shutdown;
break;
case BIO_CTRL_SET_CLOSE:
bio->shutdown = (int)num;
ret = 1;
break;
case BIO_CTRL_PENDING:
if (b->peer != NULL) {
struct bio_bio_st *peer_b = b->peer->ptr;
ret = (long)peer_b->len;
} else
ret = 0;
break;
case BIO_CTRL_WPENDING:
if (b->buf != NULL)
ret = (long)b->len;
else
ret = 0;
break;
case BIO_CTRL_DUP:
/* See BIO_dup_chain for circumstances we have to expect. */
{
BIO *other_bio = ptr;
struct bio_bio_st *other_b;
assert(other_bio != NULL);
other_b = other_bio->ptr;
assert(other_b != NULL);
assert(other_b->buf == NULL); /* other_bio is always fresh */
other_b->size = b->size;
}
ret = 1;
break;
case BIO_CTRL_FLUSH:
ret = 1;
break;
case BIO_CTRL_EOF:
if (b->peer != NULL) {
struct bio_bio_st *peer_b = b->peer->ptr;
if (peer_b->len == 0 && peer_b->closed)
ret = 1;
else
ret = 0;
} else {
ret = 1;
}
break;
default:
ret = 0;
}
return ret;
}
static int bio_puts(BIO *bio, const char *str)
{
return bio_write(bio, str, strlen(str));
}
static int bio_make_pair(BIO *bio1, BIO *bio2)
{
struct bio_bio_st *b1, *b2;
assert(bio1 != NULL);
assert(bio2 != NULL);
b1 = bio1->ptr;
b2 = bio2->ptr;
if (b1->peer != NULL || b2->peer != NULL) {
BIOerr(BIO_F_BIO_MAKE_PAIR, BIO_R_IN_USE);
return 0;
}
if (b1->buf == NULL) {
b1->buf = OPENSSL_malloc(b1->size);
if (b1->buf == NULL) {
BIOerr(BIO_F_BIO_MAKE_PAIR, ERR_R_MALLOC_FAILURE);
return 0;
}
b1->len = 0;
b1->offset = 0;
}
if (b2->buf == NULL) {
b2->buf = OPENSSL_malloc(b2->size);
if (b2->buf == NULL) {
BIOerr(BIO_F_BIO_MAKE_PAIR, ERR_R_MALLOC_FAILURE);
return 0;
}
b2->len = 0;
b2->offset = 0;
}
b1->peer = bio2;
b1->closed = 0;
b1->request = 0;
b2->peer = bio1;
b2->closed = 0;
b2->request = 0;
bio1->init = 1;
bio2->init = 1;
return 1;
}
static void bio_destroy_pair(BIO *bio)
{
struct bio_bio_st *b = bio->ptr;
if (b != NULL) {
BIO *peer_bio = b->peer;
if (peer_bio != NULL) {
struct bio_bio_st *peer_b = peer_bio->ptr;
assert(peer_b != NULL);
assert(peer_b->peer == bio);
peer_b->peer = NULL;
peer_bio->init = 0;
assert(peer_b->buf != NULL);
peer_b->len = 0;
peer_b->offset = 0;
b->peer = NULL;
bio->init = 0;
assert(b->buf != NULL);
b->len = 0;
b->offset = 0;
}
}
}
/* Exported convenience functions */
int BIO_new_bio_pair(BIO **bio1_p, size_t writebuf1,
BIO **bio2_p, size_t writebuf2)
{
BIO *bio1 = NULL, *bio2 = NULL;
long r;
int ret = 0;
bio1 = BIO_new(BIO_s_bio());
if (bio1 == NULL)
goto err;
bio2 = BIO_new(BIO_s_bio());
if (bio2 == NULL)
goto err;
if (writebuf1) {
r = BIO_set_write_buf_size(bio1, writebuf1);
if (!r)
goto err;
}
if (writebuf2) {
r = BIO_set_write_buf_size(bio2, writebuf2);
if (!r)
goto err;
}
r = BIO_make_bio_pair(bio1, bio2);
if (!r)
goto err;
ret = 1;
err:
if (ret == 0) {
if (bio1) {
BIO_free(bio1);
bio1 = NULL;
}
if (bio2) {
BIO_free(bio2);
bio2 = NULL;
}
}
*bio1_p = bio1;
*bio2_p = bio2;
return ret;
}
size_t BIO_ctrl_get_write_guarantee(BIO *bio)
{
return BIO_ctrl(bio, BIO_C_GET_WRITE_GUARANTEE, 0, NULL);
}
size_t BIO_ctrl_get_read_request(BIO *bio)
{
return BIO_ctrl(bio, BIO_C_GET_READ_REQUEST, 0, NULL);
}
int BIO_ctrl_reset_read_request(BIO *bio)
{
return (BIO_ctrl(bio, BIO_C_RESET_READ_REQUEST, 0, NULL) != 0);
}
/*
* BIO_nread0/nread/nwrite0/nwrite are available only for BIO pairs for now
* (conceivably some other BIOs could allow non-copying reads and writes
* too.)
*/
int BIO_nread0(BIO *bio, char **buf)
{
long ret;
if (!bio->init) {
BIOerr(BIO_F_BIO_NREAD0, BIO_R_UNINITIALIZED);
return -2;
}
ret = BIO_ctrl(bio, BIO_C_NREAD0, 0, buf);
if (ret > INT_MAX)
return INT_MAX;
else
return (int)ret;
}
int BIO_nread(BIO *bio, char **buf, int num)
{
int ret;
if (!bio->init) {
BIOerr(BIO_F_BIO_NREAD, BIO_R_UNINITIALIZED);
return -2;
}
ret = (int)BIO_ctrl(bio, BIO_C_NREAD, num, buf);
if (ret > 0)
bio->num_read += ret;
return ret;
}
int BIO_nwrite0(BIO *bio, char **buf)
{
long ret;
if (!bio->init) {
BIOerr(BIO_F_BIO_NWRITE0, BIO_R_UNINITIALIZED);
return -2;
}
ret = BIO_ctrl(bio, BIO_C_NWRITE0, 0, buf);
if (ret > INT_MAX)
return INT_MAX;
else
return (int)ret;
}
int BIO_nwrite(BIO *bio, char **buf, int num)
{
int ret;
if (!bio->init) {
BIOerr(BIO_F_BIO_NWRITE, BIO_R_UNINITIALIZED);
return -2;
}
ret = BIO_ctrl(bio, BIO_C_NWRITE, num, buf);
if (ret > 0)
bio->num_write += ret;
return ret;
}
diff --git a/crypto/bio/bss_conn.c b/crypto/bio/bss_conn.c
index 7d15ad29dcd7..bbc6d5ab48bc 100644
--- a/crypto/bio/bss_conn.c
+++ b/crypto/bio/bss_conn.c
@@ -1,612 +1,612 @@
/* crypto/bio/bss_conn.c */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
#include <stdio.h>
#include <errno.h>
#define USE_SOCKETS
#include "cryptlib.h"
#include <openssl/bio.h>
#ifndef OPENSSL_NO_SOCK
# ifdef OPENSSL_SYS_WIN16
# define SOCKET_PROTOCOL 0 /* more microsoft stupidity */
# else
# define SOCKET_PROTOCOL IPPROTO_TCP
# endif
# if (defined(OPENSSL_SYS_VMS) && __VMS_VER < 70000000)
/* FIONBIO used as a switch to enable ioctl, and that isn't in VMS < 7.0 */
# undef FIONBIO
# endif
typedef struct bio_connect_st {
int state;
char *param_hostname;
char *param_port;
int nbio;
unsigned char ip[4];
unsigned short port;
struct sockaddr_in them;
/*
* int socket; this will be kept in bio->num so that it is compatible
* with the bss_sock bio
*/
/*
* called when the connection is initially made callback(BIO,state,ret);
* The callback should return 'ret'. state is for compatibility with the
* ssl info_callback
*/
int (*info_callback) (const BIO *bio, int state, int ret);
} BIO_CONNECT;
static int conn_write(BIO *h, const char *buf, int num);
static int conn_read(BIO *h, char *buf, int size);
static int conn_puts(BIO *h, const char *str);
static long conn_ctrl(BIO *h, int cmd, long arg1, void *arg2);
static int conn_new(BIO *h);
static int conn_free(BIO *data);
static long conn_callback_ctrl(BIO *h, int cmd, bio_info_cb *);
static int conn_state(BIO *b, BIO_CONNECT *c);
static void conn_close_socket(BIO *data);
BIO_CONNECT *BIO_CONNECT_new(void);
void BIO_CONNECT_free(BIO_CONNECT *a);
static BIO_METHOD methods_connectp = {
BIO_TYPE_CONNECT,
"socket connect",
conn_write,
conn_read,
conn_puts,
NULL, /* connect_gets, */
conn_ctrl,
conn_new,
conn_free,
conn_callback_ctrl,
};
static int conn_state(BIO *b, BIO_CONNECT *c)
{
int ret = -1, i;
unsigned long l;
char *p, *q;
int (*cb) (const BIO *, int, int) = NULL;
if (c->info_callback != NULL)
cb = c->info_callback;
for (;;) {
switch (c->state) {
case BIO_CONN_S_BEFORE:
p = c->param_hostname;
if (p == NULL) {
BIOerr(BIO_F_CONN_STATE, BIO_R_NO_HOSTNAME_SPECIFIED);
goto exit_loop;
}
for (; *p != '\0'; p++) {
if ((*p == ':') || (*p == '/'))
break;
}
i = *p;
if ((i == ':') || (i == '/')) {
*(p++) = '\0';
if (i == ':') {
for (q = p; *q; q++)
if (*q == '/') {
*q = '\0';
break;
}
if (c->param_port != NULL)
OPENSSL_free(c->param_port);
c->param_port = BUF_strdup(p);
}
}
if (c->param_port == NULL) {
BIOerr(BIO_F_CONN_STATE, BIO_R_NO_PORT_SPECIFIED);
ERR_add_error_data(2, "host=", c->param_hostname);
goto exit_loop;
}
c->state = BIO_CONN_S_GET_IP;
break;
case BIO_CONN_S_GET_IP:
if (BIO_get_host_ip(c->param_hostname, &(c->ip[0])) <= 0)
goto exit_loop;
c->state = BIO_CONN_S_GET_PORT;
break;
case BIO_CONN_S_GET_PORT:
if (c->param_port == NULL) {
/* abort(); */
goto exit_loop;
} else if (BIO_get_port(c->param_port, &c->port) <= 0)
goto exit_loop;
c->state = BIO_CONN_S_CREATE_SOCKET;
break;
case BIO_CONN_S_CREATE_SOCKET:
/* now setup address */
memset((char *)&c->them, 0, sizeof(c->them));
c->them.sin_family = AF_INET;
c->them.sin_port = htons((unsigned short)c->port);
l = (unsigned long)
((unsigned long)c->ip[0] << 24L) |
((unsigned long)c->ip[1] << 16L) |
((unsigned long)c->ip[2] << 8L) | ((unsigned long)c->ip[3]);
c->them.sin_addr.s_addr = htonl(l);
c->state = BIO_CONN_S_CREATE_SOCKET;
ret = socket(AF_INET, SOCK_STREAM, SOCKET_PROTOCOL);
if (ret == INVALID_SOCKET) {
SYSerr(SYS_F_SOCKET, get_last_socket_error());
ERR_add_error_data(4, "host=", c->param_hostname,
":", c->param_port);
BIOerr(BIO_F_CONN_STATE, BIO_R_UNABLE_TO_CREATE_SOCKET);
goto exit_loop;
}
b->num = ret;
c->state = BIO_CONN_S_NBIO;
break;
case BIO_CONN_S_NBIO:
if (c->nbio) {
if (!BIO_socket_nbio(b->num, 1)) {
BIOerr(BIO_F_CONN_STATE, BIO_R_ERROR_SETTING_NBIO);
ERR_add_error_data(4, "host=",
c->param_hostname, ":", c->param_port);
goto exit_loop;
}
}
c->state = BIO_CONN_S_CONNECT;
# if defined(SO_KEEPALIVE) && !defined(OPENSSL_SYS_MPE)
i = 1;
i = setsockopt(b->num, SOL_SOCKET, SO_KEEPALIVE, (char *)&i,
sizeof(i));
if (i < 0) {
SYSerr(SYS_F_SOCKET, get_last_socket_error());
ERR_add_error_data(4, "host=", c->param_hostname,
":", c->param_port);
BIOerr(BIO_F_CONN_STATE, BIO_R_KEEPALIVE);
goto exit_loop;
}
# endif
break;
case BIO_CONN_S_CONNECT:
BIO_clear_retry_flags(b);
ret = connect(b->num,
(struct sockaddr *)&c->them, sizeof(c->them));
b->retry_reason = 0;
if (ret < 0) {
if (BIO_sock_should_retry(ret)) {
BIO_set_retry_special(b);
c->state = BIO_CONN_S_BLOCKED_CONNECT;
b->retry_reason = BIO_RR_CONNECT;
} else {
SYSerr(SYS_F_CONNECT, get_last_socket_error());
ERR_add_error_data(4, "host=",
c->param_hostname, ":", c->param_port);
BIOerr(BIO_F_CONN_STATE, BIO_R_CONNECT_ERROR);
}
goto exit_loop;
} else
c->state = BIO_CONN_S_OK;
break;
case BIO_CONN_S_BLOCKED_CONNECT:
i = BIO_sock_error(b->num);
if (i) {
BIO_clear_retry_flags(b);
SYSerr(SYS_F_CONNECT, i);
ERR_add_error_data(4, "host=",
c->param_hostname, ":", c->param_port);
BIOerr(BIO_F_CONN_STATE, BIO_R_NBIO_CONNECT_ERROR);
ret = 0;
goto exit_loop;
} else
c->state = BIO_CONN_S_OK;
break;
case BIO_CONN_S_OK:
ret = 1;
goto exit_loop;
default:
/* abort(); */
goto exit_loop;
}
if (cb != NULL) {
if (!(ret = cb((BIO *)b, c->state, ret)))
goto end;
}
}
/* Loop does not exit */
exit_loop:
if (cb != NULL)
ret = cb((BIO *)b, c->state, ret);
end:
return (ret);
}
BIO_CONNECT *BIO_CONNECT_new(void)
{
BIO_CONNECT *ret;
if ((ret = (BIO_CONNECT *)OPENSSL_malloc(sizeof(BIO_CONNECT))) == NULL)
return (NULL);
ret->state = BIO_CONN_S_BEFORE;
ret->param_hostname = NULL;
ret->param_port = NULL;
ret->info_callback = NULL;
ret->nbio = 0;
ret->ip[0] = 0;
ret->ip[1] = 0;
ret->ip[2] = 0;
ret->ip[3] = 0;
ret->port = 0;
memset((char *)&ret->them, 0, sizeof(ret->them));
return (ret);
}
void BIO_CONNECT_free(BIO_CONNECT *a)
{
if (a == NULL)
return;
if (a->param_hostname != NULL)
OPENSSL_free(a->param_hostname);
if (a->param_port != NULL)
OPENSSL_free(a->param_port);
OPENSSL_free(a);
}
BIO_METHOD *BIO_s_connect(void)
{
return (&methods_connectp);
}
static int conn_new(BIO *bi)
{
bi->init = 0;
bi->num = INVALID_SOCKET;
bi->flags = 0;
if ((bi->ptr = (char *)BIO_CONNECT_new()) == NULL)
return (0);
else
return (1);
}
static void conn_close_socket(BIO *bio)
{
BIO_CONNECT *c;
c = (BIO_CONNECT *)bio->ptr;
if (bio->num != INVALID_SOCKET) {
/* Only do a shutdown if things were established */
if (c->state == BIO_CONN_S_OK)
shutdown(bio->num, 2);
closesocket(bio->num);
bio->num = INVALID_SOCKET;
}
}
static int conn_free(BIO *a)
{
BIO_CONNECT *data;
if (a == NULL)
return (0);
data = (BIO_CONNECT *)a->ptr;
if (a->shutdown) {
conn_close_socket(a);
BIO_CONNECT_free(data);
a->ptr = NULL;
a->flags = 0;
a->init = 0;
}
return (1);
}
static int conn_read(BIO *b, char *out, int outl)
{
int ret = 0;
BIO_CONNECT *data;
data = (BIO_CONNECT *)b->ptr;
if (data->state != BIO_CONN_S_OK) {
ret = conn_state(b, data);
if (ret <= 0)
return (ret);
}
if (out != NULL) {
clear_socket_error();
ret = readsocket(b->num, out, outl);
BIO_clear_retry_flags(b);
if (ret <= 0) {
if (BIO_sock_should_retry(ret))
BIO_set_retry_read(b);
}
}
return (ret);
}
static int conn_write(BIO *b, const char *in, int inl)
{
int ret;
BIO_CONNECT *data;
data = (BIO_CONNECT *)b->ptr;
if (data->state != BIO_CONN_S_OK) {
ret = conn_state(b, data);
if (ret <= 0)
return (ret);
}
clear_socket_error();
ret = writesocket(b->num, in, inl);
BIO_clear_retry_flags(b);
if (ret <= 0) {
if (BIO_sock_should_retry(ret))
BIO_set_retry_write(b);
}
return (ret);
}
static long conn_ctrl(BIO *b, int cmd, long num, void *ptr)
{
BIO *dbio;
int *ip;
const char **pptr = NULL;
long ret = 1;
BIO_CONNECT *data;
data = (BIO_CONNECT *)b->ptr;
switch (cmd) {
case BIO_CTRL_RESET:
ret = 0;
data->state = BIO_CONN_S_BEFORE;
conn_close_socket(b);
b->flags = 0;
break;
case BIO_C_DO_STATE_MACHINE:
/* use this one to start the connection */
if (data->state != BIO_CONN_S_OK)
ret = (long)conn_state(b, data);
else
ret = 1;
break;
case BIO_C_GET_CONNECT:
if (ptr != NULL) {
pptr = (const char **)ptr;
}
if (b->init) {
if (pptr != NULL) {
ret = 1;
if (num == 0) {
*pptr = data->param_hostname;
} else if (num == 1) {
*pptr = data->param_port;
} else if (num == 2) {
*pptr = (char *)&(data->ip[0]);
} else {
ret = 0;
}
}
if (num == 3) {
ret = data->port;
}
} else {
if (pptr != NULL)
*pptr = "not initialized";
ret = 0;
}
break;
case BIO_C_SET_CONNECT:
if (ptr != NULL) {
b->init = 1;
if (num == 0) {
if (data->param_hostname != NULL)
OPENSSL_free(data->param_hostname);
data->param_hostname = BUF_strdup(ptr);
} else if (num == 1) {
if (data->param_port != NULL)
OPENSSL_free(data->param_port);
data->param_port = BUF_strdup(ptr);
} else if (num == 2) {
char buf[16];
unsigned char *p = ptr;
- BIO_snprintf(buf, sizeof buf, "%d.%d.%d.%d",
+ BIO_snprintf(buf, sizeof(buf), "%d.%d.%d.%d",
p[0], p[1], p[2], p[3]);
if (data->param_hostname != NULL)
OPENSSL_free(data->param_hostname);
data->param_hostname = BUF_strdup(buf);
memcpy(&(data->ip[0]), ptr, 4);
} else if (num == 3) {
char buf[DECIMAL_SIZE(int) + 1];
- BIO_snprintf(buf, sizeof buf, "%d", *(int *)ptr);
+ BIO_snprintf(buf, sizeof(buf), "%d", *(int *)ptr);
if (data->param_port != NULL)
OPENSSL_free(data->param_port);
data->param_port = BUF_strdup(buf);
data->port = *(int *)ptr;
}
}
break;
case BIO_C_SET_NBIO:
data->nbio = (int)num;
break;
case BIO_C_GET_FD:
if (b->init) {
ip = (int *)ptr;
if (ip != NULL)
*ip = b->num;
ret = b->num;
} else
ret = -1;
break;
case BIO_CTRL_GET_CLOSE:
ret = b->shutdown;
break;
case BIO_CTRL_SET_CLOSE:
b->shutdown = (int)num;
break;
case BIO_CTRL_PENDING:
case BIO_CTRL_WPENDING:
ret = 0;
break;
case BIO_CTRL_FLUSH:
break;
case BIO_CTRL_DUP:
{
dbio = (BIO *)ptr;
if (data->param_port)
BIO_set_conn_port(dbio, data->param_port);
if (data->param_hostname)
BIO_set_conn_hostname(dbio, data->param_hostname);
BIO_set_nbio(dbio, data->nbio);
/*
* FIXME: the cast of the function seems unlikely to be a good
* idea
*/
(void)BIO_set_info_callback(dbio,
(bio_info_cb *)data->info_callback);
}
break;
case BIO_CTRL_SET_CALLBACK:
{
# if 0 /* FIXME: Should this be used? -- Richard
* Levitte */
BIOerr(BIO_F_CONN_CTRL, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
ret = -1;
# else
ret = 0;
# endif
}
break;
case BIO_CTRL_GET_CALLBACK:
{
int (**fptr) (const BIO *bio, int state, int xret);
fptr = (int (**)(const BIO *bio, int state, int xret))ptr;
*fptr = data->info_callback;
}
break;
default:
ret = 0;
break;
}
return (ret);
}
static long conn_callback_ctrl(BIO *b, int cmd, bio_info_cb *fp)
{
long ret = 1;
BIO_CONNECT *data;
data = (BIO_CONNECT *)b->ptr;
switch (cmd) {
case BIO_CTRL_SET_CALLBACK:
{
data->info_callback =
(int (*)(const struct bio_st *, int, int))fp;
}
break;
default:
ret = 0;
break;
}
return (ret);
}
static int conn_puts(BIO *bp, const char *str)
{
int n, ret;
n = strlen(str);
ret = conn_write(bp, str, n);
return (ret);
}
BIO *BIO_new_connect(const char *str)
{
BIO *ret;
ret = BIO_new(BIO_s_connect());
if (ret == NULL)
return (NULL);
if (BIO_set_conn_hostname(ret, str))
return (ret);
else {
BIO_free(ret);
return (NULL);
}
}
#endif
diff --git a/crypto/bio/bss_file.c b/crypto/bio/bss_file.c
index 0cf67e5b770b..bbf906fabba0 100644
--- a/crypto/bio/bss_file.c
+++ b/crypto/bio/bss_file.c
@@ -1,484 +1,484 @@
/* crypto/bio/bss_file.c */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
/*-
* 03-Dec-1997 rdenny@dc3.com Fix bug preventing use of stdin/stdout
* with binary data (e.g. asn1parse -inform DER < xxx) under
* Windows
*/
#ifndef HEADER_BSS_FILE_C
# define HEADER_BSS_FILE_C
# if defined(__linux) || defined(__sun) || defined(__hpux)
/*
* Following definition aliases fopen to fopen64 on above mentioned
* platforms. This makes it possible to open and sequentially access files
* larger than 2GB from 32-bit application. It does not allow to traverse
* them beyond 2GB with fseek/ftell, but on the other hand *no* 32-bit
* platform permits that, not with fseek/ftell. Not to mention that breaking
* 2GB limit for seeking would require surgery to *our* API. But sequential
* access suffices for practical cases when you can run into large files,
* such as fingerprinting, so we can let API alone. For reference, the list
* of 32-bit platforms which allow for sequential access of large files
* without extra "magic" comprise *BSD, Darwin, IRIX...
*/
# ifndef _FILE_OFFSET_BITS
# define _FILE_OFFSET_BITS 64
# endif
# endif
# include <stdio.h>
# include <errno.h>
# include "cryptlib.h"
# include "bio_lcl.h"
# include <openssl/err.h>
# if defined(OPENSSL_SYS_NETWARE) && defined(NETWARE_CLIB)
# include <nwfileio.h>
# endif
# if !defined(OPENSSL_NO_STDIO)
static int MS_CALLBACK file_write(BIO *h, const char *buf, int num);
static int MS_CALLBACK file_read(BIO *h, char *buf, int size);
static int MS_CALLBACK file_puts(BIO *h, const char *str);
static int MS_CALLBACK file_gets(BIO *h, char *str, int size);
static long MS_CALLBACK file_ctrl(BIO *h, int cmd, long arg1, void *arg2);
static int MS_CALLBACK file_new(BIO *h);
static int MS_CALLBACK file_free(BIO *data);
static BIO_METHOD methods_filep = {
BIO_TYPE_FILE,
"FILE pointer",
file_write,
file_read,
file_puts,
file_gets,
file_ctrl,
file_new,
file_free,
NULL,
};
static FILE *file_fopen(const char *filename, const char *mode)
{
FILE *file = NULL;
# if defined(_WIN32) && defined(CP_UTF8)
int sz, len_0 = (int)strlen(filename) + 1;
DWORD flags;
/*
* Basically there are three cases to cover: a) filename is
* pure ASCII string; b) actual UTF-8 encoded string and
* c) locale-ized string, i.e. one containing 8-bit
* characters that are meaningful in current system locale.
* If filename is pure ASCII or real UTF-8 encoded string,
* MultiByteToWideChar succeeds and _wfopen works. If
* filename is locale-ized string, chances are that
* MultiByteToWideChar fails reporting
* ERROR_NO_UNICODE_TRANSLATION, in which case we fall
* back to fopen...
*/
if ((sz = MultiByteToWideChar(CP_UTF8, (flags = MB_ERR_INVALID_CHARS),
filename, len_0, NULL, 0)) > 0 ||
(GetLastError() == ERROR_INVALID_FLAGS &&
(sz = MultiByteToWideChar(CP_UTF8, (flags = 0),
filename, len_0, NULL, 0)) > 0)
) {
WCHAR wmode[8];
WCHAR *wfilename = _alloca(sz * sizeof(WCHAR));
if (MultiByteToWideChar(CP_UTF8, flags,
filename, len_0, wfilename, sz) &&
MultiByteToWideChar(CP_UTF8, 0, mode, strlen(mode) + 1,
wmode, sizeof(wmode) / sizeof(wmode[0])) &&
(file = _wfopen(wfilename, wmode)) == NULL &&
(errno == ENOENT || errno == EBADF)
) {
/*
* UTF-8 decode succeeded, but no file, filename
* could still have been locale-ized...
*/
file = fopen(filename, mode);
}
} else if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION) {
file = fopen(filename, mode);
}
# else
file = fopen(filename, mode);
# endif
return (file);
}
BIO *BIO_new_file(const char *filename, const char *mode)
{
BIO *ret;
FILE *file = file_fopen(filename, mode);
if (file == NULL) {
SYSerr(SYS_F_FOPEN, get_last_sys_error());
ERR_add_error_data(5, "fopen('", filename, "','", mode, "')");
if (errno == ENOENT
# ifdef ENXIO
|| errno == ENXIO
# endif
)
BIOerr(BIO_F_BIO_NEW_FILE, BIO_R_NO_SUCH_FILE);
else
BIOerr(BIO_F_BIO_NEW_FILE, ERR_R_SYS_LIB);
return (NULL);
}
if ((ret = BIO_new(BIO_s_file())) == NULL) {
fclose(file);
return (NULL);
}
BIO_clear_flags(ret, BIO_FLAGS_UPLINK); /* we did fopen -> we disengage
* UPLINK */
BIO_set_fp(ret, file, BIO_CLOSE);
return (ret);
}
BIO *BIO_new_fp(FILE *stream, int close_flag)
{
BIO *ret;
if ((ret = BIO_new(BIO_s_file())) == NULL)
return (NULL);
BIO_set_flags(ret, BIO_FLAGS_UPLINK); /* redundant, left for
* documentation puposes */
BIO_set_fp(ret, stream, close_flag);
return (ret);
}
BIO_METHOD *BIO_s_file(void)
{
return (&methods_filep);
}
static int MS_CALLBACK file_new(BIO *bi)
{
bi->init = 0;
bi->num = 0;
bi->ptr = NULL;
bi->flags = BIO_FLAGS_UPLINK; /* default to UPLINK */
return (1);
}
static int MS_CALLBACK file_free(BIO *a)
{
if (a == NULL)
return (0);
if (a->shutdown) {
if ((a->init) && (a->ptr != NULL)) {
if (a->flags & BIO_FLAGS_UPLINK)
UP_fclose(a->ptr);
else
fclose(a->ptr);
a->ptr = NULL;
a->flags = BIO_FLAGS_UPLINK;
}
a->init = 0;
}
return (1);
}
static int MS_CALLBACK file_read(BIO *b, char *out, int outl)
{
int ret = 0;
if (b->init && (out != NULL)) {
if (b->flags & BIO_FLAGS_UPLINK)
ret = UP_fread(out, 1, (int)outl, b->ptr);
else
ret = fread(out, 1, (int)outl, (FILE *)b->ptr);
if (ret == 0
&& (b->flags & BIO_FLAGS_UPLINK) ? UP_ferror((FILE *)b->ptr) :
ferror((FILE *)b->ptr)) {
SYSerr(SYS_F_FREAD, get_last_sys_error());
BIOerr(BIO_F_FILE_READ, ERR_R_SYS_LIB);
ret = -1;
}
}
return (ret);
}
static int MS_CALLBACK file_write(BIO *b, const char *in, int inl)
{
int ret = 0;
if (b->init && (in != NULL)) {
if (b->flags & BIO_FLAGS_UPLINK)
ret = UP_fwrite(in, (int)inl, 1, b->ptr);
else
ret = fwrite(in, (int)inl, 1, (FILE *)b->ptr);
if (ret)
ret = inl;
/* ret=fwrite(in,1,(int)inl,(FILE *)b->ptr); */
/*
* according to Tim Hudson <tjh@cryptsoft.com>, the commented out
* version above can cause 'inl' write calls under some stupid stdio
* implementations (VMS)
*/
}
return (ret);
}
static long MS_CALLBACK file_ctrl(BIO *b, int cmd, long num, void *ptr)
{
long ret = 1;
FILE *fp = (FILE *)b->ptr;
FILE **fpp;
char p[4];
int st;
switch (cmd) {
case BIO_C_FILE_SEEK:
case BIO_CTRL_RESET:
if (b->flags & BIO_FLAGS_UPLINK)
ret = (long)UP_fseek(b->ptr, num, 0);
else
ret = (long)fseek(fp, num, 0);
break;
case BIO_CTRL_EOF:
if (b->flags & BIO_FLAGS_UPLINK)
ret = (long)UP_feof(fp);
else
ret = (long)feof(fp);
break;
case BIO_C_FILE_TELL:
case BIO_CTRL_INFO:
if (b->flags & BIO_FLAGS_UPLINK)
ret = UP_ftell(b->ptr);
else
ret = ftell(fp);
break;
case BIO_C_SET_FILE_PTR:
file_free(b);
b->shutdown = (int)num & BIO_CLOSE;
b->ptr = ptr;
b->init = 1;
# if BIO_FLAGS_UPLINK!=0
# if defined(__MINGW32__) && defined(__MSVCRT__) && !defined(_IOB_ENTRIES)
# define _IOB_ENTRIES 20
# endif
/* Safety net to catch purely internal BIO_set_fp calls */
# if defined(_MSC_VER) && _MSC_VER>=1900
if (ptr == stdin || ptr == stdout || ptr == stderr)
BIO_clear_flags(b, BIO_FLAGS_UPLINK);
# elif defined(_IOB_ENTRIES)
if ((size_t)ptr >= (size_t)stdin &&
(size_t)ptr < (size_t)(stdin + _IOB_ENTRIES))
BIO_clear_flags(b, BIO_FLAGS_UPLINK);
# endif
# endif
# ifdef UP_fsetmod
if (b->flags & BIO_FLAGS_UPLINK)
UP_fsetmod(b->ptr, (char)((num & BIO_FP_TEXT) ? 't' : 'b'));
else
# endif
{
# if defined(OPENSSL_SYS_WINDOWS)
int fd = _fileno((FILE *)ptr);
if (num & BIO_FP_TEXT)
_setmode(fd, _O_TEXT);
else
_setmode(fd, _O_BINARY);
# elif defined(OPENSSL_SYS_NETWARE) && defined(NETWARE_CLIB)
int fd = fileno((FILE *)ptr);
/* Under CLib there are differences in file modes */
if (num & BIO_FP_TEXT)
setmode(fd, O_TEXT);
else
setmode(fd, O_BINARY);
# elif defined(OPENSSL_SYS_MSDOS)
int fd = fileno((FILE *)ptr);
/* Set correct text/binary mode */
if (num & BIO_FP_TEXT)
_setmode(fd, _O_TEXT);
/* Dangerous to set stdin/stdout to raw (unless redirected) */
else {
if (fd == STDIN_FILENO || fd == STDOUT_FILENO) {
if (isatty(fd) <= 0)
_setmode(fd, _O_BINARY);
} else
_setmode(fd, _O_BINARY);
}
# elif defined(OPENSSL_SYS_OS2) || defined(OPENSSL_SYS_WIN32_CYGWIN)
int fd = fileno((FILE *)ptr);
if (num & BIO_FP_TEXT)
setmode(fd, O_TEXT);
else
setmode(fd, O_BINARY);
# endif
}
break;
case BIO_C_SET_FILENAME:
file_free(b);
b->shutdown = (int)num & BIO_CLOSE;
if (num & BIO_FP_APPEND) {
if (num & BIO_FP_READ)
- BUF_strlcpy(p, "a+", sizeof p);
+ BUF_strlcpy(p, "a+", sizeof(p));
else
- BUF_strlcpy(p, "a", sizeof p);
+ BUF_strlcpy(p, "a", sizeof(p));
} else if ((num & BIO_FP_READ) && (num & BIO_FP_WRITE))
- BUF_strlcpy(p, "r+", sizeof p);
+ BUF_strlcpy(p, "r+", sizeof(p));
else if (num & BIO_FP_WRITE)
- BUF_strlcpy(p, "w", sizeof p);
+ BUF_strlcpy(p, "w", sizeof(p));
else if (num & BIO_FP_READ)
- BUF_strlcpy(p, "r", sizeof p);
+ BUF_strlcpy(p, "r", sizeof(p));
else {
BIOerr(BIO_F_FILE_CTRL, BIO_R_BAD_FOPEN_MODE);
ret = 0;
break;
}
# if defined(OPENSSL_SYS_MSDOS) || defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_OS2) || defined(OPENSSL_SYS_WIN32_CYGWIN)
if (!(num & BIO_FP_TEXT))
strcat(p, "b");
else
strcat(p, "t");
# endif
# if defined(OPENSSL_SYS_NETWARE)
if (!(num & BIO_FP_TEXT))
strcat(p, "b");
else
strcat(p, "t");
# endif
fp = file_fopen(ptr, p);
if (fp == NULL) {
SYSerr(SYS_F_FOPEN, get_last_sys_error());
ERR_add_error_data(5, "fopen('", ptr, "','", p, "')");
BIOerr(BIO_F_FILE_CTRL, ERR_R_SYS_LIB);
ret = 0;
break;
}
b->ptr = fp;
b->init = 1;
BIO_clear_flags(b, BIO_FLAGS_UPLINK); /* we did fopen -> we disengage
* UPLINK */
break;
case BIO_C_GET_FILE_PTR:
/* the ptr parameter is actually a FILE ** in this case. */
if (ptr != NULL) {
fpp = (FILE **)ptr;
*fpp = (FILE *)b->ptr;
}
break;
case BIO_CTRL_GET_CLOSE:
ret = (long)b->shutdown;
break;
case BIO_CTRL_SET_CLOSE:
b->shutdown = (int)num;
break;
case BIO_CTRL_FLUSH:
st = b->flags & BIO_FLAGS_UPLINK
? UP_fflush(b->ptr) : fflush((FILE *)b->ptr);
if (st == EOF) {
SYSerr(SYS_F_FFLUSH, get_last_sys_error());
ERR_add_error_data(1, "fflush()");
BIOerr(BIO_F_FILE_CTRL, ERR_R_SYS_LIB);
ret = 0;
}
break;
case BIO_CTRL_DUP:
ret = 1;
break;
case BIO_CTRL_WPENDING:
case BIO_CTRL_PENDING:
case BIO_CTRL_PUSH:
case BIO_CTRL_POP:
default:
ret = 0;
break;
}
return (ret);
}
static int MS_CALLBACK file_gets(BIO *bp, char *buf, int size)
{
int ret = 0;
buf[0] = '\0';
if (bp->flags & BIO_FLAGS_UPLINK) {
if (!UP_fgets(buf, size, bp->ptr))
goto err;
} else {
if (!fgets(buf, size, (FILE *)bp->ptr))
goto err;
}
if (buf[0] != '\0')
ret = strlen(buf);
err:
return (ret);
}
static int MS_CALLBACK file_puts(BIO *bp, const char *str)
{
int n, ret;
n = strlen(str);
ret = file_write(bp, str, n);
return (ret);
}
# endif /* OPENSSL_NO_STDIO */
#endif /* HEADER_BSS_FILE_C */
diff --git a/crypto/bn/bn_exp.c b/crypto/bn/bn_exp.c
index c4b63e44ba36..40115fc72052 100644
--- a/crypto/bn/bn_exp.c
+++ b/crypto/bn/bn_exp.c
@@ -1,1468 +1,1472 @@
/* crypto/bn/bn_exp.c */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
/* ====================================================================
- * Copyright (c) 1998-2005 The OpenSSL Project. All rights reserved.
+ * Copyright (c) 1998-2018 The OpenSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* openssl-core@openssl.org.
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.openssl.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*
* This product includes cryptographic software written by Eric Young
* (eay@cryptsoft.com). This product includes software written by Tim
* Hudson (tjh@cryptsoft.com).
*
*/
#include "cryptlib.h"
#include "constant_time_locl.h"
#include "bn_lcl.h"
#include <stdlib.h>
#ifdef _WIN32
# include <malloc.h>
# ifndef alloca
# define alloca _alloca
# endif
#elif defined(__GNUC__)
# ifndef alloca
# define alloca(s) __builtin_alloca((s))
# endif
#elif defined(__sun)
# include <alloca.h>
#endif
#include "rsaz_exp.h"
#undef SPARC_T4_MONT
#if defined(OPENSSL_BN_ASM_MONT) && (defined(__sparc__) || defined(__sparc))
# include "sparc_arch.h"
extern unsigned int OPENSSL_sparcv9cap_P[];
# define SPARC_T4_MONT
#endif
/* maximum precomputation table size for *variable* sliding windows */
#define TABLE_SIZE 32
/* this one works - simple but works */
int BN_exp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, BN_CTX *ctx)
{
int i, bits, ret = 0;
BIGNUM *v, *rr;
if (BN_get_flags(p, BN_FLG_CONSTTIME) != 0
|| BN_get_flags(a, BN_FLG_CONSTTIME) != 0) {
/* BN_FLG_CONSTTIME only supported by BN_mod_exp_mont() */
BNerr(BN_F_BN_EXP, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
return 0;
}
BN_CTX_start(ctx);
if ((r == a) || (r == p))
rr = BN_CTX_get(ctx);
else
rr = r;
v = BN_CTX_get(ctx);
if (rr == NULL || v == NULL)
goto err;
if (BN_copy(v, a) == NULL)
goto err;
bits = BN_num_bits(p);
if (BN_is_odd(p)) {
if (BN_copy(rr, a) == NULL)
goto err;
} else {
if (!BN_one(rr))
goto err;
}
for (i = 1; i < bits; i++) {
if (!BN_sqr(v, v, ctx))
goto err;
if (BN_is_bit_set(p, i)) {
if (!BN_mul(rr, rr, v, ctx))
goto err;
}
}
if (r != rr && BN_copy(r, rr) == NULL)
goto err;
ret = 1;
err:
BN_CTX_end(ctx);
bn_check_top(r);
return (ret);
}
int BN_mod_exp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, const BIGNUM *m,
BN_CTX *ctx)
{
int ret;
bn_check_top(a);
bn_check_top(p);
bn_check_top(m);
/*-
* For even modulus m = 2^k*m_odd, it might make sense to compute
* a^p mod m_odd and a^p mod 2^k separately (with Montgomery
* exponentiation for the odd part), using appropriate exponent
* reductions, and combine the results using the CRT.
*
* For now, we use Montgomery only if the modulus is odd; otherwise,
* exponentiation using the reciprocal-based quick remaindering
* algorithm is used.
*
* (Timing obtained with expspeed.c [computations a^p mod m
* where a, p, m are of the same length: 256, 512, 1024, 2048,
* 4096, 8192 bits], compared to the running time of the
* standard algorithm:
*
* BN_mod_exp_mont 33 .. 40 % [AMD K6-2, Linux, debug configuration]
* 55 .. 77 % [UltraSparc processor, but
* debug-solaris-sparcv8-gcc conf.]
*
* BN_mod_exp_recp 50 .. 70 % [AMD K6-2, Linux, debug configuration]
* 62 .. 118 % [UltraSparc, debug-solaris-sparcv8-gcc]
*
* On the Sparc, BN_mod_exp_recp was faster than BN_mod_exp_mont
* at 2048 and more bits, but at 512 and 1024 bits, it was
* slower even than the standard algorithm!
*
* "Real" timings [linux-elf, solaris-sparcv9-gcc configurations]
* should be obtained when the new Montgomery reduction code
* has been integrated into OpenSSL.)
*/
#define MONT_MUL_MOD
#define MONT_EXP_WORD
#define RECP_MUL_MOD
#ifdef MONT_MUL_MOD
/*
* I have finally been able to take out this pre-condition of the top bit
* being set. It was caused by an error in BN_div with negatives. There
* was also another problem when for a^b%m a >= m. eay 07-May-97
*/
/* if ((m->d[m->top-1]&BN_TBIT) && BN_is_odd(m)) */
if (BN_is_odd(m)) {
# ifdef MONT_EXP_WORD
if (a->top == 1 && !a->neg
&& (BN_get_flags(p, BN_FLG_CONSTTIME) == 0)
&& (BN_get_flags(a, BN_FLG_CONSTTIME) == 0)
&& (BN_get_flags(m, BN_FLG_CONSTTIME) == 0)) {
BN_ULONG A = a->d[0];
ret = BN_mod_exp_mont_word(r, A, p, m, ctx, NULL);
} else
# endif
ret = BN_mod_exp_mont(r, a, p, m, ctx, NULL);
} else
#endif
#ifdef RECP_MUL_MOD
{
ret = BN_mod_exp_recp(r, a, p, m, ctx);
}
#else
{
ret = BN_mod_exp_simple(r, a, p, m, ctx);
}
#endif
bn_check_top(r);
return (ret);
}
int BN_mod_exp_recp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p,
const BIGNUM *m, BN_CTX *ctx)
{
int i, j, bits, ret = 0, wstart, wend, window, wvalue;
int start = 1;
BIGNUM *aa;
/* Table of variables obtained from 'ctx' */
BIGNUM *val[TABLE_SIZE];
BN_RECP_CTX recp;
if (BN_get_flags(p, BN_FLG_CONSTTIME) != 0
|| BN_get_flags(a, BN_FLG_CONSTTIME) != 0
|| BN_get_flags(m, BN_FLG_CONSTTIME) != 0) {
/* BN_FLG_CONSTTIME only supported by BN_mod_exp_mont() */
BNerr(BN_F_BN_MOD_EXP_RECP, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
return 0;
}
bits = BN_num_bits(p);
if (bits == 0) {
/* x**0 mod 1 is still zero. */
if (BN_is_one(m)) {
ret = 1;
BN_zero(r);
} else {
ret = BN_one(r);
}
return ret;
}
BN_CTX_start(ctx);
aa = BN_CTX_get(ctx);
val[0] = BN_CTX_get(ctx);
if (!aa || !val[0])
goto err;
BN_RECP_CTX_init(&recp);
if (m->neg) {
/* ignore sign of 'm' */
if (!BN_copy(aa, m))
goto err;
aa->neg = 0;
if (BN_RECP_CTX_set(&recp, aa, ctx) <= 0)
goto err;
} else {
if (BN_RECP_CTX_set(&recp, m, ctx) <= 0)
goto err;
}
if (!BN_nnmod(val[0], a, m, ctx))
goto err; /* 1 */
if (BN_is_zero(val[0])) {
BN_zero(r);
ret = 1;
goto err;
}
window = BN_window_bits_for_exponent_size(bits);
if (window > 1) {
if (!BN_mod_mul_reciprocal(aa, val[0], val[0], &recp, ctx))
goto err; /* 2 */
j = 1 << (window - 1);
for (i = 1; i < j; i++) {
if (((val[i] = BN_CTX_get(ctx)) == NULL) ||
!BN_mod_mul_reciprocal(val[i], val[i - 1], aa, &recp, ctx))
goto err;
}
}
start = 1; /* This is used to avoid multiplication etc
* when there is only the value '1' in the
* buffer. */
wvalue = 0; /* The 'value' of the window */
wstart = bits - 1; /* The top bit of the window */
wend = 0; /* The bottom bit of the window */
if (!BN_one(r))
goto err;
for (;;) {
if (BN_is_bit_set(p, wstart) == 0) {
if (!start)
if (!BN_mod_mul_reciprocal(r, r, r, &recp, ctx))
goto err;
if (wstart == 0)
break;
wstart--;
continue;
}
/*
* We now have wstart on a 'set' bit, we now need to work out how bit
* a window to do. To do this we need to scan forward until the last
* set bit before the end of the window
*/
j = wstart;
wvalue = 1;
wend = 0;
for (i = 1; i < window; i++) {
if (wstart - i < 0)
break;
if (BN_is_bit_set(p, wstart - i)) {
wvalue <<= (i - wend);
wvalue |= 1;
wend = i;
}
}
/* wend is the size of the current window */
j = wend + 1;
/* add the 'bytes above' */
if (!start)
for (i = 0; i < j; i++) {
if (!BN_mod_mul_reciprocal(r, r, r, &recp, ctx))
goto err;
}
/* wvalue will be an odd number < 2^window */
if (!BN_mod_mul_reciprocal(r, r, val[wvalue >> 1], &recp, ctx))
goto err;
/* move the 'window' down further */
wstart -= wend + 1;
wvalue = 0;
start = 0;
if (wstart < 0)
break;
}
ret = 1;
err:
BN_CTX_end(ctx);
BN_RECP_CTX_free(&recp);
bn_check_top(r);
return (ret);
}
int BN_mod_exp_mont(BIGNUM *rr, const BIGNUM *a, const BIGNUM *p,
const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *in_mont)
{
int i, j, bits, ret = 0, wstart, wend, window, wvalue;
int start = 1;
BIGNUM *d, *r;
const BIGNUM *aa;
/* Table of variables obtained from 'ctx' */
BIGNUM *val[TABLE_SIZE];
BN_MONT_CTX *mont = NULL;
if (BN_get_flags(p, BN_FLG_CONSTTIME) != 0
|| BN_get_flags(a, BN_FLG_CONSTTIME) != 0
|| BN_get_flags(m, BN_FLG_CONSTTIME) != 0) {
return BN_mod_exp_mont_consttime(rr, a, p, m, ctx, in_mont);
}
bn_check_top(a);
bn_check_top(p);
bn_check_top(m);
if (!BN_is_odd(m)) {
BNerr(BN_F_BN_MOD_EXP_MONT, BN_R_CALLED_WITH_EVEN_MODULUS);
return (0);
}
bits = BN_num_bits(p);
if (bits == 0) {
/* x**0 mod 1 is still zero. */
if (BN_is_one(m)) {
ret = 1;
BN_zero(rr);
} else {
ret = BN_one(rr);
}
return ret;
}
BN_CTX_start(ctx);
d = BN_CTX_get(ctx);
r = BN_CTX_get(ctx);
val[0] = BN_CTX_get(ctx);
if (!d || !r || !val[0])
goto err;
/*
* If this is not done, things will break in the montgomery part
*/
if (in_mont != NULL)
mont = in_mont;
else {
if ((mont = BN_MONT_CTX_new()) == NULL)
goto err;
if (!BN_MONT_CTX_set(mont, m, ctx))
goto err;
}
if (a->neg || BN_ucmp(a, m) >= 0) {
if (!BN_nnmod(val[0], a, m, ctx))
goto err;
aa = val[0];
} else
aa = a;
if (BN_is_zero(aa)) {
BN_zero(rr);
ret = 1;
goto err;
}
if (!BN_to_montgomery(val[0], aa, mont, ctx))
goto err; /* 1 */
window = BN_window_bits_for_exponent_size(bits);
if (window > 1) {
if (!BN_mod_mul_montgomery(d, val[0], val[0], mont, ctx))
goto err; /* 2 */
j = 1 << (window - 1);
for (i = 1; i < j; i++) {
if (((val[i] = BN_CTX_get(ctx)) == NULL) ||
!BN_mod_mul_montgomery(val[i], val[i - 1], d, mont, ctx))
goto err;
}
}
start = 1; /* This is used to avoid multiplication etc
* when there is only the value '1' in the
* buffer. */
wvalue = 0; /* The 'value' of the window */
wstart = bits - 1; /* The top bit of the window */
wend = 0; /* The bottom bit of the window */
#if 1 /* by Shay Gueron's suggestion */
j = m->top; /* borrow j */
if (m->d[j - 1] & (((BN_ULONG)1) << (BN_BITS2 - 1))) {
if (bn_wexpand(r, j) == NULL)
goto err;
/* 2^(top*BN_BITS2) - m */
r->d[0] = (0 - m->d[0]) & BN_MASK2;
for (i = 1; i < j; i++)
r->d[i] = (~m->d[i]) & BN_MASK2;
r->top = j;
/*
* Upper words will be zero if the corresponding words of 'm' were
* 0xfff[...], so decrement r->top accordingly.
*/
bn_correct_top(r);
} else
#endif
if (!BN_to_montgomery(r, BN_value_one(), mont, ctx))
goto err;
for (;;) {
if (BN_is_bit_set(p, wstart) == 0) {
if (!start) {
if (!BN_mod_mul_montgomery(r, r, r, mont, ctx))
goto err;
}
if (wstart == 0)
break;
wstart--;
continue;
}
/*
* We now have wstart on a 'set' bit, we now need to work out how bit
* a window to do. To do this we need to scan forward until the last
* set bit before the end of the window
*/
j = wstart;
wvalue = 1;
wend = 0;
for (i = 1; i < window; i++) {
if (wstart - i < 0)
break;
if (BN_is_bit_set(p, wstart - i)) {
wvalue <<= (i - wend);
wvalue |= 1;
wend = i;
}
}
/* wend is the size of the current window */
j = wend + 1;
/* add the 'bytes above' */
if (!start)
for (i = 0; i < j; i++) {
if (!BN_mod_mul_montgomery(r, r, r, mont, ctx))
goto err;
}
/* wvalue will be an odd number < 2^window */
if (!BN_mod_mul_montgomery(r, r, val[wvalue >> 1], mont, ctx))
goto err;
/* move the 'window' down further */
wstart -= wend + 1;
wvalue = 0;
start = 0;
if (wstart < 0)
break;
}
#if defined(SPARC_T4_MONT)
if (OPENSSL_sparcv9cap_P[0] & (SPARCV9_VIS3 | SPARCV9_PREFER_FPU)) {
j = mont->N.top; /* borrow j */
val[0]->d[0] = 1; /* borrow val[0] */
for (i = 1; i < j; i++)
val[0]->d[i] = 0;
val[0]->top = j;
if (!BN_mod_mul_montgomery(rr, r, val[0], mont, ctx))
goto err;
} else
#endif
if (!BN_from_montgomery(rr, r, mont, ctx))
goto err;
ret = 1;
err:
if ((in_mont == NULL) && (mont != NULL))
BN_MONT_CTX_free(mont);
BN_CTX_end(ctx);
bn_check_top(rr);
return (ret);
}
#if defined(SPARC_T4_MONT)
static BN_ULONG bn_get_bits(const BIGNUM *a, int bitpos)
{
BN_ULONG ret = 0;
int wordpos;
wordpos = bitpos / BN_BITS2;
bitpos %= BN_BITS2;
if (wordpos >= 0 && wordpos < a->top) {
ret = a->d[wordpos] & BN_MASK2;
if (bitpos) {
ret >>= bitpos;
if (++wordpos < a->top)
ret |= a->d[wordpos] << (BN_BITS2 - bitpos);
}
}
return ret & BN_MASK2;
}
#endif
/*
* BN_mod_exp_mont_consttime() stores the precomputed powers in a specific
* layout so that accessing any of these table values shows the same access
* pattern as far as cache lines are concerned. The following functions are
* used to transfer a BIGNUM from/to that table.
*/
static int MOD_EXP_CTIME_COPY_TO_PREBUF(const BIGNUM *b, int top,
unsigned char *buf, int idx,
int window)
{
int i, j;
int width = 1 << window;
BN_ULONG *table = (BN_ULONG *)buf;
if (top > b->top)
top = b->top; /* this works because 'buf' is explicitly
* zeroed */
for (i = 0, j = idx; i < top; i++, j += width) {
table[j] = b->d[i];
}
return 1;
}
static int MOD_EXP_CTIME_COPY_FROM_PREBUF(BIGNUM *b, int top,
unsigned char *buf, int idx,
int window)
{
int i, j;
int width = 1 << window;
volatile BN_ULONG *table = (volatile BN_ULONG *)buf;
if (bn_wexpand(b, top) == NULL)
return 0;
if (window <= 3) {
for (i = 0; i < top; i++, table += width) {
BN_ULONG acc = 0;
for (j = 0; j < width; j++) {
acc |= table[j] &
((BN_ULONG)0 - (constant_time_eq_int(j,idx)&1));
}
b->d[i] = acc;
}
} else {
int xstride = 1 << (window - 2);
BN_ULONG y0, y1, y2, y3;
i = idx >> (window - 2); /* equivalent of idx / xstride */
idx &= xstride - 1; /* equivalent of idx % xstride */
y0 = (BN_ULONG)0 - (constant_time_eq_int(i,0)&1);
y1 = (BN_ULONG)0 - (constant_time_eq_int(i,1)&1);
y2 = (BN_ULONG)0 - (constant_time_eq_int(i,2)&1);
y3 = (BN_ULONG)0 - (constant_time_eq_int(i,3)&1);
for (i = 0; i < top; i++, table += width) {
BN_ULONG acc = 0;
for (j = 0; j < xstride; j++) {
acc |= ( (table[j + 0 * xstride] & y0) |
(table[j + 1 * xstride] & y1) |
(table[j + 2 * xstride] & y2) |
(table[j + 3 * xstride] & y3) )
& ((BN_ULONG)0 - (constant_time_eq_int(j,idx)&1));
}
b->d[i] = acc;
}
}
b->top = top;
bn_correct_top(b);
return 1;
}
/*
* Given a pointer value, compute the next address that is a cache line
* multiple.
*/
#define MOD_EXP_CTIME_ALIGN(x_) \
((unsigned char*)(x_) + (MOD_EXP_CTIME_MIN_CACHE_LINE_WIDTH - (((size_t)(x_)) & (MOD_EXP_CTIME_MIN_CACHE_LINE_MASK))))
/*
* This variant of BN_mod_exp_mont() uses fixed windows and the special
* precomputation memory layout to limit data-dependency to a minimum to
* protect secret exponents (cf. the hyper-threading timing attacks pointed
* out by Colin Percival,
* http://www.daemonology.net/hyperthreading-considered-harmful/)
*/
int BN_mod_exp_mont_consttime(BIGNUM *rr, const BIGNUM *a, const BIGNUM *p,
const BIGNUM *m, BN_CTX *ctx,
BN_MONT_CTX *in_mont)
{
int i, bits, ret = 0, window, wvalue;
int top;
BN_MONT_CTX *mont = NULL;
int numPowers;
unsigned char *powerbufFree = NULL;
int powerbufLen = 0;
unsigned char *powerbuf = NULL;
BIGNUM tmp, am;
#if defined(SPARC_T4_MONT)
unsigned int t4 = 0;
#endif
bn_check_top(a);
bn_check_top(p);
bn_check_top(m);
if (!BN_is_odd(m)) {
BNerr(BN_F_BN_MOD_EXP_MONT_CONSTTIME, BN_R_CALLED_WITH_EVEN_MODULUS);
return (0);
}
top = m->top;
- bits = BN_num_bits(p);
+ /*
+ * Use all bits stored in |p|, rather than |BN_num_bits|, so we do not leak
+ * whether the top bits are zero.
+ */
+ bits = p->top * BN_BITS2;
if (bits == 0) {
/* x**0 mod 1 is still zero. */
if (BN_is_one(m)) {
ret = 1;
BN_zero(rr);
} else {
ret = BN_one(rr);
}
return ret;
}
BN_CTX_start(ctx);
/*
* Allocate a montgomery context if it was not supplied by the caller. If
* this is not done, things will break in the montgomery part.
*/
if (in_mont != NULL)
mont = in_mont;
else {
if ((mont = BN_MONT_CTX_new()) == NULL)
goto err;
if (!BN_MONT_CTX_set(mont, m, ctx))
goto err;
}
#ifdef RSAZ_ENABLED
/*
* If the size of the operands allow it, perform the optimized
* RSAZ exponentiation. For further information see
* crypto/bn/rsaz_exp.c and accompanying assembly modules.
*/
if ((16 == a->top) && (16 == p->top) && (BN_num_bits(m) == 1024)
&& rsaz_avx2_eligible()) {
if (NULL == bn_wexpand(rr, 16))
goto err;
RSAZ_1024_mod_exp_avx2(rr->d, a->d, p->d, m->d, mont->RR.d,
mont->n0[0]);
rr->top = 16;
rr->neg = 0;
bn_correct_top(rr);
ret = 1;
goto err;
} else if ((8 == a->top) && (8 == p->top) && (BN_num_bits(m) == 512)) {
if (NULL == bn_wexpand(rr, 8))
goto err;
RSAZ_512_mod_exp(rr->d, a->d, p->d, m->d, mont->n0[0], mont->RR.d);
rr->top = 8;
rr->neg = 0;
bn_correct_top(rr);
ret = 1;
goto err;
}
#endif
/* Get the window size to use with size of p. */
window = BN_window_bits_for_ctime_exponent_size(bits);
#if defined(SPARC_T4_MONT)
if (window >= 5 && (top & 15) == 0 && top <= 64 &&
(OPENSSL_sparcv9cap_P[1] & (CFR_MONTMUL | CFR_MONTSQR)) ==
(CFR_MONTMUL | CFR_MONTSQR) && (t4 = OPENSSL_sparcv9cap_P[0]))
window = 5;
else
#endif
#if defined(OPENSSL_BN_ASM_MONT5)
if (window >= 5) {
window = 5; /* ~5% improvement for RSA2048 sign, and even
* for RSA4096 */
/* reserve space for mont->N.d[] copy */
powerbufLen += top * sizeof(mont->N.d[0]);
}
#endif
(void)0;
/*
* Allocate a buffer large enough to hold all of the pre-computed powers
* of am, am itself and tmp.
*/
numPowers = 1 << window;
powerbufLen += sizeof(m->d[0]) * (top * numPowers +
((2 * top) >
numPowers ? (2 * top) : numPowers));
#ifdef alloca
if (powerbufLen < 3072)
powerbufFree =
alloca(powerbufLen + MOD_EXP_CTIME_MIN_CACHE_LINE_WIDTH);
else
#endif
if ((powerbufFree =
(unsigned char *)OPENSSL_malloc(powerbufLen +
MOD_EXP_CTIME_MIN_CACHE_LINE_WIDTH))
== NULL)
goto err;
powerbuf = MOD_EXP_CTIME_ALIGN(powerbufFree);
memset(powerbuf, 0, powerbufLen);
#ifdef alloca
if (powerbufLen < 3072)
powerbufFree = NULL;
#endif
/* lay down tmp and am right after powers table */
tmp.d = (BN_ULONG *)(powerbuf + sizeof(m->d[0]) * top * numPowers);
am.d = tmp.d + top;
tmp.top = am.top = 0;
tmp.dmax = am.dmax = top;
tmp.neg = am.neg = 0;
tmp.flags = am.flags = BN_FLG_STATIC_DATA;
/* prepare a^0 in Montgomery domain */
#if 1 /* by Shay Gueron's suggestion */
if (m->d[top - 1] & (((BN_ULONG)1) << (BN_BITS2 - 1))) {
/* 2^(top*BN_BITS2) - m */
tmp.d[0] = (0 - m->d[0]) & BN_MASK2;
for (i = 1; i < top; i++)
tmp.d[i] = (~m->d[i]) & BN_MASK2;
tmp.top = top;
} else
#endif
if (!BN_to_montgomery(&tmp, BN_value_one(), mont, ctx))
goto err;
/* prepare a^1 in Montgomery domain */
if (a->neg || BN_ucmp(a, m) >= 0) {
if (!BN_mod(&am, a, m, ctx))
goto err;
if (!BN_to_montgomery(&am, &am, mont, ctx))
goto err;
} else if (!BN_to_montgomery(&am, a, mont, ctx))
goto err;
#if defined(SPARC_T4_MONT)
if (t4) {
typedef int (*bn_pwr5_mont_f) (BN_ULONG *tp, const BN_ULONG *np,
const BN_ULONG *n0, const void *table,
int power, int bits);
int bn_pwr5_mont_t4_8(BN_ULONG *tp, const BN_ULONG *np,
const BN_ULONG *n0, const void *table,
int power, int bits);
int bn_pwr5_mont_t4_16(BN_ULONG *tp, const BN_ULONG *np,
const BN_ULONG *n0, const void *table,
int power, int bits);
int bn_pwr5_mont_t4_24(BN_ULONG *tp, const BN_ULONG *np,
const BN_ULONG *n0, const void *table,
int power, int bits);
int bn_pwr5_mont_t4_32(BN_ULONG *tp, const BN_ULONG *np,
const BN_ULONG *n0, const void *table,
int power, int bits);
static const bn_pwr5_mont_f pwr5_funcs[4] = {
bn_pwr5_mont_t4_8, bn_pwr5_mont_t4_16,
bn_pwr5_mont_t4_24, bn_pwr5_mont_t4_32
};
bn_pwr5_mont_f pwr5_worker = pwr5_funcs[top / 16 - 1];
typedef int (*bn_mul_mont_f) (BN_ULONG *rp, const BN_ULONG *ap,
const void *bp, const BN_ULONG *np,
const BN_ULONG *n0);
int bn_mul_mont_t4_8(BN_ULONG *rp, const BN_ULONG *ap, const void *bp,
const BN_ULONG *np, const BN_ULONG *n0);
int bn_mul_mont_t4_16(BN_ULONG *rp, const BN_ULONG *ap,
const void *bp, const BN_ULONG *np,
const BN_ULONG *n0);
int bn_mul_mont_t4_24(BN_ULONG *rp, const BN_ULONG *ap,
const void *bp, const BN_ULONG *np,
const BN_ULONG *n0);
int bn_mul_mont_t4_32(BN_ULONG *rp, const BN_ULONG *ap,
const void *bp, const BN_ULONG *np,
const BN_ULONG *n0);
static const bn_mul_mont_f mul_funcs[4] = {
bn_mul_mont_t4_8, bn_mul_mont_t4_16,
bn_mul_mont_t4_24, bn_mul_mont_t4_32
};
bn_mul_mont_f mul_worker = mul_funcs[top / 16 - 1];
void bn_mul_mont_vis3(BN_ULONG *rp, const BN_ULONG *ap,
const void *bp, const BN_ULONG *np,
const BN_ULONG *n0, int num);
void bn_mul_mont_t4(BN_ULONG *rp, const BN_ULONG *ap,
const void *bp, const BN_ULONG *np,
const BN_ULONG *n0, int num);
void bn_mul_mont_gather5_t4(BN_ULONG *rp, const BN_ULONG *ap,
const void *table, const BN_ULONG *np,
const BN_ULONG *n0, int num, int power);
void bn_flip_n_scatter5_t4(const BN_ULONG *inp, size_t num,
void *table, size_t power);
void bn_gather5_t4(BN_ULONG *out, size_t num,
void *table, size_t power);
void bn_flip_t4(BN_ULONG *dst, BN_ULONG *src, size_t num);
BN_ULONG *np = mont->N.d, *n0 = mont->n0;
int stride = 5 * (6 - (top / 16 - 1)); /* multiple of 5, but less
* than 32 */
/*
* BN_to_montgomery can contaminate words above .top [in
* BN_DEBUG[_DEBUG] build]...
*/
for (i = am.top; i < top; i++)
am.d[i] = 0;
for (i = tmp.top; i < top; i++)
tmp.d[i] = 0;
bn_flip_n_scatter5_t4(tmp.d, top, powerbuf, 0);
bn_flip_n_scatter5_t4(am.d, top, powerbuf, 1);
if (!(*mul_worker) (tmp.d, am.d, am.d, np, n0) &&
!(*mul_worker) (tmp.d, am.d, am.d, np, n0))
bn_mul_mont_vis3(tmp.d, am.d, am.d, np, n0, top);
bn_flip_n_scatter5_t4(tmp.d, top, powerbuf, 2);
for (i = 3; i < 32; i++) {
/* Calculate a^i = a^(i-1) * a */
if (!(*mul_worker) (tmp.d, tmp.d, am.d, np, n0) &&
!(*mul_worker) (tmp.d, tmp.d, am.d, np, n0))
bn_mul_mont_vis3(tmp.d, tmp.d, am.d, np, n0, top);
bn_flip_n_scatter5_t4(tmp.d, top, powerbuf, i);
}
/* switch to 64-bit domain */
np = alloca(top * sizeof(BN_ULONG));
top /= 2;
bn_flip_t4(np, mont->N.d, top);
bits--;
for (wvalue = 0, i = bits % 5; i >= 0; i--, bits--)
wvalue = (wvalue << 1) + BN_is_bit_set(p, bits);
bn_gather5_t4(tmp.d, top, powerbuf, wvalue);
/*
* Scan the exponent one window at a time starting from the most
* significant bits.
*/
while (bits >= 0) {
if (bits < stride)
stride = bits + 1;
bits -= stride;
wvalue = bn_get_bits(p, bits + 1);
if ((*pwr5_worker) (tmp.d, np, n0, powerbuf, wvalue, stride))
continue;
/* retry once and fall back */
if ((*pwr5_worker) (tmp.d, np, n0, powerbuf, wvalue, stride))
continue;
bits += stride - 5;
wvalue >>= stride - 5;
wvalue &= 31;
bn_mul_mont_t4(tmp.d, tmp.d, tmp.d, np, n0, top);
bn_mul_mont_t4(tmp.d, tmp.d, tmp.d, np, n0, top);
bn_mul_mont_t4(tmp.d, tmp.d, tmp.d, np, n0, top);
bn_mul_mont_t4(tmp.d, tmp.d, tmp.d, np, n0, top);
bn_mul_mont_t4(tmp.d, tmp.d, tmp.d, np, n0, top);
bn_mul_mont_gather5_t4(tmp.d, tmp.d, powerbuf, np, n0, top,
wvalue);
}
bn_flip_t4(tmp.d, tmp.d, top);
top *= 2;
/* back to 32-bit domain */
tmp.top = top;
bn_correct_top(&tmp);
OPENSSL_cleanse(np, top * sizeof(BN_ULONG));
} else
#endif
#if defined(OPENSSL_BN_ASM_MONT5)
if (window == 5 && top > 1) {
/*
* This optimization uses ideas from http://eprint.iacr.org/2011/239,
* specifically optimization of cache-timing attack countermeasures
* and pre-computation optimization.
*/
/*
* Dedicated window==4 case improves 512-bit RSA sign by ~15%, but as
* 512-bit RSA is hardly relevant, we omit it to spare size...
*/
void bn_mul_mont_gather5(BN_ULONG *rp, const BN_ULONG *ap,
const void *table, const BN_ULONG *np,
const BN_ULONG *n0, int num, int power);
void bn_scatter5(const BN_ULONG *inp, size_t num,
void *table, size_t power);
void bn_gather5(BN_ULONG *out, size_t num, void *table, size_t power);
void bn_power5(BN_ULONG *rp, const BN_ULONG *ap,
const void *table, const BN_ULONG *np,
const BN_ULONG *n0, int num, int power);
int bn_get_bits5(const BN_ULONG *ap, int off);
int bn_from_montgomery(BN_ULONG *rp, const BN_ULONG *ap,
const BN_ULONG *not_used, const BN_ULONG *np,
const BN_ULONG *n0, int num);
BN_ULONG *n0 = mont->n0, *np;
/*
* BN_to_montgomery can contaminate words above .top [in
* BN_DEBUG[_DEBUG] build]...
*/
for (i = am.top; i < top; i++)
am.d[i] = 0;
for (i = tmp.top; i < top; i++)
tmp.d[i] = 0;
/*
* copy mont->N.d[] to improve cache locality
*/
for (np = am.d + top, i = 0; i < top; i++)
np[i] = mont->N.d[i];
bn_scatter5(tmp.d, top, powerbuf, 0);
bn_scatter5(am.d, am.top, powerbuf, 1);
bn_mul_mont(tmp.d, am.d, am.d, np, n0, top);
bn_scatter5(tmp.d, top, powerbuf, 2);
# if 0
for (i = 3; i < 32; i++) {
/* Calculate a^i = a^(i-1) * a */
bn_mul_mont_gather5(tmp.d, am.d, powerbuf, np, n0, top, i - 1);
bn_scatter5(tmp.d, top, powerbuf, i);
}
# else
/* same as above, but uses squaring for 1/2 of operations */
for (i = 4; i < 32; i *= 2) {
bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top);
bn_scatter5(tmp.d, top, powerbuf, i);
}
for (i = 3; i < 8; i += 2) {
int j;
bn_mul_mont_gather5(tmp.d, am.d, powerbuf, np, n0, top, i - 1);
bn_scatter5(tmp.d, top, powerbuf, i);
for (j = 2 * i; j < 32; j *= 2) {
bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top);
bn_scatter5(tmp.d, top, powerbuf, j);
}
}
for (; i < 16; i += 2) {
bn_mul_mont_gather5(tmp.d, am.d, powerbuf, np, n0, top, i - 1);
bn_scatter5(tmp.d, top, powerbuf, i);
bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top);
bn_scatter5(tmp.d, top, powerbuf, 2 * i);
}
for (; i < 32; i += 2) {
bn_mul_mont_gather5(tmp.d, am.d, powerbuf, np, n0, top, i - 1);
bn_scatter5(tmp.d, top, powerbuf, i);
}
# endif
bits--;
for (wvalue = 0, i = bits % 5; i >= 0; i--, bits--)
wvalue = (wvalue << 1) + BN_is_bit_set(p, bits);
bn_gather5(tmp.d, top, powerbuf, wvalue);
/*
* Scan the exponent one window at a time starting from the most
* significant bits.
*/
if (top & 7)
while (bits >= 0) {
for (wvalue = 0, i = 0; i < 5; i++, bits--)
wvalue = (wvalue << 1) + BN_is_bit_set(p, bits);
bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top);
bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top);
bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top);
bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top);
bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top);
bn_mul_mont_gather5(tmp.d, tmp.d, powerbuf, np, n0, top,
wvalue);
} else {
while (bits >= 0) {
wvalue = bn_get_bits5(p->d, bits - 4);
bits -= 5;
bn_power5(tmp.d, tmp.d, powerbuf, np, n0, top, wvalue);
}
}
ret = bn_from_montgomery(tmp.d, tmp.d, NULL, np, n0, top);
tmp.top = top;
bn_correct_top(&tmp);
if (ret) {
if (!BN_copy(rr, &tmp))
ret = 0;
goto err; /* non-zero ret means it's not error */
}
} else
#endif
{
if (!MOD_EXP_CTIME_COPY_TO_PREBUF(&tmp, top, powerbuf, 0, window))
goto err;
if (!MOD_EXP_CTIME_COPY_TO_PREBUF(&am, top, powerbuf, 1, window))
goto err;
/*
* If the window size is greater than 1, then calculate
* val[i=2..2^winsize-1]. Powers are computed as a*a^(i-1) (even
* powers could instead be computed as (a^(i/2))^2 to use the slight
* performance advantage of sqr over mul).
*/
if (window > 1) {
if (!BN_mod_mul_montgomery(&tmp, &am, &am, mont, ctx))
goto err;
if (!MOD_EXP_CTIME_COPY_TO_PREBUF(&tmp, top, powerbuf, 2,
window))
goto err;
for (i = 3; i < numPowers; i++) {
/* Calculate a^i = a^(i-1) * a */
if (!BN_mod_mul_montgomery(&tmp, &am, &tmp, mont, ctx))
goto err;
if (!MOD_EXP_CTIME_COPY_TO_PREBUF(&tmp, top, powerbuf, i,
window))
goto err;
}
}
bits--;
for (wvalue = 0, i = bits % window; i >= 0; i--, bits--)
wvalue = (wvalue << 1) + BN_is_bit_set(p, bits);
if (!MOD_EXP_CTIME_COPY_FROM_PREBUF(&tmp, top, powerbuf, wvalue,
window))
goto err;
/*
* Scan the exponent one window at a time starting from the most
* significant bits.
*/
while (bits >= 0) {
wvalue = 0; /* The 'value' of the window */
/* Scan the window, squaring the result as we go */
for (i = 0; i < window; i++, bits--) {
if (!BN_mod_mul_montgomery(&tmp, &tmp, &tmp, mont, ctx))
goto err;
wvalue = (wvalue << 1) + BN_is_bit_set(p, bits);
}
/*
* Fetch the appropriate pre-computed value from the pre-buf
*/
if (!MOD_EXP_CTIME_COPY_FROM_PREBUF(&am, top, powerbuf, wvalue,
window))
goto err;
/* Multiply the result into the intermediate result */
if (!BN_mod_mul_montgomery(&tmp, &tmp, &am, mont, ctx))
goto err;
}
}
/* Convert the final result from montgomery to standard format */
#if defined(SPARC_T4_MONT)
if (OPENSSL_sparcv9cap_P[0] & (SPARCV9_VIS3 | SPARCV9_PREFER_FPU)) {
am.d[0] = 1; /* borrow am */
for (i = 1; i < top; i++)
am.d[i] = 0;
if (!BN_mod_mul_montgomery(rr, &tmp, &am, mont, ctx))
goto err;
} else
#endif
if (!BN_from_montgomery(rr, &tmp, mont, ctx))
goto err;
ret = 1;
err:
if ((in_mont == NULL) && (mont != NULL))
BN_MONT_CTX_free(mont);
if (powerbuf != NULL) {
OPENSSL_cleanse(powerbuf, powerbufLen);
if (powerbufFree)
OPENSSL_free(powerbufFree);
}
BN_CTX_end(ctx);
return (ret);
}
int BN_mod_exp_mont_word(BIGNUM *rr, BN_ULONG a, const BIGNUM *p,
const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *in_mont)
{
BN_MONT_CTX *mont = NULL;
int b, bits, ret = 0;
int r_is_one;
BN_ULONG w, next_w;
BIGNUM *d, *r, *t;
BIGNUM *swap_tmp;
#define BN_MOD_MUL_WORD(r, w, m) \
(BN_mul_word(r, (w)) && \
(/* BN_ucmp(r, (m)) < 0 ? 1 :*/ \
(BN_mod(t, r, m, ctx) && (swap_tmp = r, r = t, t = swap_tmp, 1))))
/*
* BN_MOD_MUL_WORD is only used with 'w' large, so the BN_ucmp test is
* probably more overhead than always using BN_mod (which uses BN_copy if
* a similar test returns true).
*/
/*
* We can use BN_mod and do not need BN_nnmod because our accumulator is
* never negative (the result of BN_mod does not depend on the sign of
* the modulus).
*/
#define BN_TO_MONTGOMERY_WORD(r, w, mont) \
(BN_set_word(r, (w)) && BN_to_montgomery(r, r, (mont), ctx))
if (BN_get_flags(p, BN_FLG_CONSTTIME) != 0
|| BN_get_flags(m, BN_FLG_CONSTTIME) != 0) {
/* BN_FLG_CONSTTIME only supported by BN_mod_exp_mont() */
BNerr(BN_F_BN_MOD_EXP_MONT_WORD, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
return 0;
}
bn_check_top(p);
bn_check_top(m);
if (!BN_is_odd(m)) {
BNerr(BN_F_BN_MOD_EXP_MONT_WORD, BN_R_CALLED_WITH_EVEN_MODULUS);
return (0);
}
if (m->top == 1)
a %= m->d[0]; /* make sure that 'a' is reduced */
bits = BN_num_bits(p);
if (bits == 0) {
/* x**0 mod 1 is still zero. */
if (BN_is_one(m)) {
ret = 1;
BN_zero(rr);
} else {
ret = BN_one(rr);
}
return ret;
}
if (a == 0) {
BN_zero(rr);
ret = 1;
return ret;
}
BN_CTX_start(ctx);
d = BN_CTX_get(ctx);
r = BN_CTX_get(ctx);
t = BN_CTX_get(ctx);
if (d == NULL || r == NULL || t == NULL)
goto err;
if (in_mont != NULL)
mont = in_mont;
else {
if ((mont = BN_MONT_CTX_new()) == NULL)
goto err;
if (!BN_MONT_CTX_set(mont, m, ctx))
goto err;
}
r_is_one = 1; /* except for Montgomery factor */
/* bits-1 >= 0 */
/* The result is accumulated in the product r*w. */
w = a; /* bit 'bits-1' of 'p' is always set */
for (b = bits - 2; b >= 0; b--) {
/* First, square r*w. */
next_w = w * w;
if ((next_w / w) != w) { /* overflow */
if (r_is_one) {
if (!BN_TO_MONTGOMERY_WORD(r, w, mont))
goto err;
r_is_one = 0;
} else {
if (!BN_MOD_MUL_WORD(r, w, m))
goto err;
}
next_w = 1;
}
w = next_w;
if (!r_is_one) {
if (!BN_mod_mul_montgomery(r, r, r, mont, ctx))
goto err;
}
/* Second, multiply r*w by 'a' if exponent bit is set. */
if (BN_is_bit_set(p, b)) {
next_w = w * a;
if ((next_w / a) != w) { /* overflow */
if (r_is_one) {
if (!BN_TO_MONTGOMERY_WORD(r, w, mont))
goto err;
r_is_one = 0;
} else {
if (!BN_MOD_MUL_WORD(r, w, m))
goto err;
}
next_w = a;
}
w = next_w;
}
}
/* Finally, set r:=r*w. */
if (w != 1) {
if (r_is_one) {
if (!BN_TO_MONTGOMERY_WORD(r, w, mont))
goto err;
r_is_one = 0;
} else {
if (!BN_MOD_MUL_WORD(r, w, m))
goto err;
}
}
if (r_is_one) { /* can happen only if a == 1 */
if (!BN_one(rr))
goto err;
} else {
if (!BN_from_montgomery(rr, r, mont, ctx))
goto err;
}
ret = 1;
err:
if ((in_mont == NULL) && (mont != NULL))
BN_MONT_CTX_free(mont);
BN_CTX_end(ctx);
bn_check_top(rr);
return (ret);
}
/* The old fallback, simple version :-) */
int BN_mod_exp_simple(BIGNUM *r, const BIGNUM *a, const BIGNUM *p,
const BIGNUM *m, BN_CTX *ctx)
{
int i, j, bits, ret = 0, wstart, wend, window, wvalue;
int start = 1;
BIGNUM *d;
/* Table of variables obtained from 'ctx' */
BIGNUM *val[TABLE_SIZE];
if (BN_get_flags(p, BN_FLG_CONSTTIME) != 0
|| BN_get_flags(a, BN_FLG_CONSTTIME) != 0
|| BN_get_flags(m, BN_FLG_CONSTTIME) != 0) {
/* BN_FLG_CONSTTIME only supported by BN_mod_exp_mont() */
BNerr(BN_F_BN_MOD_EXP_SIMPLE, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
return 0;
}
bits = BN_num_bits(p);
if (bits == 0) {
/* x**0 mod 1 is still zero. */
if (BN_is_one(m)) {
ret = 1;
BN_zero(r);
} else {
ret = BN_one(r);
}
return ret;
}
BN_CTX_start(ctx);
d = BN_CTX_get(ctx);
val[0] = BN_CTX_get(ctx);
if (!d || !val[0])
goto err;
if (!BN_nnmod(val[0], a, m, ctx))
goto err; /* 1 */
if (BN_is_zero(val[0])) {
BN_zero(r);
ret = 1;
goto err;
}
window = BN_window_bits_for_exponent_size(bits);
if (window > 1) {
if (!BN_mod_mul(d, val[0], val[0], m, ctx))
goto err; /* 2 */
j = 1 << (window - 1);
for (i = 1; i < j; i++) {
if (((val[i] = BN_CTX_get(ctx)) == NULL) ||
!BN_mod_mul(val[i], val[i - 1], d, m, ctx))
goto err;
}
}
start = 1; /* This is used to avoid multiplication etc
* when there is only the value '1' in the
* buffer. */
wvalue = 0; /* The 'value' of the window */
wstart = bits - 1; /* The top bit of the window */
wend = 0; /* The bottom bit of the window */
if (!BN_one(r))
goto err;
for (;;) {
if (BN_is_bit_set(p, wstart) == 0) {
if (!start)
if (!BN_mod_mul(r, r, r, m, ctx))
goto err;
if (wstart == 0)
break;
wstart--;
continue;
}
/*
* We now have wstart on a 'set' bit, we now need to work out how bit
* a window to do. To do this we need to scan forward until the last
* set bit before the end of the window
*/
j = wstart;
wvalue = 1;
wend = 0;
for (i = 1; i < window; i++) {
if (wstart - i < 0)
break;
if (BN_is_bit_set(p, wstart - i)) {
wvalue <<= (i - wend);
wvalue |= 1;
wend = i;
}
}
/* wend is the size of the current window */
j = wend + 1;
/* add the 'bytes above' */
if (!start)
for (i = 0; i < j; i++) {
if (!BN_mod_mul(r, r, r, m, ctx))
goto err;
}
/* wvalue will be an odd number < 2^window */
if (!BN_mod_mul(r, r, val[wvalue >> 1], m, ctx))
goto err;
/* move the 'window' down further */
wstart -= wend + 1;
wvalue = 0;
start = 0;
if (wstart < 0)
break;
}
ret = 1;
err:
BN_CTX_end(ctx);
bn_check_top(r);
return (ret);
}
diff --git a/crypto/bn/bn_lib.c b/crypto/bn/bn_lib.c
index f9c65f9f948a..27b9bdbc3c28 100644
--- a/crypto/bn/bn_lib.c
+++ b/crypto/bn/bn_lib.c
@@ -1,919 +1,889 @@
/* crypto/bn/bn_lib.c */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
#ifndef BN_DEBUG
# undef NDEBUG /* avoid conflicting definitions */
# define NDEBUG
#endif
#include <assert.h>
#include <limits.h>
#include <stdio.h>
#include "cryptlib.h"
#include "bn_lcl.h"
const char BN_version[] = "Big Number" OPENSSL_VERSION_PTEXT;
/* This stuff appears to be completely unused, so is deprecated */
#ifndef OPENSSL_NO_DEPRECATED
/*-
* For a 32 bit machine
* 2 - 4 == 128
* 3 - 8 == 256
* 4 - 16 == 512
* 5 - 32 == 1024
* 6 - 64 == 2048
* 7 - 128 == 4096
* 8 - 256 == 8192
*/
static int bn_limit_bits = 0;
static int bn_limit_num = 8; /* (1<<bn_limit_bits) */
static int bn_limit_bits_low = 0;
static int bn_limit_num_low = 8; /* (1<<bn_limit_bits_low) */
static int bn_limit_bits_high = 0;
static int bn_limit_num_high = 8; /* (1<<bn_limit_bits_high) */
static int bn_limit_bits_mont = 0;
static int bn_limit_num_mont = 8; /* (1<<bn_limit_bits_mont) */
void BN_set_params(int mult, int high, int low, int mont)
{
if (mult >= 0) {
if (mult > (int)(sizeof(int) * 8) - 1)
mult = sizeof(int) * 8 - 1;
bn_limit_bits = mult;
bn_limit_num = 1 << mult;
}
if (high >= 0) {
if (high > (int)(sizeof(int) * 8) - 1)
high = sizeof(int) * 8 - 1;
bn_limit_bits_high = high;
bn_limit_num_high = 1 << high;
}
if (low >= 0) {
if (low > (int)(sizeof(int) * 8) - 1)
low = sizeof(int) * 8 - 1;
bn_limit_bits_low = low;
bn_limit_num_low = 1 << low;
}
if (mont >= 0) {
if (mont > (int)(sizeof(int) * 8) - 1)
mont = sizeof(int) * 8 - 1;
bn_limit_bits_mont = mont;
bn_limit_num_mont = 1 << mont;
}
}
int BN_get_params(int which)
{
if (which == 0)
return (bn_limit_bits);
else if (which == 1)
return (bn_limit_bits_high);
else if (which == 2)
return (bn_limit_bits_low);
else if (which == 3)
return (bn_limit_bits_mont);
else
return (0);
}
#endif
const BIGNUM *BN_value_one(void)
{
static const BN_ULONG data_one = 1L;
static const BIGNUM const_one =
{ (BN_ULONG *)&data_one, 1, 1, 0, BN_FLG_STATIC_DATA };
return (&const_one);
}
int BN_num_bits_word(BN_ULONG l)
{
- static const unsigned char bits[256] = {
- 0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4,
- 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
- 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
- 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
- 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
- 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
- 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
- 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
- 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
- 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
- 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
- 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
- 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
- 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
- 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
- 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
- };
-
-#if defined(SIXTY_FOUR_BIT_LONG)
- if (l & 0xffffffff00000000L) {
- if (l & 0xffff000000000000L) {
- if (l & 0xff00000000000000L) {
- return (bits[(int)(l >> 56)] + 56);
- } else
- return (bits[(int)(l >> 48)] + 48);
- } else {
- if (l & 0x0000ff0000000000L) {
- return (bits[(int)(l >> 40)] + 40);
- } else
- return (bits[(int)(l >> 32)] + 32);
- }
- } else
-#else
-# ifdef SIXTY_FOUR_BIT
- if (l & 0xffffffff00000000LL) {
- if (l & 0xffff000000000000LL) {
- if (l & 0xff00000000000000LL) {
- return (bits[(int)(l >> 56)] + 56);
- } else
- return (bits[(int)(l >> 48)] + 48);
- } else {
- if (l & 0x0000ff0000000000LL) {
- return (bits[(int)(l >> 40)] + 40);
- } else
- return (bits[(int)(l >> 32)] + 32);
- }
- } else
-# endif
-#endif
- {
-#if defined(THIRTY_TWO_BIT) || defined(SIXTY_FOUR_BIT) || defined(SIXTY_FOUR_BIT_LONG)
- if (l & 0xffff0000L) {
- if (l & 0xff000000L)
- return (bits[(int)(l >> 24L)] + 24);
- else
- return (bits[(int)(l >> 16L)] + 16);
- } else
-#endif
- {
-#if defined(THIRTY_TWO_BIT) || defined(SIXTY_FOUR_BIT) || defined(SIXTY_FOUR_BIT_LONG)
- if (l & 0xff00L)
- return (bits[(int)(l >> 8)] + 8);
- else
+ BN_ULONG x, mask;
+ int bits = (l != 0);
+
+#if BN_BITS2 > 32
+ x = l >> 32;
+ mask = (0 - x) & BN_MASK2;
+ mask = (0 - (mask >> (BN_BITS2 - 1)));
+ bits += 32 & mask;
+ l ^= (x ^ l) & mask;
#endif
- return (bits[(int)(l)]);
- }
- }
+
+ x = l >> 16;
+ mask = (0 - x) & BN_MASK2;
+ mask = (0 - (mask >> (BN_BITS2 - 1)));
+ bits += 16 & mask;
+ l ^= (x ^ l) & mask;
+
+ x = l >> 8;
+ mask = (0 - x) & BN_MASK2;
+ mask = (0 - (mask >> (BN_BITS2 - 1)));
+ bits += 8 & mask;
+ l ^= (x ^ l) & mask;
+
+ x = l >> 4;
+ mask = (0 - x) & BN_MASK2;
+ mask = (0 - (mask >> (BN_BITS2 - 1)));
+ bits += 4 & mask;
+ l ^= (x ^ l) & mask;
+
+ x = l >> 2;
+ mask = (0 - x) & BN_MASK2;
+ mask = (0 - (mask >> (BN_BITS2 - 1)));
+ bits += 2 & mask;
+ l ^= (x ^ l) & mask;
+
+ x = l >> 1;
+ mask = (0 - x) & BN_MASK2;
+ mask = (0 - (mask >> (BN_BITS2 - 1)));
+ bits += 1 & mask;
+
+ return bits;
}
int BN_num_bits(const BIGNUM *a)
{
int i = a->top - 1;
bn_check_top(a);
if (BN_is_zero(a))
return 0;
return ((i * BN_BITS2) + BN_num_bits_word(a->d[i]));
}
void BN_clear_free(BIGNUM *a)
{
int i;
if (a == NULL)
return;
bn_check_top(a);
if (a->d != NULL) {
OPENSSL_cleanse(a->d, a->dmax * sizeof(a->d[0]));
if (!(BN_get_flags(a, BN_FLG_STATIC_DATA)))
OPENSSL_free(a->d);
}
i = BN_get_flags(a, BN_FLG_MALLOCED);
OPENSSL_cleanse(a, sizeof(BIGNUM));
if (i)
OPENSSL_free(a);
}
void BN_free(BIGNUM *a)
{
if (a == NULL)
return;
bn_check_top(a);
if ((a->d != NULL) && !(BN_get_flags(a, BN_FLG_STATIC_DATA)))
OPENSSL_free(a->d);
if (a->flags & BN_FLG_MALLOCED)
OPENSSL_free(a);
else {
#ifndef OPENSSL_NO_DEPRECATED
a->flags |= BN_FLG_FREE;
#endif
a->d = NULL;
}
}
void BN_init(BIGNUM *a)
{
memset(a, 0, sizeof(BIGNUM));
bn_check_top(a);
}
BIGNUM *BN_new(void)
{
BIGNUM *ret;
if ((ret = (BIGNUM *)OPENSSL_malloc(sizeof(BIGNUM))) == NULL) {
BNerr(BN_F_BN_NEW, ERR_R_MALLOC_FAILURE);
return (NULL);
}
ret->flags = BN_FLG_MALLOCED;
ret->top = 0;
ret->neg = 0;
ret->dmax = 0;
ret->d = NULL;
bn_check_top(ret);
return (ret);
}
/* This is used both by bn_expand2() and bn_dup_expand() */
/* The caller MUST check that words > b->dmax before calling this */
static BN_ULONG *bn_expand_internal(const BIGNUM *b, int words)
{
BN_ULONG *A, *a = NULL;
const BN_ULONG *B;
int i;
bn_check_top(b);
if (words > (INT_MAX / (4 * BN_BITS2))) {
BNerr(BN_F_BN_EXPAND_INTERNAL, BN_R_BIGNUM_TOO_LONG);
return NULL;
}
if (BN_get_flags(b, BN_FLG_STATIC_DATA)) {
BNerr(BN_F_BN_EXPAND_INTERNAL, BN_R_EXPAND_ON_STATIC_BIGNUM_DATA);
return (NULL);
}
a = A = (BN_ULONG *)OPENSSL_malloc(sizeof(BN_ULONG) * words);
if (A == NULL) {
BNerr(BN_F_BN_EXPAND_INTERNAL, ERR_R_MALLOC_FAILURE);
return (NULL);
}
#ifdef PURIFY
/*
* Valgrind complains in BN_consttime_swap because we process the whole
* array even if it's not initialised yet. This doesn't matter in that
* function - what's important is constant time operation (we're not
* actually going to use the data)
*/
memset(a, 0, sizeof(BN_ULONG) * words);
#endif
#if 1
B = b->d;
/* Check if the previous number needs to be copied */
if (B != NULL) {
for (i = b->top >> 2; i > 0; i--, A += 4, B += 4) {
/*
* The fact that the loop is unrolled
* 4-wise is a tribute to Intel. It's
* the one that doesn't have enough
* registers to accomodate more data.
* I'd unroll it 8-wise otherwise:-)
*
* <appro@fy.chalmers.se>
*/
BN_ULONG a0, a1, a2, a3;
a0 = B[0];
a1 = B[1];
a2 = B[2];
a3 = B[3];
A[0] = a0;
A[1] = a1;
A[2] = a2;
A[3] = a3;
}
/*
* workaround for ultrix cc: without 'case 0', the optimizer does
* the switch table by doing a=top&3; a--; goto jump_table[a];
* which fails for top== 0
*/
switch (b->top & 3) {
case 3:
A[2] = B[2];
case 2:
A[1] = B[1];
case 1:
A[0] = B[0];
case 0:
;
}
}
#else
memset(A, 0, sizeof(BN_ULONG) * words);
memcpy(A, b->d, sizeof(b->d[0]) * b->top);
#endif
return (a);
}
/*
* This is an internal function that can be used instead of bn_expand2() when
* there is a need to copy BIGNUMs instead of only expanding the data part,
* while still expanding them. Especially useful when needing to expand
* BIGNUMs that are declared 'const' and should therefore not be changed. The
* reason to use this instead of a BN_dup() followed by a bn_expand2() is
* memory allocation overhead. A BN_dup() followed by a bn_expand2() will
* allocate new memory for the BIGNUM data twice, and free it once, while
* bn_dup_expand() makes sure allocation is made only once.
*/
#ifndef OPENSSL_NO_DEPRECATED
BIGNUM *bn_dup_expand(const BIGNUM *b, int words)
{
BIGNUM *r = NULL;
bn_check_top(b);
/*
* This function does not work if words <= b->dmax && top < words because
* BN_dup() does not preserve 'dmax'! (But bn_dup_expand() is not used
* anywhere yet.)
*/
if (words > b->dmax) {
BN_ULONG *a = bn_expand_internal(b, words);
if (a) {
r = BN_new();
if (r) {
r->top = b->top;
r->dmax = words;
r->neg = b->neg;
r->d = a;
} else {
/* r == NULL, BN_new failure */
OPENSSL_free(a);
}
}
/*
* If a == NULL, there was an error in allocation in
* bn_expand_internal(), and NULL should be returned
*/
} else {
r = BN_dup(b);
}
bn_check_top(r);
return r;
}
#endif
/*
* This is an internal function that should not be used in applications. It
* ensures that 'b' has enough room for a 'words' word number and initialises
* any unused part of b->d with leading zeros. It is mostly used by the
* various BIGNUM routines. If there is an error, NULL is returned. If not,
* 'b' is returned.
*/
BIGNUM *bn_expand2(BIGNUM *b, int words)
{
bn_check_top(b);
if (words > b->dmax) {
BN_ULONG *a = bn_expand_internal(b, words);
if (!a)
return NULL;
if (b->d)
OPENSSL_free(b->d);
b->d = a;
b->dmax = words;
}
/* None of this should be necessary because of what b->top means! */
#if 0
/*
* NB: bn_wexpand() calls this only if the BIGNUM really has to grow
*/
if (b->top < b->dmax) {
int i;
BN_ULONG *A = &(b->d[b->top]);
for (i = (b->dmax - b->top) >> 3; i > 0; i--, A += 8) {
A[0] = 0;
A[1] = 0;
A[2] = 0;
A[3] = 0;
A[4] = 0;
A[5] = 0;
A[6] = 0;
A[7] = 0;
}
for (i = (b->dmax - b->top) & 7; i > 0; i--, A++)
A[0] = 0;
assert(A == &(b->d[b->dmax]));
}
#endif
bn_check_top(b);
return b;
}
BIGNUM *BN_dup(const BIGNUM *a)
{
BIGNUM *t;
if (a == NULL)
return NULL;
bn_check_top(a);
t = BN_new();
if (t == NULL)
return NULL;
if (!BN_copy(t, a)) {
BN_free(t);
return NULL;
}
bn_check_top(t);
return t;
}
BIGNUM *BN_copy(BIGNUM *a, const BIGNUM *b)
{
int i;
BN_ULONG *A;
const BN_ULONG *B;
bn_check_top(b);
if (a == b)
return (a);
if (bn_wexpand(a, b->top) == NULL)
return (NULL);
#if 1
A = a->d;
B = b->d;
for (i = b->top >> 2; i > 0; i--, A += 4, B += 4) {
BN_ULONG a0, a1, a2, a3;
a0 = B[0];
a1 = B[1];
a2 = B[2];
a3 = B[3];
A[0] = a0;
A[1] = a1;
A[2] = a2;
A[3] = a3;
}
/* ultrix cc workaround, see comments in bn_expand_internal */
switch (b->top & 3) {
case 3:
A[2] = B[2];
case 2:
A[1] = B[1];
case 1:
A[0] = B[0];
case 0:;
}
#else
memcpy(a->d, b->d, sizeof(b->d[0]) * b->top);
#endif
- if (BN_get_flags(b, BN_FLG_CONSTTIME) != 0)
- BN_set_flags(a, BN_FLG_CONSTTIME);
-
a->top = b->top;
a->neg = b->neg;
bn_check_top(a);
return (a);
}
void BN_swap(BIGNUM *a, BIGNUM *b)
{
int flags_old_a, flags_old_b;
BN_ULONG *tmp_d;
int tmp_top, tmp_dmax, tmp_neg;
bn_check_top(a);
bn_check_top(b);
flags_old_a = a->flags;
flags_old_b = b->flags;
tmp_d = a->d;
tmp_top = a->top;
tmp_dmax = a->dmax;
tmp_neg = a->neg;
a->d = b->d;
a->top = b->top;
a->dmax = b->dmax;
a->neg = b->neg;
b->d = tmp_d;
b->top = tmp_top;
b->dmax = tmp_dmax;
b->neg = tmp_neg;
a->flags =
(flags_old_a & BN_FLG_MALLOCED) | (flags_old_b & BN_FLG_STATIC_DATA);
b->flags =
(flags_old_b & BN_FLG_MALLOCED) | (flags_old_a & BN_FLG_STATIC_DATA);
bn_check_top(a);
bn_check_top(b);
}
void BN_clear(BIGNUM *a)
{
bn_check_top(a);
if (a->d != NULL)
OPENSSL_cleanse(a->d, a->dmax * sizeof(a->d[0]));
a->top = 0;
a->neg = 0;
}
BN_ULONG BN_get_word(const BIGNUM *a)
{
if (a->top > 1)
return BN_MASK2;
else if (a->top == 1)
return a->d[0];
/* a->top == 0 */
return 0;
}
int BN_set_word(BIGNUM *a, BN_ULONG w)
{
bn_check_top(a);
if (bn_expand(a, (int)sizeof(BN_ULONG) * 8) == NULL)
return (0);
a->neg = 0;
a->d[0] = w;
a->top = (w ? 1 : 0);
bn_check_top(a);
return (1);
}
BIGNUM *BN_bin2bn(const unsigned char *s, int len, BIGNUM *ret)
{
unsigned int i, m;
unsigned int n;
BN_ULONG l;
BIGNUM *bn = NULL;
if (ret == NULL)
ret = bn = BN_new();
if (ret == NULL)
return (NULL);
bn_check_top(ret);
l = 0;
n = len;
if (n == 0) {
ret->top = 0;
return (ret);
}
i = ((n - 1) / BN_BYTES) + 1;
m = ((n - 1) % (BN_BYTES));
if (bn_wexpand(ret, (int)i) == NULL) {
if (bn)
BN_free(bn);
return NULL;
}
ret->top = i;
ret->neg = 0;
while (n--) {
l = (l << 8L) | *(s++);
if (m-- == 0) {
ret->d[--i] = l;
l = 0;
m = BN_BYTES - 1;
}
}
/*
* need to call this due to clear byte at top if avoiding having the top
* bit set (-ve number)
*/
bn_correct_top(ret);
return (ret);
}
/* ignore negative */
int BN_bn2bin(const BIGNUM *a, unsigned char *to)
{
int n, i;
BN_ULONG l;
bn_check_top(a);
n = i = BN_num_bytes(a);
while (i--) {
l = a->d[i / BN_BYTES];
*(to++) = (unsigned char)(l >> (8 * (i % BN_BYTES))) & 0xff;
}
return (n);
}
int BN_ucmp(const BIGNUM *a, const BIGNUM *b)
{
int i;
BN_ULONG t1, t2, *ap, *bp;
bn_check_top(a);
bn_check_top(b);
i = a->top - b->top;
if (i != 0)
return (i);
ap = a->d;
bp = b->d;
for (i = a->top - 1; i >= 0; i--) {
t1 = ap[i];
t2 = bp[i];
if (t1 != t2)
return ((t1 > t2) ? 1 : -1);
}
return (0);
}
int BN_cmp(const BIGNUM *a, const BIGNUM *b)
{
int i;
int gt, lt;
BN_ULONG t1, t2;
if ((a == NULL) || (b == NULL)) {
if (a != NULL)
return (-1);
else if (b != NULL)
return (1);
else
return (0);
}
bn_check_top(a);
bn_check_top(b);
if (a->neg != b->neg) {
if (a->neg)
return (-1);
else
return (1);
}
if (a->neg == 0) {
gt = 1;
lt = -1;
} else {
gt = -1;
lt = 1;
}
if (a->top > b->top)
return (gt);
if (a->top < b->top)
return (lt);
for (i = a->top - 1; i >= 0; i--) {
t1 = a->d[i];
t2 = b->d[i];
if (t1 > t2)
return (gt);
if (t1 < t2)
return (lt);
}
return (0);
}
int BN_set_bit(BIGNUM *a, int n)
{
int i, j, k;
if (n < 0)
return 0;
i = n / BN_BITS2;
j = n % BN_BITS2;
if (a->top <= i) {
if (bn_wexpand(a, i + 1) == NULL)
return (0);
for (k = a->top; k < i + 1; k++)
a->d[k] = 0;
a->top = i + 1;
}
a->d[i] |= (((BN_ULONG)1) << j);
bn_check_top(a);
return (1);
}
int BN_clear_bit(BIGNUM *a, int n)
{
int i, j;
bn_check_top(a);
if (n < 0)
return 0;
i = n / BN_BITS2;
j = n % BN_BITS2;
if (a->top <= i)
return (0);
a->d[i] &= (~(((BN_ULONG)1) << j));
bn_correct_top(a);
return (1);
}
int BN_is_bit_set(const BIGNUM *a, int n)
{
int i, j;
bn_check_top(a);
if (n < 0)
return 0;
i = n / BN_BITS2;
j = n % BN_BITS2;
if (a->top <= i)
return 0;
return (int)(((a->d[i]) >> j) & ((BN_ULONG)1));
}
int BN_mask_bits(BIGNUM *a, int n)
{
int b, w;
bn_check_top(a);
if (n < 0)
return 0;
w = n / BN_BITS2;
b = n % BN_BITS2;
if (w >= a->top)
return 0;
if (b == 0)
a->top = w;
else {
a->top = w + 1;
a->d[w] &= ~(BN_MASK2 << b);
}
bn_correct_top(a);
return (1);
}
void BN_set_negative(BIGNUM *a, int b)
{
if (b && !BN_is_zero(a))
a->neg = 1;
else
a->neg = 0;
}
int bn_cmp_words(const BN_ULONG *a, const BN_ULONG *b, int n)
{
int i;
BN_ULONG aa, bb;
aa = a[n - 1];
bb = b[n - 1];
if (aa != bb)
return ((aa > bb) ? 1 : -1);
for (i = n - 2; i >= 0; i--) {
aa = a[i];
bb = b[i];
if (aa != bb)
return ((aa > bb) ? 1 : -1);
}
return (0);
}
/*
* Here follows a specialised variants of bn_cmp_words(). It has the
* property of performing the operation on arrays of different sizes. The
* sizes of those arrays is expressed through cl, which is the common length
* ( basicall, min(len(a),len(b)) ), and dl, which is the delta between the
* two lengths, calculated as len(a)-len(b). All lengths are the number of
* BN_ULONGs...
*/
int bn_cmp_part_words(const BN_ULONG *a, const BN_ULONG *b, int cl, int dl)
{
int n, i;
n = cl - 1;
if (dl < 0) {
for (i = dl; i < 0; i++) {
if (b[n - i] != 0)
return -1; /* a < b */
}
}
if (dl > 0) {
for (i = dl; i > 0; i--) {
if (a[n + i] != 0)
return 1; /* a > b */
}
}
return bn_cmp_words(a, b, cl);
}
/*
* Constant-time conditional swap of a and b.
* a and b are swapped if condition is not 0. The code assumes that at most one bit of condition is set.
* nwords is the number of words to swap. The code assumes that at least nwords are allocated in both a and b,
* and that no more than nwords are used by either a or b.
* a and b cannot be the same number
*/
void BN_consttime_swap(BN_ULONG condition, BIGNUM *a, BIGNUM *b, int nwords)
{
BN_ULONG t;
int i;
bn_wcheck_size(a, nwords);
bn_wcheck_size(b, nwords);
assert(a != b);
assert((condition & (condition - 1)) == 0);
assert(sizeof(BN_ULONG) >= sizeof(int));
condition = ((condition - 1) >> (BN_BITS2 - 1)) - 1;
t = (a->top ^ b->top) & condition;
a->top ^= t;
b->top ^= t;
#define BN_CONSTTIME_SWAP(ind) \
do { \
t = (a->d[ind] ^ b->d[ind]) & condition; \
a->d[ind] ^= t; \
b->d[ind] ^= t; \
} while (0)
switch (nwords) {
default:
for (i = 10; i < nwords; i++)
BN_CONSTTIME_SWAP(i);
/* Fallthrough */
case 10:
BN_CONSTTIME_SWAP(9); /* Fallthrough */
case 9:
BN_CONSTTIME_SWAP(8); /* Fallthrough */
case 8:
BN_CONSTTIME_SWAP(7); /* Fallthrough */
case 7:
BN_CONSTTIME_SWAP(6); /* Fallthrough */
case 6:
BN_CONSTTIME_SWAP(5); /* Fallthrough */
case 5:
BN_CONSTTIME_SWAP(4); /* Fallthrough */
case 4:
BN_CONSTTIME_SWAP(3); /* Fallthrough */
case 3:
BN_CONSTTIME_SWAP(2); /* Fallthrough */
case 2:
BN_CONSTTIME_SWAP(1); /* Fallthrough */
case 1:
BN_CONSTTIME_SWAP(0);
}
#undef BN_CONSTTIME_SWAP
}
diff --git a/crypto/bn/bn_mont.c b/crypto/bn/bn_mont.c
index 3af9db870bcb..c1703650ef1e 100644
--- a/crypto/bn/bn_mont.c
+++ b/crypto/bn/bn_mont.c
@@ -1,561 +1,528 @@
/* crypto/bn/bn_mont.c */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
/* ====================================================================
- * Copyright (c) 1998-2006 The OpenSSL Project. All rights reserved.
+ * Copyright (c) 1998-2018 The OpenSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* openssl-core@openssl.org.
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.openssl.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*
* This product includes cryptographic software written by Eric Young
* (eay@cryptsoft.com). This product includes software written by Tim
* Hudson (tjh@cryptsoft.com).
*
*/
/*
* Details about Montgomery multiplication algorithms can be found at
* http://security.ece.orst.edu/publications.html, e.g.
* http://security.ece.orst.edu/koc/papers/j37acmon.pdf and
* sections 3.8 and 4.2 in http://security.ece.orst.edu/koc/papers/r01rsasw.pdf
*/
#include <stdio.h>
#include "cryptlib.h"
#include "bn_lcl.h"
#define MONT_WORD /* use the faster word-based algorithm */
#ifdef MONT_WORD
static int BN_from_montgomery_word(BIGNUM *ret, BIGNUM *r, BN_MONT_CTX *mont);
#endif
int BN_mod_mul_montgomery(BIGNUM *r, const BIGNUM *a, const BIGNUM *b,
BN_MONT_CTX *mont, BN_CTX *ctx)
{
BIGNUM *tmp;
int ret = 0;
#if defined(OPENSSL_BN_ASM_MONT) && defined(MONT_WORD)
int num = mont->N.top;
if (num > 1 && a->top == num && b->top == num) {
if (bn_wexpand(r, num) == NULL)
return (0);
if (bn_mul_mont(r->d, a->d, b->d, mont->N.d, mont->n0, num)) {
r->neg = a->neg ^ b->neg;
r->top = num;
bn_correct_top(r);
return (1);
}
}
#endif
BN_CTX_start(ctx);
tmp = BN_CTX_get(ctx);
if (tmp == NULL)
goto err;
bn_check_top(tmp);
if (a == b) {
if (!BN_sqr(tmp, a, ctx))
goto err;
} else {
if (!BN_mul(tmp, a, b, ctx))
goto err;
}
/* reduce from aRR to aR */
#ifdef MONT_WORD
if (!BN_from_montgomery_word(r, tmp, mont))
goto err;
#else
if (!BN_from_montgomery(r, tmp, mont, ctx))
goto err;
#endif
bn_check_top(r);
ret = 1;
err:
BN_CTX_end(ctx);
return (ret);
}
#ifdef MONT_WORD
static int BN_from_montgomery_word(BIGNUM *ret, BIGNUM *r, BN_MONT_CTX *mont)
{
BIGNUM *n;
BN_ULONG *ap, *np, *rp, n0, v, carry;
int nl, max, i;
n = &(mont->N);
nl = n->top;
if (nl == 0) {
ret->top = 0;
return (1);
}
max = (2 * nl); /* carry is stored separately */
if (bn_wexpand(r, max) == NULL)
return (0);
r->neg ^= n->neg;
np = n->d;
rp = r->d;
/* clear the top words of T */
# if 1
for (i = r->top; i < max; i++) /* memset? XXX */
rp[i] = 0;
# else
memset(&(rp[r->top]), 0, (max - r->top) * sizeof(BN_ULONG));
# endif
r->top = max;
n0 = mont->n0[0];
-# ifdef BN_COUNT
- fprintf(stderr, "word BN_from_montgomery_word %d * %d\n", nl, nl);
-# endif
+ /*
+ * Add multiples of |n| to |r| until R = 2^(nl * BN_BITS2) divides it. On
+ * input, we had |r| < |n| * R, so now |r| < 2 * |n| * R. Note that |r|
+ * includes |carry| which is stored separately.
+ */
for (carry = 0, i = 0; i < nl; i++, rp++) {
-# ifdef __TANDEM
- {
- long long t1;
- long long t2;
- long long t3;
- t1 = rp[0] * (n0 & 0177777);
- t2 = 037777600000l;
- t2 = n0 & t2;
- t3 = rp[0] & 0177777;
- t2 = (t3 * t2) & BN_MASK2;
- t1 = t1 + t2;
- v = bn_mul_add_words(rp, np, nl, (BN_ULONG)t1);
- }
-# else
v = bn_mul_add_words(rp, np, nl, (rp[0] * n0) & BN_MASK2);
-# endif
v = (v + carry + rp[nl]) & BN_MASK2;
carry |= (v != rp[nl]);
carry &= (v <= rp[nl]);
rp[nl] = v;
}
if (bn_wexpand(ret, nl) == NULL)
return (0);
ret->top = nl;
ret->neg = r->neg;
rp = ret->d;
- ap = &(r->d[nl]);
-# define BRANCH_FREE 1
-# if BRANCH_FREE
- {
- BN_ULONG *nrp;
- size_t m;
+ /*
+ * Shift |nl| words to divide by R. We have |ap| < 2 * |n|. Note that |ap|
+ * includes |carry| which is stored separately.
+ */
+ ap = &(r->d[nl]);
- v = bn_sub_words(rp, ap, np, nl) - carry;
- /*
- * if subtraction result is real, then trick unconditional memcpy
- * below to perform in-place "refresh" instead of actual copy.
- */
- m = (0 - (size_t)v);
- nrp =
- (BN_ULONG *)(((PTR_SIZE_INT) rp & ~m) | ((PTR_SIZE_INT) ap & m));
-
- for (i = 0, nl -= 4; i < nl; i += 4) {
- BN_ULONG t1, t2, t3, t4;
-
- t1 = nrp[i + 0];
- t2 = nrp[i + 1];
- t3 = nrp[i + 2];
- ap[i + 0] = 0;
- t4 = nrp[i + 3];
- ap[i + 1] = 0;
- rp[i + 0] = t1;
- ap[i + 2] = 0;
- rp[i + 1] = t2;
- ap[i + 3] = 0;
- rp[i + 2] = t3;
- rp[i + 3] = t4;
- }
- for (nl += 4; i < nl; i++)
- rp[i] = nrp[i], ap[i] = 0;
+ /*
+ * |v| is one if |ap| - |np| underflowed or zero if it did not. Note |v|
+ * cannot be -1. That would imply the subtraction did not fit in |nl| words,
+ * and we know at most one subtraction is needed.
+ */
+ v = bn_sub_words(rp, ap, np, nl) - carry;
+ v = 0 - v;
+ for (i = 0; i < nl; i++) {
+ rp[i] = (v & ap[i]) | (~v & rp[i]);
+ ap[i] = 0;
}
-# else
- if (bn_sub_words(rp, ap, np, nl) - carry)
- memcpy(rp, ap, nl * sizeof(BN_ULONG));
-# endif
bn_correct_top(r);
bn_correct_top(ret);
bn_check_top(ret);
return (1);
}
#endif /* MONT_WORD */
int BN_from_montgomery(BIGNUM *ret, const BIGNUM *a, BN_MONT_CTX *mont,
BN_CTX *ctx)
{
int retn = 0;
#ifdef MONT_WORD
BIGNUM *t;
BN_CTX_start(ctx);
if ((t = BN_CTX_get(ctx)) && BN_copy(t, a))
retn = BN_from_montgomery_word(ret, t, mont);
BN_CTX_end(ctx);
#else /* !MONT_WORD */
BIGNUM *t1, *t2;
BN_CTX_start(ctx);
t1 = BN_CTX_get(ctx);
t2 = BN_CTX_get(ctx);
if (t1 == NULL || t2 == NULL)
goto err;
if (!BN_copy(t1, a))
goto err;
BN_mask_bits(t1, mont->ri);
if (!BN_mul(t2, t1, &mont->Ni, ctx))
goto err;
BN_mask_bits(t2, mont->ri);
if (!BN_mul(t1, t2, &mont->N, ctx))
goto err;
if (!BN_add(t2, a, t1))
goto err;
if (!BN_rshift(ret, t2, mont->ri))
goto err;
if (BN_ucmp(ret, &(mont->N)) >= 0) {
if (!BN_usub(ret, ret, &(mont->N)))
goto err;
}
retn = 1;
bn_check_top(ret);
err:
BN_CTX_end(ctx);
#endif /* MONT_WORD */
return (retn);
}
BN_MONT_CTX *BN_MONT_CTX_new(void)
{
BN_MONT_CTX *ret;
if ((ret = (BN_MONT_CTX *)OPENSSL_malloc(sizeof(BN_MONT_CTX))) == NULL)
return (NULL);
BN_MONT_CTX_init(ret);
ret->flags = BN_FLG_MALLOCED;
return (ret);
}
void BN_MONT_CTX_init(BN_MONT_CTX *ctx)
{
ctx->ri = 0;
BN_init(&(ctx->RR));
BN_init(&(ctx->N));
BN_init(&(ctx->Ni));
ctx->n0[0] = ctx->n0[1] = 0;
ctx->flags = 0;
}
void BN_MONT_CTX_free(BN_MONT_CTX *mont)
{
if (mont == NULL)
return;
BN_clear_free(&(mont->RR));
BN_clear_free(&(mont->N));
BN_clear_free(&(mont->Ni));
if (mont->flags & BN_FLG_MALLOCED)
OPENSSL_free(mont);
}
int BN_MONT_CTX_set(BN_MONT_CTX *mont, const BIGNUM *mod, BN_CTX *ctx)
{
int ret = 0;
BIGNUM *Ri, *R;
if (BN_is_zero(mod))
return 0;
BN_CTX_start(ctx);
if ((Ri = BN_CTX_get(ctx)) == NULL)
goto err;
R = &(mont->RR); /* grab RR as a temp */
if (!BN_copy(&(mont->N), mod))
goto err; /* Set N */
+ if (BN_get_flags(mod, BN_FLG_CONSTTIME) != 0)
+ BN_set_flags(&(mont->N), BN_FLG_CONSTTIME);
mont->N.neg = 0;
#ifdef MONT_WORD
{
BIGNUM tmod;
BN_ULONG buf[2];
BN_init(&tmod);
tmod.d = buf;
tmod.dmax = 2;
tmod.neg = 0;
if (BN_get_flags(mod, BN_FLG_CONSTTIME) != 0)
BN_set_flags(&tmod, BN_FLG_CONSTTIME);
mont->ri = (BN_num_bits(mod) + (BN_BITS2 - 1)) / BN_BITS2 * BN_BITS2;
# if defined(OPENSSL_BN_ASM_MONT) && (BN_BITS2<=32)
/*
* Only certain BN_BITS2<=32 platforms actually make use of n0[1],
* and we could use the #else case (with a shorter R value) for the
* others. However, currently only the assembler files do know which
* is which.
*/
BN_zero(R);
if (!(BN_set_bit(R, 2 * BN_BITS2)))
goto err;
tmod.top = 0;
if ((buf[0] = mod->d[0]))
tmod.top = 1;
if ((buf[1] = mod->top > 1 ? mod->d[1] : 0))
tmod.top = 2;
if ((BN_mod_inverse(Ri, R, &tmod, ctx)) == NULL)
goto err;
if (!BN_lshift(Ri, Ri, 2 * BN_BITS2))
goto err; /* R*Ri */
if (!BN_is_zero(Ri)) {
if (!BN_sub_word(Ri, 1))
goto err;
} else { /* if N mod word size == 1 */
if (bn_expand(Ri, (int)sizeof(BN_ULONG) * 2) == NULL)
goto err;
/* Ri-- (mod double word size) */
Ri->neg = 0;
Ri->d[0] = BN_MASK2;
Ri->d[1] = BN_MASK2;
Ri->top = 2;
}
if (!BN_div(Ri, NULL, Ri, &tmod, ctx))
goto err;
/*
* Ni = (R*Ri-1)/N, keep only couple of least significant words:
*/
mont->n0[0] = (Ri->top > 0) ? Ri->d[0] : 0;
mont->n0[1] = (Ri->top > 1) ? Ri->d[1] : 0;
# else
BN_zero(R);
if (!(BN_set_bit(R, BN_BITS2)))
goto err; /* R */
buf[0] = mod->d[0]; /* tmod = N mod word size */
buf[1] = 0;
tmod.top = buf[0] != 0 ? 1 : 0;
/* Ri = R^-1 mod N */
if ((BN_mod_inverse(Ri, R, &tmod, ctx)) == NULL)
goto err;
if (!BN_lshift(Ri, Ri, BN_BITS2))
goto err; /* R*Ri */
if (!BN_is_zero(Ri)) {
if (!BN_sub_word(Ri, 1))
goto err;
} else { /* if N mod word size == 1 */
if (!BN_set_word(Ri, BN_MASK2))
goto err; /* Ri-- (mod word size) */
}
if (!BN_div(Ri, NULL, Ri, &tmod, ctx))
goto err;
/*
* Ni = (R*Ri-1)/N, keep only least significant word:
*/
mont->n0[0] = (Ri->top > 0) ? Ri->d[0] : 0;
mont->n0[1] = 0;
# endif
}
#else /* !MONT_WORD */
{ /* bignum version */
mont->ri = BN_num_bits(&mont->N);
BN_zero(R);
if (!BN_set_bit(R, mont->ri))
goto err; /* R = 2^ri */
/* Ri = R^-1 mod N */
if ((BN_mod_inverse(Ri, R, &mont->N, ctx)) == NULL)
goto err;
if (!BN_lshift(Ri, Ri, mont->ri))
goto err; /* R*Ri */
if (!BN_sub_word(Ri, 1))
goto err;
/*
* Ni = (R*Ri-1) / N
*/
if (!BN_div(&(mont->Ni), NULL, Ri, &mont->N, ctx))
goto err;
}
#endif
/* setup RR for conversions */
BN_zero(&(mont->RR));
if (!BN_set_bit(&(mont->RR), mont->ri * 2))
goto err;
if (!BN_mod(&(mont->RR), &(mont->RR), &(mont->N), ctx))
goto err;
ret = 1;
err:
BN_CTX_end(ctx);
return ret;
}
BN_MONT_CTX *BN_MONT_CTX_copy(BN_MONT_CTX *to, BN_MONT_CTX *from)
{
if (to == from)
return (to);
if (!BN_copy(&(to->RR), &(from->RR)))
return NULL;
if (!BN_copy(&(to->N), &(from->N)))
return NULL;
if (!BN_copy(&(to->Ni), &(from->Ni)))
return NULL;
to->ri = from->ri;
to->n0[0] = from->n0[0];
to->n0[1] = from->n0[1];
return (to);
}
BN_MONT_CTX *BN_MONT_CTX_set_locked(BN_MONT_CTX **pmont, int lock,
const BIGNUM *mod, BN_CTX *ctx)
{
BN_MONT_CTX *ret;
CRYPTO_r_lock(lock);
ret = *pmont;
CRYPTO_r_unlock(lock);
if (ret)
return ret;
/*
* We don't want to serialise globally while doing our lazy-init math in
* BN_MONT_CTX_set. That punishes threads that are doing independent
* things. Instead, punish the case where more than one thread tries to
* lazy-init the same 'pmont', by having each do the lazy-init math work
* independently and only use the one from the thread that wins the race
* (the losers throw away the work they've done).
*/
ret = BN_MONT_CTX_new();
if (!ret)
return NULL;
if (!BN_MONT_CTX_set(ret, mod, ctx)) {
BN_MONT_CTX_free(ret);
return NULL;
}
/* The locked compare-and-set, after the local work is done. */
CRYPTO_w_lock(lock);
if (*pmont) {
BN_MONT_CTX_free(ret);
ret = *pmont;
} else
*pmont = ret;
CRYPTO_w_unlock(lock);
return ret;
}
diff --git a/crypto/bn/bn_print.c b/crypto/bn/bn_print.c
index f85a6550a54e..c0b029dad6cd 100644
--- a/crypto/bn/bn_print.c
+++ b/crypto/bn/bn_print.c
@@ -1,402 +1,402 @@
/* crypto/bn/bn_print.c */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
#include <stdio.h>
#include <ctype.h>
#include <limits.h>
#include "cryptlib.h"
#include <openssl/buffer.h>
#include "bn_lcl.h"
static const char Hex[] = "0123456789ABCDEF";
/* Must 'OPENSSL_free' the returned data */
char *BN_bn2hex(const BIGNUM *a)
{
int i, j, v, z = 0;
char *buf;
char *p;
if (BN_is_zero(a))
return OPENSSL_strdup("0");
buf = OPENSSL_malloc(a->top * BN_BYTES * 2 + 2);
if (buf == NULL) {
BNerr(BN_F_BN_BN2HEX, ERR_R_MALLOC_FAILURE);
goto err;
}
p = buf;
if (a->neg)
*(p++) = '-';
for (i = a->top - 1; i >= 0; i--) {
for (j = BN_BITS2 - 8; j >= 0; j -= 8) {
/* strip leading zeros */
v = ((int)(a->d[i] >> (long)j)) & 0xff;
if (z || (v != 0)) {
*(p++) = Hex[v >> 4];
*(p++) = Hex[v & 0x0f];
z = 1;
}
}
}
*p = '\0';
err:
return (buf);
}
/* Must 'OPENSSL_free' the returned data */
char *BN_bn2dec(const BIGNUM *a)
{
int i = 0, num, ok = 0;
char *buf = NULL;
char *p;
BIGNUM *t = NULL;
BN_ULONG *bn_data = NULL, *lp;
int bn_data_num;
/*-
* get an upper bound for the length of the decimal integer
* num <= (BN_num_bits(a) + 1) * log(2)
* <= 3 * BN_num_bits(a) * 0.1001 + log(2) + 1 (rounding error)
* <= BN_num_bits(a)/10 + BN_num_bits/1000 + 1 + 1
*/
i = BN_num_bits(a) * 3;
num = (i / 10 + i / 1000 + 1) + 1;
bn_data_num = num / BN_DEC_NUM + 1;
bn_data = OPENSSL_malloc(bn_data_num * sizeof(BN_ULONG));
buf = OPENSSL_malloc(num + 3);
if ((buf == NULL) || (bn_data == NULL)) {
BNerr(BN_F_BN_BN2DEC, ERR_R_MALLOC_FAILURE);
goto err;
}
if ((t = BN_dup(a)) == NULL)
goto err;
#define BUF_REMAIN (num+3 - (size_t)(p - buf))
p = buf;
lp = bn_data;
if (BN_is_zero(t)) {
*(p++) = '0';
*(p++) = '\0';
} else {
if (BN_is_negative(t))
*p++ = '-';
while (!BN_is_zero(t)) {
if (lp - bn_data >= bn_data_num)
goto err;
*lp = BN_div_word(t, BN_DEC_CONV);
if (*lp == (BN_ULONG)-1)
goto err;
lp++;
}
lp--;
/*
* We now have a series of blocks, BN_DEC_NUM chars in length, where
* the last one needs truncation. The blocks need to be reversed in
* order.
*/
BIO_snprintf(p, BUF_REMAIN, BN_DEC_FMT1, *lp);
while (*p)
p++;
while (lp != bn_data) {
lp--;
BIO_snprintf(p, BUF_REMAIN, BN_DEC_FMT2, *lp);
while (*p)
p++;
}
}
ok = 1;
err:
if (bn_data != NULL)
OPENSSL_free(bn_data);
if (t != NULL)
BN_free(t);
if (!ok && buf) {
OPENSSL_free(buf);
buf = NULL;
}
return (buf);
}
int BN_hex2bn(BIGNUM **bn, const char *a)
{
BIGNUM *ret = NULL;
BN_ULONG l = 0;
int neg = 0, h, m, i, j, k, c;
int num;
if ((a == NULL) || (*a == '\0'))
return (0);
if (*a == '-') {
neg = 1;
a++;
}
for (i = 0; i <= (INT_MAX/4) && isxdigit((unsigned char)a[i]); i++)
continue;
if (i > INT_MAX/4)
goto err;
num = i + neg;
if (bn == NULL)
return (num);
/* a is the start of the hex digits, and it is 'i' long */
if (*bn == NULL) {
if ((ret = BN_new()) == NULL)
return (0);
} else {
ret = *bn;
BN_zero(ret);
}
/* i is the number of hex digits */
if (bn_expand(ret, i * 4) == NULL)
goto err;
j = i; /* least significant 'hex' */
m = 0;
h = 0;
while (j > 0) {
m = ((BN_BYTES * 2) <= j) ? (BN_BYTES * 2) : j;
l = 0;
for (;;) {
c = a[j - m];
if ((c >= '0') && (c <= '9'))
k = c - '0';
else if ((c >= 'a') && (c <= 'f'))
k = c - 'a' + 10;
else if ((c >= 'A') && (c <= 'F'))
k = c - 'A' + 10;
else
k = 0; /* paranoia */
l = (l << 4) | k;
if (--m <= 0) {
ret->d[h++] = l;
break;
}
}
j -= (BN_BYTES * 2);
}
ret->top = h;
bn_correct_top(ret);
*bn = ret;
bn_check_top(ret);
/* Don't set the negative flag if it's zero. */
if (ret->top != 0)
ret->neg = neg;
return (num);
err:
if (*bn == NULL)
BN_free(ret);
return (0);
}
int BN_dec2bn(BIGNUM **bn, const char *a)
{
BIGNUM *ret = NULL;
BN_ULONG l = 0;
int neg = 0, i, j;
int num;
if ((a == NULL) || (*a == '\0'))
return (0);
if (*a == '-') {
neg = 1;
a++;
}
for (i = 0; i <= (INT_MAX/4) && isdigit((unsigned char)a[i]); i++)
continue;
if (i > INT_MAX/4)
goto err;
num = i + neg;
if (bn == NULL)
return (num);
/*
* a is the start of the digits, and it is 'i' long. We chop it into
* BN_DEC_NUM digits at a time
*/
if (*bn == NULL) {
if ((ret = BN_new()) == NULL)
return (0);
} else {
ret = *bn;
BN_zero(ret);
}
/* i is the number of digits, a bit of an over expand */
if (bn_expand(ret, i * 4) == NULL)
goto err;
j = BN_DEC_NUM - (i % BN_DEC_NUM);
if (j == BN_DEC_NUM)
j = 0;
l = 0;
while (--i >= 0) {
l *= 10;
l += *a - '0';
a++;
if (++j == BN_DEC_NUM) {
BN_mul_word(ret, BN_DEC_CONV);
BN_add_word(ret, l);
l = 0;
j = 0;
}
}
bn_correct_top(ret);
*bn = ret;
bn_check_top(ret);
/* Don't set the negative flag if it's zero. */
if (ret->top != 0)
ret->neg = neg;
return (num);
err:
if (*bn == NULL)
BN_free(ret);
return (0);
}
int BN_asc2bn(BIGNUM **bn, const char *a)
{
const char *p = a;
if (*p == '-')
p++;
if (p[0] == '0' && (p[1] == 'X' || p[1] == 'x')) {
if (!BN_hex2bn(bn, p + 2))
return 0;
} else {
if (!BN_dec2bn(bn, p))
return 0;
}
/* Don't set the negative flag if it's zero. */
if (*a == '-' && (*bn)->top != 0)
(*bn)->neg = 1;
return 1;
}
#ifndef OPENSSL_NO_BIO
# ifndef OPENSSL_NO_FP_API
int BN_print_fp(FILE *fp, const BIGNUM *a)
{
BIO *b;
int ret;
if ((b = BIO_new(BIO_s_file())) == NULL)
return (0);
BIO_set_fp(b, fp, BIO_NOCLOSE);
ret = BN_print(b, a);
BIO_free(b);
return (ret);
}
# endif
int BN_print(BIO *bp, const BIGNUM *a)
{
int i, j, v, z = 0;
int ret = 0;
if ((a->neg) && (BIO_write(bp, "-", 1) != 1))
goto end;
if (BN_is_zero(a) && (BIO_write(bp, "0", 1) != 1))
goto end;
for (i = a->top - 1; i >= 0; i--) {
for (j = BN_BITS2 - 4; j >= 0; j -= 4) {
/* strip leading zeros */
v = ((int)(a->d[i] >> (long)j)) & 0x0f;
if (z || (v != 0)) {
if (BIO_write(bp, &(Hex[v]), 1) != 1)
goto end;
z = 1;
}
}
}
ret = 1;
end:
return (ret);
}
#endif
char *BN_options(void)
{
static int init = 0;
static char data[16];
if (!init) {
init++;
#ifdef BN_LLONG
- BIO_snprintf(data, sizeof data, "bn(%d,%d)",
+ BIO_snprintf(data, sizeof(data), "bn(%d,%d)",
(int)sizeof(BN_ULLONG) * 8, (int)sizeof(BN_ULONG) * 8);
#else
- BIO_snprintf(data, sizeof data, "bn(%d,%d)",
+ BIO_snprintf(data, sizeof(data), "bn(%d,%d)",
(int)sizeof(BN_ULONG) * 8, (int)sizeof(BN_ULONG) * 8);
#endif
}
return (data);
}
diff --git a/crypto/bn/bntest.c b/crypto/bn/bntest.c
index a327b1a647b2..abe5dbe0b01a 100644
--- a/crypto/bn/bntest.c
+++ b/crypto/bn/bntest.c
@@ -1,2160 +1,2160 @@
/* crypto/bn/bntest.c */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
/* ====================================================================
* Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
*
* Portions of the attached software ("Contribution") are developed by
* SUN MICROSYSTEMS, INC., and are contributed to the OpenSSL project.
*
* The Contribution is licensed pursuant to the Eric Young open source
* license provided above.
*
* The binary polynomial arithmetic software is originally written by
* Sheueling Chang Shantz and Douglas Stebila of Sun Microsystems Laboratories.
*
*/
/*
* Until the key-gen callbacks are modified to use newer prototypes, we allow
* deprecated functions for openssl-internal code
*/
#ifdef OPENSSL_NO_DEPRECATED
# undef OPENSSL_NO_DEPRECATED
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "e_os.h"
#include <openssl/bio.h>
#include <openssl/bn.h>
#include <openssl/rand.h>
#include <openssl/x509.h>
#include <openssl/err.h>
const int num0 = 100; /* number of tests */
const int num1 = 50; /* additional tests for some functions */
const int num2 = 5; /* number of tests for slow functions */
int test_add(BIO *bp);
int test_sub(BIO *bp);
int test_lshift1(BIO *bp);
int test_lshift(BIO *bp, BN_CTX *ctx, BIGNUM *a_);
int test_rshift1(BIO *bp);
int test_rshift(BIO *bp, BN_CTX *ctx);
int test_div(BIO *bp, BN_CTX *ctx);
int test_div_word(BIO *bp);
int test_div_recp(BIO *bp, BN_CTX *ctx);
int test_mul(BIO *bp);
int test_sqr(BIO *bp, BN_CTX *ctx);
int test_mont(BIO *bp, BN_CTX *ctx);
int test_mod(BIO *bp, BN_CTX *ctx);
int test_mod_mul(BIO *bp, BN_CTX *ctx);
int test_mod_exp(BIO *bp, BN_CTX *ctx);
int test_mod_exp_mont_consttime(BIO *bp, BN_CTX *ctx);
int test_mod_exp_mont5(BIO *bp, BN_CTX *ctx);
int test_exp(BIO *bp, BN_CTX *ctx);
int test_gf2m_add(BIO *bp);
int test_gf2m_mod(BIO *bp);
int test_gf2m_mod_mul(BIO *bp, BN_CTX *ctx);
int test_gf2m_mod_sqr(BIO *bp, BN_CTX *ctx);
int test_gf2m_mod_inv(BIO *bp, BN_CTX *ctx);
int test_gf2m_mod_div(BIO *bp, BN_CTX *ctx);
int test_gf2m_mod_exp(BIO *bp, BN_CTX *ctx);
int test_gf2m_mod_sqrt(BIO *bp, BN_CTX *ctx);
int test_gf2m_mod_solve_quad(BIO *bp, BN_CTX *ctx);
int test_kron(BIO *bp, BN_CTX *ctx);
int test_sqrt(BIO *bp, BN_CTX *ctx);
int rand_neg(void);
static int results = 0;
static unsigned char lst[] =
"\xC6\x4F\x43\x04\x2A\xEA\xCA\x6E\x58\x36\x80\x5B\xE8\xC9"
"\x9B\x04\x5D\x48\x36\xC2\xFD\x16\xC9\x64\xF0";
static const char rnd_seed[] =
"string to make the random number generator think it has entropy";
static void message(BIO *out, char *m)
{
fprintf(stderr, "test %s\n", m);
BIO_puts(out, "print \"test ");
BIO_puts(out, m);
BIO_puts(out, "\\n\"\n");
}
int main(int argc, char *argv[])
{
BN_CTX *ctx;
BIO *out;
char *outfile = NULL;
results = 0;
- RAND_seed(rnd_seed, sizeof rnd_seed); /* or BN_generate_prime may fail */
+ RAND_seed(rnd_seed, sizeof(rnd_seed)); /* or BN_generate_prime may fail */
argc--;
argv++;
while (argc >= 1) {
if (strcmp(*argv, "-results") == 0)
results = 1;
else if (strcmp(*argv, "-out") == 0) {
if (--argc < 1)
break;
outfile = *(++argv);
}
argc--;
argv++;
}
ctx = BN_CTX_new();
if (ctx == NULL)
EXIT(1);
out = BIO_new(BIO_s_file());
if (out == NULL)
EXIT(1);
if (outfile == NULL) {
BIO_set_fp(out, stdout, BIO_NOCLOSE);
} else {
if (!BIO_write_filename(out, outfile)) {
perror(outfile);
EXIT(1);
}
}
if (!results)
BIO_puts(out, "obase=16\nibase=16\n");
message(out, "BN_add");
if (!test_add(out))
goto err;
(void)BIO_flush(out);
message(out, "BN_sub");
if (!test_sub(out))
goto err;
(void)BIO_flush(out);
message(out, "BN_lshift1");
if (!test_lshift1(out))
goto err;
(void)BIO_flush(out);
message(out, "BN_lshift (fixed)");
if (!test_lshift(out, ctx, BN_bin2bn(lst, sizeof(lst) - 1, NULL)))
goto err;
(void)BIO_flush(out);
message(out, "BN_lshift");
if (!test_lshift(out, ctx, NULL))
goto err;
(void)BIO_flush(out);
message(out, "BN_rshift1");
if (!test_rshift1(out))
goto err;
(void)BIO_flush(out);
message(out, "BN_rshift");
if (!test_rshift(out, ctx))
goto err;
(void)BIO_flush(out);
message(out, "BN_sqr");
if (!test_sqr(out, ctx))
goto err;
(void)BIO_flush(out);
message(out, "BN_mul");
if (!test_mul(out))
goto err;
(void)BIO_flush(out);
message(out, "BN_div");
if (!test_div(out, ctx))
goto err;
(void)BIO_flush(out);
message(out, "BN_div_word");
if (!test_div_word(out))
goto err;
(void)BIO_flush(out);
message(out, "BN_div_recp");
if (!test_div_recp(out, ctx))
goto err;
(void)BIO_flush(out);
message(out, "BN_mod");
if (!test_mod(out, ctx))
goto err;
(void)BIO_flush(out);
message(out, "BN_mod_mul");
if (!test_mod_mul(out, ctx))
goto err;
(void)BIO_flush(out);
message(out, "BN_mont");
if (!test_mont(out, ctx))
goto err;
(void)BIO_flush(out);
message(out, "BN_mod_exp");
if (!test_mod_exp(out, ctx))
goto err;
(void)BIO_flush(out);
message(out, "BN_mod_exp_mont_consttime");
if (!test_mod_exp_mont_consttime(out, ctx))
goto err;
if (!test_mod_exp_mont5(out, ctx))
goto err;
(void)BIO_flush(out);
message(out, "BN_exp");
if (!test_exp(out, ctx))
goto err;
(void)BIO_flush(out);
message(out, "BN_kronecker");
if (!test_kron(out, ctx))
goto err;
(void)BIO_flush(out);
message(out, "BN_mod_sqrt");
if (!test_sqrt(out, ctx))
goto err;
(void)BIO_flush(out);
#ifndef OPENSSL_NO_EC2M
message(out, "BN_GF2m_add");
if (!test_gf2m_add(out))
goto err;
(void)BIO_flush(out);
message(out, "BN_GF2m_mod");
if (!test_gf2m_mod(out))
goto err;
(void)BIO_flush(out);
message(out, "BN_GF2m_mod_mul");
if (!test_gf2m_mod_mul(out, ctx))
goto err;
(void)BIO_flush(out);
message(out, "BN_GF2m_mod_sqr");
if (!test_gf2m_mod_sqr(out, ctx))
goto err;
(void)BIO_flush(out);
message(out, "BN_GF2m_mod_inv");
if (!test_gf2m_mod_inv(out, ctx))
goto err;
(void)BIO_flush(out);
message(out, "BN_GF2m_mod_div");
if (!test_gf2m_mod_div(out, ctx))
goto err;
(void)BIO_flush(out);
message(out, "BN_GF2m_mod_exp");
if (!test_gf2m_mod_exp(out, ctx))
goto err;
(void)BIO_flush(out);
message(out, "BN_GF2m_mod_sqrt");
if (!test_gf2m_mod_sqrt(out, ctx))
goto err;
(void)BIO_flush(out);
message(out, "BN_GF2m_mod_solve_quad");
if (!test_gf2m_mod_solve_quad(out, ctx))
goto err;
(void)BIO_flush(out);
#endif
BN_CTX_free(ctx);
BIO_free(out);
EXIT(0);
err:
BIO_puts(out, "1\n"); /* make sure the Perl script fed by bc
* notices the failure, see test_bn in
* test/Makefile.ssl */
(void)BIO_flush(out);
ERR_load_crypto_strings();
ERR_print_errors_fp(stderr);
EXIT(1);
return (1);
}
int test_add(BIO *bp)
{
BIGNUM a, b, c;
int i;
BN_init(&a);
BN_init(&b);
BN_init(&c);
BN_bntest_rand(&a, 512, 0, 0);
for (i = 0; i < num0; i++) {
BN_bntest_rand(&b, 450 + i, 0, 0);
a.neg = rand_neg();
b.neg = rand_neg();
BN_add(&c, &a, &b);
if (bp != NULL) {
if (!results) {
BN_print(bp, &a);
BIO_puts(bp, " + ");
BN_print(bp, &b);
BIO_puts(bp, " - ");
}
BN_print(bp, &c);
BIO_puts(bp, "\n");
}
a.neg = !a.neg;
b.neg = !b.neg;
BN_add(&c, &c, &b);
BN_add(&c, &c, &a);
if (!BN_is_zero(&c)) {
fprintf(stderr, "Add test failed!\n");
return 0;
}
}
BN_free(&a);
BN_free(&b);
BN_free(&c);
return (1);
}
int test_sub(BIO *bp)
{
BIGNUM a, b, c;
int i;
BN_init(&a);
BN_init(&b);
BN_init(&c);
for (i = 0; i < num0 + num1; i++) {
if (i < num1) {
BN_bntest_rand(&a, 512, 0, 0);
BN_copy(&b, &a);
if (BN_set_bit(&a, i) == 0)
return (0);
BN_add_word(&b, i);
} else {
BN_bntest_rand(&b, 400 + i - num1, 0, 0);
a.neg = rand_neg();
b.neg = rand_neg();
}
BN_sub(&c, &a, &b);
if (bp != NULL) {
if (!results) {
BN_print(bp, &a);
BIO_puts(bp, " - ");
BN_print(bp, &b);
BIO_puts(bp, " - ");
}
BN_print(bp, &c);
BIO_puts(bp, "\n");
}
BN_add(&c, &c, &b);
BN_sub(&c, &c, &a);
if (!BN_is_zero(&c)) {
fprintf(stderr, "Subtract test failed!\n");
return 0;
}
}
BN_free(&a);
BN_free(&b);
BN_free(&c);
return (1);
}
int test_div(BIO *bp, BN_CTX *ctx)
{
BIGNUM a, b, c, d, e;
int i;
BN_init(&a);
BN_init(&b);
BN_init(&c);
BN_init(&d);
BN_init(&e);
BN_one(&a);
BN_zero(&b);
if (BN_div(&d, &c, &a, &b, ctx)) {
fprintf(stderr, "Division by zero succeeded!\n");
return 0;
}
for (i = 0; i < num0 + num1; i++) {
if (i < num1) {
BN_bntest_rand(&a, 400, 0, 0);
BN_copy(&b, &a);
BN_lshift(&a, &a, i);
BN_add_word(&a, i);
} else
BN_bntest_rand(&b, 50 + 3 * (i - num1), 0, 0);
a.neg = rand_neg();
b.neg = rand_neg();
BN_div(&d, &c, &a, &b, ctx);
if (bp != NULL) {
if (!results) {
BN_print(bp, &a);
BIO_puts(bp, " / ");
BN_print(bp, &b);
BIO_puts(bp, " - ");
}
BN_print(bp, &d);
BIO_puts(bp, "\n");
if (!results) {
BN_print(bp, &a);
BIO_puts(bp, " % ");
BN_print(bp, &b);
BIO_puts(bp, " - ");
}
BN_print(bp, &c);
BIO_puts(bp, "\n");
}
BN_mul(&e, &d, &b, ctx);
BN_add(&d, &e, &c);
BN_sub(&d, &d, &a);
if (!BN_is_zero(&d)) {
fprintf(stderr, "Division test failed!\n");
return 0;
}
}
BN_free(&a);
BN_free(&b);
BN_free(&c);
BN_free(&d);
BN_free(&e);
return (1);
}
static void print_word(BIO *bp, BN_ULONG w)
{
#ifdef SIXTY_FOUR_BIT
if (sizeof(w) > sizeof(unsigned long)) {
unsigned long h = (unsigned long)(w >> 32), l = (unsigned long)(w);
if (h)
BIO_printf(bp, "%lX%08lX", h, l);
else
BIO_printf(bp, "%lX", l);
return;
}
#endif
BIO_printf(bp, BN_HEX_FMT1, w);
}
int test_div_word(BIO *bp)
{
BIGNUM a, b;
BN_ULONG r, rmod, s;
int i;
BN_init(&a);
BN_init(&b);
for (i = 0; i < num0; i++) {
do {
BN_bntest_rand(&a, 512, -1, 0);
BN_bntest_rand(&b, BN_BITS2, -1, 0);
} while (BN_is_zero(&b));
s = b.d[0];
BN_copy(&b, &a);
rmod = BN_mod_word(&b, s);
r = BN_div_word(&b, s);
if (rmod != r) {
fprintf(stderr, "Mod (word) test failed!\n");
return 0;
}
if (bp != NULL) {
if (!results) {
BN_print(bp, &a);
BIO_puts(bp, " / ");
print_word(bp, s);
BIO_puts(bp, " - ");
}
BN_print(bp, &b);
BIO_puts(bp, "\n");
if (!results) {
BN_print(bp, &a);
BIO_puts(bp, " % ");
print_word(bp, s);
BIO_puts(bp, " - ");
}
print_word(bp, r);
BIO_puts(bp, "\n");
}
BN_mul_word(&b, s);
BN_add_word(&b, r);
BN_sub(&b, &a, &b);
if (!BN_is_zero(&b)) {
fprintf(stderr, "Division (word) test failed!\n");
return 0;
}
}
BN_free(&a);
BN_free(&b);
return (1);
}
int test_div_recp(BIO *bp, BN_CTX *ctx)
{
BIGNUM a, b, c, d, e;
BN_RECP_CTX recp;
int i;
BN_RECP_CTX_init(&recp);
BN_init(&a);
BN_init(&b);
BN_init(&c);
BN_init(&d);
BN_init(&e);
for (i = 0; i < num0 + num1; i++) {
if (i < num1) {
BN_bntest_rand(&a, 400, 0, 0);
BN_copy(&b, &a);
BN_lshift(&a, &a, i);
BN_add_word(&a, i);
} else
BN_bntest_rand(&b, 50 + 3 * (i - num1), 0, 0);
a.neg = rand_neg();
b.neg = rand_neg();
BN_RECP_CTX_set(&recp, &b, ctx);
BN_div_recp(&d, &c, &a, &recp, ctx);
if (bp != NULL) {
if (!results) {
BN_print(bp, &a);
BIO_puts(bp, " / ");
BN_print(bp, &b);
BIO_puts(bp, " - ");
}
BN_print(bp, &d);
BIO_puts(bp, "\n");
if (!results) {
BN_print(bp, &a);
BIO_puts(bp, " % ");
BN_print(bp, &b);
BIO_puts(bp, " - ");
}
BN_print(bp, &c);
BIO_puts(bp, "\n");
}
BN_mul(&e, &d, &b, ctx);
BN_add(&d, &e, &c);
BN_sub(&d, &d, &a);
if (!BN_is_zero(&d)) {
fprintf(stderr, "Reciprocal division test failed!\n");
fprintf(stderr, "a=");
BN_print_fp(stderr, &a);
fprintf(stderr, "\nb=");
BN_print_fp(stderr, &b);
fprintf(stderr, "\n");
return 0;
}
}
BN_free(&a);
BN_free(&b);
BN_free(&c);
BN_free(&d);
BN_free(&e);
BN_RECP_CTX_free(&recp);
return (1);
}
int test_mul(BIO *bp)
{
BIGNUM a, b, c, d, e;
int i;
BN_CTX *ctx;
ctx = BN_CTX_new();
if (ctx == NULL)
EXIT(1);
BN_init(&a);
BN_init(&b);
BN_init(&c);
BN_init(&d);
BN_init(&e);
for (i = 0; i < num0 + num1; i++) {
if (i <= num1) {
BN_bntest_rand(&a, 100, 0, 0);
BN_bntest_rand(&b, 100, 0, 0);
} else
BN_bntest_rand(&b, i - num1, 0, 0);
a.neg = rand_neg();
b.neg = rand_neg();
BN_mul(&c, &a, &b, ctx);
if (bp != NULL) {
if (!results) {
BN_print(bp, &a);
BIO_puts(bp, " * ");
BN_print(bp, &b);
BIO_puts(bp, " - ");
}
BN_print(bp, &c);
BIO_puts(bp, "\n");
}
BN_div(&d, &e, &c, &a, ctx);
BN_sub(&d, &d, &b);
if (!BN_is_zero(&d) || !BN_is_zero(&e)) {
fprintf(stderr, "Multiplication test failed!\n");
return 0;
}
}
BN_free(&a);
BN_free(&b);
BN_free(&c);
BN_free(&d);
BN_free(&e);
BN_CTX_free(ctx);
return (1);
}
int test_sqr(BIO *bp, BN_CTX *ctx)
{
BIGNUM *a, *c, *d, *e;
int i, ret = 0;
a = BN_new();
c = BN_new();
d = BN_new();
e = BN_new();
if (a == NULL || c == NULL || d == NULL || e == NULL) {
goto err;
}
for (i = 0; i < num0; i++) {
BN_bntest_rand(a, 40 + i * 10, 0, 0);
a->neg = rand_neg();
BN_sqr(c, a, ctx);
if (bp != NULL) {
if (!results) {
BN_print(bp, a);
BIO_puts(bp, " * ");
BN_print(bp, a);
BIO_puts(bp, " - ");
}
BN_print(bp, c);
BIO_puts(bp, "\n");
}
BN_div(d, e, c, a, ctx);
BN_sub(d, d, a);
if (!BN_is_zero(d) || !BN_is_zero(e)) {
fprintf(stderr, "Square test failed!\n");
goto err;
}
}
/* Regression test for a BN_sqr overflow bug. */
BN_hex2bn(&a,
"80000000000000008000000000000001"
"FFFFFFFFFFFFFFFE0000000000000000");
BN_sqr(c, a, ctx);
if (bp != NULL) {
if (!results) {
BN_print(bp, a);
BIO_puts(bp, " * ");
BN_print(bp, a);
BIO_puts(bp, " - ");
}
BN_print(bp, c);
BIO_puts(bp, "\n");
}
BN_mul(d, a, a, ctx);
if (BN_cmp(c, d)) {
fprintf(stderr, "Square test failed: BN_sqr and BN_mul produce "
"different results!\n");
goto err;
}
/* Regression test for a BN_sqr overflow bug. */
BN_hex2bn(&a,
"80000000000000000000000080000001"
"FFFFFFFE000000000000000000000000");
BN_sqr(c, a, ctx);
if (bp != NULL) {
if (!results) {
BN_print(bp, a);
BIO_puts(bp, " * ");
BN_print(bp, a);
BIO_puts(bp, " - ");
}
BN_print(bp, c);
BIO_puts(bp, "\n");
}
BN_mul(d, a, a, ctx);
if (BN_cmp(c, d)) {
fprintf(stderr, "Square test failed: BN_sqr and BN_mul produce "
"different results!\n");
goto err;
}
ret = 1;
err:
if (a != NULL)
BN_free(a);
if (c != NULL)
BN_free(c);
if (d != NULL)
BN_free(d);
if (e != NULL)
BN_free(e);
return ret;
}
int test_mont(BIO *bp, BN_CTX *ctx)
{
BIGNUM a, b, c, d, A, B;
BIGNUM n;
int i;
BN_MONT_CTX *mont;
BN_init(&a);
BN_init(&b);
BN_init(&c);
BN_init(&d);
BN_init(&A);
BN_init(&B);
BN_init(&n);
mont = BN_MONT_CTX_new();
if (mont == NULL)
return 0;
BN_zero(&n);
if (BN_MONT_CTX_set(mont, &n, ctx)) {
fprintf(stderr, "BN_MONT_CTX_set succeeded for zero modulus!\n");
return 0;
}
BN_set_word(&n, 16);
if (BN_MONT_CTX_set(mont, &n, ctx)) {
fprintf(stderr, "BN_MONT_CTX_set succeeded for even modulus!\n");
return 0;
}
BN_bntest_rand(&a, 100, 0, 0);
BN_bntest_rand(&b, 100, 0, 0);
for (i = 0; i < num2; i++) {
int bits = (200 * (i + 1)) / num2;
if (bits == 0)
continue;
BN_bntest_rand(&n, bits, 0, 1);
BN_MONT_CTX_set(mont, &n, ctx);
BN_nnmod(&a, &a, &n, ctx);
BN_nnmod(&b, &b, &n, ctx);
BN_to_montgomery(&A, &a, mont, ctx);
BN_to_montgomery(&B, &b, mont, ctx);
BN_mod_mul_montgomery(&c, &A, &B, mont, ctx);
BN_from_montgomery(&A, &c, mont, ctx);
if (bp != NULL) {
if (!results) {
#ifdef undef
fprintf(stderr, "%d * %d %% %d\n",
BN_num_bits(&a),
BN_num_bits(&b), BN_num_bits(mont->N));
#endif
BN_print(bp, &a);
BIO_puts(bp, " * ");
BN_print(bp, &b);
BIO_puts(bp, " % ");
BN_print(bp, &(mont->N));
BIO_puts(bp, " - ");
}
BN_print(bp, &A);
BIO_puts(bp, "\n");
}
BN_mod_mul(&d, &a, &b, &n, ctx);
BN_sub(&d, &d, &A);
if (!BN_is_zero(&d)) {
fprintf(stderr, "Montgomery multiplication test failed!\n");
return 0;
}
}
BN_MONT_CTX_free(mont);
BN_free(&a);
BN_free(&b);
BN_free(&c);
BN_free(&d);
BN_free(&A);
BN_free(&B);
BN_free(&n);
return (1);
}
int test_mod(BIO *bp, BN_CTX *ctx)
{
BIGNUM *a, *b, *c, *d, *e;
int i;
a = BN_new();
b = BN_new();
c = BN_new();
d = BN_new();
e = BN_new();
BN_bntest_rand(a, 1024, 0, 0);
for (i = 0; i < num0; i++) {
BN_bntest_rand(b, 450 + i * 10, 0, 0);
a->neg = rand_neg();
b->neg = rand_neg();
BN_mod(c, a, b, ctx);
if (bp != NULL) {
if (!results) {
BN_print(bp, a);
BIO_puts(bp, " % ");
BN_print(bp, b);
BIO_puts(bp, " - ");
}
BN_print(bp, c);
BIO_puts(bp, "\n");
}
BN_div(d, e, a, b, ctx);
BN_sub(e, e, c);
if (!BN_is_zero(e)) {
fprintf(stderr, "Modulo test failed!\n");
return 0;
}
}
BN_free(a);
BN_free(b);
BN_free(c);
BN_free(d);
BN_free(e);
return (1);
}
int test_mod_mul(BIO *bp, BN_CTX *ctx)
{
BIGNUM *a, *b, *c, *d, *e;
int i, j;
a = BN_new();
b = BN_new();
c = BN_new();
d = BN_new();
e = BN_new();
BN_one(a);
BN_one(b);
BN_zero(c);
if (BN_mod_mul(e, a, b, c, ctx)) {
fprintf(stderr, "BN_mod_mul with zero modulus succeeded!\n");
return 0;
}
for (j = 0; j < 3; j++) {
BN_bntest_rand(c, 1024, 0, 0);
for (i = 0; i < num0; i++) {
BN_bntest_rand(a, 475 + i * 10, 0, 0);
BN_bntest_rand(b, 425 + i * 11, 0, 0);
a->neg = rand_neg();
b->neg = rand_neg();
if (!BN_mod_mul(e, a, b, c, ctx)) {
unsigned long l;
while ((l = ERR_get_error()))
fprintf(stderr, "ERROR:%s\n", ERR_error_string(l, NULL));
EXIT(1);
}
if (bp != NULL) {
if (!results) {
BN_print(bp, a);
BIO_puts(bp, " * ");
BN_print(bp, b);
BIO_puts(bp, " % ");
BN_print(bp, c);
if ((a->neg ^ b->neg) && !BN_is_zero(e)) {
/*
* If (a*b) % c is negative, c must be added in order
* to obtain the normalized remainder (new with
* OpenSSL 0.9.7, previous versions of BN_mod_mul
* could generate negative results)
*/
BIO_puts(bp, " + ");
BN_print(bp, c);
}
BIO_puts(bp, " - ");
}
BN_print(bp, e);
BIO_puts(bp, "\n");
}
BN_mul(d, a, b, ctx);
BN_sub(d, d, e);
BN_div(a, b, d, c, ctx);
if (!BN_is_zero(b)) {
fprintf(stderr, "Modulo multiply test failed!\n");
ERR_print_errors_fp(stderr);
return 0;
}
}
}
BN_free(a);
BN_free(b);
BN_free(c);
BN_free(d);
BN_free(e);
return (1);
}
int test_mod_exp(BIO *bp, BN_CTX *ctx)
{
BIGNUM *a, *b, *c, *d, *e;
int i;
a = BN_new();
b = BN_new();
c = BN_new();
d = BN_new();
e = BN_new();
BN_one(a);
BN_one(b);
BN_zero(c);
if (BN_mod_exp(d, a, b, c, ctx)) {
fprintf(stderr, "BN_mod_exp with zero modulus succeeded!\n");
return 0;
}
BN_bntest_rand(c, 30, 0, 1); /* must be odd for montgomery */
for (i = 0; i < num2; i++) {
BN_bntest_rand(a, 20 + i * 5, 0, 0);
BN_bntest_rand(b, 2 + i, 0, 0);
if (!BN_mod_exp(d, a, b, c, ctx))
return (0);
if (bp != NULL) {
if (!results) {
BN_print(bp, a);
BIO_puts(bp, " ^ ");
BN_print(bp, b);
BIO_puts(bp, " % ");
BN_print(bp, c);
BIO_puts(bp, " - ");
}
BN_print(bp, d);
BIO_puts(bp, "\n");
}
BN_exp(e, a, b, ctx);
BN_sub(e, e, d);
BN_div(a, b, e, c, ctx);
if (!BN_is_zero(b)) {
fprintf(stderr, "Modulo exponentiation test failed!\n");
return 0;
}
}
/* Regression test for carry propagation bug in sqr8x_reduction */
BN_hex2bn(&a, "050505050505");
BN_hex2bn(&b, "02");
BN_hex2bn(&c,
"4141414141414141414141274141414141414141414141414141414141414141"
"4141414141414141414141414141414141414141414141414141414141414141"
"4141414141414141414141800000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000001");
BN_mod_exp(d, a, b, c, ctx);
BN_mul(e, a, a, ctx);
if (BN_cmp(d, e)) {
fprintf(stderr, "BN_mod_exp and BN_mul produce different results!\n");
return 0;
}
BN_free(a);
BN_free(b);
BN_free(c);
BN_free(d);
BN_free(e);
return (1);
}
int test_mod_exp_mont_consttime(BIO *bp, BN_CTX *ctx)
{
BIGNUM *a, *b, *c, *d, *e;
int i;
a = BN_new();
b = BN_new();
c = BN_new();
d = BN_new();
e = BN_new();
BN_one(a);
BN_one(b);
BN_zero(c);
if (BN_mod_exp_mont_consttime(d, a, b, c, ctx, NULL)) {
fprintf(stderr, "BN_mod_exp_mont_consttime with zero modulus "
"succeeded\n");
return 0;
}
BN_set_word(c, 16);
if (BN_mod_exp_mont_consttime(d, a, b, c, ctx, NULL)) {
fprintf(stderr, "BN_mod_exp_mont_consttime with even modulus "
"succeeded\n");
return 0;
}
BN_bntest_rand(c, 30, 0, 1); /* must be odd for montgomery */
for (i = 0; i < num2; i++) {
BN_bntest_rand(a, 20 + i * 5, 0, 0);
BN_bntest_rand(b, 2 + i, 0, 0);
if (!BN_mod_exp_mont_consttime(d, a, b, c, ctx, NULL))
return (00);
if (bp != NULL) {
if (!results) {
BN_print(bp, a);
BIO_puts(bp, " ^ ");
BN_print(bp, b);
BIO_puts(bp, " % ");
BN_print(bp, c);
BIO_puts(bp, " - ");
}
BN_print(bp, d);
BIO_puts(bp, "\n");
}
BN_exp(e, a, b, ctx);
BN_sub(e, e, d);
BN_div(a, b, e, c, ctx);
if (!BN_is_zero(b)) {
fprintf(stderr, "Modulo exponentiation test failed!\n");
return 0;
}
}
BN_free(a);
BN_free(b);
BN_free(c);
BN_free(d);
BN_free(e);
return (1);
}
/*
* Test constant-time modular exponentiation with 1024-bit inputs, which on
* x86_64 cause a different code branch to be taken.
*/
int test_mod_exp_mont5(BIO *bp, BN_CTX *ctx)
{
BIGNUM *a, *p, *m, *d, *e;
BN_MONT_CTX *mont;
a = BN_new();
p = BN_new();
m = BN_new();
d = BN_new();
e = BN_new();
mont = BN_MONT_CTX_new();
BN_bntest_rand(m, 1024, 0, 1); /* must be odd for montgomery */
/* Zero exponent */
BN_bntest_rand(a, 1024, 0, 0);
BN_zero(p);
if (!BN_mod_exp_mont_consttime(d, a, p, m, ctx, NULL))
return 0;
if (!BN_is_one(d)) {
fprintf(stderr, "Modular exponentiation test failed!\n");
return 0;
}
/* Zero input */
BN_bntest_rand(p, 1024, 0, 0);
BN_zero(a);
if (!BN_mod_exp_mont_consttime(d, a, p, m, ctx, NULL))
return 0;
if (!BN_is_zero(d)) {
fprintf(stderr, "Modular exponentiation test failed!\n");
return 0;
}
/*
* Craft an input whose Montgomery representation is 1, i.e., shorter
* than the modulus m, in order to test the const time precomputation
* scattering/gathering.
*/
BN_one(a);
BN_MONT_CTX_set(mont, m, ctx);
if (!BN_from_montgomery(e, a, mont, ctx))
return 0;
if (!BN_mod_exp_mont_consttime(d, e, p, m, ctx, NULL))
return 0;
if (!BN_mod_exp_simple(a, e, p, m, ctx))
return 0;
if (BN_cmp(a, d) != 0) {
fprintf(stderr, "Modular exponentiation test failed!\n");
return 0;
}
/* Finally, some regular test vectors. */
BN_bntest_rand(e, 1024, 0, 0);
if (!BN_mod_exp_mont_consttime(d, e, p, m, ctx, NULL))
return 0;
if (!BN_mod_exp_simple(a, e, p, m, ctx))
return 0;
if (BN_cmp(a, d) != 0) {
fprintf(stderr, "Modular exponentiation test failed!\n");
return 0;
}
BN_MONT_CTX_free(mont);
BN_free(a);
BN_free(p);
BN_free(m);
BN_free(d);
BN_free(e);
return (1);
}
int test_exp(BIO *bp, BN_CTX *ctx)
{
BIGNUM *a, *b, *d, *e, *one;
int i;
a = BN_new();
b = BN_new();
d = BN_new();
e = BN_new();
one = BN_new();
BN_one(one);
for (i = 0; i < num2; i++) {
BN_bntest_rand(a, 20 + i * 5, 0, 0);
BN_bntest_rand(b, 2 + i, 0, 0);
if (BN_exp(d, a, b, ctx) <= 0)
return (0);
if (bp != NULL) {
if (!results) {
BN_print(bp, a);
BIO_puts(bp, " ^ ");
BN_print(bp, b);
BIO_puts(bp, " - ");
}
BN_print(bp, d);
BIO_puts(bp, "\n");
}
BN_one(e);
for (; !BN_is_zero(b); BN_sub(b, b, one))
BN_mul(e, e, a, ctx);
BN_sub(e, e, d);
if (!BN_is_zero(e)) {
fprintf(stderr, "Exponentiation test failed!\n");
return 0;
}
}
BN_free(a);
BN_free(b);
BN_free(d);
BN_free(e);
BN_free(one);
return (1);
}
#ifndef OPENSSL_NO_EC2M
int test_gf2m_add(BIO *bp)
{
BIGNUM a, b, c;
int i, ret = 0;
BN_init(&a);
BN_init(&b);
BN_init(&c);
for (i = 0; i < num0; i++) {
BN_rand(&a, 512, 0, 0);
BN_copy(&b, BN_value_one());
a.neg = rand_neg();
b.neg = rand_neg();
BN_GF2m_add(&c, &a, &b);
# if 0 /* make test uses ouput in bc but bc can't
* handle GF(2^m) arithmetic */
if (bp != NULL) {
if (!results) {
BN_print(bp, &a);
BIO_puts(bp, " ^ ");
BN_print(bp, &b);
BIO_puts(bp, " = ");
}
BN_print(bp, &c);
BIO_puts(bp, "\n");
}
# endif
/* Test that two added values have the correct parity. */
if ((BN_is_odd(&a) && BN_is_odd(&c))
|| (!BN_is_odd(&a) && !BN_is_odd(&c))) {
fprintf(stderr, "GF(2^m) addition test (a) failed!\n");
goto err;
}
BN_GF2m_add(&c, &c, &c);
/* Test that c + c = 0. */
if (!BN_is_zero(&c)) {
fprintf(stderr, "GF(2^m) addition test (b) failed!\n");
goto err;
}
}
ret = 1;
err:
BN_free(&a);
BN_free(&b);
BN_free(&c);
return ret;
}
int test_gf2m_mod(BIO *bp)
{
BIGNUM *a, *b[2], *c, *d, *e;
int i, j, ret = 0;
int p0[] = { 163, 7, 6, 3, 0, -1 };
int p1[] = { 193, 15, 0, -1 };
a = BN_new();
b[0] = BN_new();
b[1] = BN_new();
c = BN_new();
d = BN_new();
e = BN_new();
BN_GF2m_arr2poly(p0, b[0]);
BN_GF2m_arr2poly(p1, b[1]);
for (i = 0; i < num0; i++) {
BN_bntest_rand(a, 1024, 0, 0);
for (j = 0; j < 2; j++) {
BN_GF2m_mod(c, a, b[j]);
# if 0 /* make test uses ouput in bc but bc can't
* handle GF(2^m) arithmetic */
if (bp != NULL) {
if (!results) {
BN_print(bp, a);
BIO_puts(bp, " % ");
BN_print(bp, b[j]);
BIO_puts(bp, " - ");
BN_print(bp, c);
BIO_puts(bp, "\n");
}
}
# endif
BN_GF2m_add(d, a, c);
BN_GF2m_mod(e, d, b[j]);
/* Test that a + (a mod p) mod p == 0. */
if (!BN_is_zero(e)) {
fprintf(stderr, "GF(2^m) modulo test failed!\n");
goto err;
}
}
}
ret = 1;
err:
BN_free(a);
BN_free(b[0]);
BN_free(b[1]);
BN_free(c);
BN_free(d);
BN_free(e);
return ret;
}
int test_gf2m_mod_mul(BIO *bp, BN_CTX *ctx)
{
BIGNUM *a, *b[2], *c, *d, *e, *f, *g, *h;
int i, j, ret = 0;
int p0[] = { 163, 7, 6, 3, 0, -1 };
int p1[] = { 193, 15, 0, -1 };
a = BN_new();
b[0] = BN_new();
b[1] = BN_new();
c = BN_new();
d = BN_new();
e = BN_new();
f = BN_new();
g = BN_new();
h = BN_new();
BN_GF2m_arr2poly(p0, b[0]);
BN_GF2m_arr2poly(p1, b[1]);
for (i = 0; i < num0; i++) {
BN_bntest_rand(a, 1024, 0, 0);
BN_bntest_rand(c, 1024, 0, 0);
BN_bntest_rand(d, 1024, 0, 0);
for (j = 0; j < 2; j++) {
BN_GF2m_mod_mul(e, a, c, b[j], ctx);
# if 0 /* make test uses ouput in bc but bc can't
* handle GF(2^m) arithmetic */
if (bp != NULL) {
if (!results) {
BN_print(bp, a);
BIO_puts(bp, " * ");
BN_print(bp, c);
BIO_puts(bp, " % ");
BN_print(bp, b[j]);
BIO_puts(bp, " - ");
BN_print(bp, e);
BIO_puts(bp, "\n");
}
}
# endif
BN_GF2m_add(f, a, d);
BN_GF2m_mod_mul(g, f, c, b[j], ctx);
BN_GF2m_mod_mul(h, d, c, b[j], ctx);
BN_GF2m_add(f, e, g);
BN_GF2m_add(f, f, h);
/* Test that (a+d)*c = a*c + d*c. */
if (!BN_is_zero(f)) {
fprintf(stderr,
"GF(2^m) modular multiplication test failed!\n");
goto err;
}
}
}
ret = 1;
err:
BN_free(a);
BN_free(b[0]);
BN_free(b[1]);
BN_free(c);
BN_free(d);
BN_free(e);
BN_free(f);
BN_free(g);
BN_free(h);
return ret;
}
int test_gf2m_mod_sqr(BIO *bp, BN_CTX *ctx)
{
BIGNUM *a, *b[2], *c, *d;
int i, j, ret = 0;
int p0[] = { 163, 7, 6, 3, 0, -1 };
int p1[] = { 193, 15, 0, -1 };
a = BN_new();
b[0] = BN_new();
b[1] = BN_new();
c = BN_new();
d = BN_new();
BN_GF2m_arr2poly(p0, b[0]);
BN_GF2m_arr2poly(p1, b[1]);
for (i = 0; i < num0; i++) {
BN_bntest_rand(a, 1024, 0, 0);
for (j = 0; j < 2; j++) {
BN_GF2m_mod_sqr(c, a, b[j], ctx);
BN_copy(d, a);
BN_GF2m_mod_mul(d, a, d, b[j], ctx);
# if 0 /* make test uses ouput in bc but bc can't
* handle GF(2^m) arithmetic */
if (bp != NULL) {
if (!results) {
BN_print(bp, a);
BIO_puts(bp, " ^ 2 % ");
BN_print(bp, b[j]);
BIO_puts(bp, " = ");
BN_print(bp, c);
BIO_puts(bp, "; a * a = ");
BN_print(bp, d);
BIO_puts(bp, "\n");
}
}
# endif
BN_GF2m_add(d, c, d);
/* Test that a*a = a^2. */
if (!BN_is_zero(d)) {
fprintf(stderr, "GF(2^m) modular squaring test failed!\n");
goto err;
}
}
}
ret = 1;
err:
BN_free(a);
BN_free(b[0]);
BN_free(b[1]);
BN_free(c);
BN_free(d);
return ret;
}
int test_gf2m_mod_inv(BIO *bp, BN_CTX *ctx)
{
BIGNUM *a, *b[2], *c, *d;
int i, j, ret = 0;
int p0[] = { 163, 7, 6, 3, 0, -1 };
int p1[] = { 193, 15, 0, -1 };
a = BN_new();
b[0] = BN_new();
b[1] = BN_new();
c = BN_new();
d = BN_new();
BN_GF2m_arr2poly(p0, b[0]);
BN_GF2m_arr2poly(p1, b[1]);
for (i = 0; i < num0; i++) {
BN_bntest_rand(a, 512, 0, 0);
for (j = 0; j < 2; j++) {
BN_GF2m_mod_inv(c, a, b[j], ctx);
BN_GF2m_mod_mul(d, a, c, b[j], ctx);
# if 0 /* make test uses ouput in bc but bc can't
* handle GF(2^m) arithmetic */
if (bp != NULL) {
if (!results) {
BN_print(bp, a);
BIO_puts(bp, " * ");
BN_print(bp, c);
BIO_puts(bp, " - 1 % ");
BN_print(bp, b[j]);
BIO_puts(bp, "\n");
}
}
# endif
/* Test that ((1/a)*a) = 1. */
if (!BN_is_one(d)) {
fprintf(stderr, "GF(2^m) modular inversion test failed!\n");
goto err;
}
}
}
ret = 1;
err:
BN_free(a);
BN_free(b[0]);
BN_free(b[1]);
BN_free(c);
BN_free(d);
return ret;
}
int test_gf2m_mod_div(BIO *bp, BN_CTX *ctx)
{
BIGNUM *a, *b[2], *c, *d, *e, *f;
int i, j, ret = 0;
int p0[] = { 163, 7, 6, 3, 0, -1 };
int p1[] = { 193, 15, 0, -1 };
a = BN_new();
b[0] = BN_new();
b[1] = BN_new();
c = BN_new();
d = BN_new();
e = BN_new();
f = BN_new();
BN_GF2m_arr2poly(p0, b[0]);
BN_GF2m_arr2poly(p1, b[1]);
for (i = 0; i < num0; i++) {
BN_bntest_rand(a, 512, 0, 0);
BN_bntest_rand(c, 512, 0, 0);
for (j = 0; j < 2; j++) {
BN_GF2m_mod_div(d, a, c, b[j], ctx);
BN_GF2m_mod_mul(e, d, c, b[j], ctx);
BN_GF2m_mod_div(f, a, e, b[j], ctx);
# if 0 /* make test uses ouput in bc but bc can't
* handle GF(2^m) arithmetic */
if (bp != NULL) {
if (!results) {
BN_print(bp, a);
BIO_puts(bp, " = ");
BN_print(bp, c);
BIO_puts(bp, " * ");
BN_print(bp, d);
BIO_puts(bp, " % ");
BN_print(bp, b[j]);
BIO_puts(bp, "\n");
}
}
# endif
/* Test that ((a/c)*c)/a = 1. */
if (!BN_is_one(f)) {
fprintf(stderr, "GF(2^m) modular division test failed!\n");
goto err;
}
}
}
ret = 1;
err:
BN_free(a);
BN_free(b[0]);
BN_free(b[1]);
BN_free(c);
BN_free(d);
BN_free(e);
BN_free(f);
return ret;
}
int test_gf2m_mod_exp(BIO *bp, BN_CTX *ctx)
{
BIGNUM *a, *b[2], *c, *d, *e, *f;
int i, j, ret = 0;
int p0[] = { 163, 7, 6, 3, 0, -1 };
int p1[] = { 193, 15, 0, -1 };
a = BN_new();
b[0] = BN_new();
b[1] = BN_new();
c = BN_new();
d = BN_new();
e = BN_new();
f = BN_new();
BN_GF2m_arr2poly(p0, b[0]);
BN_GF2m_arr2poly(p1, b[1]);
for (i = 0; i < num0; i++) {
BN_bntest_rand(a, 512, 0, 0);
BN_bntest_rand(c, 512, 0, 0);
BN_bntest_rand(d, 512, 0, 0);
for (j = 0; j < 2; j++) {
BN_GF2m_mod_exp(e, a, c, b[j], ctx);
BN_GF2m_mod_exp(f, a, d, b[j], ctx);
BN_GF2m_mod_mul(e, e, f, b[j], ctx);
BN_add(f, c, d);
BN_GF2m_mod_exp(f, a, f, b[j], ctx);
# if 0 /* make test uses ouput in bc but bc can't
* handle GF(2^m) arithmetic */
if (bp != NULL) {
if (!results) {
BN_print(bp, a);
BIO_puts(bp, " ^ (");
BN_print(bp, c);
BIO_puts(bp, " + ");
BN_print(bp, d);
BIO_puts(bp, ") = ");
BN_print(bp, e);
BIO_puts(bp, "; - ");
BN_print(bp, f);
BIO_puts(bp, " % ");
BN_print(bp, b[j]);
BIO_puts(bp, "\n");
}
}
# endif
BN_GF2m_add(f, e, f);
/* Test that a^(c+d)=a^c*a^d. */
if (!BN_is_zero(f)) {
fprintf(stderr,
"GF(2^m) modular exponentiation test failed!\n");
goto err;
}
}
}
ret = 1;
err:
BN_free(a);
BN_free(b[0]);
BN_free(b[1]);
BN_free(c);
BN_free(d);
BN_free(e);
BN_free(f);
return ret;
}
int test_gf2m_mod_sqrt(BIO *bp, BN_CTX *ctx)
{
BIGNUM *a, *b[2], *c, *d, *e, *f;
int i, j, ret = 0;
int p0[] = { 163, 7, 6, 3, 0, -1 };
int p1[] = { 193, 15, 0, -1 };
a = BN_new();
b[0] = BN_new();
b[1] = BN_new();
c = BN_new();
d = BN_new();
e = BN_new();
f = BN_new();
BN_GF2m_arr2poly(p0, b[0]);
BN_GF2m_arr2poly(p1, b[1]);
for (i = 0; i < num0; i++) {
BN_bntest_rand(a, 512, 0, 0);
for (j = 0; j < 2; j++) {
BN_GF2m_mod(c, a, b[j]);
BN_GF2m_mod_sqrt(d, a, b[j], ctx);
BN_GF2m_mod_sqr(e, d, b[j], ctx);
# if 0 /* make test uses ouput in bc but bc can't
* handle GF(2^m) arithmetic */
if (bp != NULL) {
if (!results) {
BN_print(bp, d);
BIO_puts(bp, " ^ 2 - ");
BN_print(bp, a);
BIO_puts(bp, "\n");
}
}
# endif
BN_GF2m_add(f, c, e);
/* Test that d^2 = a, where d = sqrt(a). */
if (!BN_is_zero(f)) {
fprintf(stderr, "GF(2^m) modular square root test failed!\n");
goto err;
}
}
}
ret = 1;
err:
BN_free(a);
BN_free(b[0]);
BN_free(b[1]);
BN_free(c);
BN_free(d);
BN_free(e);
BN_free(f);
return ret;
}
int test_gf2m_mod_solve_quad(BIO *bp, BN_CTX *ctx)
{
BIGNUM *a, *b[2], *c, *d, *e;
int i, j, s = 0, t, ret = 0;
int p0[] = { 163, 7, 6, 3, 0, -1 };
int p1[] = { 193, 15, 0, -1 };
a = BN_new();
b[0] = BN_new();
b[1] = BN_new();
c = BN_new();
d = BN_new();
e = BN_new();
BN_GF2m_arr2poly(p0, b[0]);
BN_GF2m_arr2poly(p1, b[1]);
for (i = 0; i < num0; i++) {
BN_bntest_rand(a, 512, 0, 0);
for (j = 0; j < 2; j++) {
t = BN_GF2m_mod_solve_quad(c, a, b[j], ctx);
if (t) {
s++;
BN_GF2m_mod_sqr(d, c, b[j], ctx);
BN_GF2m_add(d, c, d);
BN_GF2m_mod(e, a, b[j]);
# if 0 /* make test uses ouput in bc but bc can't
* handle GF(2^m) arithmetic */
if (bp != NULL) {
if (!results) {
BN_print(bp, c);
BIO_puts(bp, " is root of z^2 + z = ");
BN_print(bp, a);
BIO_puts(bp, " % ");
BN_print(bp, b[j]);
BIO_puts(bp, "\n");
}
}
# endif
BN_GF2m_add(e, e, d);
/*
* Test that solution of quadratic c satisfies c^2 + c = a.
*/
if (!BN_is_zero(e)) {
fprintf(stderr,
"GF(2^m) modular solve quadratic test failed!\n");
goto err;
}
} else {
# if 0 /* make test uses ouput in bc but bc can't
* handle GF(2^m) arithmetic */
if (bp != NULL) {
if (!results) {
BIO_puts(bp, "There are no roots of z^2 + z = ");
BN_print(bp, a);
BIO_puts(bp, " % ");
BN_print(bp, b[j]);
BIO_puts(bp, "\n");
}
}
# endif
}
}
}
if (s == 0) {
fprintf(stderr,
"All %i tests of GF(2^m) modular solve quadratic resulted in no roots;\n",
num0);
fprintf(stderr,
"this is very unlikely and probably indicates an error.\n");
goto err;
}
ret = 1;
err:
BN_free(a);
BN_free(b[0]);
BN_free(b[1]);
BN_free(c);
BN_free(d);
BN_free(e);
return ret;
}
#endif
static int genprime_cb(int p, int n, BN_GENCB *arg)
{
char c = '*';
if (p == 0)
c = '.';
if (p == 1)
c = '+';
if (p == 2)
c = '*';
if (p == 3)
c = '\n';
putc(c, stderr);
fflush(stderr);
return 1;
}
int test_kron(BIO *bp, BN_CTX *ctx)
{
BN_GENCB cb;
BIGNUM *a, *b, *r, *t;
int i;
int legendre, kronecker;
int ret = 0;
a = BN_new();
b = BN_new();
r = BN_new();
t = BN_new();
if (a == NULL || b == NULL || r == NULL || t == NULL)
goto err;
BN_GENCB_set(&cb, genprime_cb, NULL);
/*
* We test BN_kronecker(a, b, ctx) just for b odd (Jacobi symbol). In
* this case we know that if b is prime, then BN_kronecker(a, b, ctx) is
* congruent to $a^{(b-1)/2}$, modulo $b$ (Legendre symbol). So we
* generate a random prime b and compare these values for a number of
* random a's. (That is, we run the Solovay-Strassen primality test to
* confirm that b is prime, except that we don't want to test whether b
* is prime but whether BN_kronecker works.)
*/
if (!BN_generate_prime_ex(b, 512, 0, NULL, NULL, &cb))
goto err;
b->neg = rand_neg();
putc('\n', stderr);
for (i = 0; i < num0; i++) {
if (!BN_bntest_rand(a, 512, 0, 0))
goto err;
a->neg = rand_neg();
/* t := (|b|-1)/2 (note that b is odd) */
if (!BN_copy(t, b))
goto err;
t->neg = 0;
if (!BN_sub_word(t, 1))
goto err;
if (!BN_rshift1(t, t))
goto err;
/* r := a^t mod b */
b->neg = 0;
if (!BN_mod_exp_recp(r, a, t, b, ctx))
goto err;
b->neg = 1;
if (BN_is_word(r, 1))
legendre = 1;
else if (BN_is_zero(r))
legendre = 0;
else {
if (!BN_add_word(r, 1))
goto err;
if (0 != BN_ucmp(r, b)) {
fprintf(stderr, "Legendre symbol computation failed\n");
goto err;
}
legendre = -1;
}
kronecker = BN_kronecker(a, b, ctx);
if (kronecker < -1)
goto err;
/* we actually need BN_kronecker(a, |b|) */
if (a->neg && b->neg)
kronecker = -kronecker;
if (legendre != kronecker) {
fprintf(stderr, "legendre != kronecker; a = ");
BN_print_fp(stderr, a);
fprintf(stderr, ", b = ");
BN_print_fp(stderr, b);
fprintf(stderr, "\n");
goto err;
}
putc('.', stderr);
fflush(stderr);
}
putc('\n', stderr);
fflush(stderr);
ret = 1;
err:
if (a != NULL)
BN_free(a);
if (b != NULL)
BN_free(b);
if (r != NULL)
BN_free(r);
if (t != NULL)
BN_free(t);
return ret;
}
int test_sqrt(BIO *bp, BN_CTX *ctx)
{
BN_GENCB cb;
BIGNUM *a, *p, *r;
int i, j;
int ret = 0;
a = BN_new();
p = BN_new();
r = BN_new();
if (a == NULL || p == NULL || r == NULL)
goto err;
BN_GENCB_set(&cb, genprime_cb, NULL);
for (i = 0; i < 16; i++) {
if (i < 8) {
unsigned primes[8] = { 2, 3, 5, 7, 11, 13, 17, 19 };
if (!BN_set_word(p, primes[i]))
goto err;
} else {
if (!BN_set_word(a, 32))
goto err;
if (!BN_set_word(r, 2 * i + 1))
goto err;
if (!BN_generate_prime_ex(p, 256, 0, a, r, &cb))
goto err;
putc('\n', stderr);
}
p->neg = rand_neg();
for (j = 0; j < num2; j++) {
/*
* construct 'a' such that it is a square modulo p, but in
* general not a proper square and not reduced modulo p
*/
if (!BN_bntest_rand(r, 256, 0, 3))
goto err;
if (!BN_nnmod(r, r, p, ctx))
goto err;
if (!BN_mod_sqr(r, r, p, ctx))
goto err;
if (!BN_bntest_rand(a, 256, 0, 3))
goto err;
if (!BN_nnmod(a, a, p, ctx))
goto err;
if (!BN_mod_sqr(a, a, p, ctx))
goto err;
if (!BN_mul(a, a, r, ctx))
goto err;
if (rand_neg())
if (!BN_sub(a, a, p))
goto err;
if (!BN_mod_sqrt(r, a, p, ctx))
goto err;
if (!BN_mod_sqr(r, r, p, ctx))
goto err;
if (!BN_nnmod(a, a, p, ctx))
goto err;
if (BN_cmp(a, r) != 0) {
fprintf(stderr, "BN_mod_sqrt failed: a = ");
BN_print_fp(stderr, a);
fprintf(stderr, ", r = ");
BN_print_fp(stderr, r);
fprintf(stderr, ", p = ");
BN_print_fp(stderr, p);
fprintf(stderr, "\n");
goto err;
}
putc('.', stderr);
fflush(stderr);
}
putc('\n', stderr);
fflush(stderr);
}
ret = 1;
err:
if (a != NULL)
BN_free(a);
if (p != NULL)
BN_free(p);
if (r != NULL)
BN_free(r);
return ret;
}
int test_lshift(BIO *bp, BN_CTX *ctx, BIGNUM *a_)
{
BIGNUM *a, *b, *c, *d;
int i;
b = BN_new();
c = BN_new();
d = BN_new();
BN_one(c);
if (a_)
a = a_;
else {
a = BN_new();
BN_bntest_rand(a, 200, 0, 0);
a->neg = rand_neg();
}
for (i = 0; i < num0; i++) {
BN_lshift(b, a, i + 1);
BN_add(c, c, c);
if (bp != NULL) {
if (!results) {
BN_print(bp, a);
BIO_puts(bp, " * ");
BN_print(bp, c);
BIO_puts(bp, " - ");
}
BN_print(bp, b);
BIO_puts(bp, "\n");
}
BN_mul(d, a, c, ctx);
BN_sub(d, d, b);
if (!BN_is_zero(d)) {
fprintf(stderr, "Left shift test failed!\n");
fprintf(stderr, "a=");
BN_print_fp(stderr, a);
fprintf(stderr, "\nb=");
BN_print_fp(stderr, b);
fprintf(stderr, "\nc=");
BN_print_fp(stderr, c);
fprintf(stderr, "\nd=");
BN_print_fp(stderr, d);
fprintf(stderr, "\n");
return 0;
}
}
BN_free(a);
BN_free(b);
BN_free(c);
BN_free(d);
return (1);
}
int test_lshift1(BIO *bp)
{
BIGNUM *a, *b, *c;
int i;
a = BN_new();
b = BN_new();
c = BN_new();
BN_bntest_rand(a, 200, 0, 0);
a->neg = rand_neg();
for (i = 0; i < num0; i++) {
BN_lshift1(b, a);
if (bp != NULL) {
if (!results) {
BN_print(bp, a);
BIO_puts(bp, " * 2");
BIO_puts(bp, " - ");
}
BN_print(bp, b);
BIO_puts(bp, "\n");
}
BN_add(c, a, a);
BN_sub(a, b, c);
if (!BN_is_zero(a)) {
fprintf(stderr, "Left shift one test failed!\n");
return 0;
}
BN_copy(a, b);
}
BN_free(a);
BN_free(b);
BN_free(c);
return (1);
}
int test_rshift(BIO *bp, BN_CTX *ctx)
{
BIGNUM *a, *b, *c, *d, *e;
int i;
a = BN_new();
b = BN_new();
c = BN_new();
d = BN_new();
e = BN_new();
BN_one(c);
BN_bntest_rand(a, 200, 0, 0);
a->neg = rand_neg();
for (i = 0; i < num0; i++) {
BN_rshift(b, a, i + 1);
BN_add(c, c, c);
if (bp != NULL) {
if (!results) {
BN_print(bp, a);
BIO_puts(bp, " / ");
BN_print(bp, c);
BIO_puts(bp, " - ");
}
BN_print(bp, b);
BIO_puts(bp, "\n");
}
BN_div(d, e, a, c, ctx);
BN_sub(d, d, b);
if (!BN_is_zero(d)) {
fprintf(stderr, "Right shift test failed!\n");
return 0;
}
}
BN_free(a);
BN_free(b);
BN_free(c);
BN_free(d);
BN_free(e);
return (1);
}
int test_rshift1(BIO *bp)
{
BIGNUM *a, *b, *c;
int i;
a = BN_new();
b = BN_new();
c = BN_new();
BN_bntest_rand(a, 200, 0, 0);
a->neg = rand_neg();
for (i = 0; i < num0; i++) {
BN_rshift1(b, a);
if (bp != NULL) {
if (!results) {
BN_print(bp, a);
BIO_puts(bp, " / 2");
BIO_puts(bp, " - ");
}
BN_print(bp, b);
BIO_puts(bp, "\n");
}
BN_sub(c, a, b);
BN_sub(c, c, b);
if (!BN_is_zero(c) && !BN_abs_is_word(c, 1)) {
fprintf(stderr, "Right shift one test failed!\n");
return 0;
}
BN_copy(a, b);
}
BN_free(a);
BN_free(b);
BN_free(c);
return (1);
}
int rand_neg(void)
{
static unsigned int neg = 0;
static int sign[8] = { 0, 0, 0, 1, 1, 0, 1, 1 };
return (sign[(neg++) % 8]);
}
diff --git a/crypto/bn/expspeed.c b/crypto/bn/expspeed.c
index 513a568a481f..8ea980cdd201 100644
--- a/crypto/bn/expspeed.c
+++ b/crypto/bn/expspeed.c
@@ -1,381 +1,381 @@
/* unused */
/* crypto/bn/expspeed.c */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
/* most of this code has been pilfered from my libdes speed.c program */
#define BASENUM 5000
#define NUM_START 0
/*
* determine timings for modexp, modmul, modsqr, gcd, Kronecker symbol,
* modular inverse, or modular square roots
*/
#define TEST_EXP
#undef TEST_MUL
#undef TEST_SQR
#undef TEST_GCD
#undef TEST_KRON
#undef TEST_INV
#undef TEST_SQRT
#define P_MOD_64 9 /* least significant 6 bits for prime to be
* used for BN_sqrt timings */
#if defined(TEST_EXP) + defined(TEST_MUL) + defined(TEST_SQR) + defined(TEST_GCD) + defined(TEST_KRON) + defined(TEST_INV) +defined(TEST_SQRT) != 1
# error "choose one test"
#endif
#if defined(TEST_INV) || defined(TEST_SQRT)
# define C_PRIME
static void genprime_cb(int p, int n, void *arg);
#endif
#undef PROG
#define PROG bnspeed_main
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <string.h>
#include <openssl/crypto.h>
#include <openssl/err.h>
#include <openssl/rand.h>
#if !defined(OPENSSL_SYS_MSDOS) && (!defined(OPENSSL_SYS_VMS) || defined(__DECC)) && !defined(OPENSSL_SYS_MACOSX)
# define TIMES
#endif
#ifndef _IRIX
# include <time.h>
#endif
#ifdef TIMES
# include <sys/types.h>
# include <sys/times.h>
#endif
/*
* Depending on the VMS version, the tms structure is perhaps defined. The
* __TMS macro will show if it was. If it wasn't defined, we should undefine
* TIMES, since that tells the rest of the program how things should be
* handled. -- Richard Levitte
*/
#if defined(OPENSSL_SYS_VMS_DECC) && !defined(__TMS)
# undef TIMES
#endif
#ifndef TIMES
# include <sys/timeb.h>
#endif
#if defined(sun) || defined(__ultrix)
# define _POSIX_SOURCE
# include <limits.h>
# include <sys/param.h>
#endif
#include <openssl/bn.h>
#include <openssl/x509.h>
/* The following if from times(3) man page. It may need to be changed */
#ifndef HZ
# ifndef CLK_TCK
# ifndef _BSD_CLK_TCK_ /* FreeBSD hack */
# define HZ 100.0
# else /* _BSD_CLK_TCK_ */
# define HZ ((double)_BSD_CLK_TCK_)
# endif
# else /* CLK_TCK */
# define HZ ((double)CLK_TCK)
# endif
#endif
#undef BUFSIZE
#define BUFSIZE ((long)1024*8)
int run = 0;
static double Time_F(int s);
#define START 0
#define STOP 1
static double Time_F(int s)
{
double ret;
#ifdef TIMES
static struct tms tstart, tend;
if (s == START) {
times(&tstart);
return (0);
} else {
times(&tend);
ret = ((double)(tend.tms_utime - tstart.tms_utime)) / HZ;
return ((ret < 1e-3) ? 1e-3 : ret);
}
#else /* !times() */
static struct timeb tstart, tend;
long i;
if (s == START) {
ftime(&tstart);
return (0);
} else {
ftime(&tend);
i = (long)tend.millitm - (long)tstart.millitm;
ret = ((double)(tend.time - tstart.time)) + ((double)i) / 1000.0;
return ((ret < 0.001) ? 0.001 : ret);
}
#endif
}
#define NUM_SIZES 7
#if NUM_START > NUM_SIZES
# error "NUM_START > NUM_SIZES"
#endif
static int sizes[NUM_SIZES] = { 128, 256, 512, 1024, 2048, 4096, 8192 };
static int mul_c[NUM_SIZES] =
{ 8 * 8 * 8 * 8 * 8 * 8, 8 * 8 * 8 * 8 * 8, 8 * 8 * 8 * 8, 8 * 8 * 8,
8 * 8, 8, 1
};
/*
* static int sizes[NUM_SIZES]={59,179,299,419,539};
*/
-#define RAND_SEED(string) { const char str[] = string; RAND_seed(string, sizeof str); }
+#define RAND_SEED(string) { const char str[] = string; RAND_seed(string, sizeof(str)); }
void do_mul_exp(BIGNUM *r, BIGNUM *a, BIGNUM *b, BIGNUM *c, BN_CTX *ctx);
int main(int argc, char **argv)
{
BN_CTX *ctx;
BIGNUM *a, *b, *c, *r;
#if 1
if (!CRYPTO_set_mem_debug_functions(0, 0, 0, 0, 0))
abort();
#endif
ctx = BN_CTX_new();
a = BN_new();
b = BN_new();
c = BN_new();
r = BN_new();
while (!RAND_status())
/* not enough bits */
RAND_SEED("I demand a manual recount!");
do_mul_exp(r, a, b, c, ctx);
return 0;
}
void do_mul_exp(BIGNUM *r, BIGNUM *a, BIGNUM *b, BIGNUM *c, BN_CTX *ctx)
{
int i, k;
double tm;
long num;
num = BASENUM;
for (i = NUM_START; i < NUM_SIZES; i++) {
#ifdef C_PRIME
# ifdef TEST_SQRT
if (!BN_set_word(a, 64))
goto err;
if (!BN_set_word(b, P_MOD_64))
goto err;
# define ADD a
# define REM b
# else
# define ADD NULL
# define REM NULL
# endif
if (!BN_generate_prime(c, sizes[i], 0, ADD, REM, genprime_cb, NULL))
goto err;
putc('\n', stderr);
fflush(stderr);
#endif
for (k = 0; k < num; k++) {
if (k % 50 == 0) { /* Average over num/50 different choices of
* random numbers. */
if (!BN_pseudo_rand(a, sizes[i], 1, 0))
goto err;
if (!BN_pseudo_rand(b, sizes[i], 1, 0))
goto err;
#ifndef C_PRIME
if (!BN_pseudo_rand(c, sizes[i], 1, 1))
goto err;
#endif
#ifdef TEST_SQRT
if (!BN_mod_sqr(a, a, c, ctx))
goto err;
if (!BN_mod_sqr(b, b, c, ctx))
goto err;
#else
if (!BN_nnmod(a, a, c, ctx))
goto err;
if (!BN_nnmod(b, b, c, ctx))
goto err;
#endif
if (k == 0)
Time_F(START);
}
#if defined(TEST_EXP)
if (!BN_mod_exp(r, a, b, c, ctx))
goto err;
#elif defined(TEST_MUL)
{
int i = 0;
for (i = 0; i < 50; i++)
if (!BN_mod_mul(r, a, b, c, ctx))
goto err;
}
#elif defined(TEST_SQR)
{
int i = 0;
for (i = 0; i < 50; i++) {
if (!BN_mod_sqr(r, a, c, ctx))
goto err;
if (!BN_mod_sqr(r, b, c, ctx))
goto err;
}
}
#elif defined(TEST_GCD)
if (!BN_gcd(r, a, b, ctx))
goto err;
if (!BN_gcd(r, b, c, ctx))
goto err;
if (!BN_gcd(r, c, a, ctx))
goto err;
#elif defined(TEST_KRON)
if (-2 == BN_kronecker(a, b, ctx))
goto err;
if (-2 == BN_kronecker(b, c, ctx))
goto err;
if (-2 == BN_kronecker(c, a, ctx))
goto err;
#elif defined(TEST_INV)
if (!BN_mod_inverse(r, a, c, ctx))
goto err;
if (!BN_mod_inverse(r, b, c, ctx))
goto err;
#else /* TEST_SQRT */
if (!BN_mod_sqrt(r, a, c, ctx))
goto err;
if (!BN_mod_sqrt(r, b, c, ctx))
goto err;
#endif
}
tm = Time_F(STOP);
printf(
#if defined(TEST_EXP)
"modexp %4d ^ %4d %% %4d"
#elif defined(TEST_MUL)
"50*modmul %4d %4d %4d"
#elif defined(TEST_SQR)
"100*modsqr %4d %4d %4d"
#elif defined(TEST_GCD)
"3*gcd %4d %4d %4d"
#elif defined(TEST_KRON)
"3*kronecker %4d %4d %4d"
#elif defined(TEST_INV)
"2*inv %4d %4d mod %4d"
#else /* TEST_SQRT */
"2*sqrt [prime == %d (mod 64)] %4d %4d mod %4d"
#endif
" -> %8.6fms %5.1f (%ld)\n",
#ifdef TEST_SQRT
P_MOD_64,
#endif
sizes[i], sizes[i], sizes[i], tm * 1000.0 / num,
tm * mul_c[i] / num, num);
num /= 7;
if (num <= 0)
num = 1;
}
return;
err:
ERR_print_errors_fp(stderr);
}
#ifdef C_PRIME
static void genprime_cb(int p, int n, void *arg)
{
char c = '*';
if (p == 0)
c = '.';
if (p == 1)
c = '+';
if (p == 2)
c = '*';
if (p == 3)
c = '\n';
putc(c, stderr);
fflush(stderr);
(void)n;
(void)arg;
}
#endif
diff --git a/crypto/bn/exptest.c b/crypto/bn/exptest.c
index ac611c2e2614..779ee902036c 100644
--- a/crypto/bn/exptest.c
+++ b/crypto/bn/exptest.c
@@ -1,313 +1,315 @@
/* crypto/bn/exptest.c */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "../e_os.h"
#include <openssl/bio.h>
#include <openssl/bn.h>
#include <openssl/rand.h>
#include <openssl/err.h>
#define NUM_BITS (BN_BITS*2)
static const char rnd_seed[] =
"string to make the random number generator think it has entropy";
/*
* Test that r == 0 in test_exp_mod_zero(). Returns one on success,
* returns zero and prints debug output otherwise.
*/
static int a_is_zero_mod_one(const char *method, const BIGNUM *r,
const BIGNUM *a) {
if (!BN_is_zero(r)) {
fprintf(stderr, "%s failed:\n", method);
fprintf(stderr, "a ** 0 mod 1 = r (should be 0)\n");
fprintf(stderr, "a = ");
BN_print_fp(stderr, a);
fprintf(stderr, "\nr = ");
BN_print_fp(stderr, r);
fprintf(stderr, "\n");
return 0;
}
return 1;
}
/*
* test_exp_mod_zero tests that x**0 mod 1 == 0. It returns zero on success.
*/
static int test_exp_mod_zero()
{
BIGNUM a, p, m;
BIGNUM r;
BN_ULONG one_word = 1;
BN_CTX *ctx = BN_CTX_new();
int ret = 1, failed = 0;
BN_init(&m);
BN_one(&m);
BN_init(&a);
BN_one(&a);
BN_init(&p);
BN_zero(&p);
BN_init(&r);
if (!BN_rand(&a, 1024, 0, 0))
goto err;
if (!BN_mod_exp(&r, &a, &p, &m, ctx))
goto err;
if (!a_is_zero_mod_one("BN_mod_exp", &r, &a))
failed = 1;
if (!BN_mod_exp_recp(&r, &a, &p, &m, ctx))
goto err;
if (!a_is_zero_mod_one("BN_mod_exp_recp", &r, &a))
failed = 1;
if (!BN_mod_exp_simple(&r, &a, &p, &m, ctx))
goto err;
if (!a_is_zero_mod_one("BN_mod_exp_simple", &r, &a))
failed = 1;
if (!BN_mod_exp_mont(&r, &a, &p, &m, ctx, NULL))
goto err;
if (!a_is_zero_mod_one("BN_mod_exp_mont", &r, &a))
failed = 1;
if (!BN_mod_exp_mont_consttime(&r, &a, &p, &m, ctx, NULL)) {
goto err;
}
if (!a_is_zero_mod_one("BN_mod_exp_mont_consttime", &r, &a))
failed = 1;
/*
* A different codepath exists for single word multiplication
* in non-constant-time only.
*/
if (!BN_mod_exp_mont_word(&r, one_word, &p, &m, ctx, NULL))
goto err;
if (!BN_is_zero(&r)) {
fprintf(stderr, "BN_mod_exp_mont_word failed:\n");
fprintf(stderr, "1 ** 0 mod 1 = r (should be 0)\n");
fprintf(stderr, "r = ");
BN_print_fp(stderr, &r);
fprintf(stderr, "\n");
return 0;
}
ret = failed;
err:
BN_free(&r);
BN_free(&a);
BN_free(&p);
BN_free(&m);
BN_CTX_free(ctx);
return ret;
}
int main(int argc, char *argv[])
{
BN_CTX *ctx;
BIO *out = NULL;
int i, ret;
unsigned char c;
BIGNUM *r_mont, *r_mont_const, *r_recp, *r_simple, *a, *b, *m;
- RAND_seed(rnd_seed, sizeof rnd_seed); /* or BN_rand may fail, and we
- * don't even check its return
- * value (which we should) */
+ /*
+ * Seed or BN_rand may fail, and we don't even check its return
+ * value (which we should)
+ */
+ RAND_seed(rnd_seed, sizeof(rnd_seed));
ERR_load_BN_strings();
ctx = BN_CTX_new();
if (ctx == NULL)
EXIT(1);
r_mont = BN_new();
r_mont_const = BN_new();
r_recp = BN_new();
r_simple = BN_new();
a = BN_new();
b = BN_new();
m = BN_new();
if ((r_mont == NULL) || (r_recp == NULL) || (a == NULL) || (b == NULL))
goto err;
out = BIO_new(BIO_s_file());
if (out == NULL)
EXIT(1);
BIO_set_fp(out, stdout, BIO_NOCLOSE);
for (i = 0; i < 200; i++) {
RAND_bytes(&c, 1);
c = (c % BN_BITS) - BN_BITS2;
BN_rand(a, NUM_BITS + c, 0, 0);
RAND_bytes(&c, 1);
c = (c % BN_BITS) - BN_BITS2;
BN_rand(b, NUM_BITS + c, 0, 0);
RAND_bytes(&c, 1);
c = (c % BN_BITS) - BN_BITS2;
BN_rand(m, NUM_BITS + c, 0, 1);
BN_mod(a, a, m, ctx);
BN_mod(b, b, m, ctx);
ret = BN_mod_exp_mont(r_mont, a, b, m, ctx, NULL);
if (ret <= 0) {
printf("BN_mod_exp_mont() problems\n");
ERR_print_errors(out);
EXIT(1);
}
ret = BN_mod_exp_recp(r_recp, a, b, m, ctx);
if (ret <= 0) {
printf("BN_mod_exp_recp() problems\n");
ERR_print_errors(out);
EXIT(1);
}
ret = BN_mod_exp_simple(r_simple, a, b, m, ctx);
if (ret <= 0) {
printf("BN_mod_exp_simple() problems\n");
ERR_print_errors(out);
EXIT(1);
}
ret = BN_mod_exp_mont_consttime(r_mont_const, a, b, m, ctx, NULL);
if (ret <= 0) {
printf("BN_mod_exp_mont_consttime() problems\n");
ERR_print_errors(out);
EXIT(1);
}
if (BN_cmp(r_simple, r_mont) == 0
&& BN_cmp(r_simple, r_recp) == 0
&& BN_cmp(r_simple, r_mont_const) == 0) {
printf(".");
fflush(stdout);
} else {
if (BN_cmp(r_simple, r_mont) != 0)
printf("\nsimple and mont results differ\n");
if (BN_cmp(r_simple, r_mont_const) != 0)
printf("\nsimple and mont const time results differ\n");
if (BN_cmp(r_simple, r_recp) != 0)
printf("\nsimple and recp results differ\n");
printf("a (%3d) = ", BN_num_bits(a));
BN_print(out, a);
printf("\nb (%3d) = ", BN_num_bits(b));
BN_print(out, b);
printf("\nm (%3d) = ", BN_num_bits(m));
BN_print(out, m);
printf("\nsimple =");
BN_print(out, r_simple);
printf("\nrecp =");
BN_print(out, r_recp);
printf("\nmont =");
BN_print(out, r_mont);
printf("\nmont_ct =");
BN_print(out, r_mont_const);
printf("\n");
EXIT(1);
}
}
BN_free(r_mont);
BN_free(r_mont_const);
BN_free(r_recp);
BN_free(r_simple);
BN_free(a);
BN_free(b);
BN_free(m);
BN_CTX_free(ctx);
ERR_remove_thread_state(NULL);
CRYPTO_mem_leaks(out);
BIO_free(out);
printf("\n");
if (test_exp_mod_zero() != 0)
goto err;
printf("done\n");
EXIT(0);
err:
ERR_load_crypto_strings();
ERR_print_errors(out);
#ifdef OPENSSL_SYS_NETWARE
printf("ERROR\n");
#endif
EXIT(1);
return (1);
}
diff --git a/crypto/conf/conf_def.c b/crypto/conf/conf_def.c
index 75e309aaca81..6237f6a1b6a9 100644
--- a/crypto/conf/conf_def.c
+++ b/crypto/conf/conf_def.c
@@ -1,718 +1,718 @@
/* crypto/conf/conf.c */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
/* Part of the code in here was originally in conf.c, which is now removed */
#include <stdio.h>
#include <string.h>
#include "cryptlib.h"
#include <openssl/stack.h>
#include <openssl/lhash.h>
#include <openssl/conf.h>
#include <openssl/conf_api.h>
#include "conf_def.h"
#include <openssl/buffer.h>
#include <openssl/err.h>
/*
* 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 char *eat_ws(CONF *conf, char *p);
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)))
static CONF *def_create(CONF_METHOD *meth);
static int def_init_default(CONF *conf);
static int def_init_WIN32(CONF *conf);
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);
const char CONF_def_version[] = "CONF_def" OPENSSL_VERSION_PTEXT;
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
};
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_default()
{
return &default_method;
}
CONF_METHOD *NCONF_WIN32()
{
return &WIN32_method;
}
static CONF *def_create(CONF_METHOD *meth)
{
CONF *ret;
ret = OPENSSL_malloc(sizeof(CONF) + sizeof(unsigned short *));
if (ret)
if (meth->init(ret) == 0) {
OPENSSL_free(ret);
ret = NULL;
}
return ret;
}
static int def_init_default(CONF *conf)
{
if (conf == NULL)
return 0;
conf->meth = &default_method;
conf->meth_data = CONF_type_default;
conf->data = NULL;
return 1;
}
static int def_init_WIN32(CONF *conf)
{
if (conf == NULL)
return 0;
conf->meth = &WIN32_method;
conf->meth_data = (void *)CONF_type_win32;
conf->data = NULL;
return 1;
}
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)
CONFerr(CONF_F_DEF_LOAD, CONF_R_NO_SUCH_FILE);
else
CONFerr(CONF_F_DEF_LOAD, ERR_R_SYS_LIB);
return 0;
}
ret = def_load_bio(conf, in, line);
BIO_free(in);
return ret;
}
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;
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);
if ((buff = BUF_MEM_new()) == NULL) {
CONFerr(CONF_F_DEF_LOAD_BIO, ERR_R_BUF_LIB);
goto err;
}
section = BUF_strdup("default");
if (section == NULL) {
CONFerr(CONF_F_DEF_LOAD_BIO, ERR_R_MALLOC_FAILURE);
goto err;
}
if (_CONF_new_data(conf) == 0) {
CONFerr(CONF_F_DEF_LOAD_BIO, ERR_R_MALLOC_FAILURE);
goto err;
}
sv = _CONF_new_section(conf, section);
if (sv == NULL) {
CONFerr(CONF_F_DEF_LOAD_BIO, CONF_R_UNABLE_TO_CREATE_NEW_SECTION);
goto err;
}
bufnum = 0;
again = 0;
for (;;) {
if (!BUF_MEM_grow(buff, bufnum + CONFBUFSIZE)) {
CONFerr(CONF_F_DEF_LOAD_BIO, ERR_R_BUF_LIB);
goto err;
}
p = &(buff->data[bufnum]);
*p = '\0';
BIO_gets(in, p, CONFBUFSIZE - 1);
p[CONFBUFSIZE - 1] = '\0';
ii = i = strlen(p);
if (i == 0 && !again)
break;
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 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;
}
CONFerr(CONF_F_DEF_LOAD_BIO,
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) {
CONFerr(CONF_F_DEF_LOAD_BIO,
CONF_R_UNABLE_TO_CREATE_NEW_SECTION);
goto err;
}
continue;
} else {
pname = s;
psection = NULL;
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);
}
p = eat_ws(conf, end);
if (*p != '=') {
CONFerr(CONF_F_DEF_LOAD_BIO, CONF_R_MISSING_EQUAL_SIGN);
goto err;
}
*end = '\0';
p++;
start = eat_ws(conf, p);
while (!IS_EOF(conf, *p))
p++;
p--;
while ((p != start) && (IS_WS(conf, *p)))
p--;
p++;
*p = '\0';
if (!(v = (CONF_VALUE *)OPENSSL_malloc(sizeof(CONF_VALUE)))) {
CONFerr(CONF_F_DEF_LOAD_BIO, ERR_R_MALLOC_FAILURE);
goto err;
}
if (psection == NULL)
psection = section;
v->name = (char *)OPENSSL_malloc(strlen(pname) + 1);
v->value = NULL;
if (v->name == NULL) {
CONFerr(CONF_F_DEF_LOAD_BIO, ERR_R_MALLOC_FAILURE);
goto err;
}
BUF_strlcpy(v->name, pname, strlen(pname) + 1);
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) {
CONFerr(CONF_F_DEF_LOAD_BIO,
CONF_R_UNABLE_TO_CREATE_NEW_SECTION);
goto err;
}
} else
tv = sv;
#if 1
if (_CONF_add_string(conf, tv, v) == 0) {
CONFerr(CONF_F_DEF_LOAD_BIO, ERR_R_MALLOC_FAILURE);
goto err;
}
#else
v->section = tv->section;
if (!sk_CONF_VALUE_push(ts, v)) {
CONFerr(CONF_F_DEF_LOAD_BIO, ERR_R_MALLOC_FAILURE);
goto err;
}
vv = (CONF_VALUE *)lh_insert(conf->data, v);
if (vv != NULL) {
sk_CONF_VALUE_delete_ptr(ts, vv);
OPENSSL_free(vv->name);
OPENSSL_free(vv->value);
OPENSSL_free(vv);
}
#endif
v = NULL;
}
}
if (buff != NULL)
BUF_MEM_free(buff);
if (section != NULL)
OPENSSL_free(section);
return (1);
err:
if (buff != NULL)
BUF_MEM_free(buff);
if (section != NULL)
OPENSSL_free(section);
if (line != NULL)
*line = eline;
- BIO_snprintf(btmp, sizeof btmp, "%ld", eline);
+ BIO_snprintf(btmp, sizeof(btmp), "%ld", eline);
ERR_add_error_data(2, "line ", btmp);
if ((h != conf->data) && (conf->data != NULL)) {
CONF_free(conf->data);
conf->data = NULL;
}
if (v != NULL) {
if (v->name != NULL)
OPENSSL_free(v->name);
if (v->value != NULL)
OPENSSL_free(v->value);
if (v != NULL)
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 == '$') {
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_ALPHA_NUMERIC(conf, *e))
e++;
if ((e[0] == ':') && (e[1] == ':')) {
cp = np;
rrp = e;
rr = *e;
*rrp = '\0';
e += 2;
np = e;
while (IS_ALPHA_NUMERIC(conf, *e))
e++;
}
r = *e;
*e = '\0';
rp = e;
if (q) {
if (r != q) {
CONFerr(CONF_F_STR_COPY, 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) {
CONFerr(CONF_F_STR_COPY, CONF_R_VARIABLE_HAS_NO_VALUE);
goto err;
}
newsize = strlen(p) + buf->length - (e - from);
if (newsize > MAX_CONF_VALUE_LENGTH) {
CONFerr(CONF_F_STR_COPY, CONF_R_VARIABLE_EXPANSION_TOO_LONG);
goto err;
}
if (!BUF_MEM_grow_clean(buf, newsize)) {
CONFerr(CONF_F_STR_COPY, 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';
if (*pto != NULL)
OPENSSL_free(*pto);
*pto = buf->data;
OPENSSL_free(buf);
return (1);
err:
if (buf != NULL)
BUF_MEM_free(buf);
return (0);
}
static char *eat_ws(CONF *conf, char *p)
{
while (IS_WS(conf, *p) && (!IS_EOF(conf, *p)))
p++;
return (p);
}
static char *eat_alpha_numeric(CONF *conf, char *p)
{
for (;;) {
if (IS_ESC(conf, *p)) {
p = scan_esc(conf, p);
continue;
}
if (!IS_ALPHA_NUMERIC_PUNCT(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(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);
}
static IMPLEMENT_LHASH_DOALL_ARG_FN(dump_value, CONF_VALUE, BIO)
static int def_dump(const CONF *conf, BIO *out)
{
lh_CONF_VALUE_doall_arg(conf->data, LHASH_DOALL_ARG_FN(dump_value),
BIO, 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/conf/conf_mod.c b/crypto/conf/conf_mod.c
index e0c9a67ff68f..e2a9a81678ed 100644
--- a/crypto/conf/conf_mod.c
+++ b/crypto/conf/conf_mod.c
@@ -1,601 +1,601 @@
/* conf_mod.c */
/*
* Written by Stephen Henson (steve@openssl.org) for the OpenSSL project
* 2001.
*/
/* ====================================================================
* Copyright (c) 2001 The OpenSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* licensing@OpenSSL.org.
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*
* This product includes cryptographic software written by Eric Young
* (eay@cryptsoft.com). This product includes software written by Tim
* Hudson (tjh@cryptsoft.com).
*
*/
#include <stdio.h>
#include <ctype.h>
#include <openssl/crypto.h>
#include "cryptlib.h"
#include <openssl/conf.h>
#include <openssl/dso.h>
#include <openssl/x509.h>
#define DSO_mod_init_name "OPENSSL_init"
#define DSO_mod_finish_name "OPENSSL_finish"
/*
* This structure contains a data about supported modules. entries in this
* table correspond to either dynamic or static modules.
*/
struct conf_module_st {
/* DSO of this module or NULL if static */
DSO *dso;
/* Name of the module */
char *name;
/* Init function */
conf_init_func *init;
/* Finish function */
conf_finish_func *finish;
/* Number of successfully initialized modules */
int links;
void *usr_data;
};
/*
* This structure contains information about modules that have been
* successfully initialized. There may be more than one entry for a given
* module.
*/
struct conf_imodule_st {
CONF_MODULE *pmod;
char *name;
char *value;
unsigned long flags;
void *usr_data;
};
static STACK_OF(CONF_MODULE) *supported_modules = NULL;
static STACK_OF(CONF_IMODULE) *initialized_modules = NULL;
static void module_free(CONF_MODULE *md);
static void module_finish(CONF_IMODULE *imod);
static int module_run(const CONF *cnf, char *name, char *value,
unsigned long flags);
static CONF_MODULE *module_add(DSO *dso, const char *name,
conf_init_func *ifunc,
conf_finish_func *ffunc);
static CONF_MODULE *module_find(char *name);
static int module_init(CONF_MODULE *pmod, char *name, char *value,
const CONF *cnf);
static CONF_MODULE *module_load_dso(const CONF *cnf, char *name, char *value,
unsigned long flags);
/* Main function: load modules from a CONF structure */
int CONF_modules_load(const CONF *cnf, const char *appname,
unsigned long flags)
{
STACK_OF(CONF_VALUE) *values;
CONF_VALUE *vl;
char *vsection = NULL;
int ret, i;
if (!cnf)
return 1;
if (appname)
vsection = NCONF_get_string(cnf, NULL, appname);
if (!appname || (!vsection && (flags & CONF_MFLAGS_DEFAULT_SECTION)))
vsection = NCONF_get_string(cnf, NULL, "openssl_conf");
if (!vsection) {
ERR_clear_error();
return 1;
}
values = NCONF_get_section(cnf, vsection);
if (!values)
return 0;
for (i = 0; i < sk_CONF_VALUE_num(values); i++) {
vl = sk_CONF_VALUE_value(values, i);
ret = module_run(cnf, vl->name, vl->value, flags);
if (ret <= 0)
if (!(flags & CONF_MFLAGS_IGNORE_ERRORS))
return ret;
}
return 1;
}
int CONF_modules_load_file(const char *filename, const char *appname,
unsigned long flags)
{
char *file = NULL;
CONF *conf = NULL;
int ret = 0;
conf = NCONF_new(NULL);
if (!conf)
goto err;
if (filename == NULL) {
file = CONF_get1_default_config_file();
if (!file)
goto err;
} else
file = (char *)filename;
if (NCONF_load(conf, file, NULL) <= 0) {
if ((flags & CONF_MFLAGS_IGNORE_MISSING_FILE) &&
(ERR_GET_REASON(ERR_peek_last_error()) == CONF_R_NO_SUCH_FILE)) {
ERR_clear_error();
ret = 1;
}
goto err;
}
ret = CONF_modules_load(conf, appname, flags);
err:
if (filename == NULL)
OPENSSL_free(file);
NCONF_free(conf);
return ret;
}
static int module_run(const CONF *cnf, char *name, char *value,
unsigned long flags)
{
CONF_MODULE *md;
int ret;
md = module_find(name);
/* Module not found: try to load DSO */
if (!md && !(flags & CONF_MFLAGS_NO_DSO))
md = module_load_dso(cnf, name, value, flags);
if (!md) {
if (!(flags & CONF_MFLAGS_SILENT)) {
CONFerr(CONF_F_MODULE_RUN, CONF_R_UNKNOWN_MODULE_NAME);
ERR_add_error_data(2, "module=", name);
}
return -1;
}
ret = module_init(md, name, value, cnf);
if (ret <= 0) {
if (!(flags & CONF_MFLAGS_SILENT)) {
char rcode[DECIMAL_SIZE(ret) + 1];
CONFerr(CONF_F_MODULE_RUN, CONF_R_MODULE_INITIALIZATION_ERROR);
- BIO_snprintf(rcode, sizeof rcode, "%-8d", ret);
+ BIO_snprintf(rcode, sizeof(rcode), "%-8d", ret);
ERR_add_error_data(6, "module=", name, ", value=", value,
", retcode=", rcode);
}
}
return ret;
}
/* Load a module from a DSO */
static CONF_MODULE *module_load_dso(const CONF *cnf, char *name, char *value,
unsigned long flags)
{
DSO *dso = NULL;
conf_init_func *ifunc;
conf_finish_func *ffunc;
char *path = NULL;
int errcode = 0;
CONF_MODULE *md;
/* Look for alternative path in module section */
path = NCONF_get_string(cnf, value, "path");
if (!path) {
ERR_clear_error();
path = name;
}
dso = DSO_load(NULL, path, NULL, 0);
if (!dso) {
errcode = CONF_R_ERROR_LOADING_DSO;
goto err;
}
ifunc = (conf_init_func *)DSO_bind_func(dso, DSO_mod_init_name);
if (!ifunc) {
errcode = CONF_R_MISSING_INIT_FUNCTION;
goto err;
}
ffunc = (conf_finish_func *)DSO_bind_func(dso, DSO_mod_finish_name);
/* All OK, add module */
md = module_add(dso, name, ifunc, ffunc);
if (!md)
goto err;
return md;
err:
if (dso)
DSO_free(dso);
CONFerr(CONF_F_MODULE_LOAD_DSO, errcode);
ERR_add_error_data(4, "module=", name, ", path=", path);
return NULL;
}
/* add module to list */
static CONF_MODULE *module_add(DSO *dso, const char *name,
conf_init_func *ifunc, conf_finish_func *ffunc)
{
CONF_MODULE *tmod = NULL;
if (supported_modules == NULL)
supported_modules = sk_CONF_MODULE_new_null();
if (supported_modules == NULL)
return NULL;
tmod = OPENSSL_malloc(sizeof(CONF_MODULE));
if (tmod == NULL)
return NULL;
tmod->dso = dso;
tmod->name = BUF_strdup(name);
if (tmod->name == NULL) {
OPENSSL_free(tmod);
return NULL;
}
tmod->init = ifunc;
tmod->finish = ffunc;
tmod->links = 0;
if (!sk_CONF_MODULE_push(supported_modules, tmod)) {
OPENSSL_free(tmod);
return NULL;
}
return tmod;
}
/*
* Find a module from the list. We allow module names of the form
* modname.XXXX to just search for modname to allow the same module to be
* initialized more than once.
*/
static CONF_MODULE *module_find(char *name)
{
CONF_MODULE *tmod;
int i, nchar;
char *p;
p = strrchr(name, '.');
if (p)
nchar = p - name;
else
nchar = strlen(name);
for (i = 0; i < sk_CONF_MODULE_num(supported_modules); i++) {
tmod = sk_CONF_MODULE_value(supported_modules, i);
if (!strncmp(tmod->name, name, nchar))
return tmod;
}
return NULL;
}
/* initialize a module */
static int module_init(CONF_MODULE *pmod, char *name, char *value,
const CONF *cnf)
{
int ret = 1;
int init_called = 0;
CONF_IMODULE *imod = NULL;
/* Otherwise add initialized module to list */
imod = OPENSSL_malloc(sizeof(CONF_IMODULE));
if (!imod)
goto err;
imod->pmod = pmod;
imod->name = BUF_strdup(name);
imod->value = BUF_strdup(value);
imod->usr_data = NULL;
if (!imod->name || !imod->value)
goto memerr;
/* Try to initialize module */
if (pmod->init) {
ret = pmod->init(imod, cnf);
init_called = 1;
/* Error occurred, exit */
if (ret <= 0)
goto err;
}
if (initialized_modules == NULL) {
initialized_modules = sk_CONF_IMODULE_new_null();
if (!initialized_modules) {
CONFerr(CONF_F_MODULE_INIT, ERR_R_MALLOC_FAILURE);
goto err;
}
}
if (!sk_CONF_IMODULE_push(initialized_modules, imod)) {
CONFerr(CONF_F_MODULE_INIT, ERR_R_MALLOC_FAILURE);
goto err;
}
pmod->links++;
return ret;
err:
/* We've started the module so we'd better finish it */
if (pmod->finish && init_called)
pmod->finish(imod);
memerr:
if (imod) {
if (imod->name)
OPENSSL_free(imod->name);
if (imod->value)
OPENSSL_free(imod->value);
OPENSSL_free(imod);
}
return -1;
}
/*
* Unload any dynamic modules that have a link count of zero: i.e. have no
* active initialized modules. If 'all' is set then all modules are unloaded
* including static ones.
*/
void CONF_modules_unload(int all)
{
int i;
CONF_MODULE *md;
CONF_modules_finish();
/* unload modules in reverse order */
for (i = sk_CONF_MODULE_num(supported_modules) - 1; i >= 0; i--) {
md = sk_CONF_MODULE_value(supported_modules, i);
/* If static or in use and 'all' not set ignore it */
if (((md->links > 0) || !md->dso) && !all)
continue;
/* Since we're working in reverse this is OK */
(void)sk_CONF_MODULE_delete(supported_modules, i);
module_free(md);
}
if (sk_CONF_MODULE_num(supported_modules) == 0) {
sk_CONF_MODULE_free(supported_modules);
supported_modules = NULL;
}
}
/* unload a single module */
static void module_free(CONF_MODULE *md)
{
if (md->dso)
DSO_free(md->dso);
OPENSSL_free(md->name);
OPENSSL_free(md);
}
/* finish and free up all modules instances */
void CONF_modules_finish(void)
{
CONF_IMODULE *imod;
while (sk_CONF_IMODULE_num(initialized_modules) > 0) {
imod = sk_CONF_IMODULE_pop(initialized_modules);
module_finish(imod);
}
sk_CONF_IMODULE_free(initialized_modules);
initialized_modules = NULL;
}
/* finish a module instance */
static void module_finish(CONF_IMODULE *imod)
{
if (imod->pmod->finish)
imod->pmod->finish(imod);
imod->pmod->links--;
OPENSSL_free(imod->name);
OPENSSL_free(imod->value);
OPENSSL_free(imod);
}
/* Add a static module to OpenSSL */
int CONF_module_add(const char *name, conf_init_func *ifunc,
conf_finish_func *ffunc)
{
if (module_add(NULL, name, ifunc, ffunc))
return 1;
else
return 0;
}
void CONF_modules_free(void)
{
CONF_modules_finish();
CONF_modules_unload(1);
}
/* Utility functions */
const char *CONF_imodule_get_name(const CONF_IMODULE *md)
{
return md->name;
}
const char *CONF_imodule_get_value(const CONF_IMODULE *md)
{
return md->value;
}
void *CONF_imodule_get_usr_data(const CONF_IMODULE *md)
{
return md->usr_data;
}
void CONF_imodule_set_usr_data(CONF_IMODULE *md, void *usr_data)
{
md->usr_data = usr_data;
}
CONF_MODULE *CONF_imodule_get_module(const CONF_IMODULE *md)
{
return md->pmod;
}
unsigned long CONF_imodule_get_flags(const CONF_IMODULE *md)
{
return md->flags;
}
void CONF_imodule_set_flags(CONF_IMODULE *md, unsigned long flags)
{
md->flags = flags;
}
void *CONF_module_get_usr_data(CONF_MODULE *pmod)
{
return pmod->usr_data;
}
void CONF_module_set_usr_data(CONF_MODULE *pmod, void *usr_data)
{
pmod->usr_data = usr_data;
}
/* Return default config file name */
char *CONF_get1_default_config_file(void)
{
char *file;
int len;
file = getenv("OPENSSL_CONF");
if (file)
return BUF_strdup(file);
len = strlen(X509_get_default_cert_area());
#ifndef OPENSSL_SYS_VMS
len++;
#endif
len += strlen(OPENSSL_CONF);
file = OPENSSL_malloc(len + 1);
if (!file)
return NULL;
BUF_strlcpy(file, X509_get_default_cert_area(), len + 1);
#ifndef OPENSSL_SYS_VMS
BUF_strlcat(file, "/", len + 1);
#endif
BUF_strlcat(file, OPENSSL_CONF, len + 1);
return file;
}
/*
* This function takes a list separated by 'sep' and calls the callback
* function giving the start and length of each member optionally stripping
* leading and trailing whitespace. This can be used to parse comma separated
* lists for example.
*/
int CONF_parse_list(const char *list_, int sep, int nospc,
int (*list_cb) (const char *elem, int len, void *usr),
void *arg)
{
int ret;
const char *lstart, *tmpend, *p;
if (list_ == NULL) {
CONFerr(CONF_F_CONF_PARSE_LIST, CONF_R_LIST_CANNOT_BE_NULL);
return 0;
}
lstart = list_;
for (;;) {
if (nospc) {
while (*lstart && isspace((unsigned char)*lstart))
lstart++;
}
p = strchr(lstart, sep);
if (p == lstart || !*lstart)
ret = list_cb(NULL, 0, arg);
else {
if (p)
tmpend = p - 1;
else
tmpend = lstart + strlen(lstart) - 1;
if (nospc) {
while (isspace((unsigned char)*tmpend))
tmpend--;
}
ret = list_cb(lstart, tmpend - lstart + 1, arg);
}
if (ret <= 0)
return ret;
if (p == NULL)
return 1;
lstart = p + 1;
}
}
diff --git a/crypto/des/destest.c b/crypto/des/destest.c
index c6be34203853..f2041c1e1118 100644
--- a/crypto/des/destest.c
+++ b/crypto/des/destest.c
@@ -1,929 +1,929 @@
/* crypto/des/destest.c */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
#include <stdio.h>
#include <stdlib.h>
#include <openssl/e_os2.h>
#if defined(OPENSSL_SYS_WIN32) || defined(OPENSSL_SYS_WIN16) || defined(OPENSSL_SYS_WINDOWS)
# ifndef OPENSSL_SYS_MSDOS
# define OPENSSL_SYS_MSDOS
# endif
#endif
#ifndef OPENSSL_SYS_MSDOS
# if !defined(OPENSSL_SYS_VMS) || defined(OPENSSL_SYS_VMS_DECC)
# include OPENSSL_UNISTD
# endif
#else
# include <io.h>
#endif
#include <string.h>
#ifdef OPENSSL_NO_DES
int main(int argc, char *argv[])
{
printf("No DES support\n");
return (0);
}
#else
# include <openssl/des.h>
# define crypt(c,s) (DES_crypt((c),(s)))
/* tisk tisk - the test keys don't all have odd parity :-( */
/* test data */
# define NUM_TESTS 34
static unsigned char key_data[NUM_TESTS][8] = {
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF},
{0x30, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
{0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11},
{0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF},
{0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11},
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
{0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10},
{0x7C, 0xA1, 0x10, 0x45, 0x4A, 0x1A, 0x6E, 0x57},
{0x01, 0x31, 0xD9, 0x61, 0x9D, 0xC1, 0x37, 0x6E},
{0x07, 0xA1, 0x13, 0x3E, 0x4A, 0x0B, 0x26, 0x86},
{0x38, 0x49, 0x67, 0x4C, 0x26, 0x02, 0x31, 0x9E},
{0x04, 0xB9, 0x15, 0xBA, 0x43, 0xFE, 0xB5, 0xB6},
{0x01, 0x13, 0xB9, 0x70, 0xFD, 0x34, 0xF2, 0xCE},
{0x01, 0x70, 0xF1, 0x75, 0x46, 0x8F, 0xB5, 0xE6},
{0x43, 0x29, 0x7F, 0xAD, 0x38, 0xE3, 0x73, 0xFE},
{0x07, 0xA7, 0x13, 0x70, 0x45, 0xDA, 0x2A, 0x16},
{0x04, 0x68, 0x91, 0x04, 0xC2, 0xFD, 0x3B, 0x2F},
{0x37, 0xD0, 0x6B, 0xB5, 0x16, 0xCB, 0x75, 0x46},
{0x1F, 0x08, 0x26, 0x0D, 0x1A, 0xC2, 0x46, 0x5E},
{0x58, 0x40, 0x23, 0x64, 0x1A, 0xBA, 0x61, 0x76},
{0x02, 0x58, 0x16, 0x16, 0x46, 0x29, 0xB0, 0x07},
{0x49, 0x79, 0x3E, 0xBC, 0x79, 0xB3, 0x25, 0x8F},
{0x4F, 0xB0, 0x5E, 0x15, 0x15, 0xAB, 0x73, 0xA7},
{0x49, 0xE9, 0x5D, 0x6D, 0x4C, 0xA2, 0x29, 0xBF},
{0x01, 0x83, 0x10, 0xDC, 0x40, 0x9B, 0x26, 0xD6},
{0x1C, 0x58, 0x7F, 0x1C, 0x13, 0x92, 0x4F, 0xEF},
{0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01},
{0x1F, 0x1F, 0x1F, 0x1F, 0x0E, 0x0E, 0x0E, 0x0E},
{0xE0, 0xFE, 0xE0, 0xFE, 0xF1, 0xFE, 0xF1, 0xFE},
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF},
{0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF},
{0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10}
};
static unsigned char plain_data[NUM_TESTS][8] = {
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF},
{0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01},
{0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11},
{0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11},
{0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF},
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
{0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF},
{0x01, 0xA1, 0xD6, 0xD0, 0x39, 0x77, 0x67, 0x42},
{0x5C, 0xD5, 0x4C, 0xA8, 0x3D, 0xEF, 0x57, 0xDA},
{0x02, 0x48, 0xD4, 0x38, 0x06, 0xF6, 0x71, 0x72},
{0x51, 0x45, 0x4B, 0x58, 0x2D, 0xDF, 0x44, 0x0A},
{0x42, 0xFD, 0x44, 0x30, 0x59, 0x57, 0x7F, 0xA2},
{0x05, 0x9B, 0x5E, 0x08, 0x51, 0xCF, 0x14, 0x3A},
{0x07, 0x56, 0xD8, 0xE0, 0x77, 0x47, 0x61, 0xD2},
{0x76, 0x25, 0x14, 0xB8, 0x29, 0xBF, 0x48, 0x6A},
{0x3B, 0xDD, 0x11, 0x90, 0x49, 0x37, 0x28, 0x02},
{0x26, 0x95, 0x5F, 0x68, 0x35, 0xAF, 0x60, 0x9A},
{0x16, 0x4D, 0x5E, 0x40, 0x4F, 0x27, 0x52, 0x32},
{0x6B, 0x05, 0x6E, 0x18, 0x75, 0x9F, 0x5C, 0xCA},
{0x00, 0x4B, 0xD6, 0xEF, 0x09, 0x17, 0x60, 0x62},
{0x48, 0x0D, 0x39, 0x00, 0x6E, 0xE7, 0x62, 0xF2},
{0x43, 0x75, 0x40, 0xC8, 0x69, 0x8F, 0x3C, 0xFA},
{0x07, 0x2D, 0x43, 0xA0, 0x77, 0x07, 0x52, 0x92},
{0x02, 0xFE, 0x55, 0x77, 0x81, 0x17, 0xF1, 0x2A},
{0x1D, 0x9D, 0x5C, 0x50, 0x18, 0xF7, 0x28, 0xC2},
{0x30, 0x55, 0x32, 0x28, 0x6D, 0x6F, 0x29, 0x5A},
{0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF},
{0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF},
{0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF},
{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF},
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}
};
static unsigned char cipher_data[NUM_TESTS][8] = {
{0x8C, 0xA6, 0x4D, 0xE9, 0xC1, 0xB1, 0x23, 0xA7},
{0x73, 0x59, 0xB2, 0x16, 0x3E, 0x4E, 0xDC, 0x58},
{0x95, 0x8E, 0x6E, 0x62, 0x7A, 0x05, 0x55, 0x7B},
{0xF4, 0x03, 0x79, 0xAB, 0x9E, 0x0E, 0xC5, 0x33},
{0x17, 0x66, 0x8D, 0xFC, 0x72, 0x92, 0x53, 0x2D},
{0x8A, 0x5A, 0xE1, 0xF8, 0x1A, 0xB8, 0xF2, 0xDD},
{0x8C, 0xA6, 0x4D, 0xE9, 0xC1, 0xB1, 0x23, 0xA7},
{0xED, 0x39, 0xD9, 0x50, 0xFA, 0x74, 0xBC, 0xC4},
{0x69, 0x0F, 0x5B, 0x0D, 0x9A, 0x26, 0x93, 0x9B},
{0x7A, 0x38, 0x9D, 0x10, 0x35, 0x4B, 0xD2, 0x71},
{0x86, 0x8E, 0xBB, 0x51, 0xCA, 0xB4, 0x59, 0x9A},
{0x71, 0x78, 0x87, 0x6E, 0x01, 0xF1, 0x9B, 0x2A},
{0xAF, 0x37, 0xFB, 0x42, 0x1F, 0x8C, 0x40, 0x95},
{0x86, 0xA5, 0x60, 0xF1, 0x0E, 0xC6, 0xD8, 0x5B},
{0x0C, 0xD3, 0xDA, 0x02, 0x00, 0x21, 0xDC, 0x09},
{0xEA, 0x67, 0x6B, 0x2C, 0xB7, 0xDB, 0x2B, 0x7A},
{0xDF, 0xD6, 0x4A, 0x81, 0x5C, 0xAF, 0x1A, 0x0F},
{0x5C, 0x51, 0x3C, 0x9C, 0x48, 0x86, 0xC0, 0x88},
{0x0A, 0x2A, 0xEE, 0xAE, 0x3F, 0xF4, 0xAB, 0x77},
{0xEF, 0x1B, 0xF0, 0x3E, 0x5D, 0xFA, 0x57, 0x5A},
{0x88, 0xBF, 0x0D, 0xB6, 0xD7, 0x0D, 0xEE, 0x56},
{0xA1, 0xF9, 0x91, 0x55, 0x41, 0x02, 0x0B, 0x56},
{0x6F, 0xBF, 0x1C, 0xAF, 0xCF, 0xFD, 0x05, 0x56},
{0x2F, 0x22, 0xE4, 0x9B, 0xAB, 0x7C, 0xA1, 0xAC},
{0x5A, 0x6B, 0x61, 0x2C, 0xC2, 0x6C, 0xCE, 0x4A},
{0x5F, 0x4C, 0x03, 0x8E, 0xD1, 0x2B, 0x2E, 0x41},
{0x63, 0xFA, 0xC0, 0xD0, 0x34, 0xD9, 0xF7, 0x93},
{0x61, 0x7B, 0x3A, 0x0C, 0xE8, 0xF0, 0x71, 0x00},
{0xDB, 0x95, 0x86, 0x05, 0xF8, 0xC8, 0xC6, 0x06},
{0xED, 0xBF, 0xD1, 0xC6, 0x6C, 0x29, 0xCC, 0xC7},
{0x35, 0x55, 0x50, 0xB2, 0x15, 0x0E, 0x24, 0x51},
{0xCA, 0xAA, 0xAF, 0x4D, 0xEA, 0xF1, 0xDB, 0xAE},
{0xD5, 0xD4, 0x4F, 0xF7, 0x20, 0x68, 0x3D, 0x0D},
{0x2A, 0x2B, 0xB0, 0x08, 0xDF, 0x97, 0xC2, 0xF2}
};
static unsigned char cipher_ecb2[NUM_TESTS - 1][8] = {
{0x92, 0x95, 0xB5, 0x9B, 0xB3, 0x84, 0x73, 0x6E},
{0x19, 0x9E, 0x9D, 0x6D, 0xF3, 0x9A, 0xA8, 0x16},
{0x2A, 0x4B, 0x4D, 0x24, 0x52, 0x43, 0x84, 0x27},
{0x35, 0x84, 0x3C, 0x01, 0x9D, 0x18, 0xC5, 0xB6},
{0x4A, 0x5B, 0x2F, 0x42, 0xAA, 0x77, 0x19, 0x25},
{0xA0, 0x6B, 0xA9, 0xB8, 0xCA, 0x5B, 0x17, 0x8A},
{0xAB, 0x9D, 0xB7, 0xFB, 0xED, 0x95, 0xF2, 0x74},
{0x3D, 0x25, 0x6C, 0x23, 0xA7, 0x25, 0x2F, 0xD6},
{0xB7, 0x6F, 0xAB, 0x4F, 0xBD, 0xBD, 0xB7, 0x67},
{0x8F, 0x68, 0x27, 0xD6, 0x9C, 0xF4, 0x1A, 0x10},
{0x82, 0x57, 0xA1, 0xD6, 0x50, 0x5E, 0x81, 0x85},
{0xA2, 0x0F, 0x0A, 0xCD, 0x80, 0x89, 0x7D, 0xFA},
{0xCD, 0x2A, 0x53, 0x3A, 0xDB, 0x0D, 0x7E, 0xF3},
{0xD2, 0xC2, 0xBE, 0x27, 0xE8, 0x1B, 0x68, 0xE3},
{0xE9, 0x24, 0xCF, 0x4F, 0x89, 0x3C, 0x5B, 0x0A},
{0xA7, 0x18, 0xC3, 0x9F, 0xFA, 0x9F, 0xD7, 0x69},
{0x77, 0x2C, 0x79, 0xB1, 0xD2, 0x31, 0x7E, 0xB1},
{0x49, 0xAB, 0x92, 0x7F, 0xD0, 0x22, 0x00, 0xB7},
{0xCE, 0x1C, 0x6C, 0x7D, 0x85, 0xE3, 0x4A, 0x6F},
{0xBE, 0x91, 0xD6, 0xE1, 0x27, 0xB2, 0xE9, 0x87},
{0x70, 0x28, 0xAE, 0x8F, 0xD1, 0xF5, 0x74, 0x1A},
{0xAA, 0x37, 0x80, 0xBB, 0xF3, 0x22, 0x1D, 0xDE},
{0xA6, 0xC4, 0xD2, 0x5E, 0x28, 0x93, 0xAC, 0xB3},
{0x22, 0x07, 0x81, 0x5A, 0xE4, 0xB7, 0x1A, 0xAD},
{0xDC, 0xCE, 0x05, 0xE7, 0x07, 0xBD, 0xF5, 0x84},
{0x26, 0x1D, 0x39, 0x2C, 0xB3, 0xBA, 0xA5, 0x85},
{0xB4, 0xF7, 0x0F, 0x72, 0xFB, 0x04, 0xF0, 0xDC},
{0x95, 0xBA, 0xA9, 0x4E, 0x87, 0x36, 0xF2, 0x89},
{0xD4, 0x07, 0x3A, 0xF1, 0x5A, 0x17, 0x82, 0x0E},
{0xEF, 0x6F, 0xAF, 0xA7, 0x66, 0x1A, 0x7E, 0x89},
{0xC1, 0x97, 0xF5, 0x58, 0x74, 0x8A, 0x20, 0xE7},
{0x43, 0x34, 0xCF, 0xDA, 0x22, 0xC4, 0x86, 0xC8},
{0x08, 0xD7, 0xB4, 0xFB, 0x62, 0x9D, 0x08, 0x85}
};
static unsigned char cbc_key[8] =
{ 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef };
static unsigned char cbc2_key[8] =
{ 0xf1, 0xe0, 0xd3, 0xc2, 0xb5, 0xa4, 0x97, 0x86 };
static unsigned char cbc3_key[8] =
{ 0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54, 0x32, 0x10 };
static unsigned char cbc_iv[8] =
{ 0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54, 0x32, 0x10 };
/*
* Changed the following text constant to binary so it will work on ebcdic
* machines :-)
*/
/* static char cbc_data[40]="7654321 Now is the time for \0001"; */
static unsigned char cbc_data[40] = {
0x37, 0x36, 0x35, 0x34, 0x33, 0x32, 0x31, 0x20,
0x4E, 0x6F, 0x77, 0x20, 0x69, 0x73, 0x20, 0x74,
0x68, 0x65, 0x20, 0x74, 0x69, 0x6D, 0x65, 0x20,
0x66, 0x6F, 0x72, 0x20, 0x00, 0x31, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
};
static unsigned char cbc_ok[32] = {
0xcc, 0xd1, 0x73, 0xff, 0xab, 0x20, 0x39, 0xf4,
0xac, 0xd8, 0xae, 0xfd, 0xdf, 0xd8, 0xa1, 0xeb,
0x46, 0x8e, 0x91, 0x15, 0x78, 0x88, 0xba, 0x68,
0x1d, 0x26, 0x93, 0x97, 0xf7, 0xfe, 0x62, 0xb4
};
# ifdef SCREW_THE_PARITY
# error "SCREW_THE_PARITY is not ment to be defined."
# error "Original vectors are preserved for reference only."
static unsigned char cbc2_key[8] =
{ 0xf0, 0xe1, 0xd2, 0xc3, 0xb4, 0xa5, 0x96, 0x87 };
static unsigned char xcbc_ok[32] = {
0x86, 0x74, 0x81, 0x0D, 0x61, 0xA4, 0xA5, 0x48,
0xB9, 0x93, 0x03, 0xE1, 0xB8, 0xBB, 0xBD, 0xBD,
0x64, 0x30, 0x0B, 0xB9, 0x06, 0x65, 0x81, 0x76,
0x04, 0x1D, 0x77, 0x62, 0x17, 0xCA, 0x2B, 0xD2,
};
# else
static unsigned char xcbc_ok[32] = {
0x84, 0x6B, 0x29, 0x14, 0x85, 0x1E, 0x9A, 0x29,
0x54, 0x73, 0x2F, 0x8A, 0xA0, 0xA6, 0x11, 0xC1,
0x15, 0xCD, 0xC2, 0xD7, 0x95, 0x1B, 0x10, 0x53,
0xA6, 0x3C, 0x5E, 0x03, 0xB2, 0x1A, 0xA3, 0xC4,
};
# endif
static unsigned char cbc3_ok[32] = {
0x3F, 0xE3, 0x01, 0xC9, 0x62, 0xAC, 0x01, 0xD0,
0x22, 0x13, 0x76, 0x3C, 0x1C, 0xBD, 0x4C, 0xDC,
0x79, 0x96, 0x57, 0xC0, 0x64, 0xEC, 0xF5, 0xD4,
0x1C, 0x67, 0x38, 0x12, 0xCF, 0xDE, 0x96, 0x75
};
static unsigned char pcbc_ok[32] = {
0xcc, 0xd1, 0x73, 0xff, 0xab, 0x20, 0x39, 0xf4,
0x6d, 0xec, 0xb4, 0x70, 0xa0, 0xe5, 0x6b, 0x15,
0xae, 0xa6, 0xbf, 0x61, 0xed, 0x7d, 0x9c, 0x9f,
0xf7, 0x17, 0x46, 0x3b, 0x8a, 0xb3, 0xcc, 0x88
};
static unsigned char cfb_key[8] =
{ 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef };
static unsigned char cfb_iv[8] =
{ 0x12, 0x34, 0x56, 0x78, 0x90, 0xab, 0xcd, 0xef };
static unsigned char cfb_buf1[40], cfb_buf2[40], cfb_tmp[8];
static unsigned char plain[24] = {
0x4e, 0x6f, 0x77, 0x20, 0x69, 0x73,
0x20, 0x74, 0x68, 0x65, 0x20, 0x74,
0x69, 0x6d, 0x65, 0x20, 0x66, 0x6f,
0x72, 0x20, 0x61, 0x6c, 0x6c, 0x20
};
static unsigned char cfb_cipher8[24] = {
0xf3, 0x1f, 0xda, 0x07, 0x01, 0x14, 0x62, 0xee, 0x18, 0x7f, 0x43, 0xd8,
0x0a, 0x7c, 0xd9, 0xb5, 0xb0, 0xd2, 0x90, 0xda, 0x6e, 0x5b, 0x9a, 0x87
};
static unsigned char cfb_cipher16[24] = {
0xF3, 0x09, 0x87, 0x87, 0x7F, 0x57, 0xF7, 0x3C, 0x36, 0xB6, 0xDB, 0x70,
0xD8, 0xD5, 0x34, 0x19, 0xD3, 0x86, 0xB2, 0x23, 0xB7, 0xB2, 0xAD, 0x1B
};
static unsigned char cfb_cipher32[24] = {
0xF3, 0x09, 0x62, 0x49, 0xA4, 0xDF, 0xA4, 0x9F, 0x33, 0xDC, 0x7B, 0xAD,
0x4C, 0xC8, 0x9F, 0x64, 0xE4, 0x53, 0xE5, 0xEC, 0x67, 0x20, 0xDA, 0xB6
};
static unsigned char cfb_cipher48[24] = {
0xF3, 0x09, 0x62, 0x49, 0xC7, 0xF4, 0x30, 0xB5, 0x15, 0xEC, 0xBB, 0x85,
0x97, 0x5A, 0x13, 0x8C, 0x68, 0x60, 0xE2, 0x38, 0x34, 0x3C, 0xDC, 0x1F
};
static unsigned char cfb_cipher64[24] = {
0xF3, 0x09, 0x62, 0x49, 0xC7, 0xF4, 0x6E, 0x51, 0xA6, 0x9E, 0x83, 0x9B,
0x1A, 0x92, 0xF7, 0x84, 0x03, 0x46, 0x71, 0x33, 0x89, 0x8E, 0xA6, 0x22
};
static unsigned char ofb_key[8] =
{ 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef };
static unsigned char ofb_iv[8] =
{ 0x12, 0x34, 0x56, 0x78, 0x90, 0xab, 0xcd, 0xef };
static unsigned char ofb_buf1[24], ofb_buf2[24], ofb_tmp[8];
static unsigned char ofb_cipher[24] = {
0xf3, 0x09, 0x62, 0x49, 0xc7, 0xf4, 0x6e, 0x51,
0x35, 0xf2, 0x4a, 0x24, 0x2e, 0xeb, 0x3d, 0x3f,
0x3d, 0x6d, 0x5b, 0xe3, 0x25, 0x5a, 0xf8, 0xc3
};
# if 0
static DES_LONG cbc_cksum_ret = 0xB462FEF7L;
# else
static DES_LONG cbc_cksum_ret = 0xF7FE62B4L;
# endif
static unsigned char cbc_cksum_data[8] =
{ 0x1D, 0x26, 0x93, 0x97, 0xf7, 0xfe, 0x62, 0xb4 };
static char *pt(unsigned char *p);
static int cfb_test(int bits, unsigned char *cfb_cipher);
static int cfb64_test(unsigned char *cfb_cipher);
static int ede_cfb64_test(unsigned char *cfb_cipher);
int main(int argc, char *argv[])
{
int j, err = 0;
unsigned int i;
des_cblock in, out, outin, iv3, iv2;
des_key_schedule ks, ks2, ks3;
unsigned char cbc_in[40];
unsigned char cbc_out[40];
DES_LONG cs;
unsigned char cret[8];
# ifdef _CRAY
struct {
int a:32;
int b:32;
} lqret[2];
# else
DES_LONG lqret[4];
# endif
int num;
char *str;
# ifndef OPENSSL_NO_DESCBCM
printf("Doing cbcm\n");
if ((j = DES_set_key_checked(&cbc_key, &ks)) != 0) {
printf("Key error %d\n", j);
err = 1;
}
if ((j = DES_set_key_checked(&cbc2_key, &ks2)) != 0) {
printf("Key error %d\n", j);
err = 1;
}
if ((j = DES_set_key_checked(&cbc3_key, &ks3)) != 0) {
printf("Key error %d\n", j);
err = 1;
}
memset(cbc_out, 0, 40);
memset(cbc_in, 0, 40);
i = strlen((char *)cbc_data) + 1;
/* i=((i+7)/8)*8; */
memcpy(iv3, cbc_iv, sizeof(cbc_iv));
- memset(iv2, '\0', sizeof iv2);
+ memset(iv2, '\0', sizeof(iv2));
DES_ede3_cbcm_encrypt(cbc_data, cbc_out, 16L, &ks, &ks2, &ks3, &iv3, &iv2,
DES_ENCRYPT);
DES_ede3_cbcm_encrypt(&cbc_data[16], &cbc_out[16], i - 16, &ks, &ks2,
&ks3, &iv3, &iv2, DES_ENCRYPT);
/*- if (memcmp(cbc_out,cbc3_ok,
(unsigned int)(strlen((char *)cbc_data)+1+7)/8*8) != 0)
{
printf("des_ede3_cbc_encrypt encrypt error\n");
err=1;
}
*/
memcpy(iv3, cbc_iv, sizeof(cbc_iv));
- memset(iv2, '\0', sizeof iv2);
+ memset(iv2, '\0', sizeof(iv2));
DES_ede3_cbcm_encrypt(cbc_out, cbc_in, i, &ks, &ks2, &ks3, &iv3, &iv2,
DES_DECRYPT);
if (memcmp(cbc_in, cbc_data, strlen((char *)cbc_data) + 1) != 0) {
unsigned int n;
printf("des_ede3_cbcm_encrypt decrypt error\n");
for (n = 0; n < i; ++n)
printf(" %02x", cbc_data[n]);
printf("\n");
for (n = 0; n < i; ++n)
printf(" %02x", cbc_in[n]);
printf("\n");
err = 1;
}
# endif
printf("Doing ecb\n");
for (i = 0; i < NUM_TESTS; i++) {
DES_set_key_unchecked(&key_data[i], &ks);
memcpy(in, plain_data[i], 8);
memset(out, 0, 8);
memset(outin, 0, 8);
des_ecb_encrypt(&in, &out, ks, DES_ENCRYPT);
des_ecb_encrypt(&out, &outin, ks, DES_DECRYPT);
if (memcmp(out, cipher_data[i], 8) != 0) {
printf("Encryption error %2d\nk=%s p=%s o=%s act=%s\n",
i + 1, pt(key_data[i]), pt(in), pt(cipher_data[i]),
pt(out));
err = 1;
}
if (memcmp(in, outin, 8) != 0) {
printf("Decryption error %2d\nk=%s p=%s o=%s act=%s\n",
i + 1, pt(key_data[i]), pt(out), pt(in), pt(outin));
err = 1;
}
}
# ifndef LIBDES_LIT
printf("Doing ede ecb\n");
for (i = 0; i < (NUM_TESTS - 2); i++) {
DES_set_key_unchecked(&key_data[i], &ks);
DES_set_key_unchecked(&key_data[i + 1], &ks2);
DES_set_key_unchecked(&key_data[i + 2], &ks3);
memcpy(in, plain_data[i], 8);
memset(out, 0, 8);
memset(outin, 0, 8);
des_ecb2_encrypt(&in, &out, ks, ks2, DES_ENCRYPT);
des_ecb2_encrypt(&out, &outin, ks, ks2, DES_DECRYPT);
if (memcmp(out, cipher_ecb2[i], 8) != 0) {
printf("Encryption error %2d\nk=%s p=%s o=%s act=%s\n",
i + 1, pt(key_data[i]), pt(in), pt(cipher_ecb2[i]),
pt(out));
err = 1;
}
if (memcmp(in, outin, 8) != 0) {
printf("Decryption error %2d\nk=%s p=%s o=%s act=%s\n",
i + 1, pt(key_data[i]), pt(out), pt(in), pt(outin));
err = 1;
}
}
# endif
printf("Doing cbc\n");
if ((j = DES_set_key_checked(&cbc_key, &ks)) != 0) {
printf("Key error %d\n", j);
err = 1;
}
memset(cbc_out, 0, 40);
memset(cbc_in, 0, 40);
memcpy(iv3, cbc_iv, sizeof(cbc_iv));
des_ncbc_encrypt(cbc_data, cbc_out, strlen((char *)cbc_data) + 1, ks,
&iv3, DES_ENCRYPT);
if (memcmp(cbc_out, cbc_ok, 32) != 0) {
printf("cbc_encrypt encrypt error\n");
err = 1;
}
memcpy(iv3, cbc_iv, sizeof(cbc_iv));
des_ncbc_encrypt(cbc_out, cbc_in, strlen((char *)cbc_data) + 1, ks,
&iv3, DES_DECRYPT);
if (memcmp(cbc_in, cbc_data, strlen((char *)cbc_data)) != 0) {
printf("cbc_encrypt decrypt error\n");
err = 1;
}
# ifndef LIBDES_LIT
printf("Doing desx cbc\n");
if ((j = DES_set_key_checked(&cbc_key, &ks)) != 0) {
printf("Key error %d\n", j);
err = 1;
}
memset(cbc_out, 0, 40);
memset(cbc_in, 0, 40);
memcpy(iv3, cbc_iv, sizeof(cbc_iv));
des_xcbc_encrypt(cbc_data, cbc_out, strlen((char *)cbc_data) + 1, ks,
&iv3, &cbc2_key, &cbc3_key, DES_ENCRYPT);
if (memcmp(cbc_out, xcbc_ok, 32) != 0) {
printf("des_xcbc_encrypt encrypt error\n");
err = 1;
}
memcpy(iv3, cbc_iv, sizeof(cbc_iv));
des_xcbc_encrypt(cbc_out, cbc_in, strlen((char *)cbc_data) + 1, ks,
&iv3, &cbc2_key, &cbc3_key, DES_DECRYPT);
if (memcmp(cbc_in, cbc_data, strlen((char *)cbc_data) + 1) != 0) {
printf("des_xcbc_encrypt decrypt error\n");
err = 1;
}
# endif
printf("Doing ede cbc\n");
if ((j = DES_set_key_checked(&cbc_key, &ks)) != 0) {
printf("Key error %d\n", j);
err = 1;
}
if ((j = DES_set_key_checked(&cbc2_key, &ks2)) != 0) {
printf("Key error %d\n", j);
err = 1;
}
if ((j = DES_set_key_checked(&cbc3_key, &ks3)) != 0) {
printf("Key error %d\n", j);
err = 1;
}
memset(cbc_out, 0, 40);
memset(cbc_in, 0, 40);
i = strlen((char *)cbc_data) + 1;
/* i=((i+7)/8)*8; */
memcpy(iv3, cbc_iv, sizeof(cbc_iv));
des_ede3_cbc_encrypt(cbc_data, cbc_out, 16L, ks, ks2, ks3, &iv3,
DES_ENCRYPT);
des_ede3_cbc_encrypt(&(cbc_data[16]), &(cbc_out[16]), i - 16, ks, ks2,
ks3, &iv3, DES_ENCRYPT);
if (memcmp
(cbc_out, cbc3_ok,
(unsigned int)(strlen((char *)cbc_data) + 1 + 7) / 8 * 8) != 0) {
unsigned int n;
printf("des_ede3_cbc_encrypt encrypt error\n");
for (n = 0; n < i; ++n)
printf(" %02x", cbc_out[n]);
printf("\n");
for (n = 0; n < i; ++n)
printf(" %02x", cbc3_ok[n]);
printf("\n");
err = 1;
}
memcpy(iv3, cbc_iv, sizeof(cbc_iv));
des_ede3_cbc_encrypt(cbc_out, cbc_in, i, ks, ks2, ks3, &iv3, DES_DECRYPT);
if (memcmp(cbc_in, cbc_data, strlen((char *)cbc_data) + 1) != 0) {
unsigned int n;
printf("des_ede3_cbc_encrypt decrypt error\n");
for (n = 0; n < i; ++n)
printf(" %02x", cbc_data[n]);
printf("\n");
for (n = 0; n < i; ++n)
printf(" %02x", cbc_in[n]);
printf("\n");
err = 1;
}
# ifndef LIBDES_LIT
printf("Doing pcbc\n");
if ((j = DES_set_key_checked(&cbc_key, &ks)) != 0) {
printf("Key error %d\n", j);
err = 1;
}
memset(cbc_out, 0, 40);
memset(cbc_in, 0, 40);
des_pcbc_encrypt(cbc_data, cbc_out, strlen((char *)cbc_data) + 1, ks,
&cbc_iv, DES_ENCRYPT);
if (memcmp(cbc_out, pcbc_ok, 32) != 0) {
printf("pcbc_encrypt encrypt error\n");
err = 1;
}
des_pcbc_encrypt(cbc_out, cbc_in, strlen((char *)cbc_data) + 1, ks,
&cbc_iv, DES_DECRYPT);
if (memcmp(cbc_in, cbc_data, strlen((char *)cbc_data) + 1) != 0) {
printf("pcbc_encrypt decrypt error\n");
err = 1;
}
printf("Doing ");
printf("cfb8 ");
err += cfb_test(8, cfb_cipher8);
printf("cfb16 ");
err += cfb_test(16, cfb_cipher16);
printf("cfb32 ");
err += cfb_test(32, cfb_cipher32);
printf("cfb48 ");
err += cfb_test(48, cfb_cipher48);
printf("cfb64 ");
err += cfb_test(64, cfb_cipher64);
printf("cfb64() ");
err += cfb64_test(cfb_cipher64);
memcpy(cfb_tmp, cfb_iv, sizeof(cfb_iv));
for (i = 0; i < sizeof(plain); i++)
des_cfb_encrypt(&(plain[i]), &(cfb_buf1[i]),
8, 1, ks, &cfb_tmp, DES_ENCRYPT);
if (memcmp(cfb_cipher8, cfb_buf1, sizeof(plain)) != 0) {
printf("cfb_encrypt small encrypt error\n");
err = 1;
}
memcpy(cfb_tmp, cfb_iv, sizeof(cfb_iv));
for (i = 0; i < sizeof(plain); i++)
des_cfb_encrypt(&(cfb_buf1[i]), &(cfb_buf2[i]),
8, 1, ks, &cfb_tmp, DES_DECRYPT);
if (memcmp(plain, cfb_buf2, sizeof(plain)) != 0) {
printf("cfb_encrypt small decrypt error\n");
err = 1;
}
printf("ede_cfb64() ");
err += ede_cfb64_test(cfb_cipher64);
printf("done\n");
printf("Doing ofb\n");
DES_set_key_checked(&ofb_key, &ks);
memcpy(ofb_tmp, ofb_iv, sizeof(ofb_iv));
des_ofb_encrypt(plain, ofb_buf1, 64, sizeof(plain) / 8, ks, &ofb_tmp);
if (memcmp(ofb_cipher, ofb_buf1, sizeof(ofb_buf1)) != 0) {
printf("ofb_encrypt encrypt error\n");
printf("%02X %02X %02X %02X %02X %02X %02X %02X\n",
ofb_buf1[8 + 0], ofb_buf1[8 + 1], ofb_buf1[8 + 2],
ofb_buf1[8 + 3], ofb_buf1[8 + 4], ofb_buf1[8 + 5],
ofb_buf1[8 + 6], ofb_buf1[8 + 7]);
printf("%02X %02X %02X %02X %02X %02X %02X %02X\n", ofb_buf1[8 + 0],
ofb_cipher[8 + 1], ofb_cipher[8 + 2], ofb_cipher[8 + 3],
ofb_buf1[8 + 4], ofb_cipher[8 + 5], ofb_cipher[8 + 6],
ofb_cipher[8 + 7]);
err = 1;
}
memcpy(ofb_tmp, ofb_iv, sizeof(ofb_iv));
des_ofb_encrypt(ofb_buf1, ofb_buf2, 64, sizeof(ofb_buf1) / 8, ks,
&ofb_tmp);
if (memcmp(plain, ofb_buf2, sizeof(ofb_buf2)) != 0) {
printf("ofb_encrypt decrypt error\n");
printf("%02X %02X %02X %02X %02X %02X %02X %02X\n",
ofb_buf2[8 + 0], ofb_buf2[8 + 1], ofb_buf2[8 + 2],
ofb_buf2[8 + 3], ofb_buf2[8 + 4], ofb_buf2[8 + 5],
ofb_buf2[8 + 6], ofb_buf2[8 + 7]);
printf("%02X %02X %02X %02X %02X %02X %02X %02X\n", plain[8 + 0],
plain[8 + 1], plain[8 + 2], plain[8 + 3], plain[8 + 4],
plain[8 + 5], plain[8 + 6], plain[8 + 7]);
err = 1;
}
printf("Doing ofb64\n");
DES_set_key_checked(&ofb_key, &ks);
memcpy(ofb_tmp, ofb_iv, sizeof(ofb_iv));
memset(ofb_buf1, 0, sizeof(ofb_buf1));
memset(ofb_buf2, 0, sizeof(ofb_buf1));
num = 0;
for (i = 0; i < sizeof(plain); i++) {
des_ofb64_encrypt(&(plain[i]), &(ofb_buf1[i]), 1, ks, &ofb_tmp, &num);
}
if (memcmp(ofb_cipher, ofb_buf1, sizeof(ofb_buf1)) != 0) {
printf("ofb64_encrypt encrypt error\n");
err = 1;
}
memcpy(ofb_tmp, ofb_iv, sizeof(ofb_iv));
num = 0;
des_ofb64_encrypt(ofb_buf1, ofb_buf2, sizeof(ofb_buf1), ks, &ofb_tmp,
&num);
if (memcmp(plain, ofb_buf2, sizeof(ofb_buf2)) != 0) {
printf("ofb64_encrypt decrypt error\n");
err = 1;
}
printf("Doing ede_ofb64\n");
DES_set_key_checked(&ofb_key, &ks);
memcpy(ofb_tmp, ofb_iv, sizeof(ofb_iv));
memset(ofb_buf1, 0, sizeof(ofb_buf1));
memset(ofb_buf2, 0, sizeof(ofb_buf1));
num = 0;
for (i = 0; i < sizeof(plain); i++) {
des_ede3_ofb64_encrypt(&(plain[i]), &(ofb_buf1[i]), 1, ks, ks,
ks, &ofb_tmp, &num);
}
if (memcmp(ofb_cipher, ofb_buf1, sizeof(ofb_buf1)) != 0) {
printf("ede_ofb64_encrypt encrypt error\n");
err = 1;
}
memcpy(ofb_tmp, ofb_iv, sizeof(ofb_iv));
num = 0;
des_ede3_ofb64_encrypt(ofb_buf1, ofb_buf2, sizeof(ofb_buf1), ks, ks, ks,
&ofb_tmp, &num);
if (memcmp(plain, ofb_buf2, sizeof(ofb_buf2)) != 0) {
printf("ede_ofb64_encrypt decrypt error\n");
err = 1;
}
printf("Doing cbc_cksum\n");
DES_set_key_checked(&cbc_key, &ks);
cs = des_cbc_cksum(cbc_data, &cret, strlen((char *)cbc_data), ks,
&cbc_iv);
if (cs != cbc_cksum_ret) {
printf("bad return value (%08lX), should be %08lX\n",
(unsigned long)cs, (unsigned long)cbc_cksum_ret);
err = 1;
}
if (memcmp(cret, cbc_cksum_data, 8) != 0) {
printf("bad cbc_cksum block returned\n");
err = 1;
}
printf("Doing quad_cksum\n");
cs = des_quad_cksum(cbc_data, (des_cblock *)lqret,
(long)strlen((char *)cbc_data), 2,
(des_cblock *)cbc_iv);
if (cs != 0x70d7a63aL) {
printf("quad_cksum error, ret %08lx should be 70d7a63a\n",
(unsigned long)cs);
err = 1;
}
# ifdef _CRAY
if (lqret[0].a != 0x327eba8dL) {
printf("quad_cksum error, out[0] %08lx is not %08lx\n",
(unsigned long)lqret[0].a, 0x327eba8dUL);
err = 1;
}
if (lqret[0].b != 0x201a49ccL) {
printf("quad_cksum error, out[1] %08lx is not %08lx\n",
(unsigned long)lqret[0].b, 0x201a49ccUL);
err = 1;
}
if (lqret[1].a != 0x70d7a63aL) {
printf("quad_cksum error, out[2] %08lx is not %08lx\n",
(unsigned long)lqret[1].a, 0x70d7a63aUL);
err = 1;
}
if (lqret[1].b != 0x501c2c26L) {
printf("quad_cksum error, out[3] %08lx is not %08lx\n",
(unsigned long)lqret[1].b, 0x501c2c26UL);
err = 1;
}
# else
if (lqret[0] != 0x327eba8dL) {
printf("quad_cksum error, out[0] %08lx is not %08lx\n",
(unsigned long)lqret[0], 0x327eba8dUL);
err = 1;
}
if (lqret[1] != 0x201a49ccL) {
printf("quad_cksum error, out[1] %08lx is not %08lx\n",
(unsigned long)lqret[1], 0x201a49ccUL);
err = 1;
}
if (lqret[2] != 0x70d7a63aL) {
printf("quad_cksum error, out[2] %08lx is not %08lx\n",
(unsigned long)lqret[2], 0x70d7a63aUL);
err = 1;
}
if (lqret[3] != 0x501c2c26L) {
printf("quad_cksum error, out[3] %08lx is not %08lx\n",
(unsigned long)lqret[3], 0x501c2c26UL);
err = 1;
}
# endif
# endif
printf("input word alignment test");
for (i = 0; i < 4; i++) {
printf(" %d", i);
des_ncbc_encrypt(&(cbc_out[i]), cbc_in,
strlen((char *)cbc_data) + 1, ks,
&cbc_iv, DES_ENCRYPT);
}
printf("\noutput word alignment test");
for (i = 0; i < 4; i++) {
printf(" %d", i);
des_ncbc_encrypt(cbc_out, &(cbc_in[i]),
strlen((char *)cbc_data) + 1, ks,
&cbc_iv, DES_ENCRYPT);
}
printf("\n");
printf("fast crypt test ");
str = crypt("testing", "ef");
if (strcmp("efGnQx2725bI2", str) != 0) {
printf("fast crypt error, %s should be efGnQx2725bI2\n", str);
err = 1;
}
str = crypt("bca76;23", "yA");
if (strcmp("yA1Rp/1hZXIJk", str) != 0) {
printf("fast crypt error, %s should be yA1Rp/1hZXIJk\n", str);
err = 1;
}
# ifdef OPENSSL_SYS_NETWARE
if (err)
printf("ERROR: %d\n", err);
# endif
printf("\n");
return (err);
}
static char *pt(unsigned char *p)
{
static char bufs[10][20];
static int bnum = 0;
char *ret;
int i;
static char *f = "0123456789ABCDEF";
ret = &(bufs[bnum++][0]);
bnum %= 10;
for (i = 0; i < 8; i++) {
ret[i * 2] = f[(p[i] >> 4) & 0xf];
ret[i * 2 + 1] = f[p[i] & 0xf];
}
ret[16] = '\0';
return (ret);
}
# ifndef LIBDES_LIT
static int cfb_test(int bits, unsigned char *cfb_cipher)
{
des_key_schedule ks;
int i, err = 0;
DES_set_key_checked(&cfb_key, &ks);
memcpy(cfb_tmp, cfb_iv, sizeof(cfb_iv));
des_cfb_encrypt(plain, cfb_buf1, bits, sizeof(plain), ks, &cfb_tmp,
DES_ENCRYPT);
if (memcmp(cfb_cipher, cfb_buf1, sizeof(plain)) != 0) {
err = 1;
printf("cfb_encrypt encrypt error\n");
for (i = 0; i < 24; i += 8)
printf("%s\n", pt(&(cfb_buf1[i])));
}
memcpy(cfb_tmp, cfb_iv, sizeof(cfb_iv));
des_cfb_encrypt(cfb_buf1, cfb_buf2, bits, sizeof(plain), ks, &cfb_tmp,
DES_DECRYPT);
if (memcmp(plain, cfb_buf2, sizeof(plain)) != 0) {
err = 1;
printf("cfb_encrypt decrypt error\n");
for (i = 0; i < 24; i += 8)
printf("%s\n", pt(&(cfb_buf1[i])));
}
return (err);
}
static int cfb64_test(unsigned char *cfb_cipher)
{
des_key_schedule ks;
int err = 0, i, n;
DES_set_key_checked(&cfb_key, &ks);
memcpy(cfb_tmp, cfb_iv, sizeof(cfb_iv));
n = 0;
des_cfb64_encrypt(plain, cfb_buf1, 12, ks, &cfb_tmp, &n, DES_ENCRYPT);
des_cfb64_encrypt(&(plain[12]), &(cfb_buf1[12]), sizeof(plain) - 12, ks,
&cfb_tmp, &n, DES_ENCRYPT);
if (memcmp(cfb_cipher, cfb_buf1, sizeof(plain)) != 0) {
err = 1;
printf("cfb_encrypt encrypt error\n");
for (i = 0; i < 24; i += 8)
printf("%s\n", pt(&(cfb_buf1[i])));
}
memcpy(cfb_tmp, cfb_iv, sizeof(cfb_iv));
n = 0;
des_cfb64_encrypt(cfb_buf1, cfb_buf2, 17, ks, &cfb_tmp, &n, DES_DECRYPT);
des_cfb64_encrypt(&(cfb_buf1[17]), &(cfb_buf2[17]),
sizeof(plain) - 17, ks, &cfb_tmp, &n, DES_DECRYPT);
if (memcmp(plain, cfb_buf2, sizeof(plain)) != 0) {
err = 1;
printf("cfb_encrypt decrypt error\n");
for (i = 0; i < 24; i += 8)
printf("%s\n", pt(&(cfb_buf2[i])));
}
return (err);
}
static int ede_cfb64_test(unsigned char *cfb_cipher)
{
des_key_schedule ks;
int err = 0, i, n;
DES_set_key_checked(&cfb_key, &ks);
memcpy(cfb_tmp, cfb_iv, sizeof(cfb_iv));
n = 0;
des_ede3_cfb64_encrypt(plain, cfb_buf1, 12, ks, ks, ks, &cfb_tmp, &n,
DES_ENCRYPT);
des_ede3_cfb64_encrypt(&(plain[12]), &(cfb_buf1[12]),
sizeof(plain) - 12, ks, ks, ks,
&cfb_tmp, &n, DES_ENCRYPT);
if (memcmp(cfb_cipher, cfb_buf1, sizeof(plain)) != 0) {
err = 1;
printf("ede_cfb_encrypt encrypt error\n");
for (i = 0; i < 24; i += 8)
printf("%s\n", pt(&(cfb_buf1[i])));
}
memcpy(cfb_tmp, cfb_iv, sizeof(cfb_iv));
n = 0;
des_ede3_cfb64_encrypt(cfb_buf1, cfb_buf2, (long)17, ks, ks, ks,
&cfb_tmp, &n, DES_DECRYPT);
des_ede3_cfb64_encrypt(&(cfb_buf1[17]), &(cfb_buf2[17]),
sizeof(plain) - 17, ks, ks, ks,
&cfb_tmp, &n, DES_DECRYPT);
if (memcmp(plain, cfb_buf2, sizeof(plain)) != 0) {
err = 1;
printf("ede_cfb_encrypt decrypt error\n");
for (i = 0; i < 24; i += 8)
printf("%s\n", pt(&(cfb_buf2[i])));
}
return (err);
}
# endif
#endif
diff --git a/crypto/des/ecb_enc.c b/crypto/des/ecb_enc.c
index f97fd971dc20..60470d6db748 100644
--- a/crypto/des/ecb_enc.c
+++ b/crypto/des/ecb_enc.c
@@ -1,124 +1,124 @@
/* crypto/des/ecb_enc.c */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
#include "des_locl.h"
#include "des_ver.h"
#include <openssl/opensslv.h>
#include <openssl/bio.h>
OPENSSL_GLOBAL const char libdes_version[] = "libdes" OPENSSL_VERSION_PTEXT;
OPENSSL_GLOBAL const char DES_version[] = "DES" OPENSSL_VERSION_PTEXT;
const char *DES_options(void)
{
static int init = 1;
static char buf[32];
if (init) {
const char *ptr, *unroll, *risc, *size;
#ifdef DES_PTR
ptr = "ptr";
#else
ptr = "idx";
#endif
#if defined(DES_RISC1) || defined(DES_RISC2)
# ifdef DES_RISC1
risc = "risc1";
# endif
# ifdef DES_RISC2
risc = "risc2";
# endif
#else
risc = "cisc";
#endif
#ifdef DES_UNROLL
unroll = "16";
#else
unroll = "2";
#endif
if (sizeof(DES_LONG) != sizeof(long))
size = "int";
else
size = "long";
- BIO_snprintf(buf, sizeof buf, "des(%s,%s,%s,%s)", ptr, risc, unroll,
+ BIO_snprintf(buf, sizeof(buf), "des(%s,%s,%s,%s)", ptr, risc, unroll,
size);
init = 0;
}
return (buf);
}
void DES_ecb_encrypt(const_DES_cblock *input, DES_cblock *output,
DES_key_schedule *ks, int enc)
{
register DES_LONG l;
DES_LONG ll[2];
const unsigned char *in = &(*input)[0];
unsigned char *out = &(*output)[0];
c2l(in, l);
ll[0] = l;
c2l(in, l);
ll[1] = l;
DES_encrypt1(ll, ks, enc);
l = ll[0];
l2c(l, out);
l = ll[1];
l2c(l, out);
l = ll[0] = ll[1] = 0;
}
diff --git a/crypto/des/fcrypt.c b/crypto/des/fcrypt.c
index 111f1e4617ff..09f5792b1eb6 100644
--- a/crypto/des/fcrypt.c
+++ b/crypto/des/fcrypt.c
@@ -1,167 +1,167 @@
/* NOCW */
#include <stdio.h>
#ifdef _OSD_POSIX
# ifndef CHARSET_EBCDIC
# define CHARSET_EBCDIC 1
# endif
#endif
#ifdef CHARSET_EBCDIC
# include <openssl/ebcdic.h>
#endif
/*
* This version of crypt has been developed from my MIT compatible DES
* library. Eric Young (eay@cryptsoft.com)
*/
/*
* Modification by Jens Kupferschmidt (Cu) I have included directive PARA for
* shared memory computers. I have included a directive LONGCRYPT to using
* this routine to cipher passwords with more then 8 bytes like HP-UX 10.x it
* used. The MAXPLEN definition is the maximum of length of password and can
* changed. I have defined 24.
*/
#include "des_locl.h"
/*
* Added more values to handle illegal salt values the way normal crypt()
* implementations do. The patch was sent by Bjorn Gronvall <bg@sics.se>
*/
static unsigned const char con_salt[128] = {
0xD2, 0xD3, 0xD4, 0xD5, 0xD6, 0xD7, 0xD8, 0xD9,
0xDA, 0xDB, 0xDC, 0xDD, 0xDE, 0xDF, 0xE0, 0xE1,
0xE2, 0xE3, 0xE4, 0xE5, 0xE6, 0xE7, 0xE8, 0xE9,
0xEA, 0xEB, 0xEC, 0xED, 0xEE, 0xEF, 0xF0, 0xF1,
0xF2, 0xF3, 0xF4, 0xF5, 0xF6, 0xF7, 0xF8, 0xF9,
0xFA, 0xFB, 0xFC, 0xFD, 0xFE, 0xFF, 0x00, 0x01,
0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09,
0x0A, 0x0B, 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, 0x20, 0x21, 0x22, 0x23, 0x24,
0x25, 0x26, 0x27, 0x28, 0x29, 0x2A, 0x2B, 0x2C,
0x2D, 0x2E, 0x2F, 0x30, 0x31, 0x32, 0x33, 0x34,
0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, 0x3B, 0x3C,
0x3D, 0x3E, 0x3F, 0x40, 0x41, 0x42, 0x43, 0x44,
};
static unsigned const char cov_2char[64] = {
0x2E, 0x2F, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35,
0x36, 0x37, 0x38, 0x39, 0x41, 0x42, 0x43, 0x44,
0x45, 0x46, 0x47, 0x48, 0x49, 0x4A, 0x4B, 0x4C,
0x4D, 0x4E, 0x4F, 0x50, 0x51, 0x52, 0x53, 0x54,
0x55, 0x56, 0x57, 0x58, 0x59, 0x5A, 0x61, 0x62,
0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6A,
0x6B, 0x6C, 0x6D, 0x6E, 0x6F, 0x70, 0x71, 0x72,
0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7A
};
char *DES_crypt(const char *buf, const char *salt)
{
static char buff[14];
#ifndef CHARSET_EBCDIC
return (DES_fcrypt(buf, salt, buff));
#else
char e_salt[2 + 1];
char e_buf[32 + 1]; /* replace 32 by 8 ? */
char *ret;
/* Copy at most 2 chars of salt */
if ((e_salt[0] = salt[0]) != '\0')
e_salt[1] = salt[1];
/* Copy at most 32 chars of password */
strncpy(e_buf, buf, sizeof(e_buf));
/* Make sure we have a delimiter */
e_salt[sizeof(e_salt) - 1] = e_buf[sizeof(e_buf) - 1] = '\0';
/* Convert the e_salt to ASCII, as that's what DES_fcrypt works on */
- ebcdic2ascii(e_salt, e_salt, sizeof e_salt);
+ ebcdic2ascii(e_salt, e_salt, sizeof(e_salt));
/* Convert the cleartext password to ASCII */
- ebcdic2ascii(e_buf, e_buf, sizeof e_buf);
+ ebcdic2ascii(e_buf, e_buf, sizeof(e_buf));
/* Encrypt it (from/to ASCII) */
ret = DES_fcrypt(e_buf, e_salt, buff);
/* Convert the result back to EBCDIC */
ascii2ebcdic(ret, ret, strlen(ret));
return ret;
#endif
}
char *DES_fcrypt(const char *buf, const char *salt, char *ret)
{
unsigned int i, j, x, y;
DES_LONG Eswap0, Eswap1;
DES_LONG out[2], ll;
DES_cblock key;
DES_key_schedule ks;
unsigned char bb[9];
unsigned char *b = bb;
unsigned char c, u;
/*
* eay 25/08/92 If you call crypt("pwd","*") as often happens when you
* have * as the pwd field in /etc/passwd, the function returns
* *\0XXXXXXXXX The \0 makes the string look like * so the pwd "*" would
* crypt to "*". This was found when replacing the crypt in our shared
* libraries. People found that the disabled accounts effectively had no
* passwd :-(.
*/
#ifndef CHARSET_EBCDIC
x = ret[0] = ((salt[0] == '\0') ? 'A' : salt[0]);
Eswap0 = con_salt[x] << 2;
x = ret[1] = ((salt[1] == '\0') ? 'A' : salt[1]);
Eswap1 = con_salt[x] << 6;
#else
x = ret[0] = ((salt[0] == '\0') ? os_toascii['A'] : salt[0]);
Eswap0 = con_salt[x] << 2;
x = ret[1] = ((salt[1] == '\0') ? os_toascii['A'] : salt[1]);
Eswap1 = con_salt[x] << 6;
#endif
/*
* EAY r=strlen(buf); r=(r+7)/8;
*/
for (i = 0; i < 8; i++) {
c = *(buf++);
if (!c)
break;
key[i] = (c << 1);
}
for (; i < 8; i++)
key[i] = 0;
DES_set_key_unchecked(&key, &ks);
fcrypt_body(&(out[0]), &ks, Eswap0, Eswap1);
ll = out[0];
l2c(ll, b);
ll = out[1];
l2c(ll, b);
y = 0;
u = 0x80;
bb[8] = 0;
for (i = 2; i < 13; i++) {
c = 0;
for (j = 0; j < 6; j++) {
c <<= 1;
if (bb[y] & u)
c |= 1;
u >>= 1;
if (!u) {
y++;
u = 0x80;
}
}
ret[i] = cov_2char[c];
}
ret[13] = '\0';
return (ret);
}
diff --git a/crypto/des/read_pwd.c b/crypto/des/read_pwd.c
index 514a7063b4bf..080d3e8dfc4c 100644
--- a/crypto/des/read_pwd.c
+++ b/crypto/des/read_pwd.c
@@ -1,533 +1,533 @@
/* crypto/des/read_pwd.c */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
#include <openssl/e_os2.h>
#if !defined(OPENSSL_SYS_MSDOS) && !defined(OPENSSL_SYS_VMS) && !defined(OPENSSL_SYS_WIN32)
# ifdef OPENSSL_UNISTD
# include OPENSSL_UNISTD
# else
# include <unistd.h>
# endif
/*
* If unistd.h defines _POSIX_VERSION, we conclude that we are on a POSIX
* system and have sigaction and termios.
*/
# if defined(_POSIX_VERSION)
# define SIGACTION
# if !defined(TERMIOS) && !defined(TERMIO) && !defined(SGTTY)
# define TERMIOS
# endif
# endif
#endif
/* Define this if you have sigaction() */
/* #define SIGACTION */
#ifdef WIN16TTY
# undef OPENSSL_SYS_WIN16
# undef _WINDOWS
# include <graph.h>
#endif
/* 06-Apr-92 Luke Brennan Support for VMS */
#include "des_locl.h"
#include "cryptlib.h"
#include <signal.h>
#include <stdio.h>
#include <string.h>
#include <setjmp.h>
#include <errno.h>
#ifdef OPENSSL_SYS_VMS /* prototypes for sys$whatever */
# include <starlet.h>
# ifdef __DECC
# pragma message disable DOLLARID
# endif
#endif
#ifdef WIN_CONSOLE_BUG
# include <windows.h>
# ifndef OPENSSL_SYS_WINCE
# include <wincon.h>
# endif
#endif
/*
* There are 5 types of terminal interface supported, TERMIO, TERMIOS, VMS,
* MSDOS and SGTTY
*/
#if defined(__sgi) && !defined(TERMIOS)
# define TERMIOS
# undef TERMIO
# undef SGTTY
#endif
#if defined(linux) && !defined(TERMIO)
# undef TERMIOS
# define TERMIO
# undef SGTTY
#endif
#ifdef _LIBC
# undef TERMIOS
# define TERMIO
# undef SGTTY
#endif
#if !defined(TERMIO) && !defined(TERMIOS) && !defined(OPENSSL_SYS_VMS) && !defined(OPENSSL_SYS_MSDOS) && !defined(MAC_OS_pre_X) && !defined(MAC_OS_GUSI_SOURCE)
# undef TERMIOS
# undef TERMIO
# define SGTTY
#endif
#if defined(OPENSSL_SYS_VXWORKS)
# undef TERMIOS
# undef TERMIO
# undef SGTTY
#endif
#ifdef TERMIOS
# include <termios.h>
# define TTY_STRUCT struct termios
# define TTY_FLAGS c_lflag
# define TTY_get(tty,data) tcgetattr(tty,data)
# define TTY_set(tty,data) tcsetattr(tty,TCSANOW,data)
#endif
#ifdef TERMIO
# include <termio.h>
# define TTY_STRUCT struct termio
# define TTY_FLAGS c_lflag
# define TTY_get(tty,data) ioctl(tty,TCGETA,data)
# define TTY_set(tty,data) ioctl(tty,TCSETA,data)
#endif
#ifdef SGTTY
# include <sgtty.h>
# define TTY_STRUCT struct sgttyb
# define TTY_FLAGS sg_flags
# define TTY_get(tty,data) ioctl(tty,TIOCGETP,data)
# define TTY_set(tty,data) ioctl(tty,TIOCSETP,data)
#endif
#if !defined(_LIBC) && !defined(OPENSSL_SYS_MSDOS) && !defined(OPENSSL_SYS_VMS) && !defined(MAC_OS_pre_X)
# include <sys/ioctl.h>
#endif
#if defined(OPENSSL_SYS_MSDOS) && !defined(OPENSSL_SYS_WINCE)
# include <conio.h>
# define fgets(a,b,c) noecho_fgets(a,b,c)
#endif
#ifdef OPENSSL_SYS_VMS
# include <ssdef.h>
# include <iodef.h>
# include <ttdef.h>
# include <descrip.h>
struct IOSB {
short iosb$w_value;
short iosb$w_count;
long iosb$l_info;
};
#endif
#if defined(MAC_OS_pre_X) || defined(MAC_OS_GUSI_SOURCE)
/*
* This one needs work. As a matter of fact the code is unoperational
* and this is only a trick to get it compiled.
* <appro@fy.chalmers.se>
*/
# define TTY_STRUCT int
#endif
#ifndef NX509_SIG
# define NX509_SIG 32
#endif
static void read_till_nl(FILE *);
static void recsig(int);
static void pushsig(void);
static void popsig(void);
#if defined(OPENSSL_SYS_MSDOS) && !defined(OPENSSL_SYS_WIN16)
static int noecho_fgets(char *buf, int size, FILE *tty);
#endif
#ifdef SIGACTION
static struct sigaction savsig[NX509_SIG];
#else
static void (*savsig[NX509_SIG]) (int);
#endif
static jmp_buf save;
int des_read_pw_string(char *buf, int length, const char *prompt, int verify)
{
char buff[BUFSIZ];
int ret;
ret =
des_read_pw(buf, buff, (length > BUFSIZ) ? BUFSIZ : length, prompt,
verify);
OPENSSL_cleanse(buff, BUFSIZ);
return (ret);
}
#ifdef OPENSSL_SYS_WINCE
int des_read_pw(char *buf, char *buff, int size, const char *prompt,
int verify)
{
memset(buf, 0, size);
memset(buff, 0, size);
return (0);
}
#elif defined(OPENSSL_SYS_WIN16)
int des_read_pw(char *buf, char *buff, int size, char *prompt, int verify)
{
memset(buf, 0, size);
memset(buff, 0, size);
return (0);
}
#else /* !OPENSSL_SYS_WINCE && !OPENSSL_SYS_WIN16 */
static void read_till_nl(FILE *in)
{
# define SIZE 4
char buf[SIZE + 1];
do {
fgets(buf, SIZE, in);
} while (strchr(buf, '\n') == NULL);
}
/* return 0 if ok, 1 (or -1) otherwise */
int des_read_pw(char *buf, char *buff, int size, const char *prompt,
int verify)
{
# ifdef OPENSSL_SYS_VMS
struct IOSB iosb;
$DESCRIPTOR(terminal, "TT");
long tty_orig[3], tty_new[3];
long status;
unsigned short channel = 0;
# else
# if !defined(OPENSSL_SYS_MSDOS) || defined(__DJGPP__)
TTY_STRUCT tty_orig, tty_new;
# endif
# endif
int number;
int ok;
/*
* statics are simply to avoid warnings about longjmp clobbering things
*/
static int ps;
int is_a_tty;
static FILE *tty;
char *p;
if (setjmp(save)) {
ok = 0;
goto error;
}
number = 5;
ok = 0;
ps = 0;
is_a_tty = 1;
tty = NULL;
# ifdef OPENSSL_SYS_MSDOS
if ((tty = fopen("con", "r")) == NULL)
tty = stdin;
# elif defined(MAC_OS_pre_X) || defined(OPENSSL_SYS_VXWORKS)
tty = stdin;
# else
# ifndef OPENSSL_SYS_MPE
if ((tty = fopen("/dev/tty", "r")) == NULL)
# endif
tty = stdin;
# endif
# if defined(TTY_get) && !defined(OPENSSL_SYS_VMS)
if (TTY_get(fileno(tty), &tty_orig) == -1) {
# ifdef ENOTTY
if (errno == ENOTTY)
is_a_tty = 0;
else
# endif
# ifdef EINVAL
/*
* Ariel Glenn ariel@columbia.edu reports that solaris can return
* EINVAL instead. This should be ok
*/
if (errno == EINVAL)
is_a_tty = 0;
else
# endif
return (-1);
}
memcpy(&(tty_new), &(tty_orig), sizeof(tty_orig));
# endif
# ifdef OPENSSL_SYS_VMS
status = sys$assign(&terminal, &channel, 0, 0);
if (status != SS$_NORMAL)
return (-1);
status =
sys$qiow(0, channel, IO$_SENSEMODE, &iosb, 0, 0, tty_orig, 12, 0, 0,
0, 0);
if ((status != SS$_NORMAL) || (iosb.iosb$w_value != SS$_NORMAL))
return (-1);
# endif
pushsig();
ps = 1;
# ifdef TTY_FLAGS
tty_new.TTY_FLAGS &= ~ECHO;
# endif
# if defined(TTY_set) && !defined(OPENSSL_SYS_VMS)
if (is_a_tty && (TTY_set(fileno(tty), &tty_new) == -1))
# ifdef OPENSSL_SYS_MPE
; /* MPE lies -- echo really has been disabled */
# else
return (-1);
# endif
# endif
# ifdef OPENSSL_SYS_VMS
tty_new[0] = tty_orig[0];
tty_new[1] = tty_orig[1] | TT$M_NOECHO;
tty_new[2] = tty_orig[2];
status =
sys$qiow(0, channel, IO$_SETMODE, &iosb, 0, 0, tty_new, 12, 0, 0, 0,
0);
if ((status != SS$_NORMAL) || (iosb.iosb$w_value != SS$_NORMAL))
return (-1);
# endif
ps = 2;
while ((!ok) && (number--)) {
fputs(prompt, stderr);
fflush(stderr);
buf[0] = '\0';
fgets(buf, size, tty);
if (feof(tty))
goto error;
if (ferror(tty))
goto error;
if ((p = (char *)strchr(buf, '\n')) != NULL)
*p = '\0';
else
read_till_nl(tty);
if (verify) {
fprintf(stderr, "\nVerifying password - %s", prompt);
fflush(stderr);
buff[0] = '\0';
fgets(buff, size, tty);
if (feof(tty))
goto error;
if ((p = (char *)strchr(buff, '\n')) != NULL)
*p = '\0';
else
read_till_nl(tty);
if (strcmp(buf, buff) != 0) {
fprintf(stderr, "\nVerify failure");
fflush(stderr);
break;
/* continue; */
}
}
ok = 1;
}
error:
fprintf(stderr, "\n");
# if 0
perror("fgets(tty)");
# endif
/* What can we do if there is an error? */
# if defined(TTY_set) && !defined(OPENSSL_SYS_VMS)
if (ps >= 2)
TTY_set(fileno(tty), &tty_orig);
# endif
# ifdef OPENSSL_SYS_VMS
if (ps >= 2)
status =
sys$qiow(0, channel, IO$_SETMODE, &iosb, 0, 0, tty_orig, 12, 0, 0,
0, 0);
# endif
if (ps >= 1)
popsig();
if (stdin != tty)
fclose(tty);
# ifdef OPENSSL_SYS_VMS
status = sys$dassgn(channel);
# endif
return (!ok);
}
static void pushsig(void)
{
int i;
# ifdef SIGACTION
struct sigaction sa;
- memset(&sa, 0, sizeof sa);
+ memset(&sa, 0, sizeof(sa));
sa.sa_handler = recsig;
# endif
for (i = 1; i < NX509_SIG; i++) {
# ifdef SIGUSR1
if (i == SIGUSR1)
continue;
# endif
# ifdef SIGUSR2
if (i == SIGUSR2)
continue;
# endif
# ifdef SIGACTION
sigaction(i, &sa, &savsig[i]);
# else
savsig[i] = signal(i, recsig);
# endif
}
# ifdef SIGWINCH
signal(SIGWINCH, SIG_DFL);
# endif
}
static void popsig(void)
{
int i;
for (i = 1; i < NX509_SIG; i++) {
# ifdef SIGUSR1
if (i == SIGUSR1)
continue;
# endif
# ifdef SIGUSR2
if (i == SIGUSR2)
continue;
# endif
# ifdef SIGACTION
sigaction(i, &savsig[i], NULL);
# else
signal(i, savsig[i]);
# endif
}
}
static void recsig(int i)
{
longjmp(save, 1);
# ifdef LINT
i = i;
# endif
}
# ifdef OPENSSL_SYS_MSDOS
static int noecho_fgets(char *buf, int size, FILE *tty)
{
int i;
char *p;
p = buf;
for (;;) {
if (size == 0) {
*p = '\0';
break;
}
size--;
# ifdef WIN16TTY
i = _inchar();
# else
i = getch();
# endif
if (i == '\r')
i = '\n';
*(p++) = i;
if (i == '\n') {
*p = '\0';
break;
}
}
# ifdef WIN_CONSOLE_BUG
/*
* Win95 has several evil console bugs: one of these is that the last
* character read using getch() is passed to the next read: this is
* usually a CR so this can be trouble. No STDIO fix seems to work but
* flushing the console appears to do the trick.
*/
{
HANDLE inh;
inh = GetStdHandle(STD_INPUT_HANDLE);
FlushConsoleInputBuffer(inh);
}
# endif
return (strlen(buf));
}
# endif
#endif /* !OPENSSL_SYS_WINCE && !WIN16 */
diff --git a/crypto/des/set_key.c b/crypto/des/set_key.c
index d9c5e7fcb3bb..0a9ddb4baa7f 100644
--- a/crypto/des/set_key.c
+++ b/crypto/des/set_key.c
@@ -1,447 +1,447 @@
/* crypto/des/set_key.c */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
/*-
* set_key.c v 1.4 eay 24/9/91
* 1.4 Speed up by 400% :-)
* 1.3 added register declarations.
* 1.2 unrolled make_key_sched a bit more
* 1.1 added norm_expand_bits
* 1.0 First working version
*/
#include <openssl/crypto.h>
#include "des_locl.h"
OPENSSL_IMPLEMENT_GLOBAL(int, DES_check_key, 0)
/*
* defaults to false
*/
static const unsigned char odd_parity[256] = {
1, 1, 2, 2, 4, 4, 7, 7, 8, 8, 11, 11, 13, 13, 14, 14,
16, 16, 19, 19, 21, 21, 22, 22, 25, 25, 26, 26, 28, 28, 31, 31,
32, 32, 35, 35, 37, 37, 38, 38, 41, 41, 42, 42, 44, 44, 47, 47,
49, 49, 50, 50, 52, 52, 55, 55, 56, 56, 59, 59, 61, 61, 62, 62,
64, 64, 67, 67, 69, 69, 70, 70, 73, 73, 74, 74, 76, 76, 79, 79,
81, 81, 82, 82, 84, 84, 87, 87, 88, 88, 91, 91, 93, 93, 94, 94,
97, 97, 98, 98, 100, 100, 103, 103, 104, 104, 107, 107, 109, 109, 110,
110,
112, 112, 115, 115, 117, 117, 118, 118, 121, 121, 122, 122, 124, 124, 127,
127,
128, 128, 131, 131, 133, 133, 134, 134, 137, 137, 138, 138, 140, 140, 143,
143,
145, 145, 146, 146, 148, 148, 151, 151, 152, 152, 155, 155, 157, 157, 158,
158,
161, 161, 162, 162, 164, 164, 167, 167, 168, 168, 171, 171, 173, 173, 174,
174,
176, 176, 179, 179, 181, 181, 182, 182, 185, 185, 186, 186, 188, 188, 191,
191,
193, 193, 194, 194, 196, 196, 199, 199, 200, 200, 203, 203, 205, 205, 206,
206,
208, 208, 211, 211, 213, 213, 214, 214, 217, 217, 218, 218, 220, 220, 223,
223,
224, 224, 227, 227, 229, 229, 230, 230, 233, 233, 234, 234, 236, 236, 239,
239,
241, 241, 242, 242, 244, 244, 247, 247, 248, 248, 251, 251, 253, 253, 254,
254
};
void DES_set_odd_parity(DES_cblock *key)
{
unsigned int i;
for (i = 0; i < DES_KEY_SZ; i++)
(*key)[i] = odd_parity[(*key)[i]];
}
int DES_check_key_parity(const_DES_cblock *key)
{
unsigned int i;
for (i = 0; i < DES_KEY_SZ; i++) {
if ((*key)[i] != odd_parity[(*key)[i]])
return (0);
}
return (1);
}
/*-
* Weak and semi weak keys as taken from
* %A D.W. Davies
* %A W.L. Price
* %T Security for Computer Networks
* %I John Wiley & Sons
* %D 1984
* Many thanks to smb@ulysses.att.com (Steven Bellovin) for the reference
* (and actual cblock values).
*/
#define NUM_WEAK_KEY 16
static const DES_cblock weak_keys[NUM_WEAK_KEY] = {
/* weak keys */
{0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01},
{0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE},
{0x1F, 0x1F, 0x1F, 0x1F, 0x0E, 0x0E, 0x0E, 0x0E},
{0xE0, 0xE0, 0xE0, 0xE0, 0xF1, 0xF1, 0xF1, 0xF1},
/* semi-weak keys */
{0x01, 0xFE, 0x01, 0xFE, 0x01, 0xFE, 0x01, 0xFE},
{0xFE, 0x01, 0xFE, 0x01, 0xFE, 0x01, 0xFE, 0x01},
{0x1F, 0xE0, 0x1F, 0xE0, 0x0E, 0xF1, 0x0E, 0xF1},
{0xE0, 0x1F, 0xE0, 0x1F, 0xF1, 0x0E, 0xF1, 0x0E},
{0x01, 0xE0, 0x01, 0xE0, 0x01, 0xF1, 0x01, 0xF1},
{0xE0, 0x01, 0xE0, 0x01, 0xF1, 0x01, 0xF1, 0x01},
{0x1F, 0xFE, 0x1F, 0xFE, 0x0E, 0xFE, 0x0E, 0xFE},
{0xFE, 0x1F, 0xFE, 0x1F, 0xFE, 0x0E, 0xFE, 0x0E},
{0x01, 0x1F, 0x01, 0x1F, 0x01, 0x0E, 0x01, 0x0E},
{0x1F, 0x01, 0x1F, 0x01, 0x0E, 0x01, 0x0E, 0x01},
{0xE0, 0xFE, 0xE0, 0xFE, 0xF1, 0xFE, 0xF1, 0xFE},
{0xFE, 0xE0, 0xFE, 0xE0, 0xFE, 0xF1, 0xFE, 0xF1}
};
int DES_is_weak_key(const_DES_cblock *key)
{
int i;
for (i = 0; i < NUM_WEAK_KEY; i++)
/*
* Added == 0 to comparison, I obviously don't run this section very
* often :-(, thanks to engineering@MorningStar.Com for the fix eay
* 93/06/29 Another problem, I was comparing only the first 4 bytes,
* 97/03/18
*/
if (memcmp(weak_keys[i], key, sizeof(DES_cblock)) == 0)
return (1);
return (0);
}
/*-
* NOW DEFINED IN des_local.h
* See ecb_encrypt.c for a pseudo description of these macros.
* #define PERM_OP(a,b,t,n,m) ((t)=((((a)>>(n))^(b))&(m)),\
* (b)^=(t),\
* (a)=((a)^((t)<<(n))))
*/
#define HPERM_OP(a,t,n,m) ((t)=((((a)<<(16-(n)))^(a))&(m)),\
(a)=(a)^(t)^(t>>(16-(n))))
static const DES_LONG des_skb[8][64] = {
{
/* for C bits (numbered as per FIPS 46) 1 2 3 4 5 6 */
0x00000000L, 0x00000010L, 0x20000000L, 0x20000010L,
0x00010000L, 0x00010010L, 0x20010000L, 0x20010010L,
0x00000800L, 0x00000810L, 0x20000800L, 0x20000810L,
0x00010800L, 0x00010810L, 0x20010800L, 0x20010810L,
0x00000020L, 0x00000030L, 0x20000020L, 0x20000030L,
0x00010020L, 0x00010030L, 0x20010020L, 0x20010030L,
0x00000820L, 0x00000830L, 0x20000820L, 0x20000830L,
0x00010820L, 0x00010830L, 0x20010820L, 0x20010830L,
0x00080000L, 0x00080010L, 0x20080000L, 0x20080010L,
0x00090000L, 0x00090010L, 0x20090000L, 0x20090010L,
0x00080800L, 0x00080810L, 0x20080800L, 0x20080810L,
0x00090800L, 0x00090810L, 0x20090800L, 0x20090810L,
0x00080020L, 0x00080030L, 0x20080020L, 0x20080030L,
0x00090020L, 0x00090030L, 0x20090020L, 0x20090030L,
0x00080820L, 0x00080830L, 0x20080820L, 0x20080830L,
0x00090820L, 0x00090830L, 0x20090820L, 0x20090830L,
},
{
/* for C bits (numbered as per FIPS 46) 7 8 10 11 12 13 */
0x00000000L, 0x02000000L, 0x00002000L, 0x02002000L,
0x00200000L, 0x02200000L, 0x00202000L, 0x02202000L,
0x00000004L, 0x02000004L, 0x00002004L, 0x02002004L,
0x00200004L, 0x02200004L, 0x00202004L, 0x02202004L,
0x00000400L, 0x02000400L, 0x00002400L, 0x02002400L,
0x00200400L, 0x02200400L, 0x00202400L, 0x02202400L,
0x00000404L, 0x02000404L, 0x00002404L, 0x02002404L,
0x00200404L, 0x02200404L, 0x00202404L, 0x02202404L,
0x10000000L, 0x12000000L, 0x10002000L, 0x12002000L,
0x10200000L, 0x12200000L, 0x10202000L, 0x12202000L,
0x10000004L, 0x12000004L, 0x10002004L, 0x12002004L,
0x10200004L, 0x12200004L, 0x10202004L, 0x12202004L,
0x10000400L, 0x12000400L, 0x10002400L, 0x12002400L,
0x10200400L, 0x12200400L, 0x10202400L, 0x12202400L,
0x10000404L, 0x12000404L, 0x10002404L, 0x12002404L,
0x10200404L, 0x12200404L, 0x10202404L, 0x12202404L,
},
{
/* for C bits (numbered as per FIPS 46) 14 15 16 17 19 20 */
0x00000000L, 0x00000001L, 0x00040000L, 0x00040001L,
0x01000000L, 0x01000001L, 0x01040000L, 0x01040001L,
0x00000002L, 0x00000003L, 0x00040002L, 0x00040003L,
0x01000002L, 0x01000003L, 0x01040002L, 0x01040003L,
0x00000200L, 0x00000201L, 0x00040200L, 0x00040201L,
0x01000200L, 0x01000201L, 0x01040200L, 0x01040201L,
0x00000202L, 0x00000203L, 0x00040202L, 0x00040203L,
0x01000202L, 0x01000203L, 0x01040202L, 0x01040203L,
0x08000000L, 0x08000001L, 0x08040000L, 0x08040001L,
0x09000000L, 0x09000001L, 0x09040000L, 0x09040001L,
0x08000002L, 0x08000003L, 0x08040002L, 0x08040003L,
0x09000002L, 0x09000003L, 0x09040002L, 0x09040003L,
0x08000200L, 0x08000201L, 0x08040200L, 0x08040201L,
0x09000200L, 0x09000201L, 0x09040200L, 0x09040201L,
0x08000202L, 0x08000203L, 0x08040202L, 0x08040203L,
0x09000202L, 0x09000203L, 0x09040202L, 0x09040203L,
},
{
/* for C bits (numbered as per FIPS 46) 21 23 24 26 27 28 */
0x00000000L, 0x00100000L, 0x00000100L, 0x00100100L,
0x00000008L, 0x00100008L, 0x00000108L, 0x00100108L,
0x00001000L, 0x00101000L, 0x00001100L, 0x00101100L,
0x00001008L, 0x00101008L, 0x00001108L, 0x00101108L,
0x04000000L, 0x04100000L, 0x04000100L, 0x04100100L,
0x04000008L, 0x04100008L, 0x04000108L, 0x04100108L,
0x04001000L, 0x04101000L, 0x04001100L, 0x04101100L,
0x04001008L, 0x04101008L, 0x04001108L, 0x04101108L,
0x00020000L, 0x00120000L, 0x00020100L, 0x00120100L,
0x00020008L, 0x00120008L, 0x00020108L, 0x00120108L,
0x00021000L, 0x00121000L, 0x00021100L, 0x00121100L,
0x00021008L, 0x00121008L, 0x00021108L, 0x00121108L,
0x04020000L, 0x04120000L, 0x04020100L, 0x04120100L,
0x04020008L, 0x04120008L, 0x04020108L, 0x04120108L,
0x04021000L, 0x04121000L, 0x04021100L, 0x04121100L,
0x04021008L, 0x04121008L, 0x04021108L, 0x04121108L,
},
{
/* for D bits (numbered as per FIPS 46) 1 2 3 4 5 6 */
0x00000000L, 0x10000000L, 0x00010000L, 0x10010000L,
0x00000004L, 0x10000004L, 0x00010004L, 0x10010004L,
0x20000000L, 0x30000000L, 0x20010000L, 0x30010000L,
0x20000004L, 0x30000004L, 0x20010004L, 0x30010004L,
0x00100000L, 0x10100000L, 0x00110000L, 0x10110000L,
0x00100004L, 0x10100004L, 0x00110004L, 0x10110004L,
0x20100000L, 0x30100000L, 0x20110000L, 0x30110000L,
0x20100004L, 0x30100004L, 0x20110004L, 0x30110004L,
0x00001000L, 0x10001000L, 0x00011000L, 0x10011000L,
0x00001004L, 0x10001004L, 0x00011004L, 0x10011004L,
0x20001000L, 0x30001000L, 0x20011000L, 0x30011000L,
0x20001004L, 0x30001004L, 0x20011004L, 0x30011004L,
0x00101000L, 0x10101000L, 0x00111000L, 0x10111000L,
0x00101004L, 0x10101004L, 0x00111004L, 0x10111004L,
0x20101000L, 0x30101000L, 0x20111000L, 0x30111000L,
0x20101004L, 0x30101004L, 0x20111004L, 0x30111004L,
},
{
/* for D bits (numbered as per FIPS 46) 8 9 11 12 13 14 */
0x00000000L, 0x08000000L, 0x00000008L, 0x08000008L,
0x00000400L, 0x08000400L, 0x00000408L, 0x08000408L,
0x00020000L, 0x08020000L, 0x00020008L, 0x08020008L,
0x00020400L, 0x08020400L, 0x00020408L, 0x08020408L,
0x00000001L, 0x08000001L, 0x00000009L, 0x08000009L,
0x00000401L, 0x08000401L, 0x00000409L, 0x08000409L,
0x00020001L, 0x08020001L, 0x00020009L, 0x08020009L,
0x00020401L, 0x08020401L, 0x00020409L, 0x08020409L,
0x02000000L, 0x0A000000L, 0x02000008L, 0x0A000008L,
0x02000400L, 0x0A000400L, 0x02000408L, 0x0A000408L,
0x02020000L, 0x0A020000L, 0x02020008L, 0x0A020008L,
0x02020400L, 0x0A020400L, 0x02020408L, 0x0A020408L,
0x02000001L, 0x0A000001L, 0x02000009L, 0x0A000009L,
0x02000401L, 0x0A000401L, 0x02000409L, 0x0A000409L,
0x02020001L, 0x0A020001L, 0x02020009L, 0x0A020009L,
0x02020401L, 0x0A020401L, 0x02020409L, 0x0A020409L,
},
{
/* for D bits (numbered as per FIPS 46) 16 17 18 19 20 21 */
0x00000000L, 0x00000100L, 0x00080000L, 0x00080100L,
0x01000000L, 0x01000100L, 0x01080000L, 0x01080100L,
0x00000010L, 0x00000110L, 0x00080010L, 0x00080110L,
0x01000010L, 0x01000110L, 0x01080010L, 0x01080110L,
0x00200000L, 0x00200100L, 0x00280000L, 0x00280100L,
0x01200000L, 0x01200100L, 0x01280000L, 0x01280100L,
0x00200010L, 0x00200110L, 0x00280010L, 0x00280110L,
0x01200010L, 0x01200110L, 0x01280010L, 0x01280110L,
0x00000200L, 0x00000300L, 0x00080200L, 0x00080300L,
0x01000200L, 0x01000300L, 0x01080200L, 0x01080300L,
0x00000210L, 0x00000310L, 0x00080210L, 0x00080310L,
0x01000210L, 0x01000310L, 0x01080210L, 0x01080310L,
0x00200200L, 0x00200300L, 0x00280200L, 0x00280300L,
0x01200200L, 0x01200300L, 0x01280200L, 0x01280300L,
0x00200210L, 0x00200310L, 0x00280210L, 0x00280310L,
0x01200210L, 0x01200310L, 0x01280210L, 0x01280310L,
},
{
/* for D bits (numbered as per FIPS 46) 22 23 24 25 27 28 */
0x00000000L, 0x04000000L, 0x00040000L, 0x04040000L,
0x00000002L, 0x04000002L, 0x00040002L, 0x04040002L,
0x00002000L, 0x04002000L, 0x00042000L, 0x04042000L,
0x00002002L, 0x04002002L, 0x00042002L, 0x04042002L,
0x00000020L, 0x04000020L, 0x00040020L, 0x04040020L,
0x00000022L, 0x04000022L, 0x00040022L, 0x04040022L,
0x00002020L, 0x04002020L, 0x00042020L, 0x04042020L,
0x00002022L, 0x04002022L, 0x00042022L, 0x04042022L,
0x00000800L, 0x04000800L, 0x00040800L, 0x04040800L,
0x00000802L, 0x04000802L, 0x00040802L, 0x04040802L,
0x00002800L, 0x04002800L, 0x00042800L, 0x04042800L,
0x00002802L, 0x04002802L, 0x00042802L, 0x04042802L,
0x00000820L, 0x04000820L, 0x00040820L, 0x04040820L,
0x00000822L, 0x04000822L, 0x00040822L, 0x04040822L,
0x00002820L, 0x04002820L, 0x00042820L, 0x04042820L,
0x00002822L, 0x04002822L, 0x00042822L, 0x04042822L,
}
};
int DES_set_key(const_DES_cblock *key, DES_key_schedule *schedule)
{
if (DES_check_key) {
return DES_set_key_checked(key, schedule);
} else {
DES_set_key_unchecked(key, schedule);
return 0;
}
}
/*-
* return 0 if key parity is odd (correct),
* return -1 if key parity error,
* return -2 if illegal weak key.
*/
int DES_set_key_checked(const_DES_cblock *key, DES_key_schedule *schedule)
{
if (!DES_check_key_parity(key))
return (-1);
if (DES_is_weak_key(key))
return (-2);
DES_set_key_unchecked(key, schedule);
return 0;
}
void DES_set_key_unchecked(const_DES_cblock *key, DES_key_schedule *schedule)
#ifdef OPENSSL_FIPS
{
fips_cipher_abort(DES);
private_DES_set_key_unchecked(key, schedule);
}
void private_DES_set_key_unchecked(const_DES_cblock *key,
DES_key_schedule *schedule)
#endif
{
static const int shifts2[16] =
{ 0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0 };
register DES_LONG c, d, t, s, t2;
register const unsigned char *in;
register DES_LONG *k;
register int i;
#ifdef OPENBSD_DEV_CRYPTO
- memcpy(schedule->key, key, sizeof schedule->key);
+ memcpy(schedule->key, key, sizeof(schedule->key));
schedule->session = NULL;
#endif
k = &schedule->ks->deslong[0];
in = &(*key)[0];
c2l(in, c);
c2l(in, d);
/*
* do PC1 in 47 simple operations :-) Thanks to John Fletcher
* (john_fletcher@lccmail.ocf.llnl.gov) for the inspiration. :-)
*/
PERM_OP(d, c, t, 4, 0x0f0f0f0fL);
HPERM_OP(c, t, -2, 0xcccc0000L);
HPERM_OP(d, t, -2, 0xcccc0000L);
PERM_OP(d, c, t, 1, 0x55555555L);
PERM_OP(c, d, t, 8, 0x00ff00ffL);
PERM_OP(d, c, t, 1, 0x55555555L);
d = (((d & 0x000000ffL) << 16L) | (d & 0x0000ff00L) |
((d & 0x00ff0000L) >> 16L) | ((c & 0xf0000000L) >> 4L));
c &= 0x0fffffffL;
for (i = 0; i < ITERATIONS; i++) {
if (shifts2[i]) {
c = ((c >> 2L) | (c << 26L));
d = ((d >> 2L) | (d << 26L));
} else {
c = ((c >> 1L) | (c << 27L));
d = ((d >> 1L) | (d << 27L));
}
c &= 0x0fffffffL;
d &= 0x0fffffffL;
/*
* could be a few less shifts but I am to lazy at this point in time
* to investigate
*/
s = des_skb[0][(c) & 0x3f] |
des_skb[1][((c >> 6L) & 0x03) | ((c >> 7L) & 0x3c)] |
des_skb[2][((c >> 13L) & 0x0f) | ((c >> 14L) & 0x30)] |
des_skb[3][((c >> 20L) & 0x01) | ((c >> 21L) & 0x06) |
((c >> 22L) & 0x38)];
t = des_skb[4][(d) & 0x3f] |
des_skb[5][((d >> 7L) & 0x03) | ((d >> 8L) & 0x3c)] |
des_skb[6][(d >> 15L) & 0x3f] |
des_skb[7][((d >> 21L) & 0x0f) | ((d >> 22L) & 0x30)];
/* table contained 0213 4657 */
t2 = ((t << 16L) | (s & 0x0000ffffL)) & 0xffffffffL;
*(k++) = ROTATE(t2, 30) & 0xffffffffL;
t2 = ((s >> 16L) | (t & 0xffff0000L));
*(k++) = ROTATE(t2, 26) & 0xffffffffL;
}
}
int DES_key_sched(const_DES_cblock *key, DES_key_schedule *schedule)
{
return (DES_set_key(key, schedule));
}
/*-
#undef des_fixup_key_parity
void des_fixup_key_parity(des_cblock *key)
{
des_set_odd_parity(key);
}
*/
diff --git a/crypto/dh/dhtest.c b/crypto/dh/dhtest.c
index c5d3d87ea549..cb83109c4051 100644
--- a/crypto/dh/dhtest.c
+++ b/crypto/dh/dhtest.c
@@ -1,643 +1,643 @@
/* crypto/dh/dhtest.c */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
/*
* Until the key-gen callbacks are modified to use newer prototypes, we allow
* deprecated functions for openssl-internal code
*/
#ifdef OPENSSL_NO_DEPRECATED
# undef OPENSSL_NO_DEPRECATED
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "../e_os.h"
#include <openssl/crypto.h>
#include <openssl/bio.h>
#include <openssl/bn.h>
#include <openssl/rand.h>
#include <openssl/err.h>
#ifdef OPENSSL_NO_DH
int main(int argc, char *argv[])
{
printf("No DH support\n");
return (0);
}
#else
# include <openssl/dh.h>
# ifdef OPENSSL_SYS_WIN16
# define MS_CALLBACK _far _loadds
# else
# define MS_CALLBACK
# endif
static int MS_CALLBACK cb(int p, int n, BN_GENCB *arg);
static const char rnd_seed[] =
"string to make the random number generator think it has entropy";
static int run_rfc5114_tests(void);
int main(int argc, char *argv[])
{
BN_GENCB _cb;
DH *a;
DH *b = NULL;
char buf[12];
unsigned char *abuf = NULL, *bbuf = NULL;
int i, alen, blen, aout, bout, ret = 1;
BIO *out;
CRYPTO_malloc_debug_init();
CRYPTO_dbg_set_options(V_CRYPTO_MDEBUG_ALL);
CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON);
# ifdef OPENSSL_SYS_WIN32
CRYPTO_malloc_init();
# endif
- RAND_seed(rnd_seed, sizeof rnd_seed);
+ RAND_seed(rnd_seed, sizeof(rnd_seed));
out = BIO_new(BIO_s_file());
if (out == NULL)
EXIT(1);
BIO_set_fp(out, stdout, BIO_NOCLOSE);
BN_GENCB_set(&_cb, &cb, out);
if (((a = DH_new()) == NULL) || !DH_generate_parameters_ex(a, 64,
DH_GENERATOR_5,
&_cb))
goto err;
if (!DH_check(a, &i))
goto err;
if (i & DH_CHECK_P_NOT_PRIME)
BIO_puts(out, "p value is not prime\n");
if (i & DH_CHECK_P_NOT_SAFE_PRIME)
BIO_puts(out, "p value is not a safe prime\n");
if (i & DH_UNABLE_TO_CHECK_GENERATOR)
BIO_puts(out, "unable to check the generator value\n");
if (i & DH_NOT_SUITABLE_GENERATOR)
BIO_puts(out, "the g value is not a generator\n");
BIO_puts(out, "\np =");
BN_print(out, a->p);
BIO_puts(out, "\ng =");
BN_print(out, a->g);
BIO_puts(out, "\n");
b = DH_new();
if (b == NULL)
goto err;
b->p = BN_dup(a->p);
b->g = BN_dup(a->g);
if ((b->p == NULL) || (b->g == NULL))
goto err;
/* Set a to run with normal modexp and b to use constant time */
a->flags &= ~DH_FLAG_NO_EXP_CONSTTIME;
b->flags |= DH_FLAG_NO_EXP_CONSTTIME;
if (!DH_generate_key(a))
goto err;
BIO_puts(out, "pri 1=");
BN_print(out, a->priv_key);
BIO_puts(out, "\npub 1=");
BN_print(out, a->pub_key);
BIO_puts(out, "\n");
if (!DH_generate_key(b))
goto err;
BIO_puts(out, "pri 2=");
BN_print(out, b->priv_key);
BIO_puts(out, "\npub 2=");
BN_print(out, b->pub_key);
BIO_puts(out, "\n");
alen = DH_size(a);
abuf = (unsigned char *)OPENSSL_malloc(alen);
aout = DH_compute_key(abuf, b->pub_key, a);
BIO_puts(out, "key1 =");
for (i = 0; i < aout; i++) {
sprintf(buf, "%02X", abuf[i]);
BIO_puts(out, buf);
}
BIO_puts(out, "\n");
blen = DH_size(b);
bbuf = (unsigned char *)OPENSSL_malloc(blen);
bout = DH_compute_key(bbuf, a->pub_key, b);
BIO_puts(out, "key2 =");
for (i = 0; i < bout; i++) {
sprintf(buf, "%02X", bbuf[i]);
BIO_puts(out, buf);
}
BIO_puts(out, "\n");
if ((aout < 4) || (bout != aout) || (memcmp(abuf, bbuf, aout) != 0)) {
fprintf(stderr, "Error in DH routines\n");
ret = 1;
} else
ret = 0;
if (!run_rfc5114_tests())
ret = 1;
err:
ERR_print_errors_fp(stderr);
if (abuf != NULL)
OPENSSL_free(abuf);
if (bbuf != NULL)
OPENSSL_free(bbuf);
if (b != NULL)
DH_free(b);
if (a != NULL)
DH_free(a);
BIO_free(out);
# ifdef OPENSSL_SYS_NETWARE
if (ret)
printf("ERROR: %d\n", ret);
# endif
EXIT(ret);
return (ret);
}
static int MS_CALLBACK cb(int p, int n, BN_GENCB *arg)
{
char c = '*';
if (p == 0)
c = '.';
if (p == 1)
c = '+';
if (p == 2)
c = '*';
if (p == 3)
c = '\n';
BIO_write(arg->arg, &c, 1);
(void)BIO_flush(arg->arg);
# ifdef LINT
p = n;
# endif
return 1;
}
/* Test data from RFC 5114 */
static const unsigned char dhtest_1024_160_xA[] = {
0xB9, 0xA3, 0xB3, 0xAE, 0x8F, 0xEF, 0xC1, 0xA2, 0x93, 0x04, 0x96, 0x50,
0x70, 0x86, 0xF8, 0x45, 0x5D, 0x48, 0x94, 0x3E
};
static const unsigned char dhtest_1024_160_yA[] = {
0x2A, 0x85, 0x3B, 0x3D, 0x92, 0x19, 0x75, 0x01, 0xB9, 0x01, 0x5B, 0x2D,
0xEB, 0x3E, 0xD8, 0x4F, 0x5E, 0x02, 0x1D, 0xCC, 0x3E, 0x52, 0xF1, 0x09,
0xD3, 0x27, 0x3D, 0x2B, 0x75, 0x21, 0x28, 0x1C, 0xBA, 0xBE, 0x0E, 0x76,
0xFF, 0x57, 0x27, 0xFA, 0x8A, 0xCC, 0xE2, 0x69, 0x56, 0xBA, 0x9A, 0x1F,
0xCA, 0x26, 0xF2, 0x02, 0x28, 0xD8, 0x69, 0x3F, 0xEB, 0x10, 0x84, 0x1D,
0x84, 0xA7, 0x36, 0x00, 0x54, 0xEC, 0xE5, 0xA7, 0xF5, 0xB7, 0xA6, 0x1A,
0xD3, 0xDF, 0xB3, 0xC6, 0x0D, 0x2E, 0x43, 0x10, 0x6D, 0x87, 0x27, 0xDA,
0x37, 0xDF, 0x9C, 0xCE, 0x95, 0xB4, 0x78, 0x75, 0x5D, 0x06, 0xBC, 0xEA,
0x8F, 0x9D, 0x45, 0x96, 0x5F, 0x75, 0xA5, 0xF3, 0xD1, 0xDF, 0x37, 0x01,
0x16, 0x5F, 0xC9, 0xE5, 0x0C, 0x42, 0x79, 0xCE, 0xB0, 0x7F, 0x98, 0x95,
0x40, 0xAE, 0x96, 0xD5, 0xD8, 0x8E, 0xD7, 0x76
};
static const unsigned char dhtest_1024_160_xB[] = {
0x93, 0x92, 0xC9, 0xF9, 0xEB, 0x6A, 0x7A, 0x6A, 0x90, 0x22, 0xF7, 0xD8,
0x3E, 0x72, 0x23, 0xC6, 0x83, 0x5B, 0xBD, 0xDA
};
static const unsigned char dhtest_1024_160_yB[] = {
0x71, 0x7A, 0x6C, 0xB0, 0x53, 0x37, 0x1F, 0xF4, 0xA3, 0xB9, 0x32, 0x94,
0x1C, 0x1E, 0x56, 0x63, 0xF8, 0x61, 0xA1, 0xD6, 0xAD, 0x34, 0xAE, 0x66,
0x57, 0x6D, 0xFB, 0x98, 0xF6, 0xC6, 0xCB, 0xF9, 0xDD, 0xD5, 0xA5, 0x6C,
0x78, 0x33, 0xF6, 0xBC, 0xFD, 0xFF, 0x09, 0x55, 0x82, 0xAD, 0x86, 0x8E,
0x44, 0x0E, 0x8D, 0x09, 0xFD, 0x76, 0x9E, 0x3C, 0xEC, 0xCD, 0xC3, 0xD3,
0xB1, 0xE4, 0xCF, 0xA0, 0x57, 0x77, 0x6C, 0xAA, 0xF9, 0x73, 0x9B, 0x6A,
0x9F, 0xEE, 0x8E, 0x74, 0x11, 0xF8, 0xD6, 0xDA, 0xC0, 0x9D, 0x6A, 0x4E,
0xDB, 0x46, 0xCC, 0x2B, 0x5D, 0x52, 0x03, 0x09, 0x0E, 0xAE, 0x61, 0x26,
0x31, 0x1E, 0x53, 0xFD, 0x2C, 0x14, 0xB5, 0x74, 0xE6, 0xA3, 0x10, 0x9A,
0x3D, 0xA1, 0xBE, 0x41, 0xBD, 0xCE, 0xAA, 0x18, 0x6F, 0x5C, 0xE0, 0x67,
0x16, 0xA2, 0xB6, 0xA0, 0x7B, 0x3C, 0x33, 0xFE
};
static const unsigned char dhtest_1024_160_Z[] = {
0x5C, 0x80, 0x4F, 0x45, 0x4D, 0x30, 0xD9, 0xC4, 0xDF, 0x85, 0x27, 0x1F,
0x93, 0x52, 0x8C, 0x91, 0xDF, 0x6B, 0x48, 0xAB, 0x5F, 0x80, 0xB3, 0xB5,
0x9C, 0xAA, 0xC1, 0xB2, 0x8F, 0x8A, 0xCB, 0xA9, 0xCD, 0x3E, 0x39, 0xF3,
0xCB, 0x61, 0x45, 0x25, 0xD9, 0x52, 0x1D, 0x2E, 0x64, 0x4C, 0x53, 0xB8,
0x07, 0xB8, 0x10, 0xF3, 0x40, 0x06, 0x2F, 0x25, 0x7D, 0x7D, 0x6F, 0xBF,
0xE8, 0xD5, 0xE8, 0xF0, 0x72, 0xE9, 0xB6, 0xE9, 0xAF, 0xDA, 0x94, 0x13,
0xEA, 0xFB, 0x2E, 0x8B, 0x06, 0x99, 0xB1, 0xFB, 0x5A, 0x0C, 0xAC, 0xED,
0xDE, 0xAE, 0xAD, 0x7E, 0x9C, 0xFB, 0xB3, 0x6A, 0xE2, 0xB4, 0x20, 0x83,
0x5B, 0xD8, 0x3A, 0x19, 0xFB, 0x0B, 0x5E, 0x96, 0xBF, 0x8F, 0xA4, 0xD0,
0x9E, 0x34, 0x55, 0x25, 0x16, 0x7E, 0xCD, 0x91, 0x55, 0x41, 0x6F, 0x46,
0xF4, 0x08, 0xED, 0x31, 0xB6, 0x3C, 0x6E, 0x6D
};
static const unsigned char dhtest_2048_224_xA[] = {
0x22, 0xE6, 0x26, 0x01, 0xDB, 0xFF, 0xD0, 0x67, 0x08, 0xA6, 0x80, 0xF7,
0x47, 0xF3, 0x61, 0xF7, 0x6D, 0x8F, 0x4F, 0x72, 0x1A, 0x05, 0x48, 0xE4,
0x83, 0x29, 0x4B, 0x0C
};
static const unsigned char dhtest_2048_224_yA[] = {
0x1B, 0x3A, 0x63, 0x45, 0x1B, 0xD8, 0x86, 0xE6, 0x99, 0xE6, 0x7B, 0x49,
0x4E, 0x28, 0x8B, 0xD7, 0xF8, 0xE0, 0xD3, 0x70, 0xBA, 0xDD, 0xA7, 0xA0,
0xEF, 0xD2, 0xFD, 0xE7, 0xD8, 0xF6, 0x61, 0x45, 0xCC, 0x9F, 0x28, 0x04,
0x19, 0x97, 0x5E, 0xB8, 0x08, 0x87, 0x7C, 0x8A, 0x4C, 0x0C, 0x8E, 0x0B,
0xD4, 0x8D, 0x4A, 0x54, 0x01, 0xEB, 0x1E, 0x87, 0x76, 0xBF, 0xEE, 0xE1,
0x34, 0xC0, 0x38, 0x31, 0xAC, 0x27, 0x3C, 0xD9, 0xD6, 0x35, 0xAB, 0x0C,
0xE0, 0x06, 0xA4, 0x2A, 0x88, 0x7E, 0x3F, 0x52, 0xFB, 0x87, 0x66, 0xB6,
0x50, 0xF3, 0x80, 0x78, 0xBC, 0x8E, 0xE8, 0x58, 0x0C, 0xEF, 0xE2, 0x43,
0x96, 0x8C, 0xFC, 0x4F, 0x8D, 0xC3, 0xDB, 0x08, 0x45, 0x54, 0x17, 0x1D,
0x41, 0xBF, 0x2E, 0x86, 0x1B, 0x7B, 0xB4, 0xD6, 0x9D, 0xD0, 0xE0, 0x1E,
0xA3, 0x87, 0xCB, 0xAA, 0x5C, 0xA6, 0x72, 0xAF, 0xCB, 0xE8, 0xBD, 0xB9,
0xD6, 0x2D, 0x4C, 0xE1, 0x5F, 0x17, 0xDD, 0x36, 0xF9, 0x1E, 0xD1, 0xEE,
0xDD, 0x65, 0xCA, 0x4A, 0x06, 0x45, 0x5C, 0xB9, 0x4C, 0xD4, 0x0A, 0x52,
0xEC, 0x36, 0x0E, 0x84, 0xB3, 0xC9, 0x26, 0xE2, 0x2C, 0x43, 0x80, 0xA3,
0xBF, 0x30, 0x9D, 0x56, 0x84, 0x97, 0x68, 0xB7, 0xF5, 0x2C, 0xFD, 0xF6,
0x55, 0xFD, 0x05, 0x3A, 0x7E, 0xF7, 0x06, 0x97, 0x9E, 0x7E, 0x58, 0x06,
0xB1, 0x7D, 0xFA, 0xE5, 0x3A, 0xD2, 0xA5, 0xBC, 0x56, 0x8E, 0xBB, 0x52,
0x9A, 0x7A, 0x61, 0xD6, 0x8D, 0x25, 0x6F, 0x8F, 0xC9, 0x7C, 0x07, 0x4A,
0x86, 0x1D, 0x82, 0x7E, 0x2E, 0xBC, 0x8C, 0x61, 0x34, 0x55, 0x31, 0x15,
0xB7, 0x0E, 0x71, 0x03, 0x92, 0x0A, 0xA1, 0x6D, 0x85, 0xE5, 0x2B, 0xCB,
0xAB, 0x8D, 0x78, 0x6A, 0x68, 0x17, 0x8F, 0xA8, 0xFF, 0x7C, 0x2F, 0x5C,
0x71, 0x64, 0x8D, 0x6F
};
static const unsigned char dhtest_2048_224_xB[] = {
0x4F, 0xF3, 0xBC, 0x96, 0xC7, 0xFC, 0x6A, 0x6D, 0x71, 0xD3, 0xB3, 0x63,
0x80, 0x0A, 0x7C, 0xDF, 0xEF, 0x6F, 0xC4, 0x1B, 0x44, 0x17, 0xEA, 0x15,
0x35, 0x3B, 0x75, 0x90
};
static const unsigned char dhtest_2048_224_yB[] = {
0x4D, 0xCE, 0xE9, 0x92, 0xA9, 0x76, 0x2A, 0x13, 0xF2, 0xF8, 0x38, 0x44,
0xAD, 0x3D, 0x77, 0xEE, 0x0E, 0x31, 0xC9, 0x71, 0x8B, 0x3D, 0xB6, 0xC2,
0x03, 0x5D, 0x39, 0x61, 0x18, 0x2C, 0x3E, 0x0B, 0xA2, 0x47, 0xEC, 0x41,
0x82, 0xD7, 0x60, 0xCD, 0x48, 0xD9, 0x95, 0x99, 0x97, 0x06, 0x22, 0xA1,
0x88, 0x1B, 0xBA, 0x2D, 0xC8, 0x22, 0x93, 0x9C, 0x78, 0xC3, 0x91, 0x2C,
0x66, 0x61, 0xFA, 0x54, 0x38, 0xB2, 0x07, 0x66, 0x22, 0x2B, 0x75, 0xE2,
0x4C, 0x2E, 0x3A, 0xD0, 0xC7, 0x28, 0x72, 0x36, 0x12, 0x95, 0x25, 0xEE,
0x15, 0xB5, 0xDD, 0x79, 0x98, 0xAA, 0x04, 0xC4, 0xA9, 0x69, 0x6C, 0xAC,
0xD7, 0x17, 0x20, 0x83, 0xA9, 0x7A, 0x81, 0x66, 0x4E, 0xAD, 0x2C, 0x47,
0x9E, 0x44, 0x4E, 0x4C, 0x06, 0x54, 0xCC, 0x19, 0xE2, 0x8D, 0x77, 0x03,
0xCE, 0xE8, 0xDA, 0xCD, 0x61, 0x26, 0xF5, 0xD6, 0x65, 0xEC, 0x52, 0xC6,
0x72, 0x55, 0xDB, 0x92, 0x01, 0x4B, 0x03, 0x7E, 0xB6, 0x21, 0xA2, 0xAC,
0x8E, 0x36, 0x5D, 0xE0, 0x71, 0xFF, 0xC1, 0x40, 0x0A, 0xCF, 0x07, 0x7A,
0x12, 0x91, 0x3D, 0xD8, 0xDE, 0x89, 0x47, 0x34, 0x37, 0xAB, 0x7B, 0xA3,
0x46, 0x74, 0x3C, 0x1B, 0x21, 0x5D, 0xD9, 0xC1, 0x21, 0x64, 0xA7, 0xE4,
0x05, 0x31, 0x18, 0xD1, 0x99, 0xBE, 0xC8, 0xEF, 0x6F, 0xC5, 0x61, 0x17,
0x0C, 0x84, 0xC8, 0x7D, 0x10, 0xEE, 0x9A, 0x67, 0x4A, 0x1F, 0xA8, 0xFF,
0xE1, 0x3B, 0xDF, 0xBA, 0x1D, 0x44, 0xDE, 0x48, 0x94, 0x6D, 0x68, 0xDC,
0x0C, 0xDD, 0x77, 0x76, 0x35, 0xA7, 0xAB, 0x5B, 0xFB, 0x1E, 0x4B, 0xB7,
0xB8, 0x56, 0xF9, 0x68, 0x27, 0x73, 0x4C, 0x18, 0x41, 0x38, 0xE9, 0x15,
0xD9, 0xC3, 0x00, 0x2E, 0xBC, 0xE5, 0x31, 0x20, 0x54, 0x6A, 0x7E, 0x20,
0x02, 0x14, 0x2B, 0x6C
};
static const unsigned char dhtest_2048_224_Z[] = {
0x34, 0xD9, 0xBD, 0xDC, 0x1B, 0x42, 0x17, 0x6C, 0x31, 0x3F, 0xEA, 0x03,
0x4C, 0x21, 0x03, 0x4D, 0x07, 0x4A, 0x63, 0x13, 0xBB, 0x4E, 0xCD, 0xB3,
0x70, 0x3F, 0xFF, 0x42, 0x45, 0x67, 0xA4, 0x6B, 0xDF, 0x75, 0x53, 0x0E,
0xDE, 0x0A, 0x9D, 0xA5, 0x22, 0x9D, 0xE7, 0xD7, 0x67, 0x32, 0x28, 0x6C,
0xBC, 0x0F, 0x91, 0xDA, 0x4C, 0x3C, 0x85, 0x2F, 0xC0, 0x99, 0xC6, 0x79,
0x53, 0x1D, 0x94, 0xC7, 0x8A, 0xB0, 0x3D, 0x9D, 0xEC, 0xB0, 0xA4, 0xE4,
0xCA, 0x8B, 0x2B, 0xB4, 0x59, 0x1C, 0x40, 0x21, 0xCF, 0x8C, 0xE3, 0xA2,
0x0A, 0x54, 0x1D, 0x33, 0x99, 0x40, 0x17, 0xD0, 0x20, 0x0A, 0xE2, 0xC9,
0x51, 0x6E, 0x2F, 0xF5, 0x14, 0x57, 0x79, 0x26, 0x9E, 0x86, 0x2B, 0x0F,
0xB4, 0x74, 0xA2, 0xD5, 0x6D, 0xC3, 0x1E, 0xD5, 0x69, 0xA7, 0x70, 0x0B,
0x4C, 0x4A, 0xB1, 0x6B, 0x22, 0xA4, 0x55, 0x13, 0x53, 0x1E, 0xF5, 0x23,
0xD7, 0x12, 0x12, 0x07, 0x7B, 0x5A, 0x16, 0x9B, 0xDE, 0xFF, 0xAD, 0x7A,
0xD9, 0x60, 0x82, 0x84, 0xC7, 0x79, 0x5B, 0x6D, 0x5A, 0x51, 0x83, 0xB8,
0x70, 0x66, 0xDE, 0x17, 0xD8, 0xD6, 0x71, 0xC9, 0xEB, 0xD8, 0xEC, 0x89,
0x54, 0x4D, 0x45, 0xEC, 0x06, 0x15, 0x93, 0xD4, 0x42, 0xC6, 0x2A, 0xB9,
0xCE, 0x3B, 0x1C, 0xB9, 0x94, 0x3A, 0x1D, 0x23, 0xA5, 0xEA, 0x3B, 0xCF,
0x21, 0xA0, 0x14, 0x71, 0xE6, 0x7E, 0x00, 0x3E, 0x7F, 0x8A, 0x69, 0xC7,
0x28, 0xBE, 0x49, 0x0B, 0x2F, 0xC8, 0x8C, 0xFE, 0xB9, 0x2D, 0xB6, 0xA2,
0x15, 0xE5, 0xD0, 0x3C, 0x17, 0xC4, 0x64, 0xC9, 0xAC, 0x1A, 0x46, 0xE2,
0x03, 0xE1, 0x3F, 0x95, 0x29, 0x95, 0xFB, 0x03, 0xC6, 0x9D, 0x3C, 0xC4,
0x7F, 0xCB, 0x51, 0x0B, 0x69, 0x98, 0xFF, 0xD3, 0xAA, 0x6D, 0xE7, 0x3C,
0xF9, 0xF6, 0x38, 0x69
};
static const unsigned char dhtest_2048_256_xA[] = {
0x08, 0x81, 0x38, 0x2C, 0xDB, 0x87, 0x66, 0x0C, 0x6D, 0xC1, 0x3E, 0x61,
0x49, 0x38, 0xD5, 0xB9, 0xC8, 0xB2, 0xF2, 0x48, 0x58, 0x1C, 0xC5, 0xE3,
0x1B, 0x35, 0x45, 0x43, 0x97, 0xFC, 0xE5, 0x0E
};
static const unsigned char dhtest_2048_256_yA[] = {
0x2E, 0x93, 0x80, 0xC8, 0x32, 0x3A, 0xF9, 0x75, 0x45, 0xBC, 0x49, 0x41,
0xDE, 0xB0, 0xEC, 0x37, 0x42, 0xC6, 0x2F, 0xE0, 0xEC, 0xE8, 0x24, 0xA6,
0xAB, 0xDB, 0xE6, 0x6C, 0x59, 0xBE, 0xE0, 0x24, 0x29, 0x11, 0xBF, 0xB9,
0x67, 0x23, 0x5C, 0xEB, 0xA3, 0x5A, 0xE1, 0x3E, 0x4E, 0xC7, 0x52, 0xBE,
0x63, 0x0B, 0x92, 0xDC, 0x4B, 0xDE, 0x28, 0x47, 0xA9, 0xC6, 0x2C, 0xB8,
0x15, 0x27, 0x45, 0x42, 0x1F, 0xB7, 0xEB, 0x60, 0xA6, 0x3C, 0x0F, 0xE9,
0x15, 0x9F, 0xCC, 0xE7, 0x26, 0xCE, 0x7C, 0xD8, 0x52, 0x3D, 0x74, 0x50,
0x66, 0x7E, 0xF8, 0x40, 0xE4, 0x91, 0x91, 0x21, 0xEB, 0x5F, 0x01, 0xC8,
0xC9, 0xB0, 0xD3, 0xD6, 0x48, 0xA9, 0x3B, 0xFB, 0x75, 0x68, 0x9E, 0x82,
0x44, 0xAC, 0x13, 0x4A, 0xF5, 0x44, 0x71, 0x1C, 0xE7, 0x9A, 0x02, 0xDC,
0xC3, 0x42, 0x26, 0x68, 0x47, 0x80, 0xDD, 0xDC, 0xB4, 0x98, 0x59, 0x41,
0x06, 0xC3, 0x7F, 0x5B, 0xC7, 0x98, 0x56, 0x48, 0x7A, 0xF5, 0xAB, 0x02,
0x2A, 0x2E, 0x5E, 0x42, 0xF0, 0x98, 0x97, 0xC1, 0xA8, 0x5A, 0x11, 0xEA,
0x02, 0x12, 0xAF, 0x04, 0xD9, 0xB4, 0xCE, 0xBC, 0x93, 0x7C, 0x3C, 0x1A,
0x3E, 0x15, 0xA8, 0xA0, 0x34, 0x2E, 0x33, 0x76, 0x15, 0xC8, 0x4E, 0x7F,
0xE3, 0xB8, 0xB9, 0xB8, 0x7F, 0xB1, 0xE7, 0x3A, 0x15, 0xAF, 0x12, 0xA3,
0x0D, 0x74, 0x6E, 0x06, 0xDF, 0xC3, 0x4F, 0x29, 0x0D, 0x79, 0x7C, 0xE5,
0x1A, 0xA1, 0x3A, 0xA7, 0x85, 0xBF, 0x66, 0x58, 0xAF, 0xF5, 0xE4, 0xB0,
0x93, 0x00, 0x3C, 0xBE, 0xAF, 0x66, 0x5B, 0x3C, 0x2E, 0x11, 0x3A, 0x3A,
0x4E, 0x90, 0x52, 0x69, 0x34, 0x1D, 0xC0, 0x71, 0x14, 0x26, 0x68, 0x5F,
0x4E, 0xF3, 0x7E, 0x86, 0x8A, 0x81, 0x26, 0xFF, 0x3F, 0x22, 0x79, 0xB5,
0x7C, 0xA6, 0x7E, 0x29
};
static const unsigned char dhtest_2048_256_xB[] = {
0x7D, 0x62, 0xA7, 0xE3, 0xEF, 0x36, 0xDE, 0x61, 0x7B, 0x13, 0xD1, 0xAF,
0xB8, 0x2C, 0x78, 0x0D, 0x83, 0xA2, 0x3B, 0xD4, 0xEE, 0x67, 0x05, 0x64,
0x51, 0x21, 0xF3, 0x71, 0xF5, 0x46, 0xA5, 0x3D
};
static const unsigned char dhtest_2048_256_yB[] = {
0x57, 0x5F, 0x03, 0x51, 0xBD, 0x2B, 0x1B, 0x81, 0x74, 0x48, 0xBD, 0xF8,
0x7A, 0x6C, 0x36, 0x2C, 0x1E, 0x28, 0x9D, 0x39, 0x03, 0xA3, 0x0B, 0x98,
0x32, 0xC5, 0x74, 0x1F, 0xA2, 0x50, 0x36, 0x3E, 0x7A, 0xCB, 0xC7, 0xF7,
0x7F, 0x3D, 0xAC, 0xBC, 0x1F, 0x13, 0x1A, 0xDD, 0x8E, 0x03, 0x36, 0x7E,
0xFF, 0x8F, 0xBB, 0xB3, 0xE1, 0xC5, 0x78, 0x44, 0x24, 0x80, 0x9B, 0x25,
0xAF, 0xE4, 0xD2, 0x26, 0x2A, 0x1A, 0x6F, 0xD2, 0xFA, 0xB6, 0x41, 0x05,
0xCA, 0x30, 0xA6, 0x74, 0xE0, 0x7F, 0x78, 0x09, 0x85, 0x20, 0x88, 0x63,
0x2F, 0xC0, 0x49, 0x23, 0x37, 0x91, 0xAD, 0x4E, 0xDD, 0x08, 0x3A, 0x97,
0x8B, 0x88, 0x3E, 0xE6, 0x18, 0xBC, 0x5E, 0x0D, 0xD0, 0x47, 0x41, 0x5F,
0x2D, 0x95, 0xE6, 0x83, 0xCF, 0x14, 0x82, 0x6B, 0x5F, 0xBE, 0x10, 0xD3,
0xCE, 0x41, 0xC6, 0xC1, 0x20, 0xC7, 0x8A, 0xB2, 0x00, 0x08, 0xC6, 0x98,
0xBF, 0x7F, 0x0B, 0xCA, 0xB9, 0xD7, 0xF4, 0x07, 0xBE, 0xD0, 0xF4, 0x3A,
0xFB, 0x29, 0x70, 0xF5, 0x7F, 0x8D, 0x12, 0x04, 0x39, 0x63, 0xE6, 0x6D,
0xDD, 0x32, 0x0D, 0x59, 0x9A, 0xD9, 0x93, 0x6C, 0x8F, 0x44, 0x13, 0x7C,
0x08, 0xB1, 0x80, 0xEC, 0x5E, 0x98, 0x5C, 0xEB, 0xE1, 0x86, 0xF3, 0xD5,
0x49, 0x67, 0x7E, 0x80, 0x60, 0x73, 0x31, 0xEE, 0x17, 0xAF, 0x33, 0x80,
0xA7, 0x25, 0xB0, 0x78, 0x23, 0x17, 0xD7, 0xDD, 0x43, 0xF5, 0x9D, 0x7A,
0xF9, 0x56, 0x8A, 0x9B, 0xB6, 0x3A, 0x84, 0xD3, 0x65, 0xF9, 0x22, 0x44,
0xED, 0x12, 0x09, 0x88, 0x21, 0x93, 0x02, 0xF4, 0x29, 0x24, 0xC7, 0xCA,
0x90, 0xB8, 0x9D, 0x24, 0xF7, 0x1B, 0x0A, 0xB6, 0x97, 0x82, 0x3D, 0x7D,
0xEB, 0x1A, 0xFF, 0x5B, 0x0E, 0x8E, 0x4A, 0x45, 0xD4, 0x9F, 0x7F, 0x53,
0x75, 0x7E, 0x19, 0x13
};
static const unsigned char dhtest_2048_256_Z[] = {
0x86, 0xC7, 0x0B, 0xF8, 0xD0, 0xBB, 0x81, 0xBB, 0x01, 0x07, 0x8A, 0x17,
0x21, 0x9C, 0xB7, 0xD2, 0x72, 0x03, 0xDB, 0x2A, 0x19, 0xC8, 0x77, 0xF1,
0xD1, 0xF1, 0x9F, 0xD7, 0xD7, 0x7E, 0xF2, 0x25, 0x46, 0xA6, 0x8F, 0x00,
0x5A, 0xD5, 0x2D, 0xC8, 0x45, 0x53, 0xB7, 0x8F, 0xC6, 0x03, 0x30, 0xBE,
0x51, 0xEA, 0x7C, 0x06, 0x72, 0xCA, 0xC1, 0x51, 0x5E, 0x4B, 0x35, 0xC0,
0x47, 0xB9, 0xA5, 0x51, 0xB8, 0x8F, 0x39, 0xDC, 0x26, 0xDA, 0x14, 0xA0,
0x9E, 0xF7, 0x47, 0x74, 0xD4, 0x7C, 0x76, 0x2D, 0xD1, 0x77, 0xF9, 0xED,
0x5B, 0xC2, 0xF1, 0x1E, 0x52, 0xC8, 0x79, 0xBD, 0x95, 0x09, 0x85, 0x04,
0xCD, 0x9E, 0xEC, 0xD8, 0xA8, 0xF9, 0xB3, 0xEF, 0xBD, 0x1F, 0x00, 0x8A,
0xC5, 0x85, 0x30, 0x97, 0xD9, 0xD1, 0x83, 0x7F, 0x2B, 0x18, 0xF7, 0x7C,
0xD7, 0xBE, 0x01, 0xAF, 0x80, 0xA7, 0xC7, 0xB5, 0xEA, 0x3C, 0xA5, 0x4C,
0xC0, 0x2D, 0x0C, 0x11, 0x6F, 0xEE, 0x3F, 0x95, 0xBB, 0x87, 0x39, 0x93,
0x85, 0x87, 0x5D, 0x7E, 0x86, 0x74, 0x7E, 0x67, 0x6E, 0x72, 0x89, 0x38,
0xAC, 0xBF, 0xF7, 0x09, 0x8E, 0x05, 0xBE, 0x4D, 0xCF, 0xB2, 0x40, 0x52,
0xB8, 0x3A, 0xEF, 0xFB, 0x14, 0x78, 0x3F, 0x02, 0x9A, 0xDB, 0xDE, 0x7F,
0x53, 0xFA, 0xE9, 0x20, 0x84, 0x22, 0x40, 0x90, 0xE0, 0x07, 0xCE, 0xE9,
0x4D, 0x4B, 0xF2, 0xBA, 0xCE, 0x9F, 0xFD, 0x4B, 0x57, 0xD2, 0xAF, 0x7C,
0x72, 0x4D, 0x0C, 0xAA, 0x19, 0xBF, 0x05, 0x01, 0xF6, 0xF1, 0x7B, 0x4A,
0xA1, 0x0F, 0x42, 0x5E, 0x3E, 0xA7, 0x60, 0x80, 0xB4, 0xB9, 0xD6, 0xB3,
0xCE, 0xFE, 0xA1, 0x15, 0xB2, 0xCE, 0xB8, 0x78, 0x9B, 0xB8, 0xA3, 0xB0,
0xEA, 0x87, 0xFE, 0xBE, 0x63, 0xB6, 0xC8, 0xF8, 0x46, 0xEC, 0x6D, 0xB0,
0xC2, 0x6C, 0x5D, 0x7C
};
static const unsigned char dhtest_rfc5114_2048_224_bad_y[] = {
0x45, 0x32, 0x5F, 0x51, 0x07, 0xE5, 0xDF, 0x1C, 0xD6, 0x02, 0x82, 0xB3,
0x32, 0x8F, 0xA4, 0x0F, 0x87, 0xB8, 0x41, 0xFE, 0xB9, 0x35, 0xDE, 0xAD,
0xC6, 0x26, 0x85, 0xB4, 0xFF, 0x94, 0x8C, 0x12, 0x4C, 0xBF, 0x5B, 0x20,
0xC4, 0x46, 0xA3, 0x26, 0xEB, 0xA4, 0x25, 0xB7, 0x68, 0x8E, 0xCC, 0x67,
0xBA, 0xEA, 0x58, 0xD0, 0xF2, 0xE9, 0xD2, 0x24, 0x72, 0x60, 0xDA, 0x88,
0x18, 0x9C, 0xE0, 0x31, 0x6A, 0xAD, 0x50, 0x6D, 0x94, 0x35, 0x8B, 0x83,
0x4A, 0x6E, 0xFA, 0x48, 0x73, 0x0F, 0x83, 0x87, 0xFF, 0x6B, 0x66, 0x1F,
0xA8, 0x82, 0xC6, 0x01, 0xE5, 0x80, 0xB5, 0xB0, 0x52, 0xD0, 0xE9, 0xD8,
0x72, 0xF9, 0x7D, 0x5B, 0x8B, 0xA5, 0x4C, 0xA5, 0x25, 0x95, 0x74, 0xE2,
0x7A, 0x61, 0x4E, 0xA7, 0x8F, 0x12, 0xE2, 0xD2, 0x9D, 0x8C, 0x02, 0x70,
0x34, 0x44, 0x32, 0xC7, 0xB2, 0xF3, 0xB9, 0xFE, 0x17, 0x2B, 0xD6, 0x1F,
0x8B, 0x7E, 0x4A, 0xFA, 0xA3, 0xB5, 0x3E, 0x7A, 0x81, 0x9A, 0x33, 0x66,
0x62, 0xA4, 0x50, 0x18, 0x3E, 0xA2, 0x5F, 0x00, 0x07, 0xD8, 0x9B, 0x22,
0xE4, 0xEC, 0x84, 0xD5, 0xEB, 0x5A, 0xF3, 0x2A, 0x31, 0x23, 0xD8, 0x44,
0x22, 0x2A, 0x8B, 0x37, 0x44, 0xCC, 0xC6, 0x87, 0x4B, 0xBE, 0x50, 0x9D,
0x4A, 0xC4, 0x8E, 0x45, 0xCF, 0x72, 0x4D, 0xC0, 0x89, 0xB3, 0x72, 0xED,
0x33, 0x2C, 0xBC, 0x7F, 0x16, 0x39, 0x3B, 0xEB, 0xD2, 0xDD, 0xA8, 0x01,
0x73, 0x84, 0x62, 0xB9, 0x29, 0xD2, 0xC9, 0x51, 0x32, 0x9E, 0x7A, 0x6A,
0xCF, 0xC1, 0x0A, 0xDB, 0x0E, 0xE0, 0x62, 0x77, 0x6F, 0x59, 0x62, 0x72,
0x5A, 0x69, 0xA6, 0x5B, 0x70, 0xCA, 0x65, 0xC4, 0x95, 0x6F, 0x9A, 0xC2,
0xDF, 0x72, 0x6D, 0xB1, 0x1E, 0x54, 0x7B, 0x51, 0xB4, 0xEF, 0x7F, 0x89,
0x93, 0x74, 0x89, 0x59
};
typedef struct {
DH *(*get_param) (void);
const unsigned char *xA;
size_t xA_len;
const unsigned char *yA;
size_t yA_len;
const unsigned char *xB;
size_t xB_len;
const unsigned char *yB;
size_t yB_len;
const unsigned char *Z;
size_t Z_len;
} rfc5114_td;
# define make_rfc5114_td(pre) { \
DH_get_##pre, \
dhtest_##pre##_xA, sizeof(dhtest_##pre##_xA), \
dhtest_##pre##_yA, sizeof(dhtest_##pre##_yA), \
dhtest_##pre##_xB, sizeof(dhtest_##pre##_xB), \
dhtest_##pre##_yB, sizeof(dhtest_##pre##_yB), \
dhtest_##pre##_Z, sizeof(dhtest_##pre##_Z) \
}
static const rfc5114_td rfctd[] = {
make_rfc5114_td(1024_160),
make_rfc5114_td(2048_224),
make_rfc5114_td(2048_256)
};
static int run_rfc5114_tests(void)
{
int i;
DH *dhA = NULL;
DH *dhB = NULL;
unsigned char *Z1 = NULL;
unsigned char *Z2 = NULL;
const rfc5114_td *td = NULL;
BIGNUM *bady = NULL;
for (i = 0; i < (int)(sizeof(rfctd) / sizeof(rfc5114_td)); i++) {
td = rfctd + i;
/* Set up DH structures setting key components */
dhA = td->get_param();
dhB = td->get_param();
if (!dhA || !dhB)
goto bad_err;
dhA->priv_key = BN_bin2bn(td->xA, td->xA_len, NULL);
dhA->pub_key = BN_bin2bn(td->yA, td->yA_len, NULL);
dhB->priv_key = BN_bin2bn(td->xB, td->xB_len, NULL);
dhB->pub_key = BN_bin2bn(td->yB, td->yB_len, NULL);
if (!dhA->priv_key || !dhA->pub_key
|| !dhB->priv_key || !dhB->pub_key)
goto bad_err;
if ((td->Z_len != (size_t)DH_size(dhA))
|| (td->Z_len != (size_t)DH_size(dhB)))
goto err;
Z1 = OPENSSL_malloc(DH_size(dhA));
Z2 = OPENSSL_malloc(DH_size(dhB));
/*
* Work out shared secrets using both sides and compare with expected
* values.
*/
if (DH_compute_key(Z1, dhB->pub_key, dhA) == -1)
goto bad_err;
if (DH_compute_key(Z2, dhA->pub_key, dhB) == -1)
goto bad_err;
if (memcmp(Z1, td->Z, td->Z_len))
goto err;
if (memcmp(Z2, td->Z, td->Z_len))
goto err;
printf("RFC5114 parameter test %d OK\n", i + 1);
DH_free(dhA);
DH_free(dhB);
OPENSSL_free(Z1);
OPENSSL_free(Z2);
dhA = NULL;
dhB = NULL;
Z1 = NULL;
Z2 = NULL;
}
/* Now i == OSSL_NELEM(rfctd) */
/* RFC5114 uses unsafe primes, so now test an invalid y value */
dhA = DH_get_2048_224();
if (dhA == NULL)
goto bad_err;
Z1 = OPENSSL_malloc(DH_size(dhA));
if (Z1 == NULL)
goto bad_err;
bady = BN_bin2bn(dhtest_rfc5114_2048_224_bad_y,
sizeof(dhtest_rfc5114_2048_224_bad_y), NULL);
if (bady == NULL)
goto bad_err;
if (!DH_generate_key(dhA))
goto bad_err;
if (DH_compute_key(Z1, bady, dhA) != -1) {
/*
* DH_compute_key should fail with -1. If we get here we unexpectedly
* allowed an invalid y value
*/
goto err;
}
/* We'll have a stale error on the queue from the above test so clear it */
ERR_clear_error();
printf("RFC5114 parameter test %d OK\n", i + 1);
BN_free(bady);
DH_free(dhA);
OPENSSL_free(Z1);
return 1;
bad_err:
BN_free(bady);
DH_free(dhA);
DH_free(dhB);
OPENSSL_free(Z1);
OPENSSL_free(Z2);
fprintf(stderr, "Initalisation error RFC5114 set %d\n", i + 1);
ERR_print_errors_fp(stderr);
return 0;
err:
BN_free(bady);
DH_free(dhA);
DH_free(dhB);
OPENSSL_free(Z1);
OPENSSL_free(Z2);
fprintf(stderr, "Test failed RFC5114 set %d\n", i + 1);
return 0;
}
#endif
diff --git a/crypto/dsa/dsatest.c b/crypto/dsa/dsatest.c
index 8a224a8876c3..bee95431dffa 100644
--- a/crypto/dsa/dsatest.c
+++ b/crypto/dsa/dsatest.c
@@ -1,268 +1,268 @@
/* crypto/dsa/dsatest.c */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
/*
* Until the key-gen callbacks are modified to use newer prototypes, we allow
* deprecated functions for openssl-internal code
*/
#ifdef OPENSSL_NO_DEPRECATED
# undef OPENSSL_NO_DEPRECATED
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include "../e_os.h"
#include <openssl/crypto.h>
#include <openssl/rand.h>
#include <openssl/bio.h>
#include <openssl/err.h>
#include <openssl/bn.h>
#ifdef OPENSSL_NO_DSA
int main(int argc, char *argv[])
{
printf("No DSA support\n");
return (0);
}
#else
# include <openssl/dsa.h>
# ifdef OPENSSL_SYS_WIN16
# define MS_CALLBACK _far _loadds
# else
# define MS_CALLBACK
# endif
static int MS_CALLBACK dsa_cb(int p, int n, BN_GENCB *arg);
/*
* seed, out_p, out_q, out_g are taken from the updated Appendix 5 to FIPS
* PUB 186 and also appear in Appendix 5 to FIPS PIB 186-1
*/
static unsigned char seed[20] = {
0xd5, 0x01, 0x4e, 0x4b, 0x60, 0xef, 0x2b, 0xa8, 0xb6, 0x21, 0x1b, 0x40,
0x62, 0xba, 0x32, 0x24, 0xe0, 0x42, 0x7d, 0xd3,
};
static unsigned char out_p[] = {
0x8d, 0xf2, 0xa4, 0x94, 0x49, 0x22, 0x76, 0xaa,
0x3d, 0x25, 0x75, 0x9b, 0xb0, 0x68, 0x69, 0xcb,
0xea, 0xc0, 0xd8, 0x3a, 0xfb, 0x8d, 0x0c, 0xf7,
0xcb, 0xb8, 0x32, 0x4f, 0x0d, 0x78, 0x82, 0xe5,
0xd0, 0x76, 0x2f, 0xc5, 0xb7, 0x21, 0x0e, 0xaf,
0xc2, 0xe9, 0xad, 0xac, 0x32, 0xab, 0x7a, 0xac,
0x49, 0x69, 0x3d, 0xfb, 0xf8, 0x37, 0x24, 0xc2,
0xec, 0x07, 0x36, 0xee, 0x31, 0xc8, 0x02, 0x91,
};
static unsigned char out_q[] = {
0xc7, 0x73, 0x21, 0x8c, 0x73, 0x7e, 0xc8, 0xee,
0x99, 0x3b, 0x4f, 0x2d, 0xed, 0x30, 0xf4, 0x8e,
0xda, 0xce, 0x91, 0x5f,
};
static unsigned char out_g[] = {
0x62, 0x6d, 0x02, 0x78, 0x39, 0xea, 0x0a, 0x13,
0x41, 0x31, 0x63, 0xa5, 0x5b, 0x4c, 0xb5, 0x00,
0x29, 0x9d, 0x55, 0x22, 0x95, 0x6c, 0xef, 0xcb,
0x3b, 0xff, 0x10, 0xf3, 0x99, 0xce, 0x2c, 0x2e,
0x71, 0xcb, 0x9d, 0xe5, 0xfa, 0x24, 0xba, 0xbf,
0x58, 0xe5, 0xb7, 0x95, 0x21, 0x92, 0x5c, 0x9c,
0xc4, 0x2e, 0x9f, 0x6f, 0x46, 0x4b, 0x08, 0x8c,
0xc5, 0x72, 0xaf, 0x53, 0xe6, 0xd7, 0x88, 0x02,
};
static const unsigned char str1[] = "12345678901234567890";
static const char rnd_seed[] =
"string to make the random number generator think it has entropy";
static BIO *bio_err = NULL;
int main(int argc, char **argv)
{
BN_GENCB cb;
DSA *dsa = NULL;
int counter, ret = 0, i, j;
unsigned char buf[256];
unsigned long h;
unsigned char sig[256];
unsigned int siglen;
if (bio_err == NULL)
bio_err = BIO_new_fp(stderr, BIO_NOCLOSE);
CRYPTO_malloc_debug_init();
CRYPTO_dbg_set_options(V_CRYPTO_MDEBUG_ALL);
CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON);
ERR_load_crypto_strings();
- RAND_seed(rnd_seed, sizeof rnd_seed);
+ RAND_seed(rnd_seed, sizeof(rnd_seed));
BIO_printf(bio_err, "test generation of DSA parameters\n");
BN_GENCB_set(&cb, dsa_cb, bio_err);
if (((dsa = DSA_new()) == NULL) || !DSA_generate_parameters_ex(dsa, 512,
seed, 20,
&counter,
&h, &cb))
goto end;
BIO_printf(bio_err, "seed\n");
for (i = 0; i < 20; i += 4) {
BIO_printf(bio_err, "%02X%02X%02X%02X ",
seed[i], seed[i + 1], seed[i + 2], seed[i + 3]);
}
BIO_printf(bio_err, "\ncounter=%d h=%ld\n", counter, h);
DSA_print(bio_err, dsa, 0);
if (counter != 105) {
BIO_printf(bio_err, "counter should be 105\n");
goto end;
}
if (h != 2) {
BIO_printf(bio_err, "h should be 2\n");
goto end;
}
i = BN_bn2bin(dsa->q, buf);
j = sizeof(out_q);
if ((i != j) || (memcmp(buf, out_q, i) != 0)) {
BIO_printf(bio_err, "q value is wrong\n");
goto end;
}
i = BN_bn2bin(dsa->p, buf);
j = sizeof(out_p);
if ((i != j) || (memcmp(buf, out_p, i) != 0)) {
BIO_printf(bio_err, "p value is wrong\n");
goto end;
}
i = BN_bn2bin(dsa->g, buf);
j = sizeof(out_g);
if ((i != j) || (memcmp(buf, out_g, i) != 0)) {
BIO_printf(bio_err, "g value is wrong\n");
goto end;
}
dsa->flags |= DSA_FLAG_NO_EXP_CONSTTIME;
DSA_generate_key(dsa);
DSA_sign(0, str1, 20, sig, &siglen, dsa);
if (DSA_verify(0, str1, 20, sig, siglen, dsa) == 1)
ret = 1;
dsa->flags &= ~DSA_FLAG_NO_EXP_CONSTTIME;
DSA_generate_key(dsa);
DSA_sign(0, str1, 20, sig, &siglen, dsa);
if (DSA_verify(0, str1, 20, sig, siglen, dsa) == 1)
ret = 1;
end:
if (!ret)
ERR_print_errors(bio_err);
if (dsa != NULL)
DSA_free(dsa);
CRYPTO_cleanup_all_ex_data();
ERR_remove_thread_state(NULL);
ERR_free_strings();
CRYPTO_mem_leaks(bio_err);
if (bio_err != NULL) {
BIO_free(bio_err);
bio_err = NULL;
}
# ifdef OPENSSL_SYS_NETWARE
if (!ret)
printf("ERROR\n");
# endif
EXIT(!ret);
return (0);
}
static int MS_CALLBACK dsa_cb(int p, int n, BN_GENCB *arg)
{
char c = '*';
static int ok = 0, num = 0;
if (p == 0) {
c = '.';
num++;
};
if (p == 1)
c = '+';
if (p == 2) {
c = '*';
ok++;
}
if (p == 3)
c = '\n';
BIO_write(arg->arg, &c, 1);
(void)BIO_flush(arg->arg);
if (!ok && (p == 0) && (num > 1)) {
BIO_printf((BIO *)arg, "error in dsatest\n");
return 0;
}
return 1;
}
#endif
diff --git a/crypto/ec/ec_lib.c b/crypto/ec/ec_lib.c
index 3ffa112cc306..3241aa51d9f4 100644
--- a/crypto/ec/ec_lib.c
+++ b/crypto/ec/ec_lib.c
@@ -1,1134 +1,1134 @@
/* crypto/ec/ec_lib.c */
/*
* Originally written by Bodo Moeller for the OpenSSL project.
*/
/* ====================================================================
* Copyright (c) 1998-2003 The OpenSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* openssl-core@openssl.org.
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.openssl.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*
* This product includes cryptographic software written by Eric Young
* (eay@cryptsoft.com). This product includes software written by Tim
* Hudson (tjh@cryptsoft.com).
*
*/
/* ====================================================================
* Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
* Binary polynomial ECC support in OpenSSL originally developed by
* SUN MICROSYSTEMS, INC., and contributed to the OpenSSL project.
*/
#include <string.h>
#include <openssl/err.h>
#include <openssl/opensslv.h>
#include "ec_lcl.h"
const char EC_version[] = "EC" OPENSSL_VERSION_PTEXT;
/* functions for EC_GROUP objects */
EC_GROUP *EC_GROUP_new(const EC_METHOD *meth)
{
EC_GROUP *ret;
if (meth == NULL) {
ECerr(EC_F_EC_GROUP_NEW, EC_R_SLOT_FULL);
return NULL;
}
if (meth->group_init == 0) {
ECerr(EC_F_EC_GROUP_NEW, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
return NULL;
}
- ret = OPENSSL_malloc(sizeof *ret);
+ ret = OPENSSL_malloc(sizeof(*ret));
if (ret == NULL) {
ECerr(EC_F_EC_GROUP_NEW, ERR_R_MALLOC_FAILURE);
return NULL;
}
ret->meth = meth;
ret->extra_data = NULL;
ret->mont_data = NULL;
ret->generator = NULL;
BN_init(&ret->order);
BN_init(&ret->cofactor);
ret->curve_name = 0;
ret->asn1_flag = ~EC_GROUP_ASN1_FLAG_MASK;
ret->asn1_form = POINT_CONVERSION_UNCOMPRESSED;
ret->seed = NULL;
ret->seed_len = 0;
if (!meth->group_init(ret)) {
OPENSSL_free(ret);
return NULL;
}
return ret;
}
void EC_GROUP_free(EC_GROUP *group)
{
if (!group)
return;
if (group->meth->group_finish != 0)
group->meth->group_finish(group);
EC_EX_DATA_free_all_data(&group->extra_data);
if (EC_GROUP_VERSION(group) && group->mont_data)
BN_MONT_CTX_free(group->mont_data);
if (group->generator != NULL)
EC_POINT_free(group->generator);
BN_free(&group->order);
BN_free(&group->cofactor);
if (group->seed)
OPENSSL_free(group->seed);
OPENSSL_free(group);
}
void EC_GROUP_clear_free(EC_GROUP *group)
{
if (!group)
return;
if (group->meth->group_clear_finish != 0)
group->meth->group_clear_finish(group);
else if (group->meth->group_finish != 0)
group->meth->group_finish(group);
EC_EX_DATA_clear_free_all_data(&group->extra_data);
if (EC_GROUP_VERSION(group) && group->mont_data)
BN_MONT_CTX_free(group->mont_data);
if (group->generator != NULL)
EC_POINT_clear_free(group->generator);
BN_clear_free(&group->order);
BN_clear_free(&group->cofactor);
if (group->seed) {
OPENSSL_cleanse(group->seed, group->seed_len);
OPENSSL_free(group->seed);
}
- OPENSSL_cleanse(group, sizeof *group);
+ OPENSSL_cleanse(group, sizeof(*group));
OPENSSL_free(group);
}
int EC_GROUP_copy(EC_GROUP *dest, const EC_GROUP *src)
{
EC_EXTRA_DATA *d;
if (dest->meth->group_copy == 0) {
ECerr(EC_F_EC_GROUP_COPY, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
return 0;
}
if (dest->meth != src->meth) {
ECerr(EC_F_EC_GROUP_COPY, EC_R_INCOMPATIBLE_OBJECTS);
return 0;
}
if (dest == src)
return 1;
EC_EX_DATA_free_all_data(&dest->extra_data);
for (d = src->extra_data; d != NULL; d = d->next) {
void *t = d->dup_func(d->data);
if (t == NULL)
return 0;
if (!EC_EX_DATA_set_data
(&dest->extra_data, t, d->dup_func, d->free_func,
d->clear_free_func))
return 0;
}
if (EC_GROUP_VERSION(src) && src->mont_data != NULL) {
if (dest->mont_data == NULL) {
dest->mont_data = BN_MONT_CTX_new();
if (dest->mont_data == NULL)
return 0;
}
if (!BN_MONT_CTX_copy(dest->mont_data, src->mont_data))
return 0;
} else {
/* src->generator == NULL */
if (EC_GROUP_VERSION(dest) && dest->mont_data != NULL) {
BN_MONT_CTX_free(dest->mont_data);
dest->mont_data = NULL;
}
}
if (src->generator != NULL) {
if (dest->generator == NULL) {
dest->generator = EC_POINT_new(dest);
if (dest->generator == NULL)
return 0;
}
if (!EC_POINT_copy(dest->generator, src->generator))
return 0;
} else {
/* src->generator == NULL */
if (dest->generator != NULL) {
EC_POINT_clear_free(dest->generator);
dest->generator = NULL;
}
}
if (!BN_copy(&dest->order, &src->order))
return 0;
if (!BN_copy(&dest->cofactor, &src->cofactor))
return 0;
dest->curve_name = src->curve_name;
dest->asn1_flag = src->asn1_flag;
dest->asn1_form = src->asn1_form;
if (src->seed) {
if (dest->seed)
OPENSSL_free(dest->seed);
dest->seed = OPENSSL_malloc(src->seed_len);
if (dest->seed == NULL)
return 0;
if (!memcpy(dest->seed, src->seed, src->seed_len))
return 0;
dest->seed_len = src->seed_len;
} else {
if (dest->seed)
OPENSSL_free(dest->seed);
dest->seed = NULL;
dest->seed_len = 0;
}
return dest->meth->group_copy(dest, src);
}
EC_GROUP *EC_GROUP_dup(const EC_GROUP *a)
{
EC_GROUP *t = NULL;
int ok = 0;
if (a == NULL)
return NULL;
if ((t = EC_GROUP_new(a->meth)) == NULL)
return (NULL);
if (!EC_GROUP_copy(t, a))
goto err;
ok = 1;
err:
if (!ok) {
if (t)
EC_GROUP_free(t);
return NULL;
} else
return t;
}
const EC_METHOD *EC_GROUP_method_of(const EC_GROUP *group)
{
return group->meth;
}
int EC_METHOD_get_field_type(const EC_METHOD *meth)
{
return meth->field_type;
}
int EC_GROUP_set_generator(EC_GROUP *group, const EC_POINT *generator,
const BIGNUM *order, const BIGNUM *cofactor)
{
if (generator == NULL) {
ECerr(EC_F_EC_GROUP_SET_GENERATOR, ERR_R_PASSED_NULL_PARAMETER);
return 0;
}
if (group->generator == NULL) {
group->generator = EC_POINT_new(group);
if (group->generator == NULL)
return 0;
}
if (!EC_POINT_copy(group->generator, generator))
return 0;
if (order != NULL) {
if (!BN_copy(&group->order, order))
return 0;
} else
BN_zero(&group->order);
if (cofactor != NULL) {
if (!BN_copy(&group->cofactor, cofactor))
return 0;
} else
BN_zero(&group->cofactor);
/*
* We ignore the return value because some groups have an order with
* factors of two, which makes the Montgomery setup fail.
* |group->mont_data| will be NULL in this case.
*/
ec_precompute_mont_data(group);
return 1;
}
const EC_POINT *EC_GROUP_get0_generator(const EC_GROUP *group)
{
return group->generator;
}
BN_MONT_CTX *EC_GROUP_get_mont_data(const EC_GROUP *group)
{
return EC_GROUP_VERSION(group) ? group->mont_data : NULL;
}
int EC_GROUP_get_order(const EC_GROUP *group, BIGNUM *order, BN_CTX *ctx)
{
if (!BN_copy(order, &group->order))
return 0;
return !BN_is_zero(order);
}
int EC_GROUP_get_cofactor(const EC_GROUP *group, BIGNUM *cofactor,
BN_CTX *ctx)
{
if (!BN_copy(cofactor, &group->cofactor))
return 0;
return !BN_is_zero(&group->cofactor);
}
void EC_GROUP_set_curve_name(EC_GROUP *group, int nid)
{
group->curve_name = nid;
}
int EC_GROUP_get_curve_name(const EC_GROUP *group)
{
return group->curve_name;
}
void EC_GROUP_set_asn1_flag(EC_GROUP *group, int flag)
{
group->asn1_flag &= ~EC_GROUP_ASN1_FLAG_MASK;
group->asn1_flag |= flag & EC_GROUP_ASN1_FLAG_MASK;
}
int EC_GROUP_get_asn1_flag(const EC_GROUP *group)
{
return group->asn1_flag & EC_GROUP_ASN1_FLAG_MASK;
}
void EC_GROUP_set_point_conversion_form(EC_GROUP *group,
point_conversion_form_t form)
{
group->asn1_form = form;
}
point_conversion_form_t EC_GROUP_get_point_conversion_form(const EC_GROUP
*group)
{
return group->asn1_form;
}
size_t EC_GROUP_set_seed(EC_GROUP *group, const unsigned char *p, size_t len)
{
if (group->seed) {
OPENSSL_free(group->seed);
group->seed = NULL;
group->seed_len = 0;
}
if (!len || !p)
return 1;
if ((group->seed = OPENSSL_malloc(len)) == NULL)
return 0;
memcpy(group->seed, p, len);
group->seed_len = len;
return len;
}
unsigned char *EC_GROUP_get0_seed(const EC_GROUP *group)
{
return group->seed;
}
size_t EC_GROUP_get_seed_len(const EC_GROUP *group)
{
return group->seed_len;
}
int EC_GROUP_set_curve_GFp(EC_GROUP *group, const BIGNUM *p, const BIGNUM *a,
const BIGNUM *b, BN_CTX *ctx)
{
if (group->meth->group_set_curve == 0) {
ECerr(EC_F_EC_GROUP_SET_CURVE_GFP, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
return 0;
}
return group->meth->group_set_curve(group, p, a, b, ctx);
}
int EC_GROUP_get_curve_GFp(const EC_GROUP *group, BIGNUM *p, BIGNUM *a,
BIGNUM *b, BN_CTX *ctx)
{
if (group->meth->group_get_curve == 0) {
ECerr(EC_F_EC_GROUP_GET_CURVE_GFP, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
return 0;
}
return group->meth->group_get_curve(group, p, a, b, ctx);
}
#ifndef OPENSSL_NO_EC2M
int EC_GROUP_set_curve_GF2m(EC_GROUP *group, const BIGNUM *p, const BIGNUM *a,
const BIGNUM *b, BN_CTX *ctx)
{
if (group->meth->group_set_curve == 0) {
ECerr(EC_F_EC_GROUP_SET_CURVE_GF2M,
ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
return 0;
}
return group->meth->group_set_curve(group, p, a, b, ctx);
}
int EC_GROUP_get_curve_GF2m(const EC_GROUP *group, BIGNUM *p, BIGNUM *a,
BIGNUM *b, BN_CTX *ctx)
{
if (group->meth->group_get_curve == 0) {
ECerr(EC_F_EC_GROUP_GET_CURVE_GF2M,
ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
return 0;
}
return group->meth->group_get_curve(group, p, a, b, ctx);
}
#endif
int EC_GROUP_get_degree(const EC_GROUP *group)
{
if (group->meth->group_get_degree == 0) {
ECerr(EC_F_EC_GROUP_GET_DEGREE, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
return 0;
}
return group->meth->group_get_degree(group);
}
int EC_GROUP_check_discriminant(const EC_GROUP *group, BN_CTX *ctx)
{
if (group->meth->group_check_discriminant == 0) {
ECerr(EC_F_EC_GROUP_CHECK_DISCRIMINANT,
ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
return 0;
}
return group->meth->group_check_discriminant(group, ctx);
}
int EC_GROUP_cmp(const EC_GROUP *a, const EC_GROUP *b, BN_CTX *ctx)
{
int r = 0;
BIGNUM *a1, *a2, *a3, *b1, *b2, *b3;
BN_CTX *ctx_new = NULL;
/* compare the field types */
if (EC_METHOD_get_field_type(EC_GROUP_method_of(a)) !=
EC_METHOD_get_field_type(EC_GROUP_method_of(b)))
return 1;
/* compare the curve name (if present in both) */
if (EC_GROUP_get_curve_name(a) && EC_GROUP_get_curve_name(b) &&
EC_GROUP_get_curve_name(a) != EC_GROUP_get_curve_name(b))
return 1;
if (!ctx)
ctx_new = ctx = BN_CTX_new();
if (!ctx)
return -1;
BN_CTX_start(ctx);
a1 = BN_CTX_get(ctx);
a2 = BN_CTX_get(ctx);
a3 = BN_CTX_get(ctx);
b1 = BN_CTX_get(ctx);
b2 = BN_CTX_get(ctx);
b3 = BN_CTX_get(ctx);
if (!b3) {
BN_CTX_end(ctx);
if (ctx_new)
BN_CTX_free(ctx);
return -1;
}
/*
* XXX This approach assumes that the external representation of curves
* over the same field type is the same.
*/
if (!a->meth->group_get_curve(a, a1, a2, a3, ctx) ||
!b->meth->group_get_curve(b, b1, b2, b3, ctx))
r = 1;
if (r || BN_cmp(a1, b1) || BN_cmp(a2, b2) || BN_cmp(a3, b3))
r = 1;
/* XXX EC_POINT_cmp() assumes that the methods are equal */
if (r || EC_POINT_cmp(a, EC_GROUP_get0_generator(a),
EC_GROUP_get0_generator(b), ctx))
r = 1;
if (!r) {
/* compare the order and cofactor */
if (!EC_GROUP_get_order(a, a1, ctx) ||
!EC_GROUP_get_order(b, b1, ctx) ||
!EC_GROUP_get_cofactor(a, a2, ctx) ||
!EC_GROUP_get_cofactor(b, b2, ctx)) {
BN_CTX_end(ctx);
if (ctx_new)
BN_CTX_free(ctx);
return -1;
}
if (BN_cmp(a1, b1) || BN_cmp(a2, b2))
r = 1;
}
BN_CTX_end(ctx);
if (ctx_new)
BN_CTX_free(ctx);
return r;
}
/* this has 'package' visibility */
int EC_EX_DATA_set_data(EC_EXTRA_DATA **ex_data, void *data,
void *(*dup_func) (void *),
void (*free_func) (void *),
void (*clear_free_func) (void *))
{
EC_EXTRA_DATA *d;
if (ex_data == NULL)
return 0;
for (d = *ex_data; d != NULL; d = d->next) {
if (d->dup_func == dup_func && d->free_func == free_func
&& d->clear_free_func == clear_free_func) {
ECerr(EC_F_EC_EX_DATA_SET_DATA, EC_R_SLOT_FULL);
return 0;
}
}
if (data == NULL)
/* no explicit entry needed */
return 1;
- d = OPENSSL_malloc(sizeof *d);
+ d = OPENSSL_malloc(sizeof(*d));
if (d == NULL)
return 0;
d->data = data;
d->dup_func = dup_func;
d->free_func = free_func;
d->clear_free_func = clear_free_func;
d->next = *ex_data;
*ex_data = d;
return 1;
}
/* this has 'package' visibility */
void *EC_EX_DATA_get_data(const EC_EXTRA_DATA *ex_data,
void *(*dup_func) (void *),
void (*free_func) (void *),
void (*clear_free_func) (void *))
{
const EC_EXTRA_DATA *d;
for (d = ex_data; d != NULL; d = d->next) {
if (d->dup_func == dup_func && d->free_func == free_func
&& d->clear_free_func == clear_free_func)
return d->data;
}
return NULL;
}
/* this has 'package' visibility */
void EC_EX_DATA_free_data(EC_EXTRA_DATA **ex_data,
void *(*dup_func) (void *),
void (*free_func) (void *),
void (*clear_free_func) (void *))
{
EC_EXTRA_DATA **p;
if (ex_data == NULL)
return;
for (p = ex_data; *p != NULL; p = &((*p)->next)) {
if ((*p)->dup_func == dup_func && (*p)->free_func == free_func
&& (*p)->clear_free_func == clear_free_func) {
EC_EXTRA_DATA *next = (*p)->next;
(*p)->free_func((*p)->data);
OPENSSL_free(*p);
*p = next;
return;
}
}
}
/* this has 'package' visibility */
void EC_EX_DATA_clear_free_data(EC_EXTRA_DATA **ex_data,
void *(*dup_func) (void *),
void (*free_func) (void *),
void (*clear_free_func) (void *))
{
EC_EXTRA_DATA **p;
if (ex_data == NULL)
return;
for (p = ex_data; *p != NULL; p = &((*p)->next)) {
if ((*p)->dup_func == dup_func && (*p)->free_func == free_func
&& (*p)->clear_free_func == clear_free_func) {
EC_EXTRA_DATA *next = (*p)->next;
(*p)->clear_free_func((*p)->data);
OPENSSL_free(*p);
*p = next;
return;
}
}
}
/* this has 'package' visibility */
void EC_EX_DATA_free_all_data(EC_EXTRA_DATA **ex_data)
{
EC_EXTRA_DATA *d;
if (ex_data == NULL)
return;
d = *ex_data;
while (d) {
EC_EXTRA_DATA *next = d->next;
d->free_func(d->data);
OPENSSL_free(d);
d = next;
}
*ex_data = NULL;
}
/* this has 'package' visibility */
void EC_EX_DATA_clear_free_all_data(EC_EXTRA_DATA **ex_data)
{
EC_EXTRA_DATA *d;
if (ex_data == NULL)
return;
d = *ex_data;
while (d) {
EC_EXTRA_DATA *next = d->next;
d->clear_free_func(d->data);
OPENSSL_free(d);
d = next;
}
*ex_data = NULL;
}
/* functions for EC_POINT objects */
EC_POINT *EC_POINT_new(const EC_GROUP *group)
{
EC_POINT *ret;
if (group == NULL) {
ECerr(EC_F_EC_POINT_NEW, ERR_R_PASSED_NULL_PARAMETER);
return NULL;
}
if (group->meth->point_init == 0) {
ECerr(EC_F_EC_POINT_NEW, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
return NULL;
}
- ret = OPENSSL_malloc(sizeof *ret);
+ ret = OPENSSL_malloc(sizeof(*ret));
if (ret == NULL) {
ECerr(EC_F_EC_POINT_NEW, ERR_R_MALLOC_FAILURE);
return NULL;
}
ret->meth = group->meth;
if (!ret->meth->point_init(ret)) {
OPENSSL_free(ret);
return NULL;
}
return ret;
}
void EC_POINT_free(EC_POINT *point)
{
if (!point)
return;
if (point->meth->point_finish != 0)
point->meth->point_finish(point);
OPENSSL_free(point);
}
void EC_POINT_clear_free(EC_POINT *point)
{
if (!point)
return;
if (point->meth->point_clear_finish != 0)
point->meth->point_clear_finish(point);
else if (point->meth->point_finish != 0)
point->meth->point_finish(point);
- OPENSSL_cleanse(point, sizeof *point);
+ OPENSSL_cleanse(point, sizeof(*point));
OPENSSL_free(point);
}
int EC_POINT_copy(EC_POINT *dest, const EC_POINT *src)
{
if (dest->meth->point_copy == 0) {
ECerr(EC_F_EC_POINT_COPY, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
return 0;
}
if (dest->meth != src->meth) {
ECerr(EC_F_EC_POINT_COPY, EC_R_INCOMPATIBLE_OBJECTS);
return 0;
}
if (dest == src)
return 1;
return dest->meth->point_copy(dest, src);
}
EC_POINT *EC_POINT_dup(const EC_POINT *a, const EC_GROUP *group)
{
EC_POINT *t;
int r;
if (a == NULL)
return NULL;
t = EC_POINT_new(group);
if (t == NULL)
return (NULL);
r = EC_POINT_copy(t, a);
if (!r) {
EC_POINT_free(t);
return NULL;
} else
return t;
}
const EC_METHOD *EC_POINT_method_of(const EC_POINT *point)
{
return point->meth;
}
int EC_POINT_set_to_infinity(const EC_GROUP *group, EC_POINT *point)
{
if (group->meth->point_set_to_infinity == 0) {
ECerr(EC_F_EC_POINT_SET_TO_INFINITY,
ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
return 0;
}
if (group->meth != point->meth) {
ECerr(EC_F_EC_POINT_SET_TO_INFINITY, EC_R_INCOMPATIBLE_OBJECTS);
return 0;
}
return group->meth->point_set_to_infinity(group, point);
}
int EC_POINT_set_Jprojective_coordinates_GFp(const EC_GROUP *group,
EC_POINT *point, const BIGNUM *x,
const BIGNUM *y, const BIGNUM *z,
BN_CTX *ctx)
{
if (group->meth->point_set_Jprojective_coordinates_GFp == 0) {
ECerr(EC_F_EC_POINT_SET_JPROJECTIVE_COORDINATES_GFP,
ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
return 0;
}
if (group->meth != point->meth) {
ECerr(EC_F_EC_POINT_SET_JPROJECTIVE_COORDINATES_GFP,
EC_R_INCOMPATIBLE_OBJECTS);
return 0;
}
return group->meth->point_set_Jprojective_coordinates_GFp(group, point, x,
y, z, ctx);
}
int EC_POINT_get_Jprojective_coordinates_GFp(const EC_GROUP *group,
const EC_POINT *point, BIGNUM *x,
BIGNUM *y, BIGNUM *z,
BN_CTX *ctx)
{
if (group->meth->point_get_Jprojective_coordinates_GFp == 0) {
ECerr(EC_F_EC_POINT_GET_JPROJECTIVE_COORDINATES_GFP,
ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
return 0;
}
if (group->meth != point->meth) {
ECerr(EC_F_EC_POINT_GET_JPROJECTIVE_COORDINATES_GFP,
EC_R_INCOMPATIBLE_OBJECTS);
return 0;
}
return group->meth->point_get_Jprojective_coordinates_GFp(group, point, x,
y, z, ctx);
}
int EC_POINT_set_affine_coordinates_GFp(const EC_GROUP *group,
EC_POINT *point, const BIGNUM *x,
const BIGNUM *y, BN_CTX *ctx)
{
if (group->meth->point_set_affine_coordinates == 0) {
ECerr(EC_F_EC_POINT_SET_AFFINE_COORDINATES_GFP,
ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
return 0;
}
if (group->meth != point->meth) {
ECerr(EC_F_EC_POINT_SET_AFFINE_COORDINATES_GFP,
EC_R_INCOMPATIBLE_OBJECTS);
return 0;
}
return group->meth->point_set_affine_coordinates(group, point, x, y, ctx);
}
#ifndef OPENSSL_NO_EC2M
int EC_POINT_set_affine_coordinates_GF2m(const EC_GROUP *group,
EC_POINT *point, const BIGNUM *x,
const BIGNUM *y, BN_CTX *ctx)
{
if (group->meth->point_set_affine_coordinates == 0) {
ECerr(EC_F_EC_POINT_SET_AFFINE_COORDINATES_GF2M,
ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
return 0;
}
if (group->meth != point->meth) {
ECerr(EC_F_EC_POINT_SET_AFFINE_COORDINATES_GF2M,
EC_R_INCOMPATIBLE_OBJECTS);
return 0;
}
return group->meth->point_set_affine_coordinates(group, point, x, y, ctx);
}
#endif
int EC_POINT_get_affine_coordinates_GFp(const EC_GROUP *group,
const EC_POINT *point, BIGNUM *x,
BIGNUM *y, BN_CTX *ctx)
{
if (group->meth->point_get_affine_coordinates == 0) {
ECerr(EC_F_EC_POINT_GET_AFFINE_COORDINATES_GFP,
ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
return 0;
}
if (group->meth != point->meth) {
ECerr(EC_F_EC_POINT_GET_AFFINE_COORDINATES_GFP,
EC_R_INCOMPATIBLE_OBJECTS);
return 0;
}
return group->meth->point_get_affine_coordinates(group, point, x, y, ctx);
}
#ifndef OPENSSL_NO_EC2M
int EC_POINT_get_affine_coordinates_GF2m(const EC_GROUP *group,
const EC_POINT *point, BIGNUM *x,
BIGNUM *y, BN_CTX *ctx)
{
if (group->meth->point_get_affine_coordinates == 0) {
ECerr(EC_F_EC_POINT_GET_AFFINE_COORDINATES_GF2M,
ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
return 0;
}
if (group->meth != point->meth) {
ECerr(EC_F_EC_POINT_GET_AFFINE_COORDINATES_GF2M,
EC_R_INCOMPATIBLE_OBJECTS);
return 0;
}
return group->meth->point_get_affine_coordinates(group, point, x, y, ctx);
}
#endif
int EC_POINT_add(const EC_GROUP *group, EC_POINT *r, const EC_POINT *a,
const EC_POINT *b, BN_CTX *ctx)
{
if (group->meth->add == 0) {
ECerr(EC_F_EC_POINT_ADD, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
return 0;
}
if ((group->meth != r->meth) || (r->meth != a->meth)
|| (a->meth != b->meth)) {
ECerr(EC_F_EC_POINT_ADD, EC_R_INCOMPATIBLE_OBJECTS);
return 0;
}
return group->meth->add(group, r, a, b, ctx);
}
int EC_POINT_dbl(const EC_GROUP *group, EC_POINT *r, const EC_POINT *a,
BN_CTX *ctx)
{
if (group->meth->dbl == 0) {
ECerr(EC_F_EC_POINT_DBL, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
return 0;
}
if ((group->meth != r->meth) || (r->meth != a->meth)) {
ECerr(EC_F_EC_POINT_DBL, EC_R_INCOMPATIBLE_OBJECTS);
return 0;
}
return group->meth->dbl(group, r, a, ctx);
}
int EC_POINT_invert(const EC_GROUP *group, EC_POINT *a, BN_CTX *ctx)
{
if (group->meth->invert == 0) {
ECerr(EC_F_EC_POINT_INVERT, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
return 0;
}
if (group->meth != a->meth) {
ECerr(EC_F_EC_POINT_INVERT, EC_R_INCOMPATIBLE_OBJECTS);
return 0;
}
return group->meth->invert(group, a, ctx);
}
int EC_POINT_is_at_infinity(const EC_GROUP *group, const EC_POINT *point)
{
if (group->meth->is_at_infinity == 0) {
ECerr(EC_F_EC_POINT_IS_AT_INFINITY,
ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
return 0;
}
if (group->meth != point->meth) {
ECerr(EC_F_EC_POINT_IS_AT_INFINITY, EC_R_INCOMPATIBLE_OBJECTS);
return 0;
}
return group->meth->is_at_infinity(group, point);
}
/*
* Check whether an EC_POINT is on the curve or not. Note that the return
* value for this function should NOT be treated as a boolean. Return values:
* 1: The point is on the curve
* 0: The point is not on the curve
* -1: An error occurred
*/
int EC_POINT_is_on_curve(const EC_GROUP *group, const EC_POINT *point,
BN_CTX *ctx)
{
if (group->meth->is_on_curve == 0) {
ECerr(EC_F_EC_POINT_IS_ON_CURVE, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
return 0;
}
if (group->meth != point->meth) {
ECerr(EC_F_EC_POINT_IS_ON_CURVE, EC_R_INCOMPATIBLE_OBJECTS);
return 0;
}
return group->meth->is_on_curve(group, point, ctx);
}
int EC_POINT_cmp(const EC_GROUP *group, const EC_POINT *a, const EC_POINT *b,
BN_CTX *ctx)
{
if (group->meth->point_cmp == 0) {
ECerr(EC_F_EC_POINT_CMP, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
return -1;
}
if ((group->meth != a->meth) || (a->meth != b->meth)) {
ECerr(EC_F_EC_POINT_CMP, EC_R_INCOMPATIBLE_OBJECTS);
return -1;
}
return group->meth->point_cmp(group, a, b, ctx);
}
int EC_POINT_make_affine(const EC_GROUP *group, EC_POINT *point, BN_CTX *ctx)
{
if (group->meth->make_affine == 0) {
ECerr(EC_F_EC_POINT_MAKE_AFFINE, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
return 0;
}
if (group->meth != point->meth) {
ECerr(EC_F_EC_POINT_MAKE_AFFINE, EC_R_INCOMPATIBLE_OBJECTS);
return 0;
}
return group->meth->make_affine(group, point, ctx);
}
int EC_POINTs_make_affine(const EC_GROUP *group, size_t num,
EC_POINT *points[], BN_CTX *ctx)
{
size_t i;
if (group->meth->points_make_affine == 0) {
ECerr(EC_F_EC_POINTS_MAKE_AFFINE, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
return 0;
}
for (i = 0; i < num; i++) {
if (group->meth != points[i]->meth) {
ECerr(EC_F_EC_POINTS_MAKE_AFFINE, EC_R_INCOMPATIBLE_OBJECTS);
return 0;
}
}
return group->meth->points_make_affine(group, num, points, ctx);
}
/*
* Functions for point multiplication. If group->meth->mul is 0, we use the
* wNAF-based implementations in ec_mult.c; otherwise we dispatch through
* methods.
*/
int EC_POINTs_mul(const EC_GROUP *group, EC_POINT *r, const BIGNUM *scalar,
size_t num, const EC_POINT *points[],
const BIGNUM *scalars[], BN_CTX *ctx)
{
if (group->meth->mul == 0)
/* use default */
return ec_wNAF_mul(group, r, scalar, num, points, scalars, ctx);
return group->meth->mul(group, r, scalar, num, points, scalars, ctx);
}
int EC_POINT_mul(const EC_GROUP *group, EC_POINT *r, const BIGNUM *g_scalar,
const EC_POINT *point, const BIGNUM *p_scalar, BN_CTX *ctx)
{
/* just a convenient interface to EC_POINTs_mul() */
const EC_POINT *points[1];
const BIGNUM *scalars[1];
points[0] = point;
scalars[0] = p_scalar;
return EC_POINTs_mul(group, r, g_scalar,
(point != NULL
&& p_scalar != NULL), points, scalars, ctx);
}
int EC_GROUP_precompute_mult(EC_GROUP *group, BN_CTX *ctx)
{
if (group->meth->mul == 0)
/* use default */
return ec_wNAF_precompute_mult(group, ctx);
if (group->meth->precompute_mult != 0)
return group->meth->precompute_mult(group, ctx);
else
return 1; /* nothing to do, so report success */
}
int EC_GROUP_have_precompute_mult(const EC_GROUP *group)
{
if (group->meth->mul == 0)
/* use default */
return ec_wNAF_have_precompute_mult(group);
if (group->meth->have_precompute_mult != 0)
return group->meth->have_precompute_mult(group);
else
return 0; /* cannot tell whether precomputation has
* been performed */
}
/*
* ec_precompute_mont_data sets |group->mont_data| from |group->order| and
* returns one on success. On error it returns zero.
*/
int ec_precompute_mont_data(EC_GROUP *group)
{
BN_CTX *ctx = BN_CTX_new();
int ret = 0;
if (!EC_GROUP_VERSION(group))
goto err;
if (group->mont_data) {
BN_MONT_CTX_free(group->mont_data);
group->mont_data = NULL;
}
if (ctx == NULL)
goto err;
group->mont_data = BN_MONT_CTX_new();
if (!group->mont_data)
goto err;
if (!BN_MONT_CTX_set(group->mont_data, &group->order, ctx)) {
BN_MONT_CTX_free(group->mont_data);
group->mont_data = NULL;
goto err;
}
ret = 1;
err:
if (ctx)
BN_CTX_free(ctx);
return ret;
}
diff --git a/crypto/ec/ec_mult.c b/crypto/ec/ec_mult.c
index 24ca67a6ef1e..2231f9957ef6 100644
--- a/crypto/ec/ec_mult.c
+++ b/crypto/ec/ec_mult.c
@@ -1,917 +1,917 @@
/* crypto/ec/ec_mult.c */
/*
* Originally written by Bodo Moeller and Nils Larsch for the OpenSSL project.
*/
/* ====================================================================
* Copyright (c) 1998-2007 The OpenSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* openssl-core@openssl.org.
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.openssl.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*
* This product includes cryptographic software written by Eric Young
* (eay@cryptsoft.com). This product includes software written by Tim
* Hudson (tjh@cryptsoft.com).
*
*/
/* ====================================================================
* Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
* Portions of this software developed by SUN MICROSYSTEMS, INC.,
* and contributed to the OpenSSL project.
*/
#include <string.h>
#include <openssl/err.h>
#include "ec_lcl.h"
/*
* This file implements the wNAF-based interleaving multi-exponentiation method
* Formerly at:
* http://www.informatik.tu-darmstadt.de/TI/Mitarbeiter/moeller.html#multiexp
* You might now find it here:
* http://link.springer.com/chapter/10.1007%2F3-540-45537-X_13
* http://www.bmoeller.de/pdf/TI-01-08.multiexp.pdf
* For multiplication with precomputation, we use wNAF splitting, formerly at:
* http://www.informatik.tu-darmstadt.de/TI/Mitarbeiter/moeller.html#fastexp
*/
/* structure for precomputed multiples of the generator */
typedef struct ec_pre_comp_st {
const EC_GROUP *group; /* parent EC_GROUP object */
size_t blocksize; /* block size for wNAF splitting */
size_t numblocks; /* max. number of blocks for which we have
* precomputation */
size_t w; /* window size */
EC_POINT **points; /* array with pre-calculated multiples of
* generator: 'num' pointers to EC_POINT
* objects followed by a NULL */
size_t num; /* numblocks * 2^(w-1) */
int references;
} EC_PRE_COMP;
/* functions to manage EC_PRE_COMP within the EC_GROUP extra_data framework */
static void *ec_pre_comp_dup(void *);
static void ec_pre_comp_free(void *);
static void ec_pre_comp_clear_free(void *);
static EC_PRE_COMP *ec_pre_comp_new(const EC_GROUP *group)
{
EC_PRE_COMP *ret = NULL;
if (!group)
return NULL;
ret = (EC_PRE_COMP *)OPENSSL_malloc(sizeof(EC_PRE_COMP));
if (!ret) {
ECerr(EC_F_EC_PRE_COMP_NEW, ERR_R_MALLOC_FAILURE);
return ret;
}
ret->group = group;
ret->blocksize = 8; /* default */
ret->numblocks = 0;
ret->w = 4; /* default */
ret->points = NULL;
ret->num = 0;
ret->references = 1;
return ret;
}
static void *ec_pre_comp_dup(void *src_)
{
EC_PRE_COMP *src = src_;
/* no need to actually copy, these objects never change! */
CRYPTO_add(&src->references, 1, CRYPTO_LOCK_EC_PRE_COMP);
return src_;
}
static void ec_pre_comp_free(void *pre_)
{
int i;
EC_PRE_COMP *pre = pre_;
if (!pre)
return;
i = CRYPTO_add(&pre->references, -1, CRYPTO_LOCK_EC_PRE_COMP);
if (i > 0)
return;
if (pre->points) {
EC_POINT **p;
for (p = pre->points; *p != NULL; p++)
EC_POINT_free(*p);
OPENSSL_free(pre->points);
}
OPENSSL_free(pre);
}
static void ec_pre_comp_clear_free(void *pre_)
{
int i;
EC_PRE_COMP *pre = pre_;
if (!pre)
return;
i = CRYPTO_add(&pre->references, -1, CRYPTO_LOCK_EC_PRE_COMP);
if (i > 0)
return;
if (pre->points) {
EC_POINT **p;
for (p = pre->points; *p != NULL; p++) {
EC_POINT_clear_free(*p);
- OPENSSL_cleanse(p, sizeof *p);
+ OPENSSL_cleanse(p, sizeof(*p));
}
OPENSSL_free(pre->points);
}
- OPENSSL_cleanse(pre, sizeof *pre);
+ OPENSSL_cleanse(pre, sizeof(*pre));
OPENSSL_free(pre);
}
/*-
* 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.
*/
static signed char *compute_wNAF(const BIGNUM *scalar, int w, size_t *ret_len)
{
int window_val;
int ok = 0;
signed char *r = NULL;
int sign = 1;
int bit, next_bit, mask;
size_t len = 0, j;
if (BN_is_zero(scalar)) {
r = OPENSSL_malloc(1);
if (!r) {
ECerr(EC_F_COMPUTE_WNAF, ERR_R_MALLOC_FAILURE);
goto err;
}
r[0] = 0;
*ret_len = 1;
return r;
}
if (w <= 0 || w > 7) { /* 'signed char' can represent integers with
* absolute values less than 2^7 */
ECerr(EC_F_COMPUTE_WNAF, ERR_R_INTERNAL_ERROR);
goto err;
}
bit = 1 << w; /* at most 128 */
next_bit = bit << 1; /* at most 256 */
mask = next_bit - 1; /* at most 255 */
if (BN_is_negative(scalar)) {
sign = -1;
}
if (scalar->d == NULL || scalar->top == 0) {
ECerr(EC_F_COMPUTE_WNAF, ERR_R_INTERNAL_ERROR);
goto err;
}
len = BN_num_bits(scalar);
r = OPENSSL_malloc(len + 1); /* modified wNAF may be one digit longer
* than binary representation (*ret_len will
* be set to the actual length, i.e. at most
* BN_num_bits(scalar) + 1) */
if (r == NULL) {
ECerr(EC_F_COMPUTE_WNAF, ERR_R_MALLOC_FAILURE);
goto err;
}
window_val = scalar->d[0] & mask;
j = 0;
while ((window_val != 0) || (j + w + 1 < len)) { /* if j+w+1 >= len,
* window_val will not
* increase */
int digit = 0;
/* 0 <= window_val <= 2^(w+1) */
if (window_val & 1) {
/* 0 < window_val < 2^(w+1) */
if (window_val & bit) {
digit = window_val - next_bit; /* -2^w < digit < 0 */
#if 1 /* modified wNAF */
if (j + w + 1 >= len) {
/*
* special case for generating modified wNAFs: no new
* bits will be added into window_val, so using a
* positive digit here will decrease the total length of
* the representation
*/
digit = window_val & (mask >> 1); /* 0 < digit < 2^w */
}
#endif
} else {
digit = window_val; /* 0 < digit < 2^w */
}
if (digit <= -bit || digit >= bit || !(digit & 1)) {
ECerr(EC_F_COMPUTE_WNAF, ERR_R_INTERNAL_ERROR);
goto err;
}
window_val -= digit;
/*
* now window_val is 0 or 2^(w+1) in standard wNAF generation;
* for modified window NAFs, it may also be 2^w
*/
if (window_val != 0 && window_val != next_bit
&& window_val != bit) {
ECerr(EC_F_COMPUTE_WNAF, ERR_R_INTERNAL_ERROR);
goto err;
}
}
r[j++] = sign * digit;
window_val >>= 1;
window_val += bit * BN_is_bit_set(scalar, j + w);
if (window_val > next_bit) {
ECerr(EC_F_COMPUTE_WNAF, ERR_R_INTERNAL_ERROR);
goto err;
}
}
if (j > len + 1) {
ECerr(EC_F_COMPUTE_WNAF, ERR_R_INTERNAL_ERROR);
goto err;
}
len = j;
ok = 1;
err:
if (!ok) {
OPENSSL_free(r);
r = NULL;
}
if (ok)
*ret_len = len;
return r;
}
/*
* TODO: table should be optimised for the wNAF-based implementation,
* sometimes smaller windows will give better performance (thus the
* boundaries should be increased)
*/
#define EC_window_bits_for_scalar_size(b) \
((size_t) \
((b) >= 2000 ? 6 : \
(b) >= 800 ? 5 : \
(b) >= 300 ? 4 : \
(b) >= 70 ? 3 : \
(b) >= 20 ? 2 : \
1))
/*-
* Compute
* \sum scalars[i]*points[i],
* also including
* scalar*generator
* in the addition if scalar != NULL
*/
int ec_wNAF_mul(const EC_GROUP *group, EC_POINT *r, const BIGNUM *scalar,
size_t num, const EC_POINT *points[], const BIGNUM *scalars[],
BN_CTX *ctx)
{
BN_CTX *new_ctx = NULL;
const EC_POINT *generator = NULL;
EC_POINT *tmp = NULL;
size_t totalnum;
size_t blocksize = 0, numblocks = 0; /* for wNAF splitting */
size_t pre_points_per_block = 0;
size_t i, j;
int k;
int r_is_inverted = 0;
int r_is_at_infinity = 1;
size_t *wsize = NULL; /* individual window sizes */
signed char **wNAF = NULL; /* individual wNAFs */
size_t *wNAF_len = NULL;
size_t max_len = 0;
size_t num_val;
EC_POINT **val = NULL; /* precomputation */
EC_POINT **v;
EC_POINT ***val_sub = NULL; /* pointers to sub-arrays of 'val' or
* 'pre_comp->points' */
const EC_PRE_COMP *pre_comp = NULL;
int num_scalar = 0; /* flag: will be set to 1 if 'scalar' must be
* treated like other scalars, i.e.
* precomputation is not available */
int ret = 0;
if (group->meth != r->meth) {
ECerr(EC_F_EC_WNAF_MUL, EC_R_INCOMPATIBLE_OBJECTS);
return 0;
}
if ((scalar == NULL) && (num == 0)) {
return EC_POINT_set_to_infinity(group, r);
}
for (i = 0; i < num; i++) {
if (group->meth != points[i]->meth) {
ECerr(EC_F_EC_WNAF_MUL, EC_R_INCOMPATIBLE_OBJECTS);
return 0;
}
}
if (ctx == NULL) {
ctx = new_ctx = BN_CTX_new();
if (ctx == NULL)
goto err;
}
if (scalar != NULL) {
generator = EC_GROUP_get0_generator(group);
if (generator == NULL) {
ECerr(EC_F_EC_WNAF_MUL, EC_R_UNDEFINED_GENERATOR);
goto err;
}
/* look if we can use precomputed multiples of generator */
pre_comp =
EC_EX_DATA_get_data(group->extra_data, ec_pre_comp_dup,
ec_pre_comp_free, ec_pre_comp_clear_free);
if (pre_comp && pre_comp->numblocks
&& (EC_POINT_cmp(group, generator, pre_comp->points[0], ctx) ==
0)) {
blocksize = pre_comp->blocksize;
/*
* determine maximum number of blocks that wNAF splitting may
* yield (NB: maximum wNAF length is bit length plus one)
*/
numblocks = (BN_num_bits(scalar) / blocksize) + 1;
/*
* we cannot use more blocks than we have precomputation for
*/
if (numblocks > pre_comp->numblocks)
numblocks = pre_comp->numblocks;
pre_points_per_block = (size_t)1 << (pre_comp->w - 1);
/* check that pre_comp looks sane */
if (pre_comp->num != (pre_comp->numblocks * pre_points_per_block)) {
ECerr(EC_F_EC_WNAF_MUL, ERR_R_INTERNAL_ERROR);
goto err;
}
} else {
/* can't use precomputation */
pre_comp = NULL;
numblocks = 1;
num_scalar = 1; /* treat 'scalar' like 'num'-th element of
* 'scalars' */
}
}
totalnum = num + numblocks;
- wsize = OPENSSL_malloc(totalnum * sizeof wsize[0]);
- wNAF_len = OPENSSL_malloc(totalnum * sizeof wNAF_len[0]);
- wNAF = OPENSSL_malloc((totalnum + 1) * sizeof wNAF[0]); /* includes space
- * for pivot */
- val_sub = OPENSSL_malloc(totalnum * sizeof val_sub[0]);
+ wsize = OPENSSL_malloc(totalnum * sizeof(wsize[0]));
+ wNAF_len = OPENSSL_malloc(totalnum * sizeof(wNAF_len[0]));
+ /* include space for pivot */
+ wNAF = OPENSSL_malloc((totalnum + 1) * sizeof(wNAF[0]));
+ val_sub = OPENSSL_malloc(totalnum * sizeof(val_sub[0]));
/* Ensure wNAF is initialised in case we end up going to err */
if (wNAF)
wNAF[0] = NULL; /* preliminary pivot */
if (!wsize || !wNAF_len || !wNAF || !val_sub) {
ECerr(EC_F_EC_WNAF_MUL, ERR_R_MALLOC_FAILURE);
goto err;
}
/*
* num_val will be the total number of temporarily precomputed points
*/
num_val = 0;
for (i = 0; i < num + num_scalar; i++) {
size_t bits;
bits = i < num ? BN_num_bits(scalars[i]) : BN_num_bits(scalar);
wsize[i] = EC_window_bits_for_scalar_size(bits);
num_val += (size_t)1 << (wsize[i] - 1);
wNAF[i + 1] = NULL; /* make sure we always have a pivot */
wNAF[i] =
compute_wNAF((i < num ? scalars[i] : scalar), wsize[i],
&wNAF_len[i]);
if (wNAF[i] == NULL)
goto err;
if (wNAF_len[i] > max_len)
max_len = wNAF_len[i];
}
if (numblocks) {
/* we go here iff scalar != NULL */
if (pre_comp == NULL) {
if (num_scalar != 1) {
ECerr(EC_F_EC_WNAF_MUL, ERR_R_INTERNAL_ERROR);
goto err;
}
/* we have already generated a wNAF for 'scalar' */
} else {
signed char *tmp_wNAF = NULL;
size_t tmp_len = 0;
if (num_scalar != 0) {
ECerr(EC_F_EC_WNAF_MUL, ERR_R_INTERNAL_ERROR);
goto err;
}
/*
* use the window size for which we have precomputation
*/
wsize[num] = pre_comp->w;
tmp_wNAF = compute_wNAF(scalar, wsize[num], &tmp_len);
if (!tmp_wNAF)
goto err;
if (tmp_len <= max_len) {
/*
* One of the other wNAFs is at least as long as the wNAF
* belonging to the generator, so wNAF splitting will not buy
* us anything.
*/
numblocks = 1;
totalnum = num + 1; /* don't use wNAF splitting */
wNAF[num] = tmp_wNAF;
wNAF[num + 1] = NULL;
wNAF_len[num] = tmp_len;
if (tmp_len > max_len)
max_len = tmp_len;
/*
* pre_comp->points starts with the points that we need here:
*/
val_sub[num] = pre_comp->points;
} else {
/*
* don't include tmp_wNAF directly into wNAF array - use wNAF
* splitting and include the blocks
*/
signed char *pp;
EC_POINT **tmp_points;
if (tmp_len < numblocks * blocksize) {
/*
* possibly we can do with fewer blocks than estimated
*/
numblocks = (tmp_len + blocksize - 1) / blocksize;
if (numblocks > pre_comp->numblocks) {
ECerr(EC_F_EC_WNAF_MUL, ERR_R_INTERNAL_ERROR);
goto err;
}
totalnum = num + numblocks;
}
/* split wNAF in 'numblocks' parts */
pp = tmp_wNAF;
tmp_points = pre_comp->points;
for (i = num; i < totalnum; i++) {
if (i < totalnum - 1) {
wNAF_len[i] = blocksize;
if (tmp_len < blocksize) {
ECerr(EC_F_EC_WNAF_MUL, ERR_R_INTERNAL_ERROR);
goto err;
}
tmp_len -= blocksize;
} else
/*
* last block gets whatever is left (this could be
* more or less than 'blocksize'!)
*/
wNAF_len[i] = tmp_len;
wNAF[i + 1] = NULL;
wNAF[i] = OPENSSL_malloc(wNAF_len[i]);
if (wNAF[i] == NULL) {
ECerr(EC_F_EC_WNAF_MUL, ERR_R_MALLOC_FAILURE);
OPENSSL_free(tmp_wNAF);
goto err;
}
memcpy(wNAF[i], pp, wNAF_len[i]);
if (wNAF_len[i] > max_len)
max_len = wNAF_len[i];
if (*tmp_points == NULL) {
ECerr(EC_F_EC_WNAF_MUL, ERR_R_INTERNAL_ERROR);
OPENSSL_free(tmp_wNAF);
goto err;
}
val_sub[i] = tmp_points;
tmp_points += pre_points_per_block;
pp += blocksize;
}
OPENSSL_free(tmp_wNAF);
}
}
}
/*
* All points we precompute now go into a single array 'val'.
* 'val_sub[i]' is a pointer to the subarray for the i-th point, or to a
* subarray of 'pre_comp->points' if we already have precomputation.
*/
- val = OPENSSL_malloc((num_val + 1) * sizeof val[0]);
+ val = OPENSSL_malloc((num_val + 1) * sizeof(val[0]));
if (val == NULL) {
ECerr(EC_F_EC_WNAF_MUL, ERR_R_MALLOC_FAILURE);
goto err;
}
val[num_val] = NULL; /* pivot element */
/* allocate points for precomputation */
v = val;
for (i = 0; i < num + num_scalar; i++) {
val_sub[i] = v;
for (j = 0; j < ((size_t)1 << (wsize[i] - 1)); j++) {
*v = EC_POINT_new(group);
if (*v == NULL)
goto err;
v++;
}
}
if (!(v == val + num_val)) {
ECerr(EC_F_EC_WNAF_MUL, ERR_R_INTERNAL_ERROR);
goto err;
}
if (!(tmp = EC_POINT_new(group)))
goto err;
/*-
* prepare precomputed values:
* val_sub[i][0] := points[i]
* val_sub[i][1] := 3 * points[i]
* val_sub[i][2] := 5 * points[i]
* ...
*/
for (i = 0; i < num + num_scalar; i++) {
if (i < num) {
if (!EC_POINT_copy(val_sub[i][0], points[i]))
goto err;
} else {
if (!EC_POINT_copy(val_sub[i][0], generator))
goto err;
}
if (wsize[i] > 1) {
if (!EC_POINT_dbl(group, tmp, val_sub[i][0], ctx))
goto err;
for (j = 1; j < ((size_t)1 << (wsize[i] - 1)); j++) {
if (!EC_POINT_add
(group, val_sub[i][j], val_sub[i][j - 1], tmp, ctx))
goto err;
}
}
}
#if 1 /* optional; EC_window_bits_for_scalar_size
* assumes we do this step */
if (!EC_POINTs_make_affine(group, num_val, val, ctx))
goto err;
#endif
r_is_at_infinity = 1;
for (k = max_len - 1; k >= 0; k--) {
if (!r_is_at_infinity) {
if (!EC_POINT_dbl(group, r, r, ctx))
goto err;
}
for (i = 0; i < totalnum; i++) {
if (wNAF_len[i] > (size_t)k) {
int digit = wNAF[i][k];
int is_neg;
if (digit) {
is_neg = digit < 0;
if (is_neg)
digit = -digit;
if (is_neg != r_is_inverted) {
if (!r_is_at_infinity) {
if (!EC_POINT_invert(group, r, ctx))
goto err;
}
r_is_inverted = !r_is_inverted;
}
/* digit > 0 */
if (r_is_at_infinity) {
if (!EC_POINT_copy(r, val_sub[i][digit >> 1]))
goto err;
r_is_at_infinity = 0;
} else {
if (!EC_POINT_add
(group, r, r, val_sub[i][digit >> 1], ctx))
goto err;
}
}
}
}
}
if (r_is_at_infinity) {
if (!EC_POINT_set_to_infinity(group, r))
goto err;
} else {
if (r_is_inverted)
if (!EC_POINT_invert(group, r, ctx))
goto err;
}
ret = 1;
err:
if (new_ctx != NULL)
BN_CTX_free(new_ctx);
if (tmp != NULL)
EC_POINT_free(tmp);
if (wsize != NULL)
OPENSSL_free(wsize);
if (wNAF_len != NULL)
OPENSSL_free(wNAF_len);
if (wNAF != NULL) {
signed char **w;
for (w = wNAF; *w != NULL; w++)
OPENSSL_free(*w);
OPENSSL_free(wNAF);
}
if (val != NULL) {
for (v = val; *v != NULL; v++)
EC_POINT_clear_free(*v);
OPENSSL_free(val);
}
if (val_sub != NULL) {
OPENSSL_free(val_sub);
}
return ret;
}
/*-
* ec_wNAF_precompute_mult()
* creates an EC_PRE_COMP object with preprecomputed multiples of the generator
* for use with wNAF splitting as implemented in ec_wNAF_mul().
*
* 'pre_comp->points' is an array of multiples of the generator
* of the following form:
* points[0] = generator;
* points[1] = 3 * generator;
* ...
* points[2^(w-1)-1] = (2^(w-1)-1) * generator;
* points[2^(w-1)] = 2^blocksize * generator;
* points[2^(w-1)+1] = 3 * 2^blocksize * generator;
* ...
* points[2^(w-1)*(numblocks-1)-1] = (2^(w-1)) * 2^(blocksize*(numblocks-2)) * generator
* points[2^(w-1)*(numblocks-1)] = 2^(blocksize*(numblocks-1)) * generator
* ...
* points[2^(w-1)*numblocks-1] = (2^(w-1)) * 2^(blocksize*(numblocks-1)) * generator
* points[2^(w-1)*numblocks] = NULL
*/
int ec_wNAF_precompute_mult(EC_GROUP *group, BN_CTX *ctx)
{
const EC_POINT *generator;
EC_POINT *tmp_point = NULL, *base = NULL, **var;
BN_CTX *new_ctx = NULL;
BIGNUM *order;
size_t i, bits, w, pre_points_per_block, blocksize, numblocks, num;
EC_POINT **points = NULL;
EC_PRE_COMP *pre_comp;
int ret = 0;
/* if there is an old EC_PRE_COMP object, throw it away */
EC_EX_DATA_free_data(&group->extra_data, ec_pre_comp_dup,
ec_pre_comp_free, ec_pre_comp_clear_free);
if ((pre_comp = ec_pre_comp_new(group)) == NULL)
return 0;
generator = EC_GROUP_get0_generator(group);
if (generator == NULL) {
ECerr(EC_F_EC_WNAF_PRECOMPUTE_MULT, EC_R_UNDEFINED_GENERATOR);
goto err;
}
if (ctx == NULL) {
ctx = new_ctx = BN_CTX_new();
if (ctx == NULL)
goto err;
}
BN_CTX_start(ctx);
order = BN_CTX_get(ctx);
if (order == NULL)
goto err;
if (!EC_GROUP_get_order(group, order, ctx))
goto err;
if (BN_is_zero(order)) {
ECerr(EC_F_EC_WNAF_PRECOMPUTE_MULT, EC_R_UNKNOWN_ORDER);
goto err;
}
bits = BN_num_bits(order);
/*
* The following parameters mean we precompute (approximately) one point
* per bit. TBD: The combination 8, 4 is perfect for 160 bits; for other
* bit lengths, other parameter combinations might provide better
* efficiency.
*/
blocksize = 8;
w = 4;
if (EC_window_bits_for_scalar_size(bits) > w) {
/* let's not make the window too small ... */
w = EC_window_bits_for_scalar_size(bits);
}
numblocks = (bits + blocksize - 1) / blocksize; /* max. number of blocks
* to use for wNAF
* splitting */
pre_points_per_block = (size_t)1 << (w - 1);
num = pre_points_per_block * numblocks; /* number of points to compute
* and store */
points = OPENSSL_malloc(sizeof(EC_POINT *) * (num + 1));
if (!points) {
ECerr(EC_F_EC_WNAF_PRECOMPUTE_MULT, ERR_R_MALLOC_FAILURE);
goto err;
}
var = points;
var[num] = NULL; /* pivot */
for (i = 0; i < num; i++) {
if ((var[i] = EC_POINT_new(group)) == NULL) {
ECerr(EC_F_EC_WNAF_PRECOMPUTE_MULT, ERR_R_MALLOC_FAILURE);
goto err;
}
}
if (!(tmp_point = EC_POINT_new(group)) || !(base = EC_POINT_new(group))) {
ECerr(EC_F_EC_WNAF_PRECOMPUTE_MULT, ERR_R_MALLOC_FAILURE);
goto err;
}
if (!EC_POINT_copy(base, generator))
goto err;
/* do the precomputation */
for (i = 0; i < numblocks; i++) {
size_t j;
if (!EC_POINT_dbl(group, tmp_point, base, ctx))
goto err;
if (!EC_POINT_copy(*var++, base))
goto err;
for (j = 1; j < pre_points_per_block; j++, var++) {
/*
* calculate odd multiples of the current base point
*/
if (!EC_POINT_add(group, *var, tmp_point, *(var - 1), ctx))
goto err;
}
if (i < numblocks - 1) {
/*
* get the next base (multiply current one by 2^blocksize)
*/
size_t k;
if (blocksize <= 2) {
ECerr(EC_F_EC_WNAF_PRECOMPUTE_MULT, ERR_R_INTERNAL_ERROR);
goto err;
}
if (!EC_POINT_dbl(group, base, tmp_point, ctx))
goto err;
for (k = 2; k < blocksize; k++) {
if (!EC_POINT_dbl(group, base, base, ctx))
goto err;
}
}
}
if (!EC_POINTs_make_affine(group, num, points, ctx))
goto err;
pre_comp->group = group;
pre_comp->blocksize = blocksize;
pre_comp->numblocks = numblocks;
pre_comp->w = w;
pre_comp->points = points;
points = NULL;
pre_comp->num = num;
if (!EC_EX_DATA_set_data(&group->extra_data, pre_comp,
ec_pre_comp_dup, ec_pre_comp_free,
ec_pre_comp_clear_free))
goto err;
pre_comp = NULL;
ret = 1;
err:
if (ctx != NULL)
BN_CTX_end(ctx);
if (new_ctx != NULL)
BN_CTX_free(new_ctx);
if (pre_comp)
ec_pre_comp_free(pre_comp);
if (points) {
EC_POINT **p;
for (p = points; *p != NULL; p++)
EC_POINT_free(*p);
OPENSSL_free(points);
}
if (tmp_point)
EC_POINT_free(tmp_point);
if (base)
EC_POINT_free(base);
return ret;
}
int ec_wNAF_have_precompute_mult(const EC_GROUP *group)
{
if (EC_EX_DATA_get_data
(group->extra_data, ec_pre_comp_dup, ec_pre_comp_free,
ec_pre_comp_clear_free) != NULL)
return 1;
else
return 0;
}
diff --git a/crypto/ec/ecp_nistp224.c b/crypto/ec/ecp_nistp224.c
index fcd754e44881..121f587b58b6 100644
--- a/crypto/ec/ecp_nistp224.c
+++ b/crypto/ec/ecp_nistp224.c
@@ -1,1768 +1,1767 @@
/* crypto/ec/ecp_nistp224.c */
/*
* Written by Emilia Kasper (Google) for the OpenSSL project.
*/
/* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
*
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* A 64-bit implementation of the NIST P-224 elliptic curve point multiplication
*
* Inspired by Daniel J. Bernstein's public domain nistp224 implementation
* and Adam Langley's public domain 64-bit C implementation of curve25519
*/
#include <openssl/opensslconf.h>
#ifndef OPENSSL_NO_EC_NISTP_64_GCC_128
# ifndef OPENSSL_SYS_VMS
# include <stdint.h>
# else
# include <inttypes.h>
# endif
# include <string.h>
# include <openssl/err.h>
# include "ec_lcl.h"
# if defined(__GNUC__) && (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 1))
/* even with gcc, the typedef won't work for 32-bit platforms */
typedef __uint128_t uint128_t; /* nonstandard; implemented by gcc on 64-bit
* platforms */
# else
# error "Need GCC 3.1 or later to define type uint128_t"
# endif
typedef uint8_t u8;
typedef uint64_t u64;
-typedef int64_t s64;
/******************************************************************************/
/*-
* INTERNAL REPRESENTATION OF FIELD ELEMENTS
*
* Field elements are represented as a_0 + 2^56*a_1 + 2^112*a_2 + 2^168*a_3
* using 64-bit coefficients called 'limbs',
* and sometimes (for multiplication results) as
* b_0 + 2^56*b_1 + 2^112*b_2 + 2^168*b_3 + 2^224*b_4 + 2^280*b_5 + 2^336*b_6
* using 128-bit coefficients called 'widelimbs'.
* A 4-limb representation is an 'felem';
* a 7-widelimb representation is a 'widefelem'.
* Even within felems, bits of adjacent limbs overlap, and we don't always
* reduce the representations: we ensure that inputs to each felem
* multiplication satisfy a_i < 2^60, so outputs satisfy b_i < 4*2^60*2^60,
* and fit into a 128-bit word without overflow. The coefficients are then
* again partially reduced to obtain an felem satisfying a_i < 2^57.
* We only reduce to the unique minimal representation at the end of the
* computation.
*/
typedef uint64_t limb;
typedef uint128_t widelimb;
typedef limb felem[4];
typedef widelimb widefelem[7];
/*
* Field element represented as a byte arrary. 28*8 = 224 bits is also the
* group order size for the elliptic curve, and we also use this type for
* scalars for point multiplication.
*/
typedef u8 felem_bytearray[28];
static const felem_bytearray nistp224_curve_params[5] = {
{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, /* p */
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01},
{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, /* a */
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFE, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFE},
{0xB4, 0x05, 0x0A, 0x85, 0x0C, 0x04, 0xB3, 0xAB, 0xF5, 0x41, /* b */
0x32, 0x56, 0x50, 0x44, 0xB0, 0xB7, 0xD7, 0xBF, 0xD8, 0xBA,
0x27, 0x0B, 0x39, 0x43, 0x23, 0x55, 0xFF, 0xB4},
{0xB7, 0x0E, 0x0C, 0xBD, 0x6B, 0xB4, 0xBF, 0x7F, 0x32, 0x13, /* x */
0x90, 0xB9, 0x4A, 0x03, 0xC1, 0xD3, 0x56, 0xC2, 0x11, 0x22,
0x34, 0x32, 0x80, 0xD6, 0x11, 0x5C, 0x1D, 0x21},
{0xbd, 0x37, 0x63, 0x88, 0xb5, 0xf7, 0x23, 0xfb, 0x4c, 0x22, /* y */
0xdf, 0xe6, 0xcd, 0x43, 0x75, 0xa0, 0x5a, 0x07, 0x47, 0x64,
0x44, 0xd5, 0x81, 0x99, 0x85, 0x00, 0x7e, 0x34}
};
/*-
* Precomputed multiples of the standard generator
* Points are given in coordinates (X, Y, Z) where Z normally is 1
* (0 for the point at infinity).
* For each field element, slice a_0 is word 0, etc.
*
* The table has 2 * 16 elements, starting with the following:
* index | bits | point
* ------+---------+------------------------------
* 0 | 0 0 0 0 | 0G
* 1 | 0 0 0 1 | 1G
* 2 | 0 0 1 0 | 2^56G
* 3 | 0 0 1 1 | (2^56 + 1)G
* 4 | 0 1 0 0 | 2^112G
* 5 | 0 1 0 1 | (2^112 + 1)G
* 6 | 0 1 1 0 | (2^112 + 2^56)G
* 7 | 0 1 1 1 | (2^112 + 2^56 + 1)G
* 8 | 1 0 0 0 | 2^168G
* 9 | 1 0 0 1 | (2^168 + 1)G
* 10 | 1 0 1 0 | (2^168 + 2^56)G
* 11 | 1 0 1 1 | (2^168 + 2^56 + 1)G
* 12 | 1 1 0 0 | (2^168 + 2^112)G
* 13 | 1 1 0 1 | (2^168 + 2^112 + 1)G
* 14 | 1 1 1 0 | (2^168 + 2^112 + 2^56)G
* 15 | 1 1 1 1 | (2^168 + 2^112 + 2^56 + 1)G
* followed by a copy of this with each element multiplied by 2^28.
*
* The reason for this is so that we can clock bits into four different
* locations when doing simple scalar multiplies against the base point,
* and then another four locations using the second 16 elements.
*/
static const felem gmul[2][16][3] = { {{{0, 0, 0, 0},
{0, 0, 0, 0},
{0, 0, 0, 0}},
{{0x3280d6115c1d21, 0xc1d356c2112234,
0x7f321390b94a03, 0xb70e0cbd6bb4bf},
{0xd5819985007e34, 0x75a05a07476444,
0xfb4c22dfe6cd43, 0xbd376388b5f723},
{1, 0, 0, 0}},
{{0xfd9675666ebbe9, 0xbca7664d40ce5e,
0x2242df8d8a2a43, 0x1f49bbb0f99bc5},
{0x29e0b892dc9c43, 0xece8608436e662,
0xdc858f185310d0, 0x9812dd4eb8d321},
{1, 0, 0, 0}},
{{0x6d3e678d5d8eb8, 0x559eed1cb362f1,
0x16e9a3bbce8a3f, 0xeedcccd8c2a748},
{0xf19f90ed50266d, 0xabf2b4bf65f9df,
0x313865468fafec, 0x5cb379ba910a17},
{1, 0, 0, 0}},
{{0x0641966cab26e3, 0x91fb2991fab0a0,
0xefec27a4e13a0b, 0x0499aa8a5f8ebe},
{0x7510407766af5d, 0x84d929610d5450,
0x81d77aae82f706, 0x6916f6d4338c5b},
{1, 0, 0, 0}},
{{0xea95ac3b1f15c6, 0x086000905e82d4,
0xdd323ae4d1c8b1, 0x932b56be7685a3},
{0x9ef93dea25dbbf, 0x41665960f390f0,
0xfdec76dbe2a8a7, 0x523e80f019062a},
{1, 0, 0, 0}},
{{0x822fdd26732c73, 0xa01c83531b5d0f,
0x363f37347c1ba4, 0xc391b45c84725c},
{0xbbd5e1b2d6ad24, 0xddfbcde19dfaec,
0xc393da7e222a7f, 0x1efb7890ede244},
{1, 0, 0, 0}},
{{0x4c9e90ca217da1, 0xd11beca79159bb,
0xff8d33c2c98b7c, 0x2610b39409f849},
{0x44d1352ac64da0, 0xcdbb7b2c46b4fb,
0x966c079b753c89, 0xfe67e4e820b112},
{1, 0, 0, 0}},
{{0xe28cae2df5312d, 0xc71b61d16f5c6e,
0x79b7619a3e7c4c, 0x05c73240899b47},
{0x9f7f6382c73e3a, 0x18615165c56bda,
0x641fab2116fd56, 0x72855882b08394},
{1, 0, 0, 0}},
{{0x0469182f161c09, 0x74a98ca8d00fb5,
0xb89da93489a3e0, 0x41c98768fb0c1d},
{0xe5ea05fb32da81, 0x3dce9ffbca6855,
0x1cfe2d3fbf59e6, 0x0e5e03408738a7},
{1, 0, 0, 0}},
{{0xdab22b2333e87f, 0x4430137a5dd2f6,
0xe03ab9f738beb8, 0xcb0c5d0dc34f24},
{0x764a7df0c8fda5, 0x185ba5c3fa2044,
0x9281d688bcbe50, 0xc40331df893881},
{1, 0, 0, 0}},
{{0xb89530796f0f60, 0xade92bd26909a3,
0x1a0c83fb4884da, 0x1765bf22a5a984},
{0x772a9ee75db09e, 0x23bc6c67cec16f,
0x4c1edba8b14e2f, 0xe2a215d9611369},
{1, 0, 0, 0}},
{{0x571e509fb5efb3, 0xade88696410552,
0xc8ae85fada74fe, 0x6c7e4be83bbde3},
{0xff9f51160f4652, 0xb47ce2495a6539,
0xa2946c53b582f4, 0x286d2db3ee9a60},
{1, 0, 0, 0}},
{{0x40bbd5081a44af, 0x0995183b13926c,
0xbcefba6f47f6d0, 0x215619e9cc0057},
{0x8bc94d3b0df45e, 0xf11c54a3694f6f,
0x8631b93cdfe8b5, 0xe7e3f4b0982db9},
{1, 0, 0, 0}},
{{0xb17048ab3e1c7b, 0xac38f36ff8a1d8,
0x1c29819435d2c6, 0xc813132f4c07e9},
{0x2891425503b11f, 0x08781030579fea,
0xf5426ba5cc9674, 0x1e28ebf18562bc},
{1, 0, 0, 0}},
{{0x9f31997cc864eb, 0x06cd91d28b5e4c,
0xff17036691a973, 0xf1aef351497c58},
{0xdd1f2d600564ff, 0xdead073b1402db,
0x74a684435bd693, 0xeea7471f962558},
{1, 0, 0, 0}}},
{{{0, 0, 0, 0},
{0, 0, 0, 0},
{0, 0, 0, 0}},
{{0x9665266dddf554, 0x9613d78b60ef2d, 0xce27a34cdba417, 0xd35ab74d6afc31},
{0x85ccdd22deb15e, 0x2137e5783a6aab, 0xa141cffd8c93c6, 0x355a1830e90f2d},
{1, 0, 0, 0}},
{{0x1a494eadaade65, 0xd6da4da77fe53c, 0xe7992996abec86, 0x65c3553c6090e3},
{0xfa610b1fb09346, 0xf1c6540b8a4aaf, 0xc51a13ccd3cbab, 0x02995b1b18c28a},
{1, 0, 0, 0}},
{{0x7874568e7295ef, 0x86b419fbe38d04, 0xdc0690a7550d9a, 0xd3966a44beac33},
{0x2b7280ec29132f, 0xbeaa3b6a032df3, 0xdc7dd88ae41200, 0xd25e2513e3a100},
{1, 0, 0, 0}},
{{0x924857eb2efafd, 0xac2bce41223190, 0x8edaa1445553fc, 0x825800fd3562d5},
{0x8d79148ea96621, 0x23a01c3dd9ed8d, 0xaf8b219f9416b5, 0xd8db0cc277daea},
{1, 0, 0, 0}},
{{0x76a9c3b1a700f0, 0xe9acd29bc7e691, 0x69212d1a6b0327, 0x6322e97fe154be},
{0x469fc5465d62aa, 0x8d41ed18883b05, 0x1f8eae66c52b88, 0xe4fcbe9325be51},
{1, 0, 0, 0}},
{{0x825fdf583cac16, 0x020b857c7b023a, 0x683c17744b0165, 0x14ffd0a2daf2f1},
{0x323b36184218f9, 0x4944ec4e3b47d4, 0xc15b3080841acf, 0x0bced4b01a28bb},
{1, 0, 0, 0}},
{{0x92ac22230df5c4, 0x52f33b4063eda8, 0xcb3f19870c0c93, 0x40064f2ba65233},
{0xfe16f0924f8992, 0x012da25af5b517, 0x1a57bb24f723a6, 0x06f8bc76760def},
{1, 0, 0, 0}},
{{0x4a7084f7817cb9, 0xbcab0738ee9a78, 0x3ec11e11d9c326, 0xdc0fe90e0f1aae},
{0xcf639ea5f98390, 0x5c350aa22ffb74, 0x9afae98a4047b7, 0x956ec2d617fc45},
{1, 0, 0, 0}},
{{0x4306d648c1be6a, 0x9247cd8bc9a462, 0xf5595e377d2f2e, 0xbd1c3caff1a52e},
{0x045e14472409d0, 0x29f3e17078f773, 0x745a602b2d4f7d, 0x191837685cdfbb},
{1, 0, 0, 0}},
{{0x5b6ee254a8cb79, 0x4953433f5e7026, 0xe21faeb1d1def4, 0xc4c225785c09de},
{0x307ce7bba1e518, 0x31b125b1036db8, 0x47e91868839e8f, 0xc765866e33b9f3},
{1, 0, 0, 0}},
{{0x3bfece24f96906, 0x4794da641e5093, 0xde5df64f95db26, 0x297ecd89714b05},
{0x701bd3ebb2c3aa, 0x7073b4f53cb1d5, 0x13c5665658af16, 0x9895089d66fe58},
{1, 0, 0, 0}},
{{0x0fef05f78c4790, 0x2d773633b05d2e, 0x94229c3a951c94, 0xbbbd70df4911bb},
{0xb2c6963d2c1168, 0x105f47a72b0d73, 0x9fdf6111614080, 0x7b7e94b39e67b0},
{1, 0, 0, 0}},
{{0xad1a7d6efbe2b3, 0xf012482c0da69d, 0x6b3bdf12438345, 0x40d7558d7aa4d9},
{0x8a09fffb5c6d3d, 0x9a356e5d9ffd38, 0x5973f15f4f9b1c, 0xdcd5f59f63c3ea},
{1, 0, 0, 0}},
{{0xacf39f4c5ca7ab, 0x4c8071cc5fd737, 0xc64e3602cd1184, 0x0acd4644c9abba},
{0x6c011a36d8bf6e, 0xfecd87ba24e32a, 0x19f6f56574fad8, 0x050b204ced9405},
{1, 0, 0, 0}},
{{0xed4f1cae7d9a96, 0x5ceef7ad94c40a, 0x778e4a3bf3ef9b, 0x7405783dc3b55e},
{0x32477c61b6e8c6, 0xb46a97570f018b, 0x91176d0a7e95d1, 0x3df90fbc4c7d0e},
{1, 0, 0, 0}}}
};
/* Precomputation for the group generator. */
typedef struct {
felem g_pre_comp[2][16][3];
int references;
} NISTP224_PRE_COMP;
const EC_METHOD *EC_GFp_nistp224_method(void)
{
static const EC_METHOD ret = {
EC_FLAGS_DEFAULT_OCT,
NID_X9_62_prime_field,
ec_GFp_nistp224_group_init,
ec_GFp_simple_group_finish,
ec_GFp_simple_group_clear_finish,
ec_GFp_nist_group_copy,
ec_GFp_nistp224_group_set_curve,
ec_GFp_simple_group_get_curve,
ec_GFp_simple_group_get_degree,
ec_GFp_simple_group_check_discriminant,
ec_GFp_simple_point_init,
ec_GFp_simple_point_finish,
ec_GFp_simple_point_clear_finish,
ec_GFp_simple_point_copy,
ec_GFp_simple_point_set_to_infinity,
ec_GFp_simple_set_Jprojective_coordinates_GFp,
ec_GFp_simple_get_Jprojective_coordinates_GFp,
ec_GFp_simple_point_set_affine_coordinates,
ec_GFp_nistp224_point_get_affine_coordinates,
0 /* point_set_compressed_coordinates */ ,
0 /* point2oct */ ,
0 /* oct2point */ ,
ec_GFp_simple_add,
ec_GFp_simple_dbl,
ec_GFp_simple_invert,
ec_GFp_simple_is_at_infinity,
ec_GFp_simple_is_on_curve,
ec_GFp_simple_cmp,
ec_GFp_simple_make_affine,
ec_GFp_simple_points_make_affine,
ec_GFp_nistp224_points_mul,
ec_GFp_nistp224_precompute_mult,
ec_GFp_nistp224_have_precompute_mult,
ec_GFp_nist_field_mul,
ec_GFp_nist_field_sqr,
0 /* field_div */ ,
0 /* field_encode */ ,
0 /* field_decode */ ,
0 /* field_set_to_one */
};
return &ret;
}
/*
* Helper functions to convert field elements to/from internal representation
*/
static void bin28_to_felem(felem out, const u8 in[28])
{
out[0] = *((const uint64_t *)(in)) & 0x00ffffffffffffff;
out[1] = (*((const uint64_t *)(in + 7))) & 0x00ffffffffffffff;
out[2] = (*((const uint64_t *)(in + 14))) & 0x00ffffffffffffff;
out[3] = (*((const uint64_t *)(in+20))) >> 8;
}
static void felem_to_bin28(u8 out[28], const felem in)
{
unsigned i;
for (i = 0; i < 7; ++i) {
out[i] = in[0] >> (8 * i);
out[i + 7] = in[1] >> (8 * i);
out[i + 14] = in[2] >> (8 * i);
out[i + 21] = in[3] >> (8 * i);
}
}
/* To preserve endianness when using BN_bn2bin and BN_bin2bn */
static void flip_endian(u8 *out, const u8 *in, unsigned len)
{
unsigned i;
for (i = 0; i < len; ++i)
out[i] = in[len - 1 - i];
}
/* From OpenSSL BIGNUM to internal representation */
static int BN_to_felem(felem out, const BIGNUM *bn)
{
felem_bytearray b_in;
felem_bytearray b_out;
unsigned num_bytes;
/* BN_bn2bin eats leading zeroes */
- memset(b_out, 0, sizeof b_out);
+ memset(b_out, 0, sizeof(b_out));
num_bytes = BN_num_bytes(bn);
- if (num_bytes > sizeof b_out) {
+ if (num_bytes > sizeof(b_out)) {
ECerr(EC_F_BN_TO_FELEM, EC_R_BIGNUM_OUT_OF_RANGE);
return 0;
}
if (BN_is_negative(bn)) {
ECerr(EC_F_BN_TO_FELEM, EC_R_BIGNUM_OUT_OF_RANGE);
return 0;
}
num_bytes = BN_bn2bin(bn, b_in);
flip_endian(b_out, b_in, num_bytes);
bin28_to_felem(out, b_out);
return 1;
}
/* From internal representation to OpenSSL BIGNUM */
static BIGNUM *felem_to_BN(BIGNUM *out, const felem in)
{
felem_bytearray b_in, b_out;
felem_to_bin28(b_in, in);
- flip_endian(b_out, b_in, sizeof b_out);
- return BN_bin2bn(b_out, sizeof b_out, out);
+ flip_endian(b_out, b_in, sizeof(b_out));
+ return BN_bin2bn(b_out, sizeof(b_out), out);
}
/******************************************************************************/
/*-
* FIELD OPERATIONS
*
* Field operations, using the internal representation of field elements.
* NB! These operations are specific to our point multiplication and cannot be
* expected to be correct in general - e.g., multiplication with a large scalar
* will cause an overflow.
*
*/
static void felem_one(felem out)
{
out[0] = 1;
out[1] = 0;
out[2] = 0;
out[3] = 0;
}
static void felem_assign(felem out, const felem in)
{
out[0] = in[0];
out[1] = in[1];
out[2] = in[2];
out[3] = in[3];
}
/* Sum two field elements: out += in */
static void felem_sum(felem out, const felem in)
{
out[0] += in[0];
out[1] += in[1];
out[2] += in[2];
out[3] += in[3];
}
/* Get negative value: out = -in */
/* Assumes in[i] < 2^57 */
static void felem_neg(felem out, const felem in)
{
static const limb two58p2 = (((limb) 1) << 58) + (((limb) 1) << 2);
static const limb two58m2 = (((limb) 1) << 58) - (((limb) 1) << 2);
static const limb two58m42m2 = (((limb) 1) << 58) -
(((limb) 1) << 42) - (((limb) 1) << 2);
/* Set to 0 mod 2^224-2^96+1 to ensure out > in */
out[0] = two58p2 - in[0];
out[1] = two58m42m2 - in[1];
out[2] = two58m2 - in[2];
out[3] = two58m2 - in[3];
}
/* Subtract field elements: out -= in */
/* Assumes in[i] < 2^57 */
static void felem_diff(felem out, const felem in)
{
static const limb two58p2 = (((limb) 1) << 58) + (((limb) 1) << 2);
static const limb two58m2 = (((limb) 1) << 58) - (((limb) 1) << 2);
static const limb two58m42m2 = (((limb) 1) << 58) -
(((limb) 1) << 42) - (((limb) 1) << 2);
/* Add 0 mod 2^224-2^96+1 to ensure out > in */
out[0] += two58p2;
out[1] += two58m42m2;
out[2] += two58m2;
out[3] += two58m2;
out[0] -= in[0];
out[1] -= in[1];
out[2] -= in[2];
out[3] -= in[3];
}
/* Subtract in unreduced 128-bit mode: out -= in */
/* Assumes in[i] < 2^119 */
static void widefelem_diff(widefelem out, const widefelem in)
{
static const widelimb two120 = ((widelimb) 1) << 120;
static const widelimb two120m64 = (((widelimb) 1) << 120) -
(((widelimb) 1) << 64);
static const widelimb two120m104m64 = (((widelimb) 1) << 120) -
(((widelimb) 1) << 104) - (((widelimb) 1) << 64);
/* Add 0 mod 2^224-2^96+1 to ensure out > in */
out[0] += two120;
out[1] += two120m64;
out[2] += two120m64;
out[3] += two120;
out[4] += two120m104m64;
out[5] += two120m64;
out[6] += two120m64;
out[0] -= in[0];
out[1] -= in[1];
out[2] -= in[2];
out[3] -= in[3];
out[4] -= in[4];
out[5] -= in[5];
out[6] -= in[6];
}
/* Subtract in mixed mode: out128 -= in64 */
/* in[i] < 2^63 */
static void felem_diff_128_64(widefelem out, const felem in)
{
static const widelimb two64p8 = (((widelimb) 1) << 64) +
(((widelimb) 1) << 8);
static const widelimb two64m8 = (((widelimb) 1) << 64) -
(((widelimb) 1) << 8);
static const widelimb two64m48m8 = (((widelimb) 1) << 64) -
(((widelimb) 1) << 48) - (((widelimb) 1) << 8);
/* Add 0 mod 2^224-2^96+1 to ensure out > in */
out[0] += two64p8;
out[1] += two64m48m8;
out[2] += two64m8;
out[3] += two64m8;
out[0] -= in[0];
out[1] -= in[1];
out[2] -= in[2];
out[3] -= in[3];
}
/*
* Multiply a field element by a scalar: out = out * scalar The scalars we
* actually use are small, so results fit without overflow
*/
static void felem_scalar(felem out, const limb scalar)
{
out[0] *= scalar;
out[1] *= scalar;
out[2] *= scalar;
out[3] *= scalar;
}
/*
* Multiply an unreduced field element by a scalar: out = out * scalar The
* scalars we actually use are small, so results fit without overflow
*/
static void widefelem_scalar(widefelem out, const widelimb scalar)
{
out[0] *= scalar;
out[1] *= scalar;
out[2] *= scalar;
out[3] *= scalar;
out[4] *= scalar;
out[5] *= scalar;
out[6] *= scalar;
}
/* Square a field element: out = in^2 */
static void felem_square(widefelem out, const felem in)
{
limb tmp0, tmp1, tmp2;
tmp0 = 2 * in[0];
tmp1 = 2 * in[1];
tmp2 = 2 * in[2];
out[0] = ((widelimb) in[0]) * in[0];
out[1] = ((widelimb) in[0]) * tmp1;
out[2] = ((widelimb) in[0]) * tmp2 + ((widelimb) in[1]) * in[1];
out[3] = ((widelimb) in[3]) * tmp0 + ((widelimb) in[1]) * tmp2;
out[4] = ((widelimb) in[3]) * tmp1 + ((widelimb) in[2]) * in[2];
out[5] = ((widelimb) in[3]) * tmp2;
out[6] = ((widelimb) in[3]) * in[3];
}
/* Multiply two field elements: out = in1 * in2 */
static void felem_mul(widefelem out, const felem in1, const felem in2)
{
out[0] = ((widelimb) in1[0]) * in2[0];
out[1] = ((widelimb) in1[0]) * in2[1] + ((widelimb) in1[1]) * in2[0];
out[2] = ((widelimb) in1[0]) * in2[2] + ((widelimb) in1[1]) * in2[1] +
((widelimb) in1[2]) * in2[0];
out[3] = ((widelimb) in1[0]) * in2[3] + ((widelimb) in1[1]) * in2[2] +
((widelimb) in1[2]) * in2[1] + ((widelimb) in1[3]) * in2[0];
out[4] = ((widelimb) in1[1]) * in2[3] + ((widelimb) in1[2]) * in2[2] +
((widelimb) in1[3]) * in2[1];
out[5] = ((widelimb) in1[2]) * in2[3] + ((widelimb) in1[3]) * in2[2];
out[6] = ((widelimb) in1[3]) * in2[3];
}
/*-
* Reduce seven 128-bit coefficients to four 64-bit coefficients.
* Requires in[i] < 2^126,
* ensures out[0] < 2^56, out[1] < 2^56, out[2] < 2^56, out[3] <= 2^56 + 2^16 */
static void felem_reduce(felem out, const widefelem in)
{
static const widelimb two127p15 = (((widelimb) 1) << 127) +
(((widelimb) 1) << 15);
static const widelimb two127m71 = (((widelimb) 1) << 127) -
(((widelimb) 1) << 71);
static const widelimb two127m71m55 = (((widelimb) 1) << 127) -
(((widelimb) 1) << 71) - (((widelimb) 1) << 55);
widelimb output[5];
/* Add 0 mod 2^224-2^96+1 to ensure all differences are positive */
output[0] = in[0] + two127p15;
output[1] = in[1] + two127m71m55;
output[2] = in[2] + two127m71;
output[3] = in[3];
output[4] = in[4];
/* Eliminate in[4], in[5], in[6] */
output[4] += in[6] >> 16;
output[3] += (in[6] & 0xffff) << 40;
output[2] -= in[6];
output[3] += in[5] >> 16;
output[2] += (in[5] & 0xffff) << 40;
output[1] -= in[5];
output[2] += output[4] >> 16;
output[1] += (output[4] & 0xffff) << 40;
output[0] -= output[4];
/* Carry 2 -> 3 -> 4 */
output[3] += output[2] >> 56;
output[2] &= 0x00ffffffffffffff;
output[4] = output[3] >> 56;
output[3] &= 0x00ffffffffffffff;
/* Now output[2] < 2^56, output[3] < 2^56, output[4] < 2^72 */
/* Eliminate output[4] */
output[2] += output[4] >> 16;
/* output[2] < 2^56 + 2^56 = 2^57 */
output[1] += (output[4] & 0xffff) << 40;
output[0] -= output[4];
/* Carry 0 -> 1 -> 2 -> 3 */
output[1] += output[0] >> 56;
out[0] = output[0] & 0x00ffffffffffffff;
output[2] += output[1] >> 56;
/* output[2] < 2^57 + 2^72 */
out[1] = output[1] & 0x00ffffffffffffff;
output[3] += output[2] >> 56;
/* output[3] <= 2^56 + 2^16 */
out[2] = output[2] & 0x00ffffffffffffff;
/*-
* out[0] < 2^56, out[1] < 2^56, out[2] < 2^56,
* out[3] <= 2^56 + 2^16 (due to final carry),
* so out < 2*p
*/
out[3] = output[3];
}
static void felem_square_reduce(felem out, const felem in)
{
widefelem tmp;
felem_square(tmp, in);
felem_reduce(out, tmp);
}
static void felem_mul_reduce(felem out, const felem in1, const felem in2)
{
widefelem tmp;
felem_mul(tmp, in1, in2);
felem_reduce(out, tmp);
}
/*
* Reduce to unique minimal representation. Requires 0 <= in < 2*p (always
* call felem_reduce first)
*/
static void felem_contract(felem out, const felem in)
{
static const int64_t two56 = ((limb) 1) << 56;
/* 0 <= in < 2*p, p = 2^224 - 2^96 + 1 */
/* if in > p , reduce in = in - 2^224 + 2^96 - 1 */
int64_t tmp[4], a;
tmp[0] = in[0];
tmp[1] = in[1];
tmp[2] = in[2];
tmp[3] = in[3];
/* Case 1: a = 1 iff in >= 2^224 */
a = (in[3] >> 56);
tmp[0] -= a;
tmp[1] += a << 40;
tmp[3] &= 0x00ffffffffffffff;
/*
* Case 2: a = 0 iff p <= in < 2^224, i.e., the high 128 bits are all 1
* and the lower part is non-zero
*/
a = ((in[3] & in[2] & (in[1] | 0x000000ffffffffff)) + 1) |
(((int64_t) (in[0] + (in[1] & 0x000000ffffffffff)) - 1) >> 63);
a &= 0x00ffffffffffffff;
/* turn a into an all-one mask (if a = 0) or an all-zero mask */
a = (a - 1) >> 63;
/* subtract 2^224 - 2^96 + 1 if a is all-one */
tmp[3] &= a ^ 0xffffffffffffffff;
tmp[2] &= a ^ 0xffffffffffffffff;
tmp[1] &= (a ^ 0xffffffffffffffff) | 0x000000ffffffffff;
tmp[0] -= 1 & a;
/*
* eliminate negative coefficients: if tmp[0] is negative, tmp[1] must be
* non-zero, so we only need one step
*/
a = tmp[0] >> 63;
tmp[0] += two56 & a;
tmp[1] -= 1 & a;
/* carry 1 -> 2 -> 3 */
tmp[2] += tmp[1] >> 56;
tmp[1] &= 0x00ffffffffffffff;
tmp[3] += tmp[2] >> 56;
tmp[2] &= 0x00ffffffffffffff;
/* Now 0 <= out < p */
out[0] = tmp[0];
out[1] = tmp[1];
out[2] = tmp[2];
out[3] = tmp[3];
}
/*
* Zero-check: returns 1 if input is 0, and 0 otherwise. We know that field
* elements are reduced to in < 2^225, so we only need to check three cases:
* 0, 2^224 - 2^96 + 1, and 2^225 - 2^97 + 2
*/
static limb felem_is_zero(const felem in)
{
limb zero, two224m96p1, two225m97p2;
zero = in[0] | in[1] | in[2] | in[3];
zero = (((int64_t) (zero) - 1) >> 63) & 1;
two224m96p1 = (in[0] ^ 1) | (in[1] ^ 0x00ffff0000000000)
| (in[2] ^ 0x00ffffffffffffff) | (in[3] ^ 0x00ffffffffffffff);
two224m96p1 = (((int64_t) (two224m96p1) - 1) >> 63) & 1;
two225m97p2 = (in[0] ^ 2) | (in[1] ^ 0x00fffe0000000000)
| (in[2] ^ 0x00ffffffffffffff) | (in[3] ^ 0x01ffffffffffffff);
two225m97p2 = (((int64_t) (two225m97p2) - 1) >> 63) & 1;
return (zero | two224m96p1 | two225m97p2);
}
static int felem_is_zero_int(const void *in)
{
return (int)(felem_is_zero(in) & ((limb) 1));
}
/* Invert a field element */
/* Computation chain copied from djb's code */
static void felem_inv(felem out, const felem in)
{
felem ftmp, ftmp2, ftmp3, ftmp4;
widefelem tmp;
unsigned i;
felem_square(tmp, in);
felem_reduce(ftmp, tmp); /* 2 */
felem_mul(tmp, in, ftmp);
felem_reduce(ftmp, tmp); /* 2^2 - 1 */
felem_square(tmp, ftmp);
felem_reduce(ftmp, tmp); /* 2^3 - 2 */
felem_mul(tmp, in, ftmp);
felem_reduce(ftmp, tmp); /* 2^3 - 1 */
felem_square(tmp, ftmp);
felem_reduce(ftmp2, tmp); /* 2^4 - 2 */
felem_square(tmp, ftmp2);
felem_reduce(ftmp2, tmp); /* 2^5 - 4 */
felem_square(tmp, ftmp2);
felem_reduce(ftmp2, tmp); /* 2^6 - 8 */
felem_mul(tmp, ftmp2, ftmp);
felem_reduce(ftmp, tmp); /* 2^6 - 1 */
felem_square(tmp, ftmp);
felem_reduce(ftmp2, tmp); /* 2^7 - 2 */
for (i = 0; i < 5; ++i) { /* 2^12 - 2^6 */
felem_square(tmp, ftmp2);
felem_reduce(ftmp2, tmp);
}
felem_mul(tmp, ftmp2, ftmp);
felem_reduce(ftmp2, tmp); /* 2^12 - 1 */
felem_square(tmp, ftmp2);
felem_reduce(ftmp3, tmp); /* 2^13 - 2 */
for (i = 0; i < 11; ++i) { /* 2^24 - 2^12 */
felem_square(tmp, ftmp3);
felem_reduce(ftmp3, tmp);
}
felem_mul(tmp, ftmp3, ftmp2);
felem_reduce(ftmp2, tmp); /* 2^24 - 1 */
felem_square(tmp, ftmp2);
felem_reduce(ftmp3, tmp); /* 2^25 - 2 */
for (i = 0; i < 23; ++i) { /* 2^48 - 2^24 */
felem_square(tmp, ftmp3);
felem_reduce(ftmp3, tmp);
}
felem_mul(tmp, ftmp3, ftmp2);
felem_reduce(ftmp3, tmp); /* 2^48 - 1 */
felem_square(tmp, ftmp3);
felem_reduce(ftmp4, tmp); /* 2^49 - 2 */
for (i = 0; i < 47; ++i) { /* 2^96 - 2^48 */
felem_square(tmp, ftmp4);
felem_reduce(ftmp4, tmp);
}
felem_mul(tmp, ftmp3, ftmp4);
felem_reduce(ftmp3, tmp); /* 2^96 - 1 */
felem_square(tmp, ftmp3);
felem_reduce(ftmp4, tmp); /* 2^97 - 2 */
for (i = 0; i < 23; ++i) { /* 2^120 - 2^24 */
felem_square(tmp, ftmp4);
felem_reduce(ftmp4, tmp);
}
felem_mul(tmp, ftmp2, ftmp4);
felem_reduce(ftmp2, tmp); /* 2^120 - 1 */
for (i = 0; i < 6; ++i) { /* 2^126 - 2^6 */
felem_square(tmp, ftmp2);
felem_reduce(ftmp2, tmp);
}
felem_mul(tmp, ftmp2, ftmp);
felem_reduce(ftmp, tmp); /* 2^126 - 1 */
felem_square(tmp, ftmp);
felem_reduce(ftmp, tmp); /* 2^127 - 2 */
felem_mul(tmp, ftmp, in);
felem_reduce(ftmp, tmp); /* 2^127 - 1 */
for (i = 0; i < 97; ++i) { /* 2^224 - 2^97 */
felem_square(tmp, ftmp);
felem_reduce(ftmp, tmp);
}
felem_mul(tmp, ftmp, ftmp3);
felem_reduce(out, tmp); /* 2^224 - 2^96 - 1 */
}
/*
* Copy in constant time: if icopy == 1, copy in to out, if icopy == 0, copy
* out to itself.
*/
static void copy_conditional(felem out, const felem in, limb icopy)
{
unsigned i;
/*
* icopy is a (64-bit) 0 or 1, so copy is either all-zero or all-one
*/
const limb copy = -icopy;
for (i = 0; i < 4; ++i) {
const limb tmp = copy & (in[i] ^ out[i]);
out[i] ^= tmp;
}
}
/******************************************************************************/
/*-
* ELLIPTIC CURVE POINT OPERATIONS
*
* Points are represented in Jacobian projective coordinates:
* (X, Y, Z) corresponds to the affine point (X/Z^2, Y/Z^3),
* or to the point at infinity if Z == 0.
*
*/
/*-
* Double an elliptic curve point:
* (X', Y', Z') = 2 * (X, Y, Z), where
* X' = (3 * (X - Z^2) * (X + Z^2))^2 - 8 * X * Y^2
* Y' = 3 * (X - Z^2) * (X + Z^2) * (4 * X * Y^2 - X') - 8 * Y^2
* Z' = (Y + Z)^2 - Y^2 - Z^2 = 2 * Y * Z
* Outputs can equal corresponding inputs, i.e., x_out == x_in is allowed,
* while x_out == y_in is not (maybe this works, but it's not tested).
*/
static void
point_double(felem x_out, felem y_out, felem z_out,
const felem x_in, const felem y_in, const felem z_in)
{
widefelem tmp, tmp2;
felem delta, gamma, beta, alpha, ftmp, ftmp2;
felem_assign(ftmp, x_in);
felem_assign(ftmp2, x_in);
/* delta = z^2 */
felem_square(tmp, z_in);
felem_reduce(delta, tmp);
/* gamma = y^2 */
felem_square(tmp, y_in);
felem_reduce(gamma, tmp);
/* beta = x*gamma */
felem_mul(tmp, x_in, gamma);
felem_reduce(beta, tmp);
/* alpha = 3*(x-delta)*(x+delta) */
felem_diff(ftmp, delta);
/* ftmp[i] < 2^57 + 2^58 + 2 < 2^59 */
felem_sum(ftmp2, delta);
/* ftmp2[i] < 2^57 + 2^57 = 2^58 */
felem_scalar(ftmp2, 3);
/* ftmp2[i] < 3 * 2^58 < 2^60 */
felem_mul(tmp, ftmp, ftmp2);
/* tmp[i] < 2^60 * 2^59 * 4 = 2^121 */
felem_reduce(alpha, tmp);
/* x' = alpha^2 - 8*beta */
felem_square(tmp, alpha);
/* tmp[i] < 4 * 2^57 * 2^57 = 2^116 */
felem_assign(ftmp, beta);
felem_scalar(ftmp, 8);
/* ftmp[i] < 8 * 2^57 = 2^60 */
felem_diff_128_64(tmp, ftmp);
/* tmp[i] < 2^116 + 2^64 + 8 < 2^117 */
felem_reduce(x_out, tmp);
/* z' = (y + z)^2 - gamma - delta */
felem_sum(delta, gamma);
/* delta[i] < 2^57 + 2^57 = 2^58 */
felem_assign(ftmp, y_in);
felem_sum(ftmp, z_in);
/* ftmp[i] < 2^57 + 2^57 = 2^58 */
felem_square(tmp, ftmp);
/* tmp[i] < 4 * 2^58 * 2^58 = 2^118 */
felem_diff_128_64(tmp, delta);
/* tmp[i] < 2^118 + 2^64 + 8 < 2^119 */
felem_reduce(z_out, tmp);
/* y' = alpha*(4*beta - x') - 8*gamma^2 */
felem_scalar(beta, 4);
/* beta[i] < 4 * 2^57 = 2^59 */
felem_diff(beta, x_out);
/* beta[i] < 2^59 + 2^58 + 2 < 2^60 */
felem_mul(tmp, alpha, beta);
/* tmp[i] < 4 * 2^57 * 2^60 = 2^119 */
felem_square(tmp2, gamma);
/* tmp2[i] < 4 * 2^57 * 2^57 = 2^116 */
widefelem_scalar(tmp2, 8);
/* tmp2[i] < 8 * 2^116 = 2^119 */
widefelem_diff(tmp, tmp2);
/* tmp[i] < 2^119 + 2^120 < 2^121 */
felem_reduce(y_out, tmp);
}
/*-
* Add two elliptic curve points:
* (X_1, Y_1, Z_1) + (X_2, Y_2, Z_2) = (X_3, Y_3, Z_3), where
* X_3 = (Z_1^3 * Y_2 - Z_2^3 * Y_1)^2 - (Z_1^2 * X_2 - Z_2^2 * X_1)^3 -
* 2 * Z_2^2 * X_1 * (Z_1^2 * X_2 - Z_2^2 * X_1)^2
* Y_3 = (Z_1^3 * Y_2 - Z_2^3 * Y_1) * (Z_2^2 * X_1 * (Z_1^2 * X_2 - Z_2^2 * X_1)^2 - X_3) -
* Z_2^3 * Y_1 * (Z_1^2 * X_2 - Z_2^2 * X_1)^3
* Z_3 = (Z_1^2 * X_2 - Z_2^2 * X_1) * (Z_1 * Z_2)
*
* This runs faster if 'mixed' is set, which requires Z_2 = 1 or Z_2 = 0.
*/
/*
* This function is not entirely constant-time: it includes a branch for
* checking whether the two input points are equal, (while not equal to the
* point at infinity). This case never happens during single point
* multiplication, so there is no timing leak for ECDH or ECDSA signing.
*/
static void point_add(felem x3, felem y3, felem z3,
const felem x1, const felem y1, const felem z1,
const int mixed, const felem x2, const felem y2,
const felem z2)
{
felem ftmp, ftmp2, ftmp3, ftmp4, ftmp5, x_out, y_out, z_out;
widefelem tmp, tmp2;
limb z1_is_zero, z2_is_zero, x_equal, y_equal;
if (!mixed) {
/* ftmp2 = z2^2 */
felem_square(tmp, z2);
felem_reduce(ftmp2, tmp);
/* ftmp4 = z2^3 */
felem_mul(tmp, ftmp2, z2);
felem_reduce(ftmp4, tmp);
/* ftmp4 = z2^3*y1 */
felem_mul(tmp2, ftmp4, y1);
felem_reduce(ftmp4, tmp2);
/* ftmp2 = z2^2*x1 */
felem_mul(tmp2, ftmp2, x1);
felem_reduce(ftmp2, tmp2);
} else {
/*
* We'll assume z2 = 1 (special case z2 = 0 is handled later)
*/
/* ftmp4 = z2^3*y1 */
felem_assign(ftmp4, y1);
/* ftmp2 = z2^2*x1 */
felem_assign(ftmp2, x1);
}
/* ftmp = z1^2 */
felem_square(tmp, z1);
felem_reduce(ftmp, tmp);
/* ftmp3 = z1^3 */
felem_mul(tmp, ftmp, z1);
felem_reduce(ftmp3, tmp);
/* tmp = z1^3*y2 */
felem_mul(tmp, ftmp3, y2);
/* tmp[i] < 4 * 2^57 * 2^57 = 2^116 */
/* ftmp3 = z1^3*y2 - z2^3*y1 */
felem_diff_128_64(tmp, ftmp4);
/* tmp[i] < 2^116 + 2^64 + 8 < 2^117 */
felem_reduce(ftmp3, tmp);
/* tmp = z1^2*x2 */
felem_mul(tmp, ftmp, x2);
/* tmp[i] < 4 * 2^57 * 2^57 = 2^116 */
/* ftmp = z1^2*x2 - z2^2*x1 */
felem_diff_128_64(tmp, ftmp2);
/* tmp[i] < 2^116 + 2^64 + 8 < 2^117 */
felem_reduce(ftmp, tmp);
/*
* the formulae are incorrect if the points are equal so we check for
* this and do doubling if this happens
*/
x_equal = felem_is_zero(ftmp);
y_equal = felem_is_zero(ftmp3);
z1_is_zero = felem_is_zero(z1);
z2_is_zero = felem_is_zero(z2);
/* In affine coordinates, (X_1, Y_1) == (X_2, Y_2) */
if (x_equal && y_equal && !z1_is_zero && !z2_is_zero) {
point_double(x3, y3, z3, x1, y1, z1);
return;
}
/* ftmp5 = z1*z2 */
if (!mixed) {
felem_mul(tmp, z1, z2);
felem_reduce(ftmp5, tmp);
} else {
/* special case z2 = 0 is handled later */
felem_assign(ftmp5, z1);
}
/* z_out = (z1^2*x2 - z2^2*x1)*(z1*z2) */
felem_mul(tmp, ftmp, ftmp5);
felem_reduce(z_out, tmp);
/* ftmp = (z1^2*x2 - z2^2*x1)^2 */
felem_assign(ftmp5, ftmp);
felem_square(tmp, ftmp);
felem_reduce(ftmp, tmp);
/* ftmp5 = (z1^2*x2 - z2^2*x1)^3 */
felem_mul(tmp, ftmp, ftmp5);
felem_reduce(ftmp5, tmp);
/* ftmp2 = z2^2*x1*(z1^2*x2 - z2^2*x1)^2 */
felem_mul(tmp, ftmp2, ftmp);
felem_reduce(ftmp2, tmp);
/* tmp = z2^3*y1*(z1^2*x2 - z2^2*x1)^3 */
felem_mul(tmp, ftmp4, ftmp5);
/* tmp[i] < 4 * 2^57 * 2^57 = 2^116 */
/* tmp2 = (z1^3*y2 - z2^3*y1)^2 */
felem_square(tmp2, ftmp3);
/* tmp2[i] < 4 * 2^57 * 2^57 < 2^116 */
/* tmp2 = (z1^3*y2 - z2^3*y1)^2 - (z1^2*x2 - z2^2*x1)^3 */
felem_diff_128_64(tmp2, ftmp5);
/* tmp2[i] < 2^116 + 2^64 + 8 < 2^117 */
/* ftmp5 = 2*z2^2*x1*(z1^2*x2 - z2^2*x1)^2 */
felem_assign(ftmp5, ftmp2);
felem_scalar(ftmp5, 2);
/* ftmp5[i] < 2 * 2^57 = 2^58 */
/*-
* x_out = (z1^3*y2 - z2^3*y1)^2 - (z1^2*x2 - z2^2*x1)^3 -
* 2*z2^2*x1*(z1^2*x2 - z2^2*x1)^2
*/
felem_diff_128_64(tmp2, ftmp5);
/* tmp2[i] < 2^117 + 2^64 + 8 < 2^118 */
felem_reduce(x_out, tmp2);
/* ftmp2 = z2^2*x1*(z1^2*x2 - z2^2*x1)^2 - x_out */
felem_diff(ftmp2, x_out);
/* ftmp2[i] < 2^57 + 2^58 + 2 < 2^59 */
/*
* tmp2 = (z1^3*y2 - z2^3*y1)*(z2^2*x1*(z1^2*x2 - z2^2*x1)^2 - x_out)
*/
felem_mul(tmp2, ftmp3, ftmp2);
/* tmp2[i] < 4 * 2^57 * 2^59 = 2^118 */
/*-
* y_out = (z1^3*y2 - z2^3*y1)*(z2^2*x1*(z1^2*x2 - z2^2*x1)^2 - x_out) -
* z2^3*y1*(z1^2*x2 - z2^2*x1)^3
*/
widefelem_diff(tmp2, tmp);
/* tmp2[i] < 2^118 + 2^120 < 2^121 */
felem_reduce(y_out, tmp2);
/*
* the result (x_out, y_out, z_out) is incorrect if one of the inputs is
* the point at infinity, so we need to check for this separately
*/
/*
* if point 1 is at infinity, copy point 2 to output, and vice versa
*/
copy_conditional(x_out, x2, z1_is_zero);
copy_conditional(x_out, x1, z2_is_zero);
copy_conditional(y_out, y2, z1_is_zero);
copy_conditional(y_out, y1, z2_is_zero);
copy_conditional(z_out, z2, z1_is_zero);
copy_conditional(z_out, z1, z2_is_zero);
felem_assign(x3, x_out);
felem_assign(y3, y_out);
felem_assign(z3, z_out);
}
/*
* select_point selects the |idx|th point from a precomputation table and
* copies it to out.
* The pre_comp array argument should be size of |size| argument
*/
static void select_point(const u64 idx, unsigned int size,
const felem pre_comp[][3], felem out[3])
{
unsigned i, j;
limb *outlimbs = &out[0][0];
memset(outlimbs, 0, 3 * sizeof(felem));
for (i = 0; i < size; i++) {
const limb *inlimbs = &pre_comp[i][0][0];
u64 mask = i ^ idx;
mask |= mask >> 4;
mask |= mask >> 2;
mask |= mask >> 1;
mask &= 1;
mask--;
for (j = 0; j < 4 * 3; j++)
outlimbs[j] |= inlimbs[j] & mask;
}
}
/* get_bit returns the |i|th bit in |in| */
static char get_bit(const felem_bytearray in, unsigned i)
{
if (i >= 224)
return 0;
return (in[i >> 3] >> (i & 7)) & 1;
}
/*
* Interleaved point multiplication using precomputed point multiples: The
* small point multiples 0*P, 1*P, ..., 16*P are in pre_comp[], the scalars
* in scalars[]. If g_scalar is non-NULL, we also add this multiple of the
* generator, using certain (large) precomputed multiples in g_pre_comp.
* Output point (X, Y, Z) is stored in x_out, y_out, z_out
*/
static void batch_mul(felem x_out, felem y_out, felem z_out,
const felem_bytearray scalars[],
const unsigned num_points, const u8 *g_scalar,
const int mixed, const felem pre_comp[][17][3],
const felem g_pre_comp[2][16][3])
{
int i, skip;
unsigned num;
unsigned gen_mul = (g_scalar != NULL);
felem nq[3], tmp[4];
u64 bits;
u8 sign, digit;
/* set nq to the point at infinity */
memset(nq, 0, 3 * sizeof(felem));
/*
* Loop over all scalars msb-to-lsb, interleaving additions of multiples
* of the generator (two in each of the last 28 rounds) and additions of
* other points multiples (every 5th round).
*/
skip = 1; /* save two point operations in the first
* round */
for (i = (num_points ? 220 : 27); i >= 0; --i) {
/* double */
if (!skip)
point_double(nq[0], nq[1], nq[2], nq[0], nq[1], nq[2]);
/* add multiples of the generator */
if (gen_mul && (i <= 27)) {
/* first, look 28 bits upwards */
bits = get_bit(g_scalar, i + 196) << 3;
bits |= get_bit(g_scalar, i + 140) << 2;
bits |= get_bit(g_scalar, i + 84) << 1;
bits |= get_bit(g_scalar, i + 28);
/* select the point to add, in constant time */
select_point(bits, 16, g_pre_comp[1], tmp);
if (!skip) {
/* value 1 below is argument for "mixed" */
point_add(nq[0], nq[1], nq[2],
nq[0], nq[1], nq[2], 1, tmp[0], tmp[1], tmp[2]);
} else {
memcpy(nq, tmp, 3 * sizeof(felem));
skip = 0;
}
/* second, look at the current position */
bits = get_bit(g_scalar, i + 168) << 3;
bits |= get_bit(g_scalar, i + 112) << 2;
bits |= get_bit(g_scalar, i + 56) << 1;
bits |= get_bit(g_scalar, i);
/* select the point to add, in constant time */
select_point(bits, 16, g_pre_comp[0], tmp);
point_add(nq[0], nq[1], nq[2],
nq[0], nq[1], nq[2],
1 /* mixed */ , tmp[0], tmp[1], tmp[2]);
}
/* do other additions every 5 doublings */
if (num_points && (i % 5 == 0)) {
/* loop over all scalars */
for (num = 0; num < num_points; ++num) {
bits = get_bit(scalars[num], i + 4) << 5;
bits |= get_bit(scalars[num], i + 3) << 4;
bits |= get_bit(scalars[num], i + 2) << 3;
bits |= get_bit(scalars[num], i + 1) << 2;
bits |= get_bit(scalars[num], i) << 1;
bits |= get_bit(scalars[num], i - 1);
ec_GFp_nistp_recode_scalar_bits(&sign, &digit, bits);
/* select the point to add or subtract */
select_point(digit, 17, pre_comp[num], tmp);
felem_neg(tmp[3], tmp[1]); /* (X, -Y, Z) is the negative
* point */
copy_conditional(tmp[1], tmp[3], sign);
if (!skip) {
point_add(nq[0], nq[1], nq[2],
nq[0], nq[1], nq[2],
mixed, tmp[0], tmp[1], tmp[2]);
} else {
memcpy(nq, tmp, 3 * sizeof(felem));
skip = 0;
}
}
}
}
felem_assign(x_out, nq[0]);
felem_assign(y_out, nq[1]);
felem_assign(z_out, nq[2]);
}
/******************************************************************************/
/*
* FUNCTIONS TO MANAGE PRECOMPUTATION
*/
static NISTP224_PRE_COMP *nistp224_pre_comp_new()
{
NISTP224_PRE_COMP *ret = NULL;
- ret = (NISTP224_PRE_COMP *) OPENSSL_malloc(sizeof *ret);
+ ret = (NISTP224_PRE_COMP *) OPENSSL_malloc(sizeof(*ret));
if (!ret) {
ECerr(EC_F_NISTP224_PRE_COMP_NEW, ERR_R_MALLOC_FAILURE);
return ret;
}
memset(ret->g_pre_comp, 0, sizeof(ret->g_pre_comp));
ret->references = 1;
return ret;
}
static void *nistp224_pre_comp_dup(void *src_)
{
NISTP224_PRE_COMP *src = src_;
/* no need to actually copy, these objects never change! */
CRYPTO_add(&src->references, 1, CRYPTO_LOCK_EC_PRE_COMP);
return src_;
}
static void nistp224_pre_comp_free(void *pre_)
{
int i;
NISTP224_PRE_COMP *pre = pre_;
if (!pre)
return;
i = CRYPTO_add(&pre->references, -1, CRYPTO_LOCK_EC_PRE_COMP);
if (i > 0)
return;
OPENSSL_free(pre);
}
static void nistp224_pre_comp_clear_free(void *pre_)
{
int i;
NISTP224_PRE_COMP *pre = pre_;
if (!pre)
return;
i = CRYPTO_add(&pre->references, -1, CRYPTO_LOCK_EC_PRE_COMP);
if (i > 0)
return;
- OPENSSL_cleanse(pre, sizeof *pre);
+ OPENSSL_cleanse(pre, sizeof(*pre));
OPENSSL_free(pre);
}
/******************************************************************************/
/*
* OPENSSL EC_METHOD FUNCTIONS
*/
int ec_GFp_nistp224_group_init(EC_GROUP *group)
{
int ret;
ret = ec_GFp_simple_group_init(group);
group->a_is_minus3 = 1;
return ret;
}
int ec_GFp_nistp224_group_set_curve(EC_GROUP *group, const BIGNUM *p,
const BIGNUM *a, const BIGNUM *b,
BN_CTX *ctx)
{
int ret = 0;
BN_CTX *new_ctx = NULL;
BIGNUM *curve_p, *curve_a, *curve_b;
if (ctx == NULL)
if ((ctx = new_ctx = BN_CTX_new()) == NULL)
return 0;
BN_CTX_start(ctx);
if (((curve_p = BN_CTX_get(ctx)) == NULL) ||
((curve_a = BN_CTX_get(ctx)) == NULL) ||
((curve_b = BN_CTX_get(ctx)) == NULL))
goto err;
BN_bin2bn(nistp224_curve_params[0], sizeof(felem_bytearray), curve_p);
BN_bin2bn(nistp224_curve_params[1], sizeof(felem_bytearray), curve_a);
BN_bin2bn(nistp224_curve_params[2], sizeof(felem_bytearray), curve_b);
if ((BN_cmp(curve_p, p)) || (BN_cmp(curve_a, a)) || (BN_cmp(curve_b, b))) {
ECerr(EC_F_EC_GFP_NISTP224_GROUP_SET_CURVE,
EC_R_WRONG_CURVE_PARAMETERS);
goto err;
}
group->field_mod_func = BN_nist_mod_224;
ret = ec_GFp_simple_group_set_curve(group, p, a, b, ctx);
err:
BN_CTX_end(ctx);
if (new_ctx != NULL)
BN_CTX_free(new_ctx);
return ret;
}
/*
* Takes the Jacobian coordinates (X, Y, Z) of a point and returns (X', Y') =
* (X/Z^2, Y/Z^3)
*/
int ec_GFp_nistp224_point_get_affine_coordinates(const EC_GROUP *group,
const EC_POINT *point,
BIGNUM *x, BIGNUM *y,
BN_CTX *ctx)
{
felem z1, z2, x_in, y_in, x_out, y_out;
widefelem tmp;
if (EC_POINT_is_at_infinity(group, point)) {
ECerr(EC_F_EC_GFP_NISTP224_POINT_GET_AFFINE_COORDINATES,
EC_R_POINT_AT_INFINITY);
return 0;
}
if ((!BN_to_felem(x_in, &point->X)) || (!BN_to_felem(y_in, &point->Y)) ||
(!BN_to_felem(z1, &point->Z)))
return 0;
felem_inv(z2, z1);
felem_square(tmp, z2);
felem_reduce(z1, tmp);
felem_mul(tmp, x_in, z1);
felem_reduce(x_in, tmp);
felem_contract(x_out, x_in);
if (x != NULL) {
if (!felem_to_BN(x, x_out)) {
ECerr(EC_F_EC_GFP_NISTP224_POINT_GET_AFFINE_COORDINATES,
ERR_R_BN_LIB);
return 0;
}
}
felem_mul(tmp, z1, z2);
felem_reduce(z1, tmp);
felem_mul(tmp, y_in, z1);
felem_reduce(y_in, tmp);
felem_contract(y_out, y_in);
if (y != NULL) {
if (!felem_to_BN(y, y_out)) {
ECerr(EC_F_EC_GFP_NISTP224_POINT_GET_AFFINE_COORDINATES,
ERR_R_BN_LIB);
return 0;
}
}
return 1;
}
static void make_points_affine(size_t num, felem points[ /* num */ ][3],
felem tmp_felems[ /* num+1 */ ])
{
/*
* Runs in constant time, unless an input is the point at infinity (which
* normally shouldn't happen).
*/
ec_GFp_nistp_points_make_affine_internal(num,
points,
sizeof(felem),
tmp_felems,
(void (*)(void *))felem_one,
felem_is_zero_int,
(void (*)(void *, const void *))
felem_assign,
(void (*)(void *, const void *))
felem_square_reduce, (void (*)
(void *,
const void
*,
const void
*))
felem_mul_reduce,
(void (*)(void *, const void *))
felem_inv,
(void (*)(void *, const void *))
felem_contract);
}
/*
* Computes scalar*generator + \sum scalars[i]*points[i], ignoring NULL
* values Result is stored in r (r can equal one of the inputs).
*/
int ec_GFp_nistp224_points_mul(const EC_GROUP *group, EC_POINT *r,
const BIGNUM *scalar, size_t num,
const EC_POINT *points[],
const BIGNUM *scalars[], BN_CTX *ctx)
{
int ret = 0;
int j;
unsigned i;
int mixed = 0;
BN_CTX *new_ctx = NULL;
BIGNUM *x, *y, *z, *tmp_scalar;
felem_bytearray g_secret;
felem_bytearray *secrets = NULL;
felem(*pre_comp)[17][3] = NULL;
felem *tmp_felems = NULL;
felem_bytearray tmp;
unsigned num_bytes;
int have_pre_comp = 0;
size_t num_points = num;
felem x_in, y_in, z_in, x_out, y_out, z_out;
NISTP224_PRE_COMP *pre = NULL;
const felem(*g_pre_comp)[16][3] = NULL;
EC_POINT *generator = NULL;
const EC_POINT *p = NULL;
const BIGNUM *p_scalar = NULL;
if (ctx == NULL)
if ((ctx = new_ctx = BN_CTX_new()) == NULL)
return 0;
BN_CTX_start(ctx);
if (((x = BN_CTX_get(ctx)) == NULL) ||
((y = BN_CTX_get(ctx)) == NULL) ||
((z = BN_CTX_get(ctx)) == NULL) ||
((tmp_scalar = BN_CTX_get(ctx)) == NULL))
goto err;
if (scalar != NULL) {
pre = EC_EX_DATA_get_data(group->extra_data,
nistp224_pre_comp_dup,
nistp224_pre_comp_free,
nistp224_pre_comp_clear_free);
if (pre)
/* we have precomputation, try to use it */
g_pre_comp = (const felem(*)[16][3])pre->g_pre_comp;
else
/* try to use the standard precomputation */
g_pre_comp = &gmul[0];
generator = EC_POINT_new(group);
if (generator == NULL)
goto err;
/* get the generator from precomputation */
if (!felem_to_BN(x, g_pre_comp[0][1][0]) ||
!felem_to_BN(y, g_pre_comp[0][1][1]) ||
!felem_to_BN(z, g_pre_comp[0][1][2])) {
ECerr(EC_F_EC_GFP_NISTP224_POINTS_MUL, ERR_R_BN_LIB);
goto err;
}
if (!EC_POINT_set_Jprojective_coordinates_GFp(group,
generator, x, y, z,
ctx))
goto err;
if (0 == EC_POINT_cmp(group, generator, group->generator, ctx))
/* precomputation matches generator */
have_pre_comp = 1;
else
/*
* we don't have valid precomputation: treat the generator as a
* random point
*/
num_points = num_points + 1;
}
if (num_points > 0) {
if (num_points >= 3) {
/*
* unless we precompute multiples for just one or two points,
* converting those into affine form is time well spent
*/
mixed = 1;
}
secrets = OPENSSL_malloc(num_points * sizeof(felem_bytearray));
pre_comp = OPENSSL_malloc(num_points * 17 * 3 * sizeof(felem));
if (mixed)
tmp_felems =
OPENSSL_malloc((num_points * 17 + 1) * sizeof(felem));
if ((secrets == NULL) || (pre_comp == NULL)
|| (mixed && (tmp_felems == NULL))) {
ECerr(EC_F_EC_GFP_NISTP224_POINTS_MUL, ERR_R_MALLOC_FAILURE);
goto err;
}
/*
* we treat NULL scalars as 0, and NULL points as points at infinity,
* i.e., they contribute nothing to the linear combination
*/
memset(secrets, 0, num_points * sizeof(felem_bytearray));
memset(pre_comp, 0, num_points * 17 * 3 * sizeof(felem));
for (i = 0; i < num_points; ++i) {
if (i == num)
/* the generator */
{
p = EC_GROUP_get0_generator(group);
p_scalar = scalar;
} else
/* the i^th point */
{
p = points[i];
p_scalar = scalars[i];
}
if ((p_scalar != NULL) && (p != NULL)) {
/* reduce scalar to 0 <= scalar < 2^224 */
if ((BN_num_bits(p_scalar) > 224)
|| (BN_is_negative(p_scalar))) {
/*
* this is an unusual input, and we don't guarantee
* constant-timeness
*/
if (!BN_nnmod(tmp_scalar, p_scalar, &group->order, ctx)) {
ECerr(EC_F_EC_GFP_NISTP224_POINTS_MUL, ERR_R_BN_LIB);
goto err;
}
num_bytes = BN_bn2bin(tmp_scalar, tmp);
} else
num_bytes = BN_bn2bin(p_scalar, tmp);
flip_endian(secrets[i], tmp, num_bytes);
/* precompute multiples */
if ((!BN_to_felem(x_out, &p->X)) ||
(!BN_to_felem(y_out, &p->Y)) ||
(!BN_to_felem(z_out, &p->Z)))
goto err;
felem_assign(pre_comp[i][1][0], x_out);
felem_assign(pre_comp[i][1][1], y_out);
felem_assign(pre_comp[i][1][2], z_out);
for (j = 2; j <= 16; ++j) {
if (j & 1) {
point_add(pre_comp[i][j][0], pre_comp[i][j][1],
pre_comp[i][j][2], pre_comp[i][1][0],
pre_comp[i][1][1], pre_comp[i][1][2], 0,
pre_comp[i][j - 1][0],
pre_comp[i][j - 1][1],
pre_comp[i][j - 1][2]);
} else {
point_double(pre_comp[i][j][0], pre_comp[i][j][1],
pre_comp[i][j][2], pre_comp[i][j / 2][0],
pre_comp[i][j / 2][1],
pre_comp[i][j / 2][2]);
}
}
}
}
if (mixed)
make_points_affine(num_points * 17, pre_comp[0], tmp_felems);
}
/* the scalar for the generator */
if ((scalar != NULL) && (have_pre_comp)) {
- memset(g_secret, 0, sizeof g_secret);
+ memset(g_secret, 0, sizeof(g_secret));
/* reduce scalar to 0 <= scalar < 2^224 */
if ((BN_num_bits(scalar) > 224) || (BN_is_negative(scalar))) {
/*
* this is an unusual input, and we don't guarantee
* constant-timeness
*/
if (!BN_nnmod(tmp_scalar, scalar, &group->order, ctx)) {
ECerr(EC_F_EC_GFP_NISTP224_POINTS_MUL, ERR_R_BN_LIB);
goto err;
}
num_bytes = BN_bn2bin(tmp_scalar, tmp);
} else
num_bytes = BN_bn2bin(scalar, tmp);
flip_endian(g_secret, tmp, num_bytes);
/* do the multiplication with generator precomputation */
batch_mul(x_out, y_out, z_out,
(const felem_bytearray(*))secrets, num_points,
g_secret,
mixed, (const felem(*)[17][3])pre_comp, g_pre_comp);
} else
/* do the multiplication without generator precomputation */
batch_mul(x_out, y_out, z_out,
(const felem_bytearray(*))secrets, num_points,
NULL, mixed, (const felem(*)[17][3])pre_comp, NULL);
/* reduce the output to its unique minimal representation */
felem_contract(x_in, x_out);
felem_contract(y_in, y_out);
felem_contract(z_in, z_out);
if ((!felem_to_BN(x, x_in)) || (!felem_to_BN(y, y_in)) ||
(!felem_to_BN(z, z_in))) {
ECerr(EC_F_EC_GFP_NISTP224_POINTS_MUL, ERR_R_BN_LIB);
goto err;
}
ret = EC_POINT_set_Jprojective_coordinates_GFp(group, r, x, y, z, ctx);
err:
BN_CTX_end(ctx);
if (generator != NULL)
EC_POINT_free(generator);
if (new_ctx != NULL)
BN_CTX_free(new_ctx);
if (secrets != NULL)
OPENSSL_free(secrets);
if (pre_comp != NULL)
OPENSSL_free(pre_comp);
if (tmp_felems != NULL)
OPENSSL_free(tmp_felems);
return ret;
}
int ec_GFp_nistp224_precompute_mult(EC_GROUP *group, BN_CTX *ctx)
{
int ret = 0;
NISTP224_PRE_COMP *pre = NULL;
int i, j;
BN_CTX *new_ctx = NULL;
BIGNUM *x, *y;
EC_POINT *generator = NULL;
felem tmp_felems[32];
/* throw away old precomputation */
EC_EX_DATA_free_data(&group->extra_data, nistp224_pre_comp_dup,
nistp224_pre_comp_free,
nistp224_pre_comp_clear_free);
if (ctx == NULL)
if ((ctx = new_ctx = BN_CTX_new()) == NULL)
return 0;
BN_CTX_start(ctx);
if (((x = BN_CTX_get(ctx)) == NULL) || ((y = BN_CTX_get(ctx)) == NULL))
goto err;
/* get the generator */
if (group->generator == NULL)
goto err;
generator = EC_POINT_new(group);
if (generator == NULL)
goto err;
BN_bin2bn(nistp224_curve_params[3], sizeof(felem_bytearray), x);
BN_bin2bn(nistp224_curve_params[4], sizeof(felem_bytearray), y);
if (!EC_POINT_set_affine_coordinates_GFp(group, generator, x, y, ctx))
goto err;
if ((pre = nistp224_pre_comp_new()) == NULL)
goto err;
/*
* if the generator is the standard one, use built-in precomputation
*/
if (0 == EC_POINT_cmp(group, generator, group->generator, ctx)) {
memcpy(pre->g_pre_comp, gmul, sizeof(pre->g_pre_comp));
goto done;
}
if ((!BN_to_felem(pre->g_pre_comp[0][1][0], &group->generator->X)) ||
(!BN_to_felem(pre->g_pre_comp[0][1][1], &group->generator->Y)) ||
(!BN_to_felem(pre->g_pre_comp[0][1][2], &group->generator->Z)))
goto err;
/*
* compute 2^56*G, 2^112*G, 2^168*G for the first table, 2^28*G, 2^84*G,
* 2^140*G, 2^196*G for the second one
*/
for (i = 1; i <= 8; i <<= 1) {
point_double(pre->g_pre_comp[1][i][0], pre->g_pre_comp[1][i][1],
pre->g_pre_comp[1][i][2], pre->g_pre_comp[0][i][0],
pre->g_pre_comp[0][i][1], pre->g_pre_comp[0][i][2]);
for (j = 0; j < 27; ++j) {
point_double(pre->g_pre_comp[1][i][0], pre->g_pre_comp[1][i][1],
pre->g_pre_comp[1][i][2], pre->g_pre_comp[1][i][0],
pre->g_pre_comp[1][i][1], pre->g_pre_comp[1][i][2]);
}
if (i == 8)
break;
point_double(pre->g_pre_comp[0][2 * i][0],
pre->g_pre_comp[0][2 * i][1],
pre->g_pre_comp[0][2 * i][2], pre->g_pre_comp[1][i][0],
pre->g_pre_comp[1][i][1], pre->g_pre_comp[1][i][2]);
for (j = 0; j < 27; ++j) {
point_double(pre->g_pre_comp[0][2 * i][0],
pre->g_pre_comp[0][2 * i][1],
pre->g_pre_comp[0][2 * i][2],
pre->g_pre_comp[0][2 * i][0],
pre->g_pre_comp[0][2 * i][1],
pre->g_pre_comp[0][2 * i][2]);
}
}
for (i = 0; i < 2; i++) {
/* g_pre_comp[i][0] is the point at infinity */
memset(pre->g_pre_comp[i][0], 0, sizeof(pre->g_pre_comp[i][0]));
/* the remaining multiples */
/* 2^56*G + 2^112*G resp. 2^84*G + 2^140*G */
point_add(pre->g_pre_comp[i][6][0], pre->g_pre_comp[i][6][1],
pre->g_pre_comp[i][6][2], pre->g_pre_comp[i][4][0],
pre->g_pre_comp[i][4][1], pre->g_pre_comp[i][4][2],
0, pre->g_pre_comp[i][2][0], pre->g_pre_comp[i][2][1],
pre->g_pre_comp[i][2][2]);
/* 2^56*G + 2^168*G resp. 2^84*G + 2^196*G */
point_add(pre->g_pre_comp[i][10][0], pre->g_pre_comp[i][10][1],
pre->g_pre_comp[i][10][2], pre->g_pre_comp[i][8][0],
pre->g_pre_comp[i][8][1], pre->g_pre_comp[i][8][2],
0, pre->g_pre_comp[i][2][0], pre->g_pre_comp[i][2][1],
pre->g_pre_comp[i][2][2]);
/* 2^112*G + 2^168*G resp. 2^140*G + 2^196*G */
point_add(pre->g_pre_comp[i][12][0], pre->g_pre_comp[i][12][1],
pre->g_pre_comp[i][12][2], pre->g_pre_comp[i][8][0],
pre->g_pre_comp[i][8][1], pre->g_pre_comp[i][8][2],
0, pre->g_pre_comp[i][4][0], pre->g_pre_comp[i][4][1],
pre->g_pre_comp[i][4][2]);
/*
* 2^56*G + 2^112*G + 2^168*G resp. 2^84*G + 2^140*G + 2^196*G
*/
point_add(pre->g_pre_comp[i][14][0], pre->g_pre_comp[i][14][1],
pre->g_pre_comp[i][14][2], pre->g_pre_comp[i][12][0],
pre->g_pre_comp[i][12][1], pre->g_pre_comp[i][12][2],
0, pre->g_pre_comp[i][2][0], pre->g_pre_comp[i][2][1],
pre->g_pre_comp[i][2][2]);
for (j = 1; j < 8; ++j) {
/* odd multiples: add G resp. 2^28*G */
point_add(pre->g_pre_comp[i][2 * j + 1][0],
pre->g_pre_comp[i][2 * j + 1][1],
pre->g_pre_comp[i][2 * j + 1][2],
pre->g_pre_comp[i][2 * j][0],
pre->g_pre_comp[i][2 * j][1],
pre->g_pre_comp[i][2 * j][2], 0,
pre->g_pre_comp[i][1][0], pre->g_pre_comp[i][1][1],
pre->g_pre_comp[i][1][2]);
}
}
make_points_affine(31, &(pre->g_pre_comp[0][1]), tmp_felems);
done:
if (!EC_EX_DATA_set_data(&group->extra_data, pre, nistp224_pre_comp_dup,
nistp224_pre_comp_free,
nistp224_pre_comp_clear_free))
goto err;
ret = 1;
pre = NULL;
err:
BN_CTX_end(ctx);
if (generator != NULL)
EC_POINT_free(generator);
if (new_ctx != NULL)
BN_CTX_free(new_ctx);
if (pre)
nistp224_pre_comp_free(pre);
return ret;
}
int ec_GFp_nistp224_have_precompute_mult(const EC_GROUP *group)
{
if (EC_EX_DATA_get_data(group->extra_data, nistp224_pre_comp_dup,
nistp224_pre_comp_free,
nistp224_pre_comp_clear_free)
!= NULL)
return 1;
else
return 0;
}
#else
static void *dummy = &dummy;
#endif
diff --git a/crypto/ec/ecp_nistp256.c b/crypto/ec/ecp_nistp256.c
index 1272966fff84..378f0bae0857 100644
--- a/crypto/ec/ecp_nistp256.c
+++ b/crypto/ec/ecp_nistp256.c
@@ -1,2368 +1,2369 @@
/* crypto/ec/ecp_nistp256.c */
/*
* Written by Adam Langley (Google) for the OpenSSL project
*/
/* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
*
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* A 64-bit implementation of the NIST P-256 elliptic curve point multiplication
*
* OpenSSL integration was taken from Emilia Kasper's work in ecp_nistp224.c.
* Otherwise based on Emilia's P224 work, which was inspired by my curve25519
* work which got its smarts from Daniel J. Bernstein's work on the same.
*/
#include <openssl/opensslconf.h>
#ifndef OPENSSL_NO_EC_NISTP_64_GCC_128
# ifndef OPENSSL_SYS_VMS
# include <stdint.h>
# else
# include <inttypes.h>
# endif
# include <string.h>
# include <openssl/err.h>
# include "ec_lcl.h"
# if defined(__GNUC__) && (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 1))
/* even with gcc, the typedef won't work for 32-bit platforms */
typedef __uint128_t uint128_t; /* nonstandard; implemented by gcc on 64-bit
* platforms */
typedef __int128_t int128_t;
# else
# error "Need GCC 3.1 or later to define type uint128_t"
# endif
typedef uint8_t u8;
typedef uint32_t u32;
typedef uint64_t u64;
-typedef int64_t s64;
/*
* The underlying field. P256 operates over GF(2^256-2^224+2^192+2^96-1). We
* can serialise an element of this field into 32 bytes. We call this an
* felem_bytearray.
*/
typedef u8 felem_bytearray[32];
/*
* These are the parameters of P256, taken from FIPS 186-3, page 86. These
* values are big-endian.
*/
static const felem_bytearray nistp256_curve_params[5] = {
{0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x01, /* p */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff},
{0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x01, /* a = -3 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfc}, /* b */
{0x5a, 0xc6, 0x35, 0xd8, 0xaa, 0x3a, 0x93, 0xe7,
0xb3, 0xeb, 0xbd, 0x55, 0x76, 0x98, 0x86, 0xbc,
0x65, 0x1d, 0x06, 0xb0, 0xcc, 0x53, 0xb0, 0xf6,
0x3b, 0xce, 0x3c, 0x3e, 0x27, 0xd2, 0x60, 0x4b},
{0x6b, 0x17, 0xd1, 0xf2, 0xe1, 0x2c, 0x42, 0x47, /* x */
0xf8, 0xbc, 0xe6, 0xe5, 0x63, 0xa4, 0x40, 0xf2,
0x77, 0x03, 0x7d, 0x81, 0x2d, 0xeb, 0x33, 0xa0,
0xf4, 0xa1, 0x39, 0x45, 0xd8, 0x98, 0xc2, 0x96},
{0x4f, 0xe3, 0x42, 0xe2, 0xfe, 0x1a, 0x7f, 0x9b, /* y */
0x8e, 0xe7, 0xeb, 0x4a, 0x7c, 0x0f, 0x9e, 0x16,
0x2b, 0xce, 0x33, 0x57, 0x6b, 0x31, 0x5e, 0xce,
0xcb, 0xb6, 0x40, 0x68, 0x37, 0xbf, 0x51, 0xf5}
};
/*-
* The representation of field elements.
* ------------------------------------
*
* We represent field elements with either four 128-bit values, eight 128-bit
* values, or four 64-bit values. The field element represented is:
* v[0]*2^0 + v[1]*2^64 + v[2]*2^128 + v[3]*2^192 (mod p)
* or:
* v[0]*2^0 + v[1]*2^64 + v[2]*2^128 + ... + v[8]*2^512 (mod p)
*
* 128-bit values are called 'limbs'. Since the limbs are spaced only 64 bits
* apart, but are 128-bits wide, the most significant bits of each limb overlap
* with the least significant bits of the next.
*
* A field element with four limbs is an 'felem'. One with eight limbs is a
* 'longfelem'
*
* A field element with four, 64-bit values is called a 'smallfelem'. Small
* values are used as intermediate values before multiplication.
*/
# define NLIMBS 4
typedef uint128_t limb;
typedef limb felem[NLIMBS];
typedef limb longfelem[NLIMBS * 2];
typedef u64 smallfelem[NLIMBS];
/* This is the value of the prime as four 64-bit words, little-endian. */
static const u64 kPrime[4] =
{ 0xfffffffffffffffful, 0xffffffff, 0, 0xffffffff00000001ul };
static const u64 bottom63bits = 0x7ffffffffffffffful;
/*
* bin32_to_felem takes a little-endian byte array and converts it into felem
* form. This assumes that the CPU is little-endian.
*/
static void bin32_to_felem(felem out, const u8 in[32])
{
out[0] = *((u64 *)&in[0]);
out[1] = *((u64 *)&in[8]);
out[2] = *((u64 *)&in[16]);
out[3] = *((u64 *)&in[24]);
}
/*
* smallfelem_to_bin32 takes a smallfelem and serialises into a little
* endian, 32 byte array. This assumes that the CPU is little-endian.
*/
static void smallfelem_to_bin32(u8 out[32], const smallfelem in)
{
*((u64 *)&out[0]) = in[0];
*((u64 *)&out[8]) = in[1];
*((u64 *)&out[16]) = in[2];
*((u64 *)&out[24]) = in[3];
}
/* To preserve endianness when using BN_bn2bin and BN_bin2bn */
static void flip_endian(u8 *out, const u8 *in, unsigned len)
{
unsigned i;
for (i = 0; i < len; ++i)
out[i] = in[len - 1 - i];
}
/* BN_to_felem converts an OpenSSL BIGNUM into an felem */
static int BN_to_felem(felem out, const BIGNUM *bn)
{
felem_bytearray b_in;
felem_bytearray b_out;
unsigned num_bytes;
/* BN_bn2bin eats leading zeroes */
- memset(b_out, 0, sizeof b_out);
+ memset(b_out, 0, sizeof(b_out));
num_bytes = BN_num_bytes(bn);
- if (num_bytes > sizeof b_out) {
+ if (num_bytes > sizeof(b_out)) {
ECerr(EC_F_BN_TO_FELEM, EC_R_BIGNUM_OUT_OF_RANGE);
return 0;
}
if (BN_is_negative(bn)) {
ECerr(EC_F_BN_TO_FELEM, EC_R_BIGNUM_OUT_OF_RANGE);
return 0;
}
num_bytes = BN_bn2bin(bn, b_in);
flip_endian(b_out, b_in, num_bytes);
bin32_to_felem(out, b_out);
return 1;
}
/* felem_to_BN converts an felem into an OpenSSL BIGNUM */
static BIGNUM *smallfelem_to_BN(BIGNUM *out, const smallfelem in)
{
felem_bytearray b_in, b_out;
smallfelem_to_bin32(b_in, in);
- flip_endian(b_out, b_in, sizeof b_out);
- return BN_bin2bn(b_out, sizeof b_out, out);
+ flip_endian(b_out, b_in, sizeof(b_out));
+ return BN_bin2bn(b_out, sizeof(b_out), out);
}
/*-
* Field operations
* ----------------
*/
static void smallfelem_one(smallfelem out)
{
out[0] = 1;
out[1] = 0;
out[2] = 0;
out[3] = 0;
}
static void smallfelem_assign(smallfelem out, const smallfelem in)
{
out[0] = in[0];
out[1] = in[1];
out[2] = in[2];
out[3] = in[3];
}
static void felem_assign(felem out, const felem in)
{
out[0] = in[0];
out[1] = in[1];
out[2] = in[2];
out[3] = in[3];
}
/* felem_sum sets out = out + in. */
static void felem_sum(felem out, const felem in)
{
out[0] += in[0];
out[1] += in[1];
out[2] += in[2];
out[3] += in[3];
}
/* felem_small_sum sets out = out + in. */
static void felem_small_sum(felem out, const smallfelem in)
{
out[0] += in[0];
out[1] += in[1];
out[2] += in[2];
out[3] += in[3];
}
/* felem_scalar sets out = out * scalar */
static void felem_scalar(felem out, const u64 scalar)
{
out[0] *= scalar;
out[1] *= scalar;
out[2] *= scalar;
out[3] *= scalar;
}
/* longfelem_scalar sets out = out * scalar */
static void longfelem_scalar(longfelem out, const u64 scalar)
{
out[0] *= scalar;
out[1] *= scalar;
out[2] *= scalar;
out[3] *= scalar;
out[4] *= scalar;
out[5] *= scalar;
out[6] *= scalar;
out[7] *= scalar;
}
# define two105m41m9 (((limb)1) << 105) - (((limb)1) << 41) - (((limb)1) << 9)
# define two105 (((limb)1) << 105)
# define two105m41p9 (((limb)1) << 105) - (((limb)1) << 41) + (((limb)1) << 9)
/* zero105 is 0 mod p */
static const felem zero105 =
{ two105m41m9, two105, two105m41p9, two105m41p9 };
/*-
* smallfelem_neg sets |out| to |-small|
* On exit:
* out[i] < out[i] + 2^105
*/
static void smallfelem_neg(felem out, const smallfelem small)
{
/* In order to prevent underflow, we subtract from 0 mod p. */
out[0] = zero105[0] - small[0];
out[1] = zero105[1] - small[1];
out[2] = zero105[2] - small[2];
out[3] = zero105[3] - small[3];
}
/*-
* felem_diff subtracts |in| from |out|
* On entry:
* in[i] < 2^104
* On exit:
* out[i] < out[i] + 2^105
*/
static void felem_diff(felem out, const felem in)
{
/*
* In order to prevent underflow, we add 0 mod p before subtracting.
*/
out[0] += zero105[0];
out[1] += zero105[1];
out[2] += zero105[2];
out[3] += zero105[3];
out[0] -= in[0];
out[1] -= in[1];
out[2] -= in[2];
out[3] -= in[3];
}
# define two107m43m11 (((limb)1) << 107) - (((limb)1) << 43) - (((limb)1) << 11)
# define two107 (((limb)1) << 107)
# define two107m43p11 (((limb)1) << 107) - (((limb)1) << 43) + (((limb)1) << 11)
/* zero107 is 0 mod p */
static const felem zero107 =
{ two107m43m11, two107, two107m43p11, two107m43p11 };
/*-
* An alternative felem_diff for larger inputs |in|
* felem_diff_zero107 subtracts |in| from |out|
* On entry:
* in[i] < 2^106
* On exit:
* out[i] < out[i] + 2^107
*/
static void felem_diff_zero107(felem out, const felem in)
{
/*
* In order to prevent underflow, we add 0 mod p before subtracting.
*/
out[0] += zero107[0];
out[1] += zero107[1];
out[2] += zero107[2];
out[3] += zero107[3];
out[0] -= in[0];
out[1] -= in[1];
out[2] -= in[2];
out[3] -= in[3];
}
/*-
* longfelem_diff subtracts |in| from |out|
* On entry:
* in[i] < 7*2^67
* On exit:
* out[i] < out[i] + 2^70 + 2^40
*/
static void longfelem_diff(longfelem out, const longfelem in)
{
static const limb two70m8p6 =
(((limb) 1) << 70) - (((limb) 1) << 8) + (((limb) 1) << 6);
static const limb two70p40 = (((limb) 1) << 70) + (((limb) 1) << 40);
static const limb two70 = (((limb) 1) << 70);
static const limb two70m40m38p6 =
(((limb) 1) << 70) - (((limb) 1) << 40) - (((limb) 1) << 38) +
(((limb) 1) << 6);
static const limb two70m6 = (((limb) 1) << 70) - (((limb) 1) << 6);
/* add 0 mod p to avoid underflow */
out[0] += two70m8p6;
out[1] += two70p40;
out[2] += two70;
out[3] += two70m40m38p6;
out[4] += two70m6;
out[5] += two70m6;
out[6] += two70m6;
out[7] += two70m6;
/* in[i] < 7*2^67 < 2^70 - 2^40 - 2^38 + 2^6 */
out[0] -= in[0];
out[1] -= in[1];
out[2] -= in[2];
out[3] -= in[3];
out[4] -= in[4];
out[5] -= in[5];
out[6] -= in[6];
out[7] -= in[7];
}
# define two64m0 (((limb)1) << 64) - 1
# define two110p32m0 (((limb)1) << 110) + (((limb)1) << 32) - 1
# define two64m46 (((limb)1) << 64) - (((limb)1) << 46)
# define two64m32 (((limb)1) << 64) - (((limb)1) << 32)
/* zero110 is 0 mod p */
static const felem zero110 = { two64m0, two110p32m0, two64m46, two64m32 };
/*-
* felem_shrink converts an felem into a smallfelem. The result isn't quite
* minimal as the value may be greater than p.
*
* On entry:
* in[i] < 2^109
* On exit:
* out[i] < 2^64
*/
static void felem_shrink(smallfelem out, const felem in)
{
felem tmp;
u64 a, b, mask;
- s64 high, low;
+ u64 high, low;
static const u64 kPrime3Test = 0x7fffffff00000001ul; /* 2^63 - 2^32 + 1 */
/* Carry 2->3 */
tmp[3] = zero110[3] + in[3] + ((u64)(in[2] >> 64));
/* tmp[3] < 2^110 */
tmp[2] = zero110[2] + (u64)in[2];
tmp[0] = zero110[0] + in[0];
tmp[1] = zero110[1] + in[1];
/* tmp[0] < 2**110, tmp[1] < 2^111, tmp[2] < 2**65 */
/*
* We perform two partial reductions where we eliminate the high-word of
* tmp[3]. We don't update the other words till the end.
*/
a = tmp[3] >> 64; /* a < 2^46 */
tmp[3] = (u64)tmp[3];
tmp[3] -= a;
tmp[3] += ((limb) a) << 32;
/* tmp[3] < 2^79 */
b = a;
a = tmp[3] >> 64; /* a < 2^15 */
b += a; /* b < 2^46 + 2^15 < 2^47 */
tmp[3] = (u64)tmp[3];
tmp[3] -= a;
tmp[3] += ((limb) a) << 32;
/* tmp[3] < 2^64 + 2^47 */
/*
* This adjusts the other two words to complete the two partial
* reductions.
*/
tmp[0] += b;
tmp[1] -= (((limb) b) << 32);
/*
* In order to make space in tmp[3] for the carry from 2 -> 3, we
* conditionally subtract kPrime if tmp[3] is large enough.
*/
- high = tmp[3] >> 64;
+ high = (u64)(tmp[3] >> 64);
/* As tmp[3] < 2^65, high is either 1 or 0 */
- high <<= 63;
- high >>= 63;
+ high = 0 - high;
/*-
* high is:
* all ones if the high word of tmp[3] is 1
- * all zeros if the high word of tmp[3] if 0 */
- low = tmp[3];
- mask = low >> 63;
+ * all zeros if the high word of tmp[3] if 0
+ */
+ low = (u64)tmp[3];
+ mask = 0 - (low >> 63);
/*-
* mask is:
* all ones if the MSB of low is 1
- * all zeros if the MSB of low if 0 */
+ * all zeros if the MSB of low if 0
+ */
low &= bottom63bits;
low -= kPrime3Test;
/* if low was greater than kPrime3Test then the MSB is zero */
low = ~low;
- low >>= 63;
+ low = 0 - (low >> 63);
/*-
* low is:
* all ones if low was > kPrime3Test
- * all zeros if low was <= kPrime3Test */
+ * all zeros if low was <= kPrime3Test
+ */
mask = (mask & low) | high;
tmp[0] -= mask & kPrime[0];
tmp[1] -= mask & kPrime[1];
/* kPrime[2] is zero, so omitted */
tmp[3] -= mask & kPrime[3];
/* tmp[3] < 2**64 - 2**32 + 1 */
tmp[1] += ((u64)(tmp[0] >> 64));
tmp[0] = (u64)tmp[0];
tmp[2] += ((u64)(tmp[1] >> 64));
tmp[1] = (u64)tmp[1];
tmp[3] += ((u64)(tmp[2] >> 64));
tmp[2] = (u64)tmp[2];
/* tmp[i] < 2^64 */
out[0] = tmp[0];
out[1] = tmp[1];
out[2] = tmp[2];
out[3] = tmp[3];
}
/* smallfelem_expand converts a smallfelem to an felem */
static void smallfelem_expand(felem out, const smallfelem in)
{
out[0] = in[0];
out[1] = in[1];
out[2] = in[2];
out[3] = in[3];
}
/*-
* smallfelem_square sets |out| = |small|^2
* On entry:
* small[i] < 2^64
* On exit:
* out[i] < 7 * 2^64 < 2^67
*/
static void smallfelem_square(longfelem out, const smallfelem small)
{
limb a;
u64 high, low;
a = ((uint128_t) small[0]) * small[0];
low = a;
high = a >> 64;
out[0] = low;
out[1] = high;
a = ((uint128_t) small[0]) * small[1];
low = a;
high = a >> 64;
out[1] += low;
out[1] += low;
out[2] = high;
a = ((uint128_t) small[0]) * small[2];
low = a;
high = a >> 64;
out[2] += low;
out[2] *= 2;
out[3] = high;
a = ((uint128_t) small[0]) * small[3];
low = a;
high = a >> 64;
out[3] += low;
out[4] = high;
a = ((uint128_t) small[1]) * small[2];
low = a;
high = a >> 64;
out[3] += low;
out[3] *= 2;
out[4] += high;
a = ((uint128_t) small[1]) * small[1];
low = a;
high = a >> 64;
out[2] += low;
out[3] += high;
a = ((uint128_t) small[1]) * small[3];
low = a;
high = a >> 64;
out[4] += low;
out[4] *= 2;
out[5] = high;
a = ((uint128_t) small[2]) * small[3];
low = a;
high = a >> 64;
out[5] += low;
out[5] *= 2;
out[6] = high;
out[6] += high;
a = ((uint128_t) small[2]) * small[2];
low = a;
high = a >> 64;
out[4] += low;
out[5] += high;
a = ((uint128_t) small[3]) * small[3];
low = a;
high = a >> 64;
out[6] += low;
out[7] = high;
}
/*-
* felem_square sets |out| = |in|^2
* On entry:
* in[i] < 2^109
* On exit:
* out[i] < 7 * 2^64 < 2^67
*/
static void felem_square(longfelem out, const felem in)
{
u64 small[4];
felem_shrink(small, in);
smallfelem_square(out, small);
}
/*-
* smallfelem_mul sets |out| = |small1| * |small2|
* On entry:
* small1[i] < 2^64
* small2[i] < 2^64
* On exit:
* out[i] < 7 * 2^64 < 2^67
*/
static void smallfelem_mul(longfelem out, const smallfelem small1,
const smallfelem small2)
{
limb a;
u64 high, low;
a = ((uint128_t) small1[0]) * small2[0];
low = a;
high = a >> 64;
out[0] = low;
out[1] = high;
a = ((uint128_t) small1[0]) * small2[1];
low = a;
high = a >> 64;
out[1] += low;
out[2] = high;
a = ((uint128_t) small1[1]) * small2[0];
low = a;
high = a >> 64;
out[1] += low;
out[2] += high;
a = ((uint128_t) small1[0]) * small2[2];
low = a;
high = a >> 64;
out[2] += low;
out[3] = high;
a = ((uint128_t) small1[1]) * small2[1];
low = a;
high = a >> 64;
out[2] += low;
out[3] += high;
a = ((uint128_t) small1[2]) * small2[0];
low = a;
high = a >> 64;
out[2] += low;
out[3] += high;
a = ((uint128_t) small1[0]) * small2[3];
low = a;
high = a >> 64;
out[3] += low;
out[4] = high;
a = ((uint128_t) small1[1]) * small2[2];
low = a;
high = a >> 64;
out[3] += low;
out[4] += high;
a = ((uint128_t) small1[2]) * small2[1];
low = a;
high = a >> 64;
out[3] += low;
out[4] += high;
a = ((uint128_t) small1[3]) * small2[0];
low = a;
high = a >> 64;
out[3] += low;
out[4] += high;
a = ((uint128_t) small1[1]) * small2[3];
low = a;
high = a >> 64;
out[4] += low;
out[5] = high;
a = ((uint128_t) small1[2]) * small2[2];
low = a;
high = a >> 64;
out[4] += low;
out[5] += high;
a = ((uint128_t) small1[3]) * small2[1];
low = a;
high = a >> 64;
out[4] += low;
out[5] += high;
a = ((uint128_t) small1[2]) * small2[3];
low = a;
high = a >> 64;
out[5] += low;
out[6] = high;
a = ((uint128_t) small1[3]) * small2[2];
low = a;
high = a >> 64;
out[5] += low;
out[6] += high;
a = ((uint128_t) small1[3]) * small2[3];
low = a;
high = a >> 64;
out[6] += low;
out[7] = high;
}
/*-
* felem_mul sets |out| = |in1| * |in2|
* On entry:
* in1[i] < 2^109
* in2[i] < 2^109
* On exit:
* out[i] < 7 * 2^64 < 2^67
*/
static void felem_mul(longfelem out, const felem in1, const felem in2)
{
smallfelem small1, small2;
felem_shrink(small1, in1);
felem_shrink(small2, in2);
smallfelem_mul(out, small1, small2);
}
/*-
* felem_small_mul sets |out| = |small1| * |in2|
* On entry:
* small1[i] < 2^64
* in2[i] < 2^109
* On exit:
* out[i] < 7 * 2^64 < 2^67
*/
static void felem_small_mul(longfelem out, const smallfelem small1,
const felem in2)
{
smallfelem small2;
felem_shrink(small2, in2);
smallfelem_mul(out, small1, small2);
}
# define two100m36m4 (((limb)1) << 100) - (((limb)1) << 36) - (((limb)1) << 4)
# define two100 (((limb)1) << 100)
# define two100m36p4 (((limb)1) << 100) - (((limb)1) << 36) + (((limb)1) << 4)
/* zero100 is 0 mod p */
static const felem zero100 =
{ two100m36m4, two100, two100m36p4, two100m36p4 };
/*-
* Internal function for the different flavours of felem_reduce.
* felem_reduce_ reduces the higher coefficients in[4]-in[7].
* On entry:
* out[0] >= in[6] + 2^32*in[6] + in[7] + 2^32*in[7]
* out[1] >= in[7] + 2^32*in[4]
* out[2] >= in[5] + 2^32*in[5]
* out[3] >= in[4] + 2^32*in[5] + 2^32*in[6]
* On exit:
* out[0] <= out[0] + in[4] + 2^32*in[5]
* out[1] <= out[1] + in[5] + 2^33*in[6]
* out[2] <= out[2] + in[7] + 2*in[6] + 2^33*in[7]
* out[3] <= out[3] + 2^32*in[4] + 3*in[7]
*/
static void felem_reduce_(felem out, const longfelem in)
{
int128_t c;
/* combine common terms from below */
c = in[4] + (in[5] << 32);
out[0] += c;
out[3] -= c;
c = in[5] - in[7];
out[1] += c;
out[2] -= c;
/* the remaining terms */
/* 256: [(0,1),(96,-1),(192,-1),(224,1)] */
out[1] -= (in[4] << 32);
out[3] += (in[4] << 32);
/* 320: [(32,1),(64,1),(128,-1),(160,-1),(224,-1)] */
out[2] -= (in[5] << 32);
/* 384: [(0,-1),(32,-1),(96,2),(128,2),(224,-1)] */
out[0] -= in[6];
out[0] -= (in[6] << 32);
out[1] += (in[6] << 33);
out[2] += (in[6] * 2);
out[3] -= (in[6] << 32);
/* 448: [(0,-1),(32,-1),(64,-1),(128,1),(160,2),(192,3)] */
out[0] -= in[7];
out[0] -= (in[7] << 32);
out[2] += (in[7] << 33);
out[3] += (in[7] * 3);
}
/*-
* felem_reduce converts a longfelem into an felem.
* To be called directly after felem_square or felem_mul.
* On entry:
* in[0] < 2^64, in[1] < 3*2^64, in[2] < 5*2^64, in[3] < 7*2^64
* in[4] < 7*2^64, in[5] < 5*2^64, in[6] < 3*2^64, in[7] < 2*64
* On exit:
* out[i] < 2^101
*/
static void felem_reduce(felem out, const longfelem in)
{
out[0] = zero100[0] + in[0];
out[1] = zero100[1] + in[1];
out[2] = zero100[2] + in[2];
out[3] = zero100[3] + in[3];
felem_reduce_(out, in);
/*-
* out[0] > 2^100 - 2^36 - 2^4 - 3*2^64 - 3*2^96 - 2^64 - 2^96 > 0
* out[1] > 2^100 - 2^64 - 7*2^96 > 0
* out[2] > 2^100 - 2^36 + 2^4 - 5*2^64 - 5*2^96 > 0
* out[3] > 2^100 - 2^36 + 2^4 - 7*2^64 - 5*2^96 - 3*2^96 > 0
*
* out[0] < 2^100 + 2^64 + 7*2^64 + 5*2^96 < 2^101
* out[1] < 2^100 + 3*2^64 + 5*2^64 + 3*2^97 < 2^101
* out[2] < 2^100 + 5*2^64 + 2^64 + 3*2^65 + 2^97 < 2^101
* out[3] < 2^100 + 7*2^64 + 7*2^96 + 3*2^64 < 2^101
*/
}
/*-
* felem_reduce_zero105 converts a larger longfelem into an felem.
* On entry:
* in[0] < 2^71
* On exit:
* out[i] < 2^106
*/
static void felem_reduce_zero105(felem out, const longfelem in)
{
out[0] = zero105[0] + in[0];
out[1] = zero105[1] + in[1];
out[2] = zero105[2] + in[2];
out[3] = zero105[3] + in[3];
felem_reduce_(out, in);
/*-
* out[0] > 2^105 - 2^41 - 2^9 - 2^71 - 2^103 - 2^71 - 2^103 > 0
* out[1] > 2^105 - 2^71 - 2^103 > 0
* out[2] > 2^105 - 2^41 + 2^9 - 2^71 - 2^103 > 0
* out[3] > 2^105 - 2^41 + 2^9 - 2^71 - 2^103 - 2^103 > 0
*
* out[0] < 2^105 + 2^71 + 2^71 + 2^103 < 2^106
* out[1] < 2^105 + 2^71 + 2^71 + 2^103 < 2^106
* out[2] < 2^105 + 2^71 + 2^71 + 2^71 + 2^103 < 2^106
* out[3] < 2^105 + 2^71 + 2^103 + 2^71 < 2^106
*/
}
/*
* subtract_u64 sets *result = *result - v and *carry to one if the
* subtraction underflowed.
*/
static void subtract_u64(u64 *result, u64 *carry, u64 v)
{
uint128_t r = *result;
r -= v;
*carry = (r >> 64) & 1;
*result = (u64)r;
}
/*
* felem_contract converts |in| to its unique, minimal representation. On
* entry: in[i] < 2^109
*/
static void felem_contract(smallfelem out, const felem in)
{
unsigned i;
u64 all_equal_so_far = 0, result = 0, carry;
felem_shrink(out, in);
/* small is minimal except that the value might be > p */
all_equal_so_far--;
/*
* We are doing a constant time test if out >= kPrime. We need to compare
* each u64, from most-significant to least significant. For each one, if
* all words so far have been equal (m is all ones) then a non-equal
* result is the answer. Otherwise we continue.
*/
for (i = 3; i < 4; i--) {
u64 equal;
uint128_t a = ((uint128_t) kPrime[i]) - out[i];
/*
* if out[i] > kPrime[i] then a will underflow and the high 64-bits
* will all be set.
*/
result |= all_equal_so_far & ((u64)(a >> 64));
/*
* if kPrime[i] == out[i] then |equal| will be all zeros and the
* decrement will make it all ones.
*/
equal = kPrime[i] ^ out[i];
equal--;
equal &= equal << 32;
equal &= equal << 16;
equal &= equal << 8;
equal &= equal << 4;
equal &= equal << 2;
equal &= equal << 1;
- equal = ((s64) equal) >> 63;
+ equal = 0 - (equal >> 63);
all_equal_so_far &= equal;
}
/*
* if all_equal_so_far is still all ones then the two values are equal
* and so out >= kPrime is true.
*/
result |= all_equal_so_far;
/* if out >= kPrime then we subtract kPrime. */
subtract_u64(&out[0], &carry, result & kPrime[0]);
subtract_u64(&out[1], &carry, carry);
subtract_u64(&out[2], &carry, carry);
subtract_u64(&out[3], &carry, carry);
subtract_u64(&out[1], &carry, result & kPrime[1]);
subtract_u64(&out[2], &carry, carry);
subtract_u64(&out[3], &carry, carry);
subtract_u64(&out[2], &carry, result & kPrime[2]);
subtract_u64(&out[3], &carry, carry);
subtract_u64(&out[3], &carry, result & kPrime[3]);
}
static void smallfelem_square_contract(smallfelem out, const smallfelem in)
{
longfelem longtmp;
felem tmp;
smallfelem_square(longtmp, in);
felem_reduce(tmp, longtmp);
felem_contract(out, tmp);
}
static void smallfelem_mul_contract(smallfelem out, const smallfelem in1,
const smallfelem in2)
{
longfelem longtmp;
felem tmp;
smallfelem_mul(longtmp, in1, in2);
felem_reduce(tmp, longtmp);
felem_contract(out, tmp);
}
/*-
* felem_is_zero returns a limb with all bits set if |in| == 0 (mod p) and 0
* otherwise.
* On entry:
* small[i] < 2^64
*/
static limb smallfelem_is_zero(const smallfelem small)
{
limb result;
u64 is_p;
u64 is_zero = small[0] | small[1] | small[2] | small[3];
is_zero--;
is_zero &= is_zero << 32;
is_zero &= is_zero << 16;
is_zero &= is_zero << 8;
is_zero &= is_zero << 4;
is_zero &= is_zero << 2;
is_zero &= is_zero << 1;
- is_zero = ((s64) is_zero) >> 63;
+ is_zero = 0 - (is_zero >> 63);
is_p = (small[0] ^ kPrime[0]) |
(small[1] ^ kPrime[1]) |
(small[2] ^ kPrime[2]) | (small[3] ^ kPrime[3]);
is_p--;
is_p &= is_p << 32;
is_p &= is_p << 16;
is_p &= is_p << 8;
is_p &= is_p << 4;
is_p &= is_p << 2;
is_p &= is_p << 1;
- is_p = ((s64) is_p) >> 63;
+ is_p = 0 - (is_p >> 63);
is_zero |= is_p;
result = is_zero;
result |= ((limb) is_zero) << 64;
return result;
}
static int smallfelem_is_zero_int(const void *small)
{
return (int)(smallfelem_is_zero(small) & ((limb) 1));
}
/*-
* felem_inv calculates |out| = |in|^{-1}
*
* Based on Fermat's Little Theorem:
* a^p = a (mod p)
* a^{p-1} = 1 (mod p)
* a^{p-2} = a^{-1} (mod p)
*/
static void felem_inv(felem out, const felem in)
{
felem ftmp, ftmp2;
/* each e_I will hold |in|^{2^I - 1} */
felem e2, e4, e8, e16, e32, e64;
longfelem tmp;
unsigned i;
felem_square(tmp, in);
felem_reduce(ftmp, tmp); /* 2^1 */
felem_mul(tmp, in, ftmp);
felem_reduce(ftmp, tmp); /* 2^2 - 2^0 */
felem_assign(e2, ftmp);
felem_square(tmp, ftmp);
felem_reduce(ftmp, tmp); /* 2^3 - 2^1 */
felem_square(tmp, ftmp);
felem_reduce(ftmp, tmp); /* 2^4 - 2^2 */
felem_mul(tmp, ftmp, e2);
felem_reduce(ftmp, tmp); /* 2^4 - 2^0 */
felem_assign(e4, ftmp);
felem_square(tmp, ftmp);
felem_reduce(ftmp, tmp); /* 2^5 - 2^1 */
felem_square(tmp, ftmp);
felem_reduce(ftmp, tmp); /* 2^6 - 2^2 */
felem_square(tmp, ftmp);
felem_reduce(ftmp, tmp); /* 2^7 - 2^3 */
felem_square(tmp, ftmp);
felem_reduce(ftmp, tmp); /* 2^8 - 2^4 */
felem_mul(tmp, ftmp, e4);
felem_reduce(ftmp, tmp); /* 2^8 - 2^0 */
felem_assign(e8, ftmp);
for (i = 0; i < 8; i++) {
felem_square(tmp, ftmp);
felem_reduce(ftmp, tmp);
} /* 2^16 - 2^8 */
felem_mul(tmp, ftmp, e8);
felem_reduce(ftmp, tmp); /* 2^16 - 2^0 */
felem_assign(e16, ftmp);
for (i = 0; i < 16; i++) {
felem_square(tmp, ftmp);
felem_reduce(ftmp, tmp);
} /* 2^32 - 2^16 */
felem_mul(tmp, ftmp, e16);
felem_reduce(ftmp, tmp); /* 2^32 - 2^0 */
felem_assign(e32, ftmp);
for (i = 0; i < 32; i++) {
felem_square(tmp, ftmp);
felem_reduce(ftmp, tmp);
} /* 2^64 - 2^32 */
felem_assign(e64, ftmp);
felem_mul(tmp, ftmp, in);
felem_reduce(ftmp, tmp); /* 2^64 - 2^32 + 2^0 */
for (i = 0; i < 192; i++) {
felem_square(tmp, ftmp);
felem_reduce(ftmp, tmp);
} /* 2^256 - 2^224 + 2^192 */
felem_mul(tmp, e64, e32);
felem_reduce(ftmp2, tmp); /* 2^64 - 2^0 */
for (i = 0; i < 16; i++) {
felem_square(tmp, ftmp2);
felem_reduce(ftmp2, tmp);
} /* 2^80 - 2^16 */
felem_mul(tmp, ftmp2, e16);
felem_reduce(ftmp2, tmp); /* 2^80 - 2^0 */
for (i = 0; i < 8; i++) {
felem_square(tmp, ftmp2);
felem_reduce(ftmp2, tmp);
} /* 2^88 - 2^8 */
felem_mul(tmp, ftmp2, e8);
felem_reduce(ftmp2, tmp); /* 2^88 - 2^0 */
for (i = 0; i < 4; i++) {
felem_square(tmp, ftmp2);
felem_reduce(ftmp2, tmp);
} /* 2^92 - 2^4 */
felem_mul(tmp, ftmp2, e4);
felem_reduce(ftmp2, tmp); /* 2^92 - 2^0 */
felem_square(tmp, ftmp2);
felem_reduce(ftmp2, tmp); /* 2^93 - 2^1 */
felem_square(tmp, ftmp2);
felem_reduce(ftmp2, tmp); /* 2^94 - 2^2 */
felem_mul(tmp, ftmp2, e2);
felem_reduce(ftmp2, tmp); /* 2^94 - 2^0 */
felem_square(tmp, ftmp2);
felem_reduce(ftmp2, tmp); /* 2^95 - 2^1 */
felem_square(tmp, ftmp2);
felem_reduce(ftmp2, tmp); /* 2^96 - 2^2 */
felem_mul(tmp, ftmp2, in);
felem_reduce(ftmp2, tmp); /* 2^96 - 3 */
felem_mul(tmp, ftmp2, ftmp);
felem_reduce(out, tmp); /* 2^256 - 2^224 + 2^192 + 2^96 - 3 */
}
static void smallfelem_inv_contract(smallfelem out, const smallfelem in)
{
felem tmp;
smallfelem_expand(tmp, in);
felem_inv(tmp, tmp);
felem_contract(out, tmp);
}
/*-
* Group operations
* ----------------
*
* Building on top of the field operations we have the operations on the
* elliptic curve group itself. Points on the curve are represented in Jacobian
* coordinates
*/
/*-
* point_double calculates 2*(x_in, y_in, z_in)
*
* The method is taken from:
* http://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html#doubling-dbl-2001-b
*
* Outputs can equal corresponding inputs, i.e., x_out == x_in is allowed.
* while x_out == y_in is not (maybe this works, but it's not tested).
*/
static void
point_double(felem x_out, felem y_out, felem z_out,
const felem x_in, const felem y_in, const felem z_in)
{
longfelem tmp, tmp2;
felem delta, gamma, beta, alpha, ftmp, ftmp2;
smallfelem small1, small2;
felem_assign(ftmp, x_in);
/* ftmp[i] < 2^106 */
felem_assign(ftmp2, x_in);
/* ftmp2[i] < 2^106 */
/* delta = z^2 */
felem_square(tmp, z_in);
felem_reduce(delta, tmp);
/* delta[i] < 2^101 */
/* gamma = y^2 */
felem_square(tmp, y_in);
felem_reduce(gamma, tmp);
/* gamma[i] < 2^101 */
felem_shrink(small1, gamma);
/* beta = x*gamma */
felem_small_mul(tmp, small1, x_in);
felem_reduce(beta, tmp);
/* beta[i] < 2^101 */
/* alpha = 3*(x-delta)*(x+delta) */
felem_diff(ftmp, delta);
/* ftmp[i] < 2^105 + 2^106 < 2^107 */
felem_sum(ftmp2, delta);
/* ftmp2[i] < 2^105 + 2^106 < 2^107 */
felem_scalar(ftmp2, 3);
/* ftmp2[i] < 3 * 2^107 < 2^109 */
felem_mul(tmp, ftmp, ftmp2);
felem_reduce(alpha, tmp);
/* alpha[i] < 2^101 */
felem_shrink(small2, alpha);
/* x' = alpha^2 - 8*beta */
smallfelem_square(tmp, small2);
felem_reduce(x_out, tmp);
felem_assign(ftmp, beta);
felem_scalar(ftmp, 8);
/* ftmp[i] < 8 * 2^101 = 2^104 */
felem_diff(x_out, ftmp);
/* x_out[i] < 2^105 + 2^101 < 2^106 */
/* z' = (y + z)^2 - gamma - delta */
felem_sum(delta, gamma);
/* delta[i] < 2^101 + 2^101 = 2^102 */
felem_assign(ftmp, y_in);
felem_sum(ftmp, z_in);
/* ftmp[i] < 2^106 + 2^106 = 2^107 */
felem_square(tmp, ftmp);
felem_reduce(z_out, tmp);
felem_diff(z_out, delta);
/* z_out[i] < 2^105 + 2^101 < 2^106 */
/* y' = alpha*(4*beta - x') - 8*gamma^2 */
felem_scalar(beta, 4);
/* beta[i] < 4 * 2^101 = 2^103 */
felem_diff_zero107(beta, x_out);
/* beta[i] < 2^107 + 2^103 < 2^108 */
felem_small_mul(tmp, small2, beta);
/* tmp[i] < 7 * 2^64 < 2^67 */
smallfelem_square(tmp2, small1);
/* tmp2[i] < 7 * 2^64 */
longfelem_scalar(tmp2, 8);
/* tmp2[i] < 8 * 7 * 2^64 = 7 * 2^67 */
longfelem_diff(tmp, tmp2);
/* tmp[i] < 2^67 + 2^70 + 2^40 < 2^71 */
felem_reduce_zero105(y_out, tmp);
/* y_out[i] < 2^106 */
}
/*
* point_double_small is the same as point_double, except that it operates on
* smallfelems
*/
static void
point_double_small(smallfelem x_out, smallfelem y_out, smallfelem z_out,
const smallfelem x_in, const smallfelem y_in,
const smallfelem z_in)
{
felem felem_x_out, felem_y_out, felem_z_out;
felem felem_x_in, felem_y_in, felem_z_in;
smallfelem_expand(felem_x_in, x_in);
smallfelem_expand(felem_y_in, y_in);
smallfelem_expand(felem_z_in, z_in);
point_double(felem_x_out, felem_y_out, felem_z_out,
felem_x_in, felem_y_in, felem_z_in);
felem_shrink(x_out, felem_x_out);
felem_shrink(y_out, felem_y_out);
felem_shrink(z_out, felem_z_out);
}
/* copy_conditional copies in to out iff mask is all ones. */
static void copy_conditional(felem out, const felem in, limb mask)
{
unsigned i;
for (i = 0; i < NLIMBS; ++i) {
const limb tmp = mask & (in[i] ^ out[i]);
out[i] ^= tmp;
}
}
/* copy_small_conditional copies in to out iff mask is all ones. */
static void copy_small_conditional(felem out, const smallfelem in, limb mask)
{
unsigned i;
const u64 mask64 = mask;
for (i = 0; i < NLIMBS; ++i) {
out[i] = ((limb) (in[i] & mask64)) | (out[i] & ~mask);
}
}
/*-
* point_add calcuates (x1, y1, z1) + (x2, y2, z2)
*
* The method is taken from:
* http://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html#addition-add-2007-bl,
* adapted for mixed addition (z2 = 1, or z2 = 0 for the point at infinity).
*
* This function includes a branch for checking whether the two input points
* are equal, (while not equal to the point at infinity). This case never
* happens during single point multiplication, so there is no timing leak for
* ECDH or ECDSA signing.
*/
static void point_add(felem x3, felem y3, felem z3,
const felem x1, const felem y1, const felem z1,
const int mixed, const smallfelem x2,
const smallfelem y2, const smallfelem z2)
{
felem ftmp, ftmp2, ftmp3, ftmp4, ftmp5, ftmp6, x_out, y_out, z_out;
longfelem tmp, tmp2;
smallfelem small1, small2, small3, small4, small5;
limb x_equal, y_equal, z1_is_zero, z2_is_zero;
felem_shrink(small3, z1);
z1_is_zero = smallfelem_is_zero(small3);
z2_is_zero = smallfelem_is_zero(z2);
/* ftmp = z1z1 = z1**2 */
smallfelem_square(tmp, small3);
felem_reduce(ftmp, tmp);
/* ftmp[i] < 2^101 */
felem_shrink(small1, ftmp);
if (!mixed) {
/* ftmp2 = z2z2 = z2**2 */
smallfelem_square(tmp, z2);
felem_reduce(ftmp2, tmp);
/* ftmp2[i] < 2^101 */
felem_shrink(small2, ftmp2);
felem_shrink(small5, x1);
/* u1 = ftmp3 = x1*z2z2 */
smallfelem_mul(tmp, small5, small2);
felem_reduce(ftmp3, tmp);
/* ftmp3[i] < 2^101 */
/* ftmp5 = z1 + z2 */
felem_assign(ftmp5, z1);
felem_small_sum(ftmp5, z2);
/* ftmp5[i] < 2^107 */
/* ftmp5 = (z1 + z2)**2 - (z1z1 + z2z2) = 2z1z2 */
felem_square(tmp, ftmp5);
felem_reduce(ftmp5, tmp);
/* ftmp2 = z2z2 + z1z1 */
felem_sum(ftmp2, ftmp);
/* ftmp2[i] < 2^101 + 2^101 = 2^102 */
felem_diff(ftmp5, ftmp2);
/* ftmp5[i] < 2^105 + 2^101 < 2^106 */
/* ftmp2 = z2 * z2z2 */
smallfelem_mul(tmp, small2, z2);
felem_reduce(ftmp2, tmp);
/* s1 = ftmp2 = y1 * z2**3 */
felem_mul(tmp, y1, ftmp2);
felem_reduce(ftmp6, tmp);
/* ftmp6[i] < 2^101 */
} else {
/*
* We'll assume z2 = 1 (special case z2 = 0 is handled later)
*/
/* u1 = ftmp3 = x1*z2z2 */
felem_assign(ftmp3, x1);
/* ftmp3[i] < 2^106 */
/* ftmp5 = 2z1z2 */
felem_assign(ftmp5, z1);
felem_scalar(ftmp5, 2);
/* ftmp5[i] < 2*2^106 = 2^107 */
/* s1 = ftmp2 = y1 * z2**3 */
felem_assign(ftmp6, y1);
/* ftmp6[i] < 2^106 */
}
/* u2 = x2*z1z1 */
smallfelem_mul(tmp, x2, small1);
felem_reduce(ftmp4, tmp);
/* h = ftmp4 = u2 - u1 */
felem_diff_zero107(ftmp4, ftmp3);
/* ftmp4[i] < 2^107 + 2^101 < 2^108 */
felem_shrink(small4, ftmp4);
x_equal = smallfelem_is_zero(small4);
/* z_out = ftmp5 * h */
felem_small_mul(tmp, small4, ftmp5);
felem_reduce(z_out, tmp);
/* z_out[i] < 2^101 */
/* ftmp = z1 * z1z1 */
smallfelem_mul(tmp, small1, small3);
felem_reduce(ftmp, tmp);
/* s2 = tmp = y2 * z1**3 */
felem_small_mul(tmp, y2, ftmp);
felem_reduce(ftmp5, tmp);
/* r = ftmp5 = (s2 - s1)*2 */
felem_diff_zero107(ftmp5, ftmp6);
/* ftmp5[i] < 2^107 + 2^107 = 2^108 */
felem_scalar(ftmp5, 2);
/* ftmp5[i] < 2^109 */
felem_shrink(small1, ftmp5);
y_equal = smallfelem_is_zero(small1);
if (x_equal && y_equal && !z1_is_zero && !z2_is_zero) {
point_double(x3, y3, z3, x1, y1, z1);
return;
}
/* I = ftmp = (2h)**2 */
felem_assign(ftmp, ftmp4);
felem_scalar(ftmp, 2);
/* ftmp[i] < 2*2^108 = 2^109 */
felem_square(tmp, ftmp);
felem_reduce(ftmp, tmp);
/* J = ftmp2 = h * I */
felem_mul(tmp, ftmp4, ftmp);
felem_reduce(ftmp2, tmp);
/* V = ftmp4 = U1 * I */
felem_mul(tmp, ftmp3, ftmp);
felem_reduce(ftmp4, tmp);
/* x_out = r**2 - J - 2V */
smallfelem_square(tmp, small1);
felem_reduce(x_out, tmp);
felem_assign(ftmp3, ftmp4);
felem_scalar(ftmp4, 2);
felem_sum(ftmp4, ftmp2);
/* ftmp4[i] < 2*2^101 + 2^101 < 2^103 */
felem_diff(x_out, ftmp4);
/* x_out[i] < 2^105 + 2^101 */
/* y_out = r(V-x_out) - 2 * s1 * J */
felem_diff_zero107(ftmp3, x_out);
/* ftmp3[i] < 2^107 + 2^101 < 2^108 */
felem_small_mul(tmp, small1, ftmp3);
felem_mul(tmp2, ftmp6, ftmp2);
longfelem_scalar(tmp2, 2);
/* tmp2[i] < 2*2^67 = 2^68 */
longfelem_diff(tmp, tmp2);
/* tmp[i] < 2^67 + 2^70 + 2^40 < 2^71 */
felem_reduce_zero105(y_out, tmp);
/* y_out[i] < 2^106 */
copy_small_conditional(x_out, x2, z1_is_zero);
copy_conditional(x_out, x1, z2_is_zero);
copy_small_conditional(y_out, y2, z1_is_zero);
copy_conditional(y_out, y1, z2_is_zero);
copy_small_conditional(z_out, z2, z1_is_zero);
copy_conditional(z_out, z1, z2_is_zero);
felem_assign(x3, x_out);
felem_assign(y3, y_out);
felem_assign(z3, z_out);
}
/*
* point_add_small is the same as point_add, except that it operates on
* smallfelems
*/
static void point_add_small(smallfelem x3, smallfelem y3, smallfelem z3,
smallfelem x1, smallfelem y1, smallfelem z1,
smallfelem x2, smallfelem y2, smallfelem z2)
{
felem felem_x3, felem_y3, felem_z3;
felem felem_x1, felem_y1, felem_z1;
smallfelem_expand(felem_x1, x1);
smallfelem_expand(felem_y1, y1);
smallfelem_expand(felem_z1, z1);
point_add(felem_x3, felem_y3, felem_z3, felem_x1, felem_y1, felem_z1, 0,
x2, y2, z2);
felem_shrink(x3, felem_x3);
felem_shrink(y3, felem_y3);
felem_shrink(z3, felem_z3);
}
/*-
* Base point pre computation
* --------------------------
*
* Two different sorts of precomputed tables are used in the following code.
* Each contain various points on the curve, where each point is three field
* elements (x, y, z).
*
* For the base point table, z is usually 1 (0 for the point at infinity).
* This table has 2 * 16 elements, starting with the following:
* index | bits | point
* ------+---------+------------------------------
* 0 | 0 0 0 0 | 0G
* 1 | 0 0 0 1 | 1G
* 2 | 0 0 1 0 | 2^64G
* 3 | 0 0 1 1 | (2^64 + 1)G
* 4 | 0 1 0 0 | 2^128G
* 5 | 0 1 0 1 | (2^128 + 1)G
* 6 | 0 1 1 0 | (2^128 + 2^64)G
* 7 | 0 1 1 1 | (2^128 + 2^64 + 1)G
* 8 | 1 0 0 0 | 2^192G
* 9 | 1 0 0 1 | (2^192 + 1)G
* 10 | 1 0 1 0 | (2^192 + 2^64)G
* 11 | 1 0 1 1 | (2^192 + 2^64 + 1)G
* 12 | 1 1 0 0 | (2^192 + 2^128)G
* 13 | 1 1 0 1 | (2^192 + 2^128 + 1)G
* 14 | 1 1 1 0 | (2^192 + 2^128 + 2^64)G
* 15 | 1 1 1 1 | (2^192 + 2^128 + 2^64 + 1)G
* followed by a copy of this with each element multiplied by 2^32.
*
* The reason for this is so that we can clock bits into four different
* locations when doing simple scalar multiplies against the base point,
* and then another four locations using the second 16 elements.
*
* Tables for other points have table[i] = iG for i in 0 .. 16. */
/* gmul is the table of precomputed base points */
static const smallfelem gmul[2][16][3] = {
{{{0, 0, 0, 0},
{0, 0, 0, 0},
{0, 0, 0, 0}},
{{0xf4a13945d898c296, 0x77037d812deb33a0, 0xf8bce6e563a440f2,
0x6b17d1f2e12c4247},
{0xcbb6406837bf51f5, 0x2bce33576b315ece, 0x8ee7eb4a7c0f9e16,
0x4fe342e2fe1a7f9b},
{1, 0, 0, 0}},
{{0x90e75cb48e14db63, 0x29493baaad651f7e, 0x8492592e326e25de,
0x0fa822bc2811aaa5},
{0xe41124545f462ee7, 0x34b1a65050fe82f5, 0x6f4ad4bcb3df188b,
0xbff44ae8f5dba80d},
{1, 0, 0, 0}},
{{0x93391ce2097992af, 0xe96c98fd0d35f1fa, 0xb257c0de95e02789,
0x300a4bbc89d6726f},
{0xaa54a291c08127a0, 0x5bb1eeada9d806a5, 0x7f1ddb25ff1e3c6f,
0x72aac7e0d09b4644},
{1, 0, 0, 0}},
{{0x57c84fc9d789bd85, 0xfc35ff7dc297eac3, 0xfb982fd588c6766e,
0x447d739beedb5e67},
{0x0c7e33c972e25b32, 0x3d349b95a7fae500, 0xe12e9d953a4aaff7,
0x2d4825ab834131ee},
{1, 0, 0, 0}},
{{0x13949c932a1d367f, 0xef7fbd2b1a0a11b7, 0xddc6068bb91dfc60,
0xef9519328a9c72ff},
{0x196035a77376d8a8, 0x23183b0895ca1740, 0xc1ee9807022c219c,
0x611e9fc37dbb2c9b},
{1, 0, 0, 0}},
{{0xcae2b1920b57f4bc, 0x2936df5ec6c9bc36, 0x7dea6482e11238bf,
0x550663797b51f5d8},
{0x44ffe216348a964c, 0x9fb3d576dbdefbe1, 0x0afa40018d9d50e5,
0x157164848aecb851},
{1, 0, 0, 0}},
{{0xe48ecafffc5cde01, 0x7ccd84e70d715f26, 0xa2e8f483f43e4391,
0xeb5d7745b21141ea},
{0xcac917e2731a3479, 0x85f22cfe2844b645, 0x0990e6a158006cee,
0xeafd72ebdbecc17b},
{1, 0, 0, 0}},
{{0x6cf20ffb313728be, 0x96439591a3c6b94a, 0x2736ff8344315fc5,
0xa6d39677a7849276},
{0xf2bab833c357f5f4, 0x824a920c2284059b, 0x66b8babd2d27ecdf,
0x674f84749b0b8816},
{1, 0, 0, 0}},
{{0x2df48c04677c8a3e, 0x74e02f080203a56b, 0x31855f7db8c7fedb,
0x4e769e7672c9ddad},
{0xa4c36165b824bbb0, 0xfb9ae16f3b9122a5, 0x1ec0057206947281,
0x42b99082de830663},
{1, 0, 0, 0}},
{{0x6ef95150dda868b9, 0xd1f89e799c0ce131, 0x7fdc1ca008a1c478,
0x78878ef61c6ce04d},
{0x9c62b9121fe0d976, 0x6ace570ebde08d4f, 0xde53142c12309def,
0xb6cb3f5d7b72c321},
{1, 0, 0, 0}},
{{0x7f991ed2c31a3573, 0x5b82dd5bd54fb496, 0x595c5220812ffcae,
0x0c88bc4d716b1287},
{0x3a57bf635f48aca8, 0x7c8181f4df2564f3, 0x18d1b5b39c04e6aa,
0xdd5ddea3f3901dc6},
{1, 0, 0, 0}},
{{0xe96a79fb3e72ad0c, 0x43a0a28c42ba792f, 0xefe0a423083e49f3,
0x68f344af6b317466},
{0xcdfe17db3fb24d4a, 0x668bfc2271f5c626, 0x604ed93c24d67ff3,
0x31b9c405f8540a20},
{1, 0, 0, 0}},
{{0xd36b4789a2582e7f, 0x0d1a10144ec39c28, 0x663c62c3edbad7a0,
0x4052bf4b6f461db9},
{0x235a27c3188d25eb, 0xe724f33999bfcc5b, 0x862be6bd71d70cc8,
0xfecf4d5190b0fc61},
{1, 0, 0, 0}},
{{0x74346c10a1d4cfac, 0xafdf5cc08526a7a4, 0x123202a8f62bff7a,
0x1eddbae2c802e41a},
{0x8fa0af2dd603f844, 0x36e06b7e4c701917, 0x0c45f45273db33a0,
0x43104d86560ebcfc},
{1, 0, 0, 0}},
{{0x9615b5110d1d78e5, 0x66b0de3225c4744b, 0x0a4a46fb6aaf363a,
0xb48e26b484f7a21c},
{0x06ebb0f621a01b2d, 0xc004e4048b7b0f98, 0x64131bcdfed6f668,
0xfac015404d4d3dab},
{1, 0, 0, 0}}},
{{{0, 0, 0, 0},
{0, 0, 0, 0},
{0, 0, 0, 0}},
{{0x3a5a9e22185a5943, 0x1ab919365c65dfb6, 0x21656b32262c71da,
0x7fe36b40af22af89},
{0xd50d152c699ca101, 0x74b3d5867b8af212, 0x9f09f40407dca6f1,
0xe697d45825b63624},
{1, 0, 0, 0}},
{{0xa84aa9397512218e, 0xe9a521b074ca0141, 0x57880b3a18a2e902,
0x4a5b506612a677a6},
{0x0beada7a4c4f3840, 0x626db15419e26d9d, 0xc42604fbe1627d40,
0xeb13461ceac089f1},
{1, 0, 0, 0}},
{{0xf9faed0927a43281, 0x5e52c4144103ecbc, 0xc342967aa815c857,
0x0781b8291c6a220a},
{0x5a8343ceeac55f80, 0x88f80eeee54a05e3, 0x97b2a14f12916434,
0x690cde8df0151593},
{1, 0, 0, 0}},
{{0xaee9c75df7f82f2a, 0x9e4c35874afdf43a, 0xf5622df437371326,
0x8a535f566ec73617},
{0xc5f9a0ac223094b7, 0xcde533864c8c7669, 0x37e02819085a92bf,
0x0455c08468b08bd7},
{1, 0, 0, 0}},
{{0x0c0a6e2c9477b5d9, 0xf9a4bf62876dc444, 0x5050a949b6cdc279,
0x06bada7ab77f8276},
{0xc8b4aed1ea48dac9, 0xdebd8a4b7ea1070f, 0x427d49101366eb70,
0x5b476dfd0e6cb18a},
{1, 0, 0, 0}},
{{0x7c5c3e44278c340a, 0x4d54606812d66f3b, 0x29a751b1ae23c5d8,
0x3e29864e8a2ec908},
{0x142d2a6626dbb850, 0xad1744c4765bd780, 0x1f150e68e322d1ed,
0x239b90ea3dc31e7e},
{1, 0, 0, 0}},
{{0x78c416527a53322a, 0x305dde6709776f8e, 0xdbcab759f8862ed4,
0x820f4dd949f72ff7},
{0x6cc544a62b5debd4, 0x75be5d937b4e8cc4, 0x1b481b1b215c14d3,
0x140406ec783a05ec},
{1, 0, 0, 0}},
{{0x6a703f10e895df07, 0xfd75f3fa01876bd8, 0xeb5b06e70ce08ffe,
0x68f6b8542783dfee},
{0x90c76f8a78712655, 0xcf5293d2f310bf7f, 0xfbc8044dfda45028,
0xcbe1feba92e40ce6},
{1, 0, 0, 0}},
{{0xe998ceea4396e4c1, 0xfc82ef0b6acea274, 0x230f729f2250e927,
0xd0b2f94d2f420109},
{0x4305adddb38d4966, 0x10b838f8624c3b45, 0x7db2636658954e7a,
0x971459828b0719e5},
{1, 0, 0, 0}},
{{0x4bd6b72623369fc9, 0x57f2929e53d0b876, 0xc2d5cba4f2340687,
0x961610004a866aba},
{0x49997bcd2e407a5e, 0x69ab197d92ddcb24, 0x2cf1f2438fe5131c,
0x7acb9fadcee75e44},
{1, 0, 0, 0}},
{{0x254e839423d2d4c0, 0xf57f0c917aea685b, 0xa60d880f6f75aaea,
0x24eb9acca333bf5b},
{0xe3de4ccb1cda5dea, 0xfeef9341c51a6b4f, 0x743125f88bac4c4d,
0x69f891c5acd079cc},
{1, 0, 0, 0}},
{{0xeee44b35702476b5, 0x7ed031a0e45c2258, 0xb422d1e7bd6f8514,
0xe51f547c5972a107},
{0xa25bcd6fc9cf343d, 0x8ca922ee097c184e, 0xa62f98b3a9fe9a06,
0x1c309a2b25bb1387},
{1, 0, 0, 0}},
{{0x9295dbeb1967c459, 0xb00148833472c98e, 0xc504977708011828,
0x20b87b8aa2c4e503},
{0x3063175de057c277, 0x1bd539338fe582dd, 0x0d11adef5f69a044,
0xf5c6fa49919776be},
{1, 0, 0, 0}},
{{0x8c944e760fd59e11, 0x3876cba1102fad5f, 0xa454c3fad83faa56,
0x1ed7d1b9332010b9},
{0xa1011a270024b889, 0x05e4d0dcac0cd344, 0x52b520f0eb6a2a24,
0x3a2b03f03217257a},
{1, 0, 0, 0}},
{{0xf20fc2afdf1d043d, 0xf330240db58d5a62, 0xfc7d229ca0058c3b,
0x15fee545c78dd9f6},
{0x501e82885bc98cda, 0x41ef80e5d046ac04, 0x557d9f49461210fb,
0x4ab5b6b2b8753f81},
{1, 0, 0, 0}}}
};
/*
* select_point selects the |idx|th point from a precomputation table and
* copies it to out.
*/
static void select_point(const u64 idx, unsigned int size,
const smallfelem pre_comp[16][3], smallfelem out[3])
{
unsigned i, j;
u64 *outlimbs = &out[0][0];
memset(outlimbs, 0, 3 * sizeof(smallfelem));
for (i = 0; i < size; i++) {
const u64 *inlimbs = (u64 *)&pre_comp[i][0][0];
u64 mask = i ^ idx;
mask |= mask >> 4;
mask |= mask >> 2;
mask |= mask >> 1;
mask &= 1;
mask--;
for (j = 0; j < NLIMBS * 3; j++)
outlimbs[j] |= inlimbs[j] & mask;
}
}
/* get_bit returns the |i|th bit in |in| */
static char get_bit(const felem_bytearray in, int i)
{
if ((i < 0) || (i >= 256))
return 0;
return (in[i >> 3] >> (i & 7)) & 1;
}
/*
* Interleaved point multiplication using precomputed point multiples: The
* small point multiples 0*P, 1*P, ..., 17*P are in pre_comp[], the scalars
* in scalars[]. If g_scalar is non-NULL, we also add this multiple of the
* generator, using certain (large) precomputed multiples in g_pre_comp.
* Output point (X, Y, Z) is stored in x_out, y_out, z_out
*/
static void batch_mul(felem x_out, felem y_out, felem z_out,
const felem_bytearray scalars[],
const unsigned num_points, const u8 *g_scalar,
const int mixed, const smallfelem pre_comp[][17][3],
const smallfelem g_pre_comp[2][16][3])
{
int i, skip;
unsigned num, gen_mul = (g_scalar != NULL);
felem nq[3], ftmp;
smallfelem tmp[3];
u64 bits;
u8 sign, digit;
/* set nq to the point at infinity */
memset(nq, 0, 3 * sizeof(felem));
/*
* Loop over all scalars msb-to-lsb, interleaving additions of multiples
* of the generator (two in each of the last 32 rounds) and additions of
* other points multiples (every 5th round).
*/
skip = 1; /* save two point operations in the first
* round */
for (i = (num_points ? 255 : 31); i >= 0; --i) {
/* double */
if (!skip)
point_double(nq[0], nq[1], nq[2], nq[0], nq[1], nq[2]);
/* add multiples of the generator */
if (gen_mul && (i <= 31)) {
/* first, look 32 bits upwards */
bits = get_bit(g_scalar, i + 224) << 3;
bits |= get_bit(g_scalar, i + 160) << 2;
bits |= get_bit(g_scalar, i + 96) << 1;
bits |= get_bit(g_scalar, i + 32);
/* select the point to add, in constant time */
select_point(bits, 16, g_pre_comp[1], tmp);
if (!skip) {
/* Arg 1 below is for "mixed" */
point_add(nq[0], nq[1], nq[2],
nq[0], nq[1], nq[2], 1, tmp[0], tmp[1], tmp[2]);
} else {
smallfelem_expand(nq[0], tmp[0]);
smallfelem_expand(nq[1], tmp[1]);
smallfelem_expand(nq[2], tmp[2]);
skip = 0;
}
/* second, look at the current position */
bits = get_bit(g_scalar, i + 192) << 3;
bits |= get_bit(g_scalar, i + 128) << 2;
bits |= get_bit(g_scalar, i + 64) << 1;
bits |= get_bit(g_scalar, i);
/* select the point to add, in constant time */
select_point(bits, 16, g_pre_comp[0], tmp);
/* Arg 1 below is for "mixed" */
point_add(nq[0], nq[1], nq[2],
nq[0], nq[1], nq[2], 1, tmp[0], tmp[1], tmp[2]);
}
/* do other additions every 5 doublings */
if (num_points && (i % 5 == 0)) {
/* loop over all scalars */
for (num = 0; num < num_points; ++num) {
bits = get_bit(scalars[num], i + 4) << 5;
bits |= get_bit(scalars[num], i + 3) << 4;
bits |= get_bit(scalars[num], i + 2) << 3;
bits |= get_bit(scalars[num], i + 1) << 2;
bits |= get_bit(scalars[num], i) << 1;
bits |= get_bit(scalars[num], i - 1);
ec_GFp_nistp_recode_scalar_bits(&sign, &digit, bits);
/*
* select the point to add or subtract, in constant time
*/
select_point(digit, 17, pre_comp[num], tmp);
smallfelem_neg(ftmp, tmp[1]); /* (X, -Y, Z) is the negative
* point */
copy_small_conditional(ftmp, tmp[1], (((limb) sign) - 1));
felem_contract(tmp[1], ftmp);
if (!skip) {
point_add(nq[0], nq[1], nq[2],
nq[0], nq[1], nq[2],
mixed, tmp[0], tmp[1], tmp[2]);
} else {
smallfelem_expand(nq[0], tmp[0]);
smallfelem_expand(nq[1], tmp[1]);
smallfelem_expand(nq[2], tmp[2]);
skip = 0;
}
}
}
}
felem_assign(x_out, nq[0]);
felem_assign(y_out, nq[1]);
felem_assign(z_out, nq[2]);
}
/* Precomputation for the group generator. */
typedef struct {
smallfelem g_pre_comp[2][16][3];
int references;
} NISTP256_PRE_COMP;
const EC_METHOD *EC_GFp_nistp256_method(void)
{
static const EC_METHOD ret = {
EC_FLAGS_DEFAULT_OCT,
NID_X9_62_prime_field,
ec_GFp_nistp256_group_init,
ec_GFp_simple_group_finish,
ec_GFp_simple_group_clear_finish,
ec_GFp_nist_group_copy,
ec_GFp_nistp256_group_set_curve,
ec_GFp_simple_group_get_curve,
ec_GFp_simple_group_get_degree,
ec_GFp_simple_group_check_discriminant,
ec_GFp_simple_point_init,
ec_GFp_simple_point_finish,
ec_GFp_simple_point_clear_finish,
ec_GFp_simple_point_copy,
ec_GFp_simple_point_set_to_infinity,
ec_GFp_simple_set_Jprojective_coordinates_GFp,
ec_GFp_simple_get_Jprojective_coordinates_GFp,
ec_GFp_simple_point_set_affine_coordinates,
ec_GFp_nistp256_point_get_affine_coordinates,
0 /* point_set_compressed_coordinates */ ,
0 /* point2oct */ ,
0 /* oct2point */ ,
ec_GFp_simple_add,
ec_GFp_simple_dbl,
ec_GFp_simple_invert,
ec_GFp_simple_is_at_infinity,
ec_GFp_simple_is_on_curve,
ec_GFp_simple_cmp,
ec_GFp_simple_make_affine,
ec_GFp_simple_points_make_affine,
ec_GFp_nistp256_points_mul,
ec_GFp_nistp256_precompute_mult,
ec_GFp_nistp256_have_precompute_mult,
ec_GFp_nist_field_mul,
ec_GFp_nist_field_sqr,
0 /* field_div */ ,
0 /* field_encode */ ,
0 /* field_decode */ ,
0 /* field_set_to_one */
};
return &ret;
}
/******************************************************************************/
/*
* FUNCTIONS TO MANAGE PRECOMPUTATION
*/
static NISTP256_PRE_COMP *nistp256_pre_comp_new()
{
NISTP256_PRE_COMP *ret = NULL;
- ret = (NISTP256_PRE_COMP *) OPENSSL_malloc(sizeof *ret);
+ ret = (NISTP256_PRE_COMP *) OPENSSL_malloc(sizeof(*ret));
if (!ret) {
ECerr(EC_F_NISTP256_PRE_COMP_NEW, ERR_R_MALLOC_FAILURE);
return ret;
}
memset(ret->g_pre_comp, 0, sizeof(ret->g_pre_comp));
ret->references = 1;
return ret;
}
static void *nistp256_pre_comp_dup(void *src_)
{
NISTP256_PRE_COMP *src = src_;
/* no need to actually copy, these objects never change! */
CRYPTO_add(&src->references, 1, CRYPTO_LOCK_EC_PRE_COMP);
return src_;
}
static void nistp256_pre_comp_free(void *pre_)
{
int i;
NISTP256_PRE_COMP *pre = pre_;
if (!pre)
return;
i = CRYPTO_add(&pre->references, -1, CRYPTO_LOCK_EC_PRE_COMP);
if (i > 0)
return;
OPENSSL_free(pre);
}
static void nistp256_pre_comp_clear_free(void *pre_)
{
int i;
NISTP256_PRE_COMP *pre = pre_;
if (!pre)
return;
i = CRYPTO_add(&pre->references, -1, CRYPTO_LOCK_EC_PRE_COMP);
if (i > 0)
return;
- OPENSSL_cleanse(pre, sizeof *pre);
+ OPENSSL_cleanse(pre, sizeof(*pre));
OPENSSL_free(pre);
}
/******************************************************************************/
/*
* OPENSSL EC_METHOD FUNCTIONS
*/
int ec_GFp_nistp256_group_init(EC_GROUP *group)
{
int ret;
ret = ec_GFp_simple_group_init(group);
group->a_is_minus3 = 1;
return ret;
}
int ec_GFp_nistp256_group_set_curve(EC_GROUP *group, const BIGNUM *p,
const BIGNUM *a, const BIGNUM *b,
BN_CTX *ctx)
{
int ret = 0;
BN_CTX *new_ctx = NULL;
BIGNUM *curve_p, *curve_a, *curve_b;
if (ctx == NULL)
if ((ctx = new_ctx = BN_CTX_new()) == NULL)
return 0;
BN_CTX_start(ctx);
if (((curve_p = BN_CTX_get(ctx)) == NULL) ||
((curve_a = BN_CTX_get(ctx)) == NULL) ||
((curve_b = BN_CTX_get(ctx)) == NULL))
goto err;
BN_bin2bn(nistp256_curve_params[0], sizeof(felem_bytearray), curve_p);
BN_bin2bn(nistp256_curve_params[1], sizeof(felem_bytearray), curve_a);
BN_bin2bn(nistp256_curve_params[2], sizeof(felem_bytearray), curve_b);
if ((BN_cmp(curve_p, p)) || (BN_cmp(curve_a, a)) || (BN_cmp(curve_b, b))) {
ECerr(EC_F_EC_GFP_NISTP256_GROUP_SET_CURVE,
EC_R_WRONG_CURVE_PARAMETERS);
goto err;
}
group->field_mod_func = BN_nist_mod_256;
ret = ec_GFp_simple_group_set_curve(group, p, a, b, ctx);
err:
BN_CTX_end(ctx);
if (new_ctx != NULL)
BN_CTX_free(new_ctx);
return ret;
}
/*
* Takes the Jacobian coordinates (X, Y, Z) of a point and returns (X', Y') =
* (X/Z^2, Y/Z^3)
*/
int ec_GFp_nistp256_point_get_affine_coordinates(const EC_GROUP *group,
const EC_POINT *point,
BIGNUM *x, BIGNUM *y,
BN_CTX *ctx)
{
felem z1, z2, x_in, y_in;
smallfelem x_out, y_out;
longfelem tmp;
if (EC_POINT_is_at_infinity(group, point)) {
ECerr(EC_F_EC_GFP_NISTP256_POINT_GET_AFFINE_COORDINATES,
EC_R_POINT_AT_INFINITY);
return 0;
}
if ((!BN_to_felem(x_in, &point->X)) || (!BN_to_felem(y_in, &point->Y)) ||
(!BN_to_felem(z1, &point->Z)))
return 0;
felem_inv(z2, z1);
felem_square(tmp, z2);
felem_reduce(z1, tmp);
felem_mul(tmp, x_in, z1);
felem_reduce(x_in, tmp);
felem_contract(x_out, x_in);
if (x != NULL) {
if (!smallfelem_to_BN(x, x_out)) {
ECerr(EC_F_EC_GFP_NISTP256_POINT_GET_AFFINE_COORDINATES,
ERR_R_BN_LIB);
return 0;
}
}
felem_mul(tmp, z1, z2);
felem_reduce(z1, tmp);
felem_mul(tmp, y_in, z1);
felem_reduce(y_in, tmp);
felem_contract(y_out, y_in);
if (y != NULL) {
if (!smallfelem_to_BN(y, y_out)) {
ECerr(EC_F_EC_GFP_NISTP256_POINT_GET_AFFINE_COORDINATES,
ERR_R_BN_LIB);
return 0;
}
}
return 1;
}
/* points below is of size |num|, and tmp_smallfelems is of size |num+1| */
static void make_points_affine(size_t num, smallfelem points[][3],
smallfelem tmp_smallfelems[])
{
/*
* Runs in constant time, unless an input is the point at infinity (which
* normally shouldn't happen).
*/
ec_GFp_nistp_points_make_affine_internal(num,
points,
sizeof(smallfelem),
tmp_smallfelems,
(void (*)(void *))smallfelem_one,
smallfelem_is_zero_int,
(void (*)(void *, const void *))
smallfelem_assign,
(void (*)(void *, const void *))
smallfelem_square_contract,
(void (*)
(void *, const void *,
const void *))
smallfelem_mul_contract,
(void (*)(void *, const void *))
smallfelem_inv_contract,
/* nothing to contract */
(void (*)(void *, const void *))
smallfelem_assign);
}
/*
* Computes scalar*generator + \sum scalars[i]*points[i], ignoring NULL
* values Result is stored in r (r can equal one of the inputs).
*/
int ec_GFp_nistp256_points_mul(const EC_GROUP *group, EC_POINT *r,
const BIGNUM *scalar, size_t num,
const EC_POINT *points[],
const BIGNUM *scalars[], BN_CTX *ctx)
{
int ret = 0;
int j;
int mixed = 0;
BN_CTX *new_ctx = NULL;
BIGNUM *x, *y, *z, *tmp_scalar;
felem_bytearray g_secret;
felem_bytearray *secrets = NULL;
smallfelem(*pre_comp)[17][3] = NULL;
smallfelem *tmp_smallfelems = NULL;
felem_bytearray tmp;
unsigned i, num_bytes;
int have_pre_comp = 0;
size_t num_points = num;
smallfelem x_in, y_in, z_in;
felem x_out, y_out, z_out;
NISTP256_PRE_COMP *pre = NULL;
const smallfelem(*g_pre_comp)[16][3] = NULL;
EC_POINT *generator = NULL;
const EC_POINT *p = NULL;
const BIGNUM *p_scalar = NULL;
if (ctx == NULL)
if ((ctx = new_ctx = BN_CTX_new()) == NULL)
return 0;
BN_CTX_start(ctx);
if (((x = BN_CTX_get(ctx)) == NULL) ||
((y = BN_CTX_get(ctx)) == NULL) ||
((z = BN_CTX_get(ctx)) == NULL) ||
((tmp_scalar = BN_CTX_get(ctx)) == NULL))
goto err;
if (scalar != NULL) {
pre = EC_EX_DATA_get_data(group->extra_data,
nistp256_pre_comp_dup,
nistp256_pre_comp_free,
nistp256_pre_comp_clear_free);
if (pre)
/* we have precomputation, try to use it */
g_pre_comp = (const smallfelem(*)[16][3])pre->g_pre_comp;
else
/* try to use the standard precomputation */
g_pre_comp = &gmul[0];
generator = EC_POINT_new(group);
if (generator == NULL)
goto err;
/* get the generator from precomputation */
if (!smallfelem_to_BN(x, g_pre_comp[0][1][0]) ||
!smallfelem_to_BN(y, g_pre_comp[0][1][1]) ||
!smallfelem_to_BN(z, g_pre_comp[0][1][2])) {
ECerr(EC_F_EC_GFP_NISTP256_POINTS_MUL, ERR_R_BN_LIB);
goto err;
}
if (!EC_POINT_set_Jprojective_coordinates_GFp(group,
generator, x, y, z,
ctx))
goto err;
if (0 == EC_POINT_cmp(group, generator, group->generator, ctx))
/* precomputation matches generator */
have_pre_comp = 1;
else
/*
* we don't have valid precomputation: treat the generator as a
* random point
*/
num_points++;
}
if (num_points > 0) {
if (num_points >= 3) {
/*
* unless we precompute multiples for just one or two points,
* converting those into affine form is time well spent
*/
mixed = 1;
}
secrets = OPENSSL_malloc(num_points * sizeof(felem_bytearray));
pre_comp = OPENSSL_malloc(num_points * 17 * 3 * sizeof(smallfelem));
if (mixed)
tmp_smallfelems =
OPENSSL_malloc((num_points * 17 + 1) * sizeof(smallfelem));
if ((secrets == NULL) || (pre_comp == NULL)
|| (mixed && (tmp_smallfelems == NULL))) {
ECerr(EC_F_EC_GFP_NISTP256_POINTS_MUL, ERR_R_MALLOC_FAILURE);
goto err;
}
/*
* we treat NULL scalars as 0, and NULL points as points at infinity,
* i.e., they contribute nothing to the linear combination
*/
memset(secrets, 0, num_points * sizeof(felem_bytearray));
memset(pre_comp, 0, num_points * 17 * 3 * sizeof(smallfelem));
for (i = 0; i < num_points; ++i) {
if (i == num)
/*
* we didn't have a valid precomputation, so we pick the
* generator
*/
{
p = EC_GROUP_get0_generator(group);
p_scalar = scalar;
} else
/* the i^th point */
{
p = points[i];
p_scalar = scalars[i];
}
if ((p_scalar != NULL) && (p != NULL)) {
/* reduce scalar to 0 <= scalar < 2^256 */
if ((BN_num_bits(p_scalar) > 256)
|| (BN_is_negative(p_scalar))) {
/*
* this is an unusual input, and we don't guarantee
* constant-timeness
*/
if (!BN_nnmod(tmp_scalar, p_scalar, &group->order, ctx)) {
ECerr(EC_F_EC_GFP_NISTP256_POINTS_MUL, ERR_R_BN_LIB);
goto err;
}
num_bytes = BN_bn2bin(tmp_scalar, tmp);
} else
num_bytes = BN_bn2bin(p_scalar, tmp);
flip_endian(secrets[i], tmp, num_bytes);
/* precompute multiples */
if ((!BN_to_felem(x_out, &p->X)) ||
(!BN_to_felem(y_out, &p->Y)) ||
(!BN_to_felem(z_out, &p->Z)))
goto err;
felem_shrink(pre_comp[i][1][0], x_out);
felem_shrink(pre_comp[i][1][1], y_out);
felem_shrink(pre_comp[i][1][2], z_out);
for (j = 2; j <= 16; ++j) {
if (j & 1) {
point_add_small(pre_comp[i][j][0], pre_comp[i][j][1],
pre_comp[i][j][2], pre_comp[i][1][0],
pre_comp[i][1][1], pre_comp[i][1][2],
pre_comp[i][j - 1][0],
pre_comp[i][j - 1][1],
pre_comp[i][j - 1][2]);
} else {
point_double_small(pre_comp[i][j][0],
pre_comp[i][j][1],
pre_comp[i][j][2],
pre_comp[i][j / 2][0],
pre_comp[i][j / 2][1],
pre_comp[i][j / 2][2]);
}
}
}
}
if (mixed)
make_points_affine(num_points * 17, pre_comp[0], tmp_smallfelems);
}
/* the scalar for the generator */
if ((scalar != NULL) && (have_pre_comp)) {
memset(g_secret, 0, sizeof(g_secret));
/* reduce scalar to 0 <= scalar < 2^256 */
if ((BN_num_bits(scalar) > 256) || (BN_is_negative(scalar))) {
/*
* this is an unusual input, and we don't guarantee
* constant-timeness
*/
if (!BN_nnmod(tmp_scalar, scalar, &group->order, ctx)) {
ECerr(EC_F_EC_GFP_NISTP256_POINTS_MUL, ERR_R_BN_LIB);
goto err;
}
num_bytes = BN_bn2bin(tmp_scalar, tmp);
} else
num_bytes = BN_bn2bin(scalar, tmp);
flip_endian(g_secret, tmp, num_bytes);
/* do the multiplication with generator precomputation */
batch_mul(x_out, y_out, z_out,
(const felem_bytearray(*))secrets, num_points,
g_secret,
mixed, (const smallfelem(*)[17][3])pre_comp, g_pre_comp);
} else
/* do the multiplication without generator precomputation */
batch_mul(x_out, y_out, z_out,
(const felem_bytearray(*))secrets, num_points,
NULL, mixed, (const smallfelem(*)[17][3])pre_comp, NULL);
/* reduce the output to its unique minimal representation */
felem_contract(x_in, x_out);
felem_contract(y_in, y_out);
felem_contract(z_in, z_out);
if ((!smallfelem_to_BN(x, x_in)) || (!smallfelem_to_BN(y, y_in)) ||
(!smallfelem_to_BN(z, z_in))) {
ECerr(EC_F_EC_GFP_NISTP256_POINTS_MUL, ERR_R_BN_LIB);
goto err;
}
ret = EC_POINT_set_Jprojective_coordinates_GFp(group, r, x, y, z, ctx);
err:
BN_CTX_end(ctx);
if (generator != NULL)
EC_POINT_free(generator);
if (new_ctx != NULL)
BN_CTX_free(new_ctx);
if (secrets != NULL)
OPENSSL_free(secrets);
if (pre_comp != NULL)
OPENSSL_free(pre_comp);
if (tmp_smallfelems != NULL)
OPENSSL_free(tmp_smallfelems);
return ret;
}
int ec_GFp_nistp256_precompute_mult(EC_GROUP *group, BN_CTX *ctx)
{
int ret = 0;
NISTP256_PRE_COMP *pre = NULL;
int i, j;
BN_CTX *new_ctx = NULL;
BIGNUM *x, *y;
EC_POINT *generator = NULL;
smallfelem tmp_smallfelems[32];
felem x_tmp, y_tmp, z_tmp;
/* throw away old precomputation */
EC_EX_DATA_free_data(&group->extra_data, nistp256_pre_comp_dup,
nistp256_pre_comp_free,
nistp256_pre_comp_clear_free);
if (ctx == NULL)
if ((ctx = new_ctx = BN_CTX_new()) == NULL)
return 0;
BN_CTX_start(ctx);
if (((x = BN_CTX_get(ctx)) == NULL) || ((y = BN_CTX_get(ctx)) == NULL))
goto err;
/* get the generator */
if (group->generator == NULL)
goto err;
generator = EC_POINT_new(group);
if (generator == NULL)
goto err;
BN_bin2bn(nistp256_curve_params[3], sizeof(felem_bytearray), x);
BN_bin2bn(nistp256_curve_params[4], sizeof(felem_bytearray), y);
if (!EC_POINT_set_affine_coordinates_GFp(group, generator, x, y, ctx))
goto err;
if ((pre = nistp256_pre_comp_new()) == NULL)
goto err;
/*
* if the generator is the standard one, use built-in precomputation
*/
if (0 == EC_POINT_cmp(group, generator, group->generator, ctx)) {
memcpy(pre->g_pre_comp, gmul, sizeof(pre->g_pre_comp));
goto done;
}
if ((!BN_to_felem(x_tmp, &group->generator->X)) ||
(!BN_to_felem(y_tmp, &group->generator->Y)) ||
(!BN_to_felem(z_tmp, &group->generator->Z)))
goto err;
felem_shrink(pre->g_pre_comp[0][1][0], x_tmp);
felem_shrink(pre->g_pre_comp[0][1][1], y_tmp);
felem_shrink(pre->g_pre_comp[0][1][2], z_tmp);
/*
* compute 2^64*G, 2^128*G, 2^192*G for the first table, 2^32*G, 2^96*G,
* 2^160*G, 2^224*G for the second one
*/
for (i = 1; i <= 8; i <<= 1) {
point_double_small(pre->g_pre_comp[1][i][0], pre->g_pre_comp[1][i][1],
pre->g_pre_comp[1][i][2], pre->g_pre_comp[0][i][0],
pre->g_pre_comp[0][i][1],
pre->g_pre_comp[0][i][2]);
for (j = 0; j < 31; ++j) {
point_double_small(pre->g_pre_comp[1][i][0],
pre->g_pre_comp[1][i][1],
pre->g_pre_comp[1][i][2],
pre->g_pre_comp[1][i][0],
pre->g_pre_comp[1][i][1],
pre->g_pre_comp[1][i][2]);
}
if (i == 8)
break;
point_double_small(pre->g_pre_comp[0][2 * i][0],
pre->g_pre_comp[0][2 * i][1],
pre->g_pre_comp[0][2 * i][2],
pre->g_pre_comp[1][i][0], pre->g_pre_comp[1][i][1],
pre->g_pre_comp[1][i][2]);
for (j = 0; j < 31; ++j) {
point_double_small(pre->g_pre_comp[0][2 * i][0],
pre->g_pre_comp[0][2 * i][1],
pre->g_pre_comp[0][2 * i][2],
pre->g_pre_comp[0][2 * i][0],
pre->g_pre_comp[0][2 * i][1],
pre->g_pre_comp[0][2 * i][2]);
}
}
for (i = 0; i < 2; i++) {
/* g_pre_comp[i][0] is the point at infinity */
memset(pre->g_pre_comp[i][0], 0, sizeof(pre->g_pre_comp[i][0]));
/* the remaining multiples */
/* 2^64*G + 2^128*G resp. 2^96*G + 2^160*G */
point_add_small(pre->g_pre_comp[i][6][0], pre->g_pre_comp[i][6][1],
pre->g_pre_comp[i][6][2], pre->g_pre_comp[i][4][0],
pre->g_pre_comp[i][4][1], pre->g_pre_comp[i][4][2],
pre->g_pre_comp[i][2][0], pre->g_pre_comp[i][2][1],
pre->g_pre_comp[i][2][2]);
/* 2^64*G + 2^192*G resp. 2^96*G + 2^224*G */
point_add_small(pre->g_pre_comp[i][10][0], pre->g_pre_comp[i][10][1],
pre->g_pre_comp[i][10][2], pre->g_pre_comp[i][8][0],
pre->g_pre_comp[i][8][1], pre->g_pre_comp[i][8][2],
pre->g_pre_comp[i][2][0], pre->g_pre_comp[i][2][1],
pre->g_pre_comp[i][2][2]);
/* 2^128*G + 2^192*G resp. 2^160*G + 2^224*G */
point_add_small(pre->g_pre_comp[i][12][0], pre->g_pre_comp[i][12][1],
pre->g_pre_comp[i][12][2], pre->g_pre_comp[i][8][0],
pre->g_pre_comp[i][8][1], pre->g_pre_comp[i][8][2],
pre->g_pre_comp[i][4][0], pre->g_pre_comp[i][4][1],
pre->g_pre_comp[i][4][2]);
/*
* 2^64*G + 2^128*G + 2^192*G resp. 2^96*G + 2^160*G + 2^224*G
*/
point_add_small(pre->g_pre_comp[i][14][0], pre->g_pre_comp[i][14][1],
pre->g_pre_comp[i][14][2], pre->g_pre_comp[i][12][0],
pre->g_pre_comp[i][12][1], pre->g_pre_comp[i][12][2],
pre->g_pre_comp[i][2][0], pre->g_pre_comp[i][2][1],
pre->g_pre_comp[i][2][2]);
for (j = 1; j < 8; ++j) {
/* odd multiples: add G resp. 2^32*G */
point_add_small(pre->g_pre_comp[i][2 * j + 1][0],
pre->g_pre_comp[i][2 * j + 1][1],
pre->g_pre_comp[i][2 * j + 1][2],
pre->g_pre_comp[i][2 * j][0],
pre->g_pre_comp[i][2 * j][1],
pre->g_pre_comp[i][2 * j][2],
pre->g_pre_comp[i][1][0],
pre->g_pre_comp[i][1][1],
pre->g_pre_comp[i][1][2]);
}
}
make_points_affine(31, &(pre->g_pre_comp[0][1]), tmp_smallfelems);
done:
if (!EC_EX_DATA_set_data(&group->extra_data, pre, nistp256_pre_comp_dup,
nistp256_pre_comp_free,
nistp256_pre_comp_clear_free))
goto err;
ret = 1;
pre = NULL;
err:
BN_CTX_end(ctx);
if (generator != NULL)
EC_POINT_free(generator);
if (new_ctx != NULL)
BN_CTX_free(new_ctx);
if (pre)
nistp256_pre_comp_free(pre);
return ret;
}
int ec_GFp_nistp256_have_precompute_mult(const EC_GROUP *group)
{
if (EC_EX_DATA_get_data(group->extra_data, nistp256_pre_comp_dup,
nistp256_pre_comp_free,
nistp256_pre_comp_clear_free)
!= NULL)
return 1;
else
return 0;
}
#else
static void *dummy = &dummy;
#endif
diff --git a/crypto/ec/ecp_nistp521.c b/crypto/ec/ecp_nistp521.c
index a1dc9946fd17..90989c5a0769 100644
--- a/crypto/ec/ecp_nistp521.c
+++ b/crypto/ec/ecp_nistp521.c
@@ -1,2147 +1,2146 @@
/* crypto/ec/ecp_nistp521.c */
/*
* Written by Adam Langley (Google) for the OpenSSL project
*/
/* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
*
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* A 64-bit implementation of the NIST P-521 elliptic curve point multiplication
*
* OpenSSL integration was taken from Emilia Kasper's work in ecp_nistp224.c.
* Otherwise based on Emilia's P224 work, which was inspired by my curve25519
* work which got its smarts from Daniel J. Bernstein's work on the same.
*/
#include <openssl/opensslconf.h>
#ifndef OPENSSL_NO_EC_NISTP_64_GCC_128
# ifndef OPENSSL_SYS_VMS
# include <stdint.h>
# else
# include <inttypes.h>
# endif
# include <string.h>
# include <openssl/err.h>
# include "ec_lcl.h"
# if defined(__GNUC__) && (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 1))
/* even with gcc, the typedef won't work for 32-bit platforms */
typedef __uint128_t uint128_t; /* nonstandard; implemented by gcc on 64-bit
* platforms */
# else
# error "Need GCC 3.1 or later to define type uint128_t"
# endif
typedef uint8_t u8;
typedef uint64_t u64;
-typedef int64_t s64;
/*
* The underlying field. P521 operates over GF(2^521-1). We can serialise an
* element of this field into 66 bytes where the most significant byte
* contains only a single bit. We call this an felem_bytearray.
*/
typedef u8 felem_bytearray[66];
/*
* These are the parameters of P521, taken from FIPS 186-3, section D.1.2.5.
* These values are big-endian.
*/
static const felem_bytearray nistp521_curve_params[5] = {
{0x01, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* p */
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff},
{0x01, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* a = -3 */
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xfc},
{0x00, 0x51, 0x95, 0x3e, 0xb9, 0x61, 0x8e, 0x1c, /* b */
0x9a, 0x1f, 0x92, 0x9a, 0x21, 0xa0, 0xb6, 0x85,
0x40, 0xee, 0xa2, 0xda, 0x72, 0x5b, 0x99, 0xb3,
0x15, 0xf3, 0xb8, 0xb4, 0x89, 0x91, 0x8e, 0xf1,
0x09, 0xe1, 0x56, 0x19, 0x39, 0x51, 0xec, 0x7e,
0x93, 0x7b, 0x16, 0x52, 0xc0, 0xbd, 0x3b, 0xb1,
0xbf, 0x07, 0x35, 0x73, 0xdf, 0x88, 0x3d, 0x2c,
0x34, 0xf1, 0xef, 0x45, 0x1f, 0xd4, 0x6b, 0x50,
0x3f, 0x00},
{0x00, 0xc6, 0x85, 0x8e, 0x06, 0xb7, 0x04, 0x04, /* x */
0xe9, 0xcd, 0x9e, 0x3e, 0xcb, 0x66, 0x23, 0x95,
0xb4, 0x42, 0x9c, 0x64, 0x81, 0x39, 0x05, 0x3f,
0xb5, 0x21, 0xf8, 0x28, 0xaf, 0x60, 0x6b, 0x4d,
0x3d, 0xba, 0xa1, 0x4b, 0x5e, 0x77, 0xef, 0xe7,
0x59, 0x28, 0xfe, 0x1d, 0xc1, 0x27, 0xa2, 0xff,
0xa8, 0xde, 0x33, 0x48, 0xb3, 0xc1, 0x85, 0x6a,
0x42, 0x9b, 0xf9, 0x7e, 0x7e, 0x31, 0xc2, 0xe5,
0xbd, 0x66},
{0x01, 0x18, 0x39, 0x29, 0x6a, 0x78, 0x9a, 0x3b, /* y */
0xc0, 0x04, 0x5c, 0x8a, 0x5f, 0xb4, 0x2c, 0x7d,
0x1b, 0xd9, 0x98, 0xf5, 0x44, 0x49, 0x57, 0x9b,
0x44, 0x68, 0x17, 0xaf, 0xbd, 0x17, 0x27, 0x3e,
0x66, 0x2c, 0x97, 0xee, 0x72, 0x99, 0x5e, 0xf4,
0x26, 0x40, 0xc5, 0x50, 0xb9, 0x01, 0x3f, 0xad,
0x07, 0x61, 0x35, 0x3c, 0x70, 0x86, 0xa2, 0x72,
0xc2, 0x40, 0x88, 0xbe, 0x94, 0x76, 0x9f, 0xd1,
0x66, 0x50}
};
/*-
* The representation of field elements.
* ------------------------------------
*
* We represent field elements with nine values. These values are either 64 or
* 128 bits and the field element represented is:
* v[0]*2^0 + v[1]*2^58 + v[2]*2^116 + ... + v[8]*2^464 (mod p)
* Each of the nine values is called a 'limb'. Since the limbs are spaced only
* 58 bits apart, but are greater than 58 bits in length, the most significant
* bits of each limb overlap with the least significant bits of the next.
*
* A field element with 64-bit limbs is an 'felem'. One with 128-bit limbs is a
* 'largefelem' */
# define NLIMBS 9
typedef uint64_t limb;
typedef limb felem[NLIMBS];
typedef uint128_t largefelem[NLIMBS];
static const limb bottom57bits = 0x1ffffffffffffff;
static const limb bottom58bits = 0x3ffffffffffffff;
/*
* bin66_to_felem takes a little-endian byte array and converts it into felem
* form. This assumes that the CPU is little-endian.
*/
static void bin66_to_felem(felem out, const u8 in[66])
{
out[0] = (*((limb *) & in[0])) & bottom58bits;
out[1] = (*((limb *) & in[7]) >> 2) & bottom58bits;
out[2] = (*((limb *) & in[14]) >> 4) & bottom58bits;
out[3] = (*((limb *) & in[21]) >> 6) & bottom58bits;
out[4] = (*((limb *) & in[29])) & bottom58bits;
out[5] = (*((limb *) & in[36]) >> 2) & bottom58bits;
out[6] = (*((limb *) & in[43]) >> 4) & bottom58bits;
out[7] = (*((limb *) & in[50]) >> 6) & bottom58bits;
out[8] = (*((limb *) & in[58])) & bottom57bits;
}
/*
* felem_to_bin66 takes an felem and serialises into a little endian, 66 byte
* array. This assumes that the CPU is little-endian.
*/
static void felem_to_bin66(u8 out[66], const felem in)
{
memset(out, 0, 66);
(*((limb *) & out[0])) = in[0];
(*((limb *) & out[7])) |= in[1] << 2;
(*((limb *) & out[14])) |= in[2] << 4;
(*((limb *) & out[21])) |= in[3] << 6;
(*((limb *) & out[29])) = in[4];
(*((limb *) & out[36])) |= in[5] << 2;
(*((limb *) & out[43])) |= in[6] << 4;
(*((limb *) & out[50])) |= in[7] << 6;
(*((limb *) & out[58])) = in[8];
}
/* To preserve endianness when using BN_bn2bin and BN_bin2bn */
static void flip_endian(u8 *out, const u8 *in, unsigned len)
{
unsigned i;
for (i = 0; i < len; ++i)
out[i] = in[len - 1 - i];
}
/* BN_to_felem converts an OpenSSL BIGNUM into an felem */
static int BN_to_felem(felem out, const BIGNUM *bn)
{
felem_bytearray b_in;
felem_bytearray b_out;
unsigned num_bytes;
/* BN_bn2bin eats leading zeroes */
- memset(b_out, 0, sizeof b_out);
+ memset(b_out, 0, sizeof(b_out));
num_bytes = BN_num_bytes(bn);
- if (num_bytes > sizeof b_out) {
+ if (num_bytes > sizeof(b_out)) {
ECerr(EC_F_BN_TO_FELEM, EC_R_BIGNUM_OUT_OF_RANGE);
return 0;
}
if (BN_is_negative(bn)) {
ECerr(EC_F_BN_TO_FELEM, EC_R_BIGNUM_OUT_OF_RANGE);
return 0;
}
num_bytes = BN_bn2bin(bn, b_in);
flip_endian(b_out, b_in, num_bytes);
bin66_to_felem(out, b_out);
return 1;
}
/* felem_to_BN converts an felem into an OpenSSL BIGNUM */
static BIGNUM *felem_to_BN(BIGNUM *out, const felem in)
{
felem_bytearray b_in, b_out;
felem_to_bin66(b_in, in);
- flip_endian(b_out, b_in, sizeof b_out);
- return BN_bin2bn(b_out, sizeof b_out, out);
+ flip_endian(b_out, b_in, sizeof(b_out));
+ return BN_bin2bn(b_out, sizeof(b_out), out);
}
/*-
* Field operations
* ----------------
*/
static void felem_one(felem out)
{
out[0] = 1;
out[1] = 0;
out[2] = 0;
out[3] = 0;
out[4] = 0;
out[5] = 0;
out[6] = 0;
out[7] = 0;
out[8] = 0;
}
static void felem_assign(felem out, const felem in)
{
out[0] = in[0];
out[1] = in[1];
out[2] = in[2];
out[3] = in[3];
out[4] = in[4];
out[5] = in[5];
out[6] = in[6];
out[7] = in[7];
out[8] = in[8];
}
/* felem_sum64 sets out = out + in. */
static void felem_sum64(felem out, const felem in)
{
out[0] += in[0];
out[1] += in[1];
out[2] += in[2];
out[3] += in[3];
out[4] += in[4];
out[5] += in[5];
out[6] += in[6];
out[7] += in[7];
out[8] += in[8];
}
/* felem_scalar sets out = in * scalar */
static void felem_scalar(felem out, const felem in, limb scalar)
{
out[0] = in[0] * scalar;
out[1] = in[1] * scalar;
out[2] = in[2] * scalar;
out[3] = in[3] * scalar;
out[4] = in[4] * scalar;
out[5] = in[5] * scalar;
out[6] = in[6] * scalar;
out[7] = in[7] * scalar;
out[8] = in[8] * scalar;
}
/* felem_scalar64 sets out = out * scalar */
static void felem_scalar64(felem out, limb scalar)
{
out[0] *= scalar;
out[1] *= scalar;
out[2] *= scalar;
out[3] *= scalar;
out[4] *= scalar;
out[5] *= scalar;
out[6] *= scalar;
out[7] *= scalar;
out[8] *= scalar;
}
/* felem_scalar128 sets out = out * scalar */
static void felem_scalar128(largefelem out, limb scalar)
{
out[0] *= scalar;
out[1] *= scalar;
out[2] *= scalar;
out[3] *= scalar;
out[4] *= scalar;
out[5] *= scalar;
out[6] *= scalar;
out[7] *= scalar;
out[8] *= scalar;
}
/*-
* felem_neg sets |out| to |-in|
* On entry:
* in[i] < 2^59 + 2^14
* On exit:
* out[i] < 2^62
*/
static void felem_neg(felem out, const felem in)
{
/* In order to prevent underflow, we subtract from 0 mod p. */
static const limb two62m3 = (((limb) 1) << 62) - (((limb) 1) << 5);
static const limb two62m2 = (((limb) 1) << 62) - (((limb) 1) << 4);
out[0] = two62m3 - in[0];
out[1] = two62m2 - in[1];
out[2] = two62m2 - in[2];
out[3] = two62m2 - in[3];
out[4] = two62m2 - in[4];
out[5] = two62m2 - in[5];
out[6] = two62m2 - in[6];
out[7] = two62m2 - in[7];
out[8] = two62m2 - in[8];
}
/*-
* felem_diff64 subtracts |in| from |out|
* On entry:
* in[i] < 2^59 + 2^14
* On exit:
* out[i] < out[i] + 2^62
*/
static void felem_diff64(felem out, const felem in)
{
/*
* In order to prevent underflow, we add 0 mod p before subtracting.
*/
static const limb two62m3 = (((limb) 1) << 62) - (((limb) 1) << 5);
static const limb two62m2 = (((limb) 1) << 62) - (((limb) 1) << 4);
out[0] += two62m3 - in[0];
out[1] += two62m2 - in[1];
out[2] += two62m2 - in[2];
out[3] += two62m2 - in[3];
out[4] += two62m2 - in[4];
out[5] += two62m2 - in[5];
out[6] += two62m2 - in[6];
out[7] += two62m2 - in[7];
out[8] += two62m2 - in[8];
}
/*-
* felem_diff_128_64 subtracts |in| from |out|
* On entry:
* in[i] < 2^62 + 2^17
* On exit:
* out[i] < out[i] + 2^63
*/
static void felem_diff_128_64(largefelem out, const felem in)
{
/*
* In order to prevent underflow, we add 0 mod p before subtracting.
*/
static const limb two63m6 = (((limb) 1) << 62) - (((limb) 1) << 5);
static const limb two63m5 = (((limb) 1) << 62) - (((limb) 1) << 4);
out[0] += two63m6 - in[0];
out[1] += two63m5 - in[1];
out[2] += two63m5 - in[2];
out[3] += two63m5 - in[3];
out[4] += two63m5 - in[4];
out[5] += two63m5 - in[5];
out[6] += two63m5 - in[6];
out[7] += two63m5 - in[7];
out[8] += two63m5 - in[8];
}
/*-
* felem_diff_128_64 subtracts |in| from |out|
* On entry:
* in[i] < 2^126
* On exit:
* out[i] < out[i] + 2^127 - 2^69
*/
static void felem_diff128(largefelem out, const largefelem in)
{
/*
* In order to prevent underflow, we add 0 mod p before subtracting.
*/
static const uint128_t two127m70 =
(((uint128_t) 1) << 127) - (((uint128_t) 1) << 70);
static const uint128_t two127m69 =
(((uint128_t) 1) << 127) - (((uint128_t) 1) << 69);
out[0] += (two127m70 - in[0]);
out[1] += (two127m69 - in[1]);
out[2] += (two127m69 - in[2]);
out[3] += (two127m69 - in[3]);
out[4] += (two127m69 - in[4]);
out[5] += (two127m69 - in[5]);
out[6] += (two127m69 - in[6]);
out[7] += (two127m69 - in[7]);
out[8] += (two127m69 - in[8]);
}
/*-
* felem_square sets |out| = |in|^2
* On entry:
* in[i] < 2^62
* On exit:
* out[i] < 17 * max(in[i]) * max(in[i])
*/
static void felem_square(largefelem out, const felem in)
{
felem inx2, inx4;
felem_scalar(inx2, in, 2);
felem_scalar(inx4, in, 4);
/*-
* We have many cases were we want to do
* in[x] * in[y] +
* in[y] * in[x]
* This is obviously just
* 2 * in[x] * in[y]
* However, rather than do the doubling on the 128 bit result, we
* double one of the inputs to the multiplication by reading from
* |inx2|
*/
out[0] = ((uint128_t) in[0]) * in[0];
out[1] = ((uint128_t) in[0]) * inx2[1];
out[2] = ((uint128_t) in[0]) * inx2[2] + ((uint128_t) in[1]) * in[1];
out[3] = ((uint128_t) in[0]) * inx2[3] + ((uint128_t) in[1]) * inx2[2];
out[4] = ((uint128_t) in[0]) * inx2[4] +
((uint128_t) in[1]) * inx2[3] + ((uint128_t) in[2]) * in[2];
out[5] = ((uint128_t) in[0]) * inx2[5] +
((uint128_t) in[1]) * inx2[4] + ((uint128_t) in[2]) * inx2[3];
out[6] = ((uint128_t) in[0]) * inx2[6] +
((uint128_t) in[1]) * inx2[5] +
((uint128_t) in[2]) * inx2[4] + ((uint128_t) in[3]) * in[3];
out[7] = ((uint128_t) in[0]) * inx2[7] +
((uint128_t) in[1]) * inx2[6] +
((uint128_t) in[2]) * inx2[5] + ((uint128_t) in[3]) * inx2[4];
out[8] = ((uint128_t) in[0]) * inx2[8] +
((uint128_t) in[1]) * inx2[7] +
((uint128_t) in[2]) * inx2[6] +
((uint128_t) in[3]) * inx2[5] + ((uint128_t) in[4]) * in[4];
/*
* The remaining limbs fall above 2^521, with the first falling at 2^522.
* They correspond to locations one bit up from the limbs produced above
* so we would have to multiply by two to align them. Again, rather than
* operate on the 128-bit result, we double one of the inputs to the
* multiplication. If we want to double for both this reason, and the
* reason above, then we end up multiplying by four.
*/
/* 9 */
out[0] += ((uint128_t) in[1]) * inx4[8] +
((uint128_t) in[2]) * inx4[7] +
((uint128_t) in[3]) * inx4[6] + ((uint128_t) in[4]) * inx4[5];
/* 10 */
out[1] += ((uint128_t) in[2]) * inx4[8] +
((uint128_t) in[3]) * inx4[7] +
((uint128_t) in[4]) * inx4[6] + ((uint128_t) in[5]) * inx2[5];
/* 11 */
out[2] += ((uint128_t) in[3]) * inx4[8] +
((uint128_t) in[4]) * inx4[7] + ((uint128_t) in[5]) * inx4[6];
/* 12 */
out[3] += ((uint128_t) in[4]) * inx4[8] +
((uint128_t) in[5]) * inx4[7] + ((uint128_t) in[6]) * inx2[6];
/* 13 */
out[4] += ((uint128_t) in[5]) * inx4[8] + ((uint128_t) in[6]) * inx4[7];
/* 14 */
out[5] += ((uint128_t) in[6]) * inx4[8] + ((uint128_t) in[7]) * inx2[7];
/* 15 */
out[6] += ((uint128_t) in[7]) * inx4[8];
/* 16 */
out[7] += ((uint128_t) in[8]) * inx2[8];
}
/*-
* felem_mul sets |out| = |in1| * |in2|
* On entry:
* in1[i] < 2^64
* in2[i] < 2^63
* On exit:
* out[i] < 17 * max(in1[i]) * max(in2[i])
*/
static void felem_mul(largefelem out, const felem in1, const felem in2)
{
felem in2x2;
felem_scalar(in2x2, in2, 2);
out[0] = ((uint128_t) in1[0]) * in2[0];
out[1] = ((uint128_t) in1[0]) * in2[1] + ((uint128_t) in1[1]) * in2[0];
out[2] = ((uint128_t) in1[0]) * in2[2] +
((uint128_t) in1[1]) * in2[1] + ((uint128_t) in1[2]) * in2[0];
out[3] = ((uint128_t) in1[0]) * in2[3] +
((uint128_t) in1[1]) * in2[2] +
((uint128_t) in1[2]) * in2[1] + ((uint128_t) in1[3]) * in2[0];
out[4] = ((uint128_t) in1[0]) * in2[4] +
((uint128_t) in1[1]) * in2[3] +
((uint128_t) in1[2]) * in2[2] +
((uint128_t) in1[3]) * in2[1] + ((uint128_t) in1[4]) * in2[0];
out[5] = ((uint128_t) in1[0]) * in2[5] +
((uint128_t) in1[1]) * in2[4] +
((uint128_t) in1[2]) * in2[3] +
((uint128_t) in1[3]) * in2[2] +
((uint128_t) in1[4]) * in2[1] + ((uint128_t) in1[5]) * in2[0];
out[6] = ((uint128_t) in1[0]) * in2[6] +
((uint128_t) in1[1]) * in2[5] +
((uint128_t) in1[2]) * in2[4] +
((uint128_t) in1[3]) * in2[3] +
((uint128_t) in1[4]) * in2[2] +
((uint128_t) in1[5]) * in2[1] + ((uint128_t) in1[6]) * in2[0];
out[7] = ((uint128_t) in1[0]) * in2[7] +
((uint128_t) in1[1]) * in2[6] +
((uint128_t) in1[2]) * in2[5] +
((uint128_t) in1[3]) * in2[4] +
((uint128_t) in1[4]) * in2[3] +
((uint128_t) in1[5]) * in2[2] +
((uint128_t) in1[6]) * in2[1] + ((uint128_t) in1[7]) * in2[0];
out[8] = ((uint128_t) in1[0]) * in2[8] +
((uint128_t) in1[1]) * in2[7] +
((uint128_t) in1[2]) * in2[6] +
((uint128_t) in1[3]) * in2[5] +
((uint128_t) in1[4]) * in2[4] +
((uint128_t) in1[5]) * in2[3] +
((uint128_t) in1[6]) * in2[2] +
((uint128_t) in1[7]) * in2[1] + ((uint128_t) in1[8]) * in2[0];
/* See comment in felem_square about the use of in2x2 here */
out[0] += ((uint128_t) in1[1]) * in2x2[8] +
((uint128_t) in1[2]) * in2x2[7] +
((uint128_t) in1[3]) * in2x2[6] +
((uint128_t) in1[4]) * in2x2[5] +
((uint128_t) in1[5]) * in2x2[4] +
((uint128_t) in1[6]) * in2x2[3] +
((uint128_t) in1[7]) * in2x2[2] + ((uint128_t) in1[8]) * in2x2[1];
out[1] += ((uint128_t) in1[2]) * in2x2[8] +
((uint128_t) in1[3]) * in2x2[7] +
((uint128_t) in1[4]) * in2x2[6] +
((uint128_t) in1[5]) * in2x2[5] +
((uint128_t) in1[6]) * in2x2[4] +
((uint128_t) in1[7]) * in2x2[3] + ((uint128_t) in1[8]) * in2x2[2];
out[2] += ((uint128_t) in1[3]) * in2x2[8] +
((uint128_t) in1[4]) * in2x2[7] +
((uint128_t) in1[5]) * in2x2[6] +
((uint128_t) in1[6]) * in2x2[5] +
((uint128_t) in1[7]) * in2x2[4] + ((uint128_t) in1[8]) * in2x2[3];
out[3] += ((uint128_t) in1[4]) * in2x2[8] +
((uint128_t) in1[5]) * in2x2[7] +
((uint128_t) in1[6]) * in2x2[6] +
((uint128_t) in1[7]) * in2x2[5] + ((uint128_t) in1[8]) * in2x2[4];
out[4] += ((uint128_t) in1[5]) * in2x2[8] +
((uint128_t) in1[6]) * in2x2[7] +
((uint128_t) in1[7]) * in2x2[6] + ((uint128_t) in1[8]) * in2x2[5];
out[5] += ((uint128_t) in1[6]) * in2x2[8] +
((uint128_t) in1[7]) * in2x2[7] + ((uint128_t) in1[8]) * in2x2[6];
out[6] += ((uint128_t) in1[7]) * in2x2[8] +
((uint128_t) in1[8]) * in2x2[7];
out[7] += ((uint128_t) in1[8]) * in2x2[8];
}
static const limb bottom52bits = 0xfffffffffffff;
/*-
* felem_reduce converts a largefelem to an felem.
* On entry:
* in[i] < 2^128
* On exit:
* out[i] < 2^59 + 2^14
*/
static void felem_reduce(felem out, const largefelem in)
{
u64 overflow1, overflow2;
out[0] = ((limb) in[0]) & bottom58bits;
out[1] = ((limb) in[1]) & bottom58bits;
out[2] = ((limb) in[2]) & bottom58bits;
out[3] = ((limb) in[3]) & bottom58bits;
out[4] = ((limb) in[4]) & bottom58bits;
out[5] = ((limb) in[5]) & bottom58bits;
out[6] = ((limb) in[6]) & bottom58bits;
out[7] = ((limb) in[7]) & bottom58bits;
out[8] = ((limb) in[8]) & bottom58bits;
/* out[i] < 2^58 */
out[1] += ((limb) in[0]) >> 58;
out[1] += (((limb) (in[0] >> 64)) & bottom52bits) << 6;
/*-
* out[1] < 2^58 + 2^6 + 2^58
* = 2^59 + 2^6
*/
out[2] += ((limb) (in[0] >> 64)) >> 52;
out[2] += ((limb) in[1]) >> 58;
out[2] += (((limb) (in[1] >> 64)) & bottom52bits) << 6;
out[3] += ((limb) (in[1] >> 64)) >> 52;
out[3] += ((limb) in[2]) >> 58;
out[3] += (((limb) (in[2] >> 64)) & bottom52bits) << 6;
out[4] += ((limb) (in[2] >> 64)) >> 52;
out[4] += ((limb) in[3]) >> 58;
out[4] += (((limb) (in[3] >> 64)) & bottom52bits) << 6;
out[5] += ((limb) (in[3] >> 64)) >> 52;
out[5] += ((limb) in[4]) >> 58;
out[5] += (((limb) (in[4] >> 64)) & bottom52bits) << 6;
out[6] += ((limb) (in[4] >> 64)) >> 52;
out[6] += ((limb) in[5]) >> 58;
out[6] += (((limb) (in[5] >> 64)) & bottom52bits) << 6;
out[7] += ((limb) (in[5] >> 64)) >> 52;
out[7] += ((limb) in[6]) >> 58;
out[7] += (((limb) (in[6] >> 64)) & bottom52bits) << 6;
out[8] += ((limb) (in[6] >> 64)) >> 52;
out[8] += ((limb) in[7]) >> 58;
out[8] += (((limb) (in[7] >> 64)) & bottom52bits) << 6;
/*-
* out[x > 1] < 2^58 + 2^6 + 2^58 + 2^12
* < 2^59 + 2^13
*/
overflow1 = ((limb) (in[7] >> 64)) >> 52;
overflow1 += ((limb) in[8]) >> 58;
overflow1 += (((limb) (in[8] >> 64)) & bottom52bits) << 6;
overflow2 = ((limb) (in[8] >> 64)) >> 52;
overflow1 <<= 1; /* overflow1 < 2^13 + 2^7 + 2^59 */
overflow2 <<= 1; /* overflow2 < 2^13 */
out[0] += overflow1; /* out[0] < 2^60 */
out[1] += overflow2; /* out[1] < 2^59 + 2^6 + 2^13 */
out[1] += out[0] >> 58;
out[0] &= bottom58bits;
/*-
* out[0] < 2^58
* out[1] < 2^59 + 2^6 + 2^13 + 2^2
* < 2^59 + 2^14
*/
}
static void felem_square_reduce(felem out, const felem in)
{
largefelem tmp;
felem_square(tmp, in);
felem_reduce(out, tmp);
}
static void felem_mul_reduce(felem out, const felem in1, const felem in2)
{
largefelem tmp;
felem_mul(tmp, in1, in2);
felem_reduce(out, tmp);
}
/*-
* felem_inv calculates |out| = |in|^{-1}
*
* Based on Fermat's Little Theorem:
* a^p = a (mod p)
* a^{p-1} = 1 (mod p)
* a^{p-2} = a^{-1} (mod p)
*/
static void felem_inv(felem out, const felem in)
{
felem ftmp, ftmp2, ftmp3, ftmp4;
largefelem tmp;
unsigned i;
felem_square(tmp, in);
felem_reduce(ftmp, tmp); /* 2^1 */
felem_mul(tmp, in, ftmp);
felem_reduce(ftmp, tmp); /* 2^2 - 2^0 */
felem_assign(ftmp2, ftmp);
felem_square(tmp, ftmp);
felem_reduce(ftmp, tmp); /* 2^3 - 2^1 */
felem_mul(tmp, in, ftmp);
felem_reduce(ftmp, tmp); /* 2^3 - 2^0 */
felem_square(tmp, ftmp);
felem_reduce(ftmp, tmp); /* 2^4 - 2^1 */
felem_square(tmp, ftmp2);
felem_reduce(ftmp3, tmp); /* 2^3 - 2^1 */
felem_square(tmp, ftmp3);
felem_reduce(ftmp3, tmp); /* 2^4 - 2^2 */
felem_mul(tmp, ftmp3, ftmp2);
felem_reduce(ftmp3, tmp); /* 2^4 - 2^0 */
felem_assign(ftmp2, ftmp3);
felem_square(tmp, ftmp3);
felem_reduce(ftmp3, tmp); /* 2^5 - 2^1 */
felem_square(tmp, ftmp3);
felem_reduce(ftmp3, tmp); /* 2^6 - 2^2 */
felem_square(tmp, ftmp3);
felem_reduce(ftmp3, tmp); /* 2^7 - 2^3 */
felem_square(tmp, ftmp3);
felem_reduce(ftmp3, tmp); /* 2^8 - 2^4 */
felem_assign(ftmp4, ftmp3);
felem_mul(tmp, ftmp3, ftmp);
felem_reduce(ftmp4, tmp); /* 2^8 - 2^1 */
felem_square(tmp, ftmp4);
felem_reduce(ftmp4, tmp); /* 2^9 - 2^2 */
felem_mul(tmp, ftmp3, ftmp2);
felem_reduce(ftmp3, tmp); /* 2^8 - 2^0 */
felem_assign(ftmp2, ftmp3);
for (i = 0; i < 8; i++) {
felem_square(tmp, ftmp3);
felem_reduce(ftmp3, tmp); /* 2^16 - 2^8 */
}
felem_mul(tmp, ftmp3, ftmp2);
felem_reduce(ftmp3, tmp); /* 2^16 - 2^0 */
felem_assign(ftmp2, ftmp3);
for (i = 0; i < 16; i++) {
felem_square(tmp, ftmp3);
felem_reduce(ftmp3, tmp); /* 2^32 - 2^16 */
}
felem_mul(tmp, ftmp3, ftmp2);
felem_reduce(ftmp3, tmp); /* 2^32 - 2^0 */
felem_assign(ftmp2, ftmp3);
for (i = 0; i < 32; i++) {
felem_square(tmp, ftmp3);
felem_reduce(ftmp3, tmp); /* 2^64 - 2^32 */
}
felem_mul(tmp, ftmp3, ftmp2);
felem_reduce(ftmp3, tmp); /* 2^64 - 2^0 */
felem_assign(ftmp2, ftmp3);
for (i = 0; i < 64; i++) {
felem_square(tmp, ftmp3);
felem_reduce(ftmp3, tmp); /* 2^128 - 2^64 */
}
felem_mul(tmp, ftmp3, ftmp2);
felem_reduce(ftmp3, tmp); /* 2^128 - 2^0 */
felem_assign(ftmp2, ftmp3);
for (i = 0; i < 128; i++) {
felem_square(tmp, ftmp3);
felem_reduce(ftmp3, tmp); /* 2^256 - 2^128 */
}
felem_mul(tmp, ftmp3, ftmp2);
felem_reduce(ftmp3, tmp); /* 2^256 - 2^0 */
felem_assign(ftmp2, ftmp3);
for (i = 0; i < 256; i++) {
felem_square(tmp, ftmp3);
felem_reduce(ftmp3, tmp); /* 2^512 - 2^256 */
}
felem_mul(tmp, ftmp3, ftmp2);
felem_reduce(ftmp3, tmp); /* 2^512 - 2^0 */
for (i = 0; i < 9; i++) {
felem_square(tmp, ftmp3);
felem_reduce(ftmp3, tmp); /* 2^521 - 2^9 */
}
felem_mul(tmp, ftmp3, ftmp4);
felem_reduce(ftmp3, tmp); /* 2^512 - 2^2 */
felem_mul(tmp, ftmp3, in);
felem_reduce(out, tmp); /* 2^512 - 3 */
}
/* This is 2^521-1, expressed as an felem */
static const felem kPrime = {
0x03ffffffffffffff, 0x03ffffffffffffff, 0x03ffffffffffffff,
0x03ffffffffffffff, 0x03ffffffffffffff, 0x03ffffffffffffff,
0x03ffffffffffffff, 0x03ffffffffffffff, 0x01ffffffffffffff
};
/*-
* felem_is_zero returns a limb with all bits set if |in| == 0 (mod p) and 0
* otherwise.
* On entry:
* in[i] < 2^59 + 2^14
*/
static limb felem_is_zero(const felem in)
{
felem ftmp;
limb is_zero, is_p;
felem_assign(ftmp, in);
ftmp[0] += ftmp[8] >> 57;
ftmp[8] &= bottom57bits;
/* ftmp[8] < 2^57 */
ftmp[1] += ftmp[0] >> 58;
ftmp[0] &= bottom58bits;
ftmp[2] += ftmp[1] >> 58;
ftmp[1] &= bottom58bits;
ftmp[3] += ftmp[2] >> 58;
ftmp[2] &= bottom58bits;
ftmp[4] += ftmp[3] >> 58;
ftmp[3] &= bottom58bits;
ftmp[5] += ftmp[4] >> 58;
ftmp[4] &= bottom58bits;
ftmp[6] += ftmp[5] >> 58;
ftmp[5] &= bottom58bits;
ftmp[7] += ftmp[6] >> 58;
ftmp[6] &= bottom58bits;
ftmp[8] += ftmp[7] >> 58;
ftmp[7] &= bottom58bits;
/* ftmp[8] < 2^57 + 4 */
/*
* The ninth limb of 2*(2^521-1) is 0x03ffffffffffffff, which is greater
* than our bound for ftmp[8]. Therefore we only have to check if the
* zero is zero or 2^521-1.
*/
is_zero = 0;
is_zero |= ftmp[0];
is_zero |= ftmp[1];
is_zero |= ftmp[2];
is_zero |= ftmp[3];
is_zero |= ftmp[4];
is_zero |= ftmp[5];
is_zero |= ftmp[6];
is_zero |= ftmp[7];
is_zero |= ftmp[8];
is_zero--;
/*
* We know that ftmp[i] < 2^63, therefore the only way that the top bit
* can be set is if is_zero was 0 before the decrement.
*/
- is_zero = ((s64) is_zero) >> 63;
+ is_zero = 0 - (is_zero >> 63);
is_p = ftmp[0] ^ kPrime[0];
is_p |= ftmp[1] ^ kPrime[1];
is_p |= ftmp[2] ^ kPrime[2];
is_p |= ftmp[3] ^ kPrime[3];
is_p |= ftmp[4] ^ kPrime[4];
is_p |= ftmp[5] ^ kPrime[5];
is_p |= ftmp[6] ^ kPrime[6];
is_p |= ftmp[7] ^ kPrime[7];
is_p |= ftmp[8] ^ kPrime[8];
is_p--;
- is_p = ((s64) is_p) >> 63;
+ is_p = 0 - (is_p >> 63);
is_zero |= is_p;
return is_zero;
}
static int felem_is_zero_int(const void *in)
{
return (int)(felem_is_zero(in) & ((limb) 1));
}
/*-
* felem_contract converts |in| to its unique, minimal representation.
* On entry:
* in[i] < 2^59 + 2^14
*/
static void felem_contract(felem out, const felem in)
{
limb is_p, is_greater, sign;
static const limb two58 = ((limb) 1) << 58;
felem_assign(out, in);
out[0] += out[8] >> 57;
out[8] &= bottom57bits;
/* out[8] < 2^57 */
out[1] += out[0] >> 58;
out[0] &= bottom58bits;
out[2] += out[1] >> 58;
out[1] &= bottom58bits;
out[3] += out[2] >> 58;
out[2] &= bottom58bits;
out[4] += out[3] >> 58;
out[3] &= bottom58bits;
out[5] += out[4] >> 58;
out[4] &= bottom58bits;
out[6] += out[5] >> 58;
out[5] &= bottom58bits;
out[7] += out[6] >> 58;
out[6] &= bottom58bits;
out[8] += out[7] >> 58;
out[7] &= bottom58bits;
/* out[8] < 2^57 + 4 */
/*
* If the value is greater than 2^521-1 then we have to subtract 2^521-1
* out. See the comments in felem_is_zero regarding why we don't test for
* other multiples of the prime.
*/
/*
* First, if |out| is equal to 2^521-1, we subtract it out to get zero.
*/
is_p = out[0] ^ kPrime[0];
is_p |= out[1] ^ kPrime[1];
is_p |= out[2] ^ kPrime[2];
is_p |= out[3] ^ kPrime[3];
is_p |= out[4] ^ kPrime[4];
is_p |= out[5] ^ kPrime[5];
is_p |= out[6] ^ kPrime[6];
is_p |= out[7] ^ kPrime[7];
is_p |= out[8] ^ kPrime[8];
is_p--;
is_p &= is_p << 32;
is_p &= is_p << 16;
is_p &= is_p << 8;
is_p &= is_p << 4;
is_p &= is_p << 2;
is_p &= is_p << 1;
- is_p = ((s64) is_p) >> 63;
+ is_p = 0 - (is_p >> 63);
is_p = ~is_p;
/* is_p is 0 iff |out| == 2^521-1 and all ones otherwise */
out[0] &= is_p;
out[1] &= is_p;
out[2] &= is_p;
out[3] &= is_p;
out[4] &= is_p;
out[5] &= is_p;
out[6] &= is_p;
out[7] &= is_p;
out[8] &= is_p;
/*
* In order to test that |out| >= 2^521-1 we need only test if out[8] >>
* 57 is greater than zero as (2^521-1) + x >= 2^522
*/
is_greater = out[8] >> 57;
is_greater |= is_greater << 32;
is_greater |= is_greater << 16;
is_greater |= is_greater << 8;
is_greater |= is_greater << 4;
is_greater |= is_greater << 2;
is_greater |= is_greater << 1;
- is_greater = ((s64) is_greater) >> 63;
+ is_greater = 0 - (is_greater >> 63);
out[0] -= kPrime[0] & is_greater;
out[1] -= kPrime[1] & is_greater;
out[2] -= kPrime[2] & is_greater;
out[3] -= kPrime[3] & is_greater;
out[4] -= kPrime[4] & is_greater;
out[5] -= kPrime[5] & is_greater;
out[6] -= kPrime[6] & is_greater;
out[7] -= kPrime[7] & is_greater;
out[8] -= kPrime[8] & is_greater;
/* Eliminate negative coefficients */
sign = -(out[0] >> 63);
out[0] += (two58 & sign);
out[1] -= (1 & sign);
sign = -(out[1] >> 63);
out[1] += (two58 & sign);
out[2] -= (1 & sign);
sign = -(out[2] >> 63);
out[2] += (two58 & sign);
out[3] -= (1 & sign);
sign = -(out[3] >> 63);
out[3] += (two58 & sign);
out[4] -= (1 & sign);
sign = -(out[4] >> 63);
out[4] += (two58 & sign);
out[5] -= (1 & sign);
sign = -(out[0] >> 63);
out[5] += (two58 & sign);
out[6] -= (1 & sign);
sign = -(out[6] >> 63);
out[6] += (two58 & sign);
out[7] -= (1 & sign);
sign = -(out[7] >> 63);
out[7] += (two58 & sign);
out[8] -= (1 & sign);
sign = -(out[5] >> 63);
out[5] += (two58 & sign);
out[6] -= (1 & sign);
sign = -(out[6] >> 63);
out[6] += (two58 & sign);
out[7] -= (1 & sign);
sign = -(out[7] >> 63);
out[7] += (two58 & sign);
out[8] -= (1 & sign);
}
/*-
* Group operations
* ----------------
*
* Building on top of the field operations we have the operations on the
* elliptic curve group itself. Points on the curve are represented in Jacobian
* coordinates */
/*-
* point_double calcuates 2*(x_in, y_in, z_in)
*
* The method is taken from:
* http://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html#doubling-dbl-2001-b
*
* Outputs can equal corresponding inputs, i.e., x_out == x_in is allowed.
* while x_out == y_in is not (maybe this works, but it's not tested). */
static void
point_double(felem x_out, felem y_out, felem z_out,
const felem x_in, const felem y_in, const felem z_in)
{
largefelem tmp, tmp2;
felem delta, gamma, beta, alpha, ftmp, ftmp2;
felem_assign(ftmp, x_in);
felem_assign(ftmp2, x_in);
/* delta = z^2 */
felem_square(tmp, z_in);
felem_reduce(delta, tmp); /* delta[i] < 2^59 + 2^14 */
/* gamma = y^2 */
felem_square(tmp, y_in);
felem_reduce(gamma, tmp); /* gamma[i] < 2^59 + 2^14 */
/* beta = x*gamma */
felem_mul(tmp, x_in, gamma);
felem_reduce(beta, tmp); /* beta[i] < 2^59 + 2^14 */
/* alpha = 3*(x-delta)*(x+delta) */
felem_diff64(ftmp, delta);
/* ftmp[i] < 2^61 */
felem_sum64(ftmp2, delta);
/* ftmp2[i] < 2^60 + 2^15 */
felem_scalar64(ftmp2, 3);
/* ftmp2[i] < 3*2^60 + 3*2^15 */
felem_mul(tmp, ftmp, ftmp2);
/*-
* tmp[i] < 17(3*2^121 + 3*2^76)
* = 61*2^121 + 61*2^76
* < 64*2^121 + 64*2^76
* = 2^127 + 2^82
* < 2^128
*/
felem_reduce(alpha, tmp);
/* x' = alpha^2 - 8*beta */
felem_square(tmp, alpha);
/*
* tmp[i] < 17*2^120 < 2^125
*/
felem_assign(ftmp, beta);
felem_scalar64(ftmp, 8);
/* ftmp[i] < 2^62 + 2^17 */
felem_diff_128_64(tmp, ftmp);
/* tmp[i] < 2^125 + 2^63 + 2^62 + 2^17 */
felem_reduce(x_out, tmp);
/* z' = (y + z)^2 - gamma - delta */
felem_sum64(delta, gamma);
/* delta[i] < 2^60 + 2^15 */
felem_assign(ftmp, y_in);
felem_sum64(ftmp, z_in);
/* ftmp[i] < 2^60 + 2^15 */
felem_square(tmp, ftmp);
/*
* tmp[i] < 17(2^122) < 2^127
*/
felem_diff_128_64(tmp, delta);
/* tmp[i] < 2^127 + 2^63 */
felem_reduce(z_out, tmp);
/* y' = alpha*(4*beta - x') - 8*gamma^2 */
felem_scalar64(beta, 4);
/* beta[i] < 2^61 + 2^16 */
felem_diff64(beta, x_out);
/* beta[i] < 2^61 + 2^60 + 2^16 */
felem_mul(tmp, alpha, beta);
/*-
* tmp[i] < 17*((2^59 + 2^14)(2^61 + 2^60 + 2^16))
* = 17*(2^120 + 2^75 + 2^119 + 2^74 + 2^75 + 2^30)
* = 17*(2^120 + 2^119 + 2^76 + 2^74 + 2^30)
* < 2^128
*/
felem_square(tmp2, gamma);
/*-
* tmp2[i] < 17*(2^59 + 2^14)^2
* = 17*(2^118 + 2^74 + 2^28)
*/
felem_scalar128(tmp2, 8);
/*-
* tmp2[i] < 8*17*(2^118 + 2^74 + 2^28)
* = 2^125 + 2^121 + 2^81 + 2^77 + 2^35 + 2^31
* < 2^126
*/
felem_diff128(tmp, tmp2);
/*-
* tmp[i] < 2^127 - 2^69 + 17(2^120 + 2^119 + 2^76 + 2^74 + 2^30)
* = 2^127 + 2^124 + 2^122 + 2^120 + 2^118 + 2^80 + 2^78 + 2^76 +
* 2^74 + 2^69 + 2^34 + 2^30
* < 2^128
*/
felem_reduce(y_out, tmp);
}
/* copy_conditional copies in to out iff mask is all ones. */
static void copy_conditional(felem out, const felem in, limb mask)
{
unsigned i;
for (i = 0; i < NLIMBS; ++i) {
const limb tmp = mask & (in[i] ^ out[i]);
out[i] ^= tmp;
}
}
/*-
* point_add calcuates (x1, y1, z1) + (x2, y2, z2)
*
* The method is taken from
* http://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html#addition-add-2007-bl,
* adapted for mixed addition (z2 = 1, or z2 = 0 for the point at infinity).
*
* This function includes a branch for checking whether the two input points
* are equal (while not equal to the point at infinity). This case never
* happens during single point multiplication, so there is no timing leak for
* ECDH or ECDSA signing. */
static void point_add(felem x3, felem y3, felem z3,
const felem x1, const felem y1, const felem z1,
const int mixed, const felem x2, const felem y2,
const felem z2)
{
felem ftmp, ftmp2, ftmp3, ftmp4, ftmp5, ftmp6, x_out, y_out, z_out;
largefelem tmp, tmp2;
limb x_equal, y_equal, z1_is_zero, z2_is_zero;
z1_is_zero = felem_is_zero(z1);
z2_is_zero = felem_is_zero(z2);
/* ftmp = z1z1 = z1**2 */
felem_square(tmp, z1);
felem_reduce(ftmp, tmp);
if (!mixed) {
/* ftmp2 = z2z2 = z2**2 */
felem_square(tmp, z2);
felem_reduce(ftmp2, tmp);
/* u1 = ftmp3 = x1*z2z2 */
felem_mul(tmp, x1, ftmp2);
felem_reduce(ftmp3, tmp);
/* ftmp5 = z1 + z2 */
felem_assign(ftmp5, z1);
felem_sum64(ftmp5, z2);
/* ftmp5[i] < 2^61 */
/* ftmp5 = (z1 + z2)**2 - z1z1 - z2z2 = 2*z1z2 */
felem_square(tmp, ftmp5);
/* tmp[i] < 17*2^122 */
felem_diff_128_64(tmp, ftmp);
/* tmp[i] < 17*2^122 + 2^63 */
felem_diff_128_64(tmp, ftmp2);
/* tmp[i] < 17*2^122 + 2^64 */
felem_reduce(ftmp5, tmp);
/* ftmp2 = z2 * z2z2 */
felem_mul(tmp, ftmp2, z2);
felem_reduce(ftmp2, tmp);
/* s1 = ftmp6 = y1 * z2**3 */
felem_mul(tmp, y1, ftmp2);
felem_reduce(ftmp6, tmp);
} else {
/*
* We'll assume z2 = 1 (special case z2 = 0 is handled later)
*/
/* u1 = ftmp3 = x1*z2z2 */
felem_assign(ftmp3, x1);
/* ftmp5 = 2*z1z2 */
felem_scalar(ftmp5, z1, 2);
/* s1 = ftmp6 = y1 * z2**3 */
felem_assign(ftmp6, y1);
}
/* u2 = x2*z1z1 */
felem_mul(tmp, x2, ftmp);
/* tmp[i] < 17*2^120 */
/* h = ftmp4 = u2 - u1 */
felem_diff_128_64(tmp, ftmp3);
/* tmp[i] < 17*2^120 + 2^63 */
felem_reduce(ftmp4, tmp);
x_equal = felem_is_zero(ftmp4);
/* z_out = ftmp5 * h */
felem_mul(tmp, ftmp5, ftmp4);
felem_reduce(z_out, tmp);
/* ftmp = z1 * z1z1 */
felem_mul(tmp, ftmp, z1);
felem_reduce(ftmp, tmp);
/* s2 = tmp = y2 * z1**3 */
felem_mul(tmp, y2, ftmp);
/* tmp[i] < 17*2^120 */
/* r = ftmp5 = (s2 - s1)*2 */
felem_diff_128_64(tmp, ftmp6);
/* tmp[i] < 17*2^120 + 2^63 */
felem_reduce(ftmp5, tmp);
y_equal = felem_is_zero(ftmp5);
felem_scalar64(ftmp5, 2);
/* ftmp5[i] < 2^61 */
if (x_equal && y_equal && !z1_is_zero && !z2_is_zero) {
point_double(x3, y3, z3, x1, y1, z1);
return;
}
/* I = ftmp = (2h)**2 */
felem_assign(ftmp, ftmp4);
felem_scalar64(ftmp, 2);
/* ftmp[i] < 2^61 */
felem_square(tmp, ftmp);
/* tmp[i] < 17*2^122 */
felem_reduce(ftmp, tmp);
/* J = ftmp2 = h * I */
felem_mul(tmp, ftmp4, ftmp);
felem_reduce(ftmp2, tmp);
/* V = ftmp4 = U1 * I */
felem_mul(tmp, ftmp3, ftmp);
felem_reduce(ftmp4, tmp);
/* x_out = r**2 - J - 2V */
felem_square(tmp, ftmp5);
/* tmp[i] < 17*2^122 */
felem_diff_128_64(tmp, ftmp2);
/* tmp[i] < 17*2^122 + 2^63 */
felem_assign(ftmp3, ftmp4);
felem_scalar64(ftmp4, 2);
/* ftmp4[i] < 2^61 */
felem_diff_128_64(tmp, ftmp4);
/* tmp[i] < 17*2^122 + 2^64 */
felem_reduce(x_out, tmp);
/* y_out = r(V-x_out) - 2 * s1 * J */
felem_diff64(ftmp3, x_out);
/*
* ftmp3[i] < 2^60 + 2^60 = 2^61
*/
felem_mul(tmp, ftmp5, ftmp3);
/* tmp[i] < 17*2^122 */
felem_mul(tmp2, ftmp6, ftmp2);
/* tmp2[i] < 17*2^120 */
felem_scalar128(tmp2, 2);
/* tmp2[i] < 17*2^121 */
felem_diff128(tmp, tmp2);
/*-
* tmp[i] < 2^127 - 2^69 + 17*2^122
* = 2^126 - 2^122 - 2^6 - 2^2 - 1
* < 2^127
*/
felem_reduce(y_out, tmp);
copy_conditional(x_out, x2, z1_is_zero);
copy_conditional(x_out, x1, z2_is_zero);
copy_conditional(y_out, y2, z1_is_zero);
copy_conditional(y_out, y1, z2_is_zero);
copy_conditional(z_out, z2, z1_is_zero);
copy_conditional(z_out, z1, z2_is_zero);
felem_assign(x3, x_out);
felem_assign(y3, y_out);
felem_assign(z3, z_out);
}
/*-
* Base point pre computation
* --------------------------
*
* Two different sorts of precomputed tables are used in the following code.
* Each contain various points on the curve, where each point is three field
* elements (x, y, z).
*
* For the base point table, z is usually 1 (0 for the point at infinity).
* This table has 16 elements:
* index | bits | point
* ------+---------+------------------------------
* 0 | 0 0 0 0 | 0G
* 1 | 0 0 0 1 | 1G
* 2 | 0 0 1 0 | 2^130G
* 3 | 0 0 1 1 | (2^130 + 1)G
* 4 | 0 1 0 0 | 2^260G
* 5 | 0 1 0 1 | (2^260 + 1)G
* 6 | 0 1 1 0 | (2^260 + 2^130)G
* 7 | 0 1 1 1 | (2^260 + 2^130 + 1)G
* 8 | 1 0 0 0 | 2^390G
* 9 | 1 0 0 1 | (2^390 + 1)G
* 10 | 1 0 1 0 | (2^390 + 2^130)G
* 11 | 1 0 1 1 | (2^390 + 2^130 + 1)G
* 12 | 1 1 0 0 | (2^390 + 2^260)G
* 13 | 1 1 0 1 | (2^390 + 2^260 + 1)G
* 14 | 1 1 1 0 | (2^390 + 2^260 + 2^130)G
* 15 | 1 1 1 1 | (2^390 + 2^260 + 2^130 + 1)G
*
* The reason for this is so that we can clock bits into four different
* locations when doing simple scalar multiplies against the base point.
*
* Tables for other points have table[i] = iG for i in 0 .. 16. */
/* gmul is the table of precomputed base points */
static const felem gmul[16][3] = { {{0, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 0}},
{{0x017e7e31c2e5bd66, 0x022cf0615a90a6fe, 0x00127a2ffa8de334,
0x01dfbf9d64a3f877, 0x006b4d3dbaa14b5e, 0x014fed487e0a2bd8,
0x015b4429c6481390, 0x03a73678fb2d988e, 0x00c6858e06b70404},
{0x00be94769fd16650, 0x031c21a89cb09022, 0x039013fad0761353,
0x02657bd099031542, 0x03273e662c97ee72, 0x01e6d11a05ebef45,
0x03d1bd998f544495, 0x03001172297ed0b1, 0x011839296a789a3b},
{1, 0, 0, 0, 0, 0, 0, 0, 0}},
{{0x0373faacbc875bae, 0x00f325023721c671, 0x00f666fd3dbde5ad,
0x01a6932363f88ea7, 0x01fc6d9e13f9c47b, 0x03bcbffc2bbf734e,
0x013ee3c3647f3a92, 0x029409fefe75d07d, 0x00ef9199963d85e5},
{0x011173743ad5b178, 0x02499c7c21bf7d46, 0x035beaeabb8b1a58,
0x00f989c4752ea0a3, 0x0101e1de48a9c1a3, 0x01a20076be28ba6c,
0x02f8052e5eb2de95, 0x01bfe8f82dea117c, 0x0160074d3c36ddb7},
{1, 0, 0, 0, 0, 0, 0, 0, 0}},
{{0x012f3fc373393b3b, 0x03d3d6172f1419fa, 0x02adc943c0b86873,
0x00d475584177952b, 0x012a4d1673750ee2, 0x00512517a0f13b0c,
0x02b184671a7b1734, 0x0315b84236f1a50a, 0x00a4afc472edbdb9},
{0x00152a7077f385c4, 0x03044007d8d1c2ee, 0x0065829d61d52b52,
0x00494ff6b6631d0d, 0x00a11d94d5f06bcf, 0x02d2f89474d9282e,
0x0241c5727c06eeb9, 0x0386928710fbdb9d, 0x01f883f727b0dfbe},
{1, 0, 0, 0, 0, 0, 0, 0, 0}},
{{0x019b0c3c9185544d, 0x006243a37c9d97db, 0x02ee3cbe030a2ad2,
0x00cfdd946bb51e0d, 0x0271c00932606b91, 0x03f817d1ec68c561,
0x03f37009806a369c, 0x03c1f30baf184fd5, 0x01091022d6d2f065},
{0x0292c583514c45ed, 0x0316fca51f9a286c, 0x00300af507c1489a,
0x0295f69008298cf1, 0x02c0ed8274943d7b, 0x016509b9b47a431e,
0x02bc9de9634868ce, 0x005b34929bffcb09, 0x000c1a0121681524},
{1, 0, 0, 0, 0, 0, 0, 0, 0}},
{{0x0286abc0292fb9f2, 0x02665eee9805b3f7, 0x01ed7455f17f26d6,
0x0346355b83175d13, 0x006284944cd0a097, 0x0191895bcdec5e51,
0x02e288370afda7d9, 0x03b22312bfefa67a, 0x01d104d3fc0613fe},
{0x0092421a12f7e47f, 0x0077a83fa373c501, 0x03bd25c5f696bd0d,
0x035c41e4d5459761, 0x01ca0d1742b24f53, 0x00aaab27863a509c,
0x018b6de47df73917, 0x025c0b771705cd01, 0x01fd51d566d760a7},
{1, 0, 0, 0, 0, 0, 0, 0, 0}},
{{0x01dd92ff6b0d1dbd, 0x039c5e2e8f8afa69, 0x0261ed13242c3b27,
0x0382c6e67026e6a0, 0x01d60b10be2089f9, 0x03c15f3dce86723f,
0x03c764a32d2a062d, 0x017307eac0fad056, 0x018207c0b96c5256},
{0x0196a16d60e13154, 0x03e6ce74c0267030, 0x00ddbf2b4e52a5aa,
0x012738241bbf31c8, 0x00ebe8dc04685a28, 0x024c2ad6d380d4a2,
0x035ee062a6e62d0e, 0x0029ed74af7d3a0f, 0x00eef32aec142ebd},
{1, 0, 0, 0, 0, 0, 0, 0, 0}},
{{0x00c31ec398993b39, 0x03a9f45bcda68253, 0x00ac733c24c70890,
0x00872b111401ff01, 0x01d178c23195eafb, 0x03bca2c816b87f74,
0x0261a9af46fbad7a, 0x0324b2a8dd3d28f9, 0x00918121d8f24e23},
{0x032bc8c1ca983cd7, 0x00d869dfb08fc8c6, 0x01693cb61fce1516,
0x012a5ea68f4e88a8, 0x010869cab88d7ae3, 0x009081ad277ceee1,
0x033a77166d064cdc, 0x03955235a1fb3a95, 0x01251a4a9b25b65e},
{1, 0, 0, 0, 0, 0, 0, 0, 0}},
{{0x00148a3a1b27f40b, 0x0123186df1b31fdc, 0x00026e7beaad34ce,
0x01db446ac1d3dbba, 0x0299c1a33437eaec, 0x024540610183cbb7,
0x0173bb0e9ce92e46, 0x02b937e43921214b, 0x01ab0436a9bf01b5},
{0x0383381640d46948, 0x008dacbf0e7f330f, 0x03602122bcc3f318,
0x01ee596b200620d6, 0x03bd0585fda430b3, 0x014aed77fd123a83,
0x005ace749e52f742, 0x0390fe041da2b842, 0x0189a8ceb3299242},
{1, 0, 0, 0, 0, 0, 0, 0, 0}},
{{0x012a19d6b3282473, 0x00c0915918b423ce, 0x023a954eb94405ae,
0x00529f692be26158, 0x0289fa1b6fa4b2aa, 0x0198ae4ceea346ef,
0x0047d8cdfbdedd49, 0x00cc8c8953f0f6b8, 0x001424abbff49203},
{0x0256732a1115a03a, 0x0351bc38665c6733, 0x03f7b950fb4a6447,
0x000afffa94c22155, 0x025763d0a4dab540, 0x000511e92d4fc283,
0x030a7e9eda0ee96c, 0x004c3cd93a28bf0a, 0x017edb3a8719217f},
{1, 0, 0, 0, 0, 0, 0, 0, 0}},
{{0x011de5675a88e673, 0x031d7d0f5e567fbe, 0x0016b2062c970ae5,
0x03f4a2be49d90aa7, 0x03cef0bd13822866, 0x03f0923dcf774a6c,
0x0284bebc4f322f72, 0x016ab2645302bb2c, 0x01793f95dace0e2a},
{0x010646e13527a28f, 0x01ca1babd59dc5e7, 0x01afedfd9a5595df,
0x01f15785212ea6b1, 0x0324e5d64f6ae3f4, 0x02d680f526d00645,
0x0127920fadf627a7, 0x03b383f75df4f684, 0x0089e0057e783b0a},
{1, 0, 0, 0, 0, 0, 0, 0, 0}},
{{0x00f334b9eb3c26c6, 0x0298fdaa98568dce, 0x01c2d24843a82292,
0x020bcb24fa1b0711, 0x02cbdb3d2b1875e6, 0x0014907598f89422,
0x03abe3aa43b26664, 0x02cbf47f720bc168, 0x0133b5e73014b79b},
{0x034aab5dab05779d, 0x00cdc5d71fee9abb, 0x0399f16bd4bd9d30,
0x03582fa592d82647, 0x02be1cdfb775b0e9, 0x0034f7cea32e94cb,
0x0335a7f08f56f286, 0x03b707e9565d1c8b, 0x0015c946ea5b614f},
{1, 0, 0, 0, 0, 0, 0, 0, 0}},
{{0x024676f6cff72255, 0x00d14625cac96378, 0x00532b6008bc3767,
0x01fc16721b985322, 0x023355ea1b091668, 0x029de7afdc0317c3,
0x02fc8a7ca2da037c, 0x02de1217d74a6f30, 0x013f7173175b73bf},
{0x0344913f441490b5, 0x0200f9e272b61eca, 0x0258a246b1dd55d2,
0x03753db9ea496f36, 0x025e02937a09c5ef, 0x030cbd3d14012692,
0x01793a67e70dc72a, 0x03ec1d37048a662e, 0x006550f700c32a8d},
{1, 0, 0, 0, 0, 0, 0, 0, 0}},
{{0x00d3f48a347eba27, 0x008e636649b61bd8, 0x00d3b93716778fb3,
0x004d1915757bd209, 0x019d5311a3da44e0, 0x016d1afcbbe6aade,
0x0241bf5f73265616, 0x0384672e5d50d39b, 0x005009fee522b684},
{0x029b4fab064435fe, 0x018868ee095bbb07, 0x01ea3d6936cc92b8,
0x000608b00f78a2f3, 0x02db911073d1c20f, 0x018205938470100a,
0x01f1e4964cbe6ff2, 0x021a19a29eed4663, 0x01414485f42afa81},
{1, 0, 0, 0, 0, 0, 0, 0, 0}},
{{0x01612b3a17f63e34, 0x03813992885428e6, 0x022b3c215b5a9608,
0x029b4057e19f2fcb, 0x0384059a587af7e6, 0x02d6400ace6fe610,
0x029354d896e8e331, 0x00c047ee6dfba65e, 0x0037720542e9d49d},
{0x02ce9eed7c5e9278, 0x0374ed703e79643b, 0x01316c54c4072006,
0x005aaa09054b2ee8, 0x002824000c840d57, 0x03d4eba24771ed86,
0x0189c50aabc3bdae, 0x0338c01541e15510, 0x00466d56e38eed42},
{1, 0, 0, 0, 0, 0, 0, 0, 0}},
{{0x007efd8330ad8bd6, 0x02465ed48047710b, 0x0034c6606b215e0c,
0x016ae30c53cbf839, 0x01fa17bd37161216, 0x018ead4e61ce8ab9,
0x005482ed5f5dee46, 0x037543755bba1d7f, 0x005e5ac7e70a9d0f},
{0x0117e1bb2fdcb2a2, 0x03deea36249f40c4, 0x028d09b4a6246cb7,
0x03524b8855bcf756, 0x023d7d109d5ceb58, 0x0178e43e3223ef9c,
0x0154536a0c6e966a, 0x037964d1286ee9fe, 0x0199bcd90e125055},
{1, 0, 0, 0, 0, 0, 0, 0, 0}}
};
/*
* select_point selects the |idx|th point from a precomputation table and
* copies it to out.
*/
/* pre_comp below is of the size provided in |size| */
static void select_point(const limb idx, unsigned int size,
const felem pre_comp[][3], felem out[3])
{
unsigned i, j;
limb *outlimbs = &out[0][0];
memset(outlimbs, 0, 3 * sizeof(felem));
for (i = 0; i < size; i++) {
const limb *inlimbs = &pre_comp[i][0][0];
limb mask = i ^ idx;
mask |= mask >> 4;
mask |= mask >> 2;
mask |= mask >> 1;
mask &= 1;
mask--;
for (j = 0; j < NLIMBS * 3; j++)
outlimbs[j] |= inlimbs[j] & mask;
}
}
/* get_bit returns the |i|th bit in |in| */
static char get_bit(const felem_bytearray in, int i)
{
if (i < 0)
return 0;
return (in[i >> 3] >> (i & 7)) & 1;
}
/*
* Interleaved point multiplication using precomputed point multiples: The
* small point multiples 0*P, 1*P, ..., 16*P are in pre_comp[], the scalars
* in scalars[]. If g_scalar is non-NULL, we also add this multiple of the
* generator, using certain (large) precomputed multiples in g_pre_comp.
* Output point (X, Y, Z) is stored in x_out, y_out, z_out
*/
static void batch_mul(felem x_out, felem y_out, felem z_out,
const felem_bytearray scalars[],
const unsigned num_points, const u8 *g_scalar,
const int mixed, const felem pre_comp[][17][3],
const felem g_pre_comp[16][3])
{
int i, skip;
unsigned num, gen_mul = (g_scalar != NULL);
felem nq[3], tmp[4];
limb bits;
u8 sign, digit;
/* set nq to the point at infinity */
memset(nq, 0, 3 * sizeof(felem));
/*
* Loop over all scalars msb-to-lsb, interleaving additions of multiples
* of the generator (last quarter of rounds) and additions of other
* points multiples (every 5th round).
*/
skip = 1; /* save two point operations in the first
* round */
for (i = (num_points ? 520 : 130); i >= 0; --i) {
/* double */
if (!skip)
point_double(nq[0], nq[1], nq[2], nq[0], nq[1], nq[2]);
/* add multiples of the generator */
if (gen_mul && (i <= 130)) {
bits = get_bit(g_scalar, i + 390) << 3;
if (i < 130) {
bits |= get_bit(g_scalar, i + 260) << 2;
bits |= get_bit(g_scalar, i + 130) << 1;
bits |= get_bit(g_scalar, i);
}
/* select the point to add, in constant time */
select_point(bits, 16, g_pre_comp, tmp);
if (!skip) {
/* The 1 argument below is for "mixed" */
point_add(nq[0], nq[1], nq[2],
nq[0], nq[1], nq[2], 1, tmp[0], tmp[1], tmp[2]);
} else {
memcpy(nq, tmp, 3 * sizeof(felem));
skip = 0;
}
}
/* do other additions every 5 doublings */
if (num_points && (i % 5 == 0)) {
/* loop over all scalars */
for (num = 0; num < num_points; ++num) {
bits = get_bit(scalars[num], i + 4) << 5;
bits |= get_bit(scalars[num], i + 3) << 4;
bits |= get_bit(scalars[num], i + 2) << 3;
bits |= get_bit(scalars[num], i + 1) << 2;
bits |= get_bit(scalars[num], i) << 1;
bits |= get_bit(scalars[num], i - 1);
ec_GFp_nistp_recode_scalar_bits(&sign, &digit, bits);
/*
* select the point to add or subtract, in constant time
*/
select_point(digit, 17, pre_comp[num], tmp);
felem_neg(tmp[3], tmp[1]); /* (X, -Y, Z) is the negative
* point */
copy_conditional(tmp[1], tmp[3], (-(limb) sign));
if (!skip) {
point_add(nq[0], nq[1], nq[2],
nq[0], nq[1], nq[2],
mixed, tmp[0], tmp[1], tmp[2]);
} else {
memcpy(nq, tmp, 3 * sizeof(felem));
skip = 0;
}
}
}
}
felem_assign(x_out, nq[0]);
felem_assign(y_out, nq[1]);
felem_assign(z_out, nq[2]);
}
/* Precomputation for the group generator. */
typedef struct {
felem g_pre_comp[16][3];
int references;
} NISTP521_PRE_COMP;
const EC_METHOD *EC_GFp_nistp521_method(void)
{
static const EC_METHOD ret = {
EC_FLAGS_DEFAULT_OCT,
NID_X9_62_prime_field,
ec_GFp_nistp521_group_init,
ec_GFp_simple_group_finish,
ec_GFp_simple_group_clear_finish,
ec_GFp_nist_group_copy,
ec_GFp_nistp521_group_set_curve,
ec_GFp_simple_group_get_curve,
ec_GFp_simple_group_get_degree,
ec_GFp_simple_group_check_discriminant,
ec_GFp_simple_point_init,
ec_GFp_simple_point_finish,
ec_GFp_simple_point_clear_finish,
ec_GFp_simple_point_copy,
ec_GFp_simple_point_set_to_infinity,
ec_GFp_simple_set_Jprojective_coordinates_GFp,
ec_GFp_simple_get_Jprojective_coordinates_GFp,
ec_GFp_simple_point_set_affine_coordinates,
ec_GFp_nistp521_point_get_affine_coordinates,
0 /* point_set_compressed_coordinates */ ,
0 /* point2oct */ ,
0 /* oct2point */ ,
ec_GFp_simple_add,
ec_GFp_simple_dbl,
ec_GFp_simple_invert,
ec_GFp_simple_is_at_infinity,
ec_GFp_simple_is_on_curve,
ec_GFp_simple_cmp,
ec_GFp_simple_make_affine,
ec_GFp_simple_points_make_affine,
ec_GFp_nistp521_points_mul,
ec_GFp_nistp521_precompute_mult,
ec_GFp_nistp521_have_precompute_mult,
ec_GFp_nist_field_mul,
ec_GFp_nist_field_sqr,
0 /* field_div */ ,
0 /* field_encode */ ,
0 /* field_decode */ ,
0 /* field_set_to_one */
};
return &ret;
}
/******************************************************************************/
/*
* FUNCTIONS TO MANAGE PRECOMPUTATION
*/
static NISTP521_PRE_COMP *nistp521_pre_comp_new()
{
NISTP521_PRE_COMP *ret = NULL;
ret = (NISTP521_PRE_COMP *) OPENSSL_malloc(sizeof(NISTP521_PRE_COMP));
if (!ret) {
ECerr(EC_F_NISTP521_PRE_COMP_NEW, ERR_R_MALLOC_FAILURE);
return ret;
}
memset(ret->g_pre_comp, 0, sizeof(ret->g_pre_comp));
ret->references = 1;
return ret;
}
static void *nistp521_pre_comp_dup(void *src_)
{
NISTP521_PRE_COMP *src = src_;
/* no need to actually copy, these objects never change! */
CRYPTO_add(&src->references, 1, CRYPTO_LOCK_EC_PRE_COMP);
return src_;
}
static void nistp521_pre_comp_free(void *pre_)
{
int i;
NISTP521_PRE_COMP *pre = pre_;
if (!pre)
return;
i = CRYPTO_add(&pre->references, -1, CRYPTO_LOCK_EC_PRE_COMP);
if (i > 0)
return;
OPENSSL_free(pre);
}
static void nistp521_pre_comp_clear_free(void *pre_)
{
int i;
NISTP521_PRE_COMP *pre = pre_;
if (!pre)
return;
i = CRYPTO_add(&pre->references, -1, CRYPTO_LOCK_EC_PRE_COMP);
if (i > 0)
return;
OPENSSL_cleanse(pre, sizeof(*pre));
OPENSSL_free(pre);
}
/******************************************************************************/
/*
* OPENSSL EC_METHOD FUNCTIONS
*/
int ec_GFp_nistp521_group_init(EC_GROUP *group)
{
int ret;
ret = ec_GFp_simple_group_init(group);
group->a_is_minus3 = 1;
return ret;
}
int ec_GFp_nistp521_group_set_curve(EC_GROUP *group, const BIGNUM *p,
const BIGNUM *a, const BIGNUM *b,
BN_CTX *ctx)
{
int ret = 0;
BN_CTX *new_ctx = NULL;
BIGNUM *curve_p, *curve_a, *curve_b;
if (ctx == NULL)
if ((ctx = new_ctx = BN_CTX_new()) == NULL)
return 0;
BN_CTX_start(ctx);
if (((curve_p = BN_CTX_get(ctx)) == NULL) ||
((curve_a = BN_CTX_get(ctx)) == NULL) ||
((curve_b = BN_CTX_get(ctx)) == NULL))
goto err;
BN_bin2bn(nistp521_curve_params[0], sizeof(felem_bytearray), curve_p);
BN_bin2bn(nistp521_curve_params[1], sizeof(felem_bytearray), curve_a);
BN_bin2bn(nistp521_curve_params[2], sizeof(felem_bytearray), curve_b);
if ((BN_cmp(curve_p, p)) || (BN_cmp(curve_a, a)) || (BN_cmp(curve_b, b))) {
ECerr(EC_F_EC_GFP_NISTP521_GROUP_SET_CURVE,
EC_R_WRONG_CURVE_PARAMETERS);
goto err;
}
group->field_mod_func = BN_nist_mod_521;
ret = ec_GFp_simple_group_set_curve(group, p, a, b, ctx);
err:
BN_CTX_end(ctx);
if (new_ctx != NULL)
BN_CTX_free(new_ctx);
return ret;
}
/*
* Takes the Jacobian coordinates (X, Y, Z) of a point and returns (X', Y') =
* (X/Z^2, Y/Z^3)
*/
int ec_GFp_nistp521_point_get_affine_coordinates(const EC_GROUP *group,
const EC_POINT *point,
BIGNUM *x, BIGNUM *y,
BN_CTX *ctx)
{
felem z1, z2, x_in, y_in, x_out, y_out;
largefelem tmp;
if (EC_POINT_is_at_infinity(group, point)) {
ECerr(EC_F_EC_GFP_NISTP521_POINT_GET_AFFINE_COORDINATES,
EC_R_POINT_AT_INFINITY);
return 0;
}
if ((!BN_to_felem(x_in, &point->X)) || (!BN_to_felem(y_in, &point->Y)) ||
(!BN_to_felem(z1, &point->Z)))
return 0;
felem_inv(z2, z1);
felem_square(tmp, z2);
felem_reduce(z1, tmp);
felem_mul(tmp, x_in, z1);
felem_reduce(x_in, tmp);
felem_contract(x_out, x_in);
if (x != NULL) {
if (!felem_to_BN(x, x_out)) {
ECerr(EC_F_EC_GFP_NISTP521_POINT_GET_AFFINE_COORDINATES,
ERR_R_BN_LIB);
return 0;
}
}
felem_mul(tmp, z1, z2);
felem_reduce(z1, tmp);
felem_mul(tmp, y_in, z1);
felem_reduce(y_in, tmp);
felem_contract(y_out, y_in);
if (y != NULL) {
if (!felem_to_BN(y, y_out)) {
ECerr(EC_F_EC_GFP_NISTP521_POINT_GET_AFFINE_COORDINATES,
ERR_R_BN_LIB);
return 0;
}
}
return 1;
}
/* points below is of size |num|, and tmp_felems is of size |num+1/ */
static void make_points_affine(size_t num, felem points[][3],
felem tmp_felems[])
{
/*
* Runs in constant time, unless an input is the point at infinity (which
* normally shouldn't happen).
*/
ec_GFp_nistp_points_make_affine_internal(num,
points,
sizeof(felem),
tmp_felems,
(void (*)(void *))felem_one,
felem_is_zero_int,
(void (*)(void *, const void *))
felem_assign,
(void (*)(void *, const void *))
felem_square_reduce, (void (*)
(void *,
const void
*,
const void
*))
felem_mul_reduce,
(void (*)(void *, const void *))
felem_inv,
(void (*)(void *, const void *))
felem_contract);
}
/*
* Computes scalar*generator + \sum scalars[i]*points[i], ignoring NULL
* values Result is stored in r (r can equal one of the inputs).
*/
int ec_GFp_nistp521_points_mul(const EC_GROUP *group, EC_POINT *r,
const BIGNUM *scalar, size_t num,
const EC_POINT *points[],
const BIGNUM *scalars[], BN_CTX *ctx)
{
int ret = 0;
int j;
int mixed = 0;
BN_CTX *new_ctx = NULL;
BIGNUM *x, *y, *z, *tmp_scalar;
felem_bytearray g_secret;
felem_bytearray *secrets = NULL;
felem(*pre_comp)[17][3] = NULL;
felem *tmp_felems = NULL;
felem_bytearray tmp;
unsigned i, num_bytes;
int have_pre_comp = 0;
size_t num_points = num;
felem x_in, y_in, z_in, x_out, y_out, z_out;
NISTP521_PRE_COMP *pre = NULL;
felem(*g_pre_comp)[3] = NULL;
EC_POINT *generator = NULL;
const EC_POINT *p = NULL;
const BIGNUM *p_scalar = NULL;
if (ctx == NULL)
if ((ctx = new_ctx = BN_CTX_new()) == NULL)
return 0;
BN_CTX_start(ctx);
if (((x = BN_CTX_get(ctx)) == NULL) ||
((y = BN_CTX_get(ctx)) == NULL) ||
((z = BN_CTX_get(ctx)) == NULL) ||
((tmp_scalar = BN_CTX_get(ctx)) == NULL))
goto err;
if (scalar != NULL) {
pre = EC_EX_DATA_get_data(group->extra_data,
nistp521_pre_comp_dup,
nistp521_pre_comp_free,
nistp521_pre_comp_clear_free);
if (pre)
/* we have precomputation, try to use it */
g_pre_comp = &pre->g_pre_comp[0];
else
/* try to use the standard precomputation */
g_pre_comp = (felem(*)[3]) gmul;
generator = EC_POINT_new(group);
if (generator == NULL)
goto err;
/* get the generator from precomputation */
if (!felem_to_BN(x, g_pre_comp[1][0]) ||
!felem_to_BN(y, g_pre_comp[1][1]) ||
!felem_to_BN(z, g_pre_comp[1][2])) {
ECerr(EC_F_EC_GFP_NISTP521_POINTS_MUL, ERR_R_BN_LIB);
goto err;
}
if (!EC_POINT_set_Jprojective_coordinates_GFp(group,
generator, x, y, z,
ctx))
goto err;
if (0 == EC_POINT_cmp(group, generator, group->generator, ctx))
/* precomputation matches generator */
have_pre_comp = 1;
else
/*
* we don't have valid precomputation: treat the generator as a
* random point
*/
num_points++;
}
if (num_points > 0) {
if (num_points >= 2) {
/*
* unless we precompute multiples for just one point, converting
* those into affine form is time well spent
*/
mixed = 1;
}
secrets = OPENSSL_malloc(num_points * sizeof(felem_bytearray));
pre_comp = OPENSSL_malloc(num_points * 17 * 3 * sizeof(felem));
if (mixed)
tmp_felems =
OPENSSL_malloc((num_points * 17 + 1) * sizeof(felem));
if ((secrets == NULL) || (pre_comp == NULL)
|| (mixed && (tmp_felems == NULL))) {
ECerr(EC_F_EC_GFP_NISTP521_POINTS_MUL, ERR_R_MALLOC_FAILURE);
goto err;
}
/*
* we treat NULL scalars as 0, and NULL points as points at infinity,
* i.e., they contribute nothing to the linear combination
*/
memset(secrets, 0, num_points * sizeof(felem_bytearray));
memset(pre_comp, 0, num_points * 17 * 3 * sizeof(felem));
for (i = 0; i < num_points; ++i) {
if (i == num)
/*
* we didn't have a valid precomputation, so we pick the
* generator
*/
{
p = EC_GROUP_get0_generator(group);
p_scalar = scalar;
} else
/* the i^th point */
{
p = points[i];
p_scalar = scalars[i];
}
if ((p_scalar != NULL) && (p != NULL)) {
/* reduce scalar to 0 <= scalar < 2^521 */
if ((BN_num_bits(p_scalar) > 521)
|| (BN_is_negative(p_scalar))) {
/*
* this is an unusual input, and we don't guarantee
* constant-timeness
*/
if (!BN_nnmod(tmp_scalar, p_scalar, &group->order, ctx)) {
ECerr(EC_F_EC_GFP_NISTP521_POINTS_MUL, ERR_R_BN_LIB);
goto err;
}
num_bytes = BN_bn2bin(tmp_scalar, tmp);
} else
num_bytes = BN_bn2bin(p_scalar, tmp);
flip_endian(secrets[i], tmp, num_bytes);
/* precompute multiples */
if ((!BN_to_felem(x_out, &p->X)) ||
(!BN_to_felem(y_out, &p->Y)) ||
(!BN_to_felem(z_out, &p->Z)))
goto err;
memcpy(pre_comp[i][1][0], x_out, sizeof(felem));
memcpy(pre_comp[i][1][1], y_out, sizeof(felem));
memcpy(pre_comp[i][1][2], z_out, sizeof(felem));
for (j = 2; j <= 16; ++j) {
if (j & 1) {
point_add(pre_comp[i][j][0], pre_comp[i][j][1],
pre_comp[i][j][2], pre_comp[i][1][0],
pre_comp[i][1][1], pre_comp[i][1][2], 0,
pre_comp[i][j - 1][0],
pre_comp[i][j - 1][1],
pre_comp[i][j - 1][2]);
} else {
point_double(pre_comp[i][j][0], pre_comp[i][j][1],
pre_comp[i][j][2], pre_comp[i][j / 2][0],
pre_comp[i][j / 2][1],
pre_comp[i][j / 2][2]);
}
}
}
}
if (mixed)
make_points_affine(num_points * 17, pre_comp[0], tmp_felems);
}
/* the scalar for the generator */
if ((scalar != NULL) && (have_pre_comp)) {
memset(g_secret, 0, sizeof(g_secret));
/* reduce scalar to 0 <= scalar < 2^521 */
if ((BN_num_bits(scalar) > 521) || (BN_is_negative(scalar))) {
/*
* this is an unusual input, and we don't guarantee
* constant-timeness
*/
if (!BN_nnmod(tmp_scalar, scalar, &group->order, ctx)) {
ECerr(EC_F_EC_GFP_NISTP521_POINTS_MUL, ERR_R_BN_LIB);
goto err;
}
num_bytes = BN_bn2bin(tmp_scalar, tmp);
} else
num_bytes = BN_bn2bin(scalar, tmp);
flip_endian(g_secret, tmp, num_bytes);
/* do the multiplication with generator precomputation */
batch_mul(x_out, y_out, z_out,
(const felem_bytearray(*))secrets, num_points,
g_secret,
mixed, (const felem(*)[17][3])pre_comp,
(const felem(*)[3])g_pre_comp);
} else
/* do the multiplication without generator precomputation */
batch_mul(x_out, y_out, z_out,
(const felem_bytearray(*))secrets, num_points,
NULL, mixed, (const felem(*)[17][3])pre_comp, NULL);
/* reduce the output to its unique minimal representation */
felem_contract(x_in, x_out);
felem_contract(y_in, y_out);
felem_contract(z_in, z_out);
if ((!felem_to_BN(x, x_in)) || (!felem_to_BN(y, y_in)) ||
(!felem_to_BN(z, z_in))) {
ECerr(EC_F_EC_GFP_NISTP521_POINTS_MUL, ERR_R_BN_LIB);
goto err;
}
ret = EC_POINT_set_Jprojective_coordinates_GFp(group, r, x, y, z, ctx);
err:
BN_CTX_end(ctx);
if (generator != NULL)
EC_POINT_free(generator);
if (new_ctx != NULL)
BN_CTX_free(new_ctx);
if (secrets != NULL)
OPENSSL_free(secrets);
if (pre_comp != NULL)
OPENSSL_free(pre_comp);
if (tmp_felems != NULL)
OPENSSL_free(tmp_felems);
return ret;
}
int ec_GFp_nistp521_precompute_mult(EC_GROUP *group, BN_CTX *ctx)
{
int ret = 0;
NISTP521_PRE_COMP *pre = NULL;
int i, j;
BN_CTX *new_ctx = NULL;
BIGNUM *x, *y;
EC_POINT *generator = NULL;
felem tmp_felems[16];
/* throw away old precomputation */
EC_EX_DATA_free_data(&group->extra_data, nistp521_pre_comp_dup,
nistp521_pre_comp_free,
nistp521_pre_comp_clear_free);
if (ctx == NULL)
if ((ctx = new_ctx = BN_CTX_new()) == NULL)
return 0;
BN_CTX_start(ctx);
if (((x = BN_CTX_get(ctx)) == NULL) || ((y = BN_CTX_get(ctx)) == NULL))
goto err;
/* get the generator */
if (group->generator == NULL)
goto err;
generator = EC_POINT_new(group);
if (generator == NULL)
goto err;
BN_bin2bn(nistp521_curve_params[3], sizeof(felem_bytearray), x);
BN_bin2bn(nistp521_curve_params[4], sizeof(felem_bytearray), y);
if (!EC_POINT_set_affine_coordinates_GFp(group, generator, x, y, ctx))
goto err;
if ((pre = nistp521_pre_comp_new()) == NULL)
goto err;
/*
* if the generator is the standard one, use built-in precomputation
*/
if (0 == EC_POINT_cmp(group, generator, group->generator, ctx)) {
memcpy(pre->g_pre_comp, gmul, sizeof(pre->g_pre_comp));
goto done;
}
if ((!BN_to_felem(pre->g_pre_comp[1][0], &group->generator->X)) ||
(!BN_to_felem(pre->g_pre_comp[1][1], &group->generator->Y)) ||
(!BN_to_felem(pre->g_pre_comp[1][2], &group->generator->Z)))
goto err;
/* compute 2^130*G, 2^260*G, 2^390*G */
for (i = 1; i <= 4; i <<= 1) {
point_double(pre->g_pre_comp[2 * i][0], pre->g_pre_comp[2 * i][1],
pre->g_pre_comp[2 * i][2], pre->g_pre_comp[i][0],
pre->g_pre_comp[i][1], pre->g_pre_comp[i][2]);
for (j = 0; j < 129; ++j) {
point_double(pre->g_pre_comp[2 * i][0],
pre->g_pre_comp[2 * i][1],
pre->g_pre_comp[2 * i][2],
pre->g_pre_comp[2 * i][0],
pre->g_pre_comp[2 * i][1],
pre->g_pre_comp[2 * i][2]);
}
}
/* g_pre_comp[0] is the point at infinity */
memset(pre->g_pre_comp[0], 0, sizeof(pre->g_pre_comp[0]));
/* the remaining multiples */
/* 2^130*G + 2^260*G */
point_add(pre->g_pre_comp[6][0], pre->g_pre_comp[6][1],
pre->g_pre_comp[6][2], pre->g_pre_comp[4][0],
pre->g_pre_comp[4][1], pre->g_pre_comp[4][2],
0, pre->g_pre_comp[2][0], pre->g_pre_comp[2][1],
pre->g_pre_comp[2][2]);
/* 2^130*G + 2^390*G */
point_add(pre->g_pre_comp[10][0], pre->g_pre_comp[10][1],
pre->g_pre_comp[10][2], pre->g_pre_comp[8][0],
pre->g_pre_comp[8][1], pre->g_pre_comp[8][2],
0, pre->g_pre_comp[2][0], pre->g_pre_comp[2][1],
pre->g_pre_comp[2][2]);
/* 2^260*G + 2^390*G */
point_add(pre->g_pre_comp[12][0], pre->g_pre_comp[12][1],
pre->g_pre_comp[12][2], pre->g_pre_comp[8][0],
pre->g_pre_comp[8][1], pre->g_pre_comp[8][2],
0, pre->g_pre_comp[4][0], pre->g_pre_comp[4][1],
pre->g_pre_comp[4][2]);
/* 2^130*G + 2^260*G + 2^390*G */
point_add(pre->g_pre_comp[14][0], pre->g_pre_comp[14][1],
pre->g_pre_comp[14][2], pre->g_pre_comp[12][0],
pre->g_pre_comp[12][1], pre->g_pre_comp[12][2],
0, pre->g_pre_comp[2][0], pre->g_pre_comp[2][1],
pre->g_pre_comp[2][2]);
for (i = 1; i < 8; ++i) {
/* odd multiples: add G */
point_add(pre->g_pre_comp[2 * i + 1][0],
pre->g_pre_comp[2 * i + 1][1],
pre->g_pre_comp[2 * i + 1][2], pre->g_pre_comp[2 * i][0],
pre->g_pre_comp[2 * i][1], pre->g_pre_comp[2 * i][2], 0,
pre->g_pre_comp[1][0], pre->g_pre_comp[1][1],
pre->g_pre_comp[1][2]);
}
make_points_affine(15, &(pre->g_pre_comp[1]), tmp_felems);
done:
if (!EC_EX_DATA_set_data(&group->extra_data, pre, nistp521_pre_comp_dup,
nistp521_pre_comp_free,
nistp521_pre_comp_clear_free))
goto err;
ret = 1;
pre = NULL;
err:
BN_CTX_end(ctx);
if (generator != NULL)
EC_POINT_free(generator);
if (new_ctx != NULL)
BN_CTX_free(new_ctx);
if (pre)
nistp521_pre_comp_free(pre);
return ret;
}
int ec_GFp_nistp521_have_precompute_mult(const EC_GROUP *group)
{
if (EC_EX_DATA_get_data(group->extra_data, nistp521_pre_comp_dup,
nistp521_pre_comp_free,
nistp521_pre_comp_clear_free)
!= NULL)
return 1;
else
return 0;
}
#else
static void *dummy = &dummy;
#endif
diff --git a/crypto/ec/ecp_nistz256.c b/crypto/ec/ecp_nistz256.c
index 99b8d613c833..9a53a39a25b9 100644
--- a/crypto/ec/ecp_nistz256.c
+++ b/crypto/ec/ecp_nistz256.c
@@ -1,1568 +1,1568 @@
/******************************************************************************
* *
* Copyright 2014 Intel Corporation *
* *
* Licensed under the Apache License, Version 2.0 (the "License"); *
* you may not use this file except in compliance with the License. *
* You may obtain a copy of the License at *
* *
* http://www.apache.org/licenses/LICENSE-2.0 *
* *
* Unless required by applicable law or agreed to in writing, software *
* distributed under the License is distributed on an "AS IS" BASIS, *
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *
* See the License for the specific language governing permissions and *
* limitations under the License. *
* *
******************************************************************************
* *
* Developers and authors: *
* Shay Gueron (1, 2), and Vlad Krasnov (1) *
* (1) Intel Corporation, Israel Development Center *
* (2) University of Haifa *
* Reference: *
* S.Gueron and V.Krasnov, "Fast Prime Field Elliptic Curve Cryptography with *
* 256 Bit Primes" *
* *
******************************************************************************/
#include <string.h>
#include <openssl/bn.h>
#include <openssl/err.h>
#include <openssl/ec.h>
#include "cryptlib.h"
#include "ec_lcl.h"
#if BN_BITS2 != 64
# define TOBN(hi,lo) lo,hi
#else
# define TOBN(hi,lo) ((BN_ULONG)hi<<32|lo)
#endif
#if defined(__GNUC__)
# define ALIGN32 __attribute((aligned(32)))
#elif defined(_MSC_VER)
# define ALIGN32 __declspec(align(32))
#else
# define ALIGN32
#endif
#define ALIGNPTR(p,N) ((unsigned char *)p+N-(size_t)p%N)
#define P256_LIMBS (256/BN_BITS2)
typedef unsigned short u16;
typedef struct {
BN_ULONG X[P256_LIMBS];
BN_ULONG Y[P256_LIMBS];
BN_ULONG Z[P256_LIMBS];
} P256_POINT;
typedef struct {
BN_ULONG X[P256_LIMBS];
BN_ULONG Y[P256_LIMBS];
} P256_POINT_AFFINE;
typedef P256_POINT_AFFINE PRECOMP256_ROW[64];
/* structure for precomputed multiples of the generator */
typedef struct ec_pre_comp_st {
const EC_GROUP *group; /* Parent EC_GROUP object */
size_t w; /* Window size */
/*
* Constant time access to the X and Y coordinates of the pre-computed,
* generator multiplies, in the Montgomery domain. Pre-calculated
* multiplies are stored in affine form.
*/
PRECOMP256_ROW *precomp;
void *precomp_storage;
int references;
} EC_PRE_COMP;
/* Functions implemented in assembly */
/*
* Most of below mentioned functions *preserve* the property of inputs
* being fully reduced, i.e. being in [0, modulus) range. Simply put if
* inputs are fully reduced, then output is too. Note that reverse is
* not true, in sense that given partially reduced inputs output can be
* either, not unlikely reduced. And "most" in first sentence refers to
* the fact that given the calculations flow one can tolerate that
* addition, 1st function below, produces partially reduced result *if*
* multiplications by 2 and 3, which customarily use addition, fully
* reduce it. This effectively gives two options: a) addition produces
* fully reduced result [as long as inputs are, just like remaining
* functions]; b) addition is allowed to produce partially reduced
* result, but multiplications by 2 and 3 perform additional reduction
* step. Choice between the two can be platform-specific, but it was a)
* in all cases so far...
*/
/* Modular add: res = a+b mod P */
void ecp_nistz256_add(BN_ULONG res[P256_LIMBS],
const BN_ULONG a[P256_LIMBS],
const BN_ULONG b[P256_LIMBS]);
/* Modular mul by 2: res = 2*a mod P */
void ecp_nistz256_mul_by_2(BN_ULONG res[P256_LIMBS],
const BN_ULONG a[P256_LIMBS]);
/* Modular mul by 3: res = 3*a mod P */
void ecp_nistz256_mul_by_3(BN_ULONG res[P256_LIMBS],
const BN_ULONG a[P256_LIMBS]);
/* Modular div by 2: res = a/2 mod P */
void ecp_nistz256_div_by_2(BN_ULONG res[P256_LIMBS],
const BN_ULONG a[P256_LIMBS]);
/* Modular sub: res = a-b mod P */
void ecp_nistz256_sub(BN_ULONG res[P256_LIMBS],
const BN_ULONG a[P256_LIMBS],
const BN_ULONG b[P256_LIMBS]);
/* Modular neg: res = -a mod P */
void ecp_nistz256_neg(BN_ULONG res[P256_LIMBS], const BN_ULONG a[P256_LIMBS]);
/* Montgomery mul: res = a*b*2^-256 mod P */
void ecp_nistz256_mul_mont(BN_ULONG res[P256_LIMBS],
const BN_ULONG a[P256_LIMBS],
const BN_ULONG b[P256_LIMBS]);
/* Montgomery sqr: res = a*a*2^-256 mod P */
void ecp_nistz256_sqr_mont(BN_ULONG res[P256_LIMBS],
const BN_ULONG a[P256_LIMBS]);
/* Convert a number from Montgomery domain, by multiplying with 1 */
void ecp_nistz256_from_mont(BN_ULONG res[P256_LIMBS],
const BN_ULONG in[P256_LIMBS]);
/* Convert a number to Montgomery domain, by multiplying with 2^512 mod P*/
void ecp_nistz256_to_mont(BN_ULONG res[P256_LIMBS],
const BN_ULONG in[P256_LIMBS]);
/* Functions that perform constant time access to the precomputed tables */
void ecp_nistz256_select_w5(P256_POINT * val,
const P256_POINT * in_t, int index);
void ecp_nistz256_select_w7(P256_POINT_AFFINE * val,
const P256_POINT_AFFINE * in_t, int index);
/* One converted into the Montgomery domain */
static const BN_ULONG ONE[P256_LIMBS] = {
TOBN(0x00000000, 0x00000001), TOBN(0xffffffff, 0x00000000),
TOBN(0xffffffff, 0xffffffff), TOBN(0x00000000, 0xfffffffe)
};
static void *ecp_nistz256_pre_comp_dup(void *);
static void ecp_nistz256_pre_comp_free(void *);
static void ecp_nistz256_pre_comp_clear_free(void *);
static EC_PRE_COMP *ecp_nistz256_pre_comp_new(const EC_GROUP *group);
/* Precomputed tables for the default generator */
#include "ecp_nistz256_table.c"
/* Recode window to a signed digit, see ecp_nistputil.c for details */
static unsigned int _booth_recode_w5(unsigned int in)
{
unsigned int s, d;
s = ~((in >> 5) - 1);
d = (1 << 6) - in - 1;
d = (d & s) | (in & ~s);
d = (d >> 1) + (d & 1);
return (d << 1) + (s & 1);
}
static unsigned int _booth_recode_w7(unsigned int in)
{
unsigned int s, d;
s = ~((in >> 7) - 1);
d = (1 << 8) - in - 1;
d = (d & s) | (in & ~s);
d = (d >> 1) + (d & 1);
return (d << 1) + (s & 1);
}
static void copy_conditional(BN_ULONG dst[P256_LIMBS],
const BN_ULONG src[P256_LIMBS], BN_ULONG move)
{
BN_ULONG mask1 = -move;
BN_ULONG mask2 = ~mask1;
dst[0] = (src[0] & mask1) ^ (dst[0] & mask2);
dst[1] = (src[1] & mask1) ^ (dst[1] & mask2);
dst[2] = (src[2] & mask1) ^ (dst[2] & mask2);
dst[3] = (src[3] & mask1) ^ (dst[3] & mask2);
if (P256_LIMBS == 8) {
dst[4] = (src[4] & mask1) ^ (dst[4] & mask2);
dst[5] = (src[5] & mask1) ^ (dst[5] & mask2);
dst[6] = (src[6] & mask1) ^ (dst[6] & mask2);
dst[7] = (src[7] & mask1) ^ (dst[7] & mask2);
}
}
static BN_ULONG is_zero(BN_ULONG in)
{
in |= (0 - in);
in = ~in;
in &= BN_MASK2;
in >>= BN_BITS2 - 1;
return in;
}
static BN_ULONG is_equal(const BN_ULONG a[P256_LIMBS],
const BN_ULONG b[P256_LIMBS])
{
BN_ULONG res;
res = a[0] ^ b[0];
res |= a[1] ^ b[1];
res |= a[2] ^ b[2];
res |= a[3] ^ b[3];
if (P256_LIMBS == 8) {
res |= a[4] ^ b[4];
res |= a[5] ^ b[5];
res |= a[6] ^ b[6];
res |= a[7] ^ b[7];
}
return is_zero(res);
}
static BN_ULONG is_one(const BIGNUM *z)
{
BN_ULONG res = 0;
BN_ULONG *a = z->d;
if (z->top == (P256_LIMBS - P256_LIMBS / 8)) {
res = a[0] ^ ONE[0];
res |= a[1] ^ ONE[1];
res |= a[2] ^ ONE[2];
res |= a[3] ^ ONE[3];
if (P256_LIMBS == 8) {
res |= a[4] ^ ONE[4];
res |= a[5] ^ ONE[5];
res |= a[6] ^ ONE[6];
/*
* no check for a[7] (being zero) on 32-bit platforms,
* because value of "one" takes only 7 limbs.
*/
}
res = is_zero(res);
}
return res;
}
static int ecp_nistz256_set_words(BIGNUM *a, BN_ULONG words[P256_LIMBS])
{
if (bn_wexpand(a, P256_LIMBS) == NULL) {
ECerr(EC_F_ECP_NISTZ256_SET_WORDS, ERR_R_MALLOC_FAILURE);
return 0;
}
memcpy(a->d, words, sizeof(BN_ULONG) * P256_LIMBS);
a->top = P256_LIMBS;
bn_correct_top(a);
return 1;
}
#ifndef ECP_NISTZ256_REFERENCE_IMPLEMENTATION
void ecp_nistz256_point_double(P256_POINT *r, const P256_POINT *a);
void ecp_nistz256_point_add(P256_POINT *r,
const P256_POINT *a, const P256_POINT *b);
void ecp_nistz256_point_add_affine(P256_POINT *r,
const P256_POINT *a,
const P256_POINT_AFFINE *b);
#else
/* Point double: r = 2*a */
static void ecp_nistz256_point_double(P256_POINT *r, const P256_POINT *a)
{
BN_ULONG S[P256_LIMBS];
BN_ULONG M[P256_LIMBS];
BN_ULONG Zsqr[P256_LIMBS];
BN_ULONG tmp0[P256_LIMBS];
const BN_ULONG *in_x = a->X;
const BN_ULONG *in_y = a->Y;
const BN_ULONG *in_z = a->Z;
BN_ULONG *res_x = r->X;
BN_ULONG *res_y = r->Y;
BN_ULONG *res_z = r->Z;
ecp_nistz256_mul_by_2(S, in_y);
ecp_nistz256_sqr_mont(Zsqr, in_z);
ecp_nistz256_sqr_mont(S, S);
ecp_nistz256_mul_mont(res_z, in_z, in_y);
ecp_nistz256_mul_by_2(res_z, res_z);
ecp_nistz256_add(M, in_x, Zsqr);
ecp_nistz256_sub(Zsqr, in_x, Zsqr);
ecp_nistz256_sqr_mont(res_y, S);
ecp_nistz256_div_by_2(res_y, res_y);
ecp_nistz256_mul_mont(M, M, Zsqr);
ecp_nistz256_mul_by_3(M, M);
ecp_nistz256_mul_mont(S, S, in_x);
ecp_nistz256_mul_by_2(tmp0, S);
ecp_nistz256_sqr_mont(res_x, M);
ecp_nistz256_sub(res_x, res_x, tmp0);
ecp_nistz256_sub(S, S, res_x);
ecp_nistz256_mul_mont(S, S, M);
ecp_nistz256_sub(res_y, S, res_y);
}
/* Point addition: r = a+b */
static void ecp_nistz256_point_add(P256_POINT *r,
const P256_POINT *a, const P256_POINT *b)
{
BN_ULONG U2[P256_LIMBS], S2[P256_LIMBS];
BN_ULONG U1[P256_LIMBS], S1[P256_LIMBS];
BN_ULONG Z1sqr[P256_LIMBS];
BN_ULONG Z2sqr[P256_LIMBS];
BN_ULONG H[P256_LIMBS], R[P256_LIMBS];
BN_ULONG Hsqr[P256_LIMBS];
BN_ULONG Rsqr[P256_LIMBS];
BN_ULONG Hcub[P256_LIMBS];
BN_ULONG res_x[P256_LIMBS];
BN_ULONG res_y[P256_LIMBS];
BN_ULONG res_z[P256_LIMBS];
BN_ULONG in1infty, in2infty;
const BN_ULONG *in1_x = a->X;
const BN_ULONG *in1_y = a->Y;
const BN_ULONG *in1_z = a->Z;
const BN_ULONG *in2_x = b->X;
const BN_ULONG *in2_y = b->Y;
const BN_ULONG *in2_z = b->Z;
/*
* Infinity in encoded as (,,0)
*/
in1infty = (in1_z[0] | in1_z[1] | in1_z[2] | in1_z[3]);
if (P256_LIMBS == 8)
in1infty |= (in1_z[4] | in1_z[5] | in1_z[6] | in1_z[7]);
in2infty = (in2_z[0] | in2_z[1] | in2_z[2] | in2_z[3]);
if (P256_LIMBS == 8)
in2infty |= (in2_z[4] | in2_z[5] | in2_z[6] | in2_z[7]);
in1infty = is_zero(in1infty);
in2infty = is_zero(in2infty);
ecp_nistz256_sqr_mont(Z2sqr, in2_z); /* Z2^2 */
ecp_nistz256_sqr_mont(Z1sqr, in1_z); /* Z1^2 */
ecp_nistz256_mul_mont(S1, Z2sqr, in2_z); /* S1 = Z2^3 */
ecp_nistz256_mul_mont(S2, Z1sqr, in1_z); /* S2 = Z1^3 */
ecp_nistz256_mul_mont(S1, S1, in1_y); /* S1 = Y1*Z2^3 */
ecp_nistz256_mul_mont(S2, S2, in2_y); /* S2 = Y2*Z1^3 */
ecp_nistz256_sub(R, S2, S1); /* R = S2 - S1 */
ecp_nistz256_mul_mont(U1, in1_x, Z2sqr); /* U1 = X1*Z2^2 */
ecp_nistz256_mul_mont(U2, in2_x, Z1sqr); /* U2 = X2*Z1^2 */
ecp_nistz256_sub(H, U2, U1); /* H = U2 - U1 */
/*
* This should not happen during sign/ecdh, so no constant time violation
*/
if (is_equal(U1, U2) && !in1infty && !in2infty) {
if (is_equal(S1, S2)) {
ecp_nistz256_point_double(r, a);
return;
} else {
memset(r, 0, sizeof(*r));
return;
}
}
ecp_nistz256_sqr_mont(Rsqr, R); /* R^2 */
ecp_nistz256_mul_mont(res_z, H, in1_z); /* Z3 = H*Z1*Z2 */
ecp_nistz256_sqr_mont(Hsqr, H); /* H^2 */
ecp_nistz256_mul_mont(res_z, res_z, in2_z); /* Z3 = H*Z1*Z2 */
ecp_nistz256_mul_mont(Hcub, Hsqr, H); /* H^3 */
ecp_nistz256_mul_mont(U2, U1, Hsqr); /* U1*H^2 */
ecp_nistz256_mul_by_2(Hsqr, U2); /* 2*U1*H^2 */
ecp_nistz256_sub(res_x, Rsqr, Hsqr);
ecp_nistz256_sub(res_x, res_x, Hcub);
ecp_nistz256_sub(res_y, U2, res_x);
ecp_nistz256_mul_mont(S2, S1, Hcub);
ecp_nistz256_mul_mont(res_y, R, res_y);
ecp_nistz256_sub(res_y, res_y, S2);
copy_conditional(res_x, in2_x, in1infty);
copy_conditional(res_y, in2_y, in1infty);
copy_conditional(res_z, in2_z, in1infty);
copy_conditional(res_x, in1_x, in2infty);
copy_conditional(res_y, in1_y, in2infty);
copy_conditional(res_z, in1_z, in2infty);
memcpy(r->X, res_x, sizeof(res_x));
memcpy(r->Y, res_y, sizeof(res_y));
memcpy(r->Z, res_z, sizeof(res_z));
}
/* Point addition when b is known to be affine: r = a+b */
static void ecp_nistz256_point_add_affine(P256_POINT *r,
const P256_POINT *a,
const P256_POINT_AFFINE *b)
{
BN_ULONG U2[P256_LIMBS], S2[P256_LIMBS];
BN_ULONG Z1sqr[P256_LIMBS];
BN_ULONG H[P256_LIMBS], R[P256_LIMBS];
BN_ULONG Hsqr[P256_LIMBS];
BN_ULONG Rsqr[P256_LIMBS];
BN_ULONG Hcub[P256_LIMBS];
BN_ULONG res_x[P256_LIMBS];
BN_ULONG res_y[P256_LIMBS];
BN_ULONG res_z[P256_LIMBS];
BN_ULONG in1infty, in2infty;
const BN_ULONG *in1_x = a->X;
const BN_ULONG *in1_y = a->Y;
const BN_ULONG *in1_z = a->Z;
const BN_ULONG *in2_x = b->X;
const BN_ULONG *in2_y = b->Y;
/*
* Infinity in encoded as (,,0)
*/
in1infty = (in1_z[0] | in1_z[1] | in1_z[2] | in1_z[3]);
if (P256_LIMBS == 8)
in1infty |= (in1_z[4] | in1_z[5] | in1_z[6] | in1_z[7]);
/*
* In affine representation we encode infinity as (0,0), which is
* not on the curve, so it is OK
*/
in2infty = (in2_x[0] | in2_x[1] | in2_x[2] | in2_x[3] |
in2_y[0] | in2_y[1] | in2_y[2] | in2_y[3]);
if (P256_LIMBS == 8)
in2infty |= (in2_x[4] | in2_x[5] | in2_x[6] | in2_x[7] |
in2_y[4] | in2_y[5] | in2_y[6] | in2_y[7]);
in1infty = is_zero(in1infty);
in2infty = is_zero(in2infty);
ecp_nistz256_sqr_mont(Z1sqr, in1_z); /* Z1^2 */
ecp_nistz256_mul_mont(U2, in2_x, Z1sqr); /* U2 = X2*Z1^2 */
ecp_nistz256_sub(H, U2, in1_x); /* H = U2 - U1 */
ecp_nistz256_mul_mont(S2, Z1sqr, in1_z); /* S2 = Z1^3 */
ecp_nistz256_mul_mont(res_z, H, in1_z); /* Z3 = H*Z1*Z2 */
ecp_nistz256_mul_mont(S2, S2, in2_y); /* S2 = Y2*Z1^3 */
ecp_nistz256_sub(R, S2, in1_y); /* R = S2 - S1 */
ecp_nistz256_sqr_mont(Hsqr, H); /* H^2 */
ecp_nistz256_sqr_mont(Rsqr, R); /* R^2 */
ecp_nistz256_mul_mont(Hcub, Hsqr, H); /* H^3 */
ecp_nistz256_mul_mont(U2, in1_x, Hsqr); /* U1*H^2 */
ecp_nistz256_mul_by_2(Hsqr, U2); /* 2*U1*H^2 */
ecp_nistz256_sub(res_x, Rsqr, Hsqr);
ecp_nistz256_sub(res_x, res_x, Hcub);
ecp_nistz256_sub(H, U2, res_x);
ecp_nistz256_mul_mont(S2, in1_y, Hcub);
ecp_nistz256_mul_mont(H, H, R);
ecp_nistz256_sub(res_y, H, S2);
copy_conditional(res_x, in2_x, in1infty);
copy_conditional(res_x, in1_x, in2infty);
copy_conditional(res_y, in2_y, in1infty);
copy_conditional(res_y, in1_y, in2infty);
copy_conditional(res_z, ONE, in1infty);
copy_conditional(res_z, in1_z, in2infty);
memcpy(r->X, res_x, sizeof(res_x));
memcpy(r->Y, res_y, sizeof(res_y));
memcpy(r->Z, res_z, sizeof(res_z));
}
#endif
/* r = in^-1 mod p */
static void ecp_nistz256_mod_inverse(BN_ULONG r[P256_LIMBS],
const BN_ULONG in[P256_LIMBS])
{
/*
* The poly is ffffffff 00000001 00000000 00000000 00000000 ffffffff
* ffffffff ffffffff We use FLT and used poly-2 as exponent
*/
BN_ULONG p2[P256_LIMBS];
BN_ULONG p4[P256_LIMBS];
BN_ULONG p8[P256_LIMBS];
BN_ULONG p16[P256_LIMBS];
BN_ULONG p32[P256_LIMBS];
BN_ULONG res[P256_LIMBS];
int i;
ecp_nistz256_sqr_mont(res, in);
ecp_nistz256_mul_mont(p2, res, in); /* 3*p */
ecp_nistz256_sqr_mont(res, p2);
ecp_nistz256_sqr_mont(res, res);
ecp_nistz256_mul_mont(p4, res, p2); /* f*p */
ecp_nistz256_sqr_mont(res, p4);
ecp_nistz256_sqr_mont(res, res);
ecp_nistz256_sqr_mont(res, res);
ecp_nistz256_sqr_mont(res, res);
ecp_nistz256_mul_mont(p8, res, p4); /* ff*p */
ecp_nistz256_sqr_mont(res, p8);
for (i = 0; i < 7; i++)
ecp_nistz256_sqr_mont(res, res);
ecp_nistz256_mul_mont(p16, res, p8); /* ffff*p */
ecp_nistz256_sqr_mont(res, p16);
for (i = 0; i < 15; i++)
ecp_nistz256_sqr_mont(res, res);
ecp_nistz256_mul_mont(p32, res, p16); /* ffffffff*p */
ecp_nistz256_sqr_mont(res, p32);
for (i = 0; i < 31; i++)
ecp_nistz256_sqr_mont(res, res);
ecp_nistz256_mul_mont(res, res, in);
for (i = 0; i < 32 * 4; i++)
ecp_nistz256_sqr_mont(res, res);
ecp_nistz256_mul_mont(res, res, p32);
for (i = 0; i < 32; i++)
ecp_nistz256_sqr_mont(res, res);
ecp_nistz256_mul_mont(res, res, p32);
for (i = 0; i < 16; i++)
ecp_nistz256_sqr_mont(res, res);
ecp_nistz256_mul_mont(res, res, p16);
for (i = 0; i < 8; i++)
ecp_nistz256_sqr_mont(res, res);
ecp_nistz256_mul_mont(res, res, p8);
ecp_nistz256_sqr_mont(res, res);
ecp_nistz256_sqr_mont(res, res);
ecp_nistz256_sqr_mont(res, res);
ecp_nistz256_sqr_mont(res, res);
ecp_nistz256_mul_mont(res, res, p4);
ecp_nistz256_sqr_mont(res, res);
ecp_nistz256_sqr_mont(res, res);
ecp_nistz256_mul_mont(res, res, p2);
ecp_nistz256_sqr_mont(res, res);
ecp_nistz256_sqr_mont(res, res);
ecp_nistz256_mul_mont(res, res, in);
memcpy(r, res, sizeof(res));
}
/*
* ecp_nistz256_bignum_to_field_elem copies the contents of |in| to |out| and
* returns one if it fits. Otherwise it returns zero.
*/
static int ecp_nistz256_bignum_to_field_elem(BN_ULONG out[P256_LIMBS],
const BIGNUM *in)
{
if (in->top > P256_LIMBS)
return 0;
memset(out, 0, sizeof(BN_ULONG) * P256_LIMBS);
memcpy(out, in->d, sizeof(BN_ULONG) * in->top);
return 1;
}
/* r = sum(scalar[i]*point[i]) */
static int ecp_nistz256_windowed_mul(const EC_GROUP *group,
P256_POINT *r,
const BIGNUM **scalar,
const EC_POINT **point,
int num, BN_CTX *ctx)
{
int i, j, ret = 0;
unsigned int index;
unsigned char (*p_str)[33] = NULL;
const unsigned int window_size = 5;
const unsigned int mask = (1 << (window_size + 1)) - 1;
unsigned int wvalue;
BN_ULONG tmp[P256_LIMBS];
ALIGN32 P256_POINT h;
const BIGNUM **scalars = NULL;
P256_POINT (*table)[16] = NULL;
void *table_storage = NULL;
if ((table_storage =
OPENSSL_malloc(num * 16 * sizeof(P256_POINT) + 64)) == NULL
|| (p_str =
OPENSSL_malloc(num * 33 * sizeof(unsigned char))) == NULL
|| (scalars = OPENSSL_malloc(num * sizeof(BIGNUM *))) == NULL) {
ECerr(EC_F_ECP_NISTZ256_WINDOWED_MUL, ERR_R_MALLOC_FAILURE);
goto err;
} else {
table = (void *)ALIGNPTR(table_storage, 64);
}
for (i = 0; i < num; i++) {
P256_POINT *row = table[i];
/* This is an unusual input, we don't guarantee constant-timeness. */
if ((BN_num_bits(scalar[i]) > 256) || BN_is_negative(scalar[i])) {
BIGNUM *mod;
if ((mod = BN_CTX_get(ctx)) == NULL)
goto err;
if (!BN_nnmod(mod, scalar[i], &group->order, ctx)) {
ECerr(EC_F_ECP_NISTZ256_WINDOWED_MUL, ERR_R_BN_LIB);
goto err;
}
scalars[i] = mod;
} else
scalars[i] = scalar[i];
for (j = 0; j < scalars[i]->top * BN_BYTES; j += BN_BYTES) {
BN_ULONG d = scalars[i]->d[j / BN_BYTES];
p_str[i][j + 0] = d & 0xff;
p_str[i][j + 1] = (d >> 8) & 0xff;
p_str[i][j + 2] = (d >> 16) & 0xff;
p_str[i][j + 3] = (d >>= 24) & 0xff;
if (BN_BYTES == 8) {
d >>= 8;
p_str[i][j + 4] = d & 0xff;
p_str[i][j + 5] = (d >> 8) & 0xff;
p_str[i][j + 6] = (d >> 16) & 0xff;
p_str[i][j + 7] = (d >> 24) & 0xff;
}
}
for (; j < 33; j++)
p_str[i][j] = 0;
/* table[0] is implicitly (0,0,0) (the point at infinity),
* therefore it is not stored. All other values are actually
* stored with an offset of -1 in table.
*/
if (!ecp_nistz256_bignum_to_field_elem(row[1 - 1].X, &point[i]->X)
|| !ecp_nistz256_bignum_to_field_elem(row[1 - 1].Y, &point[i]->Y)
|| !ecp_nistz256_bignum_to_field_elem(row[1 - 1].Z, &point[i]->Z)) {
ECerr(EC_F_ECP_NISTZ256_WINDOWED_MUL, EC_R_COORDINATES_OUT_OF_RANGE);
goto err;
}
ecp_nistz256_point_double(&row[ 2 - 1], &row[ 1 - 1]);
ecp_nistz256_point_add (&row[ 3 - 1], &row[ 2 - 1], &row[1 - 1]);
ecp_nistz256_point_double(&row[ 4 - 1], &row[ 2 - 1]);
ecp_nistz256_point_double(&row[ 6 - 1], &row[ 3 - 1]);
ecp_nistz256_point_double(&row[ 8 - 1], &row[ 4 - 1]);
ecp_nistz256_point_double(&row[12 - 1], &row[ 6 - 1]);
ecp_nistz256_point_add (&row[ 5 - 1], &row[ 4 - 1], &row[1 - 1]);
ecp_nistz256_point_add (&row[ 7 - 1], &row[ 6 - 1], &row[1 - 1]);
ecp_nistz256_point_add (&row[ 9 - 1], &row[ 8 - 1], &row[1 - 1]);
ecp_nistz256_point_add (&row[13 - 1], &row[12 - 1], &row[1 - 1]);
ecp_nistz256_point_double(&row[14 - 1], &row[ 7 - 1]);
ecp_nistz256_point_double(&row[10 - 1], &row[ 5 - 1]);
ecp_nistz256_point_add (&row[15 - 1], &row[14 - 1], &row[1 - 1]);
ecp_nistz256_point_add (&row[11 - 1], &row[10 - 1], &row[1 - 1]);
ecp_nistz256_point_add (&row[16 - 1], &row[15 - 1], &row[1 - 1]);
}
index = 255;
wvalue = p_str[0][(index - 1) / 8];
wvalue = (wvalue >> ((index - 1) % 8)) & mask;
ecp_nistz256_select_w5(r, table[0], _booth_recode_w5(wvalue) >> 1);
while (index >= 5) {
for (i = (index == 255 ? 1 : 0); i < num; i++) {
unsigned int off = (index - 1) / 8;
wvalue = p_str[i][off] | p_str[i][off + 1] << 8;
wvalue = (wvalue >> ((index - 1) % 8)) & mask;
wvalue = _booth_recode_w5(wvalue);
ecp_nistz256_select_w5(&h, table[i], wvalue >> 1);
ecp_nistz256_neg(tmp, h.Y);
copy_conditional(h.Y, tmp, (wvalue & 1));
ecp_nistz256_point_add(r, r, &h);
}
index -= window_size;
ecp_nistz256_point_double(r, r);
ecp_nistz256_point_double(r, r);
ecp_nistz256_point_double(r, r);
ecp_nistz256_point_double(r, r);
ecp_nistz256_point_double(r, r);
}
/* Final window */
for (i = 0; i < num; i++) {
wvalue = p_str[i][0];
wvalue = (wvalue << 1) & mask;
wvalue = _booth_recode_w5(wvalue);
ecp_nistz256_select_w5(&h, table[i], wvalue >> 1);
ecp_nistz256_neg(tmp, h.Y);
copy_conditional(h.Y, tmp, wvalue & 1);
ecp_nistz256_point_add(r, r, &h);
}
ret = 1;
err:
if (table_storage)
OPENSSL_free(table_storage);
if (p_str)
OPENSSL_free(p_str);
if (scalars)
OPENSSL_free(scalars);
return ret;
}
/* Coordinates of G, for which we have precomputed tables */
const static BN_ULONG def_xG[P256_LIMBS] = {
TOBN(0x79e730d4, 0x18a9143c), TOBN(0x75ba95fc, 0x5fedb601),
TOBN(0x79fb732b, 0x77622510), TOBN(0x18905f76, 0xa53755c6)
};
const static BN_ULONG def_yG[P256_LIMBS] = {
TOBN(0xddf25357, 0xce95560a), TOBN(0x8b4ab8e4, 0xba19e45c),
TOBN(0xd2e88688, 0xdd21f325), TOBN(0x8571ff18, 0x25885d85)
};
/*
* ecp_nistz256_is_affine_G returns one if |generator| is the standard, P-256
* generator.
*/
static int ecp_nistz256_is_affine_G(const EC_POINT *generator)
{
return (generator->X.top == P256_LIMBS) &&
(generator->Y.top == P256_LIMBS) &&
is_equal(generator->X.d, def_xG) &&
is_equal(generator->Y.d, def_yG) && is_one(&generator->Z);
}
static int ecp_nistz256_mult_precompute(EC_GROUP *group, BN_CTX *ctx)
{
/*
* We precompute a table for a Booth encoded exponent (wNAF) based
* computation. Each table holds 64 values for safe access, with an
* implicit value of infinity at index zero. We use window of size 7, and
* therefore require ceil(256/7) = 37 tables.
*/
BIGNUM *order;
EC_POINT *P = NULL, *T = NULL;
const EC_POINT *generator;
EC_PRE_COMP *pre_comp;
BN_CTX *new_ctx = NULL;
int i, j, k, ret = 0;
size_t w;
PRECOMP256_ROW *preComputedTable = NULL;
unsigned char *precomp_storage = NULL;
/* if there is an old EC_PRE_COMP object, throw it away */
EC_EX_DATA_free_data(&group->extra_data, ecp_nistz256_pre_comp_dup,
ecp_nistz256_pre_comp_free,
ecp_nistz256_pre_comp_clear_free);
generator = EC_GROUP_get0_generator(group);
if (generator == NULL) {
ECerr(EC_F_ECP_NISTZ256_MULT_PRECOMPUTE, EC_R_UNDEFINED_GENERATOR);
return 0;
}
if (ecp_nistz256_is_affine_G(generator)) {
/*
* No need to calculate tables for the standard generator because we
* have them statically.
*/
return 1;
}
if ((pre_comp = ecp_nistz256_pre_comp_new(group)) == NULL)
return 0;
if (ctx == NULL) {
ctx = new_ctx = BN_CTX_new();
if (ctx == NULL)
goto err;
}
BN_CTX_start(ctx);
order = BN_CTX_get(ctx);
if (order == NULL)
goto err;
if (!EC_GROUP_get_order(group, order, ctx))
goto err;
if (BN_is_zero(order)) {
ECerr(EC_F_ECP_NISTZ256_MULT_PRECOMPUTE, EC_R_UNKNOWN_ORDER);
goto err;
}
w = 7;
if ((precomp_storage =
OPENSSL_malloc(37 * 64 * sizeof(P256_POINT_AFFINE) + 64)) == NULL) {
ECerr(EC_F_ECP_NISTZ256_MULT_PRECOMPUTE, ERR_R_MALLOC_FAILURE);
goto err;
} else {
preComputedTable = (void *)ALIGNPTR(precomp_storage, 64);
}
P = EC_POINT_new(group);
T = EC_POINT_new(group);
if (P == NULL || T == NULL)
goto err;
/*
* The zero entry is implicitly infinity, and we skip it, storing other
* values with -1 offset.
*/
if (!EC_POINT_copy(T, generator))
goto err;
for (k = 0; k < 64; k++) {
if (!EC_POINT_copy(P, T))
goto err;
for (j = 0; j < 37; j++) {
/*
* It would be faster to use EC_POINTs_make_affine and
* make multiple points affine at the same time.
*/
if (!EC_POINT_make_affine(group, P, ctx))
goto err;
if (!ecp_nistz256_bignum_to_field_elem(preComputedTable[j][k].X,
&P->X) ||
!ecp_nistz256_bignum_to_field_elem(preComputedTable[j][k].Y,
&P->Y)) {
ECerr(EC_F_ECP_NISTZ256_MULT_PRECOMPUTE,
EC_R_COORDINATES_OUT_OF_RANGE);
goto err;
}
for (i = 0; i < 7; i++) {
if (!EC_POINT_dbl(group, P, P, ctx))
goto err;
}
}
if (!EC_POINT_add(group, T, T, generator, ctx))
goto err;
}
pre_comp->group = group;
pre_comp->w = w;
pre_comp->precomp = preComputedTable;
pre_comp->precomp_storage = precomp_storage;
precomp_storage = NULL;
if (!EC_EX_DATA_set_data(&group->extra_data, pre_comp,
ecp_nistz256_pre_comp_dup,
ecp_nistz256_pre_comp_free,
ecp_nistz256_pre_comp_clear_free)) {
goto err;
}
pre_comp = NULL;
ret = 1;
err:
if (ctx != NULL)
BN_CTX_end(ctx);
BN_CTX_free(new_ctx);
if (pre_comp)
ecp_nistz256_pre_comp_free(pre_comp);
if (precomp_storage)
OPENSSL_free(precomp_storage);
if (P)
EC_POINT_free(P);
if (T)
EC_POINT_free(T);
return ret;
}
/*
* Note that by default ECP_NISTZ256_AVX2 is undefined. While it's great
* code processing 4 points in parallel, corresponding serial operation
* is several times slower, because it uses 29x29=58-bit multiplication
* as opposite to 64x64=128-bit in integer-only scalar case. As result
* it doesn't provide *significant* performance improvement. Note that
* just defining ECP_NISTZ256_AVX2 is not sufficient to make it work,
* you'd need to compile even asm/ecp_nistz256-avx.pl module.
*/
#if defined(ECP_NISTZ256_AVX2)
# if !(defined(__x86_64) || defined(__x86_64__)) || \
defined(_M_AMD64) || defined(_MX64)) || \
!(defined(__GNUC__) || defined(_MSC_VER)) /* this is for ALIGN32 */
# undef ECP_NISTZ256_AVX2
# else
/* Constant time access, loading four values, from four consecutive tables */
void ecp_nistz256_avx2_select_w7(P256_POINT_AFFINE * val,
const P256_POINT_AFFINE * in_t, int index);
void ecp_nistz256_avx2_multi_select_w7(void *result, const void *in, int index0,
int index1, int index2, int index3);
void ecp_nistz256_avx2_transpose_convert(void *RESULTx4, const void *in);
void ecp_nistz256_avx2_convert_transpose_back(void *result, const void *Ax4);
void ecp_nistz256_avx2_point_add_affine_x4(void *RESULTx4, const void *Ax4,
const void *Bx4);
void ecp_nistz256_avx2_point_add_affines_x4(void *RESULTx4, const void *Ax4,
const void *Bx4);
void ecp_nistz256_avx2_to_mont(void *RESULTx4, const void *Ax4);
void ecp_nistz256_avx2_from_mont(void *RESULTx4, const void *Ax4);
void ecp_nistz256_avx2_set1(void *RESULTx4);
int ecp_nistz_avx2_eligible(void);
static void booth_recode_w7(unsigned char *sign,
unsigned char *digit, unsigned char in)
{
unsigned char s, d;
s = ~((in >> 7) - 1);
d = (1 << 8) - in - 1;
d = (d & s) | (in & ~s);
d = (d >> 1) + (d & 1);
*sign = s & 1;
*digit = d;
}
/*
* ecp_nistz256_avx2_mul_g performs multiplication by G, using only the
* precomputed table. It does 4 affine point additions in parallel,
* significantly speeding up point multiplication for a fixed value.
*/
static void ecp_nistz256_avx2_mul_g(P256_POINT *r,
unsigned char p_str[33],
const P256_POINT_AFFINE(*preComputedTable)[64])
{
const unsigned int window_size = 7;
const unsigned int mask = (1 << (window_size + 1)) - 1;
unsigned int wvalue;
/* Using 4 windows at a time */
unsigned char sign0, digit0;
unsigned char sign1, digit1;
unsigned char sign2, digit2;
unsigned char sign3, digit3;
unsigned int index = 0;
BN_ULONG tmp[P256_LIMBS];
int i;
ALIGN32 BN_ULONG aX4[4 * 9 * 3] = { 0 };
ALIGN32 BN_ULONG bX4[4 * 9 * 2] = { 0 };
ALIGN32 P256_POINT_AFFINE point_arr[P256_LIMBS];
ALIGN32 P256_POINT res_point_arr[P256_LIMBS];
/* Initial four windows */
wvalue = *((u16 *) & p_str[0]);
wvalue = (wvalue << 1) & mask;
index += window_size;
booth_recode_w7(&sign0, &digit0, wvalue);
wvalue = *((u16 *) & p_str[(index - 1) / 8]);
wvalue = (wvalue >> ((index - 1) % 8)) & mask;
index += window_size;
booth_recode_w7(&sign1, &digit1, wvalue);
wvalue = *((u16 *) & p_str[(index - 1) / 8]);
wvalue = (wvalue >> ((index - 1) % 8)) & mask;
index += window_size;
booth_recode_w7(&sign2, &digit2, wvalue);
wvalue = *((u16 *) & p_str[(index - 1) / 8]);
wvalue = (wvalue >> ((index - 1) % 8)) & mask;
index += window_size;
booth_recode_w7(&sign3, &digit3, wvalue);
ecp_nistz256_avx2_multi_select_w7(point_arr, preComputedTable[0],
digit0, digit1, digit2, digit3);
ecp_nistz256_neg(tmp, point_arr[0].Y);
copy_conditional(point_arr[0].Y, tmp, sign0);
ecp_nistz256_neg(tmp, point_arr[1].Y);
copy_conditional(point_arr[1].Y, tmp, sign1);
ecp_nistz256_neg(tmp, point_arr[2].Y);
copy_conditional(point_arr[2].Y, tmp, sign2);
ecp_nistz256_neg(tmp, point_arr[3].Y);
copy_conditional(point_arr[3].Y, tmp, sign3);
ecp_nistz256_avx2_transpose_convert(aX4, point_arr);
ecp_nistz256_avx2_to_mont(aX4, aX4);
ecp_nistz256_avx2_to_mont(&aX4[4 * 9], &aX4[4 * 9]);
ecp_nistz256_avx2_set1(&aX4[4 * 9 * 2]);
wvalue = *((u16 *) & p_str[(index - 1) / 8]);
wvalue = (wvalue >> ((index - 1) % 8)) & mask;
index += window_size;
booth_recode_w7(&sign0, &digit0, wvalue);
wvalue = *((u16 *) & p_str[(index - 1) / 8]);
wvalue = (wvalue >> ((index - 1) % 8)) & mask;
index += window_size;
booth_recode_w7(&sign1, &digit1, wvalue);
wvalue = *((u16 *) & p_str[(index - 1) / 8]);
wvalue = (wvalue >> ((index - 1) % 8)) & mask;
index += window_size;
booth_recode_w7(&sign2, &digit2, wvalue);
wvalue = *((u16 *) & p_str[(index - 1) / 8]);
wvalue = (wvalue >> ((index - 1) % 8)) & mask;
index += window_size;
booth_recode_w7(&sign3, &digit3, wvalue);
ecp_nistz256_avx2_multi_select_w7(point_arr, preComputedTable[4 * 1],
digit0, digit1, digit2, digit3);
ecp_nistz256_neg(tmp, point_arr[0].Y);
copy_conditional(point_arr[0].Y, tmp, sign0);
ecp_nistz256_neg(tmp, point_arr[1].Y);
copy_conditional(point_arr[1].Y, tmp, sign1);
ecp_nistz256_neg(tmp, point_arr[2].Y);
copy_conditional(point_arr[2].Y, tmp, sign2);
ecp_nistz256_neg(tmp, point_arr[3].Y);
copy_conditional(point_arr[3].Y, tmp, sign3);
ecp_nistz256_avx2_transpose_convert(bX4, point_arr);
ecp_nistz256_avx2_to_mont(bX4, bX4);
ecp_nistz256_avx2_to_mont(&bX4[4 * 9], &bX4[4 * 9]);
/* Optimized when both inputs are affine */
ecp_nistz256_avx2_point_add_affines_x4(aX4, aX4, bX4);
for (i = 2; i < 9; i++) {
wvalue = *((u16 *) & p_str[(index - 1) / 8]);
wvalue = (wvalue >> ((index - 1) % 8)) & mask;
index += window_size;
booth_recode_w7(&sign0, &digit0, wvalue);
wvalue = *((u16 *) & p_str[(index - 1) / 8]);
wvalue = (wvalue >> ((index - 1) % 8)) & mask;
index += window_size;
booth_recode_w7(&sign1, &digit1, wvalue);
wvalue = *((u16 *) & p_str[(index - 1) / 8]);
wvalue = (wvalue >> ((index - 1) % 8)) & mask;
index += window_size;
booth_recode_w7(&sign2, &digit2, wvalue);
wvalue = *((u16 *) & p_str[(index - 1) / 8]);
wvalue = (wvalue >> ((index - 1) % 8)) & mask;
index += window_size;
booth_recode_w7(&sign3, &digit3, wvalue);
ecp_nistz256_avx2_multi_select_w7(point_arr,
preComputedTable[4 * i],
digit0, digit1, digit2, digit3);
ecp_nistz256_neg(tmp, point_arr[0].Y);
copy_conditional(point_arr[0].Y, tmp, sign0);
ecp_nistz256_neg(tmp, point_arr[1].Y);
copy_conditional(point_arr[1].Y, tmp, sign1);
ecp_nistz256_neg(tmp, point_arr[2].Y);
copy_conditional(point_arr[2].Y, tmp, sign2);
ecp_nistz256_neg(tmp, point_arr[3].Y);
copy_conditional(point_arr[3].Y, tmp, sign3);
ecp_nistz256_avx2_transpose_convert(bX4, point_arr);
ecp_nistz256_avx2_to_mont(bX4, bX4);
ecp_nistz256_avx2_to_mont(&bX4[4 * 9], &bX4[4 * 9]);
ecp_nistz256_avx2_point_add_affine_x4(aX4, aX4, bX4);
}
ecp_nistz256_avx2_from_mont(&aX4[4 * 9 * 0], &aX4[4 * 9 * 0]);
ecp_nistz256_avx2_from_mont(&aX4[4 * 9 * 1], &aX4[4 * 9 * 1]);
ecp_nistz256_avx2_from_mont(&aX4[4 * 9 * 2], &aX4[4 * 9 * 2]);
ecp_nistz256_avx2_convert_transpose_back(res_point_arr, aX4);
/* Last window is performed serially */
wvalue = *((u16 *) & p_str[(index - 1) / 8]);
wvalue = (wvalue >> ((index - 1) % 8)) & mask;
booth_recode_w7(&sign0, &digit0, wvalue);
ecp_nistz256_avx2_select_w7((P256_POINT_AFFINE *) r,
preComputedTable[36], digit0);
ecp_nistz256_neg(tmp, r->Y);
copy_conditional(r->Y, tmp, sign0);
memcpy(r->Z, ONE, sizeof(ONE));
/* Sum the four windows */
ecp_nistz256_point_add(r, r, &res_point_arr[0]);
ecp_nistz256_point_add(r, r, &res_point_arr[1]);
ecp_nistz256_point_add(r, r, &res_point_arr[2]);
ecp_nistz256_point_add(r, r, &res_point_arr[3]);
}
# endif
#endif
static int ecp_nistz256_set_from_affine(EC_POINT *out, const EC_GROUP *group,
const P256_POINT_AFFINE *in,
BN_CTX *ctx)
{
BIGNUM x, y;
BN_ULONG d_x[P256_LIMBS], d_y[P256_LIMBS];
int ret = 0;
memcpy(d_x, in->X, sizeof(d_x));
x.d = d_x;
x.dmax = x.top = P256_LIMBS;
x.neg = 0;
x.flags = BN_FLG_STATIC_DATA;
memcpy(d_y, in->Y, sizeof(d_y));
y.d = d_y;
y.dmax = y.top = P256_LIMBS;
y.neg = 0;
y.flags = BN_FLG_STATIC_DATA;
ret = EC_POINT_set_affine_coordinates_GFp(group, out, &x, &y, ctx);
return ret;
}
/* r = scalar*G + sum(scalars[i]*points[i]) */
static int ecp_nistz256_points_mul(const EC_GROUP *group,
EC_POINT *r,
const BIGNUM *scalar,
size_t num,
const EC_POINT *points[],
const BIGNUM *scalars[], BN_CTX *ctx)
{
int i = 0, ret = 0, no_precomp_for_generator = 0, p_is_infinity = 0;
size_t j;
unsigned char p_str[33] = { 0 };
const PRECOMP256_ROW *preComputedTable = NULL;
const EC_PRE_COMP *pre_comp = NULL;
const EC_POINT *generator = NULL;
unsigned int index = 0;
BN_CTX *new_ctx = NULL;
const BIGNUM **new_scalars = NULL;
const EC_POINT **new_points = NULL;
const unsigned int window_size = 7;
const unsigned int mask = (1 << (window_size + 1)) - 1;
unsigned int wvalue;
ALIGN32 union {
P256_POINT p;
P256_POINT_AFFINE a;
} t, p;
BIGNUM *tmp_scalar;
if (group->meth != r->meth) {
ECerr(EC_F_ECP_NISTZ256_POINTS_MUL, EC_R_INCOMPATIBLE_OBJECTS);
return 0;
}
if ((scalar == NULL) && (num == 0))
return EC_POINT_set_to_infinity(group, r);
for (j = 0; j < num; j++) {
if (group->meth != points[j]->meth) {
ECerr(EC_F_ECP_NISTZ256_POINTS_MUL, EC_R_INCOMPATIBLE_OBJECTS);
return 0;
}
}
if (ctx == NULL) {
ctx = new_ctx = BN_CTX_new();
if (ctx == NULL)
goto err;
}
BN_CTX_start(ctx);
if (scalar) {
generator = EC_GROUP_get0_generator(group);
if (generator == NULL) {
ECerr(EC_F_ECP_NISTZ256_POINTS_MUL, EC_R_UNDEFINED_GENERATOR);
goto err;
}
/* look if we can use precomputed multiples of generator */
pre_comp =
EC_EX_DATA_get_data(group->extra_data, ecp_nistz256_pre_comp_dup,
ecp_nistz256_pre_comp_free,
ecp_nistz256_pre_comp_clear_free);
if (pre_comp) {
/*
* If there is a precomputed table for the generator, check that
* it was generated with the same generator.
*/
EC_POINT *pre_comp_generator = EC_POINT_new(group);
if (pre_comp_generator == NULL)
goto err;
if (!ecp_nistz256_set_from_affine
(pre_comp_generator, group, pre_comp->precomp[0], ctx)) {
EC_POINT_free(pre_comp_generator);
goto err;
}
if (0 == EC_POINT_cmp(group, generator, pre_comp_generator, ctx))
preComputedTable = (const PRECOMP256_ROW *)pre_comp->precomp;
EC_POINT_free(pre_comp_generator);
}
if (preComputedTable == NULL && ecp_nistz256_is_affine_G(generator)) {
/*
* If there is no precomputed data, but the generator
* is the default, a hardcoded table of precomputed
* data is used. This is because applications, such as
* Apache, do not use EC_KEY_precompute_mult.
*/
preComputedTable = (const PRECOMP256_ROW *)ecp_nistz256_precomputed;
}
if (preComputedTable) {
if ((BN_num_bits(scalar) > 256)
|| BN_is_negative(scalar)) {
if ((tmp_scalar = BN_CTX_get(ctx)) == NULL)
goto err;
if (!BN_nnmod(tmp_scalar, scalar, &group->order, ctx)) {
ECerr(EC_F_ECP_NISTZ256_POINTS_MUL, ERR_R_BN_LIB);
goto err;
}
scalar = tmp_scalar;
}
for (i = 0; i < scalar->top * BN_BYTES; i += BN_BYTES) {
BN_ULONG d = scalar->d[i / BN_BYTES];
p_str[i + 0] = d & 0xff;
p_str[i + 1] = (d >> 8) & 0xff;
p_str[i + 2] = (d >> 16) & 0xff;
p_str[i + 3] = (d >>= 24) & 0xff;
if (BN_BYTES == 8) {
d >>= 8;
p_str[i + 4] = d & 0xff;
p_str[i + 5] = (d >> 8) & 0xff;
p_str[i + 6] = (d >> 16) & 0xff;
p_str[i + 7] = (d >> 24) & 0xff;
}
}
for (; i < 33; i++)
p_str[i] = 0;
#if defined(ECP_NISTZ256_AVX2)
if (ecp_nistz_avx2_eligible()) {
ecp_nistz256_avx2_mul_g(&p.p, p_str, preComputedTable);
} else
#endif
{
BN_ULONG infty;
/* First window */
wvalue = (p_str[0] << 1) & mask;
index += window_size;
wvalue = _booth_recode_w7(wvalue);
ecp_nistz256_select_w7(&p.a, preComputedTable[0], wvalue >> 1);
ecp_nistz256_neg(p.p.Z, p.p.Y);
copy_conditional(p.p.Y, p.p.Z, wvalue & 1);
/*
* Since affine infinity is encoded as (0,0) and
* Jacobian ias (,,0), we need to harmonize them
* by assigning "one" or zero to Z.
*/
infty = (p.p.X[0] | p.p.X[1] | p.p.X[2] | p.p.X[3] |
p.p.Y[0] | p.p.Y[1] | p.p.Y[2] | p.p.Y[3]);
if (P256_LIMBS == 8)
infty |= (p.p.X[4] | p.p.X[5] | p.p.X[6] | p.p.X[7] |
p.p.Y[4] | p.p.Y[5] | p.p.Y[6] | p.p.Y[7]);
infty = 0 - is_zero(infty);
infty = ~infty;
p.p.Z[0] = ONE[0] & infty;
p.p.Z[1] = ONE[1] & infty;
p.p.Z[2] = ONE[2] & infty;
p.p.Z[3] = ONE[3] & infty;
if (P256_LIMBS == 8) {
p.p.Z[4] = ONE[4] & infty;
p.p.Z[5] = ONE[5] & infty;
p.p.Z[6] = ONE[6] & infty;
p.p.Z[7] = ONE[7] & infty;
}
for (i = 1; i < 37; i++) {
unsigned int off = (index - 1) / 8;
wvalue = p_str[off] | p_str[off + 1] << 8;
wvalue = (wvalue >> ((index - 1) % 8)) & mask;
index += window_size;
wvalue = _booth_recode_w7(wvalue);
ecp_nistz256_select_w7(&t.a,
preComputedTable[i], wvalue >> 1);
ecp_nistz256_neg(t.p.Z, t.a.Y);
copy_conditional(t.a.Y, t.p.Z, wvalue & 1);
ecp_nistz256_point_add_affine(&p.p, &p.p, &t.a);
}
}
} else {
p_is_infinity = 1;
no_precomp_for_generator = 1;
}
} else
p_is_infinity = 1;
if (no_precomp_for_generator) {
/*
* Without a precomputed table for the generator, it has to be
* handled like a normal point.
*/
new_scalars = OPENSSL_malloc((num + 1) * sizeof(BIGNUM *));
if (!new_scalars) {
ECerr(EC_F_ECP_NISTZ256_POINTS_MUL, ERR_R_MALLOC_FAILURE);
goto err;
}
new_points = OPENSSL_malloc((num + 1) * sizeof(EC_POINT *));
if (!new_points) {
ECerr(EC_F_ECP_NISTZ256_POINTS_MUL, ERR_R_MALLOC_FAILURE);
goto err;
}
memcpy(new_scalars, scalars, num * sizeof(BIGNUM *));
new_scalars[num] = scalar;
memcpy(new_points, points, num * sizeof(EC_POINT *));
new_points[num] = generator;
scalars = new_scalars;
points = new_points;
num++;
}
if (num) {
P256_POINT *out = &t.p;
if (p_is_infinity)
out = &p.p;
if (!ecp_nistz256_windowed_mul(group, out, scalars, points, num, ctx))
goto err;
if (!p_is_infinity)
ecp_nistz256_point_add(&p.p, &p.p, out);
}
/* Not constant-time, but we're only operating on the public output. */
if (!ecp_nistz256_set_words(&r->X, p.p.X) ||
!ecp_nistz256_set_words(&r->Y, p.p.Y) ||
!ecp_nistz256_set_words(&r->Z, p.p.Z)) {
goto err;
}
r->Z_is_one = is_one(&r->Z) & 1;
ret = 1;
err:
if (ctx)
BN_CTX_end(ctx);
BN_CTX_free(new_ctx);
if (new_points)
OPENSSL_free(new_points);
if (new_scalars)
OPENSSL_free(new_scalars);
return ret;
}
static int ecp_nistz256_get_affine(const EC_GROUP *group,
const EC_POINT *point,
BIGNUM *x, BIGNUM *y, BN_CTX *ctx)
{
BN_ULONG z_inv2[P256_LIMBS];
BN_ULONG z_inv3[P256_LIMBS];
BN_ULONG x_aff[P256_LIMBS];
BN_ULONG y_aff[P256_LIMBS];
BN_ULONG point_x[P256_LIMBS], point_y[P256_LIMBS], point_z[P256_LIMBS];
BN_ULONG x_ret[P256_LIMBS], y_ret[P256_LIMBS];
if (EC_POINT_is_at_infinity(group, point)) {
ECerr(EC_F_ECP_NISTZ256_GET_AFFINE, EC_R_POINT_AT_INFINITY);
return 0;
}
if (!ecp_nistz256_bignum_to_field_elem(point_x, &point->X) ||
!ecp_nistz256_bignum_to_field_elem(point_y, &point->Y) ||
!ecp_nistz256_bignum_to_field_elem(point_z, &point->Z)) {
ECerr(EC_F_ECP_NISTZ256_GET_AFFINE, EC_R_COORDINATES_OUT_OF_RANGE);
return 0;
}
ecp_nistz256_mod_inverse(z_inv3, point_z);
ecp_nistz256_sqr_mont(z_inv2, z_inv3);
ecp_nistz256_mul_mont(x_aff, z_inv2, point_x);
if (x != NULL) {
ecp_nistz256_from_mont(x_ret, x_aff);
if (!ecp_nistz256_set_words(x, x_ret))
return 0;
}
if (y != NULL) {
ecp_nistz256_mul_mont(z_inv3, z_inv3, z_inv2);
ecp_nistz256_mul_mont(y_aff, z_inv3, point_y);
ecp_nistz256_from_mont(y_ret, y_aff);
if (!ecp_nistz256_set_words(y, y_ret))
return 0;
}
return 1;
}
static EC_PRE_COMP *ecp_nistz256_pre_comp_new(const EC_GROUP *group)
{
EC_PRE_COMP *ret = NULL;
if (!group)
return NULL;
ret = (EC_PRE_COMP *)OPENSSL_malloc(sizeof(EC_PRE_COMP));
if (!ret) {
ECerr(EC_F_ECP_NISTZ256_PRE_COMP_NEW, ERR_R_MALLOC_FAILURE);
return ret;
}
ret->group = group;
ret->w = 6; /* default */
ret->precomp = NULL;
ret->precomp_storage = NULL;
ret->references = 1;
return ret;
}
static void *ecp_nistz256_pre_comp_dup(void *src_)
{
EC_PRE_COMP *src = src_;
/* no need to actually copy, these objects never change! */
CRYPTO_add(&src->references, 1, CRYPTO_LOCK_EC_PRE_COMP);
return src_;
}
static void ecp_nistz256_pre_comp_free(void *pre_)
{
int i;
EC_PRE_COMP *pre = pre_;
if (!pre)
return;
i = CRYPTO_add(&pre->references, -1, CRYPTO_LOCK_EC_PRE_COMP);
if (i > 0)
return;
if (pre->precomp_storage)
OPENSSL_free(pre->precomp_storage);
OPENSSL_free(pre);
}
static void ecp_nistz256_pre_comp_clear_free(void *pre_)
{
int i;
EC_PRE_COMP *pre = pre_;
if (!pre)
return;
i = CRYPTO_add(&pre->references, -1, CRYPTO_LOCK_EC_PRE_COMP);
if (i > 0)
return;
if (pre->precomp_storage) {
OPENSSL_cleanse(pre->precomp,
32 * sizeof(unsigned char) * (1 << pre->w) * 2 * 37);
OPENSSL_free(pre->precomp_storage);
}
- OPENSSL_cleanse(pre, sizeof *pre);
+ OPENSSL_cleanse(pre, sizeof(*pre));
OPENSSL_free(pre);
}
static int ecp_nistz256_window_have_precompute_mult(const EC_GROUP *group)
{
/* There is a hard-coded table for the default generator. */
const EC_POINT *generator = EC_GROUP_get0_generator(group);
if (generator != NULL && ecp_nistz256_is_affine_G(generator)) {
/* There is a hard-coded table for the default generator. */
return 1;
}
return EC_EX_DATA_get_data(group->extra_data, ecp_nistz256_pre_comp_dup,
ecp_nistz256_pre_comp_free,
ecp_nistz256_pre_comp_clear_free) != NULL;
}
const EC_METHOD *EC_GFp_nistz256_method(void)
{
static const EC_METHOD ret = {
EC_FLAGS_DEFAULT_OCT,
NID_X9_62_prime_field,
ec_GFp_mont_group_init,
ec_GFp_mont_group_finish,
ec_GFp_mont_group_clear_finish,
ec_GFp_mont_group_copy,
ec_GFp_mont_group_set_curve,
ec_GFp_simple_group_get_curve,
ec_GFp_simple_group_get_degree,
ec_GFp_simple_group_check_discriminant,
ec_GFp_simple_point_init,
ec_GFp_simple_point_finish,
ec_GFp_simple_point_clear_finish,
ec_GFp_simple_point_copy,
ec_GFp_simple_point_set_to_infinity,
ec_GFp_simple_set_Jprojective_coordinates_GFp,
ec_GFp_simple_get_Jprojective_coordinates_GFp,
ec_GFp_simple_point_set_affine_coordinates,
ecp_nistz256_get_affine,
0, 0, 0,
ec_GFp_simple_add,
ec_GFp_simple_dbl,
ec_GFp_simple_invert,
ec_GFp_simple_is_at_infinity,
ec_GFp_simple_is_on_curve,
ec_GFp_simple_cmp,
ec_GFp_simple_make_affine,
ec_GFp_simple_points_make_affine,
ecp_nistz256_points_mul, /* mul */
ecp_nistz256_mult_precompute, /* precompute_mult */
ecp_nistz256_window_have_precompute_mult, /* have_precompute_mult */
ec_GFp_mont_field_mul,
ec_GFp_mont_field_sqr,
0, /* field_div */
ec_GFp_mont_field_encode,
ec_GFp_mont_field_decode,
ec_GFp_mont_field_set_to_one
};
return &ret;
}
diff --git a/crypto/ec/ecp_smpl.c b/crypto/ec/ecp_smpl.c
index 2b848216d78c..e94a7d49368d 100644
--- a/crypto/ec/ecp_smpl.c
+++ b/crypto/ec/ecp_smpl.c
@@ -1,1418 +1,1418 @@
/* crypto/ec/ecp_smpl.c */
/*
* Includes code written by Lenka Fibikova <fibikova@exp-math.uni-essen.de>
* for the OpenSSL project. Includes code written by Bodo Moeller for the
* OpenSSL project.
*/
/* ====================================================================
* Copyright (c) 1998-2002 The OpenSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* openssl-core@openssl.org.
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.openssl.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*
* This product includes cryptographic software written by Eric Young
* (eay@cryptsoft.com). This product includes software written by Tim
* Hudson (tjh@cryptsoft.com).
*
*/
/* ====================================================================
* Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
* Portions of this software developed by SUN MICROSYSTEMS, INC.,
* and contributed to the OpenSSL project.
*/
#include <openssl/err.h>
#include <openssl/symhacks.h>
#ifdef OPENSSL_FIPS
# include <openssl/fips.h>
#endif
#include "ec_lcl.h"
const EC_METHOD *EC_GFp_simple_method(void)
{
static const EC_METHOD ret = {
EC_FLAGS_DEFAULT_OCT,
NID_X9_62_prime_field,
ec_GFp_simple_group_init,
ec_GFp_simple_group_finish,
ec_GFp_simple_group_clear_finish,
ec_GFp_simple_group_copy,
ec_GFp_simple_group_set_curve,
ec_GFp_simple_group_get_curve,
ec_GFp_simple_group_get_degree,
ec_GFp_simple_group_check_discriminant,
ec_GFp_simple_point_init,
ec_GFp_simple_point_finish,
ec_GFp_simple_point_clear_finish,
ec_GFp_simple_point_copy,
ec_GFp_simple_point_set_to_infinity,
ec_GFp_simple_set_Jprojective_coordinates_GFp,
ec_GFp_simple_get_Jprojective_coordinates_GFp,
ec_GFp_simple_point_set_affine_coordinates,
ec_GFp_simple_point_get_affine_coordinates,
0, 0, 0,
ec_GFp_simple_add,
ec_GFp_simple_dbl,
ec_GFp_simple_invert,
ec_GFp_simple_is_at_infinity,
ec_GFp_simple_is_on_curve,
ec_GFp_simple_cmp,
ec_GFp_simple_make_affine,
ec_GFp_simple_points_make_affine,
0 /* mul */ ,
0 /* precompute_mult */ ,
0 /* have_precompute_mult */ ,
ec_GFp_simple_field_mul,
ec_GFp_simple_field_sqr,
0 /* field_div */ ,
0 /* field_encode */ ,
0 /* field_decode */ ,
0 /* field_set_to_one */
};
#ifdef OPENSSL_FIPS
if (FIPS_mode())
return fips_ec_gfp_simple_method();
#endif
return &ret;
}
/*
* Most method functions in this file are designed to work with
* non-trivial representations of field elements if necessary
* (see ecp_mont.c): while standard modular addition and subtraction
* are used, the field_mul and field_sqr methods will be used for
* multiplication, and field_encode and field_decode (if defined)
* will be used for converting between representations.
*
* Functions ec_GFp_simple_points_make_affine() and
* ec_GFp_simple_point_get_affine_coordinates() specifically assume
* that if a non-trivial representation is used, it is a Montgomery
* representation (i.e. 'encoding' means multiplying by some factor R).
*/
int ec_GFp_simple_group_init(EC_GROUP *group)
{
BN_init(&group->field);
BN_init(&group->a);
BN_init(&group->b);
group->a_is_minus3 = 0;
return 1;
}
void ec_GFp_simple_group_finish(EC_GROUP *group)
{
BN_free(&group->field);
BN_free(&group->a);
BN_free(&group->b);
}
void ec_GFp_simple_group_clear_finish(EC_GROUP *group)
{
BN_clear_free(&group->field);
BN_clear_free(&group->a);
BN_clear_free(&group->b);
}
int ec_GFp_simple_group_copy(EC_GROUP *dest, const EC_GROUP *src)
{
if (!BN_copy(&dest->field, &src->field))
return 0;
if (!BN_copy(&dest->a, &src->a))
return 0;
if (!BN_copy(&dest->b, &src->b))
return 0;
dest->a_is_minus3 = src->a_is_minus3;
return 1;
}
int ec_GFp_simple_group_set_curve(EC_GROUP *group,
const BIGNUM *p, const BIGNUM *a,
const BIGNUM *b, BN_CTX *ctx)
{
int ret = 0;
BN_CTX *new_ctx = NULL;
BIGNUM *tmp_a;
/* p must be a prime > 3 */
if (BN_num_bits(p) <= 2 || !BN_is_odd(p)) {
ECerr(EC_F_EC_GFP_SIMPLE_GROUP_SET_CURVE, EC_R_INVALID_FIELD);
return 0;
}
if (ctx == NULL) {
ctx = new_ctx = BN_CTX_new();
if (ctx == NULL)
return 0;
}
BN_CTX_start(ctx);
tmp_a = BN_CTX_get(ctx);
if (tmp_a == NULL)
goto err;
/* group->field */
if (!BN_copy(&group->field, p))
goto err;
BN_set_negative(&group->field, 0);
/* group->a */
if (!BN_nnmod(tmp_a, a, p, ctx))
goto err;
if (group->meth->field_encode) {
if (!group->meth->field_encode(group, &group->a, tmp_a, ctx))
goto err;
} else if (!BN_copy(&group->a, tmp_a))
goto err;
/* group->b */
if (!BN_nnmod(&group->b, b, p, ctx))
goto err;
if (group->meth->field_encode)
if (!group->meth->field_encode(group, &group->b, &group->b, ctx))
goto err;
/* group->a_is_minus3 */
if (!BN_add_word(tmp_a, 3))
goto err;
group->a_is_minus3 = (0 == BN_cmp(tmp_a, &group->field));
ret = 1;
err:
BN_CTX_end(ctx);
if (new_ctx != NULL)
BN_CTX_free(new_ctx);
return ret;
}
int ec_GFp_simple_group_get_curve(const EC_GROUP *group, BIGNUM *p, BIGNUM *a,
BIGNUM *b, BN_CTX *ctx)
{
int ret = 0;
BN_CTX *new_ctx = NULL;
if (p != NULL) {
if (!BN_copy(p, &group->field))
return 0;
}
if (a != NULL || b != NULL) {
if (group->meth->field_decode) {
if (ctx == NULL) {
ctx = new_ctx = BN_CTX_new();
if (ctx == NULL)
return 0;
}
if (a != NULL) {
if (!group->meth->field_decode(group, a, &group->a, ctx))
goto err;
}
if (b != NULL) {
if (!group->meth->field_decode(group, b, &group->b, ctx))
goto err;
}
} else {
if (a != NULL) {
if (!BN_copy(a, &group->a))
goto err;
}
if (b != NULL) {
if (!BN_copy(b, &group->b))
goto err;
}
}
}
ret = 1;
err:
if (new_ctx)
BN_CTX_free(new_ctx);
return ret;
}
int ec_GFp_simple_group_get_degree(const EC_GROUP *group)
{
return BN_num_bits(&group->field);
}
int ec_GFp_simple_group_check_discriminant(const EC_GROUP *group, BN_CTX *ctx)
{
int ret = 0;
BIGNUM *a, *b, *order, *tmp_1, *tmp_2;
const BIGNUM *p = &group->field;
BN_CTX *new_ctx = NULL;
if (ctx == NULL) {
ctx = new_ctx = BN_CTX_new();
if (ctx == NULL) {
ECerr(EC_F_EC_GFP_SIMPLE_GROUP_CHECK_DISCRIMINANT,
ERR_R_MALLOC_FAILURE);
goto err;
}
}
BN_CTX_start(ctx);
a = BN_CTX_get(ctx);
b = BN_CTX_get(ctx);
tmp_1 = BN_CTX_get(ctx);
tmp_2 = BN_CTX_get(ctx);
order = BN_CTX_get(ctx);
if (order == NULL)
goto err;
if (group->meth->field_decode) {
if (!group->meth->field_decode(group, a, &group->a, ctx))
goto err;
if (!group->meth->field_decode(group, b, &group->b, ctx))
goto err;
} else {
if (!BN_copy(a, &group->a))
goto err;
if (!BN_copy(b, &group->b))
goto err;
}
/*-
* check the discriminant:
* y^2 = x^3 + a*x + b is an elliptic curve <=> 4*a^3 + 27*b^2 != 0 (mod p)
* 0 =< a, b < p
*/
if (BN_is_zero(a)) {
if (BN_is_zero(b))
goto err;
} else if (!BN_is_zero(b)) {
if (!BN_mod_sqr(tmp_1, a, p, ctx))
goto err;
if (!BN_mod_mul(tmp_2, tmp_1, a, p, ctx))
goto err;
if (!BN_lshift(tmp_1, tmp_2, 2))
goto err;
/* tmp_1 = 4*a^3 */
if (!BN_mod_sqr(tmp_2, b, p, ctx))
goto err;
if (!BN_mul_word(tmp_2, 27))
goto err;
/* tmp_2 = 27*b^2 */
if (!BN_mod_add(a, tmp_1, tmp_2, p, ctx))
goto err;
if (BN_is_zero(a))
goto err;
}
ret = 1;
err:
if (ctx != NULL)
BN_CTX_end(ctx);
if (new_ctx != NULL)
BN_CTX_free(new_ctx);
return ret;
}
int ec_GFp_simple_point_init(EC_POINT *point)
{
BN_init(&point->X);
BN_init(&point->Y);
BN_init(&point->Z);
point->Z_is_one = 0;
return 1;
}
void ec_GFp_simple_point_finish(EC_POINT *point)
{
BN_free(&point->X);
BN_free(&point->Y);
BN_free(&point->Z);
}
void ec_GFp_simple_point_clear_finish(EC_POINT *point)
{
BN_clear_free(&point->X);
BN_clear_free(&point->Y);
BN_clear_free(&point->Z);
point->Z_is_one = 0;
}
int ec_GFp_simple_point_copy(EC_POINT *dest, const EC_POINT *src)
{
if (!BN_copy(&dest->X, &src->X))
return 0;
if (!BN_copy(&dest->Y, &src->Y))
return 0;
if (!BN_copy(&dest->Z, &src->Z))
return 0;
dest->Z_is_one = src->Z_is_one;
return 1;
}
int ec_GFp_simple_point_set_to_infinity(const EC_GROUP *group,
EC_POINT *point)
{
point->Z_is_one = 0;
BN_zero(&point->Z);
return 1;
}
int ec_GFp_simple_set_Jprojective_coordinates_GFp(const EC_GROUP *group,
EC_POINT *point,
const BIGNUM *x,
const BIGNUM *y,
const BIGNUM *z,
BN_CTX *ctx)
{
BN_CTX *new_ctx = NULL;
int ret = 0;
if (ctx == NULL) {
ctx = new_ctx = BN_CTX_new();
if (ctx == NULL)
return 0;
}
if (x != NULL) {
if (!BN_nnmod(&point->X, x, &group->field, ctx))
goto err;
if (group->meth->field_encode) {
if (!group->meth->field_encode(group, &point->X, &point->X, ctx))
goto err;
}
}
if (y != NULL) {
if (!BN_nnmod(&point->Y, y, &group->field, ctx))
goto err;
if (group->meth->field_encode) {
if (!group->meth->field_encode(group, &point->Y, &point->Y, ctx))
goto err;
}
}
if (z != NULL) {
int Z_is_one;
if (!BN_nnmod(&point->Z, z, &group->field, ctx))
goto err;
Z_is_one = BN_is_one(&point->Z);
if (group->meth->field_encode) {
if (Z_is_one && (group->meth->field_set_to_one != 0)) {
if (!group->meth->field_set_to_one(group, &point->Z, ctx))
goto err;
} else {
if (!group->
meth->field_encode(group, &point->Z, &point->Z, ctx))
goto err;
}
}
point->Z_is_one = Z_is_one;
}
ret = 1;
err:
if (new_ctx != NULL)
BN_CTX_free(new_ctx);
return ret;
}
int ec_GFp_simple_get_Jprojective_coordinates_GFp(const EC_GROUP *group,
const EC_POINT *point,
BIGNUM *x, BIGNUM *y,
BIGNUM *z, BN_CTX *ctx)
{
BN_CTX *new_ctx = NULL;
int ret = 0;
if (group->meth->field_decode != 0) {
if (ctx == NULL) {
ctx = new_ctx = BN_CTX_new();
if (ctx == NULL)
return 0;
}
if (x != NULL) {
if (!group->meth->field_decode(group, x, &point->X, ctx))
goto err;
}
if (y != NULL) {
if (!group->meth->field_decode(group, y, &point->Y, ctx))
goto err;
}
if (z != NULL) {
if (!group->meth->field_decode(group, z, &point->Z, ctx))
goto err;
}
} else {
if (x != NULL) {
if (!BN_copy(x, &point->X))
goto err;
}
if (y != NULL) {
if (!BN_copy(y, &point->Y))
goto err;
}
if (z != NULL) {
if (!BN_copy(z, &point->Z))
goto err;
}
}
ret = 1;
err:
if (new_ctx != NULL)
BN_CTX_free(new_ctx);
return ret;
}
int ec_GFp_simple_point_set_affine_coordinates(const EC_GROUP *group,
EC_POINT *point,
const BIGNUM *x,
const BIGNUM *y, BN_CTX *ctx)
{
if (x == NULL || y == NULL) {
/*
* unlike for projective coordinates, we do not tolerate this
*/
ECerr(EC_F_EC_GFP_SIMPLE_POINT_SET_AFFINE_COORDINATES,
ERR_R_PASSED_NULL_PARAMETER);
return 0;
}
return EC_POINT_set_Jprojective_coordinates_GFp(group, point, x, y,
BN_value_one(), ctx);
}
int ec_GFp_simple_point_get_affine_coordinates(const EC_GROUP *group,
const EC_POINT *point,
BIGNUM *x, BIGNUM *y,
BN_CTX *ctx)
{
BN_CTX *new_ctx = NULL;
BIGNUM *Z, *Z_1, *Z_2, *Z_3;
const BIGNUM *Z_;
int ret = 0;
if (EC_POINT_is_at_infinity(group, point)) {
ECerr(EC_F_EC_GFP_SIMPLE_POINT_GET_AFFINE_COORDINATES,
EC_R_POINT_AT_INFINITY);
return 0;
}
if (ctx == NULL) {
ctx = new_ctx = BN_CTX_new();
if (ctx == NULL)
return 0;
}
BN_CTX_start(ctx);
Z = BN_CTX_get(ctx);
Z_1 = BN_CTX_get(ctx);
Z_2 = BN_CTX_get(ctx);
Z_3 = BN_CTX_get(ctx);
if (Z_3 == NULL)
goto err;
/* transform (X, Y, Z) into (x, y) := (X/Z^2, Y/Z^3) */
if (group->meth->field_decode) {
if (!group->meth->field_decode(group, Z, &point->Z, ctx))
goto err;
Z_ = Z;
} else {
Z_ = &point->Z;
}
if (BN_is_one(Z_)) {
if (group->meth->field_decode) {
if (x != NULL) {
if (!group->meth->field_decode(group, x, &point->X, ctx))
goto err;
}
if (y != NULL) {
if (!group->meth->field_decode(group, y, &point->Y, ctx))
goto err;
}
} else {
if (x != NULL) {
if (!BN_copy(x, &point->X))
goto err;
}
if (y != NULL) {
if (!BN_copy(y, &point->Y))
goto err;
}
}
} else {
if (!BN_mod_inverse(Z_1, Z_, &group->field, ctx)) {
ECerr(EC_F_EC_GFP_SIMPLE_POINT_GET_AFFINE_COORDINATES,
ERR_R_BN_LIB);
goto err;
}
if (group->meth->field_encode == 0) {
/* field_sqr works on standard representation */
if (!group->meth->field_sqr(group, Z_2, Z_1, ctx))
goto err;
} else {
if (!BN_mod_sqr(Z_2, Z_1, &group->field, ctx))
goto err;
}
if (x != NULL) {
/*
* in the Montgomery case, field_mul will cancel out Montgomery
* factor in X:
*/
if (!group->meth->field_mul(group, x, &point->X, Z_2, ctx))
goto err;
}
if (y != NULL) {
if (group->meth->field_encode == 0) {
/*
* field_mul works on standard representation
*/
if (!group->meth->field_mul(group, Z_3, Z_2, Z_1, ctx))
goto err;
} else {
if (!BN_mod_mul(Z_3, Z_2, Z_1, &group->field, ctx))
goto err;
}
/*
* in the Montgomery case, field_mul will cancel out Montgomery
* factor in Y:
*/
if (!group->meth->field_mul(group, y, &point->Y, Z_3, ctx))
goto err;
}
}
ret = 1;
err:
BN_CTX_end(ctx);
if (new_ctx != NULL)
BN_CTX_free(new_ctx);
return ret;
}
int ec_GFp_simple_add(const EC_GROUP *group, EC_POINT *r, const EC_POINT *a,
const EC_POINT *b, BN_CTX *ctx)
{
int (*field_mul) (const EC_GROUP *, BIGNUM *, const BIGNUM *,
const BIGNUM *, BN_CTX *);
int (*field_sqr) (const EC_GROUP *, BIGNUM *, const BIGNUM *, BN_CTX *);
const BIGNUM *p;
BN_CTX *new_ctx = NULL;
BIGNUM *n0, *n1, *n2, *n3, *n4, *n5, *n6;
int ret = 0;
if (a == b)
return EC_POINT_dbl(group, r, a, ctx);
if (EC_POINT_is_at_infinity(group, a))
return EC_POINT_copy(r, b);
if (EC_POINT_is_at_infinity(group, b))
return EC_POINT_copy(r, a);
field_mul = group->meth->field_mul;
field_sqr = group->meth->field_sqr;
p = &group->field;
if (ctx == NULL) {
ctx = new_ctx = BN_CTX_new();
if (ctx == NULL)
return 0;
}
BN_CTX_start(ctx);
n0 = BN_CTX_get(ctx);
n1 = BN_CTX_get(ctx);
n2 = BN_CTX_get(ctx);
n3 = BN_CTX_get(ctx);
n4 = BN_CTX_get(ctx);
n5 = BN_CTX_get(ctx);
n6 = BN_CTX_get(ctx);
if (n6 == NULL)
goto end;
/*
* Note that in this function we must not read components of 'a' or 'b'
* once we have written the corresponding components of 'r'. ('r' might
* be one of 'a' or 'b'.)
*/
/* n1, n2 */
if (b->Z_is_one) {
if (!BN_copy(n1, &a->X))
goto end;
if (!BN_copy(n2, &a->Y))
goto end;
/* n1 = X_a */
/* n2 = Y_a */
} else {
if (!field_sqr(group, n0, &b->Z, ctx))
goto end;
if (!field_mul(group, n1, &a->X, n0, ctx))
goto end;
/* n1 = X_a * Z_b^2 */
if (!field_mul(group, n0, n0, &b->Z, ctx))
goto end;
if (!field_mul(group, n2, &a->Y, n0, ctx))
goto end;
/* n2 = Y_a * Z_b^3 */
}
/* n3, n4 */
if (a->Z_is_one) {
if (!BN_copy(n3, &b->X))
goto end;
if (!BN_copy(n4, &b->Y))
goto end;
/* n3 = X_b */
/* n4 = Y_b */
} else {
if (!field_sqr(group, n0, &a->Z, ctx))
goto end;
if (!field_mul(group, n3, &b->X, n0, ctx))
goto end;
/* n3 = X_b * Z_a^2 */
if (!field_mul(group, n0, n0, &a->Z, ctx))
goto end;
if (!field_mul(group, n4, &b->Y, n0, ctx))
goto end;
/* n4 = Y_b * Z_a^3 */
}
/* n5, n6 */
if (!BN_mod_sub_quick(n5, n1, n3, p))
goto end;
if (!BN_mod_sub_quick(n6, n2, n4, p))
goto end;
/* n5 = n1 - n3 */
/* n6 = n2 - n4 */
if (BN_is_zero(n5)) {
if (BN_is_zero(n6)) {
/* a is the same point as b */
BN_CTX_end(ctx);
ret = EC_POINT_dbl(group, r, a, ctx);
ctx = NULL;
goto end;
} else {
/* a is the inverse of b */
BN_zero(&r->Z);
r->Z_is_one = 0;
ret = 1;
goto end;
}
}
/* 'n7', 'n8' */
if (!BN_mod_add_quick(n1, n1, n3, p))
goto end;
if (!BN_mod_add_quick(n2, n2, n4, p))
goto end;
/* 'n7' = n1 + n3 */
/* 'n8' = n2 + n4 */
/* Z_r */
if (a->Z_is_one && b->Z_is_one) {
if (!BN_copy(&r->Z, n5))
goto end;
} else {
if (a->Z_is_one) {
if (!BN_copy(n0, &b->Z))
goto end;
} else if (b->Z_is_one) {
if (!BN_copy(n0, &a->Z))
goto end;
} else {
if (!field_mul(group, n0, &a->Z, &b->Z, ctx))
goto end;
}
if (!field_mul(group, &r->Z, n0, n5, ctx))
goto end;
}
r->Z_is_one = 0;
/* Z_r = Z_a * Z_b * n5 */
/* X_r */
if (!field_sqr(group, n0, n6, ctx))
goto end;
if (!field_sqr(group, n4, n5, ctx))
goto end;
if (!field_mul(group, n3, n1, n4, ctx))
goto end;
if (!BN_mod_sub_quick(&r->X, n0, n3, p))
goto end;
/* X_r = n6^2 - n5^2 * 'n7' */
/* 'n9' */
if (!BN_mod_lshift1_quick(n0, &r->X, p))
goto end;
if (!BN_mod_sub_quick(n0, n3, n0, p))
goto end;
/* n9 = n5^2 * 'n7' - 2 * X_r */
/* Y_r */
if (!field_mul(group, n0, n0, n6, ctx))
goto end;
if (!field_mul(group, n5, n4, n5, ctx))
goto end; /* now n5 is n5^3 */
if (!field_mul(group, n1, n2, n5, ctx))
goto end;
if (!BN_mod_sub_quick(n0, n0, n1, p))
goto end;
if (BN_is_odd(n0))
if (!BN_add(n0, n0, p))
goto end;
/* now 0 <= n0 < 2*p, and n0 is even */
if (!BN_rshift1(&r->Y, n0))
goto end;
/* Y_r = (n6 * 'n9' - 'n8' * 'n5^3') / 2 */
ret = 1;
end:
if (ctx) /* otherwise we already called BN_CTX_end */
BN_CTX_end(ctx);
if (new_ctx != NULL)
BN_CTX_free(new_ctx);
return ret;
}
int ec_GFp_simple_dbl(const EC_GROUP *group, EC_POINT *r, const EC_POINT *a,
BN_CTX *ctx)
{
int (*field_mul) (const EC_GROUP *, BIGNUM *, const BIGNUM *,
const BIGNUM *, BN_CTX *);
int (*field_sqr) (const EC_GROUP *, BIGNUM *, const BIGNUM *, BN_CTX *);
const BIGNUM *p;
BN_CTX *new_ctx = NULL;
BIGNUM *n0, *n1, *n2, *n3;
int ret = 0;
if (EC_POINT_is_at_infinity(group, a)) {
BN_zero(&r->Z);
r->Z_is_one = 0;
return 1;
}
field_mul = group->meth->field_mul;
field_sqr = group->meth->field_sqr;
p = &group->field;
if (ctx == NULL) {
ctx = new_ctx = BN_CTX_new();
if (ctx == NULL)
return 0;
}
BN_CTX_start(ctx);
n0 = BN_CTX_get(ctx);
n1 = BN_CTX_get(ctx);
n2 = BN_CTX_get(ctx);
n3 = BN_CTX_get(ctx);
if (n3 == NULL)
goto err;
/*
* Note that in this function we must not read components of 'a' once we
* have written the corresponding components of 'r'. ('r' might the same
* as 'a'.)
*/
/* n1 */
if (a->Z_is_one) {
if (!field_sqr(group, n0, &a->X, ctx))
goto err;
if (!BN_mod_lshift1_quick(n1, n0, p))
goto err;
if (!BN_mod_add_quick(n0, n0, n1, p))
goto err;
if (!BN_mod_add_quick(n1, n0, &group->a, p))
goto err;
/* n1 = 3 * X_a^2 + a_curve */
} else if (group->a_is_minus3) {
if (!field_sqr(group, n1, &a->Z, ctx))
goto err;
if (!BN_mod_add_quick(n0, &a->X, n1, p))
goto err;
if (!BN_mod_sub_quick(n2, &a->X, n1, p))
goto err;
if (!field_mul(group, n1, n0, n2, ctx))
goto err;
if (!BN_mod_lshift1_quick(n0, n1, p))
goto err;
if (!BN_mod_add_quick(n1, n0, n1, p))
goto err;
/*-
* n1 = 3 * (X_a + Z_a^2) * (X_a - Z_a^2)
* = 3 * X_a^2 - 3 * Z_a^4
*/
} else {
if (!field_sqr(group, n0, &a->X, ctx))
goto err;
if (!BN_mod_lshift1_quick(n1, n0, p))
goto err;
if (!BN_mod_add_quick(n0, n0, n1, p))
goto err;
if (!field_sqr(group, n1, &a->Z, ctx))
goto err;
if (!field_sqr(group, n1, n1, ctx))
goto err;
if (!field_mul(group, n1, n1, &group->a, ctx))
goto err;
if (!BN_mod_add_quick(n1, n1, n0, p))
goto err;
/* n1 = 3 * X_a^2 + a_curve * Z_a^4 */
}
/* Z_r */
if (a->Z_is_one) {
if (!BN_copy(n0, &a->Y))
goto err;
} else {
if (!field_mul(group, n0, &a->Y, &a->Z, ctx))
goto err;
}
if (!BN_mod_lshift1_quick(&r->Z, n0, p))
goto err;
r->Z_is_one = 0;
/* Z_r = 2 * Y_a * Z_a */
/* n2 */
if (!field_sqr(group, n3, &a->Y, ctx))
goto err;
if (!field_mul(group, n2, &a->X, n3, ctx))
goto err;
if (!BN_mod_lshift_quick(n2, n2, 2, p))
goto err;
/* n2 = 4 * X_a * Y_a^2 */
/* X_r */
if (!BN_mod_lshift1_quick(n0, n2, p))
goto err;
if (!field_sqr(group, &r->X, n1, ctx))
goto err;
if (!BN_mod_sub_quick(&r->X, &r->X, n0, p))
goto err;
/* X_r = n1^2 - 2 * n2 */
/* n3 */
if (!field_sqr(group, n0, n3, ctx))
goto err;
if (!BN_mod_lshift_quick(n3, n0, 3, p))
goto err;
/* n3 = 8 * Y_a^4 */
/* Y_r */
if (!BN_mod_sub_quick(n0, n2, &r->X, p))
goto err;
if (!field_mul(group, n0, n1, n0, ctx))
goto err;
if (!BN_mod_sub_quick(&r->Y, n0, n3, p))
goto err;
/* Y_r = n1 * (n2 - X_r) - n3 */
ret = 1;
err:
BN_CTX_end(ctx);
if (new_ctx != NULL)
BN_CTX_free(new_ctx);
return ret;
}
int ec_GFp_simple_invert(const EC_GROUP *group, EC_POINT *point, BN_CTX *ctx)
{
if (EC_POINT_is_at_infinity(group, point) || BN_is_zero(&point->Y))
/* point is its own inverse */
return 1;
return BN_usub(&point->Y, &group->field, &point->Y);
}
int ec_GFp_simple_is_at_infinity(const EC_GROUP *group, const EC_POINT *point)
{
return BN_is_zero(&point->Z);
}
int ec_GFp_simple_is_on_curve(const EC_GROUP *group, const EC_POINT *point,
BN_CTX *ctx)
{
int (*field_mul) (const EC_GROUP *, BIGNUM *, const BIGNUM *,
const BIGNUM *, BN_CTX *);
int (*field_sqr) (const EC_GROUP *, BIGNUM *, const BIGNUM *, BN_CTX *);
const BIGNUM *p;
BN_CTX *new_ctx = NULL;
BIGNUM *rh, *tmp, *Z4, *Z6;
int ret = -1;
if (EC_POINT_is_at_infinity(group, point))
return 1;
field_mul = group->meth->field_mul;
field_sqr = group->meth->field_sqr;
p = &group->field;
if (ctx == NULL) {
ctx = new_ctx = BN_CTX_new();
if (ctx == NULL)
return -1;
}
BN_CTX_start(ctx);
rh = BN_CTX_get(ctx);
tmp = BN_CTX_get(ctx);
Z4 = BN_CTX_get(ctx);
Z6 = BN_CTX_get(ctx);
if (Z6 == NULL)
goto err;
/*-
* We have a curve defined by a Weierstrass equation
* y^2 = x^3 + a*x + b.
* The point to consider is given in Jacobian projective coordinates
* where (X, Y, Z) represents (x, y) = (X/Z^2, Y/Z^3).
* Substituting this and multiplying by Z^6 transforms the above equation into
* Y^2 = X^3 + a*X*Z^4 + b*Z^6.
* To test this, we add up the right-hand side in 'rh'.
*/
/* rh := X^2 */
if (!field_sqr(group, rh, &point->X, ctx))
goto err;
if (!point->Z_is_one) {
if (!field_sqr(group, tmp, &point->Z, ctx))
goto err;
if (!field_sqr(group, Z4, tmp, ctx))
goto err;
if (!field_mul(group, Z6, Z4, tmp, ctx))
goto err;
/* rh := (rh + a*Z^4)*X */
if (group->a_is_minus3) {
if (!BN_mod_lshift1_quick(tmp, Z4, p))
goto err;
if (!BN_mod_add_quick(tmp, tmp, Z4, p))
goto err;
if (!BN_mod_sub_quick(rh, rh, tmp, p))
goto err;
if (!field_mul(group, rh, rh, &point->X, ctx))
goto err;
} else {
if (!field_mul(group, tmp, Z4, &group->a, ctx))
goto err;
if (!BN_mod_add_quick(rh, rh, tmp, p))
goto err;
if (!field_mul(group, rh, rh, &point->X, ctx))
goto err;
}
/* rh := rh + b*Z^6 */
if (!field_mul(group, tmp, &group->b, Z6, ctx))
goto err;
if (!BN_mod_add_quick(rh, rh, tmp, p))
goto err;
} else {
/* point->Z_is_one */
/* rh := (rh + a)*X */
if (!BN_mod_add_quick(rh, rh, &group->a, p))
goto err;
if (!field_mul(group, rh, rh, &point->X, ctx))
goto err;
/* rh := rh + b */
if (!BN_mod_add_quick(rh, rh, &group->b, p))
goto err;
}
/* 'lh' := Y^2 */
if (!field_sqr(group, tmp, &point->Y, ctx))
goto err;
ret = (0 == BN_ucmp(tmp, rh));
err:
BN_CTX_end(ctx);
if (new_ctx != NULL)
BN_CTX_free(new_ctx);
return ret;
}
int ec_GFp_simple_cmp(const EC_GROUP *group, const EC_POINT *a,
const EC_POINT *b, BN_CTX *ctx)
{
/*-
* return values:
* -1 error
* 0 equal (in affine coordinates)
* 1 not equal
*/
int (*field_mul) (const EC_GROUP *, BIGNUM *, const BIGNUM *,
const BIGNUM *, BN_CTX *);
int (*field_sqr) (const EC_GROUP *, BIGNUM *, const BIGNUM *, BN_CTX *);
BN_CTX *new_ctx = NULL;
BIGNUM *tmp1, *tmp2, *Za23, *Zb23;
const BIGNUM *tmp1_, *tmp2_;
int ret = -1;
if (EC_POINT_is_at_infinity(group, a)) {
return EC_POINT_is_at_infinity(group, b) ? 0 : 1;
}
if (EC_POINT_is_at_infinity(group, b))
return 1;
if (a->Z_is_one && b->Z_is_one) {
return ((BN_cmp(&a->X, &b->X) == 0)
&& BN_cmp(&a->Y, &b->Y) == 0) ? 0 : 1;
}
field_mul = group->meth->field_mul;
field_sqr = group->meth->field_sqr;
if (ctx == NULL) {
ctx = new_ctx = BN_CTX_new();
if (ctx == NULL)
return -1;
}
BN_CTX_start(ctx);
tmp1 = BN_CTX_get(ctx);
tmp2 = BN_CTX_get(ctx);
Za23 = BN_CTX_get(ctx);
Zb23 = BN_CTX_get(ctx);
if (Zb23 == NULL)
goto end;
/*-
* We have to decide whether
* (X_a/Z_a^2, Y_a/Z_a^3) = (X_b/Z_b^2, Y_b/Z_b^3),
* or equivalently, whether
* (X_a*Z_b^2, Y_a*Z_b^3) = (X_b*Z_a^2, Y_b*Z_a^3).
*/
if (!b->Z_is_one) {
if (!field_sqr(group, Zb23, &b->Z, ctx))
goto end;
if (!field_mul(group, tmp1, &a->X, Zb23, ctx))
goto end;
tmp1_ = tmp1;
} else
tmp1_ = &a->X;
if (!a->Z_is_one) {
if (!field_sqr(group, Za23, &a->Z, ctx))
goto end;
if (!field_mul(group, tmp2, &b->X, Za23, ctx))
goto end;
tmp2_ = tmp2;
} else
tmp2_ = &b->X;
/* compare X_a*Z_b^2 with X_b*Z_a^2 */
if (BN_cmp(tmp1_, tmp2_) != 0) {
ret = 1; /* points differ */
goto end;
}
if (!b->Z_is_one) {
if (!field_mul(group, Zb23, Zb23, &b->Z, ctx))
goto end;
if (!field_mul(group, tmp1, &a->Y, Zb23, ctx))
goto end;
/* tmp1_ = tmp1 */
} else
tmp1_ = &a->Y;
if (!a->Z_is_one) {
if (!field_mul(group, Za23, Za23, &a->Z, ctx))
goto end;
if (!field_mul(group, tmp2, &b->Y, Za23, ctx))
goto end;
/* tmp2_ = tmp2 */
} else
tmp2_ = &b->Y;
/* compare Y_a*Z_b^3 with Y_b*Z_a^3 */
if (BN_cmp(tmp1_, tmp2_) != 0) {
ret = 1; /* points differ */
goto end;
}
/* points are equal */
ret = 0;
end:
BN_CTX_end(ctx);
if (new_ctx != NULL)
BN_CTX_free(new_ctx);
return ret;
}
int ec_GFp_simple_make_affine(const EC_GROUP *group, EC_POINT *point,
BN_CTX *ctx)
{
BN_CTX *new_ctx = NULL;
BIGNUM *x, *y;
int ret = 0;
if (point->Z_is_one || EC_POINT_is_at_infinity(group, point))
return 1;
if (ctx == NULL) {
ctx = new_ctx = BN_CTX_new();
if (ctx == NULL)
return 0;
}
BN_CTX_start(ctx);
x = BN_CTX_get(ctx);
y = BN_CTX_get(ctx);
if (y == NULL)
goto err;
if (!EC_POINT_get_affine_coordinates_GFp(group, point, x, y, ctx))
goto err;
if (!EC_POINT_set_affine_coordinates_GFp(group, point, x, y, ctx))
goto err;
if (!point->Z_is_one) {
ECerr(EC_F_EC_GFP_SIMPLE_MAKE_AFFINE, ERR_R_INTERNAL_ERROR);
goto err;
}
ret = 1;
err:
BN_CTX_end(ctx);
if (new_ctx != NULL)
BN_CTX_free(new_ctx);
return ret;
}
int ec_GFp_simple_points_make_affine(const EC_GROUP *group, size_t num,
EC_POINT *points[], BN_CTX *ctx)
{
BN_CTX *new_ctx = NULL;
BIGNUM *tmp, *tmp_Z;
BIGNUM **prod_Z = NULL;
size_t i;
int ret = 0;
if (num == 0)
return 1;
if (ctx == NULL) {
ctx = new_ctx = BN_CTX_new();
if (ctx == NULL)
return 0;
}
BN_CTX_start(ctx);
tmp = BN_CTX_get(ctx);
tmp_Z = BN_CTX_get(ctx);
if (tmp == NULL || tmp_Z == NULL)
goto err;
- prod_Z = OPENSSL_malloc(num * sizeof prod_Z[0]);
+ prod_Z = OPENSSL_malloc(num * sizeof(prod_Z[0]));
if (prod_Z == NULL)
goto err;
for (i = 0; i < num; i++) {
prod_Z[i] = BN_new();
if (prod_Z[i] == NULL)
goto err;
}
/*
* Set each prod_Z[i] to the product of points[0]->Z .. points[i]->Z,
* skipping any zero-valued inputs (pretend that they're 1).
*/
if (!BN_is_zero(&points[0]->Z)) {
if (!BN_copy(prod_Z[0], &points[0]->Z))
goto err;
} else {
if (group->meth->field_set_to_one != 0) {
if (!group->meth->field_set_to_one(group, prod_Z[0], ctx))
goto err;
} else {
if (!BN_one(prod_Z[0]))
goto err;
}
}
for (i = 1; i < num; i++) {
if (!BN_is_zero(&points[i]->Z)) {
if (!group->meth->field_mul(group, prod_Z[i], prod_Z[i - 1],
&points[i]->Z, ctx))
goto err;
} else {
if (!BN_copy(prod_Z[i], prod_Z[i - 1]))
goto err;
}
}
/*
* Now use a single explicit inversion to replace every non-zero
* points[i]->Z by its inverse.
*/
if (!BN_mod_inverse(tmp, prod_Z[num - 1], &group->field, ctx)) {
ECerr(EC_F_EC_GFP_SIMPLE_POINTS_MAKE_AFFINE, ERR_R_BN_LIB);
goto err;
}
if (group->meth->field_encode != 0) {
/*
* In the Montgomery case, we just turned R*H (representing H) into
* 1/(R*H), but we need R*(1/H) (representing 1/H); i.e. we need to
* multiply by the Montgomery factor twice.
*/
if (!group->meth->field_encode(group, tmp, tmp, ctx))
goto err;
if (!group->meth->field_encode(group, tmp, tmp, ctx))
goto err;
}
for (i = num - 1; i > 0; --i) {
/*
* Loop invariant: tmp is the product of the inverses of points[0]->Z
* .. points[i]->Z (zero-valued inputs skipped).
*/
if (!BN_is_zero(&points[i]->Z)) {
/*
* Set tmp_Z to the inverse of points[i]->Z (as product of Z
* inverses 0 .. i, Z values 0 .. i - 1).
*/
if (!group->
meth->field_mul(group, tmp_Z, prod_Z[i - 1], tmp, ctx))
goto err;
/*
* Update tmp to satisfy the loop invariant for i - 1.
*/
if (!group->meth->field_mul(group, tmp, tmp, &points[i]->Z, ctx))
goto err;
/* Replace points[i]->Z by its inverse. */
if (!BN_copy(&points[i]->Z, tmp_Z))
goto err;
}
}
if (!BN_is_zero(&points[0]->Z)) {
/* Replace points[0]->Z by its inverse. */
if (!BN_copy(&points[0]->Z, tmp))
goto err;
}
/* Finally, fix up the X and Y coordinates for all points. */
for (i = 0; i < num; i++) {
EC_POINT *p = points[i];
if (!BN_is_zero(&p->Z)) {
/* turn (X, Y, 1/Z) into (X/Z^2, Y/Z^3, 1) */
if (!group->meth->field_sqr(group, tmp, &p->Z, ctx))
goto err;
if (!group->meth->field_mul(group, &p->X, &p->X, tmp, ctx))
goto err;
if (!group->meth->field_mul(group, tmp, tmp, &p->Z, ctx))
goto err;
if (!group->meth->field_mul(group, &p->Y, &p->Y, tmp, ctx))
goto err;
if (group->meth->field_set_to_one != 0) {
if (!group->meth->field_set_to_one(group, &p->Z, ctx))
goto err;
} else {
if (!BN_one(&p->Z))
goto err;
}
p->Z_is_one = 1;
}
}
ret = 1;
err:
BN_CTX_end(ctx);
if (new_ctx != NULL)
BN_CTX_free(new_ctx);
if (prod_Z != NULL) {
for (i = 0; i < num; i++) {
if (prod_Z[i] == NULL)
break;
BN_clear_free(prod_Z[i]);
}
OPENSSL_free(prod_Z);
}
return ret;
}
int ec_GFp_simple_field_mul(const EC_GROUP *group, BIGNUM *r, const BIGNUM *a,
const BIGNUM *b, BN_CTX *ctx)
{
return BN_mod_mul(r, a, b, &group->field, ctx);
}
int ec_GFp_simple_field_sqr(const EC_GROUP *group, BIGNUM *r, const BIGNUM *a,
BN_CTX *ctx)
{
return BN_mod_sqr(r, a, &group->field, ctx);
}
diff --git a/crypto/ec/ectest.c b/crypto/ec/ectest.c
index 40a1f003259f..5e1ef5093383 100644
--- a/crypto/ec/ectest.c
+++ b/crypto/ec/ectest.c
@@ -1,1870 +1,1870 @@
/* crypto/ec/ectest.c */
/*
* Originally written by Bodo Moeller for the OpenSSL project.
*/
/* ====================================================================
* Copyright (c) 1998-2001 The OpenSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* openssl-core@openssl.org.
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.openssl.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*
* This product includes cryptographic software written by Eric Young
* (eay@cryptsoft.com). This product includes software written by Tim
* Hudson (tjh@cryptsoft.com).
*
*/
/* ====================================================================
* Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
*
* Portions of the attached software ("Contribution") are developed by
* SUN MICROSYSTEMS, INC., and are contributed to the OpenSSL project.
*
* The Contribution is licensed pursuant to the OpenSSL open source
* license provided above.
*
* The elliptic curve binary polynomial software is originally written by
* Sheueling Chang Shantz and Douglas Stebila of Sun Microsystems Laboratories.
*
*/
#include <stdio.h>
#include <stdlib.h>
#ifdef FLAT_INC
# include "e_os.h"
#else
# include "../e_os.h"
#endif
#include <string.h>
#include <time.h>
#ifdef OPENSSL_NO_EC
int main(int argc, char *argv[])
{
puts("Elliptic curves are disabled.");
return 0;
}
#else
# include <openssl/ec.h>
# ifndef OPENSSL_NO_ENGINE
# include <openssl/engine.h>
# endif
# include <openssl/err.h>
# include <openssl/obj_mac.h>
# include <openssl/objects.h>
# include <openssl/rand.h>
# include <openssl/bn.h>
# include <openssl/opensslconf.h>
# if defined(_MSC_VER) && defined(_MIPS_) && (_MSC_VER/100==12)
/* suppress "too big too optimize" warning */
# pragma warning(disable:4959)
# endif
# define ABORT do { \
fflush(stdout); \
fprintf(stderr, "%s:%d: ABORT\n", __FILE__, __LINE__); \
ERR_print_errors_fp(stderr); \
EXIT(1); \
} while (0)
# define TIMING_BASE_PT 0
# define TIMING_RAND_PT 1
# define TIMING_SIMUL 2
# if 0
static void timings(EC_GROUP *group, int type, BN_CTX *ctx)
{
clock_t clck;
int i, j;
BIGNUM *s;
BIGNUM *r[10], *r0[10];
EC_POINT *P;
s = BN_new();
if (s == NULL)
ABORT;
fprintf(stdout, "Timings for %d-bit field, ", EC_GROUP_get_degree(group));
if (!EC_GROUP_get_order(group, s, ctx))
ABORT;
fprintf(stdout, "%d-bit scalars ", (int)BN_num_bits(s));
fflush(stdout);
P = EC_POINT_new(group);
if (P == NULL)
ABORT;
EC_POINT_copy(P, EC_GROUP_get0_generator(group));
for (i = 0; i < 10; i++) {
if ((r[i] = BN_new()) == NULL)
ABORT;
if (!BN_pseudo_rand(r[i], BN_num_bits(s), 0, 0))
ABORT;
if (type != TIMING_BASE_PT) {
if ((r0[i] = BN_new()) == NULL)
ABORT;
if (!BN_pseudo_rand(r0[i], BN_num_bits(s), 0, 0))
ABORT;
}
}
clck = clock();
for (i = 0; i < 10; i++) {
for (j = 0; j < 10; j++) {
if (!EC_POINT_mul
(group, P, (type != TIMING_RAND_PT) ? r[i] : NULL,
(type != TIMING_BASE_PT) ? P : NULL,
(type != TIMING_BASE_PT) ? r0[i] : NULL, ctx))
ABORT;
}
}
clck = clock() - clck;
fprintf(stdout, "\n");
# ifdef CLOCKS_PER_SEC
/*
* "To determine the time in seconds, the value returned by the clock
* function should be divided by the value of the macro CLOCKS_PER_SEC."
* -- ISO/IEC 9899
*/
# define UNIT "s"
# else
/*
* "`CLOCKS_PER_SEC' undeclared (first use this function)" -- cc on
* NeXTstep/OpenStep
*/
# define UNIT "units"
# define CLOCKS_PER_SEC 1
# endif
if (type == TIMING_BASE_PT) {
fprintf(stdout, "%i %s in %.2f " UNIT "\n", i * j,
"base point multiplications", (double)clck / CLOCKS_PER_SEC);
} else if (type == TIMING_RAND_PT) {
fprintf(stdout, "%i %s in %.2f " UNIT "\n", i * j,
"random point multiplications",
(double)clck / CLOCKS_PER_SEC);
} else if (type == TIMING_SIMUL) {
fprintf(stdout, "%i %s in %.2f " UNIT "\n", i * j,
"s*P+t*Q operations", (double)clck / CLOCKS_PER_SEC);
}
fprintf(stdout, "average: %.4f " UNIT "\n",
(double)clck / (CLOCKS_PER_SEC * i * j));
EC_POINT_free(P);
BN_free(s);
for (i = 0; i < 10; i++) {
BN_free(r[i]);
if (type != TIMING_BASE_PT)
BN_free(r0[i]);
}
}
# endif
/* test multiplication with group order, long and negative scalars */
static void group_order_tests(EC_GROUP *group)
{
BIGNUM *n1, *n2, *order;
EC_POINT *P = EC_POINT_new(group);
EC_POINT *Q = EC_POINT_new(group);
BN_CTX *ctx = BN_CTX_new();
int i;
n1 = BN_new();
n2 = BN_new();
order = BN_new();
fprintf(stdout, "verify group order ...");
fflush(stdout);
if (!EC_GROUP_get_order(group, order, ctx))
ABORT;
if (!EC_POINT_mul(group, Q, order, NULL, NULL, ctx))
ABORT;
if (!EC_POINT_is_at_infinity(group, Q))
ABORT;
fprintf(stdout, ".");
fflush(stdout);
if (!EC_GROUP_precompute_mult(group, ctx))
ABORT;
if (!EC_POINT_mul(group, Q, order, NULL, NULL, ctx))
ABORT;
if (!EC_POINT_is_at_infinity(group, Q))
ABORT;
fprintf(stdout, " ok\n");
fprintf(stdout, "long/negative scalar tests ");
for (i = 1; i <= 2; i++) {
const BIGNUM *scalars[6];
const EC_POINT *points[6];
fprintf(stdout, i == 1 ?
"allowing precomputation ... " :
"without precomputation ... ");
if (!BN_set_word(n1, i))
ABORT;
/*
* If i == 1, P will be the predefined generator for which
* EC_GROUP_precompute_mult has set up precomputation.
*/
if (!EC_POINT_mul(group, P, n1, NULL, NULL, ctx))
ABORT;
if (!BN_one(n1))
ABORT;
/* n1 = 1 - order */
if (!BN_sub(n1, n1, order))
ABORT;
if (!EC_POINT_mul(group, Q, NULL, P, n1, ctx))
ABORT;
if (0 != EC_POINT_cmp(group, Q, P, ctx))
ABORT;
/* n2 = 1 + order */
if (!BN_add(n2, order, BN_value_one()))
ABORT;
if (!EC_POINT_mul(group, Q, NULL, P, n2, ctx))
ABORT;
if (0 != EC_POINT_cmp(group, Q, P, ctx))
ABORT;
/* n2 = (1 - order) * (1 + order) = 1 - order^2 */
if (!BN_mul(n2, n1, n2, ctx))
ABORT;
if (!EC_POINT_mul(group, Q, NULL, P, n2, ctx))
ABORT;
if (0 != EC_POINT_cmp(group, Q, P, ctx))
ABORT;
/* n2 = order^2 - 1 */
BN_set_negative(n2, 0);
if (!EC_POINT_mul(group, Q, NULL, P, n2, ctx))
ABORT;
/* Add P to verify the result. */
if (!EC_POINT_add(group, Q, Q, P, ctx))
ABORT;
if (!EC_POINT_is_at_infinity(group, Q))
ABORT;
/* Exercise EC_POINTs_mul, including corner cases. */
if (EC_POINT_is_at_infinity(group, P))
ABORT;
scalars[0] = n1;
points[0] = Q; /* => infinity */
scalars[1] = n2;
points[1] = P; /* => -P */
scalars[2] = n1;
points[2] = Q; /* => infinity */
scalars[3] = n2;
points[3] = Q; /* => infinity */
scalars[4] = n1;
points[4] = P; /* => P */
scalars[5] = n2;
points[5] = Q; /* => infinity */
if (!EC_POINTs_mul(group, P, NULL, 6, points, scalars, ctx))
ABORT;
if (!EC_POINT_is_at_infinity(group, P))
ABORT;
}
fprintf(stdout, "ok\n");
EC_POINT_free(P);
EC_POINT_free(Q);
BN_free(n1);
BN_free(n2);
BN_free(order);
BN_CTX_free(ctx);
}
static void prime_field_tests(void)
{
BN_CTX *ctx = NULL;
BIGNUM *p, *a, *b;
EC_GROUP *group;
EC_GROUP *P_160 = NULL, *P_192 = NULL, *P_224 = NULL, *P_256 =
NULL, *P_384 = NULL, *P_521 = NULL;
EC_POINT *P, *Q, *R;
BIGNUM *x, *y, *z;
unsigned char buf[100];
size_t i, len;
int k;
# if 1 /* optional */
ctx = BN_CTX_new();
if (!ctx)
ABORT;
# endif
p = BN_new();
a = BN_new();
b = BN_new();
if (!p || !a || !b)
ABORT;
if (!BN_hex2bn(&p, "17"))
ABORT;
if (!BN_hex2bn(&a, "1"))
ABORT;
if (!BN_hex2bn(&b, "1"))
ABORT;
group = EC_GROUP_new(EC_GFp_mont_method()); /* applications should use
* EC_GROUP_new_curve_GFp so
* that the library gets to
* choose the EC_METHOD */
if (!group)
ABORT;
if (!EC_GROUP_set_curve_GFp(group, p, a, b, ctx))
ABORT;
{
EC_GROUP *tmp;
tmp = EC_GROUP_new(EC_GROUP_method_of(group));
if (!tmp)
ABORT;
if (!EC_GROUP_copy(tmp, group))
ABORT;
EC_GROUP_free(group);
group = tmp;
}
if (!EC_GROUP_get_curve_GFp(group, p, a, b, ctx))
ABORT;
fprintf(stdout,
"Curve defined by Weierstrass equation\n y^2 = x^3 + a*x + b (mod 0x");
BN_print_fp(stdout, p);
fprintf(stdout, ")\n a = 0x");
BN_print_fp(stdout, a);
fprintf(stdout, "\n b = 0x");
BN_print_fp(stdout, b);
fprintf(stdout, "\n");
P = EC_POINT_new(group);
Q = EC_POINT_new(group);
R = EC_POINT_new(group);
if (!P || !Q || !R)
ABORT;
if (!EC_POINT_set_to_infinity(group, P))
ABORT;
if (!EC_POINT_is_at_infinity(group, P))
ABORT;
buf[0] = 0;
if (!EC_POINT_oct2point(group, Q, buf, 1, ctx))
ABORT;
if (!EC_POINT_add(group, P, P, Q, ctx))
ABORT;
if (!EC_POINT_is_at_infinity(group, P))
ABORT;
x = BN_new();
y = BN_new();
z = BN_new();
if (!x || !y || !z)
ABORT;
if (!BN_hex2bn(&x, "D"))
ABORT;
if (!EC_POINT_set_compressed_coordinates_GFp(group, Q, x, 1, ctx))
ABORT;
if (EC_POINT_is_on_curve(group, Q, ctx) <= 0) {
if (!EC_POINT_get_affine_coordinates_GFp(group, Q, x, y, ctx))
ABORT;
fprintf(stderr, "Point is not on curve: x = 0x");
BN_print_fp(stderr, x);
fprintf(stderr, ", y = 0x");
BN_print_fp(stderr, y);
fprintf(stderr, "\n");
ABORT;
}
fprintf(stdout, "A cyclic subgroup:\n");
k = 100;
do {
if (k-- == 0)
ABORT;
if (EC_POINT_is_at_infinity(group, P))
fprintf(stdout, " point at infinity\n");
else {
if (!EC_POINT_get_affine_coordinates_GFp(group, P, x, y, ctx))
ABORT;
fprintf(stdout, " x = 0x");
BN_print_fp(stdout, x);
fprintf(stdout, ", y = 0x");
BN_print_fp(stdout, y);
fprintf(stdout, "\n");
}
if (!EC_POINT_copy(R, P))
ABORT;
if (!EC_POINT_add(group, P, P, Q, ctx))
ABORT;
# if 0 /* optional */
{
EC_POINT *points[3];
points[0] = R;
points[1] = Q;
points[2] = P;
if (!EC_POINTs_make_affine(group, 2, points, ctx))
ABORT;
}
# endif
}
while (!EC_POINT_is_at_infinity(group, P));
if (!EC_POINT_add(group, P, Q, R, ctx))
ABORT;
if (!EC_POINT_is_at_infinity(group, P))
ABORT;
len =
EC_POINT_point2oct(group, Q, POINT_CONVERSION_COMPRESSED, buf,
- sizeof buf, ctx);
+ sizeof(buf), ctx);
if (len == 0)
ABORT;
if (!EC_POINT_oct2point(group, P, buf, len, ctx))
ABORT;
if (0 != EC_POINT_cmp(group, P, Q, ctx))
ABORT;
fprintf(stdout, "Generator as octet string, compressed form:\n ");
for (i = 0; i < len; i++)
fprintf(stdout, "%02X", buf[i]);
len =
EC_POINT_point2oct(group, Q, POINT_CONVERSION_UNCOMPRESSED, buf,
- sizeof buf, ctx);
+ sizeof(buf), ctx);
if (len == 0)
ABORT;
if (!EC_POINT_oct2point(group, P, buf, len, ctx))
ABORT;
if (0 != EC_POINT_cmp(group, P, Q, ctx))
ABORT;
fprintf(stdout, "\nGenerator as octet string, uncompressed form:\n ");
for (i = 0; i < len; i++)
fprintf(stdout, "%02X", buf[i]);
len =
- EC_POINT_point2oct(group, Q, POINT_CONVERSION_HYBRID, buf, sizeof buf,
+ EC_POINT_point2oct(group, Q, POINT_CONVERSION_HYBRID, buf, sizeof(buf),
ctx);
if (len == 0)
ABORT;
if (!EC_POINT_oct2point(group, P, buf, len, ctx))
ABORT;
if (0 != EC_POINT_cmp(group, P, Q, ctx))
ABORT;
fprintf(stdout, "\nGenerator as octet string, hybrid form:\n ");
for (i = 0; i < len; i++)
fprintf(stdout, "%02X", buf[i]);
if (!EC_POINT_get_Jprojective_coordinates_GFp(group, R, x, y, z, ctx))
ABORT;
fprintf(stdout,
"\nA representation of the inverse of that generator in\nJacobian projective coordinates:\n X = 0x");
BN_print_fp(stdout, x);
fprintf(stdout, ", Y = 0x");
BN_print_fp(stdout, y);
fprintf(stdout, ", Z = 0x");
BN_print_fp(stdout, z);
fprintf(stdout, "\n");
if (!EC_POINT_invert(group, P, ctx))
ABORT;
if (0 != EC_POINT_cmp(group, P, R, ctx))
ABORT;
/*
* Curve secp160r1 (Certicom Research SEC 2 Version 1.0, section 2.4.2,
* 2000) -- not a NIST curve, but commonly used
*/
if (!BN_hex2bn(&p, "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFF"))
ABORT;
if (1 != BN_is_prime_ex(p, BN_prime_checks, ctx, NULL))
ABORT;
if (!BN_hex2bn(&a, "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFC"))
ABORT;
if (!BN_hex2bn(&b, "1C97BEFC54BD7A8B65ACF89F81D4D4ADC565FA45"))
ABORT;
if (!EC_GROUP_set_curve_GFp(group, p, a, b, ctx))
ABORT;
if (!BN_hex2bn(&x, "4A96B5688EF573284664698968C38BB913CBFC82"))
ABORT;
if (!BN_hex2bn(&y, "23a628553168947d59dcc912042351377ac5fb32"))
ABORT;
if (!EC_POINT_set_affine_coordinates_GFp(group, P, x, y, ctx))
ABORT;
if (EC_POINT_is_on_curve(group, P, ctx) <= 0)
ABORT;
if (!BN_hex2bn(&z, "0100000000000000000001F4C8F927AED3CA752257"))
ABORT;
if (!EC_GROUP_set_generator(group, P, z, BN_value_one()))
ABORT;
if (!EC_POINT_get_affine_coordinates_GFp(group, P, x, y, ctx))
ABORT;
fprintf(stdout, "\nSEC2 curve secp160r1 -- Generator:\n x = 0x");
BN_print_fp(stdout, x);
fprintf(stdout, "\n y = 0x");
BN_print_fp(stdout, y);
fprintf(stdout, "\n");
/* G_y value taken from the standard: */
if (!BN_hex2bn(&z, "23a628553168947d59dcc912042351377ac5fb32"))
ABORT;
if (0 != BN_cmp(y, z))
ABORT;
fprintf(stdout, "verify degree ...");
if (EC_GROUP_get_degree(group) != 160)
ABORT;
fprintf(stdout, " ok\n");
group_order_tests(group);
if (!(P_160 = EC_GROUP_new(EC_GROUP_method_of(group))))
ABORT;
if (!EC_GROUP_copy(P_160, group))
ABORT;
/* Curve P-192 (FIPS PUB 186-2, App. 6) */
if (!BN_hex2bn(&p, "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFF"))
ABORT;
if (1 != BN_is_prime_ex(p, BN_prime_checks, ctx, NULL))
ABORT;
if (!BN_hex2bn(&a, "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFC"))
ABORT;
if (!BN_hex2bn(&b, "64210519E59C80E70FA7E9AB72243049FEB8DEECC146B9B1"))
ABORT;
if (!EC_GROUP_set_curve_GFp(group, p, a, b, ctx))
ABORT;
if (!BN_hex2bn(&x, "188DA80EB03090F67CBF20EB43A18800F4FF0AFD82FF1012"))
ABORT;
if (!EC_POINT_set_compressed_coordinates_GFp(group, P, x, 1, ctx))
ABORT;
if (EC_POINT_is_on_curve(group, P, ctx) <= 0)
ABORT;
if (!BN_hex2bn(&z, "FFFFFFFFFFFFFFFFFFFFFFFF99DEF836146BC9B1B4D22831"))
ABORT;
if (!EC_GROUP_set_generator(group, P, z, BN_value_one()))
ABORT;
if (!EC_POINT_get_affine_coordinates_GFp(group, P, x, y, ctx))
ABORT;
fprintf(stdout, "\nNIST curve P-192 -- Generator:\n x = 0x");
BN_print_fp(stdout, x);
fprintf(stdout, "\n y = 0x");
BN_print_fp(stdout, y);
fprintf(stdout, "\n");
/* G_y value taken from the standard: */
if (!BN_hex2bn(&z, "07192B95FFC8DA78631011ED6B24CDD573F977A11E794811"))
ABORT;
if (0 != BN_cmp(y, z))
ABORT;
fprintf(stdout, "verify degree ...");
if (EC_GROUP_get_degree(group) != 192)
ABORT;
fprintf(stdout, " ok\n");
group_order_tests(group);
if (!(P_192 = EC_GROUP_new(EC_GROUP_method_of(group))))
ABORT;
if (!EC_GROUP_copy(P_192, group))
ABORT;
/* Curve P-224 (FIPS PUB 186-2, App. 6) */
if (!BN_hex2bn
(&p, "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF000000000000000000000001"))
ABORT;
if (1 != BN_is_prime_ex(p, BN_prime_checks, ctx, NULL))
ABORT;
if (!BN_hex2bn
(&a, "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFE"))
ABORT;
if (!BN_hex2bn
(&b, "B4050A850C04B3ABF54132565044B0B7D7BFD8BA270B39432355FFB4"))
ABORT;
if (!EC_GROUP_set_curve_GFp(group, p, a, b, ctx))
ABORT;
if (!BN_hex2bn
(&x, "B70E0CBD6BB4BF7F321390B94A03C1D356C21122343280D6115C1D21"))
ABORT;
if (!EC_POINT_set_compressed_coordinates_GFp(group, P, x, 0, ctx))
ABORT;
if (EC_POINT_is_on_curve(group, P, ctx) <= 0)
ABORT;
if (!BN_hex2bn
(&z, "FFFFFFFFFFFFFFFFFFFFFFFFFFFF16A2E0B8F03E13DD29455C5C2A3D"))
ABORT;
if (!EC_GROUP_set_generator(group, P, z, BN_value_one()))
ABORT;
if (!EC_POINT_get_affine_coordinates_GFp(group, P, x, y, ctx))
ABORT;
fprintf(stdout, "\nNIST curve P-224 -- Generator:\n x = 0x");
BN_print_fp(stdout, x);
fprintf(stdout, "\n y = 0x");
BN_print_fp(stdout, y);
fprintf(stdout, "\n");
/* G_y value taken from the standard: */
if (!BN_hex2bn
(&z, "BD376388B5F723FB4C22DFE6CD4375A05A07476444D5819985007E34"))
ABORT;
if (0 != BN_cmp(y, z))
ABORT;
fprintf(stdout, "verify degree ...");
if (EC_GROUP_get_degree(group) != 224)
ABORT;
fprintf(stdout, " ok\n");
group_order_tests(group);
if (!(P_224 = EC_GROUP_new(EC_GROUP_method_of(group))))
ABORT;
if (!EC_GROUP_copy(P_224, group))
ABORT;
/* Curve P-256 (FIPS PUB 186-2, App. 6) */
if (!BN_hex2bn
(&p,
"FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF"))
ABORT;
if (1 != BN_is_prime_ex(p, BN_prime_checks, ctx, NULL))
ABORT;
if (!BN_hex2bn
(&a,
"FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC"))
ABORT;
if (!BN_hex2bn
(&b,
"5AC635D8AA3A93E7B3EBBD55769886BC651D06B0CC53B0F63BCE3C3E27D2604B"))
ABORT;
if (!EC_GROUP_set_curve_GFp(group, p, a, b, ctx))
ABORT;
if (!BN_hex2bn
(&x,
"6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296"))
ABORT;
if (!EC_POINT_set_compressed_coordinates_GFp(group, P, x, 1, ctx))
ABORT;
if (EC_POINT_is_on_curve(group, P, ctx) <= 0)
ABORT;
if (!BN_hex2bn(&z, "FFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E"
"84F3B9CAC2FC632551"))
ABORT;
if (!EC_GROUP_set_generator(group, P, z, BN_value_one()))
ABORT;
if (!EC_POINT_get_affine_coordinates_GFp(group, P, x, y, ctx))
ABORT;
fprintf(stdout, "\nNIST curve P-256 -- Generator:\n x = 0x");
BN_print_fp(stdout, x);
fprintf(stdout, "\n y = 0x");
BN_print_fp(stdout, y);
fprintf(stdout, "\n");
/* G_y value taken from the standard: */
if (!BN_hex2bn
(&z,
"4FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5"))
ABORT;
if (0 != BN_cmp(y, z))
ABORT;
fprintf(stdout, "verify degree ...");
if (EC_GROUP_get_degree(group) != 256)
ABORT;
fprintf(stdout, " ok\n");
group_order_tests(group);
if (!(P_256 = EC_GROUP_new(EC_GROUP_method_of(group))))
ABORT;
if (!EC_GROUP_copy(P_256, group))
ABORT;
/* Curve P-384 (FIPS PUB 186-2, App. 6) */
if (!BN_hex2bn(&p, "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
"FFFFFFFFFFFFFFFFFEFFFFFFFF0000000000000000FFFFFFFF"))
ABORT;
if (1 != BN_is_prime_ex(p, BN_prime_checks, ctx, NULL))
ABORT;
if (!BN_hex2bn(&a, "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
"FFFFFFFFFFFFFFFFFEFFFFFFFF0000000000000000FFFFFFFC"))
ABORT;
if (!BN_hex2bn(&b, "B3312FA7E23EE7E4988E056BE3F82D19181D9C6EFE8141"
"120314088F5013875AC656398D8A2ED19D2A85C8EDD3EC2AEF"))
ABORT;
if (!EC_GROUP_set_curve_GFp(group, p, a, b, ctx))
ABORT;
if (!BN_hex2bn(&x, "AA87CA22BE8B05378EB1C71EF320AD746E1D3B628BA79B"
"9859F741E082542A385502F25DBF55296C3A545E3872760AB7"))
ABORT;
if (!EC_POINT_set_compressed_coordinates_GFp(group, P, x, 1, ctx))
ABORT;
if (EC_POINT_is_on_curve(group, P, ctx) <= 0)
ABORT;
if (!BN_hex2bn(&z, "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
"FFC7634D81F4372DDF581A0DB248B0A77AECEC196ACCC52973"))
ABORT;
if (!EC_GROUP_set_generator(group, P, z, BN_value_one()))
ABORT;
if (!EC_POINT_get_affine_coordinates_GFp(group, P, x, y, ctx))
ABORT;
fprintf(stdout, "\nNIST curve P-384 -- Generator:\n x = 0x");
BN_print_fp(stdout, x);
fprintf(stdout, "\n y = 0x");
BN_print_fp(stdout, y);
fprintf(stdout, "\n");
/* G_y value taken from the standard: */
if (!BN_hex2bn(&z, "3617DE4A96262C6F5D9E98BF9292DC29F8F41DBD289A14"
"7CE9DA3113B5F0B8C00A60B1CE1D7E819D7A431D7C90EA0E5F"))
ABORT;
if (0 != BN_cmp(y, z))
ABORT;
fprintf(stdout, "verify degree ...");
if (EC_GROUP_get_degree(group) != 384)
ABORT;
fprintf(stdout, " ok\n");
group_order_tests(group);
if (!(P_384 = EC_GROUP_new(EC_GROUP_method_of(group))))
ABORT;
if (!EC_GROUP_copy(P_384, group))
ABORT;
/* Curve P-521 (FIPS PUB 186-2, App. 6) */
if (!BN_hex2bn(&p, "1FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
"FFFFFFFFFFFFFFFFFFFFFFFFFFFF"))
ABORT;
if (1 != BN_is_prime_ex(p, BN_prime_checks, ctx, NULL))
ABORT;
if (!BN_hex2bn(&a, "1FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
"FFFFFFFFFFFFFFFFFFFFFFFFFFFC"))
ABORT;
if (!BN_hex2bn(&b, "051953EB9618E1C9A1F929A21A0B68540EEA2DA725B99B"
"315F3B8B489918EF109E156193951EC7E937B1652C0BD3BB1BF073573"
"DF883D2C34F1EF451FD46B503F00"))
ABORT;
if (!EC_GROUP_set_curve_GFp(group, p, a, b, ctx))
ABORT;
if (!BN_hex2bn(&x, "C6858E06B70404E9CD9E3ECB662395B4429C648139053F"
"B521F828AF606B4D3DBAA14B5E77EFE75928FE1DC127A2FFA8DE3348B"
"3C1856A429BF97E7E31C2E5BD66"))
ABORT;
if (!EC_POINT_set_compressed_coordinates_GFp(group, P, x, 0, ctx))
ABORT;
if (EC_POINT_is_on_curve(group, P, ctx) <= 0)
ABORT;
if (!BN_hex2bn(&z, "1FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
"FFFFFFFFFFFFFFFFFFFFA51868783BF2F966B7FCC0148F709A5D03BB5"
"C9B8899C47AEBB6FB71E91386409"))
ABORT;
if (!EC_GROUP_set_generator(group, P, z, BN_value_one()))
ABORT;
if (!EC_POINT_get_affine_coordinates_GFp(group, P, x, y, ctx))
ABORT;
fprintf(stdout, "\nNIST curve P-521 -- Generator:\n x = 0x");
BN_print_fp(stdout, x);
fprintf(stdout, "\n y = 0x");
BN_print_fp(stdout, y);
fprintf(stdout, "\n");
/* G_y value taken from the standard: */
if (!BN_hex2bn(&z, "11839296A789A3BC0045C8A5FB42C7D1BD998F54449579"
"B446817AFBD17273E662C97EE72995EF42640C550B9013FAD0761353C"
"7086A272C24088BE94769FD16650"))
ABORT;
if (0 != BN_cmp(y, z))
ABORT;
fprintf(stdout, "verify degree ...");
if (EC_GROUP_get_degree(group) != 521)
ABORT;
fprintf(stdout, " ok\n");
group_order_tests(group);
if (!(P_521 = EC_GROUP_new(EC_GROUP_method_of(group))))
ABORT;
if (!EC_GROUP_copy(P_521, group))
ABORT;
/* more tests using the last curve */
if (!EC_POINT_copy(Q, P))
ABORT;
if (EC_POINT_is_at_infinity(group, Q))
ABORT;
if (!EC_POINT_dbl(group, P, P, ctx))
ABORT;
if (EC_POINT_is_on_curve(group, P, ctx) <= 0)
ABORT;
if (!EC_POINT_invert(group, Q, ctx))
ABORT; /* P = -2Q */
if (!EC_POINT_add(group, R, P, Q, ctx))
ABORT;
if (!EC_POINT_add(group, R, R, Q, ctx))
ABORT;
if (!EC_POINT_is_at_infinity(group, R))
ABORT; /* R = P + 2Q */
{
const EC_POINT *points[4];
const BIGNUM *scalars[4];
BIGNUM scalar3;
if (EC_POINT_is_at_infinity(group, Q))
ABORT;
points[0] = Q;
points[1] = Q;
points[2] = Q;
points[3] = Q;
if (!EC_GROUP_get_order(group, z, ctx))
ABORT;
if (!BN_add(y, z, BN_value_one()))
ABORT;
if (BN_is_odd(y))
ABORT;
if (!BN_rshift1(y, y))
ABORT;
scalars[0] = y; /* (group order + 1)/2, so y*Q + y*Q = Q */
scalars[1] = y;
fprintf(stdout, "combined multiplication ...");
fflush(stdout);
/* z is still the group order */
if (!EC_POINTs_mul(group, P, NULL, 2, points, scalars, ctx))
ABORT;
if (!EC_POINTs_mul(group, R, z, 2, points, scalars, ctx))
ABORT;
if (0 != EC_POINT_cmp(group, P, R, ctx))
ABORT;
if (0 != EC_POINT_cmp(group, R, Q, ctx))
ABORT;
fprintf(stdout, ".");
fflush(stdout);
if (!BN_pseudo_rand(y, BN_num_bits(y), 0, 0))
ABORT;
if (!BN_add(z, z, y))
ABORT;
BN_set_negative(z, 1);
scalars[0] = y;
scalars[1] = z; /* z = -(order + y) */
if (!EC_POINTs_mul(group, P, NULL, 2, points, scalars, ctx))
ABORT;
if (!EC_POINT_is_at_infinity(group, P))
ABORT;
fprintf(stdout, ".");
fflush(stdout);
if (!BN_pseudo_rand(x, BN_num_bits(y) - 1, 0, 0))
ABORT;
if (!BN_add(z, x, y))
ABORT;
BN_set_negative(z, 1);
scalars[0] = x;
scalars[1] = y;
scalars[2] = z; /* z = -(x+y) */
BN_init(&scalar3);
BN_zero(&scalar3);
scalars[3] = &scalar3;
if (!EC_POINTs_mul(group, P, NULL, 4, points, scalars, ctx))
ABORT;
if (!EC_POINT_is_at_infinity(group, P))
ABORT;
fprintf(stdout, " ok\n\n");
BN_free(&scalar3);
}
# if 0
timings(P_160, TIMING_BASE_PT, ctx);
timings(P_160, TIMING_RAND_PT, ctx);
timings(P_160, TIMING_SIMUL, ctx);
timings(P_192, TIMING_BASE_PT, ctx);
timings(P_192, TIMING_RAND_PT, ctx);
timings(P_192, TIMING_SIMUL, ctx);
timings(P_224, TIMING_BASE_PT, ctx);
timings(P_224, TIMING_RAND_PT, ctx);
timings(P_224, TIMING_SIMUL, ctx);
timings(P_256, TIMING_BASE_PT, ctx);
timings(P_256, TIMING_RAND_PT, ctx);
timings(P_256, TIMING_SIMUL, ctx);
timings(P_384, TIMING_BASE_PT, ctx);
timings(P_384, TIMING_RAND_PT, ctx);
timings(P_384, TIMING_SIMUL, ctx);
timings(P_521, TIMING_BASE_PT, ctx);
timings(P_521, TIMING_RAND_PT, ctx);
timings(P_521, TIMING_SIMUL, ctx);
# endif
if (ctx)
BN_CTX_free(ctx);
BN_free(p);
BN_free(a);
BN_free(b);
EC_GROUP_free(group);
EC_POINT_free(P);
EC_POINT_free(Q);
EC_POINT_free(R);
BN_free(x);
BN_free(y);
BN_free(z);
if (P_160)
EC_GROUP_free(P_160);
if (P_192)
EC_GROUP_free(P_192);
if (P_224)
EC_GROUP_free(P_224);
if (P_256)
EC_GROUP_free(P_256);
if (P_384)
EC_GROUP_free(P_384);
if (P_521)
EC_GROUP_free(P_521);
}
/* Change test based on whether binary point compression is enabled or not. */
# ifdef OPENSSL_EC_BIN_PT_COMP
# define CHAR2_CURVE_TEST_INTERNAL(_name, _p, _a, _b, _x, _y, _y_bit, _order, _cof, _degree, _variable) \
if (!BN_hex2bn(&x, _x)) ABORT; \
if (!EC_POINT_set_compressed_coordinates_GF2m(group, P, x, _y_bit, ctx)) ABORT; \
if (EC_POINT_is_on_curve(group, P, ctx) <= 0) ABORT; \
if (!BN_hex2bn(&z, _order)) ABORT; \
if (!BN_hex2bn(&cof, _cof)) ABORT; \
if (!EC_GROUP_set_generator(group, P, z, cof)) ABORT; \
if (!EC_POINT_get_affine_coordinates_GF2m(group, P, x, y, ctx)) ABORT; \
fprintf(stdout, "\n%s -- Generator:\n x = 0x", _name); \
BN_print_fp(stdout, x); \
fprintf(stdout, "\n y = 0x"); \
BN_print_fp(stdout, y); \
fprintf(stdout, "\n"); \
/* G_y value taken from the standard: */ \
if (!BN_hex2bn(&z, _y)) ABORT; \
if (0 != BN_cmp(y, z)) ABORT;
# else
# define CHAR2_CURVE_TEST_INTERNAL(_name, _p, _a, _b, _x, _y, _y_bit, _order, _cof, _degree, _variable) \
if (!BN_hex2bn(&x, _x)) ABORT; \
if (!BN_hex2bn(&y, _y)) ABORT; \
if (!EC_POINT_set_affine_coordinates_GF2m(group, P, x, y, ctx)) ABORT; \
if (EC_POINT_is_on_curve(group, P, ctx) <= 0) ABORT; \
if (!BN_hex2bn(&z, _order)) ABORT; \
if (!BN_hex2bn(&cof, _cof)) ABORT; \
if (!EC_GROUP_set_generator(group, P, z, cof)) ABORT; \
fprintf(stdout, "\n%s -- Generator:\n x = 0x", _name); \
BN_print_fp(stdout, x); \
fprintf(stdout, "\n y = 0x"); \
BN_print_fp(stdout, y); \
fprintf(stdout, "\n");
# endif
# define CHAR2_CURVE_TEST(_name, _p, _a, _b, _x, _y, _y_bit, _order, _cof, _degree, _variable) \
if (!BN_hex2bn(&p, _p)) ABORT; \
if (!BN_hex2bn(&a, _a)) ABORT; \
if (!BN_hex2bn(&b, _b)) ABORT; \
if (!EC_GROUP_set_curve_GF2m(group, p, a, b, ctx)) ABORT; \
CHAR2_CURVE_TEST_INTERNAL(_name, _p, _a, _b, _x, _y, _y_bit, _order, _cof, _degree, _variable) \
fprintf(stdout, "verify degree ..."); \
if (EC_GROUP_get_degree(group) != _degree) ABORT; \
fprintf(stdout, " ok\n"); \
group_order_tests(group); \
if (!(_variable = EC_GROUP_new(EC_GROUP_method_of(group)))) ABORT; \
if (!EC_GROUP_copy(_variable, group)) ABORT; \
# ifndef OPENSSL_NO_EC2M
static void char2_field_tests(void)
{
BN_CTX *ctx = NULL;
BIGNUM *p, *a, *b;
EC_GROUP *group;
EC_GROUP *C2_K163 = NULL, *C2_K233 = NULL, *C2_K283 = NULL, *C2_K409 =
NULL, *C2_K571 = NULL;
EC_GROUP *C2_B163 = NULL, *C2_B233 = NULL, *C2_B283 = NULL, *C2_B409 =
NULL, *C2_B571 = NULL;
EC_POINT *P, *Q, *R;
BIGNUM *x, *y, *z, *cof;
unsigned char buf[100];
size_t i, len;
int k;
# if 1 /* optional */
ctx = BN_CTX_new();
if (!ctx)
ABORT;
# endif
p = BN_new();
a = BN_new();
b = BN_new();
if (!p || !a || !b)
ABORT;
if (!BN_hex2bn(&p, "13"))
ABORT;
if (!BN_hex2bn(&a, "3"))
ABORT;
if (!BN_hex2bn(&b, "1"))
ABORT;
group = EC_GROUP_new(EC_GF2m_simple_method()); /* applications should use
* EC_GROUP_new_curve_GF2m
* so that the library gets
* to choose the EC_METHOD */
if (!group)
ABORT;
if (!EC_GROUP_set_curve_GF2m(group, p, a, b, ctx))
ABORT;
{
EC_GROUP *tmp;
tmp = EC_GROUP_new(EC_GROUP_method_of(group));
if (!tmp)
ABORT;
if (!EC_GROUP_copy(tmp, group))
ABORT;
EC_GROUP_free(group);
group = tmp;
}
if (!EC_GROUP_get_curve_GF2m(group, p, a, b, ctx))
ABORT;
fprintf(stdout,
"Curve defined by Weierstrass equation\n y^2 + x*y = x^3 + a*x^2 + b (mod 0x");
BN_print_fp(stdout, p);
fprintf(stdout, ")\n a = 0x");
BN_print_fp(stdout, a);
fprintf(stdout, "\n b = 0x");
BN_print_fp(stdout, b);
fprintf(stdout, "\n(0x... means binary polynomial)\n");
P = EC_POINT_new(group);
Q = EC_POINT_new(group);
R = EC_POINT_new(group);
if (!P || !Q || !R)
ABORT;
if (!EC_POINT_set_to_infinity(group, P))
ABORT;
if (!EC_POINT_is_at_infinity(group, P))
ABORT;
buf[0] = 0;
if (!EC_POINT_oct2point(group, Q, buf, 1, ctx))
ABORT;
if (!EC_POINT_add(group, P, P, Q, ctx))
ABORT;
if (!EC_POINT_is_at_infinity(group, P))
ABORT;
x = BN_new();
y = BN_new();
z = BN_new();
cof = BN_new();
if (!x || !y || !z || !cof)
ABORT;
if (!BN_hex2bn(&x, "6"))
ABORT;
/* Change test based on whether binary point compression is enabled or not. */
# ifdef OPENSSL_EC_BIN_PT_COMP
if (!EC_POINT_set_compressed_coordinates_GF2m(group, Q, x, 1, ctx))
ABORT;
# else
if (!BN_hex2bn(&y, "8"))
ABORT;
if (!EC_POINT_set_affine_coordinates_GF2m(group, Q, x, y, ctx))
ABORT;
# endif
if (EC_POINT_is_on_curve(group, Q, ctx) <= 0) {
/* Change test based on whether binary point compression is enabled or not. */
# ifdef OPENSSL_EC_BIN_PT_COMP
if (!EC_POINT_get_affine_coordinates_GF2m(group, Q, x, y, ctx))
ABORT;
# endif
fprintf(stderr, "Point is not on curve: x = 0x");
BN_print_fp(stderr, x);
fprintf(stderr, ", y = 0x");
BN_print_fp(stderr, y);
fprintf(stderr, "\n");
ABORT;
}
fprintf(stdout, "A cyclic subgroup:\n");
k = 100;
do {
if (k-- == 0)
ABORT;
if (EC_POINT_is_at_infinity(group, P))
fprintf(stdout, " point at infinity\n");
else {
if (!EC_POINT_get_affine_coordinates_GF2m(group, P, x, y, ctx))
ABORT;
fprintf(stdout, " x = 0x");
BN_print_fp(stdout, x);
fprintf(stdout, ", y = 0x");
BN_print_fp(stdout, y);
fprintf(stdout, "\n");
}
if (!EC_POINT_copy(R, P))
ABORT;
if (!EC_POINT_add(group, P, P, Q, ctx))
ABORT;
}
while (!EC_POINT_is_at_infinity(group, P));
if (!EC_POINT_add(group, P, Q, R, ctx))
ABORT;
if (!EC_POINT_is_at_infinity(group, P))
ABORT;
/* Change test based on whether binary point compression is enabled or not. */
# ifdef OPENSSL_EC_BIN_PT_COMP
len =
EC_POINT_point2oct(group, Q, POINT_CONVERSION_COMPRESSED, buf,
- sizeof buf, ctx);
+ sizeof(buf), ctx);
if (len == 0)
ABORT;
if (!EC_POINT_oct2point(group, P, buf, len, ctx))
ABORT;
if (0 != EC_POINT_cmp(group, P, Q, ctx))
ABORT;
fprintf(stdout, "Generator as octet string, compressed form:\n ");
for (i = 0; i < len; i++)
fprintf(stdout, "%02X", buf[i]);
# endif
len =
EC_POINT_point2oct(group, Q, POINT_CONVERSION_UNCOMPRESSED, buf,
- sizeof buf, ctx);
+ sizeof(buf), ctx);
if (len == 0)
ABORT;
if (!EC_POINT_oct2point(group, P, buf, len, ctx))
ABORT;
if (0 != EC_POINT_cmp(group, P, Q, ctx))
ABORT;
fprintf(stdout, "\nGenerator as octet string, uncompressed form:\n ");
for (i = 0; i < len; i++)
fprintf(stdout, "%02X", buf[i]);
/* Change test based on whether binary point compression is enabled or not. */
# ifdef OPENSSL_EC_BIN_PT_COMP
len =
- EC_POINT_point2oct(group, Q, POINT_CONVERSION_HYBRID, buf, sizeof buf,
+ EC_POINT_point2oct(group, Q, POINT_CONVERSION_HYBRID, buf, sizeof(buf),
ctx);
if (len == 0)
ABORT;
if (!EC_POINT_oct2point(group, P, buf, len, ctx))
ABORT;
if (0 != EC_POINT_cmp(group, P, Q, ctx))
ABORT;
fprintf(stdout, "\nGenerator as octet string, hybrid form:\n ");
for (i = 0; i < len; i++)
fprintf(stdout, "%02X", buf[i]);
# endif
fprintf(stdout, "\n");
if (!EC_POINT_invert(group, P, ctx))
ABORT;
if (0 != EC_POINT_cmp(group, P, R, ctx))
ABORT;
/* Curve K-163 (FIPS PUB 186-2, App. 6) */
CHAR2_CURVE_TEST
("NIST curve K-163",
"0800000000000000000000000000000000000000C9",
"1",
"1",
"02FE13C0537BBC11ACAA07D793DE4E6D5E5C94EEE8",
"0289070FB05D38FF58321F2E800536D538CCDAA3D9",
1, "04000000000000000000020108A2E0CC0D99F8A5EF", "2", 163, C2_K163);
/* Curve B-163 (FIPS PUB 186-2, App. 6) */
CHAR2_CURVE_TEST
("NIST curve B-163",
"0800000000000000000000000000000000000000C9",
"1",
"020A601907B8C953CA1481EB10512F78744A3205FD",
"03F0EBA16286A2D57EA0991168D4994637E8343E36",
"00D51FBC6C71A0094FA2CDD545B11C5C0C797324F1",
1, "040000000000000000000292FE77E70C12A4234C33", "2", 163, C2_B163);
/* Curve K-233 (FIPS PUB 186-2, App. 6) */
CHAR2_CURVE_TEST
("NIST curve K-233",
"020000000000000000000000000000000000000004000000000000000001",
"0",
"1",
"017232BA853A7E731AF129F22FF4149563A419C26BF50A4C9D6EEFAD6126",
"01DB537DECE819B7F70F555A67C427A8CD9BF18AEB9B56E0C11056FAE6A3",
0,
"008000000000000000000000000000069D5BB915BCD46EFB1AD5F173ABDF",
"4", 233, C2_K233);
/* Curve B-233 (FIPS PUB 186-2, App. 6) */
CHAR2_CURVE_TEST
("NIST curve B-233",
"020000000000000000000000000000000000000004000000000000000001",
"000000000000000000000000000000000000000000000000000000000001",
"0066647EDE6C332C7F8C0923BB58213B333B20E9CE4281FE115F7D8F90AD",
"00FAC9DFCBAC8313BB2139F1BB755FEF65BC391F8B36F8F8EB7371FD558B",
"01006A08A41903350678E58528BEBF8A0BEFF867A7CA36716F7E01F81052",
1,
"01000000000000000000000000000013E974E72F8A6922031D2603CFE0D7",
"2", 233, C2_B233);
/* Curve K-283 (FIPS PUB 186-2, App. 6) */
CHAR2_CURVE_TEST
("NIST curve K-283",
"0800000000000000000000000000000000000000000000000000000000000000000010A1",
"0",
"1",
"0503213F78CA44883F1A3B8162F188E553CD265F23C1567A16876913B0C2AC2458492836",
"01CCDA380F1C9E318D90F95D07E5426FE87E45C0E8184698E45962364E34116177DD2259",
0,
"01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFE9AE2ED07577265DFF7F94451E061E163C61",
"4", 283, C2_K283);
/* Curve B-283 (FIPS PUB 186-2, App. 6) */
CHAR2_CURVE_TEST
("NIST curve B-283",
"0800000000000000000000000000000000000000000000000000000000000000000010A1",
"000000000000000000000000000000000000000000000000000000000000000000000001",
"027B680AC8B8596DA5A4AF8A19A0303FCA97FD7645309FA2A581485AF6263E313B79A2F5",
"05F939258DB7DD90E1934F8C70B0DFEC2EED25B8557EAC9C80E2E198F8CDBECD86B12053",
"03676854FE24141CB98FE6D4B20D02B4516FF702350EDDB0826779C813F0DF45BE8112F4",
1,
"03FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEF90399660FC938A90165B042A7CEFADB307",
"2", 283, C2_B283);
/* Curve K-409 (FIPS PUB 186-2, App. 6) */
CHAR2_CURVE_TEST
("NIST curve K-409",
"02000000000000000000000000000000000000000000000000000000000000000000000000000000008000000000000000000001",
"0",
"1",
"0060F05F658F49C1AD3AB1890F7184210EFD0987E307C84C27ACCFB8F9F67CC2C460189EB5AAAA62EE222EB1B35540CFE9023746",
"01E369050B7C4E42ACBA1DACBF04299C3460782F918EA427E6325165E9EA10E3DA5F6C42E9C55215AA9CA27A5863EC48D8E0286B",
1,
"007FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFE5F83B2D4EA20400EC4557D5ED3E3E7CA5B4B5C83B8E01E5FCF",
"4", 409, C2_K409);
/* Curve B-409 (FIPS PUB 186-2, App. 6) */
CHAR2_CURVE_TEST
("NIST curve B-409",
"02000000000000000000000000000000000000000000000000000000000000000000000000000000008000000000000000000001",
"00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001",
"0021A5C2C8EE9FEB5C4B9A753B7B476B7FD6422EF1F3DD674761FA99D6AC27C8A9A197B272822F6CD57A55AA4F50AE317B13545F",
"015D4860D088DDB3496B0C6064756260441CDE4AF1771D4DB01FFE5B34E59703DC255A868A1180515603AEAB60794E54BB7996A7",
"0061B1CFAB6BE5F32BBFA78324ED106A7636B9C5A7BD198D0158AA4F5488D08F38514F1FDF4B4F40D2181B3681C364BA0273C706",
1,
"010000000000000000000000000000000000000000000000000001E2AAD6A612F33307BE5FA47C3C9E052F838164CD37D9A21173",
"2", 409, C2_B409);
/* Curve K-571 (FIPS PUB 186-2, App. 6) */
CHAR2_CURVE_TEST
("NIST curve K-571",
"80000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000425",
"0",
"1",
"026EB7A859923FBC82189631F8103FE4AC9CA2970012D5D46024804801841CA44370958493B205E647DA304DB4CEB08CBBD1BA39494776FB988B47174DCA88C7E2945283A01C8972",
"0349DC807F4FBF374F4AEADE3BCA95314DD58CEC9F307A54FFC61EFC006D8A2C9D4979C0AC44AEA74FBEBBB9F772AEDCB620B01A7BA7AF1B320430C8591984F601CD4C143EF1C7A3",
0,
"020000000000000000000000000000000000000000000000000000000000000000000000131850E1F19A63E4B391A8DB917F4138B630D84BE5D639381E91DEB45CFE778F637C1001",
"4", 571, C2_K571);
/* Curve B-571 (FIPS PUB 186-2, App. 6) */
CHAR2_CURVE_TEST
("NIST curve B-571",
"80000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000425",
"000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001",
"02F40E7E2221F295DE297117B7F3D62F5C6A97FFCB8CEFF1CD6BA8CE4A9A18AD84FFABBD8EFA59332BE7AD6756A66E294AFD185A78FF12AA520E4DE739BACA0C7FFEFF7F2955727A",
"0303001D34B856296C16C0D40D3CD7750A93D1D2955FA80AA5F40FC8DB7B2ABDBDE53950F4C0D293CDD711A35B67FB1499AE60038614F1394ABFA3B4C850D927E1E7769C8EEC2D19",
"037BF27342DA639B6DCCFFFEB73D69D78C6C27A6009CBBCA1980F8533921E8A684423E43BAB08A576291AF8F461BB2A8B3531D2F0485C19B16E2F1516E23DD3C1A4827AF1B8AC15B",
1,
"03FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFE661CE18FF55987308059B186823851EC7DD9CA1161DE93D5174D66E8382E9BB2FE84E47",
"2", 571, C2_B571);
/* more tests using the last curve */
if (!EC_POINT_copy(Q, P))
ABORT;
if (EC_POINT_is_at_infinity(group, Q))
ABORT;
if (!EC_POINT_dbl(group, P, P, ctx))
ABORT;
if (EC_POINT_is_on_curve(group, P, ctx) <= 0)
ABORT;
if (!EC_POINT_invert(group, Q, ctx))
ABORT; /* P = -2Q */
if (!EC_POINT_add(group, R, P, Q, ctx))
ABORT;
if (!EC_POINT_add(group, R, R, Q, ctx))
ABORT;
if (!EC_POINT_is_at_infinity(group, R))
ABORT; /* R = P + 2Q */
{
const EC_POINT *points[3];
const BIGNUM *scalars[3];
if (EC_POINT_is_at_infinity(group, Q))
ABORT;
points[0] = Q;
points[1] = Q;
points[2] = Q;
if (!BN_add(y, z, BN_value_one()))
ABORT;
if (BN_is_odd(y))
ABORT;
if (!BN_rshift1(y, y))
ABORT;
scalars[0] = y; /* (group order + 1)/2, so y*Q + y*Q = Q */
scalars[1] = y;
fprintf(stdout, "combined multiplication ...");
fflush(stdout);
/* z is still the group order */
if (!EC_POINTs_mul(group, P, NULL, 2, points, scalars, ctx))
ABORT;
if (!EC_POINTs_mul(group, R, z, 2, points, scalars, ctx))
ABORT;
if (0 != EC_POINT_cmp(group, P, R, ctx))
ABORT;
if (0 != EC_POINT_cmp(group, R, Q, ctx))
ABORT;
fprintf(stdout, ".");
fflush(stdout);
if (!BN_pseudo_rand(y, BN_num_bits(y), 0, 0))
ABORT;
if (!BN_add(z, z, y))
ABORT;
BN_set_negative(z, 1);
scalars[0] = y;
scalars[1] = z; /* z = -(order + y) */
if (!EC_POINTs_mul(group, P, NULL, 2, points, scalars, ctx))
ABORT;
if (!EC_POINT_is_at_infinity(group, P))
ABORT;
fprintf(stdout, ".");
fflush(stdout);
if (!BN_pseudo_rand(x, BN_num_bits(y) - 1, 0, 0))
ABORT;
if (!BN_add(z, x, y))
ABORT;
BN_set_negative(z, 1);
scalars[0] = x;
scalars[1] = y;
scalars[2] = z; /* z = -(x+y) */
if (!EC_POINTs_mul(group, P, NULL, 3, points, scalars, ctx))
ABORT;
if (!EC_POINT_is_at_infinity(group, P))
ABORT;
fprintf(stdout, " ok\n\n");
}
# if 0
timings(C2_K163, TIMING_BASE_PT, ctx);
timings(C2_K163, TIMING_RAND_PT, ctx);
timings(C2_K163, TIMING_SIMUL, ctx);
timings(C2_B163, TIMING_BASE_PT, ctx);
timings(C2_B163, TIMING_RAND_PT, ctx);
timings(C2_B163, TIMING_SIMUL, ctx);
timings(C2_K233, TIMING_BASE_PT, ctx);
timings(C2_K233, TIMING_RAND_PT, ctx);
timings(C2_K233, TIMING_SIMUL, ctx);
timings(C2_B233, TIMING_BASE_PT, ctx);
timings(C2_B233, TIMING_RAND_PT, ctx);
timings(C2_B233, TIMING_SIMUL, ctx);
timings(C2_K283, TIMING_BASE_PT, ctx);
timings(C2_K283, TIMING_RAND_PT, ctx);
timings(C2_K283, TIMING_SIMUL, ctx);
timings(C2_B283, TIMING_BASE_PT, ctx);
timings(C2_B283, TIMING_RAND_PT, ctx);
timings(C2_B283, TIMING_SIMUL, ctx);
timings(C2_K409, TIMING_BASE_PT, ctx);
timings(C2_K409, TIMING_RAND_PT, ctx);
timings(C2_K409, TIMING_SIMUL, ctx);
timings(C2_B409, TIMING_BASE_PT, ctx);
timings(C2_B409, TIMING_RAND_PT, ctx);
timings(C2_B409, TIMING_SIMUL, ctx);
timings(C2_K571, TIMING_BASE_PT, ctx);
timings(C2_K571, TIMING_RAND_PT, ctx);
timings(C2_K571, TIMING_SIMUL, ctx);
timings(C2_B571, TIMING_BASE_PT, ctx);
timings(C2_B571, TIMING_RAND_PT, ctx);
timings(C2_B571, TIMING_SIMUL, ctx);
# endif
if (ctx)
BN_CTX_free(ctx);
BN_free(p);
BN_free(a);
BN_free(b);
EC_GROUP_free(group);
EC_POINT_free(P);
EC_POINT_free(Q);
EC_POINT_free(R);
BN_free(x);
BN_free(y);
BN_free(z);
BN_free(cof);
if (C2_K163)
EC_GROUP_free(C2_K163);
if (C2_B163)
EC_GROUP_free(C2_B163);
if (C2_K233)
EC_GROUP_free(C2_K233);
if (C2_B233)
EC_GROUP_free(C2_B233);
if (C2_K283)
EC_GROUP_free(C2_K283);
if (C2_B283)
EC_GROUP_free(C2_B283);
if (C2_K409)
EC_GROUP_free(C2_K409);
if (C2_B409)
EC_GROUP_free(C2_B409);
if (C2_K571)
EC_GROUP_free(C2_K571);
if (C2_B571)
EC_GROUP_free(C2_B571);
}
# endif
static void internal_curve_test(void)
{
EC_builtin_curve *curves = NULL;
size_t crv_len = 0, n = 0;
int ok = 1;
crv_len = EC_get_builtin_curves(NULL, 0);
curves = OPENSSL_malloc(sizeof(EC_builtin_curve) * crv_len);
if (curves == NULL)
return;
if (!EC_get_builtin_curves(curves, crv_len)) {
OPENSSL_free(curves);
return;
}
fprintf(stdout, "testing internal curves: ");
for (n = 0; n < crv_len; n++) {
EC_GROUP *group = NULL;
int nid = curves[n].nid;
if ((group = EC_GROUP_new_by_curve_name(nid)) == NULL) {
ok = 0;
fprintf(stdout, "\nEC_GROUP_new_curve_name() failed with"
" curve %s\n", OBJ_nid2sn(nid));
/* try next curve */
continue;
}
if (!EC_GROUP_check(group, NULL)) {
ok = 0;
fprintf(stdout, "\nEC_GROUP_check() failed with"
" curve %s\n", OBJ_nid2sn(nid));
EC_GROUP_free(group);
/* try the next curve */
continue;
}
fprintf(stdout, ".");
fflush(stdout);
EC_GROUP_free(group);
}
if (ok)
fprintf(stdout, " ok\n\n");
else {
fprintf(stdout, " failed\n\n");
ABORT;
}
OPENSSL_free(curves);
return;
}
# ifndef OPENSSL_NO_EC_NISTP_64_GCC_128
/*
* nistp_test_params contains magic numbers for testing our optimized
* implementations of several NIST curves with characteristic > 3.
*/
struct nistp_test_params {
const EC_METHOD *(*meth) ();
int degree;
/*
* Qx, Qy and D are taken from
* http://csrc.nist.gov/groups/ST/toolkit/documents/Examples/ECDSA_Prime.pdf
* Otherwise, values are standard curve parameters from FIPS 180-3
*/
const char *p, *a, *b, *Qx, *Qy, *Gx, *Gy, *order, *d;
};
static const struct nistp_test_params nistp_tests_params[] = {
{
/* P-224 */
EC_GFp_nistp224_method,
224,
/* p */
"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF000000000000000000000001",
/* a */
"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFE",
/* b */
"B4050A850C04B3ABF54132565044B0B7D7BFD8BA270B39432355FFB4",
/* Qx */
"E84FB0B8E7000CB657D7973CF6B42ED78B301674276DF744AF130B3E",
/* Qy */
"4376675C6FC5612C21A0FF2D2A89D2987DF7A2BC52183B5982298555",
/* Gx */
"B70E0CBD6BB4BF7F321390B94A03C1D356C21122343280D6115C1D21",
/* Gy */
"BD376388B5F723FB4C22DFE6CD4375A05A07476444D5819985007E34",
/* order */
"FFFFFFFFFFFFFFFFFFFFFFFFFFFF16A2E0B8F03E13DD29455C5C2A3D",
/* d */
"3F0C488E987C80BE0FEE521F8D90BE6034EC69AE11CA72AA777481E8",
},
{
/* P-256 */
EC_GFp_nistp256_method,
256,
/* p */
"ffffffff00000001000000000000000000000000ffffffffffffffffffffffff",
/* a */
"ffffffff00000001000000000000000000000000fffffffffffffffffffffffc",
/* b */
"5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b",
/* Qx */
"b7e08afdfe94bad3f1dc8c734798ba1c62b3a0ad1e9ea2a38201cd0889bc7a19",
/* Qy */
"3603f747959dbf7a4bb226e41928729063adc7ae43529e61b563bbc606cc5e09",
/* Gx */
"6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296",
/* Gy */
"4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5",
/* order */
"ffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551",
/* d */
"c477f9f65c22cce20657faa5b2d1d8122336f851a508a1ed04e479c34985bf96",
},
{
/* P-521 */
EC_GFp_nistp521_method,
521,
/* p */
"1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
/* a */
"1fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc",
/* b */
"051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00",
/* Qx */
"0098e91eef9a68452822309c52fab453f5f117c1da8ed796b255e9ab8f6410cca16e59df403a6bdc6ca467a37056b1e54b3005d8ac030decfeb68df18b171885d5c4",
/* Qy */
"0164350c321aecfc1cca1ba4364c9b15656150b4b78d6a48d7d28e7f31985ef17be8554376b72900712c4b83ad668327231526e313f5f092999a4632fd50d946bc2e",
/* Gx */
"c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66",
/* Gy */
"11839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650",
/* order */
"1fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409",
/* d */
"0100085f47b8e1b8b11b7eb33028c0b2888e304bfc98501955b45bba1478dc184eeedf09b86a5f7c21994406072787205e69a63709fe35aa93ba333514b24f961722",
},
};
static void nistp_single_test(const struct nistp_test_params *test)
{
BN_CTX *ctx;
BIGNUM *p, *a, *b, *x, *y, *n, *m, *order;
EC_GROUP *NISTP;
EC_POINT *G, *P, *Q, *Q_CHECK;
fprintf(stdout, "\nNIST curve P-%d (optimised implementation):\n",
test->degree);
ctx = BN_CTX_new();
p = BN_new();
a = BN_new();
b = BN_new();
x = BN_new();
y = BN_new();
m = BN_new();
n = BN_new();
order = BN_new();
NISTP = EC_GROUP_new(test->meth());
if (!NISTP)
ABORT;
if (!BN_hex2bn(&p, test->p))
ABORT;
if (1 != BN_is_prime_ex(p, BN_prime_checks, ctx, NULL))
ABORT;
if (!BN_hex2bn(&a, test->a))
ABORT;
if (!BN_hex2bn(&b, test->b))
ABORT;
if (!EC_GROUP_set_curve_GFp(NISTP, p, a, b, ctx))
ABORT;
G = EC_POINT_new(NISTP);
P = EC_POINT_new(NISTP);
Q = EC_POINT_new(NISTP);
Q_CHECK = EC_POINT_new(NISTP);
if (!BN_hex2bn(&x, test->Qx))
ABORT;
if (!BN_hex2bn(&y, test->Qy))
ABORT;
if (!EC_POINT_set_affine_coordinates_GFp(NISTP, Q_CHECK, x, y, ctx))
ABORT;
if (!BN_hex2bn(&x, test->Gx))
ABORT;
if (!BN_hex2bn(&y, test->Gy))
ABORT;
if (!EC_POINT_set_affine_coordinates_GFp(NISTP, G, x, y, ctx))
ABORT;
if (!BN_hex2bn(&order, test->order))
ABORT;
if (!EC_GROUP_set_generator(NISTP, G, order, BN_value_one()))
ABORT;
fprintf(stdout, "verify degree ... ");
if (EC_GROUP_get_degree(NISTP) != test->degree)
ABORT;
fprintf(stdout, "ok\n");
fprintf(stdout, "NIST test vectors ... ");
if (!BN_hex2bn(&n, test->d))
ABORT;
/* fixed point multiplication */
EC_POINT_mul(NISTP, Q, n, NULL, NULL, ctx);
if (0 != EC_POINT_cmp(NISTP, Q, Q_CHECK, ctx))
ABORT;
/* random point multiplication */
EC_POINT_mul(NISTP, Q, NULL, G, n, ctx);
if (0 != EC_POINT_cmp(NISTP, Q, Q_CHECK, ctx))
ABORT;
/* set generator to P = 2*G, where G is the standard generator */
if (!EC_POINT_dbl(NISTP, P, G, ctx))
ABORT;
if (!EC_GROUP_set_generator(NISTP, P, order, BN_value_one()))
ABORT;
/* set the scalar to m=n/2, where n is the NIST test scalar */
if (!BN_rshift(m, n, 1))
ABORT;
/* test the non-standard generator */
/* fixed point multiplication */
EC_POINT_mul(NISTP, Q, m, NULL, NULL, ctx);
if (0 != EC_POINT_cmp(NISTP, Q, Q_CHECK, ctx))
ABORT;
/* random point multiplication */
EC_POINT_mul(NISTP, Q, NULL, P, m, ctx);
if (0 != EC_POINT_cmp(NISTP, Q, Q_CHECK, ctx))
ABORT;
/*
* We have not performed precomputation so have_precompute mult should be
* false
*/
if (EC_GROUP_have_precompute_mult(NISTP))
ABORT;
/* now repeat all tests with precomputation */
if (!EC_GROUP_precompute_mult(NISTP, ctx))
ABORT;
if (!EC_GROUP_have_precompute_mult(NISTP))
ABORT;
/* fixed point multiplication */
EC_POINT_mul(NISTP, Q, m, NULL, NULL, ctx);
if (0 != EC_POINT_cmp(NISTP, Q, Q_CHECK, ctx))
ABORT;
/* random point multiplication */
EC_POINT_mul(NISTP, Q, NULL, P, m, ctx);
if (0 != EC_POINT_cmp(NISTP, Q, Q_CHECK, ctx))
ABORT;
/* reset generator */
if (!EC_GROUP_set_generator(NISTP, G, order, BN_value_one()))
ABORT;
/* fixed point multiplication */
EC_POINT_mul(NISTP, Q, n, NULL, NULL, ctx);
if (0 != EC_POINT_cmp(NISTP, Q, Q_CHECK, ctx))
ABORT;
/* random point multiplication */
EC_POINT_mul(NISTP, Q, NULL, G, n, ctx);
if (0 != EC_POINT_cmp(NISTP, Q, Q_CHECK, ctx))
ABORT;
fprintf(stdout, "ok\n");
group_order_tests(NISTP);
# if 0
timings(NISTP, TIMING_BASE_PT, ctx);
timings(NISTP, TIMING_RAND_PT, ctx);
# endif
EC_GROUP_free(NISTP);
EC_POINT_free(G);
EC_POINT_free(P);
EC_POINT_free(Q);
EC_POINT_free(Q_CHECK);
BN_free(n);
BN_free(m);
BN_free(p);
BN_free(a);
BN_free(b);
BN_free(x);
BN_free(y);
BN_free(order);
BN_CTX_free(ctx);
}
static void nistp_tests()
{
unsigned i;
for (i = 0;
i < sizeof(nistp_tests_params) / sizeof(struct nistp_test_params);
i++) {
nistp_single_test(&nistp_tests_params[i]);
}
}
# endif
static const char rnd_seed[] =
"string to make the random number generator think it has entropy";
int main(int argc, char *argv[])
{
/* enable memory leak checking unless explicitly disabled */
if (!((getenv("OPENSSL_DEBUG_MEMORY") != NULL)
&& (0 == strcmp(getenv("OPENSSL_DEBUG_MEMORY"), "off")))) {
CRYPTO_malloc_debug_init();
CRYPTO_set_mem_debug_options(V_CRYPTO_MDEBUG_ALL);
} else {
/* OPENSSL_DEBUG_MEMORY=off */
CRYPTO_set_mem_debug_functions(0, 0, 0, 0, 0);
}
CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON);
ERR_load_crypto_strings();
- RAND_seed(rnd_seed, sizeof rnd_seed); /* or BN_generate_prime may fail */
+ RAND_seed(rnd_seed, sizeof(rnd_seed)); /* or BN_generate_prime may fail */
prime_field_tests();
puts("");
# ifndef OPENSSL_NO_EC2M
char2_field_tests();
# endif
# ifndef OPENSSL_NO_EC_NISTP_64_GCC_128
nistp_tests();
# endif
/* test the internal curves */
internal_curve_test();
# ifndef OPENSSL_NO_ENGINE
ENGINE_cleanup();
# endif
CRYPTO_cleanup_all_ex_data();
ERR_free_strings();
ERR_remove_thread_state(NULL);
CRYPTO_mem_leaks_fp(stderr);
return 0;
}
#endif
diff --git a/crypto/ecdh/ecdhtest.c b/crypto/ecdh/ecdhtest.c
index 2fe2c66443d0..3febf10188ba 100644
--- a/crypto/ecdh/ecdhtest.c
+++ b/crypto/ecdh/ecdhtest.c
@@ -1,580 +1,580 @@
/* crypto/ecdh/ecdhtest.c */
/* ====================================================================
* Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
*
* The Elliptic Curve Public-Key Crypto Library (ECC Code) included
* herein is developed by SUN MICROSYSTEMS, INC., and is contributed
* to the OpenSSL project.
*
* The ECC Code is licensed pursuant to the OpenSSL open source
* license provided below.
*
* The ECDH software is originally written by Douglas Stebila of
* Sun Microsystems Laboratories.
*
*/
/* ====================================================================
* Copyright (c) 1998-2003 The OpenSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* openssl-core@openssl.org.
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.openssl.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*
* This product includes cryptographic software written by Eric Young
* (eay@cryptsoft.com). This product includes software written by Tim
* Hudson (tjh@cryptsoft.com).
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "../e_os.h"
#include <openssl/opensslconf.h> /* for OPENSSL_NO_ECDH */
#include <openssl/crypto.h>
#include <openssl/bio.h>
#include <openssl/bn.h>
#include <openssl/objects.h>
#include <openssl/rand.h>
#include <openssl/sha.h>
#include <openssl/err.h>
#ifdef OPENSSL_NO_ECDH
int main(int argc, char *argv[])
{
printf("No ECDH support\n");
return (0);
}
#else
# include <openssl/ec.h>
# include <openssl/ecdh.h>
# ifdef OPENSSL_SYS_WIN16
# define MS_CALLBACK _far _loadds
# else
# define MS_CALLBACK
# endif
# if 0
static void MS_CALLBACK cb(int p, int n, void *arg);
# endif
static const char rnd_seed[] =
"string to make the random number generator think it has entropy";
static const int KDF1_SHA1_len = 20;
static void *KDF1_SHA1(const void *in, size_t inlen, void *out,
size_t *outlen)
{
# ifndef OPENSSL_NO_SHA
if (*outlen < SHA_DIGEST_LENGTH)
return NULL;
else
*outlen = SHA_DIGEST_LENGTH;
return SHA1(in, inlen, out);
# else
return NULL;
# endif
}
static int test_ecdh_curve(int nid, const char *text, BN_CTX *ctx, BIO *out)
{
EC_KEY *a = NULL;
EC_KEY *b = NULL;
BIGNUM *x_a = NULL, *y_a = NULL, *x_b = NULL, *y_b = NULL;
char buf[12];
unsigned char *abuf = NULL, *bbuf = NULL;
int i, alen, blen, aout, bout, ret = 0;
const EC_GROUP *group;
a = EC_KEY_new_by_curve_name(nid);
b = EC_KEY_new_by_curve_name(nid);
if (a == NULL || b == NULL)
goto err;
group = EC_KEY_get0_group(a);
if ((x_a = BN_new()) == NULL)
goto err;
if ((y_a = BN_new()) == NULL)
goto err;
if ((x_b = BN_new()) == NULL)
goto err;
if ((y_b = BN_new()) == NULL)
goto err;
BIO_puts(out, "Testing key generation with ");
BIO_puts(out, text);
# ifdef NOISY
BIO_puts(out, "\n");
# else
(void)BIO_flush(out);
# endif
if (!EC_KEY_generate_key(a))
goto err;
if (EC_METHOD_get_field_type(EC_GROUP_method_of(group)) ==
NID_X9_62_prime_field) {
if (!EC_POINT_get_affine_coordinates_GFp
(group, EC_KEY_get0_public_key(a), x_a, y_a, ctx))
goto err;
}
# ifndef OPENSSL_NO_EC2M
else {
if (!EC_POINT_get_affine_coordinates_GF2m(group,
EC_KEY_get0_public_key(a),
x_a, y_a, ctx))
goto err;
}
# endif
# ifdef NOISY
BIO_puts(out, " pri 1=");
BN_print(out, a->priv_key);
BIO_puts(out, "\n pub 1=");
BN_print(out, x_a);
BIO_puts(out, ",");
BN_print(out, y_a);
BIO_puts(out, "\n");
# else
BIO_printf(out, " .");
(void)BIO_flush(out);
# endif
if (!EC_KEY_generate_key(b))
goto err;
if (EC_METHOD_get_field_type(EC_GROUP_method_of(group)) ==
NID_X9_62_prime_field) {
if (!EC_POINT_get_affine_coordinates_GFp
(group, EC_KEY_get0_public_key(b), x_b, y_b, ctx))
goto err;
}
# ifndef OPENSSL_NO_EC2M
else {
if (!EC_POINT_get_affine_coordinates_GF2m(group,
EC_KEY_get0_public_key(b),
x_b, y_b, ctx))
goto err;
}
# endif
# ifdef NOISY
BIO_puts(out, " pri 2=");
BN_print(out, b->priv_key);
BIO_puts(out, "\n pub 2=");
BN_print(out, x_b);
BIO_puts(out, ",");
BN_print(out, y_b);
BIO_puts(out, "\n");
# else
BIO_printf(out, ".");
(void)BIO_flush(out);
# endif
alen = KDF1_SHA1_len;
abuf = (unsigned char *)OPENSSL_malloc(alen);
aout =
ECDH_compute_key(abuf, alen, EC_KEY_get0_public_key(b), a, KDF1_SHA1);
# ifdef NOISY
BIO_puts(out, " key1 =");
for (i = 0; i < aout; i++) {
sprintf(buf, "%02X", abuf[i]);
BIO_puts(out, buf);
}
BIO_puts(out, "\n");
# else
BIO_printf(out, ".");
(void)BIO_flush(out);
# endif
blen = KDF1_SHA1_len;
bbuf = (unsigned char *)OPENSSL_malloc(blen);
bout =
ECDH_compute_key(bbuf, blen, EC_KEY_get0_public_key(a), b, KDF1_SHA1);
# ifdef NOISY
BIO_puts(out, " key2 =");
for (i = 0; i < bout; i++) {
sprintf(buf, "%02X", bbuf[i]);
BIO_puts(out, buf);
}
BIO_puts(out, "\n");
# else
BIO_printf(out, ".");
(void)BIO_flush(out);
# endif
if ((aout < 4) || (bout != aout) || (memcmp(abuf, bbuf, aout) != 0)) {
# ifndef NOISY
BIO_printf(out, " failed\n\n");
BIO_printf(out, "key a:\n");
BIO_printf(out, "private key: ");
BN_print(out, EC_KEY_get0_private_key(a));
BIO_printf(out, "\n");
BIO_printf(out, "public key (x,y): ");
BN_print(out, x_a);
BIO_printf(out, ",");
BN_print(out, y_a);
BIO_printf(out, "\nkey b:\n");
BIO_printf(out, "private key: ");
BN_print(out, EC_KEY_get0_private_key(b));
BIO_printf(out, "\n");
BIO_printf(out, "public key (x,y): ");
BN_print(out, x_b);
BIO_printf(out, ",");
BN_print(out, y_b);
BIO_printf(out, "\n");
BIO_printf(out, "generated key a: ");
for (i = 0; i < bout; i++) {
sprintf(buf, "%02X", bbuf[i]);
BIO_puts(out, buf);
}
BIO_printf(out, "\n");
BIO_printf(out, "generated key b: ");
for (i = 0; i < aout; i++) {
sprintf(buf, "%02X", abuf[i]);
BIO_puts(out, buf);
}
BIO_printf(out, "\n");
# endif
fprintf(stderr, "Error in ECDH routines\n");
ret = 0;
} else {
# ifndef NOISY
BIO_printf(out, " ok\n");
# endif
ret = 1;
}
err:
ERR_print_errors_fp(stderr);
if (abuf != NULL)
OPENSSL_free(abuf);
if (bbuf != NULL)
OPENSSL_free(bbuf);
if (x_a)
BN_free(x_a);
if (y_a)
BN_free(y_a);
if (x_b)
BN_free(x_b);
if (y_b)
BN_free(y_b);
if (b)
EC_KEY_free(b);
if (a)
EC_KEY_free(a);
return (ret);
}
/* Keys and shared secrets from RFC 7027 */
static const unsigned char bp256_da[] = {
0x81, 0xDB, 0x1E, 0xE1, 0x00, 0x15, 0x0F, 0xF2, 0xEA, 0x33, 0x8D, 0x70,
0x82, 0x71, 0xBE, 0x38, 0x30, 0x0C, 0xB5, 0x42, 0x41, 0xD7, 0x99, 0x50,
0xF7, 0x7B, 0x06, 0x30, 0x39, 0x80, 0x4F, 0x1D
};
static const unsigned char bp256_db[] = {
0x55, 0xE4, 0x0B, 0xC4, 0x1E, 0x37, 0xE3, 0xE2, 0xAD, 0x25, 0xC3, 0xC6,
0x65, 0x45, 0x11, 0xFF, 0xA8, 0x47, 0x4A, 0x91, 0xA0, 0x03, 0x20, 0x87,
0x59, 0x38, 0x52, 0xD3, 0xE7, 0xD7, 0x6B, 0xD3
};
static const unsigned char bp256_Z[] = {
0x89, 0xAF, 0xC3, 0x9D, 0x41, 0xD3, 0xB3, 0x27, 0x81, 0x4B, 0x80, 0x94,
0x0B, 0x04, 0x25, 0x90, 0xF9, 0x65, 0x56, 0xEC, 0x91, 0xE6, 0xAE, 0x79,
0x39, 0xBC, 0xE3, 0x1F, 0x3A, 0x18, 0xBF, 0x2B
};
static const unsigned char bp384_da[] = {
0x1E, 0x20, 0xF5, 0xE0, 0x48, 0xA5, 0x88, 0x6F, 0x1F, 0x15, 0x7C, 0x74,
0xE9, 0x1B, 0xDE, 0x2B, 0x98, 0xC8, 0xB5, 0x2D, 0x58, 0xE5, 0x00, 0x3D,
0x57, 0x05, 0x3F, 0xC4, 0xB0, 0xBD, 0x65, 0xD6, 0xF1, 0x5E, 0xB5, 0xD1,
0xEE, 0x16, 0x10, 0xDF, 0x87, 0x07, 0x95, 0x14, 0x36, 0x27, 0xD0, 0x42
};
static const unsigned char bp384_db[] = {
0x03, 0x26, 0x40, 0xBC, 0x60, 0x03, 0xC5, 0x92, 0x60, 0xF7, 0x25, 0x0C,
0x3D, 0xB5, 0x8C, 0xE6, 0x47, 0xF9, 0x8E, 0x12, 0x60, 0xAC, 0xCE, 0x4A,
0xCD, 0xA3, 0xDD, 0x86, 0x9F, 0x74, 0xE0, 0x1F, 0x8B, 0xA5, 0xE0, 0x32,
0x43, 0x09, 0xDB, 0x6A, 0x98, 0x31, 0x49, 0x7A, 0xBA, 0xC9, 0x66, 0x70
};
static const unsigned char bp384_Z[] = {
0x0B, 0xD9, 0xD3, 0xA7, 0xEA, 0x0B, 0x3D, 0x51, 0x9D, 0x09, 0xD8, 0xE4,
0x8D, 0x07, 0x85, 0xFB, 0x74, 0x4A, 0x6B, 0x35, 0x5E, 0x63, 0x04, 0xBC,
0x51, 0xC2, 0x29, 0xFB, 0xBC, 0xE2, 0x39, 0xBB, 0xAD, 0xF6, 0x40, 0x37,
0x15, 0xC3, 0x5D, 0x4F, 0xB2, 0xA5, 0x44, 0x4F, 0x57, 0x5D, 0x4F, 0x42
};
static const unsigned char bp512_da[] = {
0x16, 0x30, 0x2F, 0xF0, 0xDB, 0xBB, 0x5A, 0x8D, 0x73, 0x3D, 0xAB, 0x71,
0x41, 0xC1, 0xB4, 0x5A, 0xCB, 0xC8, 0x71, 0x59, 0x39, 0x67, 0x7F, 0x6A,
0x56, 0x85, 0x0A, 0x38, 0xBD, 0x87, 0xBD, 0x59, 0xB0, 0x9E, 0x80, 0x27,
0x96, 0x09, 0xFF, 0x33, 0x3E, 0xB9, 0xD4, 0xC0, 0x61, 0x23, 0x1F, 0xB2,
0x6F, 0x92, 0xEE, 0xB0, 0x49, 0x82, 0xA5, 0xF1, 0xD1, 0x76, 0x4C, 0xAD,
0x57, 0x66, 0x54, 0x22
};
static const unsigned char bp512_db[] = {
0x23, 0x0E, 0x18, 0xE1, 0xBC, 0xC8, 0x8A, 0x36, 0x2F, 0xA5, 0x4E, 0x4E,
0xA3, 0x90, 0x20, 0x09, 0x29, 0x2F, 0x7F, 0x80, 0x33, 0x62, 0x4F, 0xD4,
0x71, 0xB5, 0xD8, 0xAC, 0xE4, 0x9D, 0x12, 0xCF, 0xAB, 0xBC, 0x19, 0x96,
0x3D, 0xAB, 0x8E, 0x2F, 0x1E, 0xBA, 0x00, 0xBF, 0xFB, 0x29, 0xE4, 0xD7,
0x2D, 0x13, 0xF2, 0x22, 0x45, 0x62, 0xF4, 0x05, 0xCB, 0x80, 0x50, 0x36,
0x66, 0xB2, 0x54, 0x29
};
static const unsigned char bp512_Z[] = {
0xA7, 0x92, 0x70, 0x98, 0x65, 0x5F, 0x1F, 0x99, 0x76, 0xFA, 0x50, 0xA9,
0xD5, 0x66, 0x86, 0x5D, 0xC5, 0x30, 0x33, 0x18, 0x46, 0x38, 0x1C, 0x87,
0x25, 0x6B, 0xAF, 0x32, 0x26, 0x24, 0x4B, 0x76, 0xD3, 0x64, 0x03, 0xC0,
0x24, 0xD7, 0xBB, 0xF0, 0xAA, 0x08, 0x03, 0xEA, 0xFF, 0x40, 0x5D, 0x3D,
0x24, 0xF1, 0x1A, 0x9B, 0x5C, 0x0B, 0xEF, 0x67, 0x9F, 0xE1, 0x45, 0x4B,
0x21, 0xC4, 0xCD, 0x1F
};
/* Given private value and NID, create EC_KEY structure */
static EC_KEY *mk_eckey(int nid, const unsigned char *p, size_t plen)
{
int ok = 0;
EC_KEY *k = NULL;
BIGNUM *priv = NULL;
EC_POINT *pub = NULL;
const EC_GROUP *grp;
k = EC_KEY_new_by_curve_name(nid);
if (!k)
goto err;
priv = BN_bin2bn(p, plen, NULL);
if (!priv)
goto err;
if (!EC_KEY_set_private_key(k, priv))
goto err;
grp = EC_KEY_get0_group(k);
pub = EC_POINT_new(grp);
if (!pub)
goto err;
if (!EC_POINT_mul(grp, pub, priv, NULL, NULL, NULL))
goto err;
if (!EC_KEY_set_public_key(k, pub))
goto err;
ok = 1;
err:
if (priv)
BN_clear_free(priv);
if (pub)
EC_POINT_free(pub);
if (ok)
return k;
else if (k)
EC_KEY_free(k);
return NULL;
}
/*
* Known answer test: compute shared secret and check it matches expected
* value.
*/
static int ecdh_kat(BIO *out, const char *cname, int nid,
const unsigned char *k1, size_t k1_len,
const unsigned char *k2, size_t k2_len,
const unsigned char *Z, size_t Zlen)
{
int rv = 0;
EC_KEY *key1 = NULL, *key2 = NULL;
unsigned char *Ztmp = NULL;
size_t Ztmplen;
BIO_puts(out, "Testing ECDH shared secret with ");
BIO_puts(out, cname);
key1 = mk_eckey(nid, k1, k1_len);
key2 = mk_eckey(nid, k2, k2_len);
if (!key1 || !key2)
goto err;
Ztmplen = (EC_GROUP_get_degree(EC_KEY_get0_group(key1)) + 7) / 8;
if (Ztmplen != Zlen)
goto err;
Ztmp = OPENSSL_malloc(Ztmplen);
if (!ECDH_compute_key(Ztmp, Ztmplen,
EC_KEY_get0_public_key(key2), key1, 0))
goto err;
if (memcmp(Ztmp, Z, Zlen))
goto err;
memset(Ztmp, 0, Zlen);
if (!ECDH_compute_key(Ztmp, Ztmplen,
EC_KEY_get0_public_key(key1), key2, 0))
goto err;
if (memcmp(Ztmp, Z, Zlen))
goto err;
rv = 1;
err:
if (key1)
EC_KEY_free(key1);
if (key2)
EC_KEY_free(key2);
if (Ztmp)
OPENSSL_free(Ztmp);
if (rv)
BIO_puts(out, " ok\n");
else {
fprintf(stderr, "Error in ECDH routines\n");
ERR_print_errors_fp(stderr);
}
return rv;
}
# define test_ecdh_kat(bio, curve, bits) \
ecdh_kat(bio, curve, NID_brainpoolP##bits##r1, \
bp##bits##_da, sizeof(bp##bits##_da), \
bp##bits##_db, sizeof(bp##bits##_db), \
bp##bits##_Z, sizeof(bp##bits##_Z))
int main(int argc, char *argv[])
{
BN_CTX *ctx = NULL;
int ret = 1;
BIO *out;
CRYPTO_malloc_debug_init();
CRYPTO_dbg_set_options(V_CRYPTO_MDEBUG_ALL);
CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON);
# ifdef OPENSSL_SYS_WIN32
CRYPTO_malloc_init();
# endif
- RAND_seed(rnd_seed, sizeof rnd_seed);
+ RAND_seed(rnd_seed, sizeof(rnd_seed));
out = BIO_new(BIO_s_file());
if (out == NULL)
EXIT(1);
BIO_set_fp(out, stdout, BIO_NOCLOSE);
if ((ctx = BN_CTX_new()) == NULL)
goto err;
/* NIST PRIME CURVES TESTS */
if (!test_ecdh_curve
(NID_X9_62_prime192v1, "NIST Prime-Curve P-192", ctx, out))
goto err;
if (!test_ecdh_curve(NID_secp224r1, "NIST Prime-Curve P-224", ctx, out))
goto err;
if (!test_ecdh_curve
(NID_X9_62_prime256v1, "NIST Prime-Curve P-256", ctx, out))
goto err;
if (!test_ecdh_curve(NID_secp384r1, "NIST Prime-Curve P-384", ctx, out))
goto err;
if (!test_ecdh_curve(NID_secp521r1, "NIST Prime-Curve P-521", ctx, out))
goto err;
# ifndef OPENSSL_NO_EC2M
/* NIST BINARY CURVES TESTS */
if (!test_ecdh_curve(NID_sect163k1, "NIST Binary-Curve K-163", ctx, out))
goto err;
if (!test_ecdh_curve(NID_sect163r2, "NIST Binary-Curve B-163", ctx, out))
goto err;
if (!test_ecdh_curve(NID_sect233k1, "NIST Binary-Curve K-233", ctx, out))
goto err;
if (!test_ecdh_curve(NID_sect233r1, "NIST Binary-Curve B-233", ctx, out))
goto err;
if (!test_ecdh_curve(NID_sect283k1, "NIST Binary-Curve K-283", ctx, out))
goto err;
if (!test_ecdh_curve(NID_sect283r1, "NIST Binary-Curve B-283", ctx, out))
goto err;
if (!test_ecdh_curve(NID_sect409k1, "NIST Binary-Curve K-409", ctx, out))
goto err;
if (!test_ecdh_curve(NID_sect409r1, "NIST Binary-Curve B-409", ctx, out))
goto err;
if (!test_ecdh_curve(NID_sect571k1, "NIST Binary-Curve K-571", ctx, out))
goto err;
if (!test_ecdh_curve(NID_sect571r1, "NIST Binary-Curve B-571", ctx, out))
goto err;
# endif
if (!test_ecdh_kat(out, "Brainpool Prime-Curve brainpoolP256r1", 256))
goto err;
if (!test_ecdh_kat(out, "Brainpool Prime-Curve brainpoolP384r1", 384))
goto err;
if (!test_ecdh_kat(out, "Brainpool Prime-Curve brainpoolP512r1", 512))
goto err;
ret = 0;
err:
ERR_print_errors_fp(stderr);
if (ctx)
BN_CTX_free(ctx);
BIO_free(out);
CRYPTO_cleanup_all_ex_data();
ERR_remove_thread_state(NULL);
CRYPTO_mem_leaks_fp(stderr);
EXIT(ret);
return (ret);
}
# if 0
static void MS_CALLBACK cb(int p, int n, void *arg)
{
char c = '*';
if (p == 0)
c = '.';
if (p == 1)
c = '+';
if (p == 2)
c = '*';
if (p == 3)
c = '\n';
BIO_write((BIO *)arg, &c, 1);
(void)BIO_flush((BIO *)arg);
# ifdef LINT
p = n;
# endif
}
# endif
#endif
diff --git a/crypto/engine/eng_cryptodev.c b/crypto/engine/eng_cryptodev.c
index af59471c4771..d8cac4bdfd31 100644
--- a/crypto/engine/eng_cryptodev.c
+++ b/crypto/engine/eng_cryptodev.c
@@ -1,1549 +1,1549 @@
/*
* Copyright (c) 2002 Bob Beck <beck@openbsd.org>
* Copyright (c) 2002 Theo de Raadt
* Copyright (c) 2002 Markus Friedl
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include <string.h>
#include <openssl/objects.h>
#include <openssl/engine.h>
#include <openssl/evp.h>
#include <openssl/bn.h>
#if (defined(__unix__) || defined(unix)) && !defined(USG) && \
(defined(OpenBSD) || defined(__FreeBSD__))
# include <sys/param.h>
# if (OpenBSD >= 200112) || ((__FreeBSD_version >= 470101 && __FreeBSD_version < 500000) || __FreeBSD_version >= 500041)
# define HAVE_CRYPTODEV
# endif
# if (OpenBSD >= 200110)
# define HAVE_SYSLOG_R
# endif
#endif
#ifndef HAVE_CRYPTODEV
void ENGINE_load_cryptodev(void)
{
/* This is a NOP on platforms without /dev/crypto */
return;
}
#else
# include <sys/types.h>
# include <crypto/cryptodev.h>
# include <openssl/dh.h>
# include <openssl/dsa.h>
# include <openssl/err.h>
# include <openssl/rsa.h>
# include <sys/ioctl.h>
# include <errno.h>
# include <stdio.h>
# include <unistd.h>
# include <fcntl.h>
# include <stdarg.h>
# include <syslog.h>
# include <errno.h>
# include <string.h>
struct dev_crypto_state {
struct session_op d_sess;
int d_fd;
# ifdef USE_CRYPTODEV_DIGESTS
char dummy_mac_key[HASH_MAX_LEN];
unsigned char digest_res[HASH_MAX_LEN];
char *mac_data;
int mac_len;
# endif
};
static u_int32_t cryptodev_asymfeat = 0;
static int get_asym_dev_crypto(void);
static int open_dev_crypto(void);
static int get_dev_crypto(void);
static int get_cryptodev_ciphers(const int **cnids);
# ifdef USE_CRYPTODEV_DIGESTS
static int get_cryptodev_digests(const int **cnids);
# endif
static int cryptodev_usable_ciphers(const int **nids);
static int cryptodev_usable_digests(const int **nids);
static int cryptodev_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
const unsigned char *in, size_t inl);
static int cryptodev_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key,
const unsigned char *iv, int enc);
static int cryptodev_cleanup(EVP_CIPHER_CTX *ctx);
static int cryptodev_engine_ciphers(ENGINE *e, const EVP_CIPHER **cipher,
const int **nids, int nid);
static int cryptodev_engine_digests(ENGINE *e, const EVP_MD **digest,
const int **nids, int nid);
static int bn2crparam(const BIGNUM *a, struct crparam *crp);
static int crparam2bn(struct crparam *crp, BIGNUM *a);
static void zapparams(struct crypt_kop *kop);
static int cryptodev_asym(struct crypt_kop *kop, int rlen, BIGNUM *r,
int slen, BIGNUM *s);
static int cryptodev_bn_mod_exp(BIGNUM *r, const BIGNUM *a,
const BIGNUM *p, const BIGNUM *m, BN_CTX *ctx,
BN_MONT_CTX *m_ctx);
static int cryptodev_rsa_nocrt_mod_exp(BIGNUM *r0, const BIGNUM *I, RSA *rsa,
BN_CTX *ctx);
static int cryptodev_rsa_mod_exp(BIGNUM *r0, const BIGNUM *I, RSA *rsa,
BN_CTX *ctx);
static int cryptodev_dsa_bn_mod_exp(DSA *dsa, BIGNUM *r, BIGNUM *a,
const BIGNUM *p, const BIGNUM *m,
BN_CTX *ctx, BN_MONT_CTX *m_ctx);
static int cryptodev_dsa_dsa_mod_exp(DSA *dsa, BIGNUM *t1, BIGNUM *g,
BIGNUM *u1, BIGNUM *pub_key, BIGNUM *u2,
BIGNUM *p, BN_CTX *ctx,
BN_MONT_CTX *mont);
static DSA_SIG *cryptodev_dsa_do_sign(const unsigned char *dgst, int dlen,
DSA *dsa);
static int cryptodev_dsa_verify(const unsigned char *dgst, int dgst_len,
DSA_SIG *sig, DSA *dsa);
static int cryptodev_mod_exp_dh(const DH *dh, BIGNUM *r, const BIGNUM *a,
const BIGNUM *p, const BIGNUM *m, BN_CTX *ctx,
BN_MONT_CTX *m_ctx);
static int cryptodev_dh_compute_key(unsigned char *key, const BIGNUM *pub_key,
DH *dh);
static int cryptodev_ctrl(ENGINE *e, int cmd, long i, void *p,
void (*f) (void));
void ENGINE_load_cryptodev(void);
static const ENGINE_CMD_DEFN cryptodev_defns[] = {
{0, NULL, NULL, 0}
};
static struct {
int id;
int nid;
int ivmax;
int keylen;
} ciphers[] = {
{
CRYPTO_ARC4, NID_rc4, 0, 16,
},
{
CRYPTO_DES_CBC, NID_des_cbc, 8, 8,
},
{
CRYPTO_3DES_CBC, NID_des_ede3_cbc, 8, 24,
},
{
CRYPTO_AES_CBC, NID_aes_128_cbc, 16, 16,
},
{
CRYPTO_AES_CBC, NID_aes_192_cbc, 16, 24,
},
{
CRYPTO_AES_CBC, NID_aes_256_cbc, 16, 32,
},
# ifdef CRYPTO_AES_CTR
{
CRYPTO_AES_CTR, NID_aes_128_ctr, 14, 16,
},
{
CRYPTO_AES_CTR, NID_aes_192_ctr, 14, 24,
},
{
CRYPTO_AES_CTR, NID_aes_256_ctr, 14, 32,
},
# endif
{
CRYPTO_BLF_CBC, NID_bf_cbc, 8, 16,
},
{
CRYPTO_CAST_CBC, NID_cast5_cbc, 8, 16,
},
{
CRYPTO_SKIPJACK_CBC, NID_undef, 0, 0,
},
{
0, NID_undef, 0, 0,
},
};
# ifdef USE_CRYPTODEV_DIGESTS
static struct {
int id;
int nid;
int keylen;
} digests[] = {
{
CRYPTO_MD5_HMAC, NID_hmacWithMD5, 16
},
{
CRYPTO_SHA1_HMAC, NID_hmacWithSHA1, 20
},
{
CRYPTO_RIPEMD160_HMAC, NID_ripemd160, 16
/* ? */
},
{
CRYPTO_MD5_KPDK, NID_undef, 0
},
{
CRYPTO_SHA1_KPDK, NID_undef, 0
},
{
CRYPTO_MD5, NID_md5, 16
},
{
CRYPTO_SHA1, NID_sha1, 20
},
{
0, NID_undef, 0
},
};
# endif
/*
* Return a fd if /dev/crypto seems usable, 0 otherwise.
*/
static int open_dev_crypto(void)
{
static int fd = -1;
if (fd == -1) {
if ((fd = open("/dev/crypto", O_RDWR, 0)) == -1)
return (-1);
/* close on exec */
if (fcntl(fd, F_SETFD, 1) == -1) {
close(fd);
fd = -1;
return (-1);
}
}
return (fd);
}
static int get_dev_crypto(void)
{
int fd, retfd;
if ((fd = open_dev_crypto()) == -1)
return (-1);
# ifndef CRIOGET_NOT_NEEDED
if (ioctl(fd, CRIOGET, &retfd) == -1)
return (-1);
/* close on exec */
if (fcntl(retfd, F_SETFD, 1) == -1) {
close(retfd);
return (-1);
}
# else
retfd = fd;
# endif
return (retfd);
}
static void put_dev_crypto(int fd)
{
# ifndef CRIOGET_NOT_NEEDED
close(fd);
# endif
}
/* Caching version for asym operations */
static int get_asym_dev_crypto(void)
{
static int fd = -1;
if (fd == -1)
fd = get_dev_crypto();
return fd;
}
/*
* Find out what ciphers /dev/crypto will let us have a session for.
* XXX note, that some of these openssl doesn't deal with yet!
* returning them here is harmless, as long as we return NULL
* when asked for a handler in the cryptodev_engine_ciphers routine
*/
static int get_cryptodev_ciphers(const int **cnids)
{
static int nids[CRYPTO_ALGORITHM_MAX];
struct session_op sess;
int fd, i, count = 0;
if ((fd = get_dev_crypto()) < 0) {
*cnids = NULL;
return (0);
}
memset(&sess, 0, sizeof(sess));
sess.key = (caddr_t) "123456789abcdefghijklmno";
for (i = 0; ciphers[i].id && count < CRYPTO_ALGORITHM_MAX; i++) {
if (ciphers[i].nid == NID_undef)
continue;
sess.cipher = ciphers[i].id;
sess.keylen = ciphers[i].keylen;
sess.mac = 0;
if (ioctl(fd, CIOCGSESSION, &sess) != -1 &&
ioctl(fd, CIOCFSESSION, &sess.ses) != -1)
nids[count++] = ciphers[i].nid;
}
put_dev_crypto(fd);
if (count > 0)
*cnids = nids;
else
*cnids = NULL;
return (count);
}
# ifdef USE_CRYPTODEV_DIGESTS
/*
* Find out what digests /dev/crypto will let us have a session for.
* XXX note, that some of these openssl doesn't deal with yet!
* returning them here is harmless, as long as we return NULL
* when asked for a handler in the cryptodev_engine_digests routine
*/
static int get_cryptodev_digests(const int **cnids)
{
static int nids[CRYPTO_ALGORITHM_MAX];
struct session_op sess;
int fd, i, count = 0;
if ((fd = get_dev_crypto()) < 0) {
*cnids = NULL;
return (0);
}
memset(&sess, 0, sizeof(sess));
sess.mackey = (caddr_t) "123456789abcdefghijklmno";
for (i = 0; digests[i].id && count < CRYPTO_ALGORITHM_MAX; i++) {
if (digests[i].nid == NID_undef)
continue;
sess.mac = digests[i].id;
sess.mackeylen = digests[i].keylen;
sess.cipher = 0;
if (ioctl(fd, CIOCGSESSION, &sess) != -1 &&
ioctl(fd, CIOCFSESSION, &sess.ses) != -1)
nids[count++] = digests[i].nid;
}
put_dev_crypto(fd);
if (count > 0)
*cnids = nids;
else
*cnids = NULL;
return (count);
}
# endif /* 0 */
/*
* Find the useable ciphers|digests from dev/crypto - this is the first
* thing called by the engine init crud which determines what it
* can use for ciphers from this engine. We want to return
* only what we can do, anythine else is handled by software.
*
* If we can't initialize the device to do anything useful for
* any reason, we want to return a NULL array, and 0 length,
* which forces everything to be done is software. By putting
* the initalization of the device in here, we ensure we can
* use this engine as the default, and if for whatever reason
* /dev/crypto won't do what we want it will just be done in
* software
*
* This can (should) be greatly expanded to perhaps take into
* account speed of the device, and what we want to do.
* (although the disabling of particular alg's could be controlled
* by the device driver with sysctl's.) - this is where we
* want most of the decisions made about what we actually want
* to use from /dev/crypto.
*/
static int cryptodev_usable_ciphers(const int **nids)
{
return (get_cryptodev_ciphers(nids));
}
static int cryptodev_usable_digests(const int **nids)
{
# ifdef USE_CRYPTODEV_DIGESTS
return (get_cryptodev_digests(nids));
# else
/*
* XXXX just disable all digests for now, because it sucks.
* we need a better way to decide this - i.e. I may not
* want digests on slow cards like hifn on fast machines,
* but might want them on slow or loaded machines, etc.
* will also want them when using crypto cards that don't
* suck moose gonads - would be nice to be able to decide something
* as reasonable default without having hackery that's card dependent.
* of course, the default should probably be just do everything,
* with perhaps a sysctl to turn algoritms off (or have them off
* by default) on cards that generally suck like the hifn.
*/
*nids = NULL;
return (0);
# endif
}
static int
cryptodev_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
const unsigned char *in, size_t inl)
{
struct crypt_op cryp;
struct dev_crypto_state *state = ctx->cipher_data;
struct session_op *sess = &state->d_sess;
const void *iiv;
unsigned char save_iv[EVP_MAX_IV_LENGTH];
if (state->d_fd < 0)
return (0);
if (!inl)
return (1);
if ((inl % ctx->cipher->block_size) != 0)
return (0);
memset(&cryp, 0, sizeof(cryp));
cryp.ses = sess->ses;
cryp.flags = 0;
cryp.len = inl;
cryp.src = (caddr_t) in;
cryp.dst = (caddr_t) out;
cryp.mac = 0;
cryp.op = ctx->encrypt ? COP_ENCRYPT : COP_DECRYPT;
if (ctx->cipher->iv_len) {
cryp.iv = (caddr_t) ctx->iv;
if (!ctx->encrypt) {
iiv = in + inl - ctx->cipher->iv_len;
memcpy(save_iv, iiv, ctx->cipher->iv_len);
}
} else
cryp.iv = NULL;
if (ioctl(state->d_fd, CIOCCRYPT, &cryp) == -1) {
/*
* XXX need better errror handling this can fail for a number of
* different reasons.
*/
return (0);
}
if (ctx->cipher->iv_len) {
if (ctx->encrypt)
iiv = out + inl - ctx->cipher->iv_len;
else
iiv = save_iv;
memcpy(ctx->iv, iiv, ctx->cipher->iv_len);
}
return (1);
}
static int
cryptodev_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key,
const unsigned char *iv, int enc)
{
struct dev_crypto_state *state = ctx->cipher_data;
struct session_op *sess = &state->d_sess;
int cipher = -1, i;
for (i = 0; ciphers[i].id; i++)
if (ctx->cipher->nid == ciphers[i].nid &&
ctx->cipher->iv_len <= ciphers[i].ivmax &&
ctx->key_len == ciphers[i].keylen) {
cipher = ciphers[i].id;
break;
}
if (!ciphers[i].id) {
state->d_fd = -1;
return (0);
}
memset(sess, 0, sizeof(struct session_op));
if ((state->d_fd = get_dev_crypto()) < 0)
return (0);
sess->key = (caddr_t) key;
sess->keylen = ctx->key_len;
sess->cipher = cipher;
if (ioctl(state->d_fd, CIOCGSESSION, sess) == -1) {
put_dev_crypto(state->d_fd);
state->d_fd = -1;
return (0);
}
return (1);
}
/*
* free anything we allocated earlier when initting a
* session, and close the session.
*/
static int cryptodev_cleanup(EVP_CIPHER_CTX *ctx)
{
int ret = 0;
struct dev_crypto_state *state = ctx->cipher_data;
struct session_op *sess = &state->d_sess;
if (state->d_fd < 0)
return (0);
/*
* XXX if this ioctl fails, someting's wrong. the invoker may have called
* us with a bogus ctx, or we could have a device that for whatever
* reason just doesn't want to play ball - it's not clear what's right
* here - should this be an error? should it just increase a counter,
* hmm. For right now, we return 0 - I don't believe that to be "right".
* we could call the gorpy openssl lib error handlers that print messages
* to users of the library. hmm..
*/
if (ioctl(state->d_fd, CIOCFSESSION, &sess->ses) == -1) {
ret = 0;
} else {
ret = 1;
}
put_dev_crypto(state->d_fd);
state->d_fd = -1;
return (ret);
}
/*
* libcrypto EVP stuff - this is how we get wired to EVP so the engine
* gets called when libcrypto requests a cipher NID.
*/
/* RC4 */
const EVP_CIPHER cryptodev_rc4 = {
NID_rc4,
1, 16, 0,
EVP_CIPH_VARIABLE_LENGTH,
cryptodev_init_key,
cryptodev_cipher,
cryptodev_cleanup,
sizeof(struct dev_crypto_state),
NULL,
NULL,
NULL
};
/* DES CBC EVP */
const EVP_CIPHER cryptodev_des_cbc = {
NID_des_cbc,
8, 8, 8,
EVP_CIPH_CBC_MODE,
cryptodev_init_key,
cryptodev_cipher,
cryptodev_cleanup,
sizeof(struct dev_crypto_state),
EVP_CIPHER_set_asn1_iv,
EVP_CIPHER_get_asn1_iv,
NULL
};
/* 3DES CBC EVP */
const EVP_CIPHER cryptodev_3des_cbc = {
NID_des_ede3_cbc,
8, 24, 8,
EVP_CIPH_CBC_MODE,
cryptodev_init_key,
cryptodev_cipher,
cryptodev_cleanup,
sizeof(struct dev_crypto_state),
EVP_CIPHER_set_asn1_iv,
EVP_CIPHER_get_asn1_iv,
NULL
};
const EVP_CIPHER cryptodev_bf_cbc = {
NID_bf_cbc,
8, 16, 8,
EVP_CIPH_CBC_MODE,
cryptodev_init_key,
cryptodev_cipher,
cryptodev_cleanup,
sizeof(struct dev_crypto_state),
EVP_CIPHER_set_asn1_iv,
EVP_CIPHER_get_asn1_iv,
NULL
};
const EVP_CIPHER cryptodev_cast_cbc = {
NID_cast5_cbc,
8, 16, 8,
EVP_CIPH_CBC_MODE,
cryptodev_init_key,
cryptodev_cipher,
cryptodev_cleanup,
sizeof(struct dev_crypto_state),
EVP_CIPHER_set_asn1_iv,
EVP_CIPHER_get_asn1_iv,
NULL
};
const EVP_CIPHER cryptodev_aes_cbc = {
NID_aes_128_cbc,
16, 16, 16,
EVP_CIPH_CBC_MODE,
cryptodev_init_key,
cryptodev_cipher,
cryptodev_cleanup,
sizeof(struct dev_crypto_state),
EVP_CIPHER_set_asn1_iv,
EVP_CIPHER_get_asn1_iv,
NULL
};
const EVP_CIPHER cryptodev_aes_192_cbc = {
NID_aes_192_cbc,
16, 24, 16,
EVP_CIPH_CBC_MODE,
cryptodev_init_key,
cryptodev_cipher,
cryptodev_cleanup,
sizeof(struct dev_crypto_state),
EVP_CIPHER_set_asn1_iv,
EVP_CIPHER_get_asn1_iv,
NULL
};
const EVP_CIPHER cryptodev_aes_256_cbc = {
NID_aes_256_cbc,
16, 32, 16,
EVP_CIPH_CBC_MODE,
cryptodev_init_key,
cryptodev_cipher,
cryptodev_cleanup,
sizeof(struct dev_crypto_state),
EVP_CIPHER_set_asn1_iv,
EVP_CIPHER_get_asn1_iv,
NULL
};
# ifdef CRYPTO_AES_CTR
const EVP_CIPHER cryptodev_aes_ctr = {
NID_aes_128_ctr,
16, 16, 14,
EVP_CIPH_CTR_MODE,
cryptodev_init_key,
cryptodev_cipher,
cryptodev_cleanup,
sizeof(struct dev_crypto_state),
EVP_CIPHER_set_asn1_iv,
EVP_CIPHER_get_asn1_iv,
NULL
};
const EVP_CIPHER cryptodev_aes_ctr_192 = {
NID_aes_192_ctr,
16, 24, 14,
EVP_CIPH_CTR_MODE,
cryptodev_init_key,
cryptodev_cipher,
cryptodev_cleanup,
sizeof(struct dev_crypto_state),
EVP_CIPHER_set_asn1_iv,
EVP_CIPHER_get_asn1_iv,
NULL
};
const EVP_CIPHER cryptodev_aes_ctr_256 = {
NID_aes_256_ctr,
16, 32, 14,
EVP_CIPH_CTR_MODE,
cryptodev_init_key,
cryptodev_cipher,
cryptodev_cleanup,
sizeof(struct dev_crypto_state),
EVP_CIPHER_set_asn1_iv,
EVP_CIPHER_get_asn1_iv,
NULL
};
# endif
/*
* Registered by the ENGINE when used to find out how to deal with
* a particular NID in the ENGINE. this says what we'll do at the
* top level - note, that list is restricted by what we answer with
*/
static int
cryptodev_engine_ciphers(ENGINE *e, const EVP_CIPHER **cipher,
const int **nids, int nid)
{
if (!cipher)
return (cryptodev_usable_ciphers(nids));
switch (nid) {
case NID_rc4:
*cipher = &cryptodev_rc4;
break;
case NID_des_ede3_cbc:
*cipher = &cryptodev_3des_cbc;
break;
case NID_des_cbc:
*cipher = &cryptodev_des_cbc;
break;
case NID_bf_cbc:
*cipher = &cryptodev_bf_cbc;
break;
case NID_cast5_cbc:
*cipher = &cryptodev_cast_cbc;
break;
case NID_aes_128_cbc:
*cipher = &cryptodev_aes_cbc;
break;
case NID_aes_192_cbc:
*cipher = &cryptodev_aes_192_cbc;
break;
case NID_aes_256_cbc:
*cipher = &cryptodev_aes_256_cbc;
break;
# ifdef CRYPTO_AES_CTR
case NID_aes_128_ctr:
*cipher = &cryptodev_aes_ctr;
break;
case NID_aes_192_ctr:
*cipher = &cryptodev_aes_ctr_192;
break;
case NID_aes_256_ctr:
*cipher = &cryptodev_aes_ctr_256;
break;
# endif
default:
*cipher = NULL;
break;
}
return (*cipher != NULL);
}
# ifdef USE_CRYPTODEV_DIGESTS
/* convert digest type to cryptodev */
static int digest_nid_to_cryptodev(int nid)
{
int i;
for (i = 0; digests[i].id; i++)
if (digests[i].nid == nid)
return (digests[i].id);
return (0);
}
static int digest_key_length(int nid)
{
int i;
for (i = 0; digests[i].id; i++)
if (digests[i].nid == nid)
return digests[i].keylen;
return (0);
}
static int cryptodev_digest_init(EVP_MD_CTX *ctx)
{
struct dev_crypto_state *state = ctx->md_data;
struct session_op *sess = &state->d_sess;
int digest;
if ((digest = digest_nid_to_cryptodev(ctx->digest->type)) == NID_undef) {
printf("cryptodev_digest_init: Can't get digest \n");
return (0);
}
memset(state, 0, sizeof(struct dev_crypto_state));
if ((state->d_fd = get_dev_crypto()) < 0) {
printf("cryptodev_digest_init: Can't get Dev \n");
return (0);
}
sess->mackey = state->dummy_mac_key;
sess->mackeylen = digest_key_length(ctx->digest->type);
sess->mac = digest;
if (ioctl(state->d_fd, CIOCGSESSION, sess) < 0) {
put_dev_crypto(state->d_fd);
state->d_fd = -1;
printf("cryptodev_digest_init: Open session failed\n");
return (0);
}
return (1);
}
static int cryptodev_digest_update(EVP_MD_CTX *ctx, const void *data,
size_t count)
{
struct crypt_op cryp;
struct dev_crypto_state *state = ctx->md_data;
struct session_op *sess = &state->d_sess;
if (!data || state->d_fd < 0) {
printf("cryptodev_digest_update: illegal inputs \n");
return (0);
}
if (!count) {
return (0);
}
if (!(ctx->flags & EVP_MD_CTX_FLAG_ONESHOT)) {
/* if application doesn't support one buffer */
char *mac_data =
OPENSSL_realloc(state->mac_data, state->mac_len + count);
if (mac_data == NULL) {
printf("cryptodev_digest_update: realloc failed\n");
return (0);
}
state->mac_data = mac_data;
memcpy(state->mac_data + state->mac_len, data, count);
state->mac_len += count;
return (1);
}
memset(&cryp, 0, sizeof(cryp));
cryp.ses = sess->ses;
cryp.flags = 0;
cryp.len = count;
cryp.src = (caddr_t) data;
cryp.dst = NULL;
cryp.mac = (caddr_t) state->digest_res;
if (ioctl(state->d_fd, CIOCCRYPT, &cryp) < 0) {
printf("cryptodev_digest_update: digest failed\n");
return (0);
}
return (1);
}
static int cryptodev_digest_final(EVP_MD_CTX *ctx, unsigned char *md)
{
struct crypt_op cryp;
struct dev_crypto_state *state = ctx->md_data;
struct session_op *sess = &state->d_sess;
int ret = 1;
if (!md || state->d_fd < 0) {
printf("cryptodev_digest_final: illegal input\n");
return (0);
}
if (!(ctx->flags & EVP_MD_CTX_FLAG_ONESHOT)) {
/* if application doesn't support one buffer */
memset(&cryp, 0, sizeof(cryp));
cryp.ses = sess->ses;
cryp.flags = 0;
cryp.len = state->mac_len;
cryp.src = state->mac_data;
cryp.dst = NULL;
cryp.mac = (caddr_t) md;
if (ioctl(state->d_fd, CIOCCRYPT, &cryp) < 0) {
printf("cryptodev_digest_final: digest failed\n");
return (0);
}
return 1;
}
memcpy(md, state->digest_res, ctx->digest->md_size);
return (ret);
}
static int cryptodev_digest_cleanup(EVP_MD_CTX *ctx)
{
int ret = 1;
struct dev_crypto_state *state = ctx->md_data;
struct session_op *sess = &state->d_sess;
if (state == NULL)
return 0;
if (state->d_fd < 0) {
printf("cryptodev_digest_cleanup: illegal input\n");
return (0);
}
if (state->mac_data) {
OPENSSL_free(state->mac_data);
state->mac_data = NULL;
state->mac_len = 0;
}
if (ioctl(state->d_fd, CIOCFSESSION, &sess->ses) < 0) {
printf("cryptodev_digest_cleanup: failed to close session\n");
ret = 0;
} else {
ret = 1;
}
put_dev_crypto(state->d_fd);
state->d_fd = -1;
return (ret);
}
static int cryptodev_digest_copy(EVP_MD_CTX *to, const EVP_MD_CTX *from)
{
struct dev_crypto_state *fstate = from->md_data;
struct dev_crypto_state *dstate = to->md_data;
struct session_op *sess;
int digest;
if (dstate == NULL || fstate == NULL)
return 1;
memcpy(dstate, fstate, sizeof(struct dev_crypto_state));
sess = &dstate->d_sess;
digest = digest_nid_to_cryptodev(to->digest->type);
sess->mackey = dstate->dummy_mac_key;
sess->mackeylen = digest_key_length(to->digest->type);
sess->mac = digest;
dstate->d_fd = get_dev_crypto();
if (ioctl(dstate->d_fd, CIOCGSESSION, sess) < 0) {
put_dev_crypto(dstate->d_fd);
dstate->d_fd = -1;
printf("cryptodev_digest_init: Open session failed\n");
return (0);
}
dstate->mac_len = fstate->mac_len;
if (fstate->mac_len != 0) {
if (fstate->mac_data != NULL) {
dstate->mac_data = OPENSSL_malloc(fstate->mac_len);
if (dstate->mac_data == NULL) {
printf("cryptodev_digest_init: malloc failed\n");
return 0;
}
memcpy(dstate->mac_data, fstate->mac_data, fstate->mac_len);
}
}
return 1;
}
const EVP_MD cryptodev_sha1 = {
NID_sha1,
NID_undef,
SHA_DIGEST_LENGTH,
EVP_MD_FLAG_ONESHOT,
cryptodev_digest_init,
cryptodev_digest_update,
cryptodev_digest_final,
cryptodev_digest_copy,
cryptodev_digest_cleanup,
EVP_PKEY_NULL_method,
SHA_CBLOCK,
sizeof(struct dev_crypto_state),
};
const EVP_MD cryptodev_md5 = {
NID_md5,
NID_undef,
16 /* MD5_DIGEST_LENGTH */ ,
EVP_MD_FLAG_ONESHOT,
cryptodev_digest_init,
cryptodev_digest_update,
cryptodev_digest_final,
cryptodev_digest_copy,
cryptodev_digest_cleanup,
EVP_PKEY_NULL_method,
64 /* MD5_CBLOCK */ ,
sizeof(struct dev_crypto_state),
};
# endif /* USE_CRYPTODEV_DIGESTS */
static int
cryptodev_engine_digests(ENGINE *e, const EVP_MD **digest,
const int **nids, int nid)
{
if (!digest)
return (cryptodev_usable_digests(nids));
switch (nid) {
# ifdef USE_CRYPTODEV_DIGESTS
case NID_md5:
*digest = &cryptodev_md5;
break;
case NID_sha1:
*digest = &cryptodev_sha1;
break;
default:
# endif /* USE_CRYPTODEV_DIGESTS */
*digest = NULL;
break;
}
return (*digest != NULL);
}
/*
* Convert a BIGNUM to the representation that /dev/crypto needs.
* Upon completion of use, the caller is responsible for freeing
* crp->crp_p.
*/
static int bn2crparam(const BIGNUM *a, struct crparam *crp)
{
int i, j, k;
ssize_t bytes, bits;
u_char *b;
crp->crp_p = NULL;
crp->crp_nbits = 0;
bits = BN_num_bits(a);
bytes = (bits + 7) / 8;
b = malloc(bytes);
if (b == NULL)
return (1);
memset(b, 0, bytes);
crp->crp_p = (caddr_t) b;
crp->crp_nbits = bits;
for (i = 0, j = 0; i < a->top; i++) {
for (k = 0; k < BN_BITS2 / 8; k++) {
if ((j + k) >= bytes)
return (0);
b[j + k] = a->d[i] >> (k * 8);
}
j += BN_BITS2 / 8;
}
return (0);
}
/* Convert a /dev/crypto parameter to a BIGNUM */
static int crparam2bn(struct crparam *crp, BIGNUM *a)
{
u_int8_t *pd;
int i, bytes;
bytes = (crp->crp_nbits + 7) / 8;
if (bytes == 0)
return (-1);
if ((pd = (u_int8_t *) malloc(bytes)) == NULL)
return (-1);
for (i = 0; i < bytes; i++)
- pd[i] = crp->crp_p[bytes - i - 1];
+ pd[i] = ((char *)crp->crp_p)[bytes - i - 1];
BN_bin2bn(pd, bytes, a);
free(pd);
return (0);
}
static void zapparams(struct crypt_kop *kop)
{
int i;
for (i = 0; i < kop->crk_iparams + kop->crk_oparams; i++) {
OPENSSL_free(kop->crk_param[i].crp_p);
kop->crk_param[i].crp_p = NULL;
kop->crk_param[i].crp_nbits = 0;
}
}
static int
cryptodev_asym(struct crypt_kop *kop, int rlen, BIGNUM *r, int slen,
BIGNUM *s)
{
int fd, ret = -1;
if ((fd = get_asym_dev_crypto()) < 0)
return ret;
if (r) {
kop->crk_param[kop->crk_iparams].crp_p = OPENSSL_malloc(rlen);
if (kop->crk_param[kop->crk_iparams].crp_p == NULL)
return ret;
memset(kop->crk_param[kop->crk_iparams].crp_p, 0, (size_t)rlen);
kop->crk_param[kop->crk_iparams].crp_nbits = rlen * 8;
kop->crk_oparams++;
}
if (s) {
kop->crk_param[kop->crk_iparams + 1].crp_p = OPENSSL_malloc(slen);
/* No need to free the kop->crk_iparams parameter if it was allocated,
* callers of this routine have to free allocated parameters through
* zapparams both in case of success and failure
*/
if (kop->crk_param[kop->crk_iparams+1].crp_p == NULL)
return ret;
memset(kop->crk_param[kop->crk_iparams + 1].crp_p, 0, (size_t)slen);
kop->crk_param[kop->crk_iparams + 1].crp_nbits = slen * 8;
kop->crk_oparams++;
}
if (ioctl(fd, CIOCKEY, kop) == 0) {
if (r)
crparam2bn(&kop->crk_param[kop->crk_iparams], r);
if (s)
crparam2bn(&kop->crk_param[kop->crk_iparams + 1], s);
ret = 0;
}
return ret;
}
static int
cryptodev_bn_mod_exp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p,
const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *in_mont)
{
struct crypt_kop kop;
int ret = 1;
/*
* Currently, we know we can do mod exp iff we can do any asymmetric
* operations at all.
*/
if (cryptodev_asymfeat == 0) {
ret = BN_mod_exp(r, a, p, m, ctx);
return (ret);
}
- memset(&kop, 0, sizeof kop);
+ memset(&kop, 0, sizeof(kop));
kop.crk_op = CRK_MOD_EXP;
/* inputs: a^p % m */
if (bn2crparam(a, &kop.crk_param[0]))
goto err;
if (bn2crparam(p, &kop.crk_param[1]))
goto err;
if (bn2crparam(m, &kop.crk_param[2]))
goto err;
kop.crk_iparams = 3;
if (cryptodev_asym(&kop, BN_num_bytes(m), r, 0, NULL)) {
const RSA_METHOD *meth = RSA_PKCS1_SSLeay();
printf("OCF asym process failed, Running in software\n");
ret = meth->bn_mod_exp(r, a, p, m, ctx, in_mont);
} else if (ECANCELED == kop.crk_status) {
const RSA_METHOD *meth = RSA_PKCS1_SSLeay();
printf("OCF hardware operation cancelled. Running in Software\n");
ret = meth->bn_mod_exp(r, a, p, m, ctx, in_mont);
}
/* else cryptodev operation worked ok ==> ret = 1 */
err:
zapparams(&kop);
return (ret);
}
static int
cryptodev_rsa_nocrt_mod_exp(BIGNUM *r0, const BIGNUM *I, RSA *rsa,
BN_CTX *ctx)
{
int r;
ctx = BN_CTX_new();
r = cryptodev_bn_mod_exp(r0, I, rsa->d, rsa->n, ctx, NULL);
BN_CTX_free(ctx);
return (r);
}
static int
cryptodev_rsa_mod_exp(BIGNUM *r0, const BIGNUM *I, RSA *rsa, BN_CTX *ctx)
{
struct crypt_kop kop;
int ret = 1;
if (!rsa->p || !rsa->q || !rsa->dmp1 || !rsa->dmq1 || !rsa->iqmp) {
/* XXX 0 means failure?? */
return (0);
}
- memset(&kop, 0, sizeof kop);
+ memset(&kop, 0, sizeof(kop));
kop.crk_op = CRK_MOD_EXP_CRT;
/* inputs: rsa->p rsa->q I rsa->dmp1 rsa->dmq1 rsa->iqmp */
if (bn2crparam(rsa->p, &kop.crk_param[0]))
goto err;
if (bn2crparam(rsa->q, &kop.crk_param[1]))
goto err;
if (bn2crparam(I, &kop.crk_param[2]))
goto err;
if (bn2crparam(rsa->dmp1, &kop.crk_param[3]))
goto err;
if (bn2crparam(rsa->dmq1, &kop.crk_param[4]))
goto err;
if (bn2crparam(rsa->iqmp, &kop.crk_param[5]))
goto err;
kop.crk_iparams = 6;
if (cryptodev_asym(&kop, BN_num_bytes(rsa->n), r0, 0, NULL)) {
const RSA_METHOD *meth = RSA_PKCS1_SSLeay();
printf("OCF asym process failed, running in Software\n");
ret = (*meth->rsa_mod_exp) (r0, I, rsa, ctx);
} else if (ECANCELED == kop.crk_status) {
const RSA_METHOD *meth = RSA_PKCS1_SSLeay();
printf("OCF hardware operation cancelled. Running in Software\n");
ret = (*meth->rsa_mod_exp) (r0, I, rsa, ctx);
}
/* else cryptodev operation worked ok ==> ret = 1 */
err:
zapparams(&kop);
return (ret);
}
static RSA_METHOD cryptodev_rsa = {
"cryptodev RSA method",
NULL, /* rsa_pub_enc */
NULL, /* rsa_pub_dec */
NULL, /* rsa_priv_enc */
NULL, /* rsa_priv_dec */
NULL,
NULL,
NULL, /* init */
NULL, /* finish */
0, /* flags */
NULL, /* app_data */
NULL, /* rsa_sign */
NULL /* rsa_verify */
};
static int
cryptodev_dsa_bn_mod_exp(DSA *dsa, BIGNUM *r, BIGNUM *a, const BIGNUM *p,
const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *m_ctx)
{
return (cryptodev_bn_mod_exp(r, a, p, m, ctx, m_ctx));
}
static int
cryptodev_dsa_dsa_mod_exp(DSA *dsa, BIGNUM *t1, BIGNUM *g,
BIGNUM *u1, BIGNUM *pub_key, BIGNUM *u2, BIGNUM *p,
BN_CTX *ctx, BN_MONT_CTX *mont)
{
BIGNUM t2;
int ret = 0;
BN_init(&t2);
/* v = ( g^u1 * y^u2 mod p ) mod q */
/* let t1 = g ^ u1 mod p */
ret = 0;
if (!dsa->meth->bn_mod_exp(dsa, t1, dsa->g, u1, dsa->p, ctx, mont))
goto err;
/* let t2 = y ^ u2 mod p */
if (!dsa->meth->bn_mod_exp(dsa, &t2, dsa->pub_key, u2, dsa->p, ctx, mont))
goto err;
/* let u1 = t1 * t2 mod p */
if (!BN_mod_mul(u1, t1, &t2, dsa->p, ctx))
goto err;
BN_copy(t1, u1);
ret = 1;
err:
BN_free(&t2);
return (ret);
}
static DSA_SIG *cryptodev_dsa_do_sign(const unsigned char *dgst, int dlen,
DSA *dsa)
{
struct crypt_kop kop;
BIGNUM *r = NULL, *s = NULL;
DSA_SIG *dsaret = NULL;
if ((r = BN_new()) == NULL)
goto err;
if ((s = BN_new()) == NULL) {
BN_free(r);
goto err;
}
- memset(&kop, 0, sizeof kop);
+ memset(&kop, 0, sizeof(kop));
kop.crk_op = CRK_DSA_SIGN;
/* inputs: dgst dsa->p dsa->q dsa->g dsa->priv_key */
kop.crk_param[0].crp_p = (caddr_t) dgst;
kop.crk_param[0].crp_nbits = dlen * 8;
if (bn2crparam(dsa->p, &kop.crk_param[1]))
goto err;
if (bn2crparam(dsa->q, &kop.crk_param[2]))
goto err;
if (bn2crparam(dsa->g, &kop.crk_param[3]))
goto err;
if (bn2crparam(dsa->priv_key, &kop.crk_param[4]))
goto err;
kop.crk_iparams = 5;
if (cryptodev_asym(&kop, BN_num_bytes(dsa->q), r,
BN_num_bytes(dsa->q), s) == 0) {
dsaret = DSA_SIG_new();
if (dsaret == NULL)
goto err;
dsaret->r = r;
dsaret->s = s;
r = s = NULL;
} else {
const DSA_METHOD *meth = DSA_OpenSSL();
dsaret = (meth->dsa_do_sign) (dgst, dlen, dsa);
}
err:
BN_free(r);
BN_free(s);
kop.crk_param[0].crp_p = NULL;
zapparams(&kop);
return (dsaret);
}
static int
cryptodev_dsa_verify(const unsigned char *dgst, int dlen,
DSA_SIG *sig, DSA *dsa)
{
struct crypt_kop kop;
int dsaret = 1;
- memset(&kop, 0, sizeof kop);
+ memset(&kop, 0, sizeof(kop));
kop.crk_op = CRK_DSA_VERIFY;
/* inputs: dgst dsa->p dsa->q dsa->g dsa->pub_key sig->r sig->s */
kop.crk_param[0].crp_p = (caddr_t) dgst;
kop.crk_param[0].crp_nbits = dlen * 8;
if (bn2crparam(dsa->p, &kop.crk_param[1]))
goto err;
if (bn2crparam(dsa->q, &kop.crk_param[2]))
goto err;
if (bn2crparam(dsa->g, &kop.crk_param[3]))
goto err;
if (bn2crparam(dsa->pub_key, &kop.crk_param[4]))
goto err;
if (bn2crparam(sig->r, &kop.crk_param[5]))
goto err;
if (bn2crparam(sig->s, &kop.crk_param[6]))
goto err;
kop.crk_iparams = 7;
if (cryptodev_asym(&kop, 0, NULL, 0, NULL) == 0) {
/*
* OCF success value is 0, if not zero, change dsaret to fail
*/
if (0 != kop.crk_status)
dsaret = 0;
} else {
const DSA_METHOD *meth = DSA_OpenSSL();
dsaret = (meth->dsa_do_verify) (dgst, dlen, sig, dsa);
}
err:
kop.crk_param[0].crp_p = NULL;
zapparams(&kop);
return (dsaret);
}
static DSA_METHOD cryptodev_dsa = {
"cryptodev DSA method",
NULL,
NULL, /* dsa_sign_setup */
NULL,
NULL, /* dsa_mod_exp */
NULL,
NULL, /* init */
NULL, /* finish */
0, /* flags */
NULL /* app_data */
};
static int
cryptodev_mod_exp_dh(const DH *dh, BIGNUM *r, const BIGNUM *a,
const BIGNUM *p, const BIGNUM *m, BN_CTX *ctx,
BN_MONT_CTX *m_ctx)
{
return (cryptodev_bn_mod_exp(r, a, p, m, ctx, m_ctx));
}
static int
cryptodev_dh_compute_key(unsigned char *key, const BIGNUM *pub_key, DH *dh)
{
struct crypt_kop kop;
int dhret = 1;
int fd, keylen;
if ((fd = get_asym_dev_crypto()) < 0) {
const DH_METHOD *meth = DH_OpenSSL();
return ((meth->compute_key) (key, pub_key, dh));
}
keylen = BN_num_bits(dh->p);
- memset(&kop, 0, sizeof kop);
+ memset(&kop, 0, sizeof(kop));
kop.crk_op = CRK_DH_COMPUTE_KEY;
/* inputs: dh->priv_key pub_key dh->p key */
if (bn2crparam(dh->priv_key, &kop.crk_param[0]))
goto err;
if (bn2crparam(pub_key, &kop.crk_param[1]))
goto err;
if (bn2crparam(dh->p, &kop.crk_param[2]))
goto err;
kop.crk_iparams = 3;
kop.crk_param[3].crp_p = (caddr_t) key;
kop.crk_param[3].crp_nbits = keylen * 8;
kop.crk_oparams = 1;
if (ioctl(fd, CIOCKEY, &kop) == -1) {
const DH_METHOD *meth = DH_OpenSSL();
dhret = (meth->compute_key) (key, pub_key, dh);
}
err:
kop.crk_param[3].crp_p = NULL;
zapparams(&kop);
return (dhret);
}
static DH_METHOD cryptodev_dh = {
"cryptodev DH method",
NULL, /* cryptodev_dh_generate_key */
NULL,
NULL,
NULL,
NULL,
0, /* flags */
NULL /* app_data */
};
/*
* ctrl right now is just a wrapper that doesn't do much
* but I expect we'll want some options soon.
*/
static int
cryptodev_ctrl(ENGINE *e, int cmd, long i, void *p, void (*f) (void))
{
# ifdef HAVE_SYSLOG_R
struct syslog_data sd = SYSLOG_DATA_INIT;
# endif
switch (cmd) {
default:
# ifdef HAVE_SYSLOG_R
syslog_r(LOG_ERR, &sd, "cryptodev_ctrl: unknown command %d", cmd);
# else
syslog(LOG_ERR, "cryptodev_ctrl: unknown command %d", cmd);
# endif
break;
}
return (1);
}
void ENGINE_load_cryptodev(void)
{
ENGINE *engine = ENGINE_new();
int fd;
if (engine == NULL)
return;
if ((fd = get_dev_crypto()) < 0) {
ENGINE_free(engine);
return;
}
/*
* find out what asymmetric crypto algorithms we support
*/
if (ioctl(fd, CIOCASYMFEAT, &cryptodev_asymfeat) == -1) {
put_dev_crypto(fd);
ENGINE_free(engine);
return;
}
put_dev_crypto(fd);
if (!ENGINE_set_id(engine, "cryptodev") ||
!ENGINE_set_name(engine, "BSD cryptodev engine") ||
!ENGINE_set_ciphers(engine, cryptodev_engine_ciphers) ||
!ENGINE_set_digests(engine, cryptodev_engine_digests) ||
!ENGINE_set_ctrl_function(engine, cryptodev_ctrl) ||
!ENGINE_set_cmd_defns(engine, cryptodev_defns)) {
ENGINE_free(engine);
return;
}
if (ENGINE_set_RSA(engine, &cryptodev_rsa)) {
const RSA_METHOD *rsa_meth = RSA_PKCS1_SSLeay();
cryptodev_rsa.bn_mod_exp = rsa_meth->bn_mod_exp;
cryptodev_rsa.rsa_mod_exp = rsa_meth->rsa_mod_exp;
cryptodev_rsa.rsa_pub_enc = rsa_meth->rsa_pub_enc;
cryptodev_rsa.rsa_pub_dec = rsa_meth->rsa_pub_dec;
cryptodev_rsa.rsa_priv_enc = rsa_meth->rsa_priv_enc;
cryptodev_rsa.rsa_priv_dec = rsa_meth->rsa_priv_dec;
if (cryptodev_asymfeat & CRF_MOD_EXP) {
cryptodev_rsa.bn_mod_exp = cryptodev_bn_mod_exp;
if (cryptodev_asymfeat & CRF_MOD_EXP_CRT)
cryptodev_rsa.rsa_mod_exp = cryptodev_rsa_mod_exp;
else
cryptodev_rsa.rsa_mod_exp = cryptodev_rsa_nocrt_mod_exp;
}
}
if (ENGINE_set_DSA(engine, &cryptodev_dsa)) {
const DSA_METHOD *meth = DSA_OpenSSL();
memcpy(&cryptodev_dsa, meth, sizeof(DSA_METHOD));
if (cryptodev_asymfeat & CRF_DSA_SIGN)
cryptodev_dsa.dsa_do_sign = cryptodev_dsa_do_sign;
if (cryptodev_asymfeat & CRF_MOD_EXP) {
cryptodev_dsa.bn_mod_exp = cryptodev_dsa_bn_mod_exp;
cryptodev_dsa.dsa_mod_exp = cryptodev_dsa_dsa_mod_exp;
}
if (cryptodev_asymfeat & CRF_DSA_VERIFY)
cryptodev_dsa.dsa_do_verify = cryptodev_dsa_verify;
}
if (ENGINE_set_DH(engine, &cryptodev_dh)) {
const DH_METHOD *dh_meth = DH_OpenSSL();
cryptodev_dh.generate_key = dh_meth->generate_key;
cryptodev_dh.compute_key = dh_meth->compute_key;
cryptodev_dh.bn_mod_exp = dh_meth->bn_mod_exp;
if (cryptodev_asymfeat & CRF_MOD_EXP) {
cryptodev_dh.bn_mod_exp = cryptodev_mod_exp_dh;
if (cryptodev_asymfeat & CRF_DH_COMPUTE_KEY)
cryptodev_dh.compute_key = cryptodev_dh_compute_key;
}
}
ENGINE_add(engine);
ENGINE_free(engine);
ERR_clear_error();
}
#endif /* HAVE_CRYPTODEV */
diff --git a/crypto/engine/eng_table.c b/crypto/engine/eng_table.c
index 27d31f70c855..709393fae57d 100644
--- a/crypto/engine/eng_table.c
+++ b/crypto/engine/eng_table.c
@@ -1,358 +1,363 @@
/* ====================================================================
- * Copyright (c) 2001 The OpenSSL Project. All rights reserved.
+ * Copyright (c) 2001-2018 The OpenSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* licensing@OpenSSL.org.
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*
* This product includes cryptographic software written by Eric Young
* (eay@cryptsoft.com). This product includes software written by Tim
* Hudson (tjh@cryptsoft.com).
*
*/
#include "cryptlib.h"
#include <openssl/evp.h>
#include <openssl/lhash.h>
#include "eng_int.h"
/* The type of the items in the table */
typedef 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;
} ENGINE_PILE;
DECLARE_LHASH_OF(ENGINE_PILE);
/* The type exposed in eng_int.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 IMPLEMENT_LHASH_HASH_FN(engine_pile, ENGINE_PILE)
static IMPLEMENT_LHASH_COMP_FN(engine_pile, ENGINE_PILE)
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()) == NULL)
return 0;
*t = (ENGINE_TABLE *)lh;
return 1;
}
/*
* Privately exposed (via eng_int.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;
CRYPTO_w_lock(CRYPTO_LOCK_ENGINE);
if (!(*table))
added = 1;
if (!int_table_check(table, 1))
goto end;
if (added)
/* The cleanup callback needs to be added */
engine_cleanup_add_first(cleanup);
while (num_nids--) {
tmplate.nid = *nids;
fnd = lh_ENGINE_PILE_retrieve(&(*table)->piles, &tmplate);
if (!fnd) {
fnd = OPENSSL_malloc(sizeof(ENGINE_PILE));
if (!fnd)
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 duplciate 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)) {
ENGINEerr(ENGINE_F_ENGINE_TABLE_REGISTER,
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_w_unlock(CRYPTO_LOCK_ENGINE);
return ret;
}
static void int_unregister_cb_doall_arg(ENGINE_PILE *pile, ENGINE *e)
{
int n;
/* Iterate the 'c->sk' stack removing any occurance 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;
}
}
static IMPLEMENT_LHASH_DOALL_ARG_FN(int_unregister_cb, ENGINE_PILE, ENGINE)
void engine_table_unregister(ENGINE_TABLE **table, ENGINE *e)
{
CRYPTO_w_lock(CRYPTO_LOCK_ENGINE);
if (int_table_check(table, 0))
lh_ENGINE_PILE_doall_arg(&(*table)->piles,
LHASH_DOALL_ARG_FN(int_unregister_cb),
ENGINE, e);
CRYPTO_w_unlock(CRYPTO_LOCK_ENGINE);
}
static void int_cleanup_cb_doall(ENGINE_PILE *p)
{
sk_ENGINE_free(p->sk);
if (p->funct)
engine_unlocked_finish(p->funct, 0);
OPENSSL_free(p);
}
static IMPLEMENT_LHASH_DOALL_FN(int_cleanup_cb, ENGINE_PILE)
void engine_table_cleanup(ENGINE_TABLE **table)
{
CRYPTO_w_lock(CRYPTO_LOCK_ENGINE);
if (*table) {
lh_ENGINE_PILE_doall(&(*table)->piles,
LHASH_DOALL_FN(int_cleanup_cb));
lh_ENGINE_PILE_free(&(*table)->piles);
*table = NULL;
}
CRYPTO_w_unlock(CRYPTO_LOCK_ENGINE);
}
/* return a functional reference for a given 'nid' */
#ifndef ENGINE_TABLE_DEBUG
ENGINE *engine_table_select(ENGINE_TABLE **table, int nid)
#else
ENGINE *engine_table_select_tmp(ENGINE_TABLE **table, int nid, const char *f,
int l)
#endif
{
ENGINE *ret = NULL;
ENGINE_PILE tmplate, *fnd = NULL;
int initres, loop = 0;
if (!(*table)) {
#ifdef ENGINE_TABLE_DEBUG
fprintf(stderr, "engine_table_dbg: %s:%d, nid=%d, nothing "
"registered!\n", f, l, nid);
#endif
return NULL;
}
ERR_set_mark();
CRYPTO_w_lock(CRYPTO_LOCK_ENGINE);
/*
* Check again inside the lock otherwise we could race against cleanup
* operations. But don't worry about a fprintf(stderr).
*/
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)) {
#ifdef ENGINE_TABLE_DEBUG
fprintf(stderr, "engine_table_dbg: %s:%d, nid=%d, using "
"ENGINE '%s' cached\n", f, l, nid, fnd->funct->id);
#endif
ret = fnd->funct;
goto end;
}
if (fnd->uptodate) {
ret = fnd->funct;
goto end;
}
trynext:
ret = sk_ENGINE_value(fnd->sk, loop++);
if (!ret) {
#ifdef ENGINE_TABLE_DEBUG
fprintf(stderr, "engine_table_dbg: %s:%d, nid=%d, no "
"registered implementations would initialise\n", f, l, nid);
#endif
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;
#ifdef ENGINE_TABLE_DEBUG
fprintf(stderr, "engine_table_dbg: %s:%d, nid=%d, "
"setting default to '%s'\n", f, l, nid, ret->id);
#endif
}
#ifdef ENGINE_TABLE_DEBUG
fprintf(stderr, "engine_table_dbg: %s:%d, nid=%d, using "
"newly initialised '%s'\n", f, l, nid, ret->id);
#endif
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;
#ifdef ENGINE_TABLE_DEBUG
if (ret)
fprintf(stderr, "engine_table_dbg: %s:%d, nid=%d, caching "
"ENGINE '%s'\n", f, l, nid, ret->id);
else
fprintf(stderr, "engine_table_dbg: %s:%d, nid=%d, caching "
"'no matching ENGINE'\n", f, l, nid);
#endif
CRYPTO_w_unlock(CRYPTO_LOCK_ENGINE);
/*
* 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_cb_doall_arg(ENGINE_PILE *pile, ENGINE_PILE_DOALL *dall)
{
dall->cb(pile->nid, pile->sk, pile->funct, dall->arg);
}
static IMPLEMENT_LHASH_DOALL_ARG_FN(int_cb, 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_arg(&table->piles,
LHASH_DOALL_ARG_FN(int_cb),
ENGINE_PILE_DOALL, &dall);
}
diff --git a/crypto/err/err.c b/crypto/err/err.c
index cfe0e8083f39..e9ef2156e11f 100644
--- a/crypto/err/err.c
+++ b/crypto/err/err.c
@@ -1,1158 +1,1158 @@
/* crypto/err/err.c */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
/* ====================================================================
* Copyright (c) 1998-2006 The OpenSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* openssl-core@openssl.org.
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.openssl.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*
* This product includes cryptographic software written by Eric Young
* (eay@cryptsoft.com). This product includes software written by Tim
* Hudson (tjh@cryptsoft.com).
*
*/
#include <stdio.h>
#include <stdarg.h>
#include <string.h>
#include "cryptlib.h"
#include <openssl/lhash.h>
#include <openssl/crypto.h>
#include <openssl/buffer.h>
#include <openssl/bio.h>
#include <openssl/err.h>
DECLARE_LHASH_OF(ERR_STRING_DATA);
DECLARE_LHASH_OF(ERR_STATE);
static void err_load_strings(int lib, ERR_STRING_DATA *str);
static void ERR_STATE_free(ERR_STATE *s);
#ifndef OPENSSL_NO_ERR
static ERR_STRING_DATA ERR_str_libraries[] = {
{ERR_PACK(ERR_LIB_NONE, 0, 0), "unknown library"},
{ERR_PACK(ERR_LIB_SYS, 0, 0), "system library"},
{ERR_PACK(ERR_LIB_BN, 0, 0), "bignum routines"},
{ERR_PACK(ERR_LIB_RSA, 0, 0), "rsa routines"},
{ERR_PACK(ERR_LIB_DH, 0, 0), "Diffie-Hellman routines"},
{ERR_PACK(ERR_LIB_EVP, 0, 0), "digital envelope routines"},
{ERR_PACK(ERR_LIB_BUF, 0, 0), "memory buffer routines"},
{ERR_PACK(ERR_LIB_OBJ, 0, 0), "object identifier routines"},
{ERR_PACK(ERR_LIB_PEM, 0, 0), "PEM routines"},
{ERR_PACK(ERR_LIB_DSA, 0, 0), "dsa routines"},
{ERR_PACK(ERR_LIB_X509, 0, 0), "x509 certificate routines"},
{ERR_PACK(ERR_LIB_ASN1, 0, 0), "asn1 encoding routines"},
{ERR_PACK(ERR_LIB_CONF, 0, 0), "configuration file routines"},
{ERR_PACK(ERR_LIB_CRYPTO, 0, 0), "common libcrypto routines"},
{ERR_PACK(ERR_LIB_EC, 0, 0), "elliptic curve routines"},
{ERR_PACK(ERR_LIB_SSL, 0, 0), "SSL routines"},
{ERR_PACK(ERR_LIB_BIO, 0, 0), "BIO routines"},
{ERR_PACK(ERR_LIB_PKCS7, 0, 0), "PKCS7 routines"},
{ERR_PACK(ERR_LIB_X509V3, 0, 0), "X509 V3 routines"},
{ERR_PACK(ERR_LIB_PKCS12, 0, 0), "PKCS12 routines"},
{ERR_PACK(ERR_LIB_RAND, 0, 0), "random number generator"},
{ERR_PACK(ERR_LIB_DSO, 0, 0), "DSO support routines"},
{ERR_PACK(ERR_LIB_TS, 0, 0), "time stamp routines"},
{ERR_PACK(ERR_LIB_ENGINE, 0, 0), "engine routines"},
{ERR_PACK(ERR_LIB_OCSP, 0, 0), "OCSP routines"},
{ERR_PACK(ERR_LIB_FIPS, 0, 0), "FIPS routines"},
{ERR_PACK(ERR_LIB_CMS, 0, 0), "CMS routines"},
{ERR_PACK(ERR_LIB_HMAC, 0, 0), "HMAC routines"},
{0, NULL},
};
static ERR_STRING_DATA ERR_str_functs[] = {
{ERR_PACK(0, SYS_F_FOPEN, 0), "fopen"},
{ERR_PACK(0, SYS_F_CONNECT, 0), "connect"},
{ERR_PACK(0, SYS_F_GETSERVBYNAME, 0), "getservbyname"},
{ERR_PACK(0, SYS_F_SOCKET, 0), "socket"},
{ERR_PACK(0, SYS_F_IOCTLSOCKET, 0), "ioctlsocket"},
{ERR_PACK(0, SYS_F_BIND, 0), "bind"},
{ERR_PACK(0, SYS_F_LISTEN, 0), "listen"},
{ERR_PACK(0, SYS_F_ACCEPT, 0), "accept"},
# ifdef OPENSSL_SYS_WINDOWS
{ERR_PACK(0, SYS_F_WSASTARTUP, 0), "WSAstartup"},
# endif
{ERR_PACK(0, SYS_F_OPENDIR, 0), "opendir"},
{ERR_PACK(0, SYS_F_FREAD, 0), "fread"},
{ERR_PACK(0, SYS_F_FFLUSH, 0), "fflush"},
{0, NULL},
};
static ERR_STRING_DATA ERR_str_reasons[] = {
{ERR_R_SYS_LIB, "system lib"},
{ERR_R_BN_LIB, "BN lib"},
{ERR_R_RSA_LIB, "RSA lib"},
{ERR_R_DH_LIB, "DH lib"},
{ERR_R_EVP_LIB, "EVP lib"},
{ERR_R_BUF_LIB, "BUF lib"},
{ERR_R_OBJ_LIB, "OBJ lib"},
{ERR_R_PEM_LIB, "PEM lib"},
{ERR_R_DSA_LIB, "DSA lib"},
{ERR_R_X509_LIB, "X509 lib"},
{ERR_R_ASN1_LIB, "ASN1 lib"},
{ERR_R_CONF_LIB, "CONF lib"},
{ERR_R_CRYPTO_LIB, "CRYPTO lib"},
{ERR_R_EC_LIB, "EC lib"},
{ERR_R_SSL_LIB, "SSL lib"},
{ERR_R_BIO_LIB, "BIO lib"},
{ERR_R_PKCS7_LIB, "PKCS7 lib"},
{ERR_R_X509V3_LIB, "X509V3 lib"},
{ERR_R_PKCS12_LIB, "PKCS12 lib"},
{ERR_R_RAND_LIB, "RAND lib"},
{ERR_R_DSO_LIB, "DSO lib"},
{ERR_R_ENGINE_LIB, "ENGINE lib"},
{ERR_R_OCSP_LIB, "OCSP lib"},
{ERR_R_TS_LIB, "TS lib"},
{ERR_R_NESTED_ASN1_ERROR, "nested asn1 error"},
{ERR_R_BAD_ASN1_OBJECT_HEADER, "bad asn1 object header"},
{ERR_R_BAD_GET_ASN1_OBJECT_CALL, "bad get asn1 object call"},
{ERR_R_EXPECTING_AN_ASN1_SEQUENCE, "expecting an asn1 sequence"},
{ERR_R_ASN1_LENGTH_MISMATCH, "asn1 length mismatch"},
{ERR_R_MISSING_ASN1_EOS, "missing asn1 eos"},
{ERR_R_FATAL, "fatal"},
{ERR_R_MALLOC_FAILURE, "malloc failure"},
{ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED,
"called a function you should not call"},
{ERR_R_PASSED_NULL_PARAMETER, "passed a null parameter"},
{ERR_R_INTERNAL_ERROR, "internal error"},
{ERR_R_DISABLED, "called a function that was disabled at compile-time"},
{0, NULL},
};
#endif
/* Define the predeclared (but externally opaque) "ERR_FNS" type */
struct st_ERR_FNS {
/* Works on the "error_hash" string table */
LHASH_OF(ERR_STRING_DATA) *(*cb_err_get) (int create);
void (*cb_err_del) (void);
ERR_STRING_DATA *(*cb_err_get_item) (const ERR_STRING_DATA *);
ERR_STRING_DATA *(*cb_err_set_item) (ERR_STRING_DATA *);
ERR_STRING_DATA *(*cb_err_del_item) (ERR_STRING_DATA *);
/* Works on the "thread_hash" error-state table */
LHASH_OF(ERR_STATE) *(*cb_thread_get) (int create);
void (*cb_thread_release) (LHASH_OF(ERR_STATE) **hash);
ERR_STATE *(*cb_thread_get_item) (const ERR_STATE *);
ERR_STATE *(*cb_thread_set_item) (ERR_STATE *);
void (*cb_thread_del_item) (const ERR_STATE *);
/* Returns the next available error "library" numbers */
int (*cb_get_next_lib) (void);
};
/* Predeclarations of the "err_defaults" functions */
static LHASH_OF(ERR_STRING_DATA) *int_err_get(int create);
static void int_err_del(void);
static ERR_STRING_DATA *int_err_get_item(const ERR_STRING_DATA *);
static ERR_STRING_DATA *int_err_set_item(ERR_STRING_DATA *);
static ERR_STRING_DATA *int_err_del_item(ERR_STRING_DATA *);
static LHASH_OF(ERR_STATE) *int_thread_get(int create);
static void int_thread_release(LHASH_OF(ERR_STATE) **hash);
static ERR_STATE *int_thread_get_item(const ERR_STATE *);
static ERR_STATE *int_thread_set_item(ERR_STATE *);
static void int_thread_del_item(const ERR_STATE *);
static int int_err_get_next_lib(void);
/* The static ERR_FNS table using these defaults functions */
static const ERR_FNS err_defaults = {
int_err_get,
int_err_del,
int_err_get_item,
int_err_set_item,
int_err_del_item,
int_thread_get,
int_thread_release,
int_thread_get_item,
int_thread_set_item,
int_thread_del_item,
int_err_get_next_lib
};
/* The replacable table of ERR_FNS functions we use at run-time */
static const ERR_FNS *err_fns = NULL;
/* Eg. rather than using "err_get()", use "ERRFN(err_get)()". */
#define ERRFN(a) err_fns->cb_##a
/*
* The internal state used by "err_defaults" - as such, the setting, reading,
* creating, and deleting of this data should only be permitted via the
* "err_defaults" functions. This way, a linked module can completely defer
* all ERR state operation (together with requisite locking) to the
* implementations and state in the loading application.
*/
static LHASH_OF(ERR_STRING_DATA) *int_error_hash = NULL;
static LHASH_OF(ERR_STATE) *int_thread_hash = NULL;
static int int_thread_hash_references = 0;
static int int_err_library_number = ERR_LIB_USER;
/*
* Internal function that checks whether "err_fns" is set and if not, sets it
* to the defaults.
*/
static void err_fns_check(void)
{
if (err_fns)
return;
CRYPTO_w_lock(CRYPTO_LOCK_ERR);
if (!err_fns)
err_fns = &err_defaults;
CRYPTO_w_unlock(CRYPTO_LOCK_ERR);
}
/* API functions to get or set the underlying ERR functions. */
const ERR_FNS *ERR_get_implementation(void)
{
err_fns_check();
return err_fns;
}
int ERR_set_implementation(const ERR_FNS *fns)
{
int ret = 0;
CRYPTO_w_lock(CRYPTO_LOCK_ERR);
/*
* It's too late if 'err_fns' is non-NULL. BTW: not much point setting an
* error is there?!
*/
if (!err_fns) {
err_fns = fns;
ret = 1;
}
CRYPTO_w_unlock(CRYPTO_LOCK_ERR);
return ret;
}
/*
* These are the callbacks provided to "lh_new()" when creating the LHASH
* tables internal to the "err_defaults" implementation.
*/
static unsigned long get_error_values(int inc, int top, const char **file,
int *line, const char **data,
int *flags);
/* The internal functions used in the "err_defaults" implementation */
static unsigned long err_string_data_hash(const ERR_STRING_DATA *a)
{
unsigned long ret, l;
l = a->error;
ret = l ^ ERR_GET_LIB(l) ^ ERR_GET_FUNC(l);
return (ret ^ ret % 19 * 13);
}
static IMPLEMENT_LHASH_HASH_FN(err_string_data, ERR_STRING_DATA)
static int err_string_data_cmp(const ERR_STRING_DATA *a,
const ERR_STRING_DATA *b)
{
return (int)(a->error - b->error);
}
static IMPLEMENT_LHASH_COMP_FN(err_string_data, ERR_STRING_DATA)
static LHASH_OF(ERR_STRING_DATA) *int_err_get(int create)
{
LHASH_OF(ERR_STRING_DATA) *ret = NULL;
CRYPTO_w_lock(CRYPTO_LOCK_ERR);
if (!int_error_hash && create) {
CRYPTO_push_info("int_err_get (err.c)");
int_error_hash = lh_ERR_STRING_DATA_new();
CRYPTO_pop_info();
}
if (int_error_hash)
ret = int_error_hash;
CRYPTO_w_unlock(CRYPTO_LOCK_ERR);
return ret;
}
static void int_err_del(void)
{
CRYPTO_w_lock(CRYPTO_LOCK_ERR);
if (int_error_hash) {
lh_ERR_STRING_DATA_free(int_error_hash);
int_error_hash = NULL;
}
CRYPTO_w_unlock(CRYPTO_LOCK_ERR);
}
static ERR_STRING_DATA *int_err_get_item(const ERR_STRING_DATA *d)
{
ERR_STRING_DATA *p;
LHASH_OF(ERR_STRING_DATA) *hash;
err_fns_check();
hash = ERRFN(err_get) (0);
if (!hash)
return NULL;
CRYPTO_r_lock(CRYPTO_LOCK_ERR);
p = lh_ERR_STRING_DATA_retrieve(hash, d);
CRYPTO_r_unlock(CRYPTO_LOCK_ERR);
return p;
}
static ERR_STRING_DATA *int_err_set_item(ERR_STRING_DATA *d)
{
ERR_STRING_DATA *p;
LHASH_OF(ERR_STRING_DATA) *hash;
err_fns_check();
hash = ERRFN(err_get) (1);
if (!hash)
return NULL;
CRYPTO_w_lock(CRYPTO_LOCK_ERR);
p = lh_ERR_STRING_DATA_insert(hash, d);
CRYPTO_w_unlock(CRYPTO_LOCK_ERR);
return p;
}
static ERR_STRING_DATA *int_err_del_item(ERR_STRING_DATA *d)
{
ERR_STRING_DATA *p;
LHASH_OF(ERR_STRING_DATA) *hash;
err_fns_check();
hash = ERRFN(err_get) (0);
if (!hash)
return NULL;
CRYPTO_w_lock(CRYPTO_LOCK_ERR);
p = lh_ERR_STRING_DATA_delete(hash, d);
CRYPTO_w_unlock(CRYPTO_LOCK_ERR);
return p;
}
static unsigned long err_state_hash(const ERR_STATE *a)
{
return CRYPTO_THREADID_hash(&a->tid) * 13;
}
static IMPLEMENT_LHASH_HASH_FN(err_state, ERR_STATE)
static int err_state_cmp(const ERR_STATE *a, const ERR_STATE *b)
{
return CRYPTO_THREADID_cmp(&a->tid, &b->tid);
}
static IMPLEMENT_LHASH_COMP_FN(err_state, ERR_STATE)
static LHASH_OF(ERR_STATE) *int_thread_get(int create)
{
LHASH_OF(ERR_STATE) *ret = NULL;
CRYPTO_w_lock(CRYPTO_LOCK_ERR);
if (!int_thread_hash && create) {
CRYPTO_push_info("int_thread_get (err.c)");
int_thread_hash = lh_ERR_STATE_new();
CRYPTO_pop_info();
}
if (int_thread_hash) {
int_thread_hash_references++;
ret = int_thread_hash;
}
CRYPTO_w_unlock(CRYPTO_LOCK_ERR);
return ret;
}
static void int_thread_release(LHASH_OF(ERR_STATE) **hash)
{
int i;
if (hash == NULL || *hash == NULL)
return;
i = CRYPTO_add(&int_thread_hash_references, -1, CRYPTO_LOCK_ERR);
#ifdef REF_PRINT
fprintf(stderr, "%4d:%s\n", int_thread_hash_references, "ERR");
#endif
if (i > 0)
return;
#ifdef REF_CHECK
if (i < 0) {
fprintf(stderr, "int_thread_release, bad reference count\n");
abort(); /* ok */
}
#endif
*hash = NULL;
}
static ERR_STATE *int_thread_get_item(const ERR_STATE *d)
{
ERR_STATE *p;
LHASH_OF(ERR_STATE) *hash;
err_fns_check();
hash = ERRFN(thread_get) (0);
if (!hash)
return NULL;
CRYPTO_r_lock(CRYPTO_LOCK_ERR);
p = lh_ERR_STATE_retrieve(hash, d);
CRYPTO_r_unlock(CRYPTO_LOCK_ERR);
ERRFN(thread_release) (&hash);
return p;
}
static ERR_STATE *int_thread_set_item(ERR_STATE *d)
{
ERR_STATE *p;
LHASH_OF(ERR_STATE) *hash;
err_fns_check();
hash = ERRFN(thread_get) (1);
if (!hash)
return NULL;
CRYPTO_w_lock(CRYPTO_LOCK_ERR);
p = lh_ERR_STATE_insert(hash, d);
CRYPTO_w_unlock(CRYPTO_LOCK_ERR);
ERRFN(thread_release) (&hash);
return p;
}
static void int_thread_del_item(const ERR_STATE *d)
{
ERR_STATE *p;
LHASH_OF(ERR_STATE) *hash;
err_fns_check();
hash = ERRFN(thread_get) (0);
if (!hash)
return;
CRYPTO_w_lock(CRYPTO_LOCK_ERR);
p = lh_ERR_STATE_delete(hash, d);
/* make sure we don't leak memory */
if (int_thread_hash_references == 1
&& int_thread_hash && lh_ERR_STATE_num_items(int_thread_hash) == 0) {
lh_ERR_STATE_free(int_thread_hash);
int_thread_hash = NULL;
}
CRYPTO_w_unlock(CRYPTO_LOCK_ERR);
ERRFN(thread_release) (&hash);
if (p)
ERR_STATE_free(p);
}
static int int_err_get_next_lib(void)
{
int ret;
CRYPTO_w_lock(CRYPTO_LOCK_ERR);
ret = int_err_library_number++;
CRYPTO_w_unlock(CRYPTO_LOCK_ERR);
return ret;
}
#ifndef OPENSSL_NO_ERR
# define NUM_SYS_STR_REASONS 127
# define LEN_SYS_STR_REASON 32
static ERR_STRING_DATA SYS_str_reasons[NUM_SYS_STR_REASONS + 1];
/*
* SYS_str_reasons is filled with copies of strerror() results at
* initialization. 'errno' values up to 127 should cover all usual errors,
* others will be displayed numerically by ERR_error_string. It is crucial
* that we have something for each reason code that occurs in
* ERR_str_reasons, or bogus reason strings will be returned for SYSerr(),
* which always gets an errno value and never one of those 'standard' reason
* codes.
*/
static void build_SYS_str_reasons(void)
{
/* OPENSSL_malloc cannot be used here, use static storage instead */
static char strerror_tab[NUM_SYS_STR_REASONS][LEN_SYS_STR_REASON];
int i;
static int init = 1;
CRYPTO_r_lock(CRYPTO_LOCK_ERR);
if (!init) {
CRYPTO_r_unlock(CRYPTO_LOCK_ERR);
return;
}
CRYPTO_r_unlock(CRYPTO_LOCK_ERR);
CRYPTO_w_lock(CRYPTO_LOCK_ERR);
if (!init) {
CRYPTO_w_unlock(CRYPTO_LOCK_ERR);
return;
}
for (i = 1; i <= NUM_SYS_STR_REASONS; i++) {
ERR_STRING_DATA *str = &SYS_str_reasons[i - 1];
str->error = (unsigned long)i;
if (str->string == NULL) {
char (*dest)[LEN_SYS_STR_REASON] = &(strerror_tab[i - 1]);
char *src = strerror(i);
if (src != NULL) {
- strncpy(*dest, src, sizeof *dest);
- (*dest)[sizeof *dest - 1] = '\0';
+ strncpy(*dest, src, sizeof(*dest));
+ (*dest)[sizeof(*dest) - 1] = '\0';
str->string = *dest;
}
}
if (str->string == NULL)
str->string = "unknown";
}
/*
* Now we still have SYS_str_reasons[NUM_SYS_STR_REASONS] = {0, NULL}, as
* required by ERR_load_strings.
*/
init = 0;
CRYPTO_w_unlock(CRYPTO_LOCK_ERR);
}
#endif
#define err_clear_data(p,i) \
do { \
if (((p)->err_data[i] != NULL) && \
(p)->err_data_flags[i] & ERR_TXT_MALLOCED) \
{ \
OPENSSL_free((p)->err_data[i]); \
(p)->err_data[i]=NULL; \
} \
(p)->err_data_flags[i]=0; \
} while(0)
#define err_clear(p,i) \
do { \
(p)->err_flags[i]=0; \
(p)->err_buffer[i]=0; \
err_clear_data(p,i); \
(p)->err_file[i]=NULL; \
(p)->err_line[i]= -1; \
} while(0)
static void ERR_STATE_free(ERR_STATE *s)
{
int i;
if (s == NULL)
return;
for (i = 0; i < ERR_NUM_ERRORS; i++) {
err_clear_data(s, i);
}
OPENSSL_free(s);
}
void ERR_load_ERR_strings(void)
{
err_fns_check();
#ifndef OPENSSL_NO_ERR
err_load_strings(0, ERR_str_libraries);
err_load_strings(0, ERR_str_reasons);
err_load_strings(ERR_LIB_SYS, ERR_str_functs);
build_SYS_str_reasons();
err_load_strings(ERR_LIB_SYS, SYS_str_reasons);
#endif
}
static void err_load_strings(int lib, ERR_STRING_DATA *str)
{
while (str->error) {
if (lib)
str->error |= ERR_PACK(lib, 0, 0);
ERRFN(err_set_item) (str);
str++;
}
}
void ERR_load_strings(int lib, ERR_STRING_DATA *str)
{
ERR_load_ERR_strings();
err_load_strings(lib, str);
}
void ERR_unload_strings(int lib, ERR_STRING_DATA *str)
{
while (str->error) {
if (lib)
str->error |= ERR_PACK(lib, 0, 0);
ERRFN(err_del_item) (str);
str++;
}
}
void ERR_free_strings(void)
{
err_fns_check();
ERRFN(err_del) ();
}
/********************************************************/
void ERR_put_error(int lib, int func, int reason, const char *file, int line)
{
ERR_STATE *es;
#ifdef _OSD_POSIX
/*
* In the BS2000-OSD POSIX subsystem, the compiler generates path names
* in the form "*POSIX(/etc/passwd)". This dirty hack strips them to
* something sensible. @@@ We shouldn't modify a const string, though.
*/
if (strncmp(file, "*POSIX(", sizeof("*POSIX(") - 1) == 0) {
char *end;
/* Skip the "*POSIX(" prefix */
file += sizeof("*POSIX(") - 1;
end = &file[strlen(file) - 1];
if (*end == ')')
*end = '\0';
/* Optional: use the basename of the path only. */
if ((end = strrchr(file, '/')) != NULL)
file = &end[1];
}
#endif
es = ERR_get_state();
if (es == NULL)
return;
es->top = (es->top + 1) % ERR_NUM_ERRORS;
if (es->top == es->bottom)
es->bottom = (es->bottom + 1) % ERR_NUM_ERRORS;
es->err_flags[es->top] = 0;
es->err_buffer[es->top] = ERR_PACK(lib, func, reason);
es->err_file[es->top] = file;
es->err_line[es->top] = line;
err_clear_data(es, es->top);
}
void ERR_clear_error(void)
{
int i;
ERR_STATE *es;
es = ERR_get_state();
if (es == NULL)
return;
for (i = 0; i < ERR_NUM_ERRORS; i++) {
err_clear(es, i);
}
es->top = es->bottom = 0;
}
unsigned long ERR_get_error(void)
{
return (get_error_values(1, 0, NULL, NULL, NULL, NULL));
}
unsigned long ERR_get_error_line(const char **file, int *line)
{
return (get_error_values(1, 0, file, line, NULL, NULL));
}
unsigned long ERR_get_error_line_data(const char **file, int *line,
const char **data, int *flags)
{
return (get_error_values(1, 0, file, line, data, flags));
}
unsigned long ERR_peek_error(void)
{
return (get_error_values(0, 0, NULL, NULL, NULL, NULL));
}
unsigned long ERR_peek_error_line(const char **file, int *line)
{
return (get_error_values(0, 0, file, line, NULL, NULL));
}
unsigned long ERR_peek_error_line_data(const char **file, int *line,
const char **data, int *flags)
{
return (get_error_values(0, 0, file, line, data, flags));
}
unsigned long ERR_peek_last_error(void)
{
return (get_error_values(0, 1, NULL, NULL, NULL, NULL));
}
unsigned long ERR_peek_last_error_line(const char **file, int *line)
{
return (get_error_values(0, 1, file, line, NULL, NULL));
}
unsigned long ERR_peek_last_error_line_data(const char **file, int *line,
const char **data, int *flags)
{
return (get_error_values(0, 1, file, line, data, flags));
}
static unsigned long get_error_values(int inc, int top, const char **file,
int *line, const char **data,
int *flags)
{
int i = 0;
ERR_STATE *es;
unsigned long ret;
es = ERR_get_state();
if (es == NULL)
return 0;
if (inc && top) {
if (file)
*file = "";
if (line)
*line = 0;
if (data)
*data = "";
if (flags)
*flags = 0;
return ERR_R_INTERNAL_ERROR;
}
if (es->bottom == es->top)
return 0;
if (top)
i = es->top; /* last error */
else
i = (es->bottom + 1) % ERR_NUM_ERRORS; /* first error */
ret = es->err_buffer[i];
if (inc) {
es->bottom = i;
es->err_buffer[i] = 0;
}
if ((file != NULL) && (line != NULL)) {
if (es->err_file[i] == NULL) {
*file = "NA";
if (line != NULL)
*line = 0;
} else {
*file = es->err_file[i];
if (line != NULL)
*line = es->err_line[i];
}
}
if (data == NULL) {
if (inc) {
err_clear_data(es, i);
}
} else {
if (es->err_data[i] == NULL) {
*data = "";
if (flags != NULL)
*flags = 0;
} else {
*data = es->err_data[i];
if (flags != NULL)
*flags = es->err_data_flags[i];
}
}
return ret;
}
void ERR_error_string_n(unsigned long e, char *buf, size_t len)
{
char lsbuf[64], fsbuf[64], rsbuf[64];
const char *ls, *fs, *rs;
unsigned long l, f, r;
if (len == 0)
return;
l = ERR_GET_LIB(e);
f = ERR_GET_FUNC(e);
r = ERR_GET_REASON(e);
ls = ERR_lib_error_string(e);
fs = ERR_func_error_string(e);
rs = ERR_reason_error_string(e);
if (ls == NULL)
BIO_snprintf(lsbuf, sizeof(lsbuf), "lib(%lu)", l);
if (fs == NULL)
BIO_snprintf(fsbuf, sizeof(fsbuf), "func(%lu)", f);
if (rs == NULL)
BIO_snprintf(rsbuf, sizeof(rsbuf), "reason(%lu)", r);
BIO_snprintf(buf, len, "error:%08lX:%s:%s:%s", e, ls ? ls : lsbuf,
fs ? fs : fsbuf, rs ? rs : rsbuf);
if (strlen(buf) == len - 1) {
/*
* output may be truncated; make sure we always have 5
* colon-separated fields, i.e. 4 colons ...
*/
#define NUM_COLONS 4
if (len > NUM_COLONS) { /* ... if possible */
int i;
char *s = buf;
for (i = 0; i < NUM_COLONS; i++) {
char *colon = strchr(s, ':');
if (colon == NULL || colon > &buf[len - 1] - NUM_COLONS + i) {
/*
* set colon no. i at last possible position (buf[len-1]
* is the terminating 0)
*/
colon = &buf[len - 1] - NUM_COLONS + i;
*colon = ':';
}
s = colon + 1;
}
}
}
}
/* BAD for multi-threading: uses a local buffer if ret == NULL */
/*
* ERR_error_string_n should be used instead for ret != NULL as
* ERR_error_string cannot know how large the buffer is
*/
char *ERR_error_string(unsigned long e, char *ret)
{
static char buf[256];
if (ret == NULL)
ret = buf;
ERR_error_string_n(e, ret, 256);
return ret;
}
LHASH_OF(ERR_STRING_DATA) *ERR_get_string_table(void)
{
err_fns_check();
return ERRFN(err_get) (0);
}
LHASH_OF(ERR_STATE) *ERR_get_err_state_table(void)
{
err_fns_check();
return ERRFN(thread_get) (0);
}
void ERR_release_err_state_table(LHASH_OF(ERR_STATE) **hash)
{
err_fns_check();
ERRFN(thread_release) (hash);
}
const char *ERR_lib_error_string(unsigned long e)
{
ERR_STRING_DATA d, *p;
unsigned long l;
err_fns_check();
l = ERR_GET_LIB(e);
d.error = ERR_PACK(l, 0, 0);
p = ERRFN(err_get_item) (&d);
return ((p == NULL) ? NULL : p->string);
}
const char *ERR_func_error_string(unsigned long e)
{
ERR_STRING_DATA d, *p;
unsigned long l, f;
err_fns_check();
l = ERR_GET_LIB(e);
f = ERR_GET_FUNC(e);
d.error = ERR_PACK(l, f, 0);
p = ERRFN(err_get_item) (&d);
return ((p == NULL) ? NULL : p->string);
}
const char *ERR_reason_error_string(unsigned long e)
{
ERR_STRING_DATA d, *p = NULL;
unsigned long l, r;
err_fns_check();
l = ERR_GET_LIB(e);
r = ERR_GET_REASON(e);
d.error = ERR_PACK(l, 0, r);
p = ERRFN(err_get_item) (&d);
if (!p) {
d.error = ERR_PACK(0, 0, r);
p = ERRFN(err_get_item) (&d);
}
return ((p == NULL) ? NULL : p->string);
}
void ERR_remove_thread_state(const CRYPTO_THREADID *id)
{
ERR_STATE tmp;
if (id)
CRYPTO_THREADID_cpy(&tmp.tid, id);
else
CRYPTO_THREADID_current(&tmp.tid);
err_fns_check();
/*
* thread_del_item automatically destroys the LHASH if the number of
* items reaches zero.
*/
ERRFN(thread_del_item) (&tmp);
}
#ifndef OPENSSL_NO_DEPRECATED
void ERR_remove_state(unsigned long pid)
{
ERR_remove_thread_state(NULL);
}
#endif
ERR_STATE *ERR_get_state(void)
{
ERR_STATE *ret, tmp, *tmpp = NULL;
int i;
CRYPTO_THREADID tid;
err_fns_check();
CRYPTO_THREADID_current(&tid);
CRYPTO_THREADID_cpy(&tmp.tid, &tid);
ret = ERRFN(thread_get_item) (&tmp);
/* ret == the error state, if NULL, make a new one */
if (ret == NULL) {
ret = (ERR_STATE *)OPENSSL_malloc(sizeof(ERR_STATE));
if (ret == NULL)
return NULL;
CRYPTO_THREADID_cpy(&ret->tid, &tid);
ret->top = 0;
ret->bottom = 0;
for (i = 0; i < ERR_NUM_ERRORS; i++) {
ret->err_data[i] = NULL;
ret->err_data_flags[i] = 0;
}
tmpp = ERRFN(thread_set_item) (ret);
/* To check if insertion failed, do a get. */
if (ERRFN(thread_get_item) (ret) != ret) {
ERR_STATE_free(ret); /* could not insert it */
return NULL;
}
/*
* If a race occured in this function and we came second, tmpp is the
* first one that we just replaced.
*/
if (tmpp)
ERR_STATE_free(tmpp);
}
return ret;
}
int ERR_get_next_error_library(void)
{
err_fns_check();
return ERRFN(get_next_lib) ();
}
void ERR_set_error_data(char *data, int flags)
{
ERR_STATE *es;
int i;
es = ERR_get_state();
if (es == NULL)
return;
i = es->top;
err_clear_data(es, i);
es->err_data[i] = data;
es->err_data_flags[i] = flags;
}
void ERR_add_error_data(int num, ...)
{
va_list args;
va_start(args, num);
ERR_add_error_vdata(num, args);
va_end(args);
}
void ERR_add_error_vdata(int num, va_list args)
{
int i, n, s;
char *str, *p, *a;
s = 80;
str = OPENSSL_malloc(s + 1);
if (str == NULL)
return;
str[0] = '\0';
n = 0;
for (i = 0; i < num; i++) {
a = va_arg(args, char *);
/* ignore NULLs, thanks to Bob Beck <beck@obtuse.com> */
if (a != NULL) {
n += strlen(a);
if (n > s) {
s = n + 20;
p = OPENSSL_realloc(str, s + 1);
if (p == NULL) {
OPENSSL_free(str);
return;
} else
str = p;
}
BUF_strlcat(str, a, (size_t)s + 1);
}
}
ERR_set_error_data(str, ERR_TXT_MALLOCED | ERR_TXT_STRING);
}
int ERR_set_mark(void)
{
ERR_STATE *es;
es = ERR_get_state();
if (es == NULL)
return 0;
if (es->bottom == es->top)
return 0;
es->err_flags[es->top] |= ERR_FLAG_MARK;
return 1;
}
int ERR_pop_to_mark(void)
{
ERR_STATE *es;
es = ERR_get_state();
if (es == NULL)
return 0;
while (es->bottom != es->top
&& (es->err_flags[es->top] & ERR_FLAG_MARK) == 0) {
err_clear(es, es->top);
es->top -= 1;
if (es->top == -1)
es->top = ERR_NUM_ERRORS - 1;
}
if (es->bottom == es->top)
return 0;
es->err_flags[es->top] &= ~ERR_FLAG_MARK;
return 1;
}
diff --git a/crypto/err/err_prn.c b/crypto/err/err_prn.c
index 6e352effe31d..25c808eab73b 100644
--- a/crypto/err/err_prn.c
+++ b/crypto/err/err_prn.c
@@ -1,113 +1,113 @@
/* crypto/err/err_prn.c */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
#include <stdio.h>
#include "cryptlib.h"
#include <openssl/lhash.h>
#include <openssl/crypto.h>
#include <openssl/buffer.h>
#include <openssl/err.h>
void ERR_print_errors_cb(int (*cb) (const char *str, size_t len, void *u),
void *u)
{
unsigned long l;
char buf[256];
char buf2[4096];
const char *file, *data;
int line, flags;
unsigned long es;
CRYPTO_THREADID cur;
CRYPTO_THREADID_current(&cur);
es = CRYPTO_THREADID_hash(&cur);
while ((l = ERR_get_error_line_data(&file, &line, &data, &flags)) != 0) {
- ERR_error_string_n(l, buf, sizeof buf);
+ ERR_error_string_n(l, buf, sizeof(buf));
BIO_snprintf(buf2, sizeof(buf2), "%lu:%s:%s:%d:%s\n", es, buf,
file, line, (flags & ERR_TXT_STRING) ? data : "");
if (cb(buf2, strlen(buf2), u) <= 0)
break; /* abort outputting the error report */
}
}
#ifndef OPENSSL_NO_FP_API
static int print_fp(const char *str, size_t len, void *fp)
{
BIO bio;
BIO_set(&bio, BIO_s_file());
BIO_set_fp(&bio, fp, BIO_NOCLOSE);
return BIO_printf(&bio, "%s", str);
}
void ERR_print_errors_fp(FILE *fp)
{
ERR_print_errors_cb(print_fp, fp);
}
#endif
static int print_bio(const char *str, size_t len, void *bp)
{
return BIO_write((BIO *)bp, str, len);
}
void ERR_print_errors(BIO *bp)
{
ERR_print_errors_cb(print_bio, bp);
}
diff --git a/crypto/evp/bio_b64.c b/crypto/evp/bio_b64.c
index 538b5202643a..5ad5a950352b 100644
--- a/crypto/evp/bio_b64.c
+++ b/crypto/evp/bio_b64.c
@@ -1,573 +1,581 @@
/* crypto/evp/bio_b64.c */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
#include <stdio.h>
#include <errno.h>
#include "cryptlib.h"
#include <openssl/buffer.h>
#include <openssl/evp.h>
static int b64_write(BIO *h, const char *buf, int num);
static int b64_read(BIO *h, char *buf, int size);
static int b64_puts(BIO *h, const char *str);
/*
* static int b64_gets(BIO *h, char *str, int size);
*/
static long b64_ctrl(BIO *h, int cmd, long arg1, void *arg2);
static int b64_new(BIO *h);
static int b64_free(BIO *data);
static long b64_callback_ctrl(BIO *h, int cmd, bio_info_cb *fp);
#define B64_BLOCK_SIZE 1024
#define B64_BLOCK_SIZE2 768
#define B64_NONE 0
#define B64_ENCODE 1
#define B64_DECODE 2
typedef struct b64_struct {
/*
* BIO *bio; moved to the BIO structure
*/
int buf_len;
int buf_off;
int tmp_len; /* used to find the start when decoding */
int tmp_nl; /* If true, scan until '\n' */
int encode;
int start; /* have we started decoding yet? */
int cont; /* <= 0 when finished */
EVP_ENCODE_CTX base64;
char buf[EVP_ENCODE_LENGTH(B64_BLOCK_SIZE) + 10];
char tmp[B64_BLOCK_SIZE];
} BIO_B64_CTX;
static BIO_METHOD methods_b64 = {
BIO_TYPE_BASE64, "base64 encoding",
b64_write,
b64_read,
b64_puts,
NULL, /* b64_gets, */
b64_ctrl,
b64_new,
b64_free,
b64_callback_ctrl,
};
BIO_METHOD *BIO_f_base64(void)
{
return (&methods_b64);
}
static int b64_new(BIO *bi)
{
BIO_B64_CTX *ctx;
ctx = (BIO_B64_CTX *)OPENSSL_malloc(sizeof(BIO_B64_CTX));
if (ctx == NULL)
return (0);
ctx->buf_len = 0;
ctx->tmp_len = 0;
ctx->tmp_nl = 0;
ctx->buf_off = 0;
ctx->cont = 1;
ctx->start = 1;
ctx->encode = 0;
bi->init = 1;
bi->ptr = (char *)ctx;
bi->flags = 0;
bi->num = 0;
return (1);
}
static int b64_free(BIO *a)
{
if (a == NULL)
return (0);
OPENSSL_free(a->ptr);
a->ptr = NULL;
a->init = 0;
a->flags = 0;
return (1);
}
static int b64_read(BIO *b, char *out, int outl)
{
int ret = 0, i, ii, j, k, x, n, num, ret_code = 0;
BIO_B64_CTX *ctx;
unsigned char *p, *q;
if (out == NULL)
return (0);
ctx = (BIO_B64_CTX *)b->ptr;
if ((ctx == NULL) || (b->next_bio == NULL))
return (0);
BIO_clear_retry_flags(b);
if (ctx->encode != B64_DECODE) {
ctx->encode = B64_DECODE;
ctx->buf_len = 0;
ctx->buf_off = 0;
ctx->tmp_len = 0;
EVP_DecodeInit(&(ctx->base64));
}
/* First check if there are bytes decoded/encoded */
if (ctx->buf_len > 0) {
OPENSSL_assert(ctx->buf_len >= ctx->buf_off);
i = ctx->buf_len - ctx->buf_off;
if (i > outl)
i = outl;
OPENSSL_assert(ctx->buf_off + i < (int)sizeof(ctx->buf));
memcpy(out, &(ctx->buf[ctx->buf_off]), i);
ret = i;
out += i;
outl -= i;
ctx->buf_off += i;
if (ctx->buf_len == ctx->buf_off) {
ctx->buf_len = 0;
ctx->buf_off = 0;
}
}
/*
* At this point, we have room of outl bytes and an empty buffer, so we
* should read in some more.
*/
ret_code = 0;
while (outl > 0) {
if (ctx->cont <= 0)
break;
i = BIO_read(b->next_bio, &(ctx->tmp[ctx->tmp_len]),
B64_BLOCK_SIZE - ctx->tmp_len);
if (i <= 0) {
ret_code = i;
/* Should we continue next time we are called? */
if (!BIO_should_retry(b->next_bio)) {
ctx->cont = i;
/* If buffer empty break */
if (ctx->tmp_len == 0)
break;
/* Fall through and process what we have */
else
i = 0;
}
/* else we retry and add more data to buffer */
else
break;
}
i += ctx->tmp_len;
ctx->tmp_len = i;
/*
* We need to scan, a line at a time until we have a valid line if we
* are starting.
*/
if (ctx->start && (BIO_get_flags(b) & BIO_FLAGS_BASE64_NO_NL)) {
/* ctx->start=1; */
ctx->tmp_len = 0;
} else if (ctx->start) {
q = p = (unsigned char *)ctx->tmp;
num = 0;
for (j = 0; j < i; j++) {
if (*(q++) != '\n')
continue;
/*
* due to a previous very long line, we need to keep on
* scanning for a '\n' before we even start looking for
* base64 encoded stuff.
*/
if (ctx->tmp_nl) {
p = q;
ctx->tmp_nl = 0;
continue;
}
k = EVP_DecodeUpdate(&(ctx->base64),
(unsigned char *)ctx->buf,
&num, p, q - p);
if ((k <= 0) && (num == 0) && (ctx->start))
EVP_DecodeInit(&ctx->base64);
else {
if (p != (unsigned char *)
&(ctx->tmp[0])) {
i -= (p - (unsigned char *)
&(ctx->tmp[0]));
for (x = 0; x < i; x++)
ctx->tmp[x] = p[x];
}
EVP_DecodeInit(&ctx->base64);
ctx->start = 0;
break;
}
p = q;
}
/* we fell off the end without starting */
if ((j == i) && (num == 0)) {
/*
* Is this is one long chunk?, if so, keep on reading until a
* new line.
*/
if (p == (unsigned char *)&(ctx->tmp[0])) {
/* Check buffer full */
if (i == B64_BLOCK_SIZE) {
ctx->tmp_nl = 1;
ctx->tmp_len = 0;
}
} else if (p != q) { /* finished on a '\n' */
n = q - p;
for (ii = 0; ii < n; ii++)
ctx->tmp[ii] = p[ii];
ctx->tmp_len = n;
}
/* else finished on a '\n' */
continue;
} else {
ctx->tmp_len = 0;
}
} else if ((i < B64_BLOCK_SIZE) && (ctx->cont > 0)) {
/*
* If buffer isn't full and we can retry then restart to read in
* more data.
*/
continue;
}
if (BIO_get_flags(b) & BIO_FLAGS_BASE64_NO_NL) {
int z, jj;
#if 0
jj = (i >> 2) << 2;
#else
jj = i & ~3; /* process per 4 */
#endif
z = EVP_DecodeBlock((unsigned char *)ctx->buf,
(unsigned char *)ctx->tmp, jj);
if (jj > 2) {
if (ctx->tmp[jj - 1] == '=') {
z--;
if (ctx->tmp[jj - 2] == '=')
z--;
}
}
/*
* z is now number of output bytes and jj is the number consumed
*/
if (jj != i) {
memmove(ctx->tmp, &ctx->tmp[jj], i - jj);
ctx->tmp_len = i - jj;
}
ctx->buf_len = 0;
if (z > 0) {
ctx->buf_len = z;
}
i = z;
} else {
i = EVP_DecodeUpdate(&(ctx->base64),
(unsigned char *)ctx->buf, &ctx->buf_len,
(unsigned char *)ctx->tmp, i);
ctx->tmp_len = 0;
}
+ /*
+ * If eof or an error was signalled, then the condition
+ * 'ctx->cont <= 0' will prevent b64_read() from reading
+ * more data on subsequent calls. This assignment was
+ * deleted accidentally in commit 5562cfaca4f3.
+ */
+ ctx->cont = i;
+
ctx->buf_off = 0;
if (i < 0) {
ret_code = 0;
ctx->buf_len = 0;
break;
}
if (ctx->buf_len <= outl)
i = ctx->buf_len;
else
i = outl;
memcpy(out, ctx->buf, i);
ret += i;
ctx->buf_off = i;
if (ctx->buf_off == ctx->buf_len) {
ctx->buf_len = 0;
ctx->buf_off = 0;
}
outl -= i;
out += i;
}
/* BIO_clear_retry_flags(b); */
BIO_copy_next_retry(b);
return ((ret == 0) ? ret_code : ret);
}
static int b64_write(BIO *b, const char *in, int inl)
{
int ret = 0;
int n;
int i;
BIO_B64_CTX *ctx;
ctx = (BIO_B64_CTX *)b->ptr;
BIO_clear_retry_flags(b);
if (ctx->encode != B64_ENCODE) {
ctx->encode = B64_ENCODE;
ctx->buf_len = 0;
ctx->buf_off = 0;
ctx->tmp_len = 0;
EVP_EncodeInit(&(ctx->base64));
}
OPENSSL_assert(ctx->buf_off < (int)sizeof(ctx->buf));
OPENSSL_assert(ctx->buf_len <= (int)sizeof(ctx->buf));
OPENSSL_assert(ctx->buf_len >= ctx->buf_off);
n = ctx->buf_len - ctx->buf_off;
while (n > 0) {
i = BIO_write(b->next_bio, &(ctx->buf[ctx->buf_off]), n);
if (i <= 0) {
BIO_copy_next_retry(b);
return (i);
}
OPENSSL_assert(i <= n);
ctx->buf_off += i;
OPENSSL_assert(ctx->buf_off <= (int)sizeof(ctx->buf));
OPENSSL_assert(ctx->buf_len >= ctx->buf_off);
n -= i;
}
/* at this point all pending data has been written */
ctx->buf_off = 0;
ctx->buf_len = 0;
if ((in == NULL) || (inl <= 0))
return (0);
while (inl > 0) {
n = (inl > B64_BLOCK_SIZE) ? B64_BLOCK_SIZE : inl;
if (BIO_get_flags(b) & BIO_FLAGS_BASE64_NO_NL) {
if (ctx->tmp_len > 0) {
OPENSSL_assert(ctx->tmp_len <= 3);
n = 3 - ctx->tmp_len;
/*
* There's a theoretical possibility for this
*/
if (n > inl)
n = inl;
memcpy(&(ctx->tmp[ctx->tmp_len]), in, n);
ctx->tmp_len += n;
ret += n;
if (ctx->tmp_len < 3)
break;
ctx->buf_len =
EVP_EncodeBlock((unsigned char *)ctx->buf,
(unsigned char *)ctx->tmp, ctx->tmp_len);
OPENSSL_assert(ctx->buf_len <= (int)sizeof(ctx->buf));
OPENSSL_assert(ctx->buf_len >= ctx->buf_off);
/*
* Since we're now done using the temporary buffer, the
* length should be 0'd
*/
ctx->tmp_len = 0;
} else {
if (n < 3) {
memcpy(ctx->tmp, in, n);
ctx->tmp_len = n;
ret += n;
break;
}
n -= n % 3;
ctx->buf_len =
EVP_EncodeBlock((unsigned char *)ctx->buf,
(const unsigned char *)in, n);
OPENSSL_assert(ctx->buf_len <= (int)sizeof(ctx->buf));
OPENSSL_assert(ctx->buf_len >= ctx->buf_off);
ret += n;
}
} else {
EVP_EncodeUpdate(&(ctx->base64),
(unsigned char *)ctx->buf, &ctx->buf_len,
(unsigned char *)in, n);
OPENSSL_assert(ctx->buf_len <= (int)sizeof(ctx->buf));
OPENSSL_assert(ctx->buf_len >= ctx->buf_off);
ret += n;
}
inl -= n;
in += n;
ctx->buf_off = 0;
n = ctx->buf_len;
while (n > 0) {
i = BIO_write(b->next_bio, &(ctx->buf[ctx->buf_off]), n);
if (i <= 0) {
BIO_copy_next_retry(b);
return ((ret == 0) ? i : ret);
}
OPENSSL_assert(i <= n);
n -= i;
ctx->buf_off += i;
OPENSSL_assert(ctx->buf_off <= (int)sizeof(ctx->buf));
OPENSSL_assert(ctx->buf_len >= ctx->buf_off);
}
ctx->buf_len = 0;
ctx->buf_off = 0;
}
return (ret);
}
static long b64_ctrl(BIO *b, int cmd, long num, void *ptr)
{
BIO_B64_CTX *ctx;
long ret = 1;
int i;
ctx = (BIO_B64_CTX *)b->ptr;
switch (cmd) {
case BIO_CTRL_RESET:
ctx->cont = 1;
ctx->start = 1;
ctx->encode = B64_NONE;
ret = BIO_ctrl(b->next_bio, cmd, num, ptr);
break;
case BIO_CTRL_EOF: /* More to read */
if (ctx->cont <= 0)
ret = 1;
else
ret = BIO_ctrl(b->next_bio, cmd, num, ptr);
break;
case BIO_CTRL_WPENDING: /* More to write in buffer */
OPENSSL_assert(ctx->buf_len >= ctx->buf_off);
ret = ctx->buf_len - ctx->buf_off;
if ((ret == 0) && (ctx->encode != B64_NONE)
&& (ctx->base64.num != 0))
ret = 1;
else if (ret <= 0)
ret = BIO_ctrl(b->next_bio, cmd, num, ptr);
break;
case BIO_CTRL_PENDING: /* More to read in buffer */
OPENSSL_assert(ctx->buf_len >= ctx->buf_off);
ret = ctx->buf_len - ctx->buf_off;
if (ret <= 0)
ret = BIO_ctrl(b->next_bio, cmd, num, ptr);
break;
case BIO_CTRL_FLUSH:
/* do a final write */
again:
while (ctx->buf_len != ctx->buf_off) {
i = b64_write(b, NULL, 0);
if (i < 0)
return i;
}
if (BIO_get_flags(b) & BIO_FLAGS_BASE64_NO_NL) {
if (ctx->tmp_len != 0) {
ctx->buf_len = EVP_EncodeBlock((unsigned char *)ctx->buf,
(unsigned char *)ctx->tmp,
ctx->tmp_len);
ctx->buf_off = 0;
ctx->tmp_len = 0;
goto again;
}
} else if (ctx->encode != B64_NONE && ctx->base64.num != 0) {
ctx->buf_off = 0;
EVP_EncodeFinal(&(ctx->base64),
(unsigned char *)ctx->buf, &(ctx->buf_len));
/* push out the bytes */
goto again;
}
/* Finally flush the underlying BIO */
ret = BIO_ctrl(b->next_bio, cmd, num, ptr);
break;
case BIO_C_DO_STATE_MACHINE:
BIO_clear_retry_flags(b);
ret = BIO_ctrl(b->next_bio, cmd, num, ptr);
BIO_copy_next_retry(b);
break;
case BIO_CTRL_DUP:
break;
case BIO_CTRL_INFO:
case BIO_CTRL_GET:
case BIO_CTRL_SET:
default:
ret = BIO_ctrl(b->next_bio, cmd, num, ptr);
break;
}
return (ret);
}
static long b64_callback_ctrl(BIO *b, int cmd, bio_info_cb *fp)
{
long ret = 1;
if (b->next_bio == NULL)
return (0);
switch (cmd) {
default:
ret = BIO_callback_ctrl(b->next_bio, cmd, fp);
break;
}
return (ret);
}
static int b64_puts(BIO *b, const char *str)
{
return b64_write(b, str, strlen(str));
}
diff --git a/crypto/evp/digest.c b/crypto/evp/digest.c
index 4db179629d04..d4274c5729b7 100644
--- a/crypto/evp/digest.c
+++ b/crypto/evp/digest.c
@@ -1,408 +1,408 @@
/* crypto/evp/digest.c */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
/* ====================================================================
* Copyright (c) 1998-2001 The OpenSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* openssl-core@openssl.org.
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.openssl.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*
* This product includes cryptographic software written by Eric Young
* (eay@cryptsoft.com). This product includes software written by Tim
* Hudson (tjh@cryptsoft.com).
*
*/
#include <stdio.h>
#include "cryptlib.h"
#include <openssl/objects.h>
#include <openssl/evp.h>
#ifndef OPENSSL_NO_ENGINE
# include <openssl/engine.h>
#endif
#ifdef OPENSSL_FIPS
# include <openssl/fips.h>
# include "evp_locl.h"
#endif
void EVP_MD_CTX_init(EVP_MD_CTX *ctx)
{
- memset(ctx, '\0', sizeof *ctx);
+ memset(ctx, '\0', sizeof(*ctx));
}
EVP_MD_CTX *EVP_MD_CTX_create(void)
{
- EVP_MD_CTX *ctx = OPENSSL_malloc(sizeof *ctx);
+ EVP_MD_CTX *ctx = OPENSSL_malloc(sizeof(*ctx));
if (ctx)
EVP_MD_CTX_init(ctx);
return ctx;
}
int EVP_DigestInit(EVP_MD_CTX *ctx, const EVP_MD *type)
{
EVP_MD_CTX_init(ctx);
return EVP_DigestInit_ex(ctx, type, NULL);
}
int EVP_DigestInit_ex(EVP_MD_CTX *ctx, const EVP_MD *type, ENGINE *impl)
{
EVP_MD_CTX_clear_flags(ctx, EVP_MD_CTX_FLAG_CLEANED);
#ifdef OPENSSL_FIPS
/* If FIPS mode switch to approved implementation if possible */
if (FIPS_mode()) {
const EVP_MD *fipsmd;
if (type) {
fipsmd = evp_get_fips_md(type);
if (fipsmd)
type = fipsmd;
}
}
#endif
#ifndef OPENSSL_NO_ENGINE
/*
* 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 unecessary.
*/
if (ctx->engine && ctx->digest && (!type ||
(type
&& (type->type ==
ctx->digest->type))))
goto skip_to_init;
if (type) {
/*
* 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).
*/
if (ctx->engine)
ENGINE_finish(ctx->engine);
if (impl) {
if (!ENGINE_init(impl)) {
EVPerr(EVP_F_EVP_DIGESTINIT_EX, EVP_R_INITIALIZATION_ERROR);
return 0;
}
} else
/* Ask if an ENGINE is reserved for this job */
impl = ENGINE_get_digest_engine(type->type);
if (impl) {
/* There's an ENGINE for this job ... (apparently) */
const EVP_MD *d = ENGINE_get_digest(impl, type->type);
if (!d) {
/* Same comment from evp_enc.c */
EVPerr(EVP_F_EVP_DIGESTINIT_EX, 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;
} else {
if (!ctx->digest) {
EVPerr(EVP_F_EVP_DIGESTINIT_EX, EVP_R_NO_DIGEST_SET);
return 0;
}
type = ctx->digest;
}
#endif
if (ctx->digest != type) {
if (ctx->digest && ctx->digest->ctx_size) {
OPENSSL_free(ctx->md_data);
ctx->md_data = NULL;
}
ctx->digest = type;
if (!(ctx->flags & EVP_MD_CTX_FLAG_NO_INIT) && type->ctx_size) {
ctx->update = type->update;
ctx->md_data = OPENSSL_malloc(type->ctx_size);
if (ctx->md_data == NULL) {
EVPerr(EVP_F_EVP_DIGESTINIT_EX, ERR_R_MALLOC_FAILURE);
return 0;
}
}
}
#ifndef OPENSSL_NO_ENGINE
skip_to_init:
#endif
if (ctx->pctx) {
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;
}
if (ctx->flags & EVP_MD_CTX_FLAG_NO_INIT)
return 1;
#ifdef OPENSSL_FIPS
if (FIPS_mode()) {
if (FIPS_digestinit(ctx, type))
return 1;
OPENSSL_free(ctx->md_data);
ctx->md_data = NULL;
return 0;
}
#endif
return ctx->digest->init(ctx);
}
int EVP_DigestUpdate(EVP_MD_CTX *ctx, const void *data, size_t count)
{
#ifdef OPENSSL_FIPS
if (FIPS_mode())
return FIPS_digestupdate(ctx, data, count);
#endif
return ctx->update(ctx, data, count);
}
/* 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_cleanup(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 *size)
{
int ret;
#ifdef OPENSSL_FIPS
if (FIPS_mode())
return FIPS_digestfinal(ctx, md, size);
#endif
OPENSSL_assert(ctx->digest->md_size <= EVP_MAX_MD_SIZE);
ret = ctx->digest->final(ctx, md);
if (size != NULL)
*size = ctx->digest->md_size;
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_MD_CTX_copy(EVP_MD_CTX *out, const EVP_MD_CTX *in)
{
EVP_MD_CTX_init(out);
return EVP_MD_CTX_copy_ex(out, in);
}
int EVP_MD_CTX_copy_ex(EVP_MD_CTX *out, const EVP_MD_CTX *in)
{
unsigned char *tmp_buf;
if ((in == NULL) || (in->digest == NULL)) {
EVPerr(EVP_F_EVP_MD_CTX_COPY_EX, EVP_R_INPUT_NOT_INITIALIZED);
return 0;
}
#ifndef OPENSSL_NO_ENGINE
/* Make sure it's safe to copy a digest context using an ENGINE */
if (in->engine && !ENGINE_init(in->engine)) {
EVPerr(EVP_F_EVP_MD_CTX_COPY_EX, 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_cleanup(out);
- memcpy(out, in, sizeof *out);
+ memcpy(out, in, sizeof(*out));
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) {
EVPerr(EVP_F_EVP_MD_CTX_COPY_EX, ERR_R_MALLOC_FAILURE);
return 0;
}
}
memcpy(out->md_data, in->md_data, out->digest->ctx_size);
}
out->update = in->update;
if (in->pctx) {
out->pctx = EVP_PKEY_CTX_dup(in->pctx);
if (!out->pctx) {
EVP_MD_CTX_cleanup(out);
return 0;
}
}
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;
int ret;
EVP_MD_CTX_init(&ctx);
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_cleanup(&ctx);
return ret;
}
void EVP_MD_CTX_destroy(EVP_MD_CTX *ctx)
{
if (ctx) {
EVP_MD_CTX_cleanup(ctx);
OPENSSL_free(ctx);
}
}
/* This call frees resources associated with the context */
int EVP_MD_CTX_cleanup(EVP_MD_CTX *ctx)
{
#ifndef OPENSSL_FIPS
/*
* Don't assume ctx->md_data was cleaned in EVP_Digest_Final, because
* sometimes only copies of the context are ever finalised.
*/
if (ctx->digest && ctx->digest->cleanup
&& !EVP_MD_CTX_test_flags(ctx, EVP_MD_CTX_FLAG_CLEANED))
ctx->digest->cleanup(ctx);
if (ctx->digest && ctx->digest->ctx_size && ctx->md_data
&& !EVP_MD_CTX_test_flags(ctx, EVP_MD_CTX_FLAG_REUSE)) {
OPENSSL_cleanse(ctx->md_data, ctx->digest->ctx_size);
OPENSSL_free(ctx->md_data);
}
#endif
if (ctx->pctx)
EVP_PKEY_CTX_free(ctx->pctx);
#ifndef OPENSSL_NO_ENGINE
if (ctx->engine)
/*
* The EVP_MD we used belongs to an ENGINE, release the functional
* reference we held for this reason.
*/
ENGINE_finish(ctx->engine);
#endif
#ifdef OPENSSL_FIPS
FIPS_md_ctx_cleanup(ctx);
#endif
- memset(ctx, '\0', sizeof *ctx);
+ memset(ctx, '\0', sizeof(*ctx));
return 1;
}
diff --git a/crypto/evp/e_aes.c b/crypto/evp/e_aes.c
index b45b364466ac..ccc626f1d81c 100644
--- a/crypto/evp/e_aes.c
+++ b/crypto/evp/e_aes.c
@@ -1,2031 +1,2033 @@
/* ====================================================================
- * Copyright (c) 2001-2011 The OpenSSL Project. All rights reserved.
+ * Copyright (c) 2001-2018 The OpenSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* openssl-core@openssl.org.
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.openssl.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*
*/
#include <openssl/opensslconf.h>
#ifndef OPENSSL_NO_AES
#include <openssl/crypto.h>
# include <openssl/evp.h>
# include <openssl/err.h>
# include <string.h>
# include <assert.h>
# include <openssl/aes.h>
# include "evp_locl.h"
# include "modes_lcl.h"
# include <openssl/rand.h>
# undef EVP_CIPH_FLAG_FIPS
# define EVP_CIPH_FLAG_FIPS 0
typedef struct {
union {
double align;
AES_KEY ks;
} ks;
block128_f block;
union {
cbc128_f cbc;
ctr128_f ctr;
} stream;
} EVP_AES_KEY;
typedef struct {
union {
double align;
AES_KEY ks;
} ks; /* AES key schedule to use */
int key_set; /* Set if key initialised */
int iv_set; /* Set if an iv is set */
GCM128_CONTEXT gcm;
unsigned char *iv; /* Temporary IV store */
int ivlen; /* IV length */
int taglen;
int iv_gen; /* It is OK to generate IVs */
int tls_aad_len; /* TLS AAD length */
ctr128_f ctr;
} EVP_AES_GCM_CTX;
typedef struct {
union {
double align;
AES_KEY ks;
} ks1, ks2; /* AES key schedules to use */
XTS128_CONTEXT xts;
void (*stream) (const unsigned char *in,
unsigned char *out, size_t length,
const AES_KEY *key1, const AES_KEY *key2,
const unsigned char iv[16]);
} EVP_AES_XTS_CTX;
typedef struct {
union {
double align;
AES_KEY ks;
} ks; /* AES key schedule to use */
int key_set; /* Set if key initialised */
int iv_set; /* Set if an iv is set */
int tag_set; /* Set if tag is valid */
int len_set; /* Set if message length set */
int L, M; /* L and M parameters from RFC3610 */
CCM128_CONTEXT ccm;
ccm128_f str;
} EVP_AES_CCM_CTX;
# define MAXBITCHUNK ((size_t)1<<(sizeof(size_t)*8-4))
# 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
# ifdef BSAES_ASM
void bsaes_cbc_encrypt(const unsigned char *in, unsigned char *out,
size_t length, const AES_KEY *key,
unsigned char ivec[16], int enc);
void bsaes_ctr32_encrypt_blocks(const unsigned char *in, unsigned char *out,
size_t len, const AES_KEY *key,
const unsigned char ivec[16]);
void 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 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
# 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
# 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
# if defined(OPENSSL_CPUID_OBJ) && (defined(__powerpc__) || defined(__ppc__) || defined(_ARCH_PPC))
# include "ppc_arch.h"
# ifdef VPAES_ASM
# define VPAES_CAPABLE (OPENSSL_ppccap_P & PPC_ALTIVEC)
# endif
# 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
# 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) || \
defined(__INTEL__) )
extern unsigned int OPENSSL_ia32cap_P[];
# 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
/*
* AES-NI section
*/
# define AESNI_CAPABLE (OPENSSL_ia32cap_P[1]&(1<<(57-32)))
int aesni_set_encrypt_key(const unsigned char *userKey, int bits,
AES_KEY *key);
int aesni_set_decrypt_key(const unsigned char *userKey, int bits,
AES_KEY *key);
void aesni_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);
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);
# define AES_gcm_encrypt aesni_gcm_encrypt
size_t aesni_gcm_decrypt(const unsigned char *in,
unsigned char *out,
size_t len,
const void *key, unsigned char ivec[16], u64 *Xi);
# define AES_gcm_decrypt aesni_gcm_decrypt
void gcm_ghash_avx(u64 Xi[2], const u128 Htable[16], const u8 *in,
size_t len);
# define AES_GCM_ASM(gctx) (gctx->ctr==aesni_ctr32_encrypt_blocks && \
gctx->gcm.ghash==gcm_ghash_avx)
# define AES_GCM_ASM2(gctx) (gctx->gcm.block==(block128_f)aesni_encrypt && \
gctx->gcm.ghash==gcm_ghash_avx)
# undef AES_GCM_ASM2 /* minor size optimization */
# endif
static int aesni_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key,
const unsigned char *iv, int enc)
{
int ret, mode;
EVP_AES_KEY *dat = (EVP_AES_KEY *) ctx->cipher_data;
mode = ctx->cipher->flags & EVP_CIPH_MODE;
if ((mode == EVP_CIPH_ECB_MODE || mode == EVP_CIPH_CBC_MODE)
&& !enc) {
ret = aesni_set_decrypt_key(key, ctx->key_len * 8, ctx->cipher_data);
dat->block = (block128_f) aesni_decrypt;
dat->stream.cbc = mode == EVP_CIPH_CBC_MODE ?
(cbc128_f) aesni_cbc_encrypt : NULL;
} else {
ret = aesni_set_encrypt_key(key, ctx->key_len * 8, ctx->cipher_data);
dat->block = (block128_f) aesni_encrypt;
if (mode == EVP_CIPH_CBC_MODE)
dat->stream.cbc = (cbc128_f) aesni_cbc_encrypt;
else if (mode == EVP_CIPH_CTR_MODE)
dat->stream.ctr = (ctr128_f) aesni_ctr32_encrypt_blocks;
else
dat->stream.cbc = NULL;
}
if (ret < 0) {
EVPerr(EVP_F_AESNI_INIT_KEY, EVP_R_AES_KEY_SETUP_FAILED);
return 0;
}
return 1;
}
static int aesni_cbc_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
const unsigned char *in, size_t len)
{
aesni_cbc_encrypt(in, out, len, ctx->cipher_data, ctx->iv, ctx->encrypt);
return 1;
}
static int aesni_ecb_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
const unsigned char *in, size_t len)
{
size_t bl = ctx->cipher->block_size;
if (len < bl)
return 1;
aesni_ecb_encrypt(in, out, len, ctx->cipher_data, ctx->encrypt);
return 1;
}
# define aesni_ofb_cipher aes_ofb_cipher
static int aesni_ofb_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
const unsigned char *in, size_t len);
# define aesni_cfb_cipher aes_cfb_cipher
static int aesni_cfb_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
const unsigned char *in, size_t len);
# define aesni_cfb8_cipher aes_cfb8_cipher
static int aesni_cfb8_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
const unsigned char *in, size_t len);
# define aesni_cfb1_cipher aes_cfb1_cipher
static int aesni_cfb1_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
const unsigned char *in, size_t len);
# define aesni_ctr_cipher aes_ctr_cipher
static int aesni_ctr_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
const unsigned char *in, size_t len);
static int aesni_gcm_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key,
const unsigned char *iv, int enc)
{
EVP_AES_GCM_CTX *gctx = ctx->cipher_data;
if (!iv && !key)
return 1;
if (key) {
aesni_set_encrypt_key(key, ctx->key_len * 8, &gctx->ks.ks);
CRYPTO_gcm128_init(&gctx->gcm, &gctx->ks, (block128_f) aesni_encrypt);
gctx->ctr = (ctr128_f) aesni_ctr32_encrypt_blocks;
/*
* If we have an iv can set it directly, otherwise use saved IV.
*/
if (iv == NULL && gctx->iv_set)
iv = gctx->iv;
if (iv) {
CRYPTO_gcm128_setiv(&gctx->gcm, iv, gctx->ivlen);
gctx->iv_set = 1;
}
gctx->key_set = 1;
} else {
/* If key set use IV, otherwise copy */
if (gctx->key_set)
CRYPTO_gcm128_setiv(&gctx->gcm, iv, gctx->ivlen);
else
memcpy(gctx->iv, iv, gctx->ivlen);
gctx->iv_set = 1;
gctx->iv_gen = 0;
}
return 1;
}
# define aesni_gcm_cipher aes_gcm_cipher
static int aesni_gcm_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
const unsigned char *in, size_t len);
static int aesni_xts_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key,
const unsigned char *iv, int enc)
{
EVP_AES_XTS_CTX *xctx = ctx->cipher_data;
if (!iv && !key)
return 1;
if (key) {
/* key_len is two AES keys */
if (enc) {
aesni_set_encrypt_key(key, ctx->key_len * 4, &xctx->ks1.ks);
xctx->xts.block1 = (block128_f) aesni_encrypt;
xctx->stream = aesni_xts_encrypt;
} else {
aesni_set_decrypt_key(key, ctx->key_len * 4, &xctx->ks1.ks);
xctx->xts.block1 = (block128_f) aesni_decrypt;
xctx->stream = aesni_xts_decrypt;
}
aesni_set_encrypt_key(key + ctx->key_len / 2,
ctx->key_len * 4, &xctx->ks2.ks);
xctx->xts.block2 = (block128_f) aesni_encrypt;
xctx->xts.key1 = &xctx->ks1;
}
if (iv) {
xctx->xts.key2 = &xctx->ks2;
memcpy(ctx->iv, iv, 16);
}
return 1;
}
# define aesni_xts_cipher aes_xts_cipher
static int aesni_xts_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
const unsigned char *in, size_t len);
static int aesni_ccm_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key,
const unsigned char *iv, int enc)
{
EVP_AES_CCM_CTX *cctx = ctx->cipher_data;
if (!iv && !key)
return 1;
if (key) {
aesni_set_encrypt_key(key, ctx->key_len * 8, &cctx->ks.ks);
CRYPTO_ccm128_init(&cctx->ccm, cctx->M, cctx->L,
&cctx->ks, (block128_f) aesni_encrypt);
cctx->str = enc ? (ccm128_f) aesni_ccm64_encrypt_blocks :
(ccm128_f) aesni_ccm64_decrypt_blocks;
cctx->key_set = 1;
}
if (iv) {
memcpy(ctx->iv, iv, 15 - cctx->L);
cctx->iv_set = 1;
}
return 1;
}
# define aesni_ccm_cipher aes_ccm_cipher
static int aesni_ccm_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
const unsigned char *in, size_t len);
# define BLOCK_CIPHER_generic(nid,keylen,blocksize,ivlen,nmode,mode,MODE,flags) \
static const EVP_CIPHER aesni_##keylen##_##mode = { \
nid##_##keylen##_##nmode,blocksize,keylen/8,ivlen, \
flags|EVP_CIPH_##MODE##_MODE, \
aesni_init_key, \
aesni_##mode##_cipher, \
NULL, \
sizeof(EVP_AES_KEY), \
NULL,NULL,NULL,NULL }; \
static const EVP_CIPHER aes_##keylen##_##mode = { \
nid##_##keylen##_##nmode,blocksize, \
keylen/8,ivlen, \
flags|EVP_CIPH_##MODE##_MODE, \
aes_init_key, \
aes_##mode##_cipher, \
NULL, \
sizeof(EVP_AES_KEY), \
NULL,NULL,NULL,NULL }; \
const EVP_CIPHER *EVP_aes_##keylen##_##mode(void) \
{ return AESNI_CAPABLE?&aesni_##keylen##_##mode:&aes_##keylen##_##mode; }
# define BLOCK_CIPHER_custom(nid,keylen,blocksize,ivlen,mode,MODE,flags) \
static const EVP_CIPHER aesni_##keylen##_##mode = { \
nid##_##keylen##_##mode,blocksize, \
(EVP_CIPH_##MODE##_MODE==EVP_CIPH_XTS_MODE?2:1)*keylen/8, ivlen, \
flags|EVP_CIPH_##MODE##_MODE, \
aesni_##mode##_init_key, \
aesni_##mode##_cipher, \
aes_##mode##_cleanup, \
sizeof(EVP_AES_##MODE##_CTX), \
NULL,NULL,aes_##mode##_ctrl,NULL }; \
static const EVP_CIPHER aes_##keylen##_##mode = { \
nid##_##keylen##_##mode,blocksize, \
(EVP_CIPH_##MODE##_MODE==EVP_CIPH_XTS_MODE?2:1)*keylen/8, ivlen, \
flags|EVP_CIPH_##MODE##_MODE, \
aes_##mode##_init_key, \
aes_##mode##_cipher, \
aes_##mode##_cleanup, \
sizeof(EVP_AES_##MODE##_CTX), \
NULL,NULL,aes_##mode##_ctrl,NULL }; \
const EVP_CIPHER *EVP_aes_##keylen##_##mode(void) \
{ return AESNI_CAPABLE?&aesni_##keylen##_##mode:&aes_##keylen##_##mode; }
# elif defined(AES_ASM) && (defined(__sparc) || defined(__sparc__))
# include "sparc_arch.h"
extern unsigned int OPENSSL_sparcv9cap_P[];
# define SPARC_AES_CAPABLE (OPENSSL_sparcv9cap_P[1] & CFR_AES)
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 specfic 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);
void aes128_t4_cbc_decrypt(const unsigned char *in, unsigned char *out,
size_t len, const AES_KEY *key,
unsigned char *ivec);
void aes192_t4_cbc_encrypt(const unsigned char *in, unsigned char *out,
size_t len, const AES_KEY *key,
unsigned char *ivec);
void aes192_t4_cbc_decrypt(const unsigned char *in, unsigned char *out,
size_t len, const AES_KEY *key,
unsigned char *ivec);
void aes256_t4_cbc_encrypt(const unsigned char *in, unsigned char *out,
size_t len, const AES_KEY *key,
unsigned char *ivec);
void aes256_t4_cbc_decrypt(const unsigned char *in, unsigned char *out,
size_t len, const AES_KEY *key,
unsigned char *ivec);
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);
static int aes_t4_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key,
const unsigned char *iv, int enc)
{
int ret, mode, bits;
EVP_AES_KEY *dat = (EVP_AES_KEY *) ctx->cipher_data;
mode = ctx->cipher->flags & EVP_CIPH_MODE;
bits = ctx->key_len * 8;
if ((mode == EVP_CIPH_ECB_MODE || mode == EVP_CIPH_CBC_MODE)
&& !enc) {
ret = 0;
aes_t4_set_decrypt_key(key, bits, ctx->cipher_data);
dat->block = (block128_f) aes_t4_decrypt;
switch (bits) {
case 128:
dat->stream.cbc = mode == EVP_CIPH_CBC_MODE ?
(cbc128_f) aes128_t4_cbc_decrypt : NULL;
break;
case 192:
dat->stream.cbc = mode == EVP_CIPH_CBC_MODE ?
(cbc128_f) aes192_t4_cbc_decrypt : NULL;
break;
case 256:
dat->stream.cbc = mode == EVP_CIPH_CBC_MODE ?
(cbc128_f) aes256_t4_cbc_decrypt : NULL;
break;
default:
ret = -1;
}
} else {
ret = 0;
aes_t4_set_encrypt_key(key, bits, ctx->cipher_data);
dat->block = (block128_f) aes_t4_encrypt;
switch (bits) {
case 128:
if (mode == EVP_CIPH_CBC_MODE)
dat->stream.cbc = (cbc128_f) aes128_t4_cbc_encrypt;
else if (mode == EVP_CIPH_CTR_MODE)
dat->stream.ctr = (ctr128_f) aes128_t4_ctr32_encrypt;
else
dat->stream.cbc = NULL;
break;
case 192:
if (mode == EVP_CIPH_CBC_MODE)
dat->stream.cbc = (cbc128_f) aes192_t4_cbc_encrypt;
else if (mode == EVP_CIPH_CTR_MODE)
dat->stream.ctr = (ctr128_f) aes192_t4_ctr32_encrypt;
else
dat->stream.cbc = NULL;
break;
case 256:
if (mode == EVP_CIPH_CBC_MODE)
dat->stream.cbc = (cbc128_f) aes256_t4_cbc_encrypt;
else if (mode == EVP_CIPH_CTR_MODE)
dat->stream.ctr = (ctr128_f) aes256_t4_ctr32_encrypt;
else
dat->stream.cbc = NULL;
break;
default:
ret = -1;
}
}
if (ret < 0) {
EVPerr(EVP_F_AES_T4_INIT_KEY, EVP_R_AES_KEY_SETUP_FAILED);
return 0;
}
return 1;
}
# define aes_t4_cbc_cipher aes_cbc_cipher
static int aes_t4_cbc_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
const unsigned char *in, size_t len);
# define aes_t4_ecb_cipher aes_ecb_cipher
static int aes_t4_ecb_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
const unsigned char *in, size_t len);
# define aes_t4_ofb_cipher aes_ofb_cipher
static int aes_t4_ofb_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
const unsigned char *in, size_t len);
# define aes_t4_cfb_cipher aes_cfb_cipher
static int aes_t4_cfb_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
const unsigned char *in, size_t len);
# define aes_t4_cfb8_cipher aes_cfb8_cipher
static int aes_t4_cfb8_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
const unsigned char *in, size_t len);
# define aes_t4_cfb1_cipher aes_cfb1_cipher
static int aes_t4_cfb1_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
const unsigned char *in, size_t len);
# define aes_t4_ctr_cipher aes_ctr_cipher
static int aes_t4_ctr_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
const unsigned char *in, size_t len);
static int aes_t4_gcm_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key,
const unsigned char *iv, int enc)
{
EVP_AES_GCM_CTX *gctx = ctx->cipher_data;
if (!iv && !key)
return 1;
if (key) {
int bits = ctx->key_len * 8;
aes_t4_set_encrypt_key(key, bits, &gctx->ks.ks);
CRYPTO_gcm128_init(&gctx->gcm, &gctx->ks,
(block128_f) aes_t4_encrypt);
switch (bits) {
case 128:
gctx->ctr = (ctr128_f) aes128_t4_ctr32_encrypt;
break;
case 192:
gctx->ctr = (ctr128_f) aes192_t4_ctr32_encrypt;
break;
case 256:
gctx->ctr = (ctr128_f) aes256_t4_ctr32_encrypt;
break;
default:
return 0;
}
/*
* If we have an iv can set it directly, otherwise use saved IV.
*/
if (iv == NULL && gctx->iv_set)
iv = gctx->iv;
if (iv) {
CRYPTO_gcm128_setiv(&gctx->gcm, iv, gctx->ivlen);
gctx->iv_set = 1;
}
gctx->key_set = 1;
} else {
/* If key set use IV, otherwise copy */
if (gctx->key_set)
CRYPTO_gcm128_setiv(&gctx->gcm, iv, gctx->ivlen);
else
memcpy(gctx->iv, iv, gctx->ivlen);
gctx->iv_set = 1;
gctx->iv_gen = 0;
}
return 1;
}
# define aes_t4_gcm_cipher aes_gcm_cipher
static int aes_t4_gcm_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
const unsigned char *in, size_t len);
static int aes_t4_xts_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key,
const unsigned char *iv, int enc)
{
EVP_AES_XTS_CTX *xctx = ctx->cipher_data;
if (!iv && !key)
return 1;
if (key) {
int bits = ctx->key_len * 4;
xctx->stream = NULL;
/* key_len is two AES keys */
if (enc) {
aes_t4_set_encrypt_key(key, bits, &xctx->ks1.ks);
xctx->xts.block1 = (block128_f) aes_t4_encrypt;
switch (bits) {
case 128:
xctx->stream = aes128_t4_xts_encrypt;
break;
# if 0 /* not yet */
case 192:
xctx->stream = aes192_t4_xts_encrypt;
break;
# endif
case 256:
xctx->stream = aes256_t4_xts_encrypt;
break;
default:
return 0;
}
} else {
aes_t4_set_decrypt_key(key, ctx->key_len * 4, &xctx->ks1.ks);
xctx->xts.block1 = (block128_f) aes_t4_decrypt;
switch (bits) {
case 128:
xctx->stream = aes128_t4_xts_decrypt;
break;
# if 0 /* not yet */
case 192:
xctx->stream = aes192_t4_xts_decrypt;
break;
# endif
case 256:
xctx->stream = aes256_t4_xts_decrypt;
break;
default:
return 0;
}
}
aes_t4_set_encrypt_key(key + ctx->key_len / 2,
ctx->key_len * 4, &xctx->ks2.ks);
xctx->xts.block2 = (block128_f) aes_t4_encrypt;
xctx->xts.key1 = &xctx->ks1;
}
if (iv) {
xctx->xts.key2 = &xctx->ks2;
memcpy(ctx->iv, iv, 16);
}
return 1;
}
# define aes_t4_xts_cipher aes_xts_cipher
static int aes_t4_xts_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
const unsigned char *in, size_t len);
static int aes_t4_ccm_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key,
const unsigned char *iv, int enc)
{
EVP_AES_CCM_CTX *cctx = ctx->cipher_data;
if (!iv && !key)
return 1;
if (key) {
int bits = ctx->key_len * 8;
aes_t4_set_encrypt_key(key, bits, &cctx->ks.ks);
CRYPTO_ccm128_init(&cctx->ccm, cctx->M, cctx->L,
&cctx->ks, (block128_f) aes_t4_encrypt);
# if 0 /* not yet */
switch (bits) {
case 128:
cctx->str = enc ? (ccm128_f) aes128_t4_ccm64_encrypt :
(ccm128_f) ae128_t4_ccm64_decrypt;
break;
case 192:
cctx->str = enc ? (ccm128_f) aes192_t4_ccm64_encrypt :
(ccm128_f) ae192_t4_ccm64_decrypt;
break;
case 256:
cctx->str = enc ? (ccm128_f) aes256_t4_ccm64_encrypt :
(ccm128_f) ae256_t4_ccm64_decrypt;
break;
default:
return 0;
}
# else
cctx->str = NULL;
# endif
cctx->key_set = 1;
}
if (iv) {
memcpy(ctx->iv, iv, 15 - cctx->L);
cctx->iv_set = 1;
}
return 1;
}
# define aes_t4_ccm_cipher aes_ccm_cipher
static int aes_t4_ccm_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
const unsigned char *in, size_t len);
# define BLOCK_CIPHER_generic(nid,keylen,blocksize,ivlen,nmode,mode,MODE,flags) \
static const EVP_CIPHER aes_t4_##keylen##_##mode = { \
nid##_##keylen##_##nmode,blocksize,keylen/8,ivlen, \
flags|EVP_CIPH_##MODE##_MODE, \
aes_t4_init_key, \
aes_t4_##mode##_cipher, \
NULL, \
sizeof(EVP_AES_KEY), \
NULL,NULL,NULL,NULL }; \
static const EVP_CIPHER aes_##keylen##_##mode = { \
nid##_##keylen##_##nmode,blocksize, \
keylen/8,ivlen, \
flags|EVP_CIPH_##MODE##_MODE, \
aes_init_key, \
aes_##mode##_cipher, \
NULL, \
sizeof(EVP_AES_KEY), \
NULL,NULL,NULL,NULL }; \
const EVP_CIPHER *EVP_aes_##keylen##_##mode(void) \
{ return SPARC_AES_CAPABLE?&aes_t4_##keylen##_##mode:&aes_##keylen##_##mode; }
# define BLOCK_CIPHER_custom(nid,keylen,blocksize,ivlen,mode,MODE,flags) \
static const EVP_CIPHER aes_t4_##keylen##_##mode = { \
nid##_##keylen##_##mode,blocksize, \
(EVP_CIPH_##MODE##_MODE==EVP_CIPH_XTS_MODE?2:1)*keylen/8, ivlen, \
flags|EVP_CIPH_##MODE##_MODE, \
aes_t4_##mode##_init_key, \
aes_t4_##mode##_cipher, \
aes_##mode##_cleanup, \
sizeof(EVP_AES_##MODE##_CTX), \
NULL,NULL,aes_##mode##_ctrl,NULL }; \
static const EVP_CIPHER aes_##keylen##_##mode = { \
nid##_##keylen##_##mode,blocksize, \
(EVP_CIPH_##MODE##_MODE==EVP_CIPH_XTS_MODE?2:1)*keylen/8, ivlen, \
flags|EVP_CIPH_##MODE##_MODE, \
aes_##mode##_init_key, \
aes_##mode##_cipher, \
aes_##mode##_cleanup, \
sizeof(EVP_AES_##MODE##_CTX), \
NULL,NULL,aes_##mode##_ctrl,NULL }; \
const EVP_CIPHER *EVP_aes_##keylen##_##mode(void) \
{ return SPARC_AES_CAPABLE?&aes_t4_##keylen##_##mode:&aes_##keylen##_##mode; }
# else
# define BLOCK_CIPHER_generic(nid,keylen,blocksize,ivlen,nmode,mode,MODE,flags) \
static const EVP_CIPHER aes_##keylen##_##mode = { \
nid##_##keylen##_##nmode,blocksize,keylen/8,ivlen, \
flags|EVP_CIPH_##MODE##_MODE, \
aes_init_key, \
aes_##mode##_cipher, \
NULL, \
sizeof(EVP_AES_KEY), \
NULL,NULL,NULL,NULL }; \
const EVP_CIPHER *EVP_aes_##keylen##_##mode(void) \
{ return &aes_##keylen##_##mode; }
# define BLOCK_CIPHER_custom(nid,keylen,blocksize,ivlen,mode,MODE,flags) \
static const EVP_CIPHER aes_##keylen##_##mode = { \
nid##_##keylen##_##mode,blocksize, \
(EVP_CIPH_##MODE##_MODE==EVP_CIPH_XTS_MODE?2:1)*keylen/8, ivlen, \
flags|EVP_CIPH_##MODE##_MODE, \
aes_##mode##_init_key, \
aes_##mode##_cipher, \
aes_##mode##_cleanup, \
sizeof(EVP_AES_##MODE##_CTX), \
NULL,NULL,aes_##mode##_ctrl,NULL }; \
const EVP_CIPHER *EVP_aes_##keylen##_##mode(void) \
{ return &aes_##keylen##_##mode; }
# endif
# if defined(OPENSSL_CPUID_OBJ) && (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
# 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_ctr32_encrypt_blocks aes_v8_ctr32_encrypt_blocks
# endif
# 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_ctr32_encrypt_blocks(const unsigned char *in, unsigned char *out,
size_t len, const AES_KEY *key,
const unsigned char ivec[16]);
# endif
# define BLOCK_CIPHER_generic_pack(nid,keylen,flags) \
BLOCK_CIPHER_generic(nid,keylen,16,16,cbc,cbc,CBC,flags|EVP_CIPH_FLAG_DEFAULT_ASN1) \
BLOCK_CIPHER_generic(nid,keylen,16,0,ecb,ecb,ECB,flags|EVP_CIPH_FLAG_DEFAULT_ASN1) \
BLOCK_CIPHER_generic(nid,keylen,1,16,ofb128,ofb,OFB,flags|EVP_CIPH_FLAG_DEFAULT_ASN1) \
BLOCK_CIPHER_generic(nid,keylen,1,16,cfb128,cfb,CFB,flags|EVP_CIPH_FLAG_DEFAULT_ASN1) \
BLOCK_CIPHER_generic(nid,keylen,1,16,cfb1,cfb1,CFB,flags) \
BLOCK_CIPHER_generic(nid,keylen,1,16,cfb8,cfb8,CFB,flags) \
BLOCK_CIPHER_generic(nid,keylen,1,16,ctr,ctr,CTR,flags)
static int aes_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key,
const unsigned char *iv, int enc)
{
int ret, mode;
EVP_AES_KEY *dat = (EVP_AES_KEY *) ctx->cipher_data;
mode = ctx->cipher->flags & EVP_CIPH_MODE;
if ((mode == EVP_CIPH_ECB_MODE || mode == EVP_CIPH_CBC_MODE)
&& !enc)
# ifdef HWAES_CAPABLE
if (HWAES_CAPABLE) {
ret = HWAES_set_decrypt_key(key, ctx->key_len * 8, &dat->ks.ks);
dat->block = (block128_f) HWAES_decrypt;
dat->stream.cbc = NULL;
# ifdef HWAES_cbc_encrypt
if (mode == EVP_CIPH_CBC_MODE)
dat->stream.cbc = (cbc128_f) HWAES_cbc_encrypt;
# endif
} else
# endif
# ifdef BSAES_CAPABLE
if (BSAES_CAPABLE && mode == EVP_CIPH_CBC_MODE) {
ret = AES_set_decrypt_key(key, ctx->key_len * 8, &dat->ks.ks);
dat->block = (block128_f) AES_decrypt;
dat->stream.cbc = (cbc128_f) bsaes_cbc_encrypt;
} else
# endif
# ifdef VPAES_CAPABLE
if (VPAES_CAPABLE) {
ret = vpaes_set_decrypt_key(key, ctx->key_len * 8, &dat->ks.ks);
dat->block = (block128_f) vpaes_decrypt;
dat->stream.cbc = mode == EVP_CIPH_CBC_MODE ?
(cbc128_f) vpaes_cbc_encrypt : NULL;
} else
# endif
{
ret = AES_set_decrypt_key(key, ctx->key_len * 8, &dat->ks.ks);
dat->block = (block128_f) AES_decrypt;
dat->stream.cbc = mode == EVP_CIPH_CBC_MODE ?
(cbc128_f) AES_cbc_encrypt : NULL;
} else
# ifdef HWAES_CAPABLE
if (HWAES_CAPABLE) {
ret = HWAES_set_encrypt_key(key, ctx->key_len * 8, &dat->ks.ks);
dat->block = (block128_f) HWAES_encrypt;
dat->stream.cbc = NULL;
# ifdef HWAES_cbc_encrypt
if (mode == EVP_CIPH_CBC_MODE)
dat->stream.cbc = (cbc128_f) HWAES_cbc_encrypt;
else
# endif
# ifdef HWAES_ctr32_encrypt_blocks
if (mode == EVP_CIPH_CTR_MODE)
dat->stream.ctr = (ctr128_f) HWAES_ctr32_encrypt_blocks;
else
# endif
(void)0; /* terminate potentially open 'else' */
} else
# endif
# ifdef BSAES_CAPABLE
if (BSAES_CAPABLE && mode == EVP_CIPH_CTR_MODE) {
ret = AES_set_encrypt_key(key, ctx->key_len * 8, &dat->ks.ks);
dat->block = (block128_f) AES_encrypt;
dat->stream.ctr = (ctr128_f) bsaes_ctr32_encrypt_blocks;
} else
# endif
# ifdef VPAES_CAPABLE
if (VPAES_CAPABLE) {
ret = vpaes_set_encrypt_key(key, ctx->key_len * 8, &dat->ks.ks);
dat->block = (block128_f) vpaes_encrypt;
dat->stream.cbc = mode == EVP_CIPH_CBC_MODE ?
(cbc128_f) vpaes_cbc_encrypt : NULL;
} else
# endif
{
ret = AES_set_encrypt_key(key, ctx->key_len * 8, &dat->ks.ks);
dat->block = (block128_f) AES_encrypt;
dat->stream.cbc = mode == EVP_CIPH_CBC_MODE ?
(cbc128_f) AES_cbc_encrypt : NULL;
# ifdef AES_CTR_ASM
if (mode == EVP_CIPH_CTR_MODE)
dat->stream.ctr = (ctr128_f) AES_ctr32_encrypt;
# endif
}
if (ret < 0) {
EVPerr(EVP_F_AES_INIT_KEY, EVP_R_AES_KEY_SETUP_FAILED);
return 0;
}
return 1;
}
static int aes_cbc_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
const unsigned char *in, size_t len)
{
EVP_AES_KEY *dat = (EVP_AES_KEY *) ctx->cipher_data;
if (dat->stream.cbc)
(*dat->stream.cbc) (in, out, len, &dat->ks, ctx->iv, ctx->encrypt);
else if (ctx->encrypt)
CRYPTO_cbc128_encrypt(in, out, len, &dat->ks, ctx->iv, dat->block);
else
CRYPTO_cbc128_decrypt(in, out, len, &dat->ks, ctx->iv, dat->block);
return 1;
}
static int aes_ecb_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
const unsigned char *in, size_t len)
{
size_t bl = ctx->cipher->block_size;
size_t i;
EVP_AES_KEY *dat = (EVP_AES_KEY *) ctx->cipher_data;
if (len < bl)
return 1;
for (i = 0, len -= bl; i <= len; i += bl)
(*dat->block) (in + i, out + i, &dat->ks);
return 1;
}
static int aes_ofb_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
const unsigned char *in, size_t len)
{
EVP_AES_KEY *dat = (EVP_AES_KEY *) ctx->cipher_data;
CRYPTO_ofb128_encrypt(in, out, len, &dat->ks,
ctx->iv, &ctx->num, dat->block);
return 1;
}
static int aes_cfb_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
const unsigned char *in, size_t len)
{
EVP_AES_KEY *dat = (EVP_AES_KEY *) ctx->cipher_data;
CRYPTO_cfb128_encrypt(in, out, len, &dat->ks,
ctx->iv, &ctx->num, ctx->encrypt, dat->block);
return 1;
}
static int aes_cfb8_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
const unsigned char *in, size_t len)
{
EVP_AES_KEY *dat = (EVP_AES_KEY *) ctx->cipher_data;
CRYPTO_cfb128_8_encrypt(in, out, len, &dat->ks,
ctx->iv, &ctx->num, ctx->encrypt, dat->block);
return 1;
}
static int aes_cfb1_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
const unsigned char *in, size_t len)
{
EVP_AES_KEY *dat = (EVP_AES_KEY *) ctx->cipher_data;
if (ctx->flags & EVP_CIPH_FLAG_LENGTH_BITS) {
CRYPTO_cfb128_1_encrypt(in, out, len, &dat->ks,
ctx->iv, &ctx->num, ctx->encrypt, dat->block);
return 1;
}
while (len >= MAXBITCHUNK) {
CRYPTO_cfb128_1_encrypt(in, out, MAXBITCHUNK * 8, &dat->ks,
ctx->iv, &ctx->num, ctx->encrypt, dat->block);
len -= MAXBITCHUNK;
+ out += MAXBITCHUNK;
+ in += MAXBITCHUNK;
}
if (len)
CRYPTO_cfb128_1_encrypt(in, out, len * 8, &dat->ks,
ctx->iv, &ctx->num, ctx->encrypt, dat->block);
return 1;
}
static int aes_ctr_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
const unsigned char *in, size_t len)
{
unsigned int num = ctx->num;
EVP_AES_KEY *dat = (EVP_AES_KEY *) ctx->cipher_data;
if (dat->stream.ctr)
CRYPTO_ctr128_encrypt_ctr32(in, out, len, &dat->ks,
ctx->iv, ctx->buf, &num, dat->stream.ctr);
else
CRYPTO_ctr128_encrypt(in, out, len, &dat->ks,
ctx->iv, ctx->buf, &num, dat->block);
ctx->num = (size_t)num;
return 1;
}
BLOCK_CIPHER_generic_pack(NID_aes, 128, EVP_CIPH_FLAG_FIPS)
BLOCK_CIPHER_generic_pack(NID_aes, 192, EVP_CIPH_FLAG_FIPS)
BLOCK_CIPHER_generic_pack(NID_aes, 256, EVP_CIPH_FLAG_FIPS)
static int aes_gcm_cleanup(EVP_CIPHER_CTX *c)
{
EVP_AES_GCM_CTX *gctx = c->cipher_data;
if (gctx == NULL)
return 0;
OPENSSL_cleanse(&gctx->gcm, sizeof(gctx->gcm));
if (gctx->iv != c->iv)
OPENSSL_free(gctx->iv);
return 1;
}
/* increment counter (64-bit int) by 1 */
static void ctr64_inc(unsigned char *counter)
{
int n = 8;
unsigned char c;
do {
--n;
c = counter[n];
++c;
counter[n] = c;
if (c)
return;
} while (n);
}
static int aes_gcm_ctrl(EVP_CIPHER_CTX *c, int type, int arg, void *ptr)
{
EVP_AES_GCM_CTX *gctx = c->cipher_data;
switch (type) {
case EVP_CTRL_INIT:
gctx->key_set = 0;
gctx->iv_set = 0;
gctx->ivlen = c->cipher->iv_len;
gctx->iv = c->iv;
gctx->taglen = -1;
gctx->iv_gen = 0;
gctx->tls_aad_len = -1;
return 1;
case EVP_CTRL_GCM_SET_IVLEN:
if (arg <= 0)
return 0;
/* Allocate memory for IV if needed */
if ((arg > EVP_MAX_IV_LENGTH) && (arg > gctx->ivlen)) {
if (gctx->iv != c->iv)
OPENSSL_free(gctx->iv);
gctx->iv = OPENSSL_malloc(arg);
if (!gctx->iv)
return 0;
}
gctx->ivlen = arg;
return 1;
case EVP_CTRL_GCM_SET_TAG:
if (arg <= 0 || arg > 16 || c->encrypt)
return 0;
memcpy(c->buf, ptr, arg);
gctx->taglen = arg;
return 1;
case EVP_CTRL_GCM_GET_TAG:
if (arg <= 0 || arg > 16 || !c->encrypt || gctx->taglen < 0)
return 0;
memcpy(ptr, c->buf, arg);
return 1;
case EVP_CTRL_GCM_SET_IV_FIXED:
/* Special case: -1 length restores whole IV */
if (arg == -1) {
memcpy(gctx->iv, ptr, gctx->ivlen);
gctx->iv_gen = 1;
return 1;
}
/*
* Fixed field must be at least 4 bytes and invocation field at least
* 8.
*/
if ((arg < 4) || (gctx->ivlen - arg) < 8)
return 0;
if (arg)
memcpy(gctx->iv, ptr, arg);
if (c->encrypt && RAND_bytes(gctx->iv + arg, gctx->ivlen - arg) <= 0)
return 0;
gctx->iv_gen = 1;
return 1;
case EVP_CTRL_GCM_IV_GEN:
if (gctx->iv_gen == 0 || gctx->key_set == 0)
return 0;
CRYPTO_gcm128_setiv(&gctx->gcm, gctx->iv, gctx->ivlen);
if (arg <= 0 || arg > gctx->ivlen)
arg = gctx->ivlen;
memcpy(ptr, gctx->iv + gctx->ivlen - arg, arg);
/*
* Invocation field will be at least 8 bytes in size and so no need
* to check wrap around or increment more than last 8 bytes.
*/
ctr64_inc(gctx->iv + gctx->ivlen - 8);
gctx->iv_set = 1;
return 1;
case EVP_CTRL_GCM_SET_IV_INV:
if (gctx->iv_gen == 0 || gctx->key_set == 0 || c->encrypt)
return 0;
memcpy(gctx->iv + gctx->ivlen - arg, ptr, arg);
CRYPTO_gcm128_setiv(&gctx->gcm, gctx->iv, gctx->ivlen);
gctx->iv_set = 1;
return 1;
case EVP_CTRL_AEAD_TLS1_AAD:
/* Save the AAD for later use */
if (arg != EVP_AEAD_TLS1_AAD_LEN)
return 0;
memcpy(c->buf, ptr, arg);
gctx->tls_aad_len = arg;
{
unsigned int len = c->buf[arg - 2] << 8 | c->buf[arg - 1];
/* Correct length for explicit IV */
if (len < EVP_GCM_TLS_EXPLICIT_IV_LEN)
return 0;
len -= EVP_GCM_TLS_EXPLICIT_IV_LEN;
/* If decrypting correct for tag too */
if (!c->encrypt) {
if (len < EVP_GCM_TLS_TAG_LEN)
return 0;
len -= EVP_GCM_TLS_TAG_LEN;
}
c->buf[arg - 2] = len >> 8;
c->buf[arg - 1] = len & 0xff;
}
/* Extra padding: tag appended to record */
return EVP_GCM_TLS_TAG_LEN;
case EVP_CTRL_COPY:
{
EVP_CIPHER_CTX *out = ptr;
EVP_AES_GCM_CTX *gctx_out = out->cipher_data;
if (gctx->gcm.key) {
if (gctx->gcm.key != &gctx->ks)
return 0;
gctx_out->gcm.key = &gctx_out->ks;
}
if (gctx->iv == c->iv)
gctx_out->iv = out->iv;
else {
gctx_out->iv = OPENSSL_malloc(gctx->ivlen);
if (!gctx_out->iv)
return 0;
memcpy(gctx_out->iv, gctx->iv, gctx->ivlen);
}
return 1;
}
default:
return -1;
}
}
static int aes_gcm_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key,
const unsigned char *iv, int enc)
{
EVP_AES_GCM_CTX *gctx = ctx->cipher_data;
if (!iv && !key)
return 1;
if (key) {
do {
# ifdef HWAES_CAPABLE
if (HWAES_CAPABLE) {
HWAES_set_encrypt_key(key, ctx->key_len * 8, &gctx->ks.ks);
CRYPTO_gcm128_init(&gctx->gcm, &gctx->ks,
(block128_f) HWAES_encrypt);
# ifdef HWAES_ctr32_encrypt_blocks
gctx->ctr = (ctr128_f) HWAES_ctr32_encrypt_blocks;
# else
gctx->ctr = NULL;
# endif
break;
} else
# endif
# ifdef BSAES_CAPABLE
if (BSAES_CAPABLE) {
AES_set_encrypt_key(key, ctx->key_len * 8, &gctx->ks.ks);
CRYPTO_gcm128_init(&gctx->gcm, &gctx->ks,
(block128_f) AES_encrypt);
gctx->ctr = (ctr128_f) bsaes_ctr32_encrypt_blocks;
break;
} else
# endif
# ifdef VPAES_CAPABLE
if (VPAES_CAPABLE) {
vpaes_set_encrypt_key(key, ctx->key_len * 8, &gctx->ks.ks);
CRYPTO_gcm128_init(&gctx->gcm, &gctx->ks,
(block128_f) vpaes_encrypt);
gctx->ctr = NULL;
break;
} else
# endif
(void)0; /* terminate potentially open 'else' */
AES_set_encrypt_key(key, ctx->key_len * 8, &gctx->ks.ks);
CRYPTO_gcm128_init(&gctx->gcm, &gctx->ks,
(block128_f) AES_encrypt);
# ifdef AES_CTR_ASM
gctx->ctr = (ctr128_f) AES_ctr32_encrypt;
# else
gctx->ctr = NULL;
# endif
} while (0);
/*
* If we have an iv can set it directly, otherwise use saved IV.
*/
if (iv == NULL && gctx->iv_set)
iv = gctx->iv;
if (iv) {
CRYPTO_gcm128_setiv(&gctx->gcm, iv, gctx->ivlen);
gctx->iv_set = 1;
}
gctx->key_set = 1;
} else {
/* If key set use IV, otherwise copy */
if (gctx->key_set)
CRYPTO_gcm128_setiv(&gctx->gcm, iv, gctx->ivlen);
else
memcpy(gctx->iv, iv, gctx->ivlen);
gctx->iv_set = 1;
gctx->iv_gen = 0;
}
return 1;
}
/*
* Handle TLS GCM packet format. This consists of the last portion of the IV
* followed by the payload and finally the tag. On encrypt generate IV,
* encrypt payload and write the tag. On verify retrieve IV, decrypt payload
* and verify tag.
*/
static int aes_gcm_tls_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
const unsigned char *in, size_t len)
{
EVP_AES_GCM_CTX *gctx = ctx->cipher_data;
int rv = -1;
/* Encrypt/decrypt must be performed in place */
if (out != in
|| len < (EVP_GCM_TLS_EXPLICIT_IV_LEN + EVP_GCM_TLS_TAG_LEN))
return -1;
/*
* Set IV from start of buffer or generate IV and write to start of
* buffer.
*/
if (EVP_CIPHER_CTX_ctrl(ctx, ctx->encrypt ?
EVP_CTRL_GCM_IV_GEN : EVP_CTRL_GCM_SET_IV_INV,
EVP_GCM_TLS_EXPLICIT_IV_LEN, out) <= 0)
goto err;
/* Use saved AAD */
if (CRYPTO_gcm128_aad(&gctx->gcm, ctx->buf, gctx->tls_aad_len))
goto err;
/* Fix buffer and length to point to payload */
in += EVP_GCM_TLS_EXPLICIT_IV_LEN;
out += EVP_GCM_TLS_EXPLICIT_IV_LEN;
len -= EVP_GCM_TLS_EXPLICIT_IV_LEN + EVP_GCM_TLS_TAG_LEN;
if (ctx->encrypt) {
/* Encrypt payload */
if (gctx->ctr) {
size_t bulk = 0;
# if defined(AES_GCM_ASM)
if (len >= 32 && AES_GCM_ASM(gctx)) {
if (CRYPTO_gcm128_encrypt(&gctx->gcm, NULL, NULL, 0))
return -1;
bulk = AES_gcm_encrypt(in, out, len,
gctx->gcm.key,
gctx->gcm.Yi.c, gctx->gcm.Xi.u);
gctx->gcm.len.u[1] += bulk;
}
# endif
if (CRYPTO_gcm128_encrypt_ctr32(&gctx->gcm,
in + bulk,
out + bulk,
len - bulk, gctx->ctr))
goto err;
} else {
size_t bulk = 0;
# if defined(AES_GCM_ASM2)
if (len >= 32 && AES_GCM_ASM2(gctx)) {
if (CRYPTO_gcm128_encrypt(&gctx->gcm, NULL, NULL, 0))
return -1;
bulk = AES_gcm_encrypt(in, out, len,
gctx->gcm.key,
gctx->gcm.Yi.c, gctx->gcm.Xi.u);
gctx->gcm.len.u[1] += bulk;
}
# endif
if (CRYPTO_gcm128_encrypt(&gctx->gcm,
in + bulk, out + bulk, len - bulk))
goto err;
}
out += len;
/* Finally write tag */
CRYPTO_gcm128_tag(&gctx->gcm, out, EVP_GCM_TLS_TAG_LEN);
rv = len + EVP_GCM_TLS_EXPLICIT_IV_LEN + EVP_GCM_TLS_TAG_LEN;
} else {
/* Decrypt */
if (gctx->ctr) {
size_t bulk = 0;
# if defined(AES_GCM_ASM)
if (len >= 16 && AES_GCM_ASM(gctx)) {
if (CRYPTO_gcm128_decrypt(&gctx->gcm, NULL, NULL, 0))
return -1;
bulk = AES_gcm_decrypt(in, out, len,
gctx->gcm.key,
gctx->gcm.Yi.c, gctx->gcm.Xi.u);
gctx->gcm.len.u[1] += bulk;
}
# endif
if (CRYPTO_gcm128_decrypt_ctr32(&gctx->gcm,
in + bulk,
out + bulk,
len - bulk, gctx->ctr))
goto err;
} else {
size_t bulk = 0;
# if defined(AES_GCM_ASM2)
if (len >= 16 && AES_GCM_ASM2(gctx)) {
if (CRYPTO_gcm128_decrypt(&gctx->gcm, NULL, NULL, 0))
return -1;
bulk = AES_gcm_decrypt(in, out, len,
gctx->gcm.key,
gctx->gcm.Yi.c, gctx->gcm.Xi.u);
gctx->gcm.len.u[1] += bulk;
}
# endif
if (CRYPTO_gcm128_decrypt(&gctx->gcm,
in + bulk, out + bulk, len - bulk))
goto err;
}
/* Retrieve tag */
CRYPTO_gcm128_tag(&gctx->gcm, ctx->buf, EVP_GCM_TLS_TAG_LEN);
/* If tag mismatch wipe buffer */
if (CRYPTO_memcmp(ctx->buf, in + len, EVP_GCM_TLS_TAG_LEN)) {
OPENSSL_cleanse(out, len);
goto err;
}
rv = len;
}
err:
gctx->iv_set = 0;
gctx->tls_aad_len = -1;
return rv;
}
static int aes_gcm_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
const unsigned char *in, size_t len)
{
EVP_AES_GCM_CTX *gctx = ctx->cipher_data;
/* If not set up, return error */
if (!gctx->key_set)
return -1;
if (gctx->tls_aad_len >= 0)
return aes_gcm_tls_cipher(ctx, out, in, len);
if (!gctx->iv_set)
return -1;
if (in) {
if (out == NULL) {
if (CRYPTO_gcm128_aad(&gctx->gcm, in, len))
return -1;
} else if (ctx->encrypt) {
if (gctx->ctr) {
size_t bulk = 0;
# if defined(AES_GCM_ASM)
if (len >= 32 && AES_GCM_ASM(gctx)) {
size_t res = (16 - gctx->gcm.mres) % 16;
if (CRYPTO_gcm128_encrypt(&gctx->gcm, in, out, res))
return -1;
bulk = AES_gcm_encrypt(in + res,
out + res, len - res,
gctx->gcm.key, gctx->gcm.Yi.c,
gctx->gcm.Xi.u);
gctx->gcm.len.u[1] += bulk;
bulk += res;
}
# endif
if (CRYPTO_gcm128_encrypt_ctr32(&gctx->gcm,
in + bulk,
out + bulk,
len - bulk, gctx->ctr))
return -1;
} else {
size_t bulk = 0;
# if defined(AES_GCM_ASM2)
if (len >= 32 && AES_GCM_ASM2(gctx)) {
size_t res = (16 - gctx->gcm.mres) % 16;
if (CRYPTO_gcm128_encrypt(&gctx->gcm, in, out, res))
return -1;
bulk = AES_gcm_encrypt(in + res,
out + res, len - res,
gctx->gcm.key, gctx->gcm.Yi.c,
gctx->gcm.Xi.u);
gctx->gcm.len.u[1] += bulk;
bulk += res;
}
# endif
if (CRYPTO_gcm128_encrypt(&gctx->gcm,
in + bulk, out + bulk, len - bulk))
return -1;
}
} else {
if (gctx->ctr) {
size_t bulk = 0;
# if defined(AES_GCM_ASM)
if (len >= 16 && AES_GCM_ASM(gctx)) {
size_t res = (16 - gctx->gcm.mres) % 16;
if (CRYPTO_gcm128_decrypt(&gctx->gcm, in, out, res))
return -1;
bulk = AES_gcm_decrypt(in + res,
out + res, len - res,
gctx->gcm.key,
gctx->gcm.Yi.c, gctx->gcm.Xi.u);
gctx->gcm.len.u[1] += bulk;
bulk += res;
}
# endif
if (CRYPTO_gcm128_decrypt_ctr32(&gctx->gcm,
in + bulk,
out + bulk,
len - bulk, gctx->ctr))
return -1;
} else {
size_t bulk = 0;
# if defined(AES_GCM_ASM2)
if (len >= 16 && AES_GCM_ASM2(gctx)) {
size_t res = (16 - gctx->gcm.mres) % 16;
if (CRYPTO_gcm128_decrypt(&gctx->gcm, in, out, res))
return -1;
bulk = AES_gcm_decrypt(in + res,
out + res, len - res,
gctx->gcm.key,
gctx->gcm.Yi.c, gctx->gcm.Xi.u);
gctx->gcm.len.u[1] += bulk;
bulk += res;
}
# endif
if (CRYPTO_gcm128_decrypt(&gctx->gcm,
in + bulk, out + bulk, len - bulk))
return -1;
}
}
return len;
} else {
if (!ctx->encrypt) {
if (gctx->taglen < 0)
return -1;
if (CRYPTO_gcm128_finish(&gctx->gcm, ctx->buf, gctx->taglen) != 0)
return -1;
gctx->iv_set = 0;
return 0;
}
CRYPTO_gcm128_tag(&gctx->gcm, ctx->buf, 16);
gctx->taglen = 16;
/* Don't reuse the IV */
gctx->iv_set = 0;
return 0;
}
}
# define CUSTOM_FLAGS (EVP_CIPH_FLAG_DEFAULT_ASN1 \
| EVP_CIPH_CUSTOM_IV | EVP_CIPH_FLAG_CUSTOM_CIPHER \
| EVP_CIPH_ALWAYS_CALL_INIT | EVP_CIPH_CTRL_INIT \
| EVP_CIPH_CUSTOM_COPY)
BLOCK_CIPHER_custom(NID_aes, 128, 1, 12, gcm, GCM,
EVP_CIPH_FLAG_FIPS | EVP_CIPH_FLAG_AEAD_CIPHER |
CUSTOM_FLAGS)
BLOCK_CIPHER_custom(NID_aes, 192, 1, 12, gcm, GCM,
EVP_CIPH_FLAG_FIPS | EVP_CIPH_FLAG_AEAD_CIPHER |
CUSTOM_FLAGS)
BLOCK_CIPHER_custom(NID_aes, 256, 1, 12, gcm, GCM,
EVP_CIPH_FLAG_FIPS | EVP_CIPH_FLAG_AEAD_CIPHER |
CUSTOM_FLAGS)
static int aes_xts_ctrl(EVP_CIPHER_CTX *c, int type, int arg, void *ptr)
{
EVP_AES_XTS_CTX *xctx = c->cipher_data;
if (type == EVP_CTRL_COPY) {
EVP_CIPHER_CTX *out = ptr;
EVP_AES_XTS_CTX *xctx_out = out->cipher_data;
if (xctx->xts.key1) {
if (xctx->xts.key1 != &xctx->ks1)
return 0;
xctx_out->xts.key1 = &xctx_out->ks1;
}
if (xctx->xts.key2) {
if (xctx->xts.key2 != &xctx->ks2)
return 0;
xctx_out->xts.key2 = &xctx_out->ks2;
}
return 1;
} else if (type != EVP_CTRL_INIT)
return -1;
/* key1 and key2 are used as an indicator both key and IV are set */
xctx->xts.key1 = NULL;
xctx->xts.key2 = NULL;
return 1;
}
static int aes_xts_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key,
const unsigned char *iv, int enc)
{
EVP_AES_XTS_CTX *xctx = ctx->cipher_data;
if (!iv && !key)
return 1;
if (key)
do {
# ifdef AES_XTS_ASM
xctx->stream = enc ? AES_xts_encrypt : AES_xts_decrypt;
# else
xctx->stream = NULL;
# endif
/* key_len is two AES keys */
# ifdef HWAES_CAPABLE
if (HWAES_CAPABLE) {
if (enc) {
HWAES_set_encrypt_key(key, ctx->key_len * 4,
&xctx->ks1.ks);
xctx->xts.block1 = (block128_f) HWAES_encrypt;
} else {
HWAES_set_decrypt_key(key, ctx->key_len * 4,
&xctx->ks1.ks);
xctx->xts.block1 = (block128_f) HWAES_decrypt;
}
HWAES_set_encrypt_key(key + ctx->key_len / 2,
ctx->key_len * 4, &xctx->ks2.ks);
xctx->xts.block2 = (block128_f) HWAES_encrypt;
xctx->xts.key1 = &xctx->ks1;
break;
} else
# endif
# ifdef BSAES_CAPABLE
if (BSAES_CAPABLE)
xctx->stream = enc ? bsaes_xts_encrypt : bsaes_xts_decrypt;
else
# endif
# ifdef VPAES_CAPABLE
if (VPAES_CAPABLE) {
if (enc) {
vpaes_set_encrypt_key(key, ctx->key_len * 4,
&xctx->ks1.ks);
xctx->xts.block1 = (block128_f) vpaes_encrypt;
} else {
vpaes_set_decrypt_key(key, ctx->key_len * 4,
&xctx->ks1.ks);
xctx->xts.block1 = (block128_f) vpaes_decrypt;
}
vpaes_set_encrypt_key(key + ctx->key_len / 2,
ctx->key_len * 4, &xctx->ks2.ks);
xctx->xts.block2 = (block128_f) vpaes_encrypt;
xctx->xts.key1 = &xctx->ks1;
break;
} else
# endif
(void)0; /* terminate potentially open 'else' */
if (enc) {
AES_set_encrypt_key(key, ctx->key_len * 4, &xctx->ks1.ks);
xctx->xts.block1 = (block128_f) AES_encrypt;
} else {
AES_set_decrypt_key(key, ctx->key_len * 4, &xctx->ks1.ks);
xctx->xts.block1 = (block128_f) AES_decrypt;
}
AES_set_encrypt_key(key + ctx->key_len / 2,
ctx->key_len * 4, &xctx->ks2.ks);
xctx->xts.block2 = (block128_f) AES_encrypt;
xctx->xts.key1 = &xctx->ks1;
} while (0);
if (iv) {
xctx->xts.key2 = &xctx->ks2;
memcpy(ctx->iv, iv, 16);
}
return 1;
}
static int aes_xts_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
const unsigned char *in, size_t len)
{
EVP_AES_XTS_CTX *xctx = ctx->cipher_data;
if (!xctx->xts.key1 || !xctx->xts.key2)
return 0;
if (!out || !in || len < AES_BLOCK_SIZE)
return 0;
if (xctx->stream)
(*xctx->stream) (in, out, len,
xctx->xts.key1, xctx->xts.key2, ctx->iv);
else if (CRYPTO_xts128_encrypt(&xctx->xts, ctx->iv, in, out, len,
ctx->encrypt))
return 0;
return 1;
}
# define aes_xts_cleanup NULL
# define XTS_FLAGS (EVP_CIPH_FLAG_DEFAULT_ASN1 | EVP_CIPH_CUSTOM_IV \
| EVP_CIPH_ALWAYS_CALL_INIT | EVP_CIPH_CTRL_INIT \
| EVP_CIPH_CUSTOM_COPY)
BLOCK_CIPHER_custom(NID_aes, 128, 1, 16, xts, XTS,
EVP_CIPH_FLAG_FIPS | XTS_FLAGS)
BLOCK_CIPHER_custom(NID_aes, 256, 1, 16, xts, XTS,
EVP_CIPH_FLAG_FIPS | XTS_FLAGS)
static int aes_ccm_ctrl(EVP_CIPHER_CTX *c, int type, int arg, void *ptr)
{
EVP_AES_CCM_CTX *cctx = c->cipher_data;
switch (type) {
case EVP_CTRL_INIT:
cctx->key_set = 0;
cctx->iv_set = 0;
cctx->L = 8;
cctx->M = 12;
cctx->tag_set = 0;
cctx->len_set = 0;
return 1;
case EVP_CTRL_CCM_SET_IVLEN:
arg = 15 - arg;
case EVP_CTRL_CCM_SET_L:
if (arg < 2 || arg > 8)
return 0;
cctx->L = arg;
return 1;
case EVP_CTRL_CCM_SET_TAG:
if ((arg & 1) || arg < 4 || arg > 16)
return 0;
if (c->encrypt && ptr)
return 0;
if (ptr) {
cctx->tag_set = 1;
memcpy(c->buf, ptr, arg);
}
cctx->M = arg;
return 1;
case EVP_CTRL_CCM_GET_TAG:
if (!c->encrypt || !cctx->tag_set)
return 0;
if (!CRYPTO_ccm128_tag(&cctx->ccm, ptr, (size_t)arg))
return 0;
cctx->tag_set = 0;
cctx->iv_set = 0;
cctx->len_set = 0;
return 1;
case EVP_CTRL_COPY:
{
EVP_CIPHER_CTX *out = ptr;
EVP_AES_CCM_CTX *cctx_out = out->cipher_data;
if (cctx->ccm.key) {
if (cctx->ccm.key != &cctx->ks)
return 0;
cctx_out->ccm.key = &cctx_out->ks;
}
return 1;
}
default:
return -1;
}
}
static int aes_ccm_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key,
const unsigned char *iv, int enc)
{
EVP_AES_CCM_CTX *cctx = ctx->cipher_data;
if (!iv && !key)
return 1;
if (key)
do {
# ifdef HWAES_CAPABLE
if (HWAES_CAPABLE) {
HWAES_set_encrypt_key(key, ctx->key_len * 8, &cctx->ks.ks);
CRYPTO_ccm128_init(&cctx->ccm, cctx->M, cctx->L,
&cctx->ks, (block128_f) HWAES_encrypt);
cctx->str = NULL;
cctx->key_set = 1;
break;
} else
# endif
# ifdef VPAES_CAPABLE
if (VPAES_CAPABLE) {
vpaes_set_encrypt_key(key, ctx->key_len * 8, &cctx->ks.ks);
CRYPTO_ccm128_init(&cctx->ccm, cctx->M, cctx->L,
&cctx->ks, (block128_f) vpaes_encrypt);
cctx->str = NULL;
cctx->key_set = 1;
break;
}
# endif
AES_set_encrypt_key(key, ctx->key_len * 8, &cctx->ks.ks);
CRYPTO_ccm128_init(&cctx->ccm, cctx->M, cctx->L,
&cctx->ks, (block128_f) AES_encrypt);
cctx->str = NULL;
cctx->key_set = 1;
} while (0);
if (iv) {
memcpy(ctx->iv, iv, 15 - cctx->L);
cctx->iv_set = 1;
}
return 1;
}
static int aes_ccm_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
const unsigned char *in, size_t len)
{
EVP_AES_CCM_CTX *cctx = ctx->cipher_data;
CCM128_CONTEXT *ccm = &cctx->ccm;
/* If not set up, return error */
if (!cctx->iv_set && !cctx->key_set)
return -1;
if (!ctx->encrypt && !cctx->tag_set)
return -1;
if (!out) {
if (!in) {
if (CRYPTO_ccm128_setiv(ccm, ctx->iv, 15 - cctx->L, len))
return -1;
cctx->len_set = 1;
return len;
}
/* If have AAD need message length */
if (!cctx->len_set && len)
return -1;
CRYPTO_ccm128_aad(ccm, in, len);
return len;
}
/* EVP_*Final() doesn't return any data */
if (!in)
return 0;
/* If not set length yet do it */
if (!cctx->len_set) {
if (CRYPTO_ccm128_setiv(ccm, ctx->iv, 15 - cctx->L, len))
return -1;
cctx->len_set = 1;
}
if (ctx->encrypt) {
if (cctx->str ? CRYPTO_ccm128_encrypt_ccm64(ccm, in, out, len,
cctx->str) :
CRYPTO_ccm128_encrypt(ccm, in, out, len))
return -1;
cctx->tag_set = 1;
return len;
} else {
int rv = -1;
if (cctx->str ? !CRYPTO_ccm128_decrypt_ccm64(ccm, in, out, len,
cctx->str) :
!CRYPTO_ccm128_decrypt(ccm, in, out, len)) {
unsigned char tag[16];
if (CRYPTO_ccm128_tag(ccm, tag, cctx->M)) {
if (!CRYPTO_memcmp(tag, ctx->buf, cctx->M))
rv = len;
}
}
if (rv == -1)
OPENSSL_cleanse(out, len);
cctx->iv_set = 0;
cctx->tag_set = 0;
cctx->len_set = 0;
return rv;
}
}
# define aes_ccm_cleanup NULL
BLOCK_CIPHER_custom(NID_aes, 128, 1, 12, ccm, CCM,
EVP_CIPH_FLAG_FIPS | CUSTOM_FLAGS)
BLOCK_CIPHER_custom(NID_aes, 192, 1, 12, ccm, CCM,
EVP_CIPH_FLAG_FIPS | CUSTOM_FLAGS)
BLOCK_CIPHER_custom(NID_aes, 256, 1, 12, ccm, CCM,
EVP_CIPH_FLAG_FIPS | CUSTOM_FLAGS)
#endif
typedef struct {
union {
double align;
AES_KEY ks;
} ks;
/* Indicates if IV has been set */
unsigned char *iv;
} EVP_AES_WRAP_CTX;
static int aes_wrap_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key,
const unsigned char *iv, int enc)
{
EVP_AES_WRAP_CTX *wctx = ctx->cipher_data;
if (!iv && !key)
return 1;
if (key) {
if (ctx->encrypt)
AES_set_encrypt_key(key, ctx->key_len * 8, &wctx->ks.ks);
else
AES_set_decrypt_key(key, ctx->key_len * 8, &wctx->ks.ks);
if (!iv)
wctx->iv = NULL;
}
if (iv) {
memcpy(ctx->iv, iv, 8);
wctx->iv = ctx->iv;
}
return 1;
}
static int aes_wrap_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
const unsigned char *in, size_t inlen)
{
EVP_AES_WRAP_CTX *wctx = ctx->cipher_data;
size_t rv;
if (!in)
return 0;
if (inlen % 8)
return -1;
if (ctx->encrypt && inlen < 8)
return -1;
if (!ctx->encrypt && inlen < 16)
return -1;
if (!out) {
if (ctx->encrypt)
return inlen + 8;
else
return inlen - 8;
}
if (ctx->encrypt)
rv = CRYPTO_128_wrap(&wctx->ks.ks, wctx->iv, out, in, inlen,
(block128_f) AES_encrypt);
else
rv = CRYPTO_128_unwrap(&wctx->ks.ks, wctx->iv, out, in, inlen,
(block128_f) AES_decrypt);
return rv ? (int)rv : -1;
}
#define WRAP_FLAGS (EVP_CIPH_WRAP_MODE \
| EVP_CIPH_CUSTOM_IV | EVP_CIPH_FLAG_CUSTOM_CIPHER \
| EVP_CIPH_ALWAYS_CALL_INIT | EVP_CIPH_FLAG_DEFAULT_ASN1)
static const EVP_CIPHER aes_128_wrap = {
NID_id_aes128_wrap,
8, 16, 8, WRAP_FLAGS,
aes_wrap_init_key, aes_wrap_cipher,
NULL,
sizeof(EVP_AES_WRAP_CTX),
NULL, NULL, NULL, NULL
};
const EVP_CIPHER *EVP_aes_128_wrap(void)
{
return &aes_128_wrap;
}
static const EVP_CIPHER aes_192_wrap = {
NID_id_aes192_wrap,
8, 24, 8, WRAP_FLAGS,
aes_wrap_init_key, aes_wrap_cipher,
NULL,
sizeof(EVP_AES_WRAP_CTX),
NULL, NULL, NULL, NULL
};
const EVP_CIPHER *EVP_aes_192_wrap(void)
{
return &aes_192_wrap;
}
static const EVP_CIPHER aes_256_wrap = {
NID_id_aes256_wrap,
8, 32, 8, WRAP_FLAGS,
aes_wrap_init_key, aes_wrap_cipher,
NULL,
sizeof(EVP_AES_WRAP_CTX),
NULL, NULL, NULL, NULL
};
const EVP_CIPHER *EVP_aes_256_wrap(void)
{
return &aes_256_wrap;
}
diff --git a/crypto/evp/e_camellia.c b/crypto/evp/e_camellia.c
index f273f9c9475a..996aed2a676b 100644
--- a/crypto/evp/e_camellia.c
+++ b/crypto/evp/e_camellia.c
@@ -1,394 +1,396 @@
/* crypto/evp/e_camellia.c */
/* ====================================================================
- * Copyright (c) 2006 The OpenSSL Project. All rights reserved.
+ * Copyright (c) 2006-2018 The OpenSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* openssl-core@openssl.org.
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.openssl.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*
* This product includes cryptographic software written by Eric Young
* (eay@cryptsoft.com). This product includes software written by Tim
* Hudson (tjh@cryptsoft.com).
*
*/
#include <openssl/opensslconf.h>
#ifndef OPENSSL_NO_CAMELLIA
# include <openssl/evp.h>
# include <openssl/err.h>
# include <string.h>
# include <assert.h>
# include <openssl/camellia.h>
# include "evp_locl.h"
# include "modes_lcl.h"
static int camellia_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key,
const unsigned char *iv, int enc);
/* Camellia subkey Structure */
typedef struct {
CAMELLIA_KEY ks;
block128_f block;
union {
cbc128_f cbc;
ctr128_f ctr;
} stream;
} EVP_CAMELLIA_KEY;
# define MAXBITCHUNK ((size_t)1<<(sizeof(size_t)*8-4))
/* Attribute operation for Camellia */
# define data(ctx) EVP_C_DATA(EVP_CAMELLIA_KEY,ctx)
# if defined(AES_ASM) && (defined(__sparc) || defined(__sparc__))
/* ---------^^^ this is not a typo, just a way to detect that
* assembler support was in general requested... */
# include "sparc_arch.h"
extern unsigned int OPENSSL_sparcv9cap_P[];
# define SPARC_CMLL_CAPABLE (OPENSSL_sparcv9cap_P[1] & CFR_CAMELLIA)
void cmll_t4_set_key(const unsigned char *key, int bits, CAMELLIA_KEY *ks);
void cmll_t4_encrypt(const unsigned char *in, unsigned char *out,
const CAMELLIA_KEY *key);
void cmll_t4_decrypt(const unsigned char *in, unsigned char *out,
const CAMELLIA_KEY *key);
void cmll128_t4_cbc_encrypt(const unsigned char *in, unsigned char *out,
size_t len, const CAMELLIA_KEY *key,
unsigned char *ivec);
void cmll128_t4_cbc_decrypt(const unsigned char *in, unsigned char *out,
size_t len, const CAMELLIA_KEY *key,
unsigned char *ivec);
void cmll256_t4_cbc_encrypt(const unsigned char *in, unsigned char *out,
size_t len, const CAMELLIA_KEY *key,
unsigned char *ivec);
void cmll256_t4_cbc_decrypt(const unsigned char *in, unsigned char *out,
size_t len, const CAMELLIA_KEY *key,
unsigned char *ivec);
void cmll128_t4_ctr32_encrypt(const unsigned char *in, unsigned char *out,
size_t blocks, const CAMELLIA_KEY *key,
unsigned char *ivec);
void cmll256_t4_ctr32_encrypt(const unsigned char *in, unsigned char *out,
size_t blocks, const CAMELLIA_KEY *key,
unsigned char *ivec);
static int cmll_t4_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key,
const unsigned char *iv, int enc)
{
int ret, mode, bits;
EVP_CAMELLIA_KEY *dat = (EVP_CAMELLIA_KEY *) ctx->cipher_data;
mode = ctx->cipher->flags & EVP_CIPH_MODE;
bits = ctx->key_len * 8;
cmll_t4_set_key(key, bits, &dat->ks);
if ((mode == EVP_CIPH_ECB_MODE || mode == EVP_CIPH_CBC_MODE)
&& !enc) {
ret = 0;
dat->block = (block128_f) cmll_t4_decrypt;
switch (bits) {
case 128:
dat->stream.cbc = mode == EVP_CIPH_CBC_MODE ?
(cbc128_f) cmll128_t4_cbc_decrypt : NULL;
break;
case 192:
case 256:
dat->stream.cbc = mode == EVP_CIPH_CBC_MODE ?
(cbc128_f) cmll256_t4_cbc_decrypt : NULL;
break;
default:
ret = -1;
}
} else {
ret = 0;
dat->block = (block128_f) cmll_t4_encrypt;
switch (bits) {
case 128:
if (mode == EVP_CIPH_CBC_MODE)
dat->stream.cbc = (cbc128_f) cmll128_t4_cbc_encrypt;
else if (mode == EVP_CIPH_CTR_MODE)
dat->stream.ctr = (ctr128_f) cmll128_t4_ctr32_encrypt;
else
dat->stream.cbc = NULL;
break;
case 192:
case 256:
if (mode == EVP_CIPH_CBC_MODE)
dat->stream.cbc = (cbc128_f) cmll256_t4_cbc_encrypt;
else if (mode == EVP_CIPH_CTR_MODE)
dat->stream.ctr = (ctr128_f) cmll256_t4_ctr32_encrypt;
else
dat->stream.cbc = NULL;
break;
default:
ret = -1;
}
}
if (ret < 0) {
EVPerr(EVP_F_CMLL_T4_INIT_KEY, EVP_R_CAMELLIA_KEY_SETUP_FAILED);
return 0;
}
return 1;
}
# define cmll_t4_cbc_cipher camellia_cbc_cipher
static int cmll_t4_cbc_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
const unsigned char *in, size_t len);
# define cmll_t4_ecb_cipher camellia_ecb_cipher
static int cmll_t4_ecb_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
const unsigned char *in, size_t len);
# define cmll_t4_ofb_cipher camellia_ofb_cipher
static int cmll_t4_ofb_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
const unsigned char *in, size_t len);
# define cmll_t4_cfb_cipher camellia_cfb_cipher
static int cmll_t4_cfb_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
const unsigned char *in, size_t len);
# define cmll_t4_cfb8_cipher camellia_cfb8_cipher
static int cmll_t4_cfb8_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
const unsigned char *in, size_t len);
# define cmll_t4_cfb1_cipher camellia_cfb1_cipher
static int cmll_t4_cfb1_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
const unsigned char *in, size_t len);
# define cmll_t4_ctr_cipher camellia_ctr_cipher
static int cmll_t4_ctr_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
const unsigned char *in, size_t len);
# define BLOCK_CIPHER_generic(nid,keylen,blocksize,ivlen,nmode,mode,MODE,flags) \
static const EVP_CIPHER cmll_t4_##keylen##_##mode = { \
nid##_##keylen##_##nmode,blocksize,keylen/8,ivlen, \
flags|EVP_CIPH_##MODE##_MODE, \
cmll_t4_init_key, \
cmll_t4_##mode##_cipher, \
NULL, \
sizeof(EVP_CAMELLIA_KEY), \
NULL,NULL,NULL,NULL }; \
static const EVP_CIPHER camellia_##keylen##_##mode = { \
nid##_##keylen##_##nmode,blocksize, \
keylen/8,ivlen, \
flags|EVP_CIPH_##MODE##_MODE, \
camellia_init_key, \
camellia_##mode##_cipher, \
NULL, \
sizeof(EVP_CAMELLIA_KEY), \
NULL,NULL,NULL,NULL }; \
const EVP_CIPHER *EVP_camellia_##keylen##_##mode(void) \
{ return SPARC_CMLL_CAPABLE?&cmll_t4_##keylen##_##mode:&camellia_##keylen##_##mode; }
# else
# define BLOCK_CIPHER_generic(nid,keylen,blocksize,ivlen,nmode,mode,MODE,flags) \
static const EVP_CIPHER camellia_##keylen##_##mode = { \
nid##_##keylen##_##nmode,blocksize,keylen/8,ivlen, \
flags|EVP_CIPH_##MODE##_MODE, \
camellia_init_key, \
camellia_##mode##_cipher, \
NULL, \
sizeof(EVP_CAMELLIA_KEY), \
NULL,NULL,NULL,NULL }; \
const EVP_CIPHER *EVP_camellia_##keylen##_##mode(void) \
{ return &camellia_##keylen##_##mode; }
# endif
# define BLOCK_CIPHER_generic_pack(nid,keylen,flags) \
BLOCK_CIPHER_generic(nid,keylen,16,16,cbc,cbc,CBC,flags|EVP_CIPH_FLAG_DEFAULT_ASN1) \
BLOCK_CIPHER_generic(nid,keylen,16,0,ecb,ecb,ECB,flags|EVP_CIPH_FLAG_DEFAULT_ASN1) \
BLOCK_CIPHER_generic(nid,keylen,1,16,ofb128,ofb,OFB,flags|EVP_CIPH_FLAG_DEFAULT_ASN1) \
BLOCK_CIPHER_generic(nid,keylen,1,16,cfb128,cfb,CFB,flags|EVP_CIPH_FLAG_DEFAULT_ASN1) \
BLOCK_CIPHER_generic(nid,keylen,1,16,cfb1,cfb1,CFB,flags) \
BLOCK_CIPHER_generic(nid,keylen,1,16,cfb8,cfb8,CFB,flags)
# if 0 /* not yet, missing NID */
BLOCK_CIPHER_generic(nid, keylen, 1, 16, ctr, ctr, CTR, flags)
# endif
/* The subkey for Camellia is generated. */
static int camellia_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key,
const unsigned char *iv, int enc)
{
int ret, mode;
EVP_CAMELLIA_KEY *dat = (EVP_CAMELLIA_KEY *) ctx->cipher_data;
ret = Camellia_set_key(key, ctx->key_len * 8, &dat->ks);
if (ret < 0) {
EVPerr(EVP_F_CAMELLIA_INIT_KEY, EVP_R_CAMELLIA_KEY_SETUP_FAILED);
return 0;
}
mode = ctx->cipher->flags & EVP_CIPH_MODE;
if ((mode == EVP_CIPH_ECB_MODE || mode == EVP_CIPH_CBC_MODE)
&& !enc) {
dat->block = (block128_f) Camellia_decrypt;
dat->stream.cbc = mode == EVP_CIPH_CBC_MODE ?
(cbc128_f) Camellia_cbc_encrypt : NULL;
} else {
dat->block = (block128_f) Camellia_encrypt;
dat->stream.cbc = mode == EVP_CIPH_CBC_MODE ?
(cbc128_f) Camellia_cbc_encrypt : NULL;
}
return 1;
}
static int camellia_cbc_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
const unsigned char *in, size_t len)
{
EVP_CAMELLIA_KEY *dat = (EVP_CAMELLIA_KEY *) ctx->cipher_data;
if (dat->stream.cbc)
(*dat->stream.cbc) (in, out, len, &dat->ks, ctx->iv, ctx->encrypt);
else if (ctx->encrypt)
CRYPTO_cbc128_encrypt(in, out, len, &dat->ks, ctx->iv, dat->block);
else
CRYPTO_cbc128_decrypt(in, out, len, &dat->ks, ctx->iv, dat->block);
return 1;
}
static int camellia_ecb_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
const unsigned char *in, size_t len)
{
size_t bl = ctx->cipher->block_size;
size_t i;
EVP_CAMELLIA_KEY *dat = (EVP_CAMELLIA_KEY *) ctx->cipher_data;
if (len < bl)
return 1;
for (i = 0, len -= bl; i <= len; i += bl)
(*dat->block) (in + i, out + i, &dat->ks);
return 1;
}
static int camellia_ofb_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
const unsigned char *in, size_t len)
{
EVP_CAMELLIA_KEY *dat = (EVP_CAMELLIA_KEY *) ctx->cipher_data;
CRYPTO_ofb128_encrypt(in, out, len, &dat->ks,
ctx->iv, &ctx->num, dat->block);
return 1;
}
static int camellia_cfb_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
const unsigned char *in, size_t len)
{
EVP_CAMELLIA_KEY *dat = (EVP_CAMELLIA_KEY *) ctx->cipher_data;
CRYPTO_cfb128_encrypt(in, out, len, &dat->ks,
ctx->iv, &ctx->num, ctx->encrypt, dat->block);
return 1;
}
static int camellia_cfb8_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
const unsigned char *in, size_t len)
{
EVP_CAMELLIA_KEY *dat = (EVP_CAMELLIA_KEY *) ctx->cipher_data;
CRYPTO_cfb128_8_encrypt(in, out, len, &dat->ks,
ctx->iv, &ctx->num, ctx->encrypt, dat->block);
return 1;
}
static int camellia_cfb1_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
const unsigned char *in, size_t len)
{
EVP_CAMELLIA_KEY *dat = (EVP_CAMELLIA_KEY *) ctx->cipher_data;
if (ctx->flags & EVP_CIPH_FLAG_LENGTH_BITS) {
CRYPTO_cfb128_1_encrypt(in, out, len, &dat->ks,
ctx->iv, &ctx->num, ctx->encrypt, dat->block);
return 1;
}
while (len >= MAXBITCHUNK) {
CRYPTO_cfb128_1_encrypt(in, out, MAXBITCHUNK * 8, &dat->ks,
ctx->iv, &ctx->num, ctx->encrypt, dat->block);
len -= MAXBITCHUNK;
+ out += MAXBITCHUNK;
+ in += MAXBITCHUNK;
}
if (len)
CRYPTO_cfb128_1_encrypt(in, out, len * 8, &dat->ks,
ctx->iv, &ctx->num, ctx->encrypt, dat->block);
return 1;
}
# if 0 /* not yet, missing NID */
static int camellia_ctr_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
const unsigned char *in, size_t len)
{
unsigned int num = ctx->num;
EVP_CAMELLIA_KEY *dat = (EVP_CAMELLIA_KEY *) ctx->cipher_data;
if (dat->stream.ctr)
CRYPTO_ctr128_encrypt_ctr32(in, out, len, &dat->ks,
ctx->iv, ctx->buf, &num, dat->stream.ctr);
else
CRYPTO_ctr128_encrypt(in, out, len, &dat->ks,
ctx->iv, ctx->buf, &num, dat->block);
ctx->num = (size_t)num;
return 1;
}
# endif
BLOCK_CIPHER_generic_pack(NID_camellia, 128, 0)
BLOCK_CIPHER_generic_pack(NID_camellia, 192, 0)
BLOCK_CIPHER_generic_pack(NID_camellia, 256, 0)
#else
# ifdef PEDANTIC
static void *dummy = &dummy;
# endif
#endif
diff --git a/crypto/evp/evp_enc.c b/crypto/evp/evp_enc.c
index be577bac767f..0c740d167902 100644
--- a/crypto/evp/evp_enc.c
+++ b/crypto/evp/evp_enc.c
@@ -1,673 +1,673 @@
/* crypto/evp/evp_enc.c */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
#include <stdio.h>
#include "cryptlib.h"
#include <openssl/evp.h>
#include <openssl/err.h>
#include <openssl/rand.h>
#ifndef OPENSSL_NO_ENGINE
# include <openssl/engine.h>
#endif
#ifdef OPENSSL_FIPS
# include <openssl/fips.h>
#endif
#include "evp_locl.h"
#ifdef OPENSSL_FIPS
# define M_do_cipher(ctx, out, in, inl) FIPS_cipher(ctx, out, in, inl)
#else
# define M_do_cipher(ctx, out, in, inl) ctx->cipher->do_cipher(ctx, out, in, inl)
#endif
const char EVP_version[] = "EVP" OPENSSL_VERSION_PTEXT;
void EVP_CIPHER_CTX_init(EVP_CIPHER_CTX *ctx)
{
memset(ctx, 0, sizeof(EVP_CIPHER_CTX));
/* ctx->cipher=NULL; */
}
EVP_CIPHER_CTX *EVP_CIPHER_CTX_new(void)
{
- EVP_CIPHER_CTX *ctx = OPENSSL_malloc(sizeof *ctx);
+ EVP_CIPHER_CTX *ctx = OPENSSL_malloc(sizeof(*ctx));
if (ctx)
EVP_CIPHER_CTX_init(ctx);
return ctx;
}
int EVP_CipherInit(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher,
const unsigned char *key, const unsigned char *iv, int enc)
{
if (cipher)
EVP_CIPHER_CTX_init(ctx);
return EVP_CipherInit_ex(ctx, cipher, NULL, key, iv, enc);
}
int EVP_CipherInit_ex(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher,
ENGINE *impl, const unsigned char *key,
const unsigned char *iv, int enc)
{
if (enc == -1)
enc = ctx->encrypt;
else {
if (enc)
enc = 1;
ctx->encrypt = enc;
}
#ifndef OPENSSL_NO_ENGINE
/*
* 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 unecessary.
*/
if (ctx->engine && ctx->cipher && (!cipher ||
(cipher
&& (cipher->nid ==
ctx->cipher->nid))))
goto skip_to_init;
#endif
if (cipher) {
/*
* Ensure a context left lying around from last time is cleared (the
* previous check attempted to avoid this if the same ENGINE and
* EVP_CIPHER could be used).
*/
if (ctx->cipher) {
unsigned long flags = ctx->flags;
EVP_CIPHER_CTX_cleanup(ctx);
/* Restore encrypt and flags */
ctx->encrypt = enc;
ctx->flags = flags;
}
#ifndef OPENSSL_NO_ENGINE
if (impl) {
if (!ENGINE_init(impl)) {
EVPerr(EVP_F_EVP_CIPHERINIT_EX, EVP_R_INITIALIZATION_ERROR);
return 0;
}
} else
/* Ask if an ENGINE is reserved for this job */
impl = ENGINE_get_cipher_engine(cipher->nid);
if (impl) {
/* There's an ENGINE for this job ... (apparently) */
const EVP_CIPHER *c = ENGINE_get_cipher(impl, cipher->nid);
if (!c) {
/*
* One positive side-effect of US's export control history,
* is that we should at least be able to avoid using US
* mispellings of "initialisation"?
*/
EVPerr(EVP_F_EVP_CIPHERINIT_EX, EVP_R_INITIALIZATION_ERROR);
return 0;
}
/* We'll use the ENGINE's private cipher definition */
cipher = c;
/*
* Store the ENGINE functional reference so we know 'cipher' came
* from an ENGINE and we need to release it when done.
*/
ctx->engine = impl;
} else
ctx->engine = NULL;
#endif
#ifdef OPENSSL_FIPS
if (FIPS_mode()) {
const EVP_CIPHER *fcipher = NULL;
if (cipher)
fcipher = evp_get_fips_cipher(cipher);
if (fcipher)
cipher = fcipher;
return FIPS_cipherinit(ctx, cipher, key, iv, enc);
}
#endif
ctx->cipher = cipher;
if (ctx->cipher->ctx_size) {
ctx->cipher_data = OPENSSL_malloc(ctx->cipher->ctx_size);
if (!ctx->cipher_data) {
ctx->cipher = NULL;
EVPerr(EVP_F_EVP_CIPHERINIT_EX, ERR_R_MALLOC_FAILURE);
return 0;
}
} else {
ctx->cipher_data = NULL;
}
ctx->key_len = cipher->key_len;
/* Preserve wrap enable flag, zero everything else */
ctx->flags &= EVP_CIPHER_CTX_FLAG_WRAP_ALLOW;
if (ctx->cipher->flags & EVP_CIPH_CTRL_INIT) {
if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_INIT, 0, NULL)) {
ctx->cipher = NULL;
EVPerr(EVP_F_EVP_CIPHERINIT_EX, EVP_R_INITIALIZATION_ERROR);
return 0;
}
}
} else if (!ctx->cipher) {
EVPerr(EVP_F_EVP_CIPHERINIT_EX, EVP_R_NO_CIPHER_SET);
return 0;
}
#ifndef OPENSSL_NO_ENGINE
skip_to_init:
#endif
#ifdef OPENSSL_FIPS
if (FIPS_mode())
return FIPS_cipherinit(ctx, cipher, key, iv, enc);
#endif
/* we assume block size is a power of 2 in *cryptUpdate */
OPENSSL_assert(ctx->cipher->block_size == 1
|| ctx->cipher->block_size == 8
|| ctx->cipher->block_size == 16);
if (!(ctx->flags & EVP_CIPHER_CTX_FLAG_WRAP_ALLOW)
&& EVP_CIPHER_CTX_mode(ctx) == EVP_CIPH_WRAP_MODE) {
EVPerr(EVP_F_EVP_CIPHERINIT_EX, EVP_R_WRAP_MODE_NOT_ALLOWED);
return 0;
}
if (!(EVP_CIPHER_CTX_flags(ctx) & EVP_CIPH_CUSTOM_IV)) {
switch (EVP_CIPHER_CTX_mode(ctx)) {
case EVP_CIPH_STREAM_CIPHER:
case EVP_CIPH_ECB_MODE:
break;
case EVP_CIPH_CFB_MODE:
case EVP_CIPH_OFB_MODE:
ctx->num = 0;
/* fall-through */
case EVP_CIPH_CBC_MODE:
OPENSSL_assert(EVP_CIPHER_CTX_iv_length(ctx) <=
(int)sizeof(ctx->iv));
if (iv)
memcpy(ctx->oiv, iv, EVP_CIPHER_CTX_iv_length(ctx));
memcpy(ctx->iv, ctx->oiv, EVP_CIPHER_CTX_iv_length(ctx));
break;
case EVP_CIPH_CTR_MODE:
ctx->num = 0;
/* Don't reuse IV for CTR mode */
if (iv)
memcpy(ctx->iv, iv, EVP_CIPHER_CTX_iv_length(ctx));
break;
default:
return 0;
break;
}
}
if (key || (ctx->cipher->flags & EVP_CIPH_ALWAYS_CALL_INIT)) {
if (!ctx->cipher->init(ctx, key, iv, enc))
return 0;
}
ctx->buf_len = 0;
ctx->final_used = 0;
ctx->block_mask = ctx->cipher->block_size - 1;
return 1;
}
int EVP_CipherUpdate(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl,
const unsigned char *in, int inl)
{
if (ctx->encrypt)
return EVP_EncryptUpdate(ctx, out, outl, in, inl);
else
return EVP_DecryptUpdate(ctx, out, outl, in, inl);
}
int EVP_CipherFinal_ex(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl)
{
if (ctx->encrypt)
return EVP_EncryptFinal_ex(ctx, out, outl);
else
return EVP_DecryptFinal_ex(ctx, out, outl);
}
int EVP_CipherFinal(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl)
{
if (ctx->encrypt)
return EVP_EncryptFinal(ctx, out, outl);
else
return EVP_DecryptFinal(ctx, out, outl);
}
int EVP_EncryptInit(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher,
const unsigned char *key, const unsigned char *iv)
{
return EVP_CipherInit(ctx, cipher, key, iv, 1);
}
int EVP_EncryptInit_ex(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher,
ENGINE *impl, const unsigned char *key,
const unsigned char *iv)
{
return EVP_CipherInit_ex(ctx, cipher, impl, key, iv, 1);
}
int EVP_DecryptInit(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher,
const unsigned char *key, const unsigned char *iv)
{
return EVP_CipherInit(ctx, cipher, key, iv, 0);
}
int EVP_DecryptInit_ex(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher,
ENGINE *impl, const unsigned char *key,
const unsigned char *iv)
{
return EVP_CipherInit_ex(ctx, cipher, impl, key, iv, 0);
}
int EVP_EncryptUpdate(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl,
const unsigned char *in, int inl)
{
int i, j, bl;
if (ctx->cipher->flags & EVP_CIPH_FLAG_CUSTOM_CIPHER) {
i = M_do_cipher(ctx, out, in, inl);
if (i < 0)
return 0;
else
*outl = i;
return 1;
}
if (inl <= 0) {
*outl = 0;
return inl == 0;
}
if (ctx->buf_len == 0 && (inl & (ctx->block_mask)) == 0) {
if (M_do_cipher(ctx, out, in, inl)) {
*outl = inl;
return 1;
} else {
*outl = 0;
return 0;
}
}
i = ctx->buf_len;
bl = ctx->cipher->block_size;
OPENSSL_assert(bl <= (int)sizeof(ctx->buf));
if (i != 0) {
if (bl - i > inl) {
memcpy(&(ctx->buf[i]), in, inl);
ctx->buf_len += inl;
*outl = 0;
return 1;
} else {
j = bl - i;
memcpy(&(ctx->buf[i]), in, j);
if (!M_do_cipher(ctx, out, ctx->buf, bl))
return 0;
inl -= j;
in += j;
out += bl;
*outl = bl;
}
} else
*outl = 0;
i = inl & (bl - 1);
inl -= i;
if (inl > 0) {
if (!M_do_cipher(ctx, out, in, inl))
return 0;
*outl += inl;
}
if (i != 0)
memcpy(ctx->buf, &(in[inl]), i);
ctx->buf_len = i;
return 1;
}
int EVP_EncryptFinal(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl)
{
int ret;
ret = EVP_EncryptFinal_ex(ctx, out, outl);
return ret;
}
int EVP_EncryptFinal_ex(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl)
{
int n, ret;
unsigned int i, b, bl;
if (ctx->cipher->flags & EVP_CIPH_FLAG_CUSTOM_CIPHER) {
ret = M_do_cipher(ctx, out, NULL, 0);
if (ret < 0)
return 0;
else
*outl = ret;
return 1;
}
b = ctx->cipher->block_size;
- OPENSSL_assert(b <= sizeof ctx->buf);
+ OPENSSL_assert(b <= sizeof(ctx->buf));
if (b == 1) {
*outl = 0;
return 1;
}
bl = ctx->buf_len;
if (ctx->flags & EVP_CIPH_NO_PADDING) {
if (bl) {
EVPerr(EVP_F_EVP_ENCRYPTFINAL_EX,
EVP_R_DATA_NOT_MULTIPLE_OF_BLOCK_LENGTH);
return 0;
}
*outl = 0;
return 1;
}
n = b - bl;
for (i = bl; i < b; i++)
ctx->buf[i] = n;
ret = M_do_cipher(ctx, out, ctx->buf, b);
if (ret)
*outl = b;
return ret;
}
int EVP_DecryptUpdate(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl,
const unsigned char *in, int inl)
{
int fix_len;
unsigned int b;
if (ctx->cipher->flags & EVP_CIPH_FLAG_CUSTOM_CIPHER) {
fix_len = M_do_cipher(ctx, out, in, inl);
if (fix_len < 0) {
*outl = 0;
return 0;
} else
*outl = fix_len;
return 1;
}
if (inl <= 0) {
*outl = 0;
return inl == 0;
}
if (ctx->flags & EVP_CIPH_NO_PADDING)
return EVP_EncryptUpdate(ctx, out, outl, in, inl);
b = ctx->cipher->block_size;
- OPENSSL_assert(b <= sizeof ctx->final);
+ OPENSSL_assert(b <= sizeof(ctx->final));
if (ctx->final_used) {
memcpy(out, ctx->final, b);
out += b;
fix_len = 1;
} else
fix_len = 0;
if (!EVP_EncryptUpdate(ctx, out, outl, in, inl))
return 0;
/*
* if we have 'decrypted' a multiple of block size, make sure we have a
* copy of this last block
*/
if (b > 1 && !ctx->buf_len) {
*outl -= b;
ctx->final_used = 1;
memcpy(ctx->final, &out[*outl], b);
} else
ctx->final_used = 0;
if (fix_len)
*outl += b;
return 1;
}
int EVP_DecryptFinal(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl)
{
int ret;
ret = EVP_DecryptFinal_ex(ctx, out, outl);
return ret;
}
int EVP_DecryptFinal_ex(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl)
{
int i, n;
unsigned int b;
*outl = 0;
if (ctx->cipher->flags & EVP_CIPH_FLAG_CUSTOM_CIPHER) {
i = M_do_cipher(ctx, out, NULL, 0);
if (i < 0)
return 0;
else
*outl = i;
return 1;
}
b = ctx->cipher->block_size;
if (ctx->flags & EVP_CIPH_NO_PADDING) {
if (ctx->buf_len) {
EVPerr(EVP_F_EVP_DECRYPTFINAL_EX,
EVP_R_DATA_NOT_MULTIPLE_OF_BLOCK_LENGTH);
return 0;
}
*outl = 0;
return 1;
}
if (b > 1) {
if (ctx->buf_len || !ctx->final_used) {
EVPerr(EVP_F_EVP_DECRYPTFINAL_EX, EVP_R_WRONG_FINAL_BLOCK_LENGTH);
return (0);
}
- OPENSSL_assert(b <= sizeof ctx->final);
+ OPENSSL_assert(b <= sizeof(ctx->final));
/*
* The following assumes that the ciphertext has been authenticated.
* Otherwise it provides a padding oracle.
*/
n = ctx->final[b - 1];
if (n == 0 || n > (int)b) {
EVPerr(EVP_F_EVP_DECRYPTFINAL_EX, EVP_R_BAD_DECRYPT);
return (0);
}
for (i = 0; i < n; i++) {
if (ctx->final[--b] != n) {
EVPerr(EVP_F_EVP_DECRYPTFINAL_EX, EVP_R_BAD_DECRYPT);
return (0);
}
}
n = ctx->cipher->block_size - n;
for (i = 0; i < n; i++)
out[i] = ctx->final[i];
*outl = n;
} else
*outl = 0;
return (1);
}
void EVP_CIPHER_CTX_free(EVP_CIPHER_CTX *ctx)
{
if (ctx) {
EVP_CIPHER_CTX_cleanup(ctx);
OPENSSL_free(ctx);
}
}
int EVP_CIPHER_CTX_cleanup(EVP_CIPHER_CTX *c)
{
#ifndef OPENSSL_FIPS
if (c->cipher != NULL) {
if (c->cipher->cleanup && !c->cipher->cleanup(c))
return 0;
/* Cleanse cipher context data */
if (c->cipher_data)
OPENSSL_cleanse(c->cipher_data, c->cipher->ctx_size);
}
if (c->cipher_data)
OPENSSL_free(c->cipher_data);
#endif
#ifndef OPENSSL_NO_ENGINE
if (c->engine)
/*
* The EVP_CIPHER we used belongs to an ENGINE, release the
* functional reference we held for this reason.
*/
ENGINE_finish(c->engine);
#endif
#ifdef OPENSSL_FIPS
FIPS_cipher_ctx_cleanup(c);
#endif
memset(c, 0, sizeof(EVP_CIPHER_CTX));
return 1;
}
int EVP_CIPHER_CTX_set_key_length(EVP_CIPHER_CTX *c, int keylen)
{
if (c->cipher->flags & EVP_CIPH_CUSTOM_KEY_LENGTH)
return EVP_CIPHER_CTX_ctrl(c, EVP_CTRL_SET_KEY_LENGTH, keylen, NULL);
if (c->key_len == keylen)
return 1;
if ((keylen > 0) && (c->cipher->flags & EVP_CIPH_VARIABLE_LENGTH)) {
c->key_len = keylen;
return 1;
}
EVPerr(EVP_F_EVP_CIPHER_CTX_SET_KEY_LENGTH, EVP_R_INVALID_KEY_LENGTH);
return 0;
}
int EVP_CIPHER_CTX_set_padding(EVP_CIPHER_CTX *ctx, int pad)
{
if (pad)
ctx->flags &= ~EVP_CIPH_NO_PADDING;
else
ctx->flags |= EVP_CIPH_NO_PADDING;
return 1;
}
int EVP_CIPHER_CTX_ctrl(EVP_CIPHER_CTX *ctx, int type, int arg, void *ptr)
{
int ret;
if (!ctx->cipher) {
EVPerr(EVP_F_EVP_CIPHER_CTX_CTRL, EVP_R_NO_CIPHER_SET);
return 0;
}
if (!ctx->cipher->ctrl) {
EVPerr(EVP_F_EVP_CIPHER_CTX_CTRL, EVP_R_CTRL_NOT_IMPLEMENTED);
return 0;
}
ret = ctx->cipher->ctrl(ctx, type, arg, ptr);
if (ret == -1) {
EVPerr(EVP_F_EVP_CIPHER_CTX_CTRL,
EVP_R_CTRL_OPERATION_NOT_IMPLEMENTED);
return 0;
}
return ret;
}
int EVP_CIPHER_CTX_rand_key(EVP_CIPHER_CTX *ctx, unsigned char *key)
{
if (ctx->cipher->flags & EVP_CIPH_RAND_KEY)
return EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_RAND_KEY, 0, key);
if (RAND_bytes(key, ctx->key_len) <= 0)
return 0;
return 1;
}
int EVP_CIPHER_CTX_copy(EVP_CIPHER_CTX *out, const EVP_CIPHER_CTX *in)
{
if ((in == NULL) || (in->cipher == NULL)) {
EVPerr(EVP_F_EVP_CIPHER_CTX_COPY, EVP_R_INPUT_NOT_INITIALIZED);
return 0;
}
#ifndef OPENSSL_NO_ENGINE
/* Make sure it's safe to copy a cipher context using an ENGINE */
if (in->engine && !ENGINE_init(in->engine)) {
EVPerr(EVP_F_EVP_CIPHER_CTX_COPY, ERR_R_ENGINE_LIB);
return 0;
}
#endif
EVP_CIPHER_CTX_cleanup(out);
- memcpy(out, in, sizeof *out);
+ memcpy(out, in, sizeof(*out));
if (in->cipher_data && in->cipher->ctx_size) {
out->cipher_data = OPENSSL_malloc(in->cipher->ctx_size);
if (!out->cipher_data) {
out->cipher = NULL;
EVPerr(EVP_F_EVP_CIPHER_CTX_COPY, ERR_R_MALLOC_FAILURE);
return 0;
}
memcpy(out->cipher_data, in->cipher_data, in->cipher->ctx_size);
}
if (in->cipher->flags & EVP_CIPH_CUSTOM_COPY)
if (!in->cipher->ctrl((EVP_CIPHER_CTX *)in, EVP_CTRL_COPY, 0, out)) {
out->cipher = NULL;
EVPerr(EVP_F_EVP_CIPHER_CTX_COPY, EVP_R_INITIALIZATION_ERROR);
return 0;
}
return 1;
}
diff --git a/crypto/evp/evp_locl.h b/crypto/evp/evp_locl.h
index 2bb709a065d5..bee7f6d16504 100644
--- a/crypto/evp/evp_locl.h
+++ b/crypto/evp/evp_locl.h
@@ -1,373 +1,373 @@
/* evp_locl.h */
/*
* Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL project
* 2000.
*/
/* ====================================================================
- * Copyright (c) 1999 The OpenSSL Project. All rights reserved.
+ * Copyright (c) 1999-2018 The OpenSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* licensing@OpenSSL.org.
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*
* This product includes cryptographic software written by Eric Young
* (eay@cryptsoft.com). This product includes software written by Tim
* Hudson (tjh@cryptsoft.com).
*
*/
/* Macros to code block cipher wrappers */
/* Wrapper functions for each cipher mode */
#define BLOCK_CIPHER_ecb_loop() \
size_t i, bl; \
bl = ctx->cipher->block_size;\
if(inl < bl) return 1;\
inl -= bl; \
for(i=0; i <= inl; i+=bl)
#define BLOCK_CIPHER_func_ecb(cname, cprefix, kstruct, ksched) \
static int cname##_ecb_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t inl) \
{\
BLOCK_CIPHER_ecb_loop() \
cprefix##_ecb_encrypt(in + i, out + i, &((kstruct *)ctx->cipher_data)->ksched, ctx->encrypt);\
return 1;\
}
#define EVP_MAXCHUNK ((size_t)1<<(sizeof(long)*8-2))
#define BLOCK_CIPHER_func_ofb(cname, cprefix, cbits, kstruct, ksched) \
static int cname##_ofb_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t inl) \
{\
while(inl>=EVP_MAXCHUNK)\
{\
cprefix##_ofb##cbits##_encrypt(in, out, (long)EVP_MAXCHUNK, &((kstruct *)ctx->cipher_data)->ksched, ctx->iv, &ctx->num);\
inl-=EVP_MAXCHUNK;\
in +=EVP_MAXCHUNK;\
out+=EVP_MAXCHUNK;\
}\
if (inl)\
cprefix##_ofb##cbits##_encrypt(in, out, (long)inl, &((kstruct *)ctx->cipher_data)->ksched, ctx->iv, &ctx->num);\
return 1;\
}
#define BLOCK_CIPHER_func_cbc(cname, cprefix, kstruct, ksched) \
static int cname##_cbc_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t inl) \
{\
while(inl>=EVP_MAXCHUNK) \
{\
cprefix##_cbc_encrypt(in, out, (long)EVP_MAXCHUNK, &((kstruct *)ctx->cipher_data)->ksched, ctx->iv, ctx->encrypt);\
inl-=EVP_MAXCHUNK;\
in +=EVP_MAXCHUNK;\
out+=EVP_MAXCHUNK;\
}\
if (inl)\
cprefix##_cbc_encrypt(in, out, (long)inl, &((kstruct *)ctx->cipher_data)->ksched, ctx->iv, ctx->encrypt);\
return 1;\
}
#define BLOCK_CIPHER_func_cfb(cname, cprefix, cbits, kstruct, ksched) \
static int cname##_cfb##cbits##_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t inl) \
{\
size_t chunk=EVP_MAXCHUNK;\
if (cbits==1) chunk>>=3;\
if (inl<chunk) chunk=inl;\
while(inl && inl>=chunk)\
{\
- cprefix##_cfb##cbits##_encrypt(in, out, (long)((cbits==1) && !(ctx->flags & EVP_CIPH_FLAG_LENGTH_BITS) ?inl*8:inl), &((kstruct *)ctx->cipher_data)->ksched, ctx->iv, &ctx->num, ctx->encrypt);\
+ cprefix##_cfb##cbits##_encrypt(in, out, (long)((cbits==1) && !(ctx->flags & EVP_CIPH_FLAG_LENGTH_BITS) ?chunk*8:chunk), &((kstruct *)ctx->cipher_data)->ksched, ctx->iv, &ctx->num, ctx->encrypt);\
inl-=chunk;\
in +=chunk;\
out+=chunk;\
if(inl<chunk) chunk=inl;\
}\
return 1;\
}
#define BLOCK_CIPHER_all_funcs(cname, cprefix, cbits, kstruct, ksched) \
BLOCK_CIPHER_func_cbc(cname, cprefix, kstruct, ksched) \
BLOCK_CIPHER_func_cfb(cname, cprefix, cbits, kstruct, ksched) \
BLOCK_CIPHER_func_ecb(cname, cprefix, kstruct, ksched) \
BLOCK_CIPHER_func_ofb(cname, cprefix, cbits, kstruct, ksched)
#define BLOCK_CIPHER_def1(cname, nmode, mode, MODE, kstruct, nid, block_size, \
key_len, iv_len, flags, init_key, cleanup, \
set_asn1, get_asn1, ctrl) \
static const EVP_CIPHER cname##_##mode = { \
nid##_##nmode, block_size, key_len, iv_len, \
flags | EVP_CIPH_##MODE##_MODE, \
init_key, \
cname##_##mode##_cipher, \
cleanup, \
sizeof(kstruct), \
set_asn1, get_asn1,\
ctrl, \
NULL \
}; \
const EVP_CIPHER *EVP_##cname##_##mode(void) { return &cname##_##mode; }
#define BLOCK_CIPHER_def_cbc(cname, kstruct, nid, block_size, key_len, \
iv_len, flags, init_key, cleanup, set_asn1, \
get_asn1, ctrl) \
BLOCK_CIPHER_def1(cname, cbc, cbc, CBC, kstruct, nid, block_size, key_len, \
iv_len, flags, init_key, cleanup, set_asn1, get_asn1, ctrl)
#define BLOCK_CIPHER_def_cfb(cname, kstruct, nid, key_len, \
iv_len, cbits, flags, init_key, cleanup, \
set_asn1, get_asn1, ctrl) \
BLOCK_CIPHER_def1(cname, cfb##cbits, cfb##cbits, CFB, kstruct, nid, 1, \
key_len, iv_len, flags, init_key, cleanup, set_asn1, \
get_asn1, ctrl)
#define BLOCK_CIPHER_def_ofb(cname, kstruct, nid, key_len, \
iv_len, cbits, flags, init_key, cleanup, \
set_asn1, get_asn1, ctrl) \
BLOCK_CIPHER_def1(cname, ofb##cbits, ofb, OFB, kstruct, nid, 1, \
key_len, iv_len, flags, init_key, cleanup, set_asn1, \
get_asn1, ctrl)
#define BLOCK_CIPHER_def_ecb(cname, kstruct, nid, block_size, key_len, \
flags, init_key, cleanup, set_asn1, \
get_asn1, ctrl) \
BLOCK_CIPHER_def1(cname, ecb, ecb, ECB, kstruct, nid, block_size, key_len, \
0, flags, init_key, cleanup, set_asn1, get_asn1, ctrl)
#define BLOCK_CIPHER_defs(cname, kstruct, \
nid, block_size, key_len, iv_len, cbits, flags, \
init_key, cleanup, set_asn1, get_asn1, ctrl) \
BLOCK_CIPHER_def_cbc(cname, kstruct, nid, block_size, key_len, iv_len, flags, \
init_key, cleanup, set_asn1, get_asn1, ctrl) \
BLOCK_CIPHER_def_cfb(cname, kstruct, nid, key_len, iv_len, cbits, \
flags, init_key, cleanup, set_asn1, get_asn1, ctrl) \
BLOCK_CIPHER_def_ofb(cname, kstruct, nid, key_len, iv_len, cbits, \
flags, init_key, cleanup, set_asn1, get_asn1, ctrl) \
BLOCK_CIPHER_def_ecb(cname, kstruct, nid, block_size, key_len, flags, \
init_key, cleanup, set_asn1, get_asn1, ctrl)
/*-
#define BLOCK_CIPHER_defs(cname, kstruct, \
nid, block_size, key_len, iv_len, flags,\
init_key, cleanup, set_asn1, get_asn1, ctrl)\
static const EVP_CIPHER cname##_cbc = {\
nid##_cbc, block_size, key_len, iv_len, \
flags | EVP_CIPH_CBC_MODE,\
init_key,\
cname##_cbc_cipher,\
cleanup,\
sizeof(EVP_CIPHER_CTX)-sizeof((((EVP_CIPHER_CTX *)NULL)->c))+\
sizeof((((EVP_CIPHER_CTX *)NULL)->c.kstruct)),\
set_asn1, get_asn1,\
ctrl, \
NULL \
};\
const EVP_CIPHER *EVP_##cname##_cbc(void) { return &cname##_cbc; }\
static const EVP_CIPHER cname##_cfb = {\
nid##_cfb64, 1, key_len, iv_len, \
flags | EVP_CIPH_CFB_MODE,\
init_key,\
cname##_cfb_cipher,\
cleanup,\
sizeof(EVP_CIPHER_CTX)-sizeof((((EVP_CIPHER_CTX *)NULL)->c))+\
sizeof((((EVP_CIPHER_CTX *)NULL)->c.kstruct)),\
set_asn1, get_asn1,\
ctrl,\
NULL \
};\
const EVP_CIPHER *EVP_##cname##_cfb(void) { return &cname##_cfb; }\
static const EVP_CIPHER cname##_ofb = {\
nid##_ofb64, 1, key_len, iv_len, \
flags | EVP_CIPH_OFB_MODE,\
init_key,\
cname##_ofb_cipher,\
cleanup,\
sizeof(EVP_CIPHER_CTX)-sizeof((((EVP_CIPHER_CTX *)NULL)->c))+\
sizeof((((EVP_CIPHER_CTX *)NULL)->c.kstruct)),\
set_asn1, get_asn1,\
ctrl,\
NULL \
};\
const EVP_CIPHER *EVP_##cname##_ofb(void) { return &cname##_ofb; }\
static const EVP_CIPHER cname##_ecb = {\
nid##_ecb, block_size, key_len, iv_len, \
flags | EVP_CIPH_ECB_MODE,\
init_key,\
cname##_ecb_cipher,\
cleanup,\
sizeof(EVP_CIPHER_CTX)-sizeof((((EVP_CIPHER_CTX *)NULL)->c))+\
sizeof((((EVP_CIPHER_CTX *)NULL)->c.kstruct)),\
set_asn1, get_asn1,\
ctrl,\
NULL \
};\
const EVP_CIPHER *EVP_##cname##_ecb(void) { return &cname##_ecb; }
*/
#define IMPLEMENT_BLOCK_CIPHER(cname, ksched, cprefix, kstruct, nid, \
block_size, key_len, iv_len, cbits, \
flags, init_key, \
cleanup, set_asn1, get_asn1, ctrl) \
BLOCK_CIPHER_all_funcs(cname, cprefix, cbits, kstruct, ksched) \
BLOCK_CIPHER_defs(cname, kstruct, nid, block_size, key_len, iv_len, \
cbits, flags, init_key, cleanup, set_asn1, \
get_asn1, ctrl)
#define EVP_C_DATA(kstruct, ctx) ((kstruct *)(ctx)->cipher_data)
#define IMPLEMENT_CFBR(cipher,cprefix,kstruct,ksched,keysize,cbits,iv_len) \
BLOCK_CIPHER_func_cfb(cipher##_##keysize,cprefix,cbits,kstruct,ksched) \
BLOCK_CIPHER_def_cfb(cipher##_##keysize,kstruct, \
NID_##cipher##_##keysize, keysize/8, iv_len, cbits, \
0, cipher##_init_key, NULL, \
EVP_CIPHER_set_asn1_iv, \
EVP_CIPHER_get_asn1_iv, \
NULL)
struct evp_pkey_ctx_st {
/* Method associated with this operation */
const EVP_PKEY_METHOD *pmeth;
/* Engine that implements this method or NULL if builtin */
ENGINE *engine;
/* Key: may be NULL */
EVP_PKEY *pkey;
/* Peer key for key agreement, may be NULL */
EVP_PKEY *peerkey;
/* Actual operation */
int operation;
/* Algorithm specific data */
void *data;
/* Application specific data */
void *app_data;
/* Keygen callback */
EVP_PKEY_gen_cb *pkey_gencb;
/* implementation specific keygen data */
int *keygen_info;
int keygen_info_count;
} /* EVP_PKEY_CTX */ ;
#define EVP_PKEY_FLAG_DYNAMIC 1
struct evp_pkey_method_st {
int pkey_id;
int flags;
int (*init) (EVP_PKEY_CTX *ctx);
int (*copy) (EVP_PKEY_CTX *dst, EVP_PKEY_CTX *src);
void (*cleanup) (EVP_PKEY_CTX *ctx);
int (*paramgen_init) (EVP_PKEY_CTX *ctx);
int (*paramgen) (EVP_PKEY_CTX *ctx, EVP_PKEY *pkey);
int (*keygen_init) (EVP_PKEY_CTX *ctx);
int (*keygen) (EVP_PKEY_CTX *ctx, EVP_PKEY *pkey);
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);
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);
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);
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);
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);
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);
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);
int (*derive_init) (EVP_PKEY_CTX *ctx);
int (*derive) (EVP_PKEY_CTX *ctx, unsigned char *key, size_t *keylen);
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);
} /* EVP_PKEY_METHOD */ ;
void evp_pkey_set_cb_translate(BN_GENCB *cb, EVP_PKEY_CTX *ctx);
int PKCS5_v2_PBKDF2_keyivgen(EVP_CIPHER_CTX *ctx, const char *pass,
int passlen, ASN1_TYPE *param,
const EVP_CIPHER *c, const EVP_MD *md,
int en_de);
const EVP_MD *evp_get_fips_md(const EVP_MD *md);
const EVP_CIPHER *evp_get_fips_cipher(const EVP_CIPHER *cipher);
#ifdef OPENSSL_FIPS
# ifdef OPENSSL_DOING_MAKEDEPEND
# undef SHA1_Init
# undef SHA1_Update
# undef SHA224_Init
# undef SHA256_Init
# undef SHA384_Init
# undef SHA512_Init
# undef DES_set_key_unchecked
# endif
# define RIPEMD160_Init private_RIPEMD160_Init
# define WHIRLPOOL_Init private_WHIRLPOOL_Init
# define MD5_Init private_MD5_Init
# define MD4_Init private_MD4_Init
# define MD2_Init private_MD2_Init
# define MDC2_Init private_MDC2_Init
# define SHA_Init private_SHA_Init
# define SHA1_Init private_SHA1_Init
# define SHA224_Init private_SHA224_Init
# define SHA256_Init private_SHA256_Init
# define SHA384_Init private_SHA384_Init
# define SHA512_Init private_SHA512_Init
# define BF_set_key private_BF_set_key
# define CAST_set_key private_CAST_set_key
# define idea_set_encrypt_key private_idea_set_encrypt_key
# define SEED_set_key private_SEED_set_key
# define RC2_set_key private_RC2_set_key
# define RC4_set_key private_RC4_set_key
# define DES_set_key_unchecked private_DES_set_key_unchecked
# define Camellia_set_key private_Camellia_set_key
#endif
diff --git a/crypto/evp/evp_pbe.c b/crypto/evp/evp_pbe.c
index 7934c95fad0c..5d2f04bf9eda 100644
--- a/crypto/evp/evp_pbe.c
+++ b/crypto/evp/evp_pbe.c
@@ -1,312 +1,312 @@
/* evp_pbe.c */
/*
* Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL project
* 1999.
*/
/* ====================================================================
* Copyright (c) 1999-2006 The OpenSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* licensing@OpenSSL.org.
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*
* This product includes cryptographic software written by Eric Young
* (eay@cryptsoft.com). This product includes software written by Tim
* Hudson (tjh@cryptsoft.com).
*
*/
#include <stdio.h>
#include "cryptlib.h"
#include <openssl/evp.h>
#include <openssl/pkcs12.h>
#include <openssl/x509.h>
#include "evp_locl.h"
/* Password based encryption (PBE) functions */
DECLARE_STACK_OF(EVP_PBE_CTL)
static STACK_OF(EVP_PBE_CTL) *pbe_algs;
/* Setup a cipher context from a PBE algorithm */
typedef struct {
int pbe_type;
int pbe_nid;
int cipher_nid;
int md_nid;
EVP_PBE_KEYGEN *keygen;
} EVP_PBE_CTL;
static const EVP_PBE_CTL builtin_pbe[] = {
{EVP_PBE_TYPE_OUTER, NID_pbeWithMD2AndDES_CBC,
NID_des_cbc, NID_md2, PKCS5_PBE_keyivgen},
{EVP_PBE_TYPE_OUTER, NID_pbeWithMD5AndDES_CBC,
NID_des_cbc, NID_md5, PKCS5_PBE_keyivgen},
{EVP_PBE_TYPE_OUTER, NID_pbeWithSHA1AndRC2_CBC,
NID_rc2_64_cbc, NID_sha1, PKCS5_PBE_keyivgen},
#ifndef OPENSSL_NO_HMAC
{EVP_PBE_TYPE_OUTER, NID_id_pbkdf2, -1, -1, PKCS5_v2_PBKDF2_keyivgen},
#endif
{EVP_PBE_TYPE_OUTER, NID_pbe_WithSHA1And128BitRC4,
NID_rc4, NID_sha1, PKCS12_PBE_keyivgen},
{EVP_PBE_TYPE_OUTER, NID_pbe_WithSHA1And40BitRC4,
NID_rc4_40, NID_sha1, PKCS12_PBE_keyivgen},
{EVP_PBE_TYPE_OUTER, NID_pbe_WithSHA1And3_Key_TripleDES_CBC,
NID_des_ede3_cbc, NID_sha1, PKCS12_PBE_keyivgen},
{EVP_PBE_TYPE_OUTER, NID_pbe_WithSHA1And2_Key_TripleDES_CBC,
NID_des_ede_cbc, NID_sha1, PKCS12_PBE_keyivgen},
{EVP_PBE_TYPE_OUTER, NID_pbe_WithSHA1And128BitRC2_CBC,
NID_rc2_cbc, NID_sha1, PKCS12_PBE_keyivgen},
{EVP_PBE_TYPE_OUTER, NID_pbe_WithSHA1And40BitRC2_CBC,
NID_rc2_40_cbc, NID_sha1, PKCS12_PBE_keyivgen},
#ifndef OPENSSL_NO_HMAC
{EVP_PBE_TYPE_OUTER, NID_pbes2, -1, -1, PKCS5_v2_PBE_keyivgen},
#endif
{EVP_PBE_TYPE_OUTER, NID_pbeWithMD2AndRC2_CBC,
NID_rc2_64_cbc, NID_md2, PKCS5_PBE_keyivgen},
{EVP_PBE_TYPE_OUTER, NID_pbeWithMD5AndRC2_CBC,
NID_rc2_64_cbc, NID_md5, PKCS5_PBE_keyivgen},
{EVP_PBE_TYPE_OUTER, NID_pbeWithSHA1AndDES_CBC,
NID_des_cbc, NID_sha1, PKCS5_PBE_keyivgen},
{EVP_PBE_TYPE_PRF, NID_hmacWithSHA1, -1, NID_sha1, 0},
{EVP_PBE_TYPE_PRF, NID_hmacWithMD5, -1, NID_md5, 0},
{EVP_PBE_TYPE_PRF, NID_hmacWithSHA224, -1, NID_sha224, 0},
{EVP_PBE_TYPE_PRF, NID_hmacWithSHA256, -1, NID_sha256, 0},
{EVP_PBE_TYPE_PRF, NID_hmacWithSHA384, -1, NID_sha384, 0},
{EVP_PBE_TYPE_PRF, NID_hmacWithSHA512, -1, NID_sha512, 0},
{EVP_PBE_TYPE_PRF, NID_id_HMACGostR3411_94, -1, NID_id_GostR3411_94, 0},
};
#ifdef TEST
int main(int argc, char **argv)
{
int i, nid_md, nid_cipher;
EVP_PBE_CTL *tpbe, *tpbe2;
/*
* OpenSSL_add_all_algorithms();
*/
for (i = 0; i < sizeof(builtin_pbe) / sizeof(EVP_PBE_CTL); i++) {
tpbe = builtin_pbe + i;
fprintf(stderr, "%d %d %s ", tpbe->pbe_type, tpbe->pbe_nid,
OBJ_nid2sn(tpbe->pbe_nid));
if (EVP_PBE_find(tpbe->pbe_type, tpbe->pbe_nid,
&nid_cipher, &nid_md, 0))
fprintf(stderr, "Found %s %s\n",
OBJ_nid2sn(nid_cipher), OBJ_nid2sn(nid_md));
else
fprintf(stderr, "Find ERROR!!\n");
}
return 0;
}
#endif
int EVP_PBE_CipherInit(ASN1_OBJECT *pbe_obj, const char *pass, int passlen,
ASN1_TYPE *param, EVP_CIPHER_CTX *ctx, int en_de)
{
const EVP_CIPHER *cipher;
const EVP_MD *md;
int cipher_nid, md_nid;
EVP_PBE_KEYGEN *keygen;
if (!EVP_PBE_find(EVP_PBE_TYPE_OUTER, OBJ_obj2nid(pbe_obj),
&cipher_nid, &md_nid, &keygen)) {
char obj_tmp[80];
EVPerr(EVP_F_EVP_PBE_CIPHERINIT, EVP_R_UNKNOWN_PBE_ALGORITHM);
if (!pbe_obj)
- BUF_strlcpy(obj_tmp, "NULL", sizeof obj_tmp);
+ BUF_strlcpy(obj_tmp, "NULL", sizeof(obj_tmp));
else
- i2t_ASN1_OBJECT(obj_tmp, sizeof obj_tmp, pbe_obj);
+ i2t_ASN1_OBJECT(obj_tmp, sizeof(obj_tmp), pbe_obj);
ERR_add_error_data(2, "TYPE=", obj_tmp);
return 0;
}
if (!pass)
passlen = 0;
else if (passlen == -1)
passlen = strlen(pass);
if (cipher_nid == -1)
cipher = NULL;
else {
cipher = EVP_get_cipherbynid(cipher_nid);
if (!cipher) {
EVPerr(EVP_F_EVP_PBE_CIPHERINIT, EVP_R_UNKNOWN_CIPHER);
return 0;
}
}
if (md_nid == -1)
md = NULL;
else {
md = EVP_get_digestbynid(md_nid);
if (!md) {
EVPerr(EVP_F_EVP_PBE_CIPHERINIT, EVP_R_UNKNOWN_DIGEST);
return 0;
}
}
if (!keygen(ctx, pass, passlen, param, cipher, md, en_de)) {
EVPerr(EVP_F_EVP_PBE_CIPHERINIT, EVP_R_KEYGEN_FAILURE);
return 0;
}
return 1;
}
DECLARE_OBJ_BSEARCH_CMP_FN(EVP_PBE_CTL, EVP_PBE_CTL, pbe2);
static int pbe2_cmp(const EVP_PBE_CTL *pbe1, const EVP_PBE_CTL *pbe2)
{
int ret = pbe1->pbe_type - pbe2->pbe_type;
if (ret)
return ret;
else
return pbe1->pbe_nid - pbe2->pbe_nid;
}
IMPLEMENT_OBJ_BSEARCH_CMP_FN(EVP_PBE_CTL, EVP_PBE_CTL, pbe2);
static int pbe_cmp(const EVP_PBE_CTL *const *a, const EVP_PBE_CTL *const *b)
{
int ret = (*a)->pbe_type - (*b)->pbe_type;
if (ret)
return ret;
else
return (*a)->pbe_nid - (*b)->pbe_nid;
}
/* Add a PBE algorithm */
int EVP_PBE_alg_add_type(int pbe_type, int pbe_nid, int cipher_nid,
int md_nid, EVP_PBE_KEYGEN *keygen)
{
EVP_PBE_CTL *pbe_tmp;
if (pbe_algs == NULL) {
pbe_algs = sk_EVP_PBE_CTL_new(pbe_cmp);
if (pbe_algs == NULL)
goto err;
}
if ((pbe_tmp = OPENSSL_malloc(sizeof(*pbe_tmp))) == NULL)
goto err;
pbe_tmp->pbe_type = pbe_type;
pbe_tmp->pbe_nid = pbe_nid;
pbe_tmp->cipher_nid = cipher_nid;
pbe_tmp->md_nid = md_nid;
pbe_tmp->keygen = keygen;
sk_EVP_PBE_CTL_push(pbe_algs, pbe_tmp);
return 1;
err:
EVPerr(EVP_F_EVP_PBE_ALG_ADD_TYPE, ERR_R_MALLOC_FAILURE);
return 0;
}
int EVP_PBE_alg_add(int nid, const EVP_CIPHER *cipher, const EVP_MD *md,
EVP_PBE_KEYGEN *keygen)
{
int cipher_nid, md_nid;
if (cipher)
cipher_nid = EVP_CIPHER_nid(cipher);
else
cipher_nid = -1;
if (md)
md_nid = EVP_MD_type(md);
else
md_nid = -1;
return EVP_PBE_alg_add_type(EVP_PBE_TYPE_OUTER, nid,
cipher_nid, md_nid, keygen);
}
int EVP_PBE_find(int type, int pbe_nid,
int *pcnid, int *pmnid, EVP_PBE_KEYGEN **pkeygen)
{
EVP_PBE_CTL *pbetmp = NULL, pbelu;
int i;
if (pbe_nid == NID_undef)
return 0;
pbelu.pbe_type = type;
pbelu.pbe_nid = pbe_nid;
if (pbe_algs) {
i = sk_EVP_PBE_CTL_find(pbe_algs, &pbelu);
if (i != -1)
pbetmp = sk_EVP_PBE_CTL_value(pbe_algs, i);
}
if (pbetmp == NULL) {
pbetmp = OBJ_bsearch_pbe2(&pbelu, builtin_pbe,
sizeof(builtin_pbe) / sizeof(EVP_PBE_CTL));
}
if (pbetmp == NULL)
return 0;
if (pcnid)
*pcnid = pbetmp->cipher_nid;
if (pmnid)
*pmnid = pbetmp->md_nid;
if (pkeygen)
*pkeygen = pbetmp->keygen;
return 1;
}
static void free_evp_pbe_ctl(EVP_PBE_CTL *pbe)
{
OPENSSL_freeFunc(pbe);
}
void EVP_PBE_cleanup(void)
{
sk_EVP_PBE_CTL_pop_free(pbe_algs, free_evp_pbe_ctl);
pbe_algs = NULL;
}
diff --git a/crypto/evp/evp_test.c b/crypto/evp/evp_test.c
index 98796427bf49..97a208302785 100644
--- a/crypto/evp/evp_test.c
+++ b/crypto/evp/evp_test.c
@@ -1,598 +1,598 @@
/* Written by Ben Laurie, 2001 */
/*
* Copyright (c) 2001 The OpenSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* openssl-core@openssl.org.
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.openssl.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <stdio.h>
#include <string.h>
#include "../e_os.h"
#include <openssl/opensslconf.h>
#include <openssl/evp.h>
#ifndef OPENSSL_NO_ENGINE
# include <openssl/engine.h>
#endif
#include <openssl/err.h>
#include <openssl/conf.h>
static void hexdump(FILE *f, const char *title, const unsigned char *s, int l)
{
int n = 0;
fprintf(f, "%s", title);
for (; n < l; ++n) {
if ((n % 16) == 0)
fprintf(f, "\n%04x", n);
fprintf(f, " %02x", s[n]);
}
fprintf(f, "\n");
}
static int convert(unsigned char *s)
{
unsigned char *d;
int digits = 0;
for (d = s; *s; s += 2, ++d) {
unsigned int n;
if (!s[1]) {
fprintf(stderr, "Odd number of hex digits!");
EXIT(4);
}
sscanf((char *)s, "%2x", &n);
*d = (unsigned char)n;
digits++;
}
return digits;
}
static char *sstrsep(char **string, const char *delim)
{
char isdelim[256];
char *token = *string;
if (**string == 0)
return NULL;
memset(isdelim, 0, 256);
isdelim[0] = 1;
while (*delim) {
isdelim[(unsigned char)(*delim)] = 1;
delim++;
}
while (!isdelim[(unsigned char)(**string)]) {
(*string)++;
}
if (**string) {
**string = 0;
(*string)++;
}
return token;
}
static unsigned char *ustrsep(char **p, const char *sep)
{
return (unsigned char *)sstrsep(p, sep);
}
static int test1_exit(int ec)
{
EXIT(ec);
return (0); /* To keep some compilers quiet */
}
static void test1(const EVP_CIPHER *c, const unsigned char *key, int kn,
const unsigned char *iv, int in,
const unsigned char *plaintext, int pn,
const unsigned char *ciphertext, int cn,
const unsigned char *aad, int an,
const unsigned char *tag, int tn, int encdec)
{
EVP_CIPHER_CTX ctx;
unsigned char out[4096];
int outl, outl2, mode;
printf("Testing cipher %s%s\n", EVP_CIPHER_name(c),
(encdec ==
1 ? "(encrypt)" : (encdec ==
0 ? "(decrypt)" : "(encrypt/decrypt)")));
hexdump(stdout, "Key", key, kn);
if (in)
hexdump(stdout, "IV", iv, in);
hexdump(stdout, "Plaintext", plaintext, pn);
hexdump(stdout, "Ciphertext", ciphertext, cn);
if (an)
hexdump(stdout, "AAD", aad, an);
if (tn)
hexdump(stdout, "Tag", tag, tn);
mode = EVP_CIPHER_mode(c);
if (kn != EVP_CIPHER_key_length(c)) {
fprintf(stderr, "Key length doesn't match, got %d expected %lu\n", kn,
(unsigned long)EVP_CIPHER_key_length(c));
test1_exit(5);
}
EVP_CIPHER_CTX_init(&ctx);
EVP_CIPHER_CTX_set_flags(&ctx, EVP_CIPHER_CTX_FLAG_WRAP_ALLOW);
if (encdec != 0) {
if (mode == EVP_CIPH_GCM_MODE) {
if (!EVP_EncryptInit_ex(&ctx, c, NULL, NULL, NULL)) {
fprintf(stderr, "EncryptInit failed\n");
ERR_print_errors_fp(stderr);
test1_exit(10);
}
if (!EVP_CIPHER_CTX_ctrl(&ctx, EVP_CTRL_GCM_SET_IVLEN, in, NULL)) {
fprintf(stderr, "IV length set failed\n");
ERR_print_errors_fp(stderr);
test1_exit(11);
}
if (!EVP_EncryptInit_ex(&ctx, NULL, NULL, key, iv)) {
fprintf(stderr, "Key/IV set failed\n");
ERR_print_errors_fp(stderr);
test1_exit(12);
}
if (an && !EVP_EncryptUpdate(&ctx, NULL, &outl, aad, an)) {
fprintf(stderr, "AAD set failed\n");
ERR_print_errors_fp(stderr);
test1_exit(13);
}
} else if (mode == EVP_CIPH_CCM_MODE) {
if (!EVP_EncryptInit_ex(&ctx, c, NULL, NULL, NULL)) {
fprintf(stderr, "EncryptInit failed\n");
ERR_print_errors_fp(stderr);
test1_exit(10);
}
if (!EVP_CIPHER_CTX_ctrl(&ctx, EVP_CTRL_CCM_SET_IVLEN, in, NULL)) {
fprintf(stderr, "IV length set failed\n");
ERR_print_errors_fp(stderr);
test1_exit(11);
}
if (!EVP_CIPHER_CTX_ctrl(&ctx, EVP_CTRL_CCM_SET_TAG, tn, NULL)) {
fprintf(stderr, "Tag length set failed\n");
ERR_print_errors_fp(stderr);
test1_exit(11);
}
if (!EVP_EncryptInit_ex(&ctx, NULL, NULL, key, iv)) {
fprintf(stderr, "Key/IV set failed\n");
ERR_print_errors_fp(stderr);
test1_exit(12);
}
if (!EVP_EncryptUpdate(&ctx, NULL, &outl, NULL, pn)) {
fprintf(stderr, "Plaintext length set failed\n");
ERR_print_errors_fp(stderr);
test1_exit(12);
}
if (an && !EVP_EncryptUpdate(&ctx, NULL, &outl, aad, an)) {
fprintf(stderr, "AAD set failed\n");
ERR_print_errors_fp(stderr);
test1_exit(13);
}
} else if (mode == EVP_CIPH_WRAP_MODE) {
if (!EVP_EncryptInit_ex(&ctx, c, NULL, key, in ? iv : NULL)) {
fprintf(stderr, "EncryptInit failed\n");
ERR_print_errors_fp(stderr);
test1_exit(10);
}
} else if (!EVP_EncryptInit_ex(&ctx, c, NULL, key, iv)) {
fprintf(stderr, "EncryptInit failed\n");
ERR_print_errors_fp(stderr);
test1_exit(10);
}
EVP_CIPHER_CTX_set_padding(&ctx, 0);
if (!EVP_EncryptUpdate(&ctx, out, &outl, plaintext, pn)) {
fprintf(stderr, "Encrypt failed\n");
ERR_print_errors_fp(stderr);
test1_exit(6);
}
if (!EVP_EncryptFinal_ex(&ctx, out + outl, &outl2)) {
fprintf(stderr, "EncryptFinal failed\n");
ERR_print_errors_fp(stderr);
test1_exit(7);
}
if (outl + outl2 != cn) {
fprintf(stderr, "Ciphertext length mismatch got %d expected %d\n",
outl + outl2, cn);
test1_exit(8);
}
if (memcmp(out, ciphertext, cn)) {
fprintf(stderr, "Ciphertext mismatch\n");
hexdump(stderr, "Got", out, cn);
hexdump(stderr, "Expected", ciphertext, cn);
test1_exit(9);
}
if (mode == EVP_CIPH_GCM_MODE || mode == EVP_CIPH_CCM_MODE) {
unsigned char rtag[16];
/*
* Note: EVP_CTRL_CCM_GET_TAG has same value as
* EVP_CTRL_GCM_GET_TAG
*/
if (!EVP_CIPHER_CTX_ctrl(&ctx, EVP_CTRL_GCM_GET_TAG, tn, rtag)) {
fprintf(stderr, "Get tag failed\n");
ERR_print_errors_fp(stderr);
test1_exit(14);
}
if (memcmp(rtag, tag, tn)) {
fprintf(stderr, "Tag mismatch\n");
hexdump(stderr, "Got", rtag, tn);
hexdump(stderr, "Expected", tag, tn);
test1_exit(9);
}
}
}
if (encdec <= 0) {
if (mode == EVP_CIPH_GCM_MODE) {
if (!EVP_DecryptInit_ex(&ctx, c, NULL, NULL, NULL)) {
fprintf(stderr, "EncryptInit failed\n");
ERR_print_errors_fp(stderr);
test1_exit(10);
}
if (!EVP_CIPHER_CTX_ctrl(&ctx, EVP_CTRL_GCM_SET_IVLEN, in, NULL)) {
fprintf(stderr, "IV length set failed\n");
ERR_print_errors_fp(stderr);
test1_exit(11);
}
if (!EVP_DecryptInit_ex(&ctx, NULL, NULL, key, iv)) {
fprintf(stderr, "Key/IV set failed\n");
ERR_print_errors_fp(stderr);
test1_exit(12);
}
if (!EVP_CIPHER_CTX_ctrl
(&ctx, EVP_CTRL_GCM_SET_TAG, tn, (void *)tag)) {
fprintf(stderr, "Set tag failed\n");
ERR_print_errors_fp(stderr);
test1_exit(14);
}
if (an && !EVP_DecryptUpdate(&ctx, NULL, &outl, aad, an)) {
fprintf(stderr, "AAD set failed\n");
ERR_print_errors_fp(stderr);
test1_exit(13);
}
} else if (mode == EVP_CIPH_CCM_MODE) {
if (!EVP_DecryptInit_ex(&ctx, c, NULL, NULL, NULL)) {
fprintf(stderr, "DecryptInit failed\n");
ERR_print_errors_fp(stderr);
test1_exit(10);
}
if (!EVP_CIPHER_CTX_ctrl(&ctx, EVP_CTRL_CCM_SET_IVLEN, in, NULL)) {
fprintf(stderr, "IV length set failed\n");
ERR_print_errors_fp(stderr);
test1_exit(11);
}
if (!EVP_CIPHER_CTX_ctrl
(&ctx, EVP_CTRL_CCM_SET_TAG, tn, (void *)tag)) {
fprintf(stderr, "Tag length set failed\n");
ERR_print_errors_fp(stderr);
test1_exit(11);
}
if (!EVP_DecryptInit_ex(&ctx, NULL, NULL, key, iv)) {
fprintf(stderr, "Key/Nonce set failed\n");
ERR_print_errors_fp(stderr);
test1_exit(12);
}
if (!EVP_DecryptUpdate(&ctx, NULL, &outl, NULL, pn)) {
fprintf(stderr, "Plaintext length set failed\n");
ERR_print_errors_fp(stderr);
test1_exit(12);
}
if (an && !EVP_EncryptUpdate(&ctx, NULL, &outl, aad, an)) {
fprintf(stderr, "AAD set failed\n");
ERR_print_errors_fp(stderr);
test1_exit(13);
}
} else if (mode == EVP_CIPH_WRAP_MODE) {
if (!EVP_DecryptInit_ex(&ctx, c, NULL, key, in ? iv : NULL)) {
fprintf(stderr, "EncryptInit failed\n");
ERR_print_errors_fp(stderr);
test1_exit(10);
}
} else if (!EVP_DecryptInit_ex(&ctx, c, NULL, key, iv)) {
fprintf(stderr, "DecryptInit failed\n");
ERR_print_errors_fp(stderr);
test1_exit(11);
}
EVP_CIPHER_CTX_set_padding(&ctx, 0);
if (!EVP_DecryptUpdate(&ctx, out, &outl, ciphertext, cn)) {
fprintf(stderr, "Decrypt failed\n");
ERR_print_errors_fp(stderr);
test1_exit(6);
}
if (mode != EVP_CIPH_CCM_MODE
&& !EVP_DecryptFinal_ex(&ctx, out + outl, &outl2)) {
fprintf(stderr, "DecryptFinal failed\n");
ERR_print_errors_fp(stderr);
test1_exit(7);
}
if (outl + outl2 != pn) {
fprintf(stderr, "Plaintext length mismatch got %d expected %d\n",
outl + outl2, pn);
test1_exit(8);
}
if (memcmp(out, plaintext, pn)) {
fprintf(stderr, "Plaintext mismatch\n");
hexdump(stderr, "Got", out, pn);
hexdump(stderr, "Expected", plaintext, pn);
test1_exit(9);
}
}
EVP_CIPHER_CTX_cleanup(&ctx);
printf("\n");
}
static int test_cipher(const char *cipher, const unsigned char *key, int kn,
const unsigned char *iv, int in,
const unsigned char *plaintext, int pn,
const unsigned char *ciphertext, int cn,
const unsigned char *aad, int an,
const unsigned char *tag, int tn, int encdec)
{
const EVP_CIPHER *c;
c = EVP_get_cipherbyname(cipher);
if (!c)
return 0;
test1(c, key, kn, iv, in, plaintext, pn, ciphertext, cn, aad, an, tag, tn,
encdec);
return 1;
}
static int test_digest(const char *digest,
const unsigned char *plaintext, int pn,
const unsigned char *ciphertext, unsigned int cn)
{
const EVP_MD *d;
EVP_MD_CTX ctx;
unsigned char md[EVP_MAX_MD_SIZE];
unsigned int mdn;
d = EVP_get_digestbyname(digest);
if (!d)
return 0;
printf("Testing digest %s\n", EVP_MD_name(d));
hexdump(stdout, "Plaintext", plaintext, pn);
hexdump(stdout, "Digest", ciphertext, cn);
EVP_MD_CTX_init(&ctx);
if (!EVP_DigestInit_ex(&ctx, d, NULL)) {
fprintf(stderr, "DigestInit failed\n");
ERR_print_errors_fp(stderr);
EXIT(100);
}
if (!EVP_DigestUpdate(&ctx, plaintext, pn)) {
fprintf(stderr, "DigestUpdate failed\n");
ERR_print_errors_fp(stderr);
EXIT(101);
}
if (!EVP_DigestFinal_ex(&ctx, md, &mdn)) {
fprintf(stderr, "DigestFinal failed\n");
ERR_print_errors_fp(stderr);
EXIT(101);
}
EVP_MD_CTX_cleanup(&ctx);
if (mdn != cn) {
fprintf(stderr, "Digest length mismatch, got %d expected %d\n", mdn,
cn);
EXIT(102);
}
if (memcmp(md, ciphertext, cn)) {
fprintf(stderr, "Digest mismatch\n");
hexdump(stderr, "Got", md, cn);
hexdump(stderr, "Expected", ciphertext, cn);
EXIT(103);
}
printf("\n");
EVP_MD_CTX_cleanup(&ctx);
return 1;
}
int main(int argc, char **argv)
{
const char *szTestFile;
FILE *f;
if (argc != 2) {
fprintf(stderr, "%s <test file>\n", argv[0]);
EXIT(1);
}
CRYPTO_malloc_debug_init();
CRYPTO_set_mem_debug_options(V_CRYPTO_MDEBUG_ALL);
CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON);
szTestFile = argv[1];
f = fopen(szTestFile, "r");
if (!f) {
perror(szTestFile);
EXIT(2);
}
ERR_load_crypto_strings();
/* Load up the software EVP_CIPHER and EVP_MD definitions */
OpenSSL_add_all_ciphers();
OpenSSL_add_all_digests();
#ifndef OPENSSL_NO_ENGINE
/* Load all compiled-in ENGINEs */
ENGINE_load_builtin_engines();
#endif
#if 0
OPENSSL_config();
#endif
#ifndef OPENSSL_NO_ENGINE
/*
* Register all available ENGINE implementations of ciphers and digests.
* This could perhaps be changed to "ENGINE_register_all_complete()"?
*/
ENGINE_register_all_ciphers();
ENGINE_register_all_digests();
/*
* If we add command-line options, this statement should be switchable.
* It'll prevent ENGINEs being ENGINE_init()ialised for cipher/digest use
* if they weren't already initialised.
*/
/* ENGINE_set_cipher_flags(ENGINE_CIPHER_FLAG_NOINIT); */
#endif
for (;;) {
char line[4096];
char *p;
char *cipher;
unsigned char *iv, *key, *plaintext, *ciphertext, *aad, *tag;
int encdec;
int kn, in, pn, cn;
int an = 0;
int tn = 0;
- if (!fgets((char *)line, sizeof line, f))
+ if (!fgets((char *)line, sizeof(line), f))
break;
if (line[0] == '#' || line[0] == '\n')
continue;
p = line;
cipher = sstrsep(&p, ":");
key = ustrsep(&p, ":");
iv = ustrsep(&p, ":");
plaintext = ustrsep(&p, ":");
ciphertext = ustrsep(&p, ":");
if (p[-1] == '\n') {
encdec = -1;
p[-1] = '\0';
tag = aad = NULL;
an = tn = 0;
} else {
aad = ustrsep(&p, ":");
tag = ustrsep(&p, ":");
if (tag == NULL) {
p = (char *)aad;
tag = aad = NULL;
an = tn = 0;
}
if (p[-1] == '\n') {
encdec = -1;
p[-1] = '\0';
} else
encdec = atoi(sstrsep(&p, "\n"));
}
kn = convert(key);
in = convert(iv);
pn = convert(plaintext);
cn = convert(ciphertext);
if (aad) {
an = convert(aad);
tn = convert(tag);
}
if (!test_cipher
(cipher, key, kn, iv, in, plaintext, pn, ciphertext, cn, aad, an,
tag, tn, encdec)
&& !test_digest(cipher, plaintext, pn, ciphertext, cn)) {
#ifdef OPENSSL_NO_AES
if (strstr(cipher, "AES") == cipher) {
fprintf(stdout, "Cipher disabled, skipping %s\n", cipher);
continue;
}
#endif
#ifdef OPENSSL_NO_DES
if (strstr(cipher, "DES") == cipher) {
fprintf(stdout, "Cipher disabled, skipping %s\n", cipher);
continue;
}
#endif
#ifdef OPENSSL_NO_RC4
if (strstr(cipher, "RC4") == cipher) {
fprintf(stdout, "Cipher disabled, skipping %s\n", cipher);
continue;
}
#endif
#ifdef OPENSSL_NO_CAMELLIA
if (strstr(cipher, "CAMELLIA") == cipher) {
fprintf(stdout, "Cipher disabled, skipping %s\n", cipher);
continue;
}
#endif
#ifdef OPENSSL_NO_SEED
if (strstr(cipher, "SEED") == cipher) {
fprintf(stdout, "Cipher disabled, skipping %s\n", cipher);
continue;
}
#endif
fprintf(stderr, "Can't find %s\n", cipher);
EXIT(3);
}
}
fclose(f);
#ifndef OPENSSL_NO_ENGINE
ENGINE_cleanup();
#endif
EVP_cleanup();
CRYPTO_cleanup_all_ex_data();
ERR_remove_thread_state(NULL);
ERR_free_strings();
CRYPTO_mem_leaks_fp(stderr);
return 0;
}
diff --git a/crypto/evp/openbsd_hw.c b/crypto/evp/openbsd_hw.c
index 07decf267433..24a358e54306 100644
--- a/crypto/evp/openbsd_hw.c
+++ b/crypto/evp/openbsd_hw.c
@@ -1,453 +1,453 @@
/* Written by Ben Laurie, 2001 */
/*
* Copyright (c) 2001 The OpenSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* openssl-core@openssl.org.
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.openssl.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <openssl/evp.h>
#include <openssl/objects.h>
#include <openssl/rsa.h>
#include "evp_locl.h"
/*
* This stuff should now all be supported through
* crypto/engine/hw_openbsd_dev_crypto.c unless I botched it up
*/
static void *dummy = &dummy;
#if 0
/* check flag after OpenSSL headers to ensure make depend works */
# ifdef OPENSSL_OPENBSD_DEV_CRYPTO
# include <fcntl.h>
# include <stdio.h>
# include <errno.h>
# include <sys/ioctl.h>
# include <crypto/cryptodev.h>
# include <unistd.h>
# include <assert.h>
/* longest key supported in hardware */
# define MAX_HW_KEY 24
# define MAX_HW_IV 8
# define MD5_DIGEST_LENGTH 16
# define MD5_CBLOCK 64
static int fd;
static int dev_failed;
typedef struct session_op session_op;
# define CDATA(ctx) EVP_C_DATA(session_op,ctx)
static void err(const char *str)
{
fprintf(stderr, "%s: errno %d\n", str, errno);
}
static int dev_crypto_init(session_op *ses)
{
if (dev_failed)
return 0;
if (!fd) {
int cryptodev_fd;
if ((cryptodev_fd = open("/dev/crypto", O_RDWR, 0)) < 0) {
err("/dev/crypto");
dev_failed = 1;
return 0;
}
if (ioctl(cryptodev_fd, CRIOGET, &fd) == -1) {
err("CRIOGET failed");
close(cryptodev_fd);
dev_failed = 1;
return 0;
}
close(cryptodev_fd);
}
assert(ses);
- memset(ses, '\0', sizeof *ses);
+ memset(ses, '\0', sizeof(*ses));
return 1;
}
static int dev_crypto_cleanup(EVP_CIPHER_CTX *ctx)
{
if (ioctl(fd, CIOCFSESSION, &CDATA(ctx)->ses) == -1)
err("CIOCFSESSION failed");
OPENSSL_free(CDATA(ctx)->key);
return 1;
}
static int dev_crypto_init_key(EVP_CIPHER_CTX *ctx, int cipher,
const unsigned char *key, int klen)
{
if (!dev_crypto_init(CDATA(ctx)))
return 0;
CDATA(ctx)->key = OPENSSL_malloc(MAX_HW_KEY);
if (CDATA(ctx)->key == NULL {
err("CDATA(ctx)->key memory allocation failed");
return 0;
}
assert(ctx->cipher->iv_len <= MAX_HW_IV);
memcpy(CDATA(ctx)->key, key, klen);
CDATA(ctx)->cipher = cipher;
CDATA(ctx)->keylen = klen;
if (ioctl(fd, CIOCGSESSION, CDATA(ctx)) == -1) {
err("CIOCGSESSION failed");
return 0;
}
return 1;
}
static int dev_crypto_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
const unsigned char *in, unsigned int inl)
{
struct crypt_op cryp;
unsigned char lb[MAX_HW_IV];
if (!inl)
return 1;
assert(CDATA(ctx));
assert(!dev_failed);
- memset(&cryp, '\0', sizeof cryp);
+ memset(&cryp, '\0', sizeof(cryp));
cryp.ses = CDATA(ctx)->ses;
cryp.op = ctx->encrypt ? COP_ENCRYPT : COP_DECRYPT;
cryp.flags = 0;
cryp.len = inl;
assert((inl & (ctx->cipher->block_size - 1)) == 0);
cryp.src = (caddr_t) in;
cryp.dst = (caddr_t) out;
cryp.mac = 0;
if (ctx->cipher->iv_len)
cryp.iv = (caddr_t) ctx->iv;
if (!ctx->encrypt)
memcpy(lb, &in[cryp.len - ctx->cipher->iv_len], ctx->cipher->iv_len);
if (ioctl(fd, CIOCCRYPT, &cryp) == -1) {
if (errno == EINVAL) { /* buffers are misaligned */
unsigned int cinl = 0;
char *cin = NULL;
char *cout = NULL;
/* NB: this can only make cinl != inl with stream ciphers */
cinl = (inl + 3) / 4 * 4;
if (((unsigned long)in & 3) || cinl != inl) {
cin = OPENSSL_malloc(cinl);
if (cin == NULL) {
err("cin - memory allocation failed");
abort();
return 0;
}
memcpy(cin, in, inl);
cryp.src = cin;
}
if (((unsigned long)out & 3) || cinl != inl) {
cout = OPENSSL_malloc(cinl);
cryp.dst = cout;
}
cryp.len = cinl;
if (ioctl(fd, CIOCCRYPT, &cryp) == -1) {
err("CIOCCRYPT(2) failed");
printf("src=%p dst=%p\n", cryp.src, cryp.dst);
abort();
return 0;
}
if (cout) {
memcpy(out, cout, inl);
OPENSSL_free(cout);
}
if (cin)
OPENSSL_free(cin);
} else {
err("CIOCCRYPT failed");
abort();
return 0;
}
}
if (ctx->encrypt)
memcpy(ctx->iv, &out[cryp.len - ctx->cipher->iv_len],
ctx->cipher->iv_len);
else
memcpy(ctx->iv, lb, ctx->cipher->iv_len);
return 1;
}
static int dev_crypto_des_ede3_init_key(EVP_CIPHER_CTX *ctx,
const unsigned char *key,
const unsigned char *iv, int enc)
{
return dev_crypto_init_key(ctx, CRYPTO_3DES_CBC, key, 24);
}
# define dev_crypto_des_ede3_cbc_cipher dev_crypto_cipher
BLOCK_CIPHER_def_cbc(dev_crypto_des_ede3, session_op, NID_des_ede3, 8, 24, 8,
0, dev_crypto_des_ede3_init_key,
dev_crypto_cleanup,
EVP_CIPHER_set_asn1_iv, EVP_CIPHER_get_asn1_iv, NULL)
static int dev_crypto_rc4_init_key(EVP_CIPHER_CTX *ctx,
const unsigned char *key,
const unsigned char *iv, int enc)
{
return dev_crypto_init_key(ctx, CRYPTO_ARC4, key, 16);
}
static const EVP_CIPHER r4_cipher = {
NID_rc4,
1, 16, 0, /* FIXME: key should be up to 256 bytes */
EVP_CIPH_VARIABLE_LENGTH,
dev_crypto_rc4_init_key,
dev_crypto_cipher,
dev_crypto_cleanup,
sizeof(session_op),
NULL,
NULL,
NULL
};
const EVP_CIPHER *EVP_dev_crypto_rc4(void)
{
return &r4_cipher;
}
typedef struct {
session_op sess;
char *data;
int len;
unsigned char md[EVP_MAX_MD_SIZE];
} MD_DATA;
static int dev_crypto_init_digest(MD_DATA *md_data, int mac)
{
if (!dev_crypto_init(&md_data->sess))
return 0;
md_data->len = 0;
md_data->data = NULL;
md_data->sess.mac = mac;
if (ioctl(fd, CIOCGSESSION, &md_data->sess) == -1) {
err("CIOCGSESSION failed");
return 0;
}
return 1;
}
static int dev_crypto_cleanup_digest(MD_DATA *md_data)
{
if (ioctl(fd, CIOCFSESSION, &md_data->sess.ses) == -1) {
err("CIOCFSESSION failed");
return 0;
}
return 1;
}
/* FIXME: if device can do chained MACs, then don't accumulate */
/* FIXME: move accumulation to the framework */
static int dev_crypto_md5_init(EVP_MD_CTX *ctx)
{
return dev_crypto_init_digest(ctx->md_data, CRYPTO_MD5);
}
static int do_digest(int ses, unsigned char *md, const void *data, int len)
{
struct crypt_op cryp;
static unsigned char md5zero[16] = {
0xd4, 0x1d, 0x8c, 0xd9, 0x8f, 0x00, 0xb2, 0x04,
0xe9, 0x80, 0x09, 0x98, 0xec, 0xf8, 0x42, 0x7e
};
/* some cards can't do zero length */
if (!len) {
memcpy(md, md5zero, 16);
return 1;
}
- memset(&cryp, '\0', sizeof cryp);
+ memset(&cryp, '\0', sizeof(cryp));
cryp.ses = ses;
cryp.op = COP_ENCRYPT; /* required to do the MAC rather than check
* it */
cryp.len = len;
cryp.src = (caddr_t) data;
cryp.dst = (caddr_t) data; // FIXME!!!
cryp.mac = (caddr_t) md;
if (ioctl(fd, CIOCCRYPT, &cryp) == -1) {
if (errno == EINVAL) { /* buffer is misaligned */
char *dcopy;
dcopy = OPENSSL_malloc(len);
if (dcopy == NULL) {
err("dcopy - memory allocation failed");
abort();
return 0;
}
memcpy(dcopy, data, len);
cryp.src = dcopy;
cryp.dst = cryp.src; // FIXME!!!
if (ioctl(fd, CIOCCRYPT, &cryp) == -1) {
err("CIOCCRYPT(MAC2) failed");
abort();
return 0;
}
OPENSSL_free(dcopy);
} else {
err("CIOCCRYPT(MAC) failed");
abort();
return 0;
}
}
// printf("done\n");
return 1;
}
static int dev_crypto_md5_update(EVP_MD_CTX *ctx, const void *data,
unsigned long len)
{
MD_DATA *md_data = ctx->md_data;
if (ctx->flags & EVP_MD_CTX_FLAG_ONESHOT)
return do_digest(md_data->sess.ses, md_data->md, data, len);
md_data->data = OPENSSL_realloc(md_data->data, md_data->len + len);
if (md_data->data == NULL) {
err("DEV_CRYPTO_MD5_UPDATE: unable to allocate memory");
abort();
}
memcpy(md_data->data + md_data->len, data, len);
md_data->len += len;
return 1;
}
static int dev_crypto_md5_final(EVP_MD_CTX *ctx, unsigned char *md)
{
int ret;
MD_DATA *md_data = ctx->md_data;
if (ctx->flags & EVP_MD_CTX_FLAG_ONESHOT) {
memcpy(md, md_data->md, MD5_DIGEST_LENGTH);
ret = 1;
} else {
ret = do_digest(md_data->sess.ses, md, md_data->data, md_data->len);
OPENSSL_free(md_data->data);
md_data->data = NULL;
md_data->len = 0;
}
return ret;
}
static int dev_crypto_md5_copy(EVP_MD_CTX *to, const EVP_MD_CTX *from)
{
const MD_DATA *from_md = from->md_data;
MD_DATA *to_md = to->md_data;
// How do we copy sessions?
assert(from->digest->flags & EVP_MD_FLAG_ONESHOT);
to_md->data = OPENSSL_malloc(from_md->len);
if (to_md->data == NULL) {
err("DEV_CRYPTO_MD5_COPY: unable to allocate memory");
abort();
}
memcpy(to_md->data, from_md->data, from_md->len);
return 1;
}
static int dev_crypto_md5_cleanup(EVP_MD_CTX *ctx)
{
return dev_crypto_cleanup_digest(ctx->md_data);
}
static const EVP_MD md5_md = {
NID_md5,
NID_md5WithRSAEncryption,
MD5_DIGEST_LENGTH,
EVP_MD_FLAG_ONESHOT, // XXX: set according to device info...
dev_crypto_md5_init,
dev_crypto_md5_update,
dev_crypto_md5_final,
dev_crypto_md5_copy,
dev_crypto_md5_cleanup,
EVP_PKEY_RSA_method,
MD5_CBLOCK,
sizeof(MD_DATA),
};
const EVP_MD *EVP_dev_crypto_md5(void)
{
return &md5_md;
}
# endif
#endif
diff --git a/crypto/evp/p5_crpt2.c b/crypto/evp/p5_crpt2.c
index f2ae1e5790d0..46fefa9ad584 100644
--- a/crypto/evp/p5_crpt2.c
+++ b/crypto/evp/p5_crpt2.c
@@ -1,334 +1,334 @@
/* p5_crpt2.c */
/*
* Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL project
* 1999.
*/
/* ====================================================================
* Copyright (c) 1999-2006 The OpenSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* licensing@OpenSSL.org.
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*
* This product includes cryptographic software written by Eric Young
* (eay@cryptsoft.com). This product includes software written by Tim
* Hudson (tjh@cryptsoft.com).
*
*/
#include <stdio.h>
#include <stdlib.h>
#include "cryptlib.h"
#if !defined(OPENSSL_NO_HMAC) && !defined(OPENSSL_NO_SHA)
# include <openssl/x509.h>
# include <openssl/evp.h>
# include <openssl/hmac.h>
# include "evp_locl.h"
/* set this to print out info about the keygen algorithm */
/* #define DEBUG_PKCS5V2 */
# ifdef DEBUG_PKCS5V2
static void h__dump(const unsigned char *p, int len);
# endif
/*
* This is an implementation of PKCS#5 v2.0 password based encryption key
* derivation function PBKDF2. SHA1 version verified against test vectors
* posted by Peter Gutmann <pgut001@cs.auckland.ac.nz> to the PKCS-TNG
* <pkcs-tng@rsa.com> mailing list.
*/
int PKCS5_PBKDF2_HMAC(const char *pass, int passlen,
const unsigned char *salt, int saltlen, int iter,
const EVP_MD *digest, int keylen, unsigned char *out)
{
unsigned char digtmp[EVP_MAX_MD_SIZE], *p, itmp[4];
int cplen, j, k, tkeylen, mdlen;
unsigned long i = 1;
HMAC_CTX hctx_tpl, hctx;
mdlen = EVP_MD_size(digest);
if (mdlen < 0)
return 0;
HMAC_CTX_init(&hctx_tpl);
p = out;
tkeylen = keylen;
if (!pass)
passlen = 0;
else if (passlen == -1)
passlen = strlen(pass);
if (!HMAC_Init_ex(&hctx_tpl, pass, passlen, digest, NULL)) {
HMAC_CTX_cleanup(&hctx_tpl);
return 0;
}
while (tkeylen) {
if (tkeylen > mdlen)
cplen = mdlen;
else
cplen = tkeylen;
/*
* We are unlikely to ever use more than 256 blocks (5120 bits!) but
* just in case...
*/
itmp[0] = (unsigned char)((i >> 24) & 0xff);
itmp[1] = (unsigned char)((i >> 16) & 0xff);
itmp[2] = (unsigned char)((i >> 8) & 0xff);
itmp[3] = (unsigned char)(i & 0xff);
if (!HMAC_CTX_copy(&hctx, &hctx_tpl)) {
HMAC_CTX_cleanup(&hctx_tpl);
return 0;
}
if (!HMAC_Update(&hctx, salt, saltlen)
|| !HMAC_Update(&hctx, itmp, 4)
|| !HMAC_Final(&hctx, digtmp, NULL)) {
HMAC_CTX_cleanup(&hctx_tpl);
HMAC_CTX_cleanup(&hctx);
return 0;
}
HMAC_CTX_cleanup(&hctx);
memcpy(p, digtmp, cplen);
for (j = 1; j < iter; j++) {
if (!HMAC_CTX_copy(&hctx, &hctx_tpl)) {
HMAC_CTX_cleanup(&hctx_tpl);
return 0;
}
if (!HMAC_Update(&hctx, digtmp, mdlen)
|| !HMAC_Final(&hctx, digtmp, NULL)) {
HMAC_CTX_cleanup(&hctx_tpl);
HMAC_CTX_cleanup(&hctx);
return 0;
}
HMAC_CTX_cleanup(&hctx);
for (k = 0; k < cplen; k++)
p[k] ^= digtmp[k];
}
tkeylen -= cplen;
i++;
p += cplen;
}
HMAC_CTX_cleanup(&hctx_tpl);
# ifdef DEBUG_PKCS5V2
fprintf(stderr, "Password:\n");
h__dump(pass, passlen);
fprintf(stderr, "Salt:\n");
h__dump(salt, saltlen);
fprintf(stderr, "Iteration count %d\n", iter);
fprintf(stderr, "Key:\n");
h__dump(out, keylen);
# endif
return 1;
}
int PKCS5_PBKDF2_HMAC_SHA1(const char *pass, int passlen,
const unsigned char *salt, int saltlen, int iter,
int keylen, unsigned char *out)
{
return PKCS5_PBKDF2_HMAC(pass, passlen, salt, saltlen, iter, EVP_sha1(),
keylen, out);
}
# ifdef DO_TEST
main()
{
unsigned char out[4];
unsigned char salt[] = { 0x12, 0x34, 0x56, 0x78 };
PKCS5_PBKDF2_HMAC_SHA1("password", -1, salt, 4, 5, 4, out);
fprintf(stderr, "Out %02X %02X %02X %02X\n",
out[0], out[1], out[2], out[3]);
}
# endif
/*
* Now the key derivation function itself. This is a bit evil because it has
* to check the ASN1 parameters are valid: and there are quite a few of
* them...
*/
int PKCS5_v2_PBE_keyivgen(EVP_CIPHER_CTX *ctx, const char *pass, int passlen,
ASN1_TYPE *param, const EVP_CIPHER *c,
const EVP_MD *md, int en_de)
{
const unsigned char *pbuf;
int plen;
PBE2PARAM *pbe2 = NULL;
const EVP_CIPHER *cipher;
int rv = 0;
if (param == NULL || param->type != V_ASN1_SEQUENCE ||
param->value.sequence == NULL) {
EVPerr(EVP_F_PKCS5_V2_PBE_KEYIVGEN, EVP_R_DECODE_ERROR);
goto err;
}
pbuf = param->value.sequence->data;
plen = param->value.sequence->length;
if (!(pbe2 = d2i_PBE2PARAM(NULL, &pbuf, plen))) {
EVPerr(EVP_F_PKCS5_V2_PBE_KEYIVGEN, EVP_R_DECODE_ERROR);
goto err;
}
/* See if we recognise the key derivation function */
if (OBJ_obj2nid(pbe2->keyfunc->algorithm) != NID_id_pbkdf2) {
EVPerr(EVP_F_PKCS5_V2_PBE_KEYIVGEN,
EVP_R_UNSUPPORTED_KEY_DERIVATION_FUNCTION);
goto err;
}
/*
* lets see if we recognise the encryption algorithm.
*/
cipher = EVP_get_cipherbyobj(pbe2->encryption->algorithm);
if (!cipher) {
EVPerr(EVP_F_PKCS5_V2_PBE_KEYIVGEN, EVP_R_UNSUPPORTED_CIPHER);
goto err;
}
/* Fixup cipher based on AlgorithmIdentifier */
if (!EVP_CipherInit_ex(ctx, cipher, NULL, NULL, NULL, en_de))
goto err;
if (EVP_CIPHER_asn1_to_param(ctx, pbe2->encryption->parameter) < 0) {
EVPerr(EVP_F_PKCS5_V2_PBE_KEYIVGEN, EVP_R_CIPHER_PARAMETER_ERROR);
goto err;
}
rv = PKCS5_v2_PBKDF2_keyivgen(ctx, pass, passlen,
pbe2->keyfunc->parameter, c, md, en_de);
err:
PBE2PARAM_free(pbe2);
return rv;
}
int PKCS5_v2_PBKDF2_keyivgen(EVP_CIPHER_CTX *ctx, const char *pass,
int passlen, ASN1_TYPE *param,
const EVP_CIPHER *c, const EVP_MD *md, int en_de)
{
unsigned char *salt, key[EVP_MAX_KEY_LENGTH];
const unsigned char *pbuf;
int saltlen, iter, plen;
int rv = 0;
unsigned int keylen = 0;
int prf_nid, hmac_md_nid;
PBKDF2PARAM *kdf = NULL;
const EVP_MD *prfmd;
if (EVP_CIPHER_CTX_cipher(ctx) == NULL) {
EVPerr(EVP_F_PKCS5_V2_PBKDF2_KEYIVGEN, EVP_R_NO_CIPHER_SET);
goto err;
}
keylen = EVP_CIPHER_CTX_key_length(ctx);
- OPENSSL_assert(keylen <= sizeof key);
+ OPENSSL_assert(keylen <= sizeof(key));
/* Decode parameter */
if (!param || (param->type != V_ASN1_SEQUENCE)) {
EVPerr(EVP_F_PKCS5_V2_PBKDF2_KEYIVGEN, EVP_R_DECODE_ERROR);
goto err;
}
pbuf = param->value.sequence->data;
plen = param->value.sequence->length;
if (!(kdf = d2i_PBKDF2PARAM(NULL, &pbuf, plen))) {
EVPerr(EVP_F_PKCS5_V2_PBKDF2_KEYIVGEN, EVP_R_DECODE_ERROR);
goto err;
}
keylen = EVP_CIPHER_CTX_key_length(ctx);
/* Now check the parameters of the kdf */
if (kdf->keylength && (ASN1_INTEGER_get(kdf->keylength) != (int)keylen)) {
EVPerr(EVP_F_PKCS5_V2_PBKDF2_KEYIVGEN, EVP_R_UNSUPPORTED_KEYLENGTH);
goto err;
}
if (kdf->prf)
prf_nid = OBJ_obj2nid(kdf->prf->algorithm);
else
prf_nid = NID_hmacWithSHA1;
if (!EVP_PBE_find(EVP_PBE_TYPE_PRF, prf_nid, NULL, &hmac_md_nid, 0)) {
EVPerr(EVP_F_PKCS5_V2_PBKDF2_KEYIVGEN, EVP_R_UNSUPPORTED_PRF);
goto err;
}
prfmd = EVP_get_digestbynid(hmac_md_nid);
if (prfmd == NULL) {
EVPerr(EVP_F_PKCS5_V2_PBKDF2_KEYIVGEN, EVP_R_UNSUPPORTED_PRF);
goto err;
}
if (kdf->salt->type != V_ASN1_OCTET_STRING) {
EVPerr(EVP_F_PKCS5_V2_PBKDF2_KEYIVGEN, EVP_R_UNSUPPORTED_SALT_TYPE);
goto err;
}
/* it seems that its all OK */
salt = kdf->salt->value.octet_string->data;
saltlen = kdf->salt->value.octet_string->length;
iter = ASN1_INTEGER_get(kdf->iter);
if (!PKCS5_PBKDF2_HMAC(pass, passlen, salt, saltlen, iter, prfmd,
keylen, key))
goto err;
rv = EVP_CipherInit_ex(ctx, NULL, NULL, key, NULL, en_de);
err:
OPENSSL_cleanse(key, keylen);
PBKDF2PARAM_free(kdf);
return rv;
}
# ifdef DEBUG_PKCS5V2
static void h__dump(const unsigned char *p, int len)
{
for (; len--; p++)
fprintf(stderr, "%02X ", *p);
fprintf(stderr, "\n");
}
# endif
#endif
diff --git a/crypto/hmac/hmac.c b/crypto/hmac/hmac.c
index 213504e85fee..023ec456f94c 100644
--- a/crypto/hmac/hmac.c
+++ b/crypto/hmac/hmac.c
@@ -1,268 +1,268 @@
/* crypto/hmac/hmac.c */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "cryptlib.h"
#include <openssl/hmac.h>
#ifdef OPENSSL_FIPS
# include <openssl/fips.h>
#endif
int HMAC_Init_ex(HMAC_CTX *ctx, const void *key, int len,
const EVP_MD *md, ENGINE *impl)
{
int i, j, reset = 0;
unsigned char pad[HMAC_MAX_MD_CBLOCK];
#ifdef OPENSSL_FIPS
/* If FIPS mode switch to approved implementation if possible */
if (FIPS_mode()) {
const EVP_MD *fipsmd;
if (md) {
fipsmd = FIPS_get_digestbynid(EVP_MD_type(md));
if (fipsmd)
md = fipsmd;
}
}
if (FIPS_mode()) {
/* If we have an ENGINE need to allow non FIPS */
if ((impl || ctx->i_ctx.engine)
&& !(ctx->i_ctx.flags & EVP_CIPH_FLAG_NON_FIPS_ALLOW)) {
EVPerr(EVP_F_HMAC_INIT_EX, EVP_R_DISABLED_FOR_FIPS);
return 0;
}
/*
* Other algorithm blocking will be done in FIPS_cmac_init, via
* FIPS_hmac_init_ex().
*/
if (!impl && !ctx->i_ctx.engine)
return FIPS_hmac_init_ex(ctx, key, len, md, NULL);
}
#endif
/* If we are changing MD then we must have a key */
if (md != NULL && md != ctx->md && (key == NULL || len < 0))
return 0;
if (md != NULL) {
reset = 1;
ctx->md = md;
} else if (ctx->md) {
md = ctx->md;
} else {
return 0;
}
if (key != NULL) {
reset = 1;
j = EVP_MD_block_size(md);
OPENSSL_assert(j <= (int)sizeof(ctx->key));
if (j < len) {
if (!EVP_DigestInit_ex(&ctx->md_ctx, md, impl))
goto err;
if (!EVP_DigestUpdate(&ctx->md_ctx, key, len))
goto err;
if (!EVP_DigestFinal_ex(&(ctx->md_ctx), ctx->key,
&ctx->key_length))
goto err;
} else {
if (len < 0 || len > (int)sizeof(ctx->key))
return 0;
memcpy(ctx->key, key, len);
ctx->key_length = len;
}
if (ctx->key_length != HMAC_MAX_MD_CBLOCK)
memset(&ctx->key[ctx->key_length], 0,
HMAC_MAX_MD_CBLOCK - ctx->key_length);
}
if (reset) {
for (i = 0; i < HMAC_MAX_MD_CBLOCK; i++)
pad[i] = 0x36 ^ ctx->key[i];
if (!EVP_DigestInit_ex(&ctx->i_ctx, md, impl))
goto err;
if (!EVP_DigestUpdate(&ctx->i_ctx, pad, EVP_MD_block_size(md)))
goto err;
for (i = 0; i < HMAC_MAX_MD_CBLOCK; i++)
pad[i] = 0x5c ^ ctx->key[i];
if (!EVP_DigestInit_ex(&ctx->o_ctx, md, impl))
goto err;
if (!EVP_DigestUpdate(&ctx->o_ctx, pad, EVP_MD_block_size(md)))
goto err;
}
if (!EVP_MD_CTX_copy_ex(&ctx->md_ctx, &ctx->i_ctx))
goto err;
return 1;
err:
return 0;
}
int HMAC_Init(HMAC_CTX *ctx, const void *key, int len, const EVP_MD *md)
{
if (key && md)
HMAC_CTX_init(ctx);
return HMAC_Init_ex(ctx, key, len, md, NULL);
}
int HMAC_Update(HMAC_CTX *ctx, const unsigned char *data, size_t len)
{
#ifdef OPENSSL_FIPS
if (FIPS_mode() && !ctx->i_ctx.engine)
return FIPS_hmac_update(ctx, data, len);
#endif
if (!ctx->md)
return 0;
return EVP_DigestUpdate(&ctx->md_ctx, data, len);
}
int HMAC_Final(HMAC_CTX *ctx, unsigned char *md, unsigned int *len)
{
unsigned int i;
unsigned char buf[EVP_MAX_MD_SIZE];
#ifdef OPENSSL_FIPS
if (FIPS_mode() && !ctx->i_ctx.engine)
return FIPS_hmac_final(ctx, md, len);
#endif
if (!ctx->md)
goto err;
if (!EVP_DigestFinal_ex(&ctx->md_ctx, buf, &i))
goto err;
if (!EVP_MD_CTX_copy_ex(&ctx->md_ctx, &ctx->o_ctx))
goto err;
if (!EVP_DigestUpdate(&ctx->md_ctx, buf, i))
goto err;
if (!EVP_DigestFinal_ex(&ctx->md_ctx, md, len))
goto err;
return 1;
err:
return 0;
}
void HMAC_CTX_init(HMAC_CTX *ctx)
{
EVP_MD_CTX_init(&ctx->i_ctx);
EVP_MD_CTX_init(&ctx->o_ctx);
EVP_MD_CTX_init(&ctx->md_ctx);
ctx->md = NULL;
}
int HMAC_CTX_copy(HMAC_CTX *dctx, HMAC_CTX *sctx)
{
if (!EVP_MD_CTX_copy(&dctx->i_ctx, &sctx->i_ctx))
goto err;
if (!EVP_MD_CTX_copy(&dctx->o_ctx, &sctx->o_ctx))
goto err;
if (!EVP_MD_CTX_copy(&dctx->md_ctx, &sctx->md_ctx))
goto err;
memcpy(dctx->key, sctx->key, HMAC_MAX_MD_CBLOCK);
dctx->key_length = sctx->key_length;
dctx->md = sctx->md;
return 1;
err:
return 0;
}
void HMAC_CTX_cleanup(HMAC_CTX *ctx)
{
#ifdef OPENSSL_FIPS
if (FIPS_mode() && !ctx->i_ctx.engine) {
FIPS_hmac_ctx_cleanup(ctx);
return;
}
#endif
EVP_MD_CTX_cleanup(&ctx->i_ctx);
EVP_MD_CTX_cleanup(&ctx->o_ctx);
EVP_MD_CTX_cleanup(&ctx->md_ctx);
- OPENSSL_cleanse(ctx, sizeof *ctx);
+ OPENSSL_cleanse(ctx, sizeof(*ctx));
}
unsigned char *HMAC(const EVP_MD *evp_md, const void *key, int key_len,
const unsigned char *d, size_t n, unsigned char *md,
unsigned int *md_len)
{
HMAC_CTX c;
static unsigned char m[EVP_MAX_MD_SIZE];
if (md == NULL)
md = m;
HMAC_CTX_init(&c);
if (!HMAC_Init(&c, key, key_len, evp_md))
goto err;
if (!HMAC_Update(&c, d, n))
goto err;
if (!HMAC_Final(&c, md, md_len))
goto err;
HMAC_CTX_cleanup(&c);
return md;
err:
HMAC_CTX_cleanup(&c);
return NULL;
}
void HMAC_CTX_set_flags(HMAC_CTX *ctx, unsigned long flags)
{
EVP_MD_CTX_set_flags(&ctx->i_ctx, flags);
EVP_MD_CTX_set_flags(&ctx->o_ctx, flags);
EVP_MD_CTX_set_flags(&ctx->md_ctx, flags);
}
diff --git a/crypto/jpake/jpake.c b/crypto/jpake/jpake.c
index 2ba75f0172c1..daf27228352a 100644
--- a/crypto/jpake/jpake.c
+++ b/crypto/jpake/jpake.c
@@ -1,516 +1,516 @@
#include "jpake.h"
#include <openssl/crypto.h>
#include <openssl/sha.h>
#include <openssl/err.h>
#include <memory.h>
#include <string.h>
/*
* In the definition, (xa, xb, xc, xd) are Alice's (x1, x2, x3, x4) or
* Bob's (x3, x4, x1, x2). If you see what I mean.
*/
typedef struct {
char *name; /* Must be unique */
char *peer_name;
BIGNUM *p;
BIGNUM *g;
BIGNUM *q;
BIGNUM *gxc; /* Alice's g^{x3} or Bob's g^{x1} */
BIGNUM *gxd; /* Alice's g^{x4} or Bob's g^{x2} */
} JPAKE_CTX_PUBLIC;
struct JPAKE_CTX {
JPAKE_CTX_PUBLIC p;
BIGNUM *secret; /* The shared secret */
BN_CTX *ctx;
BIGNUM *xa; /* Alice's x1 or Bob's x3 */
BIGNUM *xb; /* Alice's x2 or Bob's x4 */
BIGNUM *key; /* The calculated (shared) key */
};
static void JPAKE_ZKP_init(JPAKE_ZKP *zkp)
{
zkp->gr = BN_new();
zkp->b = BN_new();
}
static void JPAKE_ZKP_release(JPAKE_ZKP *zkp)
{
BN_free(zkp->b);
BN_free(zkp->gr);
}
/* Two birds with one stone - make the global name as expected */
#define JPAKE_STEP_PART_init JPAKE_STEP2_init
#define JPAKE_STEP_PART_release JPAKE_STEP2_release
void JPAKE_STEP_PART_init(JPAKE_STEP_PART *p)
{
p->gx = BN_new();
JPAKE_ZKP_init(&p->zkpx);
}
void JPAKE_STEP_PART_release(JPAKE_STEP_PART *p)
{
JPAKE_ZKP_release(&p->zkpx);
BN_free(p->gx);
}
void JPAKE_STEP1_init(JPAKE_STEP1 *s1)
{
JPAKE_STEP_PART_init(&s1->p1);
JPAKE_STEP_PART_init(&s1->p2);
}
void JPAKE_STEP1_release(JPAKE_STEP1 *s1)
{
JPAKE_STEP_PART_release(&s1->p2);
JPAKE_STEP_PART_release(&s1->p1);
}
static void JPAKE_CTX_init(JPAKE_CTX *ctx, const char *name,
const char *peer_name, const BIGNUM *p,
const BIGNUM *g, const BIGNUM *q,
const BIGNUM *secret)
{
ctx->p.name = OPENSSL_strdup(name);
ctx->p.peer_name = OPENSSL_strdup(peer_name);
ctx->p.p = BN_dup(p);
ctx->p.g = BN_dup(g);
ctx->p.q = BN_dup(q);
ctx->secret = BN_dup(secret);
ctx->p.gxc = BN_new();
ctx->p.gxd = BN_new();
ctx->xa = BN_new();
ctx->xb = BN_new();
ctx->key = BN_new();
ctx->ctx = BN_CTX_new();
}
static void JPAKE_CTX_release(JPAKE_CTX *ctx)
{
BN_CTX_free(ctx->ctx);
BN_clear_free(ctx->key);
BN_clear_free(ctx->xb);
BN_clear_free(ctx->xa);
BN_free(ctx->p.gxd);
BN_free(ctx->p.gxc);
BN_clear_free(ctx->secret);
BN_free(ctx->p.q);
BN_free(ctx->p.g);
BN_free(ctx->p.p);
OPENSSL_free(ctx->p.peer_name);
OPENSSL_free(ctx->p.name);
- memset(ctx, '\0', sizeof *ctx);
+ memset(ctx, '\0', sizeof(*ctx));
}
JPAKE_CTX *JPAKE_CTX_new(const char *name, const char *peer_name,
const BIGNUM *p, const BIGNUM *g, const BIGNUM *q,
const BIGNUM *secret)
{
- JPAKE_CTX *ctx = OPENSSL_malloc(sizeof *ctx);
+ JPAKE_CTX *ctx = OPENSSL_malloc(sizeof(*ctx));
if (ctx == NULL)
return NULL;
JPAKE_CTX_init(ctx, name, peer_name, p, g, q, secret);
return ctx;
}
void JPAKE_CTX_free(JPAKE_CTX *ctx)
{
JPAKE_CTX_release(ctx);
OPENSSL_free(ctx);
}
static void hashlength(SHA_CTX *sha, size_t l)
{
unsigned char b[2];
OPENSSL_assert(l <= 0xffff);
b[0] = l >> 8;
b[1] = l & 0xff;
SHA1_Update(sha, b, 2);
}
static void hashstring(SHA_CTX *sha, const char *string)
{
size_t l = strlen(string);
hashlength(sha, l);
SHA1_Update(sha, string, l);
}
static void hashbn(SHA_CTX *sha, const BIGNUM *bn)
{
size_t l = BN_num_bytes(bn);
unsigned char *bin = OPENSSL_malloc(l);
if (bin == NULL)
return;
hashlength(sha, l);
BN_bn2bin(bn, bin);
SHA1_Update(sha, bin, l);
OPENSSL_free(bin);
}
/* h=hash(g, g^r, g^x, name) */
static void zkp_hash(BIGNUM *h, const BIGNUM *zkpg, const JPAKE_STEP_PART *p,
const char *proof_name)
{
unsigned char md[SHA_DIGEST_LENGTH];
SHA_CTX sha;
/*
* XXX: hash should not allow moving of the boundaries - Java code
* is flawed in this respect. Length encoding seems simplest.
*/
SHA1_Init(&sha);
hashbn(&sha, zkpg);
OPENSSL_assert(!BN_is_zero(p->zkpx.gr));
hashbn(&sha, p->zkpx.gr);
hashbn(&sha, p->gx);
hashstring(&sha, proof_name);
SHA1_Final(md, &sha);
BN_bin2bn(md, SHA_DIGEST_LENGTH, h);
}
/*
* Prove knowledge of x
* Note that p->gx has already been calculated
*/
static void generate_zkp(JPAKE_STEP_PART *p, const BIGNUM *x,
const BIGNUM *zkpg, JPAKE_CTX *ctx)
{
BIGNUM *r = BN_new();
BIGNUM *h = BN_new();
BIGNUM *t = BN_new();
/*-
* r in [0,q)
* XXX: Java chooses r in [0, 2^160) - i.e. distribution not uniform
*/
BN_rand_range(r, ctx->p.q);
/* g^r */
BN_mod_exp(p->zkpx.gr, zkpg, r, ctx->p.p, ctx->ctx);
/* h=hash... */
zkp_hash(h, zkpg, p, ctx->p.name);
/* b = r - x*h */
BN_mod_mul(t, x, h, ctx->p.q, ctx->ctx);
BN_mod_sub(p->zkpx.b, r, t, ctx->p.q, ctx->ctx);
/* cleanup */
BN_free(t);
BN_free(h);
BN_free(r);
}
static int verify_zkp(const JPAKE_STEP_PART *p, const BIGNUM *zkpg,
JPAKE_CTX *ctx)
{
BIGNUM *h = BN_new();
BIGNUM *t1 = BN_new();
BIGNUM *t2 = BN_new();
BIGNUM *t3 = BN_new();
int ret = 0;
if (h == NULL || t1 == NULL || t2 == NULL || t3 == NULL)
goto end;
zkp_hash(h, zkpg, p, ctx->p.peer_name);
/* t1 = g^b */
BN_mod_exp(t1, zkpg, p->zkpx.b, ctx->p.p, ctx->ctx);
/* t2 = (g^x)^h = g^{hx} */
BN_mod_exp(t2, p->gx, h, ctx->p.p, ctx->ctx);
/* t3 = t1 * t2 = g^{hx} * g^b = g^{hx+b} = g^r (allegedly) */
BN_mod_mul(t3, t1, t2, ctx->p.p, ctx->ctx);
/* verify t3 == g^r */
if (BN_cmp(t3, p->zkpx.gr) == 0)
ret = 1;
else
JPAKEerr(JPAKE_F_VERIFY_ZKP, JPAKE_R_ZKP_VERIFY_FAILED);
end:
/* cleanup */
BN_free(t3);
BN_free(t2);
BN_free(t1);
BN_free(h);
return ret;
}
static void generate_step_part(JPAKE_STEP_PART *p, const BIGNUM *x,
const BIGNUM *g, JPAKE_CTX *ctx)
{
BN_mod_exp(p->gx, g, x, ctx->p.p, ctx->ctx);
generate_zkp(p, x, g, ctx);
}
/* Generate each party's random numbers. xa is in [0, q), xb is in [1, q). */
static void genrand(JPAKE_CTX *ctx)
{
BIGNUM *qm1;
/* xa in [0, q) */
BN_rand_range(ctx->xa, ctx->p.q);
/* q-1 */
qm1 = BN_new();
BN_copy(qm1, ctx->p.q);
BN_sub_word(qm1, 1);
/* ... and xb in [0, q-1) */
BN_rand_range(ctx->xb, qm1);
/* [1, q) */
BN_add_word(ctx->xb, 1);
/* cleanup */
BN_free(qm1);
}
int JPAKE_STEP1_generate(JPAKE_STEP1 *send, JPAKE_CTX *ctx)
{
genrand(ctx);
generate_step_part(&send->p1, ctx->xa, ctx->p.g, ctx);
generate_step_part(&send->p2, ctx->xb, ctx->p.g, ctx);
return 1;
}
/* g^x is a legal value */
static int is_legal(const BIGNUM *gx, const JPAKE_CTX *ctx)
{
BIGNUM *t;
int res;
if (BN_is_negative(gx) || BN_is_zero(gx) || BN_cmp(gx, ctx->p.p) >= 0)
return 0;
t = BN_new();
BN_mod_exp(t, gx, ctx->p.q, ctx->p.p, ctx->ctx);
res = BN_is_one(t);
BN_free(t);
return res;
}
int JPAKE_STEP1_process(JPAKE_CTX *ctx, const JPAKE_STEP1 *received)
{
if (!is_legal(received->p1.gx, ctx)) {
JPAKEerr(JPAKE_F_JPAKE_STEP1_PROCESS,
JPAKE_R_G_TO_THE_X3_IS_NOT_LEGAL);
return 0;
}
if (!is_legal(received->p2.gx, ctx)) {
JPAKEerr(JPAKE_F_JPAKE_STEP1_PROCESS,
JPAKE_R_G_TO_THE_X4_IS_NOT_LEGAL);
return 0;
}
/* verify their ZKP(xc) */
if (!verify_zkp(&received->p1, ctx->p.g, ctx)) {
JPAKEerr(JPAKE_F_JPAKE_STEP1_PROCESS, JPAKE_R_VERIFY_X3_FAILED);
return 0;
}
/* verify their ZKP(xd) */
if (!verify_zkp(&received->p2, ctx->p.g, ctx)) {
JPAKEerr(JPAKE_F_JPAKE_STEP1_PROCESS, JPAKE_R_VERIFY_X4_FAILED);
return 0;
}
/* g^xd != 1 */
if (BN_is_one(received->p2.gx)) {
JPAKEerr(JPAKE_F_JPAKE_STEP1_PROCESS, JPAKE_R_G_TO_THE_X4_IS_ONE);
return 0;
}
/* Save the bits we need for later */
BN_copy(ctx->p.gxc, received->p1.gx);
BN_copy(ctx->p.gxd, received->p2.gx);
return 1;
}
int JPAKE_STEP2_generate(JPAKE_STEP2 *send, JPAKE_CTX *ctx)
{
BIGNUM *t1 = BN_new();
BIGNUM *t2 = BN_new();
/*-
* X = g^{(xa + xc + xd) * xb * s}
* t1 = g^xa
*/
BN_mod_exp(t1, ctx->p.g, ctx->xa, ctx->p.p, ctx->ctx);
/* t2 = t1 * g^{xc} = g^{xa} * g^{xc} = g^{xa + xc} */
BN_mod_mul(t2, t1, ctx->p.gxc, ctx->p.p, ctx->ctx);
/* t1 = t2 * g^{xd} = g^{xa + xc + xd} */
BN_mod_mul(t1, t2, ctx->p.gxd, ctx->p.p, ctx->ctx);
/* t2 = xb * s */
BN_mod_mul(t2, ctx->xb, ctx->secret, ctx->p.q, ctx->ctx);
/*-
* ZKP(xb * s)
* XXX: this is kinda funky, because we're using
*
* g' = g^{xa + xc + xd}
*
* as the generator, which means X is g'^{xb * s}
* X = t1^{t2} = t1^{xb * s} = g^{(xa + xc + xd) * xb * s}
*/
generate_step_part(send, t2, t1, ctx);
/* cleanup */
BN_free(t1);
BN_free(t2);
return 1;
}
/* gx = g^{xc + xa + xb} * xd * s */
static int compute_key(JPAKE_CTX *ctx, const BIGNUM *gx)
{
BIGNUM *t1 = BN_new();
BIGNUM *t2 = BN_new();
BIGNUM *t3 = BN_new();
/*-
* K = (gx/g^{xb * xd * s})^{xb}
* = (g^{(xc + xa + xb) * xd * s - xb * xd *s})^{xb}
* = (g^{(xa + xc) * xd * s})^{xb}
* = g^{(xa + xc) * xb * xd * s}
* [which is the same regardless of who calculates it]
*/
/* t1 = (g^{xd})^{xb} = g^{xb * xd} */
BN_mod_exp(t1, ctx->p.gxd, ctx->xb, ctx->p.p, ctx->ctx);
/* t2 = -s = q-s */
BN_sub(t2, ctx->p.q, ctx->secret);
/* t3 = t1^t2 = g^{-xb * xd * s} */
BN_mod_exp(t3, t1, t2, ctx->p.p, ctx->ctx);
/* t1 = gx * t3 = X/g^{xb * xd * s} */
BN_mod_mul(t1, gx, t3, ctx->p.p, ctx->ctx);
/* K = t1^{xb} */
BN_mod_exp(ctx->key, t1, ctx->xb, ctx->p.p, ctx->ctx);
/* cleanup */
BN_free(t3);
BN_free(t2);
BN_free(t1);
return 1;
}
int JPAKE_STEP2_process(JPAKE_CTX *ctx, const JPAKE_STEP2 *received)
{
BIGNUM *t1 = BN_new();
BIGNUM *t2 = BN_new();
int ret = 0;
/*-
* g' = g^{xc + xa + xb} [from our POV]
* t1 = xa + xb
*/
BN_mod_add(t1, ctx->xa, ctx->xb, ctx->p.q, ctx->ctx);
/* t2 = g^{t1} = g^{xa+xb} */
BN_mod_exp(t2, ctx->p.g, t1, ctx->p.p, ctx->ctx);
/* t1 = g^{xc} * t2 = g^{xc + xa + xb} */
BN_mod_mul(t1, ctx->p.gxc, t2, ctx->p.p, ctx->ctx);
if (verify_zkp(received, t1, ctx))
ret = 1;
else
JPAKEerr(JPAKE_F_JPAKE_STEP2_PROCESS, JPAKE_R_VERIFY_B_FAILED);
compute_key(ctx, received->gx);
/* cleanup */
BN_free(t2);
BN_free(t1);
return ret;
}
static void quickhashbn(unsigned char *md, const BIGNUM *bn)
{
SHA_CTX sha;
SHA1_Init(&sha);
hashbn(&sha, bn);
SHA1_Final(md, &sha);
}
void JPAKE_STEP3A_init(JPAKE_STEP3A *s3a)
{
}
int JPAKE_STEP3A_generate(JPAKE_STEP3A *send, JPAKE_CTX *ctx)
{
quickhashbn(send->hhk, ctx->key);
- SHA1(send->hhk, sizeof send->hhk, send->hhk);
+ SHA1(send->hhk, sizeof(send->hhk), send->hhk);
return 1;
}
int JPAKE_STEP3A_process(JPAKE_CTX *ctx, const JPAKE_STEP3A *received)
{
unsigned char hhk[SHA_DIGEST_LENGTH];
quickhashbn(hhk, ctx->key);
- SHA1(hhk, sizeof hhk, hhk);
- if (memcmp(hhk, received->hhk, sizeof hhk)) {
+ SHA1(hhk, sizeof(hhk), hhk);
+ if (memcmp(hhk, received->hhk, sizeof(hhk))) {
JPAKEerr(JPAKE_F_JPAKE_STEP3A_PROCESS,
JPAKE_R_HASH_OF_HASH_OF_KEY_MISMATCH);
return 0;
}
return 1;
}
void JPAKE_STEP3A_release(JPAKE_STEP3A *s3a)
{
}
void JPAKE_STEP3B_init(JPAKE_STEP3B *s3b)
{
}
int JPAKE_STEP3B_generate(JPAKE_STEP3B *send, JPAKE_CTX *ctx)
{
quickhashbn(send->hk, ctx->key);
return 1;
}
int JPAKE_STEP3B_process(JPAKE_CTX *ctx, const JPAKE_STEP3B *received)
{
unsigned char hk[SHA_DIGEST_LENGTH];
quickhashbn(hk, ctx->key);
- if (memcmp(hk, received->hk, sizeof hk)) {
+ if (memcmp(hk, received->hk, sizeof(hk))) {
JPAKEerr(JPAKE_F_JPAKE_STEP3B_PROCESS, JPAKE_R_HASH_OF_KEY_MISMATCH);
return 0;
}
return 1;
}
void JPAKE_STEP3B_release(JPAKE_STEP3B *s3b)
{
}
const BIGNUM *JPAKE_get_shared_key(JPAKE_CTX *ctx)
{
return ctx->key;
}
diff --git a/crypto/md2/md2_dgst.c b/crypto/md2/md2_dgst.c
index 7f5d9ba69ba2..44193e282b43 100644
--- a/crypto/md2/md2_dgst.c
+++ b/crypto/md2/md2_dgst.c
@@ -1,224 +1,224 @@
/* crypto/md2/md2_dgst.c */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/md2.h>
#include <openssl/opensslv.h>
#include <openssl/crypto.h>
const char MD2_version[] = "MD2" OPENSSL_VERSION_PTEXT;
/*
* Implemented from RFC1319 The MD2 Message-Digest Algorithm
*/
#define UCHAR unsigned char
static void md2_block(MD2_CTX *c, const unsigned char *d);
/*
* The magic S table - I have converted it to hex since it is basically just
* a random byte string.
*/
static const MD2_INT S[256] = {
0x29, 0x2E, 0x43, 0xC9, 0xA2, 0xD8, 0x7C, 0x01,
0x3D, 0x36, 0x54, 0xA1, 0xEC, 0xF0, 0x06, 0x13,
0x62, 0xA7, 0x05, 0xF3, 0xC0, 0xC7, 0x73, 0x8C,
0x98, 0x93, 0x2B, 0xD9, 0xBC, 0x4C, 0x82, 0xCA,
0x1E, 0x9B, 0x57, 0x3C, 0xFD, 0xD4, 0xE0, 0x16,
0x67, 0x42, 0x6F, 0x18, 0x8A, 0x17, 0xE5, 0x12,
0xBE, 0x4E, 0xC4, 0xD6, 0xDA, 0x9E, 0xDE, 0x49,
0xA0, 0xFB, 0xF5, 0x8E, 0xBB, 0x2F, 0xEE, 0x7A,
0xA9, 0x68, 0x79, 0x91, 0x15, 0xB2, 0x07, 0x3F,
0x94, 0xC2, 0x10, 0x89, 0x0B, 0x22, 0x5F, 0x21,
0x80, 0x7F, 0x5D, 0x9A, 0x5A, 0x90, 0x32, 0x27,
0x35, 0x3E, 0xCC, 0xE7, 0xBF, 0xF7, 0x97, 0x03,
0xFF, 0x19, 0x30, 0xB3, 0x48, 0xA5, 0xB5, 0xD1,
0xD7, 0x5E, 0x92, 0x2A, 0xAC, 0x56, 0xAA, 0xC6,
0x4F, 0xB8, 0x38, 0xD2, 0x96, 0xA4, 0x7D, 0xB6,
0x76, 0xFC, 0x6B, 0xE2, 0x9C, 0x74, 0x04, 0xF1,
0x45, 0x9D, 0x70, 0x59, 0x64, 0x71, 0x87, 0x20,
0x86, 0x5B, 0xCF, 0x65, 0xE6, 0x2D, 0xA8, 0x02,
0x1B, 0x60, 0x25, 0xAD, 0xAE, 0xB0, 0xB9, 0xF6,
0x1C, 0x46, 0x61, 0x69, 0x34, 0x40, 0x7E, 0x0F,
0x55, 0x47, 0xA3, 0x23, 0xDD, 0x51, 0xAF, 0x3A,
0xC3, 0x5C, 0xF9, 0xCE, 0xBA, 0xC5, 0xEA, 0x26,
0x2C, 0x53, 0x0D, 0x6E, 0x85, 0x28, 0x84, 0x09,
0xD3, 0xDF, 0xCD, 0xF4, 0x41, 0x81, 0x4D, 0x52,
0x6A, 0xDC, 0x37, 0xC8, 0x6C, 0xC1, 0xAB, 0xFA,
0x24, 0xE1, 0x7B, 0x08, 0x0C, 0xBD, 0xB1, 0x4A,
0x78, 0x88, 0x95, 0x8B, 0xE3, 0x63, 0xE8, 0x6D,
0xE9, 0xCB, 0xD5, 0xFE, 0x3B, 0x00, 0x1D, 0x39,
0xF2, 0xEF, 0xB7, 0x0E, 0x66, 0x58, 0xD0, 0xE4,
0xA6, 0x77, 0x72, 0xF8, 0xEB, 0x75, 0x4B, 0x0A,
0x31, 0x44, 0x50, 0xB4, 0x8F, 0xED, 0x1F, 0x1A,
0xDB, 0x99, 0x8D, 0x33, 0x9F, 0x11, 0x83, 0x14,
};
const char *MD2_options(void)
{
if (sizeof(MD2_INT) == 1)
return ("md2(char)");
else
return ("md2(int)");
}
fips_md_init(MD2)
{
c->num = 0;
- memset(c->state, 0, sizeof c->state);
- memset(c->cksm, 0, sizeof c->cksm);
- memset(c->data, 0, sizeof c->data);
+ memset(c->state, 0, sizeof(c->state));
+ memset(c->cksm, 0, sizeof(c->cksm));
+ memset(c->data, 0, sizeof(c->data));
return 1;
}
int MD2_Update(MD2_CTX *c, const unsigned char *data, size_t len)
{
register UCHAR *p;
if (len == 0)
return 1;
p = c->data;
if (c->num != 0) {
if ((c->num + len) >= MD2_BLOCK) {
memcpy(&(p[c->num]), data, MD2_BLOCK - c->num);
md2_block(c, c->data);
data += (MD2_BLOCK - c->num);
len -= (MD2_BLOCK - c->num);
c->num = 0;
/* drop through and do the rest */
} else {
memcpy(&(p[c->num]), data, len);
/* data+=len; */
c->num += (int)len;
return 1;
}
}
/*
* we now can process the input data in blocks of MD2_BLOCK chars and
* save the leftovers to c->data.
*/
while (len >= MD2_BLOCK) {
md2_block(c, data);
data += MD2_BLOCK;
len -= MD2_BLOCK;
}
memcpy(p, data, len);
c->num = (int)len;
return 1;
}
static void md2_block(MD2_CTX *c, const unsigned char *d)
{
register MD2_INT t, *sp1, *sp2;
register int i, j;
MD2_INT state[48];
sp1 = c->state;
sp2 = c->cksm;
j = sp2[MD2_BLOCK - 1];
for (i = 0; i < 16; i++) {
state[i] = sp1[i];
state[i + 16] = t = d[i];
state[i + 32] = (t ^ sp1[i]);
j = sp2[i] ^= S[t ^ j];
}
t = 0;
for (i = 0; i < 18; i++) {
for (j = 0; j < 48; j += 8) {
t = state[j + 0] ^= S[t];
t = state[j + 1] ^= S[t];
t = state[j + 2] ^= S[t];
t = state[j + 3] ^= S[t];
t = state[j + 4] ^= S[t];
t = state[j + 5] ^= S[t];
t = state[j + 6] ^= S[t];
t = state[j + 7] ^= S[t];
}
t = (t + i) & 0xff;
}
memcpy(sp1, state, 16 * sizeof(MD2_INT));
OPENSSL_cleanse(state, 48 * sizeof(MD2_INT));
}
int MD2_Final(unsigned char *md, MD2_CTX *c)
{
int i, v;
register UCHAR *cp;
register MD2_INT *p1, *p2;
cp = c->data;
p1 = c->state;
p2 = c->cksm;
v = MD2_BLOCK - c->num;
for (i = c->num; i < MD2_BLOCK; i++)
cp[i] = (UCHAR) v;
md2_block(c, cp);
for (i = 0; i < MD2_BLOCK; i++)
cp[i] = (UCHAR) p2[i];
md2_block(c, cp);
for (i = 0; i < 16; i++)
md[i] = (UCHAR) (p1[i] & 0xff);
OPENSSL_cleanse(c, sizeof(*c));
return 1;
}
diff --git a/crypto/md4/md4.c b/crypto/md4/md4.c
index c9fab6669aff..a79997f8ffcc 100644
--- a/crypto/md4/md4.c
+++ b/crypto/md4/md4.c
@@ -1,121 +1,121 @@
/* crypto/md4/md4.c */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
#include <stdio.h>
#include <stdlib.h>
#include <openssl/md4.h>
#define BUFSIZE 1024*16
void do_fp(FILE *f);
void pt(unsigned char *md);
#if !defined(_OSD_POSIX) && !defined(__DJGPP__)
int read(int, void *, unsigned int);
#endif
int main(int argc, char **argv)
{
int i, err = 0;
FILE *IN;
if (argc == 1) {
do_fp(stdin);
} else {
for (i = 1; i < argc; i++) {
IN = fopen(argv[i], "r");
if (IN == NULL) {
perror(argv[i]);
err++;
continue;
}
printf("MD4(%s)= ", argv[i]);
do_fp(IN);
fclose(IN);
}
}
exit(err);
}
void do_fp(FILE *f)
{
MD4_CTX c;
unsigned char md[MD4_DIGEST_LENGTH];
int fd;
int i;
static unsigned char buf[BUFSIZE];
fd = fileno(f);
MD4_Init(&c);
for (;;) {
- i = read(fd, buf, sizeof buf);
+ i = read(fd, buf, sizeof(buf));
if (i <= 0)
break;
MD4_Update(&c, buf, (unsigned long)i);
}
MD4_Final(&(md[0]), &c);
pt(md);
}
void pt(unsigned char *md)
{
int i;
for (i = 0; i < MD4_DIGEST_LENGTH; i++)
printf("%02x", md[i]);
printf("\n");
}
diff --git a/crypto/mem_dbg.c b/crypto/mem_dbg.c
index 8525ded78c79..9e1be508951e 100644
--- a/crypto/mem_dbg.c
+++ b/crypto/mem_dbg.c
@@ -1,830 +1,836 @@
/* crypto/mem_dbg.c */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
/* ====================================================================
- * Copyright (c) 1998-2006 The OpenSSL Project. All rights reserved.
+ * Copyright (c) 1998-2018 The OpenSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* openssl-core@openssl.org.
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.openssl.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*
* This product includes cryptographic software written by Eric Young
* (eay@cryptsoft.com). This product includes software written by Tim
* Hudson (tjh@cryptsoft.com).
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include "cryptlib.h"
#include <openssl/crypto.h>
#include <openssl/buffer.h>
#include <openssl/bio.h>
#include <openssl/lhash.h>
static int mh_mode = CRYPTO_MEM_CHECK_OFF;
/*
* The state changes to CRYPTO_MEM_CHECK_ON | CRYPTO_MEM_CHECK_ENABLE when
* the application asks for it (usually after library initialisation for
* which no book-keeping is desired). State CRYPTO_MEM_CHECK_ON exists only
* temporarily when the library thinks that certain allocations should not be
* checked (e.g. the data structures used for memory checking). It is not
* suitable as an initial state: the library will unexpectedly enable memory
* checking when it executes one of those sections that want to disable
* checking temporarily. State CRYPTO_MEM_CHECK_ENABLE without ..._ON makes
* no sense whatsoever.
*/
static unsigned long order = 0; /* number of memory requests */
DECLARE_LHASH_OF(MEM);
static LHASH_OF(MEM) *mh = NULL; /* hash-table of memory requests (address as
* key); access requires MALLOC2 lock */
typedef struct app_mem_info_st
/*-
* For application-defined information (static C-string `info')
* to be displayed in memory leak list.
* Each thread has its own stack. For applications, there is
* CRYPTO_push_info("...") to push an entry,
* CRYPTO_pop_info() to pop an entry,
* CRYPTO_remove_all_info() to pop all entries.
*/
{
CRYPTO_THREADID threadid;
const char *file;
int line;
const char *info;
struct app_mem_info_st *next; /* tail of thread's stack */
int references;
} APP_INFO;
static void app_info_free(APP_INFO *);
DECLARE_LHASH_OF(APP_INFO);
static LHASH_OF(APP_INFO) *amih = NULL; /* hash-table with those
* app_mem_info_st's that are at the
* top of their thread's stack (with
* `thread' as key); access requires
* MALLOC2 lock */
typedef struct mem_st
/* memory-block description */
{
void *addr;
int num;
const char *file;
int line;
CRYPTO_THREADID threadid;
unsigned long order;
time_t time;
APP_INFO *app_info;
} MEM;
static long options = /* extra information to be recorded */
#if defined(CRYPTO_MDEBUG_TIME) || defined(CRYPTO_MDEBUG_ALL)
V_CRYPTO_MDEBUG_TIME |
#endif
#if defined(CRYPTO_MDEBUG_THREAD) || defined(CRYPTO_MDEBUG_ALL)
V_CRYPTO_MDEBUG_THREAD |
#endif
0;
static unsigned int num_disable = 0; /* num_disable > 0 iff mh_mode ==
* CRYPTO_MEM_CHECK_ON (w/o ..._ENABLE) */
/*
* Valid iff num_disable > 0. CRYPTO_LOCK_MALLOC2 is locked exactly in this
* case (by the thread named in disabling_thread).
*/
static CRYPTO_THREADID disabling_threadid;
static void app_info_free(APP_INFO *inf)
{
if (--(inf->references) <= 0) {
if (inf->next != NULL) {
app_info_free(inf->next);
}
OPENSSL_free(inf);
}
}
int CRYPTO_mem_ctrl(int mode)
{
int ret = mh_mode;
CRYPTO_w_lock(CRYPTO_LOCK_MALLOC);
switch (mode) {
/*
* for applications (not to be called while multiple threads use the
* library):
*/
case CRYPTO_MEM_CHECK_ON: /* aka MemCheck_start() */
mh_mode = CRYPTO_MEM_CHECK_ON | CRYPTO_MEM_CHECK_ENABLE;
num_disable = 0;
break;
case CRYPTO_MEM_CHECK_OFF: /* aka MemCheck_stop() */
mh_mode = 0;
num_disable = 0; /* should be true *before* MemCheck_stop is
* used, or there'll be a lot of confusion */
break;
/* switch off temporarily (for library-internal use): */
case CRYPTO_MEM_CHECK_DISABLE: /* aka MemCheck_off() */
if (mh_mode & CRYPTO_MEM_CHECK_ON) {
CRYPTO_THREADID cur;
CRYPTO_THREADID_current(&cur);
/* see if we don't have the MALLOC2 lock already */
if (!num_disable
|| CRYPTO_THREADID_cmp(&disabling_threadid, &cur)) {
/*
* Long-time lock CRYPTO_LOCK_MALLOC2 must not be claimed
* while we're holding CRYPTO_LOCK_MALLOC, or we'll deadlock
* if somebody else holds CRYPTO_LOCK_MALLOC2 (and cannot
* release it because we block entry to this function). Give
* them a chance, first, and then claim the locks in
* appropriate order (long-time lock first).
*/
CRYPTO_w_unlock(CRYPTO_LOCK_MALLOC);
/*
* Note that after we have waited for CRYPTO_LOCK_MALLOC2 and
* CRYPTO_LOCK_MALLOC, we'll still be in the right "case" and
* "if" branch because MemCheck_start and MemCheck_stop may
* never be used while there are multiple OpenSSL threads.
*/
CRYPTO_w_lock(CRYPTO_LOCK_MALLOC2);
CRYPTO_w_lock(CRYPTO_LOCK_MALLOC);
mh_mode &= ~CRYPTO_MEM_CHECK_ENABLE;
CRYPTO_THREADID_cpy(&disabling_threadid, &cur);
}
num_disable++;
}
break;
case CRYPTO_MEM_CHECK_ENABLE: /* aka MemCheck_on() */
if (mh_mode & CRYPTO_MEM_CHECK_ON) {
if (num_disable) { /* always true, or something is going wrong */
num_disable--;
if (num_disable == 0) {
mh_mode |= CRYPTO_MEM_CHECK_ENABLE;
CRYPTO_w_unlock(CRYPTO_LOCK_MALLOC2);
}
}
}
break;
default:
break;
}
CRYPTO_w_unlock(CRYPTO_LOCK_MALLOC);
return (ret);
}
int CRYPTO_is_mem_check_on(void)
{
int ret = 0;
if (mh_mode & CRYPTO_MEM_CHECK_ON) {
CRYPTO_THREADID cur;
CRYPTO_THREADID_current(&cur);
CRYPTO_r_lock(CRYPTO_LOCK_MALLOC);
ret = (mh_mode & CRYPTO_MEM_CHECK_ENABLE)
|| CRYPTO_THREADID_cmp(&disabling_threadid, &cur);
CRYPTO_r_unlock(CRYPTO_LOCK_MALLOC);
}
return (ret);
}
void CRYPTO_dbg_set_options(long bits)
{
options = bits;
}
long CRYPTO_dbg_get_options(void)
{
return options;
}
static int mem_cmp(const MEM *a, const MEM *b)
{
#ifdef _WIN64
const char *ap = (const char *)a->addr, *bp = (const char *)b->addr;
if (ap == bp)
return 0;
else if (ap > bp)
return 1;
else
return -1;
#else
return (const char *)a->addr - (const char *)b->addr;
#endif
}
static IMPLEMENT_LHASH_COMP_FN(mem, MEM)
static unsigned long mem_hash(const MEM *a)
{
unsigned long ret;
ret = (unsigned long)a->addr;
ret = ret * 17851 + (ret >> 14) * 7 + (ret >> 4) * 251;
return (ret);
}
static IMPLEMENT_LHASH_HASH_FN(mem, MEM)
/* static int app_info_cmp(APP_INFO *a, APP_INFO *b) */
static int app_info_cmp(const void *a_void, const void *b_void)
{
return CRYPTO_THREADID_cmp(&((const APP_INFO *)a_void)->threadid,
&((const APP_INFO *)b_void)->threadid);
}
static IMPLEMENT_LHASH_COMP_FN(app_info, APP_INFO)
static unsigned long app_info_hash(const APP_INFO *a)
{
unsigned long ret;
ret = CRYPTO_THREADID_hash(&a->threadid);
/* This is left in as a "who am I to question legacy?" measure */
ret = ret * 17851 + (ret >> 14) * 7 + (ret >> 4) * 251;
return (ret);
}
static IMPLEMENT_LHASH_HASH_FN(app_info, APP_INFO)
static APP_INFO *pop_info(void)
{
APP_INFO tmp;
APP_INFO *ret = NULL;
if (amih != NULL) {
CRYPTO_THREADID_current(&tmp.threadid);
if ((ret = lh_APP_INFO_delete(amih, &tmp)) != NULL) {
APP_INFO *next = ret->next;
if (next != NULL) {
next->references++;
(void)lh_APP_INFO_insert(amih, next);
}
#ifdef LEVITTE_DEBUG_MEM
if (CRYPTO_THREADID_cmp(&ret->threadid, &tmp.threadid)) {
fprintf(stderr,
"pop_info(): deleted info has other thread ID (%lu) than the current thread (%lu)!!!!\n",
CRYPTO_THREADID_hash(&ret->threadid),
CRYPTO_THREADID_hash(&tmp.threadid));
abort();
}
#endif
if (--(ret->references) <= 0) {
ret->next = NULL;
if (next != NULL)
next->references--;
OPENSSL_free(ret);
}
}
}
return (ret);
}
int CRYPTO_push_info_(const char *info, const char *file, int line)
{
APP_INFO *ami, *amim;
int ret = 0;
if (is_MemCheck_on()) {
MemCheck_off(); /* obtain MALLOC2 lock */
if ((ami = (APP_INFO *)OPENSSL_malloc(sizeof(APP_INFO))) == NULL) {
ret = 0;
goto err;
}
if (amih == NULL) {
if ((amih = lh_APP_INFO_new()) == NULL) {
OPENSSL_free(ami);
ret = 0;
goto err;
}
}
CRYPTO_THREADID_current(&ami->threadid);
ami->file = file;
ami->line = line;
ami->info = info;
ami->references = 1;
ami->next = NULL;
if ((amim = lh_APP_INFO_insert(amih, ami)) != NULL) {
#ifdef LEVITTE_DEBUG_MEM
if (CRYPTO_THREADID_cmp(&ami->threadid, &amim->threadid)) {
fprintf(stderr,
"CRYPTO_push_info(): previous info has other thread ID (%lu) than the current thread (%lu)!!!!\n",
CRYPTO_THREADID_hash(&amim->threadid),
CRYPTO_THREADID_hash(&ami->threadid));
abort();
}
#endif
ami->next = amim;
}
err:
MemCheck_on(); /* release MALLOC2 lock */
}
return (ret);
}
int CRYPTO_pop_info(void)
{
int ret = 0;
if (is_MemCheck_on()) { /* _must_ be true, or something went severely
* wrong */
MemCheck_off(); /* obtain MALLOC2 lock */
ret = (pop_info() != NULL);
MemCheck_on(); /* release MALLOC2 lock */
}
return (ret);
}
int CRYPTO_remove_all_info(void)
{
int ret = 0;
if (is_MemCheck_on()) { /* _must_ be true */
MemCheck_off(); /* obtain MALLOC2 lock */
while (pop_info() != NULL)
ret++;
MemCheck_on(); /* release MALLOC2 lock */
}
return (ret);
}
static unsigned long break_order_num = 0;
void CRYPTO_dbg_malloc(void *addr, int num, const char *file, int line,
int before_p)
{
MEM *m, *mm;
APP_INFO tmp, *amim;
switch (before_p & 127) {
case 0:
break;
case 1:
if (addr == NULL)
break;
if (is_MemCheck_on()) {
MemCheck_off(); /* make sure we hold MALLOC2 lock */
if ((m = (MEM *)OPENSSL_malloc(sizeof(MEM))) == NULL) {
OPENSSL_free(addr);
MemCheck_on(); /* release MALLOC2 lock if num_disabled drops
* to 0 */
return;
}
if (mh == NULL) {
if ((mh = lh_MEM_new()) == NULL) {
OPENSSL_free(addr);
OPENSSL_free(m);
addr = NULL;
goto err;
}
}
m->addr = addr;
m->file = file;
m->line = line;
m->num = num;
if (options & V_CRYPTO_MDEBUG_THREAD)
CRYPTO_THREADID_current(&m->threadid);
else
memset(&m->threadid, 0, sizeof(m->threadid));
if (order == break_order_num) {
/* BREAK HERE */
m->order = order;
}
m->order = order++;
#ifdef LEVITTE_DEBUG_MEM
fprintf(stderr, "LEVITTE_DEBUG_MEM: [%5ld] %c 0x%p (%d)\n",
m->order, (before_p & 128) ? '*' : '+', m->addr, m->num);
#endif
if (options & V_CRYPTO_MDEBUG_TIME)
m->time = time(NULL);
else
m->time = 0;
CRYPTO_THREADID_current(&tmp.threadid);
m->app_info = NULL;
if (amih != NULL
&& (amim = lh_APP_INFO_retrieve(amih, &tmp)) != NULL) {
m->app_info = amim;
amim->references++;
}
if ((mm = lh_MEM_insert(mh, m)) != NULL) {
/* Not good, but don't sweat it */
if (mm->app_info != NULL) {
mm->app_info->references--;
}
OPENSSL_free(mm);
}
err:
MemCheck_on(); /* release MALLOC2 lock if num_disabled drops
* to 0 */
}
break;
}
return;
}
void CRYPTO_dbg_free(void *addr, int before_p)
{
MEM m, *mp;
switch (before_p) {
case 0:
if (addr == NULL)
break;
if (is_MemCheck_on() && (mh != NULL)) {
MemCheck_off(); /* make sure we hold MALLOC2 lock */
m.addr = addr;
mp = lh_MEM_delete(mh, &m);
if (mp != NULL) {
#ifdef LEVITTE_DEBUG_MEM
fprintf(stderr, "LEVITTE_DEBUG_MEM: [%5ld] - 0x%p (%d)\n",
mp->order, mp->addr, mp->num);
#endif
if (mp->app_info != NULL)
app_info_free(mp->app_info);
OPENSSL_free(mp);
}
MemCheck_on(); /* release MALLOC2 lock if num_disabled drops
* to 0 */
}
break;
case 1:
break;
}
}
void CRYPTO_dbg_realloc(void *addr1, void *addr2, int num,
const char *file, int line, int before_p)
{
MEM m, *mp;
#ifdef LEVITTE_DEBUG_MEM
fprintf(stderr,
"LEVITTE_DEBUG_MEM: --> CRYPTO_dbg_malloc(addr1 = %p, addr2 = %p, num = %d, file = \"%s\", line = %d, before_p = %d)\n",
addr1, addr2, num, file, line, before_p);
#endif
switch (before_p) {
case 0:
break;
case 1:
if (addr2 == NULL)
break;
if (addr1 == NULL) {
CRYPTO_dbg_malloc(addr2, num, file, line, 128 | before_p);
break;
}
if (is_MemCheck_on()) {
MemCheck_off(); /* make sure we hold MALLOC2 lock */
m.addr = addr1;
mp = lh_MEM_delete(mh, &m);
if (mp != NULL) {
#ifdef LEVITTE_DEBUG_MEM
fprintf(stderr,
"LEVITTE_DEBUG_MEM: [%5ld] * 0x%p (%d) -> 0x%p (%d)\n",
mp->order, mp->addr, mp->num, addr2, num);
#endif
mp->addr = addr2;
mp->num = num;
(void)lh_MEM_insert(mh, mp);
}
MemCheck_on(); /* release MALLOC2 lock if num_disabled drops
* to 0 */
}
break;
}
return;
}
typedef struct mem_leak_st {
BIO *bio;
int chunks;
long bytes;
} MEM_LEAK;
static void print_leak_doall_arg(const MEM *m, MEM_LEAK *l)
{
char buf[1024];
char *bufp = buf;
APP_INFO *amip;
int ami_cnt;
struct tm *lcl = NULL;
+ struct tm result = {0};
CRYPTO_THREADID ti;
-#define BUF_REMAIN (sizeof buf - (size_t)(bufp - buf))
+#define BUF_REMAIN (sizeof(buf) - (size_t)(bufp - buf))
if (m->addr == (char *)l->bio)
return;
if (options & V_CRYPTO_MDEBUG_TIME) {
+# if defined(OPENSSL_THREADS) && !defined(OPENSSL_SYS_WIN32) && \
+ !defined(OPENSSL_SYS_OS2) && !defined(OPENSSL_SYS_SUNOS) && \
+ (!defined(OPENSSL_SYS_VMS) || defined(localtime_r))
+ lcl = localtime_r(&m->time, &result);
+# else
lcl = localtime(&m->time);
-
+# endif
BIO_snprintf(bufp, BUF_REMAIN, "[%02d:%02d:%02d] ",
lcl->tm_hour, lcl->tm_min, lcl->tm_sec);
bufp += strlen(bufp);
}
BIO_snprintf(bufp, BUF_REMAIN, "%5lu file=%s, line=%d, ",
m->order, m->file, m->line);
bufp += strlen(bufp);
if (options & V_CRYPTO_MDEBUG_THREAD) {
BIO_snprintf(bufp, BUF_REMAIN, "thread=%lu, ",
CRYPTO_THREADID_hash(&m->threadid));
bufp += strlen(bufp);
}
BIO_snprintf(bufp, BUF_REMAIN, "number=%d, address=%08lX\n",
m->num, (unsigned long)m->addr);
bufp += strlen(bufp);
BIO_puts(l->bio, buf);
l->chunks++;
l->bytes += m->num;
amip = m->app_info;
ami_cnt = 0;
if (!amip)
return;
CRYPTO_THREADID_cpy(&ti, &amip->threadid);
do {
int buf_len;
int info_len;
ami_cnt++;
memset(buf, '>', ami_cnt);
- BIO_snprintf(buf + ami_cnt, sizeof buf - ami_cnt,
+ BIO_snprintf(buf + ami_cnt, sizeof(buf) - ami_cnt,
" thread=%lu, file=%s, line=%d, info=\"",
CRYPTO_THREADID_hash(&amip->threadid), amip->file,
amip->line);
buf_len = strlen(buf);
info_len = strlen(amip->info);
if (128 - buf_len - 3 < info_len) {
memcpy(buf + buf_len, amip->info, 128 - buf_len - 3);
buf_len = 128 - 3;
} else {
- BUF_strlcpy(buf + buf_len, amip->info, sizeof buf - buf_len);
+ BUF_strlcpy(buf + buf_len, amip->info, sizeof(buf) - buf_len);
buf_len = strlen(buf);
}
- BIO_snprintf(buf + buf_len, sizeof buf - buf_len, "\"\n");
+ BIO_snprintf(buf + buf_len, sizeof(buf) - buf_len, "\"\n");
BIO_puts(l->bio, buf);
amip = amip->next;
}
while (amip && !CRYPTO_THREADID_cmp(&amip->threadid, &ti));
#ifdef LEVITTE_DEBUG_MEM
if (amip) {
fprintf(stderr, "Thread switch detected in backtrace!!!!\n");
abort();
}
#endif
}
static IMPLEMENT_LHASH_DOALL_ARG_FN(print_leak, const MEM, MEM_LEAK)
void CRYPTO_mem_leaks(BIO *b)
{
MEM_LEAK ml;
if (mh == NULL && amih == NULL)
return;
MemCheck_off(); /* obtain MALLOC2 lock */
ml.bio = b;
ml.bytes = 0;
ml.chunks = 0;
if (mh != NULL)
lh_MEM_doall_arg(mh, LHASH_DOALL_ARG_FN(print_leak), MEM_LEAK, &ml);
if (ml.chunks != 0) {
BIO_printf(b, "%ld bytes leaked in %d chunks\n", ml.bytes, ml.chunks);
#ifdef CRYPTO_MDEBUG_ABORT
abort();
#endif
} else {
/*
* Make sure that, if we found no leaks, memory-leak debugging itself
* does not introduce memory leaks (which might irritate external
* debugging tools). (When someone enables leak checking, but does not
* call this function, we declare it to be their fault.) XXX This
* should be in CRYPTO_mem_leaks_cb, and CRYPTO_mem_leaks should be
* implemented by using CRYPTO_mem_leaks_cb. (Also there should be a
* variant of lh_doall_arg that takes a function pointer instead of a
* void *; this would obviate the ugly and illegal void_fn_to_char
* kludge in CRYPTO_mem_leaks_cb. Otherwise the code police will come
* and get us.)
*/
int old_mh_mode;
CRYPTO_w_lock(CRYPTO_LOCK_MALLOC);
/*
* avoid deadlock when lh_free() uses CRYPTO_dbg_free(), which uses
* CRYPTO_is_mem_check_on
*/
old_mh_mode = mh_mode;
mh_mode = CRYPTO_MEM_CHECK_OFF;
if (mh != NULL) {
lh_MEM_free(mh);
mh = NULL;
}
if (amih != NULL) {
if (lh_APP_INFO_num_items(amih) == 0) {
lh_APP_INFO_free(amih);
amih = NULL;
}
}
mh_mode = old_mh_mode;
CRYPTO_w_unlock(CRYPTO_LOCK_MALLOC);
}
MemCheck_on(); /* release MALLOC2 lock */
}
#ifndef OPENSSL_NO_FP_API
void CRYPTO_mem_leaks_fp(FILE *fp)
{
BIO *b;
if (mh == NULL)
return;
/*
* Need to turn off memory checking when allocated BIOs ... especially as
* we're creating them at a time when we're trying to check we've not
* left anything un-free()'d!!
*/
MemCheck_off();
b = BIO_new(BIO_s_file());
MemCheck_on();
if (!b)
return;
BIO_set_fp(b, fp, BIO_NOCLOSE);
CRYPTO_mem_leaks(b);
BIO_free(b);
}
#endif
/*
* FIXME: We really don't allow much to the callback. For example, it has no
* chance of reaching the info stack for the item it processes. Should it
* really be this way? -- Richard Levitte
*/
/*
* NB: The prototypes have been typedef'd to CRYPTO_MEM_LEAK_CB inside
* crypto.h If this code is restructured, remove the callback type if it is
* no longer needed. -- Geoff Thorpe
*/
/*
* Can't pass CRYPTO_MEM_LEAK_CB directly to lh_MEM_doall_arg because it is a
* function pointer and conversion to void * is prohibited. Instead pass its
* address
*/
typedef CRYPTO_MEM_LEAK_CB *PCRYPTO_MEM_LEAK_CB;
static void cb_leak_doall_arg(const MEM *m, PCRYPTO_MEM_LEAK_CB *cb)
{
(*cb) (m->order, m->file, m->line, m->num, m->addr);
}
static IMPLEMENT_LHASH_DOALL_ARG_FN(cb_leak, const MEM, PCRYPTO_MEM_LEAK_CB)
void CRYPTO_mem_leaks_cb(CRYPTO_MEM_LEAK_CB *cb)
{
if (mh == NULL)
return;
CRYPTO_w_lock(CRYPTO_LOCK_MALLOC2);
lh_MEM_doall_arg(mh, LHASH_DOALL_ARG_FN(cb_leak), PCRYPTO_MEM_LEAK_CB,
&cb);
CRYPTO_w_unlock(CRYPTO_LOCK_MALLOC2);
}
diff --git a/crypto/o_init.c b/crypto/o_init.c
index 185841ea048c..18bb85894d36 100644
--- a/crypto/o_init.c
+++ b/crypto/o_init.c
@@ -1,86 +1,91 @@
/* o_init.c */
/*
* Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL
* project.
*/
/* ====================================================================
* Copyright (c) 2011 The OpenSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* openssl-core@openssl.org.
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.openssl.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*
*/
#include <e_os.h>
#include <openssl/err.h>
#ifdef OPENSSL_FIPS
# include <openssl/fips.h>
# include <openssl/rand.h>
+
+# ifndef OPENSSL_NO_DEPRECATED
+/* the prototype is missing in <openssl/fips.h> */
+void FIPS_crypto_set_id_callback(unsigned long (*func)(void));
+# endif
#endif
/*
* Perform any essential OpenSSL initialization operations. Currently only
* sets FIPS callbacks
*/
void OPENSSL_init(void)
{
static int done = 0;
if (done)
return;
done = 1;
#ifdef OPENSSL_FIPS
FIPS_set_locking_callbacks(CRYPTO_lock, CRYPTO_add_lock);
# ifndef OPENSSL_NO_DEPRECATED
FIPS_crypto_set_id_callback(CRYPTO_thread_id);
# endif
FIPS_set_error_callbacks(ERR_put_error, ERR_add_error_vdata);
FIPS_set_malloc_callbacks(CRYPTO_malloc, CRYPTO_free);
RAND_init_fips();
#endif
#if 0
fprintf(stderr, "Called OPENSSL_init\n");
#endif
}
diff --git a/crypto/o_time.c b/crypto/o_time.c
index 04d805d9a96d..61927439eaf5 100644
--- a/crypto/o_time.c
+++ b/crypto/o_time.c
@@ -1,474 +1,474 @@
/* crypto/o_time.c */
/*
* Written by Richard Levitte (richard@levitte.org) for the OpenSSL project
* 2001.
*/
/*
* Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL project
* 2008.
*/
/* ====================================================================
- * Copyright (c) 2001 The OpenSSL Project. All rights reserved.
+ * Copyright (c) 2001-2018 The OpenSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* licensing@OpenSSL.org.
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*
* This product includes cryptographic software written by Eric Young
* (eay@cryptsoft.com). This product includes software written by Tim
* Hudson (tjh@cryptsoft.com).
*
*/
#include <openssl/e_os2.h>
#include <string.h>
#include "o_time.h"
#ifdef OPENSSL_SYS_VMS
# if __CRTL_VER >= 70000000 && \
(defined _POSIX_C_SOURCE || !defined _ANSI_C_SOURCE)
# define VMS_GMTIME_OK
# endif
# ifndef VMS_GMTIME_OK
# include <libdtdef.h>
# include <lib$routines.h>
# include <lnmdef.h>
# include <starlet.h>
# include <descrip.h>
# include <stdlib.h>
# endif /* ndef VMS_GMTIME_OK */
/*
* Needed to pick up the correct definitions and declarations in some of the
* DEC C Header Files (*.H).
*/
# define __NEW_STARLET 1
# if (defined(__alpha) || defined(__ia64))
# include <iledef.h>
# else
/* VAX */
typedef struct _ile3 { /* Copied from ILEDEF.H for Alpha */
# pragma __nomember_alignment
unsigned short int ile3$w_length; /* Length of buffer in bytes */
unsigned short int ile3$w_code; /* Item code value */
void *ile3$ps_bufaddr; /* Buffer address */
unsigned short int *ile3$ps_retlen_addr; /* Address of word for returned length */
} ILE3;
# endif /* alpha || ia64 */
#endif /* OPENSSL_SYS_VMS */
struct tm *OPENSSL_gmtime(const time_t *timer, struct tm *result)
{
struct tm *ts = NULL;
-#if defined(OPENSSL_THREADS) && !defined(OPENSSL_SYS_WIN32) && !defined(OPENSSL_SYS_OS2) && (!defined(OPENSSL_SYS_VMS) || defined(gmtime_r)) && !defined(OPENSSL_SYS_MACOSX) && !defined(OPENSSL_SYS_SUNOS)
+#if defined(OPENSSL_THREADS) && !defined(OPENSSL_SYS_WIN32) && !defined(OPENSSL_SYS_OS2) && (!defined(OPENSSL_SYS_VMS) || defined(gmtime_r)) && !defined(OPENSSL_SYS_SUNOS)
if (gmtime_r(timer, result) == NULL)
return NULL;
ts = result;
#elif !defined(OPENSSL_SYS_VMS) || defined(VMS_GMTIME_OK)
ts = gmtime(timer);
if (ts == NULL)
return NULL;
memcpy(result, ts, sizeof(struct tm));
ts = result;
#endif
#if defined( OPENSSL_SYS_VMS) && !defined( VMS_GMTIME_OK)
if (ts == NULL) {
static $DESCRIPTOR(tabnam, "LNM$DCL_LOGICAL");
static $DESCRIPTOR(lognam, "SYS$TIMEZONE_DIFFERENTIAL");
char logvalue[256];
unsigned int reslen = 0;
# if __INITIAL_POINTER_SIZE == 64
ILEB_64 itemlist[2], *pitem;
# else
ILE3 itemlist[2], *pitem;
# endif
int status;
time_t t;
/*
* Setup an itemlist for the call to $TRNLNM - Translate Logical Name.
*/
pitem = itemlist;
# if __INITIAL_POINTER_SIZE == 64
pitem->ileb_64$w_mbo = 1;
pitem->ileb_64$w_code = LNM$_STRING;
pitem->ileb_64$l_mbmo = -1;
- pitem->ileb_64$q_length = sizeof (logvalue);
+ pitem->ileb_64$q_length = sizeof(logvalue);
pitem->ileb_64$pq_bufaddr = logvalue;
pitem->ileb_64$pq_retlen_addr = (unsigned __int64 *) &reslen;
pitem++;
/* Last item of the item list is null terminated */
pitem->ileb_64$q_length = pitem->ileb_64$w_code = 0;
# else
- pitem->ile3$w_length = sizeof (logvalue);
+ pitem->ile3$w_length = sizeof(logvalue);
pitem->ile3$w_code = LNM$_STRING;
pitem->ile3$ps_bufaddr = logvalue;
pitem->ile3$ps_retlen_addr = (unsigned short int *) &reslen;
pitem++;
/* Last item of the item list is null terminated */
pitem->ile3$w_length = pitem->ile3$w_code = 0;
# endif
/* Get the value for SYS$TIMEZONE_DIFFERENTIAL */
status = sys$trnlnm(0, &tabnam, &lognam, 0, itemlist);
if (!(status & 1))
return NULL;
logvalue[reslen] = '\0';
t = *timer;
/* The following is extracted from the DEC C header time.h */
/*
** Beginning in OpenVMS Version 7.0 mktime, time, ctime, strftime
** have two implementations. One implementation is provided
** for compatibility and deals with time in terms of local time,
** the other __utc_* deals with time in terms of UTC.
*/
/*
* We use the same conditions as in said time.h to check if we should
* assume that t contains local time (and should therefore be
* adjusted) or UTC (and should therefore be left untouched).
*/
# if __CRTL_VER < 70000000 || defined _VMS_V6_SOURCE
/* Get the numerical value of the equivalence string */
status = atoi(logvalue);
/* and use it to move time to GMT */
t -= status;
# endif
/* then convert the result to the time structure */
/*
* Since there was no gmtime_r() to do this stuff for us, we have to
* do it the hard way.
*/
{
/*-
* The VMS epoch is the astronomical Smithsonian date,
if I remember correctly, which is November 17, 1858.
Furthermore, time is measure in thenths of microseconds
and stored in quadwords (64 bit integers). unix_epoch
below is January 1st 1970 expressed as a VMS time. The
following code was used to get this number:
#include <stdio.h>
#include <stdlib.h>
#include <lib$routines.h>
#include <starlet.h>
main()
{
unsigned long systime[2];
unsigned short epoch_values[7] =
{ 1970, 1, 1, 0, 0, 0, 0 };
lib$cvt_vectim(epoch_values, systime);
printf("%u %u", systime[0], systime[1]);
}
*/
unsigned long unix_epoch[2] = { 1273708544, 8164711 };
unsigned long deltatime[2];
unsigned long systime[2];
struct vms_vectime {
short year, month, day, hour, minute, second, centi_second;
} time_values;
long operation;
/*
* Turn the number of seconds since January 1st 1970 to an
* internal delta time. Note that lib$cvt_to_internal_time() will
* assume that t is signed, and will therefore break on 32-bit
* systems some time in 2038.
*/
operation = LIB$K_DELTA_SECONDS;
status = lib$cvt_to_internal_time(&operation, &t, deltatime);
/*
* Add the delta time with the Unix epoch and we have the current
* UTC time in internal format
*/
status = lib$add_times(unix_epoch, deltatime, systime);
/* Turn the internal time into a time vector */
status = sys$numtim(&time_values, systime);
/* Fill in the struct tm with the result */
result->tm_sec = time_values.second;
result->tm_min = time_values.minute;
result->tm_hour = time_values.hour;
result->tm_mday = time_values.day;
result->tm_mon = time_values.month - 1;
result->tm_year = time_values.year - 1900;
operation = LIB$K_DAY_OF_WEEK;
status = lib$cvt_from_internal_time(&operation,
&result->tm_wday, systime);
result->tm_wday %= 7;
operation = LIB$K_DAY_OF_YEAR;
status = lib$cvt_from_internal_time(&operation,
&result->tm_yday, systime);
result->tm_yday--;
result->tm_isdst = 0; /* There's no way to know... */
ts = result;
}
}
#endif
return ts;
}
/*
* Take a tm structure and add an offset to it. This avoids any OS issues
* with restricted date types and overflows which cause the year 2038
* problem.
*/
#define SECS_PER_DAY (24 * 60 * 60)
static long date_to_julian(int y, int m, int d);
static void julian_to_date(long jd, int *y, int *m, int *d);
static int julian_adj(const struct tm *tm, int off_day, long offset_sec,
long *pday, int *psec);
int OPENSSL_gmtime_adj(struct tm *tm, int off_day, long offset_sec)
{
int time_sec, time_year, time_month, time_day;
long time_jd;
/* Convert time and offset into julian day and seconds */
if (!julian_adj(tm, off_day, offset_sec, &time_jd, &time_sec))
return 0;
/* Convert Julian day back to date */
julian_to_date(time_jd, &time_year, &time_month, &time_day);
if (time_year < 1900 || time_year > 9999)
return 0;
/* Update tm structure */
tm->tm_year = time_year - 1900;
tm->tm_mon = time_month - 1;
tm->tm_mday = time_day;
tm->tm_hour = time_sec / 3600;
tm->tm_min = (time_sec / 60) % 60;
tm->tm_sec = time_sec % 60;
return 1;
}
int OPENSSL_gmtime_diff(int *pday, int *psec,
const struct tm *from, const struct tm *to)
{
int from_sec, to_sec, diff_sec;
long from_jd, to_jd, diff_day;
if (!julian_adj(from, 0, 0, &from_jd, &from_sec))
return 0;
if (!julian_adj(to, 0, 0, &to_jd, &to_sec))
return 0;
diff_day = to_jd - from_jd;
diff_sec = to_sec - from_sec;
/* Adjust differences so both positive or both negative */
if (diff_day > 0 && diff_sec < 0) {
diff_day--;
diff_sec += SECS_PER_DAY;
}
if (diff_day < 0 && diff_sec > 0) {
diff_day++;
diff_sec -= SECS_PER_DAY;
}
if (pday)
*pday = (int)diff_day;
if (psec)
*psec = diff_sec;
return 1;
}
/* Convert tm structure and offset into julian day and seconds */
static int julian_adj(const struct tm *tm, int off_day, long offset_sec,
long *pday, int *psec)
{
int offset_hms, offset_day;
long time_jd;
int time_year, time_month, time_day;
/* split offset into days and day seconds */
offset_day = offset_sec / SECS_PER_DAY;
/* Avoid sign issues with % operator */
offset_hms = offset_sec - (offset_day * SECS_PER_DAY);
offset_day += off_day;
/* Add current time seconds to offset */
offset_hms += tm->tm_hour * 3600 + tm->tm_min * 60 + tm->tm_sec;
/* Adjust day seconds if overflow */
if (offset_hms >= SECS_PER_DAY) {
offset_day++;
offset_hms -= SECS_PER_DAY;
} else if (offset_hms < 0) {
offset_day--;
offset_hms += SECS_PER_DAY;
}
/*
* Convert date of time structure into a Julian day number.
*/
time_year = tm->tm_year + 1900;
time_month = tm->tm_mon + 1;
time_day = tm->tm_mday;
time_jd = date_to_julian(time_year, time_month, time_day);
/* Work out Julian day of new date */
time_jd += offset_day;
if (time_jd < 0)
return 0;
*pday = time_jd;
*psec = offset_hms;
return 1;
}
/*
* Convert date to and from julian day Uses Fliegel & Van Flandern algorithm
*/
static long date_to_julian(int y, int m, int d)
{
return (1461 * (y + 4800 + (m - 14) / 12)) / 4 +
(367 * (m - 2 - 12 * ((m - 14) / 12))) / 12 -
(3 * ((y + 4900 + (m - 14) / 12) / 100)) / 4 + d - 32075;
}
static void julian_to_date(long jd, int *y, int *m, int *d)
{
long L = jd + 68569;
long n = (4 * L) / 146097;
long i, j;
L = L - (146097 * n + 3) / 4;
i = (4000 * (L + 1)) / 1461001;
L = L - (1461 * i) / 4 + 31;
j = (80 * L) / 2447;
*d = L - (2447 * j) / 80;
L = j / 11;
*m = j + 2 - (12 * L);
*y = 100 * (n - 49) + i + L;
}
#ifdef OPENSSL_TIME_TEST
# include <stdio.h>
/*
* Time checking test code. Check times are identical for a wide range of
* offsets. This should be run on a machine with 64 bit time_t or it will
* trigger the very errors the routines fix.
*/
int main(int argc, char **argv)
{
long offset;
for (offset = 0; offset < 1000000; offset++) {
check_time(offset);
check_time(-offset);
check_time(offset * 1000);
check_time(-offset * 1000);
}
}
int check_time(long offset)
{
struct tm tm1, tm2, o1;
int off_day, off_sec;
long toffset;
time_t t1, t2;
time(&t1);
t2 = t1 + offset;
OPENSSL_gmtime(&t2, &tm2);
OPENSSL_gmtime(&t1, &tm1);
o1 = tm1;
OPENSSL_gmtime_adj(&tm1, 0, offset);
if ((tm1.tm_year != tm2.tm_year) ||
(tm1.tm_mon != tm2.tm_mon) ||
(tm1.tm_mday != tm2.tm_mday) ||
(tm1.tm_hour != tm2.tm_hour) ||
(tm1.tm_min != tm2.tm_min) || (tm1.tm_sec != tm2.tm_sec)) {
fprintf(stderr, "TIME ERROR!!\n");
fprintf(stderr, "Time1: %d/%d/%d, %d:%02d:%02d\n",
tm2.tm_mday, tm2.tm_mon + 1, tm2.tm_year + 1900,
tm2.tm_hour, tm2.tm_min, tm2.tm_sec);
fprintf(stderr, "Time2: %d/%d/%d, %d:%02d:%02d\n",
tm1.tm_mday, tm1.tm_mon + 1, tm1.tm_year + 1900,
tm1.tm_hour, tm1.tm_min, tm1.tm_sec);
return 0;
}
OPENSSL_gmtime_diff(&o1, &tm1, &off_day, &off_sec);
toffset = (long)off_day *SECS_PER_DAY + off_sec;
if (offset != toffset) {
fprintf(stderr, "TIME OFFSET ERROR!!\n");
fprintf(stderr, "Expected %ld, Got %ld (%d:%d)\n",
offset, toffset, off_day, off_sec);
return 0;
}
return 1;
}
#endif
diff --git a/crypto/objects/o_names.c b/crypto/objects/o_names.c
index f106905ffa77..b8bdc5c5202e 100644
--- a/crypto/objects/o_names.c
+++ b/crypto/objects/o_names.c
@@ -1,367 +1,367 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/err.h>
#include <openssl/lhash.h>
#include <openssl/objects.h>
#include <openssl/safestack.h>
#include <openssl/e_os2.h>
/*
* Later versions of DEC C has started to add lnkage information to certain
* functions, which makes it tricky to use them as values to regular function
* pointers. One way is to define a macro that takes care of casting them
* correctly.
*/
#ifdef OPENSSL_SYS_VMS_DECC
# define OPENSSL_strcmp (int (*)(const char *,const char *))strcmp
#else
# define OPENSSL_strcmp strcmp
#endif
/*
* I use the ex_data stuff to manage the identifiers for the obj_name_types
* that applications may define. I only really use the free function field.
*/
DECLARE_LHASH_OF(OBJ_NAME);
static LHASH_OF(OBJ_NAME) *names_lh = NULL;
static int names_type_num = OBJ_NAME_TYPE_NUM;
typedef struct name_funcs_st {
unsigned long (*hash_func) (const char *name);
int (*cmp_func) (const char *a, const char *b);
void (*free_func) (const char *, int, const char *);
} NAME_FUNCS;
DECLARE_STACK_OF(NAME_FUNCS)
IMPLEMENT_STACK_OF(NAME_FUNCS)
static STACK_OF(NAME_FUNCS) *name_funcs_stack;
/*
* The LHASH callbacks now use the raw "void *" prototypes and do
* per-variable casting in the functions. This prevents function pointer
* casting without the need for macro-generated wrapper functions.
*/
/* static unsigned long obj_name_hash(OBJ_NAME *a); */
static unsigned long obj_name_hash(const void *a_void);
/* static int obj_name_cmp(OBJ_NAME *a,OBJ_NAME *b); */
static int obj_name_cmp(const void *a_void, const void *b_void);
static IMPLEMENT_LHASH_HASH_FN(obj_name, OBJ_NAME)
static IMPLEMENT_LHASH_COMP_FN(obj_name, OBJ_NAME)
int OBJ_NAME_init(void)
{
if (names_lh != NULL)
return (1);
MemCheck_off();
names_lh = lh_OBJ_NAME_new();
MemCheck_on();
return (names_lh != NULL);
}
int OBJ_NAME_new_index(unsigned long (*hash_func) (const char *),
int (*cmp_func) (const char *, const char *),
void (*free_func) (const char *, int, const char *))
{
int ret;
int i;
NAME_FUNCS *name_funcs;
if (name_funcs_stack == NULL) {
MemCheck_off();
name_funcs_stack = sk_NAME_FUNCS_new_null();
MemCheck_on();
}
if (name_funcs_stack == NULL) {
/* ERROR */
return (0);
}
ret = names_type_num;
names_type_num++;
for (i = sk_NAME_FUNCS_num(name_funcs_stack); i < names_type_num; i++) {
MemCheck_off();
name_funcs = OPENSSL_malloc(sizeof(NAME_FUNCS));
MemCheck_on();
if (!name_funcs) {
OBJerr(OBJ_F_OBJ_NAME_NEW_INDEX, ERR_R_MALLOC_FAILURE);
return (0);
}
name_funcs->hash_func = lh_strhash;
name_funcs->cmp_func = OPENSSL_strcmp;
name_funcs->free_func = 0; /* NULL is often declared to * ((void
* *)0), which according * to Compaq C is
* not really * compatible with a function
* * pointer. -- Richard Levitte */
MemCheck_off();
sk_NAME_FUNCS_push(name_funcs_stack, name_funcs);
MemCheck_on();
}
name_funcs = sk_NAME_FUNCS_value(name_funcs_stack, ret);
if (hash_func != NULL)
name_funcs->hash_func = hash_func;
if (cmp_func != NULL)
name_funcs->cmp_func = cmp_func;
if (free_func != NULL)
name_funcs->free_func = free_func;
return (ret);
}
/* static int obj_name_cmp(OBJ_NAME *a, OBJ_NAME *b) */
static int obj_name_cmp(const void *a_void, const void *b_void)
{
int ret;
const OBJ_NAME *a = (const OBJ_NAME *)a_void;
const OBJ_NAME *b = (const OBJ_NAME *)b_void;
ret = a->type - b->type;
if (ret == 0) {
if ((name_funcs_stack != NULL)
&& (sk_NAME_FUNCS_num(name_funcs_stack) > a->type)) {
ret = sk_NAME_FUNCS_value(name_funcs_stack,
a->type)->cmp_func(a->name, b->name);
} else
ret = strcmp(a->name, b->name);
}
return (ret);
}
/* static unsigned long obj_name_hash(OBJ_NAME *a) */
static unsigned long obj_name_hash(const void *a_void)
{
unsigned long ret;
const OBJ_NAME *a = (const OBJ_NAME *)a_void;
if ((name_funcs_stack != NULL)
&& (sk_NAME_FUNCS_num(name_funcs_stack) > a->type)) {
ret =
sk_NAME_FUNCS_value(name_funcs_stack,
a->type)->hash_func(a->name);
} else {
ret = lh_strhash(a->name);
}
ret ^= a->type;
return (ret);
}
const char *OBJ_NAME_get(const char *name, int type)
{
OBJ_NAME on, *ret;
int num = 0, alias;
if (name == NULL)
return (NULL);
if ((names_lh == NULL) && !OBJ_NAME_init())
return (NULL);
alias = type & OBJ_NAME_ALIAS;
type &= ~OBJ_NAME_ALIAS;
on.name = name;
on.type = type;
for (;;) {
ret = lh_OBJ_NAME_retrieve(names_lh, &on);
if (ret == NULL)
return (NULL);
if ((ret->alias) && !alias) {
if (++num > 10)
return (NULL);
on.name = ret->data;
} else {
return (ret->data);
}
}
}
int OBJ_NAME_add(const char *name, int type, const char *data)
{
OBJ_NAME *onp, *ret;
int alias;
if ((names_lh == NULL) && !OBJ_NAME_init())
return (0);
alias = type & OBJ_NAME_ALIAS;
type &= ~OBJ_NAME_ALIAS;
onp = (OBJ_NAME *)OPENSSL_malloc(sizeof(OBJ_NAME));
if (onp == NULL) {
/* ERROR */
return 0;
}
onp->name = name;
onp->alias = alias;
onp->type = type;
onp->data = data;
ret = lh_OBJ_NAME_insert(names_lh, onp);
if (ret != NULL) {
/* free things */
if ((name_funcs_stack != NULL)
&& (sk_NAME_FUNCS_num(name_funcs_stack) > ret->type)) {
/*
* XXX: I'm not sure I understand why the free function should
* get three arguments... -- Richard Levitte
*/
sk_NAME_FUNCS_value(name_funcs_stack,
ret->type)->free_func(ret->name, ret->type,
ret->data);
}
OPENSSL_free(ret);
} else {
if (lh_OBJ_NAME_error(names_lh)) {
/* ERROR */
OPENSSL_free(onp);
return 0;
}
}
return 1;
}
int OBJ_NAME_remove(const char *name, int type)
{
OBJ_NAME on, *ret;
if (names_lh == NULL)
return (0);
type &= ~OBJ_NAME_ALIAS;
on.name = name;
on.type = type;
ret = lh_OBJ_NAME_delete(names_lh, &on);
if (ret != NULL) {
/* free things */
if ((name_funcs_stack != NULL)
&& (sk_NAME_FUNCS_num(name_funcs_stack) > ret->type)) {
/*
* XXX: I'm not sure I understand why the free function should
* get three arguments... -- Richard Levitte
*/
sk_NAME_FUNCS_value(name_funcs_stack,
ret->type)->free_func(ret->name, ret->type,
ret->data);
}
OPENSSL_free(ret);
return (1);
} else
return (0);
}
struct doall {
int type;
void (*fn) (const OBJ_NAME *, void *arg);
void *arg;
};
static void do_all_fn_doall_arg(const OBJ_NAME *name, struct doall *d)
{
if (name->type == d->type)
d->fn(name, d->arg);
}
static IMPLEMENT_LHASH_DOALL_ARG_FN(do_all_fn, const OBJ_NAME, struct doall)
void OBJ_NAME_do_all(int type, void (*fn) (const OBJ_NAME *, void *arg),
void *arg)
{
struct doall d;
d.type = type;
d.fn = fn;
d.arg = arg;
lh_OBJ_NAME_doall_arg(names_lh, LHASH_DOALL_ARG_FN(do_all_fn),
struct doall, &d);
}
struct doall_sorted {
int type;
int n;
const OBJ_NAME **names;
};
static void do_all_sorted_fn(const OBJ_NAME *name, void *d_)
{
struct doall_sorted *d = d_;
if (name->type != d->type)
return;
d->names[d->n++] = name;
}
static int do_all_sorted_cmp(const void *n1_, const void *n2_)
{
const OBJ_NAME *const *n1 = n1_;
const OBJ_NAME *const *n2 = n2_;
return strcmp((*n1)->name, (*n2)->name);
}
void OBJ_NAME_do_all_sorted(int type,
void (*fn) (const OBJ_NAME *, void *arg),
void *arg)
{
struct doall_sorted d;
int n;
d.type = type;
d.names =
- OPENSSL_malloc(lh_OBJ_NAME_num_items(names_lh) * sizeof *d.names);
+ OPENSSL_malloc(lh_OBJ_NAME_num_items(names_lh) * sizeof(*d.names));
/* Really should return an error if !d.names...but its a void function! */
if (d.names) {
d.n = 0;
OBJ_NAME_do_all(type, do_all_sorted_fn, &d);
- qsort((void *)d.names, d.n, sizeof *d.names, do_all_sorted_cmp);
+ qsort((void *)d.names, d.n, sizeof(*d.names), do_all_sorted_cmp);
for (n = 0; n < d.n; ++n)
fn(d.names[n], arg);
OPENSSL_free((void *)d.names);
}
}
static int free_type;
static void names_lh_free_doall(OBJ_NAME *onp)
{
if (onp == NULL)
return;
if (free_type < 0 || free_type == onp->type)
OBJ_NAME_remove(onp->name, onp->type);
}
static IMPLEMENT_LHASH_DOALL_FN(names_lh_free, OBJ_NAME)
static void name_funcs_free(NAME_FUNCS *ptr)
{
OPENSSL_free(ptr);
}
void OBJ_NAME_cleanup(int type)
{
unsigned long down_load;
if (names_lh == NULL)
return;
free_type = type;
down_load = lh_OBJ_NAME_down_load(names_lh);
lh_OBJ_NAME_down_load(names_lh) = 0;
lh_OBJ_NAME_doall(names_lh, LHASH_DOALL_FN(names_lh_free));
if (type < 0) {
lh_OBJ_NAME_free(names_lh);
sk_NAME_FUNCS_pop_free(name_funcs_stack, name_funcs_free);
names_lh = NULL;
name_funcs_stack = NULL;
} else
lh_OBJ_NAME_down_load(names_lh) = down_load;
}
diff --git a/crypto/objects/obj_dat.c b/crypto/objects/obj_dat.c
index aca382a6e9f3..315afa9dbed3 100644
--- a/crypto/objects/obj_dat.c
+++ b/crypto/objects/obj_dat.c
@@ -1,801 +1,807 @@
/* crypto/objects/obj_dat.c */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
#include <stdio.h>
#include <ctype.h>
#include <limits.h>
#include "cryptlib.h"
#include <openssl/lhash.h>
#include <openssl/asn1.h>
#include <openssl/objects.h>
#include <openssl/bn.h>
/* obj_dat.h is generated from objects.h by obj_dat.pl */
#ifndef OPENSSL_NO_OBJECT
# include "obj_dat.h"
#else
/* You will have to load all the objects needed manually in the application */
# define NUM_NID 0
# define NUM_SN 0
# define NUM_LN 0
# define NUM_OBJ 0
static const unsigned char lvalues[1];
static const ASN1_OBJECT nid_objs[1];
static const unsigned int sn_objs[1];
static const unsigned int ln_objs[1];
static const unsigned int obj_objs[1];
#endif
DECLARE_OBJ_BSEARCH_CMP_FN(const ASN1_OBJECT *, unsigned int, sn);
DECLARE_OBJ_BSEARCH_CMP_FN(const ASN1_OBJECT *, unsigned int, ln);
DECLARE_OBJ_BSEARCH_CMP_FN(const ASN1_OBJECT *, unsigned int, obj);
#define ADDED_DATA 0
#define ADDED_SNAME 1
#define ADDED_LNAME 2
#define ADDED_NID 3
typedef struct added_obj_st {
int type;
ASN1_OBJECT *obj;
} ADDED_OBJ;
DECLARE_LHASH_OF(ADDED_OBJ);
static int new_nid = NUM_NID;
static LHASH_OF(ADDED_OBJ) *added = NULL;
static int sn_cmp(const ASN1_OBJECT *const *a, const unsigned int *b)
{
return (strcmp((*a)->sn, nid_objs[*b].sn));
}
IMPLEMENT_OBJ_BSEARCH_CMP_FN(const ASN1_OBJECT *, unsigned int, sn);
static int ln_cmp(const ASN1_OBJECT *const *a, const unsigned int *b)
{
return (strcmp((*a)->ln, nid_objs[*b].ln));
}
IMPLEMENT_OBJ_BSEARCH_CMP_FN(const ASN1_OBJECT *, unsigned int, ln);
static unsigned long added_obj_hash(const ADDED_OBJ *ca)
{
const ASN1_OBJECT *a;
int i;
unsigned long ret = 0;
unsigned char *p;
a = ca->obj;
switch (ca->type) {
case ADDED_DATA:
ret = a->length << 20L;
p = (unsigned char *)a->data;
for (i = 0; i < a->length; i++)
ret ^= p[i] << ((i * 3) % 24);
break;
case ADDED_SNAME:
ret = lh_strhash(a->sn);
break;
case ADDED_LNAME:
ret = lh_strhash(a->ln);
break;
case ADDED_NID:
ret = a->nid;
break;
default:
/* abort(); */
return 0;
}
ret &= 0x3fffffffL;
ret |= ((unsigned long)ca->type) << 30L;
return (ret);
}
static IMPLEMENT_LHASH_HASH_FN(added_obj, ADDED_OBJ)
static int added_obj_cmp(const ADDED_OBJ *ca, const ADDED_OBJ *cb)
{
ASN1_OBJECT *a, *b;
int i;
i = ca->type - cb->type;
if (i)
return (i);
a = ca->obj;
b = cb->obj;
switch (ca->type) {
case ADDED_DATA:
i = (a->length - b->length);
if (i)
return (i);
return (memcmp(a->data, b->data, (size_t)a->length));
case ADDED_SNAME:
if (a->sn == NULL)
return (-1);
else if (b->sn == NULL)
return (1);
else
return (strcmp(a->sn, b->sn));
case ADDED_LNAME:
if (a->ln == NULL)
return (-1);
else if (b->ln == NULL)
return (1);
else
return (strcmp(a->ln, b->ln));
case ADDED_NID:
return (a->nid - b->nid);
default:
/* abort(); */
return 0;
}
}
static IMPLEMENT_LHASH_COMP_FN(added_obj, ADDED_OBJ)
static int init_added(void)
{
if (added != NULL)
return (1);
added = lh_ADDED_OBJ_new();
return (added != NULL);
}
static void cleanup1_doall(ADDED_OBJ *a)
{
a->obj->nid = 0;
a->obj->flags |= ASN1_OBJECT_FLAG_DYNAMIC |
ASN1_OBJECT_FLAG_DYNAMIC_STRINGS | ASN1_OBJECT_FLAG_DYNAMIC_DATA;
}
static void cleanup2_doall(ADDED_OBJ *a)
{
a->obj->nid++;
}
static void cleanup3_doall(ADDED_OBJ *a)
{
if (--a->obj->nid == 0)
ASN1_OBJECT_free(a->obj);
OPENSSL_free(a);
}
static IMPLEMENT_LHASH_DOALL_FN(cleanup1, ADDED_OBJ)
static IMPLEMENT_LHASH_DOALL_FN(cleanup2, ADDED_OBJ)
static IMPLEMENT_LHASH_DOALL_FN(cleanup3, ADDED_OBJ)
/*
* The purpose of obj_cleanup_defer is to avoid EVP_cleanup() attempting to
* use freed up OIDs. If neccessary the actual freeing up of OIDs is delayed.
*/
int obj_cleanup_defer = 0;
void check_defer(int nid)
{
if (!obj_cleanup_defer && nid >= NUM_NID)
obj_cleanup_defer = 1;
}
void OBJ_cleanup(void)
{
if (obj_cleanup_defer) {
obj_cleanup_defer = 2;
return;
}
if (added == NULL)
return;
lh_ADDED_OBJ_down_load(added) = 0;
lh_ADDED_OBJ_doall(added, LHASH_DOALL_FN(cleanup1)); /* zero counters */
lh_ADDED_OBJ_doall(added, LHASH_DOALL_FN(cleanup2)); /* set counters */
lh_ADDED_OBJ_doall(added, LHASH_DOALL_FN(cleanup3)); /* free objects */
lh_ADDED_OBJ_free(added);
added = NULL;
}
int OBJ_new_nid(int num)
{
int i;
i = new_nid;
new_nid += num;
return (i);
}
int OBJ_add_object(const ASN1_OBJECT *obj)
{
ASN1_OBJECT *o;
ADDED_OBJ *ao[4] = { NULL, NULL, NULL, NULL }, *aop;
int i;
if (added == NULL)
if (!init_added())
return (0);
if ((o = OBJ_dup(obj)) == NULL)
goto err;
if (!(ao[ADDED_NID] = (ADDED_OBJ *)OPENSSL_malloc(sizeof(ADDED_OBJ))))
goto err2;
if ((o->length != 0) && (obj->data != NULL))
if (!
(ao[ADDED_DATA] = (ADDED_OBJ *)OPENSSL_malloc(sizeof(ADDED_OBJ))))
goto err2;
if (o->sn != NULL)
if (!
(ao[ADDED_SNAME] =
(ADDED_OBJ *)OPENSSL_malloc(sizeof(ADDED_OBJ))))
goto err2;
if (o->ln != NULL)
if (!
(ao[ADDED_LNAME] =
(ADDED_OBJ *)OPENSSL_malloc(sizeof(ADDED_OBJ))))
goto err2;
for (i = ADDED_DATA; i <= ADDED_NID; i++) {
if (ao[i] != NULL) {
ao[i]->type = i;
ao[i]->obj = o;
aop = lh_ADDED_OBJ_insert(added, ao[i]);
/* memory leak, buit should not normally matter */
if (aop != NULL)
OPENSSL_free(aop);
}
}
o->flags &=
~(ASN1_OBJECT_FLAG_DYNAMIC | ASN1_OBJECT_FLAG_DYNAMIC_STRINGS |
ASN1_OBJECT_FLAG_DYNAMIC_DATA);
return (o->nid);
err2:
OBJerr(OBJ_F_OBJ_ADD_OBJECT, ERR_R_MALLOC_FAILURE);
err:
for (i = ADDED_DATA; i <= ADDED_NID; i++)
if (ao[i] != NULL)
OPENSSL_free(ao[i]);
- if (o != NULL)
- OPENSSL_free(o);
- return (NID_undef);
+ ASN1_OBJECT_free(o);
+ return NID_undef;
}
ASN1_OBJECT *OBJ_nid2obj(int n)
{
ADDED_OBJ ad, *adp;
ASN1_OBJECT ob;
if ((n >= 0) && (n < NUM_NID)) {
if ((n != NID_undef) && (nid_objs[n].nid == NID_undef)) {
OBJerr(OBJ_F_OBJ_NID2OBJ, OBJ_R_UNKNOWN_NID);
return (NULL);
}
return ((ASN1_OBJECT *)&(nid_objs[n]));
} else if (added == NULL)
return (NULL);
else {
ad.type = ADDED_NID;
ad.obj = &ob;
ob.nid = n;
adp = lh_ADDED_OBJ_retrieve(added, &ad);
if (adp != NULL)
return (adp->obj);
else {
OBJerr(OBJ_F_OBJ_NID2OBJ, OBJ_R_UNKNOWN_NID);
return (NULL);
}
}
}
const char *OBJ_nid2sn(int n)
{
ADDED_OBJ ad, *adp;
ASN1_OBJECT ob;
if ((n >= 0) && (n < NUM_NID)) {
if ((n != NID_undef) && (nid_objs[n].nid == NID_undef)) {
OBJerr(OBJ_F_OBJ_NID2SN, OBJ_R_UNKNOWN_NID);
return (NULL);
}
return (nid_objs[n].sn);
} else if (added == NULL)
return (NULL);
else {
ad.type = ADDED_NID;
ad.obj = &ob;
ob.nid = n;
adp = lh_ADDED_OBJ_retrieve(added, &ad);
if (adp != NULL)
return (adp->obj->sn);
else {
OBJerr(OBJ_F_OBJ_NID2SN, OBJ_R_UNKNOWN_NID);
return (NULL);
}
}
}
const char *OBJ_nid2ln(int n)
{
ADDED_OBJ ad, *adp;
ASN1_OBJECT ob;
if ((n >= 0) && (n < NUM_NID)) {
if ((n != NID_undef) && (nid_objs[n].nid == NID_undef)) {
OBJerr(OBJ_F_OBJ_NID2LN, OBJ_R_UNKNOWN_NID);
return (NULL);
}
return (nid_objs[n].ln);
} else if (added == NULL)
return (NULL);
else {
ad.type = ADDED_NID;
ad.obj = &ob;
ob.nid = n;
adp = lh_ADDED_OBJ_retrieve(added, &ad);
if (adp != NULL)
return (adp->obj->ln);
else {
OBJerr(OBJ_F_OBJ_NID2LN, OBJ_R_UNKNOWN_NID);
return (NULL);
}
}
}
static int obj_cmp(const ASN1_OBJECT *const *ap, const unsigned int *bp)
{
int j;
const ASN1_OBJECT *a = *ap;
const ASN1_OBJECT *b = &nid_objs[*bp];
j = (a->length - b->length);
if (j)
return (j);
if (a->length == 0)
return 0;
return (memcmp(a->data, b->data, a->length));
}
IMPLEMENT_OBJ_BSEARCH_CMP_FN(const ASN1_OBJECT *, unsigned int, obj);
int OBJ_obj2nid(const ASN1_OBJECT *a)
{
const unsigned int *op;
ADDED_OBJ ad, *adp;
if (a == NULL)
return (NID_undef);
if (a->nid != 0)
return (a->nid);
if (a->length == 0)
return NID_undef;
if (added != NULL) {
ad.type = ADDED_DATA;
ad.obj = (ASN1_OBJECT *)a; /* XXX: ugly but harmless */
adp = lh_ADDED_OBJ_retrieve(added, &ad);
if (adp != NULL)
return (adp->obj->nid);
}
op = OBJ_bsearch_obj(&a, obj_objs, NUM_OBJ);
if (op == NULL)
return (NID_undef);
return (nid_objs[*op].nid);
}
/*
* Convert an object name into an ASN1_OBJECT if "noname" is not set then
* search for short and long names first. This will convert the "dotted" form
* into an object: unlike OBJ_txt2nid it can be used with any objects, not
* just registered ones.
*/
ASN1_OBJECT *OBJ_txt2obj(const char *s, int no_name)
{
int nid = NID_undef;
ASN1_OBJECT *op = NULL;
unsigned char *buf;
unsigned char *p;
const unsigned char *cp;
int i, j;
if (!no_name) {
if (((nid = OBJ_sn2nid(s)) != NID_undef) ||
((nid = OBJ_ln2nid(s)) != NID_undef))
return OBJ_nid2obj(nid);
}
/* Work out size of content octets */
i = a2d_ASN1_OBJECT(NULL, 0, s, -1);
if (i <= 0) {
/* Don't clear the error */
/*
* ERR_clear_error();
*/
return NULL;
}
/* Work out total size */
j = ASN1_object_size(0, i, V_ASN1_OBJECT);
if ((buf = (unsigned char *)OPENSSL_malloc(j)) == NULL)
return NULL;
p = buf;
/* Write out tag+length */
ASN1_put_object(&p, 0, i, V_ASN1_OBJECT, V_ASN1_UNIVERSAL);
/* Write out contents */
a2d_ASN1_OBJECT(p, i, s, -1);
cp = buf;
op = d2i_ASN1_OBJECT(NULL, &cp, j);
OPENSSL_free(buf);
return op;
}
int OBJ_obj2txt(char *buf, int buf_len, const ASN1_OBJECT *a, int no_name)
{
int i, n = 0, len, nid, first, use_bn;
BIGNUM *bl;
unsigned long l;
const unsigned char *p;
char tbuf[DECIMAL_SIZE(i) + DECIMAL_SIZE(l) + 2];
/* Ensure that, at every state, |buf| is NUL-terminated. */
if (buf && buf_len > 0)
buf[0] = '\0';
if ((a == NULL) || (a->data == NULL))
return (0);
if (!no_name && (nid = OBJ_obj2nid(a)) != NID_undef) {
const char *s;
s = OBJ_nid2ln(nid);
if (s == NULL)
s = OBJ_nid2sn(nid);
if (s) {
if (buf)
BUF_strlcpy(buf, s, buf_len);
n = strlen(s);
return n;
}
}
len = a->length;
p = a->data;
first = 1;
bl = NULL;
while (len > 0) {
l = 0;
use_bn = 0;
for (;;) {
unsigned char c = *p++;
len--;
if ((len == 0) && (c & 0x80))
goto err;
if (use_bn) {
if (!BN_add_word(bl, c & 0x7f))
goto err;
} else
l |= c & 0x7f;
if (!(c & 0x80))
break;
if (!use_bn && (l > (ULONG_MAX >> 7L))) {
if (!bl && !(bl = BN_new()))
goto err;
if (!BN_set_word(bl, l))
goto err;
use_bn = 1;
}
if (use_bn) {
if (!BN_lshift(bl, bl, 7))
goto err;
} else
l <<= 7L;
}
if (first) {
first = 0;
if (l >= 80) {
i = 2;
if (use_bn) {
if (!BN_sub_word(bl, 80))
goto err;
} else
l -= 80;
} else {
i = (int)(l / 40);
l -= (long)(i * 40);
}
if (buf && (buf_len > 1)) {
*buf++ = i + '0';
*buf = '\0';
buf_len--;
}
n++;
}
if (use_bn) {
char *bndec;
bndec = BN_bn2dec(bl);
if (!bndec)
goto err;
i = strlen(bndec);
if (buf) {
if (buf_len > 1) {
*buf++ = '.';
*buf = '\0';
buf_len--;
}
BUF_strlcpy(buf, bndec, buf_len);
if (i > buf_len) {
buf += buf_len;
buf_len = 0;
} else {
buf += i;
buf_len -= i;
}
}
n++;
n += i;
OPENSSL_free(bndec);
} else {
- BIO_snprintf(tbuf, sizeof tbuf, ".%lu", l);
+ BIO_snprintf(tbuf, sizeof(tbuf), ".%lu", l);
i = strlen(tbuf);
if (buf && (buf_len > 0)) {
BUF_strlcpy(buf, tbuf, buf_len);
if (i > buf_len) {
buf += buf_len;
buf_len = 0;
} else {
buf += i;
buf_len -= i;
}
}
n += i;
l = 0;
}
}
if (bl)
BN_free(bl);
return n;
err:
if (bl)
BN_free(bl);
return -1;
}
int OBJ_txt2nid(const char *s)
{
ASN1_OBJECT *obj;
int nid;
obj = OBJ_txt2obj(s, 0);
nid = OBJ_obj2nid(obj);
ASN1_OBJECT_free(obj);
return nid;
}
int OBJ_ln2nid(const char *s)
{
ASN1_OBJECT o;
const ASN1_OBJECT *oo = &o;
ADDED_OBJ ad, *adp;
const unsigned int *op;
o.ln = s;
if (added != NULL) {
ad.type = ADDED_LNAME;
ad.obj = &o;
adp = lh_ADDED_OBJ_retrieve(added, &ad);
if (adp != NULL)
return (adp->obj->nid);
}
op = OBJ_bsearch_ln(&oo, ln_objs, NUM_LN);
if (op == NULL)
return (NID_undef);
return (nid_objs[*op].nid);
}
int OBJ_sn2nid(const char *s)
{
ASN1_OBJECT o;
const ASN1_OBJECT *oo = &o;
ADDED_OBJ ad, *adp;
const unsigned int *op;
o.sn = s;
if (added != NULL) {
ad.type = ADDED_SNAME;
ad.obj = &o;
adp = lh_ADDED_OBJ_retrieve(added, &ad);
if (adp != NULL)
return (adp->obj->nid);
}
op = OBJ_bsearch_sn(&oo, sn_objs, NUM_SN);
if (op == NULL)
return (NID_undef);
return (nid_objs[*op].nid);
}
const void *OBJ_bsearch_(const void *key, const void *base, int num, int size,
int (*cmp) (const void *, const void *))
{
return OBJ_bsearch_ex_(key, base, num, size, cmp, 0);
}
const void *OBJ_bsearch_ex_(const void *key, const void *base_, int num,
int size,
int (*cmp) (const void *, const void *),
int flags)
{
const char *base = base_;
int l, h, i = 0, c = 0;
const char *p = NULL;
if (num == 0)
return (NULL);
l = 0;
h = num;
while (l < h) {
i = (l + h) / 2;
p = &(base[i * size]);
c = (*cmp) (key, p);
if (c < 0)
h = i;
else if (c > 0)
l = i + 1;
else
break;
}
#ifdef CHARSET_EBCDIC
/*
* THIS IS A KLUDGE - Because the *_obj is sorted in ASCII order, and I
* don't have perl (yet), we revert to a *LINEAR* search when the object
* wasn't found in the binary search.
*/
if (c != 0) {
for (i = 0; i < num; ++i) {
p = &(base[i * size]);
c = (*cmp) (key, p);
if (c == 0 || (c < 0 && (flags & OBJ_BSEARCH_VALUE_ON_NOMATCH)))
return p;
}
}
#endif
if (c != 0 && !(flags & OBJ_BSEARCH_VALUE_ON_NOMATCH))
p = NULL;
else if (c == 0 && (flags & OBJ_BSEARCH_FIRST_VALUE_ON_MATCH)) {
while (i > 0 && (*cmp) (key, &(base[(i - 1) * size])) == 0)
i--;
p = &(base[i * size]);
}
return (p);
}
+/*
+ * Parse a BIO sink to create some extra oid's objects.
+ * Line format:<OID:isdigit or '.']><isspace><SN><isspace><LN>
+ */
int OBJ_create_objects(BIO *in)
{
MS_STATIC char buf[512];
int i, num = 0;
char *o, *s, *l = NULL;
for (;;) {
s = o = NULL;
i = BIO_gets(in, buf, 512);
if (i <= 0)
return (num);
buf[i - 1] = '\0';
if (!isalnum((unsigned char)buf[0]))
return (num);
o = s = buf;
while (isdigit((unsigned char)*s) || (*s == '.'))
s++;
if (*s != '\0') {
*(s++) = '\0';
while (isspace((unsigned char)*s))
s++;
- if (*s == '\0')
+ if (*s == '\0') {
s = NULL;
- else {
+ } else {
l = s;
while ((*l != '\0') && !isspace((unsigned char)*l))
l++;
if (*l != '\0') {
*(l++) = '\0';
while (isspace((unsigned char)*l))
l++;
- if (*l == '\0')
+ if (*l == '\0') {
l = NULL;
- } else
+ }
+ } else {
l = NULL;
+ }
}
- } else
+ } else {
s = NULL;
- if ((o == NULL) || (*o == '\0'))
- return (num);
+ }
+ if (*o == '\0')
+ return num;
if (!OBJ_create(o, s, l))
return (num);
num++;
}
/* return(num); */
}
int OBJ_create(const char *oid, const char *sn, const char *ln)
{
int ok = 0;
ASN1_OBJECT *op = NULL;
unsigned char *buf;
int i;
i = a2d_ASN1_OBJECT(NULL, 0, oid, -1);
if (i <= 0)
return (0);
if ((buf = (unsigned char *)OPENSSL_malloc(i)) == NULL) {
OBJerr(OBJ_F_OBJ_CREATE, ERR_R_MALLOC_FAILURE);
return (0);
}
i = a2d_ASN1_OBJECT(buf, i, oid, -1);
if (i == 0)
goto err;
op = (ASN1_OBJECT *)ASN1_OBJECT_create(OBJ_new_nid(1), buf, i, sn, ln);
if (op == NULL)
goto err;
ok = OBJ_add_object(op);
err:
ASN1_OBJECT_free(op);
OPENSSL_free(buf);
return (ok);
}
diff --git a/crypto/opensslv.h b/crypto/opensslv.h
index baee2d0865fd..77f124e2cb3c 100644
--- a/crypto/opensslv.h
+++ b/crypto/opensslv.h
@@ -1,97 +1,97 @@
#ifndef HEADER_OPENSSLV_H
# define HEADER_OPENSSLV_H
#ifdef __cplusplus
extern "C" {
#endif
/*-
* Numeric release version identifier:
* MNNFFPPS: major minor fix patch status
* The status nibble has one of the values 0 for development, 1 to e for betas
* 1 to 14, and f for release. The patch level is exactly that.
* For example:
* 0.9.3-dev 0x00903000
* 0.9.3-beta1 0x00903001
* 0.9.3-beta2-dev 0x00903002
* 0.9.3-beta2 0x00903002 (same as ...beta2-dev)
* 0.9.3 0x0090300f
* 0.9.3a 0x0090301f
* 0.9.4 0x0090400f
* 1.2.3z 0x102031af
*
* For continuity reasons (because 0.9.5 is already out, and is coded
* 0x00905100), between 0.9.5 and 0.9.6 the coding of the patch level
* part is slightly different, by setting the highest bit. This means
* that 0.9.5a looks like this: 0x0090581f. At 0.9.6, we can start
* with 0x0090600S...
*
* (Prior to 0.9.3-dev a different scheme was used: 0.9.2b is 0x0922.)
* (Prior to 0.9.5a beta1, a different scheme was used: MMNNFFRBB for
* major minor fix final patch/beta)
*/
-# define OPENSSL_VERSION_NUMBER 0x100020efL
+# define OPENSSL_VERSION_NUMBER 0x100020ffL
# ifdef OPENSSL_FIPS
-# define OPENSSL_VERSION_TEXT "OpenSSL 1.0.2n-fips 7 Dec 2017"
+# define OPENSSL_VERSION_TEXT "OpenSSL 1.0.2o-fips 27 Mar 2018"
# else
-# define OPENSSL_VERSION_TEXT "OpenSSL 1.0.2n 7 Dec 2017"
+# define OPENSSL_VERSION_TEXT "OpenSSL 1.0.2o 27 Mar 2018"
# endif
# define OPENSSL_VERSION_PTEXT " part of " OPENSSL_VERSION_TEXT
/*-
* The macros below are to be used for shared library (.so, .dll, ...)
* versioning. That kind of versioning works a bit differently between
* operating systems. The most usual scheme is to set a major and a minor
* number, and have the runtime loader check that the major number is equal
* to what it was at application link time, while the minor number has to
* be greater or equal to what it was at application link time. With this
* scheme, the version number is usually part of the file name, like this:
*
* libcrypto.so.0.9
*
* Some unixen also make a softlink with the major verson number only:
*
* libcrypto.so.0
*
* On Tru64 and IRIX 6.x it works a little bit differently. There, the
* shared library version is stored in the file, and is actually a series
* of versions, separated by colons. The rightmost version present in the
* library when linking an application is stored in the application to be
* matched at run time. When the application is run, a check is done to
* see if the library version stored in the application matches any of the
* versions in the version string of the library itself.
* This version string can be constructed in any way, depending on what
* kind of matching is desired. However, to implement the same scheme as
* the one used in the other unixen, all compatible versions, from lowest
* to highest, should be part of the string. Consecutive builds would
* give the following versions strings:
*
* 3.0
* 3.0:3.1
* 3.0:3.1:3.2
* 4.0
* 4.0:4.1
*
* Notice how version 4 is completely incompatible with version, and
* therefore give the breach you can see.
*
* There may be other schemes as well that I haven't yet discovered.
*
* So, here's the way it works here: first of all, the library version
* number doesn't need at all to match the overall OpenSSL version.
* However, it's nice and more understandable if it actually does.
* The current library version is stored in the macro SHLIB_VERSION_NUMBER,
* which is just a piece of text in the format "M.m.e" (Major, minor, edit).
* For the sake of Tru64, IRIX, and any other OS that behaves in similar ways,
* we need to keep a history of version numbers, which is done in the
* macro SHLIB_VERSION_HISTORY. The numbers are separated by colons and
* should only keep the versions that are binary compatible with the current.
*/
# define SHLIB_VERSION_HISTORY ""
# define SHLIB_VERSION_NUMBER "1.0.0"
#ifdef __cplusplus
}
#endif
#endif /* HEADER_OPENSSLV_H */
diff --git a/crypto/pem/pem_info.c b/crypto/pem/pem_info.c
index 4d736a1d07e5..0994020d2eac 100644
--- a/crypto/pem/pem_info.c
+++ b/crypto/pem/pem_info.c
@@ -1,394 +1,394 @@
/* crypto/pem/pem_info.c */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
#include <stdio.h>
#include "cryptlib.h"
#include <openssl/buffer.h>
#include <openssl/objects.h>
#include <openssl/evp.h>
#include <openssl/x509.h>
#include <openssl/pem.h>
#ifndef OPENSSL_NO_RSA
# include <openssl/rsa.h>
#endif
#ifndef OPENSSL_NO_DSA
# include <openssl/dsa.h>
#endif
#ifndef OPENSSL_NO_FP_API
STACK_OF(X509_INFO) *PEM_X509_INFO_read(FILE *fp, STACK_OF(X509_INFO) *sk,
pem_password_cb *cb, void *u)
{
BIO *b;
STACK_OF(X509_INFO) *ret;
if ((b = BIO_new(BIO_s_file())) == NULL) {
PEMerr(PEM_F_PEM_X509_INFO_READ, ERR_R_BUF_LIB);
return (0);
}
BIO_set_fp(b, fp, BIO_NOCLOSE);
ret = PEM_X509_INFO_read_bio(b, sk, cb, u);
BIO_free(b);
return (ret);
}
#endif
STACK_OF(X509_INFO) *PEM_X509_INFO_read_bio(BIO *bp, STACK_OF(X509_INFO) *sk,
pem_password_cb *cb, void *u)
{
X509_INFO *xi = NULL;
char *name = NULL, *header = NULL;
void *pp;
unsigned char *data = NULL;
const unsigned char *p;
long len, error = 0;
int ok = 0;
STACK_OF(X509_INFO) *ret = NULL;
unsigned int i, raw, ptype;
d2i_of_void *d2i = 0;
if (sk == NULL) {
if ((ret = sk_X509_INFO_new_null()) == NULL) {
PEMerr(PEM_F_PEM_X509_INFO_READ_BIO, ERR_R_MALLOC_FAILURE);
goto err;
}
} else
ret = sk;
if ((xi = X509_INFO_new()) == NULL)
goto err;
for (;;) {
raw = 0;
ptype = 0;
i = PEM_read_bio(bp, &name, &header, &data, &len);
if (i == 0) {
error = ERR_GET_REASON(ERR_peek_last_error());
if (error == PEM_R_NO_START_LINE) {
ERR_clear_error();
break;
}
goto err;
}
start:
if ((strcmp(name, PEM_STRING_X509) == 0) ||
(strcmp(name, PEM_STRING_X509_OLD) == 0)) {
d2i = (D2I_OF(void)) d2i_X509;
if (xi->x509 != NULL) {
if (!sk_X509_INFO_push(ret, xi))
goto err;
if ((xi = X509_INFO_new()) == NULL)
goto err;
goto start;
}
pp = &(xi->x509);
} else if ((strcmp(name, PEM_STRING_X509_TRUSTED) == 0)) {
d2i = (D2I_OF(void)) d2i_X509_AUX;
if (xi->x509 != NULL) {
if (!sk_X509_INFO_push(ret, xi))
goto err;
if ((xi = X509_INFO_new()) == NULL)
goto err;
goto start;
}
pp = &(xi->x509);
} else if (strcmp(name, PEM_STRING_X509_CRL) == 0) {
d2i = (D2I_OF(void)) d2i_X509_CRL;
if (xi->crl != NULL) {
if (!sk_X509_INFO_push(ret, xi))
goto err;
if ((xi = X509_INFO_new()) == NULL)
goto err;
goto start;
}
pp = &(xi->crl);
} else
#ifndef OPENSSL_NO_RSA
if (strcmp(name, PEM_STRING_RSA) == 0) {
d2i = (D2I_OF(void)) d2i_RSAPrivateKey;
if (xi->x_pkey != NULL) {
if (!sk_X509_INFO_push(ret, xi))
goto err;
if ((xi = X509_INFO_new()) == NULL)
goto err;
goto start;
}
xi->enc_data = NULL;
xi->enc_len = 0;
xi->x_pkey = X509_PKEY_new();
if (xi->x_pkey == NULL)
goto err;
ptype = EVP_PKEY_RSA;
pp = &xi->x_pkey->dec_pkey;
if ((int)strlen(header) > 10) /* assume encrypted */
raw = 1;
} else
#endif
#ifndef OPENSSL_NO_DSA
if (strcmp(name, PEM_STRING_DSA) == 0) {
d2i = (D2I_OF(void)) d2i_DSAPrivateKey;
if (xi->x_pkey != NULL) {
if (!sk_X509_INFO_push(ret, xi))
goto err;
if ((xi = X509_INFO_new()) == NULL)
goto err;
goto start;
}
xi->enc_data = NULL;
xi->enc_len = 0;
xi->x_pkey = X509_PKEY_new();
if (xi->x_pkey == NULL)
goto err;
ptype = EVP_PKEY_DSA;
pp = &xi->x_pkey->dec_pkey;
if ((int)strlen(header) > 10) /* assume encrypted */
raw = 1;
} else
#endif
#ifndef OPENSSL_NO_EC
if (strcmp(name, PEM_STRING_ECPRIVATEKEY) == 0) {
d2i = (D2I_OF(void)) d2i_ECPrivateKey;
if (xi->x_pkey != NULL) {
if (!sk_X509_INFO_push(ret, xi))
goto err;
if ((xi = X509_INFO_new()) == NULL)
goto err;
goto start;
}
xi->enc_data = NULL;
xi->enc_len = 0;
xi->x_pkey = X509_PKEY_new();
if (xi->x_pkey == NULL)
goto err;
ptype = EVP_PKEY_EC;
pp = &xi->x_pkey->dec_pkey;
if ((int)strlen(header) > 10) /* assume encrypted */
raw = 1;
} else
#endif
{
d2i = NULL;
pp = NULL;
}
if (d2i != NULL) {
if (!raw) {
EVP_CIPHER_INFO cipher;
if (!PEM_get_EVP_CIPHER_INFO(header, &cipher))
goto err;
if (!PEM_do_header(&cipher, data, &len, cb, u))
goto err;
p = data;
if (ptype) {
if (!d2i_PrivateKey(ptype, pp, &p, len)) {
PEMerr(PEM_F_PEM_X509_INFO_READ_BIO, ERR_R_ASN1_LIB);
goto err;
}
} else if (d2i(pp, &p, len) == NULL) {
PEMerr(PEM_F_PEM_X509_INFO_READ_BIO, ERR_R_ASN1_LIB);
goto err;
}
} else { /* encrypted RSA data */
if (!PEM_get_EVP_CIPHER_INFO(header, &xi->enc_cipher))
goto err;
xi->enc_data = (char *)data;
xi->enc_len = (int)len;
data = NULL;
}
} else {
/* unknown */
}
if (name != NULL)
OPENSSL_free(name);
if (header != NULL)
OPENSSL_free(header);
if (data != NULL)
OPENSSL_free(data);
name = NULL;
header = NULL;
data = NULL;
}
/*
* if the last one hasn't been pushed yet and there is anything in it
* then add it to the stack ...
*/
if ((xi->x509 != NULL) || (xi->crl != NULL) ||
(xi->x_pkey != NULL) || (xi->enc_data != NULL)) {
if (!sk_X509_INFO_push(ret, xi))
goto err;
xi = NULL;
}
ok = 1;
err:
if (xi != NULL)
X509_INFO_free(xi);
if (!ok) {
for (i = 0; ((int)i) < sk_X509_INFO_num(ret); i++) {
xi = sk_X509_INFO_value(ret, i);
X509_INFO_free(xi);
}
if (ret != sk)
sk_X509_INFO_free(ret);
ret = NULL;
}
if (name != NULL)
OPENSSL_free(name);
if (header != NULL)
OPENSSL_free(header);
if (data != NULL)
OPENSSL_free(data);
return (ret);
}
/* A TJH addition */
int PEM_X509_INFO_write_bio(BIO *bp, X509_INFO *xi, EVP_CIPHER *enc,
unsigned char *kstr, int klen,
pem_password_cb *cb, void *u)
{
EVP_CIPHER_CTX ctx;
int i, ret = 0;
unsigned char *data = NULL;
const char *objstr = NULL;
char buf[PEM_BUFSIZE];
unsigned char *iv = NULL;
if (enc != NULL) {
objstr = OBJ_nid2sn(EVP_CIPHER_nid(enc));
if (objstr == NULL) {
PEMerr(PEM_F_PEM_X509_INFO_WRITE_BIO, PEM_R_UNSUPPORTED_CIPHER);
goto err;
}
}
/*
* now for the fun part ... if we have a private key then we have to be
* able to handle a not-yet-decrypted key being written out correctly ...
* if it is decrypted or it is non-encrypted then we use the base code
*/
if (xi->x_pkey != NULL) {
if ((xi->enc_data != NULL) && (xi->enc_len > 0)) {
if (enc == NULL) {
PEMerr(PEM_F_PEM_X509_INFO_WRITE_BIO, PEM_R_CIPHER_IS_NULL);
goto err;
}
/* copy from weirdo names into more normal things */
iv = xi->enc_cipher.iv;
data = (unsigned char *)xi->enc_data;
i = xi->enc_len;
/*
* we take the encryption data from the internal stuff rather
* than what the user has passed us ... as we have to match
* exactly for some strange reason
*/
objstr = OBJ_nid2sn(EVP_CIPHER_nid(xi->enc_cipher.cipher));
if (objstr == NULL) {
PEMerr(PEM_F_PEM_X509_INFO_WRITE_BIO,
PEM_R_UNSUPPORTED_CIPHER);
goto err;
}
/* create the right magic header stuff */
OPENSSL_assert(strlen(objstr) + 23 + 2 * enc->iv_len + 13 <=
- sizeof buf);
+ sizeof(buf));
buf[0] = '\0';
PEM_proc_type(buf, PEM_TYPE_ENCRYPTED);
PEM_dek_info(buf, objstr, enc->iv_len, (char *)iv);
/* use the normal code to write things out */
i = PEM_write_bio(bp, PEM_STRING_RSA, buf, data, i);
if (i <= 0)
goto err;
} else {
/* Add DSA/DH */
#ifndef OPENSSL_NO_RSA
/* normal optionally encrypted stuff */
if (PEM_write_bio_RSAPrivateKey(bp,
xi->x_pkey->dec_pkey->pkey.rsa,
enc, kstr, klen, cb, u) <= 0)
goto err;
#endif
}
}
/* if we have a certificate then write it out now */
if ((xi->x509 != NULL) && (PEM_write_bio_X509(bp, xi->x509) <= 0))
goto err;
/*
* we are ignoring anything else that is loaded into the X509_INFO
* structure for the moment ... as I don't need it so I'm not coding it
* here and Eric can do it when this makes it into the base library --tjh
*/
ret = 1;
err:
OPENSSL_cleanse((char *)&ctx, sizeof(ctx));
OPENSSL_cleanse(buf, PEM_BUFSIZE);
return (ret);
}
diff --git a/crypto/pem/pem_lib.c b/crypto/pem/pem_lib.c
index 865976bf8cce..4d5f053e4680 100644
--- a/crypto/pem/pem_lib.c
+++ b/crypto/pem/pem_lib.c
@@ -1,872 +1,872 @@
/* crypto/pem/pem_lib.c */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
#include <stdio.h>
#include <ctype.h>
#include "cryptlib.h"
#include <openssl/buffer.h>
#include <openssl/objects.h>
#include <openssl/evp.h>
#include <openssl/rand.h>
#include <openssl/x509.h>
#include <openssl/pem.h>
#include <openssl/pkcs12.h>
#include "asn1_locl.h"
#ifndef OPENSSL_NO_DES
# include <openssl/des.h>
#endif
#ifndef OPENSSL_NO_ENGINE
# include <openssl/engine.h>
#endif
const char PEM_version[] = "PEM" OPENSSL_VERSION_PTEXT;
#define MIN_LENGTH 4
static int load_iv(char **fromp, unsigned char *to, int num);
static int check_pem(const char *nm, const char *name);
int pem_check_suffix(const char *pem_str, const char *suffix);
int PEM_def_callback(char *buf, int num, int w, void *key)
{
#ifdef OPENSSL_NO_FP_API
/*
* We should not ever call the default callback routine from windows.
*/
PEMerr(PEM_F_PEM_DEF_CALLBACK, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
return (-1);
#else
int i, j;
const char *prompt;
if (key) {
i = strlen(key);
i = (i > num) ? num : i;
memcpy(buf, key, i);
return (i);
}
prompt = EVP_get_pw_prompt();
if (prompt == NULL)
prompt = "Enter PEM pass phrase:";
for (;;) {
/*
* We assume that w == 0 means decryption,
* while w == 1 means encryption
*/
int min_len = w ? MIN_LENGTH : 0;
i = EVP_read_pw_string_min(buf, min_len, num, prompt, w);
if (i != 0) {
PEMerr(PEM_F_PEM_DEF_CALLBACK, PEM_R_PROBLEMS_GETTING_PASSWORD);
memset(buf, 0, (unsigned int)num);
return (-1);
}
j = strlen(buf);
if (min_len && j < min_len) {
fprintf(stderr,
"phrase is too short, needs to be at least %d chars\n",
min_len);
} else
break;
}
return (j);
#endif
}
void PEM_proc_type(char *buf, int type)
{
const char *str;
if (type == PEM_TYPE_ENCRYPTED)
str = "ENCRYPTED";
else if (type == PEM_TYPE_MIC_CLEAR)
str = "MIC-CLEAR";
else if (type == PEM_TYPE_MIC_ONLY)
str = "MIC-ONLY";
else
str = "BAD-TYPE";
BUF_strlcat(buf, "Proc-Type: 4,", PEM_BUFSIZE);
BUF_strlcat(buf, str, PEM_BUFSIZE);
BUF_strlcat(buf, "\n", PEM_BUFSIZE);
}
void PEM_dek_info(char *buf, const char *type, int len, char *str)
{
static const unsigned char map[17] = "0123456789ABCDEF";
long i;
int j;
BUF_strlcat(buf, "DEK-Info: ", PEM_BUFSIZE);
BUF_strlcat(buf, type, PEM_BUFSIZE);
BUF_strlcat(buf, ",", PEM_BUFSIZE);
j = strlen(buf);
if (j + (len * 2) + 1 > PEM_BUFSIZE)
return;
for (i = 0; i < len; i++) {
buf[j + i * 2] = map[(str[i] >> 4) & 0x0f];
buf[j + i * 2 + 1] = map[(str[i]) & 0x0f];
}
buf[j + i * 2] = '\n';
buf[j + i * 2 + 1] = '\0';
}
#ifndef OPENSSL_NO_FP_API
void *PEM_ASN1_read(d2i_of_void *d2i, const char *name, FILE *fp, void **x,
pem_password_cb *cb, void *u)
{
BIO *b;
void *ret;
if ((b = BIO_new(BIO_s_file())) == NULL) {
PEMerr(PEM_F_PEM_ASN1_READ, ERR_R_BUF_LIB);
return (0);
}
BIO_set_fp(b, fp, BIO_NOCLOSE);
ret = PEM_ASN1_read_bio(d2i, name, b, x, cb, u);
BIO_free(b);
return (ret);
}
#endif
static int check_pem(const char *nm, const char *name)
{
/* Normal matching nm and name */
if (!strcmp(nm, name))
return 1;
/* Make PEM_STRING_EVP_PKEY match any private key */
if (!strcmp(name, PEM_STRING_EVP_PKEY)) {
int slen;
const EVP_PKEY_ASN1_METHOD *ameth;
if (!strcmp(nm, PEM_STRING_PKCS8))
return 1;
if (!strcmp(nm, PEM_STRING_PKCS8INF))
return 1;
slen = pem_check_suffix(nm, "PRIVATE KEY");
if (slen > 0) {
/*
* NB: ENGINE implementations wont contain a deprecated old
* private key decode function so don't look for them.
*/
ameth = EVP_PKEY_asn1_find_str(NULL, nm, slen);
if (ameth && ameth->old_priv_decode)
return 1;
}
return 0;
}
if (!strcmp(name, PEM_STRING_PARAMETERS)) {
int slen;
const EVP_PKEY_ASN1_METHOD *ameth;
slen = pem_check_suffix(nm, "PARAMETERS");
if (slen > 0) {
ENGINE *e;
ameth = EVP_PKEY_asn1_find_str(&e, nm, slen);
if (ameth) {
int r;
if (ameth->param_decode)
r = 1;
else
r = 0;
#ifndef OPENSSL_NO_ENGINE
if (e)
ENGINE_finish(e);
#endif
return r;
}
}
return 0;
}
/* If reading DH parameters handle X9.42 DH format too */
if (!strcmp(nm, PEM_STRING_DHXPARAMS) &&
!strcmp(name, PEM_STRING_DHPARAMS))
return 1;
/* Permit older strings */
if (!strcmp(nm, PEM_STRING_X509_OLD) && !strcmp(name, PEM_STRING_X509))
return 1;
if (!strcmp(nm, PEM_STRING_X509_REQ_OLD) &&
!strcmp(name, PEM_STRING_X509_REQ))
return 1;
/* Allow normal certs to be read as trusted certs */
if (!strcmp(nm, PEM_STRING_X509) &&
!strcmp(name, PEM_STRING_X509_TRUSTED))
return 1;
if (!strcmp(nm, PEM_STRING_X509_OLD) &&
!strcmp(name, PEM_STRING_X509_TRUSTED))
return 1;
/* Some CAs use PKCS#7 with CERTIFICATE headers */
if (!strcmp(nm, PEM_STRING_X509) && !strcmp(name, PEM_STRING_PKCS7))
return 1;
if (!strcmp(nm, PEM_STRING_PKCS7_SIGNED) &&
!strcmp(name, PEM_STRING_PKCS7))
return 1;
#ifndef OPENSSL_NO_CMS
if (!strcmp(nm, PEM_STRING_X509) && !strcmp(name, PEM_STRING_CMS))
return 1;
/* Allow CMS to be read from PKCS#7 headers */
if (!strcmp(nm, PEM_STRING_PKCS7) && !strcmp(name, PEM_STRING_CMS))
return 1;
#endif
return 0;
}
int PEM_bytes_read_bio(unsigned char **pdata, long *plen, char **pnm,
const char *name, BIO *bp, pem_password_cb *cb,
void *u)
{
EVP_CIPHER_INFO cipher;
char *nm = NULL, *header = NULL;
unsigned char *data = NULL;
long len;
int ret = 0;
for (;;) {
if (!PEM_read_bio(bp, &nm, &header, &data, &len)) {
if (ERR_GET_REASON(ERR_peek_error()) == PEM_R_NO_START_LINE)
ERR_add_error_data(2, "Expecting: ", name);
return 0;
}
if (check_pem(nm, name))
break;
OPENSSL_free(nm);
OPENSSL_free(header);
OPENSSL_free(data);
}
if (!PEM_get_EVP_CIPHER_INFO(header, &cipher))
goto err;
if (!PEM_do_header(&cipher, data, &len, cb, u))
goto err;
*pdata = data;
*plen = len;
if (pnm)
*pnm = nm;
ret = 1;
err:
if (!ret || !pnm)
OPENSSL_free(nm);
OPENSSL_free(header);
if (!ret)
OPENSSL_free(data);
return ret;
}
#ifndef OPENSSL_NO_FP_API
int PEM_ASN1_write(i2d_of_void *i2d, const char *name, FILE *fp,
void *x, const EVP_CIPHER *enc, unsigned char *kstr,
int klen, pem_password_cb *callback, void *u)
{
BIO *b;
int ret;
if ((b = BIO_new(BIO_s_file())) == NULL) {
PEMerr(PEM_F_PEM_ASN1_WRITE, ERR_R_BUF_LIB);
return (0);
}
BIO_set_fp(b, fp, BIO_NOCLOSE);
ret = PEM_ASN1_write_bio(i2d, name, b, x, enc, kstr, klen, callback, u);
BIO_free(b);
return (ret);
}
#endif
int PEM_ASN1_write_bio(i2d_of_void *i2d, const char *name, BIO *bp,
void *x, const EVP_CIPHER *enc, unsigned char *kstr,
int klen, pem_password_cb *callback, void *u)
{
EVP_CIPHER_CTX ctx;
int dsize = 0, i, j, ret = 0;
unsigned char *p, *data = NULL;
const char *objstr = NULL;
char buf[PEM_BUFSIZE];
unsigned char key[EVP_MAX_KEY_LENGTH];
unsigned char iv[EVP_MAX_IV_LENGTH];
if (enc != NULL) {
objstr = OBJ_nid2sn(EVP_CIPHER_nid(enc));
if (objstr == NULL || EVP_CIPHER_iv_length(enc) == 0) {
PEMerr(PEM_F_PEM_ASN1_WRITE_BIO, PEM_R_UNSUPPORTED_CIPHER);
goto err;
}
}
if ((dsize = i2d(x, NULL)) < 0) {
PEMerr(PEM_F_PEM_ASN1_WRITE_BIO, ERR_R_ASN1_LIB);
dsize = 0;
goto err;
}
/* dzise + 8 bytes are needed */
/* actually it needs the cipher block size extra... */
data = (unsigned char *)OPENSSL_malloc((unsigned int)dsize + 20);
if (data == NULL) {
PEMerr(PEM_F_PEM_ASN1_WRITE_BIO, ERR_R_MALLOC_FAILURE);
goto err;
}
p = data;
i = i2d(x, &p);
if (enc != NULL) {
if (kstr == NULL) {
if (callback == NULL)
klen = PEM_def_callback(buf, PEM_BUFSIZE, 1, u);
else
klen = (*callback) (buf, PEM_BUFSIZE, 1, u);
if (klen <= 0) {
PEMerr(PEM_F_PEM_ASN1_WRITE_BIO, PEM_R_READ_KEY);
goto err;
}
#ifdef CHARSET_EBCDIC
/* Convert the pass phrase from EBCDIC */
ebcdic2ascii(buf, buf, klen);
#endif
kstr = (unsigned char *)buf;
}
RAND_add(data, i, 0); /* put in the RSA key. */
OPENSSL_assert(enc->iv_len <= (int)sizeof(iv));
if (RAND_bytes(iv, enc->iv_len) <= 0) /* Generate a salt */
goto err;
/*
* The 'iv' is used as the iv and as a salt. It is NOT taken from
* the BytesToKey function
*/
if (!EVP_BytesToKey(enc, EVP_md5(), iv, kstr, klen, 1, key, NULL))
goto err;
if (kstr == (unsigned char *)buf)
OPENSSL_cleanse(buf, PEM_BUFSIZE);
OPENSSL_assert(strlen(objstr) + 23 + 2 * enc->iv_len + 13 <=
- sizeof buf);
+ sizeof(buf));
buf[0] = '\0';
PEM_proc_type(buf, PEM_TYPE_ENCRYPTED);
PEM_dek_info(buf, objstr, enc->iv_len, (char *)iv);
/* k=strlen(buf); */
EVP_CIPHER_CTX_init(&ctx);
ret = 1;
if (!EVP_EncryptInit_ex(&ctx, enc, NULL, key, iv)
|| !EVP_EncryptUpdate(&ctx, data, &j, data, i)
|| !EVP_EncryptFinal_ex(&ctx, &(data[j]), &i))
ret = 0;
EVP_CIPHER_CTX_cleanup(&ctx);
if (ret == 0)
goto err;
i += j;
} else {
ret = 1;
buf[0] = '\0';
}
i = PEM_write_bio(bp, name, buf, data, i);
if (i <= 0)
ret = 0;
err:
OPENSSL_cleanse(key, sizeof(key));
OPENSSL_cleanse(iv, sizeof(iv));
OPENSSL_cleanse((char *)&ctx, sizeof(ctx));
OPENSSL_cleanse(buf, PEM_BUFSIZE);
if (data != NULL) {
OPENSSL_cleanse(data, (unsigned int)dsize);
OPENSSL_free(data);
}
return (ret);
}
int PEM_do_header(EVP_CIPHER_INFO *cipher, unsigned char *data, long *plen,
pem_password_cb *callback, void *u)
{
int i = 0, j, o, klen;
long len;
EVP_CIPHER_CTX ctx;
unsigned char key[EVP_MAX_KEY_LENGTH];
char buf[PEM_BUFSIZE];
len = *plen;
if (cipher->cipher == NULL)
return (1);
if (callback == NULL)
klen = PEM_def_callback(buf, PEM_BUFSIZE, 0, u);
else
klen = callback(buf, PEM_BUFSIZE, 0, u);
if (klen <= 0) {
PEMerr(PEM_F_PEM_DO_HEADER, PEM_R_BAD_PASSWORD_READ);
return (0);
}
#ifdef CHARSET_EBCDIC
/* Convert the pass phrase from EBCDIC */
ebcdic2ascii(buf, buf, klen);
#endif
if (!EVP_BytesToKey(cipher->cipher, EVP_md5(), &(cipher->iv[0]),
(unsigned char *)buf, klen, 1, key, NULL))
return 0;
j = (int)len;
EVP_CIPHER_CTX_init(&ctx);
o = EVP_DecryptInit_ex(&ctx, cipher->cipher, NULL, key, &(cipher->iv[0]));
if (o)
o = EVP_DecryptUpdate(&ctx, data, &i, data, j);
if (o)
o = EVP_DecryptFinal_ex(&ctx, &(data[i]), &j);
EVP_CIPHER_CTX_cleanup(&ctx);
OPENSSL_cleanse((char *)buf, sizeof(buf));
OPENSSL_cleanse((char *)key, sizeof(key));
if (o)
j += i;
else {
PEMerr(PEM_F_PEM_DO_HEADER, PEM_R_BAD_DECRYPT);
return (0);
}
*plen = j;
return (1);
}
int PEM_get_EVP_CIPHER_INFO(char *header, EVP_CIPHER_INFO *cipher)
{
const EVP_CIPHER *enc = NULL;
char *p, c;
char **header_pp = &header;
cipher->cipher = NULL;
if ((header == NULL) || (*header == '\0') || (*header == '\n'))
return (1);
if (strncmp(header, "Proc-Type: ", 11) != 0) {
PEMerr(PEM_F_PEM_GET_EVP_CIPHER_INFO, PEM_R_NOT_PROC_TYPE);
return (0);
}
header += 11;
if (*header != '4')
return (0);
header++;
if (*header != ',')
return (0);
header++;
if (strncmp(header, "ENCRYPTED", 9) != 0) {
PEMerr(PEM_F_PEM_GET_EVP_CIPHER_INFO, PEM_R_NOT_ENCRYPTED);
return (0);
}
for (; (*header != '\n') && (*header != '\0'); header++) ;
if (*header == '\0') {
PEMerr(PEM_F_PEM_GET_EVP_CIPHER_INFO, PEM_R_SHORT_HEADER);
return (0);
}
header++;
if (strncmp(header, "DEK-Info: ", 10) != 0) {
PEMerr(PEM_F_PEM_GET_EVP_CIPHER_INFO, PEM_R_NOT_DEK_INFO);
return (0);
}
header += 10;
p = header;
for (;;) {
c = *header;
#ifndef CHARSET_EBCDIC
if (!(((c >= 'A') && (c <= 'Z')) || (c == '-') ||
((c >= '0') && (c <= '9'))))
break;
#else
if (!(isupper((unsigned char)c) || (c == '-')
|| isdigit((unsigned char)c)))
break;
#endif
header++;
}
*header = '\0';
cipher->cipher = enc = EVP_get_cipherbyname(p);
*header = c;
header++;
if (enc == NULL) {
PEMerr(PEM_F_PEM_GET_EVP_CIPHER_INFO, PEM_R_UNSUPPORTED_ENCRYPTION);
return (0);
}
if (!load_iv(header_pp, &(cipher->iv[0]), enc->iv_len))
return (0);
return (1);
}
static int load_iv(char **fromp, unsigned char *to, int num)
{
int v, i;
char *from;
from = *fromp;
for (i = 0; i < num; i++)
to[i] = 0;
num *= 2;
for (i = 0; i < num; i++) {
if ((*from >= '0') && (*from <= '9'))
v = *from - '0';
else if ((*from >= 'A') && (*from <= 'F'))
v = *from - 'A' + 10;
else if ((*from >= 'a') && (*from <= 'f'))
v = *from - 'a' + 10;
else {
PEMerr(PEM_F_LOAD_IV, PEM_R_BAD_IV_CHARS);
return (0);
}
from++;
to[i / 2] |= v << (long)((!(i & 1)) * 4);
}
*fromp = from;
return (1);
}
#ifndef OPENSSL_NO_FP_API
int PEM_write(FILE *fp, const char *name, const char *header,
const unsigned char *data, long len)
{
BIO *b;
int ret;
if ((b = BIO_new(BIO_s_file())) == NULL) {
PEMerr(PEM_F_PEM_WRITE, ERR_R_BUF_LIB);
return (0);
}
BIO_set_fp(b, fp, BIO_NOCLOSE);
ret = PEM_write_bio(b, name, header, data, len);
BIO_free(b);
return (ret);
}
#endif
int PEM_write_bio(BIO *bp, const char *name, const char *header,
const unsigned char *data, long len)
{
int nlen, n, i, j, outl;
unsigned char *buf = NULL;
EVP_ENCODE_CTX ctx;
int reason = ERR_R_BUF_LIB;
EVP_EncodeInit(&ctx);
nlen = strlen(name);
if ((BIO_write(bp, "-----BEGIN ", 11) != 11) ||
(BIO_write(bp, name, nlen) != nlen) ||
(BIO_write(bp, "-----\n", 6) != 6))
goto err;
i = strlen(header);
if (i > 0) {
if ((BIO_write(bp, header, i) != i) || (BIO_write(bp, "\n", 1) != 1))
goto err;
}
buf = OPENSSL_malloc(PEM_BUFSIZE * 8);
if (buf == NULL) {
reason = ERR_R_MALLOC_FAILURE;
goto err;
}
i = j = 0;
while (len > 0) {
n = (int)((len > (PEM_BUFSIZE * 5)) ? (PEM_BUFSIZE * 5) : len);
EVP_EncodeUpdate(&ctx, buf, &outl, &(data[j]), n);
if ((outl) && (BIO_write(bp, (char *)buf, outl) != outl))
goto err;
i += outl;
len -= n;
j += n;
}
EVP_EncodeFinal(&ctx, buf, &outl);
if ((outl > 0) && (BIO_write(bp, (char *)buf, outl) != outl))
goto err;
OPENSSL_cleanse(buf, PEM_BUFSIZE * 8);
OPENSSL_free(buf);
buf = NULL;
if ((BIO_write(bp, "-----END ", 9) != 9) ||
(BIO_write(bp, name, nlen) != nlen) ||
(BIO_write(bp, "-----\n", 6) != 6))
goto err;
return (i + outl);
err:
if (buf) {
OPENSSL_cleanse(buf, PEM_BUFSIZE * 8);
OPENSSL_free(buf);
}
PEMerr(PEM_F_PEM_WRITE_BIO, reason);
return (0);
}
#ifndef OPENSSL_NO_FP_API
int PEM_read(FILE *fp, char **name, char **header, unsigned char **data,
long *len)
{
BIO *b;
int ret;
if ((b = BIO_new(BIO_s_file())) == NULL) {
PEMerr(PEM_F_PEM_READ, ERR_R_BUF_LIB);
return (0);
}
BIO_set_fp(b, fp, BIO_NOCLOSE);
ret = PEM_read_bio(b, name, header, data, len);
BIO_free(b);
return (ret);
}
#endif
int PEM_read_bio(BIO *bp, char **name, char **header, unsigned char **data,
long *len)
{
EVP_ENCODE_CTX ctx;
int end = 0, i, k, bl = 0, hl = 0, nohead = 0;
char buf[256];
BUF_MEM *nameB;
BUF_MEM *headerB;
BUF_MEM *dataB, *tmpB;
nameB = BUF_MEM_new();
headerB = BUF_MEM_new();
dataB = BUF_MEM_new();
if ((nameB == NULL) || (headerB == NULL) || (dataB == NULL)) {
BUF_MEM_free(nameB);
BUF_MEM_free(headerB);
BUF_MEM_free(dataB);
PEMerr(PEM_F_PEM_READ_BIO, ERR_R_MALLOC_FAILURE);
return (0);
}
buf[254] = '\0';
for (;;) {
i = BIO_gets(bp, buf, 254);
if (i <= 0) {
PEMerr(PEM_F_PEM_READ_BIO, PEM_R_NO_START_LINE);
goto err;
}
while ((i >= 0) && (buf[i] <= ' '))
i--;
buf[++i] = '\n';
buf[++i] = '\0';
if (strncmp(buf, "-----BEGIN ", 11) == 0) {
i = strlen(&(buf[11]));
if (strncmp(&(buf[11 + i - 6]), "-----\n", 6) != 0)
continue;
if (!BUF_MEM_grow(nameB, i + 9)) {
PEMerr(PEM_F_PEM_READ_BIO, ERR_R_MALLOC_FAILURE);
goto err;
}
memcpy(nameB->data, &(buf[11]), i - 6);
nameB->data[i - 6] = '\0';
break;
}
}
hl = 0;
if (!BUF_MEM_grow(headerB, 256)) {
PEMerr(PEM_F_PEM_READ_BIO, ERR_R_MALLOC_FAILURE);
goto err;
}
headerB->data[0] = '\0';
for (;;) {
i = BIO_gets(bp, buf, 254);
if (i <= 0)
break;
while ((i >= 0) && (buf[i] <= ' '))
i--;
buf[++i] = '\n';
buf[++i] = '\0';
if (buf[0] == '\n')
break;
if (!BUF_MEM_grow(headerB, hl + i + 9)) {
PEMerr(PEM_F_PEM_READ_BIO, ERR_R_MALLOC_FAILURE);
goto err;
}
if (strncmp(buf, "-----END ", 9) == 0) {
nohead = 1;
break;
}
memcpy(&(headerB->data[hl]), buf, i);
headerB->data[hl + i] = '\0';
hl += i;
}
bl = 0;
if (!BUF_MEM_grow(dataB, 1024)) {
PEMerr(PEM_F_PEM_READ_BIO, ERR_R_MALLOC_FAILURE);
goto err;
}
dataB->data[0] = '\0';
if (!nohead) {
for (;;) {
i = BIO_gets(bp, buf, 254);
if (i <= 0)
break;
while ((i >= 0) && (buf[i] <= ' '))
i--;
buf[++i] = '\n';
buf[++i] = '\0';
if (i != 65)
end = 1;
if (strncmp(buf, "-----END ", 9) == 0)
break;
if (i > 65)
break;
if (!BUF_MEM_grow_clean(dataB, i + bl + 9)) {
PEMerr(PEM_F_PEM_READ_BIO, ERR_R_MALLOC_FAILURE);
goto err;
}
memcpy(&(dataB->data[bl]), buf, i);
dataB->data[bl + i] = '\0';
bl += i;
if (end) {
buf[0] = '\0';
i = BIO_gets(bp, buf, 254);
if (i <= 0)
break;
while ((i >= 0) && (buf[i] <= ' '))
i--;
buf[++i] = '\n';
buf[++i] = '\0';
break;
}
}
} else {
tmpB = headerB;
headerB = dataB;
dataB = tmpB;
bl = hl;
}
i = strlen(nameB->data);
if ((strncmp(buf, "-----END ", 9) != 0) ||
(strncmp(nameB->data, &(buf[9]), i) != 0) ||
(strncmp(&(buf[9 + i]), "-----\n", 6) != 0)) {
PEMerr(PEM_F_PEM_READ_BIO, PEM_R_BAD_END_LINE);
goto err;
}
EVP_DecodeInit(&ctx);
i = EVP_DecodeUpdate(&ctx,
(unsigned char *)dataB->data, &bl,
(unsigned char *)dataB->data, bl);
if (i < 0) {
PEMerr(PEM_F_PEM_READ_BIO, PEM_R_BAD_BASE64_DECODE);
goto err;
}
i = EVP_DecodeFinal(&ctx, (unsigned char *)&(dataB->data[bl]), &k);
if (i < 0) {
PEMerr(PEM_F_PEM_READ_BIO, PEM_R_BAD_BASE64_DECODE);
goto err;
}
bl += k;
if (bl == 0)
goto err;
*name = nameB->data;
*header = headerB->data;
*data = (unsigned char *)dataB->data;
*len = bl;
OPENSSL_free(nameB);
OPENSSL_free(headerB);
OPENSSL_free(dataB);
return (1);
err:
BUF_MEM_free(nameB);
BUF_MEM_free(headerB);
BUF_MEM_free(dataB);
return (0);
}
/*
* Check pem string and return prefix length. If for example the pem_str ==
* "RSA PRIVATE KEY" and suffix = "PRIVATE KEY" the return value is 3 for the
* string "RSA".
*/
int pem_check_suffix(const char *pem_str, const char *suffix)
{
int pem_len = strlen(pem_str);
int suffix_len = strlen(suffix);
const char *p;
if (suffix_len + 1 >= pem_len)
return 0;
p = pem_str + pem_len - suffix_len;
if (strcmp(p, suffix))
return 0;
p--;
if (*p != ' ')
return 0;
return p - pem_str;
}
diff --git a/crypto/pkcs7/pk7_doit.c b/crypto/pkcs7/pk7_doit.c
index 6cf8253bc238..6a463680d7ec 100644
--- a/crypto/pkcs7/pk7_doit.c
+++ b/crypto/pkcs7/pk7_doit.c
@@ -1,1297 +1,1299 @@
/* crypto/pkcs7/pk7_doit.c */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
#include <stdio.h>
#include "cryptlib.h"
#include <openssl/rand.h>
#include <openssl/objects.h>
#include <openssl/x509.h>
#include <openssl/x509v3.h>
#include <openssl/err.h>
static int add_attribute(STACK_OF(X509_ATTRIBUTE) **sk, int nid, int atrtype,
void *value);
static ASN1_TYPE *get_attribute(STACK_OF(X509_ATTRIBUTE) *sk, int nid);
static 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;
}
static 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)
{
BIO *btmp;
const EVP_MD *md;
if ((btmp = BIO_new(BIO_f_md())) == NULL) {
PKCS7err(PKCS7_F_PKCS7_BIO_ADD_DIGEST, ERR_R_BIO_LIB);
goto err;
}
md = EVP_get_digestbyobj(alg->algorithm);
if (md == NULL) {
PKCS7err(PKCS7_F_PKCS7_BIO_ADD_DIGEST, PKCS7_R_UNKNOWN_DIGEST_TYPE);
goto err;
}
BIO_set_md(btmp, md);
if (*pbio == NULL)
*pbio = btmp;
else if (!BIO_push(*pbio, btmp)) {
PKCS7err(PKCS7_F_PKCS7_BIO_ADD_DIGEST, ERR_R_BIO_LIB);
goto err;
}
btmp = NULL;
return 1;
err:
if (btmp)
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;
pkey = X509_get_pubkey(ri->cert);
if (!pkey)
return 0;
pctx = EVP_PKEY_CTX_new(pkey, NULL);
if (!pctx)
return 0;
if (EVP_PKEY_encrypt_init(pctx) <= 0)
goto err;
if (EVP_PKEY_CTX_ctrl(pctx, -1, EVP_PKEY_OP_ENCRYPT,
EVP_PKEY_CTRL_PKCS7_ENCRYPT, 0, ri) <= 0) {
PKCS7err(PKCS7_F_PKCS7_ENCODE_RINFO, PKCS7_R_CTRL_ERROR);
goto err;
}
if (EVP_PKEY_encrypt(pctx, NULL, &eklen, key, keylen) <= 0)
goto err;
ek = OPENSSL_malloc(eklen);
if (ek == NULL) {
PKCS7err(PKCS7_F_PKCS7_ENCODE_RINFO, 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:
if (pkey)
EVP_PKEY_free(pkey);
if (pctx)
EVP_PKEY_CTX_free(pctx);
if (ek)
OPENSSL_free(ek);
return ret;
}
static int pkcs7_decrypt_rinfo(unsigned char **pek, int *peklen,
PKCS7_RECIP_INFO *ri, EVP_PKEY *pkey)
{
EVP_PKEY_CTX *pctx = NULL;
unsigned char *ek = NULL;
size_t eklen;
int ret = -1;
pctx = EVP_PKEY_CTX_new(pkey, NULL);
if (!pctx)
return -1;
if (EVP_PKEY_decrypt_init(pctx) <= 0)
goto err;
if (EVP_PKEY_CTX_ctrl(pctx, -1, EVP_PKEY_OP_DECRYPT,
EVP_PKEY_CTRL_PKCS7_DECRYPT, 0, ri) <= 0) {
PKCS7err(PKCS7_F_PKCS7_DECRYPT_RINFO, PKCS7_R_CTRL_ERROR);
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) {
PKCS7err(PKCS7_F_PKCS7_DECRYPT_RINFO, ERR_R_MALLOC_FAILURE);
goto err;
}
if (EVP_PKEY_decrypt(pctx, ek, &eklen,
ri->enc_key->data, ri->enc_key->length) <= 0) {
ret = 0;
PKCS7err(PKCS7_F_PKCS7_DECRYPT_RINFO, ERR_R_EVP_LIB);
goto err;
}
ret = 1;
if (*pek) {
OPENSSL_cleanse(*pek, *peklen);
OPENSSL_free(*pek);
}
*pek = ek;
*peklen = eklen;
err:
if (pctx)
EVP_PKEY_CTX_free(pctx);
if (!ret && ek)
OPENSSL_free(ek);
return ret;
}
BIO *PKCS7_dataInit(PKCS7 *p7, BIO *bio)
{
int i;
BIO *out = NULL, *btmp = NULL;
X509_ALGOR *xa = NULL;
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;
if (p7 == NULL) {
PKCS7err(PKCS7_F_PKCS7_DATAINIT, PKCS7_R_INVALID_NULL_POINTER);
return NULL;
}
/*
* 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) {
PKCS7err(PKCS7_F_PKCS7_DATAINIT, 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) {
PKCS7err(PKCS7_F_PKCS7_DATAINIT, 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) {
PKCS7err(PKCS7_F_PKCS7_DATAINIT, 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:
PKCS7err(PKCS7_F_PKCS7_DATAINIT, 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)))
goto err;
if (xa && !PKCS7_bio_add_digest(&out, xa))
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) {
PKCS7err(PKCS7_F_PKCS7_DATAINIT, ERR_R_BIO_LIB);
goto err;
}
BIO_get_cipher_ctx(btmp, &ctx);
keylen = EVP_CIPHER_key_length(evp_cipher);
ivlen = EVP_CIPHER_iv_length(evp_cipher);
xalg->algorithm = OBJ_nid2obj(EVP_CIPHER_type(evp_cipher));
if (ivlen > 0)
if (RAND_bytes(iv, ivlen) <= 0)
goto err;
if (EVP_CipherInit_ex(ctx, evp_cipher, NULL, NULL, NULL, 1) <= 0)
goto err;
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))
+ if (PKCS7_is_detached(p7)) {
bio = BIO_new(BIO_s_null());
- else if (os && os->length > 0)
+ } else if (os && os->length > 0) {
bio = BIO_new_mem_buf(os->data, os->length);
- if (bio == NULL) {
+ } 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;
bio = NULL;
if (0) {
err:
if (out != NULL)
BIO_free_all(out);
if (btmp != NULL)
BIO_free_all(btmp);
out = NULL;
}
return (out);
}
static int pkcs7_cmp_ri(PKCS7_RECIP_INFO *ri, X509 *pcert)
{
int ret;
ret = X509_NAME_cmp(ri->issuer_and_serial->issuer,
pcert->cert_info->issuer);
if (ret)
return ret;
return M_ASN1_INTEGER_cmp(pcert->cert_info->serialNumber,
ri->issuer_and_serial->serial);
}
/* int */
BIO *PKCS7_dataDecode(PKCS7 *p7, EVP_PKEY *pkey, BIO *in_bio, X509 *pcert)
{
int i, j;
BIO *out = NULL, *btmp = NULL, *etmp = NULL, *bio = NULL;
X509_ALGOR *xa;
ASN1_OCTET_STRING *data_body = NULL;
const EVP_MD *evp_md;
const EVP_CIPHER *evp_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;
if (p7 == NULL) {
PKCS7err(PKCS7_F_PKCS7_DATADECODE, PKCS7_R_INVALID_NULL_POINTER);
return NULL;
}
if (p7->d.ptr == NULL) {
PKCS7err(PKCS7_F_PKCS7_DATADECODE, 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) {
PKCS7err(PKCS7_F_PKCS7_DATADECODE,
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;
evp_cipher = EVP_get_cipherbyobj(enc_alg->algorithm);
if (evp_cipher == NULL) {
PKCS7err(PKCS7_F_PKCS7_DATADECODE,
PKCS7_R_UNSUPPORTED_CIPHER_TYPE);
goto err;
}
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;
evp_cipher = EVP_get_cipherbyobj(enc_alg->algorithm);
if (evp_cipher == NULL) {
PKCS7err(PKCS7_F_PKCS7_DATADECODE,
PKCS7_R_UNSUPPORTED_CIPHER_TYPE);
goto err;
}
break;
default:
PKCS7err(PKCS7_F_PKCS7_DATADECODE, PKCS7_R_UNSUPPORTED_CONTENT_TYPE);
goto err;
}
/* Detached content must be supplied via in_bio instead. */
if (data_body == NULL && in_bio == NULL) {
PKCS7err(PKCS7_F_PKCS7_DATADECODE, 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) {
PKCS7err(PKCS7_F_PKCS7_DATADECODE, ERR_R_BIO_LIB);
goto err;
}
j = OBJ_obj2nid(xa->algorithm);
evp_md = EVP_get_digestbynid(j);
if (evp_md == NULL) {
PKCS7err(PKCS7_F_PKCS7_DATADECODE,
PKCS7_R_UNKNOWN_DIGEST_TYPE);
goto err;
}
BIO_set_md(btmp, evp_md);
if (out == NULL)
out = btmp;
else
BIO_push(out, btmp);
btmp = NULL;
}
}
if (evp_cipher != NULL) {
#if 0
unsigned char key[EVP_MAX_KEY_LENGTH];
unsigned char iv[EVP_MAX_IV_LENGTH];
unsigned char *p;
int keylen, ivlen;
int max;
X509_OBJECT ret;
#endif
if ((etmp = BIO_new(BIO_f_cipher())) == NULL) {
PKCS7err(PKCS7_F_PKCS7_DATADECODE, 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) {
PKCS7err(PKCS7_F_PKCS7_DATADECODE,
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 sucess 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);
if (pkcs7_decrypt_rinfo(&ek, &eklen, ri, pkey) < 0)
goto err;
ERR_clear_error();
}
} else {
/* Only exit on fatal errors, not decrypt failure */
if (pkcs7_decrypt_rinfo(&ek, &eklen, ri, pkey) < 0)
goto err;
ERR_clear_error();
}
evp_ctx = NULL;
BIO_get_cipher_ctx(etmp, &evp_ctx);
if (EVP_CipherInit_ex(evp_ctx, evp_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 */
tkeylen = EVP_CIPHER_CTX_key_length(evp_ctx);
tkey = OPENSSL_malloc(tkeylen);
if (!tkey)
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_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)) {
/* Use random key as MMA defence */
OPENSSL_cleanse(ek, eklen);
OPENSSL_free(ek);
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;
if (ek) {
OPENSSL_cleanse(ek, eklen);
OPENSSL_free(ek);
ek = NULL;
}
if (tkey) {
OPENSSL_cleanse(tkey, tkeylen);
OPENSSL_free(tkey);
tkey = NULL;
}
if (out == NULL)
out = etmp;
else
BIO_push(out, etmp);
etmp = NULL;
}
#if 1
if (in_bio != NULL) {
bio = in_bio;
} else {
# if 0
bio = BIO_new(BIO_s_mem());
if (bio == NULL)
goto err;
/*
* We need to set this so that when we have read all the data, the
* encrypt BIO, if present, will read EOF and encode the last few
* bytes
*/
BIO_set_mem_eof_return(bio, 0);
if (data_body->length > 0)
BIO_write(bio, (char *)data_body->data, data_body->length);
# 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;
# endif
}
BIO_push(out, bio);
bio = NULL;
#endif
if (0) {
err:
if (ek) {
OPENSSL_cleanse(ek, eklen);
OPENSSL_free(ek);
}
if (tkey) {
OPENSSL_cleanse(tkey, tkeylen);
OPENSSL_free(tkey);
}
if (out != NULL)
BIO_free_all(out);
if (btmp != NULL)
BIO_free_all(btmp);
if (etmp != NULL)
BIO_free_all(etmp);
if (bio != NULL)
BIO_free_all(bio);
out = NULL;
}
return (out);
}
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) {
PKCS7err(PKCS7_F_PKCS7_FIND_DIGEST,
PKCS7_R_UNABLE_TO_FIND_MESSAGE_DIGEST);
return NULL;
}
BIO_get_md_ctx(bio, pmd);
if (*pmd == NULL) {
PKCS7err(PKCS7_F_PKCS7_FIND_DIGEST, ERR_R_INTERNAL_ERROR);
return NULL;
}
if (EVP_MD_CTX_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)) {
PKCS7err(PKCS7_F_DO_PKCS7_SIGNED_ATTRIB, ERR_R_MALLOC_FAILURE);
return 0;
}
}
/* Add digest */
if (!EVP_DigestFinal_ex(mctx, md_data, &md_len)) {
PKCS7err(PKCS7_F_DO_PKCS7_SIGNED_ATTRIB, ERR_R_EVP_LIB);
return 0;
}
if (!PKCS7_add1_attrib_digest(si, md_data, md_len)) {
PKCS7err(PKCS7_F_DO_PKCS7_SIGNED_ATTRIB, 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;
if (p7 == NULL) {
PKCS7err(PKCS7_F_PKCS7_DATAFINAL, PKCS7_R_INVALID_NULL_POINTER);
return 0;
}
if (p7->d.ptr == NULL) {
PKCS7err(PKCS7_F_PKCS7_DATAFINAL, PKCS7_R_NO_CONTENT);
return 0;
}
EVP_MD_CTX_init(&ctx_tmp);
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) {
os = M_ASN1_OCTET_STRING_new();
if (!os) {
PKCS7err(PKCS7_F_PKCS7_DATAFINAL, 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) {
os = M_ASN1_OCTET_STRING_new();
if (!os) {
PKCS7err(PKCS7_F_PKCS7_DATAFINAL, 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) {
M_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) {
M_ASN1_OCTET_STRING_free(os);
os = NULL;
p7->d.digest->contents->d.data = NULL;
}
break;
default:
PKCS7err(PKCS7_F_PKCS7_DATAFINAL, 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_size(si->pkey);
abuf = OPENSSL_malloc(abuflen);
if (!abuf)
goto err;
if (!EVP_SignFinal(&ctx_tmp, abuf, &abuflen, si->pkey)) {
PKCS7err(PKCS7_F_PKCS7_DATAFINAL, 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;
M_ASN1_OCTET_STRING_set(p7->d.digest->digest, md_data, md_len);
}
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) {
PKCS7err(PKCS7_F_PKCS7_DATAFINAL, 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_cleanup(&ctx_tmp);
return (ret);
}
int PKCS7_SIGNER_INFO_sign(PKCS7_SIGNER_INFO *si)
{
EVP_MD_CTX mctx;
EVP_PKEY_CTX *pctx;
unsigned char *abuf = NULL;
int alen;
size_t siglen;
const EVP_MD *md = NULL;
md = EVP_get_digestbyobj(si->digest_alg->algorithm);
if (md == NULL)
return 0;
EVP_MD_CTX_init(&mctx);
if (EVP_DigestSignInit(&mctx, &pctx, md, NULL, si->pkey) <= 0)
goto err;
if (EVP_PKEY_CTX_ctrl(pctx, -1, EVP_PKEY_OP_SIGN,
EVP_PKEY_CTRL_PKCS7_SIGN, 0, si) <= 0) {
PKCS7err(PKCS7_F_PKCS7_SIGNER_INFO_SIGN, PKCS7_R_CTRL_ERROR);
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)
goto err;
if (EVP_DigestSignFinal(&mctx, abuf, &siglen) <= 0)
goto err;
if (EVP_PKEY_CTX_ctrl(pctx, -1, EVP_PKEY_OP_SIGN,
EVP_PKEY_CTRL_PKCS7_SIGN, 1, si) <= 0) {
PKCS7err(PKCS7_F_PKCS7_SIGNER_INFO_SIGN, PKCS7_R_CTRL_ERROR);
goto err;
}
EVP_MD_CTX_cleanup(&mctx);
ASN1_STRING_set0(si->enc_digest, abuf, siglen);
return 1;
err:
if (abuf)
OPENSSL_free(abuf);
EVP_MD_CTX_cleanup(&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) {
PKCS7err(PKCS7_F_PKCS7_DATAVERIFY, PKCS7_R_INVALID_NULL_POINTER);
return 0;
}
if (p7->d.ptr == NULL) {
PKCS7err(PKCS7_F_PKCS7_DATAVERIFY, 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 {
PKCS7err(PKCS7_F_PKCS7_DATAVERIFY, 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) {
PKCS7err(PKCS7_F_PKCS7_DATAVERIFY,
PKCS7_R_UNABLE_TO_FIND_CERTIFICATE);
goto err;
}
/* Lets verify */
if (!X509_STORE_CTX_init(ctx, cert_store, x509, cert)) {
PKCS7err(PKCS7_F_PKCS7_DATAVERIFY, ERR_R_X509_LIB);
goto err;
}
X509_STORE_CTX_set_purpose(ctx, X509_PURPOSE_SMIME_SIGN);
i = X509_verify_cert(ctx);
if (i <= 0) {
PKCS7err(PKCS7_F_PKCS7_DATAVERIFY, ERR_R_X509_LIB);
X509_STORE_CTX_cleanup(ctx);
goto err;
}
X509_STORE_CTX_cleanup(ctx);
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;
int ret = 0, i;
int md_type;
STACK_OF(X509_ATTRIBUTE) *sk;
BIO *btmp;
EVP_PKEY *pkey;
EVP_MD_CTX_init(&mdc_tmp);
if (!PKCS7_type_is_signed(p7) && !PKCS7_type_is_signedAndEnveloped(p7)) {
PKCS7err(PKCS7_F_PKCS7_SIGNATUREVERIFY, 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)) {
PKCS7err(PKCS7_F_PKCS7_SIGNATUREVERIFY,
PKCS7_R_UNABLE_TO_FIND_MESSAGE_DIGEST);
goto err;
}
BIO_get_md_ctx(btmp, &mdc);
if (mdc == NULL) {
PKCS7err(PKCS7_F_PKCS7_SIGNATUREVERIFY, ERR_R_INTERNAL_ERROR);
goto err;
}
if (EVP_MD_CTX_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_pkey_type(EVP_MD_CTX_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) {
PKCS7err(PKCS7_F_PKCS7_SIGNATUREVERIFY,
PKCS7_R_UNABLE_TO_FIND_MESSAGE_DIGEST);
goto err;
}
if ((message_digest->length != (int)md_len) ||
(memcmp(message_digest->data, md_dat, md_len))) {
#if 0
{
int ii;
for (ii = 0; ii < message_digest->length; ii++)
printf("%02X", message_digest->data[ii]);
printf(" sent\n");
for (ii = 0; ii < md_len; ii++)
printf("%02X", md_dat[ii]);
printf(" calc\n");
}
#endif
PKCS7err(PKCS7_F_PKCS7_SIGNATUREVERIFY, PKCS7_R_DIGEST_FAILURE);
ret = -1;
goto err;
}
if (!EVP_VerifyInit_ex(&mdc_tmp, EVP_get_digestbynid(md_type), NULL))
goto err;
alen = ASN1_item_i2d((ASN1_VALUE *)sk, &abuf,
ASN1_ITEM_rptr(PKCS7_ATTR_VERIFY));
if (alen <= 0) {
PKCS7err(PKCS7_F_PKCS7_SIGNATUREVERIFY, 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_get_pubkey(x509);
if (!pkey) {
ret = -1;
goto err;
}
i = EVP_VerifyFinal(&mdc_tmp, os->data, os->length, pkey);
EVP_PKEY_free(pkey);
if (i <= 0) {
PKCS7err(PKCS7_F_PKCS7_SIGNATUREVERIFY, PKCS7_R_SIGNATURE_FAILURE);
ret = -1;
goto err;
} else
ret = 1;
err:
EVP_MD_CTX_cleanup(&mdc_tmp);
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(PKCS7_SIGNER_INFO *si, int nid)
{
return (get_attribute(si->auth_attr, nid));
}
ASN1_TYPE *PKCS7_get_attribute(PKCS7_SIGNER_INFO *si, int nid)
{
return (get_attribute(si->unauth_attr, nid));
}
static ASN1_TYPE *get_attribute(STACK_OF(X509_ATTRIBUTE) *sk, int nid)
{
int i;
X509_ATTRIBUTE *xa;
ASN1_OBJECT *o;
o = OBJ_nid2obj(nid);
if (!o || !sk)
return (NULL);
for (i = 0; i < sk_X509_ATTRIBUTE_num(sk); i++) {
xa = sk_X509_ATTRIBUTE_value(sk, i);
if (OBJ_cmp(xa->object, o) == 0) {
if (!xa->single && sk_ASN1_TYPE_num(xa->value.set))
return (sk_ASN1_TYPE_value(xa->value.set, 0));
else
return (NULL);
}
}
return (NULL);
}
ASN1_OCTET_STRING *PKCS7_digest_from_attributes(STACK_OF(X509_ATTRIBUTE) *sk)
{
ASN1_TYPE *astype;
if (!(astype = get_attribute(sk, NID_pkcs9_messageDigest)))
return NULL;
return astype->value.octet_string;
}
int PKCS7_set_signed_attributes(PKCS7_SIGNER_INFO *p7si,
STACK_OF(X509_ATTRIBUTE) *sk)
{
int i;
if (p7si->auth_attr != NULL)
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;
if (p7si->unauth_attr != NULL)
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;
if (*sk == NULL) {
*sk = sk_X509_ATTRIBUTE_new_null();
if (*sk == NULL)
return 0;
new_attrib:
if (!(attr = X509_ATTRIBUTE_create(nid, atrtype, value)))
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(attr->object) == 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;
}
end:
return (1);
}
diff --git a/crypto/rand/md_rand.c b/crypto/rand/md_rand.c
index 29e465b07524..a7af9f9d8671 100644
--- a/crypto/rand/md_rand.c
+++ b/crypto/rand/md_rand.c
@@ -1,616 +1,616 @@
/* crypto/rand/md_rand.c */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
/* ====================================================================
* Copyright (c) 1998-2001 The OpenSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* openssl-core@openssl.org.
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.openssl.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*
* This product includes cryptographic software written by Eric Young
* (eay@cryptsoft.com). This product includes software written by Tim
* Hudson (tjh@cryptsoft.com).
*
*/
#define OPENSSL_FIPSEVP
#ifdef MD_RAND_DEBUG
# ifndef NDEBUG
# define NDEBUG
# endif
#endif
#include <assert.h>
#include <stdio.h>
#include <string.h>
#include "e_os.h"
#include <openssl/crypto.h>
#include <openssl/rand.h>
#include "rand_lcl.h"
#include <openssl/err.h>
#ifdef BN_DEBUG
# define PREDICT
#endif
/* #define PREDICT 1 */
#define STATE_SIZE 1023
static size_t state_num = 0, state_index = 0;
static unsigned char state[STATE_SIZE + MD_DIGEST_LENGTH];
static unsigned char md[MD_DIGEST_LENGTH];
static long md_count[2] = { 0, 0 };
static double entropy = 0;
static int initialized = 0;
static unsigned int crypto_lock_rand = 0; /* may be set only when a thread
* holds CRYPTO_LOCK_RAND (to
* prevent double locking) */
/* access to lockin_thread is synchronized by CRYPTO_LOCK_RAND2 */
/* valid iff crypto_lock_rand is set */
static CRYPTO_THREADID locking_threadid;
#ifdef PREDICT
int rand_predictable = 0;
#endif
const char RAND_version[] = "RAND" OPENSSL_VERSION_PTEXT;
static void ssleay_rand_cleanup(void);
static void ssleay_rand_seed(const void *buf, int num);
static void ssleay_rand_add(const void *buf, int num, double add_entropy);
static int ssleay_rand_nopseudo_bytes(unsigned char *buf, int num);
static int ssleay_rand_pseudo_bytes(unsigned char *buf, int num);
static int ssleay_rand_status(void);
RAND_METHOD rand_ssleay_meth = {
ssleay_rand_seed,
ssleay_rand_nopseudo_bytes,
ssleay_rand_cleanup,
ssleay_rand_add,
ssleay_rand_pseudo_bytes,
ssleay_rand_status
};
RAND_METHOD *RAND_SSLeay(void)
{
return (&rand_ssleay_meth);
}
static void ssleay_rand_cleanup(void)
{
OPENSSL_cleanse(state, sizeof(state));
state_num = 0;
state_index = 0;
OPENSSL_cleanse(md, MD_DIGEST_LENGTH);
md_count[0] = 0;
md_count[1] = 0;
entropy = 0;
initialized = 0;
}
static void ssleay_rand_add(const void *buf, int num, double add)
{
int i, j, k, st_idx;
long md_c[2];
unsigned char local_md[MD_DIGEST_LENGTH];
EVP_MD_CTX m;
int do_not_lock;
if (!num)
return;
/*
* (Based on the rand(3) manpage)
*
* The input is chopped up into units of 20 bytes (or less for
* the last block). Each of these blocks is run through the hash
* function as follows: The data passed to the hash function
* is the current 'md', the same number of bytes from the 'state'
* (the location determined by in incremented looping index) as
* the current 'block', the new key data 'block', and 'count'
* (which is incremented after each use).
* The result of this is kept in 'md' and also xored into the
* 'state' at the same locations that were used as input into the
* hash function.
*/
/* check if we already have the lock */
if (crypto_lock_rand) {
CRYPTO_THREADID cur;
CRYPTO_THREADID_current(&cur);
CRYPTO_r_lock(CRYPTO_LOCK_RAND2);
do_not_lock = !CRYPTO_THREADID_cmp(&locking_threadid, &cur);
CRYPTO_r_unlock(CRYPTO_LOCK_RAND2);
} else
do_not_lock = 0;
if (!do_not_lock)
CRYPTO_w_lock(CRYPTO_LOCK_RAND);
st_idx = state_index;
/*
* use our own copies of the counters so that even if a concurrent thread
* seeds with exactly the same data and uses the same subarray there's
* _some_ difference
*/
md_c[0] = md_count[0];
md_c[1] = md_count[1];
- memcpy(local_md, md, sizeof md);
+ memcpy(local_md, md, sizeof(md));
/* state_index <= state_num <= STATE_SIZE */
state_index += num;
if (state_index >= STATE_SIZE) {
state_index %= STATE_SIZE;
state_num = STATE_SIZE;
} else if (state_num < STATE_SIZE) {
if (state_index > state_num)
state_num = state_index;
}
/* state_index <= state_num <= STATE_SIZE */
/*
* state[st_idx], ..., state[(st_idx + num - 1) % STATE_SIZE] are what we
* will use now, but other threads may use them as well
*/
md_count[1] += (num / MD_DIGEST_LENGTH) + (num % MD_DIGEST_LENGTH > 0);
if (!do_not_lock)
CRYPTO_w_unlock(CRYPTO_LOCK_RAND);
EVP_MD_CTX_init(&m);
for (i = 0; i < num; i += MD_DIGEST_LENGTH) {
j = (num - i);
j = (j > MD_DIGEST_LENGTH) ? MD_DIGEST_LENGTH : j;
if (!MD_Init(&m) ||
!MD_Update(&m, local_md, MD_DIGEST_LENGTH))
goto err;
k = (st_idx + j) - STATE_SIZE;
if (k > 0) {
if (!MD_Update(&m, &(state[st_idx]), j - k) ||
!MD_Update(&m, &(state[0]), k))
goto err;
} else
if (!MD_Update(&m, &(state[st_idx]), j))
goto err;
/* DO NOT REMOVE THE FOLLOWING CALL TO MD_Update()! */
if (!MD_Update(&m, buf, j))
goto err;
/*
* We know that line may cause programs such as purify and valgrind
* to complain about use of uninitialized data. The problem is not,
* it's with the caller. Removing that line will make sure you get
* really bad randomness and thereby other problems such as very
* insecure keys.
*/
if (!MD_Update(&m, (unsigned char *)&(md_c[0]), sizeof(md_c)) ||
!MD_Final(&m, local_md))
goto err;
md_c[1]++;
buf = (const char *)buf + j;
for (k = 0; k < j; k++) {
/*
* Parallel threads may interfere with this, but always each byte
* of the new state is the XOR of some previous value of its and
* local_md (itermediate values may be lost). Alway using locking
* could hurt performance more than necessary given that
* conflicts occur only when the total seeding is longer than the
* random state.
*/
state[st_idx++] ^= local_md[k];
if (st_idx >= STATE_SIZE)
st_idx = 0;
}
}
if (!do_not_lock)
CRYPTO_w_lock(CRYPTO_LOCK_RAND);
/*
* Don't just copy back local_md into md -- this could mean that other
* thread's seeding remains without effect (except for the incremented
* counter). By XORing it we keep at least as much entropy as fits into
* md.
*/
for (k = 0; k < (int)sizeof(md); k++) {
md[k] ^= local_md[k];
}
if (entropy < ENTROPY_NEEDED) /* stop counting when we have enough */
entropy += add;
if (!do_not_lock)
CRYPTO_w_unlock(CRYPTO_LOCK_RAND);
#if !defined(OPENSSL_THREADS) && !defined(OPENSSL_SYS_WIN32)
assert(md_c[1] == md_count[1]);
#endif
err:
EVP_MD_CTX_cleanup(&m);
}
static void ssleay_rand_seed(const void *buf, int num)
{
ssleay_rand_add(buf, num, (double)num);
}
int ssleay_rand_bytes(unsigned char *buf, int num, int pseudo, int lock)
{
static volatile int stirred_pool = 0;
int i, j, k;
size_t num_ceil, st_idx, st_num;
int ok;
long md_c[2];
unsigned char local_md[MD_DIGEST_LENGTH];
EVP_MD_CTX m;
#ifndef GETPID_IS_MEANINGLESS
pid_t curr_pid = getpid();
#endif
int do_stir_pool = 0;
#ifdef PREDICT
if (rand_predictable) {
static unsigned char val = 0;
for (i = 0; i < num; i++)
buf[i] = val++;
return (1);
}
#endif
if (num <= 0)
return 1;
EVP_MD_CTX_init(&m);
/* round upwards to multiple of MD_DIGEST_LENGTH/2 */
num_ceil =
(1 + (num - 1) / (MD_DIGEST_LENGTH / 2)) * (MD_DIGEST_LENGTH / 2);
/*
* (Based on the rand(3) manpage:)
*
* For each group of 10 bytes (or less), we do the following:
*
* Input into the hash function the local 'md' (which is initialized from
* the global 'md' before any bytes are generated), the bytes that are to
* be overwritten by the random bytes, and bytes from the 'state'
* (incrementing looping index). From this digest output (which is kept
* in 'md'), the top (up to) 10 bytes are returned to the caller and the
* bottom 10 bytes are xored into the 'state'.
*
* Finally, after we have finished 'num' random bytes for the
* caller, 'count' (which is incremented) and the local and global 'md'
* are fed into the hash function and the results are kept in the
* global 'md'.
*/
if (lock)
CRYPTO_w_lock(CRYPTO_LOCK_RAND);
/* prevent ssleay_rand_bytes() from trying to obtain the lock again */
CRYPTO_w_lock(CRYPTO_LOCK_RAND2);
CRYPTO_THREADID_current(&locking_threadid);
CRYPTO_w_unlock(CRYPTO_LOCK_RAND2);
crypto_lock_rand = 1;
if (!initialized) {
RAND_poll();
initialized = 1;
}
if (!stirred_pool)
do_stir_pool = 1;
ok = (entropy >= ENTROPY_NEEDED);
if (!ok) {
/*
* If the PRNG state is not yet unpredictable, then seeing the PRNG
* output may help attackers to determine the new state; thus we have
* to decrease the entropy estimate. Once we've had enough initial
* seeding we don't bother to adjust the entropy count, though,
* because we're not ambitious to provide *information-theoretic*
* randomness. NOTE: This approach fails if the program forks before
* we have enough entropy. Entropy should be collected in a separate
* input pool and be transferred to the output pool only when the
* entropy limit has been reached.
*/
entropy -= num;
if (entropy < 0)
entropy = 0;
}
if (do_stir_pool) {
/*
* In the output function only half of 'md' remains secret, so we
* better make sure that the required entropy gets 'evenly
* distributed' through 'state', our randomness pool. The input
* function (ssleay_rand_add) chains all of 'md', which makes it more
* suitable for this purpose.
*/
int n = STATE_SIZE; /* so that the complete pool gets accessed */
while (n > 0) {
#if MD_DIGEST_LENGTH > 20
# error "Please adjust DUMMY_SEED."
#endif
#define DUMMY_SEED "...................." /* at least MD_DIGEST_LENGTH */
/*
* Note that the seed does not matter, it's just that
* ssleay_rand_add expects to have something to hash.
*/
ssleay_rand_add(DUMMY_SEED, MD_DIGEST_LENGTH, 0.0);
n -= MD_DIGEST_LENGTH;
}
if (ok)
stirred_pool = 1;
}
st_idx = state_index;
st_num = state_num;
md_c[0] = md_count[0];
md_c[1] = md_count[1];
- memcpy(local_md, md, sizeof md);
+ memcpy(local_md, md, sizeof(md));
state_index += num_ceil;
if (state_index > state_num)
state_index %= state_num;
/*
* state[st_idx], ..., state[(st_idx + num_ceil - 1) % st_num] are now
* ours (but other threads may use them too)
*/
md_count[0] += 1;
/* before unlocking, we must clear 'crypto_lock_rand' */
crypto_lock_rand = 0;
if (lock)
CRYPTO_w_unlock(CRYPTO_LOCK_RAND);
while (num > 0) {
/* num_ceil -= MD_DIGEST_LENGTH/2 */
j = (num >= MD_DIGEST_LENGTH / 2) ? MD_DIGEST_LENGTH / 2 : num;
num -= j;
if (!MD_Init(&m))
goto err;
#ifndef GETPID_IS_MEANINGLESS
if (curr_pid) { /* just in the first iteration to save time */
- if (!MD_Update(&m, (unsigned char *)&curr_pid, sizeof curr_pid))
+ if (!MD_Update(&m, (unsigned char *)&curr_pid, sizeof(curr_pid)))
goto err;
curr_pid = 0;
}
#endif
if (!MD_Update(&m, local_md, MD_DIGEST_LENGTH) ||
!MD_Update(&m, (unsigned char *)&(md_c[0]), sizeof(md_c)))
goto err;
#ifndef PURIFY /* purify complains */
/*
* The following line uses the supplied buffer as a small source of
* entropy: since this buffer is often uninitialised it may cause
* programs such as purify or valgrind to complain. So for those
* builds it is not used: the removal of such a small source of
* entropy has negligible impact on security.
*/
if (!MD_Update(&m, buf, j))
goto err;
#endif
k = (st_idx + MD_DIGEST_LENGTH / 2) - st_num;
if (k > 0) {
if (!MD_Update(&m, &(state[st_idx]), MD_DIGEST_LENGTH / 2 - k) ||
!MD_Update(&m, &(state[0]), k))
goto err;
} else {
if (!MD_Update(&m, &(state[st_idx]), MD_DIGEST_LENGTH / 2))
goto err;
}
if (!MD_Final(&m, local_md))
goto err;
for (i = 0; i < MD_DIGEST_LENGTH / 2; i++) {
/* may compete with other threads */
state[st_idx++] ^= local_md[i];
if (st_idx >= st_num)
st_idx = 0;
if (i < j)
*(buf++) = local_md[i + MD_DIGEST_LENGTH / 2];
}
}
if (!MD_Init(&m) ||
!MD_Update(&m, (unsigned char *)&(md_c[0]), sizeof(md_c)) ||
!MD_Update(&m, local_md, MD_DIGEST_LENGTH))
goto err;
if (lock)
CRYPTO_w_lock(CRYPTO_LOCK_RAND);
if (!MD_Update(&m, md, MD_DIGEST_LENGTH) ||
!MD_Final(&m, md)) {
if (lock)
CRYPTO_w_unlock(CRYPTO_LOCK_RAND);
goto err;
}
if (lock)
CRYPTO_w_unlock(CRYPTO_LOCK_RAND);
EVP_MD_CTX_cleanup(&m);
if (ok)
return (1);
else if (pseudo)
return 0;
else {
RANDerr(RAND_F_SSLEAY_RAND_BYTES, RAND_R_PRNG_NOT_SEEDED);
ERR_add_error_data(1, "You need to read the OpenSSL FAQ, "
"http://www.openssl.org/support/faq.html");
return (0);
}
err:
EVP_MD_CTX_cleanup(&m);
return (0);
}
static int ssleay_rand_nopseudo_bytes(unsigned char *buf, int num)
{
return ssleay_rand_bytes(buf, num, 0, 1);
}
/*
* pseudo-random bytes that are guaranteed to be unique but not unpredictable
*/
static int ssleay_rand_pseudo_bytes(unsigned char *buf, int num)
{
return ssleay_rand_bytes(buf, num, 1, 1);
}
static int ssleay_rand_status(void)
{
CRYPTO_THREADID cur;
int ret;
int do_not_lock;
CRYPTO_THREADID_current(&cur);
/*
* check if we already have the lock (could happen if a RAND_poll()
* implementation calls RAND_status())
*/
if (crypto_lock_rand) {
CRYPTO_r_lock(CRYPTO_LOCK_RAND2);
do_not_lock = !CRYPTO_THREADID_cmp(&locking_threadid, &cur);
CRYPTO_r_unlock(CRYPTO_LOCK_RAND2);
} else
do_not_lock = 0;
if (!do_not_lock) {
CRYPTO_w_lock(CRYPTO_LOCK_RAND);
/*
* prevent ssleay_rand_bytes() from trying to obtain the lock again
*/
CRYPTO_w_lock(CRYPTO_LOCK_RAND2);
CRYPTO_THREADID_cpy(&locking_threadid, &cur);
CRYPTO_w_unlock(CRYPTO_LOCK_RAND2);
crypto_lock_rand = 1;
}
if (!initialized) {
RAND_poll();
initialized = 1;
}
ret = entropy >= ENTROPY_NEEDED;
if (!do_not_lock) {
/* before unlocking, we must clear 'crypto_lock_rand' */
crypto_lock_rand = 0;
CRYPTO_w_unlock(CRYPTO_LOCK_RAND);
}
return ret;
}
diff --git a/crypto/rand/rand_egd.c b/crypto/rand/rand_egd.c
index 737aebfa22fe..66fb14c87efd 100644
--- a/crypto/rand/rand_egd.c
+++ b/crypto/rand/rand_egd.c
@@ -1,292 +1,292 @@
/* crypto/rand/rand_egd.c */
/* Written by Ulf Moeller and Lutz Jaenicke for the OpenSSL project. */
/* ====================================================================
* Copyright (c) 1998-2000 The OpenSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* openssl-core@openssl.org.
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.openssl.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*
* This product includes cryptographic software written by Eric Young
* (eay@cryptsoft.com). This product includes software written by Tim
* Hudson (tjh@cryptsoft.com).
*
*/
#include <openssl/e_os2.h>
#include <openssl/rand.h>
#include <openssl/buffer.h>
/*-
* Query the EGD <URL: http://www.lothar.com/tech/crypto/>.
*
* This module supplies three routines:
*
* RAND_query_egd_bytes(path, buf, bytes)
* will actually query "bytes" bytes of entropy form the egd-socket located
* at path and will write them to buf (if supplied) or will directly feed
* it to RAND_seed() if buf==NULL.
* The number of bytes is not limited by the maximum chunk size of EGD,
* which is 255 bytes. If more than 255 bytes are wanted, several chunks
* of entropy bytes are requested. The connection is left open until the
* query is competed.
* RAND_query_egd_bytes() returns with
* -1 if an error occured during connection or communication.
* num the number of bytes read from the EGD socket. This number is either
* the number of bytes requested or smaller, if the EGD pool is
* drained and the daemon signals that the pool is empty.
* This routine does not touch any RAND_status(). This is necessary, since
* PRNG functions may call it during initialization.
*
* RAND_egd_bytes(path, bytes) will query "bytes" bytes and have them
* used to seed the PRNG.
* RAND_egd_bytes() is a wrapper for RAND_query_egd_bytes() with buf=NULL.
* Unlike RAND_query_egd_bytes(), RAND_status() is used to test the
* seed status so that the return value can reflect the seed state:
* -1 if an error occured during connection or communication _or_
* if the PRNG has still not received the required seeding.
* num the number of bytes read from the EGD socket. This number is either
* the number of bytes requested or smaller, if the EGD pool is
* drained and the daemon signals that the pool is empty.
*
* RAND_egd(path) will query 255 bytes and use the bytes retreived to seed
* the PRNG.
* RAND_egd() is a wrapper for RAND_egd_bytes() with numbytes=255.
*/
#if defined(OPENSSL_SYS_WIN32) || defined(OPENSSL_SYS_VMS) || defined(OPENSSL_SYS_MSDOS) || defined(OPENSSL_SYS_VXWORKS) || defined(OPENSSL_SYS_NETWARE) || defined(OPENSSL_SYS_VOS) || defined(OPENSSL_SYS_BEOS)
int RAND_query_egd_bytes(const char *path, unsigned char *buf, int bytes)
{
return (-1);
}
int RAND_egd(const char *path)
{
return (-1);
}
int RAND_egd_bytes(const char *path, int bytes)
{
return (-1);
}
#else
# include <openssl/opensslconf.h>
# include OPENSSL_UNISTD
# include <stddef.h>
# include <sys/types.h>
# include <sys/socket.h>
# ifndef NO_SYS_UN_H
# ifdef OPENSSL_SYS_VXWORKS
# include <streams/un.h>
# else
# include <sys/un.h>
# endif
# else
struct sockaddr_un {
short sun_family; /* AF_UNIX */
char sun_path[108]; /* path name (gag) */
};
# endif /* NO_SYS_UN_H */
# include <string.h>
# include <errno.h>
# ifndef offsetof
# define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)
# endif
int RAND_query_egd_bytes(const char *path, unsigned char *buf, int bytes)
{
int ret = 0;
struct sockaddr_un addr;
int len, num, numbytes;
int fd = -1;
int success;
unsigned char egdbuf[2], tempbuf[255], *retrievebuf;
memset(&addr, 0, sizeof(addr));
addr.sun_family = AF_UNIX;
if (strlen(path) >= sizeof(addr.sun_path))
return (-1);
- BUF_strlcpy(addr.sun_path, path, sizeof addr.sun_path);
+ BUF_strlcpy(addr.sun_path, path, sizeof(addr.sun_path));
len = offsetof(struct sockaddr_un, sun_path) + strlen(path);
fd = socket(AF_UNIX, SOCK_STREAM, 0);
if (fd == -1)
return (-1);
success = 0;
while (!success) {
if (connect(fd, (struct sockaddr *)&addr, len) == 0)
success = 1;
else {
switch (errno) {
# ifdef EINTR
case EINTR:
# endif
# ifdef EAGAIN
case EAGAIN:
# endif
# ifdef EINPROGRESS
case EINPROGRESS:
# endif
# ifdef EALREADY
case EALREADY:
# endif
/* No error, try again */
break;
# ifdef EISCONN
case EISCONN:
success = 1;
break;
# endif
default:
goto err; /* failure */
}
}
}
while (bytes > 0) {
egdbuf[0] = 1;
egdbuf[1] = bytes < 255 ? bytes : 255;
numbytes = 0;
while (numbytes != 2) {
num = write(fd, egdbuf + numbytes, 2 - numbytes);
if (num >= 0)
numbytes += num;
else {
switch (errno) {
# ifdef EINTR
case EINTR:
# endif
# ifdef EAGAIN
case EAGAIN:
# endif
/* No error, try again */
break;
default:
ret = -1;
goto err; /* failure */
}
}
}
numbytes = 0;
while (numbytes != 1) {
num = read(fd, egdbuf, 1);
if (num == 0)
goto err; /* descriptor closed */
else if (num > 0)
numbytes += num;
else {
switch (errno) {
# ifdef EINTR
case EINTR:
# endif
# ifdef EAGAIN
case EAGAIN:
# endif
/* No error, try again */
break;
default:
ret = -1;
goto err; /* failure */
}
}
}
if (egdbuf[0] == 0)
goto err;
if (buf)
retrievebuf = buf + ret;
else
retrievebuf = tempbuf;
numbytes = 0;
while (numbytes != egdbuf[0]) {
num = read(fd, retrievebuf + numbytes, egdbuf[0] - numbytes);
if (num == 0)
goto err; /* descriptor closed */
else if (num > 0)
numbytes += num;
else {
switch (errno) {
# ifdef EINTR
case EINTR:
# endif
# ifdef EAGAIN
case EAGAIN:
# endif
/* No error, try again */
break;
default:
ret = -1;
goto err; /* failure */
}
}
}
ret += egdbuf[0];
bytes -= egdbuf[0];
if (!buf)
RAND_seed(tempbuf, egdbuf[0]);
}
err:
if (fd != -1)
close(fd);
return (ret);
}
int RAND_egd_bytes(const char *path, int bytes)
{
int num, ret = 0;
num = RAND_query_egd_bytes(path, NULL, bytes);
if (num < 1)
goto err;
if (RAND_status() == 1)
ret = num;
err:
return (ret);
}
int RAND_egd(const char *path)
{
return (RAND_egd_bytes(path, 255));
}
#endif
diff --git a/crypto/rand/rand_unix.c b/crypto/rand/rand_unix.c
index 6c5b65da0070..097e4099181a 100644
--- a/crypto/rand/rand_unix.c
+++ b/crypto/rand/rand_unix.c
@@ -1,447 +1,447 @@
/* crypto/rand/rand_unix.c */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
/* ====================================================================
* Copyright (c) 1998-2006 The OpenSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* openssl-core@openssl.org.
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.openssl.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*
* This product includes cryptographic software written by Eric Young
* (eay@cryptsoft.com). This product includes software written by Tim
* Hudson (tjh@cryptsoft.com).
*
*/
#include <stdio.h>
#define USE_SOCKETS
#include "e_os.h"
#include "cryptlib.h"
#include <openssl/rand.h>
#include "rand_lcl.h"
#if !(defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_WIN32) || defined(OPENSSL_SYS_VMS) || defined(OPENSSL_SYS_OS2) || defined(OPENSSL_SYS_VXWORKS) || defined(OPENSSL_SYS_NETWARE))
# include <sys/types.h>
# include <sys/time.h>
# include <sys/times.h>
# include <sys/stat.h>
# include <fcntl.h>
# include <unistd.h>
# include <time.h>
# if defined(OPENSSL_SYS_LINUX) /* should actually be available virtually
* everywhere */
# include <poll.h>
# endif
# include <limits.h>
# ifndef FD_SETSIZE
# define FD_SETSIZE (8*sizeof(fd_set))
# endif
# if defined(OPENSSL_SYS_VOS)
/*
* The following algorithm repeatedly samples the real-time clock (RTC) to
* generate a sequence of unpredictable data. The algorithm relies upon the
* uneven execution speed of the code (due to factors such as cache misses,
* interrupts, bus activity, and scheduling) and upon the rather large
* relative difference between the speed of the clock and the rate at which
* it can be read.
*
* If this code is ported to an environment where execution speed is more
* constant or where the RTC ticks at a much slower rate, or the clock can be
* read with fewer instructions, it is likely that the results would be far
* more predictable.
*
* As a precaution, we generate 4 times the minimum required amount of seed
* data.
*/
int RAND_poll(void)
{
short int code;
gid_t curr_gid;
pid_t curr_pid;
uid_t curr_uid;
int i, k;
struct timespec ts;
unsigned char v;
# ifdef OPENSSL_SYS_VOS_HPPA
long duration;
extern void s$sleep(long *_duration, short int *_code);
# else
# ifdef OPENSSL_SYS_VOS_IA32
long long duration;
extern void s$sleep2(long long *_duration, short int *_code);
# else
# error "Unsupported Platform."
# endif /* OPENSSL_SYS_VOS_IA32 */
# endif /* OPENSSL_SYS_VOS_HPPA */
/*
* Seed with the gid, pid, and uid, to ensure *some* variation between
* different processes.
*/
curr_gid = getgid();
- RAND_add(&curr_gid, sizeof curr_gid, 1);
+ RAND_add(&curr_gid, sizeof(curr_gid), 1);
curr_gid = 0;
curr_pid = getpid();
- RAND_add(&curr_pid, sizeof curr_pid, 1);
+ RAND_add(&curr_pid, sizeof(curr_pid), 1);
curr_pid = 0;
curr_uid = getuid();
- RAND_add(&curr_uid, sizeof curr_uid, 1);
+ RAND_add(&curr_uid, sizeof(curr_uid), 1);
curr_uid = 0;
for (i = 0; i < (ENTROPY_NEEDED * 4); i++) {
/*
* burn some cpu; hope for interrupts, cache collisions, bus
* interference, etc.
*/
for (k = 0; k < 99; k++)
ts.tv_nsec = random();
# ifdef OPENSSL_SYS_VOS_HPPA
/* sleep for 1/1024 of a second (976 us). */
duration = 1;
s$sleep(&duration, &code);
# else
# ifdef OPENSSL_SYS_VOS_IA32
/* sleep for 1/65536 of a second (15 us). */
duration = 1;
s$sleep2(&duration, &code);
# endif /* OPENSSL_SYS_VOS_IA32 */
# endif /* OPENSSL_SYS_VOS_HPPA */
/* get wall clock time. */
clock_gettime(CLOCK_REALTIME, &ts);
/* take 8 bits */
v = (unsigned char)(ts.tv_nsec % 256);
- RAND_add(&v, sizeof v, 1);
+ RAND_add(&v, sizeof(v), 1);
v = 0;
}
return 1;
}
# elif defined __OpenBSD__
int RAND_poll(void)
{
u_int32_t rnd = 0, i;
unsigned char buf[ENTROPY_NEEDED];
for (i = 0; i < sizeof(buf); i++) {
if (i % 4 == 0)
rnd = arc4random();
buf[i] = rnd;
rnd >>= 8;
}
RAND_add(buf, sizeof(buf), ENTROPY_NEEDED);
OPENSSL_cleanse(buf, sizeof(buf));
return 1;
}
# else /* !defined(__OpenBSD__) */
int RAND_poll(void)
{
unsigned long l;
pid_t curr_pid = getpid();
# if defined(DEVRANDOM) || defined(DEVRANDOM_EGD)
unsigned char tmpbuf[ENTROPY_NEEDED];
int n = 0;
# endif
# ifdef DEVRANDOM
static const char *randomfiles[] = { DEVRANDOM };
struct stat randomstats[sizeof(randomfiles) / sizeof(randomfiles[0])];
int fd;
unsigned int i;
# endif
# ifdef DEVRANDOM_EGD
static const char *egdsockets[] = { DEVRANDOM_EGD, NULL };
const char **egdsocket = NULL;
# endif
# ifdef DEVRANDOM
memset(randomstats, 0, sizeof(randomstats));
/*
* Use a random entropy pool device. Linux, FreeBSD and OpenBSD have
* this. Use /dev/urandom if you can as /dev/random may block if it runs
* out of random entries.
*/
for (i = 0; (i < sizeof(randomfiles) / sizeof(randomfiles[0])) &&
(n < ENTROPY_NEEDED); i++) {
if ((fd = open(randomfiles[i], O_RDONLY
# ifdef O_NONBLOCK
| O_NONBLOCK
# endif
# ifdef O_BINARY
| O_BINARY
# endif
# ifdef O_NOCTTY /* If it happens to be a TTY (god forbid), do
* not make it our controlling tty */
| O_NOCTTY
# endif
)) >= 0) {
int usec = 10 * 1000; /* spend 10ms on each file */
int r;
unsigned int j;
struct stat *st = &randomstats[i];
/*
* Avoid using same input... Used to be O_NOFOLLOW above, but
* it's not universally appropriate...
*/
if (fstat(fd, st) != 0) {
close(fd);
continue;
}
for (j = 0; j < i; j++) {
if (randomstats[j].st_ino == st->st_ino &&
randomstats[j].st_dev == st->st_dev)
break;
}
if (j < i) {
close(fd);
continue;
}
do {
int try_read = 0;
# if defined(OPENSSL_SYS_BEOS_R5)
/*
* select() is broken in BeOS R5, so we simply try to read
* something and snooze if we couldn't
*/
try_read = 1;
# elif defined(OPENSSL_SYS_LINUX)
/* use poll() */
struct pollfd pset;
pset.fd = fd;
pset.events = POLLIN;
pset.revents = 0;
if (poll(&pset, 1, usec / 1000) < 0)
usec = 0;
else
try_read = (pset.revents & POLLIN) != 0;
# else
/* use select() */
fd_set fset;
struct timeval t;
t.tv_sec = 0;
t.tv_usec = usec;
if (FD_SETSIZE > 0 && (unsigned)fd >= FD_SETSIZE) {
/*
* can't use select, so just try to read once anyway
*/
try_read = 1;
} else {
FD_ZERO(&fset);
FD_SET(fd, &fset);
if (select(fd + 1, &fset, NULL, NULL, &t) >= 0) {
usec = t.tv_usec;
if (FD_ISSET(fd, &fset))
try_read = 1;
} else
usec = 0;
}
# endif
if (try_read) {
r = read(fd, (unsigned char *)tmpbuf + n,
ENTROPY_NEEDED - n);
if (r > 0)
n += r;
# if defined(OPENSSL_SYS_BEOS_R5)
if (r == 0)
snooze(t.tv_usec);
# endif
} else
r = -1;
/*
* Some Unixen will update t in select(), some won't. For
* those who won't, or if we didn't use select() in the first
* place, give up here, otherwise, we will do this once again
* for the remaining time.
*/
if (usec == 10 * 1000)
usec = 0;
}
while ((r > 0 ||
(errno == EINTR || errno == EAGAIN)) && usec != 0
&& n < ENTROPY_NEEDED);
close(fd);
}
}
# endif /* defined(DEVRANDOM) */
# ifdef DEVRANDOM_EGD
/*
* Use an EGD socket to read entropy from an EGD or PRNGD entropy
* collecting daemon.
*/
for (egdsocket = egdsockets; *egdsocket && n < ENTROPY_NEEDED;
egdsocket++) {
int r;
r = RAND_query_egd_bytes(*egdsocket, (unsigned char *)tmpbuf + n,
ENTROPY_NEEDED - n);
if (r > 0)
n += r;
}
# endif /* defined(DEVRANDOM_EGD) */
# if defined(DEVRANDOM) || defined(DEVRANDOM_EGD)
if (n > 0) {
- RAND_add(tmpbuf, sizeof tmpbuf, (double)n);
+ RAND_add(tmpbuf, sizeof(tmpbuf), (double)n);
OPENSSL_cleanse(tmpbuf, n);
}
# endif
/* put in some default random data, we need more than just this */
l = curr_pid;
RAND_add(&l, sizeof(l), 0.0);
l = getuid();
RAND_add(&l, sizeof(l), 0.0);
l = time(NULL);
RAND_add(&l, sizeof(l), 0.0);
# if defined(OPENSSL_SYS_BEOS)
{
system_info sysInfo;
get_system_info(&sysInfo);
RAND_add(&sysInfo, sizeof(sysInfo), 0);
}
# endif
# if defined(DEVRANDOM) || defined(DEVRANDOM_EGD)
return 1;
# else
return 0;
# endif
}
# endif /* defined(__OpenBSD__) */
#endif /* !(defined(OPENSSL_SYS_WINDOWS) ||
* defined(OPENSSL_SYS_WIN32) ||
* defined(OPENSSL_SYS_VMS) ||
* defined(OPENSSL_SYS_OS2) ||
* defined(OPENSSL_SYS_VXWORKS) ||
* defined(OPENSSL_SYS_NETWARE)) */
#if defined(OPENSSL_SYS_VXWORKS)
int RAND_poll(void)
{
return 0;
}
#endif
diff --git a/crypto/rsa/rsa_crpt.c b/crypto/rsa/rsa_crpt.c
index 5c416b53fab0..68f2981cc54d 100644
--- a/crypto/rsa/rsa_crpt.c
+++ b/crypto/rsa/rsa_crpt.c
@@ -1,247 +1,247 @@
/* crypto/rsa/rsa_lib.c */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
#include <stdio.h>
#include <openssl/crypto.h>
#include "cryptlib.h"
#include <openssl/lhash.h>
#include <openssl/bn.h>
#include <openssl/rsa.h>
#include <openssl/rand.h>
#ifndef OPENSSL_NO_ENGINE
# include <openssl/engine.h>
#endif
int RSA_size(const RSA *r)
{
return (BN_num_bytes(r->n));
}
int RSA_public_encrypt(int flen, const unsigned char *from, unsigned char *to,
RSA *rsa, int padding)
{
#ifdef OPENSSL_FIPS
if (FIPS_mode() && !(rsa->meth->flags & RSA_FLAG_FIPS_METHOD)
&& !(rsa->flags & RSA_FLAG_NON_FIPS_ALLOW)) {
RSAerr(RSA_F_RSA_PUBLIC_ENCRYPT, RSA_R_NON_FIPS_RSA_METHOD);
return -1;
}
#endif
return (rsa->meth->rsa_pub_enc(flen, from, to, rsa, padding));
}
int RSA_private_encrypt(int flen, const unsigned char *from,
unsigned char *to, RSA *rsa, int padding)
{
#ifdef OPENSSL_FIPS
if (FIPS_mode() && !(rsa->meth->flags & RSA_FLAG_FIPS_METHOD)
&& !(rsa->flags & RSA_FLAG_NON_FIPS_ALLOW)) {
RSAerr(RSA_F_RSA_PRIVATE_ENCRYPT, RSA_R_NON_FIPS_RSA_METHOD);
return -1;
}
#endif
return (rsa->meth->rsa_priv_enc(flen, from, to, rsa, padding));
}
int RSA_private_decrypt(int flen, const unsigned char *from,
unsigned char *to, RSA *rsa, int padding)
{
#ifdef OPENSSL_FIPS
if (FIPS_mode() && !(rsa->meth->flags & RSA_FLAG_FIPS_METHOD)
&& !(rsa->flags & RSA_FLAG_NON_FIPS_ALLOW)) {
RSAerr(RSA_F_RSA_PRIVATE_DECRYPT, RSA_R_NON_FIPS_RSA_METHOD);
return -1;
}
#endif
return (rsa->meth->rsa_priv_dec(flen, from, to, rsa, padding));
}
int RSA_public_decrypt(int flen, const unsigned char *from, unsigned char *to,
RSA *rsa, int padding)
{
#ifdef OPENSSL_FIPS
if (FIPS_mode() && !(rsa->meth->flags & RSA_FLAG_FIPS_METHOD)
&& !(rsa->flags & RSA_FLAG_NON_FIPS_ALLOW)) {
RSAerr(RSA_F_RSA_PUBLIC_DECRYPT, RSA_R_NON_FIPS_RSA_METHOD);
return -1;
}
#endif
return (rsa->meth->rsa_pub_dec(flen, from, to, rsa, padding));
}
int RSA_flags(const RSA *r)
{
return ((r == NULL) ? 0 : r->meth->flags);
}
void RSA_blinding_off(RSA *rsa)
{
if (rsa->blinding != NULL) {
BN_BLINDING_free(rsa->blinding);
rsa->blinding = NULL;
}
rsa->flags &= ~RSA_FLAG_BLINDING;
rsa->flags |= RSA_FLAG_NO_BLINDING;
}
int RSA_blinding_on(RSA *rsa, BN_CTX *ctx)
{
int ret = 0;
if (rsa->blinding != NULL)
RSA_blinding_off(rsa);
rsa->blinding = RSA_setup_blinding(rsa, ctx);
if (rsa->blinding == NULL)
goto err;
rsa->flags |= RSA_FLAG_BLINDING;
rsa->flags &= ~RSA_FLAG_NO_BLINDING;
ret = 1;
err:
return (ret);
}
static BIGNUM *rsa_get_public_exp(const BIGNUM *d, const BIGNUM *p,
const BIGNUM *q, BN_CTX *ctx)
{
BIGNUM *ret = NULL, *r0, *r1, *r2;
if (d == NULL || p == NULL || q == NULL)
return NULL;
BN_CTX_start(ctx);
r0 = BN_CTX_get(ctx);
r1 = BN_CTX_get(ctx);
r2 = BN_CTX_get(ctx);
if (r2 == NULL)
goto err;
if (!BN_sub(r1, p, BN_value_one()))
goto err;
if (!BN_sub(r2, q, BN_value_one()))
goto err;
if (!BN_mul(r0, r1, r2, ctx))
goto err;
ret = BN_mod_inverse(NULL, d, r0, ctx);
err:
BN_CTX_end(ctx);
return ret;
}
BN_BLINDING *RSA_setup_blinding(RSA *rsa, BN_CTX *in_ctx)
{
BIGNUM local_n;
BIGNUM *e, *n;
BN_CTX *ctx;
BN_BLINDING *ret = NULL;
if (in_ctx == NULL) {
if ((ctx = BN_CTX_new()) == NULL)
return 0;
} else
ctx = in_ctx;
BN_CTX_start(ctx);
e = BN_CTX_get(ctx);
if (e == NULL) {
RSAerr(RSA_F_RSA_SETUP_BLINDING, ERR_R_MALLOC_FAILURE);
goto err;
}
if (rsa->e == NULL) {
e = rsa_get_public_exp(rsa->d, rsa->p, rsa->q, ctx);
if (e == NULL) {
RSAerr(RSA_F_RSA_SETUP_BLINDING, RSA_R_NO_PUBLIC_EXPONENT);
goto err;
}
} else
e = rsa->e;
if ((RAND_status() == 0) && rsa->d != NULL && rsa->d->d != NULL) {
/*
* if PRNG is not properly seeded, resort to secret exponent as
* unpredictable seed
*/
- RAND_add(rsa->d->d, rsa->d->dmax * sizeof rsa->d->d[0], 0.0);
+ RAND_add(rsa->d->d, rsa->d->dmax * sizeof(rsa->d->d[0]), 0.0);
}
if (!(rsa->flags & RSA_FLAG_NO_CONSTTIME)) {
/* Set BN_FLG_CONSTTIME flag */
n = &local_n;
BN_with_flags(n, rsa->n, BN_FLG_CONSTTIME);
} else
n = rsa->n;
ret = BN_BLINDING_create_param(NULL, e, n, ctx,
rsa->meth->bn_mod_exp, rsa->_method_mod_n);
if (ret == NULL) {
RSAerr(RSA_F_RSA_SETUP_BLINDING, ERR_R_BN_LIB);
goto err;
}
CRYPTO_THREADID_current(BN_BLINDING_thread_id(ret));
err:
BN_CTX_end(ctx);
if (in_ctx == NULL)
BN_CTX_free(ctx);
if (rsa->e == NULL)
BN_free(e);
return ret;
}
diff --git a/crypto/rsa/rsa_gen.c b/crypto/rsa/rsa_gen.c
index a85493d6097b..9ca5dfefb707 100644
--- a/crypto/rsa/rsa_gen.c
+++ b/crypto/rsa/rsa_gen.c
@@ -1,250 +1,270 @@
/* crypto/rsa/rsa_gen.c */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
/*
* NB: these functions have been "upgraded", the deprecated versions (which
* are compatibility wrappers using these functions) are in rsa_depr.c. -
* Geoff
*/
#include <stdio.h>
#include <time.h>
#include "cryptlib.h"
#include <openssl/bn.h>
#include <openssl/rsa.h>
#ifdef OPENSSL_FIPS
# include <openssl/fips.h>
extern int FIPS_rsa_x931_generate_key_ex(RSA *rsa, int bits, BIGNUM *e,
BN_GENCB *cb);
#endif
static int rsa_builtin_keygen(RSA *rsa, int bits, BIGNUM *e_value,
BN_GENCB *cb);
/*
* NB: this wrapper would normally be placed in rsa_lib.c and the static
* implementation would probably be in rsa_eay.c. Nonetheless, is kept here
* so that we don't introduce a new linker dependency. Eg. any application
* that wasn't previously linking object code related to key-generation won't
* have to now just because key-generation is part of RSA_METHOD.
*/
int RSA_generate_key_ex(RSA *rsa, int bits, BIGNUM *e_value, BN_GENCB *cb)
{
#ifdef OPENSSL_FIPS
if (FIPS_mode() && !(rsa->meth->flags & RSA_FLAG_FIPS_METHOD)
&& !(rsa->flags & RSA_FLAG_NON_FIPS_ALLOW)) {
RSAerr(RSA_F_RSA_GENERATE_KEY_EX, RSA_R_NON_FIPS_RSA_METHOD);
return 0;
}
#endif
if (rsa->meth->rsa_keygen)
return rsa->meth->rsa_keygen(rsa, bits, e_value, cb);
#ifdef OPENSSL_FIPS
if (FIPS_mode())
return FIPS_rsa_x931_generate_key_ex(rsa, bits, e_value, cb);
#endif
return rsa_builtin_keygen(rsa, bits, e_value, cb);
}
static int rsa_builtin_keygen(RSA *rsa, int bits, BIGNUM *e_value,
BN_GENCB *cb)
{
BIGNUM *r0 = NULL, *r1 = NULL, *r2 = NULL, *r3 = NULL, *tmp;
BIGNUM local_r0, local_d, local_p;
BIGNUM *pr0, *d, *p;
int bitsp, bitsq, ok = -1, n = 0;
BN_CTX *ctx = NULL;
+ unsigned long error = 0;
/*
* When generating ridiculously small keys, we can get stuck
* continually regenerating the same prime values.
*/
if (bits < 16) {
ok = 0; /* we set our own err */
RSAerr(RSA_F_RSA_BUILTIN_KEYGEN, RSA_R_KEY_SIZE_TOO_SMALL);
goto err;
}
ctx = BN_CTX_new();
if (ctx == NULL)
goto err;
BN_CTX_start(ctx);
r0 = BN_CTX_get(ctx);
r1 = BN_CTX_get(ctx);
r2 = BN_CTX_get(ctx);
r3 = BN_CTX_get(ctx);
if (r3 == NULL)
goto err;
bitsp = (bits + 1) / 2;
bitsq = bits - bitsp;
/* We need the RSA components non-NULL */
if (!rsa->n && ((rsa->n = BN_new()) == NULL))
goto err;
if (!rsa->d && ((rsa->d = BN_new()) == NULL))
goto err;
if (!rsa->e && ((rsa->e = BN_new()) == NULL))
goto err;
if (!rsa->p && ((rsa->p = BN_new()) == NULL))
goto err;
if (!rsa->q && ((rsa->q = BN_new()) == NULL))
goto err;
if (!rsa->dmp1 && ((rsa->dmp1 = BN_new()) == NULL))
goto err;
if (!rsa->dmq1 && ((rsa->dmq1 = BN_new()) == NULL))
goto err;
if (!rsa->iqmp && ((rsa->iqmp = BN_new()) == NULL))
goto err;
if (BN_copy(rsa->e, e_value) == NULL)
goto err;
+ BN_set_flags(r2, BN_FLG_CONSTTIME);
/* generate p and q */
for (;;) {
if (!BN_generate_prime_ex(rsa->p, bitsp, 0, NULL, NULL, cb))
goto err;
if (!BN_sub(r2, rsa->p, BN_value_one()))
goto err;
- if (!BN_gcd(r1, r2, rsa->e, ctx))
- goto err;
- if (BN_is_one(r1))
+ ERR_set_mark();
+ if (BN_mod_inverse(r1, r2, rsa->e, ctx) != NULL) {
+ /* GCD == 1 since inverse exists */
break;
+ }
+ error = ERR_peek_last_error();
+ if (ERR_GET_LIB(error) == ERR_LIB_BN
+ && ERR_GET_REASON(error) == BN_R_NO_INVERSE) {
+ /* GCD != 1 */
+ ERR_pop_to_mark();
+ } else {
+ goto err;
+ }
if (!BN_GENCB_call(cb, 2, n++))
goto err;
}
if (!BN_GENCB_call(cb, 3, 0))
goto err;
for (;;) {
do {
if (!BN_generate_prime_ex(rsa->q, bitsq, 0, NULL, NULL, cb))
goto err;
} while (BN_cmp(rsa->p, rsa->q) == 0);
if (!BN_sub(r2, rsa->q, BN_value_one()))
goto err;
- if (!BN_gcd(r1, r2, rsa->e, ctx))
- goto err;
- if (BN_is_one(r1))
+ ERR_set_mark();
+ if (BN_mod_inverse(r1, r2, rsa->e, ctx) != NULL) {
+ /* GCD == 1 since inverse exists */
break;
+ }
+ error = ERR_peek_last_error();
+ if (ERR_GET_LIB(error) == ERR_LIB_BN
+ && ERR_GET_REASON(error) == BN_R_NO_INVERSE) {
+ /* GCD != 1 */
+ ERR_pop_to_mark();
+ } else {
+ goto err;
+ }
if (!BN_GENCB_call(cb, 2, n++))
goto err;
}
if (!BN_GENCB_call(cb, 3, 1))
goto err;
if (BN_cmp(rsa->p, rsa->q) < 0) {
tmp = rsa->p;
rsa->p = rsa->q;
rsa->q = tmp;
}
/* calculate n */
if (!BN_mul(rsa->n, rsa->p, rsa->q, ctx))
goto err;
/* calculate d */
if (!BN_sub(r1, rsa->p, BN_value_one()))
goto err; /* p-1 */
if (!BN_sub(r2, rsa->q, BN_value_one()))
goto err; /* q-1 */
if (!BN_mul(r0, r1, r2, ctx))
goto err; /* (p-1)(q-1) */
if (!(rsa->flags & RSA_FLAG_NO_CONSTTIME)) {
pr0 = &local_r0;
BN_with_flags(pr0, r0, BN_FLG_CONSTTIME);
} else
pr0 = r0;
if (!BN_mod_inverse(rsa->d, rsa->e, pr0, ctx))
goto err; /* d */
/* set up d for correct BN_FLG_CONSTTIME flag */
if (!(rsa->flags & RSA_FLAG_NO_CONSTTIME)) {
d = &local_d;
BN_with_flags(d, rsa->d, BN_FLG_CONSTTIME);
} else
d = rsa->d;
/* calculate d mod (p-1) */
if (!BN_mod(rsa->dmp1, d, r1, ctx))
goto err;
/* calculate d mod (q-1) */
if (!BN_mod(rsa->dmq1, d, r2, ctx))
goto err;
/* calculate inverse of q mod p */
if (!(rsa->flags & RSA_FLAG_NO_CONSTTIME)) {
p = &local_p;
BN_with_flags(p, rsa->p, BN_FLG_CONSTTIME);
} else
p = rsa->p;
if (!BN_mod_inverse(rsa->iqmp, rsa->q, p, ctx))
goto err;
ok = 1;
err:
if (ok == -1) {
RSAerr(RSA_F_RSA_BUILTIN_KEYGEN, ERR_LIB_BN);
ok = 0;
}
if (ctx != NULL) {
BN_CTX_end(ctx);
BN_CTX_free(ctx);
}
return ok;
}
diff --git a/crypto/rsa/rsa_pss.c b/crypto/rsa/rsa_pss.c
index 2c3fd73b0996..3c9250ba5eb3 100644
--- a/crypto/rsa/rsa_pss.c
+++ b/crypto/rsa/rsa_pss.c
@@ -1,299 +1,299 @@
/* rsa_pss.c */
/*
* Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL project
* 2005.
*/
/* ====================================================================
* Copyright (c) 2005 The OpenSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* licensing@OpenSSL.org.
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*
* This product includes cryptographic software written by Eric Young
* (eay@cryptsoft.com). This product includes software written by Tim
* Hudson (tjh@cryptsoft.com).
*
*/
#include <stdio.h>
#include "cryptlib.h"
#include <openssl/bn.h>
#include <openssl/rsa.h>
#include <openssl/evp.h>
#include <openssl/rand.h>
#include <openssl/sha.h>
static const unsigned char zeroes[] = { 0, 0, 0, 0, 0, 0, 0, 0 };
#if defined(_MSC_VER) && defined(_ARM_)
# pragma optimize("g", off)
#endif
int RSA_verify_PKCS1_PSS(RSA *rsa, const unsigned char *mHash,
const EVP_MD *Hash, const unsigned char *EM,
int sLen)
{
return RSA_verify_PKCS1_PSS_mgf1(rsa, mHash, Hash, NULL, EM, sLen);
}
int RSA_verify_PKCS1_PSS_mgf1(RSA *rsa, const unsigned char *mHash,
const EVP_MD *Hash, const EVP_MD *mgf1Hash,
const unsigned char *EM, int sLen)
{
int i;
int ret = 0;
int hLen, maskedDBLen, MSBits, emLen;
const unsigned char *H;
unsigned char *DB = NULL;
EVP_MD_CTX ctx;
unsigned char H_[EVP_MAX_MD_SIZE];
EVP_MD_CTX_init(&ctx);
if (mgf1Hash == NULL)
mgf1Hash = Hash;
hLen = EVP_MD_size(Hash);
if (hLen < 0)
goto err;
/*-
* Negative sLen has special meanings:
* -1 sLen == hLen
* -2 salt length is autorecovered from signature
* -N reserved
*/
if (sLen == -1)
sLen = hLen;
else if (sLen == -2)
sLen = -2;
else if (sLen < -2) {
RSAerr(RSA_F_RSA_VERIFY_PKCS1_PSS_MGF1, RSA_R_SLEN_CHECK_FAILED);
goto err;
}
MSBits = (BN_num_bits(rsa->n) - 1) & 0x7;
emLen = RSA_size(rsa);
if (EM[0] & (0xFF << MSBits)) {
RSAerr(RSA_F_RSA_VERIFY_PKCS1_PSS_MGF1, RSA_R_FIRST_OCTET_INVALID);
goto err;
}
if (MSBits == 0) {
EM++;
emLen--;
}
if (emLen < hLen + 2) {
RSAerr(RSA_F_RSA_VERIFY_PKCS1_PSS_MGF1, RSA_R_DATA_TOO_LARGE);
goto err;
}
if (sLen > emLen - hLen - 2) { /* sLen can be small negative */
RSAerr(RSA_F_RSA_VERIFY_PKCS1_PSS_MGF1, RSA_R_DATA_TOO_LARGE);
goto err;
}
if (EM[emLen - 1] != 0xbc) {
RSAerr(RSA_F_RSA_VERIFY_PKCS1_PSS_MGF1, RSA_R_LAST_OCTET_INVALID);
goto err;
}
maskedDBLen = emLen - hLen - 1;
H = EM + maskedDBLen;
DB = OPENSSL_malloc(maskedDBLen);
if (!DB) {
RSAerr(RSA_F_RSA_VERIFY_PKCS1_PSS_MGF1, ERR_R_MALLOC_FAILURE);
goto err;
}
if (PKCS1_MGF1(DB, maskedDBLen, H, hLen, mgf1Hash) < 0)
goto err;
for (i = 0; i < maskedDBLen; i++)
DB[i] ^= EM[i];
if (MSBits)
DB[0] &= 0xFF >> (8 - MSBits);
for (i = 0; DB[i] == 0 && i < (maskedDBLen - 1); i++) ;
if (DB[i++] != 0x1) {
RSAerr(RSA_F_RSA_VERIFY_PKCS1_PSS_MGF1, RSA_R_SLEN_RECOVERY_FAILED);
goto err;
}
if (sLen >= 0 && (maskedDBLen - i) != sLen) {
RSAerr(RSA_F_RSA_VERIFY_PKCS1_PSS_MGF1, RSA_R_SLEN_CHECK_FAILED);
goto err;
}
if (!EVP_DigestInit_ex(&ctx, Hash, NULL)
- || !EVP_DigestUpdate(&ctx, zeroes, sizeof zeroes)
+ || !EVP_DigestUpdate(&ctx, zeroes, sizeof(zeroes))
|| !EVP_DigestUpdate(&ctx, mHash, hLen))
goto err;
if (maskedDBLen - i) {
if (!EVP_DigestUpdate(&ctx, DB + i, maskedDBLen - i))
goto err;
}
if (!EVP_DigestFinal_ex(&ctx, H_, NULL))
goto err;
if (memcmp(H_, H, hLen)) {
RSAerr(RSA_F_RSA_VERIFY_PKCS1_PSS_MGF1, RSA_R_BAD_SIGNATURE);
ret = 0;
} else
ret = 1;
err:
if (DB)
OPENSSL_free(DB);
EVP_MD_CTX_cleanup(&ctx);
return ret;
}
int RSA_padding_add_PKCS1_PSS(RSA *rsa, unsigned char *EM,
const unsigned char *mHash,
const EVP_MD *Hash, int sLen)
{
return RSA_padding_add_PKCS1_PSS_mgf1(rsa, EM, mHash, Hash, NULL, sLen);
}
int RSA_padding_add_PKCS1_PSS_mgf1(RSA *rsa, unsigned char *EM,
const unsigned char *mHash,
const EVP_MD *Hash, const EVP_MD *mgf1Hash,
int sLen)
{
int i;
int ret = 0;
int hLen, maskedDBLen, MSBits, emLen;
unsigned char *H, *salt = NULL, *p;
EVP_MD_CTX ctx;
if (mgf1Hash == NULL)
mgf1Hash = Hash;
hLen = EVP_MD_size(Hash);
if (hLen < 0)
goto err;
/*-
* Negative sLen has special meanings:
* -1 sLen == hLen
* -2 salt length is maximized
* -N reserved
*/
if (sLen == -1)
sLen = hLen;
else if (sLen == -2)
sLen = -2;
else if (sLen < -2) {
RSAerr(RSA_F_RSA_PADDING_ADD_PKCS1_PSS_MGF1, RSA_R_SLEN_CHECK_FAILED);
goto err;
}
MSBits = (BN_num_bits(rsa->n) - 1) & 0x7;
emLen = RSA_size(rsa);
if (MSBits == 0) {
*EM++ = 0;
emLen--;
}
if (emLen < hLen + 2) {
RSAerr(RSA_F_RSA_PADDING_ADD_PKCS1_PSS_MGF1,
RSA_R_DATA_TOO_LARGE_FOR_KEY_SIZE);
goto err;
}
if (sLen == -2) {
sLen = emLen - hLen - 2;
} else if (sLen > emLen - hLen - 2) {
RSAerr(RSA_F_RSA_PADDING_ADD_PKCS1_PSS_MGF1,
RSA_R_DATA_TOO_LARGE_FOR_KEY_SIZE);
goto err;
}
if (sLen > 0) {
salt = OPENSSL_malloc(sLen);
if (!salt) {
RSAerr(RSA_F_RSA_PADDING_ADD_PKCS1_PSS_MGF1,
ERR_R_MALLOC_FAILURE);
goto err;
}
if (RAND_bytes(salt, sLen) <= 0)
goto err;
}
maskedDBLen = emLen - hLen - 1;
H = EM + maskedDBLen;
EVP_MD_CTX_init(&ctx);
if (!EVP_DigestInit_ex(&ctx, Hash, NULL)
- || !EVP_DigestUpdate(&ctx, zeroes, sizeof zeroes)
+ || !EVP_DigestUpdate(&ctx, zeroes, sizeof(zeroes))
|| !EVP_DigestUpdate(&ctx, mHash, hLen))
goto err;
if (sLen && !EVP_DigestUpdate(&ctx, salt, sLen))
goto err;
if (!EVP_DigestFinal_ex(&ctx, H, NULL))
goto err;
EVP_MD_CTX_cleanup(&ctx);
/* Generate dbMask in place then perform XOR on it */
if (PKCS1_MGF1(EM, maskedDBLen, H, hLen, mgf1Hash))
goto err;
p = EM;
/*
* Initial PS XORs with all zeroes which is a NOP so just update pointer.
* Note from a test above this value is guaranteed to be non-negative.
*/
p += emLen - sLen - hLen - 2;
*p++ ^= 0x1;
if (sLen > 0) {
for (i = 0; i < sLen; i++)
*p++ ^= salt[i];
}
if (MSBits)
EM[0] &= 0xFF >> (8 - MSBits);
/* H is already in place so just set final 0xbc */
EM[emLen - 1] = 0xbc;
ret = 1;
err:
if (salt)
OPENSSL_free(salt);
return ret;
}
#if defined(_MSC_VER)
# pragma optimize("",on)
#endif
diff --git a/crypto/rsa/rsa_test.c b/crypto/rsa/rsa_test.c
index 85c7440b8c68..ed78f01081b1 100644
--- a/crypto/rsa/rsa_test.c
+++ b/crypto/rsa/rsa_test.c
@@ -1,339 +1,339 @@
/* test vectors from p1ovect1.txt */
#include <stdio.h>
#include <string.h>
#include "e_os.h"
#include <openssl/crypto.h>
#include <openssl/err.h>
#include <openssl/rand.h>
#include <openssl/bn.h>
#ifdef OPENSSL_NO_RSA
int main(int argc, char *argv[])
{
printf("No RSA support\n");
return (0);
}
#else
# include <openssl/rsa.h>
# define SetKey \
key->n = BN_bin2bn(n, sizeof(n)-1, key->n); \
key->e = BN_bin2bn(e, sizeof(e)-1, key->e); \
key->d = BN_bin2bn(d, sizeof(d)-1, key->d); \
key->p = BN_bin2bn(p, sizeof(p)-1, key->p); \
key->q = BN_bin2bn(q, sizeof(q)-1, key->q); \
key->dmp1 = BN_bin2bn(dmp1, sizeof(dmp1)-1, key->dmp1); \
key->dmq1 = BN_bin2bn(dmq1, sizeof(dmq1)-1, key->dmq1); \
key->iqmp = BN_bin2bn(iqmp, sizeof(iqmp)-1, key->iqmp); \
memcpy(c, ctext_ex, sizeof(ctext_ex) - 1); \
return (sizeof(ctext_ex) - 1);
static int key1(RSA *key, unsigned char *c)
{
static unsigned char n[] =
"\x00\xAA\x36\xAB\xCE\x88\xAC\xFD\xFF\x55\x52\x3C\x7F\xC4\x52\x3F"
"\x90\xEF\xA0\x0D\xF3\x77\x4A\x25\x9F\x2E\x62\xB4\xC5\xD9\x9C\xB5"
"\xAD\xB3\x00\xA0\x28\x5E\x53\x01\x93\x0E\x0C\x70\xFB\x68\x76\x93"
"\x9C\xE6\x16\xCE\x62\x4A\x11\xE0\x08\x6D\x34\x1E\xBC\xAC\xA0\xA1"
"\xF5";
static unsigned char e[] = "\x11";
static unsigned char d[] =
"\x0A\x03\x37\x48\x62\x64\x87\x69\x5F\x5F\x30\xBC\x38\xB9\x8B\x44"
"\xC2\xCD\x2D\xFF\x43\x40\x98\xCD\x20\xD8\xA1\x38\xD0\x90\xBF\x64"
"\x79\x7C\x3F\xA7\xA2\xCD\xCB\x3C\xD1\xE0\xBD\xBA\x26\x54\xB4\xF9"
"\xDF\x8E\x8A\xE5\x9D\x73\x3D\x9F\x33\xB3\x01\x62\x4A\xFD\x1D\x51";
static unsigned char p[] =
"\x00\xD8\x40\xB4\x16\x66\xB4\x2E\x92\xEA\x0D\xA3\xB4\x32\x04\xB5"
"\xCF\xCE\x33\x52\x52\x4D\x04\x16\xA5\xA4\x41\xE7\x00\xAF\x46\x12"
"\x0D";
static unsigned char q[] =
"\x00\xC9\x7F\xB1\xF0\x27\xF4\x53\xF6\x34\x12\x33\xEA\xAA\xD1\xD9"
"\x35\x3F\x6C\x42\xD0\x88\x66\xB1\xD0\x5A\x0F\x20\x35\x02\x8B\x9D"
"\x89";
static unsigned char dmp1[] =
"\x59\x0B\x95\x72\xA2\xC2\xA9\xC4\x06\x05\x9D\xC2\xAB\x2F\x1D\xAF"
"\xEB\x7E\x8B\x4F\x10\xA7\x54\x9E\x8E\xED\xF5\xB4\xFC\xE0\x9E\x05";
static unsigned char dmq1[] =
"\x00\x8E\x3C\x05\x21\xFE\x15\xE0\xEA\x06\xA3\x6F\xF0\xF1\x0C\x99"
"\x52\xC3\x5B\x7A\x75\x14\xFD\x32\x38\xB8\x0A\xAD\x52\x98\x62\x8D"
"\x51";
static unsigned char iqmp[] =
"\x36\x3F\xF7\x18\x9D\xA8\xE9\x0B\x1D\x34\x1F\x71\xD0\x9B\x76\xA8"
"\xA9\x43\xE1\x1D\x10\xB2\x4D\x24\x9F\x2D\xEA\xFE\xF8\x0C\x18\x26";
static unsigned char ctext_ex[] =
"\x1b\x8f\x05\xf9\xca\x1a\x79\x52\x6e\x53\xf3\xcc\x51\x4f\xdb\x89"
"\x2b\xfb\x91\x93\x23\x1e\x78\xb9\x92\xe6\x8d\x50\xa4\x80\xcb\x52"
"\x33\x89\x5c\x74\x95\x8d\x5d\x02\xab\x8c\x0f\xd0\x40\xeb\x58\x44"
"\xb0\x05\xc3\x9e\xd8\x27\x4a\x9d\xbf\xa8\x06\x71\x40\x94\x39\xd2";
SetKey;
}
static int key2(RSA *key, unsigned char *c)
{
static unsigned char n[] =
"\x00\xA3\x07\x9A\x90\xDF\x0D\xFD\x72\xAC\x09\x0C\xCC\x2A\x78\xB8"
"\x74\x13\x13\x3E\x40\x75\x9C\x98\xFA\xF8\x20\x4F\x35\x8A\x0B\x26"
"\x3C\x67\x70\xE7\x83\xA9\x3B\x69\x71\xB7\x37\x79\xD2\x71\x7B\xE8"
"\x34\x77\xCF";
static unsigned char e[] = "\x3";
static unsigned char d[] =
"\x6C\xAF\xBC\x60\x94\xB3\xFE\x4C\x72\xB0\xB3\x32\xC6\xFB\x25\xA2"
"\xB7\x62\x29\x80\x4E\x68\x65\xFC\xA4\x5A\x74\xDF\x0F\x8F\xB8\x41"
"\x3B\x52\xC0\xD0\xE5\x3D\x9B\x59\x0F\xF1\x9B\xE7\x9F\x49\xDD\x21"
"\xE5\xEB";
static unsigned char p[] =
"\x00\xCF\x20\x35\x02\x8B\x9D\x86\x98\x40\xB4\x16\x66\xB4\x2E\x92"
"\xEA\x0D\xA3\xB4\x32\x04\xB5\xCF\xCE\x91";
static unsigned char q[] =
"\x00\xC9\x7F\xB1\xF0\x27\xF4\x53\xF6\x34\x12\x33\xEA\xAA\xD1\xD9"
"\x35\x3F\x6C\x42\xD0\x88\x66\xB1\xD0\x5F";
static unsigned char dmp1[] =
"\x00\x8A\x15\x78\xAC\x5D\x13\xAF\x10\x2B\x22\xB9\x99\xCD\x74\x61"
"\xF1\x5E\x6D\x22\xCC\x03\x23\xDF\xDF\x0B";
static unsigned char dmq1[] =
"\x00\x86\x55\x21\x4A\xC5\x4D\x8D\x4E\xCD\x61\x77\xF1\xC7\x36\x90"
"\xCE\x2A\x48\x2C\x8B\x05\x99\xCB\xE0\x3F";
static unsigned char iqmp[] =
"\x00\x83\xEF\xEF\xB8\xA9\xA4\x0D\x1D\xB6\xED\x98\xAD\x84\xED\x13"
"\x35\xDC\xC1\x08\xF3\x22\xD0\x57\xCF\x8D";
static unsigned char ctext_ex[] =
"\x14\xbd\xdd\x28\xc9\x83\x35\x19\x23\x80\xe8\xe5\x49\xb1\x58\x2a"
"\x8b\x40\xb4\x48\x6d\x03\xa6\xa5\x31\x1f\x1f\xd5\xf0\xa1\x80\xe4"
"\x17\x53\x03\x29\xa9\x34\x90\x74\xb1\x52\x13\x54\x29\x08\x24\x52"
"\x62\x51";
SetKey;
}
static int key3(RSA *key, unsigned char *c)
{
static unsigned char n[] =
"\x00\xBB\xF8\x2F\x09\x06\x82\xCE\x9C\x23\x38\xAC\x2B\x9D\xA8\x71"
"\xF7\x36\x8D\x07\xEE\xD4\x10\x43\xA4\x40\xD6\xB6\xF0\x74\x54\xF5"
"\x1F\xB8\xDF\xBA\xAF\x03\x5C\x02\xAB\x61\xEA\x48\xCE\xEB\x6F\xCD"
"\x48\x76\xED\x52\x0D\x60\xE1\xEC\x46\x19\x71\x9D\x8A\x5B\x8B\x80"
"\x7F\xAF\xB8\xE0\xA3\xDF\xC7\x37\x72\x3E\xE6\xB4\xB7\xD9\x3A\x25"
"\x84\xEE\x6A\x64\x9D\x06\x09\x53\x74\x88\x34\xB2\x45\x45\x98\x39"
"\x4E\xE0\xAA\xB1\x2D\x7B\x61\xA5\x1F\x52\x7A\x9A\x41\xF6\xC1\x68"
"\x7F\xE2\x53\x72\x98\xCA\x2A\x8F\x59\x46\xF8\xE5\xFD\x09\x1D\xBD"
"\xCB";
static unsigned char e[] = "\x11";
static unsigned char d[] =
"\x00\xA5\xDA\xFC\x53\x41\xFA\xF2\x89\xC4\xB9\x88\xDB\x30\xC1\xCD"
"\xF8\x3F\x31\x25\x1E\x06\x68\xB4\x27\x84\x81\x38\x01\x57\x96\x41"
"\xB2\x94\x10\xB3\xC7\x99\x8D\x6B\xC4\x65\x74\x5E\x5C\x39\x26\x69"
"\xD6\x87\x0D\xA2\xC0\x82\xA9\x39\xE3\x7F\xDC\xB8\x2E\xC9\x3E\xDA"
"\xC9\x7F\xF3\xAD\x59\x50\xAC\xCF\xBC\x11\x1C\x76\xF1\xA9\x52\x94"
"\x44\xE5\x6A\xAF\x68\xC5\x6C\x09\x2C\xD3\x8D\xC3\xBE\xF5\xD2\x0A"
"\x93\x99\x26\xED\x4F\x74\xA1\x3E\xDD\xFB\xE1\xA1\xCE\xCC\x48\x94"
"\xAF\x94\x28\xC2\xB7\xB8\x88\x3F\xE4\x46\x3A\x4B\xC8\x5B\x1C\xB3"
"\xC1";
static unsigned char p[] =
"\x00\xEE\xCF\xAE\x81\xB1\xB9\xB3\xC9\x08\x81\x0B\x10\xA1\xB5\x60"
"\x01\x99\xEB\x9F\x44\xAE\xF4\xFD\xA4\x93\xB8\x1A\x9E\x3D\x84\xF6"
"\x32\x12\x4E\xF0\x23\x6E\x5D\x1E\x3B\x7E\x28\xFA\xE7\xAA\x04\x0A"
"\x2D\x5B\x25\x21\x76\x45\x9D\x1F\x39\x75\x41\xBA\x2A\x58\xFB\x65"
"\x99";
static unsigned char q[] =
"\x00\xC9\x7F\xB1\xF0\x27\xF4\x53\xF6\x34\x12\x33\xEA\xAA\xD1\xD9"
"\x35\x3F\x6C\x42\xD0\x88\x66\xB1\xD0\x5A\x0F\x20\x35\x02\x8B\x9D"
"\x86\x98\x40\xB4\x16\x66\xB4\x2E\x92\xEA\x0D\xA3\xB4\x32\x04\xB5"
"\xCF\xCE\x33\x52\x52\x4D\x04\x16\xA5\xA4\x41\xE7\x00\xAF\x46\x15"
"\x03";
static unsigned char dmp1[] =
"\x54\x49\x4C\xA6\x3E\xBA\x03\x37\xE4\xE2\x40\x23\xFC\xD6\x9A\x5A"
"\xEB\x07\xDD\xDC\x01\x83\xA4\xD0\xAC\x9B\x54\xB0\x51\xF2\xB1\x3E"
"\xD9\x49\x09\x75\xEA\xB7\x74\x14\xFF\x59\xC1\xF7\x69\x2E\x9A\x2E"
"\x20\x2B\x38\xFC\x91\x0A\x47\x41\x74\xAD\xC9\x3C\x1F\x67\xC9\x81";
static unsigned char dmq1[] =
"\x47\x1E\x02\x90\xFF\x0A\xF0\x75\x03\x51\xB7\xF8\x78\x86\x4C\xA9"
"\x61\xAD\xBD\x3A\x8A\x7E\x99\x1C\x5C\x05\x56\xA9\x4C\x31\x46\xA7"
"\xF9\x80\x3F\x8F\x6F\x8A\xE3\x42\xE9\x31\xFD\x8A\xE4\x7A\x22\x0D"
"\x1B\x99\xA4\x95\x84\x98\x07\xFE\x39\xF9\x24\x5A\x98\x36\xDA\x3D";
static unsigned char iqmp[] =
"\x00\xB0\x6C\x4F\xDA\xBB\x63\x01\x19\x8D\x26\x5B\xDB\xAE\x94\x23"
"\xB3\x80\xF2\x71\xF7\x34\x53\x88\x50\x93\x07\x7F\xCD\x39\xE2\x11"
"\x9F\xC9\x86\x32\x15\x4F\x58\x83\xB1\x67\xA9\x67\xBF\x40\x2B\x4E"
"\x9E\x2E\x0F\x96\x56\xE6\x98\xEA\x36\x66\xED\xFB\x25\x79\x80\x39"
"\xF7";
static unsigned char ctext_ex[] =
"\xb8\x24\x6b\x56\xa6\xed\x58\x81\xae\xb5\x85\xd9\xa2\x5b\x2a\xd7"
"\x90\xc4\x17\xe0\x80\x68\x1b\xf1\xac\x2b\xc3\xde\xb6\x9d\x8b\xce"
"\xf0\xc4\x36\x6f\xec\x40\x0a\xf0\x52\xa7\x2e\x9b\x0e\xff\xb5\xb3"
"\xf2\xf1\x92\xdb\xea\xca\x03\xc1\x27\x40\x05\x71\x13\xbf\x1f\x06"
"\x69\xac\x22\xe9\xf3\xa7\x85\x2e\x3c\x15\xd9\x13\xca\xb0\xb8\x86"
"\x3a\x95\xc9\x92\x94\xce\x86\x74\x21\x49\x54\x61\x03\x46\xf4\xd4"
"\x74\xb2\x6f\x7c\x48\xb4\x2e\xe6\x8e\x1f\x57\x2a\x1f\xc4\x02\x6a"
"\xc4\x56\xb4\xf5\x9f\x7b\x62\x1e\xa1\xb9\xd8\x8f\x64\x20\x2f\xb1";
SetKey;
}
static int pad_unknown(void)
{
unsigned long l;
while ((l = ERR_get_error()) != 0)
if (ERR_GET_REASON(l) == RSA_R_UNKNOWN_PADDING_TYPE)
return (1);
return (0);
}
static const char rnd_seed[] =
"string to make the random number generator think it has entropy";
int main(int argc, char *argv[])
{
int err = 0;
int v;
RSA *key;
unsigned char ptext[256];
unsigned char ctext[256];
static unsigned char ptext_ex[] = "\x54\x85\x9b\x34\x2c\x49\xea\x2a";
unsigned char ctext_ex[256];
int plen;
int clen = 0;
int num;
int n;
CRYPTO_malloc_debug_init();
CRYPTO_dbg_set_options(V_CRYPTO_MDEBUG_ALL);
CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON);
- RAND_seed(rnd_seed, sizeof rnd_seed); /* or OAEP may fail */
+ RAND_seed(rnd_seed, sizeof(rnd_seed)); /* or OAEP may fail */
plen = sizeof(ptext_ex) - 1;
for (v = 0; v < 6; v++) {
key = RSA_new();
switch (v % 3) {
case 0:
clen = key1(key, ctext_ex);
break;
case 1:
clen = key2(key, ctext_ex);
break;
case 2:
clen = key3(key, ctext_ex);
break;
}
if (v / 3 >= 1)
key->flags |= RSA_FLAG_NO_CONSTTIME;
num = RSA_public_encrypt(plen, ptext_ex, ctext, key,
RSA_PKCS1_PADDING);
if (num != clen) {
printf("PKCS#1 v1.5 encryption failed!\n");
err = 1;
goto oaep;
}
num = RSA_private_decrypt(num, ctext, ptext, key, RSA_PKCS1_PADDING);
if (num != plen || memcmp(ptext, ptext_ex, num) != 0) {
printf("PKCS#1 v1.5 decryption failed!\n");
err = 1;
} else
printf("PKCS #1 v1.5 encryption/decryption ok\n");
oaep:
ERR_clear_error();
num = RSA_public_encrypt(plen, ptext_ex, ctext, key,
RSA_PKCS1_OAEP_PADDING);
if (num == -1 && pad_unknown()) {
printf("No OAEP support\n");
goto next;
}
if (num != clen) {
printf("OAEP encryption failed!\n");
err = 1;
goto next;
}
num = RSA_private_decrypt(num, ctext, ptext, key,
RSA_PKCS1_OAEP_PADDING);
if (num != plen || memcmp(ptext, ptext_ex, num) != 0) {
printf("OAEP decryption (encrypted data) failed!\n");
err = 1;
} else if (memcmp(ctext, ctext_ex, num) == 0)
printf("OAEP test vector %d passed!\n", v);
/*
* Different ciphertexts (rsa_oaep.c without -DPKCS_TESTVECT). Try
* decrypting ctext_ex
*/
num = RSA_private_decrypt(clen, ctext_ex, ptext, key,
RSA_PKCS1_OAEP_PADDING);
if (num != plen || memcmp(ptext, ptext_ex, num) != 0) {
printf("OAEP decryption (test vector data) failed!\n");
err = 1;
} else
printf("OAEP encryption/decryption ok\n");
/* Try decrypting corrupted ciphertexts. */
for (n = 0; n < clen; ++n) {
ctext[n] ^= 1;
num = RSA_private_decrypt(clen, ctext, ptext, key,
RSA_PKCS1_OAEP_PADDING);
if (num > 0) {
printf("Corrupt data decrypted!\n");
err = 1;
break;
}
ctext[n] ^= 1;
}
/* Test truncated ciphertexts, as well as negative length. */
for (n = -1; n < clen; ++n) {
num = RSA_private_decrypt(n, ctext, ptext, key,
RSA_PKCS1_OAEP_PADDING);
if (num > 0) {
printf("Truncated data decrypted!\n");
err = 1;
break;
}
}
next:
RSA_free(key);
}
CRYPTO_cleanup_all_ex_data();
ERR_remove_thread_state(NULL);
CRYPTO_mem_leaks_fp(stderr);
# ifdef OPENSSL_SYS_NETWARE
if (err)
printf("ERROR: %d\n", err);
# endif
return err;
}
#endif
diff --git a/crypto/srp/srp_grps.h b/crypto/srp/srp_grps.h
index 31312de15c81..f76652cb8b9a 100644
--- a/crypto/srp/srp_grps.h
+++ b/crypto/srp/srp_grps.h
@@ -1,528 +1,528 @@
/* start of generated data */
static BN_ULONG bn_group_1024_value[] = {
bn_pack4(0x9FC6, 0x1D2F, 0xC0EB, 0x06E3),
bn_pack4(0xFD51, 0x38FE, 0x8376, 0x435B),
bn_pack4(0x2FD4, 0xCBF4, 0x976E, 0xAA9A),
bn_pack4(0x68ED, 0xBC3C, 0x0572, 0x6CC0),
bn_pack4(0xC529, 0xF566, 0x660E, 0x57EC),
bn_pack4(0x8255, 0x9B29, 0x7BCF, 0x1885),
bn_pack4(0xCE8E, 0xF4AD, 0x69B1, 0x5D49),
bn_pack4(0x5DC7, 0xD7B4, 0x6154, 0xD6B6),
bn_pack4(0x8E49, 0x5C1D, 0x6089, 0xDAD1),
bn_pack4(0xE0D5, 0xD8E2, 0x50B9, 0x8BE4),
bn_pack4(0x383B, 0x4813, 0xD692, 0xC6E0),
bn_pack4(0xD674, 0xDF74, 0x96EA, 0x81D3),
bn_pack4(0x9EA2, 0x314C, 0x9C25, 0x6576),
bn_pack4(0x6072, 0x6187, 0x75FF, 0x3C0B),
bn_pack4(0x9C33, 0xF80A, 0xFA8F, 0xC5E8),
bn_pack4(0xEEAF, 0x0AB9, 0xADB3, 0x8DD6)
};
static BIGNUM bn_group_1024 = {
bn_group_1024_value,
- (sizeof bn_group_1024_value) / sizeof(BN_ULONG),
- (sizeof bn_group_1024_value) / sizeof(BN_ULONG),
+ (sizeof(bn_group_1024_value)) / sizeof(BN_ULONG),
+ (sizeof(bn_group_1024_value)) / sizeof(BN_ULONG),
0,
BN_FLG_STATIC_DATA
};
static BN_ULONG bn_group_1536_value[] = {
bn_pack4(0xCF76, 0xE3FE, 0xD135, 0xF9BB),
bn_pack4(0x1518, 0x0F93, 0x499A, 0x234D),
bn_pack4(0x8CE7, 0xA28C, 0x2442, 0xC6F3),
bn_pack4(0x5A02, 0x1FFF, 0x5E91, 0x479E),
bn_pack4(0x7F8A, 0x2FE9, 0xB8B5, 0x292E),
bn_pack4(0x837C, 0x264A, 0xE3A9, 0xBEB8),
bn_pack4(0xE442, 0x734A, 0xF7CC, 0xB7AE),
bn_pack4(0x6577, 0x2E43, 0x7D6C, 0x7F8C),
bn_pack4(0xDB2F, 0xD53D, 0x24B7, 0xC486),
bn_pack4(0x6EDF, 0x0195, 0x3934, 0x9627),
bn_pack4(0x158B, 0xFD3E, 0x2B9C, 0x8CF5),
bn_pack4(0x764E, 0x3F4B, 0x53DD, 0x9DA1),
bn_pack4(0x4754, 0x8381, 0xDBC5, 0xB1FC),
bn_pack4(0x9B60, 0x9E0B, 0xE3BA, 0xB63D),
bn_pack4(0x8134, 0xB1C8, 0xB979, 0x8914),
bn_pack4(0xDF02, 0x8A7C, 0xEC67, 0xF0D0),
bn_pack4(0x80B6, 0x55BB, 0x9A22, 0xE8DC),
bn_pack4(0x1558, 0x903B, 0xA0D0, 0xF843),
bn_pack4(0x51C6, 0xA94B, 0xE460, 0x7A29),
bn_pack4(0x5F4F, 0x5F55, 0x6E27, 0xCBDE),
bn_pack4(0xBEEE, 0xA961, 0x4B19, 0xCC4D),
bn_pack4(0xDBA5, 0x1DF4, 0x99AC, 0x4C80),
bn_pack4(0xB1F1, 0x2A86, 0x17A4, 0x7BBB),
bn_pack4(0x9DEF, 0x3CAF, 0xB939, 0x277A)
};
static BIGNUM bn_group_1536 = {
bn_group_1536_value,
- (sizeof bn_group_1536_value) / sizeof(BN_ULONG),
- (sizeof bn_group_1536_value) / sizeof(BN_ULONG),
+ (sizeof(bn_group_1536_value)) / sizeof(BN_ULONG),
+ (sizeof(bn_group_1536_value)) / sizeof(BN_ULONG),
0,
BN_FLG_STATIC_DATA
};
static BN_ULONG bn_group_2048_value[] = {
bn_pack4(0x0FA7, 0x111F, 0x9E4A, 0xFF73),
bn_pack4(0x9B65, 0xE372, 0xFCD6, 0x8EF2),
bn_pack4(0x35DE, 0x236D, 0x525F, 0x5475),
bn_pack4(0x94B5, 0xC803, 0xD89F, 0x7AE4),
bn_pack4(0x71AE, 0x35F8, 0xE9DB, 0xFBB6),
bn_pack4(0x2A56, 0x98F3, 0xA8D0, 0xC382),
bn_pack4(0x9CCC, 0x041C, 0x7BC3, 0x08D8),
bn_pack4(0xAF87, 0x4E73, 0x03CE, 0x5329),
bn_pack4(0x6160, 0x2790, 0x04E5, 0x7AE6),
bn_pack4(0x032C, 0xFBDB, 0xF52F, 0xB378),
bn_pack4(0x5EA7, 0x7A27, 0x75D2, 0xECFA),
bn_pack4(0x5445, 0x23B5, 0x24B0, 0xD57D),
bn_pack4(0x5B9D, 0x32E6, 0x88F8, 0x7748),
bn_pack4(0xF1D2, 0xB907, 0x8717, 0x461A),
bn_pack4(0x76BD, 0x207A, 0x436C, 0x6481),
bn_pack4(0xCA97, 0xB43A, 0x23FB, 0x8016),
bn_pack4(0x1D28, 0x1E44, 0x6B14, 0x773B),
bn_pack4(0x7359, 0xD041, 0xD5C3, 0x3EA7),
bn_pack4(0xA80D, 0x740A, 0xDBF4, 0xFF74),
bn_pack4(0x55F9, 0x7993, 0xEC97, 0x5EEA),
bn_pack4(0x2918, 0xA996, 0x2F0B, 0x93B8),
bn_pack4(0x661A, 0x05FB, 0xD5FA, 0xAAE8),
bn_pack4(0xCF60, 0x9517, 0x9A16, 0x3AB3),
bn_pack4(0xE808, 0x3969, 0xEDB7, 0x67B0),
bn_pack4(0xCD7F, 0x48A9, 0xDA04, 0xFD50),
bn_pack4(0xD523, 0x12AB, 0x4B03, 0x310D),
bn_pack4(0x8193, 0xE075, 0x7767, 0xA13D),
bn_pack4(0xA373, 0x29CB, 0xB4A0, 0x99ED),
bn_pack4(0xFC31, 0x9294, 0x3DB5, 0x6050),
bn_pack4(0xAF72, 0xB665, 0x1987, 0xEE07),
bn_pack4(0xF166, 0xDE5E, 0x1389, 0x582F),
bn_pack4(0xAC6B, 0xDB41, 0x324A, 0x9A9B)
};
static BIGNUM bn_group_2048 = {
bn_group_2048_value,
- (sizeof bn_group_2048_value) / sizeof(BN_ULONG),
- (sizeof bn_group_2048_value) / sizeof(BN_ULONG),
+ (sizeof(bn_group_2048_value)) / sizeof(BN_ULONG),
+ (sizeof(bn_group_2048_value)) / sizeof(BN_ULONG),
0,
BN_FLG_STATIC_DATA
};
static BN_ULONG bn_group_3072_value[] = {
bn_pack4(0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF),
bn_pack4(0x4B82, 0xD120, 0xA93A, 0xD2CA),
bn_pack4(0x43DB, 0x5BFC, 0xE0FD, 0x108E),
bn_pack4(0x08E2, 0x4FA0, 0x74E5, 0xAB31),
bn_pack4(0x7709, 0x88C0, 0xBAD9, 0x46E2),
bn_pack4(0xBBE1, 0x1757, 0x7A61, 0x5D6C),
bn_pack4(0x521F, 0x2B18, 0x177B, 0x200C),
bn_pack4(0xD876, 0x0273, 0x3EC8, 0x6A64),
bn_pack4(0xF12F, 0xFA06, 0xD98A, 0x0864),
bn_pack4(0xCEE3, 0xD226, 0x1AD2, 0xEE6B),
bn_pack4(0x1E8C, 0x94E0, 0x4A25, 0x619D),
bn_pack4(0xABF5, 0xAE8C, 0xDB09, 0x33D7),
bn_pack4(0xB397, 0x0F85, 0xA6E1, 0xE4C7),
bn_pack4(0x8AEA, 0x7157, 0x5D06, 0x0C7D),
bn_pack4(0xECFB, 0x8504, 0x58DB, 0xEF0A),
bn_pack4(0xA855, 0x21AB, 0xDF1C, 0xBA64),
bn_pack4(0xAD33, 0x170D, 0x0450, 0x7A33),
bn_pack4(0x1572, 0x8E5A, 0x8AAA, 0xC42D),
bn_pack4(0x15D2, 0x2618, 0x98FA, 0x0510),
bn_pack4(0x3995, 0x497C, 0xEA95, 0x6AE5),
bn_pack4(0xDE2B, 0xCBF6, 0x9558, 0x1718),
bn_pack4(0xB5C5, 0x5DF0, 0x6F4C, 0x52C9),
bn_pack4(0x9B27, 0x83A2, 0xEC07, 0xA28F),
bn_pack4(0xE39E, 0x772C, 0x180E, 0x8603),
bn_pack4(0x3290, 0x5E46, 0x2E36, 0xCE3B),
bn_pack4(0xF174, 0x6C08, 0xCA18, 0x217C),
bn_pack4(0x670C, 0x354E, 0x4ABC, 0x9804),
bn_pack4(0x9ED5, 0x2907, 0x7096, 0x966D),
bn_pack4(0x1C62, 0xF356, 0x2085, 0x52BB),
bn_pack4(0x8365, 0x5D23, 0xDCA3, 0xAD96),
bn_pack4(0x6916, 0x3FA8, 0xFD24, 0xCF5F),
bn_pack4(0x98DA, 0x4836, 0x1C55, 0xD39A),
bn_pack4(0xC200, 0x7CB8, 0xA163, 0xBF05),
bn_pack4(0x4928, 0x6651, 0xECE4, 0x5B3D),
bn_pack4(0xAE9F, 0x2411, 0x7C4B, 0x1FE6),
bn_pack4(0xEE38, 0x6BFB, 0x5A89, 0x9FA5),
bn_pack4(0x0BFF, 0x5CB6, 0xF406, 0xB7ED),
bn_pack4(0xF44C, 0x42E9, 0xA637, 0xED6B),
bn_pack4(0xE485, 0xB576, 0x625E, 0x7EC6),
bn_pack4(0x4FE1, 0x356D, 0x6D51, 0xC245),
bn_pack4(0x302B, 0x0A6D, 0xF25F, 0x1437),
bn_pack4(0xEF95, 0x19B3, 0xCD3A, 0x431B),
bn_pack4(0x514A, 0x0879, 0x8E34, 0x04DD),
bn_pack4(0x020B, 0xBEA6, 0x3B13, 0x9B22),
bn_pack4(0x2902, 0x4E08, 0x8A67, 0xCC74),
bn_pack4(0xC4C6, 0x628B, 0x80DC, 0x1CD1),
bn_pack4(0xC90F, 0xDAA2, 0x2168, 0xC234),
bn_pack4(0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF)
};
static BIGNUM bn_group_3072 = {
bn_group_3072_value,
- (sizeof bn_group_3072_value) / sizeof(BN_ULONG),
- (sizeof bn_group_3072_value) / sizeof(BN_ULONG),
+ (sizeof(bn_group_3072_value)) / sizeof(BN_ULONG),
+ (sizeof(bn_group_3072_value)) / sizeof(BN_ULONG),
0,
BN_FLG_STATIC_DATA
};
static BN_ULONG bn_group_4096_value[] = {
bn_pack4(0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF),
bn_pack4(0x4DF4, 0x35C9, 0x3406, 0x3199),
bn_pack4(0x86FF, 0xB7DC, 0x90A6, 0xC08F),
bn_pack4(0x93B4, 0xEA98, 0x8D8F, 0xDDC1),
bn_pack4(0xD006, 0x9127, 0xD5B0, 0x5AA9),
bn_pack4(0xB81B, 0xDD76, 0x2170, 0x481C),
bn_pack4(0x1F61, 0x2970, 0xCEE2, 0xD7AF),
bn_pack4(0x233B, 0xA186, 0x515B, 0xE7ED),
bn_pack4(0x99B2, 0x964F, 0xA090, 0xC3A2),
bn_pack4(0x287C, 0x5947, 0x4E6B, 0xC05D),
bn_pack4(0x2E8E, 0xFC14, 0x1FBE, 0xCAA6),
bn_pack4(0xDBBB, 0xC2DB, 0x04DE, 0x8EF9),
bn_pack4(0x2583, 0xE9CA, 0x2AD4, 0x4CE8),
bn_pack4(0x1A94, 0x6834, 0xB615, 0x0BDA),
bn_pack4(0x99C3, 0x2718, 0x6AF4, 0xE23C),
bn_pack4(0x8871, 0x9A10, 0xBDBA, 0x5B26),
bn_pack4(0x1A72, 0x3C12, 0xA787, 0xE6D7),
bn_pack4(0x4B82, 0xD120, 0xA921, 0x0801),
bn_pack4(0x43DB, 0x5BFC, 0xE0FD, 0x108E),
bn_pack4(0x08E2, 0x4FA0, 0x74E5, 0xAB31),
bn_pack4(0x7709, 0x88C0, 0xBAD9, 0x46E2),
bn_pack4(0xBBE1, 0x1757, 0x7A61, 0x5D6C),
bn_pack4(0x521F, 0x2B18, 0x177B, 0x200C),
bn_pack4(0xD876, 0x0273, 0x3EC8, 0x6A64),
bn_pack4(0xF12F, 0xFA06, 0xD98A, 0x0864),
bn_pack4(0xCEE3, 0xD226, 0x1AD2, 0xEE6B),
bn_pack4(0x1E8C, 0x94E0, 0x4A25, 0x619D),
bn_pack4(0xABF5, 0xAE8C, 0xDB09, 0x33D7),
bn_pack4(0xB397, 0x0F85, 0xA6E1, 0xE4C7),
bn_pack4(0x8AEA, 0x7157, 0x5D06, 0x0C7D),
bn_pack4(0xECFB, 0x8504, 0x58DB, 0xEF0A),
bn_pack4(0xA855, 0x21AB, 0xDF1C, 0xBA64),
bn_pack4(0xAD33, 0x170D, 0x0450, 0x7A33),
bn_pack4(0x1572, 0x8E5A, 0x8AAA, 0xC42D),
bn_pack4(0x15D2, 0x2618, 0x98FA, 0x0510),
bn_pack4(0x3995, 0x497C, 0xEA95, 0x6AE5),
bn_pack4(0xDE2B, 0xCBF6, 0x9558, 0x1718),
bn_pack4(0xB5C5, 0x5DF0, 0x6F4C, 0x52C9),
bn_pack4(0x9B27, 0x83A2, 0xEC07, 0xA28F),
bn_pack4(0xE39E, 0x772C, 0x180E, 0x8603),
bn_pack4(0x3290, 0x5E46, 0x2E36, 0xCE3B),
bn_pack4(0xF174, 0x6C08, 0xCA18, 0x217C),
bn_pack4(0x670C, 0x354E, 0x4ABC, 0x9804),
bn_pack4(0x9ED5, 0x2907, 0x7096, 0x966D),
bn_pack4(0x1C62, 0xF356, 0x2085, 0x52BB),
bn_pack4(0x8365, 0x5D23, 0xDCA3, 0xAD96),
bn_pack4(0x6916, 0x3FA8, 0xFD24, 0xCF5F),
bn_pack4(0x98DA, 0x4836, 0x1C55, 0xD39A),
bn_pack4(0xC200, 0x7CB8, 0xA163, 0xBF05),
bn_pack4(0x4928, 0x6651, 0xECE4, 0x5B3D),
bn_pack4(0xAE9F, 0x2411, 0x7C4B, 0x1FE6),
bn_pack4(0xEE38, 0x6BFB, 0x5A89, 0x9FA5),
bn_pack4(0x0BFF, 0x5CB6, 0xF406, 0xB7ED),
bn_pack4(0xF44C, 0x42E9, 0xA637, 0xED6B),
bn_pack4(0xE485, 0xB576, 0x625E, 0x7EC6),
bn_pack4(0x4FE1, 0x356D, 0x6D51, 0xC245),
bn_pack4(0x302B, 0x0A6D, 0xF25F, 0x1437),
bn_pack4(0xEF95, 0x19B3, 0xCD3A, 0x431B),
bn_pack4(0x514A, 0x0879, 0x8E34, 0x04DD),
bn_pack4(0x020B, 0xBEA6, 0x3B13, 0x9B22),
bn_pack4(0x2902, 0x4E08, 0x8A67, 0xCC74),
bn_pack4(0xC4C6, 0x628B, 0x80DC, 0x1CD1),
bn_pack4(0xC90F, 0xDAA2, 0x2168, 0xC234),
bn_pack4(0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF)
};
static BIGNUM bn_group_4096 = {
bn_group_4096_value,
- (sizeof bn_group_4096_value) / sizeof(BN_ULONG),
- (sizeof bn_group_4096_value) / sizeof(BN_ULONG),
+ (sizeof(bn_group_4096_value)) / sizeof(BN_ULONG),
+ (sizeof(bn_group_4096_value)) / sizeof(BN_ULONG),
0,
BN_FLG_STATIC_DATA
};
static BN_ULONG bn_group_6144_value[] = {
bn_pack4(0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF),
bn_pack4(0xE694, 0xF91E, 0x6DCC, 0x4024),
bn_pack4(0x12BF, 0x2D5B, 0x0B74, 0x74D6),
bn_pack4(0x043E, 0x8F66, 0x3F48, 0x60EE),
bn_pack4(0x387F, 0xE8D7, 0x6E3C, 0x0468),
bn_pack4(0xDA56, 0xC9EC, 0x2EF2, 0x9632),
bn_pack4(0xEB19, 0xCCB1, 0xA313, 0xD55C),
bn_pack4(0xF550, 0xAA3D, 0x8A1F, 0xBFF0),
bn_pack4(0x06A1, 0xD58B, 0xB7C5, 0xDA76),
bn_pack4(0xA797, 0x15EE, 0xF29B, 0xE328),
bn_pack4(0x14CC, 0x5ED2, 0x0F80, 0x37E0),
bn_pack4(0xCC8F, 0x6D7E, 0xBF48, 0xE1D8),
bn_pack4(0x4BD4, 0x07B2, 0x2B41, 0x54AA),
bn_pack4(0x0F1D, 0x45B7, 0xFF58, 0x5AC5),
bn_pack4(0x23A9, 0x7A7E, 0x36CC, 0x88BE),
bn_pack4(0x59E7, 0xC97F, 0xBEC7, 0xE8F3),
bn_pack4(0xB5A8, 0x4031, 0x900B, 0x1C9E),
bn_pack4(0xD55E, 0x702F, 0x4698, 0x0C82),
bn_pack4(0xF482, 0xD7CE, 0x6E74, 0xFEF6),
bn_pack4(0xF032, 0xEA15, 0xD172, 0x1D03),
bn_pack4(0x5983, 0xCA01, 0xC64B, 0x92EC),
bn_pack4(0x6FB8, 0xF401, 0x378C, 0xD2BF),
bn_pack4(0x3320, 0x5151, 0x2BD7, 0xAF42),
bn_pack4(0xDB7F, 0x1447, 0xE6CC, 0x254B),
bn_pack4(0x44CE, 0x6CBA, 0xCED4, 0xBB1B),
bn_pack4(0xDA3E, 0xDBEB, 0xCF9B, 0x14ED),
bn_pack4(0x1797, 0x27B0, 0x865A, 0x8918),
bn_pack4(0xB06A, 0x53ED, 0x9027, 0xD831),
bn_pack4(0xE5DB, 0x382F, 0x4130, 0x01AE),
bn_pack4(0xF8FF, 0x9406, 0xAD9E, 0x530E),
bn_pack4(0xC975, 0x1E76, 0x3DBA, 0x37BD),
bn_pack4(0xC1D4, 0xDCB2, 0x6026, 0x46DE),
bn_pack4(0x36C3, 0xFAB4, 0xD27C, 0x7026),
bn_pack4(0x4DF4, 0x35C9, 0x3402, 0x8492),
bn_pack4(0x86FF, 0xB7DC, 0x90A6, 0xC08F),
bn_pack4(0x93B4, 0xEA98, 0x8D8F, 0xDDC1),
bn_pack4(0xD006, 0x9127, 0xD5B0, 0x5AA9),
bn_pack4(0xB81B, 0xDD76, 0x2170, 0x481C),
bn_pack4(0x1F61, 0x2970, 0xCEE2, 0xD7AF),
bn_pack4(0x233B, 0xA186, 0x515B, 0xE7ED),
bn_pack4(0x99B2, 0x964F, 0xA090, 0xC3A2),
bn_pack4(0x287C, 0x5947, 0x4E6B, 0xC05D),
bn_pack4(0x2E8E, 0xFC14, 0x1FBE, 0xCAA6),
bn_pack4(0xDBBB, 0xC2DB, 0x04DE, 0x8EF9),
bn_pack4(0x2583, 0xE9CA, 0x2AD4, 0x4CE8),
bn_pack4(0x1A94, 0x6834, 0xB615, 0x0BDA),
bn_pack4(0x99C3, 0x2718, 0x6AF4, 0xE23C),
bn_pack4(0x8871, 0x9A10, 0xBDBA, 0x5B26),
bn_pack4(0x1A72, 0x3C12, 0xA787, 0xE6D7),
bn_pack4(0x4B82, 0xD120, 0xA921, 0x0801),
bn_pack4(0x43DB, 0x5BFC, 0xE0FD, 0x108E),
bn_pack4(0x08E2, 0x4FA0, 0x74E5, 0xAB31),
bn_pack4(0x7709, 0x88C0, 0xBAD9, 0x46E2),
bn_pack4(0xBBE1, 0x1757, 0x7A61, 0x5D6C),
bn_pack4(0x521F, 0x2B18, 0x177B, 0x200C),
bn_pack4(0xD876, 0x0273, 0x3EC8, 0x6A64),
bn_pack4(0xF12F, 0xFA06, 0xD98A, 0x0864),
bn_pack4(0xCEE3, 0xD226, 0x1AD2, 0xEE6B),
bn_pack4(0x1E8C, 0x94E0, 0x4A25, 0x619D),
bn_pack4(0xABF5, 0xAE8C, 0xDB09, 0x33D7),
bn_pack4(0xB397, 0x0F85, 0xA6E1, 0xE4C7),
bn_pack4(0x8AEA, 0x7157, 0x5D06, 0x0C7D),
bn_pack4(0xECFB, 0x8504, 0x58DB, 0xEF0A),
bn_pack4(0xA855, 0x21AB, 0xDF1C, 0xBA64),
bn_pack4(0xAD33, 0x170D, 0x0450, 0x7A33),
bn_pack4(0x1572, 0x8E5A, 0x8AAA, 0xC42D),
bn_pack4(0x15D2, 0x2618, 0x98FA, 0x0510),
bn_pack4(0x3995, 0x497C, 0xEA95, 0x6AE5),
bn_pack4(0xDE2B, 0xCBF6, 0x9558, 0x1718),
bn_pack4(0xB5C5, 0x5DF0, 0x6F4C, 0x52C9),
bn_pack4(0x9B27, 0x83A2, 0xEC07, 0xA28F),
bn_pack4(0xE39E, 0x772C, 0x180E, 0x8603),
bn_pack4(0x3290, 0x5E46, 0x2E36, 0xCE3B),
bn_pack4(0xF174, 0x6C08, 0xCA18, 0x217C),
bn_pack4(0x670C, 0x354E, 0x4ABC, 0x9804),
bn_pack4(0x9ED5, 0x2907, 0x7096, 0x966D),
bn_pack4(0x1C62, 0xF356, 0x2085, 0x52BB),
bn_pack4(0x8365, 0x5D23, 0xDCA3, 0xAD96),
bn_pack4(0x6916, 0x3FA8, 0xFD24, 0xCF5F),
bn_pack4(0x98DA, 0x4836, 0x1C55, 0xD39A),
bn_pack4(0xC200, 0x7CB8, 0xA163, 0xBF05),
bn_pack4(0x4928, 0x6651, 0xECE4, 0x5B3D),
bn_pack4(0xAE9F, 0x2411, 0x7C4B, 0x1FE6),
bn_pack4(0xEE38, 0x6BFB, 0x5A89, 0x9FA5),
bn_pack4(0x0BFF, 0x5CB6, 0xF406, 0xB7ED),
bn_pack4(0xF44C, 0x42E9, 0xA637, 0xED6B),
bn_pack4(0xE485, 0xB576, 0x625E, 0x7EC6),
bn_pack4(0x4FE1, 0x356D, 0x6D51, 0xC245),
bn_pack4(0x302B, 0x0A6D, 0xF25F, 0x1437),
bn_pack4(0xEF95, 0x19B3, 0xCD3A, 0x431B),
bn_pack4(0x514A, 0x0879, 0x8E34, 0x04DD),
bn_pack4(0x020B, 0xBEA6, 0x3B13, 0x9B22),
bn_pack4(0x2902, 0x4E08, 0x8A67, 0xCC74),
bn_pack4(0xC4C6, 0x628B, 0x80DC, 0x1CD1),
bn_pack4(0xC90F, 0xDAA2, 0x2168, 0xC234),
bn_pack4(0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF)
};
static BIGNUM bn_group_6144 = {
bn_group_6144_value,
- (sizeof bn_group_6144_value) / sizeof(BN_ULONG),
- (sizeof bn_group_6144_value) / sizeof(BN_ULONG),
+ (sizeof(bn_group_6144_value)) / sizeof(BN_ULONG),
+ (sizeof(bn_group_6144_value)) / sizeof(BN_ULONG),
0,
BN_FLG_STATIC_DATA
};
static BN_ULONG bn_group_8192_value[] = {
bn_pack4(0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF),
bn_pack4(0x60C9, 0x80DD, 0x98ED, 0xD3DF),
bn_pack4(0xC81F, 0x56E8, 0x80B9, 0x6E71),
bn_pack4(0x9E30, 0x50E2, 0x7656, 0x94DF),
bn_pack4(0x9558, 0xE447, 0x5677, 0xE9AA),
bn_pack4(0xC919, 0x0DA6, 0xFC02, 0x6E47),
bn_pack4(0x889A, 0x002E, 0xD5EE, 0x382B),
bn_pack4(0x4009, 0x438B, 0x481C, 0x6CD7),
bn_pack4(0x3590, 0x46F4, 0xEB87, 0x9F92),
bn_pack4(0xFAF3, 0x6BC3, 0x1ECF, 0xA268),
bn_pack4(0xB1D5, 0x10BD, 0x7EE7, 0x4D73),
bn_pack4(0xF9AB, 0x4819, 0x5DED, 0x7EA1),
bn_pack4(0x64F3, 0x1CC5, 0x0846, 0x851D),
bn_pack4(0x4597, 0xE899, 0xA025, 0x5DC1),
bn_pack4(0xDF31, 0x0EE0, 0x74AB, 0x6A36),
bn_pack4(0x6D2A, 0x13F8, 0x3F44, 0xF82D),
bn_pack4(0x062B, 0x3CF5, 0xB3A2, 0x78A6),
bn_pack4(0x7968, 0x3303, 0xED5B, 0xDD3A),
bn_pack4(0xFA9D, 0x4B7F, 0xA2C0, 0x87E8),
bn_pack4(0x4BCB, 0xC886, 0x2F83, 0x85DD),
bn_pack4(0x3473, 0xFC64, 0x6CEA, 0x306B),
bn_pack4(0x13EB, 0x57A8, 0x1A23, 0xF0C7),
bn_pack4(0x2222, 0x2E04, 0xA403, 0x7C07),
bn_pack4(0xE3FD, 0xB8BE, 0xFC84, 0x8AD9),
bn_pack4(0x238F, 0x16CB, 0xE39D, 0x652D),
bn_pack4(0x3423, 0xB474, 0x2BF1, 0xC978),
bn_pack4(0x3AAB, 0x639C, 0x5AE4, 0xF568),
bn_pack4(0x2576, 0xF693, 0x6BA4, 0x2466),
bn_pack4(0x741F, 0xA7BF, 0x8AFC, 0x47ED),
bn_pack4(0x3BC8, 0x32B6, 0x8D9D, 0xD300),
bn_pack4(0xD8BE, 0xC4D0, 0x73B9, 0x31BA),
bn_pack4(0x3877, 0x7CB6, 0xA932, 0xDF8C),
bn_pack4(0x74A3, 0x926F, 0x12FE, 0xE5E4),
bn_pack4(0xE694, 0xF91E, 0x6DBE, 0x1159),
bn_pack4(0x12BF, 0x2D5B, 0x0B74, 0x74D6),
bn_pack4(0x043E, 0x8F66, 0x3F48, 0x60EE),
bn_pack4(0x387F, 0xE8D7, 0x6E3C, 0x0468),
bn_pack4(0xDA56, 0xC9EC, 0x2EF2, 0x9632),
bn_pack4(0xEB19, 0xCCB1, 0xA313, 0xD55C),
bn_pack4(0xF550, 0xAA3D, 0x8A1F, 0xBFF0),
bn_pack4(0x06A1, 0xD58B, 0xB7C5, 0xDA76),
bn_pack4(0xA797, 0x15EE, 0xF29B, 0xE328),
bn_pack4(0x14CC, 0x5ED2, 0x0F80, 0x37E0),
bn_pack4(0xCC8F, 0x6D7E, 0xBF48, 0xE1D8),
bn_pack4(0x4BD4, 0x07B2, 0x2B41, 0x54AA),
bn_pack4(0x0F1D, 0x45B7, 0xFF58, 0x5AC5),
bn_pack4(0x23A9, 0x7A7E, 0x36CC, 0x88BE),
bn_pack4(0x59E7, 0xC97F, 0xBEC7, 0xE8F3),
bn_pack4(0xB5A8, 0x4031, 0x900B, 0x1C9E),
bn_pack4(0xD55E, 0x702F, 0x4698, 0x0C82),
bn_pack4(0xF482, 0xD7CE, 0x6E74, 0xFEF6),
bn_pack4(0xF032, 0xEA15, 0xD172, 0x1D03),
bn_pack4(0x5983, 0xCA01, 0xC64B, 0x92EC),
bn_pack4(0x6FB8, 0xF401, 0x378C, 0xD2BF),
bn_pack4(0x3320, 0x5151, 0x2BD7, 0xAF42),
bn_pack4(0xDB7F, 0x1447, 0xE6CC, 0x254B),
bn_pack4(0x44CE, 0x6CBA, 0xCED4, 0xBB1B),
bn_pack4(0xDA3E, 0xDBEB, 0xCF9B, 0x14ED),
bn_pack4(0x1797, 0x27B0, 0x865A, 0x8918),
bn_pack4(0xB06A, 0x53ED, 0x9027, 0xD831),
bn_pack4(0xE5DB, 0x382F, 0x4130, 0x01AE),
bn_pack4(0xF8FF, 0x9406, 0xAD9E, 0x530E),
bn_pack4(0xC975, 0x1E76, 0x3DBA, 0x37BD),
bn_pack4(0xC1D4, 0xDCB2, 0x6026, 0x46DE),
bn_pack4(0x36C3, 0xFAB4, 0xD27C, 0x7026),
bn_pack4(0x4DF4, 0x35C9, 0x3402, 0x8492),
bn_pack4(0x86FF, 0xB7DC, 0x90A6, 0xC08F),
bn_pack4(0x93B4, 0xEA98, 0x8D8F, 0xDDC1),
bn_pack4(0xD006, 0x9127, 0xD5B0, 0x5AA9),
bn_pack4(0xB81B, 0xDD76, 0x2170, 0x481C),
bn_pack4(0x1F61, 0x2970, 0xCEE2, 0xD7AF),
bn_pack4(0x233B, 0xA186, 0x515B, 0xE7ED),
bn_pack4(0x99B2, 0x964F, 0xA090, 0xC3A2),
bn_pack4(0x287C, 0x5947, 0x4E6B, 0xC05D),
bn_pack4(0x2E8E, 0xFC14, 0x1FBE, 0xCAA6),
bn_pack4(0xDBBB, 0xC2DB, 0x04DE, 0x8EF9),
bn_pack4(0x2583, 0xE9CA, 0x2AD4, 0x4CE8),
bn_pack4(0x1A94, 0x6834, 0xB615, 0x0BDA),
bn_pack4(0x99C3, 0x2718, 0x6AF4, 0xE23C),
bn_pack4(0x8871, 0x9A10, 0xBDBA, 0x5B26),
bn_pack4(0x1A72, 0x3C12, 0xA787, 0xE6D7),
bn_pack4(0x4B82, 0xD120, 0xA921, 0x0801),
bn_pack4(0x43DB, 0x5BFC, 0xE0FD, 0x108E),
bn_pack4(0x08E2, 0x4FA0, 0x74E5, 0xAB31),
bn_pack4(0x7709, 0x88C0, 0xBAD9, 0x46E2),
bn_pack4(0xBBE1, 0x1757, 0x7A61, 0x5D6C),
bn_pack4(0x521F, 0x2B18, 0x177B, 0x200C),
bn_pack4(0xD876, 0x0273, 0x3EC8, 0x6A64),
bn_pack4(0xF12F, 0xFA06, 0xD98A, 0x0864),
bn_pack4(0xCEE3, 0xD226, 0x1AD2, 0xEE6B),
bn_pack4(0x1E8C, 0x94E0, 0x4A25, 0x619D),
bn_pack4(0xABF5, 0xAE8C, 0xDB09, 0x33D7),
bn_pack4(0xB397, 0x0F85, 0xA6E1, 0xE4C7),
bn_pack4(0x8AEA, 0x7157, 0x5D06, 0x0C7D),
bn_pack4(0xECFB, 0x8504, 0x58DB, 0xEF0A),
bn_pack4(0xA855, 0x21AB, 0xDF1C, 0xBA64),
bn_pack4(0xAD33, 0x170D, 0x0450, 0x7A33),
bn_pack4(0x1572, 0x8E5A, 0x8AAA, 0xC42D),
bn_pack4(0x15D2, 0x2618, 0x98FA, 0x0510),
bn_pack4(0x3995, 0x497C, 0xEA95, 0x6AE5),
bn_pack4(0xDE2B, 0xCBF6, 0x9558, 0x1718),
bn_pack4(0xB5C5, 0x5DF0, 0x6F4C, 0x52C9),
bn_pack4(0x9B27, 0x83A2, 0xEC07, 0xA28F),
bn_pack4(0xE39E, 0x772C, 0x180E, 0x8603),
bn_pack4(0x3290, 0x5E46, 0x2E36, 0xCE3B),
bn_pack4(0xF174, 0x6C08, 0xCA18, 0x217C),
bn_pack4(0x670C, 0x354E, 0x4ABC, 0x9804),
bn_pack4(0x9ED5, 0x2907, 0x7096, 0x966D),
bn_pack4(0x1C62, 0xF356, 0x2085, 0x52BB),
bn_pack4(0x8365, 0x5D23, 0xDCA3, 0xAD96),
bn_pack4(0x6916, 0x3FA8, 0xFD24, 0xCF5F),
bn_pack4(0x98DA, 0x4836, 0x1C55, 0xD39A),
bn_pack4(0xC200, 0x7CB8, 0xA163, 0xBF05),
bn_pack4(0x4928, 0x6651, 0xECE4, 0x5B3D),
bn_pack4(0xAE9F, 0x2411, 0x7C4B, 0x1FE6),
bn_pack4(0xEE38, 0x6BFB, 0x5A89, 0x9FA5),
bn_pack4(0x0BFF, 0x5CB6, 0xF406, 0xB7ED),
bn_pack4(0xF44C, 0x42E9, 0xA637, 0xED6B),
bn_pack4(0xE485, 0xB576, 0x625E, 0x7EC6),
bn_pack4(0x4FE1, 0x356D, 0x6D51, 0xC245),
bn_pack4(0x302B, 0x0A6D, 0xF25F, 0x1437),
bn_pack4(0xEF95, 0x19B3, 0xCD3A, 0x431B),
bn_pack4(0x514A, 0x0879, 0x8E34, 0x04DD),
bn_pack4(0x020B, 0xBEA6, 0x3B13, 0x9B22),
bn_pack4(0x2902, 0x4E08, 0x8A67, 0xCC74),
bn_pack4(0xC4C6, 0x628B, 0x80DC, 0x1CD1),
bn_pack4(0xC90F, 0xDAA2, 0x2168, 0xC234),
bn_pack4(0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF)
};
static BIGNUM bn_group_8192 = {
bn_group_8192_value,
- (sizeof bn_group_8192_value) / sizeof(BN_ULONG),
- (sizeof bn_group_8192_value) / sizeof(BN_ULONG),
+ (sizeof(bn_group_8192_value)) / sizeof(BN_ULONG),
+ (sizeof(bn_group_8192_value)) / sizeof(BN_ULONG),
0,
BN_FLG_STATIC_DATA
};
static BN_ULONG bn_generator_19_value[] = { 19 };
static BIGNUM bn_generator_19 = {
bn_generator_19_value,
1,
1,
0,
BN_FLG_STATIC_DATA
};
static BN_ULONG bn_generator_5_value[] = { 5 };
static BIGNUM bn_generator_5 = {
bn_generator_5_value,
1,
1,
0,
BN_FLG_STATIC_DATA
};
static BN_ULONG bn_generator_2_value[] = { 2 };
static BIGNUM bn_generator_2 = {
bn_generator_2_value,
1,
1,
0,
BN_FLG_STATIC_DATA
};
static SRP_gN knowngN[] = {
{"8192", &bn_generator_19, &bn_group_8192},
{"6144", &bn_generator_5, &bn_group_6144},
{"4096", &bn_generator_5, &bn_group_4096},
{"3072", &bn_generator_5, &bn_group_3072},
{"2048", &bn_generator_2, &bn_group_2048},
{"1536", &bn_generator_2, &bn_group_1536},
{"1024", &bn_generator_2, &bn_group_1024},
};
#define KNOWN_GN_NUMBER sizeof(knowngN) / sizeof(SRP_gN)
/* end of generated data */
diff --git a/crypto/threads/mttest.c b/crypto/threads/mttest.c
index dbff4a69f3a4..b26ed28aa9f6 100644
--- a/crypto/threads/mttest.c
+++ b/crypto/threads/mttest.c
@@ -1,1211 +1,1211 @@
/* crypto/threads/mttest.c */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#ifdef LINUX
# include <typedefs.h>
#endif
#ifdef OPENSSL_SYS_WIN32
# include <windows.h>
#endif
#ifdef SOLARIS
# include <synch.h>
# include <thread.h>
#endif
#ifdef IRIX
# include <ulocks.h>
# include <sys/prctl.h>
#endif
#ifdef PTHREADS
# include <pthread.h>
#endif
#ifdef OPENSSL_SYS_NETWARE
# if !defined __int64
# define __int64 long long
# endif
# include <nwmpk.h>
#endif
#include <openssl/lhash.h>
#include <openssl/crypto.h>
#include <openssl/buffer.h>
#include <openssl/x509.h>
#include <openssl/ssl.h>
#include <openssl/err.h>
#include <openssl/rand.h>
#ifdef OPENSSL_SYS_NETWARE
# define TEST_SERVER_CERT "/openssl/apps/server.pem"
# define TEST_CLIENT_CERT "/openssl/apps/client.pem"
#else
# define TEST_SERVER_CERT "../../apps/server.pem"
# define TEST_CLIENT_CERT "../../apps/client.pem"
#endif
#define MAX_THREAD_NUMBER 100
int verify_callback(int ok, X509_STORE_CTX *xs);
void thread_setup(void);
void thread_cleanup(void);
void do_threads(SSL_CTX *s_ctx, SSL_CTX *c_ctx);
void irix_locking_callback(int mode, int type, const char *file, int line);
void solaris_locking_callback(int mode, int type, const char *file, int line);
void win32_locking_callback(int mode, int type, const char *file, int line);
void pthreads_locking_callback(int mode, int type, const char *file, int line);
void netware_locking_callback(int mode, int type, const char *file, int line);
void beos_locking_callback(int mode, int type, const char *file, int line);
void irix_thread_id(CRYPTO_THREADID *tid);
void solaris_thread_id(CRYPTO_THREADID *tid);
void pthreads_thread_id(CRYPTO_THREADID *tid);
void netware_thread_id(CRYPTO_THREADID *tid);
void beos_thread_id(CRYPTO_THREADID *tid);
#if defined(OPENSSL_SYS_NETWARE)
static MPKMutex *lock_cs;
static MPKSema ThreadSem;
static long *lock_count;
#endif
BIO *bio_err = NULL;
BIO *bio_stdout = NULL;
static char *cipher = NULL;
int verbose = 0;
#ifdef FIONBIO
static int s_nbio = 0;
#endif
int thread_number = 10;
int number_of_loops = 10;
int reconnect = 0;
int cache_stats = 0;
static const char rnd_seed[] =
"string to make the random number generator think it has entropy";
int doit(char *ctx[4]);
static void print_stats(BIO *bio, SSL_CTX *ctx)
{
BIO_printf(bio, "%4ld items in the session cache\n",
SSL_CTX_sess_number(ctx));
BIO_printf(bio, "%4d client connects (SSL_connect())\n",
SSL_CTX_sess_connect(ctx));
BIO_printf(bio, "%4d client connects that finished\n",
SSL_CTX_sess_connect_good(ctx));
BIO_printf(bio, "%4d server connects (SSL_accept())\n",
SSL_CTX_sess_accept(ctx));
BIO_printf(bio, "%4d server connects that finished\n",
SSL_CTX_sess_accept_good(ctx));
BIO_printf(bio, "%4d session cache hits\n", SSL_CTX_sess_hits(ctx));
BIO_printf(bio, "%4d session cache misses\n", SSL_CTX_sess_misses(ctx));
BIO_printf(bio, "%4d session cache timeouts\n", SSL_CTX_sess_timeouts(ctx));
}
static void sv_usage(void)
{
BIO_printf(bio_err, "usage: ssltest [args ...]\n");
BIO_printf(bio_err, "\n");
BIO_printf(bio_err, " -server_auth - check server certificate\n");
BIO_printf(bio_err, " -client_auth - do client authentication\n");
BIO_printf(bio_err, " -v - more output\n");
BIO_printf(bio_err, " -CApath arg - PEM format directory of CA's\n");
BIO_printf(bio_err, " -CAfile arg - PEM format file of CA's\n");
BIO_printf(bio_err, " -threads arg - number of threads\n");
BIO_printf(bio_err, " -loops arg - number of 'connections', per thread\n");
BIO_printf(bio_err, " -reconnect - reuse session-id's\n");
BIO_printf(bio_err, " -stats - server session-id cache stats\n");
BIO_printf(bio_err, " -cert arg - server certificate/key\n");
BIO_printf(bio_err, " -ccert arg - client certificate/key\n");
BIO_printf(bio_err, " -ssl3 - just SSLv3n\n");
}
int main(int argc, char *argv[])
{
char *CApath = NULL, *CAfile = NULL;
int badop = 0;
int ret = 1;
int client_auth = 0;
int server_auth = 0;
SSL_CTX *s_ctx = NULL;
SSL_CTX *c_ctx = NULL;
char *scert = TEST_SERVER_CERT;
char *ccert = TEST_CLIENT_CERT;
const SSL_METHOD *ssl_method = SSLv23_method();
- RAND_seed(rnd_seed, sizeof rnd_seed);
+ RAND_seed(rnd_seed, sizeof(rnd_seed));
if (bio_err == NULL)
bio_err = BIO_new_fd(2, BIO_NOCLOSE);
if (bio_stdout == NULL)
bio_stdout = BIO_new_fd(1, BIO_NOCLOSE);
argc--;
argv++;
while (argc >= 1) {
if (strcmp(*argv, "-server_auth") == 0)
server_auth = 1;
else if (strcmp(*argv, "-client_auth") == 0)
client_auth = 1;
else if (strcmp(*argv, "-reconnect") == 0)
reconnect = 1;
else if (strcmp(*argv, "-stats") == 0)
cache_stats = 1;
else if (strcmp(*argv, "-ssl3") == 0)
ssl_method = SSLv3_method();
else if (strcmp(*argv, "-ssl2") == 0)
ssl_method = SSLv2_method();
else if (strcmp(*argv, "-CApath") == 0) {
if (--argc < 1)
goto bad;
CApath = *(++argv);
} else if (strcmp(*argv, "-CAfile") == 0) {
if (--argc < 1)
goto bad;
CAfile = *(++argv);
} else if (strcmp(*argv, "-cert") == 0) {
if (--argc < 1)
goto bad;
scert = *(++argv);
} else if (strcmp(*argv, "-ccert") == 0) {
if (--argc < 1)
goto bad;
ccert = *(++argv);
} else if (strcmp(*argv, "-threads") == 0) {
if (--argc < 1)
goto bad;
thread_number = atoi(*(++argv));
if (thread_number == 0)
thread_number = 1;
if (thread_number > MAX_THREAD_NUMBER)
thread_number = MAX_THREAD_NUMBER;
} else if (strcmp(*argv, "-loops") == 0) {
if (--argc < 1)
goto bad;
number_of_loops = atoi(*(++argv));
if (number_of_loops == 0)
number_of_loops = 1;
} else {
BIO_printf(bio_err, "unknown option %s\n", *argv);
badop = 1;
break;
}
argc--;
argv++;
}
if (badop) {
bad:
sv_usage();
goto end;
}
if (cipher == NULL && OPENSSL_issetugid() == 0)
cipher = getenv("SSL_CIPHER");
SSL_load_error_strings();
OpenSSL_add_ssl_algorithms();
c_ctx = SSL_CTX_new(ssl_method);
s_ctx = SSL_CTX_new(ssl_method);
if ((c_ctx == NULL) || (s_ctx == NULL)) {
ERR_print_errors(bio_err);
goto end;
}
SSL_CTX_set_session_cache_mode(s_ctx,
SSL_SESS_CACHE_NO_AUTO_CLEAR |
SSL_SESS_CACHE_SERVER);
SSL_CTX_set_session_cache_mode(c_ctx,
SSL_SESS_CACHE_NO_AUTO_CLEAR |
SSL_SESS_CACHE_SERVER);
if (!SSL_CTX_use_certificate_file(s_ctx, scert, SSL_FILETYPE_PEM)) {
BIO_printf(bio_err, "SSL_CTX_use_certificate_file (%s)\n", scert);
ERR_print_errors(bio_err);
goto end;
} else
if (!SSL_CTX_use_RSAPrivateKey_file(s_ctx, scert, SSL_FILETYPE_PEM)) {
BIO_printf(bio_err, "SSL_CTX_use_RSAPrivateKey_file (%s)\n", scert);
ERR_print_errors(bio_err);
goto end;
}
if (client_auth) {
SSL_CTX_use_certificate_file(c_ctx, ccert, SSL_FILETYPE_PEM);
SSL_CTX_use_RSAPrivateKey_file(c_ctx, ccert, SSL_FILETYPE_PEM);
}
if ((!SSL_CTX_load_verify_locations(s_ctx, CAfile, CApath)) ||
(!SSL_CTX_set_default_verify_paths(s_ctx)) ||
(!SSL_CTX_load_verify_locations(c_ctx, CAfile, CApath)) ||
(!SSL_CTX_set_default_verify_paths(c_ctx))) {
BIO_printf(bio_err, "SSL_load_verify_locations\n");
ERR_print_errors(bio_err);
goto end;
}
if (client_auth) {
BIO_printf(bio_err, "client authentication\n");
SSL_CTX_set_verify(s_ctx,
SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
verify_callback);
}
if (server_auth) {
BIO_printf(bio_err, "server authentication\n");
SSL_CTX_set_verify(c_ctx, SSL_VERIFY_PEER, verify_callback);
}
thread_setup();
do_threads(s_ctx, c_ctx);
thread_cleanup();
end:
if (c_ctx != NULL) {
BIO_printf(bio_err, "Client SSL_CTX stats then free it\n");
print_stats(bio_err, c_ctx);
SSL_CTX_free(c_ctx);
}
if (s_ctx != NULL) {
BIO_printf(bio_err, "Server SSL_CTX stats then free it\n");
print_stats(bio_err, s_ctx);
if (cache_stats) {
BIO_printf(bio_err, "-----\n");
lh_SSL_SESSION_stats_bio(SSL_CTX_sessions(s_ctx), bio_err);
BIO_printf(bio_err, "-----\n");
/*- lh_SSL_SESSION_node_stats_bio(SSL_CTX_sessions(s_ctx),bio_err);
BIO_printf(bio_err,"-----\n"); */
lh_SSL_SESSION_node_usage_stats_bio(SSL_CTX_sessions(s_ctx), bio_err);
BIO_printf(bio_err, "-----\n");
}
SSL_CTX_free(s_ctx);
BIO_printf(bio_err, "done free\n");
}
exit(ret);
return (0);
}
#define W_READ 1
#define W_WRITE 2
#define C_DONE 1
#define S_DONE 2
int ndoit(SSL_CTX *ssl_ctx[2])
{
int i;
int ret;
char *ctx[4];
CRYPTO_THREADID thread_id;
ctx[0] = (char *)ssl_ctx[0];
ctx[1] = (char *)ssl_ctx[1];
if (reconnect) {
ctx[2] = (char *)SSL_new(ssl_ctx[0]);
ctx[3] = (char *)SSL_new(ssl_ctx[1]);
} else {
ctx[2] = NULL;
ctx[3] = NULL;
}
CRYPTO_THREADID_current(&thread_id);
BIO_printf(bio_stdout, "started thread %lu\n",
CRYPTO_THREADID_hash(&thread_id));
for (i = 0; i < number_of_loops; i++) {
/*- BIO_printf(bio_err,"%4d %2d ctx->ref (%3d,%3d)\n",
CRYPTO_THREADID_hash(&thread_id),i,
ssl_ctx[0]->references,
ssl_ctx[1]->references); */
/* pthread_delay_np(&tm); */
ret = doit(ctx);
if (ret != 0) {
BIO_printf(bio_stdout, "error[%d] %lu - %d\n",
i, CRYPTO_THREADID_hash(&thread_id), ret);
return (ret);
}
}
BIO_printf(bio_stdout, "DONE %lu\n", CRYPTO_THREADID_hash(&thread_id));
if (reconnect) {
SSL_free((SSL *)ctx[2]);
SSL_free((SSL *)ctx[3]);
}
#ifdef OPENSSL_SYS_NETWARE
MPKSemaphoreSignal(ThreadSem);
#endif
return (0);
}
int doit(char *ctx[4])
{
SSL_CTX *s_ctx, *c_ctx;
static char cbuf[200], sbuf[200];
SSL *c_ssl = NULL;
SSL *s_ssl = NULL;
BIO *c_to_s = NULL;
BIO *s_to_c = NULL;
BIO *c_bio = NULL;
BIO *s_bio = NULL;
int c_r, c_w, s_r, s_w;
int c_want, s_want;
int i;
int done = 0;
int c_write, s_write;
int do_server = 0, do_client = 0;
s_ctx = (SSL_CTX *)ctx[0];
c_ctx = (SSL_CTX *)ctx[1];
if (ctx[2] != NULL)
s_ssl = (SSL *)ctx[2];
else
s_ssl = SSL_new(s_ctx);
if (ctx[3] != NULL)
c_ssl = (SSL *)ctx[3];
else
c_ssl = SSL_new(c_ctx);
if ((s_ssl == NULL) || (c_ssl == NULL))
goto err;
c_to_s = BIO_new(BIO_s_mem());
s_to_c = BIO_new(BIO_s_mem());
if ((s_to_c == NULL) || (c_to_s == NULL))
goto err;
c_bio = BIO_new(BIO_f_ssl());
s_bio = BIO_new(BIO_f_ssl());
if ((c_bio == NULL) || (s_bio == NULL))
goto err;
SSL_set_connect_state(c_ssl);
SSL_set_bio(c_ssl, s_to_c, c_to_s);
BIO_set_ssl(c_bio, c_ssl, (ctx[2] == NULL) ? BIO_CLOSE : BIO_NOCLOSE);
SSL_set_accept_state(s_ssl);
SSL_set_bio(s_ssl, c_to_s, s_to_c);
BIO_set_ssl(s_bio, s_ssl, (ctx[3] == NULL) ? BIO_CLOSE : BIO_NOCLOSE);
c_r = 0;
s_r = 1;
c_w = 1;
s_w = 0;
c_want = W_WRITE;
s_want = 0;
c_write = 1, s_write = 0;
/* We can always do writes */
for (;;) {
do_server = 0;
do_client = 0;
i = (int)BIO_pending(s_bio);
if ((i && s_r) || s_w)
do_server = 1;
i = (int)BIO_pending(c_bio);
if ((i && c_r) || c_w)
do_client = 1;
if (do_server && verbose) {
if (SSL_in_init(s_ssl))
BIO_printf(bio_stdout, "server waiting in SSL_accept - %s\n",
SSL_state_string_long(s_ssl));
else if (s_write)
BIO_printf(bio_stdout, "server:SSL_write()\n");
else
BIO_printf(bio_stdout, "server:SSL_read()\n");
}
if (do_client && verbose) {
if (SSL_in_init(c_ssl))
BIO_printf(bio_stdout, "client waiting in SSL_connect - %s\n",
SSL_state_string_long(c_ssl));
else if (c_write)
BIO_printf(bio_stdout, "client:SSL_write()\n");
else
BIO_printf(bio_stdout, "client:SSL_read()\n");
}
if (!do_client && !do_server) {
BIO_printf(bio_stdout, "ERROR IN STARTUP\n");
break;
}
if (do_client && !(done & C_DONE)) {
if (c_write) {
i = BIO_write(c_bio, "hello from client\n", 18);
if (i < 0) {
c_r = 0;
c_w = 0;
if (BIO_should_retry(c_bio)) {
if (BIO_should_read(c_bio))
c_r = 1;
if (BIO_should_write(c_bio))
c_w = 1;
} else {
BIO_printf(bio_err, "ERROR in CLIENT\n");
ERR_print_errors_fp(stderr);
return (1);
}
} else if (i == 0) {
BIO_printf(bio_err, "SSL CLIENT STARTUP FAILED\n");
return (1);
} else {
/* ok */
c_write = 0;
}
} else {
i = BIO_read(c_bio, cbuf, 100);
if (i < 0) {
c_r = 0;
c_w = 0;
if (BIO_should_retry(c_bio)) {
if (BIO_should_read(c_bio))
c_r = 1;
if (BIO_should_write(c_bio))
c_w = 1;
} else {
BIO_printf(bio_err, "ERROR in CLIENT\n");
ERR_print_errors_fp(stderr);
return (1);
}
} else if (i == 0) {
BIO_printf(bio_err, "SSL CLIENT STARTUP FAILED\n");
return (1);
} else {
done |= C_DONE;
#ifdef undef
BIO_printf(bio_stdout, "CLIENT:from server:");
BIO_write(bio_stdout, cbuf, i);
BIO_flush(bio_stdout);
#endif
}
}
}
if (do_server && !(done & S_DONE)) {
if (!s_write) {
i = BIO_read(s_bio, sbuf, 100);
if (i < 0) {
s_r = 0;
s_w = 0;
if (BIO_should_retry(s_bio)) {
if (BIO_should_read(s_bio))
s_r = 1;
if (BIO_should_write(s_bio))
s_w = 1;
} else {
BIO_printf(bio_err, "ERROR in SERVER\n");
ERR_print_errors_fp(stderr);
return (1);
}
} else if (i == 0) {
BIO_printf(bio_err, "SSL SERVER STARTUP FAILED\n");
return (1);
} else {
s_write = 1;
s_w = 1;
#ifdef undef
BIO_printf(bio_stdout, "SERVER:from client:");
BIO_write(bio_stdout, sbuf, i);
BIO_flush(bio_stdout);
#endif
}
} else {
i = BIO_write(s_bio, "hello from server\n", 18);
if (i < 0) {
s_r = 0;
s_w = 0;
if (BIO_should_retry(s_bio)) {
if (BIO_should_read(s_bio))
s_r = 1;
if (BIO_should_write(s_bio))
s_w = 1;
} else {
BIO_printf(bio_err, "ERROR in SERVER\n");
ERR_print_errors_fp(stderr);
return (1);
}
} else if (i == 0) {
BIO_printf(bio_err, "SSL SERVER STARTUP FAILED\n");
return (1);
} else {
s_write = 0;
s_r = 1;
done |= S_DONE;
}
}
}
if ((done & S_DONE) && (done & C_DONE))
break;
#if defined(OPENSSL_SYS_NETWARE)
ThreadSwitchWithDelay();
#endif
}
SSL_set_shutdown(c_ssl, SSL_SENT_SHUTDOWN | SSL_RECEIVED_SHUTDOWN);
SSL_set_shutdown(s_ssl, SSL_SENT_SHUTDOWN | SSL_RECEIVED_SHUTDOWN);
#ifdef undef
BIO_printf(bio_stdout, "DONE\n");
#endif
err:
/*
* We have to set the BIO's to NULL otherwise they will be free()ed
* twice. Once when th s_ssl is SSL_free()ed and again when c_ssl is
* SSL_free()ed. This is a hack required because s_ssl and c_ssl are
* sharing the same BIO structure and SSL_set_bio() and SSL_free()
* automatically BIO_free non NULL entries. You should not normally do
* this or be required to do this
*/
if (s_ssl != NULL) {
s_ssl->rbio = NULL;
s_ssl->wbio = NULL;
}
if (c_ssl != NULL) {
c_ssl->rbio = NULL;
c_ssl->wbio = NULL;
}
/* The SSL's are optionally freed in the following calls */
if (c_to_s != NULL)
BIO_free(c_to_s);
if (s_to_c != NULL)
BIO_free(s_to_c);
if (c_bio != NULL)
BIO_free(c_bio);
if (s_bio != NULL)
BIO_free(s_bio);
return (0);
}
int verify_callback(int ok, X509_STORE_CTX *ctx)
{
char *s, buf[256];
if (verbose) {
s = X509_NAME_oneline(X509_get_subject_name(ctx->current_cert),
buf, 256);
if (s != NULL) {
if (ok)
BIO_printf(bio_err, "depth=%d %s\n", ctx->error_depth, buf);
else
BIO_printf(bio_err, "depth=%d error=%d %s\n",
ctx->error_depth, ctx->error, buf);
}
}
return (ok);
}
#define THREAD_STACK_SIZE (16*1024)
#ifdef OPENSSL_SYS_WIN32
static HANDLE *lock_cs;
void thread_setup(void)
{
int i;
lock_cs = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(HANDLE));
for (i = 0; i < CRYPTO_num_locks(); i++) {
lock_cs[i] = CreateMutex(NULL, FALSE, NULL);
}
CRYPTO_set_locking_callback((void (*)(int, int, char *, int))
win32_locking_callback);
/* id callback defined */
}
void thread_cleanup(void)
{
int i;
CRYPTO_set_locking_callback(NULL);
for (i = 0; i < CRYPTO_num_locks(); i++)
CloseHandle(lock_cs[i]);
OPENSSL_free(lock_cs);
}
void win32_locking_callback(int mode, int type, const char *file, int line)
{
if (mode & CRYPTO_LOCK) {
WaitForSingleObject(lock_cs[type], INFINITE);
} else {
ReleaseMutex(lock_cs[type]);
}
}
void do_threads(SSL_CTX *s_ctx, SSL_CTX *c_ctx)
{
double ret;
SSL_CTX *ssl_ctx[2];
DWORD thread_id[MAX_THREAD_NUMBER];
HANDLE thread_handle[MAX_THREAD_NUMBER];
int i;
SYSTEMTIME start, end;
ssl_ctx[0] = s_ctx;
ssl_ctx[1] = c_ctx;
GetSystemTime(&start);
for (i = 0; i < thread_number; i++) {
thread_handle[i] = CreateThread(NULL,
THREAD_STACK_SIZE,
(LPTHREAD_START_ROUTINE) ndoit,
(void *)ssl_ctx, 0L, &(thread_id[i]));
}
BIO_printf(bio_stdout, "reaping\n");
for (i = 0; i < thread_number; i += 50) {
int j;
j = (thread_number < (i + 50)) ? (thread_number - i) : 50;
if (WaitForMultipleObjects(j,
(CONST HANDLE *) & (thread_handle[i]),
TRUE, INFINITE)
== WAIT_FAILED) {
BIO_printf(bio_err, "WaitForMultipleObjects failed:%d\n",
GetLastError());
exit(1);
}
}
GetSystemTime(&end);
if (start.wDayOfWeek > end.wDayOfWeek)
end.wDayOfWeek += 7;
ret = (end.wDayOfWeek - start.wDayOfWeek) * 24;
ret = (ret + end.wHour - start.wHour) * 60;
ret = (ret + end.wMinute - start.wMinute) * 60;
ret = (ret + end.wSecond - start.wSecond);
ret += (end.wMilliseconds - start.wMilliseconds) / 1000.0;
BIO_printf(bio_stdout, "win32 threads done - %.3f seconds\n", ret);
}
#endif /* OPENSSL_SYS_WIN32 */
#ifdef SOLARIS
static mutex_t *lock_cs;
/*
* static rwlock_t *lock_cs;
*/
static long *lock_count;
void thread_setup(void)
{
int i;
lock_cs = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(mutex_t));
lock_count = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
for (i = 0; i < CRYPTO_num_locks(); i++) {
lock_count[i] = 0;
/* rwlock_init(&(lock_cs[i]),USYNC_THREAD,NULL); */
mutex_init(&(lock_cs[i]), USYNC_THREAD, NULL);
}
CRYPTO_set_id_callback(solaris_thread_id);
CRYPTO_set_locking_callback(solaris_locking_callback);
}
void thread_cleanup(void)
{
int i;
CRYPTO_set_locking_callback(NULL);
BIO_printf(bio_err, "cleanup\n");
for (i = 0; i < CRYPTO_num_locks(); i++) {
/* rwlock_destroy(&(lock_cs[i])); */
mutex_destroy(&(lock_cs[i]));
BIO_printf(bio_err, "%8ld:%s\n", lock_count[i], CRYPTO_get_lock_name(i));
}
OPENSSL_free(lock_cs);
OPENSSL_free(lock_count);
BIO_printf(bio_err, "done cleanup\n");
}
void solaris_locking_callback(int mode, int type, const char *file, int line)
{
# ifdef undef
BIO_printf(bio_err, "thread=%4d mode=%s lock=%s %s:%d\n",
CRYPTO_thread_id(),
(mode & CRYPTO_LOCK) ? "l" : "u",
(type & CRYPTO_READ) ? "r" : "w", file, line);
# endif
/*-
if (CRYPTO_LOCK_SSL_CERT == type)
BIO_printf(bio_err,"(t,m,f,l) %ld %d %s %d\n",
CRYPTO_thread_id(),
mode,file,line);
*/
if (mode & CRYPTO_LOCK) {
/*-
if (mode & CRYPTO_READ)
rw_rdlock(&(lock_cs[type]));
else
rw_wrlock(&(lock_cs[type])); */
mutex_lock(&(lock_cs[type]));
lock_count[type]++;
} else {
/* rw_unlock(&(lock_cs[type])); */
mutex_unlock(&(lock_cs[type]));
}
}
void do_threads(SSL_CTX *s_ctx, SSL_CTX *c_ctx)
{
SSL_CTX *ssl_ctx[2];
thread_t thread_ctx[MAX_THREAD_NUMBER];
int i;
ssl_ctx[0] = s_ctx;
ssl_ctx[1] = c_ctx;
thr_setconcurrency(thread_number);
for (i = 0; i < thread_number; i++) {
thr_create(NULL, THREAD_STACK_SIZE,
(void *(*)())ndoit, (void *)ssl_ctx, 0L, &(thread_ctx[i]));
}
BIO_printf(bio_stdout, "reaping\n");
for (i = 0; i < thread_number; i++) {
thr_join(thread_ctx[i], NULL, NULL);
}
#if 0 /* We can't currently find out the reference amount */
BIO_printf(bio_stdout, "solaris threads done (%d,%d)\n",
s_ctx->references, c_ctx->references);
#else
BIO_printf(bio_stdout, "solaris threads done\n");
#endif
}
void solaris_thread_id(CRYPTO_THREADID *tid)
{
CRYPTO_THREADID_set_numeric((unsigned long)thr_self());
}
#endif /* SOLARIS */
#ifdef IRIX
static usptr_t *arena;
static usema_t **lock_cs;
void thread_setup(void)
{
int i;
char filename[20];
strcpy(filename, "/tmp/mttest.XXXXXX");
mktemp(filename);
usconfig(CONF_STHREADIOOFF);
usconfig(CONF_STHREADMALLOCOFF);
usconfig(CONF_INITUSERS, 100);
usconfig(CONF_LOCKTYPE, US_DEBUGPLUS);
arena = usinit(filename);
unlink(filename);
lock_cs = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(usema_t *));
for (i = 0; i < CRYPTO_num_locks(); i++) {
lock_cs[i] = usnewsema(arena, 1);
}
CRYPTO_set_id_callback(irix_thread_id);
CRYPTO_set_locking_callback(irix_locking_callback);
}
void thread_cleanup(void)
{
int i;
CRYPTO_set_locking_callback(NULL);
for (i = 0; i < CRYPTO_num_locks(); i++) {
char buf[10];
sprintf(buf, "%2d:", i);
usdumpsema(lock_cs[i], stdout, buf);
usfreesema(lock_cs[i], arena);
}
OPENSSL_free(lock_cs);
}
void irix_locking_callback(int mode, int type, const char *file, int line)
{
if (mode & CRYPTO_LOCK) {
BIO_printf(bio_stdout, "lock %d\n", type);
uspsema(lock_cs[type]);
} else {
BIO_printf(bio_stdout, "unlock %d\n", type);
usvsema(lock_cs[type]);
}
}
void do_threads(SSL_CTX *s_ctx, SSL_CTX *c_ctx)
{
SSL_CTX *ssl_ctx[2];
int thread_ctx[MAX_THREAD_NUMBER];
int i;
ssl_ctx[0] = s_ctx;
ssl_ctx[1] = c_ctx;
for (i = 0; i < thread_number; i++) {
thread_ctx[i] = sproc((void (*)())ndoit,
PR_SADDR | PR_SFDS, (void *)ssl_ctx);
}
BIO_printf(bio_stdout, "reaping\n");
for (i = 0; i < thread_number; i++) {
wait(NULL);
}
#if 0 /* We can't currently find out the reference amount */
BIO_printf(bio_stdout, "irix threads done (%d,%d)\n",
s_ctx->references, c_ctx->references);
#else
BIO_printf(bio_stdout, "irix threads done\n");
#endif
}
unsigned long irix_thread_id(void)
{
CRYPTO_THREADID_set_numeric((unsigned long)getpid());
}
#endif /* IRIX */
#ifdef PTHREADS
static pthread_mutex_t *lock_cs;
static long *lock_count;
void thread_setup(void)
{
int i;
lock_cs = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t));
lock_count = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
for (i = 0; i < CRYPTO_num_locks(); i++) {
lock_count[i] = 0;
pthread_mutex_init(&(lock_cs[i]), NULL);
}
CRYPTO_THREADID_set_callback(pthreads_thread_id);
CRYPTO_set_locking_callback(pthreads_locking_callback);
}
void thread_cleanup(void)
{
int i;
CRYPTO_set_locking_callback(NULL);
BIO_printf(bio_err, "cleanup\n");
for (i = 0; i < CRYPTO_num_locks(); i++) {
pthread_mutex_destroy(&(lock_cs[i]));
BIO_printf(bio_err, "%8ld:%s\n", lock_count[i], CRYPTO_get_lock_name(i));
}
OPENSSL_free(lock_cs);
OPENSSL_free(lock_count);
BIO_printf(bio_err, "done cleanup\n");
}
void pthreads_locking_callback(int mode, int type, const char *file, int line)
{
# ifdef undef
BIO_printf(bio_err, "thread=%4d mode=%s lock=%s %s:%d\n",
CRYPTO_thread_id(),
(mode & CRYPTO_LOCK) ? "l" : "u",
(type & CRYPTO_READ) ? "r" : "w", file, line);
# endif
/*-
if (CRYPTO_LOCK_SSL_CERT == type)
BIO_printf(bio_err,"(t,m,f,l) %ld %d %s %d\n",
CRYPTO_thread_id(),
mode,file,line);
*/
if (mode & CRYPTO_LOCK) {
pthread_mutex_lock(&(lock_cs[type]));
lock_count[type]++;
} else {
pthread_mutex_unlock(&(lock_cs[type]));
}
}
void do_threads(SSL_CTX *s_ctx, SSL_CTX *c_ctx)
{
SSL_CTX *ssl_ctx[2];
pthread_t thread_ctx[MAX_THREAD_NUMBER];
int i;
ssl_ctx[0] = s_ctx;
ssl_ctx[1] = c_ctx;
/*
* thr_setconcurrency(thread_number);
*/
for (i = 0; i < thread_number; i++) {
pthread_create(&(thread_ctx[i]), NULL,
(void *(*)())ndoit, (void *)ssl_ctx);
}
BIO_printf(bio_stdout, "reaping\n");
for (i = 0; i < thread_number; i++) {
pthread_join(thread_ctx[i], NULL);
}
#if 0 /* We can't currently find out the reference amount */
BIO_printf(bio_stdout, "pthreads threads done (%d,%d)\n",
s_ctx->references, c_ctx->references);
#else
BIO_printf(bio_stdout, "pthreads threads done\n");
#endif
}
void pthreads_thread_id(CRYPTO_THREADID *tid)
{
CRYPTO_THREADID_set_numeric(tid, (unsigned long)pthread_self());
}
#endif /* PTHREADS */
#ifdef OPENSSL_SYS_NETWARE
void thread_setup(void)
{
int i;
lock_cs = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(MPKMutex));
lock_count = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
for (i = 0; i < CRYPTO_num_locks(); i++) {
lock_count[i] = 0;
lock_cs[i] = MPKMutexAlloc("OpenSSL mutex");
}
ThreadSem = MPKSemaphoreAlloc("OpenSSL mttest semaphore", 0);
CRYPTO_set_id_callback(netware_thread_id);
CRYPTO_set_locking_callback(netware_locking_callback);
}
void thread_cleanup(void)
{
int i;
CRYPTO_set_locking_callback(NULL);
BIO_printf(bio_stdout, "thread_cleanup\n");
for (i = 0; i < CRYPTO_num_locks(); i++) {
MPKMutexFree(lock_cs[i]);
BIO_printf(bio_stdout, "%8ld:%s\n", lock_count[i], CRYPTO_get_lock_name(i));
}
OPENSSL_free(lock_cs);
OPENSSL_free(lock_count);
MPKSemaphoreFree(ThreadSem);
BIO_printf(bio_stdout, "done cleanup\n");
}
void netware_locking_callback(int mode, int type, const char *file, int line)
{
if (mode & CRYPTO_LOCK) {
MPKMutexLock(lock_cs[type]);
lock_count[type]++;
} else
MPKMutexUnlock(lock_cs[type]);
}
void do_threads(SSL_CTX *s_ctx, SSL_CTX *c_ctx)
{
SSL_CTX *ssl_ctx[2];
int i;
ssl_ctx[0] = s_ctx;
ssl_ctx[1] = c_ctx;
for (i = 0; i < thread_number; i++) {
BeginThread((void (*)(void *))ndoit, NULL, THREAD_STACK_SIZE,
(void *)ssl_ctx);
ThreadSwitchWithDelay();
}
BIO_printf(bio_stdout, "reaping\n");
/* loop until all threads have signaled the semaphore */
for (i = 0; i < thread_number; i++) {
MPKSemaphoreWait(ThreadSem);
}
#if 0 /* We can't currently find out the reference amount */
BIO_printf(bio_stdout, "netware threads done (%d,%d)\n",
s_ctx->references, c_ctx->references);
#else
BIO_printf(bio_stdout, "netware threads done\n");
#endif
}
unsigned long netware_thread_id(void)
{
CRYPTO_THREADID_set_numeric((unsigned long)GetThreadID());
}
#endif /* NETWARE */
#ifdef BEOS_THREADS
# include <Locker.h>
static BLocker **lock_cs;
static long *lock_count;
void thread_setup(void)
{
int i;
lock_cs =
(BLocker **) OPENSSL_malloc(CRYPTO_num_locks() * sizeof(BLocker *));
lock_count = (long *)OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
for (i = 0; i < CRYPTO_num_locks(); i++) {
lock_count[i] = 0;
lock_cs[i] = new BLocker(CRYPTO_get_lock_name(i));
}
CRYPTO_set_id_callback((unsigned long (*)())beos_thread_id);
CRYPTO_set_locking_callback(beos_locking_callback);
}
void thread_cleanup(void)
{
int i;
CRYPTO_set_locking_callback(NULL);
BIO_printf(bio_err, "cleanup\n");
for (i = 0; i < CRYPTO_num_locks(); i++) {
delete lock_cs[i];
BIO_printf(bio_err, "%8ld:%s\n", lock_count[i], CRYPTO_get_lock_name(i));
}
OPENSSL_free(lock_cs);
OPENSSL_free(lock_count);
BIO_printf(bio_err, "done cleanup\n");
}
void beos_locking_callback(int mode, int type, const char *file, int line)
{
# if 0
BIO_printf(bio_err, "thread=%4d mode=%s lock=%s %s:%d\n",
CRYPTO_thread_id(),
(mode & CRYPTO_LOCK) ? "l" : "u",
(type & CRYPTO_READ) ? "r" : "w", file, line);
# endif
if (mode & CRYPTO_LOCK) {
lock_cs[type]->Lock();
lock_count[type]++;
} else {
lock_cs[type]->Unlock();
}
}
void do_threads(SSL_CTX *s_ctx, SSL_CTX *c_ctx)
{
SSL_CTX *ssl_ctx[2];
thread_id thread_ctx[MAX_THREAD_NUMBER];
int i;
ssl_ctx[0] = s_ctx;
ssl_ctx[1] = c_ctx;
for (i = 0; i < thread_number; i++) {
thread_ctx[i] = spawn_thread((thread_func) ndoit,
NULL, B_NORMAL_PRIORITY,
(void *)ssl_ctx);
resume_thread(thread_ctx[i]);
}
BIO_printf(bio_stdout, "waiting...\n");
for (i = 0; i < thread_number; i++) {
status_t result;
wait_for_thread(thread_ctx[i], &result);
}
BIO_printf(bio_stdout, "beos threads done (%d,%d)\n",
s_ctx->references, c_ctx->references);
}
unsigned long beos_thread_id(void)
{
unsigned long ret;
ret = (unsigned long)find_thread(NULL);
return (ret);
}
#endif /* BEOS_THREADS */
diff --git a/crypto/ts/Makefile b/crypto/ts/Makefile
index cf991efe4641..4a3c0f0017e8 100644
--- a/crypto/ts/Makefile
+++ b/crypto/ts/Makefile
@@ -1,271 +1,272 @@
#
# SSLeay/crypto/ts/Makefile
#
DIR= ts
TOP= ../..
CC= cc
INCLUDES= -I.. -I../../include
CFLAG = -g
INSTALL_PREFIX=
OPENSSLDIR= /usr/local/ssl
INSTALLTOP=/usr/local/ssl
MAKEDEPPROG= makedepend
MAKEDEPEND= $(TOP)/util/domd $(TOP) -MD $(MAKEDEPPROG)
MAKEFILE= Makefile
AR= ar r
PEX_LIBS=
EX_LIBS=
CFLAGS= $(INCLUDES) $(CFLAG)
GENERAL= Makefile
TEST=
APPS=
LIB=$(TOP)/libcrypto.a
LIBSRC= ts_err.c ts_req_utils.c ts_req_print.c ts_rsp_utils.c ts_rsp_print.c \
ts_rsp_sign.c ts_rsp_verify.c ts_verify_ctx.c ts_lib.c ts_conf.c \
ts_asn1.c
LIBOBJ= ts_err.o ts_req_utils.o ts_req_print.o ts_rsp_utils.o ts_rsp_print.o \
ts_rsp_sign.o ts_rsp_verify.o ts_verify_ctx.o ts_lib.o ts_conf.o \
ts_asn1.o
SRC= $(LIBSRC)
EXHEADER= ts.h
HEADER= $(EXHEADER)
ALL= $(GENERAL) $(SRC) $(HEADER)
top:
(cd ../..; $(MAKE) DIRS=crypto SDIRS=$(DIR) sub_all)
test:
all: lib
lib: $(LIBOBJ)
$(AR) $(LIB) $(LIBOBJ)
$(RANLIB) $(LIB) || echo Never mind.
@touch lib
files:
$(PERL) $(TOP)/util/files.pl Makefile >> $(TOP)/MINFO
links:
@$(PERL) $(TOP)/util/mklink.pl ../../include/openssl $(EXHEADER)
@$(PERL) $(TOP)/util/mklink.pl ../../test $(TEST)
@$(PERL) $(TOP)/util/mklink.pl ../../apps $(APPS)
install:
@[ -n "$(INSTALLTOP)" ] # should be set by top Makefile...
@headerlist="$(EXHEADER)"; for i in $$headerlist ; \
do \
(cp $$i $(INSTALL_PREFIX)$(INSTALLTOP)/include/openssl/$$i; \
chmod 644 $(INSTALL_PREFIX)$(INSTALLTOP)/include/openssl/$$i ); \
done;
tags:
ctags $(SRC)
lint:
lint -DLINT $(INCLUDES) $(SRC)>fluff
update: depend
depend:
$(MAKEDEPEND) -- $(CFLAG) $(INCLUDES) $(DEPFLAG) -- $(LIBSRC)
dclean:
$(PERL) -pe 'if (/^# DO NOT DELETE THIS LINE/) {print; exit(0);}' $(MAKEFILE) >Makefile.new
mv -f Makefile.new $(MAKEFILE)
clean:
rm -f *.o *.obj lib tags core .pure .nfs* *.old *.bak fluff enc dec sign verify
# DO NOT DELETE THIS LINE -- make depend depends on it.
ts_asn1.o: ../../include/openssl/asn1.h ../../include/openssl/asn1t.h
ts_asn1.o: ../../include/openssl/bio.h ../../include/openssl/buffer.h
ts_asn1.o: ../../include/openssl/conf.h ../../include/openssl/crypto.h
ts_asn1.o: ../../include/openssl/dh.h ../../include/openssl/dsa.h
ts_asn1.o: ../../include/openssl/e_os2.h ../../include/openssl/ec.h
ts_asn1.o: ../../include/openssl/ecdh.h ../../include/openssl/ecdsa.h
ts_asn1.o: ../../include/openssl/err.h ../../include/openssl/evp.h
ts_asn1.o: ../../include/openssl/lhash.h ../../include/openssl/obj_mac.h
ts_asn1.o: ../../include/openssl/objects.h ../../include/openssl/opensslconf.h
ts_asn1.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h
ts_asn1.o: ../../include/openssl/pkcs7.h ../../include/openssl/rsa.h
ts_asn1.o: ../../include/openssl/safestack.h ../../include/openssl/sha.h
ts_asn1.o: ../../include/openssl/stack.h ../../include/openssl/symhacks.h
ts_asn1.o: ../../include/openssl/ts.h ../../include/openssl/x509.h
ts_asn1.o: ../../include/openssl/x509_vfy.h ../../include/openssl/x509v3.h
ts_asn1.o: ts_asn1.c
ts_conf.o: ../../e_os.h ../../include/openssl/asn1.h
ts_conf.o: ../../include/openssl/bio.h ../../include/openssl/buffer.h
ts_conf.o: ../../include/openssl/conf.h ../../include/openssl/crypto.h
ts_conf.o: ../../include/openssl/dh.h ../../include/openssl/dsa.h
ts_conf.o: ../../include/openssl/e_os2.h ../../include/openssl/ec.h
ts_conf.o: ../../include/openssl/ecdh.h ../../include/openssl/ecdsa.h
ts_conf.o: ../../include/openssl/engine.h ../../include/openssl/err.h
ts_conf.o: ../../include/openssl/evp.h ../../include/openssl/lhash.h
ts_conf.o: ../../include/openssl/obj_mac.h ../../include/openssl/objects.h
ts_conf.o: ../../include/openssl/opensslconf.h ../../include/openssl/opensslv.h
ts_conf.o: ../../include/openssl/ossl_typ.h ../../include/openssl/pem.h
ts_conf.o: ../../include/openssl/pem2.h ../../include/openssl/pkcs7.h
ts_conf.o: ../../include/openssl/rsa.h ../../include/openssl/safestack.h
ts_conf.o: ../../include/openssl/sha.h ../../include/openssl/stack.h
ts_conf.o: ../../include/openssl/symhacks.h ../../include/openssl/ts.h
ts_conf.o: ../../include/openssl/x509.h ../../include/openssl/x509_vfy.h
ts_conf.o: ../../include/openssl/x509v3.h ../cryptlib.h ts_conf.c
ts_err.o: ../../include/openssl/asn1.h ../../include/openssl/bio.h
ts_err.o: ../../include/openssl/buffer.h ../../include/openssl/conf.h
ts_err.o: ../../include/openssl/crypto.h ../../include/openssl/dh.h
ts_err.o: ../../include/openssl/dsa.h ../../include/openssl/e_os2.h
ts_err.o: ../../include/openssl/ec.h ../../include/openssl/ecdh.h
ts_err.o: ../../include/openssl/ecdsa.h ../../include/openssl/err.h
ts_err.o: ../../include/openssl/evp.h ../../include/openssl/lhash.h
ts_err.o: ../../include/openssl/obj_mac.h ../../include/openssl/objects.h
ts_err.o: ../../include/openssl/opensslconf.h ../../include/openssl/opensslv.h
ts_err.o: ../../include/openssl/ossl_typ.h ../../include/openssl/pkcs7.h
ts_err.o: ../../include/openssl/rsa.h ../../include/openssl/safestack.h
ts_err.o: ../../include/openssl/sha.h ../../include/openssl/stack.h
ts_err.o: ../../include/openssl/symhacks.h ../../include/openssl/ts.h
ts_err.o: ../../include/openssl/x509.h ../../include/openssl/x509_vfy.h
ts_err.o: ../../include/openssl/x509v3.h ts_err.c
ts_lib.o: ../../e_os.h ../../include/openssl/asn1.h ../../include/openssl/bio.h
ts_lib.o: ../../include/openssl/bn.h ../../include/openssl/buffer.h
ts_lib.o: ../../include/openssl/conf.h ../../include/openssl/crypto.h
ts_lib.o: ../../include/openssl/dh.h ../../include/openssl/dsa.h
ts_lib.o: ../../include/openssl/e_os2.h ../../include/openssl/ec.h
ts_lib.o: ../../include/openssl/ecdh.h ../../include/openssl/ecdsa.h
ts_lib.o: ../../include/openssl/err.h ../../include/openssl/evp.h
ts_lib.o: ../../include/openssl/lhash.h ../../include/openssl/obj_mac.h
ts_lib.o: ../../include/openssl/objects.h ../../include/openssl/opensslconf.h
ts_lib.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h
ts_lib.o: ../../include/openssl/pkcs7.h ../../include/openssl/rsa.h
ts_lib.o: ../../include/openssl/safestack.h ../../include/openssl/sha.h
ts_lib.o: ../../include/openssl/stack.h ../../include/openssl/symhacks.h
ts_lib.o: ../../include/openssl/x509.h ../../include/openssl/x509_vfy.h
ts_lib.o: ../../include/openssl/x509v3.h ../cryptlib.h ts.h ts_lib.c
ts_req_print.o: ../../e_os.h ../../include/openssl/asn1.h
ts_req_print.o: ../../include/openssl/bio.h ../../include/openssl/bn.h
ts_req_print.o: ../../include/openssl/buffer.h ../../include/openssl/conf.h
ts_req_print.o: ../../include/openssl/crypto.h ../../include/openssl/dh.h
ts_req_print.o: ../../include/openssl/dsa.h ../../include/openssl/e_os2.h
ts_req_print.o: ../../include/openssl/ec.h ../../include/openssl/ecdh.h
ts_req_print.o: ../../include/openssl/ecdsa.h ../../include/openssl/err.h
ts_req_print.o: ../../include/openssl/evp.h ../../include/openssl/lhash.h
ts_req_print.o: ../../include/openssl/obj_mac.h ../../include/openssl/objects.h
ts_req_print.o: ../../include/openssl/opensslconf.h
ts_req_print.o: ../../include/openssl/opensslv.h
ts_req_print.o: ../../include/openssl/ossl_typ.h ../../include/openssl/pkcs7.h
ts_req_print.o: ../../include/openssl/rsa.h ../../include/openssl/safestack.h
ts_req_print.o: ../../include/openssl/sha.h ../../include/openssl/stack.h
ts_req_print.o: ../../include/openssl/symhacks.h ../../include/openssl/ts.h
ts_req_print.o: ../../include/openssl/x509.h ../../include/openssl/x509_vfy.h
ts_req_print.o: ../../include/openssl/x509v3.h ../cryptlib.h ts_req_print.c
ts_req_utils.o: ../../e_os.h ../../include/openssl/asn1.h
ts_req_utils.o: ../../include/openssl/bio.h ../../include/openssl/buffer.h
ts_req_utils.o: ../../include/openssl/conf.h ../../include/openssl/crypto.h
ts_req_utils.o: ../../include/openssl/dh.h ../../include/openssl/dsa.h
ts_req_utils.o: ../../include/openssl/e_os2.h ../../include/openssl/ec.h
ts_req_utils.o: ../../include/openssl/ecdh.h ../../include/openssl/ecdsa.h
ts_req_utils.o: ../../include/openssl/err.h ../../include/openssl/evp.h
ts_req_utils.o: ../../include/openssl/lhash.h ../../include/openssl/obj_mac.h
ts_req_utils.o: ../../include/openssl/objects.h
ts_req_utils.o: ../../include/openssl/opensslconf.h
ts_req_utils.o: ../../include/openssl/opensslv.h
ts_req_utils.o: ../../include/openssl/ossl_typ.h ../../include/openssl/pkcs7.h
ts_req_utils.o: ../../include/openssl/rsa.h ../../include/openssl/safestack.h
ts_req_utils.o: ../../include/openssl/sha.h ../../include/openssl/stack.h
ts_req_utils.o: ../../include/openssl/symhacks.h ../../include/openssl/ts.h
ts_req_utils.o: ../../include/openssl/x509.h ../../include/openssl/x509_vfy.h
ts_req_utils.o: ../../include/openssl/x509v3.h ../cryptlib.h ts_req_utils.c
ts_rsp_print.o: ../../e_os.h ../../include/openssl/asn1.h
ts_rsp_print.o: ../../include/openssl/bio.h ../../include/openssl/bn.h
ts_rsp_print.o: ../../include/openssl/buffer.h ../../include/openssl/conf.h
ts_rsp_print.o: ../../include/openssl/crypto.h ../../include/openssl/dh.h
ts_rsp_print.o: ../../include/openssl/dsa.h ../../include/openssl/e_os2.h
ts_rsp_print.o: ../../include/openssl/ec.h ../../include/openssl/ecdh.h
ts_rsp_print.o: ../../include/openssl/ecdsa.h ../../include/openssl/err.h
ts_rsp_print.o: ../../include/openssl/evp.h ../../include/openssl/lhash.h
ts_rsp_print.o: ../../include/openssl/obj_mac.h ../../include/openssl/objects.h
ts_rsp_print.o: ../../include/openssl/opensslconf.h
ts_rsp_print.o: ../../include/openssl/opensslv.h
ts_rsp_print.o: ../../include/openssl/ossl_typ.h ../../include/openssl/pkcs7.h
ts_rsp_print.o: ../../include/openssl/rsa.h ../../include/openssl/safestack.h
ts_rsp_print.o: ../../include/openssl/sha.h ../../include/openssl/stack.h
ts_rsp_print.o: ../../include/openssl/symhacks.h ../../include/openssl/x509.h
ts_rsp_print.o: ../../include/openssl/x509_vfy.h ../../include/openssl/x509v3.h
ts_rsp_print.o: ../cryptlib.h ts.h ts_rsp_print.c
ts_rsp_sign.o: ../../e_os.h ../../include/openssl/asn1.h
ts_rsp_sign.o: ../../include/openssl/bio.h ../../include/openssl/buffer.h
ts_rsp_sign.o: ../../include/openssl/conf.h ../../include/openssl/crypto.h
ts_rsp_sign.o: ../../include/openssl/dh.h ../../include/openssl/dsa.h
ts_rsp_sign.o: ../../include/openssl/e_os2.h ../../include/openssl/ec.h
ts_rsp_sign.o: ../../include/openssl/ecdh.h ../../include/openssl/ecdsa.h
ts_rsp_sign.o: ../../include/openssl/err.h ../../include/openssl/evp.h
ts_rsp_sign.o: ../../include/openssl/lhash.h ../../include/openssl/obj_mac.h
ts_rsp_sign.o: ../../include/openssl/objects.h
ts_rsp_sign.o: ../../include/openssl/opensslconf.h
ts_rsp_sign.o: ../../include/openssl/opensslv.h
ts_rsp_sign.o: ../../include/openssl/ossl_typ.h ../../include/openssl/pkcs7.h
ts_rsp_sign.o: ../../include/openssl/rsa.h ../../include/openssl/safestack.h
ts_rsp_sign.o: ../../include/openssl/sha.h ../../include/openssl/stack.h
ts_rsp_sign.o: ../../include/openssl/symhacks.h ../../include/openssl/ts.h
ts_rsp_sign.o: ../../include/openssl/x509.h ../../include/openssl/x509_vfy.h
-ts_rsp_sign.o: ../../include/openssl/x509v3.h ../cryptlib.h ts_rsp_sign.c
+ts_rsp_sign.o: ../../include/openssl/x509v3.h ../cryptlib.h ../o_time.h
+ts_rsp_sign.o: ts_rsp_sign.c
ts_rsp_utils.o: ../../e_os.h ../../include/openssl/asn1.h
ts_rsp_utils.o: ../../include/openssl/bio.h ../../include/openssl/buffer.h
ts_rsp_utils.o: ../../include/openssl/conf.h ../../include/openssl/crypto.h
ts_rsp_utils.o: ../../include/openssl/dh.h ../../include/openssl/dsa.h
ts_rsp_utils.o: ../../include/openssl/e_os2.h ../../include/openssl/ec.h
ts_rsp_utils.o: ../../include/openssl/ecdh.h ../../include/openssl/ecdsa.h
ts_rsp_utils.o: ../../include/openssl/err.h ../../include/openssl/evp.h
ts_rsp_utils.o: ../../include/openssl/lhash.h ../../include/openssl/obj_mac.h
ts_rsp_utils.o: ../../include/openssl/objects.h
ts_rsp_utils.o: ../../include/openssl/opensslconf.h
ts_rsp_utils.o: ../../include/openssl/opensslv.h
ts_rsp_utils.o: ../../include/openssl/ossl_typ.h ../../include/openssl/pkcs7.h
ts_rsp_utils.o: ../../include/openssl/rsa.h ../../include/openssl/safestack.h
ts_rsp_utils.o: ../../include/openssl/sha.h ../../include/openssl/stack.h
ts_rsp_utils.o: ../../include/openssl/symhacks.h ../../include/openssl/ts.h
ts_rsp_utils.o: ../../include/openssl/x509.h ../../include/openssl/x509_vfy.h
ts_rsp_utils.o: ../../include/openssl/x509v3.h ../cryptlib.h ts_rsp_utils.c
ts_rsp_verify.o: ../../e_os.h ../../include/openssl/asn1.h
ts_rsp_verify.o: ../../include/openssl/bio.h ../../include/openssl/buffer.h
ts_rsp_verify.o: ../../include/openssl/conf.h ../../include/openssl/crypto.h
ts_rsp_verify.o: ../../include/openssl/dh.h ../../include/openssl/dsa.h
ts_rsp_verify.o: ../../include/openssl/e_os2.h ../../include/openssl/ec.h
ts_rsp_verify.o: ../../include/openssl/ecdh.h ../../include/openssl/ecdsa.h
ts_rsp_verify.o: ../../include/openssl/err.h ../../include/openssl/evp.h
ts_rsp_verify.o: ../../include/openssl/lhash.h ../../include/openssl/obj_mac.h
ts_rsp_verify.o: ../../include/openssl/objects.h
ts_rsp_verify.o: ../../include/openssl/opensslconf.h
ts_rsp_verify.o: ../../include/openssl/opensslv.h
ts_rsp_verify.o: ../../include/openssl/ossl_typ.h ../../include/openssl/pkcs7.h
ts_rsp_verify.o: ../../include/openssl/rsa.h ../../include/openssl/safestack.h
ts_rsp_verify.o: ../../include/openssl/sha.h ../../include/openssl/stack.h
ts_rsp_verify.o: ../../include/openssl/symhacks.h ../../include/openssl/ts.h
ts_rsp_verify.o: ../../include/openssl/x509.h ../../include/openssl/x509_vfy.h
ts_rsp_verify.o: ../../include/openssl/x509v3.h ../cryptlib.h ts_rsp_verify.c
ts_verify_ctx.o: ../../e_os.h ../../include/openssl/asn1.h
ts_verify_ctx.o: ../../include/openssl/bio.h ../../include/openssl/buffer.h
ts_verify_ctx.o: ../../include/openssl/conf.h ../../include/openssl/crypto.h
ts_verify_ctx.o: ../../include/openssl/dh.h ../../include/openssl/dsa.h
ts_verify_ctx.o: ../../include/openssl/e_os2.h ../../include/openssl/ec.h
ts_verify_ctx.o: ../../include/openssl/ecdh.h ../../include/openssl/ecdsa.h
ts_verify_ctx.o: ../../include/openssl/err.h ../../include/openssl/evp.h
ts_verify_ctx.o: ../../include/openssl/lhash.h ../../include/openssl/obj_mac.h
ts_verify_ctx.o: ../../include/openssl/objects.h
ts_verify_ctx.o: ../../include/openssl/opensslconf.h
ts_verify_ctx.o: ../../include/openssl/opensslv.h
ts_verify_ctx.o: ../../include/openssl/ossl_typ.h ../../include/openssl/pkcs7.h
ts_verify_ctx.o: ../../include/openssl/rsa.h ../../include/openssl/safestack.h
ts_verify_ctx.o: ../../include/openssl/sha.h ../../include/openssl/stack.h
ts_verify_ctx.o: ../../include/openssl/symhacks.h ../../include/openssl/ts.h
ts_verify_ctx.o: ../../include/openssl/x509.h ../../include/openssl/x509_vfy.h
ts_verify_ctx.o: ../../include/openssl/x509v3.h ../cryptlib.h ts_verify_ctx.c
diff --git a/crypto/ts/ts_rsp_sign.c b/crypto/ts/ts_rsp_sign.c
index db6ce3241f73..d55e903e836a 100644
--- a/crypto/ts/ts_rsp_sign.c
+++ b/crypto/ts/ts_rsp_sign.c
@@ -1,1020 +1,1022 @@
/* crypto/ts/ts_resp_sign.c */
/*
* Written by Zoltan Glozik (zglozik@stones.com) for the OpenSSL project
* 2002.
*/
/* ====================================================================
- * Copyright (c) 2006 The OpenSSL Project. All rights reserved.
+ * Copyright (c) 2006-2018 The OpenSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* licensing@OpenSSL.org.
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*
* This product includes cryptographic software written by Eric Young
* (eay@cryptsoft.com). This product includes software written by Tim
* Hudson (tjh@cryptsoft.com).
*
*/
#include "cryptlib.h"
+#include "o_time.h"
#if defined(OPENSSL_SYS_UNIX)
# include <sys/time.h>
#endif
#include <openssl/objects.h>
#include <openssl/ts.h>
#include <openssl/pkcs7.h>
/* Private function declarations. */
static ASN1_INTEGER *def_serial_cb(struct TS_resp_ctx *, void *);
static int def_time_cb(struct TS_resp_ctx *, void *, long *sec, long *usec);
static int def_extension_cb(struct TS_resp_ctx *, X509_EXTENSION *, void *);
static void TS_RESP_CTX_init(TS_RESP_CTX *ctx);
static void TS_RESP_CTX_cleanup(TS_RESP_CTX *ctx);
static int TS_RESP_check_request(TS_RESP_CTX *ctx);
static ASN1_OBJECT *TS_RESP_get_policy(TS_RESP_CTX *ctx);
static TS_TST_INFO *TS_RESP_create_tst_info(TS_RESP_CTX *ctx,
ASN1_OBJECT *policy);
static int TS_RESP_process_extensions(TS_RESP_CTX *ctx);
static int TS_RESP_sign(TS_RESP_CTX *ctx);
static ESS_SIGNING_CERT *ESS_SIGNING_CERT_new_init(X509 *signcert,
STACK_OF(X509) *certs);
static ESS_CERT_ID *ESS_CERT_ID_new_init(X509 *cert, int issuer_needed);
static int TS_TST_INFO_content_new(PKCS7 *p7);
static int ESS_add_signing_cert(PKCS7_SIGNER_INFO *si, ESS_SIGNING_CERT *sc);
static ASN1_GENERALIZEDTIME
*TS_RESP_set_genTime_with_precision(ASN1_GENERALIZEDTIME *, long, long,
unsigned);
/* Default callbacks for response generation. */
static ASN1_INTEGER *def_serial_cb(struct TS_resp_ctx *ctx, void *data)
{
ASN1_INTEGER *serial = ASN1_INTEGER_new();
if (!serial)
goto err;
if (!ASN1_INTEGER_set(serial, 1))
goto err;
return serial;
err:
TSerr(TS_F_DEF_SERIAL_CB, ERR_R_MALLOC_FAILURE);
TS_RESP_CTX_set_status_info(ctx, TS_STATUS_REJECTION,
"Error during serial number generation.");
return NULL;
}
#if defined(OPENSSL_SYS_UNIX)
/* Use the gettimeofday function call. */
static int def_time_cb(struct TS_resp_ctx *ctx, void *data,
long *sec, long *usec)
{
struct timeval tv;
if (gettimeofday(&tv, NULL) != 0) {
TSerr(TS_F_DEF_TIME_CB, TS_R_TIME_SYSCALL_ERROR);
TS_RESP_CTX_set_status_info(ctx, TS_STATUS_REJECTION,
"Time is not available.");
TS_RESP_CTX_add_failure_info(ctx, TS_INFO_TIME_NOT_AVAILABLE);
return 0;
}
/* Return time to caller. */
*sec = tv.tv_sec;
*usec = tv.tv_usec;
return 1;
}
#else
/* Use the time function call that provides only seconds precision. */
static int def_time_cb(struct TS_resp_ctx *ctx, void *data,
long *sec, long *usec)
{
time_t t;
if (time(&t) == (time_t)-1) {
TSerr(TS_F_DEF_TIME_CB, TS_R_TIME_SYSCALL_ERROR);
TS_RESP_CTX_set_status_info(ctx, TS_STATUS_REJECTION,
"Time is not available.");
TS_RESP_CTX_add_failure_info(ctx, TS_INFO_TIME_NOT_AVAILABLE);
return 0;
}
/* Return time to caller, only second precision. */
*sec = (long)t;
*usec = 0;
return 1;
}
#endif
static int def_extension_cb(struct TS_resp_ctx *ctx, X509_EXTENSION *ext,
void *data)
{
/* No extensions are processed here. */
TS_RESP_CTX_set_status_info(ctx, TS_STATUS_REJECTION,
"Unsupported extension.");
TS_RESP_CTX_add_failure_info(ctx, TS_INFO_UNACCEPTED_EXTENSION);
return 0;
}
/* TS_RESP_CTX management functions. */
TS_RESP_CTX *TS_RESP_CTX_new()
{
TS_RESP_CTX *ctx;
if (!(ctx = (TS_RESP_CTX *)OPENSSL_malloc(sizeof(TS_RESP_CTX)))) {
TSerr(TS_F_TS_RESP_CTX_NEW, ERR_R_MALLOC_FAILURE);
return NULL;
}
memset(ctx, 0, sizeof(TS_RESP_CTX));
/* Setting default callbacks. */
ctx->serial_cb = def_serial_cb;
ctx->time_cb = def_time_cb;
ctx->extension_cb = def_extension_cb;
return ctx;
}
void TS_RESP_CTX_free(TS_RESP_CTX *ctx)
{
if (!ctx)
return;
X509_free(ctx->signer_cert);
EVP_PKEY_free(ctx->signer_key);
sk_X509_pop_free(ctx->certs, X509_free);
sk_ASN1_OBJECT_pop_free(ctx->policies, ASN1_OBJECT_free);
ASN1_OBJECT_free(ctx->default_policy);
sk_EVP_MD_free(ctx->mds); /* No EVP_MD_free method exists. */
ASN1_INTEGER_free(ctx->seconds);
ASN1_INTEGER_free(ctx->millis);
ASN1_INTEGER_free(ctx->micros);
OPENSSL_free(ctx);
}
int TS_RESP_CTX_set_signer_cert(TS_RESP_CTX *ctx, X509 *signer)
{
if (X509_check_purpose(signer, X509_PURPOSE_TIMESTAMP_SIGN, 0) != 1) {
TSerr(TS_F_TS_RESP_CTX_SET_SIGNER_CERT,
TS_R_INVALID_SIGNER_CERTIFICATE_PURPOSE);
return 0;
}
if (ctx->signer_cert)
X509_free(ctx->signer_cert);
ctx->signer_cert = signer;
CRYPTO_add(&ctx->signer_cert->references, +1, CRYPTO_LOCK_X509);
return 1;
}
int TS_RESP_CTX_set_signer_key(TS_RESP_CTX *ctx, EVP_PKEY *key)
{
if (ctx->signer_key)
EVP_PKEY_free(ctx->signer_key);
ctx->signer_key = key;
CRYPTO_add(&ctx->signer_key->references, +1, CRYPTO_LOCK_EVP_PKEY);
return 1;
}
int TS_RESP_CTX_set_def_policy(TS_RESP_CTX *ctx, ASN1_OBJECT *def_policy)
{
if (ctx->default_policy)
ASN1_OBJECT_free(ctx->default_policy);
if (!(ctx->default_policy = OBJ_dup(def_policy)))
goto err;
return 1;
err:
TSerr(TS_F_TS_RESP_CTX_SET_DEF_POLICY, ERR_R_MALLOC_FAILURE);
return 0;
}
int TS_RESP_CTX_set_certs(TS_RESP_CTX *ctx, STACK_OF(X509) *certs)
{
if (ctx->certs) {
sk_X509_pop_free(ctx->certs, X509_free);
ctx->certs = NULL;
}
if (!certs)
return 1;
if (!(ctx->certs = X509_chain_up_ref(certs))) {
TSerr(TS_F_TS_RESP_CTX_SET_CERTS, ERR_R_MALLOC_FAILURE);
return 0;
}
return 1;
}
int TS_RESP_CTX_add_policy(TS_RESP_CTX *ctx, ASN1_OBJECT *policy)
{
ASN1_OBJECT *copy = NULL;
/* Create new policy stack if necessary. */
if (!ctx->policies && !(ctx->policies = sk_ASN1_OBJECT_new_null()))
goto err;
if (!(copy = OBJ_dup(policy)))
goto err;
if (!sk_ASN1_OBJECT_push(ctx->policies, copy))
goto err;
return 1;
err:
TSerr(TS_F_TS_RESP_CTX_ADD_POLICY, ERR_R_MALLOC_FAILURE);
ASN1_OBJECT_free(copy);
return 0;
}
int TS_RESP_CTX_add_md(TS_RESP_CTX *ctx, const EVP_MD *md)
{
/* Create new md stack if necessary. */
if (!ctx->mds && !(ctx->mds = sk_EVP_MD_new_null()))
goto err;
/* Add the shared md, no copy needed. */
if (!sk_EVP_MD_push(ctx->mds, (EVP_MD *)md))
goto err;
return 1;
err:
TSerr(TS_F_TS_RESP_CTX_ADD_MD, ERR_R_MALLOC_FAILURE);
return 0;
}
#define TS_RESP_CTX_accuracy_free(ctx) \
ASN1_INTEGER_free(ctx->seconds); \
ctx->seconds = NULL; \
ASN1_INTEGER_free(ctx->millis); \
ctx->millis = NULL; \
ASN1_INTEGER_free(ctx->micros); \
ctx->micros = NULL;
int TS_RESP_CTX_set_accuracy(TS_RESP_CTX *ctx,
int secs, int millis, int micros)
{
TS_RESP_CTX_accuracy_free(ctx);
if (secs && (!(ctx->seconds = ASN1_INTEGER_new())
|| !ASN1_INTEGER_set(ctx->seconds, secs)))
goto err;
if (millis && (!(ctx->millis = ASN1_INTEGER_new())
|| !ASN1_INTEGER_set(ctx->millis, millis)))
goto err;
if (micros && (!(ctx->micros = ASN1_INTEGER_new())
|| !ASN1_INTEGER_set(ctx->micros, micros)))
goto err;
return 1;
err:
TS_RESP_CTX_accuracy_free(ctx);
TSerr(TS_F_TS_RESP_CTX_SET_ACCURACY, ERR_R_MALLOC_FAILURE);
return 0;
}
void TS_RESP_CTX_add_flags(TS_RESP_CTX *ctx, int flags)
{
ctx->flags |= flags;
}
void TS_RESP_CTX_set_serial_cb(TS_RESP_CTX *ctx, TS_serial_cb cb, void *data)
{
ctx->serial_cb = cb;
ctx->serial_cb_data = data;
}
void TS_RESP_CTX_set_time_cb(TS_RESP_CTX *ctx, TS_time_cb cb, void *data)
{
ctx->time_cb = cb;
ctx->time_cb_data = data;
}
void TS_RESP_CTX_set_extension_cb(TS_RESP_CTX *ctx,
TS_extension_cb cb, void *data)
{
ctx->extension_cb = cb;
ctx->extension_cb_data = data;
}
int TS_RESP_CTX_set_status_info(TS_RESP_CTX *ctx,
int status, const char *text)
{
TS_STATUS_INFO *si = NULL;
ASN1_UTF8STRING *utf8_text = NULL;
int ret = 0;
if (!(si = TS_STATUS_INFO_new()))
goto err;
if (!ASN1_INTEGER_set(si->status, status))
goto err;
if (text) {
if (!(utf8_text = ASN1_UTF8STRING_new())
|| !ASN1_STRING_set(utf8_text, text, strlen(text)))
goto err;
if (!si->text && !(si->text = sk_ASN1_UTF8STRING_new_null()))
goto err;
if (!sk_ASN1_UTF8STRING_push(si->text, utf8_text))
goto err;
utf8_text = NULL; /* Ownership is lost. */
}
if (!TS_RESP_set_status_info(ctx->response, si))
goto err;
ret = 1;
err:
if (!ret)
TSerr(TS_F_TS_RESP_CTX_SET_STATUS_INFO, ERR_R_MALLOC_FAILURE);
TS_STATUS_INFO_free(si);
ASN1_UTF8STRING_free(utf8_text);
return ret;
}
int TS_RESP_CTX_set_status_info_cond(TS_RESP_CTX *ctx,
int status, const char *text)
{
int ret = 1;
TS_STATUS_INFO *si = TS_RESP_get_status_info(ctx->response);
if (ASN1_INTEGER_get(si->status) == TS_STATUS_GRANTED) {
/* Status has not been set, set it now. */
ret = TS_RESP_CTX_set_status_info(ctx, status, text);
}
return ret;
}
int TS_RESP_CTX_add_failure_info(TS_RESP_CTX *ctx, int failure)
{
TS_STATUS_INFO *si = TS_RESP_get_status_info(ctx->response);
if (!si->failure_info && !(si->failure_info = ASN1_BIT_STRING_new()))
goto err;
if (!ASN1_BIT_STRING_set_bit(si->failure_info, failure, 1))
goto err;
return 1;
err:
TSerr(TS_F_TS_RESP_CTX_ADD_FAILURE_INFO, ERR_R_MALLOC_FAILURE);
return 0;
}
TS_REQ *TS_RESP_CTX_get_request(TS_RESP_CTX *ctx)
{
return ctx->request;
}
TS_TST_INFO *TS_RESP_CTX_get_tst_info(TS_RESP_CTX *ctx)
{
return ctx->tst_info;
}
int TS_RESP_CTX_set_clock_precision_digits(TS_RESP_CTX *ctx,
unsigned precision)
{
if (precision > TS_MAX_CLOCK_PRECISION_DIGITS)
return 0;
ctx->clock_precision_digits = precision;
return 1;
}
/* Main entry method of the response generation. */
TS_RESP *TS_RESP_create_response(TS_RESP_CTX *ctx, BIO *req_bio)
{
ASN1_OBJECT *policy;
TS_RESP *response;
int result = 0;
TS_RESP_CTX_init(ctx);
/* Creating the response object. */
if (!(ctx->response = TS_RESP_new())) {
TSerr(TS_F_TS_RESP_CREATE_RESPONSE, ERR_R_MALLOC_FAILURE);
goto end;
}
/* Parsing DER request. */
if (!(ctx->request = d2i_TS_REQ_bio(req_bio, NULL))) {
TS_RESP_CTX_set_status_info(ctx, TS_STATUS_REJECTION,
"Bad request format or " "system error.");
TS_RESP_CTX_add_failure_info(ctx, TS_INFO_BAD_DATA_FORMAT);
goto end;
}
/* Setting default status info. */
if (!TS_RESP_CTX_set_status_info(ctx, TS_STATUS_GRANTED, NULL))
goto end;
/* Checking the request format. */
if (!TS_RESP_check_request(ctx))
goto end;
/* Checking acceptable policies. */
if (!(policy = TS_RESP_get_policy(ctx)))
goto end;
/* Creating the TS_TST_INFO object. */
if (!(ctx->tst_info = TS_RESP_create_tst_info(ctx, policy)))
goto end;
/* Processing extensions. */
if (!TS_RESP_process_extensions(ctx))
goto end;
/* Generating the signature. */
if (!TS_RESP_sign(ctx))
goto end;
/* Everything was successful. */
result = 1;
end:
if (!result) {
TSerr(TS_F_TS_RESP_CREATE_RESPONSE, TS_R_RESPONSE_SETUP_ERROR);
if (ctx->response != NULL) {
if (TS_RESP_CTX_set_status_info_cond(ctx,
TS_STATUS_REJECTION,
"Error during response "
"generation.") == 0) {
TS_RESP_free(ctx->response);
ctx->response = NULL;
}
}
}
response = ctx->response;
ctx->response = NULL; /* Ownership will be returned to caller. */
TS_RESP_CTX_cleanup(ctx);
return response;
}
/* Initializes the variable part of the context. */
static void TS_RESP_CTX_init(TS_RESP_CTX *ctx)
{
ctx->request = NULL;
ctx->response = NULL;
ctx->tst_info = NULL;
}
/* Cleans up the variable part of the context. */
static void TS_RESP_CTX_cleanup(TS_RESP_CTX *ctx)
{
TS_REQ_free(ctx->request);
ctx->request = NULL;
TS_RESP_free(ctx->response);
ctx->response = NULL;
TS_TST_INFO_free(ctx->tst_info);
ctx->tst_info = NULL;
}
/* Checks the format and content of the request. */
static int TS_RESP_check_request(TS_RESP_CTX *ctx)
{
TS_REQ *request = ctx->request;
TS_MSG_IMPRINT *msg_imprint;
X509_ALGOR *md_alg;
int md_alg_id;
const ASN1_OCTET_STRING *digest;
EVP_MD *md = NULL;
int i;
/* Checking request version. */
if (TS_REQ_get_version(request) != 1) {
TS_RESP_CTX_set_status_info(ctx, TS_STATUS_REJECTION,
"Bad request version.");
TS_RESP_CTX_add_failure_info(ctx, TS_INFO_BAD_REQUEST);
return 0;
}
/* Checking message digest algorithm. */
msg_imprint = TS_REQ_get_msg_imprint(request);
md_alg = TS_MSG_IMPRINT_get_algo(msg_imprint);
md_alg_id = OBJ_obj2nid(md_alg->algorithm);
for (i = 0; !md && i < sk_EVP_MD_num(ctx->mds); ++i) {
EVP_MD *current_md = sk_EVP_MD_value(ctx->mds, i);
if (md_alg_id == EVP_MD_type(current_md))
md = current_md;
}
if (!md) {
TS_RESP_CTX_set_status_info(ctx, TS_STATUS_REJECTION,
"Message digest algorithm is "
"not supported.");
TS_RESP_CTX_add_failure_info(ctx, TS_INFO_BAD_ALG);
return 0;
}
/* No message digest takes parameter. */
if (md_alg->parameter && ASN1_TYPE_get(md_alg->parameter) != V_ASN1_NULL) {
TS_RESP_CTX_set_status_info(ctx, TS_STATUS_REJECTION,
"Superfluous message digest "
"parameter.");
TS_RESP_CTX_add_failure_info(ctx, TS_INFO_BAD_ALG);
return 0;
}
/* Checking message digest size. */
digest = TS_MSG_IMPRINT_get_msg(msg_imprint);
if (digest->length != EVP_MD_size(md)) {
TS_RESP_CTX_set_status_info(ctx, TS_STATUS_REJECTION,
"Bad message digest.");
TS_RESP_CTX_add_failure_info(ctx, TS_INFO_BAD_DATA_FORMAT);
return 0;
}
return 1;
}
/* Returns the TSA policy based on the requested and acceptable policies. */
static ASN1_OBJECT *TS_RESP_get_policy(TS_RESP_CTX *ctx)
{
ASN1_OBJECT *requested = TS_REQ_get_policy_id(ctx->request);
ASN1_OBJECT *policy = NULL;
int i;
if (ctx->default_policy == NULL) {
TSerr(TS_F_TS_RESP_GET_POLICY, TS_R_INVALID_NULL_POINTER);
return NULL;
}
/*
* Return the default policy if none is requested or the default is
* requested.
*/
if (!requested || !OBJ_cmp(requested, ctx->default_policy))
policy = ctx->default_policy;
/* Check if the policy is acceptable. */
for (i = 0; !policy && i < sk_ASN1_OBJECT_num(ctx->policies); ++i) {
ASN1_OBJECT *current = sk_ASN1_OBJECT_value(ctx->policies, i);
if (!OBJ_cmp(requested, current))
policy = current;
}
if (!policy) {
TSerr(TS_F_TS_RESP_GET_POLICY, TS_R_UNACCEPTABLE_POLICY);
TS_RESP_CTX_set_status_info(ctx, TS_STATUS_REJECTION,
"Requested policy is not " "supported.");
TS_RESP_CTX_add_failure_info(ctx, TS_INFO_UNACCEPTED_POLICY);
}
return policy;
}
/* Creates the TS_TST_INFO object based on the settings of the context. */
static TS_TST_INFO *TS_RESP_create_tst_info(TS_RESP_CTX *ctx,
ASN1_OBJECT *policy)
{
int result = 0;
TS_TST_INFO *tst_info = NULL;
ASN1_INTEGER *serial = NULL;
ASN1_GENERALIZEDTIME *asn1_time = NULL;
long sec, usec;
TS_ACCURACY *accuracy = NULL;
const ASN1_INTEGER *nonce;
GENERAL_NAME *tsa_name = NULL;
if (!(tst_info = TS_TST_INFO_new()))
goto end;
if (!TS_TST_INFO_set_version(tst_info, 1))
goto end;
if (!TS_TST_INFO_set_policy_id(tst_info, policy))
goto end;
if (!TS_TST_INFO_set_msg_imprint(tst_info, ctx->request->msg_imprint))
goto end;
if (!(serial = (*ctx->serial_cb) (ctx, ctx->serial_cb_data))
|| !TS_TST_INFO_set_serial(tst_info, serial))
goto end;
if (!(*ctx->time_cb) (ctx, ctx->time_cb_data, &sec, &usec)
|| !(asn1_time = TS_RESP_set_genTime_with_precision(NULL,
sec, usec,
ctx->clock_precision_digits))
|| !TS_TST_INFO_set_time(tst_info, asn1_time))
goto end;
/* Setting accuracy if needed. */
if ((ctx->seconds || ctx->millis || ctx->micros)
&& !(accuracy = TS_ACCURACY_new()))
goto end;
if (ctx->seconds && !TS_ACCURACY_set_seconds(accuracy, ctx->seconds))
goto end;
if (ctx->millis && !TS_ACCURACY_set_millis(accuracy, ctx->millis))
goto end;
if (ctx->micros && !TS_ACCURACY_set_micros(accuracy, ctx->micros))
goto end;
if (accuracy && !TS_TST_INFO_set_accuracy(tst_info, accuracy))
goto end;
/* Setting ordering. */
if ((ctx->flags & TS_ORDERING)
&& !TS_TST_INFO_set_ordering(tst_info, 1))
goto end;
/* Setting nonce if needed. */
if ((nonce = TS_REQ_get_nonce(ctx->request)) != NULL
&& !TS_TST_INFO_set_nonce(tst_info, nonce))
goto end;
/* Setting TSA name to subject of signer certificate. */
if (ctx->flags & TS_TSA_NAME) {
if (!(tsa_name = GENERAL_NAME_new()))
goto end;
tsa_name->type = GEN_DIRNAME;
tsa_name->d.dirn =
X509_NAME_dup(ctx->signer_cert->cert_info->subject);
if (!tsa_name->d.dirn)
goto end;
if (!TS_TST_INFO_set_tsa(tst_info, tsa_name))
goto end;
}
result = 1;
end:
if (!result) {
TS_TST_INFO_free(tst_info);
tst_info = NULL;
TSerr(TS_F_TS_RESP_CREATE_TST_INFO, TS_R_TST_INFO_SETUP_ERROR);
TS_RESP_CTX_set_status_info_cond(ctx, TS_STATUS_REJECTION,
"Error during TSTInfo "
"generation.");
}
GENERAL_NAME_free(tsa_name);
TS_ACCURACY_free(accuracy);
ASN1_GENERALIZEDTIME_free(asn1_time);
ASN1_INTEGER_free(serial);
return tst_info;
}
/* Processing the extensions of the request. */
static int TS_RESP_process_extensions(TS_RESP_CTX *ctx)
{
STACK_OF(X509_EXTENSION) *exts = TS_REQ_get_exts(ctx->request);
int i;
int ok = 1;
for (i = 0; ok && i < sk_X509_EXTENSION_num(exts); ++i) {
X509_EXTENSION *ext = sk_X509_EXTENSION_value(exts, i);
/*
* XXXXX The last argument was previously (void *)ctx->extension_cb,
* but ISO C doesn't permit converting a function pointer to void *.
* For lack of better information, I'm placing a NULL there instead.
* The callback can pick its own address out from the ctx anyway...
*/
ok = (*ctx->extension_cb) (ctx, ext, NULL);
}
return ok;
}
/* Functions for signing the TS_TST_INFO structure of the context. */
static int TS_RESP_sign(TS_RESP_CTX *ctx)
{
int ret = 0;
PKCS7 *p7 = NULL;
PKCS7_SIGNER_INFO *si;
STACK_OF(X509) *certs; /* Certificates to include in sc. */
ESS_SIGNING_CERT *sc = NULL;
ASN1_OBJECT *oid;
BIO *p7bio = NULL;
int i;
/* Check if signcert and pkey match. */
if (!X509_check_private_key(ctx->signer_cert, ctx->signer_key)) {
TSerr(TS_F_TS_RESP_SIGN, TS_R_PRIVATE_KEY_DOES_NOT_MATCH_CERTIFICATE);
goto err;
}
/* Create a new PKCS7 signed object. */
if (!(p7 = PKCS7_new())) {
TSerr(TS_F_TS_RESP_SIGN, ERR_R_MALLOC_FAILURE);
goto err;
}
if (!PKCS7_set_type(p7, NID_pkcs7_signed))
goto err;
/* Force SignedData version to be 3 instead of the default 1. */
if (!ASN1_INTEGER_set(p7->d.sign->version, 3))
goto err;
/* Add signer certificate and optional certificate chain. */
if (TS_REQ_get_cert_req(ctx->request)) {
PKCS7_add_certificate(p7, ctx->signer_cert);
if (ctx->certs) {
for (i = 0; i < sk_X509_num(ctx->certs); ++i) {
X509 *cert = sk_X509_value(ctx->certs, i);
PKCS7_add_certificate(p7, cert);
}
}
}
/* Add a new signer info. */
if (!(si = PKCS7_add_signature(p7, ctx->signer_cert,
ctx->signer_key, EVP_sha1()))) {
TSerr(TS_F_TS_RESP_SIGN, TS_R_PKCS7_ADD_SIGNATURE_ERROR);
goto err;
}
/* Add content type signed attribute to the signer info. */
oid = OBJ_nid2obj(NID_id_smime_ct_TSTInfo);
if (!PKCS7_add_signed_attribute(si, NID_pkcs9_contentType,
V_ASN1_OBJECT, oid)) {
TSerr(TS_F_TS_RESP_SIGN, TS_R_PKCS7_ADD_SIGNED_ATTR_ERROR);
goto err;
}
/*
* Create the ESS SigningCertificate attribute which contains the signer
* certificate id and optionally the certificate chain.
*/
certs = ctx->flags & TS_ESS_CERT_ID_CHAIN ? ctx->certs : NULL;
if (!(sc = ESS_SIGNING_CERT_new_init(ctx->signer_cert, certs)))
goto err;
/* Add SigningCertificate signed attribute to the signer info. */
if (!ESS_add_signing_cert(si, sc)) {
TSerr(TS_F_TS_RESP_SIGN, TS_R_ESS_ADD_SIGNING_CERT_ERROR);
goto err;
}
/* Add a new empty NID_id_smime_ct_TSTInfo encapsulated content. */
if (!TS_TST_INFO_content_new(p7))
goto err;
/* Add the DER encoded tst_info to the PKCS7 structure. */
if (!(p7bio = PKCS7_dataInit(p7, NULL))) {
TSerr(TS_F_TS_RESP_SIGN, ERR_R_MALLOC_FAILURE);
goto err;
}
/* Convert tst_info to DER. */
if (!i2d_TS_TST_INFO_bio(p7bio, ctx->tst_info)) {
TSerr(TS_F_TS_RESP_SIGN, TS_R_TS_DATASIGN);
goto err;
}
/* Create the signature and add it to the signer info. */
if (!PKCS7_dataFinal(p7, p7bio)) {
TSerr(TS_F_TS_RESP_SIGN, TS_R_TS_DATASIGN);
goto err;
}
/* Set new PKCS7 and TST_INFO objects. */
TS_RESP_set_tst_info(ctx->response, p7, ctx->tst_info);
p7 = NULL; /* Ownership is lost. */
ctx->tst_info = NULL; /* Ownership is lost. */
ret = 1;
err:
if (!ret)
TS_RESP_CTX_set_status_info_cond(ctx, TS_STATUS_REJECTION,
"Error during signature "
"generation.");
BIO_free_all(p7bio);
ESS_SIGNING_CERT_free(sc);
PKCS7_free(p7);
return ret;
}
static ESS_SIGNING_CERT *ESS_SIGNING_CERT_new_init(X509 *signcert,
STACK_OF(X509) *certs)
{
ESS_CERT_ID *cid;
ESS_SIGNING_CERT *sc = NULL;
int i;
/* Creating the ESS_CERT_ID stack. */
if (!(sc = ESS_SIGNING_CERT_new()))
goto err;
if (!sc->cert_ids && !(sc->cert_ids = sk_ESS_CERT_ID_new_null()))
goto err;
/* Adding the signing certificate id. */
if (!(cid = ESS_CERT_ID_new_init(signcert, 0))
|| !sk_ESS_CERT_ID_push(sc->cert_ids, cid))
goto err;
/* Adding the certificate chain ids. */
for (i = 0; i < sk_X509_num(certs); ++i) {
X509 *cert = sk_X509_value(certs, i);
if (!(cid = ESS_CERT_ID_new_init(cert, 1))
|| !sk_ESS_CERT_ID_push(sc->cert_ids, cid))
goto err;
}
return sc;
err:
ESS_SIGNING_CERT_free(sc);
TSerr(TS_F_ESS_SIGNING_CERT_NEW_INIT, ERR_R_MALLOC_FAILURE);
return NULL;
}
static ESS_CERT_ID *ESS_CERT_ID_new_init(X509 *cert, int issuer_needed)
{
ESS_CERT_ID *cid = NULL;
GENERAL_NAME *name = NULL;
/* Recompute SHA1 hash of certificate if necessary (side effect). */
X509_check_purpose(cert, -1, 0);
if (!(cid = ESS_CERT_ID_new()))
goto err;
if (!ASN1_OCTET_STRING_set(cid->hash, cert->sha1_hash,
sizeof(cert->sha1_hash)))
goto err;
/* Setting the issuer/serial if requested. */
if (issuer_needed) {
/* Creating issuer/serial structure. */
if (!cid->issuer_serial
&& !(cid->issuer_serial = ESS_ISSUER_SERIAL_new()))
goto err;
/* Creating general name from the certificate issuer. */
if (!(name = GENERAL_NAME_new()))
goto err;
name->type = GEN_DIRNAME;
if (!(name->d.dirn = X509_NAME_dup(cert->cert_info->issuer)))
goto err;
if (!sk_GENERAL_NAME_push(cid->issuer_serial->issuer, name))
goto err;
name = NULL; /* Ownership is lost. */
/* Setting the serial number. */
ASN1_INTEGER_free(cid->issuer_serial->serial);
if (!(cid->issuer_serial->serial =
ASN1_INTEGER_dup(cert->cert_info->serialNumber)))
goto err;
}
return cid;
err:
GENERAL_NAME_free(name);
ESS_CERT_ID_free(cid);
TSerr(TS_F_ESS_CERT_ID_NEW_INIT, ERR_R_MALLOC_FAILURE);
return NULL;
}
static int TS_TST_INFO_content_new(PKCS7 *p7)
{
PKCS7 *ret = NULL;
ASN1_OCTET_STRING *octet_string = NULL;
/* Create new encapsulated NID_id_smime_ct_TSTInfo content. */
if (!(ret = PKCS7_new()))
goto err;
if (!(ret->d.other = ASN1_TYPE_new()))
goto err;
ret->type = OBJ_nid2obj(NID_id_smime_ct_TSTInfo);
if (!(octet_string = ASN1_OCTET_STRING_new()))
goto err;
ASN1_TYPE_set(ret->d.other, V_ASN1_OCTET_STRING, octet_string);
octet_string = NULL;
/* Add encapsulated content to signed PKCS7 structure. */
if (!PKCS7_set_content(p7, ret))
goto err;
return 1;
err:
ASN1_OCTET_STRING_free(octet_string);
PKCS7_free(ret);
return 0;
}
static int ESS_add_signing_cert(PKCS7_SIGNER_INFO *si, ESS_SIGNING_CERT *sc)
{
ASN1_STRING *seq = NULL;
unsigned char *p, *pp = NULL;
int len;
len = i2d_ESS_SIGNING_CERT(sc, NULL);
if (!(pp = (unsigned char *)OPENSSL_malloc(len))) {
TSerr(TS_F_ESS_ADD_SIGNING_CERT, ERR_R_MALLOC_FAILURE);
goto err;
}
p = pp;
i2d_ESS_SIGNING_CERT(sc, &p);
if (!(seq = ASN1_STRING_new()) || !ASN1_STRING_set(seq, pp, len)) {
TSerr(TS_F_ESS_ADD_SIGNING_CERT, ERR_R_MALLOC_FAILURE);
goto err;
}
OPENSSL_free(pp);
pp = NULL;
return PKCS7_add_signed_attribute(si,
NID_id_smime_aa_signingCertificate,
V_ASN1_SEQUENCE, seq);
err:
ASN1_STRING_free(seq);
OPENSSL_free(pp);
return 0;
}
static ASN1_GENERALIZEDTIME
*TS_RESP_set_genTime_with_precision(ASN1_GENERALIZEDTIME *asn1_time,
long sec, long usec, unsigned precision)
{
time_t time_sec = (time_t)sec;
struct tm *tm = NULL;
+ struct tm result = {0};
char genTime_str[17 + TS_MAX_CLOCK_PRECISION_DIGITS];
char *p = genTime_str;
char *p_end = genTime_str + sizeof(genTime_str);
if (precision > TS_MAX_CLOCK_PRECISION_DIGITS)
goto err;
- if (!(tm = gmtime(&time_sec)))
+ if (!(tm = OPENSSL_gmtime(&time_sec, &result)))
goto err;
/*
* Put "genTime_str" in GeneralizedTime format. We work around the
* restrictions imposed by rfc3280 (i.e. "GeneralizedTime values MUST
* NOT include fractional seconds") and OpenSSL related functions to
* meet the rfc3161 requirement: "GeneralizedTime syntax can include
* fraction-of-second details".
*/
p += BIO_snprintf(p, p_end - p,
"%04d%02d%02d%02d%02d%02d",
tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday,
tm->tm_hour, tm->tm_min, tm->tm_sec);
if (precision > 0) {
/* Add fraction of seconds (leave space for dot and null). */
BIO_snprintf(p, 2 + precision, ".%06ld", usec);
/*
* We cannot use the snprintf return value, because it might have
* been truncated.
*/
p += strlen(p);
/*
* To make things a bit harder, X.690 | ISO/IEC 8825-1 provides the
* following restrictions for a DER-encoding, which OpenSSL
* (specifically ASN1_GENERALIZEDTIME_check() function) doesn't
* support: "The encoding MUST terminate with a "Z" (which means
* "Zulu" time). The decimal point element, if present, MUST be the
* point option ".". The fractional-seconds elements, if present,
* MUST omit all trailing 0's; if the elements correspond to 0, they
* MUST be wholly omitted, and the decimal point element also MUST be
* omitted."
*/
/*
* Remove trailing zeros. The dot guarantees the exit condition of
* this loop even if all the digits are zero.
*/
while (*--p == '0')
/*
* empty
*/ ;
/* p points to either the dot or the last non-zero digit. */
if (*p != '.')
++p;
}
/* Add the trailing Z and the terminating null. */
*p++ = 'Z';
*p++ = '\0';
/* Now call OpenSSL to check and set our genTime value */
if (!asn1_time && !(asn1_time = M_ASN1_GENERALIZEDTIME_new()))
goto err;
if (!ASN1_GENERALIZEDTIME_set_string(asn1_time, genTime_str)) {
ASN1_GENERALIZEDTIME_free(asn1_time);
goto err;
}
return asn1_time;
err:
TSerr(TS_F_TS_RESP_SET_GENTIME_WITH_PRECISION, TS_R_COULD_NOT_SET_TIME);
return NULL;
}
diff --git a/crypto/ui/ui_openssl.c b/crypto/ui/ui_openssl.c
index 17d14f58427a..8a43590319fa 100644
--- a/crypto/ui/ui_openssl.c
+++ b/crypto/ui/ui_openssl.c
@@ -1,734 +1,734 @@
/* crypto/ui/ui_openssl.c */
/*
* Written by Richard Levitte (richard@levitte.org) and others for the
* OpenSSL project 2001.
*/
/* ====================================================================
* Copyright (c) 2001 The OpenSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* openssl-core@openssl.org.
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.openssl.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*
* This product includes cryptographic software written by Eric Young
* (eay@cryptsoft.com). This product includes software written by Tim
* Hudson (tjh@cryptsoft.com).
*
*/
/*-
* The lowest level part of this file was previously in crypto/des/read_pwd.c,
* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
#include <openssl/e_os2.h>
/*
* need for #define _POSIX_C_SOURCE arises whenever you pass -ansi to gcc
* [maybe others?], because it masks interfaces not discussed in standard,
* sigaction and fileno included. -pedantic would be more appropriate for the
* intended purposes, but we can't prevent users from adding -ansi.
*/
#if defined(OPENSSL_SYSNAME_VXWORKS)
# include <sys/types.h>
#endif
#if !defined(_POSIX_C_SOURCE) && defined(OPENSSL_SYS_VMS)
# ifndef _POSIX_C_SOURCE
# define _POSIX_C_SOURCE 2
# endif
#endif
#include <signal.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#if !defined(OPENSSL_SYS_MSDOS) && !defined(OPENSSL_SYS_VMS)
# ifdef OPENSSL_UNISTD
# include OPENSSL_UNISTD
# else
# include <unistd.h>
# endif
/*
* If unistd.h defines _POSIX_VERSION, we conclude that we are on a POSIX
* system and have sigaction and termios.
*/
# if defined(_POSIX_VERSION)
# define SIGACTION
# if !defined(TERMIOS) && !defined(TERMIO) && !defined(SGTTY)
# define TERMIOS
# endif
# endif
#endif
#ifdef WIN16TTY
# undef OPENSSL_SYS_WIN16
# undef WIN16
# undef _WINDOWS
# include <graph.h>
#endif
/* 06-Apr-92 Luke Brennan Support for VMS */
#include "ui_locl.h"
#include "cryptlib.h"
#ifdef OPENSSL_SYS_VMS /* prototypes for sys$whatever */
# include <starlet.h>
# ifdef __DECC
# pragma message disable DOLLARID
# endif
#endif
#ifdef WIN_CONSOLE_BUG
# include <windows.h>
# ifndef OPENSSL_SYS_WINCE
# include <wincon.h>
# endif
#endif
/*
* There are 5 types of terminal interface supported, TERMIO, TERMIOS, VMS,
* MSDOS and SGTTY.
*
* If someone defines one of the macros TERMIO, TERMIOS or SGTTY, it will
* remain respected. Otherwise, we default to TERMIOS except for a few
* systems that require something different.
*
* Note: we do not use SGTTY unless it's defined by the configuration. We
* may eventually opt to remove it's use entirely.
*/
#if !defined(TERMIOS) && !defined(TERMIO) && !defined(SGTTY)
# if defined(_LIBC)
# undef TERMIOS
# define TERMIO
# undef SGTTY
/*
* We know that VMS, MSDOS, VXWORKS, NETWARE use entirely other mechanisms.
* MAC_OS_GUSI_SOURCE should probably go away, but that needs to be confirmed.
*/
# elif !defined(OPENSSL_SYS_VMS) \
&& !defined(OPENSSL_SYS_MSDOS) \
&& !defined(OPENSSL_SYS_MACINTOSH_CLASSIC) \
&& !defined(MAC_OS_GUSI_SOURCE) \
&& !defined(OPENSSL_SYS_VXWORKS) \
&& !defined(OPENSSL_SYS_NETWARE)
# define TERMIOS
# undef TERMIO
# undef SGTTY
# endif
#endif
#ifdef TERMIOS
# include <termios.h>
# define TTY_STRUCT struct termios
# define TTY_FLAGS c_lflag
# define TTY_get(tty,data) tcgetattr(tty,data)
# define TTY_set(tty,data) tcsetattr(tty,TCSANOW,data)
#endif
#ifdef TERMIO
# include <termio.h>
# define TTY_STRUCT struct termio
# define TTY_FLAGS c_lflag
# define TTY_get(tty,data) ioctl(tty,TCGETA,data)
# define TTY_set(tty,data) ioctl(tty,TCSETA,data)
#endif
#ifdef SGTTY
# include <sgtty.h>
# define TTY_STRUCT struct sgttyb
# define TTY_FLAGS sg_flags
# define TTY_get(tty,data) ioctl(tty,TIOCGETP,data)
# define TTY_set(tty,data) ioctl(tty,TIOCSETP,data)
#endif
#if !defined(_LIBC) && !defined(OPENSSL_SYS_MSDOS) && !defined(OPENSSL_SYS_VMS) && !defined(OPENSSL_SYS_MACINTOSH_CLASSIC) && !defined(OPENSSL_SYS_SUNOS)
# include <sys/ioctl.h>
#endif
#ifdef OPENSSL_SYS_MSDOS
# include <conio.h>
#endif
#ifdef OPENSSL_SYS_VMS
# include <ssdef.h>
# include <iodef.h>
# include <ttdef.h>
# include <descrip.h>
struct IOSB {
short iosb$w_value;
short iosb$w_count;
long iosb$l_info;
};
#endif
#ifdef OPENSSL_SYS_SUNOS
typedef int sig_atomic_t;
#endif
#if defined(OPENSSL_SYS_MACINTOSH_CLASSIC) || defined(MAC_OS_GUSI_SOURCE) || defined(OPENSSL_SYS_NETWARE)
/*
* This one needs work. As a matter of fact the code is unoperational
* and this is only a trick to get it compiled.
* <appro@fy.chalmers.se>
*/
# define TTY_STRUCT int
#endif
#ifndef NX509_SIG
# define NX509_SIG 32
#endif
/* Define globals. They are protected by a lock */
#ifdef SIGACTION
static struct sigaction savsig[NX509_SIG];
#else
static void (*savsig[NX509_SIG]) (int);
#endif
#ifdef OPENSSL_SYS_VMS
static struct IOSB iosb;
static $DESCRIPTOR(terminal, "TT");
static long tty_orig[3], tty_new[3]; /* XXX Is there any guarantee that this
* will always suffice for the actual
* structures? */
static long status;
static unsigned short channel = 0;
#else
# if !defined(OPENSSL_SYS_MSDOS) || defined(__DJGPP__)
static TTY_STRUCT tty_orig, tty_new;
# endif
#endif
static FILE *tty_in, *tty_out;
static int is_a_tty;
/* Declare static functions */
#if !defined(OPENSSL_SYS_WIN16) && !defined(OPENSSL_SYS_WINCE)
static int read_till_nl(FILE *);
static void recsig(int);
static void pushsig(void);
static void popsig(void);
#endif
#if defined(OPENSSL_SYS_MSDOS) && !defined(OPENSSL_SYS_WIN16)
static int noecho_fgets(char *buf, int size, FILE *tty);
#endif
static int read_string_inner(UI *ui, UI_STRING *uis, int echo, int strip_nl);
static int read_string(UI *ui, UI_STRING *uis);
static int write_string(UI *ui, UI_STRING *uis);
static int open_console(UI *ui);
static int echo_console(UI *ui);
static int noecho_console(UI *ui);
static int close_console(UI *ui);
static UI_METHOD ui_openssl = {
"OpenSSL default user interface",
open_console,
write_string,
NULL, /* No flusher is needed for command lines */
read_string,
close_console,
NULL
};
/* The method with all the built-in thingies */
UI_METHOD *UI_OpenSSL(void)
{
return &ui_openssl;
}
/*
* The following function makes sure that info and error strings are printed
* before any prompt.
*/
static int write_string(UI *ui, UI_STRING *uis)
{
switch (UI_get_string_type(uis)) {
case UIT_ERROR:
case UIT_INFO:
fputs(UI_get0_output_string(uis), tty_out);
fflush(tty_out);
break;
default:
break;
}
return 1;
}
static int read_string(UI *ui, UI_STRING *uis)
{
int ok = 0;
switch (UI_get_string_type(uis)) {
case UIT_BOOLEAN:
fputs(UI_get0_output_string(uis), tty_out);
fputs(UI_get0_action_string(uis), tty_out);
fflush(tty_out);
return read_string_inner(ui, uis,
UI_get_input_flags(uis) & UI_INPUT_FLAG_ECHO,
0);
case UIT_PROMPT:
fputs(UI_get0_output_string(uis), tty_out);
fflush(tty_out);
return read_string_inner(ui, uis,
UI_get_input_flags(uis) & UI_INPUT_FLAG_ECHO,
1);
case UIT_VERIFY:
fprintf(tty_out, "Verifying - %s", UI_get0_output_string(uis));
fflush(tty_out);
if ((ok = read_string_inner(ui, uis,
UI_get_input_flags(uis) &
UI_INPUT_FLAG_ECHO, 1)) <= 0)
return ok;
if (strcmp(UI_get0_result_string(uis), UI_get0_test_string(uis)) != 0) {
fprintf(tty_out, "Verify failure\n");
fflush(tty_out);
return 0;
}
break;
default:
break;
}
return 1;
}
#if !defined(OPENSSL_SYS_WIN16) && !defined(OPENSSL_SYS_WINCE)
/* Internal functions to read a string without echoing */
static int read_till_nl(FILE *in)
{
# define SIZE 4
char buf[SIZE + 1];
do {
if (!fgets(buf, SIZE, in))
return 0;
} while (strchr(buf, '\n') == NULL);
return 1;
}
static volatile sig_atomic_t intr_signal;
#endif
static int read_string_inner(UI *ui, UI_STRING *uis, int echo, int strip_nl)
{
static int ps;
int ok;
char result[BUFSIZ];
int maxsize = BUFSIZ - 1;
#if !defined(OPENSSL_SYS_WIN16) && !defined(OPENSSL_SYS_WINCE)
char *p;
intr_signal = 0;
ok = 0;
ps = 0;
pushsig();
ps = 1;
if (!echo && !noecho_console(ui))
goto error;
ps = 2;
result[0] = '\0';
# ifdef OPENSSL_SYS_MSDOS
if (!echo) {
noecho_fgets(result, maxsize, tty_in);
p = result; /* FIXME: noecho_fgets doesn't return errors */
} else
p = fgets(result, maxsize, tty_in);
# else
p = fgets(result, maxsize, tty_in);
# endif
if (p == NULL)
goto error;
if (feof(tty_in))
goto error;
if (ferror(tty_in))
goto error;
if ((p = (char *)strchr(result, '\n')) != NULL) {
if (strip_nl)
*p = '\0';
} else if (!read_till_nl(tty_in))
goto error;
if (UI_set_result(ui, uis, result) >= 0)
ok = 1;
error:
if (intr_signal == SIGINT)
ok = -1;
if (!echo)
fprintf(tty_out, "\n");
if (ps >= 2 && !echo && !echo_console(ui))
ok = 0;
if (ps >= 1)
popsig();
#else
ok = 1;
#endif
OPENSSL_cleanse(result, BUFSIZ);
return ok;
}
/* Internal functions to open, handle and close a channel to the console. */
static int open_console(UI *ui)
{
CRYPTO_w_lock(CRYPTO_LOCK_UI);
is_a_tty = 1;
#if defined(OPENSSL_SYS_MACINTOSH_CLASSIC) || defined(OPENSSL_SYS_VXWORKS) || defined(OPENSSL_SYS_NETWARE) || defined(OPENSSL_SYS_BEOS)
tty_in = stdin;
tty_out = stderr;
#else
# ifdef OPENSSL_SYS_MSDOS
# define DEV_TTY "con"
# else
# define DEV_TTY "/dev/tty"
# endif
if ((tty_in = fopen(DEV_TTY, "r")) == NULL)
tty_in = stdin;
if ((tty_out = fopen(DEV_TTY, "w")) == NULL)
tty_out = stderr;
#endif
#if defined(TTY_get) && !defined(OPENSSL_SYS_VMS)
if (TTY_get(fileno(tty_in), &tty_orig) == -1) {
# ifdef ENOTTY
if (errno == ENOTTY)
is_a_tty = 0;
else
# endif
# ifdef EINVAL
/*
* Ariel Glenn ariel@columbia.edu reports that solaris can return
* EINVAL instead. This should be ok
*/
if (errno == EINVAL)
is_a_tty = 0;
else
# endif
# ifdef ENODEV
/*
* MacOS X returns ENODEV (Operation not supported by device),
* which seems appropriate.
*/
if (errno == ENODEV)
is_a_tty = 0;
else
# endif
return 0;
}
#endif
#ifdef OPENSSL_SYS_VMS
status = sys$assign(&terminal, &channel, 0, 0);
/* if there isn't a TT device, something is very wrong */
if (status != SS$_NORMAL)
return 0;
status = sys$qiow(0, channel, IO$_SENSEMODE, &iosb, 0, 0, tty_orig, 12,
0, 0, 0, 0);
/* If IO$_SENSEMODE doesn't work, this is not a terminal device */
if ((status != SS$_NORMAL) || (iosb.iosb$w_value != SS$_NORMAL))
is_a_tty = 0;
#endif
return 1;
}
static int noecho_console(UI *ui)
{
#ifdef TTY_FLAGS
memcpy(&(tty_new), &(tty_orig), sizeof(tty_orig));
tty_new.TTY_FLAGS &= ~ECHO;
#endif
#if defined(TTY_set) && !defined(OPENSSL_SYS_VMS)
if (is_a_tty && (TTY_set(fileno(tty_in), &tty_new) == -1))
return 0;
#endif
#ifdef OPENSSL_SYS_VMS
if (is_a_tty) {
tty_new[0] = tty_orig[0];
tty_new[1] = tty_orig[1] | TT$M_NOECHO;
tty_new[2] = tty_orig[2];
status = sys$qiow(0, channel, IO$_SETMODE, &iosb, 0, 0, tty_new, 12,
0, 0, 0, 0);
if ((status != SS$_NORMAL) || (iosb.iosb$w_value != SS$_NORMAL))
return 0;
}
#endif
return 1;
}
static int echo_console(UI *ui)
{
#if defined(TTY_set) && !defined(OPENSSL_SYS_VMS)
memcpy(&(tty_new), &(tty_orig), sizeof(tty_orig));
tty_new.TTY_FLAGS |= ECHO;
#endif
#if defined(TTY_set) && !defined(OPENSSL_SYS_VMS)
if (is_a_tty && (TTY_set(fileno(tty_in), &tty_new) == -1))
return 0;
#endif
#ifdef OPENSSL_SYS_VMS
if (is_a_tty) {
tty_new[0] = tty_orig[0];
tty_new[1] = tty_orig[1] & ~TT$M_NOECHO;
tty_new[2] = tty_orig[2];
status = sys$qiow(0, channel, IO$_SETMODE, &iosb, 0, 0, tty_new, 12,
0, 0, 0, 0);
if ((status != SS$_NORMAL) || (iosb.iosb$w_value != SS$_NORMAL))
return 0;
}
#endif
return 1;
}
static int close_console(UI *ui)
{
if (tty_in != stdin)
fclose(tty_in);
if (tty_out != stderr)
fclose(tty_out);
#ifdef OPENSSL_SYS_VMS
status = sys$dassgn(channel);
if (status != SS$_NORMAL)
return 0;
#endif
CRYPTO_w_unlock(CRYPTO_LOCK_UI);
return 1;
}
#if !defined(OPENSSL_SYS_WIN16) && !defined(OPENSSL_SYS_WINCE)
/* Internal functions to handle signals and act on them */
static void pushsig(void)
{
# ifndef OPENSSL_SYS_WIN32
int i;
# endif
# ifdef SIGACTION
struct sigaction sa;
- memset(&sa, 0, sizeof sa);
+ memset(&sa, 0, sizeof(sa));
sa.sa_handler = recsig;
# endif
# ifdef OPENSSL_SYS_WIN32
savsig[SIGABRT] = signal(SIGABRT, recsig);
savsig[SIGFPE] = signal(SIGFPE, recsig);
savsig[SIGILL] = signal(SIGILL, recsig);
savsig[SIGINT] = signal(SIGINT, recsig);
savsig[SIGSEGV] = signal(SIGSEGV, recsig);
savsig[SIGTERM] = signal(SIGTERM, recsig);
# else
for (i = 1; i < NX509_SIG; i++) {
# ifdef SIGUSR1
if (i == SIGUSR1)
continue;
# endif
# ifdef SIGUSR2
if (i == SIGUSR2)
continue;
# endif
# ifdef SIGKILL
if (i == SIGKILL) /* We can't make any action on that. */
continue;
# endif
# ifdef SIGACTION
sigaction(i, &sa, &savsig[i]);
# else
savsig[i] = signal(i, recsig);
# endif
}
# endif
# ifdef SIGWINCH
signal(SIGWINCH, SIG_DFL);
# endif
}
static void popsig(void)
{
# ifdef OPENSSL_SYS_WIN32
signal(SIGABRT, savsig[SIGABRT]);
signal(SIGFPE, savsig[SIGFPE]);
signal(SIGILL, savsig[SIGILL]);
signal(SIGINT, savsig[SIGINT]);
signal(SIGSEGV, savsig[SIGSEGV]);
signal(SIGTERM, savsig[SIGTERM]);
# else
int i;
for (i = 1; i < NX509_SIG; i++) {
# ifdef SIGUSR1
if (i == SIGUSR1)
continue;
# endif
# ifdef SIGUSR2
if (i == SIGUSR2)
continue;
# endif
# ifdef SIGACTION
sigaction(i, &savsig[i], NULL);
# else
signal(i, savsig[i]);
# endif
}
# endif
}
static void recsig(int i)
{
intr_signal = i;
}
#endif
/* Internal functions specific for Windows */
#if defined(OPENSSL_SYS_MSDOS) && !defined(OPENSSL_SYS_WIN16) && !defined(OPENSSL_SYS_WINCE)
static int noecho_fgets(char *buf, int size, FILE *tty)
{
int i;
char *p;
p = buf;
for (;;) {
if (size == 0) {
*p = '\0';
break;
}
size--;
# ifdef WIN16TTY
i = _inchar();
# elif defined(_WIN32)
i = _getch();
# else
i = getch();
# endif
if (i == '\r')
i = '\n';
*(p++) = i;
if (i == '\n') {
*p = '\0';
break;
}
}
# ifdef WIN_CONSOLE_BUG
/*
* Win95 has several evil console bugs: one of these is that the last
* character read using getch() is passed to the next read: this is
* usually a CR so this can be trouble. No STDIO fix seems to work but
* flushing the console appears to do the trick.
*/
{
HANDLE inh;
inh = GetStdHandle(STD_INPUT_HANDLE);
FlushConsoleInputBuffer(inh);
}
# endif
return (strlen(buf));
}
#endif
diff --git a/crypto/x509/x509_txt.c b/crypto/x509/x509_txt.c
index 35db09559133..594031e7722d 100644
--- a/crypto/x509/x509_txt.c
+++ b/crypto/x509/x509_txt.c
@@ -1,218 +1,218 @@
/* crypto/x509/x509_txt.c */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
#include <stdio.h>
#include <time.h>
#include <errno.h>
#include "cryptlib.h"
#include <openssl/lhash.h>
#include <openssl/buffer.h>
#include <openssl/evp.h>
#include <openssl/asn1.h>
#include <openssl/x509.h>
#include <openssl/objects.h>
const char *X509_verify_cert_error_string(long n)
{
static char buf[100];
switch ((int)n) {
case X509_V_OK:
return ("ok");
case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
return ("unable to get issuer certificate");
case X509_V_ERR_UNABLE_TO_GET_CRL:
return ("unable to get certificate CRL");
case X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE:
return ("unable to decrypt certificate's signature");
case X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE:
return ("unable to decrypt CRL's signature");
case X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY:
return ("unable to decode issuer public key");
case X509_V_ERR_CERT_SIGNATURE_FAILURE:
return ("certificate signature failure");
case X509_V_ERR_CRL_SIGNATURE_FAILURE:
return ("CRL signature failure");
case X509_V_ERR_CERT_NOT_YET_VALID:
return ("certificate is not yet valid");
case X509_V_ERR_CRL_NOT_YET_VALID:
return ("CRL is not yet valid");
case X509_V_ERR_CERT_HAS_EXPIRED:
return ("certificate has expired");
case X509_V_ERR_CRL_HAS_EXPIRED:
return ("CRL has expired");
case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
return ("format error in certificate's notBefore field");
case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
return ("format error in certificate's notAfter field");
case X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD:
return ("format error in CRL's lastUpdate field");
case X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD:
return ("format error in CRL's nextUpdate field");
case X509_V_ERR_OUT_OF_MEM:
return ("out of memory");
case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT:
return ("self signed certificate");
case X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN:
return ("self signed certificate in certificate chain");
case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY:
return ("unable to get local issuer certificate");
case X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE:
return ("unable to verify the first certificate");
case X509_V_ERR_CERT_CHAIN_TOO_LONG:
return ("certificate chain too long");
case X509_V_ERR_CERT_REVOKED:
return ("certificate revoked");
case X509_V_ERR_INVALID_CA:
return ("invalid CA certificate");
case X509_V_ERR_INVALID_NON_CA:
return ("invalid non-CA certificate (has CA markings)");
case X509_V_ERR_PATH_LENGTH_EXCEEDED:
return ("path length constraint exceeded");
case X509_V_ERR_PROXY_PATH_LENGTH_EXCEEDED:
return ("proxy path length constraint exceeded");
case X509_V_ERR_PROXY_CERTIFICATES_NOT_ALLOWED:
return
("proxy certificates not allowed, please set the appropriate flag");
case X509_V_ERR_INVALID_PURPOSE:
return ("unsupported certificate purpose");
case X509_V_ERR_CERT_UNTRUSTED:
return ("certificate not trusted");
case X509_V_ERR_CERT_REJECTED:
return ("certificate rejected");
case X509_V_ERR_APPLICATION_VERIFICATION:
return ("application verification failure");
case X509_V_ERR_SUBJECT_ISSUER_MISMATCH:
return ("subject issuer mismatch");
case X509_V_ERR_AKID_SKID_MISMATCH:
return ("authority and subject key identifier mismatch");
case X509_V_ERR_AKID_ISSUER_SERIAL_MISMATCH:
return ("authority and issuer serial number mismatch");
case X509_V_ERR_KEYUSAGE_NO_CERTSIGN:
return ("key usage does not include certificate signing");
case X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER:
return ("unable to get CRL issuer certificate");
case X509_V_ERR_UNHANDLED_CRITICAL_EXTENSION:
return ("unhandled critical extension");
case X509_V_ERR_KEYUSAGE_NO_CRL_SIGN:
return ("key usage does not include CRL signing");
case X509_V_ERR_KEYUSAGE_NO_DIGITAL_SIGNATURE:
return ("key usage does not include digital signature");
case X509_V_ERR_UNHANDLED_CRITICAL_CRL_EXTENSION:
return ("unhandled critical CRL extension");
case X509_V_ERR_INVALID_EXTENSION:
return ("invalid or inconsistent certificate extension");
case X509_V_ERR_INVALID_POLICY_EXTENSION:
return ("invalid or inconsistent certificate policy extension");
case X509_V_ERR_NO_EXPLICIT_POLICY:
return ("no explicit policy");
case X509_V_ERR_DIFFERENT_CRL_SCOPE:
return ("Different CRL scope");
case X509_V_ERR_UNSUPPORTED_EXTENSION_FEATURE:
return ("Unsupported extension feature");
case X509_V_ERR_UNNESTED_RESOURCE:
return ("RFC 3779 resource not subset of parent's resources");
case X509_V_ERR_PERMITTED_VIOLATION:
return ("permitted subtree violation");
case X509_V_ERR_EXCLUDED_VIOLATION:
return ("excluded subtree violation");
case X509_V_ERR_SUBTREE_MINMAX:
return ("name constraints minimum and maximum not supported");
case X509_V_ERR_UNSUPPORTED_CONSTRAINT_TYPE:
return ("unsupported name constraint type");
case X509_V_ERR_UNSUPPORTED_CONSTRAINT_SYNTAX:
return ("unsupported or invalid name constraint syntax");
case X509_V_ERR_UNSUPPORTED_NAME_SYNTAX:
return ("unsupported or invalid name syntax");
case X509_V_ERR_CRL_PATH_VALIDATION_ERROR:
return ("CRL path validation error");
case X509_V_ERR_SUITE_B_INVALID_VERSION:
return ("Suite B: certificate version invalid");
case X509_V_ERR_SUITE_B_INVALID_ALGORITHM:
return ("Suite B: invalid public key algorithm");
case X509_V_ERR_SUITE_B_INVALID_CURVE:
return ("Suite B: invalid ECC curve");
case X509_V_ERR_SUITE_B_INVALID_SIGNATURE_ALGORITHM:
return ("Suite B: invalid signature algorithm");
case X509_V_ERR_SUITE_B_LOS_NOT_ALLOWED:
return ("Suite B: curve not allowed for this LOS");
case X509_V_ERR_SUITE_B_CANNOT_SIGN_P_384_WITH_P_256:
return ("Suite B: cannot sign P-384 with P-256");
case X509_V_ERR_HOSTNAME_MISMATCH:
return ("Hostname mismatch");
case X509_V_ERR_EMAIL_MISMATCH:
return ("Email address mismatch");
case X509_V_ERR_IP_ADDRESS_MISMATCH:
return ("IP address mismatch");
case X509_V_ERR_INVALID_CALL:
return ("Invalid certificate verification context");
case X509_V_ERR_STORE_LOOKUP:
return ("Issuer certificate lookup error");
case X509_V_ERR_PROXY_SUBJECT_NAME_VIOLATION:
return ("proxy subject name violation");
default:
- BIO_snprintf(buf, sizeof buf, "error number %ld", n);
+ BIO_snprintf(buf, sizeof(buf), "error number %ld", n);
return (buf);
}
}
diff --git a/crypto/x509/x509_v3.c b/crypto/x509/x509_v3.c
index 4a03445a64d2..9a3517e02af1 100644
--- a/crypto/x509/x509_v3.c
+++ b/crypto/x509/x509_v3.c
@@ -1,284 +1,284 @@
/* crypto/x509/x509_v3.c */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
#include <stdio.h>
#include <openssl/stack.h>
#include "cryptlib.h"
#include <openssl/asn1.h>
#include <openssl/objects.h>
#include <openssl/evp.h>
#include <openssl/x509.h>
#include <openssl/x509v3.h>
int X509v3_get_ext_count(const STACK_OF(X509_EXTENSION) *x)
{
if (x == NULL)
return (0);
return (sk_X509_EXTENSION_num(x));
}
int X509v3_get_ext_by_NID(const STACK_OF(X509_EXTENSION) *x, int nid,
int lastpos)
{
ASN1_OBJECT *obj;
obj = OBJ_nid2obj(nid);
if (obj == NULL)
return (-2);
return (X509v3_get_ext_by_OBJ(x, obj, lastpos));
}
int X509v3_get_ext_by_OBJ(const STACK_OF(X509_EXTENSION) *sk,
ASN1_OBJECT *obj, int lastpos)
{
int n;
X509_EXTENSION *ex;
if (sk == NULL)
return (-1);
lastpos++;
if (lastpos < 0)
lastpos = 0;
n = sk_X509_EXTENSION_num(sk);
for (; lastpos < n; lastpos++) {
ex = sk_X509_EXTENSION_value(sk, lastpos);
if (OBJ_cmp(ex->object, obj) == 0)
return (lastpos);
}
return (-1);
}
int X509v3_get_ext_by_critical(const STACK_OF(X509_EXTENSION) *sk, int crit,
int lastpos)
{
int n;
X509_EXTENSION *ex;
if (sk == NULL)
return (-1);
lastpos++;
if (lastpos < 0)
lastpos = 0;
n = sk_X509_EXTENSION_num(sk);
for (; lastpos < n; lastpos++) {
ex = sk_X509_EXTENSION_value(sk, lastpos);
if (((ex->critical > 0) && crit) || ((ex->critical <= 0) && !crit))
return (lastpos);
}
return (-1);
}
X509_EXTENSION *X509v3_get_ext(const STACK_OF(X509_EXTENSION) *x, int loc)
{
if (x == NULL || sk_X509_EXTENSION_num(x) <= loc || loc < 0)
return NULL;
else
return sk_X509_EXTENSION_value(x, loc);
}
X509_EXTENSION *X509v3_delete_ext(STACK_OF(X509_EXTENSION) *x, int loc)
{
X509_EXTENSION *ret;
if (x == NULL || sk_X509_EXTENSION_num(x) <= loc || loc < 0)
return (NULL);
ret = sk_X509_EXTENSION_delete(x, loc);
return (ret);
}
STACK_OF(X509_EXTENSION) *X509v3_add_ext(STACK_OF(X509_EXTENSION) **x,
X509_EXTENSION *ex, int loc)
{
X509_EXTENSION *new_ex = NULL;
int n;
STACK_OF(X509_EXTENSION) *sk = NULL;
if (x == NULL) {
X509err(X509_F_X509V3_ADD_EXT, ERR_R_PASSED_NULL_PARAMETER);
goto err2;
}
if (*x == NULL) {
if ((sk = sk_X509_EXTENSION_new_null()) == NULL)
goto err;
} else
sk = *x;
n = sk_X509_EXTENSION_num(sk);
if (loc > n)
loc = n;
else if (loc < 0)
loc = n;
if ((new_ex = X509_EXTENSION_dup(ex)) == NULL)
goto err2;
if (!sk_X509_EXTENSION_insert(sk, new_ex, loc))
goto err;
if (*x == NULL)
*x = sk;
return (sk);
err:
X509err(X509_F_X509V3_ADD_EXT, ERR_R_MALLOC_FAILURE);
err2:
if (new_ex != NULL)
X509_EXTENSION_free(new_ex);
- if (sk != NULL)
+ if (x != NULL && *x == NULL && sk != NULL)
sk_X509_EXTENSION_free(sk);
return (NULL);
}
X509_EXTENSION *X509_EXTENSION_create_by_NID(X509_EXTENSION **ex, int nid,
int crit,
ASN1_OCTET_STRING *data)
{
ASN1_OBJECT *obj;
X509_EXTENSION *ret;
obj = OBJ_nid2obj(nid);
if (obj == NULL) {
X509err(X509_F_X509_EXTENSION_CREATE_BY_NID, X509_R_UNKNOWN_NID);
return (NULL);
}
ret = X509_EXTENSION_create_by_OBJ(ex, obj, crit, data);
if (ret == NULL)
ASN1_OBJECT_free(obj);
return (ret);
}
X509_EXTENSION *X509_EXTENSION_create_by_OBJ(X509_EXTENSION **ex,
ASN1_OBJECT *obj, int crit,
ASN1_OCTET_STRING *data)
{
X509_EXTENSION *ret;
if ((ex == NULL) || (*ex == NULL)) {
if ((ret = X509_EXTENSION_new()) == NULL) {
X509err(X509_F_X509_EXTENSION_CREATE_BY_OBJ,
ERR_R_MALLOC_FAILURE);
return (NULL);
}
} else
ret = *ex;
if (!X509_EXTENSION_set_object(ret, obj))
goto err;
if (!X509_EXTENSION_set_critical(ret, crit))
goto err;
if (!X509_EXTENSION_set_data(ret, data))
goto err;
if ((ex != NULL) && (*ex == NULL))
*ex = ret;
return (ret);
err:
if ((ex == NULL) || (ret != *ex))
X509_EXTENSION_free(ret);
return (NULL);
}
int X509_EXTENSION_set_object(X509_EXTENSION *ex, ASN1_OBJECT *obj)
{
if ((ex == NULL) || (obj == NULL))
return (0);
ASN1_OBJECT_free(ex->object);
ex->object = OBJ_dup(obj);
return (1);
}
int X509_EXTENSION_set_critical(X509_EXTENSION *ex, int crit)
{
if (ex == NULL)
return (0);
ex->critical = (crit) ? 0xFF : -1;
return (1);
}
int X509_EXTENSION_set_data(X509_EXTENSION *ex, ASN1_OCTET_STRING *data)
{
int i;
if (ex == NULL)
return (0);
i = M_ASN1_OCTET_STRING_set(ex->value, data->data, data->length);
if (!i)
return (0);
return (1);
}
ASN1_OBJECT *X509_EXTENSION_get_object(X509_EXTENSION *ex)
{
if (ex == NULL)
return (NULL);
return (ex->object);
}
ASN1_OCTET_STRING *X509_EXTENSION_get_data(X509_EXTENSION *ex)
{
if (ex == NULL)
return (NULL);
return (ex->value);
}
int X509_EXTENSION_get_critical(X509_EXTENSION *ex)
{
if (ex == NULL)
return (0);
if (ex->critical > 0)
return 1;
return 0;
}
diff --git a/crypto/x509/x509_vpm.c b/crypto/x509/x509_vpm.c
index 1ac15a881a10..7d68a4abbc94 100644
--- a/crypto/x509/x509_vpm.c
+++ b/crypto/x509/x509_vpm.c
@@ -1,662 +1,662 @@
/* x509_vpm.c */
/*
* Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL project
* 2004.
*/
/* ====================================================================
* Copyright (c) 2004 The OpenSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* licensing@OpenSSL.org.
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*
* This product includes cryptographic software written by Eric Young
* (eay@cryptsoft.com). This product includes software written by Tim
* Hudson (tjh@cryptsoft.com).
*
*/
#include <stdio.h>
#include "cryptlib.h"
#include <openssl/crypto.h>
#include <openssl/lhash.h>
#include <openssl/buffer.h>
#include <openssl/x509.h>
#include <openssl/x509v3.h>
#include "vpm_int.h"
/* X509_VERIFY_PARAM functions */
#define SET_HOST 0
#define ADD_HOST 1
static char *str_copy(const char *s)
{
return OPENSSL_strdup(s);
}
static void str_free(char *s)
{
OPENSSL_free(s);
}
#define string_stack_free(sk) sk_OPENSSL_STRING_pop_free(sk, str_free)
static int int_x509_param_set_hosts(X509_VERIFY_PARAM_ID *id, int mode,
const char *name, size_t namelen)
{
char *copy;
/*
* Refuse names with embedded NUL bytes, except perhaps as final byte.
* XXX: Do we need to push an error onto the error stack?
*/
if (namelen == 0 || name == NULL)
namelen = name ? strlen(name) : 0;
else if (name && memchr(name, '\0', namelen > 1 ? namelen - 1 : namelen))
return 0;
if (namelen > 0 && name[namelen - 1] == '\0')
--namelen;
if (mode == SET_HOST && id->hosts) {
string_stack_free(id->hosts);
id->hosts = NULL;
}
if (name == NULL || namelen == 0)
return 1;
copy = BUF_strndup(name, namelen);
if (copy == NULL)
return 0;
if (id->hosts == NULL &&
(id->hosts = sk_OPENSSL_STRING_new_null()) == NULL) {
OPENSSL_free(copy);
return 0;
}
if (!sk_OPENSSL_STRING_push(id->hosts, copy)) {
OPENSSL_free(copy);
if (sk_OPENSSL_STRING_num(id->hosts) == 0) {
sk_OPENSSL_STRING_free(id->hosts);
id->hosts = NULL;
}
return 0;
}
return 1;
}
static void x509_verify_param_zero(X509_VERIFY_PARAM *param)
{
X509_VERIFY_PARAM_ID *paramid;
if (!param)
return;
param->name = NULL;
param->purpose = 0;
param->trust = 0;
/*
* param->inh_flags = X509_VP_FLAG_DEFAULT;
*/
param->inh_flags = 0;
param->flags = 0;
param->depth = -1;
if (param->policies) {
sk_ASN1_OBJECT_pop_free(param->policies, ASN1_OBJECT_free);
param->policies = NULL;
}
paramid = param->id;
if (paramid->hosts) {
string_stack_free(paramid->hosts);
paramid->hosts = NULL;
}
if (paramid->peername)
OPENSSL_free(paramid->peername);
paramid->peername = NULL;
if (paramid->email) {
OPENSSL_free(paramid->email);
paramid->email = NULL;
paramid->emaillen = 0;
}
if (paramid->ip) {
OPENSSL_free(paramid->ip);
paramid->ip = NULL;
paramid->iplen = 0;
}
}
X509_VERIFY_PARAM *X509_VERIFY_PARAM_new(void)
{
X509_VERIFY_PARAM *param;
X509_VERIFY_PARAM_ID *paramid;
- param = OPENSSL_malloc(sizeof *param);
+ param = OPENSSL_malloc(sizeof(*param));
if (!param)
return NULL;
memset(param, 0, sizeof(*param));
paramid = OPENSSL_malloc(sizeof(*paramid));
if (!paramid) {
OPENSSL_free(param);
return NULL;
}
memset(paramid, 0, sizeof(*paramid));
/* Exotic platforms may have non-zero bit representation of NULL */
paramid->hosts = NULL;
paramid->peername = NULL;
paramid->email = NULL;
paramid->ip = NULL;
param->id = paramid;
x509_verify_param_zero(param);
return param;
}
void X509_VERIFY_PARAM_free(X509_VERIFY_PARAM *param)
{
if (param == NULL)
return;
x509_verify_param_zero(param);
OPENSSL_free(param->id);
OPENSSL_free(param);
}
/*-
* This function determines how parameters are "inherited" from one structure
* to another. There are several different ways this can happen.
*
* 1. If a child structure needs to have its values initialized from a parent
* they are simply copied across. For example SSL_CTX copied to SSL.
* 2. If the structure should take on values only if they are currently unset.
* For example the values in an SSL structure will take appropriate value
* for SSL servers or clients but only if the application has not set new
* ones.
*
* The "inh_flags" field determines how this function behaves.
*
* Normally any values which are set in the default are not copied from the
* destination and verify flags are ORed together.
*
* If X509_VP_FLAG_DEFAULT is set then anything set in the source is copied
* to the destination. Effectively the values in "to" become default values
* which will be used only if nothing new is set in "from".
*
* If X509_VP_FLAG_OVERWRITE is set then all value are copied across whether
* they are set or not. Flags is still Ored though.
*
* If X509_VP_FLAG_RESET_FLAGS is set then the flags value is copied instead
* of ORed.
*
* If X509_VP_FLAG_LOCKED is set then no values are copied.
*
* If X509_VP_FLAG_ONCE is set then the current inh_flags setting is zeroed
* after the next call.
*/
/* Macro to test if a field should be copied from src to dest */
#define test_x509_verify_param_copy(field, def) \
(to_overwrite || \
((src->field != def) && (to_default || (dest->field == def))))
/* As above but for ID fields */
#define test_x509_verify_param_copy_id(idf, def) \
test_x509_verify_param_copy(id->idf, def)
/* Macro to test and copy a field if necessary */
#define x509_verify_param_copy(field, def) \
if (test_x509_verify_param_copy(field, def)) \
dest->field = src->field
int X509_VERIFY_PARAM_inherit(X509_VERIFY_PARAM *dest,
const X509_VERIFY_PARAM *src)
{
unsigned long inh_flags;
int to_default, to_overwrite;
X509_VERIFY_PARAM_ID *id;
if (!src)
return 1;
id = src->id;
inh_flags = dest->inh_flags | src->inh_flags;
if (inh_flags & X509_VP_FLAG_ONCE)
dest->inh_flags = 0;
if (inh_flags & X509_VP_FLAG_LOCKED)
return 1;
if (inh_flags & X509_VP_FLAG_DEFAULT)
to_default = 1;
else
to_default = 0;
if (inh_flags & X509_VP_FLAG_OVERWRITE)
to_overwrite = 1;
else
to_overwrite = 0;
x509_verify_param_copy(purpose, 0);
x509_verify_param_copy(trust, 0);
x509_verify_param_copy(depth, -1);
/* If overwrite or check time not set, copy across */
if (to_overwrite || !(dest->flags & X509_V_FLAG_USE_CHECK_TIME)) {
dest->check_time = src->check_time;
dest->flags &= ~X509_V_FLAG_USE_CHECK_TIME;
/* Don't need to copy flag: that is done below */
}
if (inh_flags & X509_VP_FLAG_RESET_FLAGS)
dest->flags = 0;
dest->flags |= src->flags;
if (test_x509_verify_param_copy(policies, NULL)) {
if (!X509_VERIFY_PARAM_set1_policies(dest, src->policies))
return 0;
}
/* Copy the host flags if and only if we're copying the host list */
if (test_x509_verify_param_copy_id(hosts, NULL)) {
if (dest->id->hosts) {
string_stack_free(dest->id->hosts);
dest->id->hosts = NULL;
}
if (id->hosts) {
dest->id->hosts =
sk_OPENSSL_STRING_deep_copy(id->hosts, str_copy, str_free);
if (dest->id->hosts == NULL)
return 0;
dest->id->hostflags = id->hostflags;
}
}
if (test_x509_verify_param_copy_id(email, NULL)) {
if (!X509_VERIFY_PARAM_set1_email(dest, id->email, id->emaillen))
return 0;
}
if (test_x509_verify_param_copy_id(ip, NULL)) {
if (!X509_VERIFY_PARAM_set1_ip(dest, id->ip, id->iplen))
return 0;
}
return 1;
}
int X509_VERIFY_PARAM_set1(X509_VERIFY_PARAM *to,
const X509_VERIFY_PARAM *from)
{
unsigned long save_flags = to->inh_flags;
int ret;
to->inh_flags |= X509_VP_FLAG_DEFAULT;
ret = X509_VERIFY_PARAM_inherit(to, from);
to->inh_flags = save_flags;
return ret;
}
static int int_x509_param_set1(char **pdest, size_t *pdestlen,
const char *src, size_t srclen)
{
void *tmp;
if (src) {
if (srclen == 0) {
tmp = BUF_strdup(src);
srclen = strlen(src);
} else
tmp = BUF_memdup(src, srclen);
if (!tmp)
return 0;
} else {
tmp = NULL;
srclen = 0;
}
if (*pdest)
OPENSSL_free(*pdest);
*pdest = tmp;
if (pdestlen)
*pdestlen = srclen;
return 1;
}
int X509_VERIFY_PARAM_set1_name(X509_VERIFY_PARAM *param, const char *name)
{
if (param->name)
OPENSSL_free(param->name);
param->name = BUF_strdup(name);
if (param->name)
return 1;
return 0;
}
int X509_VERIFY_PARAM_set_flags(X509_VERIFY_PARAM *param, unsigned long flags)
{
param->flags |= flags;
if (flags & X509_V_FLAG_POLICY_MASK)
param->flags |= X509_V_FLAG_POLICY_CHECK;
return 1;
}
int X509_VERIFY_PARAM_clear_flags(X509_VERIFY_PARAM *param,
unsigned long flags)
{
param->flags &= ~flags;
return 1;
}
unsigned long X509_VERIFY_PARAM_get_flags(X509_VERIFY_PARAM *param)
{
return param->flags;
}
int X509_VERIFY_PARAM_set_purpose(X509_VERIFY_PARAM *param, int purpose)
{
return X509_PURPOSE_set(&param->purpose, purpose);
}
int X509_VERIFY_PARAM_set_trust(X509_VERIFY_PARAM *param, int trust)
{
return X509_TRUST_set(&param->trust, trust);
}
void X509_VERIFY_PARAM_set_depth(X509_VERIFY_PARAM *param, int depth)
{
param->depth = depth;
}
void X509_VERIFY_PARAM_set_time(X509_VERIFY_PARAM *param, time_t t)
{
param->check_time = t;
param->flags |= X509_V_FLAG_USE_CHECK_TIME;
}
int X509_VERIFY_PARAM_add0_policy(X509_VERIFY_PARAM *param,
ASN1_OBJECT *policy)
{
if (!param->policies) {
param->policies = sk_ASN1_OBJECT_new_null();
if (!param->policies)
return 0;
}
if (!sk_ASN1_OBJECT_push(param->policies, policy))
return 0;
return 1;
}
int X509_VERIFY_PARAM_set1_policies(X509_VERIFY_PARAM *param,
STACK_OF(ASN1_OBJECT) *policies)
{
int i;
ASN1_OBJECT *oid, *doid;
if (!param)
return 0;
if (param->policies)
sk_ASN1_OBJECT_pop_free(param->policies, ASN1_OBJECT_free);
if (!policies) {
param->policies = NULL;
return 1;
}
param->policies = sk_ASN1_OBJECT_new_null();
if (!param->policies)
return 0;
for (i = 0; i < sk_ASN1_OBJECT_num(policies); i++) {
oid = sk_ASN1_OBJECT_value(policies, i);
doid = OBJ_dup(oid);
if (!doid)
return 0;
if (!sk_ASN1_OBJECT_push(param->policies, doid)) {
ASN1_OBJECT_free(doid);
return 0;
}
}
param->flags |= X509_V_FLAG_POLICY_CHECK;
return 1;
}
int X509_VERIFY_PARAM_set1_host(X509_VERIFY_PARAM *param,
const char *name, size_t namelen)
{
return int_x509_param_set_hosts(param->id, SET_HOST, name, namelen);
}
int X509_VERIFY_PARAM_add1_host(X509_VERIFY_PARAM *param,
const char *name, size_t namelen)
{
return int_x509_param_set_hosts(param->id, ADD_HOST, name, namelen);
}
void X509_VERIFY_PARAM_set_hostflags(X509_VERIFY_PARAM *param,
unsigned int flags)
{
param->id->hostflags = flags;
}
char *X509_VERIFY_PARAM_get0_peername(X509_VERIFY_PARAM *param)
{
return param->id->peername;
}
int X509_VERIFY_PARAM_set1_email(X509_VERIFY_PARAM *param,
const char *email, size_t emaillen)
{
return int_x509_param_set1(&param->id->email, &param->id->emaillen,
email, emaillen);
}
int X509_VERIFY_PARAM_set1_ip(X509_VERIFY_PARAM *param,
const unsigned char *ip, size_t iplen)
{
if (iplen != 0 && iplen != 4 && iplen != 16)
return 0;
return int_x509_param_set1((char **)&param->id->ip, &param->id->iplen,
(char *)ip, iplen);
}
int X509_VERIFY_PARAM_set1_ip_asc(X509_VERIFY_PARAM *param, const char *ipasc)
{
unsigned char ipout[16];
size_t iplen;
iplen = (size_t)a2i_ipadd(ipout, ipasc);
if (iplen == 0)
return 0;
return X509_VERIFY_PARAM_set1_ip(param, ipout, iplen);
}
int X509_VERIFY_PARAM_get_depth(const X509_VERIFY_PARAM *param)
{
return param->depth;
}
const char *X509_VERIFY_PARAM_get0_name(const X509_VERIFY_PARAM *param)
{
return param->name;
}
static X509_VERIFY_PARAM_ID _empty_id = { NULL, 0U, NULL, NULL, 0, NULL, 0 };
#define vpm_empty_id (X509_VERIFY_PARAM_ID *)&_empty_id
/*
* Default verify parameters: these are used for various applications and can
* be overridden by the user specified table. NB: the 'name' field *must* be
* in alphabetical order because it will be searched using OBJ_search.
*/
static const X509_VERIFY_PARAM default_table[] = {
{
"default", /* X509 default parameters */
0, /* Check time */
0, /* internal flags */
0, /* flags */
0, /* purpose */
0, /* trust */
100, /* depth */
NULL, /* policies */
vpm_empty_id},
{
"pkcs7", /* S/MIME sign parameters */
0, /* Check time */
0, /* internal flags */
0, /* flags */
X509_PURPOSE_SMIME_SIGN, /* purpose */
X509_TRUST_EMAIL, /* trust */
-1, /* depth */
NULL, /* policies */
vpm_empty_id},
{
"smime_sign", /* S/MIME sign parameters */
0, /* Check time */
0, /* internal flags */
0, /* flags */
X509_PURPOSE_SMIME_SIGN, /* purpose */
X509_TRUST_EMAIL, /* trust */
-1, /* depth */
NULL, /* policies */
vpm_empty_id},
{
"ssl_client", /* SSL/TLS client parameters */
0, /* Check time */
0, /* internal flags */
0, /* flags */
X509_PURPOSE_SSL_CLIENT, /* purpose */
X509_TRUST_SSL_CLIENT, /* trust */
-1, /* depth */
NULL, /* policies */
vpm_empty_id},
{
"ssl_server", /* SSL/TLS server parameters */
0, /* Check time */
0, /* internal flags */
0, /* flags */
X509_PURPOSE_SSL_SERVER, /* purpose */
X509_TRUST_SSL_SERVER, /* trust */
-1, /* depth */
NULL, /* policies */
vpm_empty_id}
};
static STACK_OF(X509_VERIFY_PARAM) *param_table = NULL;
static int table_cmp(const X509_VERIFY_PARAM *a, const X509_VERIFY_PARAM *b)
{
return strcmp(a->name, b->name);
}
DECLARE_OBJ_BSEARCH_CMP_FN(X509_VERIFY_PARAM, X509_VERIFY_PARAM, table);
IMPLEMENT_OBJ_BSEARCH_CMP_FN(X509_VERIFY_PARAM, X509_VERIFY_PARAM, table);
static int param_cmp(const X509_VERIFY_PARAM *const *a,
const X509_VERIFY_PARAM *const *b)
{
return strcmp((*a)->name, (*b)->name);
}
int X509_VERIFY_PARAM_add0_table(X509_VERIFY_PARAM *param)
{
int idx;
X509_VERIFY_PARAM *ptmp;
if (!param_table) {
param_table = sk_X509_VERIFY_PARAM_new(param_cmp);
if (!param_table)
return 0;
} else {
idx = sk_X509_VERIFY_PARAM_find(param_table, param);
if (idx != -1) {
ptmp = sk_X509_VERIFY_PARAM_value(param_table, idx);
X509_VERIFY_PARAM_free(ptmp);
(void)sk_X509_VERIFY_PARAM_delete(param_table, idx);
}
}
if (!sk_X509_VERIFY_PARAM_push(param_table, param))
return 0;
return 1;
}
int X509_VERIFY_PARAM_get_count(void)
{
int num = sizeof(default_table) / sizeof(X509_VERIFY_PARAM);
if (param_table)
num += sk_X509_VERIFY_PARAM_num(param_table);
return num;
}
const X509_VERIFY_PARAM *X509_VERIFY_PARAM_get0(int id)
{
int num = sizeof(default_table) / sizeof(X509_VERIFY_PARAM);
if (id < num)
return default_table + id;
return sk_X509_VERIFY_PARAM_value(param_table, id - num);
}
const X509_VERIFY_PARAM *X509_VERIFY_PARAM_lookup(const char *name)
{
int idx;
X509_VERIFY_PARAM pm;
pm.name = (char *)name;
if (param_table) {
idx = sk_X509_VERIFY_PARAM_find(param_table, &pm);
if (idx != -1)
return sk_X509_VERIFY_PARAM_value(param_table, idx);
}
return OBJ_bsearch_table(&pm, default_table,
sizeof(default_table) /
sizeof(X509_VERIFY_PARAM));
}
void X509_VERIFY_PARAM_table_cleanup(void)
{
if (param_table)
sk_X509_VERIFY_PARAM_pop_free(param_table, X509_VERIFY_PARAM_free);
param_table = NULL;
}
diff --git a/crypto/x509v3/v3_alt.c b/crypto/x509v3/v3_alt.c
index a0351faf1119..d4d024c561c8 100644
--- a/crypto/x509v3/v3_alt.c
+++ b/crypto/x509v3/v3_alt.c
@@ -1,621 +1,621 @@
/* v3_alt.c */
/*
* Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL
* project.
*/
/* ====================================================================
* Copyright (c) 1999-2003 The OpenSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* licensing@OpenSSL.org.
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*
* This product includes cryptographic software written by Eric Young
* (eay@cryptsoft.com). This product includes software written by Tim
* Hudson (tjh@cryptsoft.com).
*
*/
#include <stdio.h>
#include "cryptlib.h"
#include <openssl/conf.h>
#include <openssl/x509v3.h>
static GENERAL_NAMES *v2i_subject_alt(X509V3_EXT_METHOD *method,
X509V3_CTX *ctx,
STACK_OF(CONF_VALUE) *nval);
static GENERAL_NAMES *v2i_issuer_alt(X509V3_EXT_METHOD *method,
X509V3_CTX *ctx,
STACK_OF(CONF_VALUE) *nval);
static int copy_email(X509V3_CTX *ctx, GENERAL_NAMES *gens, int move_p);
static int copy_issuer(X509V3_CTX *ctx, GENERAL_NAMES *gens);
static int do_othername(GENERAL_NAME *gen, char *value, X509V3_CTX *ctx);
static int do_dirname(GENERAL_NAME *gen, char *value, X509V3_CTX *ctx);
const X509V3_EXT_METHOD v3_alt[] = {
{NID_subject_alt_name, 0, ASN1_ITEM_ref(GENERAL_NAMES),
0, 0, 0, 0,
0, 0,
(X509V3_EXT_I2V) i2v_GENERAL_NAMES,
(X509V3_EXT_V2I)v2i_subject_alt,
NULL, NULL, NULL},
{NID_issuer_alt_name, 0, ASN1_ITEM_ref(GENERAL_NAMES),
0, 0, 0, 0,
0, 0,
(X509V3_EXT_I2V) i2v_GENERAL_NAMES,
(X509V3_EXT_V2I)v2i_issuer_alt,
NULL, NULL, NULL},
{NID_certificate_issuer, 0, ASN1_ITEM_ref(GENERAL_NAMES),
0, 0, 0, 0,
0, 0,
(X509V3_EXT_I2V) i2v_GENERAL_NAMES,
NULL, NULL, NULL, NULL},
};
STACK_OF(CONF_VALUE) *i2v_GENERAL_NAMES(X509V3_EXT_METHOD *method,
GENERAL_NAMES *gens,
STACK_OF(CONF_VALUE) *ret)
{
int i;
GENERAL_NAME *gen;
for (i = 0; i < sk_GENERAL_NAME_num(gens); i++) {
gen = sk_GENERAL_NAME_value(gens, i);
ret = i2v_GENERAL_NAME(method, gen, ret);
}
if (!ret)
return sk_CONF_VALUE_new_null();
return ret;
}
STACK_OF(CONF_VALUE) *i2v_GENERAL_NAME(X509V3_EXT_METHOD *method,
GENERAL_NAME *gen,
STACK_OF(CONF_VALUE) *ret)
{
unsigned char *p;
char oline[256], htmp[5];
int i;
switch (gen->type) {
case GEN_OTHERNAME:
if (!X509V3_add_value("othername", "<unsupported>", &ret))
return NULL;
break;
case GEN_X400:
if (!X509V3_add_value("X400Name", "<unsupported>", &ret))
return NULL;
break;
case GEN_EDIPARTY:
if (!X509V3_add_value("EdiPartyName", "<unsupported>", &ret))
return NULL;
break;
case GEN_EMAIL:
if (!X509V3_add_value_uchar("email", gen->d.ia5->data, &ret))
return NULL;
break;
case GEN_DNS:
if (!X509V3_add_value_uchar("DNS", gen->d.ia5->data, &ret))
return NULL;
break;
case GEN_URI:
if (!X509V3_add_value_uchar("URI", gen->d.ia5->data, &ret))
return NULL;
break;
case GEN_DIRNAME:
if (X509_NAME_oneline(gen->d.dirn, oline, 256) == NULL
|| !X509V3_add_value("DirName", oline, &ret))
return NULL;
break;
case GEN_IPADD:
p = gen->d.ip->data;
if (gen->d.ip->length == 4)
- BIO_snprintf(oline, sizeof oline,
+ BIO_snprintf(oline, sizeof(oline),
"%d.%d.%d.%d", p[0], p[1], p[2], p[3]);
else if (gen->d.ip->length == 16) {
oline[0] = 0;
for (i = 0; i < 8; i++) {
- BIO_snprintf(htmp, sizeof htmp, "%X", p[0] << 8 | p[1]);
+ BIO_snprintf(htmp, sizeof(htmp), "%X", p[0] << 8 | p[1]);
p += 2;
strcat(oline, htmp);
if (i != 7)
strcat(oline, ":");
}
} else {
if (!X509V3_add_value("IP Address", "<invalid>", &ret))
return NULL;
break;
}
if (!X509V3_add_value("IP Address", oline, &ret))
return NULL;
break;
case GEN_RID:
i2t_ASN1_OBJECT(oline, 256, gen->d.rid);
if (!X509V3_add_value("Registered ID", oline, &ret))
return NULL;
break;
}
return ret;
}
int GENERAL_NAME_print(BIO *out, GENERAL_NAME *gen)
{
unsigned char *p;
int i;
switch (gen->type) {
case GEN_OTHERNAME:
BIO_printf(out, "othername:<unsupported>");
break;
case GEN_X400:
BIO_printf(out, "X400Name:<unsupported>");
break;
case GEN_EDIPARTY:
/* Maybe fix this: it is supported now */
BIO_printf(out, "EdiPartyName:<unsupported>");
break;
case GEN_EMAIL:
BIO_printf(out, "email:%s", gen->d.ia5->data);
break;
case GEN_DNS:
BIO_printf(out, "DNS:%s", gen->d.ia5->data);
break;
case GEN_URI:
BIO_printf(out, "URI:%s", gen->d.ia5->data);
break;
case GEN_DIRNAME:
BIO_printf(out, "DirName: ");
X509_NAME_print_ex(out, gen->d.dirn, 0, XN_FLAG_ONELINE);
break;
case GEN_IPADD:
p = gen->d.ip->data;
if (gen->d.ip->length == 4)
BIO_printf(out, "IP Address:%d.%d.%d.%d", p[0], p[1], p[2], p[3]);
else if (gen->d.ip->length == 16) {
BIO_printf(out, "IP Address");
for (i = 0; i < 8; i++) {
BIO_printf(out, ":%X", p[0] << 8 | p[1]);
p += 2;
}
BIO_puts(out, "\n");
} else {
BIO_printf(out, "IP Address:<invalid>");
break;
}
break;
case GEN_RID:
BIO_printf(out, "Registered ID");
i2a_ASN1_OBJECT(out, gen->d.rid);
break;
}
return 1;
}
static GENERAL_NAMES *v2i_issuer_alt(X509V3_EXT_METHOD *method,
X509V3_CTX *ctx,
STACK_OF(CONF_VALUE) *nval)
{
GENERAL_NAMES *gens = NULL;
CONF_VALUE *cnf;
int i;
if (!(gens = sk_GENERAL_NAME_new_null())) {
X509V3err(X509V3_F_V2I_ISSUER_ALT, ERR_R_MALLOC_FAILURE);
return NULL;
}
for (i = 0; i < sk_CONF_VALUE_num(nval); i++) {
cnf = sk_CONF_VALUE_value(nval, i);
if (!name_cmp(cnf->name, "issuer") && cnf->value &&
!strcmp(cnf->value, "copy")) {
if (!copy_issuer(ctx, gens))
goto err;
} else {
GENERAL_NAME *gen;
if (!(gen = v2i_GENERAL_NAME(method, ctx, cnf)))
goto err;
sk_GENERAL_NAME_push(gens, gen);
}
}
return gens;
err:
sk_GENERAL_NAME_pop_free(gens, GENERAL_NAME_free);
return NULL;
}
/* Append subject altname of issuer to issuer alt name of subject */
static int copy_issuer(X509V3_CTX *ctx, GENERAL_NAMES *gens)
{
GENERAL_NAMES *ialt;
GENERAL_NAME *gen;
X509_EXTENSION *ext;
int i;
if (ctx && (ctx->flags == CTX_TEST))
return 1;
if (!ctx || !ctx->issuer_cert) {
X509V3err(X509V3_F_COPY_ISSUER, X509V3_R_NO_ISSUER_DETAILS);
goto err;
}
i = X509_get_ext_by_NID(ctx->issuer_cert, NID_subject_alt_name, -1);
if (i < 0)
return 1;
if (!(ext = X509_get_ext(ctx->issuer_cert, i)) ||
!(ialt = X509V3_EXT_d2i(ext))) {
X509V3err(X509V3_F_COPY_ISSUER, X509V3_R_ISSUER_DECODE_ERROR);
goto err;
}
for (i = 0; i < sk_GENERAL_NAME_num(ialt); i++) {
gen = sk_GENERAL_NAME_value(ialt, i);
if (!sk_GENERAL_NAME_push(gens, gen)) {
X509V3err(X509V3_F_COPY_ISSUER, ERR_R_MALLOC_FAILURE);
goto err;
}
}
sk_GENERAL_NAME_free(ialt);
return 1;
err:
return 0;
}
static GENERAL_NAMES *v2i_subject_alt(X509V3_EXT_METHOD *method,
X509V3_CTX *ctx,
STACK_OF(CONF_VALUE) *nval)
{
GENERAL_NAMES *gens = NULL;
CONF_VALUE *cnf;
int i;
if (!(gens = sk_GENERAL_NAME_new_null())) {
X509V3err(X509V3_F_V2I_SUBJECT_ALT, ERR_R_MALLOC_FAILURE);
return NULL;
}
for (i = 0; i < sk_CONF_VALUE_num(nval); i++) {
cnf = sk_CONF_VALUE_value(nval, i);
if (!name_cmp(cnf->name, "email") && cnf->value &&
!strcmp(cnf->value, "copy")) {
if (!copy_email(ctx, gens, 0))
goto err;
} else if (!name_cmp(cnf->name, "email") && cnf->value &&
!strcmp(cnf->value, "move")) {
if (!copy_email(ctx, gens, 1))
goto err;
} else {
GENERAL_NAME *gen;
if (!(gen = v2i_GENERAL_NAME(method, ctx, cnf)))
goto err;
sk_GENERAL_NAME_push(gens, gen);
}
}
return gens;
err:
sk_GENERAL_NAME_pop_free(gens, GENERAL_NAME_free);
return NULL;
}
/*
* Copy any email addresses in a certificate or request to GENERAL_NAMES
*/
static int copy_email(X509V3_CTX *ctx, GENERAL_NAMES *gens, int move_p)
{
X509_NAME *nm;
ASN1_IA5STRING *email = NULL;
X509_NAME_ENTRY *ne;
GENERAL_NAME *gen = NULL;
int i;
if (ctx != NULL && ctx->flags == CTX_TEST)
return 1;
if (!ctx || (!ctx->subject_cert && !ctx->subject_req)) {
X509V3err(X509V3_F_COPY_EMAIL, X509V3_R_NO_SUBJECT_DETAILS);
goto err;
}
/* Find the subject name */
if (ctx->subject_cert)
nm = X509_get_subject_name(ctx->subject_cert);
else
nm = X509_REQ_get_subject_name(ctx->subject_req);
/* Now add any email address(es) to STACK */
i = -1;
while ((i = X509_NAME_get_index_by_NID(nm,
NID_pkcs9_emailAddress, i)) >= 0) {
ne = X509_NAME_get_entry(nm, i);
email = M_ASN1_IA5STRING_dup(X509_NAME_ENTRY_get_data(ne));
if (move_p) {
X509_NAME_delete_entry(nm, i);
X509_NAME_ENTRY_free(ne);
i--;
}
if (!email || !(gen = GENERAL_NAME_new())) {
X509V3err(X509V3_F_COPY_EMAIL, ERR_R_MALLOC_FAILURE);
goto err;
}
gen->d.ia5 = email;
email = NULL;
gen->type = GEN_EMAIL;
if (!sk_GENERAL_NAME_push(gens, gen)) {
X509V3err(X509V3_F_COPY_EMAIL, ERR_R_MALLOC_FAILURE);
goto err;
}
gen = NULL;
}
return 1;
err:
GENERAL_NAME_free(gen);
M_ASN1_IA5STRING_free(email);
return 0;
}
GENERAL_NAMES *v2i_GENERAL_NAMES(const X509V3_EXT_METHOD *method,
X509V3_CTX *ctx, STACK_OF(CONF_VALUE) *nval)
{
GENERAL_NAME *gen;
GENERAL_NAMES *gens = NULL;
CONF_VALUE *cnf;
int i;
if (!(gens = sk_GENERAL_NAME_new_null())) {
X509V3err(X509V3_F_V2I_GENERAL_NAMES, ERR_R_MALLOC_FAILURE);
return NULL;
}
for (i = 0; i < sk_CONF_VALUE_num(nval); i++) {
cnf = sk_CONF_VALUE_value(nval, i);
if (!(gen = v2i_GENERAL_NAME(method, ctx, cnf)))
goto err;
sk_GENERAL_NAME_push(gens, gen);
}
return gens;
err:
sk_GENERAL_NAME_pop_free(gens, GENERAL_NAME_free);
return NULL;
}
GENERAL_NAME *v2i_GENERAL_NAME(const X509V3_EXT_METHOD *method,
X509V3_CTX *ctx, CONF_VALUE *cnf)
{
return v2i_GENERAL_NAME_ex(NULL, method, ctx, cnf, 0);
}
GENERAL_NAME *a2i_GENERAL_NAME(GENERAL_NAME *out,
const X509V3_EXT_METHOD *method,
X509V3_CTX *ctx, int gen_type, char *value,
int is_nc)
{
char is_string = 0;
GENERAL_NAME *gen = NULL;
if (!value) {
X509V3err(X509V3_F_A2I_GENERAL_NAME, X509V3_R_MISSING_VALUE);
return NULL;
}
if (out)
gen = out;
else {
gen = GENERAL_NAME_new();
if (gen == NULL) {
X509V3err(X509V3_F_A2I_GENERAL_NAME, ERR_R_MALLOC_FAILURE);
return NULL;
}
}
switch (gen_type) {
case GEN_URI:
case GEN_EMAIL:
case GEN_DNS:
is_string = 1;
break;
case GEN_RID:
{
ASN1_OBJECT *obj;
if (!(obj = OBJ_txt2obj(value, 0))) {
X509V3err(X509V3_F_A2I_GENERAL_NAME, X509V3_R_BAD_OBJECT);
ERR_add_error_data(2, "value=", value);
goto err;
}
gen->d.rid = obj;
}
break;
case GEN_IPADD:
if (is_nc)
gen->d.ip = a2i_IPADDRESS_NC(value);
else
gen->d.ip = a2i_IPADDRESS(value);
if (gen->d.ip == NULL) {
X509V3err(X509V3_F_A2I_GENERAL_NAME, X509V3_R_BAD_IP_ADDRESS);
ERR_add_error_data(2, "value=", value);
goto err;
}
break;
case GEN_DIRNAME:
if (!do_dirname(gen, value, ctx)) {
X509V3err(X509V3_F_A2I_GENERAL_NAME, X509V3_R_DIRNAME_ERROR);
goto err;
}
break;
case GEN_OTHERNAME:
if (!do_othername(gen, value, ctx)) {
X509V3err(X509V3_F_A2I_GENERAL_NAME, X509V3_R_OTHERNAME_ERROR);
goto err;
}
break;
default:
X509V3err(X509V3_F_A2I_GENERAL_NAME, X509V3_R_UNSUPPORTED_TYPE);
goto err;
}
if (is_string) {
if (!(gen->d.ia5 = M_ASN1_IA5STRING_new()) ||
!ASN1_STRING_set(gen->d.ia5, (unsigned char *)value,
strlen(value))) {
X509V3err(X509V3_F_A2I_GENERAL_NAME, ERR_R_MALLOC_FAILURE);
goto err;
}
}
gen->type = gen_type;
return gen;
err:
if (!out)
GENERAL_NAME_free(gen);
return NULL;
}
GENERAL_NAME *v2i_GENERAL_NAME_ex(GENERAL_NAME *out,
const X509V3_EXT_METHOD *method,
X509V3_CTX *ctx, CONF_VALUE *cnf, int is_nc)
{
int type;
char *name, *value;
name = cnf->name;
value = cnf->value;
if (!value) {
X509V3err(X509V3_F_V2I_GENERAL_NAME_EX, X509V3_R_MISSING_VALUE);
return NULL;
}
if (!name_cmp(name, "email"))
type = GEN_EMAIL;
else if (!name_cmp(name, "URI"))
type = GEN_URI;
else if (!name_cmp(name, "DNS"))
type = GEN_DNS;
else if (!name_cmp(name, "RID"))
type = GEN_RID;
else if (!name_cmp(name, "IP"))
type = GEN_IPADD;
else if (!name_cmp(name, "dirName"))
type = GEN_DIRNAME;
else if (!name_cmp(name, "otherName"))
type = GEN_OTHERNAME;
else {
X509V3err(X509V3_F_V2I_GENERAL_NAME_EX, X509V3_R_UNSUPPORTED_OPTION);
ERR_add_error_data(2, "name=", name);
return NULL;
}
return a2i_GENERAL_NAME(out, method, ctx, type, value, is_nc);
}
static int do_othername(GENERAL_NAME *gen, char *value, X509V3_CTX *ctx)
{
char *objtmp = NULL, *p;
int objlen;
if (!(p = strchr(value, ';')))
return 0;
if (!(gen->d.otherName = OTHERNAME_new()))
return 0;
/*
* Free this up because we will overwrite it. no need to free type_id
* because it is static
*/
ASN1_TYPE_free(gen->d.otherName->value);
if (!(gen->d.otherName->value = ASN1_generate_v3(p + 1, ctx)))
return 0;
objlen = p - value;
objtmp = OPENSSL_malloc(objlen + 1);
if (objtmp == NULL)
return 0;
strncpy(objtmp, value, objlen);
objtmp[objlen] = 0;
gen->d.otherName->type_id = OBJ_txt2obj(objtmp, 0);
OPENSSL_free(objtmp);
if (!gen->d.otherName->type_id)
return 0;
return 1;
}
static int do_dirname(GENERAL_NAME *gen, char *value, X509V3_CTX *ctx)
{
int ret = 0;
STACK_OF(CONF_VALUE) *sk = NULL;
X509_NAME *nm = NULL;
if (!(nm = X509_NAME_new()))
goto err;
sk = X509V3_get_section(ctx, value);
if (!sk) {
X509V3err(X509V3_F_DO_DIRNAME, X509V3_R_SECTION_NOT_FOUND);
ERR_add_error_data(2, "section=", value);
goto err;
}
/* FIXME: should allow other character types... */
ret = X509V3_NAME_from_section(nm, sk, MBSTRING_ASC);
if (!ret)
goto err;
gen->d.dirn = nm;
err:
if (ret == 0)
X509_NAME_free(nm);
X509V3_section_free(ctx, sk);
return ret;
}
diff --git a/crypto/x509v3/v3_conf.c b/crypto/x509v3/v3_conf.c
index c1b4c1a89f74..a38848cc1df7 100644
--- a/crypto/x509v3/v3_conf.c
+++ b/crypto/x509v3/v3_conf.c
@@ -1,534 +1,538 @@
/* v3_conf.c */
/*
* Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL project
* 1999.
*/
/* ====================================================================
- * Copyright (c) 1999-2002 The OpenSSL Project. All rights reserved.
+ * Copyright (c) 1999-2018 The OpenSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* licensing@OpenSSL.org.
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*
* This product includes cryptographic software written by Eric Young
* (eay@cryptsoft.com). This product includes software written by Tim
* Hudson (tjh@cryptsoft.com).
*
*/
/* extension creation utilities */
#include <stdio.h>
#include <ctype.h>
#include "cryptlib.h"
#include <openssl/conf.h>
#include <openssl/x509.h>
#include <openssl/x509v3.h>
static int v3_check_critical(char **value);
static int v3_check_generic(char **value);
static X509_EXTENSION *do_ext_nconf(CONF *conf, X509V3_CTX *ctx, int ext_nid,
int crit, char *value);
static X509_EXTENSION *v3_generic_extension(const char *ext, char *value,
int crit, int type,
X509V3_CTX *ctx);
static char *conf_lhash_get_string(void *db, char *section, char *value);
static STACK_OF(CONF_VALUE) *conf_lhash_get_section(void *db, char *section);
static X509_EXTENSION *do_ext_i2d(const X509V3_EXT_METHOD *method,
int ext_nid, int crit, void *ext_struc);
static unsigned char *generic_asn1(char *value, X509V3_CTX *ctx,
long *ext_len);
/* CONF *conf: Config file */
/* char *name: Name */
/* char *value: Value */
X509_EXTENSION *X509V3_EXT_nconf(CONF *conf, X509V3_CTX *ctx, char *name,
char *value)
{
int crit;
int ext_type;
X509_EXTENSION *ret;
crit = v3_check_critical(&value);
if ((ext_type = v3_check_generic(&value)))
return v3_generic_extension(name, value, crit, ext_type, ctx);
ret = do_ext_nconf(conf, ctx, OBJ_sn2nid(name), crit, value);
if (!ret) {
X509V3err(X509V3_F_X509V3_EXT_NCONF, X509V3_R_ERROR_IN_EXTENSION);
ERR_add_error_data(4, "name=", name, ", value=", value);
}
return ret;
}
/* CONF *conf: Config file */
/* char *value: Value */
X509_EXTENSION *X509V3_EXT_nconf_nid(CONF *conf, X509V3_CTX *ctx, int ext_nid,
char *value)
{
int crit;
int ext_type;
crit = v3_check_critical(&value);
if ((ext_type = v3_check_generic(&value)))
return v3_generic_extension(OBJ_nid2sn(ext_nid),
value, crit, ext_type, ctx);
return do_ext_nconf(conf, ctx, ext_nid, crit, value);
}
/* CONF *conf: Config file */
/* char *value: Value */
static X509_EXTENSION *do_ext_nconf(CONF *conf, X509V3_CTX *ctx, int ext_nid,
int crit, char *value)
{
const X509V3_EXT_METHOD *method;
X509_EXTENSION *ext;
STACK_OF(CONF_VALUE) *nval;
void *ext_struc;
if (ext_nid == NID_undef) {
X509V3err(X509V3_F_DO_EXT_NCONF, X509V3_R_UNKNOWN_EXTENSION_NAME);
return NULL;
}
if (!(method = X509V3_EXT_get_nid(ext_nid))) {
X509V3err(X509V3_F_DO_EXT_NCONF, X509V3_R_UNKNOWN_EXTENSION);
return NULL;
}
/* Now get internal extension representation based on type */
if (method->v2i) {
if (*value == '@')
nval = NCONF_get_section(conf, value + 1);
else
nval = X509V3_parse_list(value);
if (nval == NULL || sk_CONF_VALUE_num(nval) <= 0) {
X509V3err(X509V3_F_DO_EXT_NCONF,
X509V3_R_INVALID_EXTENSION_STRING);
ERR_add_error_data(4, "name=", OBJ_nid2sn(ext_nid), ",section=",
value);
if (*value != '@')
sk_CONF_VALUE_free(nval);
return NULL;
}
ext_struc = method->v2i(method, ctx, nval);
if (*value != '@')
sk_CONF_VALUE_pop_free(nval, X509V3_conf_free);
if (!ext_struc)
return NULL;
} else if (method->s2i) {
if (!(ext_struc = method->s2i(method, ctx, value)))
return NULL;
} else if (method->r2i) {
if (!ctx->db || !ctx->db_meth) {
X509V3err(X509V3_F_DO_EXT_NCONF, X509V3_R_NO_CONFIG_DATABASE);
return NULL;
}
if (!(ext_struc = method->r2i(method, ctx, value)))
return NULL;
} else {
X509V3err(X509V3_F_DO_EXT_NCONF,
X509V3_R_EXTENSION_SETTING_NOT_SUPPORTED);
ERR_add_error_data(2, "name=", OBJ_nid2sn(ext_nid));
return NULL;
}
ext = do_ext_i2d(method, ext_nid, crit, ext_struc);
if (method->it)
ASN1_item_free(ext_struc, ASN1_ITEM_ptr(method->it));
else
method->ext_free(ext_struc);
return ext;
}
static X509_EXTENSION *do_ext_i2d(const X509V3_EXT_METHOD *method,
int ext_nid, int crit, void *ext_struc)
{
unsigned char *ext_der;
int ext_len;
ASN1_OCTET_STRING *ext_oct;
X509_EXTENSION *ext;
/* Convert internal representation to DER */
if (method->it) {
ext_der = NULL;
ext_len =
ASN1_item_i2d(ext_struc, &ext_der, ASN1_ITEM_ptr(method->it));
if (ext_len < 0)
goto merr;
} else {
unsigned char *p;
ext_len = method->i2d(ext_struc, NULL);
if (!(ext_der = OPENSSL_malloc(ext_len)))
goto merr;
p = ext_der;
method->i2d(ext_struc, &p);
}
if (!(ext_oct = M_ASN1_OCTET_STRING_new()))
goto merr;
ext_oct->data = ext_der;
ext_oct->length = ext_len;
ext = X509_EXTENSION_create_by_NID(NULL, ext_nid, crit, ext_oct);
if (!ext)
goto merr;
M_ASN1_OCTET_STRING_free(ext_oct);
return ext;
merr:
X509V3err(X509V3_F_DO_EXT_I2D, ERR_R_MALLOC_FAILURE);
return NULL;
}
/* Given an internal structure, nid and critical flag create an extension */
X509_EXTENSION *X509V3_EXT_i2d(int ext_nid, int crit, void *ext_struc)
{
const X509V3_EXT_METHOD *method;
if (!(method = X509V3_EXT_get_nid(ext_nid))) {
X509V3err(X509V3_F_X509V3_EXT_I2D, X509V3_R_UNKNOWN_EXTENSION);
return NULL;
}
return do_ext_i2d(method, ext_nid, crit, ext_struc);
}
/* Check the extension string for critical flag */
static int v3_check_critical(char **value)
{
char *p = *value;
if ((strlen(p) < 9) || strncmp(p, "critical,", 9))
return 0;
p += 9;
while (isspace((unsigned char)*p))
p++;
*value = p;
return 1;
}
/* Check extension string for generic extension and return the type */
static int v3_check_generic(char **value)
{
int gen_type = 0;
char *p = *value;
if ((strlen(p) >= 4) && !strncmp(p, "DER:", 4)) {
p += 4;
gen_type = 1;
} else if ((strlen(p) >= 5) && !strncmp(p, "ASN1:", 5)) {
p += 5;
gen_type = 2;
} else
return 0;
while (isspace((unsigned char)*p))
p++;
*value = p;
return gen_type;
}
/* Create a generic extension: for now just handle DER type */
static X509_EXTENSION *v3_generic_extension(const char *ext, char *value,
int crit, int gen_type,
X509V3_CTX *ctx)
{
unsigned char *ext_der = NULL;
long ext_len;
ASN1_OBJECT *obj = NULL;
ASN1_OCTET_STRING *oct = NULL;
X509_EXTENSION *extension = NULL;
if (!(obj = OBJ_txt2obj(ext, 0))) {
X509V3err(X509V3_F_V3_GENERIC_EXTENSION,
X509V3_R_EXTENSION_NAME_ERROR);
ERR_add_error_data(2, "name=", ext);
goto err;
}
if (gen_type == 1)
ext_der = string_to_hex(value, &ext_len);
else if (gen_type == 2)
ext_der = generic_asn1(value, ctx, &ext_len);
if (ext_der == NULL) {
X509V3err(X509V3_F_V3_GENERIC_EXTENSION,
X509V3_R_EXTENSION_VALUE_ERROR);
ERR_add_error_data(2, "value=", value);
goto err;
}
if (!(oct = M_ASN1_OCTET_STRING_new())) {
X509V3err(X509V3_F_V3_GENERIC_EXTENSION, ERR_R_MALLOC_FAILURE);
goto err;
}
oct->data = ext_der;
oct->length = ext_len;
ext_der = NULL;
extension = X509_EXTENSION_create_by_OBJ(NULL, obj, crit, oct);
err:
ASN1_OBJECT_free(obj);
M_ASN1_OCTET_STRING_free(oct);
if (ext_der)
OPENSSL_free(ext_der);
return extension;
}
static unsigned char *generic_asn1(char *value, X509V3_CTX *ctx,
long *ext_len)
{
ASN1_TYPE *typ;
unsigned char *ext_der = NULL;
typ = ASN1_generate_v3(value, ctx);
if (typ == NULL)
return NULL;
*ext_len = i2d_ASN1_TYPE(typ, &ext_der);
ASN1_TYPE_free(typ);
return ext_der;
}
/*
* This is the main function: add a bunch of extensions based on a config
* file section to an extension STACK.
*/
int X509V3_EXT_add_nconf_sk(CONF *conf, X509V3_CTX *ctx, char *section,
STACK_OF(X509_EXTENSION) **sk)
{
X509_EXTENSION *ext;
STACK_OF(CONF_VALUE) *nval;
CONF_VALUE *val;
int i;
if (!(nval = NCONF_get_section(conf, section)))
return 0;
for (i = 0; i < sk_CONF_VALUE_num(nval); i++) {
val = sk_CONF_VALUE_value(nval, i);
if (!(ext = X509V3_EXT_nconf(conf, ctx, val->name, val->value)))
return 0;
- if (sk)
- X509v3_add_ext(sk, ext, -1);
+ if (sk != NULL) {
+ if (X509v3_add_ext(sk, ext, -1) == NULL) {
+ X509_EXTENSION_free(ext);
+ return 0;
+ }
+ }
X509_EXTENSION_free(ext);
}
return 1;
}
/*
* Convenience functions to add extensions to a certificate, CRL and request
*/
int X509V3_EXT_add_nconf(CONF *conf, X509V3_CTX *ctx, char *section,
X509 *cert)
{
STACK_OF(X509_EXTENSION) **sk = NULL;
if (cert)
sk = &cert->cert_info->extensions;
return X509V3_EXT_add_nconf_sk(conf, ctx, section, sk);
}
/* Same as above but for a CRL */
int X509V3_EXT_CRL_add_nconf(CONF *conf, X509V3_CTX *ctx, char *section,
X509_CRL *crl)
{
STACK_OF(X509_EXTENSION) **sk = NULL;
if (crl)
sk = &crl->crl->extensions;
return X509V3_EXT_add_nconf_sk(conf, ctx, section, sk);
}
/* Add extensions to certificate request */
int X509V3_EXT_REQ_add_nconf(CONF *conf, X509V3_CTX *ctx, char *section,
X509_REQ *req)
{
STACK_OF(X509_EXTENSION) *extlist = NULL, **sk = NULL;
int i;
if (req)
sk = &extlist;
i = X509V3_EXT_add_nconf_sk(conf, ctx, section, sk);
if (!i || !sk)
return i;
i = X509_REQ_add_extensions(req, extlist);
sk_X509_EXTENSION_pop_free(extlist, X509_EXTENSION_free);
return i;
}
/* Config database functions */
char *X509V3_get_string(X509V3_CTX *ctx, char *name, char *section)
{
if (!ctx->db || !ctx->db_meth || !ctx->db_meth->get_string) {
X509V3err(X509V3_F_X509V3_GET_STRING, X509V3_R_OPERATION_NOT_DEFINED);
return NULL;
}
if (ctx->db_meth->get_string)
return ctx->db_meth->get_string(ctx->db, name, section);
return NULL;
}
STACK_OF(CONF_VALUE) *X509V3_get_section(X509V3_CTX *ctx, char *section)
{
if (!ctx->db || !ctx->db_meth || !ctx->db_meth->get_section) {
X509V3err(X509V3_F_X509V3_GET_SECTION,
X509V3_R_OPERATION_NOT_DEFINED);
return NULL;
}
if (ctx->db_meth->get_section)
return ctx->db_meth->get_section(ctx->db, section);
return NULL;
}
void X509V3_string_free(X509V3_CTX *ctx, char *str)
{
if (!str)
return;
if (ctx->db_meth->free_string)
ctx->db_meth->free_string(ctx->db, str);
}
void X509V3_section_free(X509V3_CTX *ctx, STACK_OF(CONF_VALUE) *section)
{
if (!section)
return;
if (ctx->db_meth->free_section)
ctx->db_meth->free_section(ctx->db, section);
}
static char *nconf_get_string(void *db, char *section, char *value)
{
return NCONF_get_string(db, section, value);
}
static STACK_OF(CONF_VALUE) *nconf_get_section(void *db, char *section)
{
return NCONF_get_section(db, section);
}
static X509V3_CONF_METHOD nconf_method = {
nconf_get_string,
nconf_get_section,
NULL,
NULL
};
void X509V3_set_nconf(X509V3_CTX *ctx, CONF *conf)
{
ctx->db_meth = &nconf_method;
ctx->db = conf;
}
void X509V3_set_ctx(X509V3_CTX *ctx, X509 *issuer, X509 *subj, X509_REQ *req,
X509_CRL *crl, int flags)
{
ctx->issuer_cert = issuer;
ctx->subject_cert = subj;
ctx->crl = crl;
ctx->subject_req = req;
ctx->flags = flags;
}
/* Old conf compatibility functions */
X509_EXTENSION *X509V3_EXT_conf(LHASH_OF(CONF_VALUE) *conf, X509V3_CTX *ctx,
char *name, char *value)
{
CONF ctmp;
CONF_set_nconf(&ctmp, conf);
return X509V3_EXT_nconf(&ctmp, ctx, name, value);
}
/* LHASH *conf: Config file */
/* char *value: Value */
X509_EXTENSION *X509V3_EXT_conf_nid(LHASH_OF(CONF_VALUE) *conf,
X509V3_CTX *ctx, int ext_nid, char *value)
{
CONF ctmp;
CONF_set_nconf(&ctmp, conf);
return X509V3_EXT_nconf_nid(&ctmp, ctx, ext_nid, value);
}
static char *conf_lhash_get_string(void *db, char *section, char *value)
{
return CONF_get_string(db, section, value);
}
static STACK_OF(CONF_VALUE) *conf_lhash_get_section(void *db, char *section)
{
return CONF_get_section(db, section);
}
static X509V3_CONF_METHOD conf_lhash_method = {
conf_lhash_get_string,
conf_lhash_get_section,
NULL,
NULL
};
void X509V3_set_conf_lhash(X509V3_CTX *ctx, LHASH_OF(CONF_VALUE) *lhash)
{
ctx->db_meth = &conf_lhash_method;
ctx->db = lhash;
}
int X509V3_EXT_add_conf(LHASH_OF(CONF_VALUE) *conf, X509V3_CTX *ctx,
char *section, X509 *cert)
{
CONF ctmp;
CONF_set_nconf(&ctmp, conf);
return X509V3_EXT_add_nconf(&ctmp, ctx, section, cert);
}
/* Same as above but for a CRL */
int X509V3_EXT_CRL_add_conf(LHASH_OF(CONF_VALUE) *conf, X509V3_CTX *ctx,
char *section, X509_CRL *crl)
{
CONF ctmp;
CONF_set_nconf(&ctmp, conf);
return X509V3_EXT_CRL_add_nconf(&ctmp, ctx, section, crl);
}
/* Add extensions to certificate request */
int X509V3_EXT_REQ_add_conf(LHASH_OF(CONF_VALUE) *conf, X509V3_CTX *ctx,
char *section, X509_REQ *req)
{
CONF ctmp;
CONF_set_nconf(&ctmp, conf);
return X509V3_EXT_REQ_add_nconf(&ctmp, ctx, section, req);
}
diff --git a/crypto/x509v3/v3_info.c b/crypto/x509v3/v3_info.c
index 7064c725d98d..0c64b0adfcc9 100644
--- a/crypto/x509v3/v3_info.c
+++ b/crypto/x509v3/v3_info.c
@@ -1,217 +1,217 @@
/* v3_info.c */
/*
* Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL project
* 1999.
*/
/* ====================================================================
* Copyright (c) 1999 The OpenSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* licensing@OpenSSL.org.
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*
* This product includes cryptographic software written by Eric Young
* (eay@cryptsoft.com). This product includes software written by Tim
* Hudson (tjh@cryptsoft.com).
*
*/
#include <stdio.h>
#include "cryptlib.h"
#include <openssl/conf.h>
#include <openssl/asn1.h>
#include <openssl/asn1t.h>
#include <openssl/x509v3.h>
static STACK_OF(CONF_VALUE) *i2v_AUTHORITY_INFO_ACCESS(X509V3_EXT_METHOD
*method, AUTHORITY_INFO_ACCESS
*ainfo, STACK_OF(CONF_VALUE)
*ret);
static AUTHORITY_INFO_ACCESS *v2i_AUTHORITY_INFO_ACCESS(X509V3_EXT_METHOD
*method,
X509V3_CTX *ctx,
STACK_OF(CONF_VALUE)
*nval);
const X509V3_EXT_METHOD v3_info = { NID_info_access, X509V3_EXT_MULTILINE,
ASN1_ITEM_ref(AUTHORITY_INFO_ACCESS),
0, 0, 0, 0,
0, 0,
(X509V3_EXT_I2V) i2v_AUTHORITY_INFO_ACCESS,
(X509V3_EXT_V2I)v2i_AUTHORITY_INFO_ACCESS,
0, 0,
NULL
};
const X509V3_EXT_METHOD v3_sinfo = { NID_sinfo_access, X509V3_EXT_MULTILINE,
ASN1_ITEM_ref(AUTHORITY_INFO_ACCESS),
0, 0, 0, 0,
0, 0,
(X509V3_EXT_I2V) i2v_AUTHORITY_INFO_ACCESS,
(X509V3_EXT_V2I)v2i_AUTHORITY_INFO_ACCESS,
0, 0,
NULL
};
ASN1_SEQUENCE(ACCESS_DESCRIPTION) = {
ASN1_SIMPLE(ACCESS_DESCRIPTION, method, ASN1_OBJECT),
ASN1_SIMPLE(ACCESS_DESCRIPTION, location, GENERAL_NAME)
} ASN1_SEQUENCE_END(ACCESS_DESCRIPTION)
IMPLEMENT_ASN1_FUNCTIONS(ACCESS_DESCRIPTION)
ASN1_ITEM_TEMPLATE(AUTHORITY_INFO_ACCESS) =
ASN1_EX_TEMPLATE_TYPE(ASN1_TFLG_SEQUENCE_OF, 0, GeneralNames, ACCESS_DESCRIPTION)
ASN1_ITEM_TEMPLATE_END(AUTHORITY_INFO_ACCESS)
IMPLEMENT_ASN1_FUNCTIONS(AUTHORITY_INFO_ACCESS)
static STACK_OF(CONF_VALUE) *i2v_AUTHORITY_INFO_ACCESS(
X509V3_EXT_METHOD *method, AUTHORITY_INFO_ACCESS *ainfo,
STACK_OF(CONF_VALUE) *ret)
{
ACCESS_DESCRIPTION *desc;
int i, nlen;
char objtmp[80], *ntmp;
CONF_VALUE *vtmp;
STACK_OF(CONF_VALUE) *tret = ret;
for (i = 0; i < sk_ACCESS_DESCRIPTION_num(ainfo); i++) {
STACK_OF(CONF_VALUE) *tmp;
desc = sk_ACCESS_DESCRIPTION_value(ainfo, i);
tmp = i2v_GENERAL_NAME(method, desc->location, tret);
if (tmp == NULL)
goto err;
tret = tmp;
vtmp = sk_CONF_VALUE_value(tret, i);
- i2t_ASN1_OBJECT(objtmp, sizeof objtmp, desc->method);
+ i2t_ASN1_OBJECT(objtmp, sizeof(objtmp), desc->method);
nlen = strlen(objtmp) + strlen(vtmp->name) + 5;
ntmp = OPENSSL_malloc(nlen);
if (ntmp == NULL)
goto err;
BUF_strlcpy(ntmp, objtmp, nlen);
BUF_strlcat(ntmp, " - ", nlen);
BUF_strlcat(ntmp, vtmp->name, nlen);
OPENSSL_free(vtmp->name);
vtmp->name = ntmp;
}
if (ret == NULL && tret == NULL)
return sk_CONF_VALUE_new_null();
return tret;
err:
X509V3err(X509V3_F_I2V_AUTHORITY_INFO_ACCESS, ERR_R_MALLOC_FAILURE);
if (ret == NULL && tret != NULL)
sk_CONF_VALUE_pop_free(tret, X509V3_conf_free);
return NULL;
}
static AUTHORITY_INFO_ACCESS *v2i_AUTHORITY_INFO_ACCESS(X509V3_EXT_METHOD
*method,
X509V3_CTX *ctx,
STACK_OF(CONF_VALUE)
*nval)
{
AUTHORITY_INFO_ACCESS *ainfo = NULL;
CONF_VALUE *cnf, ctmp;
ACCESS_DESCRIPTION *acc;
int i, objlen;
char *objtmp, *ptmp;
if (!(ainfo = sk_ACCESS_DESCRIPTION_new_null())) {
X509V3err(X509V3_F_V2I_AUTHORITY_INFO_ACCESS, ERR_R_MALLOC_FAILURE);
return NULL;
}
for (i = 0; i < sk_CONF_VALUE_num(nval); i++) {
cnf = sk_CONF_VALUE_value(nval, i);
if (!(acc = ACCESS_DESCRIPTION_new())
|| !sk_ACCESS_DESCRIPTION_push(ainfo, acc)) {
X509V3err(X509V3_F_V2I_AUTHORITY_INFO_ACCESS,
ERR_R_MALLOC_FAILURE);
goto err;
}
ptmp = strchr(cnf->name, ';');
if (!ptmp) {
X509V3err(X509V3_F_V2I_AUTHORITY_INFO_ACCESS,
X509V3_R_INVALID_SYNTAX);
goto err;
}
objlen = ptmp - cnf->name;
ctmp.name = ptmp + 1;
ctmp.value = cnf->value;
if (!v2i_GENERAL_NAME_ex(acc->location, method, ctx, &ctmp, 0))
goto err;
if (!(objtmp = OPENSSL_malloc(objlen + 1))) {
X509V3err(X509V3_F_V2I_AUTHORITY_INFO_ACCESS,
ERR_R_MALLOC_FAILURE);
goto err;
}
strncpy(objtmp, cnf->name, objlen);
objtmp[objlen] = 0;
acc->method = OBJ_txt2obj(objtmp, 0);
if (!acc->method) {
X509V3err(X509V3_F_V2I_AUTHORITY_INFO_ACCESS,
X509V3_R_BAD_OBJECT);
ERR_add_error_data(2, "value=", objtmp);
OPENSSL_free(objtmp);
goto err;
}
OPENSSL_free(objtmp);
}
return ainfo;
err:
sk_ACCESS_DESCRIPTION_pop_free(ainfo, ACCESS_DESCRIPTION_free);
return NULL;
}
int i2a_ACCESS_DESCRIPTION(BIO *bp, ACCESS_DESCRIPTION *a)
{
i2a_ASN1_OBJECT(bp, a->method);
#ifdef UNDEF
i2a_GENERAL_NAME(bp, a->location);
#endif
return 2;
}
diff --git a/doc/apps/ca.pod b/doc/apps/ca.pod
index cc26bf48a3a7..8d94ecb4613e 100644
--- a/doc/apps/ca.pod
+++ b/doc/apps/ca.pod
@@ -1,697 +1,701 @@
=pod
=head1 NAME
openssl-ca,
ca - sample minimal CA application
=head1 SYNOPSIS
B<openssl> B<ca>
[B<-verbose>]
[B<-config filename>]
[B<-name section>]
[B<-gencrl>]
[B<-revoke file>]
[B<-status serial>]
[B<-updatedb>]
[B<-crl_reason reason>]
[B<-crl_hold instruction>]
[B<-crl_compromise time>]
[B<-crl_CA_compromise time>]
[B<-crldays days>]
[B<-crlhours hours>]
[B<-crlexts section>]
[B<-startdate date>]
[B<-enddate date>]
[B<-days arg>]
[B<-md arg>]
[B<-policy arg>]
[B<-keyfile arg>]
[B<-keyform PEM|DER>]
[B<-key arg>]
[B<-passin arg>]
[B<-cert file>]
[B<-selfsign>]
[B<-in file>]
[B<-out file>]
[B<-notext>]
[B<-outdir dir>]
[B<-infiles>]
[B<-spkac file>]
[B<-ss_cert file>]
[B<-preserveDN>]
[B<-noemailDN>]
[B<-batch>]
[B<-msie_hack>]
[B<-extensions section>]
[B<-extfile section>]
[B<-engine id>]
[B<-subj arg>]
[B<-utf8>]
[B<-multivalue-rdn>]
=head1 DESCRIPTION
The B<ca> command is a minimal CA application. It can be used
to sign certificate requests in a variety of forms and generate
CRLs it also maintains a text database of issued certificates
and their status.
The options descriptions will be divided into each purpose.
=head1 CA OPTIONS
=over 4
=item B<-config filename>
specifies the configuration file to use.
=item B<-name section>
specifies the configuration file section to use (overrides
B<default_ca> in the B<ca> section).
=item B<-in filename>
an input filename containing a single certificate request to be
signed by the CA.
=item B<-ss_cert filename>
a single self signed certificate to be signed by the CA.
=item B<-spkac filename>
a file containing a single Netscape signed public key and challenge
and additional field values to be signed by the CA. See the B<SPKAC FORMAT>
section for information on the required input and output format.
=item B<-infiles>
if present this should be the last option, all subsequent arguments
are assumed to the the names of files containing certificate requests.
=item B<-out filename>
the output file to output certificates to. The default is standard
output. The certificate details will also be printed out to this
file in PEM format (except that B<-spkac> outputs DER format).
=item B<-outdir directory>
the directory to output certificates to. The certificate will be
written to a filename consisting of the serial number in hex with
".pem" appended.
=item B<-cert>
the CA certificate file.
=item B<-keyfile filename>
the private key to sign requests with.
=item B<-keyform PEM|DER>
the format of the data in the private key file.
The default is PEM.
=item B<-key password>
the password used to encrypt the private key. Since on some
systems the command line arguments are visible (e.g. Unix with
the 'ps' utility) this option should be used with caution.
=item B<-selfsign>
indicates the issued certificates are to be signed with the key
the certificate requests were signed with (given with B<-keyfile>).
Cerificate requests signed with a different key are ignored. If
B<-spkac>, B<-ss_cert> or B<-gencrl> are given, B<-selfsign> is
ignored.
A consequence of using B<-selfsign> is that the self-signed
certificate appears among the entries in the certificate database
(see the configuration option B<database>), and uses the same
serial number counter as all other certificates sign with the
self-signed certificate.
=item B<-passin arg>
the key password source. For more information about the format of B<arg>
see the B<PASS PHRASE ARGUMENTS> section in L<openssl(1)|openssl(1)>.
=item B<-verbose>
this prints extra details about the operations being performed.
=item B<-notext>
don't output the text form of a certificate to the output file.
=item B<-startdate date>
this allows the start date to be explicitly set. The format of the
date is YYMMDDHHMMSSZ (the same as an ASN1 UTCTime structure).
=item B<-enddate date>
this allows the expiry date to be explicitly set. The format of the
date is YYMMDDHHMMSSZ (the same as an ASN1 UTCTime structure).
=item B<-days arg>
the number of days to certify the certificate for.
=item B<-md alg>
the message digest to use. Possible values include md5, sha1 and mdc2.
This option also applies to CRLs.
=item B<-policy arg>
this option defines the CA "policy" to use. This is a section in
the configuration file which decides which fields should be mandatory
or match the CA certificate. Check out the B<POLICY FORMAT> section
for more information.
=item B<-msie_hack>
this is a legacy option to make B<ca> work with very old versions of
the IE certificate enrollment control "certenr3". It used UniversalStrings
for almost everything. Since the old control has various security bugs
its use is strongly discouraged. The newer control "Xenroll" does not
need this option.
=item B<-preserveDN>
Normally the DN order of a certificate is the same as the order of the
fields in the relevant policy section. When this option is set the order
is the same as the request. This is largely for compatibility with the
older IE enrollment control which would only accept certificates if their
DNs match the order of the request. This is not needed for Xenroll.
=item B<-noemailDN>
The DN of a certificate can contain the EMAIL field if present in the
request DN, however it is good policy just having the e-mail set into
the altName extension of the certificate. When this option is set the
EMAIL field is removed from the certificate' subject and set only in
the, eventually present, extensions. The B<email_in_dn> keyword can be
used in the configuration file to enable this behaviour.
=item B<-batch>
this sets the batch mode. In this mode no questions will be asked
and all certificates will be certified automatically.
=item B<-extensions section>
the section of the configuration file containing certificate extensions
to be added when a certificate is issued (defaults to B<x509_extensions>
unless the B<-extfile> option is used). If no extension section is
present then, a V1 certificate is created. If the extension section
is present (even if it is empty), then a V3 certificate is created. See the:w
L<x509v3_config(5)|x509v3_config(5)> manual page for details of the
extension section format.
=item B<-extfile file>
an additional configuration file to read certificate extensions from
(using the default section unless the B<-extensions> option is also
used).
=item B<-engine id>
specifying an engine (by its unique B<id> string) will cause B<ca>
to attempt to obtain a functional reference to the specified engine,
thus initialising it if needed. The engine will then be set as the default
for all available algorithms.
=item B<-subj arg>
supersedes subject name given in the request.
The arg must be formatted as I</type0=value0/type1=value1/type2=...>,
characters may be escaped by \ (backslash), no spaces are skipped.
=item B<-utf8>
this option causes field values to be interpreted as UTF8 strings, by
default they are interpreted as ASCII. This means that the field
values, whether prompted from a terminal or obtained from a
configuration file, must be valid UTF8 strings.
=item B<-multivalue-rdn>
this option causes the -subj argument to be interpretedt with full
support for multivalued RDNs. Example:
I</DC=org/DC=OpenSSL/DC=users/UID=123456+CN=John Doe>
If -multi-rdn is not used then the UID value is I<123456+CN=John Doe>.
=back
=head1 CRL OPTIONS
=over 4
=item B<-gencrl>
this option generates a CRL based on information in the index file.
=item B<-crldays num>
the number of days before the next CRL is due. That is the days from
now to place in the CRL nextUpdate field.
=item B<-crlhours num>
the number of hours before the next CRL is due.
=item B<-revoke filename>
a filename containing a certificate to revoke.
=item B<-status serial>
displays the revocation status of the certificate with the specified
serial number and exits.
=item B<-updatedb>
Updates the database index to purge expired certificates.
=item B<-crl_reason reason>
revocation reason, where B<reason> is one of: B<unspecified>, B<keyCompromise>,
B<CACompromise>, B<affiliationChanged>, B<superseded>, B<cessationOfOperation>,
B<certificateHold> or B<removeFromCRL>. The matching of B<reason> is case
insensitive. Setting any revocation reason will make the CRL v2.
In practive B<removeFromCRL> is not particularly useful because it is only used
in delta CRLs which are not currently implemented.
=item B<-crl_hold instruction>
This sets the CRL revocation reason code to B<certificateHold> and the hold
instruction to B<instruction> which must be an OID. Although any OID can be
used only B<holdInstructionNone> (the use of which is discouraged by RFC2459)
B<holdInstructionCallIssuer> or B<holdInstructionReject> will normally be used.
=item B<-crl_compromise time>
This sets the revocation reason to B<keyCompromise> and the compromise time to
B<time>. B<time> should be in GeneralizedTime format that is B<YYYYMMDDHHMMSSZ>.
=item B<-crl_CA_compromise time>
This is the same as B<crl_compromise> except the revocation reason is set to
B<CACompromise>.
=item B<-crlexts section>
the section of the configuration file containing CRL extensions to
include. If no CRL extension section is present then a V1 CRL is
created, if the CRL extension section is present (even if it is
empty) then a V2 CRL is created. The CRL extensions specified are
CRL extensions and B<not> CRL entry extensions. It should be noted
that some software (for example Netscape) can't handle V2 CRLs. See
L<x509v3_config(5)|x509v3_config(5)> manual page for details of the
extension section format.
=back
=head1 CONFIGURATION FILE OPTIONS
The section of the configuration file containing options for B<ca>
is found as follows: If the B<-name> command line option is used,
then it names the section to be used. Otherwise the section to
be used must be named in the B<default_ca> option of the B<ca> section
of the configuration file (or in the default section of the
configuration file). Besides B<default_ca>, the following options are
read directly from the B<ca> section:
RANDFILE
preserve
msie_hack
With the exception of B<RANDFILE>, this is probably a bug and may
change in future releases.
Many of the configuration file options are identical to command line
options. Where the option is present in the configuration file
and the command line the command line value is used. Where an
option is described as mandatory then it must be present in
the configuration file or the command line equivalent (if
any) used.
=over 4
=item B<oid_file>
This specifies a file containing additional B<OBJECT IDENTIFIERS>.
Each line of the file should consist of the numerical form of the
object identifier followed by white space then the short name followed
by white space and finally the long name.
=item B<oid_section>
This specifies a section in the configuration file containing extra
object identifiers. Each line should consist of the short name of the
object identifier followed by B<=> and the numerical form. The short
and long names are the same when this option is used.
=item B<new_certs_dir>
the same as the B<-outdir> command line option. It specifies
the directory where new certificates will be placed. Mandatory.
=item B<certificate>
the same as B<-cert>. It gives the file containing the CA
certificate. Mandatory.
=item B<private_key>
same as the B<-keyfile> option. The file containing the
CA private key. Mandatory.
=item B<RANDFILE>
a file used to read and write random number seed information, or
an EGD socket (see L<RAND_egd(3)|RAND_egd(3)>).
=item B<default_days>
the same as the B<-days> option. The number of days to certify
a certificate for.
=item B<default_startdate>
the same as the B<-startdate> option. The start date to certify
a certificate for. If not set the current time is used.
=item B<default_enddate>
the same as the B<-enddate> option. Either this option or
B<default_days> (or the command line equivalents) must be
present.
=item B<default_crl_hours default_crl_days>
the same as the B<-crlhours> and the B<-crldays> options. These
will only be used if neither command line option is present. At
least one of these must be present to generate a CRL.
=item B<default_md>
the same as the B<-md> option. The message digest to use. Mandatory.
=item B<database>
the text database file to use. Mandatory. This file must be present
though initially it will be empty.
=item B<unique_subject>
if the value B<yes> is given, the valid certificate entries in the
database must have unique subjects. if the value B<no> is given,
several valid certificate entries may have the exact same subject.
The default value is B<yes>, to be compatible with older (pre 0.9.8)
versions of OpenSSL. However, to make CA certificate roll-over easier,
it's recommended to use the value B<no>, especially if combined with
the B<-selfsign> command line option.
+Note that it is valid in some circumstances for certificates to be created
+without any subject. In the case where there are multiple certificates without
+subjects this does not count as a duplicate.
+
=item B<serial>
a text file containing the next serial number to use in hex. Mandatory.
This file must be present and contain a valid serial number.
=item B<crlnumber>
a text file containing the next CRL number to use in hex. The crl number
will be inserted in the CRLs only if this file exists. If this file is
present, it must contain a valid CRL number.
=item B<x509_extensions>
the same as B<-extensions>.
=item B<crl_extensions>
the same as B<-crlexts>.
=item B<preserve>
the same as B<-preserveDN>
=item B<email_in_dn>
the same as B<-noemailDN>. If you want the EMAIL field to be removed
from the DN of the certificate simply set this to 'no'. If not present
the default is to allow for the EMAIL filed in the certificate's DN.
=item B<msie_hack>
the same as B<-msie_hack>
=item B<policy>
the same as B<-policy>. Mandatory. See the B<POLICY FORMAT> section
for more information.
=item B<name_opt>, B<cert_opt>
these options allow the format used to display the certificate details
when asking the user to confirm signing. All the options supported by
the B<x509> utilities B<-nameopt> and B<-certopt> switches can be used
here, except the B<no_signame> and B<no_sigdump> are permanently set
and cannot be disabled (this is because the certificate signature cannot
be displayed because the certificate has not been signed at this point).
For convenience the values B<ca_default> are accepted by both to produce
a reasonable output.
If neither option is present the format used in earlier versions of
OpenSSL is used. Use of the old format is B<strongly> discouraged because
it only displays fields mentioned in the B<policy> section, mishandles
multicharacter string types and does not display extensions.
=item B<copy_extensions>
determines how extensions in certificate requests should be handled.
If set to B<none> or this option is not present then extensions are
ignored and not copied to the certificate. If set to B<copy> then any
extensions present in the request that are not already present are copied
to the certificate. If set to B<copyall> then all extensions in the
request are copied to the certificate: if the extension is already present
in the certificate it is deleted first. See the B<WARNINGS> section before
using this option.
The main use of this option is to allow a certificate request to supply
values for certain extensions such as subjectAltName.
=back
=head1 POLICY FORMAT
The policy section consists of a set of variables corresponding to
certificate DN fields. If the value is "match" then the field value
must match the same field in the CA certificate. If the value is
"supplied" then it must be present. If the value is "optional" then
it may be present. Any fields not mentioned in the policy section
are silently deleted, unless the B<-preserveDN> option is set but
this can be regarded more of a quirk than intended behaviour.
=head1 SPKAC FORMAT
The input to the B<-spkac> command line option is a Netscape
signed public key and challenge. This will usually come from
the B<KEYGEN> tag in an HTML form to create a new private key.
It is however possible to create SPKACs using the B<spkac> utility.
The file should contain the variable SPKAC set to the value of
the SPKAC and also the required DN components as name value pairs.
If you need to include the same component twice then it can be
preceded by a number and a '.'.
When processing SPKAC format, the output is DER if the B<-out>
flag is used, but PEM format if sending to stdout or the B<-outdir>
flag is used.
=head1 EXAMPLES
Note: these examples assume that the B<ca> directory structure is
already set up and the relevant files already exist. This usually
involves creating a CA certificate and private key with B<req>, a
serial number file and an empty index file and placing them in
the relevant directories.
To use the sample configuration file below the directories demoCA,
demoCA/private and demoCA/newcerts would be created. The CA
certificate would be copied to demoCA/cacert.pem and its private
key to demoCA/private/cakey.pem. A file demoCA/serial would be
created containing for example "01" and the empty index file
demoCA/index.txt.
Sign a certificate request:
openssl ca -in req.pem -out newcert.pem
Sign a certificate request, using CA extensions:
openssl ca -in req.pem -extensions v3_ca -out newcert.pem
Generate a CRL
openssl ca -gencrl -out crl.pem
Sign several requests:
openssl ca -infiles req1.pem req2.pem req3.pem
Certify a Netscape SPKAC:
openssl ca -spkac spkac.txt
A sample SPKAC file (the SPKAC line has been truncated for clarity):
SPKAC=MIG0MGAwXDANBgkqhkiG9w0BAQEFAANLADBIAkEAn7PDhCeV/xIxUg8V70YRxK2A5
CN=Steve Test
emailAddress=steve@openssl.org
0.OU=OpenSSL Group
1.OU=Another Group
A sample configuration file with the relevant sections for B<ca>:
[ ca ]
default_ca = CA_default # The default ca section
[ CA_default ]
dir = ./demoCA # top dir
database = $dir/index.txt # index file.
new_certs_dir = $dir/newcerts # new certs dir
certificate = $dir/cacert.pem # The CA cert
serial = $dir/serial # serial no file
private_key = $dir/private/cakey.pem# CA private key
RANDFILE = $dir/private/.rand # random number file
default_days = 365 # how long to certify for
default_crl_days= 30 # how long before next CRL
default_md = md5 # md to use
policy = policy_any # default policy
email_in_dn = no # Don't add the email into cert DN
name_opt = ca_default # Subject name display option
cert_opt = ca_default # Certificate display option
copy_extensions = none # Don't copy extensions from request
[ policy_any ]
countryName = supplied
stateOrProvinceName = optional
organizationName = optional
organizationalUnitName = optional
commonName = supplied
emailAddress = optional
=head1 FILES
Note: the location of all files can change either by compile time options,
configuration file entries, environment variables or command line options.
The values below reflect the default values.
/usr/local/ssl/lib/openssl.cnf - master configuration file
./demoCA - main CA directory
./demoCA/cacert.pem - CA certificate
./demoCA/private/cakey.pem - CA private key
./demoCA/serial - CA serial number file
./demoCA/serial.old - CA serial number backup file
./demoCA/index.txt - CA text database file
./demoCA/index.txt.old - CA text database backup file
./demoCA/certs - certificate output file
./demoCA/.rnd - CA random seed information
=head1 ENVIRONMENT VARIABLES
B<OPENSSL_CONF> reflects the location of master configuration file it can
be overridden by the B<-config> command line option.
=head1 RESTRICTIONS
The text database index file is a critical part of the process and
if corrupted it can be difficult to fix. It is theoretically possible
to rebuild the index file from all the issued certificates and a current
CRL: however there is no option to do this.
V2 CRL features like delta CRLs are not currently supported.
Although several requests can be input and handled at once it is only
possible to include one SPKAC or self signed certificate.
=head1 BUGS
The use of an in memory text database can cause problems when large
numbers of certificates are present because, as the name implies
the database has to be kept in memory.
The B<ca> command really needs rewriting or the required functionality
exposed at either a command or interface level so a more friendly utility
(perl script or GUI) can handle things properly. The scripts B<CA.sh> and
B<CA.pl> help a little but not very much.
Any fields in a request that are not present in a policy are silently
deleted. This does not happen if the B<-preserveDN> option is used. To
enforce the absence of the EMAIL field within the DN, as suggested by
RFCs, regardless the contents of the request' subject the B<-noemailDN>
option can be used. The behaviour should be more friendly and
configurable.
Cancelling some commands by refusing to certify a certificate can
create an empty file.
=head1 WARNINGS
The B<ca> command is quirky and at times downright unfriendly.
The B<ca> utility was originally meant as an example of how to do things
in a CA. It was not supposed to be used as a full blown CA itself:
nevertheless some people are using it for this purpose.
The B<ca> command is effectively a single user command: no locking is
done on the various files and attempts to run more than one B<ca> command
on the same database can have unpredictable results.
The B<copy_extensions> option should be used with caution. If care is
not taken then it can be a security risk. For example if a certificate
request contains a basicConstraints extension with CA:TRUE and the
B<copy_extensions> value is set to B<copyall> and the user does not spot
this when the certificate is displayed then this will hand the requestor
a valid CA certificate.
This situation can be avoided by setting B<copy_extensions> to B<copy>
and including basicConstraints with CA:FALSE in the configuration file.
Then if the request contains a basicConstraints extension it will be
ignored.
It is advisable to also include values for other extensions such
as B<keyUsage> to prevent a request supplying its own values.
Additional restrictions can be placed on the CA certificate itself.
For example if the CA certificate has:
basicConstraints = CA:TRUE, pathlen:0
then even if a certificate is issued with CA:TRUE it will not be valid.
=head1 SEE ALSO
L<req(1)|req(1)>, L<spkac(1)|spkac(1)>, L<x509(1)|x509(1)>, L<CA.pl(1)|CA.pl(1)>,
L<config(5)|config(5)>, L<x509v3_config(5)|x509v3_config(5)>
=cut
diff --git a/doc/apps/ecparam.pod b/doc/apps/ecparam.pod
index ba2f3b9ae274..9482095266dc 100644
--- a/doc/apps/ecparam.pod
+++ b/doc/apps/ecparam.pod
@@ -1,180 +1,180 @@
=pod
=head1 NAME
openssl-ecparam,
ecparam - EC parameter manipulation and generation
=head1 SYNOPSIS
B<openssl ecparam>
[B<-inform DER|PEM>]
[B<-outform DER|PEM>]
[B<-in filename>]
[B<-out filename>]
[B<-noout>]
[B<-text>]
[B<-C>]
[B<-check>]
[B<-name arg>]
[B<-list_curves>]
[B<-conv_form arg>]
[B<-param_enc arg>]
[B<-no_seed>]
[B<-rand file(s)>]
[B<-genkey>]
[B<-engine id>]
=head1 DESCRIPTION
This command is used to manipulate or generate EC parameter files.
=head1 OPTIONS
=over 4
=item B<-inform DER|PEM>
This specifies the input format. The B<DER> option uses an ASN.1 DER encoded
form compatible with RFC 3279 EcpkParameters. The PEM form is the default
format: it consists of the B<DER> format base64 encoded with additional
header and footer lines.
=item B<-outform DER|PEM>
This specifies the output format, the options have the same meaning as the
B<-inform> option.
=item B<-in filename>
This specifies the input filename to read parameters from or standard input if
this option is not specified.
=item B<-out filename>
This specifies the output filename parameters to. Standard output is used
if this option is not present. The output filename should B<not> be the same
as the input filename.
=item B<-noout>
This option inhibits the output of the encoded version of the parameters.
=item B<-text>
This option prints out the EC parameters in human readable form.
=item B<-C>
This option converts the EC parameters into C code. The parameters can then
be loaded by calling the B<get_ec_group_XXX()> function.
=item B<-check>
Validate the elliptic curve parameters.
=item B<-name arg>
Use the EC parameters with the specified 'short' name. Use B<-list_curves>
to get a list of all currently implemented EC parameters.
=item B<-list_curves>
If this options is specified B<ecparam> will print out a list of all
currently implemented EC parameters names and exit.
=item B<-conv_form>
This specifies how the points on the elliptic curve are converted
-into octet strings. Possible values are: B<compressed> (the default
-value), B<uncompressed> and B<hybrid>. For more information regarding
+into octet strings. Possible values are: B<compressed>, B<uncompressed> (the
+default value) and B<hybrid>. For more information regarding
the point conversion forms please read the X9.62 standard.
B<Note> Due to patent issues the B<compressed> option is disabled
by default for binary curves and can be enabled by defining
the preprocessor macro B<OPENSSL_EC_BIN_PT_COMP> at compile time.
=item B<-param_enc arg>
This specifies how the elliptic curve parameters are encoded.
Possible value are: B<named_curve>, i.e. the ec parameters are
specified by a OID, or B<explicit> where the ec parameters are
explicitly given (see RFC 3279 for the definition of the
EC parameters structures). The default value is B<named_curve>.
B<Note> the B<implicitlyCA> alternative ,as specified in RFC 3279,
is currently not implemented in OpenSSL.
=item B<-no_seed>
This option inhibits that the 'seed' for the parameter generation
is included in the ECParameters structure (see RFC 3279).
=item B<-genkey>
This option will generate a EC private key using the specified parameters.
=item B<-rand file(s)>
a file or files containing random data used to seed the random number
generator, or an EGD socket (see L<RAND_egd(3)|RAND_egd(3)>).
Multiple files can be specified separated by a OS-dependent character.
The separator is B<;> for MS-Windows, B<,> for OpenVMS, and B<:> for
all others.
=item B<-engine id>
specifying an engine (by its unique B<id> string) will cause B<ecparam>
to attempt to obtain a functional reference to the specified engine,
thus initialising it if needed. The engine will then be set as the default
for all available algorithms.
=back
=head1 NOTES
PEM format EC parameters use the header and footer lines:
-----BEGIN EC PARAMETERS-----
-----END EC PARAMETERS-----
OpenSSL is currently not able to generate new groups and therefore
B<ecparam> can only create EC parameters from known (named) curves.
=head1 EXAMPLES
To create EC parameters with the group 'prime192v1':
openssl ecparam -out ec_param.pem -name prime192v1
To create EC parameters with explicit parameters:
openssl ecparam -out ec_param.pem -name prime192v1 -param_enc explicit
To validate given EC parameters:
openssl ecparam -in ec_param.pem -check
To create EC parameters and a private key:
openssl ecparam -out ec_key.pem -name prime192v1 -genkey
To change the point encoding to 'compressed':
openssl ecparam -in ec_in.pem -out ec_out.pem -conv_form compressed
To print out the EC parameters to standard output:
openssl ecparam -in ec_param.pem -noout -text
=head1 SEE ALSO
L<ec(1)|ec(1)>, L<dsaparam(1)|dsaparam(1)>
=head1 HISTORY
The ecparam command was first introduced in OpenSSL 0.9.8.
=head1 AUTHOR
Nils Larsch for the OpenSSL project (http://www.openssl.org)
=cut
diff --git a/doc/apps/s_client.pod b/doc/apps/s_client.pod
index d9413a0cf211..d2cad29d218b 100644
--- a/doc/apps/s_client.pod
+++ b/doc/apps/s_client.pod
@@ -1,388 +1,388 @@
=pod
=head1 NAME
openssl-s_client,
s_client - SSL/TLS client program
=head1 SYNOPSIS
B<openssl> B<s_client>
[B<-connect host:port>]
[B<-servername name>]
[B<-verify depth>]
[B<-verify_return_error>]
[B<-cert filename>]
[B<-certform DER|PEM>]
[B<-key filename>]
[B<-keyform DER|PEM>]
[B<-pass arg>]
[B<-CApath directory>]
[B<-CAfile filename>]
[B<-no_alt_chains>]
[B<-reconnect>]
[B<-pause>]
[B<-showcerts>]
[B<-debug>]
[B<-msg>]
[B<-nbio_test>]
[B<-state>]
[B<-nbio>]
[B<-crlf>]
[B<-ign_eof>]
[B<-no_ign_eof>]
[B<-quiet>]
[B<-ssl2>]
[B<-ssl3>]
[B<-tls1>]
[B<-no_ssl2>]
[B<-no_ssl3>]
[B<-no_tls1>]
[B<-no_tls1_1>]
[B<-no_tls1_2>]
[B<-fallback_scsv>]
[B<-bugs>]
[B<-sigalgs sigalglist>]
[B<-curves curvelist>]
[B<-cipher cipherlist>]
[B<-serverpref>]
[B<-starttls protocol>]
[B<-engine id>]
[B<-tlsextdebug>]
[B<-no_ticket>]
[B<-sess_out filename>]
[B<-sess_in filename>]
[B<-rand file(s)>]
[B<-serverinfo types>]
[B<-status>]
[B<-alpn protocols>]
[B<-nextprotoneg protocols>]
=head1 DESCRIPTION
The B<s_client> 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
=over 4
=item B<-connect host:port>
This specifies the host and optional port to connect to. If not specified
then an attempt is made to connect to the local host on port 4433.
=item B<-servername name>
Set the TLS SNI (Server Name Indication) extension in the ClientHello message.
=item B<-cert certname>
The certificate to use, if one is requested by the server. The default is
not to use a certificate.
=item B<-certform format>
The certificate format to use: DER or PEM. PEM is the default.
=item B<-key keyfile>
The private key to use. If not specified then the certificate file will
be used.
=item B<-keyform format>
The private format to use: DER or PEM. PEM is the default.
=item B<-pass arg>
the private key password source. For more information about the format of B<arg>
see the B<PASS PHRASE ARGUMENTS> section in L<openssl(1)|openssl(1)>.
=item B<-verify 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<-CApath directory>
The directory to use for server certificate verification. This directory
must be in "hash format", see B<verify> for more information. These are
also used when building the client certificate chain.
=item B<-CAfile file>
A file containing trusted certificates to use during server authentication
and to use when attempting to build the client certificate chain.
=item B<-purpose, -ignore_critical, -issuer_checks, -crl_check, -crl_check_all, -policy_check, -extended_crl, -x509_strict, -policy -check_ss_sig -no_alt_chains>
Set various certificate chain valiadition option. See the
L<B<verify>|verify(1)> manual page for details.
=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<-pause>
pauses 1 second between each read and write call.
=item B<-showcerts>
display the whole server certificate chain: normally only the server
certificate itself is displayed.
=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<-msg>
show all protocol messages with hex dump.
=item B<-nbio_test>
tests non-blocking I/O
=item B<-nbio>
turns on non-blocking 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 identity>
Use the PSK identity B<identity> when using a PSK cipher suite.
The default value is "Client_identity" (without the quotes).
=item B<-psk key>
Use the PSK key B<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<-ssl2>, B<-ssl3>, B<-tls1>, B<-tls1_1>, B<-tls1_2>, B<-no_ssl2>, B<-no_ssl3>, B<-no_tls1>, B<-no_tls1_1>, B<-no_tls1_2>
These options require or disable the use of the specified SSL or TLS protocols.
By default the initial handshake uses a I<version-flexible> method which will
negotiate the highest mutually supported protocol version.
=item B<-fallback_scsv>
Send TLS_FALLBACK_SCSV in the ClientHello.
=item B<-bugs>
there are several known bug in SSL and TLS implementations. Adding this
option enables various workarounds.
=item B<-sigalgs 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 curvelist>
Specifies the list of supported curves to be sent by the client. The curve is
is ultimately selected by the server. For a list of all curves, use:
$ openssl ecparam -list_curves
=item B<-cipher cipherlist>
this allows the cipher list sent by the client to be modified. Although
the server determines which cipher suite is used it should take the first
supported cipher in the list sent by the client. See the B<ciphers>
command for more information.
=item B<-serverpref>
use the server's cipher preferences; only used for SSLV2.
=item B<-starttls protocol>
send the protocol-specific message(s) to switch to TLS for communication.
B<protocol> is a keyword for the intended protocol. Currently, the only
-supported keywords are "smtp", "pop3", "imap", and "ftp".
+supported keywords are "smtp", "pop3", "imap", "ftp" and "xmpp".
=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 filename>
output SSL session to B<filename>
=item B<-sess_in sess.pem>
load SSL session from B<filename>. The client will attempt to resume a
connection from this session.
=item B<-engine id>
specifying an engine (by its unique B<id> string) will cause B<s_client>
to attempt to obtain a functional reference to the specified engine,
thus initialising it if needed. The engine will then be set as the default
for all available algorithms.
=item B<-rand file(s)>
a file or files containing random data used to seed the random number
generator, or an EGD socket (see L<RAND_egd(3)|RAND_egd(3)>).
Multiple files can be specified separated by a OS-dependent character.
The separator is B<;> for MS-Windows, B<,> for OpenVMS, and B<:> for
all others.
=item B<-serverinfo 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 protocols>, B<-nextprotoneg protocols>
these flags enable the
Enable the Application-Layer Protocol Negotiation or Next Protocol
Negotiation extension, respectively. ALPN is the IETF standard and
replaces NPN.
The B<protocols> list is a
comma-separated protocol names that the client should advertise
support for. The list should contain most wanted protocols first.
Protocol names are printable ASCII strings, for example "http/1.1" or
"spdy/3".
Empty list of protocols is treated specially and will cause the client to
advertise support for the TLS extension but disconnect just after
reciving ServerHello with a list of server supported protocols.
=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. When used interactively (which means neither B<-quiet> nor B<-ign_eof>
have been given), the session will be renegotiated if the line begins with an
B<R>, and if the line begins with a B<Q> or if end of file is reached, the
connection will be closed down.
=head1 NOTES
B<s_client> 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<-ssl2>,
B<-ssl3>, B<-tls1>, B<-no_ssl2>, 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 B<s_client> 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. Therefor 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 the whole chain.
Since the SSLv23 client hello cannot include compression methods or extensions
these will only be supported if its use is disabled, for example by using the
B<-no_sslv2> option.
The B<s_client> utility 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. None 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.
=head1 BUGS
Because this program has a lot of options and also because some of
the techniques used are rather old, the C source of s_client 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<sess_id(1)|sess_id(1)>, L<s_server(1)|s_server(1)>, L<ciphers(1)|ciphers(1)>
=head1 HISTORY
The -no_alt_chains options was first added to OpenSSL 1.0.2b.
=cut
diff --git a/doc/apps/verify.pod b/doc/apps/verify.pod
index 321d5ac7e126..2516718979f2 100644
--- a/doc/apps/verify.pod
+++ b/doc/apps/verify.pod
@@ -1,458 +1,458 @@
=pod
=head1 NAME
openssl-verify,
verify - Utility to verify certificates.
=head1 SYNOPSIS
B<openssl> B<verify>
[B<-CApath directory>]
[B<-CAfile file>]
[B<-purpose purpose>]
[B<-policy arg>]
[B<-ignore_critical>]
[B<-attime timestamp>]
[B<-check_ss_sig>]
-[B<-crlfile file>]
+[B<-CRLfile file>]
[B<-crl_download>]
[B<-crl_check>]
[B<-crl_check_all>]
[B<-policy_check>]
[B<-explicit_policy>]
[B<-inhibit_any>]
[B<-inhibit_map>]
[B<-x509_strict>]
[B<-extended_crl>]
[B<-use_deltas>]
[B<-policy_print>]
[B<-no_alt_chains>]
[B<-allow_proxy_certs>]
[B<-untrusted file>]
[B<-help>]
[B<-issuer_checks>]
[B<-trusted file>]
[B<-verbose>]
[B<->]
[certificates]
=head1 DESCRIPTION
The B<verify> command verifies certificate chains.
=head1 COMMAND OPTIONS
=over 4
=item B<-CApath directory>
A directory of trusted certificates. The certificates should have names
of the form: hash.0 or have symbolic links to them of this
form ("hash" is the hashed certificate subject name: see the B<-hash> option
of the B<x509> utility). Under Unix the B<c_rehash> script will automatically
create symbolic links to a directory of certificates.
=item B<-CAfile file>
A file of trusted certificates. The file should contain multiple certificates
in PEM format concatenated together.
=item B<-attime timestamp>
Perform validation checks using time specified by B<timestamp> and not
current system time. B<timestamp> is the number of seconds since
01.01.1970 (UNIX time).
=item B<-check_ss_sig>
Verify the signature on the self-signed root CA. This is disabled by default
because it doesn't add any security.
-=item B<-crlfile file>
+=item B<-CRLfile file>
File containing one or more CRL's (in PEM format) to load.
=item B<-crl_download>
Attempt to download CRL information for this certificate.
=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<-untrusted file>
A file of untrusted certificates. The file should contain multiple certificates
in PEM format concatenated together.
=item B<-purpose purpose>
The intended use for the certificate. If this option is not specified,
B<verify> will not consider certificate purpose during chain verification.
Currently accepted uses are B<sslclient>, B<sslserver>, B<nssslserver>,
B<smimesign>, B<smimeencrypt>. See the B<VERIFY OPERATION> section for more
information.
=item B<-help>
Print out a usage message.
=item B<-verbose>
Print extra information about the operations being performed.
=item B<-issuer_checks>
Print out diagnostics relating to searches for the issuer certificate of the
current certificate. This shows why each candidate issuer certificate was
rejected. The presence of rejection messages does not itself imply that
anything is wrong; during the normal verification process, several
rejections may take place.
=item B<-policy arg>
Enable policy processing and add B<arg> to the user-initial-policy-set (see
RFC5280). The policy B<arg> can be an object name an OID in numeric form.
This argument can appear more than once.
=item B<-policy_check>
Enables certificate policy processing.
=item B<-explicit_policy>
Set policy variable require-explicit-policy (see RFC5280).
=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<-no_alt_chains>
When building a certificate chain, if the first certificate chain found is not
trusted, then OpenSSL will continue to check to see if an alternative chain can
be found that is trusted. With this option that behaviour is suppressed so that
only the first chain found is ever used. Using this option will force the
behaviour to match that of previous OpenSSL versions.
=item B<-allow_proxy_certs>
Allow the verification of proxy certificates.
=item B<-trusted file>
A file of additional trusted certificates. The file should contain multiple
certificates in PEM format concatenated together.
=item B<-policy_print>
Print out diagnostics related to policy processing.
=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<-ignore_critical>
Normally if an unhandled critical extension is present which is not
supported by OpenSSL the certificate is rejected (as required by RFC5280).
If this option is set critical extensions are ignored.
=item B<-x509_strict>
For strict X.509 compliance, disable non-compliant workarounds for broken
certificates.
=item B<-extended_crl>
Enable extended CRL features such as indirect CRLs and alternate CRL
signing keys.
=item B<-use_deltas>
Enable support for delta CRLs.
=item B<-check_ss_sig>
Verify the signature on the self-signed root CA. This is disabled by default
because it doesn't add any security.
=item B<->
Indicates the last option. All arguments following this are assumed to be
certificate files. This is useful if the first certificate filename begins
with a B<->.
=item B<certificates>
One or more certificates to verify. If no certificates are given, B<verify>
will attempt to read a certificate from standard input. Certificates must be
in PEM format.
=back
=head1 VERIFY OPERATION
The B<verify> program uses the same functions as the internal SSL and S/MIME
verification, therefore this description applies to these verify operations
too.
There is one crucial difference between the verify operations performed
by the B<verify> program: wherever possible an attempt is made to continue
after an error whereas normally the verify operation would halt on the
first error. This allows all the problems with a certificate chain to be
determined.
The verify operation consists of a number of separate steps.
Firstly a certificate chain is built up starting from the supplied certificate
and ending in the root CA. It is an error if the whole chain cannot be built
up. The chain is built up by looking up the issuers certificate of the current
certificate. If a certificate is found which is its own issuer it is assumed
to be the root CA.
The process of 'looking up the issuers certificate' itself involves a number
of steps. In versions of OpenSSL before 0.9.5a the first certificate whose
subject name matched the issuer of the current certificate was assumed to be
the issuers certificate. In OpenSSL 0.9.6 and later all certificates
whose subject name matches the issuer name of the current certificate are
subject to further tests. The relevant authority key identifier components
of the current certificate (if present) must match the subject key identifier
(if present) and issuer and serial number of the candidate issuer, in addition
the keyUsage extension of the candidate issuer (if present) must permit
certificate signing.
The lookup first looks in the list of untrusted certificates and if no match
is found the remaining lookups are from the trusted certificates. The root CA
is always looked up in the trusted certificate list: if the certificate to
verify is a root certificate then an exact match must be found in the trusted
list.
The second operation is to check every untrusted certificate's extensions for
consistency with the supplied purpose. If the B<-purpose> option is not included
then no checks are done. The supplied or "leaf" certificate must have extensions
compatible with the supplied purpose and all other certificates must also be valid
CA certificates. The precise extensions required are described in more detail in
the B<CERTIFICATE EXTENSIONS> section of the B<x509> utility.
The third operation is to check the trust settings on the root CA. The root
CA should be trusted for the supplied purpose. For compatibility with previous
versions of SSLeay and OpenSSL a certificate with no trust settings is considered
to be valid for all purposes.
The final operation is to check the validity of the certificate chain. The validity
period is checked against the current system time and the notBefore and notAfter
dates in the certificate. The certificate signatures are also checked at this
point.
If all operations complete successfully then certificate is considered valid. If
any operation fails then the certificate is not valid.
=head1 DIAGNOSTICS
When a verify operation fails the output messages can be somewhat cryptic. The
general form of the error message is:
server.pem: /C=AU/ST=Queensland/O=CryptSoft Pty Ltd/CN=Test CA (1024 bit)
error 24 at 1 depth lookup:invalid CA certificate
The first line contains the name of the certificate being verified followed by
the subject name of the certificate. The second line contains the error number
and the depth. The depth is number of the certificate being verified when a
problem was detected starting with zero for the certificate being verified itself
then 1 for the CA that signed the certificate and so on. Finally a text version
of the error number is presented.
An exhaustive list of the error codes and messages is shown below, this also
includes the name of the error code as defined in the header file x509_vfy.h
Some of the error codes are defined but never returned: these are described
as "unused".
=over 4
=item B<0 X509_V_OK: ok>
the operation was successful.
=item B<2 X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT: unable to get issuer certificate>
the issuer certificate of a looked up certificate could not be found. This
normally means the list of trusted certificates is not complete.
=item B<3 X509_V_ERR_UNABLE_TO_GET_CRL: unable to get certificate CRL>
the CRL of a certificate could not be found.
=item B<4 X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE: unable to decrypt certificate's signature>
the certificate signature could not be decrypted. This means that the actual signature value
could not be determined rather than it not matching the expected value, this is only
meaningful for RSA keys.
=item B<5 X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE: unable to decrypt CRL's signature>
the CRL signature could not be decrypted: this means that the actual signature value
could not be determined rather than it not matching the expected value. Unused.
=item B<6 X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY: unable to decode issuer public key>
the public key in the certificate SubjectPublicKeyInfo could not be read.
=item B<7 X509_V_ERR_CERT_SIGNATURE_FAILURE: certificate signature failure>
the signature of the certificate is invalid.
=item B<8 X509_V_ERR_CRL_SIGNATURE_FAILURE: CRL signature failure>
the signature of the certificate is invalid.
=item B<9 X509_V_ERR_CERT_NOT_YET_VALID: certificate is not yet valid>
the certificate is not yet valid: the notBefore date is after the current time.
=item B<10 X509_V_ERR_CERT_HAS_EXPIRED: certificate has expired>
the certificate has expired: that is the notAfter date is before the current time.
=item B<11 X509_V_ERR_CRL_NOT_YET_VALID: CRL is not yet valid>
the CRL is not yet valid.
=item B<12 X509_V_ERR_CRL_HAS_EXPIRED: CRL has expired>
the CRL has expired.
=item B<13 X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD: format error in certificate's notBefore field>
the certificate notBefore field contains an invalid time.
=item B<14 X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD: format error in certificate's notAfter field>
the certificate notAfter field contains an invalid time.
=item B<15 X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD: format error in CRL's lastUpdate field>
the CRL lastUpdate field contains an invalid time.
=item B<16 X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD: format error in CRL's nextUpdate field>
the CRL nextUpdate field contains an invalid time.
=item B<17 X509_V_ERR_OUT_OF_MEM: out of memory>
an error occurred trying to allocate memory. This should never happen.
=item B<18 X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT: self signed certificate>
the passed certificate is self signed and the same certificate cannot be found in the list of
trusted certificates.
=item B<19 X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN: self signed certificate in certificate chain>
the certificate chain could be built up using the untrusted certificates but the root could not
be found locally.
=item B<20 X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY: unable to get local issuer certificate>
the issuer certificate could not be found: this occurs if the issuer
certificate of an untrusted certificate cannot be found.
=item B<21 X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE: unable to verify the first certificate>
no signatures could be verified because the chain contains only one certificate and it is not
self signed.
=item B<22 X509_V_ERR_CERT_CHAIN_TOO_LONG: certificate chain too long>
the certificate chain length is greater than the supplied maximum depth. Unused.
=item B<23 X509_V_ERR_CERT_REVOKED: certificate revoked>
the certificate has been revoked.
=item B<24 X509_V_ERR_INVALID_CA: invalid CA certificate>
a CA certificate is invalid. Either it is not a CA or its extensions are not consistent
with the supplied purpose.
=item B<25 X509_V_ERR_PATH_LENGTH_EXCEEDED: path length constraint exceeded>
the basicConstraints pathlength parameter has been exceeded.
=item B<26 X509_V_ERR_INVALID_PURPOSE: unsupported certificate purpose>
the supplied certificate cannot be used for the specified purpose.
=item B<27 X509_V_ERR_CERT_UNTRUSTED: certificate not trusted>
the root CA is not marked as trusted for the specified purpose.
=item B<28 X509_V_ERR_CERT_REJECTED: certificate rejected>
the root CA is marked to reject the specified purpose.
=item B<29 X509_V_ERR_SUBJECT_ISSUER_MISMATCH: subject issuer mismatch>
the current candidate issuer certificate was rejected because its subject name
did not match the issuer name of the current certificate. Only displayed when
the B<-issuer_checks> option is set.
=item B<30 X509_V_ERR_AKID_SKID_MISMATCH: authority and subject key identifier mismatch>
the current candidate issuer certificate was rejected because its subject key
identifier was present and did not match the authority key identifier current
certificate. Only displayed when the B<-issuer_checks> option is set.
=item B<31 X509_V_ERR_AKID_ISSUER_SERIAL_MISMATCH: authority and issuer serial number mismatch>
the current candidate issuer certificate was rejected because its issuer name
and serial number was present and did not match the authority key identifier
of the current certificate. Only displayed when the B<-issuer_checks> option is set.
=item B<32 X509_V_ERR_KEYUSAGE_NO_CERTSIGN:key usage does not include certificate signing>
the current candidate issuer certificate was rejected because its keyUsage extension
does not permit certificate signing.
=item B<50 X509_V_ERR_APPLICATION_VERIFICATION: application verification failure>
an application specific error. Unused.
=back
=head1 BUGS
Although the issuer checks are a considerable improvement over the old technique they still
suffer from limitations in the underlying X509_LOOKUP API. One consequence of this is that
trusted certificates with matching subject name must either appear in a file (as specified by the
B<-CAfile> option) or a directory (as specified by B<-CApath>. If they occur in both then only
the certificates in the file will be recognised.
Previous versions of OpenSSL assume certificates with matching subject name are identical and
mishandled them.
Previous versions of this documentation swapped the meaning of the
B<X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT> and
B<20 X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY> error codes.
=head1 SEE ALSO
L<x509(1)|x509(1)>
=head1 HISTORY
The -no_alt_chains options was first added to OpenSSL 1.0.2b.
=cut
diff --git a/doc/apps/x509.pod b/doc/apps/x509.pod
index d50625862ac3..408a5c6b8532 100644
--- a/doc/apps/x509.pod
+++ b/doc/apps/x509.pod
@@ -1,891 +1,883 @@
=pod
=head1 NAME
openssl-x509,
x509 - Certificate display and signing utility
=head1 SYNOPSIS
B<openssl> B<x509>
[B<-inform DER|PEM|NET>]
[B<-outform DER|PEM|NET>]
[B<-keyform DER|PEM>]
[B<-CAform DER|PEM>]
[B<-CAkeyform DER|PEM>]
[B<-in filename>]
[B<-out filename>]
[B<-serial>]
[B<-hash>]
[B<-subject_hash>]
[B<-issuer_hash>]
[B<-ocspid>]
[B<-subject>]
[B<-issuer>]
[B<-nameopt option>]
[B<-email>]
[B<-ocsp_uri>]
[B<-startdate>]
[B<-enddate>]
[B<-purpose>]
[B<-dates>]
[B<-checkend num>]
[B<-modulus>]
[B<-pubkey>]
[B<-fingerprint>]
[B<-alias>]
[B<-noout>]
[B<-trustout>]
[B<-clrtrust>]
[B<-clrreject>]
[B<-addtrust arg>]
[B<-addreject arg>]
[B<-setalias arg>]
[B<-days arg>]
[B<-set_serial n>]
[B<-signkey filename>]
[B<-passin arg>]
[B<-x509toreq>]
[B<-req>]
[B<-CA filename>]
[B<-CAkey filename>]
[B<-CAcreateserial>]
[B<-CAserial filename>]
[B<-force_pubkey key>]
[B<-text>]
[B<-certopt option>]
[B<-C>]
[B<-md2|-md5|-sha1|-mdc2>]
[B<-clrext>]
[B<-extfile filename>]
[B<-extensions section>]
[B<-engine id>]
=head1 DESCRIPTION
The B<x509> command is a multi purpose certificate utility. It can be
used to display certificate information, convert certificates to
various forms, sign certificate requests like a "mini CA" or edit
certificate trust settings.
Since there are a large number of options they will split up into
various sections.
=head1 OPTIONS
=head2 INPUT, OUTPUT AND GENERAL PURPOSE OPTIONS
=over 4
=item B<-inform DER|PEM|NET>
This specifies the input format normally the command will expect an X509
certificate but this can change if other options such as B<-req> are
present. The DER format is the DER encoding of the certificate and PEM
is the base64 encoding of the DER encoding with header and footer lines
added. The NET option is an obscure Netscape server format that is now
obsolete.
=item B<-outform DER|PEM|NET>
This specifies the output format, the options have the same meaning as the
B<-inform> option.
=item B<-in filename>
This specifies the input filename to read a certificate from or standard input
if this option is not specified.
=item B<-out filename>
This specifies the output filename to write to or standard output by
default.
=item B<-md2|-md5|-sha1|-mdc2>
the digest to use. This affects any signing or display option that uses a message
digest, such as the B<-fingerprint>, B<-signkey> and B<-CA> options. If not
specified then SHA1 is used. If the key being used to sign with is a DSA key
then this option has no effect: SHA1 is always used with DSA keys.
=item B<-engine id>
specifying an engine (by its unique B<id> string) will cause B<x509>
to attempt to obtain a functional reference to the specified engine,
thus initialising it if needed. The engine will then be set as the default
for all available algorithms.
=back
=head2 DISPLAY OPTIONS
Note: the B<-alias> and B<-purpose> options are also display options
but are described in the B<TRUST SETTINGS> section.
=over 4
=item B<-text>
prints out the certificate in text form. Full details are output including the
public key, signature algorithms, issuer and subject names, serial number
any extensions present and any trust settings.
=item B<-certopt option>
customise the output format used with B<-text>. The B<option> argument can be
a single option or multiple options separated by commas. The B<-certopt> switch
may be also be used more than once to set multiple options. See the B<TEXT OPTIONS>
section for more information.
=item B<-noout>
this option prevents output of the encoded version of the request.
=item B<-pubkey>
outputs the the certificate's SubjectPublicKeyInfo block in PEM format.
=item B<-modulus>
this option prints out the value of the modulus of the public key
contained in the certificate.
=item B<-serial>
outputs the certificate serial number.
=item B<-subject_hash>
outputs the "hash" of the certificate subject name. This is used in OpenSSL to
form an index to allow certificates in a directory to be looked up by subject
name.
=item B<-issuer_hash>
outputs the "hash" of the certificate issuer name.
=item B<-ocspid>
outputs the OCSP hash values for the subject name and public key.
=item B<-hash>
synonym for "-subject_hash" for backward compatibility reasons.
=item B<-subject_hash_old>
outputs the "hash" of the certificate subject name using the older algorithm
as used by OpenSSL versions before 1.0.0.
=item B<-issuer_hash_old>
outputs the "hash" of the certificate issuer name using the older algorithm
as used by OpenSSL versions before 1.0.0.
=item B<-subject>
outputs the subject name.
=item B<-issuer>
outputs the issuer name.
=item B<-nameopt option>
option which determines how the subject or issuer names are displayed. The
B<option> argument can be a single option or multiple options separated by
commas. Alternatively the B<-nameopt> switch may be used more than once to
set multiple options. See the B<NAME OPTIONS> section for more information.
=item B<-email>
outputs the email address(es) if any.
=item B<-ocsp_uri>
outputs the OCSP responder address(es) if any.
=item B<-startdate>
prints out the start date of the certificate, that is the notBefore date.
=item B<-enddate>
prints out the expiry date of the certificate, that is the notAfter date.
=item B<-dates>
prints out the start and expiry dates of a certificate.
=item B<-checkend arg>
checks if the certificate expires within the next B<arg> seconds and exits
non-zero if yes it will expire or zero if not.
=item B<-fingerprint>
-prints out the digest of the DER encoded version of the whole certificate
-(see digest options).
+Calculates and outputs the digest of the DER encoded version of the entire
+certificate (see digest options).
+This is commonly called a "fingerprint". Because of the nature of message
+digests, the fingerprint of a certificate is unique to that certificate and
+two certificates with the same fingerprint can be considered to be the same.
=item B<-C>
this outputs the certificate in the form of a C source file.
=back
=head2 TRUST SETTINGS
Please note these options are currently experimental and may well change.
A B<trusted certificate> is an ordinary certificate which has several
additional pieces of information attached to it such as the permitted
and prohibited uses of the certificate and an "alias".
Normally when a certificate is being verified at least one certificate
must be "trusted". By default a trusted certificate must be stored
locally and must be a root CA: any certificate chain ending in this CA
is then usable for any purpose.
Trust settings currently are only used with a root CA. They allow a finer
control over the purposes the root CA can be used for. For example a CA
may be trusted for SSL client but not SSL server use.
See the description of the B<verify> utility for more information on the
meaning of trust settings.
Future versions of OpenSSL will recognize trust settings on any
certificate: not just root CAs.
=over 4
=item B<-trustout>
this causes B<x509> to output a B<trusted> certificate. An ordinary
or trusted certificate can be input but by default an ordinary
certificate is output and any trust settings are discarded. With the
B<-trustout> option a trusted certificate is output. A trusted
certificate is automatically output if any trust settings are modified.
=item B<-setalias arg>
sets the alias of the certificate. This will allow the certificate
to be referred to using a nickname for example "Steve's Certificate".
=item B<-alias>
outputs the certificate alias, if any.
=item B<-clrtrust>
clears all the permitted or trusted uses of the certificate.
=item B<-clrreject>
clears all the prohibited or rejected uses of the certificate.
=item B<-addtrust arg>
adds a trusted certificate use. Any object name can be used here
but currently only B<clientAuth> (SSL client use), B<serverAuth>
(SSL server use) and B<emailProtection> (S/MIME email) are used.
Other OpenSSL applications may define additional uses.
=item B<-addreject arg>
adds a prohibited use. It accepts the same values as the B<-addtrust>
option.
=item B<-purpose>
this option performs tests on the certificate extensions and outputs
the results. For a more complete description see the B<CERTIFICATE
EXTENSIONS> section.
=back
=head2 SIGNING OPTIONS
The B<x509> utility can be used to sign certificates and requests: it
can thus behave like a "mini CA".
=over 4
=item B<-signkey filename>
this option causes the input file to be self signed using the supplied
private key.
If the input file is a certificate it sets the issuer name to the
subject name (i.e. makes it self signed) changes the public key to the
supplied value and changes the start and end dates. The start date is
set to the current time and the end date is set to a value determined
by the B<-days> option. Any certificate extensions are retained unless
the B<-clrext> option is supplied.
If the input is a certificate request then a self signed certificate
is created using the supplied private key using the subject name in
the request.
=item B<-passin arg>
the key password source. For more information about the format of B<arg>
see the B<PASS PHRASE ARGUMENTS> section in L<openssl(1)|openssl(1)>.
=item B<-clrext>
delete any extensions from a certificate. This option is used when a
certificate is being created from another certificate (for example with
the B<-signkey> or the B<-CA> options). Normally all extensions are
retained.
=item B<-keyform PEM|DER>
specifies the format (DER or PEM) of the private key file used in the
B<-signkey> option.
=item B<-days arg>
specifies the number of days to make a certificate valid for. The default
is 30 days.
=item B<-x509toreq>
converts a certificate into a certificate request. The B<-signkey> option
is used to pass the required private key.
=item B<-req>
by default a certificate is expected on input. With this option a
certificate request is expected instead.
=item B<-set_serial n>
specifies the serial number to use. This option can be used with either
the B<-signkey> or B<-CA> options. If used in conjunction with the B<-CA>
option the serial number file (as specified by the B<-CAserial> or
B<-CAcreateserial> options) is not used.
The serial number can be decimal or hex (if preceded by B<0x>). Negative
serial numbers can also be specified but their use is not recommended.
=item B<-CA filename>
specifies the CA certificate to be used for signing. When this option is
present B<x509> behaves like a "mini CA". The input file is signed by this
CA using this option: that is its issuer name is set to the subject name
of the CA and it is digitally signed using the CAs private key.
This option is normally combined with the B<-req> option. Without the
B<-req> option the input is a certificate which must be self signed.
=item B<-CAkey filename>
sets the CA private key to sign a certificate with. If this option is
not specified then it is assumed that the CA private key is present in
the CA certificate file.
=item B<-CAserial filename>
sets the CA serial number file to use.
When the B<-CA> option is used to sign a certificate it uses a serial
number specified in a file. This file consist of one line containing
an even number of hex digits with the serial number to use. After each
use the serial number is incremented and written out to the file again.
The default filename consists of the CA certificate file base name with
".srl" appended. For example if the CA certificate file is called
"mycacert.pem" it expects to find a serial number file called "mycacert.srl".
=item B<-CAcreateserial>
with this option the CA serial number file is created if it does not exist:
it will contain the serial number "02" and the certificate being signed will
have the 1 as its serial number. Normally if the B<-CA> option is specified
and the serial number file does not exist it is an error.
=item B<-extfile filename>
file containing certificate extensions to use. If not specified then
no extensions are added to the certificate.
=item B<-extensions section>
the section to add certificate extensions from. If this option is not
specified then the extensions should either be contained in the unnamed
(default) section or the default section should contain a variable called
"extensions" which contains the section to use. See the
L<x509v3_config(5)|x509v3_config(5)> manual page for details of the
extension section format.
=item B<-force_pubkey key>
when a certificate is created set its public key to B<key> instead of the
key in the certificate or certificate request. This option is useful for
creating certificates where the algorithm can't normally sign requests, for
example DH.
The format or B<key> can be specified using the B<-keyform> option.
=back
=head2 NAME OPTIONS
The B<nameopt> command line switch determines how the subject and issuer
names are displayed. If no B<nameopt> switch is present the default "oneline"
format is used which is compatible with previous versions of OpenSSL.
Each option is described in detail below, all options can be preceded by
a B<-> to turn the option off. Only the first four will normally be used.
=over 4
=item B<compat>
use the old format. This is equivalent to specifying no name options at all.
=item B<RFC2253>
displays names compatible with RFC2253 equivalent to B<esc_2253>, B<esc_ctrl>,
B<esc_msb>, B<utf8>, B<dump_nostr>, B<dump_unknown>, B<dump_der>,
B<sep_comma_plus>, B<dn_rev> and B<sname>.
=item B<oneline>
a oneline format which is more readable than RFC2253. It is equivalent to
specifying the B<esc_2253>, B<esc_ctrl>, B<esc_msb>, B<utf8>, B<dump_nostr>,
B<dump_der>, B<use_quote>, B<sep_comma_plus_space>, B<space_eq> and B<sname>
options.
=item B<multiline>
a multiline format. It is equivalent B<esc_ctrl>, B<esc_msb>, B<sep_multiline>,
B<space_eq>, B<lname> and B<align>.
=item B<esc_2253>
escape the "special" characters required by RFC2253 in a field That is
B<,+"E<lt>E<gt>;>. Additionally B<#> is escaped at the beginning of a string
and a space character at the beginning or end of a string.
=item B<esc_ctrl>
escape control characters. That is those with ASCII values less than
0x20 (space) and the delete (0x7f) character. They are escaped using the
RFC2253 \XX notation (where XX are two hex digits representing the
character value).
=item B<esc_msb>
escape characters with the MSB set, that is with ASCII values larger than
127.
=item B<use_quote>
escapes some characters by surrounding the whole string with B<"> characters,
without the option all escaping is done with the B<\> character.
=item B<utf8>
convert all strings to UTF8 format first. This is required by RFC2253. If
you are lucky enough to have a UTF8 compatible terminal then the use
of this option (and B<not> setting B<esc_msb>) may result in the correct
display of multibyte (international) characters. Is this option is not
present then multibyte characters larger than 0xff will be represented
using the format \UXXXX for 16 bits and \WXXXXXXXX for 32 bits.
Also if this option is off any UTF8Strings will be converted to their
character form first.
=item B<ignore_type>
this option does not attempt to interpret multibyte characters in any
way. That is their content octets are merely dumped as though one octet
represents each character. This is useful for diagnostic purposes but
will result in rather odd looking output.
=item B<show_type>
show the type of the ASN1 character string. The type precedes the
field contents. For example "BMPSTRING: Hello World".
=item B<dump_der>
when this option is set any fields that need to be hexdumped will
be dumped using the DER encoding of the field. Otherwise just the
content octets will be displayed. Both options use the RFC2253
B<#XXXX...> format.
=item B<dump_nostr>
dump non character string types (for example OCTET STRING) if this
option is not set then non character string types will be displayed
as though each content octet represents a single character.
=item B<dump_all>
dump all fields. This option when used with B<dump_der> allows the
DER encoding of the structure to be unambiguously determined.
=item B<dump_unknown>
dump any field whose OID is not recognised by OpenSSL.
=item B<sep_comma_plus>, B<sep_comma_plus_space>, B<sep_semi_plus_space>,
B<sep_multiline>
these options determine the field separators. The first character is
between RDNs and the second between multiple AVAs (multiple AVAs are
very rare and their use is discouraged). The options ending in
"space" additionally place a space after the separator to make it
more readable. The B<sep_multiline> uses a linefeed character for
the RDN separator and a spaced B<+> for the AVA separator. It also
indents the fields by four characters. If no field separator is specified
then B<sep_comma_plus_space> is used by default.
=item B<dn_rev>
reverse the fields of the DN. This is required by RFC2253. As a side
effect this also reverses the order of multiple AVAs but this is
permissible.
=item B<nofname>, B<sname>, B<lname>, B<oid>
these options alter how the field name is displayed. B<nofname> does
not display the field at all. B<sname> uses the "short name" form
(CN for commonName for example). B<lname> uses the long form.
B<oid> represents the OID in numerical form and is useful for
diagnostic purpose.
=item B<align>
align field values for a more readable output. Only usable with
B<sep_multiline>.
=item B<space_eq>
places spaces round the B<=> character which follows the field
name.
=back
=head2 TEXT OPTIONS
As well as customising the name output format, it is also possible to
customise the actual fields printed using the B<certopt> options when
the B<text> option is present. The default behaviour is to print all fields.
=over 4
=item B<compatible>
use the old format. This is equivalent to specifying no output options at all.
=item B<no_header>
don't print header information: that is the lines saying "Certificate" and "Data".
=item B<no_version>
don't print out the version number.
=item B<no_serial>
don't print out the serial number.
=item B<no_signame>
don't print out the signature algorithm used.
=item B<no_validity>
don't print the validity, that is the B<notBefore> and B<notAfter> fields.
=item B<no_subject>
don't print out the subject name.
=item B<no_issuer>
don't print out the issuer name.
=item B<no_pubkey>
don't print out the public key.
=item B<no_sigdump>
don't give a hexadecimal dump of the certificate signature.
=item B<no_aux>
don't print out certificate trust information.
=item B<no_extensions>
don't print out any X509V3 extensions.
=item B<ext_default>
retain default extension behaviour: attempt to print out unsupported certificate extensions.
=item B<ext_error>
print an error message for unsupported certificate extensions.
=item B<ext_parse>
ASN1 parse unsupported extensions.
=item B<ext_dump>
hex dump unsupported extensions.
=item B<ca_default>
the value used by the B<ca> utility, equivalent to B<no_issuer>, B<no_pubkey>,
B<no_header>, and B<no_version>.
=back
=head1 EXAMPLES
Note: in these examples the '\' means the example should be all on one
line.
Display the contents of a certificate:
openssl x509 -in cert.pem -noout -text
Display the certificate serial number:
openssl x509 -in cert.pem -noout -serial
Display the certificate subject name:
openssl x509 -in cert.pem -noout -subject
Display the certificate subject name in RFC2253 form:
openssl x509 -in cert.pem -noout -subject -nameopt RFC2253
Display the certificate subject name in oneline form on a terminal
supporting UTF8:
openssl x509 -in cert.pem -noout -subject -nameopt oneline,-esc_msb
-Display the certificate MD5 fingerprint:
-
- openssl x509 -in cert.pem -noout -fingerprint
-
Display the certificate SHA1 fingerprint:
openssl x509 -sha1 -in cert.pem -noout -fingerprint
Convert a certificate from PEM to DER format:
openssl x509 -in cert.pem -inform PEM -out cert.der -outform DER
Convert a certificate to a certificate request:
openssl x509 -x509toreq -in cert.pem -out req.pem -signkey key.pem
Convert a certificate request into a self signed certificate using
extensions for a CA:
openssl x509 -req -in careq.pem -extfile openssl.cnf -extensions v3_ca \
-signkey key.pem -out cacert.pem
Sign a certificate request using the CA certificate above and add user
certificate extensions:
openssl x509 -req -in req.pem -extfile openssl.cnf -extensions v3_usr \
-CA cacert.pem -CAkey key.pem -CAcreateserial
Set a certificate to be trusted for SSL client use and change set its alias to
"Steve's Class 1 CA"
openssl x509 -in cert.pem -addtrust clientAuth \
-setalias "Steve's Class 1 CA" -out trust.pem
=head1 NOTES
The PEM format uses the header and footer lines:
-----BEGIN CERTIFICATE-----
-----END CERTIFICATE-----
it will also handle files containing:
-----BEGIN X509 CERTIFICATE-----
-----END X509 CERTIFICATE-----
Trusted certificates have the lines
-----BEGIN TRUSTED CERTIFICATE-----
-----END TRUSTED CERTIFICATE-----
The conversion to UTF8 format used with the name options assumes that
T61Strings use the ISO8859-1 character set. This is wrong but Netscape
and MSIE do this as do many certificates. So although this is incorrect
it is more likely to display the majority of certificates correctly.
-The B<-fingerprint> option takes the digest of the DER encoded certificate.
-This is commonly called a "fingerprint". Because of the nature of message
-digests the fingerprint of a certificate is unique to that certificate and
-two certificates with the same fingerprint can be considered to be the same.
-
-The Netscape fingerprint uses MD5 whereas MSIE uses SHA1.
-
The B<-email> option searches the subject name and the subject alternative
name extension. Only unique email addresses will be printed out: it will
not print the same address more than once.
=head1 CERTIFICATE EXTENSIONS
The B<-purpose> option checks the certificate extensions and determines
what the certificate can be used for. The actual checks done are rather
complex and include various hacks and workarounds to handle broken
certificates and software.
The same code is used when verifying untrusted certificates in chains
so this section is useful if a chain is rejected by the verify code.
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 then the certificate is
considered to be a "possible CA" other extensions are checked according
to the intended use of the certificate. A warning is given in this case
because the certificate should really not be regarded as a CA: however
it is allowed to be a CA to work around some broken software.
If the certificate is a V1 certificate (and thus has no extensions) and
it is self signed it is also assumed to be a CA but a warning is again
given: this is to work around the problem of Verisign roots which are V1
self signed certificates.
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.
The extended key usage 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 test is given below. The comments about
basicConstraints and keyUsage and V1 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. keyUsage must be absent or it must have the
digitalSignature bit set. 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. 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. keyUsage must be absent or it
must have the digitalSignature, the keyEncipherment set or both bits set.
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. 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. Netscape certificate type must be absent or should have the
S/MIME bit set. If the S/MIME bit is not set in 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 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. 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
Extensions in certificates are not transferred to certificate requests and
vice versa.
It is possible to produce invalid certificates or requests by specifying the
wrong private key or using inconsistent options in some cases: these should
be checked.
There should be options to explicitly set such things as start and end
dates rather than an offset from the current time.
The code to implement the verify behaviour described in the B<TRUST SETTINGS>
is currently being developed. It thus describes the intended behaviour rather
than the current behaviour. It is hoped that it will represent reality in
OpenSSL 0.9.5 and later.
=head1 SEE ALSO
L<req(1)|req(1)>, L<ca(1)|ca(1)>, L<genrsa(1)|genrsa(1)>,
L<gendsa(1)|gendsa(1)>, L<verify(1)|verify(1)>,
L<x509v3_config(5)|x509v3_config(5)>
=head1 HISTORY
Before OpenSSL 0.9.8, the default digest for RSA keys was MD5.
The hash algorithm used in the B<-subject_hash> and B<-issuer_hash> options
before OpenSSL 1.0.0 was based on the deprecated MD5 algorithm and the encoding
of the distinguished name. In OpenSSL 1.0.0 and later it is based on a
canonical version of the DN using SHA1. This means that any directories using
the old form must have their links rebuilt using B<c_rehash> or similar.
=cut
diff --git a/doc/crypto/ASN1_STRING_length.pod b/doc/crypto/ASN1_STRING_length.pod
index f651e4f2aee0..4ea6e8c226c0 100644
--- a/doc/crypto/ASN1_STRING_length.pod
+++ b/doc/crypto/ASN1_STRING_length.pod
@@ -1,83 +1,83 @@
=pod
=head1 NAME
ASN1_STRING_dup, ASN1_STRING_cmp, ASN1_STRING_set, ASN1_STRING_length,
ASN1_STRING_length_set, ASN1_STRING_type, ASN1_STRING_data, ASN1_STRING_to_UTF8 -
ASN1_STRING utility functions
=head1 SYNOPSIS
#include <openssl/asn1.h>
int ASN1_STRING_length(ASN1_STRING *x);
unsigned char * ASN1_STRING_data(ASN1_STRING *x);
ASN1_STRING * ASN1_STRING_dup(ASN1_STRING *a);
int ASN1_STRING_cmp(ASN1_STRING *a, ASN1_STRING *b);
int ASN1_STRING_set(ASN1_STRING *str, const void *data, int len);
int ASN1_STRING_type(ASN1_STRING *x);
int ASN1_STRING_to_UTF8(unsigned char **out, ASN1_STRING *in);
=head1 DESCRIPTION
These functions allow an B<ASN1_STRING> structure to be manipulated.
ASN1_STRING_length() returns the length of the content of B<x>.
ASN1_STRING_data() returns an internal pointer to the data of B<x>.
Since this is an internal pointer it should B<not> be freed or
modified in any way.
ASN1_STRING_dup() returns a copy of the structure B<a>.
ASN1_STRING_cmp() compares B<a> and B<b> returning 0 if the two
are identical. The string types and content are compared.
ASN1_STRING_set() sets the data of string B<str> to the buffer
B<data> or length B<len>. The supplied data is copied. If B<len>
is -1 then the length is determined by strlen(data).
ASN1_STRING_type() returns the type of B<x>, using standard constants
such as B<V_ASN1_OCTET_STRING>.
ASN1_STRING_to_UTF8() converts the string B<in> to UTF8 format, the
converted data is allocated in a buffer in B<*out>. The length of
B<out> is returned or a negative error code. The buffer B<*out>
should be free using OPENSSL_free().
=head1 NOTES
Almost all ASN1 types in OpenSSL are represented as an B<ASN1_STRING>
structure. Other types such as B<ASN1_OCTET_STRING> are simply typedefed
to B<ASN1_STRING> and the functions call the B<ASN1_STRING> equivalents.
B<ASN1_STRING> is also used for some B<CHOICE> types which consist
entirely of primitive string types such as B<DirectoryString> and
B<Time>.
These functions should B<not> be used to examine or modify B<ASN1_INTEGER>
or B<ASN1_ENUMERATED> types: the relevant B<INTEGER> or B<ENUMERATED>
utility functions should be used instead.
In general it cannot be assumed that the data returned by ASN1_STRING_data()
is null terminated or does not contain embedded nulls. The actual format
of the data will depend on the actual string type itself: for example
-for and IA5String the data will be ASCII, for a BMPString two bytes per
-character in big endian format, UTF8String will be in UTF8 format.
+for an IA5String the data will be ASCII, for a BMPString two bytes per
+character in big endian format, and for an UTF8String it will be in UTF8 format.
Similar care should be take to ensure the data is in the correct format
when calling ASN1_STRING_set().
=head1 RETURN VALUES
=head1 SEE ALSO
L<ERR_get_error(3)|ERR_get_error(3)>
=head1 HISTORY
=cut
diff --git a/doc/crypto/BIO_s_mem.pod b/doc/crypto/BIO_s_mem.pod
index 9f239648d752..7663d8bf5ffd 100644
--- a/doc/crypto/BIO_s_mem.pod
+++ b/doc/crypto/BIO_s_mem.pod
@@ -1,115 +1,115 @@
=pod
=head1 NAME
BIO_s_mem, BIO_set_mem_eof_return, BIO_get_mem_data, BIO_set_mem_buf,
BIO_get_mem_ptr, BIO_new_mem_buf - memory BIO
=head1 SYNOPSIS
#include <openssl/bio.h>
BIO_METHOD * BIO_s_mem(void);
BIO_set_mem_eof_return(BIO *b,int v)
long BIO_get_mem_data(BIO *b, char **pp)
BIO_set_mem_buf(BIO *b,BUF_MEM *bm,int c)
BIO_get_mem_ptr(BIO *b,BUF_MEM **pp)
BIO *BIO_new_mem_buf(const void *buf, int len);
=head1 DESCRIPTION
BIO_s_mem() return the memory BIO method function.
A memory BIO is a source/sink BIO which uses memory for its I/O. Data
written to a memory BIO is stored in a BUF_MEM structure which is extended
as appropriate to accommodate the stored data.
Any data written to a memory BIO can be recalled by reading from it.
Unless the memory BIO is read only any data read from it is deleted from
the BIO.
Memory BIOs support BIO_gets() and BIO_puts().
If the BIO_CLOSE flag is set when a memory BIO is freed then the underlying
BUF_MEM structure is also freed.
Calling BIO_reset() on a read write memory BIO clears any data in it. On a
read only BIO it restores the BIO to its original state and the read only
data can be read again.
BIO_eof() is true if no data is in the BIO.
BIO_ctrl_pending() returns the number of bytes currently stored.
BIO_set_mem_eof_return() sets the behaviour of memory BIO B<b> when it is
empty. If the B<v> is zero then an empty memory BIO will return EOF (that is
it will return zero and BIO_should_retry(b) will be false. If B<v> is non
zero then it will return B<v> when it is empty and it will set the read retry
flag (that is BIO_read_retry(b) is true). To avoid ambiguity with a normal
positive return value B<v> should be set to a negative value, typically -1.
-BIO_get_mem_data() sets B<pp> to a pointer to the start of the memory BIOs data
+BIO_get_mem_data() sets *B<pp> to a pointer to the start of the memory BIOs data
and returns the total amount of data available. It is implemented as a macro.
BIO_set_mem_buf() sets the internal BUF_MEM structure to B<bm> and sets the
close flag to B<c>, that is B<c> should be either BIO_CLOSE or BIO_NOCLOSE.
It is a macro.
-BIO_get_mem_ptr() places the underlying BUF_MEM structure in B<pp>. It is
+BIO_get_mem_ptr() places the underlying BUF_MEM structure in *B<pp>. It is
a macro.
BIO_new_mem_buf() creates a memory BIO using B<len> bytes of data at B<buf>,
if B<len> is -1 then the B<buf> is assumed to be nul terminated and its
length is determined by B<strlen>. The BIO is set to a read only state and
as a result cannot be written to. This is useful when some data needs to be
made available from a static area of memory in the form of a BIO. The
supplied data is read directly from the supplied buffer: it is B<not> copied
first, so the supplied area of memory must be unchanged until the BIO is freed.
=head1 NOTES
Writes to memory BIOs will always succeed if memory is available: that is
their size can grow indefinitely.
Every read from a read write memory BIO will remove the data just read with
an internal copy operation, if a BIO contains a lot of data and it is
read in small chunks the operation can be very slow. The use of a read only
memory BIO avoids this problem. If the BIO must be read write then adding
a buffering BIO to the chain will speed up the process.
=head1 BUGS
There should be an option to set the maximum size of a memory BIO.
There should be a way to "rewind" a read write BIO without destroying
its contents.
The copying operation should not occur after every small read of a large BIO
to improve efficiency.
=head1 EXAMPLE
Create a memory BIO and write some data to it:
BIO *mem = BIO_new(BIO_s_mem());
BIO_puts(mem, "Hello World\n");
Create a read only memory BIO:
char data[] = "Hello World";
BIO *mem;
mem = BIO_new_mem_buf(data, -1);
Extract the BUF_MEM structure from a memory BIO and then free up the BIO:
BUF_MEM *bptr;
BIO_get_mem_ptr(mem, &bptr);
BIO_set_close(mem, BIO_NOCLOSE); /* So BIO_free() leaves BUF_MEM alone */
BIO_free(mem);
=head1 SEE ALSO
TBA
diff --git a/doc/crypto/BN_zero.pod b/doc/crypto/BN_zero.pod
index b555ec398859..8aa9c142b725 100644
--- a/doc/crypto/BN_zero.pod
+++ b/doc/crypto/BN_zero.pod
@@ -1,59 +1,62 @@
=pod
=head1 NAME
BN_zero, BN_one, BN_value_one, BN_set_word, BN_get_word - BIGNUM assignment
operations
=head1 SYNOPSIS
#include <openssl/bn.h>
int BN_zero(BIGNUM *a);
int BN_one(BIGNUM *a);
const BIGNUM *BN_value_one(void);
- int BN_set_word(BIGNUM *a, unsigned long w);
- unsigned long BN_get_word(BIGNUM *a);
+ int BN_set_word(BIGNUM *a, BN_ULONG w);
+ BN_ULONG BN_get_word(BIGNUM *a);
=head1 DESCRIPTION
+B<BN_ULONG> is a macro that will be an unsigned integral type optimied
+for the most efficient implementation on the local platform.
+
BN_zero(), BN_one() and BN_set_word() set B<a> to the values 0, 1 and
B<w> respectively. BN_zero() and BN_one() are macros.
BN_value_one() returns a B<BIGNUM> constant of value 1. This constant
is useful for use in comparisons and assignment.
-BN_get_word() returns B<a>, if it can be represented as an unsigned
-long.
+BN_get_word() returns B<a>, if it can be represented as a B<BN_ULONG>.
=head1 RETURN VALUES
-BN_get_word() returns the value B<a>, and 0xffffffffL if B<a> cannot
-be represented as an unsigned long.
+BN_get_word() returns the value B<a>, or all-bits-set if B<a> cannot
+be represented as a B<BN_ULONG>.
BN_zero(), BN_one() and BN_set_word() return 1 on success, 0 otherwise.
BN_value_one() returns the constant.
=head1 BUGS
-Someone might change the constant.
+If a B<BIGNUM> is equal to the value of all-bits-set, it will collide
+with the error condition returned by BN_get_word() which uses that
+as an error value.
-If a B<BIGNUM> is equal to 0xffffffffL it can be represented as an
-unsigned long but this value is also returned on error.
+B<BN_ULONG> should probably be a typedef.
=head1 SEE ALSO
L<bn(3)|bn(3)>, L<BN_bn2bin(3)|BN_bn2bin(3)>
=head1 HISTORY
BN_zero(), BN_one() and BN_set_word() are available in all versions of
SSLeay and OpenSSL. BN_value_one() and BN_get_word() were added in
SSLeay 0.8.
BN_value_one() was changed to return a true const BIGNUM * in OpenSSL
0.9.7.
=cut
diff --git a/doc/crypto/EVP_EncryptInit.pod b/doc/crypto/EVP_EncryptInit.pod
index 4cd24d7e0169..4973f0a23ba3 100644
--- a/doc/crypto/EVP_EncryptInit.pod
+++ b/doc/crypto/EVP_EncryptInit.pod
@@ -1,594 +1,594 @@
=pod
=head1 NAME
EVP_CIPHER_CTX_init, EVP_EncryptInit_ex, EVP_EncryptUpdate,
EVP_EncryptFinal_ex, EVP_DecryptInit_ex, EVP_DecryptUpdate,
EVP_DecryptFinal_ex, EVP_CipherInit_ex, EVP_CipherUpdate,
EVP_CipherFinal_ex, EVP_CIPHER_CTX_set_key_length,
EVP_CIPHER_CTX_ctrl, EVP_CIPHER_CTX_cleanup, EVP_EncryptInit,
EVP_EncryptFinal, EVP_DecryptInit, EVP_DecryptFinal,
EVP_CipherInit, EVP_CipherFinal, EVP_get_cipherbyname,
EVP_get_cipherbynid, EVP_get_cipherbyobj, EVP_CIPHER_nid,
EVP_CIPHER_block_size, EVP_CIPHER_key_length, EVP_CIPHER_iv_length,
EVP_CIPHER_flags, EVP_CIPHER_mode, EVP_CIPHER_type, EVP_CIPHER_CTX_cipher,
EVP_CIPHER_CTX_nid, EVP_CIPHER_CTX_block_size, EVP_CIPHER_CTX_key_length,
EVP_CIPHER_CTX_iv_length, EVP_CIPHER_CTX_get_app_data,
EVP_CIPHER_CTX_set_app_data, EVP_CIPHER_CTX_type, EVP_CIPHER_CTX_flags,
EVP_CIPHER_CTX_mode, EVP_CIPHER_param_to_asn1, EVP_CIPHER_asn1_to_param,
EVP_CIPHER_CTX_set_padding, EVP_enc_null, EVP_des_cbc, EVP_des_ecb,
EVP_des_cfb, EVP_des_ofb, EVP_des_ede_cbc, EVP_des_ede, EVP_des_ede_ofb,
EVP_des_ede_cfb, EVP_des_ede3_cbc, EVP_des_ede3, EVP_des_ede3_ofb,
EVP_des_ede3_cfb, EVP_desx_cbc, EVP_rc4, EVP_rc4_40, EVP_rc4_hmac_md5,
EVP_idea_cbc, EVP_idea_ecb, EVP_idea_cfb, EVP_idea_ofb, EVP_rc2_cbc,
EVP_rc2_ecb, EVP_rc2_cfb, EVP_rc2_ofb, EVP_rc2_40_cbc, EVP_rc2_64_cbc,
EVP_bf_cbc, EVP_bf_ecb, EVP_bf_cfb, EVP_bf_ofb, EVP_cast5_cbc,
EVP_cast5_ecb, EVP_cast5_cfb, EVP_cast5_ofb, EVP_rc5_32_12_16_cbc,
EVP_rc5_32_12_16_ecb, EVP_rc5_32_12_16_cfb, EVP_rc5_32_12_16_ofb,
EVP_aes_128_gcm, EVP_aes_192_gcm, EVP_aes_256_gcm, EVP_aes_128_ccm,
EVP_aes_192_ccm, EVP_aes_256_ccm,
EVP_aes_128_cbc_hmac_sha1, EVP_aes_256_cbc_hmac_sha1,
EVP_aes_128_cbc_hmac_sha256, EVP_aes_256_cbc_hmac_sha256
- EVP cipher routines
=head1 SYNOPSIS
#include <openssl/evp.h>
void EVP_CIPHER_CTX_init(EVP_CIPHER_CTX *a);
int EVP_EncryptInit_ex(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *type,
- ENGINE *impl, unsigned char *key, unsigned char *iv);
+ ENGINE *impl, const unsigned char *key, const unsigned char *iv);
int EVP_EncryptUpdate(EVP_CIPHER_CTX *ctx, unsigned char *out,
int *outl, const unsigned char *in, int inl);
int EVP_EncryptFinal_ex(EVP_CIPHER_CTX *ctx, unsigned char *out,
int *outl);
int EVP_DecryptInit_ex(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *type,
- ENGINE *impl, unsigned char *key, unsigned char *iv);
+ ENGINE *impl, const unsigned char *key, const unsigned char *iv);
int EVP_DecryptUpdate(EVP_CIPHER_CTX *ctx, unsigned char *out,
int *outl, const unsigned char *in, int inl);
int EVP_DecryptFinal_ex(EVP_CIPHER_CTX *ctx, unsigned char *outm,
int *outl);
int EVP_CipherInit_ex(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *type,
- ENGINE *impl, unsigned char *key, unsigned char *iv, int enc);
+ ENGINE *impl, const unsigned char *key, const unsigned char *iv, int enc);
int EVP_CipherUpdate(EVP_CIPHER_CTX *ctx, unsigned char *out,
- int *outl, unsigned char *in, int inl);
+ 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,
- unsigned char *key, unsigned char *iv);
+ 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,
- unsigned char *key, unsigned char *iv);
+ 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,
- unsigned char *key, unsigned char *iv, int enc);
+ 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_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 type, int arg, void *ptr);
int EVP_CIPHER_CTX_cleanup(EVP_CIPHER_CTX *a);
const EVP_CIPHER *EVP_get_cipherbyname(const char *name);
#define EVP_get_cipherbynid(a) EVP_get_cipherbyname(OBJ_nid2sn(a))
#define EVP_get_cipherbyobj(a) EVP_get_cipherbynid(OBJ_obj2nid(a))
#define EVP_CIPHER_nid(e) ((e)->nid)
#define EVP_CIPHER_block_size(e) ((e)->block_size)
#define EVP_CIPHER_key_length(e) ((e)->key_len)
#define EVP_CIPHER_iv_length(e) ((e)->iv_len)
#define EVP_CIPHER_flags(e) ((e)->flags)
#define EVP_CIPHER_mode(e) ((e)->flags) & EVP_CIPH_MODE)
int EVP_CIPHER_type(const EVP_CIPHER *ctx);
#define EVP_CIPHER_CTX_cipher(e) ((e)->cipher)
#define EVP_CIPHER_CTX_nid(e) ((e)->cipher->nid)
#define EVP_CIPHER_CTX_block_size(e) ((e)->cipher->block_size)
#define EVP_CIPHER_CTX_key_length(e) ((e)->key_len)
#define EVP_CIPHER_CTX_iv_length(e) ((e)->cipher->iv_len)
#define EVP_CIPHER_CTX_get_app_data(e) ((e)->app_data)
#define EVP_CIPHER_CTX_set_app_data(e,d) ((e)->app_data=(char *)(d))
#define EVP_CIPHER_CTX_type(c) EVP_CIPHER_type(EVP_CIPHER_CTX_cipher(c))
#define EVP_CIPHER_CTX_flags(e) ((e)->cipher->flags)
#define EVP_CIPHER_CTX_mode(e) ((e)->cipher->flags & EVP_CIPH_MODE)
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);
=head1 DESCRIPTION
The EVP cipher routines are a high level interface to certain
symmetric ciphers.
EVP_CIPHER_CTX_init() initializes cipher contex B<ctx>.
EVP_EncryptInit_ex() sets up cipher context B<ctx> for encryption
with cipher B<type> from ENGINE B<impl>. B<ctx> must be initialized
before calling this function. B<type> is normally supplied
by a function such as EVP_aes_256_cbc(). If B<impl> is NULL then the
default implementation is used. B<key> is the symmetric key to use
and B<iv> is the IV to use (if necessary), the actual number of bytes
used for the key and IV depends on the cipher. It is possible to set
all parameters to NULL except B<type> in an initial call and supply
the remaining parameters in subsequent calls, all of which have B<type>
set to NULL. This is done when the default cipher parameters are not
appropriate.
EVP_EncryptUpdate() encrypts B<inl> bytes from the buffer B<in> and
writes the encrypted version to B<out>. 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:
as a result the amount of data written may be anything from zero bytes
to (inl + cipher_block_size - 1) so B<out> should contain sufficient
room. The actual number of bytes written is placed in B<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 L<standard block padding|/NOTES> (aka PKCS padding). The encrypted
final data is written to B<out> which should have sufficient space for
one cipher block. The number of bytes written is placed in B<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.
EVP_DecryptInit_ex(), EVP_DecryptUpdate() and EVP_DecryptFinal_ex() 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 B<out>
passed to EVP_DecryptUpdate() should have sufficient room for
(B<inl> + cipher_block_size) bytes unless the cipher block size is 1 in
which case B<inl> bytes is sufficient.
EVP_CipherInit_ex(), EVP_CipherUpdate() and EVP_CipherFinal_ex() are
functions that can be used for decryption or encryption. The operation
performed depends on the value of the B<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).
EVP_CIPHER_CTX_cleanup() clears all information from a cipher context
and free up any allocated memory associate with it. It should be called
after all operations using a cipher are complete so sensitive information
does not remain in memory.
EVP_EncryptInit(), EVP_DecryptInit() and EVP_CipherInit() behave in a
similar way to EVP_EncryptInit_ex(), EVP_DecryptInit_ex and
EVP_CipherInit_ex() except the B<ctx> parameter does not need to be
initialized and they always use the default cipher implementation.
EVP_EncryptFinal(), EVP_DecryptFinal() and EVP_CipherFinal() are
identical to EVP_EncryptFinal_ex(), EVP_DecryptFinal_ex() and
EVP_CipherFinal_ex(). In previous releases they also cleaned up
the B<ctx>, but this is no longer done and EVP_CIPHER_CTX_clean()
must be called to free any context resources.
EVP_get_cipherbyname(), EVP_get_cipherbynid() and EVP_get_cipherbyobj()
return an EVP_CIPHER structure when passed a cipher name, a NID or an
ASN1_OBJECT structure.
EVP_CIPHER_nid() and EVP_CIPHER_CTX_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.
EVP_CIPHER_CTX_set_padding() enables or disables padding. By default
encryption operations are padded using standard block padding and the
padding is checked and removed when decrypting. If the B<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.
EVP_CIPHER_key_length() and EVP_CIPHER_CTX_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_key_length() is fixed for a
given cipher, the value of EVP_CIPHER_CTX_key_length() may be different
for variable key length ciphers.
EVP_CIPHER_CTX_set_key_length() sets the key length of the cipher ctx.
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.
EVP_CIPHER_iv_length() and EVP_CIPHER_CTX_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.
EVP_CIPHER_block_size() and EVP_CIPHER_CTX_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_IV_LENGTH> is also the maximum block
length for all ciphers.
EVP_CIPHER_type() and EVP_CIPHER_CTX_type() return the type of the passed
cipher or context. This "type" is the actual NID of the cipher OBJECT
IDENTIFIER as such it ignores the cipher parameters and 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>.
EVP_CIPHER_CTX_cipher() returns the B<EVP_CIPHER> structure when passed
an B<EVP_CIPHER_CTX> structure.
EVP_CIPHER_mode() and EVP_CIPHER_CTX_mode() return the block cipher mode:
EVP_CIPH_ECB_MODE, EVP_CIPH_CBC_MODE, EVP_CIPH_CFB_MODE or
EVP_CIPH_OFB_MODE. If the cipher is a stream cipher then
EVP_CIPH_STREAM_CIPHER is returned.
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.
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 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.
EVP_CIPHER_CTX_ctrl() allows various cipher specific parameters to be determined
and set.
=head1 RETURN VALUES
EVP_EncryptInit_ex(), EVP_EncryptUpdate() and EVP_EncryptFinal_ex()
return 1 for success and 0 for failure.
EVP_DecryptInit_ex() 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_ex() 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_CTX_cleanup() 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_nid() and EVP_CIPHER_CTX_nid() return a NID.
EVP_CIPHER_block_size() and EVP_CIPHER_CTX_block_size() return the block
size.
EVP_CIPHER_key_length() and EVP_CIPHER_CTX_key_length() return the key
length.
EVP_CIPHER_CTX_set_padding() always returns 1.
EVP_CIPHER_iv_length() and EVP_CIPHER_CTX_iv_length() return the IV
length or zero if the cipher does not use an IV.
EVP_CIPHER_type() and EVP_CIPHER_CTX_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_param_to_asn1() and EVP_CIPHER_asn1_to_param() return 1 for
success or zero for failure.
=head1 CIPHER LISTING
All algorithms have a fixed key length unless otherwise stated.
=over 4
=item EVP_enc_null()
Null cipher: does nothing.
=item EVP_des_cbc(void), EVP_des_ecb(void), EVP_des_cfb(void), EVP_des_ofb(void)
DES in CBC, ECB, CFB and OFB modes respectively.
=item EVP_des_ede_cbc(void), EVP_des_ede(), EVP_des_ede_ofb(void), EVP_des_ede_cfb(void)
Two key triple DES in CBC, ECB, CFB and OFB modes respectively.
=item EVP_des_ede3_cbc(void), EVP_des_ede3(), EVP_des_ede3_ofb(void), EVP_des_ede3_cfb(void)
Three key triple DES in CBC, ECB, CFB and OFB modes respectively.
=item EVP_desx_cbc(void)
DESX algorithm in CBC mode.
=item EVP_rc4(void)
RC4 stream cipher. This is a variable key length cipher with default key length 128 bits.
=item EVP_rc4_40(void)
RC4 stream cipher with 40 bit key length. This is obsolete and new code should use EVP_rc4()
and the EVP_CIPHER_CTX_set_key_length() function.
=item EVP_idea_cbc() EVP_idea_ecb(void), EVP_idea_cfb(void), EVP_idea_ofb(void), EVP_idea_cbc(void)
IDEA encryption algorithm in CBC, ECB, CFB and OFB modes respectively.
=item EVP_rc2_cbc(void), EVP_rc2_ecb(void), EVP_rc2_cfb(void), EVP_rc2_ofb(void)
RC2 encryption algorithm in CBC, ECB, CFB and OFB modes respectively. This is a variable key
length cipher with an additional parameter called "effective key bits" or "effective key length".
By default both are set to 128 bits.
=item EVP_rc2_40_cbc(void), EVP_rc2_64_cbc(void)
RC2 algorithm in CBC mode with a default key length and effective key length of 40 and 64 bits.
These are obsolete and new code should use EVP_rc2_cbc(), EVP_CIPHER_CTX_set_key_length() and
EVP_CIPHER_CTX_ctrl() to set the key length and effective key length.
=item EVP_bf_cbc(void), EVP_bf_ecb(void), EVP_bf_cfb(void), EVP_bf_ofb(void);
Blowfish encryption algorithm in CBC, ECB, CFB and OFB modes respectively. This is a variable key
length cipher.
=item EVP_cast5_cbc(void), EVP_cast5_ecb(void), EVP_cast5_cfb(void), EVP_cast5_ofb(void)
CAST encryption algorithm in CBC, ECB, CFB and OFB modes respectively. This is a variable key
length cipher.
=item EVP_rc5_32_12_16_cbc(void), EVP_rc5_32_12_16_ecb(void), EVP_rc5_32_12_16_cfb(void), EVP_rc5_32_12_16_ofb(void)
RC5 encryption algorithm in CBC, ECB, CFB and OFB modes respectively. This is a variable key length
cipher with an additional "number of rounds" parameter. By default the key length is set to 128
bits and 12 rounds.
=item EVP_aes_128_gcm(void), EVP_aes_192_gcm(void), EVP_aes_256_gcm(void)
AES Galois Counter Mode (GCM) for 128, 192 and 256 bit keys respectively.
These ciphers require additional control operations to function correctly: see
L<GCM mode> section below for details.
=item EVP_aes_128_ccm(void), EVP_aes_192_ccm(void), EVP_aes_256_ccm(void)
AES Counter with CBC-MAC Mode (CCM) for 128, 192 and 256 bit keys respectively.
These ciphers require additional control operations to function correctly: see
CCM mode section below for details.
=back
=head1 GCM Mode
For GCM mode ciphers the behaviour of the EVP interface is subtly altered and
several GCM specific ctrl operations are supported.
To specify any additional authenticated data (AAD) a call to EVP_CipherUpdate(),
EVP_EncryptUpdate() or EVP_DecryptUpdate() should be made with the output
parameter B<out> set to B<NULL>.
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 following ctrls are supported in GCM mode:
EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, ivlen, NULL);
Sets the GCM IV length: this call can only be made before specifying an IV. If
not called a default IV length is used (96 bits for AES).
EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_GET_TAG, taglen, tag);
Writes B<taglen> bytes of the tag value to the buffer indicated by B<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).
EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_TAG, taglen, tag);
Sets the expected tag to B<taglen> bytes from B<tag>. This call is only legal
when decrypting data.
=head1 CCM Mode
The behaviour of CCM mode ciphers is similar to CCM mode but with a few
additional requirements and different ctrl values.
Like GCM mode any additional authenticated data (AAD) is passed by calling
EVP_CipherUpdate(), EVP_EncryptUpdate() or EVP_DecryptUpdate() with the output
parameter B<out> set to B<NULL>. Additionally the total plaintext or ciphertext
length B<MUST> be passed to EVP_CipherUpdate(), EVP_EncryptUpdate() or
EVP_DecryptUpdate() with the output and input parameters (B<in> and B<out>)
set to B<NULL> and the length passed in the B<inl> parameter.
The following ctrls are supported in CCM mode:
EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_CCM_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 B<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).
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).
EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_CCM_SET_IVLEN, ivlen, NULL);
Sets the CCM nonce (IV) length: this call can only be made before specifying
an nonce value. The nonce length is given by B<15 - L> so it is 7 by default
for AES.
=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_EncryptFinal(), EVP_DecryptInit(),
EVP_CipherInit() and EVP_CipherFinal() are obsolete but are retained for
compatibility with existing code. New code should use EVP_EncryptInit_ex(),
EVP_EncryptFinal_ex(), EVP_DecryptInit_ex(), EVP_DecryptFinal_ex(),
EVP_CipherInit_ex() and EVP_CipherFinal_ex() because they can reuse an
existing context without allocating and freeing it up on each call.
=head1 BUGS
For RC5 the number of rounds can currently only be set to 8, 12 or 16. This is
a limitation of the current RC5 code rather than the EVP interface.
EVP_MAX_KEY_LENGTH and 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 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;
EVP_CIPHER_CTX_init(&ctx);
EVP_EncryptInit_ex(&ctx, EVP_idea_cbc(), NULL, key, iv);
if(!EVP_EncryptUpdate(&ctx, outbuf, &outlen, intext, strlen(intext)))
{
/* Error */
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 */
return 0;
}
outlen += tmplen;
EVP_CIPHER_CTX_cleanup(&ctx);
/* Need binary mode for fopen because encrypted data is
* binary data. Also cannot use strlen() on it because
* it wont be null terminated and may contain embedded
* nulls.
*/
out = fopen(outfile, "wb");
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 <filename
-K 000102030405060708090A0B0C0D0E0F -iv 0102030405060708
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 */
EVP_CIPHER_CTX_init(&ctx);
EVP_CipherInit_ex(&ctx, EVP_aes_128_cbc(), NULL, NULL, NULL,
do_encrypt);
OPENSSL_assert(EVP_CIPHER_CTX_key_length(&ctx) == 16);
OPENSSL_assert(EVP_CIPHER_CTX_iv_length(&ctx) == 16);
/* Now we can set key and IV */
EVP_CipherInit_ex(&ctx, NULL, NULL, key, iv, do_encrypt);
for(;;)
{
inlen = fread(inbuf, 1, 1024, in);
if(inlen <= 0) break;
if(!EVP_CipherUpdate(&ctx, outbuf, &outlen, inbuf, inlen))
{
/* Error */
EVP_CIPHER_CTX_cleanup(&ctx);
return 0;
}
fwrite(outbuf, 1, outlen, out);
}
if(!EVP_CipherFinal_ex(&ctx, outbuf, &outlen))
{
/* Error */
EVP_CIPHER_CTX_cleanup(&ctx);
return 0;
}
fwrite(outbuf, 1, outlen, out);
EVP_CIPHER_CTX_cleanup(&ctx);
return 1;
}
=head1 SEE ALSO
L<evp(3)|evp(3)>
=head1 HISTORY
EVP_CIPHER_CTX_init(), EVP_EncryptInit_ex(), EVP_EncryptFinal_ex(),
EVP_DecryptInit_ex(), EVP_DecryptFinal_ex(), EVP_CipherInit_ex(),
EVP_CipherFinal_ex() and EVP_CIPHER_CTX_set_padding() appeared in
OpenSSL 0.9.7.
IDEA appeared in OpenSSL 0.9.7 but was often disabled due to
patent concerns; the last patents expired in 2012.
=cut
diff --git a/doc/crypto/X509_VERIFY_PARAM_set_flags.pod b/doc/crypto/X509_VERIFY_PARAM_set_flags.pod
index 44792f91a11d..10399ecbafd0 100644
--- a/doc/crypto/X509_VERIFY_PARAM_set_flags.pod
+++ b/doc/crypto/X509_VERIFY_PARAM_set_flags.pod
@@ -1,244 +1,266 @@
=pod
=head1 NAME
X509_VERIFY_PARAM_set_flags, X509_VERIFY_PARAM_clear_flags, X509_VERIFY_PARAM_get_flags, X509_VERIFY_PARAM_set_purpose, X509_VERIFY_PARAM_set_trust, X509_VERIFY_PARAM_set_depth, X509_VERIFY_PARAM_get_depth, X509_VERIFY_PARAM_set_time, X509_VERIFY_PARAM_add0_policy, X509_VERIFY_PARAM_set1_policies, X509_VERIFY_PARAM_set1_host, X509_VERIFY_PARAM_add1_host, X509_VERIFY_PARAM_set_hostflags, X509_VERIFY_PARAM_get0_peername, X509_VERIFY_PARAM_set1_email, X509_VERIFY_PARAM_set1_ip, X509_VERIFY_PARAM_set1_ip_asc - X509 verification parameters
=head1 SYNOPSIS
#include <openssl/x509_vfy.h>
int X509_VERIFY_PARAM_set_flags(X509_VERIFY_PARAM *param, unsigned long flags);
int X509_VERIFY_PARAM_clear_flags(X509_VERIFY_PARAM *param,
unsigned long flags);
unsigned long X509_VERIFY_PARAM_get_flags(X509_VERIFY_PARAM *param);
int X509_VERIFY_PARAM_set_purpose(X509_VERIFY_PARAM *param, int purpose);
int X509_VERIFY_PARAM_set_trust(X509_VERIFY_PARAM *param, int trust);
void X509_VERIFY_PARAM_set_time(X509_VERIFY_PARAM *param, time_t t);
int X509_VERIFY_PARAM_add0_policy(X509_VERIFY_PARAM *param,
ASN1_OBJECT *policy);
int X509_VERIFY_PARAM_set1_policies(X509_VERIFY_PARAM *param,
STACK_OF(ASN1_OBJECT) *policies);
void X509_VERIFY_PARAM_set_depth(X509_VERIFY_PARAM *param, int depth);
int X509_VERIFY_PARAM_get_depth(const X509_VERIFY_PARAM *param);
int X509_VERIFY_PARAM_set1_host(X509_VERIFY_PARAM *param,
const char *name, size_t namelen);
int X509_VERIFY_PARAM_add1_host(X509_VERIFY_PARAM *param,
const char *name, size_t namelen);
void X509_VERIFY_PARAM_set_hostflags(X509_VERIFY_PARAM *param,
unsigned int flags);
char *X509_VERIFY_PARAM_get0_peername(X509_VERIFY_PARAM *param);
int X509_VERIFY_PARAM_set1_email(X509_VERIFY_PARAM *param,
const char *email, size_t emaillen);
int X509_VERIFY_PARAM_set1_ip(X509_VERIFY_PARAM *param,
const unsigned char *ip, size_t iplen);
int X509_VERIFY_PARAM_set1_ip_asc(X509_VERIFY_PARAM *param, const char *ipasc);
=head1 DESCRIPTION
These functions manipulate the B<X509_VERIFY_PARAM> structure associated with
a certificate verification operation.
The X509_VERIFY_PARAM_set_flags() function sets the flags in B<param> by oring
it with B<flags>. See the B<VERIFICATION FLAGS> section for a complete
description of values the B<flags> parameter can take.
X509_VERIFY_PARAM_get_flags() returns the flags in B<param>.
X509_VERIFY_PARAM_clear_flags() clears the flags B<flags> in B<param>.
X509_VERIFY_PARAM_set_purpose() sets the verification purpose in B<param>
to B<purpose>. This determines the acceptable purpose of the certificate
chain, for example SSL client or SSL server.
X509_VERIFY_PARAM_set_trust() sets the trust setting in B<param> to
B<trust>.
X509_VERIFY_PARAM_set_time() sets the verification time in B<param> to
B<t>. Normally the current time is used.
X509_VERIFY_PARAM_add0_policy() enables policy checking (it is disabled
by default) and adds B<policy> to the acceptable policy set.
X509_VERIFY_PARAM_set1_policies() enables policy checking (it is disabled
by default) and sets the acceptable policy set to B<policies>. Any existing
policy set is cleared. The B<policies> parameter can be B<NULL> to clear
an existing policy set.
X509_VERIFY_PARAM_set_depth() sets the maximum verification depth to B<depth>.
That is the maximum number of untrusted CA certificates that can appear in a
chain.
X509_VERIFY_PARAM_set1_host() sets the expected DNS hostname to
B<name> clearing any previously specified host name or names. If
B<name> is NULL, or empty the list of hostnames is cleared, and
name checks are not performed on the peer certificate. If B<name>
is NUL-terminated, B<namelen> may be zero, otherwise B<namelen>
must be set to the length of B<name>. When a hostname is specified,
certificate verification automatically invokes L<X509_check_host(3)>
with flags equal to the B<flags> argument given to
B<X509_VERIFY_PARAM_set_hostflags()> (default zero). Applications
are strongly advised to use this interface in preference to explicitly
calling L<X509_check_host(3)>, hostname checks are out of scope
with the DANE-EE(3) certificate usage, and the internal check will
be suppressed as appropriate when DANE support is added to OpenSSL.
X509_VERIFY_PARAM_add1_host() adds B<name> as an additional reference
identifer that can match the peer's certificate. Any previous names
set via X509_VERIFY_PARAM_set1_host() or X509_VERIFY_PARAM_add1_host()
are retained, no change is made if B<name> is NULL or empty. When
multiple names are configured, the peer is considered verified when
any name matches.
X509_VERIFY_PARAM_get0_peername() returns the DNS hostname or subject
CommonName from the peer certificate that matched one of the reference
identifiers. When wildcard matching is not disabled, or when a
reference identifier specifies a parent domain (starts with ".")
rather than a hostname, the peer name may be a wildcard name or a
sub-domain of the reference identifier respectively. The return
string is allocated by the library and is no longer valid once the
associated B<param> argument is freed. Applications must not free
the return value.
X509_VERIFY_PARAM_set1_email() sets the expected RFC822 email address to
B<email>. If B<email> is NUL-terminated, B<emaillen> may be zero, otherwise
B<emaillen> must be set to the length of B<email>. When an email address
is specified, certificate verification automatically invokes
L<X509_check_email(3)>.
X509_VERIFY_PARAM_set1_ip() sets the expected IP address to B<ip>.
The B<ip> argument is in binary format, in network byte-order and
B<iplen> must be set to 4 for IPv4 and 16 for IPv6. When an IP
address is specified, certificate verification automatically invokes
L<X509_check_ip(3)>.
X509_VERIFY_PARAM_set1_ip_asc() sets the expected IP address to
B<ipasc>. The B<ipasc> argument is a NUL-terminal ASCII string:
dotted decimal quad for IPv4 and colon-separated hexadecimal for
IPv6. The condensed "::" notation is supported for IPv6 addresses.
=head1 RETURN VALUES
X509_VERIFY_PARAM_set_flags(), X509_VERIFY_PARAM_clear_flags(),
X509_VERIFY_PARAM_set_purpose(), X509_VERIFY_PARAM_set_trust(),
X509_VERIFY_PARAM_add0_policy() X509_VERIFY_PARAM_set1_policies(),
X509_VERIFY_PARAM_set1_host(), X509_VERIFY_PARAM_set_hostflags(),
X509_VERIFY_PARAM_set1_email(), X509_VERIFY_PARAM_set1_ip() and
X509_VERIFY_PARAM_set1_ip_asc() return 1 for success and 0 for
failure.
X509_VERIFY_PARAM_get_flags() returns the current verification flags.
X509_VERIFY_PARAM_set_time() and X509_VERIFY_PARAM_set_depth() do not return
values.
X509_VERIFY_PARAM_get_depth() returns the current verification depth.
=head1 VERIFICATION FLAGS
The verification flags consists of zero or more of the following flags
ored together.
B<X509_V_FLAG_CRL_CHECK> enables CRL checking for the certificate chain leaf
certificate. An error occurs if a suitable CRL cannot be found.
B<X509_V_FLAG_CRL_CHECK_ALL> enables CRL checking for the entire certificate
chain.
B<X509_V_FLAG_IGNORE_CRITICAL> disabled critical extension checking. By default
any unhandled critical extensions in certificates or (if checked) CRLs results
in a fatal error. If this flag is set unhandled critical extensions are
ignored. B<WARNING> setting this option for anything other than debugging
purposes can be a security risk. Finer control over which extensions are
supported can be performed in the verification callback.
THe B<X509_V_FLAG_X509_STRICT> flag disables workarounds for some broken
certificates and makes the verification strictly apply B<X509> rules.
B<X509_V_FLAG_ALLOW_PROXY_CERTS> enables proxy certificate verification.
B<X509_V_FLAG_POLICY_CHECK> enables certificate policy checking, by default
no policy checking is peformed. Additional information is sent to the
verification callback relating to policy checking.
B<X509_V_FLAG_EXPLICIT_POLICY>, B<X509_V_FLAG_INHIBIT_ANY> and
B<X509_V_FLAG_INHIBIT_MAP> set the B<require explicit policy>, B<inhibit any
policy> and B<inhibit policy mapping> flags respectively as defined in
B<RFC3280>. Policy checking is automatically enabled if any of these flags
are set.
If B<X509_V_FLAG_NOTIFY_POLICY> is set and the policy checking is successful
a special status code is set to the verification callback. This permits it
to examine the valid policy tree and perform additional checks or simply
log it for debugging purposes.
By default some additional features such as indirect CRLs and CRLs signed by
different keys are disabled. If B<X509_V_FLAG_EXTENDED_CRL_SUPPORT> is set
they are enabled.
If B<X509_V_FLAG_USE_DELTAS> ise set delta CRLs (if present) are used to
determine certificate status. If not set deltas are ignored.
B<X509_V_FLAG_CHECK_SS_SIGNATURE> enables checking of the root CA self signed
cerificate signature. By default this check is disabled because it doesn't
add any additional security but in some cases applications might want to
check the signature anyway. A side effect of not checking the root CA
signature is that disabled or unsupported message digests on the root CA
are not treated as fatal errors.
The B<X509_V_FLAG_CB_ISSUER_CHECK> flag enables debugging of certificate
issuer checks. It is B<not> needed unless you are logging certificate
verification. If this flag is set then additional status codes will be sent
to the verification callback and it B<must> be prepared to handle such cases
without assuming they are hard errors.
The B<X509_V_FLAG_NO_ALT_CHAINS> flag suppresses checking for alternative
chains. By default, when building a certificate chain, if the first certificate
chain found is not trusted, then OpenSSL will continue to check to see if an
alternative chain can be found that is trusted. With this flag set the behaviour
will match that of OpenSSL versions prior to 1.0.2b.
+The B<X509_V_FLAG_TRUSTED_FIRST> flag causes chain construction to look for
+issuers in the trust store before looking at the untrusted certificates
+provided as part of the the peer chain.
+Though it is not on by default in OpenSSL 1.0.2, applications should generally
+set this flag.
+Local issuer certificates are often more likely to satisfy local security
+requirements and lead to a locally trusted root.
+This is especially important When some certificates in the trust store have
+explicit trust settings (see "TRUST SETTINGS" in L<x509(1)>).
+
+The B<X509_V_FLAG_PARTIAL_CHAIN> flag causes intermediate certificates in the
+trust store to be treated as trust-anchors, in the same way as the self-signed
+root CA certificates.
+This makes it possible to trust certificates issued by an intermediate CA
+without having to trust its ancestor root CA.
+With OpenSSL 1.0.2, chain construction continues as long as there are
+additional trusted issuers in the trust store, and the last trusted issuer
+becomes the trust-anchor.
+Thus, even when an intermediate certificate is found in the trust store, the
+verified chain passed to callbacks may still be anchored by a root CA.
+
=head1 NOTES
The above functions should be used to manipulate verification parameters
instead of legacy functions which work in specific structures such as
X509_STORE_CTX_set_flags().
=head1 BUGS
Delta CRL checking is currently primitive. Only a single delta can be used and
(partly due to limitations of B<X509_STORE>) constructed CRLs are not
maintained.
If CRLs checking is enable CRLs are expected to be available in the
corresponding B<X509_STORE> structure. No attempt is made to download
CRLs from the CRL distribution points extension.
=head1 EXAMPLE
Enable CRL checking when performing certificate verification during SSL
connections associated with an B<SSL_CTX> structure B<ctx>:
X509_VERIFY_PARAM *param;
param = X509_VERIFY_PARAM_new();
X509_VERIFY_PARAM_set_flags(param, X509_V_FLAG_CRL_CHECK);
SSL_CTX_set1_param(ctx, param);
X509_VERIFY_PARAM_free(param);
=head1 SEE ALSO
L<X509_verify_cert(3)|X509_verify_cert(3)>,
L<X509_check_host(3)|X509_check_host(3)>,
L<X509_check_email(3)|X509_check_email(3)>,
-L<X509_check_ip(3)|X509_check_ip(3)>
+L<X509_check_ip(3)|X509_check_ip(3)>,
+L<x509(1)|x509(1)>
=head1 HISTORY
The B<X509_V_FLAG_NO_ALT_CHAINS> flag was added in OpenSSL 1.0.2b
=cut
diff --git a/doc/crypto/threads.pod b/doc/crypto/threads.pod
index dc0e9391dc20..30c19b815fd8 100644
--- a/doc/crypto/threads.pod
+++ b/doc/crypto/threads.pod
@@ -1,210 +1,214 @@
=pod
=head1 NAME
CRYPTO_THREADID_set_callback, CRYPTO_THREADID_get_callback,
CRYPTO_THREADID_current, CRYPTO_THREADID_cmp, CRYPTO_THREADID_cpy,
CRYPTO_THREADID_hash, CRYPTO_set_locking_callback, CRYPTO_num_locks,
CRYPTO_set_dynlock_create_callback, CRYPTO_set_dynlock_lock_callback,
CRYPTO_set_dynlock_destroy_callback, CRYPTO_get_new_dynlockid,
CRYPTO_destroy_dynlockid, CRYPTO_lock - OpenSSL thread support
=head1 SYNOPSIS
#include <openssl/crypto.h>
/* Don't use this structure directly. */
typedef struct crypto_threadid_st
{
void *ptr;
unsigned long val;
} CRYPTO_THREADID;
/* Only use CRYPTO_THREADID_set_[numeric|pointer]() within callbacks */
void CRYPTO_THREADID_set_numeric(CRYPTO_THREADID *id, unsigned long val);
void CRYPTO_THREADID_set_pointer(CRYPTO_THREADID *id, void *ptr);
int CRYPTO_THREADID_set_callback(void (*threadid_func)(CRYPTO_THREADID *));
void (*CRYPTO_THREADID_get_callback(void))(CRYPTO_THREADID *);
void CRYPTO_THREADID_current(CRYPTO_THREADID *id);
int CRYPTO_THREADID_cmp(const CRYPTO_THREADID *a,
const CRYPTO_THREADID *b);
void CRYPTO_THREADID_cpy(CRYPTO_THREADID *dest,
const CRYPTO_THREADID *src);
unsigned long CRYPTO_THREADID_hash(const CRYPTO_THREADID *id);
int CRYPTO_num_locks(void);
/* struct CRYPTO_dynlock_value needs to be defined by the user */
struct CRYPTO_dynlock_value;
void CRYPTO_set_dynlock_create_callback(struct CRYPTO_dynlock_value *
(*dyn_create_function)(char *file, int line));
void CRYPTO_set_dynlock_lock_callback(void (*dyn_lock_function)
(int mode, struct CRYPTO_dynlock_value *l,
const char *file, int line));
void CRYPTO_set_dynlock_destroy_callback(void (*dyn_destroy_function)
(struct CRYPTO_dynlock_value *l, const char *file, int line));
int CRYPTO_get_new_dynlockid(void);
void CRYPTO_destroy_dynlockid(int i);
void CRYPTO_lock(int mode, int n, const char *file, int line);
#define CRYPTO_w_lock(type) \
CRYPTO_lock(CRYPTO_LOCK|CRYPTO_WRITE,type,__FILE__,__LINE__)
#define CRYPTO_w_unlock(type) \
CRYPTO_lock(CRYPTO_UNLOCK|CRYPTO_WRITE,type,__FILE__,__LINE__)
#define CRYPTO_r_lock(type) \
CRYPTO_lock(CRYPTO_LOCK|CRYPTO_READ,type,__FILE__,__LINE__)
#define CRYPTO_r_unlock(type) \
CRYPTO_lock(CRYPTO_UNLOCK|CRYPTO_READ,type,__FILE__,__LINE__)
#define CRYPTO_add(addr,amount,type) \
CRYPTO_add_lock(addr,amount,type,__FILE__,__LINE__)
=head1 DESCRIPTION
-OpenSSL can safely be used in multi-threaded applications provided
-that at least two callback functions are set, locking_function and
+OpenSSL can generally be used safely in multi-threaded applications provided
+that at least two callback functions are set, the locking_function and
threadid_func.
+Note that OpenSSL is not completely thread-safe, and unfortunately not all
+global resources have the necessary locks.
+Further, the thread-safety does not extend to things like multiple threads
+using the same B<SSL> object at the same time.
locking_function(int mode, int n, const char *file, int line) is
needed to perform locking on shared data structures.
(Note that OpenSSL uses a number of global data structures that
will be implicitly shared whenever multiple threads use OpenSSL.)
Multi-threaded applications will crash at random if it is not set.
locking_function() must be able to handle up to CRYPTO_num_locks()
different mutex locks. It sets the B<n>-th lock if B<mode> &
B<CRYPTO_LOCK>, and releases it otherwise.
B<file> and B<line> are the file number of the function setting the
lock. They can be useful for debugging.
threadid_func(CRYPTO_THREADID *id) is needed to record the currently-executing
thread's identifier into B<id>. The implementation of this callback should not
fill in B<id> directly, but should use CRYPTO_THREADID_set_numeric() if thread
IDs are numeric, or CRYPTO_THREADID_set_pointer() if they are pointer-based.
If the application does not register such a callback using
CRYPTO_THREADID_set_callback(), then a default implementation is used - on
Windows and BeOS this uses the system's default thread identifying APIs, and on
all other platforms it uses the address of B<errno>. The latter is satisfactory
for thread-safety if and only if the platform has a thread-local error number
facility.
Once threadid_func() is registered, or if the built-in default implementation is
to be used;
=over 4
=item *
CRYPTO_THREADID_current() records the currently-executing thread ID into the
given B<id> object.
=item *
CRYPTO_THREADID_cmp() compares two thread IDs (returning zero for equality, ie.
the same semantics as memcmp()).
=item *
CRYPTO_THREADID_cpy() duplicates a thread ID value,
=item *
CRYPTO_THREADID_hash() returns a numeric value usable as a hash-table key. This
is usually the exact numeric or pointer-based thread ID used internally, however
this also handles the unusual case where pointers are larger than 'long'
variables and the platform's thread IDs are pointer-based - in this case, mixing
is done to attempt to produce a unique numeric value even though it is not as
wide as the platform's true thread IDs.
=back
Additionally, OpenSSL supports dynamic locks, and sometimes, some parts
of OpenSSL need it for better performance. To enable this, the following
is required:
=over 4
=item *
Three additional callback function, dyn_create_function, dyn_lock_function
and dyn_destroy_function.
=item *
A structure defined with the data that each lock needs to handle.
=back
struct CRYPTO_dynlock_value has to be defined to contain whatever structure
is needed to handle locks.
dyn_create_function(const char *file, int line) is needed to create a
lock. Multi-threaded applications might crash at random if it is not set.
dyn_lock_function(int mode, CRYPTO_dynlock *l, const char *file, int line)
is needed to perform locking off dynamic lock numbered n. Multi-threaded
applications might crash at random if it is not set.
dyn_destroy_function(CRYPTO_dynlock *l, const char *file, int line) is
needed to destroy the lock l. Multi-threaded applications might crash at
random if it is not set.
CRYPTO_get_new_dynlockid() is used to create locks. It will call
dyn_create_function for the actual creation.
CRYPTO_destroy_dynlockid() is used to destroy locks. It will call
dyn_destroy_function for the actual destruction.
CRYPTO_lock() is used to lock and unlock the locks. mode is a bitfield
describing what should be done with the lock. n is the number of the
lock as returned from CRYPTO_get_new_dynlockid(). mode can be combined
from the following values. These values are pairwise exclusive, with
undefined behaviour if misused (for example, CRYPTO_READ and CRYPTO_WRITE
should not be used together):
CRYPTO_LOCK 0x01
CRYPTO_UNLOCK 0x02
CRYPTO_READ 0x04
CRYPTO_WRITE 0x08
=head1 RETURN VALUES
CRYPTO_num_locks() returns the required number of locks.
CRYPTO_get_new_dynlockid() returns the index to the newly created lock.
The other functions return no values.
=head1 NOTES
You can find out if OpenSSL was configured with thread support:
#define OPENSSL_THREAD_DEFINES
#include <openssl/opensslconf.h>
#if defined(OPENSSL_THREADS)
// thread support enabled
#else
// no thread support
#endif
Also, dynamic locks are currently not used internally by OpenSSL, but
may do so in the future.
=head1 EXAMPLES
B<crypto/threads/mttest.c> shows examples of the callback functions on
Solaris, Irix and Win32.
=head1 HISTORY
CRYPTO_set_locking_callback() is
available in all versions of SSLeay and OpenSSL.
CRYPTO_num_locks() was added in OpenSSL 0.9.4.
All functions dealing with dynamic locks were added in OpenSSL 0.9.5b-dev.
B<CRYPTO_THREADID> and associated functions were introduced in OpenSSL 1.0.0
to replace (actually, deprecate) the previous CRYPTO_set_id_callback(),
CRYPTO_get_id_callback(), and CRYPTO_thread_id() functions which assumed
thread IDs to always be represented by 'unsigned long'.
=head1 SEE ALSO
L<crypto(3)|crypto(3)>
=cut
diff --git a/engines/ccgost/README.gost b/engines/ccgost/README.gost
index c96cccc7b40a..80f7900d0987 100644
--- a/engines/ccgost/README.gost
+++ b/engines/ccgost/README.gost
@@ -1,300 +1,299 @@
GOST ENGINE
This engine provides implementation of Russian cryptography standard.
This is also an example of adding new cryptoalgorithms into OpenSSL
without changing its core. If OpenSSL is compiled with dynamic engine
support, new algorithms can be added even without recompilation of
OpenSSL and applications which use it.
ALGORITHMS SUPPORTED
GOST R 34.10-94 and GOST R 34.10-2001 - digital signature algorithms.
Also support key exchange based on public keys. See RFC 4357 for
details of VKO key exchange algorithm. These algorithms use
256 bit private keys. Public keys are 1024 bit for 94 and 512 bit for
2001 (which is elliptic-curve based). Key exchange algorithms
(VKO R 34.10) are supported on these keys too.
GOST R 34.11-94 Message digest algorithm. 256-bit hash value
GOST 28147-89 - Symmetric cipher with 256-bit key. Various modes are
defined in the standard, but only CFB and CNT modes are implemented
in the engine. To make statistical analysis more difficult, key
meshing is supported (see RFC 4357).
GOST 28147-89 MAC mode. Message authentication code. While most MAC
algorithms out there are based on hash functions using HMAC
algorithm, this algoritm is based on symmetric cipher.
It has 256-bit symmetric key and only 32 bits of MAC value
(while HMAC has same key size and value size).
It is implemented as combination of EVP_PKEY type and EVP_MD type.
USAGE OF THESE ALGORITHMS
This engine is designed to allow usage of this algorithms in the
high-level openssl functions, such as PKI, S/MIME and TLS.
See RFC 4490 for S/MIME with GOST algorithms and RFC 4491 for PKI.
TLS support is implemented according IETF
draft-chudov-cryptopro-cptls-03.txt and is compatible with
CryptoPro CSP 3.0 and 3.6 as well as with MagPro CSP.
GOST ciphersuites implemented in CryptoPro CSP 2.0 are not supported
because they use ciphersuite numbers used now by AES ciphersuites.
To use the engine you have to load it via openssl configuration
file. Applications should read openssl configuration file or provide
their own means to load engines. Also, applications which operate with
private keys, should use generic EVP_PKEY API instead of using RSA or
other algorithm-specific API.
CONFIGURATION FILE
Configuration file should include following statement in the global
section, i.e. before first bracketed section header (see config(5) for details)
openssl_conf = openssl_def
where openssl_def is name of the section in configuration file which
describes global defaults.
This section should contain following statement:
[openssl_def]
engines = engine_section
which points to the section which describes list of the engines to be
loaded. This section should contain:
[engine_section]
gost = gost_section
And section which describes configuration of the engine should contain
[gost_section]
engine_id = gost
dynamic_path = /usr/lib/ssl/engines/libgost.so
default_algorithms = ALL
CRYPT_PARAMS = id-Gost28147-89-CryptoPro-A-ParamSet
Where engine_id parameter specifies name of engine (should be "gost").
dynamic_path is a location of the loadable shared library implementing the
engine. If the engine is compiled statically or is located in the OpenSSL
engines directory, this line can be omitted.
default_algorithms parameter specifies that all algorithms, provided by
engine, should be used.
The CRYPT_PARAMS parameter is engine-specific. It allows the user to choose
between different parameter sets of symmetric cipher algorithm. RFC 4357
specifies several parameters for the GOST 28147-89 algorithm, but OpenSSL
doesn't provide user interface to choose one when encrypting. So use engine
configuration parameter instead.
Value of this parameter can be either short name, defined in OpenSSL
obj_dat.h header file or numeric representation of OID, defined in RFC
4357.
USAGE WITH COMMAND LINE openssl UTILITY
1. Generation of private key
openssl genpkey -algorithm gost2001 -pkeyopt paramset:A -out seckey.pem
Use -algorithm option to specify algorithm.
Use -pkeyopt option to pass paramset to algorithm. The following paramsets
are supported by
gost94: 0,A,B,C,D,XA,XB,XC
gost2001: 0,A,B,C,XA,XB
You can also use numeric representation of OID as to destinate
paramset.
Paramsets starting with X are intended to use for key exchange keys.
Paramsets without X are for digital signature keys.
Paramset for both algorithms 0 is the test paramset which should be used
only for test purposes.
There are no algorithm-specific things with generation of certificate
request once you have a private key.
2. Generation of certificate request along with private/public keypar
openssl req -newkey gost2001 -pkeyopt paramset:A
Syntax of -pkeyopt parameter is identical with genpkey command.
You can also use oldstyle syntax -newkey gost2001:paramfile, but in
this case you should create parameter file first.
It can be created with
openssl genpkey -genparam -algorithm gost2001 -pkeyopt paramset:A\
-out paramfile.
3. S/MIME operations
If you want to send encrypted mail using GOST algorithms, don't forget
to specify -gost89 as encryption algorithm for OpenSSL smime command.
While OpenSSL is clever enough to find out that GOST R 34.11-94 digest
must be used for digital signing with GOST private key, it have no way
to derive symmetric encryption algorithm from key exchange keys.
4. TLS operations
OpenSSL supports all four ciphersuites defined in the IETF draft.
Once you've loaded GOST key and certificate into your TLS server,
ciphersuites which use GOST 28147-89 encryption are enabled.
Ciphersuites with NULL encryption should be enabled explicitely if
needed.
GOST2001-GOST89-GOST89 Uses GOST R 34.10-2001 for auth and key exchange
GOST 28147-89 for encryption and GOST 28147-89 MAC
GOST94-GOST89-GOST89 Uses GOST R 34.10-94 for auth and key exchange
GOST 28147-89 for encryption and GOST 28147-89 MAC
GOST2001-NULL-GOST94 Uses GOST R 34.10-2001 for auth and key exchange,
no encryption and HMAC, based on GOST R 34.11-94
GOST94-NULL-GOST94 Uses GOST R 34.10-94 for auth and key exchange,
no encryption and HMAC, based on GOST R 34.11-94
Gost 94 and gost 2001 keys can be used simultaneously in the TLS server.
RSA, DSA and EC keys can be used simultaneously with GOST keys, if
server implementation supports loading more than two private
key/certificate pairs. In this case ciphersuites which use any of loaded
keys would be supported and clients can negotiate ones they wish.
This allows creation of TLS servers which use GOST ciphersuites for
Russian clients and RSA/DSA ciphersuites for foreign clients.
5. Calculation of digests and symmetric encryption
OpenSSL provides specific commands (like sha1, aes etc) for calculation
of digests and symmetric encryption. Since such commands cannot be
added dynamically, no such commands are provided for GOST algorithms.
Use generic commands 'dgst' and 'enc'.
Calculation of GOST R 34.11-94 message digest
openssl dgst -md_gost94 datafile
Note that GOST R 34.11-94 specifies that digest value should be
interpreted as little-endian number, but OpenSSL outputs just hex dump
of digest value.
So, to obtain correct digest value, such as produced by gostsum utility
included in the engine distribution, bytes of output should be
reversed.
Calculation of HMAC based on GOST R 34.11-94
openssl dgst -md_gost94 -mac hmac -macopt key:<32 bytes of key> datafile
(or use hexkey if key contain NUL bytes)
Calculation of GOST 28147 MAC
openssl dgst -mac gost-mac -macopt key:<32 bytes of key> datafile
- Note absense of an option that specifies digest algorithm. gost-mac
+ Note absence of an option that specifies digest algorithm. gost-mac
algorithm supports only one digest (which is actually part of
implementation of this mac) and OpenSSL is clever enough to find out
this.
Encryption with GOST 28147 CFB mode
openssl enc -gost89 -out encrypted-file -in plain-text-file -k <passphrase>
Encryption with GOST 28147 CNT mode
openssl enc -gost89-cnt -out encrypted-file -in plain-text-file -k <passphrase>
6. Encrypting private keys and PKCS12
To produce PKCS12 files compatible with MagPro CSP, you need to use
GOST algorithm for encryption of PKCS12 file and also GOST R 34.11-94
hash to derive key from password.
openssl pksc12 -export -inkey gost.pem -in gost_cert.pem -keypbe gost89\
-certpbe gost89 -macalg md_gost94
7. Testing speed of symmetric ciphers.
To test performance of GOST symmetric ciphers you should use -evp switch
-of the openssl speed command. Engine-provided ciphers couldn't be
-accessed by cipher-specific functions, only via generic evp interface
+of the openssl speed command. Engine-provided ciphers can be accessed only via
+generic evp interface and not by cipher-specific functions.
openssl speed -evp gost89
openssl speed -evp gost89-cnt
PROGRAMMING INTERFACES DETAILS
-Applications never should access engine directly. They only use provided
+Applications should never access engine directly. They should only use provided
EVP_PKEY API. But there are some details, which should be taken into
account.
EVP provides two kinds of API for key exchange:
1. EVP_PKEY_encrypt/EVP_PKEY_decrypt functions, intended to use with
RSA-like public key encryption algorithms
2. EVP_PKEY_derive, intended to use with Diffie-Hellman-like shared key
computing algorithms.
Although VKO R 34.10 algorithms, described in the RFC 4357 are
definitely second case, engine provides BOTH API for GOST R 34.10 keys.
EVP_PKEY_derive just invokes appropriate VKO algorithm and computes
256 bit shared key. VKO R 34.10-2001 requires 64 bits of random user key
material (UKM). This UKM should be transmitted to other party, so it is
not generated inside derive function.
It should be set by EVP_PKEY_CTX_ctrl function using
EVP_PKEY_CTRL_SET_IV command after call of EVP_PKEY_derive_init, but
before EVP_PKEY_derive.
unsigned char ukm[8];
RAND_bytes(ukm,8);
EVP_PKEY_CTX_ctrl(ctx, -1, EVP_PKEY_OP_DERIVE, 8, ukm)
EVP_PKEY_encrypt encrypts provided session key with VKO shared key and
packs it into GOST key transport structure, described in the RFC 4490.
It typically uses ephemeral key pair to compute shared key and packs its
public part along with encrypted key. So, for most cases use of
EVP_PKEY_encrypt/EVP_PKEY_decrypt with GOST keys is almost same as with
RSA.
However, if peerkey field in the EVP_PKEY_CTX structure is set (using
EVP_PKEY_derive_set_peerkey function) to EVP_PKEY structure which has private
key and uses same parameters as the public key from which this EVP_PKEY_CTX is
created, EVP_PKEY_encrypt will use this private key to compute shared key and
set ephemeral key in the GOST_key_transport structure to NULL. In this case
pkey and peerkey fields in the EVP_PKEY_CTX are used upside-down.
If EVP_PKEY_decrypt encounters GOST_key_transport structure with NULL
public key field, it tries to use peerkey field from the context to
compute shared key. In this case peerkey field should really contain
peer public key.
Encrypt operation supports EVP_PKEY_CTRL_SET_IV operation as well.
It can be used when some specific restriction on UKM are imposed by
higher level protocol. For instance, description of GOST ciphersuites
requires UKM to be derived from shared secret.
If UKM is not set by this control command, encrypt operation would
generate random UKM.
-This sources include implementation of GOST 28147-89 and GOST R 34.11-94
-which are completely indepentent from OpenSSL and can be used separately
-(files gost89.c, gost89.h, gosthash.c, gosthash.h) Utility gostsum (file
-gostsum.c) is provided as example of such separate usage. This is
-program, simular to md5sum and sha1sum utilities, but calculates GOST R
-34.11-94 hash.
+These sources include implementation of GOST 28147-89 and GOST R 34.11-94
+which are completely independent from OpenSSL and can be used separately
+(files gost89.c, gost89.h, gosthash.c, gosthash.h). Utility gostsum (file
+gostsum.c) is provided as an example of such separate usage. This program is
+similar to md5sum and sha1sum utilities, but calculates GOST R 34.11-94 hash.
Makefile doesn't include rule for compiling gostsum.
Use command
$(CC) -o gostsum gostsum.c gost89.c gosthash.c
where $(CC) is name of your C compiler.
Implementations of GOST R 34.10-xx, including VKO algorithms heavily
depends on OpenSSL BIGNUM and Elliptic Curve libraries.
diff --git a/engines/ccgost/gost_eng.c b/engines/ccgost/gost_eng.c
index 5924791b7735..ea52c4dbe9db 100644
--- a/engines/ccgost/gost_eng.c
+++ b/engines/ccgost/gost_eng.c
@@ -1,281 +1,280 @@
/**********************************************************************
* gost_eng.c *
* Copyright (c) 2005-2006 Cryptocom LTD *
* This file is distributed under the same license as OpenSSL *
* *
* Main file of GOST engine *
* for OpenSSL *
* Requires OpenSSL 0.9.9 for compilation *
**********************************************************************/
#include <string.h>
#include <openssl/crypto.h>
#include <openssl/err.h>
#include <openssl/evp.h>
#include <openssl/engine.h>
#include <openssl/obj_mac.h>
#include "e_gost_err.h"
#include "gost_lcl.h"
static const char *engine_gost_id = "gost";
static const char *engine_gost_name =
"Reference implementation of GOST engine";
/* Symmetric cipher and digest function registrar */
static int gost_ciphers(ENGINE *e, const EVP_CIPHER **cipher,
const int **nids, int nid);
static int gost_digests(ENGINE *e, const EVP_MD **digest,
const int **nids, int ind);
static int gost_pkey_meths(ENGINE *e, EVP_PKEY_METHOD **pmeth,
const int **nids, int nid);
static int gost_pkey_asn1_meths(ENGINE *e, EVP_PKEY_ASN1_METHOD **ameth,
const int **nids, int nid);
static int gost_cipher_nids[] = { NID_id_Gost28147_89, NID_gost89_cnt, 0 };
static int gost_digest_nids[] =
{ NID_id_GostR3411_94, NID_id_Gost28147_89_MAC, 0 };
static int gost_pkey_meth_nids[] = { NID_id_GostR3410_94,
NID_id_GostR3410_2001, NID_id_Gost28147_89_MAC, 0
};
static EVP_PKEY_METHOD *pmeth_GostR3410_94 = NULL,
*pmeth_GostR3410_2001 = NULL, *pmeth_Gost28147_MAC = NULL;
static EVP_PKEY_ASN1_METHOD *ameth_GostR3410_94 = NULL,
*ameth_GostR3410_2001 = NULL, *ameth_Gost28147_MAC = NULL;
static int gost_engine_init(ENGINE *e)
{
return 1;
}
static int gost_engine_finish(ENGINE *e)
{
return 1;
}
static int gost_engine_destroy(ENGINE *e)
{
gost_param_free();
pmeth_GostR3410_94 = NULL;
pmeth_GostR3410_2001 = NULL;
pmeth_Gost28147_MAC = NULL;
ameth_GostR3410_94 = NULL;
ameth_GostR3410_2001 = NULL;
ameth_Gost28147_MAC = NULL;
return 1;
}
static int bind_gost(ENGINE *e, const char *id)
{
int ret = 0;
if (id && strcmp(id, engine_gost_id))
return 0;
if (ameth_GostR3410_94) {
printf("GOST engine already loaded\n");
goto end;
}
if (!ENGINE_set_id(e, engine_gost_id)) {
printf("ENGINE_set_id failed\n");
goto end;
}
if (!ENGINE_set_name(e, engine_gost_name)) {
printf("ENGINE_set_name failed\n");
goto end;
}
if (!ENGINE_set_digests(e, gost_digests)) {
printf("ENGINE_set_digests failed\n");
goto end;
}
if (!ENGINE_set_ciphers(e, gost_ciphers)) {
printf("ENGINE_set_ciphers failed\n");
goto end;
}
if (!ENGINE_set_pkey_meths(e, gost_pkey_meths)) {
printf("ENGINE_set_pkey_meths failed\n");
goto end;
}
if (!ENGINE_set_pkey_asn1_meths(e, gost_pkey_asn1_meths)) {
printf("ENGINE_set_pkey_asn1_meths failed\n");
goto end;
}
/* Control function and commands */
if (!ENGINE_set_cmd_defns(e, gost_cmds)) {
fprintf(stderr, "ENGINE_set_cmd_defns failed\n");
goto end;
}
if (!ENGINE_set_ctrl_function(e, gost_control_func)) {
fprintf(stderr, "ENGINE_set_ctrl_func failed\n");
goto end;
}
if (!ENGINE_set_destroy_function(e, gost_engine_destroy)
|| !ENGINE_set_init_function(e, gost_engine_init)
|| !ENGINE_set_finish_function(e, gost_engine_finish)) {
goto end;
}
if (!register_ameth_gost
(NID_id_GostR3410_94, &ameth_GostR3410_94, "GOST94",
"GOST R 34.10-94"))
goto end;
if (!register_ameth_gost
(NID_id_GostR3410_2001, &ameth_GostR3410_2001, "GOST2001",
"GOST R 34.10-2001"))
goto end;
if (!register_ameth_gost(NID_id_Gost28147_89_MAC, &ameth_Gost28147_MAC,
"GOST-MAC", "GOST 28147-89 MAC"))
goto end;
if (!register_pmeth_gost(NID_id_GostR3410_94, &pmeth_GostR3410_94, 0))
goto end;
if (!register_pmeth_gost(NID_id_GostR3410_2001, &pmeth_GostR3410_2001, 0))
goto end;
if (!register_pmeth_gost
(NID_id_Gost28147_89_MAC, &pmeth_Gost28147_MAC, 0))
goto end;
if (!ENGINE_register_ciphers(e)
|| !ENGINE_register_digests(e)
|| !ENGINE_register_pkey_meths(e)
/* These two actually should go in LIST_ADD command */
|| !EVP_add_cipher(&cipher_gost)
|| !EVP_add_cipher(&cipher_gost_cpacnt)
|| !EVP_add_digest(&digest_gost)
|| !EVP_add_digest(&imit_gost_cpa)
) {
goto end;
}
ERR_load_GOST_strings();
ret = 1;
end:
return ret;
}
-#ifndef OPENSSL_NO_DYNAMIC_ENGINE
-IMPLEMENT_DYNAMIC_BIND_FN(bind_gost)
- IMPLEMENT_DYNAMIC_CHECK_FN()
-#endif /* ndef OPENSSL_NO_DYNAMIC_ENGINE */
static int gost_digests(ENGINE *e, const EVP_MD **digest,
const int **nids, int nid)
{
int ok = 1;
if (!digest) {
*nids = gost_digest_nids;
return 2;
}
/*
* printf("Digest no %d requested\n",nid);
*/
if (nid == NID_id_GostR3411_94) {
*digest = &digest_gost;
} else if (nid == NID_id_Gost28147_89_MAC) {
*digest = &imit_gost_cpa;
} else {
ok = 0;
*digest = NULL;
}
return ok;
}
static int gost_ciphers(ENGINE *e, const EVP_CIPHER **cipher,
const int **nids, int nid)
{
int ok = 1;
if (!cipher) {
*nids = gost_cipher_nids;
return 2; /* two ciphers are supported */
}
if (nid == NID_id_Gost28147_89) {
*cipher = &cipher_gost;
} else if (nid == NID_gost89_cnt) {
*cipher = &cipher_gost_cpacnt;
} else {
ok = 0;
*cipher = NULL;
}
return ok;
}
static int gost_pkey_meths(ENGINE *e, EVP_PKEY_METHOD **pmeth,
const int **nids, int nid)
{
if (!pmeth) {
*nids = gost_pkey_meth_nids;
return 3;
}
switch (nid) {
case NID_id_GostR3410_94:
*pmeth = pmeth_GostR3410_94;
return 1;
case NID_id_GostR3410_2001:
*pmeth = pmeth_GostR3410_2001;
return 1;
case NID_id_Gost28147_89_MAC:
*pmeth = pmeth_Gost28147_MAC;
return 1;
default:;
}
*pmeth = NULL;
return 0;
}
static int gost_pkey_asn1_meths(ENGINE *e, EVP_PKEY_ASN1_METHOD **ameth,
const int **nids, int nid)
{
if (!ameth) {
*nids = gost_pkey_meth_nids;
return 3;
}
switch (nid) {
case NID_id_GostR3410_94:
*ameth = ameth_GostR3410_94;
return 1;
case NID_id_GostR3410_2001:
*ameth = ameth_GostR3410_2001;
return 1;
case NID_id_Gost28147_89_MAC:
*ameth = ameth_Gost28147_MAC;
return 1;
default:;
}
*ameth = NULL;
return 0;
}
#ifdef OPENSSL_NO_DYNAMIC_ENGINE
static ENGINE *engine_gost(void)
{
ENGINE *ret = ENGINE_new();
if (!ret)
return NULL;
if (!bind_gost(ret, engine_gost_id)) {
ENGINE_free(ret);
return NULL;
}
return ret;
}
void ENGINE_load_gost(void)
{
ENGINE *toadd;
if (pmeth_GostR3410_94)
return;
toadd = engine_gost();
if (!toadd)
return;
ENGINE_add(toadd);
ENGINE_free(toadd);
ERR_clear_error();
}
+#else
+IMPLEMENT_DYNAMIC_BIND_FN(bind_gost)
+IMPLEMENT_DYNAMIC_CHECK_FN()
#endif
diff --git a/engines/e_atalla.c b/engines/e_atalla.c
index 6a324e6766b0..7d136fff0736 100644
--- a/engines/e_atalla.c
+++ b/engines/e_atalla.c
@@ -1,626 +1,626 @@
/* crypto/engine/hw_atalla.c */
/*
* Written by Geoff Thorpe (geoff@geoffthorpe.net) for the OpenSSL project
* 2000.
*/
/* ====================================================================
* Copyright (c) 1999-2001 The OpenSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* licensing@OpenSSL.org.
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*
* This product includes cryptographic software written by Eric Young
* (eay@cryptsoft.com). This product includes software written by Tim
* Hudson (tjh@cryptsoft.com).
*
*/
#include <stdio.h>
#include <string.h>
#include <openssl/crypto.h>
#include <openssl/buffer.h>
#include <openssl/dso.h>
#include <openssl/engine.h>
#ifndef OPENSSL_NO_RSA
# include <openssl/rsa.h>
#endif
#ifndef OPENSSL_NO_DSA
# include <openssl/dsa.h>
#endif
#ifndef OPENSSL_NO_DH
# include <openssl/dh.h>
#endif
#include <openssl/bn.h>
#ifndef OPENSSL_NO_HW
# ifndef OPENSSL_NO_HW_ATALLA
# ifdef FLAT_INC
# include "atalla.h"
# else
# include "vendor_defns/atalla.h"
# endif
# define ATALLA_LIB_NAME "atalla engine"
# include "e_atalla_err.c"
static int atalla_destroy(ENGINE *e);
static int atalla_init(ENGINE *e);
static int atalla_finish(ENGINE *e);
static int atalla_ctrl(ENGINE *e, int cmd, long i, void *p, void (*f) (void));
/* BIGNUM stuff */
static int atalla_mod_exp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p,
const BIGNUM *m, BN_CTX *ctx);
# ifndef OPENSSL_NO_RSA
/* RSA stuff */
static int atalla_rsa_mod_exp(BIGNUM *r0, const BIGNUM *I, RSA *rsa,
BN_CTX *ctx);
/* This function is aliased to mod_exp (with the mont stuff dropped). */
static int atalla_mod_exp_mont(BIGNUM *r, const BIGNUM *a, const BIGNUM *p,
const BIGNUM *m, BN_CTX *ctx,
BN_MONT_CTX *m_ctx);
# endif
# ifndef OPENSSL_NO_DSA
/* DSA stuff */
static int atalla_dsa_mod_exp(DSA *dsa, BIGNUM *rr, BIGNUM *a1,
BIGNUM *p1, BIGNUM *a2, BIGNUM *p2, BIGNUM *m,
BN_CTX *ctx, BN_MONT_CTX *in_mont);
static int atalla_mod_exp_dsa(DSA *dsa, BIGNUM *r, BIGNUM *a,
const BIGNUM *p, const BIGNUM *m, BN_CTX *ctx,
BN_MONT_CTX *m_ctx);
# endif
# ifndef OPENSSL_NO_DH
/* DH stuff */
/* This function is alised to mod_exp (with the DH and mont dropped). */
static int atalla_mod_exp_dh(const DH *dh, BIGNUM *r,
const BIGNUM *a, const BIGNUM *p,
const BIGNUM *m, BN_CTX *ctx,
BN_MONT_CTX *m_ctx);
# endif
/* The definitions for control commands specific to this engine */
# define ATALLA_CMD_SO_PATH ENGINE_CMD_BASE
static const ENGINE_CMD_DEFN atalla_cmd_defns[] = {
{ATALLA_CMD_SO_PATH,
"SO_PATH",
"Specifies the path to the 'atasi' shared library",
ENGINE_CMD_FLAG_STRING},
{0, NULL, NULL, 0}
};
# ifndef OPENSSL_NO_RSA
/* Our internal RSA_METHOD that we provide pointers to */
static RSA_METHOD atalla_rsa = {
"Atalla RSA method",
NULL,
NULL,
NULL,
NULL,
atalla_rsa_mod_exp,
atalla_mod_exp_mont,
NULL,
NULL,
0,
NULL,
NULL,
NULL,
NULL
};
# endif
# ifndef OPENSSL_NO_DSA
/* Our internal DSA_METHOD that we provide pointers to */
static DSA_METHOD atalla_dsa = {
"Atalla DSA method",
NULL, /* dsa_do_sign */
NULL, /* dsa_sign_setup */
NULL, /* dsa_do_verify */
atalla_dsa_mod_exp, /* dsa_mod_exp */
atalla_mod_exp_dsa, /* bn_mod_exp */
NULL, /* init */
NULL, /* finish */
0, /* flags */
NULL, /* app_data */
NULL, /* dsa_paramgen */
NULL /* dsa_keygen */
};
# endif
# ifndef OPENSSL_NO_DH
/* Our internal DH_METHOD that we provide pointers to */
static DH_METHOD atalla_dh = {
"Atalla DH method",
NULL,
NULL,
atalla_mod_exp_dh,
NULL,
NULL,
0,
NULL,
NULL
};
# endif
/* Constants used when creating the ENGINE */
static const char *engine_atalla_id = "atalla";
static const char *engine_atalla_name = "Atalla hardware engine support";
/*
* This internal function is used by ENGINE_atalla() and possibly by the
* "dynamic" ENGINE support too
*/
static int bind_helper(ENGINE *e)
{
# ifndef OPENSSL_NO_RSA
const RSA_METHOD *meth1;
# endif
# ifndef OPENSSL_NO_DSA
const DSA_METHOD *meth2;
# endif
# ifndef OPENSSL_NO_DH
const DH_METHOD *meth3;
# endif
if (!ENGINE_set_id(e, engine_atalla_id) ||
!ENGINE_set_name(e, engine_atalla_name) ||
# ifndef OPENSSL_NO_RSA
!ENGINE_set_RSA(e, &atalla_rsa) ||
# endif
# ifndef OPENSSL_NO_DSA
!ENGINE_set_DSA(e, &atalla_dsa) ||
# endif
# ifndef OPENSSL_NO_DH
!ENGINE_set_DH(e, &atalla_dh) ||
# endif
!ENGINE_set_destroy_function(e, atalla_destroy) ||
!ENGINE_set_init_function(e, atalla_init) ||
!ENGINE_set_finish_function(e, atalla_finish) ||
!ENGINE_set_ctrl_function(e, atalla_ctrl) ||
!ENGINE_set_cmd_defns(e, atalla_cmd_defns))
return 0;
# ifndef OPENSSL_NO_RSA
/*
* We know that the "PKCS1_SSLeay()" functions hook properly to the
* atalla-specific mod_exp and mod_exp_crt so we use those functions. NB:
* We don't use ENGINE_openssl() or anything "more generic" because
* something like the RSAref code may not hook properly, and if you own
* one of these cards then you have the right to do RSA operations on it
* anyway!
*/
meth1 = RSA_PKCS1_SSLeay();
atalla_rsa.rsa_pub_enc = meth1->rsa_pub_enc;
atalla_rsa.rsa_pub_dec = meth1->rsa_pub_dec;
atalla_rsa.rsa_priv_enc = meth1->rsa_priv_enc;
atalla_rsa.rsa_priv_dec = meth1->rsa_priv_dec;
# endif
# ifndef OPENSSL_NO_DSA
/*
* Use the DSA_OpenSSL() method and just hook the mod_exp-ish bits.
*/
meth2 = DSA_OpenSSL();
atalla_dsa.dsa_do_sign = meth2->dsa_do_sign;
atalla_dsa.dsa_sign_setup = meth2->dsa_sign_setup;
atalla_dsa.dsa_do_verify = meth2->dsa_do_verify;
# endif
# ifndef OPENSSL_NO_DH
/* Much the same for Diffie-Hellman */
meth3 = DH_OpenSSL();
atalla_dh.generate_key = meth3->generate_key;
atalla_dh.compute_key = meth3->compute_key;
# endif
/* Ensure the atalla error handling is set up */
ERR_load_ATALLA_strings();
return 1;
}
# ifdef OPENSSL_NO_DYNAMIC_ENGINE
static ENGINE *engine_atalla(void)
{
ENGINE *ret = ENGINE_new();
if (!ret)
return NULL;
if (!bind_helper(ret)) {
ENGINE_free(ret);
return NULL;
}
return ret;
}
void ENGINE_load_atalla(void)
{
/* Copied from eng_[openssl|dyn].c */
ENGINE *toadd = engine_atalla();
if (!toadd)
return;
ENGINE_add(toadd);
ENGINE_free(toadd);
ERR_clear_error();
}
# endif
/*
* This is a process-global DSO handle used for loading and unloading the
* Atalla library. NB: This is only set (or unset) during an init() or
* finish() call (reference counts permitting) and they're operating with
* global locks, so this should be thread-safe implicitly.
*/
static DSO *atalla_dso = NULL;
/*
* These are the function pointers that are (un)set when the library has
* successfully (un)loaded.
*/
static tfnASI_GetHardwareConfig *p_Atalla_GetHardwareConfig = NULL;
static tfnASI_RSAPrivateKeyOpFn *p_Atalla_RSAPrivateKeyOpFn = NULL;
static tfnASI_GetPerformanceStatistics *p_Atalla_GetPerformanceStatistics =
NULL;
/*
* These are the static string constants for the DSO file name and the
* function symbol names to bind to. Regrettably, the DSO name on *nix
* appears to be "atasi.so" rather than something more consistent like
* "libatasi.so". At the time of writing, I'm not sure what the file name on
* win32 is but clearly native name translation is not possible (eg
* libatasi.so on *nix, and atasi.dll on win32). For the purposes of testing,
* I have created a symbollic link called "libatasi.so" so that we can use
* native name-translation - a better solution will be needed.
*/
static const char *ATALLA_LIBNAME = NULL;
static const char *get_ATALLA_LIBNAME(void)
{
if (ATALLA_LIBNAME)
return ATALLA_LIBNAME;
return "atasi";
}
static void free_ATALLA_LIBNAME(void)
{
if (ATALLA_LIBNAME)
OPENSSL_free((void *)ATALLA_LIBNAME);
ATALLA_LIBNAME = NULL;
}
static long set_ATALLA_LIBNAME(const char *name)
{
free_ATALLA_LIBNAME();
return (((ATALLA_LIBNAME = BUF_strdup(name)) != NULL) ? 1 : 0);
}
static const char *ATALLA_F1 = "ASI_GetHardwareConfig";
static const char *ATALLA_F2 = "ASI_RSAPrivateKeyOpFn";
static const char *ATALLA_F3 = "ASI_GetPerformanceStatistics";
/* Destructor (complements the "ENGINE_atalla()" constructor) */
static int atalla_destroy(ENGINE *e)
{
free_ATALLA_LIBNAME();
/*
* Unload the atalla error strings so any error state including our
* functs or reasons won't lead to a segfault (they simply get displayed
* without corresponding string data because none will be found).
*/
ERR_unload_ATALLA_strings();
return 1;
}
/* (de)initialisation functions. */
static int atalla_init(ENGINE *e)
{
tfnASI_GetHardwareConfig *p1;
tfnASI_RSAPrivateKeyOpFn *p2;
tfnASI_GetPerformanceStatistics *p3;
/*
* Not sure of the origin of this magic value, but Ben's code had it and
* it seemed to have been working for a few people. :-)
*/
unsigned int config_buf[1024];
if (atalla_dso != NULL) {
ATALLAerr(ATALLA_F_ATALLA_INIT, ATALLA_R_ALREADY_LOADED);
goto err;
}
/*
* Attempt to load libatasi.so/atasi.dll/whatever. Needs to be changed
* unfortunately because the Atalla drivers don't have standard library
* names that can be platform-translated well.
*/
/*
* TODO: Work out how to actually map to the names the Atalla drivers
* really use - for now a symbollic link needs to be created on the host
* system from libatasi.so to atasi.so on unix variants.
*/
atalla_dso = DSO_load(NULL, get_ATALLA_LIBNAME(), NULL, 0);
if (atalla_dso == NULL) {
ATALLAerr(ATALLA_F_ATALLA_INIT, ATALLA_R_NOT_LOADED);
goto err;
}
if (!
(p1 =
(tfnASI_GetHardwareConfig *) DSO_bind_func(atalla_dso, ATALLA_F1))
|| !(p2 = (tfnASI_RSAPrivateKeyOpFn *) DSO_bind_func(atalla_dso, ATALLA_F2))
|| !(p3 =
(tfnASI_GetPerformanceStatistics *) DSO_bind_func(atalla_dso,
ATALLA_F3))) {
ATALLAerr(ATALLA_F_ATALLA_INIT, ATALLA_R_NOT_LOADED);
goto err;
}
/* Copy the pointers */
p_Atalla_GetHardwareConfig = p1;
p_Atalla_RSAPrivateKeyOpFn = p2;
p_Atalla_GetPerformanceStatistics = p3;
/*
* Perform a basic test to see if there's actually any unit running.
*/
if (p1(0L, config_buf) != 0) {
ATALLAerr(ATALLA_F_ATALLA_INIT, ATALLA_R_UNIT_FAILURE);
goto err;
}
/* Everything's fine. */
return 1;
err:
if (atalla_dso)
DSO_free(atalla_dso);
atalla_dso = NULL;
p_Atalla_GetHardwareConfig = NULL;
p_Atalla_RSAPrivateKeyOpFn = NULL;
p_Atalla_GetPerformanceStatistics = NULL;
return 0;
}
static int atalla_finish(ENGINE *e)
{
free_ATALLA_LIBNAME();
if (atalla_dso == NULL) {
ATALLAerr(ATALLA_F_ATALLA_FINISH, ATALLA_R_NOT_LOADED);
return 0;
}
if (!DSO_free(atalla_dso)) {
ATALLAerr(ATALLA_F_ATALLA_FINISH, ATALLA_R_UNIT_FAILURE);
return 0;
}
atalla_dso = NULL;
p_Atalla_GetHardwareConfig = NULL;
p_Atalla_RSAPrivateKeyOpFn = NULL;
p_Atalla_GetPerformanceStatistics = NULL;
return 1;
}
static int atalla_ctrl(ENGINE *e, int cmd, long i, void *p, void (*f) (void))
{
int initialised = ((atalla_dso == NULL) ? 0 : 1);
switch (cmd) {
case ATALLA_CMD_SO_PATH:
if (p == NULL) {
ATALLAerr(ATALLA_F_ATALLA_CTRL, ERR_R_PASSED_NULL_PARAMETER);
return 0;
}
if (initialised) {
ATALLAerr(ATALLA_F_ATALLA_CTRL, ATALLA_R_ALREADY_LOADED);
return 0;
}
return set_ATALLA_LIBNAME((const char *)p);
default:
break;
}
ATALLAerr(ATALLA_F_ATALLA_CTRL, ATALLA_R_CTRL_COMMAND_NOT_IMPLEMENTED);
return 0;
}
static int atalla_mod_exp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p,
const BIGNUM *m, BN_CTX *ctx)
{
/*
* I need somewhere to store temporary serialised values for use with the
* Atalla API calls. A neat cheat - I'll use BIGNUMs from the BN_CTX but
* access their arrays directly as byte arrays <grin>. This way I don't
* have to clean anything up.
*/
BIGNUM *modulus;
BIGNUM *exponent;
BIGNUM *argument;
BIGNUM *result;
RSAPrivateKey keydata;
int to_return, numbytes;
modulus = exponent = argument = result = NULL;
to_return = 0; /* expect failure */
if (!atalla_dso) {
ATALLAerr(ATALLA_F_ATALLA_MOD_EXP, ATALLA_R_NOT_LOADED);
goto err;
}
/* Prepare the params */
BN_CTX_start(ctx);
modulus = BN_CTX_get(ctx);
exponent = BN_CTX_get(ctx);
argument = BN_CTX_get(ctx);
result = BN_CTX_get(ctx);
if (!result) {
ATALLAerr(ATALLA_F_ATALLA_MOD_EXP, ATALLA_R_BN_CTX_FULL);
goto err;
}
if (!bn_wexpand(modulus, m->top) || !bn_wexpand(exponent, m->top) ||
!bn_wexpand(argument, m->top) || !bn_wexpand(result, m->top)) {
ATALLAerr(ATALLA_F_ATALLA_MOD_EXP, ATALLA_R_BN_EXPAND_FAIL);
goto err;
}
/* Prepare the key-data */
- memset(&keydata, 0, sizeof keydata);
+ memset(&keydata, 0, sizeof(keydata));
numbytes = BN_num_bytes(m);
memset(exponent->d, 0, numbytes);
memset(modulus->d, 0, numbytes);
BN_bn2bin(p, (unsigned char *)exponent->d + numbytes - BN_num_bytes(p));
BN_bn2bin(m, (unsigned char *)modulus->d + numbytes - BN_num_bytes(m));
keydata.privateExponent.data = (unsigned char *)exponent->d;
keydata.privateExponent.len = numbytes;
keydata.modulus.data = (unsigned char *)modulus->d;
keydata.modulus.len = numbytes;
/* Prepare the argument */
memset(argument->d, 0, numbytes);
memset(result->d, 0, numbytes);
BN_bn2bin(a, (unsigned char *)argument->d + numbytes - BN_num_bytes(a));
/* Perform the operation */
if (p_Atalla_RSAPrivateKeyOpFn(&keydata, (unsigned char *)result->d,
(unsigned char *)argument->d,
keydata.modulus.len) != 0) {
ATALLAerr(ATALLA_F_ATALLA_MOD_EXP, ATALLA_R_REQUEST_FAILED);
goto err;
}
/* Convert the response */
BN_bin2bn((unsigned char *)result->d, numbytes, r);
to_return = 1;
err:
BN_CTX_end(ctx);
return to_return;
}
# ifndef OPENSSL_NO_RSA
static int atalla_rsa_mod_exp(BIGNUM *r0, const BIGNUM *I, RSA *rsa,
BN_CTX *ctx)
{
int to_return = 0;
if (!atalla_dso) {
ATALLAerr(ATALLA_F_ATALLA_RSA_MOD_EXP, ATALLA_R_NOT_LOADED);
goto err;
}
if (!rsa->d || !rsa->n) {
ATALLAerr(ATALLA_F_ATALLA_RSA_MOD_EXP,
ATALLA_R_MISSING_KEY_COMPONENTS);
goto err;
}
to_return = atalla_mod_exp(r0, I, rsa->d, rsa->n, ctx);
err:
return to_return;
}
# endif
# ifndef OPENSSL_NO_DSA
/*
* This code was liberated and adapted from the commented-out code in
* dsa_ossl.c. Because of the unoptimised form of the Atalla acceleration (it
* doesn't have a CRT form for RSA), this function means that an Atalla
* system running with a DSA server certificate can handshake around 5 or 6
* times faster/more than an equivalent system running with RSA. Just check
* out the "signs" statistics from the RSA and DSA parts of "openssl speed
* -engine atalla dsa1024 rsa1024".
*/
static int atalla_dsa_mod_exp(DSA *dsa, BIGNUM *rr, BIGNUM *a1,
BIGNUM *p1, BIGNUM *a2, BIGNUM *p2, BIGNUM *m,
BN_CTX *ctx, BN_MONT_CTX *in_mont)
{
BIGNUM t;
int to_return = 0;
BN_init(&t);
/* let rr = a1 ^ p1 mod m */
if (!atalla_mod_exp(rr, a1, p1, m, ctx))
goto end;
/* let t = a2 ^ p2 mod m */
if (!atalla_mod_exp(&t, a2, p2, m, ctx))
goto end;
/* let rr = rr * t mod m */
if (!BN_mod_mul(rr, rr, &t, m, ctx))
goto end;
to_return = 1;
end:
BN_free(&t);
return to_return;
}
static int atalla_mod_exp_dsa(DSA *dsa, BIGNUM *r, BIGNUM *a,
const BIGNUM *p, const BIGNUM *m, BN_CTX *ctx,
BN_MONT_CTX *m_ctx)
{
return atalla_mod_exp(r, a, p, m, ctx);
}
# endif
# ifndef OPENSSL_NO_RSA
/* This function is aliased to mod_exp (with the mont stuff dropped). */
static int atalla_mod_exp_mont(BIGNUM *r, const BIGNUM *a, const BIGNUM *p,
const BIGNUM *m, BN_CTX *ctx,
BN_MONT_CTX *m_ctx)
{
return atalla_mod_exp(r, a, p, m, ctx);
}
# endif
# ifndef OPENSSL_NO_DH
/* This function is aliased to mod_exp (with the dh and mont dropped). */
static int atalla_mod_exp_dh(const DH *dh, BIGNUM *r,
const BIGNUM *a, const BIGNUM *p,
const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *m_ctx)
{
return atalla_mod_exp(r, a, p, m, ctx);
}
# endif
/*
* This stuff is needed if this ENGINE is being compiled into a
* self-contained shared-library.
*/
# ifndef OPENSSL_NO_DYNAMIC_ENGINE
static int bind_fn(ENGINE *e, const char *id)
{
if (id && (strcmp(id, engine_atalla_id) != 0))
return 0;
if (!bind_helper(e))
return 0;
return 1;
}
IMPLEMENT_DYNAMIC_CHECK_FN()
IMPLEMENT_DYNAMIC_BIND_FN(bind_fn)
# endif /* OPENSSL_NO_DYNAMIC_ENGINE */
# endif /* !OPENSSL_NO_HW_ATALLA */
#endif /* !OPENSSL_NO_HW */
diff --git a/ssl/Makefile b/ssl/Makefile
index 7866a3ccd77b..b0a4ee8577c8 100644
--- a/ssl/Makefile
+++ b/ssl/Makefile
@@ -1,1124 +1,1124 @@
#
# OpenSSL/ssl/Makefile
#
DIR= ssl
TOP= ..
CC= cc
INCLUDES= -I../crypto -I$(TOP) -I../include $(KRB5_INCLUDES)
CFLAG=-g
MAKEFILE= Makefile
AR= ar r
# KRB5 stuff
KRB5_INCLUDES=
CFLAGS= $(INCLUDES) $(CFLAG)
GENERAL=Makefile README ssl-lib.com install.com
TEST=ssltest.c heartbeat_test.c clienthellotest.c sslv2conftest.c dtlstest.c \
bad_dtls_test.c fatalerrtest.c
APPS=
LIB=$(TOP)/libssl.a
SHARED_LIB= libssl$(SHLIB_EXT)
LIBSRC= \
s2_meth.c s2_srvr.c s2_clnt.c s2_lib.c s2_enc.c s2_pkt.c \
s3_meth.c s3_srvr.c s3_clnt.c s3_lib.c s3_enc.c s3_pkt.c s3_both.c s3_cbc.c \
s23_meth.c s23_srvr.c s23_clnt.c s23_lib.c s23_pkt.c \
t1_meth.c t1_srvr.c t1_clnt.c t1_lib.c t1_enc.c t1_ext.c \
d1_meth.c d1_srvr.c d1_clnt.c d1_lib.c d1_pkt.c \
d1_both.c d1_srtp.c \
ssl_lib.c ssl_err2.c ssl_cert.c ssl_sess.c \
ssl_ciph.c ssl_stat.c ssl_rsa.c \
ssl_asn1.c ssl_txt.c ssl_algs.c ssl_conf.c \
bio_ssl.c ssl_err.c kssl.c t1_reneg.c tls_srp.c t1_trce.c ssl_utst.c
LIBOBJ= \
s2_meth.o s2_srvr.o s2_clnt.o s2_lib.o s2_enc.o s2_pkt.o \
s3_meth.o s3_srvr.o s3_clnt.o s3_lib.o s3_enc.o s3_pkt.o s3_both.o s3_cbc.o \
s23_meth.o s23_srvr.o s23_clnt.o s23_lib.o s23_pkt.o \
t1_meth.o t1_srvr.o t1_clnt.o t1_lib.o t1_enc.o t1_ext.o \
d1_meth.o d1_srvr.o d1_clnt.o d1_lib.o d1_pkt.o \
d1_both.o d1_srtp.o\
ssl_lib.o ssl_err2.o ssl_cert.o ssl_sess.o \
ssl_ciph.o ssl_stat.o ssl_rsa.o \
ssl_asn1.o ssl_txt.o ssl_algs.o ssl_conf.o \
bio_ssl.o ssl_err.o kssl.o t1_reneg.o tls_srp.o t1_trce.o ssl_utst.o
SRC= $(LIBSRC)
EXHEADER= ssl.h ssl2.h ssl3.h ssl23.h tls1.h dtls1.h kssl.h srtp.h
HEADER= $(EXHEADER) ssl_locl.h kssl_lcl.h
ALL= $(GENERAL) $(SRC) $(HEADER)
top:
(cd ..; $(MAKE) DIRS=$(DIR) all)
all: shared
lib: $(LIBOBJ)
$(AR) $(LIB) $(LIBOBJ)
$(RANLIB) $(LIB) || echo Never mind.
@touch lib
shared: lib
if [ -n "$(SHARED_LIBS)" ]; then \
(cd ..; $(MAKE) $(SHARED_LIB)); \
fi
files:
$(PERL) $(TOP)/util/files.pl Makefile >> $(TOP)/MINFO
links:
@$(PERL) $(TOP)/util/mklink.pl ../include/openssl $(EXHEADER)
@$(PERL) $(TOP)/util/mklink.pl ../test $(TEST)
@$(PERL) $(TOP)/util/mklink.pl ../apps $(APPS)
install:
@[ -n "$(INSTALLTOP)" ] # should be set by top Makefile...
@headerlist="$(EXHEADER)"; for i in $$headerlist ; \
do \
(cp $$i $(INSTALL_PREFIX)$(INSTALLTOP)/include/openssl/$$i; \
chmod 644 $(INSTALL_PREFIX)$(INSTALLTOP)/include/openssl/$$i ); \
done;
tags:
ctags $(SRC)
tests:
lint:
lint -DLINT $(INCLUDES) $(SRC)>fluff
update: local_depend
@if [ -z "$(THIS)" ]; then $(MAKE) -f $(TOP)/Makefile reflect THIS=$@; fi
depend: local_depend
@if [ -z "$(THIS)" ]; then $(MAKE) -f $(TOP)/Makefile reflect THIS=$@; fi
local_depend:
@[ -z "$(THIS)" ] || $(MAKEDEPEND) -- $(CFLAG) $(INCLUDES) $(DEPFLAG) -- $(PROGS) $(LIBSRC)
dclean:
$(PERL) -pe 'if (/^# DO NOT DELETE THIS LINE/) {print; exit(0);}' $(MAKEFILE) >Makefile.new
mv -f Makefile.new $(MAKEFILE)
clean:
rm -f *.o *.obj lib tags core .pure .nfs* *.old *.bak fluff
# DO NOT DELETE THIS LINE -- make depend depends on it.
bio_ssl.o: ../include/openssl/asn1.h ../include/openssl/bio.h
bio_ssl.o: ../include/openssl/buffer.h ../include/openssl/comp.h
bio_ssl.o: ../include/openssl/crypto.h ../include/openssl/dtls1.h
bio_ssl.o: ../include/openssl/e_os2.h ../include/openssl/ec.h
bio_ssl.o: ../include/openssl/ecdh.h ../include/openssl/ecdsa.h
bio_ssl.o: ../include/openssl/err.h ../include/openssl/evp.h
bio_ssl.o: ../include/openssl/hmac.h ../include/openssl/kssl.h
bio_ssl.o: ../include/openssl/lhash.h ../include/openssl/obj_mac.h
bio_ssl.o: ../include/openssl/objects.h ../include/openssl/opensslconf.h
bio_ssl.o: ../include/openssl/opensslv.h ../include/openssl/ossl_typ.h
bio_ssl.o: ../include/openssl/pem.h ../include/openssl/pem2.h
bio_ssl.o: ../include/openssl/pkcs7.h ../include/openssl/pqueue.h
bio_ssl.o: ../include/openssl/safestack.h ../include/openssl/sha.h
bio_ssl.o: ../include/openssl/srtp.h ../include/openssl/ssl.h
bio_ssl.o: ../include/openssl/ssl2.h ../include/openssl/ssl23.h
bio_ssl.o: ../include/openssl/ssl3.h ../include/openssl/stack.h
bio_ssl.o: ../include/openssl/symhacks.h ../include/openssl/tls1.h
bio_ssl.o: ../include/openssl/x509.h ../include/openssl/x509_vfy.h bio_ssl.c
d1_both.o: ../e_os.h ../include/openssl/asn1.h ../include/openssl/bio.h
d1_both.o: ../include/openssl/buffer.h ../include/openssl/comp.h
d1_both.o: ../include/openssl/crypto.h ../include/openssl/dsa.h
d1_both.o: ../include/openssl/dtls1.h ../include/openssl/e_os2.h
d1_both.o: ../include/openssl/ec.h ../include/openssl/ecdh.h
d1_both.o: ../include/openssl/ecdsa.h ../include/openssl/err.h
d1_both.o: ../include/openssl/evp.h ../include/openssl/hmac.h
d1_both.o: ../include/openssl/kssl.h ../include/openssl/lhash.h
d1_both.o: ../include/openssl/obj_mac.h ../include/openssl/objects.h
d1_both.o: ../include/openssl/opensslconf.h ../include/openssl/opensslv.h
d1_both.o: ../include/openssl/ossl_typ.h ../include/openssl/pem.h
d1_both.o: ../include/openssl/pem2.h ../include/openssl/pkcs7.h
d1_both.o: ../include/openssl/pqueue.h ../include/openssl/rand.h
d1_both.o: ../include/openssl/rsa.h ../include/openssl/safestack.h
d1_both.o: ../include/openssl/sha.h ../include/openssl/srtp.h
d1_both.o: ../include/openssl/ssl.h ../include/openssl/ssl2.h
d1_both.o: ../include/openssl/ssl23.h ../include/openssl/ssl3.h
d1_both.o: ../include/openssl/stack.h ../include/openssl/symhacks.h
d1_both.o: ../include/openssl/tls1.h ../include/openssl/x509.h
d1_both.o: ../include/openssl/x509_vfy.h d1_both.c ssl_locl.h
d1_clnt.o: ../e_os.h ../include/openssl/asn1.h ../include/openssl/bio.h
d1_clnt.o: ../include/openssl/bn.h ../include/openssl/buffer.h
d1_clnt.o: ../include/openssl/comp.h ../include/openssl/crypto.h
d1_clnt.o: ../include/openssl/dh.h ../include/openssl/dsa.h
d1_clnt.o: ../include/openssl/dtls1.h ../include/openssl/e_os2.h
d1_clnt.o: ../include/openssl/ec.h ../include/openssl/ecdh.h
d1_clnt.o: ../include/openssl/ecdsa.h ../include/openssl/err.h
d1_clnt.o: ../include/openssl/evp.h ../include/openssl/hmac.h
d1_clnt.o: ../include/openssl/kssl.h ../include/openssl/lhash.h
d1_clnt.o: ../include/openssl/md5.h ../include/openssl/obj_mac.h
d1_clnt.o: ../include/openssl/objects.h ../include/openssl/opensslconf.h
d1_clnt.o: ../include/openssl/opensslv.h ../include/openssl/ossl_typ.h
d1_clnt.o: ../include/openssl/pem.h ../include/openssl/pem2.h
d1_clnt.o: ../include/openssl/pkcs7.h ../include/openssl/pqueue.h
d1_clnt.o: ../include/openssl/rand.h ../include/openssl/rsa.h
d1_clnt.o: ../include/openssl/safestack.h ../include/openssl/sha.h
d1_clnt.o: ../include/openssl/srtp.h ../include/openssl/ssl.h
d1_clnt.o: ../include/openssl/ssl2.h ../include/openssl/ssl23.h
d1_clnt.o: ../include/openssl/ssl3.h ../include/openssl/stack.h
d1_clnt.o: ../include/openssl/symhacks.h ../include/openssl/tls1.h
d1_clnt.o: ../include/openssl/x509.h ../include/openssl/x509_vfy.h d1_clnt.c
d1_clnt.o: kssl_lcl.h ssl_locl.h
d1_lib.o: ../e_os.h ../include/openssl/asn1.h ../include/openssl/bio.h
d1_lib.o: ../include/openssl/buffer.h ../include/openssl/comp.h
d1_lib.o: ../include/openssl/crypto.h ../include/openssl/dsa.h
d1_lib.o: ../include/openssl/dtls1.h ../include/openssl/e_os2.h
d1_lib.o: ../include/openssl/ec.h ../include/openssl/ecdh.h
d1_lib.o: ../include/openssl/ecdsa.h ../include/openssl/err.h
d1_lib.o: ../include/openssl/evp.h ../include/openssl/hmac.h
d1_lib.o: ../include/openssl/kssl.h ../include/openssl/lhash.h
d1_lib.o: ../include/openssl/obj_mac.h ../include/openssl/objects.h
d1_lib.o: ../include/openssl/opensslconf.h ../include/openssl/opensslv.h
d1_lib.o: ../include/openssl/ossl_typ.h ../include/openssl/pem.h
d1_lib.o: ../include/openssl/pem2.h ../include/openssl/pkcs7.h
d1_lib.o: ../include/openssl/pqueue.h ../include/openssl/rsa.h
d1_lib.o: ../include/openssl/safestack.h ../include/openssl/sha.h
d1_lib.o: ../include/openssl/srtp.h ../include/openssl/ssl.h
d1_lib.o: ../include/openssl/ssl2.h ../include/openssl/ssl23.h
d1_lib.o: ../include/openssl/ssl3.h ../include/openssl/stack.h
d1_lib.o: ../include/openssl/symhacks.h ../include/openssl/tls1.h
d1_lib.o: ../include/openssl/x509.h ../include/openssl/x509_vfy.h d1_lib.c
d1_lib.o: ssl_locl.h
d1_meth.o: ../e_os.h ../include/openssl/asn1.h ../include/openssl/bio.h
d1_meth.o: ../include/openssl/buffer.h ../include/openssl/comp.h
d1_meth.o: ../include/openssl/crypto.h ../include/openssl/dsa.h
d1_meth.o: ../include/openssl/dtls1.h ../include/openssl/e_os2.h
d1_meth.o: ../include/openssl/ec.h ../include/openssl/ecdh.h
d1_meth.o: ../include/openssl/ecdsa.h ../include/openssl/err.h
d1_meth.o: ../include/openssl/evp.h ../include/openssl/hmac.h
d1_meth.o: ../include/openssl/kssl.h ../include/openssl/lhash.h
d1_meth.o: ../include/openssl/obj_mac.h ../include/openssl/objects.h
d1_meth.o: ../include/openssl/opensslconf.h ../include/openssl/opensslv.h
d1_meth.o: ../include/openssl/ossl_typ.h ../include/openssl/pem.h
d1_meth.o: ../include/openssl/pem2.h ../include/openssl/pkcs7.h
d1_meth.o: ../include/openssl/pqueue.h ../include/openssl/rsa.h
d1_meth.o: ../include/openssl/safestack.h ../include/openssl/sha.h
d1_meth.o: ../include/openssl/srtp.h ../include/openssl/ssl.h
d1_meth.o: ../include/openssl/ssl2.h ../include/openssl/ssl23.h
d1_meth.o: ../include/openssl/ssl3.h ../include/openssl/stack.h
d1_meth.o: ../include/openssl/symhacks.h ../include/openssl/tls1.h
d1_meth.o: ../include/openssl/x509.h ../include/openssl/x509_vfy.h d1_meth.c
d1_meth.o: ssl_locl.h
d1_pkt.o: ../e_os.h ../include/openssl/asn1.h ../include/openssl/bio.h
d1_pkt.o: ../include/openssl/buffer.h ../include/openssl/comp.h
d1_pkt.o: ../include/openssl/crypto.h ../include/openssl/dsa.h
d1_pkt.o: ../include/openssl/dtls1.h ../include/openssl/e_os2.h
d1_pkt.o: ../include/openssl/ec.h ../include/openssl/ecdh.h
d1_pkt.o: ../include/openssl/ecdsa.h ../include/openssl/err.h
d1_pkt.o: ../include/openssl/evp.h ../include/openssl/hmac.h
d1_pkt.o: ../include/openssl/kssl.h ../include/openssl/lhash.h
d1_pkt.o: ../include/openssl/obj_mac.h ../include/openssl/objects.h
d1_pkt.o: ../include/openssl/opensslconf.h ../include/openssl/opensslv.h
d1_pkt.o: ../include/openssl/ossl_typ.h ../include/openssl/pem.h
d1_pkt.o: ../include/openssl/pem2.h ../include/openssl/pkcs7.h
d1_pkt.o: ../include/openssl/pqueue.h ../include/openssl/rand.h
d1_pkt.o: ../include/openssl/rsa.h ../include/openssl/safestack.h
d1_pkt.o: ../include/openssl/sha.h ../include/openssl/srtp.h
d1_pkt.o: ../include/openssl/ssl.h ../include/openssl/ssl2.h
d1_pkt.o: ../include/openssl/ssl23.h ../include/openssl/ssl3.h
d1_pkt.o: ../include/openssl/stack.h ../include/openssl/symhacks.h
d1_pkt.o: ../include/openssl/tls1.h ../include/openssl/x509.h
d1_pkt.o: ../include/openssl/x509_vfy.h d1_pkt.c ssl_locl.h
d1_srtp.o: ../e_os.h ../include/openssl/asn1.h ../include/openssl/bio.h
d1_srtp.o: ../include/openssl/buffer.h ../include/openssl/comp.h
d1_srtp.o: ../include/openssl/crypto.h ../include/openssl/dsa.h
d1_srtp.o: ../include/openssl/dtls1.h ../include/openssl/e_os2.h
d1_srtp.o: ../include/openssl/ec.h ../include/openssl/ecdh.h
d1_srtp.o: ../include/openssl/ecdsa.h ../include/openssl/err.h
d1_srtp.o: ../include/openssl/evp.h ../include/openssl/hmac.h
d1_srtp.o: ../include/openssl/kssl.h ../include/openssl/lhash.h
d1_srtp.o: ../include/openssl/obj_mac.h ../include/openssl/objects.h
d1_srtp.o: ../include/openssl/opensslconf.h ../include/openssl/opensslv.h
d1_srtp.o: ../include/openssl/ossl_typ.h ../include/openssl/pem.h
d1_srtp.o: ../include/openssl/pem2.h ../include/openssl/pkcs7.h
d1_srtp.o: ../include/openssl/pqueue.h ../include/openssl/rsa.h
d1_srtp.o: ../include/openssl/safestack.h ../include/openssl/sha.h
d1_srtp.o: ../include/openssl/srtp.h ../include/openssl/ssl.h
d1_srtp.o: ../include/openssl/ssl2.h ../include/openssl/ssl23.h
d1_srtp.o: ../include/openssl/ssl3.h ../include/openssl/stack.h
d1_srtp.o: ../include/openssl/symhacks.h ../include/openssl/tls1.h
d1_srtp.o: ../include/openssl/x509.h ../include/openssl/x509_vfy.h d1_srtp.c
d1_srtp.o: srtp.h ssl_locl.h
d1_srvr.o: ../e_os.h ../include/openssl/asn1.h ../include/openssl/bio.h
d1_srvr.o: ../include/openssl/bn.h ../include/openssl/buffer.h
d1_srvr.o: ../include/openssl/comp.h ../include/openssl/crypto.h
d1_srvr.o: ../include/openssl/dh.h ../include/openssl/dsa.h
d1_srvr.o: ../include/openssl/dtls1.h ../include/openssl/e_os2.h
d1_srvr.o: ../include/openssl/ec.h ../include/openssl/ecdh.h
d1_srvr.o: ../include/openssl/ecdsa.h ../include/openssl/err.h
d1_srvr.o: ../include/openssl/evp.h ../include/openssl/hmac.h
d1_srvr.o: ../include/openssl/kssl.h ../include/openssl/lhash.h
d1_srvr.o: ../include/openssl/md5.h ../include/openssl/obj_mac.h
d1_srvr.o: ../include/openssl/objects.h ../include/openssl/opensslconf.h
d1_srvr.o: ../include/openssl/opensslv.h ../include/openssl/ossl_typ.h
d1_srvr.o: ../include/openssl/pem.h ../include/openssl/pem2.h
d1_srvr.o: ../include/openssl/pkcs7.h ../include/openssl/pqueue.h
d1_srvr.o: ../include/openssl/rand.h ../include/openssl/rsa.h
d1_srvr.o: ../include/openssl/safestack.h ../include/openssl/sha.h
d1_srvr.o: ../include/openssl/srtp.h ../include/openssl/ssl.h
d1_srvr.o: ../include/openssl/ssl2.h ../include/openssl/ssl23.h
d1_srvr.o: ../include/openssl/ssl3.h ../include/openssl/stack.h
d1_srvr.o: ../include/openssl/symhacks.h ../include/openssl/tls1.h
d1_srvr.o: ../include/openssl/x509.h ../include/openssl/x509_vfy.h d1_srvr.c
d1_srvr.o: ssl_locl.h
-kssl.o: ../include/openssl/asn1.h ../include/openssl/bio.h
+kssl.o: ../crypto/o_time.h ../include/openssl/asn1.h ../include/openssl/bio.h
kssl.o: ../include/openssl/buffer.h ../include/openssl/comp.h
kssl.o: ../include/openssl/crypto.h ../include/openssl/dtls1.h
kssl.o: ../include/openssl/e_os2.h ../include/openssl/ec.h
kssl.o: ../include/openssl/ecdh.h ../include/openssl/ecdsa.h
kssl.o: ../include/openssl/evp.h ../include/openssl/hmac.h
kssl.o: ../include/openssl/krb5_asn.h ../include/openssl/kssl.h
kssl.o: ../include/openssl/lhash.h ../include/openssl/obj_mac.h
kssl.o: ../include/openssl/objects.h ../include/openssl/opensslconf.h
kssl.o: ../include/openssl/opensslv.h ../include/openssl/ossl_typ.h
kssl.o: ../include/openssl/pem.h ../include/openssl/pem2.h
kssl.o: ../include/openssl/pkcs7.h ../include/openssl/pqueue.h
kssl.o: ../include/openssl/safestack.h ../include/openssl/sha.h
kssl.o: ../include/openssl/srtp.h ../include/openssl/ssl.h
kssl.o: ../include/openssl/ssl2.h ../include/openssl/ssl23.h
kssl.o: ../include/openssl/ssl3.h ../include/openssl/stack.h
kssl.o: ../include/openssl/symhacks.h ../include/openssl/tls1.h
kssl.o: ../include/openssl/x509.h ../include/openssl/x509_vfy.h kssl.c
kssl.o: kssl_lcl.h
s23_clnt.o: ../e_os.h ../include/openssl/asn1.h ../include/openssl/bio.h
s23_clnt.o: ../include/openssl/buffer.h ../include/openssl/comp.h
s23_clnt.o: ../include/openssl/crypto.h ../include/openssl/dsa.h
s23_clnt.o: ../include/openssl/dtls1.h ../include/openssl/e_os2.h
s23_clnt.o: ../include/openssl/ec.h ../include/openssl/ecdh.h
s23_clnt.o: ../include/openssl/ecdsa.h ../include/openssl/err.h
s23_clnt.o: ../include/openssl/evp.h ../include/openssl/hmac.h
s23_clnt.o: ../include/openssl/kssl.h ../include/openssl/lhash.h
s23_clnt.o: ../include/openssl/obj_mac.h ../include/openssl/objects.h
s23_clnt.o: ../include/openssl/opensslconf.h ../include/openssl/opensslv.h
s23_clnt.o: ../include/openssl/ossl_typ.h ../include/openssl/pem.h
s23_clnt.o: ../include/openssl/pem2.h ../include/openssl/pkcs7.h
s23_clnt.o: ../include/openssl/pqueue.h ../include/openssl/rand.h
s23_clnt.o: ../include/openssl/rsa.h ../include/openssl/safestack.h
s23_clnt.o: ../include/openssl/sha.h ../include/openssl/srtp.h
s23_clnt.o: ../include/openssl/ssl.h ../include/openssl/ssl2.h
s23_clnt.o: ../include/openssl/ssl23.h ../include/openssl/ssl3.h
s23_clnt.o: ../include/openssl/stack.h ../include/openssl/symhacks.h
s23_clnt.o: ../include/openssl/tls1.h ../include/openssl/x509.h
s23_clnt.o: ../include/openssl/x509_vfy.h s23_clnt.c ssl_locl.h
s23_lib.o: ../e_os.h ../include/openssl/asn1.h ../include/openssl/bio.h
s23_lib.o: ../include/openssl/buffer.h ../include/openssl/comp.h
s23_lib.o: ../include/openssl/crypto.h ../include/openssl/dsa.h
s23_lib.o: ../include/openssl/dtls1.h ../include/openssl/e_os2.h
s23_lib.o: ../include/openssl/ec.h ../include/openssl/ecdh.h
s23_lib.o: ../include/openssl/ecdsa.h ../include/openssl/err.h
s23_lib.o: ../include/openssl/evp.h ../include/openssl/hmac.h
s23_lib.o: ../include/openssl/kssl.h ../include/openssl/lhash.h
s23_lib.o: ../include/openssl/obj_mac.h ../include/openssl/objects.h
s23_lib.o: ../include/openssl/opensslconf.h ../include/openssl/opensslv.h
s23_lib.o: ../include/openssl/ossl_typ.h ../include/openssl/pem.h
s23_lib.o: ../include/openssl/pem2.h ../include/openssl/pkcs7.h
s23_lib.o: ../include/openssl/pqueue.h ../include/openssl/rsa.h
s23_lib.o: ../include/openssl/safestack.h ../include/openssl/sha.h
s23_lib.o: ../include/openssl/srtp.h ../include/openssl/ssl.h
s23_lib.o: ../include/openssl/ssl2.h ../include/openssl/ssl23.h
s23_lib.o: ../include/openssl/ssl3.h ../include/openssl/stack.h
s23_lib.o: ../include/openssl/symhacks.h ../include/openssl/tls1.h
s23_lib.o: ../include/openssl/x509.h ../include/openssl/x509_vfy.h s23_lib.c
s23_lib.o: ssl_locl.h
s23_meth.o: ../e_os.h ../include/openssl/asn1.h ../include/openssl/bio.h
s23_meth.o: ../include/openssl/buffer.h ../include/openssl/comp.h
s23_meth.o: ../include/openssl/crypto.h ../include/openssl/dsa.h
s23_meth.o: ../include/openssl/dtls1.h ../include/openssl/e_os2.h
s23_meth.o: ../include/openssl/ec.h ../include/openssl/ecdh.h
s23_meth.o: ../include/openssl/ecdsa.h ../include/openssl/err.h
s23_meth.o: ../include/openssl/evp.h ../include/openssl/hmac.h
s23_meth.o: ../include/openssl/kssl.h ../include/openssl/lhash.h
s23_meth.o: ../include/openssl/obj_mac.h ../include/openssl/objects.h
s23_meth.o: ../include/openssl/opensslconf.h ../include/openssl/opensslv.h
s23_meth.o: ../include/openssl/ossl_typ.h ../include/openssl/pem.h
s23_meth.o: ../include/openssl/pem2.h ../include/openssl/pkcs7.h
s23_meth.o: ../include/openssl/pqueue.h ../include/openssl/rsa.h
s23_meth.o: ../include/openssl/safestack.h ../include/openssl/sha.h
s23_meth.o: ../include/openssl/srtp.h ../include/openssl/ssl.h
s23_meth.o: ../include/openssl/ssl2.h ../include/openssl/ssl23.h
s23_meth.o: ../include/openssl/ssl3.h ../include/openssl/stack.h
s23_meth.o: ../include/openssl/symhacks.h ../include/openssl/tls1.h
s23_meth.o: ../include/openssl/x509.h ../include/openssl/x509_vfy.h s23_meth.c
s23_meth.o: ssl_locl.h
s23_pkt.o: ../e_os.h ../include/openssl/asn1.h ../include/openssl/bio.h
s23_pkt.o: ../include/openssl/buffer.h ../include/openssl/comp.h
s23_pkt.o: ../include/openssl/crypto.h ../include/openssl/dsa.h
s23_pkt.o: ../include/openssl/dtls1.h ../include/openssl/e_os2.h
s23_pkt.o: ../include/openssl/ec.h ../include/openssl/ecdh.h
s23_pkt.o: ../include/openssl/ecdsa.h ../include/openssl/err.h
s23_pkt.o: ../include/openssl/evp.h ../include/openssl/hmac.h
s23_pkt.o: ../include/openssl/kssl.h ../include/openssl/lhash.h
s23_pkt.o: ../include/openssl/obj_mac.h ../include/openssl/objects.h
s23_pkt.o: ../include/openssl/opensslconf.h ../include/openssl/opensslv.h
s23_pkt.o: ../include/openssl/ossl_typ.h ../include/openssl/pem.h
s23_pkt.o: ../include/openssl/pem2.h ../include/openssl/pkcs7.h
s23_pkt.o: ../include/openssl/pqueue.h ../include/openssl/rsa.h
s23_pkt.o: ../include/openssl/safestack.h ../include/openssl/sha.h
s23_pkt.o: ../include/openssl/srtp.h ../include/openssl/ssl.h
s23_pkt.o: ../include/openssl/ssl2.h ../include/openssl/ssl23.h
s23_pkt.o: ../include/openssl/ssl3.h ../include/openssl/stack.h
s23_pkt.o: ../include/openssl/symhacks.h ../include/openssl/tls1.h
s23_pkt.o: ../include/openssl/x509.h ../include/openssl/x509_vfy.h s23_pkt.c
s23_pkt.o: ssl_locl.h
s23_srvr.o: ../e_os.h ../include/openssl/asn1.h ../include/openssl/bio.h
s23_srvr.o: ../include/openssl/buffer.h ../include/openssl/comp.h
s23_srvr.o: ../include/openssl/crypto.h ../include/openssl/dsa.h
s23_srvr.o: ../include/openssl/dtls1.h ../include/openssl/e_os2.h
s23_srvr.o: ../include/openssl/ec.h ../include/openssl/ecdh.h
s23_srvr.o: ../include/openssl/ecdsa.h ../include/openssl/err.h
s23_srvr.o: ../include/openssl/evp.h ../include/openssl/hmac.h
s23_srvr.o: ../include/openssl/kssl.h ../include/openssl/lhash.h
s23_srvr.o: ../include/openssl/obj_mac.h ../include/openssl/objects.h
s23_srvr.o: ../include/openssl/opensslconf.h ../include/openssl/opensslv.h
s23_srvr.o: ../include/openssl/ossl_typ.h ../include/openssl/pem.h
s23_srvr.o: ../include/openssl/pem2.h ../include/openssl/pkcs7.h
s23_srvr.o: ../include/openssl/pqueue.h ../include/openssl/rand.h
s23_srvr.o: ../include/openssl/rsa.h ../include/openssl/safestack.h
s23_srvr.o: ../include/openssl/sha.h ../include/openssl/srtp.h
s23_srvr.o: ../include/openssl/ssl.h ../include/openssl/ssl2.h
s23_srvr.o: ../include/openssl/ssl23.h ../include/openssl/ssl3.h
s23_srvr.o: ../include/openssl/stack.h ../include/openssl/symhacks.h
s23_srvr.o: ../include/openssl/tls1.h ../include/openssl/x509.h
s23_srvr.o: ../include/openssl/x509_vfy.h s23_srvr.c ssl_locl.h
s2_clnt.o: ../e_os.h ../include/openssl/asn1.h ../include/openssl/bio.h
s2_clnt.o: ../include/openssl/buffer.h ../include/openssl/comp.h
s2_clnt.o: ../include/openssl/crypto.h ../include/openssl/dsa.h
s2_clnt.o: ../include/openssl/dtls1.h ../include/openssl/e_os2.h
s2_clnt.o: ../include/openssl/ec.h ../include/openssl/ecdh.h
s2_clnt.o: ../include/openssl/ecdsa.h ../include/openssl/err.h
s2_clnt.o: ../include/openssl/evp.h ../include/openssl/hmac.h
s2_clnt.o: ../include/openssl/kssl.h ../include/openssl/lhash.h
s2_clnt.o: ../include/openssl/obj_mac.h ../include/openssl/objects.h
s2_clnt.o: ../include/openssl/opensslconf.h ../include/openssl/opensslv.h
s2_clnt.o: ../include/openssl/ossl_typ.h ../include/openssl/pem.h
s2_clnt.o: ../include/openssl/pem2.h ../include/openssl/pkcs7.h
s2_clnt.o: ../include/openssl/pqueue.h ../include/openssl/rsa.h
s2_clnt.o: ../include/openssl/safestack.h ../include/openssl/sha.h
s2_clnt.o: ../include/openssl/srtp.h ../include/openssl/ssl.h
s2_clnt.o: ../include/openssl/ssl2.h ../include/openssl/ssl23.h
s2_clnt.o: ../include/openssl/ssl3.h ../include/openssl/stack.h
s2_clnt.o: ../include/openssl/symhacks.h ../include/openssl/tls1.h
s2_clnt.o: ../include/openssl/x509.h ../include/openssl/x509_vfy.h s2_clnt.c
s2_clnt.o: ssl_locl.h
s2_enc.o: ../e_os.h ../include/openssl/asn1.h ../include/openssl/bio.h
s2_enc.o: ../include/openssl/buffer.h ../include/openssl/comp.h
s2_enc.o: ../include/openssl/crypto.h ../include/openssl/dsa.h
s2_enc.o: ../include/openssl/dtls1.h ../include/openssl/e_os2.h
s2_enc.o: ../include/openssl/ec.h ../include/openssl/ecdh.h
s2_enc.o: ../include/openssl/ecdsa.h ../include/openssl/err.h
s2_enc.o: ../include/openssl/evp.h ../include/openssl/hmac.h
s2_enc.o: ../include/openssl/kssl.h ../include/openssl/lhash.h
s2_enc.o: ../include/openssl/obj_mac.h ../include/openssl/objects.h
s2_enc.o: ../include/openssl/opensslconf.h ../include/openssl/opensslv.h
s2_enc.o: ../include/openssl/ossl_typ.h ../include/openssl/pem.h
s2_enc.o: ../include/openssl/pem2.h ../include/openssl/pkcs7.h
s2_enc.o: ../include/openssl/pqueue.h ../include/openssl/rsa.h
s2_enc.o: ../include/openssl/safestack.h ../include/openssl/sha.h
s2_enc.o: ../include/openssl/srtp.h ../include/openssl/ssl.h
s2_enc.o: ../include/openssl/ssl2.h ../include/openssl/ssl23.h
s2_enc.o: ../include/openssl/ssl3.h ../include/openssl/stack.h
s2_enc.o: ../include/openssl/symhacks.h ../include/openssl/tls1.h
s2_enc.o: ../include/openssl/x509.h ../include/openssl/x509_vfy.h s2_enc.c
s2_enc.o: ssl_locl.h
s2_lib.o: ../e_os.h ../include/openssl/asn1.h ../include/openssl/bio.h
s2_lib.o: ../include/openssl/buffer.h ../include/openssl/comp.h
s2_lib.o: ../include/openssl/crypto.h ../include/openssl/dsa.h
s2_lib.o: ../include/openssl/dtls1.h ../include/openssl/e_os2.h
s2_lib.o: ../include/openssl/ec.h ../include/openssl/ecdh.h
s2_lib.o: ../include/openssl/ecdsa.h ../include/openssl/err.h
s2_lib.o: ../include/openssl/evp.h ../include/openssl/hmac.h
s2_lib.o: ../include/openssl/kssl.h ../include/openssl/lhash.h
s2_lib.o: ../include/openssl/obj_mac.h ../include/openssl/objects.h
s2_lib.o: ../include/openssl/opensslconf.h ../include/openssl/opensslv.h
s2_lib.o: ../include/openssl/ossl_typ.h ../include/openssl/pem.h
s2_lib.o: ../include/openssl/pem2.h ../include/openssl/pkcs7.h
s2_lib.o: ../include/openssl/pqueue.h ../include/openssl/rsa.h
s2_lib.o: ../include/openssl/safestack.h ../include/openssl/sha.h
s2_lib.o: ../include/openssl/srtp.h ../include/openssl/ssl.h
s2_lib.o: ../include/openssl/ssl2.h ../include/openssl/ssl23.h
s2_lib.o: ../include/openssl/ssl3.h ../include/openssl/stack.h
s2_lib.o: ../include/openssl/symhacks.h ../include/openssl/tls1.h
s2_lib.o: ../include/openssl/x509.h ../include/openssl/x509_vfy.h s2_lib.c
s2_lib.o: ssl_locl.h
s2_meth.o: ../e_os.h ../include/openssl/asn1.h ../include/openssl/bio.h
s2_meth.o: ../include/openssl/buffer.h ../include/openssl/comp.h
s2_meth.o: ../include/openssl/crypto.h ../include/openssl/dsa.h
s2_meth.o: ../include/openssl/dtls1.h ../include/openssl/e_os2.h
s2_meth.o: ../include/openssl/ec.h ../include/openssl/ecdh.h
s2_meth.o: ../include/openssl/ecdsa.h ../include/openssl/err.h
s2_meth.o: ../include/openssl/evp.h ../include/openssl/hmac.h
s2_meth.o: ../include/openssl/kssl.h ../include/openssl/lhash.h
s2_meth.o: ../include/openssl/obj_mac.h ../include/openssl/objects.h
s2_meth.o: ../include/openssl/opensslconf.h ../include/openssl/opensslv.h
s2_meth.o: ../include/openssl/ossl_typ.h ../include/openssl/pem.h
s2_meth.o: ../include/openssl/pem2.h ../include/openssl/pkcs7.h
s2_meth.o: ../include/openssl/pqueue.h ../include/openssl/rsa.h
s2_meth.o: ../include/openssl/safestack.h ../include/openssl/sha.h
s2_meth.o: ../include/openssl/srtp.h ../include/openssl/ssl.h
s2_meth.o: ../include/openssl/ssl2.h ../include/openssl/ssl23.h
s2_meth.o: ../include/openssl/ssl3.h ../include/openssl/stack.h
s2_meth.o: ../include/openssl/symhacks.h ../include/openssl/tls1.h
s2_meth.o: ../include/openssl/x509.h ../include/openssl/x509_vfy.h s2_meth.c
s2_meth.o: ssl_locl.h
s2_pkt.o: ../e_os.h ../include/openssl/asn1.h ../include/openssl/bio.h
s2_pkt.o: ../include/openssl/buffer.h ../include/openssl/comp.h
s2_pkt.o: ../include/openssl/crypto.h ../include/openssl/dsa.h
s2_pkt.o: ../include/openssl/dtls1.h ../include/openssl/e_os2.h
s2_pkt.o: ../include/openssl/ec.h ../include/openssl/ecdh.h
s2_pkt.o: ../include/openssl/ecdsa.h ../include/openssl/err.h
s2_pkt.o: ../include/openssl/evp.h ../include/openssl/hmac.h
s2_pkt.o: ../include/openssl/kssl.h ../include/openssl/lhash.h
s2_pkt.o: ../include/openssl/obj_mac.h ../include/openssl/objects.h
s2_pkt.o: ../include/openssl/opensslconf.h ../include/openssl/opensslv.h
s2_pkt.o: ../include/openssl/ossl_typ.h ../include/openssl/pem.h
s2_pkt.o: ../include/openssl/pem2.h ../include/openssl/pkcs7.h
s2_pkt.o: ../include/openssl/pqueue.h ../include/openssl/rsa.h
s2_pkt.o: ../include/openssl/safestack.h ../include/openssl/sha.h
s2_pkt.o: ../include/openssl/srtp.h ../include/openssl/ssl.h
s2_pkt.o: ../include/openssl/ssl2.h ../include/openssl/ssl23.h
s2_pkt.o: ../include/openssl/ssl3.h ../include/openssl/stack.h
s2_pkt.o: ../include/openssl/symhacks.h ../include/openssl/tls1.h
s2_pkt.o: ../include/openssl/x509.h ../include/openssl/x509_vfy.h s2_pkt.c
s2_pkt.o: ssl_locl.h
s2_srvr.o: ../e_os.h ../include/openssl/asn1.h ../include/openssl/bio.h
s2_srvr.o: ../include/openssl/buffer.h ../include/openssl/comp.h
s2_srvr.o: ../include/openssl/crypto.h ../include/openssl/dsa.h
s2_srvr.o: ../include/openssl/dtls1.h ../include/openssl/e_os2.h
s2_srvr.o: ../include/openssl/ec.h ../include/openssl/ecdh.h
s2_srvr.o: ../include/openssl/ecdsa.h ../include/openssl/err.h
s2_srvr.o: ../include/openssl/evp.h ../include/openssl/hmac.h
s2_srvr.o: ../include/openssl/kssl.h ../include/openssl/lhash.h
s2_srvr.o: ../include/openssl/obj_mac.h ../include/openssl/objects.h
s2_srvr.o: ../include/openssl/opensslconf.h ../include/openssl/opensslv.h
s2_srvr.o: ../include/openssl/ossl_typ.h ../include/openssl/pem.h
s2_srvr.o: ../include/openssl/pem2.h ../include/openssl/pkcs7.h
s2_srvr.o: ../include/openssl/pqueue.h ../include/openssl/rsa.h
s2_srvr.o: ../include/openssl/safestack.h ../include/openssl/sha.h
s2_srvr.o: ../include/openssl/srtp.h ../include/openssl/ssl.h
s2_srvr.o: ../include/openssl/ssl2.h ../include/openssl/ssl23.h
s2_srvr.o: ../include/openssl/ssl3.h ../include/openssl/stack.h
s2_srvr.o: ../include/openssl/symhacks.h ../include/openssl/tls1.h
s2_srvr.o: ../include/openssl/x509.h ../include/openssl/x509_vfy.h s2_srvr.c
s2_srvr.o: ssl_locl.h
s3_both.o: ../e_os.h ../include/openssl/asn1.h ../include/openssl/bio.h
s3_both.o: ../include/openssl/buffer.h ../include/openssl/comp.h
s3_both.o: ../include/openssl/crypto.h ../include/openssl/dsa.h
s3_both.o: ../include/openssl/dtls1.h ../include/openssl/e_os2.h
s3_both.o: ../include/openssl/ec.h ../include/openssl/ecdh.h
s3_both.o: ../include/openssl/ecdsa.h ../include/openssl/err.h
s3_both.o: ../include/openssl/evp.h ../include/openssl/hmac.h
s3_both.o: ../include/openssl/kssl.h ../include/openssl/lhash.h
s3_both.o: ../include/openssl/obj_mac.h ../include/openssl/objects.h
s3_both.o: ../include/openssl/opensslconf.h ../include/openssl/opensslv.h
s3_both.o: ../include/openssl/ossl_typ.h ../include/openssl/pem.h
s3_both.o: ../include/openssl/pem2.h ../include/openssl/pkcs7.h
s3_both.o: ../include/openssl/pqueue.h ../include/openssl/rand.h
s3_both.o: ../include/openssl/rsa.h ../include/openssl/safestack.h
s3_both.o: ../include/openssl/sha.h ../include/openssl/srtp.h
s3_both.o: ../include/openssl/ssl.h ../include/openssl/ssl2.h
s3_both.o: ../include/openssl/ssl23.h ../include/openssl/ssl3.h
s3_both.o: ../include/openssl/stack.h ../include/openssl/symhacks.h
s3_both.o: ../include/openssl/tls1.h ../include/openssl/x509.h
s3_both.o: ../include/openssl/x509_vfy.h s3_both.c ssl_locl.h
s3_cbc.o: ../crypto/constant_time_locl.h ../e_os.h ../include/openssl/asn1.h
s3_cbc.o: ../include/openssl/bio.h ../include/openssl/buffer.h
s3_cbc.o: ../include/openssl/comp.h ../include/openssl/crypto.h
s3_cbc.o: ../include/openssl/dsa.h ../include/openssl/dtls1.h
s3_cbc.o: ../include/openssl/e_os2.h ../include/openssl/ec.h
s3_cbc.o: ../include/openssl/ecdh.h ../include/openssl/ecdsa.h
s3_cbc.o: ../include/openssl/err.h ../include/openssl/evp.h
s3_cbc.o: ../include/openssl/hmac.h ../include/openssl/kssl.h
s3_cbc.o: ../include/openssl/lhash.h ../include/openssl/md5.h
s3_cbc.o: ../include/openssl/obj_mac.h ../include/openssl/objects.h
s3_cbc.o: ../include/openssl/opensslconf.h ../include/openssl/opensslv.h
s3_cbc.o: ../include/openssl/ossl_typ.h ../include/openssl/pem.h
s3_cbc.o: ../include/openssl/pem2.h ../include/openssl/pkcs7.h
s3_cbc.o: ../include/openssl/pqueue.h ../include/openssl/rsa.h
s3_cbc.o: ../include/openssl/safestack.h ../include/openssl/sha.h
s3_cbc.o: ../include/openssl/srtp.h ../include/openssl/ssl.h
s3_cbc.o: ../include/openssl/ssl2.h ../include/openssl/ssl23.h
s3_cbc.o: ../include/openssl/ssl3.h ../include/openssl/stack.h
s3_cbc.o: ../include/openssl/symhacks.h ../include/openssl/tls1.h
s3_cbc.o: ../include/openssl/x509.h ../include/openssl/x509_vfy.h s3_cbc.c
s3_cbc.o: ssl_locl.h
s3_clnt.o: ../e_os.h ../include/openssl/asn1.h ../include/openssl/bio.h
s3_clnt.o: ../include/openssl/bn.h ../include/openssl/buffer.h
s3_clnt.o: ../include/openssl/comp.h ../include/openssl/crypto.h
s3_clnt.o: ../include/openssl/dh.h ../include/openssl/dsa.h
s3_clnt.o: ../include/openssl/dtls1.h ../include/openssl/e_os2.h
s3_clnt.o: ../include/openssl/ec.h ../include/openssl/ecdh.h
s3_clnt.o: ../include/openssl/ecdsa.h ../include/openssl/engine.h
s3_clnt.o: ../include/openssl/err.h ../include/openssl/evp.h
s3_clnt.o: ../include/openssl/hmac.h ../include/openssl/kssl.h
s3_clnt.o: ../include/openssl/lhash.h ../include/openssl/md5.h
s3_clnt.o: ../include/openssl/obj_mac.h ../include/openssl/objects.h
s3_clnt.o: ../include/openssl/opensslconf.h ../include/openssl/opensslv.h
s3_clnt.o: ../include/openssl/ossl_typ.h ../include/openssl/pem.h
s3_clnt.o: ../include/openssl/pem2.h ../include/openssl/pkcs7.h
s3_clnt.o: ../include/openssl/pqueue.h ../include/openssl/rand.h
s3_clnt.o: ../include/openssl/rsa.h ../include/openssl/safestack.h
s3_clnt.o: ../include/openssl/sha.h ../include/openssl/srtp.h
s3_clnt.o: ../include/openssl/ssl.h ../include/openssl/ssl2.h
s3_clnt.o: ../include/openssl/ssl23.h ../include/openssl/ssl3.h
s3_clnt.o: ../include/openssl/stack.h ../include/openssl/symhacks.h
s3_clnt.o: ../include/openssl/tls1.h ../include/openssl/x509.h
s3_clnt.o: ../include/openssl/x509_vfy.h kssl_lcl.h s3_clnt.c ssl_locl.h
s3_enc.o: ../e_os.h ../include/openssl/asn1.h ../include/openssl/bio.h
s3_enc.o: ../include/openssl/buffer.h ../include/openssl/comp.h
s3_enc.o: ../include/openssl/crypto.h ../include/openssl/dsa.h
s3_enc.o: ../include/openssl/dtls1.h ../include/openssl/e_os2.h
s3_enc.o: ../include/openssl/ec.h ../include/openssl/ecdh.h
s3_enc.o: ../include/openssl/ecdsa.h ../include/openssl/err.h
s3_enc.o: ../include/openssl/evp.h ../include/openssl/hmac.h
s3_enc.o: ../include/openssl/kssl.h ../include/openssl/lhash.h
s3_enc.o: ../include/openssl/md5.h ../include/openssl/obj_mac.h
s3_enc.o: ../include/openssl/objects.h ../include/openssl/opensslconf.h
s3_enc.o: ../include/openssl/opensslv.h ../include/openssl/ossl_typ.h
s3_enc.o: ../include/openssl/pem.h ../include/openssl/pem2.h
s3_enc.o: ../include/openssl/pkcs7.h ../include/openssl/pqueue.h
s3_enc.o: ../include/openssl/rsa.h ../include/openssl/safestack.h
s3_enc.o: ../include/openssl/sha.h ../include/openssl/srtp.h
s3_enc.o: ../include/openssl/ssl.h ../include/openssl/ssl2.h
s3_enc.o: ../include/openssl/ssl23.h ../include/openssl/ssl3.h
s3_enc.o: ../include/openssl/stack.h ../include/openssl/symhacks.h
s3_enc.o: ../include/openssl/tls1.h ../include/openssl/x509.h
s3_enc.o: ../include/openssl/x509_vfy.h s3_enc.c ssl_locl.h
s3_lib.o: ../e_os.h ../include/openssl/asn1.h ../include/openssl/bio.h
s3_lib.o: ../include/openssl/buffer.h ../include/openssl/comp.h
s3_lib.o: ../include/openssl/crypto.h ../include/openssl/dh.h
s3_lib.o: ../include/openssl/dsa.h ../include/openssl/dtls1.h
s3_lib.o: ../include/openssl/e_os2.h ../include/openssl/ec.h
s3_lib.o: ../include/openssl/ecdh.h ../include/openssl/ecdsa.h
s3_lib.o: ../include/openssl/err.h ../include/openssl/evp.h
s3_lib.o: ../include/openssl/hmac.h ../include/openssl/kssl.h
s3_lib.o: ../include/openssl/lhash.h ../include/openssl/md5.h
s3_lib.o: ../include/openssl/obj_mac.h ../include/openssl/objects.h
s3_lib.o: ../include/openssl/opensslconf.h ../include/openssl/opensslv.h
s3_lib.o: ../include/openssl/ossl_typ.h ../include/openssl/pem.h
s3_lib.o: ../include/openssl/pem2.h ../include/openssl/pkcs7.h
s3_lib.o: ../include/openssl/pqueue.h ../include/openssl/rsa.h
s3_lib.o: ../include/openssl/safestack.h ../include/openssl/sha.h
s3_lib.o: ../include/openssl/srtp.h ../include/openssl/ssl.h
s3_lib.o: ../include/openssl/ssl2.h ../include/openssl/ssl23.h
s3_lib.o: ../include/openssl/ssl3.h ../include/openssl/stack.h
s3_lib.o: ../include/openssl/symhacks.h ../include/openssl/tls1.h
s3_lib.o: ../include/openssl/x509.h ../include/openssl/x509_vfy.h kssl_lcl.h
s3_lib.o: s3_lib.c ssl_locl.h
s3_meth.o: ../e_os.h ../include/openssl/asn1.h ../include/openssl/bio.h
s3_meth.o: ../include/openssl/buffer.h ../include/openssl/comp.h
s3_meth.o: ../include/openssl/crypto.h ../include/openssl/dsa.h
s3_meth.o: ../include/openssl/dtls1.h ../include/openssl/e_os2.h
s3_meth.o: ../include/openssl/ec.h ../include/openssl/ecdh.h
s3_meth.o: ../include/openssl/ecdsa.h ../include/openssl/err.h
s3_meth.o: ../include/openssl/evp.h ../include/openssl/hmac.h
s3_meth.o: ../include/openssl/kssl.h ../include/openssl/lhash.h
s3_meth.o: ../include/openssl/obj_mac.h ../include/openssl/objects.h
s3_meth.o: ../include/openssl/opensslconf.h ../include/openssl/opensslv.h
s3_meth.o: ../include/openssl/ossl_typ.h ../include/openssl/pem.h
s3_meth.o: ../include/openssl/pem2.h ../include/openssl/pkcs7.h
s3_meth.o: ../include/openssl/pqueue.h ../include/openssl/rsa.h
s3_meth.o: ../include/openssl/safestack.h ../include/openssl/sha.h
s3_meth.o: ../include/openssl/srtp.h ../include/openssl/ssl.h
s3_meth.o: ../include/openssl/ssl2.h ../include/openssl/ssl23.h
s3_meth.o: ../include/openssl/ssl3.h ../include/openssl/stack.h
s3_meth.o: ../include/openssl/symhacks.h ../include/openssl/tls1.h
s3_meth.o: ../include/openssl/x509.h ../include/openssl/x509_vfy.h s3_meth.c
s3_meth.o: ssl_locl.h
s3_pkt.o: ../e_os.h ../include/openssl/asn1.h ../include/openssl/bio.h
s3_pkt.o: ../include/openssl/buffer.h ../include/openssl/comp.h
s3_pkt.o: ../include/openssl/crypto.h ../include/openssl/dsa.h
s3_pkt.o: ../include/openssl/dtls1.h ../include/openssl/e_os2.h
s3_pkt.o: ../include/openssl/ec.h ../include/openssl/ecdh.h
s3_pkt.o: ../include/openssl/ecdsa.h ../include/openssl/err.h
s3_pkt.o: ../include/openssl/evp.h ../include/openssl/hmac.h
s3_pkt.o: ../include/openssl/kssl.h ../include/openssl/lhash.h
s3_pkt.o: ../include/openssl/obj_mac.h ../include/openssl/objects.h
s3_pkt.o: ../include/openssl/opensslconf.h ../include/openssl/opensslv.h
s3_pkt.o: ../include/openssl/ossl_typ.h ../include/openssl/pem.h
s3_pkt.o: ../include/openssl/pem2.h ../include/openssl/pkcs7.h
s3_pkt.o: ../include/openssl/pqueue.h ../include/openssl/rand.h
s3_pkt.o: ../include/openssl/rsa.h ../include/openssl/safestack.h
s3_pkt.o: ../include/openssl/sha.h ../include/openssl/srtp.h
s3_pkt.o: ../include/openssl/ssl.h ../include/openssl/ssl2.h
s3_pkt.o: ../include/openssl/ssl23.h ../include/openssl/ssl3.h
s3_pkt.o: ../include/openssl/stack.h ../include/openssl/symhacks.h
s3_pkt.o: ../include/openssl/tls1.h ../include/openssl/x509.h
s3_pkt.o: ../include/openssl/x509_vfy.h s3_pkt.c ssl_locl.h
s3_srvr.o: ../crypto/constant_time_locl.h ../e_os.h ../include/openssl/asn1.h
s3_srvr.o: ../include/openssl/bio.h ../include/openssl/bn.h
s3_srvr.o: ../include/openssl/buffer.h ../include/openssl/comp.h
s3_srvr.o: ../include/openssl/crypto.h ../include/openssl/dh.h
s3_srvr.o: ../include/openssl/dsa.h ../include/openssl/dtls1.h
s3_srvr.o: ../include/openssl/e_os2.h ../include/openssl/ec.h
s3_srvr.o: ../include/openssl/ecdh.h ../include/openssl/ecdsa.h
s3_srvr.o: ../include/openssl/err.h ../include/openssl/evp.h
s3_srvr.o: ../include/openssl/hmac.h ../include/openssl/krb5_asn.h
s3_srvr.o: ../include/openssl/kssl.h ../include/openssl/lhash.h
s3_srvr.o: ../include/openssl/md5.h ../include/openssl/obj_mac.h
s3_srvr.o: ../include/openssl/objects.h ../include/openssl/opensslconf.h
s3_srvr.o: ../include/openssl/opensslv.h ../include/openssl/ossl_typ.h
s3_srvr.o: ../include/openssl/pem.h ../include/openssl/pem2.h
s3_srvr.o: ../include/openssl/pkcs7.h ../include/openssl/pqueue.h
s3_srvr.o: ../include/openssl/rand.h ../include/openssl/rsa.h
s3_srvr.o: ../include/openssl/safestack.h ../include/openssl/sha.h
s3_srvr.o: ../include/openssl/srtp.h ../include/openssl/ssl.h
s3_srvr.o: ../include/openssl/ssl2.h ../include/openssl/ssl23.h
s3_srvr.o: ../include/openssl/ssl3.h ../include/openssl/stack.h
s3_srvr.o: ../include/openssl/symhacks.h ../include/openssl/tls1.h
s3_srvr.o: ../include/openssl/x509.h ../include/openssl/x509_vfy.h kssl_lcl.h
s3_srvr.o: s3_srvr.c ssl_locl.h
ssl_algs.o: ../e_os.h ../include/openssl/asn1.h ../include/openssl/bio.h
ssl_algs.o: ../include/openssl/buffer.h ../include/openssl/comp.h
ssl_algs.o: ../include/openssl/crypto.h ../include/openssl/dsa.h
ssl_algs.o: ../include/openssl/dtls1.h ../include/openssl/e_os2.h
ssl_algs.o: ../include/openssl/ec.h ../include/openssl/ecdh.h
ssl_algs.o: ../include/openssl/ecdsa.h ../include/openssl/err.h
ssl_algs.o: ../include/openssl/evp.h ../include/openssl/hmac.h
ssl_algs.o: ../include/openssl/kssl.h ../include/openssl/lhash.h
ssl_algs.o: ../include/openssl/obj_mac.h ../include/openssl/objects.h
ssl_algs.o: ../include/openssl/opensslconf.h ../include/openssl/opensslv.h
ssl_algs.o: ../include/openssl/ossl_typ.h ../include/openssl/pem.h
ssl_algs.o: ../include/openssl/pem2.h ../include/openssl/pkcs7.h
ssl_algs.o: ../include/openssl/pqueue.h ../include/openssl/rsa.h
ssl_algs.o: ../include/openssl/safestack.h ../include/openssl/sha.h
ssl_algs.o: ../include/openssl/srtp.h ../include/openssl/ssl.h
ssl_algs.o: ../include/openssl/ssl2.h ../include/openssl/ssl23.h
ssl_algs.o: ../include/openssl/ssl3.h ../include/openssl/stack.h
ssl_algs.o: ../include/openssl/symhacks.h ../include/openssl/tls1.h
ssl_algs.o: ../include/openssl/x509.h ../include/openssl/x509_vfy.h ssl_algs.c
ssl_algs.o: ssl_locl.h
ssl_asn1.o: ../e_os.h ../include/openssl/asn1.h ../include/openssl/asn1_mac.h
ssl_asn1.o: ../include/openssl/bio.h ../include/openssl/buffer.h
ssl_asn1.o: ../include/openssl/comp.h ../include/openssl/crypto.h
ssl_asn1.o: ../include/openssl/dsa.h ../include/openssl/dtls1.h
ssl_asn1.o: ../include/openssl/e_os2.h ../include/openssl/ec.h
ssl_asn1.o: ../include/openssl/ecdh.h ../include/openssl/ecdsa.h
ssl_asn1.o: ../include/openssl/err.h ../include/openssl/evp.h
ssl_asn1.o: ../include/openssl/hmac.h ../include/openssl/kssl.h
ssl_asn1.o: ../include/openssl/lhash.h ../include/openssl/obj_mac.h
ssl_asn1.o: ../include/openssl/objects.h ../include/openssl/opensslconf.h
ssl_asn1.o: ../include/openssl/opensslv.h ../include/openssl/ossl_typ.h
ssl_asn1.o: ../include/openssl/pem.h ../include/openssl/pem2.h
ssl_asn1.o: ../include/openssl/pkcs7.h ../include/openssl/pqueue.h
ssl_asn1.o: ../include/openssl/rsa.h ../include/openssl/safestack.h
ssl_asn1.o: ../include/openssl/sha.h ../include/openssl/srtp.h
ssl_asn1.o: ../include/openssl/ssl.h ../include/openssl/ssl2.h
ssl_asn1.o: ../include/openssl/ssl23.h ../include/openssl/ssl3.h
ssl_asn1.o: ../include/openssl/stack.h ../include/openssl/symhacks.h
ssl_asn1.o: ../include/openssl/tls1.h ../include/openssl/x509.h
ssl_asn1.o: ../include/openssl/x509_vfy.h ssl_asn1.c ssl_locl.h
ssl_cert.o: ../crypto/o_dir.h ../e_os.h ../include/openssl/asn1.h
ssl_cert.o: ../include/openssl/bio.h ../include/openssl/bn.h
ssl_cert.o: ../include/openssl/buffer.h ../include/openssl/comp.h
ssl_cert.o: ../include/openssl/conf.h ../include/openssl/crypto.h
ssl_cert.o: ../include/openssl/dh.h ../include/openssl/dsa.h
ssl_cert.o: ../include/openssl/dtls1.h ../include/openssl/e_os2.h
ssl_cert.o: ../include/openssl/ec.h ../include/openssl/ecdh.h
ssl_cert.o: ../include/openssl/ecdsa.h ../include/openssl/err.h
ssl_cert.o: ../include/openssl/evp.h ../include/openssl/hmac.h
ssl_cert.o: ../include/openssl/kssl.h ../include/openssl/lhash.h
ssl_cert.o: ../include/openssl/obj_mac.h ../include/openssl/objects.h
ssl_cert.o: ../include/openssl/opensslconf.h ../include/openssl/opensslv.h
ssl_cert.o: ../include/openssl/ossl_typ.h ../include/openssl/pem.h
ssl_cert.o: ../include/openssl/pem2.h ../include/openssl/pkcs7.h
ssl_cert.o: ../include/openssl/pqueue.h ../include/openssl/rsa.h
ssl_cert.o: ../include/openssl/safestack.h ../include/openssl/sha.h
ssl_cert.o: ../include/openssl/srtp.h ../include/openssl/ssl.h
ssl_cert.o: ../include/openssl/ssl2.h ../include/openssl/ssl23.h
ssl_cert.o: ../include/openssl/ssl3.h ../include/openssl/stack.h
ssl_cert.o: ../include/openssl/symhacks.h ../include/openssl/tls1.h
ssl_cert.o: ../include/openssl/x509.h ../include/openssl/x509_vfy.h
ssl_cert.o: ../include/openssl/x509v3.h ssl_cert.c ssl_locl.h
ssl_ciph.o: ../e_os.h ../include/openssl/asn1.h ../include/openssl/bio.h
ssl_ciph.o: ../include/openssl/buffer.h ../include/openssl/comp.h
ssl_ciph.o: ../include/openssl/crypto.h ../include/openssl/dsa.h
ssl_ciph.o: ../include/openssl/dtls1.h ../include/openssl/e_os2.h
ssl_ciph.o: ../include/openssl/ec.h ../include/openssl/ecdh.h
ssl_ciph.o: ../include/openssl/ecdsa.h ../include/openssl/engine.h
ssl_ciph.o: ../include/openssl/err.h ../include/openssl/evp.h
ssl_ciph.o: ../include/openssl/hmac.h ../include/openssl/kssl.h
ssl_ciph.o: ../include/openssl/lhash.h ../include/openssl/obj_mac.h
ssl_ciph.o: ../include/openssl/objects.h ../include/openssl/opensslconf.h
ssl_ciph.o: ../include/openssl/opensslv.h ../include/openssl/ossl_typ.h
ssl_ciph.o: ../include/openssl/pem.h ../include/openssl/pem2.h
ssl_ciph.o: ../include/openssl/pkcs7.h ../include/openssl/pqueue.h
ssl_ciph.o: ../include/openssl/rsa.h ../include/openssl/safestack.h
ssl_ciph.o: ../include/openssl/sha.h ../include/openssl/srtp.h
ssl_ciph.o: ../include/openssl/ssl.h ../include/openssl/ssl2.h
ssl_ciph.o: ../include/openssl/ssl23.h ../include/openssl/ssl3.h
ssl_ciph.o: ../include/openssl/stack.h ../include/openssl/symhacks.h
ssl_ciph.o: ../include/openssl/tls1.h ../include/openssl/x509.h
ssl_ciph.o: ../include/openssl/x509_vfy.h ssl_ciph.c ssl_locl.h
ssl_conf.o: ../e_os.h ../include/openssl/asn1.h ../include/openssl/bio.h
ssl_conf.o: ../include/openssl/buffer.h ../include/openssl/comp.h
ssl_conf.o: ../include/openssl/conf.h ../include/openssl/crypto.h
ssl_conf.o: ../include/openssl/dh.h ../include/openssl/dsa.h
ssl_conf.o: ../include/openssl/dtls1.h ../include/openssl/e_os2.h
ssl_conf.o: ../include/openssl/ec.h ../include/openssl/ecdh.h
ssl_conf.o: ../include/openssl/ecdsa.h ../include/openssl/err.h
ssl_conf.o: ../include/openssl/evp.h ../include/openssl/hmac.h
ssl_conf.o: ../include/openssl/kssl.h ../include/openssl/lhash.h
ssl_conf.o: ../include/openssl/obj_mac.h ../include/openssl/objects.h
ssl_conf.o: ../include/openssl/opensslconf.h ../include/openssl/opensslv.h
ssl_conf.o: ../include/openssl/ossl_typ.h ../include/openssl/pem.h
ssl_conf.o: ../include/openssl/pem2.h ../include/openssl/pkcs7.h
ssl_conf.o: ../include/openssl/pqueue.h ../include/openssl/rsa.h
ssl_conf.o: ../include/openssl/safestack.h ../include/openssl/sha.h
ssl_conf.o: ../include/openssl/srtp.h ../include/openssl/ssl.h
ssl_conf.o: ../include/openssl/ssl2.h ../include/openssl/ssl23.h
ssl_conf.o: ../include/openssl/ssl3.h ../include/openssl/stack.h
ssl_conf.o: ../include/openssl/symhacks.h ../include/openssl/tls1.h
ssl_conf.o: ../include/openssl/x509.h ../include/openssl/x509_vfy.h ssl_conf.c
ssl_conf.o: ssl_locl.h
ssl_err.o: ../include/openssl/asn1.h ../include/openssl/bio.h
ssl_err.o: ../include/openssl/buffer.h ../include/openssl/comp.h
ssl_err.o: ../include/openssl/crypto.h ../include/openssl/dtls1.h
ssl_err.o: ../include/openssl/e_os2.h ../include/openssl/ec.h
ssl_err.o: ../include/openssl/ecdh.h ../include/openssl/ecdsa.h
ssl_err.o: ../include/openssl/err.h ../include/openssl/evp.h
ssl_err.o: ../include/openssl/hmac.h ../include/openssl/kssl.h
ssl_err.o: ../include/openssl/lhash.h ../include/openssl/obj_mac.h
ssl_err.o: ../include/openssl/objects.h ../include/openssl/opensslconf.h
ssl_err.o: ../include/openssl/opensslv.h ../include/openssl/ossl_typ.h
ssl_err.o: ../include/openssl/pem.h ../include/openssl/pem2.h
ssl_err.o: ../include/openssl/pkcs7.h ../include/openssl/pqueue.h
ssl_err.o: ../include/openssl/safestack.h ../include/openssl/sha.h
ssl_err.o: ../include/openssl/srtp.h ../include/openssl/ssl.h
ssl_err.o: ../include/openssl/ssl2.h ../include/openssl/ssl23.h
ssl_err.o: ../include/openssl/ssl3.h ../include/openssl/stack.h
ssl_err.o: ../include/openssl/symhacks.h ../include/openssl/tls1.h
ssl_err.o: ../include/openssl/x509.h ../include/openssl/x509_vfy.h ssl_err.c
ssl_err2.o: ../include/openssl/asn1.h ../include/openssl/bio.h
ssl_err2.o: ../include/openssl/buffer.h ../include/openssl/comp.h
ssl_err2.o: ../include/openssl/crypto.h ../include/openssl/dtls1.h
ssl_err2.o: ../include/openssl/e_os2.h ../include/openssl/ec.h
ssl_err2.o: ../include/openssl/ecdh.h ../include/openssl/ecdsa.h
ssl_err2.o: ../include/openssl/err.h ../include/openssl/evp.h
ssl_err2.o: ../include/openssl/hmac.h ../include/openssl/kssl.h
ssl_err2.o: ../include/openssl/lhash.h ../include/openssl/obj_mac.h
ssl_err2.o: ../include/openssl/objects.h ../include/openssl/opensslconf.h
ssl_err2.o: ../include/openssl/opensslv.h ../include/openssl/ossl_typ.h
ssl_err2.o: ../include/openssl/pem.h ../include/openssl/pem2.h
ssl_err2.o: ../include/openssl/pkcs7.h ../include/openssl/pqueue.h
ssl_err2.o: ../include/openssl/safestack.h ../include/openssl/sha.h
ssl_err2.o: ../include/openssl/srtp.h ../include/openssl/ssl.h
ssl_err2.o: ../include/openssl/ssl2.h ../include/openssl/ssl23.h
ssl_err2.o: ../include/openssl/ssl3.h ../include/openssl/stack.h
ssl_err2.o: ../include/openssl/symhacks.h ../include/openssl/tls1.h
ssl_err2.o: ../include/openssl/x509.h ../include/openssl/x509_vfy.h ssl_err2.c
ssl_lib.o: ../e_os.h ../include/openssl/asn1.h ../include/openssl/bio.h
ssl_lib.o: ../include/openssl/buffer.h ../include/openssl/comp.h
ssl_lib.o: ../include/openssl/conf.h ../include/openssl/crypto.h
ssl_lib.o: ../include/openssl/dh.h ../include/openssl/dsa.h
ssl_lib.o: ../include/openssl/dtls1.h ../include/openssl/e_os2.h
ssl_lib.o: ../include/openssl/ec.h ../include/openssl/ecdh.h
ssl_lib.o: ../include/openssl/ecdsa.h ../include/openssl/engine.h
ssl_lib.o: ../include/openssl/err.h ../include/openssl/evp.h
ssl_lib.o: ../include/openssl/hmac.h ../include/openssl/kssl.h
ssl_lib.o: ../include/openssl/lhash.h ../include/openssl/obj_mac.h
ssl_lib.o: ../include/openssl/objects.h ../include/openssl/ocsp.h
ssl_lib.o: ../include/openssl/opensslconf.h ../include/openssl/opensslv.h
ssl_lib.o: ../include/openssl/ossl_typ.h ../include/openssl/pem.h
ssl_lib.o: ../include/openssl/pem2.h ../include/openssl/pkcs7.h
ssl_lib.o: ../include/openssl/pqueue.h ../include/openssl/rand.h
ssl_lib.o: ../include/openssl/rsa.h ../include/openssl/safestack.h
ssl_lib.o: ../include/openssl/sha.h ../include/openssl/srtp.h
ssl_lib.o: ../include/openssl/ssl.h ../include/openssl/ssl2.h
ssl_lib.o: ../include/openssl/ssl23.h ../include/openssl/ssl3.h
ssl_lib.o: ../include/openssl/stack.h ../include/openssl/symhacks.h
ssl_lib.o: ../include/openssl/tls1.h ../include/openssl/x509.h
ssl_lib.o: ../include/openssl/x509_vfy.h ../include/openssl/x509v3.h kssl_lcl.h
ssl_lib.o: ssl_lib.c ssl_locl.h
ssl_rsa.o: ../e_os.h ../include/openssl/asn1.h ../include/openssl/bio.h
ssl_rsa.o: ../include/openssl/buffer.h ../include/openssl/comp.h
ssl_rsa.o: ../include/openssl/crypto.h ../include/openssl/dsa.h
ssl_rsa.o: ../include/openssl/dtls1.h ../include/openssl/e_os2.h
ssl_rsa.o: ../include/openssl/ec.h ../include/openssl/ecdh.h
ssl_rsa.o: ../include/openssl/ecdsa.h ../include/openssl/err.h
ssl_rsa.o: ../include/openssl/evp.h ../include/openssl/hmac.h
ssl_rsa.o: ../include/openssl/kssl.h ../include/openssl/lhash.h
ssl_rsa.o: ../include/openssl/obj_mac.h ../include/openssl/objects.h
ssl_rsa.o: ../include/openssl/opensslconf.h ../include/openssl/opensslv.h
ssl_rsa.o: ../include/openssl/ossl_typ.h ../include/openssl/pem.h
ssl_rsa.o: ../include/openssl/pem2.h ../include/openssl/pkcs7.h
ssl_rsa.o: ../include/openssl/pqueue.h ../include/openssl/rsa.h
ssl_rsa.o: ../include/openssl/safestack.h ../include/openssl/sha.h
ssl_rsa.o: ../include/openssl/srtp.h ../include/openssl/ssl.h
ssl_rsa.o: ../include/openssl/ssl2.h ../include/openssl/ssl23.h
ssl_rsa.o: ../include/openssl/ssl3.h ../include/openssl/stack.h
ssl_rsa.o: ../include/openssl/symhacks.h ../include/openssl/tls1.h
ssl_rsa.o: ../include/openssl/x509.h ../include/openssl/x509_vfy.h ssl_locl.h
ssl_rsa.o: ssl_rsa.c
ssl_sess.o: ../e_os.h ../include/openssl/asn1.h ../include/openssl/bio.h
ssl_sess.o: ../include/openssl/buffer.h ../include/openssl/comp.h
ssl_sess.o: ../include/openssl/crypto.h ../include/openssl/dsa.h
ssl_sess.o: ../include/openssl/dtls1.h ../include/openssl/e_os2.h
ssl_sess.o: ../include/openssl/ec.h ../include/openssl/ecdh.h
ssl_sess.o: ../include/openssl/ecdsa.h ../include/openssl/engine.h
ssl_sess.o: ../include/openssl/err.h ../include/openssl/evp.h
ssl_sess.o: ../include/openssl/hmac.h ../include/openssl/kssl.h
ssl_sess.o: ../include/openssl/lhash.h ../include/openssl/obj_mac.h
ssl_sess.o: ../include/openssl/objects.h ../include/openssl/opensslconf.h
ssl_sess.o: ../include/openssl/opensslv.h ../include/openssl/ossl_typ.h
ssl_sess.o: ../include/openssl/pem.h ../include/openssl/pem2.h
ssl_sess.o: ../include/openssl/pkcs7.h ../include/openssl/pqueue.h
ssl_sess.o: ../include/openssl/rand.h ../include/openssl/rsa.h
ssl_sess.o: ../include/openssl/safestack.h ../include/openssl/sha.h
ssl_sess.o: ../include/openssl/srtp.h ../include/openssl/ssl.h
ssl_sess.o: ../include/openssl/ssl2.h ../include/openssl/ssl23.h
ssl_sess.o: ../include/openssl/ssl3.h ../include/openssl/stack.h
ssl_sess.o: ../include/openssl/symhacks.h ../include/openssl/tls1.h
ssl_sess.o: ../include/openssl/x509.h ../include/openssl/x509_vfy.h ssl_locl.h
ssl_sess.o: ssl_sess.c
ssl_stat.o: ../e_os.h ../include/openssl/asn1.h ../include/openssl/bio.h
ssl_stat.o: ../include/openssl/buffer.h ../include/openssl/comp.h
ssl_stat.o: ../include/openssl/crypto.h ../include/openssl/dsa.h
ssl_stat.o: ../include/openssl/dtls1.h ../include/openssl/e_os2.h
ssl_stat.o: ../include/openssl/ec.h ../include/openssl/ecdh.h
ssl_stat.o: ../include/openssl/ecdsa.h ../include/openssl/err.h
ssl_stat.o: ../include/openssl/evp.h ../include/openssl/hmac.h
ssl_stat.o: ../include/openssl/kssl.h ../include/openssl/lhash.h
ssl_stat.o: ../include/openssl/obj_mac.h ../include/openssl/objects.h
ssl_stat.o: ../include/openssl/opensslconf.h ../include/openssl/opensslv.h
ssl_stat.o: ../include/openssl/ossl_typ.h ../include/openssl/pem.h
ssl_stat.o: ../include/openssl/pem2.h ../include/openssl/pkcs7.h
ssl_stat.o: ../include/openssl/pqueue.h ../include/openssl/rsa.h
ssl_stat.o: ../include/openssl/safestack.h ../include/openssl/sha.h
ssl_stat.o: ../include/openssl/srtp.h ../include/openssl/ssl.h
ssl_stat.o: ../include/openssl/ssl2.h ../include/openssl/ssl23.h
ssl_stat.o: ../include/openssl/ssl3.h ../include/openssl/stack.h
ssl_stat.o: ../include/openssl/symhacks.h ../include/openssl/tls1.h
ssl_stat.o: ../include/openssl/x509.h ../include/openssl/x509_vfy.h ssl_locl.h
ssl_stat.o: ssl_stat.c
ssl_txt.o: ../e_os.h ../include/openssl/asn1.h ../include/openssl/bio.h
ssl_txt.o: ../include/openssl/buffer.h ../include/openssl/comp.h
ssl_txt.o: ../include/openssl/crypto.h ../include/openssl/dsa.h
ssl_txt.o: ../include/openssl/dtls1.h ../include/openssl/e_os2.h
ssl_txt.o: ../include/openssl/ec.h ../include/openssl/ecdh.h
ssl_txt.o: ../include/openssl/ecdsa.h ../include/openssl/err.h
ssl_txt.o: ../include/openssl/evp.h ../include/openssl/hmac.h
ssl_txt.o: ../include/openssl/kssl.h ../include/openssl/lhash.h
ssl_txt.o: ../include/openssl/obj_mac.h ../include/openssl/objects.h
ssl_txt.o: ../include/openssl/opensslconf.h ../include/openssl/opensslv.h
ssl_txt.o: ../include/openssl/ossl_typ.h ../include/openssl/pem.h
ssl_txt.o: ../include/openssl/pem2.h ../include/openssl/pkcs7.h
ssl_txt.o: ../include/openssl/pqueue.h ../include/openssl/rsa.h
ssl_txt.o: ../include/openssl/safestack.h ../include/openssl/sha.h
ssl_txt.o: ../include/openssl/srtp.h ../include/openssl/ssl.h
ssl_txt.o: ../include/openssl/ssl2.h ../include/openssl/ssl23.h
ssl_txt.o: ../include/openssl/ssl3.h ../include/openssl/stack.h
ssl_txt.o: ../include/openssl/symhacks.h ../include/openssl/tls1.h
ssl_txt.o: ../include/openssl/x509.h ../include/openssl/x509_vfy.h ssl_locl.h
ssl_txt.o: ssl_txt.c
ssl_utst.o: ../e_os.h ../include/openssl/asn1.h ../include/openssl/bio.h
ssl_utst.o: ../include/openssl/buffer.h ../include/openssl/comp.h
ssl_utst.o: ../include/openssl/crypto.h ../include/openssl/dsa.h
ssl_utst.o: ../include/openssl/dtls1.h ../include/openssl/e_os2.h
ssl_utst.o: ../include/openssl/ec.h ../include/openssl/ecdh.h
ssl_utst.o: ../include/openssl/ecdsa.h ../include/openssl/err.h
ssl_utst.o: ../include/openssl/evp.h ../include/openssl/hmac.h
ssl_utst.o: ../include/openssl/kssl.h ../include/openssl/lhash.h
ssl_utst.o: ../include/openssl/obj_mac.h ../include/openssl/objects.h
ssl_utst.o: ../include/openssl/opensslconf.h ../include/openssl/opensslv.h
ssl_utst.o: ../include/openssl/ossl_typ.h ../include/openssl/pem.h
ssl_utst.o: ../include/openssl/pem2.h ../include/openssl/pkcs7.h
ssl_utst.o: ../include/openssl/pqueue.h ../include/openssl/rsa.h
ssl_utst.o: ../include/openssl/safestack.h ../include/openssl/sha.h
ssl_utst.o: ../include/openssl/srtp.h ../include/openssl/ssl.h
ssl_utst.o: ../include/openssl/ssl2.h ../include/openssl/ssl23.h
ssl_utst.o: ../include/openssl/ssl3.h ../include/openssl/stack.h
ssl_utst.o: ../include/openssl/symhacks.h ../include/openssl/tls1.h
ssl_utst.o: ../include/openssl/x509.h ../include/openssl/x509_vfy.h ssl_locl.h
ssl_utst.o: ssl_utst.c
t1_clnt.o: ../e_os.h ../include/openssl/asn1.h ../include/openssl/bio.h
t1_clnt.o: ../include/openssl/buffer.h ../include/openssl/comp.h
t1_clnt.o: ../include/openssl/crypto.h ../include/openssl/dsa.h
t1_clnt.o: ../include/openssl/dtls1.h ../include/openssl/e_os2.h
t1_clnt.o: ../include/openssl/ec.h ../include/openssl/ecdh.h
t1_clnt.o: ../include/openssl/ecdsa.h ../include/openssl/err.h
t1_clnt.o: ../include/openssl/evp.h ../include/openssl/hmac.h
t1_clnt.o: ../include/openssl/kssl.h ../include/openssl/lhash.h
t1_clnt.o: ../include/openssl/obj_mac.h ../include/openssl/objects.h
t1_clnt.o: ../include/openssl/opensslconf.h ../include/openssl/opensslv.h
t1_clnt.o: ../include/openssl/ossl_typ.h ../include/openssl/pem.h
t1_clnt.o: ../include/openssl/pem2.h ../include/openssl/pkcs7.h
t1_clnt.o: ../include/openssl/pqueue.h ../include/openssl/rand.h
t1_clnt.o: ../include/openssl/rsa.h ../include/openssl/safestack.h
t1_clnt.o: ../include/openssl/sha.h ../include/openssl/srtp.h
t1_clnt.o: ../include/openssl/ssl.h ../include/openssl/ssl2.h
t1_clnt.o: ../include/openssl/ssl23.h ../include/openssl/ssl3.h
t1_clnt.o: ../include/openssl/stack.h ../include/openssl/symhacks.h
t1_clnt.o: ../include/openssl/tls1.h ../include/openssl/x509.h
t1_clnt.o: ../include/openssl/x509_vfy.h ssl_locl.h t1_clnt.c
t1_enc.o: ../e_os.h ../include/openssl/asn1.h ../include/openssl/bio.h
t1_enc.o: ../include/openssl/buffer.h ../include/openssl/comp.h
t1_enc.o: ../include/openssl/crypto.h ../include/openssl/dsa.h
t1_enc.o: ../include/openssl/dtls1.h ../include/openssl/e_os2.h
t1_enc.o: ../include/openssl/ec.h ../include/openssl/ecdh.h
t1_enc.o: ../include/openssl/ecdsa.h ../include/openssl/err.h
t1_enc.o: ../include/openssl/evp.h ../include/openssl/hmac.h
t1_enc.o: ../include/openssl/kssl.h ../include/openssl/lhash.h
t1_enc.o: ../include/openssl/md5.h ../include/openssl/obj_mac.h
t1_enc.o: ../include/openssl/objects.h ../include/openssl/opensslconf.h
t1_enc.o: ../include/openssl/opensslv.h ../include/openssl/ossl_typ.h
t1_enc.o: ../include/openssl/pem.h ../include/openssl/pem2.h
t1_enc.o: ../include/openssl/pkcs7.h ../include/openssl/pqueue.h
t1_enc.o: ../include/openssl/rand.h ../include/openssl/rsa.h
t1_enc.o: ../include/openssl/safestack.h ../include/openssl/sha.h
t1_enc.o: ../include/openssl/srtp.h ../include/openssl/ssl.h
t1_enc.o: ../include/openssl/ssl2.h ../include/openssl/ssl23.h
t1_enc.o: ../include/openssl/ssl3.h ../include/openssl/stack.h
t1_enc.o: ../include/openssl/symhacks.h ../include/openssl/tls1.h
t1_enc.o: ../include/openssl/x509.h ../include/openssl/x509_vfy.h ssl_locl.h
t1_enc.o: t1_enc.c
t1_ext.o: ../e_os.h ../include/openssl/asn1.h ../include/openssl/bio.h
t1_ext.o: ../include/openssl/buffer.h ../include/openssl/comp.h
t1_ext.o: ../include/openssl/crypto.h ../include/openssl/dsa.h
t1_ext.o: ../include/openssl/dtls1.h ../include/openssl/e_os2.h
t1_ext.o: ../include/openssl/ec.h ../include/openssl/ecdh.h
t1_ext.o: ../include/openssl/ecdsa.h ../include/openssl/err.h
t1_ext.o: ../include/openssl/evp.h ../include/openssl/hmac.h
t1_ext.o: ../include/openssl/kssl.h ../include/openssl/lhash.h
t1_ext.o: ../include/openssl/obj_mac.h ../include/openssl/objects.h
t1_ext.o: ../include/openssl/opensslconf.h ../include/openssl/opensslv.h
t1_ext.o: ../include/openssl/ossl_typ.h ../include/openssl/pem.h
t1_ext.o: ../include/openssl/pem2.h ../include/openssl/pkcs7.h
t1_ext.o: ../include/openssl/pqueue.h ../include/openssl/rsa.h
t1_ext.o: ../include/openssl/safestack.h ../include/openssl/sha.h
t1_ext.o: ../include/openssl/srtp.h ../include/openssl/ssl.h
t1_ext.o: ../include/openssl/ssl2.h ../include/openssl/ssl23.h
t1_ext.o: ../include/openssl/ssl3.h ../include/openssl/stack.h
t1_ext.o: ../include/openssl/symhacks.h ../include/openssl/tls1.h
t1_ext.o: ../include/openssl/x509.h ../include/openssl/x509_vfy.h ssl_locl.h
t1_ext.o: t1_ext.c
t1_lib.o: ../e_os.h ../include/openssl/asn1.h ../include/openssl/bio.h
t1_lib.o: ../include/openssl/buffer.h ../include/openssl/comp.h
t1_lib.o: ../include/openssl/conf.h ../include/openssl/crypto.h
t1_lib.o: ../include/openssl/dsa.h ../include/openssl/dtls1.h
t1_lib.o: ../include/openssl/e_os2.h ../include/openssl/ec.h
t1_lib.o: ../include/openssl/ecdh.h ../include/openssl/ecdsa.h
t1_lib.o: ../include/openssl/err.h ../include/openssl/evp.h
t1_lib.o: ../include/openssl/hmac.h ../include/openssl/kssl.h
t1_lib.o: ../include/openssl/lhash.h ../include/openssl/obj_mac.h
t1_lib.o: ../include/openssl/objects.h ../include/openssl/ocsp.h
t1_lib.o: ../include/openssl/opensslconf.h ../include/openssl/opensslv.h
t1_lib.o: ../include/openssl/ossl_typ.h ../include/openssl/pem.h
t1_lib.o: ../include/openssl/pem2.h ../include/openssl/pkcs7.h
t1_lib.o: ../include/openssl/pqueue.h ../include/openssl/rand.h
t1_lib.o: ../include/openssl/rsa.h ../include/openssl/safestack.h
t1_lib.o: ../include/openssl/sha.h ../include/openssl/srtp.h
t1_lib.o: ../include/openssl/ssl.h ../include/openssl/ssl2.h
t1_lib.o: ../include/openssl/ssl23.h ../include/openssl/ssl3.h
t1_lib.o: ../include/openssl/stack.h ../include/openssl/symhacks.h
t1_lib.o: ../include/openssl/tls1.h ../include/openssl/x509.h
t1_lib.o: ../include/openssl/x509_vfy.h ../include/openssl/x509v3.h ssl_locl.h
t1_lib.o: t1_lib.c
t1_meth.o: ../e_os.h ../include/openssl/asn1.h ../include/openssl/bio.h
t1_meth.o: ../include/openssl/buffer.h ../include/openssl/comp.h
t1_meth.o: ../include/openssl/crypto.h ../include/openssl/dsa.h
t1_meth.o: ../include/openssl/dtls1.h ../include/openssl/e_os2.h
t1_meth.o: ../include/openssl/ec.h ../include/openssl/ecdh.h
t1_meth.o: ../include/openssl/ecdsa.h ../include/openssl/err.h
t1_meth.o: ../include/openssl/evp.h ../include/openssl/hmac.h
t1_meth.o: ../include/openssl/kssl.h ../include/openssl/lhash.h
t1_meth.o: ../include/openssl/obj_mac.h ../include/openssl/objects.h
t1_meth.o: ../include/openssl/opensslconf.h ../include/openssl/opensslv.h
t1_meth.o: ../include/openssl/ossl_typ.h ../include/openssl/pem.h
t1_meth.o: ../include/openssl/pem2.h ../include/openssl/pkcs7.h
t1_meth.o: ../include/openssl/pqueue.h ../include/openssl/rsa.h
t1_meth.o: ../include/openssl/safestack.h ../include/openssl/sha.h
t1_meth.o: ../include/openssl/srtp.h ../include/openssl/ssl.h
t1_meth.o: ../include/openssl/ssl2.h ../include/openssl/ssl23.h
t1_meth.o: ../include/openssl/ssl3.h ../include/openssl/stack.h
t1_meth.o: ../include/openssl/symhacks.h ../include/openssl/tls1.h
t1_meth.o: ../include/openssl/x509.h ../include/openssl/x509_vfy.h ssl_locl.h
t1_meth.o: t1_meth.c
t1_reneg.o: ../e_os.h ../include/openssl/asn1.h ../include/openssl/bio.h
t1_reneg.o: ../include/openssl/buffer.h ../include/openssl/comp.h
t1_reneg.o: ../include/openssl/crypto.h ../include/openssl/dsa.h
t1_reneg.o: ../include/openssl/dtls1.h ../include/openssl/e_os2.h
t1_reneg.o: ../include/openssl/ec.h ../include/openssl/ecdh.h
t1_reneg.o: ../include/openssl/ecdsa.h ../include/openssl/err.h
t1_reneg.o: ../include/openssl/evp.h ../include/openssl/hmac.h
t1_reneg.o: ../include/openssl/kssl.h ../include/openssl/lhash.h
t1_reneg.o: ../include/openssl/obj_mac.h ../include/openssl/objects.h
t1_reneg.o: ../include/openssl/opensslconf.h ../include/openssl/opensslv.h
t1_reneg.o: ../include/openssl/ossl_typ.h ../include/openssl/pem.h
t1_reneg.o: ../include/openssl/pem2.h ../include/openssl/pkcs7.h
t1_reneg.o: ../include/openssl/pqueue.h ../include/openssl/rsa.h
t1_reneg.o: ../include/openssl/safestack.h ../include/openssl/sha.h
t1_reneg.o: ../include/openssl/srtp.h ../include/openssl/ssl.h
t1_reneg.o: ../include/openssl/ssl2.h ../include/openssl/ssl23.h
t1_reneg.o: ../include/openssl/ssl3.h ../include/openssl/stack.h
t1_reneg.o: ../include/openssl/symhacks.h ../include/openssl/tls1.h
t1_reneg.o: ../include/openssl/x509.h ../include/openssl/x509_vfy.h ssl_locl.h
t1_reneg.o: t1_reneg.c
t1_srvr.o: ../e_os.h ../include/openssl/asn1.h ../include/openssl/bio.h
t1_srvr.o: ../include/openssl/buffer.h ../include/openssl/comp.h
t1_srvr.o: ../include/openssl/crypto.h ../include/openssl/dsa.h
t1_srvr.o: ../include/openssl/dtls1.h ../include/openssl/e_os2.h
t1_srvr.o: ../include/openssl/ec.h ../include/openssl/ecdh.h
t1_srvr.o: ../include/openssl/ecdsa.h ../include/openssl/err.h
t1_srvr.o: ../include/openssl/evp.h ../include/openssl/hmac.h
t1_srvr.o: ../include/openssl/kssl.h ../include/openssl/lhash.h
t1_srvr.o: ../include/openssl/obj_mac.h ../include/openssl/objects.h
t1_srvr.o: ../include/openssl/opensslconf.h ../include/openssl/opensslv.h
t1_srvr.o: ../include/openssl/ossl_typ.h ../include/openssl/pem.h
t1_srvr.o: ../include/openssl/pem2.h ../include/openssl/pkcs7.h
t1_srvr.o: ../include/openssl/pqueue.h ../include/openssl/rand.h
t1_srvr.o: ../include/openssl/rsa.h ../include/openssl/safestack.h
t1_srvr.o: ../include/openssl/sha.h ../include/openssl/srtp.h
t1_srvr.o: ../include/openssl/ssl.h ../include/openssl/ssl2.h
t1_srvr.o: ../include/openssl/ssl23.h ../include/openssl/ssl3.h
t1_srvr.o: ../include/openssl/stack.h ../include/openssl/symhacks.h
t1_srvr.o: ../include/openssl/tls1.h ../include/openssl/x509.h
t1_srvr.o: ../include/openssl/x509_vfy.h ssl_locl.h t1_srvr.c
t1_trce.o: ../e_os.h ../include/openssl/asn1.h ../include/openssl/bio.h
t1_trce.o: ../include/openssl/buffer.h ../include/openssl/comp.h
t1_trce.o: ../include/openssl/crypto.h ../include/openssl/dsa.h
t1_trce.o: ../include/openssl/dtls1.h ../include/openssl/e_os2.h
t1_trce.o: ../include/openssl/ec.h ../include/openssl/ecdh.h
t1_trce.o: ../include/openssl/ecdsa.h ../include/openssl/err.h
t1_trce.o: ../include/openssl/evp.h ../include/openssl/hmac.h
t1_trce.o: ../include/openssl/kssl.h ../include/openssl/lhash.h
t1_trce.o: ../include/openssl/obj_mac.h ../include/openssl/objects.h
t1_trce.o: ../include/openssl/opensslconf.h ../include/openssl/opensslv.h
t1_trce.o: ../include/openssl/ossl_typ.h ../include/openssl/pem.h
t1_trce.o: ../include/openssl/pem2.h ../include/openssl/pkcs7.h
t1_trce.o: ../include/openssl/pqueue.h ../include/openssl/rsa.h
t1_trce.o: ../include/openssl/safestack.h ../include/openssl/sha.h
t1_trce.o: ../include/openssl/srtp.h ../include/openssl/ssl.h
t1_trce.o: ../include/openssl/ssl2.h ../include/openssl/ssl23.h
t1_trce.o: ../include/openssl/ssl3.h ../include/openssl/stack.h
t1_trce.o: ../include/openssl/symhacks.h ../include/openssl/tls1.h
t1_trce.o: ../include/openssl/x509.h ../include/openssl/x509_vfy.h ssl_locl.h
t1_trce.o: t1_trce.c
tls_srp.o: ../e_os.h ../include/openssl/asn1.h ../include/openssl/bio.h
tls_srp.o: ../include/openssl/bn.h ../include/openssl/buffer.h
tls_srp.o: ../include/openssl/comp.h ../include/openssl/crypto.h
tls_srp.o: ../include/openssl/dsa.h ../include/openssl/dtls1.h
tls_srp.o: ../include/openssl/e_os2.h ../include/openssl/ec.h
tls_srp.o: ../include/openssl/ecdh.h ../include/openssl/ecdsa.h
tls_srp.o: ../include/openssl/err.h ../include/openssl/evp.h
tls_srp.o: ../include/openssl/hmac.h ../include/openssl/kssl.h
tls_srp.o: ../include/openssl/lhash.h ../include/openssl/obj_mac.h
tls_srp.o: ../include/openssl/objects.h ../include/openssl/opensslconf.h
tls_srp.o: ../include/openssl/opensslv.h ../include/openssl/ossl_typ.h
tls_srp.o: ../include/openssl/pem.h ../include/openssl/pem2.h
tls_srp.o: ../include/openssl/pkcs7.h ../include/openssl/pqueue.h
tls_srp.o: ../include/openssl/rand.h ../include/openssl/rsa.h
tls_srp.o: ../include/openssl/safestack.h ../include/openssl/sha.h
tls_srp.o: ../include/openssl/srp.h ../include/openssl/srtp.h
tls_srp.o: ../include/openssl/ssl.h ../include/openssl/ssl2.h
tls_srp.o: ../include/openssl/ssl23.h ../include/openssl/ssl3.h
tls_srp.o: ../include/openssl/stack.h ../include/openssl/symhacks.h
tls_srp.o: ../include/openssl/tls1.h ../include/openssl/x509.h
tls_srp.o: ../include/openssl/x509_vfy.h ssl_locl.h tls_srp.c
diff --git a/ssl/bad_dtls_test.c b/ssl/bad_dtls_test.c
index 34af37d9a9f4..ff754e1e497b 100644
--- a/ssl/bad_dtls_test.c
+++ b/ssl/bad_dtls_test.c
@@ -1,926 +1,926 @@
/*
* Copyright 2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
/*
* Unit test for Cisco DTLS1_BAD_VER session resume, as used by
* AnyConnect VPN protocol.
*
* This is designed to exercise the code paths in
* http://git.infradead.org/users/dwmw2/openconnect.git/blob/HEAD:/dtls.c
* which have frequently been affected by regressions in DTLS1_BAD_VER
* support.
*
* Note that unlike other SSL tests, we don't test against our own SSL
* server method. Firstly because we don't have one; we *only* support
* DTLS1_BAD_VER as a client. And secondly because even if that were
- * fixed up it's the wrong thing to test against — because if changes
+ * fixed up it's the wrong thing to test against - because if changes
* are made in generic DTLS code which don't take DTLS1_BAD_VER into
* account, there's plenty of scope for making those changes such that
* they break *both* the client and the server in the same way.
*
* So we handle the server side manually. In a session resume there isn't
* much to be done anyway.
*/
#include <string.h>
/* On Windows this will include <winsock2.h> and thus it needs to be
* included *before* anything that includes <windows.h>. Ick. */
#include "e_os.h" /* for 'inline' */
#include <openssl/bio.h>
#include <openssl/crypto.h>
#include <openssl/evp.h>
#include <openssl/ssl.h>
#include <openssl/err.h>
#include <openssl/rand.h>
/* PACKET functions lifted from OpenSSL 1.1's ssl/packet_locl.h */
typedef struct {
/* Pointer to where we are currently reading from */
const unsigned char *curr;
/* Number of bytes remaining */
size_t remaining;
} PACKET;
/* Internal unchecked shorthand; don't use outside this file. */
static inline void packet_forward(PACKET *pkt, size_t len)
{
pkt->curr += len;
pkt->remaining -= len;
}
/*
* Returns the number of bytes remaining to be read in the PACKET
*/
static inline size_t PACKET_remaining(const PACKET *pkt)
{
return pkt->remaining;
}
/*
* Initialise a PACKET with |len| bytes held in |buf|. This does not make a
* copy of the data so |buf| must be present for the whole time that the PACKET
* is being used.
*/
static inline int PACKET_buf_init(PACKET *pkt,
const unsigned char *buf,
size_t len)
{
/* Sanity check for negative values. */
if (len > (size_t)65536)
return 0;
pkt->curr = buf;
pkt->remaining = len;
return 1;
}
/*
* Returns 1 if the packet has length |num| and its contents equal the |num|
* bytes read from |ptr|. Returns 0 otherwise (lengths or contents not equal).
* If lengths are equal, performs the comparison in constant time.
*/
static inline int PACKET_equal(const PACKET *pkt, const void *ptr,
size_t num)
{
if (PACKET_remaining(pkt) != num)
return 0;
return CRYPTO_memcmp(pkt->curr, ptr, num) == 0;
}
/*
* Peek ahead at 2 bytes in network order from |pkt| and store the value in
* |*data|
*/
static inline int PACKET_peek_net_2(const PACKET *pkt,
unsigned int *data)
{
if (PACKET_remaining(pkt) < 2)
return 0;
*data = ((unsigned int)(*pkt->curr)) << 8;
*data |= *(pkt->curr + 1);
return 1;
}
/* Equivalent of n2s */
/* Get 2 bytes in network order from |pkt| and store the value in |*data| */
static inline int PACKET_get_net_2(PACKET *pkt,
unsigned int *data)
{
if (!PACKET_peek_net_2(pkt, data))
return 0;
packet_forward(pkt, 2);
return 1;
}
/* Peek ahead at 1 byte from |pkt| and store the value in |*data| */
static inline int PACKET_peek_1(const PACKET *pkt,
unsigned int *data)
{
if (!PACKET_remaining(pkt))
return 0;
*data = *pkt->curr;
return 1;
}
/* Get 1 byte from |pkt| and store the value in |*data| */
static inline int PACKET_get_1(PACKET *pkt, unsigned int *data)
{
if (!PACKET_peek_1(pkt, data))
return 0;
packet_forward(pkt, 1);
return 1;
}
/*
* Peek ahead at |len| bytes from the |pkt| and store a pointer to them in
* |*data|. This just points at the underlying buffer that |pkt| is using. The
* caller should not free this data directly (it will be freed when the
* underlying buffer gets freed
*/
static inline int PACKET_peek_bytes(const PACKET *pkt,
const unsigned char **data,
size_t len)
{
if (PACKET_remaining(pkt) < len)
return 0;
*data = pkt->curr;
return 1;
}
/*
* Read |len| bytes from the |pkt| and store a pointer to them in |*data|. This
* just points at the underlying buffer that |pkt| is using. The caller should
* not free this data directly (it will be freed when the underlying buffer gets
* freed
*/
static inline int PACKET_get_bytes(PACKET *pkt,
const unsigned char **data,
size_t len)
{
if (!PACKET_peek_bytes(pkt, data, len))
return 0;
packet_forward(pkt, len);
return 1;
}
/* Peek ahead at |len| bytes from |pkt| and copy them to |data| */
static inline int PACKET_peek_copy_bytes(const PACKET *pkt,
unsigned char *data,
size_t len)
{
if (PACKET_remaining(pkt) < len)
return 0;
memcpy(data, pkt->curr, len);
return 1;
}
/*
* Read |len| bytes from |pkt| and copy them to |data|.
* The caller is responsible for ensuring that |data| can hold |len| bytes.
*/
static inline int PACKET_copy_bytes(PACKET *pkt,
unsigned char *data,
size_t len)
{
if (!PACKET_peek_copy_bytes(pkt, data, len))
return 0;
packet_forward(pkt, len);
return 1;
}
/* Move the current reading position forward |len| bytes */
static inline int PACKET_forward(PACKET *pkt, size_t len)
{
if (PACKET_remaining(pkt) < len)
return 0;
packet_forward(pkt, len);
return 1;
}
/*
* Reads a variable-length vector prefixed with a one-byte length, and stores
* the contents in |subpkt|. |pkt| can equal |subpkt|.
* Data is not copied: the |subpkt| packet will share its underlying buffer with
* the original |pkt|, so data wrapped by |pkt| must outlive the |subpkt|.
* Upon failure, the original |pkt| and |subpkt| are not modified.
*/
static inline int PACKET_get_length_prefixed_1(PACKET *pkt,
PACKET *subpkt)
{
unsigned int length;
const unsigned char *data;
PACKET tmp = *pkt;
if (!PACKET_get_1(&tmp, &length) ||
!PACKET_get_bytes(&tmp, &data, (size_t)length)) {
return 0;
}
*pkt = tmp;
subpkt->curr = data;
subpkt->remaining = length;
return 1;
}
#define OSSL_NELEM(x) (sizeof(x)/sizeof(x[0]))
/* For DTLS1_BAD_VER packets the MAC doesn't include the handshake header */
#define MAC_OFFSET (DTLS1_RT_HEADER_LENGTH + DTLS1_HM_HEADER_LENGTH)
static unsigned char client_random[SSL3_RANDOM_SIZE];
static unsigned char server_random[SSL3_RANDOM_SIZE];
/* These are all generated locally, sized purely according to our own whim */
static unsigned char session_id[32];
static unsigned char master_secret[48];
static unsigned char cookie[20];
/* We've hard-coded the cipher suite; we know it's 104 bytes */
static unsigned char key_block[104];
#define mac_key (key_block + 20)
#define dec_key (key_block + 40)
#define enc_key (key_block + 56)
static EVP_MD_CTX handshake_md5;
static EVP_MD_CTX handshake_sha1;
/* PRF lifted from ssl/t1_enc.c since we can't easily use it directly */
static int tls1_P_hash(const EVP_MD *md, const unsigned char *sec,
int sec_len,
const void *seed1, int seed1_len,
const void *seed2, int seed2_len,
const void *seed3, int seed3_len,
unsigned char *out, int olen)
{
int chunk;
size_t j;
EVP_MD_CTX ctx, ctx_tmp, ctx_init;
EVP_PKEY *prf_mac_key;
unsigned char A1[EVP_MAX_MD_SIZE];
size_t A1_len;
int ret = 0;
chunk = EVP_MD_size(md);
OPENSSL_assert(chunk >= 0);
EVP_MD_CTX_init(&ctx);
EVP_MD_CTX_init(&ctx_tmp);
EVP_MD_CTX_init(&ctx_init);
EVP_MD_CTX_set_flags(&ctx_init, EVP_MD_CTX_FLAG_NON_FIPS_ALLOW);
prf_mac_key = EVP_PKEY_new_mac_key(EVP_PKEY_HMAC, NULL, sec, sec_len);
if (!prf_mac_key)
goto err;
if (!EVP_DigestSignInit(&ctx_init, NULL, md, NULL, prf_mac_key))
goto err;
if (!EVP_MD_CTX_copy_ex(&ctx, &ctx_init))
goto err;
if (seed1 && !EVP_DigestSignUpdate(&ctx, seed1, seed1_len))
goto err;
if (seed2 && !EVP_DigestSignUpdate(&ctx, seed2, seed2_len))
goto err;
if (seed3 && !EVP_DigestSignUpdate(&ctx, seed3, seed3_len))
goto err;
if (!EVP_DigestSignFinal(&ctx, A1, &A1_len))
goto err;
for (;;) {
/* Reinit mac contexts */
if (!EVP_MD_CTX_copy_ex(&ctx, &ctx_init))
goto err;
if (!EVP_DigestSignUpdate(&ctx, A1, A1_len))
goto err;
if (olen > chunk && !EVP_MD_CTX_copy_ex(&ctx_tmp, &ctx))
goto err;
if (seed1 && !EVP_DigestSignUpdate(&ctx, seed1, seed1_len))
goto err;
if (seed2 && !EVP_DigestSignUpdate(&ctx, seed2, seed2_len))
goto err;
if (seed3 && !EVP_DigestSignUpdate(&ctx, seed3, seed3_len))
goto err;
if (olen > chunk) {
if (!EVP_DigestSignFinal(&ctx, out, &j))
goto err;
out += j;
olen -= j;
/* calc the next A1 value */
if (!EVP_DigestSignFinal(&ctx_tmp, A1, &A1_len))
goto err;
} else { /* last one */
if (!EVP_DigestSignFinal(&ctx, A1, &A1_len))
goto err;
memcpy(out, A1, olen);
break;
}
}
ret = 1;
err:
EVP_PKEY_free(prf_mac_key);
EVP_MD_CTX_cleanup(&ctx);
EVP_MD_CTX_cleanup(&ctx_tmp);
EVP_MD_CTX_cleanup(&ctx_init);
OPENSSL_cleanse(A1, sizeof(A1));
return ret;
}
/* seed1 through seed5 are virtually concatenated */
static int do_PRF(const void *seed1, int seed1_len,
const void *seed2, int seed2_len,
const void *seed3, int seed3_len,
unsigned char *out, int olen)
{
unsigned char out2[104];
int i, len;
if (olen > (int)sizeof(out2))
return 0;
len = sizeof(master_secret) / 2;
if (!tls1_P_hash(EVP_md5(), master_secret, len,
seed1, seed1_len, seed2, seed2_len, seed3,
seed3_len, out, olen))
return 0;
if (!tls1_P_hash(EVP_sha1(), master_secret + len, len,
seed1, seed1_len, seed2, seed2_len, seed3,
seed3_len, out2, olen))
return 0;
for (i = 0; i < olen; i++) {
out[i] ^= out2[i];
}
return 1;
}
static SSL_SESSION *client_session(void)
{
static unsigned char session_asn1[] = {
0x30, 0x5F, /* SEQUENCE, length 0x5F */
0x02, 0x01, 0x01, /* INTEGER, SSL_SESSION_ASN1_VERSION */
0x02, 0x02, 0x01, 0x00, /* INTEGER, DTLS1_BAD_VER */
0x04, 0x02, 0x00, 0x2F, /* OCTET_STRING, AES128-SHA */
0x04, 0x20, /* OCTET_STRING, session id */
#define SS_SESSID_OFS 15 /* Session ID goes here */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x04, 0x30, /* OCTET_STRING, master secret */
#define SS_SECRET_OFS 49 /* Master secret goes here */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
};
const unsigned char *p = session_asn1;
/* Copy the randomly-generated fields into the above ASN1 */
memcpy(session_asn1 + SS_SESSID_OFS, session_id, sizeof(session_id));
memcpy(session_asn1 + SS_SECRET_OFS, master_secret, sizeof(master_secret));
return d2i_SSL_SESSION(NULL, &p, sizeof(session_asn1));
}
/* Returns 1 for initial ClientHello, 2 for ClientHello with cookie */
static int validate_client_hello(BIO *wbio)
{
PACKET pkt, pkt2;
long len;
unsigned char *data;
int cookie_found = 0;
unsigned int u;
len = BIO_get_mem_data(wbio, (char **)&data);
if (!PACKET_buf_init(&pkt, data, len))
return 0;
/* Check record header type */
if (!PACKET_get_1(&pkt, &u) || u != SSL3_RT_HANDSHAKE)
return 0;
/* Version */
if (!PACKET_get_net_2(&pkt, &u) || u != DTLS1_BAD_VER)
return 0;
/* Skip the rest of the record header */
if (!PACKET_forward(&pkt, DTLS1_RT_HEADER_LENGTH - 3))
return 0;
/* Check it's a ClientHello */
if (!PACKET_get_1(&pkt, &u) || u != SSL3_MT_CLIENT_HELLO)
return 0;
/* Skip the rest of the handshake message header */
if (!PACKET_forward(&pkt, DTLS1_HM_HEADER_LENGTH - 1))
return 0;
/* Check client version */
if (!PACKET_get_net_2(&pkt, &u) || u != DTLS1_BAD_VER)
return 0;
/* Store random */
if (!PACKET_copy_bytes(&pkt, client_random, SSL3_RANDOM_SIZE))
return 0;
/* Check session id length and content */
if (!PACKET_get_length_prefixed_1(&pkt, &pkt2) ||
!PACKET_equal(&pkt2, session_id, sizeof(session_id)))
return 0;
/* Check cookie */
if (!PACKET_get_length_prefixed_1(&pkt, &pkt2))
return 0;
if (PACKET_remaining(&pkt2)) {
if (!PACKET_equal(&pkt2, cookie, sizeof(cookie)))
return 0;
cookie_found = 1;
}
/* Skip ciphers */
if (!PACKET_get_net_2(&pkt, &u) || !PACKET_forward(&pkt, u))
return 0;
/* Skip compression */
if (!PACKET_get_1(&pkt, &u) || !PACKET_forward(&pkt, u))
return 0;
/* Skip extensions */
if (!PACKET_get_net_2(&pkt, &u) || !PACKET_forward(&pkt, u))
return 0;
/* Now we are at the end */
if (PACKET_remaining(&pkt))
return 0;
/* Update handshake MAC for second ClientHello (with cookie) */
if (cookie_found && (!EVP_DigestUpdate(&handshake_md5, data + MAC_OFFSET,
len - MAC_OFFSET) ||
!EVP_DigestUpdate(&handshake_sha1, data + MAC_OFFSET,
len - MAC_OFFSET)))
printf("EVP_DigestUpdate() failed\n");
(void)BIO_reset(wbio);
return 1 + cookie_found;
}
static int send_hello_verify(BIO *rbio)
{
static unsigned char hello_verify[] = {
0x16, /* Handshake */
0x01, 0x00, /* DTLS1_BAD_VER */
0x00, 0x00, /* Epoch 0 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* Seq# 0 */
0x00, 0x23, /* Length */
0x03, /* Hello Verify */
0x00, 0x00, 0x17, /* Length */
0x00, 0x00, /* Seq# 0 */
0x00, 0x00, 0x00, /* Fragment offset */
0x00, 0x00, 0x17, /* Fragment length */
0x01, 0x00, /* DTLS1_BAD_VER */
0x14, /* Cookie length */
#define HV_COOKIE_OFS 28 /* Cookie goes here */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
};
memcpy(hello_verify + HV_COOKIE_OFS, cookie, sizeof(cookie));
BIO_write(rbio, hello_verify, sizeof(hello_verify));
return 1;
}
static int send_server_hello(BIO *rbio)
{
static unsigned char server_hello[] = {
0x16, /* Handshake */
0x01, 0x00, /* DTLS1_BAD_VER */
0x00, 0x00, /* Epoch 0 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x01, /* Seq# 1 */
0x00, 0x52, /* Length */
0x02, /* Server Hello */
0x00, 0x00, 0x46, /* Length */
0x00, 0x01, /* Seq# */
0x00, 0x00, 0x00, /* Fragment offset */
0x00, 0x00, 0x46, /* Fragment length */
0x01, 0x00, /* DTLS1_BAD_VER */
#define SH_RANDOM_OFS 27 /* Server random goes here */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x20, /* Session ID length */
#define SH_SESSID_OFS 60 /* Session ID goes here */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x2f, /* Cipher suite AES128-SHA */
0x00, /* Compression null */
};
static unsigned char change_cipher_spec[] = {
0x14, /* Change Cipher Spec */
0x01, 0x00, /* DTLS1_BAD_VER */
0x00, 0x00, /* Epoch 0 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x02, /* Seq# 2 */
0x00, 0x03, /* Length */
0x01, 0x00, 0x02, /* Message */
};
memcpy(server_hello + SH_RANDOM_OFS, server_random, sizeof(server_random));
memcpy(server_hello + SH_SESSID_OFS, session_id, sizeof(session_id));
if (!EVP_DigestUpdate(&handshake_md5, server_hello + MAC_OFFSET,
sizeof(server_hello) - MAC_OFFSET) ||
!EVP_DigestUpdate(&handshake_sha1, server_hello + MAC_OFFSET,
sizeof(server_hello) - MAC_OFFSET))
printf("EVP_DigestUpdate() failed\n");
BIO_write(rbio, server_hello, sizeof(server_hello));
BIO_write(rbio, change_cipher_spec, sizeof(change_cipher_spec));
return 1;
}
/* Create header, HMAC, pad, encrypt and send a record */
static int send_record(BIO *rbio, unsigned char type, unsigned long seqnr,
const void *msg, size_t len)
{
/* Note that the order of the record header fields on the wire,
* and in the HMAC, is different. So we just keep them in separate
* variables and handle them individually. */
static unsigned char epoch[2] = { 0x00, 0x01 };
static unsigned char seq[6] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
static unsigned char ver[2] = { 0x01, 0x00 }; /* DTLS1_BAD_VER */
unsigned char lenbytes[2];
HMAC_CTX ctx;
EVP_CIPHER_CTX enc_ctx;
unsigned char iv[16];
unsigned char pad;
unsigned char *enc;
#ifdef SIXTY_FOUR_BIT_LONG
seq[0] = (unsigned char)(seqnr >> 40);
seq[1] = (unsigned char)(seqnr >> 32);
#endif
seq[2] = (unsigned char)(seqnr >> 24);
seq[3] = (unsigned char)(seqnr >> 16);
seq[4] = (unsigned char)(seqnr >> 8);
seq[5] = (unsigned char)(seqnr);
pad = 15 - ((len + SHA_DIGEST_LENGTH) % 16);
enc = OPENSSL_malloc(len + SHA_DIGEST_LENGTH + 1 + pad);
if (enc == NULL)
return 0;
/* Copy record to encryption buffer */
memcpy(enc, msg, len);
/* Append HMAC to data */
HMAC_Init(&ctx, mac_key, 20, EVP_sha1());
HMAC_Update(&ctx, epoch, 2);
HMAC_Update(&ctx, seq, 6);
HMAC_Update(&ctx, &type, 1);
HMAC_Update(&ctx, ver, 2); /* Version */
lenbytes[0] = (unsigned char)(len >> 8);
lenbytes[1] = (unsigned char)(len);
HMAC_Update(&ctx, lenbytes, 2); /* Length */
HMAC_Update(&ctx, enc, len); /* Finally the data itself */
HMAC_Final(&ctx, enc + len, NULL);
HMAC_CTX_cleanup(&ctx);
/* Append padding bytes */
len += SHA_DIGEST_LENGTH;
do {
enc[len++] = pad;
} while (len % 16);
/* Generate IV, and encrypt */
RAND_bytes(iv, sizeof(iv));
EVP_CIPHER_CTX_init(&enc_ctx);
EVP_CipherInit_ex(&enc_ctx, EVP_aes_128_cbc(), NULL, enc_key, iv, 1);
EVP_Cipher(&enc_ctx, enc, enc, len);
EVP_CIPHER_CTX_cleanup(&enc_ctx);
/* Finally write header (from fragmented variables), IV and encrypted record */
BIO_write(rbio, &type, 1);
BIO_write(rbio, ver, 2);
BIO_write(rbio, epoch, 2);
BIO_write(rbio, seq, 6);
lenbytes[0] = (unsigned char)((len + sizeof(iv)) >> 8);
lenbytes[1] = (unsigned char)(len + sizeof(iv));
BIO_write(rbio, lenbytes, 2);
BIO_write(rbio, iv, sizeof(iv));
BIO_write(rbio, enc, len);
OPENSSL_free(enc);
return 1;
}
static int send_finished(SSL *s, BIO *rbio)
{
static unsigned char finished_msg[DTLS1_HM_HEADER_LENGTH +
TLS1_FINISH_MAC_LENGTH] = {
0x14, /* Finished */
0x00, 0x00, 0x0c, /* Length */
0x00, 0x03, /* Seq# 3 */
0x00, 0x00, 0x00, /* Fragment offset */
0x00, 0x00, 0x0c, /* Fragment length */
/* Finished MAC (12 bytes) */
};
unsigned char handshake_hash[EVP_MAX_MD_SIZE * 2];
/* Derive key material */
do_PRF(TLS_MD_KEY_EXPANSION_CONST, TLS_MD_KEY_EXPANSION_CONST_SIZE,
server_random, SSL3_RANDOM_SIZE,
client_random, SSL3_RANDOM_SIZE,
key_block, sizeof(key_block));
/* Generate Finished MAC */
if (!EVP_DigestFinal_ex(&handshake_md5, handshake_hash, NULL) ||
!EVP_DigestFinal_ex(&handshake_sha1, handshake_hash + EVP_MD_CTX_size(&handshake_md5), NULL))
printf("EVP_DigestFinal_ex() failed\n");
do_PRF(TLS_MD_SERVER_FINISH_CONST, TLS_MD_SERVER_FINISH_CONST_SIZE,
handshake_hash, EVP_MD_CTX_size(&handshake_md5) + EVP_MD_CTX_size(&handshake_sha1),
NULL, 0,
finished_msg + DTLS1_HM_HEADER_LENGTH, TLS1_FINISH_MAC_LENGTH);
return send_record(rbio, SSL3_RT_HANDSHAKE, 0,
finished_msg, sizeof(finished_msg));
}
static int validate_ccs(BIO *wbio)
{
PACKET pkt;
long len;
unsigned char *data;
unsigned int u;
len = BIO_get_mem_data(wbio, (char **)&data);
if (!PACKET_buf_init(&pkt, data, len))
return 0;
/* Check record header type */
if (!PACKET_get_1(&pkt, &u) || u != SSL3_RT_CHANGE_CIPHER_SPEC)
return 0;
/* Version */
if (!PACKET_get_net_2(&pkt, &u) || u != DTLS1_BAD_VER)
return 0;
/* Skip the rest of the record header */
if (!PACKET_forward(&pkt, DTLS1_RT_HEADER_LENGTH - 3))
return 0;
/* Check ChangeCipherSpec message */
if (!PACKET_get_1(&pkt, &u) || u != SSL3_MT_CCS)
return 0;
/* A DTLS1_BAD_VER ChangeCipherSpec also contains the
* handshake sequence number (which is 2 here) */
if (!PACKET_get_net_2(&pkt, &u) || u != 0x0002)
return 0;
/* Now check the Finished packet */
if (!PACKET_get_1(&pkt, &u) || u != SSL3_RT_HANDSHAKE)
return 0;
if (!PACKET_get_net_2(&pkt, &u) || u != DTLS1_BAD_VER)
return 0;
/* Check epoch is now 1 */
if (!PACKET_get_net_2(&pkt, &u) || u != 0x0001)
return 0;
/* That'll do for now. If OpenSSL accepted *our* Finished packet
* then it's evidently remembered that DTLS1_BAD_VER doesn't
* include the handshake header in the MAC. There's not a lot of
* point in implementing decryption here, just to check that it
* continues to get it right for one more packet. */
return 1;
}
#define NODROP(x) { x##UL, 0 }
#define DROP(x) { x##UL, 1 }
static struct {
unsigned long seq;
int drop;
} tests[] = {
NODROP(1), NODROP(3), NODROP(2),
NODROP(0x1234), NODROP(0x1230), NODROP(0x1235),
NODROP(0xffff), NODROP(0x10001), NODROP(0xfffe), NODROP(0x10000),
DROP(0x10001), DROP(0xff), NODROP(0x100000), NODROP(0x800000), NODROP(0x7fffe1),
NODROP(0xffffff), NODROP(0x1000000), NODROP(0xfffffe), DROP(0xffffff), NODROP(0x1000010),
NODROP(0xfffffd), NODROP(0x1000011), DROP(0x12), NODROP(0x1000012),
NODROP(0x1ffffff), NODROP(0x2000000), DROP(0x1ff00fe), NODROP(0x2000001),
NODROP(0x20fffff), NODROP(0x2105500), DROP(0x20ffffe), NODROP(0x21054ff),
NODROP(0x211ffff), DROP(0x2110000), NODROP(0x2120000)
/* The last test should be NODROP, because a DROP wouldn't get tested. */
};
int main(int argc, char *argv[])
{
SSL_SESSION *sess;
SSL_CTX *ctx;
SSL *con;
BIO *rbio;
BIO *wbio;
BIO *err;
time_t now = 0;
int testresult = 0;
int ret;
int i;
SSL_library_init();
SSL_load_error_strings();
err = BIO_new_fp(stderr, BIO_NOCLOSE | BIO_FP_TEXT);
CRYPTO_malloc_debug_init();
CRYPTO_set_mem_debug_options(V_CRYPTO_MDEBUG_ALL);
CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON);
RAND_bytes(session_id, sizeof(session_id));
RAND_bytes(master_secret, sizeof(master_secret));
RAND_bytes(cookie, sizeof(cookie));
RAND_bytes(server_random + 4, sizeof(server_random) - 4);
now = time(NULL);
memcpy(server_random, &now, sizeof(now));
sess = client_session();
if (sess == NULL) {
printf("Failed to generate SSL_SESSION\n");
goto end;
}
if (!EVP_DigestInit_ex(&handshake_md5, EVP_md5(), NULL) ||
!EVP_DigestInit_ex(&handshake_sha1, EVP_sha1(), NULL)) {
printf("Failed to initialise handshake_md\n");
goto end;
}
ctx = SSL_CTX_new(DTLSv1_client_method());
if (ctx == NULL) {
printf("Failed to allocate SSL_CTX\n");
goto end_md;
}
SSL_CTX_set_options(ctx, SSL_OP_CISCO_ANYCONNECT);
if (!SSL_CTX_set_cipher_list(ctx, "AES128-SHA")) {
printf("SSL_CTX_set_cipher_list() failed\n");
goto end_ctx;
}
con = SSL_new(ctx);
if (!SSL_set_session(con, sess)) {
printf("SSL_set_session() failed\n");
goto end_con;
}
SSL_SESSION_free(sess);
rbio = BIO_new(BIO_s_mem());
wbio = BIO_new(BIO_s_mem());
BIO_set_nbio(rbio, 1);
BIO_set_nbio(wbio, 1);
SSL_set_bio(con, rbio, wbio);
SSL_set_connect_state(con);
/* Send initial ClientHello */
ret = SSL_do_handshake(con);
if (ret > 0 || SSL_get_error(con, ret) != SSL_ERROR_WANT_READ) {
printf("Unexpected handshake result at initial call!\n");
goto end_con;
}
if (validate_client_hello(wbio) != 1) {
printf("Initial ClientHello failed validation\n");
goto end_con;
}
if (send_hello_verify(rbio) != 1) {
printf("Failed to send HelloVerify\n");
goto end_con;
}
ret = SSL_do_handshake(con);
if (ret > 0 || SSL_get_error(con, ret) != SSL_ERROR_WANT_READ) {
printf("Unexpected handshake result after HelloVerify!\n");
goto end_con;
}
if (validate_client_hello(wbio) != 2) {
printf("Second ClientHello failed validation\n");
goto end_con;
}
if (send_server_hello(rbio) != 1) {
printf("Failed to send ServerHello\n");
goto end_con;
}
ret = SSL_do_handshake(con);
if (ret > 0 || SSL_get_error(con, ret) != SSL_ERROR_WANT_READ) {
printf("Unexpected handshake result after ServerHello!\n");
goto end_con;
}
if (send_finished(con, rbio) != 1) {
printf("Failed to send Finished\n");
goto end_con;
}
ret = SSL_do_handshake(con);
if (ret < 1) {
printf("Handshake not successful after Finished!\n");
goto end_con;
}
if (validate_ccs(wbio) != 1) {
printf("Failed to validate client CCS/Finished\n");
goto end_con;
}
/* While we're here and crafting packets by hand, we might as well do a
bit of a stress test on the DTLS record replay handling. Not Cisco-DTLS
specific but useful anyway for the general case. It's been broken
before, and in fact was broken even for a basic 0, 2, 1 test case
when this test was first added.... */
for (i = 0; i < (int)OSSL_NELEM(tests); i++) {
unsigned long recv_buf[2];
if (send_record(rbio, SSL3_RT_APPLICATION_DATA, tests[i].seq,
&tests[i].seq, sizeof(unsigned long)) != 1) {
printf("Failed to send data seq #0x%lx (%d)\n",
tests[i].seq, i);
goto end_con;
}
if (tests[i].drop)
continue;
ret = SSL_read(con, recv_buf, 2 * sizeof(unsigned long));
if (ret != sizeof(unsigned long)) {
printf("SSL_read failed or wrong size on seq#0x%lx (%d)\n",
tests[i].seq, i);
goto end_con;
}
if (recv_buf[0] != tests[i].seq) {
printf("Wrong data packet received (0x%lx not 0x%lx) at packet %d\n",
recv_buf[0], tests[i].seq, i);
goto end_con;
}
}
if (tests[i-1].drop) {
printf("Error: last test cannot be DROP()\n");
goto end_con;
}
testresult=1;
end_con:
SSL_free(con);
end_ctx:
SSL_CTX_free(ctx);
end_md:
EVP_MD_CTX_cleanup(&handshake_md5);
EVP_MD_CTX_cleanup(&handshake_sha1);
end:
ERR_print_errors_fp(stderr);
if (!testresult) {
printf("Cisco BadDTLS test: FAILED\n");
}
ERR_free_strings();
ERR_remove_thread_state(NULL);
EVP_cleanup();
CRYPTO_cleanup_all_ex_data();
CRYPTO_mem_leaks(err);
BIO_free(err);
return testresult?0:1;
}
diff --git a/ssl/d1_lib.c b/ssl/d1_lib.c
index debd4fd5dcca..95b5033d3d33 100644
--- a/ssl/d1_lib.c
+++ b/ssl/d1_lib.c
@@ -1,588 +1,588 @@
/* ssl/d1_lib.c */
/*
* DTLS implementation written by Nagendra Modadugu
* (nagendra@cs.stanford.edu) for the OpenSSL project 2005.
*/
/* ====================================================================
* Copyright (c) 1999-2005 The OpenSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* openssl-core@OpenSSL.org.
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*
* This product includes cryptographic software written by Eric Young
* (eay@cryptsoft.com). This product includes software written by Tim
* Hudson (tjh@cryptsoft.com).
*
*/
#include <stdio.h>
#define USE_SOCKETS
#include <openssl/objects.h>
#include "ssl_locl.h"
#if defined(OPENSSL_SYS_VMS)
# include <sys/timeb.h>
#endif
static void get_current_time(struct timeval *t);
static void dtls1_set_handshake_header(SSL *s, int type, unsigned long len);
static int dtls1_handshake_write(SSL *s);
const char dtls1_version_str[] = "DTLSv1" OPENSSL_VERSION_PTEXT;
int dtls1_listen(SSL *s, struct sockaddr *client);
SSL3_ENC_METHOD DTLSv1_enc_data = {
tls1_enc,
tls1_mac,
tls1_setup_key_block,
tls1_generate_master_secret,
tls1_change_cipher_state,
tls1_final_finish_mac,
TLS1_FINISH_MAC_LENGTH,
tls1_cert_verify_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_DTLS | SSL_ENC_FLAG_EXPLICIT_IV,
DTLS1_HM_HEADER_LENGTH,
dtls1_set_handshake_header,
dtls1_handshake_write
};
SSL3_ENC_METHOD DTLSv1_2_enc_data = {
tls1_enc,
tls1_mac,
tls1_setup_key_block,
tls1_generate_master_secret,
tls1_change_cipher_state,
tls1_final_finish_mac,
TLS1_FINISH_MAC_LENGTH,
tls1_cert_verify_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_DTLS | SSL_ENC_FLAG_EXPLICIT_IV | SSL_ENC_FLAG_SIGALGS
| SSL_ENC_FLAG_SHA256_PRF | SSL_ENC_FLAG_TLS1_2_CIPHERS,
DTLS1_HM_HEADER_LENGTH,
dtls1_set_handshake_header,
dtls1_handshake_write
};
long dtls1_default_timeout(void)
{
/*
* 2 hours, the 24 hours mentioned in the DTLSv1 spec is way too long for
* http, the cache would over fill
*/
return (60 * 60 * 2);
}
int dtls1_new(SSL *s)
{
DTLS1_STATE *d1;
if (!ssl3_new(s))
return (0);
- if ((d1 = OPENSSL_malloc(sizeof *d1)) == NULL)
+ if ((d1 = OPENSSL_malloc(sizeof(*d1))) == NULL)
return (0);
- memset(d1, 0, sizeof *d1);
+ memset(d1, 0, sizeof(*d1));
/* d1->handshake_epoch=0; */
d1->unprocessed_rcds.q = pqueue_new();
d1->processed_rcds.q = pqueue_new();
d1->buffered_messages = pqueue_new();
d1->sent_messages = pqueue_new();
d1->buffered_app_data.q = pqueue_new();
if (s->server) {
d1->cookie_len = sizeof(s->d1->cookie);
}
d1->link_mtu = 0;
d1->mtu = 0;
if (!d1->unprocessed_rcds.q || !d1->processed_rcds.q
|| !d1->buffered_messages || !d1->sent_messages
|| !d1->buffered_app_data.q) {
if (d1->unprocessed_rcds.q)
pqueue_free(d1->unprocessed_rcds.q);
if (d1->processed_rcds.q)
pqueue_free(d1->processed_rcds.q);
if (d1->buffered_messages)
pqueue_free(d1->buffered_messages);
if (d1->sent_messages)
pqueue_free(d1->sent_messages);
if (d1->buffered_app_data.q)
pqueue_free(d1->buffered_app_data.q);
OPENSSL_free(d1);
return (0);
}
s->d1 = d1;
s->method->ssl_clear(s);
return (1);
}
static void dtls1_clear_queues(SSL *s)
{
pitem *item = NULL;
DTLS1_RECORD_DATA *rdata;
while ((item = pqueue_pop(s->d1->unprocessed_rcds.q)) != NULL) {
rdata = (DTLS1_RECORD_DATA *)item->data;
if (rdata->rbuf.buf) {
OPENSSL_free(rdata->rbuf.buf);
}
OPENSSL_free(item->data);
pitem_free(item);
}
while ((item = pqueue_pop(s->d1->processed_rcds.q)) != NULL) {
rdata = (DTLS1_RECORD_DATA *)item->data;
if (rdata->rbuf.buf) {
OPENSSL_free(rdata->rbuf.buf);
}
OPENSSL_free(item->data);
pitem_free(item);
}
while ((item = pqueue_pop(s->d1->buffered_app_data.q)) != NULL) {
rdata = (DTLS1_RECORD_DATA *)item->data;
if (rdata->rbuf.buf) {
OPENSSL_free(rdata->rbuf.buf);
}
OPENSSL_free(item->data);
pitem_free(item);
}
dtls1_clear_received_buffer(s);
dtls1_clear_sent_buffer(s);
}
void dtls1_clear_received_buffer(SSL *s)
{
pitem *item = NULL;
hm_fragment *frag = NULL;
while ((item = pqueue_pop(s->d1->buffered_messages)) != NULL) {
frag = (hm_fragment *)item->data;
dtls1_hm_fragment_free(frag);
pitem_free(item);
}
}
void dtls1_clear_sent_buffer(SSL *s)
{
pitem *item = NULL;
hm_fragment *frag = NULL;
while ((item = pqueue_pop(s->d1->sent_messages)) != NULL) {
frag = (hm_fragment *)item->data;
dtls1_hm_fragment_free(frag);
pitem_free(item);
}
}
void dtls1_free(SSL *s)
{
ssl3_free(s);
dtls1_clear_queues(s);
pqueue_free(s->d1->unprocessed_rcds.q);
pqueue_free(s->d1->processed_rcds.q);
pqueue_free(s->d1->buffered_messages);
pqueue_free(s->d1->sent_messages);
pqueue_free(s->d1->buffered_app_data.q);
OPENSSL_free(s->d1);
s->d1 = NULL;
}
void dtls1_clear(SSL *s)
{
pqueue unprocessed_rcds;
pqueue processed_rcds;
pqueue buffered_messages;
pqueue sent_messages;
pqueue buffered_app_data;
unsigned int mtu;
unsigned int link_mtu;
if (s->d1) {
unprocessed_rcds = s->d1->unprocessed_rcds.q;
processed_rcds = s->d1->processed_rcds.q;
buffered_messages = s->d1->buffered_messages;
sent_messages = s->d1->sent_messages;
buffered_app_data = s->d1->buffered_app_data.q;
mtu = s->d1->mtu;
link_mtu = s->d1->link_mtu;
dtls1_clear_queues(s);
memset(s->d1, 0, sizeof(*(s->d1)));
if (s->server) {
s->d1->cookie_len = sizeof(s->d1->cookie);
}
if (SSL_get_options(s) & SSL_OP_NO_QUERY_MTU) {
s->d1->mtu = mtu;
s->d1->link_mtu = link_mtu;
}
s->d1->unprocessed_rcds.q = unprocessed_rcds;
s->d1->processed_rcds.q = processed_rcds;
s->d1->buffered_messages = buffered_messages;
s->d1->sent_messages = sent_messages;
s->d1->buffered_app_data.q = buffered_app_data;
}
ssl3_clear(s);
if (s->options & SSL_OP_CISCO_ANYCONNECT)
s->client_version = s->version = DTLS1_BAD_VER;
else if (s->method->version == DTLS_ANY_VERSION)
s->version = DTLS1_2_VERSION;
else
s->version = s->method->version;
}
long dtls1_ctrl(SSL *s, int cmd, long larg, void *parg)
{
int ret = 0;
switch (cmd) {
case DTLS_CTRL_GET_TIMEOUT:
if (dtls1_get_timeout(s, (struct timeval *)parg) != NULL) {
ret = 1;
}
break;
case DTLS_CTRL_HANDLE_TIMEOUT:
ret = dtls1_handle_timeout(s);
break;
case DTLS_CTRL_LISTEN:
ret = dtls1_listen(s, parg);
break;
case SSL_CTRL_CHECK_PROTO_VERSION:
/*
* For library-internal use; checks 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 == DTLS_method()->version) {
#if DTLS_MAX_VERSION != DTLS1_2_VERSION
# error Code needs update for DTLS_method() support beyond DTLS1_2_VERSION.
#endif
if (!(s->options & SSL_OP_NO_DTLSv1_2))
return s->version == DTLS1_2_VERSION;
if (!(s->options & SSL_OP_NO_DTLSv1))
return s->version == DTLS1_VERSION;
}
return 0; /* Unexpected state; fail closed. */
case DTLS_CTRL_SET_LINK_MTU:
if (larg < (long)dtls1_link_min_mtu())
return 0;
s->d1->link_mtu = larg;
return 1;
case DTLS_CTRL_GET_LINK_MIN_MTU:
return (long)dtls1_link_min_mtu();
case SSL_CTRL_SET_MTU:
/*
* We may not have a BIO set yet so can't call dtls1_min_mtu()
* We'll have to make do with dtls1_link_min_mtu() and max overhead
*/
if (larg < (long)dtls1_link_min_mtu() - DTLS1_MAX_MTU_OVERHEAD)
return 0;
s->d1->mtu = larg;
return larg;
default:
ret = ssl3_ctrl(s, cmd, larg, parg);
break;
}
return (ret);
}
/*
* As it's impossible to use stream ciphers in "datagram" mode, this
* simple filter is designed to disengage them in DTLS. Unfortunately
* there is no universal way to identify stream SSL_CIPHER, so we have
* to explicitly list their SSL_* codes. Currently RC4 is the only one
* available, but if new ones emerge, they will have to be added...
*/
const SSL_CIPHER *dtls1_get_cipher(unsigned int u)
{
const SSL_CIPHER *ciph = ssl3_get_cipher(u);
if (ciph != NULL) {
if (ciph->algorithm_enc == SSL_RC4)
return NULL;
}
return ciph;
}
void dtls1_start_timer(SSL *s)
{
#ifndef OPENSSL_NO_SCTP
/* Disable timer for SCTP */
if (BIO_dgram_is_sctp(SSL_get_wbio(s))) {
memset(&(s->d1->next_timeout), 0, sizeof(struct timeval));
return;
}
#endif
/* If timer is not set, initialize duration with 1 second */
if (s->d1->next_timeout.tv_sec == 0 && s->d1->next_timeout.tv_usec == 0) {
s->d1->timeout_duration = 1;
}
/* Set timeout to current time */
get_current_time(&(s->d1->next_timeout));
/* Add duration to current time */
s->d1->next_timeout.tv_sec += s->d1->timeout_duration;
BIO_ctrl(SSL_get_rbio(s), BIO_CTRL_DGRAM_SET_NEXT_TIMEOUT, 0,
&(s->d1->next_timeout));
}
struct timeval *dtls1_get_timeout(SSL *s, struct timeval *timeleft)
{
struct timeval timenow;
/* If no timeout is set, just return NULL */
if (s->d1->next_timeout.tv_sec == 0 && s->d1->next_timeout.tv_usec == 0) {
return NULL;
}
/* Get current time */
get_current_time(&timenow);
/* If timer already expired, set remaining time to 0 */
if (s->d1->next_timeout.tv_sec < timenow.tv_sec ||
(s->d1->next_timeout.tv_sec == timenow.tv_sec &&
s->d1->next_timeout.tv_usec <= timenow.tv_usec)) {
memset(timeleft, 0, sizeof(struct timeval));
return timeleft;
}
/* Calculate time left until timer expires */
memcpy(timeleft, &(s->d1->next_timeout), sizeof(struct timeval));
timeleft->tv_sec -= timenow.tv_sec;
timeleft->tv_usec -= timenow.tv_usec;
if (timeleft->tv_usec < 0) {
timeleft->tv_sec--;
timeleft->tv_usec += 1000000;
}
/*
* If remaining time is less than 15 ms, set it to 0 to prevent issues
* because of small devergences with socket timeouts.
*/
if (timeleft->tv_sec == 0 && timeleft->tv_usec < 15000) {
memset(timeleft, 0, sizeof(struct timeval));
}
return timeleft;
}
int dtls1_is_timer_expired(SSL *s)
{
struct timeval timeleft;
/* Get time left until timeout, return false if no timer running */
if (dtls1_get_timeout(s, &timeleft) == NULL) {
return 0;
}
/* Return false if timer is not expired yet */
if (timeleft.tv_sec > 0 || timeleft.tv_usec > 0) {
return 0;
}
/* Timer expired, so return true */
return 1;
}
void dtls1_double_timeout(SSL *s)
{
s->d1->timeout_duration *= 2;
if (s->d1->timeout_duration > 60)
s->d1->timeout_duration = 60;
dtls1_start_timer(s);
}
void dtls1_stop_timer(SSL *s)
{
/* Reset everything */
memset(&(s->d1->timeout), 0, sizeof(struct dtls1_timeout_st));
memset(&(s->d1->next_timeout), 0, sizeof(struct timeval));
s->d1->timeout_duration = 1;
BIO_ctrl(SSL_get_rbio(s), BIO_CTRL_DGRAM_SET_NEXT_TIMEOUT, 0,
&(s->d1->next_timeout));
/* Clear retransmission buffer */
dtls1_clear_sent_buffer(s);
}
int dtls1_check_timeout_num(SSL *s)
{
unsigned int mtu;
s->d1->timeout.num_alerts++;
/* Reduce MTU after 2 unsuccessful retransmissions */
if (s->d1->timeout.num_alerts > 2
&& !(SSL_get_options(s) & SSL_OP_NO_QUERY_MTU)) {
mtu =
BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_GET_FALLBACK_MTU, 0,
NULL);
if (mtu < s->d1->mtu)
s->d1->mtu = mtu;
}
if (s->d1->timeout.num_alerts > DTLS1_TMO_ALERT_COUNT) {
/* fail the connection, enough alerts have been sent */
SSLerr(SSL_F_DTLS1_CHECK_TIMEOUT_NUM, SSL_R_READ_TIMEOUT_EXPIRED);
return -1;
}
return 0;
}
int dtls1_handle_timeout(SSL *s)
{
/* if no timer is expired, don't do anything */
if (!dtls1_is_timer_expired(s)) {
return 0;
}
dtls1_double_timeout(s);
if (dtls1_check_timeout_num(s) < 0)
return -1;
s->d1->timeout.read_timeouts++;
if (s->d1->timeout.read_timeouts > DTLS1_TMO_READ_COUNT) {
s->d1->timeout.read_timeouts = 1;
}
#ifndef OPENSSL_NO_HEARTBEATS
if (s->tlsext_hb_pending) {
s->tlsext_hb_pending = 0;
return dtls1_heartbeat(s);
}
#endif
dtls1_start_timer(s);
return dtls1_retransmit_buffered_messages(s);
}
static void get_current_time(struct timeval *t)
{
#if defined(_WIN32)
SYSTEMTIME st;
union {
unsigned __int64 ul;
FILETIME ft;
} now;
GetSystemTime(&st);
SystemTimeToFileTime(&st, &now.ft);
# ifdef __MINGW32__
now.ul -= 116444736000000000ULL;
# else
now.ul -= 116444736000000000UI64; /* re-bias to 1/1/1970 */
# endif
t->tv_sec = (long)(now.ul / 10000000);
t->tv_usec = ((int)(now.ul % 10000000)) / 10;
#elif defined(OPENSSL_SYS_VMS)
struct timeb tb;
ftime(&tb);
t->tv_sec = (long)tb.time;
t->tv_usec = (long)tb.millitm * 1000;
#else
gettimeofday(t, NULL);
#endif
}
int dtls1_listen(SSL *s, struct sockaddr *client)
{
int ret;
/* Ensure there is no state left over from a previous invocation */
SSL_clear(s);
SSL_set_options(s, SSL_OP_COOKIE_EXCHANGE);
s->d1->listen = 1;
ret = SSL_accept(s);
if (ret <= 0)
return ret;
(void)BIO_dgram_get_peer(SSL_get_rbio(s), client);
return 1;
}
static void dtls1_set_handshake_header(SSL *s, int htype, unsigned long len)
{
unsigned char *p = (unsigned char *)s->init_buf->data;
dtls1_set_message_header(s, p, htype, len, 0, len);
s->init_num = (int)len + DTLS1_HM_HEADER_LENGTH;
s->init_off = 0;
/* Buffer the message to handle re-xmits */
dtls1_buffer_message(s, 0);
}
static int dtls1_handshake_write(SSL *s)
{
return dtls1_do_write(s, SSL3_RT_HANDSHAKE);
}
diff --git a/ssl/d1_pkt.c b/ssl/d1_pkt.c
index 10586fee5408..f5deddf7706a 100644
--- a/ssl/d1_pkt.c
+++ b/ssl/d1_pkt.c
@@ -1,2020 +1,2041 @@
/* ssl/d1_pkt.c */
/*
* DTLS implementation written by Nagendra Modadugu
* (nagendra@cs.stanford.edu) for the OpenSSL project 2005.
*/
/* ====================================================================
- * Copyright (c) 1998-2005 The OpenSSL Project. All rights reserved.
+ * Copyright (c) 1998-2018 The OpenSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* openssl-core@openssl.org.
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.openssl.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*
* This product includes cryptographic software written by Eric Young
* (eay@cryptsoft.com). This product includes software written by Tim
* Hudson (tjh@cryptsoft.com).
*
*/
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
#include <stdio.h>
#include <errno.h>
#define USE_SOCKETS
#include "ssl_locl.h"
#include <openssl/evp.h>
#include <openssl/buffer.h>
#include <openssl/pqueue.h>
#include <openssl/rand.h>
/* mod 128 saturating subtract of two 64-bit values in big-endian order */
static int satsub64be(const unsigned char *v1, const unsigned char *v2)
{
int ret, i;
if (sizeof(long) == 8)
do {
const union {
long one;
char little;
} is_endian = {
1
};
long l;
if (is_endian.little)
break;
/* not reached on little-endians */
/*
* following test is redundant, because input is always aligned,
* but I take no chances...
*/
if (((size_t)v1 | (size_t)v2) & 0x7)
break;
l = *((long *)v1);
l -= *((long *)v2);
if (l > 128)
return 128;
else if (l < -128)
return -128;
else
return (int)l;
} while (0);
ret = 0;
for (i=0; i<7; i++) {
if (v1[i] > v2[i]) {
/* v1 is larger... but by how much? */
if (v1[i] != v2[i] + 1)
return 128;
while (++i <= 6) {
if (v1[i] != 0x00 || v2[i] != 0xff)
return 128; /* too much */
}
/* We checked all the way to the penultimate byte,
* so despite higher bytes changing we actually
* know that it only changed from (e.g.)
* ... (xx) ff ff ff ??
* to ... (xx+1) 00 00 00 ??
* so we add a 'bias' of 256 for the carry that
* happened, and will eventually return
* 256 + v1[7] - v2[7]. */
ret = 256;
break;
} else if (v2[i] > v1[i]) {
/* v2 is larger... but by how much? */
if (v2[i] != v1[i] + 1)
return -128;
while (++i <= 6) {
if (v2[i] != 0x00 || v1[i] != 0xff)
return -128; /* too much */
}
/* Similar to the case above, we know it changed
* from ... (xx) 00 00 00 ??
* to ... (xx-1) ff ff ff ??
* so we add a 'bias' of -256 for the borrow,
* to return -256 + v1[7] - v2[7]. */
ret = -256;
}
}
ret += (int)v1[7] - (int)v2[7];
if (ret > 128)
return 128;
else if (ret < -128)
return -128;
else
return ret;
}
static int have_handshake_fragment(SSL *s, int type, unsigned char *buf,
int len, int peek);
static int dtls1_record_replay_check(SSL *s, DTLS1_BITMAP *bitmap);
static void dtls1_record_bitmap_update(SSL *s, DTLS1_BITMAP *bitmap);
static DTLS1_BITMAP *dtls1_get_bitmap(SSL *s, SSL3_RECORD *rr,
unsigned int *is_next_epoch);
#if 0
static int dtls1_record_needs_buffering(SSL *s, SSL3_RECORD *rr,
unsigned short *priority,
unsigned long *offset);
#endif
static int dtls1_buffer_record(SSL *s, record_pqueue *q,
unsigned char *priority);
static int dtls1_process_record(SSL *s, DTLS1_BITMAP *bitmap);
/* copy buffered record into SSL structure */
static int dtls1_copy_record(SSL *s, pitem *item)
{
DTLS1_RECORD_DATA *rdata;
rdata = (DTLS1_RECORD_DATA *)item->data;
if (s->s3->rbuf.buf != NULL)
OPENSSL_free(s->s3->rbuf.buf);
s->packet = rdata->packet;
s->packet_length = rdata->packet_length;
memcpy(&(s->s3->rbuf), &(rdata->rbuf), sizeof(SSL3_BUFFER));
memcpy(&(s->s3->rrec), &(rdata->rrec), sizeof(SSL3_RECORD));
/* Set proper sequence number for mac calculation */
memcpy(&(s->s3->read_sequence[2]), &(rdata->packet[5]), 6);
return (1);
}
static int
dtls1_buffer_record(SSL *s, record_pqueue *queue, unsigned char *priority)
{
DTLS1_RECORD_DATA *rdata;
pitem *item;
/* Limit the size of the queue to prevent DOS attacks */
if (pqueue_size(queue->q) >= 100)
return 0;
rdata = OPENSSL_malloc(sizeof(DTLS1_RECORD_DATA));
item = pitem_new(priority, rdata);
if (rdata == NULL || item == NULL) {
if (rdata != NULL)
OPENSSL_free(rdata);
if (item != NULL)
pitem_free(item);
SSLerr(SSL_F_DTLS1_BUFFER_RECORD, ERR_R_INTERNAL_ERROR);
return -1;
}
rdata->packet = s->packet;
rdata->packet_length = s->packet_length;
memcpy(&(rdata->rbuf), &(s->s3->rbuf), sizeof(SSL3_BUFFER));
memcpy(&(rdata->rrec), &(s->s3->rrec), sizeof(SSL3_RECORD));
item->data = rdata;
#ifndef OPENSSL_NO_SCTP
/* Store bio_dgram_sctp_rcvinfo struct */
if (BIO_dgram_is_sctp(SSL_get_rbio(s)) &&
(s->state == SSL3_ST_SR_FINISHED_A
|| s->state == SSL3_ST_CR_FINISHED_A)) {
BIO_ctrl(SSL_get_rbio(s), BIO_CTRL_DGRAM_SCTP_GET_RCVINFO,
sizeof(rdata->recordinfo), &rdata->recordinfo);
}
#endif
s->packet = NULL;
s->packet_length = 0;
memset(&(s->s3->rbuf), 0, sizeof(SSL3_BUFFER));
memset(&(s->s3->rrec), 0, sizeof(SSL3_RECORD));
if (!ssl3_setup_buffers(s)) {
SSLerr(SSL_F_DTLS1_BUFFER_RECORD, ERR_R_INTERNAL_ERROR);
if (rdata->rbuf.buf != NULL)
OPENSSL_free(rdata->rbuf.buf);
OPENSSL_free(rdata);
pitem_free(item);
return (-1);
}
/* insert should not fail, since duplicates are dropped */
if (pqueue_insert(queue->q, item) == NULL) {
SSLerr(SSL_F_DTLS1_BUFFER_RECORD, ERR_R_INTERNAL_ERROR);
if (rdata->rbuf.buf != NULL)
OPENSSL_free(rdata->rbuf.buf);
OPENSSL_free(rdata);
pitem_free(item);
return (-1);
}
return (1);
}
static int dtls1_retrieve_buffered_record(SSL *s, record_pqueue *queue)
{
pitem *item;
item = pqueue_pop(queue->q);
if (item) {
dtls1_copy_record(s, item);
OPENSSL_free(item->data);
pitem_free(item);
return (1);
}
return (0);
}
/*
* retrieve a buffered record that belongs to the new epoch, i.e., not
* processed yet
*/
#define dtls1_get_unprocessed_record(s) \
dtls1_retrieve_buffered_record((s), \
&((s)->d1->unprocessed_rcds))
/*
* retrieve a buffered record that belongs to the current epoch, ie,
* processed
*/
#define dtls1_get_processed_record(s) \
dtls1_retrieve_buffered_record((s), \
&((s)->d1->processed_rcds))
static int dtls1_process_buffered_records(SSL *s)
{
pitem *item;
SSL3_BUFFER *rb;
SSL3_RECORD *rr;
DTLS1_BITMAP *bitmap;
unsigned int is_next_epoch;
int replayok = 1;
item = pqueue_peek(s->d1->unprocessed_rcds.q);
if (item) {
/* Check if epoch is current. */
if (s->d1->unprocessed_rcds.epoch != s->d1->r_epoch)
return 1; /* Nothing to do. */
rr = &s->s3->rrec;
rb = &s->s3->rbuf;
if (rb->left > 0) {
/*
* We've still got data from the current packet to read. There could
* be a record from the new epoch in it - so don't overwrite it
* with the unprocessed records yet (we'll do it when we've
* finished reading the current packet).
*/
return 1;
}
/* Process all the records. */
while (pqueue_peek(s->d1->unprocessed_rcds.q)) {
dtls1_get_unprocessed_record(s);
bitmap = dtls1_get_bitmap(s, rr, &is_next_epoch);
if (bitmap == NULL) {
/*
* Should not happen. This will only ever be NULL when the
* current record is from a different epoch. But that cannot
* be the case because we already checked the epoch above
*/
SSLerr(SSL_F_DTLS1_PROCESS_BUFFERED_RECORDS,
ERR_R_INTERNAL_ERROR);
return 0;
}
#ifndef OPENSSL_NO_SCTP
/* Only do replay check if no SCTP bio */
if (!BIO_dgram_is_sctp(SSL_get_rbio(s)))
#endif
{
/*
* Check whether this is a repeat, or aged record. We did this
* check once already when we first received the record - but
* we might have updated the window since then due to
* records we subsequently processed.
*/
replayok = dtls1_record_replay_check(s, bitmap);
}
if (!replayok || !dtls1_process_record(s, bitmap)) {
/* dump this record */
rr->length = 0;
s->packet_length = 0;
continue;
}
if (dtls1_buffer_record(s, &(s->d1->processed_rcds),
s->s3->rrec.seq_num) < 0)
return 0;
}
}
/*
* sync epoch numbers once all the unprocessed records have been
* processed
*/
s->d1->processed_rcds.epoch = s->d1->r_epoch;
s->d1->unprocessed_rcds.epoch = s->d1->r_epoch + 1;
return 1;
}
#if 0
static int dtls1_get_buffered_record(SSL *s)
{
pitem *item;
PQ_64BIT priority =
(((PQ_64BIT) s->d1->handshake_read_seq) << 32) |
((PQ_64BIT) s->d1->r_msg_hdr.frag_off);
/* if we're not (re)negotiating, nothing buffered */
if (!SSL_in_init(s))
return 0;
item = pqueue_peek(s->d1->rcvd_records);
if (item && item->priority == priority) {
/*
* Check if we've received the record of interest. It must be a
* handshake record, since data records as passed up without
* buffering
*/
DTLS1_RECORD_DATA *rdata;
item = pqueue_pop(s->d1->rcvd_records);
rdata = (DTLS1_RECORD_DATA *)item->data;
if (s->s3->rbuf.buf != NULL)
OPENSSL_free(s->s3->rbuf.buf);
s->packet = rdata->packet;
s->packet_length = rdata->packet_length;
memcpy(&(s->s3->rbuf), &(rdata->rbuf), sizeof(SSL3_BUFFER));
memcpy(&(s->s3->rrec), &(rdata->rrec), sizeof(SSL3_RECORD));
OPENSSL_free(item->data);
pitem_free(item);
/* s->d1->next_expected_seq_num++; */
return (1);
}
return 0;
}
#endif
static int dtls1_process_record(SSL *s, DTLS1_BITMAP *bitmap)
{
int i, al;
int enc_err;
SSL_SESSION *sess;
SSL3_RECORD *rr;
unsigned int mac_size, orig_len;
unsigned char md[EVP_MAX_MD_SIZE];
rr = &(s->s3->rrec);
sess = s->session;
/*
* At this point, s->packet_length == SSL3_RT_HEADER_LNGTH + rr->length,
* and we have that many bytes in s->packet
*/
rr->input = &(s->packet[DTLS1_RT_HEADER_LENGTH]);
/*
* ok, we can now read from 's->packet' data into 'rr' rr->input points
* at rr->length bytes, which need to be copied into rr->data by either
* the decryption or by the decompression When the data is 'copied' into
* the rr->data buffer, rr->input will be pointed at the new buffer
*/
/*
* We now have - encrypted [ MAC [ compressed [ plain ] ] ] rr->length
* bytes of encrypted compressed stuff.
*/
/* check is not needed I believe */
if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH) {
al = SSL_AD_RECORD_OVERFLOW;
SSLerr(SSL_F_DTLS1_PROCESS_RECORD, SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
goto f_err;
}
/* decrypt in place in 'rr->input' */
rr->data = rr->input;
enc_err = s->method->ssl3_enc->enc(s, 0);
/*-
* enc_err is:
* 0: (in non-constant time) if the record is publically invalid.
* 1: if the padding is valid
* -1: if the padding is invalid
*/
if (enc_err == 0) {
/* For DTLS we simply ignore bad packets. */
rr->length = 0;
s->packet_length = 0;
goto err;
}
#ifdef TLS_DEBUG
printf("dec %d\n", rr->length);
{
unsigned int z;
for (z = 0; z < rr->length; z++)
printf("%02X%c", rr->data[z], ((z + 1) % 16) ? ' ' : '\n');
}
printf("\n");
#endif
/* r->length is now the compressed data plus mac */
if ((sess != NULL) &&
(s->enc_read_ctx != NULL) && (EVP_MD_CTX_md(s->read_hash) != NULL)) {
/* s->read_hash != NULL => mac_size != -1 */
unsigned char *mac = NULL;
unsigned char mac_tmp[EVP_MAX_MD_SIZE];
mac_size = EVP_MD_CTX_size(s->read_hash);
OPENSSL_assert(mac_size <= EVP_MAX_MD_SIZE);
/*
* kludge: *_cbc_remove_padding passes padding length in rr->type
*/
orig_len = rr->length + ((unsigned int)rr->type >> 8);
/*
* orig_len is the length of the record before any padding was
* removed. This is public information, as is the MAC in use,
* therefore we can safely process the record in a different amount
* of time if it's too short to possibly contain a MAC.
*/
if (orig_len < mac_size ||
/* CBC records must have a padding length byte too. */
(EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
orig_len < mac_size + 1)) {
al = SSL_AD_DECODE_ERROR;
SSLerr(SSL_F_DTLS1_PROCESS_RECORD, SSL_R_LENGTH_TOO_SHORT);
goto f_err;
}
if (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE) {
/*
* We update the length so that the TLS header bytes can be
* constructed correctly but we need to extract the MAC in
* constant time from within the record, without leaking the
* contents of the padding bytes.
*/
mac = mac_tmp;
ssl3_cbc_copy_mac(mac_tmp, rr, mac_size, orig_len);
rr->length -= mac_size;
} else {
/*
* In this case there's no padding, so |orig_len| equals
* |rec->length| and we checked that there's enough bytes for
* |mac_size| above.
*/
rr->length -= mac_size;
mac = &rr->data[rr->length];
}
i = s->method->ssl3_enc->mac(s, md, 0 /* not send */ );
if (i < 0 || mac == NULL
|| CRYPTO_memcmp(md, mac, (size_t)mac_size) != 0)
enc_err = -1;
if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH + mac_size)
enc_err = -1;
}
if (enc_err < 0) {
/* decryption failed, silently discard message */
rr->length = 0;
s->packet_length = 0;
goto err;
}
/* r->length is now just compressed */
if (s->expand != NULL) {
if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH) {
al = SSL_AD_RECORD_OVERFLOW;
SSLerr(SSL_F_DTLS1_PROCESS_RECORD,
SSL_R_COMPRESSED_LENGTH_TOO_LONG);
goto f_err;
}
if (!ssl3_do_uncompress(s)) {
al = SSL_AD_DECOMPRESSION_FAILURE;
SSLerr(SSL_F_DTLS1_PROCESS_RECORD, SSL_R_BAD_DECOMPRESSION);
goto f_err;
}
}
if (rr->length > SSL3_RT_MAX_PLAIN_LENGTH) {
al = SSL_AD_RECORD_OVERFLOW;
SSLerr(SSL_F_DTLS1_PROCESS_RECORD, SSL_R_DATA_LENGTH_TOO_LONG);
goto f_err;
}
rr->off = 0;
/*-
* So at this point the following is true
* ssl->s3->rrec.type is the type of record
* ssl->s3->rrec.length == number of bytes in record
* ssl->s3->rrec.off == offset to first valid byte
* ssl->s3->rrec.data == where to take bytes from, increment
* after use :-).
*/
/* we have pulled in a full packet so zero things */
s->packet_length = 0;
/* Mark receipt of record. */
dtls1_record_bitmap_update(s, bitmap);
return (1);
f_err:
ssl3_send_alert(s, SSL3_AL_FATAL, al);
err:
return (0);
}
/*-
* Call this to get a new input record.
* It will return <= 0 if more data is needed, normally due to an error
* or non-blocking IO.
* When it finishes, one packet has been decoded and can be found in
* ssl->s3->rrec.type - is the type of record
* ssl->s3->rrec.data, - data
* ssl->s3->rrec.length, - number of bytes
*/
/* used only by dtls1_read_bytes */
int dtls1_get_record(SSL *s)
{
int ssl_major, ssl_minor;
int i, n;
SSL3_RECORD *rr;
unsigned char *p = NULL;
unsigned short version;
DTLS1_BITMAP *bitmap;
unsigned int is_next_epoch;
rr = &(s->s3->rrec);
again:
/*
* The epoch may have changed. If so, process all the pending records.
* This is a non-blocking operation.
*/
if (!dtls1_process_buffered_records(s))
return -1;
/* if we're renegotiating, then there may be buffered records */
if (dtls1_get_processed_record(s))
return 1;
/* get something from the wire */
/* check if we have the header */
if ((s->rstate != SSL_ST_READ_BODY) ||
(s->packet_length < DTLS1_RT_HEADER_LENGTH)) {
n = ssl3_read_n(s, DTLS1_RT_HEADER_LENGTH, s->s3->rbuf.len, 0);
/* read timeout is handled by dtls1_read_bytes */
if (n <= 0)
return (n); /* error or non-blocking */
/* this packet contained a partial record, dump it */
if (s->packet_length != DTLS1_RT_HEADER_LENGTH) {
s->packet_length = 0;
goto again;
}
s->rstate = SSL_ST_READ_BODY;
p = s->packet;
if (s->msg_callback)
s->msg_callback(0, 0, SSL3_RT_HEADER, p, DTLS1_RT_HEADER_LENGTH,
s, s->msg_callback_arg);
/* Pull apart the header into the DTLS1_RECORD */
rr->type = *(p++);
ssl_major = *(p++);
ssl_minor = *(p++);
version = (ssl_major << 8) | ssl_minor;
/* sequence number is 64 bits, with top 2 bytes = epoch */
n2s(p, rr->epoch);
memcpy(&(s->s3->read_sequence[2]), p, 6);
p += 6;
n2s(p, rr->length);
- /* Lets check version */
- if (!s->first_packet) {
+ /*
+ * Lets check the version. We tolerate alerts that don't have the exact
+ * version number (e.g. because of protocol version errors)
+ */
+ if (!s->first_packet && rr->type != SSL3_RT_ALERT) {
if (version != s->version) {
/* unexpected version, silently discard */
rr->length = 0;
s->packet_length = 0;
goto again;
}
}
if ((version & 0xff00) != (s->version & 0xff00)) {
/* wrong version, silently discard record */
rr->length = 0;
s->packet_length = 0;
goto again;
}
if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH) {
/* record too long, silently discard it */
rr->length = 0;
s->packet_length = 0;
goto again;
}
/* now s->rstate == SSL_ST_READ_BODY */
}
/* s->rstate == SSL_ST_READ_BODY, get and decode the data */
if (rr->length > s->packet_length - DTLS1_RT_HEADER_LENGTH) {
/* now s->packet_length == DTLS1_RT_HEADER_LENGTH */
i = rr->length;
n = ssl3_read_n(s, i, i, 1);
/* this packet contained a partial record, dump it */
if (n != i) {
rr->length = 0;
s->packet_length = 0;
goto again;
}
/*
* now n == rr->length, and s->packet_length ==
* DTLS1_RT_HEADER_LENGTH + rr->length
*/
}
s->rstate = SSL_ST_READ_HEADER; /* set state for later operations */
/* match epochs. NULL means the packet is dropped on the floor */
bitmap = dtls1_get_bitmap(s, rr, &is_next_epoch);
if (bitmap == NULL) {
rr->length = 0;
s->packet_length = 0; /* dump this record */
goto again; /* get another record */
}
#ifndef OPENSSL_NO_SCTP
/* Only do replay check if no SCTP bio */
if (!BIO_dgram_is_sctp(SSL_get_rbio(s))) {
#endif
/*
* Check whether this is a repeat, or aged record. Don't check if
* we're listening and this message is a ClientHello. They can look
* as if they're replayed, since they arrive from different
* connections and would be dropped unnecessarily.
*/
if (!(s->d1->listen && rr->type == SSL3_RT_HANDSHAKE &&
s->packet_length > DTLS1_RT_HEADER_LENGTH &&
s->packet[DTLS1_RT_HEADER_LENGTH] == SSL3_MT_CLIENT_HELLO) &&
!dtls1_record_replay_check(s, bitmap)) {
rr->length = 0;
s->packet_length = 0; /* dump this record */
goto again; /* get another record */
}
#ifndef OPENSSL_NO_SCTP
}
#endif
/* just read a 0 length packet */
if (rr->length == 0)
goto again;
/*
* If this record is from the next epoch (either HM or ALERT), and a
* handshake is currently in progress, buffer it since it cannot be
* processed at this time. However, do not buffer anything while
* listening.
*/
if (is_next_epoch) {
if ((SSL_in_init(s) || s->in_handshake) && !s->d1->listen) {
if (dtls1_buffer_record
(s, &(s->d1->unprocessed_rcds), rr->seq_num) < 0)
return -1;
}
rr->length = 0;
s->packet_length = 0;
goto again;
}
if (!dtls1_process_record(s, bitmap)) {
rr->length = 0;
s->packet_length = 0; /* dump this record */
goto again; /* get another record */
}
return (1);
}
/*-
* Return up to 'len' payload bytes received in 'type' records.
* 'type' is one of the following:
*
* - SSL3_RT_HANDSHAKE (when ssl3_get_message calls us)
* - SSL3_RT_APPLICATION_DATA (when ssl3_read calls us)
* - 0 (during a shutdown, no data has to be returned)
*
* If we don't have stored data to work from, read a SSL/TLS record first
* (possibly multiple records if we still don't have anything to return).
*
* This function must handle any surprises the peer may have for us, such as
* Alert records (e.g. close_notify), ChangeCipherSpec records (not really
* a surprise, but handled as if it were), or renegotiation requests.
* Also if record payloads contain fragments too small to process, we store
* them until there is enough for the respective protocol (the record protocol
* may use arbitrary fragmentation and even interleaving):
* Change cipher spec protocol
* just 1 byte needed, no need for keeping anything stored
* Alert protocol
* 2 bytes needed (AlertLevel, AlertDescription)
* Handshake protocol
* 4 bytes needed (HandshakeType, uint24 length) -- we just have
* to detect unexpected Client Hello and Hello Request messages
* here, anything else is handled by higher layers
* Application data protocol
* none of our business
*/
int dtls1_read_bytes(SSL *s, int type, unsigned char *buf, int len, int peek)
{
int al, i, j, ret;
unsigned int n;
SSL3_RECORD *rr;
void (*cb) (const SSL *ssl, int type2, int val) = NULL;
if (s->s3->rbuf.buf == NULL) /* Not initialized yet */
if (!ssl3_setup_buffers(s))
return (-1);
/* XXX: check what the second '&& type' is about */
if ((type && (type != SSL3_RT_APPLICATION_DATA) &&
(type != SSL3_RT_HANDSHAKE) && type) ||
(peek && (type != SSL3_RT_APPLICATION_DATA))) {
SSLerr(SSL_F_DTLS1_READ_BYTES, ERR_R_INTERNAL_ERROR);
return -1;
}
/*
* check whether there's a handshake message (client hello?) waiting
*/
if ((ret = have_handshake_fragment(s, type, buf, len, peek)))
return ret;
/*
* Now s->d1->handshake_fragment_len == 0 if type == SSL3_RT_HANDSHAKE.
*/
#ifndef OPENSSL_NO_SCTP
/*
* Continue handshake if it had to be interrupted to read app data with
* SCTP.
*/
if ((!s->in_handshake && SSL_in_init(s)) ||
(BIO_dgram_is_sctp(SSL_get_rbio(s)) &&
(s->state == DTLS1_SCTP_ST_SR_READ_SOCK
|| s->state == DTLS1_SCTP_ST_CR_READ_SOCK)
&& s->s3->in_read_app_data != 2))
#else
if (!s->in_handshake && SSL_in_init(s))
#endif
{
/* type == SSL3_RT_APPLICATION_DATA */
i = s->handshake_func(s);
if (i < 0)
return (i);
if (i == 0) {
SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_SSL_HANDSHAKE_FAILURE);
return (-1);
}
}
start:
s->rwstate = SSL_NOTHING;
/*-
* s->s3->rrec.type - is the type of record
* s->s3->rrec.data, - data
* s->s3->rrec.off, - offset into 'data' for next read
* s->s3->rrec.length, - number of bytes.
*/
rr = &(s->s3->rrec);
/*
* We are not handshaking and have no data yet, so process data buffered
* during the last handshake in advance, if any.
*/
if (s->state == SSL_ST_OK && rr->length == 0) {
pitem *item;
item = pqueue_pop(s->d1->buffered_app_data.q);
if (item) {
#ifndef OPENSSL_NO_SCTP
/* Restore bio_dgram_sctp_rcvinfo struct */
if (BIO_dgram_is_sctp(SSL_get_rbio(s))) {
DTLS1_RECORD_DATA *rdata = (DTLS1_RECORD_DATA *)item->data;
BIO_ctrl(SSL_get_rbio(s), BIO_CTRL_DGRAM_SCTP_SET_RCVINFO,
sizeof(rdata->recordinfo), &rdata->recordinfo);
}
#endif
dtls1_copy_record(s, item);
OPENSSL_free(item->data);
pitem_free(item);
}
}
/* Check for timeout */
if (dtls1_handle_timeout(s) > 0)
goto start;
/* get new packet if necessary */
if ((rr->length == 0) || (s->rstate == SSL_ST_READ_BODY)) {
ret = dtls1_get_record(s);
if (ret <= 0) {
ret = dtls1_read_failed(s, ret);
/* anything other than a timeout is an error */
if (ret <= 0)
return (ret);
else
goto start;
}
}
if (s->d1->listen && rr->type != SSL3_RT_HANDSHAKE) {
rr->length = 0;
goto start;
}
/*
* Reset the count of consecutive warning alerts if we've got a non-empty
* record that isn't an alert.
*/
if (rr->type != SSL3_RT_ALERT && rr->length != 0)
s->cert->alert_count = 0;
/* we now have a packet which can be read and processed */
if (s->s3->change_cipher_spec /* set when we receive ChangeCipherSpec,
* reset by ssl3_get_finished */
&& (rr->type != SSL3_RT_HANDSHAKE)) {
/*
* We now have application data between CCS and Finished. Most likely
* the packets were reordered on their way, so buffer the application
* data for later processing rather than dropping the connection.
*/
if (dtls1_buffer_record(s, &(s->d1->buffered_app_data), rr->seq_num) <
0) {
SSLerr(SSL_F_DTLS1_READ_BYTES, ERR_R_INTERNAL_ERROR);
return -1;
}
rr->length = 0;
goto start;
}
/*
* If the other end has shut down, throw anything we read away (even in
* 'peek' mode)
*/
if (s->shutdown & SSL_RECEIVED_SHUTDOWN) {
rr->length = 0;
s->rwstate = SSL_NOTHING;
return (0);
}
if (type == rr->type) { /* SSL3_RT_APPLICATION_DATA or
* SSL3_RT_HANDSHAKE */
/*
* make sure that we are not getting application data when we are
* doing a handshake for the first time
*/
if (SSL_in_init(s) && (type == SSL3_RT_APPLICATION_DATA) &&
(s->enc_read_ctx == NULL)) {
al = SSL_AD_UNEXPECTED_MESSAGE;
SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_APP_DATA_IN_HANDSHAKE);
goto f_err;
}
if (len <= 0)
return (len);
if ((unsigned int)len > rr->length)
n = rr->length;
else
n = (unsigned int)len;
memcpy(buf, &(rr->data[rr->off]), n);
if (!peek) {
rr->length -= n;
rr->off += n;
if (rr->length == 0) {
s->rstate = SSL_ST_READ_HEADER;
rr->off = 0;
}
}
#ifndef OPENSSL_NO_SCTP
/*
* We were about to renegotiate but had to read belated application
* data first, so retry.
*/
if (BIO_dgram_is_sctp(SSL_get_rbio(s)) &&
rr->type == SSL3_RT_APPLICATION_DATA &&
(s->state == DTLS1_SCTP_ST_SR_READ_SOCK
|| s->state == DTLS1_SCTP_ST_CR_READ_SOCK)) {
s->rwstate = SSL_READING;
BIO_clear_retry_flags(SSL_get_rbio(s));
BIO_set_retry_read(SSL_get_rbio(s));
}
/*
* We might had to delay a close_notify alert because of reordered
* app data. If there was an alert and there is no message to read
* anymore, finally set shutdown.
*/
if (BIO_dgram_is_sctp(SSL_get_rbio(s)) &&
s->d1->shutdown_received
&& !BIO_dgram_sctp_msg_waiting(SSL_get_rbio(s))) {
s->shutdown |= SSL_RECEIVED_SHUTDOWN;
return (0);
}
#endif
return (n);
}
/*
* If we get here, then type != rr->type; if we have a handshake message,
* then it was unexpected (Hello Request or Client Hello).
*/
/*
* In case of record types for which we have 'fragment' storage, fill
* that so that we can process the data at a fixed place.
*/
{
unsigned int k, dest_maxlen = 0;
unsigned char *dest = NULL;
unsigned int *dest_len = NULL;
if (rr->type == SSL3_RT_HANDSHAKE) {
- dest_maxlen = sizeof s->d1->handshake_fragment;
+ dest_maxlen = sizeof(s->d1->handshake_fragment);
dest = s->d1->handshake_fragment;
dest_len = &s->d1->handshake_fragment_len;
} else if (rr->type == SSL3_RT_ALERT) {
dest_maxlen = sizeof(s->d1->alert_fragment);
dest = s->d1->alert_fragment;
dest_len = &s->d1->alert_fragment_len;
}
#ifndef OPENSSL_NO_HEARTBEATS
else if (rr->type == TLS1_RT_HEARTBEAT) {
dtls1_process_heartbeat(s);
/* Exit and notify application to read again */
rr->length = 0;
s->rwstate = SSL_READING;
BIO_clear_retry_flags(SSL_get_rbio(s));
BIO_set_retry_read(SSL_get_rbio(s));
return (-1);
}
#endif
/* else it's a CCS message, or application data or wrong */
else if (rr->type != SSL3_RT_CHANGE_CIPHER_SPEC) {
/*
* Application data while renegotiating is allowed. Try again
* reading.
*/
if (rr->type == SSL3_RT_APPLICATION_DATA) {
BIO *bio;
s->s3->in_read_app_data = 2;
bio = SSL_get_rbio(s);
s->rwstate = SSL_READING;
BIO_clear_retry_flags(bio);
BIO_set_retry_read(bio);
return (-1);
}
/* Not certain if this is the right error handling */
al = SSL_AD_UNEXPECTED_MESSAGE;
SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_UNEXPECTED_RECORD);
goto f_err;
}
if (dest_maxlen > 0) {
/*
* XDTLS: In a pathalogical case, the Client Hello may be
* fragmented--don't always expect dest_maxlen bytes
*/
if (rr->length < dest_maxlen) {
#ifdef DTLS1_AD_MISSING_HANDSHAKE_MESSAGE
/*
* for normal alerts rr->length is 2, while
* dest_maxlen is 7 if we were to handle this
* non-existing alert...
*/
FIX ME
#endif
s->rstate = SSL_ST_READ_HEADER;
rr->length = 0;
goto start;
}
/* now move 'n' bytes: */
for (k = 0; k < dest_maxlen; k++) {
dest[k] = rr->data[rr->off++];
rr->length--;
}
*dest_len = dest_maxlen;
}
}
/*-
* s->d1->handshake_fragment_len == 12 iff rr->type == SSL3_RT_HANDSHAKE;
* s->d1->alert_fragment_len == 7 iff rr->type == SSL3_RT_ALERT.
* (Possibly rr is 'empty' now, i.e. rr->length may be 0.)
*/
/* If we are a client, check for an incoming 'Hello Request': */
if ((!s->server) &&
(s->d1->handshake_fragment_len >= DTLS1_HM_HEADER_LENGTH) &&
(s->d1->handshake_fragment[0] == SSL3_MT_HELLO_REQUEST) &&
(s->session != NULL) && (s->session->cipher != NULL)) {
s->d1->handshake_fragment_len = 0;
if ((s->d1->handshake_fragment[1] != 0) ||
(s->d1->handshake_fragment[2] != 0) ||
(s->d1->handshake_fragment[3] != 0)) {
al = SSL_AD_DECODE_ERROR;
SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_BAD_HELLO_REQUEST);
goto f_err;
}
/*
* no need to check sequence number on HELLO REQUEST messages
*/
if (s->msg_callback)
s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE,
s->d1->handshake_fragment, 4, s,
s->msg_callback_arg);
if (SSL_is_init_finished(s) &&
!(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS) &&
!s->s3->renegotiate) {
s->d1->handshake_read_seq++;
s->new_session = 1;
ssl3_renegotiate(s);
if (ssl3_renegotiate_check(s)) {
i = s->handshake_func(s);
if (i < 0)
return (i);
if (i == 0) {
SSLerr(SSL_F_DTLS1_READ_BYTES,
SSL_R_SSL_HANDSHAKE_FAILURE);
return (-1);
}
if (!(s->mode & SSL_MODE_AUTO_RETRY)) {
if (s->s3->rbuf.left == 0) { /* no read-ahead left? */
BIO *bio;
/*
* In the case where we try to read application data,
* but we trigger an SSL handshake, we return -1 with
* the retry option set. Otherwise renegotiation may
* cause nasty problems in the blocking world
*/
s->rwstate = SSL_READING;
bio = SSL_get_rbio(s);
BIO_clear_retry_flags(bio);
BIO_set_retry_read(bio);
return (-1);
}
}
}
}
/*
* we either finished a handshake or ignored the request, now try
* again to obtain the (application) data we were asked for
*/
goto start;
}
+ /*
+ * If we are a server and get a client hello when renegotiation isn't
+ * allowed send back a no renegotiation alert and carry on.
+ */
+ if (s->server
+ && SSL_is_init_finished(s)
+ && !s->s3->send_connection_binding
+ && s->d1->handshake_fragment_len >= DTLS1_HM_HEADER_LENGTH
+ && s->d1->handshake_fragment[0] == SSL3_MT_CLIENT_HELLO
+ && s->s3->previous_client_finished_len != 0
+ && (s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION) == 0) {
+ s->d1->handshake_fragment_len = 0;
+ rr->length = 0;
+ ssl3_send_alert(s, SSL3_AL_WARNING, SSL_AD_NO_RENEGOTIATION);
+ goto start;
+ }
+
+
if (s->d1->alert_fragment_len >= DTLS1_AL_HEADER_LENGTH) {
int alert_level = s->d1->alert_fragment[0];
int alert_descr = s->d1->alert_fragment[1];
s->d1->alert_fragment_len = 0;
if (s->msg_callback)
s->msg_callback(0, s->version, SSL3_RT_ALERT,
s->d1->alert_fragment, 2, s, s->msg_callback_arg);
if (s->info_callback != NULL)
cb = s->info_callback;
else if (s->ctx->info_callback != NULL)
cb = s->ctx->info_callback;
if (cb != NULL) {
j = (alert_level << 8) | alert_descr;
cb(s, SSL_CB_READ_ALERT, j);
}
if (alert_level == SSL3_AL_WARNING) {
s->s3->warn_alert = alert_descr;
s->cert->alert_count++;
if (s->cert->alert_count == MAX_WARN_ALERT_COUNT) {
al = SSL_AD_UNEXPECTED_MESSAGE;
SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_TOO_MANY_WARN_ALERTS);
goto f_err;
}
if (alert_descr == SSL_AD_CLOSE_NOTIFY) {
#ifndef OPENSSL_NO_SCTP
/*
* With SCTP and streams the socket may deliver app data
* after a close_notify alert. We have to check this first so
* that nothing gets discarded.
*/
if (BIO_dgram_is_sctp(SSL_get_rbio(s)) &&
BIO_dgram_sctp_msg_waiting(SSL_get_rbio(s))) {
s->d1->shutdown_received = 1;
s->rwstate = SSL_READING;
BIO_clear_retry_flags(SSL_get_rbio(s));
BIO_set_retry_read(SSL_get_rbio(s));
return -1;
}
#endif
s->shutdown |= SSL_RECEIVED_SHUTDOWN;
return (0);
}
#if 0
/* XXX: this is a possible improvement in the future */
/* now check if it's a missing record */
if (alert_descr == DTLS1_AD_MISSING_HANDSHAKE_MESSAGE) {
unsigned short seq;
unsigned int frag_off;
unsigned char *p = &(s->d1->alert_fragment[2]);
n2s(p, seq);
n2l3(p, frag_off);
dtls1_retransmit_message(s,
dtls1_get_queue_priority
(frag->msg_header.seq, 0), frag_off,
&found);
if (!found && SSL_in_init(s)) {
/*
* fprintf( stderr,"in init = %d\n", SSL_in_init(s));
*/
/*
* requested a message not yet sent, send an alert
* ourselves
*/
ssl3_send_alert(s, SSL3_AL_WARNING,
DTLS1_AD_MISSING_HANDSHAKE_MESSAGE);
}
}
#endif
} else if (alert_level == SSL3_AL_FATAL) {
char tmp[16];
s->rwstate = SSL_NOTHING;
s->s3->fatal_alert = alert_descr;
SSLerr(SSL_F_DTLS1_READ_BYTES,
SSL_AD_REASON_OFFSET + alert_descr);
- BIO_snprintf(tmp, sizeof tmp, "%d", alert_descr);
+ BIO_snprintf(tmp, sizeof(tmp), "%d", alert_descr);
ERR_add_error_data(2, "SSL alert number ", tmp);
s->shutdown |= SSL_RECEIVED_SHUTDOWN;
SSL_CTX_remove_session(s->session_ctx, s->session);
return (0);
} else {
al = SSL_AD_ILLEGAL_PARAMETER;
SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_UNKNOWN_ALERT_TYPE);
goto f_err;
}
goto start;
}
if (s->shutdown & SSL_SENT_SHUTDOWN) { /* but we have not received a
* shutdown */
s->rwstate = SSL_NOTHING;
rr->length = 0;
return (0);
}
if (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC) {
struct ccs_header_st ccs_hdr;
unsigned int ccs_hdr_len = DTLS1_CCS_HEADER_LENGTH;
dtls1_get_ccs_header(rr->data, &ccs_hdr);
if (s->version == DTLS1_BAD_VER)
ccs_hdr_len = 3;
/*
* 'Change Cipher Spec' is just a single byte, so we know exactly
* what the record payload has to look like
*/
/* XDTLS: check that epoch is consistent */
if ((rr->length != ccs_hdr_len) ||
(rr->off != 0) || (rr->data[0] != SSL3_MT_CCS)) {
al = SSL_AD_ILLEGAL_PARAMETER;
SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_BAD_CHANGE_CIPHER_SPEC);
goto f_err;
}
rr->length = 0;
if (s->msg_callback)
s->msg_callback(0, s->version, SSL3_RT_CHANGE_CIPHER_SPEC,
rr->data, 1, s, s->msg_callback_arg);
/*
* We can't process a CCS now, because previous handshake messages
* are still missing, so just drop it.
*/
if (!s->d1->change_cipher_spec_ok) {
goto start;
}
s->d1->change_cipher_spec_ok = 0;
s->s3->change_cipher_spec = 1;
if (!ssl3_do_change_cipher_spec(s))
goto err;
/* do this whenever CCS is processed */
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
goto start;
}
/*
* Unexpected handshake message (Client Hello, or protocol violation)
*/
if ((s->d1->handshake_fragment_len >= DTLS1_HM_HEADER_LENGTH) &&
!s->in_handshake) {
struct hm_header_st msg_hdr;
/* this may just be a stale retransmit */
dtls1_get_message_header(rr->data, &msg_hdr);
if (rr->epoch != s->d1->r_epoch) {
rr->length = 0;
goto start;
}
/*
* If we are server, we may have a repeated FINISHED of the client
* here, then retransmit our CCS and FINISHED.
*/
if (msg_hdr.type == SSL3_MT_FINISHED) {
if (dtls1_check_timeout_num(s) < 0)
return -1;
dtls1_retransmit_buffered_messages(s);
rr->length = 0;
goto start;
}
if (((s->state & SSL_ST_MASK) == SSL_ST_OK) &&
!(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS)) {
#if 0 /* worked only because C operator preferences
* are not as expected (and because this is
* not really needed for clients except for
* detecting protocol violations): */
s->state = SSL_ST_BEFORE | (s->server)
? SSL_ST_ACCEPT : SSL_ST_CONNECT;
#else
s->state = s->server ? SSL_ST_ACCEPT : SSL_ST_CONNECT;
#endif
s->renegotiate = 1;
s->new_session = 1;
}
i = s->handshake_func(s);
if (i < 0)
return (i);
if (i == 0) {
SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_SSL_HANDSHAKE_FAILURE);
return (-1);
}
if (!(s->mode & SSL_MODE_AUTO_RETRY)) {
if (s->s3->rbuf.left == 0) { /* no read-ahead left? */
BIO *bio;
/*
* In the case where we try to read application data, but we
* trigger an SSL handshake, we return -1 with the retry
* option set. Otherwise renegotiation may cause nasty
* problems in the blocking world
*/
s->rwstate = SSL_READING;
bio = SSL_get_rbio(s);
BIO_clear_retry_flags(bio);
BIO_set_retry_read(bio);
return (-1);
}
}
goto start;
}
switch (rr->type) {
default:
#ifndef OPENSSL_NO_TLS
/* TLS just ignores unknown message types */
if (s->version == TLS1_VERSION) {
rr->length = 0;
goto start;
}
#endif
al = SSL_AD_UNEXPECTED_MESSAGE;
SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_UNEXPECTED_RECORD);
goto f_err;
case SSL3_RT_CHANGE_CIPHER_SPEC:
case SSL3_RT_ALERT:
case SSL3_RT_HANDSHAKE:
/*
* we already handled all of these, with the possible exception of
* SSL3_RT_HANDSHAKE when s->in_handshake is set, but that should not
* happen when type != rr->type
*/
al = SSL_AD_UNEXPECTED_MESSAGE;
SSLerr(SSL_F_DTLS1_READ_BYTES, ERR_R_INTERNAL_ERROR);
goto f_err;
case SSL3_RT_APPLICATION_DATA:
/*
* At this point, we were expecting handshake data, but have
* application data. If the library was running inside ssl3_read()
* (i.e. in_read_app_data is set) and it makes sense to read
* application data at this point (session renegotiation not yet
* started), we will indulge it.
*/
if (s->s3->in_read_app_data &&
(s->s3->total_renegotiations != 0) &&
(((s->state & SSL_ST_CONNECT) &&
(s->state >= SSL3_ST_CW_CLNT_HELLO_A) &&
(s->state <= SSL3_ST_CR_SRVR_HELLO_A)
) || ((s->state & SSL_ST_ACCEPT) &&
(s->state <= SSL3_ST_SW_HELLO_REQ_A) &&
(s->state >= SSL3_ST_SR_CLNT_HELLO_A)
)
)) {
s->s3->in_read_app_data = 2;
return (-1);
} else {
al = SSL_AD_UNEXPECTED_MESSAGE;
SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_UNEXPECTED_RECORD);
goto f_err;
}
}
/* not reached */
f_err:
ssl3_send_alert(s, SSL3_AL_FATAL, al);
err:
return (-1);
}
int dtls1_write_app_data_bytes(SSL *s, int type, const void *buf_, int len)
{
int i;
#ifndef OPENSSL_NO_SCTP
/*
* Check if we have to continue an interrupted handshake for reading
* belated app data with SCTP.
*/
if ((SSL_in_init(s) && !s->in_handshake) ||
(BIO_dgram_is_sctp(SSL_get_wbio(s)) &&
(s->state == DTLS1_SCTP_ST_SR_READ_SOCK
|| s->state == DTLS1_SCTP_ST_CR_READ_SOCK)))
#else
if (SSL_in_init(s) && !s->in_handshake)
#endif
{
i = s->handshake_func(s);
if (i < 0)
return (i);
if (i == 0) {
SSLerr(SSL_F_DTLS1_WRITE_APP_DATA_BYTES,
SSL_R_SSL_HANDSHAKE_FAILURE);
return -1;
}
}
if (len > SSL3_RT_MAX_PLAIN_LENGTH) {
SSLerr(SSL_F_DTLS1_WRITE_APP_DATA_BYTES, SSL_R_DTLS_MESSAGE_TOO_BIG);
return -1;
}
i = dtls1_write_bytes(s, type, buf_, len);
return i;
}
/*
* this only happens when a client hello is received and a handshake
* is started.
*/
static int
have_handshake_fragment(SSL *s, int type, unsigned char *buf,
int len, int peek)
{
if ((type == SSL3_RT_HANDSHAKE) && (s->d1->handshake_fragment_len > 0))
/* (partially) satisfy request from storage */
{
unsigned char *src = s->d1->handshake_fragment;
unsigned char *dst = buf;
unsigned int k, n;
/* peek == 0 */
n = 0;
while ((len > 0) && (s->d1->handshake_fragment_len > 0)) {
*dst++ = *src++;
len--;
s->d1->handshake_fragment_len--;
n++;
}
/* move any remaining fragment bytes: */
for (k = 0; k < s->d1->handshake_fragment_len; k++)
s->d1->handshake_fragment[k] = *src++;
return n;
}
return 0;
}
/*
* Call this to write data in records of type 'type' It will return <= 0 if
* not all data has been sent or non-blocking IO.
*/
int dtls1_write_bytes(SSL *s, int type, const void *buf, int len)
{
int i;
OPENSSL_assert(len <= SSL3_RT_MAX_PLAIN_LENGTH);
s->rwstate = SSL_NOTHING;
i = do_dtls1_write(s, type, buf, len, 0);
return i;
}
int do_dtls1_write(SSL *s, int type, const unsigned char *buf,
unsigned int len, int create_empty_fragment)
{
unsigned char *p, *pseq;
int i, mac_size, clear = 0;
int prefix_len = 0;
int eivlen;
SSL3_RECORD *wr;
SSL3_BUFFER *wb;
SSL_SESSION *sess;
/*
* first check if there is a SSL3_BUFFER still being written out. This
* will happen with non blocking IO
*/
if (s->s3->wbuf.left != 0) {
OPENSSL_assert(0); /* XDTLS: want to see if we ever get here */
return (ssl3_write_pending(s, type, buf, len));
}
/* If we have an alert to send, lets send it */
if (s->s3->alert_dispatch) {
i = s->method->ssl_dispatch_alert(s);
if (i <= 0)
return (i);
/* if it went, fall through and send more stuff */
}
if (len == 0 && !create_empty_fragment)
return 0;
wr = &(s->s3->wrec);
wb = &(s->s3->wbuf);
sess = s->session;
if ((sess == NULL) ||
(s->enc_write_ctx == NULL) || (EVP_MD_CTX_md(s->write_hash) == NULL))
clear = 1;
if (clear)
mac_size = 0;
else {
mac_size = EVP_MD_CTX_size(s->write_hash);
if (mac_size < 0)
goto err;
}
/* DTLS implements explicit IV, so no need for empty fragments */
#if 0
/*
* 'create_empty_fragment' is true only when this function calls itself
*/
if (!clear && !create_empty_fragment && !s->s3->empty_fragment_done
&& SSL_version(s) != DTLS1_VERSION && SSL_version(s) != DTLS1_BAD_VER)
{
/*
* countermeasure against known-IV weakness in CBC ciphersuites (see
* http://www.openssl.org/~bodo/tls-cbc.txt)
*/
if (s->s3->need_empty_fragments && type == SSL3_RT_APPLICATION_DATA) {
/*
* recursive function call with 'create_empty_fragment' set; this
* prepares and buffers the data for an empty fragment (these
* 'prefix_len' bytes are sent out later together with the actual
* payload)
*/
prefix_len = s->method->do_ssl_write(s, type, buf, 0, 1);
if (prefix_len <= 0)
goto err;
if (s->s3->wbuf.len <
(size_t)prefix_len + SSL3_RT_MAX_PACKET_SIZE) {
/* insufficient space */
SSLerr(SSL_F_DO_DTLS1_WRITE, ERR_R_INTERNAL_ERROR);
goto err;
}
}
s->s3->empty_fragment_done = 1;
}
#endif
p = wb->buf + prefix_len;
/* write the header */
*(p++) = type & 0xff;
wr->type = type;
/*
* Special case: for hello verify request, client version 1.0 and we
* haven't decided which version to use yet send back using version 1.0
* header: otherwise some clients will ignore it.
*/
if (s->method->version == DTLS_ANY_VERSION) {
*(p++) = DTLS1_VERSION >> 8;
*(p++) = DTLS1_VERSION & 0xff;
} else {
*(p++) = s->version >> 8;
*(p++) = s->version & 0xff;
}
/* field where we are to write out packet epoch, seq num and len */
pseq = p;
p += 10;
/* Explicit IV length, block ciphers appropriate version flag */
if (s->enc_write_ctx) {
int mode = EVP_CIPHER_CTX_mode(s->enc_write_ctx);
if (mode == EVP_CIPH_CBC_MODE) {
eivlen = EVP_CIPHER_CTX_iv_length(s->enc_write_ctx);
if (eivlen <= 1)
eivlen = 0;
}
/* Need explicit part of IV for GCM mode */
else if (mode == EVP_CIPH_GCM_MODE)
eivlen = EVP_GCM_TLS_EXPLICIT_IV_LEN;
else
eivlen = 0;
} else
eivlen = 0;
/* lets setup the record stuff. */
wr->data = p + eivlen; /* make room for IV in case of CBC */
wr->length = (int)len;
wr->input = (unsigned char *)buf;
/*
* we now 'read' from wr->input, wr->length bytes into wr->data
*/
/* first we compress */
if (s->compress != NULL) {
if (!ssl3_do_compress(s)) {
SSLerr(SSL_F_DO_DTLS1_WRITE, SSL_R_COMPRESSION_FAILURE);
goto err;
}
} else {
memcpy(wr->data, wr->input, wr->length);
wr->input = wr->data;
}
/*
* we should still have the output to wr->data and the input from
* wr->input. Length should be wr->length. wr->data still points in the
* wb->buf
*/
if (mac_size != 0) {
if (s->method->ssl3_enc->mac(s, &(p[wr->length + eivlen]), 1) < 0)
goto err;
wr->length += mac_size;
}
/* this is true regardless of mac size */
wr->input = p;
wr->data = p;
if (eivlen)
wr->length += eivlen;
if (s->method->ssl3_enc->enc(s, 1) < 1)
goto err;
/* record length after mac and block padding */
/*
* if (type == SSL3_RT_APPLICATION_DATA || (type == SSL3_RT_ALERT && !
* SSL_in_init(s)))
*/
/* there's only one epoch between handshake and app data */
s2n(s->d1->w_epoch, pseq);
/* XDTLS: ?? */
/*
* else s2n(s->d1->handshake_epoch, pseq);
*/
memcpy(pseq, &(s->s3->write_sequence[2]), 6);
pseq += 6;
s2n(wr->length, pseq);
if (s->msg_callback)
s->msg_callback(1, 0, SSL3_RT_HEADER, pseq - DTLS1_RT_HEADER_LENGTH,
DTLS1_RT_HEADER_LENGTH, s, s->msg_callback_arg);
/*
* we should now have wr->data pointing to the encrypted data, which is
* wr->length long
*/
wr->type = type; /* not needed but helps for debugging */
wr->length += DTLS1_RT_HEADER_LENGTH;
#if 0 /* this is now done at the message layer */
/* buffer the record, making it easy to handle retransmits */
if (type == SSL3_RT_HANDSHAKE || type == SSL3_RT_CHANGE_CIPHER_SPEC)
dtls1_buffer_record(s, wr->data, wr->length,
*((PQ_64BIT *) & (s->s3->write_sequence[0])));
#endif
ssl3_record_sequence_update(&(s->s3->write_sequence[0]));
if (create_empty_fragment) {
/*
* we are in a recursive call; just return the length, don't write
* out anything here
*/
return wr->length;
}
/* now let's set up wb */
wb->left = prefix_len + wr->length;
wb->offset = 0;
/*
* memorize arguments so that ssl3_write_pending can detect bad write
* retries later
*/
s->s3->wpend_tot = len;
s->s3->wpend_buf = buf;
s->s3->wpend_type = type;
s->s3->wpend_ret = len;
/* we now just need to write the buffer */
return ssl3_write_pending(s, type, buf, len);
err:
return -1;
}
static int dtls1_record_replay_check(SSL *s, DTLS1_BITMAP *bitmap)
{
int cmp;
unsigned int shift;
const unsigned char *seq = s->s3->read_sequence;
cmp = satsub64be(seq, bitmap->max_seq_num);
if (cmp > 0) {
memcpy(s->s3->rrec.seq_num, seq, 8);
return 1; /* this record in new */
}
shift = -cmp;
if (shift >= sizeof(bitmap->map) * 8)
return 0; /* stale, outside the window */
else if (bitmap->map & (1UL << shift))
return 0; /* record previously received */
memcpy(s->s3->rrec.seq_num, seq, 8);
return 1;
}
static void dtls1_record_bitmap_update(SSL *s, DTLS1_BITMAP *bitmap)
{
int cmp;
unsigned int shift;
const unsigned char *seq = s->s3->read_sequence;
cmp = satsub64be(seq, bitmap->max_seq_num);
if (cmp > 0) {
shift = cmp;
if (shift < sizeof(bitmap->map) * 8)
bitmap->map <<= shift, bitmap->map |= 1UL;
else
bitmap->map = 1UL;
memcpy(bitmap->max_seq_num, seq, 8);
} else {
shift = -cmp;
if (shift < sizeof(bitmap->map) * 8)
bitmap->map |= 1UL << shift;
}
}
int dtls1_dispatch_alert(SSL *s)
{
int i, j;
void (*cb) (const SSL *ssl, int type, int val) = NULL;
unsigned char buf[DTLS1_AL_HEADER_LENGTH];
unsigned char *ptr = &buf[0];
s->s3->alert_dispatch = 0;
memset(buf, 0x00, sizeof(buf));
*ptr++ = s->s3->send_alert[0];
*ptr++ = s->s3->send_alert[1];
#ifdef DTLS1_AD_MISSING_HANDSHAKE_MESSAGE
if (s->s3->send_alert[1] == DTLS1_AD_MISSING_HANDSHAKE_MESSAGE) {
s2n(s->d1->handshake_read_seq, ptr);
# if 0
if (s->d1->r_msg_hdr.frag_off == 0)
/*
* waiting for a new msg
*/
else
s2n(s->d1->r_msg_hdr.seq, ptr); /* partial msg read */
# endif
# if 0
fprintf(stderr,
"s->d1->handshake_read_seq = %d, s->d1->r_msg_hdr.seq = %d\n",
s->d1->handshake_read_seq, s->d1->r_msg_hdr.seq);
# endif
l2n3(s->d1->r_msg_hdr.frag_off, ptr);
}
#endif
i = do_dtls1_write(s, SSL3_RT_ALERT, &buf[0], sizeof(buf), 0);
if (i <= 0) {
s->s3->alert_dispatch = 1;
/* fprintf( stderr, "not done with alert\n" ); */
} else {
if (s->s3->send_alert[0] == SSL3_AL_FATAL
#ifdef DTLS1_AD_MISSING_HANDSHAKE_MESSAGE
|| s->s3->send_alert[1] == DTLS1_AD_MISSING_HANDSHAKE_MESSAGE
#endif
)
(void)BIO_flush(s->wbio);
if (s->msg_callback)
s->msg_callback(1, s->version, SSL3_RT_ALERT, s->s3->send_alert,
2, s, s->msg_callback_arg);
if (s->info_callback != NULL)
cb = s->info_callback;
else if (s->ctx->info_callback != NULL)
cb = s->ctx->info_callback;
if (cb != NULL) {
j = (s->s3->send_alert[0] << 8) | s->s3->send_alert[1];
cb(s, SSL_CB_WRITE_ALERT, j);
}
}
return (i);
}
static DTLS1_BITMAP *dtls1_get_bitmap(SSL *s, SSL3_RECORD *rr,
unsigned int *is_next_epoch)
{
*is_next_epoch = 0;
/* In current epoch, accept HM, CCS, DATA, & ALERT */
if (rr->epoch == s->d1->r_epoch)
return &s->d1->bitmap;
/*
* Only HM and ALERT messages can be from the next epoch and only if we
* have already processed all of the unprocessed records from the last
* epoch
*/
else if (rr->epoch == (unsigned long)(s->d1->r_epoch + 1) &&
s->d1->unprocessed_rcds.epoch != s->d1->r_epoch &&
(rr->type == SSL3_RT_HANDSHAKE || rr->type == SSL3_RT_ALERT)) {
*is_next_epoch = 1;
return &s->d1->next_bitmap;
}
return NULL;
}
#if 0
static int
dtls1_record_needs_buffering(SSL *s, SSL3_RECORD *rr,
unsigned short *priority, unsigned long *offset)
{
/* alerts are passed up immediately */
if (rr->type == SSL3_RT_APPLICATION_DATA || rr->type == SSL3_RT_ALERT)
return 0;
/*
* Only need to buffer if a handshake is underway. (this implies that
* Hello Request and Client Hello are passed up immediately)
*/
if (SSL_in_init(s)) {
unsigned char *data = rr->data;
/* need to extract the HM/CCS sequence number here */
if (rr->type == SSL3_RT_HANDSHAKE ||
rr->type == SSL3_RT_CHANGE_CIPHER_SPEC) {
unsigned short seq_num;
struct hm_header_st msg_hdr;
struct ccs_header_st ccs_hdr;
if (rr->type == SSL3_RT_HANDSHAKE) {
dtls1_get_message_header(data, &msg_hdr);
seq_num = msg_hdr.seq;
*offset = msg_hdr.frag_off;
} else {
dtls1_get_ccs_header(data, &ccs_hdr);
seq_num = ccs_hdr.seq;
*offset = 0;
}
/*
* this is either a record we're waiting for, or a retransmit of
* something we happened to previously receive (higher layers
* will drop the repeat silently
*/
if (seq_num < s->d1->handshake_read_seq)
return 0;
if (rr->type == SSL3_RT_HANDSHAKE &&
seq_num == s->d1->handshake_read_seq &&
msg_hdr.frag_off < s->d1->r_msg_hdr.frag_off)
return 0;
else if (seq_num == s->d1->handshake_read_seq &&
(rr->type == SSL3_RT_CHANGE_CIPHER_SPEC ||
msg_hdr.frag_off == s->d1->r_msg_hdr.frag_off))
return 0;
else {
*priority = seq_num;
return 1;
}
} else /* unknown record type */
return 0;
}
return 0;
}
#endif
void dtls1_reset_seq_numbers(SSL *s, int rw)
{
unsigned char *seq;
unsigned int seq_bytes = sizeof(s->s3->read_sequence);
if (rw & SSL3_CC_READ) {
seq = s->s3->read_sequence;
s->d1->r_epoch++;
memcpy(&(s->d1->bitmap), &(s->d1->next_bitmap), sizeof(DTLS1_BITMAP));
memset(&(s->d1->next_bitmap), 0x00, sizeof(DTLS1_BITMAP));
/*
* We must not use any buffered messages received from the previous
* epoch
*/
dtls1_clear_received_buffer(s);
} else {
seq = s->s3->write_sequence;
memcpy(s->d1->last_write_sequence, seq,
sizeof(s->s3->write_sequence));
s->d1->w_epoch++;
}
memset(seq, 0x00, seq_bytes);
}
diff --git a/ssl/fatalerrtest.c b/ssl/fatalerrtest.c
index 0288c33fa2eb..f9d66e27b30c 100644
--- a/ssl/fatalerrtest.c
+++ b/ssl/fatalerrtest.c
@@ -1,109 +1,109 @@
/*
* Copyright 2017 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not 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/ssl.h>
#include <openssl/err.h>
#include "ssltestlib.h"
int main(int argc, char *argv[])
{
- SSL_CTX *sctx, *cctx;
- SSL *sssl, *cssl;
+ SSL_CTX *sctx = NULL, *cctx = NULL;
+ SSL *sssl = NULL, *cssl = NULL;
const char *msg = "Dummy";
BIO *err = NULL, *wbio = NULL;
int ret = 1, len;
char buf[80];
unsigned char dummyrec[] = {
0x17, 0x03, 0x03, 0x00, 0x05, 'D', 'u', 'm', 'm', 'y'
};
if (argc != 3) {
printf("Incorrect number of parameters\n");
return 1;
}
SSL_library_init();
SSL_load_error_strings();
err = BIO_new_fp(stderr, BIO_NOCLOSE | BIO_FP_TEXT);
CRYPTO_malloc_debug_init();
CRYPTO_set_mem_debug_options(V_CRYPTO_MDEBUG_ALL);
CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON);
if (!create_ssl_ctx_pair(SSLv23_method(), SSLv23_method(), &sctx, &cctx,
argv[1], argv[2])) {
printf("Failed to create SSL_CTX pair\n");
goto err;
}
/*
* Deliberately set the cipher lists for client and server to be different
* to force a handshake failure.
*/
if (!SSL_CTX_set_cipher_list(sctx, "AES128-SHA")
|| !SSL_CTX_set_cipher_list(cctx, "AES256-SHA")) {
printf("Failed to set cipher lists\n");
goto err;
}
if (!create_ssl_objects(sctx, cctx, &sssl, &cssl, NULL, NULL)) {
printf("Failed to create SSL objectx\n");
goto err;
}
wbio = SSL_get_wbio(cssl);
if (wbio == NULL) {
printf("Unexpected NULL bio received\n");
goto err;
}
if (create_ssl_connection(sssl, cssl)) {
printf("Unexpected success creating a connection\n");
goto err;
}
ERR_clear_error();
/* Inject a plaintext record from client to server */
if (BIO_write(wbio, dummyrec, sizeof(dummyrec)) <= 0) {
printf("Unexpected failure injecting dummy record\n");
goto err;
}
/* SSL_read()/SSL_write should fail because of a previous fatal error */
- if ((len = SSL_read(sssl, buf, sizeof(buf - 1))) > 0) {
+ if ((len = SSL_read(sssl, buf, sizeof(buf) - 1)) > 0) {
buf[len] = '\0';
printf("Unexpected success reading data: %s\n", buf);
goto err;
}
if (SSL_write(sssl, msg, strlen(msg)) > 0) {
printf("Unexpected success writing data\n");
goto err;
}
ret = 0;
err:
SSL_free(sssl);
SSL_free(cssl);
SSL_CTX_free(sctx);
SSL_CTX_free(cctx);
ERR_print_errors_fp(stderr);
if (ret) {
printf("Fatal err test: FAILED\n");
}
ERR_free_strings();
ERR_remove_thread_state(NULL);
EVP_cleanup();
CRYPTO_cleanup_all_ex_data();
CRYPTO_mem_leaks(err);
BIO_free(err);
return ret;
}
diff --git a/ssl/kssl.c b/ssl/kssl.c
index f2839bdcd7f5..18e5f1dcc2b0 100644
--- a/ssl/kssl.c
+++ b/ssl/kssl.c
@@ -1,2260 +1,2271 @@
/* ssl/kssl.c */
/*
* Written by Vern Staats <staatsvr@asc.hpc.mil> for the OpenSSL project
* 2000.
*/
/* ====================================================================
- * Copyright (c) 2000 The OpenSSL Project. All rights reserved.
+ * Copyright (c) 2000-2018 The OpenSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* licensing@OpenSSL.org.
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*
* This product includes cryptographic software written by Eric Young
* (eay@cryptsoft.com). This product includes software written by Tim
* Hudson (tjh@cryptsoft.com).
*
*/
/*-
* ssl/kssl.c -- Routines to support (& debug) Kerberos5 auth for openssl
*
* 19990701 VRS Started.
* 200011?? Jeffrey Altman, Richard Levitte
* Generalized for Heimdal, Newer MIT, & Win32.
* Integrated into main OpenSSL 0.9.7 snapshots.
* 20010413 Simon Wilkinson, VRS
* Real RFC2712 KerberosWrapper replaces AP_REQ.
*/
#include <openssl/opensslconf.h>
#include <string.h>
#define KRB5_PRIVATE 1
#include <openssl/ssl.h>
#include <openssl/evp.h>
#include <openssl/objects.h>
#include <openssl/krb5_asn.h>
+#include "o_time.h"
#include "kssl_lcl.h"
#ifndef OPENSSL_NO_KRB5
# ifndef ENOMEM
# define ENOMEM KRB5KRB_ERR_GENERIC
# endif
/*
* When OpenSSL is built on Windows, we do not want to require that
* the Kerberos DLLs be available in order for the OpenSSL DLLs to
* work. Therefore, all Kerberos routines are loaded at run time
* and we do not link to a .LIB file.
*/
# if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_WIN32)
/*
* The purpose of the following pre-processor statements is to provide
* compatibility with different releases of MIT Kerberos for Windows.
* All versions up to 1.2 used macros. But macros do not allow for
* a binary compatible interface for DLLs. Therefore, all macros are
* being replaced by function calls. The following code will allow
* an OpenSSL DLL built on Windows to work whether or not the macro
* or function form of the routines are utilized.
*/
# ifdef krb5_cc_get_principal
# define NO_DEF_KRB5_CCACHE
# undef krb5_cc_get_principal
# endif
# define krb5_cc_get_principal kssl_krb5_cc_get_principal
# define krb5_free_data_contents kssl_krb5_free_data_contents
# define krb5_free_context kssl_krb5_free_context
# define krb5_auth_con_free kssl_krb5_auth_con_free
# define krb5_free_principal kssl_krb5_free_principal
# define krb5_mk_req_extended kssl_krb5_mk_req_extended
# define krb5_get_credentials kssl_krb5_get_credentials
# define krb5_cc_default kssl_krb5_cc_default
# define krb5_sname_to_principal kssl_krb5_sname_to_principal
# define krb5_init_context kssl_krb5_init_context
# define krb5_free_ticket kssl_krb5_free_ticket
# define krb5_rd_req kssl_krb5_rd_req
# define krb5_kt_default kssl_krb5_kt_default
# define krb5_kt_resolve kssl_krb5_kt_resolve
/* macros in mit 1.2.2 and earlier; functions in mit 1.2.3 and greater */
# ifndef krb5_kt_close
# define krb5_kt_close kssl_krb5_kt_close
# endif /* krb5_kt_close */
# ifndef krb5_kt_get_entry
# define krb5_kt_get_entry kssl_krb5_kt_get_entry
# endif /* krb5_kt_get_entry */
# define krb5_auth_con_init kssl_krb5_auth_con_init
# define krb5_principal_compare kssl_krb5_principal_compare
# define krb5_decrypt_tkt_part kssl_krb5_decrypt_tkt_part
# define krb5_timeofday kssl_krb5_timeofday
# define krb5_rc_default kssl_krb5_rc_default
# ifdef krb5_rc_initialize
# undef krb5_rc_initialize
# endif
# define krb5_rc_initialize kssl_krb5_rc_initialize
# ifdef krb5_rc_get_lifespan
# undef krb5_rc_get_lifespan
# endif
# define krb5_rc_get_lifespan kssl_krb5_rc_get_lifespan
# ifdef krb5_rc_destroy
# undef krb5_rc_destroy
# endif
# define krb5_rc_destroy kssl_krb5_rc_destroy
# define valid_cksumtype kssl_valid_cksumtype
# define krb5_checksum_size kssl_krb5_checksum_size
# define krb5_kt_free_entry kssl_krb5_kt_free_entry
# define krb5_auth_con_setrcache kssl_krb5_auth_con_setrcache
# define krb5_auth_con_getrcache kssl_krb5_auth_con_getrcache
# define krb5_get_server_rcache kssl_krb5_get_server_rcache
/* Prototypes for built in stubs */
void kssl_krb5_free_data_contents(krb5_context, krb5_data *);
void kssl_krb5_free_principal(krb5_context, krb5_principal);
krb5_error_code kssl_krb5_kt_resolve(krb5_context,
krb5_const char *, krb5_keytab *);
krb5_error_code kssl_krb5_kt_default(krb5_context, krb5_keytab *);
krb5_error_code kssl_krb5_free_ticket(krb5_context, krb5_ticket *);
krb5_error_code kssl_krb5_rd_req(krb5_context, krb5_auth_context *,
krb5_const krb5_data *,
krb5_const_principal, krb5_keytab,
krb5_flags *, krb5_ticket **);
krb5_boolean kssl_krb5_principal_compare(krb5_context, krb5_const_principal,
krb5_const_principal);
krb5_error_code kssl_krb5_mk_req_extended(krb5_context,
krb5_auth_context *,
krb5_const krb5_flags,
krb5_data *,
krb5_creds *, krb5_data *);
krb5_error_code kssl_krb5_init_context(krb5_context *);
void kssl_krb5_free_context(krb5_context);
krb5_error_code kssl_krb5_cc_default(krb5_context, krb5_ccache *);
krb5_error_code kssl_krb5_sname_to_principal(krb5_context,
krb5_const char *,
krb5_const char *,
krb5_int32, krb5_principal *);
krb5_error_code kssl_krb5_get_credentials(krb5_context,
krb5_const krb5_flags,
krb5_ccache,
krb5_creds *, krb5_creds * *);
krb5_error_code kssl_krb5_auth_con_init(krb5_context, krb5_auth_context *);
krb5_error_code kssl_krb5_cc_get_principal(krb5_context context,
krb5_ccache cache,
krb5_principal *principal);
krb5_error_code kssl_krb5_auth_con_free(krb5_context, krb5_auth_context);
size_t kssl_krb5_checksum_size(krb5_context context, krb5_cksumtype ctype);
krb5_boolean kssl_valid_cksumtype(krb5_cksumtype ctype);
krb5_error_code krb5_kt_free_entry(krb5_context, krb5_keytab_entry FAR *);
krb5_error_code kssl_krb5_auth_con_setrcache(krb5_context,
krb5_auth_context, krb5_rcache);
krb5_error_code kssl_krb5_get_server_rcache(krb5_context,
krb5_const krb5_data *,
krb5_rcache *);
krb5_error_code kssl_krb5_auth_con_getrcache(krb5_context,
krb5_auth_context,
krb5_rcache *);
/* Function pointers (almost all Kerberos functions are _stdcall) */
static void (_stdcall *p_krb5_free_data_contents) (krb5_context, krb5_data *)
= NULL;
static void (_stdcall *p_krb5_free_principal) (krb5_context, krb5_principal)
= NULL;
static krb5_error_code(_stdcall *p_krb5_kt_resolve)
(krb5_context, krb5_const char *, krb5_keytab *) = NULL;
static krb5_error_code(_stdcall *p_krb5_kt_default) (krb5_context,
krb5_keytab *) = NULL;
static krb5_error_code(_stdcall *p_krb5_free_ticket) (krb5_context,
krb5_ticket *) = NULL;
static krb5_error_code(_stdcall *p_krb5_rd_req) (krb5_context,
krb5_auth_context *,
krb5_const krb5_data *,
krb5_const_principal,
krb5_keytab, krb5_flags *,
krb5_ticket **) = NULL;
static krb5_error_code(_stdcall *p_krb5_mk_req_extended)
(krb5_context, krb5_auth_context *,
krb5_const krb5_flags, krb5_data *, krb5_creds *, krb5_data *) = NULL;
static krb5_error_code(_stdcall *p_krb5_init_context) (krb5_context *) = NULL;
static void (_stdcall *p_krb5_free_context) (krb5_context) = NULL;
static krb5_error_code(_stdcall *p_krb5_cc_default) (krb5_context,
krb5_ccache *) = NULL;
static krb5_error_code(_stdcall *p_krb5_sname_to_principal)
(krb5_context, krb5_const char *, krb5_const char *,
krb5_int32, krb5_principal *) = NULL;
static krb5_error_code(_stdcall *p_krb5_get_credentials)
(krb5_context, krb5_const krb5_flags, krb5_ccache,
krb5_creds *, krb5_creds **) = NULL;
static krb5_error_code(_stdcall *p_krb5_auth_con_init)
(krb5_context, krb5_auth_context *) = NULL;
static krb5_error_code(_stdcall *p_krb5_cc_get_principal)
(krb5_context context, krb5_ccache cache, krb5_principal *principal) = NULL;
static krb5_error_code(_stdcall *p_krb5_auth_con_free)
(krb5_context, krb5_auth_context) = NULL;
static krb5_error_code(_stdcall *p_krb5_decrypt_tkt_part)
(krb5_context, krb5_const krb5_keyblock *, krb5_ticket *) = NULL;
static krb5_error_code(_stdcall *p_krb5_timeofday)
(krb5_context context, krb5_int32 *timeret) = NULL;
static krb5_error_code(_stdcall *p_krb5_rc_default)
(krb5_context context, krb5_rcache *rc) = NULL;
static krb5_error_code(_stdcall *p_krb5_rc_initialize)
(krb5_context context, krb5_rcache rc, krb5_deltat lifespan) = NULL;
static krb5_error_code(_stdcall *p_krb5_rc_get_lifespan)
(krb5_context context, krb5_rcache rc, krb5_deltat *lifespan) = NULL;
static krb5_error_code(_stdcall *p_krb5_rc_destroy)
(krb5_context context, krb5_rcache rc) = NULL;
static krb5_boolean(_stdcall *p_krb5_principal_compare)
(krb5_context, krb5_const_principal, krb5_const_principal) = NULL;
static size_t (_stdcall *p_krb5_checksum_size) (krb5_context context,
krb5_cksumtype ctype) = NULL;
static krb5_boolean(_stdcall *p_valid_cksumtype) (krb5_cksumtype ctype) =
NULL;
static krb5_error_code(_stdcall *p_krb5_kt_free_entry)
(krb5_context, krb5_keytab_entry *) = NULL;
static krb5_error_code(_stdcall *p_krb5_auth_con_setrcache) (krb5_context,
krb5_auth_context,
krb5_rcache) =
NULL;
static krb5_error_code(_stdcall *p_krb5_get_server_rcache) (krb5_context,
krb5_const
krb5_data *,
krb5_rcache *) =
NULL;
static krb5_error_code(*p_krb5_auth_con_getrcache) (krb5_context,
krb5_auth_context,
krb5_rcache *) = NULL;
static krb5_error_code(_stdcall *p_krb5_kt_close) (krb5_context context,
krb5_keytab keytab) = NULL;
static krb5_error_code(_stdcall *p_krb5_kt_get_entry) (krb5_context context,
krb5_keytab keytab,
krb5_const_principal
principal,
krb5_kvno vno,
krb5_enctype enctype,
krb5_keytab_entry
*entry) = NULL;
static int krb5_loaded = 0; /* only attempt to initialize func ptrs once */
/* Function to Load the Kerberos 5 DLL and initialize function pointers */
void load_krb5_dll(void)
{
HANDLE hKRB5_32;
krb5_loaded++;
hKRB5_32 = LoadLibrary(TEXT("KRB5_32"));
if (!hKRB5_32)
return;
(FARPROC) p_krb5_free_data_contents =
GetProcAddress(hKRB5_32, "krb5_free_data_contents");
(FARPROC) p_krb5_free_context =
GetProcAddress(hKRB5_32, "krb5_free_context");
(FARPROC) p_krb5_auth_con_free =
GetProcAddress(hKRB5_32, "krb5_auth_con_free");
(FARPROC) p_krb5_free_principal =
GetProcAddress(hKRB5_32, "krb5_free_principal");
(FARPROC) p_krb5_mk_req_extended =
GetProcAddress(hKRB5_32, "krb5_mk_req_extended");
(FARPROC) p_krb5_get_credentials =
GetProcAddress(hKRB5_32, "krb5_get_credentials");
(FARPROC) p_krb5_cc_get_principal =
GetProcAddress(hKRB5_32, "krb5_cc_get_principal");
(FARPROC) p_krb5_cc_default = GetProcAddress(hKRB5_32, "krb5_cc_default");
(FARPROC) p_krb5_sname_to_principal =
GetProcAddress(hKRB5_32, "krb5_sname_to_principal");
(FARPROC) p_krb5_init_context =
GetProcAddress(hKRB5_32, "krb5_init_context");
(FARPROC) p_krb5_free_ticket =
GetProcAddress(hKRB5_32, "krb5_free_ticket");
(FARPROC) p_krb5_rd_req = GetProcAddress(hKRB5_32, "krb5_rd_req");
(FARPROC) p_krb5_principal_compare =
GetProcAddress(hKRB5_32, "krb5_principal_compare");
(FARPROC) p_krb5_decrypt_tkt_part =
GetProcAddress(hKRB5_32, "krb5_decrypt_tkt_part");
(FARPROC) p_krb5_timeofday = GetProcAddress(hKRB5_32, "krb5_timeofday");
(FARPROC) p_krb5_rc_default = GetProcAddress(hKRB5_32, "krb5_rc_default");
(FARPROC) p_krb5_rc_initialize =
GetProcAddress(hKRB5_32, "krb5_rc_initialize");
(FARPROC) p_krb5_rc_get_lifespan =
GetProcAddress(hKRB5_32, "krb5_rc_get_lifespan");
(FARPROC) p_krb5_rc_destroy = GetProcAddress(hKRB5_32, "krb5_rc_destroy");
(FARPROC) p_krb5_kt_default = GetProcAddress(hKRB5_32, "krb5_kt_default");
(FARPROC) p_krb5_kt_resolve = GetProcAddress(hKRB5_32, "krb5_kt_resolve");
(FARPROC) p_krb5_auth_con_init =
GetProcAddress(hKRB5_32, "krb5_auth_con_init");
(FARPROC) p_valid_cksumtype = GetProcAddress(hKRB5_32, "valid_cksumtype");
(FARPROC) p_krb5_checksum_size =
GetProcAddress(hKRB5_32, "krb5_checksum_size");
(FARPROC) p_krb5_kt_free_entry =
GetProcAddress(hKRB5_32, "krb5_kt_free_entry");
(FARPROC) p_krb5_auth_con_setrcache =
GetProcAddress(hKRB5_32, "krb5_auth_con_setrcache");
(FARPROC) p_krb5_get_server_rcache =
GetProcAddress(hKRB5_32, "krb5_get_server_rcache");
(FARPROC) p_krb5_auth_con_getrcache =
GetProcAddress(hKRB5_32, "krb5_auth_con_getrcache");
(FARPROC) p_krb5_kt_close = GetProcAddress(hKRB5_32, "krb5_kt_close");
(FARPROC) p_krb5_kt_get_entry =
GetProcAddress(hKRB5_32, "krb5_kt_get_entry");
}
/* Stubs for each function to be dynamicly loaded */
void kssl_krb5_free_data_contents(krb5_context CO, krb5_data *data)
{
if (!krb5_loaded)
load_krb5_dll();
if (p_krb5_free_data_contents)
p_krb5_free_data_contents(CO, data);
}
krb5_error_code
kssl_krb5_mk_req_extended(krb5_context CO,
krb5_auth_context *pACO,
krb5_const krb5_flags F,
krb5_data *pD1, krb5_creds *pC, krb5_data *pD2)
{
if (!krb5_loaded)
load_krb5_dll();
if (p_krb5_mk_req_extended)
return (p_krb5_mk_req_extended(CO, pACO, F, pD1, pC, pD2));
else
return KRB5KRB_ERR_GENERIC;
}
krb5_error_code
kssl_krb5_auth_con_init(krb5_context CO, krb5_auth_context *pACO)
{
if (!krb5_loaded)
load_krb5_dll();
if (p_krb5_auth_con_init)
return (p_krb5_auth_con_init(CO, pACO));
else
return KRB5KRB_ERR_GENERIC;
}
krb5_error_code
kssl_krb5_auth_con_free(krb5_context CO, krb5_auth_context ACO)
{
if (!krb5_loaded)
load_krb5_dll();
if (p_krb5_auth_con_free)
return (p_krb5_auth_con_free(CO, ACO));
else
return KRB5KRB_ERR_GENERIC;
}
krb5_error_code
kssl_krb5_get_credentials(krb5_context CO,
krb5_const krb5_flags F,
krb5_ccache CC, krb5_creds *pCR, krb5_creds **ppCR)
{
if (!krb5_loaded)
load_krb5_dll();
if (p_krb5_get_credentials)
return (p_krb5_get_credentials(CO, F, CC, pCR, ppCR));
else
return KRB5KRB_ERR_GENERIC;
}
krb5_error_code
kssl_krb5_sname_to_principal(krb5_context CO,
krb5_const char *pC1,
krb5_const char *pC2,
krb5_int32 I, krb5_principal *pPR)
{
if (!krb5_loaded)
load_krb5_dll();
if (p_krb5_sname_to_principal)
return (p_krb5_sname_to_principal(CO, pC1, pC2, I, pPR));
else
return KRB5KRB_ERR_GENERIC;
}
krb5_error_code kssl_krb5_cc_default(krb5_context CO, krb5_ccache *pCC)
{
if (!krb5_loaded)
load_krb5_dll();
if (p_krb5_cc_default)
return (p_krb5_cc_default(CO, pCC));
else
return KRB5KRB_ERR_GENERIC;
}
krb5_error_code kssl_krb5_init_context(krb5_context *pCO)
{
if (!krb5_loaded)
load_krb5_dll();
if (p_krb5_init_context)
return (p_krb5_init_context(pCO));
else
return KRB5KRB_ERR_GENERIC;
}
void kssl_krb5_free_context(krb5_context CO)
{
if (!krb5_loaded)
load_krb5_dll();
if (p_krb5_free_context)
p_krb5_free_context(CO);
}
void kssl_krb5_free_principal(krb5_context c, krb5_principal p)
{
if (!krb5_loaded)
load_krb5_dll();
if (p_krb5_free_principal)
p_krb5_free_principal(c, p);
}
krb5_error_code
kssl_krb5_kt_resolve(krb5_context con, krb5_const char *sz, krb5_keytab *kt)
{
if (!krb5_loaded)
load_krb5_dll();
if (p_krb5_kt_resolve)
return (p_krb5_kt_resolve(con, sz, kt));
else
return KRB5KRB_ERR_GENERIC;
}
krb5_error_code kssl_krb5_kt_default(krb5_context con, krb5_keytab *kt)
{
if (!krb5_loaded)
load_krb5_dll();
if (p_krb5_kt_default)
return (p_krb5_kt_default(con, kt));
else
return KRB5KRB_ERR_GENERIC;
}
krb5_error_code kssl_krb5_free_ticket(krb5_context con, krb5_ticket *kt)
{
if (!krb5_loaded)
load_krb5_dll();
if (p_krb5_free_ticket)
return (p_krb5_free_ticket(con, kt));
else
return KRB5KRB_ERR_GENERIC;
}
krb5_error_code
kssl_krb5_rd_req(krb5_context con, krb5_auth_context *pacon,
krb5_const krb5_data *data,
krb5_const_principal princ, krb5_keytab keytab,
krb5_flags *flags, krb5_ticket **pptkt)
{
if (!krb5_loaded)
load_krb5_dll();
if (p_krb5_rd_req)
return (p_krb5_rd_req(con, pacon, data, princ, keytab, flags, pptkt));
else
return KRB5KRB_ERR_GENERIC;
}
krb5_boolean
krb5_principal_compare(krb5_context con, krb5_const_principal princ1,
krb5_const_principal princ2)
{
if (!krb5_loaded)
load_krb5_dll();
if (p_krb5_principal_compare)
return (p_krb5_principal_compare(con, princ1, princ2));
else
return KRB5KRB_ERR_GENERIC;
}
krb5_error_code
krb5_decrypt_tkt_part(krb5_context con, krb5_const krb5_keyblock *keys,
krb5_ticket *ticket)
{
if (!krb5_loaded)
load_krb5_dll();
if (p_krb5_decrypt_tkt_part)
return (p_krb5_decrypt_tkt_part(con, keys, ticket));
else
return KRB5KRB_ERR_GENERIC;
}
krb5_error_code krb5_timeofday(krb5_context con, krb5_int32 *timeret)
{
if (!krb5_loaded)
load_krb5_dll();
if (p_krb5_timeofday)
return (p_krb5_timeofday(con, timeret));
else
return KRB5KRB_ERR_GENERIC;
}
krb5_error_code krb5_rc_default(krb5_context con, krb5_rcache *rc)
{
if (!krb5_loaded)
load_krb5_dll();
if (p_krb5_rc_default)
return (p_krb5_rc_default(con, rc));
else
return KRB5KRB_ERR_GENERIC;
}
krb5_error_code
krb5_rc_initialize(krb5_context con, krb5_rcache rc, krb5_deltat lifespan)
{
if (!krb5_loaded)
load_krb5_dll();
if (p_krb5_rc_initialize)
return (p_krb5_rc_initialize(con, rc, lifespan));
else
return KRB5KRB_ERR_GENERIC;
}
krb5_error_code
krb5_rc_get_lifespan(krb5_context con, krb5_rcache rc, krb5_deltat *lifespanp)
{
if (!krb5_loaded)
load_krb5_dll();
if (p_krb5_rc_get_lifespan)
return (p_krb5_rc_get_lifespan(con, rc, lifespanp));
else
return KRB5KRB_ERR_GENERIC;
}
krb5_error_code krb5_rc_destroy(krb5_context con, krb5_rcache rc)
{
if (!krb5_loaded)
load_krb5_dll();
if (p_krb5_rc_destroy)
return (p_krb5_rc_destroy(con, rc));
else
return KRB5KRB_ERR_GENERIC;
}
size_t krb5_checksum_size(krb5_context context, krb5_cksumtype ctype)
{
if (!krb5_loaded)
load_krb5_dll();
if (p_krb5_checksum_size)
return (p_krb5_checksum_size(context, ctype));
else
return KRB5KRB_ERR_GENERIC;
}
krb5_boolean valid_cksumtype(krb5_cksumtype ctype)
{
if (!krb5_loaded)
load_krb5_dll();
if (p_valid_cksumtype)
return (p_valid_cksumtype(ctype));
else
return KRB5KRB_ERR_GENERIC;
}
krb5_error_code krb5_kt_free_entry(krb5_context con, krb5_keytab_entry *entry)
{
if (!krb5_loaded)
load_krb5_dll();
if (p_krb5_kt_free_entry)
return (p_krb5_kt_free_entry(con, entry));
else
return KRB5KRB_ERR_GENERIC;
}
/* Structure definitions */
# ifndef NO_DEF_KRB5_CCACHE
# ifndef krb5_x
# define krb5_x(ptr,args) ((ptr)?((*(ptr)) args):(abort(),1))
# define krb5_xc(ptr,args) ((ptr)?((*(ptr)) args):(abort(),(char*)0))
# endif
typedef krb5_pointer krb5_cc_cursor; /* cursor for sequential lookup */
typedef struct _krb5_ccache {
krb5_magic magic;
struct _krb5_cc_ops FAR *ops;
krb5_pointer data;
} *krb5_ccache;
typedef struct _krb5_cc_ops {
krb5_magic magic;
char *prefix;
char *(KRB5_CALLCONV *get_name)
(krb5_context, krb5_ccache);
krb5_error_code(KRB5_CALLCONV *resolve)
(krb5_context, krb5_ccache *, const char *);
krb5_error_code(KRB5_CALLCONV *gen_new)
(krb5_context, krb5_ccache *);
krb5_error_code(KRB5_CALLCONV *init)
(krb5_context, krb5_ccache, krb5_principal);
krb5_error_code(KRB5_CALLCONV *destroy)
(krb5_context, krb5_ccache);
krb5_error_code(KRB5_CALLCONV *close)
(krb5_context, krb5_ccache);
krb5_error_code(KRB5_CALLCONV *store)
(krb5_context, krb5_ccache, krb5_creds *);
krb5_error_code(KRB5_CALLCONV *retrieve)
(krb5_context, krb5_ccache, krb5_flags, krb5_creds *, krb5_creds *);
krb5_error_code(KRB5_CALLCONV *get_princ)
(krb5_context, krb5_ccache, krb5_principal *);
krb5_error_code(KRB5_CALLCONV *get_first)
(krb5_context, krb5_ccache, krb5_cc_cursor *);
krb5_error_code(KRB5_CALLCONV *get_next)
(krb5_context, krb5_ccache, krb5_cc_cursor *, krb5_creds *);
krb5_error_code(KRB5_CALLCONV *end_get)
(krb5_context, krb5_ccache, krb5_cc_cursor *);
krb5_error_code(KRB5_CALLCONV *remove_cred)
(krb5_context, krb5_ccache, krb5_flags, krb5_creds *);
krb5_error_code(KRB5_CALLCONV *set_flags)
(krb5_context, krb5_ccache, krb5_flags);
} krb5_cc_ops;
# endif /* NO_DEF_KRB5_CCACHE */
krb5_error_code
kssl_krb5_cc_get_principal
(krb5_context context, krb5_ccache cache, krb5_principal *principal) {
if (p_krb5_cc_get_principal)
return (p_krb5_cc_get_principal(context, cache, principal));
else
return (krb5_x((cache)->ops->get_princ, (context, cache, principal)));
}
krb5_error_code
kssl_krb5_auth_con_setrcache(krb5_context con, krb5_auth_context acon,
krb5_rcache rcache)
{
if (p_krb5_auth_con_setrcache)
return (p_krb5_auth_con_setrcache(con, acon, rcache));
else
return KRB5KRB_ERR_GENERIC;
}
krb5_error_code
kssl_krb5_get_server_rcache(krb5_context con, krb5_const krb5_data *data,
krb5_rcache *rcache)
{
if (p_krb5_get_server_rcache)
return (p_krb5_get_server_rcache(con, data, rcache));
else
return KRB5KRB_ERR_GENERIC;
}
krb5_error_code
kssl_krb5_auth_con_getrcache(krb5_context con, krb5_auth_context acon,
krb5_rcache *prcache)
{
if (p_krb5_auth_con_getrcache)
return (p_krb5_auth_con_getrcache(con, acon, prcache));
else
return KRB5KRB_ERR_GENERIC;
}
krb5_error_code kssl_krb5_kt_close(krb5_context context, krb5_keytab keytab)
{
if (p_krb5_kt_close)
return (p_krb5_kt_close(context, keytab));
else
return KRB5KRB_ERR_GENERIC;
}
krb5_error_code
kssl_krb5_kt_get_entry(krb5_context context, krb5_keytab keytab,
krb5_const_principal principal, krb5_kvno vno,
krb5_enctype enctype, krb5_keytab_entry *entry)
{
if (p_krb5_kt_get_entry)
return (p_krb5_kt_get_entry
(context, keytab, principal, vno, enctype, entry));
else
return KRB5KRB_ERR_GENERIC;
}
# endif /* OPENSSL_SYS_WINDOWS || OPENSSL_SYS_WIN32 */
/*
* memory allocation functions for non-temporary storage (e.g. stuff that
* gets saved into the kssl context)
*/
static void *kssl_calloc(size_t nmemb, size_t size)
{
void *p;
p = OPENSSL_malloc(nmemb * size);
if (p) {
memset(p, 0, nmemb * size);
}
return p;
}
# define kssl_malloc(size) OPENSSL_malloc((size))
# define kssl_realloc(ptr, size) OPENSSL_realloc(ptr, size)
# define kssl_free(ptr) OPENSSL_free((ptr))
char
*kstring(char *string)
{
static char *null = "[NULL]";
return ((string == NULL) ? null : string);
}
/*
* Given KRB5 enctype (basically DES or 3DES), return closest match openssl
* EVP_ encryption algorithm. Return NULL for unknown or problematic
* (krb5_dk_encrypt) enctypes. Assume ENCTYPE_*_RAW (krb5_raw_encrypt) are
* OK.
*/
const EVP_CIPHER *kssl_map_enc(krb5_enctype enctype)
{
switch (enctype) {
case ENCTYPE_DES_HMAC_SHA1: /* EVP_des_cbc(); */
case ENCTYPE_DES_CBC_CRC:
case ENCTYPE_DES_CBC_MD4:
case ENCTYPE_DES_CBC_MD5:
case ENCTYPE_DES_CBC_RAW:
return EVP_des_cbc();
break;
case ENCTYPE_DES3_CBC_SHA1: /* EVP_des_ede3_cbc(); */
case ENCTYPE_DES3_CBC_SHA:
case ENCTYPE_DES3_CBC_RAW:
return EVP_des_ede3_cbc();
break;
default:
return NULL;
break;
}
}
/*
* Return true:1 if p "looks like" the start of the real authenticator
* described in kssl_skip_confound() below. The ASN.1 pattern is "62 xx 30
* yy" (APPLICATION-2, SEQUENCE), where xx-yy =~ 2, and xx and yy are
* possibly multi-byte length fields.
*/
static int kssl_test_confound(unsigned char *p)
{
int len = 2;
int xx = 0, yy = 0;
if (*p++ != 0x62)
return 0;
if (*p > 0x82)
return 0;
switch (*p) {
case 0x82:
p++;
xx = (*p++ << 8);
xx += *p++;
break;
case 0x81:
p++;
xx = *p++;
break;
case 0x80:
return 0;
default:
xx = *p++;
break;
}
if (*p++ != 0x30)
return 0;
if (*p > 0x82)
return 0;
switch (*p) {
case 0x82:
p++;
len += 2;
yy = (*p++ << 8);
yy += *p++;
break;
case 0x81:
p++;
len++;
yy = *p++;
break;
case 0x80:
return 0;
default:
yy = *p++;
break;
}
return (xx - len == yy) ? 1 : 0;
}
/*
* Allocate, fill, and return cksumlens array of checksum lengths. This
* array holds just the unique elements from the krb5_cksumarray[]. array[n]
* == 0 signals end of data. The krb5_cksumarray[] was an internal variable
* that has since been replaced by a more general method for storing the
* data. It should not be used. Instead we use real API calls and make a
* guess for what the highest assigned CKSUMTYPE_ constant is. As of 1.2.2
* it is 0x000c (CKSUMTYPE_HMAC_SHA1_DES3). So we will use 0x0010.
*/
static size_t *populate_cksumlens(void)
{
int i, j, n;
static size_t *cklens = NULL;
# ifdef KRB5_MIT_OLD11
n = krb5_max_cksum;
# else
n = 0x0010;
# endif /* KRB5_MIT_OLD11 */
# ifdef KRB5CHECKAUTH
if (!cklens && !(cklens = (size_t *)calloc(sizeof(int), n + 1)))
return NULL;
for (i = 0; i < n; i++) {
if (!valid_cksumtype(i))
continue; /* array has holes */
for (j = 0; j < n; j++) {
if (cklens[j] == 0) {
cklens[j] = krb5_checksum_size(NULL, i);
break; /* krb5 elem was new: add */
}
if (cklens[j] == krb5_checksum_size(NULL, i)) {
break; /* ignore duplicate elements */
}
}
}
# endif /* KRB5CHECKAUTH */
return cklens;
}
/*-
* Return pointer to start of real authenticator within authenticator, or
* return NULL on error.
* Decrypted authenticator looks like this:
* [0 or 8 byte confounder] [4-24 byte checksum] [real authent'r]
* This hackery wouldn't be necessary if MIT KRB5 1.0.6 had the
* krb5_auth_con_getcksumtype() function advertised in its krb5.h.
*/
unsigned char *kssl_skip_confound(krb5_enctype etype, unsigned char *a)
{
int i, conlen;
size_t cklen;
static size_t *cksumlens = NULL;
unsigned char *test_auth;
conlen = (etype) ? 8 : 0;
if (!cksumlens && !(cksumlens = populate_cksumlens()))
return NULL;
for (i = 0; (cklen = cksumlens[i]) != 0; i++) {
test_auth = a + conlen + cklen;
if (kssl_test_confound(test_auth))
return test_auth;
}
return NULL;
}
/*
* Set kssl_err error info when reason text is a simple string kssl_err =
* struct { int reason; char text[KSSL_ERR_MAX+1]; }
*/
void kssl_err_set(KSSL_ERR *kssl_err, int reason, char *text)
{
if (kssl_err == NULL)
return;
kssl_err->reason = reason;
BIO_snprintf(kssl_err->text, KSSL_ERR_MAX, "%s", text);
return;
}
/*
* Display contents of krb5_data struct, for debugging
*/
void print_krb5_data(char *label, krb5_data *kdata)
{
int i;
fprintf(stderr, "%s[%d] ", label, kdata->length);
for (i = 0; i < (int)kdata->length; i++) {
if (0 && isprint((int)kdata->data[i]))
fprintf(stderr, "%c ", kdata->data[i]);
else
fprintf(stderr, "%02x ", (unsigned char)kdata->data[i]);
}
fprintf(stderr, "\n");
}
/*
* Display contents of krb5_authdata struct, for debugging
*/
void print_krb5_authdata(char *label, krb5_authdata **adata)
{
if (adata == NULL) {
fprintf(stderr, "%s, authdata==0\n", label);
return;
}
fprintf(stderr, "%s [%p]\n", label, (void *)adata);
# if 0
{
int i;
fprintf(stderr, "%s[at%d:%d] ", label, adata->ad_type, adata->length);
for (i = 0; i < adata->length; i++) {
fprintf(stderr, (isprint(adata->contents[i])) ? "%c " : "%02x",
adata->contents[i]);
}
fprintf(stderr, "\n");
}
# endif
}
/*
* Display contents of krb5_keyblock struct, for debugging
*/
void print_krb5_keyblock(char *label, krb5_keyblock *keyblk)
{
int i;
if (keyblk == NULL) {
fprintf(stderr, "%s, keyblk==0\n", label);
return;
}
# ifdef KRB5_HEIMDAL
fprintf(stderr, "%s\n\t[et%d:%d]: ", label, keyblk->keytype,
keyblk->keyvalue->length);
for (i = 0; i < (int)keyblk->keyvalue->length; i++) {
fprintf(stderr, "%02x",
(unsigned char *)(keyblk->keyvalue->contents)[i]);
}
fprintf(stderr, "\n");
# else
fprintf(stderr, "%s\n\t[et%d:%d]: ", label, keyblk->enctype,
keyblk->length);
for (i = 0; i < (int)keyblk->length; i++) {
fprintf(stderr, "%02x", keyblk->contents[i]);
}
fprintf(stderr, "\n");
# endif
}
/*
* Display contents of krb5_principal_data struct, for debugging
* (krb5_principal is typedef'd == krb5_principal_data *)
*/
static void print_krb5_princ(char *label, krb5_principal_data *princ)
{
int i, ui, uj;
fprintf(stderr, "%s principal Realm: ", label);
if (princ == NULL)
return;
for (ui = 0; ui < (int)princ->realm.length; ui++)
putchar(princ->realm.data[ui]);
fprintf(stderr, " (nametype %d) has %d strings:\n", princ->type,
princ->length);
for (i = 0; i < (int)princ->length; i++) {
fprintf(stderr, "\t%d [%d]: ", i, princ->data[i].length);
for (uj = 0; uj < (int)princ->data[i].length; uj++) {
putchar(princ->data[i].data[uj]);
}
fprintf(stderr, "\n");
}
return;
}
/*- Given krb5 service (typically "kssl") and hostname in kssl_ctx,
* Return encrypted Kerberos ticket for service @ hostname.
* If authenp is non-NULL, also return encrypted authenticator,
* whose data should be freed by caller.
* (Originally was: Create Kerberos AP_REQ message for SSL Client.)
*
* 19990628 VRS Started; Returns Kerberos AP_REQ message.
* 20010409 VRS Modified for RFC2712; Returns enc tkt.
* 20010606 VRS May also return optional authenticator.
*/
krb5_error_code kssl_cget_tkt( /* UPDATE */ KSSL_CTX *kssl_ctx,
/*
* OUT
*/ krb5_data **enc_ticketp,
/*
* UPDATE
*/ krb5_data *authenp,
/*
* OUT
*/ KSSL_ERR *kssl_err)
{
krb5_error_code krb5rc = KRB5KRB_ERR_GENERIC;
krb5_context krb5context = NULL;
krb5_auth_context krb5auth_context = NULL;
krb5_ccache krb5ccdef = NULL;
krb5_creds krb5creds, *krb5credsp = NULL;
krb5_data krb5_app_req;
kssl_err_set(kssl_err, 0, "");
memset((char *)&krb5creds, 0, sizeof(krb5creds));
if (!kssl_ctx) {
kssl_err_set(kssl_err, SSL_R_KRB5_S_INIT, "No kssl_ctx defined.\n");
goto err;
} else if (!kssl_ctx->service_host) {
kssl_err_set(kssl_err, SSL_R_KRB5_S_INIT,
"kssl_ctx service_host undefined.\n");
goto err;
}
if ((krb5rc = krb5_init_context(&krb5context)) != 0) {
BIO_snprintf(kssl_err->text, KSSL_ERR_MAX,
"krb5_init_context() fails: %d\n", krb5rc);
kssl_err->reason = SSL_R_KRB5_C_INIT;
goto err;
}
if ((krb5rc = krb5_sname_to_principal(krb5context,
kssl_ctx->service_host,
(kssl_ctx->service_name) ?
kssl_ctx->service_name : KRB5SVC,
KRB5_NT_SRV_HST,
&krb5creds.server)) != 0) {
BIO_snprintf(kssl_err->text, KSSL_ERR_MAX,
"krb5_sname_to_principal() fails for %s/%s\n",
kssl_ctx->service_host,
(kssl_ctx->
service_name) ? kssl_ctx->service_name : KRB5SVC);
kssl_err->reason = SSL_R_KRB5_C_INIT;
goto err;
}
if ((krb5rc = krb5_cc_default(krb5context, &krb5ccdef)) != 0) {
kssl_err_set(kssl_err, SSL_R_KRB5_C_CC_PRINC,
"krb5_cc_default fails.\n");
goto err;
}
if ((krb5rc = krb5_cc_get_principal(krb5context, krb5ccdef,
&krb5creds.client)) != 0) {
kssl_err_set(kssl_err, SSL_R_KRB5_C_CC_PRINC,
"krb5_cc_get_principal() fails.\n");
goto err;
}
if ((krb5rc = krb5_get_credentials(krb5context, 0, krb5ccdef,
&krb5creds, &krb5credsp)) != 0) {
kssl_err_set(kssl_err, SSL_R_KRB5_C_GET_CRED,
"krb5_get_credentials() fails.\n");
goto err;
}
*enc_ticketp = &krb5credsp->ticket;
# ifdef KRB5_HEIMDAL
kssl_ctx->enctype = krb5credsp->session.keytype;
# else
kssl_ctx->enctype = krb5credsp->keyblock.enctype;
# endif
krb5rc = KRB5KRB_ERR_GENERIC;
/* caller should free data of krb5_app_req */
/*
* 20010406 VRS deleted for real KerberosWrapper 20010605 VRS reinstated
* to offer Authenticator to KerberosWrapper
*/
krb5_app_req.length = 0;
if (authenp) {
krb5_data krb5in_data;
const unsigned char *p;
long arlen;
KRB5_APREQBODY *ap_req;
authenp->length = 0;
krb5in_data.data = NULL;
krb5in_data.length = 0;
if ((krb5rc = krb5_mk_req_extended(krb5context,
&krb5auth_context, 0, &krb5in_data,
krb5credsp, &krb5_app_req)) != 0) {
kssl_err_set(kssl_err, SSL_R_KRB5_C_MK_REQ,
"krb5_mk_req_extended() fails.\n");
goto err;
}
arlen = krb5_app_req.length;
p = (unsigned char *)krb5_app_req.data;
ap_req = (KRB5_APREQBODY *)d2i_KRB5_APREQ(NULL, &p, arlen);
if (ap_req) {
authenp->length = i2d_KRB5_ENCDATA(ap_req->authenticator, NULL);
if (authenp->length && (authenp->data = malloc(authenp->length))) {
unsigned char *adp = (unsigned char *)authenp->data;
authenp->length =
i2d_KRB5_ENCDATA(ap_req->authenticator, &adp);
}
}
if (ap_req)
KRB5_APREQ_free((KRB5_APREQ *) ap_req);
if (krb5_app_req.length)
kssl_krb5_free_data_contents(krb5context, &krb5_app_req);
}
# ifdef KRB5_HEIMDAL
if (kssl_ctx_setkey(kssl_ctx, &krb5credsp->session)) {
kssl_err_set(kssl_err, SSL_R_KRB5_C_INIT,
"kssl_ctx_setkey() fails.\n");
}
# else
if (kssl_ctx_setkey(kssl_ctx, &krb5credsp->keyblock)) {
kssl_err_set(kssl_err, SSL_R_KRB5_C_INIT,
"kssl_ctx_setkey() fails.\n");
}
# endif
else
krb5rc = 0;
err:
# ifdef KSSL_DEBUG
kssl_ctx_show(kssl_ctx);
# endif /* KSSL_DEBUG */
if (krb5creds.client)
krb5_free_principal(krb5context, krb5creds.client);
if (krb5creds.server)
krb5_free_principal(krb5context, krb5creds.server);
if (krb5auth_context)
krb5_auth_con_free(krb5context, krb5auth_context);
if (krb5context)
krb5_free_context(krb5context);
return (krb5rc);
}
/*-
* Given d2i_-decoded asn1ticket, allocate and return a new krb5_ticket.
* Return Kerberos error code and kssl_err struct on error.
* Allocates krb5_ticket and krb5_principal; caller should free these.
*
* 20010410 VRS Implemented krb5_decode_ticket() as
* old_krb5_decode_ticket(). Missing from MIT1.0.6.
* 20010615 VRS Re-cast as openssl/asn1 d2i_*() functions.
* Re-used some of the old krb5_decode_ticket()
* code here. This tkt should alloc/free just
* like the real thing.
*/
static krb5_error_code kssl_TKT2tkt( /* IN */ krb5_context krb5context,
/*
* IN
*/ KRB5_TKTBODY *asn1ticket,
/*
* OUT
*/ krb5_ticket **krb5ticket,
/*
* OUT
*/ KSSL_ERR *kssl_err)
{
krb5_error_code krb5rc = KRB5KRB_ERR_GENERIC;
krb5_ticket *new5ticket = NULL;
ASN1_GENERALSTRING *gstr_svc, *gstr_host;
*krb5ticket = NULL;
if (asn1ticket == NULL || asn1ticket->realm == NULL ||
asn1ticket->sname == NULL ||
sk_ASN1_GENERALSTRING_num(asn1ticket->sname->namestring) < 2) {
BIO_snprintf(kssl_err->text, KSSL_ERR_MAX,
"Null field in asn1ticket.\n");
kssl_err->reason = SSL_R_KRB5_S_RD_REQ;
return KRB5KRB_ERR_GENERIC;
}
if ((new5ticket = (krb5_ticket *)calloc(1, sizeof(krb5_ticket))) == NULL) {
BIO_snprintf(kssl_err->text, KSSL_ERR_MAX,
"Unable to allocate new krb5_ticket.\n");
kssl_err->reason = SSL_R_KRB5_S_RD_REQ;
return ENOMEM; /* or KRB5KRB_ERR_GENERIC; */
}
gstr_svc = sk_ASN1_GENERALSTRING_value(asn1ticket->sname->namestring, 0);
gstr_host = sk_ASN1_GENERALSTRING_value(asn1ticket->sname->namestring, 1);
if ((krb5rc = kssl_build_principal_2(krb5context,
&new5ticket->server,
asn1ticket->realm->length,
(char *)asn1ticket->realm->data,
gstr_svc->length,
(char *)gstr_svc->data,
gstr_host->length,
(char *)gstr_host->data)) != 0) {
free(new5ticket);
BIO_snprintf(kssl_err->text, KSSL_ERR_MAX,
"Error building ticket server principal.\n");
kssl_err->reason = SSL_R_KRB5_S_RD_REQ;
return krb5rc; /* or KRB5KRB_ERR_GENERIC; */
}
krb5_princ_type(krb5context, new5ticket->server) =
asn1ticket->sname->nametype->data[0];
new5ticket->enc_part.enctype = asn1ticket->encdata->etype->data[0];
new5ticket->enc_part.kvno = asn1ticket->encdata->kvno->data[0];
new5ticket->enc_part.ciphertext.length =
asn1ticket->encdata->cipher->length;
if ((new5ticket->enc_part.ciphertext.data =
calloc(1, asn1ticket->encdata->cipher->length)) == NULL) {
free(new5ticket);
BIO_snprintf(kssl_err->text, KSSL_ERR_MAX,
"Error allocating cipher in krb5ticket.\n");
kssl_err->reason = SSL_R_KRB5_S_RD_REQ;
return KRB5KRB_ERR_GENERIC;
} else {
memcpy(new5ticket->enc_part.ciphertext.data,
asn1ticket->encdata->cipher->data,
asn1ticket->encdata->cipher->length);
}
*krb5ticket = new5ticket;
return 0;
}
/*-
* Given krb5 service name in KSSL_CTX *kssl_ctx (typically "kssl"),
* and krb5 AP_REQ message & message length,
* Return Kerberos session key and client principle
* to SSL Server in KSSL_CTX *kssl_ctx.
*
* 19990702 VRS Started.
*/
krb5_error_code kssl_sget_tkt( /* UPDATE */ KSSL_CTX *kssl_ctx,
/*
* IN
*/ krb5_data *indata,
/*
* OUT
*/ krb5_ticket_times *ttimes,
/*
* OUT
*/ KSSL_ERR *kssl_err)
{
krb5_error_code krb5rc = KRB5KRB_ERR_GENERIC;
static krb5_context krb5context = NULL;
static krb5_auth_context krb5auth_context = NULL;
krb5_ticket *krb5ticket = NULL;
KRB5_TKTBODY *asn1ticket = NULL;
const unsigned char *p;
krb5_keytab krb5keytab = NULL;
krb5_keytab_entry kt_entry;
krb5_principal krb5server;
krb5_rcache rcache = NULL;
kssl_err_set(kssl_err, 0, "");
if (!kssl_ctx) {
kssl_err_set(kssl_err, SSL_R_KRB5_S_INIT, "No kssl_ctx defined.\n");
goto err;
}
# ifdef KSSL_DEBUG
fprintf(stderr, "in kssl_sget_tkt(%s)\n",
kstring(kssl_ctx->service_name));
# endif /* KSSL_DEBUG */
if (!krb5context && (krb5rc = krb5_init_context(&krb5context))) {
kssl_err_set(kssl_err, SSL_R_KRB5_S_INIT,
"krb5_init_context() fails.\n");
goto err;
}
if (krb5auth_context &&
(krb5rc = krb5_auth_con_free(krb5context, krb5auth_context))) {
kssl_err_set(kssl_err, SSL_R_KRB5_S_INIT,
"krb5_auth_con_free() fails.\n");
goto err;
} else
krb5auth_context = NULL;
if (!krb5auth_context &&
(krb5rc = krb5_auth_con_init(krb5context, &krb5auth_context))) {
kssl_err_set(kssl_err, SSL_R_KRB5_S_INIT,
"krb5_auth_con_init() fails.\n");
goto err;
}
if ((krb5rc = krb5_auth_con_getrcache(krb5context, krb5auth_context,
&rcache))) {
kssl_err_set(kssl_err, SSL_R_KRB5_S_INIT,
"krb5_auth_con_getrcache() fails.\n");
goto err;
}
if ((krb5rc = krb5_sname_to_principal(krb5context, NULL,
(kssl_ctx->service_name) ?
kssl_ctx->service_name : KRB5SVC,
KRB5_NT_SRV_HST,
&krb5server)) != 0) {
kssl_err_set(kssl_err, SSL_R_KRB5_S_INIT,
"krb5_sname_to_principal() fails.\n");
goto err;
}
if (rcache == NULL) {
if ((krb5rc = krb5_get_server_rcache(krb5context,
krb5_princ_component(krb5context,
krb5server,
0),
&rcache))) {
kssl_err_set(kssl_err, SSL_R_KRB5_S_INIT,
"krb5_get_server_rcache() fails.\n");
goto err;
}
}
if ((krb5rc =
krb5_auth_con_setrcache(krb5context, krb5auth_context, rcache))) {
kssl_err_set(kssl_err, SSL_R_KRB5_S_INIT,
"krb5_auth_con_setrcache() fails.\n");
goto err;
}
/*
* kssl_ctx->keytab_file == NULL ==> use Kerberos default
*/
if (kssl_ctx->keytab_file) {
krb5rc = krb5_kt_resolve(krb5context, kssl_ctx->keytab_file,
&krb5keytab);
if (krb5rc) {
kssl_err_set(kssl_err, SSL_R_KRB5_S_INIT,
"krb5_kt_resolve() fails.\n");
goto err;
}
} else {
krb5rc = krb5_kt_default(krb5context, &krb5keytab);
if (krb5rc) {
kssl_err_set(kssl_err, SSL_R_KRB5_S_INIT,
"krb5_kt_default() fails.\n");
goto err;
}
}
/*- Actual Kerberos5 krb5_recvauth() has initial conversation here
* o check KRB5_SENDAUTH_BADAUTHVERS
* unless KRB5_RECVAUTH_SKIP_VERSION
* o check KRB5_SENDAUTH_BADAPPLVERS
* o send "0" msg if all OK
*/
/*-
* 20010411 was using AP_REQ instead of true KerberosWrapper
*
* if ((krb5rc = krb5_rd_req(krb5context, &krb5auth_context,
* &krb5in_data, krb5server, krb5keytab,
* &ap_option, &krb5ticket)) != 0) { Error }
*/
p = (unsigned char *)indata->data;
if ((asn1ticket = (KRB5_TKTBODY *)d2i_KRB5_TICKET(NULL, &p,
(long)indata->length))
== NULL) {
BIO_snprintf(kssl_err->text, KSSL_ERR_MAX,
"d2i_KRB5_TICKET() ASN.1 decode failure.\n");
kssl_err->reason = SSL_R_KRB5_S_RD_REQ;
goto err;
}
/*
* Was: krb5rc = krb5_decode_ticket(krb5in_data,&krb5ticket)) != 0)
*/
if ((krb5rc = kssl_TKT2tkt(krb5context, asn1ticket, &krb5ticket,
kssl_err)) != 0) {
BIO_snprintf(kssl_err->text, KSSL_ERR_MAX,
"Error converting ASN.1 ticket to krb5_ticket.\n");
kssl_err->reason = SSL_R_KRB5_S_RD_REQ;
goto err;
}
if (!krb5_principal_compare(krb5context, krb5server, krb5ticket->server)) {
krb5rc = KRB5_PRINC_NOMATCH;
BIO_snprintf(kssl_err->text, KSSL_ERR_MAX,
"server principal != ticket principal\n");
kssl_err->reason = SSL_R_KRB5_S_RD_REQ;
goto err;
}
if ((krb5rc = krb5_kt_get_entry(krb5context, krb5keytab,
krb5ticket->server,
krb5ticket->enc_part.kvno,
krb5ticket->enc_part.enctype,
&kt_entry)) != 0) {
BIO_snprintf(kssl_err->text, KSSL_ERR_MAX,
"krb5_kt_get_entry() fails with %x.\n", krb5rc);
kssl_err->reason = SSL_R_KRB5_S_RD_REQ;
goto err;
}
if ((krb5rc = krb5_decrypt_tkt_part(krb5context, &kt_entry.key,
krb5ticket)) != 0) {
BIO_snprintf(kssl_err->text, KSSL_ERR_MAX,
"krb5_decrypt_tkt_part() failed.\n");
kssl_err->reason = SSL_R_KRB5_S_RD_REQ;
goto err;
} else {
krb5_kt_free_entry(krb5context, &kt_entry);
# ifdef KSSL_DEBUG
{
int i;
krb5_address **paddr = krb5ticket->enc_part2->caddrs;
fprintf(stderr, "Decrypted ticket fields:\n");
fprintf(stderr, "\tflags: %X, transit-type: %X",
krb5ticket->enc_part2->flags,
krb5ticket->enc_part2->transited.tr_type);
print_krb5_data("\ttransit-data: ",
&(krb5ticket->enc_part2->transited.tr_contents));
fprintf(stderr, "\tcaddrs: %p, authdata: %p\n",
krb5ticket->enc_part2->caddrs,
krb5ticket->enc_part2->authorization_data);
if (paddr) {
fprintf(stderr, "\tcaddrs:\n");
for (i = 0; paddr[i] != NULL; i++) {
krb5_data d;
d.length = paddr[i]->length;
d.data = paddr[i]->contents;
print_krb5_data("\t\tIP: ", &d);
}
}
fprintf(stderr, "\tstart/auth/end times: %d / %d / %d\n",
krb5ticket->enc_part2->times.starttime,
krb5ticket->enc_part2->times.authtime,
krb5ticket->enc_part2->times.endtime);
}
# endif /* KSSL_DEBUG */
}
krb5rc = KRB5_NO_TKT_SUPPLIED;
if (!krb5ticket || !krb5ticket->enc_part2 ||
!krb5ticket->enc_part2->client ||
!krb5ticket->enc_part2->client->data ||
!krb5ticket->enc_part2->session) {
kssl_err_set(kssl_err, SSL_R_KRB5_S_BAD_TICKET,
"bad ticket from krb5_rd_req.\n");
} else if (kssl_ctx_setprinc(kssl_ctx, KSSL_CLIENT,
&krb5ticket->enc_part2->client->realm,
krb5ticket->enc_part2->client->data,
krb5ticket->enc_part2->client->length)) {
kssl_err_set(kssl_err, SSL_R_KRB5_S_BAD_TICKET,
"kssl_ctx_setprinc() fails.\n");
} else if (kssl_ctx_setkey(kssl_ctx, krb5ticket->enc_part2->session)) {
kssl_err_set(kssl_err, SSL_R_KRB5_S_BAD_TICKET,
"kssl_ctx_setkey() fails.\n");
} else if (krb5ticket->enc_part2->flags & TKT_FLG_INVALID) {
krb5rc = KRB5KRB_AP_ERR_TKT_INVALID;
kssl_err_set(kssl_err, SSL_R_KRB5_S_BAD_TICKET,
"invalid ticket from krb5_rd_req.\n");
} else
krb5rc = 0;
kssl_ctx->enctype = krb5ticket->enc_part.enctype;
ttimes->authtime = krb5ticket->enc_part2->times.authtime;
ttimes->starttime = krb5ticket->enc_part2->times.starttime;
ttimes->endtime = krb5ticket->enc_part2->times.endtime;
ttimes->renew_till = krb5ticket->enc_part2->times.renew_till;
err:
# ifdef KSSL_DEBUG
kssl_ctx_show(kssl_ctx);
# endif /* KSSL_DEBUG */
if (asn1ticket)
KRB5_TICKET_free((KRB5_TICKET *) asn1ticket);
if (krb5keytab)
krb5_kt_close(krb5context, krb5keytab);
if (krb5ticket)
krb5_free_ticket(krb5context, krb5ticket);
if (krb5server)
krb5_free_principal(krb5context, krb5server);
return (krb5rc);
}
/*
* Allocate & return a new kssl_ctx struct.
*/
KSSL_CTX *kssl_ctx_new(void)
{
return ((KSSL_CTX *)kssl_calloc(1, sizeof(KSSL_CTX)));
}
/*
* Frees a kssl_ctx struct and any allocated memory it holds. Returns NULL.
*/
KSSL_CTX *kssl_ctx_free(KSSL_CTX *kssl_ctx)
{
if (kssl_ctx == NULL)
return kssl_ctx;
if (kssl_ctx->key)
OPENSSL_cleanse(kssl_ctx->key, kssl_ctx->length);
if (kssl_ctx->key)
kssl_free(kssl_ctx->key);
if (kssl_ctx->client_princ)
kssl_free(kssl_ctx->client_princ);
if (kssl_ctx->service_host)
kssl_free(kssl_ctx->service_host);
if (kssl_ctx->service_name)
kssl_free(kssl_ctx->service_name);
if (kssl_ctx->keytab_file)
kssl_free(kssl_ctx->keytab_file);
kssl_free(kssl_ctx);
return (KSSL_CTX *)NULL;
}
/*
* Given an array of (krb5_data *) entity (and optional realm), set the plain
* (char *) client_princ or service_host member of the kssl_ctx struct.
*/
krb5_error_code
kssl_ctx_setprinc(KSSL_CTX *kssl_ctx, int which,
krb5_data *realm, krb5_data *entity, int nentities)
{
char **princ;
int length;
int i;
if (kssl_ctx == NULL || entity == NULL)
return KSSL_CTX_ERR;
switch (which) {
case KSSL_CLIENT:
princ = &kssl_ctx->client_princ;
break;
case KSSL_SERVER:
princ = &kssl_ctx->service_host;
break;
default:
return KSSL_CTX_ERR;
break;
}
if (*princ)
kssl_free(*princ);
/* Add up all the entity->lengths */
length = 0;
for (i = 0; i < nentities; i++) {
length += entity[i].length;
}
/* Add in space for the '/' character(s) (if any) */
length += nentities - 1;
/* Space for the ('@'+realm+NULL | NULL) */
length += ((realm) ? realm->length + 2 : 1);
if ((*princ = kssl_calloc(1, length)) == NULL)
return KSSL_CTX_ERR;
else {
for (i = 0; i < nentities; i++) {
strncat(*princ, entity[i].data, entity[i].length);
if (i < nentities - 1) {
strcat(*princ, "/");
}
}
if (realm) {
strcat(*princ, "@");
(void)strncat(*princ, realm->data, realm->length);
}
}
return KSSL_CTX_OK;
}
/*- Set one of the plain (char *) string members of the kssl_ctx struct.
* Default values should be:
* which == KSSL_SERVICE => "khost" (KRB5SVC)
* which == KSSL_KEYTAB => "/etc/krb5.keytab" (KRB5KEYTAB)
*/
krb5_error_code kssl_ctx_setstring(KSSL_CTX *kssl_ctx, int which, char *text)
{
char **string;
if (!kssl_ctx)
return KSSL_CTX_ERR;
switch (which) {
case KSSL_SERVICE:
string = &kssl_ctx->service_name;
break;
case KSSL_SERVER:
string = &kssl_ctx->service_host;
break;
case KSSL_CLIENT:
string = &kssl_ctx->client_princ;
break;
case KSSL_KEYTAB:
string = &kssl_ctx->keytab_file;
break;
default:
return KSSL_CTX_ERR;
break;
}
if (*string)
kssl_free(*string);
if (!text) {
*string = '\0';
return KSSL_CTX_OK;
}
if ((*string = kssl_calloc(1, strlen(text) + 1)) == NULL)
return KSSL_CTX_ERR;
else
strcpy(*string, text);
return KSSL_CTX_OK;
}
/*
* Copy the Kerberos session key from a (krb5_keyblock *) to a kssl_ctx
* struct. Clear kssl_ctx->key if Kerberos session key is NULL.
*/
krb5_error_code kssl_ctx_setkey(KSSL_CTX *kssl_ctx, krb5_keyblock *session)
{
int length;
krb5_enctype enctype;
krb5_octet FAR *contents = NULL;
if (!kssl_ctx)
return KSSL_CTX_ERR;
if (kssl_ctx->key) {
OPENSSL_cleanse(kssl_ctx->key, kssl_ctx->length);
kssl_free(kssl_ctx->key);
}
if (session) {
# ifdef KRB5_HEIMDAL
length = session->keyvalue->length;
enctype = session->keytype;
contents = session->keyvalue->contents;
# else
length = session->length;
enctype = session->enctype;
contents = session->contents;
# endif
kssl_ctx->enctype = enctype;
kssl_ctx->length = length;
} else {
kssl_ctx->enctype = ENCTYPE_UNKNOWN;
kssl_ctx->length = 0;
return KSSL_CTX_OK;
}
if ((kssl_ctx->key =
(krb5_octet FAR *)kssl_calloc(1, kssl_ctx->length)) == NULL) {
kssl_ctx->length = 0;
return KSSL_CTX_ERR;
} else
memcpy(kssl_ctx->key, contents, length);
return KSSL_CTX_OK;
}
/*
* Display contents of kssl_ctx struct
*/
void kssl_ctx_show(KSSL_CTX *kssl_ctx)
{
int i;
printf("kssl_ctx: ");
if (kssl_ctx == NULL) {
printf("NULL\n");
return;
} else
printf("%p\n", (void *)kssl_ctx);
printf("\tservice:\t%s\n",
(kssl_ctx->service_name) ? kssl_ctx->service_name : "NULL");
printf("\tclient:\t%s\n",
(kssl_ctx->client_princ) ? kssl_ctx->client_princ : "NULL");
printf("\tserver:\t%s\n",
(kssl_ctx->service_host) ? kssl_ctx->service_host : "NULL");
printf("\tkeytab:\t%s\n",
(kssl_ctx->keytab_file) ? kssl_ctx->keytab_file : "NULL");
printf("\tkey [%d:%d]:\t", kssl_ctx->enctype, kssl_ctx->length);
for (i = 0; i < kssl_ctx->length && kssl_ctx->key; i++) {
printf("%02x", kssl_ctx->key[i]);
}
printf("\n");
return;
}
int kssl_keytab_is_available(KSSL_CTX *kssl_ctx)
{
krb5_context krb5context = NULL;
krb5_keytab krb5keytab = NULL;
krb5_keytab_entry entry;
krb5_principal princ = NULL;
krb5_error_code krb5rc = KRB5KRB_ERR_GENERIC;
int rc = 0;
if ((krb5rc = krb5_init_context(&krb5context)))
return (0);
/*
* kssl_ctx->keytab_file == NULL ==> use Kerberos default
*/
if (kssl_ctx->keytab_file) {
krb5rc = krb5_kt_resolve(krb5context, kssl_ctx->keytab_file,
&krb5keytab);
if (krb5rc)
goto exit;
} else {
krb5rc = krb5_kt_default(krb5context, &krb5keytab);
if (krb5rc)
goto exit;
}
/* the host key we are looking for */
krb5rc = krb5_sname_to_principal(krb5context, NULL,
kssl_ctx->
service_name ? kssl_ctx->service_name :
KRB5SVC, KRB5_NT_SRV_HST, &princ);
if (krb5rc)
goto exit;
krb5rc = krb5_kt_get_entry(krb5context, krb5keytab, princ,
/* IGNORE_VNO */
0,
/* IGNORE_ENCTYPE */
0, &entry);
if (krb5rc == KRB5_KT_NOTFOUND) {
rc = 1;
goto exit;
} else if (krb5rc)
goto exit;
krb5_kt_free_entry(krb5context, &entry);
rc = 1;
exit:
if (krb5keytab)
krb5_kt_close(krb5context, krb5keytab);
if (princ)
krb5_free_principal(krb5context, princ);
if (krb5context)
krb5_free_context(krb5context);
return (rc);
}
int kssl_tgt_is_available(KSSL_CTX *kssl_ctx)
{
krb5_error_code krb5rc = KRB5KRB_ERR_GENERIC;
krb5_context krb5context = NULL;
krb5_ccache krb5ccdef = NULL;
krb5_creds krb5creds, *krb5credsp = NULL;
int rc = 0;
memset((char *)&krb5creds, 0, sizeof(krb5creds));
if (!kssl_ctx)
return (0);
if (!kssl_ctx->service_host)
return (0);
if ((krb5rc = krb5_init_context(&krb5context)) != 0)
goto err;
if ((krb5rc = krb5_sname_to_principal(krb5context,
kssl_ctx->service_host,
(kssl_ctx->service_name) ?
kssl_ctx->service_name : KRB5SVC,
KRB5_NT_SRV_HST,
&krb5creds.server)) != 0)
goto err;
if ((krb5rc = krb5_cc_default(krb5context, &krb5ccdef)) != 0)
goto err;
if ((krb5rc = krb5_cc_get_principal(krb5context, krb5ccdef,
&krb5creds.client)) != 0)
goto err;
if ((krb5rc = krb5_get_credentials(krb5context, 0, krb5ccdef,
&krb5creds, &krb5credsp)) != 0)
goto err;
rc = 1;
err:
# ifdef KSSL_DEBUG
kssl_ctx_show(kssl_ctx);
# endif /* KSSL_DEBUG */
if (krb5creds.client)
krb5_free_principal(krb5context, krb5creds.client);
if (krb5creds.server)
krb5_free_principal(krb5context, krb5creds.server);
if (krb5context)
krb5_free_context(krb5context);
return (rc);
}
# if !defined(OPENSSL_SYS_WINDOWS) && !defined(OPENSSL_SYS_WIN32)
void kssl_krb5_free_data_contents(krb5_context context, krb5_data *data)
{
# ifdef KRB5_HEIMDAL
data->length = 0;
if (data->data)
free(data->data);
# elif defined(KRB5_MIT_OLD11)
if (data->data) {
krb5_xfree(data->data);
data->data = 0;
}
# else
krb5_free_data_contents(NULL, data);
# endif
}
# endif
/* !OPENSSL_SYS_WINDOWS && !OPENSSL_SYS_WIN32 */
/*
* Given pointers to KerberosTime and struct tm structs, convert the
* KerberosTime string to struct tm. Note that KerberosTime is a
* ASN1_GENERALIZEDTIME value, constrained to GMT with no fractional seconds
* as defined in RFC 1510. Return pointer to the (partially) filled in
* struct tm on success, return NULL on failure.
*/
static struct tm *k_gmtime(ASN1_GENERALIZEDTIME *gtime, struct tm *k_tm)
{
char c, *p;
if (!k_tm)
return NULL;
if (gtime == NULL || gtime->length < 14)
return NULL;
if (gtime->data == NULL)
return NULL;
p = (char *)&gtime->data[14];
c = *p;
*p = '\0';
p -= 2;
k_tm->tm_sec = atoi(p);
*(p + 2) = c;
c = *p;
*p = '\0';
p -= 2;
k_tm->tm_min = atoi(p);
*(p + 2) = c;
c = *p;
*p = '\0';
p -= 2;
k_tm->tm_hour = atoi(p);
*(p + 2) = c;
c = *p;
*p = '\0';
p -= 2;
k_tm->tm_mday = atoi(p);
*(p + 2) = c;
c = *p;
*p = '\0';
p -= 2;
k_tm->tm_mon = atoi(p) - 1;
*(p + 2) = c;
c = *p;
*p = '\0';
p -= 4;
k_tm->tm_year = atoi(p) - 1900;
*(p + 4) = c;
return k_tm;
}
/*
* Helper function for kssl_validate_times(). We need context->clockskew,
* but krb5_context is an opaque struct. So we try to sneek the clockskew
* out through the replay cache. If that fails just return a likely default
* (300 seconds).
*/
static krb5_deltat get_rc_clockskew(krb5_context context)
{
krb5_rcache rc;
krb5_deltat clockskew;
if (krb5_rc_default(context, &rc))
return KSSL_CLOCKSKEW;
if (krb5_rc_initialize(context, rc, 0))
return KSSL_CLOCKSKEW;
if (krb5_rc_get_lifespan(context, rc, &clockskew)) {
clockskew = KSSL_CLOCKSKEW;
}
(void)krb5_rc_destroy(context, rc);
return clockskew;
}
/*
* kssl_validate_times() combines (and more importantly exposes) the MIT KRB5
* internal function krb5_validate_times() and the in_clock_skew() macro.
* The authenticator client time is checked to be within clockskew secs of
* the current time and the current time is checked to be within the ticket
* start and expire times. Either check may be omitted by supplying a NULL
* value. Returns 0 for valid times, SSL_R_KRB5* error codes otherwise. See
* Also: (Kerberos source)/krb5/lib/krb5/krb/valid_times.c 20010420 VRS
*/
krb5_error_code kssl_validate_times(krb5_timestamp atime,
krb5_ticket_times *ttimes)
{
krb5_deltat skew;
krb5_timestamp start, now;
krb5_error_code rc;
krb5_context context;
if ((rc = krb5_init_context(&context)))
return SSL_R_KRB5_S_BAD_TICKET;
skew = get_rc_clockskew(context);
if ((rc = krb5_timeofday(context, &now)))
return SSL_R_KRB5_S_BAD_TICKET;
krb5_free_context(context);
if (atime && labs(atime - now) >= skew)
return SSL_R_KRB5_S_TKT_SKEW;
if (!ttimes)
return 0;
start = (ttimes->starttime != 0) ? ttimes->starttime : ttimes->authtime;
if (start - now > skew)
return SSL_R_KRB5_S_TKT_NYV;
if ((now - ttimes->endtime) > skew)
return SSL_R_KRB5_S_TKT_EXPIRED;
# ifdef KSSL_DEBUG
fprintf(stderr, "kssl_validate_times: %d |<- | %d - %d | < %d ->| %d\n",
start, atime, now, skew, ttimes->endtime);
# endif /* KSSL_DEBUG */
return 0;
}
/*
* Decode and decrypt given DER-encoded authenticator, then pass
* authenticator ctime back in *atimep (or 0 if time unavailable). Returns
* krb5_error_code and kssl_err on error. A NULL authenticator
* (authentp->length == 0) is not considered an error. Note that
* kssl_check_authent() makes use of the KRB5 session key; you must call
* kssl_sget_tkt() to get the key before calling this routine.
*/
krb5_error_code kssl_check_authent(
/*
* IN
*/ KSSL_CTX *kssl_ctx,
/*
* IN
*/ krb5_data *authentp,
/*
* OUT
*/ krb5_timestamp *atimep,
/*
* OUT
*/ KSSL_ERR *kssl_err)
{
krb5_error_code krb5rc = 0;
KRB5_ENCDATA *dec_authent = NULL;
KRB5_AUTHENTBODY *auth = NULL;
krb5_enctype enctype;
EVP_CIPHER_CTX ciph_ctx;
const EVP_CIPHER *enc = NULL;
unsigned char iv[EVP_MAX_IV_LENGTH];
const unsigned char *p;
unsigned char *unenc_authent;
int outl, unencbufsize;
struct tm tm_time, *tm_l, *tm_g;
time_t now, tl, tg, tr, tz_offset;
+ struct tm gmt_result = {0};
+ struct tm lt_result = {0};
EVP_CIPHER_CTX_init(&ciph_ctx);
*atimep = 0;
kssl_err_set(kssl_err, 0, "");
# ifndef KRB5CHECKAUTH
authentp = NULL;
# else
# if KRB5CHECKAUTH == 0
authentp = NULL;
# endif
# endif /* KRB5CHECKAUTH */
if (authentp == NULL || authentp->length == 0)
return 0;
# ifdef KSSL_DEBUG
{
unsigned int ui;
fprintf(stderr, "kssl_check_authent: authenticator[%d]:\n",
authentp->length);
p = authentp->data;
for (ui = 0; ui < authentp->length; ui++)
fprintf(stderr, "%02x ", p[ui]);
fprintf(stderr, "\n");
}
# endif /* KSSL_DEBUG */
unencbufsize = 2 * authentp->length;
if ((unenc_authent = calloc(1, unencbufsize)) == NULL) {
kssl_err_set(kssl_err, SSL_R_KRB5_S_INIT,
"Unable to allocate authenticator buffer.\n");
krb5rc = KRB5KRB_ERR_GENERIC;
goto err;
}
p = (unsigned char *)authentp->data;
if ((dec_authent = d2i_KRB5_ENCDATA(NULL, &p,
(long)authentp->length)) == NULL) {
kssl_err_set(kssl_err, SSL_R_KRB5_S_INIT,
"Error decoding authenticator.\n");
krb5rc = KRB5KRB_AP_ERR_BAD_INTEGRITY;
goto err;
}
enctype = dec_authent->etype->data[0]; /* should = kssl_ctx->enctype */
# if !defined(KRB5_MIT_OLD11)
switch (enctype) {
case ENCTYPE_DES3_CBC_SHA1: /* EVP_des_ede3_cbc(); */
case ENCTYPE_DES3_CBC_SHA:
case ENCTYPE_DES3_CBC_RAW:
krb5rc = 0; /* Skip, can't handle derived keys */
goto err;
}
# endif
enc = kssl_map_enc(enctype);
- memset(iv, 0, sizeof iv); /* per RFC 1510 */
+ memset(iv, 0, sizeof(iv)); /* per RFC 1510 */
if (enc == NULL) {
/*
* Disable kssl_check_authent for ENCTYPE_DES3_CBC_SHA1. This
* enctype indicates the authenticator was encrypted using key-usage
* derived keys which openssl cannot decrypt.
*/
goto err;
}
if (!EVP_CipherInit(&ciph_ctx, enc, kssl_ctx->key, iv, 0)) {
kssl_err_set(kssl_err, SSL_R_KRB5_S_INIT,
"EVP_CipherInit error decrypting authenticator.\n");
krb5rc = KRB5KRB_AP_ERR_BAD_INTEGRITY;
goto err;
}
outl = dec_authent->cipher->length;
if (!EVP_Cipher
(&ciph_ctx, unenc_authent, dec_authent->cipher->data, outl)) {
kssl_err_set(kssl_err, SSL_R_KRB5_S_INIT,
"EVP_Cipher error decrypting authenticator.\n");
krb5rc = KRB5KRB_AP_ERR_BAD_INTEGRITY;
goto err;
}
EVP_CIPHER_CTX_cleanup(&ciph_ctx);
# ifdef KSSL_DEBUG
{
int padl;
fprintf(stderr, "kssl_check_authent: decrypted authenticator[%d] =\n",
outl);
for (padl = 0; padl < outl; padl++)
fprintf(stderr, "%02x ", unenc_authent[padl]);
fprintf(stderr, "\n");
}
# endif /* KSSL_DEBUG */
if ((p = kssl_skip_confound(enctype, unenc_authent)) == NULL) {
kssl_err_set(kssl_err, SSL_R_KRB5_S_INIT,
"confounded by authenticator.\n");
krb5rc = KRB5KRB_AP_ERR_BAD_INTEGRITY;
goto err;
}
outl -= p - unenc_authent;
if ((auth = (KRB5_AUTHENTBODY *)d2i_KRB5_AUTHENT(NULL, &p,
(long)outl)) == NULL) {
kssl_err_set(kssl_err, SSL_R_KRB5_S_INIT,
"Error decoding authenticator body.\n");
krb5rc = KRB5KRB_AP_ERR_BAD_INTEGRITY;
goto err;
}
memset(&tm_time, 0, sizeof(struct tm));
if (k_gmtime(auth->ctime, &tm_time) &&
((tr = mktime(&tm_time)) != (time_t)(-1))) {
now = time(&now);
+ tm_g = OPENSSL_gmtime(&now, &gmt_result);
+
+# if defined(OPENSSL_THREADS) && !defined(OPENSSL_SYS_WIN32) && \
+ !defined(OPENSSL_SYS_OS2) && !defined(OPENSSL_SYS_SUNOS) && \
+ (!defined(OPENSSL_SYS_VMS) || defined(localtime_r))
+ tm_l = localtime_r(&now, &lt_result);
+# else
tm_l = localtime(&now);
+# endif
+
tl = mktime(tm_l);
- tm_g = gmtime(&now);
tg = mktime(tm_g);
tz_offset = tg - tl;
*atimep = (krb5_timestamp)(tr - tz_offset);
}
# ifdef KSSL_DEBUG
fprintf(stderr, "kssl_check_authent: returns %d for client time ",
*atimep);
if (auth && auth->ctime && auth->ctime->length && auth->ctime->data)
fprintf(stderr, "%.*s\n", auth->ctime->length, auth->ctime->data);
else
fprintf(stderr, "NULL\n");
# endif /* KSSL_DEBUG */
err:
if (auth)
KRB5_AUTHENT_free((KRB5_AUTHENT *) auth);
if (dec_authent)
KRB5_ENCDATA_free(dec_authent);
if (unenc_authent)
free(unenc_authent);
EVP_CIPHER_CTX_cleanup(&ciph_ctx);
return krb5rc;
}
/*
* Replaces krb5_build_principal_ext(), with varargs length == 2 (svc, host),
* because I don't know how to stub varargs. Returns krb5_error_code ==
* ENOMEM on alloc error, otherwise passes back newly constructed principal,
* which should be freed by caller.
*/
krb5_error_code kssl_build_principal_2(
/*
* UPDATE
*/ krb5_context context,
/*
* OUT
*/ krb5_principal *princ,
/*
* IN
*/ int rlen, const char *realm,
/*
* IN
*/ int slen, const char *svc,
/*
* IN
*/ int hlen, const char *host)
{
krb5_data *p_data = NULL;
krb5_principal new_p = NULL;
char *new_r = NULL;
if ((p_data = (krb5_data *)calloc(2, sizeof(krb5_data))) == NULL ||
(new_p = (krb5_principal)calloc(1, sizeof(krb5_principal_data)))
== NULL)
goto err;
new_p->length = 2;
new_p->data = p_data;
if ((new_r = calloc(1, rlen + 1)) == NULL)
goto err;
memcpy(new_r, realm, rlen);
krb5_princ_set_realm_length(context, new_p, rlen);
krb5_princ_set_realm_data(context, new_p, new_r);
if ((new_p->data[0].data = calloc(1, slen + 1)) == NULL)
goto err;
memcpy(new_p->data[0].data, svc, slen);
new_p->data[0].length = slen;
if ((new_p->data[1].data = calloc(1, hlen + 1)) == NULL)
goto err;
memcpy(new_p->data[1].data, host, hlen);
new_p->data[1].length = hlen;
krb5_princ_type(context, new_p) = KRB5_NT_UNKNOWN;
*princ = new_p;
return 0;
err:
if (new_p && new_p[0].data)
free(new_p[0].data);
if (new_p && new_p[1].data)
free(new_p[1].data);
if (new_p)
free(new_p);
if (new_r)
free(new_r);
return ENOMEM;
}
void SSL_set0_kssl_ctx(SSL *s, KSSL_CTX *kctx)
{
s->kssl_ctx = kctx;
}
KSSL_CTX *SSL_get0_kssl_ctx(SSL *s)
{
return s->kssl_ctx;
}
char *kssl_ctx_get0_client_princ(KSSL_CTX *kctx)
{
if (kctx)
return kctx->client_princ;
return NULL;
}
#else /* !OPENSSL_NO_KRB5 */
# if defined(PEDANTIC) || defined(OPENSSL_SYS_VMS)
static void *dummy = &dummy;
# endif
#endif /* !OPENSSL_NO_KRB5 */
diff --git a/ssl/s23_srvr.c b/ssl/s23_srvr.c
index d3f6db15ccee..d2017e7cf086 100644
--- a/ssl/s23_srvr.c
+++ b/ssl/s23_srvr.c
@@ -1,655 +1,655 @@
/* ssl/s23_srvr.c */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
/* ====================================================================
* Copyright (c) 1998-2006 The OpenSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* openssl-core@openssl.org.
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.openssl.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*
* This product includes cryptographic software written by Eric Young
* (eay@cryptsoft.com). This product includes software written by Tim
* Hudson (tjh@cryptsoft.com).
*
*/
#include <stdio.h>
#include "ssl_locl.h"
#include <openssl/buffer.h>
#include <openssl/rand.h>
#include <openssl/objects.h>
#include <openssl/evp.h>
#ifdef OPENSSL_FIPS
# include <openssl/fips.h>
#endif
static const SSL_METHOD *ssl23_get_server_method(int ver);
int ssl23_get_client_hello(SSL *s);
static const SSL_METHOD *ssl23_get_server_method(int ver)
{
#ifndef OPENSSL_NO_SSL2
if (ver == SSL2_VERSION)
return (SSLv2_server_method());
#endif
#ifndef OPENSSL_NO_SSL3
if (ver == SSL3_VERSION)
return (SSLv3_server_method());
#endif
if (ver == TLS1_VERSION)
return (TLSv1_server_method());
else if (ver == TLS1_1_VERSION)
return (TLSv1_1_server_method());
else if (ver == TLS1_2_VERSION)
return (TLSv1_2_server_method());
else
return (NULL);
}
IMPLEMENT_ssl23_meth_func(SSLv23_server_method,
ssl23_accept,
ssl_undefined_function, ssl23_get_server_method)
int ssl23_accept(SSL *s)
{
BUF_MEM *buf;
unsigned long Time = (unsigned long)time(NULL);
void (*cb) (const SSL *ssl, int type, int val) = NULL;
int ret = -1;
int new_state, state;
RAND_add(&Time, sizeof(Time), 0);
ERR_clear_error();
clear_sys_error();
if (s->info_callback != NULL)
cb = s->info_callback;
else if (s->ctx->info_callback != NULL)
cb = s->ctx->info_callback;
s->in_handshake++;
if (!SSL_in_init(s) || SSL_in_before(s))
SSL_clear(s);
for (;;) {
state = s->state;
switch (s->state) {
case SSL_ST_BEFORE:
case SSL_ST_ACCEPT:
case SSL_ST_BEFORE | SSL_ST_ACCEPT:
case SSL_ST_OK | SSL_ST_ACCEPT:
s->server = 1;
if (cb != NULL)
cb(s, SSL_CB_HANDSHAKE_START, 1);
/* s->version=SSL3_VERSION; */
s->type = SSL_ST_ACCEPT;
if (s->init_buf == NULL) {
if ((buf = BUF_MEM_new()) == NULL) {
ret = -1;
goto end;
}
if (!BUF_MEM_grow(buf, SSL3_RT_MAX_PLAIN_LENGTH)) {
BUF_MEM_free(buf);
ret = -1;
goto end;
}
s->init_buf = buf;
}
if (!ssl3_init_finished_mac(s)) {
ret = -1;
goto end;
}
s->state = SSL23_ST_SR_CLNT_HELLO_A;
s->ctx->stats.sess_accept++;
s->init_num = 0;
break;
case SSL23_ST_SR_CLNT_HELLO_A:
case SSL23_ST_SR_CLNT_HELLO_B:
s->shutdown = 0;
ret = ssl23_get_client_hello(s);
if (ret >= 0)
cb = NULL;
goto end;
/* break; */
default:
SSLerr(SSL_F_SSL23_ACCEPT, SSL_R_UNKNOWN_STATE);
ret = -1;
goto end;
/* break; */
}
if ((cb != NULL) && (s->state != state)) {
new_state = s->state;
s->state = state;
cb(s, SSL_CB_ACCEPT_LOOP, 1);
s->state = new_state;
}
}
end:
s->in_handshake--;
if (cb != NULL)
cb(s, SSL_CB_ACCEPT_EXIT, ret);
return (ret);
}
int ssl23_get_client_hello(SSL *s)
{
/*-
* Request this many bytes in initial read.
* We can detect SSL 3.0/TLS 1.0 Client Hellos
* ('type == 3') correctly only when the following
* is in a single record, which is not guaranteed by
* the protocol specification:
* Byte Content
* 0 type \
* 1/2 version > record header
* 3/4 length /
* 5 msg_type \
* 6-8 length > Client Hello message
* 9/10 client_version /
*/
char buf_space[11];
char *buf = &(buf_space[0]);
unsigned char *p, *d, *d_len, *dd;
unsigned int i;
unsigned int csl, sil, cl;
int n = 0, j;
int type = 0;
int v[2];
if (s->state == SSL23_ST_SR_CLNT_HELLO_A) {
/* read the initial header */
v[0] = v[1] = 0;
if (!ssl3_setup_buffers(s))
goto err;
- n = ssl23_read_bytes(s, sizeof buf_space);
- if (n != sizeof buf_space)
+ n = ssl23_read_bytes(s, sizeof(buf_space));
+ if (n != sizeof(buf_space))
return (n); /* n == -1 || n == 0 */
p = s->packet;
memcpy(buf, p, n);
if ((p[0] & 0x80) && (p[2] == SSL2_MT_CLIENT_HELLO)) {
/*
* SSLv2 header
*/
if ((p[3] == 0x00) && (p[4] == 0x02)) {
v[0] = p[3];
v[1] = p[4];
/* SSLv2 */
if (!(s->options & SSL_OP_NO_SSLv2))
type = 1;
} else if (p[3] == SSL3_VERSION_MAJOR) {
v[0] = p[3];
v[1] = p[4];
/* SSLv3/TLSv1 */
if (p[4] >= TLS1_VERSION_MINOR) {
if (p[4] >= TLS1_2_VERSION_MINOR &&
!(s->options & SSL_OP_NO_TLSv1_2)) {
s->version = TLS1_2_VERSION;
s->state = SSL23_ST_SR_CLNT_HELLO_B;
} else if (p[4] >= TLS1_1_VERSION_MINOR &&
!(s->options & SSL_OP_NO_TLSv1_1)) {
s->version = TLS1_1_VERSION;
/*
* type=2;
*//*
* done later to survive restarts
*/
s->state = SSL23_ST_SR_CLNT_HELLO_B;
} else if (!(s->options & SSL_OP_NO_TLSv1)) {
s->version = TLS1_VERSION;
/*
* type=2;
*//*
* done later to survive restarts
*/
s->state = SSL23_ST_SR_CLNT_HELLO_B;
} else if (!(s->options & SSL_OP_NO_SSLv3)) {
s->version = SSL3_VERSION;
/* type=2; */
s->state = SSL23_ST_SR_CLNT_HELLO_B;
} else if (!(s->options & SSL_OP_NO_SSLv2)) {
type = 1;
}
} else if (!(s->options & SSL_OP_NO_SSLv3)) {
s->version = SSL3_VERSION;
/* type=2; */
s->state = SSL23_ST_SR_CLNT_HELLO_B;
} else if (!(s->options & SSL_OP_NO_SSLv2))
type = 1;
}
}
/* p[4] < 5 ... silly record length? */
else if ((p[0] == SSL3_RT_HANDSHAKE) &&
(p[1] == SSL3_VERSION_MAJOR) &&
(p[5] == SSL3_MT_CLIENT_HELLO) && ((p[3] == 0 && p[4] < 5)
|| (p[9] >= p[1]))) {
/*
* SSLv3 or tls1 header
*/
v[0] = p[1]; /* major version (= SSL3_VERSION_MAJOR) */
/*
* We must look at client_version inside the Client Hello message
* to get the correct minor version. However if we have only a
* pathologically small fragment of the Client Hello message, this
* would be difficult, and we'd have to read more records to find
* out. No known SSL 3.0 client fragments ClientHello like this,
* so we simply reject such connections to avoid protocol version
* downgrade attacks.
*/
if (p[3] == 0 && p[4] < 6) {
SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO, SSL_R_RECORD_TOO_SMALL);
goto err;
}
/*
* if major version number > 3 set minor to a value which will
* use the highest version 3 we support. If TLS 2.0 ever appears
* we will need to revise this....
*/
if (p[9] > SSL3_VERSION_MAJOR)
v[1] = 0xff;
else
v[1] = p[10]; /* minor version according to client_version */
if (v[1] >= TLS1_VERSION_MINOR) {
if (v[1] >= TLS1_2_VERSION_MINOR &&
!(s->options & SSL_OP_NO_TLSv1_2)) {
s->version = TLS1_2_VERSION;
type = 3;
} else if (v[1] >= TLS1_1_VERSION_MINOR &&
!(s->options & SSL_OP_NO_TLSv1_1)) {
s->version = TLS1_1_VERSION;
type = 3;
} else if (!(s->options & SSL_OP_NO_TLSv1)) {
s->version = TLS1_VERSION;
type = 3;
} else if (!(s->options & SSL_OP_NO_SSLv3)) {
s->version = SSL3_VERSION;
type = 3;
}
} else {
/* client requests SSL 3.0 */
if (!(s->options & SSL_OP_NO_SSLv3)) {
s->version = SSL3_VERSION;
type = 3;
} else if (!(s->options & SSL_OP_NO_TLSv1)) {
/*
* we won't be able to use TLS of course, but this will
* send an appropriate alert
*/
s->version = TLS1_VERSION;
type = 3;
}
}
} else if ((strncmp("GET ", (char *)p, 4) == 0) ||
(strncmp("POST ", (char *)p, 5) == 0) ||
(strncmp("HEAD ", (char *)p, 5) == 0) ||
(strncmp("PUT ", (char *)p, 4) == 0)) {
SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO, SSL_R_HTTP_REQUEST);
goto err;
} else if (strncmp("CONNECT", (char *)p, 7) == 0) {
SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO, SSL_R_HTTPS_PROXY_REQUEST);
goto err;
}
}
/* ensure that TLS_MAX_VERSION is up-to-date */
OPENSSL_assert(s->version <= TLS_MAX_VERSION);
if (s->version < TLS1_2_VERSION && tls1_suiteb(s)) {
SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,
SSL_R_ONLY_TLS_1_2_ALLOWED_IN_SUITEB_MODE);
goto err;
}
#ifdef OPENSSL_FIPS
if (FIPS_mode() && (s->version < TLS1_VERSION)) {
SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,
SSL_R_ONLY_TLS_ALLOWED_IN_FIPS_MODE);
goto err;
}
#endif
if (s->state == SSL23_ST_SR_CLNT_HELLO_B) {
/*
* we have SSLv3/TLSv1 in an SSLv2 header (other cases skip this
* state)
*/
type = 2;
p = s->packet;
v[0] = p[3]; /* == SSL3_VERSION_MAJOR */
v[1] = p[4];
/*-
* An SSLv3/TLSv1 backwards-compatible CLIENT-HELLO in an SSLv2
* header is sent directly on the wire, not wrapped as a TLS
* record. It's format is:
* Byte Content
* 0-1 msg_length
* 2 msg_type
* 3-4 version
* 5-6 cipher_spec_length
* 7-8 session_id_length
* 9-10 challenge_length
* ... ...
*/
n = ((p[0] & 0x7f) << 8) | p[1];
if (n > (1024 * 4)) {
SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO, SSL_R_RECORD_TOO_LARGE);
goto err;
}
if (n < 9) {
SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,
SSL_R_RECORD_LENGTH_MISMATCH);
goto err;
}
j = ssl23_read_bytes(s, n + 2);
/*
* We previously read 11 bytes, so if j > 0, we must have j == n+2 ==
* s->packet_length. We have at least 11 valid packet bytes.
*/
if (j <= 0)
return (j);
ssl3_finish_mac(s, s->packet + 2, s->packet_length - 2);
/* CLIENT-HELLO */
if (s->msg_callback)
s->msg_callback(0, SSL2_VERSION, 0, s->packet + 2,
s->packet_length - 2, s, s->msg_callback_arg);
p = s->packet;
p += 5;
n2s(p, csl);
n2s(p, sil);
n2s(p, cl);
d = (unsigned char *)s->init_buf->data;
if ((csl + sil + cl + 11) != s->packet_length) { /* We can't have TLS
* extensions in SSL
* 2.0 format *
* Client Hello, can
* we? Error
* condition should
* be * '>'
* otherweise */
SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,
SSL_R_RECORD_LENGTH_MISMATCH);
goto err;
}
/* record header: msg_type ... */
*(d++) = SSL3_MT_CLIENT_HELLO;
/* ... and length (actual value will be written later) */
d_len = d;
d += 3;
/* client_version */
*(d++) = SSL3_VERSION_MAJOR; /* == v[0] */
*(d++) = v[1];
/* lets populate the random area */
/* get the challenge_length */
i = (cl > SSL3_RANDOM_SIZE) ? SSL3_RANDOM_SIZE : cl;
memset(d, 0, SSL3_RANDOM_SIZE);
memcpy(&(d[SSL3_RANDOM_SIZE - i]), &(p[csl + sil]), i);
d += SSL3_RANDOM_SIZE;
/* no session-id reuse */
*(d++) = 0;
/* ciphers */
j = 0;
dd = d;
d += 2;
for (i = 0; i < csl; i += 3) {
if (p[i] != 0)
continue;
*(d++) = p[i + 1];
*(d++) = p[i + 2];
j += 2;
}
s2n(j, dd);
/* COMPRESSION */
*(d++) = 1;
*(d++) = 0;
#if 0
/* copy any remaining data with may be extensions */
p = p + csl + sil + cl;
while (p < s->packet + s->packet_length) {
*(d++) = *(p++);
}
#endif
i = (d - (unsigned char *)s->init_buf->data) - 4;
l2n3((long)i, d_len);
/* get the data reused from the init_buf */
s->s3->tmp.reuse_message = 1;
s->s3->tmp.message_type = SSL3_MT_CLIENT_HELLO;
s->s3->tmp.message_size = i;
}
/* imaginary new state (for program structure): */
/* s->state = SSL23_SR_CLNT_HELLO_C */
if (type == 1) {
#ifdef OPENSSL_NO_SSL2
SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO, SSL_R_UNSUPPORTED_PROTOCOL);
goto err;
#else
/* we are talking sslv2 */
/*
* we need to clean up the SSLv3/TLSv1 setup and put in the sslv2
* stuff.
*/
if (s->s2 == NULL) {
if (!ssl2_new(s))
goto err;
} else
ssl2_clear(s);
if (s->s3 != NULL)
ssl3_free(s);
if (!BUF_MEM_grow_clean(s->init_buf,
SSL2_MAX_RECORD_LENGTH_3_BYTE_HEADER)) {
goto err;
}
s->state = SSL2_ST_GET_CLIENT_HELLO_A;
if (s->options & SSL_OP_NO_TLSv1 && s->options & SSL_OP_NO_SSLv3)
s->s2->ssl2_rollback = 0;
else
/*
* reject SSL 2.0 session if client supports SSL 3.0 or TLS 1.0
* (SSL 3.0 draft/RFC 2246, App. E.2)
*/
s->s2->ssl2_rollback = 1;
/*
* setup the n bytes we have read so we get them from the sslv2
* buffer
*/
s->rstate = SSL_ST_READ_HEADER;
s->packet_length = n;
s->packet = &(s->s2->rbuf[0]);
memcpy(s->packet, buf, n);
s->s2->rbuf_left = n;
s->s2->rbuf_offs = 0;
s->method = SSLv2_server_method();
s->handshake_func = s->method->ssl_accept;
#endif
}
if ((type == 2) || (type == 3)) {
/*
* we have SSLv3/TLSv1 (type 2: SSL2 style, type 3: SSL3/TLS style)
*/
const SSL_METHOD *new_method;
new_method = ssl23_get_server_method(s->version);
if (new_method == NULL) {
SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO, SSL_R_UNSUPPORTED_PROTOCOL);
goto err;
}
s->method = new_method;
if (!ssl_init_wbio_buffer(s, 1))
goto err;
/* we are in this state */
s->state = SSL3_ST_SR_CLNT_HELLO_A;
if (type == 3) {
/*
* put the 'n' bytes we have read into the input buffer for SSLv3
*/
s->rstate = SSL_ST_READ_HEADER;
s->packet_length = n;
if (s->s3->rbuf.buf == NULL)
if (!ssl3_setup_read_buffer(s))
goto err;
s->packet = &(s->s3->rbuf.buf[0]);
memcpy(s->packet, buf, n);
s->s3->rbuf.left = n;
s->s3->rbuf.offset = 0;
} else {
s->packet_length = 0;
s->s3->rbuf.left = 0;
s->s3->rbuf.offset = 0;
}
#if 0 /* ssl3_get_client_hello does this */
s->client_version = (v[0] << 8) | v[1];
#endif
s->handshake_func = s->method->ssl_accept;
}
if ((type < 1) || (type > 3)) {
/* bad, very bad */
SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO, SSL_R_UNKNOWN_PROTOCOL);
goto err;
}
s->init_num = 0;
if (buf != buf_space)
OPENSSL_free(buf);
return (SSL_accept(s));
err:
if (buf != buf_space)
OPENSSL_free(buf);
return (-1);
}
diff --git a/ssl/s2_clnt.c b/ssl/s2_clnt.c
index 20de1a82178f..3a8345ba2f81 100644
--- a/ssl/s2_clnt.c
+++ b/ssl/s2_clnt.c
@@ -1,1094 +1,1094 @@
/* ssl/s2_clnt.c */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
/* ====================================================================
* Copyright (c) 1998-2001 The OpenSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* openssl-core@openssl.org.
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.openssl.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*
* This product includes cryptographic software written by Eric Young
* (eay@cryptsoft.com). This product includes software written by Tim
* Hudson (tjh@cryptsoft.com).
*
*/
#include "ssl_locl.h"
#ifndef OPENSSL_NO_SSL2
# include <stdio.h>
# include <openssl/rand.h>
# include <openssl/buffer.h>
# include <openssl/objects.h>
# include <openssl/evp.h>
static const SSL_METHOD *ssl2_get_client_method(int ver);
static int get_server_finished(SSL *s);
static int get_server_verify(SSL *s);
static int get_server_hello(SSL *s);
static int client_hello(SSL *s);
static int client_master_key(SSL *s);
static int client_finished(SSL *s);
static int client_certificate(SSL *s);
static int ssl_rsa_public_encrypt(SESS_CERT *sc, int len, unsigned char *from,
unsigned char *to, int padding);
# define BREAK break
static const SSL_METHOD *ssl2_get_client_method(int ver)
{
if (ver == SSL2_VERSION)
return (SSLv2_client_method());
else
return (NULL);
}
IMPLEMENT_ssl2_meth_func(SSLv2_client_method,
ssl_undefined_function,
ssl2_connect, ssl2_get_client_method)
int ssl2_connect(SSL *s)
{
unsigned long l = (unsigned long)time(NULL);
BUF_MEM *buf = NULL;
int ret = -1;
void (*cb) (const SSL *ssl, int type, int val) = NULL;
int new_state, state;
RAND_add(&l, sizeof(l), 0);
ERR_clear_error();
clear_sys_error();
if (s->info_callback != NULL)
cb = s->info_callback;
else if (s->ctx->info_callback != NULL)
cb = s->ctx->info_callback;
/* init things to blank */
s->in_handshake++;
if (!SSL_in_init(s) || SSL_in_before(s))
SSL_clear(s);
for (;;) {
state = s->state;
switch (s->state) {
case SSL_ST_BEFORE:
case SSL_ST_CONNECT:
case SSL_ST_BEFORE | SSL_ST_CONNECT:
case SSL_ST_OK | SSL_ST_CONNECT:
s->server = 0;
if (cb != NULL)
cb(s, SSL_CB_HANDSHAKE_START, 1);
s->version = SSL2_VERSION;
s->type = SSL_ST_CONNECT;
buf = s->init_buf;
if ((buf == NULL) && ((buf = BUF_MEM_new()) == NULL)) {
ret = -1;
goto end;
}
if (!BUF_MEM_grow(buf, SSL2_MAX_RECORD_LENGTH_3_BYTE_HEADER)) {
if (buf == s->init_buf)
buf = NULL;
ret = -1;
goto end;
}
s->init_buf = buf;
buf = NULL;
s->init_num = 0;
s->state = SSL2_ST_SEND_CLIENT_HELLO_A;
s->ctx->stats.sess_connect++;
s->handshake_func = ssl2_connect;
BREAK;
case SSL2_ST_SEND_CLIENT_HELLO_A:
case SSL2_ST_SEND_CLIENT_HELLO_B:
s->shutdown = 0;
ret = client_hello(s);
if (ret <= 0)
goto end;
s->init_num = 0;
s->state = SSL2_ST_GET_SERVER_HELLO_A;
BREAK;
case SSL2_ST_GET_SERVER_HELLO_A:
case SSL2_ST_GET_SERVER_HELLO_B:
ret = get_server_hello(s);
if (ret <= 0)
goto end;
s->init_num = 0;
if (!s->hit) { /* new session */
s->state = SSL2_ST_SEND_CLIENT_MASTER_KEY_A;
BREAK;
} else {
s->state = SSL2_ST_CLIENT_START_ENCRYPTION;
break;
}
case SSL2_ST_SEND_CLIENT_MASTER_KEY_A:
case SSL2_ST_SEND_CLIENT_MASTER_KEY_B:
ret = client_master_key(s);
if (ret <= 0)
goto end;
s->init_num = 0;
s->state = SSL2_ST_CLIENT_START_ENCRYPTION;
break;
case SSL2_ST_CLIENT_START_ENCRYPTION:
/*
* Ok, we now have all the stuff needed to start encrypting, so
* lets fire it up :-)
*/
if (!ssl2_enc_init(s, 1)) {
ret = -1;
goto end;
}
s->s2->clear_text = 0;
s->state = SSL2_ST_SEND_CLIENT_FINISHED_A;
break;
case SSL2_ST_SEND_CLIENT_FINISHED_A:
case SSL2_ST_SEND_CLIENT_FINISHED_B:
ret = client_finished(s);
if (ret <= 0)
goto end;
s->init_num = 0;
s->state = SSL2_ST_GET_SERVER_VERIFY_A;
break;
case SSL2_ST_GET_SERVER_VERIFY_A:
case SSL2_ST_GET_SERVER_VERIFY_B:
ret = get_server_verify(s);
if (ret <= 0)
goto end;
s->init_num = 0;
s->state = SSL2_ST_GET_SERVER_FINISHED_A;
break;
case SSL2_ST_GET_SERVER_FINISHED_A:
case SSL2_ST_GET_SERVER_FINISHED_B:
ret = get_server_finished(s);
if (ret <= 0)
goto end;
break;
case SSL2_ST_SEND_CLIENT_CERTIFICATE_A:
case SSL2_ST_SEND_CLIENT_CERTIFICATE_B:
case SSL2_ST_SEND_CLIENT_CERTIFICATE_C:
case SSL2_ST_SEND_CLIENT_CERTIFICATE_D:
case SSL2_ST_X509_GET_CLIENT_CERTIFICATE:
ret = client_certificate(s);
if (ret <= 0)
goto end;
s->init_num = 0;
s->state = SSL2_ST_GET_SERVER_FINISHED_A;
break;
case SSL_ST_OK:
if (s->init_buf != NULL) {
BUF_MEM_free(s->init_buf);
s->init_buf = NULL;
}
s->init_num = 0;
/* ERR_clear_error(); */
/*
* If we want to cache session-ids in the client and we
* successfully add the session-id to the cache, and there is a
* callback, then pass it out. 26/11/96 - eay - only add if not a
* re-used session.
*/
ssl_update_cache(s, SSL_SESS_CACHE_CLIENT);
if (s->hit)
s->ctx->stats.sess_hit++;
ret = 1;
/* s->server=0; */
s->ctx->stats.sess_connect_good++;
if (cb != NULL)
cb(s, SSL_CB_HANDSHAKE_DONE, 1);
goto end;
/* break; */
default:
SSLerr(SSL_F_SSL2_CONNECT, SSL_R_UNKNOWN_STATE);
return (-1);
/* break; */
}
if ((cb != NULL) && (s->state != state)) {
new_state = s->state;
s->state = state;
cb(s, SSL_CB_CONNECT_LOOP, 1);
s->state = new_state;
}
}
end:
s->in_handshake--;
if (buf != NULL)
BUF_MEM_free(buf);
if (cb != NULL)
cb(s, SSL_CB_CONNECT_EXIT, ret);
return (ret);
}
static int get_server_hello(SSL *s)
{
unsigned char *buf;
unsigned char *p;
int i, j;
unsigned long len;
STACK_OF(SSL_CIPHER) *sk = NULL, *cl, *prio, *allow;
buf = (unsigned char *)s->init_buf->data;
p = buf;
if (s->state == SSL2_ST_GET_SERVER_HELLO_A) {
i = ssl2_read(s, (char *)&(buf[s->init_num]), 11 - s->init_num);
if (i < (11 - s->init_num))
return (ssl2_part_read(s, SSL_F_GET_SERVER_HELLO, i));
s->init_num = 11;
if (*(p++) != SSL2_MT_SERVER_HELLO) {
if (p[-1] != SSL2_MT_ERROR) {
ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR);
SSLerr(SSL_F_GET_SERVER_HELLO, SSL_R_READ_WRONG_PACKET_TYPE);
} else
SSLerr(SSL_F_GET_SERVER_HELLO, SSL_R_PEER_ERROR);
return (-1);
}
# if 0
s->hit = (*(p++)) ? 1 : 0;
/*
* Some [PPC?] compilers fail to increment p in above statement, e.g.
* one provided with Rhapsody 5.5, but most recent example XL C 11.1
* for AIX, even without optimization flag...
*/
# else
s->hit = (*p) ? 1 : 0;
p++;
# endif
s->s2->tmp.cert_type = *(p++);
n2s(p, i);
if (i < s->version)
s->version = i;
n2s(p, i);
s->s2->tmp.cert_length = i;
n2s(p, i);
s->s2->tmp.csl = i;
n2s(p, i);
s->s2->tmp.conn_id_length = i;
s->state = SSL2_ST_GET_SERVER_HELLO_B;
}
/* SSL2_ST_GET_SERVER_HELLO_B */
len =
11 + (unsigned long)s->s2->tmp.cert_length +
(unsigned long)s->s2->tmp.csl +
(unsigned long)s->s2->tmp.conn_id_length;
if (len > SSL2_MAX_RECORD_LENGTH_3_BYTE_HEADER) {
SSLerr(SSL_F_GET_SERVER_HELLO, SSL_R_MESSAGE_TOO_LONG);
return -1;
}
j = (int)len - s->init_num;
i = ssl2_read(s, (char *)&(buf[s->init_num]), j);
if (i != j)
return (ssl2_part_read(s, SSL_F_GET_SERVER_HELLO, i));
if (s->msg_callback) {
/* SERVER-HELLO */
s->msg_callback(0, s->version, 0, buf, (size_t)len, s,
s->msg_callback_arg);
}
/* things are looking good */
p = buf + 11;
if (s->hit) {
if (s->s2->tmp.cert_length != 0) {
SSLerr(SSL_F_GET_SERVER_HELLO, SSL_R_REUSE_CERT_LENGTH_NOT_ZERO);
return (-1);
}
if (s->s2->tmp.cert_type != 0) {
if (!(s->options & SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG)) {
SSLerr(SSL_F_GET_SERVER_HELLO,
SSL_R_REUSE_CERT_TYPE_NOT_ZERO);
return (-1);
}
}
if (s->s2->tmp.csl != 0) {
SSLerr(SSL_F_GET_SERVER_HELLO, SSL_R_REUSE_CIPHER_LIST_NOT_ZERO);
return (-1);
}
} else {
# if 0
/* very bad */
memset(s->session->session_id, 0,
SSL_MAX_SSL_SESSION_ID_LENGTH_IN_BYTES);
s->session->session_id_length = 0;
# endif
/*
* we need to do this in case we were trying to reuse a client
* session but others are already reusing it. If this was a new
* 'blank' session ID, the session-id length will still be 0
*/
if (s->session->session_id_length > 0) {
if (!ssl_get_new_session(s, 0)) {
ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR);
return (-1);
}
}
if (ssl2_set_certificate(s, s->s2->tmp.cert_type,
s->s2->tmp.cert_length, p) <= 0) {
ssl2_return_error(s, SSL2_PE_BAD_CERTIFICATE);
return (-1);
}
p += s->s2->tmp.cert_length;
if (s->s2->tmp.csl == 0) {
ssl2_return_error(s, SSL2_PE_NO_CIPHER);
SSLerr(SSL_F_GET_SERVER_HELLO, SSL_R_NO_CIPHER_LIST);
return (-1);
}
/*
* We have just received a list of ciphers back from the server. We
* need to get the ones that match, then select the one we want the
* most :-).
*/
/* load the ciphers */
sk = ssl_bytes_to_cipher_list(s, p, s->s2->tmp.csl,
&s->session->ciphers);
p += s->s2->tmp.csl;
if (sk == NULL) {
ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR);
SSLerr(SSL_F_GET_SERVER_HELLO, ERR_R_MALLOC_FAILURE);
return (-1);
}
(void)sk_SSL_CIPHER_set_cmp_func(sk, ssl_cipher_ptr_id_cmp);
/* get the array of ciphers we will accept */
cl = SSL_get_ciphers(s);
(void)sk_SSL_CIPHER_set_cmp_func(cl, ssl_cipher_ptr_id_cmp);
/*
* If server preference flag set, choose the first
* (highest priority) cipher the server sends, otherwise
* client preference has priority.
*/
if (s->options & SSL_OP_CIPHER_SERVER_PREFERENCE) {
prio = sk;
allow = cl;
} else {
prio = cl;
allow = sk;
}
/*
* In theory we could have ciphers sent back that we don't want to
* use but that does not matter since we will check against the list
* we originally sent and for performance reasons we should not
* bother to match the two lists up just to check.
*/
for (i = 0; i < sk_SSL_CIPHER_num(prio); i++) {
if (sk_SSL_CIPHER_find(allow, sk_SSL_CIPHER_value(prio, i)) >= 0)
break;
}
if (i >= sk_SSL_CIPHER_num(prio)) {
ssl2_return_error(s, SSL2_PE_NO_CIPHER);
SSLerr(SSL_F_GET_SERVER_HELLO, SSL_R_NO_CIPHER_MATCH);
return (-1);
}
s->session->cipher = sk_SSL_CIPHER_value(prio, i);
if (s->session->peer != NULL) { /* can't happen */
ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR);
SSLerr(SSL_F_GET_SERVER_HELLO, ERR_R_INTERNAL_ERROR);
return (-1);
}
s->session->peer = s->session->sess_cert->peer_key->x509;
/* peer_key->x509 has been set by ssl2_set_certificate. */
CRYPTO_add(&s->session->peer->references, 1, CRYPTO_LOCK_X509);
}
if (s->session->sess_cert == NULL
|| s->session->peer != s->session->sess_cert->peer_key->x509)
/* can't happen */
{
ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR);
SSLerr(SSL_F_GET_SERVER_HELLO, ERR_R_INTERNAL_ERROR);
return (-1);
}
s->s2->conn_id_length = s->s2->tmp.conn_id_length;
- if (s->s2->conn_id_length > sizeof s->s2->conn_id) {
+ if (s->s2->conn_id_length > sizeof(s->s2->conn_id)) {
ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR);
SSLerr(SSL_F_GET_SERVER_HELLO, SSL_R_SSL2_CONNECTION_ID_TOO_LONG);
return -1;
}
memcpy(s->s2->conn_id, p, s->s2->tmp.conn_id_length);
return (1);
}
static int client_hello(SSL *s)
{
unsigned char *buf;
unsigned char *p, *d;
/* CIPHER **cipher;*/
int i, n, j;
buf = (unsigned char *)s->init_buf->data;
if (s->state == SSL2_ST_SEND_CLIENT_HELLO_A) {
if ((s->session == NULL) || (s->session->ssl_version != s->version)) {
if (!ssl_get_new_session(s, 0)) {
ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR);
return (-1);
}
}
/* else use the pre-loaded session */
p = buf; /* header */
d = p + 9; /* data section */
*(p++) = SSL2_MT_CLIENT_HELLO; /* type */
s2n(SSL2_VERSION, p); /* version */
n = j = 0;
n = ssl_cipher_list_to_bytes(s, SSL_get_ciphers(s), d, 0);
d += n;
if (n == 0) {
SSLerr(SSL_F_CLIENT_HELLO, SSL_R_NO_CIPHERS_AVAILABLE);
return (-1);
}
s2n(n, p); /* cipher spec num bytes */
if ((s->session->session_id_length > 0) &&
(s->session->session_id_length <=
SSL2_MAX_SSL_SESSION_ID_LENGTH)) {
i = s->session->session_id_length;
s2n(i, p); /* session id length */
memcpy(d, s->session->session_id, (unsigned int)i);
d += i;
} else {
s2n(0, p);
}
s->s2->challenge_length = SSL2_CHALLENGE_LENGTH;
s2n(SSL2_CHALLENGE_LENGTH, p); /* challenge length */
/*
* challenge id data
*/
if (RAND_bytes(s->s2->challenge, SSL2_CHALLENGE_LENGTH) <= 0)
return -1;
memcpy(d, s->s2->challenge, SSL2_CHALLENGE_LENGTH);
d += SSL2_CHALLENGE_LENGTH;
s->state = SSL2_ST_SEND_CLIENT_HELLO_B;
s->init_num = d - buf;
s->init_off = 0;
}
/* SSL2_ST_SEND_CLIENT_HELLO_B */
return (ssl2_do_write(s));
}
static int client_master_key(SSL *s)
{
unsigned char *buf;
unsigned char *p, *d;
int clear, enc, karg, i;
SSL_SESSION *sess;
const EVP_CIPHER *c;
const EVP_MD *md;
buf = (unsigned char *)s->init_buf->data;
if (s->state == SSL2_ST_SEND_CLIENT_MASTER_KEY_A) {
if (!ssl_cipher_get_evp(s->session, &c, &md, NULL, NULL, NULL)) {
ssl2_return_error(s, SSL2_PE_NO_CIPHER);
SSLerr(SSL_F_CLIENT_MASTER_KEY,
SSL_R_PROBLEMS_MAPPING_CIPHER_FUNCTIONS);
return (-1);
}
sess = s->session;
p = buf;
d = p + 10;
*(p++) = SSL2_MT_CLIENT_MASTER_KEY; /* type */
i = ssl_put_cipher_by_char(s, sess->cipher, p);
p += i;
/* make key_arg data */
i = EVP_CIPHER_iv_length(c);
sess->key_arg_length = i;
if (i > SSL_MAX_KEY_ARG_LENGTH) {
ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR);
SSLerr(SSL_F_CLIENT_MASTER_KEY, ERR_R_INTERNAL_ERROR);
return -1;
}
if (i > 0)
if (RAND_bytes(sess->key_arg, i) <= 0)
return -1;
/* make a master key */
i = EVP_CIPHER_key_length(c);
sess->master_key_length = i;
if (i > 0) {
if (i > (int)sizeof(sess->master_key)) {
ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR);
SSLerr(SSL_F_CLIENT_MASTER_KEY, ERR_R_INTERNAL_ERROR);
return -1;
}
if (RAND_bytes(sess->master_key, i) <= 0) {
ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR);
return (-1);
}
}
if (sess->cipher->algorithm2 & SSL2_CF_8_BYTE_ENC)
enc = 8;
else if (SSL_C_IS_EXPORT(sess->cipher))
enc = 5;
else
enc = i;
if ((int)i < enc) {
ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR);
SSLerr(SSL_F_CLIENT_MASTER_KEY, SSL_R_CIPHER_TABLE_SRC_ERROR);
return (-1);
}
clear = i - enc;
s2n(clear, p);
memcpy(d, sess->master_key, (unsigned int)clear);
d += clear;
enc = ssl_rsa_public_encrypt(sess->sess_cert, enc,
&(sess->master_key[clear]), d,
(s->
s2->ssl2_rollback) ? RSA_SSLV23_PADDING
: RSA_PKCS1_PADDING);
if (enc <= 0) {
ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR);
SSLerr(SSL_F_CLIENT_MASTER_KEY, SSL_R_PUBLIC_KEY_ENCRYPT_ERROR);
return (-1);
}
# ifdef PKCS1_CHECK
if (s->options & SSL_OP_PKCS1_CHECK_1)
d[1]++;
if (s->options & SSL_OP_PKCS1_CHECK_2)
sess->master_key[clear]++;
# endif
s2n(enc, p);
d += enc;
karg = sess->key_arg_length;
s2n(karg, p); /* key arg size */
if (karg > (int)sizeof(sess->key_arg)) {
ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR);
SSLerr(SSL_F_CLIENT_MASTER_KEY, ERR_R_INTERNAL_ERROR);
return -1;
}
memcpy(d, sess->key_arg, (unsigned int)karg);
d += karg;
s->state = SSL2_ST_SEND_CLIENT_MASTER_KEY_B;
s->init_num = d - buf;
s->init_off = 0;
}
/* SSL2_ST_SEND_CLIENT_MASTER_KEY_B */
return (ssl2_do_write(s));
}
static int client_finished(SSL *s)
{
unsigned char *p;
if (s->state == SSL2_ST_SEND_CLIENT_FINISHED_A) {
p = (unsigned char *)s->init_buf->data;
*(p++) = SSL2_MT_CLIENT_FINISHED;
- if (s->s2->conn_id_length > sizeof s->s2->conn_id) {
+ if (s->s2->conn_id_length > sizeof(s->s2->conn_id)) {
SSLerr(SSL_F_CLIENT_FINISHED, ERR_R_INTERNAL_ERROR);
return -1;
}
memcpy(p, s->s2->conn_id, (unsigned int)s->s2->conn_id_length);
s->state = SSL2_ST_SEND_CLIENT_FINISHED_B;
s->init_num = s->s2->conn_id_length + 1;
s->init_off = 0;
}
return (ssl2_do_write(s));
}
/* read the data and then respond */
static int client_certificate(SSL *s)
{
unsigned char *buf;
unsigned char *p, *d;
int i;
unsigned int n;
int cert_ch_len;
unsigned char *cert_ch;
buf = (unsigned char *)s->init_buf->data;
/*
* We have a cert associated with the SSL, so attach it to the session if
* it does not have one
*/
if (s->state == SSL2_ST_SEND_CLIENT_CERTIFICATE_A) {
i = ssl2_read(s, (char *)&(buf[s->init_num]),
SSL2_MAX_CERT_CHALLENGE_LENGTH + 2 - s->init_num);
if (i < (SSL2_MIN_CERT_CHALLENGE_LENGTH + 2 - s->init_num))
return (ssl2_part_read(s, SSL_F_CLIENT_CERTIFICATE, i));
s->init_num += i;
if (s->msg_callback) {
/* REQUEST-CERTIFICATE */
s->msg_callback(0, s->version, 0, buf, (size_t)s->init_num, s,
s->msg_callback_arg);
}
/* type=buf[0]; */
/* type eq x509 */
if (buf[1] != SSL2_AT_MD5_WITH_RSA_ENCRYPTION) {
ssl2_return_error(s, SSL2_PE_UNSUPPORTED_CERTIFICATE_TYPE);
SSLerr(SSL_F_CLIENT_CERTIFICATE, SSL_R_BAD_AUTHENTICATION_TYPE);
return (-1);
}
if ((s->cert == NULL) ||
(s->cert->key->x509 == NULL) ||
(s->cert->key->privatekey == NULL)) {
s->state = SSL2_ST_X509_GET_CLIENT_CERTIFICATE;
} else
s->state = SSL2_ST_SEND_CLIENT_CERTIFICATE_C;
}
cert_ch = buf + 2;
cert_ch_len = s->init_num - 2;
if (s->state == SSL2_ST_X509_GET_CLIENT_CERTIFICATE) {
X509 *x509 = NULL;
EVP_PKEY *pkey = NULL;
/*
* If we get an error we need to ssl->rwstate=SSL_X509_LOOKUP;
* return(error); We should then be retried when things are ok and we
* can get a cert or not
*/
i = 0;
if (s->ctx->client_cert_cb != NULL) {
i = s->ctx->client_cert_cb(s, &(x509), &(pkey));
}
if (i < 0) {
s->rwstate = SSL_X509_LOOKUP;
return (-1);
}
s->rwstate = SSL_NOTHING;
if ((i == 1) && (pkey != NULL) && (x509 != NULL)) {
s->state = SSL2_ST_SEND_CLIENT_CERTIFICATE_C;
if (!SSL_use_certificate(s, x509) || !SSL_use_PrivateKey(s, pkey)) {
i = 0;
}
X509_free(x509);
EVP_PKEY_free(pkey);
} else if (i == 1) {
if (x509 != NULL)
X509_free(x509);
if (pkey != NULL)
EVP_PKEY_free(pkey);
SSLerr(SSL_F_CLIENT_CERTIFICATE,
SSL_R_BAD_DATA_RETURNED_BY_CALLBACK);
i = 0;
}
if (i == 0) {
/*
* We have no client certificate to respond with so send the
* correct error message back
*/
s->state = SSL2_ST_SEND_CLIENT_CERTIFICATE_B;
p = buf;
*(p++) = SSL2_MT_ERROR;
s2n(SSL2_PE_NO_CERTIFICATE, p);
s->init_off = 0;
s->init_num = 3;
/* Write is done at the end */
}
}
if (s->state == SSL2_ST_SEND_CLIENT_CERTIFICATE_B) {
return (ssl2_do_write(s));
}
if (s->state == SSL2_ST_SEND_CLIENT_CERTIFICATE_C) {
EVP_MD_CTX ctx;
/*
* ok, now we calculate the checksum do it first so we can reuse buf
* :-)
*/
p = buf;
EVP_MD_CTX_init(&ctx);
EVP_SignInit_ex(&ctx, s->ctx->rsa_md5, NULL);
EVP_SignUpdate(&ctx, s->s2->key_material, s->s2->key_material_length);
EVP_SignUpdate(&ctx, cert_ch, (unsigned int)cert_ch_len);
i = i2d_X509(s->session->sess_cert->peer_key->x509, &p);
/*
* Don't update the signature if it fails - FIXME: probably should
* handle this better
*/
if (i > 0)
EVP_SignUpdate(&ctx, buf, (unsigned int)i);
p = buf;
d = p + 6;
*(p++) = SSL2_MT_CLIENT_CERTIFICATE;
*(p++) = SSL2_CT_X509_CERTIFICATE;
n = i2d_X509(s->cert->key->x509, &d);
s2n(n, p);
if (!EVP_SignFinal(&ctx, d, &n, s->cert->key->privatekey)) {
/*
* this is not good. If things have failed it means there so
* something wrong with the key. We will continue with a 0 length
* signature
*/
}
EVP_MD_CTX_cleanup(&ctx);
s2n(n, p);
d += n;
s->state = SSL2_ST_SEND_CLIENT_CERTIFICATE_D;
s->init_num = d - buf;
s->init_off = 0;
}
/* if (s->state == SSL2_ST_SEND_CLIENT_CERTIFICATE_D) */
return (ssl2_do_write(s));
}
static int get_server_verify(SSL *s)
{
unsigned char *p;
int i, n, len;
p = (unsigned char *)s->init_buf->data;
if (s->state == SSL2_ST_GET_SERVER_VERIFY_A) {
i = ssl2_read(s, (char *)&(p[s->init_num]), 1 - s->init_num);
if (i < (1 - s->init_num))
return (ssl2_part_read(s, SSL_F_GET_SERVER_VERIFY, i));
s->init_num += i;
s->state = SSL2_ST_GET_SERVER_VERIFY_B;
if (*p != SSL2_MT_SERVER_VERIFY) {
if (p[0] != SSL2_MT_ERROR) {
ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR);
SSLerr(SSL_F_GET_SERVER_VERIFY, SSL_R_READ_WRONG_PACKET_TYPE);
} else {
SSLerr(SSL_F_GET_SERVER_VERIFY, SSL_R_PEER_ERROR);
/* try to read the error message */
i = ssl2_read(s, (char *)&(p[s->init_num]), 3 - s->init_num);
return ssl2_part_read(s, SSL_F_GET_SERVER_VERIFY, i);
}
return (-1);
}
}
p = (unsigned char *)s->init_buf->data;
len = 1 + s->s2->challenge_length;
n = len - s->init_num;
i = ssl2_read(s, (char *)&(p[s->init_num]), n);
if (i < n)
return (ssl2_part_read(s, SSL_F_GET_SERVER_VERIFY, i));
if (s->msg_callback) {
/* SERVER-VERIFY */
s->msg_callback(0, s->version, 0, p, len, s, s->msg_callback_arg);
}
p += 1;
if (CRYPTO_memcmp(p, s->s2->challenge, s->s2->challenge_length) != 0) {
ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR);
SSLerr(SSL_F_GET_SERVER_VERIFY, SSL_R_CHALLENGE_IS_DIFFERENT);
return (-1);
}
return (1);
}
static int get_server_finished(SSL *s)
{
unsigned char *buf;
unsigned char *p;
int i, n, len;
buf = (unsigned char *)s->init_buf->data;
p = buf;
if (s->state == SSL2_ST_GET_SERVER_FINISHED_A) {
i = ssl2_read(s, (char *)&(buf[s->init_num]), 1 - s->init_num);
if (i < (1 - s->init_num))
return (ssl2_part_read(s, SSL_F_GET_SERVER_FINISHED, i));
s->init_num += i;
if (*p == SSL2_MT_REQUEST_CERTIFICATE) {
s->state = SSL2_ST_SEND_CLIENT_CERTIFICATE_A;
return (1);
} else if (*p != SSL2_MT_SERVER_FINISHED) {
if (p[0] != SSL2_MT_ERROR) {
ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR);
SSLerr(SSL_F_GET_SERVER_FINISHED,
SSL_R_READ_WRONG_PACKET_TYPE);
} else {
SSLerr(SSL_F_GET_SERVER_FINISHED, SSL_R_PEER_ERROR);
/* try to read the error message */
i = ssl2_read(s, (char *)&(p[s->init_num]), 3 - s->init_num);
return ssl2_part_read(s, SSL_F_GET_SERVER_VERIFY, i);
}
return (-1);
}
s->state = SSL2_ST_GET_SERVER_FINISHED_B;
}
len = 1 + SSL2_SSL_SESSION_ID_LENGTH;
n = len - s->init_num;
i = ssl2_read(s, (char *)&(buf[s->init_num]), n);
if (i < n) {
/*
* XXX could be shorter than SSL2_SSL_SESSION_ID_LENGTH,
* that's the maximum
*/
return (ssl2_part_read(s, SSL_F_GET_SERVER_FINISHED, i));
}
s->init_num += i;
if (s->msg_callback) {
/* SERVER-FINISHED */
s->msg_callback(0, s->version, 0, buf, (size_t)s->init_num, s,
s->msg_callback_arg);
}
if (!s->hit) { /* new session */
/* new session-id */
/*
* Make sure we were not trying to re-use an old SSL_SESSION or bad
* things can happen
*/
/* ZZZZZZZZZZZZZ */
s->session->session_id_length = SSL2_SSL_SESSION_ID_LENGTH;
memcpy(s->session->session_id, p + 1, SSL2_SSL_SESSION_ID_LENGTH);
} else {
if (!(s->options & SSL_OP_MICROSOFT_SESS_ID_BUG)) {
if ((s->session->session_id_length >
- sizeof s->session->session_id)
+ sizeof(s->session->session_id))
|| (0 !=
memcmp(buf + 1, s->session->session_id,
(unsigned int)s->session->session_id_length))) {
ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR);
SSLerr(SSL_F_GET_SERVER_FINISHED,
SSL_R_SSL_SESSION_ID_IS_DIFFERENT);
return (-1);
}
}
}
s->state = SSL_ST_OK;
return (1);
}
/* loads in the certificate from the server */
int ssl2_set_certificate(SSL *s, int type, int len, const unsigned char *data)
{
STACK_OF(X509) *sk = NULL;
EVP_PKEY *pkey = NULL;
SESS_CERT *sc = NULL;
int i;
X509 *x509 = NULL;
int ret = 0;
x509 = d2i_X509(NULL, &data, (long)len);
if (x509 == NULL) {
SSLerr(SSL_F_SSL2_SET_CERTIFICATE, ERR_R_X509_LIB);
goto err;
}
if ((sk = sk_X509_new_null()) == NULL || !sk_X509_push(sk, x509)) {
SSLerr(SSL_F_SSL2_SET_CERTIFICATE, ERR_R_MALLOC_FAILURE);
goto err;
}
i = ssl_verify_cert_chain(s, sk);
if ((s->verify_mode != SSL_VERIFY_NONE) && (i <= 0)) {
SSLerr(SSL_F_SSL2_SET_CERTIFICATE, SSL_R_CERTIFICATE_VERIFY_FAILED);
goto err;
}
ERR_clear_error(); /* but we keep s->verify_result */
s->session->verify_result = s->verify_result;
/* server's cert for this session */
sc = ssl_sess_cert_new();
if (sc == NULL) {
ret = -1;
goto err;
}
if (s->session->sess_cert)
ssl_sess_cert_free(s->session->sess_cert);
s->session->sess_cert = sc;
sc->peer_pkeys[SSL_PKEY_RSA_ENC].x509 = x509;
sc->peer_key = &(sc->peer_pkeys[SSL_PKEY_RSA_ENC]);
pkey = X509_get_pubkey(x509);
x509 = NULL;
if (pkey == NULL) {
SSLerr(SSL_F_SSL2_SET_CERTIFICATE,
SSL_R_UNABLE_TO_EXTRACT_PUBLIC_KEY);
goto err;
}
if (pkey->type != EVP_PKEY_RSA) {
SSLerr(SSL_F_SSL2_SET_CERTIFICATE, SSL_R_PUBLIC_KEY_NOT_RSA);
goto err;
}
if (!ssl_set_peer_cert_type(sc, SSL2_CT_X509_CERTIFICATE))
goto err;
ret = 1;
err:
sk_X509_free(sk);
X509_free(x509);
EVP_PKEY_free(pkey);
return (ret);
}
static int ssl_rsa_public_encrypt(SESS_CERT *sc, int len, unsigned char *from,
unsigned char *to, int padding)
{
EVP_PKEY *pkey = NULL;
int i = -1;
if ((sc == NULL) || (sc->peer_key->x509 == NULL) ||
((pkey = X509_get_pubkey(sc->peer_key->x509)) == NULL)) {
SSLerr(SSL_F_SSL_RSA_PUBLIC_ENCRYPT, SSL_R_NO_PUBLICKEY);
return (-1);
}
if (pkey->type != EVP_PKEY_RSA) {
SSLerr(SSL_F_SSL_RSA_PUBLIC_ENCRYPT, SSL_R_PUBLIC_KEY_IS_NOT_RSA);
goto end;
}
/* we have the public key */
i = RSA_public_encrypt(len, from, to, pkey->pkey.rsa, padding);
if (i < 0)
SSLerr(SSL_F_SSL_RSA_PUBLIC_ENCRYPT, ERR_R_RSA_LIB);
end:
EVP_PKEY_free(pkey);
return (i);
}
#else /* !OPENSSL_NO_SSL2 */
# if PEDANTIC
static void *dummy = &dummy;
# endif
#endif
diff --git a/ssl/s2_enc.c b/ssl/s2_enc.c
index 23eef72aa43b..0115d2069ce2 100644
--- a/ssl/s2_enc.c
+++ b/ssl/s2_enc.c
@@ -1,197 +1,197 @@
/* ssl/s2_enc.c */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
#include "ssl_locl.h"
#ifndef OPENSSL_NO_SSL2
# include <stdio.h>
int ssl2_enc_init(SSL *s, int client)
{
/* Max number of bytes needed */
EVP_CIPHER_CTX *rs, *ws;
const EVP_CIPHER *c;
const EVP_MD *md;
int num;
if (!ssl_cipher_get_evp(s->session, &c, &md, NULL, NULL, NULL)) {
ssl2_return_error(s, SSL2_PE_NO_CIPHER);
SSLerr(SSL_F_SSL2_ENC_INIT, SSL_R_PROBLEMS_MAPPING_CIPHER_FUNCTIONS);
return (0);
}
ssl_replace_hash(&s->read_hash, md);
ssl_replace_hash(&s->write_hash, md);
if ((s->enc_read_ctx == NULL) && ((s->enc_read_ctx = (EVP_CIPHER_CTX *)
OPENSSL_malloc(sizeof(EVP_CIPHER_CTX)))
== NULL))
goto err;
/*
* make sure it's intialized in case the malloc for enc_write_ctx fails
* and we exit with an error
*/
rs = s->enc_read_ctx;
EVP_CIPHER_CTX_init(rs);
if ((s->enc_write_ctx == NULL) && ((s->enc_write_ctx = (EVP_CIPHER_CTX *)
OPENSSL_malloc(sizeof
(EVP_CIPHER_CTX))) ==
NULL))
goto err;
ws = s->enc_write_ctx;
EVP_CIPHER_CTX_init(ws);
num = c->key_len;
s->s2->key_material_length = num * 2;
- OPENSSL_assert(s->s2->key_material_length <= sizeof s->s2->key_material);
+ OPENSSL_assert(s->s2->key_material_length <= sizeof(s->s2->key_material));
if (ssl2_generate_key_material(s) <= 0)
return 0;
OPENSSL_assert(c->iv_len <= (int)sizeof(s->session->key_arg));
EVP_EncryptInit_ex(ws, c, NULL,
&(s->s2->key_material[(client) ? num : 0]),
s->session->key_arg);
EVP_DecryptInit_ex(rs, c, NULL,
&(s->s2->key_material[(client) ? 0 : num]),
s->session->key_arg);
s->s2->read_key = &(s->s2->key_material[(client) ? 0 : num]);
s->s2->write_key = &(s->s2->key_material[(client) ? num : 0]);
return (1);
err:
SSLerr(SSL_F_SSL2_ENC_INIT, ERR_R_MALLOC_FAILURE);
return (0);
}
/*
* read/writes from s->s2->mac_data using length for encrypt and decrypt.
* It sets s->s2->padding and s->[rw]length if we are encrypting Returns 0 on
* error and 1 on success
*/
int ssl2_enc(SSL *s, int send)
{
EVP_CIPHER_CTX *ds;
unsigned long l;
int bs;
if (send) {
ds = s->enc_write_ctx;
l = s->s2->wlength;
} else {
ds = s->enc_read_ctx;
l = s->s2->rlength;
}
/* check for NULL cipher */
if (ds == NULL)
return 1;
bs = ds->cipher->block_size;
/*
* This should be using (bs-1) and bs instead of 7 and 8, but what the
* hell.
*/
if (bs == 8)
l = (l + 7) / 8 * 8;
if (EVP_Cipher(ds, s->s2->mac_data, s->s2->mac_data, l) < 1)
return 0;
return 1;
}
void ssl2_mac(SSL *s, unsigned char *md, int send)
{
EVP_MD_CTX c;
unsigned char sequence[4], *p, *sec, *act;
unsigned long seq;
unsigned int len;
if (send) {
seq = s->s2->write_sequence;
sec = s->s2->write_key;
len = s->s2->wact_data_length;
act = s->s2->wact_data;
} else {
seq = s->s2->read_sequence;
sec = s->s2->read_key;
len = s->s2->ract_data_length;
act = s->s2->ract_data;
}
p = &(sequence[0]);
l2n(seq, p);
/* There has to be a MAC algorithm. */
EVP_MD_CTX_init(&c);
EVP_MD_CTX_copy(&c, s->read_hash);
EVP_DigestUpdate(&c, sec, EVP_CIPHER_CTX_key_length(s->enc_read_ctx));
EVP_DigestUpdate(&c, act, len);
/* the above line also does the pad data */
EVP_DigestUpdate(&c, sequence, 4);
EVP_DigestFinal_ex(&c, md, NULL);
EVP_MD_CTX_cleanup(&c);
}
#else /* !OPENSSL_NO_SSL2 */
# if PEDANTIC
static void *dummy = &dummy;
# endif
#endif
diff --git a/ssl/s2_lib.c b/ssl/s2_lib.c
index cc1360307b94..f03fe69f1e78 100644
--- a/ssl/s2_lib.c
+++ b/ssl/s2_lib.c
@@ -1,570 +1,570 @@
/* ssl/s2_lib.c */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
/* ====================================================================
* Copyright (c) 1998-2007 The OpenSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* openssl-core@openssl.org.
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.openssl.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*
* This product includes cryptographic software written by Eric Young
* (eay@cryptsoft.com). This product includes software written by Tim
* Hudson (tjh@cryptsoft.com).
*
*/
#include "ssl_locl.h"
#ifndef OPENSSL_NO_SSL2
# include <stdio.h>
# include <openssl/objects.h>
# include <openssl/evp.h>
# include <openssl/md5.h>
const char ssl2_version_str[] = "SSLv2" OPENSSL_VERSION_PTEXT;
# define SSL2_NUM_CIPHERS (sizeof(ssl2_ciphers)/sizeof(SSL_CIPHER))
/* list of available SSLv2 ciphers (sorted by id) */
OPENSSL_GLOBAL const SSL_CIPHER ssl2_ciphers[] = {
# if 0
/* NULL_WITH_MD5 v3 */
{
1,
SSL2_TXT_NULL_WITH_MD5,
SSL2_CK_NULL_WITH_MD5,
SSL_kRSA,
SSL_aRSA,
SSL_eNULL,
SSL_MD5,
SSL_SSLV2,
SSL_EXPORT | SSL_EXP40 | SSL_STRONG_NONE,
0,
0,
0,
},
# endif
/* RC4_128_WITH_MD5 */
{
1,
SSL2_TXT_RC4_128_WITH_MD5,
SSL2_CK_RC4_128_WITH_MD5,
SSL_kRSA,
SSL_aRSA,
SSL_RC4,
SSL_MD5,
SSL_SSLV2,
SSL_NOT_DEFAULT | SSL_NOT_EXP | SSL_MEDIUM,
0,
128,
128,
},
# if 0
/* RC4_128_EXPORT40_WITH_MD5 */
{
1,
SSL2_TXT_RC4_128_EXPORT40_WITH_MD5,
SSL2_CK_RC4_128_EXPORT40_WITH_MD5,
SSL_kRSA,
SSL_aRSA,
SSL_RC4,
SSL_MD5,
SSL_SSLV2,
SSL_NOT_DEFAULT | SSL_EXPORT | SSL_EXP40,
SSL2_CF_5_BYTE_ENC,
40,
128,
},
# endif
/* RC2_128_CBC_WITH_MD5 */
{
1,
SSL2_TXT_RC2_128_CBC_WITH_MD5,
SSL2_CK_RC2_128_CBC_WITH_MD5,
SSL_kRSA,
SSL_aRSA,
SSL_RC2,
SSL_MD5,
SSL_SSLV2,
SSL_NOT_DEFAULT | SSL_NOT_EXP | SSL_MEDIUM,
0,
128,
128,
},
# if 0
/* RC2_128_CBC_EXPORT40_WITH_MD5 */
{
1,
SSL2_TXT_RC2_128_CBC_EXPORT40_WITH_MD5,
SSL2_CK_RC2_128_CBC_EXPORT40_WITH_MD5,
SSL_kRSA,
SSL_aRSA,
SSL_RC2,
SSL_MD5,
SSL_SSLV2,
SSL_NOT_DEFAULT | SSL_EXPORT | SSL_EXP40,
SSL2_CF_5_BYTE_ENC,
40,
128,
},
# endif
# ifndef OPENSSL_NO_IDEA
/* IDEA_128_CBC_WITH_MD5 */
{
1,
SSL2_TXT_IDEA_128_CBC_WITH_MD5,
SSL2_CK_IDEA_128_CBC_WITH_MD5,
SSL_kRSA,
SSL_aRSA,
SSL_IDEA,
SSL_MD5,
SSL_SSLV2,
SSL_NOT_DEFAULT | SSL_NOT_EXP | SSL_MEDIUM,
0,
128,
128,
},
# endif
# if 0
/* DES_64_CBC_WITH_MD5 */
{
1,
SSL2_TXT_DES_64_CBC_WITH_MD5,
SSL2_CK_DES_64_CBC_WITH_MD5,
SSL_kRSA,
SSL_aRSA,
SSL_DES,
SSL_MD5,
SSL_SSLV2,
SSL_NOT_DEFAULT | SSL_NOT_EXP | SSL_LOW,
0,
56,
56,
},
# endif
/* DES_192_EDE3_CBC_WITH_MD5 */
{
1,
SSL2_TXT_DES_192_EDE3_CBC_WITH_MD5,
SSL2_CK_DES_192_EDE3_CBC_WITH_MD5,
SSL_kRSA,
SSL_aRSA,
SSL_3DES,
SSL_MD5,
SSL_SSLV2,
SSL_NOT_DEFAULT | SSL_NOT_EXP | SSL_MEDIUM,
0,
112,
168,
},
# if 0
/* RC4_64_WITH_MD5 */
{
1,
SSL2_TXT_RC4_64_WITH_MD5,
SSL2_CK_RC4_64_WITH_MD5,
SSL_kRSA,
SSL_aRSA,
SSL_RC4,
SSL_MD5,
SSL_SSLV2,
SSL_NOT_DEFAULT | SSL_NOT_EXP | SSL_LOW,
SSL2_CF_8_BYTE_ENC,
64,
64,
},
# endif
# if 0
/* NULL SSLeay (testing) */
{
0,
SSL2_TXT_NULL,
SSL2_CK_NULL,
0,
0,
0,
0,
SSL_SSLV2,
SSL_STRONG_NONE,
0,
0,
0,
},
# endif
/* end of list :-) */
};
long ssl2_default_timeout(void)
{
return (300);
}
int ssl2_num_ciphers(void)
{
return (SSL2_NUM_CIPHERS);
}
const SSL_CIPHER *ssl2_get_cipher(unsigned int u)
{
if (u < SSL2_NUM_CIPHERS)
return (&(ssl2_ciphers[SSL2_NUM_CIPHERS - 1 - u]));
else
return (NULL);
}
int ssl2_pending(const SSL *s)
{
return SSL_in_init(s) ? 0 : s->s2->ract_data_length;
}
int ssl2_new(SSL *s)
{
SSL2_STATE *s2;
- if ((s2 = OPENSSL_malloc(sizeof *s2)) == NULL)
+ if ((s2 = OPENSSL_malloc(sizeof(*s2))) == NULL)
goto err;
- memset(s2, 0, sizeof *s2);
+ memset(s2, 0, sizeof(*s2));
# if SSL2_MAX_RECORD_LENGTH_3_BYTE_HEADER + 3 > SSL2_MAX_RECORD_LENGTH_2_BYTE_HEADER + 2
# error "assertion failed"
# endif
if ((s2->rbuf =
OPENSSL_malloc(SSL2_MAX_RECORD_LENGTH_2_BYTE_HEADER + 2)) == NULL)
goto err;
/*
* wbuf needs one byte more because when using two-byte headers, we leave
* the first byte unused in do_ssl_write (s2_pkt.c)
*/
if ((s2->wbuf =
OPENSSL_malloc(SSL2_MAX_RECORD_LENGTH_2_BYTE_HEADER + 3)) == NULL)
goto err;
s->s2 = s2;
ssl2_clear(s);
return (1);
err:
if (s2 != NULL) {
if (s2->wbuf != NULL)
OPENSSL_free(s2->wbuf);
if (s2->rbuf != NULL)
OPENSSL_free(s2->rbuf);
OPENSSL_free(s2);
}
return (0);
}
void ssl2_free(SSL *s)
{
SSL2_STATE *s2;
if (s == NULL)
return;
s2 = s->s2;
if (s2->rbuf != NULL)
OPENSSL_free(s2->rbuf);
if (s2->wbuf != NULL)
OPENSSL_free(s2->wbuf);
- OPENSSL_cleanse(s2, sizeof *s2);
+ OPENSSL_cleanse(s2, sizeof(*s2));
OPENSSL_free(s2);
s->s2 = NULL;
}
void ssl2_clear(SSL *s)
{
SSL2_STATE *s2;
unsigned char *rbuf, *wbuf;
s2 = s->s2;
rbuf = s2->rbuf;
wbuf = s2->wbuf;
- memset(s2, 0, sizeof *s2);
+ memset(s2, 0, sizeof(*s2));
s2->rbuf = rbuf;
s2->wbuf = wbuf;
s2->clear_text = 1;
s->packet = s2->rbuf;
s->version = SSL2_VERSION;
s->packet_length = 0;
}
long ssl2_ctrl(SSL *s, int cmd, long larg, void *parg)
{
int ret = 0;
switch (cmd) {
case SSL_CTRL_GET_SESSION_REUSED:
ret = s->hit;
break;
case SSL_CTRL_CHECK_PROTO_VERSION:
return ssl3_ctrl(s, SSL_CTRL_CHECK_PROTO_VERSION, larg, parg);
default:
break;
}
return (ret);
}
long ssl2_callback_ctrl(SSL *s, int cmd, void (*fp) (void))
{
return (0);
}
long ssl2_ctx_ctrl(SSL_CTX *ctx, int cmd, long larg, void *parg)
{
return (0);
}
long ssl2_ctx_callback_ctrl(SSL_CTX *ctx, int cmd, void (*fp) (void))
{
return (0);
}
/*
* This function needs to check if the ciphers required are actually
* available
*/
const SSL_CIPHER *ssl2_get_cipher_by_char(const unsigned char *p)
{
SSL_CIPHER c;
const SSL_CIPHER *cp;
unsigned long id;
id = 0x02000000L | ((unsigned long)p[0] << 16L) |
((unsigned long)p[1] << 8L) | (unsigned long)p[2];
c.id = id;
cp = OBJ_bsearch_ssl_cipher_id(&c, ssl2_ciphers, SSL2_NUM_CIPHERS);
return cp;
}
int ssl2_put_cipher_by_char(const SSL_CIPHER *c, unsigned char *p)
{
long l;
if (p != NULL) {
l = c->id;
if ((l & 0xff000000) != 0x02000000 && l != SSL3_CK_FALLBACK_SCSV)
return (0);
p[0] = ((unsigned char)(l >> 16L)) & 0xFF;
p[1] = ((unsigned char)(l >> 8L)) & 0xFF;
p[2] = ((unsigned char)(l)) & 0xFF;
}
return (3);
}
int ssl2_generate_key_material(SSL *s)
{
unsigned int i;
EVP_MD_CTX ctx;
unsigned char *km;
unsigned char c = '0';
const EVP_MD *md5;
int md_size;
md5 = EVP_md5();
# ifdef CHARSET_EBCDIC
c = os_toascii['0']; /* Must be an ASCII '0', not EBCDIC '0', see
* SSLv2 docu */
# endif
EVP_MD_CTX_init(&ctx);
km = s->s2->key_material;
if (s->session->master_key_length < 0 ||
s->session->master_key_length > (int)sizeof(s->session->master_key)) {
SSLerr(SSL_F_SSL2_GENERATE_KEY_MATERIAL, ERR_R_INTERNAL_ERROR);
return 0;
}
md_size = EVP_MD_size(md5);
if (md_size < 0)
return 0;
for (i = 0; i < s->s2->key_material_length; i += md_size) {
if (((km - s->s2->key_material) + md_size) >
(int)sizeof(s->s2->key_material)) {
/*
* EVP_DigestFinal_ex() below would write beyond buffer
*/
SSLerr(SSL_F_SSL2_GENERATE_KEY_MATERIAL, ERR_R_INTERNAL_ERROR);
return 0;
}
EVP_DigestInit_ex(&ctx, md5, NULL);
OPENSSL_assert(s->session->master_key_length >= 0
&& s->session->master_key_length
<= (int)sizeof(s->session->master_key));
EVP_DigestUpdate(&ctx, s->session->master_key,
s->session->master_key_length);
EVP_DigestUpdate(&ctx, &c, 1);
c++;
EVP_DigestUpdate(&ctx, s->s2->challenge, s->s2->challenge_length);
EVP_DigestUpdate(&ctx, s->s2->conn_id, s->s2->conn_id_length);
EVP_DigestFinal_ex(&ctx, km, NULL);
km += md_size;
}
EVP_MD_CTX_cleanup(&ctx);
return 1;
}
void ssl2_return_error(SSL *s, int err)
{
if (!s->error) {
s->error = 3;
s->error_code = err;
ssl2_write_error(s);
}
}
void ssl2_write_error(SSL *s)
{
unsigned char buf[3];
int i, error;
buf[0] = SSL2_MT_ERROR;
buf[1] = (s->error_code >> 8) & 0xff;
buf[2] = (s->error_code) & 0xff;
/* state=s->rwstate;*/
error = s->error; /* number of bytes left to write */
s->error = 0;
OPENSSL_assert(error >= 0 && error <= (int)sizeof(buf));
i = ssl2_write(s, &(buf[3 - error]), error);
/* if (i == error) s->rwstate=state; */
if (i < 0)
s->error = error;
else {
s->error = error - i;
if (s->error == 0)
if (s->msg_callback) {
/* ERROR */
s->msg_callback(1, s->version, 0, buf, 3, s,
s->msg_callback_arg);
}
}
}
int ssl2_shutdown(SSL *s)
{
s->shutdown = (SSL_SENT_SHUTDOWN | SSL_RECEIVED_SHUTDOWN);
return (1);
}
#else /* !OPENSSL_NO_SSL2 */
# if PEDANTIC
static void *dummy = &dummy;
# endif
#endif
diff --git a/ssl/s2_srvr.c b/ssl/s2_srvr.c
index d3b243c27e02..c30161109c44 100644
--- a/ssl/s2_srvr.c
+++ b/ssl/s2_srvr.c
@@ -1,1167 +1,1167 @@
/* ssl/s2_srvr.c */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
/* ====================================================================
* Copyright (c) 1998-2001 The OpenSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* openssl-core@openssl.org.
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.openssl.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*
* This product includes cryptographic software written by Eric Young
* (eay@cryptsoft.com). This product includes software written by Tim
* Hudson (tjh@cryptsoft.com).
*
*/
#include "ssl_locl.h"
#ifndef OPENSSL_NO_SSL2
#include "../crypto/constant_time_locl.h"
# include <stdio.h>
# include <openssl/bio.h>
# include <openssl/rand.h>
# include <openssl/objects.h>
# include <openssl/evp.h>
static const SSL_METHOD *ssl2_get_server_method(int ver);
static int get_client_master_key(SSL *s);
static int get_client_hello(SSL *s);
static int server_hello(SSL *s);
static int get_client_finished(SSL *s);
static int server_verify(SSL *s);
static int server_finish(SSL *s);
static int request_certificate(SSL *s);
static int ssl_rsa_private_decrypt(CERT *c, int len, unsigned char *from,
unsigned char *to, int padding);
# define BREAK break
static const SSL_METHOD *ssl2_get_server_method(int ver)
{
if (ver == SSL2_VERSION)
return (SSLv2_server_method());
else
return (NULL);
}
IMPLEMENT_ssl2_meth_func(SSLv2_server_method,
ssl2_accept,
ssl_undefined_function, ssl2_get_server_method)
int ssl2_accept(SSL *s)
{
unsigned long l = (unsigned long)time(NULL);
BUF_MEM *buf = NULL;
int ret = -1;
long num1;
void (*cb) (const SSL *ssl, int type, int val) = NULL;
int new_state, state;
RAND_add(&l, sizeof(l), 0);
ERR_clear_error();
clear_sys_error();
if (s->info_callback != NULL)
cb = s->info_callback;
else if (s->ctx->info_callback != NULL)
cb = s->ctx->info_callback;
/* init things to blank */
s->in_handshake++;
if (!SSL_in_init(s) || SSL_in_before(s))
SSL_clear(s);
if (s->cert == NULL) {
SSLerr(SSL_F_SSL2_ACCEPT, SSL_R_NO_CERTIFICATE_SET);
return (-1);
}
clear_sys_error();
for (;;) {
state = s->state;
switch (s->state) {
case SSL_ST_BEFORE:
case SSL_ST_ACCEPT:
case SSL_ST_BEFORE | SSL_ST_ACCEPT:
case SSL_ST_OK | SSL_ST_ACCEPT:
s->server = 1;
if (cb != NULL)
cb(s, SSL_CB_HANDSHAKE_START, 1);
s->version = SSL2_VERSION;
s->type = SSL_ST_ACCEPT;
if (s->init_buf == NULL) {
if ((buf = BUF_MEM_new()) == NULL) {
ret = -1;
goto end;
}
if (!BUF_MEM_grow
(buf, (int)SSL2_MAX_RECORD_LENGTH_3_BYTE_HEADER)) {
BUF_MEM_free(buf);
ret = -1;
goto end;
}
s->init_buf = buf;
}
s->init_num = 0;
s->ctx->stats.sess_accept++;
s->handshake_func = ssl2_accept;
s->state = SSL2_ST_GET_CLIENT_HELLO_A;
BREAK;
case SSL2_ST_GET_CLIENT_HELLO_A:
case SSL2_ST_GET_CLIENT_HELLO_B:
case SSL2_ST_GET_CLIENT_HELLO_C:
s->shutdown = 0;
ret = get_client_hello(s);
if (ret <= 0)
goto end;
s->init_num = 0;
s->state = SSL2_ST_SEND_SERVER_HELLO_A;
BREAK;
case SSL2_ST_SEND_SERVER_HELLO_A:
case SSL2_ST_SEND_SERVER_HELLO_B:
ret = server_hello(s);
if (ret <= 0)
goto end;
s->init_num = 0;
if (!s->hit) {
s->state = SSL2_ST_GET_CLIENT_MASTER_KEY_A;
BREAK;
} else {
s->state = SSL2_ST_SERVER_START_ENCRYPTION;
BREAK;
}
case SSL2_ST_GET_CLIENT_MASTER_KEY_A:
case SSL2_ST_GET_CLIENT_MASTER_KEY_B:
ret = get_client_master_key(s);
if (ret <= 0)
goto end;
s->init_num = 0;
s->state = SSL2_ST_SERVER_START_ENCRYPTION;
BREAK;
case SSL2_ST_SERVER_START_ENCRYPTION:
/*
* Ok we how have sent all the stuff needed to start encrypting,
* the next packet back will be encrypted.
*/
if (!ssl2_enc_init(s, 0)) {
ret = -1;
goto end;
}
s->s2->clear_text = 0;
s->state = SSL2_ST_SEND_SERVER_VERIFY_A;
BREAK;
case SSL2_ST_SEND_SERVER_VERIFY_A:
case SSL2_ST_SEND_SERVER_VERIFY_B:
ret = server_verify(s);
if (ret <= 0)
goto end;
s->init_num = 0;
if (s->hit) {
/*
* If we are in here, we have been buffering the output, so
* we need to flush it and remove buffering from future
* traffic
*/
s->state = SSL2_ST_SEND_SERVER_VERIFY_C;
BREAK;
} else {
s->state = SSL2_ST_GET_CLIENT_FINISHED_A;
break;
}
case SSL2_ST_SEND_SERVER_VERIFY_C:
/* get the number of bytes to write */
num1 = BIO_ctrl(s->wbio, BIO_CTRL_INFO, 0, NULL);
if (num1 > 0) {
s->rwstate = SSL_WRITING;
num1 = BIO_flush(s->wbio);
if (num1 <= 0) {
ret = -1;
goto end;
}
s->rwstate = SSL_NOTHING;
}
/* flushed and now remove buffering */
s->wbio = BIO_pop(s->wbio);
s->state = SSL2_ST_GET_CLIENT_FINISHED_A;
BREAK;
case SSL2_ST_GET_CLIENT_FINISHED_A:
case SSL2_ST_GET_CLIENT_FINISHED_B:
ret = get_client_finished(s);
if (ret <= 0)
goto end;
s->init_num = 0;
s->state = SSL2_ST_SEND_REQUEST_CERTIFICATE_A;
BREAK;
case SSL2_ST_SEND_REQUEST_CERTIFICATE_A:
case SSL2_ST_SEND_REQUEST_CERTIFICATE_B:
case SSL2_ST_SEND_REQUEST_CERTIFICATE_C:
case SSL2_ST_SEND_REQUEST_CERTIFICATE_D:
/*
* don't do a 'request certificate' if we don't want to, or we
* already have one, and we only want to do it once.
*/
if (!(s->verify_mode & SSL_VERIFY_PEER) ||
((s->session->peer != NULL) &&
(s->verify_mode & SSL_VERIFY_CLIENT_ONCE))) {
s->state = SSL2_ST_SEND_SERVER_FINISHED_A;
break;
} else {
ret = request_certificate(s);
if (ret <= 0)
goto end;
s->init_num = 0;
s->state = SSL2_ST_SEND_SERVER_FINISHED_A;
}
BREAK;
case SSL2_ST_SEND_SERVER_FINISHED_A:
case SSL2_ST_SEND_SERVER_FINISHED_B:
ret = server_finish(s);
if (ret <= 0)
goto end;
s->init_num = 0;
s->state = SSL_ST_OK;
break;
case SSL_ST_OK:
BUF_MEM_free(s->init_buf);
ssl_free_wbio_buffer(s);
s->init_buf = NULL;
s->init_num = 0;
/* ERR_clear_error(); */
ssl_update_cache(s, SSL_SESS_CACHE_SERVER);
s->ctx->stats.sess_accept_good++;
/* s->server=1; */
ret = 1;
if (cb != NULL)
cb(s, SSL_CB_HANDSHAKE_DONE, 1);
goto end;
/* BREAK; */
default:
SSLerr(SSL_F_SSL2_ACCEPT, SSL_R_UNKNOWN_STATE);
ret = -1;
goto end;
/* BREAK; */
}
if ((cb != NULL) && (s->state != state)) {
new_state = s->state;
s->state = state;
cb(s, SSL_CB_ACCEPT_LOOP, 1);
s->state = new_state;
}
}
end:
s->in_handshake--;
if (cb != NULL)
cb(s, SSL_CB_ACCEPT_EXIT, ret);
return (ret);
}
static int get_client_master_key(SSL *s)
{
int is_export, i, n, keya;
unsigned int num_encrypted_key_bytes, key_length;
unsigned long len;
unsigned char *p;
const SSL_CIPHER *cp;
const EVP_CIPHER *c;
const EVP_MD *md;
unsigned char rand_premaster_secret[SSL_MAX_MASTER_KEY_LENGTH];
unsigned char decrypt_good;
size_t j;
p = (unsigned char *)s->init_buf->data;
if (s->state == SSL2_ST_GET_CLIENT_MASTER_KEY_A) {
i = ssl2_read(s, (char *)&(p[s->init_num]), 10 - s->init_num);
if (i < (10 - s->init_num))
return (ssl2_part_read(s, SSL_F_GET_CLIENT_MASTER_KEY, i));
s->init_num = 10;
if (*(p++) != SSL2_MT_CLIENT_MASTER_KEY) {
if (p[-1] != SSL2_MT_ERROR) {
ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR);
SSLerr(SSL_F_GET_CLIENT_MASTER_KEY,
SSL_R_READ_WRONG_PACKET_TYPE);
} else
SSLerr(SSL_F_GET_CLIENT_MASTER_KEY, SSL_R_PEER_ERROR);
return (-1);
}
cp = ssl2_get_cipher_by_char(p);
if (cp == NULL || sk_SSL_CIPHER_find(s->session->ciphers, cp) < 0) {
ssl2_return_error(s, SSL2_PE_NO_CIPHER);
SSLerr(SSL_F_GET_CLIENT_MASTER_KEY, SSL_R_NO_CIPHER_MATCH);
return (-1);
}
s->session->cipher = cp;
p += 3;
n2s(p, i);
s->s2->tmp.clear = i;
n2s(p, i);
s->s2->tmp.enc = i;
n2s(p, i);
if (i > SSL_MAX_KEY_ARG_LENGTH) {
ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR);
SSLerr(SSL_F_GET_CLIENT_MASTER_KEY, SSL_R_KEY_ARG_TOO_LONG);
return -1;
}
s->session->key_arg_length = i;
s->state = SSL2_ST_GET_CLIENT_MASTER_KEY_B;
}
/* SSL2_ST_GET_CLIENT_MASTER_KEY_B */
p = (unsigned char *)s->init_buf->data;
if (s->init_buf->length < SSL2_MAX_RECORD_LENGTH_3_BYTE_HEADER) {
ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR);
SSLerr(SSL_F_GET_CLIENT_MASTER_KEY, ERR_R_INTERNAL_ERROR);
return -1;
}
keya = s->session->key_arg_length;
len =
10 + (unsigned long)s->s2->tmp.clear + (unsigned long)s->s2->tmp.enc +
(unsigned long)keya;
if (len > SSL2_MAX_RECORD_LENGTH_3_BYTE_HEADER) {
ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR);
SSLerr(SSL_F_GET_CLIENT_MASTER_KEY, SSL_R_MESSAGE_TOO_LONG);
return -1;
}
n = (int)len - s->init_num;
i = ssl2_read(s, (char *)&(p[s->init_num]), n);
if (i != n)
return (ssl2_part_read(s, SSL_F_GET_CLIENT_MASTER_KEY, i));
if (s->msg_callback) {
/* CLIENT-MASTER-KEY */
s->msg_callback(0, s->version, 0, p, (size_t)len, s,
s->msg_callback_arg);
}
p += 10;
memcpy(s->session->key_arg, &(p[s->s2->tmp.clear + s->s2->tmp.enc]),
(unsigned int)keya);
if (s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey == NULL) {
ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR);
SSLerr(SSL_F_GET_CLIENT_MASTER_KEY, SSL_R_NO_PRIVATEKEY);
return (-1);
}
is_export = SSL_C_IS_EXPORT(s->session->cipher);
if (!ssl_cipher_get_evp(s->session, &c, &md, NULL, NULL, NULL)) {
ssl2_return_error(s, SSL2_PE_NO_CIPHER);
SSLerr(SSL_F_GET_CLIENT_MASTER_KEY,
SSL_R_PROBLEMS_MAPPING_CIPHER_FUNCTIONS);
return (0);
}
/*
* The format of the CLIENT-MASTER-KEY message is
* 1 byte message type
* 3 bytes cipher
* 2-byte clear key length (stored in s->s2->tmp.clear)
* 2-byte encrypted key length (stored in s->s2->tmp.enc)
* 2-byte key args length (IV etc)
* clear key
* encrypted key
* key args
*
* If the cipher is an export cipher, then the encrypted key bytes
* are a fixed portion of the total key (5 or 8 bytes). The size of
* this portion is in |num_encrypted_key_bytes|. If the cipher is not an
* export cipher, then the entire key material is encrypted (i.e., clear
* key length must be zero).
*/
key_length = (unsigned int)EVP_CIPHER_key_length(c);
if (key_length > SSL_MAX_MASTER_KEY_LENGTH) {
ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR);
SSLerr(SSL_F_GET_CLIENT_MASTER_KEY, ERR_R_INTERNAL_ERROR);
return -1;
}
if (s->session->cipher->algorithm2 & SSL2_CF_8_BYTE_ENC) {
is_export = 1;
num_encrypted_key_bytes = 8;
} else if (is_export) {
num_encrypted_key_bytes = 5;
} else {
num_encrypted_key_bytes = key_length;
}
if (s->s2->tmp.clear + num_encrypted_key_bytes != key_length) {
ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR);
SSLerr(SSL_F_GET_CLIENT_MASTER_KEY,SSL_R_BAD_LENGTH);
return -1;
}
/*
* The encrypted blob must decrypt to the encrypted portion of the key.
* Decryption can't be expanding, so if we don't have enough encrypted
* bytes to fit the key in the buffer, stop now.
*/
if (s->s2->tmp.enc < num_encrypted_key_bytes) {
ssl2_return_error(s,SSL2_PE_UNDEFINED_ERROR);
SSLerr(SSL_F_GET_CLIENT_MASTER_KEY,SSL_R_LENGTH_TOO_SHORT);
return -1;
}
/*
* We must not leak whether a decryption failure occurs because of
* Bleichenbacher's attack on PKCS #1 v1.5 RSA padding (see RFC 2246,
* section 7.4.7.1). The code follows that advice of the TLS RFC and
* generates a random premaster secret for the case that the decrypt
* fails. See https://tools.ietf.org/html/rfc5246#section-7.4.7.1
*/
if (RAND_bytes(rand_premaster_secret,
(int)num_encrypted_key_bytes) <= 0)
return 0;
i = ssl_rsa_private_decrypt(s->cert, s->s2->tmp.enc,
&(p[s->s2->tmp.clear]),
&(p[s->s2->tmp.clear]),
(s->s2->ssl2_rollback) ? RSA_SSLV23_PADDING :
RSA_PKCS1_PADDING);
ERR_clear_error();
/*
* If a bad decrypt, continue with protocol but with a random master
* secret (Bleichenbacher attack)
*/
decrypt_good = constant_time_eq_int_8(i, (int)num_encrypted_key_bytes);
for (j = 0; j < num_encrypted_key_bytes; j++) {
p[s->s2->tmp.clear + j] =
constant_time_select_8(decrypt_good, p[s->s2->tmp.clear + j],
rand_premaster_secret[j]);
}
s->session->master_key_length = (int)key_length;
memcpy(s->session->master_key, p, key_length);
OPENSSL_cleanse(p, key_length);
return 1;
}
static int get_client_hello(SSL *s)
{
int i, n;
unsigned long len;
unsigned char *p;
STACK_OF(SSL_CIPHER) *cs; /* a stack of SSL_CIPHERS */
STACK_OF(SSL_CIPHER) *cl; /* the ones we want to use */
STACK_OF(SSL_CIPHER) *prio, *allow;
int z;
/*
* This is a bit of a hack to check for the correct packet type the first
* time round.
*/
if (s->state == SSL2_ST_GET_CLIENT_HELLO_A) {
s->first_packet = 1;
s->state = SSL2_ST_GET_CLIENT_HELLO_B;
}
p = (unsigned char *)s->init_buf->data;
if (s->state == SSL2_ST_GET_CLIENT_HELLO_B) {
i = ssl2_read(s, (char *)&(p[s->init_num]), 9 - s->init_num);
if (i < (9 - s->init_num))
return (ssl2_part_read(s, SSL_F_GET_CLIENT_HELLO, i));
s->init_num = 9;
if (*(p++) != SSL2_MT_CLIENT_HELLO) {
if (p[-1] != SSL2_MT_ERROR) {
ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR);
SSLerr(SSL_F_GET_CLIENT_HELLO, SSL_R_READ_WRONG_PACKET_TYPE);
} else
SSLerr(SSL_F_GET_CLIENT_HELLO, SSL_R_PEER_ERROR);
return (-1);
}
n2s(p, i);
if (i < s->version)
s->version = i;
n2s(p, i);
s->s2->tmp.cipher_spec_length = i;
n2s(p, i);
s->s2->tmp.session_id_length = i;
if ((i < 0) || (i > SSL_MAX_SSL_SESSION_ID_LENGTH)) {
ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR);
SSLerr(SSL_F_GET_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH);
return -1;
}
n2s(p, i);
s->s2->challenge_length = i;
if ((i < SSL2_MIN_CHALLENGE_LENGTH) ||
(i > SSL2_MAX_CHALLENGE_LENGTH)) {
ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR);
SSLerr(SSL_F_GET_CLIENT_HELLO, SSL_R_INVALID_CHALLENGE_LENGTH);
return (-1);
}
s->state = SSL2_ST_GET_CLIENT_HELLO_C;
}
/* SSL2_ST_GET_CLIENT_HELLO_C */
p = (unsigned char *)s->init_buf->data;
len =
9 + (unsigned long)s->s2->tmp.cipher_spec_length +
(unsigned long)s->s2->challenge_length +
(unsigned long)s->s2->tmp.session_id_length;
if (len > SSL2_MAX_RECORD_LENGTH_3_BYTE_HEADER) {
ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR);
SSLerr(SSL_F_GET_CLIENT_HELLO, SSL_R_MESSAGE_TOO_LONG);
return -1;
}
n = (int)len - s->init_num;
i = ssl2_read(s, (char *)&(p[s->init_num]), n);
if (i != n)
return (ssl2_part_read(s, SSL_F_GET_CLIENT_HELLO, i));
if (s->msg_callback) {
/* CLIENT-HELLO */
s->msg_callback(0, s->version, 0, p, (size_t)len, s,
s->msg_callback_arg);
}
p += 9;
/*
* get session-id before cipher stuff so we can get out session structure
* if it is cached
*/
/* session-id */
if ((s->s2->tmp.session_id_length != 0) &&
(s->s2->tmp.session_id_length != SSL2_SSL_SESSION_ID_LENGTH)) {
ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR);
SSLerr(SSL_F_GET_CLIENT_HELLO, SSL_R_BAD_SSL_SESSION_ID_LENGTH);
return (-1);
}
if (s->s2->tmp.session_id_length == 0) {
if (!ssl_get_new_session(s, 1)) {
ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR);
return (-1);
}
} else {
i = ssl_get_prev_session(s, &(p[s->s2->tmp.cipher_spec_length]),
s->s2->tmp.session_id_length, NULL);
if (i == 1) { /* previous session */
s->hit = 1;
} else if (i == -1) {
ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR);
return (-1);
} else {
if (s->cert == NULL) {
ssl2_return_error(s, SSL2_PE_NO_CERTIFICATE);
SSLerr(SSL_F_GET_CLIENT_HELLO, SSL_R_NO_CERTIFICATE_SET);
return (-1);
}
if (!ssl_get_new_session(s, 1)) {
ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR);
return (-1);
}
}
}
if (!s->hit) {
cs = ssl_bytes_to_cipher_list(s, p, s->s2->tmp.cipher_spec_length,
&s->session->ciphers);
if (cs == NULL)
goto mem_err;
cl = SSL_get_ciphers(s);
if (s->options & SSL_OP_CIPHER_SERVER_PREFERENCE) {
prio = sk_SSL_CIPHER_dup(cl);
if (prio == NULL)
goto mem_err;
allow = cs;
} else {
prio = cs;
allow = cl;
}
/* Generate list of SSLv2 ciphers shared between client and server */
for (z = 0; z < sk_SSL_CIPHER_num(prio); z++) {
const SSL_CIPHER *cp = sk_SSL_CIPHER_value(prio, z);
if ((cp->algorithm_ssl & SSL_SSLV2) == 0 ||
sk_SSL_CIPHER_find(allow, cp) < 0) {
(void)sk_SSL_CIPHER_delete(prio, z);
z--;
}
}
if (s->options & SSL_OP_CIPHER_SERVER_PREFERENCE) {
sk_SSL_CIPHER_free(s->session->ciphers);
s->session->ciphers = prio;
}
/* Make sure we have at least one cipher in common */
if (sk_SSL_CIPHER_num(s->session->ciphers) == 0) {
ssl2_return_error(s, SSL2_PE_NO_CIPHER);
SSLerr(SSL_F_GET_CLIENT_HELLO, SSL_R_NO_CIPHER_MATCH);
return -1;
}
/*
* s->session->ciphers should now have a list of ciphers that are on
* both the client and server. This list is ordered by the order the
* client sent the ciphers or in the order of the server's preference
* if SSL_OP_CIPHER_SERVER_PREFERENCE was set.
*/
}
p += s->s2->tmp.cipher_spec_length;
/* done cipher selection */
/* session id extracted already */
p += s->s2->tmp.session_id_length;
/* challenge */
- if (s->s2->challenge_length > sizeof s->s2->challenge) {
+ if (s->s2->challenge_length > sizeof(s->s2->challenge)) {
ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR);
SSLerr(SSL_F_GET_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
return -1;
}
memcpy(s->s2->challenge, p, (unsigned int)s->s2->challenge_length);
return (1);
mem_err:
SSLerr(SSL_F_GET_CLIENT_HELLO, ERR_R_MALLOC_FAILURE);
return (0);
}
static int server_hello(SSL *s)
{
unsigned char *p, *d;
int n, hit;
p = (unsigned char *)s->init_buf->data;
if (s->state == SSL2_ST_SEND_SERVER_HELLO_A) {
d = p + 11;
*(p++) = SSL2_MT_SERVER_HELLO; /* type */
hit = s->hit;
*(p++) = (unsigned char)hit;
# if 1
if (!hit) {
if (s->session->sess_cert != NULL)
/*
* This can't really happen because get_client_hello has
* called ssl_get_new_session, which does not set sess_cert.
*/
ssl_sess_cert_free(s->session->sess_cert);
s->session->sess_cert = ssl_sess_cert_new();
if (s->session->sess_cert == NULL) {
SSLerr(SSL_F_SERVER_HELLO, ERR_R_MALLOC_FAILURE);
return (-1);
}
}
/*
* If 'hit' is set, then s->sess_cert may be non-NULL or NULL,
* depending on whether it survived in the internal cache or was
* retrieved from an external cache. If it is NULL, we cannot put any
* useful data in it anyway, so we don't touch it.
*/
# else /* That's what used to be done when cert_st
* and sess_cert_st were * the same. */
if (!hit) { /* else add cert to session */
CRYPTO_add(&s->cert->references, 1, CRYPTO_LOCK_SSL_CERT);
if (s->session->sess_cert != NULL)
ssl_cert_free(s->session->sess_cert);
s->session->sess_cert = s->cert;
} else { /* We have a session id-cache hit, if the *
* session-id has no certificate listed
* against * the 'cert' structure, grab the
* 'old' one * listed against the SSL
* connection */
if (s->session->sess_cert == NULL) {
CRYPTO_add(&s->cert->references, 1, CRYPTO_LOCK_SSL_CERT);
s->session->sess_cert = s->cert;
}
}
# endif
if (s->cert == NULL) {
ssl2_return_error(s, SSL2_PE_NO_CERTIFICATE);
SSLerr(SSL_F_SERVER_HELLO, SSL_R_NO_CERTIFICATE_SPECIFIED);
return (-1);
}
if (hit) {
*(p++) = 0; /* no certificate type */
s2n(s->version, p); /* version */
s2n(0, p); /* cert len */
s2n(0, p); /* ciphers len */
} else {
/* EAY EAY */
/* put certificate type */
*(p++) = SSL2_CT_X509_CERTIFICATE;
s2n(s->version, p); /* version */
n = i2d_X509(s->cert->pkeys[SSL_PKEY_RSA_ENC].x509, NULL);
s2n(n, p); /* certificate length */
i2d_X509(s->cert->pkeys[SSL_PKEY_RSA_ENC].x509, &d);
n = 0;
/*
* lets send out the ciphers we like in the prefered order
*/
n = ssl_cipher_list_to_bytes(s, s->session->ciphers, d, 0);
d += n;
s2n(n, p); /* add cipher length */
}
/* make and send conn_id */
s2n(SSL2_CONNECTION_ID_LENGTH, p); /* add conn_id length */
s->s2->conn_id_length = SSL2_CONNECTION_ID_LENGTH;
if (RAND_bytes(s->s2->conn_id, (int)s->s2->conn_id_length) <= 0)
return -1;
memcpy(d, s->s2->conn_id, SSL2_CONNECTION_ID_LENGTH);
d += SSL2_CONNECTION_ID_LENGTH;
s->state = SSL2_ST_SEND_SERVER_HELLO_B;
s->init_num = d - (unsigned char *)s->init_buf->data;
s->init_off = 0;
}
/* SSL2_ST_SEND_SERVER_HELLO_B */
/*
* If we are using TCP/IP, the performance is bad if we do 2 writes
* without a read between them. This occurs when Session-id reuse is
* used, so I will put in a buffering module
*/
if (s->hit) {
if (!ssl_init_wbio_buffer(s, 1))
return (-1);
}
return (ssl2_do_write(s));
}
static int get_client_finished(SSL *s)
{
unsigned char *p;
int i, n;
unsigned long len;
p = (unsigned char *)s->init_buf->data;
if (s->state == SSL2_ST_GET_CLIENT_FINISHED_A) {
i = ssl2_read(s, (char *)&(p[s->init_num]), 1 - s->init_num);
if (i < 1 - s->init_num)
return (ssl2_part_read(s, SSL_F_GET_CLIENT_FINISHED, i));
s->init_num += i;
if (*p != SSL2_MT_CLIENT_FINISHED) {
if (*p != SSL2_MT_ERROR) {
ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR);
SSLerr(SSL_F_GET_CLIENT_FINISHED,
SSL_R_READ_WRONG_PACKET_TYPE);
} else {
SSLerr(SSL_F_GET_CLIENT_FINISHED, SSL_R_PEER_ERROR);
/* try to read the error message */
i = ssl2_read(s, (char *)&(p[s->init_num]), 3 - s->init_num);
return ssl2_part_read(s, SSL_F_GET_SERVER_VERIFY, i);
}
return (-1);
}
s->state = SSL2_ST_GET_CLIENT_FINISHED_B;
}
/* SSL2_ST_GET_CLIENT_FINISHED_B */
- if (s->s2->conn_id_length > sizeof s->s2->conn_id) {
+ if (s->s2->conn_id_length > sizeof(s->s2->conn_id)) {
ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR);
SSLerr(SSL_F_GET_CLIENT_FINISHED, ERR_R_INTERNAL_ERROR);
return -1;
}
len = 1 + (unsigned long)s->s2->conn_id_length;
n = (int)len - s->init_num;
i = ssl2_read(s, (char *)&(p[s->init_num]), n);
if (i < n) {
return (ssl2_part_read(s, SSL_F_GET_CLIENT_FINISHED, i));
}
if (s->msg_callback) {
/* CLIENT-FINISHED */
s->msg_callback(0, s->version, 0, p, len, s, s->msg_callback_arg);
}
p += 1;
if (memcmp(p, s->s2->conn_id, s->s2->conn_id_length) != 0) {
ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR);
SSLerr(SSL_F_GET_CLIENT_FINISHED, SSL_R_CONNECTION_ID_IS_DIFFERENT);
return (-1);
}
return (1);
}
static int server_verify(SSL *s)
{
unsigned char *p;
if (s->state == SSL2_ST_SEND_SERVER_VERIFY_A) {
p = (unsigned char *)s->init_buf->data;
*(p++) = SSL2_MT_SERVER_VERIFY;
- if (s->s2->challenge_length > sizeof s->s2->challenge) {
+ if (s->s2->challenge_length > sizeof(s->s2->challenge)) {
SSLerr(SSL_F_SERVER_VERIFY, ERR_R_INTERNAL_ERROR);
return -1;
}
memcpy(p, s->s2->challenge, (unsigned int)s->s2->challenge_length);
/* p+=s->s2->challenge_length; */
s->state = SSL2_ST_SEND_SERVER_VERIFY_B;
s->init_num = s->s2->challenge_length + 1;
s->init_off = 0;
}
return (ssl2_do_write(s));
}
static int server_finish(SSL *s)
{
unsigned char *p;
if (s->state == SSL2_ST_SEND_SERVER_FINISHED_A) {
p = (unsigned char *)s->init_buf->data;
*(p++) = SSL2_MT_SERVER_FINISHED;
- if (s->session->session_id_length > sizeof s->session->session_id) {
+ if (s->session->session_id_length > sizeof(s->session->session_id)) {
SSLerr(SSL_F_SERVER_FINISH, ERR_R_INTERNAL_ERROR);
return -1;
}
memcpy(p, s->session->session_id,
(unsigned int)s->session->session_id_length);
/* p+=s->session->session_id_length; */
s->state = SSL2_ST_SEND_SERVER_FINISHED_B;
s->init_num = s->session->session_id_length + 1;
s->init_off = 0;
}
/* SSL2_ST_SEND_SERVER_FINISHED_B */
return (ssl2_do_write(s));
}
/* send the request and check the response */
static int request_certificate(SSL *s)
{
const unsigned char *cp;
unsigned char *p, *p2, *buf2;
unsigned char *ccd;
int i, j, ctype, ret = -1;
unsigned long len;
X509 *x509 = NULL;
STACK_OF(X509) *sk = NULL;
ccd = s->s2->tmp.ccl;
if (s->state == SSL2_ST_SEND_REQUEST_CERTIFICATE_A) {
p = (unsigned char *)s->init_buf->data;
*(p++) = SSL2_MT_REQUEST_CERTIFICATE;
*(p++) = SSL2_AT_MD5_WITH_RSA_ENCRYPTION;
if (RAND_bytes(ccd, SSL2_MIN_CERT_CHALLENGE_LENGTH) <= 0)
return -1;
memcpy(p, ccd, SSL2_MIN_CERT_CHALLENGE_LENGTH);
s->state = SSL2_ST_SEND_REQUEST_CERTIFICATE_B;
s->init_num = SSL2_MIN_CERT_CHALLENGE_LENGTH + 2;
s->init_off = 0;
}
if (s->state == SSL2_ST_SEND_REQUEST_CERTIFICATE_B) {
i = ssl2_do_write(s);
if (i <= 0) {
ret = i;
goto end;
}
s->init_num = 0;
s->state = SSL2_ST_SEND_REQUEST_CERTIFICATE_C;
}
if (s->state == SSL2_ST_SEND_REQUEST_CERTIFICATE_C) {
p = (unsigned char *)s->init_buf->data;
/* try to read 6 octets ... */
i = ssl2_read(s, (char *)&(p[s->init_num]), 6 - s->init_num);
/*
* ... but don't call ssl2_part_read now if we got at least 3
* (probably NO-CERTIFICATE-ERROR)
*/
if (i < 3 - s->init_num) {
ret = ssl2_part_read(s, SSL_F_REQUEST_CERTIFICATE, i);
goto end;
}
s->init_num += i;
if ((s->init_num >= 3) && (p[0] == SSL2_MT_ERROR)) {
n2s(p, i);
if (i != SSL2_PE_NO_CERTIFICATE) {
/*
* not the error message we expected -- let ssl2_part_read
* handle it
*/
s->init_num -= 3;
ret = ssl2_part_read(s, SSL_F_REQUEST_CERTIFICATE, 3);
goto end;
}
if (s->msg_callback) {
/* ERROR */
s->msg_callback(0, s->version, 0, p, 3, s,
s->msg_callback_arg);
}
/*
* this is the one place where we can recover from an SSL 2.0
* error
*/
if (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT) {
ssl2_return_error(s, SSL2_PE_BAD_CERTIFICATE);
SSLerr(SSL_F_REQUEST_CERTIFICATE,
SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
goto end;
}
ret = 1;
goto end;
}
if ((*(p++) != SSL2_MT_CLIENT_CERTIFICATE) || (s->init_num < 6)) {
ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR);
SSLerr(SSL_F_REQUEST_CERTIFICATE, SSL_R_SHORT_READ);
goto end;
}
if (s->init_num != 6) {
SSLerr(SSL_F_REQUEST_CERTIFICATE, ERR_R_INTERNAL_ERROR);
goto end;
}
/* ok we have a response */
/* certificate type, there is only one right now. */
ctype = *(p++);
if (ctype != SSL2_AT_MD5_WITH_RSA_ENCRYPTION) {
ssl2_return_error(s, SSL2_PE_UNSUPPORTED_CERTIFICATE_TYPE);
SSLerr(SSL_F_REQUEST_CERTIFICATE, SSL_R_BAD_RESPONSE_ARGUMENT);
goto end;
}
n2s(p, i);
s->s2->tmp.clen = i;
n2s(p, i);
s->s2->tmp.rlen = i;
s->state = SSL2_ST_SEND_REQUEST_CERTIFICATE_D;
}
/* SSL2_ST_SEND_REQUEST_CERTIFICATE_D */
p = (unsigned char *)s->init_buf->data;
len = 6 + (unsigned long)s->s2->tmp.clen + (unsigned long)s->s2->tmp.rlen;
if (len > SSL2_MAX_RECORD_LENGTH_3_BYTE_HEADER) {
SSLerr(SSL_F_REQUEST_CERTIFICATE, SSL_R_MESSAGE_TOO_LONG);
goto end;
}
j = (int)len - s->init_num;
i = ssl2_read(s, (char *)&(p[s->init_num]), j);
if (i < j) {
ret = ssl2_part_read(s, SSL_F_REQUEST_CERTIFICATE, i);
goto end;
}
if (s->msg_callback) {
/* CLIENT-CERTIFICATE */
s->msg_callback(0, s->version, 0, p, len, s, s->msg_callback_arg);
}
p += 6;
cp = p;
x509 = (X509 *)d2i_X509(NULL, &cp, (long)s->s2->tmp.clen);
if (x509 == NULL) {
SSLerr(SSL_F_REQUEST_CERTIFICATE, ERR_R_X509_LIB);
goto msg_end;
}
if (((sk = sk_X509_new_null()) == NULL) || (!sk_X509_push(sk, x509))) {
SSLerr(SSL_F_REQUEST_CERTIFICATE, ERR_R_MALLOC_FAILURE);
goto msg_end;
}
i = ssl_verify_cert_chain(s, sk);
if (i > 0) { /* we like the packet, now check the chksum */
EVP_MD_CTX ctx;
EVP_PKEY *pkey = NULL;
EVP_MD_CTX_init(&ctx);
if (!EVP_VerifyInit_ex(&ctx, s->ctx->rsa_md5, NULL)
|| !EVP_VerifyUpdate(&ctx, s->s2->key_material,
s->s2->key_material_length)
|| !EVP_VerifyUpdate(&ctx, ccd, SSL2_MIN_CERT_CHALLENGE_LENGTH))
goto msg_end;
i = i2d_X509(s->cert->pkeys[SSL_PKEY_RSA_ENC].x509, NULL);
buf2 = OPENSSL_malloc((unsigned int)i);
if (buf2 == NULL) {
SSLerr(SSL_F_REQUEST_CERTIFICATE, ERR_R_MALLOC_FAILURE);
goto msg_end;
}
p2 = buf2;
i = i2d_X509(s->cert->pkeys[SSL_PKEY_RSA_ENC].x509, &p2);
if (!EVP_VerifyUpdate(&ctx, buf2, (unsigned int)i)) {
OPENSSL_free(buf2);
goto msg_end;
}
OPENSSL_free(buf2);
pkey = X509_get_pubkey(x509);
if (pkey == NULL)
goto end;
i = EVP_VerifyFinal(&ctx, cp, s->s2->tmp.rlen, pkey);
EVP_PKEY_free(pkey);
EVP_MD_CTX_cleanup(&ctx);
if (i > 0) {
if (s->session->peer != NULL)
X509_free(s->session->peer);
s->session->peer = x509;
CRYPTO_add(&x509->references, 1, CRYPTO_LOCK_X509);
s->session->verify_result = s->verify_result;
ret = 1;
goto end;
} else {
SSLerr(SSL_F_REQUEST_CERTIFICATE, SSL_R_BAD_CHECKSUM);
goto msg_end;
}
} else {
msg_end:
ssl2_return_error(s, SSL2_PE_BAD_CERTIFICATE);
}
end:
sk_X509_free(sk);
X509_free(x509);
return (ret);
}
static int ssl_rsa_private_decrypt(CERT *c, int len, unsigned char *from,
unsigned char *to, int padding)
{
RSA *rsa;
int i;
if ((c == NULL) || (c->pkeys[SSL_PKEY_RSA_ENC].privatekey == NULL)) {
SSLerr(SSL_F_SSL_RSA_PRIVATE_DECRYPT, SSL_R_NO_PRIVATEKEY);
return (-1);
}
if (c->pkeys[SSL_PKEY_RSA_ENC].privatekey->type != EVP_PKEY_RSA) {
SSLerr(SSL_F_SSL_RSA_PRIVATE_DECRYPT, SSL_R_PUBLIC_KEY_IS_NOT_RSA);
return (-1);
}
rsa = c->pkeys[SSL_PKEY_RSA_ENC].privatekey->pkey.rsa;
/* we have the public key */
i = RSA_private_decrypt(len, from, to, rsa, padding);
if (i < 0)
SSLerr(SSL_F_SSL_RSA_PRIVATE_DECRYPT, ERR_R_RSA_LIB);
return (i);
}
#else /* !OPENSSL_NO_SSL2 */
# if PEDANTIC
static void *dummy = &dummy;
# endif
#endif
diff --git a/ssl/s3_clnt.c b/ssl/s3_clnt.c
index 5b8b2da59f54..bd0929d0e50e 100644
--- a/ssl/s3_clnt.c
+++ b/ssl/s3_clnt.c
@@ -1,3787 +1,3787 @@
/* ssl/s3_clnt.c */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
/* ====================================================================
* Copyright (c) 1998-2007 The OpenSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* openssl-core@openssl.org.
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.openssl.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*
* This product includes cryptographic software written by Eric Young
* (eay@cryptsoft.com). This product includes software written by Tim
* Hudson (tjh@cryptsoft.com).
*
*/
/* ====================================================================
* Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
*
* Portions of the attached software ("Contribution") are developed by
* SUN MICROSYSTEMS, INC., and are contributed to the OpenSSL project.
*
* The Contribution is licensed pursuant to the OpenSSL open source
* license provided above.
*
* ECC cipher suite support in OpenSSL originally written by
* Vipul Gupta and Sumit Gupta of Sun Microsystems Laboratories.
*
*/
/* ====================================================================
* Copyright 2005 Nokia. All rights reserved.
*
* The portions of the attached software ("Contribution") is developed by
* Nokia Corporation and is licensed pursuant to the OpenSSL open source
* license.
*
* The Contribution, originally written by Mika Kousa and Pasi Eronen of
* Nokia Corporation, consists of the "PSK" (Pre-Shared Key) ciphersuites
* support (see RFC 4279) to OpenSSL.
*
* No patent licenses or other rights except those expressly stated in
* the OpenSSL open source license shall be deemed granted or received
* expressly, by implication, estoppel, or otherwise.
*
* No assurances are provided by Nokia that the Contribution does not
* infringe the patent or other intellectual property rights of any third
* party or that the license provides you with all the necessary rights
* to make use of the Contribution.
*
* THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. IN
* ADDITION TO THE DISCLAIMERS INCLUDED IN THE LICENSE, NOKIA
* SPECIFICALLY DISCLAIMS ANY LIABILITY FOR CLAIMS BROUGHT BY YOU OR ANY
* OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS OR
* OTHERWISE.
*/
#include <stdio.h>
#include "ssl_locl.h"
#include "kssl_lcl.h"
#include <openssl/buffer.h>
#include <openssl/rand.h>
#include <openssl/objects.h>
#include <openssl/evp.h>
#include <openssl/md5.h>
#ifdef OPENSSL_FIPS
# include <openssl/fips.h>
#endif
#ifndef OPENSSL_NO_DH
# include <openssl/dh.h>
#endif
#include <openssl/bn.h>
#ifndef OPENSSL_NO_ENGINE
# include <openssl/engine.h>
#endif
static int ca_dn_cmp(const X509_NAME *const *a, const X509_NAME *const *b);
#ifndef OPENSSL_NO_TLSEXT
static int ssl3_check_finished(SSL *s);
#endif
#ifndef OPENSSL_NO_SSL3_METHOD
static const SSL_METHOD *ssl3_get_client_method(int ver)
{
if (ver == SSL3_VERSION)
return (SSLv3_client_method());
else
return (NULL);
}
IMPLEMENT_ssl3_meth_func(SSLv3_client_method,
ssl_undefined_function,
ssl3_connect, ssl3_get_client_method)
#endif
int ssl3_connect(SSL *s)
{
BUF_MEM *buf = NULL;
unsigned long Time = (unsigned long)time(NULL);
void (*cb) (const SSL *ssl, int type, int val) = NULL;
int ret = -1;
int new_state, state, skip = 0;
RAND_add(&Time, sizeof(Time), 0);
ERR_clear_error();
clear_sys_error();
if (s->info_callback != NULL)
cb = s->info_callback;
else if (s->ctx->info_callback != NULL)
cb = s->ctx->info_callback;
s->in_handshake++;
if (!SSL_in_init(s) || SSL_in_before(s))
SSL_clear(s);
#ifndef OPENSSL_NO_HEARTBEATS
/*
* If we're awaiting a HeartbeatResponse, pretend we already got and
* don't await it anymore, because Heartbeats don't make sense during
* handshakes anyway.
*/
if (s->tlsext_hb_pending) {
s->tlsext_hb_pending = 0;
s->tlsext_hb_seq++;
}
#endif
for (;;) {
state = s->state;
switch (s->state) {
case SSL_ST_RENEGOTIATE:
s->renegotiate = 1;
s->state = SSL_ST_CONNECT;
s->ctx->stats.sess_connect_renegotiate++;
/* break */
case SSL_ST_BEFORE:
case SSL_ST_CONNECT:
case SSL_ST_BEFORE | SSL_ST_CONNECT:
case SSL_ST_OK | SSL_ST_CONNECT:
s->server = 0;
if (cb != NULL)
cb(s, SSL_CB_HANDSHAKE_START, 1);
if ((s->version & 0xff00) != 0x0300) {
SSLerr(SSL_F_SSL3_CONNECT, ERR_R_INTERNAL_ERROR);
s->state = SSL_ST_ERR;
ret = -1;
goto end;
}
/* s->version=SSL3_VERSION; */
s->type = SSL_ST_CONNECT;
if (s->init_buf == NULL) {
if ((buf = BUF_MEM_new()) == NULL) {
ret = -1;
s->state = SSL_ST_ERR;
goto end;
}
if (!BUF_MEM_grow(buf, SSL3_RT_MAX_PLAIN_LENGTH)) {
ret = -1;
s->state = SSL_ST_ERR;
goto end;
}
s->init_buf = buf;
buf = NULL;
}
if (!ssl3_setup_buffers(s)) {
ret = -1;
s->state = SSL_ST_ERR;
goto end;
}
/* setup buffing BIO */
if (!ssl_init_wbio_buffer(s, 0)) {
ret = -1;
s->state = SSL_ST_ERR;
goto end;
}
/* don't push the buffering BIO quite yet */
if (!ssl3_init_finished_mac(s)) {
ret = -1;
s->state = SSL_ST_ERR;
goto end;
}
s->state = SSL3_ST_CW_CLNT_HELLO_A;
s->ctx->stats.sess_connect++;
s->init_num = 0;
s->s3->flags &= ~SSL3_FLAGS_CCS_OK;
/*
* Should have been reset by ssl3_get_finished, too.
*/
s->s3->change_cipher_spec = 0;
break;
case SSL3_ST_CW_CLNT_HELLO_A:
case SSL3_ST_CW_CLNT_HELLO_B:
s->shutdown = 0;
ret = ssl3_client_hello(s);
if (ret <= 0)
goto end;
s->state = SSL3_ST_CR_SRVR_HELLO_A;
s->init_num = 0;
/* turn on buffering for the next lot of output */
if (s->bbio != s->wbio)
s->wbio = BIO_push(s->bbio, s->wbio);
break;
case SSL3_ST_CR_SRVR_HELLO_A:
case SSL3_ST_CR_SRVR_HELLO_B:
ret = ssl3_get_server_hello(s);
if (ret <= 0)
goto end;
if (s->hit) {
s->state = SSL3_ST_CR_FINISHED_A;
#ifndef OPENSSL_NO_TLSEXT
if (s->tlsext_ticket_expected) {
/* receive renewed session ticket */
s->state = SSL3_ST_CR_SESSION_TICKET_A;
}
#endif
} else {
s->state = SSL3_ST_CR_CERT_A;
}
s->init_num = 0;
break;
case SSL3_ST_CR_CERT_A:
case SSL3_ST_CR_CERT_B:
#ifndef OPENSSL_NO_TLSEXT
/* Noop (ret = 0) for everything but EAP-FAST. */
ret = ssl3_check_finished(s);
if (ret < 0)
goto end;
if (ret == 1) {
s->hit = 1;
s->state = SSL3_ST_CR_FINISHED_A;
s->init_num = 0;
break;
}
#endif
/* Check if it is anon DH/ECDH, SRP auth */
/* or PSK */
if (!
(s->s3->tmp.
new_cipher->algorithm_auth & (SSL_aNULL | SSL_aSRP))
&& !(s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK)) {
ret = ssl3_get_server_certificate(s);
if (ret <= 0)
goto end;
#ifndef OPENSSL_NO_TLSEXT
if (s->tlsext_status_expected)
s->state = SSL3_ST_CR_CERT_STATUS_A;
else
s->state = SSL3_ST_CR_KEY_EXCH_A;
} else {
skip = 1;
s->state = SSL3_ST_CR_KEY_EXCH_A;
}
#else
} else
skip = 1;
s->state = SSL3_ST_CR_KEY_EXCH_A;
#endif
s->init_num = 0;
break;
case SSL3_ST_CR_KEY_EXCH_A:
case SSL3_ST_CR_KEY_EXCH_B:
ret = ssl3_get_key_exchange(s);
if (ret <= 0)
goto end;
s->state = SSL3_ST_CR_CERT_REQ_A;
s->init_num = 0;
/*
* at this point we check that we have the required stuff from
* the server
*/
if (!ssl3_check_cert_and_algorithm(s)) {
ret = -1;
s->state = SSL_ST_ERR;
goto end;
}
break;
case SSL3_ST_CR_CERT_REQ_A:
case SSL3_ST_CR_CERT_REQ_B:
ret = ssl3_get_certificate_request(s);
if (ret <= 0)
goto end;
s->state = SSL3_ST_CR_SRVR_DONE_A;
s->init_num = 0;
break;
case SSL3_ST_CR_SRVR_DONE_A:
case SSL3_ST_CR_SRVR_DONE_B:
ret = ssl3_get_server_done(s);
if (ret <= 0)
goto end;
#ifndef OPENSSL_NO_SRP
if (s->s3->tmp.new_cipher->algorithm_mkey & SSL_kSRP) {
if ((ret = SRP_Calc_A_param(s)) <= 0) {
SSLerr(SSL_F_SSL3_CONNECT, SSL_R_SRP_A_CALC);
ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
s->state = SSL_ST_ERR;
goto end;
}
}
#endif
if (s->s3->tmp.cert_req)
s->state = SSL3_ST_CW_CERT_A;
else
s->state = SSL3_ST_CW_KEY_EXCH_A;
s->init_num = 0;
break;
case SSL3_ST_CW_CERT_A:
case SSL3_ST_CW_CERT_B:
case SSL3_ST_CW_CERT_C:
case SSL3_ST_CW_CERT_D:
ret = ssl3_send_client_certificate(s);
if (ret <= 0)
goto end;
s->state = SSL3_ST_CW_KEY_EXCH_A;
s->init_num = 0;
break;
case SSL3_ST_CW_KEY_EXCH_A:
case SSL3_ST_CW_KEY_EXCH_B:
ret = ssl3_send_client_key_exchange(s);
if (ret <= 0)
goto end;
/*
* EAY EAY EAY need to check for DH fix cert sent back
*/
/*
* For TLS, cert_req is set to 2, so a cert chain of nothing is
* sent, but no verify packet is sent
*/
/*
* XXX: For now, we do not support client authentication in ECDH
* cipher suites with ECDH (rather than ECDSA) certificates. We
* need to skip the certificate verify message when client's
* ECDH public key is sent inside the client certificate.
*/
if (s->s3->tmp.cert_req == 1) {
s->state = SSL3_ST_CW_CERT_VRFY_A;
} else {
s->state = SSL3_ST_CW_CHANGE_A;
}
if (s->s3->flags & TLS1_FLAGS_SKIP_CERT_VERIFY) {
s->state = SSL3_ST_CW_CHANGE_A;
}
s->init_num = 0;
break;
case SSL3_ST_CW_CERT_VRFY_A:
case SSL3_ST_CW_CERT_VRFY_B:
ret = ssl3_send_client_verify(s);
if (ret <= 0)
goto end;
s->state = SSL3_ST_CW_CHANGE_A;
s->init_num = 0;
break;
case SSL3_ST_CW_CHANGE_A:
case SSL3_ST_CW_CHANGE_B:
ret = ssl3_send_change_cipher_spec(s,
SSL3_ST_CW_CHANGE_A,
SSL3_ST_CW_CHANGE_B);
if (ret <= 0)
goto end;
#if defined(OPENSSL_NO_TLSEXT) || defined(OPENSSL_NO_NEXTPROTONEG)
s->state = SSL3_ST_CW_FINISHED_A;
#else
if (s->s3->next_proto_neg_seen)
s->state = SSL3_ST_CW_NEXT_PROTO_A;
else
s->state = SSL3_ST_CW_FINISHED_A;
#endif
s->init_num = 0;
s->session->cipher = s->s3->tmp.new_cipher;
#ifdef OPENSSL_NO_COMP
s->session->compress_meth = 0;
#else
if (s->s3->tmp.new_compression == NULL)
s->session->compress_meth = 0;
else
s->session->compress_meth = s->s3->tmp.new_compression->id;
#endif
if (!s->method->ssl3_enc->setup_key_block(s)) {
ret = -1;
s->state = SSL_ST_ERR;
goto end;
}
if (!s->method->ssl3_enc->change_cipher_state(s,
SSL3_CHANGE_CIPHER_CLIENT_WRITE))
{
ret = -1;
s->state = SSL_ST_ERR;
goto end;
}
break;
#if !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_NEXTPROTONEG)
case SSL3_ST_CW_NEXT_PROTO_A:
case SSL3_ST_CW_NEXT_PROTO_B:
ret = ssl3_send_next_proto(s);
if (ret <= 0)
goto end;
s->state = SSL3_ST_CW_FINISHED_A;
break;
#endif
case SSL3_ST_CW_FINISHED_A:
case SSL3_ST_CW_FINISHED_B:
ret = ssl3_send_finished(s,
SSL3_ST_CW_FINISHED_A,
SSL3_ST_CW_FINISHED_B,
s->method->
ssl3_enc->client_finished_label,
s->method->
ssl3_enc->client_finished_label_len);
if (ret <= 0)
goto end;
s->state = SSL3_ST_CW_FLUSH;
/* clear flags */
s->s3->flags &= ~SSL3_FLAGS_POP_BUFFER;
if (s->hit) {
s->s3->tmp.next_state = SSL_ST_OK;
if (s->s3->flags & SSL3_FLAGS_DELAY_CLIENT_FINISHED) {
s->state = SSL_ST_OK;
s->s3->flags |= SSL3_FLAGS_POP_BUFFER;
s->s3->delay_buf_pop_ret = 0;
}
} else {
#ifndef OPENSSL_NO_TLSEXT
/*
* Allow NewSessionTicket if ticket expected
*/
if (s->tlsext_ticket_expected)
s->s3->tmp.next_state = SSL3_ST_CR_SESSION_TICKET_A;
else
#endif
s->s3->tmp.next_state = SSL3_ST_CR_FINISHED_A;
}
s->init_num = 0;
break;
#ifndef OPENSSL_NO_TLSEXT
case SSL3_ST_CR_SESSION_TICKET_A:
case SSL3_ST_CR_SESSION_TICKET_B:
ret = ssl3_get_new_session_ticket(s);
if (ret <= 0)
goto end;
s->state = SSL3_ST_CR_FINISHED_A;
s->init_num = 0;
break;
case SSL3_ST_CR_CERT_STATUS_A:
case SSL3_ST_CR_CERT_STATUS_B:
ret = ssl3_get_cert_status(s);
if (ret <= 0)
goto end;
s->state = SSL3_ST_CR_KEY_EXCH_A;
s->init_num = 0;
break;
#endif
case SSL3_ST_CR_FINISHED_A:
case SSL3_ST_CR_FINISHED_B:
if (!s->s3->change_cipher_spec)
s->s3->flags |= SSL3_FLAGS_CCS_OK;
ret = ssl3_get_finished(s, SSL3_ST_CR_FINISHED_A,
SSL3_ST_CR_FINISHED_B);
if (ret <= 0)
goto end;
if (s->hit)
s->state = SSL3_ST_CW_CHANGE_A;
else
s->state = SSL_ST_OK;
s->init_num = 0;
break;
case SSL3_ST_CW_FLUSH:
s->rwstate = SSL_WRITING;
if (BIO_flush(s->wbio) <= 0) {
ret = -1;
goto end;
}
s->rwstate = SSL_NOTHING;
s->state = s->s3->tmp.next_state;
break;
case SSL_ST_OK:
/* clean a few things up */
ssl3_cleanup_key_block(s);
if (s->init_buf != NULL) {
BUF_MEM_free(s->init_buf);
s->init_buf = NULL;
}
/*
* If we are not 'joining' the last two packets, remove the
* buffering now
*/
if (!(s->s3->flags & SSL3_FLAGS_POP_BUFFER))
ssl_free_wbio_buffer(s);
/* else do it later in ssl3_write */
s->init_num = 0;
s->renegotiate = 0;
s->new_session = 0;
ssl_update_cache(s, SSL_SESS_CACHE_CLIENT);
if (s->hit)
s->ctx->stats.sess_hit++;
ret = 1;
/* s->server=0; */
s->handshake_func = ssl3_connect;
s->ctx->stats.sess_connect_good++;
if (cb != NULL)
cb(s, SSL_CB_HANDSHAKE_DONE, 1);
goto end;
/* break; */
case SSL_ST_ERR:
default:
SSLerr(SSL_F_SSL3_CONNECT, SSL_R_UNKNOWN_STATE);
ret = -1;
goto end;
/* break; */
}
/* did we do anything */
if (!s->s3->tmp.reuse_message && !skip) {
if (s->debug) {
if ((ret = BIO_flush(s->wbio)) <= 0)
goto end;
}
if ((cb != NULL) && (s->state != state)) {
new_state = s->state;
s->state = state;
cb(s, SSL_CB_CONNECT_LOOP, 1);
s->state = new_state;
}
}
skip = 0;
}
end:
s->in_handshake--;
if (buf != NULL)
BUF_MEM_free(buf);
if (cb != NULL)
cb(s, SSL_CB_CONNECT_EXIT, ret);
return (ret);
}
int ssl3_client_hello(SSL *s)
{
unsigned char *buf;
unsigned char *p, *d;
int i;
unsigned long l;
int al = 0;
#ifndef OPENSSL_NO_COMP
int j;
SSL_COMP *comp;
#endif
buf = (unsigned char *)s->init_buf->data;
if (s->state == SSL3_ST_CW_CLNT_HELLO_A) {
SSL_SESSION *sess = s->session;
if ((sess == NULL) || (sess->ssl_version != s->version) ||
#ifdef OPENSSL_NO_TLSEXT
!sess->session_id_length ||
#else
/*
* In the case of EAP-FAST, we can have a pre-shared
* "ticket" without a session ID.
*/
(!sess->session_id_length && !sess->tlsext_tick) ||
#endif
(sess->not_resumable)) {
if (!ssl_get_new_session(s, 0))
goto err;
}
if (s->method->version == DTLS_ANY_VERSION) {
/* Determine which DTLS version to use */
int options = s->options;
/* If DTLS 1.2 disabled correct the version number */
if (options & SSL_OP_NO_DTLSv1_2) {
if (tls1_suiteb(s)) {
SSLerr(SSL_F_SSL3_CLIENT_HELLO,
SSL_R_ONLY_DTLS_1_2_ALLOWED_IN_SUITEB_MODE);
goto err;
}
/*
* Disabling all versions is silly: return an error.
*/
if (options & SSL_OP_NO_DTLSv1) {
SSLerr(SSL_F_SSL3_CLIENT_HELLO, SSL_R_WRONG_SSL_VERSION);
goto err;
}
/*
* Update method so we don't use any DTLS 1.2 features.
*/
s->method = DTLSv1_client_method();
s->version = DTLS1_VERSION;
} else {
/*
* We only support one version: update method
*/
if (options & SSL_OP_NO_DTLSv1)
s->method = DTLSv1_2_client_method();
s->version = DTLS1_2_VERSION;
}
s->client_version = s->version;
}
/* else use the pre-loaded session */
p = s->s3->client_random;
/*
* for DTLS if client_random is initialized, reuse it, we are
* required to use same upon reply to HelloVerify
*/
if (SSL_IS_DTLS(s)) {
size_t idx;
i = 1;
for (idx = 0; idx < sizeof(s->s3->client_random); idx++) {
if (p[idx]) {
i = 0;
break;
}
}
} else
i = 1;
if (i && ssl_fill_hello_random(s, 0, p,
sizeof(s->s3->client_random)) <= 0)
goto err;
/* Do the message type and length last */
d = p = ssl_handshake_start(s);
/*-
* version indicates the negotiated version: for example from
* an SSLv2/v3 compatible client hello). The client_version
* field is the maximum version we permit and it is also
* used in RSA encrypted premaster secrets. Some servers can
* choke if we initially report a higher version then
* renegotiate to a lower one in the premaster secret. This
* didn't happen with TLS 1.0 as most servers supported it
* but it can with TLS 1.1 or later if the server only supports
* 1.0.
*
* Possible scenario with previous logic:
* 1. Client hello indicates TLS 1.2
* 2. Server hello says TLS 1.0
* 3. RSA encrypted premaster secret uses 1.2.
* 4. Handhaked proceeds using TLS 1.0.
* 5. Server sends hello request to renegotiate.
* 6. Client hello indicates TLS v1.0 as we now
* know that is maximum server supports.
* 7. Server chokes on RSA encrypted premaster secret
* containing version 1.0.
*
* For interoperability it should be OK to always use the
* maximum version we support in client hello and then rely
* on the checking of version to ensure the servers isn't
* being inconsistent: for example initially negotiating with
* TLS 1.0 and renegotiating with TLS 1.2. We do this by using
* client_version in client hello and not resetting it to
* the negotiated version.
*/
#if 0
*(p++) = s->version >> 8;
*(p++) = s->version & 0xff;
s->client_version = s->version;
#else
*(p++) = s->client_version >> 8;
*(p++) = s->client_version & 0xff;
#endif
/* Random stuff */
memcpy(p, s->s3->client_random, SSL3_RANDOM_SIZE);
p += SSL3_RANDOM_SIZE;
/* Session ID */
if (s->new_session)
i = 0;
else
i = s->session->session_id_length;
*(p++) = i;
if (i != 0) {
if (i > (int)sizeof(s->session->session_id)) {
SSLerr(SSL_F_SSL3_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
goto err;
}
memcpy(p, s->session->session_id, i);
p += i;
}
/* cookie stuff for DTLS */
if (SSL_IS_DTLS(s)) {
if (s->d1->cookie_len > sizeof(s->d1->cookie)) {
SSLerr(SSL_F_SSL3_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
goto err;
}
*(p++) = s->d1->cookie_len;
memcpy(p, s->d1->cookie, s->d1->cookie_len);
p += s->d1->cookie_len;
}
/* Ciphers supported */
i = ssl_cipher_list_to_bytes(s, SSL_get_ciphers(s), &(p[2]), 0);
if (i == 0) {
SSLerr(SSL_F_SSL3_CLIENT_HELLO, SSL_R_NO_CIPHERS_AVAILABLE);
goto err;
}
#ifdef OPENSSL_MAX_TLS1_2_CIPHER_LENGTH
/*
* Some servers hang if client hello > 256 bytes as hack workaround
* chop number of supported ciphers to keep it well below this if we
* use TLS v1.2
*/
if (TLS1_get_version(s) >= TLS1_2_VERSION
&& i > OPENSSL_MAX_TLS1_2_CIPHER_LENGTH)
i = OPENSSL_MAX_TLS1_2_CIPHER_LENGTH & ~1;
#endif
s2n(i, p);
p += i;
/* COMPRESSION */
#ifdef OPENSSL_NO_COMP
*(p++) = 1;
#else
if ((s->options & SSL_OP_NO_COMPRESSION)
|| !s->ctx->comp_methods)
j = 0;
else
j = sk_SSL_COMP_num(s->ctx->comp_methods);
*(p++) = 1 + j;
for (i = 0; i < j; i++) {
comp = sk_SSL_COMP_value(s->ctx->comp_methods, i);
*(p++) = comp->id;
}
#endif
*(p++) = 0; /* Add the NULL method */
#ifndef OPENSSL_NO_TLSEXT
/* TLS extensions */
if (ssl_prepare_clienthello_tlsext(s) <= 0) {
SSLerr(SSL_F_SSL3_CLIENT_HELLO, SSL_R_CLIENTHELLO_TLSEXT);
goto err;
}
if ((p =
ssl_add_clienthello_tlsext(s, p, buf + SSL3_RT_MAX_PLAIN_LENGTH,
&al)) == NULL) {
ssl3_send_alert(s, SSL3_AL_FATAL, al);
SSLerr(SSL_F_SSL3_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
goto err;
}
#endif
l = p - d;
ssl_set_handshake_header(s, SSL3_MT_CLIENT_HELLO, l);
s->state = SSL3_ST_CW_CLNT_HELLO_B;
}
/* SSL3_ST_CW_CLNT_HELLO_B */
return ssl_do_write(s);
err:
s->state = SSL_ST_ERR;
return (-1);
}
int ssl3_get_server_hello(SSL *s)
{
STACK_OF(SSL_CIPHER) *sk;
const SSL_CIPHER *c;
CERT *ct = s->cert;
unsigned char *p, *d;
int i, al = SSL_AD_INTERNAL_ERROR, ok;
unsigned int j;
long n;
#ifndef OPENSSL_NO_COMP
SSL_COMP *comp;
#endif
/*
* Hello verify request and/or server hello version may not match so set
* first packet if we're negotiating version.
*/
if (SSL_IS_DTLS(s))
s->first_packet = 1;
n = s->method->ssl_get_message(s,
SSL3_ST_CR_SRVR_HELLO_A,
SSL3_ST_CR_SRVR_HELLO_B, -1, 20000, &ok);
if (!ok)
return ((int)n);
if (SSL_IS_DTLS(s)) {
s->first_packet = 0;
if (s->s3->tmp.message_type == DTLS1_MT_HELLO_VERIFY_REQUEST) {
if (s->d1->send_cookie == 0) {
s->s3->tmp.reuse_message = 1;
return 1;
} else { /* already sent a cookie */
al = SSL_AD_UNEXPECTED_MESSAGE;
SSLerr(SSL_F_SSL3_GET_SERVER_HELLO, SSL_R_BAD_MESSAGE_TYPE);
goto f_err;
}
}
}
if (s->s3->tmp.message_type != SSL3_MT_SERVER_HELLO) {
al = SSL_AD_UNEXPECTED_MESSAGE;
SSLerr(SSL_F_SSL3_GET_SERVER_HELLO, SSL_R_BAD_MESSAGE_TYPE);
goto f_err;
}
d = p = (unsigned char *)s->init_msg;
if (s->method->version == DTLS_ANY_VERSION) {
/* Work out correct protocol version to use */
int hversion = (p[0] << 8) | p[1];
int options = s->options;
if (hversion == DTLS1_2_VERSION && !(options & SSL_OP_NO_DTLSv1_2))
s->method = DTLSv1_2_client_method();
else if (tls1_suiteb(s)) {
SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,
SSL_R_ONLY_DTLS_1_2_ALLOWED_IN_SUITEB_MODE);
s->version = hversion;
al = SSL_AD_PROTOCOL_VERSION;
goto f_err;
} else if (hversion == DTLS1_VERSION && !(options & SSL_OP_NO_DTLSv1))
s->method = DTLSv1_client_method();
else {
SSLerr(SSL_F_SSL3_GET_SERVER_HELLO, SSL_R_WRONG_SSL_VERSION);
s->version = hversion;
al = SSL_AD_PROTOCOL_VERSION;
goto f_err;
}
s->session->ssl_version = s->version = s->method->version;
}
if ((p[0] != (s->version >> 8)) || (p[1] != (s->version & 0xff))) {
SSLerr(SSL_F_SSL3_GET_SERVER_HELLO, SSL_R_WRONG_SSL_VERSION);
s->version = (s->version & 0xff00) | p[1];
al = SSL_AD_PROTOCOL_VERSION;
goto f_err;
}
p += 2;
/* load the server hello data */
/* load the server random */
memcpy(s->s3->server_random, p, SSL3_RANDOM_SIZE);
p += SSL3_RANDOM_SIZE;
s->hit = 0;
/* get the session-id */
j = *(p++);
- if ((j > sizeof s->session->session_id) || (j > SSL3_SESSION_ID_SIZE)) {
+ if ((j > sizeof(s->session->session_id)) || (j > SSL3_SESSION_ID_SIZE)) {
al = SSL_AD_ILLEGAL_PARAMETER;
SSLerr(SSL_F_SSL3_GET_SERVER_HELLO, SSL_R_SSL3_SESSION_ID_TOO_LONG);
goto f_err;
}
#ifndef OPENSSL_NO_TLSEXT
/*
* Check if we can resume the session based on external pre-shared secret.
* EAP-FAST (RFC 4851) supports two types of session resumption.
* Resumption based on server-side state works with session IDs.
* Resumption based on pre-shared Protected Access Credentials (PACs)
* works by overriding the SessionTicket extension at the application
* layer, and does not send a session ID. (We do not know whether EAP-FAST
* servers would honour the session ID.) Therefore, the session ID alone
* is not a reliable indicator of session resumption, so we first check if
* we can resume, and later peek at the next handshake message to see if the
* server wants to resume.
*/
if (s->version >= TLS1_VERSION && s->tls_session_secret_cb &&
s->session->tlsext_tick) {
SSL_CIPHER *pref_cipher = NULL;
s->session->master_key_length = sizeof(s->session->master_key);
if (s->tls_session_secret_cb(s, s->session->master_key,
&s->session->master_key_length,
NULL, &pref_cipher,
s->tls_session_secret_cb_arg)) {
s->session->cipher = pref_cipher ?
pref_cipher : ssl_get_cipher_by_char(s, p + j);
} else {
SSLerr(SSL_F_SSL3_GET_SERVER_HELLO, ERR_R_INTERNAL_ERROR);
al = SSL_AD_INTERNAL_ERROR;
goto f_err;
}
}
#endif /* OPENSSL_NO_TLSEXT */
if (j != 0 && j == s->session->session_id_length
&& memcmp(p, s->session->session_id, j) == 0) {
if (s->sid_ctx_length != s->session->sid_ctx_length
|| memcmp(s->session->sid_ctx, s->sid_ctx, s->sid_ctx_length)) {
/* actually a client application bug */
al = SSL_AD_ILLEGAL_PARAMETER;
SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,
SSL_R_ATTEMPT_TO_REUSE_SESSION_IN_DIFFERENT_CONTEXT);
goto f_err;
}
s->hit = 1;
} else {
/*
* If we were trying for session-id reuse but the server
* didn't echo the ID, make a new SSL_SESSION.
* In the case of EAP-FAST and PAC, we do not send a session ID,
* so the PAC-based session secret is always preserved. It'll be
* overwritten if the server refuses resumption.
*/
if (s->session->session_id_length > 0) {
if (!ssl_get_new_session(s, 0)) {
goto f_err;
}
}
s->session->session_id_length = j;
memcpy(s->session->session_id, p, j); /* j could be 0 */
}
p += j;
c = ssl_get_cipher_by_char(s, p);
if (c == NULL) {
/* unknown cipher */
al = SSL_AD_ILLEGAL_PARAMETER;
SSLerr(SSL_F_SSL3_GET_SERVER_HELLO, SSL_R_UNKNOWN_CIPHER_RETURNED);
goto f_err;
}
/* Set version disabled mask now we know version */
if (!SSL_USE_TLS1_2_CIPHERS(s))
ct->mask_ssl = SSL_TLSV1_2;
else
ct->mask_ssl = 0;
/*
* If it is a disabled cipher we didn't send it in client hello, so
* return an error.
*/
if (c->algorithm_ssl & ct->mask_ssl ||
c->algorithm_mkey & ct->mask_k || c->algorithm_auth & ct->mask_a) {
al = SSL_AD_ILLEGAL_PARAMETER;
SSLerr(SSL_F_SSL3_GET_SERVER_HELLO, SSL_R_WRONG_CIPHER_RETURNED);
goto f_err;
}
p += ssl_put_cipher_by_char(s, NULL, NULL);
sk = ssl_get_ciphers_by_id(s);
i = sk_SSL_CIPHER_find(sk, c);
if (i < 0) {
/* we did not say we would use this cipher */
al = SSL_AD_ILLEGAL_PARAMETER;
SSLerr(SSL_F_SSL3_GET_SERVER_HELLO, SSL_R_WRONG_CIPHER_RETURNED);
goto f_err;
}
/*
* Depending on the session caching (internal/external), the cipher
* and/or cipher_id values may not be set. Make sure that cipher_id is
* set and use it for comparison.
*/
if (s->session->cipher)
s->session->cipher_id = s->session->cipher->id;
if (s->hit && (s->session->cipher_id != c->id)) {
/* Workaround is now obsolete */
#if 0
if (!(s->options & SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG))
#endif
{
al = SSL_AD_ILLEGAL_PARAMETER;
SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,
SSL_R_OLD_SESSION_CIPHER_NOT_RETURNED);
goto f_err;
}
}
s->s3->tmp.new_cipher = c;
/*
* Don't digest cached records if no sigalgs: we may need them for client
* authentication.
*/
if (!SSL_USE_SIGALGS(s) && !ssl3_digest_cached_records(s))
goto f_err;
/* lets get the compression algorithm */
/* COMPRESSION */
#ifdef OPENSSL_NO_COMP
if (*(p++) != 0) {
al = SSL_AD_ILLEGAL_PARAMETER;
SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,
SSL_R_UNSUPPORTED_COMPRESSION_ALGORITHM);
goto f_err;
}
/*
* If compression is disabled we'd better not try to resume a session
* using compression.
*/
if (s->session->compress_meth != 0) {
SSLerr(SSL_F_SSL3_GET_SERVER_HELLO, SSL_R_INCONSISTENT_COMPRESSION);
goto f_err;
}
#else
j = *(p++);
if (s->hit && j != s->session->compress_meth) {
al = SSL_AD_ILLEGAL_PARAMETER;
SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,
SSL_R_OLD_SESSION_COMPRESSION_ALGORITHM_NOT_RETURNED);
goto f_err;
}
if (j == 0)
comp = NULL;
else if (s->options & SSL_OP_NO_COMPRESSION) {
al = SSL_AD_ILLEGAL_PARAMETER;
SSLerr(SSL_F_SSL3_GET_SERVER_HELLO, SSL_R_COMPRESSION_DISABLED);
goto f_err;
} else
comp = ssl3_comp_find(s->ctx->comp_methods, j);
if ((j != 0) && (comp == NULL)) {
al = SSL_AD_ILLEGAL_PARAMETER;
SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,
SSL_R_UNSUPPORTED_COMPRESSION_ALGORITHM);
goto f_err;
} else {
s->s3->tmp.new_compression = comp;
}
#endif
#ifndef OPENSSL_NO_TLSEXT
/* TLS extensions */
if (!ssl_parse_serverhello_tlsext(s, &p, d, n)) {
SSLerr(SSL_F_SSL3_GET_SERVER_HELLO, SSL_R_PARSE_TLSEXT);
goto err;
}
#endif
if (p != (d + n)) {
/* wrong packet length */
al = SSL_AD_DECODE_ERROR;
SSLerr(SSL_F_SSL3_GET_SERVER_HELLO, SSL_R_BAD_PACKET_LENGTH);
goto f_err;
}
return (1);
f_err:
ssl3_send_alert(s, SSL3_AL_FATAL, al);
err:
s->state = SSL_ST_ERR;
return (-1);
}
int ssl3_get_server_certificate(SSL *s)
{
int al, i, ok, ret = -1;
unsigned long n, nc, llen, l;
X509 *x = NULL;
const unsigned char *q, *p;
unsigned char *d;
STACK_OF(X509) *sk = NULL;
SESS_CERT *sc;
EVP_PKEY *pkey = NULL;
int need_cert = 1; /* VRS: 0=> will allow null cert if auth ==
* KRB5 */
n = s->method->ssl_get_message(s,
SSL3_ST_CR_CERT_A,
SSL3_ST_CR_CERT_B,
-1, s->max_cert_list, &ok);
if (!ok)
return ((int)n);
if ((s->s3->tmp.message_type == SSL3_MT_SERVER_KEY_EXCHANGE) ||
((s->s3->tmp.new_cipher->algorithm_auth & SSL_aKRB5) &&
(s->s3->tmp.message_type == SSL3_MT_SERVER_DONE))) {
s->s3->tmp.reuse_message = 1;
return (1);
}
if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE) {
al = SSL_AD_UNEXPECTED_MESSAGE;
SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE, SSL_R_BAD_MESSAGE_TYPE);
goto f_err;
}
p = d = (unsigned char *)s->init_msg;
if ((sk = sk_X509_new_null()) == NULL) {
SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE, ERR_R_MALLOC_FAILURE);
goto err;
}
n2l3(p, llen);
if (llen + 3 != n) {
al = SSL_AD_DECODE_ERROR;
SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE, SSL_R_LENGTH_MISMATCH);
goto f_err;
}
for (nc = 0; nc < llen;) {
if (nc + 3 > llen) {
al = SSL_AD_DECODE_ERROR;
SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,
SSL_R_CERT_LENGTH_MISMATCH);
goto f_err;
}
n2l3(p, l);
if ((l + nc + 3) > llen) {
al = SSL_AD_DECODE_ERROR;
SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,
SSL_R_CERT_LENGTH_MISMATCH);
goto f_err;
}
q = p;
x = d2i_X509(NULL, &q, l);
if (x == NULL) {
al = SSL_AD_BAD_CERTIFICATE;
SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE, ERR_R_ASN1_LIB);
goto f_err;
}
if (q != (p + l)) {
al = SSL_AD_DECODE_ERROR;
SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,
SSL_R_CERT_LENGTH_MISMATCH);
goto f_err;
}
if (!sk_X509_push(sk, x)) {
SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE, ERR_R_MALLOC_FAILURE);
goto err;
}
x = NULL;
nc += l + 3;
p = q;
}
i = ssl_verify_cert_chain(s, sk);
if ((s->verify_mode != SSL_VERIFY_NONE) && (i <= 0)
#ifndef OPENSSL_NO_KRB5
&& !((s->s3->tmp.new_cipher->algorithm_mkey & SSL_kKRB5) &&
(s->s3->tmp.new_cipher->algorithm_auth & SSL_aKRB5))
#endif /* OPENSSL_NO_KRB5 */
) {
al = ssl_verify_alarm_type(s->verify_result);
SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,
SSL_R_CERTIFICATE_VERIFY_FAILED);
goto f_err;
}
ERR_clear_error(); /* but we keep s->verify_result */
sc = ssl_sess_cert_new();
if (sc == NULL)
goto err;
if (s->session->sess_cert)
ssl_sess_cert_free(s->session->sess_cert);
s->session->sess_cert = sc;
sc->cert_chain = sk;
/*
* Inconsistency alert: cert_chain does include the peer's certificate,
* which we don't include in s3_srvr.c
*/
x = sk_X509_value(sk, 0);
sk = NULL;
/*
* VRS 19990621: possible memory leak; sk=null ==> !sk_pop_free() @end
*/
pkey = X509_get_pubkey(x);
/* VRS: allow null cert if auth == KRB5 */
need_cert = ((s->s3->tmp.new_cipher->algorithm_mkey & SSL_kKRB5) &&
(s->s3->tmp.new_cipher->algorithm_auth & SSL_aKRB5))
? 0 : 1;
#ifdef KSSL_DEBUG
fprintf(stderr, "pkey,x = %p, %p\n", pkey, x);
fprintf(stderr, "ssl_cert_type(x,pkey) = %d\n", ssl_cert_type(x, pkey));
fprintf(stderr, "cipher, alg, nc = %s, %lx, %lx, %d\n",
s->s3->tmp.new_cipher->name,
s->s3->tmp.new_cipher->algorithm_mkey,
s->s3->tmp.new_cipher->algorithm_auth, need_cert);
#endif /* KSSL_DEBUG */
if (need_cert && ((pkey == NULL) || EVP_PKEY_missing_parameters(pkey))) {
x = NULL;
al = SSL3_AL_FATAL;
SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,
SSL_R_UNABLE_TO_FIND_PUBLIC_KEY_PARAMETERS);
goto f_err;
}
i = ssl_cert_type(x, pkey);
if (need_cert && i < 0) {
x = NULL;
al = SSL3_AL_FATAL;
SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,
SSL_R_UNKNOWN_CERTIFICATE_TYPE);
goto f_err;
}
if (need_cert) {
int exp_idx = ssl_cipher_get_cert_index(s->s3->tmp.new_cipher);
if (exp_idx >= 0 && i != exp_idx) {
x = NULL;
al = SSL_AD_ILLEGAL_PARAMETER;
SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,
SSL_R_WRONG_CERTIFICATE_TYPE);
goto f_err;
}
sc->peer_cert_type = i;
CRYPTO_add(&x->references, 1, CRYPTO_LOCK_X509);
/*
* Why would the following ever happen? We just created sc a couple
* of lines ago.
*/
if (sc->peer_pkeys[i].x509 != NULL)
X509_free(sc->peer_pkeys[i].x509);
sc->peer_pkeys[i].x509 = x;
sc->peer_key = &(sc->peer_pkeys[i]);
if (s->session->peer != NULL)
X509_free(s->session->peer);
CRYPTO_add(&x->references, 1, CRYPTO_LOCK_X509);
s->session->peer = x;
} else {
sc->peer_cert_type = i;
sc->peer_key = NULL;
if (s->session->peer != NULL)
X509_free(s->session->peer);
s->session->peer = NULL;
}
s->session->verify_result = s->verify_result;
x = NULL;
ret = 1;
if (0) {
f_err:
ssl3_send_alert(s, SSL3_AL_FATAL, al);
err:
s->state = SSL_ST_ERR;
}
EVP_PKEY_free(pkey);
X509_free(x);
sk_X509_pop_free(sk, X509_free);
return (ret);
}
int ssl3_get_key_exchange(SSL *s)
{
#ifndef OPENSSL_NO_RSA
unsigned char *q, md_buf[EVP_MAX_MD_SIZE * 2];
#endif
EVP_MD_CTX md_ctx;
unsigned char *param, *p;
int al, j, ok;
long i, param_len, n, alg_k, alg_a;
EVP_PKEY *pkey = NULL;
const EVP_MD *md = NULL;
#ifndef OPENSSL_NO_RSA
RSA *rsa = NULL;
#endif
#ifndef OPENSSL_NO_DH
DH *dh = NULL;
#endif
#ifndef OPENSSL_NO_ECDH
EC_KEY *ecdh = NULL;
BN_CTX *bn_ctx = NULL;
EC_POINT *srvr_ecpoint = NULL;
int curve_nid = 0;
int encoded_pt_len = 0;
#endif
EVP_MD_CTX_init(&md_ctx);
/*
* use same message size as in ssl3_get_certificate_request() as
* ServerKeyExchange message may be skipped
*/
n = s->method->ssl_get_message(s,
SSL3_ST_CR_KEY_EXCH_A,
SSL3_ST_CR_KEY_EXCH_B,
-1, s->max_cert_list, &ok);
if (!ok)
return ((int)n);
alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
if (s->s3->tmp.message_type != SSL3_MT_SERVER_KEY_EXCHANGE) {
/*
* Can't skip server key exchange if this is an ephemeral
* ciphersuite.
*/
if (alg_k & (SSL_kDHE | SSL_kECDHE)) {
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_UNEXPECTED_MESSAGE);
al = SSL_AD_UNEXPECTED_MESSAGE;
goto f_err;
}
#ifndef OPENSSL_NO_PSK
/*
* In plain PSK ciphersuite, ServerKeyExchange can be omitted if no
* identity hint is sent. Set session->sess_cert anyway to avoid
* problems later.
*/
if (alg_k & SSL_kPSK) {
s->session->sess_cert = ssl_sess_cert_new();
if (s->ctx->psk_identity_hint)
OPENSSL_free(s->ctx->psk_identity_hint);
s->ctx->psk_identity_hint = NULL;
}
#endif
s->s3->tmp.reuse_message = 1;
return (1);
}
param = p = (unsigned char *)s->init_msg;
if (s->session->sess_cert != NULL) {
#ifndef OPENSSL_NO_RSA
if (s->session->sess_cert->peer_rsa_tmp != NULL) {
RSA_free(s->session->sess_cert->peer_rsa_tmp);
s->session->sess_cert->peer_rsa_tmp = NULL;
}
#endif
#ifndef OPENSSL_NO_DH
if (s->session->sess_cert->peer_dh_tmp) {
DH_free(s->session->sess_cert->peer_dh_tmp);
s->session->sess_cert->peer_dh_tmp = NULL;
}
#endif
#ifndef OPENSSL_NO_ECDH
if (s->session->sess_cert->peer_ecdh_tmp) {
EC_KEY_free(s->session->sess_cert->peer_ecdh_tmp);
s->session->sess_cert->peer_ecdh_tmp = NULL;
}
#endif
} else {
s->session->sess_cert = ssl_sess_cert_new();
}
/* Total length of the parameters including the length prefix */
param_len = 0;
alg_a = s->s3->tmp.new_cipher->algorithm_auth;
al = SSL_AD_DECODE_ERROR;
#ifndef OPENSSL_NO_PSK
if (alg_k & SSL_kPSK) {
param_len = 2;
if (param_len > n) {
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT);
goto f_err;
}
n2s(p, i);
/*
* Store PSK identity hint for later use, hint is used in
* ssl3_send_client_key_exchange. Assume that the maximum length of
* a PSK identity hint can be as long as the maximum length of a PSK
* identity.
*/
if (i > PSK_MAX_IDENTITY_LEN) {
al = SSL_AD_HANDSHAKE_FAILURE;
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_DATA_LENGTH_TOO_LONG);
goto f_err;
}
if (i > n - param_len) {
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,
SSL_R_BAD_PSK_IDENTITY_HINT_LENGTH);
goto f_err;
}
param_len += i;
s->session->psk_identity_hint = BUF_strndup((char *)p, i);
if (s->session->psk_identity_hint == NULL) {
al = SSL_AD_HANDSHAKE_FAILURE;
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
goto f_err;
}
p += i;
n -= param_len;
} else
#endif /* !OPENSSL_NO_PSK */
#ifndef OPENSSL_NO_SRP
if (alg_k & SSL_kSRP) {
param_len = 2;
if (param_len > n) {
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT);
goto f_err;
}
n2s(p, i);
if (i > n - param_len) {
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_BAD_SRP_N_LENGTH);
goto f_err;
}
param_len += i;
if (!(s->srp_ctx.N = BN_bin2bn(p, i, NULL))) {
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_BN_LIB);
goto err;
}
p += i;
if (2 > n - param_len) {
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT);
goto f_err;
}
param_len += 2;
n2s(p, i);
if (i > n - param_len) {
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_BAD_SRP_G_LENGTH);
goto f_err;
}
param_len += i;
if (!(s->srp_ctx.g = BN_bin2bn(p, i, NULL))) {
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_BN_LIB);
goto err;
}
p += i;
if (1 > n - param_len) {
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT);
goto f_err;
}
param_len += 1;
i = (unsigned int)(p[0]);
p++;
if (i > n - param_len) {
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_BAD_SRP_S_LENGTH);
goto f_err;
}
param_len += i;
if (!(s->srp_ctx.s = BN_bin2bn(p, i, NULL))) {
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_BN_LIB);
goto err;
}
p += i;
if (2 > n - param_len) {
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT);
goto f_err;
}
param_len += 2;
n2s(p, i);
if (i > n - param_len) {
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_BAD_SRP_B_LENGTH);
goto f_err;
}
param_len += i;
if (!(s->srp_ctx.B = BN_bin2bn(p, i, NULL))) {
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_BN_LIB);
goto err;
}
p += i;
n -= param_len;
if (!srp_verify_server_param(s, &al)) {
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_BAD_SRP_PARAMETERS);
goto f_err;
}
/* We must check if there is a certificate */
# ifndef OPENSSL_NO_RSA
if (alg_a & SSL_aRSA)
pkey =
X509_get_pubkey(s->session->
sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509);
# else
if (0) ;
# endif
# ifndef OPENSSL_NO_DSA
else if (alg_a & SSL_aDSS)
pkey =
X509_get_pubkey(s->session->
sess_cert->peer_pkeys[SSL_PKEY_DSA_SIGN].
x509);
# endif
} else
#endif /* !OPENSSL_NO_SRP */
#ifndef OPENSSL_NO_RSA
if (alg_k & SSL_kRSA) {
/* Temporary RSA keys only allowed in export ciphersuites */
if (!SSL_C_IS_EXPORT(s->s3->tmp.new_cipher)) {
al = SSL_AD_UNEXPECTED_MESSAGE;
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_UNEXPECTED_MESSAGE);
goto f_err;
}
if ((rsa = RSA_new()) == NULL) {
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
goto err;
}
param_len = 2;
if (param_len > n) {
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT);
goto f_err;
}
n2s(p, i);
if (i > n - param_len) {
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_BAD_RSA_MODULUS_LENGTH);
goto f_err;
}
param_len += i;
if (!(rsa->n = BN_bin2bn(p, i, rsa->n))) {
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_BN_LIB);
goto err;
}
p += i;
if (2 > n - param_len) {
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT);
goto f_err;
}
param_len += 2;
n2s(p, i);
if (i > n - param_len) {
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_BAD_RSA_E_LENGTH);
goto f_err;
}
param_len += i;
if (!(rsa->e = BN_bin2bn(p, i, rsa->e))) {
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_BN_LIB);
goto err;
}
p += i;
n -= param_len;
/* this should be because we are using an export cipher */
if (alg_a & SSL_aRSA)
pkey =
X509_get_pubkey(s->session->
sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509);
else {
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
goto err;
}
if (EVP_PKEY_bits(pkey) <= SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher)) {
al = SSL_AD_UNEXPECTED_MESSAGE;
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_UNEXPECTED_MESSAGE);
goto f_err;
}
s->session->sess_cert->peer_rsa_tmp = rsa;
rsa = NULL;
}
#else /* OPENSSL_NO_RSA */
if (0) ;
#endif
#ifndef OPENSSL_NO_DH
else if (alg_k & SSL_kEDH) {
if ((dh = DH_new()) == NULL) {
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_DH_LIB);
goto err;
}
param_len = 2;
if (param_len > n) {
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT);
goto f_err;
}
n2s(p, i);
if (i > n - param_len) {
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_BAD_DH_P_LENGTH);
goto f_err;
}
param_len += i;
if (!(dh->p = BN_bin2bn(p, i, NULL))) {
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_BN_LIB);
goto err;
}
p += i;
if (2 > n - param_len) {
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT);
goto f_err;
}
param_len += 2;
n2s(p, i);
if (i > n - param_len) {
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_BAD_DH_G_LENGTH);
goto f_err;
}
param_len += i;
if (!(dh->g = BN_bin2bn(p, i, NULL))) {
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_BN_LIB);
goto err;
}
p += i;
if (2 > n - param_len) {
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT);
goto f_err;
}
param_len += 2;
n2s(p, i);
if (i > n - param_len) {
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_BAD_DH_PUB_KEY_LENGTH);
goto f_err;
}
param_len += i;
if (!(dh->pub_key = BN_bin2bn(p, i, NULL))) {
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_BN_LIB);
goto err;
}
p += i;
n -= param_len;
if (BN_is_zero(dh->pub_key)) {
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_BAD_DH_PUB_KEY_VALUE);
goto f_err;
}
/*-
* Check that p and g are suitable enough
*
* p is odd
* 1 < g < p - 1
*/
{
BIGNUM *tmp = NULL;
if (!BN_is_odd(dh->p)) {
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_BAD_DH_P_VALUE);
goto f_err;
}
if (BN_is_negative(dh->g) || BN_is_zero(dh->g)
|| BN_is_one(dh->g)) {
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_BAD_DH_G_VALUE);
goto f_err;
}
if ((tmp = BN_new()) == NULL
|| BN_copy(tmp, dh->p) == NULL
|| !BN_sub_word(tmp, 1)) {
BN_free(tmp);
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_BN_LIB);
goto err;
}
if (BN_cmp(dh->g, tmp) >= 0) {
BN_free(tmp);
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_BAD_DH_G_VALUE);
goto f_err;
}
BN_free(tmp);
}
# ifndef OPENSSL_NO_RSA
if (alg_a & SSL_aRSA)
pkey =
X509_get_pubkey(s->session->
sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509);
# else
if (0) ;
# endif
# ifndef OPENSSL_NO_DSA
else if (alg_a & SSL_aDSS)
pkey =
X509_get_pubkey(s->session->
sess_cert->peer_pkeys[SSL_PKEY_DSA_SIGN].
x509);
# endif
/* else anonymous DH, so no certificate or pkey. */
s->session->sess_cert->peer_dh_tmp = dh;
dh = NULL;
} else if ((alg_k & SSL_kDHr) || (alg_k & SSL_kDHd)) {
al = SSL_AD_ILLEGAL_PARAMETER;
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,
SSL_R_TRIED_TO_USE_UNSUPPORTED_CIPHER);
goto f_err;
}
#endif /* !OPENSSL_NO_DH */
#ifndef OPENSSL_NO_ECDH
else if (alg_k & SSL_kEECDH) {
EC_GROUP *ngroup;
const EC_GROUP *group;
if ((ecdh = EC_KEY_new()) == NULL) {
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
goto err;
}
/*
* Extract elliptic curve parameters and the server's ephemeral ECDH
* public key. Keep accumulating lengths of various components in
* param_len and make sure it never exceeds n.
*/
/*
* XXX: For now we only support named (not generic) curves and the
* ECParameters in this case is just three bytes. We also need one
* byte for the length of the encoded point
*/
param_len = 4;
if (param_len > n) {
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT);
goto f_err;
}
/*
* Check curve is one of our preferences, if not server has sent an
* invalid curve. ECParameters is 3 bytes.
*/
if (!tls1_check_curve(s, p, 3)) {
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_WRONG_CURVE);
goto f_err;
}
if ((curve_nid = tls1_ec_curve_id2nid(*(p + 2))) == 0) {
al = SSL_AD_INTERNAL_ERROR;
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,
SSL_R_UNABLE_TO_FIND_ECDH_PARAMETERS);
goto f_err;
}
ngroup = EC_GROUP_new_by_curve_name(curve_nid);
if (ngroup == NULL) {
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_EC_LIB);
goto err;
}
if (EC_KEY_set_group(ecdh, ngroup) == 0) {
EC_GROUP_free(ngroup);
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_EC_LIB);
goto err;
}
EC_GROUP_free(ngroup);
group = EC_KEY_get0_group(ecdh);
if (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) &&
(EC_GROUP_get_degree(group) > 163)) {
al = SSL_AD_EXPORT_RESTRICTION;
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,
SSL_R_ECGROUP_TOO_LARGE_FOR_CIPHER);
goto f_err;
}
p += 3;
/* Next, get the encoded ECPoint */
if (((srvr_ecpoint = EC_POINT_new(group)) == NULL) ||
((bn_ctx = BN_CTX_new()) == NULL)) {
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
goto err;
}
encoded_pt_len = *p; /* length of encoded point */
p += 1;
if ((encoded_pt_len > n - param_len) ||
(EC_POINT_oct2point(group, srvr_ecpoint,
p, encoded_pt_len, bn_ctx) == 0)) {
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_BAD_ECPOINT);
goto f_err;
}
param_len += encoded_pt_len;
n -= param_len;
p += encoded_pt_len;
/*
* The ECC/TLS specification does not mention the use of DSA to sign
* ECParameters in the server key exchange message. We do support RSA
* and ECDSA.
*/
if (0) ;
# ifndef OPENSSL_NO_RSA
else if (alg_a & SSL_aRSA)
pkey =
X509_get_pubkey(s->session->
sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509);
# endif
# ifndef OPENSSL_NO_ECDSA
else if (alg_a & SSL_aECDSA)
pkey =
X509_get_pubkey(s->session->
sess_cert->peer_pkeys[SSL_PKEY_ECC].x509);
# endif
/* else anonymous ECDH, so no certificate or pkey. */
EC_KEY_set_public_key(ecdh, srvr_ecpoint);
s->session->sess_cert->peer_ecdh_tmp = ecdh;
ecdh = NULL;
BN_CTX_free(bn_ctx);
bn_ctx = NULL;
EC_POINT_free(srvr_ecpoint);
srvr_ecpoint = NULL;
} else if (alg_k) {
al = SSL_AD_UNEXPECTED_MESSAGE;
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_UNEXPECTED_MESSAGE);
goto f_err;
}
#endif /* !OPENSSL_NO_ECDH */
/* p points to the next byte, there are 'n' bytes left */
/* if it was signed, check the signature */
if (pkey != NULL) {
if (SSL_USE_SIGALGS(s)) {
int rv;
if (2 > n) {
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT);
goto f_err;
}
rv = tls12_check_peer_sigalg(&md, s, p, pkey);
if (rv == -1)
goto err;
else if (rv == 0) {
goto f_err;
}
#ifdef SSL_DEBUG
fprintf(stderr, "USING TLSv1.2 HASH %s\n", EVP_MD_name(md));
#endif
p += 2;
n -= 2;
} else
md = EVP_sha1();
if (2 > n) {
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT);
goto f_err;
}
n2s(p, i);
n -= 2;
j = EVP_PKEY_size(pkey);
/*
* Check signature length. If n is 0 then signature is empty
*/
if ((i != n) || (n > j) || (n <= 0)) {
/* wrong packet length */
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_WRONG_SIGNATURE_LENGTH);
goto f_err;
}
#ifndef OPENSSL_NO_RSA
if (pkey->type == EVP_PKEY_RSA && !SSL_USE_SIGALGS(s)) {
int num;
unsigned int size;
j = 0;
q = md_buf;
for (num = 2; num > 0; num--) {
EVP_MD_CTX_set_flags(&md_ctx, EVP_MD_CTX_FLAG_NON_FIPS_ALLOW);
if (EVP_DigestInit_ex(&md_ctx,
(num == 2) ? s->ctx->md5 : s->ctx->sha1,
NULL) <= 0
|| EVP_DigestUpdate(&md_ctx, &(s->s3->client_random[0]),
SSL3_RANDOM_SIZE) <= 0
|| EVP_DigestUpdate(&md_ctx, &(s->s3->server_random[0]),
SSL3_RANDOM_SIZE) <= 0
|| EVP_DigestUpdate(&md_ctx, param, param_len) <= 0
|| EVP_DigestFinal_ex(&md_ctx, q, &size) <= 0) {
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,
ERR_R_INTERNAL_ERROR);
al = SSL_AD_INTERNAL_ERROR;
goto f_err;
}
q += size;
j += size;
}
i = RSA_verify(NID_md5_sha1, md_buf, j, p, n, pkey->pkey.rsa);
if (i < 0) {
al = SSL_AD_DECRYPT_ERROR;
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_BAD_RSA_DECRYPT);
goto f_err;
}
if (i == 0) {
/* bad signature */
al = SSL_AD_DECRYPT_ERROR;
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_BAD_SIGNATURE);
goto f_err;
}
} else
#endif
{
if (EVP_VerifyInit_ex(&md_ctx, md, NULL) <= 0
|| EVP_VerifyUpdate(&md_ctx, &(s->s3->client_random[0]),
SSL3_RANDOM_SIZE) <= 0
|| EVP_VerifyUpdate(&md_ctx, &(s->s3->server_random[0]),
SSL3_RANDOM_SIZE) <= 0
|| EVP_VerifyUpdate(&md_ctx, param, param_len) <= 0) {
al = SSL_AD_INTERNAL_ERROR;
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_EVP_LIB);
goto f_err;
}
if (EVP_VerifyFinal(&md_ctx, p, (int)n, pkey) <= 0) {
/* bad signature */
al = SSL_AD_DECRYPT_ERROR;
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_BAD_SIGNATURE);
goto f_err;
}
}
} else {
/* aNULL, aSRP or kPSK do not need public keys */
if (!(alg_a & (SSL_aNULL | SSL_aSRP)) && !(alg_k & SSL_kPSK)) {
/* Might be wrong key type, check it */
if (ssl3_check_cert_and_algorithm(s))
/* Otherwise this shouldn't happen */
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
goto err;
}
/* still data left over */
if (n != 0) {
SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_EXTRA_DATA_IN_MESSAGE);
goto f_err;
}
}
EVP_PKEY_free(pkey);
EVP_MD_CTX_cleanup(&md_ctx);
return (1);
f_err:
ssl3_send_alert(s, SSL3_AL_FATAL, al);
err:
EVP_PKEY_free(pkey);
#ifndef OPENSSL_NO_RSA
if (rsa != NULL)
RSA_free(rsa);
#endif
#ifndef OPENSSL_NO_DH
if (dh != NULL)
DH_free(dh);
#endif
#ifndef OPENSSL_NO_ECDH
BN_CTX_free(bn_ctx);
EC_POINT_free(srvr_ecpoint);
if (ecdh != NULL)
EC_KEY_free(ecdh);
#endif
EVP_MD_CTX_cleanup(&md_ctx);
s->state = SSL_ST_ERR;
return (-1);
}
int ssl3_get_certificate_request(SSL *s)
{
int ok, ret = 0;
unsigned long n, nc, l;
unsigned int llen, ctype_num, i;
X509_NAME *xn = NULL;
const unsigned char *p, *q;
unsigned char *d;
STACK_OF(X509_NAME) *ca_sk = NULL;
n = s->method->ssl_get_message(s,
SSL3_ST_CR_CERT_REQ_A,
SSL3_ST_CR_CERT_REQ_B,
-1, s->max_cert_list, &ok);
if (!ok)
return ((int)n);
s->s3->tmp.cert_req = 0;
if (s->s3->tmp.message_type == SSL3_MT_SERVER_DONE) {
s->s3->tmp.reuse_message = 1;
/*
* If we get here we don't need any cached handshake records as we
* wont be doing client auth.
*/
if (s->s3->handshake_buffer) {
if (!ssl3_digest_cached_records(s))
goto err;
}
return (1);
}
if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE_REQUEST) {
ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST, SSL_R_WRONG_MESSAGE_TYPE);
goto err;
}
/* TLS does not like anon-DH with client cert */
if (s->version > SSL3_VERSION) {
if (s->s3->tmp.new_cipher->algorithm_auth & SSL_aNULL) {
ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,
SSL_R_TLS_CLIENT_CERT_REQ_WITH_ANON_CIPHER);
goto err;
}
}
p = d = (unsigned char *)s->init_msg;
if ((ca_sk = sk_X509_NAME_new(ca_dn_cmp)) == NULL) {
SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST, ERR_R_MALLOC_FAILURE);
goto err;
}
/* get the certificate types */
ctype_num = *(p++);
if (s->cert->ctypes) {
OPENSSL_free(s->cert->ctypes);
s->cert->ctypes = NULL;
}
if (ctype_num > SSL3_CT_NUMBER) {
/* If we exceed static buffer copy all to cert structure */
s->cert->ctypes = OPENSSL_malloc(ctype_num);
if (s->cert->ctypes == NULL) {
SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST, ERR_R_MALLOC_FAILURE);
goto err;
}
memcpy(s->cert->ctypes, p, ctype_num);
s->cert->ctype_num = (size_t)ctype_num;
ctype_num = SSL3_CT_NUMBER;
}
for (i = 0; i < ctype_num; i++)
s->s3->tmp.ctype[i] = p[i];
p += p[-1];
if (SSL_USE_SIGALGS(s)) {
n2s(p, llen);
/*
* Check we have enough room for signature algorithms and following
* length value.
*/
if ((unsigned long)(p - d + llen + 2) > n) {
ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,
SSL_R_DATA_LENGTH_TOO_LONG);
goto err;
}
/* Clear certificate digests and validity flags */
for (i = 0; i < SSL_PKEY_NUM; i++) {
s->cert->pkeys[i].digest = NULL;
s->cert->pkeys[i].valid_flags = 0;
}
if ((llen & 1) || !tls1_save_sigalgs(s, p, llen)) {
ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,
SSL_R_SIGNATURE_ALGORITHMS_ERROR);
goto err;
}
if (!tls1_process_sigalgs(s)) {
ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST, ERR_R_MALLOC_FAILURE);
goto err;
}
p += llen;
}
/* get the CA RDNs */
n2s(p, llen);
#if 0
{
FILE *out;
out = fopen("/tmp/vsign.der", "w");
fwrite(p, 1, llen, out);
fclose(out);
}
#endif
if ((unsigned long)(p - d + llen) != n) {
ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST, SSL_R_LENGTH_MISMATCH);
goto err;
}
for (nc = 0; nc < llen;) {
if (nc + 2 > llen) {
ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST, SSL_R_CA_DN_TOO_LONG);
goto err;
}
n2s(p, l);
if ((l + nc + 2) > llen) {
if ((s->options & SSL_OP_NETSCAPE_CA_DN_BUG))
goto cont; /* netscape bugs */
ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST, SSL_R_CA_DN_TOO_LONG);
goto err;
}
q = p;
if ((xn = d2i_X509_NAME(NULL, &q, l)) == NULL) {
/* If netscape tolerance is on, ignore errors */
if (s->options & SSL_OP_NETSCAPE_CA_DN_BUG)
goto cont;
else {
ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST, ERR_R_ASN1_LIB);
goto err;
}
}
if (q != (p + l)) {
ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,
SSL_R_CA_DN_LENGTH_MISMATCH);
goto err;
}
if (!sk_X509_NAME_push(ca_sk, xn)) {
SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST, ERR_R_MALLOC_FAILURE);
goto err;
}
xn = NULL;
p += l;
nc += l + 2;
}
if (0) {
cont:
ERR_clear_error();
}
/* we should setup a certificate to return.... */
s->s3->tmp.cert_req = 1;
s->s3->tmp.ctype_num = ctype_num;
if (s->s3->tmp.ca_names != NULL)
sk_X509_NAME_pop_free(s->s3->tmp.ca_names, X509_NAME_free);
s->s3->tmp.ca_names = ca_sk;
ca_sk = NULL;
ret = 1;
goto done;
err:
s->state = SSL_ST_ERR;
done:
X509_NAME_free(xn);
if (ca_sk != NULL)
sk_X509_NAME_pop_free(ca_sk, X509_NAME_free);
return (ret);
}
static int ca_dn_cmp(const X509_NAME *const *a, const X509_NAME *const *b)
{
return (X509_NAME_cmp(*a, *b));
}
#ifndef OPENSSL_NO_TLSEXT
int ssl3_get_new_session_ticket(SSL *s)
{
int ok, al, ret = 0, ticklen;
long n;
const unsigned char *p;
unsigned char *d;
unsigned long ticket_lifetime_hint;
n = s->method->ssl_get_message(s,
SSL3_ST_CR_SESSION_TICKET_A,
SSL3_ST_CR_SESSION_TICKET_B,
SSL3_MT_NEWSESSION_TICKET, 16384, &ok);
if (!ok)
return ((int)n);
if (n < 6) {
/* need at least ticket_lifetime_hint + ticket length */
al = SSL_AD_DECODE_ERROR;
SSLerr(SSL_F_SSL3_GET_NEW_SESSION_TICKET, SSL_R_LENGTH_MISMATCH);
goto f_err;
}
p = d = (unsigned char *)s->init_msg;
n2l(p, ticket_lifetime_hint);
n2s(p, ticklen);
/* ticket_lifetime_hint + ticket_length + ticket */
if (ticklen + 6 != n) {
al = SSL_AD_DECODE_ERROR;
SSLerr(SSL_F_SSL3_GET_NEW_SESSION_TICKET, SSL_R_LENGTH_MISMATCH);
goto f_err;
}
/* Server is allowed to change its mind and send an empty ticket. */
if (ticklen == 0)
return 1;
if (s->session->session_id_length > 0) {
int i = s->session_ctx->session_cache_mode;
SSL_SESSION *new_sess;
/*
* We reused an existing session, so we need to replace it with a new
* one
*/
if (i & SSL_SESS_CACHE_CLIENT) {
/*
* Remove the old session from the cache
*/
if (i & SSL_SESS_CACHE_NO_INTERNAL_STORE) {
if (s->session_ctx->remove_session_cb != NULL)
s->session_ctx->remove_session_cb(s->session_ctx,
s->session);
} else {
/* We carry on if this fails */
SSL_CTX_remove_session(s->session_ctx, s->session);
}
}
if ((new_sess = ssl_session_dup(s->session, 0)) == 0) {
al = SSL_AD_INTERNAL_ERROR;
SSLerr(SSL_F_SSL3_GET_NEW_SESSION_TICKET, ERR_R_MALLOC_FAILURE);
goto f_err;
}
SSL_SESSION_free(s->session);
s->session = new_sess;
}
if (s->session->tlsext_tick) {
OPENSSL_free(s->session->tlsext_tick);
s->session->tlsext_ticklen = 0;
}
s->session->tlsext_tick = OPENSSL_malloc(ticklen);
if (!s->session->tlsext_tick) {
SSLerr(SSL_F_SSL3_GET_NEW_SESSION_TICKET, ERR_R_MALLOC_FAILURE);
goto err;
}
memcpy(s->session->tlsext_tick, p, ticklen);
s->session->tlsext_tick_lifetime_hint = ticket_lifetime_hint;
s->session->tlsext_ticklen = ticklen;
/*
* There are two ways to detect a resumed ticket session. One is to set
* an appropriate session ID and then the server must return a match in
* ServerHello. This allows the normal client session ID matching to work
* and we know much earlier that the ticket has been accepted. The
* other way is to set zero length session ID when the ticket is
* presented and rely on the handshake to determine session resumption.
* We choose the former approach because this fits in with assumptions
* elsewhere in OpenSSL. The session ID is set to the SHA256 (or SHA1 is
* SHA256 is disabled) hash of the ticket.
*/
EVP_Digest(p, ticklen,
s->session->session_id, &s->session->session_id_length,
# ifndef OPENSSL_NO_SHA256
EVP_sha256(), NULL);
# else
EVP_sha1(), NULL);
# endif
ret = 1;
return (ret);
f_err:
ssl3_send_alert(s, SSL3_AL_FATAL, al);
err:
s->state = SSL_ST_ERR;
return (-1);
}
int ssl3_get_cert_status(SSL *s)
{
int ok, al;
unsigned long resplen, n;
const unsigned char *p;
n = s->method->ssl_get_message(s,
SSL3_ST_CR_CERT_STATUS_A,
SSL3_ST_CR_CERT_STATUS_B,
-1, 16384, &ok);
if (!ok)
return ((int)n);
if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE_STATUS) {
/*
* The CertificateStatus message is optional even if
* tlsext_status_expected is set
*/
s->s3->tmp.reuse_message = 1;
} else {
if (n < 4) {
/* need at least status type + length */
al = SSL_AD_DECODE_ERROR;
SSLerr(SSL_F_SSL3_GET_CERT_STATUS, SSL_R_LENGTH_MISMATCH);
goto f_err;
}
p = (unsigned char *)s->init_msg;
if (*p++ != TLSEXT_STATUSTYPE_ocsp) {
al = SSL_AD_DECODE_ERROR;
SSLerr(SSL_F_SSL3_GET_CERT_STATUS, SSL_R_UNSUPPORTED_STATUS_TYPE);
goto f_err;
}
n2l3(p, resplen);
if (resplen + 4 != n) {
al = SSL_AD_DECODE_ERROR;
SSLerr(SSL_F_SSL3_GET_CERT_STATUS, SSL_R_LENGTH_MISMATCH);
goto f_err;
}
s->tlsext_ocsp_resp = BUF_memdup(p, resplen);
if (s->tlsext_ocsp_resp == NULL) {
al = SSL_AD_INTERNAL_ERROR;
SSLerr(SSL_F_SSL3_GET_CERT_STATUS, ERR_R_MALLOC_FAILURE);
goto f_err;
}
s->tlsext_ocsp_resplen = resplen;
}
if (s->ctx->tlsext_status_cb) {
int ret;
ret = s->ctx->tlsext_status_cb(s, s->ctx->tlsext_status_arg);
if (ret == 0) {
al = SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE;
SSLerr(SSL_F_SSL3_GET_CERT_STATUS, SSL_R_INVALID_STATUS_RESPONSE);
goto f_err;
}
if (ret < 0) {
al = SSL_AD_INTERNAL_ERROR;
SSLerr(SSL_F_SSL3_GET_CERT_STATUS, ERR_R_MALLOC_FAILURE);
goto f_err;
}
}
return 1;
f_err:
ssl3_send_alert(s, SSL3_AL_FATAL, al);
s->state = SSL_ST_ERR;
return (-1);
}
#endif
int ssl3_get_server_done(SSL *s)
{
int ok, ret = 0;
long n;
/* Second to last param should be very small, like 0 :-) */
n = s->method->ssl_get_message(s,
SSL3_ST_CR_SRVR_DONE_A,
SSL3_ST_CR_SRVR_DONE_B,
SSL3_MT_SERVER_DONE, 30, &ok);
if (!ok)
return ((int)n);
if (n > 0) {
/* should contain no data */
ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
SSLerr(SSL_F_SSL3_GET_SERVER_DONE, SSL_R_LENGTH_MISMATCH);
s->state = SSL_ST_ERR;
return -1;
}
ret = 1;
return (ret);
}
#ifndef OPENSSL_NO_DH
static DH *get_server_static_dh_key(SESS_CERT *scert)
{
DH *dh_srvr = NULL;
EVP_PKEY *spkey = NULL;
int idx = scert->peer_cert_type;
if (idx >= 0)
spkey = X509_get_pubkey(scert->peer_pkeys[idx].x509);
if (spkey) {
dh_srvr = EVP_PKEY_get1_DH(spkey);
EVP_PKEY_free(spkey);
}
if (dh_srvr == NULL)
SSLerr(SSL_F_GET_SERVER_STATIC_DH_KEY, ERR_R_INTERNAL_ERROR);
return dh_srvr;
}
#endif
int ssl3_send_client_key_exchange(SSL *s)
{
unsigned char *p;
int n;
unsigned long alg_k;
#ifndef OPENSSL_NO_RSA
unsigned char *q;
EVP_PKEY *pkey = NULL;
#endif
#ifndef OPENSSL_NO_KRB5
KSSL_ERR kssl_err;
#endif /* OPENSSL_NO_KRB5 */
#ifndef OPENSSL_NO_ECDH
EC_KEY *clnt_ecdh = NULL;
const EC_POINT *srvr_ecpoint = NULL;
EVP_PKEY *srvr_pub_pkey = NULL;
unsigned char *encodedPoint = NULL;
int encoded_pt_len = 0;
BN_CTX *bn_ctx = NULL;
#endif
if (s->state == SSL3_ST_CW_KEY_EXCH_A) {
p = ssl_handshake_start(s);
alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
/* Fool emacs indentation */
if (0) {
}
#ifndef OPENSSL_NO_RSA
else if (alg_k & SSL_kRSA) {
RSA *rsa;
unsigned char tmp_buf[SSL_MAX_MASTER_KEY_LENGTH];
if (s->session->sess_cert == NULL) {
/*
* We should always have a server certificate with SSL_kRSA.
*/
SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
ERR_R_INTERNAL_ERROR);
goto err;
}
if (s->session->sess_cert->peer_rsa_tmp != NULL)
rsa = s->session->sess_cert->peer_rsa_tmp;
else {
pkey =
X509_get_pubkey(s->session->
sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].
x509);
if ((pkey == NULL) || (pkey->type != EVP_PKEY_RSA)
|| (pkey->pkey.rsa == NULL)) {
SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
ERR_R_INTERNAL_ERROR);
EVP_PKEY_free(pkey);
goto err;
}
rsa = pkey->pkey.rsa;
EVP_PKEY_free(pkey);
}
tmp_buf[0] = s->client_version >> 8;
tmp_buf[1] = s->client_version & 0xff;
- if (RAND_bytes(&(tmp_buf[2]), sizeof tmp_buf - 2) <= 0)
+ if (RAND_bytes(&(tmp_buf[2]), sizeof(tmp_buf) - 2) <= 0)
goto err;
- s->session->master_key_length = sizeof tmp_buf;
+ s->session->master_key_length = sizeof(tmp_buf);
q = p;
/* Fix buf for TLS and beyond */
if (s->version > SSL3_VERSION)
p += 2;
- n = RSA_public_encrypt(sizeof tmp_buf,
+ n = RSA_public_encrypt(sizeof(tmp_buf),
tmp_buf, p, rsa, RSA_PKCS1_PADDING);
# ifdef PKCS1_CHECK
if (s->options & SSL_OP_PKCS1_CHECK_1)
p[1]++;
if (s->options & SSL_OP_PKCS1_CHECK_2)
tmp_buf[0] = 0x70;
# endif
if (n <= 0) {
SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
SSL_R_BAD_RSA_ENCRYPT);
goto err;
}
/* Fix buf for TLS and beyond */
if (s->version > SSL3_VERSION) {
s2n(n, q);
n += 2;
}
s->session->master_key_length =
s->method->ssl3_enc->generate_master_secret(s,
s->
session->master_key,
tmp_buf,
- sizeof tmp_buf);
- OPENSSL_cleanse(tmp_buf, sizeof tmp_buf);
+ sizeof(tmp_buf));
+ OPENSSL_cleanse(tmp_buf, sizeof(tmp_buf));
}
#endif
#ifndef OPENSSL_NO_KRB5
else if (alg_k & SSL_kKRB5) {
krb5_error_code krb5rc;
KSSL_CTX *kssl_ctx = s->kssl_ctx;
/* krb5_data krb5_ap_req; */
krb5_data *enc_ticket;
krb5_data authenticator, *authp = NULL;
EVP_CIPHER_CTX ciph_ctx;
const EVP_CIPHER *enc = NULL;
unsigned char iv[EVP_MAX_IV_LENGTH];
unsigned char tmp_buf[SSL_MAX_MASTER_KEY_LENGTH];
unsigned char epms[SSL_MAX_MASTER_KEY_LENGTH + EVP_MAX_IV_LENGTH];
int padl, outl = sizeof(epms);
EVP_CIPHER_CTX_init(&ciph_ctx);
# ifdef KSSL_DEBUG
fprintf(stderr, "ssl3_send_client_key_exchange(%lx & %lx)\n",
alg_k, SSL_kKRB5);
# endif /* KSSL_DEBUG */
authp = NULL;
# ifdef KRB5SENDAUTH
if (KRB5SENDAUTH)
authp = &authenticator;
# endif /* KRB5SENDAUTH */
krb5rc = kssl_cget_tkt(kssl_ctx, &enc_ticket, authp, &kssl_err);
enc = kssl_map_enc(kssl_ctx->enctype);
if (enc == NULL)
goto err;
# ifdef KSSL_DEBUG
{
fprintf(stderr, "kssl_cget_tkt rtn %d\n", krb5rc);
if (krb5rc && kssl_err.text)
fprintf(stderr, "kssl_cget_tkt kssl_err=%s\n",
kssl_err.text);
}
# endif /* KSSL_DEBUG */
if (krb5rc) {
ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, kssl_err.reason);
goto err;
}
/*-
* 20010406 VRS - Earlier versions used KRB5 AP_REQ
* in place of RFC 2712 KerberosWrapper, as in:
*
* Send ticket (copy to *p, set n = length)
* n = krb5_ap_req.length;
* memcpy(p, krb5_ap_req.data, krb5_ap_req.length);
* if (krb5_ap_req.data)
* kssl_krb5_free_data_contents(NULL,&krb5_ap_req);
*
* Now using real RFC 2712 KerberosWrapper
* (Thanks to Simon Wilkinson <sxw@sxw.org.uk>)
* Note: 2712 "opaque" types are here replaced
* with a 2-byte length followed by the value.
* Example:
* KerberosWrapper= xx xx asn1ticket 0 0 xx xx encpms
* Where "xx xx" = length bytes. Shown here with
* optional authenticator omitted.
*/
/* KerberosWrapper.Ticket */
s2n(enc_ticket->length, p);
memcpy(p, enc_ticket->data, enc_ticket->length);
p += enc_ticket->length;
n = enc_ticket->length + 2;
/* KerberosWrapper.Authenticator */
if (authp && authp->length) {
s2n(authp->length, p);
memcpy(p, authp->data, authp->length);
p += authp->length;
n += authp->length + 2;
free(authp->data);
authp->data = NULL;
authp->length = 0;
} else {
s2n(0, p); /* null authenticator length */
n += 2;
}
tmp_buf[0] = s->client_version >> 8;
tmp_buf[1] = s->client_version & 0xff;
- if (RAND_bytes(&(tmp_buf[2]), sizeof tmp_buf - 2) <= 0)
+ if (RAND_bytes(&(tmp_buf[2]), sizeof(tmp_buf) - 2) <= 0)
goto err;
/*-
* 20010420 VRS. Tried it this way; failed.
* EVP_EncryptInit_ex(&ciph_ctx,enc, NULL,NULL);
* EVP_CIPHER_CTX_set_key_length(&ciph_ctx,
* kssl_ctx->length);
* EVP_EncryptInit_ex(&ciph_ctx,NULL, key,iv);
*/
- memset(iv, 0, sizeof iv); /* per RFC 1510 */
+ memset(iv, 0, sizeof(iv)); /* per RFC 1510 */
EVP_EncryptInit_ex(&ciph_ctx, enc, NULL, kssl_ctx->key, iv);
EVP_EncryptUpdate(&ciph_ctx, epms, &outl, tmp_buf,
- sizeof tmp_buf);
+ sizeof(tmp_buf));
EVP_EncryptFinal_ex(&ciph_ctx, &(epms[outl]), &padl);
outl += padl;
- if (outl > (int)sizeof epms) {
+ if (outl > (int)sizeof(epms)) {
SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
ERR_R_INTERNAL_ERROR);
goto err;
}
EVP_CIPHER_CTX_cleanup(&ciph_ctx);
/* KerberosWrapper.EncryptedPreMasterSecret */
s2n(outl, p);
memcpy(p, epms, outl);
p += outl;
n += outl + 2;
s->session->master_key_length =
s->method->ssl3_enc->generate_master_secret(s,
s->
session->master_key,
tmp_buf,
- sizeof tmp_buf);
+ sizeof(tmp_buf));
- OPENSSL_cleanse(tmp_buf, sizeof tmp_buf);
+ OPENSSL_cleanse(tmp_buf, sizeof(tmp_buf));
OPENSSL_cleanse(epms, outl);
}
#endif
#ifndef OPENSSL_NO_DH
else if (alg_k & (SSL_kEDH | SSL_kDHr | SSL_kDHd)) {
DH *dh_srvr, *dh_clnt;
SESS_CERT *scert = s->session->sess_cert;
if (scert == NULL) {
ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
SSL_R_UNEXPECTED_MESSAGE);
goto err;
}
if (scert->peer_dh_tmp != NULL) {
dh_srvr = scert->peer_dh_tmp;
} else {
dh_srvr = get_server_static_dh_key(scert);
if (dh_srvr == NULL)
goto err;
}
if (s->s3->flags & TLS1_FLAGS_SKIP_CERT_VERIFY) {
/* Use client certificate key */
EVP_PKEY *clkey = s->cert->key->privatekey;
dh_clnt = NULL;
if (clkey)
dh_clnt = EVP_PKEY_get1_DH(clkey);
if (dh_clnt == NULL) {
SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
ERR_R_INTERNAL_ERROR);
goto err;
}
} else {
/* generate a new random key */
if ((dh_clnt = DHparams_dup(dh_srvr)) == NULL) {
SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_DH_LIB);
goto err;
}
if (!DH_generate_key(dh_clnt)) {
SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_DH_LIB);
DH_free(dh_clnt);
goto err;
}
}
/*
* use the 'p' output buffer for the DH key, but make sure to
* clear it out afterwards
*/
n = DH_compute_key(p, dh_srvr->pub_key, dh_clnt);
if (scert->peer_dh_tmp == NULL)
DH_free(dh_srvr);
if (n <= 0) {
SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_DH_LIB);
DH_free(dh_clnt);
goto err;
}
/* generate master key from the result */
s->session->master_key_length =
s->method->ssl3_enc->generate_master_secret(s,
s->
session->master_key,
p, n);
/* clean up */
memset(p, 0, n);
if (s->s3->flags & TLS1_FLAGS_SKIP_CERT_VERIFY)
n = 0;
else {
/* send off the data */
n = BN_num_bytes(dh_clnt->pub_key);
s2n(n, p);
BN_bn2bin(dh_clnt->pub_key, p);
n += 2;
}
DH_free(dh_clnt);
}
#endif
#ifndef OPENSSL_NO_ECDH
else if (alg_k & (SSL_kEECDH | SSL_kECDHr | SSL_kECDHe)) {
const EC_GROUP *srvr_group = NULL;
EC_KEY *tkey;
int ecdh_clnt_cert = 0;
int field_size = 0;
if (s->session->sess_cert == NULL) {
ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
SSL_R_UNEXPECTED_MESSAGE);
goto err;
}
/*
* Did we send out the client's ECDH share for use in premaster
* computation as part of client certificate? If so, set
* ecdh_clnt_cert to 1.
*/
if ((alg_k & (SSL_kECDHr | SSL_kECDHe)) && (s->cert != NULL)) {
/*-
* XXX: For now, we do not support client
* authentication using ECDH certificates.
* To add such support, one needs to add
* code that checks for appropriate
* conditions and sets ecdh_clnt_cert to 1.
* For example, the cert have an ECC
* key on the same curve as the server's
* and the key should be authorized for
* key agreement.
*
* One also needs to add code in ssl3_connect
* to skip sending the certificate verify
* message.
*
* if ((s->cert->key->privatekey != NULL) &&
* (s->cert->key->privatekey->type ==
* EVP_PKEY_EC) && ...)
* ecdh_clnt_cert = 1;
*/
}
if (s->session->sess_cert->peer_ecdh_tmp != NULL) {
tkey = s->session->sess_cert->peer_ecdh_tmp;
} else {
/* Get the Server Public Key from Cert */
srvr_pub_pkey =
X509_get_pubkey(s->session->
sess_cert->peer_pkeys[SSL_PKEY_ECC].x509);
if ((srvr_pub_pkey == NULL)
|| (srvr_pub_pkey->type != EVP_PKEY_EC)
|| (srvr_pub_pkey->pkey.ec == NULL)) {
SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
ERR_R_INTERNAL_ERROR);
goto err;
}
tkey = srvr_pub_pkey->pkey.ec;
}
srvr_group = EC_KEY_get0_group(tkey);
srvr_ecpoint = EC_KEY_get0_public_key(tkey);
if ((srvr_group == NULL) || (srvr_ecpoint == NULL)) {
SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
ERR_R_INTERNAL_ERROR);
goto err;
}
if ((clnt_ecdh = EC_KEY_new()) == NULL) {
SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
ERR_R_MALLOC_FAILURE);
goto err;
}
if (!EC_KEY_set_group(clnt_ecdh, srvr_group)) {
SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_EC_LIB);
goto err;
}
if (ecdh_clnt_cert) {
/*
* Reuse key info from our certificate We only need our
* private key to perform the ECDH computation.
*/
const BIGNUM *priv_key;
tkey = s->cert->key->privatekey->pkey.ec;
priv_key = EC_KEY_get0_private_key(tkey);
if (priv_key == NULL) {
SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
ERR_R_MALLOC_FAILURE);
goto err;
}
if (!EC_KEY_set_private_key(clnt_ecdh, priv_key)) {
SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_EC_LIB);
goto err;
}
} else {
/* Generate a new ECDH key pair */
if (!(EC_KEY_generate_key(clnt_ecdh))) {
SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
ERR_R_ECDH_LIB);
goto err;
}
}
/*
* use the 'p' output buffer for the ECDH key, but make sure to
* clear it out afterwards
*/
field_size = EC_GROUP_get_degree(srvr_group);
if (field_size <= 0) {
SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_ECDH_LIB);
goto err;
}
n = ECDH_compute_key(p, (field_size + 7) / 8, srvr_ecpoint,
clnt_ecdh, NULL);
if (n <= 0) {
SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_ECDH_LIB);
goto err;
}
/* generate master key from the result */
s->session->master_key_length =
s->method->ssl3_enc->generate_master_secret(s,
s->
session->master_key,
p, n);
memset(p, 0, n); /* clean up */
if (ecdh_clnt_cert) {
/* Send empty client key exch message */
n = 0;
} else {
/*
* First check the size of encoding and allocate memory
* accordingly.
*/
encoded_pt_len =
EC_POINT_point2oct(srvr_group,
EC_KEY_get0_public_key(clnt_ecdh),
POINT_CONVERSION_UNCOMPRESSED,
NULL, 0, NULL);
encodedPoint = (unsigned char *)
OPENSSL_malloc(encoded_pt_len * sizeof(unsigned char));
bn_ctx = BN_CTX_new();
if ((encodedPoint == NULL) || (bn_ctx == NULL)) {
SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
ERR_R_MALLOC_FAILURE);
goto err;
}
/* Encode the public key */
n = EC_POINT_point2oct(srvr_group,
EC_KEY_get0_public_key(clnt_ecdh),
POINT_CONVERSION_UNCOMPRESSED,
encodedPoint, encoded_pt_len, bn_ctx);
*p = n; /* length of encoded point */
/* Encoded point will be copied here */
p += 1;
/* copy the point */
memcpy((unsigned char *)p, encodedPoint, n);
/* increment n to account for length field */
n += 1;
}
/* Free allocated memory */
BN_CTX_free(bn_ctx);
if (encodedPoint != NULL)
OPENSSL_free(encodedPoint);
if (clnt_ecdh != NULL)
EC_KEY_free(clnt_ecdh);
EVP_PKEY_free(srvr_pub_pkey);
}
#endif /* !OPENSSL_NO_ECDH */
else if (alg_k & SSL_kGOST) {
/* GOST key exchange message creation */
EVP_PKEY_CTX *pkey_ctx;
X509 *peer_cert;
size_t msglen;
unsigned int md_len;
int keytype;
unsigned char premaster_secret[32], shared_ukm[32], tmp[256];
EVP_MD_CTX *ukm_hash;
EVP_PKEY *pub_key;
/*
* Get server sertificate PKEY and create ctx from it
*/
peer_cert =
s->session->
sess_cert->peer_pkeys[(keytype = SSL_PKEY_GOST01)].x509;
if (!peer_cert)
peer_cert =
s->session->
sess_cert->peer_pkeys[(keytype = SSL_PKEY_GOST94)].x509;
if (!peer_cert) {
SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
SSL_R_NO_GOST_CERTIFICATE_SENT_BY_PEER);
goto err;
}
pkey_ctx = EVP_PKEY_CTX_new(pub_key =
X509_get_pubkey(peer_cert), NULL);
if (pkey_ctx == NULL) {
SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
ERR_R_MALLOC_FAILURE);
goto err;
}
/*
* If we have send a certificate, and certificate key
*
* * parameters match those of server certificate, use
* certificate key for key exchange
*/
/* Otherwise, generate ephemeral key pair */
if (pkey_ctx == NULL
|| EVP_PKEY_encrypt_init(pkey_ctx) <= 0
/* Generate session key */
|| RAND_bytes(premaster_secret, 32) <= 0) {
EVP_PKEY_CTX_free(pkey_ctx);
SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
ERR_R_INTERNAL_ERROR);
goto err;
}
/*
* Compute shared IV and store it in algorithm-specific context
* data
*/
ukm_hash = EVP_MD_CTX_create();
if (EVP_DigestInit(ukm_hash,
EVP_get_digestbynid(NID_id_GostR3411_94)) <= 0
|| EVP_DigestUpdate(ukm_hash, s->s3->client_random,
SSL3_RANDOM_SIZE) <= 0
|| EVP_DigestUpdate(ukm_hash, s->s3->server_random,
SSL3_RANDOM_SIZE) <= 0
|| EVP_DigestFinal_ex(ukm_hash, shared_ukm, &md_len) <= 0) {
EVP_MD_CTX_destroy(ukm_hash);
SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
ERR_R_INTERNAL_ERROR);
goto err;
}
EVP_MD_CTX_destroy(ukm_hash);
if (EVP_PKEY_CTX_ctrl
(pkey_ctx, -1, EVP_PKEY_OP_ENCRYPT, EVP_PKEY_CTRL_SET_IV, 8,
shared_ukm) < 0) {
SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
SSL_R_LIBRARY_BUG);
goto err;
}
/* Make GOST keytransport blob message */
/*
* Encapsulate it into sequence
*/
*(p++) = V_ASN1_SEQUENCE | V_ASN1_CONSTRUCTED;
msglen = 255;
if (EVP_PKEY_encrypt(pkey_ctx, tmp, &msglen, premaster_secret, 32)
<= 0) {
SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
SSL_R_LIBRARY_BUG);
goto err;
}
if (msglen >= 0x80) {
*(p++) = 0x81;
*(p++) = msglen & 0xff;
n = msglen + 3;
} else {
*(p++) = msglen & 0xff;
n = msglen + 2;
}
memcpy(p, tmp, msglen);
EVP_PKEY_CTX_free(pkey_ctx);
s->session->master_key_length =
s->method->ssl3_enc->generate_master_secret(s,
s->
session->master_key,
premaster_secret,
32);
EVP_PKEY_free(pub_key);
}
#ifndef OPENSSL_NO_SRP
else if (alg_k & SSL_kSRP) {
if (s->srp_ctx.A != NULL) {
/* send off the data */
n = BN_num_bytes(s->srp_ctx.A);
s2n(n, p);
BN_bn2bin(s->srp_ctx.A, p);
n += 2;
} else {
SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
ERR_R_INTERNAL_ERROR);
goto err;
}
if (s->session->srp_username != NULL)
OPENSSL_free(s->session->srp_username);
s->session->srp_username = BUF_strdup(s->srp_ctx.login);
if (s->session->srp_username == NULL) {
SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
ERR_R_MALLOC_FAILURE);
goto err;
}
if ((s->session->master_key_length =
SRP_generate_client_master_secret(s,
s->session->master_key)) <
0) {
SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
ERR_R_INTERNAL_ERROR);
goto err;
}
}
#endif
#ifndef OPENSSL_NO_PSK
else if (alg_k & SSL_kPSK) {
/*
* The callback needs PSK_MAX_IDENTITY_LEN + 1 bytes to return a
* \0-terminated identity. The last byte is for us for simulating
* strnlen.
*/
char identity[PSK_MAX_IDENTITY_LEN + 2];
size_t identity_len;
unsigned char *t = NULL;
unsigned char psk_or_pre_ms[PSK_MAX_PSK_LEN * 2 + 4];
unsigned int pre_ms_len = 0, psk_len = 0;
int psk_err = 1;
n = 0;
if (s->psk_client_callback == NULL) {
SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
SSL_R_PSK_NO_CLIENT_CB);
goto err;
}
memset(identity, 0, sizeof(identity));
psk_len = s->psk_client_callback(s, s->session->psk_identity_hint,
identity, sizeof(identity) - 1,
psk_or_pre_ms,
sizeof(psk_or_pre_ms));
if (psk_len > PSK_MAX_PSK_LEN) {
SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
ERR_R_INTERNAL_ERROR);
goto psk_err;
} else if (psk_len == 0) {
SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
SSL_R_PSK_IDENTITY_NOT_FOUND);
goto psk_err;
}
identity[PSK_MAX_IDENTITY_LEN + 1] = '\0';
identity_len = strlen(identity);
if (identity_len > PSK_MAX_IDENTITY_LEN) {
SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
ERR_R_INTERNAL_ERROR);
goto psk_err;
}
/* create PSK pre_master_secret */
pre_ms_len = 2 + psk_len + 2 + psk_len;
t = psk_or_pre_ms;
memmove(psk_or_pre_ms + psk_len + 4, psk_or_pre_ms, psk_len);
s2n(psk_len, t);
memset(t, 0, psk_len);
t += psk_len;
s2n(psk_len, t);
if (s->session->psk_identity_hint != NULL)
OPENSSL_free(s->session->psk_identity_hint);
s->session->psk_identity_hint =
BUF_strdup(s->ctx->psk_identity_hint);
if (s->ctx->psk_identity_hint != NULL
&& s->session->psk_identity_hint == NULL) {
SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
ERR_R_MALLOC_FAILURE);
goto psk_err;
}
if (s->session->psk_identity != NULL)
OPENSSL_free(s->session->psk_identity);
s->session->psk_identity = BUF_strdup(identity);
if (s->session->psk_identity == NULL) {
SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
ERR_R_MALLOC_FAILURE);
goto psk_err;
}
s->session->master_key_length =
s->method->ssl3_enc->generate_master_secret(s,
s->
session->master_key,
psk_or_pre_ms,
pre_ms_len);
s2n(identity_len, p);
memcpy(p, identity, identity_len);
n = 2 + identity_len;
psk_err = 0;
psk_err:
OPENSSL_cleanse(identity, sizeof(identity));
OPENSSL_cleanse(psk_or_pre_ms, sizeof(psk_or_pre_ms));
if (psk_err != 0) {
ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
goto err;
}
}
#endif
else {
ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
goto err;
}
ssl_set_handshake_header(s, SSL3_MT_CLIENT_KEY_EXCHANGE, n);
s->state = SSL3_ST_CW_KEY_EXCH_B;
}
/* SSL3_ST_CW_KEY_EXCH_B */
return ssl_do_write(s);
err:
#ifndef OPENSSL_NO_ECDH
BN_CTX_free(bn_ctx);
if (encodedPoint != NULL)
OPENSSL_free(encodedPoint);
if (clnt_ecdh != NULL)
EC_KEY_free(clnt_ecdh);
EVP_PKEY_free(srvr_pub_pkey);
#endif
s->state = SSL_ST_ERR;
return (-1);
}
int ssl3_send_client_verify(SSL *s)
{
unsigned char *p;
unsigned char data[MD5_DIGEST_LENGTH + SHA_DIGEST_LENGTH];
EVP_PKEY *pkey;
EVP_PKEY_CTX *pctx = NULL;
EVP_MD_CTX mctx;
unsigned u = 0;
unsigned long n;
int j;
EVP_MD_CTX_init(&mctx);
if (s->state == SSL3_ST_CW_CERT_VRFY_A) {
p = ssl_handshake_start(s);
pkey = s->cert->key->privatekey;
/* Create context from key and test if sha1 is allowed as digest */
pctx = EVP_PKEY_CTX_new(pkey, NULL);
if (pctx == NULL || EVP_PKEY_sign_init(pctx) <= 0) {
SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY, ERR_R_INTERNAL_ERROR);
goto err;
}
if (EVP_PKEY_CTX_set_signature_md(pctx, EVP_sha1()) > 0) {
if (!SSL_USE_SIGALGS(s))
s->method->ssl3_enc->cert_verify_mac(s,
NID_sha1,
&(data
[MD5_DIGEST_LENGTH]));
} else {
ERR_clear_error();
}
/*
* For TLS v1.2 send signature algorithm and signature using agreed
* digest and cached handshake records.
*/
if (SSL_USE_SIGALGS(s)) {
long hdatalen = 0;
void *hdata;
const EVP_MD *md = s->cert->key->digest;
hdatalen = BIO_get_mem_data(s->s3->handshake_buffer, &hdata);
if (hdatalen <= 0 || !tls12_get_sigandhash(p, pkey, md)) {
SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY, ERR_R_INTERNAL_ERROR);
goto err;
}
p += 2;
#ifdef SSL_DEBUG
fprintf(stderr, "Using TLS 1.2 with client alg %s\n",
EVP_MD_name(md));
#endif
if (!EVP_SignInit_ex(&mctx, md, NULL)
|| !EVP_SignUpdate(&mctx, hdata, hdatalen)
|| !EVP_SignFinal(&mctx, p + 2, &u, pkey)) {
SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY, ERR_R_EVP_LIB);
goto err;
}
s2n(u, p);
n = u + 4;
if (!ssl3_digest_cached_records(s))
goto err;
} else
#ifndef OPENSSL_NO_RSA
if (pkey->type == EVP_PKEY_RSA) {
s->method->ssl3_enc->cert_verify_mac(s, NID_md5, &(data[0]));
if (RSA_sign(NID_md5_sha1, data,
MD5_DIGEST_LENGTH + SHA_DIGEST_LENGTH,
&(p[2]), &u, pkey->pkey.rsa) <= 0) {
SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY, ERR_R_RSA_LIB);
goto err;
}
s2n(u, p);
n = u + 2;
} else
#endif
#ifndef OPENSSL_NO_DSA
if (pkey->type == EVP_PKEY_DSA) {
if (!DSA_sign(pkey->save_type,
&(data[MD5_DIGEST_LENGTH]),
SHA_DIGEST_LENGTH, &(p[2]),
(unsigned int *)&j, pkey->pkey.dsa)) {
SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY, ERR_R_DSA_LIB);
goto err;
}
s2n(j, p);
n = j + 2;
} else
#endif
#ifndef OPENSSL_NO_ECDSA
if (pkey->type == EVP_PKEY_EC) {
if (!ECDSA_sign(pkey->save_type,
&(data[MD5_DIGEST_LENGTH]),
SHA_DIGEST_LENGTH, &(p[2]),
(unsigned int *)&j, pkey->pkey.ec)) {
SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY, ERR_R_ECDSA_LIB);
goto err;
}
s2n(j, p);
n = j + 2;
} else
#endif
if (pkey->type == NID_id_GostR3410_94
|| pkey->type == NID_id_GostR3410_2001) {
unsigned char signbuf[64];
int i;
size_t sigsize = 64;
s->method->ssl3_enc->cert_verify_mac(s,
NID_id_GostR3411_94, data);
if (EVP_PKEY_sign(pctx, signbuf, &sigsize, data, 32) <= 0) {
SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY, ERR_R_INTERNAL_ERROR);
goto err;
}
for (i = 63, j = 0; i >= 0; j++, i--) {
p[2 + j] = signbuf[i];
}
s2n(j, p);
n = j + 2;
} else {
SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY, ERR_R_INTERNAL_ERROR);
goto err;
}
ssl_set_handshake_header(s, SSL3_MT_CERTIFICATE_VERIFY, n);
s->state = SSL3_ST_CW_CERT_VRFY_B;
}
EVP_MD_CTX_cleanup(&mctx);
EVP_PKEY_CTX_free(pctx);
return ssl_do_write(s);
err:
EVP_MD_CTX_cleanup(&mctx);
EVP_PKEY_CTX_free(pctx);
s->state = SSL_ST_ERR;
return (-1);
}
/*
* Check a certificate can be used for client authentication. Currently check
* cert exists, if we have a suitable digest for TLS 1.2 if static DH client
* certificates can be used and optionally checks suitability for Suite B.
*/
static int ssl3_check_client_certificate(SSL *s)
{
unsigned long alg_k;
if (!s->cert || !s->cert->key->x509 || !s->cert->key->privatekey)
return 0;
/* If no suitable signature algorithm can't use certificate */
if (SSL_USE_SIGALGS(s) && !s->cert->key->digest)
return 0;
/*
* If strict mode check suitability of chain before using it. This also
* adjusts suite B digest if necessary.
*/
if (s->cert->cert_flags & SSL_CERT_FLAGS_CHECK_TLS_STRICT &&
!tls1_check_chain(s, NULL, NULL, NULL, -2))
return 0;
alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
/* See if we can use client certificate for fixed DH */
if (alg_k & (SSL_kDHr | SSL_kDHd)) {
SESS_CERT *scert = s->session->sess_cert;
int i = scert->peer_cert_type;
EVP_PKEY *clkey = NULL, *spkey = NULL;
clkey = s->cert->key->privatekey;
/* If client key not DH assume it can be used */
if (EVP_PKEY_id(clkey) != EVP_PKEY_DH)
return 1;
if (i >= 0)
spkey = X509_get_pubkey(scert->peer_pkeys[i].x509);
if (spkey) {
/* Compare server and client parameters */
i = EVP_PKEY_cmp_parameters(clkey, spkey);
EVP_PKEY_free(spkey);
if (i != 1)
return 0;
}
s->s3->flags |= TLS1_FLAGS_SKIP_CERT_VERIFY;
}
return 1;
}
int ssl3_send_client_certificate(SSL *s)
{
X509 *x509 = NULL;
EVP_PKEY *pkey = NULL;
int i;
if (s->state == SSL3_ST_CW_CERT_A) {
/* Let cert callback update client certificates if required */
if (s->cert->cert_cb) {
i = s->cert->cert_cb(s, s->cert->cert_cb_arg);
if (i < 0) {
s->rwstate = SSL_X509_LOOKUP;
return -1;
}
if (i == 0) {
ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
s->state = SSL_ST_ERR;
return 0;
}
s->rwstate = SSL_NOTHING;
}
if (ssl3_check_client_certificate(s))
s->state = SSL3_ST_CW_CERT_C;
else
s->state = SSL3_ST_CW_CERT_B;
}
/* We need to get a client cert */
if (s->state == SSL3_ST_CW_CERT_B) {
/*
* If we get an error, we need to ssl->rwstate=SSL_X509_LOOKUP;
* return(-1); We then get retied later
*/
i = ssl_do_client_cert_cb(s, &x509, &pkey);
if (i < 0) {
s->rwstate = SSL_X509_LOOKUP;
return (-1);
}
s->rwstate = SSL_NOTHING;
if ((i == 1) && (pkey != NULL) && (x509 != NULL)) {
s->state = SSL3_ST_CW_CERT_B;
if (!SSL_use_certificate(s, x509) || !SSL_use_PrivateKey(s, pkey))
i = 0;
} else if (i == 1) {
i = 0;
SSLerr(SSL_F_SSL3_SEND_CLIENT_CERTIFICATE,
SSL_R_BAD_DATA_RETURNED_BY_CALLBACK);
}
if (x509 != NULL)
X509_free(x509);
if (pkey != NULL)
EVP_PKEY_free(pkey);
if (i && !ssl3_check_client_certificate(s))
i = 0;
if (i == 0) {
if (s->version == SSL3_VERSION) {
s->s3->tmp.cert_req = 0;
ssl3_send_alert(s, SSL3_AL_WARNING, SSL_AD_NO_CERTIFICATE);
return (1);
} else {
s->s3->tmp.cert_req = 2;
}
}
/* Ok, we have a cert */
s->state = SSL3_ST_CW_CERT_C;
}
if (s->state == SSL3_ST_CW_CERT_C) {
s->state = SSL3_ST_CW_CERT_D;
if (!ssl3_output_cert_chain(s,
(s->s3->tmp.cert_req ==
2) ? NULL : s->cert->key)) {
SSLerr(SSL_F_SSL3_SEND_CLIENT_CERTIFICATE, ERR_R_INTERNAL_ERROR);
ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
s->state = SSL_ST_ERR;
return 0;
}
}
/* SSL3_ST_CW_CERT_D */
return ssl_do_write(s);
}
#define has_bits(i,m) (((i)&(m)) == (m))
int ssl3_check_cert_and_algorithm(SSL *s)
{
int i, idx;
long alg_k, alg_a;
EVP_PKEY *pkey = NULL;
int pkey_bits;
SESS_CERT *sc;
#ifndef OPENSSL_NO_RSA
RSA *rsa;
#endif
#ifndef OPENSSL_NO_DH
DH *dh;
#endif
int al = SSL_AD_HANDSHAKE_FAILURE;
alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
alg_a = s->s3->tmp.new_cipher->algorithm_auth;
/* we don't have a certificate */
if ((alg_a & (SSL_aNULL | SSL_aKRB5)) || (alg_k & SSL_kPSK))
return (1);
sc = s->session->sess_cert;
if (sc == NULL) {
SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM, ERR_R_INTERNAL_ERROR);
goto err;
}
#ifndef OPENSSL_NO_RSA
rsa = s->session->sess_cert->peer_rsa_tmp;
#endif
#ifndef OPENSSL_NO_DH
dh = s->session->sess_cert->peer_dh_tmp;
#endif
/* This is the passed certificate */
idx = sc->peer_cert_type;
#ifndef OPENSSL_NO_ECDH
if (idx == SSL_PKEY_ECC) {
if (ssl_check_srvr_ecc_cert_and_alg(sc->peer_pkeys[idx].x509, s) == 0) {
/* check failed */
SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM, SSL_R_BAD_ECC_CERT);
goto f_err;
} else {
return 1;
}
} else if (alg_a & SSL_aECDSA) {
SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,
SSL_R_MISSING_ECDSA_SIGNING_CERT);
goto f_err;
} else if (alg_k & (SSL_kECDHr | SSL_kECDHe)) {
SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM, SSL_R_MISSING_ECDH_CERT);
goto f_err;
}
#endif
pkey = X509_get_pubkey(sc->peer_pkeys[idx].x509);
pkey_bits = EVP_PKEY_bits(pkey);
i = X509_certificate_type(sc->peer_pkeys[idx].x509, pkey);
EVP_PKEY_free(pkey);
/* Check that we have a certificate if we require one */
if ((alg_a & SSL_aRSA) && !has_bits(i, EVP_PK_RSA | EVP_PKT_SIGN)) {
SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,
SSL_R_MISSING_RSA_SIGNING_CERT);
goto f_err;
}
#ifndef OPENSSL_NO_DSA
else if ((alg_a & SSL_aDSS) && !has_bits(i, EVP_PK_DSA | EVP_PKT_SIGN)) {
SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,
SSL_R_MISSING_DSA_SIGNING_CERT);
goto f_err;
}
#endif
#ifndef OPENSSL_NO_RSA
if (alg_k & SSL_kRSA) {
if (!SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) &&
!has_bits(i, EVP_PK_RSA | EVP_PKT_ENC)) {
SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,
SSL_R_MISSING_RSA_ENCRYPTING_CERT);
goto f_err;
} else if (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher)) {
if (pkey_bits <= SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher)) {
if (!has_bits(i, EVP_PK_RSA | EVP_PKT_ENC)) {
SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,
SSL_R_MISSING_RSA_ENCRYPTING_CERT);
goto f_err;
}
if (rsa != NULL) {
/* server key exchange is not allowed. */
al = SSL_AD_INTERNAL_ERROR;
SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM, ERR_R_INTERNAL_ERROR);
goto f_err;
}
}
}
}
#endif
#ifndef OPENSSL_NO_DH
if ((alg_k & SSL_kEDH) && dh == NULL) {
al = SSL_AD_INTERNAL_ERROR;
SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM, ERR_R_INTERNAL_ERROR);
goto f_err;
}
if ((alg_k & SSL_kDHr) && !SSL_USE_SIGALGS(s) &&
!has_bits(i, EVP_PK_DH | EVP_PKS_RSA)) {
SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,
SSL_R_MISSING_DH_RSA_CERT);
goto f_err;
}
# ifndef OPENSSL_NO_DSA
if ((alg_k & SSL_kDHd) && !SSL_USE_SIGALGS(s) &&
!has_bits(i, EVP_PK_DH | EVP_PKS_DSA)) {
SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,
SSL_R_MISSING_DH_DSA_CERT);
goto f_err;
}
# endif
if (alg_k & (SSL_kDHE | SSL_kDHr | SSL_kDHd)) {
int dh_size;
if (alg_k & SSL_kDHE) {
dh_size = BN_num_bits(dh->p);
} else {
DH *dh_srvr = get_server_static_dh_key(sc);
if (dh_srvr == NULL)
goto f_err;
dh_size = BN_num_bits(dh_srvr->p);
DH_free(dh_srvr);
}
if ((!SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) && dh_size < 1024)
|| (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) && dh_size < 512)) {
SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM, SSL_R_DH_KEY_TOO_SMALL);
goto f_err;
}
}
#endif /* !OPENSSL_NO_DH */
if (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) &&
pkey_bits > SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher)) {
#ifndef OPENSSL_NO_RSA
if (alg_k & SSL_kRSA) {
if (rsa == NULL) {
SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,
SSL_R_MISSING_EXPORT_TMP_RSA_KEY);
goto f_err;
} else if (BN_num_bits(rsa->n) >
SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher)) {
/* We have a temporary RSA key but it's too large. */
al = SSL_AD_EXPORT_RESTRICTION;
SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,
SSL_R_MISSING_EXPORT_TMP_RSA_KEY);
goto f_err;
}
} else
#endif
#ifndef OPENSSL_NO_DH
if (alg_k & SSL_kDHE) {
if (BN_num_bits(dh->p) >
SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher)) {
/* We have a temporary DH key but it's too large. */
al = SSL_AD_EXPORT_RESTRICTION;
SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,
SSL_R_MISSING_EXPORT_TMP_DH_KEY);
goto f_err;
}
} else if (alg_k & (SSL_kDHr | SSL_kDHd)) {
/* The cert should have had an export DH key. */
al = SSL_AD_EXPORT_RESTRICTION;
SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,
SSL_R_MISSING_EXPORT_TMP_DH_KEY);
goto f_err;
} else
#endif
{
SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,
SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE);
goto f_err;
}
}
return (1);
f_err:
ssl3_send_alert(s, SSL3_AL_FATAL, al);
err:
return (0);
}
#ifndef OPENSSL_NO_TLSEXT
/*
* Normally, we can tell if the server is resuming the session from
* the session ID. EAP-FAST (RFC 4851), however, relies on the next server
* message after the ServerHello to determine if the server is resuming.
* Therefore, we allow EAP-FAST to peek ahead.
* ssl3_check_finished returns 1 if we are resuming from an external
* pre-shared secret, we have a "ticket" and the next server handshake message
* is Finished; and 0 otherwise. It returns -1 upon an error.
*/
static int ssl3_check_finished(SSL *s)
{
int ok = 0;
if (s->version < TLS1_VERSION || !s->tls_session_secret_cb ||
!s->session->tlsext_tick)
return 0;
/* Need to permit this temporarily, in case the next message is Finished. */
s->s3->flags |= SSL3_FLAGS_CCS_OK;
/*
* This function is called when we might get a Certificate message instead,
* so permit appropriate message length.
* We ignore the return value as we're only interested in the message type
* and not its length.
*/
s->method->ssl_get_message(s,
SSL3_ST_CR_CERT_A,
SSL3_ST_CR_CERT_B,
-1, s->max_cert_list, &ok);
s->s3->flags &= ~SSL3_FLAGS_CCS_OK;
if (!ok)
return -1;
s->s3->tmp.reuse_message = 1;
if (s->s3->tmp.message_type == SSL3_MT_FINISHED)
return 1;
/* If we're not done, then the CCS arrived early and we should bail. */
if (s->s3->change_cipher_spec) {
SSLerr(SSL_F_SSL3_CHECK_FINISHED, SSL_R_CCS_RECEIVED_EARLY);
ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
return -1;
}
return 0;
}
# ifndef OPENSSL_NO_NEXTPROTONEG
int ssl3_send_next_proto(SSL *s)
{
unsigned int len, padding_len;
unsigned char *d;
if (s->state == SSL3_ST_CW_NEXT_PROTO_A) {
len = s->next_proto_negotiated_len;
padding_len = 32 - ((len + 2) % 32);
d = (unsigned char *)s->init_buf->data;
d[4] = len;
memcpy(d + 5, s->next_proto_negotiated, len);
d[5 + len] = padding_len;
memset(d + 6 + len, 0, padding_len);
*(d++) = SSL3_MT_NEXT_PROTO;
l2n3(2 + len + padding_len, d);
s->state = SSL3_ST_CW_NEXT_PROTO_B;
s->init_num = 4 + 2 + len + padding_len;
s->init_off = 0;
}
return ssl3_do_write(s, SSL3_RT_HANDSHAKE);
}
#endif /* !OPENSSL_NO_NEXTPROTONEG */
#endif /* !OPENSSL_NO_TLSEXT */
int ssl_do_client_cert_cb(SSL *s, X509 **px509, EVP_PKEY **ppkey)
{
int i = 0;
#ifndef OPENSSL_NO_ENGINE
if (s->ctx->client_cert_engine) {
i = ENGINE_load_ssl_client_cert(s->ctx->client_cert_engine, s,
SSL_get_client_CA_list(s),
px509, ppkey, NULL, NULL, NULL);
if (i != 0)
return i;
}
#endif
if (s->ctx->client_cert_cb)
i = s->ctx->client_cert_cb(s, px509, ppkey);
return i;
}
diff --git a/ssl/s3_lib.c b/ssl/s3_lib.c
index 1014a3fce16f..7e27dae35b0c 100644
--- a/ssl/s3_lib.c
+++ b/ssl/s3_lib.c
@@ -1,4539 +1,4539 @@
/* ssl/s3_lib.c */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
/* ====================================================================
* Copyright (c) 1998-2007 The OpenSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* openssl-core@openssl.org.
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.openssl.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*
* This product includes cryptographic software written by Eric Young
* (eay@cryptsoft.com). This product includes software written by Tim
* Hudson (tjh@cryptsoft.com).
*
*/
/* ====================================================================
* Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
*
* Portions of the attached software ("Contribution") are developed by
* SUN MICROSYSTEMS, INC., and are contributed to the OpenSSL project.
*
* The Contribution is licensed pursuant to the OpenSSL open source
* license provided above.
*
* ECC cipher suite support in OpenSSL originally written by
* Vipul Gupta and Sumit Gupta of Sun Microsystems Laboratories.
*
*/
/* ====================================================================
* Copyright 2005 Nokia. All rights reserved.
*
* The portions of the attached software ("Contribution") is developed by
* Nokia Corporation and is licensed pursuant to the OpenSSL open source
* license.
*
* The Contribution, originally written by Mika Kousa and Pasi Eronen of
* Nokia Corporation, consists of the "PSK" (Pre-Shared Key) ciphersuites
* support (see RFC 4279) to OpenSSL.
*
* No patent licenses or other rights except those expressly stated in
* the OpenSSL open source license shall be deemed granted or received
* expressly, by implication, estoppel, or otherwise.
*
* No assurances are provided by Nokia that the Contribution does not
* infringe the patent or other intellectual property rights of any third
* party or that the license provides you with all the necessary rights
* to make use of the Contribution.
*
* THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. IN
* ADDITION TO THE DISCLAIMERS INCLUDED IN THE LICENSE, NOKIA
* SPECIFICALLY DISCLAIMS ANY LIABILITY FOR CLAIMS BROUGHT BY YOU OR ANY
* OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS OR
* OTHERWISE.
*/
#include <stdio.h>
#include <openssl/objects.h>
#include "ssl_locl.h"
#include "kssl_lcl.h"
#include <openssl/md5.h>
#ifndef OPENSSL_NO_DH
# include <openssl/dh.h>
#endif
const char ssl3_version_str[] = "SSLv3" OPENSSL_VERSION_PTEXT;
#define SSL3_NUM_CIPHERS (sizeof(ssl3_ciphers)/sizeof(SSL_CIPHER))
/* list of available SSLv3 ciphers (sorted by id) */
OPENSSL_GLOBAL SSL_CIPHER ssl3_ciphers[] = {
/* The RSA ciphers */
/* Cipher 01 */
{
1,
SSL3_TXT_RSA_NULL_MD5,
SSL3_CK_RSA_NULL_MD5,
SSL_kRSA,
SSL_aRSA,
SSL_eNULL,
SSL_MD5,
SSL_SSLV3,
SSL_NOT_EXP | SSL_STRONG_NONE,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
0,
0,
},
/* Cipher 02 */
{
1,
SSL3_TXT_RSA_NULL_SHA,
SSL3_CK_RSA_NULL_SHA,
SSL_kRSA,
SSL_aRSA,
SSL_eNULL,
SSL_SHA1,
SSL_SSLV3,
SSL_NOT_EXP | SSL_STRONG_NONE | SSL_FIPS,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
0,
0,
},
/* Cipher 03 */
#ifndef OPENSSL_NO_WEAK_SSL_CIPHERS
{
1,
SSL3_TXT_RSA_RC4_40_MD5,
SSL3_CK_RSA_RC4_40_MD5,
SSL_kRSA,
SSL_aRSA,
SSL_RC4,
SSL_MD5,
SSL_SSLV3,
SSL_NOT_DEFAULT | SSL_EXPORT | SSL_EXP40,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
40,
128,
},
#endif
/* Cipher 04 */
{
1,
SSL3_TXT_RSA_RC4_128_MD5,
SSL3_CK_RSA_RC4_128_MD5,
SSL_kRSA,
SSL_aRSA,
SSL_RC4,
SSL_MD5,
SSL_SSLV3,
SSL_NOT_EXP | SSL_MEDIUM,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
128,
128,
},
/* Cipher 05 */
{
1,
SSL3_TXT_RSA_RC4_128_SHA,
SSL3_CK_RSA_RC4_128_SHA,
SSL_kRSA,
SSL_aRSA,
SSL_RC4,
SSL_SHA1,
SSL_SSLV3,
SSL_NOT_EXP | SSL_MEDIUM,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
128,
128,
},
/* Cipher 06 */
#ifndef OPENSSL_NO_WEAK_SSL_CIPHERS
{
1,
SSL3_TXT_RSA_RC2_40_MD5,
SSL3_CK_RSA_RC2_40_MD5,
SSL_kRSA,
SSL_aRSA,
SSL_RC2,
SSL_MD5,
SSL_SSLV3,
SSL_NOT_DEFAULT | SSL_EXPORT | SSL_EXP40,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
40,
128,
},
#endif
/* Cipher 07 */
#ifndef OPENSSL_NO_IDEA
{
1,
SSL3_TXT_RSA_IDEA_128_SHA,
SSL3_CK_RSA_IDEA_128_SHA,
SSL_kRSA,
SSL_aRSA,
SSL_IDEA,
SSL_SHA1,
SSL_SSLV3,
SSL_NOT_EXP | SSL_MEDIUM,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
128,
128,
},
#endif
/* Cipher 08 */
#ifndef OPENSSL_NO_WEAK_SSL_CIPHERS
{
1,
SSL3_TXT_RSA_DES_40_CBC_SHA,
SSL3_CK_RSA_DES_40_CBC_SHA,
SSL_kRSA,
SSL_aRSA,
SSL_DES,
SSL_SHA1,
SSL_SSLV3,
SSL_NOT_DEFAULT | SSL_EXPORT | SSL_EXP40,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
40,
56,
},
#endif
/* Cipher 09 */
#ifndef OPENSSL_NO_WEAK_SSL_CIPHERS
{
1,
SSL3_TXT_RSA_DES_64_CBC_SHA,
SSL3_CK_RSA_DES_64_CBC_SHA,
SSL_kRSA,
SSL_aRSA,
SSL_DES,
SSL_SHA1,
SSL_SSLV3,
SSL_NOT_DEFAULT | SSL_NOT_EXP | SSL_LOW,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
56,
56,
},
#endif
/* Cipher 0A */
{
1,
SSL3_TXT_RSA_DES_192_CBC3_SHA,
SSL3_CK_RSA_DES_192_CBC3_SHA,
SSL_kRSA,
SSL_aRSA,
SSL_3DES,
SSL_SHA1,
SSL_SSLV3,
SSL_NOT_EXP | SSL_MEDIUM | SSL_FIPS,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
112,
168,
},
/* The DH ciphers */
/* Cipher 0B */
#ifndef OPENSSL_NO_WEAK_SSL_CIPHERS
{
0,
SSL3_TXT_DH_DSS_DES_40_CBC_SHA,
SSL3_CK_DH_DSS_DES_40_CBC_SHA,
SSL_kDHd,
SSL_aDH,
SSL_DES,
SSL_SHA1,
SSL_SSLV3,
SSL_NOT_DEFAULT | SSL_EXPORT | SSL_EXP40,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
40,
56,
},
#endif
/* Cipher 0C */
#ifndef OPENSSL_NO_WEAK_SSL_CIPHERS
{
1,
SSL3_TXT_DH_DSS_DES_64_CBC_SHA,
SSL3_CK_DH_DSS_DES_64_CBC_SHA,
SSL_kDHd,
SSL_aDH,
SSL_DES,
SSL_SHA1,
SSL_SSLV3,
SSL_NOT_DEFAULT | SSL_NOT_EXP | SSL_LOW,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
56,
56,
},
#endif
/* Cipher 0D */
{
1,
SSL3_TXT_DH_DSS_DES_192_CBC3_SHA,
SSL3_CK_DH_DSS_DES_192_CBC3_SHA,
SSL_kDHd,
SSL_aDH,
SSL_3DES,
SSL_SHA1,
SSL_SSLV3,
SSL_NOT_EXP | SSL_MEDIUM | SSL_FIPS,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
112,
168,
},
/* Cipher 0E */
#ifndef OPENSSL_NO_WEAK_SSL_CIPHERS
{
0,
SSL3_TXT_DH_RSA_DES_40_CBC_SHA,
SSL3_CK_DH_RSA_DES_40_CBC_SHA,
SSL_kDHr,
SSL_aDH,
SSL_DES,
SSL_SHA1,
SSL_SSLV3,
SSL_NOT_DEFAULT | SSL_EXPORT | SSL_EXP40,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
40,
56,
},
#endif
/* Cipher 0F */
#ifndef OPENSSL_NO_WEAK_SSL_CIPHERS
{
1,
SSL3_TXT_DH_RSA_DES_64_CBC_SHA,
SSL3_CK_DH_RSA_DES_64_CBC_SHA,
SSL_kDHr,
SSL_aDH,
SSL_DES,
SSL_SHA1,
SSL_SSLV3,
SSL_NOT_DEFAULT | SSL_NOT_EXP | SSL_LOW,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
56,
56,
},
#endif
/* Cipher 10 */
{
1,
SSL3_TXT_DH_RSA_DES_192_CBC3_SHA,
SSL3_CK_DH_RSA_DES_192_CBC3_SHA,
SSL_kDHr,
SSL_aDH,
SSL_3DES,
SSL_SHA1,
SSL_SSLV3,
SSL_NOT_EXP | SSL_MEDIUM | SSL_FIPS,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
112,
168,
},
/* The Ephemeral DH ciphers */
/* Cipher 11 */
#ifndef OPENSSL_NO_WEAK_SSL_CIPHERS
{
1,
SSL3_TXT_EDH_DSS_DES_40_CBC_SHA,
SSL3_CK_EDH_DSS_DES_40_CBC_SHA,
SSL_kEDH,
SSL_aDSS,
SSL_DES,
SSL_SHA1,
SSL_SSLV3,
SSL_NOT_DEFAULT | SSL_EXPORT | SSL_EXP40,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
40,
56,
},
#endif
/* Cipher 12 */
#ifndef OPENSSL_NO_WEAK_SSL_CIPHERS
{
1,
SSL3_TXT_EDH_DSS_DES_64_CBC_SHA,
SSL3_CK_EDH_DSS_DES_64_CBC_SHA,
SSL_kEDH,
SSL_aDSS,
SSL_DES,
SSL_SHA1,
SSL_SSLV3,
SSL_NOT_DEFAULT | SSL_NOT_EXP | SSL_LOW,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
56,
56,
},
#endif
/* Cipher 13 */
{
1,
SSL3_TXT_EDH_DSS_DES_192_CBC3_SHA,
SSL3_CK_EDH_DSS_DES_192_CBC3_SHA,
SSL_kEDH,
SSL_aDSS,
SSL_3DES,
SSL_SHA1,
SSL_SSLV3,
SSL_NOT_EXP | SSL_MEDIUM | SSL_FIPS,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
112,
168,
},
/* Cipher 14 */
#ifndef OPENSSL_NO_WEAK_SSL_CIPHERS
{
1,
SSL3_TXT_EDH_RSA_DES_40_CBC_SHA,
SSL3_CK_EDH_RSA_DES_40_CBC_SHA,
SSL_kEDH,
SSL_aRSA,
SSL_DES,
SSL_SHA1,
SSL_SSLV3,
SSL_NOT_DEFAULT | SSL_EXPORT | SSL_EXP40,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
40,
56,
},
#endif
/* Cipher 15 */
#ifndef OPENSSL_NO_WEAK_SSL_CIPHERS
{
1,
SSL3_TXT_EDH_RSA_DES_64_CBC_SHA,
SSL3_CK_EDH_RSA_DES_64_CBC_SHA,
SSL_kEDH,
SSL_aRSA,
SSL_DES,
SSL_SHA1,
SSL_SSLV3,
SSL_NOT_DEFAULT | SSL_NOT_EXP | SSL_LOW,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
56,
56,
},
#endif
/* Cipher 16 */
{
1,
SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA,
SSL3_CK_EDH_RSA_DES_192_CBC3_SHA,
SSL_kEDH,
SSL_aRSA,
SSL_3DES,
SSL_SHA1,
SSL_SSLV3,
SSL_NOT_EXP | SSL_MEDIUM | SSL_FIPS,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
112,
168,
},
/* Cipher 17 */
#ifndef OPENSSL_NO_WEAK_SSL_CIPHERS
{
1,
SSL3_TXT_ADH_RC4_40_MD5,
SSL3_CK_ADH_RC4_40_MD5,
SSL_kEDH,
SSL_aNULL,
SSL_RC4,
SSL_MD5,
SSL_SSLV3,
SSL_NOT_DEFAULT | SSL_EXPORT | SSL_EXP40,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
40,
128,
},
#endif
/* Cipher 18 */
{
1,
SSL3_TXT_ADH_RC4_128_MD5,
SSL3_CK_ADH_RC4_128_MD5,
SSL_kEDH,
SSL_aNULL,
SSL_RC4,
SSL_MD5,
SSL_SSLV3,
SSL_NOT_DEFAULT | SSL_NOT_EXP | SSL_MEDIUM,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
128,
128,
},
/* Cipher 19 */
#ifndef OPENSSL_NO_WEAK_SSL_CIPHERS
{
1,
SSL3_TXT_ADH_DES_40_CBC_SHA,
SSL3_CK_ADH_DES_40_CBC_SHA,
SSL_kEDH,
SSL_aNULL,
SSL_DES,
SSL_SHA1,
SSL_SSLV3,
SSL_NOT_DEFAULT | SSL_EXPORT | SSL_EXP40,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
40,
128,
},
#endif
/* Cipher 1A */
#ifndef OPENSSL_NO_WEAK_SSL_CIPHERS
{
1,
SSL3_TXT_ADH_DES_64_CBC_SHA,
SSL3_CK_ADH_DES_64_CBC_SHA,
SSL_kEDH,
SSL_aNULL,
SSL_DES,
SSL_SHA1,
SSL_SSLV3,
SSL_NOT_DEFAULT | SSL_NOT_EXP | SSL_LOW,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
56,
56,
},
#endif
/* Cipher 1B */
{
1,
SSL3_TXT_ADH_DES_192_CBC_SHA,
SSL3_CK_ADH_DES_192_CBC_SHA,
SSL_kEDH,
SSL_aNULL,
SSL_3DES,
SSL_SHA1,
SSL_SSLV3,
SSL_NOT_DEFAULT | SSL_NOT_EXP | SSL_MEDIUM | SSL_FIPS,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
112,
168,
},
/* Fortezza ciphersuite from SSL 3.0 spec */
#if 0
/* Cipher 1C */
{
0,
SSL3_TXT_FZA_DMS_NULL_SHA,
SSL3_CK_FZA_DMS_NULL_SHA,
SSL_kFZA,
SSL_aFZA,
SSL_eNULL,
SSL_SHA1,
SSL_SSLV3,
SSL_NOT_EXP | SSL_STRONG_NONE,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
0,
0,
},
/* Cipher 1D */
{
0,
SSL3_TXT_FZA_DMS_FZA_SHA,
SSL3_CK_FZA_DMS_FZA_SHA,
SSL_kFZA,
SSL_aFZA,
SSL_eFZA,
SSL_SHA1,
SSL_SSLV3,
SSL_NOT_EXP | SSL_STRONG_NONE,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
0,
0,
},
/* Cipher 1E */
{
0,
SSL3_TXT_FZA_DMS_RC4_SHA,
SSL3_CK_FZA_DMS_RC4_SHA,
SSL_kFZA,
SSL_aFZA,
SSL_RC4,
SSL_SHA1,
SSL_SSLV3,
SSL_NOT_EXP | SSL_MEDIUM,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
128,
128,
},
#endif
#ifndef OPENSSL_NO_KRB5
/* The Kerberos ciphers*/
/* Cipher 1E */
# ifndef OPENSSL_NO_WEAK_SSL_CIPHERS
{
1,
SSL3_TXT_KRB5_DES_64_CBC_SHA,
SSL3_CK_KRB5_DES_64_CBC_SHA,
SSL_kKRB5,
SSL_aKRB5,
SSL_DES,
SSL_SHA1,
SSL_SSLV3,
SSL_NOT_DEFAULT | SSL_NOT_EXP | SSL_LOW,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
56,
56,
},
# endif
/* Cipher 1F */
{
1,
SSL3_TXT_KRB5_DES_192_CBC3_SHA,
SSL3_CK_KRB5_DES_192_CBC3_SHA,
SSL_kKRB5,
SSL_aKRB5,
SSL_3DES,
SSL_SHA1,
SSL_SSLV3,
SSL_NOT_EXP | SSL_MEDIUM | SSL_FIPS,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
112,
168,
},
/* Cipher 20 */
{
1,
SSL3_TXT_KRB5_RC4_128_SHA,
SSL3_CK_KRB5_RC4_128_SHA,
SSL_kKRB5,
SSL_aKRB5,
SSL_RC4,
SSL_SHA1,
SSL_SSLV3,
SSL_NOT_EXP | SSL_MEDIUM,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
128,
128,
},
/* Cipher 21 */
{
1,
SSL3_TXT_KRB5_IDEA_128_CBC_SHA,
SSL3_CK_KRB5_IDEA_128_CBC_SHA,
SSL_kKRB5,
SSL_aKRB5,
SSL_IDEA,
SSL_SHA1,
SSL_SSLV3,
SSL_NOT_EXP | SSL_MEDIUM,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
128,
128,
},
/* Cipher 22 */
# ifndef OPENSSL_NO_WEAK_SSL_CIPHERS
{
1,
SSL3_TXT_KRB5_DES_64_CBC_MD5,
SSL3_CK_KRB5_DES_64_CBC_MD5,
SSL_kKRB5,
SSL_aKRB5,
SSL_DES,
SSL_MD5,
SSL_SSLV3,
SSL_NOT_DEFAULT | SSL_NOT_EXP | SSL_LOW,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
56,
56,
},
# endif
/* Cipher 23 */
{
1,
SSL3_TXT_KRB5_DES_192_CBC3_MD5,
SSL3_CK_KRB5_DES_192_CBC3_MD5,
SSL_kKRB5,
SSL_aKRB5,
SSL_3DES,
SSL_MD5,
SSL_SSLV3,
SSL_NOT_EXP | SSL_MEDIUM,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
112,
168,
},
/* Cipher 24 */
{
1,
SSL3_TXT_KRB5_RC4_128_MD5,
SSL3_CK_KRB5_RC4_128_MD5,
SSL_kKRB5,
SSL_aKRB5,
SSL_RC4,
SSL_MD5,
SSL_SSLV3,
SSL_NOT_EXP | SSL_MEDIUM,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
128,
128,
},
/* Cipher 25 */
{
1,
SSL3_TXT_KRB5_IDEA_128_CBC_MD5,
SSL3_CK_KRB5_IDEA_128_CBC_MD5,
SSL_kKRB5,
SSL_aKRB5,
SSL_IDEA,
SSL_MD5,
SSL_SSLV3,
SSL_NOT_EXP | SSL_MEDIUM,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
128,
128,
},
/* Cipher 26 */
# ifndef OPENSSL_NO_WEAK_SSL_CIPHERS
{
1,
SSL3_TXT_KRB5_DES_40_CBC_SHA,
SSL3_CK_KRB5_DES_40_CBC_SHA,
SSL_kKRB5,
SSL_aKRB5,
SSL_DES,
SSL_SHA1,
SSL_SSLV3,
SSL_NOT_DEFAULT | SSL_EXPORT | SSL_EXP40,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
40,
56,
},
# endif
/* Cipher 27 */
# ifndef OPENSSL_NO_WEAK_SSL_CIPHERS
{
1,
SSL3_TXT_KRB5_RC2_40_CBC_SHA,
SSL3_CK_KRB5_RC2_40_CBC_SHA,
SSL_kKRB5,
SSL_aKRB5,
SSL_RC2,
SSL_SHA1,
SSL_SSLV3,
SSL_NOT_DEFAULT | SSL_EXPORT | SSL_EXP40,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
40,
128,
},
# endif
/* Cipher 28 */
# ifndef OPENSSL_NO_WEAK_SSL_CIPHERS
{
1,
SSL3_TXT_KRB5_RC4_40_SHA,
SSL3_CK_KRB5_RC4_40_SHA,
SSL_kKRB5,
SSL_aKRB5,
SSL_RC4,
SSL_SHA1,
SSL_SSLV3,
SSL_NOT_DEFAULT | SSL_EXPORT | SSL_EXP40,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
40,
128,
},
# endif
/* Cipher 29 */
# ifndef OPENSSL_NO_WEAK_SSL_CIPHERS
{
1,
SSL3_TXT_KRB5_DES_40_CBC_MD5,
SSL3_CK_KRB5_DES_40_CBC_MD5,
SSL_kKRB5,
SSL_aKRB5,
SSL_DES,
SSL_MD5,
SSL_SSLV3,
SSL_NOT_DEFAULT | SSL_EXPORT | SSL_EXP40,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
40,
56,
},
# endif
/* Cipher 2A */
# ifndef OPENSSL_NO_WEAK_SSL_CIPHERS
{
1,
SSL3_TXT_KRB5_RC2_40_CBC_MD5,
SSL3_CK_KRB5_RC2_40_CBC_MD5,
SSL_kKRB5,
SSL_aKRB5,
SSL_RC2,
SSL_MD5,
SSL_SSLV3,
SSL_NOT_DEFAULT | SSL_EXPORT | SSL_EXP40,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
40,
128,
},
# endif
/* Cipher 2B */
# ifndef OPENSSL_NO_WEAK_SSL_CIPHERS
{
1,
SSL3_TXT_KRB5_RC4_40_MD5,
SSL3_CK_KRB5_RC4_40_MD5,
SSL_kKRB5,
SSL_aKRB5,
SSL_RC4,
SSL_MD5,
SSL_SSLV3,
SSL_NOT_DEFAULT | SSL_EXPORT | SSL_EXP40,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
40,
128,
},
# endif
#endif /* OPENSSL_NO_KRB5 */
/* New AES ciphersuites */
/* Cipher 2F */
{
1,
TLS1_TXT_RSA_WITH_AES_128_SHA,
TLS1_CK_RSA_WITH_AES_128_SHA,
SSL_kRSA,
SSL_aRSA,
SSL_AES128,
SSL_SHA1,
SSL_TLSV1,
SSL_NOT_EXP | SSL_HIGH | SSL_FIPS,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
128,
128,
},
/* Cipher 30 */
{
1,
TLS1_TXT_DH_DSS_WITH_AES_128_SHA,
TLS1_CK_DH_DSS_WITH_AES_128_SHA,
SSL_kDHd,
SSL_aDH,
SSL_AES128,
SSL_SHA1,
SSL_TLSV1,
SSL_NOT_EXP | SSL_HIGH | SSL_FIPS,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
128,
128,
},
/* Cipher 31 */
{
1,
TLS1_TXT_DH_RSA_WITH_AES_128_SHA,
TLS1_CK_DH_RSA_WITH_AES_128_SHA,
SSL_kDHr,
SSL_aDH,
SSL_AES128,
SSL_SHA1,
SSL_TLSV1,
SSL_NOT_EXP | SSL_HIGH | SSL_FIPS,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
128,
128,
},
/* Cipher 32 */
{
1,
TLS1_TXT_DHE_DSS_WITH_AES_128_SHA,
TLS1_CK_DHE_DSS_WITH_AES_128_SHA,
SSL_kEDH,
SSL_aDSS,
SSL_AES128,
SSL_SHA1,
SSL_TLSV1,
SSL_NOT_EXP | SSL_HIGH | SSL_FIPS,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
128,
128,
},
/* Cipher 33 */
{
1,
TLS1_TXT_DHE_RSA_WITH_AES_128_SHA,
TLS1_CK_DHE_RSA_WITH_AES_128_SHA,
SSL_kEDH,
SSL_aRSA,
SSL_AES128,
SSL_SHA1,
SSL_TLSV1,
SSL_NOT_EXP | SSL_HIGH | SSL_FIPS,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
128,
128,
},
/* Cipher 34 */
{
1,
TLS1_TXT_ADH_WITH_AES_128_SHA,
TLS1_CK_ADH_WITH_AES_128_SHA,
SSL_kEDH,
SSL_aNULL,
SSL_AES128,
SSL_SHA1,
SSL_TLSV1,
SSL_NOT_DEFAULT | SSL_NOT_EXP | SSL_HIGH | SSL_FIPS,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
128,
128,
},
/* Cipher 35 */
{
1,
TLS1_TXT_RSA_WITH_AES_256_SHA,
TLS1_CK_RSA_WITH_AES_256_SHA,
SSL_kRSA,
SSL_aRSA,
SSL_AES256,
SSL_SHA1,
SSL_TLSV1,
SSL_NOT_EXP | SSL_HIGH | SSL_FIPS,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
256,
256,
},
/* Cipher 36 */
{
1,
TLS1_TXT_DH_DSS_WITH_AES_256_SHA,
TLS1_CK_DH_DSS_WITH_AES_256_SHA,
SSL_kDHd,
SSL_aDH,
SSL_AES256,
SSL_SHA1,
SSL_TLSV1,
SSL_NOT_EXP | SSL_HIGH | SSL_FIPS,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
256,
256,
},
/* Cipher 37 */
{
1,
TLS1_TXT_DH_RSA_WITH_AES_256_SHA,
TLS1_CK_DH_RSA_WITH_AES_256_SHA,
SSL_kDHr,
SSL_aDH,
SSL_AES256,
SSL_SHA1,
SSL_TLSV1,
SSL_NOT_EXP | SSL_HIGH | SSL_FIPS,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
256,
256,
},
/* Cipher 38 */
{
1,
TLS1_TXT_DHE_DSS_WITH_AES_256_SHA,
TLS1_CK_DHE_DSS_WITH_AES_256_SHA,
SSL_kEDH,
SSL_aDSS,
SSL_AES256,
SSL_SHA1,
SSL_TLSV1,
SSL_NOT_EXP | SSL_HIGH | SSL_FIPS,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
256,
256,
},
/* Cipher 39 */
{
1,
TLS1_TXT_DHE_RSA_WITH_AES_256_SHA,
TLS1_CK_DHE_RSA_WITH_AES_256_SHA,
SSL_kEDH,
SSL_aRSA,
SSL_AES256,
SSL_SHA1,
SSL_TLSV1,
SSL_NOT_EXP | SSL_HIGH | SSL_FIPS,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
256,
256,
},
/* Cipher 3A */
{
1,
TLS1_TXT_ADH_WITH_AES_256_SHA,
TLS1_CK_ADH_WITH_AES_256_SHA,
SSL_kEDH,
SSL_aNULL,
SSL_AES256,
SSL_SHA1,
SSL_TLSV1,
SSL_NOT_DEFAULT | SSL_NOT_EXP | SSL_HIGH | SSL_FIPS,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
256,
256,
},
/* TLS v1.2 ciphersuites */
/* Cipher 3B */
{
1,
TLS1_TXT_RSA_WITH_NULL_SHA256,
TLS1_CK_RSA_WITH_NULL_SHA256,
SSL_kRSA,
SSL_aRSA,
SSL_eNULL,
SSL_SHA256,
SSL_TLSV1_2,
SSL_NOT_EXP | SSL_STRONG_NONE | SSL_FIPS,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
0,
0,
},
/* Cipher 3C */
{
1,
TLS1_TXT_RSA_WITH_AES_128_SHA256,
TLS1_CK_RSA_WITH_AES_128_SHA256,
SSL_kRSA,
SSL_aRSA,
SSL_AES128,
SSL_SHA256,
SSL_TLSV1_2,
SSL_NOT_EXP | SSL_HIGH | SSL_FIPS,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
128,
128,
},
/* Cipher 3D */
{
1,
TLS1_TXT_RSA_WITH_AES_256_SHA256,
TLS1_CK_RSA_WITH_AES_256_SHA256,
SSL_kRSA,
SSL_aRSA,
SSL_AES256,
SSL_SHA256,
SSL_TLSV1_2,
SSL_NOT_EXP | SSL_HIGH | SSL_FIPS,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
256,
256,
},
/* Cipher 3E */
{
1,
TLS1_TXT_DH_DSS_WITH_AES_128_SHA256,
TLS1_CK_DH_DSS_WITH_AES_128_SHA256,
SSL_kDHd,
SSL_aDH,
SSL_AES128,
SSL_SHA256,
SSL_TLSV1_2,
SSL_NOT_EXP | SSL_HIGH | SSL_FIPS,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
128,
128,
},
/* Cipher 3F */
{
1,
TLS1_TXT_DH_RSA_WITH_AES_128_SHA256,
TLS1_CK_DH_RSA_WITH_AES_128_SHA256,
SSL_kDHr,
SSL_aDH,
SSL_AES128,
SSL_SHA256,
SSL_TLSV1_2,
SSL_NOT_EXP | SSL_HIGH | SSL_FIPS,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
128,
128,
},
/* Cipher 40 */
{
1,
TLS1_TXT_DHE_DSS_WITH_AES_128_SHA256,
TLS1_CK_DHE_DSS_WITH_AES_128_SHA256,
SSL_kEDH,
SSL_aDSS,
SSL_AES128,
SSL_SHA256,
SSL_TLSV1_2,
SSL_NOT_EXP | SSL_HIGH | SSL_FIPS,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
128,
128,
},
#ifndef OPENSSL_NO_CAMELLIA
/* Camellia ciphersuites from RFC4132 (128-bit portion) */
/* Cipher 41 */
{
1,
TLS1_TXT_RSA_WITH_CAMELLIA_128_CBC_SHA,
TLS1_CK_RSA_WITH_CAMELLIA_128_CBC_SHA,
SSL_kRSA,
SSL_aRSA,
SSL_CAMELLIA128,
SSL_SHA1,
SSL_TLSV1,
SSL_NOT_EXP | SSL_HIGH,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
128,
128,
},
/* Cipher 42 */
{
1,
TLS1_TXT_DH_DSS_WITH_CAMELLIA_128_CBC_SHA,
TLS1_CK_DH_DSS_WITH_CAMELLIA_128_CBC_SHA,
SSL_kDHd,
SSL_aDH,
SSL_CAMELLIA128,
SSL_SHA1,
SSL_TLSV1,
SSL_NOT_EXP | SSL_HIGH,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
128,
128,
},
/* Cipher 43 */
{
1,
TLS1_TXT_DH_RSA_WITH_CAMELLIA_128_CBC_SHA,
TLS1_CK_DH_RSA_WITH_CAMELLIA_128_CBC_SHA,
SSL_kDHr,
SSL_aDH,
SSL_CAMELLIA128,
SSL_SHA1,
SSL_TLSV1,
SSL_NOT_EXP | SSL_HIGH,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
128,
128,
},
/* Cipher 44 */
{
1,
TLS1_TXT_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA,
TLS1_CK_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA,
SSL_kEDH,
SSL_aDSS,
SSL_CAMELLIA128,
SSL_SHA1,
SSL_TLSV1,
SSL_NOT_EXP | SSL_HIGH,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
128,
128,
},
/* Cipher 45 */
{
1,
TLS1_TXT_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA,
TLS1_CK_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA,
SSL_kEDH,
SSL_aRSA,
SSL_CAMELLIA128,
SSL_SHA1,
SSL_TLSV1,
SSL_NOT_EXP | SSL_HIGH,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
128,
128,
},
/* Cipher 46 */
{
1,
TLS1_TXT_ADH_WITH_CAMELLIA_128_CBC_SHA,
TLS1_CK_ADH_WITH_CAMELLIA_128_CBC_SHA,
SSL_kEDH,
SSL_aNULL,
SSL_CAMELLIA128,
SSL_SHA1,
SSL_TLSV1,
SSL_NOT_DEFAULT | SSL_NOT_EXP | SSL_HIGH,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
128,
128,
},
#endif /* OPENSSL_NO_CAMELLIA */
#if TLS1_ALLOW_EXPERIMENTAL_CIPHERSUITES
/* New TLS Export CipherSuites from expired ID */
# if 0
/* Cipher 60 */
{
1,
TLS1_TXT_RSA_EXPORT1024_WITH_RC4_56_MD5,
TLS1_CK_RSA_EXPORT1024_WITH_RC4_56_MD5,
SSL_kRSA,
SSL_aRSA,
SSL_RC4,
SSL_MD5,
SSL_TLSV1,
SSL_NOT_DEFAULT | SSL_EXPORT | SSL_EXP56,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
56,
128,
},
/* Cipher 61 */
{
1,
TLS1_TXT_RSA_EXPORT1024_WITH_RC2_CBC_56_MD5,
TLS1_CK_RSA_EXPORT1024_WITH_RC2_CBC_56_MD5,
SSL_kRSA,
SSL_aRSA,
SSL_RC2,
SSL_MD5,
SSL_TLSV1,
SSL_NOT_DEFAULT | SSL_EXPORT | SSL_EXP56,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
56,
128,
},
# endif
/* Cipher 62 */
# ifndef OPENSSL_NO_WEAK_SSL_CIPHERS
{
1,
TLS1_TXT_RSA_EXPORT1024_WITH_DES_CBC_SHA,
TLS1_CK_RSA_EXPORT1024_WITH_DES_CBC_SHA,
SSL_kRSA,
SSL_aRSA,
SSL_DES,
SSL_SHA1,
SSL_TLSV1,
SSL_NOT_DEFAULT | SSL_EXPORT | SSL_EXP56,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
56,
56,
},
# endif
/* Cipher 63 */
# ifndef OPENSSL_NO_WEAK_SSL_CIPHERS
{
1,
TLS1_TXT_DHE_DSS_EXPORT1024_WITH_DES_CBC_SHA,
TLS1_CK_DHE_DSS_EXPORT1024_WITH_DES_CBC_SHA,
SSL_kEDH,
SSL_aDSS,
SSL_DES,
SSL_SHA1,
SSL_TLSV1,
SSL_NOT_DEFAULT | SSL_EXPORT | SSL_EXP56,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
56,
56,
},
# endif
/* Cipher 64 */
# ifndef OPENSSL_NO_WEAK_SSL_CIPHERS
{
1,
TLS1_TXT_RSA_EXPORT1024_WITH_RC4_56_SHA,
TLS1_CK_RSA_EXPORT1024_WITH_RC4_56_SHA,
SSL_kRSA,
SSL_aRSA,
SSL_RC4,
SSL_SHA1,
SSL_TLSV1,
SSL_NOT_DEFAULT | SSL_EXPORT | SSL_EXP56,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
56,
128,
},
# endif
/* Cipher 65 */
# ifndef OPENSSL_NO_WEAK_SSL_CIPHERS
{
1,
TLS1_TXT_DHE_DSS_EXPORT1024_WITH_RC4_56_SHA,
TLS1_CK_DHE_DSS_EXPORT1024_WITH_RC4_56_SHA,
SSL_kEDH,
SSL_aDSS,
SSL_RC4,
SSL_SHA1,
SSL_TLSV1,
SSL_NOT_DEFAULT | SSL_EXPORT | SSL_EXP56,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
56,
128,
},
# endif
/* Cipher 66 */
{
1,
TLS1_TXT_DHE_DSS_WITH_RC4_128_SHA,
TLS1_CK_DHE_DSS_WITH_RC4_128_SHA,
SSL_kEDH,
SSL_aDSS,
SSL_RC4,
SSL_SHA1,
SSL_TLSV1,
SSL_NOT_EXP | SSL_MEDIUM,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
128,
128,
},
#endif
/* TLS v1.2 ciphersuites */
/* Cipher 67 */
{
1,
TLS1_TXT_DHE_RSA_WITH_AES_128_SHA256,
TLS1_CK_DHE_RSA_WITH_AES_128_SHA256,
SSL_kEDH,
SSL_aRSA,
SSL_AES128,
SSL_SHA256,
SSL_TLSV1_2,
SSL_NOT_EXP | SSL_HIGH | SSL_FIPS,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
128,
128,
},
/* Cipher 68 */
{
1,
TLS1_TXT_DH_DSS_WITH_AES_256_SHA256,
TLS1_CK_DH_DSS_WITH_AES_256_SHA256,
SSL_kDHd,
SSL_aDH,
SSL_AES256,
SSL_SHA256,
SSL_TLSV1_2,
SSL_NOT_EXP | SSL_HIGH | SSL_FIPS,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
256,
256,
},
/* Cipher 69 */
{
1,
TLS1_TXT_DH_RSA_WITH_AES_256_SHA256,
TLS1_CK_DH_RSA_WITH_AES_256_SHA256,
SSL_kDHr,
SSL_aDH,
SSL_AES256,
SSL_SHA256,
SSL_TLSV1_2,
SSL_NOT_EXP | SSL_HIGH | SSL_FIPS,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
256,
256,
},
/* Cipher 6A */
{
1,
TLS1_TXT_DHE_DSS_WITH_AES_256_SHA256,
TLS1_CK_DHE_DSS_WITH_AES_256_SHA256,
SSL_kEDH,
SSL_aDSS,
SSL_AES256,
SSL_SHA256,
SSL_TLSV1_2,
SSL_NOT_EXP | SSL_HIGH | SSL_FIPS,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
256,
256,
},
/* Cipher 6B */
{
1,
TLS1_TXT_DHE_RSA_WITH_AES_256_SHA256,
TLS1_CK_DHE_RSA_WITH_AES_256_SHA256,
SSL_kEDH,
SSL_aRSA,
SSL_AES256,
SSL_SHA256,
SSL_TLSV1_2,
SSL_NOT_EXP | SSL_HIGH | SSL_FIPS,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
256,
256,
},
/* Cipher 6C */
{
1,
TLS1_TXT_ADH_WITH_AES_128_SHA256,
TLS1_CK_ADH_WITH_AES_128_SHA256,
SSL_kEDH,
SSL_aNULL,
SSL_AES128,
SSL_SHA256,
SSL_TLSV1_2,
SSL_NOT_DEFAULT | SSL_NOT_EXP | SSL_HIGH | SSL_FIPS,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
128,
128,
},
/* Cipher 6D */
{
1,
TLS1_TXT_ADH_WITH_AES_256_SHA256,
TLS1_CK_ADH_WITH_AES_256_SHA256,
SSL_kEDH,
SSL_aNULL,
SSL_AES256,
SSL_SHA256,
SSL_TLSV1_2,
SSL_NOT_DEFAULT | SSL_NOT_EXP | SSL_HIGH | SSL_FIPS,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
256,
256,
},
/* GOST Ciphersuites */
{
1,
"GOST94-GOST89-GOST89",
0x3000080,
SSL_kGOST,
SSL_aGOST94,
SSL_eGOST2814789CNT,
SSL_GOST89MAC,
SSL_TLSV1,
SSL_NOT_EXP | SSL_HIGH,
SSL_HANDSHAKE_MAC_GOST94 | TLS1_PRF_GOST94 | TLS1_STREAM_MAC,
256,
256},
{
1,
"GOST2001-GOST89-GOST89",
0x3000081,
SSL_kGOST,
SSL_aGOST01,
SSL_eGOST2814789CNT,
SSL_GOST89MAC,
SSL_TLSV1,
SSL_NOT_EXP | SSL_HIGH,
SSL_HANDSHAKE_MAC_GOST94 | TLS1_PRF_GOST94 | TLS1_STREAM_MAC,
256,
256},
{
1,
"GOST94-NULL-GOST94",
0x3000082,
SSL_kGOST,
SSL_aGOST94,
SSL_eNULL,
SSL_GOST94,
SSL_TLSV1,
SSL_NOT_EXP | SSL_STRONG_NONE,
SSL_HANDSHAKE_MAC_GOST94 | TLS1_PRF_GOST94,
0,
0},
{
1,
"GOST2001-NULL-GOST94",
0x3000083,
SSL_kGOST,
SSL_aGOST01,
SSL_eNULL,
SSL_GOST94,
SSL_TLSV1,
SSL_NOT_EXP | SSL_STRONG_NONE,
SSL_HANDSHAKE_MAC_GOST94 | TLS1_PRF_GOST94,
0,
0},
#ifndef OPENSSL_NO_CAMELLIA
/* Camellia ciphersuites from RFC4132 (256-bit portion) */
/* Cipher 84 */
{
1,
TLS1_TXT_RSA_WITH_CAMELLIA_256_CBC_SHA,
TLS1_CK_RSA_WITH_CAMELLIA_256_CBC_SHA,
SSL_kRSA,
SSL_aRSA,
SSL_CAMELLIA256,
SSL_SHA1,
SSL_TLSV1,
SSL_NOT_EXP | SSL_HIGH,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
256,
256,
},
/* Cipher 85 */
{
1,
TLS1_TXT_DH_DSS_WITH_CAMELLIA_256_CBC_SHA,
TLS1_CK_DH_DSS_WITH_CAMELLIA_256_CBC_SHA,
SSL_kDHd,
SSL_aDH,
SSL_CAMELLIA256,
SSL_SHA1,
SSL_TLSV1,
SSL_NOT_EXP | SSL_HIGH,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
256,
256,
},
/* Cipher 86 */
{
1,
TLS1_TXT_DH_RSA_WITH_CAMELLIA_256_CBC_SHA,
TLS1_CK_DH_RSA_WITH_CAMELLIA_256_CBC_SHA,
SSL_kDHr,
SSL_aDH,
SSL_CAMELLIA256,
SSL_SHA1,
SSL_TLSV1,
SSL_NOT_EXP | SSL_HIGH,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
256,
256,
},
/* Cipher 87 */
{
1,
TLS1_TXT_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA,
TLS1_CK_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA,
SSL_kEDH,
SSL_aDSS,
SSL_CAMELLIA256,
SSL_SHA1,
SSL_TLSV1,
SSL_NOT_EXP | SSL_HIGH,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
256,
256,
},
/* Cipher 88 */
{
1,
TLS1_TXT_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA,
TLS1_CK_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA,
SSL_kEDH,
SSL_aRSA,
SSL_CAMELLIA256,
SSL_SHA1,
SSL_TLSV1,
SSL_NOT_EXP | SSL_HIGH,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
256,
256,
},
/* Cipher 89 */
{
1,
TLS1_TXT_ADH_WITH_CAMELLIA_256_CBC_SHA,
TLS1_CK_ADH_WITH_CAMELLIA_256_CBC_SHA,
SSL_kEDH,
SSL_aNULL,
SSL_CAMELLIA256,
SSL_SHA1,
SSL_TLSV1,
SSL_NOT_DEFAULT | SSL_NOT_EXP | SSL_HIGH,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
256,
256,
},
#endif /* OPENSSL_NO_CAMELLIA */
#ifndef OPENSSL_NO_PSK
/* Cipher 8A */
{
1,
TLS1_TXT_PSK_WITH_RC4_128_SHA,
TLS1_CK_PSK_WITH_RC4_128_SHA,
SSL_kPSK,
SSL_aPSK,
SSL_RC4,
SSL_SHA1,
SSL_TLSV1,
SSL_NOT_EXP | SSL_MEDIUM,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
128,
128,
},
/* Cipher 8B */
{
1,
TLS1_TXT_PSK_WITH_3DES_EDE_CBC_SHA,
TLS1_CK_PSK_WITH_3DES_EDE_CBC_SHA,
SSL_kPSK,
SSL_aPSK,
SSL_3DES,
SSL_SHA1,
SSL_TLSV1,
SSL_NOT_EXP | SSL_MEDIUM | SSL_FIPS,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
112,
168,
},
/* Cipher 8C */
{
1,
TLS1_TXT_PSK_WITH_AES_128_CBC_SHA,
TLS1_CK_PSK_WITH_AES_128_CBC_SHA,
SSL_kPSK,
SSL_aPSK,
SSL_AES128,
SSL_SHA1,
SSL_TLSV1,
SSL_NOT_EXP | SSL_HIGH | SSL_FIPS,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
128,
128,
},
/* Cipher 8D */
{
1,
TLS1_TXT_PSK_WITH_AES_256_CBC_SHA,
TLS1_CK_PSK_WITH_AES_256_CBC_SHA,
SSL_kPSK,
SSL_aPSK,
SSL_AES256,
SSL_SHA1,
SSL_TLSV1,
SSL_NOT_EXP | SSL_HIGH | SSL_FIPS,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
256,
256,
},
#endif /* OPENSSL_NO_PSK */
#ifndef OPENSSL_NO_SEED
/* SEED ciphersuites from RFC4162 */
/* Cipher 96 */
{
1,
TLS1_TXT_RSA_WITH_SEED_SHA,
TLS1_CK_RSA_WITH_SEED_SHA,
SSL_kRSA,
SSL_aRSA,
SSL_SEED,
SSL_SHA1,
SSL_TLSV1,
SSL_NOT_EXP | SSL_MEDIUM,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
128,
128,
},
/* Cipher 97 */
{
1,
TLS1_TXT_DH_DSS_WITH_SEED_SHA,
TLS1_CK_DH_DSS_WITH_SEED_SHA,
SSL_kDHd,
SSL_aDH,
SSL_SEED,
SSL_SHA1,
SSL_TLSV1,
SSL_NOT_EXP | SSL_MEDIUM,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
128,
128,
},
/* Cipher 98 */
{
1,
TLS1_TXT_DH_RSA_WITH_SEED_SHA,
TLS1_CK_DH_RSA_WITH_SEED_SHA,
SSL_kDHr,
SSL_aDH,
SSL_SEED,
SSL_SHA1,
SSL_TLSV1,
SSL_NOT_EXP | SSL_MEDIUM,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
128,
128,
},
/* Cipher 99 */
{
1,
TLS1_TXT_DHE_DSS_WITH_SEED_SHA,
TLS1_CK_DHE_DSS_WITH_SEED_SHA,
SSL_kEDH,
SSL_aDSS,
SSL_SEED,
SSL_SHA1,
SSL_TLSV1,
SSL_NOT_EXP | SSL_MEDIUM,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
128,
128,
},
/* Cipher 9A */
{
1,
TLS1_TXT_DHE_RSA_WITH_SEED_SHA,
TLS1_CK_DHE_RSA_WITH_SEED_SHA,
SSL_kEDH,
SSL_aRSA,
SSL_SEED,
SSL_SHA1,
SSL_TLSV1,
SSL_NOT_EXP | SSL_MEDIUM,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
128,
128,
},
/* Cipher 9B */
{
1,
TLS1_TXT_ADH_WITH_SEED_SHA,
TLS1_CK_ADH_WITH_SEED_SHA,
SSL_kEDH,
SSL_aNULL,
SSL_SEED,
SSL_SHA1,
SSL_TLSV1,
SSL_NOT_DEFAULT | SSL_NOT_EXP | SSL_MEDIUM,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
128,
128,
},
#endif /* OPENSSL_NO_SEED */
/* GCM ciphersuites from RFC5288 */
/* Cipher 9C */
{
1,
TLS1_TXT_RSA_WITH_AES_128_GCM_SHA256,
TLS1_CK_RSA_WITH_AES_128_GCM_SHA256,
SSL_kRSA,
SSL_aRSA,
SSL_AES128GCM,
SSL_AEAD,
SSL_TLSV1_2,
SSL_NOT_EXP | SSL_HIGH | SSL_FIPS,
SSL_HANDSHAKE_MAC_SHA256 | TLS1_PRF_SHA256,
128,
128,
},
/* Cipher 9D */
{
1,
TLS1_TXT_RSA_WITH_AES_256_GCM_SHA384,
TLS1_CK_RSA_WITH_AES_256_GCM_SHA384,
SSL_kRSA,
SSL_aRSA,
SSL_AES256GCM,
SSL_AEAD,
SSL_TLSV1_2,
SSL_NOT_EXP | SSL_HIGH | SSL_FIPS,
SSL_HANDSHAKE_MAC_SHA384 | TLS1_PRF_SHA384,
256,
256,
},
/* Cipher 9E */
{
1,
TLS1_TXT_DHE_RSA_WITH_AES_128_GCM_SHA256,
TLS1_CK_DHE_RSA_WITH_AES_128_GCM_SHA256,
SSL_kEDH,
SSL_aRSA,
SSL_AES128GCM,
SSL_AEAD,
SSL_TLSV1_2,
SSL_NOT_EXP | SSL_HIGH | SSL_FIPS,
SSL_HANDSHAKE_MAC_SHA256 | TLS1_PRF_SHA256,
128,
128,
},
/* Cipher 9F */
{
1,
TLS1_TXT_DHE_RSA_WITH_AES_256_GCM_SHA384,
TLS1_CK_DHE_RSA_WITH_AES_256_GCM_SHA384,
SSL_kEDH,
SSL_aRSA,
SSL_AES256GCM,
SSL_AEAD,
SSL_TLSV1_2,
SSL_NOT_EXP | SSL_HIGH | SSL_FIPS,
SSL_HANDSHAKE_MAC_SHA384 | TLS1_PRF_SHA384,
256,
256,
},
/* Cipher A0 */
{
1,
TLS1_TXT_DH_RSA_WITH_AES_128_GCM_SHA256,
TLS1_CK_DH_RSA_WITH_AES_128_GCM_SHA256,
SSL_kDHr,
SSL_aDH,
SSL_AES128GCM,
SSL_AEAD,
SSL_TLSV1_2,
SSL_NOT_EXP | SSL_HIGH | SSL_FIPS,
SSL_HANDSHAKE_MAC_SHA256 | TLS1_PRF_SHA256,
128,
128,
},
/* Cipher A1 */
{
1,
TLS1_TXT_DH_RSA_WITH_AES_256_GCM_SHA384,
TLS1_CK_DH_RSA_WITH_AES_256_GCM_SHA384,
SSL_kDHr,
SSL_aDH,
SSL_AES256GCM,
SSL_AEAD,
SSL_TLSV1_2,
SSL_NOT_EXP | SSL_HIGH | SSL_FIPS,
SSL_HANDSHAKE_MAC_SHA384 | TLS1_PRF_SHA384,
256,
256,
},
/* Cipher A2 */
{
1,
TLS1_TXT_DHE_DSS_WITH_AES_128_GCM_SHA256,
TLS1_CK_DHE_DSS_WITH_AES_128_GCM_SHA256,
SSL_kEDH,
SSL_aDSS,
SSL_AES128GCM,
SSL_AEAD,
SSL_TLSV1_2,
SSL_NOT_EXP | SSL_HIGH | SSL_FIPS,
SSL_HANDSHAKE_MAC_SHA256 | TLS1_PRF_SHA256,
128,
128,
},
/* Cipher A3 */
{
1,
TLS1_TXT_DHE_DSS_WITH_AES_256_GCM_SHA384,
TLS1_CK_DHE_DSS_WITH_AES_256_GCM_SHA384,
SSL_kEDH,
SSL_aDSS,
SSL_AES256GCM,
SSL_AEAD,
SSL_TLSV1_2,
SSL_NOT_EXP | SSL_HIGH | SSL_FIPS,
SSL_HANDSHAKE_MAC_SHA384 | TLS1_PRF_SHA384,
256,
256,
},
/* Cipher A4 */
{
1,
TLS1_TXT_DH_DSS_WITH_AES_128_GCM_SHA256,
TLS1_CK_DH_DSS_WITH_AES_128_GCM_SHA256,
SSL_kDHd,
SSL_aDH,
SSL_AES128GCM,
SSL_AEAD,
SSL_TLSV1_2,
SSL_NOT_EXP | SSL_HIGH | SSL_FIPS,
SSL_HANDSHAKE_MAC_SHA256 | TLS1_PRF_SHA256,
128,
128,
},
/* Cipher A5 */
{
1,
TLS1_TXT_DH_DSS_WITH_AES_256_GCM_SHA384,
TLS1_CK_DH_DSS_WITH_AES_256_GCM_SHA384,
SSL_kDHd,
SSL_aDH,
SSL_AES256GCM,
SSL_AEAD,
SSL_TLSV1_2,
SSL_NOT_EXP | SSL_HIGH | SSL_FIPS,
SSL_HANDSHAKE_MAC_SHA384 | TLS1_PRF_SHA384,
256,
256,
},
/* Cipher A6 */
{
1,
TLS1_TXT_ADH_WITH_AES_128_GCM_SHA256,
TLS1_CK_ADH_WITH_AES_128_GCM_SHA256,
SSL_kEDH,
SSL_aNULL,
SSL_AES128GCM,
SSL_AEAD,
SSL_TLSV1_2,
SSL_NOT_DEFAULT | SSL_NOT_EXP | SSL_HIGH | SSL_FIPS,
SSL_HANDSHAKE_MAC_SHA256 | TLS1_PRF_SHA256,
128,
128,
},
/* Cipher A7 */
{
1,
TLS1_TXT_ADH_WITH_AES_256_GCM_SHA384,
TLS1_CK_ADH_WITH_AES_256_GCM_SHA384,
SSL_kEDH,
SSL_aNULL,
SSL_AES256GCM,
SSL_AEAD,
SSL_TLSV1_2,
SSL_NOT_DEFAULT | SSL_NOT_EXP | SSL_HIGH | SSL_FIPS,
SSL_HANDSHAKE_MAC_SHA384 | TLS1_PRF_SHA384,
256,
256,
},
#ifdef OPENSSL_SSL_DEBUG_BROKEN_PROTOCOL
{
1,
"SCSV",
SSL3_CK_SCSV,
0,
0,
0,
0,
0,
0,
0,
0,
0},
#endif
#ifndef OPENSSL_NO_ECDH
/* Cipher C001 */
{
1,
TLS1_TXT_ECDH_ECDSA_WITH_NULL_SHA,
TLS1_CK_ECDH_ECDSA_WITH_NULL_SHA,
SSL_kECDHe,
SSL_aECDH,
SSL_eNULL,
SSL_SHA1,
SSL_TLSV1,
SSL_NOT_EXP | SSL_STRONG_NONE | SSL_FIPS,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
0,
0,
},
/* Cipher C002 */
{
1,
TLS1_TXT_ECDH_ECDSA_WITH_RC4_128_SHA,
TLS1_CK_ECDH_ECDSA_WITH_RC4_128_SHA,
SSL_kECDHe,
SSL_aECDH,
SSL_RC4,
SSL_SHA1,
SSL_TLSV1,
SSL_NOT_EXP | SSL_MEDIUM,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
128,
128,
},
/* Cipher C003 */
{
1,
TLS1_TXT_ECDH_ECDSA_WITH_DES_192_CBC3_SHA,
TLS1_CK_ECDH_ECDSA_WITH_DES_192_CBC3_SHA,
SSL_kECDHe,
SSL_aECDH,
SSL_3DES,
SSL_SHA1,
SSL_TLSV1,
SSL_NOT_EXP | SSL_MEDIUM | SSL_FIPS,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
112,
168,
},
/* Cipher C004 */
{
1,
TLS1_TXT_ECDH_ECDSA_WITH_AES_128_CBC_SHA,
TLS1_CK_ECDH_ECDSA_WITH_AES_128_CBC_SHA,
SSL_kECDHe,
SSL_aECDH,
SSL_AES128,
SSL_SHA1,
SSL_TLSV1,
SSL_NOT_EXP | SSL_HIGH | SSL_FIPS,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
128,
128,
},
/* Cipher C005 */
{
1,
TLS1_TXT_ECDH_ECDSA_WITH_AES_256_CBC_SHA,
TLS1_CK_ECDH_ECDSA_WITH_AES_256_CBC_SHA,
SSL_kECDHe,
SSL_aECDH,
SSL_AES256,
SSL_SHA1,
SSL_TLSV1,
SSL_NOT_EXP | SSL_HIGH | SSL_FIPS,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
256,
256,
},
/* Cipher C006 */
{
1,
TLS1_TXT_ECDHE_ECDSA_WITH_NULL_SHA,
TLS1_CK_ECDHE_ECDSA_WITH_NULL_SHA,
SSL_kEECDH,
SSL_aECDSA,
SSL_eNULL,
SSL_SHA1,
SSL_TLSV1,
SSL_NOT_EXP | SSL_STRONG_NONE | SSL_FIPS,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
0,
0,
},
/* Cipher C007 */
{
1,
TLS1_TXT_ECDHE_ECDSA_WITH_RC4_128_SHA,
TLS1_CK_ECDHE_ECDSA_WITH_RC4_128_SHA,
SSL_kEECDH,
SSL_aECDSA,
SSL_RC4,
SSL_SHA1,
SSL_TLSV1,
SSL_NOT_EXP | SSL_MEDIUM,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
128,
128,
},
/* Cipher C008 */
{
1,
TLS1_TXT_ECDHE_ECDSA_WITH_DES_192_CBC3_SHA,
TLS1_CK_ECDHE_ECDSA_WITH_DES_192_CBC3_SHA,
SSL_kEECDH,
SSL_aECDSA,
SSL_3DES,
SSL_SHA1,
SSL_TLSV1,
SSL_NOT_EXP | SSL_MEDIUM | SSL_FIPS,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
112,
168,
},
/* Cipher C009 */
{
1,
TLS1_TXT_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,
TLS1_CK_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,
SSL_kEECDH,
SSL_aECDSA,
SSL_AES128,
SSL_SHA1,
SSL_TLSV1,
SSL_NOT_EXP | SSL_HIGH | SSL_FIPS,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
128,
128,
},
/* Cipher C00A */
{
1,
TLS1_TXT_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
TLS1_CK_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
SSL_kEECDH,
SSL_aECDSA,
SSL_AES256,
SSL_SHA1,
SSL_TLSV1,
SSL_NOT_EXP | SSL_HIGH | SSL_FIPS,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
256,
256,
},
/* Cipher C00B */
{
1,
TLS1_TXT_ECDH_RSA_WITH_NULL_SHA,
TLS1_CK_ECDH_RSA_WITH_NULL_SHA,
SSL_kECDHr,
SSL_aECDH,
SSL_eNULL,
SSL_SHA1,
SSL_TLSV1,
SSL_NOT_EXP | SSL_STRONG_NONE | SSL_FIPS,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
0,
0,
},
/* Cipher C00C */
{
1,
TLS1_TXT_ECDH_RSA_WITH_RC4_128_SHA,
TLS1_CK_ECDH_RSA_WITH_RC4_128_SHA,
SSL_kECDHr,
SSL_aECDH,
SSL_RC4,
SSL_SHA1,
SSL_TLSV1,
SSL_NOT_EXP | SSL_MEDIUM,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
128,
128,
},
/* Cipher C00D */
{
1,
TLS1_TXT_ECDH_RSA_WITH_DES_192_CBC3_SHA,
TLS1_CK_ECDH_RSA_WITH_DES_192_CBC3_SHA,
SSL_kECDHr,
SSL_aECDH,
SSL_3DES,
SSL_SHA1,
SSL_TLSV1,
SSL_NOT_EXP | SSL_MEDIUM | SSL_FIPS,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
112,
168,
},
/* Cipher C00E */
{
1,
TLS1_TXT_ECDH_RSA_WITH_AES_128_CBC_SHA,
TLS1_CK_ECDH_RSA_WITH_AES_128_CBC_SHA,
SSL_kECDHr,
SSL_aECDH,
SSL_AES128,
SSL_SHA1,
SSL_TLSV1,
SSL_NOT_EXP | SSL_HIGH | SSL_FIPS,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
128,
128,
},
/* Cipher C00F */
{
1,
TLS1_TXT_ECDH_RSA_WITH_AES_256_CBC_SHA,
TLS1_CK_ECDH_RSA_WITH_AES_256_CBC_SHA,
SSL_kECDHr,
SSL_aECDH,
SSL_AES256,
SSL_SHA1,
SSL_TLSV1,
SSL_NOT_EXP | SSL_HIGH | SSL_FIPS,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
256,
256,
},
/* Cipher C010 */
{
1,
TLS1_TXT_ECDHE_RSA_WITH_NULL_SHA,
TLS1_CK_ECDHE_RSA_WITH_NULL_SHA,
SSL_kEECDH,
SSL_aRSA,
SSL_eNULL,
SSL_SHA1,
SSL_TLSV1,
SSL_NOT_EXP | SSL_STRONG_NONE | SSL_FIPS,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
0,
0,
},
/* Cipher C011 */
{
1,
TLS1_TXT_ECDHE_RSA_WITH_RC4_128_SHA,
TLS1_CK_ECDHE_RSA_WITH_RC4_128_SHA,
SSL_kEECDH,
SSL_aRSA,
SSL_RC4,
SSL_SHA1,
SSL_TLSV1,
SSL_NOT_EXP | SSL_MEDIUM,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
128,
128,
},
/* Cipher C012 */
{
1,
TLS1_TXT_ECDHE_RSA_WITH_DES_192_CBC3_SHA,
TLS1_CK_ECDHE_RSA_WITH_DES_192_CBC3_SHA,
SSL_kEECDH,
SSL_aRSA,
SSL_3DES,
SSL_SHA1,
SSL_TLSV1,
SSL_NOT_EXP | SSL_MEDIUM | SSL_FIPS,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
112,
168,
},
/* Cipher C013 */
{
1,
TLS1_TXT_ECDHE_RSA_WITH_AES_128_CBC_SHA,
TLS1_CK_ECDHE_RSA_WITH_AES_128_CBC_SHA,
SSL_kEECDH,
SSL_aRSA,
SSL_AES128,
SSL_SHA1,
SSL_TLSV1,
SSL_NOT_EXP | SSL_HIGH | SSL_FIPS,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
128,
128,
},
/* Cipher C014 */
{
1,
TLS1_TXT_ECDHE_RSA_WITH_AES_256_CBC_SHA,
TLS1_CK_ECDHE_RSA_WITH_AES_256_CBC_SHA,
SSL_kEECDH,
SSL_aRSA,
SSL_AES256,
SSL_SHA1,
SSL_TLSV1,
SSL_NOT_EXP | SSL_HIGH | SSL_FIPS,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
256,
256,
},
/* Cipher C015 */
{
1,
TLS1_TXT_ECDH_anon_WITH_NULL_SHA,
TLS1_CK_ECDH_anon_WITH_NULL_SHA,
SSL_kEECDH,
SSL_aNULL,
SSL_eNULL,
SSL_SHA1,
SSL_TLSV1,
SSL_NOT_EXP | SSL_STRONG_NONE | SSL_FIPS,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
0,
0,
},
/* Cipher C016 */
{
1,
TLS1_TXT_ECDH_anon_WITH_RC4_128_SHA,
TLS1_CK_ECDH_anon_WITH_RC4_128_SHA,
SSL_kEECDH,
SSL_aNULL,
SSL_RC4,
SSL_SHA1,
SSL_TLSV1,
SSL_NOT_DEFAULT | SSL_NOT_EXP | SSL_MEDIUM,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
128,
128,
},
/* Cipher C017 */
{
1,
TLS1_TXT_ECDH_anon_WITH_DES_192_CBC3_SHA,
TLS1_CK_ECDH_anon_WITH_DES_192_CBC3_SHA,
SSL_kEECDH,
SSL_aNULL,
SSL_3DES,
SSL_SHA1,
SSL_TLSV1,
SSL_NOT_DEFAULT | SSL_NOT_EXP | SSL_MEDIUM | SSL_FIPS,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
112,
168,
},
/* Cipher C018 */
{
1,
TLS1_TXT_ECDH_anon_WITH_AES_128_CBC_SHA,
TLS1_CK_ECDH_anon_WITH_AES_128_CBC_SHA,
SSL_kEECDH,
SSL_aNULL,
SSL_AES128,
SSL_SHA1,
SSL_TLSV1,
SSL_NOT_DEFAULT | SSL_NOT_EXP | SSL_HIGH | SSL_FIPS,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
128,
128,
},
/* Cipher C019 */
{
1,
TLS1_TXT_ECDH_anon_WITH_AES_256_CBC_SHA,
TLS1_CK_ECDH_anon_WITH_AES_256_CBC_SHA,
SSL_kEECDH,
SSL_aNULL,
SSL_AES256,
SSL_SHA1,
SSL_TLSV1,
SSL_NOT_DEFAULT | SSL_NOT_EXP | SSL_HIGH | SSL_FIPS,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
256,
256,
},
#endif /* OPENSSL_NO_ECDH */
#ifndef OPENSSL_NO_SRP
/* Cipher C01A */
{
1,
TLS1_TXT_SRP_SHA_WITH_3DES_EDE_CBC_SHA,
TLS1_CK_SRP_SHA_WITH_3DES_EDE_CBC_SHA,
SSL_kSRP,
SSL_aSRP,
SSL_3DES,
SSL_SHA1,
SSL_TLSV1,
SSL_NOT_EXP | SSL_MEDIUM,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
112,
168,
},
/* Cipher C01B */
{
1,
TLS1_TXT_SRP_SHA_RSA_WITH_3DES_EDE_CBC_SHA,
TLS1_CK_SRP_SHA_RSA_WITH_3DES_EDE_CBC_SHA,
SSL_kSRP,
SSL_aRSA,
SSL_3DES,
SSL_SHA1,
SSL_TLSV1,
SSL_NOT_EXP | SSL_MEDIUM,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
112,
168,
},
/* Cipher C01C */
{
1,
TLS1_TXT_SRP_SHA_DSS_WITH_3DES_EDE_CBC_SHA,
TLS1_CK_SRP_SHA_DSS_WITH_3DES_EDE_CBC_SHA,
SSL_kSRP,
SSL_aDSS,
SSL_3DES,
SSL_SHA1,
SSL_TLSV1,
SSL_NOT_EXP | SSL_MEDIUM,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
112,
168,
},
/* Cipher C01D */
{
1,
TLS1_TXT_SRP_SHA_WITH_AES_128_CBC_SHA,
TLS1_CK_SRP_SHA_WITH_AES_128_CBC_SHA,
SSL_kSRP,
SSL_aSRP,
SSL_AES128,
SSL_SHA1,
SSL_TLSV1,
SSL_NOT_EXP | SSL_HIGH,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
128,
128,
},
/* Cipher C01E */
{
1,
TLS1_TXT_SRP_SHA_RSA_WITH_AES_128_CBC_SHA,
TLS1_CK_SRP_SHA_RSA_WITH_AES_128_CBC_SHA,
SSL_kSRP,
SSL_aRSA,
SSL_AES128,
SSL_SHA1,
SSL_TLSV1,
SSL_NOT_EXP | SSL_HIGH,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
128,
128,
},
/* Cipher C01F */
{
1,
TLS1_TXT_SRP_SHA_DSS_WITH_AES_128_CBC_SHA,
TLS1_CK_SRP_SHA_DSS_WITH_AES_128_CBC_SHA,
SSL_kSRP,
SSL_aDSS,
SSL_AES128,
SSL_SHA1,
SSL_TLSV1,
SSL_NOT_EXP | SSL_HIGH,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
128,
128,
},
/* Cipher C020 */
{
1,
TLS1_TXT_SRP_SHA_WITH_AES_256_CBC_SHA,
TLS1_CK_SRP_SHA_WITH_AES_256_CBC_SHA,
SSL_kSRP,
SSL_aSRP,
SSL_AES256,
SSL_SHA1,
SSL_TLSV1,
SSL_NOT_EXP | SSL_HIGH,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
256,
256,
},
/* Cipher C021 */
{
1,
TLS1_TXT_SRP_SHA_RSA_WITH_AES_256_CBC_SHA,
TLS1_CK_SRP_SHA_RSA_WITH_AES_256_CBC_SHA,
SSL_kSRP,
SSL_aRSA,
SSL_AES256,
SSL_SHA1,
SSL_TLSV1,
SSL_NOT_EXP | SSL_HIGH,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
256,
256,
},
/* Cipher C022 */
{
1,
TLS1_TXT_SRP_SHA_DSS_WITH_AES_256_CBC_SHA,
TLS1_CK_SRP_SHA_DSS_WITH_AES_256_CBC_SHA,
SSL_kSRP,
SSL_aDSS,
SSL_AES256,
SSL_SHA1,
SSL_TLSV1,
SSL_NOT_EXP | SSL_HIGH,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
256,
256,
},
#endif /* OPENSSL_NO_SRP */
#ifndef OPENSSL_NO_ECDH
/* HMAC based TLS v1.2 ciphersuites from RFC5289 */
/* Cipher C023 */
{
1,
TLS1_TXT_ECDHE_ECDSA_WITH_AES_128_SHA256,
TLS1_CK_ECDHE_ECDSA_WITH_AES_128_SHA256,
SSL_kEECDH,
SSL_aECDSA,
SSL_AES128,
SSL_SHA256,
SSL_TLSV1_2,
SSL_NOT_EXP | SSL_HIGH | SSL_FIPS,
SSL_HANDSHAKE_MAC_SHA256 | TLS1_PRF_SHA256,
128,
128,
},
/* Cipher C024 */
{
1,
TLS1_TXT_ECDHE_ECDSA_WITH_AES_256_SHA384,
TLS1_CK_ECDHE_ECDSA_WITH_AES_256_SHA384,
SSL_kEECDH,
SSL_aECDSA,
SSL_AES256,
SSL_SHA384,
SSL_TLSV1_2,
SSL_NOT_EXP | SSL_HIGH | SSL_FIPS,
SSL_HANDSHAKE_MAC_SHA384 | TLS1_PRF_SHA384,
256,
256,
},
/* Cipher C025 */
{
1,
TLS1_TXT_ECDH_ECDSA_WITH_AES_128_SHA256,
TLS1_CK_ECDH_ECDSA_WITH_AES_128_SHA256,
SSL_kECDHe,
SSL_aECDH,
SSL_AES128,
SSL_SHA256,
SSL_TLSV1_2,
SSL_NOT_EXP | SSL_HIGH | SSL_FIPS,
SSL_HANDSHAKE_MAC_SHA256 | TLS1_PRF_SHA256,
128,
128,
},
/* Cipher C026 */
{
1,
TLS1_TXT_ECDH_ECDSA_WITH_AES_256_SHA384,
TLS1_CK_ECDH_ECDSA_WITH_AES_256_SHA384,
SSL_kECDHe,
SSL_aECDH,
SSL_AES256,
SSL_SHA384,
SSL_TLSV1_2,
SSL_NOT_EXP | SSL_HIGH | SSL_FIPS,
SSL_HANDSHAKE_MAC_SHA384 | TLS1_PRF_SHA384,
256,
256,
},
/* Cipher C027 */
{
1,
TLS1_TXT_ECDHE_RSA_WITH_AES_128_SHA256,
TLS1_CK_ECDHE_RSA_WITH_AES_128_SHA256,
SSL_kEECDH,
SSL_aRSA,
SSL_AES128,
SSL_SHA256,
SSL_TLSV1_2,
SSL_NOT_EXP | SSL_HIGH | SSL_FIPS,
SSL_HANDSHAKE_MAC_SHA256 | TLS1_PRF_SHA256,
128,
128,
},
/* Cipher C028 */
{
1,
TLS1_TXT_ECDHE_RSA_WITH_AES_256_SHA384,
TLS1_CK_ECDHE_RSA_WITH_AES_256_SHA384,
SSL_kEECDH,
SSL_aRSA,
SSL_AES256,
SSL_SHA384,
SSL_TLSV1_2,
SSL_NOT_EXP | SSL_HIGH | SSL_FIPS,
SSL_HANDSHAKE_MAC_SHA384 | TLS1_PRF_SHA384,
256,
256,
},
/* Cipher C029 */
{
1,
TLS1_TXT_ECDH_RSA_WITH_AES_128_SHA256,
TLS1_CK_ECDH_RSA_WITH_AES_128_SHA256,
SSL_kECDHr,
SSL_aECDH,
SSL_AES128,
SSL_SHA256,
SSL_TLSV1_2,
SSL_NOT_EXP | SSL_HIGH | SSL_FIPS,
SSL_HANDSHAKE_MAC_SHA256 | TLS1_PRF_SHA256,
128,
128,
},
/* Cipher C02A */
{
1,
TLS1_TXT_ECDH_RSA_WITH_AES_256_SHA384,
TLS1_CK_ECDH_RSA_WITH_AES_256_SHA384,
SSL_kECDHr,
SSL_aECDH,
SSL_AES256,
SSL_SHA384,
SSL_TLSV1_2,
SSL_NOT_EXP | SSL_HIGH | SSL_FIPS,
SSL_HANDSHAKE_MAC_SHA384 | TLS1_PRF_SHA384,
256,
256,
},
/* GCM based TLS v1.2 ciphersuites from RFC5289 */
/* Cipher C02B */
{
1,
TLS1_TXT_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
TLS1_CK_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
SSL_kEECDH,
SSL_aECDSA,
SSL_AES128GCM,
SSL_AEAD,
SSL_TLSV1_2,
SSL_NOT_EXP | SSL_HIGH | SSL_FIPS,
SSL_HANDSHAKE_MAC_SHA256 | TLS1_PRF_SHA256,
128,
128,
},
/* Cipher C02C */
{
1,
TLS1_TXT_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
TLS1_CK_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
SSL_kEECDH,
SSL_aECDSA,
SSL_AES256GCM,
SSL_AEAD,
SSL_TLSV1_2,
SSL_NOT_EXP | SSL_HIGH | SSL_FIPS,
SSL_HANDSHAKE_MAC_SHA384 | TLS1_PRF_SHA384,
256,
256,
},
/* Cipher C02D */
{
1,
TLS1_TXT_ECDH_ECDSA_WITH_AES_128_GCM_SHA256,
TLS1_CK_ECDH_ECDSA_WITH_AES_128_GCM_SHA256,
SSL_kECDHe,
SSL_aECDH,
SSL_AES128GCM,
SSL_AEAD,
SSL_TLSV1_2,
SSL_NOT_EXP | SSL_HIGH | SSL_FIPS,
SSL_HANDSHAKE_MAC_SHA256 | TLS1_PRF_SHA256,
128,
128,
},
/* Cipher C02E */
{
1,
TLS1_TXT_ECDH_ECDSA_WITH_AES_256_GCM_SHA384,
TLS1_CK_ECDH_ECDSA_WITH_AES_256_GCM_SHA384,
SSL_kECDHe,
SSL_aECDH,
SSL_AES256GCM,
SSL_AEAD,
SSL_TLSV1_2,
SSL_NOT_EXP | SSL_HIGH | SSL_FIPS,
SSL_HANDSHAKE_MAC_SHA384 | TLS1_PRF_SHA384,
256,
256,
},
/* Cipher C02F */
{
1,
TLS1_TXT_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
TLS1_CK_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
SSL_kEECDH,
SSL_aRSA,
SSL_AES128GCM,
SSL_AEAD,
SSL_TLSV1_2,
SSL_NOT_EXP | SSL_HIGH | SSL_FIPS,
SSL_HANDSHAKE_MAC_SHA256 | TLS1_PRF_SHA256,
128,
128,
},
/* Cipher C030 */
{
1,
TLS1_TXT_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
TLS1_CK_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
SSL_kEECDH,
SSL_aRSA,
SSL_AES256GCM,
SSL_AEAD,
SSL_TLSV1_2,
SSL_NOT_EXP | SSL_HIGH | SSL_FIPS,
SSL_HANDSHAKE_MAC_SHA384 | TLS1_PRF_SHA384,
256,
256,
},
/* Cipher C031 */
{
1,
TLS1_TXT_ECDH_RSA_WITH_AES_128_GCM_SHA256,
TLS1_CK_ECDH_RSA_WITH_AES_128_GCM_SHA256,
SSL_kECDHr,
SSL_aECDH,
SSL_AES128GCM,
SSL_AEAD,
SSL_TLSV1_2,
SSL_NOT_EXP | SSL_HIGH | SSL_FIPS,
SSL_HANDSHAKE_MAC_SHA256 | TLS1_PRF_SHA256,
128,
128,
},
/* Cipher C032 */
{
1,
TLS1_TXT_ECDH_RSA_WITH_AES_256_GCM_SHA384,
TLS1_CK_ECDH_RSA_WITH_AES_256_GCM_SHA384,
SSL_kECDHr,
SSL_aECDH,
SSL_AES256GCM,
SSL_AEAD,
SSL_TLSV1_2,
SSL_NOT_EXP | SSL_HIGH | SSL_FIPS,
SSL_HANDSHAKE_MAC_SHA384 | TLS1_PRF_SHA384,
256,
256,
},
#endif /* OPENSSL_NO_ECDH */
#ifdef TEMP_GOST_TLS
/* Cipher FF00 */
{
1,
"GOST-MD5",
0x0300ff00,
SSL_kRSA,
SSL_aRSA,
SSL_eGOST2814789CNT,
SSL_MD5,
SSL_TLSV1,
SSL_NOT_EXP | SSL_HIGH,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
256,
256,
},
{
1,
"GOST-GOST94",
0x0300ff01,
SSL_kRSA,
SSL_aRSA,
SSL_eGOST2814789CNT,
SSL_GOST94,
SSL_TLSV1,
SSL_NOT_EXP | SSL_HIGH,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
256,
256},
{
1,
"GOST-GOST89MAC",
0x0300ff02,
SSL_kRSA,
SSL_aRSA,
SSL_eGOST2814789CNT,
SSL_GOST89MAC,
SSL_TLSV1,
SSL_NOT_EXP | SSL_HIGH,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF,
256,
256},
{
1,
"GOST-GOST89STREAM",
0x0300ff03,
SSL_kRSA,
SSL_aRSA,
SSL_eGOST2814789CNT,
SSL_GOST89MAC,
SSL_TLSV1,
SSL_NOT_EXP | SSL_HIGH,
SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF | TLS1_STREAM_MAC,
256,
256},
#endif
/* end of list */
};
SSL3_ENC_METHOD SSLv3_enc_data = {
ssl3_enc,
n_ssl3_mac,
ssl3_setup_key_block,
ssl3_generate_master_secret,
ssl3_change_cipher_state,
ssl3_final_finish_mac,
MD5_DIGEST_LENGTH + SHA_DIGEST_LENGTH,
ssl3_cert_verify_mac,
SSL3_MD_CLIENT_FINISHED_CONST, 4,
SSL3_MD_SERVER_FINISHED_CONST, 4,
ssl3_alert_code,
(int (*)(SSL *, unsigned char *, size_t, const char *,
size_t, const unsigned char *, size_t,
int use_context))ssl_undefined_function,
0,
SSL3_HM_HEADER_LENGTH,
ssl3_set_handshake_header,
ssl3_handshake_write
};
long ssl3_default_timeout(void)
{
/*
* 2 hours, the 24 hours mentioned in the SSLv3 spec is way too long for
* http, the cache would over fill
*/
return (60 * 60 * 2);
}
int ssl3_num_ciphers(void)
{
return (SSL3_NUM_CIPHERS);
}
const SSL_CIPHER *ssl3_get_cipher(unsigned int u)
{
if (u < SSL3_NUM_CIPHERS)
return (&(ssl3_ciphers[SSL3_NUM_CIPHERS - 1 - u]));
else
return (NULL);
}
int ssl3_pending(const SSL *s)
{
if (s->rstate == SSL_ST_READ_BODY)
return 0;
return (s->s3->rrec.type ==
SSL3_RT_APPLICATION_DATA) ? s->s3->rrec.length : 0;
}
void ssl3_set_handshake_header(SSL *s, int htype, unsigned long len)
{
unsigned char *p = (unsigned char *)s->init_buf->data;
*(p++) = htype;
l2n3(len, p);
s->init_num = (int)len + SSL3_HM_HEADER_LENGTH;
s->init_off = 0;
}
int ssl3_handshake_write(SSL *s)
{
return ssl3_do_write(s, SSL3_RT_HANDSHAKE);
}
int ssl3_new(SSL *s)
{
SSL3_STATE *s3;
- if ((s3 = OPENSSL_malloc(sizeof *s3)) == NULL)
+ if ((s3 = OPENSSL_malloc(sizeof(*s3))) == NULL)
goto err;
- memset(s3, 0, sizeof *s3);
+ memset(s3, 0, sizeof(*s3));
memset(s3->rrec.seq_num, 0, sizeof(s3->rrec.seq_num));
memset(s3->wrec.seq_num, 0, sizeof(s3->wrec.seq_num));
s->s3 = s3;
#ifndef OPENSSL_NO_SRP
SSL_SRP_CTX_init(s);
#endif
s->method->ssl_clear(s);
return (1);
err:
return (0);
}
void ssl3_free(SSL *s)
{
if (s == NULL || s->s3 == NULL)
return;
#ifdef TLSEXT_TYPE_opaque_prf_input
if (s->s3->client_opaque_prf_input != NULL)
OPENSSL_free(s->s3->client_opaque_prf_input);
if (s->s3->server_opaque_prf_input != NULL)
OPENSSL_free(s->s3->server_opaque_prf_input);
#endif
ssl3_cleanup_key_block(s);
if (s->s3->rbuf.buf != NULL)
ssl3_release_read_buffer(s);
if (s->s3->wbuf.buf != NULL)
ssl3_release_write_buffer(s);
if (s->s3->rrec.comp != NULL)
OPENSSL_free(s->s3->rrec.comp);
#ifndef OPENSSL_NO_DH
if (s->s3->tmp.dh != NULL)
DH_free(s->s3->tmp.dh);
#endif
#ifndef OPENSSL_NO_ECDH
if (s->s3->tmp.ecdh != NULL)
EC_KEY_free(s->s3->tmp.ecdh);
#endif
if (s->s3->tmp.ca_names != NULL)
sk_X509_NAME_pop_free(s->s3->tmp.ca_names, X509_NAME_free);
if (s->s3->handshake_buffer) {
BIO_free(s->s3->handshake_buffer);
}
if (s->s3->handshake_dgst)
ssl3_free_digest_list(s);
#ifndef OPENSSL_NO_TLSEXT
if (s->s3->alpn_selected)
OPENSSL_free(s->s3->alpn_selected);
#endif
#ifndef OPENSSL_NO_SRP
SSL_SRP_CTX_free(s);
#endif
- OPENSSL_cleanse(s->s3, sizeof *s->s3);
+ OPENSSL_cleanse(s->s3, sizeof(*s->s3));
OPENSSL_free(s->s3);
s->s3 = NULL;
}
void ssl3_clear(SSL *s)
{
unsigned char *rp, *wp;
size_t rlen, wlen;
int init_extra;
#ifdef TLSEXT_TYPE_opaque_prf_input
if (s->s3->client_opaque_prf_input != NULL)
OPENSSL_free(s->s3->client_opaque_prf_input);
s->s3->client_opaque_prf_input = NULL;
if (s->s3->server_opaque_prf_input != NULL)
OPENSSL_free(s->s3->server_opaque_prf_input);
s->s3->server_opaque_prf_input = NULL;
#endif
ssl3_cleanup_key_block(s);
if (s->s3->tmp.ca_names != NULL)
sk_X509_NAME_pop_free(s->s3->tmp.ca_names, X509_NAME_free);
if (s->s3->rrec.comp != NULL) {
OPENSSL_free(s->s3->rrec.comp);
s->s3->rrec.comp = NULL;
}
#ifndef OPENSSL_NO_DH
if (s->s3->tmp.dh != NULL) {
DH_free(s->s3->tmp.dh);
s->s3->tmp.dh = NULL;
}
#endif
#ifndef OPENSSL_NO_ECDH
if (s->s3->tmp.ecdh != NULL) {
EC_KEY_free(s->s3->tmp.ecdh);
s->s3->tmp.ecdh = NULL;
}
#endif
#ifndef OPENSSL_NO_TLSEXT
# ifndef OPENSSL_NO_EC
s->s3->is_probably_safari = 0;
# endif /* !OPENSSL_NO_EC */
#endif /* !OPENSSL_NO_TLSEXT */
rp = s->s3->rbuf.buf;
wp = s->s3->wbuf.buf;
rlen = s->s3->rbuf.len;
wlen = s->s3->wbuf.len;
init_extra = s->s3->init_extra;
if (s->s3->handshake_buffer) {
BIO_free(s->s3->handshake_buffer);
s->s3->handshake_buffer = NULL;
}
if (s->s3->handshake_dgst) {
ssl3_free_digest_list(s);
}
#if !defined(OPENSSL_NO_TLSEXT)
if (s->s3->alpn_selected) {
OPENSSL_free(s->s3->alpn_selected);
s->s3->alpn_selected = NULL;
}
#endif
- memset(s->s3, 0, sizeof *s->s3);
+ memset(s->s3, 0, sizeof(*s->s3));
s->s3->rbuf.buf = rp;
s->s3->wbuf.buf = wp;
s->s3->rbuf.len = rlen;
s->s3->wbuf.len = wlen;
s->s3->init_extra = init_extra;
ssl_free_wbio_buffer(s);
s->packet_length = 0;
s->s3->renegotiate = 0;
s->s3->total_renegotiations = 0;
s->s3->num_renegotiations = 0;
s->s3->in_read_app_data = 0;
s->version = SSL3_VERSION;
#if !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_NEXTPROTONEG)
if (s->next_proto_negotiated) {
OPENSSL_free(s->next_proto_negotiated);
s->next_proto_negotiated = NULL;
s->next_proto_negotiated_len = 0;
}
#endif
}
#ifndef OPENSSL_NO_SRP
static char *MS_CALLBACK srp_password_from_info_cb(SSL *s, void *arg)
{
return BUF_strdup(s->srp_ctx.info);
}
#endif
static int ssl3_set_req_cert_type(CERT *c, const unsigned char *p,
size_t len);
long ssl3_ctrl(SSL *s, int cmd, long larg, void *parg)
{
int ret = 0;
#if !defined(OPENSSL_NO_DSA) || !defined(OPENSSL_NO_RSA)
if (
# ifndef OPENSSL_NO_RSA
cmd == SSL_CTRL_SET_TMP_RSA || cmd == SSL_CTRL_SET_TMP_RSA_CB ||
# endif
# ifndef OPENSSL_NO_DSA
cmd == SSL_CTRL_SET_TMP_DH || cmd == SSL_CTRL_SET_TMP_DH_CB ||
# endif
0) {
if (!ssl_cert_inst(&s->cert)) {
SSLerr(SSL_F_SSL3_CTRL, ERR_R_MALLOC_FAILURE);
return (0);
}
}
#endif
switch (cmd) {
case SSL_CTRL_GET_SESSION_REUSED:
ret = s->hit;
break;
case SSL_CTRL_GET_CLIENT_CERT_REQUEST:
break;
case SSL_CTRL_GET_NUM_RENEGOTIATIONS:
ret = s->s3->num_renegotiations;
break;
case SSL_CTRL_CLEAR_NUM_RENEGOTIATIONS:
ret = s->s3->num_renegotiations;
s->s3->num_renegotiations = 0;
break;
case SSL_CTRL_GET_TOTAL_RENEGOTIATIONS:
ret = s->s3->total_renegotiations;
break;
case SSL_CTRL_GET_FLAGS:
ret = (int)(s->s3->flags);
break;
#ifndef OPENSSL_NO_RSA
case SSL_CTRL_NEED_TMP_RSA:
if ((s->cert != NULL) && (s->cert->rsa_tmp == NULL) &&
((s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey == NULL) ||
(EVP_PKEY_size(s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey) >
(512 / 8))))
ret = 1;
break;
case SSL_CTRL_SET_TMP_RSA:
{
RSA *rsa = (RSA *)parg;
if (rsa == NULL) {
SSLerr(SSL_F_SSL3_CTRL, ERR_R_PASSED_NULL_PARAMETER);
return (ret);
}
if ((rsa = RSAPrivateKey_dup(rsa)) == NULL) {
SSLerr(SSL_F_SSL3_CTRL, ERR_R_RSA_LIB);
return (ret);
}
if (s->cert->rsa_tmp != NULL)
RSA_free(s->cert->rsa_tmp);
s->cert->rsa_tmp = rsa;
ret = 1;
}
break;
case SSL_CTRL_SET_TMP_RSA_CB:
{
SSLerr(SSL_F_SSL3_CTRL, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
return (ret);
}
break;
#endif
#ifndef OPENSSL_NO_DH
case SSL_CTRL_SET_TMP_DH:
{
DH *dh = (DH *)parg;
if (dh == NULL) {
SSLerr(SSL_F_SSL3_CTRL, ERR_R_PASSED_NULL_PARAMETER);
return (ret);
}
if ((dh = DHparams_dup(dh)) == NULL) {
SSLerr(SSL_F_SSL3_CTRL, ERR_R_DH_LIB);
return (ret);
}
if (s->cert->dh_tmp != NULL)
DH_free(s->cert->dh_tmp);
s->cert->dh_tmp = dh;
ret = 1;
}
break;
case SSL_CTRL_SET_TMP_DH_CB:
{
SSLerr(SSL_F_SSL3_CTRL, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
return (ret);
}
break;
#endif
#ifndef OPENSSL_NO_ECDH
case SSL_CTRL_SET_TMP_ECDH:
{
EC_KEY *ecdh = NULL;
if (parg == NULL) {
SSLerr(SSL_F_SSL3_CTRL, ERR_R_PASSED_NULL_PARAMETER);
return (ret);
}
if (!EC_KEY_up_ref((EC_KEY *)parg)) {
SSLerr(SSL_F_SSL3_CTRL, ERR_R_ECDH_LIB);
return (ret);
}
ecdh = (EC_KEY *)parg;
if (!(s->options & SSL_OP_SINGLE_ECDH_USE)) {
if (!EC_KEY_generate_key(ecdh)) {
EC_KEY_free(ecdh);
SSLerr(SSL_F_SSL3_CTRL, ERR_R_ECDH_LIB);
return (ret);
}
}
if (s->cert->ecdh_tmp != NULL)
EC_KEY_free(s->cert->ecdh_tmp);
s->cert->ecdh_tmp = ecdh;
ret = 1;
}
break;
case SSL_CTRL_SET_TMP_ECDH_CB:
{
SSLerr(SSL_F_SSL3_CTRL, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
return (ret);
}
break;
#endif /* !OPENSSL_NO_ECDH */
#ifndef OPENSSL_NO_TLSEXT
case SSL_CTRL_SET_TLSEXT_HOSTNAME:
if (larg == TLSEXT_NAMETYPE_host_name) {
size_t len;
if (s->tlsext_hostname != NULL)
OPENSSL_free(s->tlsext_hostname);
s->tlsext_hostname = NULL;
ret = 1;
if (parg == NULL)
break;
len = strlen((char *)parg);
if (len == 0 || len > TLSEXT_MAXLEN_host_name) {
SSLerr(SSL_F_SSL3_CTRL, SSL_R_SSL3_EXT_INVALID_SERVERNAME);
return 0;
}
if ((s->tlsext_hostname = BUF_strdup((char *)parg)) == NULL) {
SSLerr(SSL_F_SSL3_CTRL, ERR_R_INTERNAL_ERROR);
return 0;
}
} else {
SSLerr(SSL_F_SSL3_CTRL, SSL_R_SSL3_EXT_INVALID_SERVERNAME_TYPE);
return 0;
}
break;
case SSL_CTRL_SET_TLSEXT_DEBUG_ARG:
s->tlsext_debug_arg = parg;
ret = 1;
break;
# ifdef TLSEXT_TYPE_opaque_prf_input
case SSL_CTRL_SET_TLSEXT_OPAQUE_PRF_INPUT:
if (larg > 12288) { /* actual internal limit is 2^16 for the
* complete hello message * (including the
* cert chain and everything) */
SSLerr(SSL_F_SSL3_CTRL, SSL_R_OPAQUE_PRF_INPUT_TOO_LONG);
break;
}
if (s->tlsext_opaque_prf_input != NULL)
OPENSSL_free(s->tlsext_opaque_prf_input);
if ((size_t)larg == 0)
s->tlsext_opaque_prf_input = OPENSSL_malloc(1); /* dummy byte
* just to get
* non-NULL */
else
s->tlsext_opaque_prf_input = BUF_memdup(parg, (size_t)larg);
if (s->tlsext_opaque_prf_input != NULL) {
s->tlsext_opaque_prf_input_len = (size_t)larg;
ret = 1;
} else
s->tlsext_opaque_prf_input_len = 0;
break;
# endif
case SSL_CTRL_SET_TLSEXT_STATUS_REQ_TYPE:
s->tlsext_status_type = larg;
ret = 1;
break;
case SSL_CTRL_GET_TLSEXT_STATUS_REQ_EXTS:
*(STACK_OF(X509_EXTENSION) **)parg = s->tlsext_ocsp_exts;
ret = 1;
break;
case SSL_CTRL_SET_TLSEXT_STATUS_REQ_EXTS:
s->tlsext_ocsp_exts = parg;
ret = 1;
break;
case SSL_CTRL_GET_TLSEXT_STATUS_REQ_IDS:
*(STACK_OF(OCSP_RESPID) **)parg = s->tlsext_ocsp_ids;
ret = 1;
break;
case SSL_CTRL_SET_TLSEXT_STATUS_REQ_IDS:
s->tlsext_ocsp_ids = parg;
ret = 1;
break;
case SSL_CTRL_GET_TLSEXT_STATUS_REQ_OCSP_RESP:
*(unsigned char **)parg = s->tlsext_ocsp_resp;
return s->tlsext_ocsp_resplen;
case SSL_CTRL_SET_TLSEXT_STATUS_REQ_OCSP_RESP:
if (s->tlsext_ocsp_resp)
OPENSSL_free(s->tlsext_ocsp_resp);
s->tlsext_ocsp_resp = parg;
s->tlsext_ocsp_resplen = larg;
ret = 1;
break;
# ifndef OPENSSL_NO_HEARTBEATS
case SSL_CTRL_TLS_EXT_SEND_HEARTBEAT:
if (SSL_IS_DTLS(s))
ret = dtls1_heartbeat(s);
else
ret = tls1_heartbeat(s);
break;
case SSL_CTRL_GET_TLS_EXT_HEARTBEAT_PENDING:
ret = s->tlsext_hb_pending;
break;
case SSL_CTRL_SET_TLS_EXT_HEARTBEAT_NO_REQUESTS:
if (larg)
s->tlsext_heartbeat |= SSL_TLSEXT_HB_DONT_RECV_REQUESTS;
else
s->tlsext_heartbeat &= ~SSL_TLSEXT_HB_DONT_RECV_REQUESTS;
ret = 1;
break;
# endif
#endif /* !OPENSSL_NO_TLSEXT */
case SSL_CTRL_CHAIN:
if (larg)
return ssl_cert_set1_chain(s->cert, (STACK_OF(X509) *)parg);
else
return ssl_cert_set0_chain(s->cert, (STACK_OF(X509) *)parg);
case SSL_CTRL_CHAIN_CERT:
if (larg)
return ssl_cert_add1_chain_cert(s->cert, (X509 *)parg);
else
return ssl_cert_add0_chain_cert(s->cert, (X509 *)parg);
case SSL_CTRL_GET_CHAIN_CERTS:
*(STACK_OF(X509) **)parg = s->cert->key->chain;
break;
case SSL_CTRL_SELECT_CURRENT_CERT:
return ssl_cert_select_current(s->cert, (X509 *)parg);
case SSL_CTRL_SET_CURRENT_CERT:
if (larg == SSL_CERT_SET_SERVER) {
CERT_PKEY *cpk;
const SSL_CIPHER *cipher;
if (!s->server)
return 0;
cipher = s->s3->tmp.new_cipher;
if (!cipher)
return 0;
/*
* No certificate for unauthenticated ciphersuites or using SRP
* authentication
*/
if (cipher->algorithm_auth & (SSL_aNULL | SSL_aSRP))
return 2;
cpk = ssl_get_server_send_pkey(s);
if (!cpk)
return 0;
s->cert->key = cpk;
return 1;
}
return ssl_cert_set_current(s->cert, larg);
#ifndef OPENSSL_NO_EC
case SSL_CTRL_GET_CURVES:
{
unsigned char *clist;
size_t clistlen;
if (!s->session)
return 0;
clist = s->session->tlsext_ellipticcurvelist;
clistlen = s->session->tlsext_ellipticcurvelist_length / 2;
if (parg) {
size_t i;
int *cptr = parg;
unsigned int cid, nid;
for (i = 0; i < clistlen; i++) {
n2s(clist, cid);
nid = tls1_ec_curve_id2nid(cid);
if (nid != 0)
cptr[i] = nid;
else
cptr[i] = TLSEXT_nid_unknown | cid;
}
}
return (int)clistlen;
}
case SSL_CTRL_SET_CURVES:
return tls1_set_curves(&s->tlsext_ellipticcurvelist,
&s->tlsext_ellipticcurvelist_length,
parg, larg);
case SSL_CTRL_SET_CURVES_LIST:
return tls1_set_curves_list(&s->tlsext_ellipticcurvelist,
&s->tlsext_ellipticcurvelist_length,
parg);
case SSL_CTRL_GET_SHARED_CURVE:
return tls1_shared_curve(s, larg);
# ifndef OPENSSL_NO_ECDH
case SSL_CTRL_SET_ECDH_AUTO:
s->cert->ecdh_tmp_auto = larg;
return 1;
# endif
#endif
case SSL_CTRL_SET_SIGALGS:
return tls1_set_sigalgs(s->cert, parg, larg, 0);
case SSL_CTRL_SET_SIGALGS_LIST:
return tls1_set_sigalgs_list(s->cert, parg, 0);
case SSL_CTRL_SET_CLIENT_SIGALGS:
return tls1_set_sigalgs(s->cert, parg, larg, 1);
case SSL_CTRL_SET_CLIENT_SIGALGS_LIST:
return tls1_set_sigalgs_list(s->cert, parg, 1);
case SSL_CTRL_GET_CLIENT_CERT_TYPES:
{
const unsigned char **pctype = parg;
if (s->server || !s->s3->tmp.cert_req)
return 0;
if (s->cert->ctypes) {
if (pctype)
*pctype = s->cert->ctypes;
return (int)s->cert->ctype_num;
}
if (pctype)
*pctype = (unsigned char *)s->s3->tmp.ctype;
return s->s3->tmp.ctype_num;
}
case SSL_CTRL_SET_CLIENT_CERT_TYPES:
if (!s->server)
return 0;
return ssl3_set_req_cert_type(s->cert, parg, larg);
case SSL_CTRL_BUILD_CERT_CHAIN:
return ssl_build_cert_chain(s->cert, s->ctx->cert_store, larg);
case SSL_CTRL_SET_VERIFY_CERT_STORE:
return ssl_cert_set_cert_store(s->cert, parg, 0, larg);
case SSL_CTRL_SET_CHAIN_CERT_STORE:
return ssl_cert_set_cert_store(s->cert, parg, 1, larg);
case SSL_CTRL_GET_PEER_SIGNATURE_NID:
if (SSL_USE_SIGALGS(s)) {
if (s->session && s->session->sess_cert) {
const EVP_MD *sig;
sig = s->session->sess_cert->peer_key->digest;
if (sig) {
*(int *)parg = EVP_MD_type(sig);
return 1;
}
}
return 0;
}
/* Might want to do something here for other versions */
else
return 0;
case SSL_CTRL_GET_SERVER_TMP_KEY:
if (s->server || !s->session || !s->session->sess_cert)
return 0;
else {
SESS_CERT *sc;
EVP_PKEY *ptmp;
int rv = 0;
sc = s->session->sess_cert;
#if !defined(OPENSSL_NO_RSA) && !defined(OPENSSL_NO_DH) && !defined(OPENSSL_NO_EC) && !defined(OPENSSL_NO_ECDH)
if (!sc->peer_rsa_tmp && !sc->peer_dh_tmp && !sc->peer_ecdh_tmp)
return 0;
#endif
ptmp = EVP_PKEY_new();
if (!ptmp)
return 0;
if (0) ;
#ifndef OPENSSL_NO_RSA
else if (sc->peer_rsa_tmp)
rv = EVP_PKEY_set1_RSA(ptmp, sc->peer_rsa_tmp);
#endif
#ifndef OPENSSL_NO_DH
else if (sc->peer_dh_tmp)
rv = EVP_PKEY_set1_DH(ptmp, sc->peer_dh_tmp);
#endif
#ifndef OPENSSL_NO_ECDH
else if (sc->peer_ecdh_tmp)
rv = EVP_PKEY_set1_EC_KEY(ptmp, sc->peer_ecdh_tmp);
#endif
if (rv) {
*(EVP_PKEY **)parg = ptmp;
return 1;
}
EVP_PKEY_free(ptmp);
return 0;
}
#ifndef OPENSSL_NO_EC
case SSL_CTRL_GET_EC_POINT_FORMATS:
{
SSL_SESSION *sess = s->session;
const unsigned char **pformat = parg;
if (!sess || !sess->tlsext_ecpointformatlist)
return 0;
*pformat = sess->tlsext_ecpointformatlist;
return (int)sess->tlsext_ecpointformatlist_length;
}
#endif
case SSL_CTRL_CHECK_PROTO_VERSION:
/*
* For library-internal use; checks 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 == SSLv23_method()->version) {
#if TLS_MAX_VERSION != TLS1_2_VERSION
# error Code needs update for SSLv23_method() support beyond TLS1_2_VERSION.
#endif
if (!(s->options & SSL_OP_NO_TLSv1_2))
return s->version == TLS1_2_VERSION;
if (!(s->options & SSL_OP_NO_TLSv1_1))
return s->version == TLS1_1_VERSION;
if (!(s->options & SSL_OP_NO_TLSv1))
return s->version == TLS1_VERSION;
if (!(s->options & SSL_OP_NO_SSLv3))
return s->version == SSL3_VERSION;
if (!(s->options & SSL_OP_NO_SSLv2))
return s->version == SSL2_VERSION;
}
return 0; /* Unexpected state; fail closed. */
default:
break;
}
return (ret);
}
long ssl3_callback_ctrl(SSL *s, int cmd, void (*fp) (void))
{
int ret = 0;
#if !defined(OPENSSL_NO_DSA) || !defined(OPENSSL_NO_RSA)
if (
# ifndef OPENSSL_NO_RSA
cmd == SSL_CTRL_SET_TMP_RSA_CB ||
# endif
# ifndef OPENSSL_NO_DSA
cmd == SSL_CTRL_SET_TMP_DH_CB ||
# endif
0) {
if (!ssl_cert_inst(&s->cert)) {
SSLerr(SSL_F_SSL3_CALLBACK_CTRL, ERR_R_MALLOC_FAILURE);
return (0);
}
}
#endif
switch (cmd) {
#ifndef OPENSSL_NO_RSA
case SSL_CTRL_SET_TMP_RSA_CB:
{
s->cert->rsa_tmp_cb = (RSA *(*)(SSL *, int, int))fp;
}
break;
#endif
#ifndef OPENSSL_NO_DH
case SSL_CTRL_SET_TMP_DH_CB:
{
s->cert->dh_tmp_cb = (DH *(*)(SSL *, int, int))fp;
}
break;
#endif
#ifndef OPENSSL_NO_ECDH
case SSL_CTRL_SET_TMP_ECDH_CB:
{
s->cert->ecdh_tmp_cb = (EC_KEY *(*)(SSL *, int, int))fp;
}
break;
#endif
#ifndef OPENSSL_NO_TLSEXT
case SSL_CTRL_SET_TLSEXT_DEBUG_CB:
s->tlsext_debug_cb = (void (*)(SSL *, int, int,
unsigned char *, int, void *))fp;
break;
#endif
default:
break;
}
return (ret);
}
long ssl3_ctx_ctrl(SSL_CTX *ctx, int cmd, long larg, void *parg)
{
CERT *cert;
cert = ctx->cert;
switch (cmd) {
#ifndef OPENSSL_NO_RSA
case SSL_CTRL_NEED_TMP_RSA:
if ((cert->rsa_tmp == NULL) &&
((cert->pkeys[SSL_PKEY_RSA_ENC].privatekey == NULL) ||
(EVP_PKEY_size(cert->pkeys[SSL_PKEY_RSA_ENC].privatekey) >
(512 / 8)))
)
return (1);
else
return (0);
/* break; */
case SSL_CTRL_SET_TMP_RSA:
{
RSA *rsa;
int i;
rsa = (RSA *)parg;
i = 1;
if (rsa == NULL)
i = 0;
else {
if ((rsa = RSAPrivateKey_dup(rsa)) == NULL)
i = 0;
}
if (!i) {
SSLerr(SSL_F_SSL3_CTX_CTRL, ERR_R_RSA_LIB);
return (0);
} else {
if (cert->rsa_tmp != NULL)
RSA_free(cert->rsa_tmp);
cert->rsa_tmp = rsa;
return (1);
}
}
/* break; */
case SSL_CTRL_SET_TMP_RSA_CB:
{
SSLerr(SSL_F_SSL3_CTX_CTRL, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
return (0);
}
break;
#endif
#ifndef OPENSSL_NO_DH
case SSL_CTRL_SET_TMP_DH:
{
DH *new = NULL, *dh;
dh = (DH *)parg;
if ((new = DHparams_dup(dh)) == NULL) {
SSLerr(SSL_F_SSL3_CTX_CTRL, ERR_R_DH_LIB);
return 0;
}
if (cert->dh_tmp != NULL)
DH_free(cert->dh_tmp);
cert->dh_tmp = new;
return 1;
}
/*
* break;
*/
case SSL_CTRL_SET_TMP_DH_CB:
{
SSLerr(SSL_F_SSL3_CTX_CTRL, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
return (0);
}
break;
#endif
#ifndef OPENSSL_NO_ECDH
case SSL_CTRL_SET_TMP_ECDH:
{
EC_KEY *ecdh = NULL;
if (parg == NULL) {
SSLerr(SSL_F_SSL3_CTX_CTRL, ERR_R_ECDH_LIB);
return 0;
}
ecdh = EC_KEY_dup((EC_KEY *)parg);
if (ecdh == NULL) {
SSLerr(SSL_F_SSL3_CTX_CTRL, ERR_R_EC_LIB);
return 0;
}
if (!(ctx->options & SSL_OP_SINGLE_ECDH_USE)) {
if (!EC_KEY_generate_key(ecdh)) {
EC_KEY_free(ecdh);
SSLerr(SSL_F_SSL3_CTX_CTRL, ERR_R_ECDH_LIB);
return 0;
}
}
if (cert->ecdh_tmp != NULL) {
EC_KEY_free(cert->ecdh_tmp);
}
cert->ecdh_tmp = ecdh;
return 1;
}
/* break; */
case SSL_CTRL_SET_TMP_ECDH_CB:
{
SSLerr(SSL_F_SSL3_CTX_CTRL, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
return (0);
}
break;
#endif /* !OPENSSL_NO_ECDH */
#ifndef OPENSSL_NO_TLSEXT
case SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG:
ctx->tlsext_servername_arg = parg;
break;
case SSL_CTRL_SET_TLSEXT_TICKET_KEYS:
case SSL_CTRL_GET_TLSEXT_TICKET_KEYS:
{
unsigned char *keys = parg;
if (!keys)
return 48;
if (larg != 48) {
SSLerr(SSL_F_SSL3_CTX_CTRL, SSL_R_INVALID_TICKET_KEYS_LENGTH);
return 0;
}
if (cmd == SSL_CTRL_SET_TLSEXT_TICKET_KEYS) {
memcpy(ctx->tlsext_tick_key_name, keys, 16);
memcpy(ctx->tlsext_tick_hmac_key, keys + 16, 16);
memcpy(ctx->tlsext_tick_aes_key, keys + 32, 16);
} else {
memcpy(keys, ctx->tlsext_tick_key_name, 16);
memcpy(keys + 16, ctx->tlsext_tick_hmac_key, 16);
memcpy(keys + 32, ctx->tlsext_tick_aes_key, 16);
}
return 1;
}
# ifdef TLSEXT_TYPE_opaque_prf_input
case SSL_CTRL_SET_TLSEXT_OPAQUE_PRF_INPUT_CB_ARG:
ctx->tlsext_opaque_prf_input_callback_arg = parg;
return 1;
# endif
case SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB_ARG:
ctx->tlsext_status_arg = parg;
return 1;
break;
# ifndef OPENSSL_NO_SRP
case SSL_CTRL_SET_TLS_EXT_SRP_USERNAME:
ctx->srp_ctx.srp_Mask |= SSL_kSRP;
if (ctx->srp_ctx.login != NULL)
OPENSSL_free(ctx->srp_ctx.login);
ctx->srp_ctx.login = NULL;
if (parg == NULL)
break;
if (strlen((const char *)parg) > 255
|| strlen((const char *)parg) < 1) {
SSLerr(SSL_F_SSL3_CTX_CTRL, SSL_R_INVALID_SRP_USERNAME);
return 0;
}
if ((ctx->srp_ctx.login = BUF_strdup((char *)parg)) == NULL) {
SSLerr(SSL_F_SSL3_CTX_CTRL, ERR_R_INTERNAL_ERROR);
return 0;
}
break;
case SSL_CTRL_SET_TLS_EXT_SRP_PASSWORD:
ctx->srp_ctx.SRP_give_srp_client_pwd_callback =
srp_password_from_info_cb;
ctx->srp_ctx.info = parg;
break;
case SSL_CTRL_SET_SRP_ARG:
ctx->srp_ctx.srp_Mask |= SSL_kSRP;
ctx->srp_ctx.SRP_cb_arg = parg;
break;
case SSL_CTRL_SET_TLS_EXT_SRP_STRENGTH:
ctx->srp_ctx.strength = larg;
break;
# endif
# ifndef OPENSSL_NO_EC
case SSL_CTRL_SET_CURVES:
return tls1_set_curves(&ctx->tlsext_ellipticcurvelist,
&ctx->tlsext_ellipticcurvelist_length,
parg, larg);
case SSL_CTRL_SET_CURVES_LIST:
return tls1_set_curves_list(&ctx->tlsext_ellipticcurvelist,
&ctx->tlsext_ellipticcurvelist_length,
parg);
# ifndef OPENSSL_NO_ECDH
case SSL_CTRL_SET_ECDH_AUTO:
ctx->cert->ecdh_tmp_auto = larg;
return 1;
# endif
# endif
case SSL_CTRL_SET_SIGALGS:
return tls1_set_sigalgs(ctx->cert, parg, larg, 0);
case SSL_CTRL_SET_SIGALGS_LIST:
return tls1_set_sigalgs_list(ctx->cert, parg, 0);
case SSL_CTRL_SET_CLIENT_SIGALGS:
return tls1_set_sigalgs(ctx->cert, parg, larg, 1);
case SSL_CTRL_SET_CLIENT_SIGALGS_LIST:
return tls1_set_sigalgs_list(ctx->cert, parg, 1);
case SSL_CTRL_SET_CLIENT_CERT_TYPES:
return ssl3_set_req_cert_type(ctx->cert, parg, larg);
case SSL_CTRL_BUILD_CERT_CHAIN:
return ssl_build_cert_chain(ctx->cert, ctx->cert_store, larg);
case SSL_CTRL_SET_VERIFY_CERT_STORE:
return ssl_cert_set_cert_store(ctx->cert, parg, 0, larg);
case SSL_CTRL_SET_CHAIN_CERT_STORE:
return ssl_cert_set_cert_store(ctx->cert, parg, 1, larg);
#endif /* !OPENSSL_NO_TLSEXT */
/* A Thawte special :-) */
case SSL_CTRL_EXTRA_CHAIN_CERT:
if (ctx->extra_certs == NULL) {
if ((ctx->extra_certs = sk_X509_new_null()) == NULL)
return (0);
}
sk_X509_push(ctx->extra_certs, (X509 *)parg);
break;
case SSL_CTRL_GET_EXTRA_CHAIN_CERTS:
if (ctx->extra_certs == NULL && larg == 0)
*(STACK_OF(X509) **)parg = ctx->cert->key->chain;
else
*(STACK_OF(X509) **)parg = ctx->extra_certs;
break;
case SSL_CTRL_CLEAR_EXTRA_CHAIN_CERTS:
if (ctx->extra_certs) {
sk_X509_pop_free(ctx->extra_certs, X509_free);
ctx->extra_certs = NULL;
}
break;
case SSL_CTRL_CHAIN:
if (larg)
return ssl_cert_set1_chain(ctx->cert, (STACK_OF(X509) *)parg);
else
return ssl_cert_set0_chain(ctx->cert, (STACK_OF(X509) *)parg);
case SSL_CTRL_CHAIN_CERT:
if (larg)
return ssl_cert_add1_chain_cert(ctx->cert, (X509 *)parg);
else
return ssl_cert_add0_chain_cert(ctx->cert, (X509 *)parg);
case SSL_CTRL_GET_CHAIN_CERTS:
*(STACK_OF(X509) **)parg = ctx->cert->key->chain;
break;
case SSL_CTRL_SELECT_CURRENT_CERT:
return ssl_cert_select_current(ctx->cert, (X509 *)parg);
case SSL_CTRL_SET_CURRENT_CERT:
return ssl_cert_set_current(ctx->cert, larg);
default:
return (0);
}
return (1);
}
long ssl3_ctx_callback_ctrl(SSL_CTX *ctx, int cmd, void (*fp) (void))
{
CERT *cert;
cert = ctx->cert;
switch (cmd) {
#ifndef OPENSSL_NO_RSA
case SSL_CTRL_SET_TMP_RSA_CB:
{
cert->rsa_tmp_cb = (RSA *(*)(SSL *, int, int))fp;
}
break;
#endif
#ifndef OPENSSL_NO_DH
case SSL_CTRL_SET_TMP_DH_CB:
{
cert->dh_tmp_cb = (DH *(*)(SSL *, int, int))fp;
}
break;
#endif
#ifndef OPENSSL_NO_ECDH
case SSL_CTRL_SET_TMP_ECDH_CB:
{
cert->ecdh_tmp_cb = (EC_KEY *(*)(SSL *, int, int))fp;
}
break;
#endif
#ifndef OPENSSL_NO_TLSEXT
case SSL_CTRL_SET_TLSEXT_SERVERNAME_CB:
ctx->tlsext_servername_callback = (int (*)(SSL *, int *, void *))fp;
break;
# ifdef TLSEXT_TYPE_opaque_prf_input
case SSL_CTRL_SET_TLSEXT_OPAQUE_PRF_INPUT_CB:
ctx->tlsext_opaque_prf_input_callback =
(int (*)(SSL *, void *, size_t, void *))fp;
break;
# endif
case SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB:
ctx->tlsext_status_cb = (int (*)(SSL *, void *))fp;
break;
case SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB:
ctx->tlsext_ticket_key_cb = (int (*)(SSL *, unsigned char *,
unsigned char *,
EVP_CIPHER_CTX *,
HMAC_CTX *, int))fp;
break;
# ifndef OPENSSL_NO_SRP
case SSL_CTRL_SET_SRP_VERIFY_PARAM_CB:
ctx->srp_ctx.srp_Mask |= SSL_kSRP;
ctx->srp_ctx.SRP_verify_param_callback = (int (*)(SSL *, void *))fp;
break;
case SSL_CTRL_SET_TLS_EXT_SRP_USERNAME_CB:
ctx->srp_ctx.srp_Mask |= SSL_kSRP;
ctx->srp_ctx.TLS_ext_srp_username_callback =
(int (*)(SSL *, int *, void *))fp;
break;
case SSL_CTRL_SET_SRP_GIVE_CLIENT_PWD_CB:
ctx->srp_ctx.srp_Mask |= SSL_kSRP;
ctx->srp_ctx.SRP_give_srp_client_pwd_callback =
(char *(*)(SSL *, void *))fp;
break;
# endif
#endif
default:
return (0);
}
return (1);
}
/*
* This function needs to check if the ciphers required are actually
* available
*/
const SSL_CIPHER *ssl3_get_cipher_by_char(const unsigned char *p)
{
SSL_CIPHER c;
const SSL_CIPHER *cp;
unsigned long id;
id = 0x03000000L | ((unsigned long)p[0] << 8L) | (unsigned long)p[1];
c.id = id;
cp = OBJ_bsearch_ssl_cipher_id(&c, ssl3_ciphers, SSL3_NUM_CIPHERS);
#ifdef DEBUG_PRINT_UNKNOWN_CIPHERSUITES
if (cp == NULL)
fprintf(stderr, "Unknown cipher ID %x\n", (p[0] << 8) | p[1]);
#endif
return cp;
}
int ssl3_put_cipher_by_char(const SSL_CIPHER *c, unsigned char *p)
{
long l;
if (p != NULL) {
l = c->id;
if ((l & 0xff000000) != 0x03000000)
return (0);
p[0] = ((unsigned char)(l >> 8L)) & 0xFF;
p[1] = ((unsigned char)(l)) & 0xFF;
}
return (2);
}
SSL_CIPHER *ssl3_choose_cipher(SSL *s, STACK_OF(SSL_CIPHER) *clnt,
STACK_OF(SSL_CIPHER) *srvr)
{
SSL_CIPHER *c, *ret = NULL;
STACK_OF(SSL_CIPHER) *prio, *allow;
int i, ii, ok;
CERT *cert;
unsigned long alg_k, alg_a, mask_k, mask_a, emask_k, emask_a;
/* Let's see which ciphers we can support */
cert = s->cert;
#if 0
/*
* Do not set the compare functions, because this may lead to a
* reordering by "id". We want to keep the original ordering. We may pay
* a price in performance during sk_SSL_CIPHER_find(), but would have to
* pay with the price of sk_SSL_CIPHER_dup().
*/
sk_SSL_CIPHER_set_cmp_func(srvr, ssl_cipher_ptr_id_cmp);
sk_SSL_CIPHER_set_cmp_func(clnt, ssl_cipher_ptr_id_cmp);
#endif
#ifdef CIPHER_DEBUG
fprintf(stderr, "Server has %d from %p:\n", sk_SSL_CIPHER_num(srvr),
(void *)srvr);
for (i = 0; i < sk_SSL_CIPHER_num(srvr); ++i) {
c = sk_SSL_CIPHER_value(srvr, i);
fprintf(stderr, "%p:%s\n", (void *)c, c->name);
}
fprintf(stderr, "Client sent %d from %p:\n", sk_SSL_CIPHER_num(clnt),
(void *)clnt);
for (i = 0; i < sk_SSL_CIPHER_num(clnt); ++i) {
c = sk_SSL_CIPHER_value(clnt, i);
fprintf(stderr, "%p:%s\n", (void *)c, c->name);
}
#endif
if (s->options & SSL_OP_CIPHER_SERVER_PREFERENCE || tls1_suiteb(s)) {
prio = srvr;
allow = clnt;
} else {
prio = clnt;
allow = srvr;
}
tls1_set_cert_validity(s);
for (i = 0; i < sk_SSL_CIPHER_num(prio); i++) {
c = sk_SSL_CIPHER_value(prio, i);
/* Skip TLS v1.2 only ciphersuites if not supported */
if ((c->algorithm_ssl & SSL_TLSV1_2) && !SSL_USE_TLS1_2_CIPHERS(s))
continue;
ssl_set_cert_masks(cert, c);
mask_k = cert->mask_k;
mask_a = cert->mask_a;
emask_k = cert->export_mask_k;
emask_a = cert->export_mask_a;
#ifndef OPENSSL_NO_SRP
if (s->srp_ctx.srp_Mask & SSL_kSRP) {
mask_k |= SSL_kSRP;
emask_k |= SSL_kSRP;
mask_a |= SSL_aSRP;
emask_a |= SSL_aSRP;
}
#endif
#ifdef KSSL_DEBUG
/*
* fprintf(stderr,"ssl3_choose_cipher %d alg= %lx\n",
* i,c->algorithms);
*/
#endif /* KSSL_DEBUG */
alg_k = c->algorithm_mkey;
alg_a = c->algorithm_auth;
#ifndef OPENSSL_NO_KRB5
if (alg_k & SSL_kKRB5) {
if (!kssl_keytab_is_available(s->kssl_ctx))
continue;
}
#endif /* OPENSSL_NO_KRB5 */
#ifndef OPENSSL_NO_PSK
/* with PSK there must be server callback set */
if ((alg_k & SSL_kPSK) && s->psk_server_callback == NULL)
continue;
#endif /* OPENSSL_NO_PSK */
if (SSL_C_IS_EXPORT(c)) {
ok = (alg_k & emask_k) && (alg_a & emask_a);
#ifdef CIPHER_DEBUG
fprintf(stderr, "%d:[%08lX:%08lX:%08lX:%08lX]%p:%s (export)\n",
ok, alg_k, alg_a, emask_k, emask_a, (void *)c, c->name);
#endif
} else {
ok = (alg_k & mask_k) && (alg_a & mask_a);
#ifdef CIPHER_DEBUG
fprintf(stderr, "%d:[%08lX:%08lX:%08lX:%08lX]%p:%s\n", ok, alg_k,
alg_a, mask_k, mask_a, (void *)c, c->name);
#endif
}
#ifndef OPENSSL_NO_TLSEXT
# ifndef OPENSSL_NO_EC
# ifndef OPENSSL_NO_ECDH
/*
* if we are considering an ECC cipher suite that uses an ephemeral
* EC key check it
*/
if (alg_k & SSL_kEECDH)
ok = ok && tls1_check_ec_tmp_key(s, c->id);
# endif /* OPENSSL_NO_ECDH */
# endif /* OPENSSL_NO_EC */
#endif /* OPENSSL_NO_TLSEXT */
if (!ok)
continue;
ii = sk_SSL_CIPHER_find(allow, c);
if (ii >= 0) {
#if !defined(OPENSSL_NO_EC) && !defined(OPENSSL_NO_TLSEXT)
if ((alg_k & SSL_kEECDH) && (alg_a & SSL_aECDSA)
&& s->s3->is_probably_safari) {
if (!ret)
ret = sk_SSL_CIPHER_value(allow, ii);
continue;
}
#endif
ret = sk_SSL_CIPHER_value(allow, ii);
break;
}
}
return (ret);
}
int ssl3_get_req_cert_type(SSL *s, unsigned char *p)
{
int ret = 0;
const unsigned char *sig;
size_t i, siglen;
int have_rsa_sign = 0, have_dsa_sign = 0;
#ifndef OPENSSL_NO_ECDSA
int have_ecdsa_sign = 0;
#endif
int nostrict = 1;
unsigned long alg_k;
/* If we have custom certificate types set, use them */
if (s->cert->ctypes) {
memcpy(p, s->cert->ctypes, s->cert->ctype_num);
return (int)s->cert->ctype_num;
}
/* get configured sigalgs */
siglen = tls12_get_psigalgs(s, 1, &sig);
if (s->cert->cert_flags & SSL_CERT_FLAGS_CHECK_TLS_STRICT)
nostrict = 0;
for (i = 0; i < siglen; i += 2, sig += 2) {
switch (sig[1]) {
case TLSEXT_signature_rsa:
have_rsa_sign = 1;
break;
case TLSEXT_signature_dsa:
have_dsa_sign = 1;
break;
#ifndef OPENSSL_NO_ECDSA
case TLSEXT_signature_ecdsa:
have_ecdsa_sign = 1;
break;
#endif
}
}
alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
#ifndef OPENSSL_NO_GOST
if (s->version >= TLS1_VERSION) {
if (alg_k & SSL_kGOST) {
p[ret++] = TLS_CT_GOST94_SIGN;
p[ret++] = TLS_CT_GOST01_SIGN;
return (ret);
}
}
#endif
#ifndef OPENSSL_NO_DH
if (alg_k & (SSL_kDHr | SSL_kEDH)) {
# ifndef OPENSSL_NO_RSA
/*
* Since this refers to a certificate signed with an RSA algorithm,
* only check for rsa signing in strict mode.
*/
if (nostrict || have_rsa_sign)
p[ret++] = SSL3_CT_RSA_FIXED_DH;
# endif
# ifndef OPENSSL_NO_DSA
if (nostrict || have_dsa_sign)
p[ret++] = SSL3_CT_DSS_FIXED_DH;
# endif
}
if ((s->version == SSL3_VERSION) &&
(alg_k & (SSL_kEDH | SSL_kDHd | SSL_kDHr))) {
# ifndef OPENSSL_NO_RSA
p[ret++] = SSL3_CT_RSA_EPHEMERAL_DH;
# endif
# ifndef OPENSSL_NO_DSA
p[ret++] = SSL3_CT_DSS_EPHEMERAL_DH;
# endif
}
#endif /* !OPENSSL_NO_DH */
#ifndef OPENSSL_NO_RSA
if (have_rsa_sign)
p[ret++] = SSL3_CT_RSA_SIGN;
#endif
#ifndef OPENSSL_NO_DSA
if (have_dsa_sign)
p[ret++] = SSL3_CT_DSS_SIGN;
#endif
#ifndef OPENSSL_NO_ECDH
if ((alg_k & (SSL_kECDHr | SSL_kECDHe)) && (s->version >= TLS1_VERSION)) {
if (nostrict || have_rsa_sign)
p[ret++] = TLS_CT_RSA_FIXED_ECDH;
if (nostrict || have_ecdsa_sign)
p[ret++] = TLS_CT_ECDSA_FIXED_ECDH;
}
#endif
#ifndef OPENSSL_NO_ECDSA
/*
* ECDSA certs can be used with RSA cipher suites as well so we don't
* need to check for SSL_kECDH or SSL_kEECDH
*/
if (s->version >= TLS1_VERSION) {
if (have_ecdsa_sign)
p[ret++] = TLS_CT_ECDSA_SIGN;
}
#endif
return (ret);
}
static int ssl3_set_req_cert_type(CERT *c, const unsigned char *p, size_t len)
{
if (c->ctypes) {
OPENSSL_free(c->ctypes);
c->ctypes = NULL;
}
if (!p || !len)
return 1;
if (len > 0xff)
return 0;
c->ctypes = OPENSSL_malloc(len);
if (!c->ctypes)
return 0;
memcpy(c->ctypes, p, len);
c->ctype_num = len;
return 1;
}
int ssl3_shutdown(SSL *s)
{
int ret;
/*
* Don't do anything much if we have not done the handshake or we don't
* want to send messages :-)
*/
if ((s->quiet_shutdown) || (s->state == SSL_ST_BEFORE)) {
s->shutdown = (SSL_SENT_SHUTDOWN | SSL_RECEIVED_SHUTDOWN);
return (1);
}
if (!(s->shutdown & SSL_SENT_SHUTDOWN)) {
s->shutdown |= SSL_SENT_SHUTDOWN;
#if 1
ssl3_send_alert(s, SSL3_AL_WARNING, SSL_AD_CLOSE_NOTIFY);
#endif
/*
* our shutdown alert has been sent now, and if it still needs to be
* written, s->s3->alert_dispatch will be true
*/
if (s->s3->alert_dispatch)
return (-1); /* return WANT_WRITE */
} else if (s->s3->alert_dispatch) {
/* resend it if not sent */
#if 1
ret = s->method->ssl_dispatch_alert(s);
if (ret == -1) {
/*
* we only get to return -1 here the 2nd/Nth invocation, we must
* have already signalled return 0 upon a previous invoation,
* return WANT_WRITE
*/
return (ret);
}
#endif
} else if (!(s->shutdown & SSL_RECEIVED_SHUTDOWN)) {
/*
* If we are waiting for a close from our peer, we are closed
*/
s->method->ssl_read_bytes(s, 0, NULL, 0, 0);
if (!(s->shutdown & SSL_RECEIVED_SHUTDOWN)) {
return (-1); /* return WANT_READ */
}
}
if ((s->shutdown == (SSL_SENT_SHUTDOWN | SSL_RECEIVED_SHUTDOWN)) &&
!s->s3->alert_dispatch)
return (1);
else
return (0);
}
int ssl3_write(SSL *s, const void *buf, int len)
{
int ret, n;
#if 0
if (s->shutdown & SSL_SEND_SHUTDOWN) {
s->rwstate = SSL_NOTHING;
return (0);
}
#endif
clear_sys_error();
if (s->s3->renegotiate)
ssl3_renegotiate_check(s);
/*
* This is an experimental flag that sends the last handshake message in
* the same packet as the first use data - used to see if it helps the
* TCP protocol during session-id reuse
*/
/* The second test is because the buffer may have been removed */
if ((s->s3->flags & SSL3_FLAGS_POP_BUFFER) && (s->wbio == s->bbio)) {
/* First time through, we write into the buffer */
if (s->s3->delay_buf_pop_ret == 0) {
ret = ssl3_write_bytes(s, SSL3_RT_APPLICATION_DATA, buf, len);
if (ret <= 0)
return (ret);
s->s3->delay_buf_pop_ret = ret;
}
s->rwstate = SSL_WRITING;
n = BIO_flush(s->wbio);
if (n <= 0)
return (n);
s->rwstate = SSL_NOTHING;
/* We have flushed the buffer, so remove it */
ssl_free_wbio_buffer(s);
s->s3->flags &= ~SSL3_FLAGS_POP_BUFFER;
ret = s->s3->delay_buf_pop_ret;
s->s3->delay_buf_pop_ret = 0;
} else {
ret = s->method->ssl_write_bytes(s, SSL3_RT_APPLICATION_DATA,
buf, len);
if (ret <= 0)
return (ret);
}
return (ret);
}
static int ssl3_read_internal(SSL *s, void *buf, int len, int peek)
{
int ret;
clear_sys_error();
if (s->s3->renegotiate)
ssl3_renegotiate_check(s);
s->s3->in_read_app_data = 1;
ret =
s->method->ssl_read_bytes(s, SSL3_RT_APPLICATION_DATA, buf, len,
peek);
if ((ret == -1) && (s->s3->in_read_app_data == 2)) {
/*
* ssl3_read_bytes decided to call s->handshake_func, which called
* ssl3_read_bytes to read handshake data. However, ssl3_read_bytes
* actually found application data and thinks that application data
* makes sense here; so disable handshake processing and try to read
* application data again.
*/
s->in_handshake++;
ret =
s->method->ssl_read_bytes(s, SSL3_RT_APPLICATION_DATA, buf, len,
peek);
s->in_handshake--;
} else
s->s3->in_read_app_data = 0;
return (ret);
}
int ssl3_read(SSL *s, void *buf, int len)
{
return ssl3_read_internal(s, buf, len, 0);
}
int ssl3_peek(SSL *s, void *buf, int len)
{
return ssl3_read_internal(s, buf, len, 1);
}
int ssl3_renegotiate(SSL *s)
{
if (s->handshake_func == NULL)
return (1);
if (s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS)
return (0);
s->s3->renegotiate = 1;
return (1);
}
int ssl3_renegotiate_check(SSL *s)
{
int ret = 0;
if (s->s3->renegotiate) {
if ((s->s3->rbuf.left == 0) &&
(s->s3->wbuf.left == 0) && !SSL_in_init(s)) {
/*
* if we are the server, and we have sent a 'RENEGOTIATE'
* message, we need to go to SSL_ST_ACCEPT.
*/
/* SSL_ST_ACCEPT */
s->state = SSL_ST_RENEGOTIATE;
s->s3->renegotiate = 0;
s->s3->num_renegotiations++;
s->s3->total_renegotiations++;
ret = 1;
}
}
return (ret);
}
/*
* If we are using default SHA1+MD5 algorithms switch to new SHA256 PRF and
* handshake macs if required.
*/
long ssl_get_algorithm2(SSL *s)
{
long alg2;
if (s->s3 == NULL || s->s3->tmp.new_cipher == NULL)
return -1;
alg2 = s->s3->tmp.new_cipher->algorithm2;
if (s->method->ssl3_enc->enc_flags & SSL_ENC_FLAG_SHA256_PRF
&& alg2 == (SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF))
return SSL_HANDSHAKE_MAC_SHA256 | TLS1_PRF_SHA256;
return alg2;
}
diff --git a/ssl/s3_pkt.c b/ssl/s3_pkt.c
index b91456843041..6527df8ce228 100644
--- a/ssl/s3_pkt.c
+++ b/ssl/s3_pkt.c
@@ -1,1773 +1,1771 @@
/* ssl/s3_pkt.c */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
/* ====================================================================
- * Copyright (c) 1998-2002 The OpenSSL Project. All rights reserved.
+ * Copyright (c) 1998-2018 The OpenSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* openssl-core@openssl.org.
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.openssl.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*
* This product includes cryptographic software written by Eric Young
* (eay@cryptsoft.com). This product includes software written by Tim
* Hudson (tjh@cryptsoft.com).
*
*/
#include <stdio.h>
#include <limits.h>
#include <errno.h>
#define USE_SOCKETS
#include "ssl_locl.h"
#include <openssl/evp.h>
#include <openssl/buffer.h>
#include <openssl/rand.h>
#ifndef EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK
# define EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK 0
#endif
#if defined(OPENSSL_SMALL_FOOTPRINT) || \
!( defined(AES_ASM) && ( \
defined(__x86_64) || defined(__x86_64__) || \
defined(_M_AMD64) || defined(_M_X64) || \
defined(__INTEL__) ) \
)
# undef EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK
# define EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK 0
#endif
static int do_ssl3_write(SSL *s, int type, const unsigned char *buf,
unsigned int len, int create_empty_fragment);
static int ssl3_get_record(SSL *s);
/*
* Return values are as per SSL_read()
*/
int ssl3_read_n(SSL *s, int n, int max, int extend)
{
/*
* If extend == 0, obtain new n-byte packet; if extend == 1, increase
* packet by another n bytes. The packet will be in the sub-array of
* s->s3->rbuf.buf specified by s->packet and s->packet_length. (If
* s->read_ahead is set, 'max' bytes may be stored in rbuf [plus
* s->packet_length bytes if extend == 1].)
*/
int i, len, left;
long align = 0;
unsigned char *pkt;
SSL3_BUFFER *rb;
if (n <= 0)
return n;
rb = &(s->s3->rbuf);
if (rb->buf == NULL)
if (!ssl3_setup_read_buffer(s))
return -1;
left = rb->left;
#if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD!=0
align = (long)rb->buf + SSL3_RT_HEADER_LENGTH;
align = (-align) & (SSL3_ALIGN_PAYLOAD - 1);
#endif
if (!extend) {
/* start with empty packet ... */
if (left == 0)
rb->offset = align;
else if (align != 0 && left >= SSL3_RT_HEADER_LENGTH) {
/*
* check if next packet length is large enough to justify payload
* alignment...
*/
pkt = rb->buf + rb->offset;
if (pkt[0] == SSL3_RT_APPLICATION_DATA
&& (pkt[3] << 8 | pkt[4]) >= 128) {
/*
* Note that even if packet is corrupted and its length field
* is insane, we can only be led to wrong decision about
* whether memmove will occur or not. Header values has no
* effect on memmove arguments and therefore no buffer
* overrun can be triggered.
*/
memmove(rb->buf + align, pkt, left);
rb->offset = align;
}
}
s->packet = rb->buf + rb->offset;
s->packet_length = 0;
/* ... now we can act as if 'extend' was set */
}
/*
* For DTLS/UDP reads should not span multiple packets because the read
* operation returns the whole packet at once (as long as it fits into
* the buffer).
*/
if (SSL_IS_DTLS(s)) {
if (left == 0 && extend)
return 0;
if (left > 0 && n > left)
n = left;
}
/* if there is enough in the buffer from a previous read, take some */
if (left >= n) {
s->packet_length += n;
rb->left = left - n;
rb->offset += n;
return (n);
}
/* else we need to read more data */
len = s->packet_length;
pkt = rb->buf + align;
/*
* Move any available bytes to front of buffer: 'len' bytes already
* pointed to by 'packet', 'left' extra ones at the end
*/
if (s->packet != pkt) { /* len > 0 */
memmove(pkt, s->packet, len + left);
s->packet = pkt;
rb->offset = len + align;
}
if (n > (int)(rb->len - rb->offset)) { /* does not happen */
SSLerr(SSL_F_SSL3_READ_N, ERR_R_INTERNAL_ERROR);
return -1;
}
/* We always act like read_ahead is set for DTLS */
if (!s->read_ahead && !SSL_IS_DTLS(s))
/* ignore max parameter */
max = n;
else {
if (max < n)
max = n;
if (max > (int)(rb->len - rb->offset))
max = rb->len - rb->offset;
}
while (left < n) {
/*
* Now we have len+left bytes at the front of s->s3->rbuf.buf and
* need to read in more until we have len+n (up to len+max if
* possible)
*/
clear_sys_error();
if (s->rbio != NULL) {
s->rwstate = SSL_READING;
i = BIO_read(s->rbio, pkt + len + left, max - left);
} else {
SSLerr(SSL_F_SSL3_READ_N, SSL_R_READ_BIO_NOT_SET);
i = -1;
}
if (i <= 0) {
rb->left = left;
if (s->mode & SSL_MODE_RELEASE_BUFFERS && !SSL_IS_DTLS(s))
if (len + left == 0)
ssl3_release_read_buffer(s);
return (i);
}
left += i;
/*
* reads should *never* span multiple packets for DTLS because the
* underlying transport protocol is message oriented as opposed to
* byte oriented as in the TLS case.
*/
if (SSL_IS_DTLS(s)) {
if (n > left)
n = left; /* makes the while condition false */
}
}
/* done reading, now the book-keeping */
rb->offset += n;
rb->left = left - n;
s->packet_length += n;
s->rwstate = SSL_NOTHING;
return (n);
}
/*
* MAX_EMPTY_RECORDS defines the number of consecutive, empty records that
* will be processed per call to ssl3_get_record. Without this limit an
* attacker could send empty records at a faster rate than we can process and
* cause ssl3_get_record to loop forever.
*/
#define MAX_EMPTY_RECORDS 32
/*-
* Call this to get a new input record.
* It will return <= 0 if more data is needed, normally due to an error
* or non-blocking IO.
* When it finishes, one packet has been decoded and can be found in
* ssl->s3->rrec.type - is the type of record
* ssl->s3->rrec.data, - data
* ssl->s3->rrec.length, - number of bytes
*/
/* used only by ssl3_read_bytes */
static int ssl3_get_record(SSL *s)
{
int ssl_major, ssl_minor, al;
int enc_err, n, i, ret = -1;
SSL3_RECORD *rr;
SSL_SESSION *sess;
unsigned char *p;
unsigned char md[EVP_MAX_MD_SIZE];
short version;
unsigned mac_size, orig_len;
size_t extra;
unsigned empty_record_count = 0;
rr = &(s->s3->rrec);
sess = s->session;
if (s->options & SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER)
extra = SSL3_RT_MAX_EXTRA;
else
extra = 0;
if (extra && !s->s3->init_extra) {
/*
* An application error: SLS_OP_MICROSOFT_BIG_SSLV3_BUFFER set after
* ssl3_setup_buffers() was done
*/
SSLerr(SSL_F_SSL3_GET_RECORD, ERR_R_INTERNAL_ERROR);
return -1;
}
again:
/* check if we have the header */
if ((s->rstate != SSL_ST_READ_BODY) ||
(s->packet_length < SSL3_RT_HEADER_LENGTH)) {
n = ssl3_read_n(s, SSL3_RT_HEADER_LENGTH, s->s3->rbuf.len, 0);
if (n <= 0)
return (n); /* error or non-blocking */
s->rstate = SSL_ST_READ_BODY;
p = s->packet;
if (s->msg_callback)
s->msg_callback(0, 0, SSL3_RT_HEADER, p, 5, s,
s->msg_callback_arg);
/* Pull apart the header into the SSL3_RECORD */
rr->type = *(p++);
ssl_major = *(p++);
ssl_minor = *(p++);
version = (ssl_major << 8) | ssl_minor;
n2s(p, rr->length);
#if 0
fprintf(stderr, "Record type=%d, Length=%d\n", rr->type, rr->length);
#endif
/* Lets check version */
if (!s->first_packet) {
if (version != s->version) {
SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_WRONG_VERSION_NUMBER);
if ((s->version & 0xFF00) == (version & 0xFF00)
&& !s->enc_write_ctx && !s->write_hash) {
if (rr->type == SSL3_RT_ALERT) {
/*
* The record is using an incorrect version number, but
* what we've got appears to be an alert. We haven't
* read the body yet to check whether its a fatal or
* not - but chances are it is. We probably shouldn't
* send a fatal alert back. We'll just end.
*/
goto err;
}
/*
* Send back error using their minor version number :-)
*/
s->version = (unsigned short)version;
}
al = SSL_AD_PROTOCOL_VERSION;
goto f_err;
}
}
if ((version >> 8) != SSL3_VERSION_MAJOR) {
SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_WRONG_VERSION_NUMBER);
goto err;
}
if (rr->length > s->s3->rbuf.len - SSL3_RT_HEADER_LENGTH) {
al = SSL_AD_RECORD_OVERFLOW;
SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_PACKET_LENGTH_TOO_LONG);
goto f_err;
}
/* now s->rstate == SSL_ST_READ_BODY */
}
/* s->rstate == SSL_ST_READ_BODY, get and decode the data */
if (rr->length > s->packet_length - SSL3_RT_HEADER_LENGTH) {
/* now s->packet_length == SSL3_RT_HEADER_LENGTH */
i = rr->length;
n = ssl3_read_n(s, i, i, 1);
if (n <= 0)
return (n); /* error or non-blocking io */
/*
* now n == rr->length, and s->packet_length == SSL3_RT_HEADER_LENGTH
* + rr->length
*/
}
s->rstate = SSL_ST_READ_HEADER; /* set state for later operations */
/*
* At this point, s->packet_length == SSL3_RT_HEADER_LNGTH + rr->length,
* and we have that many bytes in s->packet
*/
rr->input = &(s->packet[SSL3_RT_HEADER_LENGTH]);
/*
* ok, we can now read from 's->packet' data into 'rr' rr->input points
* at rr->length bytes, which need to be copied into rr->data by either
* the decryption or by the decompression When the data is 'copied' into
* the rr->data buffer, rr->input will be pointed at the new buffer
*/
/*
* We now have - encrypted [ MAC [ compressed [ plain ] ] ] rr->length
* bytes of encrypted compressed stuff.
*/
/* check is not needed I believe */
if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH + extra) {
al = SSL_AD_RECORD_OVERFLOW;
SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
goto f_err;
}
/* decrypt in place in 'rr->input' */
rr->data = rr->input;
enc_err = s->method->ssl3_enc->enc(s, 0);
/*-
* enc_err is:
* 0: (in non-constant time) if the record is publically invalid.
* 1: if the padding is valid
* -1: if the padding is invalid
*/
if (enc_err == 0) {
al = SSL_AD_DECRYPTION_FAILED;
SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_BLOCK_CIPHER_PAD_IS_WRONG);
goto f_err;
}
#ifdef TLS_DEBUG
printf("dec %d\n", rr->length);
{
unsigned int z;
for (z = 0; z < rr->length; z++)
printf("%02X%c", rr->data[z], ((z + 1) % 16) ? ' ' : '\n');
}
printf("\n");
#endif
/* r->length is now the compressed data plus mac */
if ((sess != NULL) &&
(s->enc_read_ctx != NULL) && (EVP_MD_CTX_md(s->read_hash) != NULL)) {
/* s->read_hash != NULL => mac_size != -1 */
unsigned char *mac = NULL;
unsigned char mac_tmp[EVP_MAX_MD_SIZE];
mac_size = EVP_MD_CTX_size(s->read_hash);
OPENSSL_assert(mac_size <= EVP_MAX_MD_SIZE);
/*
* kludge: *_cbc_remove_padding passes padding length in rr->type
*/
orig_len = rr->length + ((unsigned int)rr->type >> 8);
/*
* orig_len is the length of the record before any padding was
* removed. This is public information, as is the MAC in use,
* therefore we can safely process the record in a different amount
* of time if it's too short to possibly contain a MAC.
*/
if (orig_len < mac_size ||
/* CBC records must have a padding length byte too. */
(EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
orig_len < mac_size + 1)) {
al = SSL_AD_DECODE_ERROR;
SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_LENGTH_TOO_SHORT);
goto f_err;
}
if (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE) {
/*
* We update the length so that the TLS header bytes can be
* constructed correctly but we need to extract the MAC in
* constant time from within the record, without leaking the
* contents of the padding bytes.
*/
mac = mac_tmp;
ssl3_cbc_copy_mac(mac_tmp, rr, mac_size, orig_len);
rr->length -= mac_size;
} else {
/*
* In this case there's no padding, so |orig_len| equals
* |rec->length| and we checked that there's enough bytes for
* |mac_size| above.
*/
rr->length -= mac_size;
mac = &rr->data[rr->length];
}
i = s->method->ssl3_enc->mac(s, md, 0 /* not send */ );
if (i < 0 || mac == NULL
|| CRYPTO_memcmp(md, mac, (size_t)mac_size) != 0)
enc_err = -1;
if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH + extra + mac_size)
enc_err = -1;
}
if (enc_err < 0) {
/*
* A separate 'decryption_failed' alert was introduced with TLS 1.0,
* SSL 3.0 only has 'bad_record_mac'. But unless a decryption
* failure is directly visible from the ciphertext anyway, we should
* not reveal which kind of error occured -- this might become
* visible to an attacker (e.g. via a logfile)
*/
al = SSL_AD_BAD_RECORD_MAC;
SSLerr(SSL_F_SSL3_GET_RECORD,
SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
goto f_err;
}
/* r->length is now just compressed */
if (s->expand != NULL) {
if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH + extra) {
al = SSL_AD_RECORD_OVERFLOW;
SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_COMPRESSED_LENGTH_TOO_LONG);
goto f_err;
}
if (!ssl3_do_uncompress(s)) {
al = SSL_AD_DECOMPRESSION_FAILURE;
SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_BAD_DECOMPRESSION);
goto f_err;
}
}
if (rr->length > SSL3_RT_MAX_PLAIN_LENGTH + extra) {
al = SSL_AD_RECORD_OVERFLOW;
SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_DATA_LENGTH_TOO_LONG);
goto f_err;
}
rr->off = 0;
/*-
* So at this point the following is true
* ssl->s3->rrec.type is the type of record
* ssl->s3->rrec.length == number of bytes in record
* ssl->s3->rrec.off == offset to first valid byte
* ssl->s3->rrec.data == where to take bytes from, increment
* after use :-).
*/
/* we have pulled in a full packet so zero things */
s->packet_length = 0;
/* just read a 0 length packet */
if (rr->length == 0) {
empty_record_count++;
if (empty_record_count > MAX_EMPTY_RECORDS) {
al = SSL_AD_UNEXPECTED_MESSAGE;
SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_RECORD_TOO_SMALL);
goto f_err;
}
goto again;
}
#if 0
fprintf(stderr, "Ultimate Record type=%d, Length=%d\n", rr->type,
rr->length);
#endif
return (1);
f_err:
ssl3_send_alert(s, SSL3_AL_FATAL, al);
err:
return (ret);
}
int ssl3_do_uncompress(SSL *ssl)
{
#ifndef OPENSSL_NO_COMP
int i;
SSL3_RECORD *rr;
rr = &(ssl->s3->rrec);
i = COMP_expand_block(ssl->expand, rr->comp,
SSL3_RT_MAX_PLAIN_LENGTH, rr->data,
(int)rr->length);
if (i < 0)
return (0);
else
rr->length = i;
rr->data = rr->comp;
#endif
return (1);
}
int ssl3_do_compress(SSL *ssl)
{
#ifndef OPENSSL_NO_COMP
int i;
SSL3_RECORD *wr;
wr = &(ssl->s3->wrec);
i = COMP_compress_block(ssl->compress, wr->data,
SSL3_RT_MAX_COMPRESSED_LENGTH,
wr->input, (int)wr->length);
if (i < 0)
return (0);
else
wr->length = i;
wr->input = wr->data;
#endif
return (1);
}
/*
* Call this to write data in records of type 'type' It will return <= 0 if
* not all data has been sent or non-blocking IO.
*/
int ssl3_write_bytes(SSL *s, int type, const void *buf_, int len)
{
const unsigned char *buf = buf_;
int tot;
unsigned int n, nw;
#if !defined(OPENSSL_NO_MULTIBLOCK) && EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK
unsigned int max_send_fragment;
#endif
SSL3_BUFFER *wb = &(s->s3->wbuf);
int i;
s->rwstate = SSL_NOTHING;
OPENSSL_assert(s->s3->wnum <= INT_MAX);
tot = s->s3->wnum;
s->s3->wnum = 0;
if (SSL_in_init(s) && !s->in_handshake) {
i = s->handshake_func(s);
if (i < 0)
return (i);
if (i == 0) {
SSLerr(SSL_F_SSL3_WRITE_BYTES, SSL_R_SSL_HANDSHAKE_FAILURE);
return -1;
}
}
/*
* ensure that if we end up with a smaller value of data to write out
* than the the original len from a write which didn't complete for
* non-blocking I/O and also somehow ended up avoiding the check for
* this in ssl3_write_pending/SSL_R_BAD_WRITE_RETRY as it must never be
* possible to end up with (len-tot) as a large number that will then
* promptly send beyond the end of the users buffer ... so we trap and
* report the error in a way the user will notice
*/
if ((len < tot) || ((wb->left != 0) && (len < (tot + s->s3->wpend_tot)))) {
SSLerr(SSL_F_SSL3_WRITE_BYTES, SSL_R_BAD_LENGTH);
return (-1);
}
/*
* first check if there is a SSL3_BUFFER still being written out. This
* will happen with non blocking IO
*/
if (wb->left != 0) {
i = ssl3_write_pending(s, type, &buf[tot], s->s3->wpend_tot);
if (i <= 0) {
/* XXX should we ssl3_release_write_buffer if i<0? */
s->s3->wnum = tot;
return i;
}
tot += i; /* this might be last fragment */
}
#if !defined(OPENSSL_NO_MULTIBLOCK) && EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK
/*
* Depending on platform multi-block can deliver several *times*
* better performance. Downside is that it has to allocate
* jumbo buffer to accomodate up to 8 records, but the
* compromise is considered worthy.
*/
if (type == SSL3_RT_APPLICATION_DATA &&
len >= 4 * (int)(max_send_fragment = s->max_send_fragment) &&
s->compress == NULL && s->msg_callback == NULL &&
SSL_USE_EXPLICIT_IV(s) &&
s->enc_write_ctx != NULL &&
EVP_CIPHER_flags(s->enc_write_ctx->cipher) &
EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK) {
unsigned char aad[13];
EVP_CTRL_TLS1_1_MULTIBLOCK_PARAM mb_param;
int packlen;
/* minimize address aliasing conflicts */
if ((max_send_fragment & 0xfff) == 0)
max_send_fragment -= 512;
if (tot == 0 || wb->buf == NULL) { /* allocate jumbo buffer */
ssl3_release_write_buffer(s);
packlen = EVP_CIPHER_CTX_ctrl(s->enc_write_ctx,
EVP_CTRL_TLS1_1_MULTIBLOCK_MAX_BUFSIZE,
max_send_fragment, NULL);
if (len >= 8 * (int)max_send_fragment)
packlen *= 8;
else
packlen *= 4;
wb->buf = OPENSSL_malloc(packlen);
if (!wb->buf) {
SSLerr(SSL_F_SSL3_WRITE_BYTES, ERR_R_MALLOC_FAILURE);
return -1;
}
wb->len = packlen;
} else if (tot == len) { /* done? */
OPENSSL_free(wb->buf); /* free jumbo buffer */
wb->buf = NULL;
return tot;
}
n = (len - tot);
for (;;) {
if (n < 4 * max_send_fragment) {
OPENSSL_free(wb->buf); /* free jumbo buffer */
wb->buf = NULL;
break;
}
if (s->s3->alert_dispatch) {
i = s->method->ssl_dispatch_alert(s);
if (i <= 0) {
s->s3->wnum = tot;
return i;
}
}
if (n >= 8 * max_send_fragment)
nw = max_send_fragment * (mb_param.interleave = 8);
else
nw = max_send_fragment * (mb_param.interleave = 4);
memcpy(aad, s->s3->write_sequence, 8);
aad[8] = type;
aad[9] = (unsigned char)(s->version >> 8);
aad[10] = (unsigned char)(s->version);
aad[11] = 0;
aad[12] = 0;
mb_param.out = NULL;
mb_param.inp = aad;
mb_param.len = nw;
packlen = EVP_CIPHER_CTX_ctrl(s->enc_write_ctx,
EVP_CTRL_TLS1_1_MULTIBLOCK_AAD,
sizeof(mb_param), &mb_param);
if (packlen <= 0 || packlen > (int)wb->len) { /* never happens */
OPENSSL_free(wb->buf); /* free jumbo buffer */
wb->buf = NULL;
break;
}
mb_param.out = wb->buf;
mb_param.inp = &buf[tot];
mb_param.len = nw;
if (EVP_CIPHER_CTX_ctrl(s->enc_write_ctx,
EVP_CTRL_TLS1_1_MULTIBLOCK_ENCRYPT,
sizeof(mb_param), &mb_param) <= 0)
return -1;
s->s3->write_sequence[7] += mb_param.interleave;
if (s->s3->write_sequence[7] < mb_param.interleave) {
int j = 6;
while (j >= 0 && (++s->s3->write_sequence[j--]) == 0) ;
}
wb->offset = 0;
wb->left = packlen;
s->s3->wpend_tot = nw;
s->s3->wpend_buf = &buf[tot];
s->s3->wpend_type = type;
s->s3->wpend_ret = nw;
i = ssl3_write_pending(s, type, &buf[tot], nw);
if (i <= 0) {
if (i < 0 && (!s->wbio || !BIO_should_retry(s->wbio))) {
OPENSSL_free(wb->buf);
wb->buf = NULL;
}
s->s3->wnum = tot;
return i;
}
if (i == (int)n) {
OPENSSL_free(wb->buf); /* free jumbo buffer */
wb->buf = NULL;
return tot + i;
}
n -= i;
tot += i;
}
} else
#endif
if (tot == len) { /* done? */
if (s->mode & SSL_MODE_RELEASE_BUFFERS && !SSL_IS_DTLS(s))
ssl3_release_write_buffer(s);
return tot;
}
n = (len - tot);
for (;;) {
if (n > s->max_send_fragment)
nw = s->max_send_fragment;
else
nw = n;
i = do_ssl3_write(s, type, &(buf[tot]), nw, 0);
if (i <= 0) {
/* XXX should we ssl3_release_write_buffer if i<0? */
s->s3->wnum = tot;
return i;
}
if ((i == (int)n) ||
(type == SSL3_RT_APPLICATION_DATA &&
(s->mode & SSL_MODE_ENABLE_PARTIAL_WRITE))) {
/*
* next chunk of data should get another prepended empty fragment
* in ciphersuites with known-IV weakness:
*/
s->s3->empty_fragment_done = 0;
if ((i == (int)n) && s->mode & SSL_MODE_RELEASE_BUFFERS &&
!SSL_IS_DTLS(s))
ssl3_release_write_buffer(s);
return tot + i;
}
n -= i;
tot += i;
}
}
static int do_ssl3_write(SSL *s, int type, const unsigned char *buf,
unsigned int len, int create_empty_fragment)
{
unsigned char *p, *plen;
int i, mac_size, clear = 0;
int prefix_len = 0;
int eivlen;
long align = 0;
SSL3_RECORD *wr;
SSL3_BUFFER *wb = &(s->s3->wbuf);
SSL_SESSION *sess;
/*
* first check if there is a SSL3_BUFFER still being written out. This
* will happen with non blocking IO
*/
if (wb->left != 0)
return (ssl3_write_pending(s, type, buf, len));
/* If we have an alert to send, lets send it */
if (s->s3->alert_dispatch) {
i = s->method->ssl_dispatch_alert(s);
if (i <= 0)
return (i);
/* if it went, fall through and send more stuff */
}
if (wb->buf == NULL)
if (!ssl3_setup_write_buffer(s))
return -1;
if (len == 0 && !create_empty_fragment)
return 0;
wr = &(s->s3->wrec);
sess = s->session;
if ((sess == NULL) ||
(s->enc_write_ctx == NULL) ||
(EVP_MD_CTX_md(s->write_hash) == NULL)) {
#if 1
clear = s->enc_write_ctx ? 0 : 1; /* must be AEAD cipher */
#else
clear = 1;
#endif
mac_size = 0;
} else {
mac_size = EVP_MD_CTX_size(s->write_hash);
if (mac_size < 0)
goto err;
}
/*
* 'create_empty_fragment' is true only when this function calls itself
*/
if (!clear && !create_empty_fragment && !s->s3->empty_fragment_done) {
/*
* countermeasure against known-IV weakness in CBC ciphersuites (see
* http://www.openssl.org/~bodo/tls-cbc.txt)
*/
if (s->s3->need_empty_fragments && type == SSL3_RT_APPLICATION_DATA) {
/*
* recursive function call with 'create_empty_fragment' set; this
* prepares and buffers the data for an empty fragment (these
* 'prefix_len' bytes are sent out later together with the actual
* payload)
*/
prefix_len = do_ssl3_write(s, type, buf, 0, 1);
if (prefix_len <= 0)
goto err;
if (prefix_len >
(SSL3_RT_HEADER_LENGTH + SSL3_RT_SEND_MAX_ENCRYPTED_OVERHEAD))
{
/* insufficient space */
SSLerr(SSL_F_DO_SSL3_WRITE, ERR_R_INTERNAL_ERROR);
goto err;
}
}
s->s3->empty_fragment_done = 1;
}
if (create_empty_fragment) {
#if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD!=0
/*
* extra fragment would be couple of cipher blocks, which would be
* multiple of SSL3_ALIGN_PAYLOAD, so if we want to align the real
* payload, then we can just pretent we simply have two headers.
*/
align = (long)wb->buf + 2 * SSL3_RT_HEADER_LENGTH;
align = (-align) & (SSL3_ALIGN_PAYLOAD - 1);
#endif
p = wb->buf + align;
wb->offset = align;
} else if (prefix_len) {
p = wb->buf + wb->offset + prefix_len;
} else {
#if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD!=0
align = (long)wb->buf + SSL3_RT_HEADER_LENGTH;
align = (-align) & (SSL3_ALIGN_PAYLOAD - 1);
#endif
p = wb->buf + align;
wb->offset = align;
}
/* write the header */
*(p++) = type & 0xff;
wr->type = type;
*(p++) = (s->version >> 8);
/*
* Some servers hang if iniatial client hello is larger than 256 bytes
* and record version number > TLS 1.0
*/
if (s->state == SSL3_ST_CW_CLNT_HELLO_B
&& !s->renegotiate && TLS1_get_version(s) > TLS1_VERSION)
*(p++) = 0x1;
else
*(p++) = s->version & 0xff;
/* field where we are to write out packet length */
plen = p;
p += 2;
/* Explicit IV length, block ciphers appropriate version flag */
if (s->enc_write_ctx && SSL_USE_EXPLICIT_IV(s)) {
int mode = EVP_CIPHER_CTX_mode(s->enc_write_ctx);
if (mode == EVP_CIPH_CBC_MODE) {
eivlen = EVP_CIPHER_CTX_iv_length(s->enc_write_ctx);
if (eivlen <= 1)
eivlen = 0;
}
/* Need explicit part of IV for GCM mode */
else if (mode == EVP_CIPH_GCM_MODE)
eivlen = EVP_GCM_TLS_EXPLICIT_IV_LEN;
else
eivlen = 0;
} else
eivlen = 0;
/* lets setup the record stuff. */
wr->data = p + eivlen;
wr->length = (int)len;
wr->input = (unsigned char *)buf;
/*
* we now 'read' from wr->input, wr->length bytes into wr->data
*/
/* first we compress */
if (s->compress != NULL) {
if (!ssl3_do_compress(s)) {
SSLerr(SSL_F_DO_SSL3_WRITE, SSL_R_COMPRESSION_FAILURE);
goto err;
}
} else {
memcpy(wr->data, wr->input, wr->length);
wr->input = wr->data;
}
/*
* we should still have the output to wr->data and the input from
* wr->input. Length should be wr->length. wr->data still points in the
* wb->buf
*/
if (mac_size != 0) {
if (s->method->ssl3_enc->mac(s, &(p[wr->length + eivlen]), 1) < 0)
goto err;
wr->length += mac_size;
}
wr->input = p;
wr->data = p;
if (eivlen) {
/*
* if (RAND_pseudo_bytes(p, eivlen) <= 0) goto err;
*/
wr->length += eivlen;
}
if (s->method->ssl3_enc->enc(s, 1) < 1)
goto err;
/* record length after mac and block padding */
s2n(wr->length, plen);
if (s->msg_callback)
s->msg_callback(1, 0, SSL3_RT_HEADER, plen - 5, 5, s,
s->msg_callback_arg);
/*
* we should now have wr->data pointing to the encrypted data, which is
* wr->length long
*/
wr->type = type; /* not needed but helps for debugging */
wr->length += SSL3_RT_HEADER_LENGTH;
if (create_empty_fragment) {
/*
* we are in a recursive call; just return the length, don't write
* out anything here
*/
return wr->length;
}
/* now let's set up wb */
wb->left = prefix_len + wr->length;
/*
* memorize arguments so that ssl3_write_pending can detect bad write
* retries later
*/
s->s3->wpend_tot = len;
s->s3->wpend_buf = buf;
s->s3->wpend_type = type;
s->s3->wpend_ret = len;
/* we now just need to write the buffer */
return ssl3_write_pending(s, type, buf, len);
err:
return -1;
}
/* if s->s3->wbuf.left != 0, we need to call this
*
* Return values are as per SSL_write(), i.e.
*/
int ssl3_write_pending(SSL *s, int type, const unsigned char *buf,
unsigned int len)
{
int i;
SSL3_BUFFER *wb = &(s->s3->wbuf);
-/* XXXX */
if ((s->s3->wpend_tot > (int)len)
- || ((s->s3->wpend_buf != buf) &&
- !(s->mode & SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER))
+ || (!(s->mode & SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER)
+ && (s->s3->wpend_buf != buf))
|| (s->s3->wpend_type != type)) {
SSLerr(SSL_F_SSL3_WRITE_PENDING, SSL_R_BAD_WRITE_RETRY);
return (-1);
}
for (;;) {
clear_sys_error();
if (s->wbio != NULL) {
s->rwstate = SSL_WRITING;
i = BIO_write(s->wbio,
(char *)&(wb->buf[wb->offset]),
(unsigned int)wb->left);
} else {
SSLerr(SSL_F_SSL3_WRITE_PENDING, SSL_R_BIO_NOT_SET);
i = -1;
}
if (i == wb->left) {
wb->left = 0;
wb->offset += i;
s->rwstate = SSL_NOTHING;
return (s->s3->wpend_ret);
} else if (i <= 0) {
if (SSL_IS_DTLS(s)) {
/*
* For DTLS, just drop it. That's kind of the whole point in
* using a datagram service
*/
wb->left = 0;
}
return i;
}
wb->offset += i;
wb->left -= i;
}
}
/*-
* Return up to 'len' payload bytes received in 'type' records.
* 'type' is one of the following:
*
* - SSL3_RT_HANDSHAKE (when ssl3_get_message calls us)
* - SSL3_RT_APPLICATION_DATA (when ssl3_read calls us)
* - 0 (during a shutdown, no data has to be returned)
*
* If we don't have stored data to work from, read a SSL/TLS record first
* (possibly multiple records if we still don't have anything to return).
*
* This function must handle any surprises the peer may have for us, such as
* Alert records (e.g. close_notify), ChangeCipherSpec records (not really
* a surprise, but handled as if it were), or renegotiation requests.
* Also if record payloads contain fragments too small to process, we store
* them until there is enough for the respective protocol (the record protocol
* may use arbitrary fragmentation and even interleaving):
* Change cipher spec protocol
* just 1 byte needed, no need for keeping anything stored
* Alert protocol
* 2 bytes needed (AlertLevel, AlertDescription)
* Handshake protocol
* 4 bytes needed (HandshakeType, uint24 length) -- we just have
* to detect unexpected Client Hello and Hello Request messages
* here, anything else is handled by higher layers
* Application data protocol
* none of our business
*/
int ssl3_read_bytes(SSL *s, int type, unsigned char *buf, int len, int peek)
{
int al, i, j, ret;
unsigned int n;
SSL3_RECORD *rr;
void (*cb) (const SSL *ssl, int type2, int val) = NULL;
if (s->s3->rbuf.buf == NULL) /* Not initialized yet */
if (!ssl3_setup_read_buffer(s))
return (-1);
if ((type && (type != SSL3_RT_APPLICATION_DATA)
&& (type != SSL3_RT_HANDSHAKE)) || (peek
&& (type !=
SSL3_RT_APPLICATION_DATA))) {
SSLerr(SSL_F_SSL3_READ_BYTES, ERR_R_INTERNAL_ERROR);
return -1;
}
if ((type == SSL3_RT_HANDSHAKE) && (s->s3->handshake_fragment_len > 0))
/* (partially) satisfy request from storage */
{
unsigned char *src = s->s3->handshake_fragment;
unsigned char *dst = buf;
unsigned int k;
/* peek == 0 */
n = 0;
while ((len > 0) && (s->s3->handshake_fragment_len > 0)) {
*dst++ = *src++;
len--;
s->s3->handshake_fragment_len--;
n++;
}
/* move any remaining fragment bytes: */
for (k = 0; k < s->s3->handshake_fragment_len; k++)
s->s3->handshake_fragment[k] = *src++;
return n;
}
/*
* Now s->s3->handshake_fragment_len == 0 if type == SSL3_RT_HANDSHAKE.
*/
if (!s->in_handshake && SSL_in_init(s)) {
/* type == SSL3_RT_APPLICATION_DATA */
i = s->handshake_func(s);
if (i < 0)
return (i);
if (i == 0) {
SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_SSL_HANDSHAKE_FAILURE);
return (-1);
}
}
start:
s->rwstate = SSL_NOTHING;
/*-
* s->s3->rrec.type - is the type of record
* s->s3->rrec.data, - data
* s->s3->rrec.off, - offset into 'data' for next read
* s->s3->rrec.length, - number of bytes.
*/
rr = &(s->s3->rrec);
/* get new packet if necessary */
if ((rr->length == 0) || (s->rstate == SSL_ST_READ_BODY)) {
ret = ssl3_get_record(s);
if (ret <= 0)
return (ret);
}
/*
* Reset the count of consecutive warning alerts if we've got a non-empty
* record that isn't an alert.
*/
if (rr->type != SSL3_RT_ALERT && rr->length != 0)
s->cert->alert_count = 0;
/* we now have a packet which can be read and processed */
if (s->s3->change_cipher_spec /* set when we receive ChangeCipherSpec,
* reset by ssl3_get_finished */
&& (rr->type != SSL3_RT_HANDSHAKE)) {
al = SSL_AD_UNEXPECTED_MESSAGE;
SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_DATA_BETWEEN_CCS_AND_FINISHED);
goto f_err;
}
/*
* If the other end has shut down, throw anything we read away (even in
* 'peek' mode)
*/
if (s->shutdown & SSL_RECEIVED_SHUTDOWN) {
rr->length = 0;
s->rwstate = SSL_NOTHING;
return (0);
}
if (type == rr->type) { /* SSL3_RT_APPLICATION_DATA or
* SSL3_RT_HANDSHAKE */
/*
* make sure that we are not getting application data when we are
* doing a handshake for the first time
*/
if (SSL_in_init(s) && (type == SSL3_RT_APPLICATION_DATA) &&
(s->enc_read_ctx == NULL)) {
al = SSL_AD_UNEXPECTED_MESSAGE;
SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_APP_DATA_IN_HANDSHAKE);
goto f_err;
}
if (len <= 0)
return (len);
if ((unsigned int)len > rr->length)
n = rr->length;
else
n = (unsigned int)len;
memcpy(buf, &(rr->data[rr->off]), n);
if (!peek) {
rr->length -= n;
rr->off += n;
if (rr->length == 0) {
s->rstate = SSL_ST_READ_HEADER;
rr->off = 0;
if (s->mode & SSL_MODE_RELEASE_BUFFERS
&& s->s3->rbuf.left == 0)
ssl3_release_read_buffer(s);
}
}
return (n);
}
/*
* If we get here, then type != rr->type; if we have a handshake message,
* then it was unexpected (Hello Request or Client Hello).
*/
/*
* In case of record types for which we have 'fragment' storage, fill
* that so that we can process the data at a fixed place.
*/
{
unsigned int dest_maxlen = 0;
unsigned char *dest = NULL;
unsigned int *dest_len = NULL;
if (rr->type == SSL3_RT_HANDSHAKE) {
- dest_maxlen = sizeof s->s3->handshake_fragment;
+ dest_maxlen = sizeof(s->s3->handshake_fragment);
dest = s->s3->handshake_fragment;
dest_len = &s->s3->handshake_fragment_len;
} else if (rr->type == SSL3_RT_ALERT) {
- dest_maxlen = sizeof s->s3->alert_fragment;
+ dest_maxlen = sizeof(s->s3->alert_fragment);
dest = s->s3->alert_fragment;
dest_len = &s->s3->alert_fragment_len;
}
#ifndef OPENSSL_NO_HEARTBEATS
else if (rr->type == TLS1_RT_HEARTBEAT) {
i = tls1_process_heartbeat(s);
if (i < 0)
return i;
rr->length = 0;
if (s->mode & SSL_MODE_AUTO_RETRY)
goto start;
/* Exit and notify application to read again */
s->rwstate = SSL_READING;
BIO_clear_retry_flags(SSL_get_rbio(s));
BIO_set_retry_read(SSL_get_rbio(s));
return (-1);
}
#endif
if (dest_maxlen > 0) {
n = dest_maxlen - *dest_len; /* available space in 'dest' */
if (rr->length < n)
n = rr->length; /* available bytes */
/* now move 'n' bytes: */
while (n-- > 0) {
dest[(*dest_len)++] = rr->data[rr->off++];
rr->length--;
}
if (*dest_len < dest_maxlen)
goto start; /* fragment was too small */
}
}
/*-
* s->s3->handshake_fragment_len == 4 iff rr->type == SSL3_RT_HANDSHAKE;
* s->s3->alert_fragment_len == 2 iff rr->type == SSL3_RT_ALERT.
* (Possibly rr is 'empty' now, i.e. rr->length may be 0.)
*/
/* If we are a client, check for an incoming 'Hello Request': */
if ((!s->server) &&
(s->s3->handshake_fragment_len >= 4) &&
(s->s3->handshake_fragment[0] == SSL3_MT_HELLO_REQUEST) &&
(s->session != NULL) && (s->session->cipher != NULL)) {
s->s3->handshake_fragment_len = 0;
if ((s->s3->handshake_fragment[1] != 0) ||
(s->s3->handshake_fragment[2] != 0) ||
(s->s3->handshake_fragment[3] != 0)) {
al = SSL_AD_DECODE_ERROR;
SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_BAD_HELLO_REQUEST);
goto f_err;
}
if (s->msg_callback)
s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE,
s->s3->handshake_fragment, 4, s,
s->msg_callback_arg);
if (SSL_is_init_finished(s) &&
!(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS) &&
!s->s3->renegotiate) {
ssl3_renegotiate(s);
if (ssl3_renegotiate_check(s)) {
i = s->handshake_func(s);
if (i < 0)
return (i);
if (i == 0) {
SSLerr(SSL_F_SSL3_READ_BYTES,
SSL_R_SSL_HANDSHAKE_FAILURE);
return (-1);
}
if (!(s->mode & SSL_MODE_AUTO_RETRY)) {
if (s->s3->rbuf.left == 0) { /* no read-ahead left? */
BIO *bio;
/*
* In the case where we try to read application data,
* but we trigger an SSL handshake, we return -1 with
* the retry option set. Otherwise renegotiation may
* cause nasty problems in the blocking world
*/
s->rwstate = SSL_READING;
bio = SSL_get_rbio(s);
BIO_clear_retry_flags(bio);
BIO_set_retry_read(bio);
return (-1);
}
}
}
}
/*
* we either finished a handshake or ignored the request, now try
* again to obtain the (application) data we were asked for
*/
goto start;
}
+
/*
* If we are a server and get a client hello when renegotiation isn't
- * allowed send back a no renegotiation alert and carry on. WARNING:
- * experimental code, needs reviewing (steve)
+ * allowed send back a no renegotiation alert and carry on.
*/
- if (s->server &&
- SSL_is_init_finished(s) &&
- !s->s3->send_connection_binding &&
- (s->version > SSL3_VERSION) &&
- (s->s3->handshake_fragment_len >= 4) &&
- (s->s3->handshake_fragment[0] == SSL3_MT_CLIENT_HELLO) &&
- (s->session != NULL) && (s->session->cipher != NULL) &&
- !(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)) {
- /*
- * s->s3->handshake_fragment_len = 0;
- */
+ if (s->server
+ && SSL_is_init_finished(s)
+ && !s->s3->send_connection_binding
+ && s->version > SSL3_VERSION
+ && s->s3->handshake_fragment_len >= SSL3_HM_HEADER_LENGTH
+ && s->s3->handshake_fragment[0] == SSL3_MT_CLIENT_HELLO
+ && s->s3->previous_client_finished_len != 0
+ && (s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION) == 0) {
+ s->s3->handshake_fragment_len = 0;
rr->length = 0;
ssl3_send_alert(s, SSL3_AL_WARNING, SSL_AD_NO_RENEGOTIATION);
goto start;
}
+
if (s->s3->alert_fragment_len >= 2) {
int alert_level = s->s3->alert_fragment[0];
int alert_descr = s->s3->alert_fragment[1];
s->s3->alert_fragment_len = 0;
if (s->msg_callback)
s->msg_callback(0, s->version, SSL3_RT_ALERT,
s->s3->alert_fragment, 2, s, s->msg_callback_arg);
if (s->info_callback != NULL)
cb = s->info_callback;
else if (s->ctx->info_callback != NULL)
cb = s->ctx->info_callback;
if (cb != NULL) {
j = (alert_level << 8) | alert_descr;
cb(s, SSL_CB_READ_ALERT, j);
}
if (alert_level == SSL3_AL_WARNING) {
s->s3->warn_alert = alert_descr;
s->cert->alert_count++;
if (s->cert->alert_count == MAX_WARN_ALERT_COUNT) {
al = SSL_AD_UNEXPECTED_MESSAGE;
SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_TOO_MANY_WARN_ALERTS);
goto f_err;
}
if (alert_descr == SSL_AD_CLOSE_NOTIFY) {
s->shutdown |= SSL_RECEIVED_SHUTDOWN;
return (0);
}
/*
* This is a warning but we receive it if we requested
* renegotiation and the peer denied it. Terminate with a fatal
* alert because if application tried to renegotiatie it
* presumably had a good reason and expects it to succeed. In
* future we might have a renegotiation where we don't care if
* the peer refused it where we carry on.
*/
else if (alert_descr == SSL_AD_NO_RENEGOTIATION) {
al = SSL_AD_HANDSHAKE_FAILURE;
SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_NO_RENEGOTIATION);
goto f_err;
}
#ifdef SSL_AD_MISSING_SRP_USERNAME
else if (alert_descr == SSL_AD_MISSING_SRP_USERNAME)
return (0);
#endif
} else if (alert_level == SSL3_AL_FATAL) {
char tmp[16];
s->rwstate = SSL_NOTHING;
s->s3->fatal_alert = alert_descr;
SSLerr(SSL_F_SSL3_READ_BYTES, SSL_AD_REASON_OFFSET + alert_descr);
- BIO_snprintf(tmp, sizeof tmp, "%d", alert_descr);
+ BIO_snprintf(tmp, sizeof(tmp), "%d", alert_descr);
ERR_add_error_data(2, "SSL alert number ", tmp);
s->shutdown |= SSL_RECEIVED_SHUTDOWN;
SSL_CTX_remove_session(s->session_ctx, s->session);
return (0);
} else {
al = SSL_AD_ILLEGAL_PARAMETER;
SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_UNKNOWN_ALERT_TYPE);
goto f_err;
}
goto start;
}
if (s->shutdown & SSL_SENT_SHUTDOWN) { /* but we have not received a
* shutdown */
s->rwstate = SSL_NOTHING;
rr->length = 0;
return (0);
}
if (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC) {
/*
* 'Change Cipher Spec' is just a single byte, so we know exactly
* what the record payload has to look like
*/
if ((rr->length != 1) || (rr->off != 0) ||
(rr->data[0] != SSL3_MT_CCS)) {
al = SSL_AD_ILLEGAL_PARAMETER;
SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_BAD_CHANGE_CIPHER_SPEC);
goto f_err;
}
/* Check we have a cipher to change to */
if (s->s3->tmp.new_cipher == NULL) {
al = SSL_AD_UNEXPECTED_MESSAGE;
SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_CCS_RECEIVED_EARLY);
goto f_err;
}
if (!(s->s3->flags & SSL3_FLAGS_CCS_OK)) {
al = SSL_AD_UNEXPECTED_MESSAGE;
SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_CCS_RECEIVED_EARLY);
goto f_err;
}
s->s3->flags &= ~SSL3_FLAGS_CCS_OK;
rr->length = 0;
if (s->msg_callback)
s->msg_callback(0, s->version, SSL3_RT_CHANGE_CIPHER_SPEC,
rr->data, 1, s, s->msg_callback_arg);
s->s3->change_cipher_spec = 1;
if (!ssl3_do_change_cipher_spec(s))
goto err;
else
goto start;
}
/*
* Unexpected handshake message (Client Hello, or protocol violation)
*/
if ((s->s3->handshake_fragment_len >= 4) && !s->in_handshake) {
if (((s->state & SSL_ST_MASK) == SSL_ST_OK) &&
!(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS)) {
#if 0 /* worked only because C operator preferences
* are not as expected (and because this is
* not really needed for clients except for
* detecting protocol violations): */
s->state = SSL_ST_BEFORE | (s->server)
? SSL_ST_ACCEPT : SSL_ST_CONNECT;
#else
s->state = s->server ? SSL_ST_ACCEPT : SSL_ST_CONNECT;
#endif
s->renegotiate = 1;
s->new_session = 1;
}
i = s->handshake_func(s);
if (i < 0)
return (i);
if (i == 0) {
SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_SSL_HANDSHAKE_FAILURE);
return (-1);
}
if (!(s->mode & SSL_MODE_AUTO_RETRY)) {
if (s->s3->rbuf.left == 0) { /* no read-ahead left? */
BIO *bio;
/*
* In the case where we try to read application data, but we
* trigger an SSL handshake, we return -1 with the retry
* option set. Otherwise renegotiation may cause nasty
* problems in the blocking world
*/
s->rwstate = SSL_READING;
bio = SSL_get_rbio(s);
BIO_clear_retry_flags(bio);
BIO_set_retry_read(bio);
return (-1);
}
}
goto start;
}
switch (rr->type) {
default:
/*
* TLS 1.0 and 1.1 say you SHOULD ignore unrecognised record types, but
* TLS 1.2 says you MUST send an unexpected message alert. We use the
* TLS 1.2 behaviour for all protocol versions to prevent issues where
* no progress is being made and the peer continually sends unrecognised
* record types, using up resources processing them.
*/
al = SSL_AD_UNEXPECTED_MESSAGE;
SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_UNEXPECTED_RECORD);
goto f_err;
case SSL3_RT_CHANGE_CIPHER_SPEC:
case SSL3_RT_ALERT:
case SSL3_RT_HANDSHAKE:
/*
* we already handled all of these, with the possible exception of
* SSL3_RT_HANDSHAKE when s->in_handshake is set, but that should not
* happen when type != rr->type
*/
al = SSL_AD_UNEXPECTED_MESSAGE;
SSLerr(SSL_F_SSL3_READ_BYTES, ERR_R_INTERNAL_ERROR);
goto f_err;
case SSL3_RT_APPLICATION_DATA:
/*
* At this point, we were expecting handshake data, but have
* application data. If the library was running inside ssl3_read()
* (i.e. in_read_app_data is set) and it makes sense to read
* application data at this point (session renegotiation not yet
* started), we will indulge it.
*/
if (s->s3->in_read_app_data &&
(s->s3->total_renegotiations != 0) &&
(((s->state & SSL_ST_CONNECT) &&
(s->state >= SSL3_ST_CW_CLNT_HELLO_A) &&
(s->state <= SSL3_ST_CR_SRVR_HELLO_A)
) || ((s->state & SSL_ST_ACCEPT) &&
(s->state <= SSL3_ST_SW_HELLO_REQ_A) &&
(s->state >= SSL3_ST_SR_CLNT_HELLO_A)
)
)) {
s->s3->in_read_app_data = 2;
return (-1);
} else {
al = SSL_AD_UNEXPECTED_MESSAGE;
SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_UNEXPECTED_RECORD);
goto f_err;
}
}
/* not reached */
f_err:
ssl3_send_alert(s, SSL3_AL_FATAL, al);
err:
return (-1);
}
int ssl3_do_change_cipher_spec(SSL *s)
{
int i;
const char *sender;
int slen;
if (s->state & SSL_ST_ACCEPT)
i = SSL3_CHANGE_CIPHER_SERVER_READ;
else
i = SSL3_CHANGE_CIPHER_CLIENT_READ;
if (s->s3->tmp.key_block == NULL) {
if (s->session == NULL || s->session->master_key_length == 0) {
/* might happen if dtls1_read_bytes() calls this */
SSLerr(SSL_F_SSL3_DO_CHANGE_CIPHER_SPEC,
SSL_R_CCS_RECEIVED_EARLY);
return (0);
}
s->session->cipher = s->s3->tmp.new_cipher;
if (!s->method->ssl3_enc->setup_key_block(s))
return (0);
}
if (!s->method->ssl3_enc->change_cipher_state(s, i))
return (0);
/*
* we have to record the message digest at this point so we can get it
* before we read the finished message
*/
if (s->state & SSL_ST_CONNECT) {
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;
}
i = s->method->ssl3_enc->final_finish_mac(s,
sender, slen,
s->s3->tmp.peer_finish_md);
if (i == 0) {
SSLerr(SSL_F_SSL3_DO_CHANGE_CIPHER_SPEC, ERR_R_INTERNAL_ERROR);
return 0;
}
s->s3->tmp.peer_finish_md_len = i;
return (1);
}
int ssl3_send_alert(SSL *s, int level, int desc)
{
/* Map tls/ssl alert value to correct one */
desc = s->method->ssl3_enc->alert_value(desc);
if (s->version == SSL3_VERSION && desc == SSL_AD_PROTOCOL_VERSION)
desc = SSL_AD_HANDSHAKE_FAILURE; /* SSL 3.0 does not have
* protocol_version alerts */
if (desc < 0)
return -1;
/* If a fatal one, remove from cache */
if ((level == 2) && (s->session != NULL))
SSL_CTX_remove_session(s->session_ctx, s->session);
s->s3->alert_dispatch = 1;
s->s3->send_alert[0] = level;
s->s3->send_alert[1] = desc;
if (s->s3->wbuf.left == 0) /* data still being written out? */
return s->method->ssl_dispatch_alert(s);
/*
* else data is still being written out, we will get written some time in
* the future
*/
return -1;
}
int ssl3_dispatch_alert(SSL *s)
{
int i, j;
void (*cb) (const SSL *ssl, int type, int val) = NULL;
s->s3->alert_dispatch = 0;
i = do_ssl3_write(s, SSL3_RT_ALERT, &s->s3->send_alert[0], 2, 0);
if (i <= 0) {
s->s3->alert_dispatch = 1;
} else {
/*
* Alert sent to BIO. If it is important, flush it now. If the
* message does not get sent due to non-blocking IO, we will not
* worry too much.
*/
if (s->s3->send_alert[0] == SSL3_AL_FATAL)
(void)BIO_flush(s->wbio);
if (s->msg_callback)
s->msg_callback(1, s->version, SSL3_RT_ALERT, s->s3->send_alert,
2, s, s->msg_callback_arg);
if (s->info_callback != NULL)
cb = s->info_callback;
else if (s->ctx->info_callback != NULL)
cb = s->ctx->info_callback;
if (cb != NULL) {
j = (s->s3->send_alert[0] << 8) | s->s3->send_alert[1];
cb(s, SSL_CB_WRITE_ALERT, j);
}
}
return (i);
}
diff --git a/ssl/s3_srvr.c b/ssl/s3_srvr.c
index 0fb4845d44fa..96d973cd02bb 100644
--- a/ssl/s3_srvr.c
+++ b/ssl/s3_srvr.c
@@ -1,3699 +1,3699 @@
/* ssl/s3_srvr.c */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
/* ====================================================================
* Copyright (c) 1998-2007 The OpenSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* openssl-core@openssl.org.
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.openssl.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*
* This product includes cryptographic software written by Eric Young
* (eay@cryptsoft.com). This product includes software written by Tim
* Hudson (tjh@cryptsoft.com).
*
*/
/* ====================================================================
* Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
*
* Portions of the attached software ("Contribution") are developed by
* SUN MICROSYSTEMS, INC., and are contributed to the OpenSSL project.
*
* The Contribution is licensed pursuant to the OpenSSL open source
* license provided above.
*
* ECC cipher suite support in OpenSSL originally written by
* Vipul Gupta and Sumit Gupta of Sun Microsystems Laboratories.
*
*/
/* ====================================================================
* Copyright 2005 Nokia. All rights reserved.
*
* The portions of the attached software ("Contribution") is developed by
* Nokia Corporation and is licensed pursuant to the OpenSSL open source
* license.
*
* The Contribution, originally written by Mika Kousa and Pasi Eronen of
* Nokia Corporation, consists of the "PSK" (Pre-Shared Key) ciphersuites
* support (see RFC 4279) to OpenSSL.
*
* No patent licenses or other rights except those expressly stated in
* the OpenSSL open source license shall be deemed granted or received
* expressly, by implication, estoppel, or otherwise.
*
* No assurances are provided by Nokia that the Contribution does not
* infringe the patent or other intellectual property rights of any third
* party or that the license provides you with all the necessary rights
* to make use of the Contribution.
*
* THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. IN
* ADDITION TO THE DISCLAIMERS INCLUDED IN THE LICENSE, NOKIA
* SPECIFICALLY DISCLAIMS ANY LIABILITY FOR CLAIMS BROUGHT BY YOU OR ANY
* OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS OR
* OTHERWISE.
*/
#define REUSE_CIPHER_BUG
#define NETSCAPE_HANG_BUG
#include <stdio.h>
#include "ssl_locl.h"
#include "kssl_lcl.h"
#include "../crypto/constant_time_locl.h"
#include <openssl/buffer.h>
#include <openssl/rand.h>
#include <openssl/objects.h>
#include <openssl/evp.h>
#include <openssl/hmac.h>
#include <openssl/x509.h>
#ifndef OPENSSL_NO_DH
# include <openssl/dh.h>
#endif
#include <openssl/bn.h>
#ifndef OPENSSL_NO_KRB5
# include <openssl/krb5_asn.h>
#endif
#include <openssl/md5.h>
#ifndef OPENSSL_NO_SSL3_METHOD
static const SSL_METHOD *ssl3_get_server_method(int ver);
static const SSL_METHOD *ssl3_get_server_method(int ver)
{
if (ver == SSL3_VERSION)
return (SSLv3_server_method());
else
return (NULL);
}
IMPLEMENT_ssl3_meth_func(SSLv3_server_method,
ssl3_accept,
ssl_undefined_function, ssl3_get_server_method)
#endif
#ifndef OPENSSL_NO_SRP
static int ssl_check_srp_ext_ClientHello(SSL *s, int *al)
{
int ret = SSL_ERROR_NONE;
*al = SSL_AD_UNRECOGNIZED_NAME;
if ((s->s3->tmp.new_cipher->algorithm_mkey & SSL_kSRP) &&
(s->srp_ctx.TLS_ext_srp_username_callback != NULL)) {
if (s->srp_ctx.login == NULL) {
/*
* RFC 5054 says SHOULD reject, we do so if There is no srp
* login name
*/
ret = SSL3_AL_FATAL;
*al = SSL_AD_UNKNOWN_PSK_IDENTITY;
} else {
ret = SSL_srp_server_param_with_username(s, al);
}
}
return ret;
}
#endif
int ssl3_accept(SSL *s)
{
BUF_MEM *buf;
unsigned long alg_k, Time = (unsigned long)time(NULL);
void (*cb) (const SSL *ssl, int type, int val) = NULL;
int ret = -1;
int new_state, state, skip = 0;
RAND_add(&Time, sizeof(Time), 0);
ERR_clear_error();
clear_sys_error();
if (s->info_callback != NULL)
cb = s->info_callback;
else if (s->ctx->info_callback != NULL)
cb = s->ctx->info_callback;
/* init things to blank */
s->in_handshake++;
if (!SSL_in_init(s) || SSL_in_before(s))
SSL_clear(s);
if (s->cert == NULL) {
SSLerr(SSL_F_SSL3_ACCEPT, SSL_R_NO_CERTIFICATE_SET);
return (-1);
}
#ifndef OPENSSL_NO_HEARTBEATS
/*
* If we're awaiting a HeartbeatResponse, pretend we already got and
* don't await it anymore, because Heartbeats don't make sense during
* handshakes anyway.
*/
if (s->tlsext_hb_pending) {
s->tlsext_hb_pending = 0;
s->tlsext_hb_seq++;
}
#endif
for (;;) {
state = s->state;
switch (s->state) {
case SSL_ST_RENEGOTIATE:
s->renegotiate = 1;
/* s->state=SSL_ST_ACCEPT; */
case SSL_ST_BEFORE:
case SSL_ST_ACCEPT:
case SSL_ST_BEFORE | SSL_ST_ACCEPT:
case SSL_ST_OK | SSL_ST_ACCEPT:
s->server = 1;
if (cb != NULL)
cb(s, SSL_CB_HANDSHAKE_START, 1);
if ((s->version >> 8) != 3) {
SSLerr(SSL_F_SSL3_ACCEPT, ERR_R_INTERNAL_ERROR);
s->state = SSL_ST_ERR;
return -1;
}
s->type = SSL_ST_ACCEPT;
if (s->init_buf == NULL) {
if ((buf = BUF_MEM_new()) == NULL) {
ret = -1;
s->state = SSL_ST_ERR;
goto end;
}
if (!BUF_MEM_grow(buf, SSL3_RT_MAX_PLAIN_LENGTH)) {
BUF_MEM_free(buf);
ret = -1;
s->state = SSL_ST_ERR;
goto end;
}
s->init_buf = buf;
}
if (!ssl3_setup_buffers(s)) {
ret = -1;
s->state = SSL_ST_ERR;
goto end;
}
s->init_num = 0;
s->s3->flags &= ~TLS1_FLAGS_SKIP_CERT_VERIFY;
s->s3->flags &= ~SSL3_FLAGS_CCS_OK;
/*
* Should have been reset by ssl3_get_finished, too.
*/
s->s3->change_cipher_spec = 0;
if (s->state != SSL_ST_RENEGOTIATE) {
/*
* Ok, we now need to push on a buffering BIO so that the
* output is sent in a way that TCP likes :-)
*/
if (!ssl_init_wbio_buffer(s, 1)) {
ret = -1;
s->state = SSL_ST_ERR;
goto end;
}
if (!ssl3_init_finished_mac(s)) {
ret = -1;
s->state = SSL_ST_ERR;
goto end;
}
s->state = SSL3_ST_SR_CLNT_HELLO_A;
s->ctx->stats.sess_accept++;
} else if (!s->s3->send_connection_binding &&
!(s->options &
SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)) {
/*
* Server attempting to renegotiate with client that doesn't
* support secure renegotiation.
*/
SSLerr(SSL_F_SSL3_ACCEPT,
SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
ret = -1;
s->state = SSL_ST_ERR;
goto end;
} else {
/*
* s->state == SSL_ST_RENEGOTIATE, we will just send a
* HelloRequest
*/
s->ctx->stats.sess_accept_renegotiate++;
s->state = SSL3_ST_SW_HELLO_REQ_A;
}
break;
case SSL3_ST_SW_HELLO_REQ_A:
case SSL3_ST_SW_HELLO_REQ_B:
s->shutdown = 0;
ret = ssl3_send_hello_request(s);
if (ret <= 0)
goto end;
s->s3->tmp.next_state = SSL3_ST_SW_HELLO_REQ_C;
s->state = SSL3_ST_SW_FLUSH;
s->init_num = 0;
if (!ssl3_init_finished_mac(s)) {
ret = -1;
s->state = SSL_ST_ERR;
goto end;
}
break;
case SSL3_ST_SW_HELLO_REQ_C:
s->state = SSL_ST_OK;
break;
case SSL3_ST_SR_CLNT_HELLO_A:
case SSL3_ST_SR_CLNT_HELLO_B:
case SSL3_ST_SR_CLNT_HELLO_C:
s->shutdown = 0;
ret = ssl3_get_client_hello(s);
if (ret <= 0)
goto end;
#ifndef OPENSSL_NO_SRP
s->state = SSL3_ST_SR_CLNT_HELLO_D;
case SSL3_ST_SR_CLNT_HELLO_D:
{
int al;
if ((ret = ssl_check_srp_ext_ClientHello(s, &al)) < 0) {
/*
* callback indicates firther work to be done
*/
s->rwstate = SSL_X509_LOOKUP;
goto end;
}
if (ret != SSL_ERROR_NONE) {
ssl3_send_alert(s, SSL3_AL_FATAL, al);
/*
* This is not really an error but the only means to for
* a client to detect whether srp is supported.
*/
if (al != TLS1_AD_UNKNOWN_PSK_IDENTITY)
SSLerr(SSL_F_SSL3_ACCEPT, SSL_R_CLIENTHELLO_TLSEXT);
ret = -1;
s->state = SSL_ST_ERR;
goto end;
}
}
#endif
s->renegotiate = 2;
s->state = SSL3_ST_SW_SRVR_HELLO_A;
s->init_num = 0;
break;
case SSL3_ST_SW_SRVR_HELLO_A:
case SSL3_ST_SW_SRVR_HELLO_B:
ret = ssl3_send_server_hello(s);
if (ret <= 0)
goto end;
#ifndef OPENSSL_NO_TLSEXT
if (s->hit) {
if (s->tlsext_ticket_expected)
s->state = SSL3_ST_SW_SESSION_TICKET_A;
else
s->state = SSL3_ST_SW_CHANGE_A;
}
#else
if (s->hit)
s->state = SSL3_ST_SW_CHANGE_A;
#endif
else
s->state = SSL3_ST_SW_CERT_A;
s->init_num = 0;
break;
case SSL3_ST_SW_CERT_A:
case SSL3_ST_SW_CERT_B:
/* Check if it is anon DH or anon ECDH, */
/* normal PSK or KRB5 or SRP */
if (!
(s->s3->tmp.
new_cipher->algorithm_auth & (SSL_aNULL | SSL_aKRB5 |
SSL_aSRP))
&& !(s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK)) {
ret = ssl3_send_server_certificate(s);
if (ret <= 0)
goto end;
#ifndef OPENSSL_NO_TLSEXT
if (s->tlsext_status_expected)
s->state = SSL3_ST_SW_CERT_STATUS_A;
else
s->state = SSL3_ST_SW_KEY_EXCH_A;
} else {
skip = 1;
s->state = SSL3_ST_SW_KEY_EXCH_A;
}
#else
} else
skip = 1;
s->state = SSL3_ST_SW_KEY_EXCH_A;
#endif
s->init_num = 0;
break;
case SSL3_ST_SW_KEY_EXCH_A:
case SSL3_ST_SW_KEY_EXCH_B:
alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
/*
* clear this, it may get reset by
* send_server_key_exchange
*/
s->s3->tmp.use_rsa_tmp = 0;
/*
* only send if a DH key exchange, fortezza or RSA but we have a
* sign only certificate PSK: may send PSK identity hints For
* ECC ciphersuites, we send a serverKeyExchange message only if
* the cipher suite is either ECDH-anon or ECDHE. In other cases,
* the server certificate contains the server's public key for
* key exchange.
*/
if (0
/*
* PSK: send ServerKeyExchange if PSK identity hint if
* provided
*/
#ifndef OPENSSL_NO_PSK
|| ((alg_k & SSL_kPSK) && s->ctx->psk_identity_hint)
#endif
#ifndef OPENSSL_NO_SRP
/* SRP: send ServerKeyExchange */
|| (alg_k & SSL_kSRP)
#endif
|| (alg_k & SSL_kEDH)
|| (alg_k & SSL_kEECDH)
|| ((alg_k & SSL_kRSA)
&& (s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey == NULL
|| (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher)
&& EVP_PKEY_size(s->cert->pkeys
[SSL_PKEY_RSA_ENC].privatekey) *
8 > SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher)
)
)
)
) {
ret = ssl3_send_server_key_exchange(s);
if (ret <= 0)
goto end;
} else
skip = 1;
s->state = SSL3_ST_SW_CERT_REQ_A;
s->init_num = 0;
break;
case SSL3_ST_SW_CERT_REQ_A:
case SSL3_ST_SW_CERT_REQ_B:
if ( /* don't request cert unless asked for it: */
!(s->verify_mode & SSL_VERIFY_PEER) ||
/*
* if SSL_VERIFY_CLIENT_ONCE is set, don't request cert
* during re-negotiation:
*/
(s->s3->tmp.finish_md_len != 0 &&
(s->verify_mode & SSL_VERIFY_CLIENT_ONCE)) ||
/*
* never request cert in anonymous ciphersuites (see
* section "Certificate request" in SSL 3 drafts and in
* RFC 2246):
*/
((s->s3->tmp.new_cipher->algorithm_auth & SSL_aNULL) &&
/*
* ... except when the application insists on
* verification (against the specs, but s3_clnt.c accepts
* this for SSL 3)
*/
!(s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) ||
/*
* never request cert in Kerberos ciphersuites
*/
(s->s3->tmp.new_cipher->algorithm_auth & SSL_aKRB5) ||
/* don't request certificate for SRP auth */
(s->s3->tmp.new_cipher->algorithm_auth & SSL_aSRP)
/*
* With normal PSK Certificates and Certificate Requests
* are omitted
*/
|| (s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK)) {
/* no cert request */
skip = 1;
s->s3->tmp.cert_request = 0;
s->state = SSL3_ST_SW_SRVR_DONE_A;
if (s->s3->handshake_buffer) {
if (!ssl3_digest_cached_records(s)) {
s->state = SSL_ST_ERR;
return -1;
}
}
} else {
s->s3->tmp.cert_request = 1;
ret = ssl3_send_certificate_request(s);
if (ret <= 0)
goto end;
#ifndef NETSCAPE_HANG_BUG
s->state = SSL3_ST_SW_SRVR_DONE_A;
#else
s->state = SSL3_ST_SW_FLUSH;
s->s3->tmp.next_state = SSL3_ST_SR_CERT_A;
#endif
s->init_num = 0;
}
break;
case SSL3_ST_SW_SRVR_DONE_A:
case SSL3_ST_SW_SRVR_DONE_B:
ret = ssl3_send_server_done(s);
if (ret <= 0)
goto end;
s->s3->tmp.next_state = SSL3_ST_SR_CERT_A;
s->state = SSL3_ST_SW_FLUSH;
s->init_num = 0;
break;
case SSL3_ST_SW_FLUSH:
/*
* This code originally checked to see if any data was pending
* using BIO_CTRL_INFO and then flushed. This caused problems as
* documented in PR#1939. The proposed fix doesn't completely
* resolve this issue as buggy implementations of
* BIO_CTRL_PENDING still exist. So instead we just flush
* unconditionally.
*/
s->rwstate = SSL_WRITING;
if (BIO_flush(s->wbio) <= 0) {
ret = -1;
goto end;
}
s->rwstate = SSL_NOTHING;
s->state = s->s3->tmp.next_state;
break;
case SSL3_ST_SR_CERT_A:
case SSL3_ST_SR_CERT_B:
if (s->s3->tmp.cert_request) {
ret = ssl3_get_client_certificate(s);
if (ret <= 0)
goto end;
}
s->init_num = 0;
s->state = SSL3_ST_SR_KEY_EXCH_A;
break;
case SSL3_ST_SR_KEY_EXCH_A:
case SSL3_ST_SR_KEY_EXCH_B:
ret = ssl3_get_client_key_exchange(s);
if (ret <= 0)
goto end;
if (ret == 2) {
/*
* For the ECDH ciphersuites when the client sends its ECDH
* pub key in a certificate, the CertificateVerify message is
* not sent. Also for GOST ciphersuites when the client uses
* its key from the certificate for key exchange.
*/
#if defined(OPENSSL_NO_TLSEXT) || defined(OPENSSL_NO_NEXTPROTONEG)
s->state = SSL3_ST_SR_FINISHED_A;
#else
if (s->s3->next_proto_neg_seen)
s->state = SSL3_ST_SR_NEXT_PROTO_A;
else
s->state = SSL3_ST_SR_FINISHED_A;
#endif
s->init_num = 0;
} else if (SSL_USE_SIGALGS(s)) {
s->state = SSL3_ST_SR_CERT_VRFY_A;
s->init_num = 0;
if (!s->session->peer)
break;
/*
* For sigalgs freeze the handshake buffer at this point and
* digest cached records.
*/
if (!s->s3->handshake_buffer) {
SSLerr(SSL_F_SSL3_ACCEPT, ERR_R_INTERNAL_ERROR);
s->state = SSL_ST_ERR;
return -1;
}
s->s3->flags |= TLS1_FLAGS_KEEP_HANDSHAKE;
if (!ssl3_digest_cached_records(s)) {
s->state = SSL_ST_ERR;
return -1;
}
} else {
int offset = 0;
int dgst_num;
s->state = SSL3_ST_SR_CERT_VRFY_A;
s->init_num = 0;
/*
* We need to get hashes here so if there is a client cert,
* it can be verified FIXME - digest processing for
* CertificateVerify should be generalized. But it is next
* step
*/
if (s->s3->handshake_buffer) {
if (!ssl3_digest_cached_records(s)) {
s->state = SSL_ST_ERR;
return -1;
}
}
for (dgst_num = 0; dgst_num < SSL_MAX_DIGEST; dgst_num++)
if (s->s3->handshake_dgst[dgst_num]) {
int dgst_size;
s->method->ssl3_enc->cert_verify_mac(s,
EVP_MD_CTX_type
(s->
s3->handshake_dgst
[dgst_num]),
&(s->s3->
tmp.cert_verify_md
[offset]));
dgst_size =
EVP_MD_CTX_size(s->s3->handshake_dgst[dgst_num]);
if (dgst_size < 0) {
s->state = SSL_ST_ERR;
ret = -1;
goto end;
}
offset += dgst_size;
}
}
break;
case SSL3_ST_SR_CERT_VRFY_A:
case SSL3_ST_SR_CERT_VRFY_B:
ret = ssl3_get_cert_verify(s);
if (ret <= 0)
goto end;
#if defined(OPENSSL_NO_TLSEXT) || defined(OPENSSL_NO_NEXTPROTONEG)
s->state = SSL3_ST_SR_FINISHED_A;
#else
if (s->s3->next_proto_neg_seen)
s->state = SSL3_ST_SR_NEXT_PROTO_A;
else
s->state = SSL3_ST_SR_FINISHED_A;
#endif
s->init_num = 0;
break;
#if !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_NEXTPROTONEG)
case SSL3_ST_SR_NEXT_PROTO_A:
case SSL3_ST_SR_NEXT_PROTO_B:
/*
* Enable CCS for NPN. Receiving a CCS clears the flag, so make
* sure not to re-enable it to ban duplicates. This *should* be the
* first time we have received one - but we check anyway to be
* cautious.
* s->s3->change_cipher_spec is set when a CCS is
* processed in s3_pkt.c, and remains set until
* the client's Finished message is read.
*/
if (!s->s3->change_cipher_spec)
s->s3->flags |= SSL3_FLAGS_CCS_OK;
ret = ssl3_get_next_proto(s);
if (ret <= 0)
goto end;
s->init_num = 0;
s->state = SSL3_ST_SR_FINISHED_A;
break;
#endif
case SSL3_ST_SR_FINISHED_A:
case SSL3_ST_SR_FINISHED_B:
/*
* Enable CCS for handshakes without NPN. In NPN the CCS flag has
* already been set. Receiving a CCS clears the flag, so make
* sure not to re-enable it to ban duplicates.
* s->s3->change_cipher_spec is set when a CCS is
* processed in s3_pkt.c, and remains set until
* the client's Finished message is read.
*/
if (!s->s3->change_cipher_spec)
s->s3->flags |= SSL3_FLAGS_CCS_OK;
ret = ssl3_get_finished(s, SSL3_ST_SR_FINISHED_A,
SSL3_ST_SR_FINISHED_B);
if (ret <= 0)
goto end;
if (s->hit)
s->state = SSL_ST_OK;
#ifndef OPENSSL_NO_TLSEXT
else if (s->tlsext_ticket_expected)
s->state = SSL3_ST_SW_SESSION_TICKET_A;
#endif
else
s->state = SSL3_ST_SW_CHANGE_A;
s->init_num = 0;
break;
#ifndef OPENSSL_NO_TLSEXT
case SSL3_ST_SW_SESSION_TICKET_A:
case SSL3_ST_SW_SESSION_TICKET_B:
ret = ssl3_send_newsession_ticket(s);
if (ret <= 0)
goto end;
s->state = SSL3_ST_SW_CHANGE_A;
s->init_num = 0;
break;
case SSL3_ST_SW_CERT_STATUS_A:
case SSL3_ST_SW_CERT_STATUS_B:
ret = ssl3_send_cert_status(s);
if (ret <= 0)
goto end;
s->state = SSL3_ST_SW_KEY_EXCH_A;
s->init_num = 0;
break;
#endif
case SSL3_ST_SW_CHANGE_A:
case SSL3_ST_SW_CHANGE_B:
s->session->cipher = s->s3->tmp.new_cipher;
if (!s->method->ssl3_enc->setup_key_block(s)) {
ret = -1;
s->state = SSL_ST_ERR;
goto end;
}
ret = ssl3_send_change_cipher_spec(s,
SSL3_ST_SW_CHANGE_A,
SSL3_ST_SW_CHANGE_B);
if (ret <= 0)
goto end;
s->state = SSL3_ST_SW_FINISHED_A;
s->init_num = 0;
if (!s->method->ssl3_enc->change_cipher_state(s,
SSL3_CHANGE_CIPHER_SERVER_WRITE))
{
ret = -1;
s->state = SSL_ST_ERR;
goto end;
}
break;
case SSL3_ST_SW_FINISHED_A:
case SSL3_ST_SW_FINISHED_B:
ret = ssl3_send_finished(s,
SSL3_ST_SW_FINISHED_A,
SSL3_ST_SW_FINISHED_B,
s->method->
ssl3_enc->server_finished_label,
s->method->
ssl3_enc->server_finished_label_len);
if (ret <= 0)
goto end;
s->state = SSL3_ST_SW_FLUSH;
if (s->hit) {
#if defined(OPENSSL_NO_TLSEXT) || defined(OPENSSL_NO_NEXTPROTONEG)
s->s3->tmp.next_state = SSL3_ST_SR_FINISHED_A;
#else
if (s->s3->next_proto_neg_seen) {
s->s3->tmp.next_state = SSL3_ST_SR_NEXT_PROTO_A;
} else
s->s3->tmp.next_state = SSL3_ST_SR_FINISHED_A;
#endif
} else
s->s3->tmp.next_state = SSL_ST_OK;
s->init_num = 0;
break;
case SSL_ST_OK:
/* clean a few things up */
ssl3_cleanup_key_block(s);
BUF_MEM_free(s->init_buf);
s->init_buf = NULL;
/* remove buffering on output */
ssl_free_wbio_buffer(s);
s->init_num = 0;
if (s->renegotiate == 2) { /* skipped if we just sent a
* HelloRequest */
s->renegotiate = 0;
s->new_session = 0;
ssl_update_cache(s, SSL_SESS_CACHE_SERVER);
s->ctx->stats.sess_accept_good++;
/* s->server=1; */
s->handshake_func = ssl3_accept;
if (cb != NULL)
cb(s, SSL_CB_HANDSHAKE_DONE, 1);
}
ret = 1;
goto end;
/* break; */
case SSL_ST_ERR:
default:
SSLerr(SSL_F_SSL3_ACCEPT, SSL_R_UNKNOWN_STATE);
ret = -1;
goto end;
/* break; */
}
if (!s->s3->tmp.reuse_message && !skip) {
if (s->debug) {
if ((ret = BIO_flush(s->wbio)) <= 0)
goto end;
}
if ((cb != NULL) && (s->state != state)) {
new_state = s->state;
s->state = state;
cb(s, SSL_CB_ACCEPT_LOOP, 1);
s->state = new_state;
}
}
skip = 0;
}
end:
/* BIO_flush(s->wbio); */
s->in_handshake--;
if (cb != NULL)
cb(s, SSL_CB_ACCEPT_EXIT, ret);
return (ret);
}
int ssl3_send_hello_request(SSL *s)
{
if (s->state == SSL3_ST_SW_HELLO_REQ_A) {
ssl_set_handshake_header(s, SSL3_MT_HELLO_REQUEST, 0);
s->state = SSL3_ST_SW_HELLO_REQ_B;
}
/* SSL3_ST_SW_HELLO_REQ_B */
return ssl_do_write(s);
}
int ssl3_get_client_hello(SSL *s)
{
int i, j, ok, al = SSL_AD_INTERNAL_ERROR, ret = -1, cookie_valid = 0;
unsigned int cookie_len;
long n;
unsigned long id;
unsigned char *p, *d;
SSL_CIPHER *c;
#ifndef OPENSSL_NO_COMP
unsigned char *q;
SSL_COMP *comp = NULL;
#endif
STACK_OF(SSL_CIPHER) *ciphers = NULL;
if (s->state == SSL3_ST_SR_CLNT_HELLO_C && !s->first_packet)
goto retry_cert;
/*
* We do this so that we will respond with our native type. If we are
* TLSv1 and we get SSLv3, we will respond with TLSv1, This down
* switching should be handled by a different method. If we are SSLv3, we
* will respond with SSLv3, even if prompted with TLSv1.
*/
if (s->state == SSL3_ST_SR_CLNT_HELLO_A) {
s->state = SSL3_ST_SR_CLNT_HELLO_B;
}
s->first_packet = 1;
n = s->method->ssl_get_message(s,
SSL3_ST_SR_CLNT_HELLO_B,
SSL3_ST_SR_CLNT_HELLO_C,
SSL3_MT_CLIENT_HELLO,
SSL3_RT_MAX_PLAIN_LENGTH, &ok);
if (!ok)
return ((int)n);
s->first_packet = 0;
d = p = (unsigned char *)s->init_msg;
/*
* 2 bytes for client version, SSL3_RANDOM_SIZE bytes for random, 1 byte
* for session id length
*/
if (n < 2 + SSL3_RANDOM_SIZE + 1) {
al = SSL_AD_DECODE_ERROR;
SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_TOO_SHORT);
goto f_err;
}
/*
* use version from inside client hello, not from record header (may
* differ: see RFC 2246, Appendix E, second paragraph)
*/
s->client_version = (((int)p[0]) << 8) | (int)p[1];
p += 2;
if (SSL_IS_DTLS(s) ? (s->client_version > s->version &&
s->method->version != DTLS_ANY_VERSION)
: (s->client_version < s->version)) {
SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_WRONG_VERSION_NUMBER);
if ((s->client_version >> 8) == SSL3_VERSION_MAJOR &&
!s->enc_write_ctx && !s->write_hash) {
/*
* similar to ssl3_get_record, send alert using remote version
* number
*/
s->version = s->client_version;
}
al = SSL_AD_PROTOCOL_VERSION;
goto f_err;
}
/*
* If we require cookies and this ClientHello doesn't contain one, just
* return since we do not want to allocate any memory yet. So check
* cookie length...
*/
if (SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE) {
unsigned int session_length, cookie_length;
session_length = *(p + SSL3_RANDOM_SIZE);
if (SSL3_RANDOM_SIZE + session_length + 1
>= (unsigned int)((d + n) - p)) {
al = SSL_AD_DECODE_ERROR;
SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_TOO_SHORT);
goto f_err;
}
cookie_length = *(p + SSL3_RANDOM_SIZE + session_length + 1);
if (cookie_length == 0)
return 1;
}
/* load the client random */
memcpy(s->s3->client_random, p, SSL3_RANDOM_SIZE);
p += SSL3_RANDOM_SIZE;
/* get the session-id */
j = *(p++);
if ((d + n) - p < j) {
al = SSL_AD_DECODE_ERROR;
SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_TOO_SHORT);
goto f_err;
}
if ((j < 0) || (j > SSL_MAX_SSL_SESSION_ID_LENGTH)) {
al = SSL_AD_DECODE_ERROR;
SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH);
goto f_err;
}
s->hit = 0;
/*
* Versions before 0.9.7 always allow clients to resume sessions in
* renegotiation. 0.9.7 and later allow this by default, but optionally
* ignore resumption requests with flag
* SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (it's a new flag rather
* than a change to default behavior so that applications relying on this
* for security won't even compile against older library versions).
* 1.0.1 and later also have a function SSL_renegotiate_abbreviated() to
* request renegotiation but not a new session (s->new_session remains
* unset): for servers, this essentially just means that the
* SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION setting will be ignored.
*/
if ((s->new_session
&& (s->options & SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION))) {
if (!ssl_get_new_session(s, 1))
goto err;
} else {
i = ssl_get_prev_session(s, p, j, d + n);
/*
* Only resume if the session's version matches the negotiated
* version.
* RFC 5246 does not provide much useful advice on resumption
* with a different protocol version. It doesn't forbid it but
* the sanity of such behaviour would be questionable.
* In practice, clients do not accept a version mismatch and
* will abort the handshake with an error.
*/
if (i == 1 && s->version == s->session->ssl_version) { /* previous
* session */
s->hit = 1;
} else if (i == -1)
goto err;
else { /* i == 0 */
if (!ssl_get_new_session(s, 1))
goto err;
}
}
p += j;
if (SSL_IS_DTLS(s)) {
/* cookie stuff */
if ((d + n) - p < 1) {
al = SSL_AD_DECODE_ERROR;
SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_TOO_SHORT);
goto f_err;
}
cookie_len = *(p++);
if ((unsigned int)((d + n ) - p) < cookie_len) {
al = SSL_AD_DECODE_ERROR;
SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_TOO_SHORT);
goto f_err;
}
/*
* The ClientHello may contain a cookie even if the
* HelloVerify message has not been sent--make sure that it
* does not cause an overflow.
*/
if (cookie_len > sizeof(s->d1->rcvd_cookie)) {
/* too much data */
al = SSL_AD_DECODE_ERROR;
SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_COOKIE_MISMATCH);
goto f_err;
}
/* verify the cookie if appropriate option is set. */
if ((SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE) && cookie_len > 0) {
memcpy(s->d1->rcvd_cookie, p, cookie_len);
if (s->ctx->app_verify_cookie_cb != NULL) {
if (s->ctx->app_verify_cookie_cb(s, s->d1->rcvd_cookie,
cookie_len) == 0) {
al = SSL_AD_HANDSHAKE_FAILURE;
SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
SSL_R_COOKIE_MISMATCH);
goto f_err;
}
/* else cookie verification succeeded */
}
/* default verification */
else if (memcmp(s->d1->rcvd_cookie, s->d1->cookie,
s->d1->cookie_len) != 0) {
al = SSL_AD_HANDSHAKE_FAILURE;
SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_COOKIE_MISMATCH);
goto f_err;
}
cookie_valid = 1;
}
p += cookie_len;
if (s->method->version == DTLS_ANY_VERSION) {
/* Select version to use */
if (s->client_version <= DTLS1_2_VERSION &&
!(s->options & SSL_OP_NO_DTLSv1_2)) {
s->version = DTLS1_2_VERSION;
s->method = DTLSv1_2_server_method();
} else if (tls1_suiteb(s)) {
SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
SSL_R_ONLY_DTLS_1_2_ALLOWED_IN_SUITEB_MODE);
s->version = s->client_version;
al = SSL_AD_PROTOCOL_VERSION;
goto f_err;
} else if (s->client_version <= DTLS1_VERSION &&
!(s->options & SSL_OP_NO_DTLSv1)) {
s->version = DTLS1_VERSION;
s->method = DTLSv1_server_method();
} else {
SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
SSL_R_WRONG_VERSION_NUMBER);
s->version = s->client_version;
al = SSL_AD_PROTOCOL_VERSION;
goto f_err;
}
s->session->ssl_version = s->version;
}
}
if ((d + n ) - p < 2) {
al = SSL_AD_DECODE_ERROR;
SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_TOO_SHORT);
goto f_err;
}
n2s(p, i);
if (i == 0) {
al = SSL_AD_ILLEGAL_PARAMETER;
SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_NO_CIPHERS_SPECIFIED);
goto f_err;
}
/* i bytes of cipher data + 1 byte for compression length later */
if ((d + n) - p < i + 1) {
/* not enough data */
al = SSL_AD_DECODE_ERROR;
SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH);
goto f_err;
}
if (ssl_bytes_to_cipher_list(s, p, i, &(ciphers)) == NULL) {
goto err;
}
p += i;
/* If it is a hit, check that the cipher is in the list */
if (s->hit) {
j = 0;
id = s->session->cipher->id;
#ifdef CIPHER_DEBUG
fprintf(stderr, "client sent %d ciphers\n",
sk_SSL_CIPHER_num(ciphers));
#endif
for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
c = sk_SSL_CIPHER_value(ciphers, i);
#ifdef CIPHER_DEBUG
fprintf(stderr, "client [%2d of %2d]:%s\n",
i, sk_SSL_CIPHER_num(ciphers), SSL_CIPHER_get_name(c));
#endif
if (c->id == id) {
j = 1;
break;
}
}
/*
* Disabled because it can be used in a ciphersuite downgrade attack:
* CVE-2010-4180.
*/
#if 0
if (j == 0 && (s->options & SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG)
&& (sk_SSL_CIPHER_num(ciphers) == 1)) {
/*
* Special case as client bug workaround: the previously used
* cipher may not be in the current list, the client instead
* might be trying to continue using a cipher that before wasn't
* chosen due to server preferences. We'll have to reject the
* connection if the cipher is not enabled, though.
*/
c = sk_SSL_CIPHER_value(ciphers, 0);
if (sk_SSL_CIPHER_find(SSL_get_ciphers(s), c) >= 0) {
s->session->cipher = c;
j = 1;
}
}
#endif
if (j == 0) {
/*
* we need to have the cipher in the cipher list if we are asked
* to reuse it
*/
al = SSL_AD_ILLEGAL_PARAMETER;
SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
SSL_R_REQUIRED_CIPHER_MISSING);
goto f_err;
}
}
/* compression */
i = *(p++);
if ((d + n) - p < i) {
/* not enough data */
al = SSL_AD_DECODE_ERROR;
SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH);
goto f_err;
}
#ifndef OPENSSL_NO_COMP
q = p;
#endif
for (j = 0; j < i; j++) {
if (p[j] == 0)
break;
}
p += i;
if (j >= i) {
/* no compress */
al = SSL_AD_DECODE_ERROR;
SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_NO_COMPRESSION_SPECIFIED);
goto f_err;
}
#ifndef OPENSSL_NO_TLSEXT
/* TLS extensions */
if (s->version >= SSL3_VERSION) {
if (!ssl_parse_clienthello_tlsext(s, &p, d + n)) {
SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_PARSE_TLSEXT);
goto err;
}
}
/*
* Check if we want to use external pre-shared secret for this handshake
* for not reused session only. We need to generate server_random before
* calling tls_session_secret_cb in order to allow SessionTicket
* processing to use it in key derivation.
*/
{
unsigned char *pos;
pos = s->s3->server_random;
if (ssl_fill_hello_random(s, 1, pos, SSL3_RANDOM_SIZE) <= 0) {
goto f_err;
}
}
if (!s->hit && s->version >= TLS1_VERSION && s->tls_session_secret_cb) {
SSL_CIPHER *pref_cipher = NULL;
s->session->master_key_length = sizeof(s->session->master_key);
if (s->tls_session_secret_cb(s, s->session->master_key,
&s->session->master_key_length, ciphers,
&pref_cipher,
s->tls_session_secret_cb_arg)) {
s->hit = 1;
s->session->ciphers = ciphers;
s->session->verify_result = X509_V_OK;
ciphers = NULL;
/* check if some cipher was preferred by call back */
pref_cipher =
pref_cipher ? pref_cipher : ssl3_choose_cipher(s,
s->
session->ciphers,
SSL_get_ciphers
(s));
if (pref_cipher == NULL) {
al = SSL_AD_HANDSHAKE_FAILURE;
SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_NO_SHARED_CIPHER);
goto f_err;
}
s->session->cipher = pref_cipher;
if (s->cipher_list)
sk_SSL_CIPHER_free(s->cipher_list);
if (s->cipher_list_by_id)
sk_SSL_CIPHER_free(s->cipher_list_by_id);
s->cipher_list = sk_SSL_CIPHER_dup(s->session->ciphers);
s->cipher_list_by_id = sk_SSL_CIPHER_dup(s->session->ciphers);
}
}
#endif
/*
* Worst case, we will use the NULL compression, but if we have other
* options, we will now look for them. We have i-1 compression
* algorithms from the client, starting at q.
*/
s->s3->tmp.new_compression = NULL;
#ifndef OPENSSL_NO_COMP
/* This only happens if we have a cache hit */
if (s->session->compress_meth != 0) {
int m, comp_id = s->session->compress_meth;
/* Perform sanity checks on resumed compression algorithm */
/* Can't disable compression */
if (s->options & SSL_OP_NO_COMPRESSION) {
SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
SSL_R_INCONSISTENT_COMPRESSION);
goto f_err;
}
/* Look for resumed compression method */
for (m = 0; m < sk_SSL_COMP_num(s->ctx->comp_methods); m++) {
comp = sk_SSL_COMP_value(s->ctx->comp_methods, m);
if (comp_id == comp->id) {
s->s3->tmp.new_compression = comp;
break;
}
}
if (s->s3->tmp.new_compression == NULL) {
SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
SSL_R_INVALID_COMPRESSION_ALGORITHM);
goto f_err;
}
/* Look for resumed method in compression list */
for (m = 0; m < i; m++) {
if (q[m] == comp_id)
break;
}
if (m >= i) {
al = SSL_AD_ILLEGAL_PARAMETER;
SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
SSL_R_REQUIRED_COMPRESSSION_ALGORITHM_MISSING);
goto f_err;
}
} else if (s->hit)
comp = NULL;
else if (!(s->options & SSL_OP_NO_COMPRESSION) && s->ctx->comp_methods) {
/* See if we have a match */
int m, nn, o, v, done = 0;
nn = sk_SSL_COMP_num(s->ctx->comp_methods);
for (m = 0; m < nn; m++) {
comp = sk_SSL_COMP_value(s->ctx->comp_methods, m);
v = comp->id;
for (o = 0; o < i; o++) {
if (v == q[o]) {
done = 1;
break;
}
}
if (done)
break;
}
if (done)
s->s3->tmp.new_compression = comp;
else
comp = NULL;
}
#else
/*
* If compression is disabled we'd better not try to resume a session
* using compression.
*/
if (s->session->compress_meth != 0) {
SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_INCONSISTENT_COMPRESSION);
goto f_err;
}
#endif
/*
* Given s->session->ciphers and SSL_get_ciphers, we must pick a cipher
*/
if (!s->hit) {
#ifdef OPENSSL_NO_COMP
s->session->compress_meth = 0;
#else
s->session->compress_meth = (comp == NULL) ? 0 : comp->id;
#endif
if (s->session->ciphers != NULL)
sk_SSL_CIPHER_free(s->session->ciphers);
s->session->ciphers = ciphers;
if (ciphers == NULL) {
al = SSL_AD_INTERNAL_ERROR;
SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
goto f_err;
}
ciphers = NULL;
if (!tls1_set_server_sigalgs(s)) {
SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_CLIENTHELLO_TLSEXT);
goto err;
}
/* Let cert callback update server certificates if required */
retry_cert:
if (s->cert->cert_cb) {
int rv = s->cert->cert_cb(s, s->cert->cert_cb_arg);
if (rv == 0) {
al = SSL_AD_INTERNAL_ERROR;
SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_CERT_CB_ERROR);
goto f_err;
}
if (rv < 0) {
s->rwstate = SSL_X509_LOOKUP;
return -1;
}
s->rwstate = SSL_NOTHING;
}
c = ssl3_choose_cipher(s, s->session->ciphers, SSL_get_ciphers(s));
if (c == NULL) {
al = SSL_AD_HANDSHAKE_FAILURE;
SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_NO_SHARED_CIPHER);
goto f_err;
}
s->s3->tmp.new_cipher = c;
} else {
/* Session-id reuse */
#ifdef REUSE_CIPHER_BUG
STACK_OF(SSL_CIPHER) *sk;
SSL_CIPHER *nc = NULL;
SSL_CIPHER *ec = NULL;
if (s->options & SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG) {
sk = s->session->ciphers;
for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) {
c = sk_SSL_CIPHER_value(sk, i);
if (c->algorithm_enc & SSL_eNULL)
nc = c;
if (SSL_C_IS_EXPORT(c))
ec = c;
}
if (nc != NULL)
s->s3->tmp.new_cipher = nc;
else if (ec != NULL)
s->s3->tmp.new_cipher = ec;
else
s->s3->tmp.new_cipher = s->session->cipher;
} else
#endif
s->s3->tmp.new_cipher = s->session->cipher;
}
if (!SSL_USE_SIGALGS(s) || !(s->verify_mode & SSL_VERIFY_PEER)) {
if (!ssl3_digest_cached_records(s))
goto f_err;
}
/*-
* we now have the following setup.
* client_random
* cipher_list - our prefered list of ciphers
* ciphers - the clients prefered list of ciphers
* compression - basically ignored right now
* ssl version is set - sslv3
* s->session - The ssl session has been setup.
* s->hit - session reuse flag
* s->tmp.new_cipher - the new cipher to use.
*/
/* Handles TLS extensions that we couldn't check earlier */
if (s->version >= SSL3_VERSION) {
if (!ssl_check_clienthello_tlsext_late(s, &al)) {
SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_CLIENTHELLO_TLSEXT);
goto f_err;
}
}
ret = cookie_valid ? 2 : 1;
if (0) {
f_err:
ssl3_send_alert(s, SSL3_AL_FATAL, al);
err:
s->state = SSL_ST_ERR;
}
if (ciphers != NULL)
sk_SSL_CIPHER_free(ciphers);
return ret;
}
int ssl3_send_server_hello(SSL *s)
{
unsigned char *buf;
unsigned char *p, *d;
int i, sl;
int al = 0;
unsigned long l;
if (s->state == SSL3_ST_SW_SRVR_HELLO_A) {
buf = (unsigned char *)s->init_buf->data;
#ifdef OPENSSL_NO_TLSEXT
p = s->s3->server_random;
if (ssl_fill_hello_random(s, 1, p, SSL3_RANDOM_SIZE) <= 0) {
s->state = SSL_ST_ERR;
return -1;
}
#endif
/* Do the message type and length last */
d = p = ssl_handshake_start(s);
*(p++) = s->version >> 8;
*(p++) = s->version & 0xff;
/* Random stuff */
memcpy(p, s->s3->server_random, SSL3_RANDOM_SIZE);
p += SSL3_RANDOM_SIZE;
/*-
* There are several cases for the session ID to send
* back in the server hello:
* - For session reuse from the session cache,
* we send back the old session ID.
* - If stateless session reuse (using a session ticket)
* is successful, we send back the client's "session ID"
* (which doesn't actually identify the session).
* - If it is a new session, we send back the new
* session ID.
* - However, if we want the new session to be single-use,
* we send back a 0-length session ID.
* s->hit is non-zero in either case of session reuse,
* so the following won't overwrite an ID that we're supposed
* to send back.
*/
if (!(s->ctx->session_cache_mode & SSL_SESS_CACHE_SERVER)
&& !s->hit)
s->session->session_id_length = 0;
sl = s->session->session_id_length;
if (sl > (int)sizeof(s->session->session_id)) {
SSLerr(SSL_F_SSL3_SEND_SERVER_HELLO, ERR_R_INTERNAL_ERROR);
s->state = SSL_ST_ERR;
return -1;
}
*(p++) = sl;
memcpy(p, s->session->session_id, sl);
p += sl;
/* put the cipher */
i = ssl3_put_cipher_by_char(s->s3->tmp.new_cipher, p);
p += i;
/* put the compression method */
#ifdef OPENSSL_NO_COMP
*(p++) = 0;
#else
if (s->s3->tmp.new_compression == NULL)
*(p++) = 0;
else
*(p++) = s->s3->tmp.new_compression->id;
#endif
#ifndef OPENSSL_NO_TLSEXT
if (ssl_prepare_serverhello_tlsext(s) <= 0) {
SSLerr(SSL_F_SSL3_SEND_SERVER_HELLO, SSL_R_SERVERHELLO_TLSEXT);
s->state = SSL_ST_ERR;
return -1;
}
if ((p =
ssl_add_serverhello_tlsext(s, p, buf + SSL3_RT_MAX_PLAIN_LENGTH,
&al)) == NULL) {
ssl3_send_alert(s, SSL3_AL_FATAL, al);
SSLerr(SSL_F_SSL3_SEND_SERVER_HELLO, ERR_R_INTERNAL_ERROR);
s->state = SSL_ST_ERR;
return -1;
}
#endif
/* do the header */
l = (p - d);
ssl_set_handshake_header(s, SSL3_MT_SERVER_HELLO, l);
s->state = SSL3_ST_SW_SRVR_HELLO_B;
}
/* SSL3_ST_SW_SRVR_HELLO_B */
return ssl_do_write(s);
}
int ssl3_send_server_done(SSL *s)
{
if (s->state == SSL3_ST_SW_SRVR_DONE_A) {
ssl_set_handshake_header(s, SSL3_MT_SERVER_DONE, 0);
s->state = SSL3_ST_SW_SRVR_DONE_B;
}
/* SSL3_ST_SW_SRVR_DONE_B */
return ssl_do_write(s);
}
int ssl3_send_server_key_exchange(SSL *s)
{
#ifndef OPENSSL_NO_RSA
unsigned char *q;
int j, num;
RSA *rsa;
unsigned char md_buf[MD5_DIGEST_LENGTH + SHA_DIGEST_LENGTH];
unsigned int u;
#endif
#ifndef OPENSSL_NO_DH
# ifdef OPENSSL_NO_RSA
int j;
# endif
DH *dh = NULL, *dhp;
#endif
#ifndef OPENSSL_NO_ECDH
EC_KEY *ecdh = NULL, *ecdhp;
unsigned char *encodedPoint = NULL;
int encodedlen = 0;
int curve_id = 0;
BN_CTX *bn_ctx = NULL;
#endif
EVP_PKEY *pkey;
const EVP_MD *md = NULL;
unsigned char *p, *d;
int al, i;
unsigned long type;
int n;
CERT *cert;
BIGNUM *r[4];
int nr[4], kn;
BUF_MEM *buf;
EVP_MD_CTX md_ctx;
EVP_MD_CTX_init(&md_ctx);
if (s->state == SSL3_ST_SW_KEY_EXCH_A) {
type = s->s3->tmp.new_cipher->algorithm_mkey;
cert = s->cert;
buf = s->init_buf;
r[0] = r[1] = r[2] = r[3] = NULL;
n = 0;
#ifndef OPENSSL_NO_RSA
if (type & SSL_kRSA) {
rsa = cert->rsa_tmp;
if ((rsa == NULL) && (s->cert->rsa_tmp_cb != NULL)) {
rsa = s->cert->rsa_tmp_cb(s,
SSL_C_IS_EXPORT(s->s3->
tmp.new_cipher),
SSL_C_EXPORT_PKEYLENGTH(s->s3->
tmp.new_cipher));
if (rsa == NULL) {
al = SSL_AD_HANDSHAKE_FAILURE;
SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
SSL_R_ERROR_GENERATING_TMP_RSA_KEY);
goto f_err;
}
RSA_up_ref(rsa);
cert->rsa_tmp = rsa;
}
if (rsa == NULL) {
al = SSL_AD_HANDSHAKE_FAILURE;
SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
SSL_R_MISSING_TMP_RSA_KEY);
goto f_err;
}
r[0] = rsa->n;
r[1] = rsa->e;
s->s3->tmp.use_rsa_tmp = 1;
} else
#endif
#ifndef OPENSSL_NO_DH
if (type & SSL_kEDH) {
dhp = cert->dh_tmp;
if ((dhp == NULL) && (s->cert->dh_tmp_cb != NULL))
dhp = s->cert->dh_tmp_cb(s,
SSL_C_IS_EXPORT(s->s3->
tmp.new_cipher),
SSL_C_EXPORT_PKEYLENGTH(s->s3->
tmp.new_cipher));
if (dhp == NULL) {
al = SSL_AD_HANDSHAKE_FAILURE;
SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
SSL_R_MISSING_TMP_DH_KEY);
goto f_err;
}
if (s->s3->tmp.dh != NULL) {
SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
ERR_R_INTERNAL_ERROR);
goto err;
}
if ((dh = DHparams_dup(dhp)) == NULL) {
SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_DH_LIB);
goto err;
}
s->s3->tmp.dh = dh;
if (!DH_generate_key(dh)) {
SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_DH_LIB);
goto err;
}
r[0] = dh->p;
r[1] = dh->g;
r[2] = dh->pub_key;
} else
#endif
#ifndef OPENSSL_NO_ECDH
if (type & SSL_kEECDH) {
const EC_GROUP *group;
if (s->s3->tmp.ecdh != NULL) {
SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
ERR_R_INTERNAL_ERROR);
goto err;
}
ecdhp = cert->ecdh_tmp;
if (s->cert->ecdh_tmp_auto) {
/* Get NID of appropriate shared curve */
int nid = tls1_shared_curve(s, -2);
if (nid != NID_undef)
ecdhp = EC_KEY_new_by_curve_name(nid);
} else if ((ecdhp == NULL) && s->cert->ecdh_tmp_cb) {
ecdhp = s->cert->ecdh_tmp_cb(s,
SSL_C_IS_EXPORT(s->s3->
tmp.new_cipher),
SSL_C_EXPORT_PKEYLENGTH(s->
s3->tmp.new_cipher));
}
if (ecdhp == NULL) {
al = SSL_AD_HANDSHAKE_FAILURE;
SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
SSL_R_MISSING_TMP_ECDH_KEY);
goto f_err;
}
/* Duplicate the ECDH structure. */
if (s->cert->ecdh_tmp_auto)
ecdh = ecdhp;
else if ((ecdh = EC_KEY_dup(ecdhp)) == NULL) {
SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_ECDH_LIB);
goto err;
}
s->s3->tmp.ecdh = ecdh;
if ((EC_KEY_get0_public_key(ecdh) == NULL) ||
(EC_KEY_get0_private_key(ecdh) == NULL) ||
(s->options & SSL_OP_SINGLE_ECDH_USE)) {
if (!EC_KEY_generate_key(ecdh)) {
SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
ERR_R_ECDH_LIB);
goto err;
}
}
if (((group = EC_KEY_get0_group(ecdh)) == NULL) ||
(EC_KEY_get0_public_key(ecdh) == NULL) ||
(EC_KEY_get0_private_key(ecdh) == NULL)) {
SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_ECDH_LIB);
goto err;
}
if (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) &&
(EC_GROUP_get_degree(group) > 163)) {
SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
SSL_R_ECGROUP_TOO_LARGE_FOR_CIPHER);
goto err;
}
/*
* XXX: For now, we only support ephemeral ECDH keys over named
* (not generic) curves. For supported named curves, curve_id is
* non-zero.
*/
if ((curve_id =
tls1_ec_nid2curve_id(EC_GROUP_get_curve_name(group)))
== 0) {
SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
SSL_R_UNSUPPORTED_ELLIPTIC_CURVE);
goto err;
}
/*
* Encode the public key. First check the size of encoding and
* allocate memory accordingly.
*/
encodedlen = EC_POINT_point2oct(group,
EC_KEY_get0_public_key(ecdh),
POINT_CONVERSION_UNCOMPRESSED,
NULL, 0, NULL);
encodedPoint = (unsigned char *)
OPENSSL_malloc(encodedlen * sizeof(unsigned char));
bn_ctx = BN_CTX_new();
if ((encodedPoint == NULL) || (bn_ctx == NULL)) {
SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
ERR_R_MALLOC_FAILURE);
goto err;
}
encodedlen = EC_POINT_point2oct(group,
EC_KEY_get0_public_key(ecdh),
POINT_CONVERSION_UNCOMPRESSED,
encodedPoint, encodedlen, bn_ctx);
if (encodedlen == 0) {
SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_ECDH_LIB);
goto err;
}
BN_CTX_free(bn_ctx);
bn_ctx = NULL;
/*
* XXX: For now, we only support named (not generic) curves in
* ECDH ephemeral key exchanges. In this situation, we need four
* additional bytes to encode the entire ServerECDHParams
* structure.
*/
n = 4 + encodedlen;
/*
* We'll generate the serverKeyExchange message explicitly so we
* can set these to NULLs
*/
r[0] = NULL;
r[1] = NULL;
r[2] = NULL;
r[3] = NULL;
} else
#endif /* !OPENSSL_NO_ECDH */
#ifndef OPENSSL_NO_PSK
if (type & SSL_kPSK) {
/*
* reserve size for record length and PSK identity hint
*/
n += 2 + strlen(s->ctx->psk_identity_hint);
} else
#endif /* !OPENSSL_NO_PSK */
#ifndef OPENSSL_NO_SRP
if (type & SSL_kSRP) {
if ((s->srp_ctx.N == NULL) ||
(s->srp_ctx.g == NULL) ||
(s->srp_ctx.s == NULL) || (s->srp_ctx.B == NULL)) {
SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
SSL_R_MISSING_SRP_PARAM);
goto err;
}
r[0] = s->srp_ctx.N;
r[1] = s->srp_ctx.g;
r[2] = s->srp_ctx.s;
r[3] = s->srp_ctx.B;
} else
#endif
{
al = SSL_AD_HANDSHAKE_FAILURE;
SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE);
goto f_err;
}
for (i = 0; i < 4 && r[i] != NULL; i++) {
nr[i] = BN_num_bytes(r[i]);
#ifndef OPENSSL_NO_SRP
if ((i == 2) && (type & SSL_kSRP))
n += 1 + nr[i];
else
#endif
#ifndef OPENSSL_NO_DH
/*
* for interoperability with some versions of the Microsoft TLS
* stack, we need to zero pad the DHE pub key to the same length
* as the prime, so use the length of the prime here
*/
if ((i == 2) && (type & (SSL_kEDH)))
n += 2 + nr[0];
else
#endif
n += 2 + nr[i];
}
if (!(s->s3->tmp.new_cipher->algorithm_auth & (SSL_aNULL | SSL_aSRP))
&& !(s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK)) {
if ((pkey = ssl_get_sign_pkey(s, s->s3->tmp.new_cipher, &md))
== NULL) {
al = SSL_AD_DECODE_ERROR;
goto f_err;
}
kn = EVP_PKEY_size(pkey);
/* Allow space for signature algorithm */
if (SSL_USE_SIGALGS(s))
kn += 2;
/* Allow space for signature length */
kn += 2;
} else {
pkey = NULL;
kn = 0;
}
if (!BUF_MEM_grow_clean(buf, n + SSL_HM_HEADER_LENGTH(s) + kn)) {
SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_LIB_BUF);
goto err;
}
d = p = ssl_handshake_start(s);
for (i = 0; i < 4 && r[i] != NULL; i++) {
#ifndef OPENSSL_NO_SRP
if ((i == 2) && (type & SSL_kSRP)) {
*p = nr[i];
p++;
} else
#endif
#ifndef OPENSSL_NO_DH
/*
* for interoperability with some versions of the Microsoft TLS
* stack, we need to zero pad the DHE pub key to the same length
* as the prime
*/
if ((i == 2) && (type & (SSL_kEDH))) {
s2n(nr[0], p);
for (j = 0; j < (nr[0] - nr[2]); ++j) {
*p = 0;
++p;
}
} else
#endif
s2n(nr[i], p);
BN_bn2bin(r[i], p);
p += nr[i];
}
#ifndef OPENSSL_NO_ECDH
if (type & SSL_kEECDH) {
/*
* XXX: For now, we only support named (not generic) curves. In
* this situation, the serverKeyExchange message has: [1 byte
* CurveType], [2 byte CurveName] [1 byte length of encoded
* point], followed by the actual encoded point itself
*/
*p = NAMED_CURVE_TYPE;
p += 1;
*p = 0;
p += 1;
*p = curve_id;
p += 1;
*p = encodedlen;
p += 1;
memcpy((unsigned char *)p,
(unsigned char *)encodedPoint, encodedlen);
OPENSSL_free(encodedPoint);
encodedPoint = NULL;
p += encodedlen;
}
#endif
#ifndef OPENSSL_NO_PSK
if (type & SSL_kPSK) {
/* copy PSK identity hint */
s2n(strlen(s->ctx->psk_identity_hint), p);
strncpy((char *)p, s->ctx->psk_identity_hint,
strlen(s->ctx->psk_identity_hint));
p += strlen(s->ctx->psk_identity_hint);
}
#endif
/* not anonymous */
if (pkey != NULL) {
/*
* n is the length of the params, they start at &(d[4]) and p
* points to the space at the end.
*/
#ifndef OPENSSL_NO_RSA
if (pkey->type == EVP_PKEY_RSA && !SSL_USE_SIGALGS(s)) {
q = md_buf;
j = 0;
for (num = 2; num > 0; num--) {
EVP_MD_CTX_set_flags(&md_ctx,
EVP_MD_CTX_FLAG_NON_FIPS_ALLOW);
if (EVP_DigestInit_ex(&md_ctx,
(num == 2) ? s->ctx->md5
: s->ctx->sha1,
NULL) <= 0
|| EVP_DigestUpdate(&md_ctx, &(s->s3->client_random[0]),
SSL3_RANDOM_SIZE) <= 0
|| EVP_DigestUpdate(&md_ctx, &(s->s3->server_random[0]),
SSL3_RANDOM_SIZE) <= 0
|| EVP_DigestUpdate(&md_ctx, d, n) <= 0
|| EVP_DigestFinal_ex(&md_ctx, q,
(unsigned int *)&i) <= 0) {
SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
ERR_LIB_EVP);
al = SSL_AD_INTERNAL_ERROR;
goto f_err;
}
q += i;
j += i;
}
if (RSA_sign(NID_md5_sha1, md_buf, j,
&(p[2]), &u, pkey->pkey.rsa) <= 0) {
SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_LIB_RSA);
goto err;
}
s2n(u, p);
n += u + 2;
} else
#endif
if (md) {
/* send signature algorithm */
if (SSL_USE_SIGALGS(s)) {
if (!tls12_get_sigandhash(p, pkey, md)) {
/* Should never happen */
al = SSL_AD_INTERNAL_ERROR;
SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
ERR_R_INTERNAL_ERROR);
goto f_err;
}
p += 2;
}
#ifdef SSL_DEBUG
fprintf(stderr, "Using hash %s\n", EVP_MD_name(md));
#endif
if (EVP_SignInit_ex(&md_ctx, md, NULL) <= 0
|| EVP_SignUpdate(&md_ctx, &(s->s3->client_random[0]),
SSL3_RANDOM_SIZE) <= 0
|| EVP_SignUpdate(&md_ctx, &(s->s3->server_random[0]),
SSL3_RANDOM_SIZE) <= 0
|| EVP_SignUpdate(&md_ctx, d, n) <= 0
|| EVP_SignFinal(&md_ctx, &(p[2]),
(unsigned int *)&i, pkey) <= 0) {
SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_LIB_EVP);
al = SSL_AD_INTERNAL_ERROR;
goto f_err;
}
s2n(i, p);
n += i + 2;
if (SSL_USE_SIGALGS(s))
n += 2;
} else {
/* Is this error check actually needed? */
al = SSL_AD_HANDSHAKE_FAILURE;
SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
SSL_R_UNKNOWN_PKEY_TYPE);
goto f_err;
}
}
ssl_set_handshake_header(s, SSL3_MT_SERVER_KEY_EXCHANGE, n);
}
s->state = SSL3_ST_SW_KEY_EXCH_B;
EVP_MD_CTX_cleanup(&md_ctx);
return ssl_do_write(s);
f_err:
ssl3_send_alert(s, SSL3_AL_FATAL, al);
err:
#ifndef OPENSSL_NO_ECDH
if (encodedPoint != NULL)
OPENSSL_free(encodedPoint);
BN_CTX_free(bn_ctx);
#endif
EVP_MD_CTX_cleanup(&md_ctx);
s->state = SSL_ST_ERR;
return (-1);
}
int ssl3_send_certificate_request(SSL *s)
{
unsigned char *p, *d;
int i, j, nl, off, n;
STACK_OF(X509_NAME) *sk = NULL;
X509_NAME *name;
BUF_MEM *buf;
if (s->state == SSL3_ST_SW_CERT_REQ_A) {
buf = s->init_buf;
d = p = ssl_handshake_start(s);
/* get the list of acceptable cert types */
p++;
n = ssl3_get_req_cert_type(s, p);
d[0] = n;
p += n;
n++;
if (SSL_USE_SIGALGS(s)) {
const unsigned char *psigs;
nl = tls12_get_psigalgs(s, 1, &psigs);
s2n(nl, p);
memcpy(p, psigs, nl);
p += nl;
n += nl + 2;
}
off = n;
p += 2;
n += 2;
sk = SSL_get_client_CA_list(s);
nl = 0;
if (sk != NULL) {
for (i = 0; i < sk_X509_NAME_num(sk); i++) {
name = sk_X509_NAME_value(sk, i);
j = i2d_X509_NAME(name, NULL);
if (!BUF_MEM_grow_clean
(buf, SSL_HM_HEADER_LENGTH(s) + n + j + 2)) {
SSLerr(SSL_F_SSL3_SEND_CERTIFICATE_REQUEST,
ERR_R_BUF_LIB);
goto err;
}
p = ssl_handshake_start(s) + n;
if (!(s->options & SSL_OP_NETSCAPE_CA_DN_BUG)) {
s2n(j, p);
i2d_X509_NAME(name, &p);
n += 2 + j;
nl += 2 + j;
} else {
d = p;
i2d_X509_NAME(name, &p);
j -= 2;
s2n(j, d);
j += 2;
n += j;
nl += j;
}
}
}
/* else no CA names */
p = ssl_handshake_start(s) + off;
s2n(nl, p);
ssl_set_handshake_header(s, SSL3_MT_CERTIFICATE_REQUEST, n);
#ifdef NETSCAPE_HANG_BUG
if (!SSL_IS_DTLS(s)) {
if (!BUF_MEM_grow_clean(buf, s->init_num + 4)) {
SSLerr(SSL_F_SSL3_SEND_CERTIFICATE_REQUEST, ERR_R_BUF_LIB);
goto err;
}
p = (unsigned char *)s->init_buf->data + s->init_num;
/* do the header */
*(p++) = SSL3_MT_SERVER_DONE;
*(p++) = 0;
*(p++) = 0;
*(p++) = 0;
s->init_num += 4;
}
#endif
s->state = SSL3_ST_SW_CERT_REQ_B;
}
/* SSL3_ST_SW_CERT_REQ_B */
return ssl_do_write(s);
err:
s->state = SSL_ST_ERR;
return (-1);
}
int ssl3_get_client_key_exchange(SSL *s)
{
int i, al, ok;
long n;
unsigned long alg_k;
unsigned char *p;
#ifndef OPENSSL_NO_RSA
RSA *rsa = NULL;
EVP_PKEY *pkey = NULL;
#endif
#ifndef OPENSSL_NO_DH
BIGNUM *pub = NULL;
DH *dh_srvr, *dh_clnt = NULL;
#endif
#ifndef OPENSSL_NO_KRB5
KSSL_ERR kssl_err;
#endif /* OPENSSL_NO_KRB5 */
#ifndef OPENSSL_NO_ECDH
EC_KEY *srvr_ecdh = NULL;
EVP_PKEY *clnt_pub_pkey = NULL;
EC_POINT *clnt_ecpoint = NULL;
BN_CTX *bn_ctx = NULL;
#endif
n = s->method->ssl_get_message(s,
SSL3_ST_SR_KEY_EXCH_A,
SSL3_ST_SR_KEY_EXCH_B,
SSL3_MT_CLIENT_KEY_EXCHANGE, 2048, &ok);
if (!ok)
return ((int)n);
p = (unsigned char *)s->init_msg;
alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
#ifndef OPENSSL_NO_RSA
if (alg_k & SSL_kRSA) {
unsigned char rand_premaster_secret[SSL_MAX_MASTER_KEY_LENGTH];
int decrypt_len;
unsigned char decrypt_good, version_good;
size_t j, padding_len;
/* FIX THIS UP EAY EAY EAY EAY */
if (s->s3->tmp.use_rsa_tmp) {
if ((s->cert != NULL) && (s->cert->rsa_tmp != NULL))
rsa = s->cert->rsa_tmp;
/*
* Don't do a callback because rsa_tmp should be sent already
*/
if (rsa == NULL) {
al = SSL_AD_HANDSHAKE_FAILURE;
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
SSL_R_MISSING_TMP_RSA_PKEY);
goto f_err;
}
} else {
pkey = s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey;
if ((pkey == NULL) ||
(pkey->type != EVP_PKEY_RSA) || (pkey->pkey.rsa == NULL)) {
al = SSL_AD_HANDSHAKE_FAILURE;
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
SSL_R_MISSING_RSA_CERTIFICATE);
goto f_err;
}
rsa = pkey->pkey.rsa;
}
/* TLS and [incidentally] DTLS{0xFEFF} */
if (s->version > SSL3_VERSION && s->version != DTLS1_BAD_VER) {
n2s(p, i);
if (n != i + 2) {
if (!(s->options & SSL_OP_TLS_D5_BUG)) {
al = SSL_AD_DECODE_ERROR;
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
SSL_R_TLS_RSA_ENCRYPTED_VALUE_LENGTH_IS_WRONG);
goto f_err;
} else
p -= 2;
} else
n = i;
}
/*
* Reject overly short RSA ciphertext because we want to be sure
* that the buffer size makes it safe to iterate over the entire
* size of a premaster secret (SSL_MAX_MASTER_KEY_LENGTH). The
* actual expected size is larger due to RSA padding, but the
* bound is sufficient to be safe.
*/
if (n < SSL_MAX_MASTER_KEY_LENGTH) {
al = SSL_AD_DECRYPT_ERROR;
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
SSL_R_TLS_RSA_ENCRYPTED_VALUE_LENGTH_IS_WRONG);
goto f_err;
}
/*
* We must not leak whether a decryption failure occurs because of
* Bleichenbacher's attack on PKCS #1 v1.5 RSA padding (see RFC 2246,
* section 7.4.7.1). The code follows that advice of the TLS RFC and
* generates a random premaster secret for the case that the decrypt
* fails. See https://tools.ietf.org/html/rfc5246#section-7.4.7.1
*/
if (RAND_bytes(rand_premaster_secret,
sizeof(rand_premaster_secret)) <= 0)
goto err;
/*
* Decrypt with no padding. PKCS#1 padding will be removed as part of
* the timing-sensitive code below.
*/
decrypt_len =
RSA_private_decrypt((int)n, p, p, rsa, RSA_NO_PADDING);
if (decrypt_len < 0)
goto err;
/* Check the padding. See RFC 3447, section 7.2.2. */
/*
* The smallest padded premaster is 11 bytes of overhead. Small keys
* are publicly invalid, so this may return immediately. This ensures
* PS is at least 8 bytes.
*/
if (decrypt_len < 11 + SSL_MAX_MASTER_KEY_LENGTH) {
al = SSL_AD_DECRYPT_ERROR;
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
SSL_R_DECRYPTION_FAILED);
goto f_err;
}
padding_len = decrypt_len - SSL_MAX_MASTER_KEY_LENGTH;
decrypt_good = constant_time_eq_int_8(p[0], 0) &
constant_time_eq_int_8(p[1], 2);
for (j = 2; j < padding_len - 1; j++) {
decrypt_good &= ~constant_time_is_zero_8(p[j]);
}
decrypt_good &= constant_time_is_zero_8(p[padding_len - 1]);
p += padding_len;
/*
* If the version in the decrypted pre-master secret is correct then
* version_good will be 0xff, otherwise it'll be zero. The
* Klima-Pokorny-Rosa extension of Bleichenbacher's attack
* (http://eprint.iacr.org/2003/052/) exploits the version number
* check as a "bad version oracle". Thus version checks are done in
* constant time and are treated like any other decryption error.
*/
version_good =
constant_time_eq_8(p[0], (unsigned)(s->client_version >> 8));
version_good &=
constant_time_eq_8(p[1], (unsigned)(s->client_version & 0xff));
/*
* The premaster secret must contain the same version number as the
* ClientHello to detect version rollback attacks (strangely, the
* protocol does not offer such protection for DH ciphersuites).
* However, buggy clients exist that send the negotiated protocol
* version instead if the server does not support the requested
* protocol version. If SSL_OP_TLS_ROLLBACK_BUG is set, tolerate such
* clients.
*/
if (s->options & SSL_OP_TLS_ROLLBACK_BUG) {
unsigned char workaround_good;
workaround_good =
constant_time_eq_8(p[0], (unsigned)(s->version >> 8));
workaround_good &=
constant_time_eq_8(p[1], (unsigned)(s->version & 0xff));
version_good |= workaround_good;
}
/*
* Both decryption and version must be good for decrypt_good to
* remain non-zero (0xff).
*/
decrypt_good &= version_good;
/*
* Now copy rand_premaster_secret over from p using
* decrypt_good_mask. If decryption failed, then p does not
* contain valid plaintext, however, a check above guarantees
* it is still sufficiently large to read from.
*/
for (j = 0; j < sizeof(rand_premaster_secret); j++) {
p[j] = constant_time_select_8(decrypt_good, p[j],
rand_premaster_secret[j]);
}
s->session->master_key_length =
s->method->ssl3_enc->generate_master_secret(s,
s->
session->master_key,
p,
sizeof
(rand_premaster_secret));
OPENSSL_cleanse(p, sizeof(rand_premaster_secret));
} else
#endif
#ifndef OPENSSL_NO_DH
if (alg_k & (SSL_kEDH | SSL_kDHr | SSL_kDHd)) {
int idx = -1;
EVP_PKEY *skey = NULL;
if (n > 1) {
n2s(p, i);
} else {
if (alg_k & SSL_kDHE) {
al = SSL_AD_HANDSHAKE_FAILURE;
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
SSL_R_DH_PUBLIC_VALUE_LENGTH_IS_WRONG);
goto f_err;
}
i = 0;
}
if (n && n != i + 2) {
if (!(s->options & SSL_OP_SSLEAY_080_CLIENT_DH_BUG)) {
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
SSL_R_DH_PUBLIC_VALUE_LENGTH_IS_WRONG);
al = SSL_AD_HANDSHAKE_FAILURE;
goto f_err;
} else {
p -= 2;
i = (int)n;
}
}
if (alg_k & SSL_kDHr)
idx = SSL_PKEY_DH_RSA;
else if (alg_k & SSL_kDHd)
idx = SSL_PKEY_DH_DSA;
if (idx >= 0) {
skey = s->cert->pkeys[idx].privatekey;
if ((skey == NULL) ||
(skey->type != EVP_PKEY_DH) || (skey->pkey.dh == NULL)) {
al = SSL_AD_HANDSHAKE_FAILURE;
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
SSL_R_MISSING_RSA_CERTIFICATE);
goto f_err;
}
dh_srvr = skey->pkey.dh;
} else if (s->s3->tmp.dh == NULL) {
al = SSL_AD_HANDSHAKE_FAILURE;
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
SSL_R_MISSING_TMP_DH_KEY);
goto f_err;
} else
dh_srvr = s->s3->tmp.dh;
if (n == 0L) {
/* Get pubkey from cert */
EVP_PKEY *clkey = X509_get_pubkey(s->session->peer);
if (clkey) {
if (EVP_PKEY_cmp_parameters(clkey, skey) == 1)
dh_clnt = EVP_PKEY_get1_DH(clkey);
}
if (dh_clnt == NULL) {
al = SSL_AD_HANDSHAKE_FAILURE;
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
SSL_R_MISSING_TMP_DH_KEY);
goto f_err;
}
EVP_PKEY_free(clkey);
pub = dh_clnt->pub_key;
} else
pub = BN_bin2bn(p, i, NULL);
if (pub == NULL) {
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_R_BN_LIB);
goto err;
}
i = DH_compute_key(p, pub, dh_srvr);
if (i <= 0) {
al = SSL_AD_HANDSHAKE_FAILURE;
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_DH_LIB);
BN_clear_free(pub);
goto f_err;
}
DH_free(s->s3->tmp.dh);
s->s3->tmp.dh = NULL;
if (dh_clnt)
DH_free(dh_clnt);
else
BN_clear_free(pub);
pub = NULL;
s->session->master_key_length =
s->method->ssl3_enc->generate_master_secret(s,
s->
session->master_key,
p, i);
OPENSSL_cleanse(p, i);
if (dh_clnt)
return 2;
} else
#endif
#ifndef OPENSSL_NO_KRB5
if (alg_k & SSL_kKRB5) {
krb5_error_code krb5rc;
krb5_data enc_ticket;
krb5_data authenticator;
krb5_data enc_pms;
KSSL_CTX *kssl_ctx = s->kssl_ctx;
EVP_CIPHER_CTX ciph_ctx;
const EVP_CIPHER *enc = NULL;
unsigned char iv[EVP_MAX_IV_LENGTH];
unsigned char pms[SSL_MAX_MASTER_KEY_LENGTH + EVP_MAX_BLOCK_LENGTH];
int padl, outl;
krb5_timestamp authtime = 0;
krb5_ticket_times ttimes;
int kerr = 0;
EVP_CIPHER_CTX_init(&ciph_ctx);
if (!kssl_ctx)
kssl_ctx = kssl_ctx_new();
n2s(p, i);
enc_ticket.length = i;
if (n < (long)(enc_ticket.length + 6)) {
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
SSL_R_DATA_LENGTH_TOO_LONG);
goto err;
}
enc_ticket.data = (char *)p;
p += enc_ticket.length;
n2s(p, i);
authenticator.length = i;
if (n < (long)(enc_ticket.length + authenticator.length + 6)) {
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
SSL_R_DATA_LENGTH_TOO_LONG);
goto err;
}
authenticator.data = (char *)p;
p += authenticator.length;
n2s(p, i);
enc_pms.length = i;
enc_pms.data = (char *)p;
p += enc_pms.length;
/*
* Note that the length is checked again below, ** after decryption
*/
- if (enc_pms.length > sizeof pms) {
+ if (enc_pms.length > sizeof(pms)) {
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
SSL_R_DATA_LENGTH_TOO_LONG);
goto err;
}
if (n != (long)(enc_ticket.length + authenticator.length +
enc_pms.length + 6)) {
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
SSL_R_DATA_LENGTH_TOO_LONG);
goto err;
}
if ((krb5rc = kssl_sget_tkt(kssl_ctx, &enc_ticket, &ttimes,
&kssl_err)) != 0) {
# ifdef KSSL_DEBUG
fprintf(stderr, "kssl_sget_tkt rtn %d [%d]\n",
krb5rc, kssl_err.reason);
if (kssl_err.text)
fprintf(stderr, "kssl_err text= %s\n", kssl_err.text);
# endif /* KSSL_DEBUG */
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, kssl_err.reason);
goto err;
}
/*
* Note: no authenticator is not considered an error, ** but will
* return authtime == 0.
*/
if ((krb5rc = kssl_check_authent(kssl_ctx, &authenticator,
&authtime, &kssl_err)) != 0) {
# ifdef KSSL_DEBUG
fprintf(stderr, "kssl_check_authent rtn %d [%d]\n",
krb5rc, kssl_err.reason);
if (kssl_err.text)
fprintf(stderr, "kssl_err text= %s\n", kssl_err.text);
# endif /* KSSL_DEBUG */
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, kssl_err.reason);
goto err;
}
if ((krb5rc = kssl_validate_times(authtime, &ttimes)) != 0) {
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, krb5rc);
goto err;
}
# ifdef KSSL_DEBUG
kssl_ctx_show(kssl_ctx);
# endif /* KSSL_DEBUG */
enc = kssl_map_enc(kssl_ctx->enctype);
if (enc == NULL)
goto err;
- memset(iv, 0, sizeof iv); /* per RFC 1510 */
+ memset(iv, 0, sizeof(iv)); /* per RFC 1510 */
if (!EVP_DecryptInit_ex(&ciph_ctx, enc, NULL, kssl_ctx->key, iv)) {
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
SSL_R_DECRYPTION_FAILED);
goto err;
}
if (!EVP_DecryptUpdate(&ciph_ctx, pms, &outl,
(unsigned char *)enc_pms.data, enc_pms.length))
{
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
SSL_R_DECRYPTION_FAILED);
kerr = 1;
goto kclean;
}
if (outl > SSL_MAX_MASTER_KEY_LENGTH) {
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
SSL_R_DATA_LENGTH_TOO_LONG);
kerr = 1;
goto kclean;
}
if (!EVP_DecryptFinal_ex(&ciph_ctx, &(pms[outl]), &padl)) {
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
SSL_R_DECRYPTION_FAILED);
kerr = 1;
goto kclean;
}
outl += padl;
if (outl > SSL_MAX_MASTER_KEY_LENGTH) {
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
SSL_R_DATA_LENGTH_TOO_LONG);
kerr = 1;
goto kclean;
}
if (!((pms[0] == (s->client_version >> 8))
&& (pms[1] == (s->client_version & 0xff)))) {
/*
* The premaster secret must contain the same version number as
* the ClientHello to detect version rollback attacks (strangely,
* the protocol does not offer such protection for DH
* ciphersuites). However, buggy clients exist that send random
* bytes instead of the protocol version. If
* SSL_OP_TLS_ROLLBACK_BUG is set, tolerate such clients.
* (Perhaps we should have a separate BUG value for the Kerberos
* cipher)
*/
if (!(s->options & SSL_OP_TLS_ROLLBACK_BUG)) {
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
SSL_AD_DECODE_ERROR);
kerr = 1;
goto kclean;
}
}
EVP_CIPHER_CTX_cleanup(&ciph_ctx);
s->session->master_key_length =
s->method->ssl3_enc->generate_master_secret(s,
s->
session->master_key,
pms, outl);
if (kssl_ctx->client_princ) {
size_t len = strlen(kssl_ctx->client_princ);
if (len < SSL_MAX_KRB5_PRINCIPAL_LENGTH) {
s->session->krb5_client_princ_len = len;
memcpy(s->session->krb5_client_princ, kssl_ctx->client_princ,
len);
}
}
/*- Was doing kssl_ctx_free() here,
* but it caused problems for apache.
* kssl_ctx = kssl_ctx_free(kssl_ctx);
* if (s->kssl_ctx) s->kssl_ctx = NULL;
*/
kclean:
OPENSSL_cleanse(pms, sizeof(pms));
if (kerr)
goto err;
} else
#endif /* OPENSSL_NO_KRB5 */
#ifndef OPENSSL_NO_ECDH
if (alg_k & (SSL_kEECDH | SSL_kECDHr | SSL_kECDHe)) {
int ret = 1;
int field_size = 0;
const EC_KEY *tkey;
const EC_GROUP *group;
const BIGNUM *priv_key;
/* initialize structures for server's ECDH key pair */
if ((srvr_ecdh = EC_KEY_new()) == NULL) {
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
goto err;
}
/* Let's get server private key and group information */
if (alg_k & (SSL_kECDHr | SSL_kECDHe)) {
/* use the certificate */
tkey = s->cert->pkeys[SSL_PKEY_ECC].privatekey->pkey.ec;
} else {
/*
* use the ephermeral values we saved when generating the
* ServerKeyExchange msg.
*/
tkey = s->s3->tmp.ecdh;
}
group = EC_KEY_get0_group(tkey);
priv_key = EC_KEY_get0_private_key(tkey);
if (!EC_KEY_set_group(srvr_ecdh, group) ||
!EC_KEY_set_private_key(srvr_ecdh, priv_key)) {
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_EC_LIB);
goto err;
}
/* Let's get client's public key */
if ((clnt_ecpoint = EC_POINT_new(group)) == NULL) {
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
goto err;
}
if (n == 0L) {
/* Client Publickey was in Client Certificate */
if (alg_k & SSL_kEECDH) {
al = SSL_AD_HANDSHAKE_FAILURE;
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
SSL_R_MISSING_TMP_ECDH_KEY);
goto f_err;
}
if (((clnt_pub_pkey = X509_get_pubkey(s->session->peer))
== NULL) || (clnt_pub_pkey->type != EVP_PKEY_EC)) {
/*
* XXX: For now, we do not support client authentication
* using ECDH certificates so this branch (n == 0L) of the
* code is never executed. When that support is added, we
* ought to ensure the key received in the certificate is
* authorized for key agreement. ECDH_compute_key implicitly
* checks that the two ECDH shares are for the same group.
*/
al = SSL_AD_HANDSHAKE_FAILURE;
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
SSL_R_UNABLE_TO_DECODE_ECDH_CERTS);
goto f_err;
}
if (EC_POINT_copy(clnt_ecpoint,
EC_KEY_get0_public_key(clnt_pub_pkey->
pkey.ec)) == 0) {
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_EC_LIB);
goto err;
}
ret = 2; /* Skip certificate verify processing */
} else {
/*
* Get client's public key from encoded point in the
* ClientKeyExchange message.
*/
if ((bn_ctx = BN_CTX_new()) == NULL) {
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
ERR_R_MALLOC_FAILURE);
goto err;
}
/* Get encoded point length */
i = *p;
p += 1;
if (n != 1 + i) {
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_R_LENGTH_MISMATCH);
al = SSL_AD_DECODE_ERROR;
goto f_err;
}
if (EC_POINT_oct2point(group, clnt_ecpoint, p, i, bn_ctx) == 0) {
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_EC_LIB);
al = SSL_AD_HANDSHAKE_FAILURE;
goto f_err;
}
/*
* p is pointing to somewhere in the buffer currently, so set it
* to the start
*/
p = (unsigned char *)s->init_buf->data;
}
/* Compute the shared pre-master secret */
field_size = EC_GROUP_get_degree(group);
if (field_size <= 0) {
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_ECDH_LIB);
goto err;
}
i = ECDH_compute_key(p, (field_size + 7) / 8, clnt_ecpoint, srvr_ecdh,
NULL);
if (i <= 0) {
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_ECDH_LIB);
goto err;
}
EVP_PKEY_free(clnt_pub_pkey);
EC_POINT_free(clnt_ecpoint);
EC_KEY_free(srvr_ecdh);
BN_CTX_free(bn_ctx);
EC_KEY_free(s->s3->tmp.ecdh);
s->s3->tmp.ecdh = NULL;
/* Compute the master secret */
s->session->master_key_length =
s->method->ssl3_enc->generate_master_secret(s,
s->
session->master_key,
p, i);
OPENSSL_cleanse(p, i);
return (ret);
} else
#endif
#ifndef OPENSSL_NO_PSK
if (alg_k & SSL_kPSK) {
unsigned char *t = NULL;
unsigned char psk_or_pre_ms[PSK_MAX_PSK_LEN * 2 + 4];
unsigned int pre_ms_len = 0, psk_len = 0;
int psk_err = 1;
char tmp_id[PSK_MAX_IDENTITY_LEN + 1];
al = SSL_AD_HANDSHAKE_FAILURE;
n2s(p, i);
if (n != i + 2) {
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_R_LENGTH_MISMATCH);
goto psk_err;
}
if (i > PSK_MAX_IDENTITY_LEN) {
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
SSL_R_DATA_LENGTH_TOO_LONG);
goto psk_err;
}
if (s->psk_server_callback == NULL) {
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
SSL_R_PSK_NO_SERVER_CB);
goto psk_err;
}
/*
* Create guaranteed NULL-terminated identity string for the callback
*/
memcpy(tmp_id, p, i);
memset(tmp_id + i, 0, PSK_MAX_IDENTITY_LEN + 1 - i);
psk_len = s->psk_server_callback(s, tmp_id,
psk_or_pre_ms,
sizeof(psk_or_pre_ms));
OPENSSL_cleanse(tmp_id, PSK_MAX_IDENTITY_LEN + 1);
if (psk_len > PSK_MAX_PSK_LEN) {
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
goto psk_err;
} else if (psk_len == 0) {
/*
* PSK related to the given identity not found
*/
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
SSL_R_PSK_IDENTITY_NOT_FOUND);
al = SSL_AD_UNKNOWN_PSK_IDENTITY;
goto psk_err;
}
/* create PSK pre_master_secret */
pre_ms_len = 2 + psk_len + 2 + psk_len;
t = psk_or_pre_ms;
memmove(psk_or_pre_ms + psk_len + 4, psk_or_pre_ms, psk_len);
s2n(psk_len, t);
memset(t, 0, psk_len);
t += psk_len;
s2n(psk_len, t);
if (s->session->psk_identity != NULL)
OPENSSL_free(s->session->psk_identity);
s->session->psk_identity = BUF_strndup((char *)p, i);
if (s->session->psk_identity == NULL) {
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
goto psk_err;
}
if (s->session->psk_identity_hint != NULL)
OPENSSL_free(s->session->psk_identity_hint);
s->session->psk_identity_hint = BUF_strdup(s->ctx->psk_identity_hint);
if (s->ctx->psk_identity_hint != NULL &&
s->session->psk_identity_hint == NULL) {
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
goto psk_err;
}
s->session->master_key_length =
s->method->ssl3_enc->generate_master_secret(s,
s->
session->master_key,
psk_or_pre_ms,
pre_ms_len);
psk_err = 0;
psk_err:
OPENSSL_cleanse(psk_or_pre_ms, sizeof(psk_or_pre_ms));
if (psk_err != 0)
goto f_err;
} else
#endif
#ifndef OPENSSL_NO_SRP
if (alg_k & SSL_kSRP) {
int param_len;
n2s(p, i);
param_len = i + 2;
if (param_len > n) {
al = SSL_AD_DECODE_ERROR;
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
SSL_R_BAD_SRP_A_LENGTH);
goto f_err;
}
if (!(s->srp_ctx.A = BN_bin2bn(p, i, NULL))) {
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_BN_LIB);
goto err;
}
if (BN_ucmp(s->srp_ctx.A, s->srp_ctx.N) >= 0
|| BN_is_zero(s->srp_ctx.A)) {
al = SSL_AD_ILLEGAL_PARAMETER;
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
SSL_R_BAD_SRP_PARAMETERS);
goto f_err;
}
if (s->session->srp_username != NULL)
OPENSSL_free(s->session->srp_username);
s->session->srp_username = BUF_strdup(s->srp_ctx.login);
if (s->session->srp_username == NULL) {
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
goto err;
}
if ((s->session->master_key_length =
SRP_generate_server_master_secret(s,
s->session->master_key)) < 0) {
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
goto err;
}
p += i;
} else
#endif /* OPENSSL_NO_SRP */
if (alg_k & SSL_kGOST) {
int ret = 0;
EVP_PKEY_CTX *pkey_ctx;
EVP_PKEY *client_pub_pkey = NULL, *pk = NULL;
unsigned char premaster_secret[32], *start;
size_t outlen = 32, inlen;
unsigned long alg_a;
int Ttag, Tclass;
long Tlen;
/* Get our certificate private key */
alg_a = s->s3->tmp.new_cipher->algorithm_auth;
if (alg_a & SSL_aGOST94)
pk = s->cert->pkeys[SSL_PKEY_GOST94].privatekey;
else if (alg_a & SSL_aGOST01)
pk = s->cert->pkeys[SSL_PKEY_GOST01].privatekey;
pkey_ctx = EVP_PKEY_CTX_new(pk, NULL);
if (pkey_ctx == NULL) {
al = SSL_AD_INTERNAL_ERROR;
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
goto f_err;
}
if (EVP_PKEY_decrypt_init(pkey_ctx) <= 0) {
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
goto gerr;
}
/*
* If client certificate is present and is of the same type, maybe
* use it for key exchange. Don't mind errors from
* EVP_PKEY_derive_set_peer, because it is completely valid to use a
* client certificate for authorization only.
*/
client_pub_pkey = X509_get_pubkey(s->session->peer);
if (client_pub_pkey) {
if (EVP_PKEY_derive_set_peer(pkey_ctx, client_pub_pkey) <= 0)
ERR_clear_error();
}
/* Decrypt session key */
if (ASN1_get_object
((const unsigned char **)&p, &Tlen, &Ttag, &Tclass,
n) != V_ASN1_CONSTRUCTED || Ttag != V_ASN1_SEQUENCE
|| Tclass != V_ASN1_UNIVERSAL) {
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
SSL_R_DECRYPTION_FAILED);
goto gerr;
}
start = p;
inlen = Tlen;
if (EVP_PKEY_decrypt
(pkey_ctx, premaster_secret, &outlen, start, inlen) <= 0) {
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
SSL_R_DECRYPTION_FAILED);
goto gerr;
}
/* Generate master secret */
s->session->master_key_length =
s->method->ssl3_enc->generate_master_secret(s,
s->
session->master_key,
premaster_secret, 32);
OPENSSL_cleanse(premaster_secret, sizeof(premaster_secret));
/* Check if pubkey from client certificate was used */
if (EVP_PKEY_CTX_ctrl
(pkey_ctx, -1, -1, EVP_PKEY_CTRL_PEER_KEY, 2, NULL) > 0)
ret = 2;
else
ret = 1;
gerr:
EVP_PKEY_free(client_pub_pkey);
EVP_PKEY_CTX_free(pkey_ctx);
if (ret)
return ret;
else
goto err;
} else {
al = SSL_AD_HANDSHAKE_FAILURE;
SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_R_UNKNOWN_CIPHER_TYPE);
goto f_err;
}
return (1);
f_err:
ssl3_send_alert(s, SSL3_AL_FATAL, al);
#if !defined(OPENSSL_NO_DH) || !defined(OPENSSL_NO_RSA) || !defined(OPENSSL_NO_ECDH) || defined(OPENSSL_NO_SRP)
err:
#endif
#ifndef OPENSSL_NO_ECDH
EVP_PKEY_free(clnt_pub_pkey);
EC_POINT_free(clnt_ecpoint);
if (srvr_ecdh != NULL)
EC_KEY_free(srvr_ecdh);
BN_CTX_free(bn_ctx);
#endif
s->state = SSL_ST_ERR;
return (-1);
}
int ssl3_get_cert_verify(SSL *s)
{
EVP_PKEY *pkey = NULL;
unsigned char *p;
int al, ok, ret = 0;
long n;
int type = 0, i, j;
X509 *peer;
const EVP_MD *md = NULL;
EVP_MD_CTX mctx;
EVP_MD_CTX_init(&mctx);
/*
* We should only process a CertificateVerify message if we have received
* a Certificate from the client. If so then |s->session->peer| will be non
* NULL. In some instances a CertificateVerify message is not required even
* if the peer has sent a Certificate (e.g. such as in the case of static
* DH). In that case the ClientKeyExchange processing will skip the
* CertificateVerify state so we should not arrive here.
*/
if (s->session->peer == NULL) {
ret = 1;
goto end;
}
n = s->method->ssl_get_message(s,
SSL3_ST_SR_CERT_VRFY_A,
SSL3_ST_SR_CERT_VRFY_B,
SSL3_MT_CERTIFICATE_VERIFY,
SSL3_RT_MAX_PLAIN_LENGTH, &ok);
if (!ok)
return ((int)n);
peer = s->session->peer;
pkey = X509_get_pubkey(peer);
if (pkey == NULL) {
al = SSL_AD_INTERNAL_ERROR;
goto f_err;
}
type = X509_certificate_type(peer, pkey);
if (!(type & EVP_PKT_SIGN)) {
SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,
SSL_R_SIGNATURE_FOR_NON_SIGNING_CERTIFICATE);
al = SSL_AD_ILLEGAL_PARAMETER;
goto f_err;
}
/* we now have a signature that we need to verify */
p = (unsigned char *)s->init_msg;
/* Check for broken implementations of GOST ciphersuites */
/*
* If key is GOST and n is exactly 64, it is bare signature without
* length field
*/
if (n == 64 && (pkey->type == NID_id_GostR3410_94 ||
pkey->type == NID_id_GostR3410_2001)) {
i = 64;
} else {
if (SSL_USE_SIGALGS(s)) {
int rv = tls12_check_peer_sigalg(&md, s, p, pkey);
if (rv == -1) {
al = SSL_AD_INTERNAL_ERROR;
goto f_err;
} else if (rv == 0) {
al = SSL_AD_DECODE_ERROR;
goto f_err;
}
#ifdef SSL_DEBUG
fprintf(stderr, "USING TLSv1.2 HASH %s\n", EVP_MD_name(md));
#endif
p += 2;
n -= 2;
}
n2s(p, i);
n -= 2;
if (i > n) {
SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_LENGTH_MISMATCH);
al = SSL_AD_DECODE_ERROR;
goto f_err;
}
}
j = EVP_PKEY_size(pkey);
if ((i > j) || (n > j) || (n <= 0)) {
SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_WRONG_SIGNATURE_SIZE);
al = SSL_AD_DECODE_ERROR;
goto f_err;
}
if (SSL_USE_SIGALGS(s)) {
long hdatalen = 0;
void *hdata;
hdatalen = BIO_get_mem_data(s->s3->handshake_buffer, &hdata);
if (hdatalen <= 0) {
SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, ERR_R_INTERNAL_ERROR);
al = SSL_AD_INTERNAL_ERROR;
goto f_err;
}
#ifdef SSL_DEBUG
fprintf(stderr, "Using TLS 1.2 with client verify alg %s\n",
EVP_MD_name(md));
#endif
if (!EVP_VerifyInit_ex(&mctx, md, NULL)
|| !EVP_VerifyUpdate(&mctx, hdata, hdatalen)) {
SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, ERR_R_EVP_LIB);
al = SSL_AD_INTERNAL_ERROR;
goto f_err;
}
if (EVP_VerifyFinal(&mctx, p, i, pkey) <= 0) {
al = SSL_AD_DECRYPT_ERROR;
SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_BAD_SIGNATURE);
goto f_err;
}
} else
#ifndef OPENSSL_NO_RSA
if (pkey->type == EVP_PKEY_RSA) {
i = RSA_verify(NID_md5_sha1, s->s3->tmp.cert_verify_md,
MD5_DIGEST_LENGTH + SHA_DIGEST_LENGTH, p, i,
pkey->pkey.rsa);
if (i < 0) {
al = SSL_AD_DECRYPT_ERROR;
SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_BAD_RSA_DECRYPT);
goto f_err;
}
if (i == 0) {
al = SSL_AD_DECRYPT_ERROR;
SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_BAD_RSA_SIGNATURE);
goto f_err;
}
} else
#endif
#ifndef OPENSSL_NO_DSA
if (pkey->type == EVP_PKEY_DSA) {
j = DSA_verify(pkey->save_type,
&(s->s3->tmp.cert_verify_md[MD5_DIGEST_LENGTH]),
SHA_DIGEST_LENGTH, p, i, pkey->pkey.dsa);
if (j <= 0) {
/* bad signature */
al = SSL_AD_DECRYPT_ERROR;
SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_BAD_DSA_SIGNATURE);
goto f_err;
}
} else
#endif
#ifndef OPENSSL_NO_ECDSA
if (pkey->type == EVP_PKEY_EC) {
j = ECDSA_verify(pkey->save_type,
&(s->s3->tmp.cert_verify_md[MD5_DIGEST_LENGTH]),
SHA_DIGEST_LENGTH, p, i, pkey->pkey.ec);
if (j <= 0) {
/* bad signature */
al = SSL_AD_DECRYPT_ERROR;
SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_BAD_ECDSA_SIGNATURE);
goto f_err;
}
} else
#endif
if (pkey->type == NID_id_GostR3410_94
|| pkey->type == NID_id_GostR3410_2001) {
unsigned char signature[64];
int idx;
EVP_PKEY_CTX *pctx = EVP_PKEY_CTX_new(pkey, NULL);
if (pctx == NULL) {
al = SSL_AD_INTERNAL_ERROR;
SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, ERR_R_MALLOC_FAILURE);
goto f_err;
}
if (EVP_PKEY_verify_init(pctx) <= 0) {
EVP_PKEY_CTX_free(pctx);
al = SSL_AD_INTERNAL_ERROR;
SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, ERR_R_INTERNAL_ERROR);
goto f_err;
}
if (i != 64) {
#ifdef SSL_DEBUG
fprintf(stderr, "GOST signature length is %d", i);
#endif
}
for (idx = 0; idx < 64; idx++) {
signature[63 - idx] = p[idx];
}
j = EVP_PKEY_verify(pctx, signature, 64, s->s3->tmp.cert_verify_md,
32);
EVP_PKEY_CTX_free(pctx);
if (j <= 0) {
al = SSL_AD_DECRYPT_ERROR;
SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_BAD_ECDSA_SIGNATURE);
goto f_err;
}
} else {
SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, ERR_R_INTERNAL_ERROR);
al = SSL_AD_UNSUPPORTED_CERTIFICATE;
goto f_err;
}
ret = 1;
if (0) {
f_err:
ssl3_send_alert(s, SSL3_AL_FATAL, al);
s->state = SSL_ST_ERR;
}
end:
if (s->s3->handshake_buffer) {
BIO_free(s->s3->handshake_buffer);
s->s3->handshake_buffer = NULL;
s->s3->flags &= ~TLS1_FLAGS_KEEP_HANDSHAKE;
}
EVP_MD_CTX_cleanup(&mctx);
EVP_PKEY_free(pkey);
return (ret);
}
int ssl3_get_client_certificate(SSL *s)
{
int i, ok, al, ret = -1;
X509 *x = NULL;
unsigned long l, nc, llen, n;
const unsigned char *p, *q;
unsigned char *d;
STACK_OF(X509) *sk = NULL;
n = s->method->ssl_get_message(s,
SSL3_ST_SR_CERT_A,
SSL3_ST_SR_CERT_B,
-1, s->max_cert_list, &ok);
if (!ok)
return ((int)n);
if (s->s3->tmp.message_type == SSL3_MT_CLIENT_KEY_EXCHANGE) {
if ((s->verify_mode & SSL_VERIFY_PEER) &&
(s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) {
SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,
SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
al = SSL_AD_HANDSHAKE_FAILURE;
goto f_err;
}
/*
* If tls asked for a client cert, the client must return a 0 list
*/
if ((s->version > SSL3_VERSION) && s->s3->tmp.cert_request) {
SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,
SSL_R_TLS_PEER_DID_NOT_RESPOND_WITH_CERTIFICATE_LIST);
al = SSL_AD_UNEXPECTED_MESSAGE;
goto f_err;
}
s->s3->tmp.reuse_message = 1;
return (1);
}
if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE) {
al = SSL_AD_UNEXPECTED_MESSAGE;
SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE, SSL_R_WRONG_MESSAGE_TYPE);
goto f_err;
}
p = d = (unsigned char *)s->init_msg;
if ((sk = sk_X509_new_null()) == NULL) {
SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE, ERR_R_MALLOC_FAILURE);
goto err;
}
n2l3(p, llen);
if (llen + 3 != n) {
al = SSL_AD_DECODE_ERROR;
SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE, SSL_R_LENGTH_MISMATCH);
goto f_err;
}
for (nc = 0; nc < llen;) {
if (nc + 3 > llen) {
al = SSL_AD_DECODE_ERROR;
SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,
SSL_R_CERT_LENGTH_MISMATCH);
goto f_err;
}
n2l3(p, l);
if ((l + nc + 3) > llen) {
al = SSL_AD_DECODE_ERROR;
SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,
SSL_R_CERT_LENGTH_MISMATCH);
goto f_err;
}
q = p;
x = d2i_X509(NULL, &p, l);
if (x == NULL) {
SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE, ERR_R_ASN1_LIB);
goto err;
}
if (p != (q + l)) {
al = SSL_AD_DECODE_ERROR;
SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,
SSL_R_CERT_LENGTH_MISMATCH);
goto f_err;
}
if (!sk_X509_push(sk, x)) {
SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE, ERR_R_MALLOC_FAILURE);
goto err;
}
x = NULL;
nc += l + 3;
}
if (sk_X509_num(sk) <= 0) {
/* TLS does not mind 0 certs returned */
if (s->version == SSL3_VERSION) {
al = SSL_AD_HANDSHAKE_FAILURE;
SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,
SSL_R_NO_CERTIFICATES_RETURNED);
goto f_err;
}
/* Fail for TLS only if we required a certificate */
else if ((s->verify_mode & SSL_VERIFY_PEER) &&
(s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) {
SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,
SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
al = SSL_AD_HANDSHAKE_FAILURE;
goto f_err;
}
/* No client certificate so digest cached records */
if (s->s3->handshake_buffer && !ssl3_digest_cached_records(s)) {
al = SSL_AD_INTERNAL_ERROR;
goto f_err;
}
} else {
i = ssl_verify_cert_chain(s, sk);
if (i <= 0) {
al = ssl_verify_alarm_type(s->verify_result);
SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,
SSL_R_CERTIFICATE_VERIFY_FAILED);
goto f_err;
}
}
if (s->session->peer != NULL) /* This should not be needed */
X509_free(s->session->peer);
s->session->peer = sk_X509_shift(sk);
s->session->verify_result = s->verify_result;
/*
* With the current implementation, sess_cert will always be NULL when we
* arrive here.
*/
if (s->session->sess_cert == NULL) {
s->session->sess_cert = ssl_sess_cert_new();
if (s->session->sess_cert == NULL) {
SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE, ERR_R_MALLOC_FAILURE);
goto err;
}
}
if (s->session->sess_cert->cert_chain != NULL)
sk_X509_pop_free(s->session->sess_cert->cert_chain, X509_free);
s->session->sess_cert->cert_chain = sk;
/*
* Inconsistency alert: cert_chain does *not* include the peer's own
* certificate, while we do include it in s3_clnt.c
*/
sk = NULL;
ret = 1;
if (0) {
f_err:
ssl3_send_alert(s, SSL3_AL_FATAL, al);
err:
s->state = SSL_ST_ERR;
}
if (x != NULL)
X509_free(x);
if (sk != NULL)
sk_X509_pop_free(sk, X509_free);
return (ret);
}
int ssl3_send_server_certificate(SSL *s)
{
CERT_PKEY *cpk;
if (s->state == SSL3_ST_SW_CERT_A) {
cpk = ssl_get_server_send_pkey(s);
if (cpk == NULL) {
/* VRS: allow null cert if auth == KRB5 */
if ((s->s3->tmp.new_cipher->algorithm_auth != SSL_aKRB5) ||
(s->s3->tmp.new_cipher->algorithm_mkey & SSL_kKRB5)) {
SSLerr(SSL_F_SSL3_SEND_SERVER_CERTIFICATE,
ERR_R_INTERNAL_ERROR);
s->state = SSL_ST_ERR;
return (0);
}
}
if (!ssl3_output_cert_chain(s, cpk)) {
SSLerr(SSL_F_SSL3_SEND_SERVER_CERTIFICATE, ERR_R_INTERNAL_ERROR);
s->state = SSL_ST_ERR;
return (0);
}
s->state = SSL3_ST_SW_CERT_B;
}
/* SSL3_ST_SW_CERT_B */
return ssl_do_write(s);
}
#ifndef OPENSSL_NO_TLSEXT
/* send a new session ticket (not necessarily for a new session) */
int ssl3_send_newsession_ticket(SSL *s)
{
unsigned char *senc = NULL;
EVP_CIPHER_CTX ctx;
HMAC_CTX hctx;
if (s->state == SSL3_ST_SW_SESSION_TICKET_A) {
unsigned char *p, *macstart;
const unsigned char *const_p;
int len, slen_full, slen;
SSL_SESSION *sess;
unsigned int hlen;
SSL_CTX *tctx = s->initial_ctx;
unsigned char iv[EVP_MAX_IV_LENGTH];
unsigned char key_name[16];
/* get session encoding length */
slen_full = i2d_SSL_SESSION(s->session, NULL);
/*
* Some length values are 16 bits, so forget it if session is too
* long
*/
if (slen_full == 0 || slen_full > 0xFF00) {
s->state = SSL_ST_ERR;
return -1;
}
senc = OPENSSL_malloc(slen_full);
if (!senc) {
s->state = SSL_ST_ERR;
return -1;
}
EVP_CIPHER_CTX_init(&ctx);
HMAC_CTX_init(&hctx);
p = senc;
if (!i2d_SSL_SESSION(s->session, &p))
goto err;
/*
* create a fresh copy (not shared with other threads) to clean up
*/
const_p = senc;
sess = d2i_SSL_SESSION(NULL, &const_p, slen_full);
if (sess == NULL)
goto err;
sess->session_id_length = 0; /* ID is irrelevant for the ticket */
slen = i2d_SSL_SESSION(sess, NULL);
if (slen == 0 || slen > slen_full) { /* shouldn't ever happen */
SSL_SESSION_free(sess);
goto err;
}
p = senc;
if (!i2d_SSL_SESSION(sess, &p)) {
SSL_SESSION_free(sess);
goto err;
}
SSL_SESSION_free(sess);
/*-
* Grow buffer if need be: the length calculation is as
* follows handshake_header_length +
* 4 (ticket lifetime hint) + 2 (ticket length) +
* 16 (key name) + max_iv_len (iv length) +
* session_length + max_enc_block_size (max encrypted session
* length) + max_md_size (HMAC).
*/
if (!BUF_MEM_grow(s->init_buf,
SSL_HM_HEADER_LENGTH(s) + 22 + EVP_MAX_IV_LENGTH +
EVP_MAX_BLOCK_LENGTH + EVP_MAX_MD_SIZE + slen))
goto err;
p = ssl_handshake_start(s);
/*
* Initialize HMAC and cipher contexts. If callback present it does
* all the work otherwise use generated values from parent ctx.
*/
if (tctx->tlsext_ticket_key_cb) {
/* if 0 is returned, write en empty ticket */
int ret = tctx->tlsext_ticket_key_cb(s, key_name, iv, &ctx,
&hctx, 1);
if (ret == 0) {
l2n(0, p); /* timeout */
s2n(0, p); /* length */
ssl_set_handshake_header(s, SSL3_MT_NEWSESSION_TICKET,
p - ssl_handshake_start(s));
s->state = SSL3_ST_SW_SESSION_TICKET_B;
OPENSSL_free(senc);
EVP_CIPHER_CTX_cleanup(&ctx);
HMAC_CTX_cleanup(&hctx);
return ssl_do_write(s);
}
if (ret < 0)
goto err;
} else {
if (RAND_bytes(iv, 16) <= 0)
goto err;
if (!EVP_EncryptInit_ex(&ctx, EVP_aes_128_cbc(), NULL,
tctx->tlsext_tick_aes_key, iv))
goto err;
if (!HMAC_Init_ex(&hctx, tctx->tlsext_tick_hmac_key, 16,
tlsext_tick_md(), NULL))
goto err;
memcpy(key_name, tctx->tlsext_tick_key_name, 16);
}
/*
* Ticket lifetime hint (advisory only): We leave this unspecified
* for resumed session (for simplicity), and guess that tickets for
* new sessions will live as long as their sessions.
*/
l2n(s->hit ? 0 : s->session->timeout, p);
/* Skip ticket length for now */
p += 2;
/* Output key name */
macstart = p;
memcpy(p, key_name, 16);
p += 16;
/* output IV */
memcpy(p, iv, EVP_CIPHER_CTX_iv_length(&ctx));
p += EVP_CIPHER_CTX_iv_length(&ctx);
/* Encrypt session data */
if (!EVP_EncryptUpdate(&ctx, p, &len, senc, slen))
goto err;
p += len;
if (!EVP_EncryptFinal(&ctx, p, &len))
goto err;
p += len;
if (!HMAC_Update(&hctx, macstart, p - macstart))
goto err;
if (!HMAC_Final(&hctx, p, &hlen))
goto err;
EVP_CIPHER_CTX_cleanup(&ctx);
HMAC_CTX_cleanup(&hctx);
p += hlen;
/* Now write out lengths: p points to end of data written */
/* Total length */
len = p - ssl_handshake_start(s);
/* Skip ticket lifetime hint */
p = ssl_handshake_start(s) + 4;
s2n(len - 6, p);
ssl_set_handshake_header(s, SSL3_MT_NEWSESSION_TICKET, len);
s->state = SSL3_ST_SW_SESSION_TICKET_B;
OPENSSL_free(senc);
}
/* SSL3_ST_SW_SESSION_TICKET_B */
return ssl_do_write(s);
err:
if (senc)
OPENSSL_free(senc);
EVP_CIPHER_CTX_cleanup(&ctx);
HMAC_CTX_cleanup(&hctx);
s->state = SSL_ST_ERR;
return -1;
}
int ssl3_send_cert_status(SSL *s)
{
if (s->state == SSL3_ST_SW_CERT_STATUS_A) {
unsigned char *p;
size_t msglen;
/*-
* Grow buffer if need be: the length calculation is as
* follows handshake_header_length +
* 1 (ocsp response type) + 3 (ocsp response length)
* + (ocsp response)
*/
msglen = 4 + s->tlsext_ocsp_resplen;
if (!BUF_MEM_grow(s->init_buf, SSL_HM_HEADER_LENGTH(s) + msglen)) {
s->state = SSL_ST_ERR;
return -1;
}
p = ssl_handshake_start(s);
/* status type */
*(p++) = s->tlsext_status_type;
/* length of OCSP response */
l2n3(s->tlsext_ocsp_resplen, p);
/* actual response */
memcpy(p, s->tlsext_ocsp_resp, s->tlsext_ocsp_resplen);
ssl_set_handshake_header(s, SSL3_MT_CERTIFICATE_STATUS, msglen);
}
/* SSL3_ST_SW_CERT_STATUS_B */
return (ssl_do_write(s));
}
# ifndef OPENSSL_NO_NEXTPROTONEG
/*
* ssl3_get_next_proto reads a Next Protocol Negotiation handshake message.
* It sets the next_proto member in s if found
*/
int ssl3_get_next_proto(SSL *s)
{
int ok;
int proto_len, padding_len;
long n;
const unsigned char *p;
/*
* Clients cannot send a NextProtocol message if we didn't see the
* extension in their ClientHello
*/
if (!s->s3->next_proto_neg_seen) {
SSLerr(SSL_F_SSL3_GET_NEXT_PROTO,
SSL_R_GOT_NEXT_PROTO_WITHOUT_EXTENSION);
s->state = SSL_ST_ERR;
return -1;
}
/* See the payload format below */
n = s->method->ssl_get_message(s,
SSL3_ST_SR_NEXT_PROTO_A,
SSL3_ST_SR_NEXT_PROTO_B,
SSL3_MT_NEXT_PROTO, 514, &ok);
if (!ok)
return ((int)n);
/*
* s->state doesn't reflect whether ChangeCipherSpec has been received in
* this handshake, but s->s3->change_cipher_spec does (will be reset by
* ssl3_get_finished).
*/
if (!s->s3->change_cipher_spec) {
SSLerr(SSL_F_SSL3_GET_NEXT_PROTO, SSL_R_GOT_NEXT_PROTO_BEFORE_A_CCS);
s->state = SSL_ST_ERR;
return -1;
}
if (n < 2) {
s->state = SSL_ST_ERR;
return 0; /* The body must be > 1 bytes long */
}
p = (unsigned char *)s->init_msg;
/*-
* The payload looks like:
* uint8 proto_len;
* uint8 proto[proto_len];
* uint8 padding_len;
* uint8 padding[padding_len];
*/
proto_len = p[0];
if (proto_len + 2 > s->init_num) {
s->state = SSL_ST_ERR;
return 0;
}
padding_len = p[proto_len + 1];
if (proto_len + padding_len + 2 != s->init_num) {
s->state = SSL_ST_ERR;
return 0;
}
s->next_proto_negotiated = OPENSSL_malloc(proto_len);
if (!s->next_proto_negotiated) {
SSLerr(SSL_F_SSL3_GET_NEXT_PROTO, ERR_R_MALLOC_FAILURE);
s->state = SSL_ST_ERR;
return 0;
}
memcpy(s->next_proto_negotiated, p + 1, proto_len);
s->next_proto_negotiated_len = proto_len;
return 1;
}
# endif
#endif
diff --git a/ssl/ssl_cert.c b/ssl/ssl_cert.c
index 155728d03772..363d2b2d6044 100644
--- a/ssl/ssl_cert.c
+++ b/ssl/ssl_cert.c
@@ -1,1263 +1,1263 @@
/*
* ! \file ssl/ssl_cert.c
*/
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
/* ====================================================================
* Copyright (c) 1998-2007 The OpenSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* openssl-core@openssl.org.
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.openssl.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*
* This product includes cryptographic software written by Eric Young
* (eay@cryptsoft.com). This product includes software written by Tim
* Hudson (tjh@cryptsoft.com).
*
*/
/* ====================================================================
* Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
* ECC cipher suite support in OpenSSL originally developed by
* SUN MICROSYSTEMS, INC., and contributed to the OpenSSL project.
*/
#include <stdio.h>
#include "e_os.h"
#ifndef NO_SYS_TYPES_H
# include <sys/types.h>
#endif
#include "o_dir.h"
#include <openssl/objects.h>
#include <openssl/bio.h>
#include <openssl/pem.h>
#include <openssl/x509v3.h>
#ifndef OPENSSL_NO_DH
# include <openssl/dh.h>
#endif
#include <openssl/bn.h>
#include "ssl_locl.h"
int SSL_get_ex_data_X509_STORE_CTX_idx(void)
{
static volatile int ssl_x509_store_ctx_idx = -1;
int got_write_lock = 0;
if (((size_t)&ssl_x509_store_ctx_idx &
(sizeof(ssl_x509_store_ctx_idx) - 1))
== 0) { /* check alignment, practically always true */
int ret;
if ((ret = ssl_x509_store_ctx_idx) < 0) {
CRYPTO_w_lock(CRYPTO_LOCK_SSL_CTX);
if ((ret = ssl_x509_store_ctx_idx) < 0) {
ret = ssl_x509_store_ctx_idx =
X509_STORE_CTX_get_ex_new_index(0,
"SSL for verify callback",
NULL, NULL, NULL);
}
CRYPTO_w_unlock(CRYPTO_LOCK_SSL_CTX);
}
return ret;
} else { /* commonly eliminated */
CRYPTO_r_lock(CRYPTO_LOCK_SSL_CTX);
if (ssl_x509_store_ctx_idx < 0) {
CRYPTO_r_unlock(CRYPTO_LOCK_SSL_CTX);
CRYPTO_w_lock(CRYPTO_LOCK_SSL_CTX);
got_write_lock = 1;
if (ssl_x509_store_ctx_idx < 0) {
ssl_x509_store_ctx_idx =
X509_STORE_CTX_get_ex_new_index(0,
"SSL for verify callback",
NULL, NULL, NULL);
}
}
if (got_write_lock)
CRYPTO_w_unlock(CRYPTO_LOCK_SSL_CTX);
else
CRYPTO_r_unlock(CRYPTO_LOCK_SSL_CTX);
return ssl_x509_store_ctx_idx;
}
}
void ssl_cert_set_default_md(CERT *cert)
{
/* Set digest values to defaults */
#ifndef OPENSSL_NO_DSA
cert->pkeys[SSL_PKEY_DSA_SIGN].digest = EVP_sha1();
#endif
#ifndef OPENSSL_NO_RSA
cert->pkeys[SSL_PKEY_RSA_SIGN].digest = EVP_sha1();
cert->pkeys[SSL_PKEY_RSA_ENC].digest = EVP_sha1();
#endif
#ifndef OPENSSL_NO_ECDSA
cert->pkeys[SSL_PKEY_ECC].digest = EVP_sha1();
#endif
}
CERT *ssl_cert_new(void)
{
CERT *ret;
ret = (CERT *)OPENSSL_malloc(sizeof(CERT));
if (ret == NULL) {
SSLerr(SSL_F_SSL_CERT_NEW, ERR_R_MALLOC_FAILURE);
return (NULL);
}
memset(ret, 0, sizeof(CERT));
ret->key = &(ret->pkeys[SSL_PKEY_RSA_ENC]);
ret->references = 1;
ssl_cert_set_default_md(ret);
return (ret);
}
CERT *ssl_cert_dup(CERT *cert)
{
CERT *ret;
int i;
ret = (CERT *)OPENSSL_malloc(sizeof(CERT));
if (ret == NULL) {
SSLerr(SSL_F_SSL_CERT_DUP, ERR_R_MALLOC_FAILURE);
return (NULL);
}
memset(ret, 0, sizeof(CERT));
ret->references = 1;
ret->key = &ret->pkeys[cert->key - &cert->pkeys[0]];
/*
* or ret->key = ret->pkeys + (cert->key - cert->pkeys), if you find that
* more readable
*/
ret->valid = cert->valid;
ret->mask_k = cert->mask_k;
ret->mask_a = cert->mask_a;
ret->export_mask_k = cert->export_mask_k;
ret->export_mask_a = cert->export_mask_a;
#ifndef OPENSSL_NO_RSA
if (cert->rsa_tmp != NULL) {
RSA_up_ref(cert->rsa_tmp);
ret->rsa_tmp = cert->rsa_tmp;
}
ret->rsa_tmp_cb = cert->rsa_tmp_cb;
#endif
#ifndef OPENSSL_NO_DH
if (cert->dh_tmp != NULL) {
ret->dh_tmp = DHparams_dup(cert->dh_tmp);
if (ret->dh_tmp == NULL) {
SSLerr(SSL_F_SSL_CERT_DUP, ERR_R_DH_LIB);
goto err;
}
if (cert->dh_tmp->priv_key) {
BIGNUM *b = BN_dup(cert->dh_tmp->priv_key);
if (!b) {
SSLerr(SSL_F_SSL_CERT_DUP, ERR_R_BN_LIB);
goto err;
}
ret->dh_tmp->priv_key = b;
}
if (cert->dh_tmp->pub_key) {
BIGNUM *b = BN_dup(cert->dh_tmp->pub_key);
if (!b) {
SSLerr(SSL_F_SSL_CERT_DUP, ERR_R_BN_LIB);
goto err;
}
ret->dh_tmp->pub_key = b;
}
}
ret->dh_tmp_cb = cert->dh_tmp_cb;
#endif
#ifndef OPENSSL_NO_ECDH
if (cert->ecdh_tmp) {
ret->ecdh_tmp = EC_KEY_dup(cert->ecdh_tmp);
if (ret->ecdh_tmp == NULL) {
SSLerr(SSL_F_SSL_CERT_DUP, ERR_R_EC_LIB);
goto err;
}
}
ret->ecdh_tmp_cb = cert->ecdh_tmp_cb;
ret->ecdh_tmp_auto = cert->ecdh_tmp_auto;
#endif
for (i = 0; i < SSL_PKEY_NUM; i++) {
CERT_PKEY *cpk = cert->pkeys + i;
CERT_PKEY *rpk = ret->pkeys + i;
if (cpk->x509 != NULL) {
rpk->x509 = cpk->x509;
CRYPTO_add(&rpk->x509->references, 1, CRYPTO_LOCK_X509);
}
if (cpk->privatekey != NULL) {
rpk->privatekey = cpk->privatekey;
CRYPTO_add(&cpk->privatekey->references, 1, CRYPTO_LOCK_EVP_PKEY);
}
if (cpk->chain) {
rpk->chain = X509_chain_up_ref(cpk->chain);
if (!rpk->chain) {
SSLerr(SSL_F_SSL_CERT_DUP, ERR_R_MALLOC_FAILURE);
goto err;
}
}
rpk->valid_flags = 0;
#ifndef OPENSSL_NO_TLSEXT
if (cert->pkeys[i].serverinfo != NULL) {
/* Just copy everything. */
ret->pkeys[i].serverinfo =
OPENSSL_malloc(cert->pkeys[i].serverinfo_length);
if (ret->pkeys[i].serverinfo == NULL) {
SSLerr(SSL_F_SSL_CERT_DUP, ERR_R_MALLOC_FAILURE);
goto err;
}
ret->pkeys[i].serverinfo_length =
cert->pkeys[i].serverinfo_length;
memcpy(ret->pkeys[i].serverinfo,
cert->pkeys[i].serverinfo,
cert->pkeys[i].serverinfo_length);
}
#endif
}
/*
* Set digests to defaults. NB: we don't copy existing values as they
* will be set during handshake.
*/
ssl_cert_set_default_md(ret);
/* Peer sigalgs set to NULL as we get these from handshake too */
ret->peer_sigalgs = NULL;
ret->peer_sigalgslen = 0;
/* Configured sigalgs however we copy across */
if (cert->conf_sigalgs) {
ret->conf_sigalgs = OPENSSL_malloc(cert->conf_sigalgslen);
if (!ret->conf_sigalgs)
goto err;
memcpy(ret->conf_sigalgs, cert->conf_sigalgs, cert->conf_sigalgslen);
ret->conf_sigalgslen = cert->conf_sigalgslen;
} else
ret->conf_sigalgs = NULL;
if (cert->client_sigalgs) {
ret->client_sigalgs = OPENSSL_malloc(cert->client_sigalgslen);
if (!ret->client_sigalgs)
goto err;
memcpy(ret->client_sigalgs, cert->client_sigalgs,
cert->client_sigalgslen);
ret->client_sigalgslen = cert->client_sigalgslen;
} else
ret->client_sigalgs = NULL;
/* Shared sigalgs also NULL */
ret->shared_sigalgs = NULL;
/* Copy any custom client certificate types */
if (cert->ctypes) {
ret->ctypes = OPENSSL_malloc(cert->ctype_num);
if (!ret->ctypes)
goto err;
memcpy(ret->ctypes, cert->ctypes, cert->ctype_num);
ret->ctype_num = cert->ctype_num;
}
ret->cert_flags = cert->cert_flags;
ret->cert_cb = cert->cert_cb;
ret->cert_cb_arg = cert->cert_cb_arg;
if (cert->verify_store) {
CRYPTO_add(&cert->verify_store->references, 1,
CRYPTO_LOCK_X509_STORE);
ret->verify_store = cert->verify_store;
}
if (cert->chain_store) {
CRYPTO_add(&cert->chain_store->references, 1, CRYPTO_LOCK_X509_STORE);
ret->chain_store = cert->chain_store;
}
ret->ciphers_raw = NULL;
#ifndef OPENSSL_NO_TLSEXT
if (!custom_exts_copy(&ret->cli_ext, &cert->cli_ext))
goto err;
if (!custom_exts_copy(&ret->srv_ext, &cert->srv_ext))
goto err;
#endif
return (ret);
err:
#ifndef OPENSSL_NO_RSA
if (ret->rsa_tmp != NULL)
RSA_free(ret->rsa_tmp);
#endif
#ifndef OPENSSL_NO_DH
if (ret->dh_tmp != NULL)
DH_free(ret->dh_tmp);
#endif
#ifndef OPENSSL_NO_ECDH
if (ret->ecdh_tmp != NULL)
EC_KEY_free(ret->ecdh_tmp);
#endif
#ifndef OPENSSL_NO_TLSEXT
custom_exts_free(&ret->cli_ext);
custom_exts_free(&ret->srv_ext);
#endif
ssl_cert_clear_certs(ret);
OPENSSL_free(ret);
return NULL;
}
/* Free up and clear all certificates and chains */
void ssl_cert_clear_certs(CERT *c)
{
int i;
if (c == NULL)
return;
for (i = 0; i < SSL_PKEY_NUM; i++) {
CERT_PKEY *cpk = c->pkeys + i;
if (cpk->x509) {
X509_free(cpk->x509);
cpk->x509 = NULL;
}
if (cpk->privatekey) {
EVP_PKEY_free(cpk->privatekey);
cpk->privatekey = NULL;
}
if (cpk->chain) {
sk_X509_pop_free(cpk->chain, X509_free);
cpk->chain = NULL;
}
#ifndef OPENSSL_NO_TLSEXT
if (cpk->serverinfo) {
OPENSSL_free(cpk->serverinfo);
cpk->serverinfo = NULL;
cpk->serverinfo_length = 0;
}
#endif
/* Clear all flags apart from explicit sign */
cpk->valid_flags &= CERT_PKEY_EXPLICIT_SIGN;
}
}
void ssl_cert_free(CERT *c)
{
int i;
if (c == NULL)
return;
i = CRYPTO_add(&c->references, -1, CRYPTO_LOCK_SSL_CERT);
#ifdef REF_PRINT
REF_PRINT("CERT", c);
#endif
if (i > 0)
return;
#ifdef REF_CHECK
if (i < 0) {
fprintf(stderr, "ssl_cert_free, bad reference count\n");
abort(); /* ok */
}
#endif
#ifndef OPENSSL_NO_RSA
if (c->rsa_tmp)
RSA_free(c->rsa_tmp);
#endif
#ifndef OPENSSL_NO_DH
if (c->dh_tmp)
DH_free(c->dh_tmp);
#endif
#ifndef OPENSSL_NO_ECDH
if (c->ecdh_tmp)
EC_KEY_free(c->ecdh_tmp);
#endif
ssl_cert_clear_certs(c);
if (c->peer_sigalgs)
OPENSSL_free(c->peer_sigalgs);
if (c->conf_sigalgs)
OPENSSL_free(c->conf_sigalgs);
if (c->client_sigalgs)
OPENSSL_free(c->client_sigalgs);
if (c->shared_sigalgs)
OPENSSL_free(c->shared_sigalgs);
if (c->ctypes)
OPENSSL_free(c->ctypes);
if (c->verify_store)
X509_STORE_free(c->verify_store);
if (c->chain_store)
X509_STORE_free(c->chain_store);
if (c->ciphers_raw)
OPENSSL_free(c->ciphers_raw);
#ifndef OPENSSL_NO_TLSEXT
custom_exts_free(&c->cli_ext);
custom_exts_free(&c->srv_ext);
if (c->alpn_proposed)
OPENSSL_free(c->alpn_proposed);
#endif
OPENSSL_free(c);
}
int ssl_cert_inst(CERT **o)
{
/*
* Create a CERT if there isn't already one (which cannot really happen,
* as it is initially created in SSL_CTX_new; but the earlier code
* usually allows for that one being non-existant, so we follow that
* behaviour, as it might turn out that there actually is a reason for it
* -- but I'm not sure that *all* of the existing code could cope with
* s->cert being NULL, otherwise we could do without the initialization
* in SSL_CTX_new).
*/
if (o == NULL) {
SSLerr(SSL_F_SSL_CERT_INST, ERR_R_PASSED_NULL_PARAMETER);
return (0);
}
if (*o == NULL) {
if ((*o = ssl_cert_new()) == NULL) {
SSLerr(SSL_F_SSL_CERT_INST, ERR_R_MALLOC_FAILURE);
return (0);
}
}
return (1);
}
int ssl_cert_set0_chain(CERT *c, STACK_OF(X509) *chain)
{
CERT_PKEY *cpk = c->key;
if (!cpk)
return 0;
if (cpk->chain)
sk_X509_pop_free(cpk->chain, X509_free);
cpk->chain = chain;
return 1;
}
int ssl_cert_set1_chain(CERT *c, STACK_OF(X509) *chain)
{
STACK_OF(X509) *dchain;
if (!chain)
return ssl_cert_set0_chain(c, NULL);
dchain = X509_chain_up_ref(chain);
if (!dchain)
return 0;
if (!ssl_cert_set0_chain(c, dchain)) {
sk_X509_pop_free(dchain, X509_free);
return 0;
}
return 1;
}
int ssl_cert_add0_chain_cert(CERT *c, X509 *x)
{
CERT_PKEY *cpk = c->key;
if (!cpk)
return 0;
if (!cpk->chain)
cpk->chain = sk_X509_new_null();
if (!cpk->chain || !sk_X509_push(cpk->chain, x))
return 0;
return 1;
}
int ssl_cert_add1_chain_cert(CERT *c, X509 *x)
{
if (!ssl_cert_add0_chain_cert(c, x))
return 0;
CRYPTO_add(&x->references, 1, CRYPTO_LOCK_X509);
return 1;
}
int ssl_cert_select_current(CERT *c, X509 *x)
{
int i;
if (x == NULL)
return 0;
for (i = 0; i < SSL_PKEY_NUM; i++) {
CERT_PKEY *cpk = c->pkeys + i;
if (cpk->x509 == x && cpk->privatekey) {
c->key = cpk;
return 1;
}
}
for (i = 0; i < SSL_PKEY_NUM; i++) {
CERT_PKEY *cpk = c->pkeys + i;
if (cpk->privatekey && cpk->x509 && !X509_cmp(cpk->x509, x)) {
c->key = cpk;
return 1;
}
}
return 0;
}
int ssl_cert_set_current(CERT *c, long op)
{
int i, idx;
if (!c)
return 0;
if (op == SSL_CERT_SET_FIRST)
idx = 0;
else if (op == SSL_CERT_SET_NEXT) {
idx = (int)(c->key - c->pkeys + 1);
if (idx >= SSL_PKEY_NUM)
return 0;
} else
return 0;
for (i = idx; i < SSL_PKEY_NUM; i++) {
CERT_PKEY *cpk = c->pkeys + i;
if (cpk->x509 && cpk->privatekey) {
c->key = cpk;
return 1;
}
}
return 0;
}
void ssl_cert_set_cert_cb(CERT *c, int (*cb) (SSL *ssl, void *arg), void *arg)
{
c->cert_cb = cb;
c->cert_cb_arg = arg;
}
SESS_CERT *ssl_sess_cert_new(void)
{
SESS_CERT *ret;
- ret = OPENSSL_malloc(sizeof *ret);
+ ret = OPENSSL_malloc(sizeof(*ret));
if (ret == NULL) {
SSLerr(SSL_F_SSL_SESS_CERT_NEW, ERR_R_MALLOC_FAILURE);
return NULL;
}
- memset(ret, 0, sizeof *ret);
+ memset(ret, 0, sizeof(*ret));
ret->peer_key = &(ret->peer_pkeys[SSL_PKEY_RSA_ENC]);
ret->references = 1;
return ret;
}
void ssl_sess_cert_free(SESS_CERT *sc)
{
int i;
if (sc == NULL)
return;
i = CRYPTO_add(&sc->references, -1, CRYPTO_LOCK_SSL_SESS_CERT);
#ifdef REF_PRINT
REF_PRINT("SESS_CERT", sc);
#endif
if (i > 0)
return;
#ifdef REF_CHECK
if (i < 0) {
fprintf(stderr, "ssl_sess_cert_free, bad reference count\n");
abort(); /* ok */
}
#endif
/* i == 0 */
if (sc->cert_chain != NULL)
sk_X509_pop_free(sc->cert_chain, X509_free);
for (i = 0; i < SSL_PKEY_NUM; i++) {
if (sc->peer_pkeys[i].x509 != NULL)
X509_free(sc->peer_pkeys[i].x509);
#if 0 /* We don't have the peer's private key.
* These lines are just * here as a reminder
* that we're still using a
* not-quite-appropriate * data structure. */
if (sc->peer_pkeys[i].privatekey != NULL)
EVP_PKEY_free(sc->peer_pkeys[i].privatekey);
#endif
}
#ifndef OPENSSL_NO_RSA
if (sc->peer_rsa_tmp != NULL)
RSA_free(sc->peer_rsa_tmp);
#endif
#ifndef OPENSSL_NO_DH
if (sc->peer_dh_tmp != NULL)
DH_free(sc->peer_dh_tmp);
#endif
#ifndef OPENSSL_NO_ECDH
if (sc->peer_ecdh_tmp != NULL)
EC_KEY_free(sc->peer_ecdh_tmp);
#endif
OPENSSL_free(sc);
}
int ssl_set_peer_cert_type(SESS_CERT *sc, int type)
{
sc->peer_cert_type = type;
return (1);
}
int ssl_verify_cert_chain(SSL *s, STACK_OF(X509) *sk)
{
X509 *x;
int i;
X509_STORE *verify_store;
X509_STORE_CTX ctx;
if (s->cert->verify_store)
verify_store = s->cert->verify_store;
else
verify_store = s->ctx->cert_store;
if ((sk == NULL) || (sk_X509_num(sk) == 0))
return (0);
x = sk_X509_value(sk, 0);
if (!X509_STORE_CTX_init(&ctx, verify_store, x, sk)) {
SSLerr(SSL_F_SSL_VERIFY_CERT_CHAIN, ERR_R_X509_LIB);
return (0);
}
/* Set suite B flags if needed */
X509_STORE_CTX_set_flags(&ctx, tls1_suiteb(s));
#if 0
if (SSL_get_verify_depth(s) >= 0)
X509_STORE_CTX_set_depth(&ctx, SSL_get_verify_depth(s));
#endif
X509_STORE_CTX_set_ex_data(&ctx, SSL_get_ex_data_X509_STORE_CTX_idx(), s);
/*
* We need to inherit the verify parameters. These can be determined by
* the context: if its a server it will verify SSL client certificates or
* vice versa.
*/
X509_STORE_CTX_set_default(&ctx, s->server ? "ssl_client" : "ssl_server");
/*
* Anything non-default in "param" should overwrite anything in the ctx.
*/
X509_VERIFY_PARAM_set1(X509_STORE_CTX_get0_param(&ctx), s->param);
if (s->verify_callback)
X509_STORE_CTX_set_verify_cb(&ctx, s->verify_callback);
if (s->ctx->app_verify_callback != NULL)
#if 1 /* new with OpenSSL 0.9.7 */
i = s->ctx->app_verify_callback(&ctx, s->ctx->app_verify_arg);
#else
i = s->ctx->app_verify_callback(&ctx); /* should pass app_verify_arg */
#endif
else {
#ifndef OPENSSL_NO_X509_VERIFY
i = X509_verify_cert(&ctx);
#else
i = 0;
ctx.error = X509_V_ERR_APPLICATION_VERIFICATION;
SSLerr(SSL_F_SSL_VERIFY_CERT_CHAIN, SSL_R_NO_VERIFY_CALLBACK);
#endif
}
s->verify_result = ctx.error;
X509_STORE_CTX_cleanup(&ctx);
return (i);
}
static void set_client_CA_list(STACK_OF(X509_NAME) **ca_list,
STACK_OF(X509_NAME) *name_list)
{
if (*ca_list != NULL)
sk_X509_NAME_pop_free(*ca_list, X509_NAME_free);
*ca_list = name_list;
}
STACK_OF(X509_NAME) *SSL_dup_CA_list(STACK_OF(X509_NAME) *sk)
{
int i;
STACK_OF(X509_NAME) *ret;
X509_NAME *name;
ret = sk_X509_NAME_new_null();
for (i = 0; i < sk_X509_NAME_num(sk); i++) {
name = X509_NAME_dup(sk_X509_NAME_value(sk, i));
if ((name == NULL) || !sk_X509_NAME_push(ret, name)) {
sk_X509_NAME_pop_free(ret, X509_NAME_free);
return (NULL);
}
}
return (ret);
}
void SSL_set_client_CA_list(SSL *s, STACK_OF(X509_NAME) *name_list)
{
set_client_CA_list(&(s->client_CA), name_list);
}
void SSL_CTX_set_client_CA_list(SSL_CTX *ctx, STACK_OF(X509_NAME) *name_list)
{
set_client_CA_list(&(ctx->client_CA), name_list);
}
STACK_OF(X509_NAME) *SSL_CTX_get_client_CA_list(const SSL_CTX *ctx)
{
return (ctx->client_CA);
}
STACK_OF(X509_NAME) *SSL_get_client_CA_list(const SSL *s)
{
if (s->type == SSL_ST_CONNECT) { /* we are in the client */
if (((s->version >> 8) == SSL3_VERSION_MAJOR) && (s->s3 != NULL))
return (s->s3->tmp.ca_names);
else
return (NULL);
} else {
if (s->client_CA != NULL)
return (s->client_CA);
else
return (s->ctx->client_CA);
}
}
static int add_client_CA(STACK_OF(X509_NAME) **sk, X509 *x)
{
X509_NAME *name;
if (x == NULL)
return (0);
if ((*sk == NULL) && ((*sk = sk_X509_NAME_new_null()) == NULL))
return (0);
if ((name = X509_NAME_dup(X509_get_subject_name(x))) == NULL)
return (0);
if (!sk_X509_NAME_push(*sk, name)) {
X509_NAME_free(name);
return (0);
}
return (1);
}
int SSL_add_client_CA(SSL *ssl, X509 *x)
{
return (add_client_CA(&(ssl->client_CA), x));
}
int SSL_CTX_add_client_CA(SSL_CTX *ctx, X509 *x)
{
return (add_client_CA(&(ctx->client_CA), x));
}
static int xname_cmp(const X509_NAME *const *a, const X509_NAME *const *b)
{
return (X509_NAME_cmp(*a, *b));
}
#ifndef OPENSSL_NO_STDIO
/**
* Load CA certs from a file into a ::STACK. Note that it is somewhat misnamed;
* it doesn't really have anything to do with clients (except that a common use
* for a stack of CAs is to send it to the client). Actually, it doesn't have
* much to do with CAs, either, since it will load any old cert.
* \param file the file containing one or more certs.
* \return a ::STACK containing the certs.
*/
STACK_OF(X509_NAME) *SSL_load_client_CA_file(const char *file)
{
BIO *in;
X509 *x = NULL;
X509_NAME *xn = NULL;
STACK_OF(X509_NAME) *ret = NULL, *sk;
sk = sk_X509_NAME_new(xname_cmp);
in = BIO_new(BIO_s_file_internal());
if ((sk == NULL) || (in == NULL)) {
SSLerr(SSL_F_SSL_LOAD_CLIENT_CA_FILE, ERR_R_MALLOC_FAILURE);
goto err;
}
if (!BIO_read_filename(in, file))
goto err;
for (;;) {
if (PEM_read_bio_X509(in, &x, NULL, NULL) == NULL)
break;
if (ret == NULL) {
ret = sk_X509_NAME_new_null();
if (ret == NULL) {
SSLerr(SSL_F_SSL_LOAD_CLIENT_CA_FILE, ERR_R_MALLOC_FAILURE);
goto err;
}
}
if ((xn = X509_get_subject_name(x)) == NULL)
goto err;
/* check for duplicates */
xn = X509_NAME_dup(xn);
if (xn == NULL)
goto err;
if (sk_X509_NAME_find(sk, xn) >= 0)
X509_NAME_free(xn);
else {
sk_X509_NAME_push(sk, xn);
sk_X509_NAME_push(ret, xn);
}
}
if (0) {
err:
if (ret != NULL)
sk_X509_NAME_pop_free(ret, X509_NAME_free);
ret = NULL;
}
if (sk != NULL)
sk_X509_NAME_free(sk);
if (in != NULL)
BIO_free(in);
if (x != NULL)
X509_free(x);
if (ret != NULL)
ERR_clear_error();
return (ret);
}
#endif
/**
* Add a file of certs to a stack.
* \param stack the stack to add to.
* \param file the file to add from. All certs in this file that are not
* already in the stack will be added.
* \return 1 for success, 0 for failure. Note that in the case of failure some
* certs may have been added to \c stack.
*/
int SSL_add_file_cert_subjects_to_stack(STACK_OF(X509_NAME) *stack,
const char *file)
{
BIO *in;
X509 *x = NULL;
X509_NAME *xn = NULL;
int ret = 1;
int (*oldcmp) (const X509_NAME *const *a, const X509_NAME *const *b);
oldcmp = sk_X509_NAME_set_cmp_func(stack, xname_cmp);
in = BIO_new(BIO_s_file_internal());
if (in == NULL) {
SSLerr(SSL_F_SSL_ADD_FILE_CERT_SUBJECTS_TO_STACK,
ERR_R_MALLOC_FAILURE);
goto err;
}
if (!BIO_read_filename(in, file))
goto err;
for (;;) {
if (PEM_read_bio_X509(in, &x, NULL, NULL) == NULL)
break;
if ((xn = X509_get_subject_name(x)) == NULL)
goto err;
xn = X509_NAME_dup(xn);
if (xn == NULL)
goto err;
if (sk_X509_NAME_find(stack, xn) >= 0)
X509_NAME_free(xn);
else
sk_X509_NAME_push(stack, xn);
}
ERR_clear_error();
if (0) {
err:
ret = 0;
}
if (in != NULL)
BIO_free(in);
if (x != NULL)
X509_free(x);
(void)sk_X509_NAME_set_cmp_func(stack, oldcmp);
return ret;
}
/**
* Add a directory of certs to a stack.
* \param stack the stack to append to.
* \param dir the directory to append from. All files in this directory will be
* examined as potential certs. Any that are acceptable to
* SSL_add_dir_cert_subjects_to_stack() that are not already in the stack will be
* included.
* \return 1 for success, 0 for failure. Note that in the case of failure some
* certs may have been added to \c stack.
*/
int SSL_add_dir_cert_subjects_to_stack(STACK_OF(X509_NAME) *stack,
const char *dir)
{
OPENSSL_DIR_CTX *d = NULL;
const char *filename;
int ret = 0;
CRYPTO_w_lock(CRYPTO_LOCK_READDIR);
/* Note that a side effect is that the CAs will be sorted by name */
while ((filename = OPENSSL_DIR_read(&d, dir))) {
char buf[1024];
int r;
- if (strlen(dir) + strlen(filename) + 2 > sizeof buf) {
+ if (strlen(dir) + strlen(filename) + 2 > sizeof(buf)) {
SSLerr(SSL_F_SSL_ADD_DIR_CERT_SUBJECTS_TO_STACK,
SSL_R_PATH_TOO_LONG);
goto err;
}
#ifdef OPENSSL_SYS_VMS
- r = BIO_snprintf(buf, sizeof buf, "%s%s", dir, filename);
+ r = BIO_snprintf(buf, sizeof(buf), "%s%s", dir, filename);
#else
- r = BIO_snprintf(buf, sizeof buf, "%s/%s", dir, filename);
+ r = BIO_snprintf(buf, sizeof(buf), "%s/%s", dir, filename);
#endif
if (r <= 0 || r >= (int)sizeof(buf))
goto err;
if (!SSL_add_file_cert_subjects_to_stack(stack, buf))
goto err;
}
if (errno) {
SYSerr(SYS_F_OPENDIR, get_last_sys_error());
ERR_add_error_data(3, "OPENSSL_DIR_read(&ctx, '", dir, "')");
SSLerr(SSL_F_SSL_ADD_DIR_CERT_SUBJECTS_TO_STACK, ERR_R_SYS_LIB);
goto err;
}
ret = 1;
err:
if (d)
OPENSSL_DIR_end(&d);
CRYPTO_w_unlock(CRYPTO_LOCK_READDIR);
return ret;
}
/* Add a certificate to a BUF_MEM structure */
static int ssl_add_cert_to_buf(BUF_MEM *buf, unsigned long *l, X509 *x)
{
int n;
unsigned char *p;
n = i2d_X509(x, NULL);
if (n < 0 || !BUF_MEM_grow_clean(buf, (int)(n + (*l) + 3))) {
SSLerr(SSL_F_SSL_ADD_CERT_TO_BUF, ERR_R_BUF_LIB);
return 0;
}
p = (unsigned char *)&(buf->data[*l]);
l2n3(n, p);
n = i2d_X509(x, &p);
if (n < 0) {
/* Shouldn't happen */
SSLerr(SSL_F_SSL_ADD_CERT_TO_BUF, ERR_R_BUF_LIB);
return 0;
}
*l += n + 3;
return 1;
}
/* Add certificate chain to internal SSL BUF_MEM strcuture */
int ssl_add_cert_chain(SSL *s, CERT_PKEY *cpk, unsigned long *l)
{
BUF_MEM *buf = s->init_buf;
int no_chain;
int i;
X509 *x;
STACK_OF(X509) *extra_certs;
X509_STORE *chain_store;
if (cpk)
x = cpk->x509;
else
x = NULL;
if (s->cert->chain_store)
chain_store = s->cert->chain_store;
else
chain_store = s->ctx->cert_store;
/*
* If we have a certificate specific chain use it, else use parent ctx.
*/
if (cpk && cpk->chain)
extra_certs = cpk->chain;
else
extra_certs = s->ctx->extra_certs;
if ((s->mode & SSL_MODE_NO_AUTO_CHAIN) || extra_certs)
no_chain = 1;
else
no_chain = 0;
/* TLSv1 sends a chain with nothing in it, instead of an alert */
if (!BUF_MEM_grow_clean(buf, 10)) {
SSLerr(SSL_F_SSL_ADD_CERT_CHAIN, ERR_R_BUF_LIB);
return 0;
}
if (x != NULL) {
if (no_chain) {
if (!ssl_add_cert_to_buf(buf, l, x))
return 0;
} else {
X509_STORE_CTX xs_ctx;
if (!X509_STORE_CTX_init(&xs_ctx, chain_store, x, NULL)) {
SSLerr(SSL_F_SSL_ADD_CERT_CHAIN, ERR_R_X509_LIB);
return (0);
}
X509_verify_cert(&xs_ctx);
/* Don't leave errors in the queue */
ERR_clear_error();
for (i = 0; i < sk_X509_num(xs_ctx.chain); i++) {
x = sk_X509_value(xs_ctx.chain, i);
if (!ssl_add_cert_to_buf(buf, l, x)) {
X509_STORE_CTX_cleanup(&xs_ctx);
return 0;
}
}
X509_STORE_CTX_cleanup(&xs_ctx);
}
}
for (i = 0; i < sk_X509_num(extra_certs); i++) {
x = sk_X509_value(extra_certs, i);
if (!ssl_add_cert_to_buf(buf, l, x))
return 0;
}
return 1;
}
/* Build a certificate chain for current certificate */
int ssl_build_cert_chain(CERT *c, X509_STORE *chain_store, int flags)
{
CERT_PKEY *cpk = c->key;
X509_STORE_CTX xs_ctx;
STACK_OF(X509) *chain = NULL, *untrusted = NULL;
X509 *x;
int i, rv = 0;
unsigned long error;
if (!cpk->x509) {
SSLerr(SSL_F_SSL_BUILD_CERT_CHAIN, SSL_R_NO_CERTIFICATE_SET);
goto err;
}
/* Rearranging and check the chain: add everything to a store */
if (flags & SSL_BUILD_CHAIN_FLAG_CHECK) {
chain_store = X509_STORE_new();
if (!chain_store)
goto err;
for (i = 0; i < sk_X509_num(cpk->chain); i++) {
x = sk_X509_value(cpk->chain, i);
if (!X509_STORE_add_cert(chain_store, x)) {
error = ERR_peek_last_error();
if (ERR_GET_LIB(error) != ERR_LIB_X509 ||
ERR_GET_REASON(error) !=
X509_R_CERT_ALREADY_IN_HASH_TABLE)
goto err;
ERR_clear_error();
}
}
/* Add EE cert too: it might be self signed */
if (!X509_STORE_add_cert(chain_store, cpk->x509)) {
error = ERR_peek_last_error();
if (ERR_GET_LIB(error) != ERR_LIB_X509 ||
ERR_GET_REASON(error) != X509_R_CERT_ALREADY_IN_HASH_TABLE)
goto err;
ERR_clear_error();
}
} else {
if (c->chain_store)
chain_store = c->chain_store;
if (flags & SSL_BUILD_CHAIN_FLAG_UNTRUSTED)
untrusted = cpk->chain;
}
if (!X509_STORE_CTX_init(&xs_ctx, chain_store, cpk->x509, untrusted)) {
SSLerr(SSL_F_SSL_BUILD_CERT_CHAIN, ERR_R_X509_LIB);
goto err;
}
/* Set suite B flags if needed */
X509_STORE_CTX_set_flags(&xs_ctx,
c->cert_flags & SSL_CERT_FLAG_SUITEB_128_LOS);
i = X509_verify_cert(&xs_ctx);
if (i <= 0 && flags & SSL_BUILD_CHAIN_FLAG_IGNORE_ERROR) {
if (flags & SSL_BUILD_CHAIN_FLAG_CLEAR_ERROR)
ERR_clear_error();
i = 1;
rv = 2;
}
if (i > 0)
chain = X509_STORE_CTX_get1_chain(&xs_ctx);
if (i <= 0) {
SSLerr(SSL_F_SSL_BUILD_CERT_CHAIN, SSL_R_CERTIFICATE_VERIFY_FAILED);
i = X509_STORE_CTX_get_error(&xs_ctx);
ERR_add_error_data(2, "Verify error:",
X509_verify_cert_error_string(i));
X509_STORE_CTX_cleanup(&xs_ctx);
goto err;
}
X509_STORE_CTX_cleanup(&xs_ctx);
if (cpk->chain)
sk_X509_pop_free(cpk->chain, X509_free);
/* Remove EE certificate from chain */
x = sk_X509_shift(chain);
X509_free(x);
if (flags & SSL_BUILD_CHAIN_FLAG_NO_ROOT) {
if (sk_X509_num(chain) > 0) {
/* See if last cert is self signed */
x = sk_X509_value(chain, sk_X509_num(chain) - 1);
X509_check_purpose(x, -1, 0);
if (x->ex_flags & EXFLAG_SS) {
x = sk_X509_pop(chain);
X509_free(x);
}
}
}
cpk->chain = chain;
if (rv == 0)
rv = 1;
err:
if (flags & SSL_BUILD_CHAIN_FLAG_CHECK)
X509_STORE_free(chain_store);
return rv;
}
int ssl_cert_set_cert_store(CERT *c, X509_STORE *store, int chain, int ref)
{
X509_STORE **pstore;
if (chain)
pstore = &c->chain_store;
else
pstore = &c->verify_store;
if (*pstore)
X509_STORE_free(*pstore);
*pstore = store;
if (ref && store)
CRYPTO_add(&store->references, 1, CRYPTO_LOCK_X509_STORE);
return 1;
}
diff --git a/ssl/ssl_lib.c b/ssl/ssl_lib.c
index 3539f4b8d20a..3a6c1b14d4a5 100644
--- a/ssl/ssl_lib.c
+++ b/ssl/ssl_lib.c
@@ -1,3584 +1,3584 @@
/*
* ! \file ssl/ssl_lib.c \brief Version independent SSL functions.
*/
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
/* ====================================================================
* Copyright (c) 1998-2007 The OpenSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* openssl-core@openssl.org.
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.openssl.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*
* This product includes cryptographic software written by Eric Young
* (eay@cryptsoft.com). This product includes software written by Tim
* Hudson (tjh@cryptsoft.com).
*
*/
/* ====================================================================
* Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
* ECC cipher suite support in OpenSSL originally developed by
* SUN MICROSYSTEMS, INC., and contributed to the OpenSSL project.
*/
/* ====================================================================
* Copyright 2005 Nokia. All rights reserved.
*
* The portions of the attached software ("Contribution") is developed by
* Nokia Corporation and is licensed pursuant to the OpenSSL open source
* license.
*
* The Contribution, originally written by Mika Kousa and Pasi Eronen of
* Nokia Corporation, consists of the "PSK" (Pre-Shared Key) ciphersuites
* support (see RFC 4279) to OpenSSL.
*
* No patent licenses or other rights except those expressly stated in
* the OpenSSL open source license shall be deemed granted or received
* expressly, by implication, estoppel, or otherwise.
*
* No assurances are provided by Nokia that the Contribution does not
* infringe the patent or other intellectual property rights of any third
* party or that the license provides you with all the necessary rights
* to make use of the Contribution.
*
* THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. IN
* ADDITION TO THE DISCLAIMERS INCLUDED IN THE LICENSE, NOKIA
* SPECIFICALLY DISCLAIMS ANY LIABILITY FOR CLAIMS BROUGHT BY YOU OR ANY
* OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS OR
* OTHERWISE.
*/
#ifdef REF_CHECK
# include <assert.h>
#endif
#include <stdio.h>
#include "ssl_locl.h"
#include "kssl_lcl.h"
#include <openssl/objects.h>
#include <openssl/lhash.h>
#include <openssl/x509v3.h>
#include <openssl/rand.h>
#include <openssl/ocsp.h>
#ifndef OPENSSL_NO_DH
# include <openssl/dh.h>
#endif
#ifndef OPENSSL_NO_ENGINE
# include <openssl/engine.h>
#endif
const char *SSL_version_str = OPENSSL_VERSION_TEXT;
SSL3_ENC_METHOD ssl3_undef_enc_method = {
/*
* evil casts, but these functions are only called if there's a library
* bug
*/
(int (*)(SSL *, int))ssl_undefined_function,
(int (*)(SSL *, unsigned char *, int))ssl_undefined_function,
ssl_undefined_function,
(int (*)(SSL *, unsigned char *, unsigned char *, int))
ssl_undefined_function,
(int (*)(SSL *, int))ssl_undefined_function,
(int (*)(SSL *, const char *, int, unsigned char *))
ssl_undefined_function,
0, /* finish_mac_length */
(int (*)(SSL *, int, unsigned char *))ssl_undefined_function,
NULL, /* client_finished_label */
0, /* client_finished_label_len */
NULL, /* server_finished_label */
0, /* server_finished_label_len */
(int (*)(int))ssl_undefined_function,
(int (*)(SSL *, unsigned char *, size_t, const char *,
size_t, const unsigned char *, size_t,
int use_context))ssl_undefined_function,
};
int SSL_clear(SSL *s)
{
if (s->method == NULL) {
SSLerr(SSL_F_SSL_CLEAR, SSL_R_NO_METHOD_SPECIFIED);
return (0);
}
if (ssl_clear_bad_session(s)) {
SSL_SESSION_free(s->session);
s->session = NULL;
}
s->error = 0;
s->hit = 0;
s->shutdown = 0;
#if 0
/*
* Disabled since version 1.10 of this file (early return not
* needed because SSL_clear is not called when doing renegotiation)
*/
/*
* This is set if we are doing dynamic renegotiation so keep
* the old cipher. It is sort of a SSL_clear_lite :-)
*/
if (s->renegotiate)
return (1);
#else
if (s->renegotiate) {
SSLerr(SSL_F_SSL_CLEAR, ERR_R_INTERNAL_ERROR);
return 0;
}
#endif
s->type = 0;
s->state = SSL_ST_BEFORE | ((s->server) ? SSL_ST_ACCEPT : SSL_ST_CONNECT);
s->version = s->method->version;
s->client_version = s->version;
s->rwstate = SSL_NOTHING;
s->rstate = SSL_ST_READ_HEADER;
#if 0
s->read_ahead = s->ctx->read_ahead;
#endif
if (s->init_buf != NULL) {
BUF_MEM_free(s->init_buf);
s->init_buf = NULL;
}
ssl_clear_cipher_ctx(s);
ssl_clear_hash_ctx(&s->read_hash);
ssl_clear_hash_ctx(&s->write_hash);
s->first_packet = 0;
#ifndef OPENSSL_NO_TLSEXT
if (s->cert != NULL) {
if (s->cert->alpn_proposed) {
OPENSSL_free(s->cert->alpn_proposed);
s->cert->alpn_proposed = NULL;
}
s->cert->alpn_proposed_len = 0;
s->cert->alpn_sent = 0;
}
#endif
#if 1
/*
* Check to see if we were changed into a different method, if so, revert
* back if we are not doing session-id reuse.
*/
if (!s->in_handshake && (s->session == NULL)
&& (s->method != s->ctx->method)) {
s->method->ssl_free(s);
s->method = s->ctx->method;
if (!s->method->ssl_new(s))
return (0);
} else
#endif
s->method->ssl_clear(s);
return (1);
}
/** 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;
sk = ssl_create_cipher_list(ctx->method, &(ctx->cipher_list),
&(ctx->cipher_list_by_id),
meth->version ==
SSL2_VERSION ? "SSLv2" :
SSL_DEFAULT_CIPHER_LIST, ctx->cert);
if ((sk == NULL) || (sk_SSL_CIPHER_num(sk) <= 0)) {
SSLerr(SSL_F_SSL_CTX_SET_SSL_VERSION,
SSL_R_SSL_LIBRARY_HAS_NO_CIPHERS);
return (0);
}
return (1);
}
SSL *SSL_new(SSL_CTX *ctx)
{
SSL *s;
if (ctx == NULL) {
SSLerr(SSL_F_SSL_NEW, SSL_R_NULL_SSL_CTX);
return (NULL);
}
if (ctx->method == NULL) {
SSLerr(SSL_F_SSL_NEW, SSL_R_SSL_CTX_HAS_NO_DEFAULT_SSL_VERSION);
return (NULL);
}
s = (SSL *)OPENSSL_malloc(sizeof(SSL));
if (s == NULL)
goto err;
memset(s, 0, sizeof(SSL));
#ifndef OPENSSL_NO_KRB5
s->kssl_ctx = kssl_ctx_new();
#endif /* OPENSSL_NO_KRB5 */
s->options = ctx->options;
s->mode = ctx->mode;
s->max_cert_list = ctx->max_cert_list;
s->references = 1;
if (ctx->cert != NULL) {
/*
* 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;
} else
s->cert = NULL; /* Cannot really happen (see SSL_CTX_new) */
s->read_ahead = ctx->read_ahead;
s->msg_callback = ctx->msg_callback;
s->msg_callback_arg = ctx->msg_callback_arg;
s->verify_mode = ctx->verify_mode;
#if 0
s->verify_depth = ctx->verify_depth;
#endif
s->sid_ctx_length = ctx->sid_ctx_length;
- OPENSSL_assert(s->sid_ctx_length <= sizeof s->sid_ctx);
+ OPENSSL_assert(s->sid_ctx_length <= sizeof(s->sid_ctx));
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)
goto err;
X509_VERIFY_PARAM_inherit(s->param, ctx->param);
#if 0
s->purpose = ctx->purpose;
s->trust = ctx->trust;
#endif
s->quiet_shutdown = ctx->quiet_shutdown;
s->max_send_fragment = ctx->max_send_fragment;
CRYPTO_add(&ctx->references, 1, CRYPTO_LOCK_SSL_CTX);
s->ctx = ctx;
#ifndef OPENSSL_NO_TLSEXT
s->tlsext_debug_cb = 0;
s->tlsext_debug_arg = NULL;
s->tlsext_ticket_expected = 0;
s->tlsext_status_type = -1;
s->tlsext_status_expected = 0;
s->tlsext_ocsp_ids = NULL;
s->tlsext_ocsp_exts = NULL;
s->tlsext_ocsp_resp = NULL;
s->tlsext_ocsp_resplen = -1;
CRYPTO_add(&ctx->references, 1, CRYPTO_LOCK_SSL_CTX);
s->initial_ctx = ctx;
# ifndef OPENSSL_NO_EC
if (ctx->tlsext_ecpointformatlist) {
s->tlsext_ecpointformatlist =
BUF_memdup(ctx->tlsext_ecpointformatlist,
ctx->tlsext_ecpointformatlist_length);
if (!s->tlsext_ecpointformatlist)
goto err;
s->tlsext_ecpointformatlist_length =
ctx->tlsext_ecpointformatlist_length;
}
if (ctx->tlsext_ellipticcurvelist) {
s->tlsext_ellipticcurvelist =
BUF_memdup(ctx->tlsext_ellipticcurvelist,
ctx->tlsext_ellipticcurvelist_length);
if (!s->tlsext_ellipticcurvelist)
goto err;
s->tlsext_ellipticcurvelist_length =
ctx->tlsext_ellipticcurvelist_length;
}
# endif
# ifndef OPENSSL_NO_NEXTPROTONEG
s->next_proto_negotiated = NULL;
# endif
if (s->ctx->alpn_client_proto_list) {
s->alpn_client_proto_list =
OPENSSL_malloc(s->ctx->alpn_client_proto_list_len);
if (s->alpn_client_proto_list == NULL)
goto err;
memcpy(s->alpn_client_proto_list, s->ctx->alpn_client_proto_list,
s->ctx->alpn_client_proto_list_len);
s->alpn_client_proto_list_len = s->ctx->alpn_client_proto_list_len;
}
#endif
s->verify_result = X509_V_OK;
s->method = ctx->method;
if (!s->method->ssl_new(s))
goto err;
s->server = (ctx->method->ssl_accept == ssl_undefined_function) ? 0 : 1;
SSL_clear(s);
CRYPTO_new_ex_data(CRYPTO_EX_INDEX_SSL, s, &s->ex_data);
#ifndef OPENSSL_NO_PSK
s->psk_client_callback = ctx->psk_client_callback;
s->psk_server_callback = ctx->psk_server_callback;
#endif
return (s);
err:
if (s != NULL)
SSL_free(s);
SSLerr(SSL_F_SSL_NEW, ERR_R_MALLOC_FAILURE);
return (NULL);
}
int SSL_CTX_set_session_id_context(SSL_CTX *ctx, const unsigned char *sid_ctx,
unsigned int sid_ctx_len)
{
- if (sid_ctx_len > sizeof ctx->sid_ctx) {
+ if (sid_ctx_len > sizeof(ctx->sid_ctx)) {
SSLerr(SSL_F_SSL_CTX_SET_SESSION_ID_CONTEXT,
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) {
SSLerr(SSL_F_SSL_SET_SESSION_ID_CONTEXT,
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)
{
CRYPTO_w_lock(CRYPTO_LOCK_SSL_CTX);
ctx->generate_session_id = cb;
CRYPTO_w_unlock(CRYPTO_LOCK_SSL_CTX);
return 1;
}
int SSL_set_generate_session_id(SSL *ssl, GEN_SESSION_CB cb)
{
CRYPTO_w_lock(CRYPTO_LOCK_SSL);
ssl->generate_session_id = cb;
CRYPTO_w_unlock(CRYPTO_LOCK_SSL);
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 - ie. 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)
+ 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);
/*
* NB: SSLv2 always uses a fixed 16-byte session ID, so even if a
* callback is calling us to check the uniqueness of a shorter ID, it
* must be compared as a padded-out ID because that is what it will be
* converted to when the callback has finished choosing it.
*/
if ((r.ssl_version == SSL2_VERSION) &&
(id_len < SSL2_SSL_SESSION_ID_LENGTH)) {
memset(r.session_id + id_len, 0, SSL2_SSL_SESSION_ID_LENGTH - id_len);
r.session_id_length = SSL2_SSL_SESSION_ID_LENGTH;
}
CRYPTO_r_lock(CRYPTO_LOCK_SSL_CTX);
p = lh_SSL_SESSION_retrieve(ssl->ctx->sessions, &r);
CRYPTO_r_unlock(CRYPTO_LOCK_SSL_CTX);
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_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;
i = CRYPTO_add(&s->references, -1, CRYPTO_LOCK_SSL);
#ifdef REF_PRINT
REF_PRINT("SSL", s);
#endif
if (i > 0)
return;
#ifdef REF_CHECK
if (i < 0) {
fprintf(stderr, "SSL_free, bad reference count\n");
abort(); /* ok */
}
#endif
if (s->param)
X509_VERIFY_PARAM_free(s->param);
CRYPTO_free_ex_data(CRYPTO_EX_INDEX_SSL, s, &s->ex_data);
if (s->bbio != NULL) {
/* If the buffering BIO is in place, pop it off */
if (s->bbio == s->wbio) {
s->wbio = BIO_pop(s->wbio);
}
BIO_free(s->bbio);
s->bbio = NULL;
}
if (s->rbio != NULL)
BIO_free_all(s->rbio);
if ((s->wbio != NULL) && (s->wbio != s->rbio))
BIO_free_all(s->wbio);
if (s->init_buf != NULL)
BUF_MEM_free(s->init_buf);
/* add extra stuff */
if (s->cipher_list != NULL)
sk_SSL_CIPHER_free(s->cipher_list);
if (s->cipher_list_by_id != NULL)
sk_SSL_CIPHER_free(s->cipher_list_by_id);
/* Make the next call work :-) */
if (s->session != NULL) {
ssl_clear_bad_session(s);
SSL_SESSION_free(s->session);
}
ssl_clear_cipher_ctx(s);
ssl_clear_hash_ctx(&s->read_hash);
ssl_clear_hash_ctx(&s->write_hash);
if (s->cert != NULL)
ssl_cert_free(s->cert);
/* Free up if allocated */
#ifndef OPENSSL_NO_TLSEXT
if (s->tlsext_hostname)
OPENSSL_free(s->tlsext_hostname);
if (s->initial_ctx)
SSL_CTX_free(s->initial_ctx);
# ifndef OPENSSL_NO_EC
if (s->tlsext_ecpointformatlist)
OPENSSL_free(s->tlsext_ecpointformatlist);
if (s->tlsext_ellipticcurvelist)
OPENSSL_free(s->tlsext_ellipticcurvelist);
# endif /* OPENSSL_NO_EC */
if (s->tlsext_opaque_prf_input)
OPENSSL_free(s->tlsext_opaque_prf_input);
if (s->tlsext_ocsp_exts)
sk_X509_EXTENSION_pop_free(s->tlsext_ocsp_exts, X509_EXTENSION_free);
if (s->tlsext_ocsp_ids)
sk_OCSP_RESPID_pop_free(s->tlsext_ocsp_ids, OCSP_RESPID_free);
if (s->tlsext_ocsp_resp)
OPENSSL_free(s->tlsext_ocsp_resp);
if (s->alpn_client_proto_list)
OPENSSL_free(s->alpn_client_proto_list);
#endif
if (s->client_CA != NULL)
sk_X509_NAME_pop_free(s->client_CA, X509_NAME_free);
if (s->method != NULL)
s->method->ssl_free(s);
if (s->ctx)
SSL_CTX_free(s->ctx);
#ifndef OPENSSL_NO_KRB5
if (s->kssl_ctx != NULL)
kssl_ctx_free(s->kssl_ctx);
#endif /* OPENSSL_NO_KRB5 */
#if !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_NEXTPROTONEG)
if (s->next_proto_negotiated)
OPENSSL_free(s->next_proto_negotiated);
#endif
#ifndef OPENSSL_NO_SRTP
if (s->srtp_profiles)
sk_SRTP_PROTECTION_PROFILE_free(s->srtp_profiles);
#endif
OPENSSL_free(s);
}
void SSL_set_bio(SSL *s, BIO *rbio, BIO *wbio)
{
/*
* If the output buffering BIO is still in place, remove it
*/
if (s->bbio != NULL) {
if (s->wbio == s->bbio) {
s->wbio = s->wbio->next_bio;
s->bbio->next_bio = NULL;
}
}
if ((s->rbio != NULL) && (s->rbio != rbio))
BIO_free_all(s->rbio);
if ((s->wbio != NULL) && (s->wbio != wbio) && (s->rbio != s->wbio))
BIO_free_all(s->wbio);
s->rbio = rbio;
s->wbio = wbio;
}
BIO *SSL_get_rbio(const SSL *s)
{
return (s->rbio);
}
BIO *SSL_get_wbio(const SSL *s)
{
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) {
SSLerr(SSL_F_SSL_SET_FD, ERR_R_BUF_LIB);
goto err;
}
BIO_set_fd(bio, fd, BIO_NOCLOSE);
SSL_set_bio(s, bio, bio);
ret = 1;
err:
return (ret);
}
int SSL_set_wfd(SSL *s, int fd)
{
int ret = 0;
BIO *bio = NULL;
if ((s->rbio == NULL) || (BIO_method_type(s->rbio) != BIO_TYPE_SOCKET)
|| ((int)BIO_get_fd(s->rbio, NULL) != fd)) {
bio = BIO_new(BIO_s_socket());
if (bio == NULL) {
SSLerr(SSL_F_SSL_SET_WFD, ERR_R_BUF_LIB);
goto err;
}
BIO_set_fd(bio, fd, BIO_NOCLOSE);
SSL_set_bio(s, SSL_get_rbio(s), bio);
} else
SSL_set_bio(s, SSL_get_rbio(s), SSL_get_rbio(s));
ret = 1;
err:
return (ret);
}
int SSL_set_rfd(SSL *s, int fd)
{
int ret = 0;
BIO *bio = NULL;
if ((s->wbio == NULL) || (BIO_method_type(s->wbio) != BIO_TYPE_SOCKET)
|| ((int)BIO_get_fd(s->wbio, NULL) != fd)) {
bio = BIO_new(BIO_s_socket());
if (bio == NULL) {
SSLerr(SSL_F_SSL_SET_RFD, ERR_R_BUF_LIB);
goto err;
}
BIO_set_fd(bio, fd, BIO_NOCLOSE);
SSL_set_bio(s, bio, SSL_get_wbio(s));
} else
SSL_set_bio(s, SSL_get_wbio(s), SSL_get_wbio(s));
ret = 1;
err:
return (ret);
}
#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;
if (s->s3 != NULL) {
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;
if (s->s3 != NULL) {
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)
{
s->read_ahead = yes;
}
int SSL_get_read_ahead(const SSL *s)
{
return (s->read_ahead);
}
int SSL_pending(const SSL *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.)
*/
return (s->method->ssl_pending(s));
}
X509 *SSL_get_peer_certificate(const SSL *s)
{
X509 *r;
if ((s == NULL) || (s->session == NULL))
r = NULL;
else
r = s->session->peer;
if (r == NULL)
return (r);
CRYPTO_add(&r->references, 1, CRYPTO_LOCK_X509);
return (r);
}
STACK_OF(X509) *SSL_get_peer_cert_chain(const SSL *s)
{
STACK_OF(X509) *r;
if ((s == NULL) || (s->session == NULL)
|| (s->session->sess_cert == NULL))
r = NULL;
else
r = s->session->sess_cert->cert_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
*/
void SSL_copy_session_id(SSL *t, const SSL *f)
{
CERT *tmp;
/* Do we need to to SSL locking? */
SSL_set_session(t, SSL_get_session(f));
/*
* what if we are setup as SSLv2 but want to talk SSLv3 or vice-versa
*/
if (t->method != f->method) {
t->method->ssl_free(t); /* cleanup current */
t->method = f->method; /* change method */
t->method->ssl_new(t); /* setup new */
}
tmp = t->cert;
if (f->cert != NULL) {
CRYPTO_add(&f->cert->references, 1, CRYPTO_LOCK_SSL_CERT);
t->cert = f->cert;
} else
t->cert = NULL;
if (tmp != NULL)
ssl_cert_free(tmp);
SSL_set_session_id_context(t, f->sid_ctx, f->sid_ctx_length);
}
/* 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 == NULL) || (ctx->cert->key->x509 == NULL)) {
SSLerr(SSL_F_SSL_CTX_CHECK_PRIVATE_KEY,
SSL_R_NO_CERTIFICATE_ASSIGNED);
return (0);
}
if (ctx->cert->key->privatekey == NULL) {
SSLerr(SSL_F_SSL_CTX_CHECK_PRIVATE_KEY,
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) {
SSLerr(SSL_F_SSL_CHECK_PRIVATE_KEY, ERR_R_PASSED_NULL_PARAMETER);
return (0);
}
if (ssl->cert == NULL) {
SSLerr(SSL_F_SSL_CHECK_PRIVATE_KEY, SSL_R_NO_CERTIFICATE_ASSIGNED);
return 0;
}
if (ssl->cert->key->x509 == NULL) {
SSLerr(SSL_F_SSL_CHECK_PRIVATE_KEY, SSL_R_NO_CERTIFICATE_ASSIGNED);
return (0);
}
if (ssl->cert->key->privatekey == NULL) {
SSLerr(SSL_F_SSL_CHECK_PRIVATE_KEY, SSL_R_NO_PRIVATE_KEY_ASSIGNED);
return (0);
}
return (X509_check_private_key(ssl->cert->key->x509,
ssl->cert->key->privatekey));
}
int SSL_accept(SSL *s)
{
if (s->handshake_func == 0)
/* Not properly initialized yet */
SSL_set_accept_state(s);
return (s->method->ssl_accept(s));
}
int SSL_connect(SSL *s)
{
if (s->handshake_func == 0)
/* Not properly initialized yet */
SSL_set_connect_state(s);
return (s->method->ssl_connect(s));
}
long SSL_get_default_timeout(const SSL *s)
{
return (s->method->get_timeout());
}
int SSL_read(SSL *s, void *buf, int num)
{
if (s->handshake_func == 0) {
SSLerr(SSL_F_SSL_READ, SSL_R_UNINITIALIZED);
return -1;
}
if (s->shutdown & SSL_RECEIVED_SHUTDOWN) {
s->rwstate = SSL_NOTHING;
return (0);
}
return (s->method->ssl_read(s, buf, num));
}
int SSL_peek(SSL *s, void *buf, int num)
{
if (s->handshake_func == 0) {
SSLerr(SSL_F_SSL_PEEK, SSL_R_UNINITIALIZED);
return -1;
}
if (s->shutdown & SSL_RECEIVED_SHUTDOWN) {
return (0);
}
return (s->method->ssl_peek(s, buf, num));
}
int SSL_write(SSL *s, const void *buf, int num)
{
if (s->handshake_func == 0) {
SSLerr(SSL_F_SSL_WRITE, SSL_R_UNINITIALIZED);
return -1;
}
if (s->shutdown & SSL_SENT_SHUTDOWN) {
s->rwstate = SSL_NOTHING;
SSLerr(SSL_F_SSL_WRITE, SSL_R_PROTOCOL_IS_SHUTDOWN);
return (-1);
}
return (s->method->ssl_write(s, buf, num));
}
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 == 0) {
SSLerr(SSL_F_SSL_SHUTDOWN, SSL_R_UNINITIALIZED);
return -1;
}
if (!SSL_in_init(s)) {
return s->method->ssl_shutdown(s);
} else {
SSLerr(SSL_F_SSL_SHUTDOWN, SSL_R_SHUTDOWN_WHILE_IN_INIT);
return -1;
}
}
int SSL_renegotiate(SSL *s)
{
if (s->renegotiate == 0)
s->renegotiate = 1;
s->new_session = 1;
return (s->method->ssl_renegotiate(s));
}
int SSL_renegotiate_abbreviated(SSL *s)
{
if (s->renegotiate == 0)
s->renegotiate = 1;
s->new_session = 0;
return (s->method->ssl_renegotiate(s));
}
int SSL_renegotiate_pending(SSL *s)
{
/*
* becomes true when negotiation is requested; false again once a
* handshake has finished
*/
return (s->renegotiate != 0);
}
long SSL_ctrl(SSL *s, int cmd, long larg, void *parg)
{
long l;
switch (cmd) {
case SSL_CTRL_GET_READ_AHEAD:
return (s->read_ahead);
case SSL_CTRL_SET_READ_AHEAD:
l = s->read_ahead;
s->read_ahead = larg;
return (l);
case SSL_CTRL_SET_MSG_CALLBACK_ARG:
s->msg_callback_arg = parg;
return 1;
case SSL_CTRL_OPTIONS:
return (s->options |= larg);
case SSL_CTRL_CLEAR_OPTIONS:
return (s->options &= ~larg);
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 (s->max_cert_list);
case SSL_CTRL_SET_MAX_CERT_LIST:
l = s->max_cert_list;
s->max_cert_list = larg;
return (l);
case SSL_CTRL_SET_MAX_SEND_FRAGMENT:
if (larg < 512 || larg > SSL3_RT_MAX_PLAIN_LENGTH)
return 0;
s->max_send_fragment = larg;
return 1;
case SSL_CTRL_GET_RI_SUPPORT:
if (s->s3)
return s->s3->send_connection_binding;
else
return 0;
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->cert->ciphers_raw == NULL)
return 0;
*(unsigned char **)parg = s->cert->ciphers_raw;
return (int)s->cert->ciphers_rawlen;
} else
return ssl_put_cipher_by_char(s, NULL, NULL);
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;
}
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) {
#ifndef OPENSSL_NO_EC
case SSL_CTRL_SET_CURVES_LIST:
return tls1_set_curves_list(NULL, NULL, parg);
#endif
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 (ctx->max_cert_list);
case SSL_CTRL_SET_MAX_CERT_LIST:
l = ctx->max_cert_list;
ctx->max_cert_list = larg;
return (l);
case SSL_CTRL_SET_SESS_CACHE_SIZE:
l = ctx->session_cache_size;
ctx->session_cache_size = larg;
return (l);
case SSL_CTRL_GET_SESS_CACHE_SIZE:
return (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 (ctx->stats.sess_connect);
case SSL_CTRL_SESS_CONNECT_GOOD:
return (ctx->stats.sess_connect_good);
case SSL_CTRL_SESS_CONNECT_RENEGOTIATE:
return (ctx->stats.sess_connect_renegotiate);
case SSL_CTRL_SESS_ACCEPT:
return (ctx->stats.sess_accept);
case SSL_CTRL_SESS_ACCEPT_GOOD:
return (ctx->stats.sess_accept_good);
case SSL_CTRL_SESS_ACCEPT_RENEGOTIATE:
return (ctx->stats.sess_accept_renegotiate);
case SSL_CTRL_SESS_HIT:
return (ctx->stats.sess_hit);
case SSL_CTRL_SESS_CB_HIT:
return (ctx->stats.sess_cb_hit);
case SSL_CTRL_SESS_MISSES:
return (ctx->stats.sess_miss);
case SSL_CTRL_SESS_TIMEOUTS:
return (ctx->stats.sess_timeout);
case SSL_CTRL_SESS_CACHE_FULL:
return (ctx->stats.sess_cache_full);
case SSL_CTRL_OPTIONS:
return (ctx->options |= larg);
case SSL_CTRL_CLEAR_OPTIONS:
return (ctx->options &= ~larg);
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;
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);
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)
{
long l;
l = a->id - b->id;
if (l == 0L)
return (0);
else
return ((l > 0) ? 1 : -1);
}
int ssl_cipher_ptr_id_cmp(const SSL_CIPHER *const *ap,
const SSL_CIPHER *const *bp)
{
long l;
l = (*ap)->id - (*bp)->id;
if (l == 0L)
return (0);
else
return ((l > 0) ? 1 : -1);
}
/** 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);
}
/** 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)
{
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);
}
/** 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->method, &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 (sk_SSL_CIPHER_num(sk) == 0) {
SSLerr(SSL_F_SSL_CTX_SET_CIPHER_LIST, 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->method, &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 (sk_SSL_CIPHER_num(sk) == 0) {
SSLerr(SSL_F_SSL_SET_CIPHER_LIST, SSL_R_NO_CIPHER_MATCH);
return 0;
}
return 1;
}
/* works well for SSLv2, not so good for SSLv3 */
char *SSL_get_shared_ciphers(const SSL *s, char *buf, int len)
{
char *p;
STACK_OF(SSL_CIPHER) *sk;
SSL_CIPHER *c;
int i;
if ((s->session == NULL) || (s->session->ciphers == NULL) || (len < 2))
return (NULL);
p = buf;
sk = s->session->ciphers;
if (sk_SSL_CIPHER_num(sk) == 0)
return NULL;
for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) {
int n;
c = sk_SSL_CIPHER_value(sk, i);
n = strlen(c->name);
if (n + 1 > len) {
if (p != buf)
--p;
*p = '\0';
return buf;
}
strcpy(p, c->name);
p += n;
*(p++) = ':';
len -= n + 1;
}
p[-1] = '\0';
return (buf);
}
int ssl_cipher_list_to_bytes(SSL *s, STACK_OF(SSL_CIPHER) *sk,
unsigned char *p,
int (*put_cb) (const SSL_CIPHER *,
unsigned char *))
{
int i, j = 0;
SSL_CIPHER *c;
CERT *ct = s->cert;
unsigned char *q;
int empty_reneg_info_scsv = !s->renegotiate;
/* Set disabled masks for this session */
ssl_set_client_disabled(s);
if (sk == NULL)
return (0);
q = p;
if (put_cb == NULL)
put_cb = s->method->put_cipher_by_char;
for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) {
c = sk_SSL_CIPHER_value(sk, i);
/* Skip disabled ciphers */
if (c->algorithm_ssl & ct->mask_ssl ||
c->algorithm_mkey & ct->mask_k || c->algorithm_auth & ct->mask_a)
continue;
#ifdef OPENSSL_SSL_DEBUG_BROKEN_PROTOCOL
if (c->id == SSL3_CK_SCSV) {
if (!empty_reneg_info_scsv)
continue;
else
empty_reneg_info_scsv = 0;
}
#endif
j = put_cb(c, p);
p += j;
}
/*
* If p == q, no ciphers; caller indicates an error. Otherwise, add
* applicable SCSVs.
*/
if (p != q) {
if (empty_reneg_info_scsv) {
static SSL_CIPHER scsv = {
0, NULL, SSL3_CK_SCSV, 0, 0, 0, 0, 0, 0, 0, 0, 0
};
j = put_cb(&scsv, p);
p += j;
#ifdef OPENSSL_RI_DEBUG
fprintf(stderr,
"TLS_EMPTY_RENEGOTIATION_INFO_SCSV sent by client\n");
#endif
}
if (s->mode & SSL_MODE_SEND_FALLBACK_SCSV) {
static SSL_CIPHER scsv = {
0, NULL, SSL3_CK_FALLBACK_SCSV, 0, 0, 0, 0, 0, 0, 0, 0, 0
};
j = put_cb(&scsv, p);
p += j;
}
}
return (p - q);
}
STACK_OF(SSL_CIPHER) *ssl_bytes_to_cipher_list(SSL *s, unsigned char *p,
int num,
STACK_OF(SSL_CIPHER) **skp)
{
const SSL_CIPHER *c;
STACK_OF(SSL_CIPHER) *sk;
int i, n;
if (s->s3)
s->s3->send_connection_binding = 0;
n = ssl_put_cipher_by_char(s, NULL, NULL);
if (n == 0 || (num % n) != 0) {
SSLerr(SSL_F_SSL_BYTES_TO_CIPHER_LIST,
SSL_R_ERROR_IN_RECEIVED_CIPHER_LIST);
return (NULL);
}
if ((skp == NULL) || (*skp == NULL)) {
sk = sk_SSL_CIPHER_new_null(); /* change perhaps later */
if(sk == NULL) {
SSLerr(SSL_F_SSL_BYTES_TO_CIPHER_LIST, ERR_R_MALLOC_FAILURE);
return NULL;
}
} else {
sk = *skp;
sk_SSL_CIPHER_zero(sk);
}
if (s->cert->ciphers_raw)
OPENSSL_free(s->cert->ciphers_raw);
s->cert->ciphers_raw = BUF_memdup(p, num);
if (s->cert->ciphers_raw == NULL) {
SSLerr(SSL_F_SSL_BYTES_TO_CIPHER_LIST, ERR_R_MALLOC_FAILURE);
goto err;
}
s->cert->ciphers_rawlen = (size_t)num;
for (i = 0; i < num; i += n) {
/* Check for TLS_EMPTY_RENEGOTIATION_INFO_SCSV */
if (s->s3 && (n != 3 || !p[0]) &&
(p[n - 2] == ((SSL3_CK_SCSV >> 8) & 0xff)) &&
(p[n - 1] == (SSL3_CK_SCSV & 0xff))) {
/* SCSV fatal if renegotiating */
if (s->renegotiate) {
SSLerr(SSL_F_SSL_BYTES_TO_CIPHER_LIST,
SSL_R_SCSV_RECEIVED_WHEN_RENEGOTIATING);
ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
goto err;
}
s->s3->send_connection_binding = 1;
p += n;
#ifdef OPENSSL_RI_DEBUG
fprintf(stderr, "SCSV received by server\n");
#endif
continue;
}
/* Check for TLS_FALLBACK_SCSV */
if ((n != 3 || !p[0]) &&
(p[n - 2] == ((SSL3_CK_FALLBACK_SCSV >> 8) & 0xff)) &&
(p[n - 1] == (SSL3_CK_FALLBACK_SCSV & 0xff))) {
/*
* The SCSV indicates that the client previously tried a higher
* version. Fail if the current version is an unexpected
* downgrade.
*/
if (!SSL_ctrl(s, SSL_CTRL_CHECK_PROTO_VERSION, 0, NULL)) {
SSLerr(SSL_F_SSL_BYTES_TO_CIPHER_LIST,
SSL_R_INAPPROPRIATE_FALLBACK);
if (s->s3)
ssl3_send_alert(s, SSL3_AL_FATAL,
SSL_AD_INAPPROPRIATE_FALLBACK);
goto err;
}
p += n;
continue;
}
c = ssl_get_cipher_by_char(s, p);
p += n;
if (c != NULL) {
if (!sk_SSL_CIPHER_push(sk, c)) {
SSLerr(SSL_F_SSL_BYTES_TO_CIPHER_LIST, ERR_R_MALLOC_FAILURE);
goto err;
}
}
}
if (skp != NULL)
*skp = sk;
return (sk);
err:
if ((skp == NULL) || (*skp == NULL))
sk_SSL_CIPHER_free(sk);
return (NULL);
}
#ifndef OPENSSL_NO_TLSEXT
/** return a servername extension value if provided in Client Hello, or NULL.
* So far, only host_name types are defined (RFC 3546).
*/
const char *SSL_get_servername(const SSL *s, const int type)
{
if (type != TLSEXT_NAMETYPE_host_name)
return NULL;
return s->session && !s->tlsext_hostname ?
s->session->tlsext_hostname : s->tlsext_hostname;
}
int SSL_get_servername_type(const SSL *s)
{
if (s->session
&& (!s->tlsext_hostname ? s->session->
tlsext_hostname : s->tlsext_hostname))
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 protcol in its list, but indicates via the API that this
* fallback case was enacted. 3) Otherwise, the client finds the first
* protocol in the server's list that it supports and selects this protocol.
* This is because it's assumed that the server has better information about
* which protocol a client should use. 4) If the client doesn't support any
* of the server's advertised protocols, then this is treated the same as
* case 2. It returns either OPENSSL_NPN_NEGOTIATED if a common protocol was
* found, or OPENSSL_NPN_NO_OVERLAP if the fallback case was reached.
*/
int SSL_select_next_proto(unsigned char **out, unsigned char *outlen,
const unsigned char *server,
unsigned int server_len,
const unsigned char *client,
unsigned int client_len)
{
unsigned int i, j;
const unsigned char *result;
int status = OPENSSL_NPN_UNSUPPORTED;
/*
* For each protocol in server preference order, see if we support it.
*/
for (i = 0; i < server_len;) {
for (j = 0; j < client_len;) {
if (server[i] == client[j] &&
memcmp(&server[i + 1], &client[j + 1], server[i]) == 0) {
/* We found a match */
result = &server[i];
status = OPENSSL_NPN_NEGOTIATED;
goto found;
}
j += client[j];
j++;
}
i += server[i];
i++;
}
/* There's no overlap between our protocols and the server's list. */
result = client;
status = OPENSSL_NPN_NO_OVERLAP;
found:
*out = (unsigned char *)result + 1;
*outlen = result[0];
return status;
}
# ifndef OPENSSL_NO_NEXTPROTONEG
/*
* SSL_get0_next_proto_negotiated sets *data and *len to point to the
* client's requested protocol for this connection and returns 0. If the
* client didn't request any protocol, then *data is set to NULL. Note that
* the client can request any protocol it chooses. The value returned from
* this function need not be a member of the list of supported protocols
* provided by the callback.
*/
void SSL_get0_next_proto_negotiated(const SSL *s, const unsigned char **data,
unsigned *len)
{
*data = s->next_proto_negotiated;
if (!*data) {
*len = 0;
} else {
*len = s->next_proto_negotiated_len;
}
}
/*
* SSL_CTX_set_next_protos_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_next_protos_advertised_cb(SSL_CTX *ctx,
int (*cb) (SSL *ssl,
const unsigned char
**out,
unsigned int *outlen,
void *arg), void *arg)
{
ctx->next_protos_advertised_cb = cb;
ctx->next_protos_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_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)
{
ctx->next_proto_select_cb = cb;
ctx->next_proto_select_cb_arg = arg;
}
# endif
/*
* 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 protos_len)
{
if (ctx->alpn_client_proto_list)
OPENSSL_free(ctx->alpn_client_proto_list);
ctx->alpn_client_proto_list = OPENSSL_malloc(protos_len);
if (!ctx->alpn_client_proto_list)
return 1;
memcpy(ctx->alpn_client_proto_list, protos, protos_len);
ctx->alpn_client_proto_list_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 protos_len)
{
if (ssl->alpn_client_proto_list)
OPENSSL_free(ssl->alpn_client_proto_list);
ssl->alpn_client_proto_list = OPENSSL_malloc(protos_len);
if (!ssl->alpn_client_proto_list)
return 1;
memcpy(ssl->alpn_client_proto_list, protos, protos_len);
ssl->alpn_client_proto_list_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,
int (*cb) (SSL *ssl,
const unsigned char **out,
unsigned char *outlen,
const unsigned char *in,
unsigned int inlen,
void *arg), void *arg)
{
ctx->alpn_select_cb = cb;
ctx->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 *len)
{
*data = NULL;
if (ssl->s3)
*data = ssl->s3->alpn_selected;
if (*data == NULL)
*len = 0;
else
*len = ssl->s3->alpn_selected_len;
}
#endif /* !OPENSSL_NO_TLSEXT */
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->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);
}
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.
*/
static IMPLEMENT_LHASH_HASH_FN(ssl_session, SSL_SESSION)
static IMPLEMENT_LHASH_COMP_FN(ssl_session, SSL_SESSION)
SSL_CTX *SSL_CTX_new(const SSL_METHOD *meth)
{
SSL_CTX *ret = NULL;
if (meth == NULL) {
SSLerr(SSL_F_SSL_CTX_NEW, SSL_R_NULL_SSL_METHOD_PASSED);
return (NULL);
}
#ifdef OPENSSL_FIPS
if (FIPS_mode() && (meth->version < TLS1_VERSION)) {
SSLerr(SSL_F_SSL_CTX_NEW, SSL_R_ONLY_TLS_ALLOWED_IN_FIPS_MODE);
return NULL;
}
#endif
if (SSL_get_ex_data_X509_STORE_CTX_idx() < 0) {
SSLerr(SSL_F_SSL_CTX_NEW, SSL_R_X509_VERIFICATION_SETUP_PROBLEMS);
goto err;
}
ret = (SSL_CTX *)OPENSSL_malloc(sizeof(SSL_CTX));
if (ret == NULL)
goto err;
memset(ret, 0, sizeof(SSL_CTX));
ret->method = meth;
ret->cert_store = NULL;
ret->session_cache_mode = SSL_SESS_CACHE_SERVER;
ret->session_cache_size = SSL_SESSION_CACHE_MAX_SIZE_DEFAULT;
ret->session_cache_head = NULL;
ret->session_cache_tail = NULL;
/* We take the system default */
ret->session_timeout = meth->get_timeout();
ret->new_session_cb = 0;
ret->remove_session_cb = 0;
ret->get_session_cb = 0;
ret->generate_session_id = 0;
memset((char *)&ret->stats, 0, sizeof(ret->stats));
ret->references = 1;
ret->quiet_shutdown = 0;
/* ret->cipher=NULL;*/
/*-
ret->s2->challenge=NULL;
ret->master_key=NULL;
ret->key_arg=NULL;
ret->s2->conn_id=NULL; */
ret->info_callback = NULL;
ret->app_verify_callback = 0;
ret->app_verify_arg = NULL;
ret->max_cert_list = SSL_MAX_CERT_LIST_DEFAULT;
ret->read_ahead = 0;
ret->msg_callback = 0;
ret->msg_callback_arg = NULL;
ret->verify_mode = SSL_VERIFY_NONE;
#if 0
ret->verify_depth = -1; /* Don't impose a limit (but x509_lu.c does) */
#endif
ret->sid_ctx_length = 0;
ret->default_verify_callback = NULL;
if ((ret->cert = ssl_cert_new()) == NULL)
goto err;
ret->default_passwd_callback = 0;
ret->default_passwd_callback_userdata = NULL;
ret->client_cert_cb = 0;
ret->app_gen_cookie_cb = 0;
ret->app_verify_cookie_cb = 0;
ret->sessions = lh_SSL_SESSION_new();
if (ret->sessions == NULL)
goto err;
ret->cert_store = X509_STORE_new();
if (ret->cert_store == NULL)
goto err;
ssl_create_cipher_list(ret->method,
&ret->cipher_list, &ret->cipher_list_by_id,
meth->version ==
SSL2_VERSION ? "SSLv2" : SSL_DEFAULT_CIPHER_LIST,
ret->cert);
if (ret->cipher_list == NULL || sk_SSL_CIPHER_num(ret->cipher_list) <= 0) {
SSLerr(SSL_F_SSL_CTX_NEW, SSL_R_LIBRARY_HAS_NO_CIPHERS);
goto err2;
}
ret->param = X509_VERIFY_PARAM_new();
if (!ret->param)
goto err;
if ((ret->rsa_md5 = EVP_get_digestbyname("ssl2-md5")) == NULL) {
SSLerr(SSL_F_SSL_CTX_NEW, SSL_R_UNABLE_TO_LOAD_SSL2_MD5_ROUTINES);
goto err2;
}
if ((ret->md5 = EVP_get_digestbyname("ssl3-md5")) == NULL) {
SSLerr(SSL_F_SSL_CTX_NEW, SSL_R_UNABLE_TO_LOAD_SSL3_MD5_ROUTINES);
goto err2;
}
if ((ret->sha1 = EVP_get_digestbyname("ssl3-sha1")) == NULL) {
SSLerr(SSL_F_SSL_CTX_NEW, SSL_R_UNABLE_TO_LOAD_SSL3_SHA1_ROUTINES);
goto err2;
}
if ((ret->client_CA = sk_X509_NAME_new_null()) == NULL)
goto err;
CRYPTO_new_ex_data(CRYPTO_EX_INDEX_SSL_CTX, ret, &ret->ex_data);
ret->extra_certs = NULL;
/* 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;
#ifndef OPENSSL_NO_TLSEXT
ret->tlsext_servername_callback = 0;
ret->tlsext_servername_arg = NULL;
/* Setup RFC4507 ticket keys */
if ((RAND_bytes(ret->tlsext_tick_key_name, 16) <= 0)
|| (RAND_bytes(ret->tlsext_tick_hmac_key, 16) <= 0)
|| (RAND_bytes(ret->tlsext_tick_aes_key, 16) <= 0))
ret->options |= SSL_OP_NO_TICKET;
ret->tlsext_status_cb = 0;
ret->tlsext_status_arg = NULL;
# ifndef OPENSSL_NO_NEXTPROTONEG
ret->next_protos_advertised_cb = 0;
ret->next_proto_select_cb = 0;
# endif
#endif
#ifndef OPENSSL_NO_PSK
ret->psk_identity_hint = NULL;
ret->psk_client_callback = NULL;
ret->psk_server_callback = NULL;
#endif
#ifndef OPENSSL_NO_SRP
SSL_CTX_SRP_CTX_init(ret);
#endif
#ifndef OPENSSL_NO_BUF_FREELISTS
ret->freelist_max_len = SSL_MAX_BUF_FREELIST_LEN_DEFAULT;
ret->rbuf_freelist = OPENSSL_malloc(sizeof(SSL3_BUF_FREELIST));
if (!ret->rbuf_freelist)
goto err;
ret->rbuf_freelist->chunklen = 0;
ret->rbuf_freelist->len = 0;
ret->rbuf_freelist->head = NULL;
ret->wbuf_freelist = OPENSSL_malloc(sizeof(SSL3_BUF_FREELIST));
if (!ret->wbuf_freelist)
goto err;
ret->wbuf_freelist->chunklen = 0;
ret->wbuf_freelist->len = 0;
ret->wbuf_freelist->head = NULL;
#endif
#ifndef OPENSSL_NO_ENGINE
ret->client_cert_engine = NULL;
# 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
/*
* Default is to connect to non-RI servers. When RI is more widely
* deployed might change this.
*/
ret->options |= SSL_OP_LEGACY_SERVER_CONNECT;
/*
* Disable SSLv2 by default, callers that want to enable SSLv2 will have to
* explicitly clear this option via either of SSL_CTX_clear_options() or
* SSL_clear_options().
*/
ret->options |= SSL_OP_NO_SSLv2;
return (ret);
err:
SSLerr(SSL_F_SSL_CTX_NEW, ERR_R_MALLOC_FAILURE);
err2:
if (ret != NULL)
SSL_CTX_free(ret);
return (NULL);
}
#if 0
static void SSL_COMP_free(SSL_COMP *comp)
{
OPENSSL_free(comp);
}
#endif
#ifndef OPENSSL_NO_BUF_FREELISTS
static void ssl_buf_freelist_free(SSL3_BUF_FREELIST *list)
{
SSL3_BUF_FREELIST_ENTRY *ent, *next;
for (ent = list->head; ent; ent = next) {
next = ent->next;
OPENSSL_free(ent);
}
OPENSSL_free(list);
}
#endif
void SSL_CTX_free(SSL_CTX *a)
{
int i;
if (a == NULL)
return;
i = CRYPTO_add(&a->references, -1, CRYPTO_LOCK_SSL_CTX);
#ifdef REF_PRINT
REF_PRINT("SSL_CTX", a);
#endif
if (i > 0)
return;
#ifdef REF_CHECK
if (i < 0) {
fprintf(stderr, "SSL_CTX_free, bad reference count\n");
abort(); /* ok */
}
#endif
if (a->param)
X509_VERIFY_PARAM_free(a->param);
/*
* 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);
if (a->sessions != NULL)
lh_SSL_SESSION_free(a->sessions);
if (a->cert_store != NULL)
X509_STORE_free(a->cert_store);
if (a->cipher_list != NULL)
sk_SSL_CIPHER_free(a->cipher_list);
if (a->cipher_list_by_id != NULL)
sk_SSL_CIPHER_free(a->cipher_list_by_id);
if (a->cert != NULL)
ssl_cert_free(a->cert);
if (a->client_CA != NULL)
sk_X509_NAME_pop_free(a->client_CA, X509_NAME_free);
if (a->extra_certs != NULL)
sk_X509_pop_free(a->extra_certs, X509_free);
#if 0 /* This should never be done, since it
* removes a global database */
if (a->comp_methods != NULL)
sk_SSL_COMP_pop_free(a->comp_methods, SSL_COMP_free);
#else
a->comp_methods = NULL;
#endif
#ifndef OPENSSL_NO_SRTP
if (a->srtp_profiles)
sk_SRTP_PROTECTION_PROFILE_free(a->srtp_profiles);
#endif
#ifndef OPENSSL_NO_PSK
if (a->psk_identity_hint)
OPENSSL_free(a->psk_identity_hint);
#endif
#ifndef OPENSSL_NO_SRP
SSL_CTX_SRP_CTX_free(a);
#endif
#ifndef OPENSSL_NO_ENGINE
if (a->client_cert_engine)
ENGINE_finish(a->client_cert_engine);
#endif
#ifndef OPENSSL_NO_BUF_FREELISTS
if (a->wbuf_freelist)
ssl_buf_freelist_free(a->wbuf_freelist);
if (a->rbuf_freelist)
ssl_buf_freelist_free(a->rbuf_freelist);
#endif
#ifndef OPENSSL_NO_TLSEXT
# ifndef OPENSSL_NO_EC
if (a->tlsext_ecpointformatlist)
OPENSSL_free(a->tlsext_ecpointformatlist);
if (a->tlsext_ellipticcurvelist)
OPENSSL_free(a->tlsext_ellipticcurvelist);
# endif /* OPENSSL_NO_EC */
if (a->alpn_client_proto_list != NULL)
OPENSSL_free(a->alpn_client_proto_list);
#endif
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;
}
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_cert_masks(CERT *c, const SSL_CIPHER *cipher)
{
CERT_PKEY *cpk;
int rsa_enc, rsa_tmp, rsa_sign, dh_tmp, dh_rsa, dh_dsa, dsa_sign;
int rsa_enc_export, dh_rsa_export, dh_dsa_export;
int rsa_tmp_export, dh_tmp_export, kl;
unsigned long mask_k, mask_a, emask_k, emask_a;
#ifndef OPENSSL_NO_ECDSA
int have_ecc_cert, ecdsa_ok, ecc_pkey_size;
#endif
#ifndef OPENSSL_NO_ECDH
int have_ecdh_tmp, ecdh_ok;
#endif
#ifndef OPENSSL_NO_EC
X509 *x = NULL;
EVP_PKEY *ecc_pkey = NULL;
int signature_nid = 0, pk_nid = 0, md_nid = 0;
#endif
if (c == NULL)
return;
kl = SSL_C_EXPORT_PKEYLENGTH(cipher);
#ifndef OPENSSL_NO_RSA
rsa_tmp = (c->rsa_tmp != NULL || c->rsa_tmp_cb != NULL);
rsa_tmp_export = (c->rsa_tmp_cb != NULL ||
(rsa_tmp && RSA_size(c->rsa_tmp) * 8 <= kl));
#else
rsa_tmp = rsa_tmp_export = 0;
#endif
#ifndef OPENSSL_NO_DH
dh_tmp = (c->dh_tmp != NULL || c->dh_tmp_cb != NULL);
dh_tmp_export = (c->dh_tmp_cb != NULL ||
(dh_tmp && DH_size(c->dh_tmp) * 8 <= kl));
#else
dh_tmp = dh_tmp_export = 0;
#endif
#ifndef OPENSSL_NO_ECDH
have_ecdh_tmp = (c->ecdh_tmp || c->ecdh_tmp_cb || c->ecdh_tmp_auto);
#endif
cpk = &(c->pkeys[SSL_PKEY_RSA_ENC]);
rsa_enc = cpk->valid_flags & CERT_PKEY_VALID;
rsa_enc_export = (rsa_enc && EVP_PKEY_size(cpk->privatekey) * 8 <= kl);
cpk = &(c->pkeys[SSL_PKEY_RSA_SIGN]);
rsa_sign = cpk->valid_flags & CERT_PKEY_SIGN;
cpk = &(c->pkeys[SSL_PKEY_DSA_SIGN]);
dsa_sign = cpk->valid_flags & CERT_PKEY_SIGN;
cpk = &(c->pkeys[SSL_PKEY_DH_RSA]);
dh_rsa = cpk->valid_flags & CERT_PKEY_VALID;
dh_rsa_export = (dh_rsa && EVP_PKEY_size(cpk->privatekey) * 8 <= kl);
cpk = &(c->pkeys[SSL_PKEY_DH_DSA]);
/* FIX THIS EAY EAY EAY */
dh_dsa = cpk->valid_flags & CERT_PKEY_VALID;
dh_dsa_export = (dh_dsa && EVP_PKEY_size(cpk->privatekey) * 8 <= kl);
cpk = &(c->pkeys[SSL_PKEY_ECC]);
#ifndef OPENSSL_NO_EC
have_ecc_cert = cpk->valid_flags & CERT_PKEY_VALID;
#endif
mask_k = 0;
mask_a = 0;
emask_k = 0;
emask_a = 0;
#ifdef CIPHER_DEBUG
fprintf(stderr,
"rt=%d rte=%d dht=%d ecdht=%d re=%d ree=%d rs=%d ds=%d dhr=%d dhd=%d\n",
rsa_tmp, rsa_tmp_export, dh_tmp, have_ecdh_tmp, rsa_enc,
rsa_enc_export, rsa_sign, dsa_sign, dh_rsa, dh_dsa);
#endif
cpk = &(c->pkeys[SSL_PKEY_GOST01]);
if (cpk->x509 != NULL && cpk->privatekey != NULL) {
mask_k |= SSL_kGOST;
mask_a |= SSL_aGOST01;
}
cpk = &(c->pkeys[SSL_PKEY_GOST94]);
if (cpk->x509 != NULL && cpk->privatekey != NULL) {
mask_k |= SSL_kGOST;
mask_a |= SSL_aGOST94;
}
if (rsa_enc || (rsa_tmp && rsa_sign))
mask_k |= SSL_kRSA;
if (rsa_enc_export || (rsa_tmp_export && (rsa_sign || rsa_enc)))
emask_k |= SSL_kRSA;
#if 0
/* The match needs to be both kEDH and aRSA or aDSA, so don't worry */
if ((dh_tmp || dh_rsa || dh_dsa) && (rsa_enc || rsa_sign || dsa_sign))
mask_k |= SSL_kEDH;
if ((dh_tmp_export || dh_rsa_export || dh_dsa_export) &&
(rsa_enc || rsa_sign || dsa_sign))
emask_k |= SSL_kEDH;
#endif
if (dh_tmp_export)
emask_k |= SSL_kEDH;
if (dh_tmp)
mask_k |= SSL_kEDH;
if (dh_rsa)
mask_k |= SSL_kDHr;
if (dh_rsa_export)
emask_k |= SSL_kDHr;
if (dh_dsa)
mask_k |= SSL_kDHd;
if (dh_dsa_export)
emask_k |= SSL_kDHd;
if (mask_k & (SSL_kDHr | SSL_kDHd))
mask_a |= SSL_aDH;
if (rsa_enc || rsa_sign) {
mask_a |= SSL_aRSA;
emask_a |= SSL_aRSA;
}
if (dsa_sign) {
mask_a |= SSL_aDSS;
emask_a |= SSL_aDSS;
}
mask_a |= SSL_aNULL;
emask_a |= SSL_aNULL;
#ifndef OPENSSL_NO_KRB5
mask_k |= SSL_kKRB5;
mask_a |= SSL_aKRB5;
emask_k |= SSL_kKRB5;
emask_a |= SSL_aKRB5;
#endif
/*
* An ECC certificate may be usable for ECDH and/or ECDSA cipher suites
* depending on the key usage extension.
*/
#ifndef OPENSSL_NO_EC
if (have_ecc_cert) {
cpk = &c->pkeys[SSL_PKEY_ECC];
x = cpk->x509;
/* This call populates extension flags (ex_flags) */
X509_check_purpose(x, -1, 0);
# ifndef OPENSSL_NO_ECDH
ecdh_ok = (x->ex_flags & EXFLAG_KUSAGE) ?
(x->ex_kusage & X509v3_KU_KEY_AGREEMENT) : 1;
# endif
ecdsa_ok = (x->ex_flags & EXFLAG_KUSAGE) ?
(x->ex_kusage & X509v3_KU_DIGITAL_SIGNATURE) : 1;
if (!(cpk->valid_flags & CERT_PKEY_SIGN))
ecdsa_ok = 0;
ecc_pkey = X509_get_pubkey(x);
ecc_pkey_size = (ecc_pkey != NULL) ? EVP_PKEY_bits(ecc_pkey) : 0;
EVP_PKEY_free(ecc_pkey);
if ((x->sig_alg) && (x->sig_alg->algorithm)) {
signature_nid = OBJ_obj2nid(x->sig_alg->algorithm);
OBJ_find_sigid_algs(signature_nid, &md_nid, &pk_nid);
}
# ifndef OPENSSL_NO_ECDH
if (ecdh_ok) {
if (pk_nid == NID_rsaEncryption || pk_nid == NID_rsa) {
mask_k |= SSL_kECDHr;
mask_a |= SSL_aECDH;
if (ecc_pkey_size <= 163) {
emask_k |= SSL_kECDHr;
emask_a |= SSL_aECDH;
}
}
if (pk_nid == NID_X9_62_id_ecPublicKey) {
mask_k |= SSL_kECDHe;
mask_a |= SSL_aECDH;
if (ecc_pkey_size <= 163) {
emask_k |= SSL_kECDHe;
emask_a |= SSL_aECDH;
}
}
}
# endif
# ifndef OPENSSL_NO_ECDSA
if (ecdsa_ok) {
mask_a |= SSL_aECDSA;
emask_a |= SSL_aECDSA;
}
# endif
}
#endif
#ifndef OPENSSL_NO_ECDH
if (have_ecdh_tmp) {
mask_k |= SSL_kEECDH;
emask_k |= SSL_kEECDH;
}
#endif
#ifndef OPENSSL_NO_PSK
mask_k |= SSL_kPSK;
mask_a |= SSL_aPSK;
emask_k |= SSL_kPSK;
emask_a |= SSL_aPSK;
#endif
c->mask_k = mask_k;
c->mask_a = mask_a;
c->export_mask_k = emask_k;
c->export_mask_a = emask_a;
c->valid = 1;
}
/* This handy macro borrowed from crypto/x509v3/v3_purp.c */
#define ku_reject(x, usage) \
(((x)->ex_flags & EXFLAG_KUSAGE) && !((x)->ex_kusage & (usage)))
#ifndef OPENSSL_NO_EC
int ssl_check_srvr_ecc_cert_and_alg(X509 *x, SSL *s)
{
unsigned long alg_k, alg_a;
EVP_PKEY *pkey = NULL;
int keysize = 0;
int signature_nid = 0, md_nid = 0, pk_nid = 0;
const SSL_CIPHER *cs = s->s3->tmp.new_cipher;
alg_k = cs->algorithm_mkey;
alg_a = cs->algorithm_auth;
if (SSL_C_IS_EXPORT(cs)) {
/* ECDH key length in export ciphers must be <= 163 bits */
pkey = X509_get_pubkey(x);
if (pkey == NULL)
return 0;
keysize = EVP_PKEY_bits(pkey);
EVP_PKEY_free(pkey);
if (keysize > 163)
return 0;
}
/* This call populates the ex_flags field correctly */
X509_check_purpose(x, -1, 0);
if ((x->sig_alg) && (x->sig_alg->algorithm)) {
signature_nid = OBJ_obj2nid(x->sig_alg->algorithm);
OBJ_find_sigid_algs(signature_nid, &md_nid, &pk_nid);
}
if (alg_k & SSL_kECDHe || alg_k & SSL_kECDHr) {
/* key usage, if present, must allow key agreement */
if (ku_reject(x, X509v3_KU_KEY_AGREEMENT)) {
SSLerr(SSL_F_SSL_CHECK_SRVR_ECC_CERT_AND_ALG,
SSL_R_ECC_CERT_NOT_FOR_KEY_AGREEMENT);
return 0;
}
if ((alg_k & SSL_kECDHe) && TLS1_get_version(s) < TLS1_2_VERSION) {
/* signature alg must be ECDSA */
if (pk_nid != NID_X9_62_id_ecPublicKey) {
SSLerr(SSL_F_SSL_CHECK_SRVR_ECC_CERT_AND_ALG,
SSL_R_ECC_CERT_SHOULD_HAVE_SHA1_SIGNATURE);
return 0;
}
}
if ((alg_k & SSL_kECDHr) && TLS1_get_version(s) < TLS1_2_VERSION) {
/* signature alg must be RSA */
if (pk_nid != NID_rsaEncryption && pk_nid != NID_rsa) {
SSLerr(SSL_F_SSL_CHECK_SRVR_ECC_CERT_AND_ALG,
SSL_R_ECC_CERT_SHOULD_HAVE_RSA_SIGNATURE);
return 0;
}
}
}
if (alg_a & SSL_aECDSA) {
/* key usage, if present, must allow signing */
if (ku_reject(x, X509v3_KU_DIGITAL_SIGNATURE)) {
SSLerr(SSL_F_SSL_CHECK_SRVR_ECC_CERT_AND_ALG,
SSL_R_ECC_CERT_NOT_FOR_SIGNING);
return 0;
}
}
return 1; /* all checks are ok */
}
#endif
static int ssl_get_server_cert_index(const SSL *s)
{
int idx;
idx = ssl_cipher_get_cert_index(s->s3->tmp.new_cipher);
if (idx == SSL_PKEY_RSA_ENC && !s->cert->pkeys[SSL_PKEY_RSA_ENC].x509)
idx = SSL_PKEY_RSA_SIGN;
if (idx == -1)
SSLerr(SSL_F_SSL_GET_SERVER_CERT_INDEX, ERR_R_INTERNAL_ERROR);
return idx;
}
CERT_PKEY *ssl_get_server_send_pkey(const SSL *s)
{
CERT *c;
int i;
c = s->cert;
if (!s->s3 || !s->s3->tmp.new_cipher)
return NULL;
ssl_set_cert_masks(c, s->s3->tmp.new_cipher);
#ifdef OPENSSL_SSL_DEBUG_BROKEN_PROTOCOL
/*
* Broken protocol test: return last used certificate: which may mismatch
* the one expected.
*/
if (c->cert_flags & SSL_CERT_FLAG_BROKEN_PROTOCOL)
return c->key;
#endif
i = ssl_get_server_cert_index(s);
/* This may or may not be an error. */
if (i < 0)
return NULL;
/* May be NULL. */
return &c->pkeys[i];
}
EVP_PKEY *ssl_get_sign_pkey(SSL *s, const SSL_CIPHER *cipher,
const EVP_MD **pmd)
{
unsigned long alg_a;
CERT *c;
int idx = -1;
alg_a = cipher->algorithm_auth;
c = s->cert;
#ifdef OPENSSL_SSL_DEBUG_BROKEN_PROTOCOL
/*
* Broken protocol test: use last key: which may mismatch the one
* expected.
*/
if (c->cert_flags & SSL_CERT_FLAG_BROKEN_PROTOCOL)
idx = c->key - c->pkeys;
else
#endif
if ((alg_a & SSL_aDSS) &&
(c->pkeys[SSL_PKEY_DSA_SIGN].privatekey != NULL))
idx = SSL_PKEY_DSA_SIGN;
else if (alg_a & SSL_aRSA) {
if (c->pkeys[SSL_PKEY_RSA_SIGN].privatekey != NULL)
idx = SSL_PKEY_RSA_SIGN;
else if (c->pkeys[SSL_PKEY_RSA_ENC].privatekey != NULL)
idx = SSL_PKEY_RSA_ENC;
} else if ((alg_a & SSL_aECDSA) &&
(c->pkeys[SSL_PKEY_ECC].privatekey != NULL))
idx = SSL_PKEY_ECC;
if (idx == -1) {
SSLerr(SSL_F_SSL_GET_SIGN_PKEY, ERR_R_INTERNAL_ERROR);
return (NULL);
}
if (pmd)
*pmd = c->pkeys[idx].digest;
return c->pkeys[idx].privatekey;
}
#ifndef OPENSSL_NO_TLSEXT
int ssl_get_server_cert_serverinfo(SSL *s, const unsigned char **serverinfo,
size_t *serverinfo_length)
{
CERT *c = NULL;
int i = 0;
*serverinfo_length = 0;
c = s->cert;
i = ssl_get_server_cert_index(s);
if (i == -1)
return 0;
if (c->pkeys[i].serverinfo == NULL)
return 0;
*serverinfo = c->pkeys[i].serverinfo;
*serverinfo_length = c->pkeys[i].serverinfo_length;
return 1;
}
#endif
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 :-)
*/
if (s->session->session_id_length == 0)
return;
i = s->session_ctx->session_cache_mode;
if ((i & mode) && (!s->hit)
&& ((i & SSL_SESS_CACHE_NO_INTERNAL_STORE)
|| SSL_CTX_add_session(s->session_ctx, s->session))
&& (s->session_ctx->new_session_cb != NULL)) {
CRYPTO_add(&s->session->references, 1, CRYPTO_LOCK_SSL_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)) {
if ((((mode & SSL_SESS_CACHE_CLIENT)
? s->session_ctx->stats.sess_connect_good
: s->session_ctx->stats.sess_accept_good) & 0xff) == 0xff) {
SSL_CTX_flush_sessions(s->session_ctx, (unsigned long)time(NULL));
}
}
}
const SSL_METHOD *SSL_CTX_get_ssl_method(SSL_CTX *ctx)
{
return ctx->method;
}
const SSL_METHOD *SSL_get_ssl_method(SSL *s)
{
return (s->method);
}
int SSL_set_ssl_method(SSL *s, const SSL_METHOD *meth)
{
int conn = -1;
int ret = 1;
if (s->method != meth) {
if (s->handshake_func != NULL)
conn = (s->handshake_func == s->method->ssl_connect);
if (s->method->version == meth->version)
s->method = meth;
else {
s->method->ssl_free(s);
s->method = meth;
ret = s->method->ssl_new(s);
}
if (conn == 1)
s->handshake_func = meth->ssl_connect;
else if (conn == 0)
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 ((i < 0) && 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 ((i < 0) && SSL_want_write(s)) {
bio = SSL_get_wbio(s);
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 ((i < 0) && SSL_want_x509_lookup(s)) {
return (SSL_ERROR_WANT_X509_LOOKUP);
}
if (i == 0) {
if (s->version == SSL2_VERSION) {
/* assume it is the socket being closed */
return (SSL_ERROR_ZERO_RETURN);
} else {
if ((s->shutdown & SSL_RECEIVED_SHUTDOWN) &&
(s->s3->warn_alert == SSL_AD_CLOSE_NOTIFY))
return (SSL_ERROR_ZERO_RETURN);
}
}
return (SSL_ERROR_SYSCALL);
}
int SSL_do_handshake(SSL *s)
{
int ret = 1;
if (s->handshake_func == NULL) {
SSLerr(SSL_F_SSL_DO_HANDSHAKE, SSL_R_CONNECTION_TYPE_NOT_SET);
return (-1);
}
s->method->ssl_renegotiate_check(s);
if (SSL_in_init(s) || SSL_in_before(s)) {
ret = s->handshake_func(s);
}
return (ret);
}
/*
* For the next 2 functions, SSL_clear() sets shutdown and so one of these
* calls will reset it
*/
void SSL_set_accept_state(SSL *s)
{
s->server = 1;
s->shutdown = 0;
s->state = SSL_ST_ACCEPT | SSL_ST_BEFORE;
s->handshake_func = s->method->ssl_accept;
/* clear the current cipher */
ssl_clear_cipher_ctx(s);
ssl_clear_hash_ctx(&s->read_hash);
ssl_clear_hash_ctx(&s->write_hash);
}
void SSL_set_connect_state(SSL *s)
{
s->server = 0;
s->shutdown = 0;
s->state = SSL_ST_CONNECT | SSL_ST_BEFORE;
s->handshake_func = s->method->ssl_connect;
/* 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_undefined_function(SSL *s)
{
SSLerr(SSL_F_SSL_UNDEFINED_FUNCTION, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
return (0);
}
int ssl_undefined_void_function(void)
{
SSLerr(SSL_F_SSL_UNDEFINED_VOID_FUNCTION,
ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
return (0);
}
int ssl_undefined_const_function(const SSL *s)
{
SSLerr(SSL_F_SSL_UNDEFINED_CONST_FUNCTION,
ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
return (0);
}
SSL_METHOD *ssl_bad_method(int ver)
{
SSLerr(SSL_F_SSL_BAD_METHOD, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
return (NULL);
}
const char *SSL_get_version(const SSL *s)
{
if (s->version == TLS1_2_VERSION)
return ("TLSv1.2");
else if (s->version == TLS1_1_VERSION)
return ("TLSv1.1");
else if (s->version == TLS1_VERSION)
return ("TLSv1");
else if (s->version == SSL3_VERSION)
return ("SSLv3");
else if (s->version == SSL2_VERSION)
return ("SSLv2");
else if (s->version == DTLS1_BAD_VER)
return ("DTLSv0.9");
else if (s->version == DTLS1_VERSION)
return ("DTLSv1");
else if (s->version == DTLS1_2_VERSION)
return ("DTLSv1.2");
else
return ("unknown");
}
SSL *SSL_dup(SSL *s)
{
STACK_OF(X509_NAME) *sk;
X509_NAME *xn;
SSL *ret;
int i;
if ((ret = SSL_new(SSL_get_SSL_CTX(s))) == NULL)
return (NULL);
ret->version = s->version;
ret->type = s->type;
ret->method = s->method;
if (s->session != NULL) {
/* This copies session-id, SSL_METHOD, sid_ctx, and 'cert' */
SSL_copy_session_id(ret, s);
} 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.
*/
ret->method->ssl_free(ret);
ret->method = s->method;
ret->method->ssl_new(ret);
if (s->cert != NULL) {
if (ret->cert != NULL) {
ssl_cert_free(ret->cert);
}
ret->cert = ssl_cert_dup(s->cert);
if (ret->cert == NULL)
goto err;
}
SSL_set_session_id_context(ret, s->sid_ctx, s->sid_ctx_length);
}
ret->options = s->options;
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));
ret->debug = s->debug;
/* copy app data, a little dangerous perhaps */
if (!CRYPTO_dup_ex_data(CRYPTO_EX_INDEX_SSL, &ret->ex_data, &s->ex_data))
goto err;
/* setup rbio, and wbio */
if (s->rbio != NULL) {
if (!BIO_dup_state(s->rbio, (char *)&ret->rbio))
goto err;
}
if (s->wbio != NULL) {
if (s->wbio != s->rbio) {
if (!BIO_dup_state(s->wbio, (char *)&ret->wbio))
goto err;
} else
ret->wbio = ret->rbio;
}
ret->rwstate = s->rwstate;
ret->in_handshake = s->in_handshake;
ret->handshake_func = s->handshake_func;
ret->server = s->server;
ret->renegotiate = s->renegotiate;
ret->new_session = s->new_session;
ret->quiet_shutdown = s->quiet_shutdown;
ret->shutdown = s->shutdown;
ret->state = s->state; /* SSL_dup does not really work at any state,
* though */
ret->rstate = s->rstate;
ret->init_num = 0; /* would have to copy ret->init_buf,
* ret->init_msg, ret->init_num,
* ret->init_off */
ret->hit = s->hit;
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 (s->client_CA != NULL) {
if ((sk = sk_X509_NAME_dup(s->client_CA)) == NULL)
goto err;
ret->client_CA = sk;
for (i = 0; i < sk_X509_NAME_num(sk); i++) {
xn = sk_X509_NAME_value(sk, i);
if (sk_X509_NAME_set(sk, i, X509_NAME_dup(xn)) == NULL) {
X509_NAME_free(xn);
goto err;
}
}
}
if (0) {
err:
if (ret != NULL)
SSL_free(ret);
ret = NULL;
}
return (ret);
}
void ssl_clear_cipher_ctx(SSL *s)
{
if (s->enc_read_ctx != NULL) {
EVP_CIPHER_CTX_cleanup(s->enc_read_ctx);
OPENSSL_free(s->enc_read_ctx);
s->enc_read_ctx = NULL;
}
if (s->enc_write_ctx != NULL) {
EVP_CIPHER_CTX_cleanup(s->enc_write_ctx);
OPENSSL_free(s->enc_write_ctx);
s->enc_write_ctx = NULL;
}
#ifndef OPENSSL_NO_COMP
if (s->expand != NULL) {
COMP_CTX_free(s->expand);
s->expand = NULL;
}
if (s->compress != 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);
}
#ifdef OPENSSL_NO_COMP
const COMP_METHOD *SSL_get_current_compression(SSL *s)
{
return NULL;
}
const COMP_METHOD *SSL_get_current_expansion(SSL *s)
{
return NULL;
}
#else
const COMP_METHOD *SSL_get_current_compression(SSL *s)
{
if (s->compress != NULL)
return (s->compress->meth);
return (NULL);
}
const COMP_METHOD *SSL_get_current_expansion(SSL *s)
{
if (s->expand != NULL)
return (s->expand->meth);
return (NULL);
}
#endif
int ssl_init_wbio_buffer(SSL *s, int push)
{
BIO *bbio;
if (s->bbio == NULL) {
bbio = BIO_new(BIO_f_buffer());
if (bbio == NULL)
return (0);
s->bbio = bbio;
} else {
bbio = s->bbio;
if (s->bbio == s->wbio)
s->wbio = BIO_pop(s->wbio);
}
(void)BIO_reset(bbio);
/* if (!BIO_set_write_buffer_size(bbio,16*1024)) */
if (!BIO_set_read_buffer_size(bbio, 1)) {
SSLerr(SSL_F_SSL_INIT_WBIO_BUFFER, ERR_R_BUF_LIB);
return (0);
}
if (push) {
if (s->wbio != bbio)
s->wbio = BIO_push(bbio, s->wbio);
} else {
if (s->wbio == bbio)
s->wbio = BIO_pop(bbio);
}
return (1);
}
void ssl_free_wbio_buffer(SSL *s)
{
if (s->bbio == NULL)
return;
if (s->bbio == s->wbio) {
/* remove buffering */
s->wbio = BIO_pop(s->wbio);
#ifdef REF_CHECK /* not the usual REF_CHECK, but this avoids
* adding one more preprocessor symbol */
assert(s->wbio != NULL);
#endif
}
BIO_free(s->bbio);
s->bbio = NULL;
}
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);
}
SSL_CTX *SSL_get_SSL_CTX(const SSL *ssl)
{
return (ssl->ctx);
}
SSL_CTX *SSL_set_SSL_CTX(SSL *ssl, SSL_CTX *ctx)
{
CERT *ocert = ssl->cert;
if (ssl->ctx == ctx)
return ssl->ctx;
#ifndef OPENSSL_NO_TLSEXT
if (ctx == NULL)
ctx = ssl->initial_ctx;
#endif
ssl->cert = ssl_cert_dup(ctx->cert);
if (ocert) {
int i;
/* Preserve any already negotiated parameters */
if (ssl->server) {
ssl->cert->peer_sigalgs = ocert->peer_sigalgs;
ssl->cert->peer_sigalgslen = ocert->peer_sigalgslen;
ocert->peer_sigalgs = NULL;
ssl->cert->ciphers_raw = ocert->ciphers_raw;
ssl->cert->ciphers_rawlen = ocert->ciphers_rawlen;
ocert->ciphers_raw = NULL;
}
for (i = 0; i < SSL_PKEY_NUM; i++) {
ssl->cert->pkeys[i].digest = ocert->pkeys[i].digest;
}
#ifndef OPENSSL_NO_TLSEXT
ssl->cert->alpn_proposed = ocert->alpn_proposed;
ssl->cert->alpn_proposed_len = ocert->alpn_proposed_len;
ocert->alpn_proposed = NULL;
ssl->cert->alpn_sent = ocert->alpn_sent;
if (!custom_exts_copy_flags(&ssl->cert->srv_ext, &ocert->srv_ext))
return NULL;
#endif
ssl_cert_free(ocert);
}
/*
* Program invariant: |sid_ctx| has fixed size (SSL_MAX_SID_CTX_LENGTH),
* so setter APIs must prevent invalid lengths from entering the system.
*/
OPENSSL_assert(ssl->sid_ctx_length <= sizeof(ssl->sid_ctx));
/*
* 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));
}
CRYPTO_add(&ctx->references, 1, CRYPTO_LOCK_SSL_CTX);
if (ssl->ctx != NULL)
SSL_CTX_free(ssl->ctx); /* decrement reference count */
ssl->ctx = ctx;
return (ssl->ctx);
}
#ifndef OPENSSL_NO_STDIO
int SSL_CTX_set_default_verify_paths(SSL_CTX *ctx)
{
return (X509_STORE_set_default_paths(ctx->cert_store));
}
int SSL_CTX_load_verify_locations(SSL_CTX *ctx, const char *CAfile,
const char *CApath)
{
return (X509_STORE_load_locations(ctx->cert_store, CAfile, CApath));
}
#endif
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;
}
int SSL_state(const SSL *ssl)
{
return (ssl->state);
}
void SSL_set_state(SSL *ssl, int state)
{
ssl->state = state;
}
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);
}
int SSL_get_ex_new_index(long argl, void *argp, CRYPTO_EX_new *new_func,
CRYPTO_EX_dup *dup_func, CRYPTO_EX_free *free_func)
{
return CRYPTO_get_ex_new_index(CRYPTO_EX_INDEX_SSL, argl, argp,
new_func, dup_func, free_func);
}
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_get_ex_new_index(long argl, void *argp, CRYPTO_EX_new *new_func,
CRYPTO_EX_dup *dup_func,
CRYPTO_EX_free *free_func)
{
return CRYPTO_get_ex_new_index(CRYPTO_EX_INDEX_SSL_CTX, argl, argp,
new_func, dup_func, free_func);
}
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));
}
int ssl_ok(SSL *s)
{
return (1);
}
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)
{
if (ctx->cert_store != NULL)
X509_STORE_free(ctx->cert_store);
ctx->cert_store = store;
}
int SSL_want(const SSL *s)
{
return (s->rwstate);
}
/**
* \brief Set the callback for generating temporary RSA keys.
* \param ctx the SSL context.
* \param cb the callback
*/
#ifndef OPENSSL_NO_RSA
void SSL_CTX_set_tmp_rsa_callback(SSL_CTX *ctx, RSA *(*cb) (SSL *ssl,
int is_export,
int keylength))
{
SSL_CTX_callback_ctrl(ctx, SSL_CTRL_SET_TMP_RSA_CB, (void (*)(void))cb);
}
void SSL_set_tmp_rsa_callback(SSL *ssl, RSA *(*cb) (SSL *ssl,
int is_export,
int keylength))
{
SSL_callback_ctrl(ssl, SSL_CTRL_SET_TMP_RSA_CB, (void (*)(void))cb);
}
#endif
#ifdef DOXYGEN
/**
* \brief The RSA temporary key callback function.
* \param ssl the SSL session.
* \param is_export \c TRUE if the temp RSA key is for an export ciphersuite.
* \param keylength if \c is_export is \c TRUE, then \c keylength is the size
* of the required key in bits.
* \return the temporary RSA key.
* \sa SSL_CTX_set_tmp_rsa_callback, SSL_set_tmp_rsa_callback
*/
RSA *cb(SSL *ssl, int is_export, int keylength)
{
}
#endif
/**
* \brief Set the callback for generating temporary DH keys.
* \param ctx the SSL context.
* \param dh the callback
*/
#ifndef OPENSSL_NO_DH
void SSL_CTX_set_tmp_dh_callback(SSL_CTX *ctx,
DH *(*dh) (SSL *ssl, int is_export,
int keylength))
{
SSL_CTX_callback_ctrl(ctx, SSL_CTRL_SET_TMP_DH_CB, (void (*)(void))dh);
}
void SSL_set_tmp_dh_callback(SSL *ssl, DH *(*dh) (SSL *ssl, int is_export,
int keylength))
{
SSL_callback_ctrl(ssl, SSL_CTRL_SET_TMP_DH_CB, (void (*)(void))dh);
}
#endif
#ifndef OPENSSL_NO_ECDH
void SSL_CTX_set_tmp_ecdh_callback(SSL_CTX *ctx,
EC_KEY *(*ecdh) (SSL *ssl, int is_export,
int keylength))
{
SSL_CTX_callback_ctrl(ctx, SSL_CTRL_SET_TMP_ECDH_CB,
(void (*)(void))ecdh);
}
void SSL_set_tmp_ecdh_callback(SSL *ssl,
EC_KEY *(*ecdh) (SSL *ssl, int is_export,
int keylength))
{
SSL_callback_ctrl(ssl, SSL_CTRL_SET_TMP_ECDH_CB, (void (*)(void))ecdh);
}
#endif
#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) {
SSLerr(SSL_F_SSL_CTX_USE_PSK_IDENTITY_HINT,
SSL_R_DATA_LENGTH_TOO_LONG);
return 0;
}
if (ctx->psk_identity_hint != NULL)
OPENSSL_free(ctx->psk_identity_hint);
if (identity_hint != NULL) {
ctx->psk_identity_hint = BUF_strdup(identity_hint);
if (ctx->psk_identity_hint == NULL)
return 0;
} else
ctx->psk_identity_hint = NULL;
return 1;
}
int SSL_use_psk_identity_hint(SSL *s, const char *identity_hint)
{
if (s == NULL)
return 0;
if (s->session == NULL)
return 1; /* session not created yet, ignored */
if (identity_hint != NULL && strlen(identity_hint) > PSK_MAX_IDENTITY_LEN) {
SSLerr(SSL_F_SSL_USE_PSK_IDENTITY_HINT, SSL_R_DATA_LENGTH_TOO_LONG);
return 0;
}
if (s->session->psk_identity_hint != NULL)
OPENSSL_free(s->session->psk_identity_hint);
if (identity_hint != NULL) {
s->session->psk_identity_hint = BUF_strdup(identity_hint);
if (s->session->psk_identity_hint == NULL)
return 0;
} else
s->session->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,
unsigned int (*cb) (SSL *ssl,
const char *hint,
char *identity,
unsigned int
max_identity_len,
unsigned char *psk,
unsigned int
max_psk_len))
{
s->psk_client_callback = cb;
}
void SSL_CTX_set_psk_client_callback(SSL_CTX *ctx,
unsigned int (*cb) (SSL *ssl,
const char *hint,
char *identity,
unsigned int
max_identity_len,
unsigned char *psk,
unsigned int
max_psk_len))
{
ctx->psk_client_callback = cb;
}
void SSL_set_psk_server_callback(SSL *s,
unsigned int (*cb) (SSL *ssl,
const char *identity,
unsigned char *psk,
unsigned int
max_psk_len))
{
s->psk_server_callback = cb;
}
void SSL_CTX_set_psk_server_callback(SSL_CTX *ctx,
unsigned int (*cb) (SSL *ssl,
const char *identity,
unsigned char *psk,
unsigned int
max_psk_len))
{
ctx->psk_server_callback = cb;
}
#endif
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);
}
/*
* Allocates new EVP_MD_CTX and sets pointer to it into given pointer
* vairable, freeing EVP_MD_CTX previously stored in that variable, if any.
* If EVP_MD pointer is passed, initializes ctx with this md Returns 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_create();
if (*hash == NULL || (md && EVP_DigestInit_ex(*hash, md, NULL) <= 0)) {
EVP_MD_CTX_destroy(*hash);
*hash = NULL;
return NULL;
}
return *hash;
}
void ssl_clear_hash_ctx(EVP_MD_CTX **hash)
{
if (*hash)
EVP_MD_CTX_destroy(*hash);
*hash = NULL;
}
void SSL_set_debug(SSL *s, int debug)
{
s->debug = debug;
}
int SSL_cache_hit(SSL *s)
{
return s->hit;
}
int SSL_is_server(SSL *s)
{
return s->server;
}
#if defined(_WINDLL) && defined(OPENSSL_SYS_WIN16)
# include "../crypto/bio/bss_file.c"
#endif
IMPLEMENT_STACK_OF(SSL_CIPHER)
IMPLEMENT_STACK_OF(SSL_COMP)
IMPLEMENT_OBJ_BSEARCH_GLOBAL_CMP_FN(SSL_CIPHER, SSL_CIPHER, ssl_cipher_id);
diff --git a/ssl/ssl_sess.c b/ssl/ssl_sess.c
index 23dd3e7a01c3..6a5ad5374bec 100644
--- a/ssl/ssl_sess.c
+++ b/ssl/ssl_sess.c
@@ -1,1289 +1,1289 @@
/* ssl/ssl_sess.c */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
/* ====================================================================
* Copyright (c) 1998-2006 The OpenSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* openssl-core@openssl.org.
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.openssl.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*
* This product includes cryptographic software written by Eric Young
* (eay@cryptsoft.com). This product includes software written by Tim
* Hudson (tjh@cryptsoft.com).
*
*/
/* ====================================================================
* Copyright 2005 Nokia. All rights reserved.
*
* The portions of the attached software ("Contribution") is developed by
* Nokia Corporation and is licensed pursuant to the OpenSSL open source
* license.
*
* The Contribution, originally written by Mika Kousa and Pasi Eronen of
* Nokia Corporation, consists of the "PSK" (Pre-Shared Key) ciphersuites
* support (see RFC 4279) to OpenSSL.
*
* No patent licenses or other rights except those expressly stated in
* the OpenSSL open source license shall be deemed granted or received
* expressly, by implication, estoppel, or otherwise.
*
* No assurances are provided by Nokia that the Contribution does not
* infringe the patent or other intellectual property rights of any third
* party or that the license provides you with all the necessary rights
* to make use of the Contribution.
*
* THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. IN
* ADDITION TO THE DISCLAIMERS INCLUDED IN THE LICENSE, NOKIA
* SPECIFICALLY DISCLAIMS ANY LIABILITY FOR CLAIMS BROUGHT BY YOU OR ANY
* OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS OR
* OTHERWISE.
*/
#include <stdio.h>
#include <openssl/lhash.h>
#include <openssl/rand.h>
#ifndef OPENSSL_NO_ENGINE
# include <openssl/engine.h>
#endif
#include "ssl_locl.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);
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.
*/
CRYPTO_w_lock(CRYPTO_LOCK_SSL_SESSION);
sess = ssl->session;
if (sess)
sess->references++;
CRYPTO_w_unlock(CRYPTO_LOCK_SSL_SESSION);
return (sess);
}
int SSL_SESSION_get_ex_new_index(long argl, void *argp,
CRYPTO_EX_new *new_func,
CRYPTO_EX_dup *dup_func,
CRYPTO_EX_free *free_func)
{
return CRYPTO_get_ex_new_index(CRYPTO_EX_INDEX_SSL_SESSION, argl, argp,
new_func, dup_func, free_func);
}
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;
ss = (SSL_SESSION *)OPENSSL_malloc(sizeof(SSL_SESSION));
if (ss == NULL) {
SSLerr(SSL_F_SSL_SESSION_NEW, ERR_R_MALLOC_FAILURE);
return (0);
}
memset(ss, 0, sizeof(SSL_SESSION));
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 = (unsigned long)time(NULL);
ss->prev = NULL;
ss->next = NULL;
ss->compress_meth = 0;
#ifndef OPENSSL_NO_TLSEXT
ss->tlsext_hostname = NULL;
# ifndef OPENSSL_NO_EC
ss->tlsext_ecpointformatlist_length = 0;
ss->tlsext_ecpointformatlist = NULL;
ss->tlsext_ellipticcurvelist_length = 0;
ss->tlsext_ellipticcurvelist = NULL;
# endif
#endif
CRYPTO_new_ex_data(CRYPTO_EX_INDEX_SSL_SESSION, ss, &ss->ex_data);
#ifndef OPENSSL_NO_PSK
ss->psk_identity_hint = NULL;
ss->psk_identity = NULL;
#endif
#ifndef OPENSSL_NO_SRP
ss->srp_username = NULL;
#endif
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.
*/
SSL_SESSION *ssl_session_dup(SSL_SESSION *src, int ticket)
{
SSL_SESSION *dest;
dest = OPENSSL_malloc(sizeof(*src));
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->ciphers = NULL;
#ifndef OPENSSL_NO_TLSEXT
dest->tlsext_hostname = NULL;
# ifndef OPENSSL_NO_EC
dest->tlsext_ecpointformatlist = NULL;
dest->tlsext_ellipticcurvelist = NULL;
# endif
dest->tlsext_tick = NULL;
#endif
#ifndef OPENSSL_NO_SRP
dest->srp_username = NULL;
#endif
/* We deliberately don't copy the prev and next pointers */
dest->prev = NULL;
dest->next = NULL;
dest->references = 1;
if (src->sess_cert != NULL)
CRYPTO_add(&src->sess_cert->references, 1, CRYPTO_LOCK_SSL_SESS_CERT);
if (src->peer != NULL)
CRYPTO_add(&src->peer->references, 1, CRYPTO_LOCK_X509);
if (!CRYPTO_new_ex_data(CRYPTO_EX_INDEX_SSL_SESSION, dest, &dest->ex_data))
goto err;
#ifndef OPENSSL_NO_PSK
if (src->psk_identity_hint) {
dest->psk_identity_hint = BUF_strdup(src->psk_identity_hint);
if (dest->psk_identity_hint == NULL) {
goto err;
}
}
if (src->psk_identity) {
dest->psk_identity = BUF_strdup(src->psk_identity);
if (dest->psk_identity == NULL) {
goto err;
}
}
#endif
if(src->ciphers != NULL) {
dest->ciphers = sk_SSL_CIPHER_dup(src->ciphers);
if (dest->ciphers == NULL)
goto err;
}
if (!CRYPTO_dup_ex_data(CRYPTO_EX_INDEX_SSL_SESSION,
&dest->ex_data, &src->ex_data)) {
goto err;
}
#ifndef OPENSSL_NO_TLSEXT
if (src->tlsext_hostname) {
dest->tlsext_hostname = BUF_strdup(src->tlsext_hostname);
if (dest->tlsext_hostname == NULL) {
goto err;
}
}
# ifndef OPENSSL_NO_EC
if (src->tlsext_ecpointformatlist) {
dest->tlsext_ecpointformatlist =
BUF_memdup(src->tlsext_ecpointformatlist,
src->tlsext_ecpointformatlist_length);
if (dest->tlsext_ecpointformatlist == NULL)
goto err;
}
if (src->tlsext_ellipticcurvelist) {
dest->tlsext_ellipticcurvelist =
BUF_memdup(src->tlsext_ellipticcurvelist,
src->tlsext_ellipticcurvelist_length);
if (dest->tlsext_ellipticcurvelist == NULL)
goto err;
}
# endif
if (ticket != 0 && src->tlsext_tick != NULL) {
dest->tlsext_tick = BUF_memdup(src->tlsext_tick, src->tlsext_ticklen);
if(dest->tlsext_tick == NULL)
goto err;
} else {
dest->tlsext_tick_lifetime_hint = 0;
dest->tlsext_ticklen = 0;
}
#endif
#ifndef OPENSSL_NO_SRP
if (src->srp_username) {
dest->srp_username = BUF_strdup(src->srp_username);
if (dest->srp_username == NULL) {
goto err;
}
}
#endif
return dest;
err:
SSLerr(SSL_F_SSL_SESSION_DUP, ERR_R_MALLOC_FAILURE);
SSL_SESSION_free(dest);
return NULL;
}
const unsigned char *SSL_SESSION_get_id(const SSL_SESSION *s,
unsigned int *len)
{
if (len)
*len = s->session_id_length;
return s->session_id;
}
unsigned int SSL_SESSION_get_compress_id(const SSL_SESSION *s)
{
return s->compress_meth;
}
/*
* Even with SSLv2, we have 16 bytes (128 bits) of session ID space.
* SSLv3/TLSv1 has 32 bytes (256 bits). As such, filling the ID with random
* gunk 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^128 (or 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(const SSL *ssl, unsigned char *id,
unsigned int *id_len)
{
unsigned int retry = 0;
do
if (RAND_bytes(id, *id_len) <= 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_get_new_session(SSL *s, int session)
{
/* This gets used by clients and servers. */
unsigned int tmp;
SSL_SESSION *ss = NULL;
GEN_SESSION_CB cb = def_generate_session_id;
if ((ss = SSL_SESSION_new()) == NULL)
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;
if (s->session != NULL) {
SSL_SESSION_free(s->session);
s->session = NULL;
}
if (session) {
if (s->version == SSL2_VERSION) {
ss->ssl_version = SSL2_VERSION;
ss->session_id_length = SSL2_SSL_SESSION_ID_LENGTH;
} else if (s->version == SSL3_VERSION) {
ss->ssl_version = SSL3_VERSION;
ss->session_id_length = SSL3_SSL_SESSION_ID_LENGTH;
} else if (s->version == TLS1_VERSION) {
ss->ssl_version = TLS1_VERSION;
ss->session_id_length = SSL3_SSL_SESSION_ID_LENGTH;
} else if (s->version == TLS1_1_VERSION) {
ss->ssl_version = TLS1_1_VERSION;
ss->session_id_length = SSL3_SSL_SESSION_ID_LENGTH;
} else if (s->version == TLS1_2_VERSION) {
ss->ssl_version = TLS1_2_VERSION;
ss->session_id_length = SSL3_SSL_SESSION_ID_LENGTH;
} else if (s->version == DTLS1_BAD_VER) {
ss->ssl_version = DTLS1_BAD_VER;
ss->session_id_length = SSL3_SSL_SESSION_ID_LENGTH;
} else if (s->version == DTLS1_VERSION) {
ss->ssl_version = DTLS1_VERSION;
ss->session_id_length = SSL3_SSL_SESSION_ID_LENGTH;
} else if (s->version == DTLS1_2_VERSION) {
ss->ssl_version = DTLS1_2_VERSION;
ss->session_id_length = SSL3_SSL_SESSION_ID_LENGTH;
} else {
SSLerr(SSL_F_SSL_GET_NEW_SESSION, SSL_R_UNSUPPORTED_SSL_VERSION);
SSL_SESSION_free(ss);
return (0);
}
#ifndef OPENSSL_NO_TLSEXT
/*-
* 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, s3_srvr.c calls
* ssl_get_new_session() in ssl3_get_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) s3_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->tlsext_ticket_expected) {
ss->session_id_length = 0;
goto sess_id_done;
}
#endif
/* Choose which callback will set the session ID */
CRYPTO_r_lock(CRYPTO_LOCK_SSL_CTX);
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_r_unlock(CRYPTO_LOCK_SSL_CTX);
/* Choose a session ID */
tmp = ss->session_id_length;
if (!cb(s, ss->session_id, &tmp)) {
/* The callback failed */
SSLerr(SSL_F_SSL_GET_NEW_SESSION,
SSL_R_SSL_SESSION_ID_CALLBACK_FAILED);
SSL_SESSION_free(ss);
return (0);
}
/*
* Don't allow the callback to set the session length to zero. nor
* set it higher than it was.
*/
if (!tmp || (tmp > ss->session_id_length)) {
/* The callback set an illegal length */
SSLerr(SSL_F_SSL_GET_NEW_SESSION,
SSL_R_SSL_SESSION_ID_HAS_BAD_LENGTH);
SSL_SESSION_free(ss);
return (0);
}
/* If the session length was shrunk and we're SSLv2, pad it */
if ((tmp < ss->session_id_length) && (s->version == SSL2_VERSION))
memset(ss->session_id + tmp, 0, ss->session_id_length - tmp);
else
ss->session_id_length = tmp;
/* Finally, check for a conflict */
if (SSL_has_matching_session_id(s, ss->session_id,
ss->session_id_length)) {
SSLerr(SSL_F_SSL_GET_NEW_SESSION, SSL_R_SSL_SESSION_ID_CONFLICT);
SSL_SESSION_free(ss);
return (0);
}
#ifndef OPENSSL_NO_TLSEXT
sess_id_done:
if (s->tlsext_hostname) {
ss->tlsext_hostname = BUF_strdup(s->tlsext_hostname);
if (ss->tlsext_hostname == NULL) {
SSLerr(SSL_F_SSL_GET_NEW_SESSION, ERR_R_INTERNAL_ERROR);
SSL_SESSION_free(ss);
return 0;
}
}
#endif
} else {
ss->session_id_length = 0;
}
- if (s->sid_ctx_length > sizeof ss->sid_ctx) {
+ if (s->sid_ctx_length > sizeof(ss->sid_ctx)) {
SSLerr(SSL_F_SSL_GET_NEW_SESSION, 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;
return (1);
}
/*-
* ssl_get_prev attempts to find an SSL_SESSION to be used to resume this
* connection. It is only called by servers.
*
* session_id: points at the session ID in the ClientHello. This code will
* read past the end of this in order to parse out the session ticket
* extension, if any.
* len: the length of the session ID.
* limit: a pointer to the first byte after the ClientHello.
*
* Returns:
* -1: error
* 0: 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->tlsext_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, unsigned char *session_id, int len,
const unsigned char *limit)
{
/* This is used only by servers. */
SSL_SESSION *ret = NULL;
int fatal = 0;
int try_session_cache = 1;
#ifndef OPENSSL_NO_TLSEXT
int r;
#endif
if (limit - session_id < len) {
fatal = 1;
goto err;
}
if (len == 0)
try_session_cache = 0;
#ifndef OPENSSL_NO_TLSEXT
/* sets s->tlsext_ticket_expected */
r = tls1_process_ticket(s, session_id, len, limit, &ret);
switch (r) {
case -1: /* Error during processing */
fatal = 1;
goto err;
case 0: /* No ticket found */
case 1: /* Zero length ticket found */
break; /* Ok to carry on processing session id. */
case 2: /* Ticket found but not decrypted. */
case 3: /* Ticket decrypted, *ret has been set. */
try_session_cache = 0;
break;
default:
abort();
}
#endif
if (try_session_cache &&
ret == NULL &&
!(s->session_ctx->session_cache_mode &
SSL_SESS_CACHE_NO_INTERNAL_LOOKUP)) {
SSL_SESSION data;
data.ssl_version = s->version;
data.session_id_length = len;
if (len == 0)
return 0;
memcpy(data.session_id, session_id, len);
CRYPTO_r_lock(CRYPTO_LOCK_SSL_CTX);
ret = lh_SSL_SESSION_retrieve(s->session_ctx->sessions, &data);
if (ret != NULL) {
/* don't allow other threads to steal it: */
CRYPTO_add(&ret->references, 1, CRYPTO_LOCK_SSL_SESSION);
}
CRYPTO_r_unlock(CRYPTO_LOCK_SSL_CTX);
if (ret == NULL)
s->session_ctx->stats.sess_miss++;
}
if (try_session_cache &&
ret == NULL && s->session_ctx->get_session_cb != NULL) {
int copy = 1;
if ((ret = s->session_ctx->get_session_cb(s, session_id, len, &copy))) {
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)
CRYPTO_add(&ret->references, 1, CRYPTO_LOCK_SSL_SESSION);
/*
* 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))
/*
* The following should not return 1, otherwise, things are
* very strange
*/
SSL_CTX_add_session(s->session_ctx, ret);
}
}
if (ret == NULL)
goto err;
/* Now ret is non-NULL and we own one of its reference counts. */
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).
*/
SSLerr(SSL_F_SSL_GET_PREV_SESSION,
SSL_R_SESSION_ID_CONTEXT_UNINITIALIZED);
fatal = 1;
goto err;
}
if (ret->cipher == NULL) {
unsigned char buf[5], *p;
unsigned long l;
p = buf;
l = ret->cipher_id;
l2n(l, p);
if ((ret->ssl_version >> 8) >= SSL3_VERSION_MAJOR)
ret->cipher = ssl_get_cipher_by_char(s, &(buf[2]));
else
ret->cipher = ssl_get_cipher_by_char(s, &(buf[1]));
if (ret->cipher == NULL)
goto err;
}
if (ret->timeout < (long)(time(NULL) - ret->time)) { /* timeout */
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;
}
s->session_ctx->stats.sess_hit++;
if (s->session != NULL)
SSL_SESSION_free(s->session);
s->session = ret;
s->verify_result = s->session->verify_result;
return 1;
err:
if (ret != NULL) {
SSL_SESSION_free(ret);
#ifndef OPENSSL_NO_TLSEXT
if (!try_session_cache) {
/*
* The session was from a ticket, so we should issue a ticket for
* the new session
*/
s->tlsext_ticket_expected = 1;
}
#endif
}
if (fatal)
return -1;
else
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
*/
CRYPTO_add(&c->references, 1, CRYPTO_LOCK_SSL_SESSION);
/*
* if session c is in already in cache, we take back the increment later
*/
CRYPTO_w_lock(CRYPTO_LOCK_SSL_CTX);
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;
}
/* Put at the head of the queue unless it is already in the cache */
if (s == NULL)
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;
} else {
/*
* new cache entry -- remove old ones if cache has become too large
*/
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
ctx->stats.sess_cache_full++;
}
}
}
CRYPTO_w_unlock(CRYPTO_LOCK_SSL_CTX);
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)
CRYPTO_w_lock(CRYPTO_LOCK_SSL_CTX);
if ((r = lh_SSL_SESSION_retrieve(ctx->sessions, c)) == c) {
ret = 1;
r = lh_SSL_SESSION_delete(ctx->sessions, c);
SSL_SESSION_list_remove(ctx, c);
}
if (lck)
CRYPTO_w_unlock(CRYPTO_LOCK_SSL_CTX);
if (ret) {
r->not_resumable = 1;
if (ctx->remove_session_cb != NULL)
ctx->remove_session_cb(ctx, r);
SSL_SESSION_free(r);
}
} else
ret = 0;
return (ret);
}
void SSL_SESSION_free(SSL_SESSION *ss)
{
int i;
if (ss == NULL)
return;
i = CRYPTO_add(&ss->references, -1, CRYPTO_LOCK_SSL_SESSION);
#ifdef REF_PRINT
REF_PRINT("SSL_SESSION", ss);
#endif
if (i > 0)
return;
#ifdef REF_CHECK
if (i < 0) {
fprintf(stderr, "SSL_SESSION_free, bad reference count\n");
abort(); /* ok */
}
#endif
CRYPTO_free_ex_data(CRYPTO_EX_INDEX_SSL_SESSION, ss, &ss->ex_data);
- OPENSSL_cleanse(ss->key_arg, sizeof ss->key_arg);
- OPENSSL_cleanse(ss->master_key, sizeof ss->master_key);
- OPENSSL_cleanse(ss->session_id, sizeof ss->session_id);
+ OPENSSL_cleanse(ss->key_arg, sizeof(ss->key_arg));
+ OPENSSL_cleanse(ss->master_key, sizeof(ss->master_key));
+ OPENSSL_cleanse(ss->session_id, sizeof(ss->session_id));
if (ss->sess_cert != NULL)
ssl_sess_cert_free(ss->sess_cert);
if (ss->peer != NULL)
X509_free(ss->peer);
if (ss->ciphers != NULL)
sk_SSL_CIPHER_free(ss->ciphers);
#ifndef OPENSSL_NO_TLSEXT
if (ss->tlsext_hostname != NULL)
OPENSSL_free(ss->tlsext_hostname);
if (ss->tlsext_tick != NULL)
OPENSSL_free(ss->tlsext_tick);
# ifndef OPENSSL_NO_EC
ss->tlsext_ecpointformatlist_length = 0;
if (ss->tlsext_ecpointformatlist != NULL)
OPENSSL_free(ss->tlsext_ecpointformatlist);
ss->tlsext_ellipticcurvelist_length = 0;
if (ss->tlsext_ellipticcurvelist != NULL)
OPENSSL_free(ss->tlsext_ellipticcurvelist);
# endif /* OPENSSL_NO_EC */
#endif
#ifndef OPENSSL_NO_PSK
if (ss->psk_identity_hint != NULL)
OPENSSL_free(ss->psk_identity_hint);
if (ss->psk_identity != NULL)
OPENSSL_free(ss->psk_identity);
#endif
#ifndef OPENSSL_NO_SRP
if (ss->srp_username != NULL)
OPENSSL_free(ss->srp_username);
#endif
OPENSSL_cleanse(ss, sizeof(*ss));
OPENSSL_free(ss);
}
int SSL_set_session(SSL *s, SSL_SESSION *session)
{
int ret = 0;
const SSL_METHOD *meth;
if (session != NULL) {
meth = s->ctx->method->get_ssl_method(session->ssl_version);
if (meth == NULL)
meth = s->method->get_ssl_method(session->ssl_version);
if (meth == NULL) {
SSLerr(SSL_F_SSL_SET_SESSION, SSL_R_UNABLE_TO_FIND_SSL_METHOD);
return (0);
}
if (meth != s->method) {
if (!SSL_set_ssl_method(s, meth))
return (0);
}
#ifndef OPENSSL_NO_KRB5
if (s->kssl_ctx && !s->kssl_ctx->client_princ &&
session->krb5_client_princ_len > 0) {
s->kssl_ctx->client_princ =
(char *)OPENSSL_malloc(session->krb5_client_princ_len + 1);
if (s->kssl_ctx->client_princ == NULL) {
SSLerr(SSL_F_SSL_SET_SESSION, ERR_R_MALLOC_FAILURE);
return 0;
}
memcpy(s->kssl_ctx->client_princ, session->krb5_client_princ,
session->krb5_client_princ_len);
s->kssl_ctx->client_princ[session->krb5_client_princ_len] = '\0';
}
#endif /* OPENSSL_NO_KRB5 */
/* CRYPTO_w_lock(CRYPTO_LOCK_SSL); */
CRYPTO_add(&session->references, 1, CRYPTO_LOCK_SSL_SESSION);
if (s->session != NULL)
SSL_SESSION_free(s->session);
s->session = session;
s->verify_result = s->session->verify_result;
/* CRYPTO_w_unlock(CRYPTO_LOCK_SSL); */
ret = 1;
} else {
if (s->session != NULL) {
SSL_SESSION_free(s->session);
s->session = NULL;
}
meth = s->ctx->method;
if (meth != s->method) {
if (!SSL_set_ssl_method(s, meth))
return (0);
}
ret = 1;
}
return (ret);
}
long SSL_SESSION_set_timeout(SSL_SESSION *s, long t)
{
if (s == NULL)
return (0);
s->timeout = t;
return (1);
}
long SSL_SESSION_get_timeout(const SSL_SESSION *s)
{
if (s == NULL)
return (0);
return (s->timeout);
}
long SSL_SESSION_get_time(const SSL_SESSION *s)
{
if (s == NULL)
return (0);
return (s->time);
}
long SSL_SESSION_set_time(SSL_SESSION *s, long t)
{
if (s == NULL)
return (0);
s->time = t;
return (t);
}
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) {
SSLerr(SSL_F_SSL_SESSION_SET1_ID_CONTEXT,
SSL_R_SSL_SESSION_ID_CONTEXT_TOO_LONG);
return 0;
}
s->sid_ctx_length = sid_ctx_len;
if (s->sid_ctx != sid_ctx)
memcpy(s->sid_ctx, sid_ctx, sid_ctx_len);
return 1;
}
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);
}
#ifndef OPENSSL_NO_TLSEXT
int SSL_set_session_secret_cb(SSL *s,
int (*tls_session_secret_cb) (SSL *s,
void *secret,
int *secret_len,
STACK_OF(SSL_CIPHER)
*peer_ciphers,
SSL_CIPHER
**cipher,
void *arg),
void *arg)
{
if (s == NULL)
return (0);
s->tls_session_secret_cb = tls_session_secret_cb;
s->tls_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->tls_session_ticket_ext_cb = cb;
s->tls_session_ticket_ext_cb_arg = arg;
return (1);
}
int SSL_set_session_ticket_ext(SSL *s, void *ext_data, int ext_len)
{
if (s->version >= TLS1_VERSION) {
if (s->tlsext_session_ticket) {
OPENSSL_free(s->tlsext_session_ticket);
s->tlsext_session_ticket = NULL;
}
s->tlsext_session_ticket =
OPENSSL_malloc(sizeof(TLS_SESSION_TICKET_EXT) + ext_len);
if (!s->tlsext_session_ticket) {
SSLerr(SSL_F_SSL_SET_SESSION_TICKET_EXT, ERR_R_MALLOC_FAILURE);
return 0;
}
if (ext_data) {
s->tlsext_session_ticket->length = ext_len;
s->tlsext_session_ticket->data = s->tlsext_session_ticket + 1;
memcpy(s->tlsext_session_ticket->data, ext_data, ext_len);
} else {
s->tlsext_session_ticket->length = 0;
s->tlsext_session_ticket->data = NULL;
}
return 1;
}
return 0;
}
#endif /* OPENSSL_NO_TLSEXT */
typedef struct timeout_param_st {
SSL_CTX *ctx;
long time;
LHASH_OF(SSL_SESSION) *cache;
} TIMEOUT_PARAM;
static void timeout_doall_arg(SSL_SESSION *s, TIMEOUT_PARAM *p)
{
if ((p->time == 0) || (p->time > (s->time + s->timeout))) { /* timeout */
/*
* The reason we don't call SSL_CTX_remove_session() is to save on
* locking overhead
*/
(void)lh_SSL_SESSION_delete(p->cache, s);
SSL_SESSION_list_remove(p->ctx, s);
s->not_resumable = 1;
if (p->ctx->remove_session_cb != NULL)
p->ctx->remove_session_cb(p->ctx, s);
SSL_SESSION_free(s);
}
}
static IMPLEMENT_LHASH_DOALL_ARG_FN(timeout, SSL_SESSION, TIMEOUT_PARAM)
void SSL_CTX_flush_sessions(SSL_CTX *s, long t)
{
unsigned long i;
TIMEOUT_PARAM tp;
tp.ctx = s;
tp.cache = s->sessions;
if (tp.cache == NULL)
return;
tp.time = t;
CRYPTO_w_lock(CRYPTO_LOCK_SSL_CTX);
i = CHECKED_LHASH_OF(SSL_SESSION, tp.cache)->down_load;
CHECKED_LHASH_OF(SSL_SESSION, tp.cache)->down_load = 0;
lh_SSL_SESSION_doall_arg(tp.cache, LHASH_DOALL_ARG_FN(timeout),
TIMEOUT_PARAM, &tp);
CHECKED_LHASH_OF(SSL_SESSION, tp.cache)->down_load = i;
CRYPTO_w_unlock(CRYPTO_LOCK_SSL_CTX);
}
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;
}
static void SSL_SESSION_list_add(SSL_CTX *ctx, SSL_SESSION *s)
{
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 {
s->next = ctx->session_cache_head;
s->next->prev = s;
s->prev = (SSL_SESSION *)&(ctx->session_cache_head);
ctx->session_cache_head = s;
}
}
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,
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,
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;
}
#ifndef OPENSSL_NO_ENGINE
int SSL_CTX_set_client_cert_engine(SSL_CTX *ctx, ENGINE *e)
{
if (!ENGINE_init(e)) {
SSLerr(SSL_F_SSL_CTX_SET_CLIENT_CERT_ENGINE, ERR_R_ENGINE_LIB);
return 0;
}
if (!ENGINE_get_ssl_client_cert_function(e)) {
SSLerr(SSL_F_SSL_CTX_SET_CLIENT_CERT_ENGINE,
SSL_R_NO_CLIENT_CERT_METHOD);
ENGINE_finish(e);
return 0;
}
ctx->client_cert_engine = e;
return 1;
}
#endif
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, unsigned char *cookie,
unsigned int cookie_len))
{
ctx->app_verify_cookie_cb = cb;
}
IMPLEMENT_PEM_rw(SSL_SESSION, SSL_SESSION, PEM_STRING_SSL_SESSION,
SSL_SESSION)
diff --git a/ssl/ssltest.c b/ssl/ssltest.c
index f6a8f195eeb7..b861e4956937 100644
--- a/ssl/ssltest.c
+++ b/ssl/ssltest.c
@@ -1,3370 +1,3370 @@
/* ssl/ssltest.c */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
/* ====================================================================
* Copyright (c) 1998-2000 The OpenSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* openssl-core@openssl.org.
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.openssl.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*
* This product includes cryptographic software written by Eric Young
* (eay@cryptsoft.com). This product includes software written by Tim
* Hudson (tjh@cryptsoft.com).
*
*/
/* ====================================================================
* Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
* ECC cipher suite support in OpenSSL originally developed by
* SUN MICROSYSTEMS, INC., and contributed to the OpenSSL project.
*/
/* ====================================================================
* Copyright 2005 Nokia. All rights reserved.
*
* The portions of the attached software ("Contribution") is developed by
* Nokia Corporation and is licensed pursuant to the OpenSSL open source
* license.
*
* The Contribution, originally written by Mika Kousa and Pasi Eronen of
* Nokia Corporation, consists of the "PSK" (Pre-Shared Key) ciphersuites
* support (see RFC 4279) to OpenSSL.
*
* No patent licenses or other rights except those expressly stated in
* the OpenSSL open source license shall be deemed granted or received
* expressly, by implication, estoppel, or otherwise.
*
* No assurances are provided by Nokia that the Contribution does not
* infringe the patent or other intellectual property rights of any third
* party or that the license provides you with all the necessary rights
* to make use of the Contribution.
*
* THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. IN
* ADDITION TO THE DISCLAIMERS INCLUDED IN THE LICENSE, NOKIA
* SPECIFICALLY DISCLAIMS ANY LIABILITY FOR CLAIMS BROUGHT BY YOU OR ANY
* OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS OR
* OTHERWISE.
*/
/* Or gethostname won't be declared properly on Linux and GNU platforms. */
#define _BSD_SOURCE 1
#define _DEFAULT_SOURCE 1
#include <assert.h>
#include <errno.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#define USE_SOCKETS
#include "e_os.h"
#ifdef OPENSSL_SYS_VMS
/*
* Or isascii won't be declared properly on VMS (at least with DECompHP C).
*/
# define _XOPEN_SOURCE 500
#endif
#include <ctype.h>
#include <openssl/bio.h>
#include <openssl/crypto.h>
#include <openssl/evp.h>
#include <openssl/x509.h>
#include <openssl/x509v3.h>
#include <openssl/ssl.h>
#ifndef OPENSSL_NO_ENGINE
# include <openssl/engine.h>
#endif
#include <openssl/err.h>
#include <openssl/rand.h>
#ifndef OPENSSL_NO_RSA
# include <openssl/rsa.h>
#endif
#ifndef OPENSSL_NO_DSA
# include <openssl/dsa.h>
#endif
#ifndef OPENSSL_NO_DH
# include <openssl/dh.h>
#endif
#ifndef OPENSSL_NO_SRP
# include <openssl/srp.h>
#endif
#include <openssl/bn.h>
/*
* Or gethostname won't be declared properly
* on Compaq platforms (at least with DEC C).
* Do not try to put it earlier, or IPv6 includes
* get screwed...
*/
#define _XOPEN_SOURCE_EXTENDED 1
#ifdef OPENSSL_SYS_WINDOWS
# include <winsock.h>
#else
# include OPENSSL_UNISTD
#endif
#ifdef OPENSSL_SYS_VMS
# define TEST_SERVER_CERT "SYS$DISK:[-.APPS]SERVER.PEM"
# define TEST_CLIENT_CERT "SYS$DISK:[-.APPS]CLIENT.PEM"
#elif defined(OPENSSL_SYS_WINCE)
# define TEST_SERVER_CERT "\\OpenSSL\\server.pem"
# define TEST_CLIENT_CERT "\\OpenSSL\\client.pem"
#elif defined(OPENSSL_SYS_NETWARE)
# define TEST_SERVER_CERT "\\openssl\\apps\\server.pem"
# define TEST_CLIENT_CERT "\\openssl\\apps\\client.pem"
#else
# define TEST_SERVER_CERT "../apps/server.pem"
# define TEST_CLIENT_CERT "../apps/client.pem"
#endif
static SSL_CTX *s_ctx = NULL;
static SSL_CTX *s_ctx2 = NULL;
/*
* There is really no standard for this, so let's assign some tentative
* numbers. In any case, these numbers are only for this test
*/
#define COMP_RLE 255
#define COMP_ZLIB 1
static int MS_CALLBACK verify_callback(int ok, X509_STORE_CTX *ctx);
#ifndef OPENSSL_NO_RSA
static RSA MS_CALLBACK *tmp_rsa_cb(SSL *s, int is_export, int keylength);
static void free_tmp_rsa(void);
#endif
static int MS_CALLBACK app_verify_callback(X509_STORE_CTX *ctx, void *arg);
#define APP_CALLBACK_STRING "Test Callback Argument"
struct app_verify_arg {
char *string;
int app_verify;
int allow_proxy_certs;
char *proxy_auth;
char *proxy_cond;
};
#ifndef OPENSSL_NO_DH
static DH *get_dh512(void);
static DH *get_dh1024(void);
static DH *get_dh1024dsa(void);
#endif
static char *psk_key = NULL; /* by default PSK is not used */
#ifndef OPENSSL_NO_PSK
static unsigned int psk_client_callback(SSL *ssl, const char *hint,
char *identity,
unsigned int max_identity_len,
unsigned char *psk,
unsigned int max_psk_len);
static unsigned int psk_server_callback(SSL *ssl, const char *identity,
unsigned char *psk,
unsigned int max_psk_len);
#endif
#ifndef OPENSSL_NO_SRP
/* SRP client */
/* This is a context that we pass to all callbacks */
typedef struct srp_client_arg_st {
char *srppassin;
char *srplogin;
} SRP_CLIENT_ARG;
# define PWD_STRLEN 1024
static char *MS_CALLBACK ssl_give_srp_client_pwd_cb(SSL *s, void *arg)
{
SRP_CLIENT_ARG *srp_client_arg = (SRP_CLIENT_ARG *)arg;
return BUF_strdup((char *)srp_client_arg->srppassin);
}
/* SRP server */
/* This is a context that we pass to SRP server callbacks */
typedef struct srp_server_arg_st {
char *expected_user;
char *pass;
} SRP_SERVER_ARG;
static int MS_CALLBACK ssl_srp_server_param_cb(SSL *s, int *ad, void *arg)
{
SRP_SERVER_ARG *p = (SRP_SERVER_ARG *)arg;
if (strcmp(p->expected_user, SSL_get_srp_username(s)) != 0) {
fprintf(stderr, "User %s doesn't exist\n", SSL_get_srp_username(s));
return SSL3_AL_FATAL;
}
if (SSL_set_srp_server_param_pw(s, p->expected_user, p->pass, "1024") < 0) {
*ad = SSL_AD_INTERNAL_ERROR;
return SSL3_AL_FATAL;
}
return SSL_ERROR_NONE;
}
#endif
static BIO *bio_err = NULL;
static BIO *bio_stdout = NULL;
static const char *alpn_client;
static char *alpn_server;
static char *alpn_server2;
static const char *alpn_expected;
static unsigned char *alpn_selected;
static const char *sn_client;
static const char *sn_server1;
static const char *sn_server2;
static int sn_expect = 0;
static int s_ticket1 = 0;
static int s_ticket2 = 0;
static int c_ticket = 0;
static int ticket_expect = -1;
static int sni_in_cert_cb = 0;
static const char *client_sigalgs = NULL;
static const char *server_digest_expect = NULL;
static int servername_cb(SSL *s, int *ad, void *arg)
{
const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
if (sn_server2 == NULL) {
BIO_printf(bio_stdout, "Servername 2 is NULL\n");
return SSL_TLSEXT_ERR_NOACK;
}
if (servername != NULL) {
if (s_ctx2 != NULL && sn_server2 != NULL &&
!strcasecmp(servername, sn_server2)) {
BIO_printf(bio_stdout, "Switching server context.\n");
SSL_set_SSL_CTX(s, s_ctx2);
/* Copy over all the SSL_CTX options */
SSL_clear_options(s, 0xFFFFFFFFL);
SSL_set_options(s, SSL_CTX_get_options(s_ctx2));
}
}
return SSL_TLSEXT_ERR_OK;
}
static int verify_servername(SSL *client, SSL *server)
{
/* just need to see if sn_context is what we expect */
SSL_CTX* ctx = SSL_get_SSL_CTX(server);
if (sn_expect == 0)
return 0;
if (sn_expect == 1 && ctx == s_ctx)
return 0;
if (sn_expect == 2 && ctx == s_ctx2)
return 0;
BIO_printf(bio_stdout, "Servername: expected context %d\n", sn_expect);
if (ctx == s_ctx2)
BIO_printf(bio_stdout, "Servername: context is 2\n");
else if (ctx == s_ctx)
BIO_printf(bio_stdout, "Servername: context is 1\n");
else
BIO_printf(bio_stdout, "Servername: context is unknown\n");
return -1;
}
static int cert_cb(SSL *ssl, void *arg)
{
int unused;
return servername_cb(ssl, &unused, NULL) != SSL_TLSEXT_ERR_ALERT_FATAL;
}
static int verify_ticket(SSL* ssl)
{
if (ticket_expect == -1)
return 0;
if (ticket_expect == 0 &&
(ssl->session->tlsext_tick == NULL ||
ssl->session->tlsext_ticklen == 0))
return 1;
if (ticket_expect == 1 &&
(ssl->session->tlsext_tick != NULL &&
ssl->session->tlsext_ticklen != 0))
return 1;
return -1;
}
static int verify_server_digest(SSL* ssl)
{
int nid = NID_undef;
if (server_digest_expect == NULL)
return 0;
SSL_get_peer_signature_nid(ssl, &nid);
if (strcmp(server_digest_expect, OBJ_nid2sn(nid)) == 0)
return 1;
BIO_printf(bio_stdout, "Expected server digest %s, got %s.\n",
server_digest_expect, OBJ_nid2sn(nid));
return -1;
}
/*-
* next_protos_parse parses a comma separated list of strings into a string
* in a format suitable for passing to SSL_CTX_set_next_protos_advertised.
* outlen: (output) set to the length of the resulting buffer on success.
* err: (maybe NULL) on failure, an error message line is written to this BIO.
* in: a NUL terminated string like "abc,def,ghi"
*
* returns: a malloced buffer or NULL on failure.
*/
static unsigned char *next_protos_parse(unsigned short *outlen,
const char *in)
{
size_t len;
unsigned char *out;
size_t i, start = 0;
len = strlen(in);
if (len >= 65535)
return NULL;
out = OPENSSL_malloc(strlen(in) + 1);
if (!out)
return NULL;
for (i = 0; i <= len; ++i) {
if (i == len || in[i] == ',') {
if (i - start > 255) {
OPENSSL_free(out);
return NULL;
}
out[start] = (unsigned char)(i - start);
start = i + 1;
} else
out[i + 1] = in[i];
}
*outlen = (unsigned char)(len + 1);
return out;
}
static int cb_server_alpn(SSL *s, const unsigned char **out,
unsigned char *outlen, const unsigned char *in,
unsigned int inlen, void *arg)
{
unsigned char *protos;
unsigned short protos_len;
char* alpn_str = arg;
protos = next_protos_parse(&protos_len, alpn_str);
if (protos == NULL) {
fprintf(stderr, "failed to parser ALPN server protocol string: %s\n",
alpn_str);
abort();
}
if (SSL_select_next_proto
((unsigned char **)out, outlen, protos, protos_len, in,
inlen) != OPENSSL_NPN_NEGOTIATED) {
OPENSSL_free(protos);
return SSL_TLSEXT_ERR_NOACK;
}
/*
* Make a copy of the selected protocol which will be freed in
* verify_alpn.
*/
alpn_selected = OPENSSL_malloc(*outlen);
memcpy(alpn_selected, *out, *outlen);
*out = alpn_selected;
OPENSSL_free(protos);
return SSL_TLSEXT_ERR_OK;
}
static int verify_alpn(SSL *client, SSL *server)
{
const unsigned char *client_proto, *server_proto;
unsigned int client_proto_len = 0, server_proto_len = 0;
SSL_get0_alpn_selected(client, &client_proto, &client_proto_len);
SSL_get0_alpn_selected(server, &server_proto, &server_proto_len);
if (alpn_selected != NULL) {
OPENSSL_free(alpn_selected);
alpn_selected = NULL;
}
if (client_proto_len != server_proto_len ||
memcmp(client_proto, server_proto, client_proto_len) != 0) {
BIO_printf(bio_stdout, "ALPN selected protocols differ!\n");
goto err;
}
if (client_proto_len > 0 && alpn_expected == NULL) {
BIO_printf(bio_stdout, "ALPN unexpectedly negotiated\n");
goto err;
}
if (alpn_expected != NULL &&
(client_proto_len != strlen(alpn_expected) ||
memcmp(client_proto, alpn_expected, client_proto_len) != 0)) {
BIO_printf(bio_stdout,
"ALPN selected protocols not equal to expected protocol: %s\n",
alpn_expected);
goto err;
}
return 0;
err:
BIO_printf(bio_stdout, "ALPN results: client: '");
BIO_write(bio_stdout, client_proto, client_proto_len);
BIO_printf(bio_stdout, "', server: '");
BIO_write(bio_stdout, server_proto, server_proto_len);
BIO_printf(bio_stdout, "'\n");
BIO_printf(bio_stdout, "ALPN configured: client: '%s', server: ",
alpn_client);
if (SSL_get_SSL_CTX(server) == s_ctx2) {
BIO_printf(bio_stdout, "'%s'\n",
alpn_server2);
} else if (SSL_get_SSL_CTX(server) == s_ctx){
BIO_printf(bio_stdout, "'%s'\n",
alpn_server);
} else {
BIO_printf(bio_stdout, "unknown\n");
}
return -1;
}
#ifndef OPENSSL_NO_TLSEXT
static int cb_ticket0(SSL* s, unsigned char* key_name, unsigned char *iv, EVP_CIPHER_CTX *ctx, HMAC_CTX *hctx, int enc)
{
return 0;
}
static int cb_ticket1(SSL* s, unsigned char* key_name, unsigned char *iv, EVP_CIPHER_CTX *ctx, HMAC_CTX *hctx, int enc)
{
static unsigned char key[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 };
static char name[] = "ticket11ticket11";
if (SSL_get_options(s) & SSL_OP_NO_TICKET)
return 0;
if (enc) {
RAND_pseudo_bytes(iv, EVP_MAX_IV_LENGTH);
EVP_EncryptInit_ex(ctx, EVP_aes_128_cbc(), NULL, key, iv);
HMAC_Init_ex(hctx, key, sizeof(key), EVP_sha1(), NULL);
memcpy(key_name, name, 16);
return 1;
} else {
if (memcmp(key_name, name, 16) == 0) {
EVP_DecryptInit_ex(ctx, EVP_aes_128_cbc(), NULL, key, iv);
HMAC_Init_ex(hctx, key, sizeof(key), EVP_sha1(), NULL);
return 1;
}
}
return 0;
}
static int cb_ticket2(SSL* s, unsigned char* key_name, unsigned char *iv, EVP_CIPHER_CTX *ctx, HMAC_CTX *hctx, int enc)
{
fprintf(stderr, "ticket callback for SNI context should never be called\n");
EXIT(1);
return 0;
}
#endif
#define SCT_EXT_TYPE 18
/*
* WARNING : below extension types are *NOT* IETF assigned, and could
* conflict if these types are reassigned and handled specially by OpenSSL
* in the future
*/
#define TACK_EXT_TYPE 62208
#define CUSTOM_EXT_TYPE_0 1000
#define CUSTOM_EXT_TYPE_1 1001
#define CUSTOM_EXT_TYPE_2 1002
#define CUSTOM_EXT_TYPE_3 1003
const char custom_ext_cli_string[] = "abc";
const char custom_ext_srv_string[] = "defg";
/* These set from cmdline */
char *serverinfo_file = NULL;
int serverinfo_sct = 0;
int serverinfo_tack = 0;
/* These set based on extension callbacks */
int serverinfo_sct_seen = 0;
int serverinfo_tack_seen = 0;
int serverinfo_other_seen = 0;
/* This set from cmdline */
int custom_ext = 0;
/* This set based on extension callbacks */
int custom_ext_error = 0;
static int serverinfo_cli_parse_cb(SSL *s, unsigned int ext_type,
const unsigned char *in, size_t inlen,
int *al, void *arg)
{
if (ext_type == SCT_EXT_TYPE)
serverinfo_sct_seen++;
else if (ext_type == TACK_EXT_TYPE)
serverinfo_tack_seen++;
else
serverinfo_other_seen++;
return 1;
}
static int verify_serverinfo()
{
if (serverinfo_sct != serverinfo_sct_seen)
return -1;
if (serverinfo_tack != serverinfo_tack_seen)
return -1;
if (serverinfo_other_seen)
return -1;
return 0;
}
/*-
* Four test cases for custom extensions:
* 0 - no ClientHello extension or ServerHello response
* 1 - ClientHello with "abc", no response
* 2 - ClientHello with "abc", empty response
* 3 - ClientHello with "abc", "defg" response
*/
static int custom_ext_0_cli_add_cb(SSL *s, unsigned int ext_type,
const unsigned char **out,
size_t *outlen, int *al, void *arg)
{
if (ext_type != CUSTOM_EXT_TYPE_0)
custom_ext_error = 1;
return 0; /* Don't send an extension */
}
static int custom_ext_0_cli_parse_cb(SSL *s, unsigned int ext_type,
const unsigned char *in,
size_t inlen, int *al, void *arg)
{
return 1;
}
static int custom_ext_1_cli_add_cb(SSL *s, unsigned int ext_type,
const unsigned char **out,
size_t *outlen, int *al, void *arg)
{
if (ext_type != CUSTOM_EXT_TYPE_1)
custom_ext_error = 1;
*out = (const unsigned char *)custom_ext_cli_string;
*outlen = strlen(custom_ext_cli_string);
return 1; /* Send "abc" */
}
static int custom_ext_1_cli_parse_cb(SSL *s, unsigned int ext_type,
const unsigned char *in,
size_t inlen, int *al, void *arg)
{
return 1;
}
static int custom_ext_2_cli_add_cb(SSL *s, unsigned int ext_type,
const unsigned char **out,
size_t *outlen, int *al, void *arg)
{
if (ext_type != CUSTOM_EXT_TYPE_2)
custom_ext_error = 1;
*out = (const unsigned char *)custom_ext_cli_string;
*outlen = strlen(custom_ext_cli_string);
return 1; /* Send "abc" */
}
static int custom_ext_2_cli_parse_cb(SSL *s, unsigned int ext_type,
const unsigned char *in,
size_t inlen, int *al, void *arg)
{
if (ext_type != CUSTOM_EXT_TYPE_2)
custom_ext_error = 1;
if (inlen != 0)
custom_ext_error = 1; /* Should be empty response */
return 1;
}
static int custom_ext_3_cli_add_cb(SSL *s, unsigned int ext_type,
const unsigned char **out,
size_t *outlen, int *al, void *arg)
{
if (ext_type != CUSTOM_EXT_TYPE_3)
custom_ext_error = 1;
*out = (const unsigned char *)custom_ext_cli_string;
*outlen = strlen(custom_ext_cli_string);
return 1; /* Send "abc" */
}
static int custom_ext_3_cli_parse_cb(SSL *s, unsigned int ext_type,
const unsigned char *in,
size_t inlen, int *al, void *arg)
{
if (ext_type != CUSTOM_EXT_TYPE_3)
custom_ext_error = 1;
if (inlen != strlen(custom_ext_srv_string))
custom_ext_error = 1;
if (memcmp(custom_ext_srv_string, in, inlen) != 0)
custom_ext_error = 1; /* Check for "defg" */
return 1;
}
/*
* custom_ext_0_cli_add_cb returns 0 - the server won't receive a callback
* for this extension
*/
static int custom_ext_0_srv_parse_cb(SSL *s, unsigned int ext_type,
const unsigned char *in,
size_t inlen, int *al, void *arg)
{
custom_ext_error = 1;
return 1;
}
/* 'add' callbacks are only called if the 'parse' callback is called */
static int custom_ext_0_srv_add_cb(SSL *s, unsigned int ext_type,
const unsigned char **out,
size_t *outlen, int *al, void *arg)
{
/* Error: should not have been called */
custom_ext_error = 1;
return 0; /* Don't send an extension */
}
static int custom_ext_1_srv_parse_cb(SSL *s, unsigned int ext_type,
const unsigned char *in,
size_t inlen, int *al, void *arg)
{
if (ext_type != CUSTOM_EXT_TYPE_1)
custom_ext_error = 1;
/* Check for "abc" */
if (inlen != strlen(custom_ext_cli_string))
custom_ext_error = 1;
if (memcmp(in, custom_ext_cli_string, inlen) != 0)
custom_ext_error = 1;
return 1;
}
static int custom_ext_1_srv_add_cb(SSL *s, unsigned int ext_type,
const unsigned char **out,
size_t *outlen, int *al, void *arg)
{
return 0; /* Don't send an extension */
}
static int custom_ext_2_srv_parse_cb(SSL *s, unsigned int ext_type,
const unsigned char *in,
size_t inlen, int *al, void *arg)
{
if (ext_type != CUSTOM_EXT_TYPE_2)
custom_ext_error = 1;
/* Check for "abc" */
if (inlen != strlen(custom_ext_cli_string))
custom_ext_error = 1;
if (memcmp(in, custom_ext_cli_string, inlen) != 0)
custom_ext_error = 1;
return 1;
}
static int custom_ext_2_srv_add_cb(SSL *s, unsigned int ext_type,
const unsigned char **out,
size_t *outlen, int *al, void *arg)
{
*out = NULL;
*outlen = 0;
return 1; /* Send empty extension */
}
static int custom_ext_3_srv_parse_cb(SSL *s, unsigned int ext_type,
const unsigned char *in,
size_t inlen, int *al, void *arg)
{
if (ext_type != CUSTOM_EXT_TYPE_3)
custom_ext_error = 1;
/* Check for "abc" */
if (inlen != strlen(custom_ext_cli_string))
custom_ext_error = 1;
if (memcmp(in, custom_ext_cli_string, inlen) != 0)
custom_ext_error = 1;
return 1;
}
static int custom_ext_3_srv_add_cb(SSL *s, unsigned int ext_type,
const unsigned char **out,
size_t *outlen, int *al, void *arg)
{
*out = (const unsigned char *)custom_ext_srv_string;
*outlen = strlen(custom_ext_srv_string);
return 1; /* Send "defg" */
}
static char *cipher = NULL;
static int verbose = 0;
static int debug = 0;
#if 0
/* Not used yet. */
# ifdef FIONBIO
static int s_nbio = 0;
# endif
#endif
static const char rnd_seed[] =
"string to make the random number generator think it has entropy";
int doit_biopair(SSL *s_ssl, SSL *c_ssl, long bytes, clock_t *s_time,
clock_t *c_time);
int doit(SSL *s_ssl, SSL *c_ssl, long bytes);
static int do_test_cipherlist(void);
static void sv_usage(void)
{
fprintf(stderr, "usage: ssltest [args ...]\n");
fprintf(stderr, "\n");
#ifdef OPENSSL_FIPS
fprintf(stderr, "-F - run test in FIPS mode\n");
#endif
fprintf(stderr, " -server_auth - check server certificate\n");
fprintf(stderr, " -client_auth - do client authentication\n");
fprintf(stderr, " -proxy - allow proxy certificates\n");
fprintf(stderr, " -proxy_auth <val> - set proxy policy rights\n");
fprintf(stderr,
" -proxy_cond <val> - expression to test proxy policy rights\n");
fprintf(stderr, " -v - more output\n");
fprintf(stderr, " -d - debug output\n");
fprintf(stderr, " -reuse - use session-id reuse\n");
fprintf(stderr, " -num <val> - number of connections to perform\n");
fprintf(stderr,
" -bytes <val> - number of bytes to swap between client/server\n");
#ifndef OPENSSL_NO_DH
fprintf(stderr,
" -dhe512 - use 512 bit key for DHE (to test failure)\n");
fprintf(stderr,
" -dhe1024 - use 1024 bit key (safe prime) for DHE (default, no-op)\n");
fprintf(stderr,
" -dhe1024dsa - use 1024 bit key (with 160-bit subprime) for DHE\n");
fprintf(stderr, " -no_dhe - disable DHE\n");
#endif
#ifndef OPENSSL_NO_ECDH
fprintf(stderr, " -no_ecdhe - disable ECDHE\n");
#endif
#ifndef OPENSSL_NO_PSK
fprintf(stderr, " -psk arg - PSK in hex (without 0x)\n");
#endif
#ifndef OPENSSL_NO_SRP
fprintf(stderr, " -srpuser user - SRP username to use\n");
fprintf(stderr, " -srppass arg - password for 'user'\n");
#endif
#ifndef OPENSSL_NO_SSL2
fprintf(stderr, " -ssl2 - use SSLv2\n");
#endif
#ifndef OPENSSL_NO_SSL3_METHOD
fprintf(stderr, " -ssl3 - use SSLv3\n");
#endif
#ifndef OPENSSL_NO_TLS1
fprintf(stderr, " -tls1 - use TLSv1\n");
fprintf(stderr, " -tls12 - use TLSv1.2\n");
#endif
#ifndef OPENSSL_NO_DTLS
fprintf(stderr, " -dtls1 - use DTLSv1\n");
fprintf(stderr, " -dtls12 - use DTLSv1.2\n");
#endif
fprintf(stderr, " -CApath arg - PEM format directory of CA's\n");
fprintf(stderr, " -CAfile arg - PEM format file of CA's\n");
fprintf(stderr, " -cert arg - Server certificate file\n");
fprintf(stderr,
" -key arg - Server key file (default: same as -cert)\n");
fprintf(stderr, " -c_cert arg - Client certificate file\n");
fprintf(stderr,
" -c_key arg - Client key file (default: same as -c_cert)\n");
fprintf(stderr, " -cipher arg - The cipher list\n");
fprintf(stderr, " -bio_pair - Use BIO pairs\n");
fprintf(stderr, " -f - Test even cases that can't work\n");
fprintf(stderr,
" -time - measure processor time used by client and server\n");
fprintf(stderr, " -zlib - use zlib compression\n");
fprintf(stderr, " -rle - use rle compression\n");
#ifndef OPENSSL_NO_ECDH
fprintf(stderr,
" -named_curve arg - Elliptic curve name to use for ephemeral ECDH keys.\n"
" Use \"openssl ecparam -list_curves\" for all names\n"
" (default is sect163r2).\n");
#endif
fprintf(stderr,
" -test_cipherlist - Verifies the order of the ssl cipher lists.\n"
" When this option is requested, the cipherlist\n"
" tests are run instead of handshake tests.\n");
fprintf(stderr, " -serverinfo_file file - have server use this file\n");
fprintf(stderr, " -serverinfo_sct - have client offer and expect SCT\n");
fprintf(stderr,
" -serverinfo_tack - have client offer and expect TACK\n");
fprintf(stderr,
" -custom_ext - try various custom extension callbacks\n");
fprintf(stderr, " -alpn_client <string> - have client side offer ALPN\n");
fprintf(stderr, " -alpn_server <string> - have server side offer ALPN\n");
fprintf(stderr, " -alpn_server1 <string> - alias for -alpn_server\n");
fprintf(stderr, " -alpn_server2 <string> - have server side context 2 offer ALPN\n");
fprintf(stderr,
" -alpn_expected <string> - the ALPN protocol that should be negotiated\n");
fprintf(stderr, " -sn_client <string> - have client request this servername\n");
fprintf(stderr, " -sn_server1 <string> - have server context 1 respond to this servername\n");
fprintf(stderr, " -sn_server2 <string> - have server context 2 respond to this servername\n");
fprintf(stderr, " -sn_expect1 - expected server 1\n");
fprintf(stderr, " -sn_expect2 - expected server 2\n");
#ifndef OPENSSL_NO_TLSEXT
fprintf(stderr, " -s_ticket1 <yes|no|broken> - enable/disable session tickets on context 1\n");
fprintf(stderr, " -s_ticket2 <yes|no> - enable/disable session tickets on context 2\n");
fprintf(stderr, " -c_ticket <yes|no> - enable/disable session tickets on the client\n");
fprintf(stderr, " -ticket_expect <yes|no> - indicate that the client should (or should not) have a ticket\n");
#endif
fprintf(stderr, " -sni_in_cert_cb - have the server handle SNI in the certificate callback\n");
fprintf(stderr, " -client_sigalgs arg - the signature algorithms to configure on the client\n");
fprintf(stderr, " -server_digest_expect arg - the expected server signing digest\n");
}
static void print_details(SSL *c_ssl, const char *prefix)
{
const SSL_CIPHER *ciph;
X509 *cert;
ciph = SSL_get_current_cipher(c_ssl);
BIO_printf(bio_stdout, "%s%s, cipher %s %s",
prefix,
SSL_get_version(c_ssl),
SSL_CIPHER_get_version(ciph), SSL_CIPHER_get_name(ciph));
cert = SSL_get_peer_certificate(c_ssl);
if (cert != NULL) {
EVP_PKEY *pkey = X509_get_pubkey(cert);
if (pkey != NULL) {
if (0) ;
#ifndef OPENSSL_NO_RSA
else if (pkey->type == EVP_PKEY_RSA && pkey->pkey.rsa != NULL
&& pkey->pkey.rsa->n != NULL) {
BIO_printf(bio_stdout, ", %d bit RSA",
BN_num_bits(pkey->pkey.rsa->n));
}
#endif
#ifndef OPENSSL_NO_DSA
else if (pkey->type == EVP_PKEY_DSA && pkey->pkey.dsa != NULL
&& pkey->pkey.dsa->p != NULL) {
BIO_printf(bio_stdout, ", %d bit DSA",
BN_num_bits(pkey->pkey.dsa->p));
}
#endif
EVP_PKEY_free(pkey);
}
X509_free(cert);
}
/*
* The SSL API does not allow us to look at temporary RSA/DH keys,
* otherwise we should print their lengths too
*/
BIO_printf(bio_stdout, "\n");
}
static void lock_dbg_cb(int mode, int type, const char *file, int line)
{
static int modes[CRYPTO_NUM_LOCKS]; /* = {0, 0, ... } */
const char *errstr = NULL;
int rw;
rw = mode & (CRYPTO_READ | CRYPTO_WRITE);
if (!((rw == CRYPTO_READ) || (rw == CRYPTO_WRITE))) {
errstr = "invalid mode";
goto err;
}
if (type < 0 || type >= CRYPTO_NUM_LOCKS) {
errstr = "type out of bounds";
goto err;
}
if (mode & CRYPTO_LOCK) {
if (modes[type]) {
errstr = "already locked";
/*
* must not happen in a single-threaded program (would deadlock)
*/
goto err;
}
modes[type] = rw;
} else if (mode & CRYPTO_UNLOCK) {
if (!modes[type]) {
errstr = "not locked";
goto err;
}
if (modes[type] != rw) {
errstr = (rw == CRYPTO_READ) ?
"CRYPTO_r_unlock on write lock" :
"CRYPTO_w_unlock on read lock";
}
modes[type] = 0;
} else {
errstr = "invalid mode";
goto err;
}
err:
if (errstr) {
/* we cannot use bio_err here */
fprintf(stderr,
"openssl (lock_dbg_cb): %s (mode=%d, type=%d) at %s:%d\n",
errstr, mode, type, file, line);
}
}
#ifdef TLSEXT_TYPE_opaque_prf_input
struct cb_info_st {
void *input;
size_t len;
int ret;
};
struct cb_info_st co1 = { "C", 1, 1 }; /* try to negotiate oqaque PRF input */
struct cb_info_st co2 = { "C", 1, 2 }; /* insist on oqaque PRF input */
struct cb_info_st so1 = { "S", 1, 1 }; /* try to negotiate oqaque PRF input */
struct cb_info_st so2 = { "S", 1, 2 }; /* insist on oqaque PRF input */
int opaque_prf_input_cb(SSL *ssl, void *peerinput, size_t len, void *arg_)
{
struct cb_info_st *arg = arg_;
if (arg == NULL)
return 1;
if (!SSL_set_tlsext_opaque_prf_input(ssl, arg->input, arg->len))
return 0;
return arg->ret;
}
#endif
int main(int argc, char *argv[])
{
char *CApath = NULL, *CAfile = NULL;
int badop = 0;
int bio_pair = 0;
int force = 0;
int dtls1 = 0, dtls12 = 0, tls1 = 0, tls12 = 0, ssl2 = 0, ssl3 = 0, ret = 1;
int client_auth = 0;
int server_auth = 0, i;
struct app_verify_arg app_verify_arg =
{ APP_CALLBACK_STRING, 0, 0, NULL, NULL };
char *server_cert = TEST_SERVER_CERT;
char *server_key = NULL;
char *client_cert = TEST_CLIENT_CERT;
char *client_key = NULL;
#ifndef OPENSSL_NO_ECDH
char *named_curve = NULL;
#endif
SSL_CTX *c_ctx = NULL;
const SSL_METHOD *meth = NULL;
SSL *c_ssl, *s_ssl;
int number = 1, reuse = 0;
long bytes = 256L;
#ifndef OPENSSL_NO_DH
DH *dh;
int dhe512 = 0, dhe1024dsa = 0;
#endif
#ifndef OPENSSL_NO_ECDH
EC_KEY *ecdh = NULL;
#endif
#ifndef OPENSSL_NO_SRP
/* client */
SRP_CLIENT_ARG srp_client_arg = { NULL, NULL };
/* server */
SRP_SERVER_ARG srp_server_arg = { NULL, NULL };
#endif
int no_dhe = 0;
int no_ecdhe = 0;
int no_psk = 0;
int print_time = 0;
clock_t s_time = 0, c_time = 0;
#ifndef OPENSSL_NO_COMP
int comp = 0;
COMP_METHOD *cm = NULL;
STACK_OF(SSL_COMP) *ssl_comp_methods = NULL;
#endif
int test_cipherlist = 0;
#ifdef OPENSSL_FIPS
int fips_mode = 0;
#endif
int no_protocol = 0;
verbose = 0;
debug = 0;
cipher = 0;
bio_err = BIO_new_fp(stderr, BIO_NOCLOSE | BIO_FP_TEXT);
CRYPTO_set_locking_callback(lock_dbg_cb);
/* enable memory leak checking unless explicitly disabled */
if (!((getenv("OPENSSL_DEBUG_MEMORY") != NULL)
&& (0 == strcmp(getenv("OPENSSL_DEBUG_MEMORY"), "off")))) {
CRYPTO_malloc_debug_init();
CRYPTO_set_mem_debug_options(V_CRYPTO_MDEBUG_ALL);
} else {
/* OPENSSL_DEBUG_MEMORY=off */
CRYPTO_set_mem_debug_functions(0, 0, 0, 0, 0);
}
CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON);
- RAND_seed(rnd_seed, sizeof rnd_seed);
+ RAND_seed(rnd_seed, sizeof(rnd_seed));
bio_stdout = BIO_new_fp(stdout, BIO_NOCLOSE | BIO_FP_TEXT);
argc--;
argv++;
while (argc >= 1) {
if (!strcmp(*argv, "-F")) {
#ifdef OPENSSL_FIPS
fips_mode = 1;
#else
fprintf(stderr,
"not compiled with FIPS support, so exiting without running.\n");
EXIT(0);
#endif
} else if (strcmp(*argv, "-server_auth") == 0)
server_auth = 1;
else if (strcmp(*argv, "-client_auth") == 0)
client_auth = 1;
else if (strcmp(*argv, "-proxy_auth") == 0) {
if (--argc < 1)
goto bad;
app_verify_arg.proxy_auth = *(++argv);
} else if (strcmp(*argv, "-proxy_cond") == 0) {
if (--argc < 1)
goto bad;
app_verify_arg.proxy_cond = *(++argv);
} else if (strcmp(*argv, "-v") == 0)
verbose = 1;
else if (strcmp(*argv, "-d") == 0)
debug = 1;
else if (strcmp(*argv, "-reuse") == 0)
reuse = 1;
else if (strcmp(*argv, "-dhe512") == 0) {
#ifndef OPENSSL_NO_DH
dhe512 = 1;
#else
fprintf(stderr,
"ignoring -dhe512, since I'm compiled without DH\n");
#endif
} else if (strcmp(*argv, "-dhe1024dsa") == 0) {
#ifndef OPENSSL_NO_DH
dhe1024dsa = 1;
#else
fprintf(stderr,
"ignoring -dhe1024dsa, since I'm compiled without DH\n");
#endif
} else if (strcmp(*argv, "-no_dhe") == 0)
no_dhe = 1;
else if (strcmp(*argv, "-no_ecdhe") == 0)
no_ecdhe = 1;
else if (strcmp(*argv, "-psk") == 0) {
if (--argc < 1)
goto bad;
psk_key = *(++argv);
#ifndef OPENSSL_NO_PSK
if (strspn(psk_key, "abcdefABCDEF1234567890") != strlen(psk_key)) {
BIO_printf(bio_err, "Not a hex number '%s'\n", *argv);
goto bad;
}
#else
no_psk = 1;
#endif
}
#ifndef OPENSSL_NO_SRP
else if (strcmp(*argv, "-srpuser") == 0) {
if (--argc < 1)
goto bad;
srp_server_arg.expected_user = srp_client_arg.srplogin =
*(++argv);
tls1 = 1;
} else if (strcmp(*argv, "-srppass") == 0) {
if (--argc < 1)
goto bad;
srp_server_arg.pass = srp_client_arg.srppassin = *(++argv);
tls1 = 1;
}
#endif
else if (strcmp(*argv, "-ssl2") == 0) {
#ifdef OPENSSL_NO_SSL2
no_protocol = 1;
#endif
ssl2 = 1;
} else if (strcmp(*argv, "-tls1") == 0) {
#ifdef OPENSSL_NO_TLS1
no_protocol = 1;
#endif
tls1 = 1;
} else if (strcmp(*argv, "-tls12") == 0) {
#ifdef OPENSSL_NO_TLS1
no_protocol = 1;
#endif
tls12 = 1;
} else if (strcmp(*argv, "-ssl3") == 0) {
#ifdef OPENSSL_NO_SSL3_METHOD
no_protocol = 1;
#endif
ssl3 = 1;
} else if (strcmp(*argv, "-dtls1") == 0) {
#ifdef OPENSSL_NO_DTLS
no_protocol = 1;
#endif
dtls1 = 1;
} else if (strcmp(*argv, "-dtls12") == 0) {
#ifdef OPENSSL_NO_DTLS
no_protocol = 1;
#endif
dtls12 = 1;
} else if (strncmp(*argv, "-num", 4) == 0) {
if (--argc < 1)
goto bad;
number = atoi(*(++argv));
if (number == 0)
number = 1;
} else if (strcmp(*argv, "-bytes") == 0) {
if (--argc < 1)
goto bad;
bytes = atol(*(++argv));
if (bytes == 0L)
bytes = 1L;
i = strlen(argv[0]);
if (argv[0][i - 1] == 'k')
bytes *= 1024L;
if (argv[0][i - 1] == 'm')
bytes *= 1024L * 1024L;
} else if (strcmp(*argv, "-cert") == 0) {
if (--argc < 1)
goto bad;
server_cert = *(++argv);
} else if (strcmp(*argv, "-s_cert") == 0) {
if (--argc < 1)
goto bad;
server_cert = *(++argv);
} else if (strcmp(*argv, "-key") == 0) {
if (--argc < 1)
goto bad;
server_key = *(++argv);
} else if (strcmp(*argv, "-s_key") == 0) {
if (--argc < 1)
goto bad;
server_key = *(++argv);
} else if (strcmp(*argv, "-c_cert") == 0) {
if (--argc < 1)
goto bad;
client_cert = *(++argv);
} else if (strcmp(*argv, "-c_key") == 0) {
if (--argc < 1)
goto bad;
client_key = *(++argv);
} else if (strcmp(*argv, "-cipher") == 0) {
if (--argc < 1)
goto bad;
cipher = *(++argv);
} else if (strcmp(*argv, "-CApath") == 0) {
if (--argc < 1)
goto bad;
CApath = *(++argv);
} else if (strcmp(*argv, "-CAfile") == 0) {
if (--argc < 1)
goto bad;
CAfile = *(++argv);
} else if (strcmp(*argv, "-bio_pair") == 0) {
bio_pair = 1;
} else if (strcmp(*argv, "-f") == 0) {
force = 1;
} else if (strcmp(*argv, "-time") == 0) {
print_time = 1;
}
else if (strcmp(*argv, "-zlib") == 0) {
#ifndef OPENSSL_NO_COMP
comp = COMP_ZLIB;
#else
fprintf(stderr,
"ignoring -zlib, since I'm compiled without COMP\n");
#endif
} else if (strcmp(*argv, "-rle") == 0) {
#ifndef OPENSSL_NO_COMP
comp = COMP_RLE;
#else
fprintf(stderr,
"ignoring -rle, since I'm compiled without COMP\n");
#endif
}
else if (strcmp(*argv, "-named_curve") == 0) {
if (--argc < 1)
goto bad;
#ifndef OPENSSL_NO_ECDH
named_curve = *(++argv);
#else
fprintf(stderr,
"ignoring -named_curve, since I'm compiled without ECDH\n");
++argv;
#endif
} else if (strcmp(*argv, "-app_verify") == 0) {
app_verify_arg.app_verify = 1;
} else if (strcmp(*argv, "-proxy") == 0) {
app_verify_arg.allow_proxy_certs = 1;
} else if (strcmp(*argv, "-test_cipherlist") == 0) {
test_cipherlist = 1;
} else if (strcmp(*argv, "-serverinfo_sct") == 0) {
serverinfo_sct = 1;
} else if (strcmp(*argv, "-serverinfo_tack") == 0) {
serverinfo_tack = 1;
} else if (strcmp(*argv, "-serverinfo_file") == 0) {
if (--argc < 1)
goto bad;
serverinfo_file = *(++argv);
} else if (strcmp(*argv, "-custom_ext") == 0) {
custom_ext = 1;
} else if (strcmp(*argv, "-alpn_client") == 0) {
if (--argc < 1)
goto bad;
alpn_client = *(++argv);
} else if (strcmp(*argv, "-alpn_server") == 0 ||
strcmp(*argv, "-alpn_server1") == 0) {
if (--argc < 1)
goto bad;
alpn_server = *(++argv);
} else if (strcmp(*argv, "-alpn_server2") == 0) {
if (--argc < 1)
goto bad;
alpn_server2 = *(++argv);
} else if (strcmp(*argv, "-alpn_expected") == 0) {
if (--argc < 1)
goto bad;
alpn_expected = *(++argv);
} else if (strcmp(*argv, "-sn_client") == 0) {
if (--argc < 1)
goto bad;
sn_client = *(++argv);
} else if (strcmp(*argv, "-sn_server1") == 0) {
if (--argc < 1)
goto bad;
sn_server1 = *(++argv);
} else if (strcmp(*argv, "-sn_server2") == 0) {
if (--argc < 1)
goto bad;
sn_server2 = *(++argv);
} else if (strcmp(*argv, "-sn_expect1") == 0) {
sn_expect = 1;
} else if (strcmp(*argv, "-sn_expect2") == 0) {
sn_expect = 2;
#ifndef OPENSSL_NO_TLSEXT
} else if (strcmp(*argv, "-s_ticket1") == 0) {
if (--argc < 1)
goto bad;
argv++;
if (strcmp(*argv, "yes") == 0)
s_ticket1 = 1;
if (strcmp(*argv, "broken") == 0)
s_ticket1 = 2;
} else if (strcmp(*argv, "-s_ticket2") == 0) {
if (--argc < 1)
goto bad;
argv++;
if (strcmp(*argv, "yes") == 0)
s_ticket2 = 1;
} else if (strcmp(*argv, "-c_ticket") == 0) {
if (--argc < 1)
goto bad;
argv++;
if (strcmp(*argv, "yes") == 0)
c_ticket = 1;
} else if (strcmp(*argv, "-ticket_expect") == 0) {
if (--argc < 1)
goto bad;
argv++;
if (strcmp(*argv, "yes") == 0)
ticket_expect = 1;
else if (strcmp(*argv, "no") == 0)
ticket_expect = 0;
#endif
} else if (strcmp(*argv, "-sni_in_cert_cb") == 0) {
sni_in_cert_cb = 1;
} else if (strcmp(*argv, "-client_sigalgs") == 0) {
if (--argc < 1)
goto bad;
client_sigalgs = *(++argv);
} else if (strcmp(*argv, "-server_digest_expect") == 0) {
if (--argc < 1)
goto bad;
server_digest_expect = *(++argv);
} else {
fprintf(stderr, "unknown option %s\n", *argv);
badop = 1;
break;
}
argc--;
argv++;
}
if (badop) {
bad:
sv_usage();
goto end;
}
/*
* test_cipherlist prevails over protocol switch: we test the cipherlist
* for all enabled protocols.
*/
if (test_cipherlist == 1) {
/*
* ensure that the cipher list are correctly sorted and exit
*/
fprintf(stdout, "Testing cipherlist order only. Ignoring all "
"other options.\n");
if (do_test_cipherlist() == 0)
EXIT(1);
ret = 0;
goto end;
}
if (ssl2 + ssl3 + tls1 + tls12 + dtls1 + dtls12 > 1) {
fprintf(stderr, "At most one of -ssl2, -ssl3, -tls1, -tls12, -dtls1 or "
"-dtls12 should be requested.\n");
EXIT(1);
}
/*
* Testing was requested for a compiled-out protocol (e.g. SSLv2).
* Ideally, we would error out, but the generic test wrapper can't know
* when to expect failure. So we do nothing and return success.
*/
if (no_protocol) {
fprintf(stderr, "Testing was requested for a disabled protocol. "
"Skipping tests.\n");
ret = 0;
goto end;
}
if (!ssl2 && !ssl3 && !tls1 && !tls12 && !dtls1 && !dtls12 && number > 1
&& !reuse && !force) {
fprintf(stderr, "This case cannot work. Use -f to perform "
"the test anyway (and\n-d to see what happens), "
"or add one of ssl2, -ssl3, -tls1, -tls12, -dtls1, -dtls12, -reuse\n"
"to avoid protocol mismatch.\n");
EXIT(1);
}
#ifdef OPENSSL_FIPS
if (fips_mode) {
if (!FIPS_mode_set(1)) {
ERR_load_crypto_strings();
ERR_print_errors(BIO_new_fp(stderr, BIO_NOCLOSE));
EXIT(1);
} else
fprintf(stderr, "*** IN FIPS MODE ***\n");
}
#endif
if (print_time) {
if (!bio_pair) {
fprintf(stderr, "Using BIO pair (-bio_pair)\n");
bio_pair = 1;
}
if (number < 50 && !force)
fprintf(stderr,
"Warning: For accurate timings, use more connections (e.g. -num 1000)\n");
}
/* if (cipher == NULL) cipher=getenv("SSL_CIPHER"); */
SSL_library_init();
SSL_load_error_strings();
#ifndef OPENSSL_NO_COMP
if (comp == COMP_ZLIB)
cm = COMP_zlib();
if (comp == COMP_RLE)
cm = COMP_rle();
if (cm != NULL) {
if (cm->type != NID_undef) {
if (SSL_COMP_add_compression_method(comp, cm) != 0) {
fprintf(stderr, "Failed to add compression method\n");
ERR_print_errors_fp(stderr);
}
} else {
fprintf(stderr,
"Warning: %s compression not supported\n",
(comp == COMP_RLE ? "rle" :
(comp == COMP_ZLIB ? "zlib" : "unknown")));
ERR_print_errors_fp(stderr);
}
}
ssl_comp_methods = SSL_COMP_get_compression_methods();
fprintf(stderr, "Available compression methods:\n");
{
int j, n = sk_SSL_COMP_num(ssl_comp_methods);
if (n == 0)
fprintf(stderr, " NONE\n");
else
for (j = 0; j < n; j++) {
SSL_COMP *c = sk_SSL_COMP_value(ssl_comp_methods, j);
fprintf(stderr, " %d: %s\n", c->id, c->name);
}
}
#endif
/*
* At this point, ssl2/ssl3/tls1/tls12 is only set if the protocol is
* available. (Otherwise we exit early.) However the compiler doesn't
* know this, so we ifdef.
*/
#ifndef OPENSSL_NO_SSL2
if (ssl2)
meth = SSLv2_method();
else
#endif
#ifndef OPENSSL_NO_SSL3
if (ssl3)
meth = SSLv3_method();
else
#endif
#ifndef OPENSSL_NO_DTLS
if (dtls1)
meth = DTLSv1_method();
else if (dtls12)
meth = DTLSv1_2_method();
else
#endif
#ifndef OPENSSL_NO_TLS1
if (tls1)
meth = TLSv1_method();
else if (tls12)
meth = TLSv1_2_method();
else
#endif
meth = SSLv23_method();
c_ctx = SSL_CTX_new(meth);
s_ctx = SSL_CTX_new(meth);
s_ctx2 = SSL_CTX_new(meth); /* no SSL_CTX_dup! */
if ((c_ctx == NULL) || (s_ctx == NULL) || (s_ctx2 == NULL)) {
ERR_print_errors(bio_err);
goto end;
}
if (cipher != NULL) {
SSL_CTX_set_cipher_list(c_ctx, cipher);
SSL_CTX_set_cipher_list(s_ctx, cipher);
SSL_CTX_set_cipher_list(s_ctx2, cipher);
}
#ifndef OPENSSL_NO_DH
if (!no_dhe) {
if (dhe1024dsa) {
/*
* use SSL_OP_SINGLE_DH_USE to avoid small subgroup attacks
*/
SSL_CTX_set_options(s_ctx, SSL_OP_SINGLE_DH_USE);
SSL_CTX_set_options(s_ctx2, SSL_OP_SINGLE_DH_USE);
dh = get_dh1024dsa();
} else if (dhe512)
dh = get_dh512();
else
dh = get_dh1024();
SSL_CTX_set_tmp_dh(s_ctx, dh);
SSL_CTX_set_tmp_dh(s_ctx2, dh);
DH_free(dh);
}
#else
(void)no_dhe;
#endif
#ifndef OPENSSL_NO_ECDH
if (!no_ecdhe) {
int nid;
if (named_curve != NULL) {
nid = OBJ_sn2nid(named_curve);
if (nid == 0) {
BIO_printf(bio_err, "unknown curve name (%s)\n", named_curve);
goto end;
}
} else {
nid = NID_X9_62_prime256v1;
}
ecdh = EC_KEY_new_by_curve_name(nid);
if (ecdh == NULL) {
BIO_printf(bio_err, "unable to create curve\n");
goto end;
}
SSL_CTX_set_tmp_ecdh(s_ctx, ecdh);
SSL_CTX_set_tmp_ecdh(s_ctx2, ecdh);
SSL_CTX_set_options(s_ctx, SSL_OP_SINGLE_ECDH_USE);
SSL_CTX_set_options(s_ctx2, SSL_OP_SINGLE_ECDH_USE);
EC_KEY_free(ecdh);
}
#else
(void)no_ecdhe;
#endif
#ifndef OPENSSL_NO_RSA
SSL_CTX_set_tmp_rsa_callback(s_ctx, tmp_rsa_cb);
SSL_CTX_set_tmp_rsa_callback(s_ctx2, tmp_rsa_cb);
#endif
#ifdef TLSEXT_TYPE_opaque_prf_input
SSL_CTX_set_tlsext_opaque_prf_input_callback(c_ctx, opaque_prf_input_cb);
SSL_CTX_set_tlsext_opaque_prf_input_callback(s_ctx, opaque_prf_input_cb);
SSL_CTX_set_tlsext_opaque_prf_input_callback(s_ctx2, opaque_prf_input_cb);
/* or &co2 or NULL */
SSL_CTX_set_tlsext_opaque_prf_input_callback_arg(c_ctx, &co1);
/* or &so2 or NULL */
SSL_CTX_set_tlsext_opaque_prf_input_callback_arg(s_ctx, &so1);
SSL_CTX_set_tlsext_opaque_prf_input_callback_arg(s_ctx2, &so1);
#endif
if (!SSL_CTX_use_certificate_file(s_ctx, server_cert, SSL_FILETYPE_PEM)) {
ERR_print_errors(bio_err);
} else if (!SSL_CTX_use_PrivateKey_file(s_ctx,
(server_key ? server_key :
server_cert),
SSL_FILETYPE_PEM)) {
ERR_print_errors(bio_err);
goto end;
}
if (!SSL_CTX_use_certificate_file(s_ctx2, server_cert, SSL_FILETYPE_PEM)) {
ERR_print_errors(bio_err);
} else if (!SSL_CTX_use_PrivateKey_file(s_ctx2,
(server_key ? server_key :
server_cert),
SSL_FILETYPE_PEM)) {
ERR_print_errors(bio_err);
goto end;
}
if (client_auth) {
SSL_CTX_use_certificate_file(c_ctx, client_cert, SSL_FILETYPE_PEM);
SSL_CTX_use_PrivateKey_file(c_ctx,
(client_key ? client_key : client_cert),
SSL_FILETYPE_PEM);
}
if ((!SSL_CTX_load_verify_locations(s_ctx, CAfile, CApath)) ||
(!SSL_CTX_set_default_verify_paths(s_ctx)) ||
(!SSL_CTX_load_verify_locations(s_ctx2, CAfile, CApath)) ||
(!SSL_CTX_set_default_verify_paths(s_ctx2)) ||
(!SSL_CTX_load_verify_locations(c_ctx, CAfile, CApath)) ||
(!SSL_CTX_set_default_verify_paths(c_ctx))) {
/* fprintf(stderr,"SSL_load_verify_locations\n"); */
ERR_print_errors(bio_err);
/* goto end; */
}
if (client_auth) {
BIO_printf(bio_err, "client authentication\n");
SSL_CTX_set_verify(s_ctx,
SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
verify_callback);
SSL_CTX_set_cert_verify_callback(s_ctx, app_verify_callback,
&app_verify_arg);
SSL_CTX_set_verify(s_ctx2,
SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
verify_callback);
SSL_CTX_set_cert_verify_callback(s_ctx2, app_verify_callback,
&app_verify_arg);
}
if (server_auth) {
BIO_printf(bio_err, "server authentication\n");
SSL_CTX_set_verify(c_ctx, SSL_VERIFY_PEER, verify_callback);
SSL_CTX_set_cert_verify_callback(c_ctx, app_verify_callback,
&app_verify_arg);
}
{
int session_id_context = 0;
SSL_CTX_set_session_id_context(s_ctx, (void *)&session_id_context,
- sizeof session_id_context);
+ sizeof(session_id_context));
SSL_CTX_set_session_id_context(s_ctx2, (void *)&session_id_context,
- sizeof session_id_context);
+ sizeof(session_id_context));
}
/* Use PSK only if PSK key is given */
if (psk_key != NULL) {
/*
* no_psk is used to avoid putting psk command to openssl tool
*/
if (no_psk) {
/*
* if PSK is not compiled in and psk key is given, do nothing and
* exit successfully
*/
ret = 0;
goto end;
}
#ifndef OPENSSL_NO_PSK
SSL_CTX_set_psk_client_callback(c_ctx, psk_client_callback);
SSL_CTX_set_psk_server_callback(s_ctx, psk_server_callback);
SSL_CTX_set_psk_server_callback(s_ctx2, psk_server_callback);
if (debug)
BIO_printf(bio_err, "setting PSK identity hint to s_ctx\n");
if (!SSL_CTX_use_psk_identity_hint(s_ctx, "ctx server identity_hint")) {
BIO_printf(bio_err, "error setting PSK identity hint to s_ctx\n");
ERR_print_errors(bio_err);
goto end;
}
if (!SSL_CTX_use_psk_identity_hint(s_ctx2, "ctx server identity_hint")) {
BIO_printf(bio_err, "error setting PSK identity hint to s_ctx2\n");
ERR_print_errors(bio_err);
goto end;
}
#endif
}
#ifndef OPENSSL_NO_SRP
if (srp_client_arg.srplogin) {
if (!SSL_CTX_set_srp_username(c_ctx, srp_client_arg.srplogin)) {
BIO_printf(bio_err, "Unable to set SRP username\n");
goto end;
}
SSL_CTX_set_srp_cb_arg(c_ctx, &srp_client_arg);
SSL_CTX_set_srp_client_pwd_callback(c_ctx,
ssl_give_srp_client_pwd_cb);
/*
* SSL_CTX_set_srp_strength(c_ctx, srp_client_arg.strength);
*/
}
if (srp_server_arg.expected_user != NULL) {
SSL_CTX_set_verify(s_ctx, SSL_VERIFY_NONE, verify_callback);
SSL_CTX_set_verify(s_ctx2, SSL_VERIFY_NONE, verify_callback);
SSL_CTX_set_srp_cb_arg(s_ctx, &srp_server_arg);
SSL_CTX_set_srp_cb_arg(s_ctx2, &srp_server_arg);
SSL_CTX_set_srp_username_callback(s_ctx, ssl_srp_server_param_cb);
SSL_CTX_set_srp_username_callback(s_ctx2, ssl_srp_server_param_cb);
}
#endif
if (serverinfo_sct)
SSL_CTX_add_client_custom_ext(c_ctx, SCT_EXT_TYPE,
NULL, NULL, NULL,
serverinfo_cli_parse_cb, NULL);
if (serverinfo_tack)
SSL_CTX_add_client_custom_ext(c_ctx, TACK_EXT_TYPE,
NULL, NULL, NULL,
serverinfo_cli_parse_cb, NULL);
if (serverinfo_file) {
if (!SSL_CTX_use_serverinfo_file(s_ctx, serverinfo_file)) {
BIO_printf(bio_err, "missing serverinfo file\n");
goto end;
}
if (!SSL_CTX_use_serverinfo_file(s_ctx2, serverinfo_file)) {
BIO_printf(bio_err, "missing serverinfo file\n");
goto end;
}
}
if (custom_ext) {
SSL_CTX_add_client_custom_ext(c_ctx, CUSTOM_EXT_TYPE_0,
custom_ext_0_cli_add_cb,
NULL, NULL,
custom_ext_0_cli_parse_cb, NULL);
SSL_CTX_add_client_custom_ext(c_ctx, CUSTOM_EXT_TYPE_1,
custom_ext_1_cli_add_cb,
NULL, NULL,
custom_ext_1_cli_parse_cb, NULL);
SSL_CTX_add_client_custom_ext(c_ctx, CUSTOM_EXT_TYPE_2,
custom_ext_2_cli_add_cb,
NULL, NULL,
custom_ext_2_cli_parse_cb, NULL);
SSL_CTX_add_client_custom_ext(c_ctx, CUSTOM_EXT_TYPE_3,
custom_ext_3_cli_add_cb,
NULL, NULL,
custom_ext_3_cli_parse_cb, NULL);
SSL_CTX_add_server_custom_ext(s_ctx, CUSTOM_EXT_TYPE_0,
custom_ext_0_srv_add_cb,
NULL, NULL,
custom_ext_0_srv_parse_cb, NULL);
SSL_CTX_add_server_custom_ext(s_ctx, CUSTOM_EXT_TYPE_1,
custom_ext_1_srv_add_cb,
NULL, NULL,
custom_ext_1_srv_parse_cb, NULL);
SSL_CTX_add_server_custom_ext(s_ctx, CUSTOM_EXT_TYPE_2,
custom_ext_2_srv_add_cb,
NULL, NULL,
custom_ext_2_srv_parse_cb, NULL);
SSL_CTX_add_server_custom_ext(s_ctx, CUSTOM_EXT_TYPE_3,
custom_ext_3_srv_add_cb,
NULL, NULL,
custom_ext_3_srv_parse_cb, NULL);
SSL_CTX_add_server_custom_ext(s_ctx2, CUSTOM_EXT_TYPE_0,
custom_ext_0_srv_add_cb,
NULL, NULL,
custom_ext_0_srv_parse_cb, NULL);
SSL_CTX_add_server_custom_ext(s_ctx2, CUSTOM_EXT_TYPE_1,
custom_ext_1_srv_add_cb,
NULL, NULL,
custom_ext_1_srv_parse_cb, NULL);
SSL_CTX_add_server_custom_ext(s_ctx2, CUSTOM_EXT_TYPE_2,
custom_ext_2_srv_add_cb,
NULL, NULL,
custom_ext_2_srv_parse_cb, NULL);
SSL_CTX_add_server_custom_ext(s_ctx2, CUSTOM_EXT_TYPE_3,
custom_ext_3_srv_add_cb,
NULL, NULL,
custom_ext_3_srv_parse_cb, NULL);
}
if (alpn_server)
SSL_CTX_set_alpn_select_cb(s_ctx, cb_server_alpn, alpn_server);
if (alpn_server2)
SSL_CTX_set_alpn_select_cb(s_ctx2, cb_server_alpn, alpn_server2);
if (alpn_client) {
unsigned short alpn_len;
unsigned char *alpn = next_protos_parse(&alpn_len, alpn_client);
if (alpn == NULL) {
BIO_printf(bio_err, "Error parsing -alpn_client argument\n");
goto end;
}
SSL_CTX_set_alpn_protos(c_ctx, alpn, alpn_len);
OPENSSL_free(alpn);
}
if (sn_server1 || sn_server2) {
if (sni_in_cert_cb)
SSL_CTX_set_cert_cb(s_ctx, cert_cb, NULL);
else
SSL_CTX_set_tlsext_servername_callback(s_ctx, servername_cb);
}
#ifndef OPENSSL_NO_TLSEXT
if (s_ticket1 == 0)
SSL_CTX_set_options(s_ctx, SSL_OP_NO_TICKET);
/* always set the callback */
if (s_ticket1 == 2)
SSL_CTX_set_tlsext_ticket_key_cb(s_ctx, cb_ticket0);
else
SSL_CTX_set_tlsext_ticket_key_cb(s_ctx, cb_ticket1);
if (!s_ticket2)
SSL_CTX_set_options(s_ctx2, SSL_OP_NO_TICKET);
/* always set the callback - this should never be called */
SSL_CTX_set_tlsext_ticket_key_cb(s_ctx2, cb_ticket2);
if (!c_ticket)
SSL_CTX_set_options(c_ctx, SSL_OP_NO_TICKET);
#endif
if (client_sigalgs != NULL)
SSL_CTX_set1_sigalgs_list(c_ctx, client_sigalgs);
c_ssl = SSL_new(c_ctx);
s_ssl = SSL_new(s_ctx);
if (sn_client)
SSL_set_tlsext_host_name(c_ssl, sn_client);
#ifndef OPENSSL_NO_KRB5
if (c_ssl && c_ssl->kssl_ctx) {
char localhost[MAXHOSTNAMELEN + 2];
- if (gethostname(localhost, sizeof localhost - 1) == 0) {
- localhost[sizeof localhost - 1] = '\0';
- if (strlen(localhost) == sizeof localhost - 1) {
+ if (gethostname(localhost, sizeof(localhost) - 1) == 0) {
+ localhost[sizeof(localhost) - 1] = '\0';
+ if (strlen(localhost) == sizeof(localhost) - 1) {
BIO_printf(bio_err, "localhost name too long\n");
goto end;
}
kssl_ctx_setstring(c_ssl->kssl_ctx, KSSL_SERVER, localhost);
}
}
#endif /* OPENSSL_NO_KRB5 */
for (i = 0; i < number; i++) {
if (!reuse)
SSL_set_session(c_ssl, NULL);
if (bio_pair)
ret = doit_biopair(s_ssl, c_ssl, bytes, &s_time, &c_time);
else
ret = doit(s_ssl, c_ssl, bytes);
}
if (!verbose) {
print_details(c_ssl, "");
}
if ((number > 1) || (bytes > 1L))
BIO_printf(bio_stdout, "%d handshakes of %ld bytes done\n", number,
bytes);
if (print_time) {
#ifdef CLOCKS_PER_SEC
/*
* "To determine the time in seconds, the value returned by the clock
* function should be divided by the value of the macro
* CLOCKS_PER_SEC." -- ISO/IEC 9899
*/
BIO_printf(bio_stdout, "Approximate total server time: %6.2f s\n"
"Approximate total client time: %6.2f s\n",
(double)s_time / CLOCKS_PER_SEC,
(double)c_time / CLOCKS_PER_SEC);
#else
/*
* "`CLOCKS_PER_SEC' undeclared (first use this function)" -- cc on
* NeXTstep/OpenStep
*/
BIO_printf(bio_stdout,
"Approximate total server time: %6.2f units\n"
"Approximate total client time: %6.2f units\n",
(double)s_time, (double)c_time);
#endif
}
if (verify_alpn(c_ssl, s_ssl) < 0)
ret = 1;
if (verify_servername(c_ssl, s_ssl) < 0)
ret = 1;
if (verify_ticket(c_ssl) < 0)
ret = 1;
if (verify_server_digest(c_ssl) < 0)
ret = 1;
SSL_free(s_ssl);
SSL_free(c_ssl);
end:
if (s_ctx != NULL)
SSL_CTX_free(s_ctx);
if (s_ctx2 != NULL)
SSL_CTX_free(s_ctx2);
if (c_ctx != NULL)
SSL_CTX_free(c_ctx);
if (bio_stdout != NULL)
BIO_free(bio_stdout);
#ifndef OPENSSL_NO_RSA
free_tmp_rsa();
#endif
#ifndef OPENSSL_NO_ENGINE
ENGINE_cleanup();
#endif
CRYPTO_cleanup_all_ex_data();
ERR_free_strings();
ERR_remove_thread_state(NULL);
EVP_cleanup();
CRYPTO_mem_leaks(bio_err);
if (bio_err != NULL)
BIO_free(bio_err);
EXIT(ret);
return ret;
}
int doit_biopair(SSL *s_ssl, SSL *c_ssl, long count,
clock_t *s_time, clock_t *c_time)
{
long cw_num = count, cr_num = count, sw_num = count, sr_num = count;
BIO *s_ssl_bio = NULL, *c_ssl_bio = NULL;
BIO *server = NULL, *server_io = NULL, *client = NULL, *client_io = NULL;
int ret = 1;
size_t bufsiz = 256; /* small buffer for testing */
if (!BIO_new_bio_pair(&server, bufsiz, &server_io, bufsiz))
goto err;
if (!BIO_new_bio_pair(&client, bufsiz, &client_io, bufsiz))
goto err;
s_ssl_bio = BIO_new(BIO_f_ssl());
if (!s_ssl_bio)
goto err;
c_ssl_bio = BIO_new(BIO_f_ssl());
if (!c_ssl_bio)
goto err;
SSL_set_connect_state(c_ssl);
SSL_set_bio(c_ssl, client, client);
(void)BIO_set_ssl(c_ssl_bio, c_ssl, BIO_NOCLOSE);
SSL_set_accept_state(s_ssl);
SSL_set_bio(s_ssl, server, server);
(void)BIO_set_ssl(s_ssl_bio, s_ssl, BIO_NOCLOSE);
do {
/*-
* c_ssl_bio: SSL filter BIO
*
* client: pseudo-I/O for SSL library
*
* client_io: client's SSL communication; usually to be
* relayed over some I/O facility, but in this
* test program, we're the server, too:
*
* server_io: server's SSL communication
*
* server: pseudo-I/O for SSL library
*
* s_ssl_bio: SSL filter BIO
*
* The client and the server each employ a "BIO pair":
* client + client_io, server + server_io.
* BIO pairs are symmetric. A BIO pair behaves similar
* to a non-blocking socketpair (but both endpoints must
* be handled by the same thread).
* [Here we could connect client and server to the ends
* of a single BIO pair, but then this code would be less
* suitable as an example for BIO pairs in general.]
*
* Useful functions for querying the state of BIO pair endpoints:
*
* BIO_ctrl_pending(bio) number of bytes we can read now
* BIO_ctrl_get_read_request(bio) number of bytes needed to fulfil
* other side's read attempt
* BIO_ctrl_get_write_guarantee(bio) number of bytes we can write now
*
* ..._read_request is never more than ..._write_guarantee;
* it depends on the application which one you should use.
*/
/*
* We have non-blocking behaviour throughout this test program, but
* can be sure that there is *some* progress in each iteration; so we
* don't have to worry about ..._SHOULD_READ or ..._SHOULD_WRITE --
* we just try everything in each iteration
*/
{
/* CLIENT */
MS_STATIC char cbuf[1024 * 8];
int i, r;
clock_t c_clock = clock();
memset(cbuf, 0, sizeof(cbuf));
if (debug)
if (SSL_in_init(c_ssl))
printf("client waiting in SSL_connect - %s\n",
SSL_state_string_long(c_ssl));
if (cw_num > 0) {
/* Write to server. */
- if (cw_num > (long)sizeof cbuf)
- i = sizeof cbuf;
+ if (cw_num > (long)sizeof(cbuf))
+ i = sizeof(cbuf);
else
i = (int)cw_num;
r = BIO_write(c_ssl_bio, cbuf, i);
if (r < 0) {
if (!BIO_should_retry(c_ssl_bio)) {
fprintf(stderr, "ERROR in CLIENT\n");
goto err;
}
/*
* BIO_should_retry(...) can just be ignored here. The
* library expects us to call BIO_write with the same
* arguments again, and that's what we will do in the
* next iteration.
*/
} else if (r == 0) {
fprintf(stderr, "SSL CLIENT STARTUP FAILED\n");
goto err;
} else {
if (debug)
printf("client wrote %d\n", r);
cw_num -= r;
}
}
if (cr_num > 0) {
/* Read from server. */
r = BIO_read(c_ssl_bio, cbuf, sizeof(cbuf));
if (r < 0) {
if (!BIO_should_retry(c_ssl_bio)) {
fprintf(stderr, "ERROR in CLIENT\n");
goto err;
}
/*
* Again, "BIO_should_retry" can be ignored.
*/
} else if (r == 0) {
fprintf(stderr, "SSL CLIENT STARTUP FAILED\n");
goto err;
} else {
if (debug)
printf("client read %d\n", r);
cr_num -= r;
}
}
/*
* c_time and s_time increments will typically be very small
* (depending on machine speed and clock tick intervals), but
* sampling over a large number of connections should result in
* fairly accurate figures. We cannot guarantee a lot, however
* -- if each connection lasts for exactly one clock tick, it
* will be counted only for the client or only for the server or
* even not at all.
*/
*c_time += (clock() - c_clock);
}
{
/* SERVER */
MS_STATIC char sbuf[1024 * 8];
int i, r;
clock_t s_clock = clock();
memset(sbuf, 0, sizeof(sbuf));
if (debug)
if (SSL_in_init(s_ssl))
printf("server waiting in SSL_accept - %s\n",
SSL_state_string_long(s_ssl));
if (sw_num > 0) {
/* Write to client. */
- if (sw_num > (long)sizeof sbuf)
- i = sizeof sbuf;
+ if (sw_num > (long)sizeof(sbuf))
+ i = sizeof(sbuf);
else
i = (int)sw_num;
r = BIO_write(s_ssl_bio, sbuf, i);
if (r < 0) {
if (!BIO_should_retry(s_ssl_bio)) {
fprintf(stderr, "ERROR in SERVER\n");
goto err;
}
/* Ignore "BIO_should_retry". */
} else if (r == 0) {
fprintf(stderr, "SSL SERVER STARTUP FAILED\n");
goto err;
} else {
if (debug)
printf("server wrote %d\n", r);
sw_num -= r;
}
}
if (sr_num > 0) {
/* Read from client. */
r = BIO_read(s_ssl_bio, sbuf, sizeof(sbuf));
if (r < 0) {
if (!BIO_should_retry(s_ssl_bio)) {
fprintf(stderr, "ERROR in SERVER\n");
goto err;
}
/* blah, blah */
} else if (r == 0) {
fprintf(stderr, "SSL SERVER STARTUP FAILED\n");
goto err;
} else {
if (debug)
printf("server read %d\n", r);
sr_num -= r;
}
}
*s_time += (clock() - s_clock);
}
{
/* "I/O" BETWEEN CLIENT AND SERVER. */
size_t r1, r2;
BIO *io1 = server_io, *io2 = client_io;
/*
* we use the non-copying interface for io1 and the standard
* BIO_write/BIO_read interface for io2
*/
static int prev_progress = 1;
int progress = 0;
/* io1 to io2 */
do {
size_t num;
int r;
r1 = BIO_ctrl_pending(io1);
r2 = BIO_ctrl_get_write_guarantee(io2);
num = r1;
if (r2 < num)
num = r2;
if (num) {
char *dataptr;
if (INT_MAX < num) /* yeah, right */
num = INT_MAX;
r = BIO_nread(io1, &dataptr, (int)num);
assert(r > 0);
assert(r <= (int)num);
/*
* possibly r < num (non-contiguous data)
*/
num = r;
r = BIO_write(io2, dataptr, (int)num);
if (r != (int)num) { /* can't happen */
fprintf(stderr, "ERROR: BIO_write could not write "
"BIO_ctrl_get_write_guarantee() bytes");
goto err;
}
progress = 1;
if (debug)
printf((io1 == client_io) ?
"C->S relaying: %d bytes\n" :
"S->C relaying: %d bytes\n", (int)num);
}
}
while (r1 && r2);
/* io2 to io1 */
{
size_t num;
int r;
r1 = BIO_ctrl_pending(io2);
r2 = BIO_ctrl_get_read_request(io1);
/*
* here we could use ..._get_write_guarantee instead of
* ..._get_read_request, but by using the latter we test
* restartability of the SSL implementation more thoroughly
*/
num = r1;
if (r2 < num)
num = r2;
if (num) {
char *dataptr;
if (INT_MAX < num)
num = INT_MAX;
if (num > 1)
--num; /* test restartability even more thoroughly */
r = BIO_nwrite0(io1, &dataptr);
assert(r > 0);
if (r < (int)num)
num = r;
r = BIO_read(io2, dataptr, (int)num);
if (r != (int)num) { /* can't happen */
fprintf(stderr, "ERROR: BIO_read could not read "
"BIO_ctrl_pending() bytes");
goto err;
}
progress = 1;
r = BIO_nwrite(io1, &dataptr, (int)num);
if (r != (int)num) { /* can't happen */
fprintf(stderr, "ERROR: BIO_nwrite() did not accept "
"BIO_nwrite0() bytes");
goto err;
}
if (debug)
printf((io2 == client_io) ?
"C->S relaying: %d bytes\n" :
"S->C relaying: %d bytes\n", (int)num);
}
} /* no loop, BIO_ctrl_get_read_request now
* returns 0 anyway */
if (!progress && !prev_progress)
if (cw_num > 0 || cr_num > 0 || sw_num > 0 || sr_num > 0) {
fprintf(stderr, "ERROR: got stuck\n");
if (strcmp("SSLv2", SSL_get_version(c_ssl)) == 0) {
fprintf(stderr, "This can happen for SSL2 because "
"CLIENT-FINISHED and SERVER-VERIFY are written \n"
"concurrently ...");
if (strncmp("2SCF", SSL_state_string(c_ssl), 4) == 0
&& strncmp("2SSV", SSL_state_string(s_ssl),
4) == 0) {
fprintf(stderr, " ok.\n");
goto end;
}
}
fprintf(stderr, " ERROR.\n");
goto err;
}
prev_progress = progress;
}
}
while (cw_num > 0 || cr_num > 0 || sw_num > 0 || sr_num > 0);
if (verbose)
print_details(c_ssl, "DONE via BIO pair: ");
if (verify_serverinfo() < 0) {
ret = 1;
goto err;
}
if (custom_ext_error) {
ret = 1;
goto err;
}
end:
ret = 0;
err:
ERR_print_errors(bio_err);
if (server)
BIO_free(server);
if (server_io)
BIO_free(server_io);
if (client)
BIO_free(client);
if (client_io)
BIO_free(client_io);
if (s_ssl_bio)
BIO_free(s_ssl_bio);
if (c_ssl_bio)
BIO_free(c_ssl_bio);
return ret;
}
#define W_READ 1
#define W_WRITE 2
#define C_DONE 1
#define S_DONE 2
int doit(SSL *s_ssl, SSL *c_ssl, long count)
{
char *cbuf = NULL, *sbuf = NULL;
long bufsiz;
long cw_num = count, cr_num = count;
long sw_num = count, sr_num = count;
int ret = 1;
BIO *c_to_s = NULL;
BIO *s_to_c = NULL;
BIO *c_bio = NULL;
BIO *s_bio = NULL;
int c_r, c_w, s_r, s_w;
int i, j;
int done = 0;
int c_write, s_write;
int do_server = 0, do_client = 0;
int max_frag = 5 * 1024;
bufsiz = count > 40 * 1024 ? 40 * 1024 : count;
if ((cbuf = OPENSSL_malloc(bufsiz)) == NULL)
goto err;
if ((sbuf = OPENSSL_malloc(bufsiz)) == NULL)
goto err;
memset(cbuf, 0, bufsiz);
memset(sbuf, 0, bufsiz);
c_to_s = BIO_new(BIO_s_mem());
s_to_c = BIO_new(BIO_s_mem());
if ((s_to_c == NULL) || (c_to_s == NULL)) {
ERR_print_errors(bio_err);
goto err;
}
c_bio = BIO_new(BIO_f_ssl());
s_bio = BIO_new(BIO_f_ssl());
if ((c_bio == NULL) || (s_bio == NULL)) {
ERR_print_errors(bio_err);
goto err;
}
SSL_set_connect_state(c_ssl);
SSL_set_bio(c_ssl, s_to_c, c_to_s);
SSL_set_max_send_fragment(c_ssl, max_frag);
BIO_set_ssl(c_bio, c_ssl, BIO_NOCLOSE);
SSL_set_accept_state(s_ssl);
SSL_set_bio(s_ssl, c_to_s, s_to_c);
SSL_set_max_send_fragment(s_ssl, max_frag);
BIO_set_ssl(s_bio, s_ssl, BIO_NOCLOSE);
c_r = 0;
s_r = 1;
c_w = 1;
s_w = 0;
c_write = 1, s_write = 0;
/* We can always do writes */
for (;;) {
do_server = 0;
do_client = 0;
i = (int)BIO_pending(s_bio);
if ((i && s_r) || s_w)
do_server = 1;
i = (int)BIO_pending(c_bio);
if ((i && c_r) || c_w)
do_client = 1;
if (do_server && debug) {
if (SSL_in_init(s_ssl))
printf("server waiting in SSL_accept - %s\n",
SSL_state_string_long(s_ssl));
/*-
else if (s_write)
printf("server:SSL_write()\n");
else
printf("server:SSL_read()\n"); */
}
if (do_client && debug) {
if (SSL_in_init(c_ssl))
printf("client waiting in SSL_connect - %s\n",
SSL_state_string_long(c_ssl));
/*-
else if (c_write)
printf("client:SSL_write()\n");
else
printf("client:SSL_read()\n"); */
}
if (!do_client && !do_server) {
fprintf(stdout, "ERROR IN STARTUP\n");
ERR_print_errors(bio_err);
goto err;
}
if (do_client && !(done & C_DONE)) {
if (c_write) {
j = (cw_num > bufsiz) ? (int)bufsiz : (int)cw_num;
i = BIO_write(c_bio, cbuf, j);
if (i < 0) {
c_r = 0;
c_w = 0;
if (BIO_should_retry(c_bio)) {
if (BIO_should_read(c_bio))
c_r = 1;
if (BIO_should_write(c_bio))
c_w = 1;
} else {
fprintf(stderr, "ERROR in CLIENT\n");
ERR_print_errors(bio_err);
goto err;
}
} else if (i == 0) {
fprintf(stderr, "SSL CLIENT STARTUP FAILED\n");
goto err;
} else {
if (debug)
printf("client wrote %d\n", i);
/* ok */
s_r = 1;
c_write = 0;
cw_num -= i;
if (max_frag > 1029)
SSL_set_max_send_fragment(c_ssl, max_frag -= 5);
}
} else {
i = BIO_read(c_bio, cbuf, bufsiz);
if (i < 0) {
c_r = 0;
c_w = 0;
if (BIO_should_retry(c_bio)) {
if (BIO_should_read(c_bio))
c_r = 1;
if (BIO_should_write(c_bio))
c_w = 1;
} else {
fprintf(stderr, "ERROR in CLIENT\n");
ERR_print_errors(bio_err);
goto err;
}
} else if (i == 0) {
fprintf(stderr, "SSL CLIENT STARTUP FAILED\n");
goto err;
} else {
if (debug)
printf("client read %d\n", i);
cr_num -= i;
if (sw_num > 0) {
s_write = 1;
s_w = 1;
}
if (cr_num <= 0) {
s_write = 1;
s_w = 1;
done = S_DONE | C_DONE;
}
}
}
}
if (do_server && !(done & S_DONE)) {
if (!s_write) {
i = BIO_read(s_bio, sbuf, bufsiz);
if (i < 0) {
s_r = 0;
s_w = 0;
if (BIO_should_retry(s_bio)) {
if (BIO_should_read(s_bio))
s_r = 1;
if (BIO_should_write(s_bio))
s_w = 1;
} else {
fprintf(stderr, "ERROR in SERVER\n");
ERR_print_errors(bio_err);
goto err;
}
} else if (i == 0) {
ERR_print_errors(bio_err);
fprintf(stderr,
"SSL SERVER STARTUP FAILED in SSL_read\n");
goto err;
} else {
if (debug)
printf("server read %d\n", i);
sr_num -= i;
if (cw_num > 0) {
c_write = 1;
c_w = 1;
}
if (sr_num <= 0) {
s_write = 1;
s_w = 1;
c_write = 0;
}
}
} else {
j = (sw_num > bufsiz) ? (int)bufsiz : (int)sw_num;
i = BIO_write(s_bio, sbuf, j);
if (i < 0) {
s_r = 0;
s_w = 0;
if (BIO_should_retry(s_bio)) {
if (BIO_should_read(s_bio))
s_r = 1;
if (BIO_should_write(s_bio))
s_w = 1;
} else {
fprintf(stderr, "ERROR in SERVER\n");
ERR_print_errors(bio_err);
goto err;
}
} else if (i == 0) {
ERR_print_errors(bio_err);
fprintf(stderr,
"SSL SERVER STARTUP FAILED in SSL_write\n");
goto err;
} else {
if (debug)
printf("server wrote %d\n", i);
sw_num -= i;
s_write = 0;
c_r = 1;
if (sw_num <= 0)
done |= S_DONE;
if (max_frag > 1029)
SSL_set_max_send_fragment(s_ssl, max_frag -= 5);
}
}
}
if ((done & S_DONE) && (done & C_DONE))
break;
}
if (verbose)
print_details(c_ssl, "DONE: ");
if (verify_serverinfo() < 0) {
ret = 1;
goto err;
}
if (custom_ext_error) {
ret = 1;
goto err;
}
ret = 0;
err:
/*
* We have to set the BIO's to NULL otherwise they will be
* OPENSSL_free()ed twice. Once when th s_ssl is SSL_free()ed and again
* when c_ssl is SSL_free()ed. This is a hack required because s_ssl and
* c_ssl are sharing the same BIO structure and SSL_set_bio() and
* SSL_free() automatically BIO_free non NULL entries. You should not
* normally do this or be required to do this
*/
if (s_ssl != NULL) {
s_ssl->rbio = NULL;
s_ssl->wbio = NULL;
}
if (c_ssl != NULL) {
c_ssl->rbio = NULL;
c_ssl->wbio = NULL;
}
if (c_to_s != NULL)
BIO_free(c_to_s);
if (s_to_c != NULL)
BIO_free(s_to_c);
if (c_bio != NULL)
BIO_free_all(c_bio);
if (s_bio != NULL)
BIO_free_all(s_bio);
if (cbuf)
OPENSSL_free(cbuf);
if (sbuf)
OPENSSL_free(sbuf);
return (ret);
}
static int get_proxy_auth_ex_data_idx(void)
{
static volatile int idx = -1;
if (idx < 0) {
CRYPTO_w_lock(CRYPTO_LOCK_SSL_CTX);
if (idx < 0) {
idx = X509_STORE_CTX_get_ex_new_index(0,
"SSLtest for verify callback",
NULL, NULL, NULL);
}
CRYPTO_w_unlock(CRYPTO_LOCK_SSL_CTX);
}
return idx;
}
static int MS_CALLBACK verify_callback(int ok, X509_STORE_CTX *ctx)
{
char *s, buf[256];
s = X509_NAME_oneline(X509_get_subject_name(ctx->current_cert), buf,
- sizeof buf);
+ sizeof(buf));
if (s != NULL) {
if (ok)
fprintf(stderr, "depth=%d %s\n", ctx->error_depth, buf);
else {
fprintf(stderr, "depth=%d error=%d %s\n",
ctx->error_depth, ctx->error, buf);
}
}
if (ok == 0) {
fprintf(stderr, "Error string: %s\n",
X509_verify_cert_error_string(ctx->error));
switch (ctx->error) {
case X509_V_ERR_CERT_NOT_YET_VALID:
case X509_V_ERR_CERT_HAS_EXPIRED:
case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT:
fprintf(stderr, " ... ignored.\n");
ok = 1;
}
}
if (ok == 1) {
X509 *xs = ctx->current_cert;
#if 0
X509 *xi = ctx->current_issuer;
#endif
if (xs->ex_flags & EXFLAG_PROXY) {
unsigned int *letters = X509_STORE_CTX_get_ex_data(ctx,
get_proxy_auth_ex_data_idx
());
if (letters) {
int found_any = 0;
int i;
PROXY_CERT_INFO_EXTENSION *pci =
X509_get_ext_d2i(xs, NID_proxyCertInfo,
NULL, NULL);
switch (OBJ_obj2nid(pci->proxyPolicy->policyLanguage)) {
case NID_Independent:
/*
* Completely meaningless in this program, as there's no
* way to grant explicit rights to a specific PrC.
* Basically, using id-ppl-Independent is the perfect way
* to grant no rights at all.
*/
fprintf(stderr, " Independent proxy certificate");
for (i = 0; i < 26; i++)
letters[i] = 0;
break;
case NID_id_ppl_inheritAll:
/*
* This is basically a NOP, we simply let the current
* rights stand as they are.
*/
fprintf(stderr, " Proxy certificate inherits all");
break;
default:
s = (char *)
pci->proxyPolicy->policy->data;
i = pci->proxyPolicy->policy->length;
/*
* The algorithm works as follows: it is assumed that
* previous iterations or the initial granted rights has
* already set some elements of `letters'. What we need
* to do is to clear those that weren't granted by the
* current PrC as well. The easiest way to do this is to
* add 1 to all the elements whose letters are given with
* the current policy. That way, all elements that are
* set by the current policy and were already set by
* earlier policies and through the original grant of
* rights will get the value 2 or higher. The last thing
* to do is to sweep through `letters' and keep the
* elements having the value 2 as set, and clear all the
* others.
*/
fprintf(stderr, " Certificate proxy rights = %*.*s", i,
i, s);
while (i-- > 0) {
int c = *s++;
if (isascii(c) && isalpha(c)) {
if (islower(c))
c = toupper(c);
letters[c - 'A']++;
}
}
for (i = 0; i < 26; i++)
if (letters[i] < 2)
letters[i] = 0;
else
letters[i] = 1;
}
found_any = 0;
fprintf(stderr, ", resulting proxy rights = ");
for (i = 0; i < 26; i++)
if (letters[i]) {
fprintf(stderr, "%c", i + 'A');
found_any = 1;
}
if (!found_any)
fprintf(stderr, "none");
fprintf(stderr, "\n");
PROXY_CERT_INFO_EXTENSION_free(pci);
}
}
}
return (ok);
}
static void process_proxy_debug(int indent, const char *format, ...)
{
/* That's 80 > */
static const char indentation[] =
">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"
">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>";
char my_format[256];
va_list args;
BIO_snprintf(my_format, sizeof(my_format), "%*.*s %s",
indent, indent, indentation, format);
va_start(args, format);
vfprintf(stderr, my_format, args);
va_end(args);
}
/*-
* Priority levels:
* 0 [!]var, ()
* 1 & ^
* 2 |
*/
static int process_proxy_cond_adders(unsigned int letters[26],
const char *cond, const char **cond_end,
int *pos, int indent);
static int process_proxy_cond_val(unsigned int letters[26], const char *cond,
const char **cond_end, int *pos, int indent)
{
int c;
int ok = 1;
int negate = 0;
while (isspace((int)*cond)) {
cond++;
(*pos)++;
}
c = *cond;
if (debug)
process_proxy_debug(indent,
"Start process_proxy_cond_val at position %d: %s\n",
*pos, cond);
while (c == '!') {
negate = !negate;
cond++;
(*pos)++;
while (isspace((int)*cond)) {
cond++;
(*pos)++;
}
c = *cond;
}
if (c == '(') {
cond++;
(*pos)++;
ok = process_proxy_cond_adders(letters, cond, cond_end, pos,
indent + 1);
cond = *cond_end;
if (ok < 0)
goto end;
while (isspace((int)*cond)) {
cond++;
(*pos)++;
}
c = *cond;
if (c != ')') {
fprintf(stderr,
"Weird condition character in position %d: "
"%c\n", *pos, c);
ok = -1;
goto end;
}
cond++;
(*pos)++;
} else if (isascii(c) && isalpha(c)) {
if (islower(c))
c = toupper(c);
ok = letters[c - 'A'];
cond++;
(*pos)++;
} else {
fprintf(stderr,
"Weird condition character in position %d: " "%c\n", *pos, c);
ok = -1;
goto end;
}
end:
*cond_end = cond;
if (ok >= 0 && negate)
ok = !ok;
if (debug)
process_proxy_debug(indent,
"End process_proxy_cond_val at position %d: %s, returning %d\n",
*pos, cond, ok);
return ok;
}
static int process_proxy_cond_multipliers(unsigned int letters[26],
const char *cond,
const char **cond_end, int *pos,
int indent)
{
int ok;
char c;
if (debug)
process_proxy_debug(indent,
"Start process_proxy_cond_multipliers at position %d: %s\n",
*pos, cond);
ok = process_proxy_cond_val(letters, cond, cond_end, pos, indent + 1);
cond = *cond_end;
if (ok < 0)
goto end;
while (ok >= 0) {
while (isspace((int)*cond)) {
cond++;
(*pos)++;
}
c = *cond;
switch (c) {
case '&':
case '^':
{
int save_ok = ok;
cond++;
(*pos)++;
ok = process_proxy_cond_val(letters,
cond, cond_end, pos, indent + 1);
cond = *cond_end;
if (ok < 0)
break;
switch (c) {
case '&':
ok &= save_ok;
break;
case '^':
ok ^= save_ok;
break;
default:
fprintf(stderr, "SOMETHING IS SERIOUSLY WRONG!"
" STOPPING\n");
EXIT(1);
}
}
break;
default:
goto end;
}
}
end:
if (debug)
process_proxy_debug(indent,
"End process_proxy_cond_multipliers at position %d: %s, returning %d\n",
*pos, cond, ok);
*cond_end = cond;
return ok;
}
static int process_proxy_cond_adders(unsigned int letters[26],
const char *cond, const char **cond_end,
int *pos, int indent)
{
int ok;
char c;
if (debug)
process_proxy_debug(indent,
"Start process_proxy_cond_adders at position %d: %s\n",
*pos, cond);
ok = process_proxy_cond_multipliers(letters, cond, cond_end, pos,
indent + 1);
cond = *cond_end;
if (ok < 0)
goto end;
while (ok >= 0) {
while (isspace((int)*cond)) {
cond++;
(*pos)++;
}
c = *cond;
switch (c) {
case '|':
{
int save_ok = ok;
cond++;
(*pos)++;
ok = process_proxy_cond_multipliers(letters,
cond, cond_end, pos,
indent + 1);
cond = *cond_end;
if (ok < 0)
break;
switch (c) {
case '|':
ok |= save_ok;
break;
default:
fprintf(stderr, "SOMETHING IS SERIOUSLY WRONG!"
" STOPPING\n");
EXIT(1);
}
}
break;
default:
goto end;
}
}
end:
if (debug)
process_proxy_debug(indent,
"End process_proxy_cond_adders at position %d: %s, returning %d\n",
*pos, cond, ok);
*cond_end = cond;
return ok;
}
static int process_proxy_cond(unsigned int letters[26],
const char *cond, const char **cond_end)
{
int pos = 1;
return process_proxy_cond_adders(letters, cond, cond_end, &pos, 1);
}
static int MS_CALLBACK app_verify_callback(X509_STORE_CTX *ctx, void *arg)
{
int ok = 1;
struct app_verify_arg *cb_arg = arg;
unsigned int letters[26]; /* only used with proxy_auth */
if (cb_arg->app_verify) {
char *s = NULL, buf[256];
fprintf(stderr, "In app_verify_callback, allowing cert. ");
fprintf(stderr, "Arg is: %s\n", cb_arg->string);
fprintf(stderr,
"Finished printing do we have a context? 0x%p a cert? 0x%p\n",
(void *)ctx, (void *)ctx->cert);
if (ctx->cert)
s = X509_NAME_oneline(X509_get_subject_name(ctx->cert), buf, 256);
if (s != NULL) {
fprintf(stderr, "cert depth=%d %s\n", ctx->error_depth, buf);
}
return (1);
}
if (cb_arg->proxy_auth) {
int found_any = 0, i;
char *sp;
for (i = 0; i < 26; i++)
letters[i] = 0;
for (sp = cb_arg->proxy_auth; *sp; sp++) {
int c = *sp;
if (isascii(c) && isalpha(c)) {
if (islower(c))
c = toupper(c);
letters[c - 'A'] = 1;
}
}
fprintf(stderr, " Initial proxy rights = ");
for (i = 0; i < 26; i++)
if (letters[i]) {
fprintf(stderr, "%c", i + 'A');
found_any = 1;
}
if (!found_any)
fprintf(stderr, "none");
fprintf(stderr, "\n");
X509_STORE_CTX_set_ex_data(ctx,
get_proxy_auth_ex_data_idx(), letters);
}
if (cb_arg->allow_proxy_certs) {
X509_STORE_CTX_set_flags(ctx, X509_V_FLAG_ALLOW_PROXY_CERTS);
}
#ifndef OPENSSL_NO_X509_VERIFY
ok = X509_verify_cert(ctx);
#endif
if (cb_arg->proxy_auth) {
if (ok > 0) {
const char *cond_end = NULL;
ok = process_proxy_cond(letters, cb_arg->proxy_cond, &cond_end);
if (ok < 0)
EXIT(3);
if (*cond_end) {
fprintf(stderr,
"Stopped processing condition before it's end.\n");
ok = 0;
}
if (!ok)
fprintf(stderr,
"Proxy rights check with condition '%s' proved invalid\n",
cb_arg->proxy_cond);
else
fprintf(stderr,
"Proxy rights check with condition '%s' proved valid\n",
cb_arg->proxy_cond);
}
}
return (ok);
}
#ifndef OPENSSL_NO_RSA
static RSA *rsa_tmp = NULL;
static RSA MS_CALLBACK *tmp_rsa_cb(SSL *s, int is_export, int keylength)
{
BIGNUM *bn = NULL;
if (rsa_tmp == NULL) {
bn = BN_new();
rsa_tmp = RSA_new();
if (!bn || !rsa_tmp || !BN_set_word(bn, RSA_F4)) {
BIO_printf(bio_err, "Memory error...");
goto end;
}
BIO_printf(bio_err, "Generating temp (%d bit) RSA key...", keylength);
(void)BIO_flush(bio_err);
if (!RSA_generate_key_ex(rsa_tmp, keylength, bn, NULL)) {
BIO_printf(bio_err, "Error generating key.");
RSA_free(rsa_tmp);
rsa_tmp = NULL;
}
end:
BIO_printf(bio_err, "\n");
(void)BIO_flush(bio_err);
}
if (bn)
BN_free(bn);
return (rsa_tmp);
}
static void free_tmp_rsa(void)
{
if (rsa_tmp != NULL) {
RSA_free(rsa_tmp);
rsa_tmp = NULL;
}
}
#endif
#ifndef OPENSSL_NO_DH
/*-
* These DH parameters have been generated as follows:
* $ openssl dhparam -C -noout 512
* $ openssl dhparam -C -noout 1024
* $ openssl dhparam -C -noout -dsaparam 1024
* (The third function has been renamed to avoid name conflicts.)
*/
static DH *get_dh512()
{
static unsigned char dh512_p[] = {
0xCB, 0xC8, 0xE1, 0x86, 0xD0, 0x1F, 0x94, 0x17, 0xA6, 0x99, 0xF0,
0xC6,
0x1F, 0x0D, 0xAC, 0xB6, 0x25, 0x3E, 0x06, 0x39, 0xCA, 0x72, 0x04,
0xB0,
0x6E, 0xDA, 0xC0, 0x61, 0xE6, 0x7A, 0x77, 0x25, 0xE8, 0x3B, 0xB9,
0x5F,
0x9A, 0xB6, 0xB5, 0xFE, 0x99, 0x0B, 0xA1, 0x93, 0x4E, 0x35, 0x33,
0xB8,
0xE1, 0xF1, 0x13, 0x4F, 0x59, 0x1A, 0xD2, 0x57, 0xC0, 0x26, 0x21,
0x33,
0x02, 0xC5, 0xAE, 0x23,
};
static unsigned char dh512_g[] = {
0x02,
};
DH *dh;
if ((dh = DH_new()) == NULL)
return (NULL);
dh->p = BN_bin2bn(dh512_p, sizeof(dh512_p), NULL);
dh->g = BN_bin2bn(dh512_g, sizeof(dh512_g), NULL);
if ((dh->p == NULL) || (dh->g == NULL)) {
DH_free(dh);
return (NULL);
}
return (dh);
}
static DH *get_dh1024()
{
static unsigned char dh1024_p[] = {
0xF8, 0x81, 0x89, 0x7D, 0x14, 0x24, 0xC5, 0xD1, 0xE6, 0xF7, 0xBF,
0x3A,
0xE4, 0x90, 0xF4, 0xFC, 0x73, 0xFB, 0x34, 0xB5, 0xFA, 0x4C, 0x56,
0xA2,
0xEA, 0xA7, 0xE9, 0xC0, 0xC0, 0xCE, 0x89, 0xE1, 0xFA, 0x63, 0x3F,
0xB0,
0x6B, 0x32, 0x66, 0xF1, 0xD1, 0x7B, 0xB0, 0x00, 0x8F, 0xCA, 0x87,
0xC2,
0xAE, 0x98, 0x89, 0x26, 0x17, 0xC2, 0x05, 0xD2, 0xEC, 0x08, 0xD0,
0x8C,
0xFF, 0x17, 0x52, 0x8C, 0xC5, 0x07, 0x93, 0x03, 0xB1, 0xF6, 0x2F,
0xB8,
0x1C, 0x52, 0x47, 0x27, 0x1B, 0xDB, 0xD1, 0x8D, 0x9D, 0x69, 0x1D,
0x52,
0x4B, 0x32, 0x81, 0xAA, 0x7F, 0x00, 0xC8, 0xDC, 0xE6, 0xD9, 0xCC,
0xC1,
0x11, 0x2D, 0x37, 0x34, 0x6C, 0xEA, 0x02, 0x97, 0x4B, 0x0E, 0xBB,
0xB1,
0x71, 0x33, 0x09, 0x15, 0xFD, 0xDD, 0x23, 0x87, 0x07, 0x5E, 0x89,
0xAB,
0x6B, 0x7C, 0x5F, 0xEC, 0xA6, 0x24, 0xDC, 0x53,
};
static unsigned char dh1024_g[] = {
0x02,
};
DH *dh;
if ((dh = DH_new()) == NULL)
return (NULL);
dh->p = BN_bin2bn(dh1024_p, sizeof(dh1024_p), NULL);
dh->g = BN_bin2bn(dh1024_g, sizeof(dh1024_g), NULL);
if ((dh->p == NULL) || (dh->g == NULL)) {
DH_free(dh);
return (NULL);
}
return (dh);
}
static DH *get_dh1024dsa()
{
static unsigned char dh1024_p[] = {
0xC8, 0x00, 0xF7, 0x08, 0x07, 0x89, 0x4D, 0x90, 0x53, 0xF3, 0xD5,
0x00,
0x21, 0x1B, 0xF7, 0x31, 0xA6, 0xA2, 0xDA, 0x23, 0x9A, 0xC7, 0x87,
0x19,
0x3B, 0x47, 0xB6, 0x8C, 0x04, 0x6F, 0xFF, 0xC6, 0x9B, 0xB8, 0x65,
0xD2,
0xC2, 0x5F, 0x31, 0x83, 0x4A, 0xA7, 0x5F, 0x2F, 0x88, 0x38, 0xB6,
0x55,
0xCF, 0xD9, 0x87, 0x6D, 0x6F, 0x9F, 0xDA, 0xAC, 0xA6, 0x48, 0xAF,
0xFC,
0x33, 0x84, 0x37, 0x5B, 0x82, 0x4A, 0x31, 0x5D, 0xE7, 0xBD, 0x52,
0x97,
0xA1, 0x77, 0xBF, 0x10, 0x9E, 0x37, 0xEA, 0x64, 0xFA, 0xCA, 0x28,
0x8D,
0x9D, 0x3B, 0xD2, 0x6E, 0x09, 0x5C, 0x68, 0xC7, 0x45, 0x90, 0xFD,
0xBB,
0x70, 0xC9, 0x3A, 0xBB, 0xDF, 0xD4, 0x21, 0x0F, 0xC4, 0x6A, 0x3C,
0xF6,
0x61, 0xCF, 0x3F, 0xD6, 0x13, 0xF1, 0x5F, 0xBC, 0xCF, 0xBC, 0x26,
0x9E,
0xBC, 0x0B, 0xBD, 0xAB, 0x5D, 0xC9, 0x54, 0x39,
};
static unsigned char dh1024_g[] = {
0x3B, 0x40, 0x86, 0xE7, 0xF3, 0x6C, 0xDE, 0x67, 0x1C, 0xCC, 0x80,
0x05,
0x5A, 0xDF, 0xFE, 0xBD, 0x20, 0x27, 0x74, 0x6C, 0x24, 0xC9, 0x03,
0xF3,
0xE1, 0x8D, 0xC3, 0x7D, 0x98, 0x27, 0x40, 0x08, 0xB8, 0x8C, 0x6A,
0xE9,
0xBB, 0x1A, 0x3A, 0xD6, 0x86, 0x83, 0x5E, 0x72, 0x41, 0xCE, 0x85,
0x3C,
0xD2, 0xB3, 0xFC, 0x13, 0xCE, 0x37, 0x81, 0x9E, 0x4C, 0x1C, 0x7B,
0x65,
0xD3, 0xE6, 0xA6, 0x00, 0xF5, 0x5A, 0x95, 0x43, 0x5E, 0x81, 0xCF,
0x60,
0xA2, 0x23, 0xFC, 0x36, 0xA7, 0x5D, 0x7A, 0x4C, 0x06, 0x91, 0x6E,
0xF6,
0x57, 0xEE, 0x36, 0xCB, 0x06, 0xEA, 0xF5, 0x3D, 0x95, 0x49, 0xCB,
0xA7,
0xDD, 0x81, 0xDF, 0x80, 0x09, 0x4A, 0x97, 0x4D, 0xA8, 0x22, 0x72,
0xA1,
0x7F, 0xC4, 0x70, 0x56, 0x70, 0xE8, 0x20, 0x10, 0x18, 0x8F, 0x2E,
0x60,
0x07, 0xE7, 0x68, 0x1A, 0x82, 0x5D, 0x32, 0xA2,
};
DH *dh;
if ((dh = DH_new()) == NULL)
return (NULL);
dh->p = BN_bin2bn(dh1024_p, sizeof(dh1024_p), NULL);
dh->g = BN_bin2bn(dh1024_g, sizeof(dh1024_g), NULL);
if ((dh->p == NULL) || (dh->g == NULL)) {
DH_free(dh);
return (NULL);
}
dh->length = 160;
return (dh);
}
#endif
#ifndef OPENSSL_NO_PSK
/* convert the PSK key (psk_key) in ascii to binary (psk) */
static int psk_key2bn(const char *pskkey, unsigned char *psk,
unsigned int max_psk_len)
{
int ret;
BIGNUM *bn = NULL;
ret = BN_hex2bn(&bn, pskkey);
if (!ret) {
BIO_printf(bio_err, "Could not convert PSK key '%s' to BIGNUM\n",
pskkey);
if (bn)
BN_free(bn);
return 0;
}
if (BN_num_bytes(bn) > (int)max_psk_len) {
BIO_printf(bio_err,
"psk buffer of callback is too small (%d) for key (%d)\n",
max_psk_len, BN_num_bytes(bn));
BN_free(bn);
return 0;
}
ret = BN_bn2bin(bn, psk);
BN_free(bn);
return ret;
}
static unsigned int psk_client_callback(SSL *ssl, const char *hint,
char *identity,
unsigned int max_identity_len,
unsigned char *psk,
unsigned int max_psk_len)
{
int ret;
unsigned int psk_len = 0;
ret = BIO_snprintf(identity, max_identity_len, "Client_identity");
if (ret < 0)
goto out_err;
if (debug)
fprintf(stderr, "client: created identity '%s' len=%d\n", identity,
ret);
ret = psk_key2bn(psk_key, psk, max_psk_len);
if (ret < 0)
goto out_err;
psk_len = ret;
out_err:
return psk_len;
}
static unsigned int psk_server_callback(SSL *ssl, const char *identity,
unsigned char *psk,
unsigned int max_psk_len)
{
unsigned int psk_len = 0;
if (strcmp(identity, "Client_identity") != 0) {
BIO_printf(bio_err, "server: PSK error: client identity not found\n");
return 0;
}
psk_len = psk_key2bn(psk_key, psk, max_psk_len);
return psk_len;
}
#endif
static int do_test_cipherlist(void)
{
#if !defined(OPENSSL_NO_SSL2) || !defined(OPENSSL_NO_SSL3) || \
!defined(OPENSSL_NO_TLS1)
int i = 0;
const SSL_METHOD *meth;
const SSL_CIPHER *ci, *tci = NULL;
#endif
#ifndef OPENSSL_NO_SSL2
fprintf(stderr, "testing SSLv2 cipher list order: ");
meth = SSLv2_method();
while ((ci = meth->get_cipher(i++)) != NULL) {
if (tci != NULL)
if (ci->id >= tci->id) {
fprintf(stderr, "failed %lx vs. %lx\n", ci->id, tci->id);
return 0;
}
tci = ci;
}
fprintf(stderr, "ok\n");
#endif
#ifndef OPENSSL_NO_SSL3
fprintf(stderr, "testing SSLv3 cipher list order: ");
meth = SSLv3_method();
tci = NULL;
while ((ci = meth->get_cipher(i++)) != NULL) {
if (tci != NULL)
if (ci->id >= tci->id) {
fprintf(stderr, "failed %lx vs. %lx\n", ci->id, tci->id);
return 0;
}
tci = ci;
}
fprintf(stderr, "ok\n");
#endif
#ifndef OPENSSL_NO_TLS1
fprintf(stderr, "testing TLSv1 cipher list order: ");
meth = TLSv1_method();
tci = NULL;
while ((ci = meth->get_cipher(i++)) != NULL) {
if (tci != NULL)
if (ci->id >= tci->id) {
fprintf(stderr, "failed %lx vs. %lx\n", ci->id, tci->id);
return 0;
}
tci = ci;
}
fprintf(stderr, "ok\n");
#endif
return 1;
}
diff --git a/ssl/t1_enc.c b/ssl/t1_enc.c
index b6d1ee95a521..50491ff62ff4 100644
--- a/ssl/t1_enc.c
+++ b/ssl/t1_enc.c
@@ -1,1376 +1,1376 @@
/* ssl/t1_enc.c */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
/* ====================================================================
* Copyright (c) 1998-2007 The OpenSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* openssl-core@openssl.org.
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.openssl.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*
* This product includes cryptographic software written by Eric Young
* (eay@cryptsoft.com). This product includes software written by Tim
* Hudson (tjh@cryptsoft.com).
*
*/
/* ====================================================================
* Copyright 2005 Nokia. All rights reserved.
*
* The portions of the attached software ("Contribution") is developed by
* Nokia Corporation and is licensed pursuant to the OpenSSL open source
* license.
*
* The Contribution, originally written by Mika Kousa and Pasi Eronen of
* Nokia Corporation, consists of the "PSK" (Pre-Shared Key) ciphersuites
* support (see RFC 4279) to OpenSSL.
*
* No patent licenses or other rights except those expressly stated in
* the OpenSSL open source license shall be deemed granted or received
* expressly, by implication, estoppel, or otherwise.
*
* No assurances are provided by Nokia that the Contribution does not
* infringe the patent or other intellectual property rights of any third
* party or that the license provides you with all the necessary rights
* to make use of the Contribution.
*
* THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. IN
* ADDITION TO THE DISCLAIMERS INCLUDED IN THE LICENSE, NOKIA
* SPECIFICALLY DISCLAIMS ANY LIABILITY FOR CLAIMS BROUGHT BY YOU OR ANY
* OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS OR
* OTHERWISE.
*/
#include <stdio.h>
#include "ssl_locl.h"
#ifndef OPENSSL_NO_COMP
# include <openssl/comp.h>
#endif
#include <openssl/evp.h>
#include <openssl/hmac.h>
#include <openssl/md5.h>
#include <openssl/rand.h>
#ifdef KSSL_DEBUG
# include <openssl/des.h>
#endif
/* seed1 through seed5 are virtually concatenated */
static int tls1_P_hash(const EVP_MD *md, const unsigned char *sec,
int sec_len,
const void *seed1, int seed1_len,
const void *seed2, int seed2_len,
const void *seed3, int seed3_len,
const void *seed4, int seed4_len,
const void *seed5, int seed5_len,
unsigned char *out, int olen)
{
int chunk;
size_t j;
EVP_MD_CTX ctx, ctx_tmp, ctx_init;
EVP_PKEY *mac_key;
unsigned char A1[EVP_MAX_MD_SIZE];
size_t A1_len;
int ret = 0;
chunk = EVP_MD_size(md);
OPENSSL_assert(chunk >= 0);
EVP_MD_CTX_init(&ctx);
EVP_MD_CTX_init(&ctx_tmp);
EVP_MD_CTX_init(&ctx_init);
EVP_MD_CTX_set_flags(&ctx_init, EVP_MD_CTX_FLAG_NON_FIPS_ALLOW);
mac_key = EVP_PKEY_new_mac_key(EVP_PKEY_HMAC, NULL, sec, sec_len);
if (!mac_key)
goto err;
if (!EVP_DigestSignInit(&ctx_init, NULL, md, NULL, mac_key))
goto err;
if (!EVP_MD_CTX_copy_ex(&ctx, &ctx_init))
goto err;
if (seed1 && !EVP_DigestSignUpdate(&ctx, seed1, seed1_len))
goto err;
if (seed2 && !EVP_DigestSignUpdate(&ctx, seed2, seed2_len))
goto err;
if (seed3 && !EVP_DigestSignUpdate(&ctx, seed3, seed3_len))
goto err;
if (seed4 && !EVP_DigestSignUpdate(&ctx, seed4, seed4_len))
goto err;
if (seed5 && !EVP_DigestSignUpdate(&ctx, seed5, seed5_len))
goto err;
if (!EVP_DigestSignFinal(&ctx, A1, &A1_len))
goto err;
for (;;) {
/* Reinit mac contexts */
if (!EVP_MD_CTX_copy_ex(&ctx, &ctx_init))
goto err;
if (!EVP_DigestSignUpdate(&ctx, A1, A1_len))
goto err;
if (olen > chunk && !EVP_MD_CTX_copy_ex(&ctx_tmp, &ctx))
goto err;
if (seed1 && !EVP_DigestSignUpdate(&ctx, seed1, seed1_len))
goto err;
if (seed2 && !EVP_DigestSignUpdate(&ctx, seed2, seed2_len))
goto err;
if (seed3 && !EVP_DigestSignUpdate(&ctx, seed3, seed3_len))
goto err;
if (seed4 && !EVP_DigestSignUpdate(&ctx, seed4, seed4_len))
goto err;
if (seed5 && !EVP_DigestSignUpdate(&ctx, seed5, seed5_len))
goto err;
if (olen > chunk) {
if (!EVP_DigestSignFinal(&ctx, out, &j))
goto err;
out += j;
olen -= j;
/* calc the next A1 value */
if (!EVP_DigestSignFinal(&ctx_tmp, A1, &A1_len))
goto err;
} else { /* last one */
if (!EVP_DigestSignFinal(&ctx, A1, &A1_len))
goto err;
memcpy(out, A1, olen);
break;
}
}
ret = 1;
err:
EVP_PKEY_free(mac_key);
EVP_MD_CTX_cleanup(&ctx);
EVP_MD_CTX_cleanup(&ctx_tmp);
EVP_MD_CTX_cleanup(&ctx_init);
OPENSSL_cleanse(A1, sizeof(A1));
return ret;
}
/* seed1 through seed5 are virtually concatenated */
static int tls1_PRF(long digest_mask,
const void *seed1, int seed1_len,
const void *seed2, int seed2_len,
const void *seed3, int seed3_len,
const void *seed4, int seed4_len,
const void *seed5, int seed5_len,
const unsigned char *sec, int slen,
unsigned char *out1, unsigned char *out2, int olen)
{
int len, i, idx, count;
const unsigned char *S1;
long m;
const EVP_MD *md;
int ret = 0;
/* Count number of digests and partition sec evenly */
count = 0;
for (idx = 0; ssl_get_handshake_digest(idx, &m, &md); idx++) {
if ((m << TLS1_PRF_DGST_SHIFT) & digest_mask)
count++;
}
if (!count) {
/* Should never happen */
SSLerr(SSL_F_TLS1_PRF, ERR_R_INTERNAL_ERROR);
goto err;
}
len = slen / count;
if (count == 1)
slen = 0;
S1 = sec;
memset(out1, 0, olen);
for (idx = 0; ssl_get_handshake_digest(idx, &m, &md); idx++) {
if ((m << TLS1_PRF_DGST_SHIFT) & digest_mask) {
if (!md) {
SSLerr(SSL_F_TLS1_PRF, SSL_R_UNSUPPORTED_DIGEST_TYPE);
goto err;
}
if (!tls1_P_hash(md, S1, len + (slen & 1),
seed1, seed1_len, seed2, seed2_len, seed3,
seed3_len, seed4, seed4_len, seed5, seed5_len,
out2, olen))
goto err;
S1 += len;
for (i = 0; i < olen; i++) {
out1[i] ^= out2[i];
}
}
}
ret = 1;
err:
return ret;
}
static int tls1_generate_key_block(SSL *s, unsigned char *km,
unsigned char *tmp, int num)
{
int ret;
ret = tls1_PRF(ssl_get_algorithm2(s),
TLS_MD_KEY_EXPANSION_CONST,
TLS_MD_KEY_EXPANSION_CONST_SIZE, s->s3->server_random,
SSL3_RANDOM_SIZE, s->s3->client_random, SSL3_RANDOM_SIZE,
NULL, 0, NULL, 0, s->session->master_key,
s->session->master_key_length, km, tmp, num);
#ifdef KSSL_DEBUG
fprintf(stderr, "tls1_generate_key_block() ==> %d byte master_key =\n\t",
s->session->master_key_length);
{
int i;
for (i = 0; i < s->session->master_key_length; i++) {
fprintf(stderr, "%02X", s->session->master_key[i]);
}
fprintf(stderr, "\n");
}
#endif /* KSSL_DEBUG */
return ret;
}
int tls1_change_cipher_state(SSL *s, int which)
{
static const unsigned char empty[] = "";
unsigned char *p, *mac_secret;
unsigned char *exp_label;
unsigned char tmp1[EVP_MAX_KEY_LENGTH];
unsigned char tmp2[EVP_MAX_KEY_LENGTH];
unsigned char iv1[EVP_MAX_IV_LENGTH * 2];
unsigned char iv2[EVP_MAX_IV_LENGTH * 2];
unsigned char *ms, *key, *iv;
int client_write;
EVP_CIPHER_CTX *dd;
const EVP_CIPHER *c;
#ifndef OPENSSL_NO_COMP
const SSL_COMP *comp;
#endif
const EVP_MD *m;
int mac_type;
int *mac_secret_size;
EVP_MD_CTX *mac_ctx;
EVP_PKEY *mac_key;
int is_export, n, i, j, k, exp_label_len, cl;
int reuse_dd = 0;
is_export = SSL_C_IS_EXPORT(s->s3->tmp.new_cipher);
c = s->s3->tmp.new_sym_enc;
m = s->s3->tmp.new_hash;
mac_type = s->s3->tmp.new_mac_pkey_type;
#ifndef OPENSSL_NO_COMP
comp = s->s3->tmp.new_compression;
#endif
#ifdef KSSL_DEBUG
fprintf(stderr, "tls1_change_cipher_state(which= %d) w/\n", which);
fprintf(stderr, "\talg= %ld/%ld, comp= %p\n",
s->s3->tmp.new_cipher->algorithm_mkey,
s->s3->tmp.new_cipher->algorithm_auth, comp);
fprintf(stderr, "\tevp_cipher == %p ==? &d_cbc_ede_cipher3\n", c);
fprintf(stderr, "\tevp_cipher: nid, blksz= %d, %d, keylen=%d, ivlen=%d\n",
c->nid, c->block_size, c->key_len, c->iv_len);
fprintf(stderr, "\tkey_block: len= %d, data= ",
s->s3->tmp.key_block_length);
{
int i;
for (i = 0; i < s->s3->tmp.key_block_length; i++)
fprintf(stderr, "%02x", s->s3->tmp.key_block[i]);
fprintf(stderr, "\n");
}
#endif /* KSSL_DEBUG */
if (which & SSL3_CC_READ) {
if (s->s3->tmp.new_cipher->algorithm2 & TLS1_STREAM_MAC)
s->mac_flags |= SSL_MAC_FLAG_READ_MAC_STREAM;
else
s->mac_flags &= ~SSL_MAC_FLAG_READ_MAC_STREAM;
if (s->enc_read_ctx != NULL)
reuse_dd = 1;
else if ((s->enc_read_ctx =
OPENSSL_malloc(sizeof(EVP_CIPHER_CTX))) == NULL)
goto err;
else
/*
* make sure it's intialized in case we exit later with an error
*/
EVP_CIPHER_CTX_init(s->enc_read_ctx);
dd = s->enc_read_ctx;
mac_ctx = ssl_replace_hash(&s->read_hash, NULL);
if (mac_ctx == NULL)
goto err;
#ifndef OPENSSL_NO_COMP
if (s->expand != NULL) {
COMP_CTX_free(s->expand);
s->expand = NULL;
}
if (comp != NULL) {
s->expand = COMP_CTX_new(comp->method);
if (s->expand == NULL) {
SSLerr(SSL_F_TLS1_CHANGE_CIPHER_STATE,
SSL_R_COMPRESSION_LIBRARY_ERROR);
goto err2;
}
if (s->s3->rrec.comp == NULL)
s->s3->rrec.comp = (unsigned char *)
OPENSSL_malloc(SSL3_RT_MAX_ENCRYPTED_LENGTH);
if (s->s3->rrec.comp == NULL)
goto err;
}
#endif
/*
* this is done by dtls1_reset_seq_numbers for DTLS
*/
if (!SSL_IS_DTLS(s))
memset(&(s->s3->read_sequence[0]), 0, 8);
mac_secret = &(s->s3->read_mac_secret[0]);
mac_secret_size = &(s->s3->read_mac_secret_size);
} else {
if (s->s3->tmp.new_cipher->algorithm2 & TLS1_STREAM_MAC)
s->mac_flags |= SSL_MAC_FLAG_WRITE_MAC_STREAM;
else
s->mac_flags &= ~SSL_MAC_FLAG_WRITE_MAC_STREAM;
if (s->enc_write_ctx != NULL && !SSL_IS_DTLS(s))
reuse_dd = 1;
else if ((s->enc_write_ctx = EVP_CIPHER_CTX_new()) == NULL)
goto err;
dd = s->enc_write_ctx;
if (SSL_IS_DTLS(s)) {
mac_ctx = EVP_MD_CTX_create();
if (mac_ctx == NULL)
goto err;
s->write_hash = mac_ctx;
} else {
mac_ctx = ssl_replace_hash(&s->write_hash, NULL);
if (mac_ctx == NULL)
goto err;
}
#ifndef OPENSSL_NO_COMP
if (s->compress != NULL) {
COMP_CTX_free(s->compress);
s->compress = NULL;
}
if (comp != NULL) {
s->compress = COMP_CTX_new(comp->method);
if (s->compress == NULL) {
SSLerr(SSL_F_TLS1_CHANGE_CIPHER_STATE,
SSL_R_COMPRESSION_LIBRARY_ERROR);
goto err2;
}
}
#endif
/*
* this is done by dtls1_reset_seq_numbers for DTLS
*/
if (!SSL_IS_DTLS(s))
memset(&(s->s3->write_sequence[0]), 0, 8);
mac_secret = &(s->s3->write_mac_secret[0]);
mac_secret_size = &(s->s3->write_mac_secret_size);
}
if (reuse_dd)
EVP_CIPHER_CTX_cleanup(dd);
p = s->s3->tmp.key_block;
i = *mac_secret_size = s->s3->tmp.new_mac_secret_size;
cl = EVP_CIPHER_key_length(c);
j = is_export ? (cl < SSL_C_EXPORT_KEYLENGTH(s->s3->tmp.new_cipher) ?
cl : SSL_C_EXPORT_KEYLENGTH(s->s3->tmp.new_cipher)) : cl;
/* Was j=(exp)?5:EVP_CIPHER_key_length(c); */
/* If GCM mode only part of IV comes from PRF */
if (EVP_CIPHER_mode(c) == EVP_CIPH_GCM_MODE)
k = EVP_GCM_TLS_FIXED_IV_LEN;
else
k = EVP_CIPHER_iv_length(c);
if ((which == SSL3_CHANGE_CIPHER_CLIENT_WRITE) ||
(which == SSL3_CHANGE_CIPHER_SERVER_READ)) {
ms = &(p[0]);
n = i + i;
key = &(p[n]);
n += j + j;
iv = &(p[n]);
n += k + k;
exp_label = (unsigned char *)TLS_MD_CLIENT_WRITE_KEY_CONST;
exp_label_len = TLS_MD_CLIENT_WRITE_KEY_CONST_SIZE;
client_write = 1;
} else {
n = i;
ms = &(p[n]);
n += i + j;
key = &(p[n]);
n += j + k;
iv = &(p[n]);
n += k;
exp_label = (unsigned char *)TLS_MD_SERVER_WRITE_KEY_CONST;
exp_label_len = TLS_MD_SERVER_WRITE_KEY_CONST_SIZE;
client_write = 0;
}
if (n > s->s3->tmp.key_block_length) {
SSLerr(SSL_F_TLS1_CHANGE_CIPHER_STATE, ERR_R_INTERNAL_ERROR);
goto err2;
}
memcpy(mac_secret, ms, i);
if (!(EVP_CIPHER_flags(c) & EVP_CIPH_FLAG_AEAD_CIPHER)) {
mac_key = EVP_PKEY_new_mac_key(mac_type, NULL,
mac_secret, *mac_secret_size);
if (mac_key == NULL
|| EVP_DigestSignInit(mac_ctx, NULL, m, NULL, mac_key) <= 0) {
EVP_PKEY_free(mac_key);
SSLerr(SSL_F_TLS1_CHANGE_CIPHER_STATE, ERR_R_INTERNAL_ERROR);
goto err2;
}
EVP_PKEY_free(mac_key);
}
#ifdef TLS_DEBUG
printf("which = %04X\nmac key=", which);
{
int z;
for (z = 0; z < i; z++)
printf("%02X%c", ms[z], ((z + 1) % 16) ? ' ' : '\n');
}
#endif
if (is_export) {
/*
* In here I set both the read and write key/iv to the same value
* since only the correct one will be used :-).
*/
if (!tls1_PRF(ssl_get_algorithm2(s),
exp_label, exp_label_len,
s->s3->client_random, SSL3_RANDOM_SIZE,
s->s3->server_random, SSL3_RANDOM_SIZE,
NULL, 0, NULL, 0,
key, j, tmp1, tmp2, EVP_CIPHER_key_length(c)))
goto err2;
key = tmp1;
if (k > 0) {
if (!tls1_PRF(ssl_get_algorithm2(s),
TLS_MD_IV_BLOCK_CONST, TLS_MD_IV_BLOCK_CONST_SIZE,
s->s3->client_random, SSL3_RANDOM_SIZE,
s->s3->server_random, SSL3_RANDOM_SIZE,
NULL, 0, NULL, 0, empty, 0, iv1, iv2, k * 2))
goto err2;
if (client_write)
iv = iv1;
else
iv = &(iv1[k]);
}
}
s->session->key_arg_length = 0;
#ifdef KSSL_DEBUG
{
int i;
fprintf(stderr, "EVP_CipherInit_ex(dd,c,key=,iv=,which)\n");
fprintf(stderr, "\tkey= ");
for (i = 0; i < c->key_len; i++)
fprintf(stderr, "%02x", key[i]);
fprintf(stderr, "\n");
fprintf(stderr, "\t iv= ");
for (i = 0; i < c->iv_len; i++)
fprintf(stderr, "%02x", iv[i]);
fprintf(stderr, "\n");
}
#endif /* KSSL_DEBUG */
if (EVP_CIPHER_mode(c) == EVP_CIPH_GCM_MODE) {
if (!EVP_CipherInit_ex(dd, c, NULL, key, NULL, (which & SSL3_CC_WRITE))
|| !EVP_CIPHER_CTX_ctrl(dd, EVP_CTRL_GCM_SET_IV_FIXED, k, iv)) {
SSLerr(SSL_F_TLS1_CHANGE_CIPHER_STATE, ERR_R_INTERNAL_ERROR);
goto err2;
}
} else {
if (!EVP_CipherInit_ex(dd, c, NULL, key, iv, (which & SSL3_CC_WRITE))) {
SSLerr(SSL_F_TLS1_CHANGE_CIPHER_STATE, ERR_R_INTERNAL_ERROR);
goto err2;
}
}
/* Needed for "composite" AEADs, such as RC4-HMAC-MD5 */
if ((EVP_CIPHER_flags(c) & EVP_CIPH_FLAG_AEAD_CIPHER) && *mac_secret_size
&& !EVP_CIPHER_CTX_ctrl(dd, EVP_CTRL_AEAD_SET_MAC_KEY,
*mac_secret_size, mac_secret)) {
SSLerr(SSL_F_TLS1_CHANGE_CIPHER_STATE, ERR_R_INTERNAL_ERROR);
goto err2;
}
#ifdef OPENSSL_SSL_TRACE_CRYPTO
if (s->msg_callback) {
int wh = which & SSL3_CC_WRITE ? TLS1_RT_CRYPTO_WRITE : 0;
if (*mac_secret_size)
s->msg_callback(2, s->version, wh | TLS1_RT_CRYPTO_MAC,
mac_secret, *mac_secret_size,
s, s->msg_callback_arg);
if (c->key_len)
s->msg_callback(2, s->version, wh | TLS1_RT_CRYPTO_KEY,
key, c->key_len, s, s->msg_callback_arg);
if (k) {
if (EVP_CIPHER_mode(c) == EVP_CIPH_GCM_MODE)
wh |= TLS1_RT_CRYPTO_FIXED_IV;
else
wh |= TLS1_RT_CRYPTO_IV;
s->msg_callback(2, s->version, wh, iv, k, s, s->msg_callback_arg);
}
}
#endif
#ifdef TLS_DEBUG
printf("which = %04X\nkey=", which);
{
int z;
for (z = 0; z < EVP_CIPHER_key_length(c); z++)
printf("%02X%c", key[z], ((z + 1) % 16) ? ' ' : '\n');
}
printf("\niv=");
{
int z;
for (z = 0; z < k; z++)
printf("%02X%c", iv[z], ((z + 1) % 16) ? ' ' : '\n');
}
printf("\n");
#endif
OPENSSL_cleanse(tmp1, sizeof(tmp1));
OPENSSL_cleanse(tmp2, sizeof(tmp1));
OPENSSL_cleanse(iv1, sizeof(iv1));
OPENSSL_cleanse(iv2, sizeof(iv2));
return (1);
err:
SSLerr(SSL_F_TLS1_CHANGE_CIPHER_STATE, ERR_R_MALLOC_FAILURE);
err2:
return (0);
}
int tls1_setup_key_block(SSL *s)
{
unsigned char *p1, *p2 = NULL;
const EVP_CIPHER *c;
const EVP_MD *hash;
int num;
SSL_COMP *comp;
int mac_type = NID_undef, mac_secret_size = 0;
int ret = 0;
#ifdef KSSL_DEBUG
fprintf(stderr, "tls1_setup_key_block()\n");
#endif /* KSSL_DEBUG */
if (s->s3->tmp.key_block_length != 0)
return (1);
if (!ssl_cipher_get_evp
(s->session, &c, &hash, &mac_type, &mac_secret_size, &comp)) {
SSLerr(SSL_F_TLS1_SETUP_KEY_BLOCK, SSL_R_CIPHER_OR_HASH_UNAVAILABLE);
return (0);
}
s->s3->tmp.new_sym_enc = c;
s->s3->tmp.new_hash = hash;
s->s3->tmp.new_mac_pkey_type = mac_type;
s->s3->tmp.new_mac_secret_size = mac_secret_size;
num =
EVP_CIPHER_key_length(c) + mac_secret_size + EVP_CIPHER_iv_length(c);
num *= 2;
ssl3_cleanup_key_block(s);
if ((p1 = (unsigned char *)OPENSSL_malloc(num)) == NULL) {
SSLerr(SSL_F_TLS1_SETUP_KEY_BLOCK, ERR_R_MALLOC_FAILURE);
goto err;
}
s->s3->tmp.key_block_length = num;
s->s3->tmp.key_block = p1;
if ((p2 = (unsigned char *)OPENSSL_malloc(num)) == NULL) {
SSLerr(SSL_F_TLS1_SETUP_KEY_BLOCK, ERR_R_MALLOC_FAILURE);
goto err;
}
#ifdef TLS_DEBUG
printf("client random\n");
{
int z;
for (z = 0; z < SSL3_RANDOM_SIZE; z++)
printf("%02X%c", s->s3->client_random[z],
((z + 1) % 16) ? ' ' : '\n');
}
printf("server random\n");
{
int z;
for (z = 0; z < SSL3_RANDOM_SIZE; z++)
printf("%02X%c", s->s3->server_random[z],
((z + 1) % 16) ? ' ' : '\n');
}
printf("pre-master\n");
{
int z;
for (z = 0; z < s->session->master_key_length; z++)
printf("%02X%c", s->session->master_key[z],
((z + 1) % 16) ? ' ' : '\n');
}
#endif
if (!tls1_generate_key_block(s, p1, p2, num))
goto err;
#ifdef TLS_DEBUG
printf("\nkey block\n");
{
int z;
for (z = 0; z < num; z++)
printf("%02X%c", p1[z], ((z + 1) % 16) ? ' ' : '\n');
}
#endif
if (!(s->options & SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS)
&& s->method->version <= TLS1_VERSION) {
/*
* enable vulnerability countermeasure for CBC ciphers with known-IV
* problem (http://www.openssl.org/~bodo/tls-cbc.txt)
*/
s->s3->need_empty_fragments = 1;
if (s->session->cipher != NULL) {
if (s->session->cipher->algorithm_enc == SSL_eNULL)
s->s3->need_empty_fragments = 0;
#ifndef OPENSSL_NO_RC4
if (s->session->cipher->algorithm_enc == SSL_RC4)
s->s3->need_empty_fragments = 0;
#endif
}
}
ret = 1;
err:
if (p2) {
OPENSSL_cleanse(p2, num);
OPENSSL_free(p2);
}
return (ret);
}
/*-
* tls1_enc encrypts/decrypts the record in |s->wrec| / |s->rrec|, respectively.
*
* Returns:
* 0: (in non-constant time) if the record is publically invalid (i.e. too
* short etc).
* 1: if the record's padding is valid / the encryption was successful.
* -1: if the record's padding/AEAD-authenticator is invalid or, if sending,
* an internal error occured.
*/
int tls1_enc(SSL *s, int send)
{
SSL3_RECORD *rec;
EVP_CIPHER_CTX *ds;
unsigned long l;
int bs, i, j, k, pad = 0, ret, mac_size = 0;
const EVP_CIPHER *enc;
if (send) {
if (EVP_MD_CTX_md(s->write_hash)) {
int n = EVP_MD_CTX_size(s->write_hash);
OPENSSL_assert(n >= 0);
}
ds = s->enc_write_ctx;
rec = &(s->s3->wrec);
if (s->enc_write_ctx == NULL)
enc = NULL;
else {
int ivlen;
enc = EVP_CIPHER_CTX_cipher(s->enc_write_ctx);
/* For TLSv1.1 and later explicit IV */
if (SSL_USE_EXPLICIT_IV(s)
&& EVP_CIPHER_mode(enc) == EVP_CIPH_CBC_MODE)
ivlen = EVP_CIPHER_iv_length(enc);
else
ivlen = 0;
if (ivlen > 1) {
if (rec->data != rec->input)
/*
* we can't write into the input stream: Can this ever
* happen?? (steve)
*/
fprintf(stderr,
"%s:%d: rec->data != rec->input\n",
__FILE__, __LINE__);
else if (RAND_bytes(rec->input, ivlen) <= 0)
return -1;
}
}
} else {
if (EVP_MD_CTX_md(s->read_hash)) {
int n = EVP_MD_CTX_size(s->read_hash);
OPENSSL_assert(n >= 0);
}
ds = s->enc_read_ctx;
rec = &(s->s3->rrec);
if (s->enc_read_ctx == NULL)
enc = NULL;
else
enc = EVP_CIPHER_CTX_cipher(s->enc_read_ctx);
}
#ifdef KSSL_DEBUG
fprintf(stderr, "tls1_enc(%d)\n", send);
#endif /* KSSL_DEBUG */
if ((s->session == NULL) || (ds == NULL) || (enc == NULL)) {
memmove(rec->data, rec->input, rec->length);
rec->input = rec->data;
ret = 1;
} else {
l = rec->length;
bs = EVP_CIPHER_block_size(ds->cipher);
if (EVP_CIPHER_flags(ds->cipher) & EVP_CIPH_FLAG_AEAD_CIPHER) {
unsigned char buf[EVP_AEAD_TLS1_AAD_LEN], *seq;
seq = send ? s->s3->write_sequence : s->s3->read_sequence;
if (SSL_IS_DTLS(s)) {
unsigned char dtlsseq[9], *p = dtlsseq;
s2n(send ? s->d1->w_epoch : s->d1->r_epoch, p);
memcpy(p, &seq[2], 6);
memcpy(buf, dtlsseq, 8);
} else {
memcpy(buf, seq, 8);
for (i = 7; i >= 0; i--) { /* increment */
++seq[i];
if (seq[i] != 0)
break;
}
}
buf[8] = rec->type;
buf[9] = (unsigned char)(s->version >> 8);
buf[10] = (unsigned char)(s->version);
buf[11] = rec->length >> 8;
buf[12] = rec->length & 0xff;
pad = EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_AEAD_TLS1_AAD,
EVP_AEAD_TLS1_AAD_LEN, buf);
if (pad <= 0)
return -1;
if (send) {
l += pad;
rec->length += pad;
}
} else if ((bs != 1) && send) {
i = bs - ((int)l % bs);
/* Add weird padding of upto 256 bytes */
/* we need to add 'i' padding bytes of value j */
j = i - 1;
if (s->options & SSL_OP_TLS_BLOCK_PADDING_BUG) {
if (s->s3->flags & TLS1_FLAGS_TLS_PADDING_BUG)
j++;
}
for (k = (int)l; k < (int)(l + i); k++)
rec->input[k] = j;
l += i;
rec->length += i;
}
#ifdef KSSL_DEBUG
{
unsigned long ui;
fprintf(stderr,
"EVP_Cipher(ds=%p,rec->data=%p,rec->input=%p,l=%ld) ==>\n",
ds, rec->data, rec->input, l);
fprintf(stderr,
"\tEVP_CIPHER_CTX: %d buf_len, %d key_len [%lu %lu], %d iv_len\n",
ds->buf_len, ds->cipher->key_len, DES_KEY_SZ,
DES_SCHEDULE_SZ, ds->cipher->iv_len);
fprintf(stderr, "\t\tIV: ");
for (i = 0; i < ds->cipher->iv_len; i++)
fprintf(stderr, "%02X", ds->iv[i]);
fprintf(stderr, "\n");
fprintf(stderr, "\trec->input=");
for (ui = 0; ui < l; ui++)
fprintf(stderr, " %02x", rec->input[ui]);
fprintf(stderr, "\n");
}
#endif /* KSSL_DEBUG */
if (!send) {
if (l == 0 || l % bs != 0)
return 0;
}
i = EVP_Cipher(ds, rec->data, rec->input, l);
if ((EVP_CIPHER_flags(ds->cipher) & EVP_CIPH_FLAG_CUSTOM_CIPHER)
? (i < 0)
: (i == 0))
return -1; /* AEAD can fail to verify MAC */
if (EVP_CIPHER_mode(enc) == EVP_CIPH_GCM_MODE && !send) {
rec->data += EVP_GCM_TLS_EXPLICIT_IV_LEN;
rec->input += EVP_GCM_TLS_EXPLICIT_IV_LEN;
rec->length -= EVP_GCM_TLS_EXPLICIT_IV_LEN;
}
#ifdef KSSL_DEBUG
{
unsigned long i;
fprintf(stderr, "\trec->data=");
for (i = 0; i < l; i++)
fprintf(stderr, " %02x", rec->data[i]);
fprintf(stderr, "\n");
}
#endif /* KSSL_DEBUG */
ret = 1;
if (EVP_MD_CTX_md(s->read_hash) != NULL)
mac_size = EVP_MD_CTX_size(s->read_hash);
if ((bs != 1) && !send)
ret = tls1_cbc_remove_padding(s, rec, bs, mac_size);
if (pad && !send)
rec->length -= pad;
}
return ret;
}
int tls1_cert_verify_mac(SSL *s, int md_nid, unsigned char *out)
{
unsigned int ret;
EVP_MD_CTX ctx, *d = NULL;
int i;
if (s->s3->handshake_buffer)
if (!ssl3_digest_cached_records(s))
return 0;
for (i = 0; i < SSL_MAX_DIGEST; i++) {
if (s->s3->handshake_dgst[i]
&& EVP_MD_CTX_type(s->s3->handshake_dgst[i]) == md_nid) {
d = s->s3->handshake_dgst[i];
break;
}
}
if (!d) {
SSLerr(SSL_F_TLS1_CERT_VERIFY_MAC, SSL_R_NO_REQUIRED_DIGEST);
return 0;
}
EVP_MD_CTX_init(&ctx);
if (EVP_MD_CTX_copy_ex(&ctx, d) <=0
|| EVP_DigestFinal_ex(&ctx, out, &ret) <= 0)
ret = 0;
EVP_MD_CTX_cleanup(&ctx);
return ((int)ret);
}
int tls1_final_finish_mac(SSL *s,
const char *str, int slen, unsigned char *out)
{
unsigned int i;
EVP_MD_CTX ctx;
unsigned char buf[2 * EVP_MAX_MD_SIZE];
unsigned char *q, buf2[12];
int idx;
long mask;
int err = 0;
const EVP_MD *md;
q = buf;
if (s->s3->handshake_buffer)
if (!ssl3_digest_cached_records(s))
return 0;
EVP_MD_CTX_init(&ctx);
for (idx = 0; ssl_get_handshake_digest(idx, &mask, &md); idx++) {
if (mask & ssl_get_algorithm2(s)) {
int hashsize = EVP_MD_size(md);
EVP_MD_CTX *hdgst = s->s3->handshake_dgst[idx];
if (!hdgst || hashsize < 0
- || hashsize > (int)(sizeof buf - (size_t)(q - buf))) {
+ || hashsize > (int)(sizeof(buf) - (size_t)(q - buf))) {
/*
* internal error: 'buf' is too small for this cipersuite!
*/
err = 1;
} else {
if (!EVP_MD_CTX_copy_ex(&ctx, hdgst) ||
!EVP_DigestFinal_ex(&ctx, q, &i) ||
(i != (unsigned int)hashsize))
err = 1;
q += hashsize;
}
}
}
if (!tls1_PRF(ssl_get_algorithm2(s),
str, slen, buf, (int)(q - buf), NULL, 0, NULL, 0, NULL, 0,
s->session->master_key, s->session->master_key_length,
- out, buf2, sizeof buf2))
+ out, buf2, sizeof(buf2)))
err = 1;
EVP_MD_CTX_cleanup(&ctx);
OPENSSL_cleanse(buf, (int)(q - buf));
OPENSSL_cleanse(buf2, sizeof(buf2));
if (err)
return 0;
else
- return sizeof buf2;
+ return sizeof(buf2);
}
int tls1_mac(SSL *ssl, unsigned char *md, int send)
{
SSL3_RECORD *rec;
unsigned char *seq;
EVP_MD_CTX *hash;
size_t md_size, orig_len;
int i;
EVP_MD_CTX hmac, *mac_ctx;
unsigned char header[13];
int stream_mac = (send ? (ssl->mac_flags & SSL_MAC_FLAG_WRITE_MAC_STREAM)
: (ssl->mac_flags & SSL_MAC_FLAG_READ_MAC_STREAM));
int t;
if (send) {
rec = &(ssl->s3->wrec);
seq = &(ssl->s3->write_sequence[0]);
hash = ssl->write_hash;
} else {
rec = &(ssl->s3->rrec);
seq = &(ssl->s3->read_sequence[0]);
hash = ssl->read_hash;
}
t = EVP_MD_CTX_size(hash);
OPENSSL_assert(t >= 0);
md_size = t;
/* I should fix this up TLS TLS TLS TLS TLS XXXXXXXX */
if (stream_mac) {
mac_ctx = hash;
} else {
if (!EVP_MD_CTX_copy(&hmac, hash))
return -1;
mac_ctx = &hmac;
}
if (SSL_IS_DTLS(ssl)) {
unsigned char dtlsseq[8], *p = dtlsseq;
s2n(send ? ssl->d1->w_epoch : ssl->d1->r_epoch, p);
memcpy(p, &seq[2], 6);
memcpy(header, dtlsseq, 8);
} else
memcpy(header, seq, 8);
/*
* kludge: tls1_cbc_remove_padding passes padding length in rec->type
*/
orig_len = rec->length + md_size + ((unsigned int)rec->type >> 8);
rec->type &= 0xff;
header[8] = rec->type;
header[9] = (unsigned char)(ssl->version >> 8);
header[10] = (unsigned char)(ssl->version);
header[11] = (rec->length) >> 8;
header[12] = (rec->length) & 0xff;
if (!send &&
EVP_CIPHER_CTX_mode(ssl->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
ssl3_cbc_record_digest_supported(mac_ctx)) {
/*
* This is a CBC-encrypted record. We must avoid leaking any
* timing-side channel information about how many blocks of data we
* are hashing because that gives an attacker a timing-oracle.
*/
/* Final param == not SSLv3 */
if (ssl3_cbc_digest_record(mac_ctx,
md, &md_size,
header, rec->input,
rec->length + md_size, orig_len,
ssl->s3->read_mac_secret,
ssl->s3->read_mac_secret_size, 0) <= 0) {
if (!stream_mac)
EVP_MD_CTX_cleanup(&hmac);
return -1;
}
} else {
if (EVP_DigestSignUpdate(mac_ctx, header, sizeof(header)) <= 0
|| EVP_DigestSignUpdate(mac_ctx, rec->input, rec->length) <= 0
|| EVP_DigestSignFinal(mac_ctx, md, &md_size) <= 0) {
if (!stream_mac)
EVP_MD_CTX_cleanup(&hmac);
return -1;
}
#ifdef OPENSSL_FIPS
if (!send && FIPS_mode())
tls_fips_digest_extra(ssl->enc_read_ctx,
mac_ctx, rec->input, rec->length, orig_len);
#endif
}
if (!stream_mac)
EVP_MD_CTX_cleanup(&hmac);
#ifdef TLS_DEBUG
fprintf(stderr, "seq=");
{
int z;
for (z = 0; z < 8; z++)
fprintf(stderr, "%02X ", seq[z]);
fprintf(stderr, "\n");
}
fprintf(stderr, "rec=");
{
unsigned int z;
for (z = 0; z < rec->length; z++)
fprintf(stderr, "%02X ", rec->data[z]);
fprintf(stderr, "\n");
}
#endif
if (!SSL_IS_DTLS(ssl)) {
for (i = 7; i >= 0; i--) {
++seq[i];
if (seq[i] != 0)
break;
}
}
#ifdef TLS_DEBUG
{
unsigned int z;
for (z = 0; z < md_size; z++)
fprintf(stderr, "%02X ", md[z]);
fprintf(stderr, "\n");
}
#endif
return (md_size);
}
int tls1_generate_master_secret(SSL *s, unsigned char *out, unsigned char *p,
int len)
{
unsigned char buff[SSL_MAX_MASTER_KEY_LENGTH];
const void *co = NULL, *so = NULL;
int col = 0, sol = 0;
#ifdef KSSL_DEBUG
fprintf(stderr, "tls1_generate_master_secret(%p,%p, %p, %d)\n", s, out, p,
len);
#endif /* KSSL_DEBUG */
#ifdef TLSEXT_TYPE_opaque_prf_input
if (s->s3->client_opaque_prf_input != NULL
&& s->s3->server_opaque_prf_input != NULL
&& s->s3->client_opaque_prf_input_len > 0
&& s->s3->client_opaque_prf_input_len ==
s->s3->server_opaque_prf_input_len) {
co = s->s3->client_opaque_prf_input;
col = s->s3->server_opaque_prf_input_len;
so = s->s3->server_opaque_prf_input;
/*
* must be same as col (see
* draft-rescorla-tls-opaque-prf-input-00.txt, section 3.1)
*/
sol = s->s3->client_opaque_prf_input_len;
}
#endif
tls1_PRF(ssl_get_algorithm2(s),
TLS_MD_MASTER_SECRET_CONST, TLS_MD_MASTER_SECRET_CONST_SIZE,
s->s3->client_random, SSL3_RANDOM_SIZE,
co, col,
s->s3->server_random, SSL3_RANDOM_SIZE,
- so, sol, p, len, s->session->master_key, buff, sizeof buff);
- OPENSSL_cleanse(buff, sizeof buff);
+ so, sol, p, len, s->session->master_key, buff, sizeof(buff));
+ OPENSSL_cleanse(buff, sizeof(buff));
#ifdef SSL_DEBUG
fprintf(stderr, "Premaster Secret:\n");
BIO_dump_fp(stderr, (char *)p, len);
fprintf(stderr, "Client Random:\n");
BIO_dump_fp(stderr, (char *)s->s3->client_random, SSL3_RANDOM_SIZE);
fprintf(stderr, "Server Random:\n");
BIO_dump_fp(stderr, (char *)s->s3->server_random, SSL3_RANDOM_SIZE);
fprintf(stderr, "Master Secret:\n");
BIO_dump_fp(stderr, (char *)s->session->master_key,
SSL3_MASTER_SECRET_SIZE);
#endif
#ifdef OPENSSL_SSL_TRACE_CRYPTO
if (s->msg_callback) {
s->msg_callback(2, s->version, TLS1_RT_CRYPTO_PREMASTER,
p, len, s, s->msg_callback_arg);
s->msg_callback(2, s->version, TLS1_RT_CRYPTO_CLIENT_RANDOM,
s->s3->client_random, SSL3_RANDOM_SIZE,
s, s->msg_callback_arg);
s->msg_callback(2, s->version, TLS1_RT_CRYPTO_SERVER_RANDOM,
s->s3->server_random, SSL3_RANDOM_SIZE,
s, s->msg_callback_arg);
s->msg_callback(2, s->version, TLS1_RT_CRYPTO_MASTER,
s->session->master_key,
SSL3_MASTER_SECRET_SIZE, s, s->msg_callback_arg);
}
#endif
#ifdef KSSL_DEBUG
fprintf(stderr, "tls1_generate_master_secret() complete\n");
#endif /* KSSL_DEBUG */
return (SSL3_MASTER_SECRET_SIZE);
}
int tls1_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)
{
unsigned char *buff;
unsigned char *val = NULL;
size_t vallen, currentvalpos;
int rv;
#ifdef KSSL_DEBUG
fprintf(stderr, "tls1_export_keying_material(%p,%p,%lu,%s,%lu,%p,%lu)\n",
s, out, olen, label, llen, context, contextlen);
#endif /* KSSL_DEBUG */
buff = OPENSSL_malloc(olen);
if (buff == NULL)
goto err2;
/*
* construct PRF arguments we construct the PRF argument ourself rather
* than passing separate values into the TLS PRF to ensure that the
* concatenation of values does not create a prohibited label.
*/
vallen = llen + SSL3_RANDOM_SIZE * 2;
if (use_context) {
vallen += 2 + contextlen;
}
val = OPENSSL_malloc(vallen);
if (val == NULL)
goto err2;
currentvalpos = 0;
memcpy(val + currentvalpos, (unsigned char *)label, llen);
currentvalpos += llen;
memcpy(val + currentvalpos, s->s3->client_random, SSL3_RANDOM_SIZE);
currentvalpos += SSL3_RANDOM_SIZE;
memcpy(val + currentvalpos, s->s3->server_random, SSL3_RANDOM_SIZE);
currentvalpos += SSL3_RANDOM_SIZE;
if (use_context) {
val[currentvalpos] = (contextlen >> 8) & 0xff;
currentvalpos++;
val[currentvalpos] = contextlen & 0xff;
currentvalpos++;
if ((contextlen > 0) || (context != NULL)) {
memcpy(val + currentvalpos, context, contextlen);
}
}
/*
* disallow prohibited labels note that SSL3_RANDOM_SIZE > max(prohibited
* label len) = 15, so size of val > max(prohibited label len) = 15 and
* the comparisons won't have buffer overflow
*/
if (memcmp(val, TLS_MD_CLIENT_FINISH_CONST,
TLS_MD_CLIENT_FINISH_CONST_SIZE) == 0)
goto err1;
if (memcmp(val, TLS_MD_SERVER_FINISH_CONST,
TLS_MD_SERVER_FINISH_CONST_SIZE) == 0)
goto err1;
if (memcmp(val, TLS_MD_MASTER_SECRET_CONST,
TLS_MD_MASTER_SECRET_CONST_SIZE) == 0)
goto err1;
if (memcmp(val, TLS_MD_KEY_EXPANSION_CONST,
TLS_MD_KEY_EXPANSION_CONST_SIZE) == 0)
goto err1;
rv = tls1_PRF(ssl_get_algorithm2(s),
val, vallen,
NULL, 0,
NULL, 0,
NULL, 0,
NULL, 0,
s->session->master_key, s->session->master_key_length,
out, buff, olen);
OPENSSL_cleanse(val, vallen);
OPENSSL_cleanse(buff, olen);
#ifdef KSSL_DEBUG
fprintf(stderr, "tls1_export_keying_material() complete\n");
#endif /* KSSL_DEBUG */
goto ret;
err1:
SSLerr(SSL_F_TLS1_EXPORT_KEYING_MATERIAL,
SSL_R_TLS_ILLEGAL_EXPORTER_LABEL);
rv = 0;
goto ret;
err2:
SSLerr(SSL_F_TLS1_EXPORT_KEYING_MATERIAL, ERR_R_MALLOC_FAILURE);
rv = 0;
ret:
if (buff != NULL)
OPENSSL_free(buff);
if (val != NULL)
OPENSSL_free(val);
return (rv);
}
int tls1_alert_code(int code)
{
switch (code) {
case SSL_AD_CLOSE_NOTIFY:
return (SSL3_AD_CLOSE_NOTIFY);
case SSL_AD_UNEXPECTED_MESSAGE:
return (SSL3_AD_UNEXPECTED_MESSAGE);
case SSL_AD_BAD_RECORD_MAC:
return (SSL3_AD_BAD_RECORD_MAC);
case SSL_AD_DECRYPTION_FAILED:
return (TLS1_AD_DECRYPTION_FAILED);
case SSL_AD_RECORD_OVERFLOW:
return (TLS1_AD_RECORD_OVERFLOW);
case SSL_AD_DECOMPRESSION_FAILURE:
return (SSL3_AD_DECOMPRESSION_FAILURE);
case SSL_AD_HANDSHAKE_FAILURE:
return (SSL3_AD_HANDSHAKE_FAILURE);
case SSL_AD_NO_CERTIFICATE:
return (-1);
case SSL_AD_BAD_CERTIFICATE:
return (SSL3_AD_BAD_CERTIFICATE);
case SSL_AD_UNSUPPORTED_CERTIFICATE:
return (SSL3_AD_UNSUPPORTED_CERTIFICATE);
case SSL_AD_CERTIFICATE_REVOKED:
return (SSL3_AD_CERTIFICATE_REVOKED);
case SSL_AD_CERTIFICATE_EXPIRED:
return (SSL3_AD_CERTIFICATE_EXPIRED);
case SSL_AD_CERTIFICATE_UNKNOWN:
return (SSL3_AD_CERTIFICATE_UNKNOWN);
case SSL_AD_ILLEGAL_PARAMETER:
return (SSL3_AD_ILLEGAL_PARAMETER);
case SSL_AD_UNKNOWN_CA:
return (TLS1_AD_UNKNOWN_CA);
case SSL_AD_ACCESS_DENIED:
return (TLS1_AD_ACCESS_DENIED);
case SSL_AD_DECODE_ERROR:
return (TLS1_AD_DECODE_ERROR);
case SSL_AD_DECRYPT_ERROR:
return (TLS1_AD_DECRYPT_ERROR);
case SSL_AD_EXPORT_RESTRICTION:
return (TLS1_AD_EXPORT_RESTRICTION);
case SSL_AD_PROTOCOL_VERSION:
return (TLS1_AD_PROTOCOL_VERSION);
case SSL_AD_INSUFFICIENT_SECURITY:
return (TLS1_AD_INSUFFICIENT_SECURITY);
case SSL_AD_INTERNAL_ERROR:
return (TLS1_AD_INTERNAL_ERROR);
case SSL_AD_USER_CANCELLED:
return (TLS1_AD_USER_CANCELLED);
case SSL_AD_NO_RENEGOTIATION:
return (TLS1_AD_NO_RENEGOTIATION);
case SSL_AD_UNSUPPORTED_EXTENSION:
return (TLS1_AD_UNSUPPORTED_EXTENSION);
case SSL_AD_CERTIFICATE_UNOBTAINABLE:
return (TLS1_AD_CERTIFICATE_UNOBTAINABLE);
case SSL_AD_UNRECOGNIZED_NAME:
return (TLS1_AD_UNRECOGNIZED_NAME);
case SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE:
return (TLS1_AD_BAD_CERTIFICATE_STATUS_RESPONSE);
case SSL_AD_BAD_CERTIFICATE_HASH_VALUE:
return (TLS1_AD_BAD_CERTIFICATE_HASH_VALUE);
case SSL_AD_UNKNOWN_PSK_IDENTITY:
return (TLS1_AD_UNKNOWN_PSK_IDENTITY);
case SSL_AD_INAPPROPRIATE_FALLBACK:
return (TLS1_AD_INAPPROPRIATE_FALLBACK);
#if 0
/* not appropriate for TLS, not used for DTLS */
case DTLS1_AD_MISSING_HANDSHAKE_MESSAGE:
return (DTLS1_AD_MISSING_HANDSHAKE_MESSAGE);
#endif
default:
return (-1);
}
}
diff --git a/ssl/t1_lib.c b/ssl/t1_lib.c
index 1a4387b78eb9..75c2f4154dfe 100644
--- a/ssl/t1_lib.c
+++ b/ssl/t1_lib.c
@@ -1,4559 +1,4576 @@
/* ssl/t1_lib.c */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
/* ====================================================================
- * Copyright (c) 1998-2007 The OpenSSL Project. All rights reserved.
+ * Copyright (c) 1998-2018 The OpenSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* openssl-core@openssl.org.
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.openssl.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*
* This product includes cryptographic software written by Eric Young
* (eay@cryptsoft.com). This product includes software written by Tim
* Hudson (tjh@cryptsoft.com).
*
*/
#include <stdio.h>
#include <openssl/objects.h>
#include <openssl/evp.h>
#include <openssl/hmac.h>
#ifndef OPENSSL_NO_EC
#ifdef OPENSSL_NO_EC2M
# include <openssl/ec.h>
#endif
#endif
#include <openssl/ocsp.h>
#include <openssl/rand.h>
#include "ssl_locl.h"
const char tls1_version_str[] = "TLSv1" OPENSSL_VERSION_PTEXT;
#ifndef OPENSSL_NO_TLSEXT
static int tls_decrypt_ticket(SSL *s, const unsigned char *tick, int ticklen,
const unsigned char *sess_id, int sesslen,
SSL_SESSION **psess);
static int ssl_check_clienthello_tlsext_early(SSL *s);
int ssl_check_serverhello_tlsext(SSL *s);
#endif
#define CHECKLEN(curr, val, limit) \
(((curr) >= (limit)) || (size_t)((limit) - (curr)) < (size_t)(val))
SSL3_ENC_METHOD TLSv1_enc_data = {
tls1_enc,
tls1_mac,
tls1_setup_key_block,
tls1_generate_master_secret,
tls1_change_cipher_state,
tls1_final_finish_mac,
TLS1_FINISH_MAC_LENGTH,
tls1_cert_verify_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_HM_HEADER_LENGTH,
ssl3_set_handshake_header,
ssl3_handshake_write
};
SSL3_ENC_METHOD TLSv1_1_enc_data = {
tls1_enc,
tls1_mac,
tls1_setup_key_block,
tls1_generate_master_secret,
tls1_change_cipher_state,
tls1_final_finish_mac,
TLS1_FINISH_MAC_LENGTH,
tls1_cert_verify_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_HM_HEADER_LENGTH,
ssl3_set_handshake_header,
ssl3_handshake_write
};
SSL3_ENC_METHOD TLSv1_2_enc_data = {
tls1_enc,
tls1_mac,
tls1_setup_key_block,
tls1_generate_master_secret,
tls1_change_cipher_state,
tls1_final_finish_mac,
TLS1_FINISH_MAC_LENGTH,
tls1_cert_verify_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_HM_HEADER_LENGTH,
ssl3_set_handshake_header,
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);
s->method->ssl_clear(s);
return (1);
}
void tls1_free(SSL *s)
{
#ifndef OPENSSL_NO_TLSEXT
if (s->tlsext_session_ticket) {
OPENSSL_free(s->tlsext_session_ticket);
}
#endif /* OPENSSL_NO_TLSEXT */
ssl3_free(s);
}
void tls1_clear(SSL *s)
{
ssl3_clear(s);
s->version = s->method->version;
}
#ifndef OPENSSL_NO_EC
static int nid_list[] = {
NID_sect163k1, /* sect163k1 (1) */
NID_sect163r1, /* sect163r1 (2) */
NID_sect163r2, /* sect163r2 (3) */
NID_sect193r1, /* sect193r1 (4) */
NID_sect193r2, /* sect193r2 (5) */
NID_sect233k1, /* sect233k1 (6) */
NID_sect233r1, /* sect233r1 (7) */
NID_sect239k1, /* sect239k1 (8) */
NID_sect283k1, /* sect283k1 (9) */
NID_sect283r1, /* sect283r1 (10) */
NID_sect409k1, /* sect409k1 (11) */
NID_sect409r1, /* sect409r1 (12) */
NID_sect571k1, /* sect571k1 (13) */
NID_sect571r1, /* sect571r1 (14) */
NID_secp160k1, /* secp160k1 (15) */
NID_secp160r1, /* secp160r1 (16) */
NID_secp160r2, /* secp160r2 (17) */
NID_secp192k1, /* secp192k1 (18) */
NID_X9_62_prime192v1, /* secp192r1 (19) */
NID_secp224k1, /* secp224k1 (20) */
NID_secp224r1, /* secp224r1 (21) */
NID_secp256k1, /* secp256k1 (22) */
NID_X9_62_prime256v1, /* secp256r1 (23) */
NID_secp384r1, /* secp384r1 (24) */
NID_secp521r1, /* secp521r1 (25) */
NID_brainpoolP256r1, /* brainpoolP256r1 (26) */
NID_brainpoolP384r1, /* brainpoolP384r1 (27) */
NID_brainpoolP512r1 /* brainpool512r1 (28) */
};
static const unsigned char ecformats_default[] = {
TLSEXT_ECPOINTFORMAT_uncompressed,
TLSEXT_ECPOINTFORMAT_ansiX962_compressed_prime,
TLSEXT_ECPOINTFORMAT_ansiX962_compressed_char2
};
/* The client's default curves / the server's 'auto' curves. */
static const unsigned char eccurves_auto[] = {
/* Prefer P-256 which has the fastest and most secure implementations. */
0, 23, /* secp256r1 (23) */
/* Other >= 256-bit prime curves. */
0, 25, /* secp521r1 (25) */
0, 28, /* brainpool512r1 (28) */
0, 27, /* brainpoolP384r1 (27) */
0, 24, /* secp384r1 (24) */
0, 26, /* brainpoolP256r1 (26) */
0, 22, /* secp256k1 (22) */
# ifndef OPENSSL_NO_EC2M
/* >= 256-bit binary curves. */
0, 14, /* sect571r1 (14) */
0, 13, /* sect571k1 (13) */
0, 11, /* sect409k1 (11) */
0, 12, /* sect409r1 (12) */
0, 9, /* sect283k1 (9) */
0, 10, /* sect283r1 (10) */
# endif
};
static const unsigned char eccurves_all[] = {
/* Prefer P-256 which has the fastest and most secure implementations. */
0, 23, /* secp256r1 (23) */
/* Other >= 256-bit prime curves. */
0, 25, /* secp521r1 (25) */
0, 28, /* brainpool512r1 (28) */
0, 27, /* brainpoolP384r1 (27) */
0, 24, /* secp384r1 (24) */
0, 26, /* brainpoolP256r1 (26) */
0, 22, /* secp256k1 (22) */
# ifndef OPENSSL_NO_EC2M
/* >= 256-bit binary curves. */
0, 14, /* sect571r1 (14) */
0, 13, /* sect571k1 (13) */
0, 11, /* sect409k1 (11) */
0, 12, /* sect409r1 (12) */
0, 9, /* sect283k1 (9) */
0, 10, /* sect283r1 (10) */
# endif
/*
* Remaining curves disabled by default but still permitted if set
* via an explicit callback or parameters.
*/
0, 20, /* secp224k1 (20) */
0, 21, /* secp224r1 (21) */
0, 18, /* secp192k1 (18) */
0, 19, /* secp192r1 (19) */
0, 15, /* secp160k1 (15) */
0, 16, /* secp160r1 (16) */
0, 17, /* secp160r2 (17) */
# ifndef OPENSSL_NO_EC2M
0, 8, /* sect239k1 (8) */
0, 6, /* sect233k1 (6) */
0, 7, /* sect233r1 (7) */
0, 4, /* sect193r1 (4) */
0, 5, /* sect193r2 (5) */
0, 1, /* sect163k1 (1) */
0, 2, /* sect163r1 (2) */
0, 3, /* sect163r2 (3) */
# endif
};
static const unsigned char suiteb_curves[] = {
0, TLSEXT_curve_P_256,
0, TLSEXT_curve_P_384
};
# ifdef OPENSSL_FIPS
/* Brainpool not allowed in FIPS mode */
static const unsigned char fips_curves_default[] = {
# ifndef OPENSSL_NO_EC2M
0, 14, /* sect571r1 (14) */
0, 13, /* sect571k1 (13) */
# endif
0, 25, /* secp521r1 (25) */
# ifndef OPENSSL_NO_EC2M
0, 11, /* sect409k1 (11) */
0, 12, /* sect409r1 (12) */
# endif
0, 24, /* secp384r1 (24) */
# ifndef OPENSSL_NO_EC2M
0, 9, /* sect283k1 (9) */
0, 10, /* sect283r1 (10) */
# endif
0, 22, /* secp256k1 (22) */
0, 23, /* secp256r1 (23) */
# ifndef OPENSSL_NO_EC2M
0, 8, /* sect239k1 (8) */
0, 6, /* sect233k1 (6) */
0, 7, /* sect233r1 (7) */
# endif
0, 20, /* secp224k1 (20) */
0, 21, /* secp224r1 (21) */
# ifndef OPENSSL_NO_EC2M
0, 4, /* sect193r1 (4) */
0, 5, /* sect193r2 (5) */
# endif
0, 18, /* secp192k1 (18) */
0, 19, /* secp192r1 (19) */
# ifndef OPENSSL_NO_EC2M
0, 1, /* sect163k1 (1) */
0, 2, /* sect163r1 (2) */
0, 3, /* sect163r2 (3) */
# endif
0, 15, /* secp160k1 (15) */
0, 16, /* secp160r1 (16) */
0, 17, /* secp160r2 (17) */
};
# endif
int tls1_ec_curve_id2nid(int curve_id)
{
/* ECC curves from RFC 4492 and RFC 7027 */
if ((curve_id < 1) || ((unsigned int)curve_id >
sizeof(nid_list) / sizeof(nid_list[0])))
return 0;
return nid_list[curve_id - 1];
}
int tls1_ec_nid2curve_id(int nid)
{
/* ECC curves from RFC 4492 and RFC 7027 */
switch (nid) {
case NID_sect163k1: /* sect163k1 (1) */
return 1;
case NID_sect163r1: /* sect163r1 (2) */
return 2;
case NID_sect163r2: /* sect163r2 (3) */
return 3;
case NID_sect193r1: /* sect193r1 (4) */
return 4;
case NID_sect193r2: /* sect193r2 (5) */
return 5;
case NID_sect233k1: /* sect233k1 (6) */
return 6;
case NID_sect233r1: /* sect233r1 (7) */
return 7;
case NID_sect239k1: /* sect239k1 (8) */
return 8;
case NID_sect283k1: /* sect283k1 (9) */
return 9;
case NID_sect283r1: /* sect283r1 (10) */
return 10;
case NID_sect409k1: /* sect409k1 (11) */
return 11;
case NID_sect409r1: /* sect409r1 (12) */
return 12;
case NID_sect571k1: /* sect571k1 (13) */
return 13;
case NID_sect571r1: /* sect571r1 (14) */
return 14;
case NID_secp160k1: /* secp160k1 (15) */
return 15;
case NID_secp160r1: /* secp160r1 (16) */
return 16;
case NID_secp160r2: /* secp160r2 (17) */
return 17;
case NID_secp192k1: /* secp192k1 (18) */
return 18;
case NID_X9_62_prime192v1: /* secp192r1 (19) */
return 19;
case NID_secp224k1: /* secp224k1 (20) */
return 20;
case NID_secp224r1: /* secp224r1 (21) */
return 21;
case NID_secp256k1: /* secp256k1 (22) */
return 22;
case NID_X9_62_prime256v1: /* secp256r1 (23) */
return 23;
case NID_secp384r1: /* secp384r1 (24) */
return 24;
case NID_secp521r1: /* secp521r1 (25) */
return 25;
case NID_brainpoolP256r1: /* brainpoolP256r1 (26) */
return 26;
case NID_brainpoolP384r1: /* brainpoolP384r1 (27) */
return 27;
case NID_brainpoolP512r1: /* brainpool512r1 (28) */
return 28;
default:
return 0;
}
}
/*
* Get curves list, if "sess" is set return client curves otherwise
* preferred list.
* Sets |num_curves| to the number of curves in the list, i.e.,
* the length of |pcurves| is 2 * num_curves.
* Returns 1 on success and 0 if the client curves list has invalid format.
* The latter indicates an internal error: we should not be accepting such
* lists in the first place.
* TODO(emilia): we should really be storing the curves list in explicitly
* parsed form instead. (However, this would affect binary compatibility
* so cannot happen in the 1.0.x series.)
*/
static int tls1_get_curvelist(SSL *s, int sess,
const unsigned char **pcurves,
size_t *num_curves)
{
size_t pcurveslen = 0;
if (sess) {
*pcurves = s->session->tlsext_ellipticcurvelist;
pcurveslen = s->session->tlsext_ellipticcurvelist_length;
} else {
/* For Suite B mode only include P-256, P-384 */
switch (tls1_suiteb(s)) {
case SSL_CERT_FLAG_SUITEB_128_LOS:
*pcurves = suiteb_curves;
pcurveslen = sizeof(suiteb_curves);
break;
case SSL_CERT_FLAG_SUITEB_128_LOS_ONLY:
*pcurves = suiteb_curves;
pcurveslen = 2;
break;
case SSL_CERT_FLAG_SUITEB_192_LOS:
*pcurves = suiteb_curves + 2;
pcurveslen = 2;
break;
default:
*pcurves = s->tlsext_ellipticcurvelist;
pcurveslen = s->tlsext_ellipticcurvelist_length;
}
if (!*pcurves) {
# ifdef OPENSSL_FIPS
if (FIPS_mode()) {
*pcurves = fips_curves_default;
pcurveslen = sizeof(fips_curves_default);
} else
# endif
{
if (!s->server || s->cert->ecdh_tmp_auto) {
*pcurves = eccurves_auto;
pcurveslen = sizeof(eccurves_auto);
} else {
*pcurves = eccurves_all;
pcurveslen = sizeof(eccurves_all);
}
}
}
}
/* We do not allow odd length arrays to enter the system. */
if (pcurveslen & 1) {
SSLerr(SSL_F_TLS1_GET_CURVELIST, ERR_R_INTERNAL_ERROR);
*num_curves = 0;
return 0;
} else {
*num_curves = pcurveslen / 2;
return 1;
}
}
/* Check a curve is one of our preferences */
int tls1_check_curve(SSL *s, const unsigned char *p, size_t len)
{
const unsigned char *curves;
size_t num_curves, i;
unsigned int suiteb_flags = tls1_suiteb(s);
if (len != 3 || p[0] != NAMED_CURVE_TYPE)
return 0;
/* Check curve matches Suite B preferences */
if (suiteb_flags) {
unsigned long cid = s->s3->tmp.new_cipher->id;
if (p[1])
return 0;
if (cid == TLS1_CK_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256) {
if (p[2] != TLSEXT_curve_P_256)
return 0;
} else if (cid == TLS1_CK_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384) {
if (p[2] != TLSEXT_curve_P_384)
return 0;
} else /* Should never happen */
return 0;
}
if (!tls1_get_curvelist(s, 0, &curves, &num_curves))
return 0;
for (i = 0; i < num_curves; i++, curves += 2) {
if (p[1] == curves[0] && p[2] == curves[1])
return 1;
}
return 0;
}
/*-
* Return |nmatch|th shared curve or NID_undef if there is no match.
* For nmatch == -1, return number of matches
* For nmatch == -2, return the NID of the curve to use for
* an EC tmp key, or NID_undef if there is no match.
*/
int tls1_shared_curve(SSL *s, int nmatch)
{
const unsigned char *pref, *supp;
size_t num_pref, num_supp, i, j;
int k;
/* Can't do anything on client side */
if (s->server == 0)
return -1;
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 NID_X9_62_prime256v1; /* P-256 */
if (cid == TLS1_CK_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384)
return NID_secp384r1; /* P-384 */
/* Should never happen */
return NID_undef;
}
/* If not Suite B just return first preference shared curve */
nmatch = 0;
}
/*
* Avoid truncation. tls1_get_curvelist takes an int
* but s->options is a long...
*/
if (!tls1_get_curvelist
(s, (s->options & SSL_OP_CIPHER_SERVER_PREFERENCE) != 0, &supp,
&num_supp))
/* In practice, NID_undef == 0 but let's be precise. */
return nmatch == -1 ? 0 : NID_undef;
if (!tls1_get_curvelist
(s, !(s->options & SSL_OP_CIPHER_SERVER_PREFERENCE), &pref,
&num_pref))
return nmatch == -1 ? 0 : NID_undef;
/*
* If the client didn't send the elliptic_curves extension all of them
* are allowed.
*/
if (num_supp == 0 && (s->options & SSL_OP_CIPHER_SERVER_PREFERENCE) != 0) {
supp = eccurves_all;
num_supp = sizeof(eccurves_all) / 2;
} else if (num_pref == 0 &&
(s->options & SSL_OP_CIPHER_SERVER_PREFERENCE) == 0) {
pref = eccurves_all;
num_pref = sizeof(eccurves_all) / 2;
}
k = 0;
for (i = 0; i < num_pref; i++, pref += 2) {
const unsigned char *tsupp = supp;
for (j = 0; j < num_supp; j++, tsupp += 2) {
if (pref[0] == tsupp[0] && pref[1] == tsupp[1]) {
if (nmatch == k) {
int id = (pref[0] << 8) | pref[1];
return tls1_ec_curve_id2nid(id);
}
k++;
}
}
}
if (nmatch == -1)
return k;
/* Out of range (nmatch > k). */
return NID_undef;
}
int tls1_set_curves(unsigned char **pext, size_t *pextlen,
int *curves, size_t ncurves)
{
unsigned char *clist, *p;
size_t i;
/*
* Bitmap of curves included to detect duplicates: only works while curve
* ids < 32
*/
unsigned long dup_list = 0;
# ifdef OPENSSL_NO_EC2M
EC_GROUP *curve;
# endif
clist = OPENSSL_malloc(ncurves * 2);
if (!clist)
return 0;
for (i = 0, p = clist; i < ncurves; i++) {
unsigned long idmask;
int id;
id = tls1_ec_nid2curve_id(curves[i]);
# ifdef OPENSSL_FIPS
/* NB: 25 is last curve ID supported by FIPS module */
if (FIPS_mode() && id > 25) {
OPENSSL_free(clist);
return 0;
}
# endif
# ifdef OPENSSL_NO_EC2M
curve = EC_GROUP_new_by_curve_name(curves[i]);
if (!curve || EC_METHOD_get_field_type(EC_GROUP_method_of(curve))
== NID_X9_62_characteristic_two_field) {
if (curve)
EC_GROUP_free(curve);
OPENSSL_free(clist);
return 0;
} else
EC_GROUP_free(curve);
# endif
idmask = 1L << id;
if (!id || (dup_list & idmask)) {
OPENSSL_free(clist);
return 0;
}
dup_list |= idmask;
s2n(id, p);
}
if (*pext)
OPENSSL_free(*pext);
*pext = clist;
*pextlen = ncurves * 2;
return 1;
}
# define MAX_CURVELIST 28
typedef struct {
size_t nidcnt;
int nid_arr[MAX_CURVELIST];
} nid_cb_st;
static int nid_cb(const char *elem, int len, void *arg)
{
nid_cb_st *narg = arg;
size_t i;
int nid;
char etmp[20];
if (elem == NULL)
return 0;
if (narg->nidcnt == MAX_CURVELIST)
return 0;
if (len > (int)(sizeof(etmp) - 1))
return 0;
memcpy(etmp, elem, len);
etmp[len] = 0;
nid = EC_curve_nist2nid(etmp);
if (nid == NID_undef)
nid = OBJ_sn2nid(etmp);
if (nid == NID_undef)
nid = OBJ_ln2nid(etmp);
if (nid == NID_undef)
return 0;
for (i = 0; i < narg->nidcnt; i++)
if (narg->nid_arr[i] == nid)
return 0;
narg->nid_arr[narg->nidcnt++] = nid;
return 1;
}
/* Set curves based on a colon separate list */
int tls1_set_curves_list(unsigned char **pext, size_t *pextlen,
const char *str)
{
nid_cb_st ncb;
ncb.nidcnt = 0;
if (!CONF_parse_list(str, ':', 1, nid_cb, &ncb))
return 0;
if (pext == NULL)
return 1;
return tls1_set_curves(pext, pextlen, ncb.nid_arr, ncb.nidcnt);
}
/* For an EC key set TLS id and required compression based on parameters */
static int tls1_set_ec_id(unsigned char *curve_id, unsigned char *comp_id,
EC_KEY *ec)
{
int is_prime, id;
const EC_GROUP *grp;
const EC_METHOD *meth;
if (!ec)
return 0;
/* Determine if it is a prime field */
grp = EC_KEY_get0_group(ec);
if (!grp)
return 0;
meth = EC_GROUP_method_of(grp);
if (!meth)
return 0;
if (EC_METHOD_get_field_type(meth) == NID_X9_62_prime_field)
is_prime = 1;
else
is_prime = 0;
/* Determine curve ID */
id = EC_GROUP_get_curve_name(grp);
id = tls1_ec_nid2curve_id(id);
/* If we have an ID set it, otherwise set arbitrary explicit curve */
if (id) {
curve_id[0] = 0;
curve_id[1] = (unsigned char)id;
} else {
curve_id[0] = 0xff;
if (is_prime)
curve_id[1] = 0x01;
else
curve_id[1] = 0x02;
}
if (comp_id) {
if (EC_KEY_get0_public_key(ec) == NULL)
return 0;
if (EC_KEY_get_conv_form(ec) == POINT_CONVERSION_COMPRESSED) {
if (is_prime)
*comp_id = TLSEXT_ECPOINTFORMAT_ansiX962_compressed_prime;
else
*comp_id = TLSEXT_ECPOINTFORMAT_ansiX962_compressed_char2;
} else
*comp_id = TLSEXT_ECPOINTFORMAT_uncompressed;
}
return 1;
}
/* Check an EC key is compatible with extensions */
static int tls1_check_ec_key(SSL *s,
unsigned char *curve_id, unsigned char *comp_id)
{
const unsigned char *pformats, *pcurves;
size_t num_formats, num_curves, i;
int j;
/*
* If point formats extension present check it, otherwise everything is
* supported (see RFC4492).
*/
if (comp_id && s->session->tlsext_ecpointformatlist) {
pformats = s->session->tlsext_ecpointformatlist;
num_formats = s->session->tlsext_ecpointformatlist_length;
for (i = 0; i < num_formats; i++, pformats++) {
if (*comp_id == *pformats)
break;
}
if (i == num_formats)
return 0;
}
if (!curve_id)
return 1;
/* Check curve is consistent with client and server preferences */
for (j = 0; j <= 1; j++) {
if (!tls1_get_curvelist(s, j, &pcurves, &num_curves))
return 0;
if (j == 1 && num_curves == 0) {
/*
* If we've not received any curves then skip this check.
* 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 elliptic curves
* extension, so num_curves == 0 always means no extension.
*/
break;
}
for (i = 0; i < num_curves; i++, pcurves += 2) {
if (pcurves[0] == curve_id[0] && pcurves[1] == curve_id[1])
break;
}
if (i == num_curves)
return 0;
/* For clients can only check sent curve list */
if (!s->server)
return 1;
}
return 1;
}
static 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->tlsext_ecpointformatlist) {
*pformats = s->tlsext_ecpointformatlist;
*num_formats = s->tlsext_ecpointformatlist_length;
} 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 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 set_ee_md)
{
unsigned char comp_id, curve_id[2];
EVP_PKEY *pkey;
int rv;
pkey = X509_get_pubkey(x);
if (!pkey)
return 0;
/* If not EC nothing to do */
if (pkey->type != EVP_PKEY_EC) {
EVP_PKEY_free(pkey);
return 1;
}
rv = tls1_set_ec_id(curve_id, &comp_id, pkey->pkey.ec);
EVP_PKEY_free(pkey);
if (!rv)
return 0;
/*
* Can't check curve_id for client certs as we don't have a supported
* curves extension.
*/
rv = tls1_check_ec_key(s, s->server ? curve_id : NULL, &comp_id);
if (!rv)
return 0;
/*
* Special case for suite B. We *MUST* sign using SHA256+P-256 or
* SHA384+P-384, adjust digest if necessary.
*/
if (set_ee_md && tls1_suiteb(s)) {
int check_md;
size_t i;
CERT *c = s->cert;
if (curve_id[0])
return 0;
/* Check to see we have necessary signing algorithm */
if (curve_id[1] == TLSEXT_curve_P_256)
check_md = NID_ecdsa_with_SHA256;
else if (curve_id[1] == TLSEXT_curve_P_384)
check_md = NID_ecdsa_with_SHA384;
else
return 0; /* Should never happen */
for (i = 0; i < c->shared_sigalgslen; i++)
if (check_md == c->shared_sigalgs[i].signandhash_nid)
break;
if (i == c->shared_sigalgslen)
return 0;
if (set_ee_md == 2) {
if (check_md == NID_ecdsa_with_SHA256)
c->pkeys[SSL_PKEY_ECC].digest = EVP_sha256();
else
c->pkeys[SSL_PKEY_ECC].digest = EVP_sha384();
}
}
return rv;
}
# ifndef OPENSSL_NO_ECDH
/* Check EC temporary key is compatible with client extensions */
int tls1_check_ec_tmp_key(SSL *s, unsigned long cid)
{
unsigned char curve_id[2];
EC_KEY *ec = s->cert->ecdh_tmp;
# ifdef OPENSSL_SSL_DEBUG_BROKEN_PROTOCOL
/* Allow any curve: not just those peer supports */
if (s->cert->cert_flags & SSL_CERT_FLAG_BROKEN_PROTOCOL)
return 1;
# endif
/*
* If Suite B, AES128 MUST use P-256 and AES256 MUST use P-384, no other
* curves permitted.
*/
if (tls1_suiteb(s)) {
/* Curve to check determined by ciphersuite */
if (cid == TLS1_CK_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256)
curve_id[1] = TLSEXT_curve_P_256;
else if (cid == TLS1_CK_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384)
curve_id[1] = TLSEXT_curve_P_384;
else
return 0;
curve_id[0] = 0;
/* Check this curve is acceptable */
if (!tls1_check_ec_key(s, curve_id, NULL))
return 0;
/* If auto or setting curve from callback assume OK */
if (s->cert->ecdh_tmp_auto || s->cert->ecdh_tmp_cb)
return 1;
/* Otherwise check curve is acceptable */
else {
unsigned char curve_tmp[2];
if (!ec)
return 0;
if (!tls1_set_ec_id(curve_tmp, NULL, ec))
return 0;
if (!curve_tmp[0] || curve_tmp[1] == curve_id[1])
return 1;
return 0;
}
}
if (s->cert->ecdh_tmp_auto) {
/* Need a shared curve */
if (tls1_shared_curve(s, 0))
return 1;
else
return 0;
}
if (!ec) {
if (s->cert->ecdh_tmp_cb)
return 1;
else
return 0;
}
if (!tls1_set_ec_id(curve_id, NULL, ec))
return 0;
/* Set this to allow use of invalid curves for testing */
# if 0
return 1;
# else
return tls1_check_ec_key(s, curve_id, NULL);
# endif
}
# endif /* OPENSSL_NO_ECDH */
#else
static int tls1_check_cert_param(SSL *s, X509 *x, int set_ee_md)
{
return 1;
}
#endif /* OPENSSL_NO_EC */
#ifndef OPENSSL_NO_TLSEXT
/*
* List of supported signature algorithms and hashes. Should make this
* customisable at some point, for now include everything we support.
*/
# ifdef OPENSSL_NO_RSA
# define tlsext_sigalg_rsa(md) /* */
# else
# define tlsext_sigalg_rsa(md) md, TLSEXT_signature_rsa,
# endif
# ifdef OPENSSL_NO_DSA
# define tlsext_sigalg_dsa(md) /* */
# else
# define tlsext_sigalg_dsa(md) md, TLSEXT_signature_dsa,
# endif
# ifdef OPENSSL_NO_ECDSA
# define tlsext_sigalg_ecdsa(md)
/* */
# else
# define tlsext_sigalg_ecdsa(md) md, TLSEXT_signature_ecdsa,
# endif
# define tlsext_sigalg(md) \
tlsext_sigalg_rsa(md) \
tlsext_sigalg_dsa(md) \
tlsext_sigalg_ecdsa(md)
static unsigned char tls12_sigalgs[] = {
# ifndef OPENSSL_NO_SHA512
tlsext_sigalg(TLSEXT_hash_sha512)
tlsext_sigalg(TLSEXT_hash_sha384)
# endif
# ifndef OPENSSL_NO_SHA256
tlsext_sigalg(TLSEXT_hash_sha256)
tlsext_sigalg(TLSEXT_hash_sha224)
# endif
# ifndef OPENSSL_NO_SHA
tlsext_sigalg(TLSEXT_hash_sha1)
# endif
};
# ifndef OPENSSL_NO_ECDSA
static unsigned char suiteb_sigalgs[] = {
tlsext_sigalg_ecdsa(TLSEXT_hash_sha256)
tlsext_sigalg_ecdsa(TLSEXT_hash_sha384)
};
# endif
size_t tls12_get_psigalgs(SSL *s, int sent, const unsigned char **psigs)
{
/*
* If Suite B mode use Suite B sigalgs only, ignore any other
* preferences.
*/
# ifndef OPENSSL_NO_EC
switch (tls1_suiteb(s)) {
case SSL_CERT_FLAG_SUITEB_128_LOS:
*psigs = suiteb_sigalgs;
return sizeof(suiteb_sigalgs);
case SSL_CERT_FLAG_SUITEB_128_LOS_ONLY:
*psigs = suiteb_sigalgs;
return 2;
case SSL_CERT_FLAG_SUITEB_192_LOS:
*psigs = suiteb_sigalgs + 2;
return 2;
}
# endif
/* If server use client authentication sigalgs if not NULL */
if (s->server == sent && s->cert->client_sigalgs) {
*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 sizeof(tls12_sigalgs);
}
}
/*
* Check signature algorithm is consistent with sent supported signature
* algorithms and if so return relevant digest.
*/
int tls12_check_peer_sigalg(const EVP_MD **pmd, SSL *s,
const unsigned char *sig, EVP_PKEY *pkey)
{
const unsigned char *sent_sigs;
size_t sent_sigslen, i;
int sigalg = tls12_get_sigid(pkey);
/* Should never happen */
if (sigalg == -1)
return -1;
/* Check key type is consistent with signature */
if (sigalg != (int)sig[1]) {
SSLerr(SSL_F_TLS12_CHECK_PEER_SIGALG, SSL_R_WRONG_SIGNATURE_TYPE);
return 0;
}
# ifndef OPENSSL_NO_EC
if (pkey->type == EVP_PKEY_EC) {
unsigned char curve_id[2], comp_id;
/* Check compression and curve matches extensions */
if (!tls1_set_ec_id(curve_id, &comp_id, pkey->pkey.ec))
return 0;
if (!s->server && !tls1_check_ec_key(s, curve_id, &comp_id)) {
SSLerr(SSL_F_TLS12_CHECK_PEER_SIGALG, SSL_R_WRONG_CURVE);
return 0;
}
/* If Suite B only P-384+SHA384 or P-256+SHA-256 allowed */
if (tls1_suiteb(s)) {
if (curve_id[0])
return 0;
if (curve_id[1] == TLSEXT_curve_P_256) {
if (sig[0] != TLSEXT_hash_sha256) {
SSLerr(SSL_F_TLS12_CHECK_PEER_SIGALG,
SSL_R_ILLEGAL_SUITEB_DIGEST);
return 0;
}
} else if (curve_id[1] == TLSEXT_curve_P_384) {
if (sig[0] != TLSEXT_hash_sha384) {
SSLerr(SSL_F_TLS12_CHECK_PEER_SIGALG,
SSL_R_ILLEGAL_SUITEB_DIGEST);
return 0;
}
} else
return 0;
}
} else if (tls1_suiteb(s))
return 0;
# endif
/* Check signature matches a type we sent */
sent_sigslen = tls12_get_psigalgs(s, 1, &sent_sigs);
for (i = 0; i < sent_sigslen; i += 2, sent_sigs += 2) {
if (sig[0] == sent_sigs[0] && sig[1] == sent_sigs[1])
break;
}
/* Allow fallback to SHA1 if not strict mode */
if (i == sent_sigslen
&& (sig[0] != TLSEXT_hash_sha1
|| s->cert->cert_flags & SSL_CERT_FLAGS_CHECK_TLS_STRICT)) {
SSLerr(SSL_F_TLS12_CHECK_PEER_SIGALG, SSL_R_WRONG_SIGNATURE_TYPE);
return 0;
}
*pmd = tls12_get_hash(sig[0]);
if (*pmd == NULL) {
SSLerr(SSL_F_TLS12_CHECK_PEER_SIGALG, SSL_R_UNKNOWN_DIGEST);
return 0;
}
/*
* Store the digest used so applications can retrieve it if they wish.
*/
if (s->session && s->session->sess_cert)
s->session->sess_cert->peer_key->digest = *pmd;
return 1;
}
/*
* Get a mask of disabled algorithms: an algorithm is disabled if it isn't
* supported or doesn't appear in supported signature algorithms. Unlike
* ssl_cipher_get_disabled this applies to a specific session and not global
* settings.
*/
void ssl_set_client_disabled(SSL *s)
{
CERT *c = s->cert;
const unsigned char *sigalgs;
size_t i, sigalgslen;
int have_rsa = 0, have_dsa = 0, have_ecdsa = 0;
c->mask_a = 0;
c->mask_k = 0;
/* Don't allow TLS 1.2 only ciphers if we don't suppport them */
if (!SSL_CLIENT_USE_TLS1_2_CIPHERS(s))
c->mask_ssl = SSL_TLSV1_2;
else
c->mask_ssl = 0;
/*
* Now go through all signature algorithms seeing if we support any for
* RSA, DSA, ECDSA. Do this for all versions not just TLS 1.2.
*/
sigalgslen = tls12_get_psigalgs(s, 1, &sigalgs);
for (i = 0; i < sigalgslen; i += 2, sigalgs += 2) {
switch (sigalgs[1]) {
# ifndef OPENSSL_NO_RSA
case TLSEXT_signature_rsa:
have_rsa = 1;
break;
# endif
# ifndef OPENSSL_NO_DSA
case TLSEXT_signature_dsa:
have_dsa = 1;
break;
# endif
# ifndef OPENSSL_NO_ECDSA
case TLSEXT_signature_ecdsa:
have_ecdsa = 1;
break;
# endif
}
}
/*
* Disable auth and static DH if we don't include any appropriate
* signature algorithms.
*/
if (!have_rsa) {
c->mask_a |= SSL_aRSA;
c->mask_k |= SSL_kDHr | SSL_kECDHr;
}
if (!have_dsa) {
c->mask_a |= SSL_aDSS;
c->mask_k |= SSL_kDHd;
}
if (!have_ecdsa) {
c->mask_a |= SSL_aECDSA;
c->mask_k |= SSL_kECDHe;
}
# ifndef OPENSSL_NO_KRB5
if (!kssl_tgt_is_available(s->kssl_ctx)) {
c->mask_a |= SSL_aKRB5;
c->mask_k |= SSL_kKRB5;
}
# endif
# ifndef OPENSSL_NO_PSK
/* with PSK there must be client callback set */
if (!s->psk_client_callback) {
c->mask_a |= SSL_aPSK;
c->mask_k |= SSL_kPSK;
}
# endif /* OPENSSL_NO_PSK */
# ifndef OPENSSL_NO_SRP
if (!(s->srp_ctx.srp_Mask & SSL_kSRP)) {
c->mask_a |= SSL_aSRP;
c->mask_k |= SSL_kSRP;
}
# endif
c->valid = 1;
}
unsigned char *ssl_add_clienthello_tlsext(SSL *s, unsigned char *buf,
unsigned char *limit, int *al)
{
int extdatalen = 0;
unsigned char *orig = buf;
unsigned char *ret = buf;
# ifndef OPENSSL_NO_EC
/* See if we support any ECC ciphersuites */
int using_ecc = 0;
if (s->version >= TLS1_VERSION || SSL_IS_DTLS(s)) {
int i;
unsigned long alg_k, alg_a;
STACK_OF(SSL_CIPHER) *cipher_stack = SSL_get_ciphers(s);
for (i = 0; i < sk_SSL_CIPHER_num(cipher_stack); i++) {
SSL_CIPHER *c = sk_SSL_CIPHER_value(cipher_stack, i);
alg_k = c->algorithm_mkey;
alg_a = c->algorithm_auth;
if ((alg_k & (SSL_kEECDH | SSL_kECDHr | SSL_kECDHe)
|| (alg_a & SSL_aECDSA))) {
using_ecc = 1;
break;
}
}
}
# endif
/* don't add extensions for SSLv3 unless doing secure renegotiation */
if (s->client_version == SSL3_VERSION && !s->s3->send_connection_binding)
return orig;
ret += 2;
if (ret >= limit)
return NULL; /* this really never occurs, but ... */
if (s->tlsext_hostname != NULL) {
/* Add TLS extension servername to the Client Hello message */
size_t size_str;
/*-
* check for enough space.
* 4 for the servername type and entension length
* 2 for servernamelist length
* 1 for the hostname type
* 2 for hostname length
* + hostname length
*/
size_str = strlen(s->tlsext_hostname);
if (CHECKLEN(ret, 9 + size_str, limit))
return NULL;
/* extension type and length */
s2n(TLSEXT_TYPE_server_name, ret);
s2n(size_str + 5, ret);
/* length of servername list */
s2n(size_str + 3, ret);
/* hostname type, length and hostname */
*(ret++) = (unsigned char)TLSEXT_NAMETYPE_host_name;
s2n(size_str, ret);
memcpy(ret, s->tlsext_hostname, size_str);
ret += size_str;
}
/* Add RI if renegotiating */
if (s->renegotiate) {
int el;
if (!ssl_add_clienthello_renegotiate_ext(s, 0, &el, 0)) {
SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
return NULL;
}
if ((limit - ret - 4 - el) < 0)
return NULL;
s2n(TLSEXT_TYPE_renegotiate, ret);
s2n(el, ret);
if (!ssl_add_clienthello_renegotiate_ext(s, ret, &el, el)) {
SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
return NULL;
}
ret += el;
}
# ifndef OPENSSL_NO_SRP
/* Add SRP username if there is one */
if (s->srp_ctx.login != NULL) { /* Add TLS extension SRP username to the
* Client Hello message */
size_t login_len = strlen(s->srp_ctx.login);
if (login_len > 255 || login_len == 0) {
SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
return NULL;
}
/*-
* check for enough space.
* 4 for the srp type type and entension length
* 1 for the srp user identity
* + srp user identity length
*/
if (CHECKLEN(ret, 5 + login_len, limit))
return NULL;
/* fill in the extension */
s2n(TLSEXT_TYPE_srp, ret);
s2n(login_len + 1, ret);
(*ret++) = (unsigned char)login_len;
memcpy(ret, s->srp_ctx.login, login_len);
ret += login_len;
}
# endif
# ifndef OPENSSL_NO_EC
if (using_ecc) {
/*
* Add TLS extension ECPointFormats to the ClientHello message
*/
const unsigned char *pcurves, *pformats;
size_t num_curves, num_formats, curves_list_len;
tls1_get_formatlist(s, &pformats, &num_formats);
if (num_formats > 255) {
SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
return NULL;
}
/*-
* check for enough space.
* 4 bytes for the ec point formats type and extension length
* 1 byte for the length of the formats
* + formats length
*/
if (CHECKLEN(ret, 5 + num_formats, limit))
return NULL;
s2n(TLSEXT_TYPE_ec_point_formats, ret);
/* The point format list has 1-byte length. */
s2n(num_formats + 1, ret);
*(ret++) = (unsigned char)num_formats;
memcpy(ret, pformats, num_formats);
ret += num_formats;
/*
* Add TLS extension EllipticCurves to the ClientHello message
*/
pcurves = s->tlsext_ellipticcurvelist;
if (!tls1_get_curvelist(s, 0, &pcurves, &num_curves))
return NULL;
if (num_curves > 65532 / 2) {
SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
return NULL;
}
curves_list_len = 2 * num_curves;
/*-
* check for enough space.
* 4 bytes for the ec curves type and extension length
* 2 bytes for the curve list length
* + curve list length
*/
if (CHECKLEN(ret, 6 + curves_list_len, limit))
return NULL;
s2n(TLSEXT_TYPE_elliptic_curves, ret);
s2n(curves_list_len + 2, ret);
s2n(curves_list_len, ret);
memcpy(ret, pcurves, curves_list_len);
ret += curves_list_len;
}
# endif /* OPENSSL_NO_EC */
if (!(SSL_get_options(s) & SSL_OP_NO_TICKET)) {
size_t ticklen;
if (!s->new_session && s->session && s->session->tlsext_tick)
ticklen = s->session->tlsext_ticklen;
else if (s->session && s->tlsext_session_ticket &&
s->tlsext_session_ticket->data) {
ticklen = s->tlsext_session_ticket->length;
s->session->tlsext_tick = OPENSSL_malloc(ticklen);
if (!s->session->tlsext_tick)
return NULL;
memcpy(s->session->tlsext_tick,
s->tlsext_session_ticket->data, ticklen);
s->session->tlsext_ticklen = ticklen;
} else
ticklen = 0;
if (ticklen == 0 && s->tlsext_session_ticket &&
s->tlsext_session_ticket->data == NULL)
goto skip_ext;
/*
* Check for enough room 2 for extension type, 2 for len rest for
* ticket
*/
if (CHECKLEN(ret, 4 + ticklen, limit))
return NULL;
s2n(TLSEXT_TYPE_session_ticket, ret);
s2n(ticklen, ret);
if (ticklen > 0) {
memcpy(ret, s->session->tlsext_tick, ticklen);
ret += ticklen;
}
}
skip_ext:
if (SSL_CLIENT_USE_SIGALGS(s)) {
size_t salglen;
const unsigned char *salg;
salglen = tls12_get_psigalgs(s, 1, &salg);
/*-
* check for enough space.
* 4 bytes for the sigalgs type and extension length
* 2 bytes for the sigalg list length
* + sigalg list length
*/
if (CHECKLEN(ret, salglen + 6, limit))
return NULL;
s2n(TLSEXT_TYPE_signature_algorithms, ret);
s2n(salglen + 2, ret);
s2n(salglen, ret);
memcpy(ret, salg, salglen);
ret += salglen;
}
# ifdef TLSEXT_TYPE_opaque_prf_input
if (s->s3->client_opaque_prf_input != NULL) {
size_t col = s->s3->client_opaque_prf_input_len;
if ((long)(limit - ret - 6 - col < 0))
return NULL;
if (col > 0xFFFD) /* can't happen */
return NULL;
s2n(TLSEXT_TYPE_opaque_prf_input, ret);
s2n(col + 2, ret);
s2n(col, ret);
memcpy(ret, s->s3->client_opaque_prf_input, col);
ret += col;
}
# endif
if (s->tlsext_status_type == TLSEXT_STATUSTYPE_ocsp) {
int i;
size_t extlen, idlen;
int lentmp;
OCSP_RESPID *id;
idlen = 0;
for (i = 0; i < sk_OCSP_RESPID_num(s->tlsext_ocsp_ids); i++) {
id = sk_OCSP_RESPID_value(s->tlsext_ocsp_ids, i);
lentmp = i2d_OCSP_RESPID(id, NULL);
if (lentmp <= 0)
return NULL;
idlen += (size_t)lentmp + 2;
}
if (s->tlsext_ocsp_exts) {
lentmp = i2d_X509_EXTENSIONS(s->tlsext_ocsp_exts, NULL);
if (lentmp < 0)
return NULL;
extlen = (size_t)lentmp;
} else
extlen = 0;
if (extlen + idlen > 0xFFF0)
return NULL;
/*
* 2 bytes for status request type
* 2 bytes for status request len
* 1 byte for OCSP request type
* 2 bytes for length of ids
* 2 bytes for length of extensions
* + length of ids
* + length of extensions
*/
if (CHECKLEN(ret, 9 + idlen + extlen, limit))
return NULL;
s2n(TLSEXT_TYPE_status_request, ret);
s2n(extlen + idlen + 5, ret);
*(ret++) = TLSEXT_STATUSTYPE_ocsp;
s2n(idlen, ret);
for (i = 0; i < sk_OCSP_RESPID_num(s->tlsext_ocsp_ids); i++) {
/* save position of id len */
unsigned char *q = ret;
id = sk_OCSP_RESPID_value(s->tlsext_ocsp_ids, i);
/* skip over id len */
ret += 2;
lentmp = i2d_OCSP_RESPID(id, &ret);
/* write id len */
s2n(lentmp, q);
}
s2n(extlen, ret);
if (extlen > 0)
i2d_X509_EXTENSIONS(s->tlsext_ocsp_exts, &ret);
}
# ifndef OPENSSL_NO_HEARTBEATS
/* Add Heartbeat extension */
/*-
* check for enough space.
* 4 bytes for the heartbeat ext type and extension length
* 1 byte for the mode
*/
if (CHECKLEN(ret, 5, limit))
return NULL;
s2n(TLSEXT_TYPE_heartbeat, ret);
s2n(1, ret);
/*-
* Set mode:
* 1: peer may send requests
* 2: peer not allowed to send requests
*/
if (s->tlsext_heartbeat & SSL_TLSEXT_HB_DONT_RECV_REQUESTS)
*(ret++) = SSL_TLSEXT_HB_DONT_SEND_REQUESTS;
else
*(ret++) = SSL_TLSEXT_HB_ENABLED;
# endif
# ifndef OPENSSL_NO_NEXTPROTONEG
if (s->ctx->next_proto_select_cb && !s->s3->tmp.finish_md_len) {
/*
* The client advertises an emtpy extension to indicate its support
* for Next Protocol Negotiation
*/
/*-
* check for enough space.
* 4 bytes for the NPN ext type and extension length
*/
if (CHECKLEN(ret, 4, limit))
return NULL;
s2n(TLSEXT_TYPE_next_proto_neg, ret);
s2n(0, ret);
}
# endif
if (s->alpn_client_proto_list && !s->s3->tmp.finish_md_len) {
/*-
* check for enough space.
* 4 bytes for the ALPN type and extension length
* 2 bytes for the ALPN protocol list length
* + ALPN protocol list length
*/
if (CHECKLEN(ret, 6 + s->alpn_client_proto_list_len, limit))
return NULL;
s2n(TLSEXT_TYPE_application_layer_protocol_negotiation, ret);
s2n(2 + s->alpn_client_proto_list_len, ret);
s2n(s->alpn_client_proto_list_len, ret);
memcpy(ret, s->alpn_client_proto_list, s->alpn_client_proto_list_len);
ret += s->alpn_client_proto_list_len;
s->cert->alpn_sent = 1;
}
# ifndef OPENSSL_NO_SRTP
if (SSL_IS_DTLS(s) && SSL_get_srtp_profiles(s)) {
int el;
ssl_add_clienthello_use_srtp_ext(s, 0, &el, 0);
/*-
* check for enough space.
* 4 bytes for the SRTP type and extension length
* + SRTP profiles length
*/
if (CHECKLEN(ret, 4 + el, limit))
return NULL;
s2n(TLSEXT_TYPE_use_srtp, ret);
s2n(el, ret);
if (ssl_add_clienthello_use_srtp_ext(s, ret, &el, el)) {
SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
return NULL;
}
ret += el;
}
# endif
custom_ext_init(&s->cert->cli_ext);
/* Add custom TLS Extensions to ClientHello */
if (!custom_ext_add(s, 0, &ret, limit, al))
return NULL;
/*
* Add padding to workaround bugs in F5 terminators. See
* https://tools.ietf.org/html/draft-agl-tls-padding-03 NB: because this
* code works out the length of all existing extensions it MUST always
* appear last.
*/
if (s->options & SSL_OP_TLSEXT_PADDING) {
int hlen = ret - (unsigned char *)s->init_buf->data;
/*
* The code in s23_clnt.c to build ClientHello messages includes the
* 5-byte record header in the buffer, while the code in s3_clnt.c
* does not.
*/
if (s->state == SSL23_ST_CW_CLNT_HELLO_A)
hlen -= 5;
if (hlen > 0xff && hlen < 0x200) {
hlen = 0x200 - hlen;
if (hlen >= 4)
hlen -= 4;
else
hlen = 0;
/*-
* check for enough space. Strictly speaking we know we've already
* got enough space because to get here the message size is < 0x200,
* but we know that we've allocated far more than that in the buffer
* - but for consistency and robustness we're going to check anyway.
*
* 4 bytes for the padding type and extension length
* + padding length
*/
if (CHECKLEN(ret, 4 + hlen, limit))
return NULL;
s2n(TLSEXT_TYPE_padding, ret);
s2n(hlen, ret);
memset(ret, 0, hlen);
ret += hlen;
}
}
if ((extdatalen = ret - orig - 2) == 0)
return orig;
s2n(extdatalen, orig);
return ret;
}
unsigned char *ssl_add_serverhello_tlsext(SSL *s, unsigned char *buf,
unsigned char *limit, int *al)
{
int extdatalen = 0;
unsigned char *orig = buf;
unsigned char *ret = buf;
# ifndef OPENSSL_NO_NEXTPROTONEG
int next_proto_neg_seen;
# endif
# ifndef OPENSSL_NO_EC
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_kEECDH | SSL_kECDHr | SSL_kECDHe))
|| (alg_a & SSL_aECDSA);
using_ecc = using_ecc && (s->session->tlsext_ecpointformatlist != NULL);
# endif
/*
* don't add extensions for SSLv3, unless doing secure renegotiation
*/
if (s->version == SSL3_VERSION && !s->s3->send_connection_binding)
return orig;
ret += 2;
if (ret >= limit)
return NULL; /* this really never occurs, but ... */
if (!s->hit && s->servername_done == 1
&& s->session->tlsext_hostname != NULL) {
if ((long)(limit - ret - 4) < 0)
return NULL;
s2n(TLSEXT_TYPE_server_name, ret);
s2n(0, ret);
}
if (s->s3->send_connection_binding) {
int el;
if (!ssl_add_serverhello_renegotiate_ext(s, 0, &el, 0)) {
SSLerr(SSL_F_SSL_ADD_SERVERHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
return NULL;
}
/*-
* check for enough space.
* 4 bytes for the reneg type and extension length
* + reneg data length
*/
if (CHECKLEN(ret, 4 + el, limit))
return NULL;
s2n(TLSEXT_TYPE_renegotiate, ret);
s2n(el, ret);
if (!ssl_add_serverhello_renegotiate_ext(s, ret, &el, el)) {
SSLerr(SSL_F_SSL_ADD_SERVERHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
return NULL;
}
ret += el;
}
# ifndef OPENSSL_NO_EC
if (using_ecc) {
const unsigned char *plist;
size_t plistlen;
/*
* Add TLS extension ECPointFormats to the ServerHello message
*/
tls1_get_formatlist(s, &plist, &plistlen);
if (plistlen > 255) {
SSLerr(SSL_F_SSL_ADD_SERVERHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
return NULL;
}
/*-
* check for enough space.
* 4 bytes for the ec points format type and extension length
* 1 byte for the points format list length
* + length of points format list
*/
if (CHECKLEN(ret, 5 + plistlen, limit))
return NULL;
s2n(TLSEXT_TYPE_ec_point_formats, ret);
s2n(plistlen + 1, ret);
*(ret++) = (unsigned char)plistlen;
memcpy(ret, plist, plistlen);
ret += plistlen;
}
/*
* Currently the server should not respond with a SupportedCurves
* extension
*/
# endif /* OPENSSL_NO_EC */
if (s->tlsext_ticket_expected && !(SSL_get_options(s) & SSL_OP_NO_TICKET)) {
/*-
* check for enough space.
* 4 bytes for the Ticket type and extension length
*/
if (CHECKLEN(ret, 4, limit))
return NULL;
s2n(TLSEXT_TYPE_session_ticket, ret);
s2n(0, ret);
} else {
/* if we don't add the above TLSEXT, we can't add a session ticket later */
s->tlsext_ticket_expected = 0;
}
if (s->tlsext_status_expected) {
/*-
* check for enough space.
* 4 bytes for the Status request type and extension length
*/
if (CHECKLEN(ret, 4, limit))
return NULL;
s2n(TLSEXT_TYPE_status_request, ret);
s2n(0, ret);
}
# ifdef TLSEXT_TYPE_opaque_prf_input
if (s->s3->server_opaque_prf_input != NULL) {
size_t sol = s->s3->server_opaque_prf_input_len;
if ((long)(limit - ret - 6 - sol) < 0)
return NULL;
if (sol > 0xFFFD) /* can't happen */
return NULL;
s2n(TLSEXT_TYPE_opaque_prf_input, ret);
s2n(sol + 2, ret);
s2n(sol, ret);
memcpy(ret, s->s3->server_opaque_prf_input, sol);
ret += sol;
}
# endif
# ifndef OPENSSL_NO_SRTP
if (SSL_IS_DTLS(s) && s->srtp_profile) {
int el;
ssl_add_serverhello_use_srtp_ext(s, 0, &el, 0);
/*-
* check for enough space.
* 4 bytes for the SRTP profiles type and extension length
* + length of the SRTP profiles list
*/
if (CHECKLEN(ret, 4 + el, limit))
return NULL;
s2n(TLSEXT_TYPE_use_srtp, ret);
s2n(el, ret);
if (ssl_add_serverhello_use_srtp_ext(s, ret, &el, el)) {
SSLerr(SSL_F_SSL_ADD_SERVERHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
return NULL;
}
ret += el;
}
# endif
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)) {
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
};
/* check for enough space. */
if (CHECKLEN(ret, sizeof(cryptopro_ext), limit))
return NULL;
memcpy(ret, cryptopro_ext, sizeof(cryptopro_ext));
ret += sizeof(cryptopro_ext);
}
# ifndef OPENSSL_NO_HEARTBEATS
/* Add Heartbeat extension if we've received one */
if (s->tlsext_heartbeat & SSL_TLSEXT_HB_ENABLED) {
/*-
* check for enough space.
* 4 bytes for the Heartbeat type and extension length
* 1 byte for the mode
*/
if (CHECKLEN(ret, 5, limit))
return NULL;
s2n(TLSEXT_TYPE_heartbeat, ret);
s2n(1, ret);
/*-
* Set mode:
* 1: peer may send requests
* 2: peer not allowed to send requests
*/
if (s->tlsext_heartbeat & SSL_TLSEXT_HB_DONT_RECV_REQUESTS)
*(ret++) = SSL_TLSEXT_HB_DONT_SEND_REQUESTS;
else
*(ret++) = SSL_TLSEXT_HB_ENABLED;
}
# endif
# ifndef OPENSSL_NO_NEXTPROTONEG
next_proto_neg_seen = s->s3->next_proto_neg_seen;
s->s3->next_proto_neg_seen = 0;
if (next_proto_neg_seen && s->ctx->next_protos_advertised_cb) {
const unsigned char *npa;
unsigned int npalen;
int r;
r = s->ctx->next_protos_advertised_cb(s, &npa, &npalen,
s->
ctx->next_protos_advertised_cb_arg);
if (r == SSL_TLSEXT_ERR_OK) {
/*-
* check for enough space.
* 4 bytes for the NPN type and extension length
* + length of protocols list
*/
if (CHECKLEN(ret, 4 + npalen, limit))
return NULL;
s2n(TLSEXT_TYPE_next_proto_neg, ret);
s2n(npalen, ret);
memcpy(ret, npa, npalen);
ret += npalen;
s->s3->next_proto_neg_seen = 1;
}
}
# endif
if (!custom_ext_add(s, 1, &ret, limit, al))
return NULL;
if (s->s3->alpn_selected) {
const unsigned char *selected = s->s3->alpn_selected;
size_t len = s->s3->alpn_selected_len;
/*-
* check for enough space.
* 4 bytes for the ALPN type and extension length
* 2 bytes for ALPN data length
* 1 byte for selected protocol length
* + length of the selected protocol
*/
if (CHECKLEN(ret, 7 + len, limit))
return NULL;
s2n(TLSEXT_TYPE_application_layer_protocol_negotiation, ret);
s2n(3 + len, ret);
s2n(1 + len, ret);
*ret++ = (unsigned char)len;
memcpy(ret, selected, len);
ret += len;
}
if ((extdatalen = ret - orig - 2) == 0)
return orig;
s2n(extdatalen, orig);
return ret;
}
# ifndef OPENSSL_NO_EC
/*-
* ssl_check_for_safari attempts to fingerprint Safari using OS X
* SecureTransport using the TLS extension block in |d|, of length |n|.
* Safari, since 10.6, sends exactly these extensions, in this order:
* SNI,
* elliptic_curves
* ec_point_formats
*
* We wish to fingerprint Safari because they broke ECDHE-ECDSA support in 10.8,
* but they advertise support. So enabling ECDHE-ECDSA ciphers breaks them.
* Sadly we cannot differentiate 10.6, 10.7 and 10.8.4 (which work), from
* 10.8..10.8.3 (which don't work).
*/
static void ssl_check_for_safari(SSL *s, const unsigned char *data,
const unsigned char *limit)
{
unsigned short type, size;
static const unsigned char kSafariExtensionsBlock[] = {
0x00, 0x0a, /* elliptic_curves extension */
0x00, 0x08, /* 8 bytes */
0x00, 0x06, /* 6 bytes of curve ids */
0x00, 0x17, /* P-256 */
0x00, 0x18, /* P-384 */
0x00, 0x19, /* P-521 */
0x00, 0x0b, /* ec_point_formats */
0x00, 0x02, /* 2 bytes */
0x01, /* 1 point format */
0x00, /* uncompressed */
};
/* The following is only present in TLS 1.2 */
static const unsigned char kSafariTLS12ExtensionsBlock[] = {
0x00, 0x0d, /* signature_algorithms */
0x00, 0x0c, /* 12 bytes */
0x00, 0x0a, /* 10 bytes */
0x05, 0x01, /* SHA-384/RSA */
0x04, 0x01, /* SHA-256/RSA */
0x02, 0x01, /* SHA-1/RSA */
0x04, 0x03, /* SHA-256/ECDSA */
0x02, 0x03, /* SHA-1/ECDSA */
};
if (limit - data <= 2)
return;
data += 2;
if (limit - data < 4)
return;
n2s(data, type);
n2s(data, size);
if (type != TLSEXT_TYPE_server_name)
return;
if (limit - data < size)
return;
data += size;
if (TLS1_get_client_version(s) >= TLS1_2_VERSION) {
const size_t len1 = sizeof(kSafariExtensionsBlock);
const size_t len2 = sizeof(kSafariTLS12ExtensionsBlock);
if (limit - data != (int)(len1 + len2))
return;
if (memcmp(data, kSafariExtensionsBlock, len1) != 0)
return;
if (memcmp(data + len1, kSafariTLS12ExtensionsBlock, len2) != 0)
return;
} else {
const size_t len = sizeof(kSafariExtensionsBlock);
if (limit - data != (int)(len))
return;
if (memcmp(data, kSafariExtensionsBlock, len) != 0)
return;
}
s->s3->is_probably_safari = 1;
}
# endif /* !OPENSSL_NO_EC */
/*
* tls1_alpn_handle_client_hello is called to save the ALPN extension in a
* ClientHello. data: the contents of the extension, not including the type
* and length. data_len: the number of bytes in |data| al: a pointer to the
* alert value to send in the event of a non-zero return. returns: 0 on
* success.
*/
static int tls1_alpn_handle_client_hello(SSL *s, const unsigned char *data,
unsigned data_len, int *al)
{
unsigned i;
unsigned proto_len;
if (data_len < 2)
goto parse_error;
/*
* data should contain a uint16 length followed by a series of 8-bit,
* length-prefixed strings.
*/
i = ((unsigned)data[0]) << 8 | ((unsigned)data[1]);
data_len -= 2;
data += 2;
if (data_len != i)
goto parse_error;
if (data_len < 2)
goto parse_error;
for (i = 0; i < data_len;) {
proto_len = data[i];
i++;
if (proto_len == 0)
goto parse_error;
if (i + proto_len < i || i + proto_len > data_len)
goto parse_error;
i += proto_len;
}
if (s->cert->alpn_proposed != NULL)
OPENSSL_free(s->cert->alpn_proposed);
s->cert->alpn_proposed = OPENSSL_malloc(data_len);
if (s->cert->alpn_proposed == NULL) {
*al = SSL_AD_INTERNAL_ERROR;
return -1;
}
memcpy(s->cert->alpn_proposed, data, data_len);
s->cert->alpn_proposed_len = data_len;
return 0;
parse_error:
*al = SSL_AD_DECODE_ERROR;
return -1;
}
/*
* Process the ALPN extension in a ClientHello.
* al: a pointer to the alert value to send in the event of a failure.
* returns 1 on success, 0 on failure: al set only on failure
*/
static int tls1_alpn_handle_client_hello_late(SSL *s, int *al)
{
const unsigned char *selected = NULL;
unsigned char selected_len = 0;
if (s->ctx->alpn_select_cb != NULL && s->cert->alpn_proposed != NULL) {
int r = s->ctx->alpn_select_cb(s, &selected, &selected_len,
s->cert->alpn_proposed,
s->cert->alpn_proposed_len,
s->ctx->alpn_select_cb_arg);
if (r == SSL_TLSEXT_ERR_OK) {
OPENSSL_free(s->s3->alpn_selected);
s->s3->alpn_selected = OPENSSL_malloc(selected_len);
if (s->s3->alpn_selected == NULL) {
*al = SSL_AD_INTERNAL_ERROR;
return 0;
}
memcpy(s->s3->alpn_selected, selected, selected_len);
s->s3->alpn_selected_len = selected_len;
# ifndef OPENSSL_NO_NEXTPROTONEG
/* ALPN takes precedence over NPN. */
s->s3->next_proto_neg_seen = 0;
# endif
}
}
return 1;
}
static int ssl_scan_clienthello_tlsext(SSL *s, unsigned char **p,
unsigned char *limit, int *al)
{
unsigned short type;
unsigned short size;
unsigned short len;
unsigned char *data = *p;
int renegotiate_seen = 0;
s->servername_done = 0;
s->tlsext_status_type = -1;
# ifndef OPENSSL_NO_NEXTPROTONEG
s->s3->next_proto_neg_seen = 0;
# endif
if (s->s3->alpn_selected) {
OPENSSL_free(s->s3->alpn_selected);
s->s3->alpn_selected = NULL;
}
s->s3->alpn_selected_len = 0;
if (s->cert->alpn_proposed) {
OPENSSL_free(s->cert->alpn_proposed);
s->cert->alpn_proposed = NULL;
}
s->cert->alpn_proposed_len = 0;
# ifndef OPENSSL_NO_HEARTBEATS
s->tlsext_heartbeat &= ~(SSL_TLSEXT_HB_ENABLED |
SSL_TLSEXT_HB_DONT_SEND_REQUESTS);
# endif
# ifndef OPENSSL_NO_EC
if (s->options & SSL_OP_SAFARI_ECDHE_ECDSA_BUG)
ssl_check_for_safari(s, data, limit);
# endif /* !OPENSSL_NO_EC */
/* Clear any signature algorithms extension received */
if (s->cert->peer_sigalgs) {
OPENSSL_free(s->cert->peer_sigalgs);
s->cert->peer_sigalgs = NULL;
}
# ifndef OPENSSL_NO_SRP
if (s->srp_ctx.login != NULL) {
OPENSSL_free(s->srp_ctx.login);
s->srp_ctx.login = NULL;
}
# endif
s->srtp_profile = NULL;
if (data == limit)
goto ri_check;
if (limit - data < 2)
goto err;
n2s(data, len);
if (limit - data != len)
goto err;
while (limit - data >= 4) {
n2s(data, type);
n2s(data, size);
if (limit - data < size)
goto err;
# if 0
fprintf(stderr, "Received extension type %d size %d\n", type, size);
# endif
if (s->tlsext_debug_cb)
s->tlsext_debug_cb(s, 0, type, data, size, s->tlsext_debug_arg);
/*-
* 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.
*
*/
if (type == TLSEXT_TYPE_server_name) {
unsigned char *sdata;
int servname_type;
int dsize;
if (size < 2)
goto err;
n2s(data, dsize);
size -= 2;
if (dsize > size)
goto err;
sdata = data;
while (dsize > 3) {
servname_type = *(sdata++);
n2s(sdata, len);
dsize -= 3;
if (len > dsize)
goto err;
if (s->servername_done == 0)
switch (servname_type) {
case TLSEXT_NAMETYPE_host_name:
if (!s->hit) {
if (s->session->tlsext_hostname)
goto err;
if (len > TLSEXT_MAXLEN_host_name) {
*al = TLS1_AD_UNRECOGNIZED_NAME;
return 0;
}
if ((s->session->tlsext_hostname =
OPENSSL_malloc(len + 1)) == NULL) {
*al = TLS1_AD_INTERNAL_ERROR;
return 0;
}
memcpy(s->session->tlsext_hostname, sdata, len);
s->session->tlsext_hostname[len] = '\0';
if (strlen(s->session->tlsext_hostname) != len) {
OPENSSL_free(s->session->tlsext_hostname);
s->session->tlsext_hostname = NULL;
*al = TLS1_AD_UNRECOGNIZED_NAME;
return 0;
}
s->servername_done = 1;
} else
s->servername_done = s->session->tlsext_hostname
&& strlen(s->session->tlsext_hostname) == len
&& strncmp(s->session->tlsext_hostname,
(char *)sdata, len) == 0;
break;
default:
break;
}
dsize -= len;
}
if (dsize != 0)
goto err;
}
# ifndef OPENSSL_NO_SRP
else if (type == TLSEXT_TYPE_srp) {
if (size == 0 || ((len = data[0])) != (size - 1))
goto err;
if (s->srp_ctx.login != NULL)
goto err;
if ((s->srp_ctx.login = OPENSSL_malloc(len + 1)) == NULL)
return -1;
memcpy(s->srp_ctx.login, &data[1], len);
s->srp_ctx.login[len] = '\0';
if (strlen(s->srp_ctx.login) != len)
goto err;
}
# endif
# ifndef OPENSSL_NO_EC
else if (type == TLSEXT_TYPE_ec_point_formats) {
unsigned char *sdata = data;
- int ecpointformatlist_length = *(sdata++);
+ int ecpointformatlist_length;
+ if (size == 0)
+ goto err;
+
+ ecpointformatlist_length = *(sdata++);
if (ecpointformatlist_length != size - 1 ||
ecpointformatlist_length < 1)
goto err;
if (!s->hit) {
if (s->session->tlsext_ecpointformatlist) {
OPENSSL_free(s->session->tlsext_ecpointformatlist);
s->session->tlsext_ecpointformatlist = NULL;
}
s->session->tlsext_ecpointformatlist_length = 0;
if ((s->session->tlsext_ecpointformatlist =
OPENSSL_malloc(ecpointformatlist_length)) == NULL) {
*al = TLS1_AD_INTERNAL_ERROR;
return 0;
}
s->session->tlsext_ecpointformatlist_length =
ecpointformatlist_length;
memcpy(s->session->tlsext_ecpointformatlist, sdata,
ecpointformatlist_length);
}
# if 0
fprintf(stderr,
"ssl_parse_clienthello_tlsext s->session->tlsext_ecpointformatlist (length=%i) ",
s->session->tlsext_ecpointformatlist_length);
sdata = s->session->tlsext_ecpointformatlist;
for (i = 0; i < s->session->tlsext_ecpointformatlist_length; i++)
fprintf(stderr, "%i ", *(sdata++));
fprintf(stderr, "\n");
# endif
} else if (type == TLSEXT_TYPE_elliptic_curves) {
unsigned char *sdata = data;
int ellipticcurvelist_length = (*(sdata++) << 8);
ellipticcurvelist_length += (*(sdata++));
if (ellipticcurvelist_length != size - 2 ||
ellipticcurvelist_length < 1 ||
/* Each NamedCurve is 2 bytes. */
ellipticcurvelist_length & 1)
goto err;
if (!s->hit) {
if (s->session->tlsext_ellipticcurvelist)
goto err;
s->session->tlsext_ellipticcurvelist_length = 0;
if ((s->session->tlsext_ellipticcurvelist =
OPENSSL_malloc(ellipticcurvelist_length)) == NULL) {
*al = TLS1_AD_INTERNAL_ERROR;
return 0;
}
s->session->tlsext_ellipticcurvelist_length =
ellipticcurvelist_length;
memcpy(s->session->tlsext_ellipticcurvelist, sdata,
ellipticcurvelist_length);
}
# if 0
fprintf(stderr,
"ssl_parse_clienthello_tlsext s->session->tlsext_ellipticcurvelist (length=%i) ",
s->session->tlsext_ellipticcurvelist_length);
sdata = s->session->tlsext_ellipticcurvelist;
for (i = 0; i < s->session->tlsext_ellipticcurvelist_length; i++)
fprintf(stderr, "%i ", *(sdata++));
fprintf(stderr, "\n");
# endif
}
# endif /* OPENSSL_NO_EC */
# ifdef TLSEXT_TYPE_opaque_prf_input
else if (type == TLSEXT_TYPE_opaque_prf_input) {
unsigned char *sdata = data;
if (size < 2) {
*al = SSL_AD_DECODE_ERROR;
return 0;
}
n2s(sdata, s->s3->client_opaque_prf_input_len);
if (s->s3->client_opaque_prf_input_len != size - 2) {
*al = SSL_AD_DECODE_ERROR;
return 0;
}
if (s->s3->client_opaque_prf_input != NULL) {
/* shouldn't really happen */
OPENSSL_free(s->s3->client_opaque_prf_input);
}
/* dummy byte just to get non-NULL */
if (s->s3->client_opaque_prf_input_len == 0)
s->s3->client_opaque_prf_input = OPENSSL_malloc(1);
else
s->s3->client_opaque_prf_input =
BUF_memdup(sdata, s->s3->client_opaque_prf_input_len);
if (s->s3->client_opaque_prf_input == NULL) {
*al = TLS1_AD_INTERNAL_ERROR;
return 0;
}
}
# endif
else if (type == TLSEXT_TYPE_session_ticket) {
if (s->tls_session_ticket_ext_cb &&
!s->tls_session_ticket_ext_cb(s, data, size,
s->tls_session_ticket_ext_cb_arg))
{
*al = TLS1_AD_INTERNAL_ERROR;
return 0;
}
} else if (type == TLSEXT_TYPE_renegotiate) {
if (!ssl_parse_clienthello_renegotiate_ext(s, data, size, al))
return 0;
renegotiate_seen = 1;
} else if (type == TLSEXT_TYPE_signature_algorithms) {
int dsize;
if (s->cert->peer_sigalgs || size < 2)
goto err;
n2s(data, dsize);
size -= 2;
if (dsize != size || dsize & 1 || !dsize)
goto err;
if (!tls1_save_sigalgs(s, data, dsize))
goto err;
} else if (type == TLSEXT_TYPE_status_request) {
if (size < 5)
goto err;
s->tlsext_status_type = *data++;
size--;
if (s->tlsext_status_type == TLSEXT_STATUSTYPE_ocsp) {
const unsigned char *sdata;
int dsize;
/* Read in responder_id_list */
n2s(data, dsize);
size -= 2;
if (dsize > size)
goto err;
/*
* We remove any OCSP_RESPIDs from a previous handshake
* to prevent unbounded memory growth - CVE-2016-6304
*/
sk_OCSP_RESPID_pop_free(s->tlsext_ocsp_ids,
OCSP_RESPID_free);
if (dsize > 0) {
s->tlsext_ocsp_ids = sk_OCSP_RESPID_new_null();
if (s->tlsext_ocsp_ids == NULL) {
*al = SSL_AD_INTERNAL_ERROR;
return 0;
}
} else {
s->tlsext_ocsp_ids = NULL;
}
while (dsize > 0) {
OCSP_RESPID *id;
int idsize;
if (dsize < 4)
goto err;
n2s(data, idsize);
dsize -= 2 + idsize;
size -= 2 + idsize;
if (dsize < 0)
goto err;
sdata = data;
data += idsize;
id = d2i_OCSP_RESPID(NULL, &sdata, idsize);
if (!id)
goto err;
if (data != sdata) {
OCSP_RESPID_free(id);
goto err;
}
if (!sk_OCSP_RESPID_push(s->tlsext_ocsp_ids, id)) {
OCSP_RESPID_free(id);
*al = SSL_AD_INTERNAL_ERROR;
return 0;
}
}
/* Read in request_extensions */
if (size < 2)
goto err;
n2s(data, dsize);
size -= 2;
if (dsize != size)
goto err;
sdata = data;
if (dsize > 0) {
if (s->tlsext_ocsp_exts) {
sk_X509_EXTENSION_pop_free(s->tlsext_ocsp_exts,
X509_EXTENSION_free);
}
s->tlsext_ocsp_exts =
d2i_X509_EXTENSIONS(NULL, &sdata, dsize);
if (!s->tlsext_ocsp_exts || (data + dsize != sdata))
goto err;
}
}
/*
* We don't know what to do with any other type * so ignore it.
*/
else
s->tlsext_status_type = -1;
}
# ifndef OPENSSL_NO_HEARTBEATS
else if (type == TLSEXT_TYPE_heartbeat) {
switch (data[0]) {
case 0x01: /* Client allows us to send HB requests */
s->tlsext_heartbeat |= SSL_TLSEXT_HB_ENABLED;
break;
case 0x02: /* Client doesn't accept HB requests */
s->tlsext_heartbeat |= SSL_TLSEXT_HB_ENABLED;
s->tlsext_heartbeat |= SSL_TLSEXT_HB_DONT_SEND_REQUESTS;
break;
default:
*al = SSL_AD_ILLEGAL_PARAMETER;
return 0;
}
}
# endif
# ifndef OPENSSL_NO_NEXTPROTONEG
else if (type == TLSEXT_TYPE_next_proto_neg &&
s->s3->tmp.finish_md_len == 0) {
/*-
* We shouldn't accept this extension on a
* renegotiation.
*
* s->new_session will be set on renegotiation, but we
* probably shouldn't rely that it couldn't be set on
* the initial renegotation too in certain cases (when
* there's some other reason to disallow resuming an
* earlier session -- the current code won't be doing
* anything like that, but this might change).
*
* A valid sign that there's been a previous handshake
* in this connection is if s->s3->tmp.finish_md_len >
* 0. (We are talking about a check that will happen
* in the Hello protocol round, well before a new
* Finished message could have been computed.)
*/
s->s3->next_proto_neg_seen = 1;
}
# endif
else if (type == TLSEXT_TYPE_application_layer_protocol_negotiation &&
s->s3->tmp.finish_md_len == 0) {
if (tls1_alpn_handle_client_hello(s, data, size, al) != 0)
return 0;
}
/* session ticket processed earlier */
# ifndef OPENSSL_NO_SRTP
else if (SSL_IS_DTLS(s) && SSL_get_srtp_profiles(s)
&& type == TLSEXT_TYPE_use_srtp) {
if (ssl_parse_clienthello_use_srtp_ext(s, data, size, al))
return 0;
}
# endif
data += size;
}
/* Spurious data on the end */
if (data != limit)
goto err;
*p = data;
ri_check:
/* Need RI if renegotiating */
if (!renegotiate_seen && s->renegotiate &&
!(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)) {
*al = SSL_AD_HANDSHAKE_FAILURE;
SSLerr(SSL_F_SSL_SCAN_CLIENTHELLO_TLSEXT,
SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
return 0;
}
return 1;
err:
*al = SSL_AD_DECODE_ERROR;
return 0;
}
/*
* Parse any custom extensions found. "data" is the start of the extension data
* and "limit" is the end of the record. TODO: add strict syntax checking.
*/
static int ssl_scan_clienthello_custom_tlsext(SSL *s,
const unsigned char *data,
const unsigned char *limit,
int *al)
{
unsigned short type, size, len;
/* If resumed session or no custom extensions nothing to do */
if (s->hit || s->cert->srv_ext.meths_count == 0)
return 1;
if (limit - data <= 2)
return 1;
n2s(data, len);
if (limit - data < len)
return 1;
while (limit - data >= 4) {
n2s(data, type);
n2s(data, size);
if (limit - data < size)
return 1;
if (custom_ext_parse(s, 1 /* server */ , type, data, size, al) <= 0)
return 0;
data += size;
}
return 1;
}
int ssl_parse_clienthello_tlsext(SSL *s, unsigned char **p,
unsigned char *limit)
{
int al = -1;
unsigned char *ptmp = *p;
/*
* Internally supported extensions are parsed first so SNI can be handled
* before custom extensions. An application processing SNI will typically
* switch the parent context using SSL_set_SSL_CTX and custom extensions
* need to be handled by the new SSL_CTX structure.
*/
if (ssl_scan_clienthello_tlsext(s, p, limit, &al) <= 0) {
ssl3_send_alert(s, SSL3_AL_FATAL, al);
return 0;
}
if (ssl_check_clienthello_tlsext_early(s) <= 0) {
SSLerr(SSL_F_SSL_PARSE_CLIENTHELLO_TLSEXT, SSL_R_CLIENTHELLO_TLSEXT);
return 0;
}
custom_ext_init(&s->cert->srv_ext);
if (ssl_scan_clienthello_custom_tlsext(s, ptmp, limit, &al) <= 0) {
ssl3_send_alert(s, SSL3_AL_FATAL, al);
return 0;
}
return 1;
}
# 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.
*/
static char ssl_next_proto_validate(unsigned char *d, unsigned len)
{
unsigned int off = 0;
while (off < len) {
if (d[off] == 0)
return 0;
off += d[off];
off++;
}
return off == len;
}
# endif
static int ssl_scan_serverhello_tlsext(SSL *s, unsigned char **p,
unsigned char *d, int n, int *al)
{
unsigned short length;
unsigned short type;
unsigned short size;
unsigned char *data = *p;
int tlsext_servername = 0;
int renegotiate_seen = 0;
# ifndef OPENSSL_NO_NEXTPROTONEG
s->s3->next_proto_neg_seen = 0;
# endif
s->tlsext_ticket_expected = 0;
if (s->s3->alpn_selected) {
OPENSSL_free(s->s3->alpn_selected);
s->s3->alpn_selected = NULL;
}
# ifndef OPENSSL_NO_HEARTBEATS
s->tlsext_heartbeat &= ~(SSL_TLSEXT_HB_ENABLED |
SSL_TLSEXT_HB_DONT_SEND_REQUESTS);
# endif
if ((d + n) - data <= 2)
goto ri_check;
n2s(data, length);
if ((d + n) - data != length) {
*al = SSL_AD_DECODE_ERROR;
return 0;
}
while ((d + n) - data >= 4) {
n2s(data, type);
n2s(data, size);
if ((d + n) - data < size)
goto ri_check;
if (s->tlsext_debug_cb)
s->tlsext_debug_cb(s, 1, type, data, size, s->tlsext_debug_arg);
if (type == TLSEXT_TYPE_server_name) {
if (s->tlsext_hostname == NULL || size > 0) {
*al = TLS1_AD_UNRECOGNIZED_NAME;
return 0;
}
tlsext_servername = 1;
}
# ifndef OPENSSL_NO_EC
else if (type == TLSEXT_TYPE_ec_point_formats) {
unsigned char *sdata = data;
- int ecpointformatlist_length = *(sdata++);
+ int ecpointformatlist_length;
+
+ if (size == 0) {
+ *al = TLS1_AD_DECODE_ERROR;
+ return 0;
+ }
+ ecpointformatlist_length = *(sdata++);
if (ecpointformatlist_length != size - 1) {
*al = TLS1_AD_DECODE_ERROR;
return 0;
}
if (!s->hit) {
s->session->tlsext_ecpointformatlist_length = 0;
if (s->session->tlsext_ecpointformatlist != NULL)
OPENSSL_free(s->session->tlsext_ecpointformatlist);
if ((s->session->tlsext_ecpointformatlist =
OPENSSL_malloc(ecpointformatlist_length)) == NULL) {
*al = TLS1_AD_INTERNAL_ERROR;
return 0;
}
s->session->tlsext_ecpointformatlist_length =
ecpointformatlist_length;
memcpy(s->session->tlsext_ecpointformatlist, sdata,
ecpointformatlist_length);
}
# if 0
fprintf(stderr,
"ssl_parse_serverhello_tlsext s->session->tlsext_ecpointformatlist ");
sdata = s->session->tlsext_ecpointformatlist;
for (i = 0; i < s->session->tlsext_ecpointformatlist_length; i++)
fprintf(stderr, "%i ", *(sdata++));
fprintf(stderr, "\n");
# endif
}
# endif /* OPENSSL_NO_EC */
else if (type == TLSEXT_TYPE_session_ticket) {
if (s->tls_session_ticket_ext_cb &&
!s->tls_session_ticket_ext_cb(s, data, size,
s->tls_session_ticket_ext_cb_arg))
{
*al = TLS1_AD_INTERNAL_ERROR;
return 0;
}
if ((SSL_get_options(s) & SSL_OP_NO_TICKET)
|| (size > 0)) {
*al = TLS1_AD_UNSUPPORTED_EXTENSION;
return 0;
}
s->tlsext_ticket_expected = 1;
}
# ifdef TLSEXT_TYPE_opaque_prf_input
else if (type == TLSEXT_TYPE_opaque_prf_input) {
unsigned char *sdata = data;
if (size < 2) {
*al = SSL_AD_DECODE_ERROR;
return 0;
}
n2s(sdata, s->s3->server_opaque_prf_input_len);
if (s->s3->server_opaque_prf_input_len != size - 2) {
*al = SSL_AD_DECODE_ERROR;
return 0;
}
if (s->s3->server_opaque_prf_input != NULL) {
/* shouldn't really happen */
OPENSSL_free(s->s3->server_opaque_prf_input);
}
if (s->s3->server_opaque_prf_input_len == 0) {
/* dummy byte just to get non-NULL */
s->s3->server_opaque_prf_input = OPENSSL_malloc(1);
} else {
s->s3->server_opaque_prf_input =
BUF_memdup(sdata, s->s3->server_opaque_prf_input_len);
}
if (s->s3->server_opaque_prf_input == NULL) {
*al = TLS1_AD_INTERNAL_ERROR;
return 0;
}
}
# endif
else if (type == TLSEXT_TYPE_status_request) {
/*
* MUST be empty and only sent if we've requested a status
* request message.
*/
if ((s->tlsext_status_type == -1) || (size > 0)) {
*al = TLS1_AD_UNSUPPORTED_EXTENSION;
return 0;
}
/* Set flag to expect CertificateStatus message */
s->tlsext_status_expected = 1;
}
# ifndef OPENSSL_NO_NEXTPROTONEG
else if (type == TLSEXT_TYPE_next_proto_neg &&
s->s3->tmp.finish_md_len == 0) {
unsigned char *selected;
unsigned char selected_len;
/* We must have requested it. */
if (s->ctx->next_proto_select_cb == NULL) {
*al = TLS1_AD_UNSUPPORTED_EXTENSION;
return 0;
}
/* The data must be valid */
if (!ssl_next_proto_validate(data, size)) {
*al = TLS1_AD_DECODE_ERROR;
return 0;
}
if (s->
ctx->next_proto_select_cb(s, &selected, &selected_len, data,
size,
s->ctx->next_proto_select_cb_arg) !=
SSL_TLSEXT_ERR_OK) {
*al = TLS1_AD_INTERNAL_ERROR;
return 0;
}
/*
* Could be non-NULL if server has sent multiple NPN extensions in
* a single Serverhello
*/
OPENSSL_free(s->next_proto_negotiated);
s->next_proto_negotiated = OPENSSL_malloc(selected_len);
if (!s->next_proto_negotiated) {
*al = TLS1_AD_INTERNAL_ERROR;
return 0;
}
memcpy(s->next_proto_negotiated, selected, selected_len);
s->next_proto_negotiated_len = selected_len;
s->s3->next_proto_neg_seen = 1;
}
# endif
else if (type == TLSEXT_TYPE_application_layer_protocol_negotiation) {
unsigned len;
/* We must have requested it. */
if (!s->cert->alpn_sent) {
*al = TLS1_AD_UNSUPPORTED_EXTENSION;
return 0;
}
if (size < 4) {
*al = TLS1_AD_DECODE_ERROR;
return 0;
}
/*-
* The extension data consists of:
* uint16 list_length
* uint8 proto_length;
* uint8 proto[proto_length];
*/
len = data[0];
len <<= 8;
len |= data[1];
if (len != (unsigned)size - 2) {
*al = TLS1_AD_DECODE_ERROR;
return 0;
}
len = data[2];
if (len != (unsigned)size - 3) {
*al = TLS1_AD_DECODE_ERROR;
return 0;
}
if (s->s3->alpn_selected)
OPENSSL_free(s->s3->alpn_selected);
s->s3->alpn_selected = OPENSSL_malloc(len);
if (!s->s3->alpn_selected) {
*al = TLS1_AD_INTERNAL_ERROR;
return 0;
}
memcpy(s->s3->alpn_selected, data + 3, len);
s->s3->alpn_selected_len = len;
}
else if (type == TLSEXT_TYPE_renegotiate) {
if (!ssl_parse_serverhello_renegotiate_ext(s, data, size, al))
return 0;
renegotiate_seen = 1;
}
# ifndef OPENSSL_NO_HEARTBEATS
else if (type == TLSEXT_TYPE_heartbeat) {
switch (data[0]) {
case 0x01: /* Server allows us to send HB requests */
s->tlsext_heartbeat |= SSL_TLSEXT_HB_ENABLED;
break;
case 0x02: /* Server doesn't accept HB requests */
s->tlsext_heartbeat |= SSL_TLSEXT_HB_ENABLED;
s->tlsext_heartbeat |= SSL_TLSEXT_HB_DONT_SEND_REQUESTS;
break;
default:
*al = SSL_AD_ILLEGAL_PARAMETER;
return 0;
}
}
# endif
# ifndef OPENSSL_NO_SRTP
else if (SSL_IS_DTLS(s) && type == TLSEXT_TYPE_use_srtp) {
if (ssl_parse_serverhello_use_srtp_ext(s, data, size, al))
return 0;
}
# endif
/*
* If this extension type was not otherwise handled, but matches a
* custom_cli_ext_record, then send it to the c callback
*/
else if (custom_ext_parse(s, 0, type, data, size, al) <= 0)
return 0;
data += size;
}
if (data != d + n) {
*al = SSL_AD_DECODE_ERROR;
return 0;
}
if (!s->hit && tlsext_servername == 1) {
if (s->tlsext_hostname) {
if (s->session->tlsext_hostname == NULL) {
s->session->tlsext_hostname = BUF_strdup(s->tlsext_hostname);
if (!s->session->tlsext_hostname) {
*al = SSL_AD_UNRECOGNIZED_NAME;
return 0;
}
} else {
*al = SSL_AD_DECODE_ERROR;
return 0;
}
}
}
*p = data;
ri_check:
/*
* Determine if we need to see RI. Strictly speaking if we want to avoid
* an attack we should *always* see RI even on initial server hello
* because the client doesn't see any renegotiation during an attack.
* However this would mean we could not connect to any server which
* doesn't support RI so for the immediate future tolerate RI absence on
* initial connect only.
*/
if (!renegotiate_seen && !(s->options & SSL_OP_LEGACY_SERVER_CONNECT)
&& !(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)) {
*al = SSL_AD_HANDSHAKE_FAILURE;
SSLerr(SSL_F_SSL_SCAN_SERVERHELLO_TLSEXT,
SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
return 0;
}
return 1;
}
int ssl_prepare_clienthello_tlsext(SSL *s)
{
# ifdef TLSEXT_TYPE_opaque_prf_input
{
int r = 1;
if (s->ctx->tlsext_opaque_prf_input_callback != 0) {
r = s->ctx->tlsext_opaque_prf_input_callback(s, NULL, 0,
s->
ctx->tlsext_opaque_prf_input_callback_arg);
if (!r)
return -1;
}
if (s->tlsext_opaque_prf_input != NULL) {
if (s->s3->client_opaque_prf_input != NULL) {
/* shouldn't really happen */
OPENSSL_free(s->s3->client_opaque_prf_input);
}
if (s->tlsext_opaque_prf_input_len == 0) {
/* dummy byte just to get non-NULL */
s->s3->client_opaque_prf_input = OPENSSL_malloc(1);
} else {
s->s3->client_opaque_prf_input =
BUF_memdup(s->tlsext_opaque_prf_input,
s->tlsext_opaque_prf_input_len);
}
if (s->s3->client_opaque_prf_input == NULL) {
SSLerr(SSL_F_SSL_PREPARE_CLIENTHELLO_TLSEXT,
ERR_R_MALLOC_FAILURE);
return -1;
}
s->s3->client_opaque_prf_input_len =
s->tlsext_opaque_prf_input_len;
}
if (r == 2)
/*
* at callback's request, insist on receiving an appropriate
* server opaque PRF input
*/
s->s3->server_opaque_prf_input_len =
s->tlsext_opaque_prf_input_len;
}
# endif
s->cert->alpn_sent = 0;
return 1;
}
int ssl_prepare_serverhello_tlsext(SSL *s)
{
return 1;
}
static int ssl_check_clienthello_tlsext_early(SSL *s)
{
int ret = SSL_TLSEXT_ERR_NOACK;
int al = SSL_AD_UNRECOGNIZED_NAME;
# ifndef OPENSSL_NO_EC
/*
* The handling of the ECPointFormats extension is done elsewhere, namely
* in ssl3_choose_cipher in s3_lib.c.
*/
/*
* The handling of the EllipticCurves extension is done elsewhere, namely
* in ssl3_choose_cipher in s3_lib.c.
*/
# endif
if (s->ctx != NULL && s->ctx->tlsext_servername_callback != 0)
ret =
s->ctx->tlsext_servername_callback(s, &al,
s->ctx->tlsext_servername_arg);
else if (s->initial_ctx != NULL
&& s->initial_ctx->tlsext_servername_callback != 0)
ret =
s->initial_ctx->tlsext_servername_callback(s, &al,
s->
initial_ctx->tlsext_servername_arg);
# ifdef TLSEXT_TYPE_opaque_prf_input
{
/*
* This sort of belongs into ssl_prepare_serverhello_tlsext(), but we
* might be sending an alert in response to the client hello, so this
* has to happen here in ssl_check_clienthello_tlsext_early().
*/
int r = 1;
if (s->ctx->tlsext_opaque_prf_input_callback != 0) {
r = s->ctx->tlsext_opaque_prf_input_callback(s, NULL, 0,
s->
ctx->tlsext_opaque_prf_input_callback_arg);
if (!r) {
ret = SSL_TLSEXT_ERR_ALERT_FATAL;
al = SSL_AD_INTERNAL_ERROR;
goto err;
}
}
if (s->s3->server_opaque_prf_input != NULL) {
/* shouldn't really happen */
OPENSSL_free(s->s3->server_opaque_prf_input);
}
s->s3->server_opaque_prf_input = NULL;
if (s->tlsext_opaque_prf_input != NULL) {
if (s->s3->client_opaque_prf_input != NULL &&
s->s3->client_opaque_prf_input_len ==
s->tlsext_opaque_prf_input_len) {
/*
* can only use this extension if we have a server opaque PRF
* input of the same length as the client opaque PRF input!
*/
if (s->tlsext_opaque_prf_input_len == 0) {
/* dummy byte just to get non-NULL */
s->s3->server_opaque_prf_input = OPENSSL_malloc(1);
} else {
s->s3->server_opaque_prf_input =
BUF_memdup(s->tlsext_opaque_prf_input,
s->tlsext_opaque_prf_input_len);
}
if (s->s3->server_opaque_prf_input == NULL) {
ret = SSL_TLSEXT_ERR_ALERT_FATAL;
al = SSL_AD_INTERNAL_ERROR;
goto err;
}
s->s3->server_opaque_prf_input_len =
s->tlsext_opaque_prf_input_len;
}
}
if (r == 2 && s->s3->server_opaque_prf_input == NULL) {
/*
* The callback wants to enforce use of the extension, but we
* can't do that with the client opaque PRF input; abort the
* handshake.
*/
ret = SSL_TLSEXT_ERR_ALERT_FATAL;
al = SSL_AD_HANDSHAKE_FAILURE;
}
}
err:
# endif
switch (ret) {
case SSL_TLSEXT_ERR_ALERT_FATAL:
ssl3_send_alert(s, SSL3_AL_FATAL, al);
return -1;
case SSL_TLSEXT_ERR_ALERT_WARNING:
ssl3_send_alert(s, SSL3_AL_WARNING, al);
return 1;
case SSL_TLSEXT_ERR_NOACK:
s->servername_done = 0;
default:
return 1;
}
}
int tls1_set_server_sigalgs(SSL *s)
{
int al;
size_t i;
/* Clear any shared sigtnature algorithms */
if (s->cert->shared_sigalgs) {
OPENSSL_free(s->cert->shared_sigalgs);
s->cert->shared_sigalgs = NULL;
s->cert->shared_sigalgslen = 0;
}
/* Clear certificate digests and validity flags */
for (i = 0; i < SSL_PKEY_NUM; i++) {
s->cert->pkeys[i].digest = NULL;
s->cert->pkeys[i].valid_flags = 0;
}
/* If sigalgs received process it. */
if (s->cert->peer_sigalgs) {
if (!tls1_process_sigalgs(s)) {
SSLerr(SSL_F_TLS1_SET_SERVER_SIGALGS, ERR_R_MALLOC_FAILURE);
al = SSL_AD_INTERNAL_ERROR;
goto err;
}
/* Fatal error is no shared signature algorithms */
if (!s->cert->shared_sigalgs) {
SSLerr(SSL_F_TLS1_SET_SERVER_SIGALGS,
SSL_R_NO_SHARED_SIGATURE_ALGORITHMS);
al = SSL_AD_ILLEGAL_PARAMETER;
goto err;
}
} else
ssl_cert_set_default_md(s->cert);
return 1;
err:
ssl3_send_alert(s, SSL3_AL_FATAL, al);
return 0;
}
/*
* Upon success, returns 1.
* Upon failure, returns 0 and sets |al| to the appropriate fatal alert.
*/
int ssl_check_clienthello_tlsext_late(SSL *s, int *al)
{
/*
* If status request then ask callback what to do. Note: this must be
* called after servername callbacks in case the certificate has changed,
* and must be called after the cipher has been chosen because this may
* influence which certificate is sent
*/
if ((s->tlsext_status_type != -1) && s->ctx && s->ctx->tlsext_status_cb) {
int ret;
CERT_PKEY *certpkey;
certpkey = ssl_get_server_send_pkey(s);
/* If no certificate can't return certificate status */
if (certpkey != NULL) {
/*
* Set current certificate to one we will use so SSL_get_certificate
* et al can pick it up.
*/
s->cert->key = certpkey;
ret = s->ctx->tlsext_status_cb(s, s->ctx->tlsext_status_arg);
switch (ret) {
/* We don't want to send a status request response */
case SSL_TLSEXT_ERR_NOACK:
s->tlsext_status_expected = 0;
break;
/* status request response should be sent */
case SSL_TLSEXT_ERR_OK:
if (s->tlsext_ocsp_resp)
s->tlsext_status_expected = 1;
break;
/* something bad happened */
case SSL_TLSEXT_ERR_ALERT_FATAL:
default:
*al = SSL_AD_INTERNAL_ERROR;
return 0;
}
}
}
if (!tls1_alpn_handle_client_hello_late(s, al)) {
return 0;
}
return 1;
}
int ssl_check_serverhello_tlsext(SSL *s)
{
int ret = SSL_TLSEXT_ERR_NOACK;
int al = SSL_AD_UNRECOGNIZED_NAME;
# ifndef OPENSSL_NO_EC
/*
* 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.
*/
unsigned long alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
unsigned long alg_a = s->s3->tmp.new_cipher->algorithm_auth;
if ((s->tlsext_ecpointformatlist != NULL)
&& (s->tlsext_ecpointformatlist_length > 0)
&& (s->session->tlsext_ecpointformatlist != NULL)
&& (s->session->tlsext_ecpointformatlist_length > 0)
&& ((alg_k & (SSL_kEECDH | SSL_kECDHr | SSL_kECDHe))
|| (alg_a & SSL_aECDSA))) {
/* we are using an ECC cipher */
size_t i;
unsigned char *list;
int found_uncompressed = 0;
list = s->session->tlsext_ecpointformatlist;
for (i = 0; i < s->session->tlsext_ecpointformatlist_length; i++) {
if (*(list++) == TLSEXT_ECPOINTFORMAT_uncompressed) {
found_uncompressed = 1;
break;
}
}
if (!found_uncompressed) {
SSLerr(SSL_F_SSL_CHECK_SERVERHELLO_TLSEXT,
SSL_R_TLS_INVALID_ECPOINTFORMAT_LIST);
return -1;
}
}
ret = SSL_TLSEXT_ERR_OK;
# endif /* OPENSSL_NO_EC */
if (s->ctx != NULL && s->ctx->tlsext_servername_callback != 0)
ret =
s->ctx->tlsext_servername_callback(s, &al,
s->ctx->tlsext_servername_arg);
else if (s->initial_ctx != NULL
&& s->initial_ctx->tlsext_servername_callback != 0)
ret =
s->initial_ctx->tlsext_servername_callback(s, &al,
s->
initial_ctx->tlsext_servername_arg);
# ifdef TLSEXT_TYPE_opaque_prf_input
if (s->s3->server_opaque_prf_input_len > 0) {
/*
* This case may indicate that we, as a client, want to insist on
* using opaque PRF inputs. So first verify that we really have a
* value from the server too.
*/
if (s->s3->server_opaque_prf_input == NULL) {
ret = SSL_TLSEXT_ERR_ALERT_FATAL;
al = SSL_AD_HANDSHAKE_FAILURE;
}
/*
* Anytime the server *has* sent an opaque PRF input, we need to
* check that we have a client opaque PRF input of the same size.
*/
if (s->s3->client_opaque_prf_input == NULL ||
s->s3->client_opaque_prf_input_len !=
s->s3->server_opaque_prf_input_len) {
ret = SSL_TLSEXT_ERR_ALERT_FATAL;
al = SSL_AD_ILLEGAL_PARAMETER;
}
}
# endif
OPENSSL_free(s->tlsext_ocsp_resp);
s->tlsext_ocsp_resp = NULL;
s->tlsext_ocsp_resplen = -1;
/*
* If we've requested certificate status and we wont get one tell the
* callback
*/
if ((s->tlsext_status_type != -1) && !(s->tlsext_status_expected)
&& !(s->hit) && s->ctx && s->ctx->tlsext_status_cb) {
int r;
/*
* Call callback with resp == NULL and resplen == -1 so callback
* knows there is no response
*/
r = s->ctx->tlsext_status_cb(s, s->ctx->tlsext_status_arg);
if (r == 0) {
al = SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE;
ret = SSL_TLSEXT_ERR_ALERT_FATAL;
}
if (r < 0) {
al = SSL_AD_INTERNAL_ERROR;
ret = SSL_TLSEXT_ERR_ALERT_FATAL;
}
}
switch (ret) {
case SSL_TLSEXT_ERR_ALERT_FATAL:
ssl3_send_alert(s, SSL3_AL_FATAL, al);
return -1;
case SSL_TLSEXT_ERR_ALERT_WARNING:
ssl3_send_alert(s, SSL3_AL_WARNING, al);
return 1;
case SSL_TLSEXT_ERR_NOACK:
s->servername_done = 0;
default:
return 1;
}
}
int ssl_parse_serverhello_tlsext(SSL *s, unsigned char **p, unsigned char *d,
int n)
{
int al = -1;
if (s->version < SSL3_VERSION)
return 1;
if (ssl_scan_serverhello_tlsext(s, p, d, n, &al) <= 0) {
ssl3_send_alert(s, SSL3_AL_FATAL, al);
return 0;
}
if (ssl_check_serverhello_tlsext(s) <= 0) {
SSLerr(SSL_F_SSL_PARSE_SERVERHELLO_TLSEXT, SSL_R_SERVERHELLO_TLSEXT);
return 0;
}
return 1;
}
/*-
* Since the server cache lookup is done early on in the processing of the
* ClientHello, and other operations depend on the result, we need to handle
* any TLS session ticket extension at the same time.
*
* session_id: points at the session ID in the ClientHello. This code will
* read past the end of this in order to parse out the session ticket
* extension, if any.
* len: the length of the session ID.
* limit: a pointer to the first byte after the ClientHello.
* ret: (output) on return, if a ticket was decrypted, then this is set to
* point to the resulting session.
*
* If s->tls_session_secret_cb is set 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->tlsext_ticket_expected be set to 1.
*
* Returns:
* -1: fatal error, either from parsing or decrypting the ticket.
* 0: no ticket was found (or was ignored, based on settings).
* 1: a zero length extension was found, indicating that the client supports
* session tickets but doesn't currently have one to offer.
* 2: either s->tls_session_secret_cb was set, or a ticket was offered but
* couldn't be decrypted because of a non-fatal error.
* 3: a ticket was successfully decrypted and *ret was set.
*
* Side effects:
* Sets s->tlsext_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->tlsext_ticket_key_cb asked to renew the client's ticket.
* Otherwise, s->tlsext_ticket_expected is set to 0.
*/
int tls1_process_ticket(SSL *s, unsigned char *session_id, int len,
const unsigned char *limit, SSL_SESSION **ret)
{
/* Point after session ID in client hello */
const unsigned char *p = session_id + len;
unsigned short i;
*ret = NULL;
s->tlsext_ticket_expected = 0;
/*
* If tickets disabled behave as if no ticket present to permit stateful
* resumption.
*/
if (SSL_get_options(s) & SSL_OP_NO_TICKET)
return 0;
if ((s->version <= SSL3_VERSION) || !limit)
return 0;
if (p >= limit)
return -1;
/* Skip past DTLS cookie */
if (SSL_IS_DTLS(s)) {
i = *(p++);
if (limit - p <= i)
return -1;
p += i;
}
/* Skip past cipher list */
n2s(p, i);
if (limit - p <= i)
return -1;
p += i;
/* Skip past compression algorithm list */
i = *(p++);
if (limit - p < i)
return -1;
p += i;
/* Now at start of extensions */
if (limit - p <= 2)
return 0;
n2s(p, i);
while (limit - p >= 4) {
unsigned short type, size;
n2s(p, type);
n2s(p, size);
if (limit - p < size)
return 0;
if (type == TLSEXT_TYPE_session_ticket) {
int r;
if (size == 0) {
/*
* The client will accept a ticket but doesn't currently have
* one.
*/
s->tlsext_ticket_expected = 1;
return 1;
}
if (s->tls_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.
*/
return 2;
}
r = tls_decrypt_ticket(s, p, size, session_id, len, ret);
switch (r) {
case 2: /* ticket couldn't be decrypted */
s->tlsext_ticket_expected = 1;
return 2;
case 3: /* ticket was decrypted */
return r;
case 4: /* ticket decrypted but need to renew */
s->tlsext_ticket_expected = 1;
return 3;
default: /* fatal error */
return -1;
}
}
p += size;
}
return 0;
}
/*-
* tls_decrypt_ticket attempts to decrypt a session ticket.
*
* etick: points to the body of the session ticket extension.
* eticklen: the length of the session tickets extenion.
* 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.
*
* Returns:
* -1: fatal error, either from parsing or decrypting the ticket.
* 2: the ticket couldn't be decrypted.
* 3: a ticket was successfully decrypted and *psess was set.
* 4: same as 3, but the ticket needs to be renewed.
*/
static int tls_decrypt_ticket(SSL *s, const unsigned char *etick,
int eticklen, const unsigned char *sess_id,
int sesslen, SSL_SESSION **psess)
{
SSL_SESSION *sess;
unsigned char *sdec;
const unsigned char *p;
int slen, mlen, renew_ticket = 0;
unsigned char tick_hmac[EVP_MAX_MD_SIZE];
HMAC_CTX hctx;
EVP_CIPHER_CTX ctx;
SSL_CTX *tctx = s->initial_ctx;
+ /* Need at least keyname + iv */
+ if (eticklen < 16 + EVP_MAX_IV_LENGTH)
+ return 2;
+
/* Initialize session ticket encryption and HMAC contexts */
HMAC_CTX_init(&hctx);
EVP_CIPHER_CTX_init(&ctx);
if (tctx->tlsext_ticket_key_cb) {
unsigned char *nctick = (unsigned char *)etick;
int rv = tctx->tlsext_ticket_key_cb(s, nctick, nctick + 16,
&ctx, &hctx, 0);
if (rv < 0)
- return -1;
- if (rv == 0)
+ goto err;
+ if (rv == 0) {
+ HMAC_CTX_cleanup(&hctx);
+ EVP_CIPHER_CTX_cleanup(&ctx);
return 2;
+ }
if (rv == 2)
renew_ticket = 1;
} else {
/* Check key name matches */
if (memcmp(etick, tctx->tlsext_tick_key_name, 16))
return 2;
if (HMAC_Init_ex(&hctx, tctx->tlsext_tick_hmac_key, 16,
tlsext_tick_md(), NULL) <= 0
|| EVP_DecryptInit_ex(&ctx, EVP_aes_128_cbc(), NULL,
tctx->tlsext_tick_aes_key,
etick + 16) <= 0) {
goto err;
}
}
/*
* Attempt to process session ticket, first conduct sanity and integrity
* checks on ticket.
*/
mlen = HMAC_size(&hctx);
if (mlen < 0) {
goto err;
}
/* Sanity check ticket length: must exceed keyname + IV + HMAC */
if (eticklen <= 16 + EVP_CIPHER_CTX_iv_length(&ctx) + mlen) {
HMAC_CTX_cleanup(&hctx);
EVP_CIPHER_CTX_cleanup(&ctx);
return 2;
}
eticklen -= mlen;
/* Check HMAC of encrypted ticket */
if (HMAC_Update(&hctx, etick, eticklen) <= 0
|| HMAC_Final(&hctx, tick_hmac, NULL) <= 0) {
goto err;
}
HMAC_CTX_cleanup(&hctx);
if (CRYPTO_memcmp(tick_hmac, etick + eticklen, mlen)) {
EVP_CIPHER_CTX_cleanup(&ctx);
return 2;
}
/* Attempt to decrypt session data */
/* Move p after IV to start of encrypted ticket, update length */
p = etick + 16 + EVP_CIPHER_CTX_iv_length(&ctx);
eticklen -= 16 + EVP_CIPHER_CTX_iv_length(&ctx);
sdec = OPENSSL_malloc(eticklen);
if (sdec == NULL
|| EVP_DecryptUpdate(&ctx, sdec, &slen, p, eticklen) <= 0) {
EVP_CIPHER_CTX_cleanup(&ctx);
OPENSSL_free(sdec);
return -1;
}
if (EVP_DecryptFinal(&ctx, sdec + slen, &mlen) <= 0) {
EVP_CIPHER_CTX_cleanup(&ctx);
OPENSSL_free(sdec);
return 2;
}
slen += mlen;
EVP_CIPHER_CTX_cleanup(&ctx);
p = sdec;
sess = d2i_SSL_SESSION(NULL, &p, slen);
slen -= p - sdec;
OPENSSL_free(sdec);
if (sess) {
/* Some additional consistency checks */
if (slen != 0 || sess->session_id_length != 0) {
SSL_SESSION_free(sess);
return 2;
}
/*
* 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;
*psess = sess;
if (renew_ticket)
return 4;
else
return 3;
}
ERR_clear_error();
/*
* For session parse failure, indicate that we need to send a new ticket.
*/
return 2;
err:
EVP_CIPHER_CTX_cleanup(&ctx);
HMAC_CTX_cleanup(&hctx);
return -1;
}
/* Tables to translate from NIDs to TLS v1.2 ids */
typedef struct {
int nid;
int id;
} tls12_lookup;
static tls12_lookup tls12_md[] = {
{NID_md5, TLSEXT_hash_md5},
{NID_sha1, TLSEXT_hash_sha1},
{NID_sha224, TLSEXT_hash_sha224},
{NID_sha256, TLSEXT_hash_sha256},
{NID_sha384, TLSEXT_hash_sha384},
{NID_sha512, TLSEXT_hash_sha512}
};
static tls12_lookup tls12_sig[] = {
{EVP_PKEY_RSA, TLSEXT_signature_rsa},
{EVP_PKEY_DSA, TLSEXT_signature_dsa},
{EVP_PKEY_EC, TLSEXT_signature_ecdsa}
};
static int tls12_find_id(int nid, tls12_lookup *table, size_t tlen)
{
size_t i;
for (i = 0; i < tlen; i++) {
if (table[i].nid == nid)
return table[i].id;
}
return -1;
}
static int tls12_find_nid(int id, tls12_lookup *table, size_t tlen)
{
size_t i;
for (i = 0; i < tlen; i++) {
if ((table[i].id) == id)
return table[i].nid;
}
return NID_undef;
}
int tls12_get_sigandhash(unsigned char *p, const EVP_PKEY *pk,
const EVP_MD *md)
{
int sig_id, md_id;
if (!md)
return 0;
md_id = tls12_find_id(EVP_MD_type(md), tls12_md,
sizeof(tls12_md) / sizeof(tls12_lookup));
if (md_id == -1)
return 0;
sig_id = tls12_get_sigid(pk);
if (sig_id == -1)
return 0;
p[0] = (unsigned char)md_id;
p[1] = (unsigned char)sig_id;
return 1;
}
int tls12_get_sigid(const EVP_PKEY *pk)
{
return tls12_find_id(pk->type, tls12_sig,
sizeof(tls12_sig) / sizeof(tls12_lookup));
}
const EVP_MD *tls12_get_hash(unsigned char hash_alg)
{
switch (hash_alg) {
# ifndef OPENSSL_NO_MD5
case TLSEXT_hash_md5:
# ifdef OPENSSL_FIPS
if (FIPS_mode())
return NULL;
# endif
return EVP_md5();
# endif
# ifndef OPENSSL_NO_SHA
case TLSEXT_hash_sha1:
return EVP_sha1();
# endif
# ifndef OPENSSL_NO_SHA256
case TLSEXT_hash_sha224:
return EVP_sha224();
case TLSEXT_hash_sha256:
return EVP_sha256();
# endif
# ifndef OPENSSL_NO_SHA512
case TLSEXT_hash_sha384:
return EVP_sha384();
case TLSEXT_hash_sha512:
return EVP_sha512();
# endif
default:
return NULL;
}
}
static int tls12_get_pkey_idx(unsigned char sig_alg)
{
switch (sig_alg) {
# ifndef OPENSSL_NO_RSA
case TLSEXT_signature_rsa:
return SSL_PKEY_RSA_SIGN;
# endif
# ifndef OPENSSL_NO_DSA
case TLSEXT_signature_dsa:
return SSL_PKEY_DSA_SIGN;
# endif
# ifndef OPENSSL_NO_ECDSA
case TLSEXT_signature_ecdsa:
return SSL_PKEY_ECC;
# endif
}
return -1;
}
/* Convert TLS 1.2 signature algorithm extension values into NIDs */
static void tls1_lookup_sigalg(int *phash_nid, int *psign_nid,
int *psignhash_nid, const unsigned char *data)
{
int sign_nid = NID_undef, hash_nid = NID_undef;
if (!phash_nid && !psign_nid && !psignhash_nid)
return;
if (phash_nid || psignhash_nid) {
hash_nid = tls12_find_nid(data[0], tls12_md,
sizeof(tls12_md) / sizeof(tls12_lookup));
if (phash_nid)
*phash_nid = hash_nid;
}
if (psign_nid || psignhash_nid) {
sign_nid = tls12_find_nid(data[1], tls12_sig,
sizeof(tls12_sig) / sizeof(tls12_lookup));
if (psign_nid)
*psign_nid = sign_nid;
}
if (psignhash_nid) {
if (sign_nid == NID_undef || hash_nid == NID_undef
|| OBJ_find_sigid_by_algs(psignhash_nid, hash_nid,
sign_nid) <= 0)
*psignhash_nid = NID_undef;
}
}
/* Given preference and allowed sigalgs set shared sigalgs */
static int tls12_do_shared_sigalgs(TLS_SIGALGS *shsig,
const unsigned char *pref, size_t preflen,
const unsigned char *allow,
size_t allowlen)
{
const unsigned char *ptmp, *atmp;
size_t i, j, nmatch = 0;
for (i = 0, ptmp = pref; i < preflen; i += 2, ptmp += 2) {
/* Skip disabled hashes or signature algorithms */
if (tls12_get_hash(ptmp[0]) == NULL)
continue;
if (tls12_get_pkey_idx(ptmp[1]) == -1)
continue;
for (j = 0, atmp = allow; j < allowlen; j += 2, atmp += 2) {
if (ptmp[0] == atmp[0] && ptmp[1] == atmp[1]) {
nmatch++;
if (shsig) {
shsig->rhash = ptmp[0];
shsig->rsign = ptmp[1];
tls1_lookup_sigalg(&shsig->hash_nid,
&shsig->sign_nid,
&shsig->signandhash_nid, ptmp);
shsig++;
}
break;
}
}
}
return nmatch;
}
/* Set shared signature algorithms for SSL structures */
static int tls1_set_shared_sigalgs(SSL *s)
{
const unsigned char *pref, *allow, *conf;
size_t preflen, allowlen, conflen;
size_t nmatch;
TLS_SIGALGS *salgs = NULL;
CERT *c = s->cert;
unsigned int is_suiteb = tls1_suiteb(s);
if (c->shared_sigalgs) {
OPENSSL_free(c->shared_sigalgs);
c->shared_sigalgs = NULL;
c->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 = c->peer_sigalgs;
allowlen = c->peer_sigalgslen;
} else {
allow = conf;
allowlen = conflen;
pref = c->peer_sigalgs;
preflen = c->peer_sigalgslen;
}
nmatch = tls12_do_shared_sigalgs(NULL, pref, preflen, allow, allowlen);
if (nmatch) {
salgs = OPENSSL_malloc(nmatch * sizeof(TLS_SIGALGS));
if (!salgs)
return 0;
nmatch = tls12_do_shared_sigalgs(salgs, pref, preflen, allow, allowlen);
} else {
salgs = NULL;
}
c->shared_sigalgs = salgs;
c->shared_sigalgslen = nmatch;
return 1;
}
/* Set preferred digest for each key type */
int tls1_save_sigalgs(SSL *s, const unsigned char *data, int dsize)
{
CERT *c = s->cert;
/* Extension ignored for inappropriate versions */
if (!SSL_USE_SIGALGS(s))
return 1;
/* Should never happen */
if (!c)
return 0;
if (c->peer_sigalgs)
OPENSSL_free(c->peer_sigalgs);
c->peer_sigalgs = OPENSSL_malloc(dsize);
if (!c->peer_sigalgs)
return 0;
c->peer_sigalgslen = dsize;
memcpy(c->peer_sigalgs, data, dsize);
return 1;
}
int tls1_process_sigalgs(SSL *s)
{
int idx;
size_t i;
const EVP_MD *md;
CERT *c = s->cert;
TLS_SIGALGS *sigptr;
if (!tls1_set_shared_sigalgs(s))
return 0;
# ifdef OPENSSL_SSL_DEBUG_BROKEN_PROTOCOL
if (s->cert->cert_flags & SSL_CERT_FLAG_BROKEN_PROTOCOL) {
/*
* Use first set signature preference to force message digest,
* ignoring any peer preferences.
*/
const unsigned char *sigs = NULL;
if (s->server)
sigs = c->conf_sigalgs;
else
sigs = c->client_sigalgs;
if (sigs) {
idx = tls12_get_pkey_idx(sigs[1]);
md = tls12_get_hash(sigs[0]);
c->pkeys[idx].digest = md;
c->pkeys[idx].valid_flags = CERT_PKEY_EXPLICIT_SIGN;
if (idx == SSL_PKEY_RSA_SIGN) {
c->pkeys[SSL_PKEY_RSA_ENC].valid_flags =
CERT_PKEY_EXPLICIT_SIGN;
c->pkeys[SSL_PKEY_RSA_ENC].digest = md;
}
}
}
# endif
for (i = 0, sigptr = c->shared_sigalgs;
i < c->shared_sigalgslen; i++, sigptr++) {
idx = tls12_get_pkey_idx(sigptr->rsign);
if (idx > 0 && c->pkeys[idx].digest == NULL) {
md = tls12_get_hash(sigptr->rhash);
c->pkeys[idx].digest = md;
c->pkeys[idx].valid_flags = CERT_PKEY_EXPLICIT_SIGN;
if (idx == SSL_PKEY_RSA_SIGN) {
c->pkeys[SSL_PKEY_RSA_ENC].valid_flags =
CERT_PKEY_EXPLICIT_SIGN;
c->pkeys[SSL_PKEY_RSA_ENC].digest = md;
}
}
}
/*
* In strict mode leave unset digests as NULL to indicate we can't use
* the certificate for signing.
*/
if (!(s->cert->cert_flags & SSL_CERT_FLAGS_CHECK_TLS_STRICT)) {
/*
* Set any remaining keys to default values. NOTE: if alg is not
* supported it stays as NULL.
*/
# ifndef OPENSSL_NO_DSA
if (!c->pkeys[SSL_PKEY_DSA_SIGN].digest)
c->pkeys[SSL_PKEY_DSA_SIGN].digest = EVP_sha1();
# endif
# ifndef OPENSSL_NO_RSA
if (!c->pkeys[SSL_PKEY_RSA_SIGN].digest) {
c->pkeys[SSL_PKEY_RSA_SIGN].digest = EVP_sha1();
c->pkeys[SSL_PKEY_RSA_ENC].digest = EVP_sha1();
}
# endif
# ifndef OPENSSL_NO_ECDSA
if (!c->pkeys[SSL_PKEY_ECC].digest)
c->pkeys[SSL_PKEY_ECC].digest = EVP_sha1();
# endif
}
return 1;
}
int SSL_get_sigalgs(SSL *s, int idx,
int *psign, int *phash, int *psignhash,
unsigned char *rsig, unsigned char *rhash)
{
const unsigned char *psig = s->cert->peer_sigalgs;
if (psig == NULL)
return 0;
if (idx >= 0) {
idx <<= 1;
if (idx >= (int)s->cert->peer_sigalgslen)
return 0;
psig += idx;
if (rhash)
*rhash = psig[0];
if (rsig)
*rsig = psig[1];
tls1_lookup_sigalg(phash, psign, psignhash, psig);
}
return s->cert->peer_sigalgslen / 2;
}
int SSL_get_shared_sigalgs(SSL *s, int idx,
int *psign, int *phash, int *psignhash,
unsigned char *rsig, unsigned char *rhash)
{
TLS_SIGALGS *shsigalgs = s->cert->shared_sigalgs;
if (!shsigalgs || idx >= (int)s->cert->shared_sigalgslen)
return 0;
shsigalgs += idx;
if (phash)
*phash = shsigalgs->hash_nid;
if (psign)
*psign = shsigalgs->sign_nid;
if (psignhash)
*psignhash = shsigalgs->signandhash_nid;
if (rsig)
*rsig = shsigalgs->rsign;
if (rhash)
*rhash = shsigalgs->rhash;
return s->cert->shared_sigalgslen;
}
# ifndef OPENSSL_NO_HEARTBEATS
int tls1_process_heartbeat(SSL *s)
{
unsigned char *p = &s->s3->rrec.data[0], *pl;
unsigned short hbtype;
unsigned int payload;
unsigned int padding = 16; /* Use minimum padding */
if (s->msg_callback)
s->msg_callback(0, s->version, TLS1_RT_HEARTBEAT,
&s->s3->rrec.data[0], s->s3->rrec.length,
s, s->msg_callback_arg);
/* Read type and payload length first */
if (1 + 2 + 16 > s->s3->rrec.length)
return 0; /* silently discard */
hbtype = *p++;
n2s(p, payload);
if (1 + 2 + payload + 16 > s->s3->rrec.length)
return 0; /* silently discard per RFC 6520 sec. 4 */
pl = p;
if (hbtype == TLS1_HB_REQUEST) {
unsigned char *buffer, *bp;
int r;
/*
* Allocate memory for the response, size is 1 bytes message type,
* plus 2 bytes payload length, plus payload, plus padding
*/
buffer = OPENSSL_malloc(1 + 2 + payload + padding);
if (buffer == NULL)
return -1;
bp = buffer;
/* Enter response type, length and copy payload */
*bp++ = TLS1_HB_RESPONSE;
s2n(payload, bp);
memcpy(bp, pl, payload);
bp += payload;
/* Random padding */
if (RAND_bytes(bp, padding) <= 0) {
OPENSSL_free(buffer);
return -1;
}
r = ssl3_write_bytes(s, TLS1_RT_HEARTBEAT, buffer,
3 + payload + padding);
if (r >= 0 && s->msg_callback)
s->msg_callback(1, s->version, TLS1_RT_HEARTBEAT,
buffer, 3 + payload + padding,
s, s->msg_callback_arg);
OPENSSL_free(buffer);
if (r < 0)
return r;
} else if (hbtype == TLS1_HB_RESPONSE) {
unsigned int seq;
/*
* We only send sequence numbers (2 bytes unsigned int), and 16
* random bytes, so we just try to read the sequence number
*/
n2s(pl, seq);
if (payload == 18 && seq == s->tlsext_hb_seq) {
s->tlsext_hb_seq++;
s->tlsext_hb_pending = 0;
}
}
return 0;
}
int tls1_heartbeat(SSL *s)
{
unsigned char *buf, *p;
int ret = -1;
unsigned int payload = 18; /* Sequence number + random bytes */
unsigned int padding = 16; /* Use minimum padding */
/* Only send if peer supports and accepts HB requests... */
if (!(s->tlsext_heartbeat & SSL_TLSEXT_HB_ENABLED) ||
s->tlsext_heartbeat & SSL_TLSEXT_HB_DONT_SEND_REQUESTS) {
SSLerr(SSL_F_TLS1_HEARTBEAT, SSL_R_TLS_HEARTBEAT_PEER_DOESNT_ACCEPT);
return -1;
}
/* ...and there is none in flight yet... */
if (s->tlsext_hb_pending) {
SSLerr(SSL_F_TLS1_HEARTBEAT, SSL_R_TLS_HEARTBEAT_PENDING);
return -1;
}
/* ...and no handshake in progress. */
if (SSL_in_init(s) || s->in_handshake) {
SSLerr(SSL_F_TLS1_HEARTBEAT, SSL_R_UNEXPECTED_MESSAGE);
return -1;
}
/*
* Check if padding is too long, payload and padding must not exceed 2^14
* - 3 = 16381 bytes in total.
*/
OPENSSL_assert(payload + padding <= 16381);
/*-
* Create HeartBeat message, we just use a sequence number
* as payload to distuingish different messages and add
* some random stuff.
* - Message Type, 1 byte
* - Payload Length, 2 bytes (unsigned int)
* - Payload, the sequence number (2 bytes uint)
* - Payload, random bytes (16 bytes uint)
* - Padding
*/
buf = OPENSSL_malloc(1 + 2 + payload + padding);
if (buf == NULL)
return -1;
p = buf;
/* Message Type */
*p++ = TLS1_HB_REQUEST;
/* Payload length (18 bytes here) */
s2n(payload, p);
/* Sequence number */
s2n(s->tlsext_hb_seq, p);
/* 16 random bytes */
if (RAND_bytes(p, 16) <= 0) {
SSLerr(SSL_F_TLS1_HEARTBEAT, ERR_R_INTERNAL_ERROR);
goto err;
}
p += 16;
/* Random padding */
if (RAND_bytes(p, padding) <= 0) {
SSLerr(SSL_F_TLS1_HEARTBEAT, ERR_R_INTERNAL_ERROR);
goto err;
}
ret = ssl3_write_bytes(s, TLS1_RT_HEARTBEAT, buf, 3 + payload + padding);
if (ret >= 0) {
if (s->msg_callback)
s->msg_callback(1, s->version, TLS1_RT_HEARTBEAT,
buf, 3 + payload + padding,
s, s->msg_callback_arg);
s->tlsext_hb_pending = 1;
}
err:
OPENSSL_free(buf);
return ret;
}
# endif
# define MAX_SIGALGLEN (TLSEXT_hash_num * TLSEXT_signature_num * 2)
typedef struct {
size_t sigalgcnt;
int sigalgs[MAX_SIGALGLEN];
} sig_cb_st;
static int sig_cb(const char *elem, int len, void *arg)
{
sig_cb_st *sarg = arg;
size_t i;
char etmp[20], *p;
int sig_alg, hash_alg;
if (elem == NULL)
return 0;
if (sarg->sigalgcnt == MAX_SIGALGLEN)
return 0;
if (len > (int)(sizeof(etmp) - 1))
return 0;
memcpy(etmp, elem, len);
etmp[len] = 0;
p = strchr(etmp, '+');
if (!p)
return 0;
*p = 0;
p++;
if (!*p)
return 0;
if (!strcmp(etmp, "RSA"))
sig_alg = EVP_PKEY_RSA;
else if (!strcmp(etmp, "DSA"))
sig_alg = EVP_PKEY_DSA;
else if (!strcmp(etmp, "ECDSA"))
sig_alg = EVP_PKEY_EC;
else
return 0;
hash_alg = OBJ_sn2nid(p);
if (hash_alg == NID_undef)
hash_alg = OBJ_ln2nid(p);
if (hash_alg == NID_undef)
return 0;
for (i = 0; i < sarg->sigalgcnt; i += 2) {
if (sarg->sigalgs[i] == sig_alg && sarg->sigalgs[i + 1] == hash_alg)
return 0;
}
sarg->sigalgs[sarg->sigalgcnt++] = hash_alg;
sarg->sigalgs[sarg->sigalgcnt++] = sig_alg;
return 1;
}
/*
* Set suppored 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_sigalgs(c, sig.sigalgs, sig.sigalgcnt, client);
}
int tls1_set_sigalgs(CERT *c, const int *psig_nids, size_t salglen,
int client)
{
unsigned char *sigalgs, *sptr;
int rhash, rsign;
size_t i;
if (salglen & 1)
return 0;
sigalgs = OPENSSL_malloc(salglen);
if (sigalgs == NULL)
return 0;
for (i = 0, sptr = sigalgs; i < salglen; i += 2) {
rhash = tls12_find_id(*psig_nids++, tls12_md,
sizeof(tls12_md) / sizeof(tls12_lookup));
rsign = tls12_find_id(*psig_nids++, tls12_sig,
sizeof(tls12_sig) / sizeof(tls12_lookup));
if (rhash == -1 || rsign == -1)
goto err;
*sptr++ = rhash;
*sptr++ = rsign;
}
if (client) {
if (c->client_sigalgs)
OPENSSL_free(c->client_sigalgs);
c->client_sigalgs = sigalgs;
c->client_sigalgslen = salglen;
} else {
if (c->conf_sigalgs)
OPENSSL_free(c->conf_sigalgs);
c->conf_sigalgs = sigalgs;
c->conf_sigalgslen = salglen;
}
return 1;
err:
OPENSSL_free(sigalgs);
return 0;
}
static int tls1_check_sig_alg(CERT *c, X509 *x, int default_nid)
{
int sig_nid;
size_t i;
if (default_nid == -1)
return 1;
sig_nid = X509_get_signature_nid(x);
if (default_nid)
return sig_nid == default_nid ? 1 : 0;
for (i = 0; i < c->shared_sigalgslen; i++)
if (sig_nid == c->shared_sigalgs[i].signandhash_nid)
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)
{
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 stict 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;
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 = cpk - c->pkeys;
} else
cpk = c->pkeys + 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;
# ifdef OPENSSL_SSL_DEBUG_BROKEN_PROTOCOL
/* Allow any certificate to pass test */
if (s->cert->cert_flags & SSL_CERT_FLAG_BROKEN_PROTOCOL) {
rv = CERT_PKEY_STRICT_FLAGS | CERT_PKEY_EXPLICIT_SIGN |
CERT_PKEY_VALID | CERT_PKEY_SIGN;
cpk->valid_flags = rv;
return rv;
}
# endif
} else {
if (!x || !pk)
return 0;
idx = ssl_cert_type(x, pk);
if (idx == -1)
return 0;
cpk = c->pkeys + 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;
unsigned char rsign = 0;
if (c->peer_sigalgs)
default_nid = 0;
/* If no sigalgs extension use defaults from RFC5246 */
else {
switch (idx) {
case SSL_PKEY_RSA_ENC:
case SSL_PKEY_RSA_SIGN:
case SSL_PKEY_DH_RSA:
rsign = TLSEXT_signature_rsa;
default_nid = NID_sha1WithRSAEncryption;
break;
case SSL_PKEY_DSA_SIGN:
case SSL_PKEY_DH_DSA:
rsign = TLSEXT_signature_dsa;
default_nid = NID_dsaWithSHA1;
break;
case SSL_PKEY_ECC:
rsign = TLSEXT_signature_ecdsa;
default_nid = NID_ecdsa_with_SHA1;
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 unsigned char *p = c->conf_sigalgs;
for (j = 0; j < c->conf_sigalgslen; j += 2, p += 2) {
if (p[0] == TLSEXT_hash_sha1 && p[1] == 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 (!tls1_check_sig_alg(c, 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(c, 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, check_flags ? 1 : 2))
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;
switch (pk->type) {
case EVP_PKEY_RSA:
check_type = TLS_CT_RSA_SIGN;
break;
case EVP_PKEY_DSA:
check_type = TLS_CT_DSS_SIGN;
break;
case EVP_PKEY_EC:
check_type = TLS_CT_ECDSA_SIGN;
break;
case EVP_PKEY_DH:
case EVP_PKEY_DHX:
{
int cert_type = X509_certificate_type(x, pk);
if (cert_type & EVP_PKS_RSA)
check_type = TLS_CT_RSA_FIXED_DH;
if (cert_type & EVP_PKS_DSA)
check_type = TLS_CT_DSS_FIXED_DH;
}
}
if (check_type) {
const unsigned char *ctypes;
int ctypelen;
if (c->ctypes) {
ctypes = c->ctypes;
ctypelen = (int)c->ctype_num;
} else {
ctypes = (unsigned char *)s->s3->tmp.ctype;
ctypelen = s->s3->tmp.ctype_num;
}
for (i = 0; i < ctypelen; i++) {
if (ctypes[i] == 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.ca_names;
if (!sk_X509_NAME_num(ca_dn))
rv |= CERT_PKEY_ISSUER_NAME;
if (!(rv & CERT_PKEY_ISSUER_NAME)) {
if (ssl_check_ca_name(ca_dn, x))
rv |= CERT_PKEY_ISSUER_NAME;
}
if (!(rv & CERT_PKEY_ISSUER_NAME)) {
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) {
if (cpk->valid_flags & CERT_PKEY_EXPLICIT_SIGN)
rv |= CERT_PKEY_EXPLICIT_SIGN | CERT_PKEY_SIGN;
else if (cpk->digest)
rv |= 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)
cpk->valid_flags = rv;
else {
/* Preserve explicit sign flag, clear rest */
cpk->valid_flags &= CERT_PKEY_EXPLICIT_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_ENC);
tls1_check_chain(s, NULL, NULL, NULL, SSL_PKEY_RSA_SIGN);
tls1_check_chain(s, NULL, NULL, NULL, SSL_PKEY_DSA_SIGN);
tls1_check_chain(s, NULL, NULL, NULL, SSL_PKEY_DH_RSA);
tls1_check_chain(s, NULL, NULL, NULL, SSL_PKEY_DH_DSA);
tls1_check_chain(s, NULL, NULL, NULL, SSL_PKEY_ECC);
}
/* User level utiity 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);
}
#endif
diff --git a/ssl/t1_trce.c b/ssl/t1_trce.c
index c5e21df77a6b..dc62df8f94cf 100644
--- a/ssl/t1_trce.c
+++ b/ssl/t1_trce.c
@@ -1,1266 +1,1268 @@
/* ssl/t1_trce.c */
/*
* Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL
* project.
*/
/* ====================================================================
* Copyright (c) 2012 The OpenSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* licensing@OpenSSL.org.
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*
*/
#include "ssl_locl.h"
#ifndef OPENSSL_NO_SSL_TRACE
/* Packet trace support for OpenSSL */
typedef struct {
int num;
const char *name;
} ssl_trace_tbl;
# define ssl_trace_str(val, tbl) \
do_ssl_trace_str(val, tbl, sizeof(tbl)/sizeof(ssl_trace_tbl))
# define ssl_trace_list(bio, indent, msg, msglen, value, table) \
do_ssl_trace_list(bio, indent, msg, msglen, value, \
table, sizeof(table)/sizeof(ssl_trace_tbl))
static const char *do_ssl_trace_str(int val, ssl_trace_tbl *tbl, size_t ntbl)
{
size_t i;
for (i = 0; i < ntbl; i++, tbl++) {
if (tbl->num == val)
return tbl->name;
}
return "UNKNOWN";
}
static int do_ssl_trace_list(BIO *bio, int indent,
const unsigned char *msg, size_t msglen,
size_t vlen, ssl_trace_tbl *tbl, size_t ntbl)
{
int val;
if (msglen % vlen)
return 0;
while (msglen) {
val = msg[0];
if (vlen == 2)
val = (val << 8) | msg[1];
BIO_indent(bio, indent, 80);
BIO_printf(bio, "%s (%d)\n", do_ssl_trace_str(val, tbl, ntbl), val);
msg += vlen;
msglen -= vlen;
}
return 1;
}
/* Version number */
static ssl_trace_tbl ssl_version_tbl[] = {
{SSL2_VERSION, "SSL 2.0"},
{SSL3_VERSION, "SSL 3.0"},
{TLS1_VERSION, "TLS 1.0"},
{TLS1_1_VERSION, "TLS 1.1"},
{TLS1_2_VERSION, "TLS 1.2"},
{DTLS1_VERSION, "DTLS 1.0"},
{DTLS1_2_VERSION, "DTLS 1.2"},
{DTLS1_BAD_VER, "DTLS 1.0 (bad)"}
};
static ssl_trace_tbl ssl_content_tbl[] = {
{SSL3_RT_CHANGE_CIPHER_SPEC, "ChangeCipherSpec"},
{SSL3_RT_ALERT, "Alert"},
{SSL3_RT_HANDSHAKE, "Handshake"},
{SSL3_RT_APPLICATION_DATA, "ApplicationData"},
{TLS1_RT_HEARTBEAT, "HeartBeat"}
};
/* Handshake types */
static ssl_trace_tbl ssl_handshake_tbl[] = {
{SSL3_MT_HELLO_REQUEST, "HelloRequest"},
{SSL3_MT_CLIENT_HELLO, "ClientHello"},
{SSL3_MT_SERVER_HELLO, "ServerHello"},
{DTLS1_MT_HELLO_VERIFY_REQUEST, "HelloVerifyRequest"},
{SSL3_MT_NEWSESSION_TICKET, "NewSessionTicket"},
{SSL3_MT_CERTIFICATE, "Certificate"},
{SSL3_MT_SERVER_KEY_EXCHANGE, "ServerKeyExchange"},
{SSL3_MT_CERTIFICATE_REQUEST, "CertificateRequest"},
{SSL3_MT_CLIENT_KEY_EXCHANGE, "ClientKeyExchange"},
{SSL3_MT_CERTIFICATE_STATUS, "CertificateStatus"},
{SSL3_MT_SERVER_DONE, "ServerHelloDone"},
{SSL3_MT_CERTIFICATE_VERIFY, "CertificateVerify"},
{SSL3_MT_CLIENT_KEY_EXCHANGE, "ClientKeyExchange"},
{SSL3_MT_FINISHED, "Finished"},
{SSL3_MT_CERTIFICATE_STATUS, "CertificateStatus"}
};
/* Cipher suites */
static ssl_trace_tbl ssl_ciphers_tbl[] = {
{0x0000, "SSL_NULL_WITH_NULL_NULL"},
{0x0001, "SSL_RSA_WITH_NULL_MD5"},
{0x0002, "SSL_RSA_WITH_NULL_SHA"},
{0x0003, "SSL_RSA_EXPORT_WITH_RC4_40_MD5"},
{0x0004, "SSL_RSA_WITH_RC4_128_MD5"},
{0x0005, "SSL_RSA_WITH_RC4_128_SHA"},
{0x0006, "SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5"},
{0x0007, "SSL_RSA_WITH_IDEA_CBC_SHA"},
{0x0008, "SSL_RSA_EXPORT_WITH_DES40_CBC_SHA"},
{0x0009, "SSL_RSA_WITH_DES_CBC_SHA"},
{0x000A, "SSL_RSA_WITH_3DES_EDE_CBC_SHA"},
{0x000B, "SSL_DH_DSS_EXPORT_WITH_DES40_CBC_SHA"},
{0x000C, "SSL_DH_DSS_WITH_DES_CBC_SHA"},
{0x000D, "SSL_DH_DSS_WITH_3DES_EDE_CBC_SHA"},
{0x000E, "SSL_DH_RSA_EXPORT_WITH_DES40_CBC_SHA"},
{0x000F, "SSL_DH_RSA_WITH_DES_CBC_SHA"},
{0x0010, "SSL_DH_RSA_WITH_3DES_EDE_CBC_SHA"},
{0x0011, "SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA"},
{0x0012, "SSL_DHE_DSS_WITH_DES_CBC_SHA"},
{0x0013, "SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA"},
{0x0014, "SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA"},
{0x0015, "SSL_DHE_RSA_WITH_DES_CBC_SHA"},
{0x0016, "SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA"},
{0x0017, "SSL_DH_anon_EXPORT_WITH_RC4_40_MD5"},
{0x0018, "SSL_DH_anon_WITH_RC4_128_MD5"},
{0x0019, "SSL_DH_anon_EXPORT_WITH_DES40_CBC_SHA"},
{0x001A, "SSL_DH_anon_WITH_DES_CBC_SHA"},
{0x001B, "SSL_DH_anon_WITH_3DES_EDE_CBC_SHA"},
{0x001D, "SSL_FORTEZZA_KEA_WITH_FORTEZZA_CBC_SHA"},
{0x001E, "SSL_FORTEZZA_KEA_WITH_RC4_128_SHA"},
{0x001F, "TLS_KRB5_WITH_3DES_EDE_CBC_SHA"},
{0x0020, "TLS_KRB5_WITH_RC4_128_SHA"},
{0x0021, "TLS_KRB5_WITH_IDEA_CBC_SHA"},
{0x0022, "TLS_KRB5_WITH_DES_CBC_MD5"},
{0x0023, "TLS_KRB5_WITH_3DES_EDE_CBC_MD5"},
{0x0024, "TLS_KRB5_WITH_RC4_128_MD5"},
{0x0025, "TLS_KRB5_WITH_IDEA_CBC_MD5"},
{0x0026, "TLS_KRB5_EXPORT_WITH_DES_CBC_40_SHA"},
{0x0027, "TLS_KRB5_EXPORT_WITH_RC2_CBC_40_SHA"},
{0x0028, "TLS_KRB5_EXPORT_WITH_RC4_40_SHA"},
{0x0029, "TLS_KRB5_EXPORT_WITH_DES_CBC_40_MD5"},
{0x002A, "TLS_KRB5_EXPORT_WITH_RC2_CBC_40_MD5"},
{0x002B, "TLS_KRB5_EXPORT_WITH_RC4_40_MD5"},
{0x002F, "TLS_RSA_WITH_AES_128_CBC_SHA"},
{0x0030, "TLS_DH_DSS_WITH_AES_128_CBC_SHA"},
{0x0031, "TLS_DH_RSA_WITH_AES_128_CBC_SHA"},
{0x0032, "TLS_DHE_DSS_WITH_AES_128_CBC_SHA"},
{0x0033, "TLS_DHE_RSA_WITH_AES_128_CBC_SHA"},
{0x0034, "TLS_DH_anon_WITH_AES_128_CBC_SHA"},
{0x0035, "TLS_RSA_WITH_AES_256_CBC_SHA"},
{0x0036, "TLS_DH_DSS_WITH_AES_256_CBC_SHA"},
{0x0037, "TLS_DH_RSA_WITH_AES_256_CBC_SHA"},
{0x0038, "TLS_DHE_DSS_WITH_AES_256_CBC_SHA"},
{0x0039, "TLS_DHE_RSA_WITH_AES_256_CBC_SHA"},
{0x003A, "TLS_DH_anon_WITH_AES_256_CBC_SHA"},
{0x003B, "TLS_RSA_WITH_NULL_SHA256"},
{0x003C, "TLS_RSA_WITH_AES_128_CBC_SHA256"},
{0x003D, "TLS_RSA_WITH_AES_256_CBC_SHA256"},
{0x003E, "TLS_DH_DSS_WITH_AES_128_CBC_SHA256"},
{0x003F, "TLS_DH_RSA_WITH_AES_128_CBC_SHA256"},
{0x0040, "TLS_DHE_DSS_WITH_AES_128_CBC_SHA256"},
{0x0041, "TLS_RSA_WITH_CAMELLIA_128_CBC_SHA"},
{0x0042, "TLS_DH_DSS_WITH_CAMELLIA_128_CBC_SHA"},
{0x0043, "TLS_DH_RSA_WITH_CAMELLIA_128_CBC_SHA"},
{0x0044, "TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA"},
{0x0045, "TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA"},
{0x0046, "TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA"},
{0x0067, "TLS_DHE_RSA_WITH_AES_128_CBC_SHA256"},
{0x0068, "TLS_DH_DSS_WITH_AES_256_CBC_SHA256"},
{0x0069, "TLS_DH_RSA_WITH_AES_256_CBC_SHA256"},
{0x006A, "TLS_DHE_DSS_WITH_AES_256_CBC_SHA256"},
{0x006B, "TLS_DHE_RSA_WITH_AES_256_CBC_SHA256"},
{0x006C, "TLS_DH_anon_WITH_AES_128_CBC_SHA256"},
{0x006D, "TLS_DH_anon_WITH_AES_256_CBC_SHA256"},
{0x0084, "TLS_RSA_WITH_CAMELLIA_256_CBC_SHA"},
{0x0085, "TLS_DH_DSS_WITH_CAMELLIA_256_CBC_SHA"},
{0x0086, "TLS_DH_RSA_WITH_CAMELLIA_256_CBC_SHA"},
{0x0087, "TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA"},
{0x0088, "TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA"},
{0x0089, "TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA"},
{0x008A, "TLS_PSK_WITH_RC4_128_SHA"},
{0x008B, "TLS_PSK_WITH_3DES_EDE_CBC_SHA"},
{0x008C, "TLS_PSK_WITH_AES_128_CBC_SHA"},
{0x008D, "TLS_PSK_WITH_AES_256_CBC_SHA"},
{0x008E, "TLS_DHE_PSK_WITH_RC4_128_SHA"},
{0x008F, "TLS_DHE_PSK_WITH_3DES_EDE_CBC_SHA"},
{0x0090, "TLS_DHE_PSK_WITH_AES_128_CBC_SHA"},
{0x0091, "TLS_DHE_PSK_WITH_AES_256_CBC_SHA"},
{0x0092, "TLS_RSA_PSK_WITH_RC4_128_SHA"},
{0x0093, "TLS_RSA_PSK_WITH_3DES_EDE_CBC_SHA"},
{0x0094, "TLS_RSA_PSK_WITH_AES_128_CBC_SHA"},
{0x0095, "TLS_RSA_PSK_WITH_AES_256_CBC_SHA"},
{0x0096, "TLS_RSA_WITH_SEED_CBC_SHA"},
{0x0097, "TLS_DH_DSS_WITH_SEED_CBC_SHA"},
{0x0098, "TLS_DH_RSA_WITH_SEED_CBC_SHA"},
{0x0099, "TLS_DHE_DSS_WITH_SEED_CBC_SHA"},
{0x009A, "TLS_DHE_RSA_WITH_SEED_CBC_SHA"},
{0x009B, "TLS_DH_anon_WITH_SEED_CBC_SHA"},
{0x009C, "TLS_RSA_WITH_AES_128_GCM_SHA256"},
{0x009D, "TLS_RSA_WITH_AES_256_GCM_SHA384"},
{0x009E, "TLS_DHE_RSA_WITH_AES_128_GCM_SHA256"},
{0x009F, "TLS_DHE_RSA_WITH_AES_256_GCM_SHA384"},
{0x00A0, "TLS_DH_RSA_WITH_AES_128_GCM_SHA256"},
{0x00A1, "TLS_DH_RSA_WITH_AES_256_GCM_SHA384"},
{0x00A2, "TLS_DHE_DSS_WITH_AES_128_GCM_SHA256"},
{0x00A3, "TLS_DHE_DSS_WITH_AES_256_GCM_SHA384"},
{0x00A4, "TLS_DH_DSS_WITH_AES_128_GCM_SHA256"},
{0x00A5, "TLS_DH_DSS_WITH_AES_256_GCM_SHA384"},
{0x00A6, "TLS_DH_anon_WITH_AES_128_GCM_SHA256"},
{0x00A7, "TLS_DH_anon_WITH_AES_256_GCM_SHA384"},
{0x00A8, "TLS_PSK_WITH_AES_128_GCM_SHA256"},
{0x00A9, "TLS_PSK_WITH_AES_256_GCM_SHA384"},
{0x00AA, "TLS_DHE_PSK_WITH_AES_128_GCM_SHA256"},
{0x00AB, "TLS_DHE_PSK_WITH_AES_256_GCM_SHA384"},
{0x00AC, "TLS_RSA_PSK_WITH_AES_128_GCM_SHA256"},
{0x00AD, "TLS_RSA_PSK_WITH_AES_256_GCM_SHA384"},
{0x00AE, "TLS_PSK_WITH_AES_128_CBC_SHA256"},
{0x00AF, "TLS_PSK_WITH_AES_256_CBC_SHA384"},
{0x00B0, "TLS_PSK_WITH_NULL_SHA256"},
{0x00B1, "TLS_PSK_WITH_NULL_SHA384"},
{0x00B2, "TLS_DHE_PSK_WITH_AES_128_CBC_SHA256"},
{0x00B3, "TLS_DHE_PSK_WITH_AES_256_CBC_SHA384"},
{0x00B4, "TLS_DHE_PSK_WITH_NULL_SHA256"},
{0x00B5, "TLS_DHE_PSK_WITH_NULL_SHA384"},
{0x00B6, "TLS_RSA_PSK_WITH_AES_128_CBC_SHA256"},
{0x00B7, "TLS_RSA_PSK_WITH_AES_256_CBC_SHA384"},
{0x00B8, "TLS_RSA_PSK_WITH_NULL_SHA256"},
{0x00B9, "TLS_RSA_PSK_WITH_NULL_SHA384"},
{0x00BA, "TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256"},
{0x00BB, "TLS_DH_DSS_WITH_CAMELLIA_128_CBC_SHA256"},
{0x00BC, "TLS_DH_RSA_WITH_CAMELLIA_128_CBC_SHA256"},
{0x00BD, "TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA256"},
{0x00BE, "TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256"},
{0x00BF, "TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA256"},
{0x00C0, "TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256"},
{0x00C1, "TLS_DH_DSS_WITH_CAMELLIA_256_CBC_SHA256"},
{0x00C2, "TLS_DH_RSA_WITH_CAMELLIA_256_CBC_SHA256"},
{0x00C3, "TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA256"},
{0x00C4, "TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256"},
{0x00C5, "TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA256"},
{0x00FF, "TLS_EMPTY_RENEGOTIATION_INFO_SCSV"},
{0xC001, "TLS_ECDH_ECDSA_WITH_NULL_SHA"},
{0xC002, "TLS_ECDH_ECDSA_WITH_RC4_128_SHA"},
{0xC003, "TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA"},
{0xC004, "TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA"},
{0xC005, "TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA"},
{0xC006, "TLS_ECDHE_ECDSA_WITH_NULL_SHA"},
{0xC007, "TLS_ECDHE_ECDSA_WITH_RC4_128_SHA"},
{0xC008, "TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA"},
{0xC009, "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA"},
{0xC00A, "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA"},
{0xC00B, "TLS_ECDH_RSA_WITH_NULL_SHA"},
{0xC00C, "TLS_ECDH_RSA_WITH_RC4_128_SHA"},
{0xC00D, "TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA"},
{0xC00E, "TLS_ECDH_RSA_WITH_AES_128_CBC_SHA"},
{0xC00F, "TLS_ECDH_RSA_WITH_AES_256_CBC_SHA"},
{0xC010, "TLS_ECDHE_RSA_WITH_NULL_SHA"},
{0xC011, "TLS_ECDHE_RSA_WITH_RC4_128_SHA"},
{0xC012, "TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA"},
{0xC013, "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA"},
{0xC014, "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA"},
{0xC015, "TLS_ECDH_anon_WITH_NULL_SHA"},
{0xC016, "TLS_ECDH_anon_WITH_RC4_128_SHA"},
{0xC017, "TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA"},
{0xC018, "TLS_ECDH_anon_WITH_AES_128_CBC_SHA"},
{0xC019, "TLS_ECDH_anon_WITH_AES_256_CBC_SHA"},
{0xC01A, "TLS_SRP_SHA_WITH_3DES_EDE_CBC_SHA"},
{0xC01B, "TLS_SRP_SHA_RSA_WITH_3DES_EDE_CBC_SHA"},
{0xC01C, "TLS_SRP_SHA_DSS_WITH_3DES_EDE_CBC_SHA"},
{0xC01D, "TLS_SRP_SHA_WITH_AES_128_CBC_SHA"},
{0xC01E, "TLS_SRP_SHA_RSA_WITH_AES_128_CBC_SHA"},
{0xC01F, "TLS_SRP_SHA_DSS_WITH_AES_128_CBC_SHA"},
{0xC020, "TLS_SRP_SHA_WITH_AES_256_CBC_SHA"},
{0xC021, "TLS_SRP_SHA_RSA_WITH_AES_256_CBC_SHA"},
{0xC022, "TLS_SRP_SHA_DSS_WITH_AES_256_CBC_SHA"},
{0xC023, "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256"},
{0xC024, "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384"},
{0xC025, "TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256"},
{0xC026, "TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384"},
{0xC027, "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256"},
{0xC028, "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384"},
{0xC029, "TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256"},
{0xC02A, "TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384"},
{0xC02B, "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256"},
{0xC02C, "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384"},
{0xC02D, "TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256"},
{0xC02E, "TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384"},
{0xC02F, "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256"},
{0xC030, "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384"},
{0xC031, "TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256"},
{0xC032, "TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384"},
{0xFEFE, "SSL_RSA_FIPS_WITH_DES_CBC_SHA"},
{0xFEFF, "SSL_RSA_FIPS_WITH_3DES_EDE_CBC_SHA"},
};
/* Compression methods */
static ssl_trace_tbl ssl_comp_tbl[] = {
{0x0000, "No Compression"},
{0x0001, "Zlib Compression"}
};
/* Extensions */
static ssl_trace_tbl ssl_exts_tbl[] = {
{TLSEXT_TYPE_server_name, "server_name"},
{TLSEXT_TYPE_max_fragment_length, "max_fragment_length"},
{TLSEXT_TYPE_client_certificate_url, "client_certificate_url"},
{TLSEXT_TYPE_trusted_ca_keys, "trusted_ca_keys"},
{TLSEXT_TYPE_truncated_hmac, "truncated_hmac"},
{TLSEXT_TYPE_status_request, "status_request"},
{TLSEXT_TYPE_user_mapping, "user_mapping"},
{TLSEXT_TYPE_client_authz, "client_authz"},
{TLSEXT_TYPE_server_authz, "server_authz"},
{TLSEXT_TYPE_cert_type, "cert_type"},
{TLSEXT_TYPE_elliptic_curves, "elliptic_curves"},
{TLSEXT_TYPE_ec_point_formats, "ec_point_formats"},
{TLSEXT_TYPE_srp, "srp"},
{TLSEXT_TYPE_signature_algorithms, "signature_algorithms"},
{TLSEXT_TYPE_use_srtp, "use_srtp"},
{TLSEXT_TYPE_heartbeat, "heartbeat"},
{TLSEXT_TYPE_session_ticket, "session_ticket"},
# ifdef TLSEXT_TYPE_opaque_prf_input
{TLSEXT_TYPE_opaque_prf_input, "opaque_prf_input"},
# endif
{TLSEXT_TYPE_renegotiate, "renegotiate"},
{TLSEXT_TYPE_next_proto_neg, "next_proto_neg"},
{TLSEXT_TYPE_padding, "padding"}
};
static ssl_trace_tbl ssl_curve_tbl[] = {
{1, "sect163k1 (K-163)"},
{2, "sect163r1"},
{3, "sect163r2 (B-163)"},
{4, "sect193r1"},
{5, "sect193r2"},
{6, "sect233k1 (K-233)"},
{7, "sect233r1 (B-233)"},
{8, "sect239k1"},
{9, "sect283k1 (K-283)"},
{10, "sect283r1 (B-283)"},
{11, "sect409k1 (K-409)"},
{12, "sect409r1 (B-409)"},
{13, "sect571k1 (K-571)"},
{14, "sect571r1 (B-571)"},
{15, "secp160k1"},
{16, "secp160r1"},
{17, "secp160r2"},
{18, "secp192k1"},
{19, "secp192r1 (P-192)"},
{20, "secp224k1"},
{21, "secp224r1 (P-224)"},
{22, "secp256k1"},
{23, "secp256r1 (P-256)"},
{24, "secp384r1 (P-384)"},
{25, "secp521r1 (P-521)"},
{26, "brainpoolP256r1"},
{27, "brainpoolP384r1"},
{28, "brainpoolP512r1"},
{0xFF01, "arbitrary_explicit_prime_curves"},
{0xFF02, "arbitrary_explicit_char2_curves"}
};
static ssl_trace_tbl ssl_point_tbl[] = {
{0, "uncompressed"},
{1, "ansiX962_compressed_prime"},
{2, "ansiX962_compressed_char2"}
};
static ssl_trace_tbl ssl_md_tbl[] = {
{0, "none"},
{1, "md5"},
{2, "sha1"},
{3, "sha224"},
{4, "sha256"},
{5, "sha384"},
{6, "sha512"}
};
static ssl_trace_tbl ssl_sig_tbl[] = {
{0, "anonymous"},
{1, "rsa"},
{2, "dsa"},
{3, "ecdsa"}
};
static ssl_trace_tbl ssl_hb_tbl[] = {
{1, "peer_allowed_to_send"},
{2, "peer_not_allowed_to_send"}
};
static ssl_trace_tbl ssl_hb_type_tbl[] = {
{1, "heartbeat_request"},
{2, "heartbeat_response"}
};
static ssl_trace_tbl ssl_ctype_tbl[] = {
{1, "rsa_sign"},
{2, "dss_sign"},
{3, "rsa_fixed_dh"},
{4, "dss_fixed_dh"},
{5, "rsa_ephemeral_dh"},
{6, "dss_ephemeral_dh"},
{20, "fortezza_dms"},
{64, "ecdsa_sign"},
{65, "rsa_fixed_ecdh"},
{66, "ecdsa_fixed_ecdh"}
};
static ssl_trace_tbl ssl_crypto_tbl[] = {
{TLS1_RT_CRYPTO_PREMASTER, "Premaster Secret"},
{TLS1_RT_CRYPTO_CLIENT_RANDOM, "Client Random"},
{TLS1_RT_CRYPTO_SERVER_RANDOM, "Server Random"},
{TLS1_RT_CRYPTO_MASTER, "Master Secret"},
{TLS1_RT_CRYPTO_MAC | TLS1_RT_CRYPTO_WRITE, "Write Mac Secret"},
{TLS1_RT_CRYPTO_MAC | TLS1_RT_CRYPTO_READ, "Read Mac Secret"},
{TLS1_RT_CRYPTO_KEY | TLS1_RT_CRYPTO_WRITE, "Write Key"},
{TLS1_RT_CRYPTO_KEY | TLS1_RT_CRYPTO_READ, "Read Key"},
{TLS1_RT_CRYPTO_IV | TLS1_RT_CRYPTO_WRITE, "Write IV"},
{TLS1_RT_CRYPTO_IV | TLS1_RT_CRYPTO_READ, "Read IV"},
{TLS1_RT_CRYPTO_FIXED_IV | TLS1_RT_CRYPTO_WRITE, "Write IV (fixed part)"},
{TLS1_RT_CRYPTO_FIXED_IV | TLS1_RT_CRYPTO_READ, "Read IV (fixed part)"}
};
static void ssl_print_hex(BIO *bio, int indent, const char *name,
const unsigned char *msg, size_t msglen)
{
size_t i;
BIO_indent(bio, indent, 80);
BIO_printf(bio, "%s (len=%d): ", name, (int)msglen);
for (i = 0; i < msglen; i++)
BIO_printf(bio, "%02X", msg[i]);
BIO_puts(bio, "\n");
}
static int ssl_print_hexbuf(BIO *bio, int indent,
const char *name, size_t nlen,
const unsigned char **pmsg, size_t *pmsglen)
{
size_t blen;
const unsigned char *p = *pmsg;
if (*pmsglen < nlen)
return 0;
blen = p[0];
if (nlen > 1)
blen = (blen << 8) | p[1];
if (*pmsglen < nlen + blen)
return 0;
p += nlen;
ssl_print_hex(bio, indent, name, p, blen);
*pmsg += blen + nlen;
*pmsglen -= blen + nlen;
return 1;
}
static int ssl_print_version(BIO *bio, int indent, const char *name,
const unsigned char **pmsg, size_t *pmsglen)
{
int vers;
if (*pmsglen < 2)
return 0;
vers = ((*pmsg)[0] << 8) | (*pmsg)[1];
BIO_indent(bio, indent, 80);
BIO_printf(bio, "%s=0x%x (%s)\n",
name, vers, ssl_trace_str(vers, ssl_version_tbl));
*pmsg += 2;
*pmsglen -= 2;
return 1;
}
static int ssl_print_random(BIO *bio, int indent,
const unsigned char **pmsg, size_t *pmsglen)
{
unsigned int tm;
const unsigned char *p = *pmsg;
if (*pmsglen < 32)
return 0;
tm = (p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3];
p += 4;
BIO_indent(bio, indent, 80);
BIO_puts(bio, "Random:\n");
BIO_indent(bio, indent + 2, 80);
BIO_printf(bio, "gmt_unix_time=0x%08X\n", tm);
ssl_print_hex(bio, indent + 2, "random_bytes", p, 28);
*pmsg += 32;
*pmsglen -= 32;
return 1;
}
static int ssl_print_signature(BIO *bio, int indent, SSL *s,
const unsigned char **pmsg, size_t *pmsglen)
{
if (*pmsglen < 2)
return 0;
if (SSL_USE_SIGALGS(s)) {
const unsigned char *p = *pmsg;
BIO_indent(bio, indent, 80);
BIO_printf(bio, "Signature Algorithm %s+%s (%d+%d)\n",
ssl_trace_str(p[0], ssl_md_tbl),
ssl_trace_str(p[1], ssl_sig_tbl), p[0], p[1]);
*pmsg += 2;
*pmsglen -= 2;
}
return ssl_print_hexbuf(bio, indent, "Signature", 2, pmsg, pmsglen);
}
static int ssl_print_extension(BIO *bio, int indent, int server, int extype,
const unsigned char *ext, size_t extlen)
{
size_t xlen;
BIO_indent(bio, indent, 80);
BIO_printf(bio, "extension_type=%s(%d), length=%d\n",
ssl_trace_str(extype, ssl_exts_tbl), extype, (int)extlen);
switch (extype) {
case TLSEXT_TYPE_ec_point_formats:
if (extlen < 1)
return 0;
xlen = ext[0];
if (extlen != xlen + 1)
return 0;
return ssl_trace_list(bio, indent + 2,
ext + 1, xlen, 1, ssl_point_tbl);
case TLSEXT_TYPE_elliptic_curves:
if (extlen < 2)
return 0;
xlen = (ext[0] << 8) | ext[1];
if (extlen != xlen + 2)
return 0;
return ssl_trace_list(bio, indent + 2,
ext + 2, xlen, 2, ssl_curve_tbl);
case TLSEXT_TYPE_signature_algorithms:
if (extlen < 2)
return 0;
xlen = (ext[0] << 8) | ext[1];
if (extlen != xlen + 2)
return 0;
if (xlen & 1)
return 0;
ext += 2;
while (xlen > 0) {
BIO_indent(bio, indent + 2, 80);
BIO_printf(bio, "%s+%s (%d+%d)\n",
ssl_trace_str(ext[0], ssl_md_tbl),
ssl_trace_str(ext[1], ssl_sig_tbl), ext[0], ext[1]);
xlen -= 2;
ext += 2;
}
break;
case TLSEXT_TYPE_renegotiate:
if (extlen < 1)
return 0;
xlen = ext[0];
if (xlen + 1 != extlen)
return 0;
ext++;
if (xlen) {
if (server) {
if (xlen & 1)
return 0;
xlen >>= 1;
}
ssl_print_hex(bio, indent + 4, "client_verify_data", ext, xlen);
if (server) {
ext += xlen;
ssl_print_hex(bio, indent + 4,
"server_verify_data", ext, xlen);
}
} else {
BIO_indent(bio, indent + 4, 80);
BIO_puts(bio, "<EMPTY>\n");
}
break;
case TLSEXT_TYPE_heartbeat:
if (extlen != 1)
return 0;
BIO_indent(bio, indent + 2, 80);
BIO_printf(bio, "HeartbeatMode: %s\n",
ssl_trace_str(ext[0], ssl_hb_tbl));
break;
case TLSEXT_TYPE_session_ticket:
if (extlen != 0)
ssl_print_hex(bio, indent + 4, "ticket", ext, extlen);
break;
default:
BIO_dump_indent(bio, (char *)ext, extlen, indent + 2);
}
return 1;
}
static int ssl_print_extensions(BIO *bio, int indent, int server,
const unsigned char *msg, size_t msglen)
{
size_t extslen;
BIO_indent(bio, indent, 80);
if (msglen == 0) {
BIO_puts(bio, "No Extensions\n");
return 1;
}
extslen = (msg[0] << 8) | msg[1];
if (extslen != msglen - 2)
return 0;
msg += 2;
msglen = extslen;
BIO_printf(bio, "extensions, length = %d\n", (int)msglen);
while (msglen > 0) {
int extype;
size_t extlen;
if (msglen < 4)
return 0;
extype = (msg[0] << 8) | msg[1];
extlen = (msg[2] << 8) | msg[3];
if (msglen < extlen + 4)
return 0;
msg += 4;
if (!ssl_print_extension(bio, indent + 2, server,
extype, msg, extlen))
return 0;
msg += extlen;
msglen -= extlen + 4;
}
return 1;
}
static int ssl_print_client_hello(BIO *bio, SSL *ssl, int indent,
const unsigned char *msg, size_t msglen)
{
size_t len;
unsigned int cs;
if (!ssl_print_version(bio, indent, "client_version", &msg, &msglen))
return 0;
if (!ssl_print_random(bio, indent, &msg, &msglen))
return 0;
if (!ssl_print_hexbuf(bio, indent, "session_id", 1, &msg, &msglen))
return 0;
if (SSL_IS_DTLS(ssl)) {
if (!ssl_print_hexbuf(bio, indent, "cookie", 1, &msg, &msglen))
return 0;
}
if (msglen < 2)
return 0;
len = (msg[0] << 8) | msg[1];
msg += 2;
msglen -= 2;
BIO_indent(bio, indent, 80);
BIO_printf(bio, "cipher_suites (len=%d)\n", (int)len);
if (msglen < len || len & 1)
return 0;
while (len > 0) {
cs = (msg[0] << 8) | msg[1];
BIO_indent(bio, indent + 2, 80);
BIO_printf(bio, "{0x%02X, 0x%02X} %s\n",
msg[0], msg[1], ssl_trace_str(cs, ssl_ciphers_tbl));
msg += 2;
msglen -= 2;
len -= 2;
}
if (msglen < 1)
return 0;
len = msg[0];
msg++;
msglen--;
if (msglen < len)
return 0;
BIO_indent(bio, indent, 80);
BIO_printf(bio, "compression_methods (len=%d)\n", (int)len);
while (len > 0) {
BIO_indent(bio, indent + 2, 80);
BIO_printf(bio, "%s (0x%02X)\n",
ssl_trace_str(msg[0], ssl_comp_tbl), msg[0]);
msg++;
msglen--;
len--;
}
if (!ssl_print_extensions(bio, indent, 0, msg, msglen))
return 0;
return 1;
}
static int dtls_print_hello_vfyrequest(BIO *bio, int indent,
const unsigned char *msg,
size_t msglen)
{
if (!ssl_print_version(bio, indent, "server_version", &msg, &msglen))
return 0;
if (!ssl_print_hexbuf(bio, indent, "cookie", 1, &msg, &msglen))
return 0;
return 1;
}
static int ssl_print_server_hello(BIO *bio, int indent,
const unsigned char *msg, size_t msglen)
{
unsigned int cs;
if (!ssl_print_version(bio, indent, "server_version", &msg, &msglen))
return 0;
if (!ssl_print_random(bio, indent, &msg, &msglen))
return 0;
if (!ssl_print_hexbuf(bio, indent, "session_id", 1, &msg, &msglen))
return 0;
if (msglen < 2)
return 0;
cs = (msg[0] << 8) | msg[1];
BIO_indent(bio, indent, 80);
BIO_printf(bio, "cipher_suite {0x%02X, 0x%02X} %s\n",
msg[0], msg[1], ssl_trace_str(cs, ssl_ciphers_tbl));
msg += 2;
msglen -= 2;
if (msglen < 1)
return 0;
BIO_indent(bio, indent, 80);
BIO_printf(bio, "compression_method: %s (0x%02X)\n",
ssl_trace_str(msg[0], ssl_comp_tbl), msg[0]);
msg++;
msglen--;
if (!ssl_print_extensions(bio, indent, 1, msg, msglen))
return 0;
return 1;
}
static int ssl_get_keyex(const char **pname, SSL *ssl)
{
unsigned long alg_k = ssl->s3->tmp.new_cipher->algorithm_mkey;
if (alg_k & SSL_kRSA) {
*pname = "rsa";
return SSL_kRSA;
}
if (alg_k & SSL_kDHr) {
*pname = "dh_rsa";
return SSL_kDHr;
}
if (alg_k & SSL_kDHd) {
*pname = "dh_dss";
return SSL_kDHd;
}
if (alg_k & SSL_kKRB5) {
*pname = "krb5";
return SSL_kKRB5;
}
if (alg_k & SSL_kEDH) {
*pname = "edh";
return SSL_kEDH;
}
if (alg_k & SSL_kEECDH) {
*pname = "EECDH";
return SSL_kEECDH;
}
if (alg_k & SSL_kECDHr) {
*pname = "ECDH RSA";
return SSL_kECDHr;
}
if (alg_k & SSL_kECDHe) {
*pname = "ECDH ECDSA";
return SSL_kECDHe;
}
if (alg_k & SSL_kPSK) {
*pname = "PSK";
return SSL_kPSK;
}
if (alg_k & SSL_kSRP) {
*pname = "SRP";
return SSL_kSRP;
}
if (alg_k & SSL_kGOST) {
*pname = "GOST";
return SSL_kGOST;
}
*pname = "UNKNOWN";
return 0;
}
static int ssl_print_client_keyex(BIO *bio, int indent, SSL *ssl,
const unsigned char *msg, size_t msglen)
{
const char *algname;
int id;
id = ssl_get_keyex(&algname, ssl);
BIO_indent(bio, indent, 80);
BIO_printf(bio, "KeyExchangeAlgorithm=%s\n", algname);
switch (id) {
case SSL_kRSA:
if (TLS1_get_version(ssl) == SSL3_VERSION) {
ssl_print_hex(bio, indent + 2,
"EncyptedPreMasterSecret", msg, msglen);
} else {
if (!ssl_print_hexbuf(bio, indent + 2,
"EncyptedPreMasterSecret", 2,
&msg, &msglen))
return 0;
}
break;
/* Implicit parameters only allowed for static DH */
case SSL_kDHd:
case SSL_kDHr:
if (msglen == 0) {
BIO_indent(bio, indent + 2, 80);
BIO_puts(bio, "implicit\n");
break;
}
case SSL_kEDH:
if (!ssl_print_hexbuf(bio, indent + 2, "dh_Yc", 2, &msg, &msglen))
return 0;
break;
case SSL_kECDHr:
case SSL_kECDHe:
if (msglen == 0) {
BIO_indent(bio, indent + 2, 80);
BIO_puts(bio, "implicit\n");
break;
}
case SSL_kEECDH:
if (!ssl_print_hexbuf(bio, indent + 2, "ecdh_Yc", 1, &msg, &msglen))
return 0;
break;
}
return 1;
}
static int ssl_print_server_keyex(BIO *bio, int indent, SSL *ssl,
const unsigned char *msg, size_t msglen)
{
const char *algname;
int id;
id = ssl_get_keyex(&algname, ssl);
BIO_indent(bio, indent, 80);
BIO_printf(bio, "KeyExchangeAlgorithm=%s\n", algname);
switch (id) {
/* Should never happen */
case SSL_kDHd:
case SSL_kDHr:
case SSL_kECDHr:
case SSL_kECDHe:
BIO_indent(bio, indent + 2, 80);
BIO_printf(bio, "Unexpected Message\n");
break;
case SSL_kRSA:
if (!ssl_print_hexbuf(bio, indent + 2, "rsa_modulus", 2,
&msg, &msglen))
return 0;
if (!ssl_print_hexbuf(bio, indent + 2, "rsa_exponent", 2,
&msg, &msglen))
return 0;
break;
case SSL_kEDH:
if (!ssl_print_hexbuf(bio, indent + 2, "dh_p", 2, &msg, &msglen))
return 0;
if (!ssl_print_hexbuf(bio, indent + 2, "dh_g", 2, &msg, &msglen))
return 0;
if (!ssl_print_hexbuf(bio, indent + 2, "dh_Ys", 2, &msg, &msglen))
return 0;
break;
case SSL_kEECDH:
if (msglen < 1)
return 0;
BIO_indent(bio, indent + 2, 80);
if (msg[0] == EXPLICIT_PRIME_CURVE_TYPE)
BIO_puts(bio, "explicit_prime\n");
else if (msg[0] == EXPLICIT_CHAR2_CURVE_TYPE)
BIO_puts(bio, "explicit_char2\n");
else if (msg[0] == NAMED_CURVE_TYPE) {
int curve;
if (msglen < 3)
return 0;
curve = (msg[1] << 8) | msg[2];
BIO_printf(bio, "named_curve: %s (%d)\n",
ssl_trace_str(curve, ssl_curve_tbl), curve);
msg += 3;
msglen -= 3;
if (!ssl_print_hexbuf(bio, indent + 2, "point", 1, &msg, &msglen))
return 0;
}
break;
}
return ssl_print_signature(bio, indent, ssl, &msg, &msglen);
}
static int ssl_print_certificate(BIO *bio, int indent,
const unsigned char **pmsg, size_t *pmsglen)
{
size_t msglen = *pmsglen;
size_t clen;
X509 *x;
const unsigned char *p = *pmsg, *q;
if (msglen < 3)
return 0;
clen = (p[0] << 16) | (p[1] << 8) | p[2];
if (msglen < clen + 3)
return 0;
q = p + 3;
BIO_indent(bio, indent, 80);
BIO_printf(bio, "ASN.1Cert, length=%d", (int)clen);
x = d2i_X509(NULL, &q, clen);
if (!x)
BIO_puts(bio, "<UNPARSEABLE CERTIFICATE>\n");
else {
BIO_puts(bio, "\n------details-----\n");
X509_print_ex(bio, x, XN_FLAG_ONELINE, 0);
PEM_write_bio_X509(bio, x);
/* Print certificate stuff */
BIO_puts(bio, "------------------\n");
X509_free(x);
}
if (q != p + 3 + clen) {
BIO_puts(bio, "<TRAILING GARBAGE AFTER CERTIFICATE>\n");
}
*pmsg += clen + 3;
*pmsglen -= clen + 3;
return 1;
}
static int ssl_print_certificates(BIO *bio, int indent,
const unsigned char *msg, size_t msglen)
{
size_t clen;
if (msglen < 3)
return 0;
clen = (msg[0] << 16) | (msg[1] << 8) | msg[2];
if (msglen != clen + 3)
return 0;
msg += 3;
BIO_indent(bio, indent, 80);
BIO_printf(bio, "certificate_list, length=%d\n", (int)clen);
while (clen > 0) {
if (!ssl_print_certificate(bio, indent + 2, &msg, &clen))
return 0;
}
return 1;
}
static int ssl_print_cert_request(BIO *bio, int indent, SSL *s,
const unsigned char *msg, size_t msglen)
{
size_t xlen;
if (msglen < 1)
return 0;
xlen = msg[0];
if (msglen < xlen + 1)
return 0;
msg++;
BIO_indent(bio, indent, 80);
BIO_printf(bio, "certificate_types (len=%d)\n", (int)xlen);
if (!ssl_trace_list(bio, indent + 2, msg, xlen, 1, ssl_ctype_tbl))
return 0;
msg += xlen;
msglen -= xlen + 1;
if (!SSL_USE_SIGALGS(s))
goto skip_sig;
if (msglen < 2)
return 0;
xlen = (msg[0] << 8) | msg[1];
if (msglen < xlen + 2 || (xlen & 1))
return 0;
msg += 2;
BIO_indent(bio, indent, 80);
BIO_printf(bio, "signature_algorithms (len=%d)\n", (int)xlen);
while (xlen > 0) {
BIO_indent(bio, indent + 2, 80);
BIO_printf(bio, "%s+%s (%d+%d)\n",
ssl_trace_str(msg[0], ssl_md_tbl),
ssl_trace_str(msg[1], ssl_sig_tbl), msg[0], msg[1]);
xlen -= 2;
msg += 2;
}
msg += xlen;
msglen -= xlen + 2;
skip_sig:
xlen = (msg[0] << 8) | msg[1];
BIO_indent(bio, indent, 80);
if (msglen < xlen + 2)
return 0;
msg += 2;
msglen -= 2;
BIO_printf(bio, "certificate_authorities (len=%d)\n", (int)xlen);
while (xlen > 0) {
size_t dlen;
X509_NAME *nm;
const unsigned char *p;
if (xlen < 2)
return 0;
dlen = (msg[0] << 8) | msg[1];
if (xlen < dlen + 2)
return 0;
msg += 2;
BIO_indent(bio, indent + 2, 80);
BIO_printf(bio, "DistinguishedName (len=%d): ", (int)dlen);
p = msg;
nm = d2i_X509_NAME(NULL, &p, dlen);
if (!nm) {
BIO_puts(bio, "<UNPARSEABLE DN>\n");
} else {
X509_NAME_print_ex(bio, nm, 0, XN_FLAG_ONELINE);
BIO_puts(bio, "\n");
X509_NAME_free(nm);
}
xlen -= dlen + 2;
msg += dlen;
}
return 1;
}
static int ssl_print_ticket(BIO *bio, int indent,
const unsigned char *msg, size_t msglen)
{
unsigned int tick_life;
if (msglen == 0) {
BIO_indent(bio, indent + 2, 80);
BIO_puts(bio, "No Ticket\n");
return 1;
}
if (msglen < 4)
return 0;
tick_life = (msg[0] << 24) | (msg[1] << 16) | (msg[2] << 8) | msg[3];
msglen -= 4;
msg += 4;
BIO_indent(bio, indent + 2, 80);
BIO_printf(bio, "ticket_lifetime_hint=%u\n", tick_life);
if (!ssl_print_hexbuf(bio, indent + 2, "ticket", 2, &msg, &msglen))
return 0;
if (msglen)
return 0;
return 1;
}
static int ssl_print_handshake(BIO *bio, SSL *ssl,
const unsigned char *msg, size_t msglen,
int indent)
{
size_t hlen;
unsigned char htype;
if (msglen < 4)
return 0;
htype = msg[0];
hlen = (msg[1] << 16) | (msg[2] << 8) | msg[3];
BIO_indent(bio, indent, 80);
BIO_printf(bio, "%s, Length=%d\n",
ssl_trace_str(htype, ssl_handshake_tbl), (int)hlen);
msg += 4;
msglen -= 4;
if (SSL_IS_DTLS(ssl)) {
if (msglen < 8)
return 0;
BIO_indent(bio, indent, 80);
BIO_printf(bio, "message_seq=%d, fragment_offset=%d, "
"fragment_length=%d\n",
(msg[0] << 8) | msg[1],
(msg[2] << 16) | (msg[3] << 8) | msg[4],
(msg[5] << 16) | (msg[6] << 8) | msg[7]);
msg += 8;
msglen -= 8;
}
if (msglen < hlen)
return 0;
switch (htype) {
case SSL3_MT_CLIENT_HELLO:
if (!ssl_print_client_hello(bio, ssl, indent + 2, msg, msglen))
return 0;
break;
case DTLS1_MT_HELLO_VERIFY_REQUEST:
if (!dtls_print_hello_vfyrequest(bio, indent + 2, msg, msglen))
return 0;
break;
case SSL3_MT_SERVER_HELLO:
if (!ssl_print_server_hello(bio, indent + 2, msg, msglen))
return 0;
break;
case SSL3_MT_SERVER_KEY_EXCHANGE:
if (!ssl_print_server_keyex(bio, indent + 2, ssl, msg, msglen))
return 0;
break;
case SSL3_MT_CLIENT_KEY_EXCHANGE:
if (!ssl_print_client_keyex(bio, indent + 2, ssl, msg, msglen))
return 0;
break;
case SSL3_MT_CERTIFICATE:
if (!ssl_print_certificates(bio, indent + 2, msg, msglen))
return 0;
break;
case SSL3_MT_CERTIFICATE_VERIFY:
if (!ssl_print_signature(bio, indent + 2, ssl, &msg, &msglen))
return 0;
break;
case SSL3_MT_CERTIFICATE_REQUEST:
if (!ssl_print_cert_request(bio, indent + 2, ssl, msg, msglen))
return 0;
break;
case SSL3_MT_FINISHED:
ssl_print_hex(bio, indent + 2, "verify_data", msg, msglen);
break;
case SSL3_MT_SERVER_DONE:
if (msglen != 0)
ssl_print_hex(bio, indent + 2, "unexpected value", msg, msglen);
break;
case SSL3_MT_NEWSESSION_TICKET:
if (!ssl_print_ticket(bio, indent + 2, msg, msglen))
return 0;
break;
default:
BIO_indent(bio, indent + 2, 80);
BIO_puts(bio, "Unsupported, hex dump follows:\n");
BIO_dump_indent(bio, (char *)msg, msglen, indent + 4);
}
return 1;
}
static int ssl_print_heartbeat(BIO *bio, int indent,
const unsigned char *msg, size_t msglen)
{
if (msglen < 3)
return 0;
BIO_indent(bio, indent, 80);
BIO_printf(bio, "HeartBeatMessageType: %s\n",
ssl_trace_str(msg[0], ssl_hb_type_tbl));
msg++;
msglen--;
if (!ssl_print_hexbuf(bio, indent, "payload", 2, &msg, &msglen))
return 0;
ssl_print_hex(bio, indent, "padding", msg, msglen);
return 1;
}
const char *SSL_CIPHER_standard_name(const SSL_CIPHER *c)
{
if (c->algorithm_ssl & SSL_SSLV2)
return NULL;
return ssl_trace_str(c->id & 0xFFFF, ssl_ciphers_tbl);
}
void SSL_trace(int write_p, int version, int content_type,
const void *buf, size_t msglen, SSL *ssl, void *arg)
{
const unsigned char *msg = buf;
BIO *bio = arg;
if (write_p == 2) {
BIO_puts(bio, "Session ");
ssl_print_hex(bio, 0,
ssl_trace_str(content_type, ssl_crypto_tbl),
msg, msglen);
return;
}
switch (content_type) {
case SSL3_RT_HEADER:
{
int hvers = msg[1] << 8 | msg[2];
BIO_puts(bio, write_p ? "Sent" : "Received");
BIO_printf(bio, " Record\nHeader:\n Version = %s (0x%x)\n",
ssl_trace_str(hvers, ssl_version_tbl), hvers);
if (SSL_IS_DTLS(ssl)) {
BIO_printf(bio,
" epoch=%d, sequence_number=%04x%04x%04x\n",
(msg[3] << 8 | msg[4]),
(msg[5] << 8 | msg[6]),
(msg[7] << 8 | msg[8]), (msg[9] << 8 | msg[10]));
# if 0
/*
* Just print handshake type so we can see what is going on
* during fragmentation.
*/
BIO_printf(bio, "(%s)\n",
ssl_trace_str(msg[msglen], ssl_handshake_tbl));
# endif
}
BIO_printf(bio, " Content Type = %s (%d)\n Length = %d",
ssl_trace_str(msg[0], ssl_content_tbl), msg[0],
msg[msglen - 2] << 8 | msg[msglen - 1]);
}
break;
case SSL3_RT_HANDSHAKE:
if (!ssl_print_handshake(bio, ssl, msg, msglen, 4))
BIO_printf(bio, "Message length parse error!\n");
break;
case SSL3_RT_CHANGE_CIPHER_SPEC:
if (msglen == 1 && msg[0] == 1)
BIO_puts(bio, " change_cipher_spec (1)\n");
else
ssl_print_hex(bio, 4, "unknown value", msg, msglen);
break;
case SSL3_RT_ALERT:
- if (msglen != 2)
+ if (msglen != 2) {
BIO_puts(bio, " Illegal Alert Length\n");
- else {
+ } else {
BIO_printf(bio, " Level=%s(%d), description=%s(%d)\n",
SSL_alert_type_string_long(msg[0] << 8),
msg[0], SSL_alert_desc_string_long(msg[1]), msg[1]);
}
+ break;
+
case TLS1_RT_HEARTBEAT:
ssl_print_heartbeat(bio, 4, msg, msglen);
break;
}
BIO_puts(bio, "\n");
}
#endif

File Metadata

Mime Type
application/octet-stream
Expires
Thu, Sep 19, 6:11 PM (2 d)
Storage Engine
chunks
Storage Format
Chunks
Storage Handle
YLyh0zCgYCk2
Default Alt Text
(5 MB)

Event Timeline